From 33d0737d1d4a6d8a7f0fa3bf2af2b242b545dc69 Mon Sep 17 00:00:00 2001 From: Tropical <42101043+tropicaaal@users.noreply.github.com> Date: Fri, 13 Mar 2026 17:06:56 -0500 Subject: [PATCH 1/5] chore: format Minecraft.World --- Minecraft.World/AI/Control/BodyControl.cpp | 72 +- Minecraft.World/AI/Control/BodyControl.h | 17 +- Minecraft.World/AI/Control/Control.h | 9 +- Minecraft.World/AI/Control/JumpControl.cpp | 19 +- Minecraft.World/AI/Control/JumpControl.h | 17 +- Minecraft.World/AI/Control/LookControl.cpp | 153 +- Minecraft.World/AI/Control/LookControl.h | 35 +- Minecraft.World/AI/Control/MoveControl.cpp | 102 +- Minecraft.World/AI/Control/MoveControl.h | 37 +- Minecraft.World/AI/Control/Sensing.cpp | 50 +- Minecraft.World/AI/Control/Sensing.h | 15 +- Minecraft.World/AI/Goals/ArrowAttackGoal.cpp | 137 +- Minecraft.World/AI/Goals/ArrowAttackGoal.h | 41 +- Minecraft.World/AI/Goals/AvoidPlayerGoal.cpp | 117 +- Minecraft.World/AI/Goals/AvoidPlayerGoal.h | 32 +- Minecraft.World/AI/Goals/BegGoal.cpp | 73 +- Minecraft.World/AI/Goals/BegGoal.h | 32 +- Minecraft.World/AI/Goals/BreakDoorGoal.cpp | 81 +- Minecraft.World/AI/Goals/BreakDoorGoal.h | 21 +- Minecraft.World/AI/Goals/BreedGoal.cpp | 175 +- Minecraft.World/AI/Goals/BreedGoal.h | 32 +- .../AI/Goals/ControlledByPlayerGoal.cpp | 230 +- .../AI/Goals/ControlledByPlayerGoal.h | 38 +- .../AI/Goals/DefendVillageTargetGoal.cpp | 27 +- .../AI/Goals/DefendVillageTargetGoal.h | 13 +- Minecraft.World/AI/Goals/DoorInteractGoal.cpp | 97 +- Minecraft.World/AI/Goals/DoorInteractGoal.h | 27 +- Minecraft.World/AI/Goals/EatTileGoal.cpp | 94 +- Minecraft.World/AI/Goals/EatTileGoal.h | 36 +- Minecraft.World/AI/Goals/FleeSunGoal.cpp | 68 +- Minecraft.World/AI/Goals/FleeSunGoal.h | 26 +- Minecraft.World/AI/Goals/FloatGoal.cpp | 19 +- Minecraft.World/AI/Goals/FloatGoal.h | 11 +- Minecraft.World/AI/Goals/FollowOwnerGoal.cpp | 123 +- Minecraft.World/AI/Goals/FollowOwnerGoal.h | 41 +- Minecraft.World/AI/Goals/FollowParentGoal.cpp | 79 +- Minecraft.World/AI/Goals/FollowParentGoal.h | 23 +- Minecraft.World/AI/Goals/Goal.cpp | 49 +- Minecraft.World/AI/Goals/Goal.h | 33 +- Minecraft.World/AI/Goals/GoalSelector.cpp | 202 +- Minecraft.World/AI/Goals/GoalSelector.h | 54 +- Minecraft.World/AI/Goals/HurtByTargetGoal.cpp | 59 +- Minecraft.World/AI/Goals/HurtByTargetGoal.h | 15 +- Minecraft.World/AI/Goals/InteractGoal.cpp | 16 +- Minecraft.World/AI/Goals/InteractGoal.h | 9 +- Minecraft.World/AI/Goals/LeapAtTargetGoal.cpp | 51 +- Minecraft.World/AI/Goals/LeapAtTargetGoal.h | 7 +- Minecraft.World/AI/Goals/LookAtPlayerGoal.cpp | 75 +- Minecraft.World/AI/Goals/LookAtPlayerGoal.h | 33 +- .../AI/Goals/LookAtTradingPlayerGoal.cpp | 21 +- .../AI/Goals/LookAtTradingPlayerGoal.h | 9 +- Minecraft.World/AI/Goals/MakeLoveGoal.cpp | 139 +- Minecraft.World/AI/Goals/MakeLoveGoal.h | 36 +- Minecraft.World/AI/Goals/MeleeAttackGoal.cpp | 129 +- Minecraft.World/AI/Goals/MeleeAttackGoal.h | 47 +- Minecraft.World/AI/Goals/MoveIndoorsGoal.cpp | 94 +- Minecraft.World/AI/Goals/MoveIndoorsGoal.h | 19 +- .../AI/Goals/MoveThroughVillageGoal.cpp | 175 +- .../AI/Goals/MoveThroughVillageGoal.h | 33 +- .../AI/Goals/MoveTowardsRestrictionGoal.cpp | 43 +- .../AI/Goals/MoveTowardsRestrictionGoal.h | 17 +- .../AI/Goals/MoveTowardsTargetGoal.cpp | 54 +- .../AI/Goals/MoveTowardsTargetGoal.h | 21 +- .../AI/Goals/NearestAttackableTargetGoal.cpp | 108 +- .../AI/Goals/NearestAttackableTargetGoal.h | 45 +- .../AI/Goals/NonTameRandomTargetGoal.cpp | 16 +- .../AI/Goals/NonTameRandomTargetGoal.h | 11 +- Minecraft.World/AI/Goals/OcelotAttackGoal.cpp | 75 +- Minecraft.World/AI/Goals/OcelotAttackGoal.h | 32 +- .../AI/Goals/OcelotSitOnTileGoal.cpp | 179 +- .../AI/Goals/OcelotSitOnTileGoal.h | 43 +- Minecraft.World/AI/Goals/OfferFlowerGoal.cpp | 48 +- Minecraft.World/AI/Goals/OfferFlowerGoal.h | 23 +- Minecraft.World/AI/Goals/OpenDoorGoal.cpp | 37 +- Minecraft.World/AI/Goals/OpenDoorGoal.h | 17 +- .../AI/Goals/OwnerHurtByTargetGoal.cpp | 28 +- .../AI/Goals/OwnerHurtByTargetGoal.h | 13 +- .../AI/Goals/OwnerHurtTargetGoal.cpp | 28 +- .../AI/Goals/OwnerHurtTargetGoal.h | 13 +- Minecraft.World/AI/Goals/PanicGoal.cpp | 38 +- Minecraft.World/AI/Goals/PanicGoal.h | 17 +- Minecraft.World/AI/Goals/PlayGoal.cpp | 119 +- Minecraft.World/AI/Goals/PlayGoal.h | 25 +- .../AI/Goals/RandomLookAroundGoal.cpp | 44 +- .../AI/Goals/RandomLookAroundGoal.h | 19 +- Minecraft.World/AI/Goals/RandomStrollGoal.cpp | 87 +- Minecraft.World/AI/Goals/RandomStrollGoal.h | 17 +- .../AI/Goals/RestrictOpenDoorGoal.cpp | 61 +- .../AI/Goals/RestrictOpenDoorGoal.h | 19 +- Minecraft.World/AI/Goals/RestrictSunGoal.cpp | 20 +- Minecraft.World/AI/Goals/RestrictSunGoal.h | 13 +- Minecraft.World/AI/Goals/SitGoal.cpp | 47 +- Minecraft.World/AI/Goals/SitGoal.h | 17 +- Minecraft.World/AI/Goals/SwellGoal.cpp | 69 +- Minecraft.World/AI/Goals/SwellGoal.h | 17 +- Minecraft.World/AI/Goals/TakeFlowerGoal.cpp | 107 +- Minecraft.World/AI/Goals/TakeFlowerGoal.h | 23 +- Minecraft.World/AI/Goals/TargetGoal.cpp | 167 +- Minecraft.World/AI/Goals/TargetGoal.h | 46 +- Minecraft.World/AI/Goals/TemptGoal.cpp | 136 +- Minecraft.World/AI/Goals/TemptGoal.h | 35 +- .../AI/Goals/TradeWithPlayerGoal.cpp | 60 +- .../AI/Goals/TradeWithPlayerGoal.h | 13 +- Minecraft.World/AI/Navigation/Node.cpp | 89 +- Minecraft.World/AI/Navigation/Node.h | 51 +- Minecraft.World/AI/Navigation/Path.cpp | 158 +- Minecraft.World/AI/Navigation/Path.h | 45 +- Minecraft.World/AI/Navigation/PathFinder.cpp | 288 +- Minecraft.World/AI/Navigation/PathFinder.h | 56 +- .../AI/Navigation/PathNavigation.cpp | 586 +- .../AI/Navigation/PathNavigation.h | 94 +- Minecraft.World/AI/Navigation/RandomPos.cpp | 134 +- Minecraft.World/AI/Navigation/RandomPos.h | 18 +- Minecraft.World/Blocks/AirTile.cpp | 4 +- Minecraft.World/Blocks/AirTile.h | 7 +- Minecraft.World/Blocks/AnvilTile.cpp | 154 +- Minecraft.World/Blocks/AnvilTile.h | 58 +- Minecraft.World/Blocks/BedTile.cpp | 350 +- Minecraft.World/Blocks/BedTile.h | 56 +- Minecraft.World/Blocks/BookshelfTile.cpp | 24 +- Minecraft.World/Blocks/BookshelfTile.h | 9 +- Minecraft.World/Blocks/BrewingStandTile.cpp | 135 +- Minecraft.World/Blocks/BrewingStandTile.h | 44 +- Minecraft.World/Blocks/ButtonTile.cpp | 372 +- Minecraft.World/Blocks/ButtonTile.h | 68 +- Minecraft.World/Blocks/CactusTile.cpp | 108 +- Minecraft.World/Blocks/CactusTile.h | 47 +- Minecraft.World/Blocks/CakeTile.cpp | 114 +- Minecraft.World/Blocks/CakeTile.h | 56 +- Minecraft.World/Blocks/CarrotTile.cpp | 49 +- Minecraft.World/Blocks/CarrotTile.h | 23 +- Minecraft.World/Blocks/CauldronTile.cpp | 182 +- Minecraft.World/Blocks/CauldronTile.h | 45 +- Minecraft.World/Blocks/ChestTile.cpp | 374 +- Minecraft.World/Blocks/ChestTile.h | 60 +- Minecraft.World/Blocks/ClayTile.cpp | 16 +- Minecraft.World/Blocks/ClayTile.h | 7 +- Minecraft.World/Blocks/ClothTile.cpp | 43 +- Minecraft.World/Blocks/ClothTile.h | 21 +- Minecraft.World/Blocks/CocoaTile.cpp | 252 +- Minecraft.World/Blocks/CocoaTile.h | 61 +- Minecraft.World/Blocks/CoralTile.cpp | 18 +- Minecraft.World/Blocks/CoralTile.h | 10 +- Minecraft.World/Blocks/CropTile.cpp | 236 +- Minecraft.World/Blocks/CropTile.h | 45 +- Minecraft.World/Blocks/DeadBushTile.cpp | 46 +- Minecraft.World/Blocks/DeadBushTile.h | 16 +- Minecraft.World/Blocks/DecorationMaterial.h | 13 +- Minecraft.World/Blocks/DetectorRailTile.cpp | 86 +- Minecraft.World/Blocks/DetectorRailTile.h | 40 +- Minecraft.World/Blocks/DiodeTile.cpp | 452 +- Minecraft.World/Blocks/DiodeTile.h | 57 +- Minecraft.World/Blocks/DirectionalTile.cpp | 15 +- Minecraft.World/Blocks/DirectionalTile.h | 13 +- Minecraft.World/Blocks/DirtTile.cpp | 4 +- Minecraft.World/Blocks/DirtTile.h | 8 +- Minecraft.World/Blocks/DispenserTile.cpp | 1014 ++- Minecraft.World/Blocks/DispenserTile.h | 64 +- Minecraft.World/Blocks/DoorTile.cpp | 522 +- Minecraft.World/Blocks/DoorTile.h | 97 +- Minecraft.World/Blocks/EggTile.cpp | 264 +- Minecraft.World/Blocks/EggTile.h | 39 +- .../Blocks/EnchantmentTableTile.cpp | 87 +- Minecraft.World/Blocks/EnchantmentTableTile.h | 38 +- Minecraft.World/Blocks/EnderChestTile.cpp | 169 +- Minecraft.World/Blocks/EnderChestTile.h | 34 +- Minecraft.World/Blocks/FallingTile.cpp | 380 +- Minecraft.World/Blocks/FallingTile.h | 56 +- Minecraft.World/Blocks/FarmTile.cpp | 141 +- Minecraft.World/Blocks/FarmTile.h | 42 +- Minecraft.World/Blocks/FenceGateTile.cpp | 168 +- Minecraft.World/Blocks/FenceGateTile.h | 34 +- Minecraft.World/Blocks/FenceTile.cpp | 102 +- Minecraft.World/Blocks/FenceTile.h | 33 +- Minecraft.World/Blocks/FireTile.cpp | 644 +- Minecraft.World/Blocks/FireTile.h | 74 +- Minecraft.World/Blocks/FlowerPotTile.cpp | 300 +- Minecraft.World/Blocks/FlowerPotTile.h | 60 +- Minecraft.World/Blocks/FurnaceTile.cpp | 304 +- Minecraft.World/Blocks/FurnaceTile.h | 50 +- Minecraft.World/Blocks/GasMaterial.h | 11 +- Minecraft.World/Blocks/GlassTile.cpp | 30 +- Minecraft.World/Blocks/GlassTile.h | 17 +- Minecraft.World/Blocks/GrassTile.cpp | 176 +- Minecraft.World/Blocks/GrassTile.h | 46 +- Minecraft.World/Blocks/GravelTile.cpp | 7 +- Minecraft.World/Blocks/GravelTile.h | 7 +- Minecraft.World/Blocks/HalfSlabTile.cpp | 190 +- Minecraft.World/Blocks/HalfSlabTile.h | 46 +- .../Blocks/HalfTransparentTile.cpp | 28 +- Minecraft.World/Blocks/HalfTransparentTile.h | 20 +- Minecraft.World/Blocks/HeavyTile.cpp | 87 +- Minecraft.World/Blocks/HeavyTile.h | 26 +- Minecraft.World/Blocks/HellSandTile.cpp | 16 +- Minecraft.World/Blocks/HellSandTile.h | 10 +- Minecraft.World/Blocks/HellStoneTile.cpp | 4 +- Minecraft.World/Blocks/HellStoneTile.h | 5 +- Minecraft.World/Blocks/HugeMushroomTile.cpp | 52 +- Minecraft.World/Blocks/HugeMushroomTile.h | 35 +- Minecraft.World/Blocks/IceTile.cpp | 114 +- Minecraft.World/Blocks/IceTile.h | 24 +- Minecraft.World/Blocks/LadderTile.cpp | 103 +- Minecraft.World/Blocks/LadderTile.h | 30 +- Minecraft.World/Blocks/LeafTile.cpp | 394 +- Minecraft.World/Blocks/LeafTile.h | 87 +- Minecraft.World/Blocks/LeverTile.cpp | 326 +- Minecraft.World/Blocks/LeverTile.h | 48 +- Minecraft.World/Blocks/LightGemTile.cpp | 22 +- Minecraft.World/Blocks/LightGemTile.h | 11 +- Minecraft.World/Blocks/LiquidMaterial.h | 14 +- Minecraft.World/Blocks/LiquidTile.cpp | 392 +- Minecraft.World/Blocks/LiquidTile.h | 101 +- Minecraft.World/Blocks/LiquidTileDynamic.cpp | 309 +- Minecraft.World/Blocks/LiquidTileDynamic.h | 76 +- Minecraft.World/Blocks/LiquidTileStatic.cpp | 77 +- Minecraft.World/Blocks/LiquidTileStatic.h | 22 +- Minecraft.World/Blocks/LockedChestTile.cpp | 21 +- Minecraft.World/Blocks/LockedChestTile.h | 14 +- Minecraft.World/Blocks/Material.cpp | 281 +- Minecraft.World/Blocks/Material.h | 127 +- Minecraft.World/Blocks/MaterialColor.cpp | 80 +- Minecraft.World/Blocks/MaterialColor.h | 39 +- Minecraft.World/Blocks/MelonTile.cpp | 45 +- Minecraft.World/Blocks/MelonTile.h | 27 +- Minecraft.World/Blocks/MetalTile.cpp | 4 +- Minecraft.World/Blocks/MetalTile.h | 5 +- Minecraft.World/Blocks/MobSpawner.cpp | 911 ++- Minecraft.World/Blocks/MobSpawner.h | 39 +- Minecraft.World/Blocks/MobSpawnerTile.cpp | 63 +- Minecraft.World/Blocks/MobSpawnerTile.h | 20 +- Minecraft.World/Blocks/MushroomPlantTile.cpp | 89 +- Minecraft.World/Blocks/MushroomPlantTile.h | 28 +- Minecraft.World/Blocks/MusicTile.cpp | 123 +- Minecraft.World/Blocks/MusicTile.h | 22 +- Minecraft.World/Blocks/MycelTile.cpp | 99 +- Minecraft.World/Blocks/MycelTile.h | 35 +- Minecraft.World/Blocks/NetherStalkTile.cpp | 162 +- Minecraft.World/Blocks/NetherStalkTile.h | 42 +- Minecraft.World/Blocks/NotGateTile.cpp | 224 +- Minecraft.World/Blocks/NotGateTile.h | 51 +- Minecraft.World/Blocks/ObsidianTile.cpp | 14 +- Minecraft.World/Blocks/ObsidianTile.h | 9 +- Minecraft.World/Blocks/OreTile.cpp | 86 +- Minecraft.World/Blocks/OreTile.h | 16 +- Minecraft.World/Blocks/PistonBaseTile.cpp | 736 +- Minecraft.World/Blocks/PistonBaseTile.h | 101 +- .../Blocks/PistonExtensionTile.cpp | 266 +- Minecraft.World/Blocks/PistonExtensionTile.h | 35 +- .../Blocks/PistonMovingTileEntity.cpp | 207 +- .../Blocks/PistonMovingTileEntity.h | 47 +- Minecraft.World/Blocks/PlantTile.cpp | 78 +- Minecraft.World/Blocks/PlantTile.h | 27 +- Minecraft.World/Blocks/PortalMaterial.h | 11 +- Minecraft.World/Blocks/PortalTile.cpp | 224 +- Minecraft.World/Blocks/PortalTile.h | 34 +- Minecraft.World/Blocks/PotatoTile.cpp | 82 +- Minecraft.World/Blocks/PotatoTile.h | 21 +- Minecraft.World/Blocks/PressurePlateTile.cpp | 196 +- Minecraft.World/Blocks/PressurePlateTile.h | 66 +- Minecraft.World/Blocks/PumpkinTile.cpp | 248 +- Minecraft.World/Blocks/PumpkinTile.h | 41 +- Minecraft.World/Blocks/QuartzBlockTile.cpp | 176 +- Minecraft.World/Blocks/QuartzBlockTile.h | 58 +- Minecraft.World/Blocks/RailTile.cpp | 1070 ++- Minecraft.World/Blocks/RailTile.h | 118 +- Minecraft.World/Blocks/RecordPlayerTile.cpp | 83 +- Minecraft.World/Blocks/RecordPlayerTile.h | 81 +- Minecraft.World/Blocks/RedLightTile.cpp | 97 +- Minecraft.World/Blocks/RedLightTile.h | 19 +- Minecraft.World/Blocks/RedStoneDustTile.cpp | 769 +- Minecraft.World/Blocks/RedStoneDustTile.h | 86 +- Minecraft.World/Blocks/RedStoneOreTile.cpp | 173 +- Minecraft.World/Blocks/RedStoneOreTile.h | 50 +- Minecraft.World/Blocks/ReedTile.cpp | 146 +- Minecraft.World/Blocks/ReedTile.h | 54 +- Minecraft.World/Blocks/SandStoneTile.cpp | 59 +- Minecraft.World/Blocks/SandStoneTile.h | 47 +- Minecraft.World/Blocks/SaplingPlantTile.cpp | 237 +- Minecraft.World/Blocks/SaplingPlantTile.h | 46 +- Minecraft.World/Blocks/SignTile.cpp | 179 +- Minecraft.World/Blocks/SignTile.h | 42 +- Minecraft.World/Blocks/SkullTile.cpp | 227 +- Minecraft.World/Blocks/SkullTile.h | 68 +- .../Blocks/SmoothStoneBrickTile.cpp | 52 +- Minecraft.World/Blocks/SmoothStoneBrickTile.h | 28 +- Minecraft.World/Blocks/SnowTile.cpp | 33 +- Minecraft.World/Blocks/SnowTile.h | 21 +- Minecraft.World/Blocks/SpongeTile.cpp | 5 +- Minecraft.World/Blocks/SpongeTile.h | 10 +- Minecraft.World/Blocks/SpringTile.cpp | 42 +- Minecraft.World/Blocks/SpringTile.h | 11 +- Minecraft.World/Blocks/StairTile.cpp | 838 +- Minecraft.World/Blocks/StairTile.h | 119 +- Minecraft.World/Blocks/StemTile.cpp | 201 +- Minecraft.World/Blocks/StemTile.h | 48 +- Minecraft.World/Blocks/StoneMonsterTile.cpp | 124 +- Minecraft.World/Blocks/StoneMonsterTile.h | 30 +- Minecraft.World/Blocks/StoneSlabTile.cpp | 118 +- Minecraft.World/Blocks/StoneSlabTile.h | 44 +- Minecraft.World/Blocks/StoneTile.cpp | 9 +- Minecraft.World/Blocks/StoneTile.h | 7 +- Minecraft.World/Blocks/TallGrassPlantTile.cpp | 129 +- Minecraft.World/Blocks/TallGrassPlantTile.h | 51 +- .../Blocks/TheEndPortalFrameTile.cpp | 80 +- .../Blocks/TheEndPortalFrameTile.h | 25 +- Minecraft.World/Blocks/TheEndPortalTile.cpp | 161 +- Minecraft.World/Blocks/TheEndPortalTile.h | 42 +- Minecraft.World/Blocks/ThinFenceTile.cpp | 131 +- Minecraft.World/Blocks/ThinFenceTile.h | 37 +- Minecraft.World/Blocks/Tile.cpp | 3430 +++++--- Minecraft.World/Blocks/Tile.h | 894 ++- .../TileEntities/BrewingStandTileEntity.cpp | 476 +- .../TileEntities/BrewingStandTileEntity.h | 38 +- .../Blocks/TileEntities/ChestTileEntity.cpp | 346 +- .../Blocks/TileEntities/ChestTileEntity.h | 57 +- .../TileEntities/DispenserTileEntity.cpp | 312 +- .../Blocks/TileEntities/DispenserTileEntity.h | 55 +- .../EnchantmentTableTileEntity.cpp | 169 +- .../TileEntities/EnchantmentTableTileEntity.h | 21 +- .../TileEntities/EnderChestTileEntity.cpp | 137 +- .../TileEntities/EnderChestTileEntity.h | 31 +- .../Blocks/TileEntities/EntityTile.cpp | 28 +- .../Blocks/TileEntities/EntityTile.h | 15 +- .../Blocks/TileEntities/FurnaceTileEntity.cpp | 506 +- .../Blocks/TileEntities/FurnaceTileEntity.h | 90 +- .../TileEntities/MobSpawnerTileEntity.cpp | 354 +- .../TileEntities/MobSpawnerTileEntity.h | 60 +- .../Blocks/TileEntities/MusicTileEntity.cpp | 66 +- .../Blocks/TileEntities/MusicTileEntity.h | 26 +- .../TileEntities/PistonPieceTileEntity.cpp | 314 +- .../TileEntities/PistonPieceTileEntity.h | 64 +- .../Blocks/TileEntities/PotionBrewing.cpp | 1356 ++-- .../Blocks/TileEntities/PotionBrewing.h | 133 +- .../Blocks/TileEntities/SignTileEntity.cpp | 267 +- .../Blocks/TileEntities/SignTileEntity.h | 66 +- .../Blocks/TileEntities/SkullTileEntity.cpp | 86 +- .../Blocks/TileEntities/SkullTileEntity.h | 46 +- .../TileEntities/TheEndPortalTileEntity.cpp | 10 +- .../TileEntities/TheEndPortalTileEntity.h | 11 +- .../Blocks/TileEntities/TileEntity.cpp | 288 +- .../Blocks/TileEntities/TileEntity.h | 106 +- Minecraft.World/Blocks/TntTile.cpp | 167 +- Minecraft.World/Blocks/TntTile.h | 38 +- Minecraft.World/Blocks/TopSnowTile.cpp | 246 +- Minecraft.World/Blocks/TopSnowTile.h | 58 +- Minecraft.World/Blocks/TorchTile.cpp | 357 +- Minecraft.World/Blocks/TorchTile.h | 53 +- Minecraft.World/Blocks/TransparentTile.cpp | 21 +- Minecraft.World/Blocks/TransparentTile.h | 15 +- Minecraft.World/Blocks/TrapDoorTile.cpp | 285 +- Minecraft.World/Blocks/TrapDoorTile.h | 81 +- Minecraft.World/Blocks/TreeTile.cpp | 198 +- Minecraft.World/Blocks/TreeTile.h | 60 +- Minecraft.World/Blocks/TripWireSourceTile.cpp | 595 +- Minecraft.World/Blocks/TripWireSourceTile.h | 66 +- Minecraft.World/Blocks/TripWireTile.cpp | 333 +- Minecraft.World/Blocks/TripWireTile.h | 60 +- Minecraft.World/Blocks/VineTile.cpp | 418 +- Minecraft.World/Blocks/VineTile.h | 48 +- Minecraft.World/Blocks/WallTile.cpp | 285 +- Minecraft.World/Blocks/WallTile.h | 44 +- Minecraft.World/Blocks/WaterLilyTile.cpp | 82 +- Minecraft.World/Blocks/WaterLilyTile.h | 27 +- Minecraft.World/Blocks/WebMaterial.h | 10 +- Minecraft.World/Blocks/WebTile.cpp | 49 +- Minecraft.World/Blocks/WebTile.h | 27 +- Minecraft.World/Blocks/WoodSlabTile.cpp | 62 +- Minecraft.World/Blocks/WoodSlabTile.h | 31 +- Minecraft.World/Blocks/WoodTile.cpp | 57 +- Minecraft.World/Blocks/WoodTile.h | 23 +- Minecraft.World/Blocks/WoolCarpetTile.cpp | 137 +- Minecraft.World/Blocks/WoolCarpetTile.h | 51 +- Minecraft.World/Blocks/WorkbenchTile.cpp | 50 +- Minecraft.World/Blocks/WorkbenchTile.h | 24 +- Minecraft.World/Commands/AdminLogCommand.h | 11 +- Minecraft.World/Commands/Command.cpp | 54 +- Minecraft.World/Commands/Command.h | 28 +- .../Commands/CommandDispatcher.cpp | 43 +- Minecraft.World/Commands/CommandDispatcher.h | 14 +- Minecraft.World/Commands/CommandSender.h | 12 +- Minecraft.World/Commands/CommandsEnum.h | 23 +- .../Commands/DefaultGameModeCommand.cpp | 28 +- .../Commands/DefaultGameModeCommand.h | 10 +- .../Commands/EnchantItemCommand.cpp | 140 +- Minecraft.World/Commands/EnchantItemCommand.h | 14 +- .../Commands/ExperienceCommand.cpp | 60 +- Minecraft.World/Commands/ExperienceCommand.h | 10 +- Minecraft.World/Commands/GameModeCommand.cpp | 87 +- Minecraft.World/Commands/GameModeCommand.h | 13 +- Minecraft.World/Commands/GiveItemCommand.cpp | 78 +- Minecraft.World/Commands/GiveItemCommand.h | 12 +- Minecraft.World/Commands/KillCommand.cpp | 15 +- Minecraft.World/Commands/KillCommand.h | 8 +- Minecraft.World/Commands/TimeCommand.cpp | 126 +- Minecraft.World/Commands/TimeCommand.h | 14 +- .../Commands/ToggleDownfallCommand.cpp | 28 +- .../Commands/ToggleDownfallCommand.h | 12 +- .../Containers/AbstractContainerMenu.cpp | 853 +- .../Containers/AbstractContainerMenu.h | 113 +- Minecraft.World/Containers/ArmorSlot.cpp | 63 +- Minecraft.World/Containers/ArmorSlot.h | 25 +- .../Containers/BrewingStandMenu.cpp | 383 +- Minecraft.World/Containers/BrewingStandMenu.h | 83 +- .../Containers/ClientSideMerchant.cpp | 73 +- .../Containers/ClientSideMerchant.h | 29 +- .../Containers/CompoundContainer.cpp | 97 +- .../Containers/CompoundContainer.h | 33 +- Minecraft.World/Containers/Container.h | 18 +- Minecraft.World/Containers/ContainerMenu.cpp | 173 +- Minecraft.World/Containers/ContainerMenu.h | 23 +- .../Containers/CraftingContainer.cpp | 134 +- .../Containers/CraftingContainer.h | 40 +- Minecraft.World/Containers/CraftingMenu.cpp | 190 +- Minecraft.World/Containers/CraftingMenu.h | 41 +- .../Containers/EnchantmentContainer.cpp | 17 +- .../Containers/EnchantmentContainer.h | 16 +- .../Containers/EnchantmentMenu.cpp | 463 +- Minecraft.World/Containers/EnchantmentMenu.h | 51 +- Minecraft.World/Containers/EnchantmentSlot.h | 16 +- Minecraft.World/Containers/FurnaceMenu.cpp | 263 +- Minecraft.World/Containers/FurnaceMenu.h | 45 +- .../Containers/FurnaceResultSlot.cpp | 126 +- .../Containers/FurnaceResultSlot.h | 26 +- Minecraft.World/Containers/Inventory.cpp | 1118 ++- Minecraft.World/Containers/Inventory.h | 141 +- Minecraft.World/Containers/InventoryMenu.cpp | 395 +- Minecraft.World/Containers/InventoryMenu.h | 55 +- Minecraft.World/Containers/MenuBackup.cpp | 57 +- Minecraft.World/Containers/MenuBackup.h | 20 +- Minecraft.World/Containers/Merchant.h | 20 +- .../Containers/MerchantContainer.cpp | 274 +- .../Containers/MerchantContainer.h | 48 +- Minecraft.World/Containers/MerchantMenu.cpp | 220 +- Minecraft.World/Containers/MerchantMenu.h | 59 +- Minecraft.World/Containers/MerchantRecipe.cpp | 208 +- Minecraft.World/Containers/MerchantRecipe.h | 59 +- .../Containers/MerchantRecipeList.cpp | 299 +- .../Containers/MerchantRecipeList.h | 44 +- .../Containers/MerchantResultSlot.cpp | 138 +- .../Containers/MerchantResultSlot.h | 32 +- .../Containers/MouseInventoryClickHandler.h | 158 +- .../Containers/RepairContainer.cpp | 13 +- Minecraft.World/Containers/RepairContainer.h | 10 +- Minecraft.World/Containers/RepairMenu.cpp | 655 +- Minecraft.World/Containers/RepairMenu.h | 82 +- .../Containers/RepairResultSlot.cpp | 109 +- Minecraft.World/Containers/RepairResultSlot.h | 20 +- .../Containers/ResultContainer.cpp | 77 +- Minecraft.World/Containers/ResultContainer.h | 34 +- Minecraft.World/Containers/ResultSlot.cpp | 176 +- Minecraft.World/Containers/ResultSlot.h | 28 +- .../Containers/SimpleContainer.cpp | 138 +- Minecraft.World/Containers/SimpleContainer.h | 41 +- Minecraft.World/Containers/Slot.cpp | 237 +- Minecraft.World/Containers/Slot.h | 52 +- Minecraft.World/Containers/TrapMenu.cpp | 114 +- Minecraft.World/Containers/TrapMenu.h | 22 +- .../Enchantments/ArrowDamageEnchantment.cpp | 21 +- .../Enchantments/ArrowDamageEnchantment.h | 11 +- .../Enchantments/ArrowFireEnchantment.cpp | 21 +- .../Enchantments/ArrowFireEnchantment.h | 11 +- .../Enchantments/ArrowInfiniteEnchantment.cpp | 21 +- .../Enchantments/ArrowInfiniteEnchantment.h | 11 +- .../ArrowKnockbackEnchantment.cpp | 21 +- .../Enchantments/ArrowKnockbackEnchantment.h | 11 +- .../Enchantments/DamageEnchantment.cpp | 75 +- .../Enchantments/DamageEnchantment.h | 35 +- .../Enchantments/DigDurabilityEnchantment.cpp | 40 +- .../Enchantments/DigDurabilityEnchantment.h | 16 +- .../Enchantments/DiggingEnchantment.cpp | 30 +- .../Enchantments/DiggingEnchantment.h | 13 +- Minecraft.World/Enchantments/Enchantment.cpp | 306 +- Minecraft.World/Enchantments/Enchantment.h | 115 +- .../Enchantments/EnchantmentCategory.cpp | 69 +- .../Enchantments/EnchantmentCategory.h | 23 +- .../Enchantments/EnchantmentHelper.cpp | 743 +- .../Enchantments/EnchantmentHelper.h | 171 +- .../Enchantments/EnchantmentInstance.cpp | 19 +- .../Enchantments/EnchantmentInstance.h | 15 +- .../Enchantments/FireAspectEnchantment.cpp | 21 +- .../Enchantments/FireAspectEnchantment.h | 11 +- .../Enchantments/KnockbackEnchantment.cpp | 23 +- .../Enchantments/KnockbackEnchantment.h | 11 +- .../Enchantments/LootBonusEnchantment.cpp | 36 +- .../Enchantments/LootBonusEnchantment.h | 13 +- .../Enchantments/OxygenEnchantment.cpp | 21 +- .../Enchantments/OxygenEnchantment.h | 11 +- .../Enchantments/ProtectionEnchantment.cpp | 129 +- .../Enchantments/ProtectionEnchantment.h | 42 +- .../Enchantments/ThornsEnchantment.cpp | 94 +- .../Enchantments/ThornsEnchantment.h | 23 +- .../Enchantments/UntouchingEnchantment.cpp | 38 +- .../Enchantments/UntouchingEnchantment.h | 15 +- .../Enchantments/WaterWorkerEnchantment.cpp | 23 +- .../Enchantments/WaterWorkerEnchantment.h | 11 +- Minecraft.World/Entities/BossMobPart.cpp | 52 +- Minecraft.World/Entities/BossMobPart.h | 26 +- Minecraft.World/Entities/DoorInfo.cpp | 83 +- Minecraft.World/Entities/DoorInfo.h | 39 +- Minecraft.World/Entities/Enemy.cpp | 2 - Minecraft.World/Entities/Enemy.h | 13 +- Minecraft.World/Entities/Entity.cpp | 3153 ++++---- Minecraft.World/Entities/Entity.h | 536 +- .../Entities/EntityDamageSource.cpp | 45 +- Minecraft.World/Entities/EntityDamageSource.h | 24 +- Minecraft.World/Entities/EntityEvent.h | 39 +- Minecraft.World/Entities/EntityPos.cpp | 85 +- Minecraft.World/Entities/EntityPos.h | 19 +- Minecraft.World/Entities/FlyingMob.cpp | 129 +- Minecraft.World/Entities/FlyingMob.h | 11 +- Minecraft.World/Entities/GlobalEntity.cpp | 1 - Minecraft.World/Entities/GlobalEntity.h | 7 +- Minecraft.World/Entities/HangingEntity.cpp | 435 +- Minecraft.World/Entities/HangingEntity.h | 55 +- .../Entities/IndirectEntityDamageSource.cpp | 62 +- .../Entities/IndirectEntityDamageSource.h | 28 +- .../Entities/InstantaneousMobEffect.cpp | 17 +- .../Entities/InstantaneousMobEffect.h | 9 +- Minecraft.World/Entities/ItemEntity.cpp | 452 +- Minecraft.World/Entities/ItemEntity.h | 73 +- Minecraft.World/Entities/Mob.cpp | 3044 ++++--- Minecraft.World/Entities/Mob.h | 463 +- Minecraft.World/Entities/MobCategory.cpp | 98 +- Minecraft.World/Entities/MobCategory.h | 155 +- Minecraft.World/Entities/MobEffect.cpp | 473 +- Minecraft.World/Entities/MobEffect.h | 171 +- .../Entities/MobEffectInstance.cpp | 185 +- Minecraft.World/Entities/MobEffectInstance.h | 51 +- Minecraft.World/Entities/MobType.h | 9 +- Minecraft.World/Entities/Mobs/AgeableMob.cpp | 172 +- Minecraft.World/Entities/Mobs/AgeableMob.h | 36 +- Minecraft.World/Entities/Mobs/Animal.cpp | 699 +- Minecraft.World/Entities/Mobs/Animal.h | 82 +- Minecraft.World/Entities/Mobs/Arrow.cpp | 795 +- Minecraft.World/Entities/Mobs/Arrow.h | 66 +- Minecraft.World/Entities/Mobs/Blaze.cpp | 344 +- Minecraft.World/Entities/Mobs/Blaze.h | 51 +- Minecraft.World/Entities/Mobs/Boat.cpp | 766 +- Minecraft.World/Entities/Mobs/Boat.h | 96 +- Minecraft.World/Entities/Mobs/BossMob.cpp | 38 +- Minecraft.World/Entities/Mobs/BossMob.h | 16 +- Minecraft.World/Entities/Mobs/CaveSpider.cpp | 85 +- Minecraft.World/Entities/Mobs/CaveSpider.h | 21 +- Minecraft.World/Entities/Mobs/Chicken.cpp | 219 +- Minecraft.World/Entities/Mobs/Chicken.h | 32 +- Minecraft.World/Entities/Mobs/Cow.cpp | 180 +- Minecraft.World/Entities/Mobs/Cow.h | 32 +- Minecraft.World/Entities/Mobs/Creature.cpp | 1 - Minecraft.World/Entities/Mobs/Creature.h | 5 +- Minecraft.World/Entities/Mobs/Creeper.cpp | 177 +- Minecraft.World/Entities/Mobs/Creeper.h | 44 +- .../Entities/Mobs/DragonFireball.cpp | 105 +- .../Entities/Mobs/DragonFireball.h | 33 +- .../Entities/Mobs/EnderCrystal.cpp | 171 +- Minecraft.World/Entities/Mobs/EnderCrystal.h | 48 +- Minecraft.World/Entities/Mobs/EnderDragon.cpp | 3155 ++++---- Minecraft.World/Entities/Mobs/EnderDragon.h | 233 +- Minecraft.World/Entities/Mobs/EnderMan.cpp | 605 +- Minecraft.World/Entities/Mobs/EnderMan.h | 93 +- .../Entities/Mobs/ExperienceOrb.cpp | 489 +- Minecraft.World/Entities/Mobs/ExperienceOrb.h | 59 +- .../Entities/Mobs/EyeOfEnderSignal.cpp | 302 +- .../Entities/Mobs/EyeOfEnderSignal.h | 43 +- Minecraft.World/Entities/Mobs/Fireball.cpp | 444 +- Minecraft.World/Entities/Mobs/Fireball.h | 74 +- Minecraft.World/Entities/Mobs/FishingHook.cpp | 761 +- Minecraft.World/Entities/Mobs/FishingHook.h | 68 +- Minecraft.World/Entities/Mobs/Ghast.cpp | 250 +- Minecraft.World/Entities/Mobs/Ghast.h | 44 +- Minecraft.World/Entities/Mobs/Giant.cpp | 36 +- Minecraft.World/Entities/Mobs/Giant.h | 16 +- Minecraft.World/Entities/Mobs/Golem.cpp | 36 +- Minecraft.World/Entities/Mobs/Golem.h | 17 +- Minecraft.World/Entities/Mobs/ItemFrame.cpp | 198 +- Minecraft.World/Entities/Mobs/ItemFrame.h | 42 +- Minecraft.World/Entities/Mobs/LavaSlime.cpp | 188 +- Minecraft.World/Entities/Mobs/LavaSlime.h | 49 +- .../Entities/Mobs/LightningBolt.cpp | 225 +- Minecraft.World/Entities/Mobs/LightningBolt.h | 30 +- Minecraft.World/Entities/Mobs/Minecart.cpp | 1983 +++-- Minecraft.World/Entities/Mobs/Minecart.h | 133 +- Minecraft.World/Entities/Mobs/MushroomCow.cpp | 130 +- Minecraft.World/Entities/Mobs/MushroomCow.h | 16 +- Minecraft.World/Entities/Mobs/Npc.cpp | 1 - Minecraft.World/Entities/Mobs/Npc.h | 5 +- Minecraft.World/Entities/Mobs/Ocelot.cpp | 469 +- Minecraft.World/Entities/Mobs/Ocelot.h | 80 +- Minecraft.World/Entities/Mobs/Painting.cpp | 193 +- Minecraft.World/Entities/Mobs/Painting.h | 148 +- Minecraft.World/Entities/Mobs/Pig.cpp | 252 +- Minecraft.World/Entities/Mobs/Pig.h | 55 +- Minecraft.World/Entities/Mobs/PigZombie.cpp | 215 +- Minecraft.World/Entities/Mobs/PigZombie.h | 48 +- Minecraft.World/Entities/Mobs/PrimedTnt.cpp | 152 +- Minecraft.World/Entities/Mobs/PrimedTnt.h | 33 +- Minecraft.World/Entities/Mobs/Sheep.cpp | 456 +- Minecraft.World/Entities/Mobs/Sheep.h | 86 +- Minecraft.World/Entities/Mobs/Silverfish.cpp | 308 +- Minecraft.World/Entities/Mobs/Silverfish.h | 44 +- Minecraft.World/Entities/Mobs/Skeleton.cpp | 159 +- Minecraft.World/Entities/Mobs/Skeleton.h | 35 +- Minecraft.World/Entities/Mobs/Slime.cpp | 415 +- Minecraft.World/Entities/Mobs/Slime.h | 84 +- .../Entities/Mobs/SmallFireball.cpp | 115 +- Minecraft.World/Entities/Mobs/SmallFireball.h | 21 +- Minecraft.World/Entities/Mobs/SnowMan.cpp | 124 +- Minecraft.World/Entities/Mobs/SnowMan.h | 19 +- Minecraft.World/Entities/Mobs/Snowball.cpp | 65 +- Minecraft.World/Entities/Mobs/Snowball.h | 18 +- Minecraft.World/Entities/Mobs/Spider.cpp | 229 +- Minecraft.World/Entities/Mobs/Spider.h | 48 +- Minecraft.World/Entities/Mobs/Squid.cpp | 282 +- Minecraft.World/Entities/Mobs/Squid.h | 53 +- Minecraft.World/Entities/Mobs/ThrownEgg.cpp | 97 +- Minecraft.World/Entities/Mobs/ThrownEgg.h | 16 +- .../Entities/Mobs/ThrownEnderPearl.cpp | 88 +- .../Entities/Mobs/ThrownEnderPearl.h | 15 +- .../Entities/Mobs/ThrownExpBottle.cpp | 61 +- .../Entities/Mobs/ThrownExpBottle.h | 22 +- .../Entities/Mobs/ThrownPotion.cpp | 202 +- Minecraft.World/Entities/Mobs/ThrownPotion.h | 37 +- Minecraft.World/Entities/Mobs/Villager.cpp | 1352 ++-- Minecraft.World/Entities/Mobs/Villager.h | 177 +- .../Entities/Mobs/VillagerGolem.cpp | 329 +- Minecraft.World/Entities/Mobs/VillagerGolem.h | 65 +- Minecraft.World/Entities/Mobs/Wolf.cpp | 810 +- Minecraft.World/Entities/Mobs/Wolf.h | 108 +- Minecraft.World/Entities/Mobs/Zombie.cpp | 525 +- Minecraft.World/Entities/Mobs/Zombie.h | 86 +- Minecraft.World/Entities/Monster.cpp | 152 +- Minecraft.World/Entities/Monster.h | 26 +- Minecraft.World/Entities/PathfinderMob.cpp | 434 +- Minecraft.World/Entities/PathfinderMob.h | 45 +- Minecraft.World/Entities/SyncedEntityData.cpp | 791 +- Minecraft.World/Entities/SyncedEntityData.h | 200 +- Minecraft.World/Entities/TamableAnimal.cpp | 201 +- Minecraft.World/Entities/TamableAnimal.h | 40 +- Minecraft.World/Entities/Throwable.cpp | 452 +- Minecraft.World/Entities/Throwable.h | 54 +- Minecraft.World/Entities/WaterAnimal.cpp | 38 +- Minecraft.World/Entities/WaterAnimal.h | 15 +- .../Headers/net.minecraft.network.packet.h | 1 - .../net.minecraft.world.ContainerListener.h | 25 +- .../Headers/net.minecraft.world.entity.h | 2 +- .../net.minecraft.world.entity.projectile.h | 2 +- ...ecraft.world.inventory.ContainerListener.h | 29 +- .../Headers/net.minecraft.world.item.h | 6 +- .../Headers/net.minecraft.world.level.biome.h | 3 +- ...net.minecraft.world.level.newbiome.layer.h | 2 +- .../net.minecraft.world.level.storage.h | 5 +- .../Headers/net.minecraft.world.level.tile.h | 2 - Minecraft.World/IO/Files/ConsoleSaveFile.h | 91 +- .../IO/Files/ConsoleSaveFileConverter.cpp | 473 +- .../IO/Files/ConsoleSaveFileConverter.h | 20 +- .../IO/Files/ConsoleSaveFileInputStream.cpp | 192 +- .../IO/Files/ConsoleSaveFileInputStream.h | 26 +- .../IO/Files/ConsoleSaveFileOriginal.cpp | 1514 ++-- .../IO/Files/ConsoleSaveFileOriginal.h | 126 +- .../IO/Files/ConsoleSaveFileOutputStream.cpp | 180 +- .../IO/Files/ConsoleSaveFileOutputStream.h | 25 +- .../IO/Files/ConsoleSaveFileSplit.cpp | 2657 +++---- .../IO/Files/ConsoleSaveFileSplit.h | 225 +- Minecraft.World/IO/Files/ConsoleSavePath.h | 12 +- Minecraft.World/IO/Files/File.cpp | 1241 ++- Minecraft.World/IO/Files/File.h | 70 +- Minecraft.World/IO/Files/FileFilter.h | 5 +- Minecraft.World/IO/Files/FileHeader.cpp | 1025 ++- Minecraft.World/IO/Files/FileHeader.h | 278 +- Minecraft.World/IO/Files/FileInputStream.cpp | 319 +- Minecraft.World/IO/Files/FileInputStream.h | 20 +- Minecraft.World/IO/Files/FileOutputStream.cpp | 202 +- Minecraft.World/IO/Files/FileOutputStream.h | 19 +- Minecraft.World/IO/Files/FilenameFilter.h | 6 +- Minecraft.World/IO/NBT/ByteArrayTag.h | 81 +- Minecraft.World/IO/NBT/ByteTag.h | 51 +- Minecraft.World/IO/NBT/CompoundTag.h | 360 +- Minecraft.World/IO/NBT/DoubleTag.h | 51 +- Minecraft.World/IO/NBT/EndTag.h | 25 +- Minecraft.World/IO/NBT/FloatTag.h | 51 +- Minecraft.World/IO/NBT/IntArrayTag.h | 90 +- Minecraft.World/IO/NBT/IntTag.h | 51 +- Minecraft.World/IO/NBT/ListTag.h | 123 +- Minecraft.World/IO/NBT/LongTag.h | 51 +- Minecraft.World/IO/NBT/NbtIO.cpp | 93 +- Minecraft.World/IO/NBT/NbtIO.h | 15 +- Minecraft.World/IO/NBT/NbtSlotFile.cpp | 309 +- Minecraft.World/IO/NBT/NbtSlotFile.h | 15 +- Minecraft.World/IO/NBT/ShortTag.h | 51 +- Minecraft.World/IO/NBT/StringTag.h | 50 +- Minecraft.World/IO/NBT/Tag.cpp | 262 +- Minecraft.World/IO/NBT/Tag.h | 31 +- Minecraft.World/IO/Streams/Buffer.cpp | 102 +- Minecraft.World/IO/Streams/Buffer.h | 48 +- .../IO/Streams/BufferedOutputStream.cpp | 164 +- .../IO/Streams/BufferedOutputStream.h | 25 +- Minecraft.World/IO/Streams/BufferedReader.cpp | 281 +- Minecraft.World/IO/Streams/BufferedReader.h | 33 +- .../IO/Streams/ByteArrayInputStream.cpp | 185 +- .../IO/Streams/ByteArrayInputStream.h | 41 +- .../IO/Streams/ByteArrayOutputStream.cpp | 114 +- .../IO/Streams/ByteArrayOutputStream.h | 33 +- Minecraft.World/IO/Streams/ByteBuffer.cpp | 709 +- Minecraft.World/IO/Streams/ByteBuffer.h | 75 +- Minecraft.World/IO/Streams/Compression.cpp | 858 +- Minecraft.World/IO/Streams/Compression.h | 122 +- Minecraft.World/IO/Streams/DataInput.h | 35 +- .../IO/Streams/DataInputStream.cpp | 1082 ++- Minecraft.World/IO/Streams/DataInputStream.h | 52 +- Minecraft.World/IO/Streams/DataOutput.h | 32 +- .../IO/Streams/DataOutputStream.cpp | 453 +- Minecraft.World/IO/Streams/DataOutputStream.h | 51 +- Minecraft.World/IO/Streams/FloatBuffer.cpp | 90 +- Minecraft.World/IO/Streams/FloatBuffer.h | 19 +- Minecraft.World/IO/Streams/GZIPInputStream.h | 23 +- Minecraft.World/IO/Streams/GZIPOutputStream.h | 23 +- Minecraft.World/IO/Streams/InputStream.cpp | 5 +- Minecraft.World/IO/Streams/InputStream.h | 17 +- .../IO/Streams/InputStreamReader.cpp | 79 +- .../IO/Streams/InputStreamReader.h | 13 +- Minecraft.World/IO/Streams/IntBuffer.cpp | 152 +- Minecraft.World/IO/Streams/IntBuffer.h | 24 +- Minecraft.World/IO/Streams/OutputStream.h | 16 +- Minecraft.World/IO/Streams/Reader.h | 14 +- Minecraft.World/Items/ArmorItem.cpp | 301 +- Minecraft.World/Items/ArmorItem.h | 126 +- Minecraft.World/Items/BedItem.cpp | 100 +- Minecraft.World/Items/BedItem.h | 11 +- Minecraft.World/Items/BoatItem.cpp | 210 +- Minecraft.World/Items/BoatItem.h | 26 +- Minecraft.World/Items/BookItem.cpp | 16 +- Minecraft.World/Items/BookItem.h | 9 +- Minecraft.World/Items/BottleItem.cpp | 135 +- Minecraft.World/Items/BottleItem.h | 19 +- Minecraft.World/Items/BowItem.cpp | 152 +- Minecraft.World/Items/BowItem.h | 37 +- Minecraft.World/Items/BowlFoodItem.cpp | 15 +- Minecraft.World/Items/BowlFoodItem.h | 9 +- Minecraft.World/Items/BucketItem.cpp | 389 +- Minecraft.World/Items/BucketItem.h | 36 +- Minecraft.World/Items/CarrotOnAStickItem.cpp | 61 +- Minecraft.World/Items/CarrotOnAStickItem.h | 13 +- Minecraft.World/Items/ClockItem.cpp | 50 +- Minecraft.World/Items/ClockItem.h | 18 +- Minecraft.World/Items/CoalItem.cpp | 20 +- Minecraft.World/Items/CoalItem.h | 13 +- Minecraft.World/Items/CompassItem.cpp | 50 +- Minecraft.World/Items/CompassItem.h | 18 +- Minecraft.World/Items/ComplexItem.cpp | 14 +- Minecraft.World/Items/ComplexItem.h | 12 +- Minecraft.World/Items/DiggerItem.cpp | 81 +- Minecraft.World/Items/DiggerItem.h | 41 +- Minecraft.World/Items/DoorItem.cpp | 100 +- Minecraft.World/Items/DoorItem.h | 15 +- Minecraft.World/Items/DyePowderItem.cpp | 453 +- Minecraft.World/Items/DyePowderItem.h | 70 +- Minecraft.World/Items/EggItem.cpp | 26 +- Minecraft.World/Items/EggItem.h | 10 +- Minecraft.World/Items/EnchantedBookItem.cpp | 229 +- Minecraft.World/Items/EnchantedBookItem.h | 37 +- Minecraft.World/Items/EnderEyeItem.cpp | 430 +- Minecraft.World/Items/EnderEyeItem.h | 16 +- Minecraft.World/Items/EnderPearlItem.cpp | 44 +- Minecraft.World/Items/EnderPearlItem.h | 13 +- Minecraft.World/Items/ExperienceItem.cpp | 37 +- Minecraft.World/Items/ExperienceItem.h | 13 +- Minecraft.World/Items/FireChargeItem.cpp | 82 +- Minecraft.World/Items/FireChargeItem.h | 17 +- Minecraft.World/Items/FishingRodItem.cpp | 77 +- Minecraft.World/Items/FishingRodItem.h | 24 +- Minecraft.World/Items/FlintAndSteelItem.cpp | 95 +- Minecraft.World/Items/FlintAndSteelItem.h | 10 +- Minecraft.World/Items/FoodItem.cpp | 149 +- Minecraft.World/Items/FoodItem.h | 58 +- Minecraft.World/Items/GoldenAppleItem.cpp | 73 +- Minecraft.World/Items/GoldenAppleItem.h | 22 +- Minecraft.World/Items/HangingEntityItem.cpp | 122 +- Minecraft.World/Items/HangingEntityItem.h | 21 +- Minecraft.World/Items/HatchetItem.cpp | 37 +- Minecraft.World/Items/HatchetItem.h | 13 +- Minecraft.World/Items/HoeItem.cpp | 65 +- Minecraft.World/Items/HoeItem.h | 18 +- Minecraft.World/Items/Item.cpp | 2384 +++--- Minecraft.World/Items/Item.h | 1290 +-- Minecraft.World/Items/ItemInstance.cpp | 904 +-- Minecraft.World/Items/ItemInstance.h | 241 +- Minecraft.World/Items/MapItem.cpp | 546 +- Minecraft.World/Items/MapItem.h | 33 +- Minecraft.World/Items/MilkBucketItem.cpp | 55 +- Minecraft.World/Items/MilkBucketItem.h | 19 +- Minecraft.World/Items/MinecartItem.cpp | 41 +- Minecraft.World/Items/MinecartItem.h | 13 +- Minecraft.World/Items/MonsterPlacerItem.cpp | 453 +- Minecraft.World/Items/MonsterPlacerItem.h | 62 +- Minecraft.World/Items/PickaxeItem.cpp | 98 +- Minecraft.World/Items/PickaxeItem.h | 17 +- Minecraft.World/Items/PotionItem.cpp | 602 +- Minecraft.World/Items/PotionItem.h | 90 +- Minecraft.World/Items/RecordingItem.cpp | 89 +- Minecraft.World/Items/RecordingItem.h | 32 +- Minecraft.World/Items/RedstoneItem.cpp | 62 +- Minecraft.World/Items/RedstoneItem.h | 15 +- Minecraft.World/Items/SaddleItem.cpp | 24 +- Minecraft.World/Items/SaddleItem.h | 13 +- Minecraft.World/Items/SeedFoodItem.cpp | 41 +- Minecraft.World/Items/SeedFoodItem.h | 15 +- Minecraft.World/Items/SeedItem.cpp | 28 +- Minecraft.World/Items/SeedItem.h | 15 +- Minecraft.World/Items/ShearsItem.cpp | 35 +- Minecraft.World/Items/ShearsItem.h | 15 +- Minecraft.World/Items/ShovelItem.cpp | 43 +- Minecraft.World/Items/ShovelItem.h | 11 +- Minecraft.World/Items/SignItem.cpp | 78 +- Minecraft.World/Items/SignItem.h | 11 +- Minecraft.World/Items/SnowballItem.cpp | 24 +- Minecraft.World/Items/SnowballItem.h | 10 +- .../Items/TileItems/AnvilTileItem.cpp | 20 +- .../Items/TileItems/AnvilTileItem.h | 10 +- .../Items/TileItems/AuxDataTileItem.cpp | 19 +- .../Items/TileItems/AuxDataTileItem.h | 11 +- .../Items/TileItems/ClothTileItem.cpp | 83 +- .../Items/TileItems/ClothTileItem.h | 21 +- .../Items/TileItems/ColoredTileItem.cpp | 80 +- .../Items/TileItems/ColoredTileItem.h | 27 +- .../Items/TileItems/LeafTileItem.cpp | 46 +- .../Items/TileItems/LeafTileItem.h | 18 +- .../Items/TileItems/MultiTextureTileItem.cpp | 58 +- .../Items/TileItems/MultiTextureTileItem.h | 23 +- .../Items/TileItems/PistonTileItem.cpp | 11 +- .../Items/TileItems/PistonTileItem.h | 8 +- .../Items/TileItems/PlanterTileItem.cpp | 103 +- .../Items/TileItems/PlanterTileItem.h | 13 +- .../Items/TileItems/SaplingTileItem.cpp | 32 +- .../Items/TileItems/SaplingTileItem.h | 15 +- Minecraft.World/Items/TileItems/SkullItem.cpp | 191 +- Minecraft.World/Items/TileItems/SkullItem.h | 34 +- .../TileItems/SmoothStoneBrickTileItem.cpp | 36 +- .../TileItems/SmoothStoneBrickTileItem.h | 15 +- .../Items/TileItems/StoneMonsterTileItem.cpp | 33 +- .../Items/TileItems/StoneMonsterTileItem.h | 16 +- .../Items/TileItems/StoneSlabTileItem.cpp | 217 +- .../Items/TileItems/StoneSlabTileItem.h | 36 +- Minecraft.World/Items/TileItems/TileItem.cpp | 303 +- Minecraft.World/Items/TileItems/TileItem.h | 58 +- .../Items/TileItems/TreeTileItem.cpp | 34 +- .../Items/TileItems/TreeTileItem.h | 15 +- .../Items/TileItems/WaterLilyTileItem.cpp | 116 +- .../Items/TileItems/WaterLilyTileItem.h | 15 +- Minecraft.World/Items/WeaponItem.cpp | 85 +- Minecraft.World/Items/WeaponItem.h | 42 +- .../Level/BlockDestructionProgress.cpp | 73 +- .../Level/BlockDestructionProgress.h | 33 +- Minecraft.World/Level/BlockGenMethods.cpp | 361 +- Minecraft.World/Level/BlockGenMethods.h | 20 +- Minecraft.World/Level/BlockReplacements.cpp | 17 +- Minecraft.World/Level/BlockReplacements.h | 5 +- Minecraft.World/Level/ChunkPos.cpp | 85 +- Minecraft.World/Level/ChunkPos.h | 52 +- Minecraft.World/Level/ChunkSource.h | 43 +- Minecraft.World/Level/CustomLevelSource.cpp | 888 ++- Minecraft.World/Level/CustomLevelSource.h | 60 +- Minecraft.World/Level/DerivedLevelData.cpp | 271 +- Minecraft.World/Level/DerivedLevelData.h | 95 +- .../Level/Dimensions/Dimension.cpp | 248 +- Minecraft.World/Level/Dimensions/Dimension.h | 50 +- .../Level/Dimensions/HellDimension.cpp | 91 +- .../Level/Dimensions/HellDimension.h | 25 +- .../Level/Dimensions/NormalDimension.h | 4 +- .../Level/Dimensions/SkyIslandDimension.cpp | 34 +- .../Level/Dimensions/TheEndDimension.cpp | 88 +- .../Level/Dimensions/TheEndDimension.h | 29 +- Minecraft.World/Level/EmptyLevelChunk.cpp | 274 +- Minecraft.World/Level/EmptyLevelChunk.h | 100 +- Minecraft.World/Level/Events/LevelEvent.h | 30 +- Minecraft.World/Level/Events/LevelListener.h | 50 +- .../Level/Events/LevelObjectInputStream.h | 3 +- Minecraft.World/Level/Events/VillageSiege.cpp | 271 +- Minecraft.World/Level/Events/VillageSiege.h | 35 +- Minecraft.World/Level/Explosion.cpp | 431 +- Minecraft.World/Level/Explosion.h | 44 +- Minecraft.World/Level/Level.cpp | 7036 ++++++++--------- Minecraft.World/Level/Level.h | 869 +- Minecraft.World/Level/LevelChunk.cpp | 3716 ++++----- Minecraft.World/Level/LevelChunk.h | 333 +- .../Level/LevelConflictException.cpp | 5 +- .../Level/LevelConflictException.h | 10 +- Minecraft.World/Level/LevelData.cpp | 700 +- Minecraft.World/Level/LevelData.h | 189 +- Minecraft.World/Level/RandomLevelSource.cpp | 945 +-- Minecraft.World/Level/RandomLevelSource.h | 84 +- Minecraft.World/Level/Storage/ChunkStorage.h | 13 +- .../Storage/ChunkStorageProfileDecorator.cpp | 77 +- .../Storage/ChunkStorageProfileDecorator.h | 23 +- .../Level/Storage/CompressedTileStorage.cpp | 2263 +++--- .../Level/Storage/CompressedTileStorage.h | 214 +- Minecraft.World/Level/Storage/DataLayer.cpp | 52 +- Minecraft.World/Level/Storage/DataLayer.h | 9 +- .../Level/Storage/DirectoryLevelStorage.cpp | 1298 ++- .../Level/Storage/DirectoryLevelStorage.h | 175 +- .../Storage/DirectoryLevelStorageSource.cpp | 169 +- .../Storage/DirectoryLevelStorageSource.h | 34 +- Minecraft.World/Level/Storage/EntityIO.cpp | 402 +- Minecraft.World/Level/Storage/EntityIO.h | 89 +- .../Level/Storage/LevelSettings.cpp | 267 +- Minecraft.World/Level/Storage/LevelSettings.h | 97 +- Minecraft.World/Level/Storage/LevelSource.h | 40 +- Minecraft.World/Level/Storage/LevelStorage.h | 35 +- .../Storage/LevelStorageProfilerDecorator.cpp | 59 +- .../Storage/LevelStorageProfilerDecorator.h | 23 +- .../Level/Storage/LevelStorageSource.h | 30 +- .../Level/Storage/LevelSummary.cpp | 99 +- Minecraft.World/Level/Storage/LevelSummary.h | 24 +- Minecraft.World/Level/Storage/LevelType.cpp | 153 +- Minecraft.World/Level/Storage/LevelType.h | 54 +- .../Level/Storage/MapItemSavedData.cpp | 917 +-- .../Level/Storage/MapItemSavedData.h | 118 +- .../Level/Storage/McRegionChunkStorage.cpp | 727 +- .../Level/Storage/McRegionChunkStorage.h | 46 +- .../Level/Storage/McRegionLevelStorage.cpp | 145 +- .../Level/Storage/McRegionLevelStorage.h | 21 +- .../Storage/McRegionLevelStorageSource.cpp | 136 +- .../Storage/McRegionLevelStorageSource.h | 31 +- .../Level/Storage/MemoryChunkStorage.cpp | 25 +- .../Level/Storage/MemoryChunkStorage.h | 10 +- .../Level/Storage/MemoryLevelStorage.cpp | 74 +- .../Level/Storage/MemoryLevelStorage.h | 17 +- .../Storage/MemoryLevelStorageSource.cpp | 71 +- .../Level/Storage/MemoryLevelStorageSource.h | 16 +- .../Level/Storage/MockedLevelStorage.cpp | 42 +- .../Level/Storage/MockedLevelStorage.h | 26 +- .../Level/Storage/OldChunkStorage.cpp | 957 ++- .../Level/Storage/OldChunkStorage.h | 69 +- Minecraft.World/Level/Storage/PlayerIO.h | 28 +- .../Level/Storage/PortalForcer.cpp | 576 +- Minecraft.World/Level/Storage/PortalForcer.h | 15 +- .../Level/Storage/ReadOnlyChunkCache.cpp | 119 +- .../Level/Storage/ReadOnlyChunkCache.h | 28 +- Minecraft.World/Level/Storage/Region.cpp | 547 +- Minecraft.World/Level/Storage/Region.h | 70 +- Minecraft.World/Level/Storage/RegionFile.cpp | 832 +- Minecraft.World/Level/Storage/RegionFile.h | 84 +- .../Level/Storage/RegionFileCache.cpp | 167 +- .../Level/Storage/RegionFileCache.h | 66 +- Minecraft.World/Level/Storage/SavedData.cpp | 22 +- Minecraft.World/Level/Storage/SavedData.h | 22 +- .../Level/Storage/SavedDataStorage.cpp | 257 +- .../Level/Storage/SavedDataStorage.h | 25 +- .../Level/Storage/SparseDataStorage.cpp | 992 +-- .../Level/Storage/SparseDataStorage.h | 150 +- .../Level/Storage/SparseLightStorage.cpp | 1013 ++- .../Level/Storage/SparseLightStorage.h | 153 +- Minecraft.World/Level/Storage/ZoneFile.cpp | 129 +- Minecraft.World/Level/Storage/ZoneFile.h | 13 +- Minecraft.World/Level/Storage/ZoneIO.cpp | 57 +- Minecraft.World/Level/Storage/ZoneIO.h | 11 +- .../Level/Storage/ZonedChunkStorage.cpp | 236 +- .../Level/Storage/ZonedChunkStorage.h | 41 +- Minecraft.World/Level/TickNextTickData.cpp | 93 +- Minecraft.World/Level/TickNextTickData.h | 54 +- Minecraft.World/Level/TileEventData.cpp | 52 +- Minecraft.World/Level/TileEventData.h | 27 +- Minecraft.World/Level/TilePos.cpp | 28 +- Minecraft.World/Level/TilePos.h | 26 +- Minecraft.World/Level/WaterLevelChunk.cpp | 193 +- Minecraft.World/Level/WaterLevelChunk.h | 82 +- Minecraft.World/Network/Connection.cpp | 974 ++- Minecraft.World/Network/Connection.h | 147 +- .../Network/Packets/AddEntityPacket.cpp | 165 +- .../Network/Packets/AddEntityPacket.h | 58 +- .../Packets/AddExperienceOrbPacket.cpp | 61 +- .../Network/Packets/AddExperienceOrbPacket.h | 29 +- .../Network/Packets/AddGlobalEntityPacket.cpp | 67 +- .../Network/Packets/AddGlobalEntityPacket.h | 25 +- .../Network/Packets/AddMobPacket.cpp | 214 +- .../Network/Packets/AddMobPacket.h | 43 +- .../Network/Packets/AddPaintingPacket.cpp | 70 +- .../Network/Packets/AddPaintingPacket.h | 27 +- .../Network/Packets/AddPlayerPacket.cpp | 215 +- .../Network/Packets/AddPlayerPacket.h | 53 +- .../Network/Packets/AnimatePacket.cpp | 38 +- .../Network/Packets/AnimatePacket.h | 43 +- .../Network/Packets/AwardStatPacket.cpp | 105 +- .../Network/Packets/AwardStatPacket.h | 41 +- .../Packets/BlockRegionUpdatePacket.cpp | 242 +- .../Network/Packets/BlockRegionUpdatePacket.h | 33 +- .../Network/Packets/ChatAutoCompletePacket.h | 3 +- .../Network/Packets/ChatPacket.cpp | 108 +- Minecraft.World/Network/Packets/ChatPacket.h | 177 +- .../Packets/ChunkTilesUpdatePacket.cpp | 262 +- .../Network/Packets/ChunkTilesUpdatePacket.h | 34 +- .../Packets/ChunkVisibilityAreaPacket.cpp | 58 +- .../Packets/ChunkVisibilityAreaPacket.h | 31 +- .../Network/Packets/ChunkVisibilityPacket.cpp | 50 +- .../Network/Packets/ChunkVisibilityPacket.h | 28 +- .../Network/Packets/ClientCommandPacket.cpp | 35 +- .../Network/Packets/ClientCommandPacket.h | 29 +- .../Network/Packets/ClientInformationPacket.h | 3 +- .../Network/Packets/ClientProtocolPacket.h | 3 +- .../Network/Packets/ComplexItemDataPacket.cpp | 65 +- .../Network/Packets/ComplexItemDataPacket.h | 30 +- .../Network/Packets/ContainerAckPacket.cpp | 47 +- .../Network/Packets/ContainerAckPacket.h | 28 +- .../Packets/ContainerButtonClickPacket.cpp | 38 +- .../Packets/ContainerButtonClickPacket.h | 27 +- .../Network/Packets/ContainerClickPacket.cpp | 82 +- .../Network/Packets/ContainerClickPacket.h | 32 +- .../Network/Packets/ContainerClosePacket.cpp | 30 +- .../Network/Packets/ContainerClosePacket.h | 28 +- .../Network/Packets/ContainerOpenPacket.cpp | 54 +- .../Network/Packets/ContainerOpenPacket.h | 52 +- .../Packets/ContainerSetContentPacket.cpp | 69 +- .../Packets/ContainerSetContentPacket.h | 31 +- .../Packets/ContainerSetDataPacket.cpp | 47 +- .../Network/Packets/ContainerSetDataPacket.h | 26 +- .../Packets/ContainerSetSlotPacket.cpp | 54 +- .../Network/Packets/ContainerSetSlotPacket.h | 29 +- .../Network/Packets/CraftItemPacket.cpp | 42 +- .../Network/Packets/CraftItemPacket.h | 30 +- .../Network/Packets/CustomPayloadPacket.cpp | 81 +- .../Network/Packets/CustomPayloadPacket.h | 49 +- .../Network/Packets/DebugOptionsPacket.cpp | 34 +- .../Network/Packets/DebugOptionsPacket.h | 29 +- .../Network/Packets/DisconnectPacket.cpp | 44 +- .../Network/Packets/DisconnectPacket.h | 100 +- .../Packets/EntityActionAtPositionPacket.cpp | 65 +- .../Packets/EntityActionAtPositionPacket.h | 29 +- .../Network/Packets/EntityEventPacket.cpp | 38 +- .../Network/Packets/EntityEventPacket.h | 28 +- .../Network/Packets/ExplodePacket.cpp | 188 +- .../Network/Packets/ExplodePacket.h | 57 +- .../Network/Packets/GameCommandPacket.cpp | 89 +- .../Network/Packets/GameCommandPacket.h | 32 +- .../Network/Packets/GameEventPacket.cpp | 44 +- .../Network/Packets/GameEventPacket.h | 75 +- .../Network/Packets/GetInfoPacket.cpp | 22 +- .../Network/Packets/GetInfoPacket.h | 18 +- .../Network/Packets/InteractPacket.cpp | 46 +- .../Network/Packets/InteractPacket.h | 25 +- .../Network/Packets/KeepAlivePacket.cpp | 49 +- .../Network/Packets/KeepAlivePacket.h | 31 +- .../Network/Packets/KickPlayerPacket.cpp | 30 +- .../Network/Packets/KickPlayerPacket.h | 24 +- .../Network/Packets/LevelEventPacket.cpp | 63 +- .../Network/Packets/LevelEventPacket.h | 25 +- .../Network/Packets/LevelSoundPacket.cpp | 126 +- .../Network/Packets/LevelSoundPacket.h | 53 +- .../Network/Packets/LoginPacket.cpp | 289 +- Minecraft.World/Network/Packets/LoginPacket.h | 76 +- .../Network/Packets/MoveEntityPacket.cpp | 220 +- .../Network/Packets/MoveEntityPacket.h | 100 +- .../Network/Packets/MoveEntityPacketSmall.cpp | 267 +- .../Network/Packets/MoveEntityPacketSmall.h | 100 +- .../Network/Packets/MovePlayerPacket.cpp | 258 +- .../Network/Packets/MovePlayerPacket.h | 105 +- Minecraft.World/Network/Packets/Packet.cpp | 969 +-- Minecraft.World/Network/Packets/Packet.h | 168 +- .../Network/Packets/PacketListener.cpp | 508 +- .../Network/Packets/PacketListener.h | 244 +- .../Network/Packets/PlayerAbilitiesPacket.cpp | 170 +- .../Network/Packets/PlayerAbilitiesPacket.h | 75 +- .../Network/Packets/PlayerActionPacket.cpp | 61 +- .../Network/Packets/PlayerActionPacket.h | 32 +- .../Network/Packets/PlayerCommandPacket.cpp | 54 +- .../Network/Packets/PlayerCommandPacket.h | 49 +- .../Network/Packets/PlayerInfoPacket.cpp | 75 +- .../Network/Packets/PlayerInfoPacket.h | 45 +- .../Network/Packets/PlayerInputPacket.cpp | 102 +- .../Network/Packets/PlayerInputPacket.h | 40 +- .../Network/Packets/PreLoginPacket.cpp | 169 +- .../Network/Packets/PreLoginPacket.h | 65 +- .../Network/Packets/RemoveEntitiesPacket.cpp | 57 +- .../Network/Packets/RemoveEntitiesPacket.h | 31 +- .../Network/Packets/RemoveMobEffectPacket.cpp | 38 +- .../Network/Packets/RemoveMobEffectPacket.h | 34 +- .../Network/Packets/RespawnPacket.cpp | 138 +- .../Network/Packets/RespawnPacket.h | 44 +- .../Network/Packets/RotateHeadPacket.cpp | 59 +- .../Network/Packets/RotateHeadPacket.h | 32 +- .../Network/Packets/ServerAuthDataPacket.h | 3 +- .../Packets/ServerSettingsChangedPacket.cpp | 56 +- .../Packets/ServerSettingsChangedPacket.h | 37 +- .../Network/Packets/SetCarriedItemPacket.cpp | 40 +- .../Network/Packets/SetCarriedItemPacket.h | 30 +- .../Packets/SetCreativeModeSlotPacket.cpp | 45 +- .../Packets/SetCreativeModeSlotPacket.h | 30 +- .../Network/Packets/SetEntityDataPacket.cpp | 68 +- .../Network/Packets/SetEntityDataPacket.h | 36 +- .../Network/Packets/SetEntityMotionPacket.cpp | 156 +- .../Network/Packets/SetEntityMotionPacket.h | 34 +- .../Network/Packets/SetEquippedItemPacket.cpp | 81 +- .../Network/Packets/SetEquippedItemPacket.h | 43 +- .../Network/Packets/SetExperiencePacket.cpp | 69 +- .../Network/Packets/SetExperiencePacket.h | 36 +- .../Network/Packets/SetHealthPacket.cpp | 70 +- .../Network/Packets/SetHealthPacket.h | 39 +- .../Network/Packets/SetRidingPacket.cpp | 54 +- .../Network/Packets/SetRidingPacket.h | 29 +- .../Packets/SetSpawnPositionPacket.cpp | 65 +- .../Network/Packets/SetSpawnPositionPacket.h | 32 +- .../Network/Packets/SetTimePacket.cpp | 49 +- .../Network/Packets/SetTimePacket.h | 31 +- .../Network/Packets/SharedKeyPacket.h | 3 +- .../Network/Packets/SignUpdatePacket.cpp | 93 +- .../Network/Packets/SignUpdatePacket.h | 34 +- .../Network/Packets/TakeItemEntityPacket.cpp | 38 +- .../Network/Packets/TakeItemEntityPacket.h | 26 +- .../Network/Packets/TeleportEntityPacket.cpp | 111 +- .../Network/Packets/TeleportEntityPacket.h | 31 +- .../TextureAndGeometryChangePacket.cpp | 61 +- .../Packets/TextureAndGeometryChangePacket.h | 29 +- .../Packets/TextureAndGeometryPacket.cpp | 287 +- .../Packets/TextureAndGeometryPacket.h | 49 +- .../Network/Packets/TextureChangePacket.cpp | 48 +- .../Network/Packets/TextureChangePacket.h | 36 +- .../Network/Packets/TexturePacket.cpp | 77 +- .../Network/Packets/TexturePacket.h | 31 +- .../Network/Packets/TileDestructionPacket.cpp | 101 +- .../Network/Packets/TileDestructionPacket.h | 47 +- .../Network/Packets/TileEntityDataPacket.cpp | 80 +- .../Network/Packets/TileEntityDataPacket.h | 42 +- .../Network/Packets/TileEventPacket.cpp | 69 +- .../Network/Packets/TileEventPacket.h | 25 +- .../Network/Packets/TileUpdatePacket.cpp | 114 +- .../Network/Packets/TileUpdatePacket.h | 28 +- .../Network/Packets/TradeItemPacket.cpp | 38 +- .../Network/Packets/TradeItemPacket.h | 26 +- .../Packets/UpdateGameRuleProgressPacket.cpp | 103 +- .../Packets/UpdateGameRuleProgressPacket.h | 37 +- .../Network/Packets/UpdateMobEffectPacket.cpp | 70 +- .../Network/Packets/UpdateMobEffectPacket.h | 35 +- .../Network/Packets/UpdateProgressPacket.cpp | 30 +- .../Network/Packets/UpdateProgressPacket.h | 36 +- .../Network/Packets/UseItemPacket.cpp | 137 +- .../Network/Packets/UseItemPacket.h | 51 +- Minecraft.World/Network/Packets/XZPacket.cpp | 52 +- Minecraft.World/Network/Packets/XZPacket.h | 33 +- Minecraft.World/Network/Socket.cpp | 898 +-- Minecraft.World/Network/Socket.h | 228 +- Minecraft.World/Network/SocketAddress.h | 5 +- Minecraft.World/Platform/Minecraft.World.cpp | 92 +- Minecraft.World/Platform/System.cpp | 304 +- Minecraft.World/Platform/System.h | 58 +- Minecraft.World/Platform/stdafx.h | 40 +- .../Platform/x64headers/extraX64.h | 520 +- Minecraft.World/Player/Abilities.cpp | 95 +- Minecraft.World/Player/Abilities.h | 33 +- Minecraft.World/Player/FoodData.cpp | 211 +- Minecraft.World/Player/FoodData.h | 43 +- Minecraft.World/Player/Player.cpp | 4607 +++++------ Minecraft.World/Player/Player.h | 942 +-- .../Player/PlayerEnderChestContainer.cpp | 100 +- .../Player/PlayerEnderChestContainer.h | 19 +- Minecraft.World/Recipes/ArmorDyeRecipe.cpp | 295 +- Minecraft.World/Recipes/ArmorDyeRecipe.h | 29 +- Minecraft.World/Recipes/ArmorRecipes.cpp | 227 +- Minecraft.World/Recipes/ArmorRecipes.h | 44 +- Minecraft.World/Recipes/ClothDyeRecipes.cpp | 151 +- Minecraft.World/Recipes/ClothDyeRecipes.h | 6 +- Minecraft.World/Recipes/FoodRecipes.cpp | 172 +- Minecraft.World/Recipes/FoodRecipes.h | 5 +- Minecraft.World/Recipes/FurnaceRecipes.cpp | 127 +- Minecraft.World/Recipes/FurnaceRecipes.h | 36 +- Minecraft.World/Recipes/OreRecipes.cpp | 89 +- Minecraft.World/Recipes/OreRecipes.h | 13 +- Minecraft.World/Recipes/Recipes.cpp | 2213 +++--- Minecraft.World/Recipes/Recipes.h | 134 +- Minecraft.World/Recipes/Recipy.h | 87 +- Minecraft.World/Recipes/ShapedRecipy.cpp | 363 +- Minecraft.World/Recipes/ShapedRecipy.h | 46 +- Minecraft.World/Recipes/ShapelessRecipy.cpp | 284 +- Minecraft.World/Recipes/ShapelessRecipy.h | 34 +- Minecraft.World/Recipes/StructureRecipes.cpp | 188 +- Minecraft.World/Recipes/StructureRecipes.h | 5 +- Minecraft.World/Recipes/ToolRecipes.cpp | 184 +- Minecraft.World/Recipes/ToolRecipes.h | 21 +- Minecraft.World/Recipes/WeaponRecipes.cpp | 147 +- Minecraft.World/Recipes/WeaponRecipes.h | 23 +- Minecraft.World/Stats/Achievement.cpp | 126 +- Minecraft.World/Stats/Achievement.h | 44 +- Minecraft.World/Stats/Achievements.cpp | 478 +- Minecraft.World/Stats/Achievements.h | 133 +- Minecraft.World/Stats/CommonStats.cpp | 422 +- Minecraft.World/Stats/CommonStats.h | 113 +- Minecraft.World/Stats/DurangoStats.cpp | 1852 ++--- Minecraft.World/Stats/DurangoStats.h | 449 +- Minecraft.World/Stats/GeneralStat.cpp | 13 +- Minecraft.World/Stats/GeneralStat.h | 10 +- Minecraft.World/Stats/GenericStats.cpp | 1251 ++- Minecraft.World/Stats/GenericStats.h | 600 +- Minecraft.World/Stats/ItemStat.cpp | 10 +- Minecraft.World/Stats/ItemStat.h | 8 +- Minecraft.World/Stats/Stat.cpp | 99 +- Minecraft.World/Stats/Stat.h | 56 +- Minecraft.World/Stats/StatFormatter.h | 6 +- Minecraft.World/Stats/Stats.cpp | 909 ++- Minecraft.World/Stats/Stats.h | 118 +- Minecraft.World/Util/AABB.cpp | 219 +- Minecraft.World/Util/AABB.h | 102 +- Minecraft.World/Util/ArrayWithLength.h | 148 +- Minecraft.World/Util/Arrays.h | 45 +- Minecraft.World/Util/BasicTypeContainers.cpp | 13 +- Minecraft.World/Util/BasicTypeContainers.h | 78 +- Minecraft.World/Util/BinaryHeap.cpp | 135 +- Minecraft.World/Util/BinaryHeap.h | 28 +- Minecraft.World/Util/BoundingBox.cpp | 165 +- Minecraft.World/Util/BoundingBox.h | 47 +- Minecraft.World/Util/C4JThread.cpp | 1635 ++-- Minecraft.World/Util/C4JThread.h | 273 +- Minecraft.World/Util/Class.cpp | 4 +- Minecraft.World/Util/Class.h | 271 +- Minecraft.World/Util/Color.cpp | 157 +- Minecraft.World/Util/Color.h | 16 +- Minecraft.World/Util/Coord.h | 9 +- Minecraft.World/Util/DamageSource.cpp | 266 +- Minecraft.World/Util/DamageSource.h | 123 +- Minecraft.World/Util/Definitions.h | 39 +- Minecraft.World/Util/DelayedRelease.cpp | 50 +- Minecraft.World/Util/DelayedRelease.h | 23 +- Minecraft.World/Util/DescFormatter.h | 6 +- Minecraft.World/Util/Difficulty.h | 3 +- Minecraft.World/Util/Direction.cpp | 64 +- Minecraft.World/Util/Direction.h | 15 +- Minecraft.World/Util/Distort.cpp | 6 +- Minecraft.World/Util/Distort.h | 9 +- Minecraft.World/Util/Emboss.cpp | 8 +- Minecraft.World/Util/Emboss.h | 7 +- Minecraft.World/Util/Exceptions.h | 27 +- Minecraft.World/Util/Facing.cpp | 20 +- Minecraft.World/Util/Facing.h | 11 +- Minecraft.World/Util/FlippedIcon.cpp | 104 +- Minecraft.World/Util/FlippedIcon.h | 42 +- Minecraft.World/Util/FoliageColor.cpp | 30 +- Minecraft.World/Util/FoliageColor.h | 23 +- Minecraft.World/Util/FoodConstants.cpp | 14 +- Minecraft.World/Util/FoodConstants.h | 3 +- Minecraft.World/Util/GrassColor.cpp | 8 +- Minecraft.World/Util/GrassColor.h | 17 +- Minecraft.World/Util/HashExtension.h | 26 +- Minecraft.World/Util/Hasher.cpp | 71 +- Minecraft.World/Util/Hasher.h | 10 +- Minecraft.World/Util/HitResult.cpp | 39 +- Minecraft.World/Util/HitResult.h | 22 +- Minecraft.World/Util/I18n.cpp | 20 +- Minecraft.World/Util/I18n.h | 8 +- Minecraft.World/Util/Icon.h | 49 +- Minecraft.World/Util/IconRegister.h | 10 +- Minecraft.World/Util/IntCache.cpp | 242 +- Minecraft.World/Util/IntCache.h | 40 +- Minecraft.World/Util/JavaIntHash.h | 97 +- Minecraft.World/Util/JavaMath.cpp | 123 +- Minecraft.World/Util/JavaMath.h | 21 +- Minecraft.World/Util/Language.cpp | 53 +- Minecraft.World/Util/Language.h | 12 +- Minecraft.World/Util/LightLayer.h | 17 +- Minecraft.World/Util/Mth.cpp | 186 +- Minecraft.World/Util/Mth.h | 41 +- Minecraft.World/Util/NumberFormatters.h | 51 +- Minecraft.World/Util/ParticleTypes.h | 105 +- Minecraft.World/Util/PerformanceTimer.cpp | 21 +- Minecraft.World/Util/PerformanceTimer.h | 11 +- Minecraft.World/Util/PortableFileIO.h | 280 +- Minecraft.World/Util/Pos.cpp | 331 +- Minecraft.World/Util/Pos.h | 99 +- Minecraft.World/Util/ProgressListener.h | 18 +- Minecraft.World/Util/Random.cpp | 111 +- Minecraft.World/Util/Random.h | 35 +- Minecraft.World/Util/Rarity.cpp | 13 +- Minecraft.World/Util/Rarity.h | 17 +- Minecraft.World/Util/Reference.h | 11 +- Minecraft.World/Util/Rotate.cpp | 8 +- Minecraft.World/Util/Rotate.h | 11 +- Minecraft.World/Util/Scale.cpp | 8 +- Minecraft.World/Util/Scale.h | 11 +- Minecraft.World/Util/SharedConstants.cpp | 50 +- Minecraft.World/Util/SharedConstants.h | 43 +- Minecraft.World/Util/SmoothFloat.cpp | 22 +- Minecraft.World/Util/SmoothFloat.h | 10 +- Minecraft.World/Util/SoundTypes.h | 472 +- Minecraft.World/Util/StringHelpers.cpp | 188 +- Minecraft.World/Util/StringHelpers.h | 44 +- Minecraft.World/Util/ThreadName.cpp | 43 +- Minecraft.World/Util/ThreadName.h | 2 +- Minecraft.World/Util/UseAnim.h | 13 +- Minecraft.World/Util/Vec3.cpp | 202 +- Minecraft.World/Util/Vec3.h | 81 +- Minecraft.World/Util/WaterColor.cpp | 6 +- Minecraft.World/Util/WaterColor.h | 21 +- Minecraft.World/Util/WeighedRandom.cpp | 66 +- Minecraft.World/Util/WeighedRandom.h | 40 +- Minecraft.World/Util/WeighedTreasure.cpp | 134 +- Minecraft.World/Util/WeighedTreasure.h | 26 +- .../WorldGen/Biomes/BeachBiome.cpp | 21 +- Minecraft.World/WorldGen/Biomes/BeachBiome.h | 5 +- Minecraft.World/WorldGen/Biomes/Biome.cpp | 602 +- Minecraft.World/WorldGen/Biomes/Biome.h | 181 +- .../WorldGen/Biomes/BiomeCache.cpp | 232 +- Minecraft.World/WorldGen/Biomes/BiomeCache.h | 72 +- .../WorldGen/Biomes/BiomeDecorator.cpp | 519 +- .../WorldGen/Biomes/BiomeDecorator.h | 114 +- .../WorldGen/Biomes/BiomeSource.cpp | 949 ++- Minecraft.World/WorldGen/Biomes/BiomeSource.h | 146 +- .../WorldGen/Biomes/DesertBiome.cpp | 41 +- Minecraft.World/WorldGen/Biomes/DesertBiome.h | 7 +- .../WorldGen/Biomes/ExtremeHillsBiome.cpp | 41 +- .../WorldGen/Biomes/ExtremeHillsBiome.h | 12 +- .../WorldGen/Biomes/FixedBiomeSource.cpp | 214 +- .../WorldGen/Biomes/FixedBiomeSource.h | 56 +- .../WorldGen/Biomes/ForestBiome.cpp | 34 +- Minecraft.World/WorldGen/Biomes/ForestBiome.h | 5 +- Minecraft.World/WorldGen/Biomes/HellBiome.cpp | 9 +- Minecraft.World/WorldGen/Biomes/HellBiome.h | 3 +- Minecraft.World/WorldGen/Biomes/IceBiome.cpp | 4 +- Minecraft.World/WorldGen/Biomes/IceBiome.h | 3 +- .../WorldGen/Biomes/JungleBiome.cpp | 85 +- Minecraft.World/WorldGen/Biomes/JungleBiome.h | 12 +- .../WorldGen/Biomes/MushroomIslandBiome.cpp | 12 +- .../WorldGen/Biomes/MushroomIslandBiome.h | 3 +- Minecraft.World/WorldGen/Biomes/OceanBiome.h | 16 +- .../WorldGen/Biomes/PlainsBiome.cpp | 9 +- Minecraft.World/WorldGen/Biomes/PlainsBiome.h | 8 +- .../WorldGen/Biomes/RainforestBiome.cpp | 10 +- .../WorldGen/Biomes/RainforestBiome.h | 7 +- Minecraft.World/WorldGen/Biomes/RiverBiome.h | 16 +- .../WorldGen/Biomes/SwampBiome.cpp | 34 +- Minecraft.World/WorldGen/Biomes/SwampBiome.h | 17 +- .../WorldGen/Biomes/TaigaBiome.cpp | 18 +- Minecraft.World/WorldGen/Biomes/TaigaBiome.h | 7 +- .../WorldGen/Biomes/TheEndBiome.cpp | 13 +- Minecraft.World/WorldGen/Biomes/TheEndBiome.h | 7 +- .../WorldGen/Features/BasicTreeFeature.cpp | 472 +- .../WorldGen/Features/BasicTreeFeature.h | 48 +- .../WorldGen/Features/BirchFeature.cpp | 79 +- .../WorldGen/Features/BirchFeature.h | 7 +- .../WorldGen/Features/BonusChestFeature.cpp | 116 +- .../WorldGen/Features/BonusChestFeature.h | 13 +- .../WorldGen/Features/CactusFeature.cpp | 15 +- .../WorldGen/Features/CactusFeature.h | 6 +- .../WorldGen/Features/CanyonFeature.cpp | 160 +- .../WorldGen/Features/CanyonFeature.h | 12 +- .../WorldGen/Features/CaveFeature.cpp | 86 +- .../WorldGen/Features/CaveFeature.h | 5 +- .../WorldGen/Features/ClayFeature.cpp | 22 +- .../WorldGen/Features/ClayFeature.h | 11 +- .../WorldGen/Features/DeadBushFeature.cpp | 21 +- .../WorldGen/Features/DeadBushFeature.h | 9 +- .../WorldGen/Features/DesertWellFeature.cpp | 145 +- .../WorldGen/Features/DesertWellFeature.h | 5 +- .../WorldGen/Features/DungeonFeature.cpp | 127 +- .../WorldGen/Features/DungeonFeature.h | 13 +- .../WorldGen/Features/EndPodiumFeature.cpp | 127 +- .../WorldGen/Features/EndPodiumFeature.h | 12 +- Minecraft.World/WorldGen/Features/Feature.cpp | 35 +- Minecraft.World/WorldGen/Features/Feature.h | 29 +- .../WorldGen/Features/FlowerFeature.cpp | 41 +- .../WorldGen/Features/FlowerFeature.h | 9 +- .../WorldGen/Features/GroundBushFeature.cpp | 66 +- .../WorldGen/Features/GroundBushFeature.h | 11 +- .../WorldGen/Features/HellFireFeature.cpp | 6 +- .../WorldGen/Features/HellFireFeature.h | 5 +- .../WorldGen/Features/HellPortalFeature.cpp | 10 +- .../WorldGen/Features/HellPortalFeature.h | 5 +- .../WorldGen/Features/HellSpringFeature.cpp | 21 +- .../WorldGen/Features/HellSpringFeature.h | 10 +- .../WorldGen/Features/HouseFeature.cpp | 123 +- .../WorldGen/Features/HouseFeature.h | 5 +- .../WorldGen/Features/HugeMushroomFeature.cpp | 80 +- .../WorldGen/Features/HugeMushroomFeature.h | 11 +- .../WorldGen/Features/LakeFeature.cpp | 201 +- .../WorldGen/Features/LakeFeature.h | 9 +- .../WorldGen/Features/LargeCaveFeature.cpp | 143 +- .../WorldGen/Features/LargeCaveFeature.h | 13 +- .../WorldGen/Features/LargeFeature.cpp | 28 +- .../WorldGen/Features/LargeFeature.h | 20 +- .../Features/LargeHellCaveFeature.cpp | 112 +- .../WorldGen/Features/LargeHellCaveFeature.h | 13 +- .../WorldGen/Features/LightGemFeature.cpp | 9 +- .../WorldGen/Features/LightGemFeature.h | 5 +- .../WorldGen/Features/MegaTreeFeature.cpp | 387 +- .../WorldGen/Features/MegaTreeFeature.h | 16 +- .../WorldGen/Features/MineShaftFeature.cpp | 27 +- .../WorldGen/Features/MineShaftFeature.h | 7 +- .../WorldGen/Features/MonsterRoomFeature.cpp | 236 +- .../WorldGen/Features/MonsterRoomFeature.h | 11 +- .../WorldGen/Features/NetherBridgeFeature.cpp | 150 +- .../WorldGen/Features/NetherBridgeFeature.h | 32 +- .../WorldGen/Features/NetherSphereFeature.cpp | 26 +- .../WorldGen/Features/NetherSphereFeature.h | 14 +- .../WorldGen/Features/OreFeature.cpp | 140 +- .../WorldGen/Features/OreFeature.h | 18 +- .../WorldGen/Features/PineFeature.cpp | 90 +- .../WorldGen/Features/PineFeature.h | 5 +- .../WorldGen/Features/PumpkinFeature.cpp | 16 +- .../WorldGen/Features/PumpkinFeature.h | 6 +- .../Features/RandomScatteredLargeFeature.cpp | 138 +- .../Features/RandomScatteredLargeFeature.h | 23 +- .../WorldGen/Features/ReedsFeature.cpp | 49 +- .../WorldGen/Features/ReedsFeature.h | 5 +- .../WorldGen/Features/SandFeature.cpp | 57 +- .../WorldGen/Features/SandFeature.h | 9 +- .../WorldGen/Features/SpikeFeature.cpp | 232 +- .../WorldGen/Features/SpikeFeature.h | 14 +- .../WorldGen/Features/SpringFeature.cpp | 38 +- .../WorldGen/Features/SpringFeature.h | 10 +- .../WorldGen/Features/SpruceFeature.cpp | 97 +- .../WorldGen/Features/SpruceFeature.h | 7 +- .../WorldGen/Features/StrongholdFeature.cpp | 307 +- .../WorldGen/Features/StrongholdFeature.h | 32 +- .../WorldGen/Features/StructureFeature.cpp | 281 +- .../WorldGen/Features/StructureFeature.h | 45 +- .../WorldGen/Features/SwampTreeFeature.cpp | 205 +- .../WorldGen/Features/SwampTreeFeature.h | 8 +- .../WorldGen/Features/TallGrassFeature.cpp | 23 +- .../WorldGen/Features/TallGrassFeature.h | 11 +- .../WorldGen/Features/TownFeature.h | 4 +- .../WorldGen/Features/TreeFeature.cpp | 347 +- .../WorldGen/Features/TreeFeature.h | 20 +- .../WorldGen/Features/VillageFeature.cpp | 153 +- .../WorldGen/Features/VillageFeature.h | 31 +- .../WorldGen/Features/VinesFeature.cpp | 51 +- .../WorldGen/Features/VinesFeature.h | 8 +- .../WorldGen/Features/WaterlilyFeature.cpp | 13 +- .../WorldGen/Features/WaterlilyFeature.h | 5 +- .../WorldGen/Layers/AddIslandLayer.cpp | 102 +- .../WorldGen/Layers/AddIslandLayer.h | 7 +- .../Layers/AddMushroomIslandLayer.cpp | 25 +- .../WorldGen/Layers/AddMushroomIslandLayer.h | 3 +- .../WorldGen/Layers/AddSnowLayer.cpp | 28 +- .../WorldGen/Layers/AddSnowLayer.h | 3 +- .../WorldGen/Layers/BiomeInitLayer.cpp | 106 +- .../WorldGen/Layers/BiomeInitLayer.h | 10 +- .../WorldGen/Layers/BiomeOverrideLayer.cpp | 81 +- .../WorldGen/Layers/BiomeOverrideLayer.h | 13 +- .../WorldGen/Layers/DownfallLayer.cpp | 21 +- .../WorldGen/Layers/DownfallLayer.h | 7 +- .../WorldGen/Layers/DownfallMixerLayer.cpp | 30 +- .../WorldGen/Layers/DownfallMixerLayer.h | 12 +- Minecraft.World/WorldGen/Layers/FlatLayer.cpp | 24 +- Minecraft.World/WorldGen/Layers/FlatLayer.h | 9 +- .../WorldGen/Layers/FuzzyZoomLayer.cpp | 111 +- .../WorldGen/Layers/FuzzyZoomLayer.h | 10 +- .../Layers/GrowMushroomIslandLayer.cpp | 35 +- .../WorldGen/Layers/GrowMushroomIslandLayer.h | 3 +- .../WorldGen/Layers/IslandLayer.cpp | 34 +- Minecraft.World/WorldGen/Layers/IslandLayer.h | 7 +- Minecraft.World/WorldGen/Layers/Layer.cpp | 312 +- Minecraft.World/WorldGen/Layers/Layer.h | 25 +- .../WorldGen/Layers/RegionHillsLayer.cpp | 112 +- .../WorldGen/Layers/RegionHillsLayer.h | 7 +- .../WorldGen/Layers/RiverInitLayer.cpp | 29 +- .../WorldGen/Layers/RiverInitLayer.h | 7 +- .../WorldGen/Layers/RiverLayer.cpp | 57 +- Minecraft.World/WorldGen/Layers/RiverLayer.h | 7 +- .../WorldGen/Layers/RiverMixerLayer.cpp | 71 +- .../WorldGen/Layers/RiverMixerLayer.h | 14 +- .../WorldGen/Layers/ShoreLayer.cpp | 86 +- Minecraft.World/WorldGen/Layers/ShoreLayer.h | 3 +- .../WorldGen/Layers/SmoothLayer.cpp | 67 +- Minecraft.World/WorldGen/Layers/SmoothLayer.h | 7 +- .../WorldGen/Layers/SmoothZoomLayer.cpp | 92 +- .../WorldGen/Layers/SmoothZoomLayer.h | 10 +- .../WorldGen/Layers/SwampRiversLayer.cpp | 44 +- .../WorldGen/Layers/SwampRiversLayer.h | 7 +- .../WorldGen/Layers/TemperatureLayer.cpp | 21 +- .../WorldGen/Layers/TemperatureLayer.h | 7 +- .../WorldGen/Layers/TemperatureMixerLayer.cpp | 30 +- .../WorldGen/Layers/TemperatureMixerLayer.h | 12 +- .../WorldGen/Layers/VoronoiZoom.cpp | 208 +- Minecraft.World/WorldGen/Layers/VoronoiZoom.h | 11 +- Minecraft.World/WorldGen/Layers/ZoomLayer.cpp | 152 +- Minecraft.World/WorldGen/Layers/ZoomLayer.h | 14 +- Minecraft.World/WorldGen/Noise/FastNoise.cpp | 87 +- Minecraft.World/WorldGen/Noise/FastNoise.h | 15 +- .../WorldGen/Noise/ImprovedNoise.cpp | 202 +- .../WorldGen/Noise/ImprovedNoise.h | 17 +- .../WorldGen/Noise/PerlinNoise.cpp | 78 +- Minecraft.World/WorldGen/Noise/PerlinNoise.h | 20 +- .../WorldGen/Noise/PerlinSimplexNoise.cpp | 112 +- .../WorldGen/Noise/PerlinSimplexNoise.h | 23 +- .../WorldGen/Noise/SimplexNoise.cpp | 332 +- Minecraft.World/WorldGen/Noise/SimplexNoise.h | 24 +- Minecraft.World/WorldGen/Noise/Synth.cpp | 9 +- Minecraft.World/WorldGen/Noise/Synth.h | 6 +- .../WorldGen/Sources/FlatLevelSource.cpp | 213 +- .../WorldGen/Sources/FlatLevelSource.h | 52 +- .../WorldGen/Sources/HellFlatLevelSource.cpp | 282 +- .../WorldGen/Sources/HellFlatLevelSource.h | 34 +- .../Sources/HellRandomLevelSource.cpp | 563 +- .../WorldGen/Sources/HellRandomLevelSource.h | 55 +- .../Sources/TheEndLevelRandomLevelSource.cpp | 413 +- .../Sources/TheEndLevelRandomLevelSource.h | 72 +- .../WorldGen/Structures/MineShaftPieces.cpp | 1335 ++-- .../WorldGen/Structures/MineShaftPieces.h | 164 +- .../WorldGen/Structures/MineShaftStart.cpp | 19 +- .../WorldGen/Structures/MineShaftStart.h | 5 +- .../Structures/NetherBridgePieces.cpp | 3162 ++++---- .../WorldGen/Structures/NetherBridgePieces.h | 530 +- .../Structures/ScatteredFeaturePieces.cpp | 1126 +-- .../Structures/ScatteredFeaturePieces.h | 90 +- .../WorldGen/Structures/StrongholdPieces.cpp | 2102 ++--- .../WorldGen/Structures/StrongholdPieces.h | 588 +- .../WorldGen/Structures/StructurePiece.cpp | 1318 ++- .../WorldGen/Structures/StructurePiece.h | 128 +- .../WorldGen/Structures/StructureStart.cpp | 103 +- .../WorldGen/Structures/StructureStart.h | 33 +- .../Structures/TheEndBiomeDecorator.cpp | 86 +- .../Structures/TheEndBiomeDecorator.h | 33 +- .../WorldGen/Structures/Village.cpp | 810 +- Minecraft.World/WorldGen/Structures/Village.h | 120 +- .../WorldGen/Structures/VillagePieces.cpp | 3224 ++++---- .../WorldGen/Structures/VillagePieces.h | 596 +- .../WorldGen/Structures/Villages.cpp | 375 +- .../WorldGen/Structures/Villages.h | 54 +- 1511 files changed, 108661 insertions(+), 115521 deletions(-) diff --git a/Minecraft.World/AI/Control/BodyControl.cpp b/Minecraft.World/AI/Control/BodyControl.cpp index baf7b9e5e..cfdec453f 100644 --- a/Minecraft.World/AI/Control/BodyControl.cpp +++ b/Minecraft.World/AI/Control/BodyControl.cpp @@ -5,50 +5,46 @@ const float BodyControl::maxClampAngle = 75.0f; -BodyControl::BodyControl(Mob *mob) -{ - this->mob = mob; +BodyControl::BodyControl(Mob* mob) { + this->mob = mob; - timeStill = 0; - lastHeadY = 0.0f; + timeStill = 0; + lastHeadY = 0.0f; } -void BodyControl::clientTick() -{ - double xd = mob->x - mob->xo; - double zd = mob->z - mob->zo; +void BodyControl::clientTick() { + double xd = mob->x - mob->xo; + double zd = mob->z - mob->zo; - if (xd * xd + zd * zd > MoveControl::MIN_SPEED_SQR) - { - // we are moving. - mob->yBodyRot = mob->yRot; - mob->yHeadRot = clamp(mob->yBodyRot, mob->yHeadRot, maxClampAngle); - lastHeadY = mob->yHeadRot; - timeStill = 0; - return; - } + if (xd * xd + zd * zd > MoveControl::MIN_SPEED_SQR) { + // we are moving. + mob->yBodyRot = mob->yRot; + mob->yHeadRot = clamp(mob->yBodyRot, mob->yHeadRot, maxClampAngle); + lastHeadY = mob->yHeadRot; + timeStill = 0; + return; + } - // Body will align to head after looking long enough in a direction - float clampAngle = maxClampAngle; - if (abs(mob->yHeadRot - lastHeadY) > 15) - { - timeStill = 0; - lastHeadY = mob->yHeadRot; - } - else - { - ++timeStill; - static const int timeStillBeforeTurn = 10; - if (timeStill > timeStillBeforeTurn) clampAngle = std::max(1 - (timeStill - timeStillBeforeTurn) / 10.f, 0.0f) * maxClampAngle; - } + // Body will align to head after looking long enough in a direction + float clampAngle = maxClampAngle; + if (abs(mob->yHeadRot - lastHeadY) > 15) { + timeStill = 0; + lastHeadY = mob->yHeadRot; + } else { + ++timeStill; + static const int timeStillBeforeTurn = 10; + if (timeStill > timeStillBeforeTurn) + clampAngle = + std::max(1 - (timeStill - timeStillBeforeTurn) / 10.f, 0.0f) * + maxClampAngle; + } - mob->yBodyRot = clamp(mob->yHeadRot, mob->yBodyRot, clampAngle); + mob->yBodyRot = clamp(mob->yHeadRot, mob->yBodyRot, clampAngle); } -float BodyControl::clamp(float clampTo, float clampFrom, float clampAngle) -{ - float headDiffBody = Mth::wrapDegrees(clampTo - clampFrom); - if (headDiffBody < -clampAngle) headDiffBody = -clampAngle; - if (headDiffBody >= clampAngle) headDiffBody = +clampAngle; - return clampTo - headDiffBody; +float BodyControl::clamp(float clampTo, float clampFrom, float clampAngle) { + float headDiffBody = Mth::wrapDegrees(clampTo - clampFrom); + if (headDiffBody < -clampAngle) headDiffBody = -clampAngle; + if (headDiffBody >= clampAngle) headDiffBody = +clampAngle; + return clampTo - headDiffBody; } \ No newline at end of file diff --git a/Minecraft.World/AI/Control/BodyControl.h b/Minecraft.World/AI/Control/BodyControl.h index 951b21972..b9e92dd12 100644 --- a/Minecraft.World/AI/Control/BodyControl.h +++ b/Minecraft.World/AI/Control/BodyControl.h @@ -2,19 +2,18 @@ #include "Control.h" -class BodyControl : public Control -{ +class BodyControl : public Control { private: - Mob *mob; - static const float maxClampAngle; - int timeStill; - float lastHeadY; + Mob* mob; + static const float maxClampAngle; + int timeStill; + float lastHeadY; public: - BodyControl(Mob *mob); + BodyControl(Mob* mob); - void clientTick(); + void clientTick(); private: - float clamp(float clampTo, float clampFrom, float clampAngle); + float clamp(float clampTo, float clampFrom, float clampAngle); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Control/Control.h b/Minecraft.World/AI/Control/Control.h index 1c12a98fd..970e2c36f 100644 --- a/Minecraft.World/AI/Control/Control.h +++ b/Minecraft.World/AI/Control/Control.h @@ -1,9 +1,8 @@ #pragma once -class Control -{ +class Control { public: - static const int MoveControlFlag = 1; - static const int LookControlFlag = 2; - static const int JumpControlFlag = 4; + static const int MoveControlFlag = 1; + static const int LookControlFlag = 2; + static const int JumpControlFlag = 4; }; \ No newline at end of file diff --git a/Minecraft.World/AI/Control/JumpControl.cpp b/Minecraft.World/AI/Control/JumpControl.cpp index 5911e295c..6cf8d3cc5 100644 --- a/Minecraft.World/AI/Control/JumpControl.cpp +++ b/Minecraft.World/AI/Control/JumpControl.cpp @@ -2,20 +2,15 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "JumpControl.h" -JumpControl::JumpControl(Mob *mob) -{ - _jump = false; +JumpControl::JumpControl(Mob* mob) { + _jump = false; - this->mob = mob; + this->mob = mob; } -void JumpControl::jump() -{ - _jump = true; -} +void JumpControl::jump() { _jump = true; } -void JumpControl::tick() -{ - mob->setJumping(_jump); - _jump = false; +void JumpControl::tick() { + mob->setJumping(_jump); + _jump = false; } \ No newline at end of file diff --git a/Minecraft.World/AI/Control/JumpControl.h b/Minecraft.World/AI/Control/JumpControl.h index 4ff9cfce7..00690aa60 100644 --- a/Minecraft.World/AI/Control/JumpControl.h +++ b/Minecraft.World/AI/Control/JumpControl.h @@ -4,17 +4,16 @@ class Mob; -class JumpControl : public Control -{ +class JumpControl : public Control { private: - Mob *mob; - bool _jump; + Mob* mob; + bool _jump; public: - JumpControl(Mob *mob); - virtual ~JumpControl(){} + JumpControl(Mob* mob); + virtual ~JumpControl() {} - void jump(); - //genuinly, why tf is this VIRTUAL - virtual void tick(); + void jump(); + // genuinly, why tf is this VIRTUAL + virtual void tick(); }; diff --git a/Minecraft.World/AI/Control/LookControl.cpp b/Minecraft.World/AI/Control/LookControl.cpp index c7f11effe..e4c4e55b9 100644 --- a/Minecraft.World/AI/Control/LookControl.cpp +++ b/Minecraft.World/AI/Control/LookControl.cpp @@ -4,114 +4,87 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "LookControl.h" -LookControl::LookControl(Mob *mob) -{ - yMax = xMax = 0.0f; - hasWanted = false; - wantedX = wantedY = wantedZ = 0.0; +LookControl::LookControl(Mob* mob) { + yMax = xMax = 0.0f; + hasWanted = false; + wantedX = wantedY = wantedZ = 0.0; - this->mob = mob; + this->mob = mob; } -void LookControl::setLookAt(std::shared_ptr target, float yMax, float xMax) -{ - this->wantedX = target->x; - std::shared_ptr targetMob = std::dynamic_pointer_cast(target); - if (targetMob != NULL) this->wantedY = target->y + targetMob->getHeadHeight(); - else this->wantedY = (target->bb->y0 + target->bb->y1) / 2; - this->wantedZ = target->z; - this->yMax = yMax; - this->xMax = xMax; - hasWanted = true; +void LookControl::setLookAt(std::shared_ptr target, float yMax, + float xMax) { + this->wantedX = target->x; + std::shared_ptr targetMob = std::dynamic_pointer_cast(target); + if (targetMob != NULL) + this->wantedY = target->y + targetMob->getHeadHeight(); + else + this->wantedY = (target->bb->y0 + target->bb->y1) / 2; + this->wantedZ = target->z; + this->yMax = yMax; + this->xMax = xMax; + hasWanted = true; } -void LookControl::setLookAt(double x, double y, double z, float yMax, float xMax) -{ - this->wantedX = x; - this->wantedY = y; - this->wantedZ = z; - this->yMax = yMax; - this->xMax = xMax; - hasWanted = true; +void LookControl::setLookAt(double x, double y, double z, float yMax, + float xMax) { + this->wantedX = x; + this->wantedY = y; + this->wantedZ = z; + this->yMax = yMax; + this->xMax = xMax; + hasWanted = true; } -void LookControl::tick() -{ - mob->xRot = 0; +void LookControl::tick() { + mob->xRot = 0; - if (hasWanted) - { - hasWanted = false; + if (hasWanted) { + hasWanted = false; - double xd = wantedX - mob->x; - double yd = wantedY - (mob->y + mob->getHeadHeight()); - double zd = wantedZ - mob->z; - double sd = sqrt(xd * xd + zd * zd); + double xd = wantedX - mob->x; + double yd = wantedY - (mob->y + mob->getHeadHeight()); + double zd = wantedZ - mob->z; + double sd = sqrt(xd * xd + zd * zd); - float yRotD = (float) (atan2(zd, xd) * 180 / PI) - 90; - float xRotD = (float) -(atan2(yd, sd) * 180 / PI); - mob->xRot = rotlerp(mob->xRot, xRotD, xMax); - mob->yHeadRot = rotlerp(mob->yHeadRot, yRotD, yMax); - } - else - { - mob->yHeadRot = rotlerp(mob->yHeadRot, mob->yBodyRot, 10); - } + float yRotD = (float)(atan2(zd, xd) * 180 / PI) - 90; + float xRotD = (float)-(atan2(yd, sd) * 180 / PI); + mob->xRot = rotlerp(mob->xRot, xRotD, xMax); + mob->yHeadRot = rotlerp(mob->yHeadRot, yRotD, yMax); + } else { + mob->yHeadRot = rotlerp(mob->yHeadRot, mob->yBodyRot, 10); + } - float headDiffBody = Mth::wrapDegrees(mob->yHeadRot - mob->yBodyRot); + float headDiffBody = Mth::wrapDegrees(mob->yHeadRot - mob->yBodyRot); - if (!mob->getNavigation()->isDone()) - { - // head clamped to body - if (headDiffBody < -75) mob->yHeadRot = mob->yBodyRot - 75; - if (headDiffBody > 75) mob->yHeadRot = mob->yBodyRot + 75; - } + if (!mob->getNavigation()->isDone()) { + // head clamped to body + if (headDiffBody < -75) mob->yHeadRot = mob->yBodyRot - 75; + if (headDiffBody > 75) mob->yHeadRot = mob->yBodyRot + 75; + } } -float LookControl::rotlerp(float a, float b, float max) -{ - float diff = b - a; - while (diff < -180) - diff += 360; - while (diff >= 180) - diff -= 360; - if (diff > max) - { - diff = max; - } - if (diff < -max) - { - diff = -max; - } - return a + diff; +float LookControl::rotlerp(float a, float b, float max) { + float diff = b - a; + while (diff < -180) diff += 360; + while (diff >= 180) diff -= 360; + if (diff > max) { + diff = max; + } + if (diff < -max) { + diff = -max; + } + return a + diff; } -bool LookControl::isHasWanted() -{ - return hasWanted; -} +bool LookControl::isHasWanted() { return hasWanted; } -float LookControl::getYMax() -{ - return yMax; -} +float LookControl::getYMax() { return yMax; } -float LookControl::getXMax() -{ - return xMax; -} +float LookControl::getXMax() { return xMax; } -double LookControl::getWantedX() -{ - return wantedX; -} +double LookControl::getWantedX() { return wantedX; } -double LookControl::getWantedY() -{ - return wantedY; -} +double LookControl::getWantedY() { return wantedY; } -double LookControl::getWantedZ() -{ - return wantedZ; -} \ No newline at end of file +double LookControl::getWantedZ() { return wantedZ; } \ No newline at end of file diff --git a/Minecraft.World/AI/Control/LookControl.h b/Minecraft.World/AI/Control/LookControl.h index 3f9dabb2e..949a647d6 100644 --- a/Minecraft.World/AI/Control/LookControl.h +++ b/Minecraft.World/AI/Control/LookControl.h @@ -4,31 +4,30 @@ class Mob; -class LookControl : public Control -{ +class LookControl : public Control { private: - Mob *mob; - float yMax, xMax; - bool hasWanted; + Mob* mob; + float yMax, xMax; + bool hasWanted; - double wantedX, wantedY, wantedZ; + double wantedX, wantedY, wantedZ; public: - LookControl(Mob *mob); - virtual ~LookControl(){} + LookControl(Mob* mob); + virtual ~LookControl() {} - void setLookAt(std::shared_ptr target, float yMax, float xMax); - void setLookAt(double x, double y, double z, float yMax, float xMax); - virtual void tick(); + void setLookAt(std::shared_ptr target, float yMax, float xMax); + void setLookAt(double x, double y, double z, float yMax, float xMax); + virtual void tick(); private: - float rotlerp(float a, float b, float max); + float rotlerp(float a, float b, float max); public: - bool isHasWanted(); - float getYMax(); - float getXMax(); - double getWantedX(); - double getWantedY(); - double getWantedZ(); + bool isHasWanted(); + float getYMax(); + float getXMax(); + double getWantedX(); + double getWantedY(); + double getWantedZ(); }; diff --git a/Minecraft.World/AI/Control/MoveControl.cpp b/Minecraft.World/AI/Control/MoveControl.cpp index 56902bf32..363d19eb0 100644 --- a/Minecraft.World/AI/Control/MoveControl.cpp +++ b/Minecraft.World/AI/Control/MoveControl.cpp @@ -7,69 +7,57 @@ const float MoveControl::MIN_SPEED = 0.0005f; const float MoveControl::MIN_SPEED_SQR = MIN_SPEED * MIN_SPEED; -MoveControl::MoveControl(Mob *mob) -{ - this->mob = mob; - wantedX = mob->x; - wantedY = mob->y; - wantedZ = mob->z; +MoveControl::MoveControl(Mob* mob) { + this->mob = mob; + wantedX = mob->x; + wantedY = mob->y; + wantedZ = mob->z; - speed = 0.0f; + speed = 0.0f; - _hasWanted = false; + _hasWanted = false; } -bool MoveControl::hasWanted() -{ - return _hasWanted; +bool MoveControl::hasWanted() { return _hasWanted; } + +float MoveControl::getSpeed() { return speed; } + +void MoveControl::setWantedPosition(double x, double y, double z, float speed) { + wantedX = x; + wantedY = y; + wantedZ = z; + this->speed = speed; + _hasWanted = true; } -float MoveControl::getSpeed() -{ - return speed; +void MoveControl::tick() { + mob->setYya(0); + if (!_hasWanted) return; + _hasWanted = false; + + int yFloor = floor(mob->bb->y0 + .5f); + + double xd = wantedX - mob->x; + double zd = wantedZ - mob->z; + double yd = wantedY - yFloor; + double dd = xd * xd + yd * yd + zd * zd; + if (dd < MIN_SPEED_SQR) return; + + float yRotD = (float)(atan2(zd, xd) * 180 / PI) - 90; + + mob->yRot = rotlerp(mob->yRot, yRotD, MAX_TURN); + mob->setSpeed(speed * mob->getWalkingSpeedModifier()); + + if (yd > 0 && xd * xd + zd * zd < 1) mob->getJumpControl()->jump(); } -void MoveControl::setWantedPosition(double x, double y, double z, float speed) -{ - wantedX = x; - wantedY = y; - wantedZ = z; - this->speed = speed; - _hasWanted = true; -} - -void MoveControl::tick() -{ - mob->setYya(0); - if (!_hasWanted) return; - _hasWanted = false; - - int yFloor = floor(mob->bb->y0 + .5f); - - double xd = wantedX - mob->x; - double zd = wantedZ - mob->z; - double yd = wantedY - yFloor; - double dd = xd * xd + yd * yd + zd * zd; - if (dd < MIN_SPEED_SQR) return; - - float yRotD = (float) (atan2(zd, xd) * 180 / PI) - 90; - - mob->yRot = rotlerp(mob->yRot, yRotD, MAX_TURN); - mob->setSpeed(speed * mob->getWalkingSpeedModifier()); - - if (yd > 0 && xd * xd + zd * zd < 1) mob->getJumpControl()->jump(); -} - -float MoveControl::rotlerp(float a, float b, float max) -{ - float diff = Mth::wrapDegrees(b - a); - if (diff > max) - { - diff = max; - } - if (diff < -max) - { - diff = -max; - } - return a + diff; +float MoveControl::rotlerp(float a, float b, float max) { + float diff = Mth::wrapDegrees(b - a); + if (diff > max) { + diff = max; + } + if (diff < -max) { + diff = -max; + } + return a + diff; } \ No newline at end of file diff --git a/Minecraft.World/AI/Control/MoveControl.h b/Minecraft.World/AI/Control/MoveControl.h index 89ac8162b..17e36ff45 100644 --- a/Minecraft.World/AI/Control/MoveControl.h +++ b/Minecraft.World/AI/Control/MoveControl.h @@ -4,32 +4,31 @@ class Mob; -class MoveControl : public Control -{ +class MoveControl : public Control { public: - static const float MIN_SPEED; - static const float MIN_SPEED_SQR; + static const float MIN_SPEED; + static const float MIN_SPEED_SQR; private: - static const int MAX_TURN = 30; + static const int MAX_TURN = 30; - Mob *mob; - double wantedX; - double wantedY; - double wantedZ; - float speed; - bool _hasWanted; + Mob* mob; + double wantedX; + double wantedY; + double wantedZ; + float speed; + bool _hasWanted; public: - MoveControl(Mob *mob); - virtual ~MoveControl(){} + MoveControl(Mob* mob); + virtual ~MoveControl() {} - bool hasWanted(); - float getSpeed(); - void setWantedPosition(double x, double y, double z, float speed); - void setSpeed(float speed); - virtual void tick(); + bool hasWanted(); + float getSpeed(); + void setWantedPosition(double x, double y, double z, float speed); + void setSpeed(float speed); + virtual void tick(); private: - float rotlerp(float a, float b, float max); + float rotlerp(float a, float b, float max); }; diff --git a/Minecraft.World/AI/Control/Sensing.cpp b/Minecraft.World/AI/Control/Sensing.cpp index 3ce942963..35963cb66 100644 --- a/Minecraft.World/AI/Control/Sensing.cpp +++ b/Minecraft.World/AI/Control/Sensing.cpp @@ -2,34 +2,30 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "Sensing.h" -Sensing::Sensing(Mob *mob) -{ - this->mob = mob; +Sensing::Sensing(Mob* mob) { this->mob = mob; } + +void Sensing::tick() { + seen.clear(); + unseen.clear(); } -void Sensing::tick() -{ - seen.clear(); - unseen.clear(); -} +bool Sensing::canSee(std::shared_ptr target) { + // if ( find(seen.begin(), seen.end(), target) != seen.end() ) return true; + // if ( find(unseen.begin(), unseen.end(), target) != unseen.end()) return + // false; + for (AUTO_VAR(it, seen.begin()); it != seen.end(); ++it) { + if (target == (*it).lock()) return true; + } + for (AUTO_VAR(it, unseen.begin()); it != unseen.end(); ++it) { + if (target == (*it).lock()) return false; + } -bool Sensing::canSee(std::shared_ptr target) -{ - //if ( find(seen.begin(), seen.end(), target) != seen.end() ) return true; - //if ( find(unseen.begin(), unseen.end(), target) != unseen.end()) return false; - for(AUTO_VAR(it, seen.begin()); it != seen.end(); ++it) - { - if(target == (*it).lock()) return true; - } - for(AUTO_VAR(it, unseen.begin()); it != unseen.end(); ++it) - { - if(target == (*it).lock()) return false; - } - - //util.Timer.push("canSee"); - bool canSee = mob->canSee(target); - //util.Timer.pop(); - if (canSee) seen.push_back(std::weak_ptr(target)); - else unseen.push_back(std::weak_ptr(target)); - return canSee; + // util.Timer.push("canSee"); + bool canSee = mob->canSee(target); + // util.Timer.pop(); + if (canSee) + seen.push_back(std::weak_ptr(target)); + else + unseen.push_back(std::weak_ptr(target)); + return canSee; } \ No newline at end of file diff --git a/Minecraft.World/AI/Control/Sensing.h b/Minecraft.World/AI/Control/Sensing.h index 7359325f8..50ad985d8 100644 --- a/Minecraft.World/AI/Control/Sensing.h +++ b/Minecraft.World/AI/Control/Sensing.h @@ -1,15 +1,14 @@ #pragma once -class Sensing -{ +class Sensing { private: - Mob *mob; - std::vector > seen; - std::vector > unseen; + Mob* mob; + std::vector > seen; + std::vector > unseen; public: - Sensing(Mob *mob); + Sensing(Mob* mob); - void tick(); - bool canSee(std::shared_ptr target); + void tick(); + bool canSee(std::shared_ptr target); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/ArrowAttackGoal.cpp b/Minecraft.World/AI/Goals/ArrowAttackGoal.cpp index 6ceecb8ce..d7e2e1ecb 100644 --- a/Minecraft.World/AI/Goals/ArrowAttackGoal.cpp +++ b/Minecraft.World/AI/Goals/ArrowAttackGoal.cpp @@ -9,83 +9,82 @@ #include "../../Util/SoundTypes.h" #include "ArrowAttackGoal.h" -ArrowAttackGoal::ArrowAttackGoal(Mob *mob, float speed, int projectileType, int attackInterval) -{ - // 4J Init - target = std::weak_ptr(); - attackTime = 0; - seeTime = 0; +ArrowAttackGoal::ArrowAttackGoal(Mob* mob, float speed, int projectileType, + int attackInterval) { + // 4J Init + target = std::weak_ptr(); + attackTime = 0; + seeTime = 0; - this->mob = mob; - this->level = mob->level; - this->speed = speed; - this->projectileType = projectileType; - this->attackInterval = attackInterval; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->mob = mob; + this->level = mob->level; + this->speed = speed; + this->projectileType = projectileType; + this->attackInterval = attackInterval; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool ArrowAttackGoal::canUse() -{ - std::shared_ptr bestTarget = mob->getTarget(); - if (bestTarget == NULL) return false; - target = std::weak_ptr(bestTarget); - return true; +bool ArrowAttackGoal::canUse() { + std::shared_ptr bestTarget = mob->getTarget(); + if (bestTarget == NULL) return false; + target = std::weak_ptr(bestTarget); + return true; } -bool ArrowAttackGoal::canContinueToUse() -{ - return target.lock() != NULL && (canUse() || !mob->getNavigation()->isDone()); +bool ArrowAttackGoal::canContinueToUse() { + return target.lock() != NULL && + (canUse() || !mob->getNavigation()->isDone()); } -void ArrowAttackGoal::stop() -{ - target = std::weak_ptr(); +void ArrowAttackGoal::stop() { target = std::weak_ptr(); } + +void ArrowAttackGoal::tick() { + double attackRadiusSqr = 10 * 10; + std::shared_ptr tar = target.lock(); + double targetDistSqr = mob->distanceToSqr(tar->x, tar->bb->y0, tar->z); + bool canSee = mob->getSensing()->canSee(tar); + + if (canSee) { + ++seeTime; + } else + seeTime = 0; + + if (targetDistSqr > attackRadiusSqr || seeTime < 20) + mob->getNavigation()->moveTo(tar, speed); + else + mob->getNavigation()->stop(); + + mob->getLookControl()->setLookAt(tar, 30, 30); + + attackTime = std::max(attackTime - 1, 0); + if (attackTime > 0) return; + if (targetDistSqr > attackRadiusSqr || !canSee) return; + fireAtTarget(); + attackTime = attackInterval; } -void ArrowAttackGoal::tick() -{ - double attackRadiusSqr = 10 * 10; - std::shared_ptr tar = target.lock(); - double targetDistSqr = mob->distanceToSqr(tar->x, tar->bb->y0, tar->z); - bool canSee = mob->getSensing()->canSee(tar); +void ArrowAttackGoal::fireAtTarget() { + std::shared_ptr tar = target.lock(); + if (projectileType == ArrowType) { + std::shared_ptr arrow = std::shared_ptr(new Arrow( + level, std::dynamic_pointer_cast(mob->shared_from_this()), tar, + 1.60f, 12)); + level->playSound(mob->shared_from_this(), eSoundType_RANDOM_BOW, 1.0f, + 1 / (mob->getRandom()->nextFloat() * 0.4f + 0.8f)); + level->addEntity(arrow); + } else if (projectileType == SnowballType) { + std::shared_ptr snowball = std::shared_ptr( + new Snowball(level, std::dynamic_pointer_cast( + mob->shared_from_this()))); + double xd = tar->x - mob->x; + double yd = (tar->y + tar->getHeadHeight() - 1.1f) - snowball->y; + double zd = tar->z - mob->z; + float yo = sqrt(xd * xd + zd * zd) * 0.2f; + snowball->shoot(xd, yd + yo, zd, 1.60f, 12); - if (canSee) - { - ++seeTime; - } - else seeTime = 0; - - if (targetDistSqr > attackRadiusSqr || seeTime < 20) mob->getNavigation()->moveTo(tar, speed); - else mob->getNavigation()->stop(); - - mob->getLookControl()->setLookAt(tar, 30, 30); - - attackTime = std::max(attackTime - 1, 0); - if (attackTime > 0) return; - if (targetDistSqr > attackRadiusSqr || !canSee) return; - fireAtTarget(); - attackTime = attackInterval; -} - -void ArrowAttackGoal::fireAtTarget() -{ - std::shared_ptr tar = target.lock(); - if (projectileType == ArrowType) - { - std::shared_ptr arrow = std::shared_ptr( new Arrow(level, std::dynamic_pointer_cast(mob->shared_from_this()), tar, 1.60f, 12) ); - level->playSound(mob->shared_from_this(), eSoundType_RANDOM_BOW, 1.0f, 1 / (mob->getRandom()->nextFloat() * 0.4f + 0.8f)); - level->addEntity(arrow); - } - else if (projectileType == SnowballType) - { - std::shared_ptr snowball = std::shared_ptr( new Snowball(level, std::dynamic_pointer_cast(mob->shared_from_this())) ); - double xd = tar->x - mob->x; - double yd = (tar->y + tar->getHeadHeight() - 1.1f) - snowball->y; - double zd = tar->z - mob->z; - float yo = sqrt(xd * xd + zd * zd) * 0.2f; - snowball->shoot(xd, yd + yo, zd, 1.60f, 12); - - level->playSound(mob->shared_from_this(), eSoundType_RANDOM_BOW, 1.0f, 1 / (mob->getRandom()->nextFloat() * 0.4f + 0.8f)); - level->addEntity(snowball); - } + level->playSound(mob->shared_from_this(), eSoundType_RANDOM_BOW, 1.0f, + 1 / (mob->getRandom()->nextFloat() * 0.4f + 0.8f)); + level->addEntity(snowball); + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/ArrowAttackGoal.h b/Minecraft.World/AI/Goals/ArrowAttackGoal.h index 9f015abda..039447f28 100644 --- a/Minecraft.World/AI/Goals/ArrowAttackGoal.h +++ b/Minecraft.World/AI/Goals/ArrowAttackGoal.h @@ -2,32 +2,33 @@ #include "Goal.h" -class ArrowAttackGoal : public Goal -{ +class ArrowAttackGoal : public Goal { public: - static const int ArrowType = 1; - static const int SnowballType = 2; + static const int ArrowType = 1; + static const int SnowballType = 2; - Level *level; - Mob *mob; // Owner of this goal - std::weak_ptr target; - int attackTime; - float speed; - int seeTime; - int projectileType; - int attackInterval; + Level* level; + Mob* mob; // Owner of this goal + std::weak_ptr target; + int attackTime; + float speed; + int seeTime; + int projectileType; + int attackInterval; - ArrowAttackGoal(Mob *mob, float speed, int projectileType, int attackInterval); + ArrowAttackGoal(Mob* mob, float speed, int projectileType, + int attackInterval); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void stop(); + virtual void tick(); private: - void fireAtTarget(); + void fireAtTarget(); public: - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/AvoidPlayerGoal.cpp b/Minecraft.World/AI/Goals/AvoidPlayerGoal.cpp index dedaf7a2f..66b3fde4f 100644 --- a/Minecraft.World/AI/Goals/AvoidPlayerGoal.cpp +++ b/Minecraft.World/AI/Goals/AvoidPlayerGoal.cpp @@ -10,76 +10,77 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "AvoidPlayerGoal.h" -AvoidPlayerGoal::AvoidPlayerGoal(PathfinderMob *mob, const std::type_info& avoidType, float maxDist, float walkSpeed, float sprintSpeed) : avoidType(avoidType) -{ - this->mob = mob; - //this->avoidType = avoidType; - this->maxDist = maxDist; - this->walkSpeed = walkSpeed; - this->sprintSpeed = sprintSpeed; - this->pathNav = mob->getNavigation(); - setRequiredControlFlags(Control::MoveControlFlag); +AvoidPlayerGoal::AvoidPlayerGoal(PathfinderMob* mob, + const std::type_info& avoidType, float maxDist, + float walkSpeed, float sprintSpeed) + : avoidType(avoidType) { + this->mob = mob; + // this->avoidType = avoidType; + this->maxDist = maxDist; + this->walkSpeed = walkSpeed; + this->sprintSpeed = sprintSpeed; + this->pathNav = mob->getNavigation(); + setRequiredControlFlags(Control::MoveControlFlag); - toAvoid = std::weak_ptr(); - path = NULL; + toAvoid = std::weak_ptr(); + path = NULL; } -AvoidPlayerGoal::~AvoidPlayerGoal() -{ - if(path != NULL) delete path; +AvoidPlayerGoal::~AvoidPlayerGoal() { + if (path != NULL) delete path; } -bool AvoidPlayerGoal::canUse() -{ - if (avoidType == typeid(Player)) - { - std::shared_ptr tamableAnimal = std::dynamic_pointer_cast(mob->shared_from_this()); - if (tamableAnimal != NULL && tamableAnimal->isTame()) return false; - toAvoid = std::weak_ptr(mob->level->getNearestPlayer(mob->shared_from_this(), maxDist)); - if (toAvoid.lock() == NULL) return false; - } - else - { - std::vector > *entities = mob->level->getEntitiesOfClass(avoidType, mob->bb->grow(maxDist, 3, maxDist)); - if (entities->empty()) - { - delete entities; - return false; - } - toAvoid = std::weak_ptr(entities->at(0)); - delete entities; - } +bool AvoidPlayerGoal::canUse() { + if (avoidType == typeid(Player)) { + std::shared_ptr tamableAnimal = + std::dynamic_pointer_cast(mob->shared_from_this()); + if (tamableAnimal != NULL && tamableAnimal->isTame()) return false; + toAvoid = std::weak_ptr( + mob->level->getNearestPlayer(mob->shared_from_this(), maxDist)); + if (toAvoid.lock() == NULL) return false; + } else { + std::vector >* entities = + mob->level->getEntitiesOfClass(avoidType, + mob->bb->grow(maxDist, 3, maxDist)); + if (entities->empty()) { + delete entities; + return false; + } + toAvoid = std::weak_ptr(entities->at(0)); + delete entities; + } - if (!mob->getSensing()->canSee(toAvoid.lock())) return false; + if (!mob->getSensing()->canSee(toAvoid.lock())) return false; - Vec3 *pos = RandomPos::getPosAvoid(std::dynamic_pointer_cast(mob->shared_from_this()), 16, 7, Vec3::newTemp(toAvoid.lock()->x, toAvoid.lock()->y, toAvoid.lock()->z)); - if (pos == NULL) return false; - if (toAvoid.lock()->distanceToSqr(pos->x, pos->y, pos->z) < toAvoid.lock()->distanceToSqr(mob->shared_from_this())) return false; - delete path; - path = pathNav->createPath(pos->x, pos->y, pos->z); - if (path == NULL) return false; - if (!path->endsInXZ(pos)) return false; - return true; + Vec3* pos = RandomPos::getPosAvoid( + std::dynamic_pointer_cast(mob->shared_from_this()), 16, + 7, + Vec3::newTemp(toAvoid.lock()->x, toAvoid.lock()->y, toAvoid.lock()->z)); + if (pos == NULL) return false; + if (toAvoid.lock()->distanceToSqr(pos->x, pos->y, pos->z) < + toAvoid.lock()->distanceToSqr(mob->shared_from_this())) + return false; + delete path; + path = pathNav->createPath(pos->x, pos->y, pos->z); + if (path == NULL) return false; + if (!path->endsInXZ(pos)) return false; + return true; } -bool AvoidPlayerGoal::canContinueToUse() -{ - return toAvoid.lock() != NULL && !pathNav->isDone(); +bool AvoidPlayerGoal::canContinueToUse() { + return toAvoid.lock() != NULL && !pathNav->isDone(); } -void AvoidPlayerGoal::start() -{ - pathNav->moveTo(path, walkSpeed); - path = NULL; +void AvoidPlayerGoal::start() { + pathNav->moveTo(path, walkSpeed); + path = NULL; } -void AvoidPlayerGoal::stop() -{ - toAvoid = std::weak_ptr(); -} +void AvoidPlayerGoal::stop() { toAvoid = std::weak_ptr(); } -void AvoidPlayerGoal::tick() -{ - if (mob->distanceToSqr(toAvoid.lock()) < 7 * 7) mob->getNavigation()->setSpeed(sprintSpeed); - else mob->getNavigation()->setSpeed(walkSpeed); +void AvoidPlayerGoal::tick() { + if (mob->distanceToSqr(toAvoid.lock()) < 7 * 7) + mob->getNavigation()->setSpeed(sprintSpeed); + else + mob->getNavigation()->setSpeed(walkSpeed); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/AvoidPlayerGoal.h b/Minecraft.World/AI/Goals/AvoidPlayerGoal.h index f4705d2c0..a790eada9 100644 --- a/Minecraft.World/AI/Goals/AvoidPlayerGoal.h +++ b/Minecraft.World/AI/Goals/AvoidPlayerGoal.h @@ -6,24 +6,24 @@ class PathNavigation; class PathfinderMob; class Path; -class AvoidPlayerGoal : public Goal -{ +class AvoidPlayerGoal : public Goal { private: - PathfinderMob *mob; // Owner of this goal - float walkSpeed, sprintSpeed; - std::weak_ptr toAvoid; - float maxDist; - Path *path; - PathNavigation *pathNav; - const std::type_info& avoidType; + PathfinderMob* mob; // Owner of this goal + float walkSpeed, sprintSpeed; + std::weak_ptr toAvoid; + float maxDist; + Path* path; + PathNavigation* pathNav; + const std::type_info& avoidType; public: - AvoidPlayerGoal(PathfinderMob *mob, const std::type_info& avoidType, float maxDist, float walkSpeed, float sprintSpeed); - ~AvoidPlayerGoal(); + AvoidPlayerGoal(PathfinderMob* mob, const std::type_info& avoidType, + float maxDist, float walkSpeed, float sprintSpeed); + ~AvoidPlayerGoal(); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/BegGoal.cpp b/Minecraft.World/AI/Goals/BegGoal.cpp index 1e55f8112..de7992e6a 100644 --- a/Minecraft.World/AI/Goals/BegGoal.cpp +++ b/Minecraft.World/AI/Goals/BegGoal.cpp @@ -6,55 +6,52 @@ #include "../../Headers/net.minecraft.world.item.h" #include "BegGoal.h" -BegGoal::BegGoal(Wolf *wolf, float lookDistance) -{ - player = std::weak_ptr(); - lookTime = 0; +BegGoal::BegGoal(Wolf* wolf, float lookDistance) { + player = std::weak_ptr(); + lookTime = 0; - this->wolf = wolf; - this->level = wolf->level; - this->lookDistance = lookDistance; - setRequiredControlFlags(Control::LookControlFlag); + this->wolf = wolf; + this->level = wolf->level; + this->lookDistance = lookDistance; + setRequiredControlFlags(Control::LookControlFlag); } -bool BegGoal::canUse() -{ - player = std::weak_ptr(level->getNearestPlayer(wolf->shared_from_this(), lookDistance)); - if (player.lock() == NULL) return false; - wolf->setDespawnProtected(); - return playerHoldingInteresting(player.lock()); +bool BegGoal::canUse() { + player = std::weak_ptr( + level->getNearestPlayer(wolf->shared_from_this(), lookDistance)); + if (player.lock() == NULL) return false; + wolf->setDespawnProtected(); + return playerHoldingInteresting(player.lock()); } -bool BegGoal::canContinueToUse() -{ - if (player.lock() == NULL || !player.lock()->isAlive()) return false; - if (wolf->distanceToSqr(player.lock()) > lookDistance * lookDistance) return false; - wolf->setDespawnProtected(); - return lookTime > 0 && playerHoldingInteresting(player.lock()); +bool BegGoal::canContinueToUse() { + if (player.lock() == NULL || !player.lock()->isAlive()) return false; + if (wolf->distanceToSqr(player.lock()) > lookDistance * lookDistance) + return false; + wolf->setDespawnProtected(); + return lookTime > 0 && playerHoldingInteresting(player.lock()); } -void BegGoal::start() -{ - wolf->setIsInterested(true); - lookTime = 40 + wolf->getRandom()->nextInt(40); +void BegGoal::start() { + wolf->setIsInterested(true); + lookTime = 40 + wolf->getRandom()->nextInt(40); } -void BegGoal::stop() -{ - wolf->setIsInterested(false); - player = std::weak_ptr(); +void BegGoal::stop() { + wolf->setIsInterested(false); + player = std::weak_ptr(); } -void BegGoal::tick() -{ - wolf->getLookControl()->setLookAt(player.lock()->x, player.lock()->y + player.lock()->getHeadHeight(), player.lock()->z, 10, wolf->getMaxHeadXRot()); - --lookTime; +void BegGoal::tick() { + wolf->getLookControl()->setLookAt( + player.lock()->x, player.lock()->y + player.lock()->getHeadHeight(), + player.lock()->z, 10, wolf->getMaxHeadXRot()); + --lookTime; } -bool BegGoal::playerHoldingInteresting(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (item == NULL) return false; - if (!wolf->isTame() && item->id == Item::bone_Id) return true; - return wolf->isFood(item); +bool BegGoal::playerHoldingInteresting(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); + if (item == NULL) return false; + if (!wolf->isTame() && item->id == Item::bone_Id) return true; + return wolf->isFood(item); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/BegGoal.h b/Minecraft.World/AI/Goals/BegGoal.h index c768ed11c..42142cba6 100644 --- a/Minecraft.World/AI/Goals/BegGoal.h +++ b/Minecraft.World/AI/Goals/BegGoal.h @@ -4,28 +4,28 @@ class Wolf; -class BegGoal : public Goal -{ +class BegGoal : public Goal { private: - Wolf *wolf; // Owner of this goal - std::weak_ptr player; - Level *level; - float lookDistance; - int lookTime; + Wolf* wolf; // Owner of this goal + std::weak_ptr player; + Level* level; + float lookDistance; + int lookTime; public: - BegGoal(Wolf *wolf, float lookDistance); + BegGoal(Wolf* wolf, float lookDistance); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); private: - bool playerHoldingInteresting(std::shared_ptr player); + bool playerHoldingInteresting(std::shared_ptr player); public: - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/BreakDoorGoal.cpp b/Minecraft.World/AI/Goals/BreakDoorGoal.cpp index 6012ce831..90ddd441b 100644 --- a/Minecraft.World/AI/Goals/BreakDoorGoal.cpp +++ b/Minecraft.World/AI/Goals/BreakDoorGoal.cpp @@ -6,60 +6,55 @@ #include "../../Util/SharedConstants.h" #include "BreakDoorGoal.h" -BreakDoorGoal::BreakDoorGoal(Mob *mob) : DoorInteractGoal(mob) -{ - breakTime = 0; - lastBreakProgress = -1; +BreakDoorGoal::BreakDoorGoal(Mob* mob) : DoorInteractGoal(mob) { + breakTime = 0; + lastBreakProgress = -1; } -bool BreakDoorGoal::canUse() -{ - if (!DoorInteractGoal::canUse()) return false; - return !doorTile->isOpen(mob->level, doorX, doorY, doorZ); +bool BreakDoorGoal::canUse() { + if (!DoorInteractGoal::canUse()) return false; + return !doorTile->isOpen(mob->level, doorX, doorY, doorZ); } -void BreakDoorGoal::start() -{ - DoorInteractGoal::start(); - breakTime = 0; +void BreakDoorGoal::start() { + DoorInteractGoal::start(); + breakTime = 0; } -bool BreakDoorGoal::canContinueToUse() -{ - double d = mob->distanceToSqr(doorX, doorY, doorZ); - return breakTime <= DOOR_BREAK_TIME && !doorTile->isOpen(mob->level, doorX, doorY, doorZ) && d < 2 * 2; +bool BreakDoorGoal::canContinueToUse() { + double d = mob->distanceToSqr(doorX, doorY, doorZ); + return breakTime <= DOOR_BREAK_TIME && + !doorTile->isOpen(mob->level, doorX, doorY, doorZ) && d < 2 * 2; } -void BreakDoorGoal::stop() -{ - DoorInteractGoal::stop(); - mob->level->destroyTileProgress(mob->entityId, doorX, doorY, doorZ, -1); +void BreakDoorGoal::stop() { + DoorInteractGoal::stop(); + mob->level->destroyTileProgress(mob->entityId, doorX, doorY, doorZ, -1); } -void BreakDoorGoal::tick() -{ - DoorInteractGoal::tick(); - if (mob->getRandom()->nextInt(20) == 0) - { - mob->level->levelEvent(LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR, doorX, doorY, doorZ, 0); - } +void BreakDoorGoal::tick() { + DoorInteractGoal::tick(); + if (mob->getRandom()->nextInt(20) == 0) { + mob->level->levelEvent(LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR, doorX, + doorY, doorZ, 0); + } - breakTime++; + breakTime++; - int progress = (int) (breakTime / (float) DOOR_BREAK_TIME * 10); - if (progress != lastBreakProgress) - { - mob->level->destroyTileProgress(mob->entityId, doorX, doorY, doorZ, progress); - lastBreakProgress = progress; - } + int progress = (int)(breakTime / (float)DOOR_BREAK_TIME * 10); + if (progress != lastBreakProgress) { + mob->level->destroyTileProgress(mob->entityId, doorX, doorY, doorZ, + progress); + lastBreakProgress = progress; + } - if (breakTime == DOOR_BREAK_TIME) - { - if (mob->level->difficulty == Difficulty::HARD) - { - mob->level->setTile(doorX, doorY, doorZ, 0); - mob->level->levelEvent(LevelEvent::SOUND_ZOMBIE_DOOR_CRASH, doorX, doorY, doorZ, 0); - mob->level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, doorX, doorY, doorZ, doorTile->id); - } - } + if (breakTime == DOOR_BREAK_TIME) { + if (mob->level->difficulty == Difficulty::HARD) { + mob->level->setTile(doorX, doorY, doorZ, 0); + mob->level->levelEvent(LevelEvent::SOUND_ZOMBIE_DOOR_CRASH, doorX, + doorY, doorZ, 0); + mob->level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, doorX, + doorY, doorZ, doorTile->id); + } + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/BreakDoorGoal.h b/Minecraft.World/AI/Goals/BreakDoorGoal.h index c04559ba2..4912d9121 100644 --- a/Minecraft.World/AI/Goals/BreakDoorGoal.h +++ b/Minecraft.World/AI/Goals/BreakDoorGoal.h @@ -3,20 +3,19 @@ #include "DoorInteractGoal.h" #include "../../Util/SharedConstants.h" -class BreakDoorGoal : public DoorInteractGoal -{ +class BreakDoorGoal : public DoorInteractGoal { private: - static const int DOOR_BREAK_TIME = SharedConstants::TICKS_PER_SECOND * 12; + static const int DOOR_BREAK_TIME = SharedConstants::TICKS_PER_SECOND * 12; - int breakTime; - int lastBreakProgress; + int breakTime; + int lastBreakProgress; public: - BreakDoorGoal(Mob *mob); + BreakDoorGoal(Mob* mob); - virtual bool canUse(); - virtual void start(); - virtual void stop(); - virtual bool canContinueToUse(); - virtual void tick(); + virtual bool canUse(); + virtual void start(); + virtual void stop(); + virtual bool canContinueToUse(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/BreedGoal.cpp b/Minecraft.World/AI/Goals/BreedGoal.cpp index 0b7ac1069..24e033c81 100644 --- a/Minecraft.World/AI/Goals/BreedGoal.cpp +++ b/Minecraft.World/AI/Goals/BreedGoal.cpp @@ -9,108 +9,111 @@ #include "../../Stats/GenericStats.h" -BreedGoal::BreedGoal(Animal *animal, float speed) -{ - partner = std::weak_ptr(); - loveTime = 0; +BreedGoal::BreedGoal(Animal* animal, float speed) { + partner = std::weak_ptr(); + loveTime = 0; - this->animal = animal; - this->level = animal->level; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->animal = animal; + this->level = animal->level; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool BreedGoal::canUse() -{ - if (!animal->isInLove()) return false; - partner = std::weak_ptr(getFreePartner()); - return partner.lock() != NULL; +bool BreedGoal::canUse() { + if (!animal->isInLove()) return false; + partner = std::weak_ptr(getFreePartner()); + return partner.lock() != NULL; } -bool BreedGoal::canContinueToUse() -{ - return partner.lock() != NULL && partner.lock()->isAlive() && partner.lock()->isInLove() && loveTime < 20 * 3; +bool BreedGoal::canContinueToUse() { + return partner.lock() != NULL && partner.lock()->isAlive() && + partner.lock()->isInLove() && loveTime < 20 * 3; } -void BreedGoal::stop() -{ - partner = std::weak_ptr(); - loveTime = 0; +void BreedGoal::stop() { + partner = std::weak_ptr(); + loveTime = 0; } -void BreedGoal::tick() -{ - animal->getLookControl()->setLookAt(partner.lock(), 10, animal->getMaxHeadXRot()); - animal->getNavigation()->moveTo(partner.lock(), speed); - ++loveTime; - if (loveTime == 20 * 3) breed(); +void BreedGoal::tick() { + animal->getLookControl()->setLookAt(partner.lock(), 10, + animal->getMaxHeadXRot()); + animal->getNavigation()->moveTo(partner.lock(), speed); + ++loveTime; + if (loveTime == 20 * 3) breed(); } -std::shared_ptr BreedGoal::getFreePartner() -{ - float r = 8; - std::vector > *others = level->getEntitiesOfClass(typeid(*animal), animal->bb->grow(r, r, r)); - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) - { - std::shared_ptr p = std::dynamic_pointer_cast(*it); - if (animal->canMate(p)) - { - delete others; - return p; - } - } - delete others; - return nullptr; +std::shared_ptr BreedGoal::getFreePartner() { + float r = 8; + std::vector >* others = + level->getEntitiesOfClass(typeid(*animal), animal->bb->grow(r, r, r)); + for (AUTO_VAR(it, others->begin()); it != others->end(); ++it) { + std::shared_ptr p = std::dynamic_pointer_cast(*it); + if (animal->canMate(p)) { + delete others; + return p; + } + } + delete others; + return nullptr; } -void BreedGoal::breed() -{ - std::shared_ptr offspring = animal->getBreedOffspring(partner.lock()); - animal->setDespawnProtected(); - partner.lock()->setDespawnProtected(); - if (offspring == NULL) - { - // This will be NULL if we've hit our limits for spawning any particular type of animal... reset things as normally as we can, without actually producing any offspring - animal->resetLove(); - partner.lock()->resetLove(); - return; - } +void BreedGoal::breed() { + std::shared_ptr offspring = + animal->getBreedOffspring(partner.lock()); + animal->setDespawnProtected(); + partner.lock()->setDespawnProtected(); + if (offspring == NULL) { + // This will be NULL if we've hit our limits for spawning any particular + // type of animal... reset things as normally as we can, without + // actually producing any offspring + animal->resetLove(); + partner.lock()->resetLove(); + return; + } - std::shared_ptr loveCause = animal->getLoveCause(); - if (loveCause == NULL && partner.lock()->getLoveCause() != NULL) - { - loveCause = partner.lock()->getLoveCause(); - } + std::shared_ptr loveCause = animal->getLoveCause(); + if (loveCause == NULL && partner.lock()->getLoveCause() != NULL) { + loveCause = partner.lock()->getLoveCause(); + } - if (loveCause != NULL) - { - // Record mob bred stat. - loveCause->awardStat(GenericStats::breedEntity(offspring->GetType()),GenericStats::param_breedEntity(offspring->GetType())); + if (loveCause != NULL) { + // Record mob bred stat. + loveCause->awardStat( + GenericStats::breedEntity(offspring->GetType()), + GenericStats::param_breedEntity(offspring->GetType())); - if (animal->GetType() == eTYPE_COW) - { - //loveCause->awardStat(Achievements.breedCow); - } - } + if (animal->GetType() == eTYPE_COW) { + // loveCause->awardStat(Achievements.breedCow); + } + } - animal->setAge(5 * 60 * 20); - partner.lock()->setAge(5 * 60 * 20); - animal->resetLove(); - partner.lock()->resetLove(); - offspring->setAge(-20 * 60 * 20); - offspring->moveTo(animal->x, animal->y, animal->z, 0, 0); - offspring->setDespawnProtected(); - level->addEntity(offspring); + animal->setAge(5 * 60 * 20); + partner.lock()->setAge(5 * 60 * 20); + animal->resetLove(); + partner.lock()->resetLove(); + offspring->setAge(-20 * 60 * 20); + offspring->moveTo(animal->x, animal->y, animal->z, 0, 0); + offspring->setDespawnProtected(); + level->addEntity(offspring); - Random *random = animal->getRandom(); - for (int i = 0; i < 7; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(eParticleType_heart, animal->x + random->nextFloat() * animal->bbWidth * 2 - animal->bbWidth, animal->y + .5f + random->nextFloat() * animal->bbHeight, animal->z + random->nextFloat() - * animal->bbWidth * 2 - animal->bbWidth, xa, ya, za); - } - // 4J-PB - Fix for 106869- Customer Encountered: TU12: Content: Gameplay: Breeding animals does not give any Experience Orbs. - level->addEntity( std::shared_ptr( new ExperienceOrb(level, animal->x, animal->y, animal->z, random->nextInt(7) + 1) ) ); + Random* random = animal->getRandom(); + for (int i = 0; i < 7; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle( + eParticleType_heart, + animal->x + random->nextFloat() * animal->bbWidth * 2 - + animal->bbWidth, + animal->y + .5f + random->nextFloat() * animal->bbHeight, + animal->z + random->nextFloat() * animal->bbWidth * 2 - + animal->bbWidth, + xa, ya, za); + } + // 4J-PB - Fix for 106869- Customer Encountered: TU12: Content: Gameplay: + // Breeding animals does not give any Experience Orbs. + level->addEntity(std::shared_ptr(new ExperienceOrb( + level, animal->x, animal->y, animal->z, random->nextInt(7) + 1))); } diff --git a/Minecraft.World/AI/Goals/BreedGoal.h b/Minecraft.World/AI/Goals/BreedGoal.h index 98e09739e..960252970 100644 --- a/Minecraft.World/AI/Goals/BreedGoal.h +++ b/Minecraft.World/AI/Goals/BreedGoal.h @@ -5,28 +5,28 @@ class Animal; class Level; -class BreedGoal : public Goal -{ +class BreedGoal : public Goal { private: - Animal *animal; // Owner of this goal - Level *level; - std::weak_ptr partner; - int loveTime; - float speed; + Animal* animal; // Owner of this goal + Level* level; + std::weak_ptr partner; + int loveTime; + float speed; public: - BreedGoal(Animal *animal, float speed); + BreedGoal(Animal* animal, float speed); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void stop(); + virtual void tick(); private: - std::shared_ptr getFreePartner(); - void breed(); + std::shared_ptr getFreePartner(); + void breed(); public: - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/ControlledByPlayerGoal.cpp b/Minecraft.World/AI/Goals/ControlledByPlayerGoal.cpp index 6f0fc49d3..0e79f23c1 100644 --- a/Minecraft.World/AI/Goals/ControlledByPlayerGoal.cpp +++ b/Minecraft.World/AI/Goals/ControlledByPlayerGoal.cpp @@ -8,145 +8,143 @@ #include "../../Headers/net.minecraft.world.level.pathfinder.h" #include "ControlledByPlayerGoal.h" -ControlledByPlayerGoal::ControlledByPlayerGoal(Mob *mob, float maxSpeed, float walkSpeed) -{ - this->mob = mob; - this->maxSpeed = maxSpeed; - this->walkSpeed = walkSpeed; - speed = 0; - boosting = false; - boostTime = 0; - boostTimeTotal = 0; - setRequiredControlFlags(Control::MoveControlFlag | Control::JumpControlFlag | Control::LookControlFlag); +ControlledByPlayerGoal::ControlledByPlayerGoal(Mob* mob, float maxSpeed, + float walkSpeed) { + this->mob = mob; + this->maxSpeed = maxSpeed; + this->walkSpeed = walkSpeed; + speed = 0; + boosting = false; + boostTime = 0; + boostTimeTotal = 0; + setRequiredControlFlags(Control::MoveControlFlag | + Control::JumpControlFlag | + Control::LookControlFlag); } -void ControlledByPlayerGoal::start() -{ - speed = 0; +void ControlledByPlayerGoal::start() { + speed = 0; - // 4J Stu - Need to initialise this otherwise the pig will never move if you jump on before another goal has made it move and set the speed - if(mob->getSpeed() < walkSpeed) mob->setSpeed(walkSpeed); + // 4J Stu - Need to initialise this otherwise the pig will never move if you + // jump on before another goal has made it move and set the speed + if (mob->getSpeed() < walkSpeed) mob->setSpeed(walkSpeed); } -void ControlledByPlayerGoal::stop() -{ - boosting = false; - speed = 0; +void ControlledByPlayerGoal::stop() { + boosting = false; + speed = 0; } -bool ControlledByPlayerGoal::canUse() -{ - std::shared_ptr player = std::dynamic_pointer_cast( mob->rider.lock() ); - return mob->isAlive() && player && (boosting || mob->canBeControlledByRider()); +bool ControlledByPlayerGoal::canUse() { + std::shared_ptr player = + std::dynamic_pointer_cast(mob->rider.lock()); + return mob->isAlive() && player && + (boosting || mob->canBeControlledByRider()); } -void ControlledByPlayerGoal::tick() -{ - std::shared_ptr player = std::dynamic_pointer_cast(mob->rider.lock()); - PathfinderMob *pig = (PathfinderMob *)mob; +void ControlledByPlayerGoal::tick() { + std::shared_ptr player = + std::dynamic_pointer_cast(mob->rider.lock()); + PathfinderMob* pig = (PathfinderMob*)mob; - float yrd = Mth::wrapDegrees(player->yRot - mob->yRot) * 0.5f; - if (yrd > 5) yrd = 5; - if (yrd < -5) yrd = -5; + float yrd = Mth::wrapDegrees(player->yRot - mob->yRot) * 0.5f; + if (yrd > 5) yrd = 5; + if (yrd < -5) yrd = -5; - mob->yRot = Mth::wrapDegrees(mob->yRot + yrd); - if (speed < maxSpeed) speed += (maxSpeed - speed) * 0.01f; - if (speed > maxSpeed) speed = maxSpeed; + mob->yRot = Mth::wrapDegrees(mob->yRot + yrd); + if (speed < maxSpeed) speed += (maxSpeed - speed) * 0.01f; + if (speed > maxSpeed) speed = maxSpeed; - int x = Mth::floor(mob->x); - int y = Mth::floor(mob->y); - int z = Mth::floor(mob->z); - float moveSpeed = speed; - if (boosting) - { - if (boostTime++ > boostTimeTotal) - { - boosting = false; - } - moveSpeed += moveSpeed * 1.15f * Mth::sin((float) boostTime / boostTimeTotal * PI); - } + int x = Mth::floor(mob->x); + int y = Mth::floor(mob->y); + int z = Mth::floor(mob->z); + float moveSpeed = speed; + if (boosting) { + if (boostTime++ > boostTimeTotal) { + boosting = false; + } + moveSpeed += moveSpeed * 1.15f * + Mth::sin((float)boostTime / boostTimeTotal * PI); + } - float friction = 0.91f; - if (mob->onGround) - { - friction = 0.6f * 0.91f; - int t = mob->level->getTile(x,y,z); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.91f; - } - } - float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / (friction * friction * friction); - float sin = Mth::sin(pig->yRot * PI / 180); - float cos = Mth::cos(pig->yRot * PI / 180); - float aproxSpeed = pig->getSpeed() * friction2; - float dist = std::max((int)moveSpeed, 1); - dist = aproxSpeed / dist; - float normMoveSpeed = moveSpeed * dist; - float xa = -(normMoveSpeed * sin); - float za = normMoveSpeed * cos; + float friction = 0.91f; + if (mob->onGround) { + friction = 0.6f * 0.91f; + int t = mob->level->getTile(x, y, z); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.91f; + } + } + float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / + (friction * friction * friction); + float sin = Mth::sin(pig->yRot * PI / 180); + float cos = Mth::cos(pig->yRot * PI / 180); + float aproxSpeed = pig->getSpeed() * friction2; + float dist = std::max((int)moveSpeed, 1); + dist = aproxSpeed / dist; + float normMoveSpeed = moveSpeed * dist; + float xa = -(normMoveSpeed * sin); + float za = normMoveSpeed * cos; - if (Mth::abs(xa) > Mth::abs(za)) - { - if (xa < 0) xa -= mob->bbWidth / 2.0f; - if (xa > 0) xa += mob->bbWidth / 2.0f; - za = 0; - } - else - { - xa = 0; - if (za < 0) za -= mob->bbWidth / 2.0f; - if (za > 0) za += mob->bbWidth / 2.0f; - } + if (Mth::abs(xa) > Mth::abs(za)) { + if (xa < 0) xa -= mob->bbWidth / 2.0f; + if (xa > 0) xa += mob->bbWidth / 2.0f; + za = 0; + } else { + xa = 0; + if (za < 0) za -= mob->bbWidth / 2.0f; + if (za > 0) za += mob->bbWidth / 2.0f; + } - int xt = Mth::floor(mob->x + xa); - int zt = Mth::floor(mob->z + za); + int xt = Mth::floor(mob->x + xa); + int zt = Mth::floor(mob->z + za); - Node *size = new Node(Mth::floor(mob->bbWidth + 1), Mth::floor(mob->bbHeight + player->bbHeight + 1), Mth::floor(mob->bbWidth + 1)); + Node* size = new Node(Mth::floor(mob->bbWidth + 1), + Mth::floor(mob->bbHeight + player->bbHeight + 1), + Mth::floor(mob->bbWidth + 1)); - if (x != xt || z != zt) - { - if (PathFinder::isFree(mob, xt, y, zt, size, false, false, true) == PathFinder::TYPE_BLOCKED - && PathFinder::isFree(mob, x, y + 1, z, size, false, false, true) == PathFinder::TYPE_OPEN - && PathFinder::isFree(mob, xt, y + 1, zt, size, false, false, true) == PathFinder::TYPE_OPEN) - { - pig->getJumpControl()->jump(); - } - } + if (x != xt || z != zt) { + if (PathFinder::isFree(mob, xt, y, zt, size, false, false, true) == + PathFinder::TYPE_BLOCKED && + PathFinder::isFree(mob, x, y + 1, z, size, false, false, true) == + PathFinder::TYPE_OPEN && + PathFinder::isFree(mob, xt, y + 1, zt, size, false, false, true) == + PathFinder::TYPE_OPEN) { + pig->getJumpControl()->jump(); + } + } - if (!player->abilities.instabuild && speed >= maxSpeed * 0.5f && mob->getRandom()->nextFloat() < 0.006f && !boosting) - { - std::shared_ptr carriedItem = player->getCarriedItem(); + if (!player->abilities.instabuild && speed >= maxSpeed * 0.5f && + mob->getRandom()->nextFloat() < 0.006f && !boosting) { + std::shared_ptr carriedItem = player->getCarriedItem(); - if (carriedItem != NULL && carriedItem->id == Item::carrotOnAStick_Id) - { - carriedItem->hurt(1, player); + if (carriedItem != NULL && carriedItem->id == Item::carrotOnAStick_Id) { + carriedItem->hurt(1, player); - if (carriedItem->count == 0) - { - std::shared_ptr replacement = std::shared_ptr(new ItemInstance(Item::fishingRod)); - replacement->setTag(carriedItem->tag); - player->inventory->items[player->inventory->selected] = replacement; - } - } - } + if (carriedItem->count == 0) { + std::shared_ptr replacement = + std::shared_ptr( + new ItemInstance(Item::fishingRod)); + replacement->setTag(carriedItem->tag); + player->inventory->items[player->inventory->selected] = + replacement; + } + } + } - mob->travel(0, moveSpeed); + mob->travel(0, moveSpeed); } -bool ControlledByPlayerGoal::isBoosting() -{ - return boosting; +bool ControlledByPlayerGoal::isBoosting() { return boosting; } + +void ControlledByPlayerGoal::boost() { + boosting = true; + boostTime = 0; + boostTimeTotal = + mob->getRandom()->nextInt(MAX_BOOST_TIME + MIN_BOOST_TIME + 1) + + MIN_BOOST_TIME; } -void ControlledByPlayerGoal::boost() -{ - boosting = true; - boostTime = 0; - boostTimeTotal = mob->getRandom()->nextInt(MAX_BOOST_TIME + MIN_BOOST_TIME + 1) + MIN_BOOST_TIME; -} - -bool ControlledByPlayerGoal::canBoost() -{ - return !isBoosting() && speed > maxSpeed * 0.3f; +bool ControlledByPlayerGoal::canBoost() { + return !isBoosting() && speed > maxSpeed * 0.3f; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/ControlledByPlayerGoal.h b/Minecraft.World/AI/Goals/ControlledByPlayerGoal.h index 5d5d613ca..707ec0c3f 100644 --- a/Minecraft.World/AI/Goals/ControlledByPlayerGoal.h +++ b/Minecraft.World/AI/Goals/ControlledByPlayerGoal.h @@ -5,28 +5,28 @@ class Mob; -class ControlledByPlayerGoal : public Goal -{ +class ControlledByPlayerGoal : public Goal { private: - static const int MIN_BOOST_TIME = SharedConstants::TICKS_PER_SECOND * 7; - static const int MAX_BOOST_TIME = SharedConstants::TICKS_PER_SECOND * 35; + static const int MIN_BOOST_TIME = SharedConstants::TICKS_PER_SECOND * 7; + static const int MAX_BOOST_TIME = SharedConstants::TICKS_PER_SECOND * 35; - Mob *mob; // Owner of this goal - float maxSpeed; - float walkSpeed; - float speed; - bool boosting; - int boostTime; - int boostTimeTotal; + Mob* mob; // Owner of this goal + float maxSpeed; + float walkSpeed; + float speed; + bool boosting; + int boostTime; + int boostTimeTotal; public: - ControlledByPlayerGoal(Mob *mob, float maxSpeed, float walkSpeed); // 4J Added walkSpeed param + ControlledByPlayerGoal(Mob* mob, float maxSpeed, + float walkSpeed); // 4J Added walkSpeed param - void start(); - void stop(); - bool canUse(); - void tick(); - bool isBoosting(); - void boost(); - bool canBoost(); + void start(); + void stop(); + bool canUse(); + void tick(); + bool isBoosting(); + void boost(); + bool canBoost(); }; diff --git a/Minecraft.World/AI/Goals/DefendVillageTargetGoal.cpp b/Minecraft.World/AI/Goals/DefendVillageTargetGoal.cpp index acf137ca2..d7ebc3c3b 100644 --- a/Minecraft.World/AI/Goals/DefendVillageTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/DefendVillageTargetGoal.cpp @@ -3,22 +3,21 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "DefendVillageTargetGoal.h" -DefendVillageTargetGoal::DefendVillageTargetGoal(VillagerGolem *golem) : TargetGoal(golem, 16, false, true) -{ - this->golem = golem; - setRequiredControlFlags(TargetGoal::TargetFlag); +DefendVillageTargetGoal::DefendVillageTargetGoal(VillagerGolem* golem) + : TargetGoal(golem, 16, false, true) { + this->golem = golem; + setRequiredControlFlags(TargetGoal::TargetFlag); } -bool DefendVillageTargetGoal::canUse() -{ - std::shared_ptr village = golem->getVillage(); - if (village == NULL) return false; - potentialTarget = std::weak_ptr(village->getClosestAggressor(std::dynamic_pointer_cast(golem->shared_from_this()))); - return canAttack(potentialTarget.lock(), false); +bool DefendVillageTargetGoal::canUse() { + std::shared_ptr village = golem->getVillage(); + if (village == NULL) return false; + potentialTarget = std::weak_ptr(village->getClosestAggressor( + std::dynamic_pointer_cast(golem->shared_from_this()))); + return canAttack(potentialTarget.lock(), false); } -void DefendVillageTargetGoal::start() -{ - golem->setTarget(potentialTarget.lock()); - TargetGoal::start(); +void DefendVillageTargetGoal::start() { + golem->setTarget(potentialTarget.lock()); + TargetGoal::start(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/DefendVillageTargetGoal.h b/Minecraft.World/AI/Goals/DefendVillageTargetGoal.h index 609c03218..c20257cc3 100644 --- a/Minecraft.World/AI/Goals/DefendVillageTargetGoal.h +++ b/Minecraft.World/AI/Goals/DefendVillageTargetGoal.h @@ -4,15 +4,14 @@ class VillagerGolem; -class DefendVillageTargetGoal : public TargetGoal -{ +class DefendVillageTargetGoal : public TargetGoal { private: - VillagerGolem *golem; // Owner of this goal - std::weak_ptr potentialTarget; + VillagerGolem* golem; // Owner of this goal + std::weak_ptr potentialTarget; public: - DefendVillageTargetGoal(VillagerGolem *golem); + DefendVillageTargetGoal(VillagerGolem* golem); - bool canUse(); - void start(); + bool canUse(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/DoorInteractGoal.cpp b/Minecraft.World/AI/Goals/DoorInteractGoal.cpp index 665d35f84..23be94098 100644 --- a/Minecraft.World/AI/Goals/DoorInteractGoal.cpp +++ b/Minecraft.World/AI/Goals/DoorInteractGoal.cpp @@ -6,68 +6,59 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "DoorInteractGoal.h" -DoorInteractGoal::DoorInteractGoal(Mob *mob) -{ - doorX = doorY = doorZ = 0; - doorTile = NULL; - passed = false; - doorOpenDirX = doorOpenDirZ = 0.0f; +DoorInteractGoal::DoorInteractGoal(Mob* mob) { + doorX = doorY = doorZ = 0; + doorTile = NULL; + passed = false; + doorOpenDirX = doorOpenDirZ = 0.0f; - this->mob = mob; + this->mob = mob; } -bool DoorInteractGoal::canUse() -{ - if (!mob->horizontalCollision) return false; - PathNavigation *pathNav = mob->getNavigation(); - Path *path = pathNav->getPath(); - if (path == NULL || path->isDone() || !pathNav->canOpenDoors()) return false; +bool DoorInteractGoal::canUse() { + if (!mob->horizontalCollision) return false; + PathNavigation* pathNav = mob->getNavigation(); + Path* path = pathNav->getPath(); + if (path == NULL || path->isDone() || !pathNav->canOpenDoors()) + return false; - for (int i = 0; i < std::min(path->getIndex() + 2, path->getSize()); ++i) - { - Node *n = path->get(i); - doorX = n->x; - doorY = n->y + 1; - doorZ = n->z; - if (mob->distanceToSqr(doorX, mob->y, doorZ) > 1.5 * 1.5) continue; - doorTile = getDoorTile(doorX, doorY, doorZ); - if (doorTile == NULL) continue; - return true; - } + for (int i = 0; i < std::min(path->getIndex() + 2, path->getSize()); ++i) { + Node* n = path->get(i); + doorX = n->x; + doorY = n->y + 1; + doorZ = n->z; + if (mob->distanceToSqr(doorX, mob->y, doorZ) > 1.5 * 1.5) continue; + doorTile = getDoorTile(doorX, doorY, doorZ); + if (doorTile == NULL) continue; + return true; + } - doorX = Mth::floor(mob->x); - doorY = Mth::floor(mob->y + 1); - doorZ = Mth::floor(mob->z); - doorTile = getDoorTile(doorX, doorY, doorZ); - return doorTile != NULL; + doorX = Mth::floor(mob->x); + doorY = Mth::floor(mob->y + 1); + doorZ = Mth::floor(mob->z); + doorTile = getDoorTile(doorX, doorY, doorZ); + return doorTile != NULL; } -bool DoorInteractGoal::canContinueToUse() -{ - return !passed; +bool DoorInteractGoal::canContinueToUse() { return !passed; } + +void DoorInteractGoal::start() { + passed = false; + doorOpenDirX = (float)(doorX + 0.5f - mob->x); + doorOpenDirZ = (float)(doorZ + 0.5f - mob->z); } -void DoorInteractGoal::start() -{ - passed = false; - doorOpenDirX = (float) (doorX + 0.5f - mob->x); - doorOpenDirZ = (float) (doorZ + 0.5f - mob->z); +void DoorInteractGoal::tick() { + float newDoorDirX = (float)(doorX + 0.5f - mob->x); + float newDoorDirZ = (float)(doorZ + 0.5f - mob->z); + float dot = doorOpenDirX * newDoorDirX + doorOpenDirZ * newDoorDirZ; + if (dot < 0) { + passed = true; + } } -void DoorInteractGoal::tick() -{ - float newDoorDirX = (float) (doorX + 0.5f - mob->x); - float newDoorDirZ = (float) (doorZ + 0.5f - mob->z); - float dot = doorOpenDirX * newDoorDirX + doorOpenDirZ * newDoorDirZ; - if (dot < 0) - { - passed = true; - } -} - -DoorTile *DoorInteractGoal::getDoorTile(int x, int y, int z) -{ - int tileId = mob->level->getTile(x, y, z); - if (tileId != Tile::door_wood_Id) return NULL; - return (DoorTile *) Tile::tiles[tileId]; +DoorTile* DoorInteractGoal::getDoorTile(int x, int y, int z) { + int tileId = mob->level->getTile(x, y, z); + if (tileId != Tile::door_wood_Id) return NULL; + return (DoorTile*)Tile::tiles[tileId]; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/DoorInteractGoal.h b/Minecraft.World/AI/Goals/DoorInteractGoal.h index e5041a166..56dcde469 100644 --- a/Minecraft.World/AI/Goals/DoorInteractGoal.h +++ b/Minecraft.World/AI/Goals/DoorInteractGoal.h @@ -4,26 +4,25 @@ class DoorTile; -class DoorInteractGoal : public Goal -{ +class DoorInteractGoal : public Goal { protected: - Mob *mob; // Owner of this goal - int doorX, doorY, doorZ; - DoorTile *doorTile; + Mob* mob; // Owner of this goal + int doorX, doorY, doorZ; + DoorTile* doorTile; private: - bool passed; - float doorOpenDirX, doorOpenDirZ; + bool passed; + float doorOpenDirX, doorOpenDirZ; public: - DoorInteractGoal(Mob *mob); - virtual ~DoorInteractGoal() {} + DoorInteractGoal(Mob* mob); + virtual ~DoorInteractGoal() {} - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void tick(); private: - DoorTile *getDoorTile(int x, int y, int z); + DoorTile* getDoorTile(int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/EatTileGoal.cpp b/Minecraft.World/AI/Goals/EatTileGoal.cpp index 028493074..ceebd3706 100644 --- a/Minecraft.World/AI/Goals/EatTileGoal.cpp +++ b/Minecraft.World/AI/Goals/EatTileGoal.cpp @@ -6,68 +6,60 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "EatTileGoal.h" -EatTileGoal::EatTileGoal(Mob *mob) -{ - eatAnimationTick = 0; +EatTileGoal::EatTileGoal(Mob* mob) { + eatAnimationTick = 0; - this->mob = mob; - this->level = mob->level; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag | Control::JumpControlFlag); + this->mob = mob; + this->level = mob->level; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag | + Control::JumpControlFlag); } -bool EatTileGoal::canUse() -{ - if (mob->getRandom()->nextInt(mob->isBaby() ? 50 : 1000) != 0) return false; +bool EatTileGoal::canUse() { + if (mob->getRandom()->nextInt(mob->isBaby() ? 50 : 1000) != 0) return false; - int xx = Mth::floor(mob->x); - int yy = Mth::floor(mob->y); - int zz = Mth::floor(mob->z); - if (level->getTile(xx, yy, zz) == Tile::tallgrass_Id && level->getData(xx, yy, zz) == TallGrass::TALL_GRASS) return true; - if (level->getTile(xx, yy - 1, zz) == Tile::grass_Id) return true; - return false; + int xx = Mth::floor(mob->x); + int yy = Mth::floor(mob->y); + int zz = Mth::floor(mob->z); + if (level->getTile(xx, yy, zz) == Tile::tallgrass_Id && + level->getData(xx, yy, zz) == TallGrass::TALL_GRASS) + return true; + if (level->getTile(xx, yy - 1, zz) == Tile::grass_Id) return true; + return false; } -void EatTileGoal::start() -{ - eatAnimationTick = EAT_ANIMATION_TICKS; - level->broadcastEntityEvent(mob->shared_from_this(), EntityEvent::EAT_GRASS); - mob->getNavigation()->stop(); +void EatTileGoal::start() { + eatAnimationTick = EAT_ANIMATION_TICKS; + level->broadcastEntityEvent(mob->shared_from_this(), + EntityEvent::EAT_GRASS); + mob->getNavigation()->stop(); } -void EatTileGoal::stop() -{ - eatAnimationTick = 0; -} +void EatTileGoal::stop() { eatAnimationTick = 0; } -bool EatTileGoal::canContinueToUse() -{ - return eatAnimationTick > 0; -} +bool EatTileGoal::canContinueToUse() { return eatAnimationTick > 0; } -int EatTileGoal::getEatAnimationTick() -{ - return eatAnimationTick; -} +int EatTileGoal::getEatAnimationTick() { return eatAnimationTick; } -void EatTileGoal::tick() -{ - eatAnimationTick = std::max(0, eatAnimationTick - 1); - if (eatAnimationTick != 4) return; +void EatTileGoal::tick() { + eatAnimationTick = std::max(0, eatAnimationTick - 1); + if (eatAnimationTick != 4) return; - int xx = Mth::floor(mob->x); - int yy = Mth::floor(mob->y); - int zz = Mth::floor(mob->z); + int xx = Mth::floor(mob->x); + int yy = Mth::floor(mob->y); + int zz = Mth::floor(mob->z); - if (level->getTile(xx, yy, zz) == Tile::tallgrass_Id) - { - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, xx, yy, zz, Tile::tallgrass_Id + (TallGrass::TALL_GRASS << Tile::TILE_NUM_SHIFT)); - level->setTile(xx, yy, zz, 0); - mob->ate(); - } - else if (level->getTile(xx, yy - 1, zz) == Tile::grass_Id) - { - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, xx, yy - 1, zz, Tile::grass_Id); - level->setTile(xx, yy - 1, zz, Tile::dirt_Id); - mob->ate(); - } + if (level->getTile(xx, yy, zz) == Tile::tallgrass_Id) { + level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, xx, yy, zz, + Tile::tallgrass_Id + + (TallGrass::TALL_GRASS << Tile::TILE_NUM_SHIFT)); + level->setTile(xx, yy, zz, 0); + mob->ate(); + } else if (level->getTile(xx, yy - 1, zz) == Tile::grass_Id) { + level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, xx, yy - 1, zz, + Tile::grass_Id); + level->setTile(xx, yy - 1, zz, Tile::dirt_Id); + mob->ate(); + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/EatTileGoal.h b/Minecraft.World/AI/Goals/EatTileGoal.h index abd7e1f05..73a8baaa2 100644 --- a/Minecraft.World/AI/Goals/EatTileGoal.h +++ b/Minecraft.World/AI/Goals/EatTileGoal.h @@ -3,26 +3,28 @@ #include "Goal.h" #include "../../Util/SharedConstants.h" -// note: Mob should implement handleEntityEvent for client state, also ate to take action upon eating -class EatTileGoal : public Goal -{ +// note: Mob should implement handleEntityEvent for client state, also ate to +// take action upon eating +class EatTileGoal : public Goal { private: - static const int EAT_ANIMATION_TICKS = SharedConstants::TICKS_PER_SECOND * 2; + static const int EAT_ANIMATION_TICKS = + SharedConstants::TICKS_PER_SECOND * 2; - Mob *mob; // Owner of this goal - Level *level; - int eatAnimationTick; + Mob* mob; // Owner of this goal + Level* level; + int eatAnimationTick; public: - EatTileGoal(Mob *mob); + EatTileGoal(Mob* mob); - virtual bool canUse(); - virtual void start(); - virtual void stop(); - virtual bool canContinueToUse(); - virtual int getEatAnimationTick(); - virtual void tick(); - - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + virtual bool canUse(); + virtual void start(); + virtual void stop(); + virtual bool canContinueToUse(); + virtual int getEatAnimationTick(); + virtual void tick(); + + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FleeSunGoal.cpp b/Minecraft.World/AI/Goals/FleeSunGoal.cpp index b15ea43a0..4fb2eedce 100644 --- a/Minecraft.World/AI/Goals/FleeSunGoal.cpp +++ b/Minecraft.World/AI/Goals/FleeSunGoal.cpp @@ -6,47 +6,43 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "FleeSunGoal.h" -FleeSunGoal::FleeSunGoal(PathfinderMob *mob, float speed) -{ - this->mob = mob; - this->speed = speed; - this->level = mob->level; - setRequiredControlFlags(Control::MoveControlFlag); +FleeSunGoal::FleeSunGoal(PathfinderMob* mob, float speed) { + this->mob = mob; + this->speed = speed; + this->level = mob->level; + setRequiredControlFlags(Control::MoveControlFlag); } -bool FleeSunGoal::canUse() -{ - if (!level->isDay()) return false; - if (!mob->isOnFire()) return false; - if (!level->canSeeSky(Mth::floor(mob->x), (int) mob->bb->y0, Mth::floor(mob->z))) return false; +bool FleeSunGoal::canUse() { + if (!level->isDay()) return false; + if (!mob->isOnFire()) return false; + if (!level->canSeeSky(Mth::floor(mob->x), (int)mob->bb->y0, + Mth::floor(mob->z))) + return false; - Vec3 *pos = getHidePos(); - if (pos == NULL) return false; - wantedX = pos->x; - wantedY = pos->y; - wantedZ = pos->z; - return true; + Vec3* pos = getHidePos(); + if (pos == NULL) return false; + wantedX = pos->x; + wantedY = pos->y; + wantedZ = pos->z; + return true; } -bool FleeSunGoal::canContinueToUse() -{ - return !mob->getNavigation()->isDone(); +bool FleeSunGoal::canContinueToUse() { return !mob->getNavigation()->isDone(); } + +void FleeSunGoal::start() { + mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); } -void FleeSunGoal::start() -{ - mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); -} - -Vec3 *FleeSunGoal::getHidePos() -{ - Random *random = mob->getRandom(); - for (int i = 0; i < 10; i++) - { - int xt = Mth::floor(mob->x + random->nextInt(20) - 10); - int yt = Mth::floor(mob->bb->y0 + random->nextInt(6) - 3); - int zt = Mth::floor(mob->z + random->nextInt(20) - 10); - if (!level->canSeeSky(xt, yt, zt) && mob->getWalkTargetValue(xt, yt, zt) < 0) return Vec3::newTemp(xt, yt, zt); - } - return NULL; +Vec3* FleeSunGoal::getHidePos() { + Random* random = mob->getRandom(); + for (int i = 0; i < 10; i++) { + int xt = Mth::floor(mob->x + random->nextInt(20) - 10); + int yt = Mth::floor(mob->bb->y0 + random->nextInt(6) - 3); + int zt = Mth::floor(mob->z + random->nextInt(20) - 10); + if (!level->canSeeSky(xt, yt, zt) && + mob->getWalkTargetValue(xt, yt, zt) < 0) + return Vec3::newTemp(xt, yt, zt); + } + return NULL; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FleeSunGoal.h b/Minecraft.World/AI/Goals/FleeSunGoal.h index 9d26c9f65..cfec75fe9 100644 --- a/Minecraft.World/AI/Goals/FleeSunGoal.h +++ b/Minecraft.World/AI/Goals/FleeSunGoal.h @@ -2,25 +2,25 @@ #include "Goal.h" -class FleeSunGoal : public Goal -{ +class FleeSunGoal : public Goal { private: - PathfinderMob *mob; // Owner of this goal - double wantedX, wantedY, wantedZ; - float speed; - Level *level; + PathfinderMob* mob; // Owner of this goal + double wantedX, wantedY, wantedZ; + float speed; + Level* level; public: - FleeSunGoal(PathfinderMob *mob, float speed); + FleeSunGoal(PathfinderMob* mob, float speed); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); private: - Vec3 *getHidePos(); + Vec3* getHidePos(); public: - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FloatGoal.cpp b/Minecraft.World/AI/Goals/FloatGoal.cpp index 8ac4e86d0..e69794d0e 100644 --- a/Minecraft.World/AI/Goals/FloatGoal.cpp +++ b/Minecraft.World/AI/Goals/FloatGoal.cpp @@ -4,19 +4,14 @@ #include "../../Headers/net.minecraft.world.entity.ai.navigation.h" #include "FloatGoal.h" -FloatGoal::FloatGoal(Mob *mob) -{ - this->mob = mob; - setRequiredControlFlags(Control::JumpControlFlag); - mob->getNavigation()->setCanFloat(true); +FloatGoal::FloatGoal(Mob* mob) { + this->mob = mob; + setRequiredControlFlags(Control::JumpControlFlag); + mob->getNavigation()->setCanFloat(true); } -bool FloatGoal::canUse() -{ - return (mob->isInWater() || mob->isInLava()); -} +bool FloatGoal::canUse() { return (mob->isInWater() || mob->isInLava()); } -void FloatGoal::tick() -{ - if (mob->getRandom()->nextFloat() < 0.8f) mob->getJumpControl()->jump(); +void FloatGoal::tick() { + if (mob->getRandom()->nextFloat() < 0.8f) mob->getJumpControl()->jump(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FloatGoal.h b/Minecraft.World/AI/Goals/FloatGoal.h index 0a24ced9b..8e55d7fb6 100644 --- a/Minecraft.World/AI/Goals/FloatGoal.h +++ b/Minecraft.World/AI/Goals/FloatGoal.h @@ -4,14 +4,13 @@ class Mob; -class FloatGoal : public Goal -{ +class FloatGoal : public Goal { private: - Mob *mob; + Mob* mob; public: - FloatGoal(Mob *mob); + FloatGoal(Mob* mob); - virtual bool canUse(); - virtual void tick(); + virtual bool canUse(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FollowOwnerGoal.cpp b/Minecraft.World/AI/Goals/FollowOwnerGoal.cpp index 51be176f2..1bfd657c4 100644 --- a/Minecraft.World/AI/Goals/FollowOwnerGoal.cpp +++ b/Minecraft.World/AI/Goals/FollowOwnerGoal.cpp @@ -7,79 +7,80 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "FollowOwnerGoal.h" -FollowOwnerGoal::FollowOwnerGoal(TamableAnimal *tamable, float speed, float startDistance, float stopDistance) -{ - owner = std::weak_ptr(); - timeToRecalcPath = 0; - oldAvoidWater = false; +FollowOwnerGoal::FollowOwnerGoal(TamableAnimal* tamable, float speed, + float startDistance, float stopDistance) { + owner = std::weak_ptr(); + timeToRecalcPath = 0; + oldAvoidWater = false; - this->tamable = tamable; - this->level = tamable->level; - this->speed = speed; - this->navigation = tamable->getNavigation(); - this->startDistance = startDistance; - this->stopDistance = stopDistance; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->tamable = tamable; + this->level = tamable->level; + this->speed = speed; + this->navigation = tamable->getNavigation(); + this->startDistance = startDistance; + this->stopDistance = stopDistance; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool FollowOwnerGoal::canUse() -{ - std::shared_ptr owner = tamable->getOwner(); - if (owner == NULL) return false; - if (tamable->isSitting()) return false; - if (tamable->distanceToSqr(owner) < startDistance * startDistance) return false; - this->owner = std::weak_ptr(owner); - return true; +bool FollowOwnerGoal::canUse() { + std::shared_ptr owner = tamable->getOwner(); + if (owner == NULL) return false; + if (tamable->isSitting()) return false; + if (tamable->distanceToSqr(owner) < startDistance * startDistance) + return false; + this->owner = std::weak_ptr(owner); + return true; } -bool FollowOwnerGoal::canContinueToUse() -{ - return owner.lock() != NULL && !navigation->isDone() && tamable->distanceToSqr(owner.lock()) > stopDistance * stopDistance && !tamable->isSitting(); +bool FollowOwnerGoal::canContinueToUse() { + return owner.lock() != NULL && !navigation->isDone() && + tamable->distanceToSqr(owner.lock()) > stopDistance * stopDistance && + !tamable->isSitting(); } -void FollowOwnerGoal::start() -{ - timeToRecalcPath = 0; - oldAvoidWater = tamable->getNavigation()->getAvoidWater(); - tamable->getNavigation()->setAvoidWater(false); +void FollowOwnerGoal::start() { + timeToRecalcPath = 0; + oldAvoidWater = tamable->getNavigation()->getAvoidWater(); + tamable->getNavigation()->setAvoidWater(false); } -void FollowOwnerGoal::stop() -{ - owner = std::weak_ptr(); - navigation->stop(); - tamable->getNavigation()->setAvoidWater(oldAvoidWater); +void FollowOwnerGoal::stop() { + owner = std::weak_ptr(); + navigation->stop(); + tamable->getNavigation()->setAvoidWater(oldAvoidWater); } -void FollowOwnerGoal::tick() -{ - tamable->getLookControl()->setLookAt(owner.lock(), 10, tamable->getMaxHeadXRot()); - if (tamable->isSitting()) return; +void FollowOwnerGoal::tick() { + tamable->getLookControl()->setLookAt(owner.lock(), 10, + tamable->getMaxHeadXRot()); + if (tamable->isSitting()) return; - if (--timeToRecalcPath > 0) return; - timeToRecalcPath = 10; + if (--timeToRecalcPath > 0) return; + timeToRecalcPath = 10; - if (navigation->moveTo(owner.lock(), speed)) return; - if (tamable->distanceToSqr(owner.lock()) < TeleportDistance * TeleportDistance) return; + if (navigation->moveTo(owner.lock(), speed)) return; + if (tamable->distanceToSqr(owner.lock()) < + TeleportDistance * TeleportDistance) + return; - // find a good spawn position nearby the owner - int sx = Mth::floor(owner.lock()->x) - 2; - int sz = Mth::floor(owner.lock()->z) - 2; - int y = Mth::floor(owner.lock()->bb->y0); - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 4; z++) - { - if (x >= 1 && z >= 1 && x <= 3 && z <= 3) - { - continue; - } - if (level->isTopSolidBlocking(sx + x, y - 1, sz + z) && !level->isSolidBlockingTile(sx + x, y, sz + z) && !level->isSolidBlockingTile(sx + x, y + 1, sz + z)) - { - tamable->moveTo(sx + x + .5f, y, sz + z + .5f, tamable->yRot, tamable->xRot); - navigation->stop(); - return; - } - } - } + // find a good spawn position nearby the owner + int sx = Mth::floor(owner.lock()->x) - 2; + int sz = Mth::floor(owner.lock()->z) - 2; + int y = Mth::floor(owner.lock()->bb->y0); + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 4; z++) { + if (x >= 1 && z >= 1 && x <= 3 && z <= 3) { + continue; + } + if (level->isTopSolidBlocking(sx + x, y - 1, sz + z) && + !level->isSolidBlockingTile(sx + x, y, sz + z) && + !level->isSolidBlockingTile(sx + x, y + 1, sz + z)) { + tamable->moveTo(sx + x + .5f, y, sz + z + .5f, tamable->yRot, + tamable->xRot); + navigation->stop(); + return; + } + } + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FollowOwnerGoal.h b/Minecraft.World/AI/Goals/FollowOwnerGoal.h index ff9aaf5d1..5ec293492 100644 --- a/Minecraft.World/AI/Goals/FollowOwnerGoal.h +++ b/Minecraft.World/AI/Goals/FollowOwnerGoal.h @@ -5,30 +5,31 @@ class PathNavigation; class TamableAnimal; -class FollowOwnerGoal : public Goal -{ +class FollowOwnerGoal : public Goal { public: - static const int TeleportDistance = 12; + static const int TeleportDistance = 12; private: - TamableAnimal *tamable; // Owner of this goal - std::weak_ptr owner; - Level *level; - float speed; - PathNavigation *navigation; - int timeToRecalcPath; - float stopDistance, startDistance; - bool oldAvoidWater; + TamableAnimal* tamable; // Owner of this goal + std::weak_ptr owner; + Level* level; + float speed; + PathNavigation* navigation; + int timeToRecalcPath; + float stopDistance, startDistance; + bool oldAvoidWater; public: - FollowOwnerGoal(TamableAnimal *tamable, float speed, float startDistance, float stopDistance); + FollowOwnerGoal(TamableAnimal* tamable, float speed, float startDistance, + float stopDistance); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); - - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); + + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FollowParentGoal.cpp b/Minecraft.World/AI/Goals/FollowParentGoal.cpp index 7f0bb3940..56aab1871 100644 --- a/Minecraft.World/AI/Goals/FollowParentGoal.cpp +++ b/Minecraft.World/AI/Goals/FollowParentGoal.cpp @@ -6,60 +6,51 @@ #include "../../Util/BasicTypeContainers.h" #include "FollowParentGoal.h" -FollowParentGoal::FollowParentGoal(Animal *animal, float speed) -{ - timeToRecalcPath = 0; +FollowParentGoal::FollowParentGoal(Animal* animal, float speed) { + timeToRecalcPath = 0; - this->animal = animal; - this->speed = speed; + this->animal = animal; + this->speed = speed; } -bool FollowParentGoal::canUse() -{ - if (animal->getAge() >= 0) return false; +bool FollowParentGoal::canUse() { + if (animal->getAge() >= 0) return false; - std::vector > *parents = animal->level->getEntitiesOfClass(typeid(*animal), animal->bb->grow(8, 4, 8)); + std::vector >* parents = + animal->level->getEntitiesOfClass(typeid(*animal), + animal->bb->grow(8, 4, 8)); - std::shared_ptr closest = nullptr; - double closestDistSqr = Double::MAX_VALUE; - for(AUTO_VAR(it, parents->begin()); it != parents->end(); ++it) - { - std::shared_ptr parent = std::dynamic_pointer_cast(*it); - if (parent->getAge() < 0) continue; - double distSqr = animal->distanceToSqr(parent); - if (distSqr > closestDistSqr) continue; - closestDistSqr = distSqr; - closest = parent; - } - delete parents; + std::shared_ptr closest = nullptr; + double closestDistSqr = Double::MAX_VALUE; + for (AUTO_VAR(it, parents->begin()); it != parents->end(); ++it) { + std::shared_ptr parent = std::dynamic_pointer_cast(*it); + if (parent->getAge() < 0) continue; + double distSqr = animal->distanceToSqr(parent); + if (distSqr > closestDistSqr) continue; + closestDistSqr = distSqr; + closest = parent; + } + delete parents; - if (closest == NULL) return false; - if (closestDistSqr < 3 * 3) return false; - parent = std::weak_ptr(closest); - return true; + if (closest == NULL) return false; + if (closestDistSqr < 3 * 3) return false; + parent = std::weak_ptr(closest); + return true; } -bool FollowParentGoal::canContinueToUse() -{ - if (parent.lock() == NULL || !parent.lock()->isAlive()) return false; - double distSqr = animal->distanceToSqr(parent.lock()); - if (distSqr < 3 * 3 || distSqr > 16 * 16) return false; - return true; +bool FollowParentGoal::canContinueToUse() { + if (parent.lock() == NULL || !parent.lock()->isAlive()) return false; + double distSqr = animal->distanceToSqr(parent.lock()); + if (distSqr < 3 * 3 || distSqr > 16 * 16) return false; + return true; } -void FollowParentGoal::start() -{ - timeToRecalcPath = 0; -} +void FollowParentGoal::start() { timeToRecalcPath = 0; } -void FollowParentGoal::stop() -{ - parent = std::weak_ptr(); -} +void FollowParentGoal::stop() { parent = std::weak_ptr(); } -void FollowParentGoal::tick() -{ - if (--timeToRecalcPath > 0) return; - timeToRecalcPath = 10; - animal->getNavigation()->moveTo(parent.lock(), speed); +void FollowParentGoal::tick() { + if (--timeToRecalcPath > 0) return; + timeToRecalcPath = 10; + animal->getNavigation()->moveTo(parent.lock(), speed); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/FollowParentGoal.h b/Minecraft.World/AI/Goals/FollowParentGoal.h index a48a48cb8..3295fc070 100644 --- a/Minecraft.World/AI/Goals/FollowParentGoal.h +++ b/Minecraft.World/AI/Goals/FollowParentGoal.h @@ -4,20 +4,19 @@ class Animal; -class FollowParentGoal : public Goal -{ +class FollowParentGoal : public Goal { private: - Animal *animal; // Owner of this goal - std::weak_ptr parent; - float speed; - int timeToRecalcPath; + Animal* animal; // Owner of this goal + std::weak_ptr parent; + float speed; + int timeToRecalcPath; public: - FollowParentGoal(Animal *animal, float speed); + FollowParentGoal(Animal* animal, float speed); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/Goal.cpp b/Minecraft.World/AI/Goals/Goal.cpp index b5b3c3501..e4ea68fb4 100644 --- a/Minecraft.World/AI/Goals/Goal.cpp +++ b/Minecraft.World/AI/Goals/Goal.cpp @@ -1,39 +1,20 @@ #include "../../Platform/stdafx.h" #include "Goal.h" -Goal::Goal() -{ - _requiredControlFlags = 0; +Goal::Goal() { _requiredControlFlags = 0; } + +bool Goal::canContinueToUse() { return canUse(); } + +bool Goal::canInterrupt() { return true; } + +void Goal::start() {} + +void Goal::stop() {} + +void Goal::tick() {} + +void Goal::setRequiredControlFlags(int requiredControlFlags) { + _requiredControlFlags = requiredControlFlags; } -bool Goal::canContinueToUse() -{ - return canUse(); -} - -bool Goal::canInterrupt() -{ - return true; -} - -void Goal::start() -{ -} - -void Goal::stop() -{ -} - -void Goal::tick() -{ -} - -void Goal::setRequiredControlFlags(int requiredControlFlags) -{ - _requiredControlFlags = requiredControlFlags; -} - -int Goal::getRequiredControlFlags() -{ - return _requiredControlFlags; -} \ No newline at end of file +int Goal::getRequiredControlFlags() { return _requiredControlFlags; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/Goal.h b/Minecraft.World/AI/Goals/Goal.h index 80d39b9ba..89e941de1 100644 --- a/Minecraft.World/AI/Goals/Goal.h +++ b/Minecraft.World/AI/Goals/Goal.h @@ -1,23 +1,24 @@ #pragma once -class Goal -{ +class Goal { private: - int _requiredControlFlags; + int _requiredControlFlags; protected: - Goal(); + Goal(); + public: - virtual ~Goal() {} - virtual bool canUse() = 0; - virtual bool canContinueToUse(); - virtual bool canInterrupt(); - virtual void start(); - virtual void stop(); - virtual void tick(); - virtual void setRequiredControlFlags(int requiredControlFlags); - virtual int getRequiredControlFlags(); - - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) {}; + virtual ~Goal() {} + virtual bool canUse() = 0; + virtual bool canContinueToUse(); + virtual bool canInterrupt(); + virtual void start(); + virtual void stop(); + virtual void tick(); + virtual void setRequiredControlFlags(int requiredControlFlags); + virtual int getRequiredControlFlags(); + + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) {}; }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/GoalSelector.cpp b/Minecraft.World/AI/Goals/GoalSelector.cpp index 270e5f355..738227020 100644 --- a/Minecraft.World/AI/Goals/GoalSelector.cpp +++ b/Minecraft.World/AI/Goals/GoalSelector.cpp @@ -2,146 +2,124 @@ #include "Goal.h" #include "GoalSelector.h" - -GoalSelector::InternalGoal::InternalGoal(int prio, Goal *goal, bool canDeletePointer) -{ - this->prio = prio; - this->goal = goal; - this->canDeletePointer = canDeletePointer; +GoalSelector::InternalGoal::InternalGoal(int prio, Goal* goal, + bool canDeletePointer) { + this->prio = prio; + this->goal = goal; + this->canDeletePointer = canDeletePointer; } -GoalSelector::GoalSelector() -{ - tickCount = 0; - newGoalRate = 3; +GoalSelector::GoalSelector() { + tickCount = 0; + newGoalRate = 3; } -GoalSelector::~GoalSelector() -{ - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) - { - if((*it)->canDeletePointer) delete (*it)->goal; - delete (*it); - } +GoalSelector::~GoalSelector() { + for (AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) { + if ((*it)->canDeletePointer) delete (*it)->goal; + delete (*it); + } } -void GoalSelector::addGoal(int prio, Goal *goal, bool canDeletePointer /*= true*/) // 4J Added canDelete param +void GoalSelector::addGoal( + int prio, Goal* goal, + bool canDeletePointer /*= true*/) // 4J Added canDelete param { - goals.push_back(new InternalGoal(prio, goal, canDeletePointer)); + goals.push_back(new InternalGoal(prio, goal, canDeletePointer)); } -void GoalSelector::tick() -{ - std::vector toStart; +void GoalSelector::tick() { + std::vector toStart; - if(tickCount++ % newGoalRate == 0) - { - //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) - { - InternalGoal *ig = *it; - //bool isUsing = usingGoals.contains(ig); - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + if (tickCount++ % newGoalRate == 0) { + // for (InternalGoal ig : goals) + for (AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) { + InternalGoal* ig = *it; + // bool isUsing = usingGoals.contains(ig); + AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); - //if (isUsing) - if(usingIt != usingGoals.end()) - { - if (!canUseInSystem(ig) || !canContinueToUse(ig)) - { - ig->goal->stop(); - //usingGoals.remove(ig); - usingGoals.erase(usingIt); - } - else continue; - } + // if (isUsing) + if (usingIt != usingGoals.end()) { + if (!canUseInSystem(ig) || !canContinueToUse(ig)) { + ig->goal->stop(); + // usingGoals.remove(ig); + usingGoals.erase(usingIt); + } else + continue; + } - if (!canUseInSystem(ig) || !ig->goal->canUse()) continue; + if (!canUseInSystem(ig) || !ig->goal->canUse()) continue; - toStart.push_back(ig); - usingGoals.push_back(ig); - } - } - else - { - for(AUTO_VAR(it, usingGoals.begin() ); it != usingGoals.end(); ) - { - InternalGoal *ig = *it; - if (!ig->goal->canContinueToUse()) - { - ig->goal->stop(); - it = usingGoals.erase(it); - } - else - { - ++it; - } - } - } + toStart.push_back(ig); + usingGoals.push_back(ig); + } + } else { + for (AUTO_VAR(it, usingGoals.begin()); it != usingGoals.end();) { + InternalGoal* ig = *it; + if (!ig->goal->canContinueToUse()) { + ig->goal->stop(); + it = usingGoals.erase(it); + } else { + ++it; + } + } + } + // bool debug = false; + // if (debug && toStart.size() > 0) System.out.println("Starting: "); + // for (InternalGoal ig : toStart) + for (AUTO_VAR(it, toStart.begin()); it != toStart.end(); ++it) { + // if (debug) System.out.println(ig.goal.toString() + ", "); + (*it)->goal->start(); + } - //bool debug = false; - //if (debug && toStart.size() > 0) System.out.println("Starting: "); - //for (InternalGoal ig : toStart) - for(AUTO_VAR(it, toStart.begin()); it != toStart.end(); ++it) - { - //if (debug) System.out.println(ig.goal.toString() + ", "); - (*it)->goal->start(); - } - - //if (debug && usingGoals.size() > 0) System.out.println("Running: "); - //for (InternalGoal ig : usingGoals) - for(AUTO_VAR(it, usingGoals.begin()); it != usingGoals.end(); ++it) - { - //if (debug) System.out.println(ig.goal.toString()); - (*it)->goal->tick(); - } + // if (debug && usingGoals.size() > 0) System.out.println("Running: "); + // for (InternalGoal ig : usingGoals) + for (AUTO_VAR(it, usingGoals.begin()); it != usingGoals.end(); ++it) { + // if (debug) System.out.println(ig.goal.toString()); + (*it)->goal->tick(); + } } -std::vector *GoalSelector::getRunningGoals() -{ - return &usingGoals; +std::vector* GoalSelector::getRunningGoals() { + return &usingGoals; } -bool GoalSelector::canContinueToUse(InternalGoal *ig) -{ - return ig->goal->canContinueToUse(); +bool GoalSelector::canContinueToUse(InternalGoal* ig) { + return ig->goal->canContinueToUse(); } -bool GoalSelector::canUseInSystem(GoalSelector::InternalGoal *goal) -{ - //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) - { - InternalGoal *ig = *it; - if (ig == goal) continue; +bool GoalSelector::canUseInSystem(GoalSelector::InternalGoal* goal) { + // for (InternalGoal ig : goals) + for (AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) { + InternalGoal* ig = *it; + if (ig == goal) continue; - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); - if (goal->prio >= ig->prio) - { - if (usingIt != usingGoals.end() && !canCoExist(goal, ig)) return false; - } - else if (usingIt != usingGoals.end() && !ig->goal->canInterrupt()) return false; - } + if (goal->prio >= ig->prio) { + if (usingIt != usingGoals.end() && !canCoExist(goal, ig)) + return false; + } else if (usingIt != usingGoals.end() && !ig->goal->canInterrupt()) + return false; + } - return true; + return true; } -bool GoalSelector::canCoExist(GoalSelector::InternalGoal *goalA, GoalSelector::InternalGoal *goalB) -{ - return (goalA->goal->getRequiredControlFlags() & goalB->goal->getRequiredControlFlags()) == 0; +bool GoalSelector::canCoExist(GoalSelector::InternalGoal* goalA, + GoalSelector::InternalGoal* goalB) { + return (goalA->goal->getRequiredControlFlags() & + goalB->goal->getRequiredControlFlags()) == 0; } -void GoalSelector::setNewGoalRate(int newGoalRate) -{ - this->newGoalRate = newGoalRate; +void GoalSelector::setNewGoalRate(int newGoalRate) { + this->newGoalRate = newGoalRate; } -void GoalSelector::setLevel(Level *level) -{ - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) - { - InternalGoal *ig = *it; - ig->goal->setLevel(level); - } +void GoalSelector::setLevel(Level* level) { + for (AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) { + InternalGoal* ig = *it; + ig->goal->setLevel(level); + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/GoalSelector.h b/Minecraft.World/AI/Goals/GoalSelector.h index f4724f56e..aeefe1a70 100644 --- a/Minecraft.World/AI/Goals/GoalSelector.h +++ b/Minecraft.World/AI/Goals/GoalSelector.h @@ -1,45 +1,43 @@ #pragma once - class Goal; -class GoalSelector -{ +class GoalSelector { private: - class InternalGoal - { - public: - // 4J Added canDelete param - InternalGoal(int prio, Goal *goal, bool canDeletePointer); + class InternalGoal { + public: + // 4J Added canDelete param + InternalGoal(int prio, Goal* goal, bool canDeletePointer); - Goal *goal; - int prio; - bool canDeletePointer; - }; + Goal* goal; + int prio; + bool canDeletePointer; + }; private: - std::vector goals; - std::vector usingGoals; - int tickCount; - int newGoalRate; + std::vector goals; + std::vector usingGoals; + int tickCount; + int newGoalRate; public: - GoalSelector(); - ~GoalSelector(); + GoalSelector(); + ~GoalSelector(); - // 4J Added canDelete param - void addGoal(int prio, Goal *goal, bool canDeletePointer = true); - void tick(); - std::vector *getRunningGoals(); + // 4J Added canDelete param + void addGoal(int prio, Goal* goal, bool canDeletePointer = true); + void tick(); + std::vector* getRunningGoals(); private: - bool canContinueToUse(InternalGoal *ig); - bool canUseInSystem(InternalGoal *goal); - bool canCoExist(InternalGoal *goalA, InternalGoal *goalB); + bool canContinueToUse(InternalGoal* ig); + bool canUseInSystem(InternalGoal* goal); + bool canCoExist(InternalGoal* goalA, InternalGoal* goalB); public: - void setNewGoalRate(int newGoalRate); + void setNewGoalRate(int newGoalRate); - // 4J Added override to update ai elements when loading entity from schematics - void setLevel(Level *level); + // 4J Added override to update ai elements when loading entity from + // schematics + void setLevel(Level* level); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/HurtByTargetGoal.cpp b/Minecraft.World/AI/Goals/HurtByTargetGoal.cpp index 482e74773..2f0d3b05d 100644 --- a/Minecraft.World/AI/Goals/HurtByTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/HurtByTargetGoal.cpp @@ -4,42 +4,41 @@ #include "../../Headers/net.minecraft.world.level.h" #include "HurtByTargetGoal.h" -HurtByTargetGoal::HurtByTargetGoal(Mob *mob, bool alertSameType) : TargetGoal(mob, 16, false) -{ - this->alertSameType = alertSameType; - setRequiredControlFlags(TargetGoal::TargetFlag); +HurtByTargetGoal::HurtByTargetGoal(Mob* mob, bool alertSameType) + : TargetGoal(mob, 16, false) { + this->alertSameType = alertSameType; + setRequiredControlFlags(TargetGoal::TargetFlag); } -bool HurtByTargetGoal::canUse() -{ - return canAttack(mob->getLastHurtByMob(), false); +bool HurtByTargetGoal::canUse() { + return canAttack(mob->getLastHurtByMob(), false); } -void HurtByTargetGoal::start() -{ - mob->setTarget(mob->getLastHurtByMob()); - oldHurtByMob = mob->getLastHurtByMob(); +void HurtByTargetGoal::start() { + mob->setTarget(mob->getLastHurtByMob()); + oldHurtByMob = mob->getLastHurtByMob(); - if (alertSameType) - { - std::vector > *nearby = mob->level->getEntitiesOfClass(typeid(*mob), AABB::newTemp(mob->x, mob->y, mob->z, mob->x + 1, mob->y + 1, mob->z + 1)->grow(within, 4, within)); - for(AUTO_VAR(it, nearby->begin()); it != nearby->end(); ++it) - { - std::shared_ptr other = std::dynamic_pointer_cast(*it); - if (this->mob->shared_from_this() == other) continue; - if (other->getTarget() != NULL) continue; - other->setTarget(mob->getLastHurtByMob()); - } - delete nearby; - } + if (alertSameType) { + std::vector >* nearby = + mob->level->getEntitiesOfClass( + typeid(*mob), AABB::newTemp(mob->x, mob->y, mob->z, mob->x + 1, + mob->y + 1, mob->z + 1) + ->grow(within, 4, within)); + for (AUTO_VAR(it, nearby->begin()); it != nearby->end(); ++it) { + std::shared_ptr other = std::dynamic_pointer_cast(*it); + if (this->mob->shared_from_this() == other) continue; + if (other->getTarget() != NULL) continue; + other->setTarget(mob->getLastHurtByMob()); + } + delete nearby; + } - TargetGoal::start(); + TargetGoal::start(); } -void HurtByTargetGoal::tick() -{ - if (mob->getLastHurtByMob() != NULL && mob->getLastHurtByMob() != oldHurtByMob) - { - this->start(); - } +void HurtByTargetGoal::tick() { + if (mob->getLastHurtByMob() != NULL && + mob->getLastHurtByMob() != oldHurtByMob) { + this->start(); + } } diff --git a/Minecraft.World/AI/Goals/HurtByTargetGoal.h b/Minecraft.World/AI/Goals/HurtByTargetGoal.h index b731fc398..9560728bc 100644 --- a/Minecraft.World/AI/Goals/HurtByTargetGoal.h +++ b/Minecraft.World/AI/Goals/HurtByTargetGoal.h @@ -2,16 +2,15 @@ #include "TargetGoal.h" -class HurtByTargetGoal : public TargetGoal -{ +class HurtByTargetGoal : public TargetGoal { private: - bool alertSameType; - std::shared_ptr oldHurtByMob; + bool alertSameType; + std::shared_ptr oldHurtByMob; public: - HurtByTargetGoal(Mob *mob, bool alertSameType); + HurtByTargetGoal(Mob* mob, bool alertSameType); - bool canUse(); - void start(); - void tick(); + bool canUse(); + void start(); + void tick(); }; diff --git a/Minecraft.World/AI/Goals/InteractGoal.cpp b/Minecraft.World/AI/Goals/InteractGoal.cpp index 3e225fd80..bb70da2d3 100644 --- a/Minecraft.World/AI/Goals/InteractGoal.cpp +++ b/Minecraft.World/AI/Goals/InteractGoal.cpp @@ -2,12 +2,16 @@ #include "../../Headers/net.minecraft.world.entity.ai.control.h" #include "InteractGoal.h" -InteractGoal::InteractGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance) : LookAtPlayerGoal(mob, lookAtType, lookDistance) -{ - setRequiredControlFlags(Control::LookControlFlag | Control::MoveControlFlag); +InteractGoal::InteractGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance) + : LookAtPlayerGoal(mob, lookAtType, lookDistance) { + setRequiredControlFlags(Control::LookControlFlag | + Control::MoveControlFlag); } -InteractGoal::InteractGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance, float probability) : LookAtPlayerGoal(mob, lookAtType, lookDistance, probability) -{ - setRequiredControlFlags(Control::LookControlFlag | Control::MoveControlFlag); +InteractGoal::InteractGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance, float probability) + : LookAtPlayerGoal(mob, lookAtType, lookDistance, probability) { + setRequiredControlFlags(Control::LookControlFlag | + Control::MoveControlFlag); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/InteractGoal.h b/Minecraft.World/AI/Goals/InteractGoal.h index 2d7f3ea5e..5b6011f16 100644 --- a/Minecraft.World/AI/Goals/InteractGoal.h +++ b/Minecraft.World/AI/Goals/InteractGoal.h @@ -2,9 +2,10 @@ #include "LookAtPlayerGoal.h" -class InteractGoal : public LookAtPlayerGoal -{ +class InteractGoal : public LookAtPlayerGoal { public: - InteractGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance); - InteractGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance, float probability); + InteractGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance); + InteractGoal(Mob* mob, const std::type_info& lookAtType, float lookDistance, + float probability); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/LeapAtTargetGoal.cpp b/Minecraft.World/AI/Goals/LeapAtTargetGoal.cpp index 6ee967147..f8b96ae35 100644 --- a/Minecraft.World/AI/Goals/LeapAtTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/LeapAtTargetGoal.cpp @@ -3,38 +3,35 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "LeapAtTargetGoal.h" -LeapAtTargetGoal::LeapAtTargetGoal(Mob *mob, float yd) -{ - target = std::weak_ptr(); +LeapAtTargetGoal::LeapAtTargetGoal(Mob* mob, float yd) { + target = std::weak_ptr(); - this->mob = mob; - this->yd = yd; - setRequiredControlFlags(Control::JumpControlFlag | Control::MoveControlFlag); + this->mob = mob; + this->yd = yd; + setRequiredControlFlags(Control::JumpControlFlag | + Control::MoveControlFlag); } -bool LeapAtTargetGoal::canUse() -{ - target = std::weak_ptr(mob->getTarget()); - if (target.lock() == NULL) return false; - double d = mob->distanceToSqr(target.lock()); - if (d < 2 * 2 || d > 4 * 4) return false; - if (!mob->onGround) return false; - if (mob->getRandom()->nextInt(5) != 0) return false; - return true; +bool LeapAtTargetGoal::canUse() { + target = std::weak_ptr(mob->getTarget()); + if (target.lock() == NULL) return false; + double d = mob->distanceToSqr(target.lock()); + if (d < 2 * 2 || d > 4 * 4) return false; + if (!mob->onGround) return false; + if (mob->getRandom()->nextInt(5) != 0) return false; + return true; } -bool LeapAtTargetGoal::canContinueToUse() -{ - return target.lock() != NULL && !mob->onGround; +bool LeapAtTargetGoal::canContinueToUse() { + return target.lock() != NULL && !mob->onGround; } -void LeapAtTargetGoal::start() -{ - // TODO: move to control? - double xdd = target.lock()->x - mob->x; - double zdd = target.lock()->z - mob->z; - float dd = sqrt(xdd * xdd + zdd * zdd); - mob->xd += (xdd / dd * 0.5f) * 0.8f + mob->xd * 0.2f; - mob->zd += (zdd / dd * 0.5f) * 0.8f + mob->zd * 0.2f; - mob->yd = yd; +void LeapAtTargetGoal::start() { + // TODO: move to control? + double xdd = target.lock()->x - mob->x; + double zdd = target.lock()->z - mob->z; + float dd = sqrt(xdd * xdd + zdd * zdd); + mob->xd += (xdd / dd * 0.5f) * 0.8f + mob->xd * 0.2f; + mob->zd += (zdd / dd * 0.5f) * 0.8f + mob->zd * 0.2f; + mob->yd = yd; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/LeapAtTargetGoal.h b/Minecraft.World/AI/Goals/LeapAtTargetGoal.h index c34130062..3f5c49f61 100644 --- a/Minecraft.World/AI/Goals/LeapAtTargetGoal.h +++ b/Minecraft.World/AI/Goals/LeapAtTargetGoal.h @@ -2,15 +2,14 @@ #include "Goal.h" -class LeapAtTargetGoal : public Goal -{ +class LeapAtTargetGoal : public Goal { private: - Mob *mob; // Owner of this goal + Mob* mob; // Owner of this goal std::weak_ptr target; float yd; public: - LeapAtTargetGoal(Mob *mob, float yd); + LeapAtTargetGoal(Mob* mob, float yd); virtual bool canUse(); virtual bool canContinueToUse(); diff --git a/Minecraft.World/AI/Goals/LookAtPlayerGoal.cpp b/Minecraft.World/AI/Goals/LookAtPlayerGoal.cpp index e37e29097..d6d1b4d0f 100644 --- a/Minecraft.World/AI/Goals/LookAtPlayerGoal.cpp +++ b/Minecraft.World/AI/Goals/LookAtPlayerGoal.cpp @@ -5,53 +5,56 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "LookAtPlayerGoal.h" -LookAtPlayerGoal::LookAtPlayerGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance) : lookAtType(lookAtType) -{ - this->mob = mob; - this->lookDistance = lookDistance; - this->probability = 0.02f; - setRequiredControlFlags(Control::LookControlFlag); +LookAtPlayerGoal::LookAtPlayerGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance) + : lookAtType(lookAtType) { + this->mob = mob; + this->lookDistance = lookDistance; + this->probability = 0.02f; + setRequiredControlFlags(Control::LookControlFlag); - lookTime = 0; + lookTime = 0; } -LookAtPlayerGoal::LookAtPlayerGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance, float probability) : lookAtType(lookAtType) -{ - this->mob = mob; - this->lookDistance = lookDistance; - this->probability = probability; - setRequiredControlFlags(Control::LookControlFlag); +LookAtPlayerGoal::LookAtPlayerGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance, float probability) + : lookAtType(lookAtType) { + this->mob = mob; + this->lookDistance = lookDistance; + this->probability = probability; + setRequiredControlFlags(Control::LookControlFlag); - lookTime = 0; + lookTime = 0; } -bool LookAtPlayerGoal::canUse() -{ - if (mob->getRandom()->nextFloat() >= probability) return false; - if (lookAtType == typeid(Player)) lookAt = mob->level->getNearestPlayer(mob->shared_from_this(), lookDistance); - else lookAt = std::weak_ptr(mob->level->getClosestEntityOfClass(lookAtType, mob->bb->grow(lookDistance, 3, lookDistance), mob->shared_from_this())); - return lookAt.lock() != NULL; +bool LookAtPlayerGoal::canUse() { + if (mob->getRandom()->nextFloat() >= probability) return false; + if (lookAtType == typeid(Player)) + lookAt = + mob->level->getNearestPlayer(mob->shared_from_this(), lookDistance); + else + lookAt = std::weak_ptr(mob->level->getClosestEntityOfClass( + lookAtType, mob->bb->grow(lookDistance, 3, lookDistance), + mob->shared_from_this())); + return lookAt.lock() != NULL; } -bool LookAtPlayerGoal::canContinueToUse() -{ - if (lookAt.lock() == NULL || !lookAt.lock()->isAlive()) return false; - if (mob->distanceToSqr(lookAt.lock()) > lookDistance * lookDistance) return false; - return lookTime > 0; +bool LookAtPlayerGoal::canContinueToUse() { + if (lookAt.lock() == NULL || !lookAt.lock()->isAlive()) return false; + if (mob->distanceToSqr(lookAt.lock()) > lookDistance * lookDistance) + return false; + return lookTime > 0; } -void LookAtPlayerGoal::start() -{ - lookTime = 40 + mob->getRandom()->nextInt(40); +void LookAtPlayerGoal::start() { + lookTime = 40 + mob->getRandom()->nextInt(40); } -void LookAtPlayerGoal::stop() -{ - lookAt = std::weak_ptr(); -} +void LookAtPlayerGoal::stop() { lookAt = std::weak_ptr(); } -void LookAtPlayerGoal::tick() -{ - mob->getLookControl()->setLookAt(lookAt.lock()->x, lookAt.lock()->y + lookAt.lock()->getHeadHeight(), lookAt.lock()->z, 10, mob->getMaxHeadXRot()); - --lookTime; +void LookAtPlayerGoal::tick() { + mob->getLookControl()->setLookAt( + lookAt.lock()->x, lookAt.lock()->y + lookAt.lock()->getHeadHeight(), + lookAt.lock()->z, 10, mob->getMaxHeadXRot()); + --lookTime; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/LookAtPlayerGoal.h b/Minecraft.World/AI/Goals/LookAtPlayerGoal.h index 1aa80265d..146d55866 100644 --- a/Minecraft.World/AI/Goals/LookAtPlayerGoal.h +++ b/Minecraft.World/AI/Goals/LookAtPlayerGoal.h @@ -5,28 +5,29 @@ class Mob; class Level; -class LookAtPlayerGoal : public Goal -{ +class LookAtPlayerGoal : public Goal { private: - Mob *mob; // Owner of this goal + Mob* mob; // Owner of this goal protected: - std::weak_ptr lookAt; + std::weak_ptr lookAt; private: - float lookDistance; - int lookTime; - float probability; - const std::type_info& lookAtType; + float lookDistance; + int lookTime; + float probability; + const std::type_info& lookAtType; public: - LookAtPlayerGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance); - LookAtPlayerGoal(Mob *mob, const std::type_info& lookAtType, float lookDistance, float probability); - virtual ~LookAtPlayerGoal() {} + LookAtPlayerGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance); + LookAtPlayerGoal(Mob* mob, const std::type_info& lookAtType, + float lookDistance, float probability); + virtual ~LookAtPlayerGoal() {} - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.cpp b/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.cpp index e6bf36bed..00c733695 100644 --- a/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.cpp +++ b/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.cpp @@ -3,17 +3,16 @@ #include "../../Headers/net.minecraft.world.entity.npc.h" #include "LookAtTradingPlayerGoal.h" -LookAtTradingPlayerGoal::LookAtTradingPlayerGoal(Villager *villager) : LookAtPlayerGoal((Mob *)villager, typeid(Player), 8) -{ - this->villager = villager; +LookAtTradingPlayerGoal::LookAtTradingPlayerGoal(Villager* villager) + : LookAtPlayerGoal((Mob*)villager, typeid(Player), 8) { + this->villager = villager; } -bool LookAtTradingPlayerGoal::canUse() -{ - if (villager->isTrading()) - { - lookAt = std::weak_ptr(std::dynamic_pointer_cast(villager->getTradingPlayer())); - return true; - } - return false; +bool LookAtTradingPlayerGoal::canUse() { + if (villager->isTrading()) { + lookAt = std::weak_ptr( + std::dynamic_pointer_cast(villager->getTradingPlayer())); + return true; + } + return false; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.h b/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.h index bebc96fd1..7637a258d 100644 --- a/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.h +++ b/Minecraft.World/AI/Goals/LookAtTradingPlayerGoal.h @@ -4,13 +4,12 @@ class Villager; -class LookAtTradingPlayerGoal : public LookAtPlayerGoal -{ +class LookAtTradingPlayerGoal : public LookAtPlayerGoal { private: - Villager *villager; // This is the owner of this goal + Villager* villager; // This is the owner of this goal public: - LookAtTradingPlayerGoal(Villager *villager); + LookAtTradingPlayerGoal(Villager* villager); - virtual bool canUse(); + virtual bool canUse(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MakeLoveGoal.cpp b/Minecraft.World/AI/Goals/MakeLoveGoal.cpp index 3bac446bc..afc7c40c5 100644 --- a/Minecraft.World/AI/Goals/MakeLoveGoal.cpp +++ b/Minecraft.World/AI/Goals/MakeLoveGoal.cpp @@ -8,96 +8,95 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "MakeLoveGoal.h" -MakeLoveGoal::MakeLoveGoal(Villager *villager) -{ - village = std::weak_ptr(); - partner = std::weak_ptr(); - loveMakingTime = 0; +MakeLoveGoal::MakeLoveGoal(Villager* villager) { + village = std::weak_ptr(); + partner = std::weak_ptr(); + loveMakingTime = 0; - this->villager = villager; - level = villager->level; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->villager = villager; + level = villager->level; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool MakeLoveGoal::canUse() -{ +bool MakeLoveGoal::canUse() { + if (villager->getAge() != 0) return false; + if (villager->getRandom()->nextInt(500) != 0) return false; - if (villager->getAge() != 0) return false; - if (villager->getRandom()->nextInt(500) != 0) return false; + village = level->villages->getClosestVillage(Mth::floor(villager->x), + Mth::floor(villager->y), + Mth::floor(villager->z), 0); + if (village.lock() == NULL) return false; + if (!villageNeedsMoreVillagers()) return false; - village = level->villages->getClosestVillage(Mth::floor(villager->x), Mth::floor(villager->y), Mth::floor(villager->z), 0); - if (village.lock() == NULL) return false; - if (!villageNeedsMoreVillagers()) return false; + std::shared_ptr mate = level->getClosestEntityOfClass( + typeid(Villager), villager->bb->grow(8, 3, 8), + villager->shared_from_this()); + if (mate == NULL) return false; - std::shared_ptr mate = level->getClosestEntityOfClass(typeid(Villager), villager->bb->grow(8, 3, 8), villager->shared_from_this()); - if (mate == NULL) return false; + partner = + std::weak_ptr(std::dynamic_pointer_cast(mate)); + if (partner.lock()->getAge() != 0) return false; - partner = std::weak_ptr(std::dynamic_pointer_cast(mate)); - if (partner.lock()->getAge() != 0) return false; - - return true; + return true; } -void MakeLoveGoal::start() -{ - loveMakingTime = 300; - villager->setInLove(true); +void MakeLoveGoal::start() { + loveMakingTime = 300; + villager->setInLove(true); } -void MakeLoveGoal::stop() -{ - village = std::weak_ptr(); - partner = std::weak_ptr(); - villager->setInLove(false); +void MakeLoveGoal::stop() { + village = std::weak_ptr(); + partner = std::weak_ptr(); + villager->setInLove(false); } -bool MakeLoveGoal::canContinueToUse() -{ - return partner.lock() != NULL && loveMakingTime >= 0 && villageNeedsMoreVillagers() && villager->getAge() == 0; +bool MakeLoveGoal::canContinueToUse() { + return partner.lock() != NULL && loveMakingTime >= 0 && + villageNeedsMoreVillagers() && villager->getAge() == 0; } -void MakeLoveGoal::tick() -{ - --loveMakingTime; - villager->getLookControl()->setLookAt(partner.lock(), 10, 30); +void MakeLoveGoal::tick() { + --loveMakingTime; + villager->getLookControl()->setLookAt(partner.lock(), 10, 30); - if (villager->distanceToSqr(partner.lock()) > 1.5 * 1.5) - { - villager->getNavigation()->moveTo(partner.lock(), 0.25f); - } - else - { - if (loveMakingTime == 0 && partner.lock()->isInLove()) breed(); - } + if (villager->distanceToSqr(partner.lock()) > 1.5 * 1.5) { + villager->getNavigation()->moveTo(partner.lock(), 0.25f); + } else { + if (loveMakingTime == 0 && partner.lock()->isInLove()) breed(); + } - if (villager->getRandom()->nextInt(35) == 0) level->broadcastEntityEvent(villager->shared_from_this(), EntityEvent::LOVE_HEARTS); + if (villager->getRandom()->nextInt(35) == 0) + level->broadcastEntityEvent(villager->shared_from_this(), + EntityEvent::LOVE_HEARTS); } -bool MakeLoveGoal::villageNeedsMoreVillagers() -{ - std::shared_ptr _village = village.lock(); - if( _village == NULL ) return false; +bool MakeLoveGoal::villageNeedsMoreVillagers() { + std::shared_ptr _village = village.lock(); + if (_village == NULL) return false; - int idealSize = (int) ((float) _village->getDoorCount() * 0.35); - // System.out.println("idealSize: " + idealSize + " pop: " + - // village.getPopulationSize()); - return _village->getPopulationSize() < idealSize; + int idealSize = (int)((float)_village->getDoorCount() * 0.35); + // System.out.println("idealSize: " + idealSize + " pop: " + + // village.getPopulationSize()); + return _village->getPopulationSize() < idealSize; } -void MakeLoveGoal::breed() -{ - // 4J Stu - This sets a timer that stops these villagers from trying to breed again - // We should do this even if breeding fails due to vilalger count to stop them continually trying to breed - partner.lock()->setAge(5 * 60 * 20); - villager->setAge(5 * 60 * 20); - // 4J - added limit to number of animals that can be bred - if(level->canCreateMore( eTYPE_VILLAGER, Level::eSpawnType_Breed) ) - { - std::shared_ptr child = std::shared_ptr( new Villager(level) ); - child->setAge(-20 * 60 * 20); - child->setProfession(villager->getRandom()->nextInt(Villager::PROFESSION_MAX)); - child->moveTo(villager->x, villager->y, villager->z, 0, 0); - level->addEntity(child); - level->broadcastEntityEvent(child, EntityEvent::LOVE_HEARTS); - } +void MakeLoveGoal::breed() { + // 4J Stu - This sets a timer that stops these villagers from trying to + // breed again We should do this even if breeding fails due to vilalger + // count to stop them continually trying to breed + partner.lock()->setAge(5 * 60 * 20); + villager->setAge(5 * 60 * 20); + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(eTYPE_VILLAGER, Level::eSpawnType_Breed)) { + std::shared_ptr child = + std::shared_ptr(new Villager(level)); + child->setAge(-20 * 60 * 20); + child->setProfession( + villager->getRandom()->nextInt(Villager::PROFESSION_MAX)); + child->moveTo(villager->x, villager->y, villager->z, 0, 0); + level->addEntity(child); + level->broadcastEntityEvent(child, EntityEvent::LOVE_HEARTS); + } } diff --git a/Minecraft.World/AI/Goals/MakeLoveGoal.h b/Minecraft.World/AI/Goals/MakeLoveGoal.h index ea747efaf..c7ef79910 100644 --- a/Minecraft.World/AI/Goals/MakeLoveGoal.h +++ b/Minecraft.World/AI/Goals/MakeLoveGoal.h @@ -5,29 +5,29 @@ class Villager; class Village; -class MakeLoveGoal : public Goal -{ +class MakeLoveGoal : public Goal { private: - Villager *villager; // Owner of this goal - std::weak_ptr partner; - Level *level; - int loveMakingTime; - std::weak_ptr village; + Villager* villager; // Owner of this goal + std::weak_ptr partner; + Level* level; + int loveMakingTime; + std::weak_ptr village; public: - MakeLoveGoal(Villager *villager); + MakeLoveGoal(Villager* villager); - bool canUse(); - void start(); - void stop(); - bool canContinueToUse(); - void tick(); + bool canUse(); + void start(); + void stop(); + bool canContinueToUse(); + void tick(); private: - bool villageNeedsMoreVillagers(); - void breed(); + bool villageNeedsMoreVillagers(); + void breed(); -public: - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } +public: + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MeleeAttackGoal.cpp b/Minecraft.World/AI/Goals/MeleeAttackGoal.cpp index 80948c7fb..93b7d0fe4 100644 --- a/Minecraft.World/AI/Goals/MeleeAttackGoal.cpp +++ b/Minecraft.World/AI/Goals/MeleeAttackGoal.cpp @@ -9,89 +9,86 @@ #include "MeleeAttackGoal.h" #include "../Navigation/Path.h" -void MeleeAttackGoal::_init(Mob *mob, float speed, bool trackTarget) -{ - this->attackType = eTYPE_NOTSET; - this->mob = mob; - this->level = mob->level; - this->speed = speed; - this->trackTarget = trackTarget; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); +void MeleeAttackGoal::_init(Mob* mob, float speed, bool trackTarget) { + this->attackType = eTYPE_NOTSET; + this->mob = mob; + this->level = mob->level; + this->speed = speed; + this->trackTarget = trackTarget; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); - - attackTime = 0; - path = NULL; - timeToRecalcPath = 0; + attackTime = 0; + path = NULL; + timeToRecalcPath = 0; } -MeleeAttackGoal::MeleeAttackGoal(Mob *mob, eINSTANCEOF attackType, float speed, bool trackTarget) -{ - _init(mob, speed, trackTarget); - this->attackType = attackType; +MeleeAttackGoal::MeleeAttackGoal(Mob* mob, eINSTANCEOF attackType, float speed, + bool trackTarget) { + _init(mob, speed, trackTarget); + this->attackType = attackType; } -MeleeAttackGoal::MeleeAttackGoal(Mob *mob, float speed, bool trackTarget) -{ - _init(mob,speed,trackTarget); +MeleeAttackGoal::MeleeAttackGoal(Mob* mob, float speed, bool trackTarget) { + _init(mob, speed, trackTarget); } -MeleeAttackGoal::~MeleeAttackGoal() -{ - if(path != NULL) delete path; +MeleeAttackGoal::~MeleeAttackGoal() { + if (path != NULL) delete path; } -bool MeleeAttackGoal::canUse() -{ - std::shared_ptr bestTarget = mob->getTarget(); - if (bestTarget == NULL) return false; - if(!bestTarget->isAlive()) return false; - if (attackType != eTYPE_NOTSET && (attackType & bestTarget->GetType()) != attackType) return false; - target = std::weak_ptr(bestTarget); - delete path; - path = mob->getNavigation()->createPath(target.lock()); - return path != NULL; +bool MeleeAttackGoal::canUse() { + std::shared_ptr bestTarget = mob->getTarget(); + if (bestTarget == NULL) return false; + if (!bestTarget->isAlive()) return false; + if (attackType != eTYPE_NOTSET && + (attackType & bestTarget->GetType()) != attackType) + return false; + target = std::weak_ptr(bestTarget); + delete path; + path = mob->getNavigation()->createPath(target.lock()); + return path != NULL; } -bool MeleeAttackGoal::canContinueToUse() -{ - std::shared_ptr bestTarget = mob->getTarget(); - if (bestTarget == NULL) return false; - if (target.lock() == NULL || !target.lock()->isAlive()) return false; - if (!trackTarget) return !mob->getNavigation()->isDone(); - if (!mob->isWithinRestriction(Mth::floor(target.lock()->x), Mth::floor(target.lock()->y), Mth::floor(target.lock()->z))) return false; - return true; +bool MeleeAttackGoal::canContinueToUse() { + std::shared_ptr bestTarget = mob->getTarget(); + if (bestTarget == NULL) return false; + if (target.lock() == NULL || !target.lock()->isAlive()) return false; + if (!trackTarget) return !mob->getNavigation()->isDone(); + if (!mob->isWithinRestriction(Mth::floor(target.lock()->x), + Mth::floor(target.lock()->y), + Mth::floor(target.lock()->z))) + return false; + return true; } -void MeleeAttackGoal::start() -{ - mob->getNavigation()->moveTo(path, speed); - path = NULL; - timeToRecalcPath = 0; +void MeleeAttackGoal::start() { + mob->getNavigation()->moveTo(path, speed); + path = NULL; + timeToRecalcPath = 0; } -void MeleeAttackGoal::stop() -{ - target = std::weak_ptr(); - mob->getNavigation()->stop(); +void MeleeAttackGoal::stop() { + target = std::weak_ptr(); + mob->getNavigation()->stop(); } -void MeleeAttackGoal::tick() -{ - mob->getLookControl()->setLookAt(target.lock(), 30, 30); - if (trackTarget || mob->getSensing()->canSee(target.lock())) - { - if (--timeToRecalcPath <= 0) - { - timeToRecalcPath = 4 + mob->getRandom()->nextInt(7); - mob->getNavigation()->moveTo(target.lock(), speed); - } - } +void MeleeAttackGoal::tick() { + mob->getLookControl()->setLookAt(target.lock(), 30, 30); + if (trackTarget || mob->getSensing()->canSee(target.lock())) { + if (--timeToRecalcPath <= 0) { + timeToRecalcPath = 4 + mob->getRandom()->nextInt(7); + mob->getNavigation()->moveTo(target.lock(), speed); + } + } - attackTime = std::max(attackTime - 1, 0); + attackTime = std::max(attackTime - 1, 0); - double meleeRadiusSqr = (mob->bbWidth * 2) * (mob->bbWidth * 2); - if (mob->distanceToSqr(target.lock()->x, target.lock()->bb->y0, target.lock()->z) > meleeRadiusSqr) return; - if (attackTime > 0) return; - attackTime = 20; - mob->doHurtTarget(target.lock()); + double meleeRadiusSqr = (mob->bbWidth * 2) * (mob->bbWidth * 2); + if (mob->distanceToSqr(target.lock()->x, target.lock()->bb->y0, + target.lock()->z) > meleeRadiusSqr) + return; + if (attackTime > 0) return; + attackTime = 20; + mob->doHurtTarget(target.lock()); } diff --git a/Minecraft.World/AI/Goals/MeleeAttackGoal.h b/Minecraft.World/AI/Goals/MeleeAttackGoal.h index 1b24b28df..ed97ecacb 100644 --- a/Minecraft.World/AI/Goals/MeleeAttackGoal.h +++ b/Minecraft.World/AI/Goals/MeleeAttackGoal.h @@ -6,33 +6,34 @@ class Level; class Mob; class Path; -class MeleeAttackGoal : public Goal -{ +class MeleeAttackGoal : public Goal { private: - Level *level; - Mob *mob; // Owner of this goal - std::weak_ptr target; + Level* level; + Mob* mob; // Owner of this goal + std::weak_ptr target; - int attackTime; - float speed; - bool trackTarget; - Path *path; - eINSTANCEOF attackType; - int timeToRecalcPath; + int attackTime; + float speed; + bool trackTarget; + Path* path; + eINSTANCEOF attackType; + int timeToRecalcPath; - void _init(Mob *mob, float speed, bool trackTarget); + void _init(Mob* mob, float speed, bool trackTarget); public: - MeleeAttackGoal(Mob *mob, eINSTANCEOF attackType, float speed, bool trackTarget); - MeleeAttackGoal(Mob *mob, float speed, bool trackTarget); - ~MeleeAttackGoal(); + MeleeAttackGoal(Mob* mob, eINSTANCEOF attackType, float speed, + bool trackTarget); + MeleeAttackGoal(Mob* mob, float speed, bool trackTarget); + ~MeleeAttackGoal(); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); - - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); + + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveIndoorsGoal.cpp b/Minecraft.World/AI/Goals/MoveIndoorsGoal.cpp index dbaf03c33..b0f83e6d2 100644 --- a/Minecraft.World/AI/Goals/MoveIndoorsGoal.cpp +++ b/Minecraft.World/AI/Goals/MoveIndoorsGoal.cpp @@ -8,58 +8,64 @@ #include "../../Headers/net.minecraft.world.level.dimension.h" #include "MoveIndoorsGoal.h" -MoveIndoorsGoal::MoveIndoorsGoal(PathfinderMob *mob) -{ - insideX = insideZ = -1; +MoveIndoorsGoal::MoveIndoorsGoal(PathfinderMob* mob) { + insideX = insideZ = -1; - this->mob = mob; - setRequiredControlFlags(Control::MoveControlFlag); + this->mob = mob; + setRequiredControlFlags(Control::MoveControlFlag); } -bool MoveIndoorsGoal::canUse() -{ - if ((mob->level->isDay() && !mob->level->isRaining()) || mob->level->dimension->hasCeiling) return false; - if (mob->getRandom()->nextInt(50) != 0) return false; - if (insideX != -1 && mob->distanceToSqr(insideX, mob->y, insideZ) < 2 * 2) return false; - std::shared_ptr village = mob->level->villages->getClosestVillage(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 14); - if (village == NULL) return false; - std::shared_ptr _doorInfo = village->getBestDoorInfo(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); - doorInfo = _doorInfo; - return _doorInfo != NULL; +bool MoveIndoorsGoal::canUse() { + if ((mob->level->isDay() && !mob->level->isRaining()) || + mob->level->dimension->hasCeiling) + return false; + if (mob->getRandom()->nextInt(50) != 0) return false; + if (insideX != -1 && mob->distanceToSqr(insideX, mob->y, insideZ) < 2 * 2) + return false; + std::shared_ptr village = mob->level->villages->getClosestVillage( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 14); + if (village == NULL) return false; + std::shared_ptr _doorInfo = village->getBestDoorInfo( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); + doorInfo = _doorInfo; + return _doorInfo != NULL; } -bool MoveIndoorsGoal::canContinueToUse() -{ - return !mob->getNavigation()->isDone(); +bool MoveIndoorsGoal::canContinueToUse() { + return !mob->getNavigation()->isDone(); } -void MoveIndoorsGoal::start() -{ - insideX = -1; - std::shared_ptr _doorInfo = doorInfo.lock(); - if( _doorInfo == NULL ) - { - doorInfo = std::weak_ptr(); - return; - } - if (mob->distanceToSqr(_doorInfo->getIndoorX(), _doorInfo->y, _doorInfo->getIndoorZ()) > 16 * 16) - { - Vec3 *pos = RandomPos::getPosTowards(std::dynamic_pointer_cast(mob->shared_from_this()), 14, 3, Vec3::newTemp(_doorInfo->getIndoorX() + 0.5, _doorInfo->getIndoorY(), _doorInfo->getIndoorZ() + 0.5)); - if (pos != NULL) mob->getNavigation()->moveTo(pos->x, pos->y, pos->z, 0.3f); - } - else mob->getNavigation()->moveTo(_doorInfo->getIndoorX() + 0.5, _doorInfo->getIndoorY(), _doorInfo->getIndoorZ() + 0.5, 0.3f); +void MoveIndoorsGoal::start() { + insideX = -1; + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo == NULL) { + doorInfo = std::weak_ptr(); + return; + } + if (mob->distanceToSqr(_doorInfo->getIndoorX(), _doorInfo->y, + _doorInfo->getIndoorZ()) > 16 * 16) { + Vec3* pos = RandomPos::getPosTowards( + std::dynamic_pointer_cast(mob->shared_from_this()), + 14, 3, + Vec3::newTemp(_doorInfo->getIndoorX() + 0.5, + _doorInfo->getIndoorY(), + _doorInfo->getIndoorZ() + 0.5)); + if (pos != NULL) + mob->getNavigation()->moveTo(pos->x, pos->y, pos->z, 0.3f); + } else + mob->getNavigation()->moveTo(_doorInfo->getIndoorX() + 0.5, + _doorInfo->getIndoorY(), + _doorInfo->getIndoorZ() + 0.5, 0.3f); } -void MoveIndoorsGoal::stop() -{ - std::shared_ptr _doorInfo = doorInfo.lock(); - if( _doorInfo == NULL ) - { - doorInfo = std::weak_ptr(); - return; - } +void MoveIndoorsGoal::stop() { + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo == NULL) { + doorInfo = std::weak_ptr(); + return; + } - insideX = _doorInfo->getIndoorX(); - insideZ = _doorInfo->getIndoorZ(); - doorInfo = std::weak_ptr(); + insideX = _doorInfo->getIndoorX(); + insideZ = _doorInfo->getIndoorZ(); + doorInfo = std::weak_ptr(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveIndoorsGoal.h b/Minecraft.World/AI/Goals/MoveIndoorsGoal.h index 823a07c12..d0c55491d 100644 --- a/Minecraft.World/AI/Goals/MoveIndoorsGoal.h +++ b/Minecraft.World/AI/Goals/MoveIndoorsGoal.h @@ -5,18 +5,17 @@ class PathfinderMob; class DoorInfo; -class MoveIndoorsGoal : public Goal -{ +class MoveIndoorsGoal : public Goal { private: - PathfinderMob *mob; - std::weak_ptr doorInfo; - int insideX, insideZ; + PathfinderMob* mob; + std::weak_ptr doorInfo; + int insideX, insideZ; public: - MoveIndoorsGoal(PathfinderMob *mob); + MoveIndoorsGoal(PathfinderMob* mob); - bool canUse(); - bool canContinueToUse(); - void start(); - void stop(); + bool canUse(); + bool canContinueToUse(); + void start(); + void stop(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveThroughVillageGoal.cpp b/Minecraft.World/AI/Goals/MoveThroughVillageGoal.cpp index b53101f54..1539287e5 100644 --- a/Minecraft.World/AI/Goals/MoveThroughVillageGoal.cpp +++ b/Minecraft.World/AI/Goals/MoveThroughVillageGoal.cpp @@ -9,119 +9,114 @@ #include "MoveThroughVillageGoal.h" #include "../Navigation/Path.h" -MoveThroughVillageGoal::MoveThroughVillageGoal(PathfinderMob *mob, float speed, bool onlyAtNight) -{ - path = NULL; - doorInfo = std::weak_ptr(); +MoveThroughVillageGoal::MoveThroughVillageGoal(PathfinderMob* mob, float speed, + bool onlyAtNight) { + path = NULL; + doorInfo = std::weak_ptr(); - this->mob = mob; - this->speed = speed; - this->onlyAtNight = onlyAtNight; - setRequiredControlFlags(Control::MoveControlFlag); + this->mob = mob; + this->speed = speed; + this->onlyAtNight = onlyAtNight; + setRequiredControlFlags(Control::MoveControlFlag); } -MoveThroughVillageGoal::~MoveThroughVillageGoal() -{ - if(path != NULL) delete path; +MoveThroughVillageGoal::~MoveThroughVillageGoal() { + if (path != NULL) delete path; } -bool MoveThroughVillageGoal::canUse() -{ - updateVisited(); +bool MoveThroughVillageGoal::canUse() { + updateVisited(); - if (onlyAtNight && mob->level->isDay()) return false; + if (onlyAtNight && mob->level->isDay()) return false; - std::shared_ptr village = mob->level->villages->getClosestVillage(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 0); - if (village == NULL) return false; + std::shared_ptr village = mob->level->villages->getClosestVillage( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 0); + if (village == NULL) return false; - std::shared_ptr _doorInfo = getNextDoorInfo(village); - if (_doorInfo == NULL) return false; - doorInfo = _doorInfo; + std::shared_ptr _doorInfo = getNextDoorInfo(village); + if (_doorInfo == NULL) return false; + doorInfo = _doorInfo; - bool oldCanOpenDoors = mob->getNavigation()->canOpenDoors(); - mob->getNavigation()->setCanOpenDoors(false); - delete path; + bool oldCanOpenDoors = mob->getNavigation()->canOpenDoors(); + mob->getNavigation()->setCanOpenDoors(false); + delete path; - path = mob->getNavigation()->createPath(_doorInfo->x, _doorInfo->y, _doorInfo->z); - mob->getNavigation()->setCanOpenDoors(oldCanOpenDoors); - if (path != NULL) return true; + path = mob->getNavigation()->createPath(_doorInfo->x, _doorInfo->y, + _doorInfo->z); + mob->getNavigation()->setCanOpenDoors(oldCanOpenDoors); + if (path != NULL) return true; - Vec3 *pos = RandomPos::getPosTowards(std::dynamic_pointer_cast(mob->shared_from_this()), 10, 7, Vec3::newTemp(_doorInfo->x, _doorInfo->y, _doorInfo->z)); - if (pos == NULL) return false; - mob->getNavigation()->setCanOpenDoors(false); - delete path; - path = mob->getNavigation()->createPath(pos->x, pos->y, pos->z); - mob->getNavigation()->setCanOpenDoors(oldCanOpenDoors); - return path != NULL; + Vec3* pos = RandomPos::getPosTowards( + std::dynamic_pointer_cast(mob->shared_from_this()), 10, + 7, Vec3::newTemp(_doorInfo->x, _doorInfo->y, _doorInfo->z)); + if (pos == NULL) return false; + mob->getNavigation()->setCanOpenDoors(false); + delete path; + path = mob->getNavigation()->createPath(pos->x, pos->y, pos->z); + mob->getNavigation()->setCanOpenDoors(oldCanOpenDoors); + return path != NULL; } -bool MoveThroughVillageGoal::canContinueToUse() -{ - if (mob->getNavigation()->isDone()) return false; - float dist = mob->bbWidth + 4.f; - std::shared_ptr _doorInfo = doorInfo.lock(); - if( _doorInfo == NULL ) return false; +bool MoveThroughVillageGoal::canContinueToUse() { + if (mob->getNavigation()->isDone()) return false; + float dist = mob->bbWidth + 4.f; + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo == NULL) return false; - return mob->distanceToSqr(_doorInfo->x, _doorInfo->y, _doorInfo->z) > dist * dist; + return mob->distanceToSqr(_doorInfo->x, _doorInfo->y, _doorInfo->z) > + dist * dist; } -void MoveThroughVillageGoal::start() -{ - mob->getNavigation()->moveTo(path, speed); - path = NULL; +void MoveThroughVillageGoal::start() { + mob->getNavigation()->moveTo(path, speed); + path = NULL; } -void MoveThroughVillageGoal::stop() -{ - std::shared_ptr _doorInfo = doorInfo.lock(); - if( _doorInfo == NULL ) return; +void MoveThroughVillageGoal::stop() { + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo == NULL) return; - if (mob->getNavigation()->isDone() || mob->distanceToSqr(_doorInfo->x, _doorInfo->y, _doorInfo->z) < 4 * 4) - { - visited.push_back(doorInfo); - } + if (mob->getNavigation()->isDone() || + mob->distanceToSqr(_doorInfo->x, _doorInfo->y, _doorInfo->z) < 4 * 4) { + visited.push_back(doorInfo); + } } -std::shared_ptr MoveThroughVillageGoal::getNextDoorInfo(std::shared_ptr village) -{ - std::shared_ptr closest = nullptr; - int closestDistSqr = Integer::MAX_VALUE; - std::vector > *doorInfos = village->getDoorInfos(); - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos->begin()); it != doorInfos->end(); ++it) - { - std::shared_ptr di = *it; - int distSqr = di->distanceToSqr(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); - if (distSqr < closestDistSqr) - { - if (hasVisited(di)) continue; - closest = di; - closestDistSqr = distSqr; - } - } - return closest; +std::shared_ptr MoveThroughVillageGoal::getNextDoorInfo( + std::shared_ptr village) { + std::shared_ptr closest = nullptr; + int closestDistSqr = Integer::MAX_VALUE; + std::vector >* doorInfos = + village->getDoorInfos(); + // for (DoorInfo di : doorInfos) + for (AUTO_VAR(it, doorInfos->begin()); it != doorInfos->end(); ++it) { + std::shared_ptr di = *it; + int distSqr = di->distanceToSqr(Mth::floor(mob->x), Mth::floor(mob->y), + Mth::floor(mob->z)); + if (distSqr < closestDistSqr) { + if (hasVisited(di)) continue; + closest = di; + closestDistSqr = distSqr; + } + } + return closest; } -bool MoveThroughVillageGoal::hasVisited(std::shared_ptrdi) -{ - //for (DoorInfo di2 : visited) - for(AUTO_VAR(it, visited.begin()); it != visited.end(); ) - { - std::shared_ptr di2 = (*it).lock(); - if( di2 == NULL ) - { - it = visited.erase(it); - } - else - { - if (di->x == di2->x && di->y == di2->y && di->z == di2->z) return true; - ++it; - } - } - return false; +bool MoveThroughVillageGoal::hasVisited(std::shared_ptr di) { + // for (DoorInfo di2 : visited) + for (AUTO_VAR(it, visited.begin()); it != visited.end();) { + std::shared_ptr di2 = (*it).lock(); + if (di2 == NULL) { + it = visited.erase(it); + } else { + if (di->x == di2->x && di->y == di2->y && di->z == di2->z) + return true; + ++it; + } + } + return false; } -void MoveThroughVillageGoal::updateVisited() -{ - if (visited.size() > 15) visited.erase(visited.begin()); +void MoveThroughVillageGoal::updateVisited() { + if (visited.size() > 15) visited.erase(visited.begin()); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveThroughVillageGoal.h b/Minecraft.World/AI/Goals/MoveThroughVillageGoal.h index d932e5fe8..315af343c 100644 --- a/Minecraft.World/AI/Goals/MoveThroughVillageGoal.h +++ b/Minecraft.World/AI/Goals/MoveThroughVillageGoal.h @@ -6,27 +6,26 @@ class PathfinderMob; class Path; class DoorInfo; -class MoveThroughVillageGoal : public Goal -{ +class MoveThroughVillageGoal : public Goal { private: - PathfinderMob *mob; - float speed; - Path *path; - std::weak_ptr doorInfo; - bool onlyAtNight; - std::vector< std::weak_ptr > visited; + PathfinderMob* mob; + float speed; + Path* path; + std::weak_ptr doorInfo; + bool onlyAtNight; + std::vector > visited; public: - MoveThroughVillageGoal(PathfinderMob *mob, float speed, bool onlyAtNight); - ~MoveThroughVillageGoal(); + MoveThroughVillageGoal(PathfinderMob* mob, float speed, bool onlyAtNight); + ~MoveThroughVillageGoal(); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); private: - std::shared_ptr getNextDoorInfo(std::shared_ptr village); - bool hasVisited(std::shared_ptr di); - void updateVisited(); + std::shared_ptr getNextDoorInfo(std::shared_ptr village); + bool hasVisited(std::shared_ptr di); + void updateVisited(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.cpp b/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.cpp index 770fb709f..2f9e99bfe 100644 --- a/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.cpp +++ b/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.cpp @@ -6,33 +6,32 @@ #include "../../Headers/net.minecraft.world.level.h" #include "MoveTowardsRestrictionGoal.h" -MoveTowardsRestrictionGoal::MoveTowardsRestrictionGoal(PathfinderMob *mob, float speed) -{ - wantedX = wantedY = wantedZ = 0.0; +MoveTowardsRestrictionGoal::MoveTowardsRestrictionGoal(PathfinderMob* mob, + float speed) { + wantedX = wantedY = wantedZ = 0.0; - this->mob = mob; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag); + this->mob = mob; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag); } -bool MoveTowardsRestrictionGoal::canUse() -{ - if (mob->isWithinRestriction()) return false; - Pos *towards = mob->getRestrictCenter(); - Vec3 *pos = RandomPos::getPosTowards(std::dynamic_pointer_cast(mob->shared_from_this()), 16, 7, Vec3::newTemp(towards->x, towards->y, towards->z)); - if (pos == NULL) return false; - wantedX = pos->x; - wantedY = pos->y; - wantedZ = pos->z; - return true; +bool MoveTowardsRestrictionGoal::canUse() { + if (mob->isWithinRestriction()) return false; + Pos* towards = mob->getRestrictCenter(); + Vec3* pos = RandomPos::getPosTowards( + std::dynamic_pointer_cast(mob->shared_from_this()), 16, + 7, Vec3::newTemp(towards->x, towards->y, towards->z)); + if (pos == NULL) return false; + wantedX = pos->x; + wantedY = pos->y; + wantedZ = pos->z; + return true; } -bool MoveTowardsRestrictionGoal::canContinueToUse() -{ - return !mob->getNavigation()->isDone(); +bool MoveTowardsRestrictionGoal::canContinueToUse() { + return !mob->getNavigation()->isDone(); } -void MoveTowardsRestrictionGoal::start() -{ - mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); +void MoveTowardsRestrictionGoal::start() { + mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.h b/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.h index 859b5ee80..f1a8d39cb 100644 --- a/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.h +++ b/Minecraft.World/AI/Goals/MoveTowardsRestrictionGoal.h @@ -2,17 +2,16 @@ #include "Goal.h" -class MoveTowardsRestrictionGoal : public Goal -{ +class MoveTowardsRestrictionGoal : public Goal { private: - PathfinderMob *mob; - double wantedX, wantedY, wantedZ; - float speed; + PathfinderMob* mob; + double wantedX, wantedY, wantedZ; + float speed; public: - MoveTowardsRestrictionGoal(PathfinderMob *mob, float speed); + MoveTowardsRestrictionGoal(PathfinderMob* mob, float speed); - bool canUse(); - bool canContinueToUse(); - void start(); + bool canUse(); + bool canContinueToUse(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.cpp b/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.cpp index 4612ee76d..c5a180300 100644 --- a/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.cpp @@ -6,38 +6,38 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "MoveTowardsTargetGoal.h" -MoveTowardsTargetGoal::MoveTowardsTargetGoal(PathfinderMob *mob, float speed, float within) -{ - this->mob = mob; - this->speed = speed; - this->within = within; - setRequiredControlFlags(Control::MoveControlFlag); +MoveTowardsTargetGoal::MoveTowardsTargetGoal(PathfinderMob* mob, float speed, + float within) { + this->mob = mob; + this->speed = speed; + this->within = within; + setRequiredControlFlags(Control::MoveControlFlag); } -bool MoveTowardsTargetGoal::canUse() -{ - target = std::weak_ptr(mob->getTarget()); - if (target.lock() == NULL) return false; - if (target.lock()->distanceToSqr(mob->shared_from_this()) > within * within) return false; - Vec3 *pos = RandomPos::getPosTowards(std::dynamic_pointer_cast(mob->shared_from_this()), 16, 7, Vec3::newTemp(target.lock()->x, target.lock()->y, target.lock()->z)); - if (pos == NULL) return false; - wantedX = pos->x; - wantedY = pos->y; - wantedZ = pos->z; - return true; +bool MoveTowardsTargetGoal::canUse() { + target = std::weak_ptr(mob->getTarget()); + if (target.lock() == NULL) return false; + if (target.lock()->distanceToSqr(mob->shared_from_this()) > within * within) + return false; + Vec3* pos = RandomPos::getPosTowards( + std::dynamic_pointer_cast(mob->shared_from_this()), 16, + 7, Vec3::newTemp(target.lock()->x, target.lock()->y, target.lock()->z)); + if (pos == NULL) return false; + wantedX = pos->x; + wantedY = pos->y; + wantedZ = pos->z; + return true; } -bool MoveTowardsTargetGoal::canContinueToUse() -{ - return target.lock() != NULL && !mob->getNavigation()->isDone() && target.lock()->isAlive() && target.lock()->distanceToSqr(mob->shared_from_this()) < within * within; +bool MoveTowardsTargetGoal::canContinueToUse() { + return target.lock() != NULL && !mob->getNavigation()->isDone() && + target.lock()->isAlive() && + target.lock()->distanceToSqr(mob->shared_from_this()) < + within * within; } -void MoveTowardsTargetGoal::stop() -{ - target = std::weak_ptr(); -} +void MoveTowardsTargetGoal::stop() { target = std::weak_ptr(); } -void MoveTowardsTargetGoal::start() -{ - mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); +void MoveTowardsTargetGoal::start() { + mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.h b/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.h index 413e8bce1..f2d00c80d 100644 --- a/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.h +++ b/Minecraft.World/AI/Goals/MoveTowardsTargetGoal.h @@ -2,19 +2,18 @@ #include "Goal.h" -class MoveTowardsTargetGoal : public Goal -{ +class MoveTowardsTargetGoal : public Goal { private: - PathfinderMob *mob; - std::weak_ptr target; - double wantedX, wantedY, wantedZ; - float speed, within; + PathfinderMob* mob; + std::weak_ptr target; + double wantedX, wantedY, wantedZ; + float speed, within; public: - MoveTowardsTargetGoal(PathfinderMob *mob, float speed, float within); + MoveTowardsTargetGoal(PathfinderMob* mob, float speed, float within); - bool canUse(); - bool canContinueToUse(); - void stop(); - void start(); + bool canUse(); + bool canContinueToUse(); + void stop(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.cpp b/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.cpp index 06071fd68..06bc41b98 100644 --- a/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.cpp @@ -4,68 +4,64 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "NearestAttackableTargetGoal.h" -NearestAttackableTargetGoal::DistComp::DistComp(Entity *source) -{ - this->source = source; +NearestAttackableTargetGoal::DistComp::DistComp(Entity* source) { + this->source = source; } -bool NearestAttackableTargetGoal::DistComp::operator() (std::shared_ptr e1, std::shared_ptr e2) -{ - // Should return true if e1 comes before e2 in the sorted list - double distSqr1 = source->distanceToSqr(e1); - double distSqr2 = source->distanceToSqr(e2); - if (distSqr1 < distSqr2) return true; - if (distSqr1 > distSqr2) return false; - return true; +bool NearestAttackableTargetGoal::DistComp::operator()( + std::shared_ptr e1, std::shared_ptr e2) { + // Should return true if e1 comes before e2 in the sorted list + double distSqr1 = source->distanceToSqr(e1); + double distSqr2 = source->distanceToSqr(e2); + if (distSqr1 < distSqr2) return true; + if (distSqr1 > distSqr2) return false; + return true; } -NearestAttackableTargetGoal::NearestAttackableTargetGoal(Mob *mob, const std::type_info& targetType, float within, int randomInterval, bool mustSee, bool mustReach /*= false*/) : TargetGoal(mob, within, mustSee, mustReach), targetType(targetType) -{ - //this->targetType = targetType; - this->within = within; - this->randomInterval = randomInterval; - this->distComp = new DistComp(mob); - setRequiredControlFlags(TargetGoal::TargetFlag); +NearestAttackableTargetGoal::NearestAttackableTargetGoal( + Mob* mob, const std::type_info& targetType, float within, + int randomInterval, bool mustSee, bool mustReach /*= false*/) + : TargetGoal(mob, within, mustSee, mustReach), targetType(targetType) { + // this->targetType = targetType; + this->within = within; + this->randomInterval = randomInterval; + this->distComp = new DistComp(mob); + setRequiredControlFlags(TargetGoal::TargetFlag); } -NearestAttackableTargetGoal::~NearestAttackableTargetGoal() -{ - delete distComp; +NearestAttackableTargetGoal::~NearestAttackableTargetGoal() { delete distComp; } + +bool NearestAttackableTargetGoal::canUse() { + if (randomInterval > 0 && mob->getRandom()->nextInt(randomInterval) != 0) + return false; + if (targetType == typeid(Player)) { + std::shared_ptr potentialTarget = + mob->level->getNearestAttackablePlayer(mob->shared_from_this(), + within); + if (canAttack(potentialTarget, false)) { + target = std::weak_ptr(potentialTarget); + return true; + } + } else { + std::vector >* entities = + mob->level->getEntitiesOfClass(targetType, + mob->bb->grow(within, 4, within)); + // Collections.sort(entities, distComp); + std::sort(entities->begin(), entities->end(), *distComp); + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + std::shared_ptr potTarget = + std::dynamic_pointer_cast(*it); + if (canAttack(potTarget, false)) { + target = std::weak_ptr(potTarget); + return true; + } + } + delete entities; + } + return false; } -bool NearestAttackableTargetGoal::canUse() -{ - if (randomInterval > 0 && mob->getRandom()->nextInt(randomInterval) != 0) return false; - if (targetType == typeid(Player)) - { - std::shared_ptr potentialTarget = mob->level->getNearestAttackablePlayer(mob->shared_from_this(), within); - if (canAttack(potentialTarget, false)) - { - target = std::weak_ptr(potentialTarget); - return true; - } - } - else - { - std::vector > *entities = mob->level->getEntitiesOfClass(targetType, mob->bb->grow(within, 4, within)); - //Collections.sort(entities, distComp); - std::sort(entities->begin(), entities->end(), *distComp); - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - std::shared_ptr potTarget = std::dynamic_pointer_cast(*it); - if (canAttack(potTarget, false)) - { - target = std::weak_ptr(potTarget); - return true; - } - } - delete entities; - } - return false; -} - -void NearestAttackableTargetGoal::start() -{ - mob->setTarget(target.lock()); - TargetGoal::start(); +void NearestAttackableTargetGoal::start() { + mob->setTarget(target.lock()); + TargetGoal::start(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.h b/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.h index 23389cf35..fec8e5569 100644 --- a/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.h +++ b/Minecraft.World/AI/Goals/NearestAttackableTargetGoal.h @@ -2,35 +2,36 @@ #include "TargetGoal.h" -class NearestAttackableTargetGoal : public TargetGoal -{ +class NearestAttackableTargetGoal : public TargetGoal { public: - class DistComp - { - private: - Entity *source; + class DistComp { + private: + Entity* source; - public: - DistComp(Entity *source); + public: + DistComp(Entity* source); - bool operator() (std::shared_ptr e1, std::shared_ptr e2); - }; + bool operator()(std::shared_ptr e1, std::shared_ptr e2); + }; private: - std::weak_ptr target; - const std::type_info& targetType; - int randomInterval; - DistComp *distComp; + std::weak_ptr target; + const std::type_info& targetType; + int randomInterval; + DistComp* distComp; public: - //public NearestAttackableTargetGoal(Mob mob, const std::type_info& targetType, float within, int randomInterval, bool mustSee) - //{ - // this(mob, targetType, within, randomInterval, mustSee, false); - //} + // public NearestAttackableTargetGoal(Mob mob, const std::type_info& + // targetType, float within, int randomInterval, bool mustSee) + //{ + // this(mob, targetType, within, randomInterval, mustSee, false); + // } - NearestAttackableTargetGoal(Mob *mob, const std::type_info& targetType, float within, int randomInterval, bool mustSee, bool mustReach = false); - virtual ~NearestAttackableTargetGoal(); + NearestAttackableTargetGoal(Mob* mob, const std::type_info& targetType, + float within, int randomInterval, bool mustSee, + bool mustReach = false); + virtual ~NearestAttackableTargetGoal(); - virtual bool canUse(); - void start(); + virtual bool canUse(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.cpp b/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.cpp index 6ea84165b..f05fb91b8 100644 --- a/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.cpp @@ -2,13 +2,15 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "NonTameRandomTargetGoal.h" -NonTameRandomTargetGoal::NonTameRandomTargetGoal(TamableAnimal *mob, const std::type_info& targetType, float within, int randomInterval, bool mustSee) : NearestAttackableTargetGoal(mob, targetType, within, randomInterval, mustSee) -{ - this->tamableMob = mob; +NonTameRandomTargetGoal::NonTameRandomTargetGoal( + TamableAnimal* mob, const std::type_info& targetType, float within, + int randomInterval, bool mustSee) + : NearestAttackableTargetGoal(mob, targetType, within, randomInterval, + mustSee) { + this->tamableMob = mob; } -bool NonTameRandomTargetGoal::canUse() -{ - if (tamableMob->isTame()) return false; - return NearestAttackableTargetGoal::canUse(); +bool NonTameRandomTargetGoal::canUse() { + if (tamableMob->isTame()) return false; + return NearestAttackableTargetGoal::canUse(); } diff --git a/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.h b/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.h index 4c2f57755..3aae62756 100644 --- a/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.h +++ b/Minecraft.World/AI/Goals/NonTameRandomTargetGoal.h @@ -4,13 +4,14 @@ class TamableAnimal; -class NonTameRandomTargetGoal : public NearestAttackableTargetGoal -{ +class NonTameRandomTargetGoal : public NearestAttackableTargetGoal { private: - TamableAnimal *tamableMob; // Owner of this goal + TamableAnimal* tamableMob; // Owner of this goal public: - NonTameRandomTargetGoal(TamableAnimal *mob, const std::type_info& targetType, float within, int randomInterval, bool mustSee); + NonTameRandomTargetGoal(TamableAnimal* mob, + const std::type_info& targetType, float within, + int randomInterval, bool mustSee); - bool canUse(); + bool canUse(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OcelotAttackGoal.cpp b/Minecraft.World/AI/Goals/OcelotAttackGoal.cpp index 5afe1e239..c66993272 100644 --- a/Minecraft.World/AI/Goals/OcelotAttackGoal.cpp +++ b/Minecraft.World/AI/Goals/OcelotAttackGoal.cpp @@ -6,56 +6,55 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "OcelotAttackGoal.h" -OzelotAttackGoal::OzelotAttackGoal(Mob *mob) -{ - target = std::weak_ptr(); - attackTime = 0; - speed = 0; - trackTarget = false; +OzelotAttackGoal::OzelotAttackGoal(Mob* mob) { + target = std::weak_ptr(); + attackTime = 0; + speed = 0; + trackTarget = false; - this->mob = mob; - this->level = mob->level; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->mob = mob; + this->level = mob->level; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool OzelotAttackGoal::canUse() -{ - std::shared_ptr bestTarget = mob->getTarget(); - if (bestTarget == NULL) return false; - target = std::weak_ptr(bestTarget); - return true; +bool OzelotAttackGoal::canUse() { + std::shared_ptr bestTarget = mob->getTarget(); + if (bestTarget == NULL) return false; + target = std::weak_ptr(bestTarget); + return true; } -bool OzelotAttackGoal::canContinueToUse() -{ - if (target.lock() == NULL || !target.lock()->isAlive()) return false; - if (mob->distanceToSqr(target.lock()) > 15 * 15) return false; - return !mob->getNavigation()->isDone() || canUse(); +bool OzelotAttackGoal::canContinueToUse() { + if (target.lock() == NULL || !target.lock()->isAlive()) return false; + if (mob->distanceToSqr(target.lock()) > 15 * 15) return false; + return !mob->getNavigation()->isDone() || canUse(); } -void OzelotAttackGoal::stop() -{ - target = std::weak_ptr(); - mob->getNavigation()->stop(); +void OzelotAttackGoal::stop() { + target = std::weak_ptr(); + mob->getNavigation()->stop(); } -void OzelotAttackGoal::tick() -{ - mob->getLookControl()->setLookAt(target.lock(), 30, 30); +void OzelotAttackGoal::tick() { + mob->getLookControl()->setLookAt(target.lock(), 30, 30); - double meleeRadiusSqr = (mob->bbWidth * 2) * (mob->bbWidth * 2); - double distSqr = mob->distanceToSqr(target.lock()->x, target.lock()->bb->y0, target.lock()->z); + double meleeRadiusSqr = (mob->bbWidth * 2) * (mob->bbWidth * 2); + double distSqr = mob->distanceToSqr(target.lock()->x, target.lock()->bb->y0, + target.lock()->z); - float speed = Ozelot::WALK_SPEED; - if (distSqr > meleeRadiusSqr && distSqr < 4 * 4) speed = Ozelot::SPRINT_SPEED; - else if (distSqr < 15 * 15) speed = Ozelot::SNEAK_SPEED; + float speed = Ozelot::WALK_SPEED; + if (distSqr > meleeRadiusSqr && distSqr < 4 * 4) + speed = Ozelot::SPRINT_SPEED; + else if (distSqr < 15 * 15) + speed = Ozelot::SNEAK_SPEED; - mob->getNavigation()->moveTo(target.lock(), speed); + mob->getNavigation()->moveTo(target.lock(), speed); - attackTime = std::max(attackTime - 1, 0); + attackTime = std::max(attackTime - 1, 0); - if (distSqr > meleeRadiusSqr) return; - if (attackTime > 0) return; - attackTime = 20; - mob->doHurtTarget(target.lock()); + if (distSqr > meleeRadiusSqr) return; + if (attackTime > 0) return; + attackTime = 20; + mob->doHurtTarget(target.lock()); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OcelotAttackGoal.h b/Minecraft.World/AI/Goals/OcelotAttackGoal.h index 75628cf19..b0eb1f78b 100644 --- a/Minecraft.World/AI/Goals/OcelotAttackGoal.h +++ b/Minecraft.World/AI/Goals/OcelotAttackGoal.h @@ -2,24 +2,24 @@ #include "Goal.h" -class OzelotAttackGoal : public Goal -{ +class OzelotAttackGoal : public Goal { private: - Level *level; - Mob *mob; - std::weak_ptr target; - int attackTime; - float speed; - bool trackTarget; + Level* level; + Mob* mob; + std::weak_ptr target; + int attackTime; + float speed; + bool trackTarget; public: - OzelotAttackGoal(Mob *mob); + OzelotAttackGoal(Mob* mob); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void stop(); - virtual void tick(); - - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level) { this->level = level; } + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void stop(); + virtual void tick(); + + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level) { this->level = level; } }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.cpp b/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.cpp index 1e835368c..fd419f6ab 100644 --- a/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.cpp +++ b/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.cpp @@ -10,118 +10,107 @@ #include "../../Util/Arrays.h" #include "OcelotSitOnTileGoal.h" -const int OcelotSitOnTileGoal::GIVE_UP_TICKS = 3 * SharedConstants::TICKS_PER_SECOND; -const int OcelotSitOnTileGoal::SIT_TICKS = 60 * SharedConstants::TICKS_PER_SECOND; +const int OcelotSitOnTileGoal::GIVE_UP_TICKS = + 3 * SharedConstants::TICKS_PER_SECOND; +const int OcelotSitOnTileGoal::SIT_TICKS = + 60 * SharedConstants::TICKS_PER_SECOND; const int OcelotSitOnTileGoal::SEARCH_RANGE = 8; const double OcelotSitOnTileGoal::SIT_CHANCE = 0.0065f; -OcelotSitOnTileGoal::OcelotSitOnTileGoal(Ozelot *ocelot, float speed) -{ - _tick = 0; - tryTicks = 0; - maxTicks = 0; - tileX = 0; - tileY = 0; - tileZ = 0; +OcelotSitOnTileGoal::OcelotSitOnTileGoal(Ozelot* ocelot, float speed) { + _tick = 0; + tryTicks = 0; + maxTicks = 0; + tileX = 0; + tileY = 0; + tileZ = 0; - this->ocelot = ocelot; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag | Control::JumpControlFlag); + this->ocelot = ocelot; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag | + Control::JumpControlFlag); } -bool OcelotSitOnTileGoal::canUse() -{ - return ocelot->isTame() && !ocelot->isSitting() && ocelot->getRandom()->nextDouble() <= SIT_CHANCE && findNearestTile(); +bool OcelotSitOnTileGoal::canUse() { + return ocelot->isTame() && !ocelot->isSitting() && + ocelot->getRandom()->nextDouble() <= SIT_CHANCE && findNearestTile(); } -bool OcelotSitOnTileGoal::canContinueToUse() -{ - return _tick <= maxTicks && tryTicks <= GIVE_UP_TICKS && isValidTarget(ocelot->level, tileX, tileY, tileZ); +bool OcelotSitOnTileGoal::canContinueToUse() { + return _tick <= maxTicks && tryTicks <= GIVE_UP_TICKS && + isValidTarget(ocelot->level, tileX, tileY, tileZ); } -void OcelotSitOnTileGoal::start() -{ - ocelot->getNavigation()->moveTo((float) tileX + 0.5, tileY + 1, (float) tileZ + 0.5, speed); - _tick = 0; - tryTicks = 0; - maxTicks = ocelot->getRandom()->nextInt(ocelot->getRandom()->nextInt(SIT_TICKS) + SIT_TICKS) + SIT_TICKS; - ocelot->getSitGoal()->wantToSit(false); +void OcelotSitOnTileGoal::start() { + ocelot->getNavigation()->moveTo((float)tileX + 0.5, tileY + 1, + (float)tileZ + 0.5, speed); + _tick = 0; + tryTicks = 0; + maxTicks = ocelot->getRandom()->nextInt( + ocelot->getRandom()->nextInt(SIT_TICKS) + SIT_TICKS) + + SIT_TICKS; + ocelot->getSitGoal()->wantToSit(false); } -void OcelotSitOnTileGoal::stop() -{ - ocelot->setSitting(false); +void OcelotSitOnTileGoal::stop() { ocelot->setSitting(false); } + +void OcelotSitOnTileGoal::tick() { + _tick++; + ocelot->getSitGoal()->wantToSit(false); + if (ocelot->distanceToSqr(tileX, tileY + 1, tileZ) > 1) { + ocelot->setSitting(false); + ocelot->getNavigation()->moveTo((float)tileX + 0.5, tileY + 1, + (float)tileZ + 0.5, speed); + tryTicks++; + } else if (!ocelot->isSitting()) { + ocelot->setSitting(true); + } else { + tryTicks--; + } } -void OcelotSitOnTileGoal::tick() -{ - _tick++; - ocelot->getSitGoal()->wantToSit(false); - if (ocelot->distanceToSqr(tileX, tileY + 1, tileZ) > 1) - { - ocelot->setSitting(false); - ocelot->getNavigation()->moveTo((float) tileX + 0.5, tileY + 1, (float) tileZ + 0.5, speed); - tryTicks++; - } - else if (!ocelot->isSitting()) - { - ocelot->setSitting(true); - } - else - { - tryTicks--; - } +bool OcelotSitOnTileGoal::findNearestTile() { + int y = (int)ocelot->y; + double distSqr = Integer::MAX_VALUE; + + for (int x = (int)ocelot->x - SEARCH_RANGE; x < ocelot->x + SEARCH_RANGE; + x++) { + for (int z = (int)ocelot->z - SEARCH_RANGE; + z < ocelot->z + SEARCH_RANGE; z++) { + if (isValidTarget(ocelot->level, x, y, z) && + ocelot->level->isEmptyTile(x, y + 1, z)) { + double dist = ocelot->distanceToSqr(x, y, z); + + if (dist < distSqr) { + this->tileX = x; + this->tileY = y; + this->tileZ = z; + distSqr = dist; + } + } + } + } + + return distSqr < Integer::MAX_VALUE; } -bool OcelotSitOnTileGoal::findNearestTile() -{ - int y = (int) ocelot->y; - double distSqr = Integer::MAX_VALUE; +bool OcelotSitOnTileGoal::isValidTarget(Level* level, int x, int y, int z) { + int tile = level->getTile(x, y, z); + int data = level->getData(x, y, z); - for (int x = (int) ocelot->x - SEARCH_RANGE; x < ocelot->x + SEARCH_RANGE; x++) - { - for (int z = (int) ocelot->z - SEARCH_RANGE; z < ocelot->z + SEARCH_RANGE; z++) - { - if (isValidTarget(ocelot->level, x, y, z) && ocelot->level->isEmptyTile(x, y + 1, z)) - { - double dist = ocelot->distanceToSqr(x, y, z); + if (tile == Tile::chest_Id) { + std::shared_ptr chest = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); - if (dist < distSqr) - { - this->tileX = x; - this->tileY = y; - this->tileZ = z; - distSqr = dist; - } - } - } - } + if (chest->openCount < 1) { + return true; + } + } else if (tile == Tile::furnace_lit_Id) { + return true; + } else if (tile == Tile::bed_Id && !BedTile::isHeadPiece(data)) { + return true; + } - return distSqr < Integer::MAX_VALUE; -} - -bool OcelotSitOnTileGoal::isValidTarget(Level *level, int x, int y, int z) -{ - int tile = level->getTile(x, y, z); - int data = level->getData(x, y, z); - - if (tile == Tile::chest_Id) - { - std::shared_ptr chest = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); - - if (chest->openCount < 1) - { - return true; - } - } - else if (tile == Tile::furnace_lit_Id) - { - return true; - } - else if (tile == Tile::bed_Id && !BedTile::isHeadPiece(data)) - { - return true; - } - - return false; + return false; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.h b/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.h index 6a8d9ed58..8b6b232d2 100644 --- a/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.h +++ b/Minecraft.World/AI/Goals/OcelotSitOnTileGoal.h @@ -4,34 +4,33 @@ class Ozelot; -class OcelotSitOnTileGoal : public Goal -{ +class OcelotSitOnTileGoal : public Goal { private: - static const int GIVE_UP_TICKS; - static const int SIT_TICKS; - static const int SEARCH_RANGE; - static const double SIT_CHANCE; + static const int GIVE_UP_TICKS; + static const int SIT_TICKS; + static const int SEARCH_RANGE; + static const double SIT_CHANCE; private: - Ozelot *ocelot; // Owner of this goal - float speed; - int _tick; - int tryTicks; - int maxTicks; - int tileX; - int tileY; - int tileZ; + Ozelot* ocelot; // Owner of this goal + float speed; + int _tick; + int tryTicks; + int maxTicks; + int tileX; + int tileY; + int tileZ; public: - OcelotSitOnTileGoal(Ozelot *ocelot, float speed); + OcelotSitOnTileGoal(Ozelot* ocelot, float speed); - bool canUse(); - bool canContinueToUse(); - void start(); - void stop(); - void tick(); + bool canUse(); + bool canContinueToUse(); + void start(); + void stop(); + void tick(); private: - bool findNearestTile(); - bool isValidTarget(Level *level, int x, int y, int z); + bool findNearestTile(); + bool isValidTarget(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OfferFlowerGoal.cpp b/Minecraft.World/AI/Goals/OfferFlowerGoal.cpp index 4da8ae746..01c1b3dbf 100644 --- a/Minecraft.World/AI/Goals/OfferFlowerGoal.cpp +++ b/Minecraft.World/AI/Goals/OfferFlowerGoal.cpp @@ -6,39 +6,37 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "OfferFlowerGoal.h" -OfferFlowerGoal::OfferFlowerGoal(VillagerGolem *golem) -{ - this->golem = golem; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); +OfferFlowerGoal::OfferFlowerGoal(VillagerGolem* golem) { + this->golem = golem; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool OfferFlowerGoal::canUse() -{ - if (!golem->level->isDay()) return false; - if (golem->getRandom()->nextInt(8000) != 0) return false; - villager = std::weak_ptr(std::dynamic_pointer_cast( golem->level->getClosestEntityOfClass(typeid(Villager), golem->bb->grow(6, 2, 6), golem->shared_from_this()) )); - return villager.lock() != NULL; +bool OfferFlowerGoal::canUse() { + if (!golem->level->isDay()) return false; + if (golem->getRandom()->nextInt(8000) != 0) return false; + villager = std::weak_ptr(std::dynamic_pointer_cast( + golem->level->getClosestEntityOfClass(typeid(Villager), + golem->bb->grow(6, 2, 6), + golem->shared_from_this()))); + return villager.lock() != NULL; } -bool OfferFlowerGoal::canContinueToUse() -{ - return _tick > 0 && villager.lock() != NULL; +bool OfferFlowerGoal::canContinueToUse() { + return _tick > 0 && villager.lock() != NULL; } -void OfferFlowerGoal::start() -{ - _tick = OFFER_TICKS; - golem->offerFlower(true); +void OfferFlowerGoal::start() { + _tick = OFFER_TICKS; + golem->offerFlower(true); } -void OfferFlowerGoal::stop() -{ - golem->offerFlower(false); - villager = std::weak_ptr(); +void OfferFlowerGoal::stop() { + golem->offerFlower(false); + villager = std::weak_ptr(); } -void OfferFlowerGoal::tick() -{ - golem->getLookControl()->setLookAt(villager.lock(), 30, 30); - --_tick; +void OfferFlowerGoal::tick() { + golem->getLookControl()->setLookAt(villager.lock(), 30, 30); + --_tick; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OfferFlowerGoal.h b/Minecraft.World/AI/Goals/OfferFlowerGoal.h index 8f3fa21ef..013f50455 100644 --- a/Minecraft.World/AI/Goals/OfferFlowerGoal.h +++ b/Minecraft.World/AI/Goals/OfferFlowerGoal.h @@ -4,22 +4,21 @@ class VillagerGolem; -class OfferFlowerGoal : public Goal -{ +class OfferFlowerGoal : public Goal { public: - static const int OFFER_TICKS = 400; + static const int OFFER_TICKS = 400; private: - VillagerGolem *golem; - std::weak_ptr villager; - int _tick; + VillagerGolem* golem; + std::weak_ptr villager; + int _tick; public: - OfferFlowerGoal(VillagerGolem *golem); + OfferFlowerGoal(VillagerGolem* golem); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OpenDoorGoal.cpp b/Minecraft.World/AI/Goals/OpenDoorGoal.cpp index 469de6573..5fc170b6d 100644 --- a/Minecraft.World/AI/Goals/OpenDoorGoal.cpp +++ b/Minecraft.World/AI/Goals/OpenDoorGoal.cpp @@ -3,33 +3,28 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "OpenDoorGoal.h" -OpenDoorGoal::OpenDoorGoal(Mob *mob, bool closeDoorAfter) : DoorInteractGoal(mob) -{ - this->mob = mob; - this->closeDoor = closeDoorAfter; +OpenDoorGoal::OpenDoorGoal(Mob* mob, bool closeDoorAfter) + : DoorInteractGoal(mob) { + this->mob = mob; + this->closeDoor = closeDoorAfter; } -bool OpenDoorGoal::canContinueToUse() -{ - return closeDoor && forgetTime > 0 && DoorInteractGoal::canContinueToUse(); +bool OpenDoorGoal::canContinueToUse() { + return closeDoor && forgetTime > 0 && DoorInteractGoal::canContinueToUse(); } -void OpenDoorGoal::start() -{ - forgetTime = 20; - doorTile->setOpen(mob->level, doorX, doorY, doorZ, true); +void OpenDoorGoal::start() { + forgetTime = 20; + doorTile->setOpen(mob->level, doorX, doorY, doorZ, true); } -void OpenDoorGoal::stop() -{ - if (closeDoor) - { - doorTile->setOpen(mob->level, doorX, doorY, doorZ, false); - } +void OpenDoorGoal::stop() { + if (closeDoor) { + doorTile->setOpen(mob->level, doorX, doorY, doorZ, false); + } } -void OpenDoorGoal::tick() -{ - --forgetTime; - DoorInteractGoal::tick(); +void OpenDoorGoal::tick() { + --forgetTime; + DoorInteractGoal::tick(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OpenDoorGoal.h b/Minecraft.World/AI/Goals/OpenDoorGoal.h index ff27367a3..794082d52 100644 --- a/Minecraft.World/AI/Goals/OpenDoorGoal.h +++ b/Minecraft.World/AI/Goals/OpenDoorGoal.h @@ -2,17 +2,16 @@ #include "DoorInteractGoal.h" -class OpenDoorGoal : public DoorInteractGoal -{ +class OpenDoorGoal : public DoorInteractGoal { private: - bool closeDoor; - int forgetTime; + bool closeDoor; + int forgetTime; public: - OpenDoorGoal(Mob *mob, bool closeDoorAfter); + OpenDoorGoal(Mob* mob, bool closeDoorAfter); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.cpp b/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.cpp index 1fe6765a4..7a748cc35 100644 --- a/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.cpp @@ -3,23 +3,21 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "OwnerHurtByTargetGoal.h" -OwnerHurtByTargetGoal::OwnerHurtByTargetGoal(TamableAnimal *tameAnimal) : TargetGoal(tameAnimal, 32, false) -{ - this->tameAnimal = tameAnimal; - setRequiredControlFlags(TargetGoal::TargetFlag); +OwnerHurtByTargetGoal::OwnerHurtByTargetGoal(TamableAnimal* tameAnimal) + : TargetGoal(tameAnimal, 32, false) { + this->tameAnimal = tameAnimal; + setRequiredControlFlags(TargetGoal::TargetFlag); } -bool OwnerHurtByTargetGoal::canUse() -{ - if (!tameAnimal->isTame()) return false; - std::shared_ptr owner = tameAnimal->getOwner(); - if (owner == NULL) return false; - ownerLastHurtBy = std::weak_ptr(owner->getLastHurtByMob()); - return canAttack(ownerLastHurtBy.lock(), false); +bool OwnerHurtByTargetGoal::canUse() { + if (!tameAnimal->isTame()) return false; + std::shared_ptr owner = tameAnimal->getOwner(); + if (owner == NULL) return false; + ownerLastHurtBy = std::weak_ptr(owner->getLastHurtByMob()); + return canAttack(ownerLastHurtBy.lock(), false); } -void OwnerHurtByTargetGoal::start() -{ - mob->setTarget(ownerLastHurtBy.lock()); - TargetGoal::start(); +void OwnerHurtByTargetGoal::start() { + mob->setTarget(ownerLastHurtBy.lock()); + TargetGoal::start(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.h b/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.h index fa6d390b3..d80b59923 100644 --- a/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.h +++ b/Minecraft.World/AI/Goals/OwnerHurtByTargetGoal.h @@ -4,15 +4,14 @@ class TamableAnimal; -class OwnerHurtByTargetGoal : public TargetGoal -{ +class OwnerHurtByTargetGoal : public TargetGoal { private: - TamableAnimal *tameAnimal; // Owner of this goal - std::weak_ptr ownerLastHurtBy; + TamableAnimal* tameAnimal; // Owner of this goal + std::weak_ptr ownerLastHurtBy; public: - OwnerHurtByTargetGoal(TamableAnimal *tameAnimal); + OwnerHurtByTargetGoal(TamableAnimal* tameAnimal); - bool canUse(); - void start(); + bool canUse(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.cpp b/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.cpp index 34fac91c7..19c32e146 100644 --- a/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.cpp +++ b/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.cpp @@ -3,23 +3,21 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "OwnerHurtTargetGoal.h" -OwnerHurtTargetGoal::OwnerHurtTargetGoal(TamableAnimal *tameAnimal) : TargetGoal(tameAnimal, 32, false) -{ - this->tameAnimal = tameAnimal; - setRequiredControlFlags(TargetGoal::TargetFlag); +OwnerHurtTargetGoal::OwnerHurtTargetGoal(TamableAnimal* tameAnimal) + : TargetGoal(tameAnimal, 32, false) { + this->tameAnimal = tameAnimal; + setRequiredControlFlags(TargetGoal::TargetFlag); } -bool OwnerHurtTargetGoal::canUse() -{ - if (!tameAnimal->isTame()) return false; - std::shared_ptr owner = tameAnimal->getOwner(); - if (owner == NULL) return false; - ownerLastHurt = std::weak_ptr(owner->getLastHurtMob()); - return canAttack(ownerLastHurt.lock(), false); +bool OwnerHurtTargetGoal::canUse() { + if (!tameAnimal->isTame()) return false; + std::shared_ptr owner = tameAnimal->getOwner(); + if (owner == NULL) return false; + ownerLastHurt = std::weak_ptr(owner->getLastHurtMob()); + return canAttack(ownerLastHurt.lock(), false); } -void OwnerHurtTargetGoal::start() -{ - mob->setTarget(ownerLastHurt.lock()); - TargetGoal::start(); +void OwnerHurtTargetGoal::start() { + mob->setTarget(ownerLastHurt.lock()); + TargetGoal::start(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.h b/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.h index 947071c9b..46024ed98 100644 --- a/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.h +++ b/Minecraft.World/AI/Goals/OwnerHurtTargetGoal.h @@ -4,15 +4,14 @@ class TamableAnimal; -class OwnerHurtTargetGoal : public TargetGoal -{ +class OwnerHurtTargetGoal : public TargetGoal { private: - TamableAnimal *tameAnimal; // Owner of this goal - std::weak_ptr ownerLastHurt; + TamableAnimal* tameAnimal; // Owner of this goal + std::weak_ptr ownerLastHurt; public: - OwnerHurtTargetGoal(TamableAnimal *tameAnimal); + OwnerHurtTargetGoal(TamableAnimal* tameAnimal); - bool canUse(); - void start(); + bool canUse(); + void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/PanicGoal.cpp b/Minecraft.World/AI/Goals/PanicGoal.cpp index 895c1d3d5..6133b5c20 100644 --- a/Minecraft.World/AI/Goals/PanicGoal.cpp +++ b/Minecraft.World/AI/Goals/PanicGoal.cpp @@ -6,30 +6,26 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "PanicGoal.h" -PanicGoal::PanicGoal(PathfinderMob *mob, float speed) -{ - this->mob = mob; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag); +PanicGoal::PanicGoal(PathfinderMob* mob, float speed) { + this->mob = mob; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag); } -bool PanicGoal::canUse() -{ - if (mob->getLastHurtByMob() == NULL) return false; - Vec3 *pos = RandomPos::getPos(std::dynamic_pointer_cast(mob->shared_from_this()), 5, 4); - if (pos == NULL) return false; - posX = pos->x; - posY = pos->y; - posZ = pos->z; - return true; +bool PanicGoal::canUse() { + if (mob->getLastHurtByMob() == NULL) return false; + Vec3* pos = RandomPos::getPos( + std::dynamic_pointer_cast(mob->shared_from_this()), 5, + 4); + if (pos == NULL) return false; + posX = pos->x; + posY = pos->y; + posZ = pos->z; + return true; } -void PanicGoal::start() -{ - mob->getNavigation()->moveTo(posX, posY, posZ, speed); +void PanicGoal::start() { + mob->getNavigation()->moveTo(posX, posY, posZ, speed); } -bool PanicGoal::canContinueToUse() -{ - return !mob->getNavigation()->isDone(); -} \ No newline at end of file +bool PanicGoal::canContinueToUse() { return !mob->getNavigation()->isDone(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/PanicGoal.h b/Minecraft.World/AI/Goals/PanicGoal.h index 03d827824..7e4794b4a 100644 --- a/Minecraft.World/AI/Goals/PanicGoal.h +++ b/Minecraft.World/AI/Goals/PanicGoal.h @@ -4,17 +4,16 @@ class PathfinderMob; -class PanicGoal : public Goal -{ +class PanicGoal : public Goal { private: - PathfinderMob *mob; - float speed; - double posX, posY, posZ; + PathfinderMob* mob; + float speed; + double posX, posY, posZ; public: - PanicGoal(PathfinderMob *mob, float speed); + PanicGoal(PathfinderMob* mob, float speed); - virtual bool canUse(); - virtual void start(); - virtual bool canContinueToUse(); + virtual bool canUse(); + virtual void start(); + virtual bool canContinueToUse(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/PlayGoal.cpp b/Minecraft.World/AI/Goals/PlayGoal.cpp index b8cd4dffd..bdeb2e835 100644 --- a/Minecraft.World/AI/Goals/PlayGoal.cpp +++ b/Minecraft.World/AI/Goals/PlayGoal.cpp @@ -9,78 +9,75 @@ #include "../../Util/BasicTypeContainers.h" #include "PlayGoal.h" -PlayGoal::PlayGoal(Villager *mob, float speed) -{ - followFriend = std::weak_ptr(); - wantedX = wantedY = wantedZ = 0.0; - playTime = 0; +PlayGoal::PlayGoal(Villager* mob, float speed) { + followFriend = std::weak_ptr(); + wantedX = wantedY = wantedZ = 0.0; + playTime = 0; - this->mob = mob; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag); + this->mob = mob; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag); } -bool PlayGoal::canUse() -{ - if (mob->getAge() >= 0) return false; - if (mob->getRandom()->nextInt(400) != 0) return false; +bool PlayGoal::canUse() { + if (mob->getAge() >= 0) return false; + if (mob->getRandom()->nextInt(400) != 0) return false; - std::vector > *children = mob->level->getEntitiesOfClass(typeid(Villager), mob->bb->grow(6, 3, 6)); - double closestDistSqr = Double::MAX_VALUE; - //for (Entity c : children) - for(AUTO_VAR(it, children->begin()); it != children->end(); ++it) - { - std::shared_ptr c = *it; - if (c.get() == mob) continue; - std::shared_ptr friendV = std::dynamic_pointer_cast(c); - if (friendV->isChasing()) continue; - if (friendV->getAge() >= 0) continue; - double distSqr = friendV->distanceToSqr(mob->shared_from_this()); - if (distSqr > closestDistSqr) continue; - closestDistSqr = distSqr; - followFriend = std::weak_ptr(friendV); - } - delete children; + std::vector >* children = + mob->level->getEntitiesOfClass(typeid(Villager), + mob->bb->grow(6, 3, 6)); + double closestDistSqr = Double::MAX_VALUE; + // for (Entity c : children) + for (AUTO_VAR(it, children->begin()); it != children->end(); ++it) { + std::shared_ptr c = *it; + if (c.get() == mob) continue; + std::shared_ptr friendV = + std::dynamic_pointer_cast(c); + if (friendV->isChasing()) continue; + if (friendV->getAge() >= 0) continue; + double distSqr = friendV->distanceToSqr(mob->shared_from_this()); + if (distSqr > closestDistSqr) continue; + closestDistSqr = distSqr; + followFriend = std::weak_ptr(friendV); + } + delete children; - if (followFriend.lock() == NULL) - { - Vec3 *pos = RandomPos::getPos(std::dynamic_pointer_cast(mob->shared_from_this()), 16, 3); - if (pos == NULL) return false; - } - return true; + if (followFriend.lock() == NULL) { + Vec3* pos = RandomPos::getPos( + std::dynamic_pointer_cast(mob->shared_from_this()), + 16, 3); + if (pos == NULL) return false; + } + return true; } -bool PlayGoal::canContinueToUse() -{ - return playTime > 0 && followFriend.lock() != NULL; +bool PlayGoal::canContinueToUse() { + return playTime > 0 && followFriend.lock() != NULL; } -void PlayGoal::start() -{ - if (followFriend.lock() != NULL) mob->setChasing(true); - playTime = 1000; +void PlayGoal::start() { + if (followFriend.lock() != NULL) mob->setChasing(true); + playTime = 1000; } -void PlayGoal::stop() -{ - mob->setChasing(false); - followFriend = std::weak_ptr(); +void PlayGoal::stop() { + mob->setChasing(false); + followFriend = std::weak_ptr(); } -void PlayGoal::tick() -{ - --playTime; - if (followFriend.lock() != NULL) - { - if (mob->distanceToSqr(followFriend.lock()) > 2 * 2) mob->getNavigation()->moveTo(followFriend.lock(), speed); - } - else - { - if (mob->getNavigation()->isDone()) - { - Vec3 *pos = RandomPos::getPos(std::dynamic_pointer_cast(mob->shared_from_this()), 16, 3); - if (pos == NULL) return; - mob->getNavigation()->moveTo(pos->x, pos->y, pos->z, speed); - } - } +void PlayGoal::tick() { + --playTime; + if (followFriend.lock() != NULL) { + if (mob->distanceToSqr(followFriend.lock()) > 2 * 2) + mob->getNavigation()->moveTo(followFriend.lock(), speed); + } else { + if (mob->getNavigation()->isDone()) { + Vec3* pos = + RandomPos::getPos(std::dynamic_pointer_cast( + mob->shared_from_this()), + 16, 3); + if (pos == NULL) return; + mob->getNavigation()->moveTo(pos->x, pos->y, pos->z, speed); + } + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/PlayGoal.h b/Minecraft.World/AI/Goals/PlayGoal.h index f70df968e..758666d33 100644 --- a/Minecraft.World/AI/Goals/PlayGoal.h +++ b/Minecraft.World/AI/Goals/PlayGoal.h @@ -2,21 +2,20 @@ #include "Goal.h" -class PlayGoal : public Goal -{ +class PlayGoal : public Goal { private: - Villager *mob; - std::weak_ptr followFriend; - float speed; - double wantedX, wantedY, wantedZ; - int playTime; + Villager* mob; + std::weak_ptr followFriend; + float speed; + double wantedX, wantedY, wantedZ; + int playTime; public: - PlayGoal(Villager *mob, float speed); + PlayGoal(Villager* mob, float speed); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RandomLookAroundGoal.cpp b/Minecraft.World/AI/Goals/RandomLookAroundGoal.cpp index 7c53b2d6a..570735bcd 100644 --- a/Minecraft.World/AI/Goals/RandomLookAroundGoal.cpp +++ b/Minecraft.World/AI/Goals/RandomLookAroundGoal.cpp @@ -3,35 +3,31 @@ #include "../../Headers/net.minecraft.world.entity.ai.control.h" #include "RandomLookAroundGoal.h" -RandomLookAroundGoal::RandomLookAroundGoal(Mob *mob) -{ - relX = relZ = 0.0; - lookTime = 0; +RandomLookAroundGoal::RandomLookAroundGoal(Mob* mob) { + relX = relZ = 0.0; + lookTime = 0; - this->mob = mob; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->mob = mob; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool RandomLookAroundGoal::canUse() -{ - return mob->getRandom()->nextFloat() < 0.02f; +bool RandomLookAroundGoal::canUse() { + return mob->getRandom()->nextFloat() < 0.02f; } -bool RandomLookAroundGoal::canContinueToUse() -{ - return lookTime >= 0; +bool RandomLookAroundGoal::canContinueToUse() { return lookTime >= 0; } + +void RandomLookAroundGoal::start() { + double rnd = 2 * PI * mob->getRandom()->nextDouble(); + relX = cos(rnd); + relZ = sin(rnd); + lookTime = 20 + mob->getRandom()->nextInt(20); } -void RandomLookAroundGoal::start() -{ - double rnd = 2 * PI * mob->getRandom()->nextDouble(); - relX = cos(rnd); - relZ = sin(rnd); - lookTime = 20 + mob->getRandom()->nextInt(20); -} - -void RandomLookAroundGoal::tick() -{ - --lookTime; - mob->getLookControl()->setLookAt(mob->x + relX, mob->y + mob->getHeadHeight(), mob->z + relZ, 10, mob->getMaxHeadXRot()); +void RandomLookAroundGoal::tick() { + --lookTime; + mob->getLookControl()->setLookAt(mob->x + relX, + mob->y + mob->getHeadHeight(), + mob->z + relZ, 10, mob->getMaxHeadXRot()); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RandomLookAroundGoal.h b/Minecraft.World/AI/Goals/RandomLookAroundGoal.h index 76d4c7ad2..a4d179632 100644 --- a/Minecraft.World/AI/Goals/RandomLookAroundGoal.h +++ b/Minecraft.World/AI/Goals/RandomLookAroundGoal.h @@ -2,18 +2,17 @@ #include "Goal.h" -class RandomLookAroundGoal : public Goal -{ +class RandomLookAroundGoal : public Goal { private: - Mob *mob; - double relX, relZ; - int lookTime; + Mob* mob; + double relX, relZ; + int lookTime; public: - RandomLookAroundGoal(Mob *mob); + RandomLookAroundGoal(Mob* mob); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RandomStrollGoal.cpp b/Minecraft.World/AI/Goals/RandomStrollGoal.cpp index 7c5d10a9d..0dbd86fb8 100644 --- a/Minecraft.World/AI/Goals/RandomStrollGoal.cpp +++ b/Minecraft.World/AI/Goals/RandomStrollGoal.cpp @@ -7,54 +7,55 @@ #include "../../Util/SharedConstants.h" #include "RandomStrollGoal.h" -RandomStrollGoal::RandomStrollGoal(PathfinderMob *mob, float speed) -{ - this->mob = mob; - this->speed = speed; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); +RandomStrollGoal::RandomStrollGoal(PathfinderMob* mob, float speed) { + this->mob = mob; + this->speed = speed; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool RandomStrollGoal::canUse() -{ - // 4J - altered a little so we can do some more random strolling when appropriate, to try and move any animals that aren't confined to a fenced-off region far enough to determine we can despawn them - if (mob->getNoActionTime() < SharedConstants::TICKS_PER_SECOND * 5) - { - if (mob->getRandom()->nextInt(120) == 0) - { - Vec3 *pos = RandomPos::getPos(std::dynamic_pointer_cast(mob->shared_from_this()), 10, 7); - if (pos == NULL) return false; - wantedX = pos->x; - wantedY = pos->y; - wantedZ = pos->z; - return true; - } - } - else - { - // This entity wouldn't normally be randomly strolling. However, if our management system says that it should do, then do. Don't - // bother waiting for random conditions to be met before picking a direction though as the point here is to see if it is possible to - // stroll out of a given area and so waiting around is just wasting time +bool RandomStrollGoal::canUse() { + // 4J - altered a little so we can do some more random strolling when + // appropriate, to try and move any animals that aren't confined to a + // fenced-off region far enough to determine we can despawn them + if (mob->getNoActionTime() < SharedConstants::TICKS_PER_SECOND * 5) { + if (mob->getRandom()->nextInt(120) == 0) { + Vec3* pos = + RandomPos::getPos(std::dynamic_pointer_cast( + mob->shared_from_this()), + 10, 7); + if (pos == NULL) return false; + wantedX = pos->x; + wantedY = pos->y; + wantedZ = pos->z; + return true; + } + } else { + // This entity wouldn't normally be randomly strolling. However, if our + // management system says that it should do, then do. Don't bother + // waiting for random conditions to be met before picking a direction + // though as the point here is to see if it is possible to stroll out of + // a given area and so waiting around is just wasting time - if( mob->isExtraWanderingEnabled() ) - { - Vec3 *pos = RandomPos::getPos(std::dynamic_pointer_cast(mob->shared_from_this()), 10, 7,mob->getWanderingQuadrant()); - if (pos == NULL) return false; - wantedX = pos->x; - wantedY = pos->y; - wantedZ = pos->z; - return true; - } - - } - return false; + if (mob->isExtraWanderingEnabled()) { + Vec3* pos = + RandomPos::getPos(std::dynamic_pointer_cast( + mob->shared_from_this()), + 10, 7, mob->getWanderingQuadrant()); + if (pos == NULL) return false; + wantedX = pos->x; + wantedY = pos->y; + wantedZ = pos->z; + return true; + } + } + return false; } -bool RandomStrollGoal::canContinueToUse() -{ - return !mob->getNavigation()->isDone(); +bool RandomStrollGoal::canContinueToUse() { + return !mob->getNavigation()->isDone(); } -void RandomStrollGoal::start() -{ - mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); +void RandomStrollGoal::start() { + mob->getNavigation()->moveTo(wantedX, wantedY, wantedZ, speed); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RandomStrollGoal.h b/Minecraft.World/AI/Goals/RandomStrollGoal.h index e46a9c952..3e7bb17cb 100644 --- a/Minecraft.World/AI/Goals/RandomStrollGoal.h +++ b/Minecraft.World/AI/Goals/RandomStrollGoal.h @@ -4,17 +4,16 @@ class PathfinderMob; -class RandomStrollGoal : public Goal -{ +class RandomStrollGoal : public Goal { private: - PathfinderMob *mob; - double wantedX, wantedY, wantedZ; - float speed; + PathfinderMob* mob; + double wantedX, wantedY, wantedZ; + float speed; public: - RandomStrollGoal(PathfinderMob *mob, float speed); + RandomStrollGoal(PathfinderMob* mob, float speed); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.cpp b/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.cpp index 620303deb..f43ee13e1 100644 --- a/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.cpp +++ b/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.cpp @@ -5,45 +5,44 @@ #include "../../Headers/net.minecraft.world.level.h" #include "RestrictOpenDoorGoal.h" -RestrictOpenDoorGoal::RestrictOpenDoorGoal(PathfinderMob *mob) -{ - this->mob = mob; +RestrictOpenDoorGoal::RestrictOpenDoorGoal(PathfinderMob* mob) { + this->mob = mob; } -bool RestrictOpenDoorGoal::canUse() -{ - if (mob->level->isDay()) return false; - std::shared_ptr village = mob->level->villages->getClosestVillage(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 16); - if (village == NULL) return false; - std::shared_ptr _doorInfo = village->getClosestDoorInfo(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); - if (_doorInfo == NULL) return false; - doorInfo = _doorInfo; - return _doorInfo->distanceToInsideSqr(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)) < 1.5 * 1.5; +bool RestrictOpenDoorGoal::canUse() { + if (mob->level->isDay()) return false; + std::shared_ptr village = mob->level->villages->getClosestVillage( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z), 16); + if (village == NULL) return false; + std::shared_ptr _doorInfo = village->getClosestDoorInfo( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); + if (_doorInfo == NULL) return false; + doorInfo = _doorInfo; + return _doorInfo->distanceToInsideSqr(Mth::floor(mob->x), + Mth::floor(mob->y), + Mth::floor(mob->z)) < 1.5 * 1.5; } -bool RestrictOpenDoorGoal::canContinueToUse() -{ - if (mob->level->isDay()) return false; - std::shared_ptr _doorInfo = doorInfo.lock(); - if ( _doorInfo == NULL ) return false; - return !_doorInfo->removed && _doorInfo->isInsideSide(Mth::floor(mob->x), Mth::floor(mob->z)); +bool RestrictOpenDoorGoal::canContinueToUse() { + if (mob->level->isDay()) return false; + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo == NULL) return false; + return !_doorInfo->removed && + _doorInfo->isInsideSide(Mth::floor(mob->x), Mth::floor(mob->z)); } -void RestrictOpenDoorGoal::start() -{ - mob->getNavigation()->setCanOpenDoors(false); - mob->getNavigation()->setCanPassDoors(false); +void RestrictOpenDoorGoal::start() { + mob->getNavigation()->setCanOpenDoors(false); + mob->getNavigation()->setCanPassDoors(false); } -void RestrictOpenDoorGoal::stop() -{ - mob->getNavigation()->setCanOpenDoors(true); - mob->getNavigation()->setCanPassDoors(true); - doorInfo = std::weak_ptr(); +void RestrictOpenDoorGoal::stop() { + mob->getNavigation()->setCanOpenDoors(true); + mob->getNavigation()->setCanPassDoors(true); + doorInfo = std::weak_ptr(); } -void RestrictOpenDoorGoal::tick() -{ - std::shared_ptr _doorInfo = doorInfo.lock(); - if ( _doorInfo ) _doorInfo->incBookingCount(); +void RestrictOpenDoorGoal::tick() { + std::shared_ptr _doorInfo = doorInfo.lock(); + if (_doorInfo) _doorInfo->incBookingCount(); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.h b/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.h index 38ce88655..3311dadc7 100644 --- a/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.h +++ b/Minecraft.World/AI/Goals/RestrictOpenDoorGoal.h @@ -5,18 +5,17 @@ class PathfinderMob; class DoorInfo; -class RestrictOpenDoorGoal : public Goal -{ +class RestrictOpenDoorGoal : public Goal { private: - PathfinderMob *mob; - std::weak_ptr doorInfo; + PathfinderMob* mob; + std::weak_ptr doorInfo; public: - RestrictOpenDoorGoal(PathfinderMob *mob); + RestrictOpenDoorGoal(PathfinderMob* mob); - virtual bool canUse(); - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); - virtual void tick(); + virtual bool canUse(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RestrictSunGoal.cpp b/Minecraft.World/AI/Goals/RestrictSunGoal.cpp index 6bce7d6f9..647e15383 100644 --- a/Minecraft.World/AI/Goals/RestrictSunGoal.cpp +++ b/Minecraft.World/AI/Goals/RestrictSunGoal.cpp @@ -4,22 +4,10 @@ #include "../../Headers/net.minecraft.world.level.h" #include "RestrictSunGoal.h" -RestrictSunGoal::RestrictSunGoal(PathfinderMob *mob) -{ - this->mob = mob; -} +RestrictSunGoal::RestrictSunGoal(PathfinderMob* mob) { this->mob = mob; } -bool RestrictSunGoal::canUse() -{ - return mob->level->isDay(); -} +bool RestrictSunGoal::canUse() { return mob->level->isDay(); } -void RestrictSunGoal::start() -{ - mob->getNavigation()->setAvoidSun(true); -} +void RestrictSunGoal::start() { mob->getNavigation()->setAvoidSun(true); } -void RestrictSunGoal::stop() -{ - mob->getNavigation()->setAvoidSun(false); -} \ No newline at end of file +void RestrictSunGoal::stop() { mob->getNavigation()->setAvoidSun(false); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/RestrictSunGoal.h b/Minecraft.World/AI/Goals/RestrictSunGoal.h index bf89aeef0..9ecba9d41 100644 --- a/Minecraft.World/AI/Goals/RestrictSunGoal.h +++ b/Minecraft.World/AI/Goals/RestrictSunGoal.h @@ -2,15 +2,14 @@ #include "Goal.h" -class RestrictSunGoal : public Goal -{ +class RestrictSunGoal : public Goal { private: - PathfinderMob *mob; + PathfinderMob* mob; public: - RestrictSunGoal(PathfinderMob *mob); + RestrictSunGoal(PathfinderMob* mob); - bool canUse(); - void start(); - void stop(); + bool canUse(); + void start(); + void stop(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/SitGoal.cpp b/Minecraft.World/AI/Goals/SitGoal.cpp index 174cd5889..e3902076a 100644 --- a/Minecraft.World/AI/Goals/SitGoal.cpp +++ b/Minecraft.World/AI/Goals/SitGoal.cpp @@ -6,40 +6,35 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "SitGoal.h" -SitGoal::SitGoal(TamableAnimal *mob) -{ - _wantToSit = false; +SitGoal::SitGoal(TamableAnimal* mob) { + _wantToSit = false; - this->mob = mob; - setRequiredControlFlags(Control::JumpControlFlag | Control::MoveControlFlag); + this->mob = mob; + setRequiredControlFlags(Control::JumpControlFlag | + Control::MoveControlFlag); } -bool SitGoal::canUse() -{ - if (!mob->isTame()) return false; - if (mob->isInWater()) return false; - if (!mob->onGround) return false; +bool SitGoal::canUse() { + if (!mob->isTame()) return false; + if (mob->isInWater()) return false; + if (!mob->onGround) return false; - std::shared_ptr owner = mob->getOwner(); - if (owner == NULL) return true; // owner not on level + std::shared_ptr owner = mob->getOwner(); + if (owner == NULL) return true; // owner not on level - if (mob->distanceToSqr(owner) < FollowOwnerGoal::TeleportDistance * FollowOwnerGoal::TeleportDistance && owner->getLastHurtByMob() != NULL) return false; + if (mob->distanceToSqr(owner) < FollowOwnerGoal::TeleportDistance * + FollowOwnerGoal::TeleportDistance && + owner->getLastHurtByMob() != NULL) + return false; - return _wantToSit; + return _wantToSit; } -void SitGoal::start() -{ - mob->getNavigation()->stop(); - mob->setSitting(true); +void SitGoal::start() { + mob->getNavigation()->stop(); + mob->setSitting(true); } -void SitGoal::stop() -{ - mob->setSitting(false); -} +void SitGoal::stop() { mob->setSitting(false); } -void SitGoal::wantToSit(bool _wantToSit) -{ - this->_wantToSit = _wantToSit; -} \ No newline at end of file +void SitGoal::wantToSit(bool _wantToSit) { this->_wantToSit = _wantToSit; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/SitGoal.h b/Minecraft.World/AI/Goals/SitGoal.h index 542ab18cb..543920bda 100644 --- a/Minecraft.World/AI/Goals/SitGoal.h +++ b/Minecraft.World/AI/Goals/SitGoal.h @@ -2,17 +2,16 @@ #include "Goal.h" -class SitGoal : public Goal -{ +class SitGoal : public Goal { private: - TamableAnimal *mob; - bool _wantToSit; + TamableAnimal* mob; + bool _wantToSit; public: - SitGoal(TamableAnimal *mob); + SitGoal(TamableAnimal* mob); - bool canUse(); - void start(); - void stop(); - void wantToSit(bool _wantToSit); + bool canUse(); + void start(); + void stop(); + void wantToSit(bool _wantToSit); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/SwellGoal.cpp b/Minecraft.World/AI/Goals/SwellGoal.cpp index fca35e9e7..0d64e6064 100644 --- a/Minecraft.World/AI/Goals/SwellGoal.cpp +++ b/Minecraft.World/AI/Goals/SwellGoal.cpp @@ -5,50 +5,41 @@ #include "../../Headers/net.minecraft.world.entity.monster.h" #include "SwellGoal.h" -SwellGoal::SwellGoal(Creeper *creeper) -{ - target = std::weak_ptr(); +SwellGoal::SwellGoal(Creeper* creeper) { + target = std::weak_ptr(); - this->creeper = creeper; - setRequiredControlFlags(Control::MoveControlFlag); + this->creeper = creeper; + setRequiredControlFlags(Control::MoveControlFlag); } -bool SwellGoal::canUse() -{ - std::shared_ptr target = creeper->getTarget(); - return creeper->getSwellDir() > 0 || (target != NULL && (creeper->distanceToSqr(target) < 3 * 3)); +bool SwellGoal::canUse() { + std::shared_ptr target = creeper->getTarget(); + return creeper->getSwellDir() > 0 || + (target != NULL && (creeper->distanceToSqr(target) < 3 * 3)); } -void SwellGoal::start() -{ - creeper->getNavigation()->stop(); - target = std::weak_ptr(creeper->getTarget()); +void SwellGoal::start() { + creeper->getNavigation()->stop(); + target = std::weak_ptr(creeper->getTarget()); } -void SwellGoal::stop() -{ - target = std::weak_ptr(); -} - -void SwellGoal::tick() -{ - if (target.lock() == NULL) - { - creeper->setSwellDir(-1); - return; - } - - if (creeper->distanceToSqr(target.lock()) > 7 * 7) - { - creeper->setSwellDir(-1); - return; - } - - if (!creeper->getSensing()->canSee(target.lock())) - { - creeper->setSwellDir(-1); - return; - } - - creeper->setSwellDir(1); +void SwellGoal::stop() { target = std::weak_ptr(); } + +void SwellGoal::tick() { + if (target.lock() == NULL) { + creeper->setSwellDir(-1); + return; + } + + if (creeper->distanceToSqr(target.lock()) > 7 * 7) { + creeper->setSwellDir(-1); + return; + } + + if (!creeper->getSensing()->canSee(target.lock())) { + creeper->setSwellDir(-1); + return; + } + + creeper->setSwellDir(1); } diff --git a/Minecraft.World/AI/Goals/SwellGoal.h b/Minecraft.World/AI/Goals/SwellGoal.h index 0d4e586b9..f6ece0f21 100644 --- a/Minecraft.World/AI/Goals/SwellGoal.h +++ b/Minecraft.World/AI/Goals/SwellGoal.h @@ -4,17 +4,16 @@ class Creeper; -class SwellGoal : public Goal -{ +class SwellGoal : public Goal { private: - Creeper *creeper; - std::weak_ptr target; + Creeper* creeper; + std::weak_ptr target; public: - SwellGoal(Creeper *creeper); + SwellGoal(Creeper* creeper); - bool canUse(); - void start(); - void stop(); - void tick(); + bool canUse(); + void start(); + void stop(); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TakeFlowerGoal.cpp b/Minecraft.World/AI/Goals/TakeFlowerGoal.cpp index 4a578bf04..0a872b8a8 100644 --- a/Minecraft.World/AI/Goals/TakeFlowerGoal.cpp +++ b/Minecraft.World/AI/Goals/TakeFlowerGoal.cpp @@ -8,75 +8,68 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "TakeFlowerGoal.h" -TakeFlowerGoal::TakeFlowerGoal(Villager *villager) -{ - takeFlower = false; - pickupTick = 0; - golem = std::weak_ptr(); +TakeFlowerGoal::TakeFlowerGoal(Villager* villager) { + takeFlower = false; + pickupTick = 0; + golem = std::weak_ptr(); - this->villager = villager; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->villager = villager; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool TakeFlowerGoal::canUse() -{ - if (villager->getAge() >= 0) return false; - if (!villager->level->isDay()) return false; +bool TakeFlowerGoal::canUse() { + if (villager->getAge() >= 0) return false; + if (!villager->level->isDay()) return false; - std::vector > *golems = villager->level->getEntitiesOfClass(typeid(VillagerGolem), villager->bb->grow(6, 2, 6)); - if (golems->size() == 0) - { - delete golems; - return false; - } + std::vector >* golems = + villager->level->getEntitiesOfClass(typeid(VillagerGolem), + villager->bb->grow(6, 2, 6)); + if (golems->size() == 0) { + delete golems; + return false; + } - //for (Entity e : golems) - for(AUTO_VAR(it,golems->begin()); it != golems->end(); ++it) - { - std::shared_ptr vg = std::dynamic_pointer_cast(*it); - if (vg->getOfferFlowerTick() > 0) - { - golem = std::weak_ptr(vg); - break; - } - } - delete golems; - return golem.lock() != NULL; + // for (Entity e : golems) + for (AUTO_VAR(it, golems->begin()); it != golems->end(); ++it) { + std::shared_ptr vg = + std::dynamic_pointer_cast(*it); + if (vg->getOfferFlowerTick() > 0) { + golem = std::weak_ptr(vg); + break; + } + } + delete golems; + return golem.lock() != NULL; } -bool TakeFlowerGoal::canContinueToUse() -{ - return golem.lock() != NULL && golem.lock()->getOfferFlowerTick() > 0; +bool TakeFlowerGoal::canContinueToUse() { + return golem.lock() != NULL && golem.lock()->getOfferFlowerTick() > 0; } -void TakeFlowerGoal::start() -{ - pickupTick = villager->getRandom()->nextInt((int) (OfferFlowerGoal::OFFER_TICKS * 0.8)); - takeFlower = false; - golem.lock()->getNavigation()->stop(); +void TakeFlowerGoal::start() { + pickupTick = villager->getRandom()->nextInt( + (int)(OfferFlowerGoal::OFFER_TICKS * 0.8)); + takeFlower = false; + golem.lock()->getNavigation()->stop(); } -void TakeFlowerGoal::stop() -{ - golem = std::weak_ptr(); - villager->getNavigation()->stop(); +void TakeFlowerGoal::stop() { + golem = std::weak_ptr(); + villager->getNavigation()->stop(); } -void TakeFlowerGoal::tick() -{ - villager->getLookControl()->setLookAt(golem.lock(), 30, 30); - if (golem.lock()->getOfferFlowerTick() == pickupTick) - { - villager->getNavigation()->moveTo(golem.lock(), 0.15f); - takeFlower = true; - } +void TakeFlowerGoal::tick() { + villager->getLookControl()->setLookAt(golem.lock(), 30, 30); + if (golem.lock()->getOfferFlowerTick() == pickupTick) { + villager->getNavigation()->moveTo(golem.lock(), 0.15f); + takeFlower = true; + } - if (takeFlower) - { - if (villager->distanceToSqr(golem.lock()) < 2 * 2) - { - golem.lock()->offerFlower(false); - villager->getNavigation()->stop(); - } - } + if (takeFlower) { + if (villager->distanceToSqr(golem.lock()) < 2 * 2) { + golem.lock()->offerFlower(false); + villager->getNavigation()->stop(); + } + } } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TakeFlowerGoal.h b/Minecraft.World/AI/Goals/TakeFlowerGoal.h index 5984a241e..d1c95f619 100644 --- a/Minecraft.World/AI/Goals/TakeFlowerGoal.h +++ b/Minecraft.World/AI/Goals/TakeFlowerGoal.h @@ -2,20 +2,19 @@ #include "Goal.h" -class TakeFlowerGoal : public Goal -{ +class TakeFlowerGoal : public Goal { private: - Villager *villager; - std::weak_ptr golem; - int pickupTick; - bool takeFlower; + Villager* villager; + std::weak_ptr golem; + int pickupTick; + bool takeFlower; public: - TakeFlowerGoal(Villager *villager); + TakeFlowerGoal(Villager* villager); - bool canUse(); - bool canContinueToUse(); - void start(); - void stop(); - void tick(); + bool canUse(); + bool canContinueToUse(); + void start(); + void stop(); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TargetGoal.cpp b/Minecraft.World/AI/Goals/TargetGoal.cpp index ac81918bd..7e515374c 100644 --- a/Minecraft.World/AI/Goals/TargetGoal.cpp +++ b/Minecraft.World/AI/Goals/TargetGoal.cpp @@ -8,106 +8,95 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "TargetGoal.h" -void TargetGoal::_init(Mob *mob, float within, bool mustSee, bool mustReach) -{ - reachCache = EmptyReachCache; - reachCacheTime = 0; - unseenTicks = 0; +void TargetGoal::_init(Mob* mob, float within, bool mustSee, bool mustReach) { + reachCache = EmptyReachCache; + reachCacheTime = 0; + unseenTicks = 0; - this->mob = mob; - this->within = within; - this->mustSee = mustSee; - this->mustReach = mustReach; + this->mob = mob; + this->within = within; + this->mustSee = mustSee; + this->mustReach = mustReach; } -TargetGoal::TargetGoal(Mob *mob, float within, bool mustSee) -{ - _init(mob, within, mustSee, false); +TargetGoal::TargetGoal(Mob* mob, float within, bool mustSee) { + _init(mob, within, mustSee, false); } -TargetGoal::TargetGoal(Mob *mob, float within, bool mustSee, bool mustReach) -{ - _init(mob,within,mustSee,mustReach); +TargetGoal::TargetGoal(Mob* mob, float within, bool mustSee, bool mustReach) { + _init(mob, within, mustSee, mustReach); } -bool TargetGoal::canContinueToUse() -{ - std::shared_ptr target = mob->getTarget(); - if (target == NULL) return false; - if (!target->isAlive()) return false; - if (mob->distanceToSqr(target) > within * within) return false; - if (mustSee) - { - if (mob->getSensing()->canSee(target)) - { - unseenTicks = 0; - } - else - { - if (++unseenTicks > UnseenMemoryTicks) return false; - } - } - return true; +bool TargetGoal::canContinueToUse() { + std::shared_ptr target = mob->getTarget(); + if (target == NULL) return false; + if (!target->isAlive()) return false; + if (mob->distanceToSqr(target) > within * within) return false; + if (mustSee) { + if (mob->getSensing()->canSee(target)) { + unseenTicks = 0; + } else { + if (++unseenTicks > UnseenMemoryTicks) return false; + } + } + return true; } -void TargetGoal::start() -{ - reachCache = EmptyReachCache; - reachCacheTime = 0; - unseenTicks = 0; +void TargetGoal::start() { + reachCache = EmptyReachCache; + reachCacheTime = 0; + unseenTicks = 0; } -void TargetGoal::stop() -{ - mob->setTarget(nullptr); +void TargetGoal::stop() { mob->setTarget(nullptr); } + +bool TargetGoal::canAttack(std::shared_ptr target, + bool allowInvulnerable) { + if (target == NULL) return false; + if (target == mob->shared_from_this()) return false; + if (!target->isAlive()) return false; + if (!mob->canAttackType(target->GetType())) return false; + + std::shared_ptr tamableAnimal = + std::dynamic_pointer_cast(mob->shared_from_this()); + if (tamableAnimal != NULL && tamableAnimal->isTame()) { + std::shared_ptr tamableTarget = + std::dynamic_pointer_cast(target); + if (tamableTarget != NULL && tamableTarget->isTame()) return false; + if (target == tamableAnimal->getOwner()) return false; + } else if (std::dynamic_pointer_cast(target) != NULL) { + if (!allowInvulnerable && + (std::dynamic_pointer_cast(target))->abilities.invulnerable) + return false; + } + + if (!mob->isWithinRestriction(Mth::floor(target->x), Mth::floor(target->y), + Mth::floor(target->z))) + return false; + + if (mustSee && !mob->getSensing()->canSee(target)) return false; + + if (mustReach) { + if (--reachCacheTime <= 0) reachCache = EmptyReachCache; + if (reachCache == EmptyReachCache) + reachCache = canReach(target) ? CanReachCache : CantReachCache; + if (reachCache == CantReachCache) return false; + } + + return true; } -bool TargetGoal::canAttack(std::shared_ptr target, bool allowInvulnerable) -{ - if (target == NULL) return false; - if (target == mob->shared_from_this()) return false; - if (!target->isAlive()) return false; - if (!mob->canAttackType(target->GetType())) return false; - - std::shared_ptr tamableAnimal = std::dynamic_pointer_cast(mob->shared_from_this()); - if (tamableAnimal != NULL && tamableAnimal->isTame()) - { - std::shared_ptr tamableTarget = std::dynamic_pointer_cast(target); - if (tamableTarget != NULL && tamableTarget->isTame()) return false; - if (target == tamableAnimal->getOwner()) return false; - } - else if (std::dynamic_pointer_cast(target) != NULL) - { - if (!allowInvulnerable && (std::dynamic_pointer_cast(target))->abilities.invulnerable) return false; - } - - if (!mob->isWithinRestriction(Mth::floor(target->x), Mth::floor(target->y), Mth::floor(target->z))) return false; - - if (mustSee && !mob->getSensing()->canSee(target)) return false; - - if (mustReach) - { - if (--reachCacheTime <= 0) reachCache = EmptyReachCache; - if (reachCache == EmptyReachCache) reachCache = canReach(target) ? CanReachCache : CantReachCache; - if (reachCache == CantReachCache) return false; - } - - return true; -} - -bool TargetGoal::canReach(std::shared_ptr target) -{ - reachCacheTime = 10 + mob->getRandom()->nextInt(5); - Path *path = mob->getNavigation()->createPath(target); - if (path == NULL) return false; - Node *last = path->last(); - if (last == NULL) - { - delete path; - return false; - } - int xx = last->x - Mth::floor(target->x); - int zz = last->z - Mth::floor(target->z); - delete path; - return xx * xx + zz * zz <= 1.5 * 1.5; +bool TargetGoal::canReach(std::shared_ptr target) { + reachCacheTime = 10 + mob->getRandom()->nextInt(5); + Path* path = mob->getNavigation()->createPath(target); + if (path == NULL) return false; + Node* last = path->last(); + if (last == NULL) { + delete path; + return false; + } + int xx = last->x - Mth::floor(target->x); + int zz = last->z - Mth::floor(target->z); + delete path; + return xx * xx + zz * zz <= 1.5 * 1.5; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TargetGoal.h b/Minecraft.World/AI/Goals/TargetGoal.h index 2e6765fec..2789e02da 100644 --- a/Minecraft.World/AI/Goals/TargetGoal.h +++ b/Minecraft.World/AI/Goals/TargetGoal.h @@ -2,43 +2,41 @@ #include "Goal.h" -class TargetGoal : public Goal -{ - +class TargetGoal : public Goal { public: - static const int TargetFlag = 1; + static const int TargetFlag = 1; private: - static const int EmptyReachCache = 0; - static const int CanReachCache = 1; - static const int CantReachCache = 2; - static const int UnseenMemoryTicks = 60; + static const int EmptyReachCache = 0; + static const int CanReachCache = 1; + static const int CantReachCache = 2; + static const int UnseenMemoryTicks = 60; protected: - Mob *mob; // Owner of this goal - float within; - bool mustSee; + Mob* mob; // Owner of this goal + float within; + bool mustSee; private: - bool mustReach; - int reachCache; - int reachCacheTime; - int unseenTicks; + bool mustReach; + int reachCache; + int reachCacheTime; + int unseenTicks; - void _init(Mob *mob, float within, bool mustSee, bool mustReach); + void _init(Mob* mob, float within, bool mustSee, bool mustReach); public: - TargetGoal(Mob *mob, float within, bool mustSee); - TargetGoal(Mob *mob, float within, bool mustSee, bool mustReach); - virtual ~TargetGoal() {} + TargetGoal(Mob* mob, float within, bool mustSee); + TargetGoal(Mob* mob, float within, bool mustSee, bool mustReach); + virtual ~TargetGoal() {} - virtual bool canContinueToUse(); - virtual void start(); - virtual void stop(); + virtual bool canContinueToUse(); + virtual void start(); + virtual void stop(); protected: - virtual bool canAttack(std::shared_ptr target, bool allowInvulnerable); + virtual bool canAttack(std::shared_ptr target, bool allowInvulnerable); private: - bool canReach(std::shared_ptr target); + bool canReach(std::shared_ptr target); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TemptGoal.cpp b/Minecraft.World/AI/Goals/TemptGoal.cpp index 89c160620..3893ee73f 100644 --- a/Minecraft.World/AI/Goals/TemptGoal.cpp +++ b/Minecraft.World/AI/Goals/TemptGoal.cpp @@ -6,86 +6,82 @@ #include "../../Headers/net.minecraft.world.level.h" #include "TemptGoal.h" -TemptGoal::TemptGoal(PathfinderMob *mob, float speed, int itemId, bool canScare) -{ - px = py = pz = pRotX = pRotY = 0.0; - player = std::weak_ptr(); - calmDown = 0; - _isRunning = false; - oldAvoidWater = false; +TemptGoal::TemptGoal(PathfinderMob* mob, float speed, int itemId, + bool canScare) { + px = py = pz = pRotX = pRotY = 0.0; + player = std::weak_ptr(); + calmDown = 0; + _isRunning = false; + oldAvoidWater = false; - this->mob = mob; - this->speed = speed; - this->itemId = itemId; - this->canScare = canScare; - setRequiredControlFlags(Control::MoveControlFlag | Control::LookControlFlag); + this->mob = mob; + this->speed = speed; + this->itemId = itemId; + this->canScare = canScare; + setRequiredControlFlags(Control::MoveControlFlag | + Control::LookControlFlag); } -bool TemptGoal::canUse() -{ - if (calmDown > 0) - { - --calmDown; - return false; - } - player = std::weak_ptr(mob->level->getNearestPlayer(mob->shared_from_this(), 10)); - if (player.lock() == NULL) return false; - mob->setDespawnProtected(); // If we've got a nearby player, then consider this mob as something we'd miss if it despawned - std::shared_ptr item = player.lock()->getSelectedItem(); - if (item == NULL) return false; - if (item->id != itemId) return false; - return true; +bool TemptGoal::canUse() { + if (calmDown > 0) { + --calmDown; + return false; + } + player = std::weak_ptr( + mob->level->getNearestPlayer(mob->shared_from_this(), 10)); + if (player.lock() == NULL) return false; + mob->setDespawnProtected(); // If we've got a nearby player, then consider + // this mob as something we'd miss if it + // despawned + std::shared_ptr item = player.lock()->getSelectedItem(); + if (item == NULL) return false; + if (item->id != itemId) return false; + return true; } -bool TemptGoal::canContinueToUse() -{ - if (canScare) - { - if(player.lock() == NULL) return false; - if (mob->distanceToSqr(player.lock()) < 6 * 6) - { - if (player.lock()->distanceToSqr(px, py, pz) > 0.1 * 0.1) return false; - if (abs(player.lock()->xRot - pRotX) > 5 || abs(player.lock()->yRot - pRotY) > 5) return false; - } - else - { - px = player.lock()->x; - py = player.lock()->y; - pz = player.lock()->z; - } - pRotX = player.lock()->xRot; - pRotY = player.lock()->yRot; - } - return canUse(); +bool TemptGoal::canContinueToUse() { + if (canScare) { + if (player.lock() == NULL) return false; + if (mob->distanceToSqr(player.lock()) < 6 * 6) { + if (player.lock()->distanceToSqr(px, py, pz) > 0.1 * 0.1) + return false; + if (abs(player.lock()->xRot - pRotX) > 5 || + abs(player.lock()->yRot - pRotY) > 5) + return false; + } else { + px = player.lock()->x; + py = player.lock()->y; + pz = player.lock()->z; + } + pRotX = player.lock()->xRot; + pRotY = player.lock()->yRot; + } + return canUse(); } -void TemptGoal::start() -{ - px = player.lock()->x; - py = player.lock()->y; - pz = player.lock()->z; - _isRunning = true; - oldAvoidWater = mob->getNavigation()->getAvoidWater(); - mob->getNavigation()->setAvoidWater(false); +void TemptGoal::start() { + px = player.lock()->x; + py = player.lock()->y; + pz = player.lock()->z; + _isRunning = true; + oldAvoidWater = mob->getNavigation()->getAvoidWater(); + mob->getNavigation()->setAvoidWater(false); } -void TemptGoal::stop() -{ - player = std::weak_ptr(); - mob->getNavigation()->stop(); - calmDown = 100; - _isRunning = false; - mob->getNavigation()->setAvoidWater(oldAvoidWater); +void TemptGoal::stop() { + player = std::weak_ptr(); + mob->getNavigation()->stop(); + calmDown = 100; + _isRunning = false; + mob->getNavigation()->setAvoidWater(oldAvoidWater); } -void TemptGoal::tick() -{ - mob->getLookControl()->setLookAt(player.lock(), 30, mob->getMaxHeadXRot()); - if (mob->distanceToSqr(player.lock()) < 2.5 * 2.5) mob->getNavigation()->stop(); - else mob->getNavigation()->moveTo(player.lock(), speed); +void TemptGoal::tick() { + mob->getLookControl()->setLookAt(player.lock(), 30, mob->getMaxHeadXRot()); + if (mob->distanceToSqr(player.lock()) < 2.5 * 2.5) + mob->getNavigation()->stop(); + else + mob->getNavigation()->moveTo(player.lock(), speed); } -bool TemptGoal::isRunning() -{ - return _isRunning; -} \ No newline at end of file +bool TemptGoal::isRunning() { return _isRunning; } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TemptGoal.h b/Minecraft.World/AI/Goals/TemptGoal.h index fb288d388..000415584 100644 --- a/Minecraft.World/AI/Goals/TemptGoal.h +++ b/Minecraft.World/AI/Goals/TemptGoal.h @@ -2,26 +2,25 @@ #include "Goal.h" -class TemptGoal : public Goal -{ +class TemptGoal : public Goal { private: - PathfinderMob *mob; - float speed; - double px, py, pz, pRotX, pRotY; - std::weak_ptr player; - int calmDown ; - bool _isRunning; - int itemId; - bool canScare; - bool oldAvoidWater; + PathfinderMob* mob; + float speed; + double px, py, pz, pRotX, pRotY; + std::weak_ptr player; + int calmDown; + bool _isRunning; + int itemId; + bool canScare; + bool oldAvoidWater; public: - TemptGoal(PathfinderMob *mob, float speed, int itemId, bool canScare); + TemptGoal(PathfinderMob* mob, float speed, int itemId, bool canScare); - bool canUse(); - bool canContinueToUse(); - void start(); - void stop(); - void tick(); - bool isRunning(); + bool canUse(); + bool canContinueToUse(); + void start(); + void stop(); + void tick(); + bool isRunning(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TradeWithPlayerGoal.cpp b/Minecraft.World/AI/Goals/TradeWithPlayerGoal.cpp index 0591185d2..cfb14d6e0 100644 --- a/Minecraft.World/AI/Goals/TradeWithPlayerGoal.cpp +++ b/Minecraft.World/AI/Goals/TradeWithPlayerGoal.cpp @@ -5,47 +5,37 @@ #include "../../Headers/net.minecraft.world.inventory.h" #include "TradeWithPlayerGoal.h" -TradeWithPlayerGoal::TradeWithPlayerGoal(Villager *mob) -{ - this->mob = mob; - setRequiredControlFlags(Control::JumpControlFlag | Control::MoveControlFlag); +TradeWithPlayerGoal::TradeWithPlayerGoal(Villager* mob) { + this->mob = mob; + setRequiredControlFlags(Control::JumpControlFlag | + Control::MoveControlFlag); } -bool TradeWithPlayerGoal::canUse() -{ - if (!mob->isAlive()) return false; - if (mob->isInWater()) return false; - if (!mob->onGround) return false; - if (mob->hurtMarked) return false; +bool TradeWithPlayerGoal::canUse() { + if (!mob->isAlive()) return false; + if (mob->isInWater()) return false; + if (!mob->onGround) return false; + if (mob->hurtMarked) return false; - std::shared_ptr trader = mob->getTradingPlayer(); - if (trader == NULL) - { - // no interaction - return false; - } + std::shared_ptr trader = mob->getTradingPlayer(); + if (trader == NULL) { + // no interaction + return false; + } - if (mob->distanceToSqr(trader) > (4 * 4)) - { - // too far away - return false; - } + if (mob->distanceToSqr(trader) > (4 * 4)) { + // too far away + return false; + } - if (!(trader->containerMenu == trader->inventoryMenu)) - { - // closed container - return false; - } + if (!(trader->containerMenu == trader->inventoryMenu)) { + // closed container + return false; + } - return true; + return true; } -void TradeWithPlayerGoal::start() -{ - mob->getNavigation()->stop(); -} +void TradeWithPlayerGoal::start() { mob->getNavigation()->stop(); } -void TradeWithPlayerGoal::stop() -{ - mob->setTradingPlayer(nullptr); -} \ No newline at end of file +void TradeWithPlayerGoal::stop() { mob->setTradingPlayer(nullptr); } \ No newline at end of file diff --git a/Minecraft.World/AI/Goals/TradeWithPlayerGoal.h b/Minecraft.World/AI/Goals/TradeWithPlayerGoal.h index 1a0e9040b..3d27c03aa 100644 --- a/Minecraft.World/AI/Goals/TradeWithPlayerGoal.h +++ b/Minecraft.World/AI/Goals/TradeWithPlayerGoal.h @@ -4,15 +4,14 @@ class Villager; -class TradeWithPlayerGoal : public Goal -{ +class TradeWithPlayerGoal : public Goal { private: - Villager *mob; // This is the owner of the goal + Villager* mob; // This is the owner of the goal public: - TradeWithPlayerGoal(Villager *mob); + TradeWithPlayerGoal(Villager* mob); - bool canUse(); - void start(); - void stop(); + bool canUse(); + void start(); + void stop(); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/Node.cpp b/Minecraft.World/AI/Navigation/Node.cpp index a9c24caab..436e4ef30 100644 --- a/Minecraft.World/AI/Navigation/Node.cpp +++ b/Minecraft.World/AI/Navigation/Node.cpp @@ -4,73 +4,60 @@ // 4J - added for common ctor code // Do all the default initialisations done in the java class -void Node::_init() -{ - heapIdx = -1; +void Node::_init() { + heapIdx = -1; - closed = false; + closed = false; - cameFrom = NULL; + cameFrom = NULL; } -Node::Node(const int x, const int y, const int z) : -x(x), -y(y), -z(z), -hash(createHash(x, y, z)) -{ - _init(); +Node::Node(const int x, const int y, const int z) + : x(x), y(y), z(z), hash(createHash(x, y, z)) { + _init(); - //this->x = x; - //this->y = y; - //this->z = z; + // this->x = x; + // this->y = y; + // this->z = z; - //hash = createHash(x, y, z); + // hash = createHash(x, y, z); } -int Node::createHash(const int x, const int y, const int z) -{ - // 4jcraft added cast to higher value to be representable after shift - return (y & 0xff) | (((int64_t)x & 0x7fff) << 8) | (((int64_t)z & 0x7fff) << 24) | ((x < 0) ? 0x0080000000 : 0) | ((z < 0) ? 0x0000008000 : 0); +int Node::createHash(const int x, const int y, const int z) { + // 4jcraft added cast to higher value to be representable after shift + return (y & 0xff) | (((int64_t)x & 0x7fff) << 8) | + (((int64_t)z & 0x7fff) << 24) | ((x < 0) ? 0x0080000000 : 0) | + ((z < 0) ? 0x0000008000 : 0); } -float Node::distanceTo(Node *to) -{ - float xd = (float) ( to->x - x ); - float yd = (float) ( to->y - y ); - float zd = (float) ( to->z - z ); - return Mth::sqrt(xd * xd + yd * yd + zd * zd); +float Node::distanceTo(Node* to) { + float xd = (float)(to->x - x); + float yd = (float)(to->y - y); + float zd = (float)(to->z - z); + return Mth::sqrt(xd * xd + yd * yd + zd * zd); } -float Node::distanceToSqr(Node *to) -{ - float xd = to->x - x; - float yd = to->y - y; - float zd = to->z - z; - return xd * xd + yd * yd + zd * zd; +float Node::distanceToSqr(Node* to) { + float xd = to->x - x; + float yd = to->y - y; + float zd = to->z - z; + return xd * xd + yd * yd + zd * zd; } -bool Node::equals(Node *o) -{ - //4J Jev, never used anything other than a node. - //if (dynamic_cast((Node *) o) != NULL) - //{ - return hash == o->hash && x == o->x && y == o->y && z == o->z; - //} - //return false; +bool Node::equals(Node* o) { + // 4J Jev, never used anything other than a node. + // if (dynamic_cast((Node *) o) != NULL) + //{ + return hash == o->hash && x == o->x && y == o->y && z == o->z; + //} + // return false; } -int Node::hashCode() -{ - return hash; -} +int Node::hashCode() { return hash; } -bool Node::inOpenSet() -{ - return heapIdx >= 0; -} +bool Node::inOpenSet() { return heapIdx >= 0; } -std::wstring Node::toString() -{ - return _toString(x) + L", " + _toString(y) + L", " + _toString(z); +std::wstring Node::toString() { + return _toString(x) + L", " + _toString(y) + L", " + + _toString(z); } diff --git a/Minecraft.World/AI/Navigation/Node.h b/Minecraft.World/AI/Navigation/Node.h index 5a3a8c27e..23ebda360 100644 --- a/Minecraft.World/AI/Navigation/Node.h +++ b/Minecraft.World/AI/Navigation/Node.h @@ -1,38 +1,41 @@ #pragma once - -class Node -{ - // 4J Jev, these classes were accessing protected members. - friend class BinaryHeap; - friend class PathFinder; - friend class EnderDragon; +class Node { + // 4J Jev, these classes were accessing protected members. + friend class BinaryHeap; + friend class PathFinder; + friend class EnderDragon; public: - const int x, y, z; + const int x, y, z; private: - const int hash; + const int hash; protected: - int heapIdx; - float g, h, f; - Node *cameFrom; + int heapIdx; + float g, h, f; + Node* cameFrom; public: - bool closed; + bool closed; - void _init(); - eINSTANCEOF GetType() { return eType_NODE;} + void _init(); + eINSTANCEOF GetType() { return eType_NODE; } - Node() : hash(0),x(0),y(0),z(0) {} // 4J - added default constructor so we can make an empty of array of these as a copy target - Node(const int x, const int y, const int z); + Node() + : hash(0), + x(0), + y(0), + z(0) {} // 4J - added default constructor so we can make an empty of + // array of these as a copy target + Node(const int x, const int y, const int z); - static int createHash(const int x, const int y, const int z); - float distanceTo(Node *to); - float distanceToSqr(Node *to); - bool equals(Node *o); - int hashCode(); - bool inOpenSet(); - std::wstring toString(); + static int createHash(const int x, const int y, const int z); + float distanceTo(Node* to); + float distanceToSqr(Node* to); + bool equals(Node* o); + int hashCode(); + bool inOpenSet(); + std::wstring toString(); }; diff --git a/Minecraft.World/AI/Navigation/Path.cpp b/Minecraft.World/AI/Navigation/Path.cpp index 54a8f0da5..eaef6b8a9 100644 --- a/Minecraft.World/AI/Navigation/Path.cpp +++ b/Minecraft.World/AI/Navigation/Path.cpp @@ -3,114 +3,84 @@ #include "../../Headers/net.minecraft.world.level.pathfinder.h" #include "Path.h" -Path::~Path() -{ - if( nodes.data ) - { - for( int i = 0; i < nodes.length; i++ ) - delete nodes.data[i]; - delete[] nodes.data; - } +Path::~Path() { + if (nodes.data) { + for (int i = 0; i < nodes.length; i++) delete nodes.data[i]; + delete[] nodes.data; + } } -Path::Path(NodeArray nodes) -{ - index = 0; +Path::Path(NodeArray nodes) { + index = 0; - length = nodes.length; - // 4J - copying these nodes over from a NodeArray (which is an array of Node * references) to just a straight array of Nodes, - // so that this Path is no longer dependent of Nodes allocated elsewhere and can handle its own destruction - // Note: cameFrom pointer will be useless now but that isn't used once this is just a path - this->nodes = NodeArray(length); + length = nodes.length; + // 4J - copying these nodes over from a NodeArray (which is an array of Node + // * references) to just a straight array of Nodes, so that this Path is no + // longer dependent of Nodes allocated elsewhere and can handle its own + // destruction Note: cameFrom pointer will be useless now but that isn't + // used once this is just a path + this->nodes = NodeArray(length); - for( int i = 0; i < length; i++ ) - { - this->nodes.data[i] = new Node(); - memcpy(this->nodes.data[i],nodes[i],sizeof(Node)); - } + for (int i = 0; i < length; i++) { + this->nodes.data[i] = new Node(); + memcpy(this->nodes.data[i], nodes[i], sizeof(Node)); + } } -void Path::next() -{ - index++; +void Path::next() { index++; } + +bool Path::isDone() { return index >= length; } + +Node* Path::last() { + if (length > 0) { + return nodes[length - 1]; + } + return NULL; } -bool Path::isDone() -{ - return index >= length; +Node* Path::get(int i) { return nodes[i]; } + +int Path::getSize() { return length; } + +void Path::setSize(int length) { this->length = length; } + +int Path::getIndex() { return index; } + +void Path::setIndex(int index) { this->index = index; } + +Vec3* Path::getPos(std::shared_ptr e, int index) { + double x = nodes[index]->x + (int)(e->bbWidth + 1) * 0.5; + double y = nodes[index]->y; + double z = nodes[index]->z + (int)(e->bbWidth + 1) * 0.5; + return Vec3::newTemp(x, y, z); } -Node *Path::last() -{ - if (length > 0) - { - return nodes[length - 1]; - } - return NULL; +Vec3* Path::currentPos(std::shared_ptr e) { return getPos(e, index); } + +Vec3* Path::currentPos() { + return Vec3::newTemp(nodes[index]->x, nodes[index]->y, nodes[index]->z); } -Node *Path::get(int i) -{ - return nodes[i]; +bool Path::sameAs(Path* path) { + if (path == NULL) return false; + if (path->nodes.length != nodes.length) return false; + for (int i = 0; i < nodes.length; ++i) + if (nodes[i]->x != path->nodes[i]->x || + nodes[i]->y != path->nodes[i]->y || + nodes[i]->z != path->nodes[i]->z) + return false; + return true; } -int Path::getSize() -{ - return length; +bool Path::endsIn(Vec3* pos) { + Node* lastNode = last(); + if (lastNode == NULL) return false; + return lastNode->x == (int)pos->x && lastNode->y == (int)pos->y && + lastNode->z == (int)pos->z; } -void Path::setSize(int length) -{ - this->length = length; -} - -int Path::getIndex() -{ - return index; -} - -void Path::setIndex(int index) -{ - this->index = index; -} - -Vec3 *Path::getPos(std::shared_ptr e, int index) -{ - double x = nodes[index]->x + (int) (e->bbWidth + 1) * 0.5; - double y = nodes[index]->y; - double z = nodes[index]->z + (int) (e->bbWidth + 1) * 0.5; - return Vec3::newTemp(x, y, z); -} - -Vec3 *Path::currentPos(std::shared_ptr e) -{ - return getPos(e, index); -} - -Vec3 *Path::currentPos() -{ - return Vec3::newTemp( nodes[index]->x, nodes[index]->y, nodes[index]->z ); -} - -bool Path::sameAs(Path *path) -{ - if (path == NULL) return false; - if (path->nodes.length != nodes.length) return false; - for (int i = 0; i < nodes.length; ++i) - if (nodes[i]->x != path->nodes[i]->x || nodes[i]->y != path->nodes[i]->y || nodes[i]->z != path->nodes[i]->z) return false; - return true; -} - -bool Path::endsIn(Vec3 *pos) -{ - Node *lastNode = last(); - if (lastNode == NULL) return false; - return lastNode->x == (int) pos->x && lastNode->y == (int) pos->y && lastNode->z == (int) pos->z; -} - -bool Path::endsInXZ(Vec3 *pos) -{ - Node *lastNode = last(); - if (lastNode == NULL) return false; - return lastNode->x == (int) pos->x && lastNode->z == (int) pos->z; +bool Path::endsInXZ(Vec3* pos) { + Node* lastNode = last(); + if (lastNode == NULL) return false; + return lastNode->x == (int)pos->x && lastNode->z == (int)pos->z; } \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/Path.h b/Minecraft.World/AI/Navigation/Path.h index b579a7b8a..0e5697959 100644 --- a/Minecraft.World/AI/Navigation/Path.h +++ b/Minecraft.World/AI/Navigation/Path.h @@ -1,31 +1,30 @@ #pragma once -class Path -{ - friend class PathFinder; +class Path { + friend class PathFinder; private: - NodeArray nodes; - int index; - int length; + NodeArray nodes; + int index; + int length; public: - Path(NodeArray nodes); - ~Path(); + Path(NodeArray nodes); + ~Path(); - void next(); - bool isDone(); - Node *last() ; - Node *get(int i); - int getSize(); - void setSize(int length); - int getIndex(); - void setIndex(int index); - Vec3 *getPos(std::shared_ptr e, int index); - NodeArray Getarray(); - Vec3 *currentPos(std::shared_ptr e); - Vec3 *currentPos(); - bool sameAs(Path *path); - bool endsIn(Vec3 *pos); - bool endsInXZ(Vec3 *pos); + void next(); + bool isDone(); + Node* last(); + Node* get(int i); + int getSize(); + void setSize(int length); + int getIndex(); + void setIndex(int index); + Vec3* getPos(std::shared_ptr e, int index); + NodeArray Getarray(); + Vec3* currentPos(std::shared_ptr e); + Vec3* currentPos(); + bool sameAs(Path* path); + bool endsIn(Vec3* pos); + bool endsInXZ(Vec3* pos); }; diff --git a/Minecraft.World/AI/Navigation/PathFinder.cpp b/Minecraft.World/AI/Navigation/PathFinder.cpp index a27839a66..fda237f6e 100644 --- a/Minecraft.World/AI/Navigation/PathFinder.cpp +++ b/Minecraft.World/AI/Navigation/PathFinder.cpp @@ -9,74 +9,75 @@ #include "Path.h" #include "PathFinder.h" -PathFinder::PathFinder(LevelSource *level, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat) -{ - neighbors = new NodeArray(32); +PathFinder::PathFinder(LevelSource* level, bool canPassDoors, bool canOpenDoors, + bool avoidWater, bool canFloat) { + neighbors = new NodeArray(32); - this->canPassDoors = canPassDoors; - this->canOpenDoors = canOpenDoors; - this->avoidWater = avoidWater; - this->canFloat = canFloat; + this->canPassDoors = canPassDoors; + this->canOpenDoors = canOpenDoors; + this->avoidWater = avoidWater; + this->canFloat = canFloat; this->level = level; } -PathFinder::~PathFinder() -{ - // All the nodes should be uniquely referenced in the nodes map, and everything else should just be duplicate - // references to the same things, so just need to destroy their containers - delete [] neighbors->data; - delete neighbors; - AUTO_VAR(itEnd, nodes.end()); - for( AUTO_VAR(it, nodes.begin()); it != itEnd; it++ ) - { - delete it->second; - } +PathFinder::~PathFinder() { + // All the nodes should be uniquely referenced in the nodes map, and + // everything else should just be duplicate references to the same things, + // so just need to destroy their containers + delete[] neighbors->data; + delete neighbors; + AUTO_VAR(itEnd, nodes.end()); + for (AUTO_VAR(it, nodes.begin()); it != itEnd; it++) { + delete it->second; + } } -Path *PathFinder::findPath(Entity *from, Entity *to, float maxDist) -{ +Path* PathFinder::findPath(Entity* from, Entity* to, float maxDist) { return findPath(from, to->x, to->bb->y0, to->z, maxDist); } -Path *PathFinder::findPath(Entity *from, int x, int y, int z, float maxDist) -{ +Path* PathFinder::findPath(Entity* from, int x, int y, int z, float maxDist) { return findPath(from, x + 0.5f, y + 0.5f, z + 0.5f, maxDist); } -Path *PathFinder::findPath(Entity *e, double xt, double yt, double zt, float maxDist) -{ +Path* PathFinder::findPath(Entity* e, double xt, double yt, double zt, + float maxDist) { openSet.clear(); - nodes.clear(); + nodes.clear(); - bool resetAvoidWater = avoidWater; - int startY = Mth::floor(e->bb->y0 + 0.5f); - if (canFloat && e->isInWater()) - { - startY = (int) (e->bb->y0); - int tileId = level->getTile((int) Mth::floor(e->x), startY, (int) Mth::floor(e->z)); - while (tileId == Tile::water_Id || tileId == Tile::calmWater_Id) - { - ++startY; - tileId = level->getTile((int) Mth::floor(e->x), startY, (int) Mth::floor(e->z)); - } - resetAvoidWater = avoidWater; - avoidWater = false; - } else startY = Mth::floor(e->bb->y0 + 0.5f); + bool resetAvoidWater = avoidWater; + int startY = Mth::floor(e->bb->y0 + 0.5f); + if (canFloat && e->isInWater()) { + startY = (int)(e->bb->y0); + int tileId = level->getTile((int)Mth::floor(e->x), startY, + (int)Mth::floor(e->z)); + while (tileId == Tile::water_Id || tileId == Tile::calmWater_Id) { + ++startY; + tileId = level->getTile((int)Mth::floor(e->x), startY, + (int)Mth::floor(e->z)); + } + resetAvoidWater = avoidWater; + avoidWater = false; + } else + startY = Mth::floor(e->bb->y0 + 0.5f); - Node *from = getNode((int) floor(e->bb->x0), startY, (int) floor(e->bb->z0)); - Node *to = getNode((int) floor(xt - e->bbWidth / 2), (int) floor(yt), (int) floor(zt - e->bbWidth / 2)); + Node* from = getNode((int)floor(e->bb->x0), startY, (int)floor(e->bb->z0)); + Node* to = getNode((int)floor(xt - e->bbWidth / 2), (int)floor(yt), + (int)floor(zt - e->bbWidth / 2)); - Node *size = new Node((int) floor(e->bbWidth + 1), (int) floor(e->bbHeight + 1), (int) floor(e->bbWidth + 1)); - Path *path = findPath(e, from, to, size, maxDist); - delete size; + Node* size = + new Node((int)floor(e->bbWidth + 1), (int)floor(e->bbHeight + 1), + (int)floor(e->bbWidth + 1)); + Path* path = findPath(e, from, to, size, maxDist); + delete size; - avoidWater = resetAvoidWater; + avoidWater = resetAvoidWater; return path; } // function A*(start,goal) -Path *PathFinder::findPath(Entity *e, Node *from, Node *to, Node *size, float maxDist) -{ +Path* PathFinder::findPath(Entity* e, Node* from, Node* to, Node* size, + float maxDist) { from->g = 0; from->h = from->distanceToSqr(to); from->f = from->h; @@ -84,40 +85,32 @@ Path *PathFinder::findPath(Entity *e, Node *from, Node *to, Node *size, float ma openSet.clear(); openSet.insert(from); - Node *closest = from; + Node* closest = from; - while (!openSet.isEmpty()) - { - Node *x = openSet.pop(); + while (!openSet.isEmpty()) { + Node* x = openSet.pop(); - if (x->equals(to)) - { + if (x->equals(to)) { return reconstruct_path(from, to); } - if (x->distanceToSqr(to) < closest->distanceToSqr(to)) - { + if (x->distanceToSqr(to) < closest->distanceToSqr(to)) { closest = x; } x->closed = true; int neighborCount = getNeighbors(e, x, size, to, maxDist); - for (int i = 0; i < neighborCount; i++) - { - Node *y = neighbors->data[i]; + for (int i = 0; i < neighborCount; i++) { + Node* y = neighbors->data[i]; float tentative_g_score = x->g + x->distanceToSqr(y); - if (!y->inOpenSet() || tentative_g_score < y->g) - { + if (!y->inOpenSet() || tentative_g_score < y->g) { y->cameFrom = x; y->g = tentative_g_score; y->h = y->distanceToSqr(to); - if (y->inOpenSet()) - { + if (y->inOpenSet()) { openSet.changeCost(y, y->g + y->h); - } - else - { + } else { y->f = y->g + y->h; openSet.insert(y); } @@ -129,47 +122,51 @@ Path *PathFinder::findPath(Entity *e, Node *from, Node *to, Node *size, float ma return reconstruct_path(from, closest); } -int PathFinder::getNeighbors(Entity *entity, Node *pos, Node *size, Node *target, float maxDist) -{ +int PathFinder::getNeighbors(Entity* entity, Node* pos, Node* size, + Node* target, float maxDist) { int p = 0; int jumpSize = 0; - if (isFree(entity, pos->x, pos->y + 1, pos->z, size) == TYPE_OPEN) jumpSize = 1; + if (isFree(entity, pos->x, pos->y + 1, pos->z, size) == TYPE_OPEN) + jumpSize = 1; - Node *n = getNode(entity, pos->x, pos->y, pos->z + 1, size, jumpSize); - Node *w = getNode(entity, pos->x - 1, pos->y, pos->z, size, jumpSize); - Node *e = getNode(entity, pos->x + 1, pos->y, pos->z, size, jumpSize); - Node *s = getNode(entity, pos->x, pos->y, pos->z - 1, size, jumpSize); + Node* n = getNode(entity, pos->x, pos->y, pos->z + 1, size, jumpSize); + Node* w = getNode(entity, pos->x - 1, pos->y, pos->z, size, jumpSize); + Node* e = getNode(entity, pos->x + 1, pos->y, pos->z, size, jumpSize); + Node* s = getNode(entity, pos->x, pos->y, pos->z - 1, size, jumpSize); - if (n != NULL && !n->closed && n->distanceTo(target) < maxDist) neighbors->data[p++] = n; - if (w != NULL && !w->closed && w->distanceTo(target) < maxDist) neighbors->data[p++] = w; - if (e != NULL && !e->closed && e->distanceTo(target) < maxDist) neighbors->data[p++] = e; - if (s != NULL && !s->closed && s->distanceTo(target) < maxDist) neighbors->data[p++] = s; + if (n != NULL && !n->closed && n->distanceTo(target) < maxDist) + neighbors->data[p++] = n; + if (w != NULL && !w->closed && w->distanceTo(target) < maxDist) + neighbors->data[p++] = w; + if (e != NULL && !e->closed && e->distanceTo(target) < maxDist) + neighbors->data[p++] = e; + if (s != NULL && !s->closed && s->distanceTo(target) < maxDist) + neighbors->data[p++] = s; return p; } -Node *PathFinder::getNode(Entity *entity, int x, int y, int z, Node *size, int jumpSize) -{ - Node *best = NULL; - int pathType = isFree(entity, x, y, z, size); - if (pathType == TYPE_WALKABLE) return getNode(x, y, z); +Node* PathFinder::getNode(Entity* entity, int x, int y, int z, Node* size, + int jumpSize) { + Node* best = NULL; + int pathType = isFree(entity, x, y, z, size); + if (pathType == TYPE_WALKABLE) return getNode(x, y, z); if (pathType == TYPE_OPEN) best = getNode(x, y, z); - if (best == NULL && jumpSize > 0 && pathType != TYPE_FENCE && pathType != TYPE_TRAP && isFree(entity, x, y + jumpSize, z, size) == TYPE_OPEN) - { + if (best == NULL && jumpSize > 0 && pathType != TYPE_FENCE && + pathType != TYPE_TRAP && + isFree(entity, x, y + jumpSize, z, size) == TYPE_OPEN) { best = getNode(x, y + jumpSize, z); y += jumpSize; } - if (best != NULL) - { + if (best != NULL) { int drop = 0; int cost = 0; - while (y > 0) - { - cost = isFree(entity, x, y - 1, z, size); - if (avoidWater && cost == TYPE_WATER) return NULL; - if (cost != TYPE_OPEN) break; + while (y > 0) { + cost = isFree(entity, x, y - 1, z, size); + if (avoidWater && cost == TYPE_WATER) return NULL; + if (cost != TYPE_OPEN) break; // fell too far? if (++drop >= 4) return NULL; y--; @@ -183,76 +180,72 @@ Node *PathFinder::getNode(Entity *entity, int x, int y, int z, Node *size, int j return best; } -/*final*/ Node *PathFinder::getNode(int x, int y, int z) -{ +/*final*/ Node* PathFinder::getNode(int x, int y, int z) { int i = Node::createHash(x, y, z); - Node *node; - AUTO_VAR(it, nodes.find(i)); - if ( it == nodes.end() ) - { - MemSect(54); + Node* node; + AUTO_VAR(it, nodes.find(i)); + if (it == nodes.end()) { + MemSect(54); node = new Node(x, y, z); - MemSect(0); - nodes.insert( std::unordered_map::value_type(i, node) ); + MemSect(0); + nodes.insert(std::unordered_map::value_type(i, node)); + } else { + node = (*it).second; } - else - { - node = (*it).second; - } return node; } -int PathFinder::isFree(Entity *entity, int x, int y, int z, Node *size) -{ - return isFree(entity, x, y, z, size, avoidWater, canOpenDoors, canPassDoors); +int PathFinder::isFree(Entity* entity, int x, int y, int z, Node* size) { + return isFree(entity, x, y, z, size, avoidWater, canOpenDoors, + canPassDoors); } -int PathFinder::isFree(Entity *entity, int x, int y, int z, Node *size, bool avoidWater, bool canOpenDoors, bool canPassDoors) -{ - bool walkable = false; - for (int xx = x; xx < x + size->x; xx++) - for (int yy = y; yy < y + size->y; yy++) - for (int zz = z; zz < z + size->z; zz++) - { - int tileId = entity->level->getTile(xx, yy, zz); - if(tileId <= 0) continue; - if (tileId == Tile::trapdoor_Id) walkable = true; - else if (tileId == Tile::water_Id || tileId == Tile::calmWater_Id) - { - if (avoidWater) return TYPE_WATER; - else walkable = true; - } - else if (!canPassDoors && tileId == Tile::door_wood_Id) - { - return TYPE_BLOCKED; - } +int PathFinder::isFree(Entity* entity, int x, int y, int z, Node* size, + bool avoidWater, bool canOpenDoors, bool canPassDoors) { + bool walkable = false; + for (int xx = x; xx < x + size->x; xx++) + for (int yy = y; yy < y + size->y; yy++) + for (int zz = z; zz < z + size->z; zz++) { + int tileId = entity->level->getTile(xx, yy, zz); + if (tileId <= 0) continue; + if (tileId == Tile::trapdoor_Id) + walkable = true; + else if (tileId == Tile::water_Id || + tileId == Tile::calmWater_Id) { + if (avoidWater) + return TYPE_WATER; + else + walkable = true; + } else if (!canPassDoors && tileId == Tile::door_wood_Id) { + return TYPE_BLOCKED; + } - Tile *tile = Tile::tiles[tileId]; - if (tile->isPathfindable(entity->level, xx, yy, zz)) continue; - if (canOpenDoors && tileId == Tile::door_wood_Id) continue; + Tile* tile = Tile::tiles[tileId]; + if (tile->isPathfindable(entity->level, xx, yy, zz)) continue; + if (canOpenDoors && tileId == Tile::door_wood_Id) continue; - int renderShape = tile->getRenderShape(); - if (renderShape == Tile::SHAPE_FENCE || tileId == Tile::fenceGate_Id || renderShape == Tile::SHAPE_WALL) return TYPE_FENCE; - if (tileId == Tile::trapdoor_Id) return TYPE_TRAP; - Material *m = tile->material; - if (m == Material::lava) - { - if (entity->isInLava()) continue; - return TYPE_LAVA; - } - return TYPE_BLOCKED; - } + int renderShape = tile->getRenderShape(); + if (renderShape == Tile::SHAPE_FENCE || + tileId == Tile::fenceGate_Id || + renderShape == Tile::SHAPE_WALL) + return TYPE_FENCE; + if (tileId == Tile::trapdoor_Id) return TYPE_TRAP; + Material* m = tile->material; + if (m == Material::lava) { + if (entity->isInLava()) continue; + return TYPE_LAVA; + } + return TYPE_BLOCKED; + } return walkable ? TYPE_WALKABLE : TYPE_OPEN; } // function reconstruct_path(came_from,current_node) -Path *PathFinder::reconstruct_path(Node *from, Node *to) -{ +Path* PathFinder::reconstruct_path(Node* from, Node* to) { int count = 1; - Node *n = to; - while (n->cameFrom != NULL) - { + Node* n = to; + while (n->cameFrom != NULL) { count++; n = n->cameFrom; } @@ -260,12 +253,11 @@ Path *PathFinder::reconstruct_path(Node *from, Node *to) NodeArray nodes = NodeArray(count); n = to; nodes.data[--count] = n; - while (n->cameFrom != NULL) - { + while (n->cameFrom != NULL) { n = n->cameFrom; nodes.data[--count] = n; } - Path *ret = new Path(nodes); - delete [] nodes.data; + Path* ret = new Path(nodes); + delete[] nodes.data; return ret; } \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/PathFinder.h b/Minecraft.World/AI/Navigation/PathFinder.h index 2978ac360..6d02f67ae 100644 --- a/Minecraft.World/AI/Navigation/PathFinder.h +++ b/Minecraft.World/AI/Navigation/PathFinder.h @@ -1,54 +1,56 @@ #pragma once #include "../../Util/JavaIntHash.h" - class LevelSource; -class PathFinder -{ +class PathFinder { private: - LevelSource *level; + LevelSource* level; BinaryHeap openSet; - // 4J Jev, was a IntHashMap, thought this was close enough. - std::unordered_map nodes; + // 4J Jev, was a IntHashMap, thought this was close enough. + std::unordered_map nodes; - NodeArray *neighbors; + NodeArray* neighbors; - bool canPassDoors; - bool canOpenDoors; - bool avoidWater; - bool canFloat; + bool canPassDoors; + bool canOpenDoors; + bool avoidWater; + bool canFloat; public: - PathFinder(LevelSource *level, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat); - ~PathFinder(); + PathFinder(LevelSource* level, bool canPassDoors, bool canOpenDoors, + bool avoidWater, bool canFloat); + ~PathFinder(); - Path *findPath(Entity *from, Entity *to, float maxDist); - Path *findPath(Entity *from, int x, int y, int z, float maxDist); + Path* findPath(Entity* from, Entity* to, float maxDist); + Path* findPath(Entity* from, int x, int y, int z, float maxDist); private: - Path *findPath(Entity *e, double xt, double yt, double zt, float maxDist); + Path* findPath(Entity* e, double xt, double yt, double zt, float maxDist); // function A*(start,goal) - Path *findPath(Entity *e, Node *from, Node *to, Node *size, float maxDist); - int getNeighbors(Entity *entity, Node *pos, Node *size, Node *target, float maxDist); - Node *getNode(Entity *entity, int x, int y, int z, Node *size, int jumpSize); - /*final*/ Node *getNode(int x, int y, int z); + Path* findPath(Entity* e, Node* from, Node* to, Node* size, float maxDist); + int getNeighbors(Entity* entity, Node* pos, Node* size, Node* target, + float maxDist); + Node* getNode(Entity* entity, int x, int y, int z, Node* size, + int jumpSize); + /*final*/ Node* getNode(int x, int y, int z); public: - static const int TYPE_TRAP = -4; - static const int TYPE_FENCE = -3; - static const int TYPE_LAVA = -2; + static const int TYPE_TRAP = -4; + static const int TYPE_FENCE = -3; + static const int TYPE_LAVA = -2; static const int TYPE_WATER = -1; static const int TYPE_BLOCKED = 0; static const int TYPE_OPEN = 1; - static const int TYPE_WALKABLE = 2; + static const int TYPE_WALKABLE = 2; - int isFree(Entity *entity, int x, int y, int z, Node *size); - static int isFree(Entity *entity, int x, int y, int z, Node *size, bool avoidWater, bool canOpenDoors, bool canPassDoors); + int isFree(Entity* entity, int x, int y, int z, Node* size); + static int isFree(Entity* entity, int x, int y, int z, Node* size, + bool avoidWater, bool canOpenDoors, bool canPassDoors); // function reconstruct_path(came_from,current_node) - Path *reconstruct_path(Node *from, Node *to); + Path* reconstruct_path(Node* from, Node* to); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/PathNavigation.cpp b/Minecraft.World/AI/Navigation/PathNavigation.cpp index 5aef7d581..9a50b9b73 100644 --- a/Minecraft.World/AI/Navigation/PathNavigation.cpp +++ b/Minecraft.World/AI/Navigation/PathNavigation.cpp @@ -8,369 +8,317 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "PathNavigation.h" -PathNavigation::PathNavigation(Mob *mob, Level *level, float maxDist) -{ - this->mob = mob; - this->level = level; - this->maxDist = maxDist; +PathNavigation::PathNavigation(Mob* mob, Level* level, float maxDist) { + this->mob = mob; + this->level = level; + this->maxDist = maxDist; - path = NULL; - speed = 0.0f; - avoidSun = false; - _tick = 0; - lastStuckCheck = 0; - lastStuckCheckPos = Vec3::newPermanent(0, 0, 0); - _canPassDoors = true; - _canOpenDoors = false; - avoidWater = false; - canFloat = false; + path = NULL; + speed = 0.0f; + avoidSun = false; + _tick = 0; + lastStuckCheck = 0; + lastStuckCheckPos = Vec3::newPermanent(0, 0, 0); + _canPassDoors = true; + _canOpenDoors = false; + avoidWater = false; + canFloat = false; } -PathNavigation::~PathNavigation() -{ - if(path != NULL) delete path; - delete lastStuckCheckPos; +PathNavigation::~PathNavigation() { + if (path != NULL) delete path; + delete lastStuckCheckPos; } -void PathNavigation::setAvoidWater(bool avoidWater) -{ - this->avoidWater = avoidWater; +void PathNavigation::setAvoidWater(bool avoidWater) { + this->avoidWater = avoidWater; } -bool PathNavigation::getAvoidWater() -{ - return avoidWater; +bool PathNavigation::getAvoidWater() { return avoidWater; } + +void PathNavigation::setCanOpenDoors(bool canOpenDoors) { + this->_canOpenDoors = canOpenDoors; } -void PathNavigation::setCanOpenDoors(bool canOpenDoors) -{ - this->_canOpenDoors = canOpenDoors; +bool PathNavigation::canPassDoors() { return _canPassDoors; } + +void PathNavigation::setCanPassDoors(bool canPass) { _canPassDoors = canPass; } + +bool PathNavigation::canOpenDoors() { return _canOpenDoors; } + +void PathNavigation::setAvoidSun(bool avoidSun) { this->avoidSun = avoidSun; } + +void PathNavigation::setSpeed(float speed) { this->speed = speed; } + +void PathNavigation::setCanFloat(bool canFloat) { this->canFloat = canFloat; } + +Path* PathNavigation::createPath(double x, double y, double z) { + if (!canUpdatePath()) return NULL; + return level->findPath(mob->shared_from_this(), Mth::floor(x), (int)y, + Mth::floor(z), maxDist, _canPassDoors, _canOpenDoors, + avoidWater, canFloat); } -bool PathNavigation::canPassDoors() -{ - return _canPassDoors; +bool PathNavigation::moveTo(double x, double y, double z, float speed) { + MemSect(52); + Path* newPath = createPath(Mth::floor(x), (int)y, Mth::floor(z)); + MemSect(0); + // No need to delete newPath here as this will be copied into the member + // variable path and the class can assume responsibility for it + return moveTo(newPath, speed); } -void PathNavigation::setCanPassDoors(bool canPass) -{ - _canPassDoors = canPass; +Path* PathNavigation::createPath(std::shared_ptr target) { + if (!canUpdatePath()) return NULL; + return level->findPath(mob->shared_from_this(), target, maxDist, + _canPassDoors, _canOpenDoors, avoidWater, canFloat); } -bool PathNavigation::canOpenDoors() -{ - return _canOpenDoors; +bool PathNavigation::moveTo(std::shared_ptr target, float speed) { + MemSect(53); + Path* newPath = createPath(target); + MemSect(0); + // No need to delete newPath here as this will be copied into the member + // variable path and the class can assume responsibility for it + if (newPath != NULL) + return moveTo(newPath, speed); + else + return false; } -void PathNavigation::setAvoidSun(bool avoidSun) -{ - this->avoidSun = avoidSun; +bool PathNavigation::moveTo(Path* newPath, float speed) { + if (newPath == NULL) { + if (path != NULL) delete path; + path = NULL; + return false; + } + if (!newPath->sameAs(path)) { + if (path != NULL) delete path; + path = newPath; + } else { + delete newPath; + } + if (avoidSun) trimPathFromSun(); + if (path->getSize() == 0) return false; + + this->speed = speed; + Vec3* mobPos = getTempMobPos(); + lastStuckCheck = _tick; + lastStuckCheckPos->x = mobPos->x; + lastStuckCheckPos->y = mobPos->y; + lastStuckCheckPos->z = mobPos->z; + return true; } -void PathNavigation::setSpeed(float speed) -{ - this->speed = speed; +Path* PathNavigation::getPath() { return path; } + +void PathNavigation::tick() { + ++_tick; + if (isDone()) return; + + if (canUpdatePath()) updatePath(); + + if (isDone()) return; + Vec3* target = path->currentPos(mob->shared_from_this()); + if (target == NULL) return; + + mob->getMoveControl()->setWantedPosition(target->x, target->y, target->z, + speed); } -void PathNavigation::setCanFloat(bool canFloat) -{ - this->canFloat = canFloat; +void PathNavigation::updatePath() { + Vec3* mobPos = getTempMobPos(); + + // find first elevations in path + int firstElevation = path->getSize(); + for (int i = path->getIndex(); path != NULL && i < path->getSize(); ++i) { + if ((int)path->get(i)->y != (int)mobPos->y) { + firstElevation = i; + break; + } + } + + // remove those within way point radius (this is not optimal, should + // check canWalkDirectly also) possibly only check next as well + float waypointRadiusSqr = mob->bbWidth * mob->bbWidth; + for (int i = path->getIndex(); i < firstElevation; ++i) { + Vec3* pathPos = path->getPos(mob->shared_from_this(), i); + if (mobPos->distanceToSqr(pathPos) < waypointRadiusSqr) { + path->setIndex(i + 1); + } + } + + // smooth remaining on same elevation + int sx = (int)ceil(mob->bbWidth); + int sy = (int)mob->bbHeight + 1; + int sz = sx; + for (int i = firstElevation - 1; i >= path->getIndex(); --i) { + if (canMoveDirectly(mobPos, path->getPos(mob->shared_from_this(), i), + sx, sy, sz)) { + path->setIndex(i); + break; + } + } + + // stuck detection (probably pushed off path) + if (_tick - lastStuckCheck > 100) { + if (mobPos->distanceToSqr(lastStuckCheckPos) < 1.5 * 1.5) stop(); + lastStuckCheck = _tick; + lastStuckCheckPos->x = mobPos->x; + lastStuckCheckPos->y = mobPos->y; + lastStuckCheckPos->z = mobPos->z; + } } -Path *PathNavigation::createPath(double x, double y, double z) -{ - if (!canUpdatePath()) return NULL; - return level->findPath(mob->shared_from_this(), Mth::floor(x), (int) y, Mth::floor(z), maxDist, _canPassDoors, _canOpenDoors, avoidWater, canFloat); +bool PathNavigation::isDone() { return path == NULL || path->isDone(); } + +void PathNavigation::stop() { + if (path != NULL) delete path; + path = NULL; } -bool PathNavigation::moveTo(double x, double y, double z, float speed) -{ - MemSect(52); - Path *newPath = createPath(Mth::floor(x), (int) y, Mth::floor(z)); - MemSect(0); - // No need to delete newPath here as this will be copied into the member variable path and the class can assume responsibility for it - return moveTo(newPath, speed); +Vec3* PathNavigation::getTempMobPos() { + return Vec3::newTemp(mob->x, getSurfaceY(), mob->z); } -Path *PathNavigation::createPath(std::shared_ptr target) -{ - if (!canUpdatePath()) return NULL; - return level->findPath(mob->shared_from_this(), target, maxDist, _canPassDoors, _canOpenDoors, avoidWater, canFloat); +int PathNavigation::getSurfaceY() { + if (!mob->isInWater() || !canFloat) return (int)(mob->bb->y0 + 0.5); + + int surface = (int)(mob->bb->y0); + int tileId = + level->getTile(Mth::floor(mob->x), surface, Mth::floor(mob->z)); + int steps = 0; + while (tileId == Tile::water_Id || tileId == Tile::calmWater_Id) { + ++surface; + tileId = + level->getTile(Mth::floor(mob->x), surface, Mth::floor(mob->z)); + if (++steps > 16) return (int)(mob->bb->y0); + } + return surface; } -bool PathNavigation::moveTo(std::shared_ptr target, float speed) -{ - MemSect(53); - Path *newPath = createPath(target); - MemSect(0); - // No need to delete newPath here as this will be copied into the member variable path and the class can assume responsibility for it - if (newPath != NULL) return moveTo(newPath, speed); - else return false; +bool PathNavigation::canUpdatePath() { + return mob->onGround || (canFloat && isInLiquid()); } -bool PathNavigation::moveTo(Path *newPath, float speed) -{ - if(newPath == NULL) - { - if(path != NULL) delete path; - path = NULL; - return false; - } - if(!newPath->sameAs(path)) - { - if(path != NULL) delete path; - path = newPath; - } - else - { - delete newPath; - } - if (avoidSun) trimPathFromSun(); - if (path->getSize() == 0) return false; - - this->speed = speed; - Vec3 *mobPos = getTempMobPos(); - lastStuckCheck = _tick; - lastStuckCheckPos->x = mobPos->x; - lastStuckCheckPos->y = mobPos->y; - lastStuckCheckPos->z = mobPos->z; - return true; +bool PathNavigation::isInLiquid() { + return mob->isInWater() || mob->isInLava(); } -Path *PathNavigation::getPath() -{ - return path; +void PathNavigation::trimPathFromSun() { + if (level->canSeeSky(Mth::floor(mob->x), (int)(mob->bb->y0 + 0.5), + Mth::floor(mob->z))) + return; + + for (int i = 0; i < path->getSize(); ++i) { + Node* n = path->get(i); + if (level->canSeeSky((int)n->x, (int)n->y, (int)n->z)) { + path->setSize(i - 1); + return; + } + } } -void PathNavigation::tick() -{ - ++_tick; - if (isDone()) return; +bool PathNavigation::canMoveDirectly(Vec3* startPos, Vec3* stopPos, int sx, + int sy, int sz) { + int gridPosX = Mth::floor(startPos->x); + int gridPosZ = Mth::floor(startPos->z); - if (canUpdatePath()) updatePath(); + double dirX = stopPos->x - startPos->x; + double dirZ = stopPos->z - startPos->z; + double distSqr = dirX * dirX + dirZ * dirZ; + if (distSqr < 0.00000001) return false; - if (isDone()) return; - Vec3 *target = path->currentPos(mob->shared_from_this()); - if (target == NULL) return; + double nf = 1 / sqrt(distSqr); + dirX *= nf; + dirZ *= nf; - mob->getMoveControl()->setWantedPosition(target->x, target->y, target->z, speed); + sx += 2; + sz += 2; + if (!canWalkOn(gridPosX, (int)startPos->y, gridPosZ, sx, sy, sz, startPos, + dirX, dirZ)) + return false; + sx -= 2; + sz -= 2; + + double deltaX = 1 / abs(dirX); + double deltaZ = 1 / abs(dirZ); + + double maxX = gridPosX * 1 - startPos->x; + double maxZ = gridPosZ * 1 - startPos->z; + if (dirX >= 0) maxX += 1; + if (dirZ >= 0) maxZ += 1; + maxX /= dirX; + maxZ /= dirZ; + + int stepX = dirX < 0 ? -1 : 1; + int stepZ = dirZ < 0 ? -1 : 1; + int gridGoalX = Mth::floor(stopPos->x); + int gridGoalZ = Mth::floor(stopPos->z); + int currentDirX = gridGoalX - gridPosX; + int currentDirZ = gridGoalZ - gridPosZ; + while (currentDirX * stepX > 0 || currentDirZ * stepZ > 0) { + if (maxX < maxZ) { + maxX += deltaX; + gridPosX += stepX; + currentDirX = gridGoalX - gridPosX; + } else { + maxZ += deltaZ; + gridPosZ += stepZ; + currentDirZ = gridGoalZ - gridPosZ; + } + + if (!canWalkOn(gridPosX, (int)startPos->y, gridPosZ, sx, sy, sz, + startPos, dirX, dirZ)) + return false; + } + return true; } -void PathNavigation::updatePath() -{ - Vec3 *mobPos = getTempMobPos(); +bool PathNavigation::canWalkOn(int x, int y, int z, int sx, int sy, int sz, + Vec3* startPos, double goalDirX, + double goalDirZ) { + int startX = x - sx / 2; + int startZ = z - sz / 2; - // find first elevations in path - int firstElevation = path->getSize(); - for (int i = path->getIndex(); path != NULL && i < path->getSize(); ++i) - { - if ((int) path->get(i)->y != (int) mobPos->y) - { - firstElevation = i; - break; - } - } + if (!canWalkAbove(startX, y, startZ, sx, sy, sz, startPos, goalDirX, + goalDirZ)) + return false; - // remove those within way point radius (this is not optimal, should - // check canWalkDirectly also) possibly only check next as well - float waypointRadiusSqr = mob->bbWidth * mob->bbWidth; - for (int i = path->getIndex(); i < firstElevation; ++i) - { - Vec3 *pathPos = path->getPos(mob->shared_from_this(), i); - if (mobPos->distanceToSqr(pathPos) < waypointRadiusSqr) - { - path->setIndex(i + 1); - } - } + // lava or water or air under + for (int xx = startX; xx < startX + sx; xx++) { + for (int zz = startZ; zz < startZ + sz; zz++) { + double dirX = xx + 0.5 - startPos->x; + double dirZ = zz + 0.5 - startPos->z; + if (dirX * goalDirX + dirZ * goalDirZ < 0) continue; + int tile = level->getTile(xx, y - 1, zz); + if (tile <= 0) return false; + Material* m = Tile::tiles[tile]->material; + if (m == Material::water && !mob->isInWater()) return false; + if (m == Material::lava) return false; + } + } - // smooth remaining on same elevation - int sx = (int) ceil(mob->bbWidth); - int sy = (int) mob->bbHeight + 1; - int sz = sx; - for (int i = firstElevation - 1; i >= path->getIndex(); --i) - { - if (canMoveDirectly(mobPos, path->getPos(mob->shared_from_this(), i), sx, sy, sz)) - { - path->setIndex(i); - break; - } - } - - // stuck detection (probably pushed off path) - if (_tick - lastStuckCheck > 100) - { - if (mobPos->distanceToSqr(lastStuckCheckPos) < 1.5 * 1.5) stop(); - lastStuckCheck = _tick; - lastStuckCheckPos->x = mobPos->x; - lastStuckCheckPos->y = mobPos->y; - lastStuckCheckPos->z = mobPos->z; - } + return true; } -bool PathNavigation::isDone() -{ - return path == NULL || path->isDone(); +bool PathNavigation::canWalkAbove(int startX, int startY, int startZ, int sx, + int sy, int sz, Vec3* startPos, + double goalDirX, double goalDirZ) { + for (int xx = startX; xx < startX + sx; xx++) { + for (int yy = startY; yy < startY + sy; yy++) { + for (int zz = startZ; zz < startZ + sz; zz++) { + double dirX = xx + 0.5 - startPos->x; + double dirZ = zz + 0.5 - startPos->z; + if (dirX * goalDirX + dirZ * goalDirZ < 0) continue; + int tile = level->getTile(xx, yy, zz); + if (tile <= 0) continue; + if (!Tile::tiles[tile]->isPathfindable(level, xx, yy, zz)) + return false; + } + } + } + return true; } -void PathNavigation::stop() -{ - if(path != NULL) delete path; - path = NULL; -} - -Vec3 *PathNavigation::getTempMobPos() -{ - return Vec3::newTemp(mob->x, getSurfaceY(), mob->z); -} - -int PathNavigation::getSurfaceY() -{ - if (!mob->isInWater() || !canFloat) return (int) (mob->bb->y0 + 0.5); - - int surface = (int) (mob->bb->y0); - int tileId = level->getTile(Mth::floor(mob->x), surface, Mth::floor(mob->z)); - int steps = 0; - while (tileId == Tile::water_Id || tileId == Tile::calmWater_Id) - { - ++surface; - tileId = level->getTile(Mth::floor(mob->x), surface, Mth::floor(mob->z)); - if (++steps > 16) return (int) (mob->bb->y0); - } - return surface; -} - -bool PathNavigation::canUpdatePath() -{ - return mob->onGround || (canFloat && isInLiquid()); -} - -bool PathNavigation::isInLiquid() -{ - return mob->isInWater() || mob->isInLava(); -} - -void PathNavigation::trimPathFromSun() -{ - if (level->canSeeSky(Mth::floor(mob->x), (int) (mob->bb->y0 + 0.5), Mth::floor(mob->z))) return; - - for (int i = 0; i < path->getSize(); ++i) - { - Node *n = path->get(i); - if (level->canSeeSky((int) n->x, (int) n->y, (int) n->z)) - { - path->setSize(i - 1); - return; - } - } -} - -bool PathNavigation::canMoveDirectly(Vec3 *startPos, Vec3 *stopPos, int sx, int sy, int sz) -{ - - int gridPosX = Mth::floor(startPos->x); - int gridPosZ = Mth::floor(startPos->z); - - double dirX = stopPos->x - startPos->x; - double dirZ = stopPos->z - startPos->z; - double distSqr = dirX * dirX + dirZ * dirZ; - if (distSqr < 0.00000001) return false; - - double nf = 1 / sqrt(distSqr); - dirX *= nf; - dirZ *= nf; - - sx += 2; - sz += 2; - if (!canWalkOn(gridPosX, (int) startPos->y, gridPosZ, sx, sy, sz, startPos, dirX, dirZ)) return false; - sx -= 2; - sz -= 2; - - double deltaX = 1 / abs(dirX); - double deltaZ = 1 / abs(dirZ); - - double maxX = gridPosX * 1 - startPos->x; - double maxZ = gridPosZ * 1 - startPos->z; - if (dirX >= 0) maxX += 1; - if (dirZ >= 0) maxZ += 1; - maxX /= dirX; - maxZ /= dirZ; - - int stepX = dirX < 0 ? -1 : 1; - int stepZ = dirZ < 0 ? -1 : 1; - int gridGoalX = Mth::floor(stopPos->x); - int gridGoalZ = Mth::floor(stopPos->z); - int currentDirX = gridGoalX - gridPosX; - int currentDirZ = gridGoalZ - gridPosZ; - while (currentDirX * stepX > 0 || currentDirZ * stepZ > 0) - { - if (maxX < maxZ) - { - maxX += deltaX; - gridPosX += stepX; - currentDirX = gridGoalX - gridPosX; - } - else - { - maxZ += deltaZ; - gridPosZ += stepZ; - currentDirZ = gridGoalZ - gridPosZ; - } - - if (!canWalkOn(gridPosX, (int) startPos->y, gridPosZ, sx, sy, sz, startPos, dirX, dirZ)) return false; - } - return true; -} - -bool PathNavigation::canWalkOn(int x, int y, int z, int sx, int sy, int sz, Vec3 *startPos, double goalDirX, double goalDirZ) -{ - - int startX = x - sx / 2; - int startZ = z - sz / 2; - - if (!canWalkAbove(startX, y, startZ, sx, sy, sz, startPos, goalDirX, goalDirZ)) return false; - - // lava or water or air under - for (int xx = startX; xx < startX + sx; xx++) - { - for (int zz = startZ; zz < startZ + sz; zz++) - { - double dirX = xx + 0.5 - startPos->x; - double dirZ = zz + 0.5 - startPos->z; - if (dirX * goalDirX + dirZ * goalDirZ < 0) continue; - int tile = level->getTile(xx, y - 1, zz); - if (tile <= 0) return false; - Material *m = Tile::tiles[tile]->material; - if (m == Material::water && !mob->isInWater()) return false; - if (m == Material::lava) return false; - } - } - - return true; -} - -bool PathNavigation::canWalkAbove(int startX, int startY, int startZ, int sx, int sy, int sz, Vec3 *startPos, double goalDirX, double goalDirZ) -{ - - for (int xx = startX; xx < startX + sx; xx++) - { - for (int yy = startY; yy < startY + sy; yy++) - { - for (int zz = startZ; zz < startZ + sz; zz++) - { - - double dirX = xx + 0.5 - startPos->x; - double dirZ = zz + 0.5 - startPos->z; - if (dirX * goalDirX + dirZ * goalDirZ < 0) continue; - int tile = level->getTile(xx, yy, zz); - if (tile <= 0) continue; - if (!Tile::tiles[tile]->isPathfindable(level, xx, yy, zz)) return false; - } - } - } - return true; -} - -void PathNavigation::setLevel(Level *level) -{ - this->level = level; -} \ No newline at end of file +void PathNavigation::setLevel(Level* level) { this->level = level; } \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/PathNavigation.h b/Minecraft.World/AI/Navigation/PathNavigation.h index 9dd40c1d0..6c2797abb 100644 --- a/Minecraft.World/AI/Navigation/PathNavigation.h +++ b/Minecraft.World/AI/Navigation/PathNavigation.h @@ -4,64 +4,66 @@ class Mob; class Level; class Path; -class PathNavigation -{ +class PathNavigation { private: - Mob *mob; - Level *level; - Path *path; - float speed; - float maxDist; - bool avoidSun; - int _tick; - int lastStuckCheck; - Vec3 *lastStuckCheckPos; + Mob* mob; + Level* level; + Path* path; + float speed; + float maxDist; + bool avoidSun; + int _tick; + int lastStuckCheck; + Vec3* lastStuckCheckPos; - bool _canPassDoors; - bool _canOpenDoors; - bool avoidWater; - bool canFloat; + bool _canPassDoors; + bool _canOpenDoors; + bool avoidWater; + bool canFloat; public: - PathNavigation(Mob *mob, Level *level, float maxDist); - ~PathNavigation(); + PathNavigation(Mob* mob, Level* level, float maxDist); + ~PathNavigation(); - void setAvoidWater(bool avoidWater); - bool getAvoidWater(); - void setCanOpenDoors(bool canOpenDoors); - bool canPassDoors(); - void setCanPassDoors(bool canPass); - bool canOpenDoors(); - void setAvoidSun(bool avoidSun); - void setSpeed(float speed); - void setCanFloat(bool canFloat); - Path *createPath(double x, double y, double z); - bool moveTo(double x, double y, double z, float speed); - Path *createPath(std::shared_ptr target); - bool moveTo(std::shared_ptr target, float speed); - bool moveTo(Path *newPath, float speed); - Path *getPath(); - void tick(); + void setAvoidWater(bool avoidWater); + bool getAvoidWater(); + void setCanOpenDoors(bool canOpenDoors); + bool canPassDoors(); + void setCanPassDoors(bool canPass); + bool canOpenDoors(); + void setAvoidSun(bool avoidSun); + void setSpeed(float speed); + void setCanFloat(bool canFloat); + Path* createPath(double x, double y, double z); + bool moveTo(double x, double y, double z, float speed); + Path* createPath(std::shared_ptr target); + bool moveTo(std::shared_ptr target, float speed); + bool moveTo(Path* newPath, float speed); + Path* getPath(); + void tick(); private: - void updatePath(); + void updatePath(); public: - bool isDone(); + bool isDone(); - void stop(); + void stop(); private: - Vec3 *getTempMobPos(); - int getSurfaceY(); - bool canUpdatePath(); - bool isInLiquid(); - void trimPathFromSun(); - bool canMoveDirectly(Vec3 *startPos, Vec3 *stopPos, int sx, int sy, int sz); - bool canWalkOn(int x, int y, int z, int sx, int sy, int sz, Vec3 *startPos, double goalDirX, double goalDirZ); - bool canWalkAbove(int startX, int startY, int startZ, int sx, int sy, int sz, Vec3 *startPos, double goalDirX, double goalDirZ); + Vec3* getTempMobPos(); + int getSurfaceY(); + bool canUpdatePath(); + bool isInLiquid(); + void trimPathFromSun(); + bool canMoveDirectly(Vec3* startPos, Vec3* stopPos, int sx, int sy, int sz); + bool canWalkOn(int x, int y, int z, int sx, int sy, int sz, Vec3* startPos, + double goalDirX, double goalDirZ); + bool canWalkAbove(int startX, int startY, int startZ, int sx, int sy, + int sz, Vec3* startPos, double goalDirX, double goalDirZ); public: - // 4J Added override to update ai elements when loading entity from schematics - void setLevel(Level *level); + // 4J Added override to update ai elements when loading entity from + // schematics + void setLevel(Level* level); }; \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/RandomPos.cpp b/Minecraft.World/AI/Navigation/RandomPos.cpp index 4f1e6272a..d092d0e82 100644 --- a/Minecraft.World/AI/Navigation/RandomPos.cpp +++ b/Minecraft.World/AI/Navigation/RandomPos.cpp @@ -3,86 +3,86 @@ #include "../../Headers/net.minecraft.world.phys.h" #include "RandomPos.h" -Vec3 *RandomPos::tempDir = Vec3::newPermanent(0, 0, 0); +Vec3* RandomPos::tempDir = Vec3::newPermanent(0, 0, 0); -Vec3 *RandomPos::getPos(std::shared_ptr mob, int xzDist, int yDist, int quadrant/*=-1*/) // 4J - added quadrant +Vec3* RandomPos::getPos(std::shared_ptr mob, int xzDist, + int yDist, int quadrant /*=-1*/) // 4J - added quadrant { - return generateRandomPos(mob, xzDist, yDist, NULL, quadrant); + return generateRandomPos(mob, xzDist, yDist, NULL, quadrant); } -Vec3 *RandomPos::getPosTowards(std::shared_ptr mob, int xzDist, int yDist, Vec3 *towardsPos) -{ - tempDir->x = towardsPos->x - mob->x; - tempDir->y = towardsPos->y - mob->y; - tempDir->z = towardsPos->z - mob->z; - return generateRandomPos(mob, xzDist, yDist, tempDir); +Vec3* RandomPos::getPosTowards(std::shared_ptr mob, int xzDist, + int yDist, Vec3* towardsPos) { + tempDir->x = towardsPos->x - mob->x; + tempDir->y = towardsPos->y - mob->y; + tempDir->z = towardsPos->z - mob->z; + return generateRandomPos(mob, xzDist, yDist, tempDir); } -Vec3 *RandomPos::getPosAvoid(std::shared_ptr mob, int xzDist, int yDist, Vec3 *avoidPos) -{ - tempDir->x = mob->x - avoidPos->x; - tempDir->y = mob->y - avoidPos->y; - tempDir->z = mob->z - avoidPos->z; - return generateRandomPos(mob, xzDist, yDist, tempDir); +Vec3* RandomPos::getPosAvoid(std::shared_ptr mob, int xzDist, + int yDist, Vec3* avoidPos) { + tempDir->x = mob->x - avoidPos->x; + tempDir->y = mob->y - avoidPos->y; + tempDir->z = mob->z - avoidPos->z; + return generateRandomPos(mob, xzDist, yDist, tempDir); } -Vec3 *RandomPos::generateRandomPos(std::shared_ptr mob, int xzDist, int yDist, Vec3 *dir, int quadrant/*=-1*/) // 4J - added quadrant +Vec3* RandomPos::generateRandomPos(std::shared_ptr mob, + int xzDist, int yDist, Vec3* dir, + int quadrant /*=-1*/) // 4J - added quadrant { - Random *random = mob->getRandom(); - bool hasBest = false; - int xBest = 0, yBest = 0, zBest = 0; - float best = -99999; + Random* random = mob->getRandom(); + bool hasBest = false; + int xBest = 0, yBest = 0, zBest = 0; + float best = -99999; - // 4J Stu - restrict is a reserved keyword - bool bRestrict; - if (mob->hasRestriction()) - { - double restDist = mob->getRestrictCenter()->distSqr(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)) + 4; - double radius = mob->getRestrictRadius() + xzDist; - bRestrict = restDist < radius * radius; - } - else bRestrict = false; + // 4J Stu - restrict is a reserved keyword + bool bRestrict; + if (mob->hasRestriction()) { + double restDist = + mob->getRestrictCenter()->distSqr( + Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)) + + 4; + double radius = mob->getRestrictRadius() + xzDist; + bRestrict = restDist < radius * radius; + } else + bRestrict = false; - for (int i = 0; i < 10; i++) - { - int xt, yt, zt; - // 4J - added quadrant here so that we can choose to select positions only within the one quadrant. Passing a parameter of -1 will - // lead to normal java behaviour - if( quadrant == -1 ) - { - xt = random->nextInt(2 * xzDist) - xzDist; - zt = random->nextInt(2 * xzDist) - xzDist; - } - else - { - int sx = ( ( quadrant & 1 ) ? -1 : 1 ); - int sz = ( ( quadrant & 2 ) ? -1 : 1 ); - xt = random->nextInt(xzDist) * sx; - zt = random->nextInt(xzDist) * sz; - } - yt = random->nextInt(2 * yDist) - yDist; + for (int i = 0; i < 10; i++) { + int xt, yt, zt; + // 4J - added quadrant here so that we can choose to select positions + // only within the one quadrant. Passing a parameter of -1 will lead to + // normal java behaviour + if (quadrant == -1) { + xt = random->nextInt(2 * xzDist) - xzDist; + zt = random->nextInt(2 * xzDist) - xzDist; + } else { + int sx = ((quadrant & 1) ? -1 : 1); + int sz = ((quadrant & 2) ? -1 : 1); + xt = random->nextInt(xzDist) * sx; + zt = random->nextInt(xzDist) * sz; + } + yt = random->nextInt(2 * yDist) - yDist; - if (dir != NULL && xt * dir->x + zt * dir->z < 0) continue; + if (dir != NULL && xt * dir->x + zt * dir->z < 0) continue; - xt += Mth::floor(mob->x); - yt += Mth::floor(mob->y); - zt += Mth::floor(mob->z); + xt += Mth::floor(mob->x); + yt += Mth::floor(mob->y); + zt += Mth::floor(mob->z); - if (bRestrict && !mob->isWithinRestriction(xt, yt, zt)) continue; - float value = mob->getWalkTargetValue(xt, yt, zt); - if (value > best) - { - best = value; - xBest = xt; - yBest = yt; - zBest = zt; - hasBest = true; - } - } - if (hasBest) - { - return Vec3::newTemp(xBest, yBest, zBest); - } + if (bRestrict && !mob->isWithinRestriction(xt, yt, zt)) continue; + float value = mob->getWalkTargetValue(xt, yt, zt); + if (value > best) { + best = value; + xBest = xt; + yBest = yt; + zBest = zt; + hasBest = true; + } + } + if (hasBest) { + return Vec3::newTemp(xBest, yBest, zBest); + } - return NULL; + return NULL; } \ No newline at end of file diff --git a/Minecraft.World/AI/Navigation/RandomPos.h b/Minecraft.World/AI/Navigation/RandomPos.h index a5ee447ba..8baa8e50f 100644 --- a/Minecraft.World/AI/Navigation/RandomPos.h +++ b/Minecraft.World/AI/Navigation/RandomPos.h @@ -2,16 +2,20 @@ class PathfinderMob; -class RandomPos -{ +class RandomPos { private: - static Vec3 *tempDir; + static Vec3* tempDir; public: - static Vec3 *getPos(std::shared_ptr mob, int xzDist, int yDist, int quadrant = -1); // 4J added quadrant - static Vec3 *getPosTowards(std::shared_ptr mob, int xzDist, int yDist, Vec3 *towardsPos); - static Vec3 *getPosAvoid(std::shared_ptr mob, int xzDist, int yDist, Vec3 *avoidPos); + static Vec3* getPos(std::shared_ptr mob, int xzDist, + int yDist, int quadrant = -1); // 4J added quadrant + static Vec3* getPosTowards(std::shared_ptr mob, int xzDist, + int yDist, Vec3* towardsPos); + static Vec3* getPosAvoid(std::shared_ptr mob, int xzDist, + int yDist, Vec3* avoidPos); private: - static Vec3 *generateRandomPos(std::shared_ptr mob, int xzDist, int yDist, Vec3 *dir, int quadrant = -1); // 4J added quadrant + static Vec3* generateRandomPos(std::shared_ptr mob, + int xzDist, int yDist, Vec3* dir, + int quadrant = -1); // 4J added quadrant }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/AirTile.cpp b/Minecraft.World/Blocks/AirTile.cpp index 93c7ab534..ccad24637 100644 --- a/Minecraft.World/Blocks/AirTile.cpp +++ b/Minecraft.World/Blocks/AirTile.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "AirTile.h" -AirTile::AirTile(int id) : Tile(id, Material::air) -{ -} +AirTile::AirTile(int id) : Tile(id, Material::air) {} diff --git a/Minecraft.World/Blocks/AirTile.h b/Minecraft.World/Blocks/AirTile.h index 4395615cb..c50484e95 100644 --- a/Minecraft.World/Blocks/AirTile.h +++ b/Minecraft.World/Blocks/AirTile.h @@ -2,10 +2,9 @@ #include "Tile.h" #include "Material.h" -class AirTile : public Tile -{ - friend class Tile; +class AirTile : public Tile { + friend class Tile; protected: - AirTile(int id); + AirTile(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/AnvilTile.cpp b/Minecraft.World/Blocks/AnvilTile.cpp index 9b15e16fa..7e2f3e3ec 100644 --- a/Minecraft.World/Blocks/AnvilTile.cpp +++ b/Minecraft.World/Blocks/AnvilTile.cpp @@ -7,111 +7,89 @@ #include "../Headers/net.minecraft.h" #include "AnvilTile.h" -const unsigned int AnvilTile::ANVIL_NAMES[ANVIL_NAMES_LENGTH] = { IDS_TILE_ANVIL_INTACT, - IDS_TILE_ANVIL_SLIGHTLYDAMAGED, - IDS_TILE_ANVIL_VERYDAMAGED, - }; - - -std::wstring AnvilTile::TEXTURE_DAMAGE_NAMES[ANVIL_NAMES_LENGTH] = { - L"anvil_top", L"anvil_top_damaged_1", L"anvil_top_damaged_2" +const unsigned int AnvilTile::ANVIL_NAMES[ANVIL_NAMES_LENGTH] = { + IDS_TILE_ANVIL_INTACT, + IDS_TILE_ANVIL_SLIGHTLYDAMAGED, + IDS_TILE_ANVIL_VERYDAMAGED, }; -AnvilTile::AnvilTile(int id) : HeavyTile(id, Material::heavyMetal, false) -{ - part = PART_BASE; - setLightBlock(0); - icons = NULL; +std::wstring AnvilTile::TEXTURE_DAMAGE_NAMES[ANVIL_NAMES_LENGTH] = { + L"anvil_top", L"anvil_top_damaged_1", L"anvil_top_damaged_2"}; + +AnvilTile::AnvilTile(int id) : HeavyTile(id, Material::heavyMetal, false) { + part = PART_BASE; + setLightBlock(0); + icons = NULL; } -bool AnvilTile::isCubeShaped() -{ - return false; +bool AnvilTile::isCubeShaped() { return false; } + +bool AnvilTile::isSolidRender(bool isServerLevel) { return false; } + +Icon* AnvilTile::getTexture(int face, int data) { + if (part == PART_TOP && face == Facing::UP) { + int damage = (data >> 2) % ANVIL_NAMES_LENGTH; + return icons[damage]; + } + return icon; } -bool AnvilTile::isSolidRender(bool isServerLevel) -{ - return false; +void AnvilTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"anvil_base"); + icons = new Icon*[ANVIL_NAMES_LENGTH]; + + for (int i = 0; i < ANVIL_NAMES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_DAMAGE_NAMES[i]); + } } -Icon *AnvilTile::getTexture(int face, int data) -{ - if (part == PART_TOP && face == Facing::UP) - { - int damage = (data >> 2) % ANVIL_NAMES_LENGTH; - return icons[damage]; - } - return icon; +void AnvilTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; + int dmg = level->getData(x, y, z) >> 2; + + dir = ++dir % 4; + if (dir == 0) level->setData(x, y, z, Direction::NORTH | (dmg << 2)); + if (dir == 1) level->setData(x, y, z, Direction::EAST | (dmg << 2)); + if (dir == 2) level->setData(x, y, z, Direction::SOUTH | (dmg << 2)); + if (dir == 3) level->setData(x, y, z, Direction::WEST | (dmg << 2)); } -void AnvilTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"anvil_base"); - icons = new Icon*[ANVIL_NAMES_LENGTH]; - - for (int i = 0; i < ANVIL_NAMES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_DAMAGE_NAMES[i]); - } +bool AnvilTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, bool soundOnly) { + if (level->isClientSide) { + return true; + } + player->startRepairing(x, y, z); + return true; } -void AnvilTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; - int dmg = level->getData(x, y, z) >> 2; +int AnvilTile::getRenderShape() { return SHAPE_ANVIL; } - dir = ++dir % 4; - if (dir == 0) level->setData(x, y, z, Direction::NORTH | (dmg << 2)); - if (dir == 1) level->setData(x, y, z, Direction::EAST | (dmg << 2)); - if (dir == 2) level->setData(x, y, z, Direction::SOUTH | (dmg << 2)); - if (dir == 3) level->setData(x, y, z, Direction::WEST | (dmg << 2)); +int AnvilTile::getSpawnResourcesAuxValue(int data) { return data >> 2; } + +void AnvilTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + int dir = level->getData(x, y, z) & 3; + + if (dir == Direction::EAST || dir == Direction::WEST) { + setShape(0, 0, 2 / 16.0f, 1, 1, 1 - 2 / 16.0f); + } else { + setShape(2 / 16.0f, 0, 0, 1 - 2 / 16.0f, 1, 1); + } } -bool AnvilTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly) -{ - if (level->isClientSide) - { - return true; - } - player->startRepairing(x, y, z); - return true; +void AnvilTile::falling(std::shared_ptr entity) { + entity->setHurtsEntities(true); } -int AnvilTile::getRenderShape() -{ - return SHAPE_ANVIL; +void AnvilTile::onLand(Level* level, int xt, int yt, int zt, int data) { + level->levelEvent(LevelEvent::SOUND_ANVIL_LAND, xt, yt, zt, 0); } -int AnvilTile::getSpawnResourcesAuxValue(int data) -{ - return data >> 2; -} - -void AnvilTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - int dir = level->getData(x, y, z) & 3; - - if (dir == Direction::EAST || dir == Direction::WEST) - { - setShape(0, 0, 2 / 16.0f, 1, 1, 1 - 2 / 16.0f); - } - else - { - setShape(2 / 16.0f, 0, 0, 1 - 2 / 16.0f, 1, 1); - } -} - -void AnvilTile::falling(std::shared_ptr entity) -{ - entity->setHurtsEntities(true); -} - -void AnvilTile::onLand(Level *level, int xt, int yt, int zt, int data) -{ - level->levelEvent(LevelEvent::SOUND_ANVIL_LAND, xt, yt, zt, 0); -} - -bool AnvilTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - return true; +bool AnvilTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + return true; } diff --git a/Minecraft.World/Blocks/AnvilTile.h b/Minecraft.World/Blocks/AnvilTile.h index 745d03997..30c8882a2 100644 --- a/Minecraft.World/Blocks/AnvilTile.h +++ b/Minecraft.World/Blocks/AnvilTile.h @@ -4,47 +4,53 @@ class FallingTile; -class AnvilTile : public HeavyTile -{ - friend class ChunkRebuildData; - friend class Tile; +class AnvilTile : public HeavyTile { + friend class ChunkRebuildData; + friend class Tile; + public: - static const int PART_BASE = 0; - static const int PART_JOINT = 1; - static const int PART_COLUMN = 2; - static const int PART_TOP = 3; + static const int PART_BASE = 0; + static const int PART_JOINT = 1; + static const int PART_COLUMN = 2; + static const int PART_TOP = 3; - static const int ANVIL_NAMES_LENGTH = 3; + static const int ANVIL_NAMES_LENGTH = 3; - static const unsigned int ANVIL_NAMES[ANVIL_NAMES_LENGTH]; + static const unsigned int ANVIL_NAMES[ANVIL_NAMES_LENGTH]; private: - static std::wstring TEXTURE_DAMAGE_NAMES[ANVIL_NAMES_LENGTH]; + static std::wstring TEXTURE_DAMAGE_NAMES[ANVIL_NAMES_LENGTH]; public: - int part; + int part; private: - Icon **icons; + Icon** icons; protected: - AnvilTile(int id); + AnvilTile(int id); public: - bool isCubeShaped(); - bool isSolidRender(bool isServerLevel = false); - Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); - void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); - int getRenderShape(); - int getSpawnResourcesAuxValue(int data); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); + bool isCubeShaped(); + bool isSolidRender(bool isServerLevel = false); + Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); + void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); + int getRenderShape(); + int getSpawnResourcesAuxValue(int data); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); protected: - void falling(std::shared_ptr entity); + void falling(std::shared_ptr entity); public: - void onLand(Level *level, int xt, int yt, int zt, int data); - bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + void onLand(Level* level, int xt, int yt, int zt, int data); + bool shouldRenderFace(LevelSource* level, int x, int y, int z, int face); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/BedTile.cpp b/Minecraft.World/Blocks/BedTile.cpp index 527dd80c7..0982bdc1b 100644 --- a/Minecraft.World/Blocks/BedTile.cpp +++ b/Minecraft.World/Blocks/BedTile.cpp @@ -7,86 +7,75 @@ #include "../Headers/net.minecraft.world.h" #include "BedTile.h" -int BedTile::HEAD_DIRECTION_OFFSETS[4][2] = -{ - { 0, 1 }, { -1, 0 }, { 0, -1 }, { 1, 0 } -}; +int BedTile::HEAD_DIRECTION_OFFSETS[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; -BedTile::BedTile(int id) : DirectionalTile(id, Material::cloth, false) -{ - setShape(); +BedTile::BedTile(int id) : DirectionalTile(id, Material::cloth, false) { + setShape(); - iconEnd = NULL; - iconSide = NULL; - iconTop = NULL; + iconEnd = NULL; + iconSide = NULL; + iconTop = NULL; } // 4J Added override -void BedTile::updateDefaultShape() -{ - setShape(); -} +void BedTile::updateDefaultShape() { setShape(); } // 4J-PB - Adding a TestUse for tooltip display -bool BedTile::TestUse(Level *level, int x, int y, int z, std::shared_ptr player) -{ - //if (level->isClientSide) return true; - - int data = level->getData(x, y, z); - - if (!BedTile::isHeadPiece(data)) - { - // fetch head piece instead - int direction = getDirection(data); - x += HEAD_DIRECTION_OFFSETS[direction][0]; - z += HEAD_DIRECTION_OFFSETS[direction][1]; - if (level->getTile(x, y, z) != id) - { - return true; - } - data = level->getData(x, y, z); - } - - if (!level->dimension->mayRespawn()) - { - return false; - } - if (BedTile::isOccupied(data)) - { - return false; - } - - Player::BedSleepingResult result = player->startSleepInBed(x, y, z, true); // true to just test the start sleep - if (result == Player::OK) - { - return true; - } - - return false; -} - -bool BedTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if( soundOnly) return false; - if (level->isClientSide) return true; +bool BedTile::TestUse(Level* level, int x, int y, int z, + std::shared_ptr player) { + // if (level->isClientSide) return true; int data = level->getData(x, y, z); - if (!BedTile::isHeadPiece(data)) - { + if (!BedTile::isHeadPiece(data)) { // fetch head piece instead int direction = getDirection(data); x += HEAD_DIRECTION_OFFSETS[direction][0]; z += HEAD_DIRECTION_OFFSETS[direction][1]; - if (level->getTile(x, y, z) != id) - { + if (level->getTile(x, y, z) != id) { return true; } data = level->getData(x, y, z); } - if (!level->dimension->mayRespawn()) - { + if (!level->dimension->mayRespawn()) { + return false; + } + if (BedTile::isOccupied(data)) { + return false; + } + + Player::BedSleepingResult result = player->startSleepInBed( + x, y, z, true); // true to just test the start sleep + if (result == Player::OK) { + return true; + } + + return false; +} + +bool BedTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, float clickX, + float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param +{ + if (soundOnly) return false; + if (level->isClientSide) return true; + + int data = level->getData(x, y, z); + + if (!BedTile::isHeadPiece(data)) { + // fetch head piece instead + int direction = getDirection(data); + x += HEAD_DIRECTION_OFFSETS[direction][0]; + z += HEAD_DIRECTION_OFFSETS[direction][1]; + if (level->getTile(x, y, z) != id) { + return true; + } + data = level->getData(x, y, z); + } + + if (!level->dimension->mayRespawn()) { double xc = x + 0.5; double yc = y + 0.5; double zc = z + 0.5; @@ -104,202 +93,164 @@ bool BedTile::use(Level *level, int x, int y, int z, std::shared_ptr pla return true; } - if (BedTile::isOccupied(data)) - { + if (BedTile::isOccupied(data)) { std::shared_ptr sleepingPlayer = nullptr; - AUTO_VAR(itEnd, level->players.end()); - for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++ ) - { - std::shared_ptr p = *it; - if (p->isSleeping()) - { + AUTO_VAR(itEnd, level->players.end()); + for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++) { + std::shared_ptr p = *it; + if (p->isSleeping()) { Pos pos = p->bedPosition; - if (pos.x == x && pos.y == y && pos.z == z) - { + if (pos.x == x && pos.y == y && pos.z == z) { sleepingPlayer = p; } } } - if (sleepingPlayer == NULL) - { + if (sleepingPlayer == NULL) { BedTile::setOccupied(level, x, y, z, false); - } - else - { - player->displayClientMessage(IDS_TILE_BED_OCCUPIED ); - + } else { + player->displayClientMessage(IDS_TILE_BED_OCCUPIED); + return true; } } Player::BedSleepingResult result = player->startSleepInBed(x, y, z); - if (result == Player::OK) - { + if (result == Player::OK) { BedTile::setOccupied(level, x, y, z, true); - // 4J-PB added - // are there multiple players in the same world as us? - if(level->AllPlayersAreSleeping()==false) - { - player->displayClientMessage(IDS_TILE_BED_PLAYERSLEEP); - } - return true; + // 4J-PB added + // are there multiple players in the same world as us? + if (level->AllPlayersAreSleeping() == false) { + player->displayClientMessage(IDS_TILE_BED_PLAYERSLEEP); + } + return true; } - if (result == Player::NOT_POSSIBLE_NOW) - { - player->displayClientMessage(IDS_TILE_BED_NO_SLEEP); - } - else if (result == Player::NOT_SAFE) - { - player->displayClientMessage(IDS_TILE_BED_NOTSAFE); + if (result == Player::NOT_POSSIBLE_NOW) { + player->displayClientMessage(IDS_TILE_BED_NO_SLEEP); + } else if (result == Player::NOT_SAFE) { + player->displayClientMessage(IDS_TILE_BED_NOTSAFE); } return true; } -Icon *BedTile::getTexture(int face, int data) -{ - if (face == Facing::DOWN) - { - return Tile::wood->getTexture(face); - } +Icon* BedTile::getTexture(int face, int data) { + if (face == Facing::DOWN) { + return Tile::wood->getTexture(face); + } - int direction = getDirection(data); - int tileFacing = Direction::RELATIVE_DIRECTION_FACING[direction][face]; + int direction = getDirection(data); + int tileFacing = Direction::RELATIVE_DIRECTION_FACING[direction][face]; - int part = isHeadPiece(data) ? PART_HEAD : PART_FOOT; + int part = isHeadPiece(data) ? PART_HEAD : PART_FOOT; - if ((part == PART_HEAD && tileFacing == Facing::NORTH) || (part == PART_FOOT && tileFacing == Facing::SOUTH)) - { - return iconEnd[part]; - } - if (tileFacing == Facing::EAST || tileFacing == Facing::WEST) - { - return iconSide[part]; - } - return iconTop[part]; + if ((part == PART_HEAD && tileFacing == Facing::NORTH) || + (part == PART_FOOT && tileFacing == Facing::SOUTH)) { + return iconEnd[part]; + } + if (tileFacing == Facing::EAST || tileFacing == Facing::WEST) { + return iconSide[part]; + } + return iconTop[part]; } -void BedTile::registerIcons(IconRegister *iconRegister) -{ - iconTop = new Icon *[2]; - iconTop[0] = iconRegister->registerIcon(L"bed_feet_top"); - iconTop[1] = iconRegister->registerIcon(L"bed_head_top"); +void BedTile::registerIcons(IconRegister* iconRegister) { + iconTop = new Icon*[2]; + iconTop[0] = iconRegister->registerIcon(L"bed_feet_top"); + iconTop[1] = iconRegister->registerIcon(L"bed_head_top"); - iconEnd = new Icon *[2]; - iconEnd[0] = iconRegister->registerIcon(L"bed_feet_end"); - iconEnd[1] = iconRegister->registerIcon(L"bed_head_end"); + iconEnd = new Icon*[2]; + iconEnd[0] = iconRegister->registerIcon(L"bed_feet_end"); + iconEnd[1] = iconRegister->registerIcon(L"bed_head_end"); - iconSide = new Icon *[2]; - iconSide[0] = iconRegister->registerIcon(L"bed_feet_side"); - iconSide[1] = iconRegister->registerIcon(L"bed_head_side"); + iconSide = new Icon*[2]; + iconSide[0] = iconRegister->registerIcon(L"bed_feet_side"); + iconSide[1] = iconRegister->registerIcon(L"bed_head_side"); } -int BedTile::getRenderShape() +int BedTile::getRenderShape() { return Tile::SHAPE_BED; } + +bool BedTile::isCubeShaped() { return false; } + +bool BedTile::isSolidRender(bool isServerLevel) { return false; } + +void BedTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - return Tile::SHAPE_BED; + setShape(); } -bool BedTile::isCubeShaped() -{ - return false; -} - -bool BedTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -void BedTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - setShape(); -} - -void BedTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void BedTile::neighborChanged(Level* level, int x, int y, int z, int type) { int data = level->getData(x, y, z); int direction = getDirection(data); - if (isHeadPiece(data)) - { - if (level->getTile(x - HEAD_DIRECTION_OFFSETS[direction][0], y, z - HEAD_DIRECTION_OFFSETS[direction][1]) != id) - { + if (isHeadPiece(data)) { + if (level->getTile(x - HEAD_DIRECTION_OFFSETS[direction][0], y, + z - HEAD_DIRECTION_OFFSETS[direction][1]) != id) { level->setTile(x, y, z, 0); } - } else - { - if (level->getTile(x + HEAD_DIRECTION_OFFSETS[direction][0], y, z + HEAD_DIRECTION_OFFSETS[direction][1]) != id) - { + } else { + if (level->getTile(x + HEAD_DIRECTION_OFFSETS[direction][0], y, + z + HEAD_DIRECTION_OFFSETS[direction][1]) != id) { level->setTile(x, y, z, 0); - if (!level->isClientSide) - { - Tile::spawnResources(level, x, y, z, data, 0); // 4J - had to add Tile:: here for C++ since this class doesn't have this overloaded method itself + if (!level->isClientSide) { + Tile::spawnResources( + level, x, y, z, data, + 0); // 4J - had to add Tile:: here for C++ since this class + // doesn't have this overloaded method itself } } } } -int BedTile::getResource(int data, Random *random, int playerBonusLevel) -{ - if (isHeadPiece(data)) - { +int BedTile::getResource(int data, Random* random, int playerBonusLevel) { + if (isHeadPiece(data)) { return 0; } return Item::bed->id; } -void BedTile::setShape() -{ - Tile::setShape(0, 0, 0, 1, 9 / 16.0f, 1); -} +void BedTile::setShape() { Tile::setShape(0, 0, 0, 1, 9 / 16.0f, 1); } -bool BedTile::isHeadPiece(int data) -{ - return (data & HEAD_PIECE_DATA) != 0; -} +bool BedTile::isHeadPiece(int data) { return (data & HEAD_PIECE_DATA) != 0; } -bool BedTile::isOccupied(int data) -{ - return (data & OCCUPIED_DATA) != 0; -} +bool BedTile::isOccupied(int data) { return (data & OCCUPIED_DATA) != 0; } -void BedTile::setOccupied(Level *level, int x, int y, int z, bool occupied) -{ +void BedTile::setOccupied(Level* level, int x, int y, int z, bool occupied) { int data = level->getData(x, y, z); - if (occupied) - { + if (occupied) { data = data | OCCUPIED_DATA; - } else - { + } else { data = data & ~OCCUPIED_DATA; } level->setData(x, y, z, data); } -Pos *BedTile::findStandUpPosition(Level *level, int x, int y, int z, int skipCount) -{ +Pos* BedTile::findStandUpPosition(Level* level, int x, int y, int z, + int skipCount) { int data = level->getData(x, y, z); int direction = DirectionalTile::getDirection(data); // try to find a clear location near the bed - for (int step = 0; step <= 1; step++) - { - int startX = x - BedTile::HEAD_DIRECTION_OFFSETS[direction][0] * step - 1; - int startZ = z - BedTile::HEAD_DIRECTION_OFFSETS[direction][1] * step - 1; + for (int step = 0; step <= 1; step++) { + int startX = + x - BedTile::HEAD_DIRECTION_OFFSETS[direction][0] * step - 1; + int startZ = + z - BedTile::HEAD_DIRECTION_OFFSETS[direction][1] * step - 1; int endX = startX + 2; int endZ = startZ + 2; - for (int standX = startX; standX <= endX; standX++) - { - for (int standZ = startZ; standZ <= endZ; standZ++) - { - // 4J Stu - Changed to check isSolidBlockingTile rather than isEmpty for the blocks that we wish to place the player - // This allows the player to spawn in blocks with snow, grass etc + for (int standX = startX; standX <= endX; standX++) { + for (int standZ = startZ; standZ <= endZ; standZ++) { + // 4J Stu - Changed to check isSolidBlockingTile rather than + // isEmpty for the blocks that we wish to place the player This + // allows the player to spawn in blocks with snow, grass etc if (level->isTopSolidBlocking(standX, y - 1, standZ) && - !level->isSolidBlockingTile(standX, y, standZ) && - !level->isSolidBlockingTile(standX, y + 1, standZ)) - { + !level->isSolidBlockingTile(standX, y, standZ) && + !level->isSolidBlockingTile(standX, y + 1, standZ)) { if (skipCount > 0) { skipCount--; continue; @@ -313,20 +264,15 @@ Pos *BedTile::findStandUpPosition(Level *level, int x, int y, int z, int skipCou return NULL; } -void BedTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ - if (!isHeadPiece(data)) - { - Tile::spawnResources(level, x, y, z, data, odds, 0); +void BedTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus) { + if (!isHeadPiece(data)) { + Tile::spawnResources(level, x, y, z, data, odds, 0); } } -int BedTile::getPistonPushReaction() -{ - return Material::PUSH_DESTROY; -} +int BedTile::getPistonPushReaction() { return Material::PUSH_DESTROY; } -int BedTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::bed_Id; +int BedTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::bed_Id; } diff --git a/Minecraft.World/Blocks/BedTile.h b/Minecraft.World/Blocks/BedTile.h index 8cd68ba90..8b2ab316d 100644 --- a/Minecraft.World/Blocks/BedTile.h +++ b/Minecraft.World/Blocks/BedTile.h @@ -6,15 +6,14 @@ class Player; class Random; class Level; -class BedTile : public DirectionalTile -{ +class BedTile : public DirectionalTile { private: - static const int PART_FOOT = 0; - static const int PART_HEAD = 1; + static const int PART_FOOT = 0; + static const int PART_HEAD = 1; - Icon **iconEnd; - Icon **iconSide; - Icon **iconTop; + Icon** iconEnd; + Icon** iconSide; + Icon** iconTop; public: static const int HEAD_PIECE_DATA = 0x8; @@ -23,31 +22,40 @@ public: static int HEAD_DIRECTION_OFFSETS[4][2]; BedTile(int id); - - virtual void updateDefaultShape(); - virtual bool TestUse(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual Icon *getTexture(int face, int data); - //@Override - void registerIcons(IconRegister *iconRegister); + + virtual void updateDefaultShape(); + virtual bool TestUse(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual Icon* getTexture(int face, int data); + //@Override + void registerIcons(IconRegister* iconRegister); virtual int getRenderShape(); - virtual bool isCubeShaped(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual int getResource(int data, Random *random,int playerBonusLevel); + virtual bool isCubeShaped(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual int getResource(int data, Random* random, int playerBonusLevel); private: - using Tile::setShape; + using Tile::setShape; void setShape(); public: static bool isHeadPiece(int data); static bool isOccupied(int data); - static void setOccupied(Level *level, int x, int y, int z, bool occupied); - static Pos *findStandUpPosition(Level *level, int x, int y, int z, int skipCount); + static void setOccupied(Level* level, int x, int y, int z, bool occupied); + static Pos* findStandUpPosition(Level* level, int x, int y, int z, + int skipCount); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); virtual int getPistonPushReaction(); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual int cloneTileId(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/BookshelfTile.cpp b/Minecraft.World/Blocks/BookshelfTile.cpp index 97cfc6f23..461fd23fe 100644 --- a/Minecraft.World/Blocks/BookshelfTile.cpp +++ b/Minecraft.World/Blocks/BookshelfTile.cpp @@ -3,22 +3,16 @@ #include "../Headers/net.minecraft.world.item.h" #include "../Headers/net.minecraft.h" -BookshelfTile::BookshelfTile(int id) : Tile(id, Material::wood) -{ +BookshelfTile::BookshelfTile(int id) : Tile(id, Material::wood) {} + +Icon* BookshelfTile::getTexture(int face, int data) { + if (face == Facing::UP || face == Facing::DOWN) + return Tile::wood->getTexture(face); + return Tile::getTexture(face, data); } -Icon *BookshelfTile::getTexture(int face, int data) -{ - if (face == Facing::UP || face == Facing::DOWN) return Tile::wood->getTexture(face); - return Tile::getTexture(face, data); -} +int BookshelfTile::getResourceCount(Random* random) { return 3; } -int BookshelfTile::getResourceCount(Random *random) -{ - return 3; -} - -int BookshelfTile::getResource(int data, Random *random,int playerBonusLevel) -{ - return Item::book_Id; +int BookshelfTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::book_Id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/BookshelfTile.h b/Minecraft.World/Blocks/BookshelfTile.h index 5b1bc21e7..a5c91f319 100644 --- a/Minecraft.World/Blocks/BookshelfTile.h +++ b/Minecraft.World/Blocks/BookshelfTile.h @@ -4,12 +4,11 @@ class Random; -class BookshelfTile : public Tile -{ +class BookshelfTile : public Tile { public: BookshelfTile(int id); - virtual Icon *getTexture(int face, int data); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random,int playerBonusLevel); + virtual Icon* getTexture(int face, int data); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/BrewingStandTile.cpp b/Minecraft.World/Blocks/BrewingStandTile.cpp index e29eb4509..749a3c8fe 100644 --- a/Minecraft.World/Blocks/BrewingStandTile.cpp +++ b/Minecraft.World/Blocks/BrewingStandTile.cpp @@ -8,103 +8,97 @@ const std::wstring BrewingStandTile::TEXTURE_BASE = L"brewingStand_base"; -BrewingStandTile::BrewingStandTile(int id) : EntityTile(id, Material::metal, false) -{ - random = new Random(); - iconBase = NULL; +BrewingStandTile::BrewingStandTile(int id) + : EntityTile(id, Material::metal, false) { + random = new Random(); + iconBase = NULL; } -BrewingStandTile::~BrewingStandTile() -{ - delete random; +BrewingStandTile::~BrewingStandTile() { delete random; } + +bool BrewingStandTile::isSolidRender(bool isServerLevel) { return false; } + +int BrewingStandTile::getRenderShape() { return SHAPE_BREWING_STAND; } + +std::shared_ptr BrewingStandTile::newTileEntity(Level* level) { + return std::shared_ptr(new BrewingStandTileEntity()); } -bool BrewingStandTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool BrewingStandTile::isCubeShaped() { return false; } -int BrewingStandTile::getRenderShape() -{ - return SHAPE_BREWING_STAND; -} - -std::shared_ptr BrewingStandTile::newTileEntity(Level *level) -{ - return std::shared_ptr(new BrewingStandTileEntity()); -} - -bool BrewingStandTile::isCubeShaped() -{ - return false; -} - -void BrewingStandTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ - setShape(7.0f / 16.0f, 0, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, 9.0f / 16.0f); +void BrewingStandTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, + std::shared_ptr source) { + setShape(7.0f / 16.0f, 0, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, + 9.0f / 16.0f); EntityTile::addAABBs(level, x, y, z, box, boxes, source); updateDefaultShape(); EntityTile::addAABBs(level, x, y, z, box, boxes, source); } -void BrewingStandTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 2.0f / 16.0f, 1); +void BrewingStandTile::updateDefaultShape() { + setShape(0, 0, 0, 1, 2.0f / 16.0f, 1); } -bool BrewingStandTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool BrewingStandTile::use( + Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if(soundOnly) return false; + if (soundOnly) return false; - if (level->isClientSide) - { + if (level->isClientSide) { return true; } - std::shared_ptr brewingStand = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); + std::shared_ptr brewingStand = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); if (brewingStand != NULL) player->openBrewingStand(brewingStand); - return true; + return true; } -void BrewingStandTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ +void BrewingStandTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { double x = xt + 0.4f + random->nextFloat() * 0.2f; double y = yt + 0.7f + random->nextFloat() * 0.3f; double z = zt + 0.4f + random->nextFloat() * 0.2f; - level->addParticle(eParticleType_smoke, x, y, z, 0, 0, 0); } -void BrewingStandTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void BrewingStandTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { std::shared_ptr tileEntity = level->getTileEntity(x, y, z); - if (tileEntity != NULL && ( std::dynamic_pointer_cast(tileEntity) != NULL) ) - { - std::shared_ptr container = std::dynamic_pointer_cast(tileEntity); - for (int i = 0; i < container->getContainerSize(); i++) - { + if (tileEntity != NULL && + (std::dynamic_pointer_cast(tileEntity) != + NULL)) { + std::shared_ptr container = + std::dynamic_pointer_cast(tileEntity); + for (int i = 0; i < container->getContainerSize(); i++) { std::shared_ptr item = container->getItem(i); - if (item != NULL) - { + if (item != NULL) { float xo = random->nextFloat() * 0.8f + 0.1f; float yo = random->nextFloat() * 0.8f + 0.1f; float zo = random->nextFloat() * 0.8f + 0.1f; - while (item->count > 0) - { + while (item->count > 0) { int count = random->nextInt(21) + 10; if (count > item->count) count = item->count; item->count -= count; - std::shared_ptr itemEntity = std::shared_ptr(new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue())))); + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())))); float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); } level->addEntity(itemEntity); } @@ -114,23 +108,18 @@ void BrewingStandTile::onRemove(Level *level, int x, int y, int z, int id, int d EntityTile::onRemove(level, x, y, z, id, data); } -int BrewingStandTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::brewingStand_Id; +int BrewingStandTile::getResource(int data, Random* random, + int playerBonusLevel) { + return Item::brewingStand_Id; } -int BrewingStandTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::brewingStand_Id; +int BrewingStandTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::brewingStand_Id; } -void BrewingStandTile::registerIcons(IconRegister *iconRegister) -{ - EntityTile::registerIcons(iconRegister); - iconBase = iconRegister->registerIcon(TEXTURE_BASE); +void BrewingStandTile::registerIcons(IconRegister* iconRegister) { + EntityTile::registerIcons(iconRegister); + iconBase = iconRegister->registerIcon(TEXTURE_BASE); } -Icon *BrewingStandTile::getBaseTexture() -{ - return iconBase; -} +Icon* BrewingStandTile::getBaseTexture() { return iconBase; } diff --git a/Minecraft.World/Blocks/BrewingStandTile.h b/Minecraft.World/Blocks/BrewingStandTile.h index 03b99361c..4be3140c2 100644 --- a/Minecraft.World/Blocks/BrewingStandTile.h +++ b/Minecraft.World/Blocks/BrewingStandTile.h @@ -4,29 +4,35 @@ class IconRegister; class ChunkRebuildData; -class BrewingStandTile : public EntityTile -{ - friend ChunkRebuildData; -public: - static const std::wstring TEXTURE_BASE; -private: - Random *random; - Icon *iconBase; +class BrewingStandTile : public EntityTile { + friend ChunkRebuildData; public: - BrewingStandTile(int id); - ~BrewingStandTile(); + static const std::wstring TEXTURE_BASE; + +private: + Random* random; + Icon* iconBase; + +public: + BrewingStandTile(int id); + ~BrewingStandTile(); virtual bool isSolidRender(bool isServerLevel = false); virtual int getRenderShape(); - virtual std::shared_ptr newTileEntity(Level *level); + virtual std::shared_ptr newTileEntity(Level* level); virtual bool isCubeShaped(); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); virtual void updateDefaultShape(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); - Icon *getBaseTexture(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); + Icon* getBaseTexture(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/ButtonTile.cpp b/Minecraft.World/Blocks/ButtonTile.cpp index d228b343d..17febb8ea 100644 --- a/Minecraft.World/Blocks/ButtonTile.cpp +++ b/Minecraft.World/Blocks/ButtonTile.cpp @@ -6,45 +6,30 @@ #include "ButtonTile.h" #include "../Util/SoundTypes.h" -ButtonTile::ButtonTile(int id, bool sensitive) : Tile(id, Material::decoration, false) -{ - this->setTicking(true); - this->sensitive = sensitive; +ButtonTile::ButtonTile(int id, bool sensitive) + : Tile(id, Material::decoration, false) { + this->setTicking(true); + this->sensitive = sensitive; } -Icon *ButtonTile::getTexture(int face, int data) -{ - if(id == Tile::button_wood_Id) return Tile::wood->getTexture(Facing::UP); - else return Tile::rock->getTexture(Facing::UP); +Icon* ButtonTile::getTexture(int face, int data) { + if (id == Tile::button_wood_Id) + return Tile::wood->getTexture(Facing::UP); + else + return Tile::rock->getTexture(Facing::UP); } -AABB *ButtonTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} +AABB* ButtonTile::getAABB(Level* level, int x, int y, int z) { return NULL; } -int ButtonTile::getTickDelay() -{ - return sensitive ? 30 : 20; -} +int ButtonTile::getTickDelay() { return sensitive ? 30 : 20; } -bool ButtonTile::blocksLight() -{ - return false; -} +bool ButtonTile::blocksLight() { return false; } -bool ButtonTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool ButtonTile::isSolidRender(bool isServerLevel) { return false; } -bool ButtonTile::isCubeShaped() -{ - return false; -} +bool ButtonTile::isCubeShaped() { return false; } -bool ButtonTile::mayPlace(Level *level, int x, int y, int z, int face) -{ +bool ButtonTile::mayPlace(Level* level, int x, int y, int z, int face) { if (face == 2 && level->isSolidBlockingTile(x, y, z + 1)) return true; if (face == 3 && level->isSolidBlockingTile(x, y, z - 1)) return true; if (face == 4 && level->isSolidBlockingTile(x + 1, y, z)) return true; @@ -52,88 +37,77 @@ bool ButtonTile::mayPlace(Level *level, int x, int y, int z, int face) return false; } -bool ButtonTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTile(x - 1, y, z)) - { +bool ButtonTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTile(x - 1, y, z)) { return true; - } - else if (level->isSolidBlockingTile(x + 1, y, z)) - { + } else if (level->isSolidBlockingTile(x + 1, y, z)) { return true; - } - else if (level->isSolidBlockingTile(x, y, z - 1)) - { + } else if (level->isSolidBlockingTile(x, y, z - 1)) { return true; - } - else if (level->isSolidBlockingTile(x, y, z + 1)) - { + } else if (level->isSolidBlockingTile(x, y, z + 1)) { return true; } return false; } -int ButtonTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ +int ButtonTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { int dir = level->getData(x, y, z); int oldFlip = dir & 8; dir &= 7; - if (face == 2 && level->isSolidBlockingTile(x, y, z + 1)) dir = 4; - else if (face == 3 && level->isSolidBlockingTile(x, y, z - 1)) dir = 3; - else if (face == 4 && level->isSolidBlockingTile(x + 1, y, z)) dir = 2; - else if (face == 5 && level->isSolidBlockingTile(x - 1, y, z)) dir = 1; - else dir = findFace(level, x, y, z); + if (face == 2 && level->isSolidBlockingTile(x, y, z + 1)) + dir = 4; + else if (face == 3 && level->isSolidBlockingTile(x, y, z - 1)) + dir = 3; + else if (face == 4 && level->isSolidBlockingTile(x + 1, y, z)) + dir = 2; + else if (face == 5 && level->isSolidBlockingTile(x - 1, y, z)) + dir = 1; + else + dir = findFace(level, x, y, z); return dir + oldFlip; } -int ButtonTile::findFace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTile(x - 1, y, z)) - { +int ButtonTile::findFace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTile(x - 1, y, z)) { return 1; - } - else if (level->isSolidBlockingTile(x + 1, y, z)) - { + } else if (level->isSolidBlockingTile(x + 1, y, z)) { return 2; - } - else if (level->isSolidBlockingTile(x, y, z - 1)) - { + } else if (level->isSolidBlockingTile(x, y, z - 1)) { return 3; - } - else if (level->isSolidBlockingTile(x, y, z + 1)) - { + } else if (level->isSolidBlockingTile(x, y, z + 1)) { return 4; } return 1; } -void ButtonTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (checkCanSurvive(level, x, y, z)) - { +void ButtonTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (checkCanSurvive(level, x, y, z)) { int dir = level->getData(x, y, z) & 7; bool replace = false; - if (!level->isSolidBlockingTile(x - 1, y, z) && dir == 1) replace = true; - if (!level->isSolidBlockingTile(x + 1, y, z) && dir == 2) replace = true; - if (!level->isSolidBlockingTile(x, y, z - 1) && dir == 3) replace = true; - if (!level->isSolidBlockingTile(x, y, z + 1) && dir == 4) replace = true; + if (!level->isSolidBlockingTile(x - 1, y, z) && dir == 1) + replace = true; + if (!level->isSolidBlockingTile(x + 1, y, z) && dir == 2) + replace = true; + if (!level->isSolidBlockingTile(x, y, z - 1) && dir == 3) + replace = true; + if (!level->isSolidBlockingTile(x, y, z + 1) && dir == 4) + replace = true; - if (replace) - { + if (replace) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } } } -bool ButtonTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!mayPlace(level, x, y, z)) - { +bool ButtonTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!mayPlace(level, x, y, z)) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); return false; @@ -141,14 +115,16 @@ bool ButtonTile::checkCanSurvive(Level *level, int x, int y, int z) return true; } -void ButtonTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void ButtonTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - int data = level->getData(x, y, z); - updateShape(data); + int data = level->getData(x, y, z); + updateShape(data); } -void ButtonTile::updateShape(int data) -{ +void ButtonTile::updateShape(int data) { int dir = data & 7; bool pressed = (data & 8) > 0; @@ -158,43 +134,36 @@ void ButtonTile::updateShape(int data) float d = 2 / 16.0f; if (pressed) d = 1 / 16.0f; - if (dir == 1) - { + if (dir == 1) { setShape(0, h0, 0.5f - r, d, h1, 0.5f + r); - } - else if (dir == 2) - { + } else if (dir == 2) { setShape(1 - d, h0, 0.5f - r, 1, h1, 0.5f + r); - } - else if (dir == 3) - { + } else if (dir == 3) { setShape(0.5f - r, h0, 0, 0.5f + r, h1, d); - } - else if (dir == 4) - { + } else if (dir == 4) { setShape(0.5f - r, h0, 1 - d, 0.5f + r, h1, 1); } } -void ButtonTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - //use(level, x, y, z, player, 0, 0, 0, 0); +void ButtonTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + // use(level, x, y, z, player, 0, 0, 0, 0); } // 4J-PB - Adding a TestUse for tooltip display -bool ButtonTile::TestUse() -{ - return true; -} +bool ButtonTile::TestUse() { return true; } -bool ButtonTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool ButtonTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly) - { - // 4J - added - just do enough to play the sound - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.6f); - return false; - } + if (soundOnly) { + // 4J - added - just do enough to play the sound + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.6f); + return false; + } int data = level->getData(x, y, z); int dir = data & 7; int open = 8 - (data & 8); @@ -203,7 +172,8 @@ bool ButtonTile::use(Level *level, int x, int y, int z, std::shared_ptr level->setData(x, y, z, dir + open); level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.6f); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, + 0.6f); updateNeighbours(level, x, y, z, dir); @@ -212,23 +182,19 @@ bool ButtonTile::use(Level *level, int x, int y, int z, std::shared_ptr return true; } -void ButtonTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - if ((data & 8) > 0) - { +void ButtonTile::onRemove(Level* level, int x, int y, int z, int id, int data) { + if ((data & 8) > 0) { int dir = data & 7; updateNeighbours(level, x, y, z, dir); } Tile::onRemove(level, x, y, z, id, data); } -bool ButtonTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return (level->getData(x, y, z) & 8) > 0; +bool ButtonTile::getSignal(LevelSource* level, int x, int y, int z, int dir) { + return (level->getData(x, y, z) & 8) > 0; } -bool ButtonTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ +bool ButtonTile::getDirectSignal(Level* level, int x, int y, int z, int dir) { int data = level->getData(x, y, z); if ((data & 8) == 0) return false; int myDir = data & 7; @@ -242,125 +208,105 @@ bool ButtonTile::getDirectSignal(Level *level, int x, int y, int z, int dir) return false; } -bool ButtonTile::isSignalSource() -{ - return true; +bool ButtonTile::isSignalSource() { return true; } + +void ButtonTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isClientSide) return; + int data = level->getData(x, y, z); + if ((data & 8) == 0) { + return; + } + if (sensitive) { + checkPressed(level, x, y, z); + } else { + level->setData(x, y, z, data & 7); + + int dir = data & 7; + updateNeighbours(level, x, y, z, dir); + + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.5f); + level->setTilesDirty(x, y, z, x, y, z); + } } -void ButtonTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isClientSide) return; - int data = level->getData(x, y, z); - if ((data & 8) == 0) - { - return; - } - if(sensitive) - { - checkPressed(level, x, y, z); - } - else - { - level->setData(x, y, z, data & 7); - - int dir = data & 7; - updateNeighbours(level, x, y, z, dir); - - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.5f); - level->setTilesDirty(x, y, z, x, y, z); - } -} - -void ButtonTile::updateDefaultShape() -{ +void ButtonTile::updateDefaultShape() { float x = 3 / 16.0f; float y = 2 / 16.0f; float z = 2 / 16.0f; setShape(0.5f - x, 0.5f - y, 0.5f - z, 0.5f + x, 0.5f + y, 0.5f + z); } -void ButtonTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (level->isClientSide) return; - if (!sensitive) return; +void ButtonTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (level->isClientSide) return; + if (!sensitive) return; - if ((level->getData(x, y, z) & 8) != 0) - { - return; - } + if ((level->getData(x, y, z) & 8) != 0) { + return; + } - checkPressed(level, x, y, z); + checkPressed(level, x, y, z); } -void ButtonTile::checkPressed(Level *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - int dir = data & 7; - bool wasPressed = (data & 8) != 0; - bool shouldBePressed; +void ButtonTile::checkPressed(Level* level, int x, int y, int z) { + int data = level->getData(x, y, z); + int dir = data & 7; + bool wasPressed = (data & 8) != 0; + bool shouldBePressed; - updateShape(data); - Tile::ThreadStorage *tls = (Tile::ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - std::vector > *entities = level->getEntitiesOfClass(typeid(Arrow), AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1)); - shouldBePressed = !entities->empty(); - delete entities; + updateShape(data); + Tile::ThreadStorage* tls = + (Tile::ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + std::vector >* entities = level->getEntitiesOfClass( + typeid(Arrow), AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, + x + tls->xx1, y + tls->yy1, z + tls->zz1)); + shouldBePressed = !entities->empty(); + delete entities; - if (shouldBePressed && !wasPressed) - { - level->setData(x, y, z, dir | 8); - updateNeighbours(level, x, y, z, dir); - level->setTilesDirty(x, y, z, x, y, z); + if (shouldBePressed && !wasPressed) { + level->setData(x, y, z, dir | 8); + updateNeighbours(level, x, y, z, dir); + level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.6f); - } - if (!shouldBePressed && wasPressed) - { - level->setData(x, y, z, dir); - updateNeighbours(level, x, y, z, dir); - level->setTilesDirty(x, y, z, x, y, z); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.6f); + } + if (!shouldBePressed && wasPressed) { + level->setData(x, y, z, dir); + updateNeighbours(level, x, y, z, dir); + level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.5f); - } + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.5f); + } - if (shouldBePressed) - { - level->addToTickNextTick(x, y, z, id, getTickDelay()); - } + if (shouldBePressed) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); + } } -void ButtonTile::updateNeighbours(Level *level, int x, int y, int z, int dir) -{ - level->updateNeighborsAt(x, y, z, id); +void ButtonTile::updateNeighbours(Level* level, int x, int y, int z, int dir) { + level->updateNeighborsAt(x, y, z, id); - if (dir == 1) - { - level->updateNeighborsAt(x - 1, y, z, id); - } - else if (dir == 2) - { - level->updateNeighborsAt(x + 1, y, z, id); - } - else if (dir == 3) - { - level->updateNeighborsAt(x, y, z - 1, id); - } - else if (dir == 4) - { - level->updateNeighborsAt(x, y, z + 1, id); - } - else - { - level->updateNeighborsAt(x, y - 1, z, id); - } + if (dir == 1) { + level->updateNeighborsAt(x - 1, y, z, id); + } else if (dir == 2) { + level->updateNeighborsAt(x + 1, y, z, id); + } else if (dir == 3) { + level->updateNeighborsAt(x, y, z - 1, id); + } else if (dir == 4) { + level->updateNeighborsAt(x, y, z + 1, id); + } else { + level->updateNeighborsAt(x, y - 1, z, id); + } } -bool ButtonTile::shouldTileTick(Level *level, int x,int y,int z) -{ - int currentData = level->getData(x, y, z); +bool ButtonTile::shouldTileTick(Level* level, int x, int y, int z) { + int currentData = level->getData(x, y, z); return (currentData & 8) != 0; } -void ButtonTile::registerIcons(IconRegister *iconRegister) -{ - // None +void ButtonTile::registerIcons(IconRegister* iconRegister) { + // None } diff --git a/Minecraft.World/Blocks/ButtonTile.h b/Minecraft.World/Blocks/ButtonTile.h index fb84c3455..3bdffe67c 100644 --- a/Minecraft.World/Blocks/ButtonTile.h +++ b/Minecraft.World/Blocks/ButtonTile.h @@ -6,61 +6,71 @@ class Player; class Random; class Level; -class ButtonTile : public Tile -{ - friend class Tile; +class ButtonTile : public Tile { + friend class Tile; private: - bool sensitive; + bool sensitive; protected: - ButtonTile(int id, bool sensitive); + ButtonTile(int id, bool sensitive); public: - Icon *getTexture(int face, int data); - virtual AABB *getAABB(Level *level, int x, int y, int z); + Icon* getTexture(int face, int data); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual int getTickDelay(); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); private: - int findFace(Level *level, int x, int y, int z); + int findFace(Level* level, int x, int y, int z); public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); private: - bool checkCanSurvive(Level *level, int x, int y, int z); + bool checkCanSurvive(Level* level, int x, int y, int z); public: - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param private: - void updateShape(int data); + void updateShape(int data); public: - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); virtual bool isSignalSource(); - virtual void tick(Level *level, int x, int y, int z, Random *random); + virtual void tick(Level* level, int x, int y, int z, Random* random); virtual void updateDefaultShape(); - void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); + void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); private: - void checkPressed(Level *level, int x, int y, int z); - void updateNeighbours(Level *level, int x, int y, int z, int dir); + void checkPressed(Level* level, int x, int y, int z); + void updateNeighbours(Level* level, int x, int y, int z, int dir); public: - void registerIcons(IconRegister *iconRegister); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + void registerIcons(IconRegister* iconRegister); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CactusTile.cpp b/Minecraft.World/Blocks/CactusTile.cpp index 92f26b745..25072b23d 100644 --- a/Minecraft.World/Blocks/CactusTile.cpp +++ b/Minecraft.World/Blocks/CactusTile.cpp @@ -8,90 +8,68 @@ #include "../Headers/net.minecraft.world.h" #include "CactusTile.h" -CactusTile::CactusTile(int id) : Tile(id, Material::cactus, false) -{ - setTicking(true); - iconTop = NULL; +CactusTile::CactusTile(int id) : Tile(id, Material::cactus, false) { + setTicking(true); + iconTop = NULL; iconBottom = NULL; } -void CactusTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isEmptyTile(x, y + 1, z)) - { - int height = 1; - while (level->getTile(x, y - height, z) == id) - { - height++; - } - if (height < 3) - { - int age = level->getData(x, y, z); - if (age == 15) - { - level->setTile(x, y + 1, z, id); - level->setData(x, y, z, 0); - } else - { - level->setData(x, y, z, age + 1); - } - } - } +void CactusTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isEmptyTile(x, y + 1, z)) { + int height = 1; + while (level->getTile(x, y - height, z) == id) { + height++; + } + if (height < 3) { + int age = level->getData(x, y, z); + if (age == 15) { + level->setTile(x, y + 1, z, id); + level->setData(x, y, z, 0); + } else { + level->setData(x, y, z, age + 1); + } + } + } } -AABB *CactusTile::getAABB(Level *level, int x, int y, int z) -{ +AABB* CactusTile::getAABB(Level* level, int x, int y, int z) { float r = 1 / 16.0f; return AABB::newTemp(x + r, y, z + r, x + 1 - r, y + 1 - r, z + 1 - r); - } -AABB *CactusTile::getTileAABB(Level *level, int x, int y, int z) -{ +AABB* CactusTile::getTileAABB(Level* level, int x, int y, int z) { float r = 1 / 16.0f; return AABB::newTemp(x + r, y, z + r, x + 1 - r, y + 1, z + 1 - r); } -Icon *CactusTile::getTexture(int face, int data) -{ +Icon* CactusTile::getTexture(int face, int data) { if (face == Facing::UP) return iconTop; - if (face == Facing::DOWN) return iconBottom; - else return icon; + if (face == Facing::DOWN) + return iconBottom; + else + return icon; } -bool CactusTile::isCubeShaped() -{ - return false; -} +bool CactusTile::isCubeShaped() { return false; } -bool CactusTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool CactusTile::isSolidRender(bool isServerLevel) { return false; } -int CactusTile::getRenderShape() -{ - return Tile::SHAPE_CACTUS; -} +int CactusTile::getRenderShape() { return Tile::SHAPE_CACTUS; } -bool CactusTile::mayPlace(Level *level, int x, int y, int z) -{ +bool CactusTile::mayPlace(Level* level, int x, int y, int z) { if (!Tile::mayPlace(level, x, y, z)) return false; return canSurvive(level, x, y, z); } -void CactusTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!canSurvive(level, x, y, z)) - { +void CactusTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!canSurvive(level, x, y, z)) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); - } + } } -bool CactusTile::canSurvive(Level *level, int x, int y, int z) -{ +bool CactusTile::canSurvive(Level* level, int x, int y, int z) { if (level->getMaterial(x - 1, y, z)->isSolid()) return false; if (level->getMaterial(x + 1, y, z)->isSolid()) return false; if (level->getMaterial(x, y, z - 1)->isSolid()) return false; @@ -100,19 +78,17 @@ bool CactusTile::canSurvive(Level *level, int x, int y, int z) return below == Tile::cactus_Id || below == Tile::sand_Id; } -void CactusTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - entity->hurt(DamageSource::cactus, 1); +void CactusTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + entity->hurt(DamageSource::cactus, 1); } -void CactusTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"cactus_side"); - iconTop = iconRegister->registerIcon(L"cactus_top"); - iconBottom = iconRegister->registerIcon(L"cactus_bottom"); +void CactusTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"cactus_side"); + iconTop = iconRegister->registerIcon(L"cactus_top"); + iconBottom = iconRegister->registerIcon(L"cactus_bottom"); } -bool CactusTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool CactusTile::shouldTileTick(Level* level, int x, int y, int z) { return level->isEmptyTile(x, y + 1, z); } diff --git a/Minecraft.World/Blocks/CactusTile.h b/Minecraft.World/Blocks/CactusTile.h index cf95bb936..a34b596d0 100644 --- a/Minecraft.World/Blocks/CactusTile.h +++ b/Minecraft.World/Blocks/CactusTile.h @@ -7,33 +7,34 @@ class Random; class Level; class ChunkRebuildData; -class CactusTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class CactusTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; private: - Icon *iconTop; - Icon *iconBottom; + Icon* iconTop; + Icon* iconBottom; protected: - CactusTile(int id); + CactusTile(int id); public: - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual Icon *getTexture(int face, int data); - virtual bool isCubeShaped(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual int getRenderShape(); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual bool canSurvive(Level *level, int x, int y, int z); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - //@Override - void registerIcons(IconRegister *iconRegister); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual Icon* getTexture(int face, int data); + virtual bool isCubeShaped(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual int getRenderShape(); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual bool canSurvive(Level* level, int x, int y, int z); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + //@Override + void registerIcons(IconRegister* iconRegister); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CakeTile.cpp b/Minecraft.World/Blocks/CakeTile.cpp index 48ebb85de..faafa0118 100644 --- a/Minecraft.World/Blocks/CakeTile.cpp +++ b/Minecraft.World/Blocks/CakeTile.cpp @@ -8,17 +8,18 @@ #include "../Headers/net.minecraft.h" #include "CakeTile.h" +CakeTile::CakeTile(int id) : Tile(id, Material::cake, false) { + setTicking(true); -CakeTile::CakeTile(int id) : Tile(id, Material::cake, false) -{ - setTicking(true); - - iconTop = NULL; - iconBottom = NULL; - iconInner = NULL; + iconTop = NULL; + iconBottom = NULL; + iconInner = NULL; } -void CakeTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void CakeTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { int d = level->getData(x, y, z); float r = 1 / 16.0f; @@ -27,15 +28,13 @@ void CakeTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat this->setShape(r2, 0, r, 1 - r, h, 1 - r); } -void CakeTile::updateDefaultShape() -{ +void CakeTile::updateDefaultShape() { float r = 1 / 16.0f; float h = 8 / 16.0f; this->setShape(r, 0, r, 1 - r, h, 1 - r); } -AABB *CakeTile::getAABB(Level *level, int x, int y, int z) -{ +AABB* CakeTile::getAABB(Level* level, int x, int y, int z) { int d = level->getData(x, y, z); float r = 1 / 16.0f; float r2 = (1 + d * 2) / 16.0f; @@ -43,8 +42,7 @@ AABB *CakeTile::getAABB(Level *level, int x, int y, int z) return AABB::newTemp(x + r2, y, z + r, x + 1 - r, y + h - r, z + 1 - r); } -AABB *CakeTile::getTileAABB(Level *level, int x, int y, int z) -{ +AABB* CakeTile::getTileAABB(Level* level, int x, int y, int z) { int d = level->getData(x, y, z); float r = 1 / 16.0f; float r2 = (1 + d * 2) / 16.0f; @@ -52,100 +50,80 @@ AABB *CakeTile::getTileAABB(Level *level, int x, int y, int z) return AABB::newTemp(x + r2, y, z + r, x + 1 - r, y + h, z + 1 - r); } -Icon *CakeTile::getTexture(int face, int data) -{ +Icon* CakeTile::getTexture(int face, int data) { if (face == Facing::UP) return iconTop; if (face == Facing::DOWN) return iconBottom; if (data > 0 && face == Facing::WEST) return iconInner; return icon; } -void CakeTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"cake_side"); - iconInner = iconRegister->registerIcon(L"cake_inner"); - iconTop = iconRegister->registerIcon(L"cake_top"); - iconBottom = iconRegister->registerIcon(L"cake_bottom"); +void CakeTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"cake_side"); + iconInner = iconRegister->registerIcon(L"cake_inner"); + iconTop = iconRegister->registerIcon(L"cake_top"); + iconBottom = iconRegister->registerIcon(L"cake_bottom"); } -bool CakeTile::isCubeShaped() -{ - return false; -} +bool CakeTile::isCubeShaped() { return false; } -bool CakeTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool CakeTile::isSolidRender(bool isServerLevel) { return false; } // 4J-PB - Adding a TestUse for tooltip display -bool CakeTile::TestUse() -{ - return true; -} +bool CakeTile::TestUse() { return true; } -bool CakeTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool CakeTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly ) return false; + if (soundOnly) return false; eat(level, x, y, z, player); return true; } -void CakeTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - eat(level, x, y, z, player); +void CakeTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + eat(level, x, y, z, player); } -void CakeTile::eat(Level *level, int x, int y, int z, std::shared_ptr player) -{ - if (player->canEat(false)) - { +void CakeTile::eat(Level* level, int x, int y, int z, + std::shared_ptr player) { + if (player->canEat(false)) { player->getFoodData()->eat(2, FoodConstants::FOOD_SATURATION_POOR); int d = level->getData(x, y, z) + 1; - if (d >= 6) - { + if (d >= 6) { level->setTile(x, y, z, 0); - } else - { + } else { level->setData(x, y, z, d); level->setTileDirty(x, y, z); } } } -bool CakeTile::mayPlace(Level *level, int x, int y, int z) -{ +bool CakeTile::mayPlace(Level* level, int x, int y, int z) { if (!Tile::mayPlace(level, x, y, z)) return false; return canSurvive(level, x, y, z); } -void CakeTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!canSurvive(level, x, y, z)) - { +void CakeTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!canSurvive(level, x, y, z)) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); - } + } } -bool CakeTile::canSurvive(Level *level, int x, int y, int z) -{ - return level->getMaterial(x, y - 1, z)->isSolid(); +bool CakeTile::canSurvive(Level* level, int x, int y, int z) { + return level->getMaterial(x, y - 1, z)->isSolid(); } -int CakeTile::getResourceCount(Random *random) -{ - return 0; +int CakeTile::getResourceCount(Random* random) { return 0; } + +int CakeTile::getResource(int data, Random* random, int playerBonusLevel) { + return 0; } -int CakeTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; -} - -int CakeTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::cake_Id; +int CakeTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::cake_Id; } diff --git a/Minecraft.World/Blocks/CakeTile.h b/Minecraft.World/Blocks/CakeTile.h index b6f6bf84d..4f201e0a0 100644 --- a/Minecraft.World/Blocks/CakeTile.h +++ b/Minecraft.World/Blocks/CakeTile.h @@ -8,37 +8,45 @@ class Random; class Level; class ChunkRebuildData; -class CakeTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class CakeTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; private: - Icon *iconTop; - Icon *iconBottom; - Icon *iconInner; + Icon* iconTop; + Icon* iconBottom; + Icon* iconInner; protected: - CakeTile(int id); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + CakeTile(int id); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param virtual void updateDefaultShape(); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual Icon *getTexture(int face, int data); - //@Override - void registerIcons(IconRegister *iconRegister); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual Icon* getTexture(int face, int data); + //@Override + void registerIcons(IconRegister* iconRegister); virtual bool isCubeShaped(); virtual bool isSolidRender(bool isServerLevel = false); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + private: - void eat(Level *level, int x, int y, int z, std::shared_ptr player); + void eat(Level* level, int x, int y, int z, std::shared_ptr player); + public: - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual bool canSurvive(Level *level, int x, int y, int z); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - int cloneTileId(Level *level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual bool canSurvive(Level* level, int x, int y, int z); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + int cloneTileId(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CarrotTile.cpp b/Minecraft.World/Blocks/CarrotTile.cpp index 5b90cee52..300e14711 100644 --- a/Minecraft.World/Blocks/CarrotTile.cpp +++ b/Minecraft.World/Blocks/CarrotTile.cpp @@ -3,40 +3,25 @@ #include "../Headers/net.minecraft.world.item.h" #include "CarrotTile.h" -CarrotTile::CarrotTile(int id) : CropTile(id) -{ +CarrotTile::CarrotTile(int id) : CropTile(id) {} + +Icon* CarrotTile::getTexture(int face, int data) { + if (data < 7) { + if (data == 6) { + data = 5; + } + return icons[data >> 1]; + } else { + return icons[3]; + } } -Icon *CarrotTile::getTexture(int face, int data) -{ - if (data < 7) - { - if (data == 6) - { - data = 5; - } - return icons[data >> 1]; - } - else - { - return icons[3]; - } -} +int CarrotTile::getBaseSeedId() { return Item::carrots_Id; } -int CarrotTile::getBaseSeedId() -{ - return Item::carrots_Id; -} +int CarrotTile::getBasePlantId() { return Item::carrots_Id; } -int CarrotTile::getBasePlantId() -{ - return Item::carrots_Id; -} - -void CarrotTile::registerIcons(IconRegister *iconRegister) -{ - for (int i = 0; i < 4; i++) - { - icons[i] = iconRegister->registerIcon(L"carrots_" + _toString(i)); - } +void CarrotTile::registerIcons(IconRegister* iconRegister) { + for (int i = 0; i < 4; i++) { + icons[i] = iconRegister->registerIcon(L"carrots_" + _toString(i)); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/CarrotTile.h b/Minecraft.World/Blocks/CarrotTile.h index 82c1c02bd..4fa96b732 100644 --- a/Minecraft.World/Blocks/CarrotTile.h +++ b/Minecraft.World/Blocks/CarrotTile.h @@ -2,20 +2,21 @@ #include "CropTile.h" -class CarrotTile : public CropTile -{ - friend class ChunkRebuildData; -private: - Icon *icons[4]; -public: - CarrotTile(int id); +class CarrotTile : public CropTile { + friend class ChunkRebuildData; - Icon *getTexture(int face, int data); +private: + Icon* icons[4]; + +public: + CarrotTile(int id); + + Icon* getTexture(int face, int data); protected: - int getBaseSeedId(); - int getBasePlantId(); + int getBaseSeedId(); + int getBasePlantId(); public: - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CauldronTile.cpp b/Minecraft.World/Blocks/CauldronTile.cpp index 7b664b16f..6ccd67813 100644 --- a/Minecraft.World/Blocks/CauldronTile.cpp +++ b/Minecraft.World/Blocks/CauldronTile.cpp @@ -11,43 +11,37 @@ const std::wstring CauldronTile::TEXTURE_INSIDE = L"cauldron_inner"; const std::wstring CauldronTile::TEXTURE_BOTTOM = L"cauldron_bottom"; -CauldronTile::CauldronTile(int id) : Tile(id, Material::metal, false) -{ +CauldronTile::CauldronTile(int id) : Tile(id, Material::metal, false) { iconInner = NULL; iconTop = NULL; iconBottom = NULL; } -Icon *CauldronTile::getTexture(int face, int data) -{ - if (face == Facing::UP) - { - return iconTop; - } - if (face == Facing::DOWN) - { - return iconBottom; - } - return icon; +Icon* CauldronTile::getTexture(int face, int data) { + if (face == Facing::UP) { + return iconTop; + } + if (face == Facing::DOWN) { + return iconBottom; + } + return icon; } -void CauldronTile::registerIcons(IconRegister *iconRegister) -{ - iconInner = iconRegister->registerIcon(L"cauldron_inner"); - iconTop = iconRegister->registerIcon(L"cauldron_top"); - iconBottom = iconRegister->registerIcon(L"cauldron_bottom"); - icon = iconRegister->registerIcon(L"cauldron_side"); +void CauldronTile::registerIcons(IconRegister* iconRegister) { + iconInner = iconRegister->registerIcon(L"cauldron_inner"); + iconTop = iconRegister->registerIcon(L"cauldron_top"); + iconBottom = iconRegister->registerIcon(L"cauldron_bottom"); + icon = iconRegister->registerIcon(L"cauldron_side"); } -Icon *CauldronTile::getTexture(const std::wstring &name) -{ - if (name.compare(TEXTURE_INSIDE) == 0) return Tile::cauldron->iconInner; - if (name.compare(TEXTURE_BOTTOM) == 0) return Tile::cauldron->iconBottom; - return NULL; +Icon* CauldronTile::getTexture(const std::wstring& name) { + if (name.compare(TEXTURE_INSIDE) == 0) return Tile::cauldron->iconInner; + if (name.compare(TEXTURE_BOTTOM) == 0) return Tile::cauldron->iconBottom; + return NULL; } -void CauldronTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ +void CauldronTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { setShape(0, 0, 0, 1, 5.0f / 16.0f, 1); Tile::addAABBs(level, x, y, z, box, boxes, source); float thickness = 2.0f / 16.0f; @@ -63,115 +57,95 @@ void CauldronTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBLi updateDefaultShape(); } -void CauldronTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 1, 1); -} +void CauldronTile::updateDefaultShape() { setShape(0, 0, 0, 1, 1, 1); } -bool CauldronTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool CauldronTile::isSolidRender(bool isServerLevel) { return false; } -int CauldronTile::getRenderShape() -{ - return SHAPE_CAULDRON; -} +int CauldronTile::getRenderShape() { return SHAPE_CAULDRON; } -bool CauldronTile::isCubeShaped() -{ - return false; -} +bool CauldronTile::isCubeShaped() { return false; } -bool CauldronTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool CauldronTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if(soundOnly) return false; + if (soundOnly) return false; - if (level->isClientSide) - { + if (level->isClientSide) { return true; } std::shared_ptr item = player->inventory->getSelected(); - if (item == NULL) - { + if (item == NULL) { return true; } int currentData = level->getData(x, y, z); - if (item->id == Item::bucket_water_Id) - { - if (currentData < 3) - { - if (!player->abilities.instabuild) - { - player->inventory->setItem(player->inventory->selected, std::shared_ptr(new ItemInstance(Item::bucket_empty))); + if (item->id == Item::bucket_water_Id) { + if (currentData < 3) { + if (!player->abilities.instabuild) { + player->inventory->setItem( + player->inventory->selected, + std::shared_ptr( + new ItemInstance(Item::bucket_empty))); } level->setData(x, y, z, 3); } return true; - } - else if (item->id == Item::glassBottle_Id) - { - if (currentData > 0) - { - std::shared_ptr potion = std::shared_ptr(new ItemInstance(Item::potion, 1, 0)); - if (!player->inventory->add(potion)) - { - level->addEntity(std::shared_ptr(new ItemEntity(level, x + 0.5, y + 1.5, z + 0.5, potion))); + } else if (item->id == Item::glassBottle_Id) { + if (currentData > 0) { + std::shared_ptr potion = + std::shared_ptr( + new ItemInstance(Item::potion, 1, 0)); + if (!player->inventory->add(potion)) { + level->addEntity(std::shared_ptr( + new ItemEntity(level, x + 0.5, y + 1.5, z + 0.5, potion))); + } + // 4J Stu - Brought forward change to update inventory when filling + // bottles with water + else if (std::dynamic_pointer_cast(player) != NULL) { + std::dynamic_pointer_cast(player) + ->refreshContainer(player->inventoryMenu); + } + // 4J-PB - don't lose the water in creative mode + if (player->abilities.instabuild == false) { + item->count--; + if (item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } } - // 4J Stu - Brought forward change to update inventory when filling bottles with water - else if (std::dynamic_pointer_cast( player ) != NULL) - { - std::dynamic_pointer_cast( player )->refreshContainer(player->inventoryMenu); - } - // 4J-PB - don't lose the water in creative mode - if (player->abilities.instabuild==false) - { - item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } level->setData(x, y, z, currentData - 1); } - } - else if (currentData > 0) - { - ArmorItem *armor = dynamic_cast(item->getItem()); - if(armor && armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) - { - armor->clearColor(item); - level->setData(x, y, z, currentData - 1); - return true; - } - } + } else if (currentData > 0) { + ArmorItem* armor = dynamic_cast(item->getItem()); + if (armor && armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) { + armor->clearColor(item); + level->setData(x, y, z, currentData - 1); + return true; + } + } return true; - } -void CauldronTile::handleRain(Level *level, int x, int y, int z) -{ - if (level->random->nextInt(20) != 1) return; +void CauldronTile::handleRain(Level* level, int x, int y, int z) { + if (level->random->nextInt(20) != 1) return; - int data = level->getData(x, y, z); + int data = level->getData(x, y, z); - if (data < 3) - { - level->setData(x, y, z, data + 1); - } + if (data < 3) { + level->setData(x, y, z, data + 1); + } } -int CauldronTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::cauldron_Id; +int CauldronTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::cauldron_Id; } -int CauldronTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::cauldron_Id; +int CauldronTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::cauldron_Id; } diff --git a/Minecraft.World/Blocks/CauldronTile.h b/Minecraft.World/Blocks/CauldronTile.h index 804a33450..9609171ff 100644 --- a/Minecraft.World/Blocks/CauldronTile.h +++ b/Minecraft.World/Blocks/CauldronTile.h @@ -3,31 +3,34 @@ class IconRegister; -class CauldronTile : public Tile -{ +class CauldronTile : public Tile { public: - static const std::wstring TEXTURE_INSIDE; + static const std::wstring TEXTURE_INSIDE; static const std::wstring TEXTURE_BOTTOM; private: - Icon *iconInner; - Icon *iconTop; - Icon *iconBottom; + Icon* iconInner; + Icon* iconTop; + Icon* iconBottom; public: - CauldronTile(int id); - using Tile::getTexture; - virtual Icon *getTexture(int face, int data); - //@Override - void registerIcons(IconRegister *iconRegister); - static Icon *getTexture(const std::wstring &name); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual void updateDefaultShape(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual int getRenderShape(); - virtual bool isCubeShaped(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void handleRain(Level *level, int x, int y, int z); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); + CauldronTile(int id); + using Tile::getTexture; + virtual Icon* getTexture(int face, int data); + //@Override + void registerIcons(IconRegister* iconRegister); + static Icon* getTexture(const std::wstring& name); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual void updateDefaultShape(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual int getRenderShape(); + virtual bool isCubeShaped(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void handleRain(Level* level, int x, int y, int z); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/ChestTile.cpp b/Minecraft.World/Blocks/ChestTile.cpp index 1f4a87570..00249f673 100644 --- a/Minecraft.World/Blocks/ChestTile.cpp +++ b/Minecraft.World/Blocks/ChestTile.cpp @@ -10,78 +10,56 @@ #include "../Util/Facing.h" #include "../Entities/Mobs/Ocelot.h" -ChestTile::ChestTile(int id) : EntityTile(id, Material::wood, false) -{ - random = new Random(); +ChestTile::ChestTile(int id) : EntityTile(id, Material::wood, false) { + random = new Random(); - setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); + setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); } -ChestTile::~ChestTile() -{ - delete random; +ChestTile::~ChestTile() { delete random; } + +bool ChestTile::isSolidRender(bool isServerLevel) { return false; } + +bool ChestTile::isCubeShaped() { return false; } + +int ChestTile::getRenderShape() { return Tile::SHAPE_ENTITYTILE_ANIMATED; } + +void ChestTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + if (level->getTile(x, y, z - 1) == id) { + setShape(1 / 16.0f, 0, 0, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); + } else if (level->getTile(x, y, z + 1) == id) { + setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 1); + } else if (level->getTile(x - 1, y, z) == id) { + setShape(0, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); + } else if (level->getTile(x + 1, y, z) == id) { + setShape(1 / 16.0f, 0, 1 / 16.0f, 1, 14 / 16.0f, 15 / 16.0f); + } else { + setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); + } } -bool ChestTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -bool ChestTile::isCubeShaped() -{ - return false; -} - -int ChestTile::getRenderShape() -{ - return Tile::SHAPE_ENTITYTILE_ANIMATED; -} - -void ChestTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - if (level->getTile(x, y, z - 1) == id) - { - setShape(1 / 16.0f, 0, 0, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); - } - else if (level->getTile(x, y, z + 1) == id) - { - setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 1); - } - else if (level->getTile(x - 1, y, z) == id) - { - setShape(0, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); - } - else if (level->getTile(x + 1, y, z) == id) - { - setShape(1 / 16.0f, 0, 1 / 16.0f, 1, 14 / 16.0f, 15 / 16.0f); - } - else - { - setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); - } -} - -void ChestTile::onPlace(Level *level, int x, int y, int z) -{ +void ChestTile::onPlace(Level* level, int x, int y, int z) { EntityTile::onPlace(level, x, y, z); recalcLockDir(level, x, y, z); - int n = level->getTile(x, y, z - 1); // face = 2 - int s = level->getTile(x, y, z + 1); // face = 3 - int w = level->getTile(x - 1, y, z); // face = 4 - int e = level->getTile(x + 1, y, z); // face = 5 + int n = level->getTile(x, y, z - 1); // face = 2 + int s = level->getTile(x, y, z + 1); // face = 3 + int w = level->getTile(x - 1, y, z); // face = 4 + int e = level->getTile(x + 1, y, z); // face = 5 if (n == id) recalcLockDir(level, x, y, z - 1); if (s == id) recalcLockDir(level, x, y, z + 1); if (w == id) recalcLockDir(level, x - 1, y, z); if (e == id) recalcLockDir(level, x + 1, y, z); } -void ChestTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int n = level->getTile(x, y, z - 1); // face = 2 - int s = level->getTile(x, y, z + 1); // face = 3 - int w = level->getTile(x - 1, y, z); // face = 4 - int e = level->getTile(x + 1, y, z); // face = 5 +void ChestTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int n = level->getTile(x, y, z - 1); // face = 2 + int s = level->getTile(x, y, z + 1); // face = 3 + int w = level->getTile(x - 1, y, z); // face = 4 + int e = level->getTile(x + 1, y, z); // face = 5 int facing = 0; int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; @@ -91,73 +69,78 @@ void ChestTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptrsetData(x, y, z, facing); - } - else - { - if ((n == id || s == id) && (facing == Facing::WEST || facing == Facing::EAST)) - { - if (n == id) level->setData(x, y, z - 1, facing); - else level->setData(x, y, z + 1, facing); + } else { + if ((n == id || s == id) && + (facing == Facing::WEST || facing == Facing::EAST)) { + if (n == id) + level->setData(x, y, z - 1, facing); + else + level->setData(x, y, z + 1, facing); level->setData(x, y, z, facing); } - if ((w == id || e == id) && (facing == Facing::NORTH || facing == Facing::SOUTH)) - { - if (w == id) level->setData(x - 1, y, z, facing); - else level->setData(x + 1, y, z, facing); + if ((w == id || e == id) && + (facing == Facing::NORTH || facing == Facing::SOUTH)) { + if (w == id) + level->setData(x - 1, y, z, facing); + else + level->setData(x + 1, y, z, facing); level->setData(x, y, z, facing); } } - } -void ChestTile::recalcLockDir(Level *level, int x, int y, int z) -{ - if (level->isClientSide) - { +void ChestTile::recalcLockDir(Level* level, int x, int y, int z) { + if (level->isClientSide) { return; } - int n = level->getTile(x, y, z - 1); // face = 2 - int s = level->getTile(x, y, z + 1); // face = 3 - int w = level->getTile(x - 1, y, z); // face = 4 - int e = level->getTile(x + 1, y, z); // face = 5 + int n = level->getTile(x, y, z - 1); // face = 2 + int s = level->getTile(x, y, z + 1); // face = 3 + int w = level->getTile(x - 1, y, z); // face = 4 + int e = level->getTile(x + 1, y, z); // face = 5 // Long! int lockDir = 4; - if (n == id || s == id) - { + if (n == id || s == id) { int w2 = level->getTile(x - 1, y, n == id ? z - 1 : z + 1); int e2 = level->getTile(x + 1, y, n == id ? z - 1 : z + 1); lockDir = 5; int otherDir = -1; - if (n == id) otherDir = level->getData(x, y, z - 1); - else otherDir = level->getData(x, y, z + 1); + if (n == id) + otherDir = level->getData(x, y, z - 1); + else + otherDir = level->getData(x, y, z + 1); if (otherDir == 4) lockDir = 4; - if ((Tile::solid[w] || Tile::solid[w2]) && !Tile::solid[e] && !Tile::solid[e2]) lockDir = 5; - if ((Tile::solid[e] || Tile::solid[e2]) && !Tile::solid[w] && !Tile::solid[w2]) lockDir = 4; - } - else if (w == id || e == id) - { + if ((Tile::solid[w] || Tile::solid[w2]) && !Tile::solid[e] && + !Tile::solid[e2]) + lockDir = 5; + if ((Tile::solid[e] || Tile::solid[e2]) && !Tile::solid[w] && + !Tile::solid[w2]) + lockDir = 4; + } else if (w == id || e == id) { int n2 = level->getTile(w == id ? x - 1 : x + 1, y, z - 1); int s2 = level->getTile(w == id ? x - 1 : x + 1, y, z + 1); lockDir = 3; int otherDir = -1; - if (w == id) otherDir = level->getData(x - 1, y, z); - else otherDir = level->getData(x + 1, y, z); + if (w == id) + otherDir = level->getData(x - 1, y, z); + else + otherDir = level->getData(x + 1, y, z); if (otherDir == 2) lockDir = 2; - if ((Tile::solid[n] || Tile::solid[n2]) && !Tile::solid[s] && !Tile::solid[s2]) lockDir = 3; - if ((Tile::solid[s] || Tile::solid[s2]) && !Tile::solid[n] && !Tile::solid[n2]) lockDir = 2; - } - else - { + if ((Tile::solid[n] || Tile::solid[n2]) && !Tile::solid[s] && + !Tile::solid[s2]) + lockDir = 3; + if ((Tile::solid[s] || Tile::solid[s2]) && !Tile::solid[n] && + !Tile::solid[n2]) + lockDir = 2; + } else { lockDir = 3; if (Tile::solid[n] && !Tile::solid[s]) lockDir = 3; if (Tile::solid[s] && !Tile::solid[n]) lockDir = 2; @@ -168,8 +151,7 @@ void ChestTile::recalcLockDir(Level *level, int x, int y, int z) level->setData(x, y, z, lockDir); } -bool ChestTile::mayPlace(Level *level, int x, int y, int z) -{ +bool ChestTile::mayPlace(Level* level, int x, int y, int z) { int chestCount = 0; if (level->getTile(x - 1, y, z) == id) chestCount++; @@ -184,11 +166,9 @@ bool ChestTile::mayPlace(Level *level, int x, int y, int z) if (isFullChest(level, x, y, z - 1)) return false; if (isFullChest(level, x, y, z + 1)) return false; return true; - } -bool ChestTile::isFullChest(Level *level, int x, int y, int z) -{ +bool ChestTile::isFullChest(Level* level, int x, int y, int z) { if (level->getTile(x, y, z) != id) return false; if (level->getTile(x - 1, y, z) == id) return true; if (level->getTile(x + 1, y, z) == id) return true; @@ -197,87 +177,120 @@ bool ChestTile::isFullChest(Level *level, int x, int y, int z) return false; } -void ChestTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void ChestTile::neighborChanged(Level* level, int x, int y, int z, int type) { EntityTile::neighborChanged(level, x, y, z, type); - std::shared_ptr(cte) = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); + std::shared_ptr(cte) = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); if (cte != NULL) cte->clearCache(); } -void ChestTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - std::shared_ptr container = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (container != NULL ) - { - for (unsigned int i = 0; i < container->getContainerSize(); i++) - { - std::shared_ptr item = container->getItem(i); - if (item != NULL) - { - float xo = random->nextFloat() * 0.8f + 0.1f; - float yo = random->nextFloat() * 0.8f + 0.1f; - float zo = random->nextFloat() * 0.8f + 0.1f; +void ChestTile::onRemove(Level* level, int x, int y, int z, int id, int data) { + std::shared_ptr container = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (container != NULL) { + for (unsigned int i = 0; i < container->getContainerSize(); i++) { + std::shared_ptr item = container->getItem(i); + if (item != NULL) { + float xo = random->nextFloat() * 0.8f + 0.1f; + float yo = random->nextFloat() * 0.8f + 0.1f; + float zo = random->nextFloat() * 0.8f + 0.1f; - while (item->count > 0) - { - int count = random->nextInt(21) + 10; - if (count > item->count) count = item->count; - item->count -= count; + while (item->count > 0) { + int count = random->nextInt(21) + 10; + if (count > item->count) count = item->count; + item->count -= count; - std::shared_ptr newItem = std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue()) ); - newItem->set4JData( item->get4JData() ); - std::shared_ptr itemEntity = std::shared_ptr(new ItemEntity(level, x + xo, y + yo, z + zo, newItem ) ); - float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); + std::shared_ptr newItem = + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())); + newItem->set4JData(item->get4JData()); + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, newItem)); + float pow = 0.05f; + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); } - level->addEntity(itemEntity); - } + level->addEntity(itemEntity); + } - // 4J Stu - Fix for duplication glitch - container->setItem(i,nullptr); - } - } - } + // 4J Stu - Fix for duplication glitch + container->setItem(i, nullptr); + } + } + } EntityTile::onRemove(level, x, y, z, id, data); } // 4J-PB - Adding a TestUse for tooltip display -bool ChestTile::TestUse() -{ - return true; -} +bool ChestTile::TestUse() { return true; } // 4J-PB - changing to 1.5 equivalent -bool ChestTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool ChestTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly ) return true; + if (soundOnly) return true; - if (level->isClientSide) - { + if (level->isClientSide) { return true; } - std::shared_ptr container = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (container == NULL) return true; + std::shared_ptr container = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (container == NULL) return true; - if (level->isSolidBlockingTile(x, y + 1, z)) return true; - if (isCatSittingOnChest(level,x, y, z)) return true; + if (level->isSolidBlockingTile(x, y + 1, z)) return true; + if (isCatSittingOnChest(level, x, y, z)) return true; - if (level->getTile(x - 1, y, z) == id && (level->isSolidBlockingTile(x - 1, y + 1, z) || isCatSittingOnChest(level, x - 1, y, z))) return true; - if (level->getTile(x + 1, y, z) == id && (level->isSolidBlockingTile(x + 1, y + 1, z) || isCatSittingOnChest(level, x + 1, y, z))) return true; - if (level->getTile(x, y, z - 1) == id && (level->isSolidBlockingTile(x, y + 1, z - 1) || isCatSittingOnChest(level, x, y, z - 1))) return true; - if (level->getTile(x, y, z + 1) == id && (level->isSolidBlockingTile(x, y + 1, z + 1) || isCatSittingOnChest(level, x, y, z + 1))) return true; + if (level->getTile(x - 1, y, z) == id && + (level->isSolidBlockingTile(x - 1, y + 1, z) || + isCatSittingOnChest(level, x - 1, y, z))) + return true; + if (level->getTile(x + 1, y, z) == id && + (level->isSolidBlockingTile(x + 1, y + 1, z) || + isCatSittingOnChest(level, x + 1, y, z))) + return true; + if (level->getTile(x, y, z - 1) == id && + (level->isSolidBlockingTile(x, y + 1, z - 1) || + isCatSittingOnChest(level, x, y, z - 1))) + return true; + if (level->getTile(x, y, z + 1) == id && + (level->isSolidBlockingTile(x, y + 1, z + 1) || + isCatSittingOnChest(level, x, y, z + 1))) + return true; - if (level->getTile(x - 1, y, z) == id) container = std::shared_ptr( new CompoundContainer(IDS_CHEST_LARGE, std::dynamic_pointer_cast( level->getTileEntity(x - 1, y, z) ), container) ); - if (level->getTile(x + 1, y, z) == id) container = std::shared_ptr( new CompoundContainer(IDS_CHEST_LARGE, container, std::dynamic_pointer_cast( level->getTileEntity(x + 1, y, z) )) ); - if (level->getTile(x, y, z - 1) == id) container = std::shared_ptr( new CompoundContainer(IDS_CHEST_LARGE, std::dynamic_pointer_cast( level->getTileEntity(x, y, z - 1) ), container) ); - if (level->getTile(x, y, z + 1) == id) container = std::shared_ptr( new CompoundContainer(IDS_CHEST_LARGE, container, std::dynamic_pointer_cast( level->getTileEntity(x, y, z + 1) )) ); + if (level->getTile(x - 1, y, z) == id) + container = std::shared_ptr( + new CompoundContainer(IDS_CHEST_LARGE, + std::dynamic_pointer_cast( + level->getTileEntity(x - 1, y, z)), + container)); + if (level->getTile(x + 1, y, z) == id) + container = std::shared_ptr( + new CompoundContainer(IDS_CHEST_LARGE, container, + std::dynamic_pointer_cast( + level->getTileEntity(x + 1, y, z)))); + if (level->getTile(x, y, z - 1) == id) + container = std::shared_ptr( + new CompoundContainer(IDS_CHEST_LARGE, + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z - 1)), + container)); + if (level->getTile(x, y, z + 1) == id) + container = std::shared_ptr( + new CompoundContainer(IDS_CHEST_LARGE, container, + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z + 1)))); player->openContainer(container); @@ -285,32 +298,29 @@ bool ChestTile::use(Level *level, int x, int y, int z, std::shared_ptr p } // 4J-PB - added from 1.5 -bool ChestTile::isCatSittingOnChest(Level *level, int x, int y, int z) -{ - std::vector > *entities = level->getEntitiesOfClass(typeid(Ozelot), AABB::newTemp(x, y + 1, z, x + 1, y + 2, z + 1)); - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - std::shared_ptr ocelot = std::dynamic_pointer_cast(*it); - if(ocelot->isSitting()) - { - return true; - } - } +bool ChestTile::isCatSittingOnChest(Level* level, int x, int y, int z) { + std::vector >* entities = level->getEntitiesOfClass( + typeid(Ozelot), AABB::newTemp(x, y + 1, z, x + 1, y + 2, z + 1)); + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + std::shared_ptr ocelot = std::dynamic_pointer_cast(*it); + if (ocelot->isSitting()) { + return true; + } + } - return false; + return false; } -std::shared_ptr ChestTile::newTileEntity(Level *level) -{ - MemSect(50); - std::shared_ptr retval = std::shared_ptr( new ChestTileEntity() ); - MemSect(0); - return retval; +std::shared_ptr ChestTile::newTileEntity(Level* level) { + MemSect(50); + std::shared_ptr retval = + std::shared_ptr(new ChestTileEntity()); + MemSect(0); + return retval; } -void ChestTile::registerIcons(IconRegister *iconRegister) -{ - // Register wood as the chest's icon, because it's used by the particles - // when destroying the chest - icon = iconRegister->registerIcon(L"wood"); +void ChestTile::registerIcons(IconRegister* iconRegister) { + // Register wood as the chest's icon, because it's used by the particles + // when destroying the chest + icon = iconRegister->registerIcon(L"wood"); } diff --git a/Minecraft.World/Blocks/ChestTile.h b/Minecraft.World/Blocks/ChestTile.h index eae9821a1..e42d21508 100644 --- a/Minecraft.World/Blocks/ChestTile.h +++ b/Minecraft.World/Blocks/ChestTile.h @@ -5,34 +5,46 @@ class Player; class Random; -class ChestTile : public EntityTile -{ - friend class Tile; +class ChestTile : public EntityTile { + friend class Tile; + public: - static const int EVENT_SET_OPEN_COUNT = 1; + static const int EVENT_SET_OPEN_COUNT = 1; + private: - Random *random; + Random* random; + protected: - ChestTile(int id); - ~ChestTile(); + ChestTile(int id); + ~ChestTile(); + public: - virtual bool isSolidRender(bool isServerLevel = false); - virtual bool isCubeShaped(); - virtual int getRenderShape(); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity = std::shared_ptr()); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - void recalcLockDir(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z); + virtual bool isSolidRender(bool isServerLevel = false); + virtual bool isCubeShaped(); + virtual int getRenderShape(); + virtual void updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity = + std::shared_ptr()); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + void recalcLockDir(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z); + private: - bool isFullChest(Level *level, int x, int y, int z); - bool isCatSittingOnChest(Level *level, int x, int y, int z); + bool isFullChest(Level* level, int x, int y, int z); + bool isCatSittingOnChest(Level* level, int x, int y, int z); + public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - std::shared_ptr newTileEntity(Level *level); - //@Override - void registerIcons(IconRegister *iconRegister); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + std::shared_ptr newTileEntity(Level* level); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/ClayTile.cpp b/Minecraft.World/Blocks/ClayTile.cpp index 871d468d5..b52ecefdb 100644 --- a/Minecraft.World/Blocks/ClayTile.cpp +++ b/Minecraft.World/Blocks/ClayTile.cpp @@ -2,16 +2,10 @@ #include "ClayTile.h" #include "../Headers/net.minecraft.world.item.h" -ClayTile::ClayTile(int id) : Tile(id, Material::clay) -{ +ClayTile::ClayTile(int id) : Tile(id, Material::clay) {} + +int ClayTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::clay->id; } -int ClayTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::clay->id; -} - -int ClayTile::getResourceCount(Random *random) -{ - return 4; -} +int ClayTile::getResourceCount(Random* random) { return 4; } diff --git a/Minecraft.World/Blocks/ClayTile.h b/Minecraft.World/Blocks/ClayTile.h index a2d9422ac..8395fa325 100644 --- a/Minecraft.World/Blocks/ClayTile.h +++ b/Minecraft.World/Blocks/ClayTile.h @@ -4,10 +4,9 @@ class Random; -class ClayTile : public Tile -{ +class ClayTile : public Tile { public: ClayTile(int id); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/ClothTile.cpp b/Minecraft.World/Blocks/ClothTile.cpp index 79e6a6df5..66c441858 100644 --- a/Minecraft.World/Blocks/ClothTile.cpp +++ b/Minecraft.World/Blocks/ClothTile.cpp @@ -2,37 +2,22 @@ #include "../Headers/net.minecraft.world.h" #include "ClothTile.h" -ClothTile::ClothTile() : Tile(35, Material::cloth) -{ - icons = NULL; +ClothTile::ClothTile() : Tile(35, Material::cloth) { icons = NULL; } + +Icon* ClothTile::getTexture(int face, int data) { return icons[data]; } + +int ClothTile::getSpawnResourcesAuxValue(int data) { return data; } + +int ClothTile::getTileDataForItemAuxValue(int auxValue) { + return (~auxValue & 0xf); } -Icon *ClothTile::getTexture(int face, int data) -{ - return icons[data]; -} +int ClothTile::getItemAuxValueForTileData(int data) { return (~data & 0xf); } -int ClothTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} +void ClothTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[16]; -int ClothTile::getTileDataForItemAuxValue(int auxValue) -{ - return (~auxValue & 0xf); -} - -int ClothTile::getItemAuxValueForTileData(int data) -{ - return (~data & 0xf); -} - -void ClothTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[16]; - - for (int i = 0; i < 16; i++) - { - icons[i] = iconRegister->registerIcon(L"cloth_" + _toString(i) ); - } + for (int i = 0; i < 16; i++) { + icons[i] = iconRegister->registerIcon(L"cloth_" + _toString(i)); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/ClothTile.h b/Minecraft.World/Blocks/ClothTile.h index 72a74a272..e8fd0b5b7 100644 --- a/Minecraft.World/Blocks/ClothTile.h +++ b/Minecraft.World/Blocks/ClothTile.h @@ -4,19 +4,22 @@ class ChunkRebuildData; -class ClothTile : public Tile -{ - friend class ChunkRebuildData; +class ClothTile : public Tile { + friend class ChunkRebuildData; + private: - Icon **icons; + Icon** icons; + public: - ClothTile(); - virtual Icon *getTexture(int face, int data); + ClothTile(); + virtual Icon* getTexture(int face, int data); + protected: - virtual int getSpawnResourcesAuxValue(int data); + virtual int getSpawnResourcesAuxValue(int data); + public: static int getTileDataForItemAuxValue(int auxValue); static int getItemAuxValueForTileData(int data); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CocoaTile.cpp b/Minecraft.World/Blocks/CocoaTile.cpp index 126994b7f..d58c70d17 100644 --- a/Minecraft.World/Blocks/CocoaTile.cpp +++ b/Minecraft.World/Blocks/CocoaTile.cpp @@ -6,171 +6,153 @@ #include "../Headers/net.minecraft.h" #include "CocoaTile.h" -const std::wstring CocoaTile::TEXTURE_AGES[] = { L"cocoa_0", L"cocoa_1", L"cocoa_2"}; +const std::wstring CocoaTile::TEXTURE_AGES[] = {L"cocoa_0", L"cocoa_1", + L"cocoa_2"}; -CocoaTile::CocoaTile(int id) : DirectionalTile(id, Material::plant, false) -{ - setTicking(true); +CocoaTile::CocoaTile(int id) : DirectionalTile(id, Material::plant, false) { + setTicking(true); } -Icon *CocoaTile::getTexture(int face, int data) -{ - return icons[2]; +Icon* CocoaTile::getTexture(int face, int data) { return icons[2]; } + +Icon* CocoaTile::getTextureForAge(int age) { + if (age < 0 || age >= COCOA_TEXTURES_LENGTH) { + age = COCOA_TEXTURES_LENGTH - 1; + } + return icons[age]; } -Icon *CocoaTile::getTextureForAge(int age) -{ - if (age < 0 || age >= COCOA_TEXTURES_LENGTH) - { - age = COCOA_TEXTURES_LENGTH - 1; - } - return icons[age]; +void CocoaTile::tick(Level* level, int x, int y, int z, Random* random) { + if (!canSurvive(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } else if (level->random->nextInt(5) == 0) { + int data = level->getData(x, y, z); + int age = getAge(data); + if (age < 2) { + age++; + level->setData(x, y, z, (age << 2) | (getDirection(data))); + } + } } -void CocoaTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (!canSurvive(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } - else if (level->random->nextInt(5) == 0) - { - int data = level->getData(x, y, z); - int age = getAge(data); - if (age < 2) - { - age++; - level->setData(x, y, z, (age << 2) | (getDirection(data))); - } - } +bool CocoaTile::canSurvive(Level* level, int x, int y, int z) { + int dir = getDirection(level->getData(x, y, z)); + + x += Direction::STEP_X[dir]; + z += Direction::STEP_Z[dir]; + int attachedTo = level->getTile(x, y, z); + + return attachedTo == Tile::treeTrunk_Id && + TreeTile::getWoodType(level->getData(x, y, z)) == + TreeTile::JUNGLE_TRUNK; } -bool CocoaTile::canSurvive(Level *level, int x, int y, int z) -{ - int dir = getDirection(level->getData(x, y, z)); +int CocoaTile::getRenderShape() { return SHAPE_COCOA; } - x += Direction::STEP_X[dir]; - z += Direction::STEP_Z[dir]; - int attachedTo = level->getTile(x, y, z); +bool CocoaTile::isCubeShaped() { return false; } - return attachedTo == Tile::treeTrunk_Id && TreeTile::getWoodType(level->getData(x, y, z)) == TreeTile::JUNGLE_TRUNK; +bool CocoaTile::isSolidRender(bool isServerLevel) { return false; } + +AABB* CocoaTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return DirectionalTile::getAABB(level, x, y, z); } -int CocoaTile::getRenderShape() -{ - return SHAPE_COCOA; +AABB* CocoaTile::getTileAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return DirectionalTile::getTileAABB(level, x, y, z); } -bool CocoaTile::isCubeShaped() -{ - return false; +void CocoaTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + int data = level->getData(x, y, z); + int dir = getDirection(data); + int age = getAge(data); + + int width = 4 + age * 2; + int height = 5 + age * 2; + + float hWidth = width / 2.0f; + + switch (dir) { + case Direction::SOUTH: + setShape((8.0f - hWidth) / 16.0f, (12.0f - height) / 16.0f, + (15.0f - width) / 16.0f, (8.0f + hWidth) / 16.0f, + (12.0f) / 16.0f, (15.0f) / 16.0f); + break; + case Direction::NORTH: + setShape((8.0f - hWidth) / 16.0f, (12.0f - height) / 16.0f, + (1.0f) / 16.0f, (8.0f + hWidth) / 16.0f, (12.0f) / 16.0f, + (1.0f + width) / 16.0f); + break; + case Direction::WEST: + setShape((1.0f) / 16.0f, (12.0f - height) / 16.0f, + (8.0f - hWidth) / 16.0f, (1.0f + width) / 16.0f, + (12.0f) / 16.0f, (8.0f + hWidth) / 16.0f); + break; + case Direction::EAST: + setShape((15.0f - width) / 16.0f, (12.0f - height) / 16.0f, + (8.0f - hWidth) / 16.0f, (15.0f) / 16.0f, (12.0f) / 16.0f, + (8.0f + hWidth) / 16.0f); + break; + } } -bool CocoaTile::isSolidRender(bool isServerLevel) -{ - return false; +void CocoaTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by, + std::shared_ptr itemInstance) { + int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3) + 0) % 4; + level->setData(x, y, z, dir); } -AABB *CocoaTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return DirectionalTile::getAABB(level, x, y, z); +int CocoaTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + if (face == Facing::UP || face == Facing::DOWN) { + face = Facing::NORTH; + } + return Direction::DIRECTION_OPPOSITE[Direction::FACING_DIRECTION[face]]; } -AABB *CocoaTile::getTileAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return DirectionalTile::getTileAABB(level, x, y, z); +void CocoaTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!canSurvive(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } } -void CocoaTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - int data = level->getData(x, y, z); - int dir = getDirection(data); - int age = getAge(data); - - int width = 4 + age * 2; - int height = 5 + age * 2; - - float hWidth = width / 2.0f; - - switch (dir) - { - case Direction::SOUTH: - setShape((8.0f - hWidth) / 16.0f, (12.0f - height) / 16.0f, (15.0f - width) / 16.0f, (8.0f + hWidth) / 16.0f, (12.0f) / 16.0f, (15.0f) / 16.0f); - break; - case Direction::NORTH: - setShape((8.0f - hWidth) / 16.0f, (12.0f - height) / 16.0f, (1.0f) / 16.0f, (8.0f + hWidth) / 16.0f, (12.0f) / 16.0f, (1.0f + width) / 16.0f); - break; - case Direction::WEST: - setShape((1.0f) / 16.0f, (12.0f - height) / 16.0f, (8.0f - hWidth) / 16.0f, (1.0f + width) / 16.0f, (12.0f) / 16.0f, (8.0f + hWidth) / 16.0f); - break; - case Direction::EAST: - setShape((15.0f - width) / 16.0f, (12.0f - height) / 16.0f, (8.0f - hWidth) / 16.0f, (15.0f) / 16.0f, (12.0f) / 16.0f, (8.0f + hWidth) / 16.0f); - break; - } +int CocoaTile::getAge(int data) { + return (data & DirectionalTile::DIRECTION_INV_MASK) >> 2; } -void CocoaTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by, std::shared_ptr itemInstance) -{ - int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3) + 0) % 4; - level->setData(x, y, z, dir); +void CocoaTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + int age = getAge(data); + int count = 1; + if (age >= 2) { + count = 3; + } + for (int i = 0; i < count; i++) { + popResource(level, x, y, z, + std::shared_ptr(new ItemInstance( + Item::dye_powder, 1, DyePowderItem::BROWN))); + } } -int CocoaTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - if (face == Facing::UP || face == Facing::DOWN) - { - face = Facing::NORTH; - } - return Direction::DIRECTION_OPPOSITE[Direction::FACING_DIRECTION[face]]; +int CocoaTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::dye_powder_Id; } -void CocoaTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!canSurvive(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } +int CocoaTile::cloneTileData(Level* level, int x, int y, int z) { + return DyePowderItem::BROWN; } -int CocoaTile::getAge(int data) -{ - return (data & DirectionalTile::DIRECTION_INV_MASK) >> 2; -} +void CocoaTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[COCOA_TEXTURES_LENGTH]; -void CocoaTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - int age = getAge(data); - int count = 1; - if (age >= 2) - { - count = 3; - } - for (int i = 0; i < count; i++) - { - popResource(level, x, y, z, std::shared_ptr( new ItemInstance(Item::dye_powder, 1, DyePowderItem::BROWN) )); - } -} - -int CocoaTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::dye_powder_Id; -} - -int CocoaTile::cloneTileData(Level *level, int x, int y, int z) -{ - return DyePowderItem::BROWN; -} - -void CocoaTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[COCOA_TEXTURES_LENGTH]; - - for (int i = 0; i < COCOA_TEXTURES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_AGES[i]); - } + for (int i = 0; i < COCOA_TEXTURES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_AGES[i]); + } } diff --git a/Minecraft.World/Blocks/CocoaTile.h b/Minecraft.World/Blocks/CocoaTile.h index 67345b338..088b511b2 100644 --- a/Minecraft.World/Blocks/CocoaTile.h +++ b/Minecraft.World/Blocks/CocoaTile.h @@ -2,37 +2,44 @@ #include "DirectionalTile.h" -class CocoaTile : public DirectionalTile -{ -public: - static const int COCOA_TEXTURES_LENGTH = 3; - static const std::wstring TEXTURE_AGES[]; +class CocoaTile : public DirectionalTile { +public: + static const int COCOA_TEXTURES_LENGTH = 3; + static const std::wstring TEXTURE_AGES[]; private: - Icon **icons; + Icon** icons; public: - using Tile::setPlacedBy; + using Tile::setPlacedBy; - CocoaTile(int id); + CocoaTile(int id); - virtual Icon *getTexture(int face, int data); - virtual Icon *getTextureForAge(int age); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual bool canSurvive(Level *level, int x, int y, int z); - virtual int getRenderShape(); - virtual bool isCubeShaped(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by, std::shared_ptr itemInstance); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - static int getAge(int data); - using DirectionalTile::spawnResources; - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); - virtual int cloneTileData(Level *level, int x, int y, int z); - virtual void registerIcons(IconRegister *iconRegister); + virtual Icon* getTexture(int face, int data); + virtual Icon* getTextureForAge(int age); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual bool canSurvive(Level* level, int x, int y, int z); + virtual int getRenderShape(); + virtual bool isCubeShaped(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by, + std::shared_ptr itemInstance); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + static int getAge(int data); + using DirectionalTile::spawnResources; + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); + virtual int cloneTileData(Level* level, int x, int y, int z); + virtual void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/CoralTile.cpp b/Minecraft.World/Blocks/CoralTile.cpp index c442c682a..15e1ba607 100644 --- a/Minecraft.World/Blocks/CoralTile.cpp +++ b/Minecraft.World/Blocks/CoralTile.cpp @@ -1,18 +1,20 @@ #include "../Platform/stdafx.h" #include "CoralTile.h" -CoralTile::CoralTile(int id) : HalfTransparentTile(id, L"coral", Material::coral, true) -{ +CoralTile::CoralTile(int id) + : HalfTransparentTile(id, L"coral", Material::coral, true) { float r = 1 / 16.0f; setShape(0 - r, 0 - r, 0 - r, 1 + r, 1 + r, 1 + r); } -int CoralTile::getColor(LevelSource *level, int x, int y, int z) -{ - return (x * x * 3187961 + x * 987243 + y * y * 43297126 + y * 987121 + z * z * 927469861 + z * 1861) & 0xffffff; +int CoralTile::getColor(LevelSource* level, int x, int y, int z) { + return (x * x * 3187961 + x * 987243 + y * y * 43297126 + y * 987121 + + z * z * 927469861 + z * 1861) & + 0xffffff; } -int CoralTile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - return (x * x * 3187961 + x * 987243 + y * y * 43297126 + y * 987121 + z * z * 927469861 + z * 1861) & 0xffffff; +int CoralTile::getColor(LevelSource* level, int x, int y, int z, int data) { + return (x * x * 3187961 + x * 987243 + y * y * 43297126 + y * 987121 + + z * z * 927469861 + z * 1861) & + 0xffffff; } diff --git a/Minecraft.World/Blocks/CoralTile.h b/Minecraft.World/Blocks/CoralTile.h index efb5837b1..54564c96e 100644 --- a/Minecraft.World/Blocks/CoralTile.h +++ b/Minecraft.World/Blocks/CoralTile.h @@ -2,10 +2,10 @@ #include "HalfTransparentTile.h" #include "Material.h" -class CoralTile : public HalfTransparentTile -{ +class CoralTile : public HalfTransparentTile { public: - CoralTile(int id); - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added + CoralTile(int id); + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/CropTile.cpp b/Minecraft.World/Blocks/CropTile.cpp index dcf7e7052..75959a31a 100644 --- a/Minecraft.World/Blocks/CropTile.cpp +++ b/Minecraft.World/Blocks/CropTile.cpp @@ -5,165 +5,133 @@ #include "../Headers/net.minecraft.world.h" #include "CropTile.h" -CropTile::CropTile(int id) : Bush(id) -{ - setTicking(true); - updateDefaultShape(); - icons = NULL; +CropTile::CropTile(int id) : Bush(id) { + setTicking(true); + updateDefaultShape(); + icons = NULL; - setDestroyTime(0.0f); - setSoundType(SOUND_GRASS); - setNotCollectStatistics(); - sendTileData(); + setDestroyTime(0.0f); + setSoundType(SOUND_GRASS); + setNotCollectStatistics(); + sendTileData(); } // 4J Added override -void CropTile::updateDefaultShape() -{ - float ss = 0.5f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); +void CropTile::updateDefaultShape() { + float ss = 0.5f; + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); } -bool CropTile::mayPlaceOn(int tile) -{ - return tile == Tile::farmland_Id; +bool CropTile::mayPlaceOn(int tile) { return tile == Tile::farmland_Id; } + +void CropTile::tick(Level* level, int x, int y, int z, Random* random) { + Bush::tick(level, x, y, z, random); + if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) { + int age = level->getData(x, y, z); + if (age < 7) { + float growthSpeed = getGrowthSpeed(level, x, y, z); + + if (random->nextInt((int)(25 / growthSpeed) + 1) == 0) { + age++; + level->setData(x, y, z, age); + } + } + } } -void CropTile::tick(Level *level, int x, int y, int z, Random *random) -{ - Bush::tick(level, x, y, z, random); - if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) - { - - int age = level->getData(x, y, z); - if (age < 7) - { - float growthSpeed = getGrowthSpeed(level, x, y, z); - - if (random->nextInt((int) (25 / growthSpeed) + 1) == 0) - { - age++; - level->setData(x, y, z, age); - } - } - } +void CropTile::growCropsToMax(Level* level, int x, int y, int z) { + level->setData(x, y, z, 7); } -void CropTile::growCropsToMax(Level *level, int x, int y, int z) -{ - level->setData(x, y, z, 7); +float CropTile::getGrowthSpeed(Level* level, int x, int y, int z) { + float speed = 1; + + int n = level->getTile(x, y, z - 1); + int s = level->getTile(x, y, z + 1); + int w = level->getTile(x - 1, y, z); + int e = level->getTile(x + 1, y, z); + + int d0 = level->getTile(x - 1, y, z - 1); + int d1 = level->getTile(x + 1, y, z - 1); + int d2 = level->getTile(x + 1, y, z + 1); + int d3 = level->getTile(x - 1, y, z + 1); + + bool horizontal = w == this->id || e == this->id; + bool vertical = n == this->id || s == this->id; + bool diagonal = + d0 == this->id || d1 == this->id || d2 == this->id || d3 == this->id; + + for (int xx = x - 1; xx <= x + 1; xx++) + for (int zz = z - 1; zz <= z + 1; zz++) { + int t = level->getTile(xx, y - 1, zz); + + float tileSpeed = 0; + if (t == Tile::farmland_Id) { + tileSpeed = 1; + if (level->getData(xx, y - 1, zz) > 0) tileSpeed = 3; + } + + if (xx != x || zz != z) tileSpeed /= 4; + + speed += tileSpeed; + } + + if (diagonal || (horizontal && vertical)) speed /= 2; + + return speed; } -float CropTile::getGrowthSpeed(Level *level, int x, int y, int z) -{ - float speed = 1; - - int n = level->getTile(x, y, z - 1); - int s = level->getTile(x, y, z + 1); - int w = level->getTile(x - 1, y, z); - int e = level->getTile(x + 1, y, z); - - int d0 = level->getTile(x - 1, y, z - 1); - int d1 = level->getTile(x + 1, y, z - 1); - int d2 = level->getTile(x + 1, y, z + 1); - int d3 = level->getTile(x - 1, y, z + 1); - - bool horizontal = w == this->id || e == this->id; - bool vertical = n == this->id || s == this->id; - bool diagonal = d0 == this->id || d1 == this->id || d2 == this->id || d3 == this->id; - - for (int xx = x - 1; xx <= x + 1; xx++) - for (int zz = z - 1; zz <= z + 1; zz++) - { - int t = level->getTile(xx, y - 1, zz); - - float tileSpeed = 0; - if (t == Tile::farmland_Id) - { - tileSpeed = 1; - if (level->getData(xx, y - 1, zz) > 0) tileSpeed = 3; - } - - if (xx != x || zz != z) tileSpeed /= 4; - - speed += tileSpeed; - } - - if (diagonal || (horizontal && vertical)) speed /= 2; - - return speed; - +Icon* CropTile::getTexture(int face, int data) { + if (data < 0 || data > 7) data = 7; + return icons[data]; } -Icon *CropTile::getTexture(int face, int data) -{ - if (data < 0 || data > 7) data = 7; - return icons[data]; -} +int CropTile::getRenderShape() { return Tile::SHAPE_ROWS; } -int CropTile::getRenderShape() -{ - return Tile::SHAPE_ROWS; -} +int CropTile::getBaseSeedId() { return Item::seeds_wheat_Id; } -int CropTile::getBaseSeedId() -{ - return Item::seeds_wheat_Id; -} - -int CropTile::getBasePlantId() -{ - return Item::wheat_Id; -} +int CropTile::getBasePlantId() { return Item::wheat_Id; } /** - * Using this method instead of destroy() to determine if seeds should be - * dropped - */ -void CropTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ - Bush::spawnResources(level, x, y, z, data, odds, 0); + * Using this method instead of destroy() to determine if seeds should be + * dropped + */ +void CropTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus) { + Bush::spawnResources(level, x, y, z, data, odds, 0); - if (level->isClientSide) - { - return; - } - if (data >= 7) { - int count = 3 + playerBonus; - for (int i = 0; i < count; i++) - { - if (level->random->nextInt(5 * 3) > data) continue; - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(getBaseSeedId(), 1, 0))); - } - } + if (level->isClientSide) { + return; + } + if (data >= 7) { + int count = 3 + playerBonus; + for (int i = 0; i < count; i++) { + if (level->random->nextInt(5 * 3) > data) continue; + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(getBaseSeedId(), 1, 0))); + } + } } -int CropTile::getResource(int data, Random *random, int playerBonusLevel) -{ - if (data == 7) - { - return getBasePlantId(); - } +int CropTile::getResource(int data, Random* random, int playerBonusLevel) { + if (data == 7) { + return getBasePlantId(); + } - return getBaseSeedId(); + return getBaseSeedId(); } -int CropTile::getResourceCount(Random *random) -{ - return 1; +int CropTile::getResourceCount(Random* random) { return 1; } + +int CropTile::cloneTileId(Level* level, int x, int y, int z) { + return getBaseSeedId(); } -int CropTile::cloneTileId(Level *level, int x, int y, int z) -{ - return getBaseSeedId(); -} +void CropTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[8]; -void CropTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[8]; - - for (int i = 0; i < 8; i++) - { - icons[i] = iconRegister->registerIcon(L"crops_" + _toString(i)); - } + for (int i = 0; i < 8; i++) { + icons[i] = iconRegister->registerIcon(L"crops_" + _toString(i)); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/CropTile.h b/Minecraft.World/Blocks/CropTile.h index 01493fdf3..383a95632 100644 --- a/Minecraft.World/Blocks/CropTile.h +++ b/Minecraft.World/Blocks/CropTile.h @@ -6,39 +6,44 @@ class Random; class Level; class ChunkRebuildData; -class CropTile : public Bush -{ - friend class Tile; - friend class ChunkRebuildData; +class CropTile : public Bush { + friend class Tile; + friend class ChunkRebuildData; + private: - Icon **icons; + Icon** icons; protected: - CropTile(int id); + CropTile(int id); virtual bool mayPlaceOn(int tile); + public: - // 4J Added override - virtual void updateDefaultShape(); - virtual void tick(Level *level, int x, int y, int z, Random *random); - void growCropsToMax(Level *level, int x, int y, int z); + // 4J Added override + virtual void updateDefaultShape(); + virtual void tick(Level* level, int x, int y, int z, Random* random); + void growCropsToMax(Level* level, int x, int y, int z); + private: - float getGrowthSpeed(Level *level, int x, int y, int z); + float getGrowthSpeed(Level* level, int x, int y, int z); + public: - virtual Icon *getTexture(int face, int data); + virtual Icon* getTexture(int face, int data); virtual int getRenderShape(); + protected: - virtual int getBaseSeedId(); - virtual int getBasePlantId(); + virtual int getBaseSeedId(); + virtual int getBasePlantId(); public: /** * Using this method instead of destroy() to determine if seeds should be * dropped */ - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual int cloneTileId(Level *level, int x, int y, int z); - //@Override - virtual void registerIcons(IconRegister *iconRegister); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int cloneTileId(Level* level, int x, int y, int z); + //@Override + virtual void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/DeadBushTile.cpp b/Minecraft.World/Blocks/DeadBushTile.cpp index ecc36f07e..1d1097671 100644 --- a/Minecraft.World/Blocks/DeadBushTile.cpp +++ b/Minecraft.World/Blocks/DeadBushTile.cpp @@ -5,42 +5,34 @@ #include "../Headers/net.minecraft.world.level.h" #include "DeadBushTile.h" -DeadBushTile::DeadBushTile(int id) : Bush(id,Material::replaceable_plant) -{ +DeadBushTile::DeadBushTile(int id) : Bush(id, Material::replaceable_plant) { updateDefaultShape(); } // 4J Added override -void DeadBushTile::updateDefaultShape() -{ +void DeadBushTile::updateDefaultShape() { float ss = 0.4f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.8f, 0.5f + ss); } -bool DeadBushTile::mayPlaceOn(int tile) -{ - return tile == Tile::sand_Id; +bool DeadBushTile::mayPlaceOn(int tile) { return tile == Tile::sand_Id; } + +int DeadBushTile::getResource(int data, Random* random, int playerBonusLevel) { + return -1; } -int DeadBushTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return -1; -} +void DeadBushTile::playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data) { + if (!level->isClientSide && player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::shears_Id) { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); -void DeadBushTile::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - if (!level->isClientSide && player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::shears_Id) - { - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); - - // drop leaf block instead of sapling - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Tile::deadBush, 1, data))); - } - else - { - Bush::playerDestroy(level, player, x, y, z, data); - } + // drop leaf block instead of sapling + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(Tile::deadBush, 1, data))); + } else { + Bush::playerDestroy(level, player, x, y, z, data); + } } diff --git a/Minecraft.World/Blocks/DeadBushTile.h b/Minecraft.World/Blocks/DeadBushTile.h index 3e46ff82e..5c895bd9e 100644 --- a/Minecraft.World/Blocks/DeadBushTile.h +++ b/Minecraft.World/Blocks/DeadBushTile.h @@ -3,14 +3,16 @@ class Random; -class DeadBushTile : public Bush -{ - friend class Tile; +class DeadBushTile : public Bush { + friend class Tile; + protected: - DeadBushTile(int id); + DeadBushTile(int id); virtual bool mayPlaceOn(int tile); + public: - virtual void updateDefaultShape(); // 4J Added override - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); + virtual void updateDefaultShape(); // 4J Added override + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); }; diff --git a/Minecraft.World/Blocks/DecorationMaterial.h b/Minecraft.World/Blocks/DecorationMaterial.h index d3012e7e0..8ddc708fb 100644 --- a/Minecraft.World/Blocks/DecorationMaterial.h +++ b/Minecraft.World/Blocks/DecorationMaterial.h @@ -1,12 +1,13 @@ #pragma once #include "Material.h" -class DecorationMaterial : public Material -{ +class DecorationMaterial : public Material { public: - DecorationMaterial(MaterialColor *color) : Material(color) { makeDestroyedByHand(); } + DecorationMaterial(MaterialColor* color) : Material(color) { + makeDestroyedByHand(); + } - virtual bool isSolid() { return false; } - virtual bool blocksLight() { return false; } - virtual bool blocksMotion() { return false; } + virtual bool isSolid() { return false; } + virtual bool blocksLight() { return false; } + virtual bool blocksMotion() { return false; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/DetectorRailTile.cpp b/Minecraft.World/Blocks/DetectorRailTile.cpp index 7d59d27bd..e903e3897 100644 --- a/Minecraft.World/Blocks/DetectorRailTile.cpp +++ b/Minecraft.World/Blocks/DetectorRailTile.cpp @@ -7,109 +7,93 @@ #include "DetectorRailTile.h" #include "../Headers/net.minecraft.h" -DetectorRailTile::DetectorRailTile(int id) : RailTile(id, true) -{ - setTicking(true); - icons = NULL; +DetectorRailTile::DetectorRailTile(int id) : RailTile(id, true) { + setTicking(true); + icons = NULL; } -int DetectorRailTile::getTickDelay() -{ - return 20; -} +int DetectorRailTile::getTickDelay() { return 20; } -bool DetectorRailTile::isSignalSource() -{ - return true; -} +bool DetectorRailTile::isSignalSource() { return true; } -void DetectorRailTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (level->isClientSide) - { +void DetectorRailTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (level->isClientSide) { return; } int data = level->getData(x, y, z); - if ((data & RAIL_DATA_BIT) != 0) - { + if ((data & RAIL_DATA_BIT) != 0) { return; } checkPressed(level, x, y, z, data); } -void DetectorRailTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void DetectorRailTile::tick(Level* level, int x, int y, int z, Random* random) { if (level->isClientSide) return; int data = level->getData(x, y, z); - if ((data & RAIL_DATA_BIT) == 0) - { + if ((data & RAIL_DATA_BIT) == 0) { return; } checkPressed(level, x, y, z, data); } -bool DetectorRailTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return (level->getData(x, y, z) & RAIL_DATA_BIT) != 0; +bool DetectorRailTile::getSignal(LevelSource* level, int x, int y, int z, + int dir) { + return (level->getData(x, y, z) & RAIL_DATA_BIT) != 0; } -bool DetectorRailTile::getDirectSignal(Level *level, int x, int y, int z, int facing) -{ +bool DetectorRailTile::getDirectSignal(Level* level, int x, int y, int z, + int facing) { if ((level->getData(x, y, z) & RAIL_DATA_BIT) == 0) return false; return (facing == Facing::UP); } -void DetectorRailTile::checkPressed(Level *level, int x, int y, int z, int currentData) -{ +void DetectorRailTile::checkPressed(Level* level, int x, int y, int z, + int currentData) { bool wasPressed = (currentData & RAIL_DATA_BIT) != 0; bool shouldBePressed = false; float b = 2 / 16.0f; - std::vector > *entities = level->getEntitiesOfClass(typeid(Minecart), AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 1 - b, z + 1 - b)); - if (!entities->empty()) - { + std::vector >* entities = level->getEntitiesOfClass( + typeid(Minecart), + AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 1 - b, z + 1 - b)); + if (!entities->empty()) { shouldBePressed = true; } - if (shouldBePressed && !wasPressed) - { + if (shouldBePressed && !wasPressed) { level->setData(x, y, z, currentData | RAIL_DATA_BIT); level->updateNeighborsAt(x, y, z, id); level->updateNeighborsAt(x, y - 1, z, id); level->setTilesDirty(x, y, z, x, y, z); } - if (!shouldBePressed && wasPressed) - { + if (!shouldBePressed && wasPressed) { level->setData(x, y, z, currentData & RAIL_DIRECTION_MASK); level->updateNeighborsAt(x, y, z, id); level->updateNeighborsAt(x, y - 1, z, id); level->setTilesDirty(x, y, z, x, y, z); } - if (shouldBePressed) - { + if (shouldBePressed) { level->addToTickNextTick(x, y, z, id, getTickDelay()); } - delete entities; + delete entities; } -void DetectorRailTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[2]; - icons[0] = iconRegister->registerIcon(L"detectorRail"); - icons[1] = iconRegister->registerIcon(L"detectorRail_on"); +void DetectorRailTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[2]; + icons[0] = iconRegister->registerIcon(L"detectorRail"); + icons[1] = iconRegister->registerIcon(L"detectorRail_on"); } -Icon *DetectorRailTile::getTexture(int face, int data) -{ - if ((data & RAIL_DATA_BIT) != 0) - { - return icons[1]; - } - return icons[0]; +Icon* DetectorRailTile::getTexture(int face, int data) { + if ((data & RAIL_DATA_BIT) != 0) { + return icons[1]; + } + return icons[0]; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/DetectorRailTile.h b/Minecraft.World/Blocks/DetectorRailTile.h index 1dcca19b5..3689adb02 100644 --- a/Minecraft.World/Blocks/DetectorRailTile.h +++ b/Minecraft.World/Blocks/DetectorRailTile.h @@ -6,26 +6,30 @@ class Random; class Level; class ChunkRebuildData; -class DetectorRailTile : public RailTile -{ - friend class ChunkRebuildData; +class DetectorRailTile : public RailTile { + friend class ChunkRebuildData; + private: - Icon **icons; + Icon** icons; public: - DetectorRailTile(int id); - virtual int getTickDelay(); - virtual bool isSignalSource(); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int facing); -private: - virtual void checkPressed(Level *level, int x, int y, int z, int currentData); -public: - //@Override - void registerIcons(IconRegister *iconRegister); + DetectorRailTile(int id); + virtual int getTickDelay(); + virtual bool isSignalSource(); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int facing); - //@Override - Icon *getTexture(int face, int data); +private: + virtual void checkPressed(Level* level, int x, int y, int z, + int currentData); + +public: + //@Override + void registerIcons(IconRegister* iconRegister); + + //@Override + Icon* getTexture(int face, int data); }; diff --git a/Minecraft.World/Blocks/DiodeTile.cpp b/Minecraft.World/Blocks/DiodeTile.cpp index 8b857f4fb..89e4a6018 100644 --- a/Minecraft.World/Blocks/DiodeTile.cpp +++ b/Minecraft.World/Blocks/DiodeTile.cpp @@ -6,294 +6,254 @@ #include "../Headers/net.minecraft.world.h" #include "DiodeTile.h" -const double DiodeTile::DELAY_RENDER_OFFSETS[4] = { -1.0f / 16.0f, 1.0f / 16.0f, 3.0f / 16.0f, 5.0f / 16.0f }; -const int DiodeTile::DELAYS[4] = { 1, 2, 3, 4 }; +const double DiodeTile::DELAY_RENDER_OFFSETS[4] = {-1.0f / 16.0f, 1.0f / 16.0f, + 3.0f / 16.0f, 5.0f / 16.0f}; +const int DiodeTile::DELAYS[4] = {1, 2, 3, 4}; -DiodeTile::DiodeTile(int id, bool on) : DirectionalTile(id, Material::decoration, false) -{ - this->on = on; - updateDefaultShape(); +DiodeTile::DiodeTile(int id, bool on) + : DirectionalTile(id, Material::decoration, false) { + this->on = on; + updateDefaultShape(); } // 4J Added override -void DiodeTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 2.0f / 16.0f, 1); +void DiodeTile::updateDefaultShape() { setShape(0, 0, 0, 1, 2.0f / 16.0f, 1); } + +bool DiodeTile::isCubeShaped() { return false; } + +bool DiodeTile::mayPlace(Level* level, int x, int y, int z) { + if (!level->isTopSolidBlocking(x, y - 1, z)) { + return false; + } + return Tile::mayPlace(level, x, y, z); } -bool DiodeTile::isCubeShaped() -{ - return false; +bool DiodeTile::canSurvive(Level* level, int x, int y, int z) { + if (!level->isTopSolidBlocking(x, y - 1, z)) { + return false; + } + return Tile::canSurvive(level, x, y, z); } -bool DiodeTile::mayPlace(Level *level, int x, int y, int z) -{ - if (!level->isTopSolidBlocking(x, y - 1, z)) - { - return false; - } - return Tile::mayPlace(level, x, y, z); +void DiodeTile::tick(Level* level, int x, int y, int z, Random* random) { + int data = level->getData(x, y, z); + bool sourceOn = getSourceSignal(level, x, y, z, data); + if (on && !sourceOn) { + level->setTileAndData(x, y, z, Tile::diode_off_Id, data); + } else if (!on) { + // when off-diodes are ticked, they always turn on for one tick and + // then off again if necessary + level->setTileAndData(x, y, z, Tile::diode_on_Id, data); + if (!sourceOn) { + int delay = (data & DELAY_MASK) >> DELAY_SHIFT; + level->addToTickNextTick(x, y, z, Tile::diode_on_Id, + DELAYS[delay] * 2); + } + } } -bool DiodeTile::canSurvive(Level *level, int x, int y, int z) -{ - if (!level->isTopSolidBlocking(x, y - 1, z)) - { - return false; - } - return Tile::canSurvive(level, x, y, z); +Icon* DiodeTile::getTexture(int face, int data) { + // down is used by the torch tesselator + if (face == Facing::DOWN) { + if (on) { + return Tile::notGate_on->getTexture(face); + } + return Tile::notGate_off->getTexture(face); + } + if (face == Facing::UP) { + return icon; + } + // edge of stone half-step + return Tile::stoneSlab->getTexture(Facing::UP); } -void DiodeTile::tick(Level *level, int x, int y, int z, Random *random) -{ - int data = level->getData(x, y, z); - bool sourceOn = getSourceSignal(level, x, y, z, data); - if (on && !sourceOn) - { - level->setTileAndData(x, y, z, Tile::diode_off_Id, data); - } - else if (!on) - { - // when off-diodes are ticked, they always turn on for one tick and - // then off again if necessary - level->setTileAndData(x, y, z, Tile::diode_on_Id, data); - if (!sourceOn) - { - int delay = (data & DELAY_MASK) >> DELAY_SHIFT; - level->addToTickNextTick(x, y, z, Tile::diode_on_Id, DELAYS[delay] * 2); - } - } +void DiodeTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(on ? L"repeater_lit" : L"repeater"); } -Icon *DiodeTile::getTexture(int face, int data) -{ - // down is used by the torch tesselator - if (face == Facing::DOWN) - { - if (on) - { - return Tile::notGate_on->getTexture(face); - } - return Tile::notGate_off->getTexture(face); - } - if (face == Facing::UP) - { - return icon; - } - // edge of stone half-step - return Tile::stoneSlab->getTexture(Facing::UP); +bool DiodeTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + if (face == Facing::DOWN || face == Facing::UP) { + // up and down is a special case handled by the shape renderer + return false; + } + return true; } -void DiodeTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(on ? L"repeater_lit" : L"repeater"); +int DiodeTile::getRenderShape() { return SHAPE_DIODE; } + +bool DiodeTile::getDirectSignal(Level* level, int x, int y, int z, int dir) { + return getSignal(level, x, y, z, dir); } -bool DiodeTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - if (face == Facing::DOWN || face == Facing::UP) - { - // up and down is a special case handled by the shape renderer - return false; - } - return true; +bool DiodeTile::getSignal(LevelSource* level, int x, int y, int z, int facing) { + if (!on) { + return false; + } + + int dir = getDirection(level->getData(x, y, z)); + + if (dir == Direction::SOUTH && facing == Facing::SOUTH) return true; + if (dir == Direction::WEST && facing == Facing::WEST) return true; + if (dir == Direction::NORTH && facing == Facing::NORTH) return true; + if (dir == Direction::EAST && facing == Facing::EAST) return true; + + return false; } -int DiodeTile::getRenderShape() -{ - return SHAPE_DIODE; +void DiodeTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!canSurvive(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + level->updateNeighborsAt(x + 1, y, z, id); + level->updateNeighborsAt(x - 1, y, z, id); + level->updateNeighborsAt(x, y, z + 1, id); + level->updateNeighborsAt(x, y, z - 1, id); + level->updateNeighborsAt(x, y - 1, z, id); + level->updateNeighborsAt(x, y + 1, z, id); + return; + } + + int data = level->getData(x, y, z); + + bool sourceOn = getSourceSignal(level, x, y, z, data); + int delay = (data & DELAY_MASK) >> DELAY_SHIFT; + if ((on && !sourceOn) || (!on && sourceOn)) { + level->addToTickNextTick(x, y, z, id, DELAYS[delay] * 2); + } } -bool DiodeTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ - return getSignal(level, x, y, z, dir); -} - -bool DiodeTile::getSignal(LevelSource *level, int x, int y, int z, int facing) -{ - if (!on) - { - return false; - } - - int dir = getDirection(level->getData(x, y, z)); - - if (dir == Direction::SOUTH && facing == Facing::SOUTH) return true; - if (dir == Direction::WEST && facing == Facing::WEST) return true; - if (dir == Direction::NORTH && facing == Facing::NORTH) return true; - if (dir == Direction::EAST && facing == Facing::EAST) return true; - - return false; -} - -void DiodeTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!canSurvive(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - level->updateNeighborsAt(x + 1, y, z, id); - level->updateNeighborsAt(x - 1, y, z, id); - level->updateNeighborsAt(x, y, z + 1, id); - level->updateNeighborsAt(x, y, z - 1, id); - level->updateNeighborsAt(x, y - 1, z, id); - level->updateNeighborsAt(x, y + 1, z, id); - return; - } - - int data = level->getData(x, y, z); - - bool sourceOn = getSourceSignal(level, x, y, z, data); - int delay = (data & DELAY_MASK) >> DELAY_SHIFT; - if ( (on && !sourceOn) || (!on && sourceOn)) - { - level->addToTickNextTick(x, y, z, id, DELAYS[delay] * 2); - } -} - -bool DiodeTile::getSourceSignal(Level *level, int x, int y, int z, int data) -{ - int dir = getDirection(data); - switch (dir) - { - case Direction::SOUTH: - return level->getSignal(x, y, z + 1, Facing::SOUTH) || (level->getTile(x, y, z + 1) == Tile::redStoneDust_Id && level->getData(x, y, z + 1) > 0); +bool DiodeTile::getSourceSignal(Level* level, int x, int y, int z, int data) { + int dir = getDirection(data); + switch (dir) { + case Direction::SOUTH: + return level->getSignal(x, y, z + 1, Facing::SOUTH) || + (level->getTile(x, y, z + 1) == Tile::redStoneDust_Id && + level->getData(x, y, z + 1) > 0); case Direction::NORTH: - return level->getSignal(x, y, z - 1, Facing::NORTH) || (level->getTile(x, y, z - 1) == Tile::redStoneDust_Id && level->getData(x, y, z - 1) > 0); + return level->getSignal(x, y, z - 1, Facing::NORTH) || + (level->getTile(x, y, z - 1) == Tile::redStoneDust_Id && + level->getData(x, y, z - 1) > 0); case Direction::EAST: - return level->getSignal(x + 1, y, z, Facing::EAST) || (level->getTile(x + 1, y, z) == Tile::redStoneDust_Id && level->getData(x + 1, y, z) > 0); + return level->getSignal(x + 1, y, z, Facing::EAST) || + (level->getTile(x + 1, y, z) == Tile::redStoneDust_Id && + level->getData(x + 1, y, z) > 0); case Direction::WEST: - return level->getSignal(x - 1, y, z, Facing::WEST) || (level->getTile(x - 1, y, z) == Tile::redStoneDust_Id && level->getData(x - 1, y, z) > 0); - } - return false; + return level->getSignal(x - 1, y, z, Facing::WEST) || + (level->getTile(x - 1, y, z) == Tile::redStoneDust_Id && + level->getData(x - 1, y, z) > 0); + } + return false; } // 4J-PB - Adding a TestUse for tooltip display -bool DiodeTile::TestUse() +bool DiodeTile::TestUse() { return true; } + +bool DiodeTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (soundOnly) return false; + + int data = level->getData(x, y, z); + int delay = (data & DELAY_MASK) >> DELAY_SHIFT; + delay = ((delay + 1) << DELAY_SHIFT) & DELAY_MASK; + + level->setData(x, y, z, delay | (data & DIRECTION_MASK)); + return true; } -bool DiodeTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if( soundOnly) return false; +bool DiodeTile::isSignalSource() { return true; } - int data = level->getData(x, y, z); - int delay = (data & DELAY_MASK) >> DELAY_SHIFT; - delay = ((delay + 1) << DELAY_SHIFT) & DELAY_MASK; +void DiodeTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3) + 2) % 4; + level->setData(x, y, z, dir); - level->setData(x, y, z, delay | (data & DIRECTION_MASK)); - return true; + bool sourceOn = getSourceSignal(level, x, y, z, dir); + if (sourceOn) { + level->addToTickNextTick(x, y, z, id, 1); + } } -bool DiodeTile::isSignalSource() -{ - return true; +void DiodeTile::onPlace(Level* level, int x, int y, int z) { + level->updateNeighborsAt(x + 1, y, z, id); + level->updateNeighborsAt(x - 1, y, z, id); + level->updateNeighborsAt(x, y, z + 1, id); + level->updateNeighborsAt(x, y, z - 1, id); + level->updateNeighborsAt(x, y - 1, z, id); + level->updateNeighborsAt(x, y + 1, z, id); } -void DiodeTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3) + 2) % 4; - level->setData(x, y, z, dir); - - bool sourceOn = getSourceSignal(level, x, y, z, dir); - if (sourceOn) - { - level->addToTickNextTick(x, y, z, id, 1); - } -} - -void DiodeTile::onPlace(Level *level, int x, int y, int z) -{ - level->updateNeighborsAt(x + 1, y, z, id); - level->updateNeighborsAt(x - 1, y, z, id); - level->updateNeighborsAt(x, y, z + 1, id); - level->updateNeighborsAt(x, y, z - 1, id); - level->updateNeighborsAt(x, y - 1, z, id); - level->updateNeighborsAt(x, y + 1, z, id); -} - -void DiodeTile::destroy(Level *level, int x, int y, int z, int data) -{ - if (on) - { - level->updateNeighborsAt(x + 1, y, z, id); - level->updateNeighborsAt(x - 1, y, z, id); - level->updateNeighborsAt(x, y, z + 1, id); - level->updateNeighborsAt(x, y, z - 1, id); - level->updateNeighborsAt(x, y - 1, z, id); - level->updateNeighborsAt(x, y + 1, z, id); - } +void DiodeTile::destroy(Level* level, int x, int y, int z, int data) { + if (on) { + level->updateNeighborsAt(x + 1, y, z, id); + level->updateNeighborsAt(x - 1, y, z, id); + level->updateNeighborsAt(x, y, z + 1, id); + level->updateNeighborsAt(x, y, z - 1, id); + level->updateNeighborsAt(x, y - 1, z, id); + level->updateNeighborsAt(x, y + 1, z, id); + } Tile::destroy(level, x, y, z, data); } -bool DiodeTile::isSolidRender(bool isServerLevel) -{ - return false; +bool DiodeTile::isSolidRender(bool isServerLevel) { return false; } + +int DiodeTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::diode->id; } -int DiodeTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::diode->id; +void DiodeTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { + if (!on) return; + int data = level->getData(xt, yt, zt); + int dir = getDirection(data); + + double x = xt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; + double y = yt + 0.4f + (random->nextFloat() - 0.5f) * 0.2; + double z = zt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; + + double xo = 0; + double zo = 0; + + if (random->nextInt(2) == 0) { + // spawn on receiver + switch (dir) { + case Direction::SOUTH: + zo = -5.0f / 16.0f; + break; + case Direction::NORTH: + zo = 5.0f / 16.0f; + break; + case Direction::EAST: + xo = -5.0f / 16.0f; + break; + case Direction::WEST: + xo = 5.0f / 16.0f; + break; + } + } else { + // spawn on transmitter + int delay = (data & DELAY_MASK) >> DELAY_SHIFT; + switch (dir) { + case Direction::SOUTH: + zo = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::NORTH: + zo = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::EAST: + xo = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::WEST: + xo = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + } + } + level->addParticle(eParticleType_reddust, x + xo, y, z + zo, 0, 0, 0); } -void DiodeTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ - if (!on) return; - int data = level->getData(xt, yt, zt); - int dir = getDirection(data); - - double x = xt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; - double y = yt + 0.4f + (random->nextFloat() - 0.5f) * 0.2; - double z = zt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; - - double xo = 0; - double zo = 0; - - if (random->nextInt(2) == 0) - { - // spawn on receiver - switch (dir) - { - case Direction::SOUTH: - zo = -5.0f / 16.0f; - break; - case Direction::NORTH: - zo = 5.0f / 16.0f; - break; - case Direction::EAST: - xo = -5.0f / 16.0f; - break; - case Direction::WEST: - xo = 5.0f / 16.0f; - break; - } - } - else - { - // spawn on transmitter - int delay = (data & DELAY_MASK) >> DELAY_SHIFT; - switch (dir) - { - case Direction::SOUTH: - zo = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::NORTH: - zo = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::EAST: - xo = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::WEST: - xo = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - } - } - level->addParticle(eParticleType_reddust, x + xo, y, z + zo, 0, 0, 0); - -} - -int DiodeTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::diode_Id; +int DiodeTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::diode_Id; } diff --git a/Minecraft.World/Blocks/DiodeTile.h b/Minecraft.World/Blocks/DiodeTile.h index ff3b7e88d..2b0ced2f2 100644 --- a/Minecraft.World/Blocks/DiodeTile.h +++ b/Minecraft.World/Blocks/DiodeTile.h @@ -5,9 +5,9 @@ class Player; class Random; class Level; -class DiodeTile : public DirectionalTile -{ - friend class Tile; +class DiodeTile : public DirectionalTile { + friend class Tile; + public: static const int DELAY_MASK = DIRECTION_INV_MASK; static const int DELAY_SHIFT = 2; @@ -19,32 +19,41 @@ private: bool on; protected: - DiodeTile(int id, bool on); + DiodeTile(int id, bool on); + public: - virtual void updateDefaultShape(); // 4J Added override + virtual void updateDefaultShape(); // 4J Added override virtual bool isCubeShaped(); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual bool canSurvive(Level *level, int x, int y, int z); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual Icon *getTexture(int face, int data); - //@Override - void registerIcons(IconRegister *iconRegister); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual bool canSurvive(Level* level, int x, int y, int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual Icon* getTexture(int face, int data); + //@Override + void registerIcons(IconRegister* iconRegister); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); virtual int getRenderShape(); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int facing); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int facing); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + private: - virtual bool getSourceSignal(Level *level, int x, int y, int z, int data); + virtual bool getSourceSignal(Level* level, int x, int y, int z, int data); + public: - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param virtual bool isSignalSource(); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void destroy(Level *level, int x, int y, int z, int data); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void destroy(Level* level, int x, int y, int z, int data); virtual bool isSolidRender(bool isServerLevel = false); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); + virtual int cloneTileId(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/DirectionalTile.cpp b/Minecraft.World/Blocks/DirectionalTile.cpp index b62ebd7e7..f9a934411 100644 --- a/Minecraft.World/Blocks/DirectionalTile.cpp +++ b/Minecraft.World/Blocks/DirectionalTile.cpp @@ -2,15 +2,10 @@ #include "DirectionalTile.h" -DirectionalTile::DirectionalTile(int id, Material *material) : Tile(id, material) -{ -} +DirectionalTile::DirectionalTile(int id, Material* material) + : Tile(id, material) {} -DirectionalTile::DirectionalTile(int id, Material *material, bool isSolidRender) : Tile(id, material, isSolidRender) -{ -} +DirectionalTile::DirectionalTile(int id, Material* material, bool isSolidRender) + : Tile(id, material, isSolidRender) {} -int DirectionalTile::getDirection(int data) -{ - return data & DIRECTION_MASK; -} \ No newline at end of file +int DirectionalTile::getDirection(int data) { return data & DIRECTION_MASK; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/DirectionalTile.h b/Minecraft.World/Blocks/DirectionalTile.h index cc4715c6f..2ded263a1 100644 --- a/Minecraft.World/Blocks/DirectionalTile.h +++ b/Minecraft.World/Blocks/DirectionalTile.h @@ -2,16 +2,15 @@ #include "Tile.h" -class DirectionalTile : public Tile -{ +class DirectionalTile : public Tile { public: - static const int DIRECTION_MASK = 0x3; - static const int DIRECTION_INV_MASK = 0xC; + static const int DIRECTION_MASK = 0x3; + static const int DIRECTION_INV_MASK = 0xC; protected: - DirectionalTile(int id, Material *material); - DirectionalTile(int id, Material *material, bool isSolidRender); + DirectionalTile(int id, Material* material); + DirectionalTile(int id, Material* material, bool isSolidRender); public: - static int getDirection(int data); + static int getDirection(int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/DirtTile.cpp b/Minecraft.World/Blocks/DirtTile.cpp index eb1a49754..adffc8c64 100644 --- a/Minecraft.World/Blocks/DirtTile.cpp +++ b/Minecraft.World/Blocks/DirtTile.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "DirtTile.h" -DirtTile::DirtTile(int id) : Tile(id, Material::dirt) -{ -} \ No newline at end of file +DirtTile::DirtTile(int id) : Tile(id, Material::dirt) {} \ No newline at end of file diff --git a/Minecraft.World/Blocks/DirtTile.h b/Minecraft.World/Blocks/DirtTile.h index 31790886a..e098f3911 100644 --- a/Minecraft.World/Blocks/DirtTile.h +++ b/Minecraft.World/Blocks/DirtTile.h @@ -1,9 +1,9 @@ #pragma once #include "Tile.h" -class DirtTile : public Tile -{ - friend class Tile; +class DirtTile : public Tile { + friend class Tile; + protected: - DirtTile(int id); + DirtTile(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/DispenserTile.cpp b/Minecraft.World/Blocks/DispenserTile.cpp index c7dbb9621..dfabb985b 100644 --- a/Minecraft.World/Blocks/DispenserTile.cpp +++ b/Minecraft.World/Blocks/DispenserTile.cpp @@ -11,563 +11,545 @@ #include "../Headers/net.minecraft.h" #include "../Entities/Mob.h" -DispenserTile::DispenserTile(int id) : EntityTile(id, Material::stone) -{ - random = new Random(); +DispenserTile::DispenserTile(int id) : EntityTile(id, Material::stone) { + random = new Random(); - iconTop = NULL; - iconFront = NULL; - iconFrontVertical = NULL; + iconTop = NULL; + iconFront = NULL; + iconFrontVertical = NULL; } -int DispenserTile::getTickDelay() -{ - return 4; +int DispenserTile::getTickDelay() { return 4; } + +int DispenserTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::dispenser_Id; } -int DispenserTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::dispenser_Id; +void DispenserTile::onPlace(Level* level, int x, int y, int z) { + EntityTile::onPlace(level, x, y, z); + recalcLockDir(level, x, y, z); } -void DispenserTile::onPlace(Level *level, int x, int y, int z) -{ - EntityTile::onPlace(level, x, y, z); - recalcLockDir(level, x, y, z); +void DispenserTile::recalcLockDir(Level* level, int x, int y, int z) { + if (level->isClientSide) { + return; + } + + int n = level->getTile(x, y, z - 1); // face = 2 + int s = level->getTile(x, y, z + 1); // face = 3 + int w = level->getTile(x - 1, y, z); // face = 4 + int e = level->getTile(x + 1, y, z); // face = 5 + + int lockDir = 3; + if (Tile::solid[n] && !Tile::solid[s]) lockDir = 3; + if (Tile::solid[s] && !Tile::solid[n]) lockDir = 2; + if (Tile::solid[w] && !Tile::solid[e]) lockDir = 5; + if (Tile::solid[e] && !Tile::solid[w]) lockDir = 4; + level->setData(x, y, z, lockDir); } -void DispenserTile::recalcLockDir(Level *level, int x, int y, int z) -{ - if (level->isClientSide) - { - return; - } +Icon* DispenserTile::getTexture(int face, int data) { + int dir = data & FACING_MASK; - int n = level->getTile(x, y, z - 1); // face = 2 - int s = level->getTile(x, y, z + 1); // face = 3 - int w = level->getTile(x - 1, y, z); // face = 4 - int e = level->getTile(x + 1, y, z); // face = 5 + if (face == dir) { + if (dir == Facing::UP || dir == Facing::DOWN) { + return iconFrontVertical; + } else { + return iconFront; + } + } - int lockDir = 3; - if (Tile::solid[n] && !Tile::solid[s]) lockDir = 3; - if (Tile::solid[s] && !Tile::solid[n]) lockDir = 2; - if (Tile::solid[w] && !Tile::solid[e]) lockDir = 5; - if (Tile::solid[e] && !Tile::solid[w]) lockDir = 4; - level->setData(x, y, z, lockDir); + if (dir == Facing::UP || dir == Facing::DOWN) { + return iconTop; + } else if (face == Facing::UP || face == Facing::DOWN) { + return iconTop; + } + + return icon; } -Icon *DispenserTile::getTexture(int face, int data) -{ - int dir = data & FACING_MASK; - - if (face == dir) - { - if (dir == Facing::UP || dir == Facing::DOWN) - { - return iconFrontVertical; - } - else - { - return iconFront; - } - } - - if (dir == Facing::UP || dir == Facing::DOWN) - { - return iconTop; - } - else if (face == Facing::UP || face == Facing::DOWN) - { - return iconTop; - } - - return icon; -} - -void DispenserTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"furnace_side"); - iconTop = iconRegister->registerIcon(L"furnace_top"); - iconFront = iconRegister->registerIcon(L"dispenser_front"); - iconFrontVertical = iconRegister->registerIcon(L"dispenser_front_vertical"); +void DispenserTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"furnace_side"); + iconTop = iconRegister->registerIcon(L"furnace_top"); + iconFront = iconRegister->registerIcon(L"dispenser_front"); + iconFrontVertical = iconRegister->registerIcon(L"dispenser_front_vertical"); } // 4J-PB - Adding a TestUse for tooltip display -bool DispenserTile::TestUse() +bool DispenserTile::TestUse() { return true; } + +bool DispenserTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (soundOnly) return false; + + if (level->isClientSide) { + return true; + } + + std::shared_ptr trap = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + player->openTrap(trap); + + return true; } -bool DispenserTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if( soundOnly) return false; +void DispenserTile::fireArrow(Level* level, int x, int y, int z, + Random* random) { + const int lockDir = level->getData(x, y, z); + // const float power = 1.1f; + const int accuracy = 6; + // bool bLaunched=true; - if (level->isClientSide) - { - return true; - } + int xd = 0, zd = 0; + if (lockDir == Facing::SOUTH) { + zd = 1; + } else if (lockDir == Facing::NORTH) { + zd = -1; + } else if (lockDir == Facing::EAST) { + xd = 1; + } else { + xd = -1; + } - std::shared_ptr trap = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - player->openTrap(trap); + std::shared_ptr trap = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (trap != NULL) { + int slot = trap->getRandomSlot(); - return true; + if (slot < 0) { + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + } else { + double xp = x + xd * 0.6 + 0.5; + double yp = y + 0.5; + double zp = z + zd * 0.6 + 0.5; + std::shared_ptr item = trap->getItem(slot); + int result = dispenseItem(trap, level, item, random, x, y, z, xd, + zd, xp, yp, zp); + if (result == REMOVE_ITEM) { + trap->removeItem(slot, 1); + } else if (result == DISPENSE_ITEM) { + item = trap->removeItem(slot, 1); + throwItem(level, item, random, accuracy, xd, zd, xp, yp, zp); + level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); + } + + level->levelEvent(LevelEvent::PARTICLES_SHOOT, x, y, z, + (xd + 1) + (zd + 1) * 3); + } + } } -void DispenserTile::fireArrow(Level *level, int x, int y, int z, Random *random) -{ - const int lockDir = level->getData(x, y, z); - //const float power = 1.1f; - const int accuracy = 6; - //bool bLaunched=true; - - int xd = 0, zd = 0; - if (lockDir == Facing::SOUTH) - { - zd = 1; - } - else if (lockDir == Facing::NORTH) - { - zd = -1; - } - else if (lockDir == Facing::EAST) - { - xd = 1; - } - else - { - xd = -1; - } - - std::shared_ptr trap = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if(trap != NULL) - { - int slot=trap->getRandomSlot(); - - if (slot < 0) - { - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - } - else - { - double xp = x + xd * 0.6 + 0.5; - double yp = y + 0.5; - double zp = z + zd * 0.6 + 0.5; - std::shared_ptr item=trap->getItem(slot); - int result = dispenseItem(trap, level, item, random, x, y, z, xd, zd, xp, yp, zp); - if (result == REMOVE_ITEM) - { - trap->removeItem(slot, 1); - } - else if (result == DISPENSE_ITEM) - { - item = trap->removeItem(slot, 1); - throwItem(level, item, random, accuracy, xd, zd, xp, yp, zp); - level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); - } - - level->levelEvent(LevelEvent::PARTICLES_SHOOT, x, y, z, (xd + 1) + (zd + 1) * 3); - } - } +void DispenserTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (type > 0 && Tile::tiles[type]->isSignalSource()) { + bool signal = level->hasNeighborSignal(x, y, z) || + level->hasNeighborSignal(x, y + 1, z); + if (signal) { + level->addToTickNextTick(x, y, z, this->id, getTickDelay()); + } + } } -void DispenserTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (type > 0 && Tile::tiles[type]->isSignalSource()) - { - bool signal = level->hasNeighborSignal(x, y, z) || level->hasNeighborSignal(x, y + 1, z); - if (signal) - { - level->addToTickNextTick(x, y, z, this->id, getTickDelay()); - } - } +void DispenserTile::tick(Level* level, int x, int y, int z, Random* random) { + if (!level->isClientSide && (level->hasNeighborSignal(x, y, z) || + level->hasNeighborSignal(x, y + 1, z))) { + fireArrow(level, x, y, z, random); + } } -void DispenserTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (!level->isClientSide && ( level->hasNeighborSignal(x, y, z) || level->hasNeighborSignal(x, y + 1, z))) - { - fireArrow(level, x, y, z, random); - } +std::shared_ptr DispenserTile::newTileEntity(Level* level) { + return std::shared_ptr(new DispenserTileEntity()); } -std::shared_ptr DispenserTile::newTileEntity(Level *level) -{ - return std::shared_ptr( new DispenserTileEntity() ); +void DispenserTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; + + if (dir == 0) level->setData(x, y, z, Facing::NORTH); + if (dir == 1) level->setData(x, y, z, Facing::EAST); + if (dir == 2) level->setData(x, y, z, Facing::SOUTH); + if (dir == 3) level->setData(x, y, z, Facing::WEST); } -void DispenserTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; +void DispenserTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + std::shared_ptr container = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (container != NULL) { + for (unsigned int i = 0; i < container->getContainerSize(); i++) { + std::shared_ptr item = container->getItem(i); + if (item != NULL) { + float xo = random->nextFloat() * 0.8f + 0.1f; + float yo = random->nextFloat() * 0.8f + 0.1f; + float zo = random->nextFloat() * 0.8f + 0.1f; - if (dir == 0) level->setData(x, y, z, Facing::NORTH); - if (dir == 1) level->setData(x, y, z, Facing::EAST); - if (dir == 2) level->setData(x, y, z, Facing::SOUTH); - if (dir == 3) level->setData(x, y, z, Facing::WEST); + while (item->count > 0) { + int count = random->nextInt(21) + 10; + if (count > item->count) count = item->count; + item->count -= count; + + std::shared_ptr newItem = + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())); + newItem->set4JData(item->get4JData()); + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, newItem)); + float pow = 0.05f; + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); + } + level->addEntity(itemEntity); + } + + // 4J Stu - Fix for duplication glitch + container->setItem(i, nullptr); + } + } + } + EntityTile::onRemove(level, x, y, z, id, data); } -void DispenserTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - std::shared_ptr container = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (container != NULL ) - { - for (unsigned int i = 0; i < container->getContainerSize(); i++) - { - std::shared_ptr item = container->getItem(i); - if (item != NULL) - { - float xo = random->nextFloat() * 0.8f + 0.1f; - float yo = random->nextFloat() * 0.8f + 0.1f; - float zo = random->nextFloat() * 0.8f + 0.1f; +void DispenserTile::throwItem(Level* level, std::shared_ptr item, + Random* random, int accuracy, int xd, int zd, + double xp, double yp, double zp) { + std::shared_ptr itemEntity = std::shared_ptr( + new ItemEntity(level, xp, yp - 0.3, zp, item)); - while (item->count > 0) - { - int count = random->nextInt(21) + 10; - if (count > item->count) count = item->count; - item->count -= count; + double pow = random->nextDouble() * 0.1 + 0.2; + itemEntity->xd = xd * pow; + itemEntity->yd = .2f; + itemEntity->zd = zd * pow; - std::shared_ptr newItem = std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue()) ); - newItem->set4JData( item->get4JData() ); - std::shared_ptr itemEntity = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, newItem ) ); - float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); - } - level->addEntity(itemEntity); - } + itemEntity->xd += (random->nextGaussian()) * 0.0075f * accuracy; + itemEntity->yd += (random->nextGaussian()) * 0.0075f * accuracy; + itemEntity->zd += (random->nextGaussian()) * 0.0075f * accuracy; - // 4J Stu - Fix for duplication glitch - container->setItem(i,nullptr); - } - } - } - EntityTile::onRemove(level, x, y, z, id, data); + level->addEntity(itemEntity); } -void DispenserTile::throwItem(Level *level, std::shared_ptr item, Random *random, int accuracy, int xd, int zd, double xp, double yp, double zp) -{ - std::shared_ptr itemEntity = std::shared_ptr(new ItemEntity(level, xp, yp - 0.3, zp, item)); +int DispenserTile::dispenseItem(std::shared_ptr trap, + Level* level, + std::shared_ptr item, + Random* random, int x, int y, int z, int xd, + int zd, double xp, double yp, double zp) { + float power = 1.1f; + int accuracy = 6; - double pow = random->nextDouble() * 0.1 + 0.2; - itemEntity->xd = xd * pow; - itemEntity->yd = .2f; - itemEntity->zd = zd * pow; + // 4J-PB - moved to a switch + switch (item->id) { + case Item::arrow_Id: { + int currentProjectiles = + level->countInstanceOf(eTYPE_PROJECTILE, false); + if (currentProjectiles < + Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit + { + std::shared_ptr arrow = + std::shared_ptr(new Arrow(level, xp, yp, zp)); + arrow->shoot(xd, .1f, zd, power, (float)accuracy); + arrow->pickup = Arrow::PICKUP_ALLOWED; + level->addEntity(arrow); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - itemEntity->xd += (random->nextGaussian()) * 0.0075f * accuracy; - itemEntity->yd += (random->nextGaussian()) * 0.0075f * accuracy; - itemEntity->zd += (random->nextGaussian()) * 0.0075f * accuracy; + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::egg_Id: { + int currentProjectiles = + level->countInstanceOf(eTYPE_PROJECTILE, false); + if (currentProjectiles < + Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit + { + std::shared_ptr egg = std::shared_ptr( + new ThrownEgg(level, xp, yp, zp)); + egg->shoot(xd, .1f, zd, power, (float)accuracy); + level->addEntity(egg); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - level->addEntity(itemEntity); -} - -int DispenserTile::dispenseItem(std::shared_ptr trap, Level *level, std::shared_ptr item, Random *random, int x, int y, int z, int xd, int zd, double xp, double yp, double zp) -{ - float power = 1.1f; - int accuracy = 6; - - // 4J-PB - moved to a switch - switch(item->id) - { - case Item::arrow_Id: - { - int currentProjectiles = level->countInstanceOf(eTYPE_PROJECTILE,false); - if(currentProjectiles < Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit - { - std::shared_ptr arrow = std::shared_ptr( new Arrow(level, xp, yp, zp) ); - arrow->shoot(xd, .1f, zd, power, (float) accuracy); - arrow->pickup = Arrow::PICKUP_ALLOWED; - level->addEntity(arrow); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::egg_Id: - { - int currentProjectiles = level->countInstanceOf(eTYPE_PROJECTILE,false); - if(currentProjectiles < Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit - { - std::shared_ptr egg = std::shared_ptr( new ThrownEgg(level, xp, yp, zp) ); - egg->shoot(xd, .1f, zd, power, (float) accuracy); - level->addEntity(egg); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::snowBall_Id: - { - int currentProjectiles = level->countInstanceOf(eTYPE_PROJECTILE,false); - if(currentProjectiles < Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit - { - std::shared_ptr snowball = std::shared_ptr( new Snowball(level, xp, yp, zp) ); - snowball->shoot(xd, .1f, zd, power, (float) accuracy); - level->addEntity(snowball); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::potion_Id: - { - int currentProjectiles = level->countInstanceOf(eTYPE_PROJECTILE,false); - if(currentProjectiles < Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit - { - if(PotionItem::isThrowable(item->getAuxValue())) - { - std::shared_ptr potion = std::shared_ptr(new ThrownPotion(level, xp, yp, zp, item->getAuxValue())); - potion->shoot(xd, .1f, zd, power * 1.25f, accuracy * .5f); - level->addEntity(potion); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - } - else - { - std::shared_ptr itemEntity = std::shared_ptr( new ItemEntity(level, xp, yp - 0.3, zp, item) ); - - double pow = random->nextDouble() * 0.1 + 0.2; - itemEntity->xd = xd * pow; - itemEntity->yd = .2f; - itemEntity->zd = zd * pow; - - itemEntity->xd += (random->nextGaussian()) * 0.0075f * accuracy; - itemEntity->yd += (random->nextGaussian()) * 0.0075f * accuracy; - itemEntity->zd += (random->nextGaussian()) * 0.0075f * accuracy; - - level->addEntity(itemEntity); - level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); - } - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::expBottle_Id: - { - int currentProjectiles = level->countInstanceOf(eTYPE_PROJECTILE,false); - if(currentProjectiles < Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit - { - std::shared_ptr expBottle = std::shared_ptr( new ThrownExpBottle(level, xp, yp, zp) ); - expBottle->shoot(xd, .1f, zd, power * 1.25f, accuracy * .5f); - level->addEntity(expBottle); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::fireball_Id: // TU9 - { - int currentFireballs = level->countInstanceOf(eTYPE_SMALL_FIREBALL,true); - if(currentFireballs < Level::MAX_DISPENSABLE_FIREBALLS) // 4J - added limit - { - std::shared_ptr fireball = std::shared_ptr( new SmallFireball(level, xp + xd * .3, yp, zp + zd * .3, xd + random->nextGaussian() * .05, random->nextGaussian() * .05, zd + random->nextGaussian() * .05)); - level->addEntity(fireball); - level->levelEvent(LevelEvent::SOUND_BLAZE_FIREBALL, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::monsterPlacer_Id: - { - int iResult=0; - //MonsterPlacerItem *spawnEgg = (MonsterPlacerItem *)item->getItem(); - std::shared_ptr newEntity = MonsterPlacerItem::canSpawn(item->getAuxValue(), level,&iResult); - - std::shared_ptr mob = std::dynamic_pointer_cast(newEntity); - if (mob != NULL) - { - // 4J-PB - Changed the line below slightly since mobs were sticking to the dispenser rather than dropping down when fired - mob->moveTo(xp + xd * 0.4, yp - 0.3, zp + zd * 0.4, level->random->nextFloat() * 360, 0); - mob->finalizeMobSpawn(); - level->addEntity(mob); - level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - // some negative sound effect? - level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - - // not sending a message here, since we will probably get flooded with them when people have automatic dispensers for spawn eggs - return LEAVE_ITEM; - } - } - break; - case Item::bucket_lava_Id: - case Item::bucket_water_Id: - { - BucketItem *pBucket = (BucketItem *) item->getItem(); - - if (pBucket->emptyBucket(level, x, y, z, x + xd, y, z + zd)) - { - item->id = Item::bucket_empty_Id; - item->count = 1; - return LEAVE_ITEM; - } - return DISPENSE_ITEM; - } - break; - case Item::bucket_empty_Id: - { - int xt = x + xd; - int zt = z + zd; - Material *pMaterial=level->getMaterial(xt, y, zt); - int data = level->getData(xt, y, zt); - - if (pMaterial == Material::water && data == 0) - { - level->setTile(xt, y, zt, 0); - - if (--item->count == 0) - { - item->id = Item::bucket_water_Id; - item->count = 1; - } - else if (trap->addItem(std::shared_ptr(new ItemInstance(Item::bucket_water))) < 0) - { - throwItem(level, std::shared_ptr(new ItemInstance(Item::bucket_water)), random, 6, xd, zd, xp, yp, zp); - } - - return LEAVE_ITEM; - } - else if (pMaterial == Material::lava && data == 0) - { - level->setTile(xt, y, zt, 0); - - if (--item->count == 0) - { - item->id = Item::bucket_lava_Id; - item->count = 1; - } - else if (trap->addItem(std::shared_ptr(new ItemInstance(Item::bucket_lava))) < 0) - { - throwItem(level, std::shared_ptr(new ItemInstance(Item::bucket_lava)), random, 6, xd, zd, xp, yp, zp); - } - - return LEAVE_ITEM; - } - return DISPENSE_ITEM; - } - - break; - // TU12 - case Item::minecart_Id: - case Item::minecart_chest_Id: - case Item::minecart_furnace_Id: - { - xp = x + (xd < 0 ? xd * 0.8 : xd * 1.8f) + Mth::abs(zd) * 0.5f; - zp = z + (zd < 0 ? zd * 0.8 : zd * 1.8f) + Mth::abs(xd) * 0.5f; - - if (RailTile::isRail(level, x + xd, y, z + zd)) - { - yp = y + 0.5f; - } - else if (level->isEmptyTile(x + xd, y, z + zd) && RailTile::isRail(level, x + xd, y - 1, z + zd)) - { - yp = y - 0.5f; - } - else - { - return DISPENSE_ITEM; - } - - if( level->countInstanceOf(eTYPE_MINECART, true) < Level::MAX_CONSOLE_MINECARTS ) // 4J - added limit - { - std::shared_ptr minecart = std::shared_ptr(new Minecart(level, xp, yp, zp, ((MinecartItem *) item->getItem())->type)); - level->addEntity(minecart); - level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); - - return REMOVE_ITEM; - } - else - { - return DISPENSE_ITEM; - } - } - break; - - case Item::boat_Id: - { - bool bLaunchBoat=false; - - xp = x + (xd < 0 ? xd * 0.8 : xd * 1.8f) + Mth::abs(zd) * 0.5f; - zp = z + (zd < 0 ? zd * 0.8 : zd * 1.8f) + Mth::abs(xd) * 0.5f; - - if (level->getMaterial(x + xd, y, z + zd) == Material::water) - { - bLaunchBoat=true; - yp = y + 1.0f; - } - else if (level->isEmptyTile(x + xd, y, z + zd) && level->getMaterial(x + xd, y - 1, z + zd) == Material::water) - { - bLaunchBoat=true; - yp = y; - } - - // check the limit on boats - if( bLaunchBoat && level->countInstanceOf(eTYPE_BOAT, true) < Level::MAX_XBOX_BOATS ) // 4J - added limit - { - std::shared_ptr boat = std::shared_ptr(new Boat(level, xp, yp, zp)); - level->addEntity(boat); - level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); - return REMOVE_ITEM; - } - else - { - return DISPENSE_ITEM; - } - } - break; - } - - return DISPENSE_ITEM; + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::snowBall_Id: { + int currentProjectiles = + level->countInstanceOf(eTYPE_PROJECTILE, false); + if (currentProjectiles < + Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit + { + std::shared_ptr snowball = + std::shared_ptr(new Snowball(level, xp, yp, zp)); + snowball->shoot(xd, .1f, zd, power, (float)accuracy); + level->addEntity(snowball); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::potion_Id: { + int currentProjectiles = + level->countInstanceOf(eTYPE_PROJECTILE, false); + if (currentProjectiles < + Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit + { + if (PotionItem::isThrowable(item->getAuxValue())) { + std::shared_ptr potion = + std::shared_ptr(new ThrownPotion( + level, xp, yp, zp, item->getAuxValue())); + potion->shoot(xd, .1f, zd, power * 1.25f, accuracy * .5f); + level->addEntity(potion); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + } else { + std::shared_ptr itemEntity = + std::shared_ptr( + new ItemEntity(level, xp, yp - 0.3, zp, item)); + + double pow = random->nextDouble() * 0.1 + 0.2; + itemEntity->xd = xd * pow; + itemEntity->yd = .2f; + itemEntity->zd = zd * pow; + + itemEntity->xd += + (random->nextGaussian()) * 0.0075f * accuracy; + itemEntity->yd += + (random->nextGaussian()) * 0.0075f * accuracy; + itemEntity->zd += + (random->nextGaussian()) * 0.0075f * accuracy; + + level->addEntity(itemEntity); + level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); + } + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::expBottle_Id: { + int currentProjectiles = + level->countInstanceOf(eTYPE_PROJECTILE, false); + if (currentProjectiles < + Level::MAX_DISPENSABLE_PROJECTILES) // 4J - added limit + { + std::shared_ptr expBottle = + std::shared_ptr( + new ThrownExpBottle(level, xp, yp, zp)); + expBottle->shoot(xd, .1f, zd, power * 1.25f, accuracy * .5f); + level->addEntity(expBottle); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::fireball_Id: // TU9 + { + int currentFireballs = + level->countInstanceOf(eTYPE_SMALL_FIREBALL, true); + if (currentFireballs < + Level::MAX_DISPENSABLE_FIREBALLS) // 4J - added limit + { + std::shared_ptr fireball = + std::shared_ptr( + new SmallFireball(level, xp + xd * .3, yp, zp + zd * .3, + xd + random->nextGaussian() * .05, + random->nextGaussian() * .05, + zd + random->nextGaussian() * .05)); + level->addEntity(fireball); + level->levelEvent(LevelEvent::SOUND_BLAZE_FIREBALL, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::monsterPlacer_Id: { + int iResult = 0; + // MonsterPlacerItem *spawnEgg = (MonsterPlacerItem + // *)item->getItem(); + std::shared_ptr newEntity = MonsterPlacerItem::canSpawn( + item->getAuxValue(), level, &iResult); + + std::shared_ptr mob = + std::dynamic_pointer_cast(newEntity); + if (mob != NULL) { + // 4J-PB - Changed the line below slightly since mobs were + // sticking to the dispenser rather than dropping down when + // fired + mob->moveTo(xp + xd * 0.4, yp - 0.3, zp + zd * 0.4, + level->random->nextFloat() * 360, 0); + mob->finalizeMobSpawn(); + level->addEntity(mob); + level->levelEvent(LevelEvent::SOUND_LAUNCH, x, y, z, 0); + return REMOVE_ITEM; + } else { + // some negative sound effect? + level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + + // not sending a message here, since we will probably get + // flooded with them when people have automatic dispensers for + // spawn eggs + return LEAVE_ITEM; + } + } break; + case Item::bucket_lava_Id: + case Item::bucket_water_Id: { + BucketItem* pBucket = (BucketItem*)item->getItem(); + + if (pBucket->emptyBucket(level, x, y, z, x + xd, y, z + zd)) { + item->id = Item::bucket_empty_Id; + item->count = 1; + return LEAVE_ITEM; + } + return DISPENSE_ITEM; + } break; + case Item::bucket_empty_Id: { + int xt = x + xd; + int zt = z + zd; + Material* pMaterial = level->getMaterial(xt, y, zt); + int data = level->getData(xt, y, zt); + + if (pMaterial == Material::water && data == 0) { + level->setTile(xt, y, zt, 0); + + if (--item->count == 0) { + item->id = Item::bucket_water_Id; + item->count = 1; + } else if (trap->addItem(std::shared_ptr( + new ItemInstance(Item::bucket_water))) < 0) { + throwItem(level, + std::shared_ptr( + new ItemInstance(Item::bucket_water)), + random, 6, xd, zd, xp, yp, zp); + } + + return LEAVE_ITEM; + } else if (pMaterial == Material::lava && data == 0) { + level->setTile(xt, y, zt, 0); + + if (--item->count == 0) { + item->id = Item::bucket_lava_Id; + item->count = 1; + } else if (trap->addItem(std::shared_ptr( + new ItemInstance(Item::bucket_lava))) < 0) { + throwItem(level, + std::shared_ptr( + new ItemInstance(Item::bucket_lava)), + random, 6, xd, zd, xp, yp, zp); + } + + return LEAVE_ITEM; + } + return DISPENSE_ITEM; + } + + break; + // TU12 + case Item::minecart_Id: + case Item::minecart_chest_Id: + case Item::minecart_furnace_Id: { + xp = x + (xd < 0 ? xd * 0.8 : xd * 1.8f) + Mth::abs(zd) * 0.5f; + zp = z + (zd < 0 ? zd * 0.8 : zd * 1.8f) + Mth::abs(xd) * 0.5f; + + if (RailTile::isRail(level, x + xd, y, z + zd)) { + yp = y + 0.5f; + } else if (level->isEmptyTile(x + xd, y, z + zd) && + RailTile::isRail(level, x + xd, y - 1, z + zd)) { + yp = y - 0.5f; + } else { + return DISPENSE_ITEM; + } + + if (level->countInstanceOf(eTYPE_MINECART, true) < + Level::MAX_CONSOLE_MINECARTS) // 4J - added limit + { + std::shared_ptr minecart = std::shared_ptr( + new Minecart(level, xp, yp, zp, + ((MinecartItem*)item->getItem())->type)); + level->addEntity(minecart); + level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); + + return REMOVE_ITEM; + } else { + return DISPENSE_ITEM; + } + } break; + + case Item::boat_Id: { + bool bLaunchBoat = false; + + xp = x + (xd < 0 ? xd * 0.8 : xd * 1.8f) + Mth::abs(zd) * 0.5f; + zp = z + (zd < 0 ? zd * 0.8 : zd * 1.8f) + Mth::abs(xd) * 0.5f; + + if (level->getMaterial(x + xd, y, z + zd) == Material::water) { + bLaunchBoat = true; + yp = y + 1.0f; + } else if (level->isEmptyTile(x + xd, y, z + zd) && + level->getMaterial(x + xd, y - 1, z + zd) == + Material::water) { + bLaunchBoat = true; + yp = y; + } + + // check the limit on boats + if (bLaunchBoat && level->countInstanceOf(eTYPE_BOAT, true) < + Level::MAX_XBOX_BOATS) // 4J - added limit + { + std::shared_ptr boat = + std::shared_ptr(new Boat(level, xp, yp, zp)); + level->addEntity(boat); + level->levelEvent(LevelEvent::SOUND_CLICK, x, y, z, 0); + return REMOVE_ITEM; + } else { + return DISPENSE_ITEM; + } + } break; + } + + return DISPENSE_ITEM; } diff --git a/Minecraft.World/Blocks/DispenserTile.h b/Minecraft.World/Blocks/DispenserTile.h index d36967dbc..4caa43963 100644 --- a/Minecraft.World/Blocks/DispenserTile.h +++ b/Minecraft.World/Blocks/DispenserTile.h @@ -4,55 +4,63 @@ class Player; class Mob; class ChunkRebuildData; -class DispenserTile : public EntityTile -{ - friend class Tile; - friend class ChunkRebuildData; +class DispenserTile : public EntityTile { + friend class Tile; + friend class ChunkRebuildData; private: - static const int DISPENSE_ITEM = 0; + static const int DISPENSE_ITEM = 0; static const int REMOVE_ITEM = 1; static const int LEAVE_ITEM = 2; public: - static const int FACING_MASK = 0x7; + static const int FACING_MASK = 0x7; protected: - Random *random; + Random* random; - Icon *iconTop; - Icon *iconFront; - Icon *iconFrontVertical; + Icon* iconTop; + Icon* iconFront; + Icon* iconFrontVertical; protected: - DispenserTile(int id); + DispenserTile(int id); public: - virtual int getTickDelay(); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void onPlace(Level *level, int x, int y, int z); + virtual int getTickDelay(); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void onPlace(Level* level, int x, int y, int z); private: - void recalcLockDir(Level *level, int x, int y, int z); + void recalcLockDir(Level* level, int x, int y, int z); public: - virtual Icon *getTexture(int face, int data); - //@Override - void registerIcons(IconRegister *iconRegister); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + virtual Icon* getTexture(int face, int data); + //@Override + void registerIcons(IconRegister* iconRegister); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param private: - void fireArrow(Level *level, int x, int y, int z, Random *random); + void fireArrow(Level* level, int x, int y, int z, Random* random); public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual std::shared_ptr newTileEntity(Level *level); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual std::shared_ptr newTileEntity(Level* level); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); private: - static void throwItem(Level *level, std::shared_ptr item, Random *random, int accuracy, int xd, int zd, double xp, double yp, double zp); - static int dispenseItem(std::shared_ptr trap, Level *level, std::shared_ptr item, Random *random, int x, int y, int z, int xd, int zd, double xp, double yp, double zp); + static void throwItem(Level* level, std::shared_ptr item, + Random* random, int accuracy, int xd, int zd, + double xp, double yp, double zp); + static int dispenseItem(std::shared_ptr trap, + Level* level, std::shared_ptr item, + Random* random, int x, int y, int z, int xd, int zd, + double xp, double yp, double zp); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/DoorTile.cpp b/Minecraft.World/Blocks/DoorTile.cpp index 203ec2175..3552377b6 100644 --- a/Minecraft.World/Blocks/DoorTile.cpp +++ b/Minecraft.World/Blocks/DoorTile.cpp @@ -8,334 +8,286 @@ #include "../Headers/net.minecraft.world.h" #include "../Headers/net.minecraft.h" -const std::wstring DoorTile::TEXTURES[] = { L"doorWood_lower", L"doorWood_upper", L"doorIron_lower", L"doorIron_upper" }; +const std::wstring DoorTile::TEXTURES[] = { + L"doorWood_lower", L"doorWood_upper", L"doorIron_lower", L"doorIron_upper"}; -DoorTile::DoorTile(int id, Material *material) : Tile(id, material, false) -{ - icons = NULL; +DoorTile::DoorTile(int id, Material* material) : Tile(id, material, false) { + icons = NULL; - if (material == Material::metal) - { - texBase = 2; - } - else - { - texBase = 0; - } + if (material == Material::metal) { + texBase = 2; + } else { + texBase = 0; + } - float r = 0.5f; - float h = 1.0f; - Tile::setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); + float r = 0.5f; + float h = 1.0f; + Tile::setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); } -Icon *DoorTile::getTexture(int face, int data) -{ - return icons[texBase]; +Icon* DoorTile::getTexture(int face, int data) { return icons[texBase]; } + +Icon* DoorTile::getTexture(LevelSource* level, int x, int y, int z, int face) { + if (face == Facing::UP || face == Facing::DOWN) return icons[texBase]; + + int compositeData = getCompositeData(level, x, y, z); + int dir = compositeData & C_DIR_MASK; + bool isOpen = (compositeData & C_OPEN_MASK) != 0; + bool flip = false; + bool upper = (compositeData & C_IS_UPPER_MASK) != 0; + + if (isOpen) { + if (dir == 0 && face == 2) + flip = !flip; + else if (dir == 1 && face == 5) + flip = !flip; + else if (dir == 2 && face == 3) + flip = !flip; + else if (dir == 3 && face == 4) + flip = !flip; + } else { + if (dir == 0 && face == 5) + flip = !flip; + else if (dir == 1 && face == 3) + flip = !flip; + else if (dir == 2 && face == 4) + flip = !flip; + else if (dir == 3 && face == 2) + flip = !flip; + if ((compositeData & C_RIGHT_HINGE_MASK) != 0) flip = !flip; + } + + return icons[texBase + (flip ? DOOR_TILE_TEXTURE_COUNT : 0) + + (upper ? 1 : 0)]; } -Icon *DoorTile::getTexture(LevelSource *level, int x, int y, int z, int face) -{ - if (face == Facing::UP || face == Facing::DOWN) return icons[texBase]; +void DoorTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[DOOR_TILE_TEXTURE_COUNT * 2]; - int compositeData = getCompositeData(level, x, y, z); - int dir = compositeData & C_DIR_MASK; - bool isOpen = (compositeData & C_OPEN_MASK) != 0; - bool flip = false; - bool upper = (compositeData & C_IS_UPPER_MASK) != 0; - - if (isOpen) - { - if (dir == 0 && face == 2) flip = !flip; - else if (dir == 1 && face == 5) flip = !flip; - else if (dir == 2 && face == 3) flip = !flip; - else if (dir == 3 && face == 4) flip = !flip; - } - else - { - if (dir == 0 && face == 5) flip = !flip; - else if (dir == 1 && face == 3) flip = !flip; - else if (dir == 2 && face == 4) flip = !flip; - else if (dir == 3 && face == 2) flip = !flip; - if ((compositeData & C_RIGHT_HINGE_MASK) != 0) flip = !flip; - } - - return icons[texBase + (flip ? DOOR_TILE_TEXTURE_COUNT : 0) + (upper ? 1 : 0)]; + for (int i = 0; i < DOOR_TILE_TEXTURE_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURES[i]); + icons[i + DOOR_TILE_TEXTURE_COUNT] = + new FlippedIcon(icons[i], true, false); + } } -void DoorTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[DOOR_TILE_TEXTURE_COUNT * 2]; +bool DoorTile::blocksLight() { return false; } - for (int i = 0; i < DOOR_TILE_TEXTURE_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURES[i]); - icons[i + DOOR_TILE_TEXTURE_COUNT] = new FlippedIcon(icons[i], true, false); - } +bool DoorTile::isSolidRender(bool isServerLevel) { return false; } + +bool DoorTile::isCubeShaped() { return false; } + +int DoorTile::getRenderShape() { return Tile::SHAPE_DOOR; } + +AABB* DoorTile::getTileAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + AABB* retval = Tile::getTileAABB(level, x, y, z); + return retval; } -bool DoorTile::blocksLight() -{ - return false; +AABB* DoorTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + AABB* retval = Tile::getAABB(level, x, y, z); + return retval; } -bool DoorTile::isSolidRender(bool isServerLevel) +void DoorTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - return false; + setShape(getCompositeData(level, x, y, z)); } -bool DoorTile::isCubeShaped() -{ - return false; +int DoorTile::getDir(LevelSource* level, int x, int y, int z) { + return getCompositeData(level, x, y, z) & C_DIR_MASK; } -int DoorTile::getRenderShape() -{ - return Tile::SHAPE_DOOR; +bool DoorTile::isOpen(LevelSource* level, int x, int y, int z) { + return (getCompositeData(level, x, y, z) & C_OPEN_MASK) != 0; } -AABB *DoorTile::getTileAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - AABB *retval = Tile::getTileAABB(level, x, y, z); - return retval; +void DoorTile::setShape(int compositeData) { + float r = 3 / 16.0f; + Tile::setShape(0, 0, 0, 1, 2, 1); + int dir = compositeData & C_DIR_MASK; + bool open = (compositeData & C_OPEN_MASK) != 0; + bool hasRightHinge = (compositeData & C_RIGHT_HINGE_MASK) != 0; + if (dir == 0) { + if (open) { + if (!hasRightHinge) + setShape(0, 0, 0, 1, 1, r); + else + setShape(0, 0, 1 - r, 1, 1, 1); + } else + setShape(0, 0, 0, r, 1, 1); + } else if (dir == 1) { + if (open) { + if (!hasRightHinge) + setShape(1 - r, 0, 0, 1, 1, 1); + else + setShape(0, 0, 0, r, 1, 1); + } else + setShape(0, 0, 0, 1, 1, r); + } else if (dir == 2) { + if (open) { + if (!hasRightHinge) + setShape(0, 0, 1 - r, 1, 1, 1); + else + setShape(0, 0, 0, 1, 1, r); + } else + setShape(1 - r, 0, 0, 1, 1, 1); + } else if (dir == 3) { + if (open) { + if (!hasRightHinge) + setShape(0, 0, 0, r, 1, 1); + else + setShape(1 - r, 0, 0, 1, 1, 1); + } else + setShape(0, 0, 1 - r, 1, 1, 1); + } } -AABB *DoorTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - AABB *retval = Tile::getAABB(level, x, y, z); - return retval; -} - -void DoorTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - setShape(getCompositeData(level,x, y, z)); -} - -int DoorTile::getDir(LevelSource *level, int x, int y, int z) -{ - return getCompositeData(level, x, y, z) & C_DIR_MASK; -} - -bool DoorTile::isOpen(LevelSource *level, int x, int y, int z) -{ - return (getCompositeData(level, x, y, z) & C_OPEN_MASK) != 0; -} - -void DoorTile::setShape(int compositeData) -{ - float r = 3 / 16.0f; - Tile::setShape(0, 0, 0, 1, 2, 1); - int dir = compositeData & C_DIR_MASK; - bool open = (compositeData & C_OPEN_MASK) != 0; - bool hasRightHinge = (compositeData & C_RIGHT_HINGE_MASK) != 0; - if (dir == 0) - { - if (open) - { - if (!hasRightHinge) setShape(0, 0, 0, 1, 1, r); - else setShape(0, 0, 1 - r, 1, 1, 1); - } - else setShape(0, 0, 0, r, 1, 1); - } - else if (dir == 1) - { - if (open) - { - if (!hasRightHinge) setShape(1 - r, 0, 0, 1, 1, 1); - else setShape(0, 0, 0, r, 1, 1); - } - else setShape(0, 0, 0, 1, 1, r); - } - else if (dir == 2) - { - if (open) - { - if (!hasRightHinge) setShape(0, 0, 1 - r, 1, 1, 1); - else setShape(0, 0, 0, 1, 1, r); - } - else setShape(1 - r, 0, 0, 1, 1, 1); - } - else if (dir == 3) - { - if (open) - { - if (!hasRightHinge) setShape(0, 0, 0, r, 1, 1); - else setShape(1 - r, 0, 0, 1, 1, 1); - } - else setShape(0, 0, 1 - r, 1, 1, 1); - } -} - -void DoorTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - // Fix for #92957 - TU11: Content: Multiplayer: Wooden Doors splits in half and glitch in open / close motion while being mined. - // In lastest PC version this is commented out, so do that now to fix bug above - //use(level, x, y, z, player); +void DoorTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + // Fix for #92957 - TU11: Content: Multiplayer: Wooden Doors splits in half + // and glitch in open / close motion while being mined. In lastest PC + // version this is commented out, so do that now to fix bug above + // use(level, x, y, z, player); } // 4J-PB - Adding a TestUse for tooltip display -bool DoorTile::TestUse() +bool DoorTile::TestUse() { return true; } + +bool DoorTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (soundOnly) { + // 4J - added - just do enough to play the sound + if (material != Material::metal) { + level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + } + return false; + } + + if (material == Material::metal) return true; + + int compositeData = getCompositeData(level, x, y, z); + int lowerData = compositeData & C_LOWER_DATA_MASK; + lowerData ^= 4; + if ((compositeData & C_IS_UPPER_MASK) == 0) { + level->setData(x, y, z, lowerData); //, Tile.UPDATE_CLIENTS); + level->setTilesDirty(x, y, z, x, y, z); + } else { + level->setData(x, y - 1, z, lowerData); //, Tile.UPDATE_CLIENTS); + level->setTilesDirty(x, y - 1, z, x, y, z); + } + + level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + return true; } -bool DoorTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if(soundOnly) - { - // 4J - added - just do enough to play the sound - if (material != Material::metal) - { - level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - } - return false; - } +void DoorTile::setOpen(Level* level, int x, int y, int z, bool shouldOpen) { + int compositeData = getCompositeData(level, x, y, z); + bool isOpen = (compositeData & C_OPEN_MASK) != 0; + if (isOpen == shouldOpen) return; - if (material == Material::metal) return true; + int lowerData = compositeData & C_LOWER_DATA_MASK; + lowerData ^= 4; + if ((compositeData & C_IS_UPPER_MASK) == 0) { + level->setData(x, y, z, lowerData); //, Tile.UPDATE_CLIENTS); + level->setTilesDirty(x, y, z, x, y, z); + } else { + level->setData(x, y - 1, z, lowerData); //, Tile.UPDATE_CLIENTS); + level->setTilesDirty(x, y - 1, z, x, y, z); + } - int compositeData = getCompositeData(level, x, y, z); - int lowerData = compositeData & C_LOWER_DATA_MASK; - lowerData ^= 4; - if ((compositeData & C_IS_UPPER_MASK) == 0) - { - level->setData(x, y, z, lowerData);//, Tile.UPDATE_CLIENTS); - level->setTilesDirty(x, y, z, x, y, z); - } - else - { - level->setData(x, y - 1, z, lowerData);//, Tile.UPDATE_CLIENTS); - level->setTilesDirty(x, y - 1, z, x, y, z); - } - - level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - return true; + level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); } -void DoorTile::setOpen(Level *level, int x, int y, int z, bool shouldOpen) -{ - int compositeData = getCompositeData(level, x, y, z); - bool isOpen = (compositeData & C_OPEN_MASK) != 0; - if (isOpen == shouldOpen) return; - - int lowerData = compositeData & C_LOWER_DATA_MASK; - lowerData ^= 4; - if ((compositeData & C_IS_UPPER_MASK) == 0) - { - level->setData(x, y, z, lowerData);//, Tile.UPDATE_CLIENTS); - level->setTilesDirty(x, y, z, x, y, z); - } - else - { - level->setData(x, y - 1, z, lowerData);//, Tile.UPDATE_CLIENTS); - level->setTilesDirty(x, y - 1, z, x, y, z); - } - - level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); +void DoorTile::neighborChanged(Level* level, int x, int y, int z, int type) { + int data = level->getData(x, y, z); + if ((data & UPPER_BIT) == 0) { + bool spawn = false; + if (level->getTile(x, y + 1, z) != id) { + level->setTile(x, y, z, 0); + spawn = true; + } + if (!level->isSolidBlockingTile(x, y - 1, z)) { + level->setTile(x, y, z, 0); + spawn = true; + if (level->getTile(x, y + 1, z) == id) { + level->setTile(x, y + 1, z, 0); + } + } + if (spawn) { + if (!level->isClientSide) { + spawnResources(level, x, y, z, data, 0); + } + } else { + bool signal = level->hasNeighborSignal(x, y, z) || + level->hasNeighborSignal(x, y + 1, z); + if ((signal || (type > 0 && Tile::tiles[type]->isSignalSource())) && + type != id) { + setOpen(level, x, y, z, signal); + } + } + } else { + if (level->getTile(x, y - 1, z) != id) { + level->setTile(x, y, z, 0); + } + if (type > 0 && type != id) { + neighborChanged(level, x, y - 1, z, type); + } + } } -void DoorTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - int data = level->getData(x, y, z); - if ((data & UPPER_BIT) == 0) - { - bool spawn = false; - if (level->getTile(x, y + 1, z) != id) - { - level->setTile(x, y, z, 0); - spawn = true; - } - if (!level->isSolidBlockingTile(x, y - 1, z)) - { - level->setTile(x, y, z, 0); - spawn = true; - if (level->getTile(x, y + 1, z) == id) - { - level->setTile(x, y + 1, z, 0); - } - } - if (spawn) - { - if (!level->isClientSide) - { - spawnResources(level, x, y, z, data, 0); - } - } - else - { - bool signal = level->hasNeighborSignal(x, y, z) || level->hasNeighborSignal(x, y + 1, z); - if ((signal || (type > 0 && Tile::tiles[type]->isSignalSource())) && type != id) - { - setOpen(level, x, y, z, signal); - } - } - } - else - { - if (level->getTile(x, y - 1, z) != id) - { - level->setTile(x, y, z, 0); - } - if (type > 0 && type != id) - { - neighborChanged(level, x, y - 1, z, type); - } - } +int DoorTile::getResource(int data, Random* random, int playerBonusLevel) { + if ((data & 8) != 0) return 0; + if (material == Material::metal) return Item::door_iron->id; + return Item::door_wood->id; } -int DoorTile::getResource(int data, Random *random, int playerBonusLevel) -{ - if ((data & 8) != 0) return 0; - if (material == Material::metal) return Item::door_iron->id; - return Item::door_wood->id; +HitResult* DoorTile::clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b) { + updateShape(level, xt, yt, zt); + return Tile::clip(level, xt, yt, zt, a, b); } -HitResult *DoorTile::clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b) -{ - updateShape(level, xt, yt, zt); - return Tile::clip(level, xt, yt, zt, a, b); +bool DoorTile::mayPlace(Level* level, int x, int y, int z) { + if (y >= Level::maxBuildHeight - 1) return false; + + return (level->isTopSolidBlocking(x, y - 1, z) && + Tile::mayPlace(level, x, y, z) && + Tile::mayPlace(level, x, y + 1, z)); } -bool DoorTile::mayPlace(Level *level, int x, int y, int z) -{ - if (y >= Level::maxBuildHeight - 1) return false; +bool DoorTile::isOpen(int data) { return (data & 4) != 0; } - return (level->isTopSolidBlocking(x, y - 1, z) && Tile::mayPlace(level, x, y, z) && Tile::mayPlace(level, x, y + 1, z)); +int DoorTile::getPistonPushReaction() { return Material::PUSH_DESTROY; } + +int DoorTile::getCompositeData(LevelSource* level, int x, int y, int z) { + int data = level->getData(x, y, z); + bool isUpper = (data & UPPER_BIT) != 0; + int lowerData; + int upperData; + if (isUpper) { + lowerData = level->getData(x, y - 1, z); + upperData = data; + } else { + lowerData = data; + upperData = level->getData(x, y + 1, z); + } + + // bits: dir, dir, open/closed, isUpper, isRightHinge + bool isRightHinge = (upperData & 1) != 0; + return (lowerData & C_LOWER_DATA_MASK) | (isUpper ? 8 : 0) | + (isRightHinge ? 16 : 0); } -bool DoorTile::isOpen(int data) -{ - return (data & 4) != 0; -} - -int DoorTile::getPistonPushReaction() -{ - return Material::PUSH_DESTROY; -} - -int DoorTile::getCompositeData(LevelSource *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - bool isUpper = (data & UPPER_BIT) != 0; - int lowerData; - int upperData; - if (isUpper) - { - lowerData = level->getData(x, y - 1, z); - upperData = data; - } - else - { - lowerData = data; - upperData = level->getData(x, y + 1, z); - } - - // bits: dir, dir, open/closed, isUpper, isRightHinge - bool isRightHinge = (upperData & 1) != 0; - return (lowerData & C_LOWER_DATA_MASK) | (isUpper ? 8 : 0) | (isRightHinge ? 16 : 0); -} - -int DoorTile::cloneTileId(Level *level, int x, int y, int z) -{ - return material == Material::metal ? Item::door_iron_Id : Item::door_wood_Id; +int DoorTile::cloneTileId(Level* level, int x, int y, int z) { + return material == Material::metal ? Item::door_iron_Id + : Item::door_wood_Id; } diff --git a/Minecraft.World/Blocks/DoorTile.h b/Minecraft.World/Blocks/DoorTile.h index 14c68b7ed..618a72a3f 100644 --- a/Minecraft.World/Blocks/DoorTile.h +++ b/Minecraft.World/Blocks/DoorTile.h @@ -6,55 +6,66 @@ class Player; class HitResult; class ChunkRebuildData; -class DoorTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class DoorTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; + public: - static const int UPPER_BIT = 8; - static const int C_DIR_MASK = 3; - static const int C_OPEN_MASK = 4; - static const int C_LOWER_DATA_MASK = 7; - static const int C_IS_UPPER_MASK = 8; - static const int C_RIGHT_HINGE_MASK = 16; + static const int UPPER_BIT = 8; + static const int C_DIR_MASK = 3; + static const int C_OPEN_MASK = 4; + static const int C_LOWER_DATA_MASK = 7; + static const int C_IS_UPPER_MASK = 8; + static const int C_RIGHT_HINGE_MASK = 16; private: - static const int DOOR_TILE_TEXTURE_COUNT = 4; - static const std::wstring TEXTURES[]; - int texBase; - Icon **icons; + static const int DOOR_TILE_TEXTURE_COUNT = 4; + static const std::wstring TEXTURES[]; + int texBase; + Icon** icons; protected: - DoorTile(int id, Material *material); + DoorTile(int id, Material* material); + public: - virtual Icon *getTexture(int face, int data); - //@Override - Icon *getTexture(LevelSource *level, int x, int y, int z, int face); - //@Override - void registerIcons(IconRegister *iconRegister); - virtual bool blocksLight(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual bool isCubeShaped(); - virtual int getRenderShape(); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - int getDir(LevelSource *level, int x, int y, int z); - bool isOpen(LevelSource *level, int x, int y, int z); + virtual Icon* getTexture(int face, int data); + //@Override + Icon* getTexture(LevelSource* level, int x, int y, int z, int face); + //@Override + void registerIcons(IconRegister* iconRegister); + virtual bool blocksLight(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual bool isCubeShaped(); + virtual int getRenderShape(); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + int getDir(LevelSource* level, int x, int y, int z); + bool isOpen(LevelSource* level, int x, int y, int z); + private: - using Tile::setShape; - virtual void setShape(int compositeData); + using Tile::setShape; + virtual void setShape(int compositeData); + public: - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - void setOpen(Level *level, int x, int y, int z, bool shouldOpen); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual HitResult *clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b); - virtual bool mayPlace(Level *level, int x, int y, int z); - static bool isOpen(int data); - virtual int getPistonPushReaction(); - int getCompositeData(LevelSource *level, int x, int y, int z); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + void setOpen(Level* level, int x, int y, int z, bool shouldOpen); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual HitResult* clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b); + virtual bool mayPlace(Level* level, int x, int y, int z); + static bool isOpen(int data); + virtual int getPistonPushReaction(); + int getCompositeData(LevelSource* level, int x, int y, int z); + virtual int cloneTileId(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/EggTile.cpp b/Minecraft.World/Blocks/EggTile.cpp index 705ef05fb..be52a29fc 100644 --- a/Minecraft.World/Blocks/EggTile.cpp +++ b/Minecraft.World/Blocks/EggTile.cpp @@ -4,170 +4,152 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "../Headers/net.minecraft.world.entity.item.h" -EggTile::EggTile(int id) : Tile(id, Material::egg, false) -{ +EggTile::EggTile(int id) : Tile(id, Material::egg, false) {} + +void EggTile::onPlace(Level* level, int x, int y, int z) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); } -void EggTile::onPlace(Level *level, int x, int y, int z) -{ - level->addToTickNextTick(x, y, z, id, getTickDelay()); +void EggTile::neighborChanged(Level* level, int x, int y, int z, int type) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); } -void EggTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - level->addToTickNextTick(x, y, z, id, getTickDelay()); +void EggTile::tick(Level* level, int x, int y, int z, Random* random) { + checkSlide(level, x, y, z); } -void EggTile::tick(Level *level, int x, int y, int z, Random *random) -{ - checkSlide(level, x, y, z); +void EggTile::checkSlide(Level* level, int x, int y, int z) { + if (HeavyTile::isFree(level, x, y - 1, z) && y >= 0) { + int r = 32; + if (HeavyTile::instaFall || + !level->hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) { + level->setTile(x, y, z, 0); + while (HeavyTile::isFree(level, x, y - 1, z) && y > 0) y--; + if (y > 0) { + level->setTile(x, y, z, id); + } + } else { + std::shared_ptr e = std::shared_ptr( + new FallingTile(level, x + 0.5f, y + 0.5f, z + 0.5f, id)); + level->addEntity(e); + } + } } -void EggTile::checkSlide(Level *level, int x, int y, int z) +bool EggTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, float clickX, + float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if (HeavyTile::isFree(level, x, y - 1, z) && y >= 0) - { - int r = 32; - if (HeavyTile::instaFall || !level->hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) - { - level->setTile(x, y, z, 0); - while (HeavyTile::isFree(level, x, y - 1, z) && y > 0) - y--; - if (y > 0) - { - level->setTile(x, y, z, id); - } - } - else - { - std::shared_ptr e = std::shared_ptr(new FallingTile(level, x + 0.5f, y + 0.5f, z + 0.5f, id)); - level->addEntity(e); - } - } -} - -bool EggTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if(soundOnly) return false; + if (soundOnly) return false; teleport(level, x, y, z); return true; } -void EggTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - teleport(level, x, y, z); +void EggTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + teleport(level, x, y, z); } -void EggTile::teleport(Level *level, int x, int y, int z) -{ - if (level->getTile(x, y, z) != id) return; +void EggTile::teleport(Level* level, int x, int y, int z) { + if (level->getTile(x, y, z) != id) return; - for (int i = 0; i < 1000; i++) - { - int xt = x + level->random->nextInt(16) - level->random->nextInt(16); - int yt = y + level->random->nextInt(8) - level->random->nextInt(8); - int zt = z + level->random->nextInt(16) - level->random->nextInt(16); - if (level->getTile(xt, yt, zt) == 0) - { - // Fix for TU9: Content: Art: Dragon egg teleport particle effect isn't present. - // Don't set tiles on client, and don't create particles on the server (matches later change in Java) - if(!level->isClientSide) - { - level->setTileAndData(xt, yt, zt, id, level->getData(x, y, z)); - level->setTile(x, y, z, 0); + for (int i = 0; i < 1000; i++) { + int xt = x + level->random->nextInt(16) - level->random->nextInt(16); + int yt = y + level->random->nextInt(8) - level->random->nextInt(8); + int zt = z + level->random->nextInt(16) - level->random->nextInt(16); + if (level->getTile(xt, yt, zt) == 0) { + // Fix for TU9: Content: Art: Dragon egg teleport particle effect + // isn't present. Don't set tiles on client, and don't create + // particles on the server (matches later change in Java) + if (!level->isClientSide) { + level->setTileAndData(xt, yt, zt, id, level->getData(x, y, z)); + level->setTile(x, y, z, 0); - // 4J Stu - The PC version is wrong as the particles calculated on the client side will point towards a different - // location to the one where the egg has actually moved. As the deltas are all small we can pack them into an int - // See generateTeleportParticles for unpacking - char deltaX = x-xt; - char deltaY = y-yt; - char deltaZ = z-zt; - int deltas = 0|(deltaX&0xFF)|((deltaY&0xFF)<<8)|((deltaZ&0xFF)<<16); + // 4J Stu - The PC version is wrong as the particles calculated + // on the client side will point towards a different location to + // the one where the egg has actually moved. As the deltas are + // all small we can pack them into an int See + // generateTeleportParticles for unpacking + char deltaX = x - xt; + char deltaY = y - yt; + char deltaZ = z - zt; + int deltas = 0 | (deltaX & 0xFF) | ((deltaY & 0xFF) << 8) | + ((deltaZ & 0xFF) << 16); - level->levelEvent(LevelEvent::END_EGG_TELEPORT,xt,yt,zt,deltas); - } + level->levelEvent(LevelEvent::END_EGG_TELEPORT, xt, yt, zt, + deltas); + } - // 4J Stu - This code will not work correctly on the client as it will show the particles going in the wrong direction - // and only for the player who attacks the egg - // else - // { - // int count = 128; - // for (int j = 0; j < count; j++) - // { - // double d = level->random->nextDouble(); // j < count / 2 ? 0 : - //// 1; - // float xa = (level->random->nextFloat() - 0.5f) * 0.2f; - // float ya = (level->random->nextFloat() - 0.5f) * 0.2f; - // float za = (level->random->nextFloat() - 0.5f) * 0.2f; + // 4J Stu - This code will not work correctly on the client as it + // will show the particles going in the wrong direction and only for + // the player who attacks the egg + // else + // { + // int count = 128; + // for (int j = 0; j < count; j++) + // { + // double d = level->random->nextDouble(); // j < + //count / 2 ? 0 : + //// 1; + // float xa = (level->random->nextFloat() - 0.5f) * + //0.2f; float ya = (level->random->nextFloat() - 0.5f) * 0.2f; float + //za = (level->random->nextFloat() - 0.5f) * 0.2f; - // double _x = xt + (x - xt) * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; - // double _y = yt + (y - yt) * d + level->random->nextDouble() * 1 - 0.5f; - // double _z = zt + (z - zt) * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; - // level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, za); - // } - // } - return; - } - } + // double _x = xt + (x - xt) * d + + //(level->random->nextDouble() - 0.5) * 1 + 0.5f; double _y = yt + + //(y - yt) * d + level->random->nextDouble() * 1 - 0.5f; double _z = + //zt + (z - zt) * d + (level->random->nextDouble() - 0.5) * 1 + + //0.5f; level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, + //za); + // } + // } + return; + } + } } -int EggTile::getTickDelay() -{ - return 3; +int EggTile::getTickDelay() { return 3; } + +bool EggTile::blocksLight() { return false; } + +bool EggTile::isSolidRender(bool isServerLevel) { return false; } + +bool EggTile::isCubeShaped() { return false; } + +int EggTile::getRenderShape() { return Tile::SHAPE_EGG; } + +int EggTile::cloneTileId(Level* level, int x, int y, int z) { return 0; } + +// 4J Added for Fix for #77475 - TU9: Content: Art: Dragon egg teleport particle +// effect isn't present. +void EggTile::generateTeleportParticles(Level* level, int xt, int yt, int zt, + int deltas) { + int count = 128; + + // See above for packing + char deltaX = deltas & 0xFF; + char deltaY = (deltas >> 8) & 0xFF; + char deltaZ = (deltas >> 16) & 0xFF; + + for (int j = 0; j < count; j++) { + double d = level->random->nextDouble(); // j < count / 2 ? 0 : + // 1; + float xa = (level->random->nextFloat() - 0.5f) * 0.2f; + float ya = (level->random->nextFloat() - 0.5f) * 0.2f; + float za = (level->random->nextFloat() - 0.5f) * 0.2f; + + double _x = + xt + deltaX * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; + double _y = yt + deltaY * d + level->random->nextDouble() * 1 - 0.5f; + double _z = + zt + deltaZ * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; + level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, za); + } } -bool EggTile::blocksLight() -{ - return false; -} - -bool EggTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -bool EggTile::isCubeShaped() -{ - return false; -} - -int EggTile::getRenderShape() -{ - return Tile::SHAPE_EGG; -} - -int EggTile::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; -} - -// 4J Added for Fix for #77475 - TU9: Content: Art: Dragon egg teleport particle effect isn't present. -void EggTile::generateTeleportParticles(Level *level,int xt,int yt, int zt,int deltas) -{ - int count = 128; - - // See above for packing - char deltaX = deltas&0xFF; - char deltaY = (deltas>>8)&0xFF; - char deltaZ = (deltas>>16)&0xFF; - - for (int j = 0; j < count; j++) - { - double d = level->random->nextDouble(); // j < count / 2 ? 0 : - // 1; - float xa = (level->random->nextFloat() - 0.5f) * 0.2f; - float ya = (level->random->nextFloat() - 0.5f) * 0.2f; - float za = (level->random->nextFloat() - 0.5f) * 0.2f; - - double _x = xt + deltaX * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; - double _y = yt + deltaY * d + level->random->nextDouble() * 1 - 0.5f; - double _z = zt + deltaZ * d + (level->random->nextDouble() - 0.5) * 1 + 0.5f; - level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, za); - } -} - -bool EggTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - return true; +bool EggTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + return true; } diff --git a/Minecraft.World/Blocks/EggTile.h b/Minecraft.World/Blocks/EggTile.h index 7102bd8dd..7984a7cdf 100644 --- a/Minecraft.World/Blocks/EggTile.h +++ b/Minecraft.World/Blocks/EggTile.h @@ -1,29 +1,38 @@ #pragma once #include "Tile.h" -class EggTile : public Tile -{ +class EggTile : public Tile { public: - EggTile(int id); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); + EggTile(int id); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + private: - void checkSlide(Level *level, int x, int y, int z); + void checkSlide(Level* level, int x, int y, int z); + public: - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + private: - void teleport(Level *level, int x, int y, int z); + void teleport(Level* level, int x, int y, int z); + public: - virtual int getTickDelay(); + virtual int getTickDelay(); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); virtual int getRenderShape(); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual int cloneTileId(Level* level, int x, int y, int z); - // 4J Added - static void generateTeleportParticles(Level *level,int xt,int yt, int zt,int deltas); + // 4J Added + static void generateTeleportParticles(Level* level, int xt, int yt, int zt, + int deltas); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/EnchantmentTableTile.cpp b/Minecraft.World/Blocks/EnchantmentTableTile.cpp index 0ab63578f..8c97dc3b5 100644 --- a/Minecraft.World/Blocks/EnchantmentTableTile.cpp +++ b/Minecraft.World/Blocks/EnchantmentTableTile.cpp @@ -9,84 +9,77 @@ const std::wstring EnchantmentTableTile::TEXTURE_SIDE = L"enchantment_side"; const std::wstring EnchantmentTableTile::TEXTURE_TOP = L"enchantment_top"; const std::wstring EnchantmentTableTile::TEXTURE_BOTTOM = L"enchantment_bottom"; -EnchantmentTableTile::EnchantmentTableTile(int id) : EntityTile(id, Material::stone, false) -{ - updateDefaultShape(); +EnchantmentTableTile::EnchantmentTableTile(int id) + : EntityTile(id, Material::stone, false) { + updateDefaultShape(); setLightBlock(0); - iconTop = NULL; - iconBottom = NULL; + iconTop = NULL; + iconBottom = NULL; } // 4J Added override -void EnchantmentTableTile::updateDefaultShape() -{ +void EnchantmentTableTile::updateDefaultShape() { setShape(0, 0, 0, 1, 12 / 16.0f, 1); } -bool EnchantmentTableTile::isCubeShaped() -{ - return false; -} +bool EnchantmentTableTile::isCubeShaped() { return false; } -void EnchantmentTableTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ +void EnchantmentTableTile::animateTick(Level* level, int x, int y, int z, + Random* random) { EntityTile::animateTick(level, x, y, z, random); - for (int xx = x - 2; xx <= x + 2; xx++) - { - for (int zz = z - 2; zz <= z + 2; zz++) - { - if (xx > x - 2 && xx < x + 2 && zz == z - 1) - { + for (int xx = x - 2; xx <= x + 2; xx++) { + for (int zz = z - 2; zz <= z + 2; zz++) { + if (xx > x - 2 && xx < x + 2 && zz == z - 1) { zz = z + 2; } if (random->nextInt(16) != 0) continue; - for (int yy = y; yy <= y + 1; yy++) - { - if (level->getTile(xx, yy, zz) == Tile::bookshelf_Id) - { - if (!level->isEmptyTile((xx - x) / 2 + x, yy, (zz - z) / 2 + z)) break; + for (int yy = y; yy <= y + 1; yy++) { + if (level->getTile(xx, yy, zz) == Tile::bookshelf_Id) { + if (!level->isEmptyTile((xx - x) / 2 + x, yy, + (zz - z) / 2 + z)) + break; - level->addParticle(eParticleType_enchantmenttable, x + 0.5, y + 2.0, z + 0.5, xx - x + random->nextFloat() - 0.5, yy - y - random->nextFloat() - 1, zz - z + random->nextFloat() - 0.5); + level->addParticle(eParticleType_enchantmenttable, x + 0.5, + y + 2.0, z + 0.5, + xx - x + random->nextFloat() - 0.5, + yy - y - random->nextFloat() - 1, + zz - z + random->nextFloat() - 0.5); } } } } } -bool EnchantmentTableTile::isSolidRender(bool isServerLevel) -{ - return false; +bool EnchantmentTableTile::isSolidRender(bool isServerLevel) { return false; } + +Icon* EnchantmentTableTile::getTexture(int face, int data) { + if (face == Facing::DOWN) return iconBottom; + if (face == Facing::UP) return iconTop; + return icon; } -Icon *EnchantmentTableTile::getTexture(int face, int data) -{ - if (face == Facing::DOWN) return iconBottom; - if (face == Facing::UP) return iconTop; - return icon; +std::shared_ptr EnchantmentTableTile::newTileEntity(Level* level) { + return std::shared_ptr(new EnchantmentTableEntity()); } -std::shared_ptr EnchantmentTableTile::newTileEntity(Level *level) +bool EnchantmentTableTile::use( + Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return std::shared_ptr(new EnchantmentTableEntity()); -} + if (soundOnly) return false; -bool EnchantmentTableTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if(soundOnly) return false; - - if (level->isClientSide) - { + if (level->isClientSide) { return true; } player->startEnchanting(x, y, z); return true; } -void EnchantmentTableTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(TEXTURE_SIDE); - iconTop = iconRegister->registerIcon(TEXTURE_TOP); - iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); +void EnchantmentTableTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(TEXTURE_SIDE); + iconTop = iconRegister->registerIcon(TEXTURE_TOP); + iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); } diff --git a/Minecraft.World/Blocks/EnchantmentTableTile.h b/Minecraft.World/Blocks/EnchantmentTableTile.h index 13860d106..ffff6ed29 100644 --- a/Minecraft.World/Blocks/EnchantmentTableTile.h +++ b/Minecraft.World/Blocks/EnchantmentTableTile.h @@ -2,28 +2,30 @@ #include "TileEntities/EntityTile.h" class ChunkRebuildData; -class EnchantmentTableTile : public EntityTile -{ - friend class ChunkRebuildData; +class EnchantmentTableTile : public EntityTile { + friend class ChunkRebuildData; + public: - static const std::wstring TEXTURE_SIDE; - static const std::wstring TEXTURE_TOP; - static const std::wstring TEXTURE_BOTTOM; + static const std::wstring TEXTURE_SIDE; + static const std::wstring TEXTURE_TOP; + static const std::wstring TEXTURE_BOTTOM; private: - Icon *iconTop; - Icon *iconBottom; + Icon* iconTop; + Icon* iconBottom; public: - EnchantmentTableTile(int id); - - virtual void updateDefaultShape(); // 4J Added override - bool isCubeShaped(); - void animateTick(Level *level, int x, int y, int z, Random *random); + EnchantmentTableTile(int id); + + virtual void updateDefaultShape(); // 4J Added override + bool isCubeShaped(); + void animateTick(Level* level, int x, int y, int z, Random* random); bool isSolidRender(bool isServerLevel = false); - Icon *getTexture(int face, int data); - std::shared_ptr newTileEntity(Level *level); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - //@Override - void registerIcons(IconRegister *iconRegister); + Icon* getTexture(int face, int data); + std::shared_ptr newTileEntity(Level* level); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + //@Override + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/EnderChestTile.cpp b/Minecraft.World/Blocks/EnderChestTile.cpp index 2c2d77c84..0c5093308 100644 --- a/Minecraft.World/Blocks/EnderChestTile.cpp +++ b/Minecraft.World/Blocks/EnderChestTile.cpp @@ -7,111 +7,96 @@ #include "../Headers/net.minecraft.h" #include "EnderChestTile.h" -EnderChestTile::EnderChestTile(int id) : EntityTile(id, Material::stone, false) -{ - updateDefaultShape(); +EnderChestTile::EnderChestTile(int id) + : EntityTile(id, Material::stone, false) { + updateDefaultShape(); } // 4J Added override -void EnderChestTile::updateDefaultShape() -{ - setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); +void EnderChestTile::updateDefaultShape() { + setShape(1 / 16.0f, 0, 1 / 16.0f, 15 / 16.0f, 14 / 16.0f, 15 / 16.0f); } -bool EnderChestTile::isSolidRender(bool isServerLevel) -{ - return false; +bool EnderChestTile::isSolidRender(bool isServerLevel) { return false; } + +bool EnderChestTile::isCubeShaped() { return false; } + +int EnderChestTile::getRenderShape() { return Tile::SHAPE_ENTITYTILE_ANIMATED; } + +int EnderChestTile::getResource(int data, Random* random, + int playerBonusLevel) { + return Tile::obsidian_Id; } -bool EnderChestTile::isCubeShaped() -{ - return false; +int EnderChestTile::getResourceCount(Random* random) { return 8; } + +bool EnderChestTile::isSilkTouchable() { return true; } + +void EnderChestTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int facing = 0; + int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5f)) & 3; + + if (dir == 0) facing = Facing::NORTH; + if (dir == 1) facing = Facing::EAST; + if (dir == 2) facing = Facing::SOUTH; + if (dir == 3) facing = Facing::WEST; + + level->setData(x, y, z, facing); } -int EnderChestTile::getRenderShape() -{ - return Tile::SHAPE_ENTITYTILE_ANIMATED; +bool EnderChestTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly) { + std::shared_ptr container = + player->getEnderChestInventory(); + std::shared_ptr enderChest = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (container == NULL || enderChest == NULL) return true; + + if (level->isSolidBlockingTile(x, y + 1, z)) return true; + + if (level->isClientSide) { + return true; + } + + container->setActiveChest(enderChest); + player->openContainer(container); + + return true; } -int EnderChestTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::obsidian_Id; +std::shared_ptr EnderChestTile::newTileEntity(Level* level) { + return std::shared_ptr(new EnderChestTileEntity()); } -int EnderChestTile::getResourceCount(Random *random) -{ - return 8; +void EnderChestTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { + for (int i = 0; i < 3; i++) { + double x = xt + random->nextFloat(); + double y = yt + random->nextFloat(); + double z = zt + random->nextFloat(); + double xa = 0; + double ya = 0; + double za = 0; + int flipX = random->nextInt(2) * 2 - 1; + int flipZ = random->nextInt(2) * 2 - 1; + xa = (random->nextFloat() - 0.5) * 0.125; + ya = (random->nextFloat() - 0.5) * 0.125; + za = (random->nextFloat() - 0.5) * 0.125; + z = zt + 0.5 + (0.25) * flipZ; + za = (random->nextFloat() * 1) * flipZ; + x = xt + 0.5 + (0.25) * flipX; + xa = (random->nextFloat() * 1) * flipX; + + level->addParticle(eParticleType_ender, x, y, z, xa, ya, za); + } } -bool EnderChestTile::isSilkTouchable() -{ - return true; -} - -void EnderChestTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int facing = 0; - int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5f)) & 3; - - if (dir == 0) facing = Facing::NORTH; - if (dir == 1) facing = Facing::EAST; - if (dir == 2) facing = Facing::SOUTH; - if (dir == 3) facing = Facing::WEST; - - level->setData(x, y, z, facing); -} - -bool EnderChestTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly) -{ - std::shared_ptr container = player->getEnderChestInventory(); - std::shared_ptr enderChest = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); - if (container == NULL || enderChest == NULL) return true; - - if (level->isSolidBlockingTile(x, y + 1, z)) return true; - - if (level->isClientSide) - { - return true; - } - - container->setActiveChest(enderChest); - player->openContainer(container); - - return true; -} - -std::shared_ptr EnderChestTile::newTileEntity(Level *level) -{ - return std::shared_ptr(new EnderChestTileEntity()); -} - -void EnderChestTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ - for (int i = 0; i < 3; i++) - { - double x = xt + random->nextFloat(); - double y = yt + random->nextFloat(); - double z = zt + random->nextFloat(); - double xa = 0; - double ya = 0; - double za = 0; - int flipX = random->nextInt(2) * 2 - 1; - int flipZ = random->nextInt(2) * 2 - 1; - xa = (random->nextFloat() - 0.5) * 0.125; - ya = (random->nextFloat() - 0.5) * 0.125; - za = (random->nextFloat() - 0.5) * 0.125; - z = zt + 0.5 + (0.25) * flipZ; - za = (random->nextFloat() * 1) * flipZ; - x = xt + 0.5 + (0.25) * flipX; - xa = (random->nextFloat() * 1) * flipX; - - level->addParticle(eParticleType_ender, x, y, z, xa, ya, za); - } -} - -void EnderChestTile::registerIcons(IconRegister *iconRegister) -{ - // Register obsidian as the chest's icon, because it's used by the - // particles when destroying the chest - icon = iconRegister->registerIcon(L"obsidian"); +void EnderChestTile::registerIcons(IconRegister* iconRegister) { + // Register obsidian as the chest's icon, because it's used by the + // particles when destroying the chest + icon = iconRegister->registerIcon(L"obsidian"); } diff --git a/Minecraft.World/Blocks/EnderChestTile.h b/Minecraft.World/Blocks/EnderChestTile.h index 45074a608..369d97f03 100644 --- a/Minecraft.World/Blocks/EnderChestTile.h +++ b/Minecraft.World/Blocks/EnderChestTile.h @@ -3,27 +3,29 @@ #include "TileEntities/EntityTile.h" #include "ChestTile.h" -class EnderChestTile : public EntityTile -{ +class EnderChestTile : public EntityTile { public: - static const int EVENT_SET_OPEN_COUNT = ChestTile::EVENT_SET_OPEN_COUNT; + static const int EVENT_SET_OPEN_COUNT = ChestTile::EVENT_SET_OPEN_COUNT; - EnderChestTile(int id); - virtual void updateDefaultShape(); // 4J Added override + EnderChestTile(int id); + virtual void updateDefaultShape(); // 4J Added override - bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); - int getRenderShape(); - int getResource(int data, Random *random, int playerBonusLevel); - int getResourceCount(Random *random); + bool isSolidRender(bool isServerLevel = false); + bool isCubeShaped(); + int getRenderShape(); + int getResource(int data, Random* random, int playerBonusLevel); + int getResourceCount(Random* random); protected: - bool isSilkTouchable(); + bool isSilkTouchable(); public: - void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); - std::shared_ptr newTileEntity(Level *level); - void animateTick(Level *level, int xt, int yt, int zt, Random *random); - virtual void registerIcons(IconRegister *iconRegister); + void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); + std::shared_ptr newTileEntity(Level* level); + void animateTick(Level* level, int xt, int yt, int zt, Random* random); + virtual void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/FallingTile.cpp b/Minecraft.World/Blocks/FallingTile.cpp index 2fa6f4d18..89e96dc39 100644 --- a/Minecraft.World/Blocks/FallingTile.cpp +++ b/Minecraft.World/Blocks/FallingTile.cpp @@ -6,235 +6,195 @@ #include "../Headers/com.mojang.nbt.h" #include "FallingTile.h" - - // 4J - added for common ctor code -void FallingTile::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void FallingTile::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - tile = 0; - data = 0; - time = 0; - dropItem = true; - - cancelDrop = false; - hurtEntities = false; - fallDamageMax = 40; - fallDamageAmount = 2; + tile = 0; + data = 0; + time = 0; + dropItem = true; - // 4J Added so that client-side falling tiles can fall through blocks - // This fixes a bug on the host where the tile update from the server comes in before the client-side falling tile - // has reached that level, causing it to stop at one block higher. - m_ignoreVerticalCollisions = level->isClientSide; + cancelDrop = false; + hurtEntities = false; + fallDamageMax = 40; + fallDamageAmount = 2; + + // 4J Added so that client-side falling tiles can fall through blocks + // This fixes a bug on the host where the tile update from the server comes + // in before the client-side falling tile has reached that level, causing it + // to stop at one block higher. + m_ignoreVerticalCollisions = level->isClientSide; } -FallingTile::FallingTile(Level *level) : - Entity( level ) -{ - _init(); +FallingTile::FallingTile(Level* level) : Entity(level) { _init(); } + +FallingTile::FallingTile(Level* level, double x, double y, double z, int tile, + int data) + : Entity(level) { + _init(); + + this->tile = tile; + this->data = data; + blocksBuilding = true; + setSize(0.98f, 0.98f); + heightOffset = bbHeight / 2.0f; + setPos(x, y, z); + + xd = 0; + yd = 0; + zd = 0; + + xo = x; + yo = y; + zo = z; + + // 4J added - without this newly created falling tiles weren't interpolating + // their render positions correctly + xOld = x; + yOld = y; + zOld = z; } -FallingTile::FallingTile(Level *level, double x, double y, double z, int tile, int data) : Entity( level ) -{ - _init(); +bool FallingTile::makeStepSound() { return false; } - this->tile = tile; - this->data = data; - blocksBuilding = true; - setSize(0.98f, 0.98f); - heightOffset = bbHeight / 2.0f; - setPos(x, y, z); +void FallingTile::defineSynchedData() {} - xd = 0; - yd = 0; - zd = 0; +bool FallingTile::isPickable() { return !removed; } - xo = x; - yo = y; - zo = z; +void FallingTile::tick() { + if (tile == 0) { + remove(); + return; + } - // 4J added - without this newly created falling tiles weren't interpolating their render positions correctly - xOld = x; - yOld = y; - zOld = z; + xo = x; + yo = y; + zo = z; + time++; + + yd -= 0.04f; + move(xd, yd, zd); + xd *= 0.98f; + yd *= 0.98f; + zd *= 0.98f; + + if (!level->isClientSide) { + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + if (time == 1) { + if (level->getTile(xt, yt, zt) == tile) { + level->setTile(xt, yt, zt, 0); + } else { + remove(); + return; + } + } + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + yd *= -0.5f; + + // if (HeavyTile.isFree(level, xt, yt, zt)) { + if (level->getTile(xt, yt, zt) != Tile::pistonMovingPiece_Id) { + remove(); + if (!cancelDrop && + level->mayPlace(tile, xt, yt, zt, true, 1, nullptr) && + !HeavyTile::isFree(level, xt, yt - 1, zt) && + level->setTileAndData(xt, yt, zt, tile, data)) { + HeavyTile* hv = dynamic_cast(Tile::tiles[tile]); + if (hv) { + hv->onLand(level, xt, yt, zt, data); + } + } else { + if (dropItem && !cancelDrop) + spawnAtLocation( + std::shared_ptr(new ItemInstance( + tile, 1, + Tile::tiles[tile]->getSpawnResourcesAuxValue( + data))), + 0); + } + } + } else if ((time > 20 * 5 && !level->isClientSide && + (yt < 1 || yt > Level::maxBuildHeight)) || + (time > 20 * 30)) { + if (dropItem) spawnAtLocation(tile, 1); + remove(); + } + } } -bool FallingTile::makeStepSound() -{ - return false; +void FallingTile::causeFallDamage(float distance) { + if (hurtEntities) { + int dmg = Mth::ceil(distance - 1); + if (dmg > 0) { + std::vector >* entities = + level->getEntities(shared_from_this(), bb); + DamageSource* source = tile == Tile::anvil_Id + ? DamageSource::anvil + : DamageSource::fallingBlock; + + // for (Entity entity : entities) + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + (*it)->hurt(source, std::min(Mth::floor(dmg * fallDamageAmount), + fallDamageMax)); + } + if (tile == Tile::anvil_Id && + random->nextFloat() < 0.05f + (dmg * 0.05)) { + int damage = data >> 2; + int dir = data & 3; + + if (++damage > 2) { + cancelDrop = true; + } else { + data = dir | (damage << 2); + } + } + } + } } -void FallingTile::defineSynchedData() -{ +void FallingTile::addAdditonalSaveData(CompoundTag* tag) { + tag->putByte(L"Tile", (uint8_t)tile); + tag->putByte(L"Data", (uint8_t)data); + tag->putByte(L"Time", (uint8_t)time); + tag->putBoolean(L"DropItem", dropItem); + tag->putBoolean(L"HurtEntities", hurtEntities); + tag->putFloat(L"FallHurtAmount", fallDamageAmount); + tag->putInt(L"FallHurtMax", fallDamageMax); } -bool FallingTile::isPickable() -{ - return !removed; +void FallingTile::readAdditionalSaveData(CompoundTag* tag) { + tile = tag->getByte(L"Tile") & 0xff; + data = tag->getByte(L"Data") & 0xff; + time = tag->getByte(L"Time") & 0xff; + + if (tag->contains(L"HurtEntities")) { + hurtEntities = tag->getBoolean(L"HurtEntities"); + fallDamageAmount = tag->getFloat(L"FallHurtAmount"); + fallDamageMax = tag->getInt(L"FallHurtMax"); + } else if (tile == Tile::anvil_Id) { + hurtEntities = true; + } + + if (tag->contains(L"DropItem")) { + dropItem = tag->getBoolean(L"DropItem"); + } + + if (tile == 0) { + tile = Tile::sand_Id; + } } -void FallingTile::tick() -{ - if (tile == 0) - { - remove(); - return; - } +float FallingTile::getShadowHeightOffs() { return 0; } - xo = x; - yo = y; - zo = z; - time++; +Level* FallingTile::getLevel() { return level; } - yd -= 0.04f; - move(xd, yd, zd); - xd *= 0.98f; - yd *= 0.98f; - zd *= 0.98f; +void FallingTile::setHurtsEntities(bool value) { this->hurtEntities = value; } - if(!level->isClientSide) - { - - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - if(time == 1) - { - if (level->getTile(xt, yt, zt) == tile) - { - level->setTile(xt, yt, zt, 0); - } - else - { - remove(); - return; - } - } - - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - yd *= -0.5f; - - // if (HeavyTile.isFree(level, xt, yt, zt)) { - if (level->getTile(xt, yt, zt) != Tile::pistonMovingPiece_Id) - { - remove(); - if (!cancelDrop && level->mayPlace(tile, xt, yt, zt, true, 1, nullptr) && !HeavyTile::isFree(level, xt, yt - 1, zt) && level->setTileAndData(xt, yt, zt, tile, data)) - { - HeavyTile *hv = dynamic_cast(Tile::tiles[tile]); - if (hv) - { - hv->onLand(level, xt, yt, zt, data); - } - } - else - { - if(dropItem && !cancelDrop) spawnAtLocation( std::shared_ptr(new ItemInstance(tile, 1, Tile::tiles[tile]->getSpawnResourcesAuxValue(data))), 0); - } - } - } - else if ( (time > 20 * 5 && !level->isClientSide && (yt < 1 || yt > Level::maxBuildHeight)) || (time > 20 * 30)) - { - if(dropItem) spawnAtLocation(tile, 1); - remove(); - } - } -} - -void FallingTile::causeFallDamage(float distance) -{ - if (hurtEntities) - { - int dmg = Mth::ceil(distance - 1); - if (dmg > 0) - { - std::vector > *entities = level->getEntities(shared_from_this(), bb); - DamageSource *source = tile == Tile::anvil_Id ? DamageSource::anvil : DamageSource::fallingBlock; - - //for (Entity entity : entities) - for(AUTO_VAR(it,entities->begin()); it != entities->end(); ++it) - { - (*it)->hurt(source, std::min(Mth::floor(dmg * fallDamageAmount), fallDamageMax)); - } - if (tile == Tile::anvil_Id && random->nextFloat() < 0.05f + (dmg * 0.05)) - { - int damage = data >> 2; - int dir = data & 3; - - if (++damage > 2) - { - cancelDrop = true; - } - else - { - data = dir | (damage << 2); - } - } - } - } -} - -void FallingTile::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putByte(L"Tile", (uint8_t) tile); - tag->putByte(L"Data", (uint8_t) data); - tag->putByte(L"Time", (uint8_t) time); - tag->putBoolean(L"DropItem", dropItem); - tag->putBoolean(L"HurtEntities", hurtEntities); - tag->putFloat(L"FallHurtAmount", fallDamageAmount); - tag->putInt(L"FallHurtMax", fallDamageMax); -} - -void FallingTile::readAdditionalSaveData(CompoundTag *tag) -{ - tile = tag->getByte(L"Tile") & 0xff; - data = tag->getByte(L"Data") & 0xff; - time = tag->getByte(L"Time") & 0xff; - - if (tag->contains(L"HurtEntities")) - { - hurtEntities = tag->getBoolean(L"HurtEntities"); - fallDamageAmount = tag->getFloat(L"FallHurtAmount"); - fallDamageMax = tag->getInt(L"FallHurtMax"); - } - else if (tile == Tile::anvil_Id) - { - hurtEntities = true; - } - - if (tag->contains(L"DropItem")) - { - dropItem = tag->getBoolean(L"DropItem"); - } - - if (tile == 0) - { - tile = Tile::sand_Id; - } -} - - -float FallingTile::getShadowHeightOffs() -{ - return 0; -} - -Level *FallingTile::getLevel() -{ - return level; -} - -void FallingTile::setHurtsEntities(bool value) -{ - this->hurtEntities = value; -} - -bool FallingTile::displayFireAnimation() -{ - return false; -} \ No newline at end of file +bool FallingTile::displayFireAnimation() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/FallingTile.h b/Minecraft.World/Blocks/FallingTile.h index 5c9d4f717..165c13abc 100644 --- a/Minecraft.World/Blocks/FallingTile.h +++ b/Minecraft.World/Blocks/FallingTile.h @@ -3,47 +3,47 @@ class Level; -class FallingTile : public Entity -{ +class FallingTile : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_FALLINGTILE;} - static Entity *create(Level *level) { return new FallingTile(level); } + eINSTANCEOF GetType() { return eTYPE_FALLINGTILE; } + static Entity* create(Level* level) { return new FallingTile(level); } - static const int serialVersionUID = 0; - int tile; - int data; - int time; - bool dropItem; + static const int serialVersionUID = 0; + int tile; + int data; + int time; + bool dropItem; private: - bool cancelDrop; - bool hurtEntities; - int fallDamageMax ; - float fallDamageAmount; + bool cancelDrop; + bool hurtEntities; + int fallDamageMax; + float fallDamageAmount; - // 4J - added for common ctor code - void _init(); + // 4J - added for common ctor code + void _init(); public: - FallingTile(Level *level); - FallingTile(Level *level, double x, double y, double z, int tile, int data = 0); + FallingTile(Level* level); + FallingTile(Level* level, double x, double y, double z, int tile, + int data = 0); protected: - virtual bool makeStepSound(); - virtual void defineSynchedData(); + virtual bool makeStepSound(); + virtual void defineSynchedData(); public: - virtual bool isPickable(); - virtual void tick(); + virtual bool isPickable(); + virtual void tick(); protected: - void causeFallDamage(float distance); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + void causeFallDamage(float distance); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); public: - virtual float getShadowHeightOffs(); - Level *getLevel(); - void setHurtsEntities(bool value); - bool displayFireAnimation(); + virtual float getShadowHeightOffs(); + Level* getLevel(); + void setHurtsEntities(bool value); + bool displayFireAnimation(); }; diff --git a/Minecraft.World/Blocks/FarmTile.cpp b/Minecraft.World/Blocks/FarmTile.cpp index 053529664..306cc22b7 100644 --- a/Minecraft.World/Blocks/FarmTile.cpp +++ b/Minecraft.World/Blocks/FarmTile.cpp @@ -5,11 +5,9 @@ #include "../Headers/net.minecraft.world.h" #include "FarmTile.h" - -FarmTile::FarmTile(int id) : Tile(id, Material::dirt, false) -{ +FarmTile::FarmTile(int id) : Tile(id, Material::dirt, false) { iconWet = NULL; - iconDry = NULL; + iconDry = NULL; setTicking(true); updateDefaultShape(); @@ -17,131 +15,102 @@ FarmTile::FarmTile(int id) : Tile(id, Material::dirt, false) } // 4J Added override -void FarmTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 15 / 16.0f, 1); +void FarmTile::updateDefaultShape() { setShape(0, 0, 0, 1, 15 / 16.0f, 1); } + +AABB* FarmTile::getAABB(Level* level, int x, int y, int z) { + return AABB::newTemp(x + 0, y + 0, z + 0, x + 1, y + 1, z + 1); } -AABB *FarmTile::getAABB(Level *level, int x, int y, int z) -{ - return AABB::newTemp(x + 0, y + 0, z + 0, x + 1, y + 1, z + 1); -} +bool FarmTile::isSolidRender(bool isServerLevel) { return false; } -bool FarmTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool FarmTile::isCubeShaped() { return false; } -bool FarmTile::isCubeShaped() -{ - return false; -} - -Icon *FarmTile::getTexture(int face, int data) -{ - if (face == Facing::UP) - { - if(data > 0) - { - return iconWet; - } - else - { - return iconDry; - } - } +Icon* FarmTile::getTexture(int face, int data) { + if (face == Facing::UP) { + if (data > 0) { + return iconWet; + } else { + return iconDry; + } + } return Tile::dirt->getTexture(face); } -void FarmTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (isNearWater(level, x, y, z) || level->isRainingAt(x, y + 1, z)) - { +void FarmTile::tick(Level* level, int x, int y, int z, Random* random) { + if (isNearWater(level, x, y, z) || level->isRainingAt(x, y + 1, z)) { level->setData(x, y, z, 7); - } else - { + } else { int moisture = level->getData(x, y, z); - if (moisture > 0) - { + if (moisture > 0) { level->setData(x, y, z, moisture - 1); - } else - { - if (!isUnderCrops(level, x, y, z)) - { + } else { + if (!isUnderCrops(level, x, y, z)) { level->setTile(x, y, z, Tile::dirt_Id); } } } } -void FarmTile::fallOn(Level *level, int x, int y, int z, std::shared_ptr entity, float fallDistance) -{ - // 4J Stu - Fix for #86148 - Code: Gameplay: Jumping on Farmland does not always result in turning to Dirt Block - // We should not be setting tiles on the client based on random values! - if (!level->isClientSide && level->random->nextFloat() < (fallDistance - .5f)) - { - // Fix for #60547 - TU7: Content: Gameplay: Players joining a game can destroy crops even with Trust Players option disabled. - std::shared_ptr player = std::dynamic_pointer_cast(entity); - if(player == NULL || player->isAllowedToMine()) level->setTile(x, y, z, Tile::dirt_Id); +void FarmTile::fallOn(Level* level, int x, int y, int z, + std::shared_ptr entity, float fallDistance) { + // 4J Stu - Fix for #86148 - Code: Gameplay: Jumping on Farmland does not + // always result in turning to Dirt Block We should not be setting tiles on + // the client based on random values! + if (!level->isClientSide && + level->random->nextFloat() < (fallDistance - .5f)) { + // Fix for #60547 - TU7: Content: Gameplay: Players joining a game can + // destroy crops even with Trust Players option disabled. + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + if (player == NULL || player->isAllowedToMine()) + level->setTile(x, y, z, Tile::dirt_Id); } } -bool FarmTile::isUnderCrops(Level *level, int x, int y, int z) -{ +bool FarmTile::isUnderCrops(Level* level, int x, int y, int z) { int r = 0; for (int xx = x - r; xx <= x + r; xx++) - for (int zz = z - r; zz <= z + r; zz++) - { + for (int zz = z - r; zz <= z + r; zz++) { int tile = level->getTile(xx, y + 1, zz); - if (tile == Tile::crops_Id || tile == Tile::melonStem_Id || tile == Tile::pumpkinStem_Id || tile == Tile::potatoes_Id || tile == Tile::carrots_Id) - { + if (tile == Tile::crops_Id || tile == Tile::melonStem_Id || + tile == Tile::pumpkinStem_Id || tile == Tile::potatoes_Id || + tile == Tile::carrots_Id) { return true; } } return false; } -bool FarmTile::isNearWater(Level *level, int x, int y, int z) -{ +bool FarmTile::isNearWater(Level* level, int x, int y, int z) { for (int xx = x - 4; xx <= x + 4; xx++) for (int yy = y; yy <= y + 1; yy++) - for (int zz = z - 4; zz <= z + 4; zz++) - { - if (level->getMaterial(xx, yy, zz) == Material::water) - { + for (int zz = z - 4; zz <= z + 4; zz++) { + if (level->getMaterial(xx, yy, zz) == Material::water) { return true; } } return false; } -void FarmTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void FarmTile::neighborChanged(Level* level, int x, int y, int z, int type) { Tile::neighborChanged(level, x, y, z, type); - Material *above = level->getMaterial(x, y + 1, z); - if (above->isSolid()) - { + Material* above = level->getMaterial(x, y + 1, z); + if (above->isSolid()) { level->setTile(x, y, z, Tile::dirt_Id); } } -bool FarmTile::blocksLight() -{ - return true; +bool FarmTile::blocksLight() { return true; } + +int FarmTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::dirt->getResource(0, random, playerBonusLevel); } -int FarmTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::dirt->getResource(0, random, playerBonusLevel); +int FarmTile::cloneTileId(Level* level, int x, int y, int z) { + return Tile::dirt_Id; } -int FarmTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Tile::dirt_Id; -} - -void FarmTile::registerIcons(IconRegister *iconRegister) -{ - iconWet = iconRegister->registerIcon(L"farmland_wet"); - iconDry = iconRegister->registerIcon(L"farmland_dry"); +void FarmTile::registerIcons(IconRegister* iconRegister) { + iconWet = iconRegister->registerIcon(L"farmland_wet"); + iconDry = iconRegister->registerIcon(L"farmland_dry"); } diff --git a/Minecraft.World/Blocks/FarmTile.h b/Minecraft.World/Blocks/FarmTile.h index 9f69a2d1a..15be34ebd 100644 --- a/Minecraft.World/Blocks/FarmTile.h +++ b/Minecraft.World/Blocks/FarmTile.h @@ -5,32 +5,36 @@ class Random; class ChunkRebuildData; -class FarmTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class FarmTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; + private: - Icon *iconWet; - Icon *iconDry; + Icon* iconWet; + Icon* iconDry; protected: - FarmTile(int id); + FarmTile(int id); + public: - virtual void updateDefaultShape(); // 4J Added override - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual void updateDefaultShape(); // 4J Added override + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual Icon *getTexture(int face, int data); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void fallOn(Level *level, int x, int y, int z, std::shared_ptr entity, float fallDistance); + virtual Icon* getTexture(int face, int data); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void fallOn(Level* level, int x, int y, int z, + std::shared_ptr entity, float fallDistance); + private: - virtual bool isUnderCrops(Level *level, int x, int y, int z); - virtual bool isNearWater(Level *level, int x, int y, int z); + virtual bool isUnderCrops(Level* level, int x, int y, int z); + virtual bool isNearWater(Level* level, int x, int y, int z); + public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); virtual bool blocksLight(); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); - //@Override - void registerIcons(IconRegister *iconRegister); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); + //@Override + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/FenceGateTile.cpp b/Minecraft.World/Blocks/FenceGateTile.cpp index ac358dc98..fc88d2ef7 100644 --- a/Minecraft.World/Blocks/FenceGateTile.cpp +++ b/Minecraft.World/Blocks/FenceGateTile.cpp @@ -5,98 +5,83 @@ #include "../Headers/net.minecraft.h" #include "../Level/Events/LevelEvent.h" -FenceGateTile::FenceGateTile(int id) : DirectionalTile(id, Material::wood, false) -{ +FenceGateTile::FenceGateTile(int id) + : DirectionalTile(id, Material::wood, false) {} + +Icon* FenceGateTile::getTexture(int face, int data) { + return Tile::wood->getTexture(face); } -Icon *FenceGateTile::getTexture(int face, int data) -{ - return Tile::wood->getTexture(face); -} - -bool FenceGateTile::mayPlace(Level *level, int x, int y, int z) -{ +bool FenceGateTile::mayPlace(Level* level, int x, int y, int z) { if (!level->getMaterial(x, y - 1, z)->isSolid()) return false; return Tile::mayPlace(level, x, y, z); } -AABB *FenceGateTile::getAABB(Level *level, int x, int y, int z) -{ +AABB* FenceGateTile::getAABB(Level* level, int x, int y, int z) { int data = level->getData(x, y, z); - if (isOpen(data)) - { + if (isOpen(data)) { return NULL; } - // 4J Brought forward change from 1.2.3 to fix hit box rotation - if (data == Direction::NORTH || data == Direction::SOUTH) - { - return AABB::newTemp(x, y, z + 6.0f / 16.0f, x + 1, y + 1.5f, z + 10.0f / 16.0f); - } - return AABB::newTemp(x + 6.0f / 16.0f, y, z, x + 10.0f / 16.0f, y + 1.5f, z + 1); - //return AABB::newTemp(x, y, z, x + 1, y + 1.5f, z + 1); + // 4J Brought forward change from 1.2.3 to fix hit box rotation + if (data == Direction::NORTH || data == Direction::SOUTH) { + return AABB::newTemp(x, y, z + 6.0f / 16.0f, x + 1, y + 1.5f, + z + 10.0f / 16.0f); + } + return AABB::newTemp(x + 6.0f / 16.0f, y, z, x + 10.0f / 16.0f, y + 1.5f, + z + 1); + // return AABB::newTemp(x, y, z, x + 1, y + 1.5f, z + 1); } // 4J - Brought forward from 1.2.3 to fix hit box rotation -void FenceGateTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void FenceGateTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - int data = getDirection(level->getData(x, y, z)); - if (data == Direction::NORTH || data == Direction::SOUTH) - { - setShape(0, 0, 6.0f / 16.0f, 1, 1.0f, 10.0f / 16.0f); - } - else - { - setShape(6.0f / 16.0f, 0, 0, 10.0f / 16.0f, 1.0f, 1); - } + int data = getDirection(level->getData(x, y, z)); + if (data == Direction::NORTH || data == Direction::SOUTH) { + setShape(0, 0, 6.0f / 16.0f, 1, 1.0f, 10.0f / 16.0f); + } else { + setShape(6.0f / 16.0f, 0, 0, 10.0f / 16.0f, 1.0f, 1); + } } -bool FenceGateTile::blocksLight() -{ - return false; +bool FenceGateTile::blocksLight() { return false; } + +bool FenceGateTile::isSolidRender(bool isServerLevel) { return false; } + +bool FenceGateTile::isCubeShaped() { return false; } + +bool FenceGateTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return isOpen(level->getData(x, y, z)); } -bool FenceGateTile::isSolidRender(bool isServerLevel) -{ - return false; -} +int FenceGateTile::getRenderShape() { return Tile::SHAPE_FENCE_GATE; } -bool FenceGateTile::isCubeShaped() -{ - return false; -} - -bool FenceGateTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return isOpen(level->getData(x, y, z)); -} - -int FenceGateTile::getRenderShape() -{ - return Tile::SHAPE_FENCE_GATE; -} - -void FenceGateTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ +void FenceGateTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3)) % 4; level->setData(x, y, z, dir); } -bool FenceGateTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool FenceGateTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly ) - { - // 4J - added - just do enough to play the sound - level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); // 4J - changed event to pass player rather than NULL as the source of the event so we can filter the broadcast properly - return false; - } + if (soundOnly) { + // 4J - added - just do enough to play the sound + level->levelEvent( + player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, + 0); // 4J - changed event to pass player rather than NULL as the + // source of the event so we can filter the broadcast properly + return false; + } int data = level->getData(x, y, z); - if (isOpen(data)) - { + if (isOpen(data)) { level->setData(x, y, z, data & ~OPEN_BIT); - } - else - { + } else { // open the door from the player int dir = (((Mth::floor(player->yRot * 4 / (360) + 0.5)) & 3)) % 4; int current = getDirection(data); @@ -109,39 +94,32 @@ bool FenceGateTile::use(Level *level, int x, int y, int z, std::shared_ptrisClientSide) return; +void FenceGateTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (level->isClientSide) return; - int data = level->getData(x, y, z); + int data = level->getData(x, y, z); - bool signal = level->hasNeighborSignal(x, y, z); - if (signal || ((type > 0 && Tile::tiles[type]->isSignalSource()) || type == 0)) - { - if (signal && !isOpen(data)) - { - level->setData(x, y, z, data | OPEN_BIT); - level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - } - else if (!signal && isOpen(data)) - { - level->setData(x, y, z, data & ~OPEN_BIT); - level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - } - } + bool signal = level->hasNeighborSignal(x, y, z); + if (signal || + ((type > 0 && Tile::tiles[type]->isSignalSource()) || type == 0)) { + if (signal && !isOpen(data)) { + level->setData(x, y, z, data | OPEN_BIT); + level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + } else if (!signal && isOpen(data)) { + level->setData(x, y, z, data & ~OPEN_BIT); + level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + } + } } -bool FenceGateTile::isOpen(int data) -{ - return (data & OPEN_BIT) != 0; +bool FenceGateTile::isOpen(int data) { return (data & OPEN_BIT) != 0; } + +void FenceGateTile::registerIcons(IconRegister* iconRegister) { + // None } -void FenceGateTile::registerIcons(IconRegister *iconRegister) -{ - // None -} - -bool FenceGateTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - return true; +bool FenceGateTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + return true; } diff --git a/Minecraft.World/Blocks/FenceGateTile.h b/Minecraft.World/Blocks/FenceGateTile.h index 83cc378bd..f453909a2 100644 --- a/Minecraft.World/Blocks/FenceGateTile.h +++ b/Minecraft.World/Blocks/FenceGateTile.h @@ -1,26 +1,34 @@ #pragma once #include "DirectionalTile.h" -class FenceGateTile : public DirectionalTile -{ +class FenceGateTile : public DirectionalTile { private: static const int OPEN_BIT = 4; public: - FenceGateTile(int id); - Icon *getTexture(int face, int data); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param // Brought forward from 1.2.3 + FenceGateTile(int id); + Icon* getTexture(int face, int data); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param // Brought + // forward from 1.2.3 virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); virtual int getRenderShape(); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void neighborChanged(Level* level, int x, int y, int z, int type); static bool isOpen(int data); - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/FenceTile.cpp b/Minecraft.World/Blocks/FenceTile.cpp index 7aa1e37e3..a22c54d30 100644 --- a/Minecraft.World/Blocks/FenceTile.cpp +++ b/Minecraft.World/Blocks/FenceTile.cpp @@ -4,13 +4,12 @@ #include "../Headers/net.minecraft.world.h" #include "FenceTile.h" -FenceTile::FenceTile(int id, const std::wstring &texture, Material *material) : Tile( id, material, false) -{ - this->texture = texture; +FenceTile::FenceTile(int id, const std::wstring& texture, Material* material) + : Tile(id, material, false) { + this->texture = texture; } -AABB *FenceTile::getAABB(Level *level, int x, int y, int z) -{ +AABB* FenceTile::getAABB(Level* level, int x, int y, int z) { bool n = connectsTo(level, x, y, z - 1); bool s = connectsTo(level, x, y, z + 1); bool w = connectsTo(level, x - 1, y, z); @@ -21,27 +20,26 @@ AABB *FenceTile::getAABB(Level *level, int x, int y, int z) float north = 6.0f / 16.0f; float south = 10.0f / 16.0f; - if (n) - { + if (n) { north = 0; } - if (s) - { + if (s) { south = 1; } - if (w) - { + if (w) { west = 0; } - if (e) - { + if (e) { east = 1; } - return AABB::newTemp(x + west, y, z + north, x + east, y + 1.5f, z + south); + return AABB::newTemp(x + west, y, z + north, x + east, y + 1.5f, z + south); } -void FenceTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void FenceTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { bool n = connectsTo(level, x, y, z - 1); bool s = connectsTo(level, x, y, z + 1); @@ -53,80 +51,58 @@ void FenceTile::updateShape(LevelSource *level, int x, int y, int z, int forceDa float north = 6.0f / 16.0f; float south = 10.0f / 16.0f; - if (n) - { + if (n) { north = 0; } - if (s) - { + if (s) { south = 1; } - if (w) - { + if (w) { west = 0; } - if (e) - { + if (e) { east = 1; } setShape(west, 0, north, east, 1.0f, south); } -bool FenceTile::blocksLight() -{ - return false; +bool FenceTile::blocksLight() { return false; } + +bool FenceTile::isSolidRender(bool isServerLevel) { return false; } + +bool FenceTile::isCubeShaped() { return false; } + +bool FenceTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return false; } -bool FenceTile::isSolidRender(bool isServerLevel) -{ - return false; -} +int FenceTile::getRenderShape() { return Tile::SHAPE_FENCE; } -bool FenceTile::isCubeShaped() -{ - return false; -} - -bool FenceTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return false; -} - -int FenceTile::getRenderShape() -{ - return Tile::SHAPE_FENCE; -} - -bool FenceTile::connectsTo(LevelSource *level, int x, int y, int z) -{ +bool FenceTile::connectsTo(LevelSource* level, int x, int y, int z) { int tile = level->getTile(x, y, z); - if (tile == id || tile == Tile::fenceGate_Id) - { + if (tile == id || tile == Tile::fenceGate_Id) { return true; } - Tile *tileInstance = Tile::tiles[tile]; - if (tileInstance != NULL) - { - if (tileInstance->material->isSolidBlocking() && tileInstance->isCubeShaped()) - { + Tile* tileInstance = Tile::tiles[tile]; + if (tileInstance != NULL) { + if (tileInstance->material->isSolidBlocking() && + tileInstance->isCubeShaped()) { return tileInstance->material != Material::vegetable; } } return false; } -bool FenceTile::isFence(int tile) -{ - return tile == Tile::fence_Id || tile == Tile::netherFence_Id; +bool FenceTile::isFence(int tile) { + return tile == Tile::fence_Id || tile == Tile::netherFence_Id; } -void FenceTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(texture); +void FenceTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(texture); } -bool FenceTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - return true; +bool FenceTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + return true; } diff --git a/Minecraft.World/Blocks/FenceTile.h b/Minecraft.World/Blocks/FenceTile.h index 001fe19f8..030592f06 100644 --- a/Minecraft.World/Blocks/FenceTile.h +++ b/Minecraft.World/Blocks/FenceTile.h @@ -2,22 +2,25 @@ #include "Tile.h" #include "../Util/Definitions.h" -class FenceTile : public Tile -{ +class FenceTile : public Tile { private: - std::wstring texture; + std::wstring texture; public: - FenceTile(int id, const std::wstring &texture, Material *material); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual bool blocksLight(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual bool isCubeShaped(); - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual int getRenderShape(); - bool connectsTo(LevelSource *level, int x, int y, int z); - static bool isFence(int tile); - void registerIcons(IconRegister *iconRegister); + FenceTile(int id, const std::wstring& texture, Material* material); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual bool blocksLight(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual bool isCubeShaped(); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual int getRenderShape(); + bool connectsTo(LevelSource* level, int x, int y, int z); + static bool isFence(int tile); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/FireTile.cpp b/Minecraft.World/Blocks/FireTile.cpp index fd422fa6a..79f0462f4 100644 --- a/Minecraft.World/Blocks/FireTile.cpp +++ b/Minecraft.World/Blocks/FireTile.cpp @@ -12,396 +12,338 @@ #include "../IO/Streams/IntBuffer.h" #include "../../Minecraft.Client/Rendering/Tesselator.h" - const std::wstring FireTile::TEXTURE_FIRST = L"fire_0"; const std::wstring FireTile::TEXTURE_SECOND = L"fire_1"; -FireTile::FireTile(int id) : Tile(id, Material::fire, false) -{ - flameOdds = new int[256]; - memset( flameOdds,0,sizeof(int)*256); +FireTile::FireTile(int id) : Tile(id, Material::fire, false) { + flameOdds = new int[256]; + memset(flameOdds, 0, sizeof(int) * 256); - burnOdds = new int[256]; - memset( burnOdds,0,sizeof(int)*256); + burnOdds = new int[256]; + memset(burnOdds, 0, sizeof(int) * 256); - icons = NULL; + icons = NULL; - setTicking(true); + setTicking(true); } -FireTile::~FireTile() -{ - delete [] flameOdds; - delete [] burnOdds; +FireTile::~FireTile() { + delete[] flameOdds; + delete[] burnOdds; } -void FireTile::init() -{ - setFlammable(Tile::wood_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::woodSlab_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::woodSlabHalf_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::fence_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::stairs_wood_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::stairs_birchwood_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::stairs_sprucewood_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::stairs_junglewood_Id, FLAME_HARD, BURN_MEDIUM); - setFlammable(Tile::treeTrunk_Id, FLAME_HARD, BURN_HARD); - setFlammable(Tile::leaves_Id, FLAME_EASY, BURN_EASY); - setFlammable(Tile::bookshelf_Id, FLAME_EASY, BURN_MEDIUM); - setFlammable(Tile::tnt_Id, FLAME_MEDIUM, BURN_INSTANT); - setFlammable(Tile::tallgrass_Id, FLAME_INSTANT, BURN_INSTANT); - setFlammable(Tile::cloth_Id, FLAME_EASY, BURN_EASY); - setFlammable(Tile::vine_Id, FLAME_MEDIUM, BURN_INSTANT); +void FireTile::init() { + setFlammable(Tile::wood_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::woodSlab_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::woodSlabHalf_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::fence_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::stairs_wood_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::stairs_birchwood_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::stairs_sprucewood_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::stairs_junglewood_Id, FLAME_HARD, BURN_MEDIUM); + setFlammable(Tile::treeTrunk_Id, FLAME_HARD, BURN_HARD); + setFlammable(Tile::leaves_Id, FLAME_EASY, BURN_EASY); + setFlammable(Tile::bookshelf_Id, FLAME_EASY, BURN_MEDIUM); + setFlammable(Tile::tnt_Id, FLAME_MEDIUM, BURN_INSTANT); + setFlammable(Tile::tallgrass_Id, FLAME_INSTANT, BURN_INSTANT); + setFlammable(Tile::cloth_Id, FLAME_EASY, BURN_EASY); + setFlammable(Tile::vine_Id, FLAME_MEDIUM, BURN_INSTANT); } -void FireTile::setFlammable(int id, int flame, int burn) -{ - flameOdds[id] = flame; - burnOdds[id] = burn; +void FireTile::setFlammable(int id, int flame, int burn) { + flameOdds[id] = flame; + burnOdds[id] = burn; } -AABB *FireTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* FireTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +bool FireTile::blocksLight() { return false; } + +bool FireTile::isSolidRender(bool isServerLevel) { return false; } + +bool FireTile::isCubeShaped() { return false; } + +int FireTile::getRenderShape() { return Tile::SHAPE_FIRE; } + +int FireTile::getResourceCount(Random* random) { return 0; } + +int FireTile::getTickDelay() { return 30; } + +void FireTile::tick(Level* level, int x, int y, int z, Random* random) { + // 4J added - we don't want fire to do anything that might create new fire, + // or destroy this fire, if we aren't actually tracking (for network) the + // chunk this is in in the player chunk map. If we did change something in + // that case, then the change wouldn't get sent to any player that had + // already received that full chunk, and so we'd just become desynchronised. + // Seems safest just to do an addToTickNextTick here instead with a decent + // delay, to make sure that we will get ticked again in the future, when we + // might again be in a chunk that is being tracked. + if (!level->isClientSide) // Note - should only be being ticked on the + // server + { + if (!MinecraftServer::getInstance()->getPlayers()->isTrackingTile( + x, y, z, level->dimension->id)) { + level->addToTickNextTick(x, y, z, id, getTickDelay() * 5); + return; + } + } + + bool infiniBurn = level->getTile(x, y - 1, z) == Tile::hellRock_Id; + if (level->dimension->id == 1) // 4J - was == instanceof TheEndDimension + { + if (level->getTile(x, y - 1, z) == Tile::unbreakable_Id) + infiniBurn = true; + } + + if (!mayPlace(level, x, y, z)) { + level->setTile(x, y, z, 0); + } + + if (!infiniBurn && level->isRaining()) { + if (level->isRainingAt(x, y, z) || level->isRainingAt(x - 1, y, z) || + level->isRainingAt(x + 1, y, z) || + level->isRainingAt(x, y, z - 1) || + level->isRainingAt(x, y, z + 1)) { + level->setTile(x, y, z, 0); + return; + } + } + + int age = level->getData(x, y, z); + if (age < 15) { + level->setDataNoUpdate(x, y, z, age + random->nextInt(3) / 2); + } + level->addToTickNextTick(x, y, z, id, getTickDelay() + random->nextInt(10)); + + if (!infiniBurn && !isValidFireLocation(level, x, y, z)) { + if (!level->isTopSolidBlocking(x, y - 1, z) || age > 3) + level->setTile(x, y, z, 0); + return; + } + + if (!infiniBurn && !canBurn(level, x, y - 1, z)) { + if (age == 15 && random->nextInt(4) == 0) { + level->setTile(x, y, z, 0); + return; + } + } + + bool isHumid = level->isHumidAt(x, y, z); + int extra = 0; + if (isHumid) { + extra = -50; + } + checkBurnOut(level, x + 1, y, z, 300 + extra, random, age); + checkBurnOut(level, x - 1, y, z, 300 + extra, random, age); + checkBurnOut(level, x, y - 1, z, 250 + extra, random, age); + checkBurnOut(level, x, y + 1, z, 250 + extra, random, age); + checkBurnOut(level, x, y, z - 1, 300 + extra, random, age); + checkBurnOut(level, x, y, z + 1, 300 + extra, random, age); + if (app.GetGameHostOption(eGameHostOption_FireSpreads)) { + for (int xx = x - 1; xx <= x + 1; xx++) { + for (int zz = z - 1; zz <= z + 1; zz++) { + for (int yy = y - 1; yy <= y + 4; yy++) { + if (xx == x && yy == y && zz == z) continue; + + int rate = 100; + if (yy > y + 1) { + rate += ((yy - (y + 1)) * 100); + } + + int fodds = getFireOdds(level, xx, yy, zz); + if (fodds > 0) { + int odds = (fodds + 40) / (age + 30); + if (isHumid) { + odds /= 2; + } + if (odds > 0 && random->nextInt(rate) <= odds) { + if ((level->isRaining() && + level->isRainingAt(xx, yy, zz)) || + level->isRainingAt(xx - 1, yy, z) || + level->isRainingAt(xx + 1, yy, zz) || + level->isRainingAt(xx, yy, zz - 1) || + level->isRainingAt(xx, yy, zz + 1)) { + // DO NOTHING, rain! + + } else { + int tAge = age + random->nextInt(5) / 4; + if (tAge > 15) tAge = 15; + level->setTileAndData(xx, yy, zz, this->id, + tAge); + } + } + } + } + } + } + } } -bool FireTile::blocksLight() -{ - return false; +void FireTile::checkBurnOut(Level* level, int x, int y, int z, int chance, + Random* random, int age) { + int odds = burnOdds[level->getTile(x, y, z)]; + if (random->nextInt(chance) < odds) { + bool wasTnt = level->getTile(x, y, z) == Tile::tnt_Id; + if (random->nextInt(age + 10) < 5 && !level->isRainingAt(x, y, z) && + app.GetGameHostOption(eGameHostOption_FireSpreads)) { + int tAge = age + random->nextInt(5) / 4; + if (tAge > 15) tAge = 15; + level->setTileAndData(x, y, z, this->id, tAge); + } else { + level->setTile(x, y, z, 0); + } + if (wasTnt) { + Tile::tnt->destroy(level, x, y, z, TntTile::EXPLODE_BIT); + } + } } -bool FireTile::isSolidRender(bool isServerLevel) -{ - return false; +bool FireTile::isValidFireLocation(Level* level, int x, int y, int z) { + if (canBurn(level, x + 1, y, z)) return true; + if (canBurn(level, x - 1, y, z)) return true; + if (canBurn(level, x, y - 1, z)) return true; + if (canBurn(level, x, y + 1, z)) return true; + if (canBurn(level, x, y, z - 1)) return true; + if (canBurn(level, x, y, z + 1)) return true; + + return false; } -bool FireTile::isCubeShaped() -{ - return false; +int FireTile::getFireOdds(Level* level, int x, int y, int z) { + int odds = 0; + if (!level->isEmptyTile(x, y, z)) return 0; + + odds = getFlammability(level, x + 1, y, z, odds); + odds = getFlammability(level, x - 1, y, z, odds); + odds = getFlammability(level, x, y - 1, z, odds); + odds = getFlammability(level, x, y + 1, z, odds); + odds = getFlammability(level, x, y, z - 1, odds); + odds = getFlammability(level, x, y, z + 1, odds); + + return odds; } -int FireTile::getRenderShape() -{ - return Tile::SHAPE_FIRE; +bool FireTile::mayPick() { return false; } + +bool FireTile::canBurn(LevelSource* level, int x, int y, int z) { + return flameOdds[level->getTile(x, y, z)] > 0; } -int FireTile::getResourceCount(Random *random) -{ - return 0; +int FireTile::getFlammability(Level* level, int x, int y, int z, int odds) { + int f = flameOdds[level->getTile(x, y, z)]; + if (f > odds) return f; + return odds; } -int FireTile::getTickDelay() -{ - return 30; +bool FireTile::mayPlace(Level* level, int x, int y, int z) { + return level->isTopSolidBlocking(x, y - 1, z) || + isValidFireLocation(level, x, y, z); } -void FireTile::tick(Level *level, int x, int y, int z, Random *random) -{ - // 4J added - we don't want fire to do anything that might create new fire, or destroy this fire, if we aren't actually tracking (for network) the chunk this is in in the player - // chunk map. If we did change something in that case, then the change wouldn't get sent to any player that had already received that full chunk, and so we'd just become desynchronised. - // Seems safest just to do an addToTickNextTick here instead with a decent delay, to make sure that we will get ticked again in the future, when we might again be in a chunk - // that is being tracked. - if( !level->isClientSide ) // Note - should only be being ticked on the server - { - if( !MinecraftServer::getInstance()->getPlayers()->isTrackingTile(x, y, z, level->dimension->id) ) - { - level->addToTickNextTick(x, y, z, id, getTickDelay() * 5); - return; - } - } - - - bool infiniBurn = level->getTile(x, y - 1, z) == Tile::hellRock_Id; - if (level->dimension->id == 1) // 4J - was == instanceof TheEndDimension - { - if (level->getTile(x, y - 1, z) == Tile::unbreakable_Id) infiniBurn = true; - } - - if (!mayPlace(level, x, y, z)) - { - level->setTile(x, y, z, 0); - } - - if (!infiniBurn && level->isRaining()) - { - if (level->isRainingAt(x, y, z) || level->isRainingAt(x - 1, y, z) || level->isRainingAt(x + 1, y, z) || level->isRainingAt(x, y, z - 1) || level->isRainingAt(x, y, z + 1)) { - - level->setTile(x, y, z, 0); - return; - } - } - - int age = level->getData(x, y, z); - if (age < 15) - { - level->setDataNoUpdate(x, y, z, age + random->nextInt(3) / 2); - } - level->addToTickNextTick(x, y, z, id, getTickDelay() + random->nextInt(10)); - - if (!infiniBurn && !isValidFireLocation(level, x, y, z)) - { - if (!level->isTopSolidBlocking(x, y - 1, z) || age > 3) level->setTile(x, y, z, 0); - return; - } - - if (!infiniBurn && !canBurn(level, x, y - 1, z)) - { - if (age == 15 && random->nextInt(4) == 0) - { - level->setTile(x, y, z, 0); - return; - } - } - - bool isHumid = level->isHumidAt(x, y, z); - int extra = 0; - if (isHumid) - { - extra = -50; - } - checkBurnOut(level, x + 1, y, z, 300 + extra, random, age); - checkBurnOut(level, x - 1, y, z, 300 + extra, random, age); - checkBurnOut(level, x, y - 1, z, 250 + extra, random, age); - checkBurnOut(level, x, y + 1, z, 250 + extra, random, age); - checkBurnOut(level, x, y, z - 1, 300 + extra, random, age); - checkBurnOut(level, x, y, z + 1, 300 + extra, random, age); - if( app.GetGameHostOption(eGameHostOption_FireSpreads) ) - { - for (int xx = x - 1; xx <= x + 1; xx++) - { - for (int zz = z - 1; zz <= z + 1; zz++) - { - for (int yy = y - 1; yy <= y + 4; yy++) - { - if (xx == x && yy == y && zz == z) continue; - - int rate = 100; - if (yy > y + 1) - { - rate += ((yy - (y + 1)) * 100); - } - - int fodds = getFireOdds(level, xx, yy, zz); - if (fodds > 0) { - int odds = (fodds + 40) / (age + 30); - if (isHumid) - { - odds /= 2; - } - if (odds > 0 && random->nextInt(rate) <= odds) - { - if ((level->isRaining() && level->isRainingAt(xx, yy, zz)) || level->isRainingAt(xx - 1, yy, z) || level->isRainingAt(xx + 1, yy, zz) || level->isRainingAt(xx, yy, zz - 1) - || level->isRainingAt(xx, yy, zz + 1)) - { - // DO NOTHING, rain! - - } else { - int tAge = age + random->nextInt(5) / 4; - if (tAge > 15) tAge = 15; - level->setTileAndData(xx, yy, zz, this->id, tAge); - - } - } - } - } - } - } - } +void FireTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!level->isTopSolidBlocking(x, y - 1, z) && + !isValidFireLocation(level, x, y, z)) { + level->setTile(x, y, z, 0); + return; + } } -void FireTile::checkBurnOut(Level *level, int x, int y, int z, int chance, Random *random, int age) -{ - int odds = burnOdds[level->getTile(x, y, z)]; - if (random->nextInt(chance) < odds) - { - bool wasTnt = level->getTile(x, y, z) == Tile::tnt_Id; - if (random->nextInt(age + 10) < 5 && !level->isRainingAt(x, y, z) && app.GetGameHostOption(eGameHostOption_FireSpreads)) - { - int tAge = age + random->nextInt(5) / 4; - if (tAge > 15) tAge = 15; - level->setTileAndData(x, y, z, this->id, tAge); - } else - { - level->setTile(x, y, z, 0); - } - if (wasTnt) - { - Tile::tnt->destroy(level, x, y, z, TntTile::EXPLODE_BIT); - } - } +void FireTile::onPlace(Level* level, int x, int y, int z) { + if (level->dimension->id <= 0 && + level->getTile(x, y - 1, z) == Tile::obsidian_Id) { + if (Tile::portalTile->trySpawnPortal(level, x, y, z, true)) { + return; + } + } + if (!level->isTopSolidBlocking(x, y - 1, z) && + !isValidFireLocation(level, x, y, z)) { + level->setTile(x, y, z, 0); + return; + } + level->addToTickNextTick(x, y, z, id, + getTickDelay() + level->random->nextInt(10)); } -bool FireTile::isValidFireLocation(Level *level, int x, int y, int z) -{ - if (canBurn(level, x + 1, y, z)) return true; - if (canBurn(level, x - 1, y, z)) return true; - if (canBurn(level, x, y - 1, z)) return true; - if (canBurn(level, x, y + 1, z)) return true; - if (canBurn(level, x, y, z - 1)) return true; - if (canBurn(level, x, y, z + 1)) return true; +bool FireTile::isFlammable(int tile) { return flameOdds[tile] > 0; } - return false; +void FireTile::animateTick(Level* level, int x, int y, int z, Random* random) { + if (random->nextInt(24) == 0) { + level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, + eSoundType_FIRE_FIRE, 1 + random->nextFloat(), + random->nextFloat() * 0.7f + 0.3f); + } + + if (level->isTopSolidBlocking(x, y - 1, z) || + Tile::fire->canBurn(level, x, y - 1, z)) { + for (int i = 0; i < 3; i++) { + float xx = x + random->nextFloat(); + float yy = y + random->nextFloat() * 0.5f + 0.5f; + float zz = z + random->nextFloat(); + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); + } + } else { + if (Tile::fire->canBurn(level, x - 1, y, z)) { + for (int i = 0; i < 2; i++) { + float xx = x + random->nextFloat() * 0.1f; + float yy = y + random->nextFloat(); + float zz = z + random->nextFloat(); + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, + 0); + } + } + if (Tile::fire->canBurn(level, x + 1, y, z)) { + for (int i = 0; i < 2; i++) { + float xx = x + 1 - random->nextFloat() * 0.1f; + float yy = y + random->nextFloat(); + float zz = z + random->nextFloat(); + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, + 0); + } + } + if (Tile::fire->canBurn(level, x, y, z - 1)) { + for (int i = 0; i < 2; i++) { + float xx = x + random->nextFloat(); + float yy = y + random->nextFloat(); + float zz = z + random->nextFloat() * 0.1f; + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, + 0); + } + } + if (Tile::fire->canBurn(level, x, y, z + 1)) { + for (int i = 0; i < 2; i++) { + float xx = x + random->nextFloat(); + float yy = y + random->nextFloat(); + float zz = z + 1 - random->nextFloat() * 0.1f; + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, + 0); + } + } + if (Tile::fire->canBurn(level, x, y + 1, z)) { + for (int i = 0; i < 2; i++) { + float xx = x + random->nextFloat(); + float yy = y + 1 - random->nextFloat() * 0.1f; + float zz = z + random->nextFloat(); + level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, + 0); + } + } + } } -int FireTile::getFireOdds(Level *level, int x, int y, int z) -{ - int odds = 0; - if (!level->isEmptyTile(x, y, z)) return 0; - - odds = getFlammability(level, x + 1, y, z, odds); - odds = getFlammability(level, x - 1, y, z, odds); - odds = getFlammability(level, x, y - 1, z, odds); - odds = getFlammability(level, x, y + 1, z, odds); - odds = getFlammability(level, x, y, z - 1, odds); - odds = getFlammability(level, x, y, z + 1, odds); - - return odds; +void FireTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[2]; + icons[0] = iconRegister->registerIcon(TEXTURE_FIRST); + icons[1] = iconRegister->registerIcon(TEXTURE_SECOND); } -bool FireTile::mayPick() -{ - return false; -} - -bool FireTile::canBurn(LevelSource *level, int x, int y, int z) -{ - return flameOdds[level->getTile(x, y, z)] > 0; -} - -int FireTile::getFlammability(Level *level, int x, int y, int z, int odds) -{ - int f = flameOdds[level->getTile(x, y, z)]; - if (f > odds) return f; - return odds; -} - -bool FireTile::mayPlace(Level *level, int x, int y, int z) -{ - return level->isTopSolidBlocking(x, y - 1, z) || isValidFireLocation(level, x, y, z); -} - -void FireTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isTopSolidBlocking(x, y - 1, z) && !isValidFireLocation(level, x, y, z)) - { - level->setTile(x, y, z, 0); - return; - } -} - -void FireTile::onPlace(Level *level, int x, int y, int z) -{ - if (level->dimension->id <= 0 && level->getTile(x, y - 1, z) == Tile::obsidian_Id) - { - if (Tile::portalTile->trySpawnPortal(level, x, y, z, true)) - { - return; - } - } - if (!level->isTopSolidBlocking(x, y - 1, z) && !isValidFireLocation(level, x, y, z)) - { - level->setTile(x, y, z, 0); - return; - } - level->addToTickNextTick(x, y, z, id, getTickDelay() + level->random->nextInt(10)); -} - -bool FireTile::isFlammable(int tile) -{ - return flameOdds[tile] > 0; -} - -void FireTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - if (random->nextInt(24) == 0) - { - level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f,eSoundType_FIRE_FIRE, 1 + random->nextFloat(), random->nextFloat() * 0.7f + 0.3f); - } - - if (level->isTopSolidBlocking(x, y - 1, z) || Tile::fire->canBurn(level, x, y - 1, z)) - { - for (int i = 0; i < 3; i++) - { - float xx = x + random->nextFloat(); - float yy = y + random->nextFloat() * 0.5f + 0.5f; - float zz = z + random->nextFloat(); - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - else - { - if (Tile::fire->canBurn(level, x - 1, y, z)) - { - for (int i = 0; i < 2; i++) - { - float xx = x + random->nextFloat() * 0.1f; - float yy = y + random->nextFloat(); - float zz = z + random->nextFloat(); - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - if (Tile::fire->canBurn(level, x + 1, y, z)) - { - for (int i = 0; i < 2; i++) - { - float xx = x + 1 - random->nextFloat() * 0.1f; - float yy = y + random->nextFloat(); - float zz = z + random->nextFloat(); - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - if (Tile::fire->canBurn(level, x, y, z - 1)) - { - for (int i = 0; i < 2; i++) - { - float xx = x + random->nextFloat(); - float yy = y + random->nextFloat(); - float zz = z + random->nextFloat() * 0.1f; - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - if (Tile::fire->canBurn(level, x, y, z + 1)) - { - for (int i = 0; i < 2; i++) - { - float xx = x + random->nextFloat(); - float yy = y + random->nextFloat(); - float zz = z + 1 - random->nextFloat() * 0.1f; - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - if (Tile::fire->canBurn(level, x, y + 1, z)) - { - for (int i = 0; i < 2; i++) - { - float xx = x + random->nextFloat(); - float yy = y + 1 - random->nextFloat() * 0.1f; - float zz = z + random->nextFloat(); - level->addParticle(eParticleType_largesmoke, xx, yy, zz, 0, 0, 0); - } - } - } -} - -void FireTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[2]; - icons[0] = iconRegister->registerIcon(TEXTURE_FIRST); - icons[1] = iconRegister->registerIcon(TEXTURE_SECOND); -} - -Icon *FireTile::getTextureLayer(int layer) -{ +Icon* FireTile::getTextureLayer(int layer) { #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag - Tesselator* t = Tesselator::getInstance(); - t->setAlphaCutOut( true ); + // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag + Tesselator* t = Tesselator::getInstance(); + t->setAlphaCutOut(true); #endif - return icons[layer]; + return icons[layer]; } -Icon *FireTile::getTexture(int face, int data) -{ - return icons[0]; -} +Icon* FireTile::getTexture(int face, int data) { return icons[0]; } diff --git a/Minecraft.World/Blocks/FireTile.h b/Minecraft.World/Blocks/FireTile.h index 35a391b3d..8091e5549 100644 --- a/Minecraft.World/Blocks/FireTile.h +++ b/Minecraft.World/Blocks/FireTile.h @@ -4,19 +4,19 @@ class Random; class ChunkRebuildData; -class FireTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; -public: - static const std::wstring TEXTURE_FIRST; - static const std::wstring TEXTURE_SECOND; +class FireTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; - static const int FLAME_INSTANT = 60; +public: + static const std::wstring TEXTURE_FIRST; + static const std::wstring TEXTURE_SECOND; + + static const int FLAME_INSTANT = 60; static const int FLAME_EASY = 30; static const int FLAME_MEDIUM = 15; static const int FLAME_HARD = 5; - + static const int BURN_INSTANT = 100; static const int BURN_EASY = 60; static const int BURN_MEDIUM = 20; @@ -24,40 +24,48 @@ public: static const int BURN_NEVER = 0; private: - int *flameOdds; - int *burnOdds; - Icon **icons; + int* flameOdds; + int* burnOdds; + Icon** icons; + protected: - FireTile(int id); - virtual ~FireTile(); + FireTile(int id); + virtual ~FireTile(); + public: - void init(); + void init(); + private: - void setFlammable(int id, int flame, int burn); + void setFlammable(int id, int flame, int burn); + public: - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - virtual int getResourceCount(Random *random); + virtual int getResourceCount(Random* random); virtual int getTickDelay(); - virtual void tick(Level *level, int x, int y, int z, Random *random); + virtual void tick(Level* level, int x, int y, int z, Random* random); + private: - void checkBurnOut(Level *level, int x, int y, int z, int chance, Random *random, int age); - bool isValidFireLocation(Level *level, int x, int y, int z); - int getFireOdds(Level *level, int x, int y, int z); + void checkBurnOut(Level* level, int x, int y, int z, int chance, + Random* random, int age); + bool isValidFireLocation(Level* level, int x, int y, int z); + int getFireOdds(Level* level, int x, int y, int z); + public: - virtual bool mayPick(); - bool canBurn(LevelSource *level, int x, int y, int z); - int getFlammability(Level *level, int x, int y, int z, int odds); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void onPlace(Level *level, int x, int y, int z); - bool isFlammable(int tile); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); + virtual bool mayPick(); + bool canBurn(LevelSource* level, int x, int y, int z); + int getFlammability(Level* level, int x, int y, int z, int odds); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void onPlace(Level* level, int x, int y, int z); + bool isFlammable(int tile); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); + public: - void registerIcons(IconRegister *iconRegister); - Icon *getTextureLayer(int layer); - Icon *getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); + Icon* getTextureLayer(int layer); + Icon* getTexture(int face, int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/FlowerPotTile.cpp b/Minecraft.World/Blocks/FlowerPotTile.cpp index aecac7d13..d9b06d775 100644 --- a/Minecraft.World/Blocks/FlowerPotTile.cpp +++ b/Minecraft.World/Blocks/FlowerPotTile.cpp @@ -5,188 +5,168 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "FlowerPotTile.h" -FlowerPotTile::FlowerPotTile(int id) : Tile(id, Material::decoration, false) -{ - updateDefaultShape(); - sendTileData(); +FlowerPotTile::FlowerPotTile(int id) : Tile(id, Material::decoration, false) { + updateDefaultShape(); + sendTileData(); } -void FlowerPotTile::updateDefaultShape() -{ - float size = 6.0f / 16.0f; - float half = size / 2; - setShape(0.5f - half, 0, 0.5f - half, 0.5f + half, size, 0.5f + half); +void FlowerPotTile::updateDefaultShape() { + float size = 6.0f / 16.0f; + float half = size / 2; + setShape(0.5f - half, 0, 0.5f - half, 0.5f + half, size, 0.5f + half); } -bool FlowerPotTile::isSolidRender(bool isServerLevel) -{ - return false; +bool FlowerPotTile::isSolidRender(bool isServerLevel) { return false; } + +int FlowerPotTile::getRenderShape() { return SHAPE_FLOWER_POT; } + +bool FlowerPotTile::isCubeShaped() { return false; } + +bool FlowerPotTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly) { + std::shared_ptr item = player->inventory->getSelected(); + if (item == NULL) return false; + if (level->getData(x, y, z) != 0) return false; + int type = getTypeFromItem(item); + + if (type > 0) { + level->setData(x, y, z, type); + + if (!player->abilities.instabuild) { + if (--item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } + } + + return true; + } + + return false; } -int FlowerPotTile::getRenderShape() -{ - return SHAPE_FLOWER_POT; +int FlowerPotTile::cloneTileId(Level* level, int x, int y, int z) { + std::shared_ptr item = + getItemFromType(level->getData(x, y, z)); + + if (item == NULL) { + return Item::flowerPot_Id; + } else { + return item->id; + } } -bool FlowerPotTile::isCubeShaped() -{ - return false; +int FlowerPotTile::cloneTileData(Level* level, int x, int y, int z) { + std::shared_ptr item = + getItemFromType(level->getData(x, y, z)); + + if (item == NULL) { + return Item::flowerPot_Id; + } else { + return item->getAuxValue(); + } } -bool FlowerPotTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (item == NULL) return false; - if (level->getData(x, y, z) != 0) return false; - int type = getTypeFromItem(item); +bool FlowerPotTile::useOwnCloneData() { return true; } - if (type > 0) - { - level->setData(x, y, z, type); - - if (!player->abilities.instabuild) - { - if (--item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - - return true; - } - - return false; +bool FlowerPotTile::mayPlace(Level* level, int x, int y, int z) { + return Tile::mayPlace(level, x, y, z) && + level->isTopSolidBlocking(x, y - 1, z); } -int FlowerPotTile::cloneTileId(Level *level, int x, int y, int z) -{ - std::shared_ptr item = getItemFromType(level->getData(x, y, z)); +void FlowerPotTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (!level->isTopSolidBlocking(x, y - 1, z)) { + spawnResources(level, x, y, z, level->getData(x, y, z), 0); - if (item == NULL) - { - return Item::flowerPot_Id; - } - else - { - return item->id; - } + level->setTile(x, y, z, 0); + } } -int FlowerPotTile::cloneTileData(Level *level, int x, int y, int z) -{ - std::shared_ptr item = getItemFromType(level->getData(x, y, z)); +void FlowerPotTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); - if (item == NULL) - { - return Item::flowerPot_Id; - } - else - { - return item->getAuxValue(); - } + if (data > 0) { + std::shared_ptr item = getItemFromType(data); + if (item != NULL) popResource(level, x, y, z, item); + } } -bool FlowerPotTile::useOwnCloneData() -{ - return true; +int FlowerPotTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::flowerPot_Id; } -bool FlowerPotTile::mayPlace(Level *level, int x, int y, int z) -{ - return Tile::mayPlace(level, x, y, z) && level->isTopSolidBlocking(x, y - 1, z); +std::shared_ptr FlowerPotTile::getItemFromType(int type) { + switch (type) { + case TYPE_FLOWER_RED: + return std::shared_ptr(new ItemInstance(Tile::rose)); + case TYPE_FLOWER_YELLOW: + return std::shared_ptr( + new ItemInstance(Tile::flower)); + case TYPE_CACTUS: + return std::shared_ptr( + new ItemInstance(Tile::cactus)); + case TYPE_MUSHROOM_BROWN: + return std::shared_ptr( + new ItemInstance(Tile::mushroom1)); + case TYPE_MUSHROOM_RED: + return std::shared_ptr( + new ItemInstance(Tile::mushroom2)); + case TYPE_DEAD_BUSH: + return std::shared_ptr( + new ItemInstance(Tile::deadBush)); + case TYPE_SAPLING_DEFAULT: + return std::shared_ptr( + new ItemInstance(Tile::sapling, 1, Sapling::TYPE_DEFAULT)); + case TYPE_SAPLING_BIRCH: + return std::shared_ptr( + new ItemInstance(Tile::sapling, 1, Sapling::TYPE_BIRCH)); + case TYPE_SAPLING_EVERGREEN: + return std::shared_ptr( + new ItemInstance(Tile::sapling, 1, Sapling::TYPE_EVERGREEN)); + case TYPE_SAPLING_JUNGLE: + return std::shared_ptr( + new ItemInstance(Tile::sapling, 1, Sapling::TYPE_JUNGLE)); + case TYPE_FERN: + return std::shared_ptr( + new ItemInstance(Tile::tallgrass, 1, TallGrass::FERN)); + } + + return nullptr; } -void FlowerPotTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isTopSolidBlocking(x, y - 1, z)) - { - spawnResources(level, x, y, z, level->getData(x, y, z), 0); +int FlowerPotTile::getTypeFromItem(std::shared_ptr item) { + int id = item->getItem()->id; - level->setTile(x, y, z, 0); - } -} - -void FlowerPotTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); - - if (data > 0) - { - std::shared_ptr item = getItemFromType(data); - if (item != NULL) popResource(level, x, y, z, item); - } -} - -int FlowerPotTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::flowerPot_Id; -} - -std::shared_ptr FlowerPotTile::getItemFromType(int type) -{ - switch (type) - { - case TYPE_FLOWER_RED: - return std::shared_ptr( new ItemInstance(Tile::rose) ); - case TYPE_FLOWER_YELLOW: - return std::shared_ptr( new ItemInstance(Tile::flower) ); - case TYPE_CACTUS: - return std::shared_ptr( new ItemInstance(Tile::cactus) ); - case TYPE_MUSHROOM_BROWN: - return std::shared_ptr( new ItemInstance(Tile::mushroom1) ); - case TYPE_MUSHROOM_RED: - return std::shared_ptr( new ItemInstance(Tile::mushroom2) ); - case TYPE_DEAD_BUSH: - return std::shared_ptr( new ItemInstance(Tile::deadBush) ); - case TYPE_SAPLING_DEFAULT: - return std::shared_ptr( new ItemInstance(Tile::sapling, 1, Sapling::TYPE_DEFAULT) ); - case TYPE_SAPLING_BIRCH: - return std::shared_ptr( new ItemInstance(Tile::sapling, 1, Sapling::TYPE_BIRCH) ); - case TYPE_SAPLING_EVERGREEN: - return std::shared_ptr( new ItemInstance(Tile::sapling, 1, Sapling::TYPE_EVERGREEN) ); - case TYPE_SAPLING_JUNGLE: - return std::shared_ptr( new ItemInstance(Tile::sapling, 1, Sapling::TYPE_JUNGLE) ); - case TYPE_FERN: - return std::shared_ptr( new ItemInstance(Tile::tallgrass, 1, TallGrass::FERN) ); - } - - return nullptr; -} - -int FlowerPotTile::getTypeFromItem(std::shared_ptr item) -{ - int id = item->getItem()->id; - - if (id == Tile::rose_Id) return TYPE_FLOWER_RED; - if (id == Tile::flower_Id) return TYPE_FLOWER_YELLOW; - if (id == Tile::cactus_Id) return TYPE_CACTUS; - if (id == Tile::mushroom1_Id) return TYPE_MUSHROOM_BROWN; - if (id == Tile::mushroom2_Id) return TYPE_MUSHROOM_RED; - if (id == Tile::deadBush_Id) return TYPE_DEAD_BUSH; - - if (id == Tile::sapling_Id) - { - switch (item->getAuxValue()) - { - case Sapling::TYPE_DEFAULT: - return TYPE_SAPLING_DEFAULT; - case Sapling::TYPE_BIRCH: - return TYPE_SAPLING_BIRCH; - case Sapling::TYPE_EVERGREEN: - return TYPE_SAPLING_EVERGREEN; - case Sapling::TYPE_JUNGLE: - return TYPE_SAPLING_JUNGLE; - } - } - - if (id == Tile::tallgrass_Id) - { - switch (item->getAuxValue()) - { - case TallGrass::FERN: - return TYPE_FERN; - } - } - - return 0; + if (id == Tile::rose_Id) return TYPE_FLOWER_RED; + if (id == Tile::flower_Id) return TYPE_FLOWER_YELLOW; + if (id == Tile::cactus_Id) return TYPE_CACTUS; + if (id == Tile::mushroom1_Id) return TYPE_MUSHROOM_BROWN; + if (id == Tile::mushroom2_Id) return TYPE_MUSHROOM_RED; + if (id == Tile::deadBush_Id) return TYPE_DEAD_BUSH; + + if (id == Tile::sapling_Id) { + switch (item->getAuxValue()) { + case Sapling::TYPE_DEFAULT: + return TYPE_SAPLING_DEFAULT; + case Sapling::TYPE_BIRCH: + return TYPE_SAPLING_BIRCH; + case Sapling::TYPE_EVERGREEN: + return TYPE_SAPLING_EVERGREEN; + case Sapling::TYPE_JUNGLE: + return TYPE_SAPLING_JUNGLE; + } + } + + if (id == Tile::tallgrass_Id) { + switch (item->getAuxValue()) { + case TallGrass::FERN: + return TYPE_FERN; + } + } + + return 0; } diff --git a/Minecraft.World/Blocks/FlowerPotTile.h b/Minecraft.World/Blocks/FlowerPotTile.h index 5a615c077..e303690ed 100644 --- a/Minecraft.World/Blocks/FlowerPotTile.h +++ b/Minecraft.World/Blocks/FlowerPotTile.h @@ -2,36 +2,38 @@ #include "Tile.h" -class FlowerPotTile : public Tile -{ +class FlowerPotTile : public Tile { public: - static const int TYPE_FLOWER_RED = 1; - static const int TYPE_FLOWER_YELLOW = 2; - static const int TYPE_SAPLING_DEFAULT = 3; - static const int TYPE_SAPLING_EVERGREEN = 4; - static const int TYPE_SAPLING_BIRCH = 5; - static const int TYPE_SAPLING_JUNGLE = 6; - static const int TYPE_MUSHROOM_RED = 7; - static const int TYPE_MUSHROOM_BROWN = 8; - static const int TYPE_CACTUS = 9; - static const int TYPE_DEAD_BUSH = 10; - static const int TYPE_FERN = 11; + static const int TYPE_FLOWER_RED = 1; + static const int TYPE_FLOWER_YELLOW = 2; + static const int TYPE_SAPLING_DEFAULT = 3; + static const int TYPE_SAPLING_EVERGREEN = 4; + static const int TYPE_SAPLING_BIRCH = 5; + static const int TYPE_SAPLING_JUNGLE = 6; + static const int TYPE_MUSHROOM_RED = 7; + static const int TYPE_MUSHROOM_BROWN = 8; + static const int TYPE_CACTUS = 9; + static const int TYPE_DEAD_BUSH = 10; + static const int TYPE_FERN = 11; - FlowerPotTile(int id); + FlowerPotTile(int id); - void updateDefaultShape(); - bool isSolidRender(bool isServerLevel = false); - int getRenderShape(); - bool isCubeShaped(); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); - int cloneTileId(Level *level, int x, int y, int z); - int cloneTileData(Level *level, int x, int y, int z); - bool useOwnCloneData(); - bool mayPlace(Level *level, int x, int y, int z); - void neighborChanged(Level *level, int x, int y, int z, int type); - using Tile::spawnResources; - void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); - int getResource(int data, Random *random, int playerBonusLevel); - static std::shared_ptr getItemFromType(int type); - static int getTypeFromItem(std::shared_ptr item); + void updateDefaultShape(); + bool isSolidRender(bool isServerLevel = false); + int getRenderShape(); + bool isCubeShaped(); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); + int cloneTileId(Level* level, int x, int y, int z); + int cloneTileData(Level* level, int x, int y, int z); + bool useOwnCloneData(); + bool mayPlace(Level* level, int x, int y, int z); + void neighborChanged(Level* level, int x, int y, int z, int type); + using Tile::spawnResources; + void spawnResources(Level* level, int x, int y, int z, int data, float odds, + int playerBonusLevel); + int getResource(int data, Random* random, int playerBonusLevel); + static std::shared_ptr getItemFromType(int type); + static int getTypeFromItem(std::shared_ptr item); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/FurnaceTile.cpp b/Minecraft.World/Blocks/FurnaceTile.cpp index 5915222f6..49638f0a7 100644 --- a/Minecraft.World/Blocks/FurnaceTile.cpp +++ b/Minecraft.World/Blocks/FurnaceTile.cpp @@ -11,198 +11,188 @@ bool FurnaceTile::noDrop = false; -FurnaceTile::FurnaceTile(int id, bool lit) : EntityTile(id, Material::stone) -{ - random = new Random(); - this->lit = lit; - - iconTop = NULL; - iconFront = NULL; +FurnaceTile::FurnaceTile(int id, bool lit) : EntityTile(id, Material::stone) { + random = new Random(); + this->lit = lit; + + iconTop = NULL; + iconFront = NULL; } -int FurnaceTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::furnace_Id; +int FurnaceTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::furnace_Id; } -void FurnaceTile::onPlace(Level *level, int x, int y, int z) -{ - EntityTile::onPlace(level, x, y, z); - recalcLockDir(level, x, y, z); +void FurnaceTile::onPlace(Level* level, int x, int y, int z) { + EntityTile::onPlace(level, x, y, z); + recalcLockDir(level, x, y, z); } -void FurnaceTile::recalcLockDir(Level *level, int x, int y, int z) -{ - if (level->isClientSide) - { - return; - } +void FurnaceTile::recalcLockDir(Level* level, int x, int y, int z) { + if (level->isClientSide) { + return; + } - int n = level->getTile(x, y, z - 1); // face = 2 - int s = level->getTile(x, y, z + 1); // face = 3 - int w = level->getTile(x - 1, y, z); // face = 4 - int e = level->getTile(x + 1, y, z); // face = 5 + int n = level->getTile(x, y, z - 1); // face = 2 + int s = level->getTile(x, y, z + 1); // face = 3 + int w = level->getTile(x - 1, y, z); // face = 4 + int e = level->getTile(x + 1, y, z); // face = 5 - int lockDir = 3; - if (Tile::solid[n] && !Tile::solid[s]) lockDir = 3; - if (Tile::solid[s] && !Tile::solid[n]) lockDir = 2; - if (Tile::solid[w] && !Tile::solid[e]) lockDir = 5; - if (Tile::solid[e] && !Tile::solid[w]) lockDir = 4; - level->setData(x, y, z, lockDir); + int lockDir = 3; + if (Tile::solid[n] && !Tile::solid[s]) lockDir = 3; + if (Tile::solid[s] && !Tile::solid[n]) lockDir = 2; + if (Tile::solid[w] && !Tile::solid[e]) lockDir = 5; + if (Tile::solid[e] && !Tile::solid[w]) lockDir = 4; + level->setData(x, y, z, lockDir); } -Icon *FurnaceTile::getTexture(int face, int data) -{ - if (face == Facing::UP) return iconTop; - if (face == Facing::DOWN) return iconTop; +Icon* FurnaceTile::getTexture(int face, int data) { + if (face == Facing::UP) return iconTop; + if (face == Facing::DOWN) return iconTop; - if (face != data) return icon; - return iconFront; + if (face != data) return icon; + return iconFront; } -void FurnaceTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"furnace_side"); - iconFront = iconRegister->registerIcon(lit ? L"furnace_front_lit" : L"furnace_front"); - iconTop = iconRegister->registerIcon(L"furnace_top"); +void FurnaceTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"furnace_side"); + iconFront = iconRegister->registerIcon(lit ? L"furnace_front_lit" + : L"furnace_front"); + iconTop = iconRegister->registerIcon(L"furnace_top"); } -void FurnaceTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ - if (!lit) return; +void FurnaceTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { + if (!lit) return; - int dir = level->getData(xt, yt, zt); + int dir = level->getData(xt, yt, zt); - float x = xt + 0.5f; - float y = yt + 0.0f + random->nextFloat() * 6 / 16.0f; - float z = zt + 0.5f; - float r = 0.52f; - float ss = random->nextFloat() * 0.6f - 0.3f; + float x = xt + 0.5f; + float y = yt + 0.0f + random->nextFloat() * 6 / 16.0f; + float z = zt + 0.5f; + float r = 0.52f; + float ss = random->nextFloat() * 0.6f - 0.3f; - if (dir == 4) - { - level->addParticle(eParticleType_smoke, x - r, y, z + ss, 0, 0, 0); - level->addParticle(eParticleType_flame, x - r, y, z + ss, 0, 0, 0); - } else if (dir == 5) - { - level->addParticle(eParticleType_smoke, x + r, y, z + ss, 0, 0, 0); - level->addParticle(eParticleType_flame, x + r, y, z + ss, 0, 0, 0); - } else if (dir == 2) - { - level->addParticle(eParticleType_smoke, x + ss, y, z - r, 0, 0, 0); - level->addParticle(eParticleType_flame, x + ss, y, z - r, 0, 0, 0); - } else if (dir == 3) - { - level->addParticle(eParticleType_smoke, x + ss, y, z + r, 0, 0, 0); - level->addParticle(eParticleType_flame, x + ss, y, z + r, 0, 0, 0); - } + if (dir == 4) { + level->addParticle(eParticleType_smoke, x - r, y, z + ss, 0, 0, 0); + level->addParticle(eParticleType_flame, x - r, y, z + ss, 0, 0, 0); + } else if (dir == 5) { + level->addParticle(eParticleType_smoke, x + r, y, z + ss, 0, 0, 0); + level->addParticle(eParticleType_flame, x + r, y, z + ss, 0, 0, 0); + } else if (dir == 2) { + level->addParticle(eParticleType_smoke, x + ss, y, z - r, 0, 0, 0); + level->addParticle(eParticleType_flame, x + ss, y, z - r, 0, 0, 0); + } else if (dir == 3) { + level->addParticle(eParticleType_smoke, x + ss, y, z + r, 0, 0, 0); + level->addParticle(eParticleType_flame, x + ss, y, z + r, 0, 0, 0); + } } // 4J-PB - Adding a TestUse for tooltip display -bool FurnaceTile::TestUse() +bool FurnaceTile::TestUse() { return true; } + +bool FurnaceTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (soundOnly) return false; + + if (level->isClientSide) { + return true; + } + std::shared_ptr furnace = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (furnace != NULL) player->openFurnace(furnace); + return true; } -bool FurnaceTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if( soundOnly) return false; +void FurnaceTile::setLit(bool lit, Level* level, int x, int y, int z) { + int data = level->getData(x, y, z); + std::shared_ptr te = level->getTileEntity(x, y, z); - if (level->isClientSide) - { - return true; - } - std::shared_ptr furnace = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (furnace != NULL ) player->openFurnace(furnace); - return true; + noDrop = true; + if (lit) + level->setTile(x, y, z, Tile::furnace_lit_Id); + else + level->setTile(x, y, z, Tile::furnace_Id); + noDrop = false; + + level->setData(x, y, z, data); + if (te != NULL) { + te->clearRemoved(); + level->setTileEntity(x, y, z, te); + } } -void FurnaceTile::setLit(bool lit, Level *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - std::shared_ptr te = level->getTileEntity(x, y, z); - - noDrop = true; - if (lit) level->setTile(x, y, z, Tile::furnace_lit_Id); - else level->setTile(x, y, z, Tile::furnace_Id); - noDrop = false; - - level->setData(x, y, z, data); - if( te != NULL ) - { - te->clearRemoved(); - level->setTileEntity(x, y, z, te); - } +std::shared_ptr FurnaceTile::newTileEntity(Level* level) { + return std::shared_ptr(new FurnaceTileEntity()); } -std::shared_ptr FurnaceTile::newTileEntity(Level *level) -{ - return std::shared_ptr( new FurnaceTileEntity() ); +void FurnaceTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; + + if (dir == 0) level->setData(x, y, z, Facing::NORTH); + if (dir == 1) level->setData(x, y, z, Facing::EAST); + if (dir == 2) level->setData(x, y, z, Facing::SOUTH); + if (dir == 3) level->setData(x, y, z, Facing::WEST); } -void FurnaceTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; +void FurnaceTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + if (!noDrop) { + std::shared_ptr container = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (container != NULL) { + for (unsigned int i = 0; i < container->getContainerSize(); i++) { + std::shared_ptr item = container->getItem(i); + if (item != NULL) { + float xo = random->nextFloat() * 0.8f + 0.1f; + float yo = random->nextFloat() * 0.8f + 0.1f; + float zo = random->nextFloat() * 0.8f + 0.1f; - if (dir == 0) level->setData(x, y, z, Facing::NORTH); - if (dir == 1) level->setData(x, y, z, Facing::EAST); - if (dir == 2) level->setData(x, y, z, Facing::SOUTH); - if (dir == 3) level->setData(x, y, z, Facing::WEST); -} - -void FurnaceTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - if (!noDrop) - { - std::shared_ptr container = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if( container != NULL ) - { - for (unsigned int i = 0; i < container->getContainerSize(); i++) - { - std::shared_ptr item = container->getItem(i); - if (item != NULL) - { - float xo = random->nextFloat() * 0.8f + 0.1f; - float yo = random->nextFloat() * 0.8f + 0.1f; - float zo = random->nextFloat() * 0.8f + 0.1f; - - while (item->count > 0) - { - int count = random->nextInt(21) + 10; - if (count > item->count) count = item->count; - item->count -= count; + while (item->count > 0) { + int count = random->nextInt(21) + 10; + if (count > item->count) count = item->count; + item->count -= count; #ifndef _CONTENT_PACKAGE - if(level->isClientSide) - { - printf("Client furnace dropping %d of %d/%d\n", count, item->id, item->getAuxValue() ); - } - else - { - printf("Server furnace dropping %d of %d/%d\n", count, item->id, item->getAuxValue() ); - } + if (level->isClientSide) { + printf("Client furnace dropping %d of %d/%d\n", + count, item->id, item->getAuxValue()); + } else { + printf("Server furnace dropping %d of %d/%d\n", + count, item->id, item->getAuxValue()); + } #endif - - std::shared_ptr newItem = std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue()) ); - newItem->set4JData( item->get4JData() ); - std::shared_ptr itemEntity = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, newItem) ); - float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); - } - level->addEntity(itemEntity); - } - // 4J Stu - Fix for duplication glitch - container->setItem(i,nullptr); - } - } - } - } - EntityTile::onRemove(level, x, y, z, id, data); + std::shared_ptr newItem = + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())); + newItem->set4JData(item->get4JData()); + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, newItem)); + float pow = 0.05f; + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = + (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); + } + level->addEntity(itemEntity); + } + // 4J Stu - Fix for duplication glitch + container->setItem(i, nullptr); + } + } + } + } + EntityTile::onRemove(level, x, y, z, id, data); } diff --git a/Minecraft.World/Blocks/FurnaceTile.h b/Minecraft.World/Blocks/FurnaceTile.h index 9513e9741..c48d16105 100644 --- a/Minecraft.World/Blocks/FurnaceTile.h +++ b/Minecraft.World/Blocks/FurnaceTile.h @@ -6,34 +6,44 @@ class Player; class Random; class ChunkRebuildData; -class FurnaceTile : public EntityTile -{ - friend class Tile; - friend class ChunkRebuildData; +class FurnaceTile : public EntityTile { + friend class Tile; + friend class ChunkRebuildData; + private: - Random *random; + Random* random; bool lit; static bool noDrop; - Icon *iconTop; - Icon *iconFront; + Icon* iconTop; + Icon* iconFront; protected: - FurnaceTile(int id, bool lit); + FurnaceTile(int id, bool lit); + public: - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void onPlace(Level *level, int x, int y, int z); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void onPlace(Level* level, int x, int y, int z); + private: - void recalcLockDir(Level *level, int x, int y, int z); + void recalcLockDir(Level* level, int x, int y, int z); + public: - Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - static void setLit(bool lit, Level *level, int x, int y, int z); + Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + static void setLit(bool lit, Level* level, int x, int y, int z); + protected: - virtual std::shared_ptr newTileEntity(Level *level); + virtual std::shared_ptr newTileEntity(Level* level); + public: - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/GasMaterial.h b/Minecraft.World/Blocks/GasMaterial.h index 1ad23a539..24b0da4ec 100644 --- a/Minecraft.World/Blocks/GasMaterial.h +++ b/Minecraft.World/Blocks/GasMaterial.h @@ -1,12 +1,11 @@ #pragma once #include "Material.h" -class GasMaterial : public Material -{ +class GasMaterial : public Material { public: - GasMaterial(MaterialColor *color) : Material(color) { replaceable(); } + GasMaterial(MaterialColor* color) : Material(color) { replaceable(); } - virtual bool isSolid() { return false; } - virtual bool blocksLight() { return false; } - virtual bool blocksMotion() { return false; } + virtual bool isSolid() { return false; } + virtual bool blocksLight() { return false; } + virtual bool blocksMotion() { return false; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/GlassTile.cpp b/Minecraft.World/Blocks/GlassTile.cpp index c5051e403..fdc9f0abc 100644 --- a/Minecraft.World/Blocks/GlassTile.cpp +++ b/Minecraft.World/Blocks/GlassTile.cpp @@ -1,31 +1,15 @@ #include "../Platform/stdafx.h" #include "GlassTile.h" -GlassTile::GlassTile(int id, Material *material, bool allowSame) : HalfTransparentTile(id, L"glass", material, allowSame) -{ -} +GlassTile::GlassTile(int id, Material* material, bool allowSame) + : HalfTransparentTile(id, L"glass", material, allowSame) {} -int GlassTile::getResourceCount(Random *random) -{ - return 0; -} +int GlassTile::getResourceCount(Random* random) { return 0; } -int GlassTile::getRenderLayer() -{ - return 0; -} +int GlassTile::getRenderLayer() { return 0; } -bool GlassTile::isSolidRender() -{ - return false; -} +bool GlassTile::isSolidRender() { return false; } -bool GlassTile::isCubeShaped() -{ - return false; -} +bool GlassTile::isCubeShaped() { return false; } -bool GlassTile::isSilkTouchable() -{ - return true; -} \ No newline at end of file +bool GlassTile::isSilkTouchable() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/GlassTile.h b/Minecraft.World/Blocks/GlassTile.h index 77c62759f..2f84734b1 100644 --- a/Minecraft.World/Blocks/GlassTile.h +++ b/Minecraft.World/Blocks/GlassTile.h @@ -3,15 +3,14 @@ class Random; -class GlassTile : public HalfTransparentTile -{ +class GlassTile : public HalfTransparentTile { public: - using HalfTransparentTile::isSolidRender; + using HalfTransparentTile::isSolidRender; - GlassTile(int id, Material *material, bool allowSame); - virtual int getResourceCount(Random *random); - virtual int getRenderLayer(); - virtual bool isSolidRender(); - virtual bool isCubeShaped(); - virtual bool isSilkTouchable(); + GlassTile(int id, Material* material, bool allowSame); + virtual int getResourceCount(Random* random); + virtual int getRenderLayer(); + virtual bool isSolidRender(); + virtual bool isCubeShaped(); + virtual bool isSilkTouchable(); }; diff --git a/Minecraft.World/Blocks/GrassTile.cpp b/Minecraft.World/Blocks/GrassTile.cpp index f5d7b9c76..5494b429f 100644 --- a/Minecraft.World/Blocks/GrassTile.cpp +++ b/Minecraft.World/Blocks/GrassTile.cpp @@ -10,137 +10,125 @@ #include "../IO/Streams/IntBuffer.h" #include "../../Minecraft.Client/Rendering/Tesselator.h" -GrassTile::GrassTile(int id) : Tile(id, Material::grass) -{ - iconTop = NULL; - iconSnowSide = NULL; - iconSideOverlay = NULL; +GrassTile::GrassTile(int id) : Tile(id, Material::grass) { + iconTop = NULL; + iconSnowSide = NULL; + iconSideOverlay = NULL; setTicking(true); } -Icon *GrassTile::getTexture(int face, int data) -{ +Icon* GrassTile::getTexture(int face, int data) { if (face == Facing::UP) return iconTop; if (face == Facing::DOWN) return Tile::dirt->getTexture(face); return icon; } -Icon *GrassTile::getTexture(LevelSource *level, int x, int y, int z, int face) -{ +Icon* GrassTile::getTexture(LevelSource* level, int x, int y, int z, int face) { if (face == Facing::UP) return iconTop; if (face == Facing::DOWN) return Tile::dirt->getTexture(face); - Material *above = level->getMaterial(x, y + 1, z); - if (above == Material::topSnow || above == Material::snow) return iconSnowSide; - else return icon; + Material* above = level->getMaterial(x, y + 1, z); + if (above == Material::topSnow || above == Material::snow) + return iconSnowSide; + else + return icon; } -void GrassTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"grass_side"); - iconTop = iconRegister->registerIcon(L"grass_top"); - iconSnowSide = iconRegister->registerIcon(L"snow_side"); - iconSideOverlay = iconRegister->registerIcon(L"grass_side_overlay"); +void GrassTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"grass_side"); + iconTop = iconRegister->registerIcon(L"grass_top"); + iconSnowSide = iconRegister->registerIcon(L"snow_side"); + iconSideOverlay = iconRegister->registerIcon(L"grass_side_overlay"); } -int GrassTile::getColor() const -{ - // 4J Replaced - //double temp = 0.5; - //double rain = 1.0; +int GrassTile::getColor() const { + // 4J Replaced + // double temp = 0.5; + // double rain = 1.0; - //return GrassColor::get(temp, rain); + // return GrassColor::get(temp, rain); - return Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Grass_Common ); + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Grass_Common); } -int GrassTile::getColor(int auxData) -{ - return getColor(); +int GrassTile::getColor(int auxData) { return getColor(); } + +int GrassTile::getColor(LevelSource* level, int x, int y, int z) { + return getColor(level, x, y, z, level->getData(x, y, z)); } -int GrassTile::getColor(LevelSource *level, int x, int y, int z) -{ - return getColor( level, x, y, z, level->getData( x, y, z ) ); +// 4J - changed interface to have data passed in, and put existing interface as +// wrapper above +int GrassTile::getColor(LevelSource* level, int x, int y, int z, int data) { + // return level->getBiomeSource()->getBiome(x, z)->getGrassColor(level, x, + // y, z); + + int totalRed = 0; + int totalGreen = 0; + int totalBlue = 0; + + for (int oz = -1; oz <= 1; oz++) { + for (int ox = -1; ox <= 1; ox++) { + int grassColor = level->getBiome(x + ox, z + oz)->getGrassColor(); + + totalRed += (grassColor & 0xff0000) >> 16; + totalGreen += (grassColor & 0xff00) >> 8; + totalBlue += (grassColor & 0xff); + } + } + + return (((totalRed / 9) & 0xFF) << 16) | (((totalGreen / 9) & 0xFF) << 8) | + (((totalBlue / 9) & 0xFF)); } -// 4J - changed interface to have data passed in, and put existing interface as wrapper above -int GrassTile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - //return level->getBiomeSource()->getBiome(x, z)->getGrassColor(level, x, y, z); - - int totalRed = 0; - int totalGreen = 0; - int totalBlue = 0; - - for (int oz = -1; oz <= 1; oz++) - { - for (int ox = -1; ox <= 1; ox++) - { - int grassColor = level->getBiome(x + ox, z + oz)->getGrassColor(); - - totalRed += (grassColor & 0xff0000) >> 16; - totalGreen += (grassColor & 0xff00) >> 8; - totalBlue += (grassColor & 0xff); - } - } - - return (((totalRed / 9) & 0xFF) << 16) | (((totalGreen / 9) & 0xFF) << 8) | (((totalBlue / 9) & 0xFF)); -} - -void GrassTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void GrassTile::tick(Level* level, int x, int y, int z, Random* random) { if (level->isClientSide) return; - if (level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) - { + if (level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && + Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) { level->setTile(x, y, z, Tile::dirt_Id); - } - else - { - if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) - { - for (int i = 0; i < 4; i++) - { - int xt = x + random->nextInt(3) - 1; - int yt = y + random->nextInt(5) - 3; - int zt = z + random->nextInt(3) - 1; - int above = level->getTile(xt, yt + 1, zt); - if (level->getTile(xt, yt, zt) == Tile::dirt_Id && level->getRawBrightness(xt, yt + 1, zt) >= MIN_BRIGHTNESS && Tile::lightBlock[above] <= 2) - { - level->setTile(xt, yt, zt, Tile::grass_Id); - } - } + } else { + if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) { + for (int i = 0; i < 4; i++) { + int xt = x + random->nextInt(3) - 1; + int yt = y + random->nextInt(5) - 3; + int zt = z + random->nextInt(3) - 1; + int above = level->getTile(xt, yt + 1, zt); + if (level->getTile(xt, yt, zt) == Tile::dirt_Id && + level->getRawBrightness(xt, yt + 1, zt) >= MIN_BRIGHTNESS && + Tile::lightBlock[above] <= 2) { + level->setTile(xt, yt, zt, Tile::grass_Id); + } + } } } } -int GrassTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::dirt->getResource(0, random, playerBonusLevel); +int GrassTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::dirt->getResource(0, random, playerBonusLevel); } -Icon *GrassTile::getSideTextureOverlay() -{ +Icon* GrassTile::getSideTextureOverlay() { #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Because of the way grass sides are treated as special case we need to set the alpha flag here - // this would normally happen in TileRenderer::getTextureOrMissing - Tesselator* t = Tesselator::getInstance(); - t->setAlphaCutOut( true ); + // AP - alpha cut out is expensive on vita. Because of the way grass sides + // are treated as special case we need to set the alpha flag here this would + // normally happen in TileRenderer::getTextureOrMissing + Tesselator* t = Tesselator::getInstance(); + t->setAlphaCutOut(true); #endif - return Tile::grass->iconSideOverlay; + return Tile::grass->iconSideOverlay; } -bool GrassTile::shouldTileTick(Level *level, int x,int y,int z) -{ - bool should = false; +bool GrassTile::shouldTileTick(Level* level, int x, int y, int z) { + bool should = false; - if( (level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) || - (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) ) - { - should = true; - } + if ((level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && + Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) || + (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6)) { + should = true; + } - return should; + return should; } diff --git a/Minecraft.World/Blocks/GrassTile.h b/Minecraft.World/Blocks/GrassTile.h index 41b595741..2913051d0 100644 --- a/Minecraft.World/Blocks/GrassTile.h +++ b/Minecraft.World/Blocks/GrassTile.h @@ -3,31 +3,35 @@ class Level; class ChunkRebuildData; -class GrassTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class GrassTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; + private: - Icon *iconTop; - Icon *iconSnowSide; - Icon *iconSideOverlay; + Icon* iconTop; + Icon* iconSnowSide; + Icon* iconSideOverlay; + public: - static const int MIN_BRIGHTNESS = 4; + static const int MIN_BRIGHTNESS = 4; protected: - GrassTile(int id); + GrassTile(int id); + public: - virtual Icon *getTexture(int face, int data); - virtual Icon *getTexture(LevelSource *level, int x, int y, int z, int face); - void registerIcons(IconRegister *iconRegister); + virtual Icon* getTexture(int face, int data); + virtual Icon* getTexture(LevelSource* level, int x, int y, int z, int face); + void registerIcons(IconRegister* iconRegister); virtual int getColor() const; - virtual int getColor(int auxData); - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - static Icon *getSideTextureOverlay(); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual int getColor(int auxData); + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + static Icon* getSideTextureOverlay(); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/GravelTile.cpp b/Minecraft.World/Blocks/GravelTile.cpp index 53b6ed40d..4441a5639 100644 --- a/Minecraft.World/Blocks/GravelTile.cpp +++ b/Minecraft.World/Blocks/GravelTile.cpp @@ -2,12 +2,9 @@ #include "GravelTile.h" #include "../Headers/net.minecraft.world.item.h" -GravelTile::GravelTile(int type) : HeavyTile(type) -{ -} +GravelTile::GravelTile(int type) : HeavyTile(type) {} -int GravelTile::getResource(int data, Random *random, int playerBonusLevel) -{ +int GravelTile::getResource(int data, Random* random, int playerBonusLevel) { if (random->nextInt(10 - playerBonusLevel * 3) == 0) return Item::flint->id; return id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/GravelTile.h b/Minecraft.World/Blocks/GravelTile.h index 0457a9e99..1ac875334 100644 --- a/Minecraft.World/Blocks/GravelTile.h +++ b/Minecraft.World/Blocks/GravelTile.h @@ -3,9 +3,8 @@ class Random; -class GravelTile : public HeavyTile -{ +class GravelTile : public HeavyTile { public: - GravelTile(int type); - virtual int getResource(int data, Random *random, int playerBonusLevel); + GravelTile(int type); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; diff --git a/Minecraft.World/Blocks/HalfSlabTile.cpp b/Minecraft.World/Blocks/HalfSlabTile.cpp index 328b60b95..b9272322f 100644 --- a/Minecraft.World/Blocks/HalfSlabTile.cpp +++ b/Minecraft.World/Blocks/HalfSlabTile.cpp @@ -16,128 +16,106 @@ import net.minecraft.world.level.*; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.AABB;*/ +HalfSlabTile::HalfSlabTile(int id, bool fullSize, Material* material) + : Tile(id, material, fullSize) { + this->fullSize = fullSize; - -HalfSlabTile::HalfSlabTile(int id, bool fullSize, Material *material) : Tile(id, material, fullSize) -{ - this->fullSize = fullSize; - - if (fullSize) - { - solid[id] = true; - } - else - { - setShape(0, 0, 0, 1, 0.5f, 1); - } - setLightBlock(255); + if (fullSize) { + solid[id] = true; + } else { + setShape(0, 0, 0, 1, 0.5f, 1); + } + setLightBlock(255); } -void HalfSlabTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void HalfSlabTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - if (fullSize) - { - setShape(0, 0, 0, 1, 1, 1); - } - else - { - bool upper = (level->getData(x, y, z) & TOP_SLOT_BIT) != 0; - if (upper) - { - setShape(0, 0.5f, 0, 1, 1, 1); - } - else - { - setShape(0, 0, 0, 1, 0.5f, 1); - } - } + if (fullSize) { + setShape(0, 0, 0, 1, 1, 1); + } else { + bool upper = (level->getData(x, y, z) & TOP_SLOT_BIT) != 0; + if (upper) { + setShape(0, 0.5f, 0, 1, 1, 1); + } else { + setShape(0, 0, 0, 1, 0.5f, 1); + } + } } -void HalfSlabTile::updateDefaultShape() -{ - if (fullSize) - { - setShape(0, 0, 0, 1, 1, 1); - } - else - { - setShape(0, 0, 0, 1, 0.5f, 1); - } +void HalfSlabTile::updateDefaultShape() { + if (fullSize) { + setShape(0, 0, 0, 1, 1, 1); + } else { + setShape(0, 0, 0, 1, 0.5f, 1); + } } -void HalfSlabTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ - updateShape(level, x, y, z); - Tile::addAABBs(level, x, y, z, box, boxes, source); +void HalfSlabTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { + updateShape(level, x, y, z); + Tile::addAABBs(level, x, y, z, box, boxes, source); } -bool HalfSlabTile::isSolidRender(bool isServerLevel) -{ - return fullSize; +bool HalfSlabTile::isSolidRender(bool isServerLevel) { return fullSize; } + +int HalfSlabTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + if (fullSize) return itemValue; + + if (face == Facing::DOWN || (face != Facing::UP && clickY > 0.5)) { + return itemValue | TOP_SLOT_BIT; + } + return itemValue; } -int HalfSlabTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - if (fullSize) return itemValue; - - if (face == Facing::DOWN || (face != Facing::UP && clickY > 0.5)) - { - return itemValue | TOP_SLOT_BIT; - } - return itemValue; +int HalfSlabTile::getResourceCount(Random* random) { + if (fullSize) { + return 2; + } + return 1; } -int HalfSlabTile::getResourceCount(Random *random) -{ - if (fullSize) - { - return 2; - } - return 1; +int HalfSlabTile::getSpawnResourcesAuxValue(int data) { + return data & TYPE_MASK; } -int HalfSlabTile::getSpawnResourcesAuxValue(int data) -{ - return data & TYPE_MASK; +bool HalfSlabTile::isCubeShaped() { return fullSize; } + +bool HalfSlabTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + if (fullSize) return Tile::shouldRenderFace(level, x, y, z, face); + + if (face != Facing::UP && face != Facing::DOWN && + !Tile::shouldRenderFace(level, x, y, z, face)) { + return false; + } + + int ox = x, oy = y, oz = z; + ox += Facing::STEP_X[Facing::OPPOSITE_FACING[face]]; + oy += Facing::STEP_Y[Facing::OPPOSITE_FACING[face]]; + oz += Facing::STEP_Z[Facing::OPPOSITE_FACING[face]]; + + boolean isUpper = (level->getData(ox, oy, oz) & TOP_SLOT_BIT) != 0; + if (isUpper) { + if (face == Facing::DOWN) return true; + if (face == Facing::UP && Tile::shouldRenderFace(level, x, y, z, face)) + return true; + return !(isHalfSlab(level->getTile(x, y, z)) && + (level->getData(x, y, z) & TOP_SLOT_BIT) != 0); + } else { + if (face == Facing::UP) return true; + if (face == Facing::DOWN && + Tile::shouldRenderFace(level, x, y, z, face)) + return true; + return !(isHalfSlab(level->getTile(x, y, z)) && + (level->getData(x, y, z) & TOP_SLOT_BIT) == 0); + } } -bool HalfSlabTile::isCubeShaped() -{ - return fullSize; +bool HalfSlabTile::isHalfSlab(int tileId) { + return tileId == Tile::stoneSlabHalf_Id || tileId == Tile::woodSlabHalf_Id; } - -bool HalfSlabTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - if (fullSize) return Tile::shouldRenderFace(level, x, y, z, face); - - if (face != Facing::UP && face != Facing::DOWN && !Tile::shouldRenderFace(level, x, y, z, face)) - { - return false; - } - - int ox = x, oy = y, oz = z; - ox += Facing::STEP_X[Facing::OPPOSITE_FACING[face]]; - oy += Facing::STEP_Y[Facing::OPPOSITE_FACING[face]]; - oz += Facing::STEP_Z[Facing::OPPOSITE_FACING[face]]; - - boolean isUpper = (level->getData(ox, oy, oz) & TOP_SLOT_BIT) != 0; - if (isUpper) - { - if (face == Facing::DOWN) return true; - if (face == Facing::UP && Tile::shouldRenderFace(level, x, y, z, face)) return true; - return !(isHalfSlab(level->getTile(x, y, z)) && (level->getData(x, y, z) & TOP_SLOT_BIT) != 0); - } - else - { - if (face == Facing::UP) return true; - if (face == Facing::DOWN && Tile::shouldRenderFace(level, x, y, z, face)) return true; - return !(isHalfSlab(level->getTile(x, y, z)) && (level->getData(x, y, z) & TOP_SLOT_BIT) == 0); - } -} - -bool HalfSlabTile::isHalfSlab(int tileId) -{ - return tileId == Tile::stoneSlabHalf_Id || tileId == Tile::woodSlabHalf_Id; -} - - diff --git a/Minecraft.World/Blocks/HalfSlabTile.h b/Minecraft.World/Blocks/HalfSlabTile.h index bd5f6dfc6..67ca7cd2e 100644 --- a/Minecraft.World/Blocks/HalfSlabTile.h +++ b/Minecraft.World/Blocks/HalfSlabTile.h @@ -2,32 +2,36 @@ #include "Tile.h" - -class HalfSlabTile : public Tile -{ - - +class HalfSlabTile : public Tile { public: - static const int TYPE_MASK = 7; - static const int TOP_SLOT_BIT = 8; + static const int TYPE_MASK = 7; + static const int TOP_SLOT_BIT = 8; protected: - bool fullSize; + bool fullSize; public: - HalfSlabTile(int id, bool fullSize, Material *material); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual void updateDefaultShape(); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual bool isSolidRender(bool isServerLevel); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual int getResourceCount(Random *random); - virtual int getSpawnResourcesAuxValue(int data); - virtual bool isCubeShaped(); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + HalfSlabTile(int id, bool fullSize, Material* material); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual void updateDefaultShape(); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual bool isSolidRender(bool isServerLevel); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual int getResourceCount(Random* random); + virtual int getSpawnResourcesAuxValue(int data); + virtual bool isCubeShaped(); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + private: - static bool isHalfSlab(int tileId); -public: - virtual int getAuxName(int auxValue) = 0; + static bool isHalfSlab(int tileId); +public: + virtual int getAuxName(int auxValue) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/HalfTransparentTile.cpp b/Minecraft.World/Blocks/HalfTransparentTile.cpp index aad08fa5f..762e0ba11 100644 --- a/Minecraft.World/Blocks/HalfTransparentTile.cpp +++ b/Minecraft.World/Blocks/HalfTransparentTile.cpp @@ -3,30 +3,24 @@ #include "../Headers/net.minecraft.world.h" #include "HalfTransparentTile.h" -HalfTransparentTile::HalfTransparentTile(int id, const std::wstring &tex, Material *material, bool allowSame) : Tile(id,material, false) -{ - this->allowSame = allowSame; - this->texture = tex; +HalfTransparentTile::HalfTransparentTile(int id, const std::wstring& tex, + Material* material, bool allowSame) + : Tile(id, material, false) { + this->allowSame = allowSame; + this->texture = tex; } -bool HalfTransparentTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool HalfTransparentTile::isSolidRender(bool isServerLevel) { return false; } -bool HalfTransparentTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ +bool HalfTransparentTile::shouldRenderFace(LevelSource* level, int x, int y, + int z, int face) { int id = level->getTile(x, y, z); if (!allowSame && id == this->id) return false; return Tile::shouldRenderFace(level, x, y, z, face); } -bool HalfTransparentTile::blocksLight() -{ - return false; -} +bool HalfTransparentTile::blocksLight() { return false; } -void HalfTransparentTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(texture); +void HalfTransparentTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(texture); } diff --git a/Minecraft.World/Blocks/HalfTransparentTile.h b/Minecraft.World/Blocks/HalfTransparentTile.h index b74cbeca0..062f2d6dd 100644 --- a/Minecraft.World/Blocks/HalfTransparentTile.h +++ b/Minecraft.World/Blocks/HalfTransparentTile.h @@ -3,17 +3,21 @@ class ChunkRebuildData; -class HalfTransparentTile : public Tile -{ - friend class ChunkRebuildData; +class HalfTransparentTile : public Tile { + friend class ChunkRebuildData; + private: - bool allowSame; - std::wstring texture; + bool allowSame; + std::wstring texture; + protected: - HalfTransparentTile(int id, const std::wstring &tex, Material *material, bool allowSame); + HalfTransparentTile(int id, const std::wstring& tex, Material* material, + bool allowSame); + public: virtual bool isSolidRender(bool isServerLevel = false); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); virtual bool blocksLight(); - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/HeavyTile.cpp b/Minecraft.World/Blocks/HeavyTile.cpp index 7e2ae7378..f03f37410 100644 --- a/Minecraft.World/Blocks/HeavyTile.cpp +++ b/Minecraft.World/Blocks/HeavyTile.cpp @@ -6,86 +6,69 @@ bool HeavyTile::instaFall = false; -HeavyTile::HeavyTile(int type, bool isSolidRender) : Tile(type, Material::sand, isSolidRender) -{ +HeavyTile::HeavyTile(int type, bool isSolidRender) + : Tile(type, Material::sand, isSolidRender) {} + +HeavyTile::HeavyTile(int type, Material* material, bool isSolidRender) + : Tile(type, material, isSolidRender) {} + +void HeavyTile::onPlace(Level* level, int x, int y, int z) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); } -HeavyTile::HeavyTile(int type, Material *material, bool isSolidRender) : Tile(type, material, isSolidRender) -{ +void HeavyTile::neighborChanged(Level* level, int x, int y, int z, int type) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); } -void HeavyTile::onPlace(Level *level, int x, int y, int z) -{ - level->addToTickNextTick(x, y, z, id, getTickDelay()); +void HeavyTile::tick(Level* level, int x, int y, int z, Random* random) { + if (!level->isClientSide) { + checkSlide(level, x, y, z); + } } -void HeavyTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - level->addToTickNextTick(x, y, z, id, getTickDelay()); -} - -void HeavyTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if(!level->isClientSide) - { - checkSlide(level, x, y, z); - } -} - -void HeavyTile::checkSlide(Level *level, int x, int y, int z) -{ +void HeavyTile::checkSlide(Level* level, int x, int y, int z) { int x2 = x; int y2 = y; int z2 = z; - if (isFree(level, x2, y2 - 1, z2) && y2 >= 0) - { + if (isFree(level, x2, y2 - 1, z2) && y2 >= 0) { int r = 32; - if (instaFall || !level->hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r) ) - { + if (instaFall || + !level->hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) { level->setTile(x, y, z, 0); - while (isFree(level, x, y - 1, z) && y > 0) - y--; + while (isFree(level, x, y - 1, z) && y > 0) y--; if (y > 0) { level->setTile(x, y, z, id); } - } - else if (!level->isClientSide) - { - // 4J added - don't do anything just now if we can't create any new falling tiles - if( !level->newFallingTileAllowed() ) - { - level->addToTickNextTick(x, y, z, id, getTickDelay()); - return; - } + } else if (!level->isClientSide) { + // 4J added - don't do anything just now if we can't create any new + // falling tiles + if (!level->newFallingTileAllowed()) { + level->addToTickNextTick(x, y, z, id, getTickDelay()); + return; + } - std::shared_ptr e = std::shared_ptr( new FallingTile(level, x + 0.5f, y + 0.5f, z + 0.5f, id, level->getData(x, y, z)) ); - falling(e); + std::shared_ptr e = std::shared_ptr( + new FallingTile(level, x + 0.5f, y + 0.5f, z + 0.5f, id, + level->getData(x, y, z))); + falling(e); level->addEntity(e); } } } -void HeavyTile::falling(std::shared_ptr entity) -{ -} +void HeavyTile::falling(std::shared_ptr entity) {} -int HeavyTile::getTickDelay() -{ - return 5; -} +int HeavyTile::getTickDelay() { return 5; } -bool HeavyTile::isFree(Level *level, int x, int y, int z) -{ +bool HeavyTile::isFree(Level* level, int x, int y, int z) { int t = level->getTile(x, y, z); if (t == 0) return true; if (t == Tile::fire_Id) return true; - Material *material = Tile::tiles[t]->material; + Material* material = Tile::tiles[t]->material; if (material == Material::water) return true; if (material == Material::lava) return true; return false; } -void HeavyTile::onLand(Level *level, int xt, int yt, int zt, int data) -{ -} \ No newline at end of file +void HeavyTile::onLand(Level* level, int xt, int yt, int zt, int data) {} \ No newline at end of file diff --git a/Minecraft.World/Blocks/HeavyTile.h b/Minecraft.World/Blocks/HeavyTile.h index 739d3ea09..a75421846 100644 --- a/Minecraft.World/Blocks/HeavyTile.h +++ b/Minecraft.World/Blocks/HeavyTile.h @@ -5,22 +5,24 @@ class Random; class Level; class FallingTile; -class HeavyTile : public Tile -{ +class HeavyTile : public Tile { public: - static bool instaFall; + static bool instaFall; HeavyTile(int type, bool isSolidRender = true); - HeavyTile(int type, Material *material, bool isSolidRender = true); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); + HeavyTile(int type, Material* material, bool isSolidRender = true); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + private: - void checkSlide(Level *level, int x, int y, int z); + void checkSlide(Level* level, int x, int y, int z); + protected: - virtual void falling(std::shared_ptr entity); + virtual void falling(std::shared_ptr entity); + public: - virtual int getTickDelay(); - static bool isFree(Level *level, int x, int y, int z); - virtual void onLand(Level *level, int xt, int yt, int zt, int data); + virtual int getTickDelay(); + static bool isFree(Level* level, int x, int y, int z); + virtual void onLand(Level* level, int xt, int yt, int zt, int data); }; diff --git a/Minecraft.World/Blocks/HellSandTile.cpp b/Minecraft.World/Blocks/HellSandTile.cpp index 1cdd7e3bc..87ee3e113 100644 --- a/Minecraft.World/Blocks/HellSandTile.cpp +++ b/Minecraft.World/Blocks/HellSandTile.cpp @@ -3,19 +3,15 @@ #include "../Headers/net.minecraft.world.phys.h" #include "HellSandTile.h" +HellSandTile::HellSandTile(int id) : Tile(id, Material::sand) {} -HellSandTile::HellSandTile(int id) : Tile(id, Material::sand) -{ -} - -AABB *HellSandTile::getAABB(Level *level, int x, int y, int z) -{ +AABB* HellSandTile::getAABB(Level* level, int x, int y, int z) { float r = 2 / 16.0f; return AABB::newTemp(x, y, z, x + 1, y + 1 - r, z + 1); } -void HellSandTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - entity->xd*=0.4; - entity->zd*=0.4; +void HellSandTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + entity->xd *= 0.4; + entity->zd *= 0.4; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/HellSandTile.h b/Minecraft.World/Blocks/HellSandTile.h index 865c34871..c65c7b2e7 100644 --- a/Minecraft.World/Blocks/HellSandTile.h +++ b/Minecraft.World/Blocks/HellSandTile.h @@ -2,10 +2,10 @@ #include "Tile.h" #include "../Util/Definitions.h" -class HellSandTile : public Tile -{ +class HellSandTile : public Tile { public: - HellSandTile(int id); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); + HellSandTile(int id); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/HellStoneTile.cpp b/Minecraft.World/Blocks/HellStoneTile.cpp index 005c2ca98..d02a3c920 100644 --- a/Minecraft.World/Blocks/HellStoneTile.cpp +++ b/Minecraft.World/Blocks/HellStoneTile.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "HellStoneTile.h" -HellStoneTile::HellStoneTile(int id) : Tile(id, Material::stone) -{ -} \ No newline at end of file +HellStoneTile::HellStoneTile(int id) : Tile(id, Material::stone) {} \ No newline at end of file diff --git a/Minecraft.World/Blocks/HellStoneTile.h b/Minecraft.World/Blocks/HellStoneTile.h index 6d0a0466a..7bc3874e0 100644 --- a/Minecraft.World/Blocks/HellStoneTile.h +++ b/Minecraft.World/Blocks/HellStoneTile.h @@ -1,8 +1,7 @@ #pragma once #include "Tile.h" -class HellStoneTile : public Tile -{ +class HellStoneTile : public Tile { public: - HellStoneTile(int id); + HellStoneTile(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/HugeMushroomTile.cpp b/Minecraft.World/Blocks/HugeMushroomTile.cpp index c7dfe8ab7..7bfbb4a26 100644 --- a/Minecraft.World/Blocks/HugeMushroomTile.cpp +++ b/Minecraft.World/Blocks/HugeMushroomTile.cpp @@ -4,18 +4,18 @@ const std::wstring HugeMushroomTile::TEXTURE_STEM = L"mushroom_skin_stem"; const std::wstring HugeMushroomTile::TEXTURE_INSIDE = L"mushroom_inside"; -const std::wstring HugeMushroomTile::TEXTURE_TYPE[] = {L"mushroom_skin_brown", L"mushroom_skin_red"}; +const std::wstring HugeMushroomTile::TEXTURE_TYPE[] = {L"mushroom_skin_brown", + L"mushroom_skin_red"}; -HugeMushroomTile::HugeMushroomTile(int id, Material *material, int type) : Tile(id, material) -{ +HugeMushroomTile::HugeMushroomTile(int id, Material* material, int type) + : Tile(id, material) { this->type = type; - icons = NULL; - iconStem = NULL; - iconInside = NULL; + icons = NULL; + iconStem = NULL; + iconInside = NULL; } -Icon *HugeMushroomTile::getTexture(int face, int data) -{ +Icon* HugeMushroomTile::getTexture(int face, int data) { // 123 // 456 10 // 789 @@ -28,44 +28,38 @@ Icon *HugeMushroomTile::getTexture(int face, int data) if ((data == 3 || data == 6 || data == 9) && face == 5) return icons[type]; // two special cases requested by rhodox (painterly pack) - if (data == 14) - { + if (data == 14) { return icons[type]; } - if (data == 15) - { + if (data == 15) { return iconStem; } return iconInside; } -int HugeMushroomTile::getResourceCount(Random *random) -{ +int HugeMushroomTile::getResourceCount(Random* random) { int count = random->nextInt(10) - 7; if (count < 0) count = 0; return count; } -int HugeMushroomTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::mushroom1_Id + type; +int HugeMushroomTile::getResource(int data, Random* random, + int playerBonusLevel) { + return Tile::mushroom1_Id + type; } -int HugeMushroomTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Tile::mushroom1_Id + type; +int HugeMushroomTile::cloneTileId(Level* level, int x, int y, int z) { + return Tile::mushroom1_Id + type; } -void HugeMushroomTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[HUGE_MUSHROOM_TEXTURE_COUNT]; +void HugeMushroomTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[HUGE_MUSHROOM_TEXTURE_COUNT]; - for (int i = 0; i < HUGE_MUSHROOM_TEXTURE_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_TYPE[i]); - } + for (int i = 0; i < HUGE_MUSHROOM_TEXTURE_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_TYPE[i]); + } - iconInside = iconRegister->registerIcon(TEXTURE_INSIDE); - iconStem = iconRegister->registerIcon(TEXTURE_STEM); + iconInside = iconRegister->registerIcon(TEXTURE_INSIDE); + iconStem = iconRegister->registerIcon(TEXTURE_STEM); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/HugeMushroomTile.h b/Minecraft.World/Blocks/HugeMushroomTile.h index 2dc4a0ddc..d5da64f59 100644 --- a/Minecraft.World/Blocks/HugeMushroomTile.h +++ b/Minecraft.World/Blocks/HugeMushroomTile.h @@ -2,25 +2,26 @@ #include "Tile.h" class ChunkRebuildData; -class HugeMushroomTile : public Tile -{ - friend class ChunkRebuildData; +class HugeMushroomTile : public Tile { + friend class ChunkRebuildData; + public: - static const std::wstring TEXTURE_STEM; - static const std::wstring TEXTURE_INSIDE; + static const std::wstring TEXTURE_STEM; + static const std::wstring TEXTURE_INSIDE; private: - static const int HUGE_MUSHROOM_TEXTURE_COUNT = 2; - static const std::wstring TEXTURE_TYPE[]; - int type; - Icon **icons; - Icon *iconStem; - Icon *iconInside; + static const int HUGE_MUSHROOM_TEXTURE_COUNT = 2; + static const std::wstring TEXTURE_TYPE[]; + int type; + Icon** icons; + Icon* iconStem; + Icon* iconInside; + public: - HugeMushroomTile(int id, Material *material, int type); - Icon *getTexture(int face, int data); - int getResourceCount(Random *random); - int getResource(int data, Random *random, int playerBonusLevel); - int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); + HugeMushroomTile(int id, Material* material, int type); + Icon* getTexture(int face, int data); + int getResourceCount(Random* random); + int getResource(int data, Random* random, int playerBonusLevel); + int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/IceTile.cpp b/Minecraft.World/Blocks/IceTile.cpp index 11a3cb5ef..f3f3f4092 100644 --- a/Minecraft.World/Blocks/IceTile.cpp +++ b/Minecraft.World/Blocks/IceTile.cpp @@ -6,78 +6,64 @@ #include "../Headers/net.minecraft.stats.h" #include "IceTile.h" -IceTile::IceTile(int id) : HalfTransparentTile(id, L"ice", Material::ice, false) -{ - friction = 0.98f; - setTicking(true); +IceTile::IceTile(int id) + : HalfTransparentTile(id, L"ice", Material::ice, false) { + friction = 0.98f; + setTicking(true); } -int IceTile::getRenderLayer() -{ - return 1; +int IceTile::getRenderLayer() { return 1; } + +bool IceTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + return HalfTransparentTile::shouldRenderFace(level, x, y, z, 1 - face); } -bool IceTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - return HalfTransparentTile::shouldRenderFace(level, x, y, z, 1 - face); +void IceTile::playerDestroy(Level* level, std::shared_ptr player, int x, + int y, int z, int data) { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); + player->causeFoodExhaustion(FoodConstants::EXHAUSTION_MINE); + + if (isSilkTouchable() && + EnchantmentHelper::hasSilkTouch(player->inventory)) { + std::shared_ptr item = getSilkTouchItemInstance(data); + if (item != NULL) { + popResource(level, x, y, z, item); + } + } else { + if (level->dimension->ultraWarm) { + level->setTile(x, y, z, 0); + return; + } + + int playerBonusLevel = + EnchantmentHelper::getDiggingLootBonus(player->inventory); + spawnResources(level, x, y, z, data, playerBonusLevel); + Material* below = level->getMaterial(x, y - 1, z); + if (below->blocksMotion() || below->isLiquid()) { + level->setTile(x, y, z, Tile::water_Id); + } + } } -void IceTile::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - player->awardStat(GenericStats::blocksMined(id), GenericStats::param_blocksMined(id,data,1) ); - player->causeFoodExhaustion(FoodConstants::EXHAUSTION_MINE); +int IceTile::getResourceCount(Random* random) { return 0; } - if (isSilkTouchable() && EnchantmentHelper::hasSilkTouch(player->inventory)) - { - std::shared_ptr item = getSilkTouchItemInstance(data); - if (item != NULL) - { - popResource(level, x, y, z, item); - } - } - else - { - if (level->dimension->ultraWarm) - { - level->setTile(x, y, z, 0); - return; - } - - int playerBonusLevel = EnchantmentHelper::getDiggingLootBonus(player->inventory); - spawnResources(level, x, y, z, data, playerBonusLevel); - Material *below = level->getMaterial(x, y - 1, z); - if (below->blocksMotion() || below->isLiquid()) - { - level->setTile(x, y, z, Tile::water_Id); - } - } +void IceTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->getBrightness(LightLayer::Block, x, y, z) > + 11 - Tile::lightBlock[id]) { + if (level->dimension->ultraWarm) { + level->setTile(x, y, z, 0); + return; + } + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, Tile::calmWater_Id); + } } -int IceTile::getResourceCount(Random *random) -{ - return 0; +bool IceTile::shouldTileTick(Level* level, int x, int y, int z) { + return level->getBrightness(LightLayer::Block, x, y, z) > + 11 - Tile::lightBlock[id]; } -void IceTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->getBrightness(LightLayer::Block, x, y, z) > 11 - Tile::lightBlock[id]) - { - if (level->dimension->ultraWarm) - { - level->setTile(x, y, z, 0); - return; - } - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, Tile::calmWater_Id); - } -} - -bool IceTile::shouldTileTick(Level *level, int x,int y,int z) -{ - return level->getBrightness(LightLayer::Block, x, y, z) > 11 - Tile::lightBlock[id]; -} - -int IceTile::getPistonPushReaction() -{ - return Material::PUSH_NORMAL; -} +int IceTile::getPistonPushReaction() { return Material::PUSH_NORMAL; } diff --git a/Minecraft.World/Blocks/IceTile.h b/Minecraft.World/Blocks/IceTile.h index 3fa9d6d6b..e54fbb474 100644 --- a/Minecraft.World/Blocks/IceTile.h +++ b/Minecraft.World/Blocks/IceTile.h @@ -3,17 +3,19 @@ class Random; -class IceTile : public HalfTransparentTile -{ +class IceTile : public HalfTransparentTile { public: - IceTile(int id); - virtual int getRenderLayer(); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); - virtual int getResourceCount(Random *random); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual int getPistonPushReaction(); + IceTile(int id); + virtual int getRenderLayer(); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); + virtual int getResourceCount(Random* random); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual int getPistonPushReaction(); - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/LadderTile.cpp b/Minecraft.World/Blocks/LadderTile.cpp index 6651e49a5..718b38861 100644 --- a/Minecraft.World/Blocks/LadderTile.cpp +++ b/Minecraft.World/Blocks/LadderTile.cpp @@ -2,94 +2,75 @@ #include "../Headers/net.minecraft.world.level.h" #include "LadderTile.h" +LadderTile::LadderTile(int id) : Tile(id, Material::decoration, false) {} -LadderTile::LadderTile(int id) : Tile(id, Material::decoration, false) -{ +AABB* LadderTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return Tile::getAABB(level, x, y, z); } -AABB *LadderTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return Tile::getAABB(level, x, y, z); -} - -AABB *LadderTile::getTileAABB(Level *level, int x, int y, int z) -{ +AABB* LadderTile::getTileAABB(Level* level, int x, int y, int z) { updateShape(level, x, y, z); return Tile::getTileAABB(level, x, y, z); } -void LadderTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void LadderTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - setShape(level->getData(x, y, z)); + setShape(level->getData(x, y, z)); } -void LadderTile::setShape(int data) -{ - int dir = data; - float r = 2 / 16.0f; +void LadderTile::setShape(int data) { + int dir = data; + float r = 2 / 16.0f; - if (dir == 2) setShape(0, 0, 1 - r, 1, 1, 1); - if (dir == 3) setShape(0, 0, 0, 1, 1, r); - if (dir == 4) setShape(1 - r, 0, 0, 1, 1, 1); - if (dir == 5) setShape(0, 0, 0, r, 1, 1); + if (dir == 2) setShape(0, 0, 1 - r, 1, 1, 1); + if (dir == 3) setShape(0, 0, 0, 1, 1, r); + if (dir == 4) setShape(1 - r, 0, 0, 1, 1, 1); + if (dir == 5) setShape(0, 0, 0, r, 1, 1); } -bool LadderTile::blocksLight() -{ - return false; -} +bool LadderTile::blocksLight() { return false; } -bool LadderTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool LadderTile::isSolidRender(bool isServerLevel) { return false; } -bool LadderTile::isCubeShaped() -{ - return false; -} +bool LadderTile::isCubeShaped() { return false; } -int LadderTile::getRenderShape() -{ - return Tile::SHAPE_LADDER; -} +int LadderTile::getRenderShape() { return Tile::SHAPE_LADDER; } -bool LadderTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTile(x - 1, y, z)) - { +bool LadderTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTile(x - 1, y, z)) { return true; - } - else if (level->isSolidBlockingTile(x + 1, y, z)) - { + } else if (level->isSolidBlockingTile(x + 1, y, z)) { return true; - } - else if (level->isSolidBlockingTile(x, y, z - 1)) - { + } else if (level->isSolidBlockingTile(x, y, z - 1)) { return true; - } - else if (level->isSolidBlockingTile(x, y, z + 1)) - { + } else if (level->isSolidBlockingTile(x, y, z + 1)) { return true; } return false; } -int LadderTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ +int LadderTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { int dir = level->getData(x, y, z); - if ((dir == 0 || face == 2) && level->isSolidBlockingTile(x, y, z + 1)) dir = 2; - if ((dir == 0 || face == 3) && level->isSolidBlockingTile(x, y, z - 1)) dir = 3; - if ((dir == 0 || face == 4) && level->isSolidBlockingTile(x + 1, y, z)) dir = 4; - if ((dir == 0 || face == 5) && level->isSolidBlockingTile(x - 1, y, z)) dir = 5; + if ((dir == 0 || face == 2) && level->isSolidBlockingTile(x, y, z + 1)) + dir = 2; + if ((dir == 0 || face == 3) && level->isSolidBlockingTile(x, y, z - 1)) + dir = 3; + if ((dir == 0 || face == 4) && level->isSolidBlockingTile(x + 1, y, z)) + dir = 4; + if ((dir == 0 || face == 5) && level->isSolidBlockingTile(x - 1, y, z)) + dir = 5; return dir; } -void LadderTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void LadderTile::neighborChanged(Level* level, int x, int y, int z, int type) { int face = level->getData(x, y, z); bool ok = false; @@ -97,8 +78,7 @@ void LadderTile::neighborChanged(Level *level, int x, int y, int z, int type) if (face == 3 && level->isSolidBlockingTile(x, y, z - 1)) ok = true; if (face == 4 && level->isSolidBlockingTile(x + 1, y, z)) ok = true; if (face == 5 && level->isSolidBlockingTile(x - 1, y, z)) ok = true; - if (!ok) - { + if (!ok) { spawnResources(level, x, y, z, face, 0); level->setTile(x, y, z, 0); } @@ -106,7 +86,4 @@ void LadderTile::neighborChanged(Level *level, int x, int y, int z, int type) Tile::neighborChanged(level, x, y, z, type); } -int LadderTile::getResourceCount(Random* random) -{ - return 1; -} +int LadderTile::getResourceCount(Random* random) { return 1; } diff --git a/Minecraft.World/Blocks/LadderTile.h b/Minecraft.World/Blocks/LadderTile.h index e75b9650c..d91eeda1f 100644 --- a/Minecraft.World/Blocks/LadderTile.h +++ b/Minecraft.World/Blocks/LadderTile.h @@ -4,23 +4,29 @@ class Random; -class LadderTile : public Tile -{ - friend class Tile; +class LadderTile : public Tile { + friend class Tile; + protected: - LadderTile(int id); + LadderTile(int id); + public: - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - using Tile::setShape; - virtual void setShape(int data); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + using Tile::setShape; + virtual void setShape(int data); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); virtual int getResourceCount(Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LeafTile.cpp b/Minecraft.World/Blocks/LeafTile.cpp index fb235da5e..437269be3 100644 --- a/Minecraft.World/Blocks/LeafTile.cpp +++ b/Minecraft.World/Blocks/LeafTile.cpp @@ -7,335 +7,315 @@ #include "../Headers/net.minecraft.stats.h" #include "../Headers/net.minecraft.world.h" -const unsigned int LeafTile::LEAF_NAMES[LEAF_NAMES_LENGTH] = { IDS_TILE_LEAVES_OAK, - IDS_TILE_LEAVES_SPRUCE, - IDS_TILE_LEAVES_BIRCH, - IDS_TILE_LEAVES_JUNGLE, - }; +const unsigned int LeafTile::LEAF_NAMES[LEAF_NAMES_LENGTH] = { + IDS_TILE_LEAVES_OAK, + IDS_TILE_LEAVES_SPRUCE, + IDS_TILE_LEAVES_BIRCH, + IDS_TILE_LEAVES_JUNGLE, +}; -const std::wstring LeafTile::TEXTURES[2][4] = { {L"leaves", L"leaves_spruce", L"leaves", L"leaves_jungle"}, {L"leaves_opaque", L"leaves_spruce_opaque", L"leaves_opaque", L"leaves_jungle_opaque"},}; +const std::wstring LeafTile::TEXTURES[2][4] = { + {L"leaves", L"leaves_spruce", L"leaves", L"leaves_jungle"}, + {L"leaves_opaque", L"leaves_spruce_opaque", L"leaves_opaque", + L"leaves_jungle_opaque"}, +}; // 4jcraft, this is the unitinialized vpointer fiassco of isSolidRender() // isSolidRender() returns !allowSame if !isServerLevel, else true // scince allowSame for TransparentTile right here is set to false // setting isSolidRender to true by default totally correct. -LeafTile::LeafTile(int id) : TransparentTile(id, Material::leaves, false, true) -{ - checkBuffer = NULL; +LeafTile::LeafTile(int id) + : TransparentTile(id, Material::leaves, false, true) { + checkBuffer = NULL; fancyTextureSet = 0; setTicking(true); } -LeafTile::~LeafTile() -{ - delete [] checkBuffer; +LeafTile::~LeafTile() { delete[] checkBuffer; } + +int LeafTile::getColor() const { + // 4J Stu - Not using this any more + // double temp = 0.5; + // double rain = 1.0; + + // return FoliageColor::get(temp, rain); + + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Foliage_Common); } -int LeafTile::getColor() const -{ - // 4J Stu - Not using this any more - //double temp = 0.5; - //double rain = 1.0; - - //return FoliageColor::get(temp, rain); - - return Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Foliage_Common ); -} - -int LeafTile::getColor(int data) -{ - if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) - { +int LeafTile::getColor(int data) { + if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) { return FoliageColor::getEvergreenColor(); } - if ((data & LEAF_TYPE_MASK) == BIRCH_LEAF) - { + if ((data & LEAF_TYPE_MASK) == BIRCH_LEAF) { return FoliageColor::getBirchColor(); } return FoliageColor::getDefaultColor(); } -int LeafTile::getColor(LevelSource *level, int x, int y, int z) -{ - return getColor(level, x, y, z, level->getData(x, y, z) ); +int LeafTile::getColor(LevelSource* level, int x, int y, int z) { + return getColor(level, x, y, z, level->getData(x, y, z)); } -// 4J - changed interface to have data passed in, and put existing interface as wrapper above -int LeafTile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) - { +// 4J - changed interface to have data passed in, and put existing interface as +// wrapper above +int LeafTile::getColor(LevelSource* level, int x, int y, int z, int data) { + if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) { return FoliageColor::getEvergreenColor(); } - if ((data & LEAF_TYPE_MASK) == BIRCH_LEAF) - { + if ((data & LEAF_TYPE_MASK) == BIRCH_LEAF) { return FoliageColor::getBirchColor(); } - int totalRed = 0; - int totalGreen = 0; - int totalBlue = 0; + int totalRed = 0; + int totalGreen = 0; + int totalBlue = 0; - for (int oz = -1; oz <= 1; oz++) - { - for (int ox = -1; ox <= 1; ox++) - { - int foliageColor = level->getBiome(x + ox, z + oz)->getFolageColor(); + for (int oz = -1; oz <= 1; oz++) { + for (int ox = -1; ox <= 1; ox++) { + int foliageColor = + level->getBiome(x + ox, z + oz)->getFolageColor(); - totalRed += (foliageColor & 0xff0000) >> 16; - totalGreen += (foliageColor & 0xff00) >> 8; - totalBlue += (foliageColor & 0xff); - } - } + totalRed += (foliageColor & 0xff0000) >> 16; + totalGreen += (foliageColor & 0xff00) >> 8; + totalBlue += (foliageColor & 0xff); + } + } - return (((totalRed / 9) & 0xFF) << 16) | (((totalGreen / 9) & 0xFF) << 8) | (((totalBlue / 9) & 0xFF)); + return (((totalRed / 9) & 0xFF) << 16) | (((totalGreen / 9) & 0xFF) << 8) | + (((totalBlue / 9) & 0xFF)); } -void LeafTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void LeafTile::onRemove(Level* level, int x, int y, int z, int id, int data) { int r = 1; int r2 = r + 1; - if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, z + r2)) - { + if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, z + r2)) { for (int xo = -r; xo <= r; xo++) for (int yo = -r; yo <= r; yo++) - for (int zo = -r; zo <= r; zo++) - { + for (int zo = -r; zo <= r; zo++) { int t = level->getTile(x + xo, y + yo, z + zo); - if (t == Tile::leaves_Id) - { - int currentData = level->getData(x + xo, y + yo, z + zo); - level->setDataNoUpdate(x + xo, y + yo, z + zo, currentData | UPDATE_LEAF_BIT); + if (t == Tile::leaves_Id) { + int currentData = + level->getData(x + xo, y + yo, z + zo); + level->setDataNoUpdate(x + xo, y + yo, z + zo, + currentData | UPDATE_LEAF_BIT); } } } - } -void LeafTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void LeafTile::tick(Level* level, int x, int y, int z, Random* random) { if (level->isClientSide) return; int currentData = level->getData(x, y, z); - if ((currentData & UPDATE_LEAF_BIT) != 0 && (currentData & PERSISTENT_LEAF_BIT) == 0) - { + if ((currentData & UPDATE_LEAF_BIT) != 0 && + (currentData & PERSISTENT_LEAF_BIT) == 0) { int r = LeafTile::REQUIRED_WOOD_RANGE; int r2 = r + 1; int W = 32; int WW = W * W; int WO = W / 2; - if (checkBuffer == NULL) - { + if (checkBuffer == NULL) { checkBuffer = new int[W * W * W]; } - if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, z + r2)) - { - // 4J Stu - Assuming we remain in the same chunk, getTile accesses an array that varies least by y - // Changing the ordering here to loop by y last + if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, + z + r2)) { + // 4J Stu - Assuming we remain in the same chunk, getTile accesses + // an array that varies least by y Changing the ordering here to + // loop by y last for (int xo = -r; xo <= r; xo++) - for (int zo = -r; zo <= r; zo++) - for (int yo = -r; yo <= r; yo++) - { + for (int zo = -r; zo <= r; zo++) + for (int yo = -r; yo <= r; yo++) { int t = level->getTile(x + xo, y + yo, z + zo); - if (t == Tile::treeTrunk_Id) - { - checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO)] = 0; - } - else if (t == Tile::leaves_Id) - { - checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO)] = -2; - } - else - { - checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO)] = -1; + if (t == Tile::treeTrunk_Id) { + checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO)] = 0; + } else if (t == Tile::leaves_Id) { + checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO)] = -2; + } else { + checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO)] = -1; } } - for (int i = 1; i <= LeafTile::REQUIRED_WOOD_RANGE; i++) - { + for (int i = 1; i <= LeafTile::REQUIRED_WOOD_RANGE; i++) { for (int xo = -r; xo <= r; xo++) for (int yo = -r; yo <= r; yo++) - for (int zo = -r; zo <= r; zo++) - { - if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO)] == i - 1) - { - if (checkBuffer[(xo + WO - 1) * WW + (yo + WO) * W + (zo + WO)] == -2) - { - checkBuffer[(xo + WO - 1) * WW + (yo + WO) * W + (zo + WO)] = i; + for (int zo = -r; zo <= r; zo++) { + if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO)] == i - 1) { + if (checkBuffer[(xo + WO - 1) * WW + + (yo + WO) * W + (zo + WO)] == + -2) { + checkBuffer[(xo + WO - 1) * WW + + (yo + WO) * W + (zo + WO)] = i; } - if (checkBuffer[(xo + WO + 1) * WW + (yo + WO) * W + (zo + WO)] == -2) - { - checkBuffer[(xo + WO + 1) * WW + (yo + WO) * W + (zo + WO)] = i; + if (checkBuffer[(xo + WO + 1) * WW + + (yo + WO) * W + (zo + WO)] == + -2) { + checkBuffer[(xo + WO + 1) * WW + + (yo + WO) * W + (zo + WO)] = i; } - if (checkBuffer[(xo + WO) * WW + (yo + WO - 1) * W + (zo + WO)] == -2) - { - checkBuffer[(xo + WO) * WW + (yo + WO - 1) * W + (zo + WO)] = i; + if (checkBuffer[(xo + WO) * WW + + (yo + WO - 1) * W + + (zo + WO)] == -2) { + checkBuffer[(xo + WO) * WW + + (yo + WO - 1) * W + (zo + WO)] = + i; } - if (checkBuffer[(xo + WO) * WW + (yo + WO + 1) * W + (zo + WO)] == -2) - { - checkBuffer[(xo + WO) * WW + (yo + WO + 1) * W + (zo + WO)] = i; + if (checkBuffer[(xo + WO) * WW + + (yo + WO + 1) * W + + (zo + WO)] == -2) { + checkBuffer[(xo + WO) * WW + + (yo + WO + 1) * W + (zo + WO)] = + i; } - if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO - 1)] == -2) - { - checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO - 1)] = i; + if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO - 1)] == -2) { + checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO - 1)] = i; } - if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO + 1)] == -2) - { - checkBuffer[(xo + WO) * WW + (yo + WO) * W + (zo + WO + 1)] = i; + if (checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO + 1)] == -2) { + checkBuffer[(xo + WO) * WW + (yo + WO) * W + + (zo + WO + 1)] = i; } } } } } - int mid = checkBuffer[(WO) * WW + (WO) * W + (WO)]; - if (mid >= 0) - { + int mid = checkBuffer[(WO)*WW + (WO)*W + (WO)]; + if (mid >= 0) { level->setDataNoUpdate(x, y, z, currentData & ~UPDATE_LEAF_BIT); - } - else - { + } else { die(level, x, y, z); } } - } -void LeafTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isRainingAt(x, y + 1, z) && !level->isTopSolidBlocking(x, y - 1, z) && random->nextInt(15) == 1) - { - double xx = x + random->nextFloat(); - double yy = y - 0.05; - double zz = z + random->nextFloat(); +void LeafTile::animateTick(Level* level, int x, int y, int z, Random* random) { + if (level->isRainingAt(x, y + 1, z) && + !level->isTopSolidBlocking(x, y - 1, z) && random->nextInt(15) == 1) { + double xx = x + random->nextFloat(); + double yy = y - 0.05; + double zz = z + random->nextFloat(); - level->addParticle(eParticleType_dripWater, xx, yy, zz, 0, 0, 0); - } + level->addParticle(eParticleType_dripWater, xx, yy, zz, 0, 0, 0); + } } -void LeafTile::die(Level *level, int x, int y, int z) -{ +void LeafTile::die(Level* level, int x, int y, int z) { Tile::spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } -int LeafTile::getResourceCount(Random *random) -{ - return random->nextInt(20) == 0 ? 1 : 0; +int LeafTile::getResourceCount(Random* random) { + return random->nextInt(20) == 0 ? 1 : 0; } -int LeafTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::sapling_Id; +int LeafTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::sapling_Id; } // 4J DCR: Brought forward from 1.2 -void LeafTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - if (!level->isClientSide) - { - int chance = 20; - if ((data & LEAF_TYPE_MASK) == JUNGLE_LEAF) - { - chance = 40; - } - if (level->random->nextInt(chance) == 0) - { - int type = getResource(data, level->random,playerBonusLevel); - popResource(level, x, y, z, std::shared_ptr( new ItemInstance(type, 1, getSpawnResourcesAuxValue(data)))); - } +void LeafTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + if (!level->isClientSide) { + int chance = 20; + if ((data & LEAF_TYPE_MASK) == JUNGLE_LEAF) { + chance = 40; + } + if (level->random->nextInt(chance) == 0) { + int type = getResource(data, level->random, playerBonusLevel); + popResource(level, x, y, z, + std::shared_ptr(new ItemInstance( + type, 1, getSpawnResourcesAuxValue(data)))); + } - if ((data & LEAF_TYPE_MASK) == NORMAL_LEAF && level->random->nextInt(200) == 0) - { - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Item::apple_Id, 1, 0))); - } - } + if ((data & LEAF_TYPE_MASK) == NORMAL_LEAF && + level->random->nextInt(200) == 0) { + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(Item::apple_Id, 1, 0))); + } + } } -void LeafTile::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - if (!level->isClientSide && player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::shears->id) - { - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); +void LeafTile::playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data) { + if (!level->isClientSide && player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::shears->id) { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); // drop leaf block instead of sapling - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Tile::leaves_Id, 1, data & LEAF_TYPE_MASK))); - } - else - { + popResource(level, x, y, z, + std::shared_ptr(new ItemInstance( + Tile::leaves_Id, 1, data & LEAF_TYPE_MASK))); + } else { TransparentTile::playerDestroy(level, player, x, y, z, data); } } -int LeafTile::getSpawnResourcesAuxValue(int data) -{ - return data & LEAF_TYPE_MASK; +int LeafTile::getSpawnResourcesAuxValue(int data) { + return data & LEAF_TYPE_MASK; } -bool LeafTile::isSolidRender(bool isServerLevel) -{ - // 4J Stu - The server level shouldn't care how the tile is rendered! - // Fix for #9407 - Gameplay: Destroying a block of snow on top of trees, removes any adjacent snow. - if(isServerLevel) return true; - return !allowSame; +bool LeafTile::isSolidRender(bool isServerLevel) { + // 4J Stu - The server level shouldn't care how the tile is rendered! + // Fix for #9407 - Gameplay: Destroying a block of snow on top of trees, + // removes any adjacent snow. + if (isServerLevel) return true; + return !allowSame; } -Icon *LeafTile::getTexture(int face, int data) -{ - if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) - { +Icon* LeafTile::getTexture(int face, int data) { + if ((data & LEAF_TYPE_MASK) == EVERGREEN_LEAF) { return icons[fancyTextureSet][EVERGREEN_LEAF]; } - if ((data & LEAF_TYPE_MASK) == JUNGLE_LEAF) - { + if ((data & LEAF_TYPE_MASK) == JUNGLE_LEAF) { return icons[fancyTextureSet][JUNGLE_LEAF]; } return icons[fancyTextureSet][0]; } -void LeafTile::setFancy(bool fancyGraphics) -{ +void LeafTile::setFancy(bool fancyGraphics) { allowSame = fancyGraphics; fancyTextureSet = (fancyGraphics ? 0 : 1); } -std::shared_ptr LeafTile::getSilkTouchItemInstance(int data) -{ - return std::shared_ptr( new ItemInstance(id, 1, data & LEAF_TYPE_MASK) ); +std::shared_ptr LeafTile::getSilkTouchItemInstance(int data) { + return std::shared_ptr( + new ItemInstance(id, 1, data & LEAF_TYPE_MASK)); } -void LeafTile::stepOn(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - TransparentTile::stepOn(level, x, y, z, entity); +void LeafTile::stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity) { + TransparentTile::stepOn(level, x, y, z, entity); } -bool LeafTile::shouldTileTick(Level *level, int x,int y,int z) -{ - int currentData = level->getData(x, y, z); +bool LeafTile::shouldTileTick(Level* level, int x, int y, int z) { + int currentData = level->getData(x, y, z); return (currentData & UPDATE_LEAF_BIT) != 0; } -unsigned int LeafTile::getDescriptionId(int iData /*= -1*/) -{ - int leafIndex = iData & LEAF_TYPE_MASK; - return LeafTile::LEAF_NAMES[leafIndex]; +unsigned int LeafTile::getDescriptionId(int iData /*= -1*/) { + int leafIndex = iData & LEAF_TYPE_MASK; + return LeafTile::LEAF_NAMES[leafIndex]; } -void LeafTile::registerIcons(IconRegister *iconRegister) -{ - for (int fancy = 0; fancy < 2; fancy++) - { - //icons[fancy] = new Icon[TEXTURES[fancy].length]; +void LeafTile::registerIcons(IconRegister* iconRegister) { + for (int fancy = 0; fancy < 2; fancy++) { + // icons[fancy] = new Icon[TEXTURES[fancy].length]; - for (int i = 0; i < 4; i++) - { - icons[fancy][i] = iconRegister->registerIcon(TEXTURES[fancy][i]); - } - } + for (int i = 0; i < 4; i++) { + icons[fancy][i] = iconRegister->registerIcon(TEXTURES[fancy][i]); + } + } } diff --git a/Minecraft.World/Blocks/LeafTile.h b/Minecraft.World/Blocks/LeafTile.h index 20b5d73c7..8ce8accbd 100644 --- a/Minecraft.World/Blocks/LeafTile.h +++ b/Minecraft.World/Blocks/LeafTile.h @@ -4,73 +4,84 @@ class Random; class ChunkRebuildData; -class LeafTile : public TransparentTile -{ - friend class Tile; - friend class ChunkRebuildData; +class LeafTile : public TransparentTile { + friend class Tile; + friend class ChunkRebuildData; + public: - static const std::wstring TEXTURES[2][4]; - static const int REQUIRED_WOOD_RANGE = 4; + static const std::wstring TEXTURES[2][4]; + static const int REQUIRED_WOOD_RANGE = 4; static const int UPDATE_LEAF_BIT = 8; - static const int PERSISTENT_LEAF_BIT = 4; // player-placed + static const int PERSISTENT_LEAF_BIT = 4; // player-placed static const int NORMAL_LEAF = 0; static const int EVERGREEN_LEAF = 1; static const int BIRCH_LEAF = 2; - static const int JUNGLE_LEAF = 3; + static const int JUNGLE_LEAF = 3; - static const int LEAF_NAMES_LENGTH = 4; + static const int LEAF_NAMES_LENGTH = 4; + + static const unsigned int LEAF_NAMES[LEAF_NAMES_LENGTH]; - static const unsigned int LEAF_NAMES[LEAF_NAMES_LENGTH]; private: - static const int LEAF_TYPE_MASK = 3; + static const int LEAF_TYPE_MASK = 3; // pppppppppp ppppppppppp pppppppppp ppppppp // ssssssssss sssssssssss s int fancyTextureSet; - Icon *icons[2][4]; + Icon* icons[2][4]; protected: - LeafTile(int id); - virtual ~LeafTile(); + LeafTile(int id); + virtual ~LeafTile(); + public: - virtual int getColor() const; - virtual int getColor(int data); + virtual int getColor() const; + virtual int getColor(int data); - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - int *checkBuffer; + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + int* checkBuffer; + + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); private: - void die(Level *level, int x, int y, int z); + void die(Level* level, int x, int y, int z); + public: - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); - // 4J DCR: Brought forward from 1.2 - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); + // 4J DCR: Brought forward from 1.2 + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); + + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); protected: - virtual int getSpawnResourcesAuxValue(int data); + virtual int getSpawnResourcesAuxValue(int data); + public: - virtual bool isSolidRender(bool isServerLevel = false); - virtual Icon *getTexture(int face, int data); + virtual bool isSolidRender(bool isServerLevel = false); + virtual Icon* getTexture(int face, int data); void setFancy(bool fancyGraphics); protected: - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual std::shared_ptr getSilkTouchItemInstance(int data); public: - virtual void stepOn(Level *level, int x, int y, int z, std::shared_ptr entity); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual void stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity); - virtual unsigned int getDescriptionId(int iData = -1); - void registerIcons(IconRegister *iconRegister); + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); + + virtual unsigned int getDescriptionId(int iData = -1); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LeverTile.cpp b/Minecraft.World/Blocks/LeverTile.cpp index 57ac6936b..2523c36c7 100644 --- a/Minecraft.World/Blocks/LeverTile.cpp +++ b/Minecraft.World/Blocks/LeverTile.cpp @@ -4,38 +4,20 @@ #include "LeverTile.h" #include "../Util/SoundTypes.h" -LeverTile::LeverTile(int id) : Tile(id, Material::decoration, false) -{ -} +LeverTile::LeverTile(int id) : Tile(id, Material::decoration, false) {} -AABB *LeverTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} +AABB* LeverTile::getAABB(Level* level, int x, int y, int z) { return NULL; } -bool LeverTile::blocksLight() -{ - return false; -} +bool LeverTile::blocksLight() { return false; } -bool LeverTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool LeverTile::isSolidRender(bool isServerLevel) { return false; } -bool LeverTile::isCubeShaped() -{ - return false; -} +bool LeverTile::isCubeShaped() { return false; } -int LeverTile::getRenderShape() -{ - return Tile::SHAPE_LEVER; -} +int LeverTile::getRenderShape() { return Tile::SHAPE_LEVER; } -bool LeverTile::mayPlace(Level *level, int x, int y, int z, int face) -{ - if (face == 0 && level->isSolidBlockingTile(x, y + 1, z)) return true; +bool LeverTile::mayPlace(Level* level, int x, int y, int z, int face) { + if (face == 0 && level->isSolidBlockingTile(x, y + 1, z)) return true; if (face == 1 && level->isTopSolidBlocking(x, y - 1, z)) return true; if (face == 2 && level->isSolidBlockingTile(x, y, z + 1)) return true; if (face == 3 && level->isSolidBlockingTile(x, y, z - 1)) return true; @@ -44,99 +26,95 @@ bool LeverTile::mayPlace(Level *level, int x, int y, int z, int face) return false; } -bool LeverTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTile(x - 1, y, z)) - { +bool LeverTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTile(x - 1, y, z)) { return true; - } else if (level->isSolidBlockingTile(x + 1, y, z)) - { + } else if (level->isSolidBlockingTile(x + 1, y, z)) { return true; - } else if (level->isSolidBlockingTile(x, y, z - 1)) - { + } else if (level->isSolidBlockingTile(x, y, z - 1)) { return true; - } else if (level->isSolidBlockingTile(x, y, z + 1)) - { + } else if (level->isSolidBlockingTile(x, y, z + 1)) { return true; - } else if (level->isTopSolidBlocking(x, y - 1, z)) - { + } else if (level->isTopSolidBlocking(x, y - 1, z)) { + return true; + } else if (level->isSolidBlockingTile(x, y + 1, z)) { return true; } - else if (level->isSolidBlockingTile(x, y + 1, z)) - { - return true; - } return false; } -int LeverTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - int dir = itemValue; +int LeverTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + int dir = itemValue; - int oldFlip = dir & 8; - dir &= 7; + int oldFlip = dir & 8; + dir &= 7; - dir = -1; + dir = -1; - if (face == Facing::DOWN && level->isSolidBlockingTile(x, y + 1, z)) dir = 0; - if (face == Facing::UP && level->isTopSolidBlocking(x, y - 1, z)) dir = 5; - if (face == Facing::NORTH && level->isSolidBlockingTile(x, y, z + 1)) dir = 4; - if (face == Facing::SOUTH && level->isSolidBlockingTile(x, y, z - 1)) dir = 3; - if (face == Facing::WEST && level->isSolidBlockingTile(x + 1, y, z)) dir = 2; - if (face == Facing::EAST && level->isSolidBlockingTile(x - 1, y, z)) dir = 1; + if (face == Facing::DOWN && level->isSolidBlockingTile(x, y + 1, z)) + dir = 0; + if (face == Facing::UP && level->isTopSolidBlocking(x, y - 1, z)) dir = 5; + if (face == Facing::NORTH && level->isSolidBlockingTile(x, y, z + 1)) + dir = 4; + if (face == Facing::SOUTH && level->isSolidBlockingTile(x, y, z - 1)) + dir = 3; + if (face == Facing::WEST && level->isSolidBlockingTile(x + 1, y, z)) + dir = 2; + if (face == Facing::EAST && level->isSolidBlockingTile(x - 1, y, z)) + dir = 1; - return dir + oldFlip; + return dir + oldFlip; } -int LeverTile::getLeverFacing(int facing) -{ - switch (facing) - { - case Facing::DOWN: - return 0; - case Facing::UP: - return 5; - case Facing::NORTH: - return 4; - case Facing::SOUTH: - return 3; - case Facing::WEST: - return 2; - case Facing::EAST: - return 1; - } - return -1; +int LeverTile::getLeverFacing(int facing) { + switch (facing) { + case Facing::DOWN: + return 0; + case Facing::UP: + return 5; + case Facing::NORTH: + return 4; + case Facing::SOUTH: + return 3; + case Facing::WEST: + return 2; + case Facing::EAST: + return 1; + } + return -1; } -void LeverTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (checkCanSurvive(level, x, y, z)) - { +void LeverTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (checkCanSurvive(level, x, y, z)) { int dir = level->getData(x, y, z) & 7; bool replace = false; - if (!level->isSolidBlockingTile(x - 1, y, z) && dir == 1) replace = true; - if (!level->isSolidBlockingTile(x + 1, y, z) && dir == 2) replace = true; - if (!level->isSolidBlockingTile(x, y, z - 1) && dir == 3) replace = true; - if (!level->isSolidBlockingTile(x, y, z + 1) && dir == 4) replace = true; - if (!level->isTopSolidBlocking(x, y - 1, z) && dir == 5) replace = true; - if (!level->isTopSolidBlocking(x, y - 1, z) && dir == 6) replace = true; - if (!level->isSolidBlockingTile(x, y + 1, z) && dir == 0) replace = true; - if (!level->isSolidBlockingTile(x, y + 1, z) && dir == 7) replace = true; + if (!level->isSolidBlockingTile(x - 1, y, z) && dir == 1) + replace = true; + if (!level->isSolidBlockingTile(x + 1, y, z) && dir == 2) + replace = true; + if (!level->isSolidBlockingTile(x, y, z - 1) && dir == 3) + replace = true; + if (!level->isSolidBlockingTile(x, y, z + 1) && dir == 4) + replace = true; + if (!level->isTopSolidBlocking(x, y - 1, z) && dir == 5) replace = true; + if (!level->isTopSolidBlocking(x, y - 1, z) && dir == 6) replace = true; + if (!level->isSolidBlockingTile(x, y + 1, z) && dir == 0) + replace = true; + if (!level->isSolidBlockingTile(x, y + 1, z) && dir == 7) + replace = true; - if (replace) - { + if (replace) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } } - } -bool LeverTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!mayPlace(level, x, y, z)) - { +bool LeverTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!mayPlace(level, x, y, z)) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); return false; @@ -144,70 +122,62 @@ bool LeverTile::checkCanSurvive(Level *level, int x, int y, int z) return true; } -void LeverTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void LeverTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { int dir = level->getData(x, y, z) & 7; float r = 3 / 16.0f; - if (dir == 1) - { + if (dir == 1) { setShape(0, 0.2f, 0.5f - r, r * 2, 0.8f, 0.5f + r); - } - else if (dir == 2) - { + } else if (dir == 2) { setShape(1 - r * 2, 0.2f, 0.5f - r, 1, 0.8f, 0.5f + r); - } - else if (dir == 3) - { + } else if (dir == 3) { setShape(0.5f - r, 0.2f, 0, 0.5f + r, 0.8f, r * 2); - } - else if (dir == 4) - { + } else if (dir == 4) { setShape(0.5f - r, 0.2f, 1 - r * 2, 0.5f + r, 0.8f, 1); - } - else if (dir == 5 || dir == 6) - { + } else if (dir == 5 || dir == 6) { r = 4 / 16.0f; setShape(0.5f - r, 0.0f, 0.5f - r, 0.5f + r, 0.6f, 0.5f + r); + } else if (dir == 0 || dir == 7) { + r = 4 / 16.0f; + setShape(0.5f - r, 0.4f, 0.5f - r, 0.5f + r, 1.0f, 0.5f + r); } - else if (dir == 0 || dir == 7) - { - r = 4 / 16.0f; - setShape(0.5f - r, 0.4f, 0.5f - r, 0.5f + r, 1.0f, 0.5f + r); - } } -void LeverTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - use(level, x, y, z, player, 0, 0, 0, 0); +void LeverTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + use(level, x, y, z, player, 0, 0, 0, 0); } // 4J-PB - Adding a TestUse for tooltip display -bool LeverTile::TestUse() -{ - return true; -} +bool LeverTile::TestUse() { return true; } -bool LeverTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool LeverTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly ) - { - // 4J - added - just do enough to play the sound - int data = level->getData(x, y, z); - int dir = data & 7; - int open = 8 - (data & 8); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, open > 0 ? 0.6f : 0.5f); - return false; - } - if (level->isClientSide) - { - // 4J - added stuff to play sound in this case too - int data = level->getData(x, y, z); - int dir = data & 7; - int open = 8 - (data & 8); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, open > 0 ? 0.6f : 0.5f); + if (soundOnly) { + // 4J - added - just do enough to play the sound + int data = level->getData(x, y, z); + int dir = data & 7; + int open = 8 - (data & 8); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, open > 0 ? 0.6f : 0.5f); + return false; + } + if (level->isClientSide) { + // 4J - added stuff to play sound in this case too + int data = level->getData(x, y, z); + int dir = data & 7; + int open = 8 - (data & 8); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, open > 0 ? 0.6f : 0.5f); - return true; - } + return true; + } int data = level->getData(x, y, z); int dir = data & 7; int open = 8 - (data & 8); @@ -215,84 +185,59 @@ bool LeverTile::use(Level *level, int x, int y, int z, std::shared_ptr p level->setData(x, y, z, dir + open); level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, open > 0 ? 0.6f : 0.5f); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, + open > 0 ? 0.6f : 0.5f); level->updateNeighborsAt(x, y, z, id); - if (dir == 1) - { + if (dir == 1) { level->updateNeighborsAt(x - 1, y, z, id); - } - else if (dir == 2) - { + } else if (dir == 2) { level->updateNeighborsAt(x + 1, y, z, id); - } - else if (dir == 3) - { + } else if (dir == 3) { level->updateNeighborsAt(x, y, z - 1, id); - } - else if (dir == 4) - { + } else if (dir == 4) { level->updateNeighborsAt(x, y, z + 1, id); - } - else if (dir == 5 || dir == 6) - { + } else if (dir == 5 || dir == 6) { level->updateNeighborsAt(x, y - 1, z, id); + } else if (dir == 0 || dir == 7) { + level->updateNeighborsAt(x, y + 1, z, id); } - else if (dir == 0 || dir == 7) - { - level->updateNeighborsAt(x, y + 1, z, id); - } return true; } -void LeverTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - if ((data & 8) > 0) - { +void LeverTile::onRemove(Level* level, int x, int y, int z, int id, int data) { + if ((data & 8) > 0) { level->updateNeighborsAt(x, y, z, this->id); int dir = data & 7; - if (dir == 1) - { + if (dir == 1) { level->updateNeighborsAt(x - 1, y, z, this->id); - } - else if (dir == 2) - { + } else if (dir == 2) { level->updateNeighborsAt(x + 1, y, z, this->id); - } - else if (dir == 3) - { + } else if (dir == 3) { level->updateNeighborsAt(x, y, z - 1, this->id); - } - else if (dir == 4) - { + } else if (dir == 4) { level->updateNeighborsAt(x, y, z + 1, this->id); - } - else if (dir == 5 || dir == 6) - { + } else if (dir == 5 || dir == 6) { level->updateNeighborsAt(x, y - 1, z, this->id); - } - else if (dir == 0 || dir == 7) - { - level->updateNeighborsAt(x, y + 1, z, this->id); - } + } else if (dir == 0 || dir == 7) { + level->updateNeighborsAt(x, y + 1, z, this->id); + } } Tile::onRemove(level, x, y, z, id, data); } -bool LeverTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return (level->getData(x, y, z) & 8) > 0; +bool LeverTile::getSignal(LevelSource* level, int x, int y, int z, int dir) { + return (level->getData(x, y, z) & 8) > 0; } -bool LeverTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ +bool LeverTile::getDirectSignal(Level* level, int x, int y, int z, int dir) { int data = level->getData(x, y, z); if ((data & 8) == 0) return false; int myDir = data & 7; - - if (myDir == 0 && dir == 0) return true; - if (myDir == 7 && dir == 0) return true; + + if (myDir == 0 && dir == 0) return true; + if (myDir == 7 && dir == 0) return true; if (myDir == 6 && dir == 1) return true; if (myDir == 5 && dir == 1) return true; if (myDir == 4 && dir == 2) return true; @@ -303,7 +248,4 @@ bool LeverTile::getDirectSignal(Level *level, int x, int y, int z, int dir) return false; } -bool LeverTile::isSignalSource() -{ - return true; -} +bool LeverTile::isSignalSource() { return true; } diff --git a/Minecraft.World/Blocks/LeverTile.h b/Minecraft.World/Blocks/LeverTile.h index 3c0140b56..50af9b9b4 100644 --- a/Minecraft.World/Blocks/LeverTile.h +++ b/Minecraft.World/Blocks/LeverTile.h @@ -1,31 +1,43 @@ #pragma once #include "Tile.h" -class LeverTile : public Tile -{ - friend class Tile; +class LeverTile : public Tile { + friend class Tile; + protected: - LeverTile(int id); + LeverTile(int id); + public: - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - static int getLeverFacing(int facing); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + static int getLeverFacing(int facing); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + private: - virtual bool checkCanSurvive(Level *level, int x, int y, int z); + virtual bool checkCanSurvive(Level* level, int x, int y, int z); + public: - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); virtual bool isSignalSource(); }; diff --git a/Minecraft.World/Blocks/LightGemTile.cpp b/Minecraft.World/Blocks/LightGemTile.cpp index 3c7eef057..bd6a240c1 100644 --- a/Minecraft.World/Blocks/LightGemTile.cpp +++ b/Minecraft.World/Blocks/LightGemTile.cpp @@ -2,21 +2,17 @@ #include "LightGemTile.h" #include "../Headers/net.minecraft.world.item.h" -LightGemTile::LightGemTile(int id, Material *material) : Tile(id, material) -{ +LightGemTile::LightGemTile(int id, Material* material) : Tile(id, material) {} + +int LightGemTile::getResourceCountForLootBonus(int bonusLevel, Random* random) { + return Mth::clamp( + getResourceCount(random) + random->nextInt(bonusLevel + 1), 1, 4); } -int LightGemTile::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - return Mth::clamp(getResourceCount(random) + random->nextInt(bonusLevel + 1), 1, 4); +int LightGemTile::getResourceCount(Random* random) { + return 2 + random->nextInt(3); } -int LightGemTile::getResourceCount(Random *random) -{ - return 2 + random->nextInt(3); -} - -int LightGemTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::yellowDust->id; +int LightGemTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::yellowDust->id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/LightGemTile.h b/Minecraft.World/Blocks/LightGemTile.h index fade11ed9..f6d50d463 100644 --- a/Minecraft.World/Blocks/LightGemTile.h +++ b/Minecraft.World/Blocks/LightGemTile.h @@ -3,11 +3,10 @@ class Random; -class LightGemTile : public Tile -{ +class LightGemTile : public Tile { public: - LightGemTile(int id, Material *material); - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); + LightGemTile(int id, Material* material); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LiquidMaterial.h b/Minecraft.World/Blocks/LiquidMaterial.h index 15a3c2942..6097fc9b9 100644 --- a/Minecraft.World/Blocks/LiquidMaterial.h +++ b/Minecraft.World/Blocks/LiquidMaterial.h @@ -1,12 +1,14 @@ #pragma once #include "Material.h" -class LiquidMaterial : public Material -{ +class LiquidMaterial : public Material { public: - LiquidMaterial(MaterialColor *color) : Material(color) { replaceable(); destroyOnPush(); } + LiquidMaterial(MaterialColor* color) : Material(color) { + replaceable(); + destroyOnPush(); + } - virtual bool isLiquid() { return true; } - virtual bool blocksMotion() { return false; } - virtual bool isSolid() { return false; } + virtual bool isLiquid() { return true; } + virtual bool blocksMotion() { return false; } + virtual bool isSolid() { return false; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LiquidTile.cpp b/Minecraft.World/Blocks/LiquidTile.cpp index e460e757a..f49c92cfb 100644 --- a/Minecraft.World/Blocks/LiquidTile.cpp +++ b/Minecraft.World/Blocks/LiquidTile.cpp @@ -12,8 +12,7 @@ const std::wstring LiquidTile::TEXTURE_WATER_STILL = L"water"; const std::wstring LiquidTile::TEXTURE_WATER_FLOW = L"water_flow"; const std::wstring LiquidTile::TEXTURE_LAVA_FLOW = L"lava_flow"; -LiquidTile::LiquidTile(int id, Material *material) : Tile(id, material, false) -{ +LiquidTile::LiquidTile(int id, Material* material) : Tile(id, material, false) { float yo = 0; float e = 0; @@ -21,140 +20,105 @@ LiquidTile::LiquidTile(int id, Material *material) : Tile(id, material, false) setTicking(true); } -bool LiquidTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return material != Material::lava; +bool LiquidTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return material != Material::lava; } -int LiquidTile::getColor() const -{ - return 0xffffff; +int LiquidTile::getColor() const { return 0xffffff; } + +int LiquidTile::getColor(LevelSource* level, int x, int y, int z) { + return getColor(level, x, y, z, 0); } -int LiquidTile::getColor(LevelSource *level, int x, int y, int z) -{ +int LiquidTile::getColor(LevelSource* level, int x, int y, int z, int d) { + if (material == Material::water) { + int totalRed = 0; + int totalGreen = 0; + int totalBlue = 0; - return getColor(level, x, y, z, 0); + for (int oz = -1; oz <= 1; oz++) { + for (int ox = -1; ox <= 1; ox++) { + int waterColor = + level->getBiome(x + ox, z + oz)->getWaterColor(); + + totalRed += (waterColor & 0xff0000) >> 16; + totalGreen += (waterColor & 0xff00) >> 8; + totalBlue += (waterColor & 0xff); + } + } + + return (((totalRed / 9) & 0xFF) << 16) | + (((totalGreen / 9) & 0xFF) << 8) | (((totalBlue / 9) & 0xFF)); + } + return 0xffffff; } -int LiquidTile::getColor(LevelSource *level, int x, int y, int z, int d) -{ - if (material == Material::water) - { - int totalRed = 0; - int totalGreen = 0; - int totalBlue = 0; - - for (int oz = -1; oz <= 1; oz++) - { - for (int ox = -1; ox <= 1; ox++) - { - int waterColor = level->getBiome(x + ox, z + oz)->getWaterColor(); - - totalRed += (waterColor & 0xff0000) >> 16; - totalGreen += (waterColor & 0xff00) >> 8; - totalBlue += (waterColor & 0xff); - } - } - - return (((totalRed / 9) & 0xFF) << 16) | (((totalGreen / 9) & 0xFF) << 8) | (((totalBlue / 9) & 0xFF)); - } - return 0xffffff; -} - -float LiquidTile::getHeight(int d) -{ +float LiquidTile::getHeight(int d) { if (d >= 8) d = 0; return (d + 1) / 9.0f; } -Icon *LiquidTile::getTexture(int face, int data) -{ - if (face == Facing::DOWN || face == Facing::UP) - { +Icon* LiquidTile::getTexture(int face, int data) { + if (face == Facing::DOWN || face == Facing::UP) { return icons[0]; - } - else - { + } else { return icons[1]; } } -int LiquidTile::getDepth(Level *level, int x, int y, int z) -{ - if (level->getMaterial(x, y, z) == material) return level->getData(x, y, z); - else return -1; +int LiquidTile::getDepth(Level* level, int x, int y, int z) { + if (level->getMaterial(x, y, z) == material) + return level->getData(x, y, z); + else + return -1; } -int LiquidTile::getRenderedDepth(LevelSource *level, int x, int y, int z) -{ +int LiquidTile::getRenderedDepth(LevelSource* level, int x, int y, int z) { if (level->getMaterial(x, y, z) != material) return -1; int d = level->getData(x, y, z); if (d >= 8) d = 0; return d; } -bool LiquidTile::isCubeShaped() -{ - return false; -} +bool LiquidTile::isCubeShaped() { return false; } -bool LiquidTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool LiquidTile::isSolidRender(bool isServerLevel) { return false; } -bool LiquidTile::mayPick(int data, bool liquid) -{ - return liquid && data == 0; -} +bool LiquidTile::mayPick(int data, bool liquid) { return liquid && data == 0; } -bool LiquidTile::isSolidFace(LevelSource *level, int x, int y, int z, int face) -{ - Material *m = level->getMaterial(x, y, z); +bool LiquidTile::isSolidFace(LevelSource* level, int x, int y, int z, + int face) { + Material* m = level->getMaterial(x, y, z); if (m == this->material) return false; - if (face == Facing::UP) return true; + if (face == Facing::UP) return true; if (m == Material::ice) return false; - + return Tile::isSolidFace(level, x, y, z, face); } -bool LiquidTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - Material *m = level->getMaterial(x, y, z); +bool LiquidTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + Material* m = level->getMaterial(x, y, z); if (m == this->material) return false; - if (face == Facing::UP) return true; + if (face == Facing::UP) return true; if (m == Material::ice) return false; return Tile::shouldRenderFace(level, x, y, z, face); } -AABB *LiquidTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* LiquidTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +int LiquidTile::getRenderShape() { return Tile::SHAPE_WATER; } + +int LiquidTile::getResource(int data, Random* random, int playerBonusLevel) { + return 0; } -int LiquidTile::getRenderShape() -{ - return Tile::SHAPE_WATER; -} +int LiquidTile::getResourceCount(Random* random) { return 0; } -int LiquidTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; -} - -int LiquidTile::getResourceCount(Random *random) -{ - return 0; -} - -Vec3 *LiquidTile::getFlow(LevelSource *level, int x, int y, int z) -{ - Vec3 *flow = Vec3::newTemp(0,0,0); +Vec3* LiquidTile::getFlow(LevelSource* level, int x, int y, int z) { + Vec3* flow = Vec3::newTemp(0, 0, 0); int mid = getRenderedDepth(level, x, y, z); - for (int d = 0; d < 4; d++) - { - + for (int d = 0; d < 4; d++) { int xt = x; int yt = y; int zt = z; @@ -165,29 +129,24 @@ Vec3 *LiquidTile::getFlow(LevelSource *level, int x, int y, int z) if (d == 3) zt++; int t = getRenderedDepth(level, xt, yt, zt); - if (t < 0) - { - if (!level->getMaterial(xt, yt, zt)->blocksMotion()) - { + if (t < 0) { + if (!level->getMaterial(xt, yt, zt)->blocksMotion()) { t = getRenderedDepth(level, xt, yt - 1, zt); - if (t >= 0) - { + if (t >= 0) { int dir = t - (mid - 8); - flow = flow->add((xt - x) * dir, (yt - y) * dir, (zt - z) * dir); + flow = flow->add((xt - x) * dir, (yt - y) * dir, + (zt - z) * dir); } } - } else - { - if (t >= 0) - { + } else { + if (t >= 0) { int dir = t - mid; - flow = flow->add((xt - x) * dir, (yt - y) * dir, (zt - z) * dir); + flow = + flow->add((xt - x) * dir, (yt - y) * dir, (zt - z) * dir); } } - } - if (level->getData(x, y, z) >= 8) - { + if (level->getData(x, y, z) >= 8) { bool ok = false; if (ok || isSolidFace(level, x, y, z - 1, 2)) ok = true; if (ok || isSolidFace(level, x, y, z + 1, 3)) ok = true; @@ -203,25 +162,25 @@ Vec3 *LiquidTile::getFlow(LevelSource *level, int x, int y, int z) return flow; } -void LiquidTile::handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current) -{ - Vec3 *flow = getFlow(level, x, y, z); +void LiquidTile::handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current) { + Vec3* flow = getFlow(level, x, y, z); current->x += flow->x; current->y += flow->y; current->z += flow->z; } -int LiquidTile::getTickDelay() -{ +int LiquidTile::getTickDelay() { if (material == Material::water) return 5; if (material == Material::lava) return 30; return 0; } // 4J - change brought forward from 1.8.2 -int LiquidTile::getLightColor(LevelSource *level, int x, int y, int z, int tileId/*=-1*/) -{ - // 4J - note that this code seems to basically be a hack to fix a problem where post-processed things like lakes aren't getting lit properly +int LiquidTile::getLightColor(LevelSource* level, int x, int y, int z, + int tileId /*=-1*/) { + // 4J - note that this code seems to basically be a hack to fix a problem + // where post-processed things like lakes aren't getting lit properly int a = level->getLightColor(x, y, z, 0, tileId); int b = level->getLightColor(x, y + 1, z, 0, tileId); @@ -233,35 +192,29 @@ int LiquidTile::getLightColor(LevelSource *level, int x, int y, int z, int tileI return (aa > ba ? aa : ba) | ((ab > bb ? ab : bb) << 16); } -float LiquidTile::getBrightness(LevelSource *level, int x, int y, int z) -{ +float LiquidTile::getBrightness(LevelSource* level, int x, int y, int z) { float a = level->getBrightness(x, y, z); float b = level->getBrightness(x, y + 1, z); return a > b ? a : b; } -int LiquidTile::getRenderLayer() -{ - return material == Material::water ? 1 : 0; -} +int LiquidTile::getRenderLayer() { return material == Material::water ? 1 : 0; } -void LiquidTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - if (material == Material::water) - { - if (random->nextInt(10) == 0) - { +void LiquidTile::animateTick(Level* level, int x, int y, int z, + Random* random) { + if (material == Material::water) { + if (random->nextInt(10) == 0) { int d = level->getData(x, y, z); - if (d <= 0 || d >= 8) - { - level->addParticle(eParticleType_suspended, x + random->nextFloat(), y + random->nextFloat(), z + random->nextFloat(), 0, 0, 0); + if (d <= 0 || d >= 8) { + level->addParticle( + eParticleType_suspended, x + random->nextFloat(), + y + random->nextFloat(), z + random->nextFloat(), 0, 0, 0); } } - // 4J-PB - this loop won't run! - for (int i = 0; i < 0; i++) - { // This was an attempt to add foam to - // the bottoms of waterfalls. It - // didn't went ok. + // 4J-PB - this loop won't run! + for (int i = 0; i < 0; i++) { // This was an attempt to add foam to + // the bottoms of waterfalls. It + // didn't went ok. int dir = random->nextInt(4); int xt = x; int zt = z; @@ -269,8 +222,9 @@ void LiquidTile::animateTick(Level *level, int x, int y, int z, Random *random) if (dir == 1) xt++; if (dir == 2) zt--; if (dir == 3) zt++; - if (level->getMaterial(xt, y, zt) == Material::air && (level->getMaterial(xt, y - 1, zt)->blocksMotion() || level->getMaterial(xt, y - 1, zt)->isLiquid())) - { + if (level->getMaterial(xt, y, zt) == Material::air && + (level->getMaterial(xt, y - 1, zt)->blocksMotion() || + level->getMaterial(xt, y - 1, zt)->isLiquid())) { float r = 1 / 16.0f; double xx = x + random->nextFloat(); double yy = y + random->nextFloat(); @@ -292,127 +246,127 @@ void LiquidTile::animateTick(Level *level, int x, int y, int z, Random *random) } } } - if (material == Material::water && random->nextInt(64) == 0) - { + if (material == Material::water && random->nextInt(64) == 0) { int d = level->getData(x, y, z); - if (d > 0 && d < 8) - { - level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_LIQUID_WATER, random->nextFloat() * 0.25f + 0.75f, random->nextFloat() * 1.0f + 0.5f); + if (d > 0 && d < 8) { + level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, + eSoundType_LIQUID_WATER, + random->nextFloat() * 0.25f + 0.75f, + random->nextFloat() * 1.0f + 0.5f); } } - if (material == Material::lava) - { - if (level->getMaterial(x, y + 1, z) == Material::air && !level->isSolidRenderTile(x, y + 1, z)) - { - if (random->nextInt(100) == 0) - { - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); + if (material == Material::lava) { + if (level->getMaterial(x, y + 1, z) == Material::air && + !level->isSolidRenderTile(x, y + 1, z)) { + if (random->nextInt(100) == 0) { + ThreadStorage* tls = + (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); double xx = x + random->nextFloat(); double yy = y + tls->yy1; double zz = z + random->nextFloat(); level->addParticle(eParticleType_lava, xx, yy, zz, 0, 0, 0); - // 4J - new sound brought forward from 1.2.3 - level->playLocalSound(xx, yy, zz, eSoundType_LIQUID_LAVA_POP, 0.2f + random->nextFloat() * 0.2f, 0.9f + random->nextFloat() * 0.15f); + // 4J - new sound brought forward from 1.2.3 + level->playLocalSound(xx, yy, zz, eSoundType_LIQUID_LAVA_POP, + 0.2f + random->nextFloat() * 0.2f, + 0.9f + random->nextFloat() * 0.15f); } - // 4J - new sound brought forward from 1.2.3 - if (random->nextInt(200) == 0) - { - level->playLocalSound(x, y, z, eSoundType_LIQUID_LAVA, 0.2f + random->nextFloat() * 0.2f, 0.9f + random->nextFloat() * 0.15f); + // 4J - new sound brought forward from 1.2.3 + if (random->nextInt(200) == 0) { + level->playLocalSound(x, y, z, eSoundType_LIQUID_LAVA, + 0.2f + random->nextFloat() * 0.2f, + 0.9f + random->nextFloat() * 0.15f); } } } - if (random->nextInt(10) == 0) - { - if (level->isTopSolidBlocking(x, y - 1, z) && !level->getMaterial(x, y - 2, z)->blocksMotion()) - { + if (random->nextInt(10) == 0) { + if (level->isTopSolidBlocking(x, y - 1, z) && + !level->getMaterial(x, y - 2, z)->blocksMotion()) { double xx = x + random->nextFloat(); double yy = y - 1.05; double zz = z + random->nextFloat(); - if (material == Material::water) level->addParticle(eParticleType_dripWater, xx, yy, zz, 0, 0, 0); - else level->addParticle(eParticleType_dripLava, xx, yy, zz, 0, 0, 0); + if (material == Material::water) + level->addParticle(eParticleType_dripWater, xx, yy, zz, 0, 0, + 0); + else + level->addParticle(eParticleType_dripLava, xx, yy, zz, 0, 0, 0); } } } -double LiquidTile::getSlopeAngle(LevelSource *level, int x, int y, int z, Material *m) -{ - Vec3 *flow = NULL; - if (m == Material::water) flow = ((LiquidTile *) Tile::water)->getFlow(level, x, y, z); - if (m == Material::lava) flow = ((LiquidTile *) Tile::lava)->getFlow(level, x, y, z); +double LiquidTile::getSlopeAngle(LevelSource* level, int x, int y, int z, + Material* m) { + Vec3* flow = NULL; + if (m == Material::water) + flow = ((LiquidTile*)Tile::water)->getFlow(level, x, y, z); + if (m == Material::lava) + flow = ((LiquidTile*)Tile::lava)->getFlow(level, x, y, z); if (flow->x == 0 && flow->z == 0) return -1000; return atan2(flow->z, flow->x) - PI / 2; } -void LiquidTile::onPlace(Level *level, int x, int y, int z) -{ - updateLiquid(level, x, y, z); +void LiquidTile::onPlace(Level* level, int x, int y, int z) { + updateLiquid(level, x, y, z); } -void LiquidTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - updateLiquid(level, x, y, z); +void LiquidTile::neighborChanged(Level* level, int x, int y, int z, int type) { + updateLiquid(level, x, y, z); } -void LiquidTile::updateLiquid(Level *level, int x, int y, int z) -{ +void LiquidTile::updateLiquid(Level* level, int x, int y, int z) { if (level->getTile(x, y, z) != id) return; - if (material == Material::lava) - { + if (material == Material::lava) { bool water = false; - if (water || level->getMaterial(x, y, z - 1) == Material::water) water = true; - if (water || level->getMaterial(x, y, z + 1) == Material::water) water = true; - if (water || level->getMaterial(x - 1, y, z) == Material::water) water = true; - if (water || level->getMaterial(x + 1, y, z) == Material::water) water = true; - if (water || level->getMaterial(x, y + 1, z) == Material::water) water = true; - if (water) - { + if (water || level->getMaterial(x, y, z - 1) == Material::water) + water = true; + if (water || level->getMaterial(x, y, z + 1) == Material::water) + water = true; + if (water || level->getMaterial(x - 1, y, z) == Material::water) + water = true; + if (water || level->getMaterial(x + 1, y, z) == Material::water) + water = true; + if (water || level->getMaterial(x, y + 1, z) == Material::water) + water = true; + if (water) { int data = level->getData(x, y, z); - if (data == 0) - { + if (data == 0) { level->setTile(x, y, z, Tile::obsidian_Id); - } - else if (data <= 4) - { + } else if (data <= 4) { level->setTile(x, y, z, Tile::stoneBrick_Id); } fizz(level, x, y, z); } } - } -void LiquidTile::fizz(Level *level, int x, int y, int z) -{ - MemSect(31); - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, 2.6f + (level->random->nextFloat() - level->random->nextFloat()) * 0.8f); - MemSect(0); - for (int i = 0; i < 8; i++) - { - level->addParticle(eParticleType_largesmoke, x +Math::random(), y + 1.2, z + Math::random(), 0, 0, 0); +void LiquidTile::fizz(Level* level, int x, int y, int z) { + MemSect(31); + level->playSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, + 2.6f + + (level->random->nextFloat() - level->random->nextFloat()) * 0.8f); + MemSect(0); + for (int i = 0; i < 8; i++) { + level->addParticle(eParticleType_largesmoke, x + Math::random(), + y + 1.2, z + Math::random(), 0, 0, 0); } } -void LiquidTile::registerIcons(IconRegister *iconRegister) -{ - if (material == Material::lava) - { - icons[0] = iconRegister->registerIcon(TEXTURE_LAVA_STILL); - icons[1] = iconRegister->registerIcon(TEXTURE_LAVA_FLOW); - } - else - { - icons[0] = iconRegister->registerIcon(TEXTURE_WATER_STILL); - icons[1] = iconRegister->registerIcon(TEXTURE_WATER_FLOW); - } +void LiquidTile::registerIcons(IconRegister* iconRegister) { + if (material == Material::lava) { + icons[0] = iconRegister->registerIcon(TEXTURE_LAVA_STILL); + icons[1] = iconRegister->registerIcon(TEXTURE_LAVA_FLOW); + } else { + icons[0] = iconRegister->registerIcon(TEXTURE_WATER_STILL); + icons[1] = iconRegister->registerIcon(TEXTURE_WATER_FLOW); + } } -Icon *LiquidTile::getTexture(const std::wstring &name) -{ - if (name.compare(TEXTURE_WATER_STILL)==0) return Tile::water->icons[0]; - if (name.compare(TEXTURE_WATER_FLOW)==0) return Tile::water->icons[1]; - if (name.compare(TEXTURE_LAVA_STILL)==0) return Tile::lava->icons[0]; - if (name.compare(TEXTURE_LAVA_FLOW)==0) return Tile::lava->icons[1]; - return NULL; +Icon* LiquidTile::getTexture(const std::wstring& name) { + if (name.compare(TEXTURE_WATER_STILL) == 0) return Tile::water->icons[0]; + if (name.compare(TEXTURE_WATER_FLOW) == 0) return Tile::water->icons[1]; + if (name.compare(TEXTURE_LAVA_STILL) == 0) return Tile::lava->icons[0]; + if (name.compare(TEXTURE_LAVA_FLOW) == 0) return Tile::lava->icons[1]; + return NULL; } diff --git a/Minecraft.World/Blocks/LiquidTile.h b/Minecraft.World/Blocks/LiquidTile.h index 4a0e8e6d5..1415a2c7e 100644 --- a/Minecraft.World/Blocks/LiquidTile.h +++ b/Minecraft.World/Blocks/LiquidTile.h @@ -5,58 +5,71 @@ class Random; class ChunkRebuildData; -class LiquidTile : public Tile -{ - friend class ChunkRebuildData; +class LiquidTile : public Tile { + friend class ChunkRebuildData; + public: - static const std::wstring TEXTURE_LAVA_STILL; - static const std::wstring TEXTURE_WATER_STILL; - static const std::wstring TEXTURE_WATER_FLOW; - static const std::wstring TEXTURE_LAVA_FLOW; + static const std::wstring TEXTURE_LAVA_STILL; + static const std::wstring TEXTURE_WATER_STILL; + static const std::wstring TEXTURE_WATER_FLOW; + static const std::wstring TEXTURE_LAVA_FLOW; private: - Icon *icons[2]; + Icon* icons[2]; protected: - LiquidTile(int id, Material *material); + LiquidTile(int id, Material* material); + public: - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - virtual int getColor() const; - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + virtual int getColor() const; + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added static float getHeight(int d); - virtual Icon *getTexture(int face, int data); + virtual Icon* getTexture(int face, int data); + protected: - virtual int getDepth(Level *level, int x, int y, int z); - virtual int getRenderedDepth(LevelSource *level, int x, int y, int z); -public: - virtual bool isCubeShaped(); - virtual bool isSolidRender(bool isServerLevel = false); - virtual bool mayPick(int data, bool liquid); - virtual bool isSolidFace(LevelSource *level, int x, int y, int z, int face); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual int getRenderShape(); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); -private: - virtual Vec3 *getFlow(LevelSource *level, int x, int y, int z); -public: - virtual void handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current); - virtual int getTickDelay(); - virtual int getLightColor(LevelSource *level, int x, int y, int z, int tileId=-1); // 4J - brought forward from 1.8.2 - virtual float getBrightness(LevelSource *level, int x, int y, int z); - virtual int getRenderLayer(); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); - static double getSlopeAngle(LevelSource *level, int x, int y, int z, Material *m); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); -private: - virtual void updateLiquid(Level *level, int x, int y, int z); -protected: - virtual void fizz(Level *level, int x, int y, int z); + virtual int getDepth(Level* level, int x, int y, int z); + virtual int getRenderedDepth(LevelSource* level, int x, int y, int z); public: - void registerIcons(IconRegister *iconRegister); - static Icon *getTexture(const std::wstring &name); + virtual bool isCubeShaped(); + virtual bool isSolidRender(bool isServerLevel = false); + virtual bool mayPick(int data, bool liquid); + virtual bool isSolidFace(LevelSource* level, int x, int y, int z, int face); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual int getRenderShape(); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + +private: + virtual Vec3* getFlow(LevelSource* level, int x, int y, int z); + +public: + virtual void handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current); + virtual int getTickDelay(); + virtual int getLightColor( + LevelSource* level, int x, int y, int z, + int tileId = -1); // 4J - brought forward from 1.8.2 + virtual float getBrightness(LevelSource* level, int x, int y, int z); + virtual int getRenderLayer(); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); + static double getSlopeAngle(LevelSource* level, int x, int y, int z, + Material* m); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + +private: + virtual void updateLiquid(Level* level, int x, int y, int z); + +protected: + virtual void fizz(Level* level, int x, int y, int z); + +public: + void registerIcons(IconRegister* iconRegister); + static Icon* getTexture(const std::wstring& name); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LiquidTileDynamic.cpp b/Minecraft.World/Blocks/LiquidTileDynamic.cpp index 556005021..1e7a5cb1a 100644 --- a/Minecraft.World/Blocks/LiquidTileDynamic.cpp +++ b/Minecraft.World/Blocks/LiquidTileDynamic.cpp @@ -3,74 +3,67 @@ #include "LiquidTileDynamic.h" #include "../Headers/net.minecraft.world.level.dimension.h" -LiquidTileDynamic::LiquidTileDynamic(int id, Material *material) : LiquidTile(id, material) -{ - maxCount = 0; +LiquidTileDynamic::LiquidTileDynamic(int id, Material* material) + : LiquidTile(id, material) { + maxCount = 0; result = new bool[4]; dist = new int[4]; - m_iterativeInstatick = false; + m_iterativeInstatick = false; } -LiquidTileDynamic::~LiquidTileDynamic() -{ - delete[] result; - delete[] dist; +LiquidTileDynamic::~LiquidTileDynamic() { + delete[] result; + delete[] dist; } -void LiquidTileDynamic::setStatic(Level *level, int x, int y, int z) -{ +void LiquidTileDynamic::setStatic(Level* level, int x, int y, int z) { int d = level->getData(x, y, z); level->setTileAndDataNoUpdate(x, y, z, id + 1, d); level->setTilesDirty(x, y, z, x, y, z); } -bool LiquidTileDynamic::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return material != Material::lava; +bool LiquidTileDynamic::isPathfindable(LevelSource* level, int x, int y, + int z) { + return material != Material::lava; } -void LiquidTileDynamic::iterativeTick(Level *level, int x, int y, int z, Random *random) -{ - m_tilesToTick.push_back(LiquidTickData(level, x,y,z,random)); +void LiquidTileDynamic::iterativeTick(Level* level, int x, int y, int z, + Random* random) { + m_tilesToTick.push_back(LiquidTickData(level, x, y, z, random)); - while(m_tilesToTick.size() > 0) - { - LiquidTickData tickData = m_tilesToTick.front(); - m_tilesToTick.pop_front(); - mainTick(tickData.level, tickData.x, tickData.y, tickData.z, tickData.random); - } + while (m_tilesToTick.size() > 0) { + LiquidTickData tickData = m_tilesToTick.front(); + m_tilesToTick.pop_front(); + mainTick(tickData.level, tickData.x, tickData.y, tickData.z, + tickData.random); + } } -void LiquidTileDynamic::tick(Level *level, int x, int y, int z, Random *random) -{ - if(!m_iterativeInstatick && level->getInstaTick() ) - { - m_iterativeInstatick = true; - iterativeTick(level, x, y, z, random); - m_iterativeInstatick = false; - } - else if(m_iterativeInstatick && level->getInstaTick()) - { - m_tilesToTick.push_back(LiquidTickData(level, x,y,z,random)); - } - else - { - mainTick(level, x, y, z, random); - } +void LiquidTileDynamic::tick(Level* level, int x, int y, int z, + Random* random) { + if (!m_iterativeInstatick && level->getInstaTick()) { + m_iterativeInstatick = true; + iterativeTick(level, x, y, z, random); + m_iterativeInstatick = false; + } else if (m_iterativeInstatick && level->getInstaTick()) { + m_tilesToTick.push_back(LiquidTickData(level, x, y, z, random)); + } else { + mainTick(level, x, y, z, random); + } } -// 4J Stu - Split off what was the tick function to be able to change between recursive and iterative ticking -// This is to fix the stack overflow that occurs sometimes when instaticking on level gen. -void LiquidTileDynamic::mainTick(Level *level, int x, int y, int z, Random *random) -{ +// 4J Stu - Split off what was the tick function to be able to change between +// recursive and iterative ticking This is to fix the stack overflow that occurs +// sometimes when instaticking on level gen. +void LiquidTileDynamic::mainTick(Level* level, int x, int y, int z, + Random* random) { int depth = getDepth(level, x, y, z); int dropOff = 1; if (material == Material::lava && !level->dimension->ultraWarm) dropOff = 2; bool becomeStatic = true; - if (depth > 0) - { + if (depth > 0) { int highest = -100; maxCount = 0; highest = getHighest(level, x - 1, y, z, highest); @@ -79,88 +72,71 @@ void LiquidTileDynamic::mainTick(Level *level, int x, int y, int z, Random *rand highest = getHighest(level, x, y, z + 1, highest); int newDepth = highest + dropOff; - if (newDepth >= 8 || highest < 0) - { + if (newDepth >= 8 || highest < 0) { newDepth = -1; } - if (getDepth(level, x, y + 1, z) >= 0) - { + if (getDepth(level, x, y + 1, z) >= 0) { int above = getDepth(level, x, y + 1, z); - if (above >= 8) newDepth = above; - else newDepth = above + 8; + if (above >= 8) + newDepth = above; + else + newDepth = above + 8; } - if (maxCount >= 2 && material == Material::water) - { + if (maxCount >= 2 && material == Material::water) { // Only spread spring if it's on top of an existing spring, or - // on top of solid ground. - if (level->getMaterial(x, y - 1, z)->isSolid()) - { + // on top of solid ground. + if (level->getMaterial(x, y - 1, z)->isSolid()) { newDepth = 0; - } - else if (level->getMaterial(x, y - 1, z) == material && level->getData(x, y - 1, z) == 0) - { + } else if (level->getMaterial(x, y - 1, z) == material && + level->getData(x, y - 1, z) == 0) { newDepth = 0; } } - if (material == Material::lava) - { - if (depth < 8 && newDepth < 8) - { - if (newDepth > depth) - { - if (random->nextInt(4) != 0) - { + if (material == Material::lava) { + if (depth < 8 && newDepth < 8) { + if (newDepth > depth) { + if (random->nextInt(4) != 0) { newDepth = depth; becomeStatic = false; } } } } - if (newDepth == depth) - { - if (becomeStatic) - { - setStatic(level, x, y, z); - } - } - else - { + if (newDepth == depth) { + if (becomeStatic) { + setStatic(level, x, y, z); + } + } else { depth = newDepth; - if (depth < 0) - { + if (depth < 0) { level->setTile(x, y, z, 0); - } else - { + } else { level->setData(x, y, z, depth); level->addToTickNextTick(x, y, z, id, getTickDelay()); level->updateNeighborsAt(x, y, z, id); } } - } else - { + } else { setStatic(level, x, y, z); } - if (canSpreadTo(level, x, y - 1, z)) - { - if (material == Material::lava) - { - if (level->getMaterial(x, y - 1, z) == Material::water) - { + if (canSpreadTo(level, x, y - 1, z)) { + if (material == Material::lava) { + if (level->getMaterial(x, y - 1, z) == Material::water) { level->setTile(x, y - 1, z, Tile::rock_Id); fizz(level, x, y - 1, z); return; } } - if (depth >= 8) trySpreadTo(level, x, y - 1, z, depth); - else trySpreadTo(level, x, y - 1, z, depth + 8); - } - else if (depth >= 0 && (depth == 0 || isWaterBlocking(level, x, y - 1, z))) - { - bool *spreads = getSpread(level, x, y, z); - int neighbor = depth + dropOff; if (depth >= 8) - { + trySpreadTo(level, x, y - 1, z, depth); + else + trySpreadTo(level, x, y - 1, z, depth + 8); + } else if (depth >= 0 && + (depth == 0 || isWaterBlocking(level, x, y - 1, z))) { + bool* spreads = getSpread(level, x, y, z); + int neighbor = depth + dropOff; + if (depth >= 8) { neighbor = 1; } if (neighbor >= 8) return; @@ -171,33 +147,28 @@ void LiquidTileDynamic::mainTick(Level *level, int x, int y, int z, Random *rand } } -void LiquidTileDynamic::trySpreadTo(Level *level, int x, int y, int z, int neighbor) -{ - if (canSpreadTo(level, x, y, z)) - { - { - int old = level->getTile(x, y, z); - if (old > 0) - { - if (material == Material::lava) - { - fizz(level, x, y, z); - } - else - { - Tile::tiles[old]->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - } - } - } +void LiquidTileDynamic::trySpreadTo(Level* level, int x, int y, int z, + int neighbor) { + if (canSpreadTo(level, x, y, z)) { + { + int old = level->getTile(x, y, z); + if (old > 0) { + if (material == Material::lava) { + fizz(level, x, y, z); + } else { + Tile::tiles[old]->spawnResources( + level, x, y, z, level->getData(x, y, z), 0); + } + } + } level->setTileAndData(x, y, z, id, neighbor); } } -int LiquidTileDynamic::getSlopeDistance(Level *level, int x, int y, int z, int pass, int from) -{ +int LiquidTileDynamic::getSlopeDistance(Level* level, int x, int y, int z, + int pass, int from) { int lowest = 1000; - for (int d = 0; d < 4; d++) - { + for (int d = 0; d < 4; d++) { if (d == 0 && from == 1) continue; if (d == 1 && from == 0) continue; if (d == 2 && from == 3) continue; @@ -212,37 +183,27 @@ int LiquidTileDynamic::getSlopeDistance(Level *level, int x, int y, int z, int p if (d == 2) zz--; if (d == 3) zz++; - if (isWaterBlocking(level, xx, yy, zz)) - { + if (isWaterBlocking(level, xx, yy, zz)) { continue; - } else if (level->getMaterial(xx, yy, zz) == material && level->getData(xx, yy, zz) == 0) - { + } else if (level->getMaterial(xx, yy, zz) == material && + level->getData(xx, yy, zz) == 0) { continue; - } - else - { - if (isWaterBlocking(level, xx, yy - 1, zz)) - { - if (pass < 4) - { + } else { + if (isWaterBlocking(level, xx, yy - 1, zz)) { + if (pass < 4) { int v = getSlopeDistance(level, xx, yy, zz, pass + 1, d); if (v < lowest) lowest = v; } - } - else - { + } else { return pass; } } } return lowest; - } -bool *LiquidTileDynamic::getSpread(Level *level, int x, int y, int z) -{ - for (int d = 0; d < 4; d++) - { +bool* LiquidTileDynamic::getSpread(Level* level, int x, int y, int z) { + for (int d = 0; d < 4; d++) { dist[d] = 1000; int xx = x; int yy = y; @@ -252,91 +213,81 @@ bool *LiquidTileDynamic::getSpread(Level *level, int x, int y, int z) if (d == 1) xx++; if (d == 2) zz--; if (d == 3) zz++; - if (isWaterBlocking(level, xx, yy, zz)) - { + if (isWaterBlocking(level, xx, yy, zz)) { + continue; + } else if (level->getMaterial(xx, yy, zz) == material && + level->getData(xx, yy, zz) == 0) { continue; } - else if (level->getMaterial(xx, yy, zz) == material && level->getData(xx, yy, zz) == 0) - { - continue; - } - { - if (isWaterBlocking(level, xx, yy - 1, zz)) - { + { + if (isWaterBlocking(level, xx, yy - 1, zz)) { dist[d] = getSlopeDistance(level, xx, yy, zz, 1, d); - } - else - { + } else { dist[d] = 0; } } } int lowest = dist[0]; - for (int d = 1; d < 4; d++) - { + for (int d = 1; d < 4; d++) { if (dist[d] < lowest) lowest = dist[d]; } - - for (int d = 0; d < 4; d++) - { + for (int d = 0; d < 4; d++) { result[d] = (dist[d] == lowest); } return result; - } -bool LiquidTileDynamic::isWaterBlocking(Level *level, int x, int y, int z) -{ +bool LiquidTileDynamic::isWaterBlocking(Level* level, int x, int y, int z) { int t = level->getTile(x, y, z); - if (t == Tile::door_wood_Id || t == Tile::door_iron_Id || t == Tile::sign_Id || t == Tile::ladder_Id || t == Tile::reeds_Id) - { + if (t == Tile::door_wood_Id || t == Tile::door_iron_Id || + t == Tile::sign_Id || t == Tile::ladder_Id || t == Tile::reeds_Id) { return true; } if (t == 0) return false; - Material *m = Tile::tiles[t]->material; + Material* m = Tile::tiles[t]->material; if (m == Material::portal) return true; if (m->blocksMotion()) return true; return false; } -int LiquidTileDynamic::getHighest(Level *level, int x, int y, int z, int current) -{ +int LiquidTileDynamic::getHighest(Level* level, int x, int y, int z, + int current) { int d = getDepth(level, x, y, z); if (d < 0) return current; if (d == 0) maxCount++; - if (d >= 8) - { + if (d >= 8) { d = 0; } return current < 0 || d < current ? d : current; } -bool LiquidTileDynamic::canSpreadTo(Level *level, int x, int y, int z) -{ - // 4J added - don't try and spread out of our restricted map. If we don't do this check then tiles at the edge of the world will try and spread outside as the outside tiles report that they contain - // only air. The fact that this successfully spreads then updates the neighbours of the tile outside of the map, one of which is the original tile just inside the map, which gets set back to being - // dynamic, and added to the pending ticks array. - int xc = x >> 4; - int zc = z >> 4; - int ix = xc + (level->chunkSourceXZSize/2); - int iz = zc + (level->chunkSourceXZSize/2); - if( ( ix < 0 ) || ( ix >= level->chunkSourceXZSize ) ) return false; - if( ( iz < 0 ) || ( iz >= level->chunkSourceXZSize ) ) return false; +bool LiquidTileDynamic::canSpreadTo(Level* level, int x, int y, int z) { + // 4J added - don't try and spread out of our restricted map. If we don't do + // this check then tiles at the edge of the world will try and spread + // outside as the outside tiles report that they contain only air. The fact + // that this successfully spreads then updates the neighbours of the tile + // outside of the map, one of which is the original tile just inside the + // map, which gets set back to being dynamic, and added to the pending ticks + // array. + int xc = x >> 4; + int zc = z >> 4; + int ix = xc + (level->chunkSourceXZSize / 2); + int iz = zc + (level->chunkSourceXZSize / 2); + if ((ix < 0) || (ix >= level->chunkSourceXZSize)) return false; + if ((iz < 0) || (iz >= level->chunkSourceXZSize)) return false; - Material *target = level->getMaterial(x, y, z); + Material* target = level->getMaterial(x, y, z); if (target == material) return false; if (target == Material::lava) return false; return !isWaterBlocking(level, x, y, z); } -void LiquidTileDynamic::onPlace(Level *level, int x, int y, int z) -{ +void LiquidTileDynamic::onPlace(Level* level, int x, int y, int z) { LiquidTile::onPlace(level, x, y, z); - if (level->getTile(x, y, z) == id) - { + if (level->getTile(x, y, z) == id) { level->addToTickNextTick(x, y, z, id, getTickDelay()); } } diff --git a/Minecraft.World/Blocks/LiquidTileDynamic.h b/Minecraft.World/Blocks/LiquidTileDynamic.h index 0aeed6319..2de923941 100644 --- a/Minecraft.World/Blocks/LiquidTileDynamic.h +++ b/Minecraft.World/Blocks/LiquidTileDynamic.h @@ -3,52 +3,58 @@ class Random; -class LiquidTileDynamic : public LiquidTile -{ - friend class Tile; +class LiquidTileDynamic : public LiquidTile { + friend class Tile; + private: - // 4J Added - typedef struct _LiquidTickData - { - Level *level; - int x, y, z; - Random *random; - _LiquidTickData(Level *level, int x, int y, int z, Random *random) - : level(level), x(x), y(y), z(z), random(random) - { - } - } LiquidTickData; - std::deque m_tilesToTick; // For an iterative version of instatick - bool m_iterativeInstatick; + // 4J Added + typedef struct _LiquidTickData { + Level* level; + int x, y, z; + Random* random; + _LiquidTickData(Level* level, int x, int y, int z, Random* random) + : level(level), x(x), y(y), z(z), random(random) {} + } LiquidTickData; + std::deque + m_tilesToTick; // For an iterative version of instatick + bool m_iterativeInstatick; + protected: - LiquidTileDynamic(int id, Material *material); - virtual ~LiquidTileDynamic(); + LiquidTileDynamic(int id, Material* material); + virtual ~LiquidTileDynamic(); + private: - void setStatic(Level *level, int x, int y, int z); + void setStatic(Level* level, int x, int y, int z); int maxCount; + public: - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); private: - // 4J Added - void iterativeTick(Level *level, int x, int y, int z, Random *random); - void mainTick(Level *level, int x, int y, int z, Random *random); + // 4J Added + void iterativeTick(Level* level, int x, int y, int z, Random* random); + void mainTick(Level* level, int x, int y, int z, Random* random); + public: - void tick(Level *level, int x, int y, int z, Random *random); -private: - void trySpreadTo(Level *level, int x, int y, int z, int neighbor); - - bool *result; - int *dist; + void tick(Level* level, int x, int y, int z, Random* random); private: - int getSlopeDistance(Level *level, int x, int y, int z, int pass, int from); - bool *getSpread(Level *level, int x, int y, int z); - bool isWaterBlocking(Level *level, int x, int y, int z); + void trySpreadTo(Level* level, int x, int y, int z, int neighbor); + + bool* result; + int* dist; + +private: + int getSlopeDistance(Level* level, int x, int y, int z, int pass, int from); + bool* getSpread(Level* level, int x, int y, int z); + bool isWaterBlocking(Level* level, int x, int y, int z); + protected: - int getHighest(Level *level, int x, int y, int z, int current); + int getHighest(Level* level, int x, int y, int z, int current); + private: - bool canSpreadTo(Level *level, int x, int y, int z); + bool canSpreadTo(Level* level, int x, int y, int z); + public: - void onPlace(Level *level, int x, int y, int z); + void onPlace(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/LiquidTileStatic.cpp b/Minecraft.World/Blocks/LiquidTileStatic.cpp index b4c874bf0..023bfb5cc 100644 --- a/Minecraft.World/Blocks/LiquidTileStatic.cpp +++ b/Minecraft.World/Blocks/LiquidTileStatic.cpp @@ -3,28 +3,25 @@ #include "LiquidTileStatic.h" #include "FireTile.h" -LiquidTileStatic::LiquidTileStatic(int id, Material *material) : LiquidTile(id, material) -{ +LiquidTileStatic::LiquidTileStatic(int id, Material* material) + : LiquidTile(id, material) { setTicking(false); if (material == Material::lava) setTicking(true); } -bool LiquidTileStatic::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return material != Material::lava; +bool LiquidTileStatic::isPathfindable(LevelSource* level, int x, int y, int z) { + return material != Material::lava; } -void LiquidTileStatic::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void LiquidTileStatic::neighborChanged(Level* level, int x, int y, int z, + int type) { LiquidTile::neighborChanged(level, x, y, z, type); - if (level->getTile(x, y, z) == id) - { + if (level->getTile(x, y, z) == id) { setDynamic(level, x, y, z); } } -void LiquidTileStatic::setDynamic(Level *level, int x, int y, int z) -{ +void LiquidTileStatic::setDynamic(Level* level, int x, int y, int z) { int d = level->getData(x, y, z); level->noNeighborUpdate = true; level->setTileAndDataNoUpdate(x, y, z, id - 1, d); @@ -33,53 +30,43 @@ void LiquidTileStatic::setDynamic(Level *level, int x, int y, int z) level->noNeighborUpdate = false; } -void LiquidTileStatic::tick(Level *level, int x, int y, int z, Random *random) -{ - if (material == Material::lava) - { +void LiquidTileStatic::tick(Level* level, int x, int y, int z, Random* random) { + if (material == Material::lava) { int h = random->nextInt(3); - for (int i = 0; i < h; i++) - { + for (int i = 0; i < h; i++) { x += random->nextInt(3) - 1; y++; z += random->nextInt(3) - 1; int t = level->getTile(x, y, z); - if (t == 0) - { + if (t == 0) { if (isFlammable(level, x - 1, y, z) || - isFlammable(level, x + 1, y, z) || - isFlammable(level, x, y, z - 1) || - isFlammable(level, x, y, z + 1) || - isFlammable(level, x, y - 1, z) || - isFlammable(level, x, y + 1, z)) - { + isFlammable(level, x + 1, y, z) || + isFlammable(level, x, y, z - 1) || + isFlammable(level, x, y, z + 1) || + isFlammable(level, x, y - 1, z) || + isFlammable(level, x, y + 1, z)) { level->setTile(x, y, z, Tile::fire_Id); return; } - } - else if (Tile::tiles[t]->material->blocksMotion()) - { + } else if (Tile::tiles[t]->material->blocksMotion()) { return; } - } - if (h == 0) - { - int ox = x; - int oz = z; - for (int i = 0; i< 3; i++) - { - x = ox + random->nextInt(3) - 1; - z = oz + random->nextInt(3) - 1; - if (level->isEmptyTile(x, y + 1, z) && isFlammable(level, x, y, z)) { - level->setTile(x, y + 1, z, Tile::fire_Id); - } - } - } + if (h == 0) { + int ox = x; + int oz = z; + for (int i = 0; i < 3; i++) { + x = ox + random->nextInt(3) - 1; + z = oz + random->nextInt(3) - 1; + if (level->isEmptyTile(x, y + 1, z) && + isFlammable(level, x, y, z)) { + level->setTile(x, y + 1, z, Tile::fire_Id); + } + } + } } } -bool LiquidTileStatic::isFlammable(Level *level, int x, int y, int z) -{ - return level->getMaterial(x, y, z)->isFlammable(); +bool LiquidTileStatic::isFlammable(Level* level, int x, int y, int z) { + return level->getMaterial(x, y, z)->isFlammable(); } diff --git a/Minecraft.World/Blocks/LiquidTileStatic.h b/Minecraft.World/Blocks/LiquidTileStatic.h index 031eef62c..c6ea3e9b8 100644 --- a/Minecraft.World/Blocks/LiquidTileStatic.h +++ b/Minecraft.World/Blocks/LiquidTileStatic.h @@ -3,18 +3,22 @@ class Random; -class LiquidTileStatic : public LiquidTile -{ - friend class Tile; +class LiquidTileStatic : public LiquidTile { + friend class Tile; + protected: - LiquidTileStatic(int id, Material *material); + LiquidTileStatic(int id, Material* material); + public: - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + private: - virtual void setDynamic(Level *level, int x, int y, int z); + virtual void setDynamic(Level* level, int x, int y, int z); + public: - virtual void tick(Level *level, int x, int y, int z, Random *random); + virtual void tick(Level* level, int x, int y, int z, Random* random); + private: - bool isFlammable(Level *level, int x, int y, int z); + bool isFlammable(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/LockedChestTile.cpp b/Minecraft.World/Blocks/LockedChestTile.cpp index 9b1f3b21f..4b48cfa97 100644 --- a/Minecraft.World/Blocks/LockedChestTile.cpp +++ b/Minecraft.World/Blocks/LockedChestTile.cpp @@ -2,21 +2,16 @@ #include "../Headers/net.minecraft.world.level.h" #include "LockedChestTile.h" -LockedChestTile::LockedChestTile(int id) : Tile(id, Material::wood) -{ +LockedChestTile::LockedChestTile(int id) : Tile(id, Material::wood) {} + +bool LockedChestTile::mayPlace(Level* level, int x, int y, int z) { + return true; } -bool LockedChestTile::mayPlace(Level *level, int x, int y, int z) -{ - return true; +void LockedChestTile::tick(Level* level, int x, int y, int z, Random* random) { + level->setTile(x, y, z, 0); } -void LockedChestTile::tick(Level *level, int x, int y, int z, Random *random) -{ - level->setTile(x,y,z,0); -} - -void LockedChestTile::registerIcons(IconRegister *iconRegister) -{ - // None +void LockedChestTile::registerIcons(IconRegister* iconRegister) { + // None } \ No newline at end of file diff --git a/Minecraft.World/Blocks/LockedChestTile.h b/Minecraft.World/Blocks/LockedChestTile.h index c093f85ca..0bf1a0b24 100644 --- a/Minecraft.World/Blocks/LockedChestTile.h +++ b/Minecraft.World/Blocks/LockedChestTile.h @@ -3,12 +3,12 @@ class Random; -class LockedChestTile : public Tile -{ - friend class Tile; +class LockedChestTile : public Tile { + friend class Tile; + protected: - LockedChestTile(int id); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void tick(Level *level, int x, int y, int z, Random *random); - void registerIcons(IconRegister *iconRegister); + LockedChestTile(int id); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/Material.cpp b/Minecraft.World/Blocks/Material.cpp index 269ef824b..6daeb824a 100644 --- a/Minecraft.World/Blocks/Material.cpp +++ b/Minecraft.World/Blocks/Material.cpp @@ -4,189 +4,180 @@ #include "GasMaterial.h" #include "LiquidMaterial.h" #include "PortalMaterial.h" -#include "WebMaterial.h"// 4J added, Java version just does a local alteration when instantiating the Material for webs to get the same thing +#include "WebMaterial.h" // 4J added, Java version just does a local alteration when instantiating the Material for webs to get the same thing -Material *Material::air = NULL; -Material *Material::grass = NULL; -Material *Material::dirt = NULL; -Material *Material::wood = NULL; -Material *Material::stone = NULL; -Material *Material::metal = NULL; -Material *Material::heavyMetal = NULL; -Material *Material::water = NULL; -Material *Material::lava = NULL; -Material *Material::leaves = NULL; -Material *Material::plant = NULL; -Material *Material::replaceable_plant = NULL; -Material *Material::sponge = NULL; -Material *Material::cloth = NULL; -Material *Material::fire = NULL; -Material *Material::sand = NULL; -Material *Material::decoration = NULL; -Material *Material::clothDecoration = NULL; -Material *Material::glass = NULL; -Material *Material::buildable_glass = NULL; -Material *Material::explosive = NULL; -Material *Material::coral = NULL; -Material *Material::ice = NULL; -Material *Material::topSnow = NULL; -Material *Material::snow = NULL; -Material *Material::cactus = NULL; -Material *Material::clay = NULL; -Material *Material::vegetable = NULL; -Material *Material::egg = NULL; -Material *Material::portal = NULL; -Material *Material::cake = NULL; -Material *Material::piston = NULL; -Material *Material::web = NULL; +Material* Material::air = NULL; +Material* Material::grass = NULL; +Material* Material::dirt = NULL; +Material* Material::wood = NULL; +Material* Material::stone = NULL; +Material* Material::metal = NULL; +Material* Material::heavyMetal = NULL; +Material* Material::water = NULL; +Material* Material::lava = NULL; +Material* Material::leaves = NULL; +Material* Material::plant = NULL; +Material* Material::replaceable_plant = NULL; +Material* Material::sponge = NULL; +Material* Material::cloth = NULL; +Material* Material::fire = NULL; +Material* Material::sand = NULL; +Material* Material::decoration = NULL; +Material* Material::clothDecoration = NULL; +Material* Material::glass = NULL; +Material* Material::buildable_glass = NULL; +Material* Material::explosive = NULL; +Material* Material::coral = NULL; +Material* Material::ice = NULL; +Material* Material::topSnow = NULL; +Material* Material::snow = NULL; +Material* Material::cactus = NULL; +Material* Material::clay = NULL; +Material* Material::vegetable = NULL; +Material* Material::egg = NULL; +Material* Material::portal = NULL; +Material* Material::cake = NULL; +Material* Material::piston = NULL; +Material* Material::web = NULL; -void Material::staticCtor() -{ - Material::air = new GasMaterial(MaterialColor::none); - Material::grass = new Material(MaterialColor::grass); - Material::dirt = new Material(MaterialColor::dirt); - Material::wood = (new Material(MaterialColor::wood))->flammable(); - Material::stone = (new Material(MaterialColor::stone))->notAlwaysDestroyable(); - Material::metal = (new Material(MaterialColor::metal))->notAlwaysDestroyable(); - Material::heavyMetal = (new Material(MaterialColor::metal))->notAlwaysDestroyable()->notPushable(); - Material::water = (new LiquidMaterial(MaterialColor::water))->destroyOnPush(); - Material::lava = (new LiquidMaterial(MaterialColor::fire))->destroyOnPush(); - Material::leaves = (new Material(MaterialColor::plant))->flammable()->neverBuildable()->destroyOnPush(); - Material::plant = (new DecorationMaterial(MaterialColor::plant))->destroyOnPush(); - Material::replaceable_plant = (new DecorationMaterial(MaterialColor::plant))->flammable()->destroyOnPush()->replaceable(); - Material::sponge = new Material(MaterialColor::cloth); - Material::cloth = (new Material(MaterialColor::cloth))->flammable(); - Material::fire = (new GasMaterial(MaterialColor::none))->destroyOnPush(); - Material::sand = new Material(MaterialColor::sand); - Material::decoration = (new DecorationMaterial(MaterialColor::none))->destroyOnPush(); - Material::clothDecoration = (new DecorationMaterial(MaterialColor::cloth))->flammable(); - Material::glass = (new Material(MaterialColor::none))->neverBuildable()->makeDestroyedByHand(); - Material::buildable_glass = (new Material(MaterialColor::none))->makeDestroyedByHand(); - Material::explosive = (new Material(MaterialColor::fire))->flammable()->neverBuildable(); - Material::coral = (new Material(MaterialColor::plant))->destroyOnPush(); - Material::ice = (new Material(MaterialColor::ice))->neverBuildable()->makeDestroyedByHand(); - Material::topSnow = (new DecorationMaterial(MaterialColor::snow))->replaceable()->neverBuildable()->notAlwaysDestroyable()->destroyOnPush(); - Material::snow = (new Material(MaterialColor::snow))->notAlwaysDestroyable(); - Material::cactus = (new Material(MaterialColor::plant))->neverBuildable()->destroyOnPush(); - Material::clay = (new Material(MaterialColor::clay)); - Material::vegetable = (new Material(MaterialColor::plant))->destroyOnPush(); - Material::egg = ( new Material(MaterialColor::plant))->destroyOnPush(); - Material::portal = (new PortalMaterial(MaterialColor::none))->notPushable(); - Material::cake = (new Material(MaterialColor::none))->destroyOnPush(); - // 4J added WebMaterial, Java version just does a local alteration when instantiating the Material for webs to get the same thing - Material::web = (new WebMaterial(MaterialColor::cloth))->notAlwaysDestroyable()->destroyOnPush(); - Material::piston = (new Material(MaterialColor::stone))->notPushable(); +void Material::staticCtor() { + Material::air = new GasMaterial(MaterialColor::none); + Material::grass = new Material(MaterialColor::grass); + Material::dirt = new Material(MaterialColor::dirt); + Material::wood = (new Material(MaterialColor::wood))->flammable(); + Material::stone = + (new Material(MaterialColor::stone))->notAlwaysDestroyable(); + Material::metal = + (new Material(MaterialColor::metal))->notAlwaysDestroyable(); + Material::heavyMetal = (new Material(MaterialColor::metal)) + ->notAlwaysDestroyable() + ->notPushable(); + Material::water = + (new LiquidMaterial(MaterialColor::water))->destroyOnPush(); + Material::lava = (new LiquidMaterial(MaterialColor::fire))->destroyOnPush(); + Material::leaves = (new Material(MaterialColor::plant)) + ->flammable() + ->neverBuildable() + ->destroyOnPush(); + Material::plant = + (new DecorationMaterial(MaterialColor::plant))->destroyOnPush(); + Material::replaceable_plant = (new DecorationMaterial(MaterialColor::plant)) + ->flammable() + ->destroyOnPush() + ->replaceable(); + Material::sponge = new Material(MaterialColor::cloth); + Material::cloth = (new Material(MaterialColor::cloth))->flammable(); + Material::fire = (new GasMaterial(MaterialColor::none))->destroyOnPush(); + Material::sand = new Material(MaterialColor::sand); + Material::decoration = + (new DecorationMaterial(MaterialColor::none))->destroyOnPush(); + Material::clothDecoration = + (new DecorationMaterial(MaterialColor::cloth))->flammable(); + Material::glass = (new Material(MaterialColor::none)) + ->neverBuildable() + ->makeDestroyedByHand(); + Material::buildable_glass = + (new Material(MaterialColor::none))->makeDestroyedByHand(); + Material::explosive = + (new Material(MaterialColor::fire))->flammable()->neverBuildable(); + Material::coral = (new Material(MaterialColor::plant))->destroyOnPush(); + Material::ice = (new Material(MaterialColor::ice)) + ->neverBuildable() + ->makeDestroyedByHand(); + Material::topSnow = (new DecorationMaterial(MaterialColor::snow)) + ->replaceable() + ->neverBuildable() + ->notAlwaysDestroyable() + ->destroyOnPush(); + Material::snow = + (new Material(MaterialColor::snow))->notAlwaysDestroyable(); + Material::cactus = + (new Material(MaterialColor::plant))->neverBuildable()->destroyOnPush(); + Material::clay = (new Material(MaterialColor::clay)); + Material::vegetable = (new Material(MaterialColor::plant))->destroyOnPush(); + Material::egg = (new Material(MaterialColor::plant))->destroyOnPush(); + Material::portal = (new PortalMaterial(MaterialColor::none))->notPushable(); + Material::cake = (new Material(MaterialColor::none))->destroyOnPush(); + // 4J added WebMaterial, Java version just does a local alteration when + // instantiating the Material for webs to get the same thing + Material::web = (new WebMaterial(MaterialColor::cloth)) + ->notAlwaysDestroyable() + ->destroyOnPush(); + Material::piston = (new Material(MaterialColor::stone))->notPushable(); } -Material::Material(MaterialColor *color) -{ - this->color = color; +Material::Material(MaterialColor* color) { + this->color = color; - // 4J Stu - Default inits - _flammable = false; - _replaceable = false; - _neverBuildable = false; - _isAlwaysDestroyable = true; - pushReaction = 0; - destroyedByHand = false; + // 4J Stu - Default inits + _flammable = false; + _replaceable = false; + _neverBuildable = false; + _isAlwaysDestroyable = true; + pushReaction = 0; + destroyedByHand = false; } -bool Material::isLiquid() -{ - return false; -} +bool Material::isLiquid() { return false; } -bool Material::letsWaterThrough() -{ - return (!isLiquid() && !isSolid()); -} +bool Material::letsWaterThrough() { return (!isLiquid() && !isSolid()); } -bool Material::isSolid() -{ - return true; -} +bool Material::isSolid() { return true; } -bool Material::blocksLight() -{ - return true; -} +bool Material::blocksLight() { return true; } -bool Material::blocksMotion() -{ - return true; -} +bool Material::blocksMotion() { return true; } -Material *Material::neverBuildable() -{ +Material* Material::neverBuildable() { this->_neverBuildable = true; return this; } -Material *Material::notAlwaysDestroyable() -{ - this->_isAlwaysDestroyable = false; - return this; +Material* Material::notAlwaysDestroyable() { + this->_isAlwaysDestroyable = false; + return this; } -Material *Material::flammable() -{ +Material* Material::flammable() { this->_flammable = true; return this; } -bool Material::isFlammable() -{ - return _flammable; -} +bool Material::isFlammable() { return _flammable; } -Material *Material::replaceable() -{ +Material* Material::replaceable() { this->_replaceable = true; return this; } -bool Material::isReplaceable() -{ - return _replaceable; -} +bool Material::isReplaceable() { return _replaceable; } -bool Material::isSolidBlocking() -{ +bool Material::isSolidBlocking() { if (_neverBuildable) return false; return blocksMotion(); } -bool Material::isAlwaysDestroyable() -{ +bool Material::isAlwaysDestroyable() { // these materials will always drop resources when destroyed, regardless - // of player's equipment + // of player's equipment return _isAlwaysDestroyable; } -int Material::getPushReaction() -{ - return pushReaction; +int Material::getPushReaction() { return pushReaction; } + +Material* Material::makeDestroyedByHand() { + this->destroyedByHand = true; + return this; } -Material *Material::makeDestroyedByHand() -{ - this->destroyedByHand = true; - return this; +bool Material::isDestroyedByHand() { return destroyedByHand; } + +Material* Material::destroyOnPush() { + pushReaction = PUSH_DESTROY; + return this; } -bool Material::isDestroyedByHand() -{ - return destroyedByHand; -} - -Material *Material::destroyOnPush() -{ - pushReaction = PUSH_DESTROY; - return this; -} - -Material *Material::notPushable() -{ - pushReaction = PUSH_BLOCK; - return this; +Material* Material::notPushable() { + pushReaction = PUSH_BLOCK; + return this; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/Material.h b/Minecraft.World/Blocks/Material.h index 6e0571cf9..452b4fed2 100644 --- a/Minecraft.World/Blocks/Material.h +++ b/Minecraft.World/Blocks/Material.h @@ -3,90 +3,91 @@ class ChunkRebuildData; -class Material -{ - friend class ChunkRebuildData; +class Material { + friend class ChunkRebuildData; + public: - static Material *air; - static Material *grass; - static Material *dirt; - static Material *wood; - static Material *stone; - static Material *metal; - static Material *heavyMetal; - static Material *water; - static Material *lava; - static Material *leaves; - static Material *plant; - static Material *replaceable_plant; - static Material *sponge; - static Material *cloth; - static Material *fire; - static Material *sand; - static Material *decoration; - static Material *clothDecoration; - static Material *glass; - static Material *buildable_glass; - static Material *explosive; - static Material *coral; - static Material *ice; - static Material *topSnow; - static Material *snow; - static Material *cactus; - static Material *clay; - static Material *vegetable; - static Material *egg; - static Material *portal; - static Material *cake; - static Material *web; - static Material *piston; + static Material* air; + static Material* grass; + static Material* dirt; + static Material* wood; + static Material* stone; + static Material* metal; + static Material* heavyMetal; + static Material* water; + static Material* lava; + static Material* leaves; + static Material* plant; + static Material* replaceable_plant; + static Material* sponge; + static Material* cloth; + static Material* fire; + static Material* sand; + static Material* decoration; + static Material* clothDecoration; + static Material* glass; + static Material* buildable_glass; + static Material* explosive; + static Material* coral; + static Material* ice; + static Material* topSnow; + static Material* snow; + static Material* cactus; + static Material* clay; + static Material* vegetable; + static Material* egg; + static Material* portal; + static Material* cake; + static Material* web; + static Material* piston; - static const int PUSH_NORMAL = 0; - static const int PUSH_DESTROY = 1; - static const int PUSH_BLOCK = 2; // not pushable + static const int PUSH_NORMAL = 0; + static const int PUSH_DESTROY = 1; + static const int PUSH_BLOCK = 2; // not pushable - static void staticCtor(); + static void staticCtor(); private: bool _flammable, _replaceable, _neverBuildable; public: - MaterialColor *color; -private: - bool _isAlwaysDestroyable; - int pushReaction; - bool destroyedByHand; -public: + MaterialColor* color; - Material(MaterialColor *color); - virtual bool isLiquid() ; +private: + bool _isAlwaysDestroyable; + int pushReaction; + bool destroyedByHand; + +public: + Material(MaterialColor* color); + virtual bool isLiquid(); virtual bool letsWaterThrough(); virtual bool isSolid(); virtual bool blocksLight(); virtual bool blocksMotion(); private: - virtual Material *neverBuildable(); + virtual Material* neverBuildable(); + protected: - virtual Material *notAlwaysDestroyable(); - virtual Material *flammable(); + virtual Material* notAlwaysDestroyable(); + virtual Material* flammable(); public: - virtual bool isFlammable(); - virtual Material *replaceable(); - virtual bool isReplaceable(); - virtual bool isSolidBlocking(); - virtual bool isAlwaysDestroyable(); - virtual int getPushReaction(); - + virtual bool isFlammable(); + virtual Material* replaceable(); + virtual bool isReplaceable(); + virtual bool isSolidBlocking(); + virtual bool isAlwaysDestroyable(); + virtual int getPushReaction(); + protected: - Material *makeDestroyedByHand(); + Material* makeDestroyedByHand(); public: - bool isDestroyedByHand(); + bool isDestroyedByHand(); protected: - Material *destroyOnPush(); - Material *notPushable(); + Material* destroyOnPush(); + Material* notPushable(); }; - diff --git a/Minecraft.World/Blocks/MaterialColor.cpp b/Minecraft.World/Blocks/MaterialColor.cpp index a46d4ea19..456c7969a 100644 --- a/Minecraft.World/Blocks/MaterialColor.cpp +++ b/Minecraft.World/Blocks/MaterialColor.cpp @@ -1,46 +1,50 @@ #include "../Platform/stdafx.h" #include "MaterialColor.h" -MaterialColor **MaterialColor::colors; - -MaterialColor *MaterialColor::none = NULL; -MaterialColor *MaterialColor::grass = NULL; -MaterialColor *MaterialColor::sand = NULL; -MaterialColor *MaterialColor::cloth = NULL; -MaterialColor *MaterialColor::fire = NULL; -MaterialColor *MaterialColor::ice = NULL; -MaterialColor *MaterialColor::metal = NULL; -MaterialColor *MaterialColor::plant = NULL; -MaterialColor *MaterialColor::snow = NULL; -MaterialColor *MaterialColor::clay = NULL; -MaterialColor *MaterialColor::dirt = NULL; -MaterialColor *MaterialColor::stone = NULL; -MaterialColor *MaterialColor::water = NULL; -MaterialColor *MaterialColor::wood = NULL; +MaterialColor** MaterialColor::colors; -void MaterialColor::staticCtor() -{ - MaterialColor::colors = new MaterialColor *[16]; +MaterialColor* MaterialColor::none = NULL; +MaterialColor* MaterialColor::grass = NULL; +MaterialColor* MaterialColor::sand = NULL; +MaterialColor* MaterialColor::cloth = NULL; +MaterialColor* MaterialColor::fire = NULL; +MaterialColor* MaterialColor::ice = NULL; +MaterialColor* MaterialColor::metal = NULL; +MaterialColor* MaterialColor::plant = NULL; +MaterialColor* MaterialColor::snow = NULL; +MaterialColor* MaterialColor::clay = NULL; +MaterialColor* MaterialColor::dirt = NULL; +MaterialColor* MaterialColor::stone = NULL; +MaterialColor* MaterialColor::water = NULL; +MaterialColor* MaterialColor::wood = NULL; - MaterialColor::none = new MaterialColor(0, eMinecraftColour_Material_None); - MaterialColor::grass = new MaterialColor(1, eMinecraftColour_Material_Grass); - MaterialColor::sand = new MaterialColor(2, eMinecraftColour_Material_Sand); - MaterialColor::cloth = new MaterialColor(3, eMinecraftColour_Material_Cloth); - MaterialColor::fire = new MaterialColor(4, eMinecraftColour_Material_Fire); - MaterialColor::ice = new MaterialColor(5, eMinecraftColour_Material_Ice); - MaterialColor::metal = new MaterialColor(6, eMinecraftColour_Material_Metal); - MaterialColor::plant = new MaterialColor(7, eMinecraftColour_Material_Plant); - MaterialColor::snow = new MaterialColor(8, eMinecraftColour_Material_Snow); - MaterialColor::clay = new MaterialColor(9, eMinecraftColour_Material_Clay); - MaterialColor::dirt = new MaterialColor(10, eMinecraftColour_Material_Dirt); - MaterialColor::stone = new MaterialColor(11, eMinecraftColour_Material_Stone); - MaterialColor::water = new MaterialColor(12, eMinecraftColour_Material_Water); - MaterialColor::wood = new MaterialColor(13, eMinecraftColour_Material_Wood); +void MaterialColor::staticCtor() { + MaterialColor::colors = new MaterialColor*[16]; + + MaterialColor::none = new MaterialColor(0, eMinecraftColour_Material_None); + MaterialColor::grass = + new MaterialColor(1, eMinecraftColour_Material_Grass); + MaterialColor::sand = new MaterialColor(2, eMinecraftColour_Material_Sand); + MaterialColor::cloth = + new MaterialColor(3, eMinecraftColour_Material_Cloth); + MaterialColor::fire = new MaterialColor(4, eMinecraftColour_Material_Fire); + MaterialColor::ice = new MaterialColor(5, eMinecraftColour_Material_Ice); + MaterialColor::metal = + new MaterialColor(6, eMinecraftColour_Material_Metal); + MaterialColor::plant = + new MaterialColor(7, eMinecraftColour_Material_Plant); + MaterialColor::snow = new MaterialColor(8, eMinecraftColour_Material_Snow); + MaterialColor::clay = new MaterialColor(9, eMinecraftColour_Material_Clay); + MaterialColor::dirt = new MaterialColor(10, eMinecraftColour_Material_Dirt); + MaterialColor::stone = + new MaterialColor(11, eMinecraftColour_Material_Stone); + MaterialColor::water = + new MaterialColor(12, eMinecraftColour_Material_Water); + MaterialColor::wood = new MaterialColor(13, eMinecraftColour_Material_Wood); } -MaterialColor::MaterialColor(int id, eMinecraftColour col) -{ - this->id = id; - this->col = col; - colors[id] = this; +MaterialColor::MaterialColor(int id, eMinecraftColour col) { + this->id = id; + this->col = col; + colors[id] = this; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/MaterialColor.h b/Minecraft.World/Blocks/MaterialColor.h index 70d2be896..213b4744e 100644 --- a/Minecraft.World/Blocks/MaterialColor.h +++ b/Minecraft.World/Blocks/MaterialColor.h @@ -1,31 +1,30 @@ #pragma once -class MaterialColor -{ +class MaterialColor { public: - static MaterialColor **colors; - - static MaterialColor *none; - static MaterialColor *grass; - static MaterialColor *sand; - static MaterialColor *cloth; - static MaterialColor *fire; - static MaterialColor *ice; - static MaterialColor *metal; - static MaterialColor *plant; - static MaterialColor *snow; - static MaterialColor *clay; - static MaterialColor *dirt; - static MaterialColor *stone; - static MaterialColor *water; - static MaterialColor *wood; + static MaterialColor** colors; - static void staticCtor(); + static MaterialColor* none; + static MaterialColor* grass; + static MaterialColor* sand; + static MaterialColor* cloth; + static MaterialColor* fire; + static MaterialColor* ice; + static MaterialColor* metal; + static MaterialColor* plant; + static MaterialColor* snow; + static MaterialColor* clay; + static MaterialColor* dirt; + static MaterialColor* stone; + static MaterialColor* water; + static MaterialColor* wood; + + static void staticCtor(); public: eMinecraftColour col; int id; private: - MaterialColor(int id, eMinecraftColour col); + MaterialColor(int id, eMinecraftColour col); }; diff --git a/Minecraft.World/Blocks/MelonTile.cpp b/Minecraft.World/Blocks/MelonTile.cpp index 4303fd4ce..9e29191d0 100644 --- a/Minecraft.World/Blocks/MelonTile.cpp +++ b/Minecraft.World/Blocks/MelonTile.cpp @@ -7,39 +7,30 @@ const std::wstring MelonTile::TEX = L"melon_side"; const std::wstring MelonTile::TEX_TOP = L"melon_top"; -MelonTile::MelonTile(int id) : Tile(id, Material::vegetable) -{ - iconTop = NULL; +MelonTile::MelonTile(int id) : Tile(id, Material::vegetable) { iconTop = NULL; } + +Icon* MelonTile::getTexture(int face, int data) { + if (face == Facing::UP || face == Facing::DOWN) return iconTop; + return icon; } -Icon *MelonTile::getTexture(int face, int data) -{ - if (face == Facing::UP || face == Facing::DOWN) return iconTop; - return icon; +int MelonTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::melon->id; } -int MelonTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::melon->id; +int MelonTile::getResourceCount(Random* random) { + return 3 + random->nextInt(5); } -int MelonTile::getResourceCount(Random *random) -{ - return 3 + random->nextInt(5); +int MelonTile::getResourceCountForLootBonus(int bonusLevel, Random* random) { + int total = getResourceCount(random) + random->nextInt(1 + bonusLevel); + if (total > 9) { + total = 9; + } + return total; } -int MelonTile::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - int total = getResourceCount(random) + random->nextInt(1 + bonusLevel); - if (total > 9) - { - total = 9; - } - return total; -} - -void MelonTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(TEX); - iconTop = iconRegister->registerIcon(TEX_TOP); +void MelonTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(TEX); + iconTop = iconRegister->registerIcon(TEX_TOP); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/MelonTile.h b/Minecraft.World/Blocks/MelonTile.h index 43b456e64..457b602c1 100644 --- a/Minecraft.World/Blocks/MelonTile.h +++ b/Minecraft.World/Blocks/MelonTile.h @@ -2,23 +2,24 @@ #include "Tile.h" class ChunkRebuildData; -class MelonTile : public Tile -{ - friend class ChunkRebuildData; +class MelonTile : public Tile { + friend class ChunkRebuildData; + private: - static const std::wstring TEX; + static const std::wstring TEX; static const std::wstring TEX_TOP; - Icon *iconTop; + Icon* iconTop; - // 4J Stu - I don't know why this is protected in Java -//protected: + // 4J Stu - I don't know why this is protected in Java + // protected: public: - MelonTile(int id); + MelonTile(int id); + public: - virtual Icon *getTexture(int face, int data); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - void registerIcons(IconRegister *iconRegister); + virtual Icon* getTexture(int face, int data); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/MetalTile.cpp b/Minecraft.World/Blocks/MetalTile.cpp index d9f96bb76..53332bbef 100644 --- a/Minecraft.World/Blocks/MetalTile.cpp +++ b/Minecraft.World/Blocks/MetalTile.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "MetalTile.h" -MetalTile::MetalTile(int id) : Tile(id, Material::metal) -{ -} \ No newline at end of file +MetalTile::MetalTile(int id) : Tile(id, Material::metal) {} \ No newline at end of file diff --git a/Minecraft.World/Blocks/MetalTile.h b/Minecraft.World/Blocks/MetalTile.h index adbb02f89..7d317a627 100644 --- a/Minecraft.World/Blocks/MetalTile.h +++ b/Minecraft.World/Blocks/MetalTile.h @@ -1,8 +1,7 @@ #pragma once #include "Tile.h" -class MetalTile : public Tile -{ +class MetalTile : public Tile { public: - MetalTile(int id); + MetalTile(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/MobSpawner.cpp b/Minecraft.World/Blocks/MobSpawner.cpp index a2be7af97..eed1fe65e 100644 --- a/Minecraft.World/Blocks/MobSpawner.cpp +++ b/Minecraft.World/Blocks/MobSpawner.cpp @@ -20,27 +20,28 @@ const int MobSpawner::MIN_SPAWN_DISTANCE = 24; -TilePos MobSpawner::getRandomPosWithin(Level *level, int cx, int cz) -{ - // 4J Stu - Added 1.2.3 but we don't need it as it was only used to access sections - // Leaving here though to help explain why chunk coords are not passed in rather than full coords - //LevelChunk *chunk = level->getChunk(cx, cz); - int x = cx * 16 + level->random->nextInt(16); - int y = level->random->nextInt(level->getHeight()); - int z = cz * 16 + level->random->nextInt(16); +TilePos MobSpawner::getRandomPosWithin(Level* level, int cx, int cz) { + // 4J Stu - Added 1.2.3 but we don't need it as it was only used to access + // sections Leaving here though to help explain why chunk coords are not + // passed in rather than full coords + // LevelChunk *chunk = level->getChunk(cx, cz); + int x = cx * 16 + level->random->nextInt(16); + int y = level->random->nextInt(level->getHeight()); + int z = cz * 16 + level->random->nextInt(16); - return TilePos(x, y, z); + return TilePos(x, y, z); } #ifdef __PSVITA__ - // AP - See CustomMap.h for an explanation of this - CustomMap MobSpawner::chunksToPoll; +// AP - See CustomMap.h for an explanation of this +CustomMap MobSpawner::chunksToPoll; #else - std::unordered_map MobSpawner::chunksToPoll; +std::unordered_map + MobSpawner::chunksToPoll; #endif -const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFriendlies) -{ +const int MobSpawner::tick(ServerLevel* level, bool spawnEnemies, + bool spawnFriendlies) { #ifndef _CONTENT_PACKAGE #if 0 @@ -94,13 +95,12 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie #endif #endif - if (!spawnEnemies && !spawnFriendlies) - { - return 0; - } - MemSect(20); - chunksToPoll.clear(); - + if (!spawnEnemies && !spawnFriendlies) { + return 0; + } + MemSect(20); + chunksToPoll.clear(); + #if 0 AUTO_VAR(itEnd, level->players.end()); for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++) @@ -117,478 +117,527 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie } } #else - // 4J - rewritten to add chunks interleaved by player, and to add them from the centre outwards. We're going to be - // potentially adding less creatures than the original so that our count stays consistent with number of players added, so - // we want to make sure as best we can that the ones we do add are near the active players - int playerCount = (int)level->players.size(); - int *xx = new int[playerCount]; - int *zz = new int[playerCount]; - for (int i = 0; i < playerCount; i++) - { - std::shared_ptr player = level->players[i]; - xx[i] = Mth::floor(player->x / 16); - zz[i] = Mth::floor(player->z / 16); + // 4J - rewritten to add chunks interleaved by player, and to add them from + // the centre outwards. We're going to be potentially adding less creatures + // than the original so that our count stays consistent with number of + // players added, so we want to make sure as best we can that the ones we do + // add are near the active players + int playerCount = (int)level->players.size(); + int* xx = new int[playerCount]; + int* zz = new int[playerCount]; + for (int i = 0; i < playerCount; i++) { + std::shared_ptr player = level->players[i]; + xx[i] = Mth::floor(player->x / 16); + zz[i] = Mth::floor(player->z / 16); #ifdef __PSVITA__ - chunksToPoll.insert(ChunkPos(xx[i], zz[i] ),false); + chunksToPoll.insert(ChunkPos(xx[i], zz[i]), false); #else - chunksToPoll.insert(std::pair(ChunkPos(xx[i], zz[i] ),false)); + chunksToPoll.insert( + std::pair(ChunkPos(xx[i], zz[i]), false)); #endif - } + } - for( int r = 1; r <= 8; r++ ) - { - for( int l = 0; l < ( r * 2 ) ; l++ ) - { - for( int i = 0; i < playerCount; i++ ) - { - bool edgeChunk = ( r == 8 ); + for (int r = 1; r <= 8; r++) { + for (int l = 0; l < (r * 2); l++) { + for (int i = 0; i < playerCount; i++) { + bool edgeChunk = (r == 8); - // If this chunk isn't at the edge of the region for this player, then always store with a flag of false - // so that if it was at the edge of another player, then this will remove that - if( !edgeChunk ) - { + // If this chunk isn't at the edge of the region for this + // player, then always store with a flag of false so that if it + // was at the edge of another player, then this will remove that + if (!edgeChunk) { #ifdef __PSVITA__ - chunksToPoll.insert(ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r ) ), false); - chunksToPoll.insert(ChunkPos( ( xx[i] + r ) , ( zz[i] - r ) + l ), false); - chunksToPoll.insert(ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r ) ), false); - chunksToPoll.insert(ChunkPos( ( xx[i] - r ) , ( zz[i] + r ) - l ), false); + chunksToPoll.insert(ChunkPos((xx[i] - r) + l, (zz[i] - r)), + false); + chunksToPoll.insert(ChunkPos((xx[i] + r), (zz[i] - r) + l), + false); + chunksToPoll.insert(ChunkPos((xx[i] + r) - l, (zz[i] + r)), + false); + chunksToPoll.insert(ChunkPos((xx[i] - r), (zz[i] + r) - l), + false); #else - chunksToPoll.insert(std::pair(ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r ) ), false)); - chunksToPoll.insert(std::pair(ChunkPos( ( xx[i] + r ) , ( zz[i] - r ) + l ), false)); - chunksToPoll.insert(std::pair(ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r ) ), false)); - chunksToPoll.insert(std::pair(ChunkPos( ( xx[i] - r ) , ( zz[i] + r ) - l ), false)); + chunksToPoll.insert(std::pair( + ChunkPos((xx[i] - r) + l, (zz[i] - r)), false)); + chunksToPoll.insert(std::pair( + ChunkPos((xx[i] + r), (zz[i] - r) + l), false)); + chunksToPoll.insert(std::pair( + ChunkPos((xx[i] + r) - l, (zz[i] + r)), false)); + chunksToPoll.insert(std::pair( + ChunkPos((xx[i] - r), (zz[i] + r) - l), false)); #endif - } - else - { + } else { #ifdef __PSVITA__ - ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); - if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); - if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); - if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); - if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); + ChunkPos cp = ChunkPos((xx[i] - r) + l, (zz[i] - r)); + if (chunksToPoll.find(cp)) chunksToPoll.insert(cp, true); + cp = ChunkPos((xx[i] + r), (zz[i] - r) + l); + if (chunksToPoll.find(cp)) chunksToPoll.insert(cp, true); + cp = ChunkPos((xx[i] + r) - l, (zz[i] + r)); + if (chunksToPoll.find(cp)) chunksToPoll.insert(cp, true); + cp = ChunkPos((xx[i] - r), (zz[i] + r) - l); + if (chunksToPoll.find(cp)) chunksToPoll.insert(cp, true); #else - ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); - if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair(cp, true)); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); - if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair(cp, true)); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); - if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair(cp, true)); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); - if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair(cp, true)); + ChunkPos cp = ChunkPos((xx[i] - r) + l, (zz[i] - r)); + if (chunksToPoll.find(cp) == chunksToPoll.end()) + chunksToPoll.insert( + std::pair(cp, true)); + cp = ChunkPos((xx[i] + r), (zz[i] - r) + l); + if (chunksToPoll.find(cp) == chunksToPoll.end()) + chunksToPoll.insert( + std::pair(cp, true)); + cp = ChunkPos((xx[i] + r) - l, (zz[i] + r)); + if (chunksToPoll.find(cp) == chunksToPoll.end()) + chunksToPoll.insert( + std::pair(cp, true)); + cp = ChunkPos((xx[i] - r), (zz[i] + r) - l); + if (chunksToPoll.find(cp) == chunksToPoll.end()) + chunksToPoll.insert( + std::pair(cp, true)); #endif - - } - } - } - } - delete [] xx; - delete [] zz; + } + } + } + } + delete[] xx; + delete[] zz; #endif - MemSect(0); - int count = 0; - MemSect(31); - Pos *spawnPos = level->getSharedSpawnPos(); - MemSect(0); - - for (unsigned int i = 0; i < MobCategory::values.length; i++) - { - MobCategory *mobCategory = MobCategory::values[i]; - if ((mobCategory->isFriendly() && !spawnFriendlies) || (!mobCategory->isFriendly() && !spawnEnemies)) - { - continue; - } + MemSect(0); + int count = 0; + MemSect(31); + Pos* spawnPos = level->getSharedSpawnPos(); + MemSect(0); - // 4J - this is now quite different to the java version. We just have global max counts for the level whereas the original has a max per chunk that - // scales with the number of chunks to be polled. - int categoryCount = level->countInstanceOf( mobCategory->getEnumBaseClass(), mobCategory->isSingleType()); - if( categoryCount >= mobCategory->getMaxInstancesPerLevel()) - { - continue; - } + for (unsigned int i = 0; i < MobCategory::values.length; i++) { + MobCategory* mobCategory = MobCategory::values[i]; + if ((mobCategory->isFriendly() && !spawnFriendlies) || + (!mobCategory->isFriendly() && !spawnEnemies)) { + continue; + } + + // 4J - this is now quite different to the java version. We just have + // global max counts for the level whereas the original has a max per + // chunk that scales with the number of chunks to be polled. + int categoryCount = level->countInstanceOf( + mobCategory->getEnumBaseClass(), mobCategory->isSingleType()); + if (categoryCount >= mobCategory->getMaxInstancesPerLevel()) { + continue; + } #ifdef __PSVITA__ - for( int i = 0;i < chunksToPoll.end();i += 1 ) - { - SCustomMapNode *it = chunksToPoll.get(i); + for (int i = 0; i < chunksToPoll.end(); i += 1) { + SCustomMapNode* it = chunksToPoll.get(i); #else - AUTO_VAR(itEndCTP, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCTP; it++) - { + AUTO_VAR(itEndCTP, chunksToPoll.end()); + for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCTP; it++) { #endif - if( it->second ) - { - // don't add mobs to edge chunks, to prevent adding mobs - // "outside" of the active playground - continue; - } - ChunkPos *cp = (ChunkPos *) (&it->first); + if (it->second) { + // don't add mobs to edge chunks, to prevent adding mobs + // "outside" of the active playground + continue; + } + ChunkPos* cp = (ChunkPos*)(&it->first); - // 4J - don't let this actually create/load a chunk that isn't here already - we'll let the normal updateDirtyChunks etc. processes do that, so it can happen on another thread - if( !level->hasChunk(cp->x,cp->z) ) continue; + // 4J - don't let this actually create/load a chunk that isn't here + // already - we'll let the normal updateDirtyChunks etc. processes + // do that, so it can happen on another thread + if (!level->hasChunk(cp->x, cp->z)) continue; - TilePos start = getRandomPosWithin(level, cp->x, cp->z); - int xStart = start.x; - int yStart = start.y; - int zStart = start.z; + TilePos start = getRandomPosWithin(level, cp->x, cp->z); + int xStart = start.x; + int yStart = start.y; + int zStart = start.z; - if (level->isSolidBlockingTile(xStart, yStart, zStart)) continue; - if (level->getMaterial(xStart, yStart, zStart) != mobCategory->getSpawnPositionMaterial()) continue; - int clusterSize = 0; + if (level->isSolidBlockingTile(xStart, yStart, zStart)) continue; + if (level->getMaterial(xStart, yStart, zStart) != + mobCategory->getSpawnPositionMaterial()) + continue; + int clusterSize = 0; - for (int dd = 0; dd < 3; dd++) - { - int x = xStart; - int y = yStart; - int z = zStart; - int ss = 6; + for (int dd = 0; dd < 3; dd++) { + int x = xStart; + int y = yStart; + int z = zStart; + int ss = 6; - Biome::MobSpawnerData *currentMobType = NULL; + Biome::MobSpawnerData* currentMobType = NULL; - for (int ll = 0; ll < 4; ll++) - { - x += level->random->nextInt(ss) - level->random->nextInt(ss); - y += level->random->nextInt(1) - level->random->nextInt(1); - z += level->random->nextInt(ss) - level->random->nextInt(ss); - // int y = heightMap[x + z * w] + 1; + for (int ll = 0; ll < 4; ll++) { + x += + level->random->nextInt(ss) - level->random->nextInt(ss); + y += level->random->nextInt(1) - level->random->nextInt(1); + z += + level->random->nextInt(ss) - level->random->nextInt(ss); + // int y = heightMap[x + z * w] + 1; - // 4J - don't let this actually create/load a chunk that isn't here already - we'll let the normal updateDirtyChunks etc. processes do that, so it can happen on another thread - if( !level->hasChunkAt( x, y, z ) ) continue; + // 4J - don't let this actually create/load a chunk that + // isn't here already - we'll let the normal + // updateDirtyChunks etc. processes do that, so it can + // happen on another thread + if (!level->hasChunkAt(x, y, z)) continue; - if (isSpawnPositionOk(mobCategory, level, x, y, z)) - { - float xx = x + 0.5f; - float yy = (float) y; - float zz = z + 0.5f; - if (level->getNearestPlayer(xx, yy, zz, MIN_SPAWN_DISTANCE) != NULL) - { - continue; - } - else - { - float xd = xx - spawnPos->x; - float yd = yy - spawnPos->y; - float zd = zz - spawnPos->z; - float sd = xd * xd + yd * yd + zd * zd; - if (sd < MIN_SPAWN_DISTANCE * MIN_SPAWN_DISTANCE) - { - continue; - } - } - - if (currentMobType == NULL) - { - currentMobType = level->getRandomMobSpawnAt(mobCategory, x, y, z); - if (currentMobType == NULL) - { - break; - } + if (isSpawnPositionOk(mobCategory, level, x, y, z)) { + float xx = x + 0.5f; + float yy = (float)y; + float zz = z + 0.5f; + if (level->getNearestPlayer( + xx, yy, zz, MIN_SPAWN_DISTANCE) != NULL) { + continue; + } else { + float xd = xx - spawnPos->x; + float yd = yy - spawnPos->y; + float zd = zz - spawnPos->z; + float sd = xd * xd + yd * yd + zd * zd; + if (sd < MIN_SPAWN_DISTANCE * MIN_SPAWN_DISTANCE) { + continue; } + } - std::shared_ptr mob; - // 4J - removed try/catch -// try -// { - MemSect(29); - //mob = type.mobClass.getConstructor(Level.class).newInstance(level); - mob = std::dynamic_pointer_cast(EntityIO::newByEnumType(currentMobType->mobClass, level)); - MemSect(0); -// } -// catch (exception e) -// { -// // TODO 4J We can't print a stack trace, and the newInstance function doesn't throw an exception just now anyway -// //e.printStackTrace(); -// return count; -// } + if (currentMobType == NULL) { + currentMobType = level->getRandomMobSpawnAt( + mobCategory, x, y, z); + if (currentMobType == NULL) { + break; + } + } - // 4J - If it is an animal or a monster, don't let any one type of mob represent more than 50% of the total amount of these things. This - // was added initially to stop flat lands being totally populated with slimes but seems like a generally good rule. - eINSTANCEOF mobType = mob->GetType(); + std::shared_ptr mob; + // 4J - removed try/catch + // try + // { + MemSect(29); + // mob = + // type.mobClass.getConstructor(Level.class).newInstance(level); + mob = std::dynamic_pointer_cast( + EntityIO::newByEnumType(currentMobType->mobClass, + level)); + MemSect(0); + // } + // catch + //(exception e) + // { + // // + //TODO 4J We can't print a stack trace, and the + //newInstance function doesn't throw an exception just + //now anyway + // //e.printStackTrace(); + // return + //count; + // } - if( ( mobType & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK ) || ( mobType & eTYPE_MONSTER ) ) - { - // even more special rule for ghasts, because filling up the nether with 25 of them is a bit unpleasant. In the java version they are - // only limited by the fact that the world fills up with pig zombies (the only other type of enemy mob in the nether) before them - they - // aren't actually even counted properly themselves - if( mobType == eTYPE_GHAST ) - { - if( level->countInstanceOf(mobType, true) >= 4 ) continue; - } - else if( mobType == eTYPE_ENDERMAN && level->dimension->id == 1 ) - { - // Special rule for the end, as we only have Endermen (plus the dragon). Increase the spawnable counts based on level difficulty - int maxEndermen = mobCategory->getMaxInstancesPerLevel(); + // 4J - If it is an animal or a monster, don't let any + // one type of mob represent more than 50% of the total + // amount of these things. This was added initially to + // stop flat lands being totally populated with slimes + // but seems like a generally good rule. + eINSTANCEOF mobType = mob->GetType(); - if( level->difficulty == Difficulty::NORMAL ) - { - maxEndermen -= mobCategory->getMaxInstancesPerLevel()/4; - } - else if( level->difficulty <= Difficulty::EASY) - { - maxEndermen -= mobCategory->getMaxInstancesPerLevel()/2; - } + if ((mobType & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) || + (mobType & eTYPE_MONSTER)) { + // even more special rule for ghasts, because + // filling up the nether with 25 of them is a bit + // unpleasant. In the java version they are only + // limited by the fact that the world fills up with + // pig zombies (the only other type of enemy mob in + // the nether) before them - they aren't actually + // even counted properly themselves + if (mobType == eTYPE_GHAST) { + if (level->countInstanceOf(mobType, true) >= 4) + continue; + } else if (mobType == eTYPE_ENDERMAN && + level->dimension->id == 1) { + // Special rule for the end, as we only have + // Endermen (plus the dragon). Increase the + // spawnable counts based on level difficulty + int maxEndermen = + mobCategory->getMaxInstancesPerLevel(); - if( level->countInstanceOf(mobType, true) >= maxEndermen ) continue; - } - else if( level->countInstanceOf(mobType, true) >= ( mobCategory->getMaxInstancesPerLevel() / 2 ) ) continue; - } + if (level->difficulty == Difficulty::NORMAL) { + maxEndermen -= + mobCategory->getMaxInstancesPerLevel() / + 4; + } else if (level->difficulty <= + Difficulty::EASY) { + maxEndermen -= + mobCategory->getMaxInstancesPerLevel() / + 2; + } - mob->moveTo(xx, yy, zz, level->random->nextFloat() * 360, 0); + if (level->countInstanceOf(mobType, true) >= + maxEndermen) + continue; + } else if (level->countInstanceOf(mobType, true) >= + (mobCategory->getMaxInstancesPerLevel() / + 2)) + continue; + } - if (mob->canSpawn()) - { - // 4J - check if we are going to despawn straight away too, and don't add if we will - otherwise we'll be sending - // network packets for adding & removal that we don't need - mob->checkDespawn(); - if( !mob->removed ) - { - clusterSize++; - categoryCount++; - mob->setDespawnProtected(); // 4J added - default to protected against despawning - level->addEntity(mob); - finalizeMobSettings(mob, level, xx, yy, zz); - mob->finalizeMobSpawn(); - // 4J - change here so that we can't ever make more than the desired amount of entities in each priority. In the original java version - // depending on the random spawn positions being considered the only limit as to the number of entities created per category is the number - // of chunks to poll. - if (categoryCount >= mobCategory->getMaxInstancesPerLevel() ) goto categoryLoop; - if (clusterSize >= mob->getMaxSpawnClusterSize()) goto chunkLoop; - } - } - count += clusterSize; - } - } - } - chunkLoop: continue; - } - categoryLoop: continue; - } - delete spawnPos; + mob->moveTo(xx, yy, zz, + level->random->nextFloat() * 360, 0); - return count; + if (mob->canSpawn()) { + // 4J - check if we are going to despawn straight + // away too, and don't add if we will - otherwise + // we'll be sending network packets for adding & + // removal that we don't need + mob->checkDespawn(); + if (!mob->removed) { + clusterSize++; + categoryCount++; + mob->setDespawnProtected(); // 4J added - + // default to + // protected + // against + // despawning + level->addEntity(mob); + finalizeMobSettings(mob, level, xx, yy, zz); + mob->finalizeMobSpawn(); + // 4J - change here so that we can't ever make + // more than the desired amount of entities in + // each priority. In the original java version + // depending on the random spawn positions being + // considered the only limit as to the number of + // entities created per category is the number + // of chunks to poll. + if (categoryCount >= + mobCategory->getMaxInstancesPerLevel()) + goto categoryLoop; + if (clusterSize >= + mob->getMaxSpawnClusterSize()) + goto chunkLoop; + } + } + count += clusterSize; + } + } + } + chunkLoop: + continue; + } + categoryLoop: + continue; + } + delete spawnPos; + + return count; } -bool MobSpawner::isSpawnPositionOk(MobCategory *category, Level *level, int x, int y, int z) -{ - // 4J - don't let this actually create/load a chunk that isn't here already - we'll let the normal updateDirtyChunks etc. processes do that, so it can happen on another thread - if( !level->hasChunkAt(x, y, z ) ) return false; +bool MobSpawner::isSpawnPositionOk(MobCategory* category, Level* level, int x, + int y, int z) { + // 4J - don't let this actually create/load a chunk that isn't here already + // - we'll let the normal updateDirtyChunks etc. processes do that, so it + // can happen on another thread + if (!level->hasChunkAt(x, y, z)) return false; #ifdef __PSVITA__ - // AP - added this for Vita. Make sure a new spawn point has 2 chunks around it. This will make sure monsters don't keep getting spawned on the edge preventing other new monsters - // from being spawned - int r = 32; - if( !level->hasChunksAt(x - r, 0, z - r, x + r, 0, z + r)) - { - return false; - } + // AP - added this for Vita. Make sure a new spawn point has 2 chunks around + // it. This will make sure monsters don't keep getting spawned on the edge + // preventing other new monsters from being spawned + int r = 32; + if (!level->hasChunksAt(x - r, 0, z - r, x + r, 0, z + r)) { + return false; + } #endif - if (category->getSpawnPositionMaterial() == Material::water) - { - // 4J - changed to spawn water things only in deep water - int yo = 0; - int liquidCount = 0; - - while( ( y - yo ) >= 0 && ( yo < 5 ) ) - { - if( level->getMaterial(x, y - yo, z)->isLiquid() ) liquidCount++; - yo++; - } + if (category->getSpawnPositionMaterial() == Material::water) { + // 4J - changed to spawn water things only in deep water + int yo = 0; + int liquidCount = 0; - // 4J - Sometimes deep water could be just a waterfall, so check that it's wide as well - bool inEnoughWater = false; - if( liquidCount == 5 ) - { - if( level->getMaterial(x+5, y, z)->isLiquid() && - level->getMaterial(x-5, y, z)->isLiquid() && - level->getMaterial(x, y, z+5)->isLiquid() && - level->getMaterial(x, y, z-5)->isLiquid() - ) - { - inEnoughWater = true; - } - } + while ((y - yo) >= 0 && (yo < 5)) { + if (level->getMaterial(x, y - yo, z)->isLiquid()) liquidCount++; + yo++; + } - return inEnoughWater && !level->isSolidBlockingTile(x, y + 1, z); - } - else - { - if (!level->isTopSolidBlocking(x, y - 1, z)) return false; - int tt = level->getTile(x, y - 1, z); - return tt != Tile::unbreakable_Id && !level->isSolidBlockingTile(x, y, z) && !level->getMaterial(x, y, z)->isLiquid() && !level->isSolidBlockingTile(x, y + 1, z); - } + // 4J - Sometimes deep water could be just a waterfall, so check that + // it's wide as well + bool inEnoughWater = false; + if (liquidCount == 5) { + if (level->getMaterial(x + 5, y, z)->isLiquid() && + level->getMaterial(x - 5, y, z)->isLiquid() && + level->getMaterial(x, y, z + 5)->isLiquid() && + level->getMaterial(x, y, z - 5)->isLiquid()) { + inEnoughWater = true; + } + } + + return inEnoughWater && !level->isSolidBlockingTile(x, y + 1, z); + } else { + if (!level->isTopSolidBlocking(x, y - 1, z)) return false; + int tt = level->getTile(x, y - 1, z); + return tt != Tile::unbreakable_Id && + !level->isSolidBlockingTile(x, y, z) && + !level->getMaterial(x, y, z)->isLiquid() && + !level->isSolidBlockingTile(x, y + 1, z); + } } - -void MobSpawner::finalizeMobSettings(std::shared_ptr mob, Level *level, float xx, float yy, float zz) -{ - if (std::dynamic_pointer_cast( mob ) != NULL && level->random->nextInt(100) == 0) - { - std::shared_ptr skeleton = std::shared_ptr( new Skeleton(level) ); - skeleton->moveTo(xx, yy, zz, mob->yRot, 0); - level->addEntity(skeleton); - skeleton->ride(mob); - } - else if (std::dynamic_pointer_cast( mob ) != NULL) - { - (std::dynamic_pointer_cast( mob ))->setColor(Sheep::getSheepColor(level->random)); - } - else if (std::dynamic_pointer_cast( mob ) != NULL) - { - if (level->random->nextInt(7) == 0) - { - for (int kitten = 0; kitten < 2; kitten++) - { - std::shared_ptr ozelot = std::shared_ptr(new Ozelot(level)); - ozelot->moveTo(xx, yy, zz, mob->yRot, 0); - ozelot->setAge(-20 * 60 * 20); - level->addEntity(ozelot); - } - } - } +void MobSpawner::finalizeMobSettings(std::shared_ptr mob, Level* level, + float xx, float yy, float zz) { + if (std::dynamic_pointer_cast(mob) != NULL && + level->random->nextInt(100) == 0) { + std::shared_ptr skeleton = + std::shared_ptr(new Skeleton(level)); + skeleton->moveTo(xx, yy, zz, mob->yRot, 0); + level->addEntity(skeleton); + skeleton->ride(mob); + } else if (std::dynamic_pointer_cast(mob) != NULL) { + (std::dynamic_pointer_cast(mob)) + ->setColor(Sheep::getSheepColor(level->random)); + } else if (std::dynamic_pointer_cast(mob) != NULL) { + if (level->random->nextInt(7) == 0) { + for (int kitten = 0; kitten < 2; kitten++) { + std::shared_ptr ozelot = + std::shared_ptr(new Ozelot(level)); + ozelot->moveTo(xx, yy, zz, mob->yRot, 0); + ozelot->setAge(-20 * 60 * 20); + level->addEntity(ozelot); + } + } + } } +// 4J Stu TODO This was an array of Class type. I haven't made a base Class type +// yet, but don't need to as this can be an array of Mob type? +eINSTANCEOF MobSpawner::bedEnemies[bedEnemyCount] = {eTYPE_SPIDER, eTYPE_ZOMBIE, + eTYPE_SKELETON}; -// 4J Stu TODO This was an array of Class type. I haven't made a base Class type yet, but don't need to -// as this can be an array of Mob type? -eINSTANCEOF MobSpawner::bedEnemies[bedEnemyCount] = { - eTYPE_SPIDER, eTYPE_ZOMBIE, eTYPE_SKELETON -}; +bool MobSpawner::attackSleepingPlayers( + Level* level, std::vector >* players) { + bool somebodyWokeUp = false; + PathFinder finder = PathFinder(level, true, false, false, true); -bool MobSpawner::attackSleepingPlayers(Level *level, std::vector > *players) -{ + AUTO_VAR(itEnd, players->end()); + for (AUTO_VAR(it, players->begin()); it != itEnd; it++) { + std::shared_ptr player = (*it); - bool somebodyWokeUp = false; + bool nextPlayer = false; - PathFinder finder = PathFinder(level, true, false, false, true); + for (int attemptCount = 0; attemptCount < 20 && !nextPlayer; + attemptCount++) { + // limit position within the range of the player + int x = Mth::floor(player->x) + level->random->nextInt(32) - + level->random->nextInt(32); + int z = Mth::floor(player->z) + level->random->nextInt(32) - + level->random->nextInt(32); + int yStart = Mth::floor(player->y) + level->random->nextInt(16) - + level->random->nextInt(16); + if (yStart < 1) { + yStart = 1; + } else if (yStart > Level::maxBuildHeight) { + yStart = Level::maxBuildHeight; + } - AUTO_VAR(itEnd, players->end()); - for (AUTO_VAR(it, players->begin()); it != itEnd; it++) - { - std::shared_ptr player = (*it); + { + int type = level->random->nextInt(bedEnemyCount); + int y = yStart; - bool nextPlayer = false; + while (y > 2 && !level->isTopSolidBlocking(x, y - 1, z)) { + y--; + } - for (int attemptCount = 0; attemptCount < 20 && !nextPlayer; attemptCount++)\ - { + while (!isSpawnPositionOk((MobCategory*)MobCategory::monster, + level, x, y, z) && + y < (yStart + 16) && y < Level::maxBuildHeight) { + y++; + } + if (y >= (yStart + 16) || y >= Level::maxBuildHeight) { + y = yStart; + continue; + } else { + float xx = x + 0.5f; + float yy = (float)y; + float zz = z + 0.5f; + std::shared_ptr mob; + // 4J - removed try/catch + // try + // { + // mob = + // classes[type].getConstructor(Level.class).newInstance(level); + // 4J - there was a classes array here which duplicated the + // bedEnemies array but have removed it + mob = std::dynamic_pointer_cast( + EntityIO::newByEnumType(bedEnemies[type], level)); + // } + // catch (exception e) + // { + // // TODO 4J Stu - + //We can't print a stack trace, and newInstance doesn't + //currently throw an exception anyway + // //e.printStackTrace(); + // return + //somebodyWokeUp; + // } - // limit position within the range of the player - int x = Mth::floor(player->x) + level->random->nextInt(32) - level->random->nextInt(32); - int z = Mth::floor(player->z) + level->random->nextInt(32) - level->random->nextInt(32); - int yStart = Mth::floor(player->y) + level->random->nextInt(16) - level->random->nextInt(16); - if (yStart < 1) - { - yStart = 1; - } - else if (yStart > Level::maxBuildHeight) - { - yStart = Level::maxBuildHeight; - } + // System.out.println("Placing night mob"); + mob->moveTo(xx, yy, zz, level->random->nextFloat() * 360, + 0); + // check if the mob can spawn at this location + if (!mob->canSpawn()) { + continue; + } + Pos* bedPos = BedTile::findStandUpPosition( + level, Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z), 1); + if (bedPos == NULL) { + // an unlikely case where the bed is + // completely blocked + bedPos = new Pos(x, y + 1, z); + } - { - int type = level->random->nextInt(bedEnemyCount); - int y = yStart; + // 4J Stu - TU-1 hotfix + // Fix for #13152 - If the player sleeps in a bed next to a + // wall in an enclosed, well lit area they will be awoken by + // a monster The pathfinder should attempt to get close to + // the position that we will move the mob to, instead of the + // player who could be next to a wall. Otherwise the paths + // gets to the other side of the the wall, then moves the + // mob inside the building + // Path *findPath = finder.findPath(mob.get(), + // player.get(), 32.0f); + Path* findPath = finder.findPath( + mob.get(), bedPos->x, bedPos->y, bedPos->z, 32.0f); + if (findPath != NULL && findPath->getSize() > 1) { + Node* last = findPath->last(); - while (y > 2 && !level->isTopSolidBlocking(x, y - 1, z)) - { - y--; - } + if (abs(last->x - bedPos->x) < 1.5 && + abs(last->z - bedPos->z) < 1.5 && + abs(last->y - bedPos->y) < 1.5) { + // System.out.println("Found path!"); - while (!isSpawnPositionOk( (MobCategory *) MobCategory::monster, level, x, y, z) && y < (yStart + 16) && y < Level::maxBuildHeight) - { - y++; - } - if (y >= (yStart + 16) || y >= Level::maxBuildHeight) - { - y = yStart; - continue; - } - else - { - float xx = x + 0.5f; - float yy = (float) y; - float zz = z + 0.5f; + mob->moveTo(bedPos->x + 0.5f, bedPos->y, + bedPos->z + 0.5f, 0, 0); + // the mob would maybe not be able to + // spawn here, but we ignore that now (we assume + // it walked here) + { + level->addEntity(mob); + finalizeMobSettings( + mob, level, bedPos->x + 0.5f, + (float)bedPos->y, bedPos->z + 0.5f); + mob->finalizeMobSpawn(); + player->stopSleepInBed(true, false, false); + // play a sound effect to scare the player + mob->playAmbientSound(); + somebodyWokeUp = true; + nextPlayer = true; + } + } + delete findPath; + } + delete bedPos; + } + } + } + } - std::shared_ptr mob; -// 4J - removed try/catch -// try -// { - //mob = classes[type].getConstructor(Level.class).newInstance(level); - // 4J - there was a classes array here which duplicated the bedEnemies array but have removed it - mob = std::dynamic_pointer_cast(EntityIO::newByEnumType(bedEnemies[type], level )); -// } -// catch (exception e) -// { -// // TODO 4J Stu - We can't print a stack trace, and newInstance doesn't currently throw an exception anyway -// //e.printStackTrace(); -// return somebodyWokeUp; -// } - - // System.out.println("Placing night mob"); - mob->moveTo(xx, yy, zz, level->random->nextFloat() * 360, 0); - // check if the mob can spawn at this location - if (!mob->canSpawn()) - { - continue; - } - Pos *bedPos = BedTile::findStandUpPosition(level, Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z), 1); - if (bedPos == NULL) - { - // an unlikely case where the bed is - // completely blocked - bedPos = new Pos(x, y + 1, z); - } - - // 4J Stu - TU-1 hotfix - // Fix for #13152 - If the player sleeps in a bed next to a wall in an enclosed, well lit area they will be awoken by a monster - // The pathfinder should attempt to get close to the position that we will move the mob to, - // instead of the player who could be next to a wall. Otherwise the paths gets to the other - // side of the the wall, then moves the mob inside the building - //Path *findPath = finder.findPath(mob.get(), player.get(), 32.0f); - Path *findPath = finder.findPath(mob.get(), bedPos->x, bedPos->y, bedPos->z, 32.0f); - if (findPath != NULL && findPath->getSize() > 1) - { - Node *last = findPath->last(); - - if (abs(last->x - bedPos->x) < 1.5 && abs(last->z - bedPos->z) < 1.5 && abs(last->y - bedPos->y) < 1.5) - { - // System.out.println("Found path!"); - - mob->moveTo(bedPos->x + 0.5f, bedPos->y, bedPos->z + 0.5f, 0, 0); - // the mob would maybe not be able to - // spawn here, but we ignore that now (we assume - // it walked here) - { - level->addEntity(mob); - finalizeMobSettings(mob, level, bedPos->x + 0.5f, (float) bedPos->y, bedPos->z + 0.5f); - mob->finalizeMobSpawn(); - player->stopSleepInBed(true, false, false); - // play a sound effect to scare the player - mob->playAmbientSound(); - somebodyWokeUp = true; - nextPlayer = true; - } - } - delete findPath; - } - delete bedPos; - } - } - } - } - - - return somebodyWokeUp; + return somebodyWokeUp; } -void MobSpawner::postProcessSpawnMobs(Level *level, Biome *biome, int xo, int zo, int cellWidth, int cellHeight, Random *random) -{ - // 4J - not for our version. Creates a few too many mobs. +void MobSpawner::postProcessSpawnMobs(Level* level, Biome* biome, int xo, + int zo, int cellWidth, int cellHeight, + Random* random) { + // 4J - not for our version. Creates a few too many mobs. #if 0 std::vector *mobs = biome->getMobs(MobCategory::creature); if (mobs->empty()) diff --git a/Minecraft.World/Blocks/MobSpawner.h b/Minecraft.World/Blocks/MobSpawner.h index cadd3f673..5a5659038 100644 --- a/Minecraft.World/Blocks/MobSpawner.h +++ b/Minecraft.World/Blocks/MobSpawner.h @@ -9,38 +9,43 @@ class Player; class Level; -class MobSpawner -{ +class MobSpawner { private: - static const int MIN_SPAWN_DISTANCE; + static const int MIN_SPAWN_DISTANCE; protected: - static TilePos getRandomPosWithin(Level *level, int cx, int cz); + static TilePos getRandomPosWithin(Level* level, int cx, int cz); private: #ifdef __PSVITA__ - // AP - See CustomMap.h for an explanation of this - static CustomMap chunksToPoll; + // AP - See CustomMap.h for an explanation of this + static CustomMap chunksToPoll; #else - static std::unordered_map chunksToPoll; + static std::unordered_map + chunksToPoll; #endif public: - static const int tick(ServerLevel *level, bool spawnEnemies, bool spawnFriendlies); - static bool isSpawnPositionOk(MobCategory *category, Level *level, int x, int y, int z); + static const int tick(ServerLevel* level, bool spawnEnemies, + bool spawnFriendlies); + static bool isSpawnPositionOk(MobCategory* category, Level* level, int x, + int y, int z); private: - static void finalizeMobSettings(std::shared_ptr mob, Level *level, float xx, float yy, float zz); + static void finalizeMobSettings(std::shared_ptr mob, Level* level, + float xx, float yy, float zz); protected: - // 4J Stu TODO This was an array of Class type. I haven't made a base Class type yet, but don't need to - // as this can be an array of Mob type? - static const int bedEnemyCount = 3; - static eINSTANCEOF bedEnemies[bedEnemyCount]; - + // 4J Stu TODO This was an array of Class type. I haven't made a base Class + // type yet, but don't need to as this can be an array of Mob type? + static const int bedEnemyCount = 3; + static eINSTANCEOF bedEnemies[bedEnemyCount]; public: - static bool attackSleepingPlayers(Level *level, std::vector > *players); + static bool attackSleepingPlayers( + Level* level, std::vector >* players); - static void postProcessSpawnMobs(Level *level, Biome *biome, int xo, int zo, int cellWidth, int cellHeight, Random *random); + static void postProcessSpawnMobs(Level* level, Biome* biome, int xo, int zo, + int cellWidth, int cellHeight, + Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/MobSpawnerTile.cpp b/Minecraft.World/Blocks/MobSpawnerTile.cpp index 2ba906ffe..36d3c41e7 100644 --- a/Minecraft.World/Blocks/MobSpawnerTile.cpp +++ b/Minecraft.World/Blocks/MobSpawnerTile.cpp @@ -3,47 +3,34 @@ #include "../Headers/net.minecraft.world.level.tile.entity.h" #include "MobSpawnerTile.h" -MobSpawnerTile::MobSpawnerTile(int id) : EntityTile(id, Material::stone, false) -{ +MobSpawnerTile::MobSpawnerTile(int id) + : EntityTile(id, Material::stone, false) {} + +std::shared_ptr MobSpawnerTile::newTileEntity(Level* level) { + return std::shared_ptr(new MobSpawnerTileEntity()); } -std::shared_ptr MobSpawnerTile::newTileEntity(Level *level) -{ - return std::shared_ptr( new MobSpawnerTileEntity() ); +int MobSpawnerTile::getResource(int data, Random* random, + int playerBonusLevel) { + return 0; } -int MobSpawnerTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; +int MobSpawnerTile::getResourceCount(Random* random) { return 0; } + +bool MobSpawnerTile::isSolidRender(bool isServerLevel) { return false; } + +bool MobSpawnerTile::blocksLight() { return false; } + +void MobSpawnerTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); + + // also spawn experience if the block is broken + { + int magicCount = + 15 + level->random->nextInt(15) + level->random->nextInt(15); + popExperience(level, x, y, z, magicCount); + } } -int MobSpawnerTile::getResourceCount(Random *random) -{ - return 0; -} - -bool MobSpawnerTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -bool MobSpawnerTile::blocksLight() -{ - return false; -} - -void MobSpawnerTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); - - // also spawn experience if the block is broken - { - int magicCount = 15 + level->random->nextInt(15) + level->random->nextInt(15); - popExperience(level, x, y, z, magicCount); - } -} - -int MobSpawnerTile::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; -} +int MobSpawnerTile::cloneTileId(Level* level, int x, int y, int z) { return 0; } diff --git a/Minecraft.World/Blocks/MobSpawnerTile.h b/Minecraft.World/Blocks/MobSpawnerTile.h index df41f8b4c..a5c970555 100644 --- a/Minecraft.World/Blocks/MobSpawnerTile.h +++ b/Minecraft.World/Blocks/MobSpawnerTile.h @@ -3,17 +3,19 @@ class Random; -class MobSpawnerTile : public EntityTile -{ - friend class Tile; +class MobSpawnerTile : public EntityTile { + friend class Tile; + protected: - MobSpawnerTile(int id); + MobSpawnerTile(int id); + public: - virtual std::shared_ptr newTileEntity(Level *level); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); + virtual std::shared_ptr newTileEntity(Level* level); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); virtual bool isSolidRender(bool isServerLevel = false); virtual bool blocksLight(); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/MushroomPlantTile.cpp b/Minecraft.World/Blocks/MushroomPlantTile.cpp index efbd6a8c7..d9f844dcb 100644 --- a/Minecraft.World/Blocks/MushroomPlantTile.cpp +++ b/Minecraft.World/Blocks/MushroomPlantTile.cpp @@ -4,104 +4,85 @@ #include "../Headers/net.minecraft.world.h" #include "MushroomPlantTile.h" -Mushroom::Mushroom(int id, const std::wstring &texture) : Bush(id) -{ +Mushroom::Mushroom(int id, const std::wstring& texture) : Bush(id) { this->updateDefaultShape(); this->setTicking(true); - this->texture = texture; + this->texture = texture; } // 4J Added override -void Mushroom::updateDefaultShape() -{ +void Mushroom::updateDefaultShape() { float ss = 0.2f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, ss * 2, 0.5f + ss); } -void Mushroom::tick(Level *level, int x, int y, int z, Random *random) -{ - if (random->nextInt(25) == 0) - { +void Mushroom::tick(Level* level, int x, int y, int z, Random* random) { + if (random->nextInt(25) == 0) { int r = 4; int max = 5; for (int xx = x - r; xx <= x + r; xx++) for (int zz = z - r; zz <= z + r; zz++) - for (int yy = y - 1; yy <= y + 1; yy++) - { + for (int yy = y - 1; yy <= y + 1; yy++) { if (level->getTile(xx, yy, zz) == id && --max <= 0) return; } int x2 = x + random->nextInt(3) - 1; int y2 = y + random->nextInt(2) - random->nextInt(2); int z2 = z + random->nextInt(3) - 1; - for (int i = 0; i < 4; i++) - { - if (level->isEmptyTile(x2, y2, z2) && canSurvive(level, x2, y2, z2)) - { - x = x2; - y = y2; - z = z2; - } - x2 = x + random->nextInt(3) - 1; - y2 = y + random->nextInt(2) - random->nextInt(2); - z2 = z + random->nextInt(3) - 1; + for (int i = 0; i < 4; i++) { + if (level->isEmptyTile(x2, y2, z2) && + canSurvive(level, x2, y2, z2)) { + x = x2; + y = y2; + z = z2; } + x2 = x + random->nextInt(3) - 1; + y2 = y + random->nextInt(2) - random->nextInt(2); + z2 = z + random->nextInt(3) - 1; + } - if (level->isEmptyTile(x2, y2, z2) && canSurvive(level, x2, y2, z2)) - { - level->setTile(x2, y2, z2, id); - } + if (level->isEmptyTile(x2, y2, z2) && canSurvive(level, x2, y2, z2)) { + level->setTile(x2, y2, z2, id); + } } } -bool Mushroom::mayPlace(Level *level, int x, int y, int z) -{ - return Bush::mayPlace(level, x, y, z) && canSurvive(level, x, y, z); +bool Mushroom::mayPlace(Level* level, int x, int y, int z) { + return Bush::mayPlace(level, x, y, z) && canSurvive(level, x, y, z); } -bool Mushroom::mayPlaceOn(int tile) -{ - return Tile::solid[tile]; -} +bool Mushroom::mayPlaceOn(int tile) { return Tile::solid[tile]; } -bool Mushroom::canSurvive(Level *level, int x, int y, int z) -{ - if (y < 0 || y >= Level::maxBuildHeight) return false; +bool Mushroom::canSurvive(Level* level, int x, int y, int z) { + if (y < 0 || y >= Level::maxBuildHeight) return false; int below = level->getTile(x, y - 1, z); - return below == Tile::mycel_Id || (level->getDaytimeRawBrightness(x, y, z) < 13 && mayPlaceOn(below)); + return below == Tile::mycel_Id || + (level->getDaytimeRawBrightness(x, y, z) < 13 && mayPlaceOn(below)); } -bool Mushroom::growTree(Level *level, int x, int y, int z, Random *random) -{ +bool Mushroom::growTree(Level* level, int x, int y, int z, Random* random) { int data = level->getData(x, y, z); level->setTileNoUpdate(x, y, z, 0); - Feature *f = NULL; + Feature* f = NULL; - if (id == Tile::mushroom1_Id) - { + if (id == Tile::mushroom1_Id) { f = new HugeMushroomFeature(0); - } - else if (id == Tile::mushroom2_Id) - { + } else if (id == Tile::mushroom2_Id) { f = new HugeMushroomFeature(1); } - if (f == NULL || !f->place(level, random, x, y, z)) - { + if (f == NULL || !f->place(level, random, x, y, z)) { level->setTileAndDataNoUpdate(x, y, z, this->id, data); - if( f != NULL ) - delete f; + if (f != NULL) delete f; return false; } - if( f != NULL ) - delete f; + if (f != NULL) delete f; return true; } -void Mushroom::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(texture); +void Mushroom::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(texture); } diff --git a/Minecraft.World/Blocks/MushroomPlantTile.h b/Minecraft.World/Blocks/MushroomPlantTile.h index 04f82d81c..f190c0d50 100644 --- a/Minecraft.World/Blocks/MushroomPlantTile.h +++ b/Minecraft.World/Blocks/MushroomPlantTile.h @@ -3,21 +3,25 @@ class Random; -class Mushroom : public Bush -{ - friend class Tile; +class Mushroom : public Bush { + friend class Tile; + private: - std::wstring texture; + std::wstring texture; + protected: - Mushroom(int id, const std::wstring &texture); + Mushroom(int id, const std::wstring& texture); + public: - virtual void updateDefaultShape(); // 4J Added override - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual bool mayPlace(Level *level, int x, int y, int z); + virtual void updateDefaultShape(); // 4J Added override + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual bool mayPlace(Level* level, int x, int y, int z); + protected: - virtual bool mayPlaceOn(int tile); + virtual bool mayPlaceOn(int tile); + public: - virtual bool canSurvive(Level *level, int x, int y, int z); - bool growTree(Level *level, int x, int y, int z, Random *random); - void registerIcons(IconRegister *iconRegister); + virtual bool canSurvive(Level* level, int x, int y, int z); + bool growTree(Level* level, int x, int y, int z, Random* random); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/MusicTile.cpp b/Minecraft.World/Blocks/MusicTile.cpp index b346b0a82..09fae12e9 100644 --- a/Minecraft.World/Blocks/MusicTile.cpp +++ b/Minecraft.World/Blocks/MusicTile.cpp @@ -4,81 +4,82 @@ #include "MusicTile.h" #include "../Util/SoundTypes.h" -MusicTile::MusicTile(int id) : EntityTile(id, Material::wood) -{ -} +MusicTile::MusicTile(int id) : EntityTile(id, Material::wood) {} -void MusicTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - app.DebugPrintf("-------- Neighbour changed type %d\n", type); - bool signal = level->hasNeighborSignal(x, y, z); - std::shared_ptr mte = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - app.DebugPrintf("-------- Signal is %s, tile is currently %s\n",signal?"TRUE":"FALSE", mte->on?"ON":"OFF"); - if (mte != NULL && mte->on != signal) - { - if (signal) - { - mte->playNote(level, x, y, z); - } - mte->on = signal; - } +void MusicTile::neighborChanged(Level* level, int x, int y, int z, int type) { + app.DebugPrintf("-------- Neighbour changed type %d\n", type); + bool signal = level->hasNeighborSignal(x, y, z); + std::shared_ptr mte = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + app.DebugPrintf("-------- Signal is %s, tile is currently %s\n", + signal ? "TRUE" : "FALSE", mte->on ? "ON" : "OFF"); + if (mte != NULL && mte->on != signal) { + if (signal) { + mte->playNote(level, x, y, z); + } + mte->on = signal; + } } // 4J-PB - Adding a TestUse for tooltip display -bool MusicTile::TestUse() -{ - return true; -} +bool MusicTile::TestUse() { return true; } -bool MusicTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool MusicTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if (soundOnly) return false; + if (soundOnly) return false; if (level->isClientSide) return true; - std::shared_ptr mte = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (mte != NULL ) - { - mte->tune(); - mte->playNote(level, x, y, z); - } + std::shared_ptr mte = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (mte != NULL) { + mte->tune(); + mte->playNote(level, x, y, z); + } return true; } -void MusicTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ +void MusicTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { if (level->isClientSide) return; - std::shared_ptr mte = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if( mte != NULL ) mte->playNote(level, x, y, z); + std::shared_ptr mte = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (mte != NULL) mte->playNote(level, x, y, z); } -std::shared_ptr MusicTile::newTileEntity(Level *level) -{ - return std::shared_ptr( new MusicTileEntity() ); +std::shared_ptr MusicTile::newTileEntity(Level* level) { + return std::shared_ptr(new MusicTileEntity()); } -void MusicTile::triggerEvent(Level *level, int x, int y, int z, int i, int note) -{ - float pitch = (float) pow(2, (note - 12) / 12.0); +void MusicTile::triggerEvent(Level* level, int x, int y, int z, int i, + int note) { + float pitch = (float)pow(2, (note - 12) / 12.0); - int iSound; - switch(i) - { - case 1: - iSound=eSoundType_NOTE_BD; - break; - case 2: - iSound=eSoundType_NOTE_SNARE; - break; - case 3: - iSound=eSoundType_NOTE_HAT; - break; - case 4: - iSound=eSoundType_NOTE_BASSATTACK; - break; - default: - iSound=eSoundType_NOTE_HARP; - break; - } - app.DebugPrintf("MusicTile::triggerEvent - playSound - pitch = %f\n",pitch); - level->playSound(x + 0.5, y + 0.5, z + 0.5, iSound, 3, pitch); - level->addParticle(eParticleType_note, x + 0.5, y + 1.2, z + 0.5, note / 24.0, 0, 0); + int iSound; + switch (i) { + case 1: + iSound = eSoundType_NOTE_BD; + break; + case 2: + iSound = eSoundType_NOTE_SNARE; + break; + case 3: + iSound = eSoundType_NOTE_HAT; + break; + case 4: + iSound = eSoundType_NOTE_BASSATTACK; + break; + default: + iSound = eSoundType_NOTE_HARP; + break; + } + app.DebugPrintf("MusicTile::triggerEvent - playSound - pitch = %f\n", + pitch); + level->playSound(x + 0.5, y + 0.5, z + 0.5, iSound, 3, pitch); + level->addParticle(eParticleType_note, x + 0.5, y + 1.2, z + 0.5, + note / 24.0, 0, 0); } diff --git a/Minecraft.World/Blocks/MusicTile.h b/Minecraft.World/Blocks/MusicTile.h index 63836dcb3..6e82ee1d4 100644 --- a/Minecraft.World/Blocks/MusicTile.h +++ b/Minecraft.World/Blocks/MusicTile.h @@ -3,14 +3,18 @@ class Player; -class MusicTile : public EntityTile -{ +class MusicTile : public EntityTile { public: - MusicTile(int id); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual std::shared_ptr newTileEntity(Level *level); - virtual void triggerEvent(Level *level, int x, int y, int z, int i, int note); + MusicTile(int id); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual std::shared_ptr newTileEntity(Level* level); + virtual void triggerEvent(Level* level, int x, int y, int z, int i, + int note); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/MycelTile.cpp b/Minecraft.World/Blocks/MycelTile.cpp index 688852e9c..2f67be7fe 100644 --- a/Minecraft.World/Blocks/MycelTile.cpp +++ b/Minecraft.World/Blocks/MycelTile.cpp @@ -4,71 +4,64 @@ #include "../Headers/net.minecraft.h" #include "../Headers/net.minecraft.world.h" -MycelTile::MycelTile(int id) : Tile(id, Material::grass) -{ - iconTop = NULL; +MycelTile::MycelTile(int id) : Tile(id, Material::grass) { + iconTop = NULL; iconSnowSide = NULL; setTicking(true); } -Icon *MycelTile::getTexture(int face, int data) -{ - if (face == Facing::UP) return iconTop; - if (face == Facing::DOWN) return Tile::dirt->getTexture(face); +Icon* MycelTile::getTexture(int face, int data) { + if (face == Facing::UP) return iconTop; + if (face == Facing::DOWN) return Tile::dirt->getTexture(face); + return icon; +} + +Icon* MycelTile::getTexture(LevelSource* level, int x, int y, int z, int face) { + if (face == Facing::UP) return iconTop; + if (face == Facing::DOWN) return Tile::dirt->getTexture(face); + Material* above = level->getMaterial(x, y + 1, z); + if (above == Material::topSnow || above == Material::snow) + return iconSnowSide; + else return icon; } -Icon *MycelTile::getTexture(LevelSource *level, int x, int y, int z, int face) -{ - if (face == Facing::UP) return iconTop; - if (face == Facing::DOWN) return Tile::dirt->getTexture(face); - Material *above = level->getMaterial(x, y + 1, z); - if (above == Material::topSnow || above == Material::snow) return iconSnowSide; - else return icon; +void MycelTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"mycel_side"); + iconTop = iconRegister->registerIcon(L"mycel_top"); + iconSnowSide = iconRegister->registerIcon(L"snow_side"); } -void MycelTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"mycel_side"); - iconTop = iconRegister->registerIcon(L"mycel_top"); - iconSnowSide = iconRegister->registerIcon(L"snow_side"); +void MycelTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isClientSide) return; + + if (level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && + Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) { + level->setTile(x, y, z, Tile::dirt_Id); + } else { + if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) { + for (int i = 0; i < 4; i++) { + int xt = x + random->nextInt(3) - 1; + int yt = y + random->nextInt(5) - 3; + int zt = z + random->nextInt(3) - 1; + int above = level->getTile(xt, yt + 1, zt); + if (level->getTile(xt, yt, zt) == Tile::dirt_Id && + level->getRawBrightness(xt, yt + 1, zt) >= MIN_BRIGHTNESS && + Tile::lightBlock[above] <= 2) { + level->setTile(xt, yt, zt, id); + } + } + } + } } -void MycelTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isClientSide) return; - - if (level->getRawBrightness(x, y + 1, z) < MIN_BRIGHTNESS && Tile::lightBlock[level->getTile(x, y + 1, z)] > 2) - { - level->setTile(x, y, z, Tile::dirt_Id); - } - else - { - if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) - { - for (int i=0; i<4; i++) - { - int xt = x + random->nextInt(3) - 1; - int yt = y + random->nextInt(5) - 3; - int zt = z + random->nextInt(3) - 1; - int above = level->getTile(xt, yt + 1, zt); - if (level->getTile(xt, yt, zt) == Tile::dirt_Id && level->getRawBrightness(xt, yt + 1, zt) >= MIN_BRIGHTNESS && Tile::lightBlock[above] <= 2) - { - level->setTile(xt, yt, zt, id); - } - } - } - } -} - -void MycelTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ +void MycelTile::animateTick(Level* level, int x, int y, int z, Random* random) { Tile::animateTick(level, x, y, z, random); - if (random->nextInt(10) == 0) level->addParticle(eParticleType_townaura, x + random->nextFloat(), y + 1.1f, z + random->nextFloat(), 0, 0, 0); - + if (random->nextInt(10) == 0) + level->addParticle(eParticleType_townaura, x + random->nextFloat(), + y + 1.1f, z + random->nextFloat(), 0, 0, 0); } -int MycelTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::dirt->getResource(0, random, playerBonusLevel); +int MycelTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::dirt->getResource(0, random, playerBonusLevel); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/MycelTile.h b/Minecraft.World/Blocks/MycelTile.h index d36b536f6..8025deb10 100644 --- a/Minecraft.World/Blocks/MycelTile.h +++ b/Minecraft.World/Blocks/MycelTile.h @@ -2,22 +2,23 @@ #include "Tile.h" class ChunkRebuildData; -class MycelTile : public Tile -{ - friend class ChunkRebuildData; -public: - static const int MIN_BRIGHTNESS = 4; - -private: - Icon *iconTop; - Icon *iconSnowSide; -public: - MycelTile(int id); +class MycelTile : public Tile { + friend class ChunkRebuildData; - virtual Icon *getTexture(int face, int data); - virtual Icon *getTexture(LevelSource *level, int x, int y, int z, int face); - void registerIcons(IconRegister *iconRegister); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); +public: + static const int MIN_BRIGHTNESS = 4; + +private: + Icon* iconTop; + Icon* iconSnowSide; + +public: + MycelTile(int id); + + virtual Icon* getTexture(int face, int data); + virtual Icon* getTexture(LevelSource* level, int x, int y, int z, int face); + void registerIcons(IconRegister* iconRegister); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; diff --git a/Minecraft.World/Blocks/NetherStalkTile.cpp b/Minecraft.World/Blocks/NetherStalkTile.cpp index fe0aa6ada..19b6aef74 100644 --- a/Minecraft.World/Blocks/NetherStalkTile.cpp +++ b/Minecraft.World/Blocks/NetherStalkTile.cpp @@ -5,118 +5,96 @@ #include "../Headers/net.minecraft.world.item.h" #include "../Headers/net.minecraft.world.h" -const std::wstring NetherStalkTile::TEXTURE_NAMES[] = { L"netherStalk_0", L"netherStalk_1", L"netherStalk_2" }; +const std::wstring NetherStalkTile::TEXTURE_NAMES[] = { + L"netherStalk_0", L"netherStalk_1", L"netherStalk_2"}; -NetherStalkTile::NetherStalkTile(int id) : Bush(id) -{ - setTicking(true); - updateDefaultShape(); +NetherStalkTile::NetherStalkTile(int id) : Bush(id) { + setTicking(true); + updateDefaultShape(); - icons = NULL; + icons = NULL; } // 4J Added override -void NetherStalkTile::updateDefaultShape() -{ - float ss = 0.5f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); +void NetherStalkTile::updateDefaultShape() { + float ss = 0.5f; + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); } -bool NetherStalkTile::mayPlaceOn(int tile) -{ - return tile == Tile::hellSand_Id; +bool NetherStalkTile::mayPlaceOn(int tile) { return tile == Tile::hellSand_Id; } + +// Brought forward to fix #60073 - TU7: Content: Gameplay: Nether Warts cannot +// be placed next to each other in the Nether +bool NetherStalkTile::canSurvive(Level* level, int x, int y, int z) { + return mayPlaceOn(level->getTile(x, y - 1, z)); } -// Brought forward to fix #60073 - TU7: Content: Gameplay: Nether Warts cannot be placed next to each other in the Nether -bool NetherStalkTile::canSurvive(Level *level, int x, int y, int z) -{ - return mayPlaceOn(level->getTile(x, y - 1, z)); +void NetherStalkTile::tick(Level* level, int x, int y, int z, Random* random) { + int age = level->getData(x, y, z); + if (age < MAX_AGE) { + // Biome *biome = biomeSource->getBiome(x, z); + // if (dynamic_cast(biome) != NULL) + //{ + if (random->nextInt(10) == 0) { + age++; + level->setData(x, y, z, age); + } + //} + } + + Bush::tick(level, x, y, z, random); } -void NetherStalkTile::tick(Level *level, int x, int y, int z, Random *random) -{ - int age = level->getData(x, y, z); - if (age < MAX_AGE) - { - //Biome *biome = biomeSource->getBiome(x, z); - //if (dynamic_cast(biome) != NULL) - //{ - if (random->nextInt(10) == 0) - { - age++; - level->setData(x, y, z, age); - } - //} - } - - Bush::tick(level, x, y, z, random); +void NetherStalkTile::growCropsToMax(Level* level, int x, int y, int z) { + level->setData(x, y, z, MAX_AGE); } -void NetherStalkTile::growCropsToMax(Level *level, int x, int y, int z) -{ - level->setData(x, y, z, MAX_AGE); +Icon* NetherStalkTile::getTexture(int face, int data) { + if (data >= MAX_AGE) { + return icons[2]; + } + if (data > 0) { + return icons[1]; + } + return icons[0]; } -Icon *NetherStalkTile::getTexture(int face, int data) -{ - if (data >= MAX_AGE) - { - return icons[2]; - } - if (data > 0) - { - return icons[1]; - } - return icons[0]; +int NetherStalkTile::getRenderShape() { return Tile::SHAPE_ROWS; } + +void NetherStalkTile::spawnResources(Level* level, int x, int y, int z, + int data, float odds, int playerBonus) { + if (level->isClientSide) { + return; + } + int count = 1; + if (data >= MAX_AGE) { + count = 2 + level->random->nextInt(3); + if (playerBonus > 0) { + count += level->random->nextInt(playerBonus + 1); + } + } + for (int i = 0; i < count; i++) { + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(Item::netherStalkSeeds))); + } } -int NetherStalkTile::getRenderShape() -{ - return Tile::SHAPE_ROWS; +int NetherStalkTile::getResource(int data, Random* random, + int playerBonusLevel) { + return 0; } -void NetherStalkTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ - if (level->isClientSide) - { - return; - } - int count = 1; - if (data >= MAX_AGE) - { - count = 2 + level->random->nextInt(3); - if (playerBonus > 0) - { - count += level->random->nextInt(playerBonus + 1); - } - } - for (int i = 0; i < count; i++) - { - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Item::netherStalkSeeds))); - } +int NetherStalkTile::getResourceCount(Random* random) { return 0; } + +int NetherStalkTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::netherStalkSeeds_Id; } -int NetherStalkTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; -} +void NetherStalkTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[NETHER_STALK_TEXTURE_COUNT]; -int NetherStalkTile::getResourceCount(Random *random) -{ - return 0; -} - -int NetherStalkTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::netherStalkSeeds_Id; -} - -void NetherStalkTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[NETHER_STALK_TEXTURE_COUNT]; - - for (int i = 0; i < NETHER_STALK_TEXTURE_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < NETHER_STALK_TEXTURE_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } } diff --git a/Minecraft.World/Blocks/NetherStalkTile.h b/Minecraft.World/Blocks/NetherStalkTile.h index f6dd55e35..9f53ab663 100644 --- a/Minecraft.World/Blocks/NetherStalkTile.h +++ b/Minecraft.World/Blocks/NetherStalkTile.h @@ -2,32 +2,34 @@ #include "PlantTile.h" class ChunkRebuildData; -class NetherStalkTile : public Bush -{ - friend class ChunkRebuildData; +class NetherStalkTile : public Bush { + friend class ChunkRebuildData; + private: - static const int MAX_AGE = 3; + static const int MAX_AGE = 3; - static const int NETHER_STALK_TEXTURE_COUNT = 3; - static const std::wstring TEXTURE_NAMES[]; + static const int NETHER_STALK_TEXTURE_COUNT = 3; + static const std::wstring TEXTURE_NAMES[]; - Icon **icons; + Icon** icons; public: - NetherStalkTile(int id); - virtual void updateDefaultShape(); // 4J Added override + NetherStalkTile(int id); + virtual void updateDefaultShape(); // 4J Added override virtual bool mayPlaceOn(int tile); - // Brought forward to fix #60073 - TU7: Content: Gameplay: Nether Warts cannot be placed next to each other in the Nether - virtual bool canSurvive(Level *level, int x, int y, int z); + // Brought forward to fix #60073 - TU7: Content: Gameplay: Nether Warts + // cannot be placed next to each other in the Nether + virtual bool canSurvive(Level* level, int x, int y, int z); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void growCropsToMax(Level *level, int x, int y, int z); - virtual Icon *getTexture(int face, int data); - virtual int getRenderShape(); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void growCropsToMax(Level* level, int x, int y, int z); + virtual Icon* getTexture(int face, int data); + virtual int getRenderShape(); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/NotGateTile.cpp b/Minecraft.World/Blocks/NotGateTile.cpp index 17c34cafd..89ecef92e 100644 --- a/Minecraft.World/Blocks/NotGateTile.cpp +++ b/Minecraft.World/Blocks/NotGateTile.cpp @@ -4,37 +4,35 @@ #include "../Util/SoundTypes.h" #include "../Headers/net.minecraft.world.h" -std::unordered_map *> NotGateTile::recentToggles = std::unordered_map *>(); +std::unordered_map*> + NotGateTile::recentToggles = + std::unordered_map*>(); -// 4J - added, to tie in with other changes brought forward from 1.3.2 to associate toggles with a level. In addition to what the java -// version does, we are also removing any references to levels that we are storing when they hit their dtor. -void NotGateTile::removeLevelReferences(Level *level) -{ - if( recentToggles.find(level) != recentToggles.end() ) - { - delete recentToggles[level]; - recentToggles.erase(level); - } +// 4J - added, to tie in with other changes brought forward from 1.3.2 to +// associate toggles with a level. In addition to what the java version does, we +// are also removing any references to levels that we are storing when they hit +// their dtor. +void NotGateTile::removeLevelReferences(Level* level) { + if (recentToggles.find(level) != recentToggles.end()) { + delete recentToggles[level]; + recentToggles.erase(level); + } } -bool NotGateTile::isToggledTooFrequently(Level *level, int x, int y, int z, bool add) -{ - // 4J - brought forward changes to associate toggles with a level from 1.3.2 - if( recentToggles.find(level) == recentToggles.end() ) - { - recentToggles[level] = new std::deque; - } +bool NotGateTile::isToggledTooFrequently(Level* level, int x, int y, int z, + bool add) { + // 4J - brought forward changes to associate toggles with a level from 1.3.2 + if (recentToggles.find(level) == recentToggles.end()) { + recentToggles[level] = new std::deque; + } if (add) recentToggles[level]->push_back(Toggle(x, y, z, level->getTime())); int count = 0; - AUTO_VAR(itEnd, recentToggles[level]->end()); - for (AUTO_VAR(it, recentToggles[level]->begin()); it != itEnd; it++) - { - if (it->x == x && it->y == y && it->z == z) - { + AUTO_VAR(itEnd, recentToggles[level]->end()); + for (AUTO_VAR(it, recentToggles[level]->begin()); it != itEnd; it++) { + if (it->x == x && it->y == y && it->z == z) { count++; - if (count >= MAX_RECENT_TOGGLES) - { + if (count >= MAX_RECENT_TOGGLES) { return true; } } @@ -42,22 +40,16 @@ bool NotGateTile::isToggledTooFrequently(Level *level, int x, int y, int z, bool return false; } -NotGateTile::NotGateTile(int id, bool on) : TorchTile(id) -{ +NotGateTile::NotGateTile(int id, bool on) : TorchTile(id) { this->on = on; this->setTicking(true); } -int NotGateTile::getTickDelay() -{ - return 2; -} +int NotGateTile::getTickDelay() { return 2; } -void NotGateTile::onPlace(Level *level, int x, int y, int z) -{ +void NotGateTile::onPlace(Level* level, int x, int y, int z) { if (level->getData(x, y, z) == 0) TorchTile::onPlace(level, x, y, z); - if (on) - { + if (on) { level->updateNeighborsAt(x, y - 1, z, id); level->updateNeighborsAt(x, y + 1, z, id); level->updateNeighborsAt(x - 1, y, z, id); @@ -67,10 +59,9 @@ void NotGateTile::onPlace(Level *level, int x, int y, int z) } } -void NotGateTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - if (on) - { +void NotGateTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + if (on) { level->updateNeighborsAt(x, y - 1, z, this->id); level->updateNeighborsAt(x, y + 1, z, this->id); level->updateNeighborsAt(x - 1, y, z, this->id); @@ -80,8 +71,7 @@ void NotGateTile::onRemove(Level *level, int x, int y, int z, int id, int data) } } -bool NotGateTile::getSignal(LevelSource *level, int x, int y, int z, int face) -{ +bool NotGateTile::getSignal(LevelSource* level, int x, int y, int z, int face) { if (!on) return false; int dir = level->getData(x, y, z); @@ -95,8 +85,7 @@ bool NotGateTile::getSignal(LevelSource *level, int x, int y, int z, int face) return true; } -bool NotGateTile::hasNeighborSignal(Level *level, int x, int y, int z) -{ +bool NotGateTile::hasNeighborSignal(Level* level, int x, int y, int z) { int dir = level->getData(x, y, z); if (dir == 5 && level->getSignal(x, y - 1, z, 0)) return true; @@ -107,85 +96,77 @@ bool NotGateTile::hasNeighborSignal(Level *level, int x, int y, int z) return false; } -void NotGateTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void NotGateTile::tick(Level* level, int x, int y, int z, Random* random) { bool neighborSignal = hasNeighborSignal(level, x, y, z); - // 4J - brought forward changes from 1.3.2 to associate toggles with level - if( recentToggles.find(level) != recentToggles.end() ) - { - std::deque *toggles = recentToggles[level]; - while (!toggles->empty() && level->getTime() - toggles->front().when > RECENT_TOGGLE_TIMER) - { - toggles->pop_front(); - } - } + // 4J - brought forward changes from 1.3.2 to associate toggles with level + if (recentToggles.find(level) != recentToggles.end()) { + std::deque* toggles = recentToggles[level]; + while (!toggles->empty() && + level->getTime() - toggles->front().when > RECENT_TOGGLE_TIMER) { + toggles->pop_front(); + } + } - if (on) - { - if (neighborSignal) - { - level->setTileAndData(x, y, z, Tile::notGate_off_Id, level->getData(x, y, z)); + if (on) { + if (neighborSignal) { + level->setTileAndData(x, y, z, Tile::notGate_off_Id, + level->getData(x, y, z)); - if (isToggledTooFrequently(level, x, y, z, true)) - { - app.DebugPrintf("Torch at (%d,%d,%d) has toggled too many times\n",x,y,z); + if (isToggledTooFrequently(level, x, y, z, true)) { + app.DebugPrintf( + "Torch at (%d,%d,%d) has toggled too many times\n", x, y, + z); - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, 2.6f + (level->random->nextFloat() - level->random->nextFloat()) * 0.8f); - for (int i = 0; i < 5; i++) - { + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + eSoundType_RANDOM_FIZZ, 0.5f, + 2.6f + (level->random->nextFloat() - + level->random->nextFloat()) * + 0.8f); + for (int i = 0; i < 5; i++) { double xx = x + random->nextDouble() * 0.6 + 0.2; double yy = y + random->nextDouble() * 0.6 + 0.2; double zz = z + random->nextDouble() * 0.6 + 0.2; - level->addParticle(eParticleType_smoke, xx, yy, zz, 0, 0, 0); + level->addParticle(eParticleType_smoke, xx, yy, zz, 0, 0, + 0); } } } - } - else - { - if (!neighborSignal) - { - if (!isToggledTooFrequently(level, x, y, z, false)) - { - level->setTileAndData(x, y, z, Tile::notGate_on_Id, level->getData(x, y, z)); + } else { + if (!neighborSignal) { + if (!isToggledTooFrequently(level, x, y, z, false)) { + level->setTileAndData(x, y, z, Tile::notGate_on_Id, + level->getData(x, y, z)); + } else { + app.DebugPrintf( + "Torch at (%d,%d,%d) has toggled too many times\n", x, y, + z); } - else - { - app.DebugPrintf("Torch at (%d,%d,%d) has toggled too many times\n",x,y,z); - } } } } -void NotGateTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void NotGateTile::neighborChanged(Level* level, int x, int y, int z, int type) { TorchTile::neighborChanged(level, x, y, z, type); level->addToTickNextTick(x, y, z, id, getTickDelay()); } -bool NotGateTile::getDirectSignal(Level *level, int x, int y, int z, int face) -{ - if (face == 0) - { +bool NotGateTile::getDirectSignal(Level* level, int x, int y, int z, int face) { + if (face == 0) { return getSignal(level, x, y, z, face); } return false; } -int NotGateTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::notGate_on_Id; +int NotGateTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::notGate_on_Id; } -bool NotGateTile::isSignalSource() -{ - return true; -} +bool NotGateTile::isSignalSource() { return true; } -void NotGateTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ +void NotGateTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { if (!on) return; int dir = level->getData(xt, yt, zt); double x = xt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; @@ -193,55 +174,38 @@ void NotGateTile::animateTick(Level *level, int xt, int yt, int zt, Random *rand double z = zt + 0.5f + (random->nextFloat() - 0.5f) * 0.2; double h = 0.22f; double r = 0.27f; - if (dir == 1) - { + if (dir == 1) { level->addParticle(eParticleType_reddust, x - r, y + h, z, 0, 0, 0); - } - else if(dir == 2) - { + } else if (dir == 2) { level->addParticle(eParticleType_reddust, x + r, y + h, z, 0, 0, 0); - } - else if (dir == 3) - { + } else if (dir == 3) { level->addParticle(eParticleType_reddust, x, y + h, z - r, 0, 0, 0); - } - else if (dir == 4) - { + } else if (dir == 4) { level->addParticle(eParticleType_reddust, x, y + h, z + r, 0, 0, 0); - } - else - { + } else { level->addParticle(eParticleType_reddust, x, y, z, 0, 0, 0); } - } -int NotGateTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Tile::notGate_on_Id; +int NotGateTile::cloneTileId(Level* level, int x, int y, int z) { + return Tile::notGate_on_Id; } -void NotGateTile::levelTimeChanged(Level *level, __int64 delta, __int64 newTime) -{ - std::deque *toggles = recentToggles[level]; +void NotGateTile::levelTimeChanged(Level* level, __int64 delta, + __int64 newTime) { + std::deque* toggles = recentToggles[level]; - if (toggles != NULL) - { - for (AUTO_VAR(it,toggles->begin()); it != toggles->end(); ++it) - { - (*it).when += delta; - } - } + if (toggles != NULL) { + for (AUTO_VAR(it, toggles->begin()); it != toggles->end(); ++it) { + (*it).when += delta; + } + } } -void NotGateTile::registerIcons(IconRegister *iconRegister) -{ - if (on) - { - icon = iconRegister->registerIcon(L"redtorch_lit"); - } - else - { - icon = iconRegister->registerIcon(L"redtorch"); - } +void NotGateTile::registerIcons(IconRegister* iconRegister) { + if (on) { + icon = iconRegister->registerIcon(L"redtorch_lit"); + } else { + icon = iconRegister->registerIcon(L"redtorch"); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/NotGateTile.h b/Minecraft.World/Blocks/NotGateTile.h index b263d6c94..4eca5ed1f 100644 --- a/Minecraft.World/Blocks/NotGateTile.h +++ b/Minecraft.World/Blocks/NotGateTile.h @@ -1,28 +1,24 @@ #pragma once #include "TorchTile.h" - class Random; -class NotGateTile : public TorchTile -{ - friend class Tile; +class NotGateTile : public TorchTile { + friend class Tile; private: - static const int RECENT_TOGGLE_TIMER = 20 * 3; + static const int RECENT_TOGGLE_TIMER = 20 * 3; static const int MAX_RECENT_TOGGLES = 8; bool on; public: - class Toggle - { - public: + class Toggle { + public: int x, y, z; __int64 when; - Toggle(int x, int y, int z, __int64 when) - { + Toggle(int x, int y, int z, __int64 when) { this->x = x; this->y = y; this->z = z; @@ -31,37 +27,38 @@ public: }; private: - static std::unordered_map *> recentToggles; // 4J - brought forward change from 1.3.2 + static std::unordered_map*> + recentToggles; // 4J - brought forward change from 1.3.2 public: - static void removeLevelReferences(Level *level); // 4J added + static void removeLevelReferences(Level* level); // 4J added private: - bool isToggledTooFrequently(Level *level, int x, int y, int z, bool add); + bool isToggledTooFrequently(Level* level, int x, int y, int z, bool add); protected: - NotGateTile(int id, bool on); + NotGateTile(int id, bool on); public: - int getTickDelay(); - void onPlace(Level *level, int x, int y, int z); - void onRemove(Level *level, int x, int y, int z, int id, int data); - bool getSignal(LevelSource *level, int x, int y, int z, int face); + int getTickDelay(); + void onPlace(Level* level, int x, int y, int z); + void onRemove(Level* level, int x, int y, int z, int id, int data); + bool getSignal(LevelSource* level, int x, int y, int z, int face); private: - bool hasNeighborSignal(Level *level, int x, int y, int z); + bool hasNeighborSignal(Level* level, int x, int y, int z); public: - void tick(Level *level, int x, int y, int z, Random *random); - void neighborChanged(Level *level, int x, int y, int z, int type); + void tick(Level* level, int x, int y, int z, Random* random); + void neighborChanged(Level* level, int x, int y, int z, int type); - bool getDirectSignal(Level *level, int x, int y, int z, int face); + bool getDirectSignal(Level* level, int x, int y, int z, int face); - int getResource(int data, Random *random, int playerBonusLevel); + int getResource(int data, Random* random, int playerBonusLevel); bool isSignalSource(); public: - void animateTick(Level *level, int xt, int yt, int zt, Random *random); - int cloneTileId(Level *level, int x, int y, int z); - void levelTimeChanged(Level *level, __int64 delta, __int64 newTime); + void animateTick(Level* level, int xt, int yt, int zt, Random* random); + int cloneTileId(Level* level, int x, int y, int z); + void levelTimeChanged(Level* level, __int64 delta, __int64 newTime); - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/ObsidianTile.cpp b/Minecraft.World/Blocks/ObsidianTile.cpp index 4c930c415..cf7ce9efc 100644 --- a/Minecraft.World/Blocks/ObsidianTile.cpp +++ b/Minecraft.World/Blocks/ObsidianTile.cpp @@ -1,16 +1,10 @@ #include "../Platform/stdafx.h" #include "ObsidianTile.h" -ObsidianTile::ObsidianTile(int id) : StoneTile(id) -{ -} +ObsidianTile::ObsidianTile(int id) : StoneTile(id) {} -int ObsidianTile::getResourceCount(Random *random) -{ - return 1; -} +int ObsidianTile::getResourceCount(Random* random) { return 1; } -int ObsidianTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::obsidian_Id; +int ObsidianTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::obsidian_Id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/ObsidianTile.h b/Minecraft.World/Blocks/ObsidianTile.h index 6bf23edf2..53d9c8e7a 100644 --- a/Minecraft.World/Blocks/ObsidianTile.h +++ b/Minecraft.World/Blocks/ObsidianTile.h @@ -3,10 +3,9 @@ class Random; -class ObsidianTile : public StoneTile -{ +class ObsidianTile : public StoneTile { public: - ObsidianTile(int id); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); + ObsidianTile(int id); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/OreTile.cpp b/Minecraft.World/Blocks/OreTile.cpp index 9985540da..1bf41cd11 100644 --- a/Minecraft.World/Blocks/OreTile.cpp +++ b/Minecraft.World/Blocks/OreTile.cpp @@ -3,74 +3,56 @@ #include "../Headers/net.minecraft.world.item.h" #include "../Headers/net.minecraft.world.level.h" -OreTile::OreTile(int id) : Tile(id, Material::stone) -{ -} +OreTile::OreTile(int id) : Tile(id, Material::stone) {} -int OreTile::getResource(int data, Random *random, int playerBonusLevel) -{ +int OreTile::getResource(int data, Random* random, int playerBonusLevel) { if (id == Tile::coalOre_Id) return Item::coal_Id; if (id == Tile::diamondOre_Id) return Item::diamond_Id; if (id == Tile::lapisOre_Id) return Item::dye_powder_Id; - if (id == Tile::emeraldOre_Id) return Item::emerald_Id; - if (id == Tile::netherQuartz_Id) return Item::netherQuartz_Id; + if (id == Tile::emeraldOre_Id) return Item::emerald_Id; + if (id == Tile::netherQuartz_Id) return Item::netherQuartz_Id; return id; } -int OreTile::getResourceCount(Random *random) -{ +int OreTile::getResourceCount(Random* random) { if (id == Tile::lapisOre_Id) return 4 + random->nextInt(5); return 1; } -int OreTile::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - if (bonusLevel > 0 && id != getResource(0, random, bonusLevel)) - { - int bonus = random->nextInt(bonusLevel + 2) - 1; - if (bonus < 0) - { - bonus = 0; - } - return getResourceCount(random) * (bonus + 1); - } - return getResourceCount(random); +int OreTile::getResourceCountForLootBonus(int bonusLevel, Random* random) { + if (bonusLevel > 0 && id != getResource(0, random, bonusLevel)) { + int bonus = random->nextInt(bonusLevel + 2) - 1; + if (bonus < 0) { + bonus = 0; + } + return getResourceCount(random) * (bonus + 1); + } + return getResourceCount(random); } -void OreTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); +void OreTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); - // also spawn experience if the block is broken - if (getResource(data, level->random, playerBonusLevel) != id) - { - int magicCount = 0; - if (id == Tile::coalOre_Id) - { - magicCount = Mth::nextInt(level->random, 0, 2); - } - else if (id == Tile::diamondOre_Id) - { - magicCount = Mth::nextInt(level->random, 3, 7); - } - else if (id == Tile::emeraldOre_Id) - { - magicCount = Mth::nextInt(level->random, 3, 7); - } - else if (id == Tile::lapisOre_Id) - { - magicCount = Mth::nextInt(level->random, 2, 5); - } - else if (id == Tile::netherQuartz_Id) - { - magicCount = Mth::nextInt(level->random, 2, 5); - } - popExperience(level, x, y, z, magicCount); - } + // also spawn experience if the block is broken + if (getResource(data, level->random, playerBonusLevel) != id) { + int magicCount = 0; + if (id == Tile::coalOre_Id) { + magicCount = Mth::nextInt(level->random, 0, 2); + } else if (id == Tile::diamondOre_Id) { + magicCount = Mth::nextInt(level->random, 3, 7); + } else if (id == Tile::emeraldOre_Id) { + magicCount = Mth::nextInt(level->random, 3, 7); + } else if (id == Tile::lapisOre_Id) { + magicCount = Mth::nextInt(level->random, 2, 5); + } else if (id == Tile::netherQuartz_Id) { + magicCount = Mth::nextInt(level->random, 2, 5); + } + popExperience(level, x, y, z, magicCount); + } } -int OreTile::getSpawnResourcesAuxValue(int data) -{ +int OreTile::getSpawnResourcesAuxValue(int data) { // lapis spawns blue dye if (id == Tile::lapisOre_Id) return DyePowderItem::BLUE; return 0; diff --git a/Minecraft.World/Blocks/OreTile.h b/Minecraft.World/Blocks/OreTile.h index 061bc4306..d0d68fde3 100644 --- a/Minecraft.World/Blocks/OreTile.h +++ b/Minecraft.World/Blocks/OreTile.h @@ -3,15 +3,15 @@ class Random; -class OreTile : public Tile -{ +class OreTile : public Tile { public: + OreTile(int id); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); - OreTile(int id); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); protected: - virtual int getSpawnResourcesAuxValue(int data); + virtual int getSpawnResourcesAuxValue(int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/PistonBaseTile.cpp b/Minecraft.World/Blocks/PistonBaseTile.cpp index 1aa424c43..9367cee39 100644 --- a/Minecraft.World/Blocks/PistonBaseTile.cpp +++ b/Minecraft.World/Blocks/PistonBaseTile.cpp @@ -20,37 +20,29 @@ const std::wstring PistonBaseTile::INSIDE_TEX = L"piston_inner_top"; const float PistonBaseTile::PLATFORM_THICKNESS = 4.0f; -namespace -{ +namespace { #if defined(_WIN32) - inline void *PistonTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +inline void* PistonTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void PistonTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } -#else - pthread_key_t CreatePistonTlsKey() - { - pthread_key_t key; - pthread_key_create(&key, NULL); - return key; - } - - inline void *PistonTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void PistonTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } -#endif +inline void PistonTlsSetValue(DWORD key, void* value) { + TlsSetValue(key, value); } +#else +pthread_key_t CreatePistonTlsKey() { + pthread_key_t key; + pthread_key_create(&key, NULL); + return key; +} + +inline void* PistonTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} + +inline void PistonTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +#endif +} // namespace #if defined(_WIN32) DWORD PistonBaseTile::tlsIdx = TlsAlloc(); @@ -58,181 +50,172 @@ DWORD PistonBaseTile::tlsIdx = TlsAlloc(); pthread_key_t PistonBaseTile::tlsIdx = CreatePistonTlsKey(); #endif -// 4J - NOTE - this ignoreUpdate stuff has been removed from the java version, but I'm not currently sure how the java version does without it... there must be -// some other mechanism that we don't have that stops the event from one piston being processed, from causing neighbours to have extra events created for them. -// For us, that means that if we create a piston next to another one, then one of them gets two events to createPush, the second of which fails, leaving the -// piston in a bad (simultaneously extended & not extended) state. -// 4J - ignoreUpdate is a static in java, implementing as TLS here to make thread safe -bool PistonBaseTile::ignoreUpdate() -{ - return PistonTlsGetValue(tlsIdx) != NULL; +// 4J - NOTE - this ignoreUpdate stuff has been removed from the java version, +// but I'm not currently sure how the java version does without it... there must +// be some other mechanism that we don't have that stops the event from one +// piston being processed, from causing neighbours to have extra events created +// for them. For us, that means that if we create a piston next to another one, +// then one of them gets two events to createPush, the second of which fails, +// leaving the piston in a bad (simultaneously extended & not extended) state. +// 4J - ignoreUpdate is a static in java, implementing as TLS here to make +// thread safe +bool PistonBaseTile::ignoreUpdate() { + return PistonTlsGetValue(tlsIdx) != NULL; } -void PistonBaseTile::ignoreUpdate(bool set) -{ - PistonTlsSetValue(tlsIdx, reinterpret_cast(static_cast(set ? 1 : 0))); +void PistonBaseTile::ignoreUpdate(bool set) { + PistonTlsSetValue( + tlsIdx, reinterpret_cast(static_cast(set ? 1 : 0))); } -PistonBaseTile::PistonBaseTile(int id, bool isSticky) : Tile(id, Material::piston, false) -{ - // 4J - added initialiser - ignoreUpdate(false); +PistonBaseTile::PistonBaseTile(int id, bool isSticky) + : Tile(id, Material::piston, false) { + // 4J - added initialiser + ignoreUpdate(false); this->isSticky = isSticky; setSoundType(SOUND_STONE); setDestroyTime(0.5f); - iconInside = NULL; - iconBack = NULL; - iconPlatform = NULL; + iconInside = NULL; + iconBack = NULL; + iconPlatform = NULL; } -Icon *PistonBaseTile::getPlatformTexture() -{ - return iconPlatform; +Icon* PistonBaseTile::getPlatformTexture() { return iconPlatform; } + +void PistonBaseTile::updateShape(float x0, float y0, float z0, float x1, + float y1, float z1) { + setShape(x0, y0, z0, x1, y1, z1); } -void PistonBaseTile::updateShape(float x0, float y0, float z0, float x1, float y1, float z1) -{ - setShape(x0, y0, z0, x1, y1, z1); -} - -Icon *PistonBaseTile::getTexture(int face, int data) -{ +Icon* PistonBaseTile::getTexture(int face, int data) { int facing = getFacing(data); - if (facing > 5) - { + if (facing > 5) { return iconPlatform; } - if (face == facing) - { + if (face == facing) { // sorry about this mess... // when the piston is extended, either normally // or because a piston arm animation, the top // texture is the furnace bottom - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - if (isExtended(data) || tls->xx0 > 0 || tls->yy0 > 0 || tls->zz0 > 0 || tls->xx1 < 1 || tls->yy1 < 1 || tls->zz1 < 1) - { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + if (isExtended(data) || tls->xx0 > 0 || tls->yy0 > 0 || tls->zz0 > 0 || + tls->xx1 < 1 || tls->yy1 < 1 || tls->zz1 < 1) { return iconInside; } return iconPlatform; } - if (face == Facing::OPPOSITE_FACING[facing]) - { + if (face == Facing::OPPOSITE_FACING[facing]) { return iconBack; } return icon; } -Icon *PistonBaseTile::getTexture(const std::wstring &name) -{ - if (name.compare(EDGE_TEX) == 0) return Tile::pistonBase->icon; - if (name.compare(PLATFORM_TEX) == 0) return Tile::pistonBase->iconPlatform; - if (name.compare(PLATFORM_STICKY_TEX) == 0) return Tile::pistonStickyBase->iconPlatform; - if (name.compare(INSIDE_TEX) == 0) return Tile::pistonBase->iconInside; +Icon* PistonBaseTile::getTexture(const std::wstring& name) { + if (name.compare(EDGE_TEX) == 0) return Tile::pistonBase->icon; + if (name.compare(PLATFORM_TEX) == 0) return Tile::pistonBase->iconPlatform; + if (name.compare(PLATFORM_STICKY_TEX) == 0) + return Tile::pistonStickyBase->iconPlatform; + if (name.compare(INSIDE_TEX) == 0) return Tile::pistonBase->iconInside; - return NULL; + return NULL; } //@Override -void PistonBaseTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(EDGE_TEX); - iconPlatform = iconRegister->registerIcon(isSticky ? PLATFORM_STICKY_TEX : PLATFORM_TEX); - iconInside = iconRegister->registerIcon(INSIDE_TEX); - iconBack = iconRegister->registerIcon(BACK_TEX); +void PistonBaseTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(EDGE_TEX); + iconPlatform = iconRegister->registerIcon(isSticky ? PLATFORM_STICKY_TEX + : PLATFORM_TEX); + iconInside = iconRegister->registerIcon(INSIDE_TEX); + iconBack = iconRegister->registerIcon(BACK_TEX); } -int PistonBaseTile::getRenderShape() +int PistonBaseTile::getRenderShape() { return SHAPE_PISTON_BASE; } + +bool PistonBaseTile::isSolidRender(bool isServerLevel) { return false; } + +bool PistonBaseTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return SHAPE_PISTON_BASE; + return false; } -bool PistonBaseTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -bool PistonBaseTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - return false; -} - -void PistonBaseTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int targetData = getNewFacing(level, x, y, z, std::dynamic_pointer_cast(by) ); +void PistonBaseTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int targetData = + getNewFacing(level, x, y, z, std::dynamic_pointer_cast(by)); level->setData(x, y, z, targetData); - if (!level->isClientSide && !ignoreUpdate()) - { + if (!level->isClientSide && !ignoreUpdate()) { checkIfExtend(level, x, y, z); } } -void PistonBaseTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isClientSide && !ignoreUpdate()) - { +void PistonBaseTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (!level->isClientSide && !ignoreUpdate()) { checkIfExtend(level, x, y, z); } } -void PistonBaseTile::onPlace(Level *level, int x, int y, int z) -{ - if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL && !ignoreUpdate()) - { +void PistonBaseTile::onPlace(Level* level, int x, int y, int z) { + if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL && + !ignoreUpdate()) { checkIfExtend(level, x, y, z); } } -void PistonBaseTile::checkIfExtend(Level *level, int x, int y, int z) -{ +void PistonBaseTile::checkIfExtend(Level* level, int x, int y, int z) { int data = level->getData(x, y, z); int facing = getFacing(data); - if (facing == UNDEFINED_FACING) - { + if (facing == UNDEFINED_FACING) { return; } bool extend = getNeighborSignal(level, x, y, z, facing); - if (extend && !isExtended(data)) - { - if (canPush(level, x, y, z, facing)) - { - //level->setDataNoUpdate(x, y, z, facing | EXTENDED_BIT); + if (extend && !isExtended(data)) { + if (canPush(level, x, y, z, facing)) { + // level->setDataNoUpdate(x, y, z, facing | EXTENDED_BIT); level->tileEvent(x, y, z, id, TRIGGER_EXTEND, facing); } - } - else if (!extend && isExtended(data)) - { - //level->setDataNoUpdate(x, y, z, facing); + } else if (!extend && isExtended(data)) { + // level->setDataNoUpdate(x, y, z, facing); level->tileEvent(x, y, z, id, TRIGGER_CONTRACT, facing); } } /** - * This method checks neighbor signals for this block and the block above, - * and directly beneath. However, it avoids checking blocks that would be - * pushed by this block. - * - * @param level - * @param x - * @param y - * @param z - * @return - */ -bool PistonBaseTile::getNeighborSignal(Level *level, int x, int y, int z, int facing) -{ + * This method checks neighbor signals for this block and the block above, + * and directly beneath. However, it avoids checking blocks that would be + * pushed by this block. + * + * @param level + * @param x + * @param y + * @param z + * @return + */ +bool PistonBaseTile::getNeighborSignal(Level* level, int x, int y, int z, + int facing) { // check adjacent neighbors, but not in push direction - if (facing != Facing::DOWN && level->getSignal(x, y - 1, z, Facing::DOWN)) return true; - if (facing != Facing::UP && level->getSignal(x, y + 1, z, Facing::UP)) return true; - if (facing != Facing::NORTH && level->getSignal(x, y, z - 1, Facing::NORTH)) return true; - if (facing != Facing::SOUTH && level->getSignal(x, y, z + 1, Facing::SOUTH)) return true; - if (facing != Facing::EAST && level->getSignal(x + 1, y, z, Facing::EAST)) return true; - if (facing != Facing::WEST && level->getSignal(x - 1, y, z, Facing::WEST)) return true; + if (facing != Facing::DOWN && level->getSignal(x, y - 1, z, Facing::DOWN)) + return true; + if (facing != Facing::UP && level->getSignal(x, y + 1, z, Facing::UP)) + return true; + if (facing != Facing::NORTH && level->getSignal(x, y, z - 1, Facing::NORTH)) + return true; + if (facing != Facing::SOUTH && level->getSignal(x, y, z + 1, Facing::SOUTH)) + return true; + if (facing != Facing::EAST && level->getSignal(x + 1, y, z, Facing::EAST)) + return true; + if (facing != Facing::WEST && level->getSignal(x - 1, y, z, Facing::WEST)) + return true; // check signals above if (level->getSignal(x, y, z, 0)) return true; @@ -245,63 +228,73 @@ bool PistonBaseTile::getNeighborSignal(Level *level, int x, int y, int z, int fa return false; } -void PistonBaseTile::triggerEvent(Level *level, int x, int y, int z, int param1, int facing) -{ - ignoreUpdate(true); +void PistonBaseTile::triggerEvent(Level* level, int x, int y, int z, int param1, + int facing) { + ignoreUpdate(true); - if (param1 == TRIGGER_EXTEND) - { - level->setDataNoUpdate(x, y, z, facing | EXTENDED_BIT); - } - else - { - level->setDataNoUpdate(x, y, z, facing); - } - - if (param1 == TRIGGER_EXTEND) - { - PIXBeginNamedEvent(0,"Create push\n"); - if (createPush(level, x, y, z, facing)) - { - // 4J - it is (currently) critical that this setData sends data to the client, so have added a bool to the method so that it sends data even if the data was already set to the same value - // as before, which was actually its behaviour until a change in 1.0.1 meant that setData only conditionally sent updates to listeners. If the data update Isn't sent, then what - // can happen is: - // (1) the host sends the tile event to the client - // (2) the client gets the tile event, and sets the tile/data value locally. - // (3) just before setting the tile/data locally, the client will put the old value in the vector of things to be restored should an update not be received back from the host - // (4) we don't get any update of the tile from the host, and so the old value gets restored on the client - // (5) the piston base ends up being restored to its retracted state whilst the piston arm is extended - // We really need to spend some time investigating a better way for pistons to work as it all seems a bit scary how the host/client interact, but forcing this to send should at least - // restore the behaviour of the pistons to something closer to what they were before the 1.0.1 update. By sending this data update, then (4) in the list above doesn't happen - // because the client does actually receive an update for this tile from the host after the event has been processed on the cient. - level->setData(x, y, z, facing | EXTENDED_BIT, true); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_TILE_PISTON_OUT, 0.5f, level->random->nextFloat() * 0.25f + 0.6f); - } - else - { - level->setDataNoUpdate(x, y, z, facing); - } - PIXEndNamedEvent(); + if (param1 == TRIGGER_EXTEND) { + level->setDataNoUpdate(x, y, z, facing | EXTENDED_BIT); + } else { + level->setDataNoUpdate(x, y, z, facing); } - else if (param1 == TRIGGER_CONTRACT) - { - PIXBeginNamedEvent(0,"Contract phase A\n"); - std::shared_ptr prevTileEntity = level->getTileEntity(x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], z + Facing::STEP_Z[facing]); - if (prevTileEntity != NULL && std::dynamic_pointer_cast(prevTileEntity) != NULL) - { - std::dynamic_pointer_cast(prevTileEntity)->finalTick(); + + if (param1 == TRIGGER_EXTEND) { + PIXBeginNamedEvent(0, "Create push\n"); + if (createPush(level, x, y, z, facing)) { + // 4J - it is (currently) critical that this setData sends data to + // the client, so have added a bool to the method so that it sends + // data even if the data was already set to the same value as + // before, which was actually its behaviour until a change in 1.0.1 + // meant that setData only conditionally sent updates to listeners. + // If the data update Isn't sent, then what can happen is: (1) the + // host sends the tile event to the client (2) the client gets the + // tile event, and sets the tile/data value locally. (3) just before + // setting the tile/data locally, the client will put the old value + // in the vector of things to be restored should an update not be + // received back from the host (4) we don't get any update of the + // tile from the host, and so the old value gets restored on the + // client (5) the piston base ends up being restored to its + // retracted state whilst the piston arm is extended We really need + // to spend some time investigating a better way for pistons to work + // as it all seems a bit scary how the host/client interact, but + // forcing this to send should at least restore the behaviour of the + // pistons to something closer to what they were before the 1.0.1 + // update. By sending this data update, then (4) in the list above + // doesn't happen because the client does actually receive an update + // for this tile from the host after the event has been processed on + // the cient. + level->setData(x, y, z, facing | EXTENDED_BIT, true); + level->playSound(x + 0.5, y + 0.5, z + 0.5, + eSoundType_TILE_PISTON_OUT, 0.5f, + level->random->nextFloat() * 0.25f + 0.6f); + } else { + level->setDataNoUpdate(x, y, z, facing); + } + PIXEndNamedEvent(); + } else if (param1 == TRIGGER_CONTRACT) { + PIXBeginNamedEvent(0, "Contract phase A\n"); + std::shared_ptr prevTileEntity = level->getTileEntity( + x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], + z + Facing::STEP_Z[facing]); + if (prevTileEntity != NULL && + std::dynamic_pointer_cast(prevTileEntity) != + NULL) { + std::dynamic_pointer_cast(prevTileEntity) + ->finalTick(); } - stopSharingIfServer(level, x, y, z); // 4J added - level->setTileAndDataNoUpdate(x, y, z, Tile::pistonMovingPiece_Id, facing); - level->setTileEntity(x, y, z, PistonMovingPiece::newMovingPieceEntity(id, facing, facing, false, true)); + stopSharingIfServer(level, x, y, z); // 4J added + level->setTileAndDataNoUpdate(x, y, z, Tile::pistonMovingPiece_Id, + facing); + level->setTileEntity(x, y, z, + PistonMovingPiece::newMovingPieceEntity( + id, facing, facing, false, true)); - PIXEndNamedEvent(); + PIXEndNamedEvent(); // sticky movement - if (isSticky) - { - PIXBeginNamedEvent(0,"Contract sticky phase A\n"); + if (isSticky) { + PIXBeginNamedEvent(0, "Contract sticky phase A\n"); int twoX = x + Facing::STEP_X[facing] * 2; int twoY = y + Facing::STEP_Y[facing] * 2; int twoZ = z + Facing::STEP_Z[facing] * 2; @@ -309,21 +302,23 @@ void PistonBaseTile::triggerEvent(Level *level, int x, int y, int z, int param1, int blockData = level->getData(twoX, twoY, twoZ); bool pistonPiece = false; - PIXEndNamedEvent(); + PIXEndNamedEvent(); - if (block == Tile::pistonMovingPiece_Id) - { - PIXBeginNamedEvent(0,"Contract sticky phase B\n"); + if (block == Tile::pistonMovingPiece_Id) { + PIXBeginNamedEvent(0, "Contract sticky phase B\n"); // the block two steps away is a moving piston block piece, // so replace it with the real data, since it's probably // this piston which is changing too fast - std::shared_ptr tileEntity = level->getTileEntity(twoX, twoY, twoZ); - if (tileEntity != NULL && std::dynamic_pointer_cast(tileEntity) != NULL ) - { - std::shared_ptr ppe = std::dynamic_pointer_cast(tileEntity); + std::shared_ptr tileEntity = + level->getTileEntity(twoX, twoY, twoZ); + if (tileEntity != NULL && + std::dynamic_pointer_cast(tileEntity) != + NULL) { + std::shared_ptr ppe = + std::dynamic_pointer_cast( + tileEntity); - if (ppe->getFacing() == facing && ppe->isExtending()) - { + if (ppe->getFacing() == facing && ppe->isExtending()) { // force the tile to air before pushing ppe->finalTick(); block = ppe->getId(); @@ -331,129 +326,125 @@ void PistonBaseTile::triggerEvent(Level *level, int x, int y, int z, int param1, pistonPiece = true; } } - PIXEndNamedEvent(); + PIXEndNamedEvent(); } - PIXBeginNamedEvent(0,"Contract sticky phase C\n"); - if (!pistonPiece && block > 0 && (isPushable(block, level, twoX, twoY, twoZ, false)) - && (Tile::tiles[block]->getPistonPushReaction() == Material::PUSH_NORMAL || block == Tile::pistonBase_Id || block == Tile::pistonStickyBase_Id)) - { - stopSharingIfServer(level, twoX, twoY, twoZ); // 4J added + PIXBeginNamedEvent(0, "Contract sticky phase C\n"); + if (!pistonPiece && block > 0 && + (isPushable(block, level, twoX, twoY, twoZ, false)) && + (Tile::tiles[block]->getPistonPushReaction() == + Material::PUSH_NORMAL || + block == Tile::pistonBase_Id || + block == Tile::pistonStickyBase_Id)) { + stopSharingIfServer(level, twoX, twoY, twoZ); // 4J added x += Facing::STEP_X[facing]; y += Facing::STEP_Y[facing]; z += Facing::STEP_Z[facing]; - level->setTileAndDataNoUpdate(x, y, z, Tile::pistonMovingPiece_Id, blockData); - level->setTileEntity(x, y, z, PistonMovingPiece::newMovingPieceEntity(block, blockData, facing, false, false)); + level->setTileAndDataNoUpdate( + x, y, z, Tile::pistonMovingPiece_Id, blockData); + level->setTileEntity( + x, y, z, + PistonMovingPiece::newMovingPieceEntity( + block, blockData, facing, false, false)); - ignoreUpdate(false); + ignoreUpdate(false); level->setTile(twoX, twoY, twoZ, 0); - ignoreUpdate(true); - } - else if (!pistonPiece) - { - stopSharingIfServer(level, x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], z + Facing::STEP_Z[facing]); // 4J added - ignoreUpdate(false); - level->setTile(x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], z + Facing::STEP_Z[facing], 0); - ignoreUpdate(true); + ignoreUpdate(true); + } else if (!pistonPiece) { + stopSharingIfServer(level, x + Facing::STEP_X[facing], + y + Facing::STEP_Y[facing], + z + Facing::STEP_Z[facing]); // 4J added + ignoreUpdate(false); + level->setTile(x + Facing::STEP_X[facing], + y + Facing::STEP_Y[facing], + z + Facing::STEP_Z[facing], 0); + ignoreUpdate(true); } - PIXEndNamedEvent(); - } - else - { - stopSharingIfServer(level, x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], z + Facing::STEP_Z[facing]); // 4J added - ignoreUpdate(false); - level->setTile(x + Facing::STEP_X[facing], y + Facing::STEP_Y[facing], z + Facing::STEP_Z[facing], 0); - ignoreUpdate(true); + PIXEndNamedEvent(); + } else { + stopSharingIfServer(level, x + Facing::STEP_X[facing], + y + Facing::STEP_Y[facing], + z + Facing::STEP_Z[facing]); // 4J added + ignoreUpdate(false); + level->setTile(x + Facing::STEP_X[facing], + y + Facing::STEP_Y[facing], + z + Facing::STEP_Z[facing], 0); + ignoreUpdate(true); } - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_TILE_PISTON_IN, 0.5f, level->random->nextFloat() * 0.15f + 0.6f); + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_TILE_PISTON_IN, + 0.5f, level->random->nextFloat() * 0.15f + 0.6f); } - ignoreUpdate(false); + ignoreUpdate(false); } -void PistonBaseTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void PistonBaseTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - int data = (forceData == -1 ) ? level->getData(x, y, z) : forceData; + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; - if (isExtended(data)) - { + if (isExtended(data)) { const float thickness = PLATFORM_THICKNESS / 16.0f; - switch (getFacing(data)) - { - case Facing::DOWN: - setShape(0, thickness, 0, 1, 1, 1); - break; - case Facing::UP: - setShape(0, 0, 0, 1, 1 - thickness, 1); - break; - case Facing::NORTH: - setShape(0, 0, thickness, 1, 1, 1); - break; - case Facing::SOUTH: - setShape(0, 0, 0, 1, 1, 1 - thickness); - break; - case Facing::WEST: - setShape(thickness, 0, 0, 1, 1, 1); - break; - case Facing::EAST: - setShape(0, 0, 0, 1 - thickness, 1, 1); - break; + switch (getFacing(data)) { + case Facing::DOWN: + setShape(0, thickness, 0, 1, 1, 1); + break; + case Facing::UP: + setShape(0, 0, 0, 1, 1 - thickness, 1); + break; + case Facing::NORTH: + setShape(0, 0, thickness, 1, 1, 1); + break; + case Facing::SOUTH: + setShape(0, 0, 0, 1, 1, 1 - thickness); + break; + case Facing::WEST: + setShape(thickness, 0, 0, 1, 1, 1); + break; + case Facing::EAST: + setShape(0, 0, 0, 1 - thickness, 1, 1); + break; } - } - else - { + } else { setShape(0, 0, 0, 1, 1, 1); } } -void PistonBaseTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 1, 1); -} +void PistonBaseTile::updateDefaultShape() { setShape(0, 0, 0, 1, 1, 1); } -void PistonBaseTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ +void PistonBaseTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { setShape(0, 0, 0, 1, 1, 1); Tile::addAABBs(level, x, y, z, box, boxes, source); } -AABB *PistonBaseTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return Tile::getAABB(level, x, y, z); +AABB* PistonBaseTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return Tile::getAABB(level, x, y, z); } -bool PistonBaseTile::isCubeShaped() -{ - return false; -} +bool PistonBaseTile::isCubeShaped() { return false; } -int PistonBaseTile::getFacing(int data) -{ - return data & 0x7; -} +int PistonBaseTile::getFacing(int data) { return data & 0x7; } -bool PistonBaseTile::isExtended(int data) -{ - return (data & EXTENDED_BIT) != 0; -} +bool PistonBaseTile::isExtended(int data) { return (data & EXTENDED_BIT) != 0; } -int PistonBaseTile::getNewFacing(Level *level, int x, int y, int z, std::shared_ptr player) -{ - if (Mth::abs((float) player->x - x) < 2 && Mth::abs((float) player->z - z) < 2) - { +int PistonBaseTile::getNewFacing(Level* level, int x, int y, int z, + std::shared_ptr player) { + if (Mth::abs((float)player->x - x) < 2 && + Mth::abs((float)player->z - z) < 2) { // If the player is above the block, the slot is on the top double py = player->y + 1.82 - player->heightOffset; - if (py - y > 2) - { + if (py - y > 2) { return Facing::UP; } // If the player is below the block, the slot is on the bottom - if (y - py > 0) - { + if (y - py > 0) { return Facing::DOWN; } } @@ -466,89 +457,78 @@ int PistonBaseTile::getNewFacing(Level *level, int x, int y, int z, std::shared_ return 0; } -bool PistonBaseTile::isPushable(int block, Level *level, int cx, int cy, int cz, bool allowDestroyable) -{ +bool PistonBaseTile::isPushable(int block, Level* level, int cx, int cy, int cz, + bool allowDestroyable) { // special case for obsidian - if (block == Tile::obsidian_Id) - { + if (block == Tile::obsidian_Id) { return false; } - if (block == Tile::pistonBase_Id || block == Tile::pistonStickyBase_Id) - { + if (block == Tile::pistonBase_Id || block == Tile::pistonStickyBase_Id) { // special case for piston bases - if (isExtended(level->getData(cx, cy, cz))) - { + if (isExtended(level->getData(cx, cy, cz))) { return false; } - } - else - { - if (Tile::tiles[block]->getDestroySpeed(level, cx, cy, cz) == Tile::INDESTRUCTIBLE_DESTROY_TIME) - { + } else { + if (Tile::tiles[block]->getDestroySpeed(level, cx, cy, cz) == + Tile::INDESTRUCTIBLE_DESTROY_TIME) { return false; } - if (Tile::tiles[block]->getPistonPushReaction() == Material::PUSH_BLOCK) - { + if (Tile::tiles[block]->getPistonPushReaction() == + Material::PUSH_BLOCK) { return false; } - - if (!allowDestroyable && Tile::tiles[block]->getPistonPushReaction() == Material::PUSH_DESTROY) - { + + if (!allowDestroyable && Tile::tiles[block]->getPistonPushReaction() == + Material::PUSH_DESTROY) { return false; } } - if( Tile::tiles[block]->isEntityTile() ) // 4J - java uses instanceof EntityTile here - { - // may not push tile entities - return false; - } + if (Tile::tiles[block] + ->isEntityTile()) // 4J - java uses instanceof EntityTile here + { + // may not push tile entities + return false; + } - return true; + return true; } -bool PistonBaseTile::canPush(Level *level, int sx, int sy, int sz, int facing) -{ +bool PistonBaseTile::canPush(Level* level, int sx, int sy, int sz, int facing) { int cx = sx + Facing::STEP_X[facing]; int cy = sy + Facing::STEP_Y[facing]; int cz = sz + Facing::STEP_Z[facing]; - for (int i = 0; i < MAX_PUSH_DEPTH + 1; i++) - { - - if (cy <= 0 || cy >= (Level::maxBuildHeight - 1)) - { + for (int i = 0; i < MAX_PUSH_DEPTH + 1; i++) { + if (cy <= 0 || cy >= (Level::maxBuildHeight - 1)) { // out of bounds return false; } - - // 4J - added to also check for out of bounds in x/z for our finite world - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; - if( ( cx <= minXZ ) || ( cx >= maxXZ ) || ( cz <= minXZ ) || ( cz >= maxXZ ) ) - { - return false; - } + + // 4J - added to also check for out of bounds in x/z for our finite + // world + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; + if ((cx <= minXZ) || (cx >= maxXZ) || (cz <= minXZ) || (cz >= maxXZ)) { + return false; + } int block = level->getTile(cx, cy, cz); - if (block == 0) - { + if (block == 0) { break; } - if (!isPushable(block, level, cx, cy, cz, true)) - { + if (!isPushable(block, level, cx, cy, cz, true)) { return false; } - if (Tile::tiles[block]->getPistonPushReaction() == Material::PUSH_DESTROY) - { + if (Tile::tiles[block]->getPistonPushReaction() == + Material::PUSH_DESTROY) { break; } - if (i == MAX_PUSH_DEPTH) - { + if (i == MAX_PUSH_DEPTH) { // we've reached the maximum push depth // without finding air or a breakable block return false; @@ -560,68 +540,61 @@ bool PistonBaseTile::canPush(Level *level, int sx, int sy, int sz, int facing) } return true; - } -void PistonBaseTile::stopSharingIfServer(Level *level, int x, int y, int z) -{ - if( !level->isClientSide ) - { - MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id); - if( clientLevel ) - { - LevelChunk *lc = clientLevel->getChunkAt( x, z ); - lc->stopSharingTilesAndData(); - } - } +void PistonBaseTile::stopSharingIfServer(Level* level, int x, int y, int z) { + if (!level->isClientSide) { + MultiPlayerLevel* clientLevel = + Minecraft::GetInstance()->getLevel(level->dimension->id); + if (clientLevel) { + LevelChunk* lc = clientLevel->getChunkAt(x, z); + lc->stopSharingTilesAndData(); + } + } } -bool PistonBaseTile::createPush(Level *level, int sx, int sy, int sz, int facing) -{ +bool PistonBaseTile::createPush(Level* level, int sx, int sy, int sz, + int facing) { int cx = sx + Facing::STEP_X[facing]; int cy = sy + Facing::STEP_Y[facing]; int cz = sz + Facing::STEP_Z[facing]; - for (int i = 0; i < MAX_PUSH_DEPTH + 1; i++) - { - if (cy <= 0 || cy >= (Level::maxBuildHeight - 1)) - { + for (int i = 0; i < MAX_PUSH_DEPTH + 1; i++) { + if (cy <= 0 || cy >= (Level::maxBuildHeight - 1)) { // out of bounds return false; } - - // 4J - added to also check for out of bounds in x/z for our finite world - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; - if( ( cx <= minXZ ) || ( cx >= maxXZ ) || ( cz <= minXZ ) || ( cz >= maxXZ ) ) - { - return false; - } - int block = level->getTile(cx, cy, cz); - if (block == 0) - { - break; - } - - if (!isPushable(block, level, cx, cy, cz, true)) - { + // 4J - added to also check for out of bounds in x/z for our finite + // world + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; + if ((cx <= minXZ) || (cx >= maxXZ) || (cz <= minXZ) || (cz >= maxXZ)) { return false; } - if (Tile::tiles[block]->getPistonPushReaction() == Material::PUSH_DESTROY) - { + int block = level->getTile(cx, cy, cz); + if (block == 0) { + break; + } + + if (!isPushable(block, level, cx, cy, cz, true)) { + return false; + } + + if (Tile::tiles[block]->getPistonPushReaction() == + Material::PUSH_DESTROY) { // this block is destroyed when pushed - Tile::tiles[block]->spawnResources(level, cx, cy, cz, level->getData(cx, cy, cz), 0); + Tile::tiles[block]->spawnResources(level, cx, cy, cz, + level->getData(cx, cy, cz), 0); // setting the tile to air is actually superflous, but // helps vs multiplayer problems - stopSharingIfServer(level, cx, cy, cz); // 4J added + stopSharingIfServer(level, cx, cy, cz); // 4J added level->setTile(cx, cy, cz, 0); break; } - if (i == MAX_PUSH_DEPTH) - { + if (i == MAX_PUSH_DEPTH) { // we've reached the maximum push depth // without finding air or a breakable block return false; @@ -632,9 +605,7 @@ bool PistonBaseTile::createPush(Level *level, int sx, int sy, int sz, int facing cz += Facing::STEP_Z[facing]; } - while (cx != sx || cy != sy || cz != sz) - { - + while (cx != sx || cy != sy || cz != sz) { int nx = cx - Facing::STEP_X[facing]; int ny = cy - Facing::STEP_Y[facing]; int nz = cz - Facing::STEP_Z[facing]; @@ -642,17 +613,25 @@ bool PistonBaseTile::createPush(Level *level, int sx, int sy, int sz, int facing int block = level->getTile(nx, ny, nz); int data = level->getData(nx, ny, nz); - stopSharingIfServer(level, cx, cy, cz); // 4J added + stopSharingIfServer(level, cx, cy, cz); // 4J added - if (block == id && nx == sx && ny == sy && nz == sz) - { - level->setTileAndDataNoUpdate(cx, cy, cz, Tile::pistonMovingPiece_Id, facing | (isSticky ? PistonExtensionTile::STICKY_BIT : 0), false); - level->setTileEntity(cx, cy, cz, PistonMovingPiece::newMovingPieceEntity(Tile::pistonExtensionPiece_Id, facing | (isSticky ? PistonExtensionTile::STICKY_BIT : 0), facing, true, false)); - } - else - { - level->setTileAndDataNoUpdate(cx, cy, cz, Tile::pistonMovingPiece_Id, data, false); - level->setTileEntity(cx, cy, cz, PistonMovingPiece::newMovingPieceEntity(block, data, facing, true, false)); + if (block == id && nx == sx && ny == sy && nz == sz) { + level->setTileAndDataNoUpdate( + cx, cy, cz, Tile::pistonMovingPiece_Id, + facing | (isSticky ? PistonExtensionTile::STICKY_BIT : 0), + false); + level->setTileEntity( + cx, cy, cz, + PistonMovingPiece::newMovingPieceEntity( + Tile::pistonExtensionPiece_Id, + facing | (isSticky ? PistonExtensionTile::STICKY_BIT : 0), + facing, true, false)); + } else { + level->setTileAndDataNoUpdate( + cx, cy, cz, Tile::pistonMovingPiece_Id, data, false); + level->setTileEntity(cx, cy, cz, + PistonMovingPiece::newMovingPieceEntity( + block, data, facing, true, false)); } cx = nx; @@ -661,5 +640,4 @@ bool PistonBaseTile::createPush(Level *level, int sx, int sy, int sz, int facing } return true; - } diff --git a/Minecraft.World/Blocks/PistonBaseTile.h b/Minecraft.World/Blocks/PistonBaseTile.h index 4e844a7e2..ebe858062 100644 --- a/Minecraft.World/Blocks/PistonBaseTile.h +++ b/Minecraft.World/Blocks/PistonBaseTile.h @@ -5,75 +5,88 @@ #include #endif -class PistonBaseTile : public Tile -{ +class PistonBaseTile : public Tile { public: - static const int EXTENDED_BIT = 8; - static const int UNDEFINED_FACING = 7; + static const int EXTENDED_BIT = 8; + static const int UNDEFINED_FACING = 7; - static const float PLATFORM_THICKNESS; - static const int MAX_PUSH_DEPTH = 12; - static const int TRIGGER_EXTEND = 0; - static const int TRIGGER_CONTRACT = 1; + static const float PLATFORM_THICKNESS; + static const int MAX_PUSH_DEPTH = 12; + static const int TRIGGER_EXTEND = 0; + static const int TRIGGER_CONTRACT = 1; - static const std::wstring EDGE_TEX; - static const std::wstring PLATFORM_TEX; - static const std::wstring PLATFORM_STICKY_TEX; - static const std::wstring BACK_TEX; - static const std::wstring INSIDE_TEX; + static const std::wstring EDGE_TEX; + static const std::wstring PLATFORM_TEX; + static const std::wstring PLATFORM_STICKY_TEX; + static const std::wstring BACK_TEX; + static const std::wstring INSIDE_TEX; private: - bool isSticky; + bool isSticky; - Icon *iconInside; - Icon *iconBack; - Icon *iconPlatform; + Icon* iconInside; + Icon* iconBack; + Icon* iconPlatform; #if defined(_WIN32) - static DWORD tlsIdx; + static DWORD tlsIdx; #else - static pthread_key_t tlsIdx; + static pthread_key_t tlsIdx; #endif - // 4J - was just a static but implemented with TLS for our version - static bool ignoreUpdate(); - static void ignoreUpdate(bool set); + // 4J - was just a static but implemented with TLS for our version + static bool ignoreUpdate(); + static void ignoreUpdate(bool set); public: - PistonBaseTile(int id, bool isSticky); + PistonBaseTile(int id, bool isSticky); - Icon *getPlatformTexture(); - virtual void updateShape(float x0, float y0, float z0, float x1, float y1, float z1); + Icon* getPlatformTexture(); + virtual void updateShape(float x0, float y0, float z0, float x1, float y1, + float z1); - virtual Icon *getTexture(int face, int data); - static Icon *getTexture(const std::wstring &name); - void registerIcons(IconRegister *iconRegister); + virtual Icon* getTexture(int face, int data); + static Icon* getTexture(const std::wstring& name); + void registerIcons(IconRegister* iconRegister); virtual int getRenderShape(); virtual bool isSolidRender(bool isServerLevel = false); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void onPlace(Level *level, int x, int y, int z); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void onPlace(Level* level, int x, int y, int z); private: - void checkIfExtend(Level *level, int x, int y, int z); - bool getNeighborSignal(Level *level, int x, int y, int z, int facing); + void checkIfExtend(Level* level, int x, int y, int z); + bool getNeighborSignal(Level* level, int x, int y, int z, int facing); public: - virtual void triggerEvent(Level *level, int x, int y, int z, int param1, int facing); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + virtual void triggerEvent(Level* level, int x, int y, int z, int param1, + int facing); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param virtual void updateDefaultShape(); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool isCubeShaped(); static int getFacing(int data); static bool isExtended(int data); - static int getNewFacing(Level *level, int x, int y, int z, std::shared_ptr player); -private: - static bool isPushable(int block, Level *level, int cx, int cy, int cz, bool allowDestroyable); - static bool canPush(Level *level, int sx, int sy, int sz, int facing); - static void stopSharingIfServer(Level *level, int x, int y, int z); // 4J added + static int getNewFacing(Level* level, int x, int y, int z, + std::shared_ptr player); - bool createPush(Level *level, int sx, int sy, int sz, int facing); +private: + static bool isPushable(int block, Level* level, int cx, int cy, int cz, + bool allowDestroyable); + static bool canPush(Level* level, int sx, int sy, int sz, int facing); + static void stopSharingIfServer(Level* level, int x, int y, + int z); // 4J added + + bool createPush(Level* level, int sx, int sy, int sz, int facing); }; diff --git a/Minecraft.World/Blocks/PistonExtensionTile.cpp b/Minecraft.World/Blocks/PistonExtensionTile.cpp index 3302ad75f..b407b1d00 100644 --- a/Minecraft.World/Blocks/PistonExtensionTile.cpp +++ b/Minecraft.World/Blocks/PistonExtensionTile.cpp @@ -4,27 +4,25 @@ #include "../Util/Facing.h" #include "../Headers/net.minecraft.world.level.h" -PistonExtensionTile::PistonExtensionTile(int id) : Tile(id, Material::piston, false) -{ - // 4J added initialiser - overrideTopTexture = NULL; +PistonExtensionTile::PistonExtensionTile(int id) + : Tile(id, Material::piston, false) { + // 4J added initialiser + overrideTopTexture = NULL; setSoundType(SOUND_STONE); setDestroyTime(0.5f); } -void PistonExtensionTile::setOverrideTopTexture(Icon *overrideTopTexture) -{ - this->overrideTopTexture = overrideTopTexture; +void PistonExtensionTile::setOverrideTopTexture(Icon* overrideTopTexture) { + this->overrideTopTexture = overrideTopTexture; } -void PistonExtensionTile::clearOverrideTopTexture() -{ - this->overrideTopTexture = NULL; +void PistonExtensionTile::clearOverrideTopTexture() { + this->overrideTopTexture = NULL; } -void PistonExtensionTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void PistonExtensionTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { Tile::onRemove(level, x, y, z, id, data); int facing = Facing::OPPOSITE_FACING[getFacing(data)]; x += Facing::STEP_X[facing]; @@ -33,178 +31,166 @@ void PistonExtensionTile::onRemove(Level *level, int x, int y, int z, int id, in int t = level->getTile(x, y, z); - if (t == Tile::pistonBase_Id || t == Tile::pistonStickyBase_Id) - { + if (t == Tile::pistonBase_Id || t == Tile::pistonStickyBase_Id) { data = level->getData(x, y, z); - if (PistonBaseTile::isExtended(data)) - { + if (PistonBaseTile::isExtended(data)) { Tile::tiles[t]->spawnResources(level, x, y, z, data, 0); level->setTile(x, y, z, 0); - } } } -Icon *PistonExtensionTile::getTexture(int face, int data) -{ +Icon* PistonExtensionTile::getTexture(int face, int data) { int facing = getFacing(data); - if (face == facing) - { - if (overrideTopTexture != NULL) - { + if (face == facing) { + if (overrideTopTexture != NULL) { return overrideTopTexture; } - if ((data & STICKY_BIT) != 0) - { - return PistonBaseTile::getTexture(PistonBaseTile::PLATFORM_STICKY_TEX); + if ((data & STICKY_BIT) != 0) { + return PistonBaseTile::getTexture( + PistonBaseTile::PLATFORM_STICKY_TEX); } return PistonBaseTile::getTexture(PistonBaseTile::PLATFORM_TEX); } - if (facing < 6 && face == Facing::OPPOSITE_FACING[facing]) - { + if (facing < 6 && face == Facing::OPPOSITE_FACING[facing]) { return PistonBaseTile::getTexture(PistonBaseTile::PLATFORM_TEX); } - return PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); // edge and arms + return PistonBaseTile::getTexture( + PistonBaseTile::EDGE_TEX); // edge and arms } -void PistonExtensionTile::registerIcons(IconRegister *iconRegister) -{ - // None +void PistonExtensionTile::registerIcons(IconRegister* iconRegister) { + // None } -int PistonExtensionTile::getRenderShape() -{ - return SHAPE_PISTON_EXTENSION; +int PistonExtensionTile::getRenderShape() { return SHAPE_PISTON_EXTENSION; } + +bool PistonExtensionTile::isSolidRender(bool isServerLevel) { return false; } + +bool PistonExtensionTile::isCubeShaped() { return false; } + +bool PistonExtensionTile::mayPlace(Level* level, int x, int y, int z) { + return false; } -bool PistonExtensionTile::isSolidRender(bool isServerLevel) -{ - return false; +bool PistonExtensionTile::mayPlace(Level* level, int x, int y, int z, + int face) { + return false; } -bool PistonExtensionTile::isCubeShaped() -{ - return false; -} +int PistonExtensionTile::getResourceCount(Random* random) { return 0; } -bool PistonExtensionTile::mayPlace(Level *level, int x, int y, int z) -{ - return false; -} - -bool PistonExtensionTile::mayPlace(Level *level, int x, int y, int z, int face) -{ - return false; -} - -int PistonExtensionTile::getResourceCount(Random *random) -{ - return 0; -} - -void PistonExtensionTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ +void PistonExtensionTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, + std::shared_ptr source) { int data = level->getData(x, y, z); const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - const float smallEdge1 = (8.0f - (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; - const float smallEdge2 = (8.0f + (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; - const float largeEdge1 = (8.0f - PistonBaseTile::PLATFORM_THICKNESS) / 16.0f; - const float largeEdge2 = (8.0f + PistonBaseTile::PLATFORM_THICKNESS) / 16.0f; + const float smallEdge1 = + (8.0f - (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float smallEdge2 = + (8.0f + (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float largeEdge1 = + (8.0f - PistonBaseTile::PLATFORM_THICKNESS) / 16.0f; + const float largeEdge2 = + (8.0f + PistonBaseTile::PLATFORM_THICKNESS) / 16.0f; - switch (getFacing(data)) - { - case Facing::DOWN: - setShape(0, 0, 0, 1, thickness, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(smallEdge1, thickness, smallEdge1, smallEdge2, 1, smallEdge2); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; - case Facing::UP: - setShape(0, 1 - thickness, 0, 1, 1, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(smallEdge1, 0, smallEdge1, smallEdge2, 1 - thickness, smallEdge2); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; - case Facing::NORTH: - setShape(0, 0, 0, 1, 1, thickness); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(largeEdge1, smallEdge1, thickness, largeEdge2, smallEdge2, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; - case Facing::SOUTH: - setShape(0, 0, 1 - thickness, 1, 1, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(largeEdge1, smallEdge1, 0, largeEdge2, smallEdge2, 1 - thickness); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; - case Facing::WEST: - setShape(0, 0, 0, thickness, 1, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(smallEdge1, largeEdge1, thickness, smallEdge2, largeEdge2, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; - case Facing::EAST: - setShape(1 - thickness, 0, 0, 1, 1, 1); - Tile::addAABBs(level, x, y, z, box, boxes, source); - setShape(0, smallEdge1, largeEdge1, 1 - thickness, smallEdge2, largeEdge2); - Tile::addAABBs(level, x, y, z, box, boxes, source); - break; + switch (getFacing(data)) { + case Facing::DOWN: + setShape(0, 0, 0, 1, thickness, 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(smallEdge1, thickness, smallEdge1, smallEdge2, 1, + smallEdge2); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; + case Facing::UP: + setShape(0, 1 - thickness, 0, 1, 1, 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(smallEdge1, 0, smallEdge1, smallEdge2, 1 - thickness, + smallEdge2); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; + case Facing::NORTH: + setShape(0, 0, 0, 1, 1, thickness); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(largeEdge1, smallEdge1, thickness, largeEdge2, smallEdge2, + 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; + case Facing::SOUTH: + setShape(0, 0, 1 - thickness, 1, 1, 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(largeEdge1, smallEdge1, 0, largeEdge2, smallEdge2, + 1 - thickness); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; + case Facing::WEST: + setShape(0, 0, 0, thickness, 1, 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(smallEdge1, largeEdge1, thickness, smallEdge2, largeEdge2, + 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; + case Facing::EAST: + setShape(1 - thickness, 0, 0, 1, 1, 1); + Tile::addAABBs(level, x, y, z, box, boxes, source); + setShape(0, smallEdge1, largeEdge1, 1 - thickness, smallEdge2, + largeEdge2); + Tile::addAABBs(level, x, y, z, box, boxes, source); + break; } setShape(0, 0, 0, 1, 1, 1); - } -void PistonExtensionTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void PistonExtensionTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - int data = (forceData == -1 ) ? level->getData(x, y, z) : forceData; + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - switch (getFacing(data)) - { - case Facing::DOWN: - setShape(0, 0, 0, 1, thickness, 1); - break; - case Facing::UP: - setShape(0, 1 - thickness, 0, 1, 1, 1); - break; - case Facing::NORTH: - setShape(0, 0, 0, 1, 1, thickness); - break; - case Facing::SOUTH: - setShape(0, 0, 1 - thickness, 1, 1, 1); - break; - case Facing::WEST: - setShape(0, 0, 0, thickness, 1, 1); - break; - case Facing::EAST: - setShape(1 - thickness, 0, 0, 1, 1, 1); - break; + switch (getFacing(data)) { + case Facing::DOWN: + setShape(0, 0, 0, 1, thickness, 1); + break; + case Facing::UP: + setShape(0, 1 - thickness, 0, 1, 1, 1); + break; + case Facing::NORTH: + setShape(0, 0, 0, 1, 1, thickness); + break; + case Facing::SOUTH: + setShape(0, 0, 1 - thickness, 1, 1, 1); + break; + case Facing::WEST: + setShape(0, 0, 0, thickness, 1, 1); + break; + case Facing::EAST: + setShape(1 - thickness, 0, 0, 1, 1, 1); + break; } } -void PistonExtensionTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void PistonExtensionTile::neighborChanged(Level* level, int x, int y, int z, + int type) { int facing = getFacing(level->getData(x, y, z)); - int tile = level->getTile(x - Facing::STEP_X[facing], y - Facing::STEP_Y[facing], z - Facing::STEP_Z[facing]); - if (tile != Tile::pistonBase_Id && tile != Tile::pistonStickyBase_Id) - { + int tile = + level->getTile(x - Facing::STEP_X[facing], y - Facing::STEP_Y[facing], + z - Facing::STEP_Z[facing]); + if (tile != Tile::pistonBase_Id && tile != Tile::pistonStickyBase_Id) { level->setTile(x, y, z, 0); - } - else - { - Tile::tiles[tile]->neighborChanged(level, x - Facing::STEP_X[facing], y - Facing::STEP_Y[facing], z - Facing::STEP_Z[facing], type); + } else { + Tile::tiles[tile]->neighborChanged(level, x - Facing::STEP_X[facing], + y - Facing::STEP_Y[facing], + z - Facing::STEP_Z[facing], type); } } -int PistonExtensionTile::getFacing(int data) -{ - return data & 0x7; -} +int PistonExtensionTile::getFacing(int data) { return data & 0x7; } -int PistonExtensionTile::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; +int PistonExtensionTile::cloneTileId(Level* level, int x, int y, int z) { + return 0; } diff --git a/Minecraft.World/Blocks/PistonExtensionTile.h b/Minecraft.World/Blocks/PistonExtensionTile.h index 8ebb9bd1e..ac0196e87 100644 --- a/Minecraft.World/Blocks/PistonExtensionTile.h +++ b/Minecraft.World/Blocks/PistonExtensionTile.h @@ -1,31 +1,34 @@ #pragma once #include "Tile.h" -class PistonExtensionTile : public Tile -{ +class PistonExtensionTile : public Tile { public: // i'm reusing this block for the sticky pistons static const int STICKY_BIT = 8; private: - Icon *overrideTopTexture; + Icon* overrideTopTexture; public: - PistonExtensionTile(int id); - void setOverrideTopTexture(Icon *overrideTopTexture); - void clearOverrideTopTexture(); - void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); + PistonExtensionTile(int id); + void setOverrideTopTexture(Icon* overrideTopTexture); + void clearOverrideTopTexture(); + void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); virtual int getRenderShape(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); - virtual int getResourceCount(Random *random); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); + virtual int getResourceCount(Random* random); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual void neighborChanged(Level* level, int x, int y, int z, int type); static int getFacing(int data); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual int cloneTileId(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/PistonMovingTileEntity.cpp b/Minecraft.World/Blocks/PistonMovingTileEntity.cpp index 452669097..27587ceca 100644 --- a/Minecraft.World/Blocks/PistonMovingTileEntity.cpp +++ b/Minecraft.World/Blocks/PistonMovingTileEntity.cpp @@ -6,64 +6,51 @@ #include "../Util/Facing.h" #include "../Util/AABB.h" -PistonMovingPiece::PistonMovingPiece(int id) : EntityTile(id, Material::piston, false ) -{ - setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME); +PistonMovingPiece::PistonMovingPiece(int id) + : EntityTile(id, Material::piston, false) { + setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME); } -std::shared_ptr PistonMovingPiece::newTileEntity(Level *level) -{ - return nullptr; +std::shared_ptr PistonMovingPiece::newTileEntity(Level* level) { + return nullptr; } -void PistonMovingPiece::onPlace(Level *level, int x, int y, int z) -{ -} +void PistonMovingPiece::onPlace(Level* level, int x, int y, int z) {} -void PistonMovingPiece::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void PistonMovingPiece::onRemove(Level* level, int x, int y, int z, int id, + int data) { std::shared_ptr tileEntity = level->getTileEntity(x, y, z); - if (tileEntity != NULL && std::dynamic_pointer_cast(tileEntity) != NULL) - { + if (tileEntity != NULL && + std::dynamic_pointer_cast(tileEntity) != NULL) { std::dynamic_pointer_cast(tileEntity)->finalTick(); - } - else - { + } else { EntityTile::onRemove(level, x, y, z, id, data); } } -bool PistonMovingPiece::mayPlace(Level *level, int x, int y, int z) -{ - return false; +bool PistonMovingPiece::mayPlace(Level* level, int x, int y, int z) { + return false; } -bool PistonMovingPiece::mayPlace(Level *level, int x, int y, int z, int face) -{ - return false; +bool PistonMovingPiece::mayPlace(Level* level, int x, int y, int z, int face) { + return false; } -int PistonMovingPiece::getRenderShape() -{ - return SHAPE_INVISIBLE; -} +int PistonMovingPiece::getRenderShape() { return SHAPE_INVISIBLE; } -bool PistonMovingPiece::isSolidRender(bool isServerLevel) -{ - return false; -} +bool PistonMovingPiece::isSolidRender(bool isServerLevel) { return false; } -bool PistonMovingPiece::isCubeShaped() -{ - return false; -} +bool PistonMovingPiece::isCubeShaped() { return false; } -bool PistonMovingPiece::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool PistonMovingPiece::use( + Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly) return false; - // this is a special case in order to help removing invisible, unbreakable, blocks in the world - if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL) - { + if (soundOnly) return false; + // this is a special case in order to help removing invisible, unbreakable, + // blocks in the world + if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL) { // this block is no longer valid level->setTile(x, y, z, 0); return true; @@ -71,73 +58,72 @@ bool PistonMovingPiece::use(Level *level, int x, int y, int z, std::shared_ptr

isClientSide) return; std::shared_ptr entity = getEntity(level, x, y, z); - if (entity == NULL) - { + if (entity == NULL) { return; } - Tile::tiles[entity->getId()]->spawnResources(level, x, y, z, entity->getData(), 0); + Tile::tiles[entity->getId()]->spawnResources(level, x, y, z, + entity->getData(), 0); } -void PistonMovingPiece::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL) - { +void PistonMovingPiece::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (!level->isClientSide && level->getTileEntity(x, y, z) == NULL) { } } -std::shared_ptr PistonMovingPiece::newMovingPieceEntity(int block, int data, int facing, bool extending, bool isSourcePiston) -{ - return std::shared_ptr(new PistonPieceEntity(block, data, facing, extending, isSourcePiston)); +std::shared_ptr PistonMovingPiece::newMovingPieceEntity( + int block, int data, int facing, bool extending, bool isSourcePiston) { + return std::shared_ptr( + new PistonPieceEntity(block, data, facing, extending, isSourcePiston)); } -AABB *PistonMovingPiece::getAABB(Level *level, int x, int y, int z) -{ +AABB* PistonMovingPiece::getAABB(Level* level, int x, int y, int z) { std::shared_ptr entity = getEntity(level, x, y, z); - if (entity == NULL) - { + if (entity == NULL) { return NULL; } // move the aabb depending on the animation float progress = entity->getProgress(0); - if (entity->isExtending()) - { + if (entity->isExtending()) { progress = 1.0f - progress; } - return getAABB(level, x, y, z, entity->getId(), progress, entity->getFacing()); + return getAABB(level, x, y, z, entity->getId(), progress, + entity->getFacing()); } -void PistonMovingPiece::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void PistonMovingPiece::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - std::shared_ptr entity = std::dynamic_pointer_cast(forceEntity); - if( entity == NULL ) entity = getEntity(level, x, y, z); - if (entity != NULL) - { - Tile *tile = Tile::tiles[entity->getId()]; - if (tile == NULL || tile == this) - { + std::shared_ptr entity = + std::dynamic_pointer_cast(forceEntity); + if (entity == NULL) entity = getEntity(level, x, y, z); + if (entity != NULL) { + Tile* tile = Tile::tiles[entity->getId()]; + if (tile == NULL || tile == this) { return; } tile->updateShape(level, x, y, z); float progress = entity->getProgress(0); - if (entity->isExtending()) - { + if (entity->isExtending()) { progress = 1.0f - progress; } int facing = entity->getFacing(); - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); tls->xx0 = tile->getShapeX0() - Facing::STEP_X[facing] * progress; tls->yy0 = tile->getShapeY0() - Facing::STEP_Y[facing] * progress; tls->zz0 = tile->getShapeZ0() - Facing::STEP_Z[facing] * progress; @@ -147,65 +133,52 @@ void PistonMovingPiece::updateShape(LevelSource *level, int x, int y, int z, int } } -AABB *PistonMovingPiece::getAABB(Level *level, int x, int y, int z, int tile, float progress, int facing) -{ - if (tile == 0 || tile == id) - { - return NULL; +AABB* PistonMovingPiece::getAABB(Level* level, int x, int y, int z, int tile, + float progress, int facing) { + if (tile == 0 || tile == id) { + return NULL; } - AABB *aabb = Tile::tiles[tile]->getAABB(level, x, y, z); + AABB* aabb = Tile::tiles[tile]->getAABB(level, x, y, z); - if (aabb == NULL) - { + if (aabb == NULL) { return NULL; } // move the aabb depending on the animation - if (Facing::STEP_X[facing] < 0) - { - aabb->x0 -= Facing::STEP_X[facing] * progress; - } - else - { - aabb->x1 -= Facing::STEP_X[facing] * progress; - } - if (Facing::STEP_Y[facing] < 0) - { - aabb->y0 -= Facing::STEP_Y[facing] * progress; - } - else - { - aabb->y1 -= Facing::STEP_Y[facing] * progress; - } - if (Facing::STEP_Z[facing] < 0) - { - aabb->z0 -= Facing::STEP_Z[facing] * progress; - } - else - { - aabb->z1 -= Facing::STEP_Z[facing] * progress; - } + if (Facing::STEP_X[facing] < 0) { + aabb->x0 -= Facing::STEP_X[facing] * progress; + } else { + aabb->x1 -= Facing::STEP_X[facing] * progress; + } + if (Facing::STEP_Y[facing] < 0) { + aabb->y0 -= Facing::STEP_Y[facing] * progress; + } else { + aabb->y1 -= Facing::STEP_Y[facing] * progress; + } + if (Facing::STEP_Z[facing] < 0) { + aabb->z0 -= Facing::STEP_Z[facing] * progress; + } else { + aabb->z1 -= Facing::STEP_Z[facing] * progress; + } return aabb; } -std::shared_ptr PistonMovingPiece::getEntity(LevelSource *level, int x, int y, int z) -{ +std::shared_ptr PistonMovingPiece::getEntity( + LevelSource* level, int x, int y, int z) { std::shared_ptr tileEntity = level->getTileEntity(x, y, z); - if (tileEntity != NULL && std::dynamic_pointer_cast(tileEntity) != NULL) - { - return std::dynamic_pointer_cast(tileEntity); + if (tileEntity != NULL && + std::dynamic_pointer_cast(tileEntity) != NULL) { + return std::dynamic_pointer_cast(tileEntity); } return nullptr; } -void PistonMovingPiece::registerIcons(IconRegister *iconRegister) -{ - // don't register null, register piston top instead (to get proper - // particle effect) - icon = iconRegister->registerIcon(L"piston_top"); +void PistonMovingPiece::registerIcons(IconRegister* iconRegister) { + // don't register null, register piston top instead (to get proper + // particle effect) + icon = iconRegister->registerIcon(L"piston_top"); } -int PistonMovingPiece::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; +int PistonMovingPiece::cloneTileId(Level* level, int x, int y, int z) { + return 0; } diff --git a/Minecraft.World/Blocks/PistonMovingTileEntity.h b/Minecraft.World/Blocks/PistonMovingTileEntity.h index 42426ffca..92f266681 100644 --- a/Minecraft.World/Blocks/PistonMovingTileEntity.h +++ b/Minecraft.World/Blocks/PistonMovingTileEntity.h @@ -3,36 +3,45 @@ class PistonPieceEntity; -class PistonMovingPiece : public EntityTile -{ +class PistonMovingPiece : public EntityTile { public: - PistonMovingPiece(int id); + PistonMovingPiece(int id); protected: - virtual std::shared_ptr newTileEntity(Level *level); + virtual std::shared_ptr newTileEntity(Level* level); public: - virtual void onPlace(Level *level, int x, int y, int z); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); virtual int getRenderShape(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param; - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - static std::shared_ptr newMovingPieceEntity(int block, int data, int facing, bool extending, bool isSourcePiston); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param; + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + static std::shared_ptr newMovingPieceEntity( + int block, int data, int facing, bool extending, bool isSourcePiston); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param - AABB *getAABB(Level *level, int x, int y, int z, int tile, float progress, int facing); + AABB* getAABB(Level* level, int x, int y, int z, int tile, float progress, + int facing); private: - std::shared_ptr getEntity(LevelSource *level, int x, int y, int z); + std::shared_ptr getEntity(LevelSource* level, int x, + int y, int z); public: - virtual int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); + virtual int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/PlantTile.cpp b/Minecraft.World/Blocks/PlantTile.cpp index eb4d2dfca..9b03d0449 100644 --- a/Minecraft.World/Blocks/PlantTile.cpp +++ b/Minecraft.World/Blocks/PlantTile.cpp @@ -3,85 +3,59 @@ #include "GrassTile.h" #include "PlantTile.h" -void Bush::_init() -{ +void Bush::_init() { setTicking(true); updateDefaultShape(); } -Bush::Bush(int id, Material *material) : Tile(id, material, false) -{ - _init(); -} +Bush::Bush(int id, Material* material) : Tile(id, material, false) { _init(); } -Bush::Bush(int id) : Tile(id, Material::plant, false) -{ - _init(); -} +Bush::Bush(int id) : Tile(id, Material::plant, false) { _init(); } // 4J Added override -void Bush::updateDefaultShape() -{ +void Bush::updateDefaultShape() { float ss = 0.2f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, ss * 3, 0.5f + ss); } -bool Bush::mayPlace(Level *level, int x, int y, int z) -{ - return Tile::mayPlace(level, x, y, z) && mayPlaceOn(level->getTile(x, y - 1, z)); +bool Bush::mayPlace(Level* level, int x, int y, int z) { + return Tile::mayPlace(level, x, y, z) && + mayPlaceOn(level->getTile(x, y - 1, z)); } -bool Bush::mayPlaceOn(int tile) -{ - return tile == Tile::grass_Id || tile == Tile::dirt_Id || tile == Tile::farmland_Id; +bool Bush::mayPlaceOn(int tile) { + return tile == Tile::grass_Id || tile == Tile::dirt_Id || + tile == Tile::farmland_Id; } -void Bush::neighborChanged(Level *level, int x, int y, int z, int type) -{ - Tile::neighborChanged(level, x, y, z, type); - checkAlive(level, x, y, z); +void Bush::neighborChanged(Level* level, int x, int y, int z, int type) { + Tile::neighborChanged(level, x, y, z, type); + checkAlive(level, x, y, z); } -void Bush::tick(Level *level, int x, int y, int z, Random *random) -{ - checkAlive(level, x, y, z); +void Bush::tick(Level* level, int x, int y, int z, Random* random) { + checkAlive(level, x, y, z); } -void Bush::checkAlive(Level *level, int x, int y, int z) -{ - if (!canSurvive(level, x, y, z)) - { +void Bush::checkAlive(Level* level, int x, int y, int z) { + if (!canSurvive(level, x, y, z)) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } } -bool Bush::canSurvive(Level *level, int x, int y, int z) -{ - return ( level->getDaytimeRawBrightness(x, y, z) >= 8 || (level->canSeeSky(x, y, z))) && mayPlaceOn(level->getTile(x, y - 1, z)); +bool Bush::canSurvive(Level* level, int x, int y, int z) { + return (level->getDaytimeRawBrightness(x, y, z) >= 8 || + (level->canSeeSky(x, y, z))) && + mayPlaceOn(level->getTile(x, y - 1, z)); } -AABB *Bush::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} +AABB* Bush::getAABB(Level* level, int x, int y, int z) { return NULL; } -bool Bush::blocksLight() -{ - return false; -} +bool Bush::blocksLight() { return false; } -bool Bush::isSolidRender(bool isServerLevel) -{ - return false; -} +bool Bush::isSolidRender(bool isServerLevel) { return false; } -bool Bush::isCubeShaped() -{ - return false; -} +bool Bush::isCubeShaped() { return false; } -int Bush::getRenderShape() -{ - return Tile::SHAPE_CROSS_TEXTURE; -} +int Bush::getRenderShape() { return Tile::SHAPE_CROSS_TEXTURE; } diff --git a/Minecraft.World/Blocks/PlantTile.h b/Minecraft.World/Blocks/PlantTile.h index 3cc3a08dd..53ebbcb46 100644 --- a/Minecraft.World/Blocks/PlantTile.h +++ b/Minecraft.World/Blocks/PlantTile.h @@ -6,34 +6,33 @@ class Random; class Level; -class Bush : public Tile -{ - friend class Tile; +class Bush : public Tile { + friend class Tile; private: - void _init(); + void _init(); protected: - Bush(int id, Material *material); - Bush(int id); + Bush(int id, Material* material); + Bush(int id); public: - virtual void updateDefaultShape(); - virtual bool mayPlace(Level *level, int x, int y, int z); + virtual void updateDefaultShape(); + virtual bool mayPlace(Level* level, int x, int y, int z); protected: - virtual bool mayPlaceOn(int tile); + virtual bool mayPlaceOn(int tile); public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); protected: - void checkAlive(Level *level, int x, int y, int z); + void checkAlive(Level* level, int x, int y, int z); public: - virtual bool canSurvive(Level *level, int x, int y, int z); - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual bool canSurvive(Level* level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); diff --git a/Minecraft.World/Blocks/PortalMaterial.h b/Minecraft.World/Blocks/PortalMaterial.h index ae40dbec1..300f74de7 100644 --- a/Minecraft.World/Blocks/PortalMaterial.h +++ b/Minecraft.World/Blocks/PortalMaterial.h @@ -1,12 +1,11 @@ #pragma once #include "Material.h" -class PortalMaterial : public Material -{ +class PortalMaterial : public Material { public: - PortalMaterial(MaterialColor *color) : Material(color) { } + PortalMaterial(MaterialColor* color) : Material(color) {} - virtual bool isSolid() { return false; } - virtual bool blocksLight() { return false; } - virtual bool blocksMotion() { return false; } + virtual bool isSolid() { return false; } + virtual bool blocksLight() { return false; } + virtual bool blocksMotion() { return false; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/PortalTile.cpp b/Minecraft.World/Blocks/PortalTile.cpp index ba5c80eeb..64a9ee0f2 100644 --- a/Minecraft.World/Blocks/PortalTile.cpp +++ b/Minecraft.World/Blocks/PortalTile.cpp @@ -6,173 +6,160 @@ #include "PortalTile.h" #include "FireTile.h" -PortalTile::PortalTile(int id) : HalfTransparentTile(id, L"portal", Material::portal, false) -{ - setTicking(true); +PortalTile::PortalTile(int id) + : HalfTransparentTile(id, L"portal", Material::portal, false) { + setTicking(true); } -void PortalTile::tick(Level *level, int x, int y, int z, Random *random) -{ - HalfTransparentTile::tick(level, x, y, z, random); +void PortalTile::tick(Level* level, int x, int y, int z, Random* random) { + HalfTransparentTile::tick(level, x, y, z, random); - if (level->dimension->isNaturalDimension() && random->nextInt(2000) < level->difficulty) - { - // locate floor - int y0 = y; - while (!level->isTopSolidBlocking(x, y0, z) && y0 > 0) - { - y0--; - } - if (y0 > 0 && !level->isSolidBlockingTile(x, y0 + 1, z)) - { - // spawn a pig man here - int result = 0; - bool spawned = MonsterPlacerItem::spawnMobAt(level, 57, x + .5, y0 + 1.1, z + .5, &result) != NULL; - } - } + if (level->dimension->isNaturalDimension() && + random->nextInt(2000) < level->difficulty) { + // locate floor + int y0 = y; + while (!level->isTopSolidBlocking(x, y0, z) && y0 > 0) { + y0--; + } + if (y0 > 0 && !level->isSolidBlockingTile(x, y0 + 1, z)) { + // spawn a pig man here + int result = 0; + bool spawned = + MonsterPlacerItem::spawnMobAt(level, 57, x + .5, y0 + 1.1, + z + .5, &result) != NULL; + } + } } -AABB *PortalTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} +AABB* PortalTile::getAABB(Level* level, int x, int y, int z) { return NULL; } -void PortalTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void PortalTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - if (level->getTile(x - 1, y, z) == id || level->getTile(x + 1, y, z) == id) - { + if (level->getTile(x - 1, y, z) == id || + level->getTile(x + 1, y, z) == id) { float xr = 8 / 16.0f; float yr = 2 / 16.0f; this->setShape(0.5f - xr, 0, 0.5f - yr, 0.5f + xr, 1, 0.5f + yr); - } - else - { + } else { float xr = 2 / 16.0f; float yr = 8 / 16.0f; this->setShape(0.5f - xr, 0, 0.5f - yr, 0.5f + xr, 1, 0.5f + yr); } } -bool PortalTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool PortalTile::isSolidRender(bool isServerLevel) { return false; } -bool PortalTile::isCubeShaped() -{ - return false; -} +bool PortalTile::isCubeShaped() { return false; } -bool PortalTile::trySpawnPortal(Level *level, int x, int y, int z, bool actuallySpawn) -{ +bool PortalTile::trySpawnPortal(Level* level, int x, int y, int z, + bool actuallySpawn) { int xd = 0; int zd = 0; - if (level->getTile(x - 1, y, z) == Tile::obsidian_Id || level->getTile(x + 1, y, z) == Tile::obsidian_Id) xd = 1; - if (level->getTile(x, y, z - 1) == Tile::obsidian_Id || level->getTile(x, y, z + 1) == Tile::obsidian_Id) zd = 1; + if (level->getTile(x - 1, y, z) == Tile::obsidian_Id || + level->getTile(x + 1, y, z) == Tile::obsidian_Id) + xd = 1; + if (level->getTile(x, y, z - 1) == Tile::obsidian_Id || + level->getTile(x, y, z + 1) == Tile::obsidian_Id) + zd = 1; if (xd == zd) return false; - if (level->getTile(x - xd, y, z - zd) == 0) - { + if (level->getTile(x - xd, y, z - zd) == 0) { x -= xd; z -= zd; } - for (int xx = -1; xx <= 2; xx++) - { - for (int yy = -1; yy <= 3; yy++) - { + for (int xx = -1; xx <= 2; xx++) { + for (int yy = -1; yy <= 3; yy++) { bool edge = (xx == -1) || (xx == 2) || (yy == -1) || (yy == 3); if ((xx == -1 || xx == 2) && (yy == -1 || yy == 3)) continue; int t = level->getTile(x + xd * xx, y + yy, z + zd * xx); - if (edge) - { + if (edge) { if (t != Tile::obsidian_Id) return false; - } - else - { + } else { if (t != 0 && t != Tile::fire_Id) return false; } } } - if( !actuallySpawn ) - return true; + if (!actuallySpawn) return true; level->noNeighborUpdate = true; - for (int xx = 0; xx < 2; xx++) - { - for (int yy = 0; yy < 3; yy++) - { - level->setTile(x + xd * xx, y + yy, z + zd * xx, Tile::portalTile_Id); + for (int xx = 0; xx < 2; xx++) { + for (int yy = 0; yy < 3; yy++) { + level->setTile(x + xd * xx, y + yy, z + zd * xx, + Tile::portalTile_Id); } } level->noNeighborUpdate = false; return true; - } -void PortalTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void PortalTile::neighborChanged(Level* level, int x, int y, int z, int type) { int xd = 0; int zd = 1; - if (level->getTile(x - 1, y, z) == id || level->getTile(x + 1, y, z) == id) - { + if (level->getTile(x - 1, y, z) == id || + level->getTile(x + 1, y, z) == id) { xd = 1; zd = 0; } int yBottom = y; - while (level->getTile(x, yBottom - 1, z) == id) - yBottom--; + while (level->getTile(x, yBottom - 1, z) == id) yBottom--; - if (level->getTile(x, yBottom - 1, z) != Tile::obsidian_Id) - { + if (level->getTile(x, yBottom - 1, z) != Tile::obsidian_Id) { level->setTile(x, y, z, 0); return; } int height = 1; - while (height < 4 && level->getTile(x, yBottom + height, z) == id) - height++; + while (height < 4 && level->getTile(x, yBottom + height, z) == id) height++; - if (height != 3 || level->getTile(x, yBottom + height, z) != Tile::obsidian_Id) - { + if (height != 3 || + level->getTile(x, yBottom + height, z) != Tile::obsidian_Id) { level->setTile(x, y, z, 0); return; } - bool we = level->getTile(x - 1, y, z) == id || level->getTile(x + 1, y, z) == id; - bool ns = level->getTile(x, y, z - 1) == id || level->getTile(x, y, z + 1) == id; - if (we && ns) - { + bool we = + level->getTile(x - 1, y, z) == id || level->getTile(x + 1, y, z) == id; + bool ns = + level->getTile(x, y, z - 1) == id || level->getTile(x, y, z + 1) == id; + if (we && ns) { level->setTile(x, y, z, 0); return; } - if (!(// - (level->getTile(x + xd, y, z + zd) == Tile::obsidian_Id && level->getTile(x - xd, y, z - zd) == id) || // - (level->getTile(x - xd, y, z - zd) == Tile::obsidian_Id && level->getTile(x + xd, y, z + zd) == id)// - )) - { + if (!( // + (level->getTile(x + xd, y, z + zd) == Tile::obsidian_Id && + level->getTile(x - xd, y, z - zd) == id) || // + (level->getTile(x - xd, y, z - zd) == Tile::obsidian_Id && + level->getTile(x + xd, y, z + zd) == id) // + )) { level->setTile(x, y, z, 0); return; } - } -bool PortalTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ +bool PortalTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { if (level->getTile(x, y, z) == id) return false; - bool w = level->getTile(x - 1, y, z) == id && level->getTile(x - 2, y, z) != id; - bool e = level->getTile(x + 1, y, z) == id && level->getTile(x + 2, y, z) != id; + bool w = + level->getTile(x - 1, y, z) == id && level->getTile(x - 2, y, z) != id; + bool e = + level->getTile(x + 1, y, z) == id && level->getTile(x + 2, y, z) != id; - bool n = level->getTile(x, y, z - 1) == id && level->getTile(x, y, z - 2) != id; - bool s = level->getTile(x, y, z + 1) == id && level->getTile(x, y, z + 2) != id; + bool n = + level->getTile(x, y, z - 1) == id && level->getTile(x, y, z - 2) != id; + bool s = + level->getTile(x, y, z + 1) == id && level->getTile(x, y, z + 2) != id; bool we = w || e; bool ns = n || s; @@ -185,29 +172,24 @@ bool PortalTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int f return false; } -int PortalTile::getResourceCount(Random *random) -{ - return 0; +int PortalTile::getResourceCount(Random* random) { return 0; } + +int PortalTile::getRenderLayer() { return 1; } + +void PortalTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (entity->riding == NULL && entity->rider.lock() == NULL) + entity->handleInsidePortal(); } -int PortalTile::getRenderLayer() -{ - return 1; -} - -void PortalTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (entity->riding == NULL && entity->rider.lock() == NULL) entity->handleInsidePortal(); -} - -void PortalTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ - if (random->nextInt(100) == 0) - { - level->playLocalSound(xt + 0.5, yt + 0.5, zt + 0.5, eSoundType_PORTAL_PORTAL, 0.5f, random->nextFloat() * 0.4f + 0.8f); +void PortalTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { + if (random->nextInt(100) == 0) { + level->playLocalSound(xt + 0.5, yt + 0.5, zt + 0.5, + eSoundType_PORTAL_PORTAL, 0.5f, + random->nextFloat() * 0.4f + 0.8f); } - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { double x = xt + random->nextFloat(); double y = yt + random->nextFloat(); double z = zt + random->nextFloat(); @@ -218,13 +200,11 @@ void PortalTile::animateTick(Level *level, int xt, int yt, int zt, Random *rando xa = (random->nextFloat() - 0.5) * 0.5; ya = (random->nextFloat() - 0.5) * 0.5; za = (random->nextFloat() - 0.5) * 0.5; - if (level->getTile(xt - 1, yt, zt) == id || level->getTile(xt + 1, yt, zt) == id) - { + if (level->getTile(xt - 1, yt, zt) == id || + level->getTile(xt + 1, yt, zt) == id) { z = zt + 0.5 + (0.25) * flip; za = (random->nextFloat() * 2) * flip; - } - else - { + } else { x = xt + 0.5 + (0.25) * flip; xa = (random->nextFloat() * 2) * flip; } @@ -233,14 +213,8 @@ void PortalTile::animateTick(Level *level, int xt, int yt, int zt, Random *rando } } -int PortalTile::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; -} +int PortalTile::cloneTileId(Level* level, int x, int y, int z) { return 0; } -// 4J Added - We cannot collect the portal tile, so don't consider it as a hit result -// Bug #754 - Riding a minecart into a portal will trap the player -bool PortalTile::mayPick() -{ - return false; -} +// 4J Added - We cannot collect the portal tile, so don't consider it as a hit +// result Bug #754 - Riding a minecart into a portal will trap the player +bool PortalTile::mayPick() { return false; } diff --git a/Minecraft.World/Blocks/PortalTile.h b/Minecraft.World/Blocks/PortalTile.h index e727d0389..b498fb1ac 100644 --- a/Minecraft.World/Blocks/PortalTile.h +++ b/Minecraft.World/Blocks/PortalTile.h @@ -4,22 +4,28 @@ class Random; -class PortalTile : public HalfTransparentTile -{ +class PortalTile : public HalfTransparentTile { public: - PortalTile(int id); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + PortalTile(int id); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual bool trySpawnPortal(Level *level, int x, int y, int z, bool actuallySpawn); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual int getResourceCount(Random *random); + virtual bool trySpawnPortal(Level* level, int x, int y, int z, + bool actuallySpawn); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual int getResourceCount(Random* random); virtual int getRenderLayer(); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); - virtual int cloneTileId(Level *level, int x, int y, int z); - virtual bool mayPick(); // 4J Added override + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); + virtual int cloneTileId(Level* level, int x, int y, int z); + virtual bool mayPick(); // 4J Added override }; diff --git a/Minecraft.World/Blocks/PotatoTile.cpp b/Minecraft.World/Blocks/PotatoTile.cpp index 3dc261476..b96ea84c1 100644 --- a/Minecraft.World/Blocks/PotatoTile.cpp +++ b/Minecraft.World/Blocks/PotatoTile.cpp @@ -4,57 +4,41 @@ #include "../Headers/net.minecraft.world.h" #include "PotatoTile.h" -PotatoTile::PotatoTile(int id) : CropTile(id) -{ +PotatoTile::PotatoTile(int id) : CropTile(id) {} + +Icon* PotatoTile::getTexture(int face, int data) { + if (data < 7) { + if (data == 6) { + data = 5; + } + return icons[data >> 1]; + } else { + return icons[3]; + } } -Icon *PotatoTile::getTexture(int face, int data) -{ - if (data < 7) - { - if (data == 6) - { - data = 5; - } - return icons[data >> 1]; - } - else - { - return icons[3]; - } +int PotatoTile::getBaseSeedId() { return Item::potato_Id; } + +int PotatoTile::getBasePlantId() { return Item::potato_Id; } + +void PotatoTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus) { + CropTile::spawnResources(level, x, y, z, data, odds, playerBonus); + + if (level->isClientSide) { + return; + } + if (data >= 7) { + if (level->random->nextInt(50) == 0) { + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(Item::potatoPoisonous))); + } + } } -int PotatoTile::getBaseSeedId() -{ - return Item::potato_Id; -} - -int PotatoTile::getBasePlantId() -{ - return Item::potato_Id; -} - -void PotatoTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ - CropTile::spawnResources(level, x, y, z, data, odds, playerBonus); - - if (level->isClientSide) - { - return; - } - if (data >= 7) - { - if (level->random->nextInt(50) == 0) - { - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Item::potatoPoisonous))); - } - } -} - -void PotatoTile::registerIcons(IconRegister *iconRegister) -{ - for (int i = 0; i < 4; i++) - { - icons[i] = iconRegister->registerIcon(L"potatoes_" + _toString(i)); - } +void PotatoTile::registerIcons(IconRegister* iconRegister) { + for (int i = 0; i < 4; i++) { + icons[i] = iconRegister->registerIcon(L"potatoes_" + _toString(i)); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/PotatoTile.h b/Minecraft.World/Blocks/PotatoTile.h index 8ce5960a6..341bae497 100644 --- a/Minecraft.World/Blocks/PotatoTile.h +++ b/Minecraft.World/Blocks/PotatoTile.h @@ -2,22 +2,23 @@ #include "CropTile.h" -class PotatoTile : public CropTile -{ - friend class ChunkRebuildData; +class PotatoTile : public CropTile { + friend class ChunkRebuildData; + private: - Icon *icons[4]; + Icon* icons[4]; public: - PotatoTile(int id); + PotatoTile(int id); - Icon *getTexture(int face, int data); + Icon* getTexture(int face, int data); protected: - int getBaseSeedId(); - int getBasePlantId(); + int getBaseSeedId(); + int getBasePlantId(); public: - void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); - void registerIcons(IconRegister *iconRegister); + void spawnResources(Level* level, int x, int y, int z, int data, float odds, + int playerBonus); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/PressurePlateTile.cpp b/Minecraft.World/Blocks/PressurePlateTile.cpp index 9f383b474..655d9bb74 100644 --- a/Minecraft.World/Blocks/PressurePlateTile.cpp +++ b/Minecraft.World/Blocks/PressurePlateTile.cpp @@ -7,205 +7,185 @@ #include "PressurePlateTile.h" #include "../Util/SoundTypes.h" -PressurePlateTile::PressurePlateTile(int id, const std::wstring &tex, Material *material, Sensitivity sensitivity) : Tile(id, material, false) -{ - this->sensitivity = sensitivity; - this->setTicking(true); - this->texture = tex; +PressurePlateTile::PressurePlateTile(int id, const std::wstring& tex, + Material* material, + Sensitivity sensitivity) + : Tile(id, material, false) { + this->sensitivity = sensitivity; + this->setTicking(true); + this->texture = tex; - float o = 1 / 16.0f; - setShape(o, 0, o, 1 - o, 0.5f / 16.0f, 1 - o); + float o = 1 / 16.0f; + setShape(o, 0, o, 1 - o, 0.5f / 16.0f, 1 - o); } -int PressurePlateTile::getTickDelay() -{ - return 20; +int PressurePlateTile::getTickDelay() { return 20; } + +AABB* PressurePlateTile::getAABB(Level* level, int x, int y, int z) { + return NULL; } -AABB *PressurePlateTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +bool PressurePlateTile::isSolidRender(bool isServerLevel) { return false; } + +bool PressurePlateTile::blocksLight() { return false; } + +bool PressurePlateTile::isCubeShaped() { return false; } + +bool PressurePlateTile::isPathfindable(LevelSource* level, int x, int y, + int z) { + return true; } -bool PressurePlateTile::isSolidRender(bool isServerLevel) -{ - return false; +bool PressurePlateTile::mayPlace(Level* level, int x, int y, int z) { + return level->isTopSolidBlocking(x, y - 1, z) || + FenceTile::isFence(level->getTile(x, y - 1, z)); } -bool PressurePlateTile::blocksLight() -{ - return false; -} - -bool PressurePlateTile::isCubeShaped() -{ - return false; -} - -bool PressurePlateTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return true; -} - -bool PressurePlateTile::mayPlace(Level *level, int x, int y, int z) -{ - return level->isTopSolidBlocking(x, y - 1, z) || FenceTile::isFence(level->getTile(x, y - 1, z)); -} - -void PressurePlateTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ +void PressurePlateTile::neighborChanged(Level* level, int x, int y, int z, + int type) { bool replace = false; - if (!level->isTopSolidBlocking(x, y - 1, z) && !FenceTile::isFence(level->getTile(x, y - 1, z))) replace = true; + if (!level->isTopSolidBlocking(x, y - 1, z) && + !FenceTile::isFence(level->getTile(x, y - 1, z))) + replace = true; - if (replace) - { + if (replace) { this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } } -void PressurePlateTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void PressurePlateTile::tick(Level* level, int x, int y, int z, + Random* random) { if (level->isClientSide) return; - if (level->getData(x, y, z) == 0) - { + if (level->getData(x, y, z) == 0) { return; } checkPressed(level, x, y, z); } -void PressurePlateTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ +void PressurePlateTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { if (level->isClientSide) return; - if (level->getData(x, y, z) == 1) - { + if (level->getData(x, y, z) == 1) { return; } checkPressed(level, x, y, z); } -void PressurePlateTile::checkPressed(Level *level, int x, int y, int z) -{ +void PressurePlateTile::checkPressed(Level* level, int x, int y, int z) { bool wasPressed = level->getData(x, y, z) == 1; bool shouldBePressed = false; float b = 2 / 16.0f; - std::vector > *entities = NULL; + std::vector >* entities = NULL; - bool entitiesToBeFreed = false; - if (sensitivity == PressurePlateTile::everything) entities = level->getEntities(nullptr, AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); + bool entitiesToBeFreed = false; + if (sensitivity == PressurePlateTile::everything) + entities = level->getEntities( + nullptr, + AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); - if (sensitivity == PressurePlateTile::mobs) - { - entities = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); - entitiesToBeFreed = true; - } - if (sensitivity == PressurePlateTile::players) - { - entities = level->getEntitiesOfClass(typeid(Player), AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); - entitiesToBeFreed = true; - } + if (sensitivity == PressurePlateTile::mobs) { + entities = level->getEntitiesOfClass( + typeid(Mob), + AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); + entitiesToBeFreed = true; + } + if (sensitivity == PressurePlateTile::players) { + entities = level->getEntitiesOfClass( + typeid(Player), + AABB::newTemp(x + b, y, z + b, x + 1 - b, y + 0.25, z + 1 - b)); + entitiesToBeFreed = true; + } - if (!entities->empty()) - { + if (!entities->empty()) { shouldBePressed = true; } - if (shouldBePressed && !wasPressed) - { + if (shouldBePressed && !wasPressed) { level->setData(x, y, z, 1); level->updateNeighborsAt(x, y, z, id); level->updateNeighborsAt(x, y - 1, z, id); level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.6f); + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.6f); } - if (!shouldBePressed && wasPressed) - { + if (!shouldBePressed && wasPressed) { level->setData(x, y, z, 0); level->updateNeighborsAt(x, y, z, id); level->updateNeighborsAt(x, y - 1, z, id); level->setTilesDirty(x, y, z, x, y, z); - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, 0.3f, 0.5f); + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, + 0.3f, 0.5f); } - if (shouldBePressed) - { + if (shouldBePressed) { level->addToTickNextTick(x, y, z, id, getTickDelay()); } - if( entitiesToBeFreed ) - { - delete entities; - } + if (entitiesToBeFreed) { + delete entities; + } } -void PressurePlateTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - if (data > 0) - { +void PressurePlateTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + if (data > 0) { level->updateNeighborsAt(x, y, z, this->id); level->updateNeighborsAt(x, y - 1, z, this->id); } Tile::onRemove(level, x, y, z, id, data); } -void PressurePlateTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void PressurePlateTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { bool pressed = level->getData(x, y, z) == 1; float o = 1 / 16.0f; - if (pressed) - { + if (pressed) { this->setShape(o, 0, o, 1 - o, 0.5f / 16.0f, 1 - o); - } - else - { + } else { setShape(o, 0, o, 1 - o, 1 / 16.0f, 1 - o); } } -bool PressurePlateTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return (level->getData(x, y, z)) > 0; +bool PressurePlateTile::getSignal(LevelSource* level, int x, int y, int z, + int dir) { + return (level->getData(x, y, z)) > 0; } -bool PressurePlateTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ +bool PressurePlateTile::getDirectSignal(Level* level, int x, int y, int z, + int dir) { if (level->getData(x, y, z) == 0) return false; return (dir == 1); } -bool PressurePlateTile::isSignalSource() -{ - return true; -} +bool PressurePlateTile::isSignalSource() { return true; } -void PressurePlateTile::updateDefaultShape() -{ +void PressurePlateTile::updateDefaultShape() { float x = 8 / 16.0f; float y = 2 / 16.0f; float z = 8 / 16.0f; setShape(0.5f - x, 0.5f - y, 0.5f - z, 0.5f + x, 0.5f + y, 0.5f + z); - } -bool PressurePlateTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool PressurePlateTile::shouldTileTick(Level* level, int x, int y, int z) { return level->getData(x, y, z) != 0; } -int PressurePlateTile::getPistonPushReaction() -{ - return Material::PUSH_DESTROY; +int PressurePlateTile::getPistonPushReaction() { + return Material::PUSH_DESTROY; } -void PressurePlateTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(texture); +void PressurePlateTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(texture); } diff --git a/Minecraft.World/Blocks/PressurePlateTile.h b/Minecraft.World/Blocks/PressurePlateTile.h index a6219feb2..c8ea4e293 100644 --- a/Minecraft.World/Blocks/PressurePlateTile.h +++ b/Minecraft.World/Blocks/PressurePlateTile.h @@ -4,46 +4,52 @@ class Random; -class PressurePlateTile : public Tile -{ - friend class Tile; -private: - std::wstring texture; -public: - enum Sensitivity - { - everything, - mobs, - players - }; +class PressurePlateTile : public Tile { + friend class Tile; private: - Sensitivity sensitivity; + std::wstring texture; + +public: + enum Sensitivity { everything, mobs, players }; + +private: + Sensitivity sensitivity; + protected: - PressurePlateTile(int id, const std::wstring &tex, Material *material, Sensitivity sensitivity); + PressurePlateTile(int id, const std::wstring& tex, Material* material, + Sensitivity sensitivity); + public: virtual int getTickDelay(); - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool isSolidRender(bool isServerLevel = false); virtual bool blocksLight(); virtual bool isCubeShaped(); - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + private: - virtual void checkPressed(Level *level, int x, int y, int z); + virtual void checkPressed(Level* level, int x, int y, int z); + public: - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); virtual bool isSignalSource(); virtual void updateDefaultShape(); - virtual int getPistonPushReaction(); - void registerIcons(IconRegister *iconRegister); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual int getPistonPushReaction(); + void registerIcons(IconRegister* iconRegister); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/PumpkinTile.cpp b/Minecraft.World/Blocks/PumpkinTile.cpp index 776868b5c..97a44f725 100644 --- a/Minecraft.World/Blocks/PumpkinTile.cpp +++ b/Minecraft.World/Blocks/PumpkinTile.cpp @@ -11,159 +11,163 @@ const std::wstring PumpkinTile::TEXTURE_FACE = L"pumpkin_face"; const std::wstring PumpkinTile::TEXTURE_LANTERN = L"pumpkin_jack"; -PumpkinTile::PumpkinTile(int id, bool lit) : DirectionalTile(id, Material::vegetable) -{ +PumpkinTile::PumpkinTile(int id, bool lit) + : DirectionalTile(id, Material::vegetable) { iconTop = NULL; - iconFace = NULL; + iconFace = NULL; setTicking(true); this->lit = lit; } -Icon *PumpkinTile::getTexture(int face, int data) -{ +Icon* PumpkinTile::getTexture(int face, int data) { if (face == Facing::UP) return iconTop; if (face == Facing::DOWN) return iconTop; if (data == DIR_NORTH && face == Facing::NORTH) return iconFace; if (data == DIR_EAST && face == Facing::EAST) return iconFace; if (data == DIR_SOUTH && face == Facing::SOUTH) return iconFace; - if (data == DIR_WEST && face == Facing::WEST) return iconFace; + if (data == DIR_WEST && face == Facing::WEST) + return iconFace; - else return icon; + else + return icon; } -void PumpkinTile::onPlace(Level *level, int x, int y, int z) -{ - Tile::onPlace(level, x, y, z); - if (level->getTile(x, y - 1, z) == Tile::snow_Id && level->getTile(x, y - 2, z) == Tile::snow_Id) - { - if (!level->isClientSide) - { - // 4J - added limit of number of snowmen that can be spawned - if( level->canCreateMore( eTYPE_SNOWMAN, Level::eSpawnType_Egg) ) - { - level->setTileNoUpdate(x, y, z, 0); - level->setTileNoUpdate(x, y - 1, z, 0); - level->setTileNoUpdate(x, y - 2, z, 0); - std::shared_ptr snowMan = std::shared_ptr(new SnowMan(level)); - snowMan->moveTo(x + 0.5, y - 1.95, z + 0.5, 0, 0); - level->addEntity(snowMan); +void PumpkinTile::onPlace(Level* level, int x, int y, int z) { + Tile::onPlace(level, x, y, z); + if (level->getTile(x, y - 1, z) == Tile::snow_Id && + level->getTile(x, y - 2, z) == Tile::snow_Id) { + if (!level->isClientSide) { + // 4J - added limit of number of snowmen that can be spawned + if (level->canCreateMore(eTYPE_SNOWMAN, Level::eSpawnType_Egg)) { + level->setTileNoUpdate(x, y, z, 0); + level->setTileNoUpdate(x, y - 1, z, 0); + level->setTileNoUpdate(x, y - 2, z, 0); + std::shared_ptr snowMan = + std::shared_ptr(new SnowMan(level)); + snowMan->moveTo(x + 0.5, y - 1.95, z + 0.5, 0, 0); + level->addEntity(snowMan); level->tileUpdated(x, y, z, 0); level->tileUpdated(x, y - 1, z, 0); level->tileUpdated(x, y - 2, z, 0); - } - else - { - // If we can't spawn it, at least give the resources back - Tile::spawnResources(level, x, y, z, level->getData(x, y, z), 0); - Tile::tiles[Tile::snow_Id]->spawnResources(level, x, y - 1, z, level->getData(x, y - 1, z), 0); - Tile::tiles[Tile::snow_Id]->spawnResources(level, x, y - 2, z, level->getData(x, y - 2, z), 0); - level->setTile(x, y, z, 0); - level->setTile(x, y - 1, z, 0); - level->setTile(x, y - 2, z, 0); - } + } else { + // If we can't spawn it, at least give the resources back + Tile::spawnResources(level, x, y, z, level->getData(x, y, z), + 0); + Tile::tiles[Tile::snow_Id]->spawnResources( + level, x, y - 1, z, level->getData(x, y - 1, z), 0); + Tile::tiles[Tile::snow_Id]->spawnResources( + level, x, y - 2, z, level->getData(x, y - 2, z), 0); + level->setTile(x, y, z, 0); + level->setTile(x, y - 1, z, 0); + level->setTile(x, y - 2, z, 0); + } } - for (int i = 0; i < 120; i++) - { - level->addParticle(eParticleType_snowshovel, x + level->random->nextDouble(), y - 2 + level->random->nextDouble() * 2.5, z + level->random->nextDouble(), 0, 0, 0); + for (int i = 0; i < 120; i++) { + level->addParticle(eParticleType_snowshovel, + x + level->random->nextDouble(), + y - 2 + level->random->nextDouble() * 2.5, + z + level->random->nextDouble(), 0, 0, 0); } - } - else if (level->getTile(x, y - 1, z) == Tile::ironBlock_Id && level->getTile(x, y - 2, z) == Tile::ironBlock_Id) - { - bool xArms = level->getTile(x - 1, y - 1, z) == Tile::ironBlock_Id && level->getTile(x + 1, y - 1, z) == Tile::ironBlock_Id; - bool zArms = level->getTile(x, y - 1, z - 1) == Tile::ironBlock_Id && level->getTile(x, y - 1, z + 1) == Tile::ironBlock_Id; - if (xArms || zArms) - { - if (!level->isClientSide) - { - // 4J - added limit of number of golems that can be spawned - if( level->canCreateMore( eTYPE_VILLAGERGOLEM, Level::eSpawnType_Egg) ) - { - level->setTileNoUpdate(x, y, z, 0); - level->setTileNoUpdate(x, y - 1, z, 0); - level->setTileNoUpdate(x, y - 2, z, 0); - if (xArms) - { - level->setTileNoUpdate(x - 1, y - 1, z, 0); - level->setTileNoUpdate(x + 1, y - 1, z, 0); - } - else - { - level->setTileNoUpdate(x, y - 1, z - 1, 0); - level->setTileNoUpdate(x, y - 1, z + 1, 0); - } + } else if (level->getTile(x, y - 1, z) == Tile::ironBlock_Id && + level->getTile(x, y - 2, z) == Tile::ironBlock_Id) { + bool xArms = level->getTile(x - 1, y - 1, z) == Tile::ironBlock_Id && + level->getTile(x + 1, y - 1, z) == Tile::ironBlock_Id; + bool zArms = level->getTile(x, y - 1, z - 1) == Tile::ironBlock_Id && + level->getTile(x, y - 1, z + 1) == Tile::ironBlock_Id; + if (xArms || zArms) { + if (!level->isClientSide) { + // 4J - added limit of number of golems that can be spawned + if (level->canCreateMore(eTYPE_VILLAGERGOLEM, + Level::eSpawnType_Egg)) { + level->setTileNoUpdate(x, y, z, 0); + level->setTileNoUpdate(x, y - 1, z, 0); + level->setTileNoUpdate(x, y - 2, z, 0); + if (xArms) { + level->setTileNoUpdate(x - 1, y - 1, z, 0); + level->setTileNoUpdate(x + 1, y - 1, z, 0); + } else { + level->setTileNoUpdate(x, y - 1, z - 1, 0); + level->setTileNoUpdate(x, y - 1, z + 1, 0); + } - std::shared_ptr villagerGolem = std::shared_ptr(new VillagerGolem(level)); - villagerGolem->setPlayerCreated(true); - villagerGolem->moveTo(x + 0.5, y - 1.95, z + 0.5, 0, 0); - level->addEntity(villagerGolem); + std::shared_ptr villagerGolem = + std::shared_ptr( + new VillagerGolem(level)); + villagerGolem->setPlayerCreated(true); + villagerGolem->moveTo(x + 0.5, y - 1.95, z + 0.5, 0, 0); + level->addEntity(villagerGolem); - for (int i = 0; i < 120; i++) - { - level->addParticle(eParticleType_snowballpoof, x + level->random->nextDouble(), y - 2 + level->random->nextDouble() * 3.9, z + level->random->nextDouble(), 0, 0, 0); - } + for (int i = 0; i < 120; i++) { + level->addParticle( + eParticleType_snowballpoof, + x + level->random->nextDouble(), + y - 2 + level->random->nextDouble() * 3.9, + z + level->random->nextDouble(), 0, 0, 0); + } - level->tileUpdated(x, y, z, 0); - level->tileUpdated(x, y - 1, z, 0); - level->tileUpdated(x, y - 2, z, 0); - if (xArms) - { - level->tileUpdated(x - 1, y - 1, z, 0); - level->tileUpdated(x + 1, y - 1, z, 0); - } - else - { - level->tileUpdated(x, y - 1, z - 1, 0); - level->tileUpdated(x, y - 1, z + 1, 0); - } - } - else - { - // If we can't spawn it, at least give the resources back - Tile::spawnResources(level, x, y, z, level->getData(x, y, z), 0); - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x, y - 1, z, level->getData(x, y - 1, z), 0); - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x, y - 2, z, level->getData(x, y - 2, z), 0); - level->setTile(x, y, z, 0); - level->setTile(x, y - 1, z, 0); - level->setTile(x, y - 2, z, 0); + level->tileUpdated(x, y, z, 0); + level->tileUpdated(x, y - 1, z, 0); + level->tileUpdated(x, y - 2, z, 0); + if (xArms) { + level->tileUpdated(x - 1, y - 1, z, 0); + level->tileUpdated(x + 1, y - 1, z, 0); + } else { + level->tileUpdated(x, y - 1, z - 1, 0); + level->tileUpdated(x, y - 1, z + 1, 0); + } + } else { + // If we can't spawn it, at least give the resources back + Tile::spawnResources(level, x, y, z, + level->getData(x, y, z), 0); + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x, y - 1, z, level->getData(x, y - 1, z), 0); + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x, y - 2, z, level->getData(x, y - 2, z), 0); + level->setTile(x, y, z, 0); + level->setTile(x, y - 1, z, 0); + level->setTile(x, y - 2, z, 0); - if(xArms) - { - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x - 1, y - 1, z, level->getData(x - 1, y - 1, z), 0); - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x + 1, y - 1, z, level->getData(x + 1, y - 1, z), 0); - level->setTile(x - 1, y - 1, z, 0); - level->setTile(x + 1, y - 1, z, 0); - } - else - { - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x, y - 1, z - 1, level->getData(x, y - 1, z - 1), 0); - Tile::tiles[Tile::ironBlock_Id]->spawnResources(level, x, y - 1, z + 1, level->getData(x, y - 1, z + 1), 0); - level->setTile(x, y - 1, z - 1, 0); - level->setTile(x, y - 1, z + 1, 0); - } - } - } - } - } + if (xArms) { + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x - 1, y - 1, z, + level->getData(x - 1, y - 1, z), 0); + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x + 1, y - 1, z, + level->getData(x + 1, y - 1, z), 0); + level->setTile(x - 1, y - 1, z, 0); + level->setTile(x + 1, y - 1, z, 0); + } else { + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x, y - 1, z - 1, + level->getData(x, y - 1, z - 1), 0); + Tile::tiles[Tile::ironBlock_Id]->spawnResources( + level, x, y - 1, z + 1, + level->getData(x, y - 1, z + 1), 0); + level->setTile(x, y - 1, z - 1, 0); + level->setTile(x, y - 1, z + 1, 0); + } + } + } + } + } } -bool PumpkinTile::mayPlace(Level *level, int x, int y, int z) -{ +bool PumpkinTile::mayPlace(Level* level, int x, int y, int z) { int t = level->getTile(x, y, z); - return (t == 0 || Tile::tiles[t]->material->isReplaceable()) && level->isTopSolidBlocking(x, y - 1, z); - + return (t == 0 || Tile::tiles[t]->material->isReplaceable()) && + level->isTopSolidBlocking(x, y - 1, z); } -void PumpkinTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ +void PumpkinTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { int dir = Mth::floor(by->yRot * 4 / (360) + 2.5) & 3; level->setData(x, y, z, dir); } -void PumpkinTile::registerIcons(IconRegister *iconRegister) -{ - iconFace = iconRegister->registerIcon(lit ? TEXTURE_LANTERN : TEXTURE_FACE); - iconTop = iconRegister->registerIcon(L"pumpkin_top"); - icon = iconRegister->registerIcon(L"pumpkin_side"); +void PumpkinTile::registerIcons(IconRegister* iconRegister) { + iconFace = iconRegister->registerIcon(lit ? TEXTURE_LANTERN : TEXTURE_FACE); + iconTop = iconRegister->registerIcon(L"pumpkin_top"); + icon = iconRegister->registerIcon(L"pumpkin_side"); } diff --git a/Minecraft.World/Blocks/PumpkinTile.h b/Minecraft.World/Blocks/PumpkinTile.h index 5117c9c30..0f6bdae8b 100644 --- a/Minecraft.World/Blocks/PumpkinTile.h +++ b/Minecraft.World/Blocks/PumpkinTile.h @@ -4,28 +4,31 @@ class Mob; class ChunkRebuildData; -class PumpkinTile : public DirectionalTile -{ - friend class Tile; - friend class ChunkRebuildData; +class PumpkinTile : public DirectionalTile { + friend class Tile; + friend class ChunkRebuildData; + public: - static const int DIR_SOUTH = 0; - static const int DIR_WEST = 1; - static const int DIR_NORTH = 2; - static const int DIR_EAST = 3; + static const int DIR_SOUTH = 0; + static const int DIR_WEST = 1; + static const int DIR_NORTH = 2; + static const int DIR_EAST = 3; private: - static const std::wstring TEXTURE_FACE; - static const std::wstring TEXTURE_LANTERN; - bool lit; - Icon *iconTop; - Icon *iconFace; + static const std::wstring TEXTURE_FACE; + static const std::wstring TEXTURE_LANTERN; + bool lit; + Icon* iconTop; + Icon* iconFace; + protected: - PumpkinTile(int id, bool lit); + PumpkinTile(int id, bool lit); + public: - virtual Icon *getTexture(int face, int data); - virtual void onPlace(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - void registerIcons(IconRegister *iconRegister); + virtual Icon* getTexture(int face, int data); + virtual void onPlace(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/QuartzBlockTile.cpp b/Minecraft.World/Blocks/QuartzBlockTile.cpp index b62429812..b67ae34b4 100644 --- a/Minecraft.World/Blocks/QuartzBlockTile.cpp +++ b/Minecraft.World/Blocks/QuartzBlockTile.cpp @@ -9,114 +9,102 @@ #include "../Player/Player.h" int QuartzBlockTile::BLOCK_NAMES[QUARTZ_BLOCK_NAMES] = { - IDS_TILE_QUARTZ_BLOCK, IDS_TILE_QUARTZ_BLOCK_CHISELED, IDS_TILE_QUARTZ_BLOCK_LINES, IDS_TILE_QUARTZ_BLOCK_LINES, IDS_TILE_QUARTZ_BLOCK_LINES -}; + IDS_TILE_QUARTZ_BLOCK, IDS_TILE_QUARTZ_BLOCK_CHISELED, + IDS_TILE_QUARTZ_BLOCK_LINES, IDS_TILE_QUARTZ_BLOCK_LINES, + IDS_TILE_QUARTZ_BLOCK_LINES}; const std::wstring QuartzBlockTile::TEXTURE_TOP = L"quartzblock_top"; -const std::wstring QuartzBlockTile::TEXTURE_CHISELED_TOP = L"quartzblock_chiseled_top"; -const std::wstring QuartzBlockTile::TEXTURE_LINES_TOP = L"quartzblock_lines_top"; +const std::wstring QuartzBlockTile::TEXTURE_CHISELED_TOP = + L"quartzblock_chiseled_top"; +const std::wstring QuartzBlockTile::TEXTURE_LINES_TOP = + L"quartzblock_lines_top"; const std::wstring QuartzBlockTile::TEXTURE_BOTTOM = L"quartzblock_bottom"; -const std::wstring QuartzBlockTile::TEXTURE_NAMES[QUARTZ_BLOCK_TEXTURES] = { L"quartzblock_side", L"quartzblock_chiseled", L"quartzblock_lines", L"", L""}; +const std::wstring QuartzBlockTile::TEXTURE_NAMES[QUARTZ_BLOCK_TEXTURES] = { + L"quartzblock_side", L"quartzblock_chiseled", L"quartzblock_lines", L"", + L""}; -QuartzBlockTile::QuartzBlockTile(int id) : Tile(id, Material::stone) -{ +QuartzBlockTile::QuartzBlockTile(int id) : Tile(id, Material::stone) {} + +Icon* QuartzBlockTile::getTexture(int face, int data) { + if (data == TYPE_LINES_Y || data == TYPE_LINES_X || data == TYPE_LINES_Z) { + if (data == TYPE_LINES_Y && + (face == Facing::UP || face == Facing::DOWN)) { + return iconLinesTop; + } else if (data == TYPE_LINES_X && + (face == Facing::EAST || face == Facing::WEST)) { + return iconLinesTop; + } else if (data == TYPE_LINES_Z && + (face == Facing::NORTH || face == Facing::SOUTH)) { + return iconLinesTop; + } + + return icons[data]; + } + + if (face == Facing::UP || (face == Facing::DOWN && data == TYPE_CHISELED)) { + if (data == TYPE_CHISELED) { + return iconChiseledTop; + } + return iconTop; + } + if (face == Facing::DOWN) { + return iconBottom; + } + if (data < 0 || data >= QUARTZ_BLOCK_TEXTURES) data = 0; + return icons[data]; } -Icon *QuartzBlockTile::getTexture(int face, int data) -{ - if (data == TYPE_LINES_Y || data == TYPE_LINES_X || data == TYPE_LINES_Z) - { - if (data == TYPE_LINES_Y && (face == Facing::UP || face == Facing::DOWN)) - { - return iconLinesTop; - } - else if (data == TYPE_LINES_X && (face == Facing::EAST || face == Facing::WEST)) - { - return iconLinesTop; - } - else if (data == TYPE_LINES_Z && (face == Facing::NORTH || face == Facing::SOUTH)) - { - return iconLinesTop; - } +int QuartzBlockTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, + float clickY, float clickZ, + int itemValue) { + if (itemValue == TYPE_LINES_Y) { + switch (face) { + case Facing::NORTH: + case Facing::SOUTH: + itemValue = TYPE_LINES_Z; + break; + case Facing::EAST: + case Facing::WEST: + itemValue = TYPE_LINES_X; + break; + case Facing::UP: + case Facing::DOWN: + itemValue = TYPE_LINES_Y; + break; + } + } - return icons[data]; - } - - if (face == Facing::UP || (face == Facing::DOWN && data == TYPE_CHISELED)) - { - if (data == TYPE_CHISELED) - { - return iconChiseledTop; - } - return iconTop; - } - if (face == Facing::DOWN) - { - return iconBottom; - } - if (data < 0 || data >= QUARTZ_BLOCK_TEXTURES) data = 0; - return icons[data]; + return itemValue; } -int QuartzBlockTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - if (itemValue == TYPE_LINES_Y) - { - switch (face) - { - case Facing::NORTH: - case Facing::SOUTH: - itemValue = TYPE_LINES_Z; - break; - case Facing::EAST: - case Facing::WEST: - itemValue = TYPE_LINES_X; - break; - case Facing::UP: - case Facing::DOWN: - itemValue = TYPE_LINES_Y; - break; - } - } +int QuartzBlockTile::getSpawnResourcesAuxValue(int data) { + if (data == TYPE_LINES_X || data == TYPE_LINES_Z) return TYPE_LINES_Y; - return itemValue; + return data; } -int QuartzBlockTile::getSpawnResourcesAuxValue(int data) -{ - if (data == TYPE_LINES_X || data == TYPE_LINES_Z) return TYPE_LINES_Y; - - return data; +std::shared_ptr QuartzBlockTile::getSilkTouchItemInstance( + int data) { + if (data == TYPE_LINES_X || data == TYPE_LINES_Z) + return std::shared_ptr( + new ItemInstance(id, 1, TYPE_LINES_Y)); + return Tile::getSilkTouchItemInstance(data); } -std::shared_ptr QuartzBlockTile::getSilkTouchItemInstance(int data) -{ - if (data == TYPE_LINES_X || data == TYPE_LINES_Z) return std::shared_ptr(new ItemInstance(id, 1, TYPE_LINES_Y)); - return Tile::getSilkTouchItemInstance(data); -} +int QuartzBlockTile::getRenderShape() { return Tile::SHAPE_QUARTZ; } -int QuartzBlockTile::getRenderShape() -{ - return Tile::SHAPE_QUARTZ; -} +void QuartzBlockTile::registerIcons(IconRegister* iconRegister) { + for (int i = 0; i < QUARTZ_BLOCK_TEXTURES; i++) { + if (TEXTURE_NAMES[i].empty()) { + icons[i] = icons[i - 1]; + } else { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } + } - -void QuartzBlockTile::registerIcons(IconRegister *iconRegister) -{ - for (int i = 0; i < QUARTZ_BLOCK_TEXTURES; i++) - { - if (TEXTURE_NAMES[i].empty()) - { - icons[i] = icons[i - 1]; - } - else - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } - } - - iconTop = iconRegister->registerIcon(TEXTURE_TOP); - iconChiseledTop = iconRegister->registerIcon(TEXTURE_CHISELED_TOP); - iconLinesTop = iconRegister->registerIcon(TEXTURE_LINES_TOP); - iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); + iconTop = iconRegister->registerIcon(TEXTURE_TOP); + iconChiseledTop = iconRegister->registerIcon(TEXTURE_CHISELED_TOP); + iconLinesTop = iconRegister->registerIcon(TEXTURE_LINES_TOP); + iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/QuartzBlockTile.h b/Minecraft.World/Blocks/QuartzBlockTile.h index 7a4e0719b..2d4dffaea 100644 --- a/Minecraft.World/Blocks/QuartzBlockTile.h +++ b/Minecraft.World/Blocks/QuartzBlockTile.h @@ -2,46 +2,48 @@ #include "Tile.h" -class QuartzBlockTile : public Tile -{ - friend class ChunkRebuildData; +class QuartzBlockTile : public Tile { + friend class ChunkRebuildData; + public: - static const int TYPE_DEFAULT = 0; - static const int TYPE_CHISELED = 1; - static const int TYPE_LINES_Y = 2; - static const int TYPE_LINES_X = 3; - static const int TYPE_LINES_Z = 4; + static const int TYPE_DEFAULT = 0; + static const int TYPE_CHISELED = 1; + static const int TYPE_LINES_Y = 2; + static const int TYPE_LINES_X = 3; + static const int TYPE_LINES_Z = 4; - static const int QUARTZ_BLOCK_NAMES = 5; + static const int QUARTZ_BLOCK_NAMES = 5; - static int BLOCK_NAMES[QUARTZ_BLOCK_NAMES]; + static int BLOCK_NAMES[QUARTZ_BLOCK_NAMES]; private: - static const int QUARTZ_BLOCK_TEXTURES = 5; + static const int QUARTZ_BLOCK_TEXTURES = 5; - static const std::wstring TEXTURE_TOP; - static const std::wstring TEXTURE_CHISELED_TOP; - static const std::wstring TEXTURE_LINES_TOP; - static const std::wstring TEXTURE_BOTTOM; - static const std::wstring TEXTURE_NAMES[QUARTZ_BLOCK_TEXTURES]; + static const std::wstring TEXTURE_TOP; + static const std::wstring TEXTURE_CHISELED_TOP; + static const std::wstring TEXTURE_LINES_TOP; + static const std::wstring TEXTURE_BOTTOM; + static const std::wstring TEXTURE_NAMES[QUARTZ_BLOCK_TEXTURES]; - Icon *icons[QUARTZ_BLOCK_TEXTURES]; - Icon *iconChiseledTop; - Icon *iconLinesTop; - Icon *iconTop; - Icon *iconBottom; + Icon* icons[QUARTZ_BLOCK_TEXTURES]; + Icon* iconChiseledTop; + Icon* iconLinesTop; + Icon* iconTop; + Icon* iconBottom; public: - QuartzBlockTile(int id); + QuartzBlockTile(int id); - Icon *getTexture(int face, int data); - int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - int getSpawnResourcesAuxValue(int data); + Icon* getTexture(int face, int data); + int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, int face, + float clickX, float clickY, float clickZ, + int itemValue); + int getSpawnResourcesAuxValue(int data); protected: - std::shared_ptr getSilkTouchItemInstance(int data); + std::shared_ptr getSilkTouchItemInstance(int data); public: - int getRenderShape(); - void registerIcons(IconRegister *iconRegister); + int getRenderShape(); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/RailTile.cpp b/Minecraft.World/Blocks/RailTile.cpp index 67709722a..0352cfabe 100644 --- a/Minecraft.World/Blocks/RailTile.cpp +++ b/Minecraft.World/Blocks/RailTile.cpp @@ -4,675 +4,555 @@ #include "../Headers/net.minecraft.world.h" #include "RailTile.h" -RailTile::Rail::Rail(Level *level, int x, int y, int z) -{ - this->level = level; - this->x = x; - this->y = y; - this->z = z; +RailTile::Rail::Rail(Level* level, int x, int y, int z) { + this->level = level; + this->x = x; + this->y = y; + this->z = z; - int id = level->getTile(x, y, z); + int id = level->getTile(x, y, z); - // 4J Stu - We saw a random crash near the end of development on XboxOne orignal version where the id here isn't a tile any more - // Adding this check in to avoid that crash - m_bValidRail = isRail(id); - if(m_bValidRail) - { - int direction = level->getData(x, y, z); - if (((RailTile *) Tile::tiles[id])->usesDataBit) - { - usesDataBit = true; - direction = direction & ~RAIL_DATA_BIT; - } - else - { - usesDataBit = false; - } - updateConnections(direction); - } + // 4J Stu - We saw a random crash near the end of development on XboxOne + // orignal version where the id here isn't a tile any more Adding this check + // in to avoid that crash + m_bValidRail = isRail(id); + if (m_bValidRail) { + int direction = level->getData(x, y, z); + if (((RailTile*)Tile::tiles[id])->usesDataBit) { + usesDataBit = true; + direction = direction & ~RAIL_DATA_BIT; + } else { + usesDataBit = false; + } + updateConnections(direction); + } } -RailTile::Rail::~Rail() -{ - for( int i = 0; i < connections.size(); i++ ) - { - delete connections[i]; - } +RailTile::Rail::~Rail() { + for (int i = 0; i < connections.size(); i++) { + delete connections[i]; + } } -void RailTile::Rail::updateConnections(int direction) -{ - if(m_bValidRail) - { - for( int i = 0; i < connections.size(); i++ ) - { - delete connections[i]; - } - connections.clear(); - MemSect(50); - if (direction == DIR_FLAT_Z) - { - connections.push_back(new TilePos(x, y, z - 1)); - connections.push_back(new TilePos(x, y, z + 1)); - } else if (direction == DIR_FLAT_X) - { - connections.push_back(new TilePos(x - 1, y, z)); - connections.push_back(new TilePos(x + 1, y, z)); - } else if (direction == 2) - { - connections.push_back(new TilePos(x - 1, y, z)); - connections.push_back(new TilePos(x + 1, y + 1, z)); - } else if (direction == 3) - { - connections.push_back(new TilePos(x - 1, y + 1, z)); - connections.push_back(new TilePos(x + 1, y, z)); - } else if (direction == 4) - { - connections.push_back(new TilePos(x, y + 1, z - 1)); - connections.push_back(new TilePos(x, y, z + 1)); - } else if (direction == 5) - { - connections.push_back(new TilePos(x, y, z - 1)); - connections.push_back(new TilePos(x, y + 1, z + 1)); - } else if (direction == 6) - { - connections.push_back(new TilePos(x + 1, y, z)); - connections.push_back(new TilePos(x, y, z + 1)); - } else if (direction == 7) - { - connections.push_back(new TilePos(x - 1, y, z)); - connections.push_back(new TilePos(x, y, z + 1)); - } else if (direction == 8) - { - connections.push_back(new TilePos(x - 1, y, z)); - connections.push_back(new TilePos(x, y, z - 1)); - } else if (direction == 9) - { - connections.push_back(new TilePos(x + 1, y, z)); - connections.push_back(new TilePos(x, y, z - 1)); - } - MemSect(0); - } +void RailTile::Rail::updateConnections(int direction) { + if (m_bValidRail) { + for (int i = 0; i < connections.size(); i++) { + delete connections[i]; + } + connections.clear(); + MemSect(50); + if (direction == DIR_FLAT_Z) { + connections.push_back(new TilePos(x, y, z - 1)); + connections.push_back(new TilePos(x, y, z + 1)); + } else if (direction == DIR_FLAT_X) { + connections.push_back(new TilePos(x - 1, y, z)); + connections.push_back(new TilePos(x + 1, y, z)); + } else if (direction == 2) { + connections.push_back(new TilePos(x - 1, y, z)); + connections.push_back(new TilePos(x + 1, y + 1, z)); + } else if (direction == 3) { + connections.push_back(new TilePos(x - 1, y + 1, z)); + connections.push_back(new TilePos(x + 1, y, z)); + } else if (direction == 4) { + connections.push_back(new TilePos(x, y + 1, z - 1)); + connections.push_back(new TilePos(x, y, z + 1)); + } else if (direction == 5) { + connections.push_back(new TilePos(x, y, z - 1)); + connections.push_back(new TilePos(x, y + 1, z + 1)); + } else if (direction == 6) { + connections.push_back(new TilePos(x + 1, y, z)); + connections.push_back(new TilePos(x, y, z + 1)); + } else if (direction == 7) { + connections.push_back(new TilePos(x - 1, y, z)); + connections.push_back(new TilePos(x, y, z + 1)); + } else if (direction == 8) { + connections.push_back(new TilePos(x - 1, y, z)); + connections.push_back(new TilePos(x, y, z - 1)); + } else if (direction == 9) { + connections.push_back(new TilePos(x + 1, y, z)); + connections.push_back(new TilePos(x, y, z - 1)); + } + MemSect(0); + } } -void RailTile::Rail::removeSoftConnections() -{ - if(m_bValidRail) - { - for (unsigned int i = 0; i < connections.size(); i++) - { - Rail *rail = getRail(connections[i]); - if (rail == NULL || !rail->connectsTo(this)) - { - delete connections[i]; - connections.erase(connections.begin()+i); - i--; - } else - { - delete connections[i]; - MemSect(50); - connections[i] =new TilePos(rail->x, rail->y, rail->z); - MemSect(0); - } - delete rail; - } - } +void RailTile::Rail::removeSoftConnections() { + if (m_bValidRail) { + for (unsigned int i = 0; i < connections.size(); i++) { + Rail* rail = getRail(connections[i]); + if (rail == NULL || !rail->connectsTo(this)) { + delete connections[i]; + connections.erase(connections.begin() + i); + i--; + } else { + delete connections[i]; + MemSect(50); + connections[i] = new TilePos(rail->x, rail->y, rail->z); + MemSect(0); + } + delete rail; + } + } } -bool RailTile::Rail::hasRail(int x, int y, int z) -{ - if(!m_bValidRail) return false; - if (isRail(level, x, y, z)) return true; - if (isRail(level, x, y + 1, z)) return true; - if (isRail(level, x, y - 1, z)) return true; - return false; +bool RailTile::Rail::hasRail(int x, int y, int z) { + if (!m_bValidRail) return false; + if (isRail(level, x, y, z)) return true; + if (isRail(level, x, y + 1, z)) return true; + if (isRail(level, x, y - 1, z)) return true; + return false; } -RailTile::Rail *RailTile::Rail::getRail(TilePos *p) -{ - if(!m_bValidRail) return NULL; - if (isRail(level, p->x, p->y, p->z)) return new Rail(level, p->x, p->y, p->z); - if (isRail(level, p->x, p->y + 1, p->z)) return new Rail(level, p->x, p->y + 1, p->z); - if (isRail(level, p->x, p->y - 1, p->z)) return new Rail(level, p->x, p->y - 1, p->z); - return NULL; +RailTile::Rail* RailTile::Rail::getRail(TilePos* p) { + if (!m_bValidRail) return NULL; + if (isRail(level, p->x, p->y, p->z)) + return new Rail(level, p->x, p->y, p->z); + if (isRail(level, p->x, p->y + 1, p->z)) + return new Rail(level, p->x, p->y + 1, p->z); + if (isRail(level, p->x, p->y - 1, p->z)) + return new Rail(level, p->x, p->y - 1, p->z); + return NULL; } - -bool RailTile::Rail::connectsTo(Rail *rail) -{ - if(m_bValidRail) - { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) - { - TilePos *p = *it; //connections[i]; - if (p->x == rail->x && p->z == rail->z) - { - return true; - } - } - } - return false; +bool RailTile::Rail::connectsTo(Rail* rail) { + if (m_bValidRail) { + AUTO_VAR(itEnd, connections.end()); + for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) { + TilePos* p = *it; // connections[i]; + if (p->x == rail->x && p->z == rail->z) { + return true; + } + } + } + return false; } -bool RailTile::Rail::hasConnection(int x, int y, int z) -{ - if(m_bValidRail) - { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) - { - TilePos *p = *it; //connections[i]; - if (p->x == x && p->z == z) - { - return true; - } - } - } - return false; +bool RailTile::Rail::hasConnection(int x, int y, int z) { + if (m_bValidRail) { + AUTO_VAR(itEnd, connections.end()); + for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) { + TilePos* p = *it; // connections[i]; + if (p->x == x && p->z == z) { + return true; + } + } + } + return false; } +int RailTile::Rail::countPotentialConnections() { + int count = 0; -int RailTile::Rail::countPotentialConnections() -{ - int count = 0; + if (m_bValidRail) { + if (hasRail(x, y, z - 1)) count++; + if (hasRail(x, y, z + 1)) count++; + if (hasRail(x - 1, y, z)) count++; + if (hasRail(x + 1, y, z)) count++; + } - if(m_bValidRail) - { - if (hasRail(x, y, z - 1)) count++; - if (hasRail(x, y, z + 1)) count++; - if (hasRail(x - 1, y, z)) count++; - if (hasRail(x + 1, y, z)) count++; - } - - return count; + return count; } -bool RailTile::Rail::canConnectTo(Rail *rail) -{ - if(!m_bValidRail) return false; - if (connectsTo(rail)) return true; - if (connections.size() == 2) - { - return false; - } - if (connections.empty()) - { - return true; - } +bool RailTile::Rail::canConnectTo(Rail* rail) { + if (!m_bValidRail) return false; + if (connectsTo(rail)) return true; + if (connections.size() == 2) { + return false; + } + if (connections.empty()) { + return true; + } - TilePos *c = connections[0]; + TilePos* c = connections[0]; - return true; + return true; } -void RailTile::Rail::connectTo(Rail *rail) -{ - if(m_bValidRail) - { - MemSect(50); - connections.push_back(new TilePos(rail->x, rail->y, rail->z)); - MemSect(0); +void RailTile::Rail::connectTo(Rail* rail) { + if (m_bValidRail) { + MemSect(50); + connections.push_back(new TilePos(rail->x, rail->y, rail->z)); + MemSect(0); - bool n = hasConnection(x, y, z - 1); - bool s = hasConnection(x, y, z + 1); - bool w = hasConnection(x - 1, y, z); - bool e = hasConnection(x + 1, y, z); + bool n = hasConnection(x, y, z - 1); + bool s = hasConnection(x, y, z + 1); + bool w = hasConnection(x - 1, y, z); + bool e = hasConnection(x + 1, y, z); - int dir = -1; + int dir = -1; - if (n || s) dir = DIR_FLAT_Z; - if (w || e) dir = DIR_FLAT_X; + if (n || s) dir = DIR_FLAT_Z; + if (w || e) dir = DIR_FLAT_X; - if (!usesDataBit) - { - if (s && e && !n && !w) dir = 6; - if (s && w && !n && !e) dir = 7; - if (n && w && !s && !e) dir = 8; - if (n && e && !s && !w) dir = 9; - } - if (dir == DIR_FLAT_Z) - { - if (isRail(level, x, y + 1, z - 1)) dir = 4; - if (isRail(level, x, y + 1, z + 1)) dir = 5; - } - if (dir == DIR_FLAT_X) - { - if (isRail(level, x + 1, y + 1, z)) dir = 2; - if (isRail(level, x - 1, y + 1, z)) dir = 3; - } + if (!usesDataBit) { + if (s && e && !n && !w) dir = 6; + if (s && w && !n && !e) dir = 7; + if (n && w && !s && !e) dir = 8; + if (n && e && !s && !w) dir = 9; + } + if (dir == DIR_FLAT_Z) { + if (isRail(level, x, y + 1, z - 1)) dir = 4; + if (isRail(level, x, y + 1, z + 1)) dir = 5; + } + if (dir == DIR_FLAT_X) { + if (isRail(level, x + 1, y + 1, z)) dir = 2; + if (isRail(level, x - 1, y + 1, z)) dir = 3; + } - if (dir < 0) dir = DIR_FLAT_Z; + if (dir < 0) dir = DIR_FLAT_Z; - int data = dir; - if (usesDataBit) - { - data = (level->getData(x, y, z) & RAIL_DATA_BIT) | dir; - } + int data = dir; + if (usesDataBit) { + data = (level->getData(x, y, z) & RAIL_DATA_BIT) | dir; + } - level->setData(x, y, z, data); - } + level->setData(x, y, z, data); + } } -bool RailTile::Rail::hasNeighborRail(int x, int y, int z) -{ - if(!m_bValidRail) return false; - TilePos tp(x,y,z); - Rail *neighbor = getRail( &tp ); - if (neighbor == NULL) return false; - neighbor->removeSoftConnections(); - bool retval = neighbor->canConnectTo(this); - delete neighbor; - return retval; +bool RailTile::Rail::hasNeighborRail(int x, int y, int z) { + if (!m_bValidRail) return false; + TilePos tp(x, y, z); + Rail* neighbor = getRail(&tp); + if (neighbor == NULL) return false; + neighbor->removeSoftConnections(); + bool retval = neighbor->canConnectTo(this); + delete neighbor; + return retval; } -void RailTile::Rail::place(bool hasSignal, bool first) -{ - if(m_bValidRail) - { - bool n = hasNeighborRail(x, y, z - 1); - bool s = hasNeighborRail(x, y, z + 1); - bool w = hasNeighborRail(x - 1, y, z); - bool e = hasNeighborRail(x + 1, y, z); +void RailTile::Rail::place(bool hasSignal, bool first) { + if (m_bValidRail) { + bool n = hasNeighborRail(x, y, z - 1); + bool s = hasNeighborRail(x, y, z + 1); + bool w = hasNeighborRail(x - 1, y, z); + bool e = hasNeighborRail(x + 1, y, z); - int dir = -1; + int dir = -1; - if ((n || s) && !w && !e) dir = DIR_FLAT_Z; - if ((w || e) && !n && !s) dir = DIR_FLAT_X; + if ((n || s) && !w && !e) dir = DIR_FLAT_Z; + if ((w || e) && !n && !s) dir = DIR_FLAT_X; - if (!usesDataBit) - { - if (s && e && !n && !w) dir = 6; - if (s && w && !n && !e) dir = 7; - if (n && w && !s && !e) dir = 8; - if (n && e && !s && !w) dir = 9; - } - if (dir == -1) - { - if (n || s) dir = DIR_FLAT_Z; - if (w || e) dir = DIR_FLAT_X; + if (!usesDataBit) { + if (s && e && !n && !w) dir = 6; + if (s && w && !n && !e) dir = 7; + if (n && w && !s && !e) dir = 8; + if (n && e && !s && !w) dir = 9; + } + if (dir == -1) { + if (n || s) dir = DIR_FLAT_Z; + if (w || e) dir = DIR_FLAT_X; - if (!usesDataBit) - { - if (hasSignal) - { - if (s && e) dir = 6; - if (w && s) dir = 7; - if (e && n) dir = 9; - if (n && w) dir = 8; - } else { - if (n && w) dir = 8; - if (e && n) dir = 9; - if (w && s) dir = 7; - if (s && e) dir = 6; - } - } - } + if (!usesDataBit) { + if (hasSignal) { + if (s && e) dir = 6; + if (w && s) dir = 7; + if (e && n) dir = 9; + if (n && w) dir = 8; + } else { + if (n && w) dir = 8; + if (e && n) dir = 9; + if (w && s) dir = 7; + if (s && e) dir = 6; + } + } + } - if (dir == DIR_FLAT_Z) - { - if (isRail(level, x, y + 1, z - 1)) dir = 4; - if (isRail(level, x, y + 1, z + 1)) dir = 5; - } - if (dir == DIR_FLAT_X) - { - if (isRail(level, x + 1, y + 1, z)) dir = 2; - if (isRail(level, x - 1, y + 1, z)) dir = 3; - } + if (dir == DIR_FLAT_Z) { + if (isRail(level, x, y + 1, z - 1)) dir = 4; + if (isRail(level, x, y + 1, z + 1)) dir = 5; + } + if (dir == DIR_FLAT_X) { + if (isRail(level, x + 1, y + 1, z)) dir = 2; + if (isRail(level, x - 1, y + 1, z)) dir = 3; + } - if (dir < 0) dir = DIR_FLAT_Z; + if (dir < 0) dir = DIR_FLAT_Z; - updateConnections(dir); + updateConnections(dir); - int data = dir; - if (usesDataBit) - { - data = (level->getData(x, y, z) & RAIL_DATA_BIT) | dir; - } + int data = dir; + if (usesDataBit) { + data = (level->getData(x, y, z) & RAIL_DATA_BIT) | dir; + } - if (first || level->getData(x, y, z) != data) - { - level->setData(x, y, z, data); + if (first || level->getData(x, y, z) != data) { + level->setData(x, y, z, data); - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) - { - Rail *neighbor = getRail(*it); - if (neighbor == NULL) continue; - neighbor->removeSoftConnections(); + AUTO_VAR(itEnd, connections.end()); + for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) { + Rail* neighbor = getRail(*it); + if (neighbor == NULL) continue; + neighbor->removeSoftConnections(); - if (neighbor->canConnectTo(this)) - { - neighbor->connectTo(this); - } - delete neighbor; - } - } - } + if (neighbor->canConnectTo(this)) { + neighbor->connectTo(this); + } + delete neighbor; + } + } + } } -bool RailTile::isRail(Level *level, int x, int y, int z) -{ - int tile = level->getTile(x, y, z); - return tile == Tile::rail_Id || tile == Tile::goldenRail_Id || tile == Tile::detectorRail_Id; - +bool RailTile::isRail(Level* level, int x, int y, int z) { + int tile = level->getTile(x, y, z); + return tile == Tile::rail_Id || tile == Tile::goldenRail_Id || + tile == Tile::detectorRail_Id; } -bool RailTile::isRail(int id) -{ - return id == Tile::rail_Id || id == Tile::goldenRail_Id || id == Tile::detectorRail_Id; +bool RailTile::isRail(int id) { + return id == Tile::rail_Id || id == Tile::goldenRail_Id || + id == Tile::detectorRail_Id; } -// 4jcraft, changed from isSolidRender() to false, _init was changed by 4jstudios -// to take in a bool to avoid calling isSolidRender before the vptr is set, -RailTile::RailTile(int id, bool usesDataBit) : Tile(id, Material::decoration, false) -{ - this->usesDataBit = usesDataBit; - this->setShape(0, 0, 0, 1, 2 / 16.0f, 1); +// 4jcraft, changed from isSolidRender() to false, _init was changed by +// 4jstudios to take in a bool to avoid calling isSolidRender before the vptr is +// set, +RailTile::RailTile(int id, bool usesDataBit) + : Tile(id, Material::decoration, false) { + this->usesDataBit = usesDataBit; + this->setShape(0, 0, 0, 1, 2 / 16.0f, 1); - iconTurn = NULL; + iconTurn = NULL; } -bool RailTile::isUsesDataBit() -{ - return usesDataBit; +bool RailTile::isUsesDataBit() { return usesDataBit; } + +AABB* RailTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +bool RailTile::blocksLight() { return false; } + +bool RailTile::isSolidRender(bool isServerLevel) { return false; } + +HitResult* RailTile::clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b) { + updateShape(level, xt, yt, zt); + return Tile::clip(level, xt, yt, zt, a, b); } -AABB *RailTile::getAABB(Level *level, int x, int y, int z) +void RailTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - return NULL; + int data = level->getData(x, y, z); + if (data >= 2 && data <= 5) { + setShape(0, 0, 0, 1, 2 / 16.0f + 0.5f, 1); + } else { + setShape(0, 0, 0, 1, 2 / 16.0f, 1); + } } -bool RailTile::blocksLight() -{ - return false; +Icon* RailTile::getTexture(int face, int data) { + if (usesDataBit) { + if (id == Tile::goldenRail_Id) { + if ((data & RAIL_DATA_BIT) == 0) { + return icon; + } else { + return iconTurn; // Actually the powered rail on version + } + } + } else if (data >= 6) + return iconTurn; + return icon; } -bool RailTile::isSolidRender(bool isServerLevel) -{ - return false; +bool RailTile::isCubeShaped() { return false; } + +int RailTile::getRenderShape() { return Tile::SHAPE_RAIL; } + +int RailTile::getResourceCount(Random random) { return 1; } + +bool RailTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isTopSolidBlocking(x, y - 1, z)) { + return true; + } + return false; } -HitResult *RailTile::clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b) -{ - updateShape(level, xt, yt, zt); - return Tile::clip(level, xt, yt, zt, a, b); +void RailTile::onPlace(Level* level, int x, int y, int z) { + if (!level->isClientSide) { + updateDir(level, x, y, z, true); + + if (id == Tile::goldenRail_Id) { + neighborChanged(level, x, y, z, id); + } + } } -void RailTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - int data = level->getData(x, y, z); - if (data >= 2 && data <= 5) - { - setShape(0, 0, 0, 1, 2 / 16.0f + 0.5f, 1); - } else - { - setShape(0, 0, 0, 1, 2 / 16.0f, 1); - } +void RailTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (level->isClientSide) return; + + int data = level->getData(x, y, z); + int dir = data; + if (usesDataBit) { + dir = dir & RAIL_DIRECTION_MASK; + } + bool remove = false; + + if (!level->isTopSolidBlocking(x, y - 1, z)) remove = true; + if (dir == 2 && !level->isTopSolidBlocking(x + 1, y, z)) remove = true; + if (dir == 3 && !level->isTopSolidBlocking(x - 1, y, z)) remove = true; + if (dir == 4 && !level->isTopSolidBlocking(x, y, z - 1)) remove = true; + if (dir == 5 && !level->isTopSolidBlocking(x, y, z + 1)) remove = true; + + if (remove) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } else { + if (id == Tile::goldenRail_Id) { + bool signal = level->hasNeighborSignal(x, y, z); + signal = signal || + findGoldenRailSignal(level, x, y, z, data, true, 0) || + findGoldenRailSignal(level, x, y, z, data, false, 0); + + bool changed = false; + if (signal && (data & RAIL_DATA_BIT) == 0) { + level->setData(x, y, z, dir | RAIL_DATA_BIT); + changed = true; + } else if (!signal && (data & RAIL_DATA_BIT) != 0) { + level->setData(x, y, z, dir); + changed = true; + } + + // usually the level only updates neighbors that are in the same + // y plane as the current tile, but sloped rails may need to + // update tiles above or below it as well + if (changed) { + level->updateNeighborsAt(x, y - 1, z, id); + if (dir == 2 || dir == 3 || dir == 4 || dir == 5) { + level->updateNeighborsAt(x, y + 1, z, id); + } + } + } else if (type > 0 && Tile::tiles[type]->isSignalSource() && + !usesDataBit) { + Rail* rail = new Rail(level, x, y, z); + if (rail->countPotentialConnections() == 3) { + updateDir(level, x, y, z, false); + } + delete rail; + } + } } -Icon *RailTile::getTexture(int face, int data) -{ - if (usesDataBit) - { - if (id == Tile::goldenRail_Id) - { - if ((data & RAIL_DATA_BIT) == 0) - { - return icon; - } - else - { - return iconTurn; // Actually the powered rail on version - } - } - } else if (data >= 6) return iconTurn; - return icon; +void RailTile::updateDir(Level* level, int x, int y, int z, bool first) { + if (level->isClientSide) return; + Rail* rail = new Rail(level, x, y, z); + rail->place(level->hasNeighborSignal(x, y, z), first); + delete rail; } -bool RailTile::isCubeShaped() -{ - return false; +bool RailTile::findGoldenRailSignal(Level* level, int x, int y, int z, int data, + bool forward, int searchDepth) { + if (searchDepth >= 8) { + return false; + } + + int dir = data & RAIL_DIRECTION_MASK; + + bool checkBelow = true; + switch (dir) { + case DIR_FLAT_Z: + if (forward) { + z++; + } else { + z--; + } + break; + case DIR_FLAT_X: + if (forward) { + x--; + } else { + x++; + } + break; + case 2: + if (forward) { + x--; + } else { + x++; + y++; + checkBelow = false; + } + dir = DIR_FLAT_X; + break; + case 3: + if (forward) { + x--; + y++; + checkBelow = false; + } else { + x++; + } + dir = DIR_FLAT_X; + break; + case 4: + if (forward) { + z++; + } else { + z--; + y++; + checkBelow = false; + } + dir = DIR_FLAT_Z; + break; + case 5: + if (forward) { + z++; + y++; + checkBelow = false; + } else { + z--; + } + dir = DIR_FLAT_Z; + break; + } + + if (isGoldenRailWithPower(level, x, y, z, forward, searchDepth, dir)) { + return true; + } + if (checkBelow && + isGoldenRailWithPower(level, x, y - 1, z, forward, searchDepth, dir)) { + return true; + } + return false; } -int RailTile::getRenderShape() -{ - return Tile::SHAPE_RAIL; +bool RailTile::isGoldenRailWithPower(Level* level, int x, int y, int z, + bool forward, int searchDepth, int dir) { + int tile = level->getTile(x, y, z); + if (tile == Tile::goldenRail_Id) { + int tileData = level->getData(x, y, z); + int myDir = tileData & RAIL_DIRECTION_MASK; + + if (dir == DIR_FLAT_X && + (myDir == DIR_FLAT_Z || myDir == 4 || myDir == 5)) { + return false; + } + if (dir == DIR_FLAT_Z && + (myDir == DIR_FLAT_X || myDir == 2 || myDir == 3)) { + return false; + } + + if ((tileData & RAIL_DATA_BIT) != 0) { + if (level->hasNeighborSignal(x, y, z)) { + return true; + } else { + return findGoldenRailSignal(level, x, y, z, tileData, forward, + searchDepth + 1); + } + } + } + return false; } -int RailTile::getResourceCount(Random random) -{ - return 1; -} - -bool RailTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isTopSolidBlocking(x, y - 1, z)) - { - return true; - } - return false; -} - -void RailTile::onPlace(Level *level, int x, int y, int z) -{ - if (!level->isClientSide) - { - updateDir(level, x, y, z, true); - - if (id == Tile::goldenRail_Id) - { - neighborChanged(level, x, y, z, id); - } - } -} - -void RailTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (level->isClientSide) return; - - int data = level->getData(x, y, z); - int dir = data; - if (usesDataBit) { - dir = dir & RAIL_DIRECTION_MASK; - } - bool remove = false; - - if (!level->isTopSolidBlocking(x, y - 1, z)) remove = true; - if (dir == 2 && !level->isTopSolidBlocking(x + 1, y, z)) remove = true; - if (dir == 3 && !level->isTopSolidBlocking(x - 1, y, z)) remove = true; - if (dir == 4 && !level->isTopSolidBlocking(x, y, z - 1)) remove = true; - if (dir == 5 && !level->isTopSolidBlocking(x, y, z + 1)) remove = true; - - if (remove) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } - else - { - if (id == Tile::goldenRail_Id) - { - bool signal = level->hasNeighborSignal(x, y, z); - signal = signal || findGoldenRailSignal(level, x, y, z, data, true, 0) || findGoldenRailSignal(level, x, y, z, data, false, 0); - - bool changed = false; - if (signal && (data & RAIL_DATA_BIT) == 0) - { - level->setData(x, y, z, dir | RAIL_DATA_BIT); - changed = true; - } else if (!signal && (data & RAIL_DATA_BIT) != 0) - { - level->setData(x, y, z, dir); - changed = true; - } - - // usually the level only updates neighbors that are in the same - // y plane as the current tile, but sloped rails may need to - // update tiles above or below it as well - if (changed) { - level->updateNeighborsAt(x, y - 1, z, id); - if (dir == 2 || dir == 3 || dir == 4 || dir == 5) - { - level->updateNeighborsAt(x, y + 1, z, id); - } - } - } - else if (type > 0 && Tile::tiles[type]->isSignalSource() && !usesDataBit) - { - Rail *rail = new Rail(level, x, y, z); - if (rail->countPotentialConnections() == 3) - { - updateDir(level, x, y, z, false); - } - delete rail; - } - } - -} - -void RailTile::updateDir(Level *level, int x, int y, int z, bool first) -{ - if (level->isClientSide) return; - Rail *rail = new Rail(level, x, y, z); - rail->place(level->hasNeighborSignal(x, y, z), first); - delete rail; -} - -bool RailTile::findGoldenRailSignal(Level *level, int x, int y, int z, int data, bool forward, int searchDepth) -{ - if (searchDepth >= 8) - { - return false; - } - - int dir = data & RAIL_DIRECTION_MASK; - - bool checkBelow = true; - switch (dir) - { - case DIR_FLAT_Z: - if (forward) - { - z++; - } else { - z--; - } - break; - case DIR_FLAT_X: - if (forward) - { - x--; - } else { - x++; - } - break; - case 2: - if (forward) - { - x--; - } else - { - x++; - y++; - checkBelow = false; - } - dir = DIR_FLAT_X; - break; - case 3: - if (forward) - { - x--; - y++; - checkBelow = false; - } else { - x++; - } - dir = DIR_FLAT_X; - break; - case 4: - if (forward) - { - z++; - } else { - z--; - y++; - checkBelow = false; - } - dir = DIR_FLAT_Z; - break; - case 5: - if (forward) - { - z++; - y++; - checkBelow = false; - } else - { - z--; - } - dir = DIR_FLAT_Z; - break; - } - - if (isGoldenRailWithPower(level, x, y, z, forward, searchDepth, dir)) - { - return true; - } - if (checkBelow && isGoldenRailWithPower(level, x, y - 1, z, forward, searchDepth, dir)) - { - return true; - } - return false; - -} - -bool RailTile::isGoldenRailWithPower(Level *level, int x, int y, int z, bool forward, int searchDepth, int dir) -{ - int tile = level->getTile(x, y, z); - if (tile == Tile::goldenRail_Id) - { - int tileData = level->getData(x, y, z); - int myDir = tileData & RAIL_DIRECTION_MASK; - - if (dir == DIR_FLAT_X && (myDir == DIR_FLAT_Z || myDir == 4 || myDir == 5)) - { - return false; - } - if (dir == DIR_FLAT_Z && (myDir == DIR_FLAT_X || myDir == 2 || myDir == 3)) - { - return false; - } - - if ((tileData & RAIL_DATA_BIT) != 0) - { - if (level->hasNeighborSignal(x, y, z)) - { - return true; - } - else - { - return findGoldenRailSignal(level, x, y, z, tileData, forward, searchDepth + 1); - } - } - } - return false; -} - -int RailTile::getPistonPushReaction() -{ - return Material::PUSH_NORMAL; -} - -void RailTile::registerIcons(IconRegister *iconRegister) -{ - Tile::registerIcons(iconRegister); - if(id == Tile::goldenRail_Id) - { - iconTurn = iconRegister->registerIcon(L"goldenRail_powered"); - } - else - { - iconTurn = iconRegister->registerIcon(L"rail_turn"); - } +int RailTile::getPistonPushReaction() { return Material::PUSH_NORMAL; } + +void RailTile::registerIcons(IconRegister* iconRegister) { + Tile::registerIcons(iconRegister); + if (id == Tile::goldenRail_Id) { + iconTurn = iconRegister->registerIcon(L"goldenRail_powered"); + } else { + iconTurn = iconRegister->registerIcon(L"rail_turn"); + } } diff --git a/Minecraft.World/Blocks/RailTile.h b/Minecraft.World/Blocks/RailTile.h index e428aa110..ada085fca 100644 --- a/Minecraft.World/Blocks/RailTile.h +++ b/Minecraft.World/Blocks/RailTile.h @@ -7,78 +7,90 @@ class Random; class HitResult; class ChunkRebuildData; +class RailTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; - -class RailTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; public: - static const int DIR_FLAT_Z = 0; + static const int DIR_FLAT_Z = 0; static const int DIR_FLAT_X = 1; // the data bit is used by boosters and detectors, so they can't turn static const int RAIL_DATA_BIT = 8; static const int RAIL_DIRECTION_MASK = 7; private: - Icon *iconTurn; + Icon* iconTurn; - bool usesDataBit; + bool usesDataBit; - class Rail - { - friend class RailTile; - private: - Level *level; + class Rail { + friend class RailTile; + + private: + Level* level; int x, y, z; bool usesDataBit; - std::vector connections; - bool m_bValidRail; // 4J added + std::vector connections; + bool m_bValidRail; // 4J added - public: - Rail(Level *level, int x, int y, int z); - ~Rail(); - private: - void updateConnections(int direction); - void removeSoftConnections(); - bool hasRail(int x, int y, int z); - Rail *getRail(TilePos *p); - bool connectsTo(Rail *rail); - bool hasConnection(int x, int y, int z); - int countPotentialConnections(); - bool canConnectTo(Rail *rail); - private: - void connectTo(Rail *rail); - bool hasNeighborRail(int x, int y, int z); - public: + public: + Rail(Level* level, int x, int y, int z); + ~Rail(); + + private: + void updateConnections(int direction); + void removeSoftConnections(); + bool hasRail(int x, int y, int z); + Rail* getRail(TilePos* p); + bool connectsTo(Rail* rail); + bool hasConnection(int x, int y, int z); + int countPotentialConnections(); + bool canConnectTo(Rail* rail); + + private: + void connectTo(Rail* rail); + bool hasNeighborRail(int x, int y, int z); + + public: void place(bool hasSignal, bool first); - }; -public: - static bool isRail(Level *level, int x, int y, int z); - static bool isRail(int id); -protected: - RailTile(int id, bool usesDataBit); -public: - using Tile::getResourceCount; + }; - bool isUsesDataBit(); - virtual AABB *getAABB(Level *level, int x, int y, int z); +public: + static bool isRail(Level* level, int x, int y, int z); + static bool isRail(int id); + +protected: + RailTile(int id, bool usesDataBit); + +public: + using Tile::getResourceCount; + + bool isUsesDataBit(); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool blocksLight(); virtual bool isSolidRender(bool isServerLevel = false); - virtual HitResult *clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual Icon *getTexture(int face, int data); - virtual bool isCubeShaped(); + virtual HitResult* clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual Icon* getTexture(int face, int data); + virtual bool isCubeShaped(); virtual int getRenderShape(); virtual int getResourceCount(Random random); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + private: - void updateDir(Level *level, int x, int y, int z, bool first); - bool findGoldenRailSignal(Level *level, int x, int y, int z, int data, bool forward, int searchDepth); - bool isGoldenRailWithPower(Level *level, int x, int y, int z, bool forward, int searchDepth, int dir); + void updateDir(Level* level, int x, int y, int z, bool first); + bool findGoldenRailSignal(Level* level, int x, int y, int z, int data, + bool forward, int searchDepth); + bool isGoldenRailWithPower(Level* level, int x, int y, int z, bool forward, + int searchDepth, int dir); + public: - virtual int getPistonPushReaction(); - void registerIcons(IconRegister *iconRegister); + virtual int getPistonPushReaction(); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/RecordPlayerTile.cpp b/Minecraft.World/Blocks/RecordPlayerTile.cpp index c727eff43..2c3708158 100644 --- a/Minecraft.World/Blocks/RecordPlayerTile.cpp +++ b/Minecraft.World/Blocks/RecordPlayerTile.cpp @@ -7,62 +7,63 @@ #include "RecordPlayerTile.h" #include "../Level/Events/LevelEvent.h" - -RecordPlayerTile::RecordPlayerTile(int id) : EntityTile(id, Material::wood) -{ - iconTop = NULL; +RecordPlayerTile::RecordPlayerTile(int id) : EntityTile(id, Material::wood) { + iconTop = NULL; } -Icon *RecordPlayerTile::getTexture(int face, int data) -{ - if (face == Facing::UP) - { - return iconTop; - } - return icon; +Icon* RecordPlayerTile::getTexture(int face, int data) { + if (face == Facing::UP) { + return iconTop; + } + return icon; } // 4J-PB - Adding a TestUse for tooltip display -bool RecordPlayerTile::TestUse(Level *level, int x, int y, int z, std::shared_ptr player) -{ - // if the jukebox is empty, return true - if (level->getData(x, y, z) == 0) return false; - return true; +bool RecordPlayerTile::TestUse(Level* level, int x, int y, int z, + std::shared_ptr player) { + // if the jukebox is empty, return true + if (level->getData(x, y, z) == 0) return false; + return true; } -bool RecordPlayerTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool RecordPlayerTile::use( + Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if (soundOnly) return false; + if (soundOnly) return false; if (level->getData(x, y, z) == 0) return false; dropRecording(level, x, y, z); return true; } -void RecordPlayerTile::setRecord(Level *level, int x, int y, int z, int record) -{ +void RecordPlayerTile::setRecord(Level* level, int x, int y, int z, + int record) { if (level->isClientSide) return; - std::shared_ptr rte = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); + std::shared_ptr rte = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); rte->record = record; rte->setChanged(); level->setData(x, y, z, 1); } -void RecordPlayerTile::dropRecording(Level *level, int x, int y, int z) -{ +void RecordPlayerTile::dropRecording(Level* level, int x, int y, int z) { if (level->isClientSide) return; - std::shared_ptr rte = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if( rte == NULL ) return; + std::shared_ptr rte = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (rte == NULL) return; int oldRecord = rte->record; if (oldRecord == 0) return; - level->levelEvent(LevelEvent::SOUND_PLAY_RECORDING, x, y, z, 0); - // 4J-PB- the level event will play the music - //level->playStreamingMusic(L"", x, y, z); + // 4J-PB- the level event will play the music + // level->playStreamingMusic(L"", x, y, z); rte->record = 0; rte->setChanged(); level->setData(x, y, z, 0); @@ -71,30 +72,32 @@ void RecordPlayerTile::dropRecording(Level *level, int x, int y, int z) double xo = level->random->nextFloat() * s + (1 - s) * 0.5; double yo = level->random->nextFloat() * s + (1 - s) * 0.2 + 0.6; double zo = level->random->nextFloat() * s + (1 - s) * 0.5; - std::shared_ptr item = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr( new ItemInstance(oldRecord, 1, 0) ) ) ); + std::shared_ptr item = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance(oldRecord, 1, 0)))); item->throwTime = 10; level->addEntity(item); } -void RecordPlayerTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void RecordPlayerTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { dropRecording(level, x, y, z); Tile::onRemove(level, x, y, z, id, data); } -void RecordPlayerTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ +void RecordPlayerTile::spawnResources(Level* level, int x, int y, int z, + int data, float odds, int playerBonus) { if (level->isClientSide) return; Tile::spawnResources(level, x, y, z, data, odds, 0); } -std::shared_ptr RecordPlayerTile::newTileEntity(Level *level) -{ - return std::shared_ptr( new RecordPlayerTile::Entity() ); +std::shared_ptr RecordPlayerTile::newTileEntity(Level* level) { + return std::shared_ptr( + new RecordPlayerTile::Entity()); } -void RecordPlayerTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"musicBlock"); - iconTop = iconRegister->registerIcon(L"jukebox_top"); +void RecordPlayerTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"musicBlock"); + iconTop = iconRegister->registerIcon(L"jukebox_top"); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/RecordPlayerTile.h b/Minecraft.World/Blocks/RecordPlayerTile.h index a12874f88..df49121a3 100644 --- a/Minecraft.World/Blocks/RecordPlayerTile.h +++ b/Minecraft.World/Blocks/RecordPlayerTile.h @@ -7,62 +7,67 @@ class CompoundTag; class ChunkRebuildData; -class RecordPlayerTile : public EntityTile -{ - friend class Tile; - friend class ChunkRebuildData; -public: - class Entity : public TileEntity - { -public: - eINSTANCEOF GetType() { return eTYPE_RECORDPLAYERTILE; } - static TileEntity *create() { return new RecordPlayerTile::Entity(); } +class RecordPlayerTile : public EntityTile { + friend class Tile; + friend class ChunkRebuildData; - public: - int record; - Entity() : TileEntity(), record( 0 ) {} +public: + class Entity : public TileEntity { + public: + eINSTANCEOF GetType() { return eTYPE_RECORDPLAYERTILE; } + static TileEntity* create() { return new RecordPlayerTile::Entity(); } - virtual void load(CompoundTag *tag) - { + public: + int record; + Entity() : TileEntity(), record(0) {} + + virtual void load(CompoundTag* tag) { TileEntity::load(tag); record = tag->getInt(L"Record"); } - virtual void save(CompoundTag *tag) - { + virtual void save(CompoundTag* tag) { TileEntity::save(tag); if (record > 0) tag->putInt(L"Record", record); - // return true; // 4J - TODO, in java there is no return type here but we can't change our derived class member function to not have one - investigate - // 4J Jev, took out the return statement, TileEntity::save is now virtual. Think this fixes above. + // return true; // 4J - TODO, in java there is no return type + // here but we can't change our derived class member function to not + // have one - investigate 4J Jev, took out the return statement, + // TileEntity::save is now virtual. Think this fixes above. } - // 4J Added - std::shared_ptr clone() - { - std::shared_ptr result = std::shared_ptr( new RecordPlayerTile::Entity() ); - TileEntity::clone(result); + // 4J Added + std::shared_ptr clone() { + std::shared_ptr result = + std::shared_ptr( + new RecordPlayerTile::Entity()); + TileEntity::clone(result); - result->record = record; + result->record = record; - return result; - } + return result; + } }; private: - Icon *iconTop; + Icon* iconTop; protected: - RecordPlayerTile(int id); + RecordPlayerTile(int id); public: - virtual Icon *getTexture(int face, int data); - virtual bool TestUse(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param - void setRecord(Level *level, int x, int y, int z, int record); - void dropRecording(Level *level, int x, int y, int z); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); + virtual Icon* getTexture(int face, int data); + virtual bool TestUse(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param + void setRecord(Level* level, int x, int y, int z, int record); + void dropRecording(Level* level, int x, int y, int z); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); - virtual std::shared_ptr newTileEntity(Level *level); - void registerIcons(IconRegister *iconRegister); + virtual std::shared_ptr newTileEntity(Level* level); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/RedLightTile.cpp b/Minecraft.World/Blocks/RedLightTile.cpp index db30b263a..627f473dd 100644 --- a/Minecraft.World/Blocks/RedLightTile.cpp +++ b/Minecraft.World/Blocks/RedLightTile.cpp @@ -4,75 +4,56 @@ #include "../Headers/net.minecraft.world.h" #include "RedLightTile.h" -RedlightTile::RedlightTile(int id, bool isLit) : Tile(id, Material::buildable_glass) -{ - this->isLit = isLit; +RedlightTile::RedlightTile(int id, bool isLit) + : Tile(id, Material::buildable_glass) { + this->isLit = isLit; - if (isLit) - { - setLightEmission(1.0f); - } + if (isLit) { + setLightEmission(1.0f); + } } -void RedlightTile::registerIcons(IconRegister *iconRegister) -{ - if (isLit) - { - icon = iconRegister->registerIcon(L"redstoneLight_lit"); - } - else - { - icon = iconRegister->registerIcon(L"redstoneLight"); - } +void RedlightTile::registerIcons(IconRegister* iconRegister) { + if (isLit) { + icon = iconRegister->registerIcon(L"redstoneLight_lit"); + } else { + icon = iconRegister->registerIcon(L"redstoneLight"); + } } -void RedlightTile::onPlace(Level *level, int x, int y, int z) -{ - if (!level->isClientSide) - { - if (isLit && !level->hasNeighborSignal(x, y, z)) - { - level->addToTickNextTick(x, y, z, id, 4); - } - else if (!isLit && level->hasNeighborSignal(x, y, z)) - { - level->setTile(x, y, z, Tile::redstoneLight_lit_Id); - } - } +void RedlightTile::onPlace(Level* level, int x, int y, int z) { + if (!level->isClientSide) { + if (isLit && !level->hasNeighborSignal(x, y, z)) { + level->addToTickNextTick(x, y, z, id, 4); + } else if (!isLit && level->hasNeighborSignal(x, y, z)) { + level->setTile(x, y, z, Tile::redstoneLight_lit_Id); + } + } } -void RedlightTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isClientSide) - { - if (isLit && !level->hasNeighborSignal(x, y, z)) - { - level->addToTickNextTick(x, y, z, id, 4); - } - else if (!isLit && level->hasNeighborSignal(x, y, z)) - { - level->setTile(x, y, z, Tile::redstoneLight_lit_Id); - } - } +void RedlightTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (!level->isClientSide) { + if (isLit && !level->hasNeighborSignal(x, y, z)) { + level->addToTickNextTick(x, y, z, id, 4); + } else if (!isLit && level->hasNeighborSignal(x, y, z)) { + level->setTile(x, y, z, Tile::redstoneLight_lit_Id); + } + } } -void RedlightTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (!level->isClientSide) - { - if (isLit && !level->hasNeighborSignal(x, y, z)) - { - level->setTile(x, y, z, Tile::redstoneLight_Id); - } - } +void RedlightTile::tick(Level* level, int x, int y, int z, Random* random) { + if (!level->isClientSide) { + if (isLit && !level->hasNeighborSignal(x, y, z)) { + level->setTile(x, y, z, Tile::redstoneLight_Id); + } + } } -int RedlightTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::redstoneLight_Id; +int RedlightTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::redstoneLight_Id; } -int RedlightTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Tile::redstoneLight_Id; +int RedlightTile::cloneTileId(Level* level, int x, int y, int z) { + return Tile::redstoneLight_Id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/RedLightTile.h b/Minecraft.World/Blocks/RedLightTile.h index f7b1c4612..fef1b97d7 100644 --- a/Minecraft.World/Blocks/RedLightTile.h +++ b/Minecraft.World/Blocks/RedLightTile.h @@ -2,18 +2,17 @@ #include "Tile.h" -class RedlightTile : public Tile -{ +class RedlightTile : public Tile { private: - bool isLit; + bool isLit; public: - RedlightTile(int id, bool isLit); + RedlightTile(int id, bool isLit); - virtual void registerIcons(IconRegister *iconRegister); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int cloneTileId(Level *level, int x, int y, int z); + virtual void registerIcons(IconRegister* iconRegister); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int cloneTileId(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/RedStoneDustTile.cpp b/Minecraft.World/Blocks/RedStoneDustTile.cpp index 6133ac039..fa7c63757 100644 --- a/Minecraft.World/Blocks/RedStoneDustTile.cpp +++ b/Minecraft.World/Blocks/RedStoneDustTile.cpp @@ -13,419 +13,440 @@ const std::wstring RedStoneDustTile::TEXTURE_CROSS = L"redstoneDust_cross"; const std::wstring RedStoneDustTile::TEXTURE_LINE = L"redstoneDust_line"; -const std::wstring RedStoneDustTile::TEXTURE_CROSS_OVERLAY = L"redstoneDust_cross_overlay"; -const std::wstring RedStoneDustTile::TEXTURE_LINE_OVERLAY = L"redstoneDust_line_overlay"; +const std::wstring RedStoneDustTile::TEXTURE_CROSS_OVERLAY = + L"redstoneDust_cross_overlay"; +const std::wstring RedStoneDustTile::TEXTURE_LINE_OVERLAY = + L"redstoneDust_line_overlay"; -RedStoneDustTile::RedStoneDustTile(int id) : Tile(id, Material::decoration, false) -{ - shouldSignal = true; +RedStoneDustTile::RedStoneDustTile(int id) + : Tile(id, Material::decoration, false) { + shouldSignal = true; - updateDefaultShape(); + updateDefaultShape(); - iconCross = NULL; - iconLine = NULL; - iconCrossOver = NULL; - iconLineOver = NULL; + iconCross = NULL; + iconLine = NULL; + iconCrossOver = NULL; + iconLineOver = NULL; } // 4J Added override -void RedStoneDustTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 1 / 16.0f, 1); +void RedStoneDustTile::updateDefaultShape() { + setShape(0, 0, 0, 1, 1 / 16.0f, 1); } -AABB *RedStoneDustTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* RedStoneDustTile::getAABB(Level* level, int x, int y, int z) { + return NULL; } -bool RedStoneDustTile::isSolidRender(bool isServerLevel) -{ - return false; +bool RedStoneDustTile::isSolidRender(bool isServerLevel) { return false; } + +bool RedStoneDustTile::isCubeShaped() { return false; } + +int RedStoneDustTile::getRenderShape() { return Tile::SHAPE_RED_DUST; } + +int RedStoneDustTile::getColor() const { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDust); // 0x800000; } -bool RedStoneDustTile::isCubeShaped() -{ - return false; +int RedStoneDustTile::getColor(LevelSource* level, int x, int y, int z) { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDust); // 0x800000; } -int RedStoneDustTile::getRenderShape() -{ - return Tile::SHAPE_RED_DUST; +int RedStoneDustTile::getColor(LevelSource* level, int x, int y, int z, + int data) { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDust); // 0x800000; } -int RedStoneDustTile::getColor() const -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_RedstoneDust); // 0x800000; +bool RedStoneDustTile::mayPlace(Level* level, int x, int y, int z) { + return level->isTopSolidBlocking(x, y - 1, z) || + level->getTile(x, y - 1, z) == Tile::lightGem_Id; } -int RedStoneDustTile::getColor(LevelSource *level, int x, int y, int z) -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_RedstoneDust); // 0x800000; -} +void RedStoneDustTile::updatePowerStrength(Level* level, int x, int y, int z) { + updatePowerStrength(level, x, y, z, x, y, z); -int RedStoneDustTile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_RedstoneDust); // 0x800000; -} + std::vector updates = + std::vector(toUpdate.begin(), toUpdate.end()); + toUpdate.clear(); -bool RedStoneDustTile::mayPlace(Level *level, int x, int y, int z) -{ - return level->isTopSolidBlocking(x, y - 1, z) || level->getTile(x, y - 1, z) == Tile::lightGem_Id; -} - -void RedStoneDustTile::updatePowerStrength(Level *level, int x, int y, int z) -{ - updatePowerStrength(level, x, y, z, x, y, z); - - std::vector updates = std::vector(toUpdate.begin(), toUpdate.end()); - toUpdate.clear(); - - AUTO_VAR(itEnd, updates.end()); - for(AUTO_VAR(it, updates.begin()); it != itEnd; it++) - { - TilePos tp = *it; - level->updateNeighborsAt(tp.x, tp.y, tp.z, id); - } -} - -void RedStoneDustTile::updatePowerStrength(Level *level, int x, int y, int z, int xFrom, int yFrom, int zFrom) -{ - int old = level->getData(x, y, z); - int target = 0; - - this->shouldSignal = false; - bool neighborSignal = level->hasNeighborSignal(x, y, z); - this->shouldSignal = true; - - if (neighborSignal) - { - target = 15; - } - else - { - for (int i = 0; i < 4; i++) - { - int xt = x; - int zt = z; - if (i == 0) xt--; - if (i == 1) xt++; - if (i == 2) zt--; - if (i == 3) zt++; - - if (xt != xFrom || y != yFrom || zt != zFrom) target = checkTarget(level, xt, y, zt, target); - if (level->isSolidBlockingTile(xt, y, zt) && !level->isSolidBlockingTile(x, y + 1, z)) - { - if (xt != xFrom || y + 1 != yFrom || zt != zFrom) target = checkTarget(level, xt, y + 1, zt, target); - } - else if (!level->isSolidBlockingTile(xt, y, zt)) - { - if (xt != xFrom || y - 1 != yFrom || zt != zFrom) target = checkTarget(level, xt, y - 1, zt, target); - } - } - if (target > 0) target--; - else target = 0; - } - - if (old != target) - { - level->noNeighborUpdate = true; - level->setData(x, y, z, target); - level->setTilesDirty(x, y, z, x, y, z); - level->noNeighborUpdate = false; - - for (int i = 0; i < 4; i++) - { - int xt = x; - int zt = z; - int yt = y - 1; - if (i == 0) xt--; - if (i == 1) xt++; - if (i == 2) zt--; - if (i == 3) zt++; - - if (level->isSolidBlockingTile(xt, y, zt)) yt += 2; - - int current = 0; - current = checkTarget(level, xt, y, zt, -1); - target = level->getData(x, y, z); - if (target > 0) target--; - if (current >= 0 && current != target) - { - updatePowerStrength(level, xt, y, zt, x, y, z); - } - current = checkTarget(level, xt, yt, zt, -1); - target = level->getData(x, y, z); - if (target > 0) target--; - if (current >= 0 && current != target) - { - updatePowerStrength(level, xt, yt, zt, x, y, z); - } - } - - if (old < target || target == 0) - { - toUpdate.insert(TilePos(x, y, z)); - toUpdate.insert(TilePos(x - 1, y, z)); - toUpdate.insert(TilePos(x + 1, y, z)); - toUpdate.insert(TilePos(x, y - 1, z)); - toUpdate.insert(TilePos(x, y + 1, z)); - toUpdate.insert(TilePos(x, y, z - 1)); - toUpdate.insert(TilePos(x, y, z + 1)); - } - } -} - -void RedStoneDustTile::checkCornerChangeAt(Level *level, int x, int y, int z) -{ - if (level->getTile(x, y, z) != id) return; - - level->updateNeighborsAt(x, y, z, id); - level->updateNeighborsAt(x - 1, y, z, id); - level->updateNeighborsAt(x + 1, y, z, id); - level->updateNeighborsAt(x, y, z - 1, id); - level->updateNeighborsAt(x, y, z + 1, id); - - level->updateNeighborsAt(x, y - 1, z, id); - level->updateNeighborsAt(x, y + 1, z, id); -} - -void RedStoneDustTile::onPlace(Level *level, int x, int y, int z) -{ - Tile::onPlace(level, x, y, z); - if (level->isClientSide) return; - - updatePowerStrength(level, x, y, z); - level->updateNeighborsAt(x, y + 1, z, id); - level->updateNeighborsAt(x, y - 1, z, id); - - checkCornerChangeAt(level, x - 1, y, z); - checkCornerChangeAt(level, x + 1, y, z); - checkCornerChangeAt(level, x, y, z - 1); - checkCornerChangeAt(level, x, y, z + 1); - - if (level->isSolidBlockingTile(x - 1, y, z)) checkCornerChangeAt(level, x - 1, y + 1, z); - else checkCornerChangeAt(level, x - 1, y - 1, z); - if (level->isSolidBlockingTile(x + 1, y, z)) checkCornerChangeAt(level, x + 1, y + 1, z); - else checkCornerChangeAt(level, x + 1, y - 1, z); - if (level->isSolidBlockingTile(x, y, z - 1)) checkCornerChangeAt(level, x, y + 1, z - 1); - else checkCornerChangeAt(level, x, y - 1, z - 1); - if (level->isSolidBlockingTile(x, y, z + 1)) checkCornerChangeAt(level, x, y + 1, z + 1); - else checkCornerChangeAt(level, x, y - 1, z + 1); - -} - -void RedStoneDustTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - Tile::onRemove(level, x, y, z, id, data); - if (level->isClientSide) return; - - level->updateNeighborsAt(x, y + 1, z, this->id); - level->updateNeighborsAt(x, y - 1, z, this->id); - level->updateNeighborsAt(x + 1, y, z, this->id); - level->updateNeighborsAt(x - 1, y, z, this->id); - level->updateNeighborsAt(x, y, z + 1, this->id); - level->updateNeighborsAt(x, y, z - 1, this->id); - updatePowerStrength(level, x, y, z); - - checkCornerChangeAt(level, x - 1, y, z); - checkCornerChangeAt(level, x + 1, y, z); - checkCornerChangeAt(level, x, y, z - 1); - checkCornerChangeAt(level, x, y, z + 1); - - if (level->isSolidBlockingTile(x - 1, y, z)) checkCornerChangeAt(level, x - 1, y + 1, z); - else checkCornerChangeAt(level, x - 1, y - 1, z); - if (level->isSolidBlockingTile(x + 1, y, z)) checkCornerChangeAt(level, x + 1, y + 1, z); - else checkCornerChangeAt(level, x + 1, y - 1, z); - if (level->isSolidBlockingTile(x, y, z - 1)) checkCornerChangeAt(level, x, y + 1, z - 1); - else checkCornerChangeAt(level, x, y - 1, z - 1); - if (level->isSolidBlockingTile(x, y, z + 1)) checkCornerChangeAt(level, x, y + 1, z + 1); - else checkCornerChangeAt(level, x, y - 1, z + 1); -} - -int RedStoneDustTile::checkTarget(Level *level, int x, int y, int z, int target) -{ - if (level->getTile(x, y, z) != id) return target; - int d = level->getData(x, y, z); - if (d > target) return d; - return target; -} - -void RedStoneDustTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (level->isClientSide) return; - int face = level->getData(x, y, z); - - bool ok = mayPlace(level, x, y, z); - - if (ok) - { - updatePowerStrength(level, x, y, z); - } - else - { - spawnResources(level, x, y, z, face, 0); - level->setTile(x, y, z, 0); - } - - Tile::neighborChanged(level, x, y, z, type); -} - -int RedStoneDustTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::redStone->id; -} - -bool RedStoneDustTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ - if (!shouldSignal) return false; - return getSignal(level, x, y, z, dir); -} - -bool RedStoneDustTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - if (!shouldSignal) return false; - if (level->getData(x, y, z) == 0) return false; - - if (dir == 1) return true; - - bool w = RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y, z, Direction::WEST) - || (!level->isSolidBlockingTile(x - 1, y, z) && RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y - 1, z, Direction::UNDEFINED)); - bool e = RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y, z, Direction::EAST) - || (!level->isSolidBlockingTile(x + 1, y, z) && RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y - 1, z, Direction::UNDEFINED)); - bool n = RedStoneDustTile::shouldReceivePowerFrom(level, x, y, z - 1, Direction::NORTH) - || (!level->isSolidBlockingTile(x, y, z - 1) && RedStoneDustTile::shouldReceivePowerFrom(level, x, y - 1, z - 1, Direction::UNDEFINED)); - bool s = RedStoneDustTile::shouldReceivePowerFrom(level, x, y, z + 1, Direction::SOUTH) - || (!level->isSolidBlockingTile(x, y, z + 1) && RedStoneDustTile::shouldReceivePowerFrom(level, x, y - 1, z + 1, Direction::UNDEFINED)); - - if (!level->isSolidBlockingTile(x, y + 1, z)) - { - if (level->isSolidBlockingTile(x - 1, y, z) && RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y + 1, z, Direction::UNDEFINED)) w = true; - if (level->isSolidBlockingTile(x + 1, y, z) && RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y + 1, z, Direction::UNDEFINED)) e = true; - if (level->isSolidBlockingTile(x, y, z - 1) && RedStoneDustTile::shouldReceivePowerFrom(level, x, y + 1, z - 1, Direction::UNDEFINED)) n = true; - if (level->isSolidBlockingTile(x, y, z + 1) && RedStoneDustTile::shouldReceivePowerFrom(level, x, y + 1, z + 1, Direction::UNDEFINED)) s = true; - } - - if (!n && !e && !w && !s && (dir >= 2 && dir <= 5)) return true; - - if (dir == 2 && n && (!w && !e)) return true; - if (dir == 3 && s && (!w && !e)) return true; - if (dir == 4 && w && (!n && !s)) return true; - if (dir == 5 && e && (!n && !s)) return true; - - return false; - -} - - -bool RedStoneDustTile::isSignalSource() -{ - return shouldSignal; -} - -void RedStoneDustTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - int data = level->getData(x, y, z); - if (data > 0) - { - double xx = x + 0.5 + (random->nextFloat() - 0.5) * 0.2; - double yy = y + 1 / 16.0f; - double zz = z + 0.5 + (random->nextFloat() - 0.5) * 0.2; - // use the x movement variable to determine particle color - - // 4J Stu - Unused - //float pow = (data / 15.0f); - //float red = pow * 0.6f + 0.4f; - //if (data == 0) red = 0; - - //float green = pow * pow * 0.7f - 0.5f; - //float blue = pow * pow * 0.6f - 0.7f; - //if (green < 0) green = 0; - //if (blue < 0) blue = 0; - - unsigned int colour = 0; - if(data == 0) - { - colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustUnlit ); - } - else - { - unsigned int minColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMin ); - unsigned int maxColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMax ); - - uint8_t redComponent = ((minColour>>16)&0xFF) + (( (maxColour>>16)&0xFF - (minColour>>16)&0xFF)*( (data-1)/14.0f)); - uint8_t greenComponent = ((minColour>>8)&0xFF) + (( (maxColour>>8)&0xFF - (minColour>>8)&0xFF)*( (data-1)/14.0f)); - uint8_t blueComponent = ((minColour)&0xFF) + (( (maxColour)&0xFF - (minColour)&0xFF)*( (data-1)/14.0f)); - - colour = redComponent<<16 | greenComponent<<8 | blueComponent; - } - - float red = ((colour>>16)&0xFF)/255.0f; - float green = ((colour>>8)&0xFF)/255.0f; - float blue = (colour&0xFF)/255.0f; - - level->addParticle(eParticleType_reddust, xx, yy, zz, red, green, blue); - } -} - - -bool RedStoneDustTile::shouldConnectTo(LevelSource *level, int x, int y, int z, int direction) -{ - int t = level->getTile(x, y, z); - if (t == Tile::redStoneDust_Id) return true; - if (t == 0) return false; - if (t == Tile::diode_off_Id || t == Tile::diode_on_Id) - { - int data = level->getData(x, y, z); - return direction == (data & DiodeTile::DIRECTION_MASK) || direction == Direction::DIRECTION_OPPOSITE[data & DiodeTile::DIRECTION_MASK]; + AUTO_VAR(itEnd, updates.end()); + for (AUTO_VAR(it, updates.begin()); it != itEnd; it++) { + TilePos tp = *it; + level->updateNeighborsAt(tp.x, tp.y, tp.z, id); } - else if (Tile::tiles[t]->isSignalSource() && direction != Direction::UNDEFINED) return true; - - return false; } -bool RedStoneDustTile::shouldReceivePowerFrom(LevelSource *level, int x, int y, int z, int direction) -{ - if (shouldConnectTo(level, x, y, z, direction)) - { +void RedStoneDustTile::updatePowerStrength(Level* level, int x, int y, int z, + int xFrom, int yFrom, int zFrom) { + int old = level->getData(x, y, z); + int target = 0; + + this->shouldSignal = false; + bool neighborSignal = level->hasNeighborSignal(x, y, z); + this->shouldSignal = true; + + if (neighborSignal) { + target = 15; + } else { + for (int i = 0; i < 4; i++) { + int xt = x; + int zt = z; + if (i == 0) xt--; + if (i == 1) xt++; + if (i == 2) zt--; + if (i == 3) zt++; + + if (xt != xFrom || y != yFrom || zt != zFrom) + target = checkTarget(level, xt, y, zt, target); + if (level->isSolidBlockingTile(xt, y, zt) && + !level->isSolidBlockingTile(x, y + 1, z)) { + if (xt != xFrom || y + 1 != yFrom || zt != zFrom) + target = checkTarget(level, xt, y + 1, zt, target); + } else if (!level->isSolidBlockingTile(xt, y, zt)) { + if (xt != xFrom || y - 1 != yFrom || zt != zFrom) + target = checkTarget(level, xt, y - 1, zt, target); + } + } + if (target > 0) + target--; + else + target = 0; + } + + if (old != target) { + level->noNeighborUpdate = true; + level->setData(x, y, z, target); + level->setTilesDirty(x, y, z, x, y, z); + level->noNeighborUpdate = false; + + for (int i = 0; i < 4; i++) { + int xt = x; + int zt = z; + int yt = y - 1; + if (i == 0) xt--; + if (i == 1) xt++; + if (i == 2) zt--; + if (i == 3) zt++; + + if (level->isSolidBlockingTile(xt, y, zt)) yt += 2; + + int current = 0; + current = checkTarget(level, xt, y, zt, -1); + target = level->getData(x, y, z); + if (target > 0) target--; + if (current >= 0 && current != target) { + updatePowerStrength(level, xt, y, zt, x, y, z); + } + current = checkTarget(level, xt, yt, zt, -1); + target = level->getData(x, y, z); + if (target > 0) target--; + if (current >= 0 && current != target) { + updatePowerStrength(level, xt, yt, zt, x, y, z); + } + } + + if (old < target || target == 0) { + toUpdate.insert(TilePos(x, y, z)); + toUpdate.insert(TilePos(x - 1, y, z)); + toUpdate.insert(TilePos(x + 1, y, z)); + toUpdate.insert(TilePos(x, y - 1, z)); + toUpdate.insert(TilePos(x, y + 1, z)); + toUpdate.insert(TilePos(x, y, z - 1)); + toUpdate.insert(TilePos(x, y, z + 1)); + } + } +} + +void RedStoneDustTile::checkCornerChangeAt(Level* level, int x, int y, int z) { + if (level->getTile(x, y, z) != id) return; + + level->updateNeighborsAt(x, y, z, id); + level->updateNeighborsAt(x - 1, y, z, id); + level->updateNeighborsAt(x + 1, y, z, id); + level->updateNeighborsAt(x, y, z - 1, id); + level->updateNeighborsAt(x, y, z + 1, id); + + level->updateNeighborsAt(x, y - 1, z, id); + level->updateNeighborsAt(x, y + 1, z, id); +} + +void RedStoneDustTile::onPlace(Level* level, int x, int y, int z) { + Tile::onPlace(level, x, y, z); + if (level->isClientSide) return; + + updatePowerStrength(level, x, y, z); + level->updateNeighborsAt(x, y + 1, z, id); + level->updateNeighborsAt(x, y - 1, z, id); + + checkCornerChangeAt(level, x - 1, y, z); + checkCornerChangeAt(level, x + 1, y, z); + checkCornerChangeAt(level, x, y, z - 1); + checkCornerChangeAt(level, x, y, z + 1); + + if (level->isSolidBlockingTile(x - 1, y, z)) + checkCornerChangeAt(level, x - 1, y + 1, z); + else + checkCornerChangeAt(level, x - 1, y - 1, z); + if (level->isSolidBlockingTile(x + 1, y, z)) + checkCornerChangeAt(level, x + 1, y + 1, z); + else + checkCornerChangeAt(level, x + 1, y - 1, z); + if (level->isSolidBlockingTile(x, y, z - 1)) + checkCornerChangeAt(level, x, y + 1, z - 1); + else + checkCornerChangeAt(level, x, y - 1, z - 1); + if (level->isSolidBlockingTile(x, y, z + 1)) + checkCornerChangeAt(level, x, y + 1, z + 1); + else + checkCornerChangeAt(level, x, y - 1, z + 1); +} + +void RedStoneDustTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + Tile::onRemove(level, x, y, z, id, data); + if (level->isClientSide) return; + + level->updateNeighborsAt(x, y + 1, z, this->id); + level->updateNeighborsAt(x, y - 1, z, this->id); + level->updateNeighborsAt(x + 1, y, z, this->id); + level->updateNeighborsAt(x - 1, y, z, this->id); + level->updateNeighborsAt(x, y, z + 1, this->id); + level->updateNeighborsAt(x, y, z - 1, this->id); + updatePowerStrength(level, x, y, z); + + checkCornerChangeAt(level, x - 1, y, z); + checkCornerChangeAt(level, x + 1, y, z); + checkCornerChangeAt(level, x, y, z - 1); + checkCornerChangeAt(level, x, y, z + 1); + + if (level->isSolidBlockingTile(x - 1, y, z)) + checkCornerChangeAt(level, x - 1, y + 1, z); + else + checkCornerChangeAt(level, x - 1, y - 1, z); + if (level->isSolidBlockingTile(x + 1, y, z)) + checkCornerChangeAt(level, x + 1, y + 1, z); + else + checkCornerChangeAt(level, x + 1, y - 1, z); + if (level->isSolidBlockingTile(x, y, z - 1)) + checkCornerChangeAt(level, x, y + 1, z - 1); + else + checkCornerChangeAt(level, x, y - 1, z - 1); + if (level->isSolidBlockingTile(x, y, z + 1)) + checkCornerChangeAt(level, x, y + 1, z + 1); + else + checkCornerChangeAt(level, x, y - 1, z + 1); +} + +int RedStoneDustTile::checkTarget(Level* level, int x, int y, int z, + int target) { + if (level->getTile(x, y, z) != id) return target; + int d = level->getData(x, y, z); + if (d > target) return d; + return target; +} + +void RedStoneDustTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (level->isClientSide) return; + int face = level->getData(x, y, z); + + bool ok = mayPlace(level, x, y, z); + + if (ok) { + updatePowerStrength(level, x, y, z); + } else { + spawnResources(level, x, y, z, face, 0); + level->setTile(x, y, z, 0); + } + + Tile::neighborChanged(level, x, y, z, type); +} + +int RedStoneDustTile::getResource(int data, Random* random, + int playerBonusLevel) { + return Item::redStone->id; +} + +bool RedStoneDustTile::getDirectSignal(Level* level, int x, int y, int z, + int dir) { + if (!shouldSignal) return false; + return getSignal(level, x, y, z, dir); +} + +bool RedStoneDustTile::getSignal(LevelSource* level, int x, int y, int z, + int dir) { + if (!shouldSignal) return false; + if (level->getData(x, y, z) == 0) return false; + + if (dir == 1) return true; + + bool w = RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y, z, + Direction::WEST) || + (!level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y - 1, z, + Direction::UNDEFINED)); + bool e = RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y, z, + Direction::EAST) || + (!level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y - 1, z, + Direction::UNDEFINED)); + bool n = RedStoneDustTile::shouldReceivePowerFrom(level, x, y, z - 1, + Direction::NORTH) || + (!level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldReceivePowerFrom(level, x, y - 1, z - 1, + Direction::UNDEFINED)); + bool s = RedStoneDustTile::shouldReceivePowerFrom(level, x, y, z + 1, + Direction::SOUTH) || + (!level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldReceivePowerFrom(level, x, y - 1, z + 1, + Direction::UNDEFINED)); + + if (!level->isSolidBlockingTile(x, y + 1, z)) { + if (level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldReceivePowerFrom(level, x - 1, y + 1, z, + Direction::UNDEFINED)) + w = true; + if (level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldReceivePowerFrom(level, x + 1, y + 1, z, + Direction::UNDEFINED)) + e = true; + if (level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldReceivePowerFrom(level, x, y + 1, z - 1, + Direction::UNDEFINED)) + n = true; + if (level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldReceivePowerFrom(level, x, y + 1, z + 1, + Direction::UNDEFINED)) + s = true; + } + + if (!n && !e && !w && !s && (dir >= 2 && dir <= 5)) return true; + + if (dir == 2 && n && (!w && !e)) return true; + if (dir == 3 && s && (!w && !e)) return true; + if (dir == 4 && w && (!n && !s)) return true; + if (dir == 5 && e && (!n && !s)) return true; + + return false; +} + +bool RedStoneDustTile::isSignalSource() { return shouldSignal; } + +void RedStoneDustTile::animateTick(Level* level, int x, int y, int z, + Random* random) { + int data = level->getData(x, y, z); + if (data > 0) { + double xx = x + 0.5 + (random->nextFloat() - 0.5) * 0.2; + double yy = y + 1 / 16.0f; + double zz = z + 0.5 + (random->nextFloat() - 0.5) * 0.2; + // use the x movement variable to determine particle color + + // 4J Stu - Unused + // float pow = (data / 15.0f); + // float red = pow * 0.6f + 0.4f; + // if (data == 0) red = 0; + + // float green = pow * pow * 0.7f - 0.5f; + // float blue = pow * pow * 0.6f - 0.7f; + // if (green < 0) green = 0; + // if (blue < 0) blue = 0; + + unsigned int colour = 0; + if (data == 0) { + colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustUnlit); + } else { + unsigned int minColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMin); + unsigned int maxColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMax); + + uint8_t redComponent = + ((minColour >> 16) & 0xFF) + + (((maxColour >> 16) & 0xFF - (minColour >> 16) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t greenComponent = + ((minColour >> 8) & 0xFF) + + (((maxColour >> 8) & 0xFF - (minColour >> 8) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t blueComponent = ((minColour) & 0xFF) + + (((maxColour) & 0xFF - (minColour) & 0xFF) * + ((data - 1) / 14.0f)); + + colour = redComponent << 16 | greenComponent << 8 | blueComponent; + } + + float red = ((colour >> 16) & 0xFF) / 255.0f; + float green = ((colour >> 8) & 0xFF) / 255.0f; + float blue = (colour & 0xFF) / 255.0f; + + level->addParticle(eParticleType_reddust, xx, yy, zz, red, green, blue); + } +} + +bool RedStoneDustTile::shouldConnectTo(LevelSource* level, int x, int y, int z, + int direction) { + int t = level->getTile(x, y, z); + if (t == Tile::redStoneDust_Id) return true; + if (t == 0) return false; + if (t == Tile::diode_off_Id || t == Tile::diode_on_Id) { + int data = level->getData(x, y, z); + return direction == (data & DiodeTile::DIRECTION_MASK) || + direction == + Direction::DIRECTION_OPPOSITE[data & + DiodeTile::DIRECTION_MASK]; + } else if (Tile::tiles[t]->isSignalSource() && + direction != Direction::UNDEFINED) + return true; + + return false; +} + +bool RedStoneDustTile::shouldReceivePowerFrom(LevelSource* level, int x, int y, + int z, int direction) { + if (shouldConnectTo(level, x, y, z, direction)) { return true; } int t = level->getTile(x, y, z); - if (t == Tile::diode_on_Id) - { + if (t == Tile::diode_on_Id) { int data = level->getData(x, y, z); return direction == (data & DiodeTile::DIRECTION_MASK); } return false; } -int RedStoneDustTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::redStone_Id; +int RedStoneDustTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::redStone_Id; } -void RedStoneDustTile::registerIcons(IconRegister *iconRegister) -{ - iconCross = iconRegister->registerIcon(TEXTURE_CROSS); - iconLine = iconRegister->registerIcon(TEXTURE_LINE); - iconCrossOver = iconRegister->registerIcon(TEXTURE_CROSS_OVERLAY); - iconLineOver = iconRegister->registerIcon(TEXTURE_LINE_OVERLAY); +void RedStoneDustTile::registerIcons(IconRegister* iconRegister) { + iconCross = iconRegister->registerIcon(TEXTURE_CROSS); + iconLine = iconRegister->registerIcon(TEXTURE_LINE); + iconCrossOver = iconRegister->registerIcon(TEXTURE_CROSS_OVERLAY); + iconLineOver = iconRegister->registerIcon(TEXTURE_LINE_OVERLAY); - icon = iconCross; + icon = iconCross; } -Icon *RedStoneDustTile::getTexture(const std::wstring &name) -{ +Icon* RedStoneDustTile::getTexture(const std::wstring& name) { #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag - Tesselator* t = Tesselator::getInstance(); - t->setAlphaCutOut( true ); + // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag + Tesselator* t = Tesselator::getInstance(); + t->setAlphaCutOut(true); #endif - if (name.compare(TEXTURE_CROSS) == 0) return Tile::redStoneDust->iconCross; - if (name.compare(TEXTURE_LINE) == 0) return Tile::redStoneDust->iconLine; - if (name.compare(TEXTURE_CROSS_OVERLAY) == 0) return Tile::redStoneDust->iconCrossOver; - if (name.compare(TEXTURE_LINE_OVERLAY) == 0) return Tile::redStoneDust->iconLineOver; - return NULL; + if (name.compare(TEXTURE_CROSS) == 0) return Tile::redStoneDust->iconCross; + if (name.compare(TEXTURE_LINE) == 0) return Tile::redStoneDust->iconLine; + if (name.compare(TEXTURE_CROSS_OVERLAY) == 0) + return Tile::redStoneDust->iconCrossOver; + if (name.compare(TEXTURE_LINE_OVERLAY) == 0) + return Tile::redStoneDust->iconLineOver; + return NULL; } diff --git a/Minecraft.World/Blocks/RedStoneDustTile.h b/Minecraft.World/Blocks/RedStoneDustTile.h index 9b55bfafd..2367a9eb3 100644 --- a/Minecraft.World/Blocks/RedStoneDustTile.h +++ b/Minecraft.World/Blocks/RedStoneDustTile.h @@ -2,60 +2,68 @@ #include "Tile.h" #include "../Util/Definitions.h" - class Random; class Level; class ChunkRebuildData; -class RedStoneDustTile : public Tile -{ - friend ChunkRebuildData; -public: - static const std::wstring TEXTURE_CROSS; - static const std::wstring TEXTURE_LINE; - static const std::wstring TEXTURE_CROSS_OVERLAY; - static const std::wstring TEXTURE_LINE_OVERLAY; -private: - bool shouldSignal; - std::unordered_set toUpdate; - Icon *iconCross; - Icon *iconLine; - Icon *iconCrossOver; - Icon *iconLineOver; +class RedStoneDustTile : public Tile { + friend ChunkRebuildData; public: - RedStoneDustTile(int id); - virtual void updateDefaultShape(); // 4J Added override - virtual AABB *getAABB(Level *level, int x, int y, int z); + static const std::wstring TEXTURE_CROSS; + static const std::wstring TEXTURE_LINE; + static const std::wstring TEXTURE_CROSS_OVERLAY; + static const std::wstring TEXTURE_LINE_OVERLAY; + +private: + bool shouldSignal; + std::unordered_set toUpdate; + Icon* iconCross; + Icon* iconLine; + Icon* iconCrossOver; + Icon* iconLineOver; + +public: + RedStoneDustTile(int id); + virtual void updateDefaultShape(); // 4J Added override + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - virtual int getColor() const; // 4J Added - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added - virtual bool mayPlace(Level *level, int x, int y, int z); + virtual int getColor() const; // 4J Added + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added + virtual bool mayPlace(Level* level, int x, int y, int z); + private: - void updatePowerStrength(Level *level, int x, int y, int z); - void updatePowerStrength(Level *level, int x, int y, int z, int xFrom, int yFrom, int zFrom); - void checkCornerChangeAt(Level *level, int x, int y, int z); + void updatePowerStrength(Level* level, int x, int y, int z); + void updatePowerStrength(Level* level, int x, int y, int z, int xFrom, + int yFrom, int zFrom); + void checkCornerChangeAt(Level* level, int x, int y, int z); + public: - virtual void onPlace(Level *level, int x, int y, int z); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + private: - int checkTarget(Level *level, int x, int y, int z, int target); + int checkTarget(Level* level, int x, int y, int z, int target); + public: - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir) ; - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); virtual bool isSignalSource(); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); - static bool shouldConnectTo(LevelSource *level, int x, int y, int z, int direction); - static bool shouldReceivePowerFrom(LevelSource *level, int x, int y, int z, int direction); - virtual int cloneTileId(Level *level, int x, int y, int z); + static bool shouldConnectTo(LevelSource* level, int x, int y, int z, + int direction); + static bool shouldReceivePowerFrom(LevelSource* level, int x, int y, int z, + int direction); + virtual int cloneTileId(Level* level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); - static Icon *getTexture(const std::wstring &name); + void registerIcons(IconRegister* iconRegister); + static Icon* getTexture(const std::wstring& name); }; diff --git a/Minecraft.World/Blocks/RedStoneOreTile.cpp b/Minecraft.World/Blocks/RedStoneOreTile.cpp index d94fed4ed..753543e7e 100644 --- a/Minecraft.World/Blocks/RedStoneOreTile.cpp +++ b/Minecraft.World/Blocks/RedStoneOreTile.cpp @@ -3,126 +3,113 @@ #include "RedStoneOreTile.h" #include "../Headers/net.minecraft.world.item.h" -RedStoneOreTile::RedStoneOreTile(int id, bool lit) : Tile(id, Material::stone) -{ - if (lit) - { - this->setTicking(true); - } - this->lit = lit; +RedStoneOreTile::RedStoneOreTile(int id, bool lit) : Tile(id, Material::stone) { + if (lit) { + this->setTicking(true); + } + this->lit = lit; } -int RedStoneOreTile::getTickDelay() -{ - return 30; +int RedStoneOreTile::getTickDelay() { return 30; } + +void RedStoneOreTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + interact(level, x, y, z); + Tile::attack(level, x, y, z, player); } -void RedStoneOreTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - interact(level, x, y, z); - Tile::attack(level, x, y, z, player); -} - -void RedStoneOreTile::stepOn(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - interact(level, x, y, z); - Tile::stepOn(level, x, y, z, entity); +void RedStoneOreTile::stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity) { + interact(level, x, y, z); + Tile::stepOn(level, x, y, z, entity); } // 4J-PB - Adding a TestUse for tooltip display -bool RedStoneOreTile::TestUse() +bool RedStoneOreTile::TestUse() { return true; } + +bool RedStoneOreTile::use( + Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (soundOnly) return false; + interact(level, x, y, z); + return Tile::use(level, x, y, z, player, clickedFace, clickX, clickY, + clickZ); } -bool RedStoneOreTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if (soundOnly) return false; - interact(level, x, y, z); - return Tile::use(level, x, y, z, player, clickedFace, clickX, clickY, clickZ); +void RedStoneOreTile::interact(Level* level, int x, int y, int z) { + poofParticles(level, x, y, z); + if (level->isClientSide) return; // 4J added + if (id == Tile::redStoneOre_Id) { + level->setTile(x, y, z, Tile::redStoneOre_lit_Id); + } } -void RedStoneOreTile::interact(Level *level, int x, int y, int z) -{ - poofParticles(level, x, y, z); - if (level->isClientSide) return; // 4J added - if (id == Tile::redStoneOre_Id) - { - level->setTile(x, y, z, Tile::redStoneOre_lit_Id); - } +void RedStoneOreTile::tick(Level* level, int x, int y, int z, Random* random) { + if (id == Tile::redStoneOre_lit_Id) { + level->setTile(x, y, z, Tile::redStoneOre_Id); + } } -void RedStoneOreTile::tick(Level *level, int x, int y, int z, Random* random) -{ - if (id == Tile::redStoneOre_lit_Id) - { - level->setTile(x, y, z, Tile::redStoneOre_Id); - } +int RedStoneOreTile::getResource(int data, Random* random, + int playerBonusLevel) { + return Item::redStone->id; } -int RedStoneOreTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::redStone->id; +int RedStoneOreTile::getResourceCountForLootBonus(int bonusLevel, + Random* random) { + return getResourceCount(random) + random->nextInt(bonusLevel + 1); } -int RedStoneOreTile::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - return getResourceCount(random) + random->nextInt(bonusLevel + 1); +int RedStoneOreTile::getResourceCount(Random* random) { + return 4 + random->nextInt(2); } -int RedStoneOreTile::getResourceCount(Random *random) -{ - return 4 + random->nextInt(2); +void RedStoneOreTile::spawnResources(Level* level, int x, int y, int z, + int data, float odds, + int playerBonusLevel) { + Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); + + // also spawn experience if the block is broken + if (getResource(data, level->random, playerBonusLevel) != id) { + int magicCount = 1 + level->random->nextInt(5); + popExperience(level, x, y, z, magicCount); + } } -void RedStoneOreTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - Tile::spawnResources(level, x, y, z, data, odds, playerBonusLevel); - - // also spawn experience if the block is broken - if (getResource(data, level->random, playerBonusLevel) != id) - { - int magicCount = 1 + level->random->nextInt(5); - popExperience(level, x, y, z, magicCount); - } +void RedStoneOreTile::animateTick(Level* level, int x, int y, int z, + Random* random) { + if (lit) { + poofParticles(level, x, y, z); + } } -void RedStoneOreTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - if (lit) - { - poofParticles(level, x, y, z); - } +void RedStoneOreTile::poofParticles(Level* level, int x, int y, int z) { + Random* random = level->random; + double r = 1 / 16.0f; + for (int i = 0; i < 6; i++) { + double xx = x + random->nextFloat(); + double yy = y + random->nextFloat(); + double zz = z + random->nextFloat(); + if (i == 0 && !level->isSolidRenderTile(x, y + 1, z)) yy = y + 1 + r; + if (i == 1 && !level->isSolidRenderTile(x, y - 1, z)) yy = y + 0 - r; + if (i == 2 && !level->isSolidRenderTile(x, y, z + 1)) zz = z + 1 + r; + if (i == 3 && !level->isSolidRenderTile(x, y, z - 1)) zz = z + 0 - r; + if (i == 4 && !level->isSolidRenderTile(x + 1, y, z)) xx = x + 1 + r; + if (i == 5 && !level->isSolidRenderTile(x - 1, y, z)) xx = x + 0 - r; + if (xx < x || xx > x + 1 || yy < 0 || yy > y + 1 || zz < z || + zz > z + 1) { + level->addParticle(eParticleType_reddust, xx, yy, zz, 0, 0, 0); + } + } } -void RedStoneOreTile::poofParticles(Level *level, int x, int y, int z) -{ - Random *random = level->random; - double r = 1 / 16.0f; - for (int i = 0; i < 6; i++) - { - double xx = x + random->nextFloat(); - double yy = y + random->nextFloat(); - double zz = z + random->nextFloat(); - if (i == 0 && !level->isSolidRenderTile(x, y + 1, z)) yy = y + 1 + r; - if (i == 1 && !level->isSolidRenderTile(x, y - 1, z)) yy = y + 0 - r; - if (i == 2 && !level->isSolidRenderTile(x, y, z + 1)) zz = z + 1 + r; - if (i == 3 && !level->isSolidRenderTile(x, y, z - 1)) zz = z + 0 - r; - if (i == 4 && !level->isSolidRenderTile(x + 1, y, z)) xx = x + 1 + r; - if (i == 5 && !level->isSolidRenderTile(x - 1, y, z)) xx = x + 0 - r; - if (xx < x || xx > x + 1 || yy < 0 || yy > y + 1 || zz < z || zz > z + 1) - { - level->addParticle(eParticleType_reddust, xx, yy, zz, 0, 0, 0); - } - } -} - -bool RedStoneOreTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool RedStoneOreTile::shouldTileTick(Level* level, int x, int y, int z) { return id == Tile::redStoneOre_lit_Id; } -std::shared_ptr RedStoneOreTile::getSilkTouchItemInstance(int data) -{ - return std::shared_ptr(new ItemInstance(Tile::redStoneOre)); +std::shared_ptr RedStoneOreTile::getSilkTouchItemInstance( + int data) { + return std::shared_ptr(new ItemInstance(Tile::redStoneOre)); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/RedStoneOreTile.h b/Minecraft.World/Blocks/RedStoneOreTile.h index 22639a10f..53107f120 100644 --- a/Minecraft.World/Blocks/RedStoneOreTile.h +++ b/Minecraft.World/Blocks/RedStoneOreTile.h @@ -4,31 +4,41 @@ class Player; class Random; -class RedStoneOreTile : public Tile -{ +class RedStoneOreTile : public Tile { private: - bool lit; + bool lit; + public: - RedStoneOreTile(int id, bool lit); + RedStoneOreTile(int id, bool lit); virtual int getTickDelay(); - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual void stepOn(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual bool TestUse(); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual void stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual bool TestUse(); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param private: - virtual void interact(Level *level, int x, int y, int z); + virtual void interact(Level* level, int x, int y, int z); + public: - virtual void tick(Level *level, int x, int y, int z, Random* random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - virtual int getResourceCount(Random *random); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + virtual int getResourceCount(Random* random); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); + private: - void poofParticles(Level *level, int x, int y, int z); + void poofParticles(Level* level, int x, int y, int z); + protected: - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual std::shared_ptr getSilkTouchItemInstance(int data); }; diff --git a/Minecraft.World/Blocks/ReedTile.cpp b/Minecraft.World/Blocks/ReedTile.cpp index 287470757..a2ff4b4fd 100644 --- a/Minecraft.World/Blocks/ReedTile.cpp +++ b/Minecraft.World/Blocks/ReedTile.cpp @@ -6,112 +6,82 @@ #include "../Headers/net.minecraft.world.phys.h" #include "ReedTile.h" -ReedTile::ReedTile(int id) : Tile( id, Material::plant, false) -{ - this->updateDefaultShape(); - this->setTicking(true); +ReedTile::ReedTile(int id) : Tile(id, Material::plant, false) { + this->updateDefaultShape(); + this->setTicking(true); } // 4J Added override -void ReedTile::updateDefaultShape() -{ - float ss = 6 / 16.0f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 1, 0.5f + ss); +void ReedTile::updateDefaultShape() { + float ss = 6 / 16.0f; + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 1, 0.5f + ss); } -void ReedTile::tick(Level *level, int x, int y, int z, Random* random) -{ - if (level->isEmptyTile(x, y + 1, z)) - { - int height = 1; - while (level->getTile(x, y - height, z) == id) - { - height++; - } - if (height < 3) - { - int age = level->getData(x, y, z); - if (age == 15) - { - level->setTile(x, y + 1, z, id); - level->setData(x, y, z, 0); - } - else - { - level->setData(x, y, z, age + 1); - } - } - } +void ReedTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isEmptyTile(x, y + 1, z)) { + int height = 1; + while (level->getTile(x, y - height, z) == id) { + height++; + } + if (height < 3) { + int age = level->getData(x, y, z); + if (age == 15) { + level->setTile(x, y + 1, z, id); + level->setData(x, y, z, 0); + } else { + level->setData(x, y, z, age + 1); + } + } + } } -bool ReedTile::mayPlace(Level *level, int x, int y, int z) -{ - int below = level->getTile(x, y - 1, z); - if (below == id) return true; - if (below != Tile::grass_Id && below != Tile::dirt_Id && below != Tile::sand_Id) return false; - if (level->getMaterial(x - 1, y - 1, z) == Material::water) return true; - if (level->getMaterial(x + 1, y - 1, z) == Material::water) return true; - if (level->getMaterial(x, y - 1, z - 1) == Material::water) return true; - if (level->getMaterial(x, y - 1, z + 1) == Material::water) return true; - //printf("no water\n"); - return false; +bool ReedTile::mayPlace(Level* level, int x, int y, int z) { + int below = level->getTile(x, y - 1, z); + if (below == id) return true; + if (below != Tile::grass_Id && below != Tile::dirt_Id && + below != Tile::sand_Id) + return false; + if (level->getMaterial(x - 1, y - 1, z) == Material::water) return true; + if (level->getMaterial(x + 1, y - 1, z) == Material::water) return true; + if (level->getMaterial(x, y - 1, z - 1) == Material::water) return true; + if (level->getMaterial(x, y - 1, z + 1) == Material::water) return true; + // printf("no water\n"); + return false; } -void ReedTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - checkAlive(level, x, y, z); +void ReedTile::neighborChanged(Level* level, int x, int y, int z, int type) { + checkAlive(level, x, y, z); } -const void ReedTile::checkAlive(Level *level, int x, int y, int z) -{ - if (!canSurvive(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } +const void ReedTile::checkAlive(Level* level, int x, int y, int z) { + if (!canSurvive(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } } -bool ReedTile::canSurvive(Level *level, int x, int y, int z) -{ - return mayPlace(level, x, y, z); +bool ReedTile::canSurvive(Level* level, int x, int y, int z) { + return mayPlace(level, x, y, z); } -AABB *ReedTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* ReedTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +int ReedTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::reeds->id; } -int ReedTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::reeds->id; +bool ReedTile::blocksLight() { return false; } + +bool ReedTile::isSolidRender(bool isServerLevel) { return false; } + +bool ReedTile::isCubeShaped() { return false; } + +int ReedTile::getRenderShape() { return Tile::SHAPE_CROSS_TEXTURE; } + +int ReedTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::reeds_Id; } -bool ReedTile::blocksLight() -{ - return false; -} - -bool ReedTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -bool ReedTile::isCubeShaped() -{ - return false; -} - -int ReedTile::getRenderShape() -{ - return Tile::SHAPE_CROSS_TEXTURE; -} - -int ReedTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::reeds_Id; -} - -bool ReedTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool ReedTile::shouldTileTick(Level* level, int x, int y, int z) { return level->isEmptyTile(x, y + 1, z); } diff --git a/Minecraft.World/Blocks/ReedTile.h b/Minecraft.World/Blocks/ReedTile.h index cb8b6e5cf..dd3a3bab4 100644 --- a/Minecraft.World/Blocks/ReedTile.h +++ b/Minecraft.World/Blocks/ReedTile.h @@ -1,52 +1,52 @@ #pragma once - #include "Tile.h" #include "../Util/Definitions.h" class Random; -class ReedTile : public Tile -{ - friend class Tile; -protected: - ReedTile(int id); - -public: - virtual void updateDefaultShape(); // 4J Added override - void tick(Level *level, int x, int y, int z, Random* random); - -public: - bool mayPlace(Level *level, int x, int y, int z); - -public: - void neighborChanged(Level *level, int x, int y, int z, int type); +class ReedTile : public Tile { + friend class Tile; protected: - const void checkAlive(Level *level, int x, int y, int z); + ReedTile(int id); public: - bool canSurvive(Level *level, int x, int y, int z); + virtual void updateDefaultShape(); // 4J Added override + void tick(Level* level, int x, int y, int z, Random* random); public: - AABB *getAABB(Level *level, int x, int y, int z); + bool mayPlace(Level* level, int x, int y, int z); public: - int getResource(int data, Random *random, int playerBonusLevel); + void neighborChanged(Level* level, int x, int y, int z, int type); + +protected: + const void checkAlive(Level* level, int x, int y, int z); public: - bool blocksLight(); + bool canSurvive(Level* level, int x, int y, int z); public: - bool isSolidRender(bool isServerLevel = false); + AABB* getAABB(Level* level, int x, int y, int z); public: - bool isCubeShaped(); + int getResource(int data, Random* random, int playerBonusLevel); public: - int getRenderShape(); - virtual int cloneTileId(Level *level, int x, int y, int z); + bool blocksLight(); - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); +public: + bool isSolidRender(bool isServerLevel = false); + +public: + bool isCubeShaped(); + +public: + int getRenderShape(); + virtual int cloneTileId(Level* level, int x, int y, int z); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/SandStoneTile.cpp b/Minecraft.World/Blocks/SandStoneTile.cpp index 5b11d5467..c9a5f8b7d 100644 --- a/Minecraft.World/Blocks/SandStoneTile.cpp +++ b/Minecraft.World/Blocks/SandStoneTile.cpp @@ -6,47 +6,40 @@ const std::wstring SandStoneTile::TEXTURE_TOP = L"sandstone_top"; const std::wstring SandStoneTile::TEXTURE_BOTTOM = L"sandstone_bottom"; -const std::wstring SandStoneTile::TEXTURE_NAMES[] = {L"sandstone_side", L"sandstone_carved", L"sandstone_smooth"}; +const std::wstring SandStoneTile::TEXTURE_NAMES[] = { + L"sandstone_side", L"sandstone_carved", L"sandstone_smooth"}; int SandStoneTile::SANDSTONE_NAMES[SANDSTONE_BLOCK_NAMES] = { - IDS_TILE_SANDSTONE, IDS_TILE_SANDSTONE_CHISELED, IDS_TILE_SANDSTONE_SMOOTH -}; + IDS_TILE_SANDSTONE, IDS_TILE_SANDSTONE_CHISELED, IDS_TILE_SANDSTONE_SMOOTH}; -SandStoneTile::SandStoneTile(int id) : Tile(id, Material::stone) -{ - icons = NULL; - iconTop = NULL; - iconBottom = NULL; +SandStoneTile::SandStoneTile(int id) : Tile(id, Material::stone) { + icons = NULL; + iconTop = NULL; + iconBottom = NULL; } -Icon *SandStoneTile::getTexture(int face, int data) -{ - if (face == Facing::UP || (face == Facing::DOWN && (data == TYPE_HEIROGLYPHS || data == TYPE_SMOOTHSIDE))) - { - return iconTop; - } - if (face == Facing::DOWN) - { - return iconBottom; - } - if (data < 0 || data >= SANDSTONE_TILE_TEXTURE_COUNT) data = 0; - return icons[data]; +Icon* SandStoneTile::getTexture(int face, int data) { + if (face == Facing::UP || + (face == Facing::DOWN && + (data == TYPE_HEIROGLYPHS || data == TYPE_SMOOTHSIDE))) { + return iconTop; + } + if (face == Facing::DOWN) { + return iconBottom; + } + if (data < 0 || data >= SANDSTONE_TILE_TEXTURE_COUNT) data = 0; + return icons[data]; } -int SandStoneTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} +int SandStoneTile::getSpawnResourcesAuxValue(int data) { return data; } -void SandStoneTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[SANDSTONE_TILE_TEXTURE_COUNT]; +void SandStoneTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[SANDSTONE_TILE_TEXTURE_COUNT]; - for (int i = 0; i < SANDSTONE_TILE_TEXTURE_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < SANDSTONE_TILE_TEXTURE_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } - iconTop = iconRegister->registerIcon(TEXTURE_TOP); - iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); + iconTop = iconRegister->registerIcon(TEXTURE_TOP); + iconBottom = iconRegister->registerIcon(TEXTURE_BOTTOM); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/SandStoneTile.h b/Minecraft.World/Blocks/SandStoneTile.h index 21c40cafd..6fff21264 100644 --- a/Minecraft.World/Blocks/SandStoneTile.h +++ b/Minecraft.World/Blocks/SandStoneTile.h @@ -1,38 +1,39 @@ #pragma once - #include "Tile.h" class ChunkRebuildData; -class SandStoneTile : public Tile -{ - friend class ChunkRebuildData; +class SandStoneTile : public Tile { + friend class ChunkRebuildData; + public: - static const int TYPE_DEFAULT = 0; - static const int TYPE_HEIROGLYPHS = 1; - static const int TYPE_SMOOTHSIDE = 2; + static const int TYPE_DEFAULT = 0; + static const int TYPE_HEIROGLYPHS = 1; + static const int TYPE_SMOOTHSIDE = 2; - // Add this in when we need it - //static final String[] SANDSTONE_NAMES = {"default", "chiseled", "smooth"}; + // Add this in when we need it + // static final String[] SANDSTONE_NAMES = {"default", "chiseled", + // "smooth"}; - static const int SANDSTONE_BLOCK_NAMES = 3; - static int SANDSTONE_NAMES[SANDSTONE_BLOCK_NAMES]; + static const int SANDSTONE_BLOCK_NAMES = 3; + static int SANDSTONE_NAMES[SANDSTONE_BLOCK_NAMES]; private: - static const std::wstring TEXTURE_TOP; - static const std::wstring TEXTURE_BOTTOM; - static const std::wstring TEXTURE_NAMES[]; - static const int SANDSTONE_TILE_TEXTURE_COUNT = 3; + static const std::wstring TEXTURE_TOP; + static const std::wstring TEXTURE_BOTTOM; + static const std::wstring TEXTURE_NAMES[]; + static const int SANDSTONE_TILE_TEXTURE_COUNT = 3; - Icon **icons; - Icon *iconTop; - Icon *iconBottom; -public: - SandStoneTile(int id); + Icon** icons; + Icon* iconTop; + Icon* iconBottom; public: - Icon *getTexture(int face, int data); - virtual int getSpawnResourcesAuxValue(int data); - void registerIcons(IconRegister *iconRegister); + SandStoneTile(int id); + +public: + Icon* getTexture(int face, int data); + virtual int getSpawnResourcesAuxValue(int data); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/SaplingPlantTile.cpp b/Minecraft.World/Blocks/SaplingPlantTile.cpp index 2d670714e..c2552b95d 100644 --- a/Minecraft.World/Blocks/SaplingPlantTile.cpp +++ b/Minecraft.World/Blocks/SaplingPlantTile.cpp @@ -6,161 +6,130 @@ #include "SaplingPlantTile.h" -const unsigned int Sapling::SAPLING_NAMES[SAPLING_NAMES_SIZE] = { IDS_TILE_SAPLING_OAK, - IDS_TILE_SAPLING_SPRUCE, - IDS_TILE_SAPLING_BIRCH, - IDS_TILE_SAPLING_JUNGLE - }; +const unsigned int Sapling::SAPLING_NAMES[SAPLING_NAMES_SIZE] = { + IDS_TILE_SAPLING_OAK, IDS_TILE_SAPLING_SPRUCE, IDS_TILE_SAPLING_BIRCH, + IDS_TILE_SAPLING_JUNGLE}; -const std::wstring Sapling::TEXTURE_NAMES[] = {L"sapling", L"sapling_spruce", L"sapling_birch", L"sapling_jungle"}; +const std::wstring Sapling::TEXTURE_NAMES[] = { + L"sapling", L"sapling_spruce", L"sapling_birch", L"sapling_jungle"}; -Sapling::Sapling(int id) : Bush( id ) -{ - this->updateDefaultShape(); - icons = NULL; +Sapling::Sapling(int id) : Bush(id) { + this->updateDefaultShape(); + icons = NULL; } // 4J Added override -void Sapling::updateDefaultShape() -{ - float ss = 0.4f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, ss * 2, 0.5f + ss); +void Sapling::updateDefaultShape() { + float ss = 0.4f; + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, ss * 2, 0.5f + ss); } -void Sapling::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isClientSide) return; +void Sapling::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isClientSide) return; - Bush::tick(level, x, y, z, random); + Bush::tick(level, x, y, z, random); - if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) - { - if (random->nextInt(7) == 0) - { - int data = level->getData(x, y, z); - if ((data & AGE_BIT) == 0) - { - level->setData(x, y, z, data | AGE_BIT); - } - else - { - growTree(level, x, y, z, random); - } - } - } + if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) { + if (random->nextInt(7) == 0) { + int data = level->getData(x, y, z); + if ((data & AGE_BIT) == 0) { + level->setData(x, y, z, data | AGE_BIT); + } else { + growTree(level, x, y, z, random); + } + } + } } -Icon *Sapling::getTexture(int face, int data) -{ - data = data & TYPE_MASK; - return icons[data]; +Icon* Sapling::getTexture(int face, int data) { + data = data & TYPE_MASK; + return icons[data]; } -void Sapling::growTree(Level *level, int x, int y, int z, Random *random) -{ - int data = level->getData(x, y, z) & TYPE_MASK; +void Sapling::growTree(Level* level, int x, int y, int z, Random* random) { + int data = level->getData(x, y, z) & TYPE_MASK; - Feature *f = NULL; + Feature* f = NULL; - int ox = 0, oz = 0; - bool multiblock = false; + int ox = 0, oz = 0; + bool multiblock = false; - if (data == TYPE_EVERGREEN) - { - f = new SpruceFeature(true); - } - else if (data == TYPE_BIRCH) - { - f = new BirchFeature(true); - } - else if (data == TYPE_JUNGLE) - { - // check for mega tree - for (ox = 0; ox >= -1; ox--) - { - for (oz = 0; oz >= -1; oz--) - { - if (isSapling(level, x + ox, y, z + oz, TYPE_JUNGLE) && - isSapling(level, x + ox + 1, y, z + oz, TYPE_JUNGLE) && - isSapling(level, x + ox, y, z + oz + 1, TYPE_JUNGLE) && - isSapling(level, x + ox + 1, y, z + oz + 1, TYPE_JUNGLE)) - { - f = new MegaTreeFeature(true, 10 + random->nextInt(20), TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF); - multiblock = true; - break; - } - } - if (f != NULL) - { - break; - } - } - if (f == NULL) - { - ox = oz = 0; - f = new TreeFeature(true, 4 + random->nextInt(7), TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF, false); - } - } - else - { - f = new TreeFeature(true); - if (random->nextInt(10) == 0) - { - delete f; - f = new BasicTree(true); - } - } - if (multiblock) - { - level->setTileNoUpdate(x + ox, y, z + oz, 0); - level->setTileNoUpdate(x + ox + 1, y, z + oz, 0); - level->setTileNoUpdate(x + ox, y, z + oz + 1, 0); - level->setTileNoUpdate(x + ox + 1, y, z + oz + 1, 0); - } - else - { - level->setTileNoUpdate(x, y, z, 0); - } - if (!f->place(level, random, x + ox, y, z + oz)) - { - if (multiblock) - { - level->setTileAndDataNoUpdate(x + ox, y, z + oz, this->id, data); - level->setTileAndDataNoUpdate(x + ox + 1, y, z + oz, this->id, data); - level->setTileAndDataNoUpdate(x + ox, y, z + oz + 1, this->id, data); - level->setTileAndDataNoUpdate(x + ox + 1, y, z + oz + 1, this->id, data); - } - else - { - level->setTileAndDataNoUpdate(x, y, z, this->id, data); - } - } - if( f != NULL ) - delete f; + if (data == TYPE_EVERGREEN) { + f = new SpruceFeature(true); + } else if (data == TYPE_BIRCH) { + f = new BirchFeature(true); + } else if (data == TYPE_JUNGLE) { + // check for mega tree + for (ox = 0; ox >= -1; ox--) { + for (oz = 0; oz >= -1; oz--) { + if (isSapling(level, x + ox, y, z + oz, TYPE_JUNGLE) && + isSapling(level, x + ox + 1, y, z + oz, TYPE_JUNGLE) && + isSapling(level, x + ox, y, z + oz + 1, TYPE_JUNGLE) && + isSapling(level, x + ox + 1, y, z + oz + 1, TYPE_JUNGLE)) { + f = new MegaTreeFeature(true, 10 + random->nextInt(20), + TreeTile::JUNGLE_TRUNK, + LeafTile::JUNGLE_LEAF); + multiblock = true; + break; + } + } + if (f != NULL) { + break; + } + } + if (f == NULL) { + ox = oz = 0; + f = new TreeFeature(true, 4 + random->nextInt(7), + TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF, + false); + } + } else { + f = new TreeFeature(true); + if (random->nextInt(10) == 0) { + delete f; + f = new BasicTree(true); + } + } + if (multiblock) { + level->setTileNoUpdate(x + ox, y, z + oz, 0); + level->setTileNoUpdate(x + ox + 1, y, z + oz, 0); + level->setTileNoUpdate(x + ox, y, z + oz + 1, 0); + level->setTileNoUpdate(x + ox + 1, y, z + oz + 1, 0); + } else { + level->setTileNoUpdate(x, y, z, 0); + } + if (!f->place(level, random, x + ox, y, z + oz)) { + if (multiblock) { + level->setTileAndDataNoUpdate(x + ox, y, z + oz, this->id, data); + level->setTileAndDataNoUpdate(x + ox + 1, y, z + oz, this->id, + data); + level->setTileAndDataNoUpdate(x + ox, y, z + oz + 1, this->id, + data); + level->setTileAndDataNoUpdate(x + ox + 1, y, z + oz + 1, this->id, + data); + } else { + level->setTileAndDataNoUpdate(x, y, z, this->id, data); + } + } + if (f != NULL) delete f; } -unsigned int Sapling::getDescriptionId(int iData /*= -1*/) -{ - if(iData < 0 ) iData = 0; - return Sapling::SAPLING_NAMES[iData]; +unsigned int Sapling::getDescriptionId(int iData /*= -1*/) { + if (iData < 0) iData = 0; + return Sapling::SAPLING_NAMES[iData]; } -int Sapling::getSpawnResourcesAuxValue(int data) -{ - return data & TYPE_MASK; +int Sapling::getSpawnResourcesAuxValue(int data) { return data & TYPE_MASK; } + +bool Sapling::isSapling(Level* level, int x, int y, int z, int type) { + return (level->getTile(x, y, z) == id) && + ((level->getData(x, y, z) & TYPE_MASK) == type); } -bool Sapling::isSapling(Level *level, int x, int y, int z, int type) -{ - return (level->getTile(x, y, z) == id) && ((level->getData(x, y, z) & TYPE_MASK) == type); -} +void Sapling::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[SAPLING_NAMES_SIZE]; -void Sapling::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[SAPLING_NAMES_SIZE]; - - for (int i = 0; i < SAPLING_NAMES_SIZE; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < SAPLING_NAMES_SIZE; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } } diff --git a/Minecraft.World/Blocks/SaplingPlantTile.h b/Minecraft.World/Blocks/SaplingPlantTile.h index 3996b6be9..92421a012 100644 --- a/Minecraft.World/Blocks/SaplingPlantTile.h +++ b/Minecraft.World/Blocks/SaplingPlantTile.h @@ -6,45 +6,45 @@ class Random; class ChunkRebuildData; -class Sapling : public Bush -{ - friend class Tile; - friend class ChunkRebuildData; +class Sapling : public Bush { + friend class Tile; + friend class ChunkRebuildData; + public: - static const int TYPE_DEFAULT = LeafTile::NORMAL_LEAF; - static const int TYPE_EVERGREEN = LeafTile::EVERGREEN_LEAF; - static const int TYPE_BIRCH = LeafTile::BIRCH_LEAF; - static const int TYPE_JUNGLE = LeafTile::JUNGLE_LEAF; + static const int TYPE_DEFAULT = LeafTile::NORMAL_LEAF; + static const int TYPE_EVERGREEN = LeafTile::EVERGREEN_LEAF; + static const int TYPE_BIRCH = LeafTile::BIRCH_LEAF; + static const int TYPE_JUNGLE = LeafTile::JUNGLE_LEAF; - static const int SAPLING_NAMES_SIZE = 4; + static const int SAPLING_NAMES_SIZE = 4; - static const unsigned int SAPLING_NAMES[SAPLING_NAMES_SIZE]; + static const unsigned int SAPLING_NAMES[SAPLING_NAMES_SIZE]; private: - static const std::wstring TEXTURE_NAMES[]; + static const std::wstring TEXTURE_NAMES[]; - Icon **icons; + Icon** icons; - static const int TYPE_MASK = 3; - static const int AGE_BIT = 8; + static const int TYPE_MASK = 3; + static const int AGE_BIT = 8; protected: - Sapling(int id); + Sapling(int id); public: - virtual void updateDefaultShape(); // 4J Added override - void tick(Level *level, int x, int y, int z, Random *random); + virtual void updateDefaultShape(); // 4J Added override + void tick(Level* level, int x, int y, int z, Random* random); - Icon *getTexture(int face, int data); + Icon* getTexture(int face, int data); - void growTree(Level *level, int x, int y, int z, Random *random); + void growTree(Level* level, int x, int y, int z, Random* random); - virtual unsigned int getDescriptionId(int iData = -1); - bool isSapling(Level *level, int x, int y, int z, int type); + virtual unsigned int getDescriptionId(int iData = -1); + bool isSapling(Level* level, int x, int y, int z, int type); protected: - int getSpawnResourcesAuxValue(int data); + int getSpawnResourcesAuxValue(int data); public: - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/SignTile.cpp b/Minecraft.World/Blocks/SignTile.cpp index 8046b7df6..914edd313 100644 --- a/Minecraft.World/Blocks/SignTile.cpp +++ b/Minecraft.World/Blocks/SignTile.cpp @@ -5,125 +5,108 @@ #include "TileEntities/SignTileEntity.h" #include "SignTile.h" -SignTile::SignTile(int id, eINSTANCEOF clas, bool onGround) : EntityTile(id, Material::wood, false) -{ - this->onGround = onGround; - this->clas = clas; - updateDefaultShape(); +SignTile::SignTile(int id, eINSTANCEOF clas, bool onGround) + : EntityTile(id, Material::wood, false) { + this->onGround = onGround; + this->clas = clas; + updateDefaultShape(); } -Icon *SignTile::getTexture(int face, int data) -{ - return Tile::wood->getTexture(face); +Icon* SignTile::getTexture(int face, int data) { + return Tile::wood->getTexture(face); } -void SignTile::updateDefaultShape() -{ - float r = 4 / 16.0f; - float h = 16 / 16.0f; - this->setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); +void SignTile::updateDefaultShape() { + float r = 4 / 16.0f; + float h = 16 / 16.0f; + this->setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); } -AABB *SignTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* SignTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +AABB* SignTile::getTileAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return EntityTile::getTileAABB(level, x, y, z); } -AABB *SignTile::getTileAABB(Level *level, int x, int y, int z) +void SignTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - updateShape(level, x, y, z); - return EntityTile::getTileAABB(level, x, y, z); + if (onGround) return; + + int face = level->getData(x, y, z); + + float h0 = (4 + 0.5f) / 16.0f; + float h1 = (12 + 0.5f) / 16.0f; + float w0 = 0 / 16.0f; + float w1 = 16 / 16.0f; + + float d0 = 2 / 16.0f; + + setShape(0, 0, 0, 1, 1, 1); + if (face == 2) setShape(w0, h0, 1 - d0, w1, h1, 1); + if (face == 3) setShape(w0, h0, 0, w1, h1, d0); + if (face == 4) setShape(1 - d0, h0, w0, 1, h1, w1); + if (face == 5) setShape(0, h0, w0, d0, h1, w1); } -void SignTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - if (onGround) return; +int SignTile::getRenderShape() { return Tile::SHAPE_INVISIBLE; } - int face = level->getData(x, y, z); +bool SignTile::isCubeShaped() { return false; } - float h0 = (4 + 0.5f) / 16.0f; - float h1 = (12 + 0.5f) / 16.0f; - float w0 = 0 / 16.0f; - float w1 = 16 / 16.0f; - - float d0 = 2 / 16.0f; - - setShape(0, 0, 0, 1, 1, 1); - if (face == 2) setShape(w0, h0, 1 - d0, w1, h1, 1); - if (face == 3) setShape(w0, h0, 0, w1, h1, d0); - if (face == 4) setShape(1 - d0, h0, w0, 1, h1, w1); - if (face == 5) setShape(0, h0, w0, d0, h1, w1); +bool SignTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return true; } -int SignTile::getRenderShape() -{ - return Tile::SHAPE_INVISIBLE; +bool SignTile::isSolidRender(bool isServerLevel) { return false; } + +std::shared_ptr SignTile::newTileEntity(Level* level) { + // try { + // 4J Stu - For some reason the newInstance wasn't working right, but doing + // it like the other TileEntities is fine + return std::shared_ptr(new SignTileEntity()); + // return std::dynamic_pointer_cast( clas->newInstance() ); + // } catch (Exception e) { + // TODO 4J Stu - Exception handling + // throw new RuntimeException(e); + // } } -bool SignTile::isCubeShaped() -{ - return false; +int SignTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::sign->id; } -bool SignTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return true; +void SignTile::neighborChanged(Level* level, int x, int y, int z, int type) { + bool remove = false; + + if (onGround) { + if (!level->getMaterial(x, y - 1, z)->isSolid()) remove = true; + } else { + int face = level->getData(x, y, z); + remove = true; + if (face == 2 && level->getMaterial(x, y, z + 1)->isSolid()) + remove = false; + if (face == 3 && level->getMaterial(x, y, z - 1)->isSolid()) + remove = false; + if (face == 4 && level->getMaterial(x + 1, y, z)->isSolid()) + remove = false; + if (face == 5 && level->getMaterial(x - 1, y, z)->isSolid()) + remove = false; + } + if (remove) { + spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } + + EntityTile::neighborChanged(level, x, y, z, type); } -bool SignTile::isSolidRender(bool isServerLevel) -{ - return false; +int SignTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::sign_Id; } -std::shared_ptr SignTile::newTileEntity(Level *level) -{ - //try { - // 4J Stu - For some reason the newInstance wasn't working right, but doing it like the other TileEntities is fine - return std::shared_ptr( new SignTileEntity() ); - //return std::dynamic_pointer_cast( clas->newInstance() ); - //} catch (Exception e) { - // TODO 4J Stu - Exception handling - // throw new RuntimeException(e); - //} -} - -int SignTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::sign->id; -} - -void SignTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - bool remove = false; - - if (onGround) - { - if (!level->getMaterial(x, y - 1, z)->isSolid()) remove = true; - } - else - { - int face = level->getData(x, y, z); - remove = true; - if (face == 2 && level->getMaterial(x, y, z + 1)->isSolid()) remove = false; - if (face == 3 && level->getMaterial(x, y, z - 1)->isSolid()) remove = false; - if (face == 4 && level->getMaterial(x + 1, y, z)->isSolid()) remove = false; - if (face == 5 && level->getMaterial(x - 1, y, z)->isSolid()) remove = false; - } - if (remove) - { - spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } - - EntityTile::neighborChanged(level, x, y, z, type); -} - -int SignTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::sign_Id; -} - -void SignTile::registerIcons(IconRegister *iconRegister) -{ - // None +void SignTile::registerIcons(IconRegister* iconRegister) { + // None } diff --git a/Minecraft.World/Blocks/SignTile.h b/Minecraft.World/Blocks/SignTile.h index 5b432f8aa..162a7317b 100644 --- a/Minecraft.World/Blocks/SignTile.h +++ b/Minecraft.World/Blocks/SignTile.h @@ -6,33 +6,37 @@ #include "../Platform/stdafx.h" #include "Material.h" -class SignTile : public EntityTile -{ - friend class Tile; +class SignTile : public EntityTile { + friend class Tile; + private: - eINSTANCEOF clas; - bool onGround; + eINSTANCEOF clas; + bool onGround; protected: - SignTile(int id, eINSTANCEOF clas, bool onGround); + SignTile(int id, eINSTANCEOF clas, bool onGround); public: - Icon *getTexture(int face, int data); + Icon* getTexture(int face, int data); virtual void updateDefaultShape(); - AABB *getAABB(Level *level, int x, int y, int z); - AABB *getTileAABB(Level *level, int x, int y, int z); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - int getRenderShape(); - bool isCubeShaped(); - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); - bool isSolidRender(bool isServerLevel = false); + AABB* getAABB(Level* level, int x, int y, int z); + AABB* getTileAABB(Level* level, int x, int y, int z); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); // 4J added forceData, + // forceEntity param + int getRenderShape(); + bool isCubeShaped(); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); + bool isSolidRender(bool isServerLevel = false); protected: - std::shared_ptr newTileEntity(Level *level); + std::shared_ptr newTileEntity(Level* level); public: - int getResource(int data, Random *random, int playerBonusLevel); - void neighborChanged(Level *level, int x, int y, int z, int type); - int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); + int getResource(int data, Random* random, int playerBonusLevel); + void neighborChanged(Level* level, int x, int y, int z, int type); + int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/SkullTile.cpp b/Minecraft.World/Blocks/SkullTile.cpp index bc17db5e6..d8ad46c56 100644 --- a/Minecraft.World/Blocks/SkullTile.cpp +++ b/Minecraft.World/Blocks/SkullTile.cpp @@ -5,100 +5,88 @@ #include "../Headers/net.minecraft.h" #include "SkullTile.h" -SkullTile::SkullTile(int id) : EntityTile(id, Material::decoration, false) -{ - setShape(4.0f / 16.0f, 0, 4.0f / 16.0f, 12.0f / 16.0f, .5f, 12.0f / 16.0f); +SkullTile::SkullTile(int id) : EntityTile(id, Material::decoration, false) { + setShape(4.0f / 16.0f, 0, 4.0f / 16.0f, 12.0f / 16.0f, .5f, 12.0f / 16.0f); } -int SkullTile::getRenderShape() -{ - return SHAPE_INVISIBLE; +int SkullTile::getRenderShape() { return SHAPE_INVISIBLE; } + +bool SkullTile::isSolidRender(bool isServerLevel) { return false; } + +bool SkullTile::isCubeShaped() { return false; } + +void SkullTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + int data = level->getData(x, y, z) & PLACEMENT_MASK; + + switch (data) { + default: + case Facing::UP: + setShape(4.0f / 16.0f, 0, 4.0f / 16.0f, 12.0f / 16.0f, .5f, + 12.0f / 16.0f); + break; + case Facing::NORTH: + setShape(4.0f / 16.0f, 4.0f / 16.0f, .5f, 12.0f / 16.0f, + 12.0f / 16.0f, 1); + break; + case Facing::SOUTH: + setShape(4.0f / 16.0f, 4.0f / 16.0f, 0, 12.0f / 16.0f, + 12.0f / 16.0f, .5f); + break; + case Facing::WEST: + setShape(.5f, 4.0f / 16.0f, 4.0f / 16.0f, 1, 12.0f / 16.0f, + 12.0f / 16.0f); + break; + case Facing::EAST: + setShape(0, 4.0f / 16.0f, 4.0f / 16.0f, .5f, 12.0f / 16.0f, + 12.0f / 16.0f); + break; + } } -bool SkullTile::isSolidRender(bool isServerLevel) -{ - return false; +AABB* SkullTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return EntityTile::getAABB(level, x, y, z); } -bool SkullTile::isCubeShaped() -{ - return false; +void SkullTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = Mth::floor(by->yRot * 4 / (360) + 2.5) & 3; + level->setData(x, y, z, dir); } -void SkullTile::updateShape(LevelSource *level, int x, int y, int z, int forceData , std::shared_ptr forceEntity) -{ - int data = level->getData(x, y, z) & PLACEMENT_MASK; - - switch (data) - { - default: - case Facing::UP: - setShape(4.0f / 16.0f, 0, 4.0f / 16.0f, 12.0f / 16.0f, .5f, 12.0f / 16.0f); - break; - case Facing::NORTH: - setShape(4.0f / 16.0f, 4.0f / 16.0f, .5f, 12.0f / 16.0f, 12.0f / 16.0f, 1); - break; - case Facing::SOUTH: - setShape(4.0f / 16.0f, 4.0f / 16.0f, 0, 12.0f / 16.0f, 12.0f / 16.0f, .5f); - break; - case Facing::WEST: - setShape(.5f, 4.0f / 16.0f, 4.0f / 16.0f, 1, 12.0f / 16.0f, 12.0f / 16.0f); - break; - case Facing::EAST: - setShape(0, 4.0f / 16.0f, 4.0f / 16.0f, .5f, 12.0f / 16.0f, 12.0f / 16.0f); - break; - } +std::shared_ptr SkullTile::newTileEntity(Level* level) { + return std::shared_ptr(new SkullTileEntity()); } -AABB *SkullTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return EntityTile::getAABB(level, x, y, z); +int SkullTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::skull_Id; } -void SkullTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = Mth::floor(by->yRot * 4 / (360) + 2.5) & 3; - level->setData(x, y, z, dir); +int SkullTile::cloneTileData(Level* level, int x, int y, int z) { + std::shared_ptr tileEntity = level->getTileEntity(x, y, z); + std::shared_ptr skull = + std::dynamic_pointer_cast(tileEntity); + if (skull != NULL) { + return skull->getSkullType(); + } + return 0; + // 4J Stu - Not added yet + // return EntityTile::cloneTileData(level, x, y, z); } -std::shared_ptr SkullTile::newTileEntity(Level *level) -{ - return std::shared_ptr(new SkullTileEntity()); +int SkullTile::getSpawnResourcesAuxValue(int data) { return data; } + +void SkullTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + // do nothing, resource is popped by onRemove + // ... because the tile entity is removed prior to spawnResources } -int SkullTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::skull_Id; -} - -int SkullTile::cloneTileData(Level *level, int x, int y, int z) -{ - std::shared_ptr tileEntity = level->getTileEntity(x, y, z); - std::shared_ptr skull = std::dynamic_pointer_cast(tileEntity); - if (skull != NULL) - { - return skull->getSkullType(); - } - return 0; - // 4J Stu - Not added yet - //return EntityTile::cloneTileData(level, x, y, z); -} - -int SkullTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} - -void SkullTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - // do nothing, resource is popped by onRemove - // ... because the tile entity is removed prior to spawnResources -} - -void SkullTile::playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player) -{ - // 4J Stu - Not implemented +void SkullTile::playerWillDestroy(Level* level, int x, int y, int z, int data, + std::shared_ptr player) { + // 4J Stu - Not implemented #if 0 if (player->abilities.instabuild) { @@ -110,34 +98,36 @@ void SkullTile::playerWillDestroy(Level *level, int x, int y, int z, int data, s #endif } -void SkullTile::onRemove(Level *level, int x, int y, int z)//, int id, int data) +void SkullTile::onRemove(Level* level, int x, int y, + int z) //, int id, int data) { - if (level->isClientSide) return; + if (level->isClientSide) return; int data = level->getData(x, y, z); - if ((data & NO_DROP_BIT) == 0) - { - std::shared_ptr item = std::shared_ptr(new ItemInstance(Item::skull_Id, 1, cloneTileData(level, x, y, z))); - std::shared_ptr entity = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); + if ((data & NO_DROP_BIT) == 0) { + std::shared_ptr item = std::shared_ptr( + new ItemInstance(Item::skull_Id, 1, cloneTileData(level, x, y, z))); + std::shared_ptr entity = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); - if (entity->getSkullType() == SkullTileEntity::TYPE_CHAR && !entity->getExtraType().empty()) - { - item->setTag(new CompoundTag()); - item->getTag()->putString(L"SkullOwner", entity->getExtraType()); - } + if (entity->getSkullType() == SkullTileEntity::TYPE_CHAR && + !entity->getExtraType().empty()) { + item->setTag(new CompoundTag()); + item->getTag()->putString(L"SkullOwner", entity->getExtraType()); + } - popResource(level, x, y, z, item); - } - EntityTile::onRemove(level, x, y, z, id, data); + popResource(level, x, y, z, item); + } + EntityTile::onRemove(level, x, y, z, id, data); } -int SkullTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::skull_Id; +int SkullTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::skull_Id; } -void SkullTile::checkMobSpawn(Level *level, int x, int y, int z, std::shared_ptr placedSkull) -{ - // 4J Stu - Don't have Withers yet, so don't need this +void SkullTile::checkMobSpawn(Level* level, int x, int y, int z, + std::shared_ptr placedSkull) { + // 4J Stu - Don't have Withers yet, so don't need this #if 0 if (placedSkull.getSkullType() == SkullTileEntity.TYPE_WITHER && y >= 2 && level.difficulty > Difficulty.PEACEFUL) { @@ -238,33 +228,28 @@ void SkullTile::checkMobSpawn(Level *level, int x, int y, int z, std::shared_ptr #endif } -bool SkullTile::isSkullAt(Level *level, int x, int y, int z, int skullType) -{ - if (level->getTile(x, y, z) != id) - { - return false; - } - std::shared_ptr te = level->getTileEntity(x, y, z); - std::shared_ptr skull = std::dynamic_pointer_cast(te); - if (skull == NULL) - { - return false; - } - return skull->getSkullType() == skullType; +bool SkullTile::isSkullAt(Level* level, int x, int y, int z, int skullType) { + if (level->getTile(x, y, z) != id) { + return false; + } + std::shared_ptr te = level->getTileEntity(x, y, z); + std::shared_ptr skull = + std::dynamic_pointer_cast(te); + if (skull == NULL) { + return false; + } + return skull->getSkullType() == skullType; } -void SkullTile::registerIcons(IconRegister *iconRegister) -{ - // None +void SkullTile::registerIcons(IconRegister* iconRegister) { + // None } -Icon *SkullTile::getTexture(int face, int data) -{ - return Tile::hellSand->getTexture(face); +Icon* SkullTile::getTexture(int face, int data) { + return Tile::hellSand->getTexture(face); } -std::wstring SkullTile::getTileItemIconName() -{ - return L""; - //return SkullItem::ICON_NAMES[0]; +std::wstring SkullTile::getTileItemIconName() { + return L""; + // return SkullItem::ICON_NAMES[0]; } diff --git a/Minecraft.World/Blocks/SkullTile.h b/Minecraft.World/Blocks/SkullTile.h index 3a2ece7b6..0661af011 100644 --- a/Minecraft.World/Blocks/SkullTile.h +++ b/Minecraft.World/Blocks/SkullTile.h @@ -4,41 +4,49 @@ class SkullTileEntity; -class SkullTile : public EntityTile -{ - friend class Tile; -public: - static const int MAX_SKULL_TILES = 40; -public: - static const int PLACEMENT_MASK = 0x7; - static const int NO_DROP_BIT = 0x8; - - SkullTile(int id); +class SkullTile : public EntityTile { + friend class Tile; public: - using EntityTile::onRemove; + static const int MAX_SKULL_TILES = 40; - int getRenderShape(); - bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); - AABB *getAABB(Level *level, int x, int y, int z); - void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - std::shared_ptr newTileEntity(Level *level); - int cloneTileId(Level *level, int x, int y, int z); - int cloneTileData(Level *level, int x, int y, int z); - int getSpawnResourcesAuxValue(int data); - void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); - void playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player); - void onRemove(Level *level, int x, int y, int z); //, int id, int data); - int getResource(int data, Random *random, int playerBonusLevel); - void checkMobSpawn(Level *level, int x, int y, int z, std::shared_ptr placedSkull); +public: + static const int PLACEMENT_MASK = 0x7; + static const int NO_DROP_BIT = 0x8; + + SkullTile(int id); + +public: + using EntityTile::onRemove; + + int getRenderShape(); + bool isSolidRender(bool isServerLevel = false); + bool isCubeShaped(); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + AABB* getAABB(Level* level, int x, int y, int z); + void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + std::shared_ptr newTileEntity(Level* level); + int cloneTileId(Level* level, int x, int y, int z); + int cloneTileData(Level* level, int x, int y, int z); + int getSpawnResourcesAuxValue(int data); + void spawnResources(Level* level, int x, int y, int z, int data, float odds, + int playerBonusLevel); + void playerWillDestroy(Level* level, int x, int y, int z, int data, + std::shared_ptr player); + void onRemove(Level* level, int x, int y, int z); //, int id, int data); + int getResource(int data, Random* random, int playerBonusLevel); + void checkMobSpawn(Level* level, int x, int y, int z, + std::shared_ptr placedSkull); private: - bool isSkullAt(Level *level, int x, int y, int z, int skullType); + bool isSkullAt(Level* level, int x, int y, int z, int skullType); public: - void registerIcons(IconRegister *iconRegister); - Icon *getTexture(int face, int data); - std::wstring getTileItemIconName(); + void registerIcons(IconRegister* iconRegister); + Icon* getTexture(int face, int data); + std::wstring getTileItemIconName(); }; diff --git a/Minecraft.World/Blocks/SmoothStoneBrickTile.cpp b/Minecraft.World/Blocks/SmoothStoneBrickTile.cpp index 86dc50d64..cdd33cd6c 100644 --- a/Minecraft.World/Blocks/SmoothStoneBrickTile.cpp +++ b/Minecraft.World/Blocks/SmoothStoneBrickTile.cpp @@ -2,42 +2,36 @@ #include "SmoothStoneBrickTile.h" #include "../Headers/net.minecraft.world.h" -const std::wstring SmoothStoneBrickTile::TEXTURE_NAMES[] = {L"stonebricksmooth", L"stonebricksmooth_mossy", L"stonebricksmooth_cracked", L"stonebricksmooth_carved"}; +const std::wstring SmoothStoneBrickTile::TEXTURE_NAMES[] = { + L"stonebricksmooth", L"stonebricksmooth_mossy", L"stonebricksmooth_cracked", + L"stonebricksmooth_carved"}; -const unsigned int SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES[SMOOTH_STONE_BRICK_NAMES_LENGTH] = { IDS_TILE_STONE_BRICK_SMOOTH, - IDS_TILE_STONE_BRICK_SMOOTH_MOSSY, - IDS_TILE_STONE_BRICK_SMOOTH_CRACKED, - IDS_TILE_STONE_BRICK_SMOOTH_CHISELED - }; +const unsigned int SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES + [SMOOTH_STONE_BRICK_NAMES_LENGTH] = {IDS_TILE_STONE_BRICK_SMOOTH, + IDS_TILE_STONE_BRICK_SMOOTH_MOSSY, + IDS_TILE_STONE_BRICK_SMOOTH_CRACKED, + IDS_TILE_STONE_BRICK_SMOOTH_CHISELED}; -SmoothStoneBrickTile::SmoothStoneBrickTile(int id) : Tile(id, Material::stone) -{ - icons = NULL; +SmoothStoneBrickTile::SmoothStoneBrickTile(int id) : Tile(id, Material::stone) { + icons = NULL; } -Icon *SmoothStoneBrickTile::getTexture(int face, int data) -{ - if (data < 0 || data >= SMOOTH_STONE_BRICK_NAMES_LENGTH) data = 0; - return icons[data]; +Icon* SmoothStoneBrickTile::getTexture(int face, int data) { + if (data < 0 || data >= SMOOTH_STONE_BRICK_NAMES_LENGTH) data = 0; + return icons[data]; } -int SmoothStoneBrickTile::getSpawnResourcesAuxValue(int data) -{ - return data; +int SmoothStoneBrickTile::getSpawnResourcesAuxValue(int data) { return data; } + +unsigned int SmoothStoneBrickTile::getDescriptionId(int iData /*= -1*/) { + if (iData < 0) iData = 0; + return SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES[iData]; } -unsigned int SmoothStoneBrickTile::getDescriptionId(int iData /*= -1*/) -{ - if(iData < 0 ) iData = 0; - return SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES[iData]; -} +void SmoothStoneBrickTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[SMOOTH_STONE_BRICK_NAMES_LENGTH]; -void SmoothStoneBrickTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[SMOOTH_STONE_BRICK_NAMES_LENGTH]; - - for (int i = 0; i < SMOOTH_STONE_BRICK_NAMES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < SMOOTH_STONE_BRICK_NAMES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/SmoothStoneBrickTile.h b/Minecraft.World/Blocks/SmoothStoneBrickTile.h index 915e74b35..17b2453f8 100644 --- a/Minecraft.World/Blocks/SmoothStoneBrickTile.h +++ b/Minecraft.World/Blocks/SmoothStoneBrickTile.h @@ -2,32 +2,32 @@ #include "Tile.h" class ChunkRebuildData; -class SmoothStoneBrickTile : public Tile -{ - friend class ChunkRebuildData; +class SmoothStoneBrickTile : public Tile { + friend class ChunkRebuildData; + public: - static const int TYPE_DEFAULT = 0; + static const int TYPE_DEFAULT = 0; static const int TYPE_MOSSY = 1; static const int TYPE_CRACKED = 2; - static const int TYPE_DETAIL = 3; + static const int TYPE_DETAIL = 3; - static const std::wstring TEXTURE_NAMES[]; + static const std::wstring TEXTURE_NAMES[]; - static const int SMOOTH_STONE_BRICK_NAMES_LENGTH = 4; + static const int SMOOTH_STONE_BRICK_NAMES_LENGTH = 4; - static const unsigned int SMOOTH_STONE_BRICK_NAMES[SMOOTH_STONE_BRICK_NAMES_LENGTH]; + static const unsigned int + SMOOTH_STONE_BRICK_NAMES[SMOOTH_STONE_BRICK_NAMES_LENGTH]; private: - Icon **icons; + Icon** icons; public: - SmoothStoneBrickTile(int id); public: - virtual Icon *getTexture(int face, int data); + virtual Icon* getTexture(int face, int data); - virtual unsigned int getDescriptionId(int iData = -1); - virtual int getSpawnResourcesAuxValue(int data); - void registerIcons(IconRegister *iconRegister); + virtual unsigned int getDescriptionId(int iData = -1); + virtual int getSpawnResourcesAuxValue(int data); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/SnowTile.cpp b/Minecraft.World/Blocks/SnowTile.cpp index 1fb62893f..56dec83c2 100644 --- a/Minecraft.World/Blocks/SnowTile.cpp +++ b/Minecraft.World/Blocks/SnowTile.cpp @@ -4,32 +4,21 @@ #include "../Headers/net.minecraft.world.item.h" #include "SnowTile.h" -SnowTile::SnowTile(int id) : Tile(id, Material::snow) -{ - setTicking(true); +SnowTile::SnowTile(int id) : Tile(id, Material::snow) { setTicking(true); } + +int SnowTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::snowBall->id; } +int SnowTile::getResourceCount(Random* random) { return 4; } -int SnowTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::snowBall->id; +void SnowTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->getBrightness(LightLayer::Block, x, y, z) > 11) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } } -int SnowTile::getResourceCount(Random *random) -{ - return 4; -} - -void SnowTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->getBrightness(LightLayer::Block, x, y, z) > 11) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } -} - -bool SnowTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool SnowTile::shouldTileTick(Level* level, int x, int y, int z) { return level->getBrightness(LightLayer::Block, x, y, z) > 11; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/SnowTile.h b/Minecraft.World/Blocks/SnowTile.h index 83b1f614b..cab2fce52 100644 --- a/Minecraft.World/Blocks/SnowTile.h +++ b/Minecraft.World/Blocks/SnowTile.h @@ -2,19 +2,20 @@ #include "Tile.h" -class SnowTile : public Tile -{ - friend class Tile; +class SnowTile : public Tile { + friend class Tile; + protected: - SnowTile(int id); + SnowTile(int id); public: - int getResource(int data, Random *random, int playerBonusLevel); + int getResource(int data, Random* random, int playerBonusLevel); - int getResourceCount(Random *random); + int getResourceCount(Random* random); - void tick(Level *level, int x, int y, int z, Random *random); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + void tick(Level* level, int x, int y, int z, Random* random); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/SpongeTile.cpp b/Minecraft.World/Blocks/SpongeTile.cpp index 6ea1989ee..434c98e6f 100644 --- a/Minecraft.World/Blocks/SpongeTile.cpp +++ b/Minecraft.World/Blocks/SpongeTile.cpp @@ -5,7 +5,4 @@ const int RANGE = 2; - -Sponge::Sponge(int id) : Tile(id, Material::sponge) -{ -} \ No newline at end of file +Sponge::Sponge(int id) : Tile(id, Material::sponge) {} \ No newline at end of file diff --git a/Minecraft.World/Blocks/SpongeTile.h b/Minecraft.World/Blocks/SpongeTile.h index a488ce629..ee6558bbd 100644 --- a/Minecraft.World/Blocks/SpongeTile.h +++ b/Minecraft.World/Blocks/SpongeTile.h @@ -2,12 +2,12 @@ #include "Tile.h" -class Sponge : public Tile -{ - friend class Tile; +class Sponge : public Tile { + friend class Tile; + public: - static const int RANGE = 2; + static const int RANGE = 2; protected: - Sponge(int id); + Sponge(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/SpringTile.cpp b/Minecraft.World/Blocks/SpringTile.cpp index e48379654..33e17cd8e 100644 --- a/Minecraft.World/Blocks/SpringTile.cpp +++ b/Minecraft.World/Blocks/SpringTile.cpp @@ -3,27 +3,31 @@ #include "SpringTile.h" - -SpringTile::SpringTile(int id, int liquidTileId) : Tile(id, Material::water) -{ - this->liquidTileId = liquidTileId; - this->setTicking(true); +SpringTile::SpringTile(int id, int liquidTileId) : Tile(id, Material::water) { + this->liquidTileId = liquidTileId; + this->setTicking(true); } -void SpringTile::onPlace(Level *level, int x, int y, int z) -{ - Tile::onPlace(level, x, y, z); - if (level->isEmptyTile(x-1, y, z)) level->setTile(x-1, y, z, liquidTileId); - if (level->isEmptyTile(x+1, y, z)) level->setTile(x+1, y, z, liquidTileId); - if (level->isEmptyTile(x, y, z-1)) level->setTile(x, y, z-1, liquidTileId); - if (level->isEmptyTile(x, y, z+1)) level->setTile(x, y, z+1, liquidTileId); +void SpringTile::onPlace(Level* level, int x, int y, int z) { + Tile::onPlace(level, x, y, z); + if (level->isEmptyTile(x - 1, y, z)) + level->setTile(x - 1, y, z, liquidTileId); + if (level->isEmptyTile(x + 1, y, z)) + level->setTile(x + 1, y, z, liquidTileId); + if (level->isEmptyTile(x, y, z - 1)) + level->setTile(x, y, z - 1, liquidTileId); + if (level->isEmptyTile(x, y, z + 1)) + level->setTile(x, y, z + 1, liquidTileId); } -void SpringTile::tick(Level *level, int x, int y, int z, Random *random) -{ - Tile::tick(level, x, y, z, random); - if (level->isEmptyTile(x-1, y, z)) level->setTile(x-1, y, z, liquidTileId); - if (level->isEmptyTile(x+1, y, z)) level->setTile(x+1, y, z, liquidTileId); - if (level->isEmptyTile(x, y, z-1)) level->setTile(x, y, z-1, liquidTileId); - if (level->isEmptyTile(x, y, z+1)) level->setTile(x, y, z+1, liquidTileId); +void SpringTile::tick(Level* level, int x, int y, int z, Random* random) { + Tile::tick(level, x, y, z, random); + if (level->isEmptyTile(x - 1, y, z)) + level->setTile(x - 1, y, z, liquidTileId); + if (level->isEmptyTile(x + 1, y, z)) + level->setTile(x + 1, y, z, liquidTileId); + if (level->isEmptyTile(x, y, z - 1)) + level->setTile(x, y, z - 1, liquidTileId); + if (level->isEmptyTile(x, y, z + 1)) + level->setTile(x, y, z + 1, liquidTileId); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/SpringTile.h b/Minecraft.World/Blocks/SpringTile.h index 8c0695590..b4f78c158 100644 --- a/Minecraft.World/Blocks/SpringTile.h +++ b/Minecraft.World/Blocks/SpringTile.h @@ -2,16 +2,15 @@ #include "Tile.h" -class SpringTile : public Tile -{ +class SpringTile : public Tile { private: - int liquidTileId; + int liquidTileId; protected: - SpringTile(int id, int liquidTileId); + SpringTile(int id, int liquidTileId); public: - void onPlace(Level *level, int x, int y, int z); + void onPlace(Level* level, int x, int y, int z); - void tick(Level *level, int x, int y, int z, Random *random); + void tick(Level* level, int x, int y, int z, Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/StairTile.cpp b/Minecraft.World/Blocks/StairTile.cpp index eaf6ba2fe..db068ae80 100644 --- a/Minecraft.World/Blocks/StairTile.cpp +++ b/Minecraft.World/Blocks/StairTile.cpp @@ -5,563 +5,491 @@ #include "../Headers/net.minecraft.h" #include "StairTile.h" -int StairTile::DEAD_SPACES[8][2] = { - {2, 6}, {3, 7}, {2, 3}, {6, 7}, - {0, 4}, {1, 5}, {0, 1}, {4, 5} - }; +int StairTile::DEAD_SPACES[8][2] = {{2, 6}, {3, 7}, {2, 3}, {6, 7}, + {0, 4}, {1, 5}, {0, 1}, {4, 5}}; -StairTile::StairTile(int id, Tile *base,int basedata) : Tile(id, base->material, false) -{ - this->base = base; - this->basedata = basedata; - isClipping = false; - clipStep = 0; - setDestroyTime(base->destroySpeed); - setExplodeable(base->explosionResistance / 3); - setSoundType(base->soundType); - setLightBlock(255); +StairTile::StairTile(int id, Tile* base, int basedata) + : Tile(id, base->material, false) { + this->base = base; + this->basedata = basedata; + isClipping = false; + clipStep = 0; + setDestroyTime(base->destroySpeed); + setExplodeable(base->explosionResistance / 3); + setSoundType(base->soundType); + setLightBlock(255); } -void StairTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void StairTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - if (isClipping) - { - setShape(0.5f * (clipStep % 2), 0.5f * (clipStep / 2 % 2), 0.5f * (clipStep / 4 % 2), 0.5f + 0.5f * (clipStep % 2), 0.5f + 0.5f * (clipStep / 2 % 2), 0.5f + 0.5f * (clipStep / 4 % 2)); - } - else - { - setShape(0, 0, 0, 1, 1, 1); - } + if (isClipping) { + setShape(0.5f * (clipStep % 2), 0.5f * (clipStep / 2 % 2), + 0.5f * (clipStep / 4 % 2), 0.5f + 0.5f * (clipStep % 2), + 0.5f + 0.5f * (clipStep / 2 % 2), + 0.5f + 0.5f * (clipStep / 4 % 2)); + } else { + setShape(0, 0, 0, 1, 1, 1); + } } -bool StairTile::isSolidRender(bool isServerLevel) -{ - return false; +bool StairTile::isSolidRender(bool isServerLevel) { return false; } + +bool StairTile::isCubeShaped() { return false; } + +int StairTile::getRenderShape() { return Tile::SHAPE_STAIRS; } + +void StairTile::setBaseShape(LevelSource* level, int x, int y, int z) { + int data = level->getData(x, y, z); + + if ((data & UPSIDEDOWN_BIT) != 0) { + setShape(0, .5f, 0, 1, 1, 1); + } else { + setShape(0, 0, 0, 1, .5f, 1); + } } -bool StairTile::isCubeShaped() -{ - return false; +bool StairTile::isStairs(int id) { + StairTile* st = dynamic_cast(Tile::tiles[id]); + return id > 0 && st != NULL; // Tile::tiles[id] instanceof StairTile; } -int StairTile::getRenderShape() -{ - return Tile::SHAPE_STAIRS; +bool StairTile::isLockAttached(LevelSource* level, int x, int y, int z, + int data) { + int lockTile = level->getTile(x, y, z); + if (isStairs(lockTile) && level->getData(x, y, z) == data) { + return true; + } + + return false; } -void StairTile::setBaseShape(LevelSource *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); +bool StairTile::setStepShape(LevelSource* level, int x, int y, int z) { + int data = level->getData(x, y, z); + int dir = data & 0x3; - if ((data & UPSIDEDOWN_BIT) != 0) - { - setShape(0, .5f, 0, 1, 1, 1); - } - else - { - setShape(0, 0, 0, 1, .5f, 1); - } -} + float bottom = 0.5f; + float top = 1.0f; -bool StairTile::isStairs(int id) -{ - StairTile *st = dynamic_cast(Tile::tiles[id]); - return id > 0 && st != NULL; //Tile::tiles[id] instanceof StairTile; -} + if ((data & UPSIDEDOWN_BIT) != 0) { + bottom = 0; + top = .5f; + } -bool StairTile::isLockAttached(LevelSource *level, int x, int y, int z, int data) -{ - int lockTile = level->getTile(x, y, z); - if (isStairs(lockTile) && level->getData(x, y, z) == data) - { - return true; - } + float west = 0; + float east = 1; + float north = 0; + float south = .5f; - return false; -} + bool checkInnerPiece = true; -bool StairTile::setStepShape(LevelSource *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - int dir = data & 0x3; + if (dir == DIR_EAST) { + west = .5f; + south = 1; - float bottom = 0.5f; - float top = 1.0f; + int backTile = level->getTile(x + 1, y, z); + int backData = level->getData(x + 1, y, z); + if (isStairs(backTile) && + ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) { + int backDir = backData & 0x3; + if (backDir == DIR_NORTH && + !isLockAttached(level, x, y, z + 1, data)) { + south = .5f; + checkInnerPiece = false; + } else if (backDir == DIR_SOUTH && + !isLockAttached(level, x, y, z - 1, data)) { + north = .5f; + checkInnerPiece = false; + } + } + } else if (dir == DIR_WEST) { + east = .5f; + south = 1; - if ((data & UPSIDEDOWN_BIT) != 0) - { - bottom = 0; - top = .5f; - } + int backTile = level->getTile(x - 1, y, z); + int backData = level->getData(x - 1, y, z); + if (isStairs(backTile) && + ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) { + int backDir = backData & 0x3; + if (backDir == DIR_NORTH && + !isLockAttached(level, x, y, z + 1, data)) { + south = .5f; + checkInnerPiece = false; + } else if (backDir == DIR_SOUTH && + !isLockAttached(level, x, y, z - 1, data)) { + north = .5f; + checkInnerPiece = false; + } + } + } else if (dir == DIR_SOUTH) { + north = .5f; + south = 1; - float west = 0; - float east = 1; - float north = 0; - float south = .5f; + int backTile = level->getTile(x, y, z + 1); + int backData = level->getData(x, y, z + 1); + if (isStairs(backTile) && + ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) { + int backDir = backData & 0x3; + if (backDir == DIR_WEST && + !isLockAttached(level, x + 1, y, z, data)) { + east = .5f; + checkInnerPiece = false; + } else if (backDir == DIR_EAST && + !isLockAttached(level, x - 1, y, z, data)) { + west = .5f; + checkInnerPiece = false; + } + } + } else if (dir == DIR_NORTH) { + int backTile = level->getTile(x, y, z - 1); + int backData = level->getData(x, y, z - 1); + if (isStairs(backTile) && + ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) { + int backDir = backData & 0x3; + if (backDir == DIR_WEST && + !isLockAttached(level, x + 1, y, z, data)) { + east = .5f; + checkInnerPiece = false; + } else if (backDir == DIR_EAST && + !isLockAttached(level, x - 1, y, z, data)) { + west = .5f; + checkInnerPiece = false; + } + } + } - bool checkInnerPiece = true; - - if (dir == DIR_EAST) - { - west = .5f; - south = 1; - - int backTile = level->getTile(x + 1, y, z); - int backData = level->getData(x + 1, y, z); - if (isStairs(backTile) && ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) - { - int backDir = backData & 0x3; - if (backDir == DIR_NORTH && !isLockAttached(level, x, y, z + 1, data)) - { - south = .5f; - checkInnerPiece = false; - } - else if (backDir == DIR_SOUTH && !isLockAttached(level, x, y, z - 1, data)) - { - north = .5f; - checkInnerPiece = false; - } - } - } - else if (dir == DIR_WEST) - { - east = .5f; - south = 1; - - int backTile = level->getTile(x - 1, y, z); - int backData = level->getData(x - 1, y, z); - if (isStairs(backTile) && ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) - { - int backDir = backData & 0x3; - if (backDir == DIR_NORTH && !isLockAttached(level, x, y, z + 1, data)) - { - south = .5f; - checkInnerPiece = false; - } - else if (backDir == DIR_SOUTH && !isLockAttached(level, x, y, z - 1, data)) - { - north = .5f; - checkInnerPiece = false; - } - } - } - else if (dir == DIR_SOUTH) - { - north = .5f; - south = 1; - - int backTile = level->getTile(x, y, z + 1); - int backData = level->getData(x, y, z + 1); - if (isStairs(backTile) && ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) - { - int backDir = backData & 0x3; - if (backDir == DIR_WEST && !isLockAttached(level, x + 1, y, z, data)) - { - east = .5f; - checkInnerPiece = false; - } - else if (backDir == DIR_EAST && !isLockAttached(level, x - 1, y, z, data)) - { - west = .5f; - checkInnerPiece = false; - } - } - } - else if (dir == DIR_NORTH) - { - int backTile = level->getTile(x, y, z - 1); - int backData = level->getData(x, y, z - 1); - if (isStairs(backTile) && ((data & UPSIDEDOWN_BIT) == (backData & UPSIDEDOWN_BIT))) - { - int backDir = backData & 0x3; - if (backDir == DIR_WEST && !isLockAttached(level, x + 1, y, z, data)) - { - east = .5f; - checkInnerPiece = false; - } - else if (backDir == DIR_EAST && !isLockAttached(level, x - 1, y, z, data)) - { - west = .5f; - checkInnerPiece = false; - } - } - } - - setShape(west, bottom, north, east, top, south); - return checkInnerPiece; + setShape(west, bottom, north, east, top, south); + return checkInnerPiece; } /* -* This method adds an extra 1/8 block if the stairs can attach as an -* "inner corner." -*/ -bool StairTile::setInnerPieceShape(LevelSource *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - int dir = data & 0x3; + * This method adds an extra 1/8 block if the stairs can attach as an + * "inner corner." + */ +bool StairTile::setInnerPieceShape(LevelSource* level, int x, int y, int z) { + int data = level->getData(x, y, z); + int dir = data & 0x3; - float bottom = 0.5f; - float top = 1.0f; + float bottom = 0.5f; + float top = 1.0f; - if ((data & UPSIDEDOWN_BIT) != 0) - { - bottom = 0; - top = .5f; - } + if ((data & UPSIDEDOWN_BIT) != 0) { + bottom = 0; + top = .5f; + } - float west = 0; - float east = .5f; - float north = .5f; - float south = 1.0f; + float west = 0; + float east = .5f; + float north = .5f; + float south = 1.0f; - bool hasInnerPiece = false; + bool hasInnerPiece = false; - if (dir == DIR_EAST) - { - int frontTile = level->getTile(x - 1, y, z); - int frontData = level->getData(x - 1, y, z); - if (isStairs(frontTile) && ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) - { - int frontDir = frontData & 0x3; - if (frontDir == DIR_NORTH && !isLockAttached(level, x, y, z - 1, data)) - { - north = 0; - south = .5f; - hasInnerPiece = true; - } - else if (frontDir == DIR_SOUTH && !isLockAttached(level, x, y, z + 1, data)) - { - north = .5f; - south = 1; - hasInnerPiece = true; - } - } - } - else if (dir == DIR_WEST) - { - int frontTile = level->getTile(x + 1, y, z); - int frontData = level->getData(x + 1, y, z); - if (isStairs(frontTile) && ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) - { - west = .5f; - east = 1.0f; - int frontDir = frontData & 0x3; - if (frontDir == DIR_NORTH && !isLockAttached(level, x, y, z - 1, data)) - { - north = 0; - south = .5f; - hasInnerPiece = true; - } - else if (frontDir == DIR_SOUTH && !isLockAttached(level, x, y, z + 1, data)) - { - north = .5f; - south = 1; - hasInnerPiece = true; - } - } - } - else if (dir == DIR_SOUTH) - { - int frontTile = level->getTile(x, y, z - 1); - int frontData = level->getData(x, y, z - 1); - if (isStairs(frontTile) && ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) - { - north = 0; - south = .5f; + if (dir == DIR_EAST) { + int frontTile = level->getTile(x - 1, y, z); + int frontData = level->getData(x - 1, y, z); + if (isStairs(frontTile) && + ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) { + int frontDir = frontData & 0x3; + if (frontDir == DIR_NORTH && + !isLockAttached(level, x, y, z - 1, data)) { + north = 0; + south = .5f; + hasInnerPiece = true; + } else if (frontDir == DIR_SOUTH && + !isLockAttached(level, x, y, z + 1, data)) { + north = .5f; + south = 1; + hasInnerPiece = true; + } + } + } else if (dir == DIR_WEST) { + int frontTile = level->getTile(x + 1, y, z); + int frontData = level->getData(x + 1, y, z); + if (isStairs(frontTile) && + ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) { + west = .5f; + east = 1.0f; + int frontDir = frontData & 0x3; + if (frontDir == DIR_NORTH && + !isLockAttached(level, x, y, z - 1, data)) { + north = 0; + south = .5f; + hasInnerPiece = true; + } else if (frontDir == DIR_SOUTH && + !isLockAttached(level, x, y, z + 1, data)) { + north = .5f; + south = 1; + hasInnerPiece = true; + } + } + } else if (dir == DIR_SOUTH) { + int frontTile = level->getTile(x, y, z - 1); + int frontData = level->getData(x, y, z - 1); + if (isStairs(frontTile) && + ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) { + north = 0; + south = .5f; - int frontDir = frontData & 0x3; - if (frontDir == DIR_WEST && !isLockAttached(level, x - 1, y, z, data)) - { - hasInnerPiece = true; - } - else if (frontDir == DIR_EAST && !isLockAttached(level, x + 1, y, z, data)) - { - west = .5f; - east = 1.0f; - hasInnerPiece = true; - } - } - } - else if (dir == DIR_NORTH) - { - int frontTile = level->getTile(x, y, z + 1); - int frontData = level->getData(x, y, z + 1); - if (isStairs(frontTile) && ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) - { - int frontDir = frontData & 0x3; - if (frontDir == DIR_WEST && !isLockAttached(level, x - 1, y, z, data)) - { - hasInnerPiece = true; - } - else if (frontDir == DIR_EAST && !isLockAttached(level, x + 1, y, z, data)) - { - west = .5f; - east = 1.0f; - hasInnerPiece = true; - } - } - } + int frontDir = frontData & 0x3; + if (frontDir == DIR_WEST && + !isLockAttached(level, x - 1, y, z, data)) { + hasInnerPiece = true; + } else if (frontDir == DIR_EAST && + !isLockAttached(level, x + 1, y, z, data)) { + west = .5f; + east = 1.0f; + hasInnerPiece = true; + } + } + } else if (dir == DIR_NORTH) { + int frontTile = level->getTile(x, y, z + 1); + int frontData = level->getData(x, y, z + 1); + if (isStairs(frontTile) && + ((data & UPSIDEDOWN_BIT) == (frontData & UPSIDEDOWN_BIT))) { + int frontDir = frontData & 0x3; + if (frontDir == DIR_WEST && + !isLockAttached(level, x - 1, y, z, data)) { + hasInnerPiece = true; + } else if (frontDir == DIR_EAST && + !isLockAttached(level, x + 1, y, z, data)) { + west = .5f; + east = 1.0f; + hasInnerPiece = true; + } + } + } - if (hasInnerPiece) - { - setShape(west, bottom, north, east, top, south); - } - return hasInnerPiece; + if (hasInnerPiece) { + setShape(west, bottom, north, east, top, south); + } + return hasInnerPiece; } -void StairTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ - setBaseShape(level, x, y, z); - Tile::addAABBs(level, x, y, z, box, boxes, source); +void StairTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { + setBaseShape(level, x, y, z); + Tile::addAABBs(level, x, y, z, box, boxes, source); - bool checkInnerPiece = setStepShape(level, x, y, z); - Tile::addAABBs(level, x, y, z, box, boxes, source); + bool checkInnerPiece = setStepShape(level, x, y, z); + Tile::addAABBs(level, x, y, z, box, boxes, source); - if (checkInnerPiece) - { - if (setInnerPieceShape(level, x, y, z)) - { - Tile::addAABBs(level, x, y, z, box, boxes, source); - } - } + if (checkInnerPiece) { + if (setInnerPieceShape(level, x, y, z)) { + Tile::addAABBs(level, x, y, z, box, boxes, source); + } + } - //int data = level->getData(x, y, z); - //int dir = data & 0x3; - //float lowerPieceY0 = 0; - //float lowerPieceY1 = 0.5f; - //float upperPieceY0 = 0.5f; - //float upperPieceY1 = 1; + // int data = level->getData(x, y, z); + // int dir = data & 0x3; + // float lowerPieceY0 = 0; + // float lowerPieceY1 = 0.5f; + // float upperPieceY0 = 0.5f; + // float upperPieceY1 = 1; - //if ((data & UPSIDEDOWN_BIT) != 0) - //{ - // lowerPieceY0 = .5f; - // lowerPieceY1 = 1; - // upperPieceY0 = 0; - // upperPieceY1 = .5f; - //} + // if ((data & UPSIDEDOWN_BIT) != 0) + //{ + // lowerPieceY0 = .5f; + // lowerPieceY1 = 1; + // upperPieceY0 = 0; + // upperPieceY1 = .5f; + // } - //setShape(0, lowerPieceY0, 0, 1, lowerPieceY1, 1); - //Tile::addAABBs(level, x, y, z, box, boxes); + // setShape(0, lowerPieceY0, 0, 1, lowerPieceY1, 1); + // Tile::addAABBs(level, x, y, z, box, boxes); - //if (dir == 0) - //{ - // setShape(0.5f, upperPieceY0, 0, 1, upperPieceY1, 1); - // Tile::addAABBs(level, x, y, z, box, boxes); - //} - //else if (dir == 1) - //{ - // setShape(0, upperPieceY0, 0, .5f, upperPieceY1, 1); - // Tile::addAABBs(level, x, y, z, box, boxes); - //} - //else if (dir == 2) - //{ - // setShape(0, upperPieceY0, 0.5f, 1, upperPieceY1, 1); - // Tile::addAABBs(level, x, y, z, box, boxes); - //} - //else if (dir == 3) - //{ - // setShape(0, upperPieceY0, 0, 1, upperPieceY1, .5f); - // Tile::addAABBs(level, x, y, z, box, boxes); - //} + // if (dir == 0) + //{ + // setShape(0.5f, upperPieceY0, 0, 1, upperPieceY1, 1); + // Tile::addAABBs(level, x, y, z, box, boxes); + // } + // else if (dir == 1) + //{ + // setShape(0, upperPieceY0, 0, .5f, upperPieceY1, 1); + // Tile::addAABBs(level, x, y, z, box, boxes); + // } + // else if (dir == 2) + //{ + // setShape(0, upperPieceY0, 0.5f, 1, upperPieceY1, 1); + // Tile::addAABBs(level, x, y, z, box, boxes); + // } + // else if (dir == 3) + //{ + // setShape(0, upperPieceY0, 0, 1, upperPieceY1, .5f); + // Tile::addAABBs(level, x, y, z, box, boxes); + // } - setShape(0, 0, 0, 1, 1, 1); + setShape(0, 0, 0, 1, 1, 1); } /** DELEGATES: **/ - -void StairTile::addLights(Level *level, int x, int y, int z) -{ - base->addLights(level, x, y, z); +void StairTile::addLights(Level* level, int x, int y, int z) { + base->addLights(level, x, y, z); } -void StairTile::animateTick(Level *level, int x, int y, int z, Random *random) -{ - base->animateTick(level, x, y, z, random); +void StairTile::animateTick(Level* level, int x, int y, int z, Random* random) { + base->animateTick(level, x, y, z, random); } -void StairTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - base->attack(level, x, y, z, player); +void StairTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + base->attack(level, x, y, z, player); } -void StairTile::destroy(Level *level, int x, int y, int z, int data) -{ - base->destroy(level, x, y, z, data); +void StairTile::destroy(Level* level, int x, int y, int z, int data) { + base->destroy(level, x, y, z, data); } // 4J - brought forward from 1.8.2 -int StairTile::getLightColor(LevelSource *level, int x, int y, int z, int tileId/*=-1*/) -{ - return base->getLightColor(level, x, y, z, tileId); +int StairTile::getLightColor(LevelSource* level, int x, int y, int z, + int tileId /*=-1*/) { + return base->getLightColor(level, x, y, z, tileId); } -float StairTile::getBrightness(LevelSource *level, int x, int y, int z) -{ - return base->getBrightness(level, x, y, z); +float StairTile::getBrightness(LevelSource* level, int x, int y, int z) { + return base->getBrightness(level, x, y, z); } -float StairTile::getExplosionResistance(std::shared_ptr source) -{ - return base->getExplosionResistance(source); +float StairTile::getExplosionResistance(std::shared_ptr source) { + return base->getExplosionResistance(source); } -int StairTile::getRenderLayer() -{ - return base->getRenderLayer(); +int StairTile::getRenderLayer() { return base->getRenderLayer(); } + +Icon* StairTile::getTexture(int face, int data) { + return base->getTexture(face, basedata); } -Icon *StairTile::getTexture(int face, int data) -{ - return base->getTexture(face, basedata); +int StairTile::getTickDelay() { return base->getTickDelay(); } + +AABB* StairTile::getTileAABB(Level* level, int x, int y, int z) { + return base->getTileAABB(level, x, y, z); } -int StairTile::getTickDelay() -{ - return base->getTickDelay(); +void StairTile::handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current) { + base->handleEntityInside(level, x, y, z, e, current); } -AABB *StairTile::getTileAABB(Level *level, int x, int y, int z) -{ - return base->getTileAABB(level, x, y, z); +bool StairTile::mayPick() { return base->mayPick(); } + +bool StairTile::mayPick(int data, bool liquid) { + return base->mayPick(data, liquid); } -void StairTile::handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current) -{ - base->handleEntityInside(level, x, y, z, e, current); +bool StairTile::mayPlace(Level* level, int x, int y, int z) { + return base->mayPlace(level, x, y, z); } -bool StairTile::mayPick() -{ - return base->mayPick(); +void StairTile::onPlace(Level* level, int x, int y, int z) { + neighborChanged(level, x, y, z, 0); + base->onPlace(level, x, y, z); } -bool StairTile::mayPick(int data, bool liquid) -{ - return base->mayPick(data, liquid); +void StairTile::onRemove(Level* level, int x, int y, int z, int id, int data) { + base->onRemove(level, x, y, z, id, data); } -bool StairTile::mayPlace(Level *level, int x, int y, int z) -{ - return base->mayPlace(level, x, y, z); +void StairTile::prepareRender(Level* level, int x, int y, int z) { + base->prepareRender(level, x, y, z); } -void StairTile::onPlace(Level *level, int x, int y, int z) -{ - neighborChanged(level, x, y, z, 0); - base->onPlace(level, x, y, z); +void StairTile::stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity) { + base->stepOn(level, x, y, z, entity); } -void StairTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - base->onRemove(level, x, y, z, id, data); -} - -void StairTile::prepareRender(Level *level, int x, int y, int z) -{ - base->prepareRender(level, x, y, z); -} - -void StairTile::stepOn(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - base->stepOn(level, x, y, z, entity); -} - -void StairTile::tick(Level *level, int x, int y, int z, Random *random) -{ - base->tick(level, x, y, z, random); +void StairTile::tick(Level* level, int x, int y, int z, Random* random) { + base->tick(level, x, y, z, random); } // 4J-HEG - Removed this to prevent weird tooltips (place steak on stairs!?) //// 4J-PB - Adding a TestUse for tooltip display -//bool StairTile::TestUse() +// bool StairTile::TestUse() //{ // return true; -//} +// } -bool StairTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool StairTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if (soundOnly) return false; - return base->use(level, x, y, z, player, 0, 0, 0, 0); + if (soundOnly) return false; + return base->use(level, x, y, z, player, 0, 0, 0, 0); } -void StairTile::wasExploded(Level *level, int x, int y, int z) -{ - base->wasExploded(level, x, y, z); +void StairTile::wasExploded(Level* level, int x, int y, int z) { + base->wasExploded(level, x, y, z); } -void StairTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int dir = ( Mth::floor(by->yRot * 4 / (360) + 0.5) ) & 3; - int usd = level->getData(x, y, z) & UPSIDEDOWN_BIT; +void StairTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int dir = (Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3; + int usd = level->getData(x, y, z) & UPSIDEDOWN_BIT; - if (dir == 0) level->setData(x, y, z, DIR_SOUTH | usd); - if (dir == 1) level->setData(x, y, z, DIR_WEST | usd); - if (dir == 2) level->setData(x, y, z, DIR_NORTH | usd); - if (dir == 3) level->setData(x, y, z, DIR_EAST | usd); + if (dir == 0) level->setData(x, y, z, DIR_SOUTH | usd); + if (dir == 1) level->setData(x, y, z, DIR_WEST | usd); + if (dir == 2) level->setData(x, y, z, DIR_NORTH | usd); + if (dir == 3) level->setData(x, y, z, DIR_EAST | usd); } -int StairTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - if (face == Facing::DOWN || (face != Facing::UP && clickY > 0.5)) - { - return itemValue | UPSIDEDOWN_BIT; - } - return itemValue; +int StairTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + if (face == Facing::DOWN || (face != Facing::UP && clickY > 0.5)) { + return itemValue | UPSIDEDOWN_BIT; + } + return itemValue; } -HitResult *StairTile::clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b) -{ - HitResult *results[8]; - for(unsigned int i = 0; i < 8; ++i) - { - results[i] = NULL; - } - int data = level->getData(xt, yt, zt); - int dir = data & 0x3; - bool upsideDown = (data & UPSIDEDOWN_BIT) == UPSIDEDOWN_BIT; - int *deadSpaces = DEAD_SPACES[dir + (upsideDown ? 4 : 0)]; +HitResult* StairTile::clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b) { + HitResult* results[8]; + for (unsigned int i = 0; i < 8; ++i) { + results[i] = NULL; + } + int data = level->getData(xt, yt, zt); + int dir = data & 0x3; + bool upsideDown = (data & UPSIDEDOWN_BIT) == UPSIDEDOWN_BIT; + int* deadSpaces = DEAD_SPACES[dir + (upsideDown ? 4 : 0)]; - isClipping = true; - for (int i = 0; i < 8; i++) - { - clipStep = i; + isClipping = true; + for (int i = 0; i < 8; i++) { + clipStep = i; - for(unsigned int j = 0; j < DEAD_SPACE_COLUMN_COUNT; ++j) - { - if (deadSpaces[j] == i) continue; - } + for (unsigned int j = 0; j < DEAD_SPACE_COLUMN_COUNT; ++j) { + if (deadSpaces[j] == i) continue; + } - results[i] = Tile::clip(level, xt, yt, zt, a, b); - } + results[i] = Tile::clip(level, xt, yt, zt, a, b); + } - for(unsigned int j = 0; j < DEAD_SPACE_COLUMN_COUNT; ++j) - { - results[deadSpaces[j]] = NULL; - } + for (unsigned int j = 0; j < DEAD_SPACE_COLUMN_COUNT; ++j) { + results[deadSpaces[j]] = NULL; + } - HitResult *closest = NULL; - double closestDist = 0; + HitResult* closest = NULL; + double closestDist = 0; - for (unsigned int i = 0; i < 8; ++i) - { - HitResult *result = results[i]; - if (result != NULL) - { - double dist = result->pos->distanceToSqr(b); + for (unsigned int i = 0; i < 8; ++i) { + HitResult* result = results[i]; + if (result != NULL) { + double dist = result->pos->distanceToSqr(b); - if (dist > closestDist) - { - closest = result; - closestDist = dist; - } - } - } + if (dist > closestDist) { + closest = result; + closestDist = dist; + } + } + } - return closest; + return closest; } -void StairTile::registerIcons(IconRegister *iconRegister) -{ - // None +void StairTile::registerIcons(IconRegister* iconRegister) { + // None } diff --git a/Minecraft.World/Blocks/StairTile.h b/Minecraft.World/Blocks/StairTile.h index 33c5a30ed..2244d19f9 100644 --- a/Minecraft.World/Blocks/StairTile.h +++ b/Minecraft.World/Blocks/StairTile.h @@ -5,102 +5,113 @@ class Mob; class Player; -class StairTile : public Tile -{ - friend class Tile; +class StairTile : public Tile { + friend class Tile; private: - static const int DEAD_SPACE_COLUMN_COUNT = 2; - static int DEAD_SPACES[8][DEAD_SPACE_COLUMN_COUNT]; + static const int DEAD_SPACE_COLUMN_COUNT = 2; + static int DEAD_SPACES[8][DEAD_SPACE_COLUMN_COUNT]; public: - static const int UPSIDEDOWN_BIT = 4; + static const int UPSIDEDOWN_BIT = 4; - // the direction is the way going up (for normal non-upsidedown stairs) - static const int DIR_EAST = 0; - static const int DIR_WEST = 1; - static const int DIR_SOUTH = 2; - static const int DIR_NORTH = 3; + // the direction is the way going up (for normal non-upsidedown stairs) + static const int DIR_EAST = 0; + static const int DIR_WEST = 1; + static const int DIR_SOUTH = 2; + static const int DIR_NORTH = 3; private: - Tile *base; - int basedata; - bool isClipping; - int clipStep; + Tile* base; + int basedata; + bool isClipping; + int clipStep; protected: - StairTile(int id, Tile *base, int basedata); + StairTile(int id, Tile* base, int basedata); public: - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - bool isSolidRender(bool isServerLevel = false); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); // 4J added forceData, + // forceEntity param + bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); + bool isCubeShaped(); - int getRenderShape(); + int getRenderShape(); - void setBaseShape(LevelSource *level, int x, int y, int z); - static bool isStairs(int id); + void setBaseShape(LevelSource* level, int x, int y, int z); + static bool isStairs(int id); private: - bool isLockAttached(LevelSource *level, int x, int y, int z, int data); + bool isLockAttached(LevelSource* level, int x, int y, int z, int data); public: - bool setStepShape(LevelSource *level, int x, int y, int z); - bool setInnerPieceShape(LevelSource *level, int x, int y, int z); + bool setStepShape(LevelSource* level, int x, int y, int z); + bool setInnerPieceShape(LevelSource* level, int x, int y, int z); - void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); + void addAABBs(Level* level, int x, int y, int z, AABB* box, AABBList* boxes, + std::shared_ptr source); - - /** DELEGATES: **/ + /** DELEGATES: **/ public: - void addLights(Level *level, int x, int y, int z); + void addLights(Level* level, int x, int y, int z); - void animateTick(Level *level, int x, int y, int z, Random *random); + void animateTick(Level* level, int x, int y, int z, Random* random); - void attack(Level *level, int x, int y, int z, std::shared_ptr player); + void attack(Level* level, int x, int y, int z, + std::shared_ptr player); - void destroy(Level *level, int x, int y, int z, int data); + void destroy(Level* level, int x, int y, int z, int data); - int getLightColor(LevelSource *level, int x, int y, int z, int tileId = -1); - float getBrightness(LevelSource *level, int x, int y, int z); + int getLightColor(LevelSource* level, int x, int y, int z, int tileId = -1); + float getBrightness(LevelSource* level, int x, int y, int z); - float getExplosionResistance(std::shared_ptr source); + float getExplosionResistance(std::shared_ptr source); - int getRenderLayer(); + int getRenderLayer(); - Icon *getTexture(int face, int data); + Icon* getTexture(int face, int data); - int getTickDelay(); + int getTickDelay(); - AABB *getTileAABB(Level *level, int x, int y, int z); + AABB* getTileAABB(Level* level, int x, int y, int z); - void handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current); + void handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current); - bool mayPick(); + bool mayPick(); - bool mayPick(int data, bool liquid); + bool mayPick(int data, bool liquid); - bool mayPlace(Level *level, int x, int y, int z); + bool mayPlace(Level* level, int x, int y, int z); - void onPlace(Level *level, int x, int y, int z); + void onPlace(Level* level, int x, int y, int z); - void onRemove(Level *level, int x, int y, int z, int id, int data); + void onRemove(Level* level, int x, int y, int z, int id, int data); - void prepareRender(Level *level, int x, int y, int z); + void prepareRender(Level* level, int x, int y, int z); - void stepOn(Level *level, int x, int y, int z, std::shared_ptr entity); + void stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity); - void tick(Level *level, int x, int y, int z, Random *random); + void tick(Level* level, int x, int y, int z, Random* random); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param - void wasExploded(Level *level, int x, int y, int z); + void wasExploded(Level* level, int x, int y, int z); - void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); + void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, int face, + float clickX, float clickY, float clickZ, + int itemValue); - HitResult *clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b); + HitResult* clip(Level* level, int xt, int yt, int zt, Vec3* a, Vec3* b); - virtual void registerIcons(IconRegister *iconRegister); + virtual void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/StemTile.cpp b/Minecraft.World/Blocks/StemTile.cpp index 22e1603ca..06e28b8a2 100644 --- a/Minecraft.World/Blocks/StemTile.cpp +++ b/Minecraft.World/Blocks/StemTile.cpp @@ -9,41 +9,31 @@ const std::wstring StemTile::TEXTURE_ANGLED = L"stem_bent"; -StemTile::StemTile(int id, Tile *fruit) : Bush(id) -{ +StemTile::StemTile(int id, Tile* fruit) : Bush(id) { this->fruit = fruit; setTicking(true); float ss = 0.125f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); - iconAngled = NULL; + iconAngled = NULL; } -bool StemTile::mayPlaceOn(int tile) -{ - return tile == Tile::farmland_Id; -} +bool StemTile::mayPlaceOn(int tile) { return tile == Tile::farmland_Id; } -void StemTile::tick(Level *level, int x, int y, int z, Random *random) -{ +void StemTile::tick(Level* level, int x, int y, int z, Random* random) { Tile::tick(level, x, y, z, random); - if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) - { - + if (level->getRawBrightness(x, y + 1, z) >= Level::MAX_BRIGHTNESS - 6) { float growthSpeed = getGrowthSpeed(level, x, y, z); - // 4J Stu - Brought forward change from 1.2.3 to make fruit more likely to grow - if (random->nextInt((int) (25 / growthSpeed) + 1) == 0) - { + // 4J Stu - Brought forward change from 1.2.3 to make fruit more likely + // to grow + if (random->nextInt((int)(25 / growthSpeed) + 1) == 0) { int age = level->getData(x, y, z); - if (age < 7) - { + if (age < 7) { age++; level->setData(x, y, z, age); - } - else - { + } else { if (level->getTile(x - 1, y, z) == fruit->id) return; if (level->getTile(x + 1, y, z) == fruit->id) return; if (level->getTile(x, y, z - 1) == fruit->id) return; @@ -56,26 +46,24 @@ void StemTile::tick(Level *level, int x, int y, int z, Random *random) if (dir == 1) xx++; if (dir == 2) zz--; if (dir == 3) zz++; - // 4J Stu - Brought forward change from 1.2.3 to not require farmland to grow fruits - int below = level->getTile(xx, y - 1, zz); - if (level->getTile(xx, y, zz) == 0 && (below == Tile::farmland_Id || below == Tile::dirt_Id || below == Tile::grass_Id)) - { + // 4J Stu - Brought forward change from 1.2.3 to not require + // farmland to grow fruits + int below = level->getTile(xx, y - 1, zz); + if (level->getTile(xx, y, zz) == 0 && + (below == Tile::farmland_Id || below == Tile::dirt_Id || + below == Tile::grass_Id)) { level->setTile(xx, y, zz, fruit->id); } - } } } - } -void StemTile::growCropsToMax(Level *level, int x, int y, int z) -{ - level->setData(x, y, z, 7); +void StemTile::growCropsToMax(Level* level, int x, int y, int z) { + level->setData(x, y, z, 7); } -float StemTile::getGrowthSpeed(Level *level, int x, int y, int z) -{ +float StemTile::getGrowthSpeed(Level* level, int x, int y, int z) { float speed = 1; int n = level->getTile(x, y, z - 1); @@ -90,16 +78,15 @@ float StemTile::getGrowthSpeed(Level *level, int x, int y, int z) bool horizontal = w == this->id || e == this->id; bool vertical = n == this->id || s == this->id; - bool diagonal = d0 == this->id || d1 == this->id || d2 == this->id || d3 == this->id; + bool diagonal = + d0 == this->id || d1 == this->id || d2 == this->id || d3 == this->id; for (int xx = x - 1; xx <= x + 1; xx++) - for (int zz = z - 1; zz <= z + 1; zz++) - { + for (int zz = z - 1; zz <= z + 1; zz++) { int t = level->getTile(xx, y - 1, zz); float tileSpeed = 0; - if (t == Tile::farmland_Id) - { + if (t == Tile::farmland_Id) { tileSpeed = 1; if (level->getData(xx, y - 1, zz) > 0) tileSpeed = 3; } @@ -114,121 +101,117 @@ float StemTile::getGrowthSpeed(Level *level, int x, int y, int z) return speed; } -int StemTile::getColor(int data) -{ - //int r = data * 32; - //int g = 255 - data * 8; - //int b = data * 4; - //return r << 16 | g << 8 | b; +int StemTile::getColor(int data) { + // int r = data * 32; + // int g = 255 - data * 8; + // int b = data * 4; + // return r << 16 | g << 8 | b; - int colour = 0; + int colour = 0; - unsigned int minColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_StemMin ); - unsigned int maxColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_StemMax ); + unsigned int minColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_StemMin); + unsigned int maxColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_StemMax); - uint8_t redComponent = ((minColour>>16)&0xFF) + (( (maxColour>>16)&0xFF - (minColour>>16)&0xFF)*( data/7.0f)); - uint8_t greenComponent = ((minColour>>8)&0xFF) + (( (maxColour>>8)&0xFF - (minColour>>8)&0xFF)*( data/7.0f)); - uint8_t blueComponent = ((minColour)&0xFF) + (( (maxColour)&0xFF - (minColour)&0xFF)*( data/7.0f)); + uint8_t redComponent = + ((minColour >> 16) & 0xFF) + + (((maxColour >> 16) & 0xFF - (minColour >> 16) & 0xFF) * (data / 7.0f)); + uint8_t greenComponent = + ((minColour >> 8) & 0xFF) + + (((maxColour >> 8) & 0xFF - (minColour >> 8) & 0xFF) * (data / 7.0f)); + uint8_t blueComponent = + ((minColour) & 0xFF) + + (((maxColour) & 0xFF - (minColour) & 0xFF) * (data / 7.0f)); - colour = redComponent<<16 | greenComponent<<8 | blueComponent; - return colour; + colour = redComponent << 16 | greenComponent << 8 | blueComponent; + return colour; } -int StemTile::getColor(LevelSource *level, int x, int y, int z) -{ - return getColor(level->getData(x, y, z)); +int StemTile::getColor(LevelSource* level, int x, int y, int z) { + return getColor(level->getData(x, y, z)); } -void StemTile::updateDefaultShape() -{ +void StemTile::updateDefaultShape() { float ss = 0.125f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.25f, 0.5f + ss); } -void StemTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void StemTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); tls->yy1 = (level->getData(x, y, z) * 2 + 2) / 16.0f; float ss = 0.125f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, (float) tls->yy1, 0.5f + ss); + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, (float)tls->yy1, + 0.5f + ss); } -int StemTile::getRenderShape() -{ - return Tile::SHAPE_STEM; -} +int StemTile::getRenderShape() { return Tile::SHAPE_STEM; } -int StemTile::getConnectDir(LevelSource *level, int x, int y, int z) - { - int d = level->getData(x, y, z); - if (d < 7) return -1; - if (level->getTile(x - 1, y, z) == fruit->id) return 0; - if (level->getTile(x + 1, y, z) == fruit->id) return 1; - if (level->getTile(x, y, z - 1) == fruit->id) return 2; - if (level->getTile(x, y, z + 1) == fruit->id) return 3; - return -1; +int StemTile::getConnectDir(LevelSource* level, int x, int y, int z) { + int d = level->getData(x, y, z); + if (d < 7) return -1; + if (level->getTile(x - 1, y, z) == fruit->id) return 0; + if (level->getTile(x + 1, y, z) == fruit->id) return 1; + if (level->getTile(x, y, z - 1) == fruit->id) return 2; + if (level->getTile(x, y, z + 1) == fruit->id) return 3; + return -1; } /** - * Using this method instead of destroy() to determine if seeds should be - * dropped - */ -void StemTile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus) -{ + * Using this method instead of destroy() to determine if seeds should be + * dropped + */ +void StemTile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus) { Tile::spawnResources(level, x, y, z, data, odds, playerBonus); - if (level->isClientSide) - { + if (level->isClientSide) { return; } - Item *seed = NULL; + Item* seed = NULL; if (fruit == Tile::pumpkin) seed = Item::seeds_pumpkin; if (fruit == Tile::melon) seed = Item::seeds_melon; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { if (level->random->nextInt(5 * 3) > data) continue; float s = 0.7f; float xo = level->random->nextFloat() * s + (1 - s) * 0.5f; float yo = level->random->nextFloat() * s + (1 - s) * 0.5f; float zo = level->random->nextFloat() * s + (1 - s) * 0.5f; - std::shared_ptr item = std::shared_ptr(new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr(new ItemInstance(seed)))); + std::shared_ptr item = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance(seed)))); item->throwTime = 10; level->addEntity(item); } } -int StemTile::getResource(int data, Random *random, int playerBonusLevel) -{ +int StemTile::getResource(int data, Random* random, int playerBonusLevel) { return -1; } -int StemTile::getResourceCount(Random *random) -{ - return 1; +int StemTile::getResourceCount(Random* random) { return 1; } + +int StemTile::cloneTileId(Level* level, int x, int y, int z) { + if (fruit == Tile::pumpkin) { + return Item::seeds_pumpkin_Id; + } else if (fruit == Tile::melon) { + return Item::seeds_melon_Id; + } + + return 0; } -int StemTile::cloneTileId(Level *level, int x, int y, int z) -{ - if (fruit == Tile::pumpkin) - { - return Item::seeds_pumpkin_Id; - } - else if (fruit == Tile::melon) - { - return Item::seeds_melon_Id; - } - - return 0; +void StemTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"stem_straight"); + iconAngled = iconRegister->registerIcon(TEXTURE_ANGLED); } -void StemTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"stem_straight"); - iconAngled = iconRegister->registerIcon(TEXTURE_ANGLED); -} - -Icon *StemTile::getAngledTexture() -{ - return iconAngled; -} +Icon* StemTile::getAngledTexture() { return iconAngled; } diff --git a/Minecraft.World/Blocks/StemTile.h b/Minecraft.World/Blocks/StemTile.h index bc2b34894..c29edd640 100644 --- a/Minecraft.World/Blocks/StemTile.h +++ b/Minecraft.World/Blocks/StemTile.h @@ -3,46 +3,52 @@ #include "PlantTile.h" class ChunkRebuildData; -class StemTile : public Bush -{ - friend class ChunkRebuildData; +class StemTile : public Bush { + friend class ChunkRebuildData; + public: - static const std::wstring TEXTURE_ANGLED; + static const std::wstring TEXTURE_ANGLED; private: - Tile *fruit; - Icon *iconAngled; + Tile* fruit; + Icon* iconAngled; public: - StemTile(int id, Tile *fruit); + StemTile(int id, Tile* fruit); virtual bool mayPlaceOn(int tile); + public: - virtual void tick(Level *level, int x, int y, int z, Random *random); - void growCropsToMax(Level *level, int x, int y, int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + void growCropsToMax(Level* level, int x, int y, int z); + private: - float getGrowthSpeed(Level *level, int x, int y, int z); + float getGrowthSpeed(Level* level, int x, int y, int z); public: - using Tile::getColor; - int getColor(int data); + using Tile::getColor; + int getColor(int data); - virtual int getColor(LevelSource *level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z); virtual void updateDefaultShape(); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param virtual int getRenderShape(); - int getConnectDir(LevelSource *level, int x, int y, int z); + int getConnectDir(LevelSource* level, int x, int y, int z); /** * Using this method instead of destroy() to determine if seeds should be * dropped */ - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonus); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonus); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); - Icon *getAngledTexture(); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); + Icon* getAngledTexture(); }; diff --git a/Minecraft.World/Blocks/StoneMonsterTile.cpp b/Minecraft.World/Blocks/StoneMonsterTile.cpp index 5da528f08..fa22ea7c7 100644 --- a/Minecraft.World/Blocks/StoneMonsterTile.cpp +++ b/Minecraft.World/Blocks/StoneMonsterTile.cpp @@ -3,112 +3,96 @@ #include "../Headers/net.minecraft.world.level.h" #include "StoneMonsterTile.h" -const unsigned int StoneMonsterTile::STONE_MONSTER_NAMES[STONE_MONSTER_NAMES_LENGTH] = { IDS_TILE_STONE_SILVERFISH, - IDS_TILE_STONE_SILVERFISH_COBBLESTONE, - IDS_TILE_STONE_SILVERFISH_STONE_BRICK, - }; +const unsigned int + StoneMonsterTile::STONE_MONSTER_NAMES[STONE_MONSTER_NAMES_LENGTH] = { + IDS_TILE_STONE_SILVERFISH, + IDS_TILE_STONE_SILVERFISH_COBBLESTONE, + IDS_TILE_STONE_SILVERFISH_STONE_BRICK, +}; -StoneMonsterTile::StoneMonsterTile(int id) : Tile(id, Material::clay) -{ +StoneMonsterTile::StoneMonsterTile(int id) : Tile(id, Material::clay) { setDestroyTime(0); } -Icon *StoneMonsterTile::getTexture(int face, int data) -{ - if (data == HOST_COBBLE) - { +Icon* StoneMonsterTile::getTexture(int face, int data) { + if (data == HOST_COBBLE) { return Tile::stoneBrick->getTexture(face); } - if (data == HOST_STONEBRICK) - { + if (data == HOST_STONEBRICK) { return Tile::stoneBrickSmooth->getTexture(face); } return Tile::rock->getTexture(face); } -void StoneMonsterTile::registerIcons(IconRegister *iconRegister) -{ - // None +void StoneMonsterTile::registerIcons(IconRegister* iconRegister) { + // None } -void StoneMonsterTile::destroy(Level *level, int x, int y, int z, int data) -{ - if (!level->isClientSide) - { - // 4J - limit total amount of monsters. The normal map spawning limits these to 50, and mobspawning tiles limit to 60, so give ourselves a bit of headroom here to also be able to make silverfish - if(level->countInstanceOf( eTYPE_MONSTER, false) < 70 ) - { - // Also limit the amount of silverfish specifically - if(level->countInstanceOf( eTYPE_SILVERFISH, true) < 15 ) - { - std::shared_ptr silverfish = std::shared_ptr(new Silverfish(level)); - silverfish->moveTo(x + .5, y, z + .5, 0, 0); - level->addEntity(silverfish); +void StoneMonsterTile::destroy(Level* level, int x, int y, int z, int data) { + if (!level->isClientSide) { + // 4J - limit total amount of monsters. The normal map spawning limits + // these to 50, and mobspawning tiles limit to 60, so give ourselves a + // bit of headroom here to also be able to make silverfish + if (level->countInstanceOf(eTYPE_MONSTER, false) < 70) { + // Also limit the amount of silverfish specifically + if (level->countInstanceOf(eTYPE_SILVERFISH, true) < 15) { + std::shared_ptr silverfish = + std::shared_ptr(new Silverfish(level)); + silverfish->moveTo(x + .5, y, z + .5, 0, 0); + level->addEntity(silverfish); - silverfish->spawnAnim(); - } - } + silverfish->spawnAnim(); + } + } } Tile::destroy(level, x, y, z, data); } -int StoneMonsterTile::getResourceCount(Random *random) -{ - return 0; +int StoneMonsterTile::getResourceCount(Random* random) { return 0; } + +bool StoneMonsterTile::isCompatibleHostBlock(int block) { + return block == Tile::rock_Id || block == Tile::stoneBrick_Id || + block == Tile::stoneBrickSmooth_Id; } -bool StoneMonsterTile::isCompatibleHostBlock(int block) -{ - return block == Tile::rock_Id || block == Tile::stoneBrick_Id || block == Tile::stoneBrickSmooth_Id; -} - -int StoneMonsterTile::getDataForHostBlock(int block) -{ - if (block == Tile::stoneBrick_Id) - { +int StoneMonsterTile::getDataForHostBlock(int block) { + if (block == Tile::stoneBrick_Id) { return HOST_COBBLE; } - if (block == Tile::stoneBrickSmooth_Id) - { + if (block == Tile::stoneBrickSmooth_Id) { return HOST_STONEBRICK; } return HOST_ROCK; } -Tile *StoneMonsterTile::getHostBlockForData(int data) -{ - switch (data) - { - case HOST_COBBLE: - return Tile::stoneBrick; - case HOST_STONEBRICK: - return Tile::stoneBrickSmooth; - default: - return Tile::rock; - } +Tile* StoneMonsterTile::getHostBlockForData(int data) { + switch (data) { + case HOST_COBBLE: + return Tile::stoneBrick; + case HOST_STONEBRICK: + return Tile::stoneBrickSmooth; + default: + return Tile::rock; + } } -std::shared_ptr StoneMonsterTile::getSilkTouchItemInstance(int data) -{ - Tile *tile = Tile::rock; - if (data == HOST_COBBLE) - { +std::shared_ptr StoneMonsterTile::getSilkTouchItemInstance( + int data) { + Tile* tile = Tile::rock; + if (data == HOST_COBBLE) { tile = Tile::stoneBrick; } - if (data == HOST_STONEBRICK) - { + if (data == HOST_STONEBRICK) { tile = Tile::stoneBrickSmooth; } return std::shared_ptr(new ItemInstance(tile)); } -int StoneMonsterTile::cloneTileData(Level *level, int x, int y, int z) -{ - return level->getData(x, y, z); +int StoneMonsterTile::cloneTileData(Level* level, int x, int y, int z) { + return level->getData(x, y, z); } -unsigned int StoneMonsterTile::getDescriptionId(int iData /*= -1*/) -{ - if(iData < 0 ) iData = 0; - return StoneMonsterTile::STONE_MONSTER_NAMES[iData]; +unsigned int StoneMonsterTile::getDescriptionId(int iData /*= -1*/) { + if (iData < 0) iData = 0; + return StoneMonsterTile::STONE_MONSTER_NAMES[iData]; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/StoneMonsterTile.h b/Minecraft.World/Blocks/StoneMonsterTile.h index 96063a140..e4649b085 100644 --- a/Minecraft.World/Blocks/StoneMonsterTile.h +++ b/Minecraft.World/Blocks/StoneMonsterTile.h @@ -3,36 +3,36 @@ class Random; -class StoneMonsterTile : public Tile -{ +class StoneMonsterTile : public Tile { public: - static const int HOST_ROCK = 0; + static const int HOST_ROCK = 0; static const int HOST_COBBLE = 1; static const int HOST_STONEBRICK = 2; - static const int STONE_MONSTER_NAMES_LENGTH = 3; + static const int STONE_MONSTER_NAMES_LENGTH = 3; - static const unsigned int STONE_MONSTER_NAMES[STONE_MONSTER_NAMES_LENGTH]; + static const unsigned int STONE_MONSTER_NAMES[STONE_MONSTER_NAMES_LENGTH]; - // 4J Stu - I don't know why this is protected in Java -//protected: + // 4J Stu - I don't know why this is protected in Java + // protected: public: StoneMonsterTile(int id); + public: - virtual Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); - virtual void destroy(Level *level, int x, int y, int z, int data); - virtual int getResourceCount(Random *random); + virtual Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); + virtual void destroy(Level* level, int x, int y, int z, int data); + virtual int getResourceCount(Random* random); static bool isCompatibleHostBlock(int block); static int getDataForHostBlock(int block); - static Tile *getHostBlockForData(int data); + static Tile* getHostBlockForData(int data); - virtual unsigned int getDescriptionId(int iData = -1); + virtual unsigned int getDescriptionId(int iData = -1); protected: - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual std::shared_ptr getSilkTouchItemInstance(int data); public: - int cloneTileData(Level *level, int x, int y, int z); + int cloneTileData(Level* level, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/StoneSlabTile.cpp b/Minecraft.World/Blocks/StoneSlabTile.cpp index 6110dd3fd..406debace 100644 --- a/Minecraft.World/Blocks/StoneSlabTile.cpp +++ b/Minecraft.World/Blocks/StoneSlabTile.cpp @@ -5,80 +5,70 @@ #include "../Headers/net.minecraft.world.h" #include "StoneSlabTile.h" +const unsigned int StoneSlabTile::SLAB_NAMES[SLAB_NAMES_LENGTH] = { + IDS_TILE_STONESLAB_STONE, IDS_TILE_STONESLAB_SAND, + IDS_TILE_STONESLAB_WOOD, IDS_TILE_STONESLAB_COBBLE, + IDS_TILE_STONESLAB_BRICK, IDS_TILE_STONESLAB_SMOOTHBRICK, + IDS_TILE_STONESLAB_NETHERBRICK, IDS_TILE_STONESLAB_QUARTZ, +}; -const unsigned int StoneSlabTile::SLAB_NAMES[SLAB_NAMES_LENGTH] = { IDS_TILE_STONESLAB_STONE, - IDS_TILE_STONESLAB_SAND, - IDS_TILE_STONESLAB_WOOD, - IDS_TILE_STONESLAB_COBBLE, - IDS_TILE_STONESLAB_BRICK, - IDS_TILE_STONESLAB_SMOOTHBRICK, - IDS_TILE_STONESLAB_NETHERBRICK, - IDS_TILE_STONESLAB_QUARTZ, - }; +StoneSlabTile::StoneSlabTile(int id, bool fullSize) + : HalfSlabTile(id, fullSize, Material::stone) {} -StoneSlabTile::StoneSlabTile(int id, bool fullSize) : HalfSlabTile(id, fullSize, Material::stone) -{ +Icon* StoneSlabTile::getTexture(int face, int data) { + int type = data & TYPE_MASK; + if (fullSize && (data & TOP_SLOT_BIT) != 0) { + face = Facing::UP; + } + switch (type) { + case STONE_SLAB: + if (face == Facing::UP || face == Facing::DOWN) return icon; + return iconSide; + break; + case SAND_SLAB: + return Tile::sandStone->getTexture(face); + case WOOD_SLAB: + return Tile::wood->getTexture(face); + case COBBLESTONE_SLAB: + return Tile::stoneBrick->getTexture(face); + case BRICK_SLAB: + return Tile::redBrick->getTexture(face); + case SMOOTHBRICK_SLAB: + return Tile::stoneBrickSmooth->getTexture( + face, SmoothStoneBrickTile::TYPE_DEFAULT); + case NETHERBRICK_SLAB: + return Tile::netherBrick->getTexture(Facing::UP); + case QUARTZ_SLAB: + return Tile::quartzBlock->getTexture(face); + } + + return icon; } -Icon *StoneSlabTile::getTexture(int face, int data) -{ - int type = data & TYPE_MASK; - if (fullSize && (data & TOP_SLOT_BIT) != 0) - { - face = Facing::UP; - } - switch(type) - { - case STONE_SLAB: - if (face == Facing::UP || face == Facing::DOWN) return icon; - return iconSide; - break; - case SAND_SLAB: - return Tile::sandStone->getTexture(face); - case WOOD_SLAB: - return Tile::wood->getTexture(face); - case COBBLESTONE_SLAB: - return Tile::stoneBrick->getTexture(face); - case BRICK_SLAB: - return Tile::redBrick->getTexture(face); - case SMOOTHBRICK_SLAB: - return Tile::stoneBrickSmooth->getTexture(face, SmoothStoneBrickTile::TYPE_DEFAULT); - case NETHERBRICK_SLAB: - return Tile::netherBrick->getTexture(Facing::UP); - case QUARTZ_SLAB: - return Tile::quartzBlock->getTexture(face); - } - - return icon; +void StoneSlabTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"stoneslab_top"); + iconSide = iconRegister->registerIcon(L"stoneslab_side"); } -void StoneSlabTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"stoneslab_top"); - iconSide = iconRegister->registerIcon(L"stoneslab_side"); +int StoneSlabTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::stoneSlabHalf_Id; } -int StoneSlabTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::stoneSlabHalf_Id; +unsigned int StoneSlabTile::getDescriptionId(int iData /*= -1*/) { + if (iData < 0) iData = 0; + return StoneSlabTile::SLAB_NAMES[iData]; } -unsigned int StoneSlabTile::getDescriptionId(int iData /*= -1*/) -{ - if(iData < 0 ) iData = 0; - return StoneSlabTile::SLAB_NAMES[iData]; +int StoneSlabTile::getAuxName(int auxValue) { + if (auxValue < 0 || auxValue >= SLAB_NAMES_LENGTH) { + auxValue = 0; + } + return SLAB_NAMES[auxValue]; // super.getDescriptionId() + "." + + // SLAB_NAMES[auxValue]; } -int StoneSlabTile::getAuxName(int auxValue) -{ - if (auxValue < 0 || auxValue >= SLAB_NAMES_LENGTH) - { - auxValue = 0; - } - return SLAB_NAMES[auxValue];//super.getDescriptionId() + "." + SLAB_NAMES[auxValue]; -} - -std::shared_ptr StoneSlabTile::getSilkTouchItemInstance(int data) -{ - return std::shared_ptr(new ItemInstance(Tile::stoneSlabHalf_Id, 2, data & TYPE_MASK)); +std::shared_ptr StoneSlabTile::getSilkTouchItemInstance( + int data) { + return std::shared_ptr( + new ItemInstance(Tile::stoneSlabHalf_Id, 2, data & TYPE_MASK)); } diff --git a/Minecraft.World/Blocks/StoneSlabTile.h b/Minecraft.World/Blocks/StoneSlabTile.h index d6a928647..80aec61a8 100644 --- a/Minecraft.World/Blocks/StoneSlabTile.h +++ b/Minecraft.World/Blocks/StoneSlabTile.h @@ -1,39 +1,39 @@ #pragma once - #include "HalfSlabTile.h" class ChunkRebuildData; -class StoneSlabTile : public HalfSlabTile -{ - friend ChunkRebuildData; +class StoneSlabTile : public HalfSlabTile { + friend ChunkRebuildData; + public: - static const int STONE_SLAB = 0; - static const int SAND_SLAB = 1; - static const int WOOD_SLAB = 2; - static const int COBBLESTONE_SLAB = 3; - static const int BRICK_SLAB = 4; - static const int SMOOTHBRICK_SLAB = 5; - static const int NETHERBRICK_SLAB = 6; - static const int QUARTZ_SLAB = 7; + static const int STONE_SLAB = 0; + static const int SAND_SLAB = 1; + static const int WOOD_SLAB = 2; + static const int COBBLESTONE_SLAB = 3; + static const int BRICK_SLAB = 4; + static const int SMOOTHBRICK_SLAB = 5; + static const int NETHERBRICK_SLAB = 6; + static const int QUARTZ_SLAB = 7; - static const int SLAB_NAMES_LENGTH = 8; + static const int SLAB_NAMES_LENGTH = 8; - static const unsigned int SLAB_NAMES[SLAB_NAMES_LENGTH]; + static const unsigned int SLAB_NAMES[SLAB_NAMES_LENGTH]; private: - Icon *iconSide; + Icon* iconSide; public: - StoneSlabTile(int id, bool fullSize); + StoneSlabTile(int id, bool fullSize); - virtual Icon *getTexture(int face, int data); + virtual Icon* getTexture(int face, int data); + + void registerIcons(IconRegister* iconRegister); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual unsigned int getDescriptionId(int iData = -1); + virtual int getAuxName(int auxValue); - void registerIcons(IconRegister *iconRegister); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual unsigned int getDescriptionId(int iData = -1); - virtual int getAuxName(int auxValue); protected: - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual std::shared_ptr getSilkTouchItemInstance(int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/StoneTile.cpp b/Minecraft.World/Blocks/StoneTile.cpp index 334cad879..6116ffd20 100644 --- a/Minecraft.World/Blocks/StoneTile.cpp +++ b/Minecraft.World/Blocks/StoneTile.cpp @@ -1,11 +1,8 @@ #include "../Platform/stdafx.h" #include "StoneTile.h" -StoneTile::StoneTile(int id) : Tile(id, Material::stone) -{ -} +StoneTile::StoneTile(int id) : Tile(id, Material::stone) {} -int StoneTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::stoneBrick_Id; +int StoneTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::stoneBrick_Id; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/StoneTile.h b/Minecraft.World/Blocks/StoneTile.h index 7d0043096..0ef556e90 100644 --- a/Minecraft.World/Blocks/StoneTile.h +++ b/Minecraft.World/Blocks/StoneTile.h @@ -3,9 +3,8 @@ class Random; -class StoneTile : public Tile -{ +class StoneTile : public Tile { public: - StoneTile(int id); - virtual int getResource(int data, Random *random, int playerBonusLevel); + StoneTile(int id); + virtual int getResource(int data, Random* random, int playerBonusLevel); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TallGrassPlantTile.cpp b/Minecraft.World/Blocks/TallGrassPlantTile.cpp index eba2d3ea9..e77036d2c 100644 --- a/Minecraft.World/Blocks/TallGrassPlantTile.cpp +++ b/Minecraft.World/Blocks/TallGrassPlantTile.cpp @@ -7,113 +7,102 @@ #include "../Headers/net.minecraft.world.h" #include "TallGrassPlantTile.h" -const unsigned int TallGrass::TALL_GRASS_TILE_NAMES[TALL_GRASS_TILE_NAMES_LENGTH] = { IDS_TILE_SHRUB, - IDS_TILE_GRASS, - IDS_TILE_FERN, - }; +const unsigned int + TallGrass::TALL_GRASS_TILE_NAMES[TALL_GRASS_TILE_NAMES_LENGTH] = { + IDS_TILE_SHRUB, + IDS_TILE_GRASS, + IDS_TILE_FERN, +}; -const std::wstring TallGrass::TEXTURE_NAMES[] = {L"deadbush", L"tallgrass", L"fern"}; +const std::wstring TallGrass::TEXTURE_NAMES[] = {L"deadbush", L"tallgrass", + L"fern"}; -TallGrass::TallGrass(int id) : Bush(id, Material::replaceable_plant) -{ - this->updateDefaultShape(); +TallGrass::TallGrass(int id) : Bush(id, Material::replaceable_plant) { + this->updateDefaultShape(); } // 4J Added override -void TallGrass::updateDefaultShape() -{ - float ss = 0.4f; - this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.8f, 0.5f + ss); +void TallGrass::updateDefaultShape() { + float ss = 0.4f; + this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, 0.8f, 0.5f + ss); } - -Icon *TallGrass::getTexture(int face, int data) -{ - if (data >= TALL_GRASS_TILE_NAMES_LENGTH) data = 0; - return icons[data]; +Icon* TallGrass::getTexture(int face, int data) { + if (data >= TALL_GRASS_TILE_NAMES_LENGTH) data = 0; + return icons[data]; } -int TallGrass::getColor(int auxData) -{ +int TallGrass::getColor(int auxData) { if (auxData == DEAD_SHRUB) return 0xffffff; return FoliageColor::getDefaultColor(); } -int TallGrass::getColor() const -{ - // 4J Stu - Not using this any more - //double temp = 0.5; - //double rain = 1.0; +int TallGrass::getColor() const { + // 4J Stu - Not using this any more + // double temp = 0.5; + // double rain = 1.0; - //return GrassColor::get(temp, rain); + // return GrassColor::get(temp, rain); - return Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Grass_Common ); + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Grass_Common); } -int TallGrass::getColor(LevelSource *level, int x, int y, int z ) -{ - return getColor( level, x, y, z, level->getData(x, y, z) ); +int TallGrass::getColor(LevelSource* level, int x, int y, int z) { + return getColor(level, x, y, z, level->getData(x, y, z)); } -// 4J - changed interface to have data passed in, and put existing interface as wrapper above -int TallGrass::getColor(LevelSource *level, int x, int y, int z, int data) -{ - int d = data; - if (d == DEAD_SHRUB) return 0xffffff; +// 4J - changed interface to have data passed in, and put existing interface as +// wrapper above +int TallGrass::getColor(LevelSource* level, int x, int y, int z, int data) { + int d = data; + if (d == DEAD_SHRUB) return 0xffffff; - return level->getBiome(x, z)->getGrassColor(); + return level->getBiome(x, z)->getGrassColor(); } -int TallGrass::getResource(int data, Random *random, int playerBonusLevel) -{ - if (random->nextInt(8) == 0) { - return Item::seeds_wheat->id; - } +int TallGrass::getResource(int data, Random* random, int playerBonusLevel) { + if (random->nextInt(8) == 0) { + return Item::seeds_wheat->id; + } - return -1; + return -1; } -int TallGrass::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - return 1 + random->nextInt(bonusLevel * 2 + 1); +int TallGrass::getResourceCountForLootBonus(int bonusLevel, Random* random) { + return 1 + random->nextInt(bonusLevel * 2 + 1); } -void TallGrass::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - if (!level->isClientSide && player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::shears->id) - { - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); +void TallGrass::playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data) { + if (!level->isClientSide && player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::shears->id) { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); // drop leaf block instead of sapling - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Tile::tallgrass, 1, data))); - } - else - { + popResource(level, x, y, z, + std::shared_ptr( + new ItemInstance(Tile::tallgrass, 1, data))); + } else { Bush::playerDestroy(level, player, x, y, z, data); } } -int TallGrass::cloneTileData(Level *level, int x, int y, int z) -{ - return level->getData(x, y, z); +int TallGrass::cloneTileData(Level* level, int x, int y, int z) { + return level->getData(x, y, z); } -unsigned int TallGrass::getDescriptionId(int iData /*= -1*/) -{ - if(iData < 0 ) iData = 0; - return TallGrass::TALL_GRASS_TILE_NAMES[iData]; +unsigned int TallGrass::getDescriptionId(int iData /*= -1*/) { + if (iData < 0) iData = 0; + return TallGrass::TALL_GRASS_TILE_NAMES[iData]; } -void TallGrass::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[TALL_GRASS_TILE_NAMES_LENGTH]; +void TallGrass::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[TALL_GRASS_TILE_NAMES_LENGTH]; - for (int i = 0; i < TALL_GRASS_TILE_NAMES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < TALL_GRASS_TILE_NAMES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } } diff --git a/Minecraft.World/Blocks/TallGrassPlantTile.h b/Minecraft.World/Blocks/TallGrassPlantTile.h index 786132a45..66988a862 100644 --- a/Minecraft.World/Blocks/TallGrassPlantTile.h +++ b/Minecraft.World/Blocks/TallGrassPlantTile.h @@ -3,41 +3,44 @@ #include "PlantTile.h" class ChunkRebuildData; -class TallGrass : public Bush -{ - friend class Tile; - friend ChunkRebuildData; +class TallGrass : public Bush { + friend class Tile; + friend ChunkRebuildData; + public: - static const int DEAD_SHRUB = 0; - static const int TALL_GRASS = 1; - static const int FERN = 2; + static const int DEAD_SHRUB = 0; + static const int TALL_GRASS = 1; + static const int FERN = 2; - static const int TALL_GRASS_TILE_NAMES_LENGTH = 3; + static const int TALL_GRASS_TILE_NAMES_LENGTH = 3; - static const unsigned int TALL_GRASS_TILE_NAMES[TALL_GRASS_TILE_NAMES_LENGTH]; + static const unsigned int + TALL_GRASS_TILE_NAMES[TALL_GRASS_TILE_NAMES_LENGTH]; private: - static const std::wstring TEXTURE_NAMES[]; - Icon **icons; + static const std::wstring TEXTURE_NAMES[]; + Icon** icons; protected: - TallGrass(int id); + TallGrass(int id); public: - virtual void updateDefaultShape(); // 4J Added override - virtual Icon *getTexture(int face, int data); + virtual void updateDefaultShape(); // 4J Added override + virtual Icon* getTexture(int face, int data); - virtual int getColor(int auxData); - virtual int getColor() const; + virtual int getColor(int auxData); + virtual int getColor() const; - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); - virtual int cloneTileData(Level *level, int x, int y, int z); - virtual unsigned int getDescriptionId(int iData = -1); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); + virtual int cloneTileData(Level* level, int x, int y, int z); + virtual unsigned int getDescriptionId(int iData = -1); - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/TheEndPortalFrameTile.cpp b/Minecraft.World/Blocks/TheEndPortalFrameTile.cpp index 49c036865..6197e9f69 100644 --- a/Minecraft.World/Blocks/TheEndPortalFrameTile.cpp +++ b/Minecraft.World/Blocks/TheEndPortalFrameTile.cpp @@ -6,78 +6,62 @@ const std::wstring TheEndPortalFrameTile::TEXTURE_EYE = L"endframe_eye"; -TheEndPortalFrameTile::TheEndPortalFrameTile(int id) : Tile(id, Material::glass, false ) -{ - iconTop = NULL; - iconEye = NULL; +TheEndPortalFrameTile::TheEndPortalFrameTile(int id) + : Tile(id, Material::glass, false) { + iconTop = NULL; + iconEye = NULL; } -Icon *TheEndPortalFrameTile::getTexture(int face, int data) -{ - if (face == Facing::UP) - { +Icon* TheEndPortalFrameTile::getTexture(int face, int data) { + if (face == Facing::UP) { return iconTop; } - if (face == Facing::DOWN) - { + if (face == Facing::DOWN) { return Tile::whiteStone->getTexture(face); } return icon; } -void TheEndPortalFrameTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"endframe_side"); - iconTop = iconRegister->registerIcon(L"endframe_top"); - iconEye = iconRegister->registerIcon(L"endframe_eye"); +void TheEndPortalFrameTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"endframe_side"); + iconTop = iconRegister->registerIcon(L"endframe_top"); + iconEye = iconRegister->registerIcon(L"endframe_eye"); } -Icon *TheEndPortalFrameTile::getEye() -{ - return iconEye; +Icon* TheEndPortalFrameTile::getEye() { return iconEye; } + +bool TheEndPortalFrameTile::isSolidRender(bool isServerLevel) { return false; } + +int TheEndPortalFrameTile::getRenderShape() { return SHAPE_PORTAL_FRAME; } + +void TheEndPortalFrameTile::updateDefaultShape() { + setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); } -bool TheEndPortalFrameTile::isSolidRender(bool isServerLevel) -{ - return false; -} - -int TheEndPortalFrameTile::getRenderShape() -{ - return SHAPE_PORTAL_FRAME; -} - -void TheEndPortalFrameTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); -} - -void TheEndPortalFrameTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ +void TheEndPortalFrameTile::addAABBs(Level* level, int x, int y, int z, + AABB* box, AABBList* boxes, + std::shared_ptr source) { setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); Tile::addAABBs(level, x, y, z, box, boxes, source); int data = level->getData(x, y, z); - if (hasEye(data)) - { - setShape(5.0f / 16.0f, 13.0f / 16.0f, 5.0f / 16.0f, 11.0f / 16.0f, 1, 11.0f / 16.0f); + if (hasEye(data)) { + setShape(5.0f / 16.0f, 13.0f / 16.0f, 5.0f / 16.0f, 11.0f / 16.0f, 1, + 11.0f / 16.0f); Tile::addAABBs(level, x, y, z, box, boxes, source); } updateDefaultShape(); } -bool TheEndPortalFrameTile::hasEye(int data) -{ - return (data & EYE_BIT) != 0; +bool TheEndPortalFrameTile::hasEye(int data) { return (data & EYE_BIT) != 0; } + +int TheEndPortalFrameTile::getResource(int data, Random* random, + int playerBonusLevel) { + return 0; } -int TheEndPortalFrameTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; -} - -void TheEndPortalFrameTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ +void TheEndPortalFrameTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { int dir = (((Mth::floor(by->yRot * 4 / (360) + 0.5)) & 3) + 2) % 4; level->setData(x, y, z, dir); } diff --git a/Minecraft.World/Blocks/TheEndPortalFrameTile.h b/Minecraft.World/Blocks/TheEndPortalFrameTile.h index ab3180ef3..688c083f0 100644 --- a/Minecraft.World/Blocks/TheEndPortalFrameTile.h +++ b/Minecraft.World/Blocks/TheEndPortalFrameTile.h @@ -1,26 +1,27 @@ #pragma once #include "Tile.h" -class TheEndPortalFrameTile : public Tile -{ +class TheEndPortalFrameTile : public Tile { public: - static const int EYE_BIT = 4; - static const std::wstring TEXTURE_EYE; + static const int EYE_BIT = 4; + static const std::wstring TEXTURE_EYE; private: - Icon *iconTop; - Icon *iconEye; + Icon* iconTop; + Icon* iconEye; public: TheEndPortalFrameTile(int id); - virtual Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); - Icon *getEye(); + virtual Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); + Icon* getEye(); virtual bool isSolidRender(bool isServerLevel = false); virtual int getRenderShape(); virtual void updateDefaultShape(); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); static bool hasEye(int data); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TheEndPortalTile.cpp b/Minecraft.World/Blocks/TheEndPortalTile.cpp index a2fbaf308..82d1db3b8 100644 --- a/Minecraft.World/Blocks/TheEndPortalTile.cpp +++ b/Minecraft.World/Blocks/TheEndPortalTile.cpp @@ -9,37 +9,29 @@ #include "../Headers/net.minecraft.world.h" #include -namespace -{ +namespace { #if defined(_WIN32) - inline void *TheEndPortalTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +inline void* TheEndPortalTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void TheEndPortalTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } -#else - pthread_key_t CreateTheEndPortalTlsKey() - { - pthread_key_t key; - pthread_key_create(&key, NULL); - return key; - } - - inline void *TheEndPortalTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void TheEndPortalTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } -#endif +inline void TheEndPortalTlsSetValue(DWORD key, void* value) { + TlsSetValue(key, value); } +#else +pthread_key_t CreateTheEndPortalTlsKey() { + pthread_key_t key; + pthread_key_create(&key, NULL); + return key; +} + +inline void* TheEndPortalTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} + +inline void TheEndPortalTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +#endif +} // namespace #if defined(_WIN32) DWORD TheEndPortal::tlsIdx = TlsAlloc(); @@ -47,75 +39,67 @@ DWORD TheEndPortal::tlsIdx = TlsAlloc(); pthread_key_t TheEndPortal::tlsIdx = CreateTheEndPortalTlsKey(); #endif -// 4J - allowAnywhere is a static in java, implementing as TLS here to make thread safe -bool TheEndPortal::allowAnywhere() -{ - return TheEndPortalTlsGetValue(tlsIdx) != NULL; +// 4J - allowAnywhere is a static in java, implementing as TLS here to make +// thread safe +bool TheEndPortal::allowAnywhere() { + return TheEndPortalTlsGetValue(tlsIdx) != NULL; } -void TheEndPortal::allowAnywhere(bool set) -{ - TheEndPortalTlsSetValue(tlsIdx, reinterpret_cast(static_cast(set ? 1 : 0))); +void TheEndPortal::allowAnywhere(bool set) { + TheEndPortalTlsSetValue( + tlsIdx, reinterpret_cast(static_cast(set ? 1 : 0))); } -TheEndPortal::TheEndPortal(int id, Material *material) : EntityTile(id, material, false) -{ +TheEndPortal::TheEndPortal(int id, Material* material) + : EntityTile(id, material, false) { this->setLightEmission(1.0f); } -std::shared_ptr TheEndPortal::newTileEntity(Level *level) -{ - return std::shared_ptr(new TheEndPortalTileEntity()); +std::shared_ptr TheEndPortal::newTileEntity(Level* level) { + return std::shared_ptr(new TheEndPortalTileEntity()); } -void TheEndPortal::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void TheEndPortal::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { float r = 1 / 16.0f; this->setShape(0, 0, 0, 1, r, 1); } -bool TheEndPortal::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ +bool TheEndPortal::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { if (face != 0) return false; return EntityTile::shouldRenderFace(level, x, y, z, face); } -void TheEndPortal::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ -} +void TheEndPortal::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) {} -bool TheEndPortal::isSolidRender(bool isServerLevel) -{ - return false; -} +bool TheEndPortal::isSolidRender(bool isServerLevel) { return false; } -bool TheEndPortal::isCubeShaped() -{ - return false; -} +bool TheEndPortal::isCubeShaped() { return false; } -int TheEndPortal::getResourceCount(Random *random) -{ - return 0; -} +int TheEndPortal::getResourceCount(Random* random) { return 0; } -void TheEndPortal::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (entity->riding == NULL && entity->rider.lock() == NULL) - { - if (std::dynamic_pointer_cast(entity) != NULL) - { - if (!level->isClientSide) - { - // 4J Stu - Update the level data position so that the stronghold portal can be shown on the maps - int x,z; - x = z = 0; - if(level->dimension == 0 && !level->getLevelData()->getHasStrongholdEndPortal() && app.GetTerrainFeaturePosition( eTerrainFeature_StrongholdEndPortal, &x, &z) ) - { - level->getLevelData()->setXStrongholdEndPortal(x); - level->getLevelData()->setZStrongholdEndPortal(z); - level->getLevelData()->setHasStrongholdEndPortal(); - } +void TheEndPortal::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (entity->riding == NULL && entity->rider.lock() == NULL) { + if (std::dynamic_pointer_cast(entity) != NULL) { + if (!level->isClientSide) { + // 4J Stu - Update the level data position so that the + // stronghold portal can be shown on the maps + int x, z; + x = z = 0; + if (level->dimension == 0 && + !level->getLevelData()->getHasStrongholdEndPortal() && + app.GetTerrainFeaturePosition( + eTerrainFeature_StrongholdEndPortal, &x, &z)) { + level->getLevelData()->setXStrongholdEndPortal(x); + level->getLevelData()->setZStrongholdEndPortal(z); + level->getLevelData()->setHasStrongholdEndPortal(); + } (std::dynamic_pointer_cast(entity))->changeDimension(1); } @@ -123,8 +107,8 @@ void TheEndPortal::entityInside(Level *level, int x, int y, int z, std::shared_p } } -void TheEndPortal::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ +void TheEndPortal::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { double x = xt + random->nextFloat(); double y = yt + 0.8f; double z = zt + random->nextFloat(); @@ -135,29 +119,20 @@ void TheEndPortal::animateTick(Level *level, int xt, int yt, int zt, Random *ran level->addParticle(eParticleType_endportal, x, y, z, xa, ya, za); } -int TheEndPortal::getRenderShape() -{ - return SHAPE_INVISIBLE; -} +int TheEndPortal::getRenderShape() { return SHAPE_INVISIBLE; } -void TheEndPortal::onPlace(Level *level, int x, int y, int z) -{ +void TheEndPortal::onPlace(Level* level, int x, int y, int z) { if (allowAnywhere()) return; - if (level->dimension->id != 0) - { + if (level->dimension->id != 0) { level->setTile(x, y, z, 0); return; } } -int TheEndPortal::cloneTileId(Level *level, int x, int y, int z) -{ - return 0; -} +int TheEndPortal::cloneTileId(Level* level, int x, int y, int z) { return 0; } -void TheEndPortal::registerIcons(IconRegister *iconRegister) -{ - // don't register null, because of particles - icon = iconRegister->registerIcon(L"portal"); +void TheEndPortal::registerIcons(IconRegister* iconRegister) { + // don't register null, because of particles + icon = iconRegister->registerIcon(L"portal"); } diff --git a/Minecraft.World/Blocks/TheEndPortalTile.h b/Minecraft.World/Blocks/TheEndPortalTile.h index 130a4232b..81b53becc 100644 --- a/Minecraft.World/Blocks/TheEndPortalTile.h +++ b/Minecraft.World/Blocks/TheEndPortalTile.h @@ -5,31 +5,37 @@ #include #endif -class TheEndPortal : public EntityTile -{ +class TheEndPortal : public EntityTile { public: #if defined(_WIN32) - static DWORD tlsIdx; + static DWORD tlsIdx; #else - static pthread_key_t tlsIdx; + static pthread_key_t tlsIdx; #endif - // 4J - was just a static but implemented with TLS for our version - static bool allowAnywhere(); - static void allowAnywhere(bool set); + // 4J - was just a static but implemented with TLS for our version + static bool allowAnywhere(); + static void allowAnywhere(bool set); - TheEndPortal(int id, Material *material); + TheEndPortal(int id, Material* material); - virtual std::shared_ptr newTileEntity(Level *level); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); + virtual std::shared_ptr newTileEntity(Level* level); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual int getResourceCount(Random *random); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); + virtual int getResourceCount(Random* random); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); virtual int getRenderShape(); - virtual void onPlace(Level *level, int x, int y, int z); - virtual int cloneTileId(Level *level, int x, int y, int z); - void registerIcons(IconRegister *iconRegister); + virtual void onPlace(Level* level, int x, int y, int z); + virtual int cloneTileId(Level* level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/ThinFenceTile.cpp b/Minecraft.World/Blocks/ThinFenceTile.cpp index 4ca3dbb78..17653166c 100644 --- a/Minecraft.World/Blocks/ThinFenceTile.cpp +++ b/Minecraft.World/Blocks/ThinFenceTile.cpp @@ -3,90 +3,71 @@ #include "../Headers/net.minecraft.world.level.h" #include "../Headers/net.minecraft.world.h" -ThinFenceTile::ThinFenceTile(int id, const std::wstring &tex, const std::wstring &edgeTex, Material *material, bool dropsResources) : Tile(id, material, false) -{ - iconSide = NULL; - edgeTexture = edgeTex; - this->dropsResources = dropsResources; - this->texture = tex; +ThinFenceTile::ThinFenceTile(int id, const std::wstring& tex, + const std::wstring& edgeTex, Material* material, + bool dropsResources) + : Tile(id, material, false) { + iconSide = NULL; + edgeTexture = edgeTex; + this->dropsResources = dropsResources; + this->texture = tex; } -int ThinFenceTile::getResource(int data, Random *random, int playerBonusLevel) -{ - if (!dropsResources) - { +int ThinFenceTile::getResource(int data, Random* random, int playerBonusLevel) { + if (!dropsResources) { return 0; } return Tile::getResource(data, random, playerBonusLevel); } -bool ThinFenceTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool ThinFenceTile::isSolidRender(bool isServerLevel) { return false; } -bool ThinFenceTile::isCubeShaped() -{ - return false; -} +bool ThinFenceTile::isCubeShaped() { return false; } -int ThinFenceTile::getRenderShape() -{ - return Tile::SHAPE_IRON_FENCE; -} +int ThinFenceTile::getRenderShape() { return Tile::SHAPE_IRON_FENCE; } -bool ThinFenceTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ +bool ThinFenceTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { int id = level->getTile(x, y, z); if (id == this->id) return false; return Tile::shouldRenderFace(level, x, y, z, face); } -void ThinFenceTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ +void ThinFenceTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { bool n = attachsTo(level->getTile(x, y, z - 1)); bool s = attachsTo(level->getTile(x, y, z + 1)); bool w = attachsTo(level->getTile(x - 1, y, z)); bool e = attachsTo(level->getTile(x + 1, y, z)); - if ((w && e) || (!w && !e && !n && !s)) - { + if ((w && e) || (!w && !e && !n && !s)) { setShape(0, 0, 7.0f / 16.0f, 1, 1, 9.0f / 16.0f); Tile::addAABBs(level, x, y, z, box, boxes, source); - } - else if (w && !e) - { + } else if (w && !e) { setShape(0, 0, 7.0f / 16.0f, .5f, 1, 9.0f / 16.0f); Tile::addAABBs(level, x, y, z, box, boxes, source); - } - else if (!w && e) - { + } else if (!w && e) { setShape(.5f, 0, 7.0f / 16.0f, 1, 1, 9.0f / 16.0f); Tile::addAABBs(level, x, y, z, box, boxes, source); } - if ((n && s) || (!w && !e && !n && !s)) - { + if ((n && s) || (!w && !e && !n && !s)) { setShape(7.0f / 16.0f, 0, 0, 9.0f / 16.0f, 1, 1); Tile::addAABBs(level, x, y, z, box, boxes, source); - } - else if (n && !s) - { + } else if (n && !s) { setShape(7.0f / 16.0f, 0, 0, 9.0f / 16.0f, 1, .5f); Tile::addAABBs(level, x, y, z, box, boxes, source); - } - else if (!n && s) - { + } else if (!n && s) { setShape(7.0f / 16.0f, 0, .5f, 9.0f / 16.0f, 1, 1); Tile::addAABBs(level, x, y, z, box, boxes, source); } } -void ThinFenceTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 1, 1); -} +void ThinFenceTile::updateDefaultShape() { setShape(0, 0, 0, 1, 1, 1); } -void ThinFenceTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void ThinFenceTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { float minX = 7.0f / 16.0f; float maxX = 9.0f / 16.0f; @@ -98,57 +79,39 @@ void ThinFenceTile::updateShape(LevelSource *level, int x, int y, int z, int for bool w = attachsTo(level->getTile(x - 1, y, z)); bool e = attachsTo(level->getTile(x + 1, y, z)); - if ((w && e) || (!w && !e && !n && !s)) - { + if ((w && e) || (!w && !e && !n && !s)) { minX = 0; maxX = 1; - } - else if (w && !e) - { + } else if (w && !e) { minX = 0; - } - else if (!w && e) - { + } else if (!w && e) { maxX = 1; } - if ((n && s) || (!w && !e && !n && !s)) - { + if ((n && s) || (!w && !e && !n && !s)) { minZ = 0; maxZ = 1; - } - else if (n && !s) - { + } else if (n && !s) { minZ = 0; - } - else if (!n && s) - { + } else if (!n && s) { maxZ = 1; } - setShape(minX, 0, minZ, maxX, 1, maxZ); + setShape(minX, 0, minZ, maxX, 1, maxZ); } -Icon *ThinFenceTile::getEdgeTexture() -{ - return iconSide; +Icon* ThinFenceTile::getEdgeTexture() { return iconSide; } + +bool ThinFenceTile::attachsTo(int tile) { + return Tile::solid[tile] || tile == id || tile == Tile::glass_Id; } -bool ThinFenceTile::attachsTo(int tile) -{ - return Tile::solid[tile] || tile == id || tile == Tile::glass_Id; +bool ThinFenceTile::isSilkTouchable() { return true; } + +std::shared_ptr ThinFenceTile::getSilkTouchItemInstance( + int data) { + return std::shared_ptr(new ItemInstance(id, 1, data)); } -bool ThinFenceTile::isSilkTouchable() -{ - return true; -} - -std::shared_ptr ThinFenceTile::getSilkTouchItemInstance(int data) -{ - return std::shared_ptr(new ItemInstance(id, 1, data)); -} - -void ThinFenceTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(texture); - iconSide = iconRegister->registerIcon(edgeTexture); +void ThinFenceTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(texture); + iconSide = iconRegister->registerIcon(edgeTexture); } diff --git a/Minecraft.World/Blocks/ThinFenceTile.h b/Minecraft.World/Blocks/ThinFenceTile.h index 7c39cabff..ff0bc2ccf 100644 --- a/Minecraft.World/Blocks/ThinFenceTile.h +++ b/Minecraft.World/Blocks/ThinFenceTile.h @@ -2,31 +2,36 @@ #include "Tile.h" #include "../Util/Definitions.h" -class ThinFenceTile : public Tile -{ +class ThinFenceTile : public Tile { private: - std::wstring edgeTexture; - bool dropsResources; - std::wstring texture; - Icon *iconSide; + std::wstring edgeTexture; + bool dropsResources; + std::wstring texture; + Icon* iconSide; public: - ThinFenceTile(int id, const std::wstring &tex, const std::wstring &edgeTex, Material *material, bool dropsResources); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual bool isSolidRender(bool isServerLevel = false); + ThinFenceTile(int id, const std::wstring& tex, const std::wstring& edgeTex, + Material* material, bool dropsResources); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); virtual void updateDefaultShape(); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual Icon *getEdgeTexture(); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual Icon* getEdgeTexture(); bool attachsTo(int tile); protected: - bool isSilkTouchable(); - std::shared_ptr getSilkTouchItemInstance(int data); + bool isSilkTouchable(); + std::shared_ptr getSilkTouchItemInstance(int data); public: - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Blocks/Tile.cpp b/Minecraft.World/Blocks/Tile.cpp index 209b76272..a58ee4217 100644 --- a/Minecraft.World/Blocks/Tile.cpp +++ b/Minecraft.World/Blocks/Tile.cpp @@ -16,223 +16,215 @@ #include "../Headers/net.minecraft.h" #include "Tile.h" -namespace -{ +namespace { #if defined(_WIN32) - inline void *TileTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +inline void* TileTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void TileTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } +inline void TileTlsSetValue(DWORD key, void* value) { TlsSetValue(key, value); } #else - pthread_key_t CreateTileTlsKey() - { - pthread_key_t key; - const int result = pthread_key_create(&key, nullptr); - assert(result == 0); - return key; - } - - inline void *TileTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void TileTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } -#endif +pthread_key_t CreateTileTlsKey() { + pthread_key_t key; + const int result = pthread_key_create(&key, nullptr); + assert(result == 0); + return key; } -std::wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; +inline void* TileTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} + +inline void TileTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +#endif +} // namespace + +std::wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; const float Tile::INDESTRUCTIBLE_DESTROY_TIME = -1.0f; -Tile::SoundType *Tile::SOUND_NORMAL = NULL; -Tile::SoundType *Tile::SOUND_WOOD = NULL; -Tile::SoundType *Tile::SOUND_GRAVEL = NULL; -Tile::SoundType *Tile::SOUND_GRASS = NULL; -Tile::SoundType *Tile::SOUND_STONE = NULL; -Tile::SoundType *Tile::SOUND_METAL = NULL; -Tile::SoundType *Tile::SOUND_GLASS = NULL; -Tile::SoundType *Tile::SOUND_CLOTH = NULL; -Tile::SoundType *Tile::SOUND_SAND = NULL; -Tile::SoundType *Tile::SOUND_SNOW = NULL; -Tile::SoundType *Tile::SOUND_LADDER = NULL; -Tile::SoundType *Tile::SOUND_ANVIL = NULL; +Tile::SoundType* Tile::SOUND_NORMAL = NULL; +Tile::SoundType* Tile::SOUND_WOOD = NULL; +Tile::SoundType* Tile::SOUND_GRAVEL = NULL; +Tile::SoundType* Tile::SOUND_GRASS = NULL; +Tile::SoundType* Tile::SOUND_STONE = NULL; +Tile::SoundType* Tile::SOUND_METAL = NULL; +Tile::SoundType* Tile::SOUND_GLASS = NULL; +Tile::SoundType* Tile::SOUND_CLOTH = NULL; +Tile::SoundType* Tile::SOUND_SAND = NULL; +Tile::SoundType* Tile::SOUND_SNOW = NULL; +Tile::SoundType* Tile::SOUND_LADDER = NULL; +Tile::SoundType* Tile::SOUND_ANVIL = NULL; bool Tile::solid[TILE_NUM_COUNT]; int Tile::lightBlock[TILE_NUM_COUNT]; bool Tile::transculent[TILE_NUM_COUNT]; int Tile::lightEmission[TILE_NUM_COUNT]; -unsigned char Tile::_sendTileData[TILE_NUM_COUNT]; // 4J changed - was bool, now bitfield to indicate which bits are important to be sent +unsigned char + Tile::_sendTileData[TILE_NUM_COUNT]; // 4J changed - was bool, now bitfield + // to indicate which bits are + // important to be sent bool Tile::mipmapEnable[TILE_NUM_COUNT]; bool Tile::propagate[TILE_NUM_COUNT]; -Tile **Tile::tiles = NULL; +Tile** Tile::tiles = NULL; -Tile *Tile::rock = NULL; -GrassTile *Tile::grass = NULL; -Tile *Tile::dirt = NULL; -Tile *Tile::stoneBrick = NULL; -Tile *Tile::wood = NULL; -Tile *Tile::sapling = NULL; -Tile *Tile::unbreakable = NULL; -LiquidTile *Tile::water = NULL; -Tile *Tile::calmWater = NULL; -LiquidTile *Tile::lava = NULL; -Tile *Tile::calmLava = NULL; -Tile *Tile::sand = NULL; -Tile *Tile::gravel = NULL; -Tile *Tile::goldOre = NULL; -Tile *Tile::ironOre = NULL; -Tile *Tile::coalOre = NULL; -Tile *Tile::treeTrunk = NULL; -LeafTile *Tile::leaves = NULL; -Tile *Tile::sponge = NULL; -Tile *Tile::glass = NULL; -Tile *Tile::lapisOre = NULL; -Tile *Tile::lapisBlock = NULL; -Tile *Tile::dispenser = NULL; -Tile *Tile::sandStone = NULL; -Tile *Tile::musicBlock = NULL; -Tile *Tile::bed = NULL; -Tile *Tile::goldenRail = NULL; -Tile *Tile::detectorRail = NULL; -PistonBaseTile *Tile::pistonStickyBase = NULL; -Tile *Tile::web = NULL; -TallGrass *Tile::tallgrass = NULL; -DeadBushTile *Tile::deadBush = NULL; -PistonBaseTile *Tile::pistonBase = NULL; -PistonExtensionTile *Tile::pistonExtension = NULL; -Tile *Tile::cloth = NULL; -PistonMovingPiece *Tile::pistonMovingPiece = NULL; -Bush *Tile::flower = NULL; -Bush *Tile::rose = NULL; -Bush *Tile::mushroom1 = NULL; -Bush *Tile::mushroom2 = NULL; -Tile *Tile::goldBlock = NULL; -Tile *Tile::ironBlock = NULL; -HalfSlabTile *Tile::stoneSlab = NULL; -HalfSlabTile *Tile::stoneSlabHalf = NULL; -Tile *Tile::redBrick = NULL; -Tile *Tile::tnt = NULL; -Tile *Tile::bookshelf = NULL; -Tile *Tile::mossStone = NULL; -Tile *Tile::obsidian = NULL; -Tile *Tile::torch = NULL; -FireTile *Tile::fire = NULL; -Tile *Tile::mobSpawner = NULL; -Tile *Tile::stairs_wood = NULL; -ChestTile *Tile::chest = NULL; -RedStoneDustTile *Tile::redStoneDust = NULL; -Tile *Tile::diamondOre = NULL; -Tile *Tile::diamondBlock = NULL; -Tile *Tile::workBench = NULL; -Tile *Tile::crops = NULL; -Tile *Tile::farmland = NULL; -Tile *Tile::furnace = NULL; -Tile *Tile::furnace_lit = NULL; -Tile *Tile::sign = NULL; -Tile *Tile::door_wood = NULL; -Tile *Tile::ladder = NULL; -Tile *Tile::rail = NULL; -Tile *Tile::stairs_stone = NULL; -Tile *Tile::wallSign = NULL; -Tile *Tile::lever = NULL; -Tile *Tile::pressurePlate_stone = NULL; -Tile *Tile::door_iron = NULL; -Tile *Tile::pressurePlate_wood = NULL; -Tile *Tile::redStoneOre = NULL; -Tile *Tile::redStoneOre_lit = NULL; -Tile *Tile::notGate_off = NULL; -Tile *Tile::notGate_on = NULL; -Tile *Tile::button = NULL; -Tile *Tile::topSnow = NULL; -Tile *Tile::ice = NULL; -Tile *Tile::snow = NULL; -Tile *Tile::cactus = NULL; -Tile *Tile::clay = NULL; -Tile *Tile::reeds = NULL; -Tile *Tile::recordPlayer = NULL; -Tile *Tile::fence = NULL; -Tile *Tile::pumpkin = NULL; -Tile *Tile::hellRock = NULL; -Tile *Tile::hellSand = NULL; -Tile *Tile::lightGem = NULL; -PortalTile *Tile::portalTile = NULL; -Tile *Tile::litPumpkin = NULL; -Tile *Tile::cake = NULL; -RepeaterTile *Tile::diode_off = NULL; -RepeaterTile *Tile::diode_on = NULL; -Tile *Tile::aprilFoolsJoke = NULL; -Tile *Tile::trapdoor = NULL; +Tile* Tile::rock = NULL; +GrassTile* Tile::grass = NULL; +Tile* Tile::dirt = NULL; +Tile* Tile::stoneBrick = NULL; +Tile* Tile::wood = NULL; +Tile* Tile::sapling = NULL; +Tile* Tile::unbreakable = NULL; +LiquidTile* Tile::water = NULL; +Tile* Tile::calmWater = NULL; +LiquidTile* Tile::lava = NULL; +Tile* Tile::calmLava = NULL; +Tile* Tile::sand = NULL; +Tile* Tile::gravel = NULL; +Tile* Tile::goldOre = NULL; +Tile* Tile::ironOre = NULL; +Tile* Tile::coalOre = NULL; +Tile* Tile::treeTrunk = NULL; +LeafTile* Tile::leaves = NULL; +Tile* Tile::sponge = NULL; +Tile* Tile::glass = NULL; +Tile* Tile::lapisOre = NULL; +Tile* Tile::lapisBlock = NULL; +Tile* Tile::dispenser = NULL; +Tile* Tile::sandStone = NULL; +Tile* Tile::musicBlock = NULL; +Tile* Tile::bed = NULL; +Tile* Tile::goldenRail = NULL; +Tile* Tile::detectorRail = NULL; +PistonBaseTile* Tile::pistonStickyBase = NULL; +Tile* Tile::web = NULL; +TallGrass* Tile::tallgrass = NULL; +DeadBushTile* Tile::deadBush = NULL; +PistonBaseTile* Tile::pistonBase = NULL; +PistonExtensionTile* Tile::pistonExtension = NULL; +Tile* Tile::cloth = NULL; +PistonMovingPiece* Tile::pistonMovingPiece = NULL; +Bush* Tile::flower = NULL; +Bush* Tile::rose = NULL; +Bush* Tile::mushroom1 = NULL; +Bush* Tile::mushroom2 = NULL; +Tile* Tile::goldBlock = NULL; +Tile* Tile::ironBlock = NULL; +HalfSlabTile* Tile::stoneSlab = NULL; +HalfSlabTile* Tile::stoneSlabHalf = NULL; +Tile* Tile::redBrick = NULL; +Tile* Tile::tnt = NULL; +Tile* Tile::bookshelf = NULL; +Tile* Tile::mossStone = NULL; +Tile* Tile::obsidian = NULL; +Tile* Tile::torch = NULL; +FireTile* Tile::fire = NULL; +Tile* Tile::mobSpawner = NULL; +Tile* Tile::stairs_wood = NULL; +ChestTile* Tile::chest = NULL; +RedStoneDustTile* Tile::redStoneDust = NULL; +Tile* Tile::diamondOre = NULL; +Tile* Tile::diamondBlock = NULL; +Tile* Tile::workBench = NULL; +Tile* Tile::crops = NULL; +Tile* Tile::farmland = NULL; +Tile* Tile::furnace = NULL; +Tile* Tile::furnace_lit = NULL; +Tile* Tile::sign = NULL; +Tile* Tile::door_wood = NULL; +Tile* Tile::ladder = NULL; +Tile* Tile::rail = NULL; +Tile* Tile::stairs_stone = NULL; +Tile* Tile::wallSign = NULL; +Tile* Tile::lever = NULL; +Tile* Tile::pressurePlate_stone = NULL; +Tile* Tile::door_iron = NULL; +Tile* Tile::pressurePlate_wood = NULL; +Tile* Tile::redStoneOre = NULL; +Tile* Tile::redStoneOre_lit = NULL; +Tile* Tile::notGate_off = NULL; +Tile* Tile::notGate_on = NULL; +Tile* Tile::button = NULL; +Tile* Tile::topSnow = NULL; +Tile* Tile::ice = NULL; +Tile* Tile::snow = NULL; +Tile* Tile::cactus = NULL; +Tile* Tile::clay = NULL; +Tile* Tile::reeds = NULL; +Tile* Tile::recordPlayer = NULL; +Tile* Tile::fence = NULL; +Tile* Tile::pumpkin = NULL; +Tile* Tile::hellRock = NULL; +Tile* Tile::hellSand = NULL; +Tile* Tile::lightGem = NULL; +PortalTile* Tile::portalTile = NULL; +Tile* Tile::litPumpkin = NULL; +Tile* Tile::cake = NULL; +RepeaterTile* Tile::diode_off = NULL; +RepeaterTile* Tile::diode_on = NULL; +Tile* Tile::aprilFoolsJoke = NULL; +Tile* Tile::trapdoor = NULL; -Tile *Tile::monsterStoneEgg = NULL; -Tile *Tile::stoneBrickSmooth = NULL; -Tile *Tile::hugeMushroom1 = NULL; -Tile *Tile::hugeMushroom2 = NULL; -Tile *Tile::ironFence = NULL; -Tile *Tile::thinGlass = NULL; -Tile *Tile::melon = NULL; -Tile *Tile::pumpkinStem = NULL; -Tile *Tile::melonStem = NULL; -Tile *Tile::vine = NULL; -Tile *Tile::fenceGate = NULL; -Tile *Tile::stairs_bricks = NULL; -Tile *Tile::stairs_stoneBrickSmooth = NULL; +Tile* Tile::monsterStoneEgg = NULL; +Tile* Tile::stoneBrickSmooth = NULL; +Tile* Tile::hugeMushroom1 = NULL; +Tile* Tile::hugeMushroom2 = NULL; +Tile* Tile::ironFence = NULL; +Tile* Tile::thinGlass = NULL; +Tile* Tile::melon = NULL; +Tile* Tile::pumpkinStem = NULL; +Tile* Tile::melonStem = NULL; +Tile* Tile::vine = NULL; +Tile* Tile::fenceGate = NULL; +Tile* Tile::stairs_bricks = NULL; +Tile* Tile::stairs_stoneBrickSmooth = NULL; -MycelTile *Tile::mycel = NULL; -Tile *Tile::waterLily = NULL; -Tile *Tile::netherBrick = NULL; -Tile *Tile::netherFence = NULL; -Tile *Tile::stairs_netherBricks = NULL; -Tile *Tile::netherStalk = NULL; -Tile *Tile::enchantTable = NULL; -Tile *Tile::brewingStand = NULL; -CauldronTile *Tile::cauldron = NULL; -Tile *Tile::endPortalTile = NULL; -Tile *Tile::endPortalFrameTile = NULL; -Tile *Tile::whiteStone = NULL; -Tile *Tile::dragonEgg = NULL; -Tile *Tile::redstoneLight = NULL; -Tile *Tile::redstoneLight_lit = NULL; +MycelTile* Tile::mycel = NULL; +Tile* Tile::waterLily = NULL; +Tile* Tile::netherBrick = NULL; +Tile* Tile::netherFence = NULL; +Tile* Tile::stairs_netherBricks = NULL; +Tile* Tile::netherStalk = NULL; +Tile* Tile::enchantTable = NULL; +Tile* Tile::brewingStand = NULL; +CauldronTile* Tile::cauldron = NULL; +Tile* Tile::endPortalTile = NULL; +Tile* Tile::endPortalFrameTile = NULL; +Tile* Tile::whiteStone = NULL; +Tile* Tile::dragonEgg = NULL; +Tile* Tile::redstoneLight = NULL; +Tile* Tile::redstoneLight_lit = NULL; // TU9 -Tile *Tile::stairs_sandstone = NULL; -Tile *Tile::woodStairsDark = NULL; -Tile *Tile::woodStairsBirch = NULL; -Tile *Tile::woodStairsJungle = NULL; +Tile* Tile::stairs_sandstone = NULL; +Tile* Tile::woodStairsDark = NULL; +Tile* Tile::woodStairsBirch = NULL; +Tile* Tile::woodStairsJungle = NULL; -Tile *Tile::button_wood = NULL; -HalfSlabTile *Tile::woodSlab = NULL; -HalfSlabTile *Tile::woodSlabHalf = NULL; +Tile* Tile::button_wood = NULL; +HalfSlabTile* Tile::woodSlab = NULL; +HalfSlabTile* Tile::woodSlabHalf = NULL; -Tile *Tile::emeraldOre = NULL; -Tile *Tile::enderChest = NULL; -TripWireSourceTile *Tile::tripWireSource = NULL; -Tile *Tile::tripWire = NULL; -Tile *Tile::emeraldBlock = NULL; - +Tile* Tile::emeraldOre = NULL; +Tile* Tile::enderChest = NULL; +TripWireSourceTile* Tile::tripWireSource = NULL; +Tile* Tile::tripWire = NULL; +Tile* Tile::emeraldBlock = NULL; -Tile *Tile::cocoa = NULL; -Tile *Tile::skull = NULL; +Tile* Tile::cocoa = NULL; +Tile* Tile::skull = NULL; -Tile *Tile::cobbleWall = NULL; -Tile *Tile::flowerPot = NULL; -Tile *Tile::carrots = NULL; -Tile *Tile::potatoes = NULL; -Tile *Tile::anvil = NULL; -Tile *Tile::netherQuartz = NULL; -Tile *Tile::quartzBlock = NULL; -Tile *Tile::stairs_quartz = NULL; +Tile* Tile::cobbleWall = NULL; +Tile* Tile::flowerPot = NULL; +Tile* Tile::carrots = NULL; +Tile* Tile::potatoes = NULL; +Tile* Tile::anvil = NULL; +Tile* Tile::netherQuartz = NULL; +Tile* Tile::quartzBlock = NULL; +Tile* Tile::stairs_quartz = NULL; -Tile *Tile::woolCarpet = NULL; +Tile* Tile::woolCarpet = NULL; #if defined(_WIN32) DWORD Tile::tlsIdxShape = TlsAlloc(); @@ -240,1285 +232,2214 @@ DWORD Tile::tlsIdxShape = TlsAlloc(); pthread_key_t Tile::tlsIdxShape = CreateTileTlsKey(); #endif -Tile::ThreadStorage::ThreadStorage() -{ - xx0 = yy0 = zz0 = xx1 = yy1 = zz1 = 0.0; - tileId = 0; +Tile::ThreadStorage::ThreadStorage() { + xx0 = yy0 = zz0 = xx1 = yy1 = zz1 = 0.0; + tileId = 0; } -void Tile::CreateNewThreadStorage() -{ - ThreadStorage *tls = new ThreadStorage(); - TileTlsSetValue(Tile::tlsIdxShape, tls); +void Tile::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + TileTlsSetValue(Tile::tlsIdxShape, tls); } -void Tile::ReleaseThreadStorage() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - delete tls; +void Tile::ReleaseThreadStorage() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + delete tls; } -void Tile::staticCtor() -{ - Tile::SOUND_NORMAL = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1); - Tile::SOUND_WOOD = new Tile::SoundType(eMaterialSoundType_WOOD, 1, 1); - Tile::SOUND_GRAVEL = new Tile::SoundType(eMaterialSoundType_GRAVEL, 1, 1); - Tile::SOUND_GRASS = new Tile::SoundType(eMaterialSoundType_GRASS, 1, 1); - Tile::SOUND_STONE = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1); - Tile::SOUND_METAL = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1.5f); - Tile::SOUND_GLASS = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1, eSoundType_RANDOM_GLASS,eSoundType_STEP_STONE); - Tile::SOUND_CLOTH = new Tile::SoundType(eMaterialSoundType_CLOTH, 1, 1); - Tile::SOUND_SAND = new Tile::SoundType(eMaterialSoundType_SAND, 1, 1); - Tile::SOUND_SNOW = new Tile::SoundType(eMaterialSoundType_SNOW, 1, 1); - Tile::SOUND_LADDER = new Tile::SoundType(eMaterialSoundType_LADDER, 1, 1,eSoundType_DIG_WOOD); - Tile::SOUND_ANVIL = new Tile::SoundType(eMaterialSoundType_ANVIL, 0.3f, 1, eSoundType_DIG_STONE, eSoundType_RANDOM_ANVIL_LAND); +void Tile::staticCtor() { + Tile::SOUND_NORMAL = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1); + Tile::SOUND_WOOD = new Tile::SoundType(eMaterialSoundType_WOOD, 1, 1); + Tile::SOUND_GRAVEL = new Tile::SoundType(eMaterialSoundType_GRAVEL, 1, 1); + Tile::SOUND_GRASS = new Tile::SoundType(eMaterialSoundType_GRASS, 1, 1); + Tile::SOUND_STONE = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1); + Tile::SOUND_METAL = new Tile::SoundType(eMaterialSoundType_STONE, 1, 1.5f); + Tile::SOUND_GLASS = + new Tile::SoundType(eMaterialSoundType_STONE, 1, 1, + eSoundType_RANDOM_GLASS, eSoundType_STEP_STONE); + Tile::SOUND_CLOTH = new Tile::SoundType(eMaterialSoundType_CLOTH, 1, 1); + Tile::SOUND_SAND = new Tile::SoundType(eMaterialSoundType_SAND, 1, 1); + Tile::SOUND_SNOW = new Tile::SoundType(eMaterialSoundType_SNOW, 1, 1); + Tile::SOUND_LADDER = new Tile::SoundType(eMaterialSoundType_LADDER, 1, 1, + eSoundType_DIG_WOOD); + Tile::SOUND_ANVIL = + new Tile::SoundType(eMaterialSoundType_ANVIL, 0.3f, 1, + eSoundType_DIG_STONE, eSoundType_RANDOM_ANVIL_LAND); - Tile::tiles = new Tile *[TILE_NUM_COUNT]; - memset( tiles, 0, sizeof( Tile *)*TILE_NUM_COUNT ); + Tile::tiles = new Tile*[TILE_NUM_COUNT]; + memset(tiles, 0, sizeof(Tile*) * TILE_NUM_COUNT); - Tile::rail = (new RailTile(66, false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_rail, Item::eMaterial_iron)->setDestroyTime(0.7f)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"rail")->setDescriptionId(IDS_TILE_RAIL)->sendTileData()->setUseDescriptionId(IDS_DESC_RAIL)->disableMipmap(); - Tile::goldenRail = (new RailTile(27, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_rail, Item::eMaterial_gold)->setDestroyTime(0.7f)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"goldenRail")->setDescriptionId(IDS_TILE_GOLDEN_RAIL)->sendTileData()->setUseDescriptionId(IDS_DESC_POWEREDRAIL)->disableMipmap(); - Tile::detectorRail = (new DetectorRailTile(28)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_rail, Item::eMaterial_detector)->setDestroyTime(0.7f)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"detectorRail")->setDescriptionId(IDS_TILE_DETECTOR_RAIL)->sendTileData()->setUseDescriptionId(IDS_DESC_DETECTORRAIL)->disableMipmap(); + Tile::rail = (new RailTile(66, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_rail, + Item::eMaterial_iron) + ->setDestroyTime(0.7f) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"rail") + ->setDescriptionId(IDS_TILE_RAIL) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_RAIL) + ->disableMipmap(); + Tile::goldenRail = (new RailTile(27, true)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_rail, Item::eMaterial_gold) + ->setDestroyTime(0.7f) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"goldenRail") + ->setDescriptionId(IDS_TILE_GOLDEN_RAIL) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_POWEREDRAIL) + ->disableMipmap(); + Tile::detectorRail = + (new DetectorRailTile(28)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_rail, + Item::eMaterial_detector) + ->setDestroyTime(0.7f) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"detectorRail") + ->setDescriptionId(IDS_TILE_DETECTOR_RAIL) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_DETECTORRAIL) + ->disableMipmap(); - Tile::goldBlock = (new MetalTile(41)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_gold)->setDestroyTime(3.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"blockGold")->setDescriptionId(IDS_TILE_BLOCK_GOLD)->setUseDescriptionId(IDS_DESC_BLOCK_GOLD); - Tile::ironBlock = (new MetalTile(42)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_iron)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"blockIron")->setDescriptionId(IDS_TILE_BLOCK_IRON)->setUseDescriptionId(IDS_DESC_BLOCK_IRON); - Tile::lapisBlock = (new Tile(22, Material::stone)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_lapis)->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"blockLapis")->setDescriptionId(IDS_TILE_BLOCK_LAPIS)->setUseDescriptionId(IDS_DESC_BLOCK_LAPIS); - Tile::musicBlock = (new MusicTile(25)) ->setDestroyTime(0.8f)->setTextureName(L"musicBlock")->setDescriptionId(IDS_TILE_MUSIC_BLOCK)->sendTileData()->setUseDescriptionId(IDS_DESC_NOTEBLOCK); - Tile::diamondBlock = (new MetalTile(57)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_diamond)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"blockDiamond")->setDescriptionId(IDS_TILE_BLOCK_DIAMOND)->setUseDescriptionId(IDS_DESC_BLOCK_DIAMOND); + Tile::goldBlock = (new MetalTile(41)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_block, Item::eMaterial_gold) + ->setDestroyTime(3.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"blockGold") + ->setDescriptionId(IDS_TILE_BLOCK_GOLD) + ->setUseDescriptionId(IDS_DESC_BLOCK_GOLD); + Tile::ironBlock = (new MetalTile(42)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_block, Item::eMaterial_iron) + ->setDestroyTime(5.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"blockIron") + ->setDescriptionId(IDS_TILE_BLOCK_IRON) + ->setUseDescriptionId(IDS_DESC_BLOCK_IRON); + Tile::lapisBlock = (new Tile(22, Material::stone)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_block, Item::eMaterial_lapis) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"blockLapis") + ->setDescriptionId(IDS_TILE_BLOCK_LAPIS) + ->setUseDescriptionId(IDS_DESC_BLOCK_LAPIS); + Tile::musicBlock = (new MusicTile(25)) + ->setDestroyTime(0.8f) + ->setTextureName(L"musicBlock") + ->setDescriptionId(IDS_TILE_MUSIC_BLOCK) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_NOTEBLOCK); + Tile::diamondBlock = + (new MetalTile(57)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, + Item::eMaterial_diamond) + ->setDestroyTime(5.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"blockDiamond") + ->setDescriptionId(IDS_TILE_BLOCK_DIAMOND) + ->setUseDescriptionId(IDS_DESC_BLOCK_DIAMOND); - Tile::goldOre = (new OreTile(14)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreGold")->setDescriptionId(IDS_TILE_ORE_GOLD)->setUseDescriptionId(IDS_DESC_ORE_GOLD); - Tile::ironOre = (new OreTile(15)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreIron")->setDescriptionId(IDS_TILE_ORE_IRON)->setUseDescriptionId(IDS_DESC_ORE_IRON); - Tile::coalOre = (new OreTile(16)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreCoal")->setDescriptionId(IDS_TILE_ORE_COAL)->setUseDescriptionId(IDS_DESC_ORE_COAL); - Tile::lapisOre = (new OreTile(21)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreLapis")->setDescriptionId(IDS_TILE_ORE_LAPIS)->setUseDescriptionId(IDS_DESC_ORE_LAPIS); - Tile::diamondOre = (new OreTile(56)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreDiamond")->setDescriptionId(IDS_TILE_ORE_DIAMOND)->setUseDescriptionId(IDS_DESC_ORE_DIAMOND); + Tile::goldOre = (new OreTile(14)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreGold") + ->setDescriptionId(IDS_TILE_ORE_GOLD) + ->setUseDescriptionId(IDS_DESC_ORE_GOLD); + Tile::ironOre = (new OreTile(15)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreIron") + ->setDescriptionId(IDS_TILE_ORE_IRON) + ->setUseDescriptionId(IDS_DESC_ORE_IRON); + Tile::coalOre = (new OreTile(16)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreCoal") + ->setDescriptionId(IDS_TILE_ORE_COAL) + ->setUseDescriptionId(IDS_DESC_ORE_COAL); + Tile::lapisOre = (new OreTile(21)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreLapis") + ->setDescriptionId(IDS_TILE_ORE_LAPIS) + ->setUseDescriptionId(IDS_DESC_ORE_LAPIS); + Tile::diamondOre = (new OreTile(56)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreDiamond") + ->setDescriptionId(IDS_TILE_ORE_DIAMOND) + ->setUseDescriptionId(IDS_DESC_ORE_DIAMOND); + Tile::rock = (new StoneTile(1)) + ->setDestroyTime(1.5f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"stone") + ->setDescriptionId(IDS_TILE_STONE) + ->setUseDescriptionId(IDS_DESC_STONE); + Tile::grass = (GrassTile*)(new GrassTile(2)) + ->setDestroyTime(0.6f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"grass") + ->setDescriptionId(IDS_TILE_GRASS) + ->setUseDescriptionId(IDS_DESC_GRASS); + Tile::dirt = (new DirtTile(3)) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_GRAVEL) + ->setTextureName(L"dirt") + ->setDescriptionId(IDS_TILE_DIRT) + ->setUseDescriptionId(IDS_DESC_DIRT); + Tile::sapling = (new Sapling(6)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"sapling") + ->setDescriptionId(IDS_TILE_SAPLING) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_SAPLING) + ->disableMipmap(); + Tile::unbreakable = (new Tile(7, Material::stone)) + ->setIndestructible() + ->setExplodeable(6000000) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"bedrock") + ->setDescriptionId(IDS_TILE_BEDROCK) + ->setNotCollectStatistics() + ->setUseDescriptionId(IDS_DESC_BEDROCK); + Tile::water = (LiquidTile*)(new LiquidTileDynamic(8, Material::water)) + ->setDestroyTime(100.0f) + ->setLightBlock(3) + ->setTextureName(L"water") + ->setDescriptionId(IDS_TILE_WATER) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_WATER); + Tile::calmWater = (new LiquidTileStatic(9, Material::water)) + ->setDestroyTime(100.0f) + ->setLightBlock(3) + ->setTextureName(L"water") + ->setDescriptionId(IDS_TILE_WATER) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_WATER); + Tile::lava = (LiquidTile*)(new LiquidTileDynamic(10, Material::lava)) + ->setDestroyTime(00.0f) + ->setLightEmission(1.0f) + ->setLightBlock(255) + ->setTextureName(L"lava") + ->setDescriptionId(IDS_TILE_LAVA) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_LAVA); + Tile::calmLava = (new LiquidTileStatic(11, Material::lava)) + ->setDestroyTime(100.0f) + ->setLightEmission(1.0f) + ->setLightBlock(255) + ->setTextureName(L"lava") + ->setDescriptionId(IDS_TILE_LAVA) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_LAVA); + Tile::sand = (new HeavyTile(12)) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_SAND) + ->setTextureName(L"sand") + ->setDescriptionId(IDS_TILE_SAND) + ->setUseDescriptionId(IDS_DESC_SAND); + Tile::gravel = (new GravelTile(13)) + ->setDestroyTime(0.6f) + ->setSoundType(Tile::SOUND_GRAVEL) + ->setTextureName(L"gravel") + ->setDescriptionId(IDS_TILE_GRAVEL) + ->setUseDescriptionId(IDS_DESC_GRAVEL); + Tile::treeTrunk = (new TreeTile(17)) + ->setDestroyTime(2.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"log") + ->setDescriptionId(IDS_TILE_LOG) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_LOG); + // 4J - for leaves, have specified that only the data bits that encode the + // type of leaf are important to be sent + Tile::leaves = (LeafTile*)(new LeafTile(18)) + ->setDestroyTime(0.2f) + ->setLightBlock(1) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"leaves") + ->setDescriptionId(IDS_TILE_LEAVES) + ->sendTileData(LeafTile::LEAF_TYPE_MASK) + ->setUseDescriptionId(IDS_DESC_LEAVES); + Tile::sponge = (new Sponge(19)) + ->setDestroyTime(0.6f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"sponge") + ->setDescriptionId(IDS_TILE_SPONGE) + ->setUseDescriptionId(IDS_DESC_SPONGE); + Tile::glass = (new GlassTile(20, Material::glass, false)) + ->setDestroyTime(0.3f) + ->setSoundType(Tile::SOUND_GLASS) + ->setTextureName(L"glass") + ->setDescriptionId(IDS_TILE_GLASS) + ->setUseDescriptionId(IDS_DESC_GLASS); + Tile::dispenser = (new DispenserTile(23)) + ->setDestroyTime(3.5f) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"dispenser") + ->setDescriptionId(IDS_TILE_DISPENSER) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_DISPENSER); - Tile::rock = (new StoneTile(1)) ->setDestroyTime(1.5f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"stone")->setDescriptionId(IDS_TILE_STONE)->setUseDescriptionId(IDS_DESC_STONE); - Tile::grass = (GrassTile *) (new GrassTile(2)) ->setDestroyTime(0.6f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"grass")->setDescriptionId(IDS_TILE_GRASS)->setUseDescriptionId(IDS_DESC_GRASS); - Tile::dirt = (new DirtTile(3)) ->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_GRAVEL)->setTextureName(L"dirt")->setDescriptionId(IDS_TILE_DIRT)->setUseDescriptionId(IDS_DESC_DIRT); - Tile::sapling = (new Sapling(6)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"sapling")->setDescriptionId(IDS_TILE_SAPLING)->sendTileData()->setUseDescriptionId(IDS_DESC_SAPLING)->disableMipmap(); - Tile::unbreakable = (new Tile(7, Material::stone)) ->setIndestructible()->setExplodeable(6000000)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"bedrock")->setDescriptionId(IDS_TILE_BEDROCK)->setNotCollectStatistics()->setUseDescriptionId(IDS_DESC_BEDROCK); - Tile::water = (LiquidTile *)(new LiquidTileDynamic(8, Material::water)) ->setDestroyTime(100.0f)->setLightBlock(3)->setTextureName(L"water")->setDescriptionId(IDS_TILE_WATER)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_WATER); - Tile::calmWater = (new LiquidTileStatic(9, Material::water))->setDestroyTime(100.0f)->setLightBlock(3)->setTextureName(L"water")->setDescriptionId(IDS_TILE_WATER)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_WATER); - Tile::lava = (LiquidTile *)(new LiquidTileDynamic(10, Material::lava)) ->setDestroyTime(00.0f)->setLightEmission(1.0f)->setLightBlock(255)->setTextureName(L"lava")->setDescriptionId(IDS_TILE_LAVA)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_LAVA); - Tile::calmLava = (new LiquidTileStatic(11, Material::lava)) ->setDestroyTime(100.0f)->setLightEmission(1.0f)->setLightBlock(255)->setTextureName(L"lava")->setDescriptionId(IDS_TILE_LAVA)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_LAVA); - Tile::sand = (new HeavyTile(12)) ->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_SAND)->setTextureName(L"sand")->setDescriptionId(IDS_TILE_SAND)->setUseDescriptionId(IDS_DESC_SAND); - Tile::gravel = (new GravelTile(13)) ->setDestroyTime(0.6f)->setSoundType(Tile::SOUND_GRAVEL)->setTextureName(L"gravel")->setDescriptionId(IDS_TILE_GRAVEL)->setUseDescriptionId(IDS_DESC_GRAVEL); - Tile::treeTrunk = (new TreeTile(17))->setDestroyTime(2.0f) ->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"log")->setDescriptionId(IDS_TILE_LOG)->sendTileData()->setUseDescriptionId(IDS_DESC_LOG); - // 4J - for leaves, have specified that only the data bits that encode the type of leaf are important to be sent - Tile::leaves = (LeafTile *)(new LeafTile(18)) ->setDestroyTime(0.2f)->setLightBlock(1)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"leaves")->setDescriptionId(IDS_TILE_LEAVES)->sendTileData(LeafTile::LEAF_TYPE_MASK)->setUseDescriptionId(IDS_DESC_LEAVES); - Tile::sponge = (new Sponge(19)) ->setDestroyTime(0.6f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"sponge")->setDescriptionId(IDS_TILE_SPONGE)->setUseDescriptionId(IDS_DESC_SPONGE); - Tile::glass = (new GlassTile(20, Material::glass, false)) ->setDestroyTime(0.3f)->setSoundType(Tile::SOUND_GLASS)->setTextureName(L"glass")->setDescriptionId(IDS_TILE_GLASS)->setUseDescriptionId(IDS_DESC_GLASS); - Tile::dispenser = (new DispenserTile(23)) ->setDestroyTime(3.5f)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"dispenser")->setDescriptionId(IDS_TILE_DISPENSER)->sendTileData()->setUseDescriptionId(IDS_DESC_DISPENSER); - - //Tile::wood = (new Tile(5, 4, Material::wood)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structwoodstuff, Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_WOOD)->setDescriptionId(IDS_TILE_WOOD)->sendTileData()->setUseDescriptionId(IDS_DESC_WOODENPLANKS); - Tile::wood = (new WoodTile(5)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structwoodstuff, Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"wood")->setDescriptionId(IDS_TILE_OAKWOOD_PLANKS)->sendTileData()->setUseDescriptionId(IDS_DESC_WOODENPLANKS); - Tile::sandStone = (new SandStoneTile(24)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_sand)->setSoundType(Tile::SOUND_STONE)->setDestroyTime(0.8f)->sendTileData()->setTextureName(L"sandStone")->setDescriptionId(IDS_TILE_SANDSTONE)->setUseDescriptionId(IDS_DESC_SANDSTONE)->sendTileData(); - Tile::stoneBrick = (new Tile(4, Material::stone)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"stonebrick")->setDescriptionId(IDS_TILE_STONE_BRICK)->setUseDescriptionId(IDS_DESC_STONE_BRICK); - Tile::redBrick = (new Tile(45, Material::stone)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_brick)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"brick")->setDescriptionId(IDS_TILE_BRICK)->setUseDescriptionId(IDS_DESC_BRICK); - Tile::clay = (new ClayTile(82)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_clay)->setDestroyTime(0.6f)->setSoundType(Tile::SOUND_GRAVEL)->setTextureName(L"clay")->setDescriptionId(IDS_TILE_CLAY)->setUseDescriptionId(IDS_DESC_CLAY_TILE); - Tile::snow = (new SnowTile(80)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_snow)->setDestroyTime(0.2f)->setSoundType(Tile::SOUND_CLOTH)->setTextureName(L"snow")->setDescriptionId(IDS_TILE_SNOW)->setUseDescriptionId(IDS_DESC_SNOW); - - Tile::torch = (new TorchTile(50)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, Item::eMaterial_wood)->setDestroyTime(0.0f)->setLightEmission(15 / 16.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"torch")->setDescriptionId(IDS_TILE_TORCH)->sendTileData()->setUseDescriptionId(IDS_DESC_TORCH)->disableMipmap(); - Tile::litPumpkin = (new PumpkinTile(91, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, Item::eMaterial_pumpkin)->setDestroyTime(1.0f)->setSoundType(Tile::SOUND_WOOD)->setLightEmission(1.0f)->setTextureName(L"litpumpkin")->setDescriptionId(IDS_TILE_LIT_PUMPKIN)->sendTileData()->setUseDescriptionId(IDS_DESC_JACKOLANTERN); - Tile::lightGem = (new LightGemTile(89, Material::glass)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, Item::eMaterial_glowstone)->setDestroyTime(0.3f)->setSoundType(Tile::SOUND_GLASS)->setLightEmission(1.0f)->setTextureName(L"lightgem")->setDescriptionId(IDS_TILE_LIGHT_GEM)->setUseDescriptionId(IDS_DESC_GLOWSTONE); + // Tile::wood = (new Tile(5, 4, Material::wood)) + // ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structwoodstuff, + // Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_WOOD)->setDescriptionId(IDS_TILE_WOOD)->sendTileData()->setUseDescriptionId(IDS_DESC_WOODENPLANKS); + Tile::wood = + (new WoodTile(5)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structwoodstuff, + Item::eMaterial_wood) + ->setDestroyTime(2.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"wood") + ->setDescriptionId(IDS_TILE_OAKWOOD_PLANKS) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_WOODENPLANKS); + Tile::sandStone = + (new SandStoneTile(24)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_sand) + ->setSoundType(Tile::SOUND_STONE) + ->setDestroyTime(0.8f) + ->sendTileData() + ->setTextureName(L"sandStone") + ->setDescriptionId(IDS_TILE_SANDSTONE) + ->setUseDescriptionId(IDS_DESC_SANDSTONE) + ->sendTileData(); + Tile::stoneBrick = + (new Tile(4, Material::stone)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_stone) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"stonebrick") + ->setDescriptionId(IDS_TILE_STONE_BRICK) + ->setUseDescriptionId(IDS_DESC_STONE_BRICK); + Tile::redBrick = + (new Tile(45, Material::stone)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_brick) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"brick") + ->setDescriptionId(IDS_TILE_BRICK) + ->setUseDescriptionId(IDS_DESC_BRICK); + Tile::clay = (new ClayTile(82)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_structblock, Item::eMaterial_clay) + ->setDestroyTime(0.6f) + ->setSoundType(Tile::SOUND_GRAVEL) + ->setTextureName(L"clay") + ->setDescriptionId(IDS_TILE_CLAY) + ->setUseDescriptionId(IDS_DESC_CLAY_TILE); + Tile::snow = (new SnowTile(80)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_structblock, Item::eMaterial_snow) + ->setDestroyTime(0.2f) + ->setSoundType(Tile::SOUND_CLOTH) + ->setTextureName(L"snow") + ->setDescriptionId(IDS_TILE_SNOW) + ->setUseDescriptionId(IDS_DESC_SNOW); - Tile::trapdoor = (new TrapDoorTile(96, Material::wood)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_door, Item::eMaterial_trap)->setDestroyTime(3.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"trapdoor")->setDescriptionId(IDS_TILE_TRAPDOOR)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_TRAPDOOR); + Tile::torch = (new TorchTile(50)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, + Item::eMaterial_wood) + ->setDestroyTime(0.0f) + ->setLightEmission(15 / 16.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"torch") + ->setDescriptionId(IDS_TILE_TORCH) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_TORCH) + ->disableMipmap(); + Tile::litPumpkin = + (new PumpkinTile(91, true)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, + Item::eMaterial_pumpkin) + ->setDestroyTime(1.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setLightEmission(1.0f) + ->setTextureName(L"litpumpkin") + ->setDescriptionId(IDS_TILE_LIT_PUMPKIN) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_JACKOLANTERN); + Tile::lightGem = (new LightGemTile(89, Material::glass)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_torch, + Item::eMaterial_glowstone) + ->setDestroyTime(0.3f) + ->setSoundType(Tile::SOUND_GLASS) + ->setLightEmission(1.0f) + ->setTextureName(L"lightgem") + ->setDescriptionId(IDS_TILE_LIGHT_GEM) + ->setUseDescriptionId(IDS_DESC_GLOWSTONE); - Tile::bed = (new BedTile(26)) ->setDestroyTime(0.2f)->setTextureName(L"bed")->setDescriptionId(IDS_TILE_BED)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_BED); - Tile::pistonStickyBase = (PistonBaseTile *)(new PistonBaseTile(29, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_piston, Item::eMaterial_stickypiston)->setTextureName(L"pistonStickyBase")->setDescriptionId(IDS_TILE_PISTON_STICK_BASE)->setUseDescriptionId(IDS_DESC_STICKY_PISTON)->sendTileData(); - Tile::web = (new WebTile(30)) ->setLightBlock(1)->setDestroyTime(4.0f)->setTextureName(L"web")->setDescriptionId(IDS_TILE_WEB)->setUseDescriptionId(IDS_DESC_WEB); - Tile::tallgrass = (TallGrass *)(new TallGrass(31)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"tallgrass")->setDescriptionId(IDS_TILE_TALL_GRASS)->setUseDescriptionId(IDS_DESC_TALL_GRASS)->disableMipmap(); - Tile::deadBush = (DeadBushTile *)(new DeadBushTile(32)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"deadbush")->setDescriptionId(IDS_TILE_DEAD_BUSH)->setUseDescriptionId(IDS_DESC_DEAD_BUSH)->disableMipmap(); - Tile::pistonBase = (PistonBaseTile *)(new PistonBaseTile(33,false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_piston, Item::eMaterial_piston)->setTextureName(L"pistonBase")->setDescriptionId(IDS_TILE_PISTON_BASE)->setUseDescriptionId(IDS_DESC_PISTON)->sendTileData(); - Tile::pistonExtension = (PistonExtensionTile *)(new PistonExtensionTile(34)) ->setDescriptionId(IDS_TILE_PISTON_BASE)->setUseDescriptionId(-1)->sendTileData(); + Tile::trapdoor = (new TrapDoorTile(96, Material::wood)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_door, + Item::eMaterial_trap) + ->setDestroyTime(3.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"trapdoor") + ->setDescriptionId(IDS_TILE_TRAPDOOR) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_TRAPDOOR); - Tile::cloth = (new ClothTile()) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_cloth, Item::eMaterial_cloth)->setDestroyTime(0.8f)->setSoundType(Tile::SOUND_CLOTH)->setTextureName(L"cloth")->setDescriptionId(IDS_TILE_CLOTH)->sendTileData()->setUseDescriptionId(IDS_DESC_WOOL); - Tile::pistonMovingPiece = (PistonMovingPiece *)(new PistonMovingPiece(36)) ->setDescriptionId(IDS_TILE_PISTON_BASE)->setUseDescriptionId(-1); + Tile::bed = (new BedTile(26)) + ->setDestroyTime(0.2f) + ->setTextureName(L"bed") + ->setDescriptionId(IDS_TILE_BED) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_BED); + Tile::pistonStickyBase = + (PistonBaseTile*)(new PistonBaseTile(29, true)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_piston, + Item::eMaterial_stickypiston) + ->setTextureName(L"pistonStickyBase") + ->setDescriptionId(IDS_TILE_PISTON_STICK_BASE) + ->setUseDescriptionId(IDS_DESC_STICKY_PISTON) + ->sendTileData(); + Tile::web = (new WebTile(30)) + ->setLightBlock(1) + ->setDestroyTime(4.0f) + ->setTextureName(L"web") + ->setDescriptionId(IDS_TILE_WEB) + ->setUseDescriptionId(IDS_DESC_WEB); + Tile::tallgrass = (TallGrass*)(new TallGrass(31)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"tallgrass") + ->setDescriptionId(IDS_TILE_TALL_GRASS) + ->setUseDescriptionId(IDS_DESC_TALL_GRASS) + ->disableMipmap(); + Tile::deadBush = (DeadBushTile*)(new DeadBushTile(32)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"deadbush") + ->setDescriptionId(IDS_TILE_DEAD_BUSH) + ->setUseDescriptionId(IDS_DESC_DEAD_BUSH) + ->disableMipmap(); + Tile::pistonBase = + (PistonBaseTile*)(new PistonBaseTile(33, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_piston, + Item::eMaterial_piston) + ->setTextureName(L"pistonBase") + ->setDescriptionId(IDS_TILE_PISTON_BASE) + ->setUseDescriptionId(IDS_DESC_PISTON) + ->sendTileData(); + Tile::pistonExtension = (PistonExtensionTile*)(new PistonExtensionTile(34)) + ->setDescriptionId(IDS_TILE_PISTON_BASE) + ->setUseDescriptionId(-1) + ->sendTileData(); - Tile::pressurePlate_stone = (Tile *)(new PressurePlateTile(70, L"stone", Material::stone, PressurePlateTile::mobs)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_pressureplate, Item::eMaterial_stone)->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"pressurePlate")->setDescriptionId(IDS_TILE_PRESSURE_PLATE)->sendTileData()->setUseDescriptionId(IDS_DESC_PRESSUREPLATE); - Tile::pressurePlate_wood = (new PressurePlateTile(72, L"wood", Material::wood, PressurePlateTile::everything)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_pressureplate, Item::eMaterial_wood)->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"pressurePlate")->setDescriptionId(IDS_TILE_PRESSURE_PLATE)->sendTileData()->setUseDescriptionId(IDS_DESC_PRESSUREPLATE); + Tile::cloth = (new ClothTile()) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_cloth, + Item::eMaterial_cloth) + ->setDestroyTime(0.8f) + ->setSoundType(Tile::SOUND_CLOTH) + ->setTextureName(L"cloth") + ->setDescriptionId(IDS_TILE_CLOTH) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_WOOL); + Tile::pistonMovingPiece = (PistonMovingPiece*)(new PistonMovingPiece(36)) + ->setDescriptionId(IDS_TILE_PISTON_BASE) + ->setUseDescriptionId(-1); - Tile::flower = (Bush *) (new Bush(37)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"flower")->setDescriptionId(IDS_TILE_FLOWER)->setUseDescriptionId(IDS_DESC_FLOWER)->disableMipmap(); - Tile::rose = (Bush *) (new Bush(38)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"rose")->setDescriptionId(IDS_TILE_ROSE)->setUseDescriptionId(IDS_DESC_FLOWER)->disableMipmap(); - Tile::mushroom1 = (Bush *) (new Mushroom(39, L"mushroom_brown")) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setLightEmission(2 / 16.0f)->setTextureName(L"mushroom")->setDescriptionId(IDS_TILE_MUSHROOM)->setUseDescriptionId(IDS_DESC_MUSHROOM)->disableMipmap(); - Tile::mushroom2 = (Bush *) (new Mushroom(40, L"mushroom_red")) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"mushroom")->setDescriptionId(IDS_TILE_MUSHROOM)->setUseDescriptionId(IDS_DESC_MUSHROOM)->disableMipmap(); + Tile::pressurePlate_stone = + (Tile*)(new PressurePlateTile(70, L"stone", Material::stone, + PressurePlateTile::mobs)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_pressureplate, + Item::eMaterial_stone) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"pressurePlate") + ->setDescriptionId(IDS_TILE_PRESSURE_PLATE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_PRESSUREPLATE); + Tile::pressurePlate_wood = + (new PressurePlateTile(72, L"wood", Material::wood, + PressurePlateTile::everything)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_pressureplate, + Item::eMaterial_wood) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"pressurePlate") + ->setDescriptionId(IDS_TILE_PRESSURE_PLATE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_PRESSUREPLATE); -// Tile::stoneSlab = (new StoneSlabTile(43, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_SLAB); -// Tile::stoneSlabHalf = (new StoneSlabTile(44, false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_HALFSLAB); + Tile::flower = (Bush*)(new Bush(37)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"flower") + ->setDescriptionId(IDS_TILE_FLOWER) + ->setUseDescriptionId(IDS_DESC_FLOWER) + ->disableMipmap(); + Tile::rose = (Bush*)(new Bush(38)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"rose") + ->setDescriptionId(IDS_TILE_ROSE) + ->setUseDescriptionId(IDS_DESC_FLOWER) + ->disableMipmap(); + Tile::mushroom1 = (Bush*)(new Mushroom(39, L"mushroom_brown")) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setLightEmission(2 / 16.0f) + ->setTextureName(L"mushroom") + ->setDescriptionId(IDS_TILE_MUSHROOM) + ->setUseDescriptionId(IDS_DESC_MUSHROOM) + ->disableMipmap(); + Tile::mushroom2 = (Bush*)(new Mushroom(40, L"mushroom_red")) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"mushroom") + ->setDescriptionId(IDS_TILE_MUSHROOM) + ->setUseDescriptionId(IDS_DESC_MUSHROOM) + ->disableMipmap(); - - Tile::tnt = (new TntTile(46)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"tnt")->setDescriptionId(IDS_TILE_TNT)->setUseDescriptionId(IDS_DESC_TNT); - Tile::bookshelf = (new BookshelfTile(47)) ->setDestroyTime(1.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"bookshelf")->setDescriptionId(IDS_TILE_BOOKSHELF)->setUseDescriptionId(IDS_DESC_BOOKSHELF); - Tile::mossStone = (new Tile(48, Material::stone)) ->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"stoneMoss")->setDescriptionId(IDS_TILE_STONE_MOSS)->setUseDescriptionId(IDS_DESC_MOSS_STONE); - // 4J - change of destroy time from 10.0f -> 50.0f for obsidian brought forward from 1.2.3 - Tile::obsidian = (new ObsidianTile(49)) ->setDestroyTime(50.0f)->setExplodeable(2000)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"obsidian")->setDescriptionId(IDS_TILE_OBSIDIAN)->setUseDescriptionId(IDS_DESC_OBSIDIAN); - + // Tile::stoneSlab = (new StoneSlabTile(43, true)) + // ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, + // Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_SLAB); + // Tile::stoneSlabHalf = (new StoneSlabTile(44, false)) + // ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, + // Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_HALFSLAB); - Tile::fire = (FireTile *) ((new FireTile(51)) ->setDestroyTime(0.0f)->setLightEmission(1.0f)->setSoundType(Tile::SOUND_WOOD))->setTextureName(L"fire")->setDescriptionId(IDS_TILE_FIRE)->setNotCollectStatistics()->setUseDescriptionId(-1); - Tile::mobSpawner = (new MobSpawnerTile(52)) ->setDestroyTime(5.0f)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"mobSpawner")->setDescriptionId(IDS_TILE_MOB_SPAWNER)->setNotCollectStatistics()->setUseDescriptionId(IDS_DESC_MOB_SPAWNER); - - Tile::chest = (ChestTile *)(new ChestTile(54)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_chest, Item::eMaterial_ender)->setDestroyTime(2.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"chest")->setDescriptionId(IDS_TILE_CHEST)->sendTileData()->setUseDescriptionId(IDS_DESC_CHEST); - Tile::redStoneDust = (RedStoneDustTile *)(new RedStoneDustTile(55)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_NORMAL)->setTextureName(L"redstoneDust")->setDescriptionId(IDS_TILE_REDSTONE_DUST)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_REDSTONE_DUST); - Tile::workBench = (new WorkbenchTile(58)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, Item::eMaterial_wood)->setDestroyTime(2.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"workbench")->setDescriptionId(IDS_TILE_WORKBENCH)->setUseDescriptionId(IDS_DESC_CRAFTINGTABLE); - Tile::crops = (new CropTile(59)) ->setTextureName(L"crops")->setDescriptionId(IDS_TILE_CROPS)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_CROPS)->disableMipmap(); - Tile::farmland = (new FarmTile(60)) ->setDestroyTime(0.6f)->setSoundType(Tile::SOUND_GRAVEL)->setTextureName(L"farmland")->setDescriptionId(IDS_TILE_FARMLAND)->setUseDescriptionId(IDS_DESC_FARMLAND)->sendTileData(); - Tile::furnace = (new FurnaceTile(61, false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, Item::eMaterial_stone)->setDestroyTime(3.5f)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"furnace")->setDescriptionId(IDS_TILE_FURNACE)->sendTileData()->setUseDescriptionId(IDS_DESC_FURNACE); - Tile::furnace_lit = (new FurnaceTile(62, true)) ->setDestroyTime(3.5f)->setSoundType(Tile::SOUND_STONE)->setLightEmission(14 / 16.0f)->setTextureName(L"furnace")->setDescriptionId(IDS_TILE_FURNACE)->sendTileData()->setUseDescriptionId(IDS_DESC_FURNACE); - Tile::sign = (new SignTile(63, eTYPE_SIGNTILEENTITY, true))->setDestroyTime(1.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"sign")->setDescriptionId(IDS_TILE_SIGN)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_SIGN); - Tile::door_wood = (new DoorTile(64, Material::wood)) ->setDestroyTime(3.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"doorWood")->setDescriptionId(IDS_TILE_DOOR_WOOD)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_DOOR_WOOD); - Tile::ladder = (new LadderTile(65)) ->setDestroyTime(0.4f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"ladder")->setDescriptionId(IDS_TILE_LADDER)->sendTileData()->setUseDescriptionId(IDS_DESC_LADDER)->disableMipmap(); - Tile::wallSign = (new SignTile(68, eTYPE_SIGNTILEENTITY, false))->setDestroyTime(1.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"sign")->setDescriptionId(IDS_TILE_SIGN)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_SIGN); - Tile::lever = (new LeverTile(69)) ->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"lever")->setDescriptionId(IDS_TILE_LEVER)->sendTileData()->setUseDescriptionId(IDS_DESC_LEVER); - Tile::door_iron = (new DoorTile(71, Material::metal)) ->setDestroyTime(5.0f)->setSoundType(Tile::SOUND_METAL)->setTextureName(L"doorIron")->setDescriptionId(IDS_TILE_DOOR_IRON)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_DOOR_IRON); - Tile::redStoneOre = (new RedStoneOreTile(73,false)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreRedstone")->setDescriptionId(IDS_TILE_ORE_REDSTONE)->sendTileData()->setUseDescriptionId(IDS_DESC_ORE_REDSTONE); - Tile::redStoneOre_lit = (new RedStoneOreTile(74, true)) ->setLightEmission(10 / 16.0f)->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"oreRedstone")->setDescriptionId(IDS_TILE_ORE_REDSTONE)->sendTileData()->setUseDescriptionId(IDS_DESC_ORE_REDSTONE); - Tile::notGate_off = (new NotGateTile(75, false)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"notGate")->setDescriptionId(IDS_TILE_NOT_GATE)->sendTileData()->setUseDescriptionId(IDS_DESC_REDSTONETORCH)->disableMipmap(); - Tile::notGate_on = (new NotGateTile(76, true)) ->setDestroyTime(0.0f)->setLightEmission(8 / 16.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"notGate")->setDescriptionId(IDS_TILE_NOT_GATE)->sendTileData()->setUseDescriptionId(IDS_DESC_REDSTONETORCH)->disableMipmap(); - Tile::button = (new ButtonTile(77,false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_button, Item::eMaterial_stone)->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"button")->setDescriptionId(IDS_TILE_BUTTON)->sendTileData()->setUseDescriptionId(IDS_DESC_BUTTON); - Tile::topSnow = (new TopSnowTile(78)) ->setDestroyTime(0.1f)->setSoundType(Tile::SOUND_CLOTH)->setTextureName(L"snow")->setDescriptionId(IDS_TILE_SNOW)->setUseDescriptionId(IDS_DESC_TOP_SNOW)->sendTileData()->setLightBlock(0); - Tile::ice = (new IceTile(79)) ->setDestroyTime(0.5f)->setLightBlock(3)->setSoundType(Tile::SOUND_GLASS)->setTextureName(L"ice")->setDescriptionId(IDS_TILE_ICE)->setUseDescriptionId(IDS_DESC_ICE); - Tile::cactus = (new CactusTile(81)) ->setDestroyTime(0.4f)->setSoundType(Tile::SOUND_CLOTH)->setTextureName(L"cactus")->setDescriptionId(IDS_TILE_CACTUS)->setUseDescriptionId(IDS_DESC_CACTUS)->disableMipmap(); - Tile::reeds = (new ReedTile(83)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_GRASS)->setTextureName(L"reeds")->setDescriptionId(IDS_TILE_REEDS)->setNotCollectStatistics()->setUseDescriptionId(IDS_DESC_REEDS)->disableMipmap(); - Tile::recordPlayer = (new RecordPlayerTile(84)) ->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"jukebox")->setDescriptionId(IDS_TILE_JUKEBOX)->sendTileData()->setUseDescriptionId(IDS_DESC_JUKEBOX); - Tile::fence = (new FenceTile(85, L"wood", Material::wood)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"fence")->setDescriptionId(IDS_TILE_FENCE)->setUseDescriptionId(IDS_DESC_FENCE); + Tile::tnt = (new TntTile(46)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"tnt") + ->setDescriptionId(IDS_TILE_TNT) + ->setUseDescriptionId(IDS_DESC_TNT); + Tile::bookshelf = (new BookshelfTile(47)) + ->setDestroyTime(1.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"bookshelf") + ->setDescriptionId(IDS_TILE_BOOKSHELF) + ->setUseDescriptionId(IDS_DESC_BOOKSHELF); + Tile::mossStone = (new Tile(48, Material::stone)) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"stoneMoss") + ->setDescriptionId(IDS_TILE_STONE_MOSS) + ->setUseDescriptionId(IDS_DESC_MOSS_STONE); + // 4J - change of destroy time from 10.0f -> 50.0f for obsidian brought + // forward from 1.2.3 + Tile::obsidian = (new ObsidianTile(49)) + ->setDestroyTime(50.0f) + ->setExplodeable(2000) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"obsidian") + ->setDescriptionId(IDS_TILE_OBSIDIAN) + ->setUseDescriptionId(IDS_DESC_OBSIDIAN); - Tile::pumpkin = (new PumpkinTile(86, false)) ->setDestroyTime(1.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"pumpkin")->setDescriptionId(IDS_TILE_PUMPKIN)->sendTileData()->setUseDescriptionId(IDS_DESC_PUMPKIN); + Tile::fire = (FireTile*)((new FireTile(51)) + ->setDestroyTime(0.0f) + ->setLightEmission(1.0f) + ->setSoundType(Tile::SOUND_WOOD)) + ->setTextureName(L"fire") + ->setDescriptionId(IDS_TILE_FIRE) + ->setNotCollectStatistics() + ->setUseDescriptionId(-1); + Tile::mobSpawner = (new MobSpawnerTile(52)) + ->setDestroyTime(5.0f) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"mobSpawner") + ->setDescriptionId(IDS_TILE_MOB_SPAWNER) + ->setNotCollectStatistics() + ->setUseDescriptionId(IDS_DESC_MOB_SPAWNER); - Tile::hellRock = (new HellStoneTile(87)) ->setDestroyTime(0.4f)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"hellrock")->setDescriptionId(IDS_TILE_HELL_ROCK)->setUseDescriptionId(IDS_DESC_HELL_ROCK); - Tile::hellSand = (new HellSandTile(88)) ->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_SAND)->setTextureName(L"hellsand")->setDescriptionId(IDS_TILE_HELL_SAND)->setUseDescriptionId(IDS_DESC_HELL_SAND); - Tile::portalTile = (PortalTile *) ((new PortalTile(90)) ->setDestroyTime(-1)->setSoundType(Tile::SOUND_GLASS)->setLightEmission(0.75f))->setTextureName(L"portal")->setDescriptionId(IDS_TILE_PORTAL)->setUseDescriptionId(IDS_DESC_PORTAL); - Tile::cake = (new CakeTile(92)) ->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_CLOTH)->setTextureName(L"cake")->setDescriptionId(IDS_TILE_CAKE)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_CAKE); + Tile::chest = (ChestTile*)(new ChestTile(54)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_chest, + Item::eMaterial_ender) + ->setDestroyTime(2.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"chest") + ->setDescriptionId(IDS_TILE_CHEST) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_CHEST); + Tile::redStoneDust = (RedStoneDustTile*)(new RedStoneDustTile(55)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_NORMAL) + ->setTextureName(L"redstoneDust") + ->setDescriptionId(IDS_TILE_REDSTONE_DUST) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_REDSTONE_DUST); + Tile::workBench = (new WorkbenchTile(58)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_device, Item::eMaterial_wood) + ->setDestroyTime(2.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"workbench") + ->setDescriptionId(IDS_TILE_WORKBENCH) + ->setUseDescriptionId(IDS_DESC_CRAFTINGTABLE); + Tile::crops = (new CropTile(59)) + ->setTextureName(L"crops") + ->setDescriptionId(IDS_TILE_CROPS) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_CROPS) + ->disableMipmap(); + Tile::farmland = (new FarmTile(60)) + ->setDestroyTime(0.6f) + ->setSoundType(Tile::SOUND_GRAVEL) + ->setTextureName(L"farmland") + ->setDescriptionId(IDS_TILE_FARMLAND) + ->setUseDescriptionId(IDS_DESC_FARMLAND) + ->sendTileData(); + Tile::furnace = (new FurnaceTile(61, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, + Item::eMaterial_stone) + ->setDestroyTime(3.5f) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"furnace") + ->setDescriptionId(IDS_TILE_FURNACE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_FURNACE); + Tile::furnace_lit = (new FurnaceTile(62, true)) + ->setDestroyTime(3.5f) + ->setSoundType(Tile::SOUND_STONE) + ->setLightEmission(14 / 16.0f) + ->setTextureName(L"furnace") + ->setDescriptionId(IDS_TILE_FURNACE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_FURNACE); + Tile::sign = (new SignTile(63, eTYPE_SIGNTILEENTITY, true)) + ->setDestroyTime(1.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"sign") + ->setDescriptionId(IDS_TILE_SIGN) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_SIGN); + Tile::door_wood = (new DoorTile(64, Material::wood)) + ->setDestroyTime(3.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"doorWood") + ->setDescriptionId(IDS_TILE_DOOR_WOOD) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_DOOR_WOOD); + Tile::ladder = (new LadderTile(65)) + ->setDestroyTime(0.4f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"ladder") + ->setDescriptionId(IDS_TILE_LADDER) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_LADDER) + ->disableMipmap(); + Tile::wallSign = (new SignTile(68, eTYPE_SIGNTILEENTITY, false)) + ->setDestroyTime(1.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"sign") + ->setDescriptionId(IDS_TILE_SIGN) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_SIGN); + Tile::lever = (new LeverTile(69)) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"lever") + ->setDescriptionId(IDS_TILE_LEVER) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_LEVER); + Tile::door_iron = (new DoorTile(71, Material::metal)) + ->setDestroyTime(5.0f) + ->setSoundType(Tile::SOUND_METAL) + ->setTextureName(L"doorIron") + ->setDescriptionId(IDS_TILE_DOOR_IRON) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_DOOR_IRON); + Tile::redStoneOre = (new RedStoneOreTile(73, false)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreRedstone") + ->setDescriptionId(IDS_TILE_ORE_REDSTONE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_ORE_REDSTONE); + Tile::redStoneOre_lit = (new RedStoneOreTile(74, true)) + ->setLightEmission(10 / 16.0f) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"oreRedstone") + ->setDescriptionId(IDS_TILE_ORE_REDSTONE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_ORE_REDSTONE); + Tile::notGate_off = (new NotGateTile(75, false)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"notGate") + ->setDescriptionId(IDS_TILE_NOT_GATE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_REDSTONETORCH) + ->disableMipmap(); + Tile::notGate_on = (new NotGateTile(76, true)) + ->setDestroyTime(0.0f) + ->setLightEmission(8 / 16.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"notGate") + ->setDescriptionId(IDS_TILE_NOT_GATE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_REDSTONETORCH) + ->disableMipmap(); + Tile::button = (new ButtonTile(77, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_button, + Item::eMaterial_stone) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"button") + ->setDescriptionId(IDS_TILE_BUTTON) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_BUTTON); + Tile::topSnow = (new TopSnowTile(78)) + ->setDestroyTime(0.1f) + ->setSoundType(Tile::SOUND_CLOTH) + ->setTextureName(L"snow") + ->setDescriptionId(IDS_TILE_SNOW) + ->setUseDescriptionId(IDS_DESC_TOP_SNOW) + ->sendTileData() + ->setLightBlock(0); + Tile::ice = (new IceTile(79)) + ->setDestroyTime(0.5f) + ->setLightBlock(3) + ->setSoundType(Tile::SOUND_GLASS) + ->setTextureName(L"ice") + ->setDescriptionId(IDS_TILE_ICE) + ->setUseDescriptionId(IDS_DESC_ICE); + Tile::cactus = (new CactusTile(81)) + ->setDestroyTime(0.4f) + ->setSoundType(Tile::SOUND_CLOTH) + ->setTextureName(L"cactus") + ->setDescriptionId(IDS_TILE_CACTUS) + ->setUseDescriptionId(IDS_DESC_CACTUS) + ->disableMipmap(); + Tile::reeds = (new ReedTile(83)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_GRASS) + ->setTextureName(L"reeds") + ->setDescriptionId(IDS_TILE_REEDS) + ->setNotCollectStatistics() + ->setUseDescriptionId(IDS_DESC_REEDS) + ->disableMipmap(); + Tile::recordPlayer = (new RecordPlayerTile(84)) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"jukebox") + ->setDescriptionId(IDS_TILE_JUKEBOX) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_JUKEBOX); + Tile::fence = (new FenceTile(85, L"wood", Material::wood)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, + Item::eMaterial_wood) + ->setDestroyTime(2.0f) + ->setExplodeable(5) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"fence") + ->setDescriptionId(IDS_TILE_FENCE) + ->setUseDescriptionId(IDS_DESC_FENCE); - // TODO Copy the translations from IDS_ITEM_DIODE to IDS_TILE_DIODE - Tile::diode_off = (RepeaterTile *)(new DiodeTile(93, false)) ->setDestroyTime(0.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"diode")->setDescriptionId(IDS_ITEM_DIODE)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER)->disableMipmap(); - Tile::diode_on = (RepeaterTile *)(new DiodeTile(94, true)) ->setDestroyTime(0.0f)->setLightEmission(10 / 16.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"diode")->setDescriptionId(IDS_ITEM_DIODE)->setNotCollectStatistics()->sendTileData()->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER)->disableMipmap(); - Tile::aprilFoolsJoke = (new LockedChestTile(95)) ->setDestroyTime(0.0f)->setLightEmission(16 / 16.0f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"lockedchest")->setDescriptionId(IDS_TILE_LOCKED_CHEST)->setTicking(true)->sendTileData()->setUseDescriptionId(-1); + Tile::pumpkin = (new PumpkinTile(86, false)) + ->setDestroyTime(1.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"pumpkin") + ->setDescriptionId(IDS_TILE_PUMPKIN) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_PUMPKIN); - Tile::monsterStoneEgg = (new StoneMonsterTile(97)) ->setDestroyTime(0.75f)->setTextureName(L"monsterStoneEgg")->setDescriptionId(IDS_TILE_STONE_SILVERFISH)->setUseDescriptionId(IDS_DESC_STONE_SILVERFISH); - Tile::stoneBrickSmooth = (new SmoothStoneBrickTile(98)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_stoneSmooth)->setDestroyTime(1.5f)->setExplodeable(10)->setSoundType(SOUND_STONE)->setTextureName(L"stonebricksmooth")->setDescriptionId(IDS_TILE_STONE_BRICK_SMOOTH)->setUseDescriptionId(IDS_DESC_STONE_BRICK_SMOOTH); - Tile::hugeMushroom1 = (new HugeMushroomTile(99, Material::wood, 0)) ->setDestroyTime(0.2f)->setSoundType(SOUND_WOOD)->setTextureName(L"mushroom")->setDescriptionId(IDS_TILE_HUGE_MUSHROOM_1)->setUseDescriptionId(IDS_DESC_MUSHROOM)->sendTileData(); - Tile::hugeMushroom2 = (new HugeMushroomTile(100, Material::wood, 1)) ->setDestroyTime(0.2f)->setSoundType(SOUND_WOOD)->setTextureName(L"mushroom")->setDescriptionId(IDS_TILE_HUGE_MUSHROOM_2)->setUseDescriptionId(IDS_DESC_MUSHROOM)->sendTileData(); - Tile::ironFence = (new ThinFenceTile(101, L"fenceIron", L"fenceIron", Material::metal, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, Item::eMaterial_iron)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setTextureName(L"fenceIron")->setDescriptionId(IDS_TILE_IRON_FENCE)->setUseDescriptionId(IDS_DESC_IRON_FENCE); - Tile::thinGlass = (new ThinFenceTile(102, L"glass", L"thinglass_top", Material::glass, false)) ->setDestroyTime(0.3f)->setSoundType(SOUND_GLASS)->setTextureName(L"thinGlass")->setDescriptionId(IDS_TILE_THIN_GLASS)->setUseDescriptionId(IDS_DESC_THIN_GLASS); - Tile::melon = (new MelonTile(103)) ->setDestroyTime(1.0f)->setSoundType(SOUND_WOOD)->setTextureName(L"melon")->setDescriptionId(IDS_TILE_MELON)->setUseDescriptionId(IDS_DESC_MELON_BLOCK); - Tile::pumpkinStem = (new StemTile(104, Tile::pumpkin)) ->setDestroyTime(0.0f)->setSoundType(SOUND_WOOD)->setTextureName(L"pumpkinStem")->setDescriptionId(IDS_TILE_PUMPKIN_STEM)->sendTileData(); - Tile::melonStem = (new StemTile(105, Tile::melon)) ->setDestroyTime(0.0f)->setSoundType(SOUND_WOOD)->setTextureName(L"pumpkinStem")->setDescriptionId(IDS_TILE_MELON_STEM)->sendTileData(); - Tile::vine = (new VineTile(106))->setDestroyTime(0.2f) ->setSoundType(SOUND_GRASS)->setTextureName(L"vine")->setDescriptionId(IDS_TILE_VINE)->setUseDescriptionId(IDS_DESC_VINE)->sendTileData(); - Tile::fenceGate = (new FenceGateTile(107)) ->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(SOUND_WOOD)->setTextureName(L"fenceGate")->setDescriptionId(IDS_TILE_FENCE_GATE)->sendTileData()->setUseDescriptionId(IDS_DESC_FENCE_GATE); + Tile::hellRock = (new HellStoneTile(87)) + ->setDestroyTime(0.4f) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"hellrock") + ->setDescriptionId(IDS_TILE_HELL_ROCK) + ->setUseDescriptionId(IDS_DESC_HELL_ROCK); + Tile::hellSand = (new HellSandTile(88)) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_SAND) + ->setTextureName(L"hellsand") + ->setDescriptionId(IDS_TILE_HELL_SAND) + ->setUseDescriptionId(IDS_DESC_HELL_SAND); + Tile::portalTile = (PortalTile*)((new PortalTile(90)) + ->setDestroyTime(-1) + ->setSoundType(Tile::SOUND_GLASS) + ->setLightEmission(0.75f)) + ->setTextureName(L"portal") + ->setDescriptionId(IDS_TILE_PORTAL) + ->setUseDescriptionId(IDS_DESC_PORTAL); + Tile::cake = (new CakeTile(92)) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_CLOTH) + ->setTextureName(L"cake") + ->setDescriptionId(IDS_TILE_CAKE) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_CAKE); + // TODO Copy the translations from IDS_ITEM_DIODE to IDS_TILE_DIODE + Tile::diode_off = (RepeaterTile*)(new DiodeTile(93, false)) + ->setDestroyTime(0.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"diode") + ->setDescriptionId(IDS_ITEM_DIODE) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER) + ->disableMipmap(); + Tile::diode_on = (RepeaterTile*)(new DiodeTile(94, true)) + ->setDestroyTime(0.0f) + ->setLightEmission(10 / 16.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"diode") + ->setDescriptionId(IDS_ITEM_DIODE) + ->setNotCollectStatistics() + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER) + ->disableMipmap(); + Tile::aprilFoolsJoke = (new LockedChestTile(95)) + ->setDestroyTime(0.0f) + ->setLightEmission(16 / 16.0f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"lockedchest") + ->setDescriptionId(IDS_TILE_LOCKED_CHEST) + ->setTicking(true) + ->sendTileData() + ->setUseDescriptionId(-1); - Tile::stairs_wood = (new StairTile(53, Tile::wood,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_wood) ->setTextureName(L"stairsWood")->setDescriptionId(IDS_TILE_STAIRS_WOOD) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::stairs_stone = (new StairTile(67, Tile::stoneBrick,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_stone) ->setTextureName(L"stairsStone")->setDescriptionId(IDS_TILE_STAIRS_STONE) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::stairs_bricks = (new StairTile(108, Tile::redBrick,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_brick) ->setTextureName(L"stairsBrick")->setDescriptionId(IDS_TILE_STAIRS_BRICKS) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::stairs_stoneBrickSmooth = (new StairTile(109, Tile::stoneBrickSmooth,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_stoneSmooth)->setTextureName(L"stairsStoneBrickSmooth")->setDescriptionId(IDS_TILE_STAIRS_STONE_BRICKS_SMOOTH) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::monsterStoneEgg = + (new StoneMonsterTile(97)) + ->setDestroyTime(0.75f) + ->setTextureName(L"monsterStoneEgg") + ->setDescriptionId(IDS_TILE_STONE_SILVERFISH) + ->setUseDescriptionId(IDS_DESC_STONE_SILVERFISH); + Tile::stoneBrickSmooth = + (new SmoothStoneBrickTile(98)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_stoneSmooth) + ->setDestroyTime(1.5f) + ->setExplodeable(10) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"stonebricksmooth") + ->setDescriptionId(IDS_TILE_STONE_BRICK_SMOOTH) + ->setUseDescriptionId(IDS_DESC_STONE_BRICK_SMOOTH); + Tile::hugeMushroom1 = (new HugeMushroomTile(99, Material::wood, 0)) + ->setDestroyTime(0.2f) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"mushroom") + ->setDescriptionId(IDS_TILE_HUGE_MUSHROOM_1) + ->setUseDescriptionId(IDS_DESC_MUSHROOM) + ->sendTileData(); + Tile::hugeMushroom2 = (new HugeMushroomTile(100, Material::wood, 1)) + ->setDestroyTime(0.2f) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"mushroom") + ->setDescriptionId(IDS_TILE_HUGE_MUSHROOM_2) + ->setUseDescriptionId(IDS_DESC_MUSHROOM) + ->sendTileData(); + Tile::ironFence = (new ThinFenceTile(101, L"fenceIron", L"fenceIron", + Material::metal, true)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_fence, Item::eMaterial_iron) + ->setDestroyTime(5.0f) + ->setExplodeable(10) + ->setSoundType(SOUND_METAL) + ->setTextureName(L"fenceIron") + ->setDescriptionId(IDS_TILE_IRON_FENCE) + ->setUseDescriptionId(IDS_DESC_IRON_FENCE); + Tile::thinGlass = (new ThinFenceTile(102, L"glass", L"thinglass_top", + Material::glass, false)) + ->setDestroyTime(0.3f) + ->setSoundType(SOUND_GLASS) + ->setTextureName(L"thinGlass") + ->setDescriptionId(IDS_TILE_THIN_GLASS) + ->setUseDescriptionId(IDS_DESC_THIN_GLASS); + Tile::melon = (new MelonTile(103)) + ->setDestroyTime(1.0f) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"melon") + ->setDescriptionId(IDS_TILE_MELON) + ->setUseDescriptionId(IDS_DESC_MELON_BLOCK); + Tile::pumpkinStem = (new StemTile(104, Tile::pumpkin)) + ->setDestroyTime(0.0f) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"pumpkinStem") + ->setDescriptionId(IDS_TILE_PUMPKIN_STEM) + ->sendTileData(); + Tile::melonStem = (new StemTile(105, Tile::melon)) + ->setDestroyTime(0.0f) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"pumpkinStem") + ->setDescriptionId(IDS_TILE_MELON_STEM) + ->sendTileData(); + Tile::vine = (new VineTile(106)) + ->setDestroyTime(0.2f) + ->setSoundType(SOUND_GRASS) + ->setTextureName(L"vine") + ->setDescriptionId(IDS_TILE_VINE) + ->setUseDescriptionId(IDS_DESC_VINE) + ->sendTileData(); + Tile::fenceGate = (new FenceGateTile(107)) + ->setDestroyTime(2.0f) + ->setExplodeable(5) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"fenceGate") + ->setDescriptionId(IDS_TILE_FENCE_GATE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_FENCE_GATE); - Tile::mycel = (MycelTile *)(new MycelTile(110)) ->setDestroyTime(0.6f)->setSoundType(SOUND_GRASS)->setTextureName(L"mycel")->setDescriptionId(IDS_TILE_MYCEL)->setUseDescriptionId(IDS_DESC_MYCEL); - Tile::waterLily = (new WaterlilyTile(111)) ->setDestroyTime(0.0f)->setSoundType(SOUND_GRASS)->setTextureName(L"waterlily")->setDescriptionId(IDS_TILE_WATERLILY)->setUseDescriptionId(IDS_DESC_WATERLILY); - Tile::netherBrick = (new Tile(112, Material::stone)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_netherbrick)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(SOUND_STONE)->setTextureName(L"netherBrick")->setDescriptionId(IDS_TILE_NETHERBRICK)->setUseDescriptionId(IDS_DESC_NETHERBRICK); - Tile::netherFence = (new FenceTile(113, L"netherBrick", Material::stone))->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, Item::eMaterial_netherbrick)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(SOUND_STONE)->setTextureName(L"netherFence")->setDescriptionId(IDS_TILE_NETHERFENCE)->setUseDescriptionId(IDS_DESC_NETHERFENCE); - Tile::stairs_netherBricks = (new StairTile(114, Tile::netherBrick,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_netherbrick)->setTextureName(L"stairsNetherBrick")->setDescriptionId(IDS_TILE_STAIRS_NETHERBRICK) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::netherStalk = (new NetherStalkTile(115)) ->setTextureName(L"netherStalk")->setDescriptionId(IDS_TILE_NETHERSTALK)->sendTileData()->setUseDescriptionId(IDS_DESC_NETHERSTALK); - Tile::enchantTable = (new EnchantmentTableTile(116)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, Item::eMaterial_magic)->setDestroyTime(5.0f)->setExplodeable(2000)->setTextureName(L"enchantmentTable")->setDescriptionId(IDS_TILE_ENCHANTMENTTABLE)->setUseDescriptionId(IDS_DESC_ENCHANTMENTTABLE); - Tile::brewingStand = (new BrewingStandTile(117)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, Item::eMaterial_blaze)->setDestroyTime(0.5f)->setLightEmission(2 / 16.0f)->setTextureName(L"brewingStand")->setDescriptionId(IDS_TILE_BREWINGSTAND)->sendTileData()->setUseDescriptionId(IDS_DESC_BREWING_STAND); - Tile::cauldron = (CauldronTile *)(new CauldronTile(118)) ->setDestroyTime(2.0f)->setTextureName(L"cauldron")->setDescriptionId(IDS_TILE_CAULDRON)->sendTileData()->setUseDescriptionId(IDS_DESC_CAULDRON); - Tile::endPortalTile = (new TheEndPortal(119, Material::portal)) ->setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME)->setExplodeable(6000000)->setDescriptionId(IDS_TILE_END_PORTAL)->setUseDescriptionId(IDS_DESC_END_PORTAL); - Tile::endPortalFrameTile = (new TheEndPortalFrameTile(120)) ->setSoundType(SOUND_GLASS)->setLightEmission(2 / 16.0f)->setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME)->setTextureName(L"endPortalFrame")->setDescriptionId(IDS_TILE_ENDPORTALFRAME)->sendTileData()->setExplodeable(6000000)->setUseDescriptionId(IDS_DESC_ENDPORTALFRAME); - Tile::whiteStone = (new Tile(121, Material::stone)) ->setDestroyTime(3.0f)->setExplodeable(15)->setSoundType(SOUND_STONE)->setTextureName(L"whiteStone")->setDescriptionId(IDS_TILE_WHITESTONE)->setUseDescriptionId(IDS_DESC_WHITESTONE); - Tile::dragonEgg = (new EggTile(122)) ->setDestroyTime(3.0f)->setExplodeable(15)->setSoundType(SOUND_STONE)->setLightEmission(2.0f / 16.0f)->setTextureName(L"dragonEgg")->setDescriptionId(IDS_TILE_DRAGONEGG)->setUseDescriptionId(IDS_DESC_DRAGONEGG); - Tile::redstoneLight = (new RedlightTile(123, false)) ->setDestroyTime(0.3f)->setSoundType(SOUND_GLASS)->setTextureName(L"redstoneLight")->setDescriptionId(IDS_TILE_REDSTONE_LIGHT)->setUseDescriptionId(IDS_DESC_REDSTONE_LIGHT); - Tile::redstoneLight_lit = (new RedlightTile(124, true)) ->setDestroyTime(0.3f)->setSoundType(SOUND_GLASS)->setTextureName(L"redstoneLight")->setDescriptionId(IDS_TILE_REDSTONE_LIGHT)->setUseDescriptionId(IDS_DESC_REDSTONE_LIGHT); + Tile::stairs_wood = + (new StairTile(53, Tile::wood, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_wood) + ->setTextureName(L"stairsWood") + ->setDescriptionId(IDS_TILE_STAIRS_WOOD) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::stairs_stone = + (new StairTile(67, Tile::stoneBrick, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_stone) + ->setTextureName(L"stairsStone") + ->setDescriptionId(IDS_TILE_STAIRS_STONE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::stairs_bricks = + (new StairTile(108, Tile::redBrick, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_brick) + ->setTextureName(L"stairsBrick") + ->setDescriptionId(IDS_TILE_STAIRS_BRICKS) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::stairs_stoneBrickSmooth = + (new StairTile(109, Tile::stoneBrickSmooth, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_stoneSmooth) + ->setTextureName(L"stairsStoneBrickSmooth") + ->setDescriptionId(IDS_TILE_STAIRS_STONE_BRICKS_SMOOTH) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); - // TU9 - Tile::stairs_sandstone = (new StairTile(128, Tile::sandStone,0)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_sand) ->setTextureName(L"stairsSandstone")->setDescriptionId(IDS_TILE_STAIRS_SANDSTONE) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::woodStairsDark = (new StairTile(134, Tile::wood, TreeTile::DARK_TRUNK)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_sprucewood)->setTextureName(L"stairsWoodSpruce")->setDescriptionId(IDS_TILE_STAIRS_SPRUCEWOOD) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::woodStairsBirch = (new StairTile(135, Tile::wood, TreeTile::BIRCH_TRUNK)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_birchwood)->setTextureName(L"stairsWoodBirch")->setDescriptionId(IDS_TILE_STAIRS_BIRCHWOOD) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::woodStairsJungle = (new StairTile(136, Tile::wood, TreeTile::JUNGLE_TRUNK))->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_junglewood)->setTextureName(L"stairsWoodJungle")->setDescriptionId(IDS_TILE_STAIRS_JUNGLEWOOD) ->sendTileData()->setUseDescriptionId(IDS_DESC_STAIRS); - Tile::button_wood = (new ButtonTile(143, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_button, Item::eMaterial_wood)->setDestroyTime(0.5f)->setSoundType(Tile::SOUND_WOOD)->setTextureName(L"button")->setDescriptionId(IDS_TILE_BUTTON)->sendTileData()->setUseDescriptionId(IDS_DESC_BUTTON); + Tile::mycel = (MycelTile*)(new MycelTile(110)) + ->setDestroyTime(0.6f) + ->setSoundType(SOUND_GRASS) + ->setTextureName(L"mycel") + ->setDescriptionId(IDS_TILE_MYCEL) + ->setUseDescriptionId(IDS_DESC_MYCEL); + Tile::waterLily = (new WaterlilyTile(111)) + ->setDestroyTime(0.0f) + ->setSoundType(SOUND_GRASS) + ->setTextureName(L"waterlily") + ->setDescriptionId(IDS_TILE_WATERLILY) + ->setUseDescriptionId(IDS_DESC_WATERLILY); + Tile::netherBrick = + (new Tile(112, Material::stone)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_netherbrick) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"netherBrick") + ->setDescriptionId(IDS_TILE_NETHERBRICK) + ->setUseDescriptionId(IDS_DESC_NETHERBRICK); + Tile::netherFence = + (new FenceTile(113, L"netherBrick", Material::stone)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, + Item::eMaterial_netherbrick) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"netherFence") + ->setDescriptionId(IDS_TILE_NETHERFENCE) + ->setUseDescriptionId(IDS_DESC_NETHERFENCE); + Tile::stairs_netherBricks = + (new StairTile(114, Tile::netherBrick, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_netherbrick) + ->setTextureName(L"stairsNetherBrick") + ->setDescriptionId(IDS_TILE_STAIRS_NETHERBRICK) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::netherStalk = (new NetherStalkTile(115)) + ->setTextureName(L"netherStalk") + ->setDescriptionId(IDS_TILE_NETHERSTALK) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_NETHERSTALK); + Tile::enchantTable = + (new EnchantmentTableTile(116)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, + Item::eMaterial_magic) + ->setDestroyTime(5.0f) + ->setExplodeable(2000) + ->setTextureName(L"enchantmentTable") + ->setDescriptionId(IDS_TILE_ENCHANTMENTTABLE) + ->setUseDescriptionId(IDS_DESC_ENCHANTMENTTABLE); + Tile::brewingStand = + (new BrewingStandTile(117)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, + Item::eMaterial_blaze) + ->setDestroyTime(0.5f) + ->setLightEmission(2 / 16.0f) + ->setTextureName(L"brewingStand") + ->setDescriptionId(IDS_TILE_BREWINGSTAND) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_BREWING_STAND); + Tile::cauldron = (CauldronTile*)(new CauldronTile(118)) + ->setDestroyTime(2.0f) + ->setTextureName(L"cauldron") + ->setDescriptionId(IDS_TILE_CAULDRON) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_CAULDRON); + Tile::endPortalTile = (new TheEndPortal(119, Material::portal)) + ->setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME) + ->setExplodeable(6000000) + ->setDescriptionId(IDS_TILE_END_PORTAL) + ->setUseDescriptionId(IDS_DESC_END_PORTAL); + Tile::endPortalFrameTile = + (new TheEndPortalFrameTile(120)) + ->setSoundType(SOUND_GLASS) + ->setLightEmission(2 / 16.0f) + ->setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME) + ->setTextureName(L"endPortalFrame") + ->setDescriptionId(IDS_TILE_ENDPORTALFRAME) + ->sendTileData() + ->setExplodeable(6000000) + ->setUseDescriptionId(IDS_DESC_ENDPORTALFRAME); + Tile::whiteStone = (new Tile(121, Material::stone)) + ->setDestroyTime(3.0f) + ->setExplodeable(15) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"whiteStone") + ->setDescriptionId(IDS_TILE_WHITESTONE) + ->setUseDescriptionId(IDS_DESC_WHITESTONE); + Tile::dragonEgg = (new EggTile(122)) + ->setDestroyTime(3.0f) + ->setExplodeable(15) + ->setSoundType(SOUND_STONE) + ->setLightEmission(2.0f / 16.0f) + ->setTextureName(L"dragonEgg") + ->setDescriptionId(IDS_TILE_DRAGONEGG) + ->setUseDescriptionId(IDS_DESC_DRAGONEGG); + Tile::redstoneLight = (new RedlightTile(123, false)) + ->setDestroyTime(0.3f) + ->setSoundType(SOUND_GLASS) + ->setTextureName(L"redstoneLight") + ->setDescriptionId(IDS_TILE_REDSTONE_LIGHT) + ->setUseDescriptionId(IDS_DESC_REDSTONE_LIGHT); + Tile::redstoneLight_lit = + (new RedlightTile(124, true)) + ->setDestroyTime(0.3f) + ->setSoundType(SOUND_GLASS) + ->setTextureName(L"redstoneLight") + ->setDescriptionId(IDS_TILE_REDSTONE_LIGHT) + ->setUseDescriptionId(IDS_DESC_REDSTONE_LIGHT); - Tile::woodSlab = (HalfSlabTile *) (new WoodSlabTile(Tile::woodSlab_Id, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(SOUND_WOOD)->setTextureName(L"woodSlab")->setDescriptionId(IDS_DESC_WOODSLAB)->setUseDescriptionId(IDS_DESC_WOODSLAB); - Tile::woodSlabHalf = (HalfSlabTile *) (new WoodSlabTile(Tile::woodSlabHalf_Id, false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, Item::eMaterial_wood)->setDestroyTime(2.0f)->setExplodeable(5)->setSoundType(SOUND_WOOD)->setTextureName(L"woodSlab")->setDescriptionId(IDS_DESC_WOODSLAB)->setUseDescriptionId(IDS_DESC_WOODSLAB); - Tile::stoneSlab = (HalfSlabTile *) (new StoneSlabTile(Tile::stoneSlab_Id, true)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"stoneSlab")->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_SLAB); - Tile::stoneSlabHalf = (HalfSlabTile *) (new StoneSlabTile(Tile::stoneSlabHalf_Id, false)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, Item::eMaterial_stone)->setDestroyTime(2.0f)->setExplodeable(10)->setSoundType(Tile::SOUND_STONE)->setTextureName(L"stoneSlab")->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_HALFSLAB); + // TU9 + Tile::stairs_sandstone = + (new StairTile(128, Tile::sandStone, 0)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_sand) + ->setTextureName(L"stairsSandstone") + ->setDescriptionId(IDS_TILE_STAIRS_SANDSTONE) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::woodStairsDark = + (new StairTile(134, Tile::wood, TreeTile::DARK_TRUNK)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_sprucewood) + ->setTextureName(L"stairsWoodSpruce") + ->setDescriptionId(IDS_TILE_STAIRS_SPRUCEWOOD) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::woodStairsBirch = + (new StairTile(135, Tile::wood, TreeTile::BIRCH_TRUNK)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_birchwood) + ->setTextureName(L"stairsWoodBirch") + ->setDescriptionId(IDS_TILE_STAIRS_BIRCHWOOD) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::woodStairsJungle = + (new StairTile(136, Tile::wood, TreeTile::JUNGLE_TRUNK)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_junglewood) + ->setTextureName(L"stairsWoodJungle") + ->setDescriptionId(IDS_TILE_STAIRS_JUNGLEWOOD) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::button_wood = + (new ButtonTile(143, true)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_button, + Item::eMaterial_wood) + ->setDestroyTime(0.5f) + ->setSoundType(Tile::SOUND_WOOD) + ->setTextureName(L"button") + ->setDescriptionId(IDS_TILE_BUTTON) + ->sendTileData() + ->setUseDescriptionId(IDS_DESC_BUTTON); - Tile::emeraldOre = (new OreTile(129)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(SOUND_STONE)->setTextureName(L"oreEmerald")->setDescriptionId(IDS_TILE_EMERALDORE)->setUseDescriptionId(IDS_DESC_EMERALDORE); - Tile::enderChest = (new EnderChestTile(130)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_chest, Item::eMaterial_ender)->setDestroyTime(22.5f)->setExplodeable(1000)->setSoundType(SOUND_STONE)->setTextureName(L"enderChest")->sendTileData()->setLightEmission(.5f)->setDescriptionId(IDS_TILE_ENDERCHEST)->setUseDescriptionId(IDS_DESC_ENDERCHEST); - Tile::tripWireSource = (TripWireSourceTile *)( new TripWireSourceTile(131) ) ->setTextureName(L"tripWireSource")->sendTileData()->setDescriptionId(IDS_TILE_TRIPWIRE_SOURCE)->setUseDescriptionId(IDS_DESC_TRIPWIRE_SOURCE); - Tile::tripWire = (new TripWireTile(132)) ->setTextureName(L"tripWire")->sendTileData()->setDescriptionId(IDS_TILE_TRIPWIRE)->setUseDescriptionId(IDS_DESC_TRIPWIRE); - Tile::emeraldBlock = (new MetalTile(133)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_emerald)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setTextureName(L"blockEmerald")->setDescriptionId(IDS_TILE_EMERALDBLOCK)->setUseDescriptionId(IDS_DESC_EMERALDBLOCK); - + Tile::woodSlab = (HalfSlabTile*)(new WoodSlabTile(Tile::woodSlab_Id, true)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, + Item::eMaterial_wood) + ->setDestroyTime(2.0f) + ->setExplodeable(5) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"woodSlab") + ->setDescriptionId(IDS_DESC_WOODSLAB) + ->setUseDescriptionId(IDS_DESC_WOODSLAB); + Tile::woodSlabHalf = + (HalfSlabTile*)(new WoodSlabTile(Tile::woodSlabHalf_Id, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, + Item::eMaterial_wood) + ->setDestroyTime(2.0f) + ->setExplodeable(5) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"woodSlab") + ->setDescriptionId(IDS_DESC_WOODSLAB) + ->setUseDescriptionId(IDS_DESC_WOODSLAB); + Tile::stoneSlab = + (HalfSlabTile*)(new StoneSlabTile(Tile::stoneSlab_Id, true)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_slab, + Item::eMaterial_stone) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"stoneSlab") + ->setDescriptionId(IDS_TILE_STONESLAB) + ->setUseDescriptionId(IDS_DESC_SLAB); + Tile::stoneSlabHalf = + (HalfSlabTile*)(new StoneSlabTile(Tile::stoneSlabHalf_Id, false)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_halfslab, + Item::eMaterial_stone) + ->setDestroyTime(2.0f) + ->setExplodeable(10) + ->setSoundType(Tile::SOUND_STONE) + ->setTextureName(L"stoneSlab") + ->setDescriptionId(IDS_TILE_STONESLAB) + ->setUseDescriptionId(IDS_DESC_HALFSLAB); - Tile::cocoa = (new CocoaTile(127)) ->setDestroyTime(0.2f)->setExplodeable(5)->setSoundType(SOUND_WOOD)->setTextureName(L"cocoa")->sendTileData()->setDescriptionId(IDS_TILE_COCOA)->setUseDescriptionId(IDS_DESC_COCOA); - Tile::skull = (new SkullTile(144)) ->setDestroyTime(1.0f)->setSoundType(SOUND_STONE)->setTextureName(L"skull")->setDescriptionId(IDS_TILE_SKULL)->setUseDescriptionId(IDS_DESC_SKULL); + Tile::emeraldOre = (new OreTile(129)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"oreEmerald") + ->setDescriptionId(IDS_TILE_EMERALDORE) + ->setUseDescriptionId(IDS_DESC_EMERALDORE); + Tile::enderChest = (new EnderChestTile(130)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_chest, Item::eMaterial_ender) + ->setDestroyTime(22.5f) + ->setExplodeable(1000) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"enderChest") + ->sendTileData() + ->setLightEmission(.5f) + ->setDescriptionId(IDS_TILE_ENDERCHEST) + ->setUseDescriptionId(IDS_DESC_ENDERCHEST); + Tile::tripWireSource = (TripWireSourceTile*)(new TripWireSourceTile(131)) + ->setTextureName(L"tripWireSource") + ->sendTileData() + ->setDescriptionId(IDS_TILE_TRIPWIRE_SOURCE) + ->setUseDescriptionId(IDS_DESC_TRIPWIRE_SOURCE); + Tile::tripWire = (new TripWireTile(132)) + ->setTextureName(L"tripWire") + ->sendTileData() + ->setDescriptionId(IDS_TILE_TRIPWIRE) + ->setUseDescriptionId(IDS_DESC_TRIPWIRE); + Tile::emeraldBlock = + (new MetalTile(133)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, + Item::eMaterial_emerald) + ->setDestroyTime(5.0f) + ->setExplodeable(10) + ->setSoundType(SOUND_METAL) + ->setTextureName(L"blockEmerald") + ->setDescriptionId(IDS_TILE_EMERALDBLOCK) + ->setUseDescriptionId(IDS_DESC_EMERALDBLOCK); - Tile::cobbleWall = (new WallTile(139, Tile::stoneBrick)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_fence, Item::eMaterial_stone)->setTextureName(L"cobbleWall")->setDescriptionId(IDS_TILE_COBBLESTONE_WALL)->setUseDescriptionId(IDS_DESC_COBBLESTONE_WALL); - Tile::flowerPot = (new FlowerPotTile(140)) ->setDestroyTime(0.0f)->setSoundType(SOUND_NORMAL)->setTextureName(L"flowerPot")->setDescriptionId(IDS_TILE_FLOWERPOT)->setUseDescriptionId(IDS_DESC_FLOWERPOT); - Tile::carrots = (new CarrotTile(141)) ->setTextureName(L"carrots")->setDescriptionId(IDS_TILE_CARROTS)->setUseDescriptionId(IDS_DESC_CARROTS)->disableMipmap(); - Tile::potatoes = (new PotatoTile(142)) ->setTextureName(L"potatoes")->setDescriptionId(IDS_TILE_POTATOES)->setUseDescriptionId(IDS_DESC_POTATO)->disableMipmap(); - Tile::anvil = (new AnvilTile(145)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, Item::eMaterial_iron)->setDestroyTime(5.0f)->setSoundType(SOUND_ANVIL)->setExplodeable(2000)->setTextureName(L"anvil")->sendTileData()->setDescriptionId(IDS_TILE_ANVIL)->setUseDescriptionId(IDS_DESC_ANVIL); - Tile::netherQuartz = (new OreTile(153)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(SOUND_STONE)->setTextureName(L"netherquartz")->setDescriptionId(IDS_TILE_NETHER_QUARTZ)->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ_ORE); - Tile::quartzBlock = (new QuartzBlockTile(155)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_quartz)->setSoundType(SOUND_STONE)->setDestroyTime(0.8f)->setTextureName(L"quartzBlock")->setDescriptionId(IDS_TILE_QUARTZ_BLOCK)->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); - Tile::stairs_quartz = (new StairTile(156, Tile::quartzBlock, QuartzBlockTile::TYPE_DEFAULT)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, Item::eMaterial_quartz)->setTextureName(L"stairsQuartz")->setDescriptionId(IDS_TILE_STAIRS_QUARTZ)->setUseDescriptionId(IDS_DESC_STAIRS); + Tile::cocoa = (new CocoaTile(127)) + ->setDestroyTime(0.2f) + ->setExplodeable(5) + ->setSoundType(SOUND_WOOD) + ->setTextureName(L"cocoa") + ->sendTileData() + ->setDescriptionId(IDS_TILE_COCOA) + ->setUseDescriptionId(IDS_DESC_COCOA); + Tile::skull = (new SkullTile(144)) + ->setDestroyTime(1.0f) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"skull") + ->setDescriptionId(IDS_TILE_SKULL) + ->setUseDescriptionId(IDS_DESC_SKULL); - Tile::woolCarpet = (new WoolCarpetTile(171)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_carpet, Item::eMaterial_cloth)->setDestroyTime(0.1f)->setSoundType(SOUND_CLOTH)->setTextureName(L"woolCarpet")->setLightBlock(0)->setDescriptionId(IDS_TILE_CARPET)->setUseDescriptionId(IDS_DESC_CARPET); + Tile::cobbleWall = (new WallTile(139, Tile::stoneBrick)) + ->setBaseItemTypeAndMaterial( + Item::eBaseItemType_fence, Item::eMaterial_stone) + ->setTextureName(L"cobbleWall") + ->setDescriptionId(IDS_TILE_COBBLESTONE_WALL) + ->setUseDescriptionId(IDS_DESC_COBBLESTONE_WALL); + Tile::flowerPot = (new FlowerPotTile(140)) + ->setDestroyTime(0.0f) + ->setSoundType(SOUND_NORMAL) + ->setTextureName(L"flowerPot") + ->setDescriptionId(IDS_TILE_FLOWERPOT) + ->setUseDescriptionId(IDS_DESC_FLOWERPOT); + Tile::carrots = (new CarrotTile(141)) + ->setTextureName(L"carrots") + ->setDescriptionId(IDS_TILE_CARROTS) + ->setUseDescriptionId(IDS_DESC_CARROTS) + ->disableMipmap(); + Tile::potatoes = (new PotatoTile(142)) + ->setTextureName(L"potatoes") + ->setDescriptionId(IDS_TILE_POTATOES) + ->setUseDescriptionId(IDS_DESC_POTATO) + ->disableMipmap(); + Tile::anvil = (new AnvilTile(145)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_device, + Item::eMaterial_iron) + ->setDestroyTime(5.0f) + ->setSoundType(SOUND_ANVIL) + ->setExplodeable(2000) + ->setTextureName(L"anvil") + ->sendTileData() + ->setDescriptionId(IDS_TILE_ANVIL) + ->setUseDescriptionId(IDS_DESC_ANVIL); + Tile::netherQuartz = (new OreTile(153)) + ->setDestroyTime(3.0f) + ->setExplodeable(5) + ->setSoundType(SOUND_STONE) + ->setTextureName(L"netherquartz") + ->setDescriptionId(IDS_TILE_NETHER_QUARTZ) + ->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ_ORE); + Tile::quartzBlock = + (new QuartzBlockTile(155)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, + Item::eMaterial_quartz) + ->setSoundType(SOUND_STONE) + ->setDestroyTime(0.8f) + ->setTextureName(L"quartzBlock") + ->setDescriptionId(IDS_TILE_QUARTZ_BLOCK) + ->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); + Tile::stairs_quartz = + (new StairTile(156, Tile::quartzBlock, QuartzBlockTile::TYPE_DEFAULT)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_stairs, + Item::eMaterial_quartz) + ->setTextureName(L"stairsQuartz") + ->setDescriptionId(IDS_TILE_STAIRS_QUARTZ) + ->setUseDescriptionId(IDS_DESC_STAIRS); - // Special cases for certain items since they can have different icons - Item::items[Tile::cloth_Id] = ( new ClothTileItem(Tile::cloth_Id- 256) )->setTextureName(L"cloth")->setDescriptionId(IDS_TILE_CLOTH)->setUseDescriptionId(IDS_DESC_WOOL); - Item::items[Tile::woolCarpet_Id] = ( new ClothTileItem(Tile::woolCarpet_Id - 256))->setTextureName(L"woolCarpet")->setDescriptionId(IDS_TILE_CARPET)->setUseDescriptionId(IDS_DESC_CARPET); - Item::items[Tile::treeTrunk_Id] = ( new TreeTileItem(Tile::treeTrunk_Id - 256, treeTrunk) )->setTextureName(L"log")->setDescriptionId(IDS_TILE_LOG)->setUseDescriptionId(IDS_DESC_LOG); - Item::items[Tile::wood_Id] = ( new MultiTextureTileItem(Tile::wood_Id - 256, Tile::wood, (int *)WoodTile::WOOD_NAMES, 4))->setTextureName(L"wood")->setDescriptionId(IDS_TILE_OAKWOOD_PLANKS)->setUseDescriptionId(IDS_DESC_LOG); // <- TODO - Item::items[Tile::monsterStoneEgg_Id] = ( new StoneMonsterTileItem(Tile::monsterStoneEgg_Id - 256))->setTextureName(L"monsterStoneEgg")->setDescriptionId(IDS_TILE_STONE_SILVERFISH)->setUseDescriptionId(IDS_DESC_STONE_SILVERFISH); // 4J - Brought forward from post-1.2 to fix stacking problem - Item::items[Tile::stoneBrickSmooth_Id] = ( new SmoothStoneBrickTileItem(Tile::stoneBrickSmooth_Id - 256, stoneBrickSmooth))->setTextureName(L"stonebricksmooth")->setDescriptionId(IDS_TILE_STONE_BRICK_SMOOTH); - Item::items[Tile::sandStone_Id] = ( new MultiTextureTileItem(sandStone_Id - 256, sandStone, SandStoneTile::SANDSTONE_NAMES, SandStoneTile::SANDSTONE_BLOCK_NAMES) )->setTextureName(L"sandStone")->setDescriptionId(IDS_TILE_SANDSTONE)->setUseDescriptionId(IDS_DESC_SANDSTONE); - Item::items[Tile::quartzBlock_Id] = ( new MultiTextureTileItem(quartzBlock_Id - 256, quartzBlock, QuartzBlockTile::BLOCK_NAMES, QuartzBlockTile::QUARTZ_BLOCK_NAMES) )->setTextureName(L"quartzBlock")->setDescriptionId(IDS_TILE_QUARTZ_BLOCK)->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); - Item::items[Tile::stoneSlabHalf_Id] = ( new StoneSlabTileItem(Tile::stoneSlabHalf_Id - 256, Tile::stoneSlabHalf, Tile::stoneSlab, false) )->setTextureName(L"stoneSlab")->setDescriptionId(IDS_TILE_STONESLAB)->setUseDescriptionId(IDS_DESC_HALFSLAB); - Item::items[Tile::stoneSlab_Id] = ( new StoneSlabTileItem(Tile::stoneSlab_Id - 256, Tile::stoneSlabHalf, Tile::stoneSlab, true))->setTextureName(L"stoneSlab")->setDescriptionId(IDS_DESC_STONESLAB)->setUseDescriptionId(IDS_DESC_SLAB); - Item::items[Tile::woodSlabHalf_Id] = ( new StoneSlabTileItem(Tile::woodSlabHalf_Id - 256, Tile::woodSlabHalf, Tile::woodSlab, false))->setTextureName(L"woodSlab")->setDescriptionId(IDS_DESC_WOODSLAB)->setUseDescriptionId(IDS_DESC_WOODSLAB); - Item::items[Tile::woodSlab_Id] = ( new StoneSlabTileItem(Tile::woodSlab_Id - 256, Tile::woodSlabHalf, Tile::woodSlab, true))->setTextureName(L"woodSlab")->setDescriptionId(IDS_DESC_WOODSLAB)->setUseDescriptionId(IDS_DESC_WOODSLAB); - Item::items[Tile::sapling_Id] = ( new SaplingTileItem(Tile::sapling_Id - 256) )->setTextureName(L"sapling")->setDescriptionId(IDS_TILE_SAPLING)->setUseDescriptionId(IDS_DESC_SAPLING); - Item::items[Tile::leaves_Id] = ( new LeafTileItem(Tile::leaves_Id - 256) )->setTextureName(L"leaves")->setDescriptionId(IDS_TILE_LEAVES)->setUseDescriptionId(IDS_DESC_LEAVES); - Item::items[Tile::vine_Id] = ( new ColoredTileItem(Tile::vine_Id - 256, false))->setDescriptionId(IDS_TILE_VINE)->setUseDescriptionId(IDS_DESC_VINE); - int idsData[3] = {IDS_TILE_SHRUB, IDS_TILE_GRASS, IDS_TILE_FERN}; - intArray ids = intArray(idsData, 3); - Item::items[Tile::tallgrass_Id] = ((ColoredTileItem *)(new ColoredTileItem(Tile::tallgrass_Id - 256, true))->setDescriptionId(IDS_TILE_TALL_GRASS))->setDescriptionPostfixes(ids); - Item::items[Tile::waterLily_Id] = ( new WaterLilyTileItem(Tile::waterLily_Id - 256)); - Item::items[Tile::pistonBase_Id] = ( new PistonTileItem(Tile::pistonBase_Id - 256) )->setDescriptionId(IDS_TILE_PISTON_BASE)->setUseDescriptionId(IDS_DESC_PISTON); - Item::items[Tile::pistonStickyBase_Id] = ( new PistonTileItem(Tile::pistonStickyBase_Id - 256) )->setDescriptionId(IDS_TILE_PISTON_STICK_BASE)->setUseDescriptionId(IDS_DESC_STICKY_PISTON); - Item::items[Tile::cobbleWall_Id] = ( new MultiTextureTileItem(cobbleWall_Id - 256, cobbleWall, (int *)WallTile::COBBLE_NAMES, 2) )->setDescriptionId(IDS_TILE_COBBLESTONE_WALL)->setUseDescriptionId(IDS_DESC_COBBLESTONE_WALL); - Item::items[Tile::anvil_Id] = ( new AnvilTileItem(anvil) )->setDescriptionId(IDS_TILE_ANVIL)->setUseDescriptionId(IDS_DESC_ANVIL); + Tile::woolCarpet = + (new WoolCarpetTile(171)) + ->setBaseItemTypeAndMaterial(Item::eBaseItemType_carpet, + Item::eMaterial_cloth) + ->setDestroyTime(0.1f) + ->setSoundType(SOUND_CLOTH) + ->setTextureName(L"woolCarpet") + ->setLightBlock(0) + ->setDescriptionId(IDS_TILE_CARPET) + ->setUseDescriptionId(IDS_DESC_CARPET); + // Special cases for certain items since they can have different icons + Item::items[Tile::cloth_Id] = (new ClothTileItem(Tile::cloth_Id - 256)) + ->setTextureName(L"cloth") + ->setDescriptionId(IDS_TILE_CLOTH) + ->setUseDescriptionId(IDS_DESC_WOOL); + Item::items[Tile::woolCarpet_Id] = + (new ClothTileItem(Tile::woolCarpet_Id - 256)) + ->setTextureName(L"woolCarpet") + ->setDescriptionId(IDS_TILE_CARPET) + ->setUseDescriptionId(IDS_DESC_CARPET); + Item::items[Tile::treeTrunk_Id] = + (new TreeTileItem(Tile::treeTrunk_Id - 256, treeTrunk)) + ->setTextureName(L"log") + ->setDescriptionId(IDS_TILE_LOG) + ->setUseDescriptionId(IDS_DESC_LOG); + Item::items[Tile::wood_Id] = + (new MultiTextureTileItem(Tile::wood_Id - 256, Tile::wood, + (int*)WoodTile::WOOD_NAMES, 4)) + ->setTextureName(L"wood") + ->setDescriptionId(IDS_TILE_OAKWOOD_PLANKS) + ->setUseDescriptionId(IDS_DESC_LOG); // <- TODO + Item::items[Tile::monsterStoneEgg_Id] = + (new StoneMonsterTileItem(Tile::monsterStoneEgg_Id - 256)) + ->setTextureName(L"monsterStoneEgg") + ->setDescriptionId(IDS_TILE_STONE_SILVERFISH) + ->setUseDescriptionId( + IDS_DESC_STONE_SILVERFISH); // 4J - Brought forward from + // post-1.2 to fix stacking problem + Item::items[Tile::stoneBrickSmooth_Id] = + (new SmoothStoneBrickTileItem(Tile::stoneBrickSmooth_Id - 256, + stoneBrickSmooth)) + ->setTextureName(L"stonebricksmooth") + ->setDescriptionId(IDS_TILE_STONE_BRICK_SMOOTH); + Item::items[Tile::sandStone_Id] = + (new MultiTextureTileItem(sandStone_Id - 256, sandStone, + SandStoneTile::SANDSTONE_NAMES, + SandStoneTile::SANDSTONE_BLOCK_NAMES)) + ->setTextureName(L"sandStone") + ->setDescriptionId(IDS_TILE_SANDSTONE) + ->setUseDescriptionId(IDS_DESC_SANDSTONE); + Item::items[Tile::quartzBlock_Id] = + (new MultiTextureTileItem(quartzBlock_Id - 256, quartzBlock, + QuartzBlockTile::BLOCK_NAMES, + QuartzBlockTile::QUARTZ_BLOCK_NAMES)) + ->setTextureName(L"quartzBlock") + ->setDescriptionId(IDS_TILE_QUARTZ_BLOCK) + ->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); + Item::items[Tile::stoneSlabHalf_Id] = + (new StoneSlabTileItem(Tile::stoneSlabHalf_Id - 256, + Tile::stoneSlabHalf, Tile::stoneSlab, false)) + ->setTextureName(L"stoneSlab") + ->setDescriptionId(IDS_TILE_STONESLAB) + ->setUseDescriptionId(IDS_DESC_HALFSLAB); + Item::items[Tile::stoneSlab_Id] = + (new StoneSlabTileItem(Tile::stoneSlab_Id - 256, Tile::stoneSlabHalf, + Tile::stoneSlab, true)) + ->setTextureName(L"stoneSlab") + ->setDescriptionId(IDS_DESC_STONESLAB) + ->setUseDescriptionId(IDS_DESC_SLAB); + Item::items[Tile::woodSlabHalf_Id] = + (new StoneSlabTileItem(Tile::woodSlabHalf_Id - 256, Tile::woodSlabHalf, + Tile::woodSlab, false)) + ->setTextureName(L"woodSlab") + ->setDescriptionId(IDS_DESC_WOODSLAB) + ->setUseDescriptionId(IDS_DESC_WOODSLAB); + Item::items[Tile::woodSlab_Id] = + (new StoneSlabTileItem(Tile::woodSlab_Id - 256, Tile::woodSlabHalf, + Tile::woodSlab, true)) + ->setTextureName(L"woodSlab") + ->setDescriptionId(IDS_DESC_WOODSLAB) + ->setUseDescriptionId(IDS_DESC_WOODSLAB); + Item::items[Tile::sapling_Id] = + (new SaplingTileItem(Tile::sapling_Id - 256)) + ->setTextureName(L"sapling") + ->setDescriptionId(IDS_TILE_SAPLING) + ->setUseDescriptionId(IDS_DESC_SAPLING); + Item::items[Tile::leaves_Id] = (new LeafTileItem(Tile::leaves_Id - 256)) + ->setTextureName(L"leaves") + ->setDescriptionId(IDS_TILE_LEAVES) + ->setUseDescriptionId(IDS_DESC_LEAVES); + Item::items[Tile::vine_Id] = + (new ColoredTileItem(Tile::vine_Id - 256, false)) + ->setDescriptionId(IDS_TILE_VINE) + ->setUseDescriptionId(IDS_DESC_VINE); + int idsData[3] = {IDS_TILE_SHRUB, IDS_TILE_GRASS, IDS_TILE_FERN}; + intArray ids = intArray(idsData, 3); + Item::items[Tile::tallgrass_Id] = + ((ColoredTileItem*)(new ColoredTileItem(Tile::tallgrass_Id - 256, true)) + ->setDescriptionId(IDS_TILE_TALL_GRASS)) + ->setDescriptionPostfixes(ids); + Item::items[Tile::waterLily_Id] = + (new WaterLilyTileItem(Tile::waterLily_Id - 256)); + Item::items[Tile::pistonBase_Id] = + (new PistonTileItem(Tile::pistonBase_Id - 256)) + ->setDescriptionId(IDS_TILE_PISTON_BASE) + ->setUseDescriptionId(IDS_DESC_PISTON); + Item::items[Tile::pistonStickyBase_Id] = + (new PistonTileItem(Tile::pistonStickyBase_Id - 256)) + ->setDescriptionId(IDS_TILE_PISTON_STICK_BASE) + ->setUseDescriptionId(IDS_DESC_STICKY_PISTON); + Item::items[Tile::cobbleWall_Id] = + (new MultiTextureTileItem(cobbleWall_Id - 256, cobbleWall, + (int*)WallTile::COBBLE_NAMES, 2)) + ->setDescriptionId(IDS_TILE_COBBLESTONE_WALL) + ->setUseDescriptionId(IDS_DESC_COBBLESTONE_WALL); + Item::items[Tile::anvil_Id] = (new AnvilTileItem(anvil)) + ->setDescriptionId(IDS_TILE_ANVIL) + ->setUseDescriptionId(IDS_DESC_ANVIL); - for (int i = 0; i < 256; i++) - { - if ( Tile::tiles[i] != NULL ) - { - if( Item::items[i] == NULL) - { - Item::items[i] = new TileItem(i - 256); - Tile::tiles[i]->init(); - } + for (int i = 0; i < 256; i++) { + if (Tile::tiles[i] != NULL) { + if (Item::items[i] == NULL) { + Item::items[i] = new TileItem(i - 256); + Tile::tiles[i]->init(); + } bool propagate = false; - if (i > 0 && Tile::tiles[i]->getRenderShape() == Tile::SHAPE_STAIRS) propagate = true; - if (i > 0 && dynamic_cast(Tile::tiles[i]) != NULL) - { + if (i > 0 && Tile::tiles[i]->getRenderShape() == Tile::SHAPE_STAIRS) + propagate = true; + if (i > 0 && dynamic_cast(Tile::tiles[i]) != NULL) { propagate = true; } if (i == Tile::farmland_Id) propagate = true; - if (Tile::transculent[i]) - { - propagate = true; - } - if (Tile::lightBlock[i] == 0) - { - propagate = true; - } + if (Tile::transculent[i]) { + propagate = true; + } + if (Tile::lightBlock[i] == 0) { + propagate = true; + } Tile::propagate[i] = propagate; - } - } - Tile::transculent[0] = true; + } + } + Tile::transculent[0] = true; - Stats::buildItemStats(); + Stats::buildItemStats(); - // */ + // */ } // 4J - added for common ctor code -void Tile::_init(int id, Material *material, bool isSolidRender) -{ - destroySpeed = 0.0f; - explosionResistance = 0.0f; - isInventoryItem = true; - collectStatistics = true; +void Tile::_init(int id, Material* material, bool isSolidRender) { + destroySpeed = 0.0f; + explosionResistance = 0.0f; + isInventoryItem = true; + collectStatistics = true; - // 4J Stu - Removed these in favour of TLS versions - //xx0 = yy0 = zz0 = xx1 = yy1 = zz1 = 0; + // 4J Stu - Removed these in favour of TLS versions + // xx0 = yy0 = zz0 = xx1 = yy1 = zz1 = 0; - soundType = Tile::SOUND_NORMAL; - gravity = 1.0f; - friction = 0.6f; - _isTicking = false; - _isEntityTile = false; + soundType = Tile::SOUND_NORMAL; + gravity = 1.0f; + friction = 0.6f; + _isTicking = false; + _isEntityTile = false; - /* 4J - TODO - if (Tile.tiles[id] != null) - { - throw new IllegalArgumentException("Slot " + id + " is already occupied by " + Tile.tiles[id] + " when adding " + this); - } - */ - this->material = material; - Tile::tiles[id] = this; - this->id = id; - updateDefaultShape(); - // 4J - note these used to call isSolidRender(), but that always calls Tile::isSolidRender in C++ so have added as a parameter that can be varied from - // derived ctors - solid[id] = isSolidRender; - lightBlock[id] = isSolidRender ? 255 : 0; - transculent[id] = !material->blocksLight(); - mipmapEnable[id] = true; // 4J added - m_textureName = L""; + /* 4J - TODO + if (Tile.tiles[id] != null) + { + throw new IllegalArgumentException("Slot " + id + " is already occupied by " + + Tile.tiles[id] + " when adding " + this); + } + */ + this->material = material; + Tile::tiles[id] = this; + this->id = id; + updateDefaultShape(); + // 4J - note these used to call isSolidRender(), but that always calls + // Tile::isSolidRender in C++ so have added as a parameter that can be + // varied from derived ctors + solid[id] = isSolidRender; + lightBlock[id] = isSolidRender ? 255 : 0; + transculent[id] = !material->blocksLight(); + mipmapEnable[id] = true; // 4J added + m_textureName = L""; } -Tile::Tile(int id, Material *material, bool isSolidRender) -{ - _init(id,material, isSolidRender); - m_iMaterial=Item::eMaterial_undefined; - m_iBaseItemType=Item::eBaseItemType_undefined; - icon = NULL; +Tile::Tile(int id, Material* material, bool isSolidRender) { + _init(id, material, isSolidRender); + m_iMaterial = Item::eMaterial_undefined; + m_iBaseItemType = Item::eBaseItemType_undefined; + icon = NULL; } -Tile *Tile::sendTileData(unsigned char importantMask/*=15*/) -{ - Tile::_sendTileData[id] = importantMask; // 4J - changed was bool, now bitfield to indicate which bits are important to be sent. Default behaviour with this method is all 4 bits - return this; +Tile* Tile::sendTileData(unsigned char importantMask /*=15*/) { + Tile::_sendTileData[id] = + importantMask; // 4J - changed was bool, now bitfield to indicate which + // bits are important to be sent. Default behaviour with + // this method is all 4 bits + return this; } -void Tile::init() -{ +void Tile::init() {} + +// 4J-PB - adding so we can class different items together for the new crafting +// menu so pickaxe_stone would get tagged with pickaxe and stone +Tile* Tile::setBaseItemTypeAndMaterial(int iType, int iMaterial) { + this->m_iBaseItemType = iType; + this->m_iMaterial = iMaterial; + return this; } +int Tile::getBaseItemType() { return this->m_iBaseItemType; } +int Tile::getMaterial() { return this->m_iMaterial; } -// 4J-PB - adding so we can class different items together for the new crafting menu -// so pickaxe_stone would get tagged with pickaxe and stone -Tile *Tile::setBaseItemTypeAndMaterial(int iType,int iMaterial) -{ - this->m_iBaseItemType = iType; - this->m_iMaterial = iMaterial; - return this; +Tile* Tile::setSoundType(const SoundType* soundType) { + this->soundType = soundType; + return this; } -int Tile::getBaseItemType() -{ - return this->m_iBaseItemType; +Tile* Tile::setLightBlock(int i) { + lightBlock[id] = i; + return this; } -int Tile::getMaterial() -{ - return this->m_iMaterial; +Tile* Tile::setLightEmission(float f) { + Tile::lightEmission[id] = (int)(Level::MAX_BRIGHTNESS * f); + return this; } - -Tile *Tile::setSoundType(const SoundType *soundType) -{ - this->soundType = soundType; - return this; +Tile* Tile::setExplodeable(float explosionResistance) { + this->explosionResistance = explosionResistance * 3; + return this; } -Tile *Tile::setLightBlock(int i) -{ - lightBlock[id] = i; - return this; +bool Tile::isSolidBlockingTile(int t) { + Tile* tile = Tile::tiles[t]; + if (tile == NULL) return false; + return tile->material->isSolidBlocking() && tile->isCubeShaped(); } -Tile *Tile::setLightEmission(float f) -{ - Tile::lightEmission[id] = (int) (Level::MAX_BRIGHTNESS * f); - return this; +bool Tile::isCubeShaped() { return true; } + +bool Tile::isPathfindable(LevelSource* level, int x, int y, int z) { + return !material->blocksMotion(); } -Tile *Tile::setExplodeable(float explosionResistance) -{ - this->explosionResistance = explosionResistance * 3; - return this; +int Tile::getRenderShape() { return SHAPE_BLOCK; } + +Tile* Tile::setDestroyTime(float destroySpeed) { + this->destroySpeed = destroySpeed; + if (explosionResistance < destroySpeed * 5) + explosionResistance = destroySpeed * 5; + return this; } -bool Tile::isSolidBlockingTile(int t) -{ - Tile *tile = Tile::tiles[t]; - if (tile == NULL) return false; - return tile->material->isSolidBlocking() && tile->isCubeShaped(); +Tile* Tile::setIndestructible() { + setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME); + return this; } -bool Tile::isCubeShaped() -{ - return true; +float Tile::getDestroySpeed(Level* level, int x, int y, int z) { + return destroySpeed; } -bool Tile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return !material->blocksMotion(); +Tile* Tile::setTicking(bool tick) { + _isTicking = tick; + return this; } -int Tile::getRenderShape() -{ - return SHAPE_BLOCK; +bool Tile::isTicking() { return _isTicking; } + +bool Tile::isEntityTile() { return _isEntityTile; } + +Tile* Tile::disableMipmap() { + mipmapEnable[id] = false; + return this; } -Tile *Tile::setDestroyTime(float destroySpeed) -{ - this->destroySpeed = destroySpeed; - if (explosionResistance < destroySpeed * 5) explosionResistance = destroySpeed * 5; - return this; +void Tile::setShape(float x0, float y0, float z0, float x1, float y1, + float z1) { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + tls->xx0 = x0; + tls->yy0 = y0; + tls->zz0 = z0; + tls->xx1 = x1; + tls->yy1 = y1; + tls->zz1 = z1; + tls->tileId = this->id; + + // this->xx0 = x0; + // this->yy0 = y0; + // this->zz0 = z0; + // this->xx1 = x1; + // this->yy1 = y1; + // this->zz1 = z1; } -Tile *Tile::setIndestructible() -{ - setDestroyTime(INDESTRUCTIBLE_DESTROY_TIME); - return this; -} - -float Tile::getDestroySpeed(Level *level, int x, int y, int z) -{ - return destroySpeed; -} - -Tile *Tile::setTicking(bool tick) -{ - _isTicking = tick; - return this; -} - -bool Tile::isTicking() -{ - return _isTicking; -} - -bool Tile::isEntityTile() -{ - return _isEntityTile; -} - -Tile *Tile::disableMipmap() -{ - mipmapEnable[id] = false; - return this; -} - -void Tile::setShape(float x0, float y0, float z0, float x1, float y1, float z1) -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - tls->xx0 = x0; - tls->yy0 = y0; - tls->zz0 = z0; - tls->xx1 = x1; - tls->yy1 = y1; - tls->zz1 = z1; - tls->tileId = this->id; - - //this->xx0 = x0; - //this->yy0 = y0; - //this->zz0 = z0; - //this->xx1 = x1; - //this->yy1 = y1; - //this->zz1 = z1; -} - -float Tile::getBrightness(LevelSource *level, int x, int y, int z) -{ - // Lighting fix brought forward from ~1.5 here - used to use the lightEmission level for this tile rather than getting the for the passed in x/y/z coords - return level->getBrightness(x, y, z, Tile::lightEmission[level->getTile(x,y,z)]); +float Tile::getBrightness(LevelSource* level, int x, int y, int z) { + // Lighting fix brought forward from ~1.5 here - used to use the + // lightEmission level for this tile rather than getting the for the passed + // in x/y/z coords + return level->getBrightness(x, y, z, + Tile::lightEmission[level->getTile(x, y, z)]); } // 4J - brought forward from 1.8.2 -int Tile::getLightColor(LevelSource *level, int x, int y, int z, int tileId/*=-1*/) -{ - // Lighting fix brought forward from ~1.5 here - used to use the lightEmission level for this tile rather than getting the for the passed in x/y/z coords - if( tileId == -1 ) - { - return level->getLightColor(x, y, z, Tile::lightEmission[level->getTile(x,y,z)], -1); - } - else - { - return level->getLightColor(x, y, z, Tile::lightEmission[tileId], tileId); - } +int Tile::getLightColor(LevelSource* level, int x, int y, int z, + int tileId /*=-1*/) { + // Lighting fix brought forward from ~1.5 here - used to use the + // lightEmission level for this tile rather than getting the for the passed + // in x/y/z coords + if (tileId == -1) { + return level->getLightColor( + x, y, z, Tile::lightEmission[level->getTile(x, y, z)], -1); + } else { + return level->getLightColor(x, y, z, Tile::lightEmission[tileId], + tileId); + } } -bool Tile::isFaceVisible(Level *level, int x, int y, int z, int f) -{ - if (f == 0) y--; - if (f == 1) y++; - if (f == 2) z--; - if (f == 3) z++; - if (f == 4) x--; - if (f == 5) x++; - return !level->isSolidRenderTile(x, y, z); +bool Tile::isFaceVisible(Level* level, int x, int y, int z, int f) { + if (f == 0) y--; + if (f == 1) y++; + if (f == 2) z--; + if (f == 3) z++; + if (f == 4) x--; + if (f == 5) x++; + return !level->isSolidRenderTile(x, y, z); } -bool Tile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - if (face == 0 && tls->yy0 > 0) return true; - if (face == 1 && tls->yy1 < 1) return true; - if (face == 2 && tls->zz0 > 0) return true; - if (face == 3 && tls->zz1 < 1) return true; - if (face == 4 && tls->xx0 > 0) return true; - if (face == 5 && tls->xx1 < 1) return true; - return (!level->isSolidRenderTile(x, y, z)); +bool Tile::shouldRenderFace(LevelSource* level, int x, int y, int z, int face) { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + if (face == 0 && tls->yy0 > 0) return true; + if (face == 1 && tls->yy1 < 1) return true; + if (face == 2 && tls->zz0 > 0) return true; + if (face == 3 && tls->zz1 < 1) return true; + if (face == 4 && tls->xx0 > 0) return true; + if (face == 5 && tls->xx1 < 1) return true; + return (!level->isSolidRenderTile(x, y, z)); } -// AP - added this function so we can generate the faceFlags for a block in a single fast function -int Tile::getFaceFlags(LevelSource *level, int x, int y, int z) -{ - int faceFlags = 0; +// AP - added this function so we can generate the faceFlags for a block in a +// single fast function +int Tile::getFaceFlags(LevelSource* level, int x, int y, int z) { + int faceFlags = 0; - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); - if( tls->yy0 > 0 || (!level->isSolidRenderTile(x, y - 1, z))) faceFlags |= 0x01; - if( tls->yy1 < 1 || (!level->isSolidRenderTile(x, y + 1, z))) faceFlags |= 0x02; - if( tls->zz0 > 0 || (!level->isSolidRenderTile(x, y, z - 1))) faceFlags |= 0x04; - if( tls->zz1 < 1 || (!level->isSolidRenderTile(x, y, z + 1))) faceFlags |= 0x08; - if( tls->xx0 > 0 || (!level->isSolidRenderTile(x - 1, y, z))) faceFlags |= 0x10; - if( tls->xx1 < 1 || (!level->isSolidRenderTile(x + 1, y, z))) faceFlags |= 0x20; + if (tls->yy0 > 0 || (!level->isSolidRenderTile(x, y - 1, z))) + faceFlags |= 0x01; + if (tls->yy1 < 1 || (!level->isSolidRenderTile(x, y + 1, z))) + faceFlags |= 0x02; + if (tls->zz0 > 0 || (!level->isSolidRenderTile(x, y, z - 1))) + faceFlags |= 0x04; + if (tls->zz1 < 1 || (!level->isSolidRenderTile(x, y, z + 1))) + faceFlags |= 0x08; + if (tls->xx0 > 0 || (!level->isSolidRenderTile(x - 1, y, z))) + faceFlags |= 0x10; + if (tls->xx1 < 1 || (!level->isSolidRenderTile(x + 1, y, z))) + faceFlags |= 0x20; - return faceFlags; + return faceFlags; } -bool Tile::isSolidFace(LevelSource *level, int x, int y, int z, int face) -{ - return (level->getMaterial(x, y, z)->isSolid()); +bool Tile::isSolidFace(LevelSource* level, int x, int y, int z, int face) { + return (level->getMaterial(x, y, z)->isSolid()); } -Icon *Tile::getTexture(LevelSource *level, int x, int y, int z, int face) -{ - // 4J - addition here to make rendering big blocks of leaves more efficient. Normally leaves never consider themselves as solid, so - // blocks of leaves will have all sides of each block completely visible. Changing to consider as solid if this block is surrounded by - // other leaves (or solid things). This is paired with another change in Level::isSolidRenderTile/Region::isSolidRenderTile which makes things solid - // code-wise (ie for determining visible sides of neighbouring blocks). This change just makes the texture a solid one (tex + 1) which - // we already have in the texture map for doing non-fancy graphics. Note: this tile-specific code is here rather than making some new virtual - // method in the tiles, for the sake of efficiency - I don't imagine we'll be doing much more of this sort of thing +Icon* Tile::getTexture(LevelSource* level, int x, int y, int z, int face) { + // 4J - addition here to make rendering big blocks of leaves more efficient. + // Normally leaves never consider themselves as solid, so blocks of leaves + // will have all sides of each block completely visible. Changing to + // consider as solid if this block is surrounded by other leaves (or solid + // things). This is paired with another change in + // Level::isSolidRenderTile/Region::isSolidRenderTile which makes things + // solid code-wise (ie for determining visible sides of neighbouring + // blocks). This change just makes the texture a solid one (tex + 1) which + // we already have in the texture map for doing non-fancy graphics. Note: + // this tile-specific code is here rather than making some new virtual + // method in the tiles, for the sake of efficiency - I don't imagine we'll + // be doing much more of this sort of thing - int tileId = level->getTile(x, y, z); - int tileData = level->getData(x, y, z); + int tileId = level->getTile(x, y, z); + int tileData = level->getData(x, y, z); - if( tileId == Tile::leaves_Id ) - { - bool opaque = true; + if (tileId == Tile::leaves_Id) { + bool opaque = true; - int axo[6] = { 1,-1, 0, 0, 0, 0}; - int ayo[6] = { 0, 0, 1,-1, 0, 0}; - int azo[6] = { 0, 0, 0, 0, 1,-1}; - for( int i = 0; (i < 6) && opaque; i++ ) - { - int t = level->getTile(x + axo[i], y + ayo[i] , z + azo[i]); - if( ( t != Tile::leaves_Id ) && ( ( Tile::tiles[t] == NULL ) || !Tile::tiles[t]->isSolidRender() ) ) - { - opaque = false; - } - } + int axo[6] = {1, -1, 0, 0, 0, 0}; + int ayo[6] = {0, 0, 1, -1, 0, 0}; + int azo[6] = {0, 0, 0, 0, 1, -1}; + for (int i = 0; (i < 6) && opaque; i++) { + int t = level->getTile(x + axo[i], y + ayo[i], z + azo[i]); + if ((t != Tile::leaves_Id) && ((Tile::tiles[t] == NULL) || + !Tile::tiles[t]->isSolidRender())) { + opaque = false; + } + } - Icon *icon = NULL; - if(opaque) - { - Tile::leaves->setFancy(false); - icon = getTexture(face, tileData); - Tile::leaves->setFancy(true); - } - else - { - icon = getTexture(face, tileData); - } - return icon; - } - return getTexture(face, tileData); + Icon* icon = NULL; + if (opaque) { + Tile::leaves->setFancy(false); + icon = getTexture(face, tileData); + Tile::leaves->setFancy(true); + } else { + icon = getTexture(face, tileData); + } + return icon; + } + return getTexture(face, tileData); } -Icon *Tile::getTexture(int face, int data) -{ - return icon; +Icon* Tile::getTexture(int face, int data) { return icon; } + +Icon* Tile::getTexture(int face) { return getTexture(face, 0); } + +AABB* Tile::getTileAABB(Level* level, int x, int y, int z) { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, + y + tls->yy1, z + tls->zz1); } -Icon *Tile::getTexture(int face) -{ - return getTexture(face, 0); +void Tile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { + AABB* aabb = getAABB(level, x, y, z); + if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); } -AABB *Tile::getTileAABB(Level *level, int x, int y, int z) -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1); +AABB* Tile::getAABB(Level* level, int x, int y, int z) { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, + y + tls->yy1, z + tls->zz1); } -void Tile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ - AABB *aabb = getAABB(level, x, y, z); - if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); +bool Tile::isSolidRender(bool isServerLevel) { return true; } + +bool Tile::mayPick(int data, bool liquid) { return mayPick(); } + +bool Tile::mayPick() { return true; } + +void Tile::tick(Level* level, int x, int y, int z, Random* random) {} + +void Tile::animateTick(Level* level, int x, int y, int z, Random* random) {} + +void Tile::destroy(Level* level, int x, int y, int z, int data) {} + +void Tile::neighborChanged(Level* level, int x, int y, int z, int type) {} + +void Tile::addLights(Level* level, int x, int y, int z) {} + +int Tile::getTickDelay() { return 10; } + +void Tile::onPlace(Level* level, int x, int y, int z) {} + +void Tile::onRemove(Level* level, int x, int y, int z, int id, int data) {} + +int Tile::getResourceCount(Random* random) { return 1; } + +int Tile::getResource(int data, Random* random, int playerBonusLevel) { + return id; } -AABB *Tile::getAABB(Level *level, int x, int y, int z) -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1); +float Tile::getDestroyProgress(std::shared_ptr player, Level* level, + int x, int y, int z) { + float destroySpeed = getDestroySpeed(level, x, y, z); + if (destroySpeed < 0) return 0; + if (!player->canDestroy(this)) return 1 / destroySpeed / 100.0f; + return (player->getDestroySpeed(this) / destroySpeed) / 30; } -bool Tile::isSolidRender(bool isServerLevel) -{ - return true; +void Tile::spawnResources(Level* level, int x, int y, int z, int data, + int playerBonusLevel) { + spawnResources(level, x, y, z, data, 1, playerBonusLevel); } -bool Tile::mayPick(int data, bool liquid) -{ - return mayPick(); +void Tile::spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel) { + if (level->isClientSide) return; + int count = getResourceCountForLootBonus(playerBonusLevel, level->random); + for (int i = 0; i < count; i++) { + if (level->random->nextFloat() > odds) continue; + int type = getResource(data, level->random, playerBonusLevel); + if (type <= 0) continue; + + popResource(level, x, y, z, + std::shared_ptr(new ItemInstance( + type, 1, getSpawnResourcesAuxValue(data)))); + } } -bool Tile::mayPick() -{ - return true; -} +void Tile::popResource(Level* level, int x, int y, int z, + std::shared_ptr itemInstance) { + if (level->isClientSide) return; -void Tile::tick(Level *level, int x, int y, int z, Random *random) -{ -} - -void Tile::animateTick(Level *level, int x, int y, int z, Random *random) -{ -} - -void Tile::destroy(Level *level, int x, int y, int z, int data) -{ -} - -void Tile::neighborChanged(Level *level, int x, int y, int z, int type) -{ -} - -void Tile::addLights(Level *level, int x, int y, int z) -{ -} - -int Tile::getTickDelay() -{ - return 10; -} - -void Tile::onPlace(Level *level, int x, int y, int z) -{ -} - -void Tile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ -} - -int Tile::getResourceCount(Random *random) -{ - return 1; -} - -int Tile::getResource(int data, Random *random, int playerBonusLevel) -{ - return id; -} - -float Tile::getDestroyProgress(std::shared_ptr player, Level *level, int x, int y, int z) -{ - float destroySpeed = getDestroySpeed(level, x, y, z); - if (destroySpeed < 0) return 0; - if (!player->canDestroy(this)) return 1 / destroySpeed / 100.0f; - return (player->getDestroySpeed(this) / destroySpeed) / 30; -} - -void Tile::spawnResources(Level *level, int x, int y, int z, int data, int playerBonusLevel) -{ - spawnResources(level, x, y, z, data, 1, playerBonusLevel); -} - -void Tile::spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel) -{ - if (level->isClientSide) return; - int count = getResourceCountForLootBonus(playerBonusLevel, level->random); - for (int i = 0; i < count; i++) - { - if (level->random->nextFloat() > odds) continue; - int type = getResource(data, level->random, playerBonusLevel); - if (type <= 0) continue; - - popResource(level, x, y, z, std::shared_ptr( new ItemInstance(type, 1, getSpawnResourcesAuxValue(data) ) ) ); - } -} - -void Tile::popResource(Level *level, int x, int y, int z, std::shared_ptr itemInstance) -{ - if( level->isClientSide ) return; - - float s = 0.7f; - double xo = level->random->nextFloat() * s + (1 - s) * 0.5; - double yo = level->random->nextFloat() * s + (1 - s) * 0.5; - double zo = level->random->nextFloat() * s + (1 - s) * 0.5; - std::shared_ptr item = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, itemInstance ) ); - item->throwTime = 10; - level->addEntity(item); + float s = 0.7f; + double xo = level->random->nextFloat() * s + (1 - s) * 0.5; + double yo = level->random->nextFloat() * s + (1 - s) * 0.5; + double zo = level->random->nextFloat() * s + (1 - s) * 0.5; + std::shared_ptr item = std::shared_ptr( + new ItemEntity(level, x + xo, y + yo, z + zo, itemInstance)); + item->throwTime = 10; + level->addEntity(item); } // Brought forward for TU7 -void Tile::popExperience(Level *level, int x, int y, int z, int amount) -{ - if (!level->isClientSide) - { - while (amount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(amount); - amount -= newCount; - level->addEntity(std::shared_ptr( new ExperienceOrb(level, x + .5, y + .5, z + .5, newCount))); - } - } +void Tile::popExperience(Level* level, int x, int y, int z, int amount) { + if (!level->isClientSide) { + while (amount > 0) { + int newCount = ExperienceOrb::getExperienceValue(amount); + amount -= newCount; + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x + .5, y + .5, z + .5, newCount))); + } + } } -int Tile::getSpawnResourcesAuxValue(int data) -{ - return 0; +int Tile::getSpawnResourcesAuxValue(int data) { return 0; } + +float Tile::getExplosionResistance(std::shared_ptr source) { + return explosionResistance / 5.0f; } -float Tile::getExplosionResistance(std::shared_ptr source) -{ - return explosionResistance / 5.0f; +HitResult* Tile::clip(Level* level, int xt, int yt, int zt, Vec3* a, Vec3* b) { + updateShape(level, xt, yt, zt); + + a = a->add(-xt, -yt, -zt); + b = b->add(-xt, -yt, -zt); + + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + Vec3* xh0 = a->clipX(b, tls->xx0); + Vec3* xh1 = a->clipX(b, tls->xx1); + + Vec3* yh0 = a->clipY(b, tls->yy0); + Vec3* yh1 = a->clipY(b, tls->yy1); + + Vec3* zh0 = a->clipZ(b, tls->zz0); + Vec3* zh1 = a->clipZ(b, tls->zz1); + + Vec3* closest = NULL; + + if (containsX(xh0) && + (closest == NULL || a->distanceToSqr(xh0) < a->distanceToSqr(closest))) + closest = xh0; + if (containsX(xh1) && + (closest == NULL || a->distanceToSqr(xh1) < a->distanceToSqr(closest))) + closest = xh1; + if (containsY(yh0) && + (closest == NULL || a->distanceToSqr(yh0) < a->distanceToSqr(closest))) + closest = yh0; + if (containsY(yh1) && + (closest == NULL || a->distanceToSqr(yh1) < a->distanceToSqr(closest))) + closest = yh1; + if (containsZ(zh0) && + (closest == NULL || a->distanceToSqr(zh0) < a->distanceToSqr(closest))) + closest = zh0; + if (containsZ(zh1) && + (closest == NULL || a->distanceToSqr(zh1) < a->distanceToSqr(closest))) + closest = zh1; + + if (closest == NULL) return NULL; + + int face = -1; + + if (closest == xh0) face = Facing::WEST; + if (closest == xh1) face = Facing::EAST; + if (closest == yh0) face = Facing::DOWN; + if (closest == yh1) face = Facing::UP; + if (closest == zh0) face = Facing::NORTH; + if (closest == zh1) face = Facing::SOUTH; + + return new HitResult(xt, yt, zt, face, closest->add(xt, yt, zt)); } -HitResult *Tile::clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b) -{ - updateShape(level, xt, yt, zt); +bool Tile::containsX(Vec3* v) { + if (v == NULL) return false; - a = a->add(-xt, -yt, -zt); - b = b->add(-xt, -yt, -zt); - - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - Vec3 *xh0 = a->clipX(b, tls->xx0); - Vec3 *xh1 = a->clipX(b, tls->xx1); - - Vec3 *yh0 = a->clipY(b, tls->yy0); - Vec3 *yh1 = a->clipY(b, tls->yy1); - - Vec3 *zh0 = a->clipZ(b, tls->zz0); - Vec3 *zh1 = a->clipZ(b, tls->zz1); - - Vec3 *closest = NULL; - - if (containsX(xh0) && (closest == NULL || a->distanceToSqr(xh0) < a->distanceToSqr(closest))) closest = xh0; - if (containsX(xh1) && (closest == NULL || a->distanceToSqr(xh1) < a->distanceToSqr(closest))) closest = xh1; - if (containsY(yh0) && (closest == NULL || a->distanceToSqr(yh0) < a->distanceToSqr(closest))) closest = yh0; - if (containsY(yh1) && (closest == NULL || a->distanceToSqr(yh1) < a->distanceToSqr(closest))) closest = yh1; - if (containsZ(zh0) && (closest == NULL || a->distanceToSqr(zh0) < a->distanceToSqr(closest))) closest = zh0; - if (containsZ(zh1) && (closest == NULL || a->distanceToSqr(zh1) < a->distanceToSqr(closest))) closest = zh1; - - if (closest == NULL) return NULL; - - int face = -1; - - if (closest == xh0) face = Facing::WEST; - if (closest == xh1) face = Facing::EAST; - if (closest == yh0) face = Facing::DOWN; - if (closest == yh1) face = Facing::UP; - if (closest == zh0) face = Facing::NORTH; - if (closest == zh1) face = Facing::SOUTH; - - return new HitResult(xt, yt, zt, face, closest->add(xt, yt, zt)); + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return v->y >= tls->yy0 && v->y <= tls->yy1 && v->z >= tls->zz0 && + v->z <= tls->zz1; } -bool Tile::containsX(Vec3 *v) -{ - if( v == NULL) return false; - - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return v->y >= tls->yy0 && v->y <= tls->yy1 && v->z >= tls->zz0 && v->z <= tls->zz1; +bool Tile::containsY(Vec3* v) { + if (v == NULL) return false; + + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return v->x >= tls->xx0 && v->x <= tls->xx1 && v->z >= tls->zz0 && + v->z <= tls->zz1; } -bool Tile::containsY(Vec3 *v) -{ - if( v == NULL) return false; +bool Tile::containsZ(Vec3* v) { + if (v == NULL) return false; - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return v->x >= tls->xx0 && v->x <= tls->xx1 && v->z >= tls->zz0 && v->z <= tls->zz1; + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return v->x >= tls->xx0 && v->x <= tls->xx1 && v->y >= tls->yy0 && + v->y <= tls->yy1; } -bool Tile::containsZ(Vec3 *v) -{ - if( v == NULL) return false; +void Tile::wasExploded(Level* level, int x, int y, int z) {} - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return v->x >= tls->xx0 && v->x <= tls->xx1 && v->y >= tls->yy0 && v->y <= tls->yy1; +int Tile::getRenderLayer() { return 0; } + +bool Tile::mayPlace(Level* level, int x, int y, int z, int face) { + return mayPlace(level, x, y, z); } -void Tile::wasExploded(Level *level, int x, int y, int z) -{ -} - -int Tile::getRenderLayer() -{ - return 0; -} - -bool Tile::mayPlace(Level *level, int x, int y, int z, int face) -{ - return mayPlace(level, x, y, z); -} - -bool Tile::mayPlace(Level *level, int x, int y, int z) -{ - int t = level->getTile(x, y, z); - return t == 0 || Tile::tiles[t]->material->isReplaceable(); +bool Tile::mayPlace(Level* level, int x, int y, int z) { + int t = level->getTile(x, y, z); + return t == 0 || Tile::tiles[t]->material->isReplaceable(); } // 4J-PB - Adding a TestUse for tooltip display -bool Tile::TestUse() -{ - return false; +bool Tile::TestUse() { return false; } + +bool Tile::TestUse(Level* level, int x, int y, int z, + std::shared_ptr player) { + return false; } -bool Tile::TestUse(Level *level, int x, int y, int z, std::shared_ptr player) +bool Tile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, float clickX, + float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return false; + return false; } -bool Tile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - return false; +void Tile::stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity) {} + +int Tile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, int face, + float clickX, float clickY, float clickZ, + int itemValue) { + return itemValue; } -void Tile::stepOn(Level *level, int x, int y, int z, std::shared_ptr entity) +void Tile::prepareRender(Level* level, int x, int y, int z) {} + +void Tile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) {} + +void Tile::handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current) {} + +void Tile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); } -int Tile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - return itemValue; +double Tile::getShapeX0() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->xx0; } -void Tile::prepareRender(Level *level, int x, int y, int z) -{ +double Tile::getShapeX1() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->xx1; } -void Tile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ +double Tile::getShapeY0() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->yy0; } -void Tile::handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current) -{ +double Tile::getShapeY1() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->yy1; } -void Tile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); +double Tile::getShapeZ0() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->zz0; } -double Tile::getShapeX0() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->xx0; +double Tile::getShapeZ1() { + ThreadStorage* tls = + static_cast(TileTlsGetValue(Tile::tlsIdxShape)); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return tls->zz1; } -double Tile::getShapeX1() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->xx1; +int Tile::getColor() const { return 0xffffff; } + +int Tile::getColor(int auxData) { return 0xffffff; } + +int Tile::getColor(LevelSource* level, int x, int y, int z) { return 0xffffff; } + +int Tile::getColor(LevelSource* level, int x, int y, int z, int data) { + return 0xffffff; } -double Tile::getShapeY0() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->yy0; +bool Tile::getSignal(LevelSource* level, int x, int y, int z) { return false; } + +bool Tile::getSignal(LevelSource* level, int x, int y, int z, int dir) { + return false; } -double Tile::getShapeY1() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->yy1; +bool Tile::isSignalSource() { return false; } + +void Tile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) {} + +bool Tile::getDirectSignal(Level* level, int x, int y, int z, int dir) { + return false; } -double Tile::getShapeZ0() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->zz0; -} +void Tile::updateDefaultShape() { setShape(0, 0, 0, 1, 1, 1); } -double Tile::getShapeZ1() -{ - ThreadStorage *tls = static_cast(TileTlsGetValue(Tile::tlsIdxShape)); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return tls->zz1; -} +void Tile::playerDestroy(Level* level, std::shared_ptr player, int x, + int y, int z, int data) { + // 4J Stu - Special case - only record a crop destroy if is fully grown + if (id == Tile::crops_Id) { + if (Tile::crops->getResource(data, NULL, 0) > 0) + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); + } else if (id == Tile::potatoes_Id) { + if (Tile::potatoes->getResource(data, NULL, 0) > 0) + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); + } else if (id == Tile::carrots_Id) { + if (Tile::potatoes->getResource(data, NULL, 0) > 0) + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); + } else { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); + } + player->awardStat( + GenericStats::totalBlocksMined(), + GenericStats::param_noArgs()); // 4J : WESTY : Added for other award. + player->causeFoodExhaustion(FoodConstants::EXHAUSTION_MINE); -int Tile::getColor() const -{ - return 0xffffff; -} + if (id == Tile::treeTrunk_Id) + player->awardStat(GenericStats::mineWood(), + GenericStats::param_noArgs()); -int Tile::getColor(int auxData) -{ - return 0xffffff; -} - -int Tile::getColor(LevelSource *level, int x, int y, int z) -{ - return 0xffffff; -} - -int Tile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - return 0xffffff; -} - -bool Tile::getSignal(LevelSource *level, int x, int y, int z) -{ - return false; -} - -bool Tile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return false; -} - -bool Tile::isSignalSource() -{ - return false; -} - -void Tile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ -} - -bool Tile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ - return false; -} - -void Tile::updateDefaultShape() -{ - setShape(0,0,0,1,1,1); -} - -void Tile::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - // 4J Stu - Special case - only record a crop destroy if is fully grown - if( id==Tile::crops_Id ) - { - if( Tile::crops->getResource(data, NULL, 0) > 0 ) - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); - } - else if (id == Tile::potatoes_Id) - { - if (Tile::potatoes->getResource(data, NULL, 0) > 0) - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); - } - else if (id == Tile::carrots_Id) - { - if (Tile::potatoes->getResource(data, NULL, 0) > 0) - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); - } - else - { - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); - } - player->awardStat(GenericStats::totalBlocksMined(), GenericStats::param_noArgs()); // 4J : WESTY : Added for other award. - player->causeFoodExhaustion(FoodConstants::EXHAUSTION_MINE); - - if( id == Tile::treeTrunk_Id ) - player->awardStat(GenericStats::mineWood(), GenericStats::param_noArgs()); - - - if (isSilkTouchable() && EnchantmentHelper::hasSilkTouch(player->inventory)) - { + if (isSilkTouchable() && + EnchantmentHelper::hasSilkTouch(player->inventory)) { std::shared_ptr item = getSilkTouchItemInstance(data); - if (item != NULL) - { + if (item != NULL) { popResource(level, x, y, z, item); } - } - else - { - int playerBonusLevel = EnchantmentHelper::getDiggingLootBonus(player->inventory); + } else { + int playerBonusLevel = + EnchantmentHelper::getDiggingLootBonus(player->inventory); spawnResources(level, x, y, z, data, playerBonusLevel); } } -bool Tile::isSilkTouchable() -{ - return isCubeShaped() && !_isEntityTile; -} +bool Tile::isSilkTouchable() { return isCubeShaped() && !_isEntityTile; } -std::shared_ptr Tile::getSilkTouchItemInstance(int data) -{ +std::shared_ptr Tile::getSilkTouchItemInstance(int data) { int popData = 0; - if (id >= 0 && id < Item::items.length && Item::items[id]->isStackedByData()) - { + if (id >= 0 && id < Item::items.length && + Item::items[id]->isStackedByData()) { popData = data; } return std::shared_ptr(new ItemInstance(id, 1, popData)); } -int Tile::getResourceCountForLootBonus(int bonusLevel, Random *random) -{ - return getResourceCount(random); +int Tile::getResourceCountForLootBonus(int bonusLevel, Random* random) { + return getResourceCount(random); } -bool Tile::canSurvive(Level *level, int x, int y, int z) -{ - return true; +bool Tile::canSurvive(Level* level, int x, int y, int z) { return true; } + +void Tile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) {} + +void Tile::finalizePlacement(Level* level, int x, int y, int z, int data) {} + +Tile* Tile::setDescriptionId(unsigned int id) { + this->descriptionId = id; + return this; } -void Tile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ +std::wstring Tile::getName() { + return L""; // I18n::get(getDescriptionId() + L".name"); } -void Tile::finalizePlacement(Level *level, int x, int y, int z, int data) -{ +unsigned int Tile::getDescriptionId(int iData /*= -1*/) { + return descriptionId; } -Tile *Tile::setDescriptionId(unsigned int id) -{ - this->descriptionId = id; - return this; +Tile* Tile::setUseDescriptionId(unsigned int id) { + this->useDescriptionId = id; + return this; } -std::wstring Tile::getName() -{ - return L"";//I18n::get(getDescriptionId() + L".name"); +unsigned int Tile::getUseDescriptionId() { return useDescriptionId; } + +void Tile::triggerEvent(Level* level, int x, int y, int z, int b0, int b1) {} + +bool Tile::isCollectStatistics() { return collectStatistics; } + +Tile* Tile::setNotCollectStatistics() { + collectStatistics = false; + return this; } -unsigned int Tile::getDescriptionId(int iData /*= -1*/) -{ - return descriptionId; -} - -Tile *Tile::setUseDescriptionId(unsigned int id) -{ - this->useDescriptionId = id; - return this; -} - -unsigned int Tile::getUseDescriptionId() -{ - return useDescriptionId; -} - -void Tile::triggerEvent(Level *level, int x, int y, int z, int b0, int b1) -{ -} - -bool Tile::isCollectStatistics() -{ - return collectStatistics; -} - -Tile *Tile::setNotCollectStatistics() -{ - collectStatistics = false; - return this; -} - -int Tile::getPistonPushReaction() -{ - return material->getPushReaction(); -} +int Tile::getPistonPushReaction() { return material->getPushReaction(); } // 4J - brought forward from 1.8.2 -float Tile::getShadeBrightness(LevelSource *level, int x, int y, int z) -{ - return level->isSolidBlockingTile(x, y, z) ? 0.2f : 1.0f; +float Tile::getShadeBrightness(LevelSource* level, int x, int y, int z) { + return level->isSolidBlockingTile(x, y, z) ? 0.2f : 1.0f; } -void Tile::fallOn(Level *level, int x, int y, int z, std::shared_ptr entity, float fallDistance) -{ +void Tile::fallOn(Level* level, int x, int y, int z, + std::shared_ptr entity, float fallDistance) {} + +int Tile::cloneTileId(Level* level, int x, int y, int z) { return id; } + +int Tile::cloneTileData(Level* level, int x, int y, int z) { + return getSpawnResourcesAuxValue(level->getData(x, y, z)); } -int Tile::cloneTileId(Level *level, int x, int y, int z) -{ - return id; +void Tile::playerWillDestroy(Level* level, int x, int y, int z, int data, + std::shared_ptr player) {} + +void Tile::onRemoving(Level* level, int x, int y, int z, int data) {} + +void Tile::handleRain(Level* level, int x, int y, int z) {} + +void Tile::levelTimeChanged(Level* level, __int64 delta, __int64 newTime) {} + +void Tile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(m_textureName); } -int Tile::cloneTileData(Level *level, int x, int y, int z) -{ - return getSpawnResourcesAuxValue(level->getData(x, y, z)); +std::wstring Tile::getTileItemIconName() { return L""; } + +Tile* Tile::setTextureName(const std::wstring& name) { + m_textureName = name; + return this; } -void Tile::playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player) -{ -} - -void Tile::onRemoving(Level *level, int x, int y, int z, int data) -{ -} - -void Tile::handleRain(Level *level, int x, int y, int z) -{ -} - - void Tile::levelTimeChanged(Level *level, __int64 delta, __int64 newTime) -{ -} - -void Tile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(m_textureName); -} - -std::wstring Tile::getTileItemIconName() -{ - return L""; -} - -Tile *Tile::setTextureName(const std::wstring &name) -{ - m_textureName = name; - return this; -} - -Tile::SoundType::SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, float pitch, int iBreakSound, int iPlaceSound) -{ - this->eMaterialSound = eMaterialSound; - if( iBreakSound>-1 ) - { - this->iBreakSound = iBreakSound; - } - else - { - switch(eMaterialSound) - { - case eMaterialSoundType_STONE: - this->iBreakSound=eSoundType_DIG_STONE; - break; - case eMaterialSoundType_WOOD: - this->iBreakSound=eSoundType_DIG_WOOD; - break; - case eMaterialSoundType_GRAVEL: - this->iBreakSound=eSoundType_DIG_GRAVEL; - break; - case eMaterialSoundType_GRASS: - this->iBreakSound=eSoundType_DIG_GRASS; - break; - case eMaterialSoundType_METAL: - this->iBreakSound=eSoundType_DIG_STONE; - break; - case eMaterialSoundType_GLASS: - this->iBreakSound=eSoundType_RANDOM_GLASS; - break; - case eMaterialSoundType_CLOTH: - this->iBreakSound=eSoundType_DIG_CLOTH; - break; - case eMaterialSoundType_SAND: - this->iBreakSound=eSoundType_DIG_SAND; - break; - case eMaterialSoundType_SNOW: - this->iBreakSound=eSoundType_DIG_SNOW; - break; - case eMaterialSoundType_LADDER: - this->iBreakSound=eSoundType_DIG_WOOD; - break; - default: - app.DebugPrintf("NO BREAK SOUND!\n"); - this->iBreakSound=-1; - break; - } - //this->breakSound = L"step." + this->name; - } - - if( iPlaceSound>-1 ) - { - this->iPlaceSound = iPlaceSound; - } - else - { - this->iPlaceSound = this->iBreakSound; - } - - switch(eMaterialSound) - { - case eMaterialSoundType_STONE: - this->iStepSound=eSoundType_STEP_STONE; - break; - case eMaterialSoundType_WOOD: - this->iStepSound=eSoundType_STEP_WOOD; - break; - case eMaterialSoundType_GRAVEL: - this->iStepSound=eSoundType_STEP_GRAVEL; - break; - case eMaterialSoundType_GRASS: - this->iStepSound=eSoundType_STEP_GRASS; - break; - case eMaterialSoundType_METAL: - this->iStepSound=eSoundType_STEP_METAL; - break; - case eMaterialSoundType_CLOTH: - this->iStepSound=eSoundType_STEP_CLOTH; - break; - case eMaterialSoundType_SAND: - this->iStepSound=eSoundType_STEP_SAND; - break; - case eMaterialSoundType_SNOW: - this->iStepSound=eSoundType_STEP_SNOW; - break; - case eMaterialSoundType_LADDER: - this->iStepSound=eSoundType_STEP_LADDER; - break; - default: - app.DebugPrintf("NO STEP SOUND!\n"); - - this->iStepSound=-1; - break; - - } - - //this->stepSound = L"step." + this->name; - this->volume = volume; - this->pitch = pitch; -} - -float Tile::SoundType::getVolume() const -{ - return volume; -} -float Tile::SoundType::getPitch() const -{ - return pitch; -} -//std::wstring getBreakSound() const { return breakSound; } -//std::wstring getStepSound() const { return stepSound; } -int Tile::SoundType::getBreakSound() const -{ - return iBreakSound; -} -int Tile::SoundType::getStepSound() const -{ - return iStepSound; -} -int Tile::SoundType::getPlaceSound() const -{ - return iPlaceSound; +Tile::SoundType::SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, + float pitch, int iBreakSound, int iPlaceSound) { + this->eMaterialSound = eMaterialSound; + if (iBreakSound > -1) { + this->iBreakSound = iBreakSound; + } else { + switch (eMaterialSound) { + case eMaterialSoundType_STONE: + this->iBreakSound = eSoundType_DIG_STONE; + break; + case eMaterialSoundType_WOOD: + this->iBreakSound = eSoundType_DIG_WOOD; + break; + case eMaterialSoundType_GRAVEL: + this->iBreakSound = eSoundType_DIG_GRAVEL; + break; + case eMaterialSoundType_GRASS: + this->iBreakSound = eSoundType_DIG_GRASS; + break; + case eMaterialSoundType_METAL: + this->iBreakSound = eSoundType_DIG_STONE; + break; + case eMaterialSoundType_GLASS: + this->iBreakSound = eSoundType_RANDOM_GLASS; + break; + case eMaterialSoundType_CLOTH: + this->iBreakSound = eSoundType_DIG_CLOTH; + break; + case eMaterialSoundType_SAND: + this->iBreakSound = eSoundType_DIG_SAND; + break; + case eMaterialSoundType_SNOW: + this->iBreakSound = eSoundType_DIG_SNOW; + break; + case eMaterialSoundType_LADDER: + this->iBreakSound = eSoundType_DIG_WOOD; + break; + default: + app.DebugPrintf("NO BREAK SOUND!\n"); + this->iBreakSound = -1; + break; + } + // this->breakSound = L"step." + this->name; + } + + if (iPlaceSound > -1) { + this->iPlaceSound = iPlaceSound; + } else { + this->iPlaceSound = this->iBreakSound; + } + + switch (eMaterialSound) { + case eMaterialSoundType_STONE: + this->iStepSound = eSoundType_STEP_STONE; + break; + case eMaterialSoundType_WOOD: + this->iStepSound = eSoundType_STEP_WOOD; + break; + case eMaterialSoundType_GRAVEL: + this->iStepSound = eSoundType_STEP_GRAVEL; + break; + case eMaterialSoundType_GRASS: + this->iStepSound = eSoundType_STEP_GRASS; + break; + case eMaterialSoundType_METAL: + this->iStepSound = eSoundType_STEP_METAL; + break; + case eMaterialSoundType_CLOTH: + this->iStepSound = eSoundType_STEP_CLOTH; + break; + case eMaterialSoundType_SAND: + this->iStepSound = eSoundType_STEP_SAND; + break; + case eMaterialSoundType_SNOW: + this->iStepSound = eSoundType_STEP_SNOW; + break; + case eMaterialSoundType_LADDER: + this->iStepSound = eSoundType_STEP_LADDER; + break; + default: + app.DebugPrintf("NO STEP SOUND!\n"); + + this->iStepSound = -1; + break; + } + + // this->stepSound = L"step." + this->name; + this->volume = volume; + this->pitch = pitch; } +float Tile::SoundType::getVolume() const { return volume; } +float Tile::SoundType::getPitch() const { return pitch; } +// std::wstring getBreakSound() const { return breakSound; } +// std::wstring getStepSound() const { return stepSound; } +int Tile::SoundType::getBreakSound() const { return iBreakSound; } +int Tile::SoundType::getStepSound() const { return iStepSound; } +int Tile::SoundType::getPlaceSound() const { return iPlaceSound; } /* - 4J: These are necessary on the PS3. - (and 4 and Vita). + 4J: These are necessary on the PS3. + (and 4 and Vita). */ -#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined __linux__) +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined __linux__) const int Tile::rock_Id; const int Tile::grass_Id; const int Tile::dirt_Id; @@ -1667,4 +2588,3 @@ const int Tile::quartzBlock_Id; const int Tile::stairs_quartz_Id; const int Tile::woolCarpet_Id; #endif - diff --git a/Minecraft.World/Blocks/Tile.h b/Minecraft.World/Blocks/Tile.h index ea4421fc0..4c997f161 100644 --- a/Minecraft.World/Blocks/Tile.h +++ b/Minecraft.World/Blocks/Tile.h @@ -7,7 +7,6 @@ #include #endif - class GrassTile; class LeafTile; class TallGrass; @@ -42,80 +41,81 @@ class IconRegister; class ChunkRebuildData; -class Tile -{ - // 4J Stu - Stair tile accesses the protected members of a Tile object passed in - friend class StairTile; - friend class ChunkRebuildData; - friend class WallTile; +class Tile { + // 4J Stu - Stair tile accesses the protected members of a Tile object + // passed in + friend class StairTile; + friend class ChunkRebuildData; + friend class WallTile; protected: - // 4J added so we can have separate shapes for different threads - class ThreadStorage - { - public: - double xx0, yy0, zz0, xx1, yy1, zz1; - int tileId; - ThreadStorage(); - }; + // 4J added so we can have separate shapes for different threads + class ThreadStorage { + public: + double xx0, yy0, zz0, xx1, yy1, zz1; + int tileId; + ThreadStorage(); + }; #if defined(_WIN32) - static DWORD tlsIdxShape; + static DWORD tlsIdxShape; #else - static pthread_key_t tlsIdxShape; + static pthread_key_t tlsIdxShape; #endif -public: - // Each new thread that needs to use Vec3 pools will need to call one of the following 2 functions, to either create its own - // local storage, or share the default storage already allocated by the main thread - static void CreateNewThreadStorage(); - static void ReleaseThreadStorage(); - -public: - static const int TILE_NUM_COUNT = 4096; - static const int TILE_NUM_MASK = 0xfff; // 4096 - 1 - static const int TILE_NUM_SHIFT = 12; // 4096 is 12 bits - -private: - // 4J Stu - Was const but had to change it so that we can initialise it in TileStaticInit - static std::wstring TILE_DESCRIPTION_PREFIX; -protected: - static const float INDESTRUCTIBLE_DESTROY_TIME; +public: + // Each new thread that needs to use Vec3 pools will need to call one of the + // following 2 functions, to either create its own local storage, or share + // the default storage already allocated by the main thread + static void CreateNewThreadStorage(); + static void ReleaseThreadStorage(); public: + static const int TILE_NUM_COUNT = 4096; + static const int TILE_NUM_MASK = 0xfff; // 4096 - 1 + static const int TILE_NUM_SHIFT = 12; // 4096 is 12 bits - class SoundType - { - public: -// std::wstring name; -// std::wstring breakSound; -// std::wstring stepSound; - eMATERIALSOUND_TYPE eMaterialSound; - int iBreakSound,iStepSound,iPlaceSound; +private: + // 4J Stu - Was const but had to change it so that we can initialise it in + // TileStaticInit + static std::wstring TILE_DESCRIPTION_PREFIX; + +protected: + static const float INDESTRUCTIBLE_DESTROY_TIME; + +public: + class SoundType { + public: + // std::wstring name; + // std::wstring breakSound; + // std::wstring stepSound; + eMATERIALSOUND_TYPE eMaterialSound; + int iBreakSound, iStepSound, iPlaceSound; float volume; float pitch; - SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, float pitch, int iBreakSound = -1, int iPlaceSound = -1); - - float getVolume() const; - float getPitch() const; - //std::wstring getBreakSound() const { return breakSound; } - //std::wstring getStepSound() const { return stepSound; } - int getBreakSound() const; - int getStepSound() const; - int getPlaceSound() const; + SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, float pitch, + int iBreakSound = -1, int iPlaceSound = -1); + + float getVolume() const; + float getPitch() const; + // std::wstring getBreakSound() const { return breakSound; } + // std::wstring getStepSound() const { return stepSound; } + int getBreakSound() const; + int getStepSound() const; + int getPlaceSound() const; }; - static SoundType *SOUND_NORMAL; - static SoundType *SOUND_WOOD; - static SoundType *SOUND_GRAVEL; - static SoundType *SOUND_GRASS; - static SoundType *SOUND_STONE; - static SoundType *SOUND_METAL; - static SoundType *SOUND_GLASS; - static SoundType *SOUND_CLOTH; - static SoundType *SOUND_SAND; - static SoundType *SOUND_SNOW; - static SoundType *SOUND_LADDER; - static SoundType *SOUND_ANVIL; + static SoundType* SOUND_NORMAL; + static SoundType* SOUND_WOOD; + static SoundType* SOUND_GRAVEL; + static SoundType* SOUND_GRASS; + static SoundType* SOUND_STONE; + static SoundType* SOUND_METAL; + static SoundType* SOUND_GLASS; + static SoundType* SOUND_CLOTH; + static SoundType* SOUND_SAND; + static SoundType* SOUND_SNOW; + static SoundType* SOUND_LADDER; + static SoundType* SOUND_ANVIL; static const int SHAPE_INVISIBLE = -1; static const int SHAPE_BLOCK = 0; @@ -134,39 +134,44 @@ public: static const int SHAPE_CACTUS = 13; static const int SHAPE_BED = 14; static const int SHAPE_DIODE = 15; - static const int SHAPE_PISTON_BASE = 16; - static const int SHAPE_PISTON_EXTENSION = 17; - static const int SHAPE_IRON_FENCE = 18; - static const int SHAPE_STEM = 19; - static const int SHAPE_VINE = 20; - static const int SHAPE_FENCE_GATE = 21; - static const int SHAPE_ENTITYTILE_ANIMATED = 22; - static const int SHAPE_LILYPAD = 23; - static const int SHAPE_CAULDRON = 24; - static const int SHAPE_BREWING_STAND = 25; - static const int SHAPE_PORTAL_FRAME = 26; - static const int SHAPE_EGG = 27; - static const int SHAPE_COCOA = 28; - static const int SHAPE_TRIPWIRE_SOURCE = 29; - static const int SHAPE_TRIPWIRE = 30; - static const int SHAPE_TREE = 31; - static const int SHAPE_WALL = 32; - static const int SHAPE_FLOWER_POT = 33; - static const int SHAPE_BEACON = 34; - static const int SHAPE_ANVIL = 35; - static const int SHAPE_QUARTZ = 39; + static const int SHAPE_PISTON_BASE = 16; + static const int SHAPE_PISTON_EXTENSION = 17; + static const int SHAPE_IRON_FENCE = 18; + static const int SHAPE_STEM = 19; + static const int SHAPE_VINE = 20; + static const int SHAPE_FENCE_GATE = 21; + static const int SHAPE_ENTITYTILE_ANIMATED = 22; + static const int SHAPE_LILYPAD = 23; + static const int SHAPE_CAULDRON = 24; + static const int SHAPE_BREWING_STAND = 25; + static const int SHAPE_PORTAL_FRAME = 26; + static const int SHAPE_EGG = 27; + static const int SHAPE_COCOA = 28; + static const int SHAPE_TRIPWIRE_SOURCE = 29; + static const int SHAPE_TRIPWIRE = 30; + static const int SHAPE_TREE = 31; + static const int SHAPE_WALL = 32; + static const int SHAPE_FLOWER_POT = 33; + static const int SHAPE_BEACON = 34; + static const int SHAPE_ANVIL = 35; + static const int SHAPE_QUARTZ = 39; - static Tile **tiles; + static Tile** tiles; - static bool mipmapEnable[TILE_NUM_COUNT]; - static bool solid[TILE_NUM_COUNT]; - static int lightBlock[TILE_NUM_COUNT]; - static bool transculent[TILE_NUM_COUNT]; - static int lightEmission[TILE_NUM_COUNT]; - static unsigned char _sendTileData[TILE_NUM_COUNT]; // 4J - was bool, changed to bitfield so we can indicate which bits are important to be sent - static bool propagate[TILE_NUM_COUNT]; + static bool mipmapEnable[TILE_NUM_COUNT]; + static bool solid[TILE_NUM_COUNT]; + static int lightBlock[TILE_NUM_COUNT]; + static bool transculent[TILE_NUM_COUNT]; + static int lightEmission[TILE_NUM_COUNT]; + static unsigned char + _sendTileData[TILE_NUM_COUNT]; // 4J - was bool, changed to bitfield so + // we can indicate which bits are + // important to be sent + static bool propagate[TILE_NUM_COUNT]; - // 4J - this array of simple constants made so the compiler can optimise references to Ids that were previous of the form Tile::->id, and are now simply Tile::whatever_Id + // 4J - this array of simple constants made so the compiler can optimise + // references to Ids that were previous of the form Tile::->id, + // and are now simply Tile::whatever_Id static const int rock_Id = 1; static const int grass_Id = 2; static const int dirt_Id = 3; @@ -195,14 +200,14 @@ public: static const int bed_Id = 26; static const int goldenRail_Id = 27; static const int detectorRail_Id = 28; - static const int pistonStickyBase_Id = 29; - static const int web_Id = 30; + static const int pistonStickyBase_Id = 29; + static const int web_Id = 30; static const int tallgrass_Id = 31; static const int deadBush_Id = 32; - static const int pistonBase_Id = 33; - static const int pistonExtensionPiece_Id = 34; + static const int pistonBase_Id = 33; + static const int pistonExtensionPiece_Id = 34; static const int cloth_Id = 35; - static const int pistonMovingPiece_Id = 36; + static const int pistonMovingPiece_Id = 36; static const int flower_Id = 37; static const int rose_Id = 38; static const int mushroom1_Id = 39; @@ -264,392 +269,443 @@ public: static const int aprilFoolsJoke_Id = 95; static const int trapdoor_Id = 96; - static const int monsterStoneEgg_Id = 97; - static const int stoneBrickSmooth_Id = 98; - static const int hugeMushroom1_Id = 99; - static const int hugeMushroom2_Id = 100; - static const int ironFence_Id = 101; - static const int thinGlass_Id = 102; - static const int melon_Id = 103; - static const int pumpkinStem_Id = 104; - static const int melonStem_Id = 105; - static const int vine_Id = 106; - static const int fenceGate_Id = 107; - static const int stairs_bricks_Id = 108; - static const int stairs_stoneBrickSmooth_Id = 109; + static const int monsterStoneEgg_Id = 97; + static const int stoneBrickSmooth_Id = 98; + static const int hugeMushroom1_Id = 99; + static const int hugeMushroom2_Id = 100; + static const int ironFence_Id = 101; + static const int thinGlass_Id = 102; + static const int melon_Id = 103; + static const int pumpkinStem_Id = 104; + static const int melonStem_Id = 105; + static const int vine_Id = 106; + static const int fenceGate_Id = 107; + static const int stairs_bricks_Id = 108; + static const int stairs_stoneBrickSmooth_Id = 109; - static const int mycel_Id = 110; - static const int waterLily_Id = 111; - static const int netherBrick_Id = 112; - static const int netherFence_Id = 113; - static const int stairs_netherBricks_Id = 114; - static const int netherStalk_Id = 115; - static const int enchantTable_Id = 116; - static const int brewingStand_Id = 117; - static const int cauldron_Id = 118; - static const int endPortalTile_Id = 119; - static const int endPortalFrameTile_Id = 120; - static const int whiteStone_Id = 121; - static const int dragonEgg_Id = 122; - static const int redstoneLight_Id = 123; - static const int redstoneLight_lit_Id = 124; + static const int mycel_Id = 110; + static const int waterLily_Id = 111; + static const int netherBrick_Id = 112; + static const int netherFence_Id = 113; + static const int stairs_netherBricks_Id = 114; + static const int netherStalk_Id = 115; + static const int enchantTable_Id = 116; + static const int brewingStand_Id = 117; + static const int cauldron_Id = 118; + static const int endPortalTile_Id = 119; + static const int endPortalFrameTile_Id = 120; + static const int whiteStone_Id = 121; + static const int dragonEgg_Id = 122; + static const int redstoneLight_Id = 123; + static const int redstoneLight_lit_Id = 124; - - static const int woodSlab_Id = 125; - static const int woodSlabHalf_Id = 126; - static const int cocoa_Id = 127; - static const int stairs_sandstone_Id = 128; - static const int stairs_sprucewood_Id = 134; - static const int stairs_birchwood_Id = 135; - static const int stairs_junglewood_Id = 136; - static const int emeraldOre_Id = 129; - static const int enderChest_Id = 130; - static const int tripWireSource_Id = 131; - static const int tripWire_Id = 132; - static const int emeraldBlock_Id = 133; + static const int woodSlab_Id = 125; + static const int woodSlabHalf_Id = 126; + static const int cocoa_Id = 127; + static const int stairs_sandstone_Id = 128; + static const int stairs_sprucewood_Id = 134; + static const int stairs_birchwood_Id = 135; + static const int stairs_junglewood_Id = 136; + static const int emeraldOre_Id = 129; + static const int enderChest_Id = 130; + static const int tripWireSource_Id = 131; + static const int tripWire_Id = 132; + static const int emeraldBlock_Id = 133; - static const int cobbleWall_Id = 139; - static const int flowerPot_Id = 140; - static const int carrots_Id = 141; - static const int potatoes_Id = 142; - static const int anvil_Id = 145; - static const int button_wood_Id = 143; - static const int skull_Id = 144; - static const int netherQuartz_Id = 153; - static const int quartzBlock_Id = 155; - static const int stairs_quartz_Id = 156; + static const int cobbleWall_Id = 139; + static const int flowerPot_Id = 140; + static const int carrots_Id = 141; + static const int potatoes_Id = 142; + static const int anvil_Id = 145; + static const int button_wood_Id = 143; + static const int skull_Id = 144; + static const int netherQuartz_Id = 153; + static const int quartzBlock_Id = 155; + static const int stairs_quartz_Id = 156; - static const int woolCarpet_Id = 171; + static const int woolCarpet_Id = 171; + static Tile* rock; + static GrassTile* grass; + static Tile* dirt; + static Tile* stoneBrick; + static Tile* wood; + static Tile* sapling; + static Tile* unbreakable; + static LiquidTile* water; + static Tile* calmWater; + static LiquidTile* lava; + static Tile* calmLava; + static Tile* sand; + static Tile* gravel; + static Tile* goldOre; + static Tile* ironOre; + static Tile* coalOre; + static Tile* treeTrunk; + static LeafTile* leaves; + static Tile* sponge; + static Tile* glass; + static Tile* lapisOre; + static Tile* lapisBlock; + static Tile* dispenser; + static Tile* sandStone; + static Tile* musicBlock; + static Tile* bed; + static Tile* goldenRail; + static Tile* detectorRail; + static PistonBaseTile* pistonStickyBase; + static Tile* web; + static TallGrass* tallgrass; + static DeadBushTile* deadBush; + static PistonBaseTile* pistonBase; + static PistonExtensionTile* pistonExtension; + static Tile* cloth; + static PistonMovingPiece* pistonMovingPiece; + static Bush* flower; + static Bush* rose; + static Bush* mushroom1; + static Bush* mushroom2; + static Tile* goldBlock; + static Tile* ironBlock; + // static Tile *stoneSlab; + // static Tile *stoneSlabHalf; + static Tile* redBrick; + static Tile* tnt; + static Tile* bookshelf; + static Tile* mossStone; + static Tile* obsidian; + static Tile* torch; + static FireTile* fire; + static Tile* mobSpawner; + static Tile* stairs_wood; + static ChestTile* chest; + static RedStoneDustTile* redStoneDust; + static Tile* diamondOre; + static Tile* diamondBlock; + static Tile* workBench; + static Tile* crops; + static Tile* farmland; + static Tile* furnace; + static Tile* furnace_lit; + static Tile* sign; + static Tile* door_wood; + static Tile* ladder; + static Tile* rail; + static Tile* stairs_stone; + static Tile* wallSign; + static Tile* lever; + static Tile* pressurePlate_stone; + static Tile* door_iron; + static Tile* pressurePlate_wood; + static Tile* redStoneOre; + static Tile* redStoneOre_lit; + static Tile* notGate_off; + static Tile* notGate_on; + static Tile* button; + static Tile* topSnow; + static Tile* ice; + static Tile* snow; + static Tile* cactus; + static Tile* clay; + static Tile* reeds; + static Tile* recordPlayer; + static Tile* fence; + static Tile* pumpkin; + static Tile* hellRock; + static Tile* hellSand; + static Tile* lightGem; + static PortalTile* portalTile; + static Tile* litPumpkin; + static Tile* cake; + static RepeaterTile* diode_off; + static RepeaterTile* diode_on; + static Tile* aprilFoolsJoke; + static Tile* trapdoor; - static Tile *rock; - static GrassTile *grass; - static Tile *dirt; - static Tile *stoneBrick; - static Tile *wood; - static Tile *sapling; - static Tile *unbreakable; - static LiquidTile *water; - static Tile *calmWater; - static LiquidTile *lava; - static Tile *calmLava; - static Tile *sand; - static Tile *gravel; - static Tile *goldOre; - static Tile *ironOre; - static Tile *coalOre; - static Tile *treeTrunk; - static LeafTile *leaves; - static Tile *sponge; - static Tile *glass; - static Tile *lapisOre; - static Tile *lapisBlock; - static Tile *dispenser; - static Tile *sandStone; - static Tile *musicBlock; - static Tile *bed; - static Tile *goldenRail; - static Tile *detectorRail; - static PistonBaseTile *pistonStickyBase; - static Tile *web; - static TallGrass *tallgrass; - static DeadBushTile *deadBush; - static PistonBaseTile *pistonBase; - static PistonExtensionTile *pistonExtension; - static Tile *cloth; - static PistonMovingPiece *pistonMovingPiece; - static Bush *flower; - static Bush *rose; - static Bush *mushroom1; - static Bush *mushroom2; - static Tile *goldBlock; - static Tile *ironBlock; -// static Tile *stoneSlab; -// static Tile *stoneSlabHalf; - static Tile *redBrick; - static Tile *tnt; - static Tile *bookshelf; - static Tile *mossStone; - static Tile *obsidian; - static Tile *torch; - static FireTile *fire; - static Tile *mobSpawner; - static Tile *stairs_wood; - static ChestTile *chest; - static RedStoneDustTile *redStoneDust; - static Tile *diamondOre; - static Tile *diamondBlock; - static Tile *workBench; - static Tile *crops; - static Tile *farmland; - static Tile *furnace; - static Tile *furnace_lit; - static Tile *sign; - static Tile *door_wood; - static Tile *ladder; - static Tile *rail; - static Tile *stairs_stone; - static Tile *wallSign; - static Tile *lever; - static Tile *pressurePlate_stone; - static Tile *door_iron; - static Tile *pressurePlate_wood; - static Tile *redStoneOre; - static Tile *redStoneOre_lit; - static Tile *notGate_off; - static Tile *notGate_on; - static Tile *button; - static Tile *topSnow; - static Tile *ice; - static Tile *snow; - static Tile *cactus; - static Tile *clay; - static Tile *reeds; - static Tile *recordPlayer; - static Tile *fence; - static Tile *pumpkin; - static Tile *hellRock; - static Tile *hellSand; - static Tile *lightGem; - static PortalTile *portalTile; - static Tile *litPumpkin; - static Tile *cake; - static RepeaterTile *diode_off; - static RepeaterTile *diode_on; - static Tile *aprilFoolsJoke; - static Tile *trapdoor; + static Tile* monsterStoneEgg; + static Tile* stoneBrickSmooth; + static Tile* hugeMushroom1; + static Tile* hugeMushroom2; + static Tile* ironFence; + static Tile* thinGlass; + static Tile* melon; + static Tile* pumpkinStem; + static Tile* melonStem; + static Tile* vine; + static Tile* fenceGate; + static Tile* stairs_bricks; + static Tile* stairs_stoneBrickSmooth; - static Tile *monsterStoneEgg; - static Tile *stoneBrickSmooth; - static Tile *hugeMushroom1; - static Tile *hugeMushroom2; - static Tile *ironFence; - static Tile *thinGlass; - static Tile *melon; - static Tile *pumpkinStem; - static Tile *melonStem; - static Tile *vine; - static Tile *fenceGate; - static Tile *stairs_bricks; - static Tile *stairs_stoneBrickSmooth; + static MycelTile* mycel; + static Tile* waterLily; + static Tile* netherBrick; + static Tile* netherFence; + static Tile* stairs_netherBricks; + static Tile* netherStalk; + static Tile* enchantTable; + static Tile* brewingStand; + static CauldronTile* cauldron; + static Tile* endPortalTile; + static Tile* endPortalFrameTile; + static Tile* whiteStone; + static Tile* dragonEgg; + static Tile* redstoneLight; + static Tile* redstoneLight_lit; - static MycelTile *mycel; - static Tile *waterLily; - static Tile *netherBrick; - static Tile *netherFence; - static Tile *stairs_netherBricks; - static Tile *netherStalk; - static Tile *enchantTable; - static Tile *brewingStand; - static CauldronTile *cauldron; - static Tile *endPortalTile; - static Tile *endPortalFrameTile; - static Tile *whiteStone; - static Tile *dragonEgg; - static Tile *redstoneLight; - static Tile *redstoneLight_lit; + static Tile* stairs_sandstone; + static Tile* woodStairsDark; + static Tile* woodStairsBirch; + static Tile* woodStairsJungle; + static Tile* button_wood; + static HalfSlabTile* woodSlab; + static HalfSlabTile* woodSlabHalf; + static HalfSlabTile* stoneSlab; + static HalfSlabTile* stoneSlabHalf; + static Tile* emeraldOre; + static Tile* enderChest; + static TripWireSourceTile* tripWireSource; + static Tile* tripWire; + static Tile* emeraldBlock; - static Tile *stairs_sandstone; - static Tile *woodStairsDark; - static Tile *woodStairsBirch; - static Tile *woodStairsJungle; - static Tile *button_wood; - static HalfSlabTile *woodSlab; - static HalfSlabTile *woodSlabHalf; - static HalfSlabTile *stoneSlab; - static HalfSlabTile *stoneSlabHalf; - static Tile *emeraldOre; - static Tile *enderChest; - static TripWireSourceTile *tripWireSource; - static Tile *tripWire; - static Tile *emeraldBlock; - - static Tile *cocoa; - static Tile *skull; + static Tile* cocoa; + static Tile* skull; - static Tile *cobbleWall; - static Tile *flowerPot; - static Tile *carrots; - static Tile *potatoes; - static Tile *anvil; - static Tile *netherQuartz; - static Tile *quartzBlock; - static Tile *stairs_quartz; + static Tile* cobbleWall; + static Tile* flowerPot; + static Tile* carrots; + static Tile* potatoes; + static Tile* anvil; + static Tile* netherQuartz; + static Tile* quartzBlock; + static Tile* stairs_quartz; - static Tile *woolCarpet; + static Tile* woolCarpet; - static void staticCtor(); + static void staticCtor(); int id; + protected: float destroySpeed; float explosionResistance; bool isInventoryItem; bool collectStatistics; - bool _isTicking; - bool _isEntityTile; - int m_iMaterial; - int m_iBaseItemType; + bool _isTicking; + bool _isEntityTile; + int m_iMaterial; + int m_iBaseItemType; - // 4J Stu - Removed this in favour of a TLS version - //double xx0, yy0, zz0, xx1, yy1, zz1; + // 4J Stu - Removed this in favour of a TLS version + // double xx0, yy0, zz0, xx1, yy1, zz1; public: - const SoundType *soundType; + const SoundType* soundType; float gravity; - Material *material; + Material* material; float friction; private: unsigned int descriptionId; - unsigned int useDescriptionId; // 4J Added + unsigned int useDescriptionId; // 4J Added - std::wstring m_textureName; + std::wstring m_textureName; protected: - Icon *icon; + Icon* icon; protected: - void _init(int id, Material *material, bool isSolidRender); - Tile(int id, Material *material, bool isSolidRender = true); - virtual ~Tile() {} + void _init(int id, Material* material, bool isSolidRender); + Tile(int id, Material* material, bool isSolidRender = true); + virtual ~Tile() {} + protected: - virtual Tile *sendTileData(unsigned char importantMask=15); // 4J - added importantMask to indicate which bits in the data are important + virtual Tile* sendTileData(unsigned char importantMask = + 15); // 4J - added importantMask to indicate + // which bits in the data are important protected: virtual void init(); - virtual Tile *setSoundType(const SoundType *soundType); - virtual Tile *setLightBlock(int i); - virtual Tile *setLightEmission(float f); - virtual Tile *setExplodeable(float explosionResistance); - Tile *setBaseItemTypeAndMaterial(int iType,int iMaterial); + virtual Tile* setSoundType(const SoundType* soundType); + virtual Tile* setLightBlock(int i); + virtual Tile* setLightEmission(float f); + virtual Tile* setExplodeable(float explosionResistance); + Tile* setBaseItemTypeAndMaterial(int iType, int iMaterial); + public: - static bool isSolidBlockingTile(int t); + static bool isSolidBlockingTile(int t); virtual bool isCubeShaped(); - virtual bool isPathfindable(LevelSource *level, int x, int y, int z); + virtual bool isPathfindable(LevelSource* level, int x, int y, int z); virtual int getRenderShape(); - // 4J-PB added - int getBaseItemType(); - int getMaterial(); + // 4J-PB added + int getBaseItemType(); + int getMaterial(); + protected: - virtual Tile *setDestroyTime(float destroySpeed); - virtual Tile *setIndestructible(); + virtual Tile* setDestroyTime(float destroySpeed); + virtual Tile* setIndestructible(); + public: - virtual float getDestroySpeed(Level *level, int x, int y, int z); + virtual float getDestroySpeed(Level* level, int x, int y, int z); + protected: - virtual Tile *setTicking(bool tick); - virtual Tile *disableMipmap(); + virtual Tile* setTicking(bool tick); + virtual Tile* disableMipmap(); + public: - virtual bool isTicking(); - virtual bool isEntityTile(); - virtual void setShape(float x0, float y0, float z0, float x1, float y1, float z1); - virtual float getBrightness(LevelSource *level, int x, int y, int z); - virtual int getLightColor(LevelSource *level, int x, int y, int z, int tileId=-1); // 4J - brought forward from 1.8.2 - static bool isFaceVisible(Level *level, int x, int y, int z, int f); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - virtual bool isSolidFace(LevelSource *level, int x, int y, int z, int face); - virtual Icon *getTexture(LevelSource *level, int x, int y, int z, int face); - virtual Icon *getTexture(int face, int data); - virtual Icon *getTexture(int face); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual bool isSolidRender(bool isServerLevel = false); // 4J - Added isServerLevel param + virtual bool isTicking(); + virtual bool isEntityTile(); + virtual void setShape(float x0, float y0, float z0, float x1, float y1, + float z1); + virtual float getBrightness(LevelSource* level, int x, int y, int z); + virtual int getLightColor( + LevelSource* level, int x, int y, int z, + int tileId = -1); // 4J - brought forward from 1.8.2 + static bool isFaceVisible(Level* level, int x, int y, int z, int f); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); + virtual bool isSolidFace(LevelSource* level, int x, int y, int z, int face); + virtual Icon* getTexture(LevelSource* level, int x, int y, int z, int face); + virtual Icon* getTexture(int face, int data); + virtual Icon* getTexture(int face); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual bool isSolidRender( + bool isServerLevel = false); // 4J - Added isServerLevel param virtual bool mayPick(int data, bool liquid); virtual bool mayPick(); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void animateTick(Level *level, int x, int y, int z, Random *random); - virtual void destroy(Level *level, int x, int y, int z, int data); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void addLights(Level *level, int x, int y, int z); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void animateTick(Level* level, int x, int y, int z, Random* random); + virtual void destroy(Level* level, int x, int y, int z, int data); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void addLights(Level* level, int x, int y, int z); virtual int getTickDelay(); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual float getDestroyProgress(std::shared_ptr player, Level *level = nullptr, int x = 0, int y = 0, int z = 0); - virtual void spawnResources(Level *level, int x, int y, int z, int data, int playerBonusLevel); - virtual void spawnResources(Level *level, int x, int y, int z, int data, float odds, int playerBonusLevel); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual float getDestroyProgress(std::shared_ptr player, + Level* level = nullptr, int x = 0, + int y = 0, int z = 0); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + int playerBonusLevel); + virtual void spawnResources(Level* level, int x, int y, int z, int data, + float odds, int playerBonusLevel); + protected: - virtual void popResource(Level *level, int x, int y, int z, std::shared_ptr itemInstance); - virtual void popExperience(Level *level, int x, int y, int z, int amount); + virtual void popResource(Level* level, int x, int y, int z, + std::shared_ptr itemInstance); + virtual void popExperience(Level* level, int x, int y, int z, int amount); public: - virtual int getSpawnResourcesAuxValue(int data); + virtual int getSpawnResourcesAuxValue(int data); virtual float getExplosionResistance(std::shared_ptr source); - virtual HitResult *clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b); + virtual HitResult* clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b); + private: - virtual bool containsX(Vec3 *v); - virtual bool containsY(Vec3 *v); - virtual bool containsZ(Vec3 *v); + virtual bool containsX(Vec3* v); + virtual bool containsY(Vec3* v); + virtual bool containsZ(Vec3* v); + public: - virtual void wasExploded(Level *level, int x, int y, int z); + virtual void wasExploded(Level* level, int x, int y, int z); virtual int getRenderLayer(); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual bool TestUse(); - virtual bool TestUse(Level *level, int x, int y, int z, std::shared_ptr player); - virtual bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace = 0, float clickX = 0.0f, float clickY = 0.0f, float clickZ = 0.0f, bool soundOnly = false); // 4J added soundOnly param - virtual void stepOn(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual void prepareRender(Level *level, int x, int y, int z); - virtual void attack(Level *level, int x, int y, int z, std::shared_ptr player); - virtual void handleEntityInside(Level *level, int x, int y, int z, std::shared_ptr e, Vec3 *current); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual double getShapeX0(); - virtual double getShapeX1(); - virtual double getShapeY0(); - virtual double getShapeY1(); - virtual double getShapeZ0(); - virtual double getShapeZ1(); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual bool TestUse(); + virtual bool TestUse(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual bool use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace = 0, + float clickX = 0.0f, float clickY = 0.0f, + float clickZ = 0.0f, + bool soundOnly = false); // 4J added soundOnly param + virtual void stepOn(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual void prepareRender(Level* level, int x, int y, int z); + virtual void attack(Level* level, int x, int y, int z, + std::shared_ptr player); + virtual void handleEntityInside(Level* level, int x, int y, int z, + std::shared_ptr e, Vec3* current); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual double getShapeX0(); + virtual double getShapeX1(); + virtual double getShapeY0(); + virtual double getShapeY1(); + virtual double getShapeZ0(); + virtual double getShapeZ1(); virtual int getColor() const; - virtual int getColor(int auxData); - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added - virtual bool getSignal(LevelSource *level, int x, int y, int z); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); + virtual int getColor(int auxData); + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added + virtual bool getSignal(LevelSource* level, int x, int y, int z); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); virtual bool isSignalSource(); - virtual void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); + virtual void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); virtual void updateDefaultShape(); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); - virtual bool canSurvive(Level *level, int x, int y, int z); + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); + virtual bool canSurvive(Level* level, int x, int y, int z); + protected: - virtual bool isSilkTouchable(); - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual bool isSilkTouchable(); + virtual std::shared_ptr getSilkTouchItemInstance(int data); + public: - virtual int getResourceCountForLootBonus(int bonusLevel, Random *random); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual void finalizePlacement(Level *level, int x, int y, int z, int data); - virtual Tile *setDescriptionId(unsigned int id); + virtual int getResourceCountForLootBonus(int bonusLevel, Random* random); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual void finalizePlacement(Level* level, int x, int y, int z, int data); + virtual Tile* setDescriptionId(unsigned int id); virtual std::wstring getName(); virtual unsigned int getDescriptionId(int iData = -1); - virtual Tile *setUseDescriptionId(unsigned int id); // 4J Added - virtual unsigned int getUseDescriptionId(); // 4J Added - virtual void triggerEvent(Level *level, int x, int y, int z, int b0, int b1); + virtual Tile* setUseDescriptionId(unsigned int id); // 4J Added + virtual unsigned int getUseDescriptionId(); // 4J Added + virtual void triggerEvent(Level* level, int x, int y, int z, int b0, + int b1); virtual bool isCollectStatistics(); - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - // Default to true (it's also checking a bool array) and just override when we need to be able to say no - virtual bool shouldTileTick(Level *level, int x,int y,int z) { return true; } + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing Default to true (it's also checking a + // bool array) and just override when we need to be able to say no + virtual bool shouldTileTick(Level* level, int x, int y, int z) { + return true; + } + protected: - virtual Tile *setNotCollectStatistics(); + virtual Tile* setNotCollectStatistics(); + public: - virtual int getPistonPushReaction(); - virtual float getShadeBrightness(LevelSource *level, int x, int y, int z); // 4J - brought forward from 1.8.2 - virtual void fallOn(Level *level, int x, int y, int z, std::shared_ptr entity, float fallDistance); - virtual int cloneTileId(Level *level, int x, int y, int z); - virtual int cloneTileData(Level *level, int x, int y, int z); - virtual void playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player); - virtual void onRemoving(Level *level, int x, int y, int z, int data); - virtual void handleRain(Level *level, int x, int y, int z); - virtual void levelTimeChanged(Level *level, __int64 delta, __int64 newTime); - virtual void registerIcons(IconRegister *iconRegister); - virtual std::wstring getTileItemIconName(); - // 4J Using per-item textures now - Tile *setTextureName(const std::wstring &name); - // AP - added this function so we can generate the faceFlags for a block in a single fast function - int getFaceFlags(LevelSource *level, int x, int y, int z); + virtual int getPistonPushReaction(); + virtual float getShadeBrightness(LevelSource* level, int x, int y, + int z); // 4J - brought forward from 1.8.2 + virtual void fallOn(Level* level, int x, int y, int z, + std::shared_ptr entity, float fallDistance); + virtual int cloneTileId(Level* level, int x, int y, int z); + virtual int cloneTileData(Level* level, int x, int y, int z); + virtual void playerWillDestroy(Level* level, int x, int y, int z, int data, + std::shared_ptr player); + virtual void onRemoving(Level* level, int x, int y, int z, int data); + virtual void handleRain(Level* level, int x, int y, int z); + virtual void levelTimeChanged(Level* level, __int64 delta, __int64 newTime); + virtual void registerIcons(IconRegister* iconRegister); + virtual std::wstring getTileItemIconName(); + // 4J Using per-item textures now + Tile* setTextureName(const std::wstring& name); + // AP - added this function so we can generate the faceFlags for a block in + // a single fast function + int getFaceFlags(LevelSource* level, int x, int y, int z); }; class stoneBrick : public Tile {}; diff --git a/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.cpp index 9a9971b25..da34405c8 100644 --- a/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.cpp @@ -6,61 +6,40 @@ #include "../../Headers/net.minecraft.world.item.h" #include "../../Headers/net.minecraft.world.item.alchemy.h" - - -BrewingStandTileEntity::BrewingStandTileEntity() -{ - brewTime = 0; - items = ItemInstanceArray(4); +BrewingStandTileEntity::BrewingStandTileEntity() { + brewTime = 0; + items = ItemInstanceArray(4); } -BrewingStandTileEntity::~BrewingStandTileEntity() -{ - delete [] items.data; -} +BrewingStandTileEntity::~BrewingStandTileEntity() { delete[] items.data; } -int BrewingStandTileEntity::getName() -{ - return IDS_TILE_BREWINGSTAND; -} +int BrewingStandTileEntity::getName() { return IDS_TILE_BREWINGSTAND; } -unsigned int BrewingStandTileEntity::getContainerSize() -{ - return items.length; -} +unsigned int BrewingStandTileEntity::getContainerSize() { return items.length; } -void BrewingStandTileEntity::tick() -{ - if (brewTime > 0) - { +void BrewingStandTileEntity::tick() { + if (brewTime > 0) { brewTime--; - if (brewTime == 0) - { + if (brewTime == 0) { // apply ingredients to all potions doBrew(); setChanged(); - } - else if (!isBrewable()) - { + } else if (!isBrewable()) { + brewTime = 0; + setChanged(); + } else if (ingredientId != items[INGREDIENT_SLOT]->id) { brewTime = 0; setChanged(); } - else if (ingredientId != items[INGREDIENT_SLOT]->id) - { - brewTime = 0; - setChanged(); - } - } - else if (isBrewable()) - { - brewTime = SharedConstants::TICKS_PER_SECOND * PotionBrewing::BREWING_TIME_SECONDS; + } else if (isBrewable()) { + brewTime = SharedConstants::TICKS_PER_SECOND * + PotionBrewing::BREWING_TIME_SECONDS; ingredientId = items[INGREDIENT_SLOT]->id; } int newCount = getPotionBits(); - if (newCount != lastPotionCount) - { + if (newCount != lastPotionCount) { lastPotionCount = newCount; level->setData(x, y, z, newCount); } @@ -68,63 +47,55 @@ void BrewingStandTileEntity::tick() TileEntity::tick(); } -int BrewingStandTileEntity::getBrewTime() -{ - return brewTime; -} +int BrewingStandTileEntity::getBrewTime() { return brewTime; } -bool BrewingStandTileEntity::isBrewable() -{ - if (items[INGREDIENT_SLOT] == NULL || items[INGREDIENT_SLOT]->count <= 0) - { +bool BrewingStandTileEntity::isBrewable() { + if (items[INGREDIENT_SLOT] == NULL || items[INGREDIENT_SLOT]->count <= 0) { return false; } std::shared_ptr ingredient = items[INGREDIENT_SLOT]; - if (PotionBrewing::SIMPLIFIED_BREWING) - { - if (!Item::items[ingredient->id]->hasPotionBrewingFormula()) - { + if (PotionBrewing::SIMPLIFIED_BREWING) { + if (!Item::items[ingredient->id]->hasPotionBrewingFormula()) { return false; } bool oneResult = false; - for (int dest = 0; dest < 3; dest++) - { - if (items[dest] != NULL && items[dest]->id == Item::potion_Id) - { + for (int dest = 0; dest < 3; dest++) { + if (items[dest] != NULL && items[dest]->id == Item::potion_Id) { int currentBrew = items[dest]->getAuxValue(); - int newBrew = NORMALISE_POTION_AUXVAL( applyIngredient(currentBrew, ingredient) ); + int newBrew = NORMALISE_POTION_AUXVAL( + applyIngredient(currentBrew, ingredient)); - if (!PotionItem::isThrowable(currentBrew) && PotionItem::isThrowable(newBrew)) - { + if (!PotionItem::isThrowable(currentBrew) && + PotionItem::isThrowable(newBrew)) { oneResult = true; break; } - std::vector *currentEffects = Item::potion->getMobEffects(currentBrew); - std::vector *newEffects = Item::potion->getMobEffects(newBrew); + std::vector* currentEffects = + Item::potion->getMobEffects(currentBrew); + std::vector* newEffects = + Item::potion->getMobEffects(newBrew); - // 4J - this code replaces an expression "currentEffects.equals(newEffects)" in the java. - // TODO - find out whether actually checking pointers to MobEffectInstance classes for equality - // is of any use - bool equals = false; - if( ( currentEffects != NULL ) && ( newEffects != NULL ) ) - { - if( currentEffects->size() == newEffects->size() ) - { - if( std::equal(currentEffects->begin(), currentEffects->end(), newEffects->begin() ) ) - { - equals = true; - } - } - } + // 4J - this code replaces an expression + // "currentEffects.equals(newEffects)" in the java. + // TODO - find out whether actually checking pointers to + // MobEffectInstance classes for equality is of any use + bool equals = false; + if ((currentEffects != NULL) && (newEffects != NULL)) { + if (currentEffects->size() == newEffects->size()) { + if (std::equal(currentEffects->begin(), + currentEffects->end(), + newEffects->begin())) { + equals = true; + } + } + } if ((currentBrew > 0 && currentEffects == newEffects) || - (currentEffects != NULL && (equals || newEffects == NULL))) - { - } - else if (currentBrew != newBrew) - { + (currentEffects != NULL && + (equals || newEffects == NULL))) { + } else if (currentBrew != newBrew) { oneResult = true; break; } @@ -132,31 +103,27 @@ bool BrewingStandTileEntity::isBrewable() } return oneResult; - } - else - { - if (!Item::items[ingredient->id]->hasPotionBrewingFormula() && ingredient->id != Item::bucket_water_Id && ingredient->id != Item::netherStalkSeeds_Id) - { + } else { + if (!Item::items[ingredient->id]->hasPotionBrewingFormula() && + ingredient->id != Item::bucket_water_Id && + ingredient->id != Item::netherStalkSeeds_Id) { return false; } bool isWater = ingredient->id == Item::bucket_water_Id; // at least one destination potion must have a result bool oneResult = false; - for (int dest = 0; dest < 3; dest++) - { - if (items[dest] != NULL && items[dest]->id == Item::potion_Id) - { + for (int dest = 0; dest < 3; dest++) { + if (items[dest] != NULL && items[dest]->id == Item::potion_Id) { int currentBrew = items[dest]->getAuxValue(); - int newBrew = NORMALISE_POTION_AUXVAL( applyIngredient(currentBrew, ingredient) ); - if (currentBrew != newBrew) - { + int newBrew = NORMALISE_POTION_AUXVAL( + applyIngredient(currentBrew, ingredient)); + if (currentBrew != newBrew) { oneResult = true; break; } - } - else if (isWater && items[dest] != NULL && items[dest]->id == Item::glassBottle_Id) - { + } else if (isWater && items[dest] != NULL && + items[dest]->id == Item::glassBottle_Id) { oneResult = true; break; } @@ -165,151 +132,134 @@ bool BrewingStandTileEntity::isBrewable() } } -void BrewingStandTileEntity::doBrew() -{ - if (!isBrewable()) - { +void BrewingStandTileEntity::doBrew() { + if (!isBrewable()) { return; } std::shared_ptr ingredient = items[INGREDIENT_SLOT]; - if (PotionBrewing::SIMPLIFIED_BREWING) - { - for (int dest = 0; dest < 3; dest++) - { - if (items[dest] != NULL && items[dest]->id == Item::potion_Id) - { + if (PotionBrewing::SIMPLIFIED_BREWING) { + for (int dest = 0; dest < 3; dest++) { + if (items[dest] != NULL && items[dest]->id == Item::potion_Id) { int currentBrew = items[dest]->getAuxValue(); - int newBrew = NORMALISE_POTION_AUXVAL( applyIngredient(currentBrew, ingredient) ); + int newBrew = NORMALISE_POTION_AUXVAL( + applyIngredient(currentBrew, ingredient)); - std::vector *currentEffects = Item::potion->getMobEffects(currentBrew); - std::vector *newEffects = Item::potion->getMobEffects(newBrew); + std::vector* currentEffects = + Item::potion->getMobEffects(currentBrew); + std::vector* newEffects = + Item::potion->getMobEffects(newBrew); - // 4J - this code replaces an expression "currentEffects.equals(newEffects)" in the java. - // TODO - find out whether actually checking pointers to MobEffectInstance classes for equality - // is of any use - bool equals = false; - if( ( currentEffects != NULL ) && ( newEffects != NULL ) ) - { - if( currentEffects->size() == newEffects->size() ) - { - if( std::equal(currentEffects->begin(), currentEffects->end(), newEffects->begin() ) ) - { - equals = true; - } - } - } + // 4J - this code replaces an expression + // "currentEffects.equals(newEffects)" in the java. + // TODO - find out whether actually checking pointers to + // MobEffectInstance classes for equality is of any use + bool equals = false; + if ((currentEffects != NULL) && (newEffects != NULL)) { + if (currentEffects->size() == newEffects->size()) { + if (std::equal(currentEffects->begin(), + currentEffects->end(), + newEffects->begin())) { + equals = true; + } + } + } if ((currentBrew > 0 && currentEffects == newEffects) || - (currentEffects != NULL && (equals || newEffects == NULL))) - { - if (!PotionItem::isThrowable(currentBrew) && PotionItem::isThrowable(newBrew)) - { + (currentEffects != NULL && + (equals || newEffects == NULL))) { + if (!PotionItem::isThrowable(currentBrew) && + PotionItem::isThrowable(newBrew)) { items[dest]->setAuxValue(newBrew); } - } - else if (currentBrew != newBrew) - { + } else if (currentBrew != newBrew) { items[dest]->setAuxValue(newBrew); } - } } - } - else - { + } else { bool isWater = ingredient->id == Item::bucket_water_Id; - for (int dest = 0; dest < 3; dest++) - { - if (items[dest] != NULL && items[dest]->id == Item::potion_Id) - { + for (int dest = 0; dest < 3; dest++) { + if (items[dest] != NULL && items[dest]->id == Item::potion_Id) { int currentBrew = items[dest]->getAuxValue(); - int newBrew = NORMALISE_POTION_AUXVAL( applyIngredient(currentBrew, ingredient) ); + int newBrew = NORMALISE_POTION_AUXVAL( + applyIngredient(currentBrew, ingredient)); items[dest]->setAuxValue(newBrew); - } - else if (isWater && items[dest] != NULL && items[dest]->id == Item::glassBottle_Id) - { - items[dest] = std::shared_ptr(new ItemInstance(Item::potion)); + } else if (isWater && items[dest] != NULL && + items[dest]->id == Item::glassBottle_Id) { + items[dest] = std::shared_ptr( + new ItemInstance(Item::potion)); } } } - if (Item::items[ingredient->id]->hasCraftingRemainingItem()) - { - items[INGREDIENT_SLOT] = std::shared_ptr(new ItemInstance(Item::items[ingredient->id]->getCraftingRemainingItem())); - } - else - { + if (Item::items[ingredient->id]->hasCraftingRemainingItem()) { + items[INGREDIENT_SLOT] = std::shared_ptr(new ItemInstance( + Item::items[ingredient->id]->getCraftingRemainingItem())); + } else { items[INGREDIENT_SLOT]->count--; - if (items[INGREDIENT_SLOT]->count <= 0) - { + if (items[INGREDIENT_SLOT]->count <= 0) { items[INGREDIENT_SLOT] = nullptr; } } } -int BrewingStandTileEntity::applyIngredient(int currentBrew, std::shared_ptr ingredient) -{ - if (ingredient == NULL) - { - return currentBrew; - } - if (!PotionBrewing::SIMPLIFIED_BREWING) - { +int BrewingStandTileEntity::applyIngredient( + int currentBrew, std::shared_ptr ingredient) { + if (ingredient == NULL) { + return currentBrew; + } + if (!PotionBrewing::SIMPLIFIED_BREWING) { #if !(_SIMPLIFIED_BREWING) - // 4J Stu - SIMPLIFIED_BREWING is on, so we never use this - if (ingredient->id == Item::bucket_water_Id) - { - return PotionBrewing::applyBrew(currentBrew, PotionBrewing::MOD_WATER); - } - if (ingredient->id == Item::netherStalkSeeds_Id) - { - return PotionBrewing::stirr(currentBrew); - } + // 4J Stu - SIMPLIFIED_BREWING is on, so we never use this + if (ingredient->id == Item::bucket_water_Id) { + return PotionBrewing::applyBrew(currentBrew, + PotionBrewing::MOD_WATER); + } + if (ingredient->id == Item::netherStalkSeeds_Id) { + return PotionBrewing::stirr(currentBrew); + } #endif - } - if (Item::items[ingredient->id]->hasPotionBrewingFormula()) - { - return PotionBrewing::applyBrew(currentBrew, Item::items[ingredient->id]->getPotionBrewingFormula()); - } - return currentBrew; + } + if (Item::items[ingredient->id]->hasPotionBrewingFormula()) { + return PotionBrewing::applyBrew( + currentBrew, + Item::items[ingredient->id]->getPotionBrewingFormula()); + } + return currentBrew; } - -void BrewingStandTileEntity::load(CompoundTag *base) -{ + +void BrewingStandTileEntity::load(CompoundTag* base) { TileEntity::load(base); - ListTag *inventoryList = base->getList(L"Items"); + ListTag* inventoryList = base->getList(L"Items"); - delete [] items.data; + delete[] items.data; items = ItemInstanceArray(getContainerSize()); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = (CompoundTag*) inventoryList->get(i); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = (CompoundTag*)inventoryList->get(i); int slot = tag->getByte(L"Slot"); - if (slot >= 0 && slot < items.length) items[slot] = ItemInstance::fromTag(tag); + if (slot >= 0 && slot < items.length) + items[slot] = ItemInstance::fromTag(tag); } brewTime = base->getShort(L"BrewTime"); } -void BrewingStandTileEntity::save(CompoundTag *base) -{ +void BrewingStandTileEntity::save(CompoundTag* base) { TileEntity::save(base); - base->putShort(L"BrewTime", (short) (brewTime)); - ListTag *listTag = new ListTag(); + base->putShort(L"BrewTime", (short)(brewTime)); + ListTag* listTag = new ListTag(); - for (int i = 0; i < items.length; i++) - { - if (items[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); + for (int i = 0; i < items.length; i++) { + if (items[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); items[i]->save(tag); listTag->add(tag); } @@ -317,96 +267,76 @@ void BrewingStandTileEntity::save(CompoundTag *base) base->put(L"Items", listTag); } -std::shared_ptr BrewingStandTileEntity::getItem(unsigned int slot) -{ - if (slot >= 0 && slot < items.length) - { - return items[slot]; - } - return nullptr; +std::shared_ptr BrewingStandTileEntity::getItem( + unsigned int slot) { + if (slot >= 0 && slot < items.length) { + return items[slot]; + } + return nullptr; } -std::shared_ptr BrewingStandTileEntity::removeItem(unsigned int slot, int count) -{ - // 4J Stu - Changed the implementation of this function to be the same as ChestTileEntity to enable the "Pickup Half" - // option on the ingredients slot - // Fix for #65373 - TU8: Content: UI: Command "Take Half" in the Brewing Stand interface doesn't work as intended. +std::shared_ptr BrewingStandTileEntity::removeItem( + unsigned int slot, int count) { + // 4J Stu - Changed the implementation of this function to be the same as + // ChestTileEntity to enable the "Pickup Half" option on the ingredients + // slot Fix for #65373 - TU8: Content: UI: Command "Take Half" in the + // Brewing Stand interface doesn't work as intended. - if (slot >= 0 && slot < items.length && items[slot] != NULL) - { - if (items[slot]->count <= count) - { - std::shared_ptr item = items[slot]; - items[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) return nullptr; - return item; - } - else - { - std::shared_ptr i = items[slot]->remove(count); - if (items[slot]->count == 0) items[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(i->count <= 0) return nullptr; - return i; - } - } - return nullptr; -} - -std::shared_ptr BrewingStandTileEntity::removeItemNoUpdate(int slot) -{ - if (slot >= 0 && slot < items.length) - { - std::shared_ptr item = items[slot]; - items[slot] = nullptr; - return item; - } - return nullptr; + if (slot >= 0 && slot < items.length && items[slot] != NULL) { + if (items[slot]->count <= count) { + std::shared_ptr item = items[slot]; + items[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) return nullptr; + return item; + } else { + std::shared_ptr i = items[slot]->remove(count); + if (items[slot]->count == 0) items[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (i->count <= 0) return nullptr; + return i; + } + } + return nullptr; } -void BrewingStandTileEntity::setItem(unsigned int slot, std::shared_ptr item) -{ - if (slot >= 0 && slot < items.length) - { +std::shared_ptr BrewingStandTileEntity::removeItemNoUpdate( + int slot) { + if (slot >= 0 && slot < items.length) { + std::shared_ptr item = items[slot]; + items[slot] = nullptr; + return item; + } + return nullptr; +} + +void BrewingStandTileEntity::setItem(unsigned int slot, + std::shared_ptr item) { + if (slot >= 0 && slot < items.length) { items[slot] = item; } } -int BrewingStandTileEntity::getMaxStackSize() -{ - return 1; -} +int BrewingStandTileEntity::getMaxStackSize() { return 1; } -bool BrewingStandTileEntity::stillValid(std::shared_ptr player) -{ +bool BrewingStandTileEntity::stillValid(std::shared_ptr player) { if (level->getTileEntity(x, y, z) != shared_from_this()) return false; if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; return true; } -void BrewingStandTileEntity::startOpen() -{ -} +void BrewingStandTileEntity::startOpen() {} -void BrewingStandTileEntity::stopOpen() -{ -} +void BrewingStandTileEntity::stopOpen() {} -void BrewingStandTileEntity::setBrewTime(int value) -{ - this->brewTime = value; -} +void BrewingStandTileEntity::setBrewTime(int value) { this->brewTime = value; } -int BrewingStandTileEntity::getPotionBits() -{ +int BrewingStandTileEntity::getPotionBits() { int newCount = 0; - for (int potion = 0; potion < 3; potion++) - { - if (items[potion] != NULL) - { + for (int potion = 0; potion < 3; potion++) { + if (items[potion] != NULL) { newCount |= (1 << potion); } } @@ -414,21 +344,19 @@ int BrewingStandTileEntity::getPotionBits() } // 4J Added -std::shared_ptr BrewingStandTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new BrewingStandTileEntity() ); - TileEntity::clone(result); +std::shared_ptr BrewingStandTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new BrewingStandTileEntity()); + TileEntity::clone(result); - result->brewTime = brewTime; + result->brewTime = brewTime; result->lastPotionCount = lastPotionCount; result->ingredientId = ingredientId; - for (unsigned int i = 0; i < items.length; i++) - { - if (items.data[i] != NULL) - { - result->items.data[i] = ItemInstance::clone(items.data[i]); - } - } - return result; + for (unsigned int i = 0; i < items.length; i++) { + if (items.data[i] != NULL) { + result->items.data[i] = ItemInstance::clone(items.data[i]); + } + } + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.h b/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.h index df8d6b3a0..cfe569fd5 100644 --- a/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/BrewingStandTileEntity.h @@ -2,14 +2,13 @@ #include "TileEntity.h" #include "../../Containers/Container.h" -class BrewingStandTileEntity : public TileEntity, public Container -{ +class BrewingStandTileEntity : public TileEntity, public Container { public: - eINSTANCEOF GetType() { return eTYPE_BREWINGSTANDTILEENTITY; } - static TileEntity *create() { return new BrewingStandTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_BREWINGSTANDTILEENTITY; } + static TileEntity* create() { return new BrewingStandTileEntity(); } private: - ItemInstanceArray items; + ItemInstanceArray items; static const int INGREDIENT_SLOT = 3; int brewTime; @@ -17,35 +16,36 @@ private: int ingredientId; public: - BrewingStandTileEntity(); - ~BrewingStandTileEntity(); - virtual int getName(); - virtual unsigned int getContainerSize(); - virtual void tick(); + BrewingStandTileEntity(); + ~BrewingStandTileEntity(); + virtual int getName(); + virtual unsigned int getContainerSize(); + virtual void tick(); int getBrewTime(); private: - bool isBrewable(); + bool isBrewable(); void doBrew(); - int applyIngredient(int currentBrew, std::shared_ptr ingredient); - + int applyIngredient(int currentBrew, + std::shared_ptr ingredient); + public: - virtual void load(CompoundTag *base); - virtual void save(CompoundTag *base); + virtual void load(CompoundTag* base); + virtual void save(CompoundTag* base); virtual std::shared_ptr getItem(unsigned int slot); virtual std::shared_ptr removeItem(unsigned int slot, int i); - virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual std::shared_ptr removeItemNoUpdate(int slot); virtual void setItem(unsigned int slot, std::shared_ptr item); virtual int getMaxStackSize(); virtual bool stillValid(std::shared_ptr player); virtual void startOpen(); virtual void stopOpen(); virtual void setBrewTime(int value); - virtual void setChanged() {} // 4J added + virtual void setChanged() {} // 4J added int getPotionBits(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/ChestTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/ChestTileEntity.cpp index 820aa482d..35ad31166 100644 --- a/Minecraft.World/Blocks/TileEntities/ChestTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/ChestTileEntity.cpp @@ -11,154 +11,126 @@ #include "ChestTileEntity.h" #include "../../Util/SoundTypes.h" +ChestTileEntity::ChestTileEntity(bool isBonusChest /* = false*/) + : TileEntity() { + items = new ItemInstanceArray(9 * 4); + hasCheckedNeighbors = false; + this->isBonusChest = isBonusChest; -ChestTileEntity::ChestTileEntity(bool isBonusChest/* = false*/) : TileEntity() -{ - items = new ItemInstanceArray(9 * 4); - - hasCheckedNeighbors = false; - this->isBonusChest = isBonusChest; - - openness = 0.0f; - oOpenness = 0.0f; - openCount = 0; - tickInterval = 0; + openness = 0.0f; + oOpenness = 0.0f; + openCount = 0; + tickInterval = 0; } -ChestTileEntity::~ChestTileEntity() -{ - delete[] items->data; - delete items; +ChestTileEntity::~ChestTileEntity() { + delete[] items->data; + delete items; } -unsigned int ChestTileEntity::getContainerSize() -{ - return 9 * 3; +unsigned int ChestTileEntity::getContainerSize() { return 9 * 3; } + +std::shared_ptr ChestTileEntity::getItem(unsigned int slot) { + return items->data[slot]; } -std::shared_ptr ChestTileEntity::getItem(unsigned int slot) -{ - return items->data[slot]; +std::shared_ptr ChestTileEntity::removeItem(unsigned int slot, + int count) { + if (items->data[slot] != NULL) { + if (items->data[slot]->count <= count) { + std::shared_ptr item = items->data[slot]; + items->data[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) return nullptr; + return item; + } else { + std::shared_ptr i = items->data[slot]->remove(count); + if (items->data[slot]->count == 0) items->data[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (i->count <= 0) return nullptr; + return i; + } + } + return nullptr; } -std::shared_ptr ChestTileEntity::removeItem(unsigned int slot, int count) -{ - if (items->data[slot] != NULL) - { - if (items->data[slot]->count <= count) - { - std::shared_ptr item = items->data[slot]; - items->data[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) return nullptr; - return item; - } - else - { - std::shared_ptr i = items->data[slot]->remove(count); - if (items->data[slot]->count == 0) items->data[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(i->count <= 0) return nullptr; - return i; - } - } - return nullptr; +std::shared_ptr ChestTileEntity::removeItemNoUpdate(int slot) { + if (items->data[slot] != NULL) { + std::shared_ptr item = items->data[slot]; + items->data[slot] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr ChestTileEntity::removeItemNoUpdate(int slot) -{ - if (items->data[slot] != NULL) - { - std::shared_ptr item = items->data[slot]; - items->data[slot] = nullptr; - return item; - } - return nullptr; +void ChestTileEntity::setItem(unsigned int slot, + std::shared_ptr item) { + items->data[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); + this->setChanged(); } -void ChestTileEntity::setItem(unsigned int slot, std::shared_ptr item) -{ - items->data[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); - this->setChanged(); +int ChestTileEntity::getName() { return IDS_TILE_CHEST; } + +void ChestTileEntity::load(CompoundTag* base) { + TileEntity::load(base); + + // 4jcraft, fixed cast of templated List to get the tag list + // and cast it to CompoundTag inside the loop + ListTag* inventoryList = base->getList(L"Items"); + + if (items) { + delete[] items->data; + delete items; + } + items = new ItemInstanceArray(getContainerSize()); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = (CompoundTag*)inventoryList->get(i); + unsigned int slot = tag->getByte(L"Slot") & 0xff; + if (slot >= 0 && slot < items->length) + (*items)[slot] = ItemInstance::fromTag(tag); + } + isBonusChest = base->getBoolean(L"bonus"); } -int ChestTileEntity::getName() -{ - return IDS_TILE_CHEST; +void ChestTileEntity::save(CompoundTag* base) { + TileEntity::save(base); + ListTag* listTag = new ListTag; + + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + items->data[i]->save(tag); + listTag->add(tag); + } + } + base->put(L"Items", listTag); + base->putBoolean(L"bonus", isBonusChest); } - -void ChestTileEntity::load(CompoundTag *base) -{ - TileEntity::load(base); - - // 4jcraft, fixed cast of templated List to get the tag list - // and cast it to CompoundTag inside the loop - ListTag *inventoryList = base->getList(L"Items"); - - if( items ) - { - delete [] items->data; - delete items; - } - items = new ItemInstanceArray(getContainerSize()); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = (CompoundTag*) inventoryList->get(i); - unsigned int slot = tag->getByte(L"Slot") & 0xff; - if (slot >= 0 && slot < items->length) (*items)[slot] = ItemInstance::fromTag(tag); - } - isBonusChest = base->getBoolean(L"bonus"); +int ChestTileEntity::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -void ChestTileEntity::save(CompoundTag *base) -{ - TileEntity::save(base); - ListTag *listTag = new ListTag; - - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - items->data[i]->save(tag); - listTag->add(tag); - } - } - base->put(L"Items", listTag); - base->putBoolean(L"bonus", isBonusChest); +bool ChestTileEntity::stillValid(std::shared_ptr player) { + if (level->getTileEntity(x, y, z) != shared_from_this()) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } -int ChestTileEntity::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; -} +void ChestTileEntity::setChanged() { TileEntity::setChanged(); } -bool ChestTileEntity::stillValid(std::shared_ptr player) -{ - if (level->getTileEntity(x, y, z) != shared_from_this() ) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; -} - -void ChestTileEntity::setChanged() -{ - TileEntity::setChanged(); -} - -void ChestTileEntity::clearCache() -{ +void ChestTileEntity::clearCache() { TileEntity::clearCache(); hasCheckedNeighbors = false; } -void ChestTileEntity::checkNeighbors() -{ +void ChestTileEntity::checkNeighbors() { if (hasCheckedNeighbors) return; hasCheckedNeighbors = true; @@ -167,21 +139,21 @@ void ChestTileEntity::checkNeighbors() w = std::weak_ptr(); s = std::weak_ptr(); - if (level->getTile(x - 1, y, z) == Tile::chest_Id) - { - w = std::dynamic_pointer_cast(level->getTileEntity(x - 1, y, z)); + if (level->getTile(x - 1, y, z) == Tile::chest_Id) { + w = std::dynamic_pointer_cast( + level->getTileEntity(x - 1, y, z)); } - if (level->getTile(x + 1, y, z) == Tile::chest_Id) - { - e = std::dynamic_pointer_cast(level->getTileEntity(x + 1, y, z)); + if (level->getTile(x + 1, y, z) == Tile::chest_Id) { + e = std::dynamic_pointer_cast( + level->getTileEntity(x + 1, y, z)); } - if (level->getTile(x, y, z - 1) == Tile::chest_Id) - { - n = std::dynamic_pointer_cast(level->getTileEntity(x, y, z - 1)); + if (level->getTile(x, y, z - 1) == Tile::chest_Id) { + n = std::dynamic_pointer_cast( + level->getTileEntity(x, y, z - 1)); } - if (level->getTile(x, y, z + 1) == Tile::chest_Id) - { - s = std::dynamic_pointer_cast(level->getTileEntity(x, y, z + 1)); + if (level->getTile(x, y, z + 1) == Tile::chest_Id) { + s = std::dynamic_pointer_cast( + level->getTileEntity(x, y, z + 1)); } if (n.lock() != NULL) n.lock()->clearCache(); @@ -190,104 +162,98 @@ void ChestTileEntity::checkNeighbors() if (w.lock() != NULL) w.lock()->clearCache(); } -void ChestTileEntity::tick() -{ +void ChestTileEntity::tick() { TileEntity::tick(); checkNeighbors(); - if (++tickInterval % 20 * 4 == 0) - { - //level->tileEvent(x, y, z, ChestTile::EVENT_SET_OPEN_COUNT, openCount); + if (++tickInterval % 20 * 4 == 0) { + // level->tileEvent(x, y, z, ChestTile::EVENT_SET_OPEN_COUNT, + // openCount); } oOpenness = openness; float speed = 0.10f; - if (openCount > 0 && openness == 0) - { - if (n.lock() == NULL && w.lock() == NULL) - { + if (openCount > 0 && openness == 0) { + if (n.lock() == NULL && w.lock() == NULL) { double xc = x + 0.5; double zc = z + 0.5; if (s.lock() != NULL) zc += 0.5; if (e.lock() != NULL) xc += 0.5; - // 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit - level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_OPEN, 0.2f, level->random->nextFloat() * 0.1f + 0.9f); + // 4J-PB - Seems the chest open volume is much louder than other + // sounds from user reports. We'll tone it down a bit + level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_OPEN, + 0.2f, level->random->nextFloat() * 0.1f + 0.9f); } } - if ((openCount == 0 && openness > 0) || (openCount > 0 && openness < 1)) - { - float oldOpen = openness; - if (openCount > 0) openness += speed; - else openness -= speed; - if (openness > 1) - { + if ((openCount == 0 && openness > 0) || (openCount > 0 && openness < 1)) { + float oldOpen = openness; + if (openCount > 0) + openness += speed; + else + openness -= speed; + if (openness > 1) { openness = 1; } - float lim = 0.5f; - if (openness < lim && oldOpen >= lim) - { - // Fix for #64546 - Customer Encountered: TU7: Chests placed by the Player are closing too fast. - //openness = 0; - if (n.lock() == NULL && w.lock() == NULL) - { + float lim = 0.5f; + if (openness < lim && oldOpen >= lim) { + // Fix for #64546 - Customer Encountered: TU7: Chests placed by the + // Player are closing too fast. + // openness = 0; + if (n.lock() == NULL && w.lock() == NULL) { double xc = x + 0.5; double zc = z + 0.5; if (s.lock() != NULL) zc += 0.5; if (e.lock() != NULL) xc += 0.5; - // 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit - level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_CLOSE, 0.2f, level->random->nextFloat() * 0.1f + 0.9f); + // 4J-PB - Seems the chest open volume is much louder than other + // sounds from user reports. We'll tone it down a bit + level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_CLOSE, + 0.2f, + level->random->nextFloat() * 0.1f + 0.9f); } - } - if (openness < 0) - { + } + if (openness < 0) { openness = 0; } } - } -void ChestTileEntity::triggerEvent(int b0, int b1) -{ - if (b0 == ChestTile::EVENT_SET_OPEN_COUNT) - { +void ChestTileEntity::triggerEvent(int b0, int b1) { + if (b0 == ChestTile::EVENT_SET_OPEN_COUNT) { openCount = b1; } } -void ChestTileEntity::startOpen() -{ - openCount++; - level->tileEvent(x, y, z, Tile::chest_Id, ChestTile::EVENT_SET_OPEN_COUNT, openCount); +void ChestTileEntity::startOpen() { + openCount++; + level->tileEvent(x, y, z, Tile::chest_Id, ChestTile::EVENT_SET_OPEN_COUNT, + openCount); } -void ChestTileEntity::stopOpen() -{ - openCount--; - level->tileEvent(x, y, z, Tile::chest_Id, ChestTile::EVENT_SET_OPEN_COUNT, openCount); +void ChestTileEntity::stopOpen() { + openCount--; + level->tileEvent(x, y, z, Tile::chest_Id, ChestTile::EVENT_SET_OPEN_COUNT, + openCount); } -void ChestTileEntity::setRemoved() -{ +void ChestTileEntity::setRemoved() { clearCache(); checkNeighbors(); TileEntity::setRemoved(); } // 4J Added -std::shared_ptr ChestTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new ChestTileEntity() ); - TileEntity::clone(result); +std::shared_ptr ChestTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new ChestTileEntity()); + TileEntity::clone(result); - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL) - { - result->items->data[i] = ItemInstance::clone(items->data[i]); - } - } - return result; + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL) { + result->items->data[i] = ItemInstance::clone(items->data[i]); + } + } + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/ChestTileEntity.h b/Minecraft.World/Blocks/TileEntities/ChestTileEntity.h index 1778898d6..83f4d3b3e 100644 --- a/Minecraft.World/Blocks/TileEntities/ChestTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/ChestTileEntity.h @@ -1,7 +1,5 @@ #pragma once - - #include "TileEntity.h" #include "../../Containers/Container.h" @@ -10,47 +8,48 @@ class Player; class CompoundTag; -class ChestTileEntity : public TileEntity, public Container -{ +class ChestTileEntity : public TileEntity, public Container { public: - eINSTANCEOF GetType() { return eTYPE_CHESTTILEENTITY; } - static TileEntity *create() { return new ChestTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_CHESTTILEENTITY; } + static TileEntity* create() { return new ChestTileEntity(); } -using TileEntity::setChanged; + using TileEntity::setChanged; public: - ChestTileEntity(bool isBonusChest = false); // 4J added param - virtual ~ChestTileEntity(); + ChestTileEntity(bool isBonusChest = false); // 4J added param + virtual ~ChestTileEntity(); private: - ItemInstanceArray *items; + ItemInstanceArray* items; public: - bool isBonusChest; // 4J added - bool hasCheckedNeighbors; + bool isBonusChest; // 4J added + bool hasCheckedNeighbors; std::weak_ptr n; std::weak_ptr e; std::weak_ptr w; std::weak_ptr s; - float openness, oOpenness; - int openCount; + float openness, oOpenness; + int openCount; + private: - int tickInterval; + int tickInterval; public: - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - virtual std::shared_ptr removeItemNoUpdate(int slot); - virtual void setItem(unsigned int slot, std::shared_ptr item); - virtual int getName(); - virtual void load(CompoundTag *base); - virtual void save(CompoundTag *base); - virtual int getMaxStackSize(); - virtual bool stillValid(std::shared_ptr player); - virtual void setChanged(); - virtual void clearCache(); + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual void setItem(unsigned int slot, std::shared_ptr item); + virtual int getName(); + virtual void load(CompoundTag* base); + virtual void save(CompoundTag* base); + virtual int getMaxStackSize(); + virtual bool stillValid(std::shared_ptr player); + virtual void setChanged(); + virtual void clearCache(); virtual void checkNeighbors(); virtual void tick(); virtual void triggerEvent(int b0, int b1); @@ -58,6 +57,6 @@ public: virtual void stopOpen(); virtual void setRemoved(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.cpp index 6673c992a..e1c79cc57 100644 --- a/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.cpp @@ -9,216 +9,176 @@ #include "../../Headers/net.minecraft.world.item.h" #include "DispenserTileEntity.h" - - -DispenserTileEntity::DispenserTileEntity() : TileEntity() -{ - items = new ItemInstanceArray(9); - random = new Random(); +DispenserTileEntity::DispenserTileEntity() : TileEntity() { + items = new ItemInstanceArray(9); + random = new Random(); } -DispenserTileEntity::~DispenserTileEntity() -{ - delete[] items->data; - delete items; +DispenserTileEntity::~DispenserTileEntity() { + delete[] items->data; + delete items; - delete random; + delete random; } -unsigned int DispenserTileEntity::getContainerSize() -{ - return 9; +unsigned int DispenserTileEntity::getContainerSize() { return 9; } + +std::shared_ptr DispenserTileEntity::getItem(unsigned int slot) { + return items->data[slot]; } -std::shared_ptr DispenserTileEntity::getItem(unsigned int slot) -{ - return items->data[slot]; +std::shared_ptr DispenserTileEntity::removeItem(unsigned int slot, + int count) { + if (items->data[slot] != NULL) { + if (items->data[slot]->count <= count) { + std::shared_ptr item = items->data[slot]; + items->data[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) return nullptr; + return item; + } else { + std::shared_ptr i = items->data[slot]->remove(count); + if (items->data[slot]->count == 0) items->data[slot] = nullptr; + this->setChanged(); + // 4J Stu - Fix for duplication glitch + if (i->count <= 0) return nullptr; + return i; + } + } + return nullptr; } -std::shared_ptr DispenserTileEntity::removeItem(unsigned int slot, int count) -{ - if (items->data[slot] != NULL) - { - if (items->data[slot]->count <= count) - { - std::shared_ptr item = items->data[slot]; - items->data[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) return nullptr; - return item; - } - else - { - std::shared_ptr i = items->data[slot]->remove(count); - if (items->data[slot]->count == 0) items->data[slot] = nullptr; - this->setChanged(); - // 4J Stu - Fix for duplication glitch - if(i->count <= 0) return nullptr; - return i; - } - } - return nullptr; +std::shared_ptr DispenserTileEntity::removeItemNoUpdate( + int slot) { + if (items->data[slot] != NULL) { + std::shared_ptr item = items->data[slot]; + items->data[slot] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr DispenserTileEntity::removeItemNoUpdate(int slot) -{ - if (items->data[slot] != NULL) - { - std::shared_ptr item = items->data[slot]; - items->data[slot] = nullptr; - return item; - } - return nullptr; -} - -// 4J-PB added for spawn eggs not being useable due to limits, so add them in again -void DispenserTileEntity::AddItemBack(std::shared_ptritem, unsigned int slot) -{ - if (items->data[slot] != NULL) - { - // just increment the count of the items - if(item->id==items->data[slot]->id) - { - items->data[slot]->count++; - this->setChanged(); - } - } - else - { - items->data[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); - this->setChanged(); - } +// 4J-PB added for spawn eggs not being useable due to limits, so add them in +// again +void DispenserTileEntity::AddItemBack(std::shared_ptr item, + unsigned int slot) { + if (items->data[slot] != NULL) { + // just increment the count of the items + if (item->id == items->data[slot]->id) { + items->data[slot]->count++; + this->setChanged(); + } + } else { + items->data[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); + this->setChanged(); + } } /** -* Removes an item with the given id and returns true if one was found. -* -* @param itemId -* @return -*/ -bool DispenserTileEntity::removeProjectile(int itemId) -{ - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL && items->data[i]->id == itemId) - { - std::shared_ptr removedItem = removeItem(i, 1); - return removedItem != NULL; - } - } - return false; + * Removes an item with the given id and returns true if one was found. + * + * @param itemId + * @return + */ +bool DispenserTileEntity::removeProjectile(int itemId) { + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL && items->data[i]->id == itemId) { + std::shared_ptr removedItem = removeItem(i, 1); + return removedItem != NULL; + } + } + return false; } -int DispenserTileEntity::getRandomSlot() -{ - int replaceSlot = -1; - int replaceOdds = 1; - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL && random->nextInt(replaceOdds++) == 0) - { - replaceSlot = i; - } - } +int DispenserTileEntity::getRandomSlot() { + int replaceSlot = -1; + int replaceOdds = 1; + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL && random->nextInt(replaceOdds++) == 0) { + replaceSlot = i; + } + } - return replaceSlot; + return replaceSlot; } -void DispenserTileEntity::setItem(unsigned int slot, std::shared_ptr item) -{ - items->data[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); - this->setChanged(); +void DispenserTileEntity::setItem(unsigned int slot, + std::shared_ptr item) { + items->data[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); + this->setChanged(); } -int DispenserTileEntity::addItem(std::shared_ptr item) -{ - for (int i = 0; i < items->length; i++) - { - if ((*items)[i] == NULL || (*items)[i]->id == 0) - { - (*items)[i] = item; - return i; - } - } +int DispenserTileEntity::addItem(std::shared_ptr item) { + for (int i = 0; i < items->length; i++) { + if ((*items)[i] == NULL || (*items)[i]->id == 0) { + (*items)[i] = item; + return i; + } + } - return -1; + return -1; } -int DispenserTileEntity::getName() -{ - return IDS_TILE_DISPENSER; +int DispenserTileEntity::getName() { return IDS_TILE_DISPENSER; } + +void DispenserTileEntity::load(CompoundTag* base) { + TileEntity::load(base); + ListTag* inventoryList = + (ListTag*)base->getList(L"Items"); + items = new ItemInstanceArray(getContainerSize()); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = inventoryList->get(i); + unsigned int slot = tag->getByte(L"Slot") & 0xff; + if (slot >= 0 && slot < items->length) + (*items)[slot] = ItemInstance::fromTag(tag); + } } -void DispenserTileEntity::load(CompoundTag *base) -{ - TileEntity::load(base); - ListTag *inventoryList = (ListTag *) base->getList(L"Items"); - items = new ItemInstanceArray(getContainerSize()); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = inventoryList->get(i); - unsigned int slot = tag->getByte(L"Slot") & 0xff; - if (slot >= 0 && slot < items->length) (*items)[slot] = ItemInstance::fromTag(tag); - } +void DispenserTileEntity::save(CompoundTag* base) { + TileEntity::save(base); + ListTag* listTag = new ListTag; + + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + items->data[i]->save(tag); + listTag->add(tag); + } + } + base->put(L"Items", listTag); } -void DispenserTileEntity::save(CompoundTag *base) -{ - TileEntity::save(base); - ListTag *listTag = new ListTag; - - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - items->data[i]->save(tag); - listTag->add(tag); - } - } - base->put(L"Items", listTag); +int DispenserTileEntity::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -int DispenserTileEntity::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; +bool DispenserTileEntity::stillValid(std::shared_ptr player) { + if (level->getTileEntity(x, y, z) != shared_from_this()) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } -bool DispenserTileEntity::stillValid(std::shared_ptr player) -{ - if (level->getTileEntity(x, y, z) != shared_from_this() ) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; -} +void DispenserTileEntity::setChanged() { return TileEntity::setChanged(); } -void DispenserTileEntity::setChanged() -{ - return TileEntity::setChanged(); -} +void DispenserTileEntity::startOpen() {} -void DispenserTileEntity::startOpen() -{ -} - -void DispenserTileEntity::stopOpen() -{ -} +void DispenserTileEntity::stopOpen() {} // 4J Added -std::shared_ptr DispenserTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new DispenserTileEntity() ); - TileEntity::clone(result); +std::shared_ptr DispenserTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new DispenserTileEntity()); + TileEntity::clone(result); - for (unsigned int i = 0; i < items->length; i++) - { - if (items->data[i] != NULL) - { - result->items->data[i] = ItemInstance::clone(items->data[i]); - } - } - return result; + for (unsigned int i = 0; i < items->length; i++) { + if (items->data[i] != NULL) { + result->items->data[i] = ItemInstance::clone(items->data[i]); + } + } + return result; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.h b/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.h index 6e72e09b8..7ccb69d97 100644 --- a/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/DispenserTileEntity.h @@ -1,7 +1,5 @@ #pragma once - - #include "../../Headers/com.mojang.nbt.h" #include "TileEntity.h" #include "../../Containers/Container.h" @@ -11,42 +9,41 @@ class Random; class Level; class CompoundTag; -class DispenserTileEntity: public TileEntity, public Container -{ +class DispenserTileEntity : public TileEntity, public Container { public: - eINSTANCEOF GetType() { return eTYPE_DISPENSERTILEENTITY; } - static TileEntity *create() { return new DispenserTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_DISPENSERTILEENTITY; } + static TileEntity* create() { return new DispenserTileEntity(); } - -using TileEntity::setChanged; + using TileEntity::setChanged; private: - ItemInstanceArray *items; - Random *random; + ItemInstanceArray* items; + Random* random; public: - DispenserTileEntity(); - virtual ~DispenserTileEntity(); + DispenserTileEntity(); + virtual ~DispenserTileEntity(); - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - std::shared_ptr removeItemNoUpdate(int slot); - bool removeProjectile(int itemId); - int getRandomSlot(); - virtual void setItem(unsigned int slot, std::shared_ptr item); - virtual int addItem(std::shared_ptr item); - virtual int getName(); - virtual void load(CompoundTag *base); - virtual void save(CompoundTag *base); - virtual int getMaxStackSize(); - virtual bool stillValid(std::shared_ptr player); - virtual void setChanged(); + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + std::shared_ptr removeItemNoUpdate(int slot); + bool removeProjectile(int itemId); + int getRandomSlot(); + virtual void setItem(unsigned int slot, std::shared_ptr item); + virtual int addItem(std::shared_ptr item); + virtual int getName(); + virtual void load(CompoundTag* base); + virtual void save(CompoundTag* base); + virtual int getMaxStackSize(); + virtual bool stillValid(std::shared_ptr player); + virtual void setChanged(); void startOpen(); void stopOpen(); - // 4J Added - virtual std::shared_ptr clone(); - void AddItemBack(std::shared_ptritem, unsigned int slot); + // 4J Added + virtual std::shared_ptr clone(); + void AddItemBack(std::shared_ptr item, unsigned int slot); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.cpp index e83c2ac45..f5fd2bba9 100644 --- a/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.cpp @@ -3,107 +3,90 @@ #include "../../Headers/net.minecraft.world.entity.player.h" #include "../../Headers/net.minecraft.world.level.h" +EnchantmentTableEntity::EnchantmentTableEntity() { + random = new Random(); - -EnchantmentTableEntity::EnchantmentTableEntity() -{ - random = new Random(); - - time = 0; + time = 0; flip = 0.0f; - oFlip = 0.0f; - flipT = 0.0f; - flipA = 0.0f; + oFlip = 0.0f; + flipT = 0.0f; + flipA = 0.0f; open = 0.0f; - oOpen = 0.0f; + oOpen = 0.0f; rot = 0.0f; - oRot = 0.0f; - tRot = 0.0f; + oRot = 0.0f; + tRot = 0.0f; } -EnchantmentTableEntity::~EnchantmentTableEntity() -{ - delete random; +EnchantmentTableEntity::~EnchantmentTableEntity() { delete random; } + +void EnchantmentTableEntity::tick() { + TileEntity::tick(); + oOpen = open; + oRot = rot; + + std::shared_ptr player = + level->getNearestPlayer(x + 0.5f, y + 0.5f, z + 0.5f, 3); + if (player != NULL) { + double xd = player->x - (x + 0.5f); + double zd = player->z - (z + 0.5f); + + tRot = (float)atan2(zd, xd); + + open += 0.1f; + + if (open < 0.5f || random->nextInt(40) == 0) { + float old = flipT; + do { + flipT += random->nextInt(4) - random->nextInt(4); + } while (old == flipT); + } + + } else { + tRot += 0.02f; + open -= 0.1f; + } + + while (rot >= PI) rot -= PI * 2; + while (rot < -PI) rot += PI * 2; + while (tRot >= PI) tRot -= PI * 2; + while (tRot < -PI) tRot += PI * 2; + float rotDir = tRot - rot; + while (rotDir >= PI) rotDir -= PI * 2; + while (rotDir < -PI) rotDir += PI * 2; + + rot += rotDir * 0.4f; + + if (open < 0) open = 0; + if (open > 1) open = 1; + + time++; + oFlip = flip; + + float diff = (flipT - flip) * 0.4f; + float max = 0.2f; + if (diff < -max) diff = -max; + if (diff > +max) diff = +max; + flipA += (diff - flipA) * 0.9f; + + flip = flip + flipA; } -void EnchantmentTableEntity::tick() -{ - TileEntity::tick(); - oOpen = open; - oRot = rot; +std::shared_ptr EnchantmentTableEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new EnchantmentTableEntity()); + TileEntity::clone(result); - std::shared_ptr player = level->getNearestPlayer(x + 0.5f, y + 0.5f, z + 0.5f, 3); - if (player != NULL) - { - double xd = player->x - (x + 0.5f); - double zd = player->z - (z + 0.5f); + result->time = time; + result->flip = flip; + result->oFlip = oFlip; + result->flipT = flipT; + result->flipA = flipA; + result->open = open; + result->oOpen = oOpen; + result->rot = rot; + result->oRot = oRot; + result->tRot = tRot; - tRot = (float) atan2(zd, xd); - - open += 0.1f; - - if (open < 0.5f || random->nextInt(40) == 0) - { - float old = flipT; - do - { - flipT += random->nextInt(4) - random->nextInt(4); - } while (old == flipT); - } - - } - else - { - tRot += 0.02f; - open -= 0.1f; - } - - while (rot >= PI) - rot -= PI * 2; - while (rot < -PI) - rot += PI * 2; - while (tRot >= PI) - tRot -= PI * 2; - while (tRot < -PI) - tRot += PI * 2; - float rotDir = tRot - rot; - while (rotDir >= PI) - rotDir -= PI * 2; - while (rotDir < -PI) - rotDir += PI * 2; - - rot += rotDir * 0.4f; - - if (open < 0) open = 0; - if (open > 1) open = 1; - - time++; - oFlip = flip; - - float diff = (flipT - flip) * 0.4f; - float max = 0.2f; - if (diff < -max) diff = -max; - if (diff > +max) diff = +max; - flipA += (diff - flipA) * 0.9f; - - flip = flip + flipA; -} - -std::shared_ptr EnchantmentTableEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new EnchantmentTableEntity() ); - TileEntity::clone(result); - - result->time = time; - result->flip = flip; - result->oFlip = oFlip; - result->flipT = flipT; - result->flipA = flipA; - result->open = open; - result->oOpen = oOpen; - result->rot = rot; - result->oRot = oRot; - result->tRot = tRot; - - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.h b/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.h index c7cef9f74..baefffca1 100644 --- a/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/EnchantmentTableTileEntity.h @@ -2,24 +2,25 @@ #include "TileEntity.h" class Random; -class EnchantmentTableEntity : public TileEntity -{ +class EnchantmentTableEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEENTITY; } - static TileEntity *create() { return new EnchantmentTableEntity(); } + eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEENTITY; } + static TileEntity* create() { return new EnchantmentTableEntity(); } public: - int time; + int time; float flip, oFlip, flipT, flipA; float open, oOpen; float rot, oRot, tRot; + private: - Random *random; + Random* random; + public: - EnchantmentTableEntity(); - ~EnchantmentTableEntity(); + EnchantmentTableEntity(); + ~EnchantmentTableEntity(); virtual void tick(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.cpp index e474e37da..260875bb8 100644 --- a/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.cpp @@ -3,97 +3,92 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "EnderChestTileEntity.h" -EnderChestTileEntity::EnderChestTileEntity() -{ - openness = oOpenness = 0.0f; - openCount = 0; - tickInterval = 0; +EnderChestTileEntity::EnderChestTileEntity() { + openness = oOpenness = 0.0f; + openCount = 0; + tickInterval = 0; } -void EnderChestTileEntity::tick() -{ - TileEntity::tick(); +void EnderChestTileEntity::tick() { + TileEntity::tick(); - if (++tickInterval % 20 * 4 == 0) - { - level->tileEvent(x, y, z, Tile::enderChest_Id, ChestTile::EVENT_SET_OPEN_COUNT, openCount); - } + if (++tickInterval % 20 * 4 == 0) { + level->tileEvent(x, y, z, Tile::enderChest_Id, + ChestTile::EVENT_SET_OPEN_COUNT, openCount); + } - oOpenness = openness; + oOpenness = openness; - float speed = 0.10f; - if (openCount > 0 && openness == 0) - { - double xc = x + 0.5; - double zc = z + 0.5; + float speed = 0.10f; + if (openCount > 0 && openness == 0) { + double xc = x + 0.5; + double zc = z + 0.5; - // 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit - level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_OPEN, 0.2f, level->random->nextFloat() * 0.1f + 0.9f); - } - if ((openCount == 0 && openness > 0) || (openCount > 0 && openness < 1)) - { - float oldOpen = openness; - if (openCount > 0) openness += speed; - else openness -= speed; - if (openness > 1) - { - openness = 1; - } - float lim = 0.5f; - if (openness < lim && oldOpen >= lim) - { - double xc = x + 0.5; - double zc = z + 0.5; + // 4J-PB - Seems the chest open volume is much louder than other sounds + // from user reports. We'll tone it down a bit + level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_OPEN, 0.2f, + level->random->nextFloat() * 0.1f + 0.9f); + } + if ((openCount == 0 && openness > 0) || (openCount > 0 && openness < 1)) { + float oldOpen = openness; + if (openCount > 0) + openness += speed; + else + openness -= speed; + if (openness > 1) { + openness = 1; + } + float lim = 0.5f; + if (openness < lim && oldOpen >= lim) { + double xc = x + 0.5; + double zc = z + 0.5; - // 4J-PB - Seems the chest open volume is much louder than other sounds from user reports. We'll tone it down a bit - level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_CLOSE, 0.2f, level->random->nextFloat() * 0.1f + 0.9f); - } - if (openness < 0) - { - openness = 0; - } - } + // 4J-PB - Seems the chest open volume is much louder than other + // sounds from user reports. We'll tone it down a bit + level->playSound(xc, y + 0.5, zc, eSoundType_RANDOM_CHEST_CLOSE, + 0.2f, level->random->nextFloat() * 0.1f + 0.9f); + } + if (openness < 0) { + openness = 0; + } + } } -void EnderChestTileEntity::triggerEvent(int b0, int b1) -{ - if (b0 == ChestTile::EVENT_SET_OPEN_COUNT) - { - openCount = b1; - } +void EnderChestTileEntity::triggerEvent(int b0, int b1) { + if (b0 == ChestTile::EVENT_SET_OPEN_COUNT) { + openCount = b1; + } } -void EnderChestTileEntity::setRemoved() -{ - clearCache(); - TileEntity::setRemoved(); +void EnderChestTileEntity::setRemoved() { + clearCache(); + TileEntity::setRemoved(); } -void EnderChestTileEntity::startOpen() -{ - openCount++; - level->tileEvent(x, y, z, Tile::enderChest_Id, ChestTile::EVENT_SET_OPEN_COUNT, openCount); +void EnderChestTileEntity::startOpen() { + openCount++; + level->tileEvent(x, y, z, Tile::enderChest_Id, + ChestTile::EVENT_SET_OPEN_COUNT, openCount); } -void EnderChestTileEntity::stopOpen() -{ - openCount--; - level->tileEvent(x, y, z, Tile::enderChest_Id, ChestTile::EVENT_SET_OPEN_COUNT, openCount); +void EnderChestTileEntity::stopOpen() { + openCount--; + level->tileEvent(x, y, z, Tile::enderChest_Id, + ChestTile::EVENT_SET_OPEN_COUNT, openCount); } -bool EnderChestTileEntity::stillValid(std::shared_ptr player) -{ - if (level->getTileEntity(x, y, z) != shared_from_this()) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; +bool EnderChestTileEntity::stillValid(std::shared_ptr player) { + if (level->getTileEntity(x, y, z) != shared_from_this()) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; + return true; } // 4J Added -std::shared_ptr EnderChestTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new EnderChestTileEntity() ); - TileEntity::clone(result); +std::shared_ptr EnderChestTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new EnderChestTileEntity()); + TileEntity::clone(result); - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.h b/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.h index e67b6bcc6..59dbefbdb 100644 --- a/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/EnderChestTileEntity.h @@ -2,29 +2,28 @@ #include "TileEntity.h" -class EnderChestTileEntity : public TileEntity -{ +class EnderChestTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_ENDERCHESTTILEENTITY; } - static TileEntity *create() { return new EnderChestTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_ENDERCHESTTILEENTITY; } + static TileEntity* create() { return new EnderChestTileEntity(); } public: - float openness, oOpenness; - int openCount; + float openness, oOpenness; + int openCount; private: - int tickInterval; + int tickInterval; public: - EnderChestTileEntity(); + EnderChestTileEntity(); - void tick(); - void triggerEvent(int b0, int b1); - void setRemoved(); - void startOpen(); - void stopOpen(); - bool stillValid(std::shared_ptr player); + void tick(); + void triggerEvent(int b0, int b1); + void setRemoved(); + void startOpen(); + void stopOpen(); + bool stillValid(std::shared_ptr player); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EntityTile.cpp b/Minecraft.World/Blocks/TileEntities/EntityTile.cpp index 9669899fa..302749035 100644 --- a/Minecraft.World/Blocks/TileEntities/EntityTile.cpp +++ b/Minecraft.World/Blocks/TileEntities/EntityTile.cpp @@ -4,29 +4,27 @@ #include "TileEntity.h" #include "EntityTile.h" -EntityTile::EntityTile(int id, Material *material, bool isSolidRender /*= true*/) : Tile(id, material, isSolidRender) -{ - _isEntityTile = true; +EntityTile::EntityTile(int id, Material* material, + bool isSolidRender /*= true*/) + : Tile(id, material, isSolidRender) { + _isEntityTile = true; } -void EntityTile::onPlace(Level *level, int x, int y, int z) -{ +void EntityTile::onPlace(Level* level, int x, int y, int z) { Tile::onPlace(level, x, y, z); level->setTileEntity(x, y, z, newTileEntity(level)); } -void EntityTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ +void EntityTile::onRemove(Level* level, int x, int y, int z, int id, int data) { Tile::onRemove(level, x, y, z, id, data); level->removeTileEntity(x, y, z); } -void EntityTile::triggerEvent(Level *level, int x, int y, int z, int b0, int b1) -{ - Tile::triggerEvent(level, x, y, z, b0, b1); - std::shared_ptr te = level->getTileEntity(x, y, z); - if (te != NULL) - { - te->triggerEvent(b0, b1); - } +void EntityTile::triggerEvent(Level* level, int x, int y, int z, int b0, + int b1) { + Tile::triggerEvent(level, x, y, z, b0, b1); + std::shared_ptr te = level->getTileEntity(x, y, z); + if (te != NULL) { + te->triggerEvent(b0, b1); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/EntityTile.h b/Minecraft.World/Blocks/TileEntities/EntityTile.h index a913f59ff..cf8d28b22 100644 --- a/Minecraft.World/Blocks/TileEntities/EntityTile.h +++ b/Minecraft.World/Blocks/TileEntities/EntityTile.h @@ -3,13 +3,14 @@ class TileEntity; -class EntityTile : public Tile -{ +class EntityTile : public Tile { protected: - EntityTile(int id, Material *material, bool isSolidRender = true); + EntityTile(int id, Material* material, bool isSolidRender = true); + public: - virtual void onPlace(Level *level, int x, int y, int z); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual std::shared_ptr newTileEntity(Level *level) = 0; - virtual void triggerEvent(Level *level, int x, int y, int z, int b0, int b1); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual std::shared_ptr newTileEntity(Level* level) = 0; + virtual void triggerEvent(Level* level, int x, int y, int z, int b0, + int b1); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.cpp index 39aa67b5b..4d5d4ac00 100644 --- a/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.cpp @@ -8,346 +8,288 @@ #include "../Material.h" #include "FurnaceTileEntity.h" - - const int FurnaceTileEntity::BURN_INTERVAL = 10 * 20; // 4J Stu - Need a ctor to initialise member variables -FurnaceTileEntity::FurnaceTileEntity() : TileEntity() -{ - items = new ItemInstanceArray(3); +FurnaceTileEntity::FurnaceTileEntity() : TileEntity() { + items = new ItemInstanceArray(3); - litTime = 0; + litTime = 0; - litDuration = 0; + litDuration = 0; - tickCount = 0; + tickCount = 0; - m_charcoalUsed = false; + m_charcoalUsed = false; } -FurnaceTileEntity::~FurnaceTileEntity() -{ - delete[] items->data; - delete items; +FurnaceTileEntity::~FurnaceTileEntity() { + delete[] items->data; + delete items; } +unsigned int FurnaceTileEntity::getContainerSize() { return items->length; } -unsigned int FurnaceTileEntity::getContainerSize() -{ - return items->length; +std::shared_ptr FurnaceTileEntity::getItem(unsigned int slot) { + return (*items)[slot]; } +std::shared_ptr FurnaceTileEntity::removeItem(unsigned int slot, + int count) { + m_charcoalUsed = false; -std::shared_ptr FurnaceTileEntity::getItem(unsigned int slot) -{ - return (*items)[slot]; + if ((*items)[slot] != NULL) { + if ((*items)[slot]->count <= count) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) return nullptr; + return item; + } else { + std::shared_ptr i = (*items)[slot]->remove(count); + if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; + // 4J Stu - Fix for duplication glitch + if (i->count <= 0) return nullptr; + return i; + } + } + return nullptr; } +std::shared_ptr FurnaceTileEntity::removeItemNoUpdate(int slot) { + m_charcoalUsed = false; -std::shared_ptr FurnaceTileEntity::removeItem(unsigned int slot, int count) -{ - m_charcoalUsed = false; - - if ((*items)[slot] != NULL) - { - if ((*items)[slot]->count <= count) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) return nullptr; - return item; - } - else - { - std::shared_ptr i = (*items)[slot]->remove(count); - if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; - // 4J Stu - Fix for duplication glitch - if(i->count <= 0) return nullptr; - return i; - } - } - return nullptr; + if (items->data[slot] != NULL) { + std::shared_ptr item = items->data[slot]; + items->data[slot] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr FurnaceTileEntity::removeItemNoUpdate(int slot) -{ - m_charcoalUsed = false; - - if (items->data[slot] != NULL) - { - std::shared_ptr item = items->data[slot]; - items->data[slot] = nullptr; - return item; - } - return nullptr; +void FurnaceTileEntity::setItem(unsigned int slot, + std::shared_ptr item) { + (*items)[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); } +int FurnaceTileEntity::getName() { return IDS_TILE_FURNACE; } -void FurnaceTileEntity::setItem(unsigned int slot, std::shared_ptr item) -{ - (*items)[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); +void FurnaceTileEntity::load(CompoundTag* base) { + TileEntity::load(base); + // 4jcraft, fixed cast of templated List to get the tag list + // and cast it to CompoundTag inside the loop + ListTag* inventoryList = base->getList(L"Items"); + + items = new ItemInstanceArray(getContainerSize()); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = (CompoundTag*)inventoryList->get(i); + unsigned int slot = tag->getByte(L"Slot"); + if (slot >= 0 && slot < items->length) + (*items)[slot] = ItemInstance::fromTag(tag); + } + + litTime = base->getShort(L"BurnTime"); + tickCount = base->getShort(L"CookTime"); + litDuration = getBurnDuration((*items)[FUEL_SLOT]); + + m_charcoalUsed = base->getBoolean(L"CharcoalUsed"); } +void FurnaceTileEntity::save(CompoundTag* base) { + TileEntity::save(base); + base->putShort(L"BurnTime", (short)(litTime)); + base->putShort(L"CookTime", (short)(tickCount)); + ListTag* listTag = new ListTag(); -int FurnaceTileEntity::getName() -{ - return IDS_TILE_FURNACE; + for (unsigned int i = 0; i < items->length; i++) { + if ((*items)[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + (*items)[i]->save(tag); + listTag->add(tag); + } + } + base->put(L"Items", listTag); + + base->putBoolean(L"CharcoalUsed", m_charcoalUsed); } -void FurnaceTileEntity::load(CompoundTag *base) -{ - TileEntity::load(base); - // 4jcraft, fixed cast of templated List to get the tag list - // and cast it to CompoundTag inside the loop - ListTag *inventoryList = base->getList(L"Items"); - - items = new ItemInstanceArray(getContainerSize()); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = (CompoundTag*) inventoryList->get(i); - unsigned int slot = tag->getByte(L"Slot"); - if (slot >= 0 && slot < items->length) (*items)[slot] = ItemInstance::fromTag(tag); - } - - litTime = base->getShort(L"BurnTime"); - tickCount = base->getShort(L"CookTime"); - litDuration = getBurnDuration((*items)[FUEL_SLOT]); - - m_charcoalUsed = base->getBoolean(L"CharcoalUsed"); +int FurnaceTileEntity::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } - -void FurnaceTileEntity::save(CompoundTag *base) -{ - TileEntity::save(base); - base->putShort(L"BurnTime", (short) (litTime)); - base->putShort(L"CookTime", (short) (tickCount)); - ListTag *listTag = new ListTag(); - - for (unsigned int i = 0; i < items->length; i++) - { - if ((*items)[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - (*items)[i]->save(tag); - listTag->add(tag); - } - } - base->put(L"Items", listTag); - - base->putBoolean(L"CharcoalUsed", m_charcoalUsed); +int FurnaceTileEntity::getBurnProgress(int max) { + return tickCount * max / BURN_INTERVAL; } - -int FurnaceTileEntity::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; +int FurnaceTileEntity::getLitProgress(int max) { + if (litDuration == 0) litDuration = BURN_INTERVAL; + return litTime * max / litDuration; } +bool FurnaceTileEntity::isLit() { return litTime > 0; } -int FurnaceTileEntity::getBurnProgress(int max) -{ - return tickCount * max / BURN_INTERVAL; +void FurnaceTileEntity::tick() { + bool wasLit = litTime > 0; + bool changed = false; + if (litTime > 0) { + litTime--; + } + + if (level != NULL && !level->isClientSide) { + if (litTime == 0 && canBurn()) { + litDuration = litTime = getBurnDuration((*items)[FUEL_SLOT]); + if (litTime > 0) { + changed = true; + if ((*items)[FUEL_SLOT] != NULL) { + // 4J Added: Keep track of whether charcoal was used in + // production of current stack. + if ((*items)[FUEL_SLOT]->getItem()->id == Item::coal_Id && + (*items)[FUEL_SLOT]->getAuxValue() == + CoalItem::CHAR_COAL) { + m_charcoalUsed = true; + } + + (*items)[FUEL_SLOT]->count--; + if ((*items)[FUEL_SLOT]->count == 0) { + Item* remaining = (*items)[FUEL_SLOT] + ->getItem() + ->getCraftingRemainingItem(); + (*items)[FUEL_SLOT] = + remaining != NULL ? std::shared_ptr( + new ItemInstance(remaining)) + : nullptr; + } + } + } + } + + if (isLit() && canBurn()) { + tickCount++; + if (tickCount == BURN_INTERVAL) { + tickCount = 0; + burn(); + changed = true; + } + } else { + tickCount = 0; + } + + if (wasLit != litTime > 0) { + changed = true; + FurnaceTile::setLit(litTime > 0, level, x, y, z); + } + } + + if (changed) setChanged(); } - -int FurnaceTileEntity::getLitProgress(int max) -{ - if (litDuration == 0) litDuration = BURN_INTERVAL; - return litTime * max / litDuration; +bool FurnaceTileEntity::canBurn() { + if ((*items)[INPUT_SLOT] == NULL) return false; + ItemInstance* burnResult = + FurnaceRecipes::getInstance()->getResult((*items)[0]->getItem()->id); + if (burnResult == NULL) return false; + if ((*items)[RESULT_SLOT] == NULL) return true; + if (!(*items)[RESULT_SLOT]->sameItem_not_shared(burnResult)) return false; + if ((*items)[RESULT_SLOT]->count < getMaxStackSize() && + (*items)[RESULT_SLOT]->count < (*items)[RESULT_SLOT]->getMaxStackSize()) + return true; + if ((*items)[RESULT_SLOT]->count < burnResult->getMaxStackSize()) + return true; + return false; } +void FurnaceTileEntity::burn() { + if (!canBurn()) return; -bool FurnaceTileEntity::isLit() -{ - return litTime > 0; + ItemInstance* result = + FurnaceRecipes::getInstance()->getResult((*items)[0]->getItem()->id); + if ((*items)[RESULT_SLOT] == NULL) + (*items)[RESULT_SLOT] = result->copy(); + else if ((*items)[RESULT_SLOT]->id == result->id) + (*items)[RESULT_SLOT]->count++; + + (*items)[INPUT_SLOT]->count--; + if ((*items)[INPUT_SLOT]->count <= 0) (*items)[INPUT_SLOT] = nullptr; } +int FurnaceTileEntity::getBurnDuration( + std::shared_ptr itemInstance) { + if (itemInstance == NULL) return 0; + int id = itemInstance->getItem()->id; -void FurnaceTileEntity::tick() -{ - bool wasLit = litTime > 0; - bool changed = false; - if (litTime > 0) - { - litTime--; - } + Item* item = itemInstance->getItem(); - if ( level != NULL && !level->isClientSide) - { - if (litTime == 0 && canBurn()) - { - litDuration = litTime = getBurnDuration((*items)[FUEL_SLOT]); - if (litTime > 0) - { - changed = true; - if ((*items)[FUEL_SLOT] != NULL) - { - // 4J Added: Keep track of whether charcoal was used in production of current stack. - if ( (*items)[FUEL_SLOT]->getItem()->id == Item::coal_Id - && (*items)[FUEL_SLOT]->getAuxValue() == CoalItem::CHAR_COAL) - { - m_charcoalUsed = true; - } + if (id < 256 && Tile::tiles[id] != NULL) { + Tile* tile = Tile::tiles[id]; - (*items)[FUEL_SLOT]->count--; - if ((*items)[FUEL_SLOT]->count == 0) - { - Item *remaining = (*items)[FUEL_SLOT]->getItem()->getCraftingRemainingItem(); - (*items)[FUEL_SLOT] = remaining != NULL ? std::shared_ptr(new ItemInstance(remaining)) : nullptr; - } - } - } - } + if (tile == Tile::woodSlabHalf) { + return BURN_INTERVAL * 3 / 4; + } - if (isLit() && canBurn()) - { - tickCount++; - if (tickCount == BURN_INTERVAL) - { - tickCount = 0; - burn(); - changed = true; - } - } - else - { - tickCount = 0; - } + if (tile->material == Material::wood) { + return BURN_INTERVAL * 3 / 2; + } + } - if (wasLit != litTime > 0) - { - changed = true; - FurnaceTile::setLit(litTime > 0, level, x, y, z); - } - } + if (dynamic_cast(item) && + ((DiggerItem*)item)->getTier() == Item::Tier::WOOD) { + return BURN_INTERVAL; + } else if (dynamic_cast(item) && + ((WeaponItem*)item)->getTier() == Item::Tier::WOOD) { + return BURN_INTERVAL; + } else if (dynamic_cast(item) && + ((HoeItem*)item)->getTier() == Item::Tier::WOOD) { + return BURN_INTERVAL; + } - if (changed) setChanged(); + if (id == Item::stick->id) { + return BURN_INTERVAL / 2; + } + + if (id == Item::coal->id) return BURN_INTERVAL * 8; + + if (id == Item::bucket_lava->id) return BURN_INTERVAL * 100; + + if (id == Tile::sapling_Id) return BURN_INTERVAL / 2; + + if (id == Item::blazeRod_Id) return BURN_INTERVAL * 12; + + return 0; } - -bool FurnaceTileEntity::canBurn() -{ - if ((*items)[INPUT_SLOT] == NULL) return false; - ItemInstance *burnResult = FurnaceRecipes::getInstance()->getResult((*items)[0]->getItem()->id); - if (burnResult == NULL) return false; - if ((*items)[RESULT_SLOT] == NULL) return true; - if (!(*items)[RESULT_SLOT]->sameItem_not_shared(burnResult)) return false; - if ((*items)[RESULT_SLOT]->count < getMaxStackSize() && (*items)[RESULT_SLOT]->count < (*items)[RESULT_SLOT]->getMaxStackSize()) return true; - if ((*items)[RESULT_SLOT]->count < burnResult->getMaxStackSize()) return true; - return false; +bool FurnaceTileEntity::isFuel(std::shared_ptr item) { + return getBurnDuration(item) > 0; } - -void FurnaceTileEntity::burn() -{ - if (!canBurn()) return; - - ItemInstance *result = FurnaceRecipes::getInstance()->getResult((*items)[0]->getItem()->id); - if ((*items)[RESULT_SLOT] == NULL) (*items)[RESULT_SLOT] = result->copy(); - else if ((*items)[RESULT_SLOT]->id == result->id) (*items)[RESULT_SLOT]->count++; - - (*items)[INPUT_SLOT]->count--; - if ((*items)[INPUT_SLOT]->count <= 0) (*items)[INPUT_SLOT] = nullptr; +bool FurnaceTileEntity::stillValid(std::shared_ptr player) { + if (level->getTileEntity(x, y, z) != shared_from_this()) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } +void FurnaceTileEntity::setChanged() { return TileEntity::setChanged(); } -int FurnaceTileEntity::getBurnDuration(std::shared_ptr itemInstance) -{ - if (itemInstance == NULL) return 0; - int id = itemInstance->getItem()->id; +void FurnaceTileEntity::startOpen() {} - Item *item = itemInstance->getItem(); - - if (id < 256 && Tile::tiles[id] != NULL) - { - Tile *tile = Tile::tiles[id]; - - if (tile == Tile::woodSlabHalf) - { - return BURN_INTERVAL * 3 / 4; - } - - if (tile->material == Material::wood) - { - return BURN_INTERVAL * 3 / 2; - } - } - - if (dynamic_cast(item) && ((DiggerItem *) item)->getTier() == Item::Tier::WOOD) - { - return BURN_INTERVAL; - } - else if (dynamic_cast(item) && ((WeaponItem *) item)->getTier() == Item::Tier::WOOD) - { - return BURN_INTERVAL; - } - else if (dynamic_cast(item) && ((HoeItem *) item)->getTier() == Item::Tier::WOOD) - { - return BURN_INTERVAL; - } - - if (id == Item::stick->id) - { - return BURN_INTERVAL / 2; - } - - if (id == Item::coal->id) return BURN_INTERVAL * 8; - - if (id == Item::bucket_lava->id) return BURN_INTERVAL * 100; - - if (id == Tile::sapling_Id) return BURN_INTERVAL / 2; - - if (id == Item::blazeRod_Id) return BURN_INTERVAL * 12; - - return 0; -} - -bool FurnaceTileEntity::isFuel(std::shared_ptr item) -{ - return getBurnDuration(item) > 0; -} - -bool FurnaceTileEntity::stillValid(std::shared_ptr player) -{ - if (level->getTileEntity(x, y, z) != shared_from_this() ) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; -} - -void FurnaceTileEntity::setChanged() -{ - return TileEntity::setChanged(); -} - -void FurnaceTileEntity::startOpen() -{ -} - -void FurnaceTileEntity::stopOpen() -{ -} +void FurnaceTileEntity::stopOpen() {} // 4J Added -std::shared_ptr FurnaceTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new FurnaceTileEntity() ); - TileEntity::clone(result); +std::shared_ptr FurnaceTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new FurnaceTileEntity()); + TileEntity::clone(result); - result->litTime = litTime; - result->tickCount = tickCount; - result->litDuration = litDuration; + result->litTime = litTime; + result->tickCount = tickCount; + result->litDuration = litDuration; - for (unsigned int i = 0; i < items->length; i++) - { - if ((*items)[i] != NULL) - { - (*result->items)[i] = ItemInstance::clone((*items)[i]); - } - } - return result; + for (unsigned int i = 0; i < items->length; i++) { + if ((*items)[i] != NULL) { + (*result->items)[i] = ItemInstance::clone((*items)[i]); + } + } + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.h b/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.h index 0c0a2f086..82b875f7c 100644 --- a/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/FurnaceTileEntity.h @@ -1,6 +1,5 @@ #pragma once - #include "../FurnaceTile.h" #include "TileEntity.h" #include "../../Containers/Container.h" @@ -8,71 +7,72 @@ class Player; class Level; -class FurnaceTileEntity : public TileEntity, public Container -{ +class FurnaceTileEntity : public TileEntity, public Container { public: - eINSTANCEOF GetType() { return eTYPE_FURNACETILEENTITY; } - static TileEntity *create() { return new FurnaceTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_FURNACETILEENTITY; } + static TileEntity* create() { return new FurnaceTileEntity(); } -using TileEntity::setChanged; + using TileEntity::setChanged; private: - static const int BURN_INTERVAL; - ItemInstanceArray *items; + static const int BURN_INTERVAL; + ItemInstanceArray* items; - enum { - INPUT_SLOT = 0, - FUEL_SLOT, - RESULT_SLOT, - }; + enum { + INPUT_SLOT = 0, + FUEL_SLOT, + RESULT_SLOT, + }; - // 4J-JEV: Added for 'Renewable Energy' achievement. - // Should be true iff characoal was consumed whilst cooking the current stack. - bool m_charcoalUsed; + // 4J-JEV: Added for 'Renewable Energy' achievement. + // Should be true iff characoal was consumed whilst cooking the current + // stack. + bool m_charcoalUsed; public: - int litTime; - int litDuration; - int tickCount; + int litTime; + int litDuration; + int tickCount; public: - // 4J Stu - Need a ctor to initialise member variables - FurnaceTileEntity(); - virtual ~FurnaceTileEntity(); + // 4J Stu - Need a ctor to initialise member variables + FurnaceTileEntity(); + virtual ~FurnaceTileEntity(); - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - virtual std::shared_ptr removeItemNoUpdate(int slot); - virtual void setItem(unsigned int slot, std::shared_ptr item); - virtual int getName(); - virtual void load(CompoundTag *base); - virtual void save(CompoundTag *base); - virtual int getMaxStackSize(); - int getBurnProgress(int max); - int getLitProgress(int max); - bool isLit(); - virtual void tick(); + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual void setItem(unsigned int slot, std::shared_ptr item); + virtual int getName(); + virtual void load(CompoundTag* base); + virtual void save(CompoundTag* base); + virtual int getMaxStackSize(); + int getBurnProgress(int max); + int getLitProgress(int max); + bool isLit(); + virtual void tick(); private: - bool canBurn(); + bool canBurn(); public: - void burn(); + void burn(); - static int getBurnDuration(std::shared_ptr itemInstance); - static bool isFuel(std::shared_ptr item); + static int getBurnDuration(std::shared_ptr itemInstance); + static bool isFuel(std::shared_ptr item); public: - virtual bool stillValid(std::shared_ptr player); - virtual void setChanged(); + virtual bool stillValid(std::shared_ptr player); + virtual void setChanged(); void startOpen(); void stopOpen(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); - // 4J-JEV: Added for 'Renewable Energy' achievement. - bool wasCharcoalUsed() { return m_charcoalUsed; } + // 4J-JEV: Added for 'Renewable Energy' achievement. + bool wasCharcoalUsed() { return m_charcoalUsed; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.cpp index 006a73207..14c326749 100644 --- a/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.cpp @@ -12,223 +12,203 @@ #include "../../Util/SharedConstants.h" #include "MobSpawnerTileEntity.h" - - const int MobSpawnerTileEntity::MAX_DIST = 16; -MobSpawnerTileEntity::MobSpawnerTileEntity() : TileEntity() -{ - spin = 0; - oSpin = 0; +MobSpawnerTileEntity::MobSpawnerTileEntity() : TileEntity() { + spin = 0; + oSpin = 0; - // entityId = "Skeleton"; - entityId = L"Pig"; - m_bEntityIdUpdated = false; + // entityId = "Skeleton"; + entityId = L"Pig"; + m_bEntityIdUpdated = false; - spawnData = NULL; + spawnData = NULL; - spawnDelay = 20; + spawnDelay = 20; - minSpawnDelay = SharedConstants::TICKS_PER_SECOND * 10; - maxSpawnDelay = SharedConstants::TICKS_PER_SECOND * 40; - spawnCount = 4; - displayEntity = nullptr; + minSpawnDelay = SharedConstants::TICKS_PER_SECOND * 10; + maxSpawnDelay = SharedConstants::TICKS_PER_SECOND * 40; + spawnCount = 4; + displayEntity = nullptr; } -std::wstring MobSpawnerTileEntity::getEntityId() -{ - return entityId; +std::wstring MobSpawnerTileEntity::getEntityId() { return entityId; } + +void MobSpawnerTileEntity::setEntityId(const std::wstring& entityId) { + this->entityId = entityId; } -void MobSpawnerTileEntity::setEntityId(const std::wstring& entityId) -{ - this->entityId = entityId; +bool MobSpawnerTileEntity::isNearPlayer() { + return level->getNearestPlayer(x + 0.5, y + 0.5, z + 0.5, MAX_DIST) != NULL; } -bool MobSpawnerTileEntity::isNearPlayer() -{ - return level->getNearestPlayer(x + 0.5, y + 0.5, z + 0.5, MAX_DIST) != NULL; +void MobSpawnerTileEntity::tick() { + if (!isNearPlayer()) { + return; + } + + if (level->isClientSide) { + double xP = x + level->random->nextFloat(); + double yP = y + level->random->nextFloat(); + double zP = z + level->random->nextFloat(); + level->addParticle(eParticleType_smoke, xP, yP, zP, 0, 0, 0); + level->addParticle(eParticleType_flame, xP, yP, zP, 0, 0, 0); + + oSpin = spin; + spin += 1000 / 220.0f; + while (spin > 360) { + spin -= 360; + } + while (oSpin > 360) { + oSpin -= 360; + } + } else { + if (spawnDelay == -1) delay(); + + if (spawnDelay > 0) { + spawnDelay--; + return; + } + + for (int c = 0; c < spawnCount; c++) { + std::shared_ptr entity = std::dynamic_pointer_cast( + EntityIO::newEntity(entityId, level)); + if (entity == NULL) return; + + Mob* entityPtr = entity.get(); + std::vector >* vecNearby = + level->getEntitiesOfClass( + typeid(*entityPtr), + AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(8, 4, 8)); + int nearBy = + (int)vecNearby + ->size(); // 4J - IB, TODO, Mob contains no getClass + delete vecNearby; + + if (nearBy >= 6) { + delay(); + return; + } + + // 4J added - our mobspawner tiles should only be spawning monsters. + // Also respect the global limits we have for those so we don't go + // creating silly numbers of them. Have set this limit slightly + // higher than the main spawner has so that this tile entity is more + // likely to actually make something (60 rather than 50) + if (level->countInstanceOf(eTYPE_MONSTER, false) >= 60) { + return; + } + + if (entity != NULL) { + double xp = x + (level->random->nextDouble() - + level->random->nextDouble()) * + 4; + double yp = y + level->random->nextInt(3) - 1; + double zp = z + (level->random->nextDouble() - + level->random->nextDouble()) * + 4; + std::shared_ptr mob = + std::dynamic_pointer_cast(entity); + + entity->moveTo(xp, yp, zp, level->random->nextFloat() * 360, 0); + + if (mob == NULL || mob->canSpawn()) { + fillExtraData(entity); + + level->addEntity(entity); + + level->levelEvent(LevelEvent::PARTICLES_MOBTILE_SPAWN, x, y, + z, 0); + + if (mob != NULL) mob->spawnAnim(); + delay(); + } + } + } + } + + TileEntity::tick(); } -void MobSpawnerTileEntity::tick() -{ - if (!isNearPlayer()) - { - return; - } +void MobSpawnerTileEntity::fillExtraData(std::shared_ptr entity) { + if (spawnData != NULL) { + CompoundTag* data = new CompoundTag(); + entity->save(data); - if (level->isClientSide) - { - double xP = x + level->random->nextFloat(); - double yP = y + level->random->nextFloat(); - double zP = z + level->random->nextFloat(); - level->addParticle(eParticleType_smoke, xP, yP, zP, 0, 0, 0); - level->addParticle(eParticleType_flame, xP, yP, zP, 0, 0, 0); + std::vector* allTags = spawnData->getAllTags(); + for (AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) { + Tag* tag = *it; + data->put((wchar_t*)tag->getName().c_str(), tag->copy()); + } + if (allTags != NULL) delete allTags; - oSpin = spin; - spin += 1000 / 220.0f; - while (spin > 360) - { - spin -= 360; - } - while(oSpin > 360) - { - oSpin -= 360; - } - } - else - { - - if (spawnDelay == -1) delay(); - - if (spawnDelay > 0) - { - spawnDelay--; - return; - } - - for (int c = 0; c < spawnCount; c++) - { - std::shared_ptr entity = std::dynamic_pointer_cast (EntityIO::newEntity(entityId, level)); - if (entity == NULL) return; - - Mob *entityPtr = entity.get(); - std::vector > *vecNearby = level->getEntitiesOfClass(typeid(*entityPtr), AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(8, 4, 8)); - int nearBy = (int)vecNearby->size(); //4J - IB, TODO, Mob contains no getClass - delete vecNearby; - - if (nearBy >= 6) - { - delay(); - return; - } - - // 4J added - our mobspawner tiles should only be spawning monsters. Also respect the global limits we have for those so we don't go - // creating silly numbers of them. Have set this limit slightly higher than the main spawner has so that this tile entity is more likely to - // actually make something (60 rather than 50) - if(level->countInstanceOf( eTYPE_MONSTER, false) >= 60 ) - { - return; - } - - if (entity != NULL) - { - double xp = x + (level->random->nextDouble() - level->random->nextDouble()) * 4; - double yp = y + level->random->nextInt(3) - 1; - double zp = z + (level->random->nextDouble() - level->random->nextDouble()) * 4; - std::shared_ptr mob = std::dynamic_pointer_cast( entity ); - - entity->moveTo(xp, yp, zp, level->random->nextFloat() * 360, 0); - - if (mob == NULL || mob->canSpawn()) - { - fillExtraData(entity); - - level->addEntity(entity); - - level->levelEvent(LevelEvent::PARTICLES_MOBTILE_SPAWN, x, y, z, 0); - - if (mob != NULL) mob->spawnAnim(); - delay(); - } - } - } - } - - TileEntity::tick(); + entity->load(data); + } } -void MobSpawnerTileEntity::fillExtraData(std::shared_ptr entity) -{ - if (spawnData != NULL) - { - CompoundTag *data = new CompoundTag(); - entity->save(data); - - std::vector *allTags = spawnData->getAllTags(); - for(AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) - { - Tag *tag = *it; - data->put((wchar_t *)tag->getName().c_str(), tag->copy()); - } - if(allTags != NULL) delete allTags; - - entity->load(data); - } +void MobSpawnerTileEntity::delay() { + spawnDelay = + minSpawnDelay + level->random->nextInt(maxSpawnDelay - minSpawnDelay); } -void MobSpawnerTileEntity::delay() -{ - spawnDelay = minSpawnDelay + level->random->nextInt(maxSpawnDelay - minSpawnDelay); +void MobSpawnerTileEntity::load(CompoundTag* tag) { + TileEntity::load(tag); + entityId = tag->getString(L"EntityId"); + m_bEntityIdUpdated = true; + + spawnDelay = tag->getShort(L"Delay"); + + if (tag->contains(L"SpawnData")) { + spawnData = tag->getCompound(L"SpawnData"); + } else { + spawnData = NULL; + } + + if (tag->contains(L"MinSpawnDelay")) { + minSpawnDelay = tag->getShort(L"MinSpawnDelay"); + maxSpawnDelay = tag->getShort(L"MaxSpawnDelay"); + spawnCount = tag->getShort(L"SpawnCount"); + } } -void MobSpawnerTileEntity::load(CompoundTag *tag) -{ - TileEntity::load(tag); - entityId = tag->getString(L"EntityId"); - m_bEntityIdUpdated = true; +void MobSpawnerTileEntity::save(CompoundTag* tag) { + TileEntity::save(tag); + tag->putString(L"EntityId", entityId); + tag->putShort(L"Delay", (short)spawnDelay); + tag->putShort(L"MinSpawnDelay", (short)minSpawnDelay); + tag->putShort(L"MaxSpawnDelay", (short)maxSpawnDelay); + tag->putShort(L"SpawnCount", (short)spawnCount); - spawnDelay = tag->getShort(L"Delay"); - - if (tag->contains(L"SpawnData")) - { - spawnData = tag->getCompound(L"SpawnData"); - } - else - { - spawnData = NULL; - } - - if (tag->contains(L"MinSpawnDelay")) - { - minSpawnDelay = tag->getShort(L"MinSpawnDelay"); - maxSpawnDelay = tag->getShort(L"MaxSpawnDelay"); - spawnCount = tag->getShort(L"SpawnCount"); - } + if (spawnData != NULL) { + tag->putCompound(L"SpawnData", spawnData); + } } -void MobSpawnerTileEntity::save(CompoundTag *tag) -{ - TileEntity::save(tag); - tag->putString(L"EntityId", entityId ); - tag->putShort(L"Delay", (short) spawnDelay); - tag->putShort(L"MinSpawnDelay", (short) minSpawnDelay); - tag->putShort(L"MaxSpawnDelay", (short) maxSpawnDelay); - tag->putShort(L"SpawnCount", (short) spawnCount); +std::shared_ptr MobSpawnerTileEntity::getDisplayEntity() { + if (displayEntity == NULL || m_bEntityIdUpdated) { + std::shared_ptr e = EntityIO::newEntity(getEntityId(), NULL); + fillExtraData(e); + displayEntity = e; + m_bEntityIdUpdated = false; + } - if (spawnData != NULL) - { - tag->putCompound(L"SpawnData", spawnData); - } + return displayEntity; } -std::shared_ptr MobSpawnerTileEntity::getDisplayEntity() -{ - if (displayEntity == NULL || m_bEntityIdUpdated) - { - std::shared_ptr e = EntityIO::newEntity(getEntityId(), NULL); - fillExtraData(e); - displayEntity = e; - m_bEntityIdUpdated = false; - } - - return displayEntity; -} - -std::shared_ptr MobSpawnerTileEntity::getUpdatePacket() -{ - CompoundTag *tag = new CompoundTag(); - save(tag); - return std::shared_ptr( new TileEntityDataPacket(x, y, z, TileEntityDataPacket::TYPE_MOB_SPAWNER, tag) ); +std::shared_ptr MobSpawnerTileEntity::getUpdatePacket() { + CompoundTag* tag = new CompoundTag(); + save(tag); + return std::shared_ptr(new TileEntityDataPacket( + x, y, z, TileEntityDataPacket::TYPE_MOB_SPAWNER, tag)); } // 4J Added -std::shared_ptr MobSpawnerTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new MobSpawnerTileEntity() ); - TileEntity::clone(result); +std::shared_ptr MobSpawnerTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new MobSpawnerTileEntity()); + TileEntity::clone(result); - result->entityId = entityId; - result->spawnDelay = spawnDelay; - return result; + result->entityId = entityId; + result->spawnDelay = spawnDelay; + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.h b/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.h index 8b0b0ec5d..c3315f3a3 100644 --- a/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/MobSpawnerTileEntity.h @@ -1,59 +1,57 @@ #pragma once - #include "TileEntity.h" class Packet; class Entity; -class MobSpawnerTileEntity : public TileEntity -{ +class MobSpawnerTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_MOBSPAWNERTILEENTITY; } - static TileEntity *create() { return new MobSpawnerTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_MOBSPAWNERTILEENTITY; } + static TileEntity* create() { return new MobSpawnerTileEntity(); } -using TileEntity::setChanged; + using TileEntity::setChanged; private: - static const int MAX_DIST; + static const int MAX_DIST; public: - int spawnDelay; + int spawnDelay; private: - std::wstring entityId; - CompoundTag *spawnData; + std::wstring entityId; + CompoundTag* spawnData; - bool m_bEntityIdUpdated; // 4J Added + bool m_bEntityIdUpdated; // 4J Added public: - double spin, oSpin; + double spin, oSpin; private: - int minSpawnDelay; - int maxSpawnDelay; - int spawnCount; - std::shared_ptr displayEntity; - -public: - MobSpawnerTileEntity(); + int minSpawnDelay; + int maxSpawnDelay; + int spawnCount; + std::shared_ptr displayEntity; - std::wstring getEntityId(); - void setEntityId(const std::wstring& entityId); - bool isNearPlayer(); - virtual void tick(); - void fillExtraData(std::shared_ptr entity); +public: + MobSpawnerTileEntity(); + + std::wstring getEntityId(); + void setEntityId(const std::wstring& entityId); + bool isNearPlayer(); + virtual void tick(); + void fillExtraData(std::shared_ptr entity); private: - void delay(); + void delay(); public: - virtual void load(CompoundTag *tag); - virtual void save(CompoundTag *tag); + virtual void load(CompoundTag* tag); + virtual void save(CompoundTag* tag); - std::shared_ptr getDisplayEntity(); - virtual std::shared_ptr getUpdatePacket(); + std::shared_ptr getDisplayEntity(); + virtual std::shared_ptr getUpdatePacket(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; diff --git a/Minecraft.World/Blocks/TileEntities/MusicTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/MusicTileEntity.cpp index ea54e0a72..4ff1f847f 100644 --- a/Minecraft.World/Blocks/TileEntities/MusicTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/MusicTileEntity.cpp @@ -8,57 +8,49 @@ #include "MusicTileEntity.h" - - -MusicTileEntity::MusicTileEntity() : TileEntity() -{ +MusicTileEntity::MusicTileEntity() : TileEntity() { note = 0; - - on = false; + + on = false; } -void MusicTileEntity::save(CompoundTag *tag) -{ - TileEntity::save(tag); - tag->putByte(L"note", note); +void MusicTileEntity::save(CompoundTag* tag) { + TileEntity::save(tag); + tag->putByte(L"note", note); } -void MusicTileEntity::load(CompoundTag *tag) -{ - TileEntity::load(tag); - note = tag->getByte(L"note"); - if (note < 0) note = 0; - if (note > 24) note = 24; +void MusicTileEntity::load(CompoundTag* tag) { + TileEntity::load(tag); + note = tag->getByte(L"note"); + if (note < 0) note = 0; + if (note > 24) note = 24; } -void MusicTileEntity::tune() -{ - note = (uint8_t) ((note + 1) % 25); - setChanged(); +void MusicTileEntity::tune() { + note = (uint8_t)((note + 1) % 25); + setChanged(); } -void MusicTileEntity::playNote(Level *level, int x, int y, int z) -{ - if (level->getMaterial(x, y + 1, z) != Material::air) return; +void MusicTileEntity::playNote(Level* level, int x, int y, int z) { + if (level->getMaterial(x, y + 1, z) != Material::air) return; - Material *m = level->getMaterial(x, y - 1, z); + Material* m = level->getMaterial(x, y - 1, z); - int i = 0; - if (m == Material::stone) i = 1; - if (m == Material::sand) i = 2; - if (m == Material::glass) i = 3; - if (m == Material::wood) i = 4; + int i = 0; + if (m == Material::stone) i = 1; + if (m == Material::sand) i = 2; + if (m == Material::glass) i = 3; + if (m == Material::wood) i = 4; - level->tileEvent(x, y, z, Tile::musicBlock_Id, i, note); + level->tileEvent(x, y, z, Tile::musicBlock_Id, i, note); } // 4J Added -std::shared_ptr MusicTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new MusicTileEntity() ); - TileEntity::clone(result); +std::shared_ptr MusicTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new MusicTileEntity()); + TileEntity::clone(result); - result->note = note; - return result; + result->note = note; + return result; } - diff --git a/Minecraft.World/Blocks/TileEntities/MusicTileEntity.h b/Minecraft.World/Blocks/TileEntities/MusicTileEntity.h index 4aad80f46..123130530 100644 --- a/Minecraft.World/Blocks/TileEntities/MusicTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/MusicTileEntity.h @@ -1,26 +1,24 @@ #pragma once - #include "TileEntity.h" -class MusicTileEntity : public TileEntity -{ +class MusicTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_MUSICTILEENTITY; } - static TileEntity *create() { return new MusicTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_MUSICTILEENTITY; } + static TileEntity* create() { return new MusicTileEntity(); } public: - uint8_t note; + uint8_t note; - bool on; + bool on; - MusicTileEntity(); + MusicTileEntity(); - virtual void save(CompoundTag *tag); - virtual void load(CompoundTag *tag); - void tune(); - void playNote(Level *level, int x, int y, int z); + virtual void save(CompoundTag* tag); + virtual void load(CompoundTag* tag); + void tune(); + void playNote(Level* level, int x, int y, int z); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; diff --git a/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.cpp index 79e2e7cb6..b5b6b656d 100644 --- a/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.cpp @@ -6,210 +6,166 @@ #include "../../Util/Facing.h" #include "../Tile.h" +PistonPieceEntity::PistonPieceEntity() { + // for the tile entity loader - -PistonPieceEntity::PistonPieceEntity() -{ - // for the tile entity loader - - // 4J - added initialisers - this->id = 0; - this->data = 0; - this->facing = 0; - this->extending = 0; - this->_isSourcePiston = 0; - progress = 0.0f; - progressO = 0.0f; + // 4J - added initialisers + this->id = 0; + this->data = 0; + this->facing = 0; + this->extending = 0; + this->_isSourcePiston = 0; + progress = 0.0f; + progressO = 0.0f; } -PistonPieceEntity::PistonPieceEntity(int id, int data, int facing, bool extending, bool isSourcePiston) : TileEntity() -{ - // 4J - added initialisers - progress = 0.0f; - progressO = 0.0f; +PistonPieceEntity::PistonPieceEntity(int id, int data, int facing, + bool extending, bool isSourcePiston) + : TileEntity() { + // 4J - added initialisers + progress = 0.0f; + progressO = 0.0f; - this->id = id; - this->data = data; - this->facing = facing; - this->extending = extending; - this->_isSourcePiston = isSourcePiston; + this->id = id; + this->data = data; + this->facing = facing; + this->extending = extending; + this->_isSourcePiston = isSourcePiston; } -int PistonPieceEntity::getId() -{ - return id; +int PistonPieceEntity::getId() { return id; } + +int PistonPieceEntity::getData() { return data; } + +bool PistonPieceEntity::isExtending() { return extending; } + +int PistonPieceEntity::getFacing() { return facing; } + +bool PistonPieceEntity::isSourcePiston() { return _isSourcePiston; } + +float PistonPieceEntity::getProgress(float a) { + if (a > 1) { + a = 1; + } + return progressO + (progress - progressO) * a; } -int PistonPieceEntity::getData() -{ - return data; +float PistonPieceEntity::getXOff(float a) { + if (extending) { + return (getProgress(a) - 1.0f) * Facing::STEP_X[facing]; + } else { + return (1.0f - getProgress(a)) * Facing::STEP_X[facing]; + } } -bool PistonPieceEntity::isExtending() -{ - return extending; +float PistonPieceEntity::getYOff(float a) { + if (extending) { + return (getProgress(a) - 1.0f) * Facing::STEP_Y[facing]; + } else { + return (1.0f - getProgress(a)) * Facing::STEP_Y[facing]; + } } -int PistonPieceEntity::getFacing() -{ - return facing; +float PistonPieceEntity::getZOff(float a) { + if (extending) { + return (getProgress(a) - 1.0f) * Facing::STEP_Z[facing]; + } else { + return (1.0f - getProgress(a)) * Facing::STEP_Z[facing]; + } } -bool PistonPieceEntity::isSourcePiston() -{ - return _isSourcePiston; +void PistonPieceEntity::moveCollidedEntities(float progress, float amount) { + if (extending) { + progress = 1.0f - progress; + } else { + progress = progress - 1.0f; + } + + AABB* aabb = + Tile::pistonMovingPiece->getAABB(level, x, y, z, id, progress, facing); + if (aabb != NULL) { + std::vector >* entities = + level->getEntities(nullptr, aabb); + if (!entities->empty()) { + std::vector > collisionHolder; + for (AUTO_VAR(it, entities->begin()); it != entities->end(); it++) { + collisionHolder.push_back(*it); + } + + for (AUTO_VAR(it, collisionHolder.begin()); + it != collisionHolder.end(); it++) { + (*it)->move(amount * Facing::STEP_X[facing], + amount * Facing::STEP_Y[facing], + amount * Facing::STEP_Z[facing]); + } + } + } } -float PistonPieceEntity::getProgress(float a) -{ - if (a > 1) - { - a = 1; - } - return progressO + (progress - progressO) * a; +void PistonPieceEntity::finalTick() { + if (progressO < 1 && level != NULL) { + progressO = progress = 1; + level->removeTileEntity(x, y, z); + setRemoved(); + if (level->getTile(x, y, z) == Tile::pistonMovingPiece_Id) + level->setTileAndData(x, y, z, id, data); + } } -float PistonPieceEntity::getXOff(float a) -{ - if (extending) - { - return (getProgress(a) - 1.0f) * Facing::STEP_X[facing]; - } - else - { - return (1.0f - getProgress(a)) * Facing::STEP_X[facing]; - } +void PistonPieceEntity::tick() { + progressO = progress; + + if (progressO >= 1) { + moveCollidedEntities(1, 4 / 16.f); + level->removeTileEntity(x, y, z); + setRemoved(); + if (level->getTile(x, y, z) == Tile::pistonMovingPiece_Id) + level->setTileAndData(x, y, z, id, data); + return; + } + + progress += .5f; + if (progress >= 1) { + progress = 1; + } + + if (extending) { + moveCollidedEntities(progress, (progress - progressO) + 1.0f / 16.0f); + } } -float PistonPieceEntity::getYOff(float a) -{ - if (extending) - { - return (getProgress(a) - 1.0f) * Facing::STEP_Y[facing]; - } - else - { - return (1.0f - getProgress(a)) * Facing::STEP_Y[facing]; - } +void PistonPieceEntity::load(CompoundTag* tag) { + TileEntity::load(tag); + + id = tag->getInt(L"blockId"); + data = tag->getInt(L"blockData"); + facing = tag->getInt(L"facing"); + progressO = progress = tag->getFloat(L"progress"); + extending = tag->getBoolean(L"extending"); } -float PistonPieceEntity::getZOff(float a) -{ - if (extending) - { - return (getProgress(a) - 1.0f) * Facing::STEP_Z[facing]; - } - else - { - return (1.0f - getProgress(a)) * Facing::STEP_Z[facing]; - } -} +void PistonPieceEntity::save(CompoundTag* tag) { + TileEntity::save(tag); -void PistonPieceEntity::moveCollidedEntities(float progress, float amount) -{ - if (extending) - { - progress = 1.0f - progress; - } - else - { - progress = progress - 1.0f; - } - - AABB *aabb = Tile::pistonMovingPiece->getAABB(level, x, y, z, id, progress, facing); - if (aabb != NULL) - { - std::vector > *entities = level->getEntities(nullptr, aabb); - if (!entities->empty()) - { - std::vector< std::shared_ptr > collisionHolder; - for( AUTO_VAR(it, entities->begin()); it != entities->end(); it++ ) - { - collisionHolder.push_back(*it); - } - - for( AUTO_VAR(it, collisionHolder.begin()); it != collisionHolder.end(); it++ ) - { - (*it)->move(amount * Facing::STEP_X[facing], - amount * Facing::STEP_Y[facing], - amount * Facing::STEP_Z[facing]); - } - } - } -} - -void PistonPieceEntity::finalTick() -{ - if (progressO < 1 && level != NULL) - { - progressO = progress = 1; - level->removeTileEntity(x, y, z); - setRemoved(); - if (level->getTile(x, y, z) == Tile::pistonMovingPiece_Id) - level->setTileAndData(x, y, z, id, data); - } -} - -void PistonPieceEntity::tick() -{ - progressO = progress; - - if (progressO >= 1) - { - moveCollidedEntities(1, 4 / 16.f); - level->removeTileEntity(x, y, z); - setRemoved(); - if (level->getTile(x, y, z) == Tile::pistonMovingPiece_Id) - level->setTileAndData(x, y, z, id, data); - return; - } - - progress += .5f; - if (progress >= 1) - { - progress = 1; - } - - if (extending) - { - moveCollidedEntities(progress, (progress - progressO) + 1.0f / 16.0f); - } -} - -void PistonPieceEntity::load(CompoundTag *tag) -{ - TileEntity::load(tag); - - id = tag->getInt(L"blockId"); - data = tag->getInt(L"blockData"); - facing = tag->getInt(L"facing"); - progressO = progress = tag->getFloat(L"progress"); - extending = tag->getBoolean(L"extending"); -} - -void PistonPieceEntity::save(CompoundTag *tag) -{ - TileEntity::save(tag); - - tag->putInt(L"blockId", id); - tag->putInt(L"blockData", data); - tag->putInt(L"facing", facing); - tag->putFloat(L"progress", progressO); - tag->putBoolean(L"extending", extending); + tag->putInt(L"blockId", id); + tag->putInt(L"blockData", data); + tag->putInt(L"facing", facing); + tag->putFloat(L"progress", progressO); + tag->putBoolean(L"extending", extending); } // 4J Added -std::shared_ptr PistonPieceEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new PistonPieceEntity() ); - TileEntity::clone(result); +std::shared_ptr PistonPieceEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new PistonPieceEntity()); + TileEntity::clone(result); - result->id = id; - result->data = data; - result->facing = facing; - result->extending = extending; - result->_isSourcePiston = _isSourcePiston; - result->progress = progress; - result->progressO = progressO; - return result; + result->id = id; + result->data = data; + result->facing = facing; + result->extending = extending; + result->_isSourcePiston = _isSourcePiston; + result->progress = progress; + result->progressO = progressO; + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h b/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h index 6eb6654f3..f70328f97 100644 --- a/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h @@ -1,41 +1,45 @@ #pragma once #include "TileEntity.h" -class PistonPieceEntity : public TileEntity -{ +class PistonPieceEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_PISTONPIECEENTITY; } - static TileEntity *create() { return new PistonPieceEntity(); } + eINSTANCEOF GetType() { return eTYPE_PISTONPIECEENTITY; } + static TileEntity* create() { return new PistonPieceEntity(); } + private: - int id; - int data; - int facing; - bool extending; - bool _isSourcePiston; + int id; + int data; + int facing; + bool extending; + bool _isSourcePiston; - float progress, progressO; + float progress, progressO; public: - PistonPieceEntity(); - PistonPieceEntity(int id, int data, int facing, bool extending, bool isSourcePiston); - int getId(); - virtual int getData(); - bool isExtending(); - int getFacing(); - bool isSourcePiston(); - float getProgress(float a); - float getXOff(float a); - float getYOff(float a); - float getZOff(float a); + PistonPieceEntity(); + PistonPieceEntity(int id, int data, int facing, bool extending, + bool isSourcePiston); + int getId(); + virtual int getData(); + bool isExtending(); + int getFacing(); + bool isSourcePiston(); + float getProgress(float a); + float getXOff(float a); + float getYOff(float a); + float getZOff(float a); + private: -// static List collisionHolder = new ArrayList(); // 4J - just using local vector for this now - void moveCollidedEntities(float progress, float amount); -public: - void finalTick(); - virtual void tick(); - virtual void load(CompoundTag *tag); - virtual void save(CompoundTag *tag); + // static List collisionHolder = new ArrayList(); + //// 4J - just using local vector for this now + void moveCollidedEntities(float progress, float amount); - // 4J Added - std::shared_ptr clone(); +public: + void finalTick(); + virtual void tick(); + virtual void load(CompoundTag* tag); + virtual void save(CompoundTag* tag); + + // 4J Added + std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/PotionBrewing.cpp b/Minecraft.World/Blocks/TileEntities/PotionBrewing.cpp index 983140c40..19b936d26 100644 --- a/Minecraft.World/Blocks/TileEntities/PotionBrewing.cpp +++ b/Minecraft.World/Blocks/TileEntities/PotionBrewing.cpp @@ -5,67 +5,50 @@ #include "../../Util/SharedConstants.h" #include "PotionBrewing.h" -const int PotionBrewing::DEFAULT_APPEARANCES[] = -{ - IDS_POTION_PREFIX_MUNDANE, - IDS_POTION_PREFIX_UNINTERESTING, - IDS_POTION_PREFIX_BLAND, - IDS_POTION_PREFIX_CLEAR, - IDS_POTION_PREFIX_MILKY, - IDS_POTION_PREFIX_DIFFUSE, - IDS_POTION_PREFIX_ARTLESS, - IDS_POTION_PREFIX_THIN, - IDS_POTION_PREFIX_AWKWARD, - IDS_POTION_PREFIX_FLAT, - IDS_POTION_PREFIX_BULKY, - IDS_POTION_PREFIX_BUNGLING, - IDS_POTION_PREFIX_BUTTERED, - IDS_POTION_PREFIX_SMOOTH, - IDS_POTION_PREFIX_SUAVE, - IDS_POTION_PREFIX_DEBONAIR, - IDS_POTION_PREFIX_THICK, - IDS_POTION_PREFIX_ELEGANT, - IDS_POTION_PREFIX_FANCY, - IDS_POTION_PREFIX_CHARMING, - IDS_POTION_PREFIX_DASHING, - IDS_POTION_PREFIX_REFINED, - IDS_POTION_PREFIX_CORDIAL, - IDS_POTION_PREFIX_SPARKLING, - IDS_POTION_PREFIX_POTENT, - IDS_POTION_PREFIX_FOUL, - IDS_POTION_PREFIX_ODORLESS, - IDS_POTION_PREFIX_RANK, - IDS_POTION_PREFIX_HARSH, - IDS_POTION_PREFIX_ACRID, - IDS_POTION_PREFIX_GROSS, - IDS_POTION_PREFIX_STINKY, +const int PotionBrewing::DEFAULT_APPEARANCES[] = { + IDS_POTION_PREFIX_MUNDANE, IDS_POTION_PREFIX_UNINTERESTING, + IDS_POTION_PREFIX_BLAND, IDS_POTION_PREFIX_CLEAR, + IDS_POTION_PREFIX_MILKY, IDS_POTION_PREFIX_DIFFUSE, + IDS_POTION_PREFIX_ARTLESS, IDS_POTION_PREFIX_THIN, + IDS_POTION_PREFIX_AWKWARD, IDS_POTION_PREFIX_FLAT, + IDS_POTION_PREFIX_BULKY, IDS_POTION_PREFIX_BUNGLING, + IDS_POTION_PREFIX_BUTTERED, IDS_POTION_PREFIX_SMOOTH, + IDS_POTION_PREFIX_SUAVE, IDS_POTION_PREFIX_DEBONAIR, + IDS_POTION_PREFIX_THICK, IDS_POTION_PREFIX_ELEGANT, + IDS_POTION_PREFIX_FANCY, IDS_POTION_PREFIX_CHARMING, + IDS_POTION_PREFIX_DASHING, IDS_POTION_PREFIX_REFINED, + IDS_POTION_PREFIX_CORDIAL, IDS_POTION_PREFIX_SPARKLING, + IDS_POTION_PREFIX_POTENT, IDS_POTION_PREFIX_FOUL, + IDS_POTION_PREFIX_ODORLESS, IDS_POTION_PREFIX_RANK, + IDS_POTION_PREFIX_HARSH, IDS_POTION_PREFIX_ACRID, + IDS_POTION_PREFIX_GROSS, IDS_POTION_PREFIX_STINKY, }; // bit 4 is the "enabler," lit by nether seeds - // bits 0-3 are effect identifiers - // 0001 - regeneration - // 0010 - move speed - // 0011 - fire resist - // 0100 - poison - // 0101 - heal - // 0110 - night vision - // 0111 - invisibility - // 1000 - weakness - // 1001 - damage boost - // 1010 - move slow - // 1011 - - // 1100 - harm - // 1101 - - // 1110 - - // 1111 - +// bits 0-3 are effect identifiers +// 0001 - regeneration +// 0010 - move speed +// 0011 - fire resist +// 0100 - poison +// 0101 - heal +// 0110 - night vision +// 0111 - invisibility +// 1000 - weakness +// 1001 - damage boost +// 1010 - move slow +// 1011 - +// 1100 - harm +// 1101 - +// 1110 - +// 1111 - /* 4J-JEV: Fix for #81196, * Bit 13 is always set in functional potions. * Therefore if bit 13 is on, don't use netherwart! * Added "&!13" which requires that bit 13 be turned off. */ -const std::wstring PotionBrewing::MOD_NETHERWART = L"+4&!13"; // L"+4" +const std::wstring PotionBrewing::MOD_NETHERWART = L"+4&!13"; // L"+4" #if _SIMPLIFIED_BREWING const std::wstring PotionBrewing::MOD_WATER = L""; @@ -77,10 +60,16 @@ const std::wstring PotionBrewing::MOD_SPECKLEDMELON = L"+0-1+2-3&4-4+13"; const std::wstring PotionBrewing::MOD_BLAZEPOWDER = L"+0-1-2+3&4-4+13"; const std::wstring PotionBrewing::MOD_GOLDENCARROT = L"-0+1+2-3+13&4-4"; const std::wstring PotionBrewing::MOD_MAGMACREAM = L"+0+1-2-3&4-4+13"; -const std::wstring PotionBrewing::MOD_REDSTONE = L"-5+6-7"; // redstone increases duration -const std::wstring PotionBrewing::MOD_GLOWSTONE = L"+5-6-7"; // glowstone increases amplification -// 4J Stu - Don't require bit 13 to be set. We don't use it in the creative menu. Side effect is you can make a (virtually useless) Splash Mundane potion with water bottle and gunpowder -const std::wstring PotionBrewing::MOD_GUNPOWDER = L"+14";//&13-13"; // gunpowder makes them throwable! // gunpowder requires 13 and sets 14 +const std::wstring PotionBrewing::MOD_REDSTONE = + L"-5+6-7"; // redstone increases duration +const std::wstring PotionBrewing::MOD_GLOWSTONE = + L"+5-6-7"; // glowstone increases amplification +// 4J Stu - Don't require bit 13 to be set. We don't use it in the creative +// menu. Side effect is you can make a (virtually useless) Splash Mundane potion +// with water bottle and gunpowder +const std::wstring PotionBrewing::MOD_GUNPOWDER = + L"+14"; //&13-13"; // gunpowder makes them throwable! // gunpowder requires + //13 and sets 14 #else const std::wstring PotionBrewing::MOD_WATER = L"-1-3-5-7-9-11-13"; const std::wstring PotionBrewing::MOD_SUGAR = L"+0"; @@ -90,9 +79,13 @@ const std::wstring PotionBrewing::MOD_FERMENTEDEYE = L"+14+9"; const std::wstring PotionBrewing::MOD_SPECKLEDMELON = L""; const std::wstring PotionBrewing::MOD_BLAZEPOWDER = L"+14"; const std::wstring PotionBrewing::MOD_MAGMACREAM = L"+14+6+1"; -const std::wstring PotionBrewing::MOD_REDSTONE = L""; // redstone increases duration -const std::wstring PotionBrewing::MOD_GLOWSTONE = L""; // glowstone increases amplification -const std::wstring PotionBrewing::MOD_GUNPOWDER = L""; // gunpowder makes them throwable! // gunpowder requires 13 and sets 14 +const std::wstring PotionBrewing::MOD_REDSTONE = + L""; // redstone increases duration +const std::wstring PotionBrewing::MOD_GLOWSTONE = + L""; // glowstone increases amplification +const std::wstring PotionBrewing::MOD_GUNPOWDER = + L""; // gunpowder makes them throwable! // gunpowder requires 13 and sets + // 14 #endif PotionBrewing::intStringMap PotionBrewing::potionEffectDuration; @@ -100,767 +93,683 @@ PotionBrewing::intStringMap PotionBrewing::potionEffectAmplifier; std::unordered_map PotionBrewing::cachedColors; -void PotionBrewing::staticCtor() -{ +void PotionBrewing::staticCtor() { #if _SIMPLIFIED_BREWING - potionEffectDuration.insert(intStringMap::value_type( MobEffect::regeneration->getId(), L"0 & !1 & !2 & !3 & 0+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::movementSpeed->getId(), L"!0 & 1 & !2 & !3 & 1+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::fireResistance->getId(), L"0 & 1 & !2 & !3 & 0+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::heal->getId(), L"0 & !1 & 2 & !3" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::poison->getId(), L"!0 & !1 & 2 & !3 & 2+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::weakness->getId(), L"!0 & !1 & !2 & 3 & 3+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::harm->getId(), L"!0 & !1 & 2 & 3" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::movementSlowdown->getId(), L"!0 & 1 & !2 & 3 & 3+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::damageBoost->getId(), L"0 & !1 & !2 & 3 & 3+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::nightVision->getId(), L"!0 & 1 & 2 & !3 & 2+6" )); - potionEffectDuration.insert(intStringMap::value_type( MobEffect::invisibility->getId(), L"!0 & 1 & 2 & 3 & 2+6" )); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::regeneration->getId(), L"0 & !1 & !2 & !3 & 0+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::movementSpeed->getId(), L"!0 & 1 & !2 & !3 & 1+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::fireResistance->getId(), L"0 & 1 & !2 & !3 & 0+6")); + potionEffectDuration.insert( + intStringMap::value_type(MobEffect::heal->getId(), L"0 & !1 & 2 & !3")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::poison->getId(), L"!0 & !1 & 2 & !3 & 2+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::weakness->getId(), L"!0 & !1 & !2 & 3 & 3+6")); + potionEffectDuration.insert( + intStringMap::value_type(MobEffect::harm->getId(), L"!0 & !1 & 2 & 3")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::movementSlowdown->getId(), L"!0 & 1 & !2 & 3 & 3+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::damageBoost->getId(), L"0 & !1 & !2 & 3 & 3+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::nightVision->getId(), L"!0 & 1 & 2 & !3 & 2+6")); + potionEffectDuration.insert(intStringMap::value_type( + MobEffect::invisibility->getId(), L"!0 & 1 & 2 & 3 & 2+6")); - // glowstone increases amplification - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::movementSpeed->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::digSpeed->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::damageBoost->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::regeneration->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::harm->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::heal->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::damageResistance->getId(), L"5" )); - potionEffectAmplifier.insert(intStringMap::value_type( MobEffect::poison->getId(), L"5" )); + // glowstone increases amplification + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::movementSpeed->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::digSpeed->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::damageBoost->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::regeneration->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::harm->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::heal->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::damageResistance->getId(), L"5")); + potionEffectAmplifier.insert( + intStringMap::value_type(MobEffect::poison->getId(), L"5")); #else - potionEffectDuration.put(movementSpeed.getId(), "!10 & !4 & 5*2+0 & >1 | !7 & !4 & 5*2+0 & >1"); - potionEffectDuration.put(movementSlowdown.getId(), "10 & 7 & !4 & 7+5+1-0"); - potionEffectDuration.put(digSpeed.getId(), "2 & 12+2+6-1-7 & <8"); - potionEffectDuration.put(digSlowdown.getId(), "!2 & !1*2-9 & 14-5"); - potionEffectDuration.put(damageBoost.getId(), "9 & 3 & 9+4+5 & <11"); - potionEffectDuration.put(weakness.getId(), "=1>5>7>9+3-7-2-11 & !9 & !0"); - potionEffectDuration.put(heal.getId(), "11 & <6"); - potionEffectDuration.put(harm.getId(), "!11 & 1 & 10 & !7"); - potionEffectDuration.put(jump.getId(), "8 & 2+0 & <5"); - potionEffectDuration.put(confusion.getId(), "8*2-!7+4-11 & !2 | 13 & 11 & 2*3-1-5"); - potionEffectDuration.put(regeneration.getId(), "!14 & 13*3-!0-!5-8"); - potionEffectDuration.put(damageResistance.getId(), "10 & 4 & 10+5+6 & <9"); - potionEffectDuration.put(fireResistance.getId(), "14 & !5 & 6-!1 & 14+13+12"); - potionEffectDuration.put(waterBreathing.getId(), "0+1+12 & !6 & 10 & !11 & !13"); - potionEffectDuration.put(invisibility.getId(), "2+5+13-0-4 & !7 & !1 & >5"); - potionEffectDuration.put(blindness.getId(), "9 & !1 & !5 & !3 & =3"); - potionEffectDuration.put(nightVision.getId(), "8*2-!7 & 5 & !0 & >3"); - potionEffectDuration.put(hunger.getId(), ">4>6>8-3-8+2"); - potionEffectDuration.put(poison.getId(), "12+9 & !13 & !0"); + potionEffectDuration.put(movementSpeed.getId(), + "!10 & !4 & 5*2+0 & >1 | !7 & !4 & 5*2+0 & >1"); + potionEffectDuration.put(movementSlowdown.getId(), "10 & 7 & !4 & 7+5+1-0"); + potionEffectDuration.put(digSpeed.getId(), "2 & 12+2+6-1-7 & <8"); + potionEffectDuration.put(digSlowdown.getId(), "!2 & !1*2-9 & 14-5"); + potionEffectDuration.put(damageBoost.getId(), "9 & 3 & 9+4+5 & <11"); + potionEffectDuration.put(weakness.getId(), "=1>5>7>9+3-7-2-11 & !9 & !0"); + potionEffectDuration.put(heal.getId(), "11 & <6"); + potionEffectDuration.put(harm.getId(), "!11 & 1 & 10 & !7"); + potionEffectDuration.put(jump.getId(), "8 & 2+0 & <5"); + potionEffectDuration.put(confusion.getId(), + "8*2-!7+4-11 & !2 | 13 & 11 & 2*3-1-5"); + potionEffectDuration.put(regeneration.getId(), "!14 & 13*3-!0-!5-8"); + potionEffectDuration.put(damageResistance.getId(), "10 & 4 & 10+5+6 & <9"); + potionEffectDuration.put(fireResistance.getId(), + "14 & !5 & 6-!1 & 14+13+12"); + potionEffectDuration.put(waterBreathing.getId(), + "0+1+12 & !6 & 10 & !11 & !13"); + potionEffectDuration.put(invisibility.getId(), "2+5+13-0-4 & !7 & !1 & >5"); + potionEffectDuration.put(blindness.getId(), "9 & !1 & !5 & !3 & =3"); + potionEffectDuration.put(nightVision.getId(), "8*2-!7 & 5 & !0 & >3"); + potionEffectDuration.put(hunger.getId(), ">4>6>8-3-8+2"); + potionEffectDuration.put(poison.getId(), "12+9 & !13 & !0"); - potionEffectAmplifier.put(movementSpeed.getId(), "7+!3-!1"); - potionEffectAmplifier.put(digSpeed.getId(), "1+0-!11"); - potionEffectAmplifier.put(damageBoost.getId(), "2+7-!12"); - potionEffectAmplifier.put(heal.getId(), "11+!0-!1-!14"); - potionEffectAmplifier.put(harm.getId(), "!11-!14+!0-!1"); - potionEffectAmplifier.put(damageResistance.getId(), "12-!2"); - potionEffectAmplifier.put(poison.getId(), "14>5"); + potionEffectAmplifier.put(movementSpeed.getId(), "7+!3-!1"); + potionEffectAmplifier.put(digSpeed.getId(), "1+0-!11"); + potionEffectAmplifier.put(damageBoost.getId(), "2+7-!12"); + potionEffectAmplifier.put(heal.getId(), "11+!0-!1-!14"); + potionEffectAmplifier.put(harm.getId(), "!11-!14+!0-!1"); + potionEffectAmplifier.put(damageResistance.getId(), "12-!2"); + potionEffectAmplifier.put(poison.getId(), "14>5"); #endif } -bool PotionBrewing::isWrappedLit(int brew, int position) -{ - return (brew & (1 << (position % NUM_BITS))) != 0; +bool PotionBrewing::isWrappedLit(int brew, int position) { + return (brew & (1 << (position % NUM_BITS))) != 0; } -bool PotionBrewing::isLit(int brew, int position) -{ - return (brew & (1 << position)) != 0; +bool PotionBrewing::isLit(int brew, int position) { + return (brew & (1 << position)) != 0; } -int PotionBrewing::isBit(int brew, int position) -{ - return isLit(brew, position) ? 1 : 0; +int PotionBrewing::isBit(int brew, int position) { + return isLit(brew, position) ? 1 : 0; } -int PotionBrewing::isNotBit(int brew, int position) -{ - return isLit(brew, position) ? 0 : 1; +int PotionBrewing::isNotBit(int brew, int position) { + return isLit(brew, position) ? 0 : 1; } -int PotionBrewing::getAppearanceValue(int brew) -{ - return valueOf(brew, 5, 4, 3, 2, 1); +int PotionBrewing::getAppearanceValue(int brew) { + return valueOf(brew, 5, 4, 3, 2, 1); } -int PotionBrewing::getColorValue(std::vector *effects) -{ - ColourTable *colourTable = Minecraft::GetInstance()->getColourTable(); +int PotionBrewing::getColorValue(std::vector* effects) { + ColourTable* colourTable = Minecraft::GetInstance()->getColourTable(); - int baseColor = colourTable->getColor( eMinecraftColour_Potion_BaseColour ); + int baseColor = colourTable->getColor(eMinecraftColour_Potion_BaseColour); - if (effects == NULL || effects->empty()) - { - return baseColor; - } + if (effects == NULL || effects->empty()) { + return baseColor; + } - float red = 0; - float green = 0; - float blue = 0; - float count = 0; + float red = 0; + float green = 0; + float blue = 0; + float count = 0; - //for (MobEffectInstance effect : effects){ - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) - { - MobEffectInstance *effect = *it; - int potionColor = colourTable->getColor( MobEffect::effects[effect->getId()]->getColor() ); + // for (MobEffectInstance effect : effects){ + for (AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) { + MobEffectInstance* effect = *it; + int potionColor = colourTable->getColor( + MobEffect::effects[effect->getId()]->getColor()); - for (int potency = 0; potency <= effect->getAmplifier(); potency++) - { - red += (float) ((potionColor >> 16) & 0xff) / 255.0f; - green += (float) ((potionColor >> 8) & 0xff) / 255.0f; - blue += (float) ((potionColor >> 0) & 0xff) / 255.0f; - count++; - } - } + for (int potency = 0; potency <= effect->getAmplifier(); potency++) { + red += (float)((potionColor >> 16) & 0xff) / 255.0f; + green += (float)((potionColor >> 8) & 0xff) / 255.0f; + blue += (float)((potionColor >> 0) & 0xff) / 255.0f; + count++; + } + } - red = (red / count) * 255.0f; - green = (green / count) * 255.0f; - blue = (blue / count) * 255.0f; + red = (red / count) * 255.0f; + green = (green / count) * 255.0f; + blue = (blue / count) * 255.0f; - return ((int) red) << 16 | ((int) green) << 8 | ((int) blue); + return ((int)red) << 16 | ((int)green) << 8 | ((int)blue); } -int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) -{ - if (!includeDisabledEffects) - { - AUTO_VAR(colIt, cachedColors.find(brew)); - if (colIt != cachedColors.end()) - { - return colIt->second;//cachedColors.get(brew); - } - std::vector *effects = getEffects(brew, false); - int color = getColorValue(effects); - if(effects != NULL) - { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) - { - MobEffectInstance *effect = *it; - delete effect; - } - delete effects; - } - cachedColors.insert( std::pair(brew, color) ); - return color; - } +int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) { + if (!includeDisabledEffects) { + AUTO_VAR(colIt, cachedColors.find(brew)); + if (colIt != cachedColors.end()) { + return colIt->second; // cachedColors.get(brew); + } + std::vector* effects = getEffects(brew, false); + int color = getColorValue(effects); + if (effects != NULL) { + for (AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) { + MobEffectInstance* effect = *it; + delete effect; + } + delete effects; + } + cachedColors.insert(std::pair(brew, color)); + return color; + } - return getColorValue(getEffects(brew, includeDisabledEffects)); + return getColorValue(getEffects(brew, includeDisabledEffects)); } -int PotionBrewing::getSmellValue(int brew) -{ - return valueOf(brew, 12, 11, 6, 4, 0); +int PotionBrewing::getSmellValue(int brew) { + return valueOf(brew, 12, 11, 6, 4, 0); } -int PotionBrewing::getAppearanceName(int brew) -{ - int value = getAppearanceValue(brew); - return DEFAULT_APPEARANCES[value]; +int PotionBrewing::getAppearanceName(int brew) { + int value = getAppearanceValue(brew); + return DEFAULT_APPEARANCES[value]; } -int PotionBrewing::constructParsedValue(bool isNot, bool hasMultiplier, bool isNeg, int countCompare, int valuePart, int multiplierPart, int brew) -{ - int value = 0; - if (isNot) - { - value = isNotBit(brew, valuePart); - } +int PotionBrewing::constructParsedValue(bool isNot, bool hasMultiplier, + bool isNeg, int countCompare, + int valuePart, int multiplierPart, + int brew) { + int value = 0; + if (isNot) { + value = isNotBit(brew, valuePart); + } #if !(_SIMPLIFIED_BREWING) - else if (countCompare != NO_COUNT) // Never true for simplified brewing - { - if (countCompare == EQUAL_COUNT && countOnes(brew) == valuePart) - { - value = 1; - } - else if (countCompare == GREATER_COUNT && countOnes(brew) > valuePart) - { - value = 1; - } - else if (countCompare == LESS_COUNT && countOnes(brew) < valuePart) - { - value = 1; - } - } + else if (countCompare != NO_COUNT) // Never true for simplified brewing + { + if (countCompare == EQUAL_COUNT && countOnes(brew) == valuePart) { + value = 1; + } else if (countCompare == GREATER_COUNT && + countOnes(brew) > valuePart) { + value = 1; + } else if (countCompare == LESS_COUNT && countOnes(brew) < valuePart) { + value = 1; + } + } #endif - else - { - value = isBit(brew, valuePart); - } + else { + value = isBit(brew, valuePart); + } #if !(_SIMPLIFIED_BREWING) - if (hasMultiplier) // Always false for simplified brewing - { - value *= multiplierPart; - } + if (hasMultiplier) // Always false for simplified brewing + { + value *= multiplierPart; + } #endif - if (isNeg) - { - value *= -1; - } - return value; + if (isNeg) { + value *= -1; + } + return value; } -int PotionBrewing::countOnes(int brew) -{ - int c = 0; - for (; brew > 0; c++) - { - brew &= brew - 1; - } - return c; +int PotionBrewing::countOnes(int brew) { + int c = 0; + for (; brew > 0; c++) { + brew &= brew - 1; + } + return c; } #if _SIMPLIFIED_BREWING -// 4J Stu - Trimmed this function to remove all the unused features for simplified brewing -int PotionBrewing::parseEffectFormulaValue(const std::wstring &definition, int start, int end, int brew) -{ - if (start >= definition.length() || end < 0 || start >= end) - { - return 0; - } +// 4J Stu - Trimmed this function to remove all the unused features for +// simplified brewing +int PotionBrewing::parseEffectFormulaValue(const std::wstring& definition, + int start, int end, int brew) { + if (start >= definition.length() || end < 0 || start >= end) { + return 0; + } - // split by and - int andIndex = (int)definition.find_first_of(L'&', start); - if (andIndex >= 0 && andIndex < end) - { - int leftSide = parseEffectFormulaValue(definition, start, andIndex - 1, brew); - if (leftSide <= 0) - { - return 0; - } + // split by and + int andIndex = (int)definition.find_first_of(L'&', start); + if (andIndex >= 0 && andIndex < end) { + int leftSide = + parseEffectFormulaValue(definition, start, andIndex - 1, brew); + if (leftSide <= 0) { + return 0; + } - int rightSide = parseEffectFormulaValue(definition, andIndex + 1, end, brew); - if (rightSide <= 0) - { - return 0; - } + int rightSide = + parseEffectFormulaValue(definition, andIndex + 1, end, brew); + if (rightSide <= 0) { + return 0; + } - if (leftSide > rightSide) - { - return leftSide; - } - return rightSide; - } + if (leftSide > rightSide) { + return leftSide; + } + return rightSide; + } - bool hasMultiplier = false; - bool hasValue = false; - bool isNot = false; - bool isNeg = false; - int bitCount = NO_COUNT; - int valuePart = 0; - int multiplierPart = 0; - int result = 0; - for (int i = start; i < end; i++) - { + bool hasMultiplier = false; + bool hasValue = false; + bool isNot = false; + bool isNeg = false; + int bitCount = NO_COUNT; + int valuePart = 0; + int multiplierPart = 0; + int result = 0; + for (int i = start; i < end; i++) { + char current = definition.at(i); + if (current >= L'0' && current <= L'9') { + valuePart *= 10; + valuePart += (int)(current - L'0'); + hasValue = true; + } else if (current == L'!') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = isNeg = isNot = false; + valuePart = 0; + } - char current = definition.at(i); - if (current >= L'0' && current <= L'9') - { - valuePart *= 10; - valuePart += (int) (current - L'0'); - hasValue = true; - } - else if (current == L'!') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = isNeg = isNot = false; - valuePart = 0; - } + isNot = true; + } else if (current == L'-') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = isNeg = isNot = false; + valuePart = 0; + } - isNot = true; - } - else if (current == L'-') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = isNeg = isNot = false; - valuePart = 0; - } + isNeg = true; + } else if (current == L'+') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = isNeg = isNot = false; + valuePart = 0; + } + } + } + if (hasValue) { + result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + } - isNeg = true; - } - else if (current == L'+') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = isNeg = isNot = false; - valuePart = 0; - } - } - } - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - } - - return result; + return result; } #else -int PotionBrewing::parseEffectFormulaValue(const std::wstring &definition, int start, int end, int brew) -{ - if (start >= definition.length() || end < 0 || start >= end) - { - return 0; - } +int PotionBrewing::parseEffectFormulaValue(const std::wstring& definition, + int start, int end, int brew) { + if (start >= definition.length() || end < 0 || start >= end) { + return 0; + } - // split by or - int orIndex = definition.find_first_of(L'|', start); - if (orIndex >= 0 && orIndex < end) - { - int leftSide = parseEffectFormulaValue(definition, start, orIndex - 1, brew); - if (leftSide > 0) - { - return leftSide; - } + // split by or + int orIndex = definition.find_first_of(L'|', start); + if (orIndex >= 0 && orIndex < end) { + int leftSide = + parseEffectFormulaValue(definition, start, orIndex - 1, brew); + if (leftSide > 0) { + return leftSide; + } - int rightSide = parseEffectFormulaValue(definition, orIndex + 1, end, brew); - if (rightSide > 0) - { - return rightSide; - } - return 0; - } - // split by and - int andIndex = definition.find_first_of(L'&', start); - if (andIndex >= 0 && andIndex < end) - { - int leftSide = parseEffectFormulaValue(definition, start, andIndex - 1, brew); - if (leftSide <= 0) - { - return 0; - } + int rightSide = + parseEffectFormulaValue(definition, orIndex + 1, end, brew); + if (rightSide > 0) { + return rightSide; + } + return 0; + } + // split by and + int andIndex = definition.find_first_of(L'&', start); + if (andIndex >= 0 && andIndex < end) { + int leftSide = + parseEffectFormulaValue(definition, start, andIndex - 1, brew); + if (leftSide <= 0) { + return 0; + } - int rightSide = parseEffectFormulaValue(definition, andIndex + 1, end, brew); - if (rightSide <= 0) - { - return 0; - } + int rightSide = + parseEffectFormulaValue(definition, andIndex + 1, end, brew); + if (rightSide <= 0) { + return 0; + } - if (leftSide > rightSide) - { - return leftSide; - } - return rightSide; - } + if (leftSide > rightSide) { + return leftSide; + } + return rightSide; + } - bool isMultiplier = false; - bool hasMultiplier = false; - bool hasValue = false; - bool isNot = false; - bool isNeg = false; - int bitCount = NO_COUNT; - int valuePart = 0; - int multiplierPart = 0; - int result = 0; - for (int i = start; i < end; i++) - { + bool isMultiplier = false; + bool hasMultiplier = false; + bool hasValue = false; + bool isNot = false; + bool isNeg = false; + int bitCount = NO_COUNT; + int valuePart = 0; + int multiplierPart = 0; + int result = 0; + for (int i = start; i < end; i++) { + char current = definition.at(i); + if (current >= L'0' && current <= L'9') { + if (isMultiplier) { + multiplierPart = (int)(current - L'0'); + hasMultiplier = true; + } else { + valuePart *= 10; + valuePart += (int)(current - L'0'); + hasValue = true; + } + } else if (current == L'*') { + isMultiplier = true; + } else if (current == L'!') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; + valuePart = multiplierPart = 0; + bitCount = NO_COUNT; + } - char current = definition.at(i); - if (current >= L'0' && current <= L'9') - { - if (isMultiplier) - { - multiplierPart = (int) (current - L'0'); - hasMultiplier = true; - } - else - { - valuePart *= 10; - valuePart += (int) (current - L'0'); - hasValue = true; - } - } - else if (current == L'*') - { - isMultiplier = true; - } - else if (current == L'!') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; - valuePart = multiplierPart = 0; - bitCount = NO_COUNT; - } + isNot = true; + } else if (current == L'-') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; + valuePart = multiplierPart = 0; + bitCount = NO_COUNT; + } - isNot = true; - } - else if (current == L'-') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; - valuePart = multiplierPart = 0; - bitCount = NO_COUNT; - } + isNeg = true; + } else if (current == L'=' || current == L'<' || current == L'>') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; + valuePart = multiplierPart = 0; + bitCount = NO_COUNT; + } - isNeg = true; - } - else if (current == L'=' || current == L'<' || current == L'>') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; - valuePart = multiplierPart = 0; - bitCount = NO_COUNT; - } + if (current == L'=') { + bitCount = EQUAL_COUNT; + } else if (current == L'<') { + bitCount = LESS_COUNT; + } else if (current == L'>') { + bitCount = GREATER_COUNT; + } + } else if (current == L'+') { + if (hasValue) { + result += + constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; + valuePart = multiplierPart = 0; + bitCount = NO_COUNT; + } + } + } + if (hasValue) { + result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, + valuePart, multiplierPart, brew); + } - if (current == L'=') - { - bitCount = EQUAL_COUNT; - } - else if (current == L'<') - { - bitCount = LESS_COUNT; - } - else if (current == L'>') - { - bitCount = GREATER_COUNT; - } - } - else if (current == L'+') - { - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - hasValue = hasMultiplier = isMultiplier = isNeg = isNot = false; - valuePart = multiplierPart = 0; - bitCount = NO_COUNT; - } - } - } - if (hasValue) - { - result += constructParsedValue(isNot, hasMultiplier, isNeg, bitCount, valuePart, multiplierPart, brew); - } - - return result; + return result; } #endif -std::vector *PotionBrewing::getEffects(int brew, bool includeDisabledEffects) -{ - std::vector *list = NULL; +std::vector* PotionBrewing::getEffects( + int brew, bool includeDisabledEffects) { + std::vector* list = NULL; - //for (MobEffect effect : MobEffect.effects) - for(unsigned int i = 0; i < MobEffect::NUM_EFFECTS; ++i) - { - MobEffect *effect = MobEffect::effects[i]; - if (effect == NULL || (effect->isDisabled() && !includeDisabledEffects)) - { - continue; - } - //std::wstring durationString = potionEffectDuration.get(effect->getId()); - AUTO_VAR(effIt, potionEffectDuration.find(effect->getId())); - if ( effIt == potionEffectDuration.end() ) - { - continue; - } - std::wstring durationString = effIt->second; + // for (MobEffect effect : MobEffect.effects) + for (unsigned int i = 0; i < MobEffect::NUM_EFFECTS; ++i) { + MobEffect* effect = MobEffect::effects[i]; + if (effect == NULL || + (effect->isDisabled() && !includeDisabledEffects)) { + continue; + } + // std::wstring durationString = + // potionEffectDuration.get(effect->getId()); + AUTO_VAR(effIt, potionEffectDuration.find(effect->getId())); + if (effIt == potionEffectDuration.end()) { + continue; + } + std::wstring durationString = effIt->second; - int duration = parseEffectFormulaValue(durationString, 0, (int)durationString.length(), brew); - if (duration > 0) - { - int amplifier = 0; - AUTO_VAR(ampIt, potionEffectAmplifier.find(effect->getId())); - if (ampIt != potionEffectAmplifier.end()) - { - std::wstring amplifierString = ampIt->second; - amplifier = parseEffectFormulaValue(amplifierString, 0, (int)amplifierString.length(), brew); - if (amplifier < 0) - { - amplifier = 0; - } - } + int duration = parseEffectFormulaValue( + durationString, 0, (int)durationString.length(), brew); + if (duration > 0) { + int amplifier = 0; + AUTO_VAR(ampIt, potionEffectAmplifier.find(effect->getId())); + if (ampIt != potionEffectAmplifier.end()) { + std::wstring amplifierString = ampIt->second; + amplifier = parseEffectFormulaValue( + amplifierString, 0, (int)amplifierString.length(), brew); + if (amplifier < 0) { + amplifier = 0; + } + } - if (effect->isInstantenous()) - { - duration = 1; - } - else - { - // 3, 8, 13, 18.. minutes - duration = (SharedConstants::TICKS_PER_SECOND * 60) * (duration * 3 + (duration - 1) * 2); - duration >>= amplifier; - duration = (int) Math::round((double) duration * effect->getDurationModifier()); + if (effect->isInstantenous()) { + duration = 1; + } else { + // 3, 8, 13, 18.. minutes + duration = (SharedConstants::TICKS_PER_SECOND * 60) * + (duration * 3 + (duration - 1) * 2); + duration >>= amplifier; + duration = (int)Math::round((double)duration * + effect->getDurationModifier()); - if ((brew & THROWABLE_MASK) != 0) - { - duration = (int) Math::round((double) duration * .75 + .5); - } - } + if ((brew & THROWABLE_MASK) != 0) { + duration = (int)Math::round((double)duration * .75 + .5); + } + } - if (list == NULL) - { - list = new std::vector(); - } - list->push_back(new MobEffectInstance(effect->getId(), duration, amplifier)); - } - } + if (list == NULL) { + list = new std::vector(); + } + list->push_back( + new MobEffectInstance(effect->getId(), duration, amplifier)); + } + } - return list; + return list; } #if !(_SIMPLIFIED_BREWING) -int PotionBrewing::boil(int brew) -{ - if ((brew & 1) == 0) - { - return brew; - } +int PotionBrewing::boil(int brew) { + if ((brew & 1) == 0) { + return brew; + } - // save highest bit - int savedBit = NUM_BITS - 1; - while ((brew & (1 << savedBit)) == 0 && savedBit >= 0) - { - savedBit--; - } - // it's not possible to boil if there are no "empty slots" in front of - // the last bit - if (savedBit < 2 || (brew & (1 << (savedBit - 1))) != 0) - { - return brew; - } - if (savedBit >= 0) - { - brew &= ~(1 << savedBit); - } + // save highest bit + int savedBit = NUM_BITS - 1; + while ((brew & (1 << savedBit)) == 0 && savedBit >= 0) { + savedBit--; + } + // it's not possible to boil if there are no "empty slots" in front of + // the last bit + if (savedBit < 2 || (brew & (1 << (savedBit - 1))) != 0) { + return brew; + } + if (savedBit >= 0) { + brew &= ~(1 << savedBit); + } - brew <<= 1; + brew <<= 1; - if (savedBit >= 0) - { - brew |= (1 << savedBit); - brew |= (1 << (savedBit - 1)); - } + if (savedBit >= 0) { + brew |= (1 << savedBit); + brew |= (1 << (savedBit - 1)); + } - return brew & BREW_MASK; + return brew & BREW_MASK; } -int PotionBrewing::shake(int brew) -{ +int PotionBrewing::shake(int brew) { + // save highest bit + int savedBit = NUM_BITS - 1; + while ((brew & (1 << savedBit)) == 0 && savedBit >= 0) { + savedBit--; + } + if (savedBit >= 0) { + brew &= ~(1 << savedBit); + } - // save highest bit - int savedBit = NUM_BITS - 1; - while ((brew & (1 << savedBit)) == 0 && savedBit >= 0) - { - savedBit--; - } - if (savedBit >= 0) - { - brew &= ~(1 << savedBit); - } + int currentResult = 0; + int nextResult = brew; - int currentResult = 0; - int nextResult = brew; + while (nextResult != currentResult) { + nextResult = brew; + currentResult = 0; + // evaluate each bit + for (int bit = 0; bit < NUM_BITS; bit++) { + bool on = isWrappedLit(brew, bit); + if (on) { + if (!isWrappedLit(brew, bit + 1) && + isWrappedLit(brew, bit + 2)) { + on = false; + } else if (!isWrappedLit(brew, bit - 1) && + isWrappedLit(brew, bit - 2)) { + on = false; + } + } else { + // turn on if both neighbors are on + on = isWrappedLit(brew, bit - 1) && isWrappedLit(brew, bit + 1); + } + if (on) { + currentResult |= (1 << bit); + } + } + brew = currentResult; + } - while (nextResult != currentResult) - { - nextResult = brew; - currentResult = 0; - // evaluate each bit - for (int bit = 0; bit < NUM_BITS; bit++) - { + if (savedBit >= 0) { + currentResult |= (1 << savedBit); + } - bool on = isWrappedLit(brew, bit); - if (on) - { - if (!isWrappedLit(brew, bit + 1) && isWrappedLit(brew, bit + 2)) - { - on = false; - } - else if (!isWrappedLit(brew, bit - 1) && isWrappedLit(brew, bit - 2)) - { - on = false; - } - } - else - { - // turn on if both neighbors are on - on = isWrappedLit(brew, bit - 1) && isWrappedLit(brew, bit + 1); - } - if (on) - { - currentResult |= (1 << bit); - } - } - brew = currentResult; - } - - if (savedBit >= 0) - { - currentResult |= (1 << savedBit); - } - - return currentResult & BREW_MASK; + return currentResult & BREW_MASK; } -int PotionBrewing::stirr(int brew) -{ - if ((brew & 1) != 0) - { - brew = boil(brew); - } - return shake(brew); +int PotionBrewing::stirr(int brew) { + if ((brew & 1) != 0) { + brew = boil(brew); + } + return shake(brew); } #endif -int PotionBrewing::applyBrewBit(int currentBrew, int bit, bool isNeg, bool isNot, bool isRequired) -{ - if (isRequired) - { - // 4J-JEV: I wanted to be able to specify that a - // bit is required to be false. - if (isLit(currentBrew, bit) == isNot) - { - return 0; - } - } - else if (isNeg) - { - currentBrew &= ~(1 << bit); - } - else if (isNot) - { - if ((currentBrew & (1 << bit)) == 0) - { - currentBrew |= (1 << bit); - } - else - { - currentBrew &= ~(1 << bit); - } - } - else - { - currentBrew |= (1 << bit); - } - return currentBrew; +int PotionBrewing::applyBrewBit(int currentBrew, int bit, bool isNeg, + bool isNot, bool isRequired) { + if (isRequired) { + // 4J-JEV: I wanted to be able to specify that a + // bit is required to be false. + if (isLit(currentBrew, bit) == isNot) { + return 0; + } + } else if (isNeg) { + currentBrew &= ~(1 << bit); + } else if (isNot) { + if ((currentBrew & (1 << bit)) == 0) { + currentBrew |= (1 << bit); + } else { + currentBrew &= ~(1 << bit); + } + } else { + currentBrew |= (1 << bit); + } + return currentBrew; } -int PotionBrewing::applyBrew(int currentBrew, const std::wstring &formula) -{ +int PotionBrewing::applyBrew(int currentBrew, const std::wstring& formula) { + int start = 0; + int end = (int)formula.length(); - int start = 0; - int end = (int)formula.length(); + bool hasValue = false; + bool isNot = false; + bool isNeg = false; + bool isRequired = false; + int valuePart = 0; + for (int i = start; i < end; i++) { + char current = formula.at(i); + if (current >= L'0' && current <= L'9') { + valuePart *= 10; + valuePart += (int)(current - L'0'); + hasValue = true; + } else if (current == L'!') { + if (hasValue) { + currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, + isRequired); + hasValue = isNeg = isNot = isRequired = false; + valuePart = 0; + } - bool hasValue = false; - bool isNot = false; - bool isNeg = false; - bool isRequired = false; - int valuePart = 0; - for (int i = start; i < end; i++) - { - char current = formula.at(i); - if (current >= L'0' && current <= L'9') - { - valuePart *= 10; - valuePart += (int) (current - L'0'); - hasValue = true; - } - else if (current == L'!') - { - if (hasValue) - { - currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); - hasValue = isNeg = isNot = isRequired = false; - valuePart = 0; - } + isNot = true; + } else if (current == L'-') { + if (hasValue) { + currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, + isRequired); + hasValue = isNeg = isNot = isRequired = false; + valuePart = 0; + } - isNot = true; - } - else if (current == L'-') - { - if (hasValue) - { - currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); - hasValue = isNeg = isNot = isRequired = false; - valuePart = 0; - } + isNeg = true; + } else if (current == L'+') { + if (hasValue) { + currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, + isRequired); + hasValue = isNeg = isNot = isRequired = false; + valuePart = 0; + } + } else if (current == L'&') { + if (hasValue) { + currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, + isRequired); + hasValue = isNeg = isNot = isRequired = false; + valuePart = 0; + } + isRequired = true; + } + } + if (hasValue) { + currentBrew = + applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); + } - isNeg = true; - } - else if (current == L'+') - { - if (hasValue) - { - currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); - hasValue = isNeg = isNot = isRequired = false; - valuePart = 0; - } - } - else if (current == L'&') - { - if (hasValue) - { - currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); - hasValue = isNeg = isNot = isRequired = false; - valuePart = 0; - } - isRequired = true; - } - } - if (hasValue) - { - currentBrew = applyBrewBit(currentBrew, valuePart, isNeg, isNot, isRequired); - } - - return currentBrew & BREW_MASK; + return currentBrew & BREW_MASK; } -int PotionBrewing::setBit(int brew, int position, bool onOff) -{ - if (onOff) - { - return brew | (1 << position); - } - return brew & ~(1 << position); +int PotionBrewing::setBit(int brew, int position, bool onOff) { + if (onOff) { + return brew | (1 << position); + } + return brew & ~(1 << position); } -int PotionBrewing::valueOf(int brew, int p1, int p2, int p3, int p4) -{ - return ((isLit(brew, p1) ? 0x08 : 0) | (isLit(brew, p2) ? 0x04 : 0) | (isLit(brew, p3) ? 0x02 : 0) | (isLit(brew, p4) ? 0x01 : 0)); +int PotionBrewing::valueOf(int brew, int p1, int p2, int p3, int p4) { + return ((isLit(brew, p1) ? 0x08 : 0) | (isLit(brew, p2) ? 0x04 : 0) | + (isLit(brew, p3) ? 0x02 : 0) | (isLit(brew, p4) ? 0x01 : 0)); } -int PotionBrewing::valueOf(int brew, int p1, int p2, int p3, int p4, int p5) -{ - return (isLit(brew, p1) ? 0x10 : 0) | (isLit(brew, p2) ? 0x08 : 0) | (isLit(brew, p3) ? 0x04 : 0) | (isLit(brew, p4) ? 0x02 : 0) | (isLit(brew, p5) ? 0x01 : 0); +int PotionBrewing::valueOf(int brew, int p1, int p2, int p3, int p4, int p5) { + return (isLit(brew, p1) ? 0x10 : 0) | (isLit(brew, p2) ? 0x08 : 0) | + (isLit(brew, p3) ? 0x04 : 0) | (isLit(brew, p4) ? 0x02 : 0) | + (isLit(brew, p5) ? 0x01 : 0); } -std::wstring PotionBrewing::toString(int brew) -{ - std::wstring string; +std::wstring PotionBrewing::toString(int brew) { + std::wstring string; - int bit = NUM_BITS - 1; - while (bit >= 0) - { - if ((brew & (1 << bit)) != 0) - { - string.append(L"O"); - } - else - { - string.append(L"x"); - } - bit--; - } + int bit = NUM_BITS - 1; + while (bit >= 0) { + if ((brew & (1 << bit)) != 0) { + string.append(L"O"); + } else { + string.append(L"x"); + } + bit--; + } - return string; + return string; } -//void main(String[] args) +// void main(String[] args) //{ -// HashMap existingCombinations = new HashMap(); -// HashMap distinctCombinations = new HashMap(); -// int noEffects = 0; -// for (int brew = 0; brew <= BREW_MASK; brew++) { -// List effects = PotionBrewing.getEffects(brew, true); -// if (effects != null) { +// HashMap existingCombinations = new HashMap(); HashMap distinctCombinations = new +//HashMap(); int noEffects = 0; for (int brew = 0; brew <= +//BREW_MASK; brew++) { List effects = +//PotionBrewing.getEffects(brew, true); if (effects != null) { // { // StringBuilder builder = new StringBuilder(); @@ -869,11 +778,9 @@ std::wstring PotionBrewing::toString(int brew) // builder.append(" "); // } // String string = builder.toString(); -// Integer count = existingCombinations.get(string); -// if (count != null) { -// count++; -// } else { -// count = 1; +// Integer count = +//existingCombinations.get(string); if (count != null) { count++; } else { count +//= 1; // } // existingCombinations.put(string, count); // } @@ -884,11 +791,9 @@ std::wstring PotionBrewing::toString(int brew) // builder.append(" "); // } // String string = builder.toString(); -// Integer count = distinctCombinations.get(string); -// if (count != null) { -// count++; -// } else { -// count = 1; +// Integer count = +//distinctCombinations.get(string); if (count != null) { count++; } else { count +//= 1; // } // distinctCombinations.put(string, count); // } @@ -904,7 +809,8 @@ std::wstring PotionBrewing::toString(int brew) // } // } -// System.out.println("Combination with no effects: " + noEffects + " (" + ((double) noEffects / BREW_MASK * 100.0) + " %)"); -// System.out.println("Unique combinations: " + existingCombinations.size()); -// System.out.println("Distinct combinations: " + distinctCombinations.size()); +// System.out.println("Combination with no effects: " + noEffects + " (" + +//((double) noEffects / BREW_MASK * 100.0) + " %)"); System.out.println("Unique +//combinations: " + existingCombinations.size()); System.out.println("Distinct +//combinations: " + distinctCombinations.size()); //} \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/PotionBrewing.h b/Minecraft.World/Blocks/TileEntities/PotionBrewing.h index 0dfb21487..04703b822 100644 --- a/Minecraft.World/Blocks/TileEntities/PotionBrewing.h +++ b/Minecraft.World/Blocks/TileEntities/PotionBrewing.h @@ -2,100 +2,105 @@ class MobEffectInstance; -class PotionBrewing -{ +class PotionBrewing { public: - static const bool SIMPLIFIED_BREWING = true; - // 4J Stu - Made #define so we can use it to select const initialisation + static const bool SIMPLIFIED_BREWING = true; + // 4J Stu - Made #define so we can use it to select const initialisation #define _SIMPLIFIED_BREWING 1 - static const int BREWING_TIME_SECONDS = 20; + static const int BREWING_TIME_SECONDS = 20; - static const int THROWABLE_BIT = 14; - static const int THROWABLE_MASK = (1 << THROWABLE_BIT); + static const int THROWABLE_BIT = 14; + static const int THROWABLE_MASK = (1 << THROWABLE_BIT); - static const std::wstring MOD_WATER; - static const std::wstring MOD_SUGAR; - static const std::wstring MOD_GHASTTEARS; - static const std::wstring MOD_SPIDEREYE; - static const std::wstring MOD_FERMENTEDEYE; - static const std::wstring MOD_SPECKLEDMELON; - static const std::wstring MOD_BLAZEPOWDER; - static const std::wstring MOD_MAGMACREAM; - static const std::wstring MOD_REDSTONE; - static const std::wstring MOD_GLOWSTONE; - static const std::wstring MOD_NETHERWART; - static const std::wstring MOD_GUNPOWDER; - static const std::wstring MOD_GOLDENCARROT; + static const std::wstring MOD_WATER; + static const std::wstring MOD_SUGAR; + static const std::wstring MOD_GHASTTEARS; + static const std::wstring MOD_SPIDEREYE; + static const std::wstring MOD_FERMENTEDEYE; + static const std::wstring MOD_SPECKLEDMELON; + static const std::wstring MOD_BLAZEPOWDER; + static const std::wstring MOD_MAGMACREAM; + static const std::wstring MOD_REDSTONE; + static const std::wstring MOD_GLOWSTONE; + static const std::wstring MOD_NETHERWART; + static const std::wstring MOD_GUNPOWDER; + static const std::wstring MOD_GOLDENCARROT; private: - typedef std::unordered_map intStringMap; - static intStringMap potionEffectDuration; - static intStringMap potionEffectAmplifier; - -public: - static void staticCtor(); - - static const int NUM_BITS = 15; - - // 4J Stu - Made public - static const int BREW_MASK = 0x7fff; -private: - static const int TOP_BIT = 0x4000; - - static bool isWrappedLit(int brew, int position); + typedef std::unordered_map intStringMap; + static intStringMap potionEffectDuration; + static intStringMap potionEffectAmplifier; public: - static bool isLit(int brew, int position); + static void staticCtor(); + + static const int NUM_BITS = 15; + + // 4J Stu - Made public + static const int BREW_MASK = 0x7fff; private: - static int isBit(int brew, int position); - static int isNotBit(int brew, int position); + static const int TOP_BIT = 0x4000; + + static bool isWrappedLit(int brew, int position); public: - static int getAppearanceValue(int brew); - static int getColorValue(std::vector *effects); + static bool isLit(int brew, int position); private: - static std::unordered_map cachedColors; + static int isBit(int brew, int position); + static int isNotBit(int brew, int position); public: - static int getColorValue(int brew, bool includeDisabledEffects); - static int getSmellValue(int brew); + static int getAppearanceValue(int brew); + static int getColorValue(std::vector* effects); private: - static const int DEFAULT_APPEARANCES[]; + static std::unordered_map cachedColors; public: - static int getAppearanceName(int brew); + static int getColorValue(int brew, bool includeDisabledEffects); + static int getSmellValue(int brew); private: - static const int NO_COUNT = -1; - static const int EQUAL_COUNT = 0; - static const int GREATER_COUNT = 1; - static const int LESS_COUNT = 2; - - static int constructParsedValue(bool isNot, bool hasMultiplier, bool isNeg, int countCompare, int valuePart, int multiplierPart, int brew); - static int countOnes(int brew); - static int parseEffectFormulaValue(const std::wstring &definition, int start, int end, int brew); + static const int DEFAULT_APPEARANCES[]; public: - static std::vector *getEffects(int brew, bool includeDisabledEffects); + static int getAppearanceName(int brew); + +private: + static const int NO_COUNT = -1; + static const int EQUAL_COUNT = 0; + static const int GREATER_COUNT = 1; + static const int LESS_COUNT = 2; + + static int constructParsedValue(bool isNot, bool hasMultiplier, bool isNeg, + int countCompare, int valuePart, + int multiplierPart, int brew); + static int countOnes(int brew); + static int parseEffectFormulaValue(const std::wstring& definition, + int start, int end, int brew); + +public: + static std::vector* getEffects( + int brew, bool includeDisabledEffects); #if !(_SIMPLIFIED_BREWING) - static int boil(int brew); - static int shake(int brew); - static int stirr(int brew); + static int boil(int brew); + static int shake(int brew); + static int stirr(int brew); #endif private: - static int applyBrewBit(int currentBrew, int bit, bool isNeg, bool isNot, bool isRequired); + static int applyBrewBit(int currentBrew, int bit, bool isNeg, bool isNot, + bool isRequired); public: - static int applyBrew(int currentBrew, const std::wstring &formula); - static int setBit(int brew, int position, bool onOff); - static int valueOf(int brew, int p1, int p2, int p3, int p4); - static int valueOf(int brew, int p1, int p2, int p3, int p4, int p5); - static std::wstring toString(int brew); - //static void main(String[] args); + static int applyBrew(int currentBrew, const std::wstring& formula); + static int setBit(int brew, int position, bool onOff); + static int valueOf(int brew, int p1, int p2, int p3, int p4); + static int valueOf(int brew, int p1, int p2, int p3, int p4, int p5); + static std::wstring toString(int brew); + // static void main(String[] args); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/SignTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/SignTileEntity.cpp index 71971e540..c98fa03d4 100644 --- a/Minecraft.World/Blocks/TileEntities/SignTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/SignTileEntity.cpp @@ -14,185 +14,168 @@ #include "../../../Minecraft.Client/Level/ServerLevel.h" #include "../../Level/Level.h" - - const int SignTileEntity::MAX_LINE_LENGTH = 15; -SignTileEntity::SignTileEntity() : TileEntity() -{ - m_wsmessages[0] = L""; - m_wsmessages[1] = L""; - m_wsmessages[2] = L""; - m_wsmessages[3] = L""; - m_bVerified=true; - m_bCensored=false; +SignTileEntity::SignTileEntity() : TileEntity() { + m_wsmessages[0] = L""; + m_wsmessages[1] = L""; + m_wsmessages[2] = L""; + m_wsmessages[3] = L""; + m_bVerified = true; + m_bCensored = false; - m_iSelectedLine = -1; + m_iSelectedLine = -1; - _isEditable = true; + _isEditable = true; } -SignTileEntity::~SignTileEntity() -{ - // TODO ORBIS_STUBBED; +SignTileEntity::~SignTileEntity() { + // TODO ORBIS_STUBBED; #ifndef __ORBIS__ - // 4J-PB - we don't need to verify strings anymore - InputManager.CancelQueuedVerifyStrings(&SignTileEntity::StringVerifyCallback, this); + // 4J-PB - we don't need to verify strings anymore - + // InputManager.CancelQueuedVerifyStrings(&SignTileEntity::StringVerifyCallback, + // this); #endif } -void SignTileEntity::save(CompoundTag *tag) -{ - TileEntity::save(tag); - tag->putString(L"Text1", m_wsmessages[0] ); - tag->putString(L"Text2", m_wsmessages[1] ); - tag->putString(L"Text3", m_wsmessages[2] ); - tag->putString(L"Text4", m_wsmessages[3] ); +void SignTileEntity::save(CompoundTag* tag) { + TileEntity::save(tag); + tag->putString(L"Text1", m_wsmessages[0]); + tag->putString(L"Text2", m_wsmessages[1]); + tag->putString(L"Text3", m_wsmessages[2]); + tag->putString(L"Text4", m_wsmessages[3]); #ifndef _CONTENT_PACKAGE - OutputDebugStringW(L"### - Saving a sign with text - \n"); - for(int i=0;i<4;i++) - { - OutputDebugStringW(m_wsmessages[i].c_str()); - OutputDebugStringW(L"\n"); - } + OutputDebugStringW(L"### - Saving a sign with text - \n"); + for (int i = 0; i < 4; i++) { + OutputDebugStringW(m_wsmessages[i].c_str()); + OutputDebugStringW(L"\n"); + } #endif } -void SignTileEntity::load(CompoundTag *tag) -{ - _isEditable = false; - TileEntity::load(tag); - for (int i = 0; i < MAX_SIGN_LINES; i++) - { - wchar_t *buf = new wchar_t[256]; - swprintf(buf, 256, L"Text%d", (i+1) ); - m_wsmessages[i] = tag->getString( buf ); - if (m_wsmessages[i].length() > MAX_LINE_LENGTH) m_wsmessages[i] = m_wsmessages[i].substr(0, MAX_LINE_LENGTH); - } +void SignTileEntity::load(CompoundTag* tag) { + _isEditable = false; + TileEntity::load(tag); + for (int i = 0; i < MAX_SIGN_LINES; i++) { + wchar_t* buf = new wchar_t[256]; + swprintf(buf, 256, L"Text%d", (i + 1)); + m_wsmessages[i] = tag->getString(buf); + if (m_wsmessages[i].length() > MAX_LINE_LENGTH) + m_wsmessages[i] = m_wsmessages[i].substr(0, MAX_LINE_LENGTH); + } #ifndef _CONTENT_PACKAGE - OutputDebugStringW(L"### - Loaded a sign with text - \n"); - for(int i=0;i<4;i++) - { - OutputDebugStringW(m_wsmessages[i].c_str()); - OutputDebugStringW(L"\n"); - } + OutputDebugStringW(L"### - Loaded a sign with text - \n"); + for (int i = 0; i < 4; i++) { + OutputDebugStringW(m_wsmessages[i].c_str()); + OutputDebugStringW(L"\n"); + } #endif - // 4J Stu - Fix for #13531 - Bug: Signs do not Censor after loading a save - // Set verified as false so that it can be re-verified - m_bVerified=false; + // 4J Stu - Fix for #13531 - Bug: Signs do not Censor after loading a save + // Set verified as false so that it can be re-verified + m_bVerified = false; - setChanged(); + setChanged(); } -std::shared_ptr SignTileEntity::getUpdatePacket() -{ - std::wstring copy[MAX_SIGN_LINES]; - for (int i = 0; i < MAX_SIGN_LINES; i++) - { - copy[i] = m_wsmessages[i]; - } - return std::shared_ptr( new SignUpdatePacket(x, y, z, m_bVerified, m_bCensored, copy) ); +std::shared_ptr SignTileEntity::getUpdatePacket() { + std::wstring copy[MAX_SIGN_LINES]; + for (int i = 0; i < MAX_SIGN_LINES; i++) { + copy[i] = m_wsmessages[i]; + } + return std::shared_ptr( + new SignUpdatePacket(x, y, z, m_bVerified, m_bCensored, copy)); } -bool SignTileEntity::isEditable() -{ - return _isEditable; +bool SignTileEntity::isEditable() { return _isEditable; } + +void SignTileEntity::setEditable(bool isEditable) { + this->_isEditable = isEditable; } -void SignTileEntity::setEditable(bool isEditable) -{ - this->_isEditable = isEditable; -} +void SignTileEntity::setChanged() { + Minecraft* pMinecraft = Minecraft::GetInstance(); -void SignTileEntity::setChanged() -{ - Minecraft *pMinecraft=Minecraft::GetInstance(); + // 4J-PB - For TU14 we are allowed to not verify strings anymore ! + m_bVerified = true; + /* + if(!g_NetworkManager.IsLocalGame() && !m_bVerified) + //if (pMinecraft->level->isClientSide) + { + WCHAR *wcMessages[MAX_SIGN_LINES]; + for (int i = 0; i < MAX_SIGN_LINES; ++i) + { + wcMessages[i]=new WCHAR [MAX_LINE_LENGTH+1]; + ZeroMemory(wcMessages[i],sizeof(WCHAR)*(MAX_LINE_LENGTH+1)); + if(m_wsmessages[i].length()>0) + { + memcpy(wcMessages[i],m_wsmessages[i].c_str(),m_wsmessages[i].length()*sizeof(WCHAR)); + } + } + // at this point, we can ask the online string verifier if our sign +text is ok #ifdef __ORBIS__ m_bVerified=true; #else - // 4J-PB - For TU14 we are allowed to not verify strings anymore ! - m_bVerified=true; - /* - if(!g_NetworkManager.IsLocalGame() && !m_bVerified) - //if (pMinecraft->level->isClientSide) - { - WCHAR *wcMessages[MAX_SIGN_LINES]; - for (int i = 0; i < MAX_SIGN_LINES; ++i) - { - wcMessages[i]=new WCHAR [MAX_LINE_LENGTH+1]; - ZeroMemory(wcMessages[i],sizeof(WCHAR)*(MAX_LINE_LENGTH+1)); - if(m_wsmessages[i].length()>0) - { - memcpy(wcMessages[i],m_wsmessages[i].c_str(),m_wsmessages[i].length()*sizeof(WCHAR)); - } - } - // at this point, we can ask the online string verifier if our sign text is ok -#ifdef __ORBIS__ - m_bVerified=true; -#else - - if(!InputManager.VerifyStrings((WCHAR**)&wcMessages,MAX_SIGN_LINES,&SignTileEntity::StringVerifyCallback, this)) - { - // Nothing to verify - m_bVerified=true; - } - for(unsigned int i = 0; i < MAX_SIGN_LINES; ++i) - { - delete [] wcMessages[i]; - } + if(!InputManager.VerifyStrings((WCHAR**)&wcMessages,MAX_SIGN_LINES,&SignTileEntity::StringVerifyCallback, +this)) + { + // Nothing to verify + m_bVerified=true; + } + for(unsigned int i = 0; i < MAX_SIGN_LINES; ++i) + { + delete [] wcMessages[i]; + } #endif - } - else - { - // set the sign to allowed (local game) - m_bVerified=true; - } - */ + } + else + { + // set the sign to allowed (local game) + m_bVerified=true; + } + */ } - -void SignTileEntity::SetMessage(int iIndex,std::wstring &wsText) -{ - m_wsmessages[iIndex]=wsText; - +void SignTileEntity::SetMessage(int iIndex, std::wstring& wsText) { + m_wsmessages[iIndex] = wsText; } // 4J-PB - added for string verification -int SignTileEntity::StringVerifyCallback(void *lpParam,STRING_VERIFY_RESPONSE *pResults) -{ - // results will be in m_pStringVerifyResponse - SignTileEntity *pClass=(SignTileEntity *)lpParam; +int SignTileEntity::StringVerifyCallback(void* lpParam, + STRING_VERIFY_RESPONSE* pResults) { + // results will be in m_pStringVerifyResponse + SignTileEntity* pClass = (SignTileEntity*)lpParam; - pClass->m_bVerified=true; - pClass->m_bCensored=false; - for(int i=0;iwNumStrings;i++) - { - if(pResults->pStringResult[i]!=ERROR_SUCCESS) - { - pClass->m_bCensored=true; - } - } + pClass->m_bVerified = true; + pClass->m_bCensored = false; + for (int i = 0; i < pResults->wNumStrings; i++) { + if (pResults->pStringResult[i] != ERROR_SUCCESS) { + pClass->m_bCensored = true; + } + } - if(!pClass->level->isClientSide) - { - ServerLevel *serverLevel = (ServerLevel *)pClass->level; - // 4J Stu - This callback gets called on the main thread, but tried to access things on the server thread. Change to go through the protected method. - //pClass->level->sendTileUpdated(pClass->x, pClass->y, pClass->z); - serverLevel->queueSendTileUpdate(pClass->x, pClass->y, pClass->z); - } + if (!pClass->level->isClientSide) { + ServerLevel* serverLevel = (ServerLevel*)pClass->level; + // 4J Stu - This callback gets called on the main thread, but tried to + // access things on the server thread. Change to go through the + // protected method. + // pClass->level->sendTileUpdated(pClass->x, pClass->y, pClass->z); + serverLevel->queueSendTileUpdate(pClass->x, pClass->y, pClass->z); + } - return 0; + return 0; } // 4J Added -std::shared_ptr SignTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new SignTileEntity() ); - TileEntity::clone(result); +std::shared_ptr SignTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new SignTileEntity()); + TileEntity::clone(result); - result->m_wsmessages[0] = m_wsmessages[0]; - result->m_wsmessages[1] = m_wsmessages[1]; - result->m_wsmessages[2] = m_wsmessages[2]; - result->m_wsmessages[3] = m_wsmessages[3]; - result->m_bVerified = m_bVerified; - result->m_bCensored = m_bCensored; - return result; + result->m_wsmessages[0] = m_wsmessages[0]; + result->m_wsmessages[1] = m_wsmessages[1]; + result->m_wsmessages[2] = m_wsmessages[2]; + result->m_wsmessages[3] = m_wsmessages[3]; + result->m_bVerified = m_bVerified; + result->m_bCensored = m_bCensored; + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/SignTileEntity.h b/Minecraft.World/Blocks/TileEntities/SignTileEntity.h index b19d413d6..822770260 100644 --- a/Minecraft.World/Blocks/TileEntities/SignTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/SignTileEntity.h @@ -1,49 +1,49 @@ #pragma once - #include "TileEntity.h" #define MAX_SIGN_LINES 4 -class SignTileEntity : public TileEntity -{ +class SignTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_SIGNTILEENTITY; } - static TileEntity *create() { return new SignTileEntity(); } -public: - static const int MAX_LINE_LENGTH; + eINSTANCEOF GetType() { return eTYPE_SIGNTILEENTITY; } + static TileEntity* create() { return new SignTileEntity(); } public: - SignTileEntity(); - virtual ~SignTileEntity(); - std::wstring GetMessage(int i) { return m_wsmessages[i];} - std::wstring *GetMessages() { return m_wsmessages;} - void SetMessage(int iIndex,std::wstring &wsText); - int GetSelectedLine() {return m_iSelectedLine;} - void SetSelectedLine(int iLine) {m_iSelectedLine=iLine;} - bool IsVerified() {return m_bVerified;} - void SetVerified(bool bVerified) {m_bVerified=bVerified;} - bool IsCensored() {return m_bCensored;} - void SetCensored(bool bCensored) {m_bCensored=bCensored;} -public: + static const int MAX_LINE_LENGTH; +public: + SignTileEntity(); + virtual ~SignTileEntity(); + std::wstring GetMessage(int i) { return m_wsmessages[i]; } + std::wstring* GetMessages() { return m_wsmessages; } + void SetMessage(int iIndex, std::wstring& wsText); + int GetSelectedLine() { return m_iSelectedLine; } + void SetSelectedLine(int iLine) { m_iSelectedLine = iLine; } + bool IsVerified() { return m_bVerified; } + void SetVerified(bool bVerified) { m_bVerified = bVerified; } + bool IsCensored() { return m_bCensored; } + void SetCensored(bool bCensored) { m_bCensored = bCensored; } + +public: private: - bool _isEditable; - bool m_bVerified; - bool m_bCensored; - int m_iSelectedLine; + bool _isEditable; + bool m_bVerified; + bool m_bCensored; + int m_iSelectedLine; - std::wstring m_wsmessages[MAX_SIGN_LINES]; + std::wstring m_wsmessages[MAX_SIGN_LINES]; public: - virtual void save(CompoundTag *tag); - virtual void load(CompoundTag *tag); - virtual std::shared_ptr getUpdatePacket(); - bool isEditable(); - void setEditable(bool isEditable); - virtual void setChanged(); - static int StringVerifyCallback(void *lpParam,STRING_VERIFY_RESPONSE *pResults); + virtual void save(CompoundTag* tag); + virtual void load(CompoundTag* tag); + virtual std::shared_ptr getUpdatePacket(); + bool isEditable(); + void setEditable(bool isEditable); + virtual void setChanged(); + static int StringVerifyCallback(void* lpParam, + STRING_VERIFY_RESPONSE* pResults); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; diff --git a/Minecraft.World/Blocks/TileEntities/SkullTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/SkullTileEntity.cpp index 68b589787..9a481564e 100644 --- a/Minecraft.World/Blocks/TileEntities/SkullTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/SkullTileEntity.cpp @@ -3,70 +3,54 @@ #include "../../Headers/net.minecraft.network.packet.h" #include "SkullTileEntity.h" -SkullTileEntity::SkullTileEntity() -{ - skullType = 0; - rotation = 0; - extraType = L""; +SkullTileEntity::SkullTileEntity() { + skullType = 0; + rotation = 0; + extraType = L""; } -void SkullTileEntity::save(CompoundTag *tag) -{ - TileEntity::save(tag); - tag->putByte(L"SkullType", static_cast(skullType & 0xff)); - tag->putByte(L"Rot", static_cast(rotation & 0xff)); - tag->putString(L"ExtraType", extraType); +void SkullTileEntity::save(CompoundTag* tag) { + TileEntity::save(tag); + tag->putByte(L"SkullType", static_cast(skullType & 0xff)); + tag->putByte(L"Rot", static_cast(rotation & 0xff)); + tag->putString(L"ExtraType", extraType); } -void SkullTileEntity::load(CompoundTag *tag) -{ - TileEntity::load(tag); - skullType = tag->getByte(L"SkullType"); - rotation = tag->getByte(L"Rot"); - if (tag->contains(L"ExtraType")) extraType = tag->getString(L"ExtraType"); +void SkullTileEntity::load(CompoundTag* tag) { + TileEntity::load(tag); + skullType = tag->getByte(L"SkullType"); + rotation = tag->getByte(L"Rot"); + if (tag->contains(L"ExtraType")) extraType = tag->getString(L"ExtraType"); } -std::shared_ptr SkullTileEntity::getUpdatePacket() -{ - CompoundTag *tag = new CompoundTag(); - save(tag); - return std::shared_ptr(new TileEntityDataPacket(x, y, z, TileEntityDataPacket::TYPE_SKULL, tag)); +std::shared_ptr SkullTileEntity::getUpdatePacket() { + CompoundTag* tag = new CompoundTag(); + save(tag); + return std::shared_ptr(new TileEntityDataPacket( + x, y, z, TileEntityDataPacket::TYPE_SKULL, tag)); } -void SkullTileEntity::setSkullType(int skullType, const std::wstring &extra) -{ - this->skullType = skullType; - this->extraType = extra; +void SkullTileEntity::setSkullType(int skullType, const std::wstring& extra) { + this->skullType = skullType; + this->extraType = extra; } -int SkullTileEntity::getSkullType() -{ - return skullType; -} +int SkullTileEntity::getSkullType() { return skullType; } -int SkullTileEntity::getRotation() -{ - return rotation; -} +int SkullTileEntity::getRotation() { return rotation; } -void SkullTileEntity::setRotation(int rot) -{ - rotation = rot; -} +void SkullTileEntity::setRotation(int rot) { rotation = rot; } -std::wstring SkullTileEntity::getExtraType() -{ - return extraType; -} +std::wstring SkullTileEntity::getExtraType() { return extraType; } // 4J Added -std::shared_ptr SkullTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new SkullTileEntity() ); - TileEntity::clone(result); - - result->skullType = skullType; - result->rotation = rotation; - result->extraType = extraType; - return result; +std::shared_ptr SkullTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new SkullTileEntity()); + TileEntity::clone(result); + + result->skullType = skullType; + result->rotation = rotation; + result->extraType = extraType; + return result; } diff --git a/Minecraft.World/Blocks/TileEntities/SkullTileEntity.h b/Minecraft.World/Blocks/TileEntities/SkullTileEntity.h index 51b9d5e77..901b289a7 100644 --- a/Minecraft.World/Blocks/TileEntities/SkullTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/SkullTileEntity.h @@ -2,35 +2,35 @@ #include "TileEntity.h" -class SkullTileEntity : public TileEntity -{ +class SkullTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_SKULLTILEENTITY; } - static TileEntity *create() { return new SkullTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_SKULLTILEENTITY; } + static TileEntity* create() { return new SkullTileEntity(); } + public: - static const int TYPE_SKELETON = 0; - static const int TYPE_WITHER = 1; - static const int TYPE_ZOMBIE = 2; - static const int TYPE_CHAR = 3; - static const int TYPE_CREEPER = 4; + static const int TYPE_SKELETON = 0; + static const int TYPE_WITHER = 1; + static const int TYPE_ZOMBIE = 2; + static const int TYPE_CHAR = 3; + static const int TYPE_CREEPER = 4; private: - int skullType; - int rotation; - std::wstring extraType; + int skullType; + int rotation; + std::wstring extraType; public: - SkullTileEntity(); + SkullTileEntity(); - void save(CompoundTag *tag); - void load(CompoundTag *tag); - std::shared_ptr getUpdatePacket(); - void setSkullType(int skullType, const std::wstring &extra); - int getSkullType(); - int getRotation(); - void setRotation(int rot); - std::wstring getExtraType(); + void save(CompoundTag* tag); + void load(CompoundTag* tag); + std::shared_ptr getUpdatePacket(); + void setSkullType(int skullType, const std::wstring& extra); + int getSkullType(); + int getRotation(); + void setRotation(int rot); + std::wstring getExtraType(); - // 4J Added - virtual std::shared_ptr clone(); + // 4J Added + virtual std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.cpp b/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.cpp index 8bb344feb..6a2376cbb 100644 --- a/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.cpp @@ -2,9 +2,9 @@ #include "TheEndPortalTileEntity.h" // 4J Added -std::shared_ptr TheEndPortalTileEntity::clone() -{ - std::shared_ptr result = std::shared_ptr( new TheEndPortalTileEntity() ); - TileEntity::clone(result); - return result; +std::shared_ptr TheEndPortalTileEntity::clone() { + std::shared_ptr result = + std::shared_ptr(new TheEndPortalTileEntity()); + TileEntity::clone(result); + return result; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.h b/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.h index 0bc0b46c0..198431609 100644 --- a/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/TheEndPortalTileEntity.h @@ -1,12 +1,11 @@ #pragma once #include "TileEntity.h" -class TheEndPortalTileEntity : public TileEntity -{ +class TheEndPortalTileEntity : public TileEntity { public: - eINSTANCEOF GetType() { return eTYPE_THEENDPORTALTILEENTITY; } - static TileEntity *create() { return new TheEndPortalTileEntity(); } + eINSTANCEOF GetType() { return eTYPE_THEENDPORTALTILEENTITY; } + static TileEntity* create() { return new TheEndPortalTileEntity(); } - // 4J Added - std::shared_ptr clone(); + // 4J Added + std::shared_ptr clone(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/TileEntity.cpp b/Minecraft.World/Blocks/TileEntities/TileEntity.cpp index 88dc90d95..a6a1604fd 100644 --- a/Minecraft.World/Blocks/TileEntities/TileEntity.cpp +++ b/Minecraft.World/Blocks/TileEntities/TileEntity.cpp @@ -6,206 +6,176 @@ #include "TileEntity.h" #include "PistonPieceTileEntity.h" +TileEntity::idToCreateMapType TileEntity::idCreateMap = + std::unordered_map(); +TileEntity::classToIdMapType TileEntity::classIdMap = + std::unordered_map(); - -TileEntity::idToCreateMapType TileEntity::idCreateMap = std::unordered_map(); -TileEntity::classToIdMapType TileEntity::classIdMap = std::unordered_map(); - -void TileEntity::staticCtor() -{ - TileEntity::setId(FurnaceTileEntity::create, eTYPE_FURNACETILEENTITY, L"Furnace"); - TileEntity::setId(ChestTileEntity::create, eTYPE_CHESTTILEENTITY, L"Chest"); - TileEntity::setId(EnderChestTileEntity::create, eTYPE_ENDERCHESTTILEENTITY, L"EnderChest"); - TileEntity::setId(RecordPlayerTile::Entity::create, eTYPE_RECORDPLAYERTILE, L"RecordPlayer"); - TileEntity::setId(DispenserTileEntity::create, eTYPE_DISPENSERTILEENTITY, L"Trap"); - TileEntity::setId(SignTileEntity::create, eTYPE_SIGNTILEENTITY, L"Sign"); - TileEntity::setId(MobSpawnerTileEntity::create, eTYPE_MOBSPAWNERTILEENTITY, L"MobSpawner"); - TileEntity::setId(MusicTileEntity::create, eTYPE_MUSICTILEENTITY, L"Music"); - TileEntity::setId(PistonPieceEntity::create, eTYPE_PISTONPIECEENTITY, L"Piston"); - TileEntity::setId(BrewingStandTileEntity::create, eTYPE_BREWINGSTANDTILEENTITY, L"Cauldron"); - TileEntity::setId(EnchantmentTableEntity::create, eTYPE_ENCHANTMENTTABLEENTITY, L"EnchantTable"); - TileEntity::setId(TheEndPortalTileEntity::create, eTYPE_THEENDPORTALTILEENTITY, L"Airportal"); - TileEntity::setId(SkullTileEntity::create,eTYPE_SKULLTILEENTITY, L"Skull"); +void TileEntity::staticCtor() { + TileEntity::setId(FurnaceTileEntity::create, eTYPE_FURNACETILEENTITY, + L"Furnace"); + TileEntity::setId(ChestTileEntity::create, eTYPE_CHESTTILEENTITY, L"Chest"); + TileEntity::setId(EnderChestTileEntity::create, eTYPE_ENDERCHESTTILEENTITY, + L"EnderChest"); + TileEntity::setId(RecordPlayerTile::Entity::create, eTYPE_RECORDPLAYERTILE, + L"RecordPlayer"); + TileEntity::setId(DispenserTileEntity::create, eTYPE_DISPENSERTILEENTITY, + L"Trap"); + TileEntity::setId(SignTileEntity::create, eTYPE_SIGNTILEENTITY, L"Sign"); + TileEntity::setId(MobSpawnerTileEntity::create, eTYPE_MOBSPAWNERTILEENTITY, + L"MobSpawner"); + TileEntity::setId(MusicTileEntity::create, eTYPE_MUSICTILEENTITY, L"Music"); + TileEntity::setId(PistonPieceEntity::create, eTYPE_PISTONPIECEENTITY, + L"Piston"); + TileEntity::setId(BrewingStandTileEntity::create, + eTYPE_BREWINGSTANDTILEENTITY, L"Cauldron"); + TileEntity::setId(EnchantmentTableEntity::create, + eTYPE_ENCHANTMENTTABLEENTITY, L"EnchantTable"); + TileEntity::setId(TheEndPortalTileEntity::create, + eTYPE_THEENDPORTALTILEENTITY, L"Airportal"); + TileEntity::setId(SkullTileEntity::create, eTYPE_SKULLTILEENTITY, L"Skull"); } -void TileEntity::setId(tileEntityCreateFn createFn, eINSTANCEOF clas, std::wstring id) -{ - // 4J Stu - Java has classIdMap.containsKey(id) which would never work as id is not of the type of the key in classIdMap - // I have changed to use idClassMap instead so that we can still search from the string key - // TODO 4J Stu - Exceptions - if (idCreateMap.find(id) != idCreateMap.end() ) {}//throw new IllegalArgumentException("Duplicate id: " + id); - idCreateMap.insert( idToCreateMapType::value_type(id, createFn) ); - classIdMap.insert( classToIdMapType::value_type( clas, id ) ); +void TileEntity::setId(tileEntityCreateFn createFn, eINSTANCEOF clas, + std::wstring id) { + // 4J Stu - Java has classIdMap.containsKey(id) which would never work as id + // is not of the type of the key in classIdMap I have changed to use + // idClassMap instead so that we can still search from the string key + // TODO 4J Stu - Exceptions + if (idCreateMap.find(id) != idCreateMap.end()) { + } // throw new IllegalArgumentException("Duplicate id: " + id); + idCreateMap.insert(idToCreateMapType::value_type(id, createFn)); + classIdMap.insert(classToIdMapType::value_type(clas, id)); } -TileEntity::TileEntity() -{ - level = NULL; - x = y = z = 0; - remove = false; - data = -1; - tile = NULL; - renderRemoveStage = e_RenderRemoveStageKeep; +TileEntity::TileEntity() { + level = NULL; + x = y = z = 0; + remove = false; + data = -1; + tile = NULL; + renderRemoveStage = e_RenderRemoveStageKeep; } -Level *TileEntity::getLevel() -{ - return level; +Level* TileEntity::getLevel() { return level; } + +void TileEntity::setLevel(Level* level) { this->level = level; } + +bool TileEntity::hasLevel() { return level != NULL; } + +void TileEntity::load(CompoundTag* tag) { + x = tag->getInt(L"x"); + y = tag->getInt(L"y"); + z = tag->getInt(L"z"); } -void TileEntity::setLevel(Level *level) -{ - this->level = level; +void TileEntity::save(CompoundTag* tag) { + AUTO_VAR(it, classIdMap.find(this->GetType())); + if (it == classIdMap.end()) { + // TODO 4J Stu - Some sort of exception handling + // throw new RuntimeException(this->getClass() + " is missing a mapping! + // This is a bug!"); + return; + } + tag->putString(L"id", ((*it).second)); + tag->putInt(L"x", x); + tag->putInt(L"y", y); + tag->putInt(L"z", z); } -bool TileEntity::hasLevel() -{ - return level != NULL; -} +void TileEntity::tick() {} -void TileEntity::load(CompoundTag *tag) -{ - x = tag->getInt(L"x"); - y = tag->getInt(L"y"); - z = tag->getInt(L"z"); -} +std::shared_ptr TileEntity::loadStatic(CompoundTag* tag) { + std::shared_ptr entity = nullptr; -void TileEntity::save(CompoundTag *tag) -{ - AUTO_VAR(it, classIdMap.find( this->GetType() )); - if ( it == classIdMap.end() ) - { - // TODO 4J Stu - Some sort of exception handling - //throw new RuntimeException(this->getClass() + " is missing a mapping! This is a bug!"); - return; - } - tag->putString(L"id", ( (*it).second ) ); - tag->putInt(L"x", x); - tag->putInt(L"y", y); - tag->putInt(L"z", z); -} - -void TileEntity::tick() -{ -} - -std::shared_ptr TileEntity::loadStatic(CompoundTag *tag) -{ - std::shared_ptr entity = nullptr; - - //try - //{ - AUTO_VAR(it, idCreateMap.find(tag->getString(L"id"))); - if (it != idCreateMap.end() ) entity = std::shared_ptr(it->second()); - //} - //catch (Exception e) - //{ - // TODO 4J Stu - Exception handling? - // e->printStackTrace(); - //} - if (entity != NULL) - { - entity->load(tag); - } - else - { + // try + //{ + AUTO_VAR(it, idCreateMap.find(tag->getString(L"id"))); + if (it != idCreateMap.end()) + entity = std::shared_ptr(it->second()); + //} + // catch (Exception e) + //{ + // TODO 4J Stu - Exception handling? + // e->printStackTrace(); + //} + if (entity != NULL) { + entity->load(tag); + } else { #ifdef _DEBUG - app.DebugPrintf("Skipping TileEntity with id %ls.\n" , tag->getString(L"id").c_str() ); + app.DebugPrintf("Skipping TileEntity with id %ls.\n", + tag->getString(L"id").c_str()); #endif - } + } - return entity; + return entity; } -int TileEntity::getData() -{ - if (data == -1) data = level->getData(x, y, z); - return data; +int TileEntity::getData() { + if (data == -1) data = level->getData(x, y, z); + return data; } -void TileEntity::setData(int data) -{ - this->data = data; - level->setData(x, y, z, data); +void TileEntity::setData(int data) { + this->data = data; + level->setData(x, y, z, data); } -void TileEntity::setChanged() -{ - if (level != NULL) - { - data = level->getData(x, y, z); - level->tileEntityChanged(x, y, z, shared_from_this()); - } +void TileEntity::setChanged() { + if (level != NULL) { + data = level->getData(x, y, z); + level->tileEntityChanged(x, y, z, shared_from_this()); + } } -double TileEntity::distanceToSqr(double xPlayer, double yPlayer, double zPlayer) -{ - double xd = (x + 0.5) - xPlayer; - double yd = (y + 0.5) - yPlayer; - double zd = (z + 0.5) - zPlayer; - return xd * xd + yd * yd + zd * zd; +double TileEntity::distanceToSqr(double xPlayer, double yPlayer, + double zPlayer) { + double xd = (x + 0.5) - xPlayer; + double yd = (y + 0.5) - yPlayer; + double zd = (z + 0.5) - zPlayer; + return xd * xd + yd * yd + zd * zd; } -Tile *TileEntity::getTile() -{ - if( tile == NULL ) tile = Tile::tiles[level->getTile(x, y, z)]; - return tile; +Tile* TileEntity::getTile() { + if (tile == NULL) tile = Tile::tiles[level->getTile(x, y, z)]; + return tile; } -std::shared_ptr TileEntity::getUpdatePacket() -{ - return nullptr; -} +std::shared_ptr TileEntity::getUpdatePacket() { return nullptr; } -bool TileEntity::isRemoved() -{ - return remove; -} +bool TileEntity::isRemoved() { return remove; } -void TileEntity::setRemoved() -{ - remove = true; -} +void TileEntity::setRemoved() { remove = true; } -void TileEntity::clearRemoved() -{ - remove = false; -} -void TileEntity::triggerEvent(int b0, int b1) -{ -} +void TileEntity::clearRemoved() { remove = false; } +void TileEntity::triggerEvent(int b0, int b1) {} -void TileEntity::clearCache() -{ +void TileEntity::clearCache() { tile = NULL; data = -1; } -void TileEntity::setRenderRemoveStage( unsigned char stage ) -{ - renderRemoveStage = stage; +void TileEntity::setRenderRemoveStage(unsigned char stage) { + renderRemoveStage = stage; } -bool TileEntity::shouldRemoveForRender() -{ - return (renderRemoveStage == e_RenderRemoveStageRemove); +bool TileEntity::shouldRemoveForRender() { + return (renderRemoveStage == e_RenderRemoveStageRemove); } -void TileEntity::upgradeRenderRemoveStage() -{ - if( renderRemoveStage == e_RenderRemoveStageFlaggedAtChunk ) - { - renderRemoveStage = e_RenderRemoveStageRemove; - } +void TileEntity::upgradeRenderRemoveStage() { + if (renderRemoveStage == e_RenderRemoveStageFlaggedAtChunk) { + renderRemoveStage = e_RenderRemoveStageRemove; + } } // 4J Added -void TileEntity::clone(std::shared_ptr tileEntity) -{ - tileEntity->level = this->level; - tileEntity->x = this->x; - tileEntity->y = this->y; - tileEntity->z = this->z; - tileEntity->data = this->data; - tileEntity->tile = this->tile; +void TileEntity::clone(std::shared_ptr tileEntity) { + tileEntity->level = this->level; + tileEntity->x = this->x; + tileEntity->y = this->y; + tileEntity->z = this->z; + tileEntity->data = this->data; + tileEntity->tile = this->tile; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TileEntities/TileEntity.h b/Minecraft.World/Blocks/TileEntities/TileEntity.h index b57d5fc94..ffc49ee65 100644 --- a/Minecraft.World/Blocks/TileEntities/TileEntity.h +++ b/Minecraft.World/Blocks/TileEntities/TileEntity.h @@ -1,6 +1,5 @@ #pragma once - #include "../../Util/HashExtension.h" #include "../../Util/JavaIntHash.h" @@ -8,67 +7,72 @@ class Level; class Packet; class CompoundTag; -typedef TileEntity *(*tileEntityCreateFn)(); +typedef TileEntity* (*tileEntityCreateFn)(); -class TileEntity : public std::enable_shared_from_this -{ +class TileEntity : public std::enable_shared_from_this { public: - static void staticCtor(); - virtual eINSTANCEOF GetType() { return eTYPE_TILEENTITY; } + static void staticCtor(); + virtual eINSTANCEOF GetType() { return eTYPE_TILEENTITY; } + private: - typedef std::unordered_map idToCreateMapType; - typedef std::unordered_map classToIdMapType; - static idToCreateMapType idCreateMap; - static classToIdMapType classIdMap; - static void setId(tileEntityCreateFn createFn, eINSTANCEOF clas, std::wstring id); - bool remove; - unsigned char renderRemoveStage; // 4J added + typedef std::unordered_map + idToCreateMapType; + typedef std::unordered_map + classToIdMapType; + static idToCreateMapType idCreateMap; + static classToIdMapType classIdMap; + static void setId(tileEntityCreateFn createFn, eINSTANCEOF clas, + std::wstring id); + bool remove; + unsigned char renderRemoveStage; // 4J added public: - Level *level; - int x, y, z; + Level* level; + int x, y, z; - // 4J added - enum RenderRemoveStage - { - e_RenderRemoveStageKeep, - e_RenderRemoveStageFlaggedAtChunk, - e_RenderRemoveStageRemove - }; + // 4J added + enum RenderRemoveStage { + e_RenderRemoveStageKeep, + e_RenderRemoveStageFlaggedAtChunk, + e_RenderRemoveStageRemove + }; - int data; - Tile *tile; + int data; + Tile* tile; public: - // 4J Java does not have a ctor, but we need one to do some initialisation of the member variables - TileEntity(); - virtual ~TileEntity() {} + // 4J Java does not have a ctor, but we need one to do some initialisation + // of the member variables + TileEntity(); + virtual ~TileEntity() {} - void setRenderRemoveStage(unsigned char stage); // 4J added - void upgradeRenderRemoveStage(); // 4J added - bool shouldRemoveForRender(); // 4J added + void setRenderRemoveStage(unsigned char stage); // 4J added + void upgradeRenderRemoveStage(); // 4J added + bool shouldRemoveForRender(); // 4J added - Level *getLevel(); - void setLevel(Level *level); - bool hasLevel(); - virtual void load(CompoundTag *tag); - virtual void save(CompoundTag *tag); - virtual void tick(); - static std::shared_ptr loadStatic(CompoundTag *tag); - int getData(); - void setData(int data); - void setChanged(); - double distanceToSqr(double xPlayer, double yPlayer, double zPlayer); - Tile *getTile(); - virtual std::shared_ptr getUpdatePacket(); - virtual bool isRemoved(); - virtual void setRemoved(); - virtual void clearRemoved(); - virtual void triggerEvent(int b0, int b1); - virtual void clearCache(); + Level* getLevel(); + void setLevel(Level* level); + bool hasLevel(); + virtual void load(CompoundTag* tag); + virtual void save(CompoundTag* tag); + virtual void tick(); + static std::shared_ptr loadStatic(CompoundTag* tag); + int getData(); + void setData(int data); + void setChanged(); + double distanceToSqr(double xPlayer, double yPlayer, double zPlayer); + Tile* getTile(); + virtual std::shared_ptr getUpdatePacket(); + virtual bool isRemoved(); + virtual void setRemoved(); + virtual void clearRemoved(); + virtual void triggerEvent(int b0, int b1); + virtual void clearCache(); + + // 4J Added + virtual std::shared_ptr clone() = 0; - // 4J Added - virtual std::shared_ptr clone() = 0; protected: - void clone(std::shared_ptr tileEntity); + void clone(std::shared_ptr tileEntity); }; diff --git a/Minecraft.World/Blocks/TntTile.cpp b/Minecraft.World/Blocks/TntTile.cpp index 76d8fc94a..504ea9069 100644 --- a/Minecraft.World/Blocks/TntTile.cpp +++ b/Minecraft.World/Blocks/TntTile.cpp @@ -8,113 +8,108 @@ #include "TntTile.h" #include "../Util/SoundTypes.h" - -TntTile::TntTile(int id) : Tile(id, Material::explosive) -{ - iconTop = NULL; - iconBottom = NULL; +TntTile::TntTile(int id) : Tile(id, Material::explosive) { + iconTop = NULL; + iconBottom = NULL; } -Icon *TntTile::getTexture(int face, int data) -{ - if (face == Facing::DOWN) return iconBottom; - if (face == Facing::UP) return iconTop; - return icon; +Icon* TntTile::getTexture(int face, int data) { + if (face == Facing::DOWN) return iconBottom; + if (face == Facing::UP) return iconTop; + return icon; } -void TntTile::onPlace(Level *level, int x, int y, int z) -{ - Tile::onPlace(level, x, y, z); - if (level->hasNeighborSignal(x, y, z) && app.GetGameHostOption(eGameHostOption_TNT)) - { +void TntTile::onPlace(Level* level, int x, int y, int z) { + Tile::onPlace(level, x, y, z); + if (level->hasNeighborSignal(x, y, z) && + app.GetGameHostOption(eGameHostOption_TNT)) { destroy(level, x, y, z, EXPLODE_BIT); level->setTile(x, y, z, 0); } } -void TntTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (type > 0 && Tile::tiles[type]->isSignalSource()) - { - if (level->hasNeighborSignal(x, y, z) && app.GetGameHostOption(eGameHostOption_TNT)) - { - destroy(level, x, y, z, EXPLODE_BIT); - level->setTile(x, y, z, 0); - } - } +void TntTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (type > 0 && Tile::tiles[type]->isSignalSource()) { + if (level->hasNeighborSignal(x, y, z) && + app.GetGameHostOption(eGameHostOption_TNT)) { + destroy(level, x, y, z, EXPLODE_BIT); + level->setTile(x, y, z, 0); + } + } } -int TntTile::getResourceCount(Random *random) -{ - return 1; +int TntTile::getResourceCount(Random* random) { return 1; } + +void TntTile::wasExploded(Level* level, int x, int y, int z) { + // 4J - added - don't every create on the client, I think this must be the + // cause of a bug reported in the java version where white tnts are created + // in the network game + if (level->isClientSide) return; + + // 4J - added condition to have finite limit of these + // 4J-JEV: Fix for #90934 - Customer Encountered: TU11: Content: Gameplay: + // TNT blocks are triggered by explosions even though "TNT explodes" option + // is unchecked. + if (level->newPrimedTntAllowed() && + app.GetGameHostOption(eGameHostOption_TNT)) { + std::shared_ptr primed = std::shared_ptr( + new PrimedTnt(level, x + 0.5f, y + 0.5f, z + 0.5f)); + primed->life = + level->random->nextInt(primed->life / 4) + primed->life / 8; + level->addEntity(primed); + } } -void TntTile::wasExploded(Level *level, int x, int y, int z) -{ - // 4J - added - don't every create on the client, I think this must be the cause of a bug reported in the java - // version where white tnts are created in the network game - if (level->isClientSide) return; +void TntTile::destroy(Level* level, int x, int y, int z, int data) { + if (level->isClientSide) return; - // 4J - added condition to have finite limit of these - // 4J-JEV: Fix for #90934 - Customer Encountered: TU11: Content: Gameplay: TNT blocks are triggered by explosions even though "TNT explodes" option is unchecked. - if( level->newPrimedTntAllowed() && app.GetGameHostOption(eGameHostOption_TNT) ) - { - std::shared_ptr primed = std::shared_ptr( new PrimedTnt(level, x + 0.5f, y + 0.5f, z + 0.5f) ); - primed->life = level->random->nextInt(primed->life / 4) + primed->life / 8; - level->addEntity(primed); - } + if ((data & EXPLODE_BIT) == 1) { + // 4J - added condition to have finite limit of these + if (level->newPrimedTntAllowed() && + app.GetGameHostOption(eGameHostOption_TNT)) { + std::shared_ptr tnt = std::shared_ptr( + new PrimedTnt(level, x + 0.5f, y + 0.5f, z + 0.5f)); + level->addEntity(tnt); + level->playSound(tnt, eSoundType_RANDOM_FUSE, 1, 1.0f); + } + } } -void TntTile::destroy(Level *level, int x, int y, int z, int data) +bool TntTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, float clickX, + float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if (level->isClientSide) return; - - if ((data & EXPLODE_BIT) == 1 ) - { - // 4J - added condition to have finite limit of these - if( level->newPrimedTntAllowed() && app.GetGameHostOption(eGameHostOption_TNT) ) - { - std::shared_ptr tnt = std::shared_ptr( new PrimedTnt(level, x + 0.5f, y + 0.5f, z + 0.5f) ); - level->addEntity(tnt); - level->playSound(tnt, eSoundType_RANDOM_FUSE, 1, 1.0f); - } - } + if (soundOnly) return false; + if (player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::flintAndSteel_Id) { + destroy(level, x, y, z, EXPLODE_BIT); + level->setTile(x, y, z, 0); + return true; + } + return Tile::use(level, x, y, z, player, clickedFace, clickX, clickY, + clickZ); } -bool TntTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if (soundOnly) return false; - if (player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::flintAndSteel_Id) - { - destroy(level, x, y, z, EXPLODE_BIT); - level->setTile(x, y, z, 0); - return true; - } - return Tile::use(level, x, y, z, player, clickedFace, clickX, clickY, clickZ); +void TntTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (entity->GetType() == eTYPE_ARROW && !level->isClientSide) { + // 4J Stu - Don't need to cast this + // std::shared_ptr arrow = + // std::dynamic_pointer_cast(entity); + if (entity->isOnFire()) { + destroy(level, x, y, z, EXPLODE_BIT); + level->setTile(x, y, z, 0); + } + } } -void TntTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (entity->GetType() == eTYPE_ARROW && !level->isClientSide) - { - // 4J Stu - Don't need to cast this - //std::shared_ptr arrow = std::dynamic_pointer_cast(entity); - if (entity->isOnFire()) - { - destroy(level, x, y, z, EXPLODE_BIT); - level->setTile(x, y, z, 0); - } - } +std::shared_ptr TntTile::getSilkTouchItemInstance(int data) { + return nullptr; } -std::shared_ptr TntTile::getSilkTouchItemInstance(int data) -{ - return nullptr; -} - -void TntTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"tnt_side"); - iconTop = iconRegister->registerIcon(L"tnt_top"); - iconBottom = iconRegister->registerIcon(L"tnt_bottom"); +void TntTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"tnt_side"); + iconTop = iconRegister->registerIcon(L"tnt_top"); + iconBottom = iconRegister->registerIcon(L"tnt_bottom"); } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TntTile.h b/Minecraft.World/Blocks/TntTile.h index b628e01c4..cc6fadad9 100644 --- a/Minecraft.World/Blocks/TntTile.h +++ b/Minecraft.World/Blocks/TntTile.h @@ -2,30 +2,34 @@ #include "Tile.h" class ChunkRebuildData; -class TntTile : public Tile -{ - friend class ChunkRebuildData; +class TntTile : public Tile { + friend class ChunkRebuildData; + private: - Icon *iconTop; - Icon *iconBottom; + Icon* iconTop; + Icon* iconBottom; + public: - static const int EXPLODE_BIT = 1; - TntTile(int id); + static const int EXPLODE_BIT = 1; + TntTile(int id); - Icon *getTexture(int face, int data); - virtual void onPlace(Level *level, int x, int y, int z); + Icon* getTexture(int face, int data); + virtual void onPlace(Level* level, int x, int y, int z); - void neighborChanged(Level *level, int x, int y, int z, int type); + void neighborChanged(Level* level, int x, int y, int z, int type); - int getResourceCount(Random *random); + int getResourceCount(Random* random); - void wasExploded(Level *level, int x, int y, int z); + void wasExploded(Level* level, int x, int y, int z); - void destroy(Level *level, int x, int y, int z, int data); + void destroy(Level* level, int x, int y, int z, int data); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param - void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - virtual std::shared_ptr getSilkTouchItemInstance(int data); - void registerIcons(IconRegister *iconRegister); + void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + virtual std::shared_ptr getSilkTouchItemInstance(int data); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TopSnowTile.cpp b/Minecraft.World/Blocks/TopSnowTile.cpp index e067cd0a2..aed8bc72f 100644 --- a/Minecraft.World/Blocks/TopSnowTile.cpp +++ b/Minecraft.World/Blocks/TopSnowTile.cpp @@ -10,173 +10,143 @@ const int TopSnowTile::MAX_HEIGHT = 6; -const int TopSnowTile::HEIGHT_MASK = 7; // max 8 steps +const int TopSnowTile::HEIGHT_MASK = 7; // max 8 steps - -TopSnowTile::TopSnowTile(int id) : Tile(id, Material::topSnow, false) -{ - setShape(0, 0, 0, 1, 2 / 16.0f, 1); - setTicking(true); +TopSnowTile::TopSnowTile(int id) : Tile(id, Material::topSnow, false) { + setShape(0, 0, 0, 1, 2 / 16.0f, 1); + setTicking(true); } -void TopSnowTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"snow"); +void TopSnowTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"snow"); } -AABB *TopSnowTile::getAABB(Level *level, int x, int y, int z) -{ - int height = level->getData(x, y, z) & HEIGHT_MASK; - if (height >= (MAX_HEIGHT / 2)) - { - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + .5f, z + tls->zz1); - } - return NULL; +AABB* TopSnowTile::getAABB(Level* level, int x, int y, int z) { + int height = level->getData(x, y, z) & HEIGHT_MASK; + if (height >= (MAX_HEIGHT / 2)) { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, + x + tls->xx1, y + .5f, z + tls->zz1); + } + return NULL; } -float TopSnowTile::getHeight(Level *level, int x, int y, int z) -{ - int height = level->getData(x, y, z) & HEIGHT_MASK; - return 2 * (1 + height) / 16.0f; +float TopSnowTile::getHeight(Level* level, int x, int y, int z) { + int height = level->getData(x, y, z) & HEIGHT_MASK; + return 2 * (1 + height) / 16.0f; } +bool TopSnowTile::blocksLight() { return false; } -bool TopSnowTile::blocksLight() +bool TopSnowTile::isSolidRender(bool isServerLevel) { return false; } + +bool TopSnowTile::isCubeShaped() { return false; } + +void TopSnowTile::updateDefaultShape() { updateShape(0); } + +void TopSnowTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - return false; + updateShape(level->getData(x, y, z)); } - -bool TopSnowTile::isSolidRender(bool isServerLevel) -{ - return false; +void TopSnowTile::updateShape(int data) { + int height = data & HEIGHT_MASK; + float o = 2 * (1 + height) / 16.0f; + setShape(0, 0, 0, 1, o, 1); } - -bool TopSnowTile::isCubeShaped() -{ - return false; +bool TopSnowTile::mayPlace(Level* level, int x, int y, int z) { + int t = level->getTile(x, y - 1, z); + // 4J Stu - Assume when placing that this is the server level and we don't + // care how it's going to be rendered Fix for #9407 - Gameplay: Destroying a + // block of snow on top of trees, removes any adjacent snow. + if (t == 0 || + (t != Tile::leaves_Id && !Tile::tiles[t]->isSolidRender(true))) + return false; + return level->getMaterial(x, y - 1, z)->blocksMotion(); } -void TopSnowTile::updateDefaultShape() -{ - updateShape(0); +void TopSnowTile::neighborChanged(Level* level, int x, int y, int z, int type) { + checkCanSurvive(level, x, y, z); } -void TopSnowTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - updateShape(level->getData(x, y, z)); +bool TopSnowTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!mayPlace(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + return false; + } + return true; } -void TopSnowTile::updateShape(int data) -{ - int height = data & HEIGHT_MASK; - float o = 2 * (1 + height) / 16.0f; - setShape(0, 0, 0, 1, o, 1); +void TopSnowTile::playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data) { + int type = Item::snowBall->id; + float s = 0.7f; + double xo = level->random->nextFloat() * s + (1 - s) * 0.5; + double yo = level->random->nextFloat() * s + (1 - s) * 0.5; + double zo = level->random->nextFloat() * s + (1 - s) * 0.5; + std::shared_ptr item = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance(type, 1, 0)))); + item->throwTime = 10; + level->addEntity(item); + level->setTile(x, y, z, 0); } -bool TopSnowTile::mayPlace(Level *level, int x, int y, int z) -{ - int t = level->getTile(x, y - 1, z); - // 4J Stu - Assume when placing that this is the server level and we don't care how it's going to be rendered - // Fix for #9407 - Gameplay: Destroying a block of snow on top of trees, removes any adjacent snow. - if (t == 0 || (t != Tile::leaves_Id && !Tile::tiles[t]->isSolidRender(true))) return false; - return level->getMaterial(x, y - 1, z)->blocksMotion(); +int TopSnowTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::snowBall->id; } +int TopSnowTile::getResourceCount(Random* random) { return 0; } -void TopSnowTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - checkCanSurvive(level, x, y, z); +void TopSnowTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->getBrightness(LightLayer::Block, x, y, z) > 11) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } } - -bool TopSnowTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!mayPlace(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - return false; - } - return true; +bool TopSnowTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + if (face == 1) return true; + // 4J - don't render faces if neighbouring tiles are also TopSnowTile with + // at least the same height as this one Otherwise we get horrible artifacts + // from the non-manifold geometry created. Fixes bug #8506 + if ((level->getTile(x, y, z) == Tile::topSnow_Id) && (face >= 2)) { + int h0 = level->getData(x, y, z) & HEIGHT_MASK; + int xx = x; + int yy = y; + int zz = z; + // Work out coords of tile who's face we're considering (rather than + // it's neighbour which is passed in here as x,y,z already offsetting by + // the face direction) + switch (face) { + case 2: + zz += 1; + break; + case 3: + zz -= 1; + break; + case 4: + xx += 1; + break; + case 5: + xx -= 1; + break; + default: + break; + } + int h1 = level->getData(xx, yy, zz) & HEIGHT_MASK; + if (h0 >= h1) return false; + } + return Tile::shouldRenderFace(level, x, y, z, face); } - -void TopSnowTile::playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data) -{ - int type = Item::snowBall->id; - float s = 0.7f; - double xo = level->random->nextFloat() * s + (1 - s) * 0.5; - double yo = level->random->nextFloat() * s + (1 - s) * 0.5; - double zo = level->random->nextFloat() * s + (1 - s) * 0.5; - std::shared_ptr item = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr( new ItemInstance(type, 1, 0) ) ) ); - item->throwTime = 10; - level->addEntity(item); - level->setTile(x, y, z, 0); -} - - -int TopSnowTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::snowBall->id; -} - - -int TopSnowTile::getResourceCount(Random *random) -{ - return 0; -} - - -void TopSnowTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->getBrightness(LightLayer::Block, x, y, z) > 11) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } -} - - -bool TopSnowTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - if (face == 1) return true; - // 4J - don't render faces if neighbouring tiles are also TopSnowTile with at least the same height as this one - // Otherwise we get horrible artifacts from the non-manifold geometry created. Fixes bug #8506 - if ( ( level->getTile(x,y,z) == Tile::topSnow_Id ) && ( face >= 2 ) ) - { - int h0 = level->getData(x,y,z) & HEIGHT_MASK; - int xx = x; - int yy = y; - int zz = z; - // Work out coords of tile who's face we're considering (rather than it's neighbour which is passed in here as x,y,z already - // offsetting by the face direction) - switch(face) - { - case 2: - zz += 1; - break; - case 3: - zz -= 1; - break; - case 4: - xx += 1; - break; - case 5: - xx -= 1; - break; - default: - break; - } - int h1 = level->getData(xx,yy,zz) & HEIGHT_MASK; - if( h0 >= h1 ) return false; - } - return Tile::shouldRenderFace(level, x, y, z, face); -} - -bool TopSnowTile::shouldTileTick(Level *level, int x,int y,int z) -{ +bool TopSnowTile::shouldTileTick(Level* level, int x, int y, int z) { return level->getBrightness(LightLayer::Block, x, y, z) > 11; } diff --git a/Minecraft.World/Blocks/TopSnowTile.h b/Minecraft.World/Blocks/TopSnowTile.h index 208fcc2ae..710aab8b8 100644 --- a/Minecraft.World/Blocks/TopSnowTile.h +++ b/Minecraft.World/Blocks/TopSnowTile.h @@ -4,63 +4,69 @@ class Player; -class TopSnowTile : public Tile -{ - friend class Tile; +class TopSnowTile : public Tile { + friend class Tile; + public: - static const int MAX_HEIGHT; - static const int HEIGHT_MASK; + static const int MAX_HEIGHT; + static const int HEIGHT_MASK; protected: - TopSnowTile(int id); + TopSnowTile(int id); public: - void registerIcons(IconRegister *iconRegister); - AABB *getAABB(Level *level, int x, int y, int z); + void registerIcons(IconRegister* iconRegister); + AABB* getAABB(Level* level, int x, int y, int z); public: - static float getHeight(Level *level, int x, int y, int z); + static float getHeight(Level* level, int x, int y, int z); public: - bool blocksLight(); + bool blocksLight(); public: - bool isSolidRender(bool isServerLevel = false); + bool isSolidRender(bool isServerLevel = false); public: - bool isCubeShaped(); + bool isCubeShaped(); public: - void updateDefaultShape(); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + void updateDefaultShape(); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); // 4J added forceData, + // forceEntity param protected: - void updateShape(int data); + void updateShape(int data); public: - bool mayPlace(Level *level, int x, int y, int z); + bool mayPlace(Level* level, int x, int y, int z); public: - void neighborChanged(Level *level, int x, int y, int z, int type); + void neighborChanged(Level* level, int x, int y, int z, int type); private: - bool checkCanSurvive(Level *level, int x, int y, int z); + bool checkCanSurvive(Level* level, int x, int y, int z); public: - void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); + void playerDestroy(Level* level, std::shared_ptr player, int x, + int y, int z, int data); public: - int getResource(int data, Random *random, int playerBonusLevel); + int getResource(int data, Random* random, int playerBonusLevel); public: - int getResourceCount(Random *random); + int getResourceCount(Random* random); public: - void tick(Level *level, int x, int y, int z, Random *random); + void tick(Level* level, int x, int y, int z, Random* random); public: - bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + bool shouldRenderFace(LevelSource* level, int x, int y, int z, int face); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/TorchTile.cpp b/Minecraft.World/Blocks/TorchTile.cpp index 8ab8e7f63..47c0e49d8 100644 --- a/Minecraft.World/Blocks/TorchTile.cpp +++ b/Minecraft.World/Blocks/TorchTile.cpp @@ -4,235 +4,186 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "TorchTile.h" -TorchTile::TorchTile(int id) : Tile(id, Material::decoration, false) -{ - this->setTicking(true); +TorchTile::TorchTile(int id) : Tile(id, Material::decoration, false) { + this->setTicking(true); } -AABB *TorchTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* TorchTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +AABB* TorchTile::getTileAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return Tile::getTileAABB(level, x, y, z); } -AABB *TorchTile::getTileAABB(Level *level, int x, int y, int z) +void TorchTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - updateShape(level, x, y, z); - return Tile::getTileAABB(level, x, y, z); + setShape(level->getData(x, y, z)); } -void TorchTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - setShape(level->getData(x, y, z)); +void TorchTile::setShape(int data) { + int dir = data & 7; + + float r = 0.15f; + if (dir == 1) { + setShape(0, 0.2f, 0.5f - r, r * 2, 0.8f, 0.5f + r); + } else if (dir == 2) { + setShape(1 - r * 2, 0.2f, 0.5f - r, 1, 0.8f, 0.5f + r); + } else if (dir == 3) { + setShape(0.5f - r, 0.2f, 0, 0.5f + r, 0.8f, r * 2); + } else if (dir == 4) { + setShape(0.5f - r, 0.2f, 1 - r * 2, 0.5f + r, 0.8f, 1); + } else { + r = 0.1f; + setShape(0.5f - r, 0.0f, 0.5f - r, 0.5f + r, 0.6f, 0.5f + r); + } } -void TorchTile::setShape(int data) -{ - int dir = data & 7; +bool TorchTile::isSolidRender(bool isServerLevel) { return false; } - float r = 0.15f; - if (dir == 1) - { - setShape(0, 0.2f, 0.5f - r, r * 2, 0.8f, 0.5f + r); - } - else if (dir == 2) - { - setShape(1 - r * 2, 0.2f, 0.5f - r, 1, 0.8f, 0.5f + r); - } - else if (dir == 3) - { - setShape(0.5f - r, 0.2f, 0, 0.5f + r, 0.8f, r * 2); - } - else if (dir == 4) - { - setShape(0.5f - r, 0.2f, 1 - r * 2, 0.5f + r, 0.8f, 1); - } - else - { - r = 0.1f; - setShape(0.5f - r, 0.0f, 0.5f - r, 0.5f + r, 0.6f, 0.5f + r); - } +bool TorchTile::isCubeShaped() { return false; } + +int TorchTile::getRenderShape() { return Tile::SHAPE_TORCH; } + +bool TorchTile::isConnection(Level* level, int x, int y, int z) { + if (level->isTopSolidBlocking(x, y, z)) { + return true; + } + int tile = level->getTile(x, y, z); + if (tile == Tile::fence_Id || tile == Tile::netherFence_Id || + tile == Tile::glass_Id || tile == Tile::cobbleWall_Id) { + return true; + } + return false; } -bool TorchTile::isSolidRender(bool isServerLevel) -{ - return false; +bool TorchTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) { + return true; + } else if (level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) { + return true; + } else if (level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) { + return true; + } else if (level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) { + return true; + } else if (isConnection(level, x, y - 1, z)) { + return true; + } + return false; } -bool TorchTile::isCubeShaped() -{ - return false; +int TorchTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + int dir = itemValue; + + if (face == 1 && isConnection(level, x, y - 1, z)) dir = 5; + if (face == 2 && level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) + dir = 4; + if (face == 3 && level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) + dir = 3; + if (face == 4 && level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) + dir = 2; + if (face == 5 && level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) + dir = 1; + + return dir; } -int TorchTile::getRenderShape() -{ - return Tile::SHAPE_TORCH; +void TorchTile::tick(Level* level, int x, int y, int z, Random* random) { + Tile::tick(level, x, y, z, random); + if (level->getData(x, y, z) == 0) onPlace(level, x, y, z); } -bool TorchTile::isConnection(Level *level, int x, int y, int z) -{ - if (level->isTopSolidBlocking(x, y, z)) - { - return true; - } - int tile = level->getTile(x, y, z); - if (tile == Tile::fence_Id || tile == Tile::netherFence_Id - || tile == Tile::glass_Id || tile == Tile::cobbleWall_Id) - { - return true; - } - return false; +void TorchTile::onPlace(Level* level, int x, int y, int z) { + if (level->getData(x, y, z) == 0) { + if (level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) { + level->setData(x, y, z, 1); + } else if (level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) { + level->setData(x, y, z, 2); + } else if (level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) { + level->setData(x, y, z, 3); + } else if (level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) { + level->setData(x, y, z, 4); + } else if (isConnection(level, x, y - 1, z)) { + level->setData(x, y, z, 5); + } + } + checkCanSurvive(level, x, y, z); } -bool TorchTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) - { - return true; - } - else if (level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) - { - return true; - } - else if (level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) - { - return true; - } - else if (level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) - { - return true; - } - else if (isConnection(level, x, y - 1, z)) - { - return true; - } - return false; +void TorchTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (checkCanSurvive(level, x, y, z)) { + int dir = level->getData(x, y, z); + bool replace = false; + + if (!level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true) && + dir == 1) + replace = true; + if (!level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true) && + dir == 2) + replace = true; + if (!level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true) && + dir == 3) + replace = true; + if (!level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true) && + dir == 4) + replace = true; + if (!isConnection(level, x, y - 1, z) && dir == 5) replace = true; + + if (replace) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } + } } -int TorchTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - int dir = itemValue; - - if (face == 1 && isConnection(level, x, y - 1, z)) dir = 5; - if (face == 2 && level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) dir = 4; - if (face == 3 && level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) dir = 3; - if (face == 4 && level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) dir = 2; - if (face == 5 && level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) dir = 1; - - return dir; +bool TorchTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!mayPlace(level, x, y, z)) { + if (level->getTile(x, y, z) == id) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + } + return false; + } + return true; } -void TorchTile::tick(Level *level, int x, int y, int z, Random *random) -{ - Tile::tick(level, x, y, z, random); - if (level->getData(x, y, z) == 0) onPlace(level, x, y, z); +HitResult* TorchTile::clip(Level* level, int x, int y, int z, Vec3* a, + Vec3* b) { + setShape(level->getData(x, y, z)); + + return Tile::clip(level, x, y, z, a, b); } -void TorchTile::onPlace(Level *level, int x, int y, int z) -{ - if(level->getData(x,y,z) == 0) - { - if (level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) - { - level->setData(x, y, z, 1); - } - else if (level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) - { - level->setData(x, y, z, 2); - } - else if (level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) - { - level->setData(x, y, z, 3); - } - else if (level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) - { - level->setData(x, y, z, 4); - } - else if (isConnection(level, x, y - 1, z)) - { - level->setData(x, y, z, 5); - } - } - checkCanSurvive(level, x, y, z); +void TorchTile::animateTick(Level* level, int xt, int yt, int zt, + Random* random) { + int dir = level->getData(xt, yt, zt); + double x = xt + 0.5f; + double y = yt + 0.7f; + double z = zt + 0.5f; + double h = 0.22f; + double r = 0.27f; + if (dir == 1) { + level->addParticle(eParticleType_smoke, x - r, y + h, z, 0, 0, 0); + level->addParticle(eParticleType_flame, x - r, y + h, z, 0, 0, 0); + } else if (dir == 2) { + level->addParticle(eParticleType_smoke, x + r, y + h, z, 0, 0, 0); + level->addParticle(eParticleType_flame, x + r, y + h, z, 0, 0, 0); + } else if (dir == 3) { + level->addParticle(eParticleType_smoke, x, y + h, z - r, 0, 0, 0); + level->addParticle(eParticleType_flame, x, y + h, z - r, 0, 0, 0); + } else if (dir == 4) { + level->addParticle(eParticleType_smoke, x, y + h, z + r, 0, 0, 0); + level->addParticle(eParticleType_flame, x, y + h, z + r, 0, 0, 0); + } else { + level->addParticle(eParticleType_smoke, x, y, z, 0, 0, 0); + level->addParticle(eParticleType_flame, x, y, z, 0, 0, 0); + } } -void TorchTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (checkCanSurvive(level, x, y, z)) - { - int dir = level->getData(x, y, z); - bool replace = false; - - if (!level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true) && dir == 1) replace = true; - if (!level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true) && dir == 2) replace = true; - if (!level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true) && dir == 3) replace = true; - if (!level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true) && dir == 4) replace = true; - if (!isConnection(level, x, y - 1, z) && dir == 5) replace = true; - - if (replace) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } - } -} - -bool TorchTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!mayPlace(level, x, y, z)) - { - if (level->getTile(x, y, z) == id) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - } - return false; - } - return true; -} - -HitResult *TorchTile::clip(Level *level, int x, int y, int z, Vec3 *a, Vec3 *b) -{ - setShape(level->getData(x, y, z)); - - return Tile::clip(level, x, y, z, a, b); -} - -void TorchTile::animateTick(Level *level, int xt, int yt, int zt, Random *random) -{ - int dir = level->getData(xt, yt, zt); - double x = xt + 0.5f; - double y = yt + 0.7f; - double z = zt + 0.5f; - double h = 0.22f; - double r = 0.27f; - if (dir == 1) - { - level->addParticle(eParticleType_smoke, x - r, y + h, z, 0, 0, 0); - level->addParticle(eParticleType_flame, x - r, y + h, z, 0, 0, 0); - } - else if (dir == 2) - { - level->addParticle(eParticleType_smoke, x + r, y + h, z, 0, 0, 0); - level->addParticle(eParticleType_flame, x + r, y + h, z, 0, 0, 0); - } - else if (dir == 3) - { - level->addParticle(eParticleType_smoke, x, y + h, z - r, 0, 0, 0); - level->addParticle(eParticleType_flame, x, y + h, z - r, 0, 0, 0); - } - else if (dir == 4) - { - level->addParticle(eParticleType_smoke, x, y + h, z + r, 0, 0, 0); - level->addParticle(eParticleType_flame, x, y + h, z + r, 0, 0, 0); - } - else - { - level->addParticle(eParticleType_smoke, x, y, z, 0, 0, 0); - level->addParticle(eParticleType_flame, x, y, z, 0, 0, 0); - } -} - -bool TorchTile::shouldTileTick(Level *level, int x,int y,int z) -{ - return level->getData(x, y, z) == 0; +bool TorchTile::shouldTileTick(Level* level, int x, int y, int z) { + return level->getData(x, y, z) == 0; } diff --git a/Minecraft.World/Blocks/TorchTile.h b/Minecraft.World/Blocks/TorchTile.h index 16f7d6067..9f258f6a7 100644 --- a/Minecraft.World/Blocks/TorchTile.h +++ b/Minecraft.World/Blocks/TorchTile.h @@ -5,32 +5,43 @@ class Random; class HitResult; -class TorchTile : public Tile -{ - friend class Tile; +class TorchTile : public Tile { + friend class Tile; + protected: - TorchTile(int id); + TorchTile(int id); + public: - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual AABB *getTileAABB(Level *level, int x, int y, int z); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - using Tile::setShape; - virtual void setShape(int data); + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual AABB* getTileAABB(Level* level, int x, int y, int z); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + using Tile::setShape; + virtual void setShape(int data); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); virtual int getRenderShape(); - bool isConnection(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual void onPlace(Level *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); + bool isConnection(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual void onPlace(Level* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + private: - virtual bool checkCanSurvive(Level *level, int x, int y, int z); + virtual bool checkCanSurvive(Level* level, int x, int y, int z); + public: - virtual HitResult *clip(Level *level, int x, int y, int z, Vec3 *a, Vec3 *b); - virtual void animateTick(Level *level, int xt, int yt, int zt, Random *random); - - // 4J Added so we can check before we try to add a tile to the tick list if it's actually going to do seomthing - virtual bool shouldTileTick(Level *level, int x,int y,int z); + virtual HitResult* clip(Level* level, int x, int y, int z, Vec3* a, + Vec3* b); + virtual void animateTick(Level* level, int xt, int yt, int zt, + Random* random); + + // 4J Added so we can check before we try to add a tile to the tick list if + // it's actually going to do seomthing + virtual bool shouldTileTick(Level* level, int x, int y, int z); }; diff --git a/Minecraft.World/Blocks/TransparentTile.cpp b/Minecraft.World/Blocks/TransparentTile.cpp index ece0de542..44fddb081 100644 --- a/Minecraft.World/Blocks/TransparentTile.cpp +++ b/Minecraft.World/Blocks/TransparentTile.cpp @@ -2,24 +2,19 @@ #include "../Headers/net.minecraft.world.level.h" #include "TransparentTile.h" -TransparentTile::TransparentTile(int id, Material *material, bool allowSame, bool isSolidRender) : Tile(id, material,isSolidRender) -{ - this->allowSame = allowSame; +TransparentTile::TransparentTile(int id, Material* material, bool allowSame, + bool isSolidRender) + : Tile(id, material, isSolidRender) { + this->allowSame = allowSame; } -bool TransparentTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool TransparentTile::isSolidRender(bool isServerLevel) { return false; } -bool TransparentTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ +bool TransparentTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { int id = level->getTile(x, y, z); if (!allowSame && id == this->id) return false; return Tile::shouldRenderFace(level, x, y, z, face); } -bool TransparentTile::blocksLight() -{ - return false; -} \ No newline at end of file +bool TransparentTile::blocksLight() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TransparentTile.h b/Minecraft.World/Blocks/TransparentTile.h index 0601be4b8..fb1c9d15a 100644 --- a/Minecraft.World/Blocks/TransparentTile.h +++ b/Minecraft.World/Blocks/TransparentTile.h @@ -1,14 +1,17 @@ #pragma once #include "Tile.h" -class TransparentTile : public Tile -{ +class TransparentTile : public Tile { protected: - bool allowSame; + bool allowSame; + protected: - TransparentTile(int id, Material *material, bool allowSame, bool isSolidRender = false); + TransparentTile(int id, Material* material, bool allowSame, + bool isSolidRender = false); + public: - virtual bool isSolidRender(bool isServerLevel = false); - virtual bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); + virtual bool isSolidRender(bool isServerLevel = false); + virtual bool shouldRenderFace(LevelSource* level, int x, int y, int z, + int face); virtual bool blocksLight(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TrapDoorTile.cpp b/Minecraft.World/Blocks/TrapDoorTile.cpp index 969d77092..48610d388 100644 --- a/Minecraft.World/Blocks/TrapDoorTile.cpp +++ b/Minecraft.World/Blocks/TrapDoorTile.cpp @@ -5,205 +5,170 @@ #include "../Headers/net.minecraft.h" #include "TrapDoorTile.h" - -TrapDoorTile::TrapDoorTile(int id, Material *material) : Tile(id, material, false) -{ - float r = 0.5f; - float h = 1.0f; - setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); +TrapDoorTile::TrapDoorTile(int id, Material* material) + : Tile(id, material, false) { + float r = 0.5f; + float h = 1.0f; + setShape(0.5f - r, 0, 0.5f - r, 0.5f + r, h, 0.5f + r); } -bool TrapDoorTile::blocksLight() -{ - return false; +bool TrapDoorTile::blocksLight() { return false; } + +bool TrapDoorTile::isSolidRender(bool isServerLevel) { return false; } + +bool TrapDoorTile::isCubeShaped() { return false; } + +bool TrapDoorTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return !isOpen(level->getData(x, y, z)); } +int TrapDoorTile::getRenderShape() { return Tile::SHAPE_BLOCK; } -bool TrapDoorTile::isSolidRender(bool isServerLevel) -{ - return false; +AABB* TrapDoorTile::getTileAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return Tile::getTileAABB(level, x, y, z); } - -bool TrapDoorTile::isCubeShaped() -{ - return false; +AABB* TrapDoorTile::getAABB(Level* level, int x, int y, int z) { + updateShape(level, x, y, z); + return Tile::getAABB(level, x, y, z); } -bool TrapDoorTile::isPathfindable(LevelSource *level, int x, int y, int z) +void TrapDoorTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - return !isOpen(level->getData(x, y, z)); + setShape(level->getData(x, y, z)); } -int TrapDoorTile::getRenderShape() -{ - return Tile::SHAPE_BLOCK; +void TrapDoorTile::updateDefaultShape() { + float r = 3 / 16.0f; + setShape(0, 0.5f - r / 2, 0, 1, 0.5f + r / 2, 1); } - -AABB *TrapDoorTile::getTileAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return Tile::getTileAABB(level, x, y, z); +void TrapDoorTile::setShape(int data) { + float r = 3 / 16.0f; + Tile::setShape(0, 0, 0, 1, r, 1); + if (isOpen(data)) { + if ((data & 3) == 0) setShape(0, 0, 1 - r, 1, 1, 1); + if ((data & 3) == 1) setShape(0, 0, 0, 1, 1, r); + if ((data & 3) == 2) setShape(1 - r, 0, 0, 1, 1, 1); + if ((data & 3) == 3) setShape(0, 0, 0, r, 1, 1); + } } - -AABB *TrapDoorTile::getAABB(Level *level, int x, int y, int z) -{ - updateShape(level, x, y, z); - return Tile::getAABB(level, x, y, z); -} - - -void TrapDoorTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param -{ - setShape(level->getData(x, y, z)); -} - - -void TrapDoorTile::updateDefaultShape() -{ - float r = 3 / 16.0f; - setShape(0, 0.5f - r / 2, 0, 1, 0.5f + r / 2, 1); -} - - -void TrapDoorTile::setShape(int data) -{ - - float r = 3 / 16.0f; - Tile::setShape(0, 0, 0, 1, r, 1); - if (isOpen(data)) - { - if ((data & 3) == 0) setShape(0, 0, 1 - r, 1, 1, 1); - if ((data & 3) == 1) setShape(0, 0, 0, 1, 1, r); - if ((data & 3) == 2) setShape(1 - r, 0, 0, 1, 1, 1); - if ((data & 3) == 3) setShape(0, 0, 0, r, 1, 1); - } -} - - -void TrapDoorTile::attack(Level *level, int x, int y, int z, std::shared_ptr player) -{ - use(level, x, y, z, player, 0, 0, 0, 0); +void TrapDoorTile::attack(Level* level, int x, int y, int z, + std::shared_ptr player) { + use(level, x, y, z, player, 0, 0, 0, 0); } // 4J-PB - Adding a TestUse for tooltip display -bool TrapDoorTile::TestUse() +bool TrapDoorTile::TestUse() { return true; } + +bool TrapDoorTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - return true; + if (material == Material::metal) return true; + + if (soundOnly) { + // 4J - added - just do enough to play the sound + level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + return false; + } + + int dir = level->getData(x, y, z); + level->setData(x, y, z, dir ^ 4); + + level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + return true; } -bool TrapDoorTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param -{ - if (material == Material::metal) return true; +void TrapDoorTile::setOpen(Level* level, int x, int y, int z, bool shouldOpen) { + int dir = level->getData(x, y, z); - if (soundOnly) - { - // 4J - added - just do enough to play the sound - level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - return false; - } + bool wasOpen = (dir & 4) > 0; + if (wasOpen == shouldOpen) return; - int dir = level->getData(x, y, z); - level->setData(x, y, z, dir ^ 4); + level->setData(x, y, z, dir ^ 4); - level->levelEvent(player, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); - return true; + level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); } +void TrapDoorTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (level->isClientSide) return; -void TrapDoorTile::setOpen(Level *level, int x, int y, int z, bool shouldOpen) -{ - int dir = level->getData(x, y, z); + int data = level->getData(x, y, z); + int xt = x; + int zt = z; + if ((data & 3) == 0) zt++; + if ((data & 3) == 1) zt--; + if ((data & 3) == 2) xt++; + if ((data & 3) == 3) xt--; - bool wasOpen = (dir & 4) > 0; - if (wasOpen == shouldOpen) return; + if (!attachesTo(level->getTile(xt, y, zt))) { + level->setTile(x, y, z, 0); + spawnResources(level, x, y, z, data, 0); + } - level->setData(x, y, z, dir ^ 4); - - level->levelEvent(nullptr, LevelEvent::SOUND_OPEN_DOOR, x, y, z, 0); + bool signal = level->hasNeighborSignal(x, y, z); + if (signal || ((type > 0 && Tile::tiles[type]->isSignalSource()))) { + setOpen(level, x, y, z, signal); + } } -void TrapDoorTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (level->isClientSide) return; - - int data = level->getData(x, y, z); - int xt = x; - int zt = z; - if ((data & 3) == 0) zt++; - if ((data & 3) == 1) zt--; - if ((data & 3) == 2) xt++; - if ((data & 3) == 3) xt--; - - - if (!attachesTo(level->getTile(xt, y, zt))) - { - level->setTile(x, y, z, 0); - spawnResources(level, x, y, z, data, 0); - } - - bool signal = level->hasNeighborSignal(x, y, z); - if( signal || ((type > 0 && Tile::tiles[type]->isSignalSource())) ) - { - setOpen(level, x, y, z, signal); - } +HitResult* TrapDoorTile::clip(Level* level, int xt, int yt, int zt, Vec3* a, + Vec3* b) { + updateShape(level, xt, yt, zt); + return Tile::clip(level, xt, yt, zt, a, b); } -HitResult *TrapDoorTile::clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b) -{ - updateShape(level, xt, yt, zt); - return Tile::clip(level, xt, yt, zt, a, b); +int TrapDoorTile::getDir(int dir) { + if ((dir & 4) == 0) { + return ((dir - 1) & 3); + } else { + return (dir & 3); + } } -int TrapDoorTile::getDir(int dir) -{ - if ((dir & 4) == 0) - { - return ((dir - 1) & 3); - } - else - { - return (dir & 3); - } +int TrapDoorTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + int dir = 0; + if (face == 2) dir = 0; + if (face == 3) dir = 1; + if (face == 4) dir = 2; + if (face == 5) dir = 3; + if (face != Facing::UP && face != Facing::DOWN && clickY > 0.5f) + dir |= TOP_MASK; + return dir; } -int TrapDoorTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - int dir = 0; - if (face == 2) dir = 0; - if (face == 3) dir = 1; - if (face == 4) dir = 2; - if (face == 5) dir = 3; - if (face != Facing::UP && face != Facing::DOWN && clickY > 0.5f) dir |= TOP_MASK; - return dir; +bool TrapDoorTile::mayPlace(Level* level, int x, int y, int z, int face) { + if (face == 0) return false; + if (face == 1) return false; + if (face == 2) z++; + if (face == 3) z--; + if (face == 4) x++; + if (face == 5) x--; + + return attachesTo(level->getTile(x, y, z)); } -bool TrapDoorTile::mayPlace(Level *level, int x, int y, int z, int face) -{ - if (face == 0) return false; - if (face == 1) return false; - if (face == 2) z++; - if (face == 3) z--; - if (face == 4) x++; - if (face == 5) x--; +bool TrapDoorTile::isOpen(int data) { return (data & 4) != 0; } - return attachesTo(level->getTile(x, y, z)); -} - -bool TrapDoorTile::isOpen(int data) -{ - return (data & 4) != 0; -} - -bool TrapDoorTile::attachesTo(int id) -{ - if (id <= 0) - { - return false; - } - Tile *tile = Tile::tiles[id]; - - return tile != NULL && (tile->material->isSolidBlocking() && tile->isCubeShaped()) || tile == Tile::lightGem || (dynamic_cast(tile) != NULL) || (dynamic_cast(tile) != NULL); +bool TrapDoorTile::attachesTo(int id) { + if (id <= 0) { + return false; + } + Tile* tile = Tile::tiles[id]; + + return tile != NULL && + (tile->material->isSolidBlocking() && tile->isCubeShaped()) || + tile == Tile::lightGem || + (dynamic_cast(tile) != NULL) || + (dynamic_cast(tile) != NULL); } diff --git a/Minecraft.World/Blocks/TrapDoorTile.h b/Minecraft.World/Blocks/TrapDoorTile.h index 5f6a52e7d..f2e978759 100644 --- a/Minecraft.World/Blocks/TrapDoorTile.h +++ b/Minecraft.World/Blocks/TrapDoorTile.h @@ -5,83 +5,90 @@ class Player; class HitResult; -class TrapDoorTile : public Tile -{ - friend class Tile; +class TrapDoorTile : public Tile { + friend class Tile; + private: - static const int TOP_MASK = 0x8; + static const int TOP_MASK = 0x8; protected: - TrapDoorTile(int id, Material *material); + TrapDoorTile(int id, Material* material); -/* - * public int getTexture(int face, int data) { if (face == 0 || face == 1) - * return tex; int dir = getDir(data); if ((dir == 0 || dir == 2) ^ (face <= 3)) - * { return tex; } int tt = (dir / 2 + ((face & 1) ^ dir)); tt += ((data & 4) / - * 4); int texture = tex - (data & 8) * 2; if ((tt & 1) != 0) { texture = - * -texture; } // if (getDir(data)==0 // tt-=((face+data&3)&1)^((data&4)>>2); - * return texture; } - */ + /* + * public int getTexture(int face, int data) { if (face == 0 || face == 1) + * return tex; int dir = getDir(data); if ((dir == 0 || dir == 2) ^ (face <= + * 3)) { return tex; } int tt = (dir / 2 + ((face & 1) ^ dir)); tt += ((data + * & 4) / 4); int texture = tex - (data & 8) * 2; if ((tt & 1) != 0) { + * texture = -texture; } // if (getDir(data)==0 // + * tt-=((face+data&3)&1)^((data&4)>>2); return texture; } + */ public: - bool blocksLight(); + bool blocksLight(); public: - bool isSolidRender(bool isServerLevel = false); + bool isSolidRender(bool isServerLevel = false); public: - bool isCubeShaped(); - bool isPathfindable(LevelSource *level, int x, int y, int z); + bool isCubeShaped(); + bool isPathfindable(LevelSource* level, int x, int y, int z); public: - int getRenderShape(); + int getRenderShape(); public: - AABB *getTileAABB(Level *level, int x, int y, int z); + AABB* getTileAABB(Level* level, int x, int y, int z); public: - AABB *getAABB(Level *level, int x, int y, int z); + AABB* getAABB(Level* level, int x, int y, int z); public: - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); // 4J added forceData, + // forceEntity param public: - void updateDefaultShape(); + void updateDefaultShape(); public: - using Tile::setShape; - void setShape(int data); + using Tile::setShape; + void setShape(int data); public: - void attack(Level *level, int x, int y, int z, std::shared_ptr player); + void attack(Level* level, int x, int y, int z, + std::shared_ptr player); public: - virtual bool TestUse(); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + virtual bool TestUse(); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param public: - void setOpen(Level *level, int x, int y, int z, bool shouldOpen); - + void setOpen(Level* level, int x, int y, int z, bool shouldOpen); public: - void neighborChanged(Level *level, int x, int y, int z, int type); - + void neighborChanged(Level* level, int x, int y, int z, int type); public: - HitResult *clip(Level *level, int xt, int yt, int zt, Vec3 *a, Vec3 *b); + HitResult* clip(Level* level, int xt, int yt, int zt, Vec3* a, Vec3* b); public: - int getDir(int dir); + int getDir(int dir); public: - int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); + int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, int face, + float clickX, float clickY, float clickZ, + int itemValue); public: - bool mayPlace(Level *level, int x, int y, int z, int face); + bool mayPlace(Level* level, int x, int y, int z, int face); public: - static bool isOpen(int data); + static bool isOpen(int data); private: - static bool attachesTo(int id); + static bool attachesTo(int id); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TreeTile.cpp b/Minecraft.World/Blocks/TreeTile.cpp index 0bcbd01b4..37cb956e1 100644 --- a/Minecraft.World/Blocks/TreeTile.cpp +++ b/Minecraft.World/Blocks/TreeTile.cpp @@ -7,135 +7,111 @@ #include "TreeTile.h" -const unsigned int TreeTile::TREE_NAMES[TREE_NAMES_LENGTH] = { IDS_TILE_LOG_OAK, - IDS_TILE_LOG_SPRUCE, - IDS_TILE_LOG_BIRCH, - IDS_TILE_LOG_JUNGLE - }; +const unsigned int TreeTile::TREE_NAMES[TREE_NAMES_LENGTH] = { + IDS_TILE_LOG_OAK, IDS_TILE_LOG_SPRUCE, IDS_TILE_LOG_BIRCH, + IDS_TILE_LOG_JUNGLE}; -const std::wstring TreeTile::TREE_TEXTURES[] = {L"tree_side", L"tree_spruce", L"tree_birch", L"tree_jungle"}; +const std::wstring TreeTile::TREE_TEXTURES[] = {L"tree_side", L"tree_spruce", + L"tree_birch", L"tree_jungle"}; -TreeTile::TreeTile(int id) : Tile(id, Material::wood) -{ - icons = NULL; - iconTop = NULL; +TreeTile::TreeTile(int id) : Tile(id, Material::wood) { + icons = NULL; + iconTop = NULL; } -int TreeTile::getRenderShape() -{ - return Tile::SHAPE_TREE; +int TreeTile::getRenderShape() { return Tile::SHAPE_TREE; } + +int TreeTile::getResourceCount(Random* random) { return 1; } + +int TreeTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::treeTrunk_Id; } -int TreeTile::getResourceCount(Random *random) -{ - return 1; +void TreeTile::onRemove(Level* level, int x, int y, int z, int id, int data) { + int r = LeafTile::REQUIRED_WOOD_RANGE; + int r2 = r + 1; + + if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, z + r2)) { + for (int xo = -r; xo <= r; xo++) + for (int yo = -r; yo <= r; yo++) + for (int zo = -r; zo <= r; zo++) { + int t = level->getTile(x + xo, y + yo, z + zo); + if (t == Tile::leaves_Id) { + int currentData = + level->getData(x + xo, y + yo, z + zo); + if ((currentData & LeafTile::UPDATE_LEAF_BIT) == 0) { + level->setDataNoUpdate( + x + xo, y + yo, z + zo, + currentData | LeafTile::UPDATE_LEAF_BIT); + } + } + } + } } -int TreeTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::treeTrunk_Id; +void TreeTile::setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by) { + int type = level->getData(x, y, z) & MASK_TYPE; + int dir = PistonBaseTile::getNewFacing( + level, x, y, z, std::dynamic_pointer_cast(by)); + int facing = 0; + + switch (dir) { + case Facing::NORTH: + case Facing::SOUTH: + facing = FACING_Z; + break; + case Facing::EAST: + case Facing::WEST: + facing = FACING_X; + break; + case Facing::UP: + case Facing::DOWN: + facing = FACING_Y; + break; + } + + level->setData(x, y, z, type | facing); } -void TreeTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - int r = LeafTile::REQUIRED_WOOD_RANGE; - int r2 = r + 1; +Icon* TreeTile::getTexture(int face, int data) { + int dir = data & MASK_FACING; + int type = data & MASK_TYPE; - if (level->hasChunksAt(x - r2, y - r2, z - r2, x + r2, y + r2, z + r2)) - { - for (int xo = -r; xo <= r; xo++) - for (int yo = -r; yo <= r; yo++) - for (int zo = -r; zo <= r; zo++) - { - int t = level->getTile(x + xo, y + yo, z + zo); - if (t == Tile::leaves_Id) - { - int currentData = level->getData(x + xo, y + yo, z + zo); - if ((currentData & LeafTile::UPDATE_LEAF_BIT) == 0) - { - level->setDataNoUpdate(x + xo, y + yo, z + zo, currentData | LeafTile::UPDATE_LEAF_BIT); - } - } - } - } + if (dir == FACING_Y && (face == Facing::UP || face == Facing::DOWN)) { + return iconTop; + } else if (dir == FACING_X && + (face == Facing::EAST || face == Facing::WEST)) { + return iconTop; + } else if (dir == FACING_Z && + (face == Facing::NORTH || face == Facing::SOUTH)) { + return iconTop; + } + + return icons[type]; } -void TreeTile::setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by) -{ - int type = level->getData(x, y, z) & MASK_TYPE; - int dir = PistonBaseTile::getNewFacing(level, x, y, z, std::dynamic_pointer_cast(by)); - int facing = 0; - - switch (dir) - { - case Facing::NORTH: - case Facing::SOUTH: - facing = FACING_Z; - break; - case Facing::EAST: - case Facing::WEST: - facing = FACING_X; - break; - case Facing::UP: - case Facing::DOWN: - facing = FACING_Y; - break; - } - - level->setData(x, y, z, type | facing); +unsigned int TreeTile::getDescriptionId(int iData /*= -1*/) { + int type = iData & MASK_TYPE; + if (type < 0) type = 0; + return TreeTile::TREE_NAMES[type]; } -Icon *TreeTile::getTexture(int face, int data) -{ - int dir = data & MASK_FACING; - int type = data & MASK_TYPE; +int TreeTile::getSpawnResourcesAuxValue(int data) { return data & MASK_TYPE; } - if (dir == FACING_Y && (face == Facing::UP || face == Facing::DOWN)) - { - return iconTop; - } - else if (dir == FACING_X && (face == Facing::EAST || face == Facing::WEST)) - { - return iconTop; - } - else if (dir == FACING_Z && (face == Facing::NORTH || face == Facing::SOUTH)) - { - return iconTop; - } +int TreeTile::getWoodType(int data) { return data & MASK_TYPE; } - return icons[type]; +std::shared_ptr TreeTile::getSilkTouchItemInstance(int data) { + // fix to avoid getting silktouched sideways logs + return std::shared_ptr( + new ItemInstance(id, 1, getWoodType(data))); } -unsigned int TreeTile::getDescriptionId(int iData /*= -1*/) -{ - int type = iData & MASK_TYPE; - if(type < 0 ) type = 0; - return TreeTile::TREE_NAMES[type]; -} +void TreeTile::registerIcons(IconRegister* iconRegister) { + iconTop = iconRegister->registerIcon(L"tree_top"); + icons = new Icon*[TREE_NAMES_LENGTH]; -int TreeTile::getSpawnResourcesAuxValue(int data) -{ - return data & MASK_TYPE; -} - -int TreeTile::getWoodType(int data) -{ - return data & MASK_TYPE; -} - -std::shared_ptr TreeTile::getSilkTouchItemInstance(int data) -{ - // fix to avoid getting silktouched sideways logs - return std::shared_ptr(new ItemInstance(id, 1, getWoodType(data))); -} - -void TreeTile::registerIcons(IconRegister *iconRegister) -{ - iconTop = iconRegister->registerIcon(L"tree_top"); - icons = new Icon*[TREE_NAMES_LENGTH]; - - for (int i = 0; i < TREE_NAMES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TREE_TEXTURES[i]); - } + for (int i = 0; i < TREE_NAMES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TREE_TEXTURES[i]); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/TreeTile.h b/Minecraft.World/Blocks/TreeTile.h index 295f3f82c..62783f917 100644 --- a/Minecraft.World/Blocks/TreeTile.h +++ b/Minecraft.World/Blocks/TreeTile.h @@ -5,51 +5,51 @@ class ChunkRebuildData; class Player; -class TreeTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class TreeTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; + public: - static const int DARK_TRUNK = 1; - static const int BIRCH_TRUNK = 2; - static const int JUNGLE_TRUNK = 3; + static const int DARK_TRUNK = 1; + static const int BIRCH_TRUNK = 2; + static const int JUNGLE_TRUNK = 3; - static const int MASK_TYPE = 0x3; - static const int MASK_FACING = 0xC; - static const int FACING_Y = 0 << 2; - static const int FACING_X = 1 << 2; - static const int FACING_Z = 2 << 2; + static const int MASK_TYPE = 0x3; + static const int MASK_FACING = 0xC; + static const int FACING_Y = 0 << 2; + static const int FACING_X = 1 << 2; + static const int FACING_Z = 2 << 2; - static const int TREE_NAMES_LENGTH = 4; + static const int TREE_NAMES_LENGTH = 4; + static const unsigned int TREE_NAMES[TREE_NAMES_LENGTH]; - static const unsigned int TREE_NAMES[TREE_NAMES_LENGTH]; - - static const std::wstring TREE_TEXTURES[]; + static const std::wstring TREE_TEXTURES[]; private: - Icon **icons; - Icon *iconTop; + Icon** icons; + Icon* iconTop; protected: - TreeTile(int id); + TreeTile(int id); public: - virtual int getRenderShape(); - virtual int getResourceCount(Random *random); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual void setPlacedBy(Level *level, int x, int y, int z, std::shared_ptr by); - virtual Icon *getTexture(int face, int data); - virtual unsigned int getDescriptionId(int iData = -1); + virtual int getRenderShape(); + virtual int getResourceCount(Random* random); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual void setPlacedBy(Level* level, int x, int y, int z, + std::shared_ptr by); + virtual Icon* getTexture(int face, int data); + virtual unsigned int getDescriptionId(int iData = -1); protected: - int getSpawnResourcesAuxValue(int data); + int getSpawnResourcesAuxValue(int data); public: - static int getWoodType(int data); - void registerIcons(IconRegister *iconRegister); + static int getWoodType(int data); + void registerIcons(IconRegister* iconRegister); protected: - virtual std::shared_ptr getSilkTouchItemInstance(int data); + virtual std::shared_ptr getSilkTouchItemInstance(int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/TripWireSourceTile.cpp b/Minecraft.World/Blocks/TripWireSourceTile.cpp index 45e7f2d17..12c5bb6bf 100644 --- a/Minecraft.World/Blocks/TripWireSourceTile.cpp +++ b/Minecraft.World/Blocks/TripWireSourceTile.cpp @@ -4,356 +4,315 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "TripWireSourceTile.h" -TripWireSourceTile::TripWireSourceTile(int id) : Tile(id, Material::decoration, false) -{ - this->setTicking(true); +TripWireSourceTile::TripWireSourceTile(int id) + : Tile(id, Material::decoration, false) { + this->setTicking(true); } -AABB *TripWireSourceTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* TripWireSourceTile::getAABB(Level* level, int x, int y, int z) { + return NULL; } -bool TripWireSourceTile::blocksLight() -{ - return false; +bool TripWireSourceTile::blocksLight() { return false; } + +bool TripWireSourceTile::isSolidRender(bool isServerLevel) { return false; } + +bool TripWireSourceTile::isCubeShaped() { return false; } + +int TripWireSourceTile::getRenderShape() { return Tile::SHAPE_TRIPWIRE_SOURCE; } + +int TripWireSourceTile::getTickDelay(Level* level) { return 10; } + +bool TripWireSourceTile::mayPlace(Level* level, int x, int y, int z, int face) { + if (face == Facing::NORTH && level->isSolidBlockingTile(x, y, z + 1)) + return true; + if (face == Facing::SOUTH && level->isSolidBlockingTile(x, y, z - 1)) + return true; + if (face == Facing::WEST && level->isSolidBlockingTile(x + 1, y, z)) + return true; + if (face == Facing::EAST && level->isSolidBlockingTile(x - 1, y, z)) + return true; + return false; } -bool TripWireSourceTile::isSolidRender(bool isServerLevel) -{ - return false; +bool TripWireSourceTile::mayPlace(Level* level, int x, int y, int z) { + if (level->isSolidBlockingTile(x - 1, y, z)) { + return true; + } else if (level->isSolidBlockingTile(x + 1, y, z)) { + return true; + } else if (level->isSolidBlockingTile(x, y, z - 1)) { + return true; + } else if (level->isSolidBlockingTile(x, y, z + 1)) { + return true; + } + return false; } -bool TripWireSourceTile::isCubeShaped() -{ - return false; +int TripWireSourceTile::getPlacedOnFaceDataValue(Level* level, int x, int y, + int z, int face, float clickX, + float clickY, float clickZ, + int itemValue) { + int dir = 0; + + if (face == Facing::NORTH && + level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) + dir = Direction::NORTH; + if (face == Facing::SOUTH && + level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) + dir = Direction::SOUTH; + if (face == Facing::WEST && + level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) + dir = Direction::WEST; + if (face == Facing::EAST && + level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) + dir = Direction::EAST; + + return dir; } -int TripWireSourceTile::getRenderShape() -{ - return Tile::SHAPE_TRIPWIRE_SOURCE; +void TripWireSourceTile::finalizePlacement(Level* level, int x, int y, int z, + int data) { + calculateState(level, x, y, z, id, data, false, -1, 0); } -int TripWireSourceTile::getTickDelay(Level *level) -{ - return 10; +void TripWireSourceTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + if (type == this->id) return; + if (checkCanSurvive(level, x, y, z)) { + int data = level->getData(x, y, z); + int dir = data & MASK_DIR; + bool replace = false; + + if (!level->isSolidBlockingTile(x - 1, y, z) && dir == Direction::EAST) + replace = true; + if (!level->isSolidBlockingTile(x + 1, y, z) && dir == Direction::WEST) + replace = true; + if (!level->isSolidBlockingTile(x, y, z - 1) && dir == Direction::SOUTH) + replace = true; + if (!level->isSolidBlockingTile(x, y, z + 1) && dir == Direction::NORTH) + replace = true; + + if (replace) { + this->spawnResources(level, x, y, z, data, 0); + level->setTile(x, y, z, 0); + } + } } -bool TripWireSourceTile::mayPlace(Level *level, int x, int y, int z, int face) -{ - if (face == Facing::NORTH && level->isSolidBlockingTile(x, y, z + 1)) return true; - if (face == Facing::SOUTH && level->isSolidBlockingTile(x, y, z - 1)) return true; - if (face == Facing::WEST && level->isSolidBlockingTile(x + 1, y, z)) return true; - if (face == Facing::EAST && level->isSolidBlockingTile(x - 1, y, z)) return true; - return false; +void TripWireSourceTile::calculateState( + Level* level, int x, int y, int z, int id, int data, bool canUpdate, + /*4J-Jev, these parameters only used with 'updateSource' -->*/ + int wireSource, int wireSourceData) { + int dir = data & MASK_DIR; + bool wasAttached = (data & MASK_ATTACHED) == MASK_ATTACHED; + bool wasPowered = (data & MASK_POWERED) == MASK_POWERED; + bool attached = + id == Tile::tripWireSource_Id; // id is only != TripwireSource_id when + // 'onRemove' + bool powered = false; + bool suspended = !level->isTopSolidBlocking(x, y - 1, z); + int stepX = Direction::STEP_X[dir]; + int stepZ = Direction::STEP_Z[dir]; + int receiverPos = 0; + int wiresData[WIRE_DIST_MAX]; + + // Loop over each tile down the wire, from this tile, to the expected + // opposing src tile. + for (int i = 1; i < WIRE_DIST_MAX; i++) { + int xx = x + stepX * i; + int zz = z + stepZ * i; + int tile = level->getTile(xx, y, zz); + + if (tile == Tile::tripWireSource_Id) { + int otherData = level->getData(xx, y, zz); + + if ((otherData & MASK_DIR) == Direction::DIRECTION_OPPOSITE[dir]) { + receiverPos = i; + } + + break; + } else if (tile == Tile::tripWire_Id || + i == wireSource) // wireSource is the wiretile that caused + // an 'updateSource' + { + int wireData = + i == wireSource ? wireSourceData : level->getData(xx, y, zz); + bool wireArmed = (wireData & TripWireTile::MASK_DISARMED) != + TripWireTile::MASK_DISARMED; + bool wirePowered = (wireData & TripWireTile::MASK_POWERED) == + TripWireTile::MASK_POWERED; + bool wireSuspended = (wireData & TripWireTile::MASK_SUSPENDED) == + TripWireTile::MASK_SUSPENDED; + attached &= wireSuspended == suspended; + powered |= wireArmed && wirePowered; + + wiresData[i] = wireData; + + if (i == wireSource) { + level->addToTickNextTick(x, y, z, id, getTickDelay(level)); + attached &= wireArmed; + } + } else // Non-wire or src tile encountered. + { + wiresData[i] = -1; + attached = false; + } + } + + attached &= receiverPos > WIRE_DIST_MIN; + powered &= attached; + int state = (attached ? MASK_ATTACHED : 0) | (powered ? MASK_POWERED : 0); + data = dir | state; + + if (receiverPos > 0) // If a receiver is detected update it's state and + // notify it's neighbours. + { + int xx = x + stepX * receiverPos; + int zz = z + stepZ * receiverPos; + int opposite = Direction::DIRECTION_OPPOSITE[dir]; + level->setData(xx, y, zz, opposite | state); + notifyNeighbors(level, xx, y, zz, opposite); + + playSound(level, xx, y, zz, attached, powered, wasAttached, wasPowered); + } + + playSound(level, x, y, z, attached, powered, wasAttached, wasPowered); + + if (id > 0) // ie. it isn't being removed. + { + level->setData(x, y, z, data); + if (canUpdate) notifyNeighbors(level, x, y, z, dir); + } + + if (wasAttached != attached) { + for (int i = 1; i < receiverPos; i++) { + int xx = x + stepX * i; + int zz = z + stepZ * i; + int wireData = wiresData[i]; + if (wireData < 0) continue; + + if (attached) { + wireData |= TripWireTile::MASK_ATTACHED; + } else { + wireData &= ~TripWireTile::MASK_ATTACHED; + } + + level->setData(xx, y, zz, wireData); + } + } } -bool TripWireSourceTile::mayPlace(Level *level, int x, int y, int z) -{ - if (level->isSolidBlockingTile(x - 1, y, z)) - { - return true; - } - else if (level->isSolidBlockingTile(x + 1, y, z)) - { - return true; - } - else if (level->isSolidBlockingTile(x, y, z - 1)) - { - return true; - } - else if (level->isSolidBlockingTile(x, y, z + 1)) - { - return true; - } - return false; +void TripWireSourceTile::tick(Level* level, int x, int y, int z, + Random* random) { + calculateState(level, x, y, z, id, level->getData(x, y, z), true, -1, 0); } -int TripWireSourceTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - int dir = 0; - - if (face == Facing::NORTH && level->isSolidBlockingTileInLoadedChunk(x, y, z + 1, true)) dir = Direction::NORTH; - if (face == Facing::SOUTH && level->isSolidBlockingTileInLoadedChunk(x, y, z - 1, true)) dir = Direction::SOUTH; - if (face == Facing::WEST && level->isSolidBlockingTileInLoadedChunk(x + 1, y, z, true)) dir = Direction::WEST; - if (face == Facing::EAST && level->isSolidBlockingTileInLoadedChunk(x - 1, y, z, true)) dir = Direction::EAST; - - return dir; +void TripWireSourceTile::playSound(Level* level, int x, int y, int z, + bool attached, bool powered, + bool wasAttached, bool wasPowered) { + if (powered && !wasPowered) { + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, + 0.4f, 0.6f); + } else if (!powered && wasPowered) { + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, + 0.4f, 0.5f); + } else if (attached && !wasAttached) { + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, + 0.4f, 0.7f); + } else if (!attached && wasAttached) { + level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_BOW_HIT, + 0.4f, + 1.2f / (level->random->nextFloat() * 0.2f + 0.9f)); + } } -void TripWireSourceTile::finalizePlacement(Level *level, int x, int y, int z, int data) -{ - calculateState(level, x, y, z, id, data, false, -1, 0); +void TripWireSourceTile::notifyNeighbors(Level* level, int x, int y, int z, + int dir) { + level->updateNeighborsAt(x, y, z, this->id); + + if (dir == Direction::EAST) { + level->updateNeighborsAt(x - 1, y, z, this->id); + } else if (dir == Direction::WEST) { + level->updateNeighborsAt(x + 1, y, z, this->id); + } else if (dir == Direction::SOUTH) { + level->updateNeighborsAt(x, y, z - 1, this->id); + } else if (dir == Direction::NORTH) { + level->updateNeighborsAt(x, y, z + 1, this->id); + } } -void TripWireSourceTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (type == this->id) return; - if (checkCanSurvive(level, x, y, z)) - { - int data = level->getData(x, y, z); - int dir = data & MASK_DIR; - bool replace = false; +bool TripWireSourceTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!mayPlace(level, x, y, z)) { + this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + return false; + } - if (!level->isSolidBlockingTile(x - 1, y, z) && dir == Direction::EAST) replace = true; - if (!level->isSolidBlockingTile(x + 1, y, z) && dir == Direction::WEST) replace = true; - if (!level->isSolidBlockingTile(x, y, z - 1) && dir == Direction::SOUTH) replace = true; - if (!level->isSolidBlockingTile(x, y, z + 1) && dir == Direction::NORTH) replace = true; - - if (replace) - { - this->spawnResources(level, x, y, z, data, 0); - level->setTile(x, y, z, 0); - } - } + return true; } -void TripWireSourceTile::calculateState(Level *level, int x, int y, int z, int id, int data, bool canUpdate, - /*4J-Jev, these parameters only used with 'updateSource' -->*/ int wireSource, int wireSourceData) -{ +void TripWireSourceTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + int dir = level->getData(x, y, z) & MASK_DIR; + float r = 3 / 16.0f; - - int dir = data & MASK_DIR; - bool wasAttached = (data & MASK_ATTACHED) == MASK_ATTACHED; - bool wasPowered = (data & MASK_POWERED) == MASK_POWERED; - bool attached = id == Tile::tripWireSource_Id; // id is only != TripwireSource_id when 'onRemove' - bool powered = false; - bool suspended = !level->isTopSolidBlocking(x, y - 1, z); - int stepX = Direction::STEP_X[dir]; - int stepZ = Direction::STEP_Z[dir]; - int receiverPos = 0; - int wiresData[WIRE_DIST_MAX]; - - // Loop over each tile down the wire, from this tile, to the expected opposing src tile. - for (int i = 1; i < WIRE_DIST_MAX; i++) - { - int xx = x + stepX * i; - int zz = z + stepZ * i; - int tile = level->getTile(xx, y, zz); - - if (tile == Tile::tripWireSource_Id) - { - int otherData = level->getData(xx, y, zz); - - if ((otherData & MASK_DIR) == Direction::DIRECTION_OPPOSITE[dir]) - { - receiverPos = i; - } - - break; - } - else if (tile == Tile::tripWire_Id || i == wireSource) // wireSource is the wiretile that caused an 'updateSource' - { - int wireData = i == wireSource ? wireSourceData : level->getData(xx, y, zz); - bool wireArmed = (wireData & TripWireTile::MASK_DISARMED) != TripWireTile::MASK_DISARMED; - bool wirePowered = (wireData & TripWireTile::MASK_POWERED) == TripWireTile::MASK_POWERED; - bool wireSuspended = (wireData & TripWireTile::MASK_SUSPENDED) == TripWireTile::MASK_SUSPENDED; - attached &= wireSuspended == suspended; - powered |= wireArmed && wirePowered; - - wiresData[i] = wireData; - - if (i == wireSource) - { - level->addToTickNextTick(x, y, z, id, getTickDelay(level)); - attached &= wireArmed; - } - } - else // Non-wire or src tile encountered. - { - wiresData[i] = -1; - attached = false; - } - } - - attached &= receiverPos > WIRE_DIST_MIN; - powered &= attached; - int state = (attached ? MASK_ATTACHED : 0) | (powered ? MASK_POWERED : 0); - data = dir | state; - - if (receiverPos > 0) // If a receiver is detected update it's state and notify it's neighbours. - { - int xx = x + stepX * receiverPos; - int zz = z + stepZ * receiverPos; - int opposite = Direction::DIRECTION_OPPOSITE[dir]; - level->setData(xx, y, zz, opposite | state); - notifyNeighbors(level, xx, y, zz, opposite); - - playSound(level, xx, y, zz, attached, powered, wasAttached, wasPowered); - } - - playSound(level, x, y, z, attached, powered, wasAttached, wasPowered); - - if (id > 0) // ie. it isn't being removed. - { - level->setData(x, y, z, data); - if (canUpdate) notifyNeighbors(level, x, y, z, dir); - } - - if (wasAttached != attached) - { - for (int i = 1; i < receiverPos; i++) - { - int xx = x + stepX * i; - int zz = z + stepZ * i; - int wireData = wiresData[i]; - if (wireData < 0) continue; - - if (attached) - { - wireData |= TripWireTile::MASK_ATTACHED; - } - else - { - wireData &= ~TripWireTile::MASK_ATTACHED; - } - - - level->setData(xx, y, zz, wireData); - } - } + if (dir == Direction::EAST) { + setShape(0, 0.2f, 0.5f - r, r * 2, 0.8f, 0.5f + r); + } else if (dir == Direction::WEST) { + setShape(1 - r * 2, 0.2f, 0.5f - r, 1, 0.8f, 0.5f + r); + } else if (dir == Direction::SOUTH) { + setShape(0.5f - r, 0.2f, 0, 0.5f + r, 0.8f, r * 2); + } else if (dir == Direction::NORTH) { + setShape(0.5f - r, 0.2f, 1 - r * 2, 0.5f + r, 0.8f, 1); + } } -void TripWireSourceTile::tick(Level *level, int x, int y, int z, Random *random) -{ - calculateState(level, x, y, z, id, level->getData(x, y, z), true, -1, 0); +void TripWireSourceTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + bool attached = (data & MASK_ATTACHED) == MASK_ATTACHED; + bool powered = (data & MASK_POWERED) == MASK_POWERED; + + if (attached || powered) { + calculateState(level, x, y, z, 0, data, false, -1, 0); // Disconnect + // the other end. + } + + if (powered) { + level->updateNeighborsAt(x, y, z, this->id); + int dir = data & MASK_DIR; + + if (dir == Direction::EAST) { + level->updateNeighborsAt(x - 1, y, z, this->id); + } else if (dir == Direction::WEST) { + level->updateNeighborsAt(x + 1, y, z, this->id); + } else if (dir == Direction::SOUTH) { + level->updateNeighborsAt(x, y, z - 1, this->id); + } else if (dir == Direction::NORTH) { + level->updateNeighborsAt(x, y, z + 1, this->id); + } + } + + Tile::onRemove(level, x, y, z, id, data); } -void TripWireSourceTile::playSound(Level *level, int x, int y, int z, bool attached, bool powered, bool wasAttached, bool wasPowered) -{ - if (powered && !wasPowered) - { - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, 0.4f, 0.6f); - } - else if (!powered && wasPowered) - { - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, 0.4f, 0.5f); - } - else if (attached && !wasAttached) - { - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_CLICK, 0.4f, 0.7f); - } - else if (!attached && wasAttached) - { - level->playSound(x + 0.5, y + 0.1, z + 0.5, eSoundType_RANDOM_BOW_HIT, 0.4f, 1.2f / (level->random->nextFloat() * 0.2f + 0.9f)); - } +bool TripWireSourceTile::getSignal(LevelSource* level, int x, int y, int z, + int dir) { + return (level->getData(x, y, z) & MASK_POWERED) == MASK_POWERED; } -void TripWireSourceTile::notifyNeighbors(Level *level, int x, int y, int z, int dir) -{ - level->updateNeighborsAt(x, y, z, this->id); +bool TripWireSourceTile::getDirectSignal(Level* level, int x, int y, int z, + int dir) { + int data = level->getData(x, y, z); + if ((data & MASK_POWERED) != MASK_POWERED) return false; + int myDir = data & MASK_DIR; - if (dir == Direction::EAST) - { - level->updateNeighborsAt(x - 1, y, z, this->id); - } - else if (dir == Direction::WEST) - { - level->updateNeighborsAt(x + 1, y, z, this->id); - } - else if (dir == Direction::SOUTH) - { - level->updateNeighborsAt(x, y, z - 1, this->id); - } - else if (dir == Direction::NORTH) - { - level->updateNeighborsAt(x, y, z + 1, this->id); - } + if (myDir == Direction::NORTH && dir == Facing::NORTH) return true; + if (myDir == Direction::SOUTH && dir == Facing::SOUTH) return true; + if (myDir == Direction::WEST && dir == Facing::WEST) return true; + if (myDir == Direction::EAST && dir == Facing::EAST) return true; + + return false; } -bool TripWireSourceTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!mayPlace(level, x, y, z)) - { - this->spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - return false; - } - - return true; -} - -void TripWireSourceTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - int dir = level->getData(x, y, z) & MASK_DIR; - float r = 3 / 16.0f; - - if (dir == Direction::EAST) - { - setShape(0, 0.2f, 0.5f - r, r * 2, 0.8f, 0.5f + r); - } - else if (dir == Direction::WEST) - { - setShape(1 - r * 2, 0.2f, 0.5f - r, 1, 0.8f, 0.5f + r); - } - else if (dir == Direction::SOUTH) - { - setShape(0.5f - r, 0.2f, 0, 0.5f + r, 0.8f, r * 2); - } - else if (dir == Direction::NORTH) - { - setShape(0.5f - r, 0.2f, 1 - r * 2, 0.5f + r, 0.8f, 1); - } -} - -void TripWireSourceTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - bool attached = (data & MASK_ATTACHED) == MASK_ATTACHED; - bool powered = (data & MASK_POWERED) == MASK_POWERED; - - if (attached || powered) - { - calculateState(level, x, y, z, 0, data, false, -1, 0); // Disconnect - // the other end. - } - - if (powered) - { - level->updateNeighborsAt(x, y, z, this->id); - int dir = data & MASK_DIR; - - if (dir == Direction::EAST) - { - level->updateNeighborsAt(x - 1, y, z, this->id); - } - else if (dir == Direction::WEST) - { - level->updateNeighborsAt(x + 1, y, z, this->id); - } - else if (dir == Direction::SOUTH) - { - level->updateNeighborsAt(x, y, z - 1, this->id); - } - else if (dir == Direction::NORTH) - { - level->updateNeighborsAt(x, y, z + 1, this->id); - } - } - - Tile::onRemove(level, x, y, z, id, data); -} - -bool TripWireSourceTile::getSignal(LevelSource *level, int x, int y, int z, int dir) -{ - return (level->getData(x, y, z) & MASK_POWERED) == MASK_POWERED; -} - -bool TripWireSourceTile::getDirectSignal(Level *level, int x, int y, int z, int dir) -{ - int data = level->getData(x, y, z); - if ((data & MASK_POWERED) != MASK_POWERED) return false; - int myDir = data & MASK_DIR; - - if (myDir == Direction::NORTH && dir == Facing::NORTH) return true; - if (myDir == Direction::SOUTH && dir == Facing::SOUTH) return true; - if (myDir == Direction::WEST && dir == Facing::WEST) return true; - if (myDir == Direction::EAST && dir == Facing::EAST) return true; - - - return false; -} - -bool TripWireSourceTile::isSignalSource() -{ - return true; -} +bool TripWireSourceTile::isSignalSource() { return true; } diff --git a/Minecraft.World/Blocks/TripWireSourceTile.h b/Minecraft.World/Blocks/TripWireSourceTile.h index a5a26ad1e..81dc1d571 100644 --- a/Minecraft.World/Blocks/TripWireSourceTile.h +++ b/Minecraft.World/Blocks/TripWireSourceTile.h @@ -2,42 +2,48 @@ #include "Tile.h" -class TripWireSourceTile : public Tile -{ +class TripWireSourceTile : public Tile { public: - using Tile::getTickDelay; + using Tile::getTickDelay; - static const int MASK_DIR = 0x3; - static const int MASK_ATTACHED = 0x4; - static const int MASK_POWERED = 0x8; - static const int WIRE_DIST_MIN = 1; - static const int WIRE_DIST_MAX = 2 + 40; // 2 hooks + x string + static const int MASK_DIR = 0x3; + static const int MASK_ATTACHED = 0x4; + static const int MASK_POWERED = 0x8; + static const int WIRE_DIST_MIN = 1; + static const int WIRE_DIST_MAX = 2 + 40; // 2 hooks + x string - TripWireSourceTile(int id); + TripWireSourceTile(int id); - AABB *getAABB(Level *level, int x, int y, int z); - bool blocksLight(); - bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); - int getRenderShape(); - int getTickDelay(Level *level); - bool mayPlace(Level *level, int x, int y, int z, int face); - bool mayPlace(Level *level, int x, int y, int z); - int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - void finalizePlacement(Level *level, int x, int y, int z, int data); - void neighborChanged(Level *level, int x, int y, int z, int type); - void calculateState(Level *level, int x, int y, int z, int id, int data, bool canUpdate, int wireSource, int wireSourceData); - void tick(Level *level, int x, int y, int z, Random *random); + AABB* getAABB(Level* level, int x, int y, int z); + bool blocksLight(); + bool isSolidRender(bool isServerLevel = false); + bool isCubeShaped(); + int getRenderShape(); + int getTickDelay(Level* level); + bool mayPlace(Level* level, int x, int y, int z, int face); + bool mayPlace(Level* level, int x, int y, int z); + int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, int face, + float clickX, float clickY, float clickZ, + int itemValue); + void finalizePlacement(Level* level, int x, int y, int z, int data); + void neighborChanged(Level* level, int x, int y, int z, int type); + void calculateState(Level* level, int x, int y, int z, int id, int data, + bool canUpdate, int wireSource, int wireSourceData); + void tick(Level* level, int x, int y, int z, Random* random); private: - void playSound(Level *level, int x, int y, int z, bool attached, bool powered, bool wasAttached, bool wasPowered); - void notifyNeighbors(Level *level, int x, int y, int z, int dir); - bool checkCanSurvive(Level *level, int x, int y, int z); + void playSound(Level* level, int x, int y, int z, bool attached, + bool powered, bool wasAttached, bool wasPowered); + void notifyNeighbors(Level* level, int x, int y, int z, int dir); + bool checkCanSurvive(Level* level, int x, int y, int z); public: - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); - void onRemove(Level *level, int x, int y, int z, int id, int data); - virtual bool getSignal(LevelSource *level, int x, int y, int z, int dir); - virtual bool getDirectSignal(Level *level, int x, int y, int z, int dir); - bool isSignalSource(); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + void onRemove(Level* level, int x, int y, int z, int id, int data); + virtual bool getSignal(LevelSource* level, int x, int y, int z, int dir); + virtual bool getDirectSignal(Level* level, int x, int y, int z, int dir); + bool isSignalSource(); }; diff --git a/Minecraft.World/Blocks/TripWireTile.cpp b/Minecraft.World/Blocks/TripWireTile.cpp index 54916674f..51477fed7 100644 --- a/Minecraft.World/Blocks/TripWireTile.cpp +++ b/Minecraft.World/Blocks/TripWireTile.cpp @@ -5,217 +5,178 @@ #include "../Headers/net.minecraft.world.phys.h" #include "TripWireTile.h" -TripWireTile::TripWireTile(int id) : Tile(id, Material::decoration, false) -{ - setShape(0, 0, 0, 1, 2.5f / 16.0f, 1); - this->setTicking(true); +TripWireTile::TripWireTile(int id) : Tile(id, Material::decoration, false) { + setShape(0, 0, 0, 1, 2.5f / 16.0f, 1); + this->setTicking(true); } -int TripWireTile::getTickDelay(Level *level) -{ - // 4J: Increased (x2); quick update caused problems with shared - // data between client and server. - return 20; // 10; +int TripWireTile::getTickDelay(Level* level) { + // 4J: Increased (x2); quick update caused problems with shared + // data between client and server. + return 20; // 10; } -AABB *TripWireTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; +AABB* TripWireTile::getAABB(Level* level, int x, int y, int z) { return NULL; } + +bool TripWireTile::blocksLight() { return false; } + +bool TripWireTile::isSolidRender(bool isServerLevel) { return false; } + +bool TripWireTile::isCubeShaped() { return false; } + +int TripWireTile::getRenderLayer() { return 1; } + +int TripWireTile::getRenderShape() { return Tile::SHAPE_TRIPWIRE; } + +int TripWireTile::getResource(int data, Random* random, int playerBonusLevel) { + return Item::string_Id; } -bool TripWireTile::blocksLight() -{ - return false; +int TripWireTile::cloneTileId(Level* level, int x, int y, int z) { + return Item::string_Id; } -bool TripWireTile::isSolidRender(bool isServerLevel) -{ - return false; +void TripWireTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + int data = level->getData(x, y, z); + bool wasSuspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; + bool isSuspended = !level->isTopSolidBlocking(x, y - 1, z); + if (wasSuspended != isSuspended) { + spawnResources(level, x, y, z, data, 0); + level->setTile(x, y, z, 0); + } } -bool TripWireTile::isCubeShaped() -{ - return false; +void TripWireTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + int data = level->getData(x, y, z); + bool attached = (data & MASK_ATTACHED) == MASK_ATTACHED; + bool suspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; + + if (!suspended) { + setShape(0, 0, 0, 1, 1.5f / 16.0f, 1); + } else if (!attached) { + setShape(0, 0, 0, 1, 8.0f / 16.0f, 1); + } else { + setShape(0, 1.0f / 16.0f, 0, 1, 2.5f / 16.0f, 1); + } } -int TripWireTile::getRenderLayer() -{ - return 1; +void TripWireTile::onPlace(Level* level, int x, int y, int z) { + int data = level->isTopSolidBlocking(x, y - 1, z) ? 0 : MASK_SUSPENDED; + level->setData(x, y, z, data); + updateSource(level, x, y, z, data); } -int TripWireTile::getRenderShape() -{ - return Tile::SHAPE_TRIPWIRE; +void TripWireTile::onRemove(Level* level, int x, int y, int z, int id, + int data) { + updateSource(level, x, y, z, data | MASK_POWERED); } -int TripWireTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Item::string_Id; +void TripWireTile::playerWillDestroy(Level* level, int x, int y, int z, + int data, std::shared_ptr player) { + if (level->isClientSide) return; + + if (player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::shears_Id) { + level->setData(x, y, z, data | MASK_DISARMED); + } } -int TripWireTile::cloneTileId(Level *level, int x, int y, int z) -{ - return Item::string_Id; +void TripWireTile::updateSource(Level* level, int x, int y, int z, int data) { + for (int dir = 0; dir < 2; dir++) { + for (int i = 1; i < TripWireSourceTile::WIRE_DIST_MAX; i++) { + int xx = x + Direction::STEP_X[dir] * i; + int zz = z + Direction::STEP_Z[dir] * i; + int tile = level->getTile(xx, y, zz); + + if (tile == Tile::tripWireSource_Id) { + int sourceDir = + level->getData(xx, y, zz) & TripWireSourceTile::MASK_DIR; + + if (sourceDir == Direction::DIRECTION_OPPOSITE[dir]) { + Tile::tripWireSource->calculateState( + level, xx, y, zz, tile, level->getData(xx, y, zz), true, + i, data); + } + + break; + } else if (tile != Tile::tripWire_Id) { + break; + } + } + } } -void TripWireTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - int data = level->getData(x, y, z); - bool wasSuspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; - bool isSuspended = !level->isTopSolidBlocking(x, y - 1, z); - if (wasSuspended != isSuspended) - { - spawnResources(level, x, y, z, data, 0); - level->setTile(x, y, z, 0); - } +void TripWireTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + if (level->isClientSide) return; + + if ((level->getData(x, y, z) & MASK_POWERED) == MASK_POWERED) return; + + checkPressed(level, x, y, z); } -void TripWireTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - int data = level->getData(x, y, z); - bool attached = (data & MASK_ATTACHED) == MASK_ATTACHED; - bool suspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; +void TripWireTile::tick(Level* level, int x, int y, int z, Random* random) { + if (level->isClientSide) return; - if (!suspended) - { - setShape(0, 0, 0, 1, 1.5f / 16.0f, 1); - } - else if (!attached) - { - setShape(0, 0, 0, 1, 8.0f / 16.0f, 1); - } - else - { - setShape(0, 1.0f / 16.0f, 0, 1, 2.5f / 16.0f, 1); - } + if ((level->getData(x, y, z) & MASK_POWERED) != MASK_POWERED) return; + + checkPressed(level, x, y, z); } -void TripWireTile::onPlace(Level *level, int x, int y, int z) -{ - int data = level->isTopSolidBlocking(x, y - 1, z) ? 0 : MASK_SUSPENDED; - level->setData(x, y, z, data); - updateSource(level, x, y, z, data); +void TripWireTile::checkPressed(Level* level, int x, int y, int z) { + int data = level->getData(x, y, z); + bool wasPressed = (data & MASK_POWERED) == MASK_POWERED; + bool shouldBePressed = false; + + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + std::vector >* entities = level->getEntities( + nullptr, AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, + x + tls->xx1, y + tls->yy1, z + tls->zz1)); + if (!entities->empty()) { + shouldBePressed = true; + } + + if (shouldBePressed && !wasPressed) { + data |= MASK_POWERED; + } + + if (!shouldBePressed && wasPressed) { + data &= ~MASK_POWERED; + } + + if (shouldBePressed != wasPressed) { + level->setData(x, y, z, data); + updateSource(level, x, y, z, data); + } + + if (shouldBePressed) { + level->addToTickNextTick(x, y, z, id, getTickDelay(level)); + } } -void TripWireTile::onRemove(Level *level, int x, int y, int z, int id, int data) -{ - updateSource(level, x, y, z, data | MASK_POWERED); -} - -void TripWireTile::playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player) -{ - if (level->isClientSide) return; - - if (player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::shears_Id) - { - level->setData(x, y, z, data | MASK_DISARMED); - } -} - -void TripWireTile::updateSource(Level *level, int x, int y, int z, int data) -{ - for (int dir = 0; dir < 2; dir++) - { - for (int i = 1; i < TripWireSourceTile::WIRE_DIST_MAX; i++) - { - int xx = x + Direction::STEP_X[dir] * i; - int zz = z + Direction::STEP_Z[dir] * i; - int tile = level->getTile(xx, y, zz); - - if (tile == Tile::tripWireSource_Id) - { - int sourceDir = level->getData(xx, y, zz) & TripWireSourceTile::MASK_DIR; - - if (sourceDir == Direction::DIRECTION_OPPOSITE[dir]) - { - Tile::tripWireSource->calculateState(level, xx, y, zz, tile, level->getData(xx, y, zz), true, i, data); - } - - break; - } - else if (tile != Tile::tripWire_Id) - { - break; - } - } - } -} - -void TripWireTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - if (level->isClientSide) return; - - if ((level->getData(x, y, z) & MASK_POWERED) == MASK_POWERED) return; - - checkPressed(level, x, y, z); -} - -void TripWireTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (level->isClientSide) return; - - if ((level->getData(x, y, z) & MASK_POWERED) != MASK_POWERED) return; - - checkPressed(level, x, y, z); -} - -void TripWireTile::checkPressed(Level *level, int x, int y, int z) -{ - int data = level->getData(x, y, z); - bool wasPressed = (data & MASK_POWERED) == MASK_POWERED; - bool shouldBePressed = false; - - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - std::vector > *entities = level->getEntities(nullptr, AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1)); - if (!entities->empty()) - { - shouldBePressed = true; - } - - if (shouldBePressed && !wasPressed) - { - data |= MASK_POWERED; - } - - if (!shouldBePressed && wasPressed) - { - data &= ~MASK_POWERED; - } - - if (shouldBePressed != wasPressed) - { - level->setData(x, y, z, data); - updateSource(level, x, y, z, data); - } - - if (shouldBePressed) - { - level->addToTickNextTick(x, y, z, id, getTickDelay(level)); - } -} - -bool TripWireTile::shouldConnectTo(LevelSource *level, int x, int y, int z, int data, int dir) -{ - int tx = x + Direction::STEP_X[dir]; - int ty = y; - int tz = z + Direction::STEP_Z[dir]; - int t = level->getTile(tx, ty, tz); - bool suspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; - - if (t == Tile::tripWireSource_Id) - { - int otherData = level->getData(tx, ty, tz); - int facing = otherData & TripWireSourceTile::MASK_DIR; - - return facing == Direction::DIRECTION_OPPOSITE[dir]; - } - - if (t == Tile::tripWire_Id) - { - int otherData = level->getData(tx, ty, tz); - bool otherSuspended = (otherData & MASK_SUSPENDED) == MASK_SUSPENDED; - return suspended == otherSuspended; - } - - return false; +bool TripWireTile::shouldConnectTo(LevelSource* level, int x, int y, int z, + int data, int dir) { + int tx = x + Direction::STEP_X[dir]; + int ty = y; + int tz = z + Direction::STEP_Z[dir]; + int t = level->getTile(tx, ty, tz); + bool suspended = (data & MASK_SUSPENDED) == MASK_SUSPENDED; + + if (t == Tile::tripWireSource_Id) { + int otherData = level->getData(tx, ty, tz); + int facing = otherData & TripWireSourceTile::MASK_DIR; + + return facing == Direction::DIRECTION_OPPOSITE[dir]; + } + + if (t == Tile::tripWire_Id) { + int otherData = level->getData(tx, ty, tz); + bool otherSuspended = (otherData & MASK_SUSPENDED) == MASK_SUSPENDED; + return suspended == otherSuspended; + } + + return false; } diff --git a/Minecraft.World/Blocks/TripWireTile.h b/Minecraft.World/Blocks/TripWireTile.h index 664541c53..f6c7becef 100644 --- a/Minecraft.World/Blocks/TripWireTile.h +++ b/Minecraft.World/Blocks/TripWireTile.h @@ -2,42 +2,48 @@ #include "Tile.h" -class TripWireTile : public Tile -{ - using Tile::getTickDelay; +class TripWireTile : public Tile { + using Tile::getTickDelay; + public: - static const int MASK_POWERED = 0x1; - static const int MASK_SUSPENDED = 0x2; - static const int MASK_ATTACHED = 0x4; - static const int MASK_DISARMED = 0x8; + static const int MASK_POWERED = 0x1; + static const int MASK_SUSPENDED = 0x2; + static const int MASK_ATTACHED = 0x4; + static const int MASK_DISARMED = 0x8; - TripWireTile(int id); + TripWireTile(int id); - int getTickDelay(Level *level); - AABB *getAABB(Level *level, int x, int y, int z); - bool blocksLight(); - bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); - int getRenderLayer(); - int getRenderShape(); - int getResource(int data, Random *random, int playerBonusLevel); - int cloneTileId(Level *level, int x, int y, int z); - void neighborChanged(Level *level, int x, int y, int z, int type); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); - void onPlace(Level *level, int x, int y, int z); - void onRemove(Level *level, int x, int y, int z, int id, int data); - void playerWillDestroy(Level *level, int x, int y, int z, int data, std::shared_ptr player); + int getTickDelay(Level* level); + AABB* getAABB(Level* level, int x, int y, int z); + bool blocksLight(); + bool isSolidRender(bool isServerLevel = false); + bool isCubeShaped(); + int getRenderLayer(); + int getRenderShape(); + int getResource(int data, Random* random, int playerBonusLevel); + int cloneTileId(Level* level, int x, int y, int z); + void neighborChanged(Level* level, int x, int y, int z, int type); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + void onPlace(Level* level, int x, int y, int z); + void onRemove(Level* level, int x, int y, int z, int id, int data); + void playerWillDestroy(Level* level, int x, int y, int z, int data, + std::shared_ptr player); private: - void updateSource(Level *level, int x, int y, int z, int data); + void updateSource(Level* level, int x, int y, int z, int data); public: - void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - void tick(Level *level, int x, int y, int z, Random *random); + void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); + void tick(Level* level, int x, int y, int z, Random* random); private: - void checkPressed(Level *level, int x, int y, int z); + void checkPressed(Level* level, int x, int y, int z); public: - static bool shouldConnectTo(LevelSource *level, int x, int y, int z, int data, int dir); + static bool shouldConnectTo(LevelSource* level, int x, int y, int z, + int data, int dir); }; diff --git a/Minecraft.World/Blocks/VineTile.cpp b/Minecraft.World/Blocks/VineTile.cpp index 9c5cf77e7..542504125 100644 --- a/Minecraft.World/Blocks/VineTile.cpp +++ b/Minecraft.World/Blocks/VineTile.cpp @@ -8,32 +8,22 @@ #include "../Headers/net.minecraft.stats.h" #include "../Headers/net.minecraft.world.level.biome.h" -VineTile::VineTile(int id) : Tile(id, Material::replaceable_plant, false) -{ +VineTile::VineTile(int id) : Tile(id, Material::replaceable_plant, false) { setTicking(true); } -void VineTile::updateDefaultShape() -{ - setShape(0, 0, 0, 1, 1, 1); -} +void VineTile::updateDefaultShape() { setShape(0, 0, 0, 1, 1, 1); } -int VineTile::getRenderShape() -{ - return SHAPE_VINE; -} +int VineTile::getRenderShape() { return SHAPE_VINE; } -bool VineTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool VineTile::isSolidRender(bool isServerLevel) { return false; } -bool VineTile::isCubeShaped() -{ - return false; -} +bool VineTile::isCubeShaped() { return false; } -void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) // 4J added forceData, forceEntity param +void VineTile::updateShape( + LevelSource* level, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { const float thickness = 1.0f / 16.0f; @@ -47,8 +37,7 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat float maxZ = 0; bool hasWall = facings > 0; - if ((facings & VINE_WEST) != 0) - { + if ((facings & VINE_WEST) != 0) { maxX = Math::_max(maxX, thickness); minX = 0; minY = 0; @@ -57,8 +46,7 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat maxZ = 1; hasWall = true; } - if ((facings & VINE_EAST) != 0) - { + if ((facings & VINE_EAST) != 0) { minX = Math::_min(minX, 1 - thickness); maxX = 1; minY = 0; @@ -67,8 +55,7 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat maxZ = 1; hasWall = true; } - if ((facings & VINE_NORTH) != 0) - { + if ((facings & VINE_NORTH) != 0) { maxZ = Math::_max(maxZ, thickness); minZ = 0; minX = 0; @@ -77,8 +64,7 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat maxY = 1; hasWall = true; } - if ((facings & VINE_SOUTH) != 0) - { + if ((facings & VINE_SOUTH) != 0) { minZ = Math::_min(minZ, 1 - thickness); maxZ = 1; minX = 0; @@ -87,8 +73,7 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat maxY = 1; hasWall = true; } - if (!hasWall && isAcceptableNeighbor(level->getTile(x, y + 1, z))) - { + if (!hasWall && isAcceptableNeighbor(level->getTile(x, y + 1, z))) { minY = Math::_min(minY, 1 - thickness); maxY = 1; minX = 0; @@ -97,59 +82,49 @@ void VineTile::updateShape(LevelSource *level, int x, int y, int z, int forceDat maxZ = 1; } setShape(minX, minY, minZ, maxX, maxY, maxZ); - } -AABB *VineTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} +AABB* VineTile::getAABB(Level* level, int x, int y, int z) { return NULL; } -bool VineTile::mayPlace(Level *level, int x, int y, int z, int face) -{ - switch (face) - { - default: - return false; - case Facing::UP: - return isAcceptableNeighbor(level->getTile(x, y + 1, z)); - case Facing::NORTH: - return isAcceptableNeighbor(level->getTile(x, y, z + 1)); - case Facing::SOUTH: - return isAcceptableNeighbor(level->getTile(x, y, z - 1)); - case Facing::EAST: - return isAcceptableNeighbor(level->getTile(x - 1, y, z)); - case Facing::WEST: - return isAcceptableNeighbor(level->getTile(x + 1, y, z)); +bool VineTile::mayPlace(Level* level, int x, int y, int z, int face) { + switch (face) { + default: + return false; + case Facing::UP: + return isAcceptableNeighbor(level->getTile(x, y + 1, z)); + case Facing::NORTH: + return isAcceptableNeighbor(level->getTile(x, y, z + 1)); + case Facing::SOUTH: + return isAcceptableNeighbor(level->getTile(x, y, z - 1)); + case Facing::EAST: + return isAcceptableNeighbor(level->getTile(x - 1, y, z)); + case Facing::WEST: + return isAcceptableNeighbor(level->getTile(x + 1, y, z)); } } -bool VineTile::isAcceptableNeighbor(int id) -{ +bool VineTile::isAcceptableNeighbor(int id) { if (id == 0) return false; - Tile *tile = Tile::tiles[id]; + Tile* tile = Tile::tiles[id]; if (tile->isCubeShaped() && tile->material->blocksMotion()) return true; return false; } -bool VineTile::updateSurvival(Level *level, int x, int y, int z) -{ +bool VineTile::updateSurvival(Level* level, int x, int y, int z) { int facings = level->getData(x, y, z); int newFacings = facings; - if (newFacings > 0) - { - for (int d = 0; d <= 3; d++) - { + if (newFacings > 0) { + for (int d = 0; d <= 3; d++) { int facing = 1 << d; - if ((facings & facing) != 0) - { - if (!isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[d], y, z + Direction::STEP_Z[d]))) - { + if ((facings & facing) != 0) { + if (!isAcceptableNeighbor( + level->getTile(x + Direction::STEP_X[d], y, + z + Direction::STEP_Z[d]))) { // no attachment in this direction, // verify that there is vines hanging above - if (level->getTile(x, y + 1, z) != id || (level->getData(x, y + 1, z) & facing) == 0) - { + if (level->getTile(x, y + 1, z) != id || + (level->getData(x, y + 1, z) & facing) == 0) { newFacings &= ~facing; } } @@ -157,172 +132,186 @@ bool VineTile::updateSurvival(Level *level, int x, int y, int z) } } - if (newFacings == 0) - { + if (newFacings == 0) { // the block will die unless it has a roof - if (!isAcceptableNeighbor(level->getTile(x, y + 1, z))) - { + if (!isAcceptableNeighbor(level->getTile(x, y + 1, z))) { return false; } } - if (newFacings != facings) - { + if (newFacings != facings) { level->setData(x, y, z, newFacings); } return true; - } -int VineTile::getColor() const -{ - return FoliageColor::getDefaultColor(); +int VineTile::getColor() const { return FoliageColor::getDefaultColor(); } + +int VineTile::getColor(int auxData) { return FoliageColor::getDefaultColor(); } + +int VineTile::getColor(LevelSource* level, int x, int y, int z, int data) { + return getColor(level, x, y, z); } -int VineTile::getColor(int auxData) -{ - return FoliageColor::getDefaultColor(); +int VineTile::getColor(LevelSource* level, int x, int y, int z) { + return level->getBiome(x, z)->getFolageColor(); } -int VineTile::getColor(LevelSource *level, int x, int y, int z, int data) -{ - return getColor(level, x, y, z); -} - -int VineTile::getColor(LevelSource *level, int x, int y, int z) -{ - return level->getBiome(x, z)->getFolageColor(); -} - -void VineTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - if (!level->isClientSide && !updateSurvival(level, x, y, z)) - { +void VineTile::neighborChanged(Level* level, int x, int y, int z, int type) { + if (!level->isClientSide && !updateSurvival(level, x, y, z)) { spawnResources(level, x, y, z, level->getData(x, y, z), 0); level->setTile(x, y, z, 0); } } -void VineTile::tick(Level *level, int x, int y, int z, Random *random) -{ - if (!level->isClientSide) - { - if (level->random->nextInt(4) == 0) - { - // 4J - Brought side spread check forward from 1.2.3 - int r = 4; - int max = 5; - bool noSideSpread = false; - for (int xx = x - r; xx <= x + r; xx++) - { - for (int zz = z - r; zz <= z + r; zz++) - for (int yy = y - 1; yy <= y + 1; yy++) - { - if (level->getTile(xx, yy, zz) == id && --max <= 0) - { - noSideSpread = true; - goto testLoop; - } - } -testLoop: if(noSideSpread) break; - } +void VineTile::tick(Level* level, int x, int y, int z, Random* random) { + if (!level->isClientSide) { + if (level->random->nextInt(4) == 0) { + // 4J - Brought side spread check forward from 1.2.3 + int r = 4; + int max = 5; + bool noSideSpread = false; + for (int xx = x - r; xx <= x + r; xx++) { + for (int zz = z - r; zz <= z + r; zz++) + for (int yy = y - 1; yy <= y + 1; yy++) { + if (level->getTile(xx, yy, zz) == id && --max <= 0) { + noSideSpread = true; + goto testLoop; + } + } + testLoop: + if (noSideSpread) break; + } int currentFacings = level->getData(x, y, z); int testFacing = level->random->nextInt(6); int testDirection = Direction::FACING_DIRECTION[testFacing]; - if (testFacing == Facing::UP && y < (Level::maxBuildHeight - 1) && level->isEmptyTile(x, y + 1, z)) - { - // 4J - Brought side spread check forward from 1.2.3 - if (noSideSpread) return; + if (testFacing == Facing::UP && y < (Level::maxBuildHeight - 1) && + level->isEmptyTile(x, y + 1, z)) { + // 4J - Brought side spread check forward from 1.2.3 + if (noSideSpread) return; // grow upwards, but only if there is something to cling to int spawnFacings = level->random->nextInt(16) & currentFacings; - if (spawnFacings > 0) - { - for (int d = 0; d <= 3; d++) - { - if (!isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[d], y + 1, z + Direction::STEP_Z[d]))) - { + if (spawnFacings > 0) { + for (int d = 0; d <= 3; d++) { + if (!isAcceptableNeighbor( + level->getTile(x + Direction::STEP_X[d], y + 1, + z + Direction::STEP_Z[d]))) { spawnFacings &= ~(1 << d); } } - if (spawnFacings > 0) - { + if (spawnFacings > 0) { level->setTileAndData(x, y + 1, z, id, spawnFacings); } } - } - else if (testFacing >= Facing::NORTH && testFacing <= Facing::EAST && (currentFacings & (1 << testDirection)) == 0) - { - // 4J - Brought side spread check forward from 1.2.3 - if (noSideSpread) return; + } else if (testFacing >= Facing::NORTH && + testFacing <= Facing::EAST && + (currentFacings & (1 << testDirection)) == 0) { + // 4J - Brought side spread check forward from 1.2.3 + if (noSideSpread) return; - int edgeTile = level->getTile(x + Direction::STEP_X[testDirection], y, z + Direction::STEP_Z[testDirection]); + int edgeTile = + level->getTile(x + Direction::STEP_X[testDirection], y, + z + Direction::STEP_Z[testDirection]); - if (edgeTile == 0 || Tile::tiles[edgeTile] == NULL) - { + if (edgeTile == 0 || Tile::tiles[edgeTile] == NULL) { // if the edge tile is air, we could possibly cling // to something int left = (testDirection + 1) & 3; int right = (testDirection + 3) & 3; // attempt to grow straight onto solid tiles - if ((currentFacings & (1 << left)) != 0 - && isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[testDirection] + Direction::STEP_X[left], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[left]))) - { - level->setTileAndData(x + Direction::STEP_X[testDirection], y, z + Direction::STEP_Z[testDirection], id, 1 << left); - } - else if ((currentFacings & (1 << right)) != 0 - && isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[testDirection] + Direction::STEP_X[right], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[right]))) - { - level->setTileAndData(x + Direction::STEP_X[testDirection], y, z + Direction::STEP_Z[testDirection], id, 1 << right); + if ((currentFacings & (1 << left)) != 0 && + isAcceptableNeighbor(level->getTile( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[left], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[left]))) { + level->setTileAndData( + x + Direction::STEP_X[testDirection], y, + z + Direction::STEP_Z[testDirection], id, + 1 << left); + } else if ((currentFacings & (1 << right)) != 0 && + isAcceptableNeighbor(level->getTile( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[right], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[right]))) { + level->setTileAndData( + x + Direction::STEP_X[testDirection], y, + z + Direction::STEP_Z[testDirection], id, + 1 << right); } // attempt to grow around corners, but only if the // base tile is solid - else if ((currentFacings & (1 << left)) != 0 - && level->isEmptyTile(x + Direction::STEP_X[testDirection] + Direction::STEP_X[left], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[left]) - && isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[left], y, z + Direction::STEP_Z[left]))) - { - level->setTileAndData(x + Direction::STEP_X[testDirection] + Direction::STEP_X[left], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[left], id, - 1 << ((testDirection + 2) & 3)); - } - else if ((currentFacings & (1 << right)) != 0 - && level->isEmptyTile(x + Direction::STEP_X[testDirection] + Direction::STEP_X[right], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[right]) - && isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[right], y, z + Direction::STEP_Z[right]))) - { - level->setTileAndData(x + Direction::STEP_X[testDirection] + Direction::STEP_X[right], y, z + Direction::STEP_Z[testDirection] + Direction::STEP_Z[right], id, - 1 << ((testDirection + 2) & 3)); + else if ((currentFacings & (1 << left)) != 0 && + level->isEmptyTile( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[left], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[left]) && + isAcceptableNeighbor( + level->getTile(x + Direction::STEP_X[left], y, + z + Direction::STEP_Z[left]))) { + level->setTileAndData( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[left], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[left], + id, 1 << ((testDirection + 2) & 3)); + } else if ((currentFacings & (1 << right)) != 0 && + level->isEmptyTile( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[right], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[right]) && + isAcceptableNeighbor(level->getTile( + x + Direction::STEP_X[right], y, + z + Direction::STEP_Z[right]))) { + level->setTileAndData( + x + Direction::STEP_X[testDirection] + + Direction::STEP_X[right], + y, + z + Direction::STEP_Z[testDirection] + + Direction::STEP_Z[right], + id, 1 << ((testDirection + 2) & 3)); } // attempt to grow onto the ceiling - else if (isAcceptableNeighbor(level->getTile(x + Direction::STEP_X[testDirection], y + 1, z + Direction::STEP_Z[testDirection]))) - { - level->setTileAndData(x + Direction::STEP_X[testDirection], y, z + Direction::STEP_Z[testDirection], id, 0); + else if (isAcceptableNeighbor(level->getTile( + x + Direction::STEP_X[testDirection], y + 1, + z + Direction::STEP_Z[testDirection]))) { + level->setTileAndData( + x + Direction::STEP_X[testDirection], y, + z + Direction::STEP_Z[testDirection], id, 0); } - } - else if (Tile::tiles[edgeTile]->material->isSolidBlocking() && Tile::tiles[edgeTile]->isCubeShaped()) - { + } else if (Tile::tiles[edgeTile]->material->isSolidBlocking() && + Tile::tiles[edgeTile]->isCubeShaped()) { // we have a wall that we can cling to - level->setData(x, y, z, currentFacings | (1 << testDirection)); + level->setData(x, y, z, + currentFacings | (1 << testDirection)); } } // growing downwards happens more often than the other // directions - else if (y > 1) - { + else if (y > 1) { int belowTile = level->getTile(x, y - 1, z); // grow downwards into air - if (belowTile == 0) - { - int spawnFacings = level->random->nextInt(16) & currentFacings; - if (spawnFacings > 0) - { + if (belowTile == 0) { + int spawnFacings = + level->random->nextInt(16) & currentFacings; + if (spawnFacings > 0) { level->setTileAndData(x, y - 1, z, id, spawnFacings); } - } - else if (belowTile == id) - { - int spawnFacings = level->random->nextInt(16) & currentFacings; + } else if (belowTile == id) { + int spawnFacings = + level->random->nextInt(16) & currentFacings; int belowData = level->getData(x, y - 1, z); if (belowData != (belowData | spawnFacings)) { level->setData(x, y - 1, z, belowData | spawnFacings); @@ -330,58 +319,51 @@ testLoop: if(noSideSpread) break; } } } - } + } } -int VineTile::getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue) -{ - int facings = 0; - switch (face) - { - case Facing::NORTH: - facings = VINE_SOUTH; - break; - case Facing::SOUTH: - facings = VINE_NORTH; - break; - case Facing::WEST: - facings = VINE_EAST; - break; - case Facing::EAST: - facings = VINE_WEST; - break; - } - if (facings != 0) - { - return facings; - } - return itemValue; +int VineTile::getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue) { + int facings = 0; + switch (face) { + case Facing::NORTH: + facings = VINE_SOUTH; + break; + case Facing::SOUTH: + facings = VINE_NORTH; + break; + case Facing::WEST: + facings = VINE_EAST; + break; + case Facing::EAST: + facings = VINE_WEST; + break; + } + if (facings != 0) { + return facings; + } + return itemValue; } -int VineTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return 0; +int VineTile::getResource(int data, Random* random, int playerBonusLevel) { + return 0; } -int VineTile::getResourceCount(Random *random) -{ - return 0; -} +int VineTile::getResourceCount(Random* random) { return 0; } -void VineTile::playerDestroy(Level *level, std::shared_ptrplayer, int x, int y, int z, int data) -{ - if (!level->isClientSide && player->getSelectedItem() != NULL && player->getSelectedItem()->id == Item::shears->id) - { - player->awardStat( - GenericStats::blocksMined(id), - GenericStats::param_blocksMined(id,data,1) - ); +void VineTile::playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data) { + if (!level->isClientSide && player->getSelectedItem() != NULL && + player->getSelectedItem()->id == Item::shears->id) { + player->awardStat(GenericStats::blocksMined(id), + GenericStats::param_blocksMined(id, data, 1)); // drop leaf block instead of sapling - popResource(level, x, y, z, std::shared_ptr(new ItemInstance(Tile::vine, 1, 0))); - } - else - { + popResource( + level, x, y, z, + std::shared_ptr(new ItemInstance(Tile::vine, 1, 0))); + } else { Tile::playerDestroy(level, player, x, y, z, data); } } diff --git a/Minecraft.World/Blocks/VineTile.h b/Minecraft.World/Blocks/VineTile.h index 8499581ee..965eba70f 100644 --- a/Minecraft.World/Blocks/VineTile.h +++ b/Minecraft.World/Blocks/VineTile.h @@ -4,35 +4,43 @@ class Level; class LevelSource; -class VineTile : public Tile -{ +class VineTile : public Tile { public: - static const int VINE_SOUTH = 1 << Direction::SOUTH; - static const int VINE_NORTH = 1 << Direction::NORTH; - static const int VINE_EAST = 1 << Direction::EAST; - static const int VINE_WEST = 1 << Direction::WEST; + static const int VINE_SOUTH = 1 << Direction::SOUTH; + static const int VINE_NORTH = 1 << Direction::NORTH; + static const int VINE_EAST = 1 << Direction::EAST; + static const int VINE_WEST = 1 << Direction::WEST; public: - VineTile(int id); + VineTile(int id); virtual void updateDefaultShape(); virtual int getRenderShape(); virtual bool isSolidRender(bool isServerLevel = false); virtual bool isCubeShaped(); - virtual void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); // 4J added forceData, forceEntity param - virtual AABB *getAABB(Level *level, int x, int y, int z); - virtual bool mayPlace(Level *level, int x, int y, int z, int face); + virtual void updateShape( + LevelSource* level, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + virtual AABB* getAABB(Level* level, int x, int y, int z); + virtual bool mayPlace(Level* level, int x, int y, int z, int face); + private: - bool isAcceptableNeighbor(int id); - bool updateSurvival(Level *level, int x, int y, int z); + bool isAcceptableNeighbor(int id); + bool updateSurvival(Level* level, int x, int y, int z); + public: virtual int getColor() const; virtual int getColor(int auxData); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual void neighborChanged(Level *level, int x, int y, int z, int type); - virtual void tick(Level *level, int x, int y, int z, Random *random); - virtual int getPlacedOnFaceDataValue(Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, int itemValue); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getResourceCount(Random *random); - virtual void playerDestroy(Level *level, std::shared_ptr player, int x, int y, int z, int data); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual void neighborChanged(Level* level, int x, int y, int z, int type); + virtual void tick(Level* level, int x, int y, int z, Random* random); + virtual int getPlacedOnFaceDataValue(Level* level, int x, int y, int z, + int face, float clickX, float clickY, + float clickZ, int itemValue); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getResourceCount(Random* random); + virtual void playerDestroy(Level* level, std::shared_ptr player, + int x, int y, int z, int data); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WallTile.cpp b/Minecraft.World/Blocks/WallTile.cpp index 9389ec9e3..861744c09 100644 --- a/Minecraft.World/Blocks/WallTile.cpp +++ b/Minecraft.World/Blocks/WallTile.cpp @@ -11,179 +11,148 @@ const float WallTile::WALL_HEIGHT = 13.0f / 16.0f; const float WallTile::POST_WIDTH = 4.0f / 16.0f; const float WallTile::POST_HEIGHT = 16.0f / 16.0f; -const unsigned int WallTile::COBBLE_NAMES[2] = { IDS_TILE_COBBLESTONE_WALL, - IDS_TILE_COBBLESTONE_WALL_MOSSY, +const unsigned int WallTile::COBBLE_NAMES[2] = { + IDS_TILE_COBBLESTONE_WALL, + IDS_TILE_COBBLESTONE_WALL_MOSSY, }; -WallTile::WallTile(int id, Tile *baseTile) : Tile(id, baseTile->material, false) -{ - setDestroyTime(baseTile->destroySpeed); - setExplodeable(baseTile->explosionResistance / 3); - setSoundType(baseTile->soundType); +WallTile::WallTile(int id, Tile* baseTile) + : Tile(id, baseTile->material, false) { + setDestroyTime(baseTile->destroySpeed); + setExplodeable(baseTile->explosionResistance / 3); + setSoundType(baseTile->soundType); } -Icon *WallTile::getTexture(int face, int data) -{ - if (data == TYPE_MOSSY) - { - return Tile::mossStone->getTexture(face); - } - return Tile::stoneBrick->getTexture(face); +Icon* WallTile::getTexture(int face, int data) { + if (data == TYPE_MOSSY) { + return Tile::mossStone->getTexture(face); + } + return Tile::stoneBrick->getTexture(face); } -int WallTile::getRenderShape() -{ - return SHAPE_WALL; +int WallTile::getRenderShape() { return SHAPE_WALL; } + +bool WallTile::isCubeShaped() { return false; } + +bool WallTile::isPathfindable(LevelSource* level, int x, int y, int z) { + return false; } -bool WallTile::isCubeShaped() -{ - return false; +bool WallTile::isSolidRender(bool isServerLevel) { return false; } + +void WallTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + bool n = connectsTo(level, x, y, z - 1); + bool s = connectsTo(level, x, y, z + 1); + bool w = connectsTo(level, x - 1, y, z); + bool e = connectsTo(level, x + 1, y, z); + + float west = .5f - POST_WIDTH; + float east = .5f + POST_WIDTH; + float north = .5f - POST_WIDTH; + float south = .5f + POST_WIDTH; + float up = POST_HEIGHT; + + if (n) { + north = 0; + } + if (s) { + south = 1; + } + if (w) { + west = 0; + } + if (e) { + east = 1; + } + + if (n && s && !w && !e) { + up = WALL_HEIGHT; + west = .5f - WALL_WIDTH; + east = .5f + WALL_WIDTH; + } else if (!n && !s && w && e) { + up = WALL_HEIGHT; + north = .5f - WALL_WIDTH; + south = .5f + WALL_WIDTH; + } + + setShape(west, 0, north, east, up, south); } -bool WallTile::isPathfindable(LevelSource *level, int x, int y, int z) -{ - return false; +AABB* WallTile::getAABB(Level* level, int x, int y, int z) { + // 4J-JEV: Changed to avoid race conditions associated with calling update + // shape. + + bool n = connectsTo(level, x, y, z - 1); + bool s = connectsTo(level, x, y, z + 1); + bool w = connectsTo(level, x - 1, y, z); + bool e = connectsTo(level, x + 1, y, z); + + float west = .5f - POST_WIDTH; + float east = .5f + POST_WIDTH; + float north = .5f - POST_WIDTH; + float south = .5f + POST_WIDTH; + float up = POST_HEIGHT; + + if (n) { + north = 0; + } + if (s) { + south = 1; + } + if (w) { + west = 0; + } + if (e) { + east = 1; + } + + /* 4J-JEV: + Stopping the width changing here, it's causing cows/mobs/passers-by + to 'jump' up when they are pressed against the wall and then the wall + section is upgraded to a wall post expanding the bounding box. It's only + a 1/16 of a block difference, it shouldn't matter if we leave it a little + larger. + */ + if (n && s && !w && !e) { + up = WALL_HEIGHT; + // west = .5f - WALL_WIDTH; + // east = .5f + WALL_WIDTH; + } else if (!n && !s && w && e) { + up = WALL_HEIGHT; + // north = .5f - WALL_WIDTH; + // south = .5f + WALL_WIDTH; + } + + return AABB::newTemp(x + west, y, z + north, x + east, y + 1.5f, z + south); } -bool WallTile::isSolidRender(bool isServerLevel) -{ - return false; +bool WallTile::connectsTo(LevelSource* level, int x, int y, int z) { + int tile = level->getTile(x, y, z); + if (tile == id || tile == Tile::fenceGate_Id) { + return true; + } + Tile* tileInstance = Tile::tiles[tile]; + if (tileInstance != NULL) { + if (tileInstance->material->isSolidBlocking() && + tileInstance->isCubeShaped()) { + return tileInstance->material != Material::vegetable; + } + } + return false; } -void WallTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - bool n = connectsTo(level, x, y, z - 1); - bool s = connectsTo(level, x, y, z + 1); - bool w = connectsTo(level, x - 1, y, z); - bool e = connectsTo(level, x + 1, y, z); +int WallTile::getSpawnResourcesAuxValue(int data) { return data; } - float west = .5f - POST_WIDTH; - float east = .5f + POST_WIDTH; - float north = .5f - POST_WIDTH; - float south = .5f + POST_WIDTH; - float up = POST_HEIGHT; - - if (n) - { - north = 0; - } - if (s) - { - south = 1; - } - if (w) - { - west = 0; - } - if (e) - { - east = 1; - } - - if (n && s && !w && !e) - { - up = WALL_HEIGHT; - west = .5f - WALL_WIDTH; - east = .5f + WALL_WIDTH; - } - else if (!n && !s && w && e) - { - up = WALL_HEIGHT; - north = .5f - WALL_WIDTH; - south = .5f + WALL_WIDTH; - } - - setShape(west, 0, north, east, up, south); +bool WallTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + if (face == Facing::DOWN) { + return Tile::shouldRenderFace(level, x, y, z, face); + } + return true; } -AABB *WallTile::getAABB(Level *level, int x, int y, int z) -{ - // 4J-JEV: Changed to avoid race conditions associated with calling update shape. - - bool n = connectsTo(level, x, y, z - 1); - bool s = connectsTo(level, x, y, z + 1); - bool w = connectsTo(level, x - 1, y, z); - bool e = connectsTo(level, x + 1, y, z); - - float west = .5f - POST_WIDTH; - float east = .5f + POST_WIDTH; - float north = .5f - POST_WIDTH; - float south = .5f + POST_WIDTH; - float up = POST_HEIGHT; - - if (n) - { - north = 0; - } - if (s) - { - south = 1; - } - if (w) - { - west = 0; - } - if (e) - { - east = 1; - } - - /* 4J-JEV: - Stopping the width changing here, it's causing cows/mobs/passers-by to 'jump' up when they are pressed against the - wall and then the wall section is upgraded to a wall post expanding the bounding box. - It's only a 1/16 of a block difference, it shouldn't matter if we leave it a little larger. - */ - if (n && s && !w && !e) - { - up = WALL_HEIGHT; - //west = .5f - WALL_WIDTH; - //east = .5f + WALL_WIDTH; - } - else if (!n && !s && w && e) - { - up = WALL_HEIGHT; - //north = .5f - WALL_WIDTH; - //south = .5f + WALL_WIDTH; - } - - return AABB::newTemp(x+west, y, z+north, x+east, y+1.5f, z+south); -} - - -bool WallTile::connectsTo(LevelSource *level, int x, int y, int z) -{ - int tile = level->getTile(x, y, z); - if (tile == id || tile == Tile::fenceGate_Id) - { - return true; - } - Tile *tileInstance = Tile::tiles[tile]; - if (tileInstance != NULL) - { - if (tileInstance->material->isSolidBlocking() && tileInstance->isCubeShaped()) - { - return tileInstance->material != Material::vegetable; - } - } - return false; -} - -int WallTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} - -bool WallTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - if (face == Facing::DOWN) - { - return Tile::shouldRenderFace(level, x, y, z, face); - } - return true; -} - -void WallTile::registerIcons(IconRegister *iconRegister) -{ - // None +void WallTile::registerIcons(IconRegister* iconRegister) { + // None } diff --git a/Minecraft.World/Blocks/WallTile.h b/Minecraft.World/Blocks/WallTile.h index e693f9a42..634253966 100644 --- a/Minecraft.World/Blocks/WallTile.h +++ b/Minecraft.World/Blocks/WallTile.h @@ -2,30 +2,32 @@ #include "Tile.h" -class WallTile : public Tile -{ +class WallTile : public Tile { public: - static const float WALL_WIDTH; - static const float WALL_HEIGHT; - static const float POST_WIDTH; - static const float POST_HEIGHT; + static const float WALL_WIDTH; + static const float WALL_HEIGHT; + static const float POST_WIDTH; + static const float POST_HEIGHT; - static const int TYPE_NORMAL = 0; - static const int TYPE_MOSSY = 1; + static const int TYPE_NORMAL = 0; + static const int TYPE_MOSSY = 1; - static const unsigned int COBBLE_NAMES[2]; + static const unsigned int COBBLE_NAMES[2]; - WallTile(int id, Tile *baseTile); + WallTile(int id, Tile* baseTile); - Icon *getTexture(int face, int data); - int getRenderShape(); - bool isCubeShaped(); - bool isPathfindable(LevelSource *level, int x, int y, int z); - bool isSolidRender(bool isServerLevel = false); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); - AABB *getAABB(Level *level, int x, int y, int z); - bool connectsTo(LevelSource *level, int x, int y, int z); - int getSpawnResourcesAuxValue(int data); - bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - void registerIcons(IconRegister *iconRegister); + Icon* getTexture(int face, int data); + int getRenderShape(); + bool isCubeShaped(); + bool isPathfindable(LevelSource* level, int x, int y, int z); + bool isSolidRender(bool isServerLevel = false); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + AABB* getAABB(Level* level, int x, int y, int z); + bool connectsTo(LevelSource* level, int x, int y, int z); + int getSpawnResourcesAuxValue(int data); + bool shouldRenderFace(LevelSource* level, int x, int y, int z, int face); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WaterLilyTile.cpp b/Minecraft.World/Blocks/WaterLilyTile.cpp index 866a3860b..a4f23ce23 100644 --- a/Minecraft.World/Blocks/WaterLilyTile.cpp +++ b/Minecraft.World/Blocks/WaterLilyTile.cpp @@ -5,72 +5,62 @@ #include "../../Minecraft.Client/Minecraft.h" #include "../Util/AABB.h" -WaterlilyTile::WaterlilyTile(int id) : Bush(id) -{ - this->updateDefaultShape(); -} +WaterlilyTile::WaterlilyTile(int id) : Bush(id) { this->updateDefaultShape(); } // 4J Added override -void WaterlilyTile::updateDefaultShape() -{ +void WaterlilyTile::updateDefaultShape() { float ss = 0.5f; float hh = 0.25f / 16.0f; this->setShape(0.5f - ss, 0, 0.5f - ss, 0.5f + ss, hh, 0.5f + ss); } -int WaterlilyTile::getRenderShape() -{ - return Tile::SHAPE_LILYPAD; +int WaterlilyTile::getRenderShape() { return Tile::SHAPE_LILYPAD; } + +void WaterlilyTile::addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source) { + if (source == NULL || !(std::dynamic_pointer_cast(source))) { + Bush::addAABBs(level, x, y, z, box, boxes, source); + } } -void WaterlilyTile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source) -{ - if (source == NULL || !(std::dynamic_pointer_cast(source))) - { - Bush::addAABBs(level, x, y, z, box, boxes, source); - } +AABB* WaterlilyTile::getAABB(Level* level, int x, int y, int z) { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, + y + tls->yy1, z + tls->zz1); } -AABB *WaterlilyTile::getAABB(Level *level, int x, int y, int z) -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1); +int WaterlilyTile::getColor() const { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_WaterLily); // 0x208030 } -int WaterlilyTile::getColor() const -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_WaterLily); //0x208030 +int WaterlilyTile::getColor(int auxData) { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_WaterLily); // 0x208030 } -int WaterlilyTile::getColor(int auxData) -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_WaterLily); //0x208030 +int WaterlilyTile::getColor(LevelSource* level, int x, int y, int z) { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_WaterLily); // 0x208030 } -int WaterlilyTile::getColor(LevelSource *level, int x, int y, int z) +int WaterlilyTile::getColor(LevelSource* level, int x, int y, int z, + int data) // 0x208030 { - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Tile_WaterLily); //0x208030 + return getColor(level, x, y, z); } -int WaterlilyTile::getColor(LevelSource *level, int x, int y, int z, int data) //0x208030 -{ - return getColor(level, x, y, z); +bool WaterlilyTile::mayPlaceOn(int tile) { return tile == Tile::calmWater_Id; } + +bool WaterlilyTile::canSurvive(Level* level, int x, int y, int z) { + if (y < 0 || y >= Level::maxBuildHeight) return false; + return level->getMaterial(x, y - 1, z) == Material::water && + level->getData(x, y - 1, z) == 0; } -bool WaterlilyTile::mayPlaceOn(int tile) -{ - return tile == Tile::calmWater_Id; -} - -bool WaterlilyTile::canSurvive(Level *level, int x, int y, int z) -{ - if (y < 0 || y >= Level::maxBuildHeight) return false; - return level->getMaterial(x, y - 1, z) == Material::water && level->getData(x, y - 1, z) == 0; -} - -bool WaterlilyTile::growTree(Level *level, int x, int y, int z, Random *random) -{ - return false; +bool WaterlilyTile::growTree(Level* level, int x, int y, int z, + Random* random) { + return false; } diff --git a/Minecraft.World/Blocks/WaterLilyTile.h b/Minecraft.World/Blocks/WaterLilyTile.h index e621d46b5..81143ddfd 100644 --- a/Minecraft.World/Blocks/WaterLilyTile.h +++ b/Minecraft.World/Blocks/WaterLilyTile.h @@ -1,24 +1,25 @@ #pragma once #include "PlantTile.h" -class WaterlilyTile : public Bush -{ +class WaterlilyTile : public Bush { private: - // static const int col = 0x208030; + // static const int col = 0x208030; public: - WaterlilyTile(int id); - virtual void updateDefaultShape(); // 4J Added override + WaterlilyTile(int id); + virtual void updateDefaultShape(); // 4J Added override - virtual int getRenderShape(); - virtual void addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, std::shared_ptr source); - virtual AABB *getAABB(Level *level, int x, int y, int z); + virtual int getRenderShape(); + virtual void addAABBs(Level* level, int x, int y, int z, AABB* box, + AABBList* boxes, std::shared_ptr source); + virtual AABB* getAABB(Level* level, int x, int y, int z); virtual int getColor() const; virtual int getColor(int auxData); - virtual int getColor(LevelSource *level, int x, int y, int z); - virtual int getColor(LevelSource *level, int x, int y, int z, int data); // 4J added + virtual int getColor(LevelSource* level, int x, int y, int z); + virtual int getColor(LevelSource* level, int x, int y, int z, + int data); // 4J added protected: - virtual bool mayPlaceOn(int tile); - virtual bool canSurvive(Level *level, int x, int y, int z); - bool growTree(Level *level, int x, int y, int z, Random *random); + virtual bool mayPlaceOn(int tile); + virtual bool canSurvive(Level* level, int x, int y, int z); + bool growTree(Level* level, int x, int y, int z, Random* random); }; diff --git a/Minecraft.World/Blocks/WebMaterial.h b/Minecraft.World/Blocks/WebMaterial.h index 576fa3966..6b95d0839 100644 --- a/Minecraft.World/Blocks/WebMaterial.h +++ b/Minecraft.World/Blocks/WebMaterial.h @@ -1,10 +1,10 @@ #pragma once #include "Material.h" -// 4J added, Java version just does a local alteration when instantiating the Material for webs to get the same thing -class WebMaterial : public Material -{ +// 4J added, Java version just does a local alteration when instantiating the +// Material for webs to get the same thing +class WebMaterial : public Material { public: - WebMaterial(MaterialColor *color) : Material(color) {} - virtual bool blocksMotion() { return false; } + WebMaterial(MaterialColor* color) : Material(color) {} + virtual bool blocksMotion() { return false; } }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WebTile.cpp b/Minecraft.World/Blocks/WebTile.cpp index 68b88a43b..ffc4137d5 100644 --- a/Minecraft.World/Blocks/WebTile.cpp +++ b/Minecraft.World/Blocks/WebTile.cpp @@ -3,51 +3,26 @@ #include "../Headers/net.minecraft.world.item.h" #include "WebTile.h" -WebTile::WebTile(int id) : Tile(id, Material::web) -{ +WebTile::WebTile(int id) : Tile(id, Material::web) {} + +void WebTile::entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity) { + entity->makeStuckInWeb(); } +bool WebTile::isSolidRender(bool isServerLevel) { return false; } -void WebTile::entityInside(Level *level, int x, int y, int z, std::shared_ptr entity) -{ - entity->makeStuckInWeb(); -} +AABB* WebTile::getAABB(Level* level, int x, int y, int z) { return NULL; } +int WebTile::getRenderShape() { return Tile::SHAPE_CROSS_TEXTURE; } -bool WebTile::isSolidRender(bool isServerLevel) -{ - return false; -} +bool WebTile::blocksLight() { return false; } +bool WebTile::isCubeShaped() { return false; } -AABB *WebTile::getAABB(Level *level, int x, int y, int z) -{ - return NULL; -} - - -int WebTile::getRenderShape() -{ - return Tile::SHAPE_CROSS_TEXTURE; -} - -bool WebTile::blocksLight() -{ - return false; -} - -bool WebTile::isCubeShaped() -{ - return false; -} - -int WebTile::getResource(int data, Random *random, int playerBonusLevel) -{ +int WebTile::getResource(int data, Random* random, int playerBonusLevel) { // @TODO: Explosives currently also give string back. Fix? return Item::string->id; } -bool WebTile::isSilkTouchable() -{ - return true; -} \ No newline at end of file +bool WebTile::isSilkTouchable() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/WebTile.h b/Minecraft.World/Blocks/WebTile.h index 546617179..1512cd92d 100644 --- a/Minecraft.World/Blocks/WebTile.h +++ b/Minecraft.World/Blocks/WebTile.h @@ -2,30 +2,27 @@ #include "Tile.h" -class WebTile : public Tile -{ +class WebTile : public Tile { +public: + WebTile(int id); public: - WebTile(int id); - + void entityInside(Level* level, int x, int y, int z, + std::shared_ptr entity); public: - void entityInside(Level *level, int x, int y, int z, std::shared_ptr entity); - + bool isSolidRender(bool isServerLevel = false); public: - bool isSolidRender(bool isServerLevel = false); + AABB* getAABB(Level* level, int x, int y, int z); public: - AABB *getAABB(Level *level, int x, int y, int z); + int getRenderShape(); -public: - int getRenderShape(); - - bool blocksLight(); - bool isCubeShaped(); - virtual int getResource(int data, Random *random, int playerBonusLevel); + bool blocksLight(); + bool isCubeShaped(); + virtual int getResource(int data, Random* random, int playerBonusLevel); protected: - bool isSilkTouchable(); + bool isSilkTouchable(); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WoodSlabTile.cpp b/Minecraft.World/Blocks/WoodSlabTile.cpp index 2fb0d2ee1..b0d8b7abd 100644 --- a/Minecraft.World/Blocks/WoodSlabTile.cpp +++ b/Minecraft.World/Blocks/WoodSlabTile.cpp @@ -7,54 +7,48 @@ #include "../Headers/net.minecraft.world.item.h" #include "../Headers/net.minecraft.stats.h" -const unsigned int WoodSlabTile::SLAB_NAMES[SLAB_NAMES_LENGTH] = { IDS_TILE_STONESLAB_OAK, - IDS_TILE_STONESLAB_SPRUCE, - IDS_TILE_STONESLAB_BIRCH, - IDS_TILE_STONESLAB_JUNGLE, +const unsigned int WoodSlabTile::SLAB_NAMES[SLAB_NAMES_LENGTH] = { + IDS_TILE_STONESLAB_OAK, + IDS_TILE_STONESLAB_SPRUCE, + IDS_TILE_STONESLAB_BIRCH, + IDS_TILE_STONESLAB_JUNGLE, }; // public static final String[] WOOD_NAMES = { // "oak", "spruce", "birch", "jungle" // }; -WoodSlabTile::WoodSlabTile(int id, bool fullSize) : HalfSlabTile(id, fullSize, Material::wood) -{ +WoodSlabTile::WoodSlabTile(int id, bool fullSize) + : HalfSlabTile(id, fullSize, Material::wood) {} + +Icon* WoodSlabTile::getTexture(int face, int data) { + return Tile::wood->getTexture(face, data & TYPE_MASK); } -Icon *WoodSlabTile::getTexture(int face, int data) -{ - return Tile::wood->getTexture(face, data & TYPE_MASK); +int WoodSlabTile::getResource(int data, Random* random, int playerBonusLevel) { + return Tile::woodSlabHalf_Id; } -int WoodSlabTile::getResource(int data, Random *random, int playerBonusLevel) -{ - return Tile::woodSlabHalf_Id; +std::shared_ptr WoodSlabTile::getSilkTouchItemInstance(int data) { + return std::shared_ptr( + new ItemInstance(Tile::woodSlabHalf, 2, data & TYPE_MASK)); } -std::shared_ptr WoodSlabTile::getSilkTouchItemInstance(int data) -{ - return std::shared_ptr(new ItemInstance(Tile::woodSlabHalf, 2, data & TYPE_MASK)); +int WoodSlabTile::getAuxName(int auxValue) { + if (auxValue < 0 || auxValue >= SLAB_NAMES_LENGTH) { + auxValue = 0; + } + return SLAB_NAMES[auxValue]; // super.getDescriptionId() + "." + + // SLAB_NAMES[auxValue]; } -int WoodSlabTile::getAuxName(int auxValue) -{ - if (auxValue < 0 || auxValue >= SLAB_NAMES_LENGTH) - { - auxValue = 0; - } - return SLAB_NAMES[auxValue];//super.getDescriptionId() + "." + SLAB_NAMES[auxValue]; +void WoodSlabTile::registerIcons(IconRegister* iconRegister) { + // None } -void WoodSlabTile::registerIcons(IconRegister *iconRegister) -{ - // None -} - -unsigned int WoodSlabTile::getDescriptionId(int iData) -{ - if (iData < 0 || iData >= SLAB_NAMES_LENGTH) - { - iData = 0; - } - return SLAB_NAMES[iData]; +unsigned int WoodSlabTile::getDescriptionId(int iData) { + if (iData < 0 || iData >= SLAB_NAMES_LENGTH) { + iData = 0; + } + return SLAB_NAMES[iData]; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/WoodSlabTile.h b/Minecraft.World/Blocks/WoodSlabTile.h index c683f87b9..49c78b16c 100644 --- a/Minecraft.World/Blocks/WoodSlabTile.h +++ b/Minecraft.World/Blocks/WoodSlabTile.h @@ -5,24 +5,23 @@ class Player; -class WoodSlabTile : HalfSlabTile -{ +class WoodSlabTile : HalfSlabTile { + friend class Tile; - friend class Tile; public: - static const int TYPE_MASK = 7; - static const int TOP_SLOT_BIT = 8; - static const int SLAB_NAMES_LENGTH = 4; - static const unsigned int SLAB_NAMES[SLAB_NAMES_LENGTH]; + static const int TYPE_MASK = 7; + static const int TOP_SLOT_BIT = 8; + static const int SLAB_NAMES_LENGTH = 4; + static const unsigned int SLAB_NAMES[SLAB_NAMES_LENGTH]; - WoodSlabTile(int id, bool fullSize); - virtual Icon *getTexture(int face, int data); - virtual int getResource(int data, Random *random, int playerBonusLevel); - virtual int getAuxName(int auxValue); + WoodSlabTile(int id, bool fullSize); + virtual Icon* getTexture(int face, int data); + virtual int getResource(int data, Random* random, int playerBonusLevel); + virtual int getAuxName(int auxValue); - virtual std::shared_ptr getSilkTouchItemInstance(int data); - void registerIcons(IconRegister *iconRegister); - - // 4J added - virtual unsigned int getDescriptionId(int iData = -1); + virtual std::shared_ptr getSilkTouchItemInstance(int data); + void registerIcons(IconRegister* iconRegister); + + // 4J added + virtual unsigned int getDescriptionId(int iData = -1); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WoodTile.cpp b/Minecraft.World/Blocks/WoodTile.cpp index fa9af638c..3b6d9699f 100644 --- a/Minecraft.World/Blocks/WoodTile.cpp +++ b/Minecraft.World/Blocks/WoodTile.cpp @@ -7,50 +7,41 @@ #include "../Headers/net.minecraft.stats.h" #include "../Headers/net.minecraft.world.h" -const unsigned int WoodTile::WOOD_NAMES[WOOD_NAMES_LENGTH] = { IDS_TILE_OAKWOOD_PLANKS, - IDS_TILE_SPRUCEWOOD_PLANKS, - IDS_TILE_BIRCHWOOD_PLANKS, - IDS_TILE_JUNGLE_PLANKS, +const unsigned int WoodTile::WOOD_NAMES[WOOD_NAMES_LENGTH] = { + IDS_TILE_OAKWOOD_PLANKS, + IDS_TILE_SPRUCEWOOD_PLANKS, + IDS_TILE_BIRCHWOOD_PLANKS, + IDS_TILE_JUNGLE_PLANKS, }; -const std::wstring WoodTile::TEXTURE_NAMES[] = {L"wood", L"wood_spruce", L"wood_birch", L"wood_jungle"}; +const std::wstring WoodTile::TEXTURE_NAMES[] = {L"wood", L"wood_spruce", + L"wood_birch", L"wood_jungle"}; // public static final String[] WOOD_NAMES = { // "oak", "spruce", "birch", "jungle" // }; -WoodTile::WoodTile(int id) : Tile(id, Material::wood) -{ - icons = NULL; +WoodTile::WoodTile(int id) : Tile(id, Material::wood) { icons = NULL; } + +unsigned int WoodTile::getDescriptionId(int iData) { + if (iData < 0 || iData >= WOOD_NAMES_LENGTH) iData = 0; + + return WOOD_NAMES[iData]; } -unsigned int WoodTile::getDescriptionId(int iData) -{ - if(iData < 0 || iData >= WOOD_NAMES_LENGTH) iData = 0; - - return WOOD_NAMES[iData]; +Icon* WoodTile::getTexture(int face, int data) { + if (data < 0 || data >= WOOD_NAMES_LENGTH) { + data = 0; + } + return icons[data]; } -Icon *WoodTile::getTexture(int face, int data) -{ - if (data < 0 || data >= WOOD_NAMES_LENGTH) - { - data = 0; - } - return icons[data]; -} +int WoodTile::getSpawnResourcesAuxValue(int data) { return data; } -int WoodTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} +void WoodTile::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[WOOD_NAMES_LENGTH]; -void WoodTile::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon*[WOOD_NAMES_LENGTH]; - - for (int i = 0; i < WOOD_NAMES_LENGTH; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); - } + for (int i = 0; i < WOOD_NAMES_LENGTH; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_NAMES[i]); + } } \ No newline at end of file diff --git a/Minecraft.World/Blocks/WoodTile.h b/Minecraft.World/Blocks/WoodTile.h index a380d934d..5f133b4c8 100644 --- a/Minecraft.World/Blocks/WoodTile.h +++ b/Minecraft.World/Blocks/WoodTile.h @@ -3,24 +3,23 @@ class ChunkRebuildData; -class WoodTile : public Tile -{ -friend class ChunkRebuildData; +class WoodTile : public Tile { + friend class ChunkRebuildData; + public: - static const int WOOD_NAMES_LENGTH = 4; + static const int WOOD_NAMES_LENGTH = 4; - - static const unsigned int WOOD_NAMES[WOOD_NAMES_LENGTH]; - static const std::wstring TEXTURE_NAMES[]; + static const unsigned int WOOD_NAMES[WOOD_NAMES_LENGTH]; + static const std::wstring TEXTURE_NAMES[]; private: - Icon **icons; + Icon** icons; public: - WoodTile(int id); + WoodTile(int id); virtual unsigned int getDescriptionId(int iData = -1); - virtual Icon *getTexture(int face, int data) ; - virtual int getSpawnResourcesAuxValue(int data); + virtual Icon* getTexture(int face, int data); + virtual int getSpawnResourcesAuxValue(int data); - void registerIcons(IconRegister *iconRegister); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WoolCarpetTile.cpp b/Minecraft.World/Blocks/WoolCarpetTile.cpp index e3ff5cde1..79d3ba931 100644 --- a/Minecraft.World/Blocks/WoolCarpetTile.cpp +++ b/Minecraft.World/Blocks/WoolCarpetTile.cpp @@ -4,108 +4,85 @@ #include "../Util/SharedConstants.h" #include "WoolCarpetTile.h" -WoolCarpetTile::WoolCarpetTile(int id) : Tile(id, Material::clothDecoration, false) -{ - setShape(0, 0, 0, 1, 1 / 16.0f, 1); - setTicking(true); - updateShape(0); +WoolCarpetTile::WoolCarpetTile(int id) + : Tile(id, Material::clothDecoration, false) { + setShape(0, 0, 0, 1, 1 / 16.0f, 1); + setTicking(true); + updateShape(0); } -Icon *WoolCarpetTile::getTexture(int face, int data) -{ - return Tile::cloth->getTexture(face, data); +Icon* WoolCarpetTile::getTexture(int face, int data) { + return Tile::cloth->getTexture(face, data); } -AABB *WoolCarpetTile::getAABB(Level *level, int x, int y, int z) -{ - int height = 0; - float offset = 1.0f / SharedConstants::WORLD_RESOLUTION; - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); - // 4J Stu - Added this so that the TLS shape is correct for this tile - if(tls->tileId != this->id) updateDefaultShape(); - return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + (height * offset), z + tls->zz1); +AABB* WoolCarpetTile::getAABB(Level* level, int x, int y, int z) { + int height = 0; + float offset = 1.0f / SharedConstants::WORLD_RESOLUTION; + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(Tile::tlsIdxShape); + // 4J Stu - Added this so that the TLS shape is correct for this tile + if (tls->tileId != this->id) updateDefaultShape(); + return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, + y + (height * offset), z + tls->zz1); } -bool WoolCarpetTile::blocksLight() -{ - return false; +bool WoolCarpetTile::blocksLight() { return false; } + +bool WoolCarpetTile::isSolidRender(bool isServerLevel) { return false; } + +bool WoolCarpetTile::isCubeShaped() { return false; } + +void WoolCarpetTile::updateDefaultShape() { updateShape(0); } + +void WoolCarpetTile::updateShape(LevelSource* level, int x, int y, int z, + int forceData, + std::shared_ptr forceEntity) { + updateShape(level->getData(x, y, z)); } -bool WoolCarpetTile::isSolidRender(bool isServerLevel) -{ - return false; +void WoolCarpetTile::updateShape(int data) { + int height = 0; + float o = 1 * (1 + height) / 16.0f; + setShape(0, 0, 0, 1, o, 1); } -bool WoolCarpetTile::isCubeShaped() -{ - return false; +bool WoolCarpetTile::mayPlace(Level* level, int x, int y, int z) { + return Tile::mayPlace(level, x, y, z) && canSurvive(level, x, y, z); } -void WoolCarpetTile::updateDefaultShape() -{ - updateShape(0); +void WoolCarpetTile::neighborChanged(Level* level, int x, int y, int z, + int type) { + checkCanSurvive(level, x, y, z); } -void WoolCarpetTile::updateShape(LevelSource *level, int x, int y, int z, int forceData, std::shared_ptr forceEntity) -{ - updateShape(level->getData(x, y, z)); +bool WoolCarpetTile::checkCanSurvive(Level* level, int x, int y, int z) { + if (!canSurvive(level, x, y, z)) { + spawnResources(level, x, y, z, level->getData(x, y, z), 0); + level->setTile(x, y, z, 0); + return false; + } + return true; } -void WoolCarpetTile::updateShape(int data) -{ - int height = 0; - float o = 1 * (1 + height) / 16.0f; - setShape(0, 0, 0, 1, o, 1); +bool WoolCarpetTile::canSurvive(Level* level, int x, int y, int z) { + return !level->isEmptyTile(x, y - 1, z); } -bool WoolCarpetTile::mayPlace(Level *level, int x, int y, int z) -{ - return Tile::mayPlace(level, x, y, z) && canSurvive(level, x, y, z); +bool WoolCarpetTile::shouldRenderFace(LevelSource* level, int x, int y, int z, + int face) { + if (face == 1) return true; + return Tile::shouldRenderFace(level, x, y, z, face); } -void WoolCarpetTile::neighborChanged(Level *level, int x, int y, int z, int type) -{ - checkCanSurvive(level, x, y, z); +int WoolCarpetTile::getSpawnResourcesAuxValue(int data) { return data; } + +int WoolCarpetTile::getTileDataForItemAuxValue(int auxValue) { + return (~auxValue & 0xf); } -bool WoolCarpetTile::checkCanSurvive(Level *level, int x, int y, int z) -{ - if (!canSurvive(level, x, y, z)) - { - spawnResources(level, x, y, z, level->getData(x, y, z), 0); - level->setTile(x, y, z, 0); - return false; - } - return true; +int WoolCarpetTile::getItemAuxValueForTileData(int data) { + return (~data & 0xf); } -bool WoolCarpetTile::canSurvive(Level *level, int x, int y, int z) -{ - return !level->isEmptyTile(x, y - 1, z); -} - -bool WoolCarpetTile::shouldRenderFace(LevelSource *level, int x, int y, int z, int face) -{ - if (face == 1) return true; - return Tile::shouldRenderFace(level, x, y, z, face); -} - -int WoolCarpetTile::getSpawnResourcesAuxValue(int data) -{ - return data; -} - -int WoolCarpetTile::getTileDataForItemAuxValue(int auxValue) -{ - return (~auxValue & 0xf); -} - -int WoolCarpetTile::getItemAuxValueForTileData(int data) -{ - return (~data & 0xf); -} - -void WoolCarpetTile::registerIcons(IconRegister *iconRegister) -{ - // None, delegates to cloth tile +void WoolCarpetTile::registerIcons(IconRegister* iconRegister) { + // None, delegates to cloth tile } diff --git a/Minecraft.World/Blocks/WoolCarpetTile.h b/Minecraft.World/Blocks/WoolCarpetTile.h index ef84514cb..7ad28797c 100644 --- a/Minecraft.World/Blocks/WoolCarpetTile.h +++ b/Minecraft.World/Blocks/WoolCarpetTile.h @@ -2,36 +2,39 @@ #include "Tile.h" -class WoolCarpetTile : public Tile -{ - friend class Tile; -protected: - WoolCarpetTile(int id); - -public: - Icon *getTexture(int face, int data); - AABB *getAABB(Level *level, int x, int y, int z); - bool blocksLight(); - bool isSolidRender(bool isServerLevel = false); - bool isCubeShaped(); - void updateDefaultShape(); - void updateShape(LevelSource *level, int x, int y, int z, int forceData = -1, std::shared_ptr forceEntity = std::shared_ptr()); +class WoolCarpetTile : public Tile { + friend class Tile; protected: - void updateShape(int data); + WoolCarpetTile(int id); public: - bool mayPlace(Level *level, int x, int y, int z); - void neighborChanged(Level *level, int x, int y, int z, int type); + Icon* getTexture(int face, int data); + AABB* getAABB(Level* level, int x, int y, int z); + bool blocksLight(); + bool isSolidRender(bool isServerLevel = false); + bool isCubeShaped(); + void updateDefaultShape(); + void updateShape(LevelSource* level, int x, int y, int z, + int forceData = -1, + std::shared_ptr forceEntity = + std::shared_ptr()); + +protected: + void updateShape(int data); + +public: + bool mayPlace(Level* level, int x, int y, int z); + void neighborChanged(Level* level, int x, int y, int z, int type); private: - bool checkCanSurvive(Level *level, int x, int y, int z); + bool checkCanSurvive(Level* level, int x, int y, int z); public: - bool canSurvive(Level *level, int x, int y, int z); - bool shouldRenderFace(LevelSource *level, int x, int y, int z, int face); - int getSpawnResourcesAuxValue(int data); - static int getTileDataForItemAuxValue(int auxValue); - static int getItemAuxValueForTileData(int data); - void registerIcons(IconRegister *iconRegister); + bool canSurvive(Level* level, int x, int y, int z); + bool shouldRenderFace(LevelSource* level, int x, int y, int z, int face); + int getSpawnResourcesAuxValue(int data); + static int getTileDataForItemAuxValue(int auxValue); + static int getItemAuxValueForTileData(int data); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Blocks/WorkbenchTile.cpp b/Minecraft.World/Blocks/WorkbenchTile.cpp index 3734b9748..916fe8ee1 100644 --- a/Minecraft.World/Blocks/WorkbenchTile.cpp +++ b/Minecraft.World/Blocks/WorkbenchTile.cpp @@ -5,40 +5,36 @@ #include "../Headers/net.minecraft.h" #include "WorkbenchTile.h" -WorkbenchTile::WorkbenchTile(int id) : Tile(id, Material::wood) -{ - iconTop = NULL; - iconFront = NULL; +WorkbenchTile::WorkbenchTile(int id) : Tile(id, Material::wood) { + iconTop = NULL; + iconFront = NULL; } -Icon *WorkbenchTile::getTexture(int face, int data) -{ - if (face == Facing::UP) return iconTop; - if (face == Facing::DOWN) return Tile::wood->getTexture(face); - if (face == Facing::NORTH || face == Facing::WEST) return iconFront; - return icon; +Icon* WorkbenchTile::getTexture(int face, int data) { + if (face == Facing::UP) return iconTop; + if (face == Facing::DOWN) return Tile::wood->getTexture(face); + if (face == Facing::NORTH || face == Facing::WEST) return iconFront; + return icon; } -void WorkbenchTile::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"workbench_side"); - iconTop = iconRegister->registerIcon(L"workbench_top"); - iconFront = iconRegister->registerIcon(L"workbench_front"); +void WorkbenchTile::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"workbench_side"); + iconTop = iconRegister->registerIcon(L"workbench_top"); + iconFront = iconRegister->registerIcon(L"workbench_front"); } // 4J-PB - Adding a TestUse for tooltip display -bool WorkbenchTile::TestUse() -{ - return true; -} +bool WorkbenchTile::TestUse() { return true; } -bool WorkbenchTile::use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly/*=false*/) // 4J added soundOnly param +bool WorkbenchTile::use(Level* level, int x, int y, int z, + std::shared_ptr player, int clickedFace, + float clickX, float clickY, float clickZ, + bool soundOnly /*=false*/) // 4J added soundOnly param { - if( soundOnly ) return false; - if (level->isClientSide) - { - return true; - } - player->startCrafting(x, y, z); - return true; + if (soundOnly) return false; + if (level->isClientSide) { + return true; + } + player->startCrafting(x, y, z); + return true; } \ No newline at end of file diff --git a/Minecraft.World/Blocks/WorkbenchTile.h b/Minecraft.World/Blocks/WorkbenchTile.h index bbbdcb85e..4a8e6d40a 100644 --- a/Minecraft.World/Blocks/WorkbenchTile.h +++ b/Minecraft.World/Blocks/WorkbenchTile.h @@ -5,22 +5,24 @@ class Player; class ChunkRebuildData; -class WorkbenchTile : public Tile -{ - friend class Tile; - friend class ChunkRebuildData; +class WorkbenchTile : public Tile { + friend class Tile; + friend class ChunkRebuildData; + private: - Icon *iconTop; - Icon *iconFront; + Icon* iconTop; + Icon* iconFront; protected: - WorkbenchTile(int id); + WorkbenchTile(int id); public: - Icon *getTexture(int face, int data); - void registerIcons(IconRegister *iconRegister); + Icon* getTexture(int face, int data); + void registerIcons(IconRegister* iconRegister); public: - virtual bool TestUse(); - bool use(Level *level, int x, int y, int z, std::shared_ptr player, int clickedFace, float clickX, float clickY, float clickZ, bool soundOnly = false); // 4J added soundOnly param + virtual bool TestUse(); + bool use(Level* level, int x, int y, int z, std::shared_ptr player, + int clickedFace, float clickX, float clickY, float clickZ, + bool soundOnly = false); // 4J added soundOnly param }; \ No newline at end of file diff --git a/Minecraft.World/Commands/AdminLogCommand.h b/Minecraft.World/Commands/AdminLogCommand.h index f3d4a483b..6b1d0e177 100644 --- a/Minecraft.World/Commands/AdminLogCommand.h +++ b/Minecraft.World/Commands/AdminLogCommand.h @@ -4,10 +4,13 @@ class CommandSender; -class AdminLogCommand -{ +class AdminLogCommand { public: - static const int LOGTYPE_DONT_SHOW_TO_SELF = 1; + static const int LOGTYPE_DONT_SHOW_TO_SELF = 1; - virtual void logAdminCommand(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L"") = 0; + virtual void logAdminCommand( + std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message = L"", int customData = -1, + const std::wstring& additionalMessage = L"") = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Commands/Command.cpp b/Minecraft.World/Commands/Command.cpp index 54dd8cc83..8da161daa 100644 --- a/Minecraft.World/Commands/Command.cpp +++ b/Minecraft.World/Commands/Command.cpp @@ -5,41 +5,39 @@ #include "../../Minecraft.Client/Player/ServerPlayer.h" #include "Command.h" -AdminLogCommand *Command::logger; +AdminLogCommand* Command::logger; -bool Command::canExecute(std::shared_ptr source) -{ - return source->hasPermission(getId()); +bool Command::canExecute(std::shared_ptr source) { + return source->hasPermission(getId()); } -void Command::logAdminAction(std::shared_ptr source, ChatPacket::EChatPacketMessage messageType, const std::wstring& message, int customData, const std::wstring& additionalMessage) -{ - logAdminAction(source, 0, messageType, message, customData, additionalMessage); +void Command::logAdminAction(std::shared_ptr source, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message, int customData, + const std::wstring& additionalMessage) { + logAdminAction(source, 0, messageType, message, customData, + additionalMessage); } -void Command::logAdminAction(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message, int customData, const std::wstring& additionalMessage) -{ - if (logger != NULL) - { - logger->logAdminCommand(source, type, messageType, message, customData, additionalMessage); - } +void Command::logAdminAction(std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message, int customData, + const std::wstring& additionalMessage) { + if (logger != NULL) { + logger->logAdminCommand(source, type, messageType, message, customData, + additionalMessage); + } } -void Command::setLogger(AdminLogCommand *logger) -{ - Command::logger = logger; -} +void Command::setLogger(AdminLogCommand* logger) { Command::logger = logger; } -std::shared_ptr Command::getPlayer(PlayerUID playerId) -{ - std::shared_ptr player = MinecraftServer::getInstance()->getPlayers()->getPlayer(playerId); +std::shared_ptr Command::getPlayer(PlayerUID playerId) { + std::shared_ptr player = + MinecraftServer::getInstance()->getPlayers()->getPlayer(playerId); - if (player == NULL) - { - return nullptr; - } - else - { - return player; - } + if (player == NULL) { + return nullptr; + } else { + return player; + } } diff --git a/Minecraft.World/Commands/Command.h b/Minecraft.World/Commands/Command.h index a0db21851..4667f6cec 100644 --- a/Minecraft.World/Commands/Command.h +++ b/Minecraft.World/Commands/Command.h @@ -9,20 +9,28 @@ class AdminLogCommand; class CommandSender; class ServerPlayer; -class Command -{ +class Command { private: - static AdminLogCommand *logger; + static AdminLogCommand* logger; public: - virtual EGameCommand getId() = 0; - virtual void execute(std::shared_ptr source, byteArray commandData) = 0; - virtual bool canExecute(std::shared_ptr source); + virtual EGameCommand getId() = 0; + virtual void execute(std::shared_ptr source, + byteArray commandData) = 0; + virtual bool canExecute(std::shared_ptr source); - static void logAdminAction(std::shared_ptr source, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L""); - static void logAdminAction(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L""); - static void setLogger(AdminLogCommand *logger); + static void logAdminAction(std::shared_ptr source, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message = L"", + int customData = -1, + const std::wstring& additionalMessage = L""); + static void logAdminAction(std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message = L"", + int customData = -1, + const std::wstring& additionalMessage = L""); + static void setLogger(AdminLogCommand* logger); protected: - std::shared_ptr getPlayer(PlayerUID playerId); + std::shared_ptr getPlayer(PlayerUID playerId); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/CommandDispatcher.cpp b/Minecraft.World/Commands/CommandDispatcher.cpp index a492a6f38..499391256 100644 --- a/Minecraft.World/Commands/CommandDispatcher.cpp +++ b/Minecraft.World/Commands/CommandDispatcher.cpp @@ -2,33 +2,28 @@ #include "../Headers/net.minecraft.commands.h" #include "CommandDispatcher.h" -void CommandDispatcher::performCommand(std::shared_ptr sender, EGameCommand command, byteArray commandData) -{ - AUTO_VAR(it, commandsById.find(command)); +void CommandDispatcher::performCommand(std::shared_ptr sender, + EGameCommand command, + byteArray commandData) { + AUTO_VAR(it, commandsById.find(command)); - if(it != commandsById.end()) - { - Command *command = it->second; - if (command->canExecute(sender)) - { - command->execute(sender, commandData); - } - else - { + if (it != commandsById.end()) { + Command* command = it->second; + if (command->canExecute(sender)) { + command->execute(sender, commandData); + } else { #ifndef _CONTENT_PACKAGE - sender->sendMessage(L"\u00A7cYou do not have permission to use this command."); + sender->sendMessage( + L"\u00A7cYou do not have permission to use this command."); #endif - } - } - else - { - app.DebugPrintf("Command %d not found!\n", command); - } + } + } else { + app.DebugPrintf("Command %d not found!\n", command); + } } -Command *CommandDispatcher::addCommand(Command *command) -{ - commandsById[command->getId()] = command; - commands.insert(command); - return command; +Command* CommandDispatcher::addCommand(Command* command) { + commandsById[command->getId()] = command; + commands.insert(command); + return command; } diff --git a/Minecraft.World/Commands/CommandDispatcher.h b/Minecraft.World/Commands/CommandDispatcher.h index 4b8ed3cf9..b84d37513 100644 --- a/Minecraft.World/Commands/CommandDispatcher.h +++ b/Minecraft.World/Commands/CommandDispatcher.h @@ -3,17 +3,17 @@ class Command; class CommandSender; -class CommandDispatcher -{ +class CommandDispatcher { private: #ifdef __ORBIS__ - std::unordered_map> commandsById; + std::unordered_map> commandsById; #else - std::unordered_map commandsById; + std::unordered_map commandsById; #endif - std::unordered_set commands; + std::unordered_set commands; public: - void performCommand(std::shared_ptr sender, EGameCommand command, byteArray commandData); - Command *addCommand(Command *command); + void performCommand(std::shared_ptr sender, + EGameCommand command, byteArray commandData); + Command* addCommand(Command* command); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/CommandSender.h b/Minecraft.World/Commands/CommandSender.h index 1484fec21..e2271d21d 100644 --- a/Minecraft.World/Commands/CommandSender.h +++ b/Minecraft.World/Commands/CommandSender.h @@ -3,10 +3,12 @@ #include "CommandsEnum.h" #include "../Network/Packets/ChatPacket.h" -class CommandSender -{ +class CommandSender { public: - //virtual int getUID() = 0; - virtual void sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L"") = 0; - virtual bool hasPermission(EGameCommand command) = 0; + // virtual int getUID() = 0; + virtual void sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, + int customData = -1, const std::wstring& additionalMessage = L"") = 0; + virtual bool hasPermission(EGameCommand command) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Commands/CommandsEnum.h b/Minecraft.World/Commands/CommandsEnum.h index 46793e214..3c86dd80e 100644 --- a/Minecraft.World/Commands/CommandsEnum.h +++ b/Minecraft.World/Commands/CommandsEnum.h @@ -1,15 +1,14 @@ #pragma once -enum EGameCommand -{ - eGameCommand_DefaultGameMode, - eGameCommand_EnchantItem, - eGameCommand_Experience, - eGameCommand_GameMode, - eGameCommand_Give, - eGameCommand_Kill, - eGameCommand_Time, - eGameCommand_ToggleDownfall, - eGameCommand_Teleport, - eGameCommand_COUNT +enum EGameCommand { + eGameCommand_DefaultGameMode, + eGameCommand_EnchantItem, + eGameCommand_Experience, + eGameCommand_GameMode, + eGameCommand_Give, + eGameCommand_Kill, + eGameCommand_Time, + eGameCommand_ToggleDownfall, + eGameCommand_Teleport, + eGameCommand_COUNT }; \ No newline at end of file diff --git a/Minecraft.World/Commands/DefaultGameModeCommand.cpp b/Minecraft.World/Commands/DefaultGameModeCommand.cpp index ba8bc48a6..1ceae7732 100644 --- a/Minecraft.World/Commands/DefaultGameModeCommand.cpp +++ b/Minecraft.World/Commands/DefaultGameModeCommand.cpp @@ -2,25 +2,23 @@ #include "../Headers/net.minecraft.commands.h" #include "DefaultGameModeCommand.h" -EGameCommand DefaultGameModeCommand::getId() -{ - return eGameCommand_DefaultGameMode; +EGameCommand DefaultGameModeCommand::getId() { + return eGameCommand_DefaultGameMode; } -void DefaultGameModeCommand::execute(std::shared_ptr source, byteArray commandData) -{ - //if (args.length > 0) - //{ - // GameType newMode = getModeForString(source, args[0]); - // doSetGameType(newMode); +void DefaultGameModeCommand::execute(std::shared_ptr source, + byteArray commandData) { + // if (args.length > 0) + //{ + // GameType newMode = getModeForString(source, args[0]); + // doSetGameType(newMode); - // String modeName = I18n.get("gameMode." + newMode.getName()); - // logAdminAction(source, "commands.defaultgamemode.success", modeName); + // String modeName = I18n.get("gameMode." + newMode.getName()); + // logAdminAction(source, "commands.defaultgamemode.success", modeName); - //} + //} } -void DefaultGameModeCommand::doSetGameType(GameType *newGameType) -{ - //MinecraftServer::getInstance()->setDefaultGameMode(newGameType); +void DefaultGameModeCommand::doSetGameType(GameType* newGameType) { + // MinecraftServer::getInstance()->setDefaultGameMode(newGameType); } \ No newline at end of file diff --git a/Minecraft.World/Commands/DefaultGameModeCommand.h b/Minecraft.World/Commands/DefaultGameModeCommand.h index 01a41331c..476f6ed4e 100644 --- a/Minecraft.World/Commands/DefaultGameModeCommand.h +++ b/Minecraft.World/Commands/DefaultGameModeCommand.h @@ -4,12 +4,12 @@ class GameType; -class DefaultGameModeCommand : public GameModeCommand -{ +class DefaultGameModeCommand : public GameModeCommand { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); protected: - void doSetGameType(GameType *newGameType); + void doSetGameType(GameType* newGameType); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/EnchantItemCommand.cpp b/Minecraft.World/Commands/EnchantItemCommand.cpp index 2bb61b277..9de07abb5 100644 --- a/Minecraft.World/Commands/EnchantItemCommand.cpp +++ b/Minecraft.World/Commands/EnchantItemCommand.cpp @@ -5,81 +5,81 @@ #include "../../Minecraft.Client/Player/ServerPlayer.h" #include "EnchantItemCommand.h" -EGameCommand EnchantItemCommand::getId() -{ - return eGameCommand_EnchantItem; +EGameCommand EnchantItemCommand::getId() { return eGameCommand_EnchantItem; } + +int EnchantItemCommand::getPermissionLevel() { + return 0; // aLEVEL_GAMEMASTERS; } -int EnchantItemCommand::getPermissionLevel() -{ - return 0; //aLEVEL_GAMEMASTERS; +void EnchantItemCommand::execute(std::shared_ptr source, + byteArray commandData) { + ByteArrayInputStream bais(commandData); + DataInputStream dis(&bais); + + PlayerUID uid = dis.readPlayerUID(); + int enchantmentId = dis.readInt(); + int enchantmentLevel = dis.readInt(); + + bais.reset(); + + std::shared_ptr player = getPlayer(uid); + + if (player == NULL) return; + + std::shared_ptr selectedItem = player->getSelectedItem(); + + if (selectedItem == NULL) return; + + Enchantment* e = Enchantment::enchantments[enchantmentId]; + + if (e == NULL) return; + if (!e->canEnchant(selectedItem)) return; + + if (enchantmentLevel < e->getMinLevel()) + enchantmentLevel = e->getMinLevel(); + if (enchantmentLevel > e->getMaxLevel()) + enchantmentLevel = e->getMaxLevel(); + + if (selectedItem->hasTag()) { + ListTag* enchantmentTags = + selectedItem->getEnchantmentTags(); + if (enchantmentTags != NULL) { + for (int i = 0; i < enchantmentTags->size(); i++) { + int type = enchantmentTags->get(i)->getShort( + (wchar_t*)ItemInstance::TAG_ENCH_ID); + + if (Enchantment::enchantments[type] != NULL) { + Enchantment* other = Enchantment::enchantments[type]; + if (!other->isCompatibleWith(e)) { + return; + // throw new + // CommandException("commands.enchant.cantCombine", + // e.getFullname(level), + // other.getFullname(enchantmentTags.get(i).getShort(ItemInstance.TAG_ENCH_LEVEL))); + } + } + } + } + } + + selectedItem->enchant(e, enchantmentLevel); + + // logAdminAction(source, "commands.enchant.success"); + logAdminAction(source, ChatPacket::e_ChatCustom, + L"commands.enchant.success"); } -void EnchantItemCommand::execute(std::shared_ptr source, byteArray commandData) -{ - ByteArrayInputStream bais(commandData); - DataInputStream dis(&bais); +std::shared_ptr EnchantItemCommand::preparePacket( + std::shared_ptr player, int enchantmentId, int enchantmentLevel) { + if (player == NULL) return nullptr; - PlayerUID uid = dis.readPlayerUID(); - int enchantmentId = dis.readInt(); - int enchantmentLevel = dis.readInt(); + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); - bais.reset(); + dos.writePlayerUID(player->getXuid()); + dos.writeInt(enchantmentId); + dos.writeInt(enchantmentLevel); - std::shared_ptr player = getPlayer(uid); - - if(player == NULL) return; - - std::shared_ptr selectedItem = player->getSelectedItem(); - - if(selectedItem == NULL) return; - - Enchantment *e = Enchantment::enchantments[enchantmentId]; - - if(e == NULL) return; - if(!e->canEnchant(selectedItem)) return; - - if(enchantmentLevel < e->getMinLevel()) enchantmentLevel = e->getMinLevel(); - if(enchantmentLevel > e->getMaxLevel()) enchantmentLevel = e->getMaxLevel(); - - if (selectedItem->hasTag()) - { - ListTag *enchantmentTags = selectedItem->getEnchantmentTags(); - if (enchantmentTags != NULL) - { - for (int i = 0; i < enchantmentTags->size(); i++) - { - int type = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - - if (Enchantment::enchantments[type] != NULL) - { - Enchantment *other = Enchantment::enchantments[type]; - if (!other->isCompatibleWith(e)) - { - return; - //throw new CommandException("commands.enchant.cantCombine", e.getFullname(level), other.getFullname(enchantmentTags.get(i).getShort(ItemInstance.TAG_ENCH_LEVEL))); - } - } - } - } - } - - selectedItem->enchant(e, enchantmentLevel); - - //logAdminAction(source, "commands.enchant.success"); - logAdminAction(source, ChatPacket::e_ChatCustom, L"commands.enchant.success"); -} - -std::shared_ptr EnchantItemCommand::preparePacket(std::shared_ptr player, int enchantmentId, int enchantmentLevel) -{ - if(player == NULL) return nullptr; - - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - - dos.writePlayerUID(player->getXuid()); - dos.writeInt(enchantmentId); - dos.writeInt(enchantmentLevel); - - return std::shared_ptr( new GameCommandPacket(eGameCommand_EnchantItem, baos.toByteArray() )); + return std::shared_ptr( + new GameCommandPacket(eGameCommand_EnchantItem, baos.toByteArray())); } diff --git a/Minecraft.World/Commands/EnchantItemCommand.h b/Minecraft.World/Commands/EnchantItemCommand.h index 6792da537..87f186484 100644 --- a/Minecraft.World/Commands/EnchantItemCommand.h +++ b/Minecraft.World/Commands/EnchantItemCommand.h @@ -4,12 +4,14 @@ class GameCommandPacket; -class EnchantItemCommand : public Command -{ +class EnchantItemCommand : public Command { public: - virtual EGameCommand getId(); - int getPermissionLevel(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + int getPermissionLevel(); + virtual void execute(std::shared_ptr source, + byteArray commandData); - static std::shared_ptr preparePacket(std::shared_ptr player, int enchantmentId, int enchantmentLevel = 1); + static std::shared_ptr preparePacket( + std::shared_ptr player, int enchantmentId, + int enchantmentLevel = 1); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/ExperienceCommand.cpp b/Minecraft.World/Commands/ExperienceCommand.cpp index a0004549a..73fd19ed8 100644 --- a/Minecraft.World/Commands/ExperienceCommand.cpp +++ b/Minecraft.World/Commands/ExperienceCommand.cpp @@ -4,38 +4,36 @@ #include "../../Minecraft.Client/Network/PlayerList.h" #include "ExperienceCommand.h" -EGameCommand ExperienceCommand::getId() -{ - return eGameCommand_Experience; +EGameCommand ExperienceCommand::getId() { return eGameCommand_Experience; } + +void ExperienceCommand::execute(std::shared_ptr source, + byteArray commandData) { + // if (args.length > 0) + //{ + // Player player; + // int amount = convertArgToInt(source, args[0], 0, 5000); + + // if (args.length > 1) { + // player = getPlayer(args[1]); + // } else { + // player = convertSourceToPlayer(source); + // } + + // player.increaseXp(amount); + // logAdminAction(source, "commands.xp.success", amount, + //player.getAName()); + //} } -void ExperienceCommand::execute(std::shared_ptr source, byteArray commandData) -{ - //if (args.length > 0) - //{ - // Player player; - // int amount = convertArgToInt(source, args[0], 0, 5000); +std::shared_ptr ExperienceCommand::getPlayer(PlayerUID playerId) { + return nullptr; + // std::shared_ptr player = + // MinecraftServer::getInstance()->getPlayers()->getPlayer(playerId); - // if (args.length > 1) { - // player = getPlayer(args[1]); - // } else { - // player = convertSourceToPlayer(source); - // } - - // player.increaseXp(amount); - // logAdminAction(source, "commands.xp.success", amount, player.getAName()); - //} -} - -std::shared_ptr ExperienceCommand::getPlayer(PlayerUID playerId) -{ - return nullptr; - //std::shared_ptr player = MinecraftServer::getInstance()->getPlayers()->getPlayer(playerId); - - //if (player == null) - //{ - // throw new PlayerNotFoundException(); - //} else { - // return player; - //} + // if (player == null) + //{ + // throw new PlayerNotFoundException(); + // } else { + // return player; + // } } diff --git a/Minecraft.World/Commands/ExperienceCommand.h b/Minecraft.World/Commands/ExperienceCommand.h index 5165428fe..0f4564b94 100644 --- a/Minecraft.World/Commands/ExperienceCommand.h +++ b/Minecraft.World/Commands/ExperienceCommand.h @@ -4,12 +4,12 @@ class CommandSender; -class ExperienceCommand : public Command -{ +class ExperienceCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); protected: - std::shared_ptr getPlayer(PlayerUID playerId); + std::shared_ptr getPlayer(PlayerUID playerId); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/GameModeCommand.cpp b/Minecraft.World/Commands/GameModeCommand.cpp index 0e53fa110..9d8d208dd 100644 --- a/Minecraft.World/Commands/GameModeCommand.cpp +++ b/Minecraft.World/Commands/GameModeCommand.cpp @@ -2,52 +2,53 @@ #include "../Headers/net.minecraft.commands.h" #include "GameModeCommand.h" -EGameCommand GameModeCommand::getId() -{ - return eGameCommand_GameMode; +EGameCommand GameModeCommand::getId() { return eGameCommand_GameMode; } + +void GameModeCommand::execute(std::shared_ptr source, + byteArray commandData) { + // if (args.length > 0) + //{ + // GameType newMode = getModeForString(source, args[0]); + // Player player = args.length >= 2 ? getPlayer(args[1]) : + //convertSourceToPlayer(source); + + // player.setGameMode(newMode); + + // String mode = I18n.get("gameMode." + newMode.getName()); + + // if (player != source) { + // logAdminAction(source, + //AdminLogCommand.LOGTYPE_DONT_SHOW_TO_SELF, + //"commands.gamemode.success.other", player.getAName(), mode); } else { + // logAdminAction(source, + //AdminLogCommand.LOGTYPE_DONT_SHOW_TO_SELF, + //"commands.gamemode.success.self", mode); + // } + //} } -void GameModeCommand::execute(std::shared_ptr source, byteArray commandData) -{ - //if (args.length > 0) - //{ - // GameType newMode = getModeForString(source, args[0]); - // Player player = args.length >= 2 ? getPlayer(args[1]) : convertSourceToPlayer(source); - - // player.setGameMode(newMode); - - // String mode = I18n.get("gameMode." + newMode.getName()); - - // if (player != source) { - // logAdminAction(source, AdminLogCommand.LOGTYPE_DONT_SHOW_TO_SELF, "commands.gamemode.success.other", player.getAName(), mode); - // } else { - // logAdminAction(source, AdminLogCommand.LOGTYPE_DONT_SHOW_TO_SELF, "commands.gamemode.success.self", mode); - // } - //} +GameType* GameModeCommand::getModeForString( + std::shared_ptr source, const std::wstring& name) { + return NULL; + // if (name.equalsIgnoreCase(GameType.SURVIVAL.getName()) || + // name.equalsIgnoreCase("s")) { return GameType.SURVIVAL; } else if + // (name.equalsIgnoreCase(GameType.CREATIVE.getName()) || + // name.equalsIgnoreCase("c")) { return GameType.CREATIVE; } else if + // (name.equalsIgnoreCase(GameType.ADVENTURE.getName()) || + // name.equalsIgnoreCase("a")) { return GameType.ADVENTURE; } else { return + //LevelSettings.validateGameType(convertArgToInt(source, name, 0, + //GameType.values().length - 2)); + // } } -GameType *GameModeCommand::getModeForString(std::shared_ptr source, const std::wstring &name) -{ - return NULL; - //if (name.equalsIgnoreCase(GameType.SURVIVAL.getName()) || name.equalsIgnoreCase("s")) { - // return GameType.SURVIVAL; - //} else if (name.equalsIgnoreCase(GameType.CREATIVE.getName()) || name.equalsIgnoreCase("c")) { - // return GameType.CREATIVE; - //} else if (name.equalsIgnoreCase(GameType.ADVENTURE.getName()) || name.equalsIgnoreCase("a")) { - // return GameType.ADVENTURE; - //} else { - // return LevelSettings.validateGameType(convertArgToInt(source, name, 0, GameType.values().length - 2)); - //} -} +std::shared_ptr GameModeCommand::getPlayer(PlayerUID playerId) { + return nullptr; + // Player player = + // MinecraftServer.getInstance().getPlayers().getPlayer(name); -std::shared_ptr GameModeCommand::getPlayer(PlayerUID playerId) -{ - return nullptr; - //Player player = MinecraftServer.getInstance().getPlayers().getPlayer(name); - - //if (player == null) { - // throw new PlayerNotFoundException(); - //} else { - // return player; - //} + // if (player == null) { + // throw new PlayerNotFoundException(); + // } else { + // return player; + // } } \ No newline at end of file diff --git a/Minecraft.World/Commands/GameModeCommand.h b/Minecraft.World/Commands/GameModeCommand.h index 14a8490c8..ef0c4c0cd 100644 --- a/Minecraft.World/Commands/GameModeCommand.h +++ b/Minecraft.World/Commands/GameModeCommand.h @@ -4,13 +4,14 @@ class GameType; -class GameModeCommand : public Command -{ +class GameModeCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); protected: - GameType *getModeForString(std::shared_ptr source, const std::wstring &name); - std::shared_ptr getPlayer(PlayerUID playerId); + GameType* getModeForString(std::shared_ptr source, + const std::wstring& name); + std::shared_ptr getPlayer(PlayerUID playerId); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/GiveItemCommand.cpp b/Minecraft.World/Commands/GiveItemCommand.cpp index 65857f951..2e9435e3a 100644 --- a/Minecraft.World/Commands/GiveItemCommand.cpp +++ b/Minecraft.World/Commands/GiveItemCommand.cpp @@ -5,46 +5,48 @@ #include "../../Minecraft.Client/Player/ServerPlayer.h" #include "GiveItemCommand.h" -EGameCommand GiveItemCommand::getId() -{ - return eGameCommand_Give; +EGameCommand GiveItemCommand::getId() { return eGameCommand_Give; } + +void GiveItemCommand::execute(std::shared_ptr source, + byteArray commandData) { + ByteArrayInputStream bais(commandData); + DataInputStream dis(&bais); + + PlayerUID uid = dis.readPlayerUID(); + int item = dis.readInt(); + int amount = dis.readInt(); + int aux = dis.readInt(); + std::wstring tag = dis.readUTF(); + + bais.reset(); + + std::shared_ptr player = getPlayer(uid); + if (player != NULL && item > 0 && Item::items[item] != NULL) { + std::shared_ptr itemInstance = + std::shared_ptr(new ItemInstance(item, amount, aux)); + player->drop(itemInstance); + // logAdminAction(source, L"commands.give.success", + // ChatPacket::e_ChatCustom, Item::items[item]->getName(itemInstance), + // item, amount, player->getAName()); + logAdminAction(source, ChatPacket::e_ChatCustom, + L"commands.give.success", item, player->getAName()); + } } -void GiveItemCommand::execute(std::shared_ptr source, byteArray commandData) -{ - ByteArrayInputStream bais(commandData); - DataInputStream dis(&bais); +std::shared_ptr GiveItemCommand::preparePacket( + std::shared_ptr player, int item, int amount, int aux, + const std::wstring& tag) { + if (player == NULL) return nullptr; - PlayerUID uid = dis.readPlayerUID(); - int item = dis.readInt(); - int amount = dis.readInt(); - int aux = dis.readInt(); - std::wstring tag = dis.readUTF(); - - bais.reset(); + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); - std::shared_ptr player = getPlayer(uid); - if(player != NULL && item > 0 && Item::items[item] != NULL) - { - std::shared_ptr itemInstance = std::shared_ptr(new ItemInstance(item, amount, aux)); - player->drop(itemInstance); - //logAdminAction(source, L"commands.give.success", ChatPacket::e_ChatCustom, Item::items[item]->getName(itemInstance), item, amount, player->getAName()); - logAdminAction(source, ChatPacket::e_ChatCustom, L"commands.give.success", item, player->getAName()); - } -} - -std::shared_ptr GiveItemCommand::preparePacket(std::shared_ptr player, int item, int amount, int aux, const std::wstring &tag) -{ - if(player == NULL) return nullptr; - - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - - dos.writePlayerUID(player->getXuid()); - dos.writeInt(item); - dos.writeInt(amount); - dos.writeInt(aux); - dos.writeUTF(tag); - - return std::shared_ptr( new GameCommandPacket(eGameCommand_Give, baos.toByteArray() )); + dos.writePlayerUID(player->getXuid()); + dos.writeInt(item); + dos.writeInt(amount); + dos.writeInt(aux); + dos.writeUTF(tag); + + return std::shared_ptr( + new GameCommandPacket(eGameCommand_Give, baos.toByteArray())); } diff --git a/Minecraft.World/Commands/GiveItemCommand.h b/Minecraft.World/Commands/GiveItemCommand.h index 9297711f7..fbde95335 100644 --- a/Minecraft.World/Commands/GiveItemCommand.h +++ b/Minecraft.World/Commands/GiveItemCommand.h @@ -4,12 +4,14 @@ class GameCommandPacket; -class GiveItemCommand : public Command -{ +class GiveItemCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); public: - static std::shared_ptr preparePacket(std::shared_ptr player, int item, int amount = 1, int aux = 0, const std::wstring &tag = L""); + static std::shared_ptr preparePacket( + std::shared_ptr player, int item, int amount = 1, int aux = 0, + const std::wstring& tag = L""); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/KillCommand.cpp b/Minecraft.World/Commands/KillCommand.cpp index bb57de139..fc144fc00 100644 --- a/Minecraft.World/Commands/KillCommand.cpp +++ b/Minecraft.World/Commands/KillCommand.cpp @@ -4,16 +4,13 @@ #include "../Headers/net.minecraft.world.damagesource.h" #include "KillCommand.h" -EGameCommand KillCommand::getId() -{ - return eGameCommand_Kill; -} +EGameCommand KillCommand::getId() { return eGameCommand_Kill; } -void KillCommand::execute(std::shared_ptr source, byteArray commandData) -{ - std::shared_ptr player = std::dynamic_pointer_cast(source); +void KillCommand::execute(std::shared_ptr source, + byteArray commandData) { + std::shared_ptr player = std::dynamic_pointer_cast(source); - player->hurt(DamageSource::outOfWorld, 1000); + player->hurt(DamageSource::outOfWorld, 1000); - source->sendMessage(L"Ouch. That look like it hurt."); + source->sendMessage(L"Ouch. That look like it hurt."); } \ No newline at end of file diff --git a/Minecraft.World/Commands/KillCommand.h b/Minecraft.World/Commands/KillCommand.h index 21155b6ff..a274d6631 100644 --- a/Minecraft.World/Commands/KillCommand.h +++ b/Minecraft.World/Commands/KillCommand.h @@ -2,9 +2,9 @@ #include "Command.h" -class KillCommand : public Command -{ +class KillCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/TimeCommand.cpp b/Minecraft.World/Commands/TimeCommand.cpp index e81b7b300..88daf6b5a 100644 --- a/Minecraft.World/Commands/TimeCommand.cpp +++ b/Minecraft.World/Commands/TimeCommand.cpp @@ -5,76 +5,70 @@ #include "../Headers/net.minecraft.network.packet.h" #include "TimeCommand.h" -EGameCommand TimeCommand::getId() -{ - return eGameCommand_Time; +EGameCommand TimeCommand::getId() { return eGameCommand_Time; } + +void TimeCommand::execute(std::shared_ptr source, + byteArray commandData) { + ByteArrayInputStream bais(commandData); + DataInputStream dis(&bais); + + bool night = dis.readBoolean(); + + bais.reset(); + + int amount = 0; + if (night) amount = 12500; + doSetTime(source, amount); + // logAdminAction(source, "commands.time.set", amount); + logAdminAction(source, ChatPacket::e_ChatCustom, L"commands.time.set"); + + // if (args.length > 1) { + // if (args[0].equals("set")) { + // int amount; + + // if (args[1].equals("day")) { + // amount = 0; + // } else if (args[1].equals("night")) { + // amount = 12500; + // } else { + // amount = convertArgToInt(source, args[1], 0); + // } + + // doSetTime(source, amount); + // logAdminAction(source, "commands.time.set", amount); + // return; + // } else if (args[0].equals("add")) { + // int amount = convertArgToInt(source, args[1], 0); + // doAddTime(source, amount); + + // logAdminAction(source, "commands.time.added", amount); + // return; + // } + //} + + // throw new UsageException("commands.time.usage"); } -void TimeCommand::execute(std::shared_ptr source, byteArray commandData) -{ - ByteArrayInputStream bais(commandData); - DataInputStream dis(&bais); - - bool night = dis.readBoolean(); - - bais.reset(); - - int amount = 0; - if(night) amount = 12500; - doSetTime(source, amount); - //logAdminAction(source, "commands.time.set", amount); - logAdminAction(source, ChatPacket::e_ChatCustom, L"commands.time.set"); - - //if (args.length > 1) { - // if (args[0].equals("set")) { - // int amount; - - // if (args[1].equals("day")) { - // amount = 0; - // } else if (args[1].equals("night")) { - // amount = 12500; - // } else { - // amount = convertArgToInt(source, args[1], 0); - // } - - // doSetTime(source, amount); - // logAdminAction(source, "commands.time.set", amount); - // return; - // } else if (args[0].equals("add")) { - // int amount = convertArgToInt(source, args[1], 0); - // doAddTime(source, amount); - - // logAdminAction(source, "commands.time.added", amount); - // return; - // } - //} - - //throw new UsageException("commands.time.usage"); +void TimeCommand::doSetTime(std::shared_ptr source, int value) { + for (int i = 0; i < MinecraftServer::getInstance()->levels.length; i++) { + MinecraftServer::getInstance()->levels[i]->setTimeAndAdjustTileTicks( + value); + } } -void TimeCommand::doSetTime(std::shared_ptr source, int value) -{ - for (int i = 0; i < MinecraftServer::getInstance()->levels.length; i++) - { - MinecraftServer::getInstance()->levels[i]->setTimeAndAdjustTileTicks(value); - } +void TimeCommand::doAddTime(std::shared_ptr source, int value) { + for (int i = 0; i < MinecraftServer::getInstance()->levels.length; i++) { + ServerLevel* level = MinecraftServer::getInstance()->levels[i]; + level->setTimeAndAdjustTileTicks(level->getTime() + value); + } } -void TimeCommand::doAddTime(std::shared_ptr source, int value) -{ - for (int i = 0; i < MinecraftServer::getInstance()->levels.length; i++) - { - ServerLevel *level = MinecraftServer::getInstance()->levels[i]; - level->setTimeAndAdjustTileTicks(level->getTime() + value); - } -} - -std::shared_ptr TimeCommand::preparePacket(bool night) -{ - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - - dos.writeBoolean(night); - - return std::shared_ptr( new GameCommandPacket(eGameCommand_Time, baos.toByteArray() )); +std::shared_ptr TimeCommand::preparePacket(bool night) { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); + + dos.writeBoolean(night); + + return std::shared_ptr( + new GameCommandPacket(eGameCommand_Time, baos.toByteArray())); } diff --git a/Minecraft.World/Commands/TimeCommand.h b/Minecraft.World/Commands/TimeCommand.h index da7008b2a..dac94253f 100644 --- a/Minecraft.World/Commands/TimeCommand.h +++ b/Minecraft.World/Commands/TimeCommand.h @@ -2,16 +2,16 @@ #include "Command.h" -class TimeCommand : public Command -{ +class TimeCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); protected: - void doSetTime(std::shared_ptr source, int value); - void doAddTime(std::shared_ptr source, int value); + void doSetTime(std::shared_ptr source, int value); + void doAddTime(std::shared_ptr source, int value); public: - static std::shared_ptr preparePacket(bool night); + static std::shared_ptr preparePacket(bool night); }; \ No newline at end of file diff --git a/Minecraft.World/Commands/ToggleDownfallCommand.cpp b/Minecraft.World/Commands/ToggleDownfallCommand.cpp index df4157495..466e8dcb4 100644 --- a/Minecraft.World/Commands/ToggleDownfallCommand.cpp +++ b/Minecraft.World/Commands/ToggleDownfallCommand.cpp @@ -7,24 +7,24 @@ #include "../Headers/net.minecraft.network.packet.h" #include "ToggleDownfallCommand.h" -EGameCommand ToggleDownfallCommand::getId() -{ - return eGameCommand_ToggleDownfall; +EGameCommand ToggleDownfallCommand::getId() { + return eGameCommand_ToggleDownfall; } -void ToggleDownfallCommand::execute(std::shared_ptr source, byteArray commandData) -{ - doToggleDownfall(); - logAdminAction(source, ChatPacket::e_ChatCustom, L"commands.downfall.success"); +void ToggleDownfallCommand::execute(std::shared_ptr source, + byteArray commandData) { + doToggleDownfall(); + logAdminAction(source, ChatPacket::e_ChatCustom, + L"commands.downfall.success"); } -void ToggleDownfallCommand::doToggleDownfall() -{ - MinecraftServer::getInstance()->levels[0]->toggleDownfall(); - MinecraftServer::getInstance()->levels[0]->getLevelData()->setThundering(true); +void ToggleDownfallCommand::doToggleDownfall() { + MinecraftServer::getInstance()->levels[0]->toggleDownfall(); + MinecraftServer::getInstance()->levels[0]->getLevelData()->setThundering( + true); } -std::shared_ptr ToggleDownfallCommand::preparePacket() -{ - return std::shared_ptr( new GameCommandPacket(eGameCommand_ToggleDownfall, byteArray() )); +std::shared_ptr ToggleDownfallCommand::preparePacket() { + return std::shared_ptr( + new GameCommandPacket(eGameCommand_ToggleDownfall, byteArray())); } diff --git a/Minecraft.World/Commands/ToggleDownfallCommand.h b/Minecraft.World/Commands/ToggleDownfallCommand.h index a19b72519..19ea908fc 100644 --- a/Minecraft.World/Commands/ToggleDownfallCommand.h +++ b/Minecraft.World/Commands/ToggleDownfallCommand.h @@ -3,15 +3,15 @@ class GameCommandPacket; -class ToggleDownfallCommand : public Command -{ +class ToggleDownfallCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); protected: - void doToggleDownfall(); + void doToggleDownfall(); public: - static std::shared_ptr preparePacket(); + static std::shared_ptr preparePacket(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/AbstractContainerMenu.cpp b/Minecraft.World/Containers/AbstractContainerMenu.cpp index 4bdf7d53f..b084acc5a 100644 --- a/Minecraft.World/Containers/AbstractContainerMenu.cpp +++ b/Minecraft.World/Containers/AbstractContainerMenu.cpp @@ -4,534 +4,453 @@ #include "Slot.h" #include "AbstractContainerMenu.h" -// 4J Stu - The java does not have ctor here (being an abstract) but we need one to initialise the member variables +// 4J Stu - The java does not have ctor here (being an abstract) but we need one +// to initialise the member variables // TODO Make sure all derived classes also call this -AbstractContainerMenu::AbstractContainerMenu() -{ - lastSlots = new std::vector >(); - slots = new std::vector(); - containerId = 0; +AbstractContainerMenu::AbstractContainerMenu() { + lastSlots = new std::vector >(); + slots = new std::vector(); + containerId = 0; - changeUid = 0; - m_bNeedsRendered = false; + changeUid = 0; + m_bNeedsRendered = false; - containerListeners = new std::vector(); + containerListeners = new std::vector(); } -AbstractContainerMenu::~AbstractContainerMenu() -{ - delete lastSlots; - for( unsigned int i = 0; i < slots->size(); i++ ) - { - delete slots->at(i); - } - delete slots; - delete containerListeners; +AbstractContainerMenu::~AbstractContainerMenu() { + delete lastSlots; + for (unsigned int i = 0; i < slots->size(); i++) { + delete slots->at(i); + } + delete slots; + delete containerListeners; } -Slot *AbstractContainerMenu::addSlot(Slot *slot) -{ - slot->index = (int)slots->size(); - slots->push_back(slot); - lastSlots->push_back(nullptr); - return slot; +Slot* AbstractContainerMenu::addSlot(Slot* slot) { + slot->index = (int)slots->size(); + slots->push_back(slot); + lastSlots->push_back(nullptr); + return slot; } +void AbstractContainerMenu::addSlotListener(ContainerListener* listener) { + // TODO 4J Add exceptions + /* + if (containerListeners->contains(listener)) { + throw new IllegalArgumentException("Listener already listening"); + } + */ + containerListeners->push_back(listener); -void AbstractContainerMenu::addSlotListener(ContainerListener *listener) -{ - // TODO 4J Add exceptions - /* - if (containerListeners->contains(listener)) { - throw new IllegalArgumentException("Listener already listening"); - } - */ - containerListeners->push_back(listener); - - - std::vector > *items = getItems(); - listener->refreshContainer(this, items); - delete items; - broadcastChanges(); + std::vector >* items = getItems(); + listener->refreshContainer(this, items); + delete items; + broadcastChanges(); } -std::vector > *AbstractContainerMenu::getItems() -{ - std::vector > *items = new std::vector >(); - AUTO_VAR(itEnd, slots->end()); - for (AUTO_VAR(it, slots->begin()); it != itEnd; it++) - { - items->push_back((*it)->getItem()); - } - return items; +std::vector >* AbstractContainerMenu::getItems() { + std::vector >* items = + new std::vector >(); + AUTO_VAR(itEnd, slots->end()); + for (AUTO_VAR(it, slots->begin()); it != itEnd; it++) { + items->push_back((*it)->getItem()); + } + return items; } -void AbstractContainerMenu::sendData(int id, int value) -{ - AUTO_VAR(itEnd, containerListeners->end()); - for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) - { - (*it)->setContainerData(this, id, value); - } +void AbstractContainerMenu::sendData(int id, int value) { + AUTO_VAR(itEnd, containerListeners->end()); + for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) { + (*it)->setContainerData(this, id, value); + } } -void AbstractContainerMenu::broadcastChanges() -{ - for (unsigned int i = 0; i < slots->size(); i++) - { - std::shared_ptr current = slots->at(i)->getItem(); - std::shared_ptr expected = lastSlots->at(i); - if (!ItemInstance::matches(expected, current)) - { - expected = current == NULL ? nullptr : current->copy(); - (*lastSlots)[i] = expected; - m_bNeedsRendered = true; +void AbstractContainerMenu::broadcastChanges() { + for (unsigned int i = 0; i < slots->size(); i++) { + std::shared_ptr current = slots->at(i)->getItem(); + std::shared_ptr expected = lastSlots->at(i); + if (!ItemInstance::matches(expected, current)) { + expected = current == NULL ? nullptr : current->copy(); + (*lastSlots)[i] = expected; + m_bNeedsRendered = true; - AUTO_VAR(itEnd, containerListeners->end()); - for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) - { - (*it)->slotChanged(this, i, expected); - } - } - } + AUTO_VAR(itEnd, containerListeners->end()); + for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) { + (*it)->slotChanged(this, i, expected); + } + } + } } -bool AbstractContainerMenu::needsRendered() -{ - bool needsRendered = m_bNeedsRendered; - m_bNeedsRendered = false; +bool AbstractContainerMenu::needsRendered() { + bool needsRendered = m_bNeedsRendered; + m_bNeedsRendered = false; - for (unsigned int i = 0; i < slots->size(); i++) - { - std::shared_ptr current = slots->at(i)->getItem(); - std::shared_ptr expected = lastSlots->at(i); - if (!ItemInstance::matches(expected, current)) - { - expected = current == NULL ? nullptr : current->copy(); - (*lastSlots)[i] = expected; - needsRendered = true; - } - } + for (unsigned int i = 0; i < slots->size(); i++) { + std::shared_ptr current = slots->at(i)->getItem(); + std::shared_ptr expected = lastSlots->at(i); + if (!ItemInstance::matches(expected, current)) { + expected = current == NULL ? nullptr : current->copy(); + (*lastSlots)[i] = expected; + needsRendered = true; + } + } - return needsRendered; + return needsRendered; } -bool AbstractContainerMenu::clickMenuButton(std::shared_ptr player, int buttonId) -{ - return false; +bool AbstractContainerMenu::clickMenuButton(std::shared_ptr player, + int buttonId) { + return false; } -Slot *AbstractContainerMenu::getSlotFor(std::shared_ptr c, int index) -{ - AUTO_VAR(itEnd, slots->end()); - for (AUTO_VAR(it, slots->begin()); it != itEnd; it++) - { - Slot *slot = *it; //slots->at(i); - if (slot->isAt(c, index)) - { - return slot; - } - } - return NULL; +Slot* AbstractContainerMenu::getSlotFor(std::shared_ptr c, + int index) { + AUTO_VAR(itEnd, slots->end()); + for (AUTO_VAR(it, slots->begin()); it != itEnd; it++) { + Slot* slot = *it; // slots->at(i); + if (slot->isAt(c, index)) { + return slot; + } + } + return NULL; } -Slot *AbstractContainerMenu::getSlot(int index) -{ - return slots->at(index); +Slot* AbstractContainerMenu::getSlot(int index) { return slots->at(index); } + +std::shared_ptr AbstractContainerMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + Slot* slot = slots->at(slotIndex); + if (slot != NULL) { + return slot->getItem(); + } + return nullptr; } -std::shared_ptr AbstractContainerMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - Slot *slot = slots->at(slotIndex); - if (slot != NULL) - { - return slot->getItem(); - } - return nullptr; -} +std::shared_ptr AbstractContainerMenu::clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player) { + std::shared_ptr clickedEntity = nullptr; + std::shared_ptr inventory = player->inventory; -std::shared_ptr AbstractContainerMenu::clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player) -{ - std::shared_ptr clickedEntity = nullptr; - std::shared_ptr inventory = player->inventory; + if ((clickType == CLICK_PICKUP || clickType == CLICK_QUICK_MOVE) && + (buttonNum == 0 || buttonNum == 1)) { + if (slotIndex == CLICKED_OUTSIDE) { + if (inventory->getCarried() != NULL) { + if (slotIndex == CLICKED_OUTSIDE) { + if (buttonNum == 0) { + player->drop(inventory->getCarried()); + inventory->setCarried(nullptr); + } + if (buttonNum == 1) { + player->drop(inventory->getCarried()->remove(1)); + if (inventory->getCarried()->count == 0) + inventory->setCarried(nullptr); + } + } + } + } else if (clickType == CLICK_QUICK_MOVE) { + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->mayPickup(player)) { + std::shared_ptr piiClicked = + quickMoveStack(player, slotIndex); + if (piiClicked != NULL) { + // int oldSize = piiClicked->count; // 4J - Commented 1.8.2 + // and replaced with below + int oldType = piiClicked->id; - if ((clickType == CLICK_PICKUP || clickType == CLICK_QUICK_MOVE) && (buttonNum == 0 || buttonNum == 1)) - { - if (slotIndex == CLICKED_OUTSIDE) - { - if (inventory->getCarried() != NULL) - { - if (slotIndex == CLICKED_OUTSIDE) - { - if (buttonNum == 0) - { - player->drop(inventory->getCarried()); - inventory->setCarried(nullptr); - } - if (buttonNum == 1) - { - player->drop(inventory->getCarried()->remove(1)); - if (inventory->getCarried()->count == 0) inventory->setCarried(nullptr); - } + clickedEntity = piiClicked->copy(); - } - } - } - else if (clickType == CLICK_QUICK_MOVE) - { - Slot *slot = slots->at(slotIndex); - if(slot != NULL && slot->mayPickup(player)) - { - std::shared_ptr piiClicked = quickMoveStack(player, slotIndex); - if (piiClicked != NULL) - { - //int oldSize = piiClicked->count; // 4J - Commented 1.8.2 and replaced with below - int oldType = piiClicked->id; + if (slot != NULL) { + if (slot->getItem() != NULL && + slot->getItem()->id == oldType) { + // 4J Stu - Brought forward loopClick from 1.2 to + // fix infinite recursion bug in creative + loopClick(slotIndex, buttonNum, true, player); + } + } + } + } + } else { + if (slotIndex < 0) return nullptr; - clickedEntity = piiClicked->copy(); + Slot* slot = slots->at(slotIndex); + if (slot != NULL) { + std::shared_ptr clicked = slot->getItem(); + std::shared_ptr carried = inventory->getCarried(); - if (slot != NULL) - { - if (slot->getItem() != NULL && slot->getItem()->id == oldType) - { - // 4J Stu - Brought forward loopClick from 1.2 to fix infinite recursion bug in creative - loopClick(slotIndex, buttonNum, true, player); - } - } - } - } - } - else - { - if (slotIndex < 0) return nullptr; + if (clicked != NULL) { + clickedEntity = clicked->copy(); + } - Slot *slot = slots->at(slotIndex); - if (slot != NULL) - { - std::shared_ptr clicked = slot->getItem(); - std::shared_ptr carried = inventory->getCarried(); + if (clicked == NULL) { + if (carried != NULL && slot->mayPlace(carried)) { + int c = buttonNum == 0 ? carried->count : 1; + if (c > slot->getMaxStackSize()) { + c = slot->getMaxStackSize(); + } + slot->set(carried->remove(c)); + if (carried->count == 0) { + inventory->setCarried(nullptr); + } + } + } + // 4J Added for dyable armour and combinining damaged items + else if (buttonNum == 1 && mayCombine(slot, carried)) { + std::shared_ptr combined = + slot->combine(carried); + if (combined != NULL) { + slot->set(combined); + if (!player->abilities.instabuild) carried->remove(1); + if (carried->count == 0) { + inventory->setCarried(nullptr); + } + } + } else if (slot->mayPickup(player)) { + if (carried == NULL) { + // pick up to empty hand + int c = buttonNum == 0 ? clicked->count + : (clicked->count + 1) / 2; + std::shared_ptr removed = slot->remove(c); - if (clicked != NULL) - { - clickedEntity = clicked->copy(); - } + inventory->setCarried(removed); + if (clicked->count == 0) { + slot->set(nullptr); + } + slot->onTake(player, inventory->getCarried()); + } else if (slot->mayPlace(carried)) { + // put down and/or pick up + if (clicked->id != carried->id || + clicked->getAuxValue() != carried->getAuxValue() || + !ItemInstance::tagMatches(clicked, carried)) { + // no match, replace + if (carried->count <= slot->getMaxStackSize()) { + slot->set(carried); + inventory->setCarried(clicked); + } + } else { + // match, attempt to fill slot + int c = buttonNum == 0 ? carried->count : 1; + if (c > slot->getMaxStackSize() - clicked->count) { + c = slot->getMaxStackSize() - clicked->count; + } + if (c > + carried->getMaxStackSize() - clicked->count) { + c = carried->getMaxStackSize() - clicked->count; + } + carried->remove(c); + if (carried->count == 0) { + inventory->setCarried(nullptr); + } + clicked->count += c; + } + } else { + // pick up to non-empty hand + if (clicked->id == carried->id && + carried->getMaxStackSize() > 1 && + (!clicked->isStackedByData() || + clicked->getAuxValue() == + carried->getAuxValue()) && + ItemInstance::tagMatches(clicked, carried)) { + int c = clicked->count; + if (c > 0 && c + carried->count <= + carried->getMaxStackSize()) { + carried->count += c; + clicked = slot->remove(c); + if (clicked->count == 0) slot->set(nullptr); + slot->onTake(player, inventory->getCarried()); + } + } + } + } + slot->setChanged(); + } + } + } else if (clickType == CLICK_SWAP && buttonNum >= 0 && buttonNum < 9) { + Slot* slot = slots->at(slotIndex); + if (slot->mayPickup(player)) { + std::shared_ptr current = + inventory->getItem(buttonNum); + bool canMove = current == NULL || (slot->container == inventory && + slot->mayPlace(current)); + int freeSlot = -1; - if (clicked == NULL) - { - if (carried != NULL && slot->mayPlace(carried)) - { - int c = buttonNum == 0 ? carried->count : 1; - if (c > slot->getMaxStackSize()) - { - c = slot->getMaxStackSize(); - } - slot->set(carried->remove(c)); - if (carried->count == 0) - { - inventory->setCarried(nullptr); - } - } - } - // 4J Added for dyable armour and combinining damaged items - else if (buttonNum == 1 && mayCombine(slot, carried)) - { - std::shared_ptr combined = slot->combine(carried); - if(combined != NULL) - { - slot->set(combined); - if(!player->abilities.instabuild) carried->remove(1); - if (carried->count == 0) - { - inventory->setCarried(nullptr); - } - } - } - else if (slot->mayPickup(player)) - { - if (carried == NULL) - { - // pick up to empty hand - int c = buttonNum == 0 ? clicked->count : (clicked->count + 1) / 2; - std::shared_ptr removed = slot->remove(c); + if (!canMove) { + freeSlot = inventory->getFreeSlot(); + canMove |= freeSlot > -1; + } - inventory->setCarried(removed); - if (clicked->count == 0) - { - slot->set(nullptr); - } - slot->onTake(player, inventory->getCarried()); - } - else if (slot->mayPlace(carried)) - { - // put down and/or pick up - if (clicked->id != carried->id || clicked->getAuxValue() != carried->getAuxValue() || !ItemInstance::tagMatches(clicked, carried)) - { - // no match, replace - if (carried->count <= slot->getMaxStackSize()) - { - slot->set(carried); - inventory->setCarried(clicked); - } - } - else - { - // match, attempt to fill slot - int c = buttonNum == 0 ? carried->count : 1; - if (c > slot->getMaxStackSize() - clicked->count) - { - c = slot->getMaxStackSize() - clicked->count; - } - if (c > carried->getMaxStackSize() - clicked->count) - { - c = carried->getMaxStackSize() - clicked->count; - } - carried->remove(c); - if (carried->count == 0) - { - inventory->setCarried(nullptr); - } - clicked->count += c; - } - } - else - { - // pick up to non-empty hand - if (clicked->id == carried->id && carried->getMaxStackSize() > 1 && (!clicked->isStackedByData() || clicked->getAuxValue() == carried->getAuxValue()) - && ItemInstance::tagMatches(clicked, carried)) - { - int c = clicked->count; - if (c > 0 && c + carried->count <= carried->getMaxStackSize()) - { - carried->count += c; - clicked = slot->remove(c); - if (clicked->count == 0) slot->set(nullptr); - slot->onTake(player, inventory->getCarried()); - } - } - } + if (slot->hasItem() && canMove) { + std::shared_ptr taking = slot->getItem(); + inventory->setItem(buttonNum, taking); - - } - slot->setChanged(); - } - } - } - else if (clickType == CLICK_SWAP && buttonNum >= 0 && buttonNum < 9) - { - Slot *slot = slots->at(slotIndex); - if (slot->mayPickup(player)) - { - std::shared_ptr current = inventory->getItem(buttonNum); - bool canMove = current == NULL || (slot->container == inventory && slot->mayPlace(current)); - int freeSlot = -1; - - if (!canMove) - { - freeSlot = inventory->getFreeSlot(); - canMove |= freeSlot > -1; - } - - if (slot->hasItem() && canMove) - { - std::shared_ptr taking = slot->getItem(); - inventory->setItem(buttonNum, taking); - - if ((slot->container == inventory && slot->mayPlace(current)) || current == NULL) - { - slot->remove(taking->count); - slot->set(current); - slot->onTake(player, taking); - } - else if (freeSlot > -1) - { - inventory->add(current); - slot->remove(taking->count); - slot->set(nullptr); - slot->onTake(player, taking); - } - } - else if (!slot->hasItem() && current != NULL && slot->mayPlace(current)) - { - inventory->setItem(buttonNum, nullptr); - slot->set(current); - } - } - } - else if (clickType == CLICK_CLONE && player->abilities.instabuild && inventory->getCarried() == NULL && slotIndex >= 0) - { - Slot *slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr copy = slot->getItem()->copy(); - copy->count = copy->getMaxStackSize(); - inventory->setCarried(copy); - } - } - return clickedEntity; + if ((slot->container == inventory && slot->mayPlace(current)) || + current == NULL) { + slot->remove(taking->count); + slot->set(current); + slot->onTake(player, taking); + } else if (freeSlot > -1) { + inventory->add(current); + slot->remove(taking->count); + slot->set(nullptr); + slot->onTake(player, taking); + } + } else if (!slot->hasItem() && current != NULL && + slot->mayPlace(current)) { + inventory->setItem(buttonNum, nullptr); + slot->set(current); + } + } + } else if (clickType == CLICK_CLONE && player->abilities.instabuild && + inventory->getCarried() == NULL && slotIndex >= 0) { + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr copy = slot->getItem()->copy(); + copy->count = copy->getMaxStackSize(); + inventory->setCarried(copy); + } + } + return clickedEntity; } // 4J Stu - Brought forward from 1.2 to fix infinite recursion bug in creative -void AbstractContainerMenu::loopClick(int slotIndex, int buttonNum, bool quickKeyHeld, std::shared_ptr player) -{ - clicked(slotIndex, buttonNum, CLICK_QUICK_MOVE, player); +void AbstractContainerMenu::loopClick(int slotIndex, int buttonNum, + bool quickKeyHeld, + std::shared_ptr player) { + clicked(slotIndex, buttonNum, CLICK_QUICK_MOVE, player); } -bool AbstractContainerMenu::mayCombine(Slot *slot, std::shared_ptr item) -{ - return false; +bool AbstractContainerMenu::mayCombine(Slot* slot, + std::shared_ptr item) { + return false; } -void AbstractContainerMenu::removed(std::shared_ptr player) -{ - std::shared_ptr inventory = player->inventory; - if (inventory->getCarried() != NULL) - { - player->drop(inventory->getCarried()); - inventory->setCarried(nullptr); - } +void AbstractContainerMenu::removed(std::shared_ptr player) { + std::shared_ptr inventory = player->inventory; + if (inventory->getCarried() != NULL) { + player->drop(inventory->getCarried()); + inventory->setCarried(nullptr); + } } -void AbstractContainerMenu::slotsChanged()// 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things +void AbstractContainerMenu:: + slotsChanged() // 4J used to take a std::shared_ptr but wasn't + // using it, so removed to simplify things { - broadcastChanges(); + broadcastChanges(); } -bool AbstractContainerMenu::isPauseScreen() -{ - return false; +bool AbstractContainerMenu::isPauseScreen() { return false; } + +void AbstractContainerMenu::setItem(unsigned int slot, + std::shared_ptr item) { + getSlot(slot)->set(item); } -void AbstractContainerMenu::setItem(unsigned int slot, std::shared_ptr item) -{ - getSlot(slot)->set(item); +void AbstractContainerMenu::setAll(ItemInstanceArray* items) { + for (unsigned int i = 0; i < items->length; i++) { + getSlot(i)->set((*items)[i]); + } } -void AbstractContainerMenu::setAll(ItemInstanceArray *items) -{ - for (unsigned int i = 0; i < items->length; i++) - { - getSlot(i)->set( (*items)[i] ); - } +void AbstractContainerMenu::setData(int id, int value) {} + +short AbstractContainerMenu::backup(std::shared_ptr inventory) { + changeUid++; + return changeUid; } -void AbstractContainerMenu::setData(int id, int value) -{ +bool AbstractContainerMenu::isSynched(std::shared_ptr player) { + return !(unSynchedPlayers.find(player) != unSynchedPlayers.end()); } -short AbstractContainerMenu::backup(std::shared_ptr inventory) -{ - changeUid++; - return changeUid; +void AbstractContainerMenu::setSynched(std::shared_ptr player, + bool synched) { + if (synched) { + AUTO_VAR(it, unSynchedPlayers.find(player)); + + if (it != unSynchedPlayers.end()) unSynchedPlayers.erase(it); + } else { + unSynchedPlayers.insert(player); + } } -bool AbstractContainerMenu::isSynched(std::shared_ptr player) -{ - return !(unSynchedPlayers.find(player) != unSynchedPlayers.end()); +// 4J Stu - Brought a few changes in this function forward from 1.2 to make it +// return a bool +bool AbstractContainerMenu::moveItemStackTo( + std::shared_ptr itemStack, int startSlot, int endSlot, + bool backwards) { + bool anythingChanged = false; + + int destSlot = startSlot; + if (backwards) { + destSlot = endSlot - 1; + } + + // find stackable slots first + if (itemStack->isStackable()) { + while (itemStack->count > 0 && ((!backwards && destSlot < endSlot) || + (backwards && destSlot >= startSlot))) { + Slot* slot = slots->at(destSlot); + std::shared_ptr target = slot->getItem(); + if (target != NULL && target->id == itemStack->id && + (!itemStack->isStackedByData() || + itemStack->getAuxValue() == target->getAuxValue()) && + ItemInstance::tagMatches(itemStack, target)) { + int totalStack = target->count + itemStack->count; + if (totalStack <= itemStack->getMaxStackSize()) { + itemStack->count = 0; + target->count = totalStack; + slot->setChanged(); + anythingChanged = true; + } else if (target->count < itemStack->getMaxStackSize()) { + itemStack->count -= + (itemStack->getMaxStackSize() - target->count); + target->count = itemStack->getMaxStackSize(); + slot->setChanged(); + anythingChanged = true; + } + } + + if (backwards) { + destSlot--; + } else { + destSlot++; + } + } + } + + // find empty slot + if (itemStack->count > 0) { + if (backwards) { + destSlot = endSlot - 1; + } else { + destSlot = startSlot; + } + while ((!backwards && destSlot < endSlot) || + (backwards && destSlot >= startSlot)) { + Slot* slot = slots->at(destSlot); + std::shared_ptr target = slot->getItem(); + + if (target == NULL) { + slot->set(itemStack->copy()); + slot->setChanged(); + itemStack->count = 0; + anythingChanged = true; + break; + } + + if (backwards) { + destSlot--; + } else { + destSlot++; + } + } + } + return anythingChanged; } -void AbstractContainerMenu::setSynched(std::shared_ptr player, bool synched) -{ - if (synched) - { - AUTO_VAR(it, unSynchedPlayers.find(player)); - - if(it != unSynchedPlayers.end()) unSynchedPlayers.erase( it ); - } - else - { - unSynchedPlayers.insert(player); - } -} - -// 4J Stu - Brought a few changes in this function forward from 1.2 to make it return a bool -bool AbstractContainerMenu::moveItemStackTo(std::shared_ptr itemStack, int startSlot, int endSlot, bool backwards) -{ - bool anythingChanged = false; - - int destSlot = startSlot; - if (backwards) - { - destSlot = endSlot - 1; - } - - // find stackable slots first - if (itemStack->isStackable()) - { - while (itemStack->count > 0 && ((!backwards && destSlot < endSlot) || (backwards && destSlot >= startSlot))) - { - - Slot *slot = slots->at(destSlot); - std::shared_ptr target = slot->getItem(); - if (target != NULL && target->id == itemStack->id && (!itemStack->isStackedByData() || itemStack->getAuxValue() == target->getAuxValue()) - && ItemInstance::tagMatches(itemStack, target) ) - { - int totalStack = target->count + itemStack->count; - if (totalStack <= itemStack->getMaxStackSize()) - { - itemStack->count = 0; - target->count = totalStack; - slot->setChanged(); - anythingChanged = true; - } - else if (target->count < itemStack->getMaxStackSize()) - { - itemStack->count -= (itemStack->getMaxStackSize() - target->count); - target->count = itemStack->getMaxStackSize(); - slot->setChanged(); - anythingChanged = true; - } - } - - if (backwards) - { - destSlot--; - } - else - { - destSlot++; - } - } - } - - // find empty slot - if (itemStack->count > 0) - { - if (backwards) - { - destSlot = endSlot - 1; - } - else - { - destSlot = startSlot; - } - while ((!backwards && destSlot < endSlot) || (backwards && destSlot >= startSlot)) - { - Slot *slot = slots->at(destSlot); - std::shared_ptr target = slot->getItem(); - - if (target == NULL) - { - slot->set(itemStack->copy()); - slot->setChanged(); - itemStack->count = 0; - anythingChanged = true; - break; - } - - if (backwards) - { - destSlot--; - } - else - { - destSlot++; - } - } - } - return anythingChanged; -} - -bool AbstractContainerMenu::isOverrideResultClick(int slotNum, int buttonNum) -{ - return false; +bool AbstractContainerMenu::isOverrideResultClick(int slotNum, int buttonNum) { + return false; } diff --git a/Minecraft.World/Containers/AbstractContainerMenu.h b/Minecraft.World/Containers/AbstractContainerMenu.h index 79ea26d11..fd3b1596b 100644 --- a/Minecraft.World/Containers/AbstractContainerMenu.h +++ b/Minecraft.World/Containers/AbstractContainerMenu.h @@ -1,6 +1,5 @@ #pragma once - #include "../Player/Player.h" #include "../Headers/net.minecraft.world.inventory.ContainerListener.h" using net_minecraft_world_inventory::ContainerListener; @@ -11,78 +10,88 @@ class Item; class ItemInstance; class Container; -class AbstractContainerMenu -{ +class AbstractContainerMenu { public: - static const int CLICKED_OUTSIDE = -999; + static const int CLICKED_OUTSIDE = -999; - static const int CLICK_PICKUP = 0; - static const int CLICK_QUICK_MOVE = 1; - static const int CLICK_SWAP = 2; - static const int CLICK_CLONE = 3; + static const int CLICK_PICKUP = 0; + static const int CLICK_QUICK_MOVE = 1; + static const int CLICK_SWAP = 2; + static const int CLICK_CLONE = 3; - // 4J Stu - Added these to fix problem with items picked up while in the creative menu replacing slots in the creative menu - static const int CONTAINER_ID_CARRIED = -1; - static const int CONTAINER_ID_INVENTORY = 0; - static const int CONTAINER_ID_CREATIVE = -2; + // 4J Stu - Added these to fix problem with items picked up while in the + // creative menu replacing slots in the creative menu + static const int CONTAINER_ID_CARRIED = -1; + static const int CONTAINER_ID_INVENTORY = 0; + static const int CONTAINER_ID_CREATIVE = -2; - std::vector > *lastSlots; - std::vector *slots; - int containerId; + std::vector >* lastSlots; + std::vector* slots; + int containerId; private: - short changeUid; - bool m_bNeedsRendered; // 4J added + short changeUid; + bool m_bNeedsRendered; // 4J added protected: - std::vector *containerListeners; + std::vector* containerListeners; - // 4J Stu - The java does not have ctor here (being an abstract) but we need one to initialise the member variables - // TODO Make sure all derived classes also call this - AbstractContainerMenu(); + // 4J Stu - The java does not have ctor here (being an abstract) but we need + // one to initialise the member variables + // TODO Make sure all derived classes also call this + AbstractContainerMenu(); - Slot *addSlot(Slot *slot); + Slot* addSlot(Slot* slot); public: - virtual ~AbstractContainerMenu(); - virtual void addSlotListener(ContainerListener *listener); - std::vector > *getItems(); - void sendData(int id, int value); - virtual void broadcastChanges(); - virtual bool needsRendered(); - virtual bool clickMenuButton(std::shared_ptr player, int buttonId); - Slot *getSlotFor(std::shared_ptr c, int index); - Slot *getSlot(int index); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); - virtual std::shared_ptr clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player); - virtual bool mayCombine(Slot *slot, std::shared_ptr item); + virtual ~AbstractContainerMenu(); + virtual void addSlotListener(ContainerListener* listener); + std::vector >* getItems(); + void sendData(int id, int value); + virtual void broadcastChanges(); + virtual bool needsRendered(); + virtual bool clickMenuButton(std::shared_ptr player, int buttonId); + Slot* getSlotFor(std::shared_ptr c, int index); + Slot* getSlot(int index); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); + virtual std::shared_ptr clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player); + virtual bool mayCombine(Slot* slot, std::shared_ptr item); + protected: - virtual void loopClick(int slotIndex, int buttonNum, bool quickKeyHeld, std::shared_ptr player); + virtual void loopClick(int slotIndex, int buttonNum, bool quickKeyHeld, + std::shared_ptr player); + public: - virtual void removed(std::shared_ptr player); - virtual void slotsChanged();// 4J used to take a std::shared_ptr container but wasn't using it, so removed to simplify things - bool isPauseScreen(); - void setItem(unsigned int slot, std::shared_ptr item); - void setAll(ItemInstanceArray *items); - virtual void setData(int id, int value); - short backup(std::shared_ptr inventory); + virtual void removed(std::shared_ptr player); + virtual void + slotsChanged(); // 4J used to take a std::shared_ptr container + // but wasn't using it, so removed to simplify things + bool isPauseScreen(); + void setItem(unsigned int slot, std::shared_ptr item); + void setAll(ItemInstanceArray* items); + virtual void setData(int id, int value); + short backup(std::shared_ptr inventory); private: - std::unordered_set , PlayerKeyHash, PlayerKeyEq> unSynchedPlayers; + std::unordered_set, PlayerKeyHash, PlayerKeyEq> + unSynchedPlayers; public: - bool isSynched(std::shared_ptr player); - void setSynched(std::shared_ptr player, bool synched); - virtual bool stillValid(std::shared_ptr player) = 0; - - // 4J Stu Added for UI - unsigned int getSize() { return (unsigned int)slots->size(); } + bool isSynched(std::shared_ptr player); + void setSynched(std::shared_ptr player, bool synched); + virtual bool stillValid(std::shared_ptr player) = 0; + // 4J Stu Added for UI + unsigned int getSize() { return (unsigned int)slots->size(); } protected: - // 4J Stu - Changes to return bool brought forward from 1.2 - bool moveItemStackTo(std::shared_ptr itemStack, int startSlot, int endSlot, bool backwards); + // 4J Stu - Changes to return bool brought forward from 1.2 + bool moveItemStackTo(std::shared_ptr itemStack, int startSlot, + int endSlot, bool backwards); public: - virtual bool isOverrideResultClick(int slotNum, int buttonNum); + virtual bool isOverrideResultClick(int slotNum, int buttonNum); }; diff --git a/Minecraft.World/Containers/ArmorSlot.cpp b/Minecraft.World/Containers/ArmorSlot.cpp index 22efe2d45..774a480e9 100644 --- a/Minecraft.World/Containers/ArmorSlot.cpp +++ b/Minecraft.World/Containers/ArmorSlot.cpp @@ -6,54 +6,45 @@ #include "../Headers/net.minecraft.world.item.crafting.h" #include "ArmorSlot.h" -ArmorSlot::ArmorSlot(int slotNum, std::shared_ptr container, int id, int x, int y) - : Slot( container, id, x, y ), - slotNum( slotNum ) -{ +ArmorSlot::ArmorSlot(int slotNum, std::shared_ptr container, int id, + int x, int y) + : Slot(container, id, x, y), slotNum(slotNum) {} + +int ArmorSlot::getMaxStackSize() { return 1; } + +bool ArmorSlot::mayPlace(std::shared_ptr item) { + if (dynamic_cast(item->getItem()) != NULL) { + return dynamic_cast(item->getItem())->slot == slotNum; + } + if (item->getItem()->id == Tile::pumpkin_Id || + item->getItem()->id == Item::skull_Id) { + return slotNum == 0; + } + return false; } -int ArmorSlot::getMaxStackSize() -{ - return 1; -} - -bool ArmorSlot::mayPlace(std::shared_ptr item) -{ - if ( dynamic_cast( item->getItem() ) != NULL) - { - return dynamic_cast( item->getItem() )->slot == slotNum; - } - if (item->getItem()->id == Tile::pumpkin_Id || item->getItem()->id == Item::skull_Id) - { - return slotNum == 0; - } - return false; -} - -Icon *ArmorSlot::getNoItemIcon() -{ - return ArmorItem::getEmptyIcon(slotNum); -} +Icon* ArmorSlot::getNoItemIcon() { return ArmorItem::getEmptyIcon(slotNum); } // -//bool ArmorSlot::mayCombine(std::shared_ptr item) +// bool ArmorSlot::mayCombine(std::shared_ptr item) //{ // std::shared_ptr thisItemI = getItem(); // if(thisItemI == NULL || item == NULL) return false; // // ArmorItem *thisItem = (ArmorItem *)thisItemI->getItem(); -// bool thisIsDyableArmor = thisItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH; -// bool itemIsDye = item->id == Item::dye_powder_Id; -// return thisIsDyableArmor && itemIsDye; +// bool thisIsDyableArmor = thisItem->getMaterial() == +//ArmorItem::ArmorMaterial::CLOTH; bool itemIsDye = item->id == +//Item::dye_powder_Id; return thisIsDyableArmor && itemIsDye; //} // -//std::shared_ptr ArmorSlot::combine(std::shared_ptr item) +// std::shared_ptr +// ArmorSlot::combine(std::shared_ptr item) //{ -// std::shared_ptr craftSlots = std::shared_ptr( new CraftingContainer(NULL, 2, 2) ); +// std::shared_ptr craftSlots = +//std::shared_ptr( new CraftingContainer(NULL, 2, 2) ); // craftSlots->setItem(0, item); // craftSlots->setItem(1, getItem()); // Armour item needs to go second -// std::shared_ptr result = ArmorDyeRecipe::assembleDyedArmor(craftSlots); -// craftSlots->setItem(0, nullptr); -// craftSlots->setItem(1, nullptr); -// return result; +// std::shared_ptr result = +//ArmorDyeRecipe::assembleDyedArmor(craftSlots); craftSlots->setItem(0, +//nullptr); craftSlots->setItem(1, nullptr); return result; //} \ No newline at end of file diff --git a/Minecraft.World/Containers/ArmorSlot.h b/Minecraft.World/Containers/ArmorSlot.h index 2bf02067c..cf25af69e 100644 --- a/Minecraft.World/Containers/ArmorSlot.h +++ b/Minecraft.World/Containers/ArmorSlot.h @@ -1,24 +1,25 @@ #pragma once // 4J Stu Added -// In InventoryMenu.java they create an anoymous class while creating some slot. I have moved the content -// of that anonymous class to here +// In InventoryMenu.java they create an anoymous class while creating some slot. +// I have moved the content of that anonymous class to here #include "Slot.h" class Container; -class ArmorSlot : public Slot -{ +class ArmorSlot : public Slot { private: - const int slotNum; + const int slotNum; public: - ArmorSlot(int slotNum, std::shared_ptr container, int id, int x, int y); - virtual ~ArmorSlot() {} + ArmorSlot(int slotNum, std::shared_ptr container, int id, int x, + int y); + virtual ~ArmorSlot() {} - virtual int getMaxStackSize(); - virtual bool mayPlace(std::shared_ptr item); - Icon *getNoItemIcon(); - //virtual bool mayCombine(std::shared_ptr item); // 4J Added - //virtual std::shared_ptr combine(std::shared_ptr item); // 4J Added + virtual int getMaxStackSize(); + virtual bool mayPlace(std::shared_ptr item); + Icon* getNoItemIcon(); + // virtual bool mayCombine(std::shared_ptr item); // 4J Added + // virtual std::shared_ptr + // combine(std::shared_ptr item); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/BrewingStandMenu.cpp b/Minecraft.World/Containers/BrewingStandMenu.cpp index 84227e7be..14c13d796 100644 --- a/Minecraft.World/Containers/BrewingStandMenu.cpp +++ b/Minecraft.World/Containers/BrewingStandMenu.cpp @@ -6,234 +6,219 @@ #include "../Headers/net.minecraft.stats.h" #include "BrewingStandMenu.h" -BrewingStandMenu::BrewingStandMenu(std::shared_ptr inventory, std::shared_ptr brewingStand) -{ - tc = 0; +BrewingStandMenu::BrewingStandMenu( + std::shared_ptr inventory, + std::shared_ptr brewingStand) { + tc = 0; - this->brewingStand = brewingStand; + this->brewingStand = brewingStand; - addSlot(new PotionSlot(std::dynamic_pointer_cast( inventory->player->shared_from_this() ), brewingStand, 0, 56, 46)); - addSlot(new PotionSlot(std::dynamic_pointer_cast( inventory->player->shared_from_this() ), brewingStand, 1, 79, 53)); - addSlot(new PotionSlot(std::dynamic_pointer_cast( inventory->player->shared_from_this() ), brewingStand, 2, 102, 46)); - ingredientSlot = addSlot(new IngredientsSlot(brewingStand, 3, 79, 17)); + addSlot(new PotionSlot(std::dynamic_pointer_cast( + inventory->player->shared_from_this()), + brewingStand, 0, 56, 46)); + addSlot(new PotionSlot(std::dynamic_pointer_cast( + inventory->player->shared_from_this()), + brewingStand, 1, 79, 53)); + addSlot(new PotionSlot(std::dynamic_pointer_cast( + inventory->player->shared_from_this()), + brewingStand, 2, 102, 46)); + ingredientSlot = addSlot(new IngredientsSlot(brewingStand, 3, 79, 17)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } } -void BrewingStandMenu::addSlotListener(ContainerListener *listener) -{ - AbstractContainerMenu::addSlotListener(listener); - listener->setContainerData(this, 0, brewingStand->getBrewTime()); +void BrewingStandMenu::addSlotListener(ContainerListener* listener) { + AbstractContainerMenu::addSlotListener(listener); + listener->setContainerData(this, 0, brewingStand->getBrewTime()); } -void BrewingStandMenu::broadcastChanges() -{ - AbstractContainerMenu::broadcastChanges(); +void BrewingStandMenu::broadcastChanges() { + AbstractContainerMenu::broadcastChanges(); - //for (int i = 0; i < containerListeners->size(); i++) - for(AUTO_VAR(it, containerListeners->begin()); it != containerListeners->end(); ++it) - { - ContainerListener *listener = *it; //containerListeners.at(i); - if (tc != brewingStand->getBrewTime()) - { - listener->setContainerData(this, 0, brewingStand->getBrewTime()); - } - } - tc = brewingStand->getBrewTime(); + // for (int i = 0; i < containerListeners->size(); i++) + for (AUTO_VAR(it, containerListeners->begin()); + it != containerListeners->end(); ++it) { + ContainerListener* listener = *it; // containerListeners.at(i); + if (tc != brewingStand->getBrewTime()) { + listener->setContainerData(this, 0, brewingStand->getBrewTime()); + } + } + tc = brewingStand->getBrewTime(); } -void BrewingStandMenu::setData(int id, int value) -{ - if (id == 0) brewingStand->setBrewTime(value); +void BrewingStandMenu::setData(int id, int value) { + if (id == 0) brewingStand->setBrewTime(value); } -bool BrewingStandMenu::stillValid(std::shared_ptr player) -{ - return brewingStand->stillValid(player); +bool BrewingStandMenu::stillValid(std::shared_ptr player) { + return brewingStand->stillValid(player); } -std::shared_ptr BrewingStandMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - Slot *IngredientSlot = slots->at(INGREDIENT_SLOT); - Slot *PotionSlot1 = slots->at(BOTTLE_SLOT_START); - Slot *PotionSlot2 = slots->at(BOTTLE_SLOT_START+1); - Slot *PotionSlot3 = slots->at(BOTTLE_SLOT_START+2); +std::shared_ptr BrewingStandMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + Slot* IngredientSlot = slots->at(INGREDIENT_SLOT); + Slot* PotionSlot1 = slots->at(BOTTLE_SLOT_START); + Slot* PotionSlot2 = slots->at(BOTTLE_SLOT_START + 1); + Slot* PotionSlot3 = slots->at(BOTTLE_SLOT_START + 2); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if ((slotIndex >= BOTTLE_SLOT_START && slotIndex <= BOTTLE_SLOT_END) || (slotIndex == INGREDIENT_SLOT)) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); - } - else if (!ingredientSlot->hasItem() && ingredientSlot->mayPlace(stack)) - { - if (!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT + 1, false)) - { - return nullptr; - } - } - else if (PotionSlot::mayPlaceItem(clicked)) - { - if (!moveItemStackTo(stack, BOTTLE_SLOT_START, BOTTLE_SLOT_END + 1, false)) - { - return nullptr; - } - } - else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - // 4J-PB - if the item is an ingredient, quickmove it into the ingredient slot - if( (Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherStalkSeeds_Id) ) && - (!IngredientSlot->hasItem() || (stack->id==IngredientSlot->getItem()->id) ) ) - { - if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false)) - { - return nullptr; - } - } - // potion? - else if((stack->id==Item::potion_Id) &&(!PotionSlot1->hasItem() || !PotionSlot2->hasItem() || !PotionSlot3->hasItem())) - { - if(!moveItemStackTo(stack, BOTTLE_SLOT_START, BOTTLE_SLOT_END+1, false)) - { - return nullptr; - } - } - else if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - // 4J-PB - if the item is an ingredient, quickmove it into the ingredient slot - if((Item::items[stack->id]->hasPotionBrewingFormula() || (stack->id == Item::netherStalkSeeds_Id)) && - (!IngredientSlot->hasItem() || (stack->id==IngredientSlot->getItem()->id) )) - { - if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false)) - { - return nullptr; - } - } - // potion? - else if((stack->id==Item::potion_Id) &&(!PotionSlot1->hasItem() || !PotionSlot2->hasItem() || !PotionSlot3->hasItem())) - { - if(!moveItemStackTo(stack, BOTTLE_SLOT_START, BOTTLE_SLOT_END+1, false)) - { - return nullptr; - } - } - else if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - else - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + if ((slotIndex >= BOTTLE_SLOT_START && slotIndex <= BOTTLE_SLOT_END) || + (slotIndex == INGREDIENT_SLOT)) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); + } else if (!ingredientSlot->hasItem() && + ingredientSlot->mayPlace(stack)) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT + 1, + false)) { + return nullptr; + } + } else if (PotionSlot::mayPlaceItem(clicked)) { + if (!moveItemStackTo(stack, BOTTLE_SLOT_START, BOTTLE_SLOT_END + 1, + false)) { + return nullptr; + } + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + // 4J-PB - if the item is an ingredient, quickmove it into the + // ingredient slot + if ((Item::items[stack->id]->hasPotionBrewingFormula() || + (stack->id == Item::netherStalkSeeds_Id)) && + (!IngredientSlot->hasItem() || + (stack->id == IngredientSlot->getItem()->id))) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, + INGREDIENT_SLOT + 1, false)) { + return nullptr; + } + } + // potion? + else if ((stack->id == Item::potion_Id) && + (!PotionSlot1->hasItem() || !PotionSlot2->hasItem() || + !PotionSlot3->hasItem())) { + if (!moveItemStackTo(stack, BOTTLE_SLOT_START, + BOTTLE_SLOT_END + 1, false)) { + return nullptr; + } + } else if (!moveItemStackTo(stack, USE_ROW_SLOT_START, + USE_ROW_SLOT_END, false)) { + return nullptr; + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + // 4J-PB - if the item is an ingredient, quickmove it into the + // ingredient slot + if ((Item::items[stack->id]->hasPotionBrewingFormula() || + (stack->id == Item::netherStalkSeeds_Id)) && + (!IngredientSlot->hasItem() || + (stack->id == IngredientSlot->getItem()->id))) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, + INGREDIENT_SLOT + 1, false)) { + return nullptr; + } + } + // potion? + else if ((stack->id == Item::potion_Id) && + (!PotionSlot1->hasItem() || !PotionSlot2->hasItem() || + !PotionSlot3->hasItem())) { + if (!moveItemStackTo(stack, BOTTLE_SLOT_START, + BOTTLE_SLOT_END + 1, false)) { + return nullptr; + } + } else if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, + false)) { + return nullptr; + } + } else { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } -BrewingStandMenu::PotionSlot::PotionSlot(std::shared_ptr player, std::shared_ptr container, int slot, int x, int y) : Slot(container, slot, x, y) -{ - this->player = player; +BrewingStandMenu::PotionSlot::PotionSlot(std::shared_ptr player, + std::shared_ptr container, + int slot, int x, int y) + : Slot(container, slot, x, y) { + this->player = player; } -bool BrewingStandMenu::PotionSlot::mayPlace(std::shared_ptr item) -{ - return mayPlaceItem(item); +bool BrewingStandMenu::PotionSlot::mayPlace( + std::shared_ptr item) { + return mayPlaceItem(item); } -int BrewingStandMenu::PotionSlot::getMaxStackSize() -{ - return 1; +int BrewingStandMenu::PotionSlot::getMaxStackSize() { return 1; } + +void BrewingStandMenu::PotionSlot::onTake( + std::shared_ptr player, std::shared_ptr carried) { + carried->onCraftedBy( + this->player->level, + std::dynamic_pointer_cast(this->player->shared_from_this()), 1); + if (carried->id == Item::potion_Id && carried->getAuxValue() > 0) + this->player->awardStat(GenericStats::potion(), + GenericStats::param_potion()); + Slot::onTake(player, carried); } -void BrewingStandMenu::PotionSlot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - carried->onCraftedBy(this->player->level, std::dynamic_pointer_cast( this->player->shared_from_this() ), 1); - if (carried->id == Item::potion_Id && carried->getAuxValue() > 0) - this->player->awardStat(GenericStats::potion(),GenericStats::param_potion()); - Slot::onTake(player, carried); +bool BrewingStandMenu::PotionSlot::mayCombine( + std::shared_ptr second) { + return false; } -bool BrewingStandMenu::PotionSlot::mayCombine(std::shared_ptr second) -{ - return false; +bool BrewingStandMenu::PotionSlot::mayPlaceItem( + std::shared_ptr item) { + return item != NULL && + (item->id == Item::potion_Id || item->id == Item::glassBottle_Id); } -bool BrewingStandMenu::PotionSlot::mayPlaceItem(std::shared_ptr item) -{ - return item != NULL && (item->id == Item::potion_Id || item->id == Item::glassBottle_Id); +BrewingStandMenu::IngredientsSlot::IngredientsSlot( + std::shared_ptr container, int slot, int x, int y) + : Slot(container, slot, x, y) {} + +bool BrewingStandMenu::IngredientsSlot::mayPlace( + std::shared_ptr item) { + if (item != NULL) { + if (PotionBrewing::SIMPLIFIED_BREWING) { + return Item::items[item->id]->hasPotionBrewingFormula(); + } else { + return Item::items[item->id]->hasPotionBrewingFormula() || + item->id == Item::netherStalkSeeds_Id || + item->id == Item::bucket_water_Id; + } + } + return false; } - - -BrewingStandMenu::IngredientsSlot::IngredientsSlot(std::shared_ptr container, int slot, int x, int y) : Slot(container, slot, x ,y) -{ +bool BrewingStandMenu::IngredientsSlot::mayCombine( + std::shared_ptr second) { + return false; } -bool BrewingStandMenu::IngredientsSlot::mayPlace(std::shared_ptr item) -{ - if (item != NULL) - { - if (PotionBrewing::SIMPLIFIED_BREWING) - { - return Item::items[item->id]->hasPotionBrewingFormula(); - } - else - { - return Item::items[item->id]->hasPotionBrewingFormula() || item->id == Item::netherStalkSeeds_Id || item->id == Item::bucket_water_Id; - } - } - return false; -} - -bool BrewingStandMenu::IngredientsSlot::mayCombine(std::shared_ptr second) -{ - return false; -} - -int BrewingStandMenu::IngredientsSlot::getMaxStackSize() -{ - return 64; -} +int BrewingStandMenu::IngredientsSlot::getMaxStackSize() { return 64; } diff --git a/Minecraft.World/Containers/BrewingStandMenu.h b/Minecraft.World/Containers/BrewingStandMenu.h index 7a981acbc..082aec757 100644 --- a/Minecraft.World/Containers/BrewingStandMenu.h +++ b/Minecraft.World/Containers/BrewingStandMenu.h @@ -8,58 +8,63 @@ class Inventory; class Player; class Container; -class BrewingStandMenu : public AbstractContainerMenu -{ - // 4J Stu - Made public so that we can access these from the XUI menus +class BrewingStandMenu : public AbstractContainerMenu { + // 4J Stu - Made public so that we can access these from the XUI menus public: - static const int INGREDIENT_SLOT = 3; - static const int BOTTLE_SLOT_START = 0; - static const int BOTTLE_SLOT_END = 2; - static const int INV_SLOT_START = INGREDIENT_SLOT + 1; - static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = INV_SLOT_END; - static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; + static const int INGREDIENT_SLOT = 3; + static const int BOTTLE_SLOT_START = 0; + static const int BOTTLE_SLOT_END = 2; + static const int INV_SLOT_START = INGREDIENT_SLOT + 1; + static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = INV_SLOT_END; + static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; private: - std::shared_ptr brewingStand; - Slot *ingredientSlot; + std::shared_ptr brewingStand; + Slot* ingredientSlot; public: - BrewingStandMenu(std::shared_ptr inventory, std::shared_ptr brewingStand); + BrewingStandMenu(std::shared_ptr inventory, + std::shared_ptr brewingStand); private: - int tc; + int tc; public: - virtual void addSlotListener(ContainerListener *listener); - virtual void broadcastChanges(); - virtual void setData(int id, int value); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); + virtual void addSlotListener(ContainerListener* listener); + virtual void broadcastChanges(); + virtual void setData(int id, int value); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); private: - class PotionSlot : public Slot - { - private: - std::shared_ptr player; + class PotionSlot : public Slot { + private: + std::shared_ptr player; - public: - PotionSlot(std::shared_ptr player, std::shared_ptr container, int slot, int x, int y); + public: + PotionSlot(std::shared_ptr player, + std::shared_ptr container, int slot, int x, + int y); - virtual bool mayPlace(std::shared_ptr item); - virtual int getMaxStackSize(); - virtual void onTake(std::shared_ptr player, std::shared_ptr carried); - static bool mayPlaceItem(std::shared_ptr item); - virtual bool mayCombine(std::shared_ptr item); // 4J Added - }; + virtual bool mayPlace(std::shared_ptr item); + virtual int getMaxStackSize(); + virtual void onTake(std::shared_ptr player, + std::shared_ptr carried); + static bool mayPlaceItem(std::shared_ptr item); + virtual bool mayCombine( + std::shared_ptr item); // 4J Added + }; - class IngredientsSlot : public Slot - { - public: - IngredientsSlot(std::shared_ptr container, int slot, int x, int y); + class IngredientsSlot : public Slot { + public: + IngredientsSlot(std::shared_ptr container, int slot, int x, + int y); - virtual bool mayPlace(std::shared_ptr item); - virtual int getMaxStackSize(); - virtual bool mayCombine(std::shared_ptr item); // 4J Added - }; + virtual bool mayPlace(std::shared_ptr item); + virtual int getMaxStackSize(); + virtual bool mayCombine( + std::shared_ptr item); // 4J Added + }; }; \ No newline at end of file diff --git a/Minecraft.World/Containers/ClientSideMerchant.cpp b/Minecraft.World/Containers/ClientSideMerchant.cpp index d17fa537a..725dd1df4 100644 --- a/Minecraft.World/Containers/ClientSideMerchant.cpp +++ b/Minecraft.World/Containers/ClientSideMerchant.cpp @@ -3,62 +3,47 @@ #include "../Headers/net.minecraft.world.inventory.h" #include "ClientSideMerchant.h" -ClientSideMerchant::ClientSideMerchant(std::shared_ptr source, int name) -{ - this->source = source; - // 4J Stu - Need to do this after creating as a std::shared_ptr - container = NULL; //new MerchantContainer(source, this); - currentOffers = NULL; - m_name = name; +ClientSideMerchant::ClientSideMerchant(std::shared_ptr source, + int name) { + this->source = source; + // 4J Stu - Need to do this after creating as a std::shared_ptr + container = NULL; // new MerchantContainer(source, this); + currentOffers = NULL; + m_name = name; } -ClientSideMerchant::~ClientSideMerchant() -{ - delete container; - delete currentOffers; +ClientSideMerchant::~ClientSideMerchant() { + delete container; + delete currentOffers; } -void ClientSideMerchant::createContainer() -{ - container = new MerchantContainer(source, shared_from_this()); +void ClientSideMerchant::createContainer() { + container = new MerchantContainer(source, shared_from_this()); } -Container *ClientSideMerchant::getContainer() -{ - return container; +Container* ClientSideMerchant::getContainer() { return container; } + +std::shared_ptr ClientSideMerchant::getTradingPlayer() { + return source; } -std::shared_ptr ClientSideMerchant::getTradingPlayer() -{ - return source; +void ClientSideMerchant::setTradingPlayer(std::shared_ptr player) {} + +MerchantRecipeList* ClientSideMerchant::getOffers( + std::shared_ptr forPlayer) { + return currentOffers; } -void ClientSideMerchant::setTradingPlayer(std::shared_ptr player) -{ - +void ClientSideMerchant::overrideOffers(MerchantRecipeList* recipeList) { + delete currentOffers; + currentOffers = recipeList; } -MerchantRecipeList *ClientSideMerchant::getOffers(std::shared_ptr forPlayer) -{ - return currentOffers; +void ClientSideMerchant::notifyTrade(MerchantRecipe* activeRecipe) { + activeRecipe->increaseUses(); } -void ClientSideMerchant::overrideOffers(MerchantRecipeList *recipeList) -{ - delete currentOffers; - currentOffers = recipeList; -} +void ClientSideMerchant::notifyTradeUpdated( + std::shared_ptr item) {} -void ClientSideMerchant::notifyTrade(MerchantRecipe *activeRecipe) -{ - activeRecipe->increaseUses(); -} - -void ClientSideMerchant::notifyTradeUpdated(std::shared_ptr item) -{ -} - -int ClientSideMerchant::getDisplayName() -{ - return m_name; -} \ No newline at end of file +int ClientSideMerchant::getDisplayName() { return m_name; } \ No newline at end of file diff --git a/Minecraft.World/Containers/ClientSideMerchant.h b/Minecraft.World/Containers/ClientSideMerchant.h index d5e8861ff..25322c452 100644 --- a/Minecraft.World/Containers/ClientSideMerchant.h +++ b/Minecraft.World/Containers/ClientSideMerchant.h @@ -6,25 +6,26 @@ class MerchantContainer; class MerchantRecipeList; class MerchantRecipe; -class ClientSideMerchant : public Merchant, public std::enable_shared_from_this -{ +class ClientSideMerchant + : public Merchant, + public std::enable_shared_from_this { private: - MerchantContainer *container; + MerchantContainer* container; std::shared_ptr source; - MerchantRecipeList *currentOffers; - int m_name; + MerchantRecipeList* currentOffers; + int m_name; public: - ClientSideMerchant(std::shared_ptr source, int name); - ~ClientSideMerchant(); + ClientSideMerchant(std::shared_ptr source, int name); + ~ClientSideMerchant(); - void createContainer(); // 4J Added - Container *getContainer(); + void createContainer(); // 4J Added + Container* getContainer(); std::shared_ptr getTradingPlayer(); void setTradingPlayer(std::shared_ptr player); - MerchantRecipeList *getOffers(std::shared_ptr forPlayer); - void overrideOffers(MerchantRecipeList *recipeList); - void notifyTrade(MerchantRecipe *activeRecipe); - void notifyTradeUpdated(std::shared_ptr item); - int getDisplayName(); + MerchantRecipeList* getOffers(std::shared_ptr forPlayer); + void overrideOffers(MerchantRecipeList* recipeList); + void notifyTrade(MerchantRecipe* activeRecipe); + void notifyTradeUpdated(std::shared_ptr item); + int getDisplayName(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/CompoundContainer.cpp b/Minecraft.World/Containers/CompoundContainer.cpp index b8a252e5b..5265f3e1f 100644 --- a/Minecraft.World/Containers/CompoundContainer.cpp +++ b/Minecraft.World/Containers/CompoundContainer.cpp @@ -3,73 +3,68 @@ #include "CompoundContainer.h" -CompoundContainer::CompoundContainer(int name, std::shared_ptr c1, std::shared_ptr c2) -{ - this->name = name; - if (c1 == NULL) c1 = c2; - if (c2 == NULL) c2 = c1; - this->c1 = c1; - this->c2 = c2; +CompoundContainer::CompoundContainer(int name, std::shared_ptr c1, + std::shared_ptr c2) { + this->name = name; + if (c1 == NULL) c1 = c2; + if (c2 == NULL) c2 = c1; + this->c1 = c1; + this->c2 = c2; } -unsigned int CompoundContainer::getContainerSize() -{ - return c1->getContainerSize() + c2->getContainerSize(); +unsigned int CompoundContainer::getContainerSize() { + return c1->getContainerSize() + c2->getContainerSize(); } -int CompoundContainer::getName() -{ - return name; +int CompoundContainer::getName() { return name; } + +std::shared_ptr CompoundContainer::getItem(unsigned int slot) { + if (slot >= c1->getContainerSize()) + return c2->getItem(slot - c1->getContainerSize()); + else + return c1->getItem(slot); } -std::shared_ptr CompoundContainer::getItem(unsigned int slot) -{ - if (slot >= c1->getContainerSize()) return c2->getItem(slot - c1->getContainerSize()); - else return c1->getItem(slot); +std::shared_ptr CompoundContainer::removeItem(unsigned int slot, + int i) { + if (slot >= c1->getContainerSize()) + return c2->removeItem(slot - c1->getContainerSize(), i); + else + return c1->removeItem(slot, i); } -std::shared_ptr CompoundContainer::removeItem(unsigned int slot, int i) -{ - if (slot >= c1->getContainerSize()) return c2->removeItem(slot - c1->getContainerSize(), i); - else return c1->removeItem(slot, i); +std::shared_ptr CompoundContainer::removeItemNoUpdate(int slot) { + if (slot >= c1->getContainerSize()) + return c2->removeItemNoUpdate(slot - c1->getContainerSize()); + else + return c1->removeItemNoUpdate(slot); } -std::shared_ptr CompoundContainer::removeItemNoUpdate(int slot) -{ - if (slot >= c1->getContainerSize()) return c2->removeItemNoUpdate(slot - c1->getContainerSize()); - else return c1->removeItemNoUpdate(slot); +void CompoundContainer::setItem(unsigned int slot, + std::shared_ptr item) { + if (slot >= c1->getContainerSize()) + c2->setItem(slot - c1->getContainerSize(), item); + else + c1->setItem(slot, item); } -void CompoundContainer::setItem(unsigned int slot, std::shared_ptr item) -{ - if (slot >= c1->getContainerSize()) c2->setItem(slot - c1->getContainerSize(), item); - else c1->setItem(slot, item); +int CompoundContainer::getMaxStackSize() { return c1->getMaxStackSize(); } + +void CompoundContainer::setChanged() { + c1->setChanged(); + c2->setChanged(); } -int CompoundContainer::getMaxStackSize() -{ - return c1->getMaxStackSize(); +bool CompoundContainer::stillValid(std::shared_ptr player) { + return c1->stillValid(player) && c2->stillValid(player); } -void CompoundContainer::setChanged() -{ - c1->setChanged(); - c2->setChanged(); +void CompoundContainer::startOpen() { + c1->startOpen(); + c2->startOpen(); } -bool CompoundContainer::stillValid(std::shared_ptr player) -{ - return c1->stillValid(player) && c2->stillValid(player); -} - -void CompoundContainer::startOpen() -{ - c1->startOpen(); - c2->startOpen(); -} - -void CompoundContainer::stopOpen() -{ - c1->stopOpen(); - c2->stopOpen(); +void CompoundContainer::stopOpen() { + c1->stopOpen(); + c2->stopOpen(); } \ No newline at end of file diff --git a/Minecraft.World/Containers/CompoundContainer.h b/Minecraft.World/Containers/CompoundContainer.h index 466dc4b82..02ad7570d 100644 --- a/Minecraft.World/Containers/CompoundContainer.h +++ b/Minecraft.World/Containers/CompoundContainer.h @@ -1,36 +1,35 @@ #pragma once - #include "Container.h" class Player; -class CompoundContainer : public Container -{ +class CompoundContainer : public Container { private: - int name; - std::shared_ptr c1, c2; + int name; + std::shared_ptr c1, c2; public: - CompoundContainer(int name, std::shared_ptr c1, std::shared_ptr c2); + CompoundContainer(int name, std::shared_ptr c1, + std::shared_ptr c2); - unsigned int getContainerSize(); + unsigned int getContainerSize(); - int getName(); + int getName(); - std::shared_ptr getItem(unsigned int slot); + std::shared_ptr getItem(unsigned int slot); - std::shared_ptr removeItem(unsigned int slot, int i); - std::shared_ptr removeItemNoUpdate(int slot); + std::shared_ptr removeItem(unsigned int slot, int i); + std::shared_ptr removeItemNoUpdate(int slot); - void setItem(unsigned int slot, std::shared_ptr item); + void setItem(unsigned int slot, std::shared_ptr item); - int getMaxStackSize(); + int getMaxStackSize(); - void setChanged(); + void setChanged(); - bool stillValid(std::shared_ptr player); + bool stillValid(std::shared_ptr player); - virtual void startOpen(); - virtual void stopOpen(); + virtual void startOpen(); + virtual void stopOpen(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/Container.h b/Minecraft.World/Containers/Container.h index 06ee42a28..82ec0b6df 100644 --- a/Minecraft.World/Containers/Container.h +++ b/Minecraft.World/Containers/Container.h @@ -1,24 +1,24 @@ #pragma once - class ItemInstance; class Player; -class Container -{ +class Container { public: - virtual ~Container(){} + virtual ~Container() {} static const int LARGE_MAX_STACK_SIZE = 64; virtual unsigned int getContainerSize() = 0; virtual std::shared_ptr getItem(unsigned int slot) = 0; - virtual std::shared_ptr removeItem(unsigned int slot, int count) = 0; - virtual std::shared_ptr removeItemNoUpdate(int slot) = 0; - virtual void setItem(unsigned int slot, std::shared_ptr item) = 0; + virtual std::shared_ptr removeItem(unsigned int slot, + int count) = 0; + virtual std::shared_ptr removeItemNoUpdate(int slot) = 0; + virtual void setItem(unsigned int slot, + std::shared_ptr item) = 0; virtual int getName() = 0; virtual int getMaxStackSize() = 0; virtual void setChanged() = 0; virtual bool stillValid(std::shared_ptr player) = 0; - virtual void startOpen() = 0; - virtual void stopOpen() = 0; + virtual void startOpen() = 0; + virtual void stopOpen() = 0; }; diff --git a/Minecraft.World/Containers/ContainerMenu.cpp b/Minecraft.World/Containers/ContainerMenu.cpp index 8bed328fd..e88558a72 100644 --- a/Minecraft.World/Containers/ContainerMenu.cpp +++ b/Minecraft.World/Containers/ContainerMenu.cpp @@ -8,113 +8,108 @@ #include "../../Minecraft.Client/Player/LocalPlayer.h" #include "ContainerMenu.h" -ContainerMenu::ContainerMenu(std::shared_ptr inventory, std::shared_ptr container) : AbstractContainerMenu() -{ - this->container = container; - this->containerRows = container->getContainerSize() / 9; - container->startOpen(); +ContainerMenu::ContainerMenu(std::shared_ptr inventory, + std::shared_ptr container) + : AbstractContainerMenu() { + this->container = container; + this->containerRows = container->getContainerSize() / 9; + container->startOpen(); - int yo = (containerRows - 4) * 18; + int yo = (containerRows - 4) * 18; - for (int y = 0; y < containerRows; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(container, x + y * 9, 8 + x * 18, 18 + y * 18)); - } - } + for (int y = 0; y < containerRows; y++) { + for (int x = 0; x < 9; x++) { + addSlot(new Slot(container, x + y * 9, 8 + x * 18, 18 + y * 18)); + } + } - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 103 + y * 18 + yo)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 161 + yo)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, + 103 + y * 18 + yo)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 161 + yo)); + } } -bool ContainerMenu::stillValid(std::shared_ptr player) -{ - return container->stillValid(player); +bool ContainerMenu::stillValid(std::shared_ptr player) { + return container->stillValid(player); } -std::shared_ptr ContainerMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); +std::shared_ptr ContainerMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex < containerRows * 9) - { - if(!moveItemStackTo(stack, containerRows * 9, (int)slots->size(), true)) - { - // 4J Stu - Brought forward from 1.2 - return nullptr; - } - } - else - { - if(!moveItemStackTo(stack, 0, containerRows * 9, false)) - { - // 4J Stu - Brought forward from 1.2 - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - } - return clicked; + if (slotIndex < containerRows * 9) { + if (!moveItemStackTo(stack, containerRows * 9, (int)slots->size(), + true)) { + // 4J Stu - Brought forward from 1.2 + return nullptr; + } + } else { + if (!moveItemStackTo(stack, 0, containerRows * 9, false)) { + // 4J Stu - Brought forward from 1.2 + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + } + return clicked; } -void ContainerMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - container->stopOpen(); +void ContainerMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + container->stopOpen(); } -std::shared_ptr ContainerMenu::clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player) -{ - std::shared_ptr out = AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); +std::shared_ptr ContainerMenu::clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player) { + std::shared_ptr out = + AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); #ifdef _EXTENDED_ACHIEVEMENTS - std::shared_ptr localPlayer = std::dynamic_pointer_cast(player); + std::shared_ptr localPlayer = + std::dynamic_pointer_cast(player); - if (localPlayer != NULL) // 4J-JEV: For "Chestful o'Cobblestone" achievement. - { - int cobblecount = 0; - for (int i = 0; i < container->getContainerSize(); i++) - { - std::shared_ptr item = container->getItem(i); - if ( (item != nullptr) && (item->id == Tile::stoneBrick_Id) ) - { - cobblecount += item->GetCount(); - } - } + if (localPlayer != + NULL) // 4J-JEV: For "Chestful o'Cobblestone" achievement. + { + int cobblecount = 0; + for (int i = 0; i < container->getContainerSize(); i++) { + std::shared_ptr item = container->getItem(i); + if ((item != nullptr) && (item->id == Tile::stoneBrick_Id)) { + cobblecount += item->GetCount(); + } + } - // 4J-JEV: This check performed on XboxOne servers, for other platforms check here. + // 4J-JEV: This check performed on XboxOne servers, for other platforms + // check here. #ifndef _DURANGO - StatsCounter *sc = Minecraft::GetInstance()->stats[localPlayer->GetXboxPad()]; - int minedCount = sc->getTotalValue(GenericStats::blocksMined(Tile::rock_Id)) + sc->getTotalValue(GenericStats::blocksMined(Tile::stoneBrick_Id)); - if (cobblecount >= 1728 && minedCount >= 1728 ) + StatsCounter* sc = + Minecraft::GetInstance()->stats[localPlayer->GetXboxPad()]; + int minedCount = + sc->getTotalValue(GenericStats::blocksMined(Tile::rock_Id)) + + sc->getTotalValue(GenericStats::blocksMined(Tile::stoneBrick_Id)); + if (cobblecount >= 1728 && minedCount >= 1728) #endif - { - localPlayer->awardStat(GenericStats::chestfulOfCobblestone(),GenericStats::param_chestfulOfCobblestone(cobblecount)); - } - } + { + localPlayer->awardStat( + GenericStats::chestfulOfCobblestone(), + GenericStats::param_chestfulOfCobblestone(cobblecount)); + } + } #endif - return out; + return out; } diff --git a/Minecraft.World/Containers/ContainerMenu.h b/Minecraft.World/Containers/ContainerMenu.h index a738cdc35..59bc388cb 100644 --- a/Minecraft.World/Containers/ContainerMenu.h +++ b/Minecraft.World/Containers/ContainerMenu.h @@ -4,19 +4,22 @@ class Container; -class ContainerMenu : public AbstractContainerMenu -{ +class ContainerMenu : public AbstractContainerMenu { private: - std::shared_ptr container; - int containerRows; + std::shared_ptr container; + int containerRows; public: - ContainerMenu(std::shared_ptr inventory, std::shared_ptr container); + ContainerMenu(std::shared_ptr inventory, + std::shared_ptr container); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); - void removed(std::shared_ptr player); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); + void removed(std::shared_ptr player); - // 4J ADDED, - virtual std::shared_ptr clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player); + // 4J ADDED, + virtual std::shared_ptr clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player); }; diff --git a/Minecraft.World/Containers/CraftingContainer.cpp b/Minecraft.World/Containers/CraftingContainer.cpp index d87d7e100..b69482551 100644 --- a/Minecraft.World/Containers/CraftingContainer.cpp +++ b/Minecraft.World/Containers/CraftingContainer.cpp @@ -4,97 +4,77 @@ #include "AbstractContainerMenu.h" #include "CraftingContainer.h" -CraftingContainer::~CraftingContainer() -{ +CraftingContainer::~CraftingContainer() {} +CraftingContainer::CraftingContainer(AbstractContainerMenu* menu, + unsigned int w, unsigned int h) { + unsigned int size = w * h; + items = new ItemInstanceArray(size); + this->menu = menu; + this->width = w; } -CraftingContainer::CraftingContainer(AbstractContainerMenu *menu, unsigned int w, unsigned int h) -{ - unsigned int size = w * h; - items = new ItemInstanceArray(size); - this->menu = menu; - this->width = w; +unsigned int CraftingContainer::getContainerSize() { return items->length; } + +std::shared_ptr CraftingContainer::getItem(unsigned int slot) { + if (slot >= getContainerSize()) { + return nullptr; + } + return (*items)[slot]; } -unsigned int CraftingContainer::getContainerSize() -{ - return items->length; +std::shared_ptr CraftingContainer::getItem(unsigned int x, + unsigned int y) { + if (x < 0 || x >= width) { + return nullptr; + } + unsigned int pos = x + y * width; + return getItem(pos); } -std::shared_ptr CraftingContainer::getItem(unsigned int slot) -{ - if (slot >= getContainerSize()) - { - return nullptr; - } - return (*items)[slot]; +int CraftingContainer::getName() { return 0; } + +std::shared_ptr CraftingContainer::removeItemNoUpdate(int slot) { + if ((*items)[slot] != NULL) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr CraftingContainer::getItem(unsigned int x, unsigned int y) -{ - if (x < 0 || x >= width) - { - return nullptr; - } - unsigned int pos = x + y * width; - return getItem(pos); +std::shared_ptr CraftingContainer::removeItem(unsigned int slot, + int count) { + if ((*items)[slot] != NULL) { + if ((*items)[slot]->count <= count) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + menu->slotsChanged(); // 4J - used to take pointer to this, but + // wasn't using it so removed + return item; + } else { + std::shared_ptr i = (*items)[slot]->remove(count); + if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; + menu->slotsChanged(); // 4J - used to take pointer to this, but + // wasn't using it so removed + return i; + } + } + return nullptr; } -int CraftingContainer::getName() -{ - return 0; +void CraftingContainer::setItem(unsigned int slot, + std::shared_ptr item) { + (*items)[slot] = item; + if (menu) menu->slotsChanged(); } -std::shared_ptr CraftingContainer::removeItemNoUpdate(int slot) -{ - if ((*items)[slot] != NULL) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - return item; - } - return nullptr; +int CraftingContainer::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -std::shared_ptr CraftingContainer::removeItem(unsigned int slot, int count) -{ - if ((*items)[slot] != NULL) - { - if ((*items)[slot]->count <= count) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - menu->slotsChanged(); // 4J - used to take pointer to this, but wasn't using it so removed - return item; - } - else - { - std::shared_ptr i = (*items)[slot]->remove(count); - if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; - menu->slotsChanged(); // 4J - used to take pointer to this, but wasn't using it so removed - return i; - } - } - return nullptr; -} +void CraftingContainer::setChanged() {} -void CraftingContainer::setItem(unsigned int slot, std::shared_ptr item) -{ - (*items)[slot] = item; - if(menu) menu->slotsChanged(); -} - -int CraftingContainer::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; -} - -void CraftingContainer::setChanged() -{ -} - -bool CraftingContainer::stillValid(std::shared_ptr player) -{ - return true; +bool CraftingContainer::stillValid(std::shared_ptr player) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Containers/CraftingContainer.h b/Minecraft.World/Containers/CraftingContainer.h index e912c0957..37885af62 100644 --- a/Minecraft.World/Containers/CraftingContainer.h +++ b/Minecraft.World/Containers/CraftingContainer.h @@ -4,29 +4,29 @@ class AbstractContainerMenu; -class CraftingContainer : public Container -{ +class CraftingContainer : public Container { private: - ItemInstanceArray *items; - unsigned int width; - AbstractContainerMenu *menu; + ItemInstanceArray* items; + unsigned int width; + AbstractContainerMenu* menu; public: - CraftingContainer(AbstractContainerMenu *menu, unsigned int w, unsigned int h); - virtual ~CraftingContainer(); + CraftingContainer(AbstractContainerMenu* menu, unsigned int w, + unsigned int h); + virtual ~CraftingContainer(); - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - std::shared_ptr getItem(unsigned int x, unsigned int y); - virtual int getName(); - virtual std::shared_ptr removeItemNoUpdate(int slot); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - virtual void setItem(unsigned int slot, std::shared_ptr item); - virtual int getMaxStackSize(); - virtual void setChanged(); - bool stillValid(std::shared_ptr player); - - void startOpen() { } // TODO Auto-generated method stub - void stopOpen() { } // TODO Auto-generated method stub + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + std::shared_ptr getItem(unsigned int x, unsigned int y); + virtual int getName(); + virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + virtual void setItem(unsigned int slot, std::shared_ptr item); + virtual int getMaxStackSize(); + virtual void setChanged(); + bool stillValid(std::shared_ptr player); + void startOpen() {} // TODO Auto-generated method stub + void stopOpen() {} // TODO Auto-generated method stub }; diff --git a/Minecraft.World/Containers/CraftingMenu.cpp b/Minecraft.World/Containers/CraftingMenu.cpp index 411fd1491..1b675b464 100644 --- a/Minecraft.World/Containers/CraftingMenu.cpp +++ b/Minecraft.World/Containers/CraftingMenu.cpp @@ -17,122 +17,106 @@ const int CraftingMenu::INV_SLOT_END = CraftingMenu::INV_SLOT_START + 9 * 3; const int CraftingMenu::USE_ROW_SLOT_START = CraftingMenu::INV_SLOT_END; const int CraftingMenu::USE_ROW_SLOT_END = CraftingMenu::USE_ROW_SLOT_START + 9; -CraftingMenu::CraftingMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt) : AbstractContainerMenu() -{ - craftSlots = std::shared_ptr( new CraftingContainer(this, 3, 3) ); - resultSlots = std::shared_ptr( new ResultContainer() ); +CraftingMenu::CraftingMenu(std::shared_ptr inventory, Level* level, + int xt, int yt, int zt) + : AbstractContainerMenu() { + craftSlots = + std::shared_ptr(new CraftingContainer(this, 3, 3)); + resultSlots = std::shared_ptr(new ResultContainer()); - this->level = level; - this->x = xt; - this->y = yt; - this->z = zt; - addSlot(new ResultSlot( inventory->player, craftSlots, resultSlots, 0, 120 + 4, 31 + 4)); + this->level = level; + this->x = xt; + this->y = yt; + this->z = zt; + addSlot(new ResultSlot(inventory->player, craftSlots, resultSlots, 0, + 120 + 4, 31 + 4)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 3; x++) - { - addSlot(new Slot(craftSlots, x + y * 3, 30 + x * 18, 17 + y * 18)); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + addSlot(new Slot(craftSlots, x + y * 3, 30 + x * 18, 17 + y * 18)); + } + } - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } - slotsChanged(); // 4J - removed craftSlots parameter, see comment below + slotsChanged(); // 4J - removed craftSlots parameter, see comment below } -void CraftingMenu::slotsChanged() // 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things +void CraftingMenu::slotsChanged() // 4J used to take a + // std::shared_ptr but wasn't + // using it, so removed to simplify things { - resultSlots->setItem(0, Recipes::getInstance()->getItemFor(craftSlots, level)); + resultSlots->setItem(0, + Recipes::getInstance()->getItemFor(craftSlots, level)); } -void CraftingMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - if (level->isClientSide) return; +void CraftingMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + if (level->isClientSide) return; - for (int i = 0; i < 9; i++) - { - std::shared_ptr item = craftSlots->removeItemNoUpdate(i); - if (item != NULL) - { - player->drop(item); - } - } + for (int i = 0; i < 9; i++) { + std::shared_ptr item = craftSlots->removeItemNoUpdate(i); + if (item != NULL) { + player->drop(item); + } + } } -bool CraftingMenu::stillValid(std::shared_ptr player) -{ - if (level->getTile(x, y, z) != Tile::workBench_Id) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; +bool CraftingMenu::stillValid(std::shared_ptr player) { + if (level->getTile(x, y, z) != Tile::workBench_Id) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } -std::shared_ptr CraftingMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); +std::shared_ptr CraftingMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex == RESULT_SLOT) - { - if(!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); - } - else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - if(!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - if(!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - else - { - if(!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - // nothing moved - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + if (slotIndex == RESULT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) { + return nullptr; + } + } else { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + // nothing moved + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } \ No newline at end of file diff --git a/Minecraft.World/Containers/CraftingMenu.h b/Minecraft.World/Containers/CraftingMenu.h index 7ebba894a..c59ee7ce1 100644 --- a/Minecraft.World/Containers/CraftingMenu.h +++ b/Minecraft.World/Containers/CraftingMenu.h @@ -5,31 +5,34 @@ class CraftingContainer; class Container; -class CraftingMenu : public AbstractContainerMenu -{ - // 4J Stu Made these public for UI menus, perhaps should make friend class? +class CraftingMenu : public AbstractContainerMenu { + // 4J Stu Made these public for UI menus, perhaps should make friend class? public: - static const int RESULT_SLOT; - static const int CRAFT_SLOT_START; - static const int CRAFT_SLOT_END; - static const int INV_SLOT_START; - static const int INV_SLOT_END; - static const int USE_ROW_SLOT_START; - static const int USE_ROW_SLOT_END; + static const int RESULT_SLOT; + static const int CRAFT_SLOT_START; + static const int CRAFT_SLOT_END; + static const int INV_SLOT_START; + static const int INV_SLOT_END; + static const int USE_ROW_SLOT_START; + static const int USE_ROW_SLOT_END; public: - std::shared_ptr craftSlots; - std::shared_ptr resultSlots; + std::shared_ptr craftSlots; + std::shared_ptr resultSlots; private: - Level *level; - int x, y, z; + Level* level; + int x, y, z; public: - CraftingMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt); + CraftingMenu(std::shared_ptr inventory, Level* level, int xt, + int yt, int zt); - virtual void slotsChanged();// 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things - virtual void removed(std::shared_ptr player); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); + virtual void + slotsChanged(); // 4J used to take a std::shared_ptr but wasn't + // using it, so removed to simplify things + virtual void removed(std::shared_ptr player); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/EnchantmentContainer.cpp b/Minecraft.World/Containers/EnchantmentContainer.cpp index fc9ba8829..5cf155da8 100644 --- a/Minecraft.World/Containers/EnchantmentContainer.cpp +++ b/Minecraft.World/Containers/EnchantmentContainer.cpp @@ -2,17 +2,12 @@ #include "../Headers/net.minecraft.world.inventory.h" #include "EnchantmentContainer.h" -EnchantmentContainer::EnchantmentContainer(EnchantmentMenu *menu) : SimpleContainer(IDS_ENCHANT, 1), m_menu( menu ) -{ -} +EnchantmentContainer::EnchantmentContainer(EnchantmentMenu* menu) + : SimpleContainer(IDS_ENCHANT, 1), m_menu(menu) {} -int EnchantmentContainer::getMaxStackSize() -{ - return 1; -} +int EnchantmentContainer::getMaxStackSize() { return 1; } -void EnchantmentContainer::setChanged() -{ - SimpleContainer::setChanged(); - m_menu->slotsChanged(); // Remove this param as it's not needed +void EnchantmentContainer::setChanged() { + SimpleContainer::setChanged(); + m_menu->slotsChanged(); // Remove this param as it's not needed } diff --git a/Minecraft.World/Containers/EnchantmentContainer.h b/Minecraft.World/Containers/EnchantmentContainer.h index 48d8687fb..ac764563a 100644 --- a/Minecraft.World/Containers/EnchantmentContainer.h +++ b/Minecraft.World/Containers/EnchantmentContainer.h @@ -1,18 +1,18 @@ #pragma once // 4J Stu Added -// In EnchantmentMenu.java they create an anoymous class while creating the container. I have moved the content -// of that anonymous class to here +// In EnchantmentMenu.java they create an anoymous class while creating the +// container. I have moved the content of that anonymous class to here #include "SimpleContainer.h" class EnchantmentMenu; -class EnchantmentContainer : public SimpleContainer -{ +class EnchantmentContainer : public SimpleContainer { private: - EnchantmentMenu *m_menu; + EnchantmentMenu* m_menu; + public: - EnchantmentContainer(EnchantmentMenu *menu); - virtual int getMaxStackSize(); - virtual void setChanged(); + EnchantmentContainer(EnchantmentMenu* menu); + virtual int getMaxStackSize(); + virtual void setChanged(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/EnchantmentMenu.cpp b/Minecraft.World/Containers/EnchantmentMenu.cpp index 5ec382e38..1c1bb52ac 100644 --- a/Minecraft.World/Containers/EnchantmentMenu.cpp +++ b/Minecraft.World/Containers/EnchantmentMenu.cpp @@ -7,293 +7,246 @@ #include "../Headers/net.minecraft.world.item.enchantment.h" #include "EnchantmentMenu.h" -EnchantmentMenu::EnchantmentMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt) -{ - enchantSlots = std::shared_ptr( new EnchantmentContainer(this) ); +EnchantmentMenu::EnchantmentMenu(std::shared_ptr inventory, + Level* level, int xt, int yt, int zt) { + enchantSlots = + std::shared_ptr(new EnchantmentContainer(this)); - for(int i = 0; i < 3; ++i) - { - costs[i] = 0; - } + for (int i = 0; i < 3; ++i) { + costs[i] = 0; + } - this->level = level; - this->x = xt; - this->y = yt; - this->z = zt; - addSlot(new EnchantmentSlot(enchantSlots, 0, 21 + 4, 43 + 4)); + this->level = level; + this->x = xt; + this->y = yt; + this->z = zt; + addSlot(new EnchantmentSlot(enchantSlots, 0, 21 + 4, 43 + 4)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } - m_costsChanged = false; + m_costsChanged = false; } -void EnchantmentMenu::addSlotListener(ContainerListener *listener) -{ - AbstractContainerMenu::addSlotListener(listener); +void EnchantmentMenu::addSlotListener(ContainerListener* listener) { + AbstractContainerMenu::addSlotListener(listener); - listener->setContainerData(this, 0, costs[0]); - listener->setContainerData(this, 1, costs[1]); - listener->setContainerData(this, 2, costs[2]); + listener->setContainerData(this, 0, costs[0]); + listener->setContainerData(this, 1, costs[1]); + listener->setContainerData(this, 2, costs[2]); } -void EnchantmentMenu::broadcastChanges() -{ - AbstractContainerMenu::broadcastChanges(); +void EnchantmentMenu::broadcastChanges() { + AbstractContainerMenu::broadcastChanges(); - // 4J Added m_costsChanged to stop continually sending update packets even when no changes have been made - if(m_costsChanged) - { - for (int i = 0; i < containerListeners->size(); i++) - { - ContainerListener *listener = containerListeners->at(i); - listener->setContainerData(this, 0, costs[0]); - listener->setContainerData(this, 1, costs[1]); - listener->setContainerData(this, 2, costs[2]); - } - m_costsChanged = false; - } + // 4J Added m_costsChanged to stop continually sending update packets even + // when no changes have been made + if (m_costsChanged) { + for (int i = 0; i < containerListeners->size(); i++) { + ContainerListener* listener = containerListeners->at(i); + listener->setContainerData(this, 0, costs[0]); + listener->setContainerData(this, 1, costs[1]); + listener->setContainerData(this, 2, costs[2]); + } + m_costsChanged = false; + } } -void EnchantmentMenu::setData(int id, int value) -{ - if (id >= 0 && id <= 2) - { - costs[id] = value; - m_costsChanged = true; - } - else - { - AbstractContainerMenu::setData(id, value); - } +void EnchantmentMenu::setData(int id, int value) { + if (id >= 0 && id <= 2) { + costs[id] = value; + m_costsChanged = true; + } else { + AbstractContainerMenu::setData(id, value); + } } -void EnchantmentMenu::slotsChanged() // 4J used to take a std::shared_ptr container but wasn't using it, so removed to simplify things +void EnchantmentMenu:: + slotsChanged() // 4J used to take a std::shared_ptr container + // but wasn't using it, so removed to simplify things { - std::shared_ptr item = enchantSlots->getItem(0); + std::shared_ptr item = enchantSlots->getItem(0); - if (item == NULL || !item->isEnchantable()) - { - for (int i = 0; i < 3; i++) - { - costs[i] = 0; - } - m_costsChanged = true; - } - else - { - nameSeed = random.nextLong(); + if (item == NULL || !item->isEnchantable()) { + for (int i = 0; i < 3; i++) { + costs[i] = 0; + } + m_costsChanged = true; + } else { + nameSeed = random.nextLong(); - if (!level->isClientSide) - { - // find book cases - int bookcases = 0; - for (int oz = -1; oz <= 1; oz++) - { - for (int ox = -1; ox <= 1; ox++) - { - if (oz == 0 && ox == 0) - { - continue; - } + if (!level->isClientSide) { + // find book cases + int bookcases = 0; + for (int oz = -1; oz <= 1; oz++) { + for (int ox = -1; ox <= 1; ox++) { + if (oz == 0 && ox == 0) { + continue; + } - if (level->isEmptyTile(x + ox, y, z + oz) && level->isEmptyTile(x + ox, y + 1, z + oz)) - { - if (level->getTile(x + ox * 2, y, z + oz * 2) == Tile::bookshelf_Id) - { - bookcases++; - } - if (level->getTile(x + ox * 2, y + 1, z + oz * 2) == Tile::bookshelf_Id) - { - bookcases++; - } - // corners - if (ox != 0 && oz != 0) - { - if (level->getTile(x + ox * 2, y, z + oz) == Tile::bookshelf_Id) - { - bookcases++; - } - if (level->getTile(x + ox * 2, y + 1, z + oz) == Tile::bookshelf_Id) - { - bookcases++; - } - if (level->getTile(x + ox, y, z + oz * 2) == Tile::bookshelf_Id) - { - bookcases++; - } - if (level->getTile(x + ox, y + 1, z + oz * 2) == Tile::bookshelf_Id) - { - bookcases++; - } - } - } - } - } + if (level->isEmptyTile(x + ox, y, z + oz) && + level->isEmptyTile(x + ox, y + 1, z + oz)) { + if (level->getTile(x + ox * 2, y, z + oz * 2) == + Tile::bookshelf_Id) { + bookcases++; + } + if (level->getTile(x + ox * 2, y + 1, z + oz * 2) == + Tile::bookshelf_Id) { + bookcases++; + } + // corners + if (ox != 0 && oz != 0) { + if (level->getTile(x + ox * 2, y, z + oz) == + Tile::bookshelf_Id) { + bookcases++; + } + if (level->getTile(x + ox * 2, y + 1, z + oz) == + Tile::bookshelf_Id) { + bookcases++; + } + if (level->getTile(x + ox, y, z + oz * 2) == + Tile::bookshelf_Id) { + bookcases++; + } + if (level->getTile(x + ox, y + 1, z + oz * 2) == + Tile::bookshelf_Id) { + bookcases++; + } + } + } + } + } - for (int i = 0; i < 3; i++) - { - costs[i] = EnchantmentHelper::getEnchantmentCost(&random, i, bookcases, item); - } - m_costsChanged = true; - broadcastChanges(); - } - } + for (int i = 0; i < 3; i++) { + costs[i] = EnchantmentHelper::getEnchantmentCost( + &random, i, bookcases, item); + } + m_costsChanged = true; + broadcastChanges(); + } + } } -bool EnchantmentMenu::clickMenuButton(std::shared_ptr player, int i) -{ - std::shared_ptr item = enchantSlots->getItem(0); - if (costs[i] > 0 && item != NULL && (player->experienceLevel >= costs[i] || player->abilities.instabuild) ) - { - if (!level->isClientSide) - { - bool isBook = item->id == Item::book_Id; +bool EnchantmentMenu::clickMenuButton(std::shared_ptr player, int i) { + std::shared_ptr item = enchantSlots->getItem(0); + if (costs[i] > 0 && item != NULL && + (player->experienceLevel >= costs[i] || player->abilities.instabuild)) { + if (!level->isClientSide) { + bool isBook = item->id == Item::book_Id; - std::vector *newEnchantment = EnchantmentHelper::selectEnchantment(&random, item, costs[i]); - if (newEnchantment != NULL) - { - player->withdrawExperienceLevels(costs[i]); - if (isBook) item->id = Item::enchantedBook_Id; - int randomIndex = isBook ? random.nextInt(newEnchantment->size()) : -1; - //for (EnchantmentInstance e : newEnchantment) - for (int index = 0; index < newEnchantment->size(); index++) - { - EnchantmentInstance *e = newEnchantment->at(index); - if (isBook && index != randomIndex) - {} - else - { - if (isBook) - { - Item::enchantedBook->addEnchantment(item, e); - } - else - { - item->enchant(e->enchantment, e->level); - } - } - delete e; - } - delete newEnchantment; - slotsChanged();// Removed enchantSlots parameter as the function can reference it directly - } - } - return true; - } - return false; + std::vector* newEnchantment = + EnchantmentHelper::selectEnchantment(&random, item, costs[i]); + if (newEnchantment != NULL) { + player->withdrawExperienceLevels(costs[i]); + if (isBook) item->id = Item::enchantedBook_Id; + int randomIndex = + isBook ? random.nextInt(newEnchantment->size()) : -1; + // for (EnchantmentInstance e : newEnchantment) + for (int index = 0; index < newEnchantment->size(); index++) { + EnchantmentInstance* e = newEnchantment->at(index); + if (isBook && index != randomIndex) { + } else { + if (isBook) { + Item::enchantedBook->addEnchantment(item, e); + } else { + item->enchant(e->enchantment, e->level); + } + } + delete e; + } + delete newEnchantment; + slotsChanged(); // Removed enchantSlots parameter as the + // function can reference it directly + } + } + return true; + } + return false; } +void EnchantmentMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + if (level->isClientSide) return; -void EnchantmentMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - if (level->isClientSide) return; - - std::shared_ptr item = enchantSlots->removeItemNoUpdate(0); - if (item != NULL) - { - player->drop(item); - } + std::shared_ptr item = enchantSlots->removeItemNoUpdate(0); + if (item != NULL) { + player->drop(item); + } } -bool EnchantmentMenu::stillValid(std::shared_ptr player) -{ - if (level->getTile(x, y, z) != Tile::enchantTable_Id) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; +bool EnchantmentMenu::stillValid(std::shared_ptr player) { + if (level->getTile(x, y, z) != Tile::enchantTable_Id) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } -std::shared_ptr EnchantmentMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - Slot *IngredientSlot = slots->at(INGREDIENT_SLOT); +std::shared_ptr EnchantmentMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + Slot* IngredientSlot = slots->at(INGREDIENT_SLOT); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex == INGREDIENT_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, true)) - { - if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } + if (slotIndex == INGREDIENT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, true)) { + if (!moveItemStackTo(stack, USE_ROW_SLOT_START, + USE_ROW_SLOT_END, false)) { + return nullptr; + } + } + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + // if the item is an enchantable tool - } - } - else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - // if the item is an enchantable tool - - if(stack->isEnchantable() && (!IngredientSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false)) - { - return nullptr; - } - } - else - { - if(!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - } - else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - // if the item is an enchantable tool + if (stack->isEnchantable() && (!IngredientSlot->hasItem())) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, + INGREDIENT_SLOT + 1, false)) { + return nullptr; + } + } else { + if (!moveItemStackTo(stack, USE_ROW_SLOT_START, + USE_ROW_SLOT_END, false)) { + return nullptr; + } + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + // if the item is an enchantable tool - if(stack->isEnchantable() && (!IngredientSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT+1, false)) - { - return nullptr; - } - } - else - { - if(!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - } - else - { - return nullptr; - } + if (stack->isEnchantable() && (!IngredientSlot->hasItem())) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, + INGREDIENT_SLOT + 1, false)) { + return nullptr; + } + } else { + if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, + false)) { + return nullptr; + } + } + } else { + return nullptr; + } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } \ No newline at end of file diff --git a/Minecraft.World/Containers/EnchantmentMenu.h b/Minecraft.World/Containers/EnchantmentMenu.h index 7c4fd4138..c93c80996 100644 --- a/Minecraft.World/Containers/EnchantmentMenu.h +++ b/Minecraft.World/Containers/EnchantmentMenu.h @@ -2,40 +2,43 @@ #include "AbstractContainerMenu.h" #include "../Util/Random.h" -class EnchantmentMenu : public AbstractContainerMenu -{ - // 4J Stu Made these public for UI menus, perhaps should make friend class? +class EnchantmentMenu : public AbstractContainerMenu { + // 4J Stu Made these public for UI menus, perhaps should make friend class? public: - static const int INGREDIENT_SLOT = 0; - static const int INV_SLOT_START = EnchantmentMenu::INGREDIENT_SLOT + 1; - static const int INV_SLOT_END = EnchantmentMenu::INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = EnchantmentMenu::INV_SLOT_END; - static const int USE_ROW_SLOT_END = EnchantmentMenu::USE_ROW_SLOT_START + 9; + static const int INGREDIENT_SLOT = 0; + static const int INV_SLOT_START = EnchantmentMenu::INGREDIENT_SLOT + 1; + static const int INV_SLOT_END = EnchantmentMenu::INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = EnchantmentMenu::INV_SLOT_END; + static const int USE_ROW_SLOT_END = EnchantmentMenu::USE_ROW_SLOT_START + 9; public: - std::shared_ptr enchantSlots; + std::shared_ptr enchantSlots; private: - Level *level; - int x, y, z; - Random random; + Level* level; + int x, y, z; + Random random; - bool m_costsChanged; // 4J Added + bool m_costsChanged; // 4J Added public: - __int64 nameSeed; + __int64 nameSeed; public: - int costs[3]; + int costs[3]; - EnchantmentMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt); + EnchantmentMenu(std::shared_ptr inventory, Level* level, int xt, + int yt, int zt); - virtual void addSlotListener(ContainerListener *listener); - virtual void broadcastChanges(); - virtual void setData(int id, int value); - virtual void slotsChanged();// 4J used to take a std::shared_ptr container but wasn't using it, so removed to simplify things - virtual bool clickMenuButton(std::shared_ptr player, int i); - void removed(std::shared_ptr player); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); + virtual void addSlotListener(ContainerListener* listener); + virtual void broadcastChanges(); + virtual void setData(int id, int value); + virtual void + slotsChanged(); // 4J used to take a std::shared_ptr container + // but wasn't using it, so removed to simplify things + virtual bool clickMenuButton(std::shared_ptr player, int i); + void removed(std::shared_ptr player); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/EnchantmentSlot.h b/Minecraft.World/Containers/EnchantmentSlot.h index c86152887..3ac9bfccd 100644 --- a/Minecraft.World/Containers/EnchantmentSlot.h +++ b/Minecraft.World/Containers/EnchantmentSlot.h @@ -1,16 +1,18 @@ #pragma once // 4J Stu Added -// In EnchantmentMenu.java they create an anoymous class while creating some slot. I have moved the content -// of that anonymous class to here +// In EnchantmentMenu.java they create an anoymous class while creating some +// slot. I have moved the content of that anonymous class to here #include "Slot.h" class Container; -class EnchantmentSlot : public Slot -{ +class EnchantmentSlot : public Slot { public: - EnchantmentSlot(std::shared_ptr container, int id, int x, int y) : Slot(container,id, x, y) {} - virtual bool mayPlace(std::shared_ptr item) {return true;} - virtual bool mayCombine(std::shared_ptr item) {return false;} // 4J Added + EnchantmentSlot(std::shared_ptr container, int id, int x, int y) + : Slot(container, id, x, y) {} + virtual bool mayPlace(std::shared_ptr item) { return true; } + virtual bool mayCombine(std::shared_ptr item) { + return false; + } // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/FurnaceMenu.cpp b/Minecraft.World/Containers/FurnaceMenu.cpp index 376aa239e..17fb4aeea 100644 --- a/Minecraft.World/Containers/FurnaceMenu.cpp +++ b/Minecraft.World/Containers/FurnaceMenu.cpp @@ -8,171 +8,154 @@ #include "FurnaceMenu.h" #include "../Recipes/FurnaceRecipes.h" -FurnaceMenu::FurnaceMenu(std::shared_ptr inventory, std::shared_ptr furnace) : AbstractContainerMenu() -{ - tc = 0; - lt = 0; - ld = 0; +FurnaceMenu::FurnaceMenu(std::shared_ptr inventory, + std::shared_ptr furnace) + : AbstractContainerMenu() { + tc = 0; + lt = 0; + ld = 0; - this->furnace = furnace; + this->furnace = furnace; - addSlot(new Slot(furnace, 0, 52 + 4, 13 + 4)); - addSlot(new Slot(furnace, 1, 52 + 4, 49 + 4)); - addSlot(new FurnaceResultSlot( std::dynamic_pointer_cast( inventory->player->shared_from_this() ), furnace, 2, 112 + 4, 31 + 4)); + addSlot(new Slot(furnace, 0, 52 + 4, 13 + 4)); + addSlot(new Slot(furnace, 1, 52 + 4, 49 + 4)); + addSlot(new FurnaceResultSlot(std::dynamic_pointer_cast( + inventory->player->shared_from_this()), + furnace, 2, 112 + 4, 31 + 4)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } } -void FurnaceMenu::addSlotListener(ContainerListener *listener) -{ - AbstractContainerMenu::addSlotListener(listener); - listener->setContainerData(this, 0, furnace->tickCount); - listener->setContainerData(this, 1, furnace->litTime); - listener->setContainerData(this, 2, furnace->litDuration); +void FurnaceMenu::addSlotListener(ContainerListener* listener) { + AbstractContainerMenu::addSlotListener(listener); + listener->setContainerData(this, 0, furnace->tickCount); + listener->setContainerData(this, 1, furnace->litTime); + listener->setContainerData(this, 2, furnace->litDuration); } -void FurnaceMenu::broadcastChanges() -{ - AbstractContainerMenu::broadcastChanges(); - - AUTO_VAR(itEnd, containerListeners->end()); - for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) - { - ContainerListener *listener = *it; //containerListeners->at(i); - if (tc != furnace->tickCount) - { - listener->setContainerData(this, 0, furnace->tickCount); - } - if (lt != furnace->litTime) - { - listener->setContainerData(this, 1, furnace->litTime); - } - if (ld != furnace->litDuration) - { - listener->setContainerData(this, 2, furnace->litDuration); - } - } +void FurnaceMenu::broadcastChanges() { + AbstractContainerMenu::broadcastChanges(); - tc = furnace->tickCount; - lt = furnace->litTime; - ld = furnace->litDuration; + AUTO_VAR(itEnd, containerListeners->end()); + for (AUTO_VAR(it, containerListeners->begin()); it != itEnd; it++) { + ContainerListener* listener = *it; // containerListeners->at(i); + if (tc != furnace->tickCount) { + listener->setContainerData(this, 0, furnace->tickCount); + } + if (lt != furnace->litTime) { + listener->setContainerData(this, 1, furnace->litTime); + } + if (ld != furnace->litDuration) { + listener->setContainerData(this, 2, furnace->litDuration); + } + } + + tc = furnace->tickCount; + lt = furnace->litTime; + ld = furnace->litDuration; } -void FurnaceMenu::setData(int id, int value) -{ - if (id == 0) furnace->tickCount = value; - if (id == 1) furnace->litTime = value; - if (id == 2) furnace->litDuration = value; +void FurnaceMenu::setData(int id, int value) { + if (id == 0) furnace->tickCount = value; + if (id == 1) furnace->litTime = value; + if (id == 2) furnace->litDuration = value; } -bool FurnaceMenu::stillValid(std::shared_ptr player) -{ - return furnace->stillValid(player); +bool FurnaceMenu::stillValid(std::shared_ptr player) { + return furnace->stillValid(player); } -std::shared_ptr FurnaceMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - //Slot *IngredientSlot = slots->at(INGREDIENT_SLOT); +std::shared_ptr FurnaceMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + // Slot *IngredientSlot = slots->at(INGREDIENT_SLOT); - bool charcoalUsed = furnace->wasCharcoalUsed(); + bool charcoalUsed = furnace->wasCharcoalUsed(); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex == RESULT_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); + if (slotIndex == RESULT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); - // 4J-JEV, hook for Durango achievement 'Renewable Energy'. + // 4J-JEV, hook for Durango achievement 'Renewable Energy'. #ifdef _EXTENDED_ACHIEVEMENTS - if ( charcoalUsed && stack->getItem()->id == Item::coal_Id && stack->getAuxValue() == CoalItem::CHAR_COAL) - player->awardStat(GenericStats::renewableEnergy(),GenericStats::param_renewableEnergy()); + if (charcoalUsed && stack->getItem()->id == Item::coal_Id && + stack->getAuxValue() == CoalItem::CHAR_COAL) + player->awardStat(GenericStats::renewableEnergy(), + GenericStats::param_renewableEnergy()); #endif - } - else if (slotIndex == FUEL_SLOT || slotIndex == INGREDIENT_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (FurnaceRecipes::getInstance()->getResult(stack->getItem()->id) != NULL) - { - if (!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT + 1, false)) - { - return nullptr; - } - } - else if (FurnaceTileEntity::isFuel(stack)) - { - if (!moveItemStackTo(stack, FUEL_SLOT, FUEL_SLOT + 1, false)) - { - return nullptr; - } - } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + } else if (slotIndex == FUEL_SLOT || slotIndex == INGREDIENT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (FurnaceRecipes::getInstance()->getResult( + stack->getItem()->id) != NULL) { + if (!moveItemStackTo(stack, INGREDIENT_SLOT, INGREDIENT_SLOT + 1, + false)) { + return nullptr; + } + } else if (FurnaceTileEntity::isFuel(stack)) { + if (!moveItemStackTo(stack, FUEL_SLOT, FUEL_SLOT + 1, false)) { + return nullptr; + } + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } -std::shared_ptr FurnaceMenu::clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player) -{ - bool charcoalUsed = furnace->wasCharcoalUsed(); +std::shared_ptr FurnaceMenu::clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player) { + bool charcoalUsed = furnace->wasCharcoalUsed(); - std::shared_ptr out = AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); + std::shared_ptr out = + AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); #ifdef _EXTENDED_ACHIEVEMENTS - if ( charcoalUsed && (out!=nullptr) && (buttonNum==0 || buttonNum==1) && clickType==CLICK_PICKUP - && out->getItem()->id == Item::coal_Id && out->getAuxValue() == CoalItem::CHAR_COAL ) - { - player->awardStat(GenericStats::renewableEnergy(),GenericStats::param_renewableEnergy()); - } + if (charcoalUsed && (out != nullptr) && + (buttonNum == 0 || buttonNum == 1) && clickType == CLICK_PICKUP && + out->getItem()->id == Item::coal_Id && + out->getAuxValue() == CoalItem::CHAR_COAL) { + player->awardStat(GenericStats::renewableEnergy(), + GenericStats::param_renewableEnergy()); + } #endif - return out; + return out; } diff --git a/Minecraft.World/Containers/FurnaceMenu.h b/Minecraft.World/Containers/FurnaceMenu.h index 576a0fa20..03a05ee7c 100644 --- a/Minecraft.World/Containers/FurnaceMenu.h +++ b/Minecraft.World/Containers/FurnaceMenu.h @@ -4,35 +4,38 @@ class FurnaceTileEntity; -class FurnaceMenu : public AbstractContainerMenu -{ - // 4J Stu Made these public for UI menus, perhaps should make friend class? +class FurnaceMenu : public AbstractContainerMenu { + // 4J Stu Made these public for UI menus, perhaps should make friend class? public: - static const int INGREDIENT_SLOT = 0; - static const int FUEL_SLOT = 1; - static const int RESULT_SLOT = 2; - static const int INV_SLOT_START = FurnaceMenu::RESULT_SLOT + 1; - static const int INV_SLOT_END = FurnaceMenu::INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = FurnaceMenu::INV_SLOT_END; - static const int USE_ROW_SLOT_END = FurnaceMenu::USE_ROW_SLOT_START + 9; + static const int INGREDIENT_SLOT = 0; + static const int FUEL_SLOT = 1; + static const int RESULT_SLOT = 2; + static const int INV_SLOT_START = FurnaceMenu::RESULT_SLOT + 1; + static const int INV_SLOT_END = FurnaceMenu::INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = FurnaceMenu::INV_SLOT_END; + static const int USE_ROW_SLOT_END = FurnaceMenu::USE_ROW_SLOT_START + 9; private: - std::shared_ptr furnace; + std::shared_ptr furnace; public: - FurnaceMenu(std::shared_ptr inventory, std::shared_ptr furnace); + FurnaceMenu(std::shared_ptr inventory, + std::shared_ptr furnace); private: - int tc; - int lt; - int ld; + int tc; + int lt; + int ld; public: - virtual void addSlotListener(ContainerListener *listener); - virtual void broadcastChanges(); - virtual void setData(int id, int value); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); + virtual void addSlotListener(ContainerListener* listener); + virtual void broadcastChanges(); + virtual void setData(int id, int value); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); - virtual std::shared_ptr clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player); + virtual std::shared_ptr clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player); }; diff --git a/Minecraft.World/Containers/FurnaceResultSlot.cpp b/Minecraft.World/Containers/FurnaceResultSlot.cpp index d448f3d67..3c81acceb 100644 --- a/Minecraft.World/Containers/FurnaceResultSlot.cpp +++ b/Minecraft.World/Containers/FurnaceResultSlot.cpp @@ -8,87 +8,85 @@ #include "../Util/JavaMath.h" #include "FurnaceResultSlot.h" - -FurnaceResultSlot::FurnaceResultSlot(std::shared_ptr player, std::shared_ptr container, int slot, int x, int y) : Slot( container, slot, x, y ) -{ - this->player = player; - removeCount = 0; +FurnaceResultSlot::FurnaceResultSlot(std::shared_ptr player, + std::shared_ptr container, + int slot, int x, int y) + : Slot(container, slot, x, y) { + this->player = player; + removeCount = 0; } -bool FurnaceResultSlot::mayPlace(std::shared_ptr item) -{ - return false; +bool FurnaceResultSlot::mayPlace(std::shared_ptr item) { + return false; } -std::shared_ptr FurnaceResultSlot::remove(int c) -{ - if (hasItem()) - { - removeCount += std::min(c, getItem()->count); - } - return Slot::remove(c); +std::shared_ptr FurnaceResultSlot::remove(int c) { + if (hasItem()) { + removeCount += std::min(c, getItem()->count); + } + return Slot::remove(c); } -void FurnaceResultSlot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - checkTakeAchievements(carried); - Slot::onTake(player, carried); +void FurnaceResultSlot::onTake(std::shared_ptr player, + std::shared_ptr carried) { + checkTakeAchievements(carried); + Slot::onTake(player, carried); } -void FurnaceResultSlot::onQuickCraft(std::shared_ptr picked, int count) -{ - removeCount += count; - checkTakeAchievements(picked); +void FurnaceResultSlot::onQuickCraft(std::shared_ptr picked, + int count) { + removeCount += count; + checkTakeAchievements(picked); } -bool FurnaceResultSlot::mayCombine(std::shared_ptr second) -{ - return false; +bool FurnaceResultSlot::mayCombine(std::shared_ptr second) { + return false; } -void FurnaceResultSlot::checkTakeAchievements(std::shared_ptr carried) -{ - carried->onCraftedBy(player->level, player, removeCount); - // spawn xp right on top of the player - if (!player->level->isClientSide) - { - int amount = removeCount; - float value = FurnaceRecipes::getInstance()->getRecipeValue(carried->id); +void FurnaceResultSlot::checkTakeAchievements( + std::shared_ptr carried) { + carried->onCraftedBy(player->level, player, removeCount); + // spawn xp right on top of the player + if (!player->level->isClientSide) { + int amount = removeCount; + float value = + FurnaceRecipes::getInstance()->getRecipeValue(carried->id); - if (value == 0) - { - amount = 0; - } - else if (value < 1) - { - int baseValue = floor((float) amount * value); - if (baseValue < ceil((float) amount * value) && (float) Math::random() < (((float) amount * value) - baseValue)) - { - baseValue++; - } - amount = baseValue; - } + if (value == 0) { + amount = 0; + } else if (value < 1) { + int baseValue = floor((float)amount * value); + if (baseValue < ceil((float)amount * value) && + (float)Math::random() < (((float)amount * value) - baseValue)) { + baseValue++; + } + amount = baseValue; + } - while (amount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(amount); - amount -= newCount; - player->level->addEntity(std::shared_ptr( new ExperienceOrb(player->level, player->x, player->y + .5, player->z + .5, newCount) )); - } - } + while (amount > 0) { + int newCount = ExperienceOrb::getExperienceValue(amount); + amount -= newCount; + player->level->addEntity(std::shared_ptr( + new ExperienceOrb(player->level, player->x, player->y + .5, + player->z + .5, newCount))); + } + } #ifdef _DURANGO - if (!player->level->isClientSide && removeCount > 0) - { - player->awardStat( - GenericStats::itemsSmelted(carried->id), - GenericStats::param_itemsSmelted(carried->id, carried->getAuxValue(), removeCount) - ); - } + if (!player->level->isClientSide && removeCount > 0) { + player->awardStat( + GenericStats::itemsSmelted(carried->id), + GenericStats::param_itemsSmelted( + carried->id, carried->getAuxValue(), removeCount)); + } #else - if (carried->id == Item::ironIngot_Id) player->awardStat(GenericStats::acquireIron(), GenericStats::param_acquireIron()); - if (carried->id == Item::fish_cooked_Id) player->awardStat(GenericStats::cookFish(), GenericStats::param_cookFish()); + if (carried->id == Item::ironIngot_Id) + player->awardStat(GenericStats::acquireIron(), + GenericStats::param_acquireIron()); + if (carried->id == Item::fish_cooked_Id) + player->awardStat(GenericStats::cookFish(), + GenericStats::param_cookFish()); #endif - removeCount = 0; + removeCount = 0; } diff --git a/Minecraft.World/Containers/FurnaceResultSlot.h b/Minecraft.World/Containers/FurnaceResultSlot.h index 00967f318..fabf38e09 100644 --- a/Minecraft.World/Containers/FurnaceResultSlot.h +++ b/Minecraft.World/Containers/FurnaceResultSlot.h @@ -2,22 +2,24 @@ #include "Slot.h" -class FurnaceResultSlot : public Slot -{ +class FurnaceResultSlot : public Slot { private: - std::shared_ptr player; - int removeCount; + std::shared_ptr player; + int removeCount; public: - FurnaceResultSlot(std::shared_ptr player, std::shared_ptr container, int slot, int x, int y); - virtual ~FurnaceResultSlot() {} + FurnaceResultSlot(std::shared_ptr player, + std::shared_ptr container, int slot, int x, + int y); + virtual ~FurnaceResultSlot() {} - virtual bool mayPlace(std::shared_ptr item); - virtual std::shared_ptr remove(int c); - virtual void onTake(std::shared_ptr player, std::shared_ptr carried); - virtual bool mayCombine(std::shared_ptr item); // 4J Added + virtual bool mayPlace(std::shared_ptr item); + virtual std::shared_ptr remove(int c); + virtual void onTake(std::shared_ptr player, + std::shared_ptr carried); + virtual bool mayCombine(std::shared_ptr item); // 4J Added protected: - virtual void onQuickCraft(std::shared_ptr picked, int count); - virtual void checkTakeAchievements(std::shared_ptr carried); + virtual void onQuickCraft(std::shared_ptr picked, int count); + virtual void checkTakeAchievements(std::shared_ptr carried); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/Inventory.cpp b/Minecraft.World/Containers/Inventory.cpp index 3d04837ee..acebcf17a 100644 --- a/Minecraft.World/Containers/Inventory.cpp +++ b/Minecraft.World/Containers/Inventory.cpp @@ -13,734 +13,606 @@ const int Inventory::MAX_INVENTORY_STACK_SIZE = 64; const int Inventory::INVENTORY_SIZE = 4 * 9; const int Inventory::SELECTION_SIZE = 9; -// 4J Stu - The Pllayer is managed by std::shared_ptrs elsewhere, but it owns us so we don't want to also -// keep a std::shared_ptr of it. If we pass it on we should use shared_from_this() though -Inventory::Inventory(Player *player) -{ - items = ItemInstanceArray( INVENTORY_SIZE ); - armor = ItemInstanceArray( 4 ); +// 4J Stu - The Pllayer is managed by std::shared_ptrs elsewhere, but it owns us +// so we don't want to also keep a std::shared_ptr of it. If we pass it on we +// should use shared_from_this() though +Inventory::Inventory(Player* player) { + items = ItemInstanceArray(INVENTORY_SIZE); + armor = ItemInstanceArray(4); - selected = 0; + selected = 0; - carried = nullptr; + carried = nullptr; - changed = false; + changed = false; - this->player = player; + this->player = player; } -Inventory::~Inventory() -{ - delete [] items.data; - delete [] armor.data; +Inventory::~Inventory() { + delete[] items.data; + delete[] armor.data; } -std::shared_ptr Inventory::getSelected() -{ - // sanity checking to prevent exploits - if (selected < SELECTION_SIZE && selected >= 0) - { - return items[selected]; - } - return nullptr; +std::shared_ptr Inventory::getSelected() { + // sanity checking to prevent exploits + if (selected < SELECTION_SIZE && selected >= 0) { + return items[selected]; + } + return nullptr; } // 4J-PB - Added for the in-game tooltips -bool Inventory::IsHeldItem() -{ - // sanity checking to prevent exploits - if (selected < SELECTION_SIZE && selected >= 0) - { - if(items[selected]) - { - return true; - } - } - return false; +bool Inventory::IsHeldItem() { + // sanity checking to prevent exploits + if (selected < SELECTION_SIZE && selected >= 0) { + if (items[selected]) { + return true; + } + } + return false; } -int Inventory::getSelectionSize() -{ - return SELECTION_SIZE; +int Inventory::getSelectionSize() { return SELECTION_SIZE; } + +int Inventory::getSlot(int tileId) { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->id == tileId) return i; + } + return -1; } - -int Inventory::getSlot(int tileId) -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->id == tileId) return i; - } - return -1; +int Inventory::getSlot(int tileId, int data) { + for (int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->id == tileId && + items[i]->getAuxValue() == data) + return i; + } + return -1; } -int Inventory::getSlot(int tileId, int data) -{ - for (int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->id == tileId && items[i]->getAuxValue() == data) return i; - } - return -1; +int Inventory::getSlotWithRemainingSpace(std::shared_ptr item) { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->id == item->id && + items[i]->isStackable() && + items[i]->count < items[i]->getMaxStackSize() && + items[i]->count < getMaxStackSize() && + (!items[i]->isStackedByData() || + items[i]->getAuxValue() == item->getAuxValue()) && + ItemInstance::tagMatches(items[i], item)) { + return i; + } + } + return -1; } -int Inventory::getSlotWithRemainingSpace(std::shared_ptr item) -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->id == item->id && items[i]->isStackable() - && items[i]->count < items[i]->getMaxStackSize() && items[i]->count < getMaxStackSize() - && (!items[i]->isStackedByData() || items[i]->getAuxValue() == item->getAuxValue()) - && ItemInstance::tagMatches(items[i], item)) - { - return i; - } - } - return -1; +int Inventory::getFreeSlot() { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] == NULL) return i; + } + return -1; } -int Inventory::getFreeSlot() -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] == NULL) return i; - } - return -1; +void Inventory::grabTexture(int id, int data, bool checkData, bool mayReplace) { + int slot = -1; + heldItem = getSelected(); + if (checkData) { + slot = getSlot(id, data); + } else { + slot = getSlot(id); + } + if (slot >= 0 && slot < 9) { + selected = slot; + return; + } + + if (mayReplace) { + if (id > 0) { + int firstEmpty = getFreeSlot(); + if (firstEmpty >= 0 && firstEmpty < 9) { + selected = firstEmpty; + } + + replaceSlot(Item::items[id], data); + } + } } +void Inventory::swapPaint(int wheel) { + if (wheel > 0) wheel = 1; + if (wheel < 0) wheel = -1; -void Inventory::grabTexture(int id, int data, bool checkData, bool mayReplace) -{ - int slot = -1; - heldItem = getSelected(); - if (checkData) - { - slot = getSlot(id, data); - } - else - { - slot = getSlot(id); - } - if (slot >= 0 && slot < 9) - { - selected = slot; - return; - } + selected -= wheel; - if (mayReplace) - { - if (id > 0) - { - int firstEmpty = getFreeSlot(); - if (firstEmpty >= 0 && firstEmpty < 9) - { - selected = firstEmpty; - } - - replaceSlot(Item::items[id], data); - } - } + while (selected < 0) selected += 9; + while (selected >= 9) selected -= 9; } -void Inventory::swapPaint(int wheel) -{ - if (wheel > 0) wheel = 1; - if (wheel < 0) wheel = -1; - - selected -= wheel; - - while (selected < 0) - selected += 9; - while (selected >= 9) - selected -= 9; +void Inventory::clearInventory() { + for (unsigned int i = 0; i < items.length; i++) { + items[i] = nullptr; + } + for (unsigned int i = 0; i < armor.length; i++) { + armor[i] = nullptr; + } } -void Inventory::clearInventory() -{ - for (unsigned int i = 0; i < items.length; i++) - { - items[i] = nullptr; - } - for (unsigned int i = 0; i < armor.length; i++) - { - armor[i] = nullptr; - } +void Inventory::replaceSlot(Item* item, int data) { + if (item != NULL) { + int oldSlot = getSlot(item->id, data); + if (oldSlot >= 0) { + items[oldSlot] = items[selected]; + } + + // It's too easy to accidentally pick block and lose enchanted + // items. + if (heldItem != NULL && heldItem->isEnchantable() && + getSlot(heldItem->id, heldItem->getDamageValue()) == selected) { + return; + } + items[selected] = std::shared_ptr( + new ItemInstance(Item::items[item->id], 1, data)); + } } -void Inventory::replaceSlot(Item *item, int data) -{ - if (item != NULL) - { - int oldSlot = getSlot(item->id, data); - if (oldSlot >= 0) - { - items[oldSlot] = items[selected]; - } +int Inventory::addResource(std::shared_ptr itemInstance) { + int type = itemInstance->id; + int count = itemInstance->count; - // It's too easy to accidentally pick block and lose enchanted - // items. - if (heldItem != NULL && heldItem->isEnchantable() && getSlot(heldItem->id, heldItem->getDamageValue()) == selected) - { - return; - } - items[selected] = std::shared_ptr(new ItemInstance(Item::items[item->id], 1, data)); - } + // 4J Stu - Brought forward from 1.2 + if (itemInstance->getMaxStackSize() == 1) { + int slot = getFreeSlot(); + if (slot < 0) return count; + if (items[slot] == NULL) { + items[slot] = ItemInstance::clone(itemInstance); + player->handleCollectItem(itemInstance); + } + return 0; + } + + int slot = getSlotWithRemainingSpace(itemInstance); + if (slot < 0) slot = getFreeSlot(); + if (slot < 0) return count; + if (items[slot] == NULL) { + items[slot] = std::shared_ptr( + new ItemInstance(type, 0, itemInstance->getAuxValue())); + // 4J Stu - Brought forward from 1.2 + if (itemInstance->hasTag()) { + items[slot]->setTag((CompoundTag*)itemInstance->getTag()->copy()); + player->handleCollectItem(itemInstance); + } + } + + int toAdd = count; + if (toAdd > items[slot]->getMaxStackSize() - items[slot]->count) { + toAdd = items[slot]->getMaxStackSize() - items[slot]->count; + } + if (toAdd > getMaxStackSize() - items[slot]->count) { + toAdd = getMaxStackSize() - items[slot]->count; + } + + if (toAdd == 0) return count; + + count -= toAdd; + items[slot]->count += toAdd; + items[slot]->popTime = POP_TIME_DURATION; + + return count; } - -int Inventory::addResource(std::shared_ptr itemInstance) -{ - - int type = itemInstance->id; - int count = itemInstance->count; - - // 4J Stu - Brought forward from 1.2 - if (itemInstance->getMaxStackSize() == 1) - { - int slot = getFreeSlot(); - if (slot < 0) return count; - if (items[slot] == NULL) - { - items[slot] = ItemInstance::clone(itemInstance); - player->handleCollectItem(itemInstance); - } - return 0; - } - - int slot = getSlotWithRemainingSpace(itemInstance); - if (slot < 0) slot = getFreeSlot(); - if (slot < 0) return count; - if (items[slot] == NULL) - { - items[slot] = std::shared_ptr( new ItemInstance(type, 0, itemInstance->getAuxValue()) ); - // 4J Stu - Brought forward from 1.2 - if (itemInstance->hasTag()) - { - items[slot]->setTag((CompoundTag *) itemInstance->getTag()->copy()); - player->handleCollectItem(itemInstance); - } - } - - int toAdd = count; - if (toAdd > items[slot]->getMaxStackSize() - items[slot]->count) - { - toAdd = items[slot]->getMaxStackSize() - items[slot]->count; - } - if (toAdd > getMaxStackSize() - items[slot]->count) - { - toAdd = getMaxStackSize() - items[slot]->count; - } - - if (toAdd == 0) return count; - - count -= toAdd; - items[slot]->count += toAdd; - items[slot]->popTime = POP_TIME_DURATION; - - return count; +void Inventory::tick() { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL) { + items[i]->inventoryTick(player->level, player->shared_from_this(), + i, selected == i); + } + } } +bool Inventory::removeResource(int type) { + int slot = getSlot(type); + if (slot < 0) return false; + if (--items[slot]->count <= 0) items[slot] = nullptr; -void Inventory::tick() -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL) - { - items[i]->inventoryTick(player->level, player->shared_from_this(), i, selected == i); - } - } + return true; } -bool Inventory::removeResource(int type) -{ - int slot = getSlot(type); - if (slot < 0) return false; - if (--items[slot]->count <= 0) items[slot] = nullptr; +bool Inventory::removeResource(int type, int iAuxVal) { + int slot = getSlot(type, iAuxVal); + if (slot < 0) return false; + if (--items[slot]->count <= 0) items[slot] = nullptr; - return true; + return true; } -bool Inventory::removeResource(int type,int iAuxVal) -{ - int slot = getSlot(type,iAuxVal); - if (slot < 0) return false; - if (--items[slot]->count <= 0) items[slot] = nullptr; +void Inventory::removeResources(std::shared_ptr item) { + if (item == NULL) return; - return true; + int countToRemove = item->count; + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->sameItemWithTags(item)) { + int slotCount = items[i]->count; + items[i]->count -= countToRemove; + if (slotCount < countToRemove) { + countToRemove -= slotCount; + } else { + countToRemove = 0; + } + if (items[i]->count <= 0) items[i] = nullptr; + } + } } -void Inventory::removeResources(std::shared_ptr item) -{ - if(item == NULL) return; - - int countToRemove = item->count; - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->sameItemWithTags(item)) - { - int slotCount = items[i]->count; - items[i]->count -= countToRemove; - if(slotCount < countToRemove) - { - countToRemove -= slotCount; - } - else - { - countToRemove = 0; - } - if(items[i]->count <= 0) items[i] = nullptr; - } - } +std::shared_ptr Inventory::getResourceItem(int type) { + int slot = getSlot(type); + if (slot < 0) return nullptr; + return getItem(slot); } -std::shared_ptr Inventory::getResourceItem(int type) -{ - int slot = getSlot(type); - if (slot < 0) return nullptr; - return getItem( slot ); +std::shared_ptr Inventory::getResourceItem(int type, + int iAuxVal) { + int slot = getSlot(type, iAuxVal); + if (slot < 0) return nullptr; + return getItem(slot); } -std::shared_ptr Inventory::getResourceItem(int type,int iAuxVal) -{ - int slot = getSlot(type,iAuxVal); - if (slot < 0) return nullptr; - return getItem( slot ); +bool Inventory::hasResource(int type) { + int slot = getSlot(type); + if (slot < 0) return false; + + return true; } -bool Inventory::hasResource(int type) -{ - int slot = getSlot(type); - if (slot < 0) return false; - - return true; +void Inventory::swapSlots(int from, int to) { + std::shared_ptr tmp = items[to]; + items[to] = items[from]; + items[from] = tmp; } -void Inventory::swapSlots(int from, int to) -{ - std::shared_ptr tmp = items[to]; - items[to] = items[from]; - items[from] = tmp; +bool Inventory::add(std::shared_ptr item) { + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) return true; + + if (!item->isDamaged()) { + int lastSize; + int count = item->count; + do { + lastSize = item->count; + item->count = addResource(item); + } while (item->count > 0 && item->count < lastSize); + if (item->count == lastSize && player->abilities.instabuild) { + // silently destroy the item when having a full inventory + item->count = 0; + return true; + } + if (item->count < lastSize) { + player->awardStat( + GenericStats::itemsCollected(item->id, item->getAuxValue()), + GenericStats::param_itemsCollected(item->id, + item->getAuxValue(), count)); + return true; + } else + return false; + } + + int slot = getFreeSlot(); + if (slot >= 0) { + player->handleCollectItem(item); + + player->awardStat( + GenericStats::itemsCollected(item->id, item->getAuxValue()), + GenericStats::param_itemsCollected(item->id, item->getAuxValue(), + item->GetCount())); + + items[slot] = ItemInstance::clone(item); + items[slot]->popTime = Inventory::POP_TIME_DURATION; + item->count = 0; + return true; + } else if (player->abilities.instabuild) { + // silently destroy the item when having a full inventory + item->count = 0; + return true; + } + return false; } -bool Inventory::add(std::shared_ptr item) -{ - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) return true; +std::shared_ptr Inventory::removeItem(unsigned int slot, + int count) { + ItemInstanceArray pile = items; + if (slot >= items.length) { + pile = armor; + slot -= items.length; + } - if (!item->isDamaged()) - { - int lastSize; - int count = item->count; - do - { - lastSize = item->count; - item->count = addResource(item); - } while (item->count > 0 && item->count < lastSize); - if (item->count == lastSize && player->abilities.instabuild) - { - // silently destroy the item when having a full inventory - item->count = 0; - return true; - } - if( item->count < lastSize ) - { - player->awardStat( - GenericStats::itemsCollected(item->id, item->getAuxValue()), - GenericStats::param_itemsCollected(item->id, item->getAuxValue(), count) - ); - return true; - } - else - return false; - } - - int slot = getFreeSlot(); - if (slot >= 0) - { - player->handleCollectItem(item); - - player->awardStat( - GenericStats::itemsCollected(item->id, item->getAuxValue()), - GenericStats::param_itemsCollected(item->id, item->getAuxValue(), item->GetCount())); - - items[slot] = ItemInstance::clone(item); - items[slot]->popTime = Inventory::POP_TIME_DURATION; - item->count = 0; - return true; - } - else if (player->abilities.instabuild) - { - // silently destroy the item when having a full inventory - item->count = 0; - return true; - } - return false; + if (pile[slot] != NULL) { + if (pile[slot]->count <= count) { + std::shared_ptr item = pile[slot]; + pile[slot] = nullptr; + return item; + } else { + std::shared_ptr i = pile[slot]->remove(count); + if (pile[slot]->count == 0) pile[slot] = nullptr; + return i; + } + } + return nullptr; } -std::shared_ptr Inventory::removeItem(unsigned int slot, int count) -{ +std::shared_ptr Inventory::removeItemNoUpdate(int slot) { + ItemInstanceArray pile = items; + if (slot >= items.length) { + pile = armor; + slot -= items.length; + } - ItemInstanceArray pile = items; - if (slot >= items.length) - { - pile = armor; - slot -= items.length; - } - - if (pile[slot] != NULL) - { - if (pile[slot]->count <= count) - { - std::shared_ptr item = pile[slot]; - pile[slot] = nullptr; - return item; - } - else - { - std::shared_ptr i = pile[slot]->remove(count); - if (pile[slot]->count == 0) pile[slot] = nullptr; - return i; - } - } - return nullptr; + if (pile[slot] != NULL) { + std::shared_ptr item = pile[slot]; + pile[slot] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr Inventory::removeItemNoUpdate(int slot) -{ - ItemInstanceArray pile = items; - if (slot >= items.length) - { - pile = armor; - slot -= items.length; - } - - if (pile[slot] != NULL) - { - std::shared_ptr item = pile[slot]; - pile[slot] = nullptr; - return item; - } - return nullptr; -} - -void Inventory::setItem(unsigned int slot, std::shared_ptr item) -{ +void Inventory::setItem(unsigned int slot, std::shared_ptr item) { #ifdef _DEBUG - if(item!=NULL) - { - std::wstring itemstring=item->toString(); - app.DebugPrintf("Inventory::setItem - slot = %d,\t item = %d ",slot,item->id); - //OutputDebugStringW(itemstring.c_str()); - app.DebugPrintf("\n"); - } + if (item != NULL) { + std::wstring itemstring = item->toString(); + app.DebugPrintf("Inventory::setItem - slot = %d,\t item = %d ", slot, + item->id); + // OutputDebugStringW(itemstring.c_str()); + app.DebugPrintf("\n"); + } #else - if(item!=NULL) - { - app.DebugPrintf("Inventory::setItem - slot = %d,\t item = %d, aux = %d\n",slot,item->id,item->getAuxValue()); - } + if (item != NULL) { + app.DebugPrintf( + "Inventory::setItem - slot = %d,\t item = %d, aux = %d\n", slot, + item->id, item->getAuxValue()); + } #endif - // 4J Stu - Changed this a little from Java to be less funn - if( slot >= items.length ) - { - armor[slot - items.length] = item; - } - else - { - items[slot] = item; - } - player->handleCollectItem(item); - /* - ItemInstanceArray& pile = items; - if (slot >= pile.length) - { - slot -= pile.length; - pile = armor; - } + // 4J Stu - Changed this a little from Java to be less funn + if (slot >= items.length) { + armor[slot - items.length] = item; + } else { + items[slot] = item; + } + player->handleCollectItem(item); + /* + ItemInstanceArray& pile = items; + if (slot >= pile.length) + { + slot -= pile.length; + pile = armor; + } - pile[slot] = item; - */ + pile[slot] = item; + */ } -float Inventory::getDestroySpeed(Tile *tile) -{ - float speed = 1.0f; - if (items[selected] != NULL) speed *= items[selected]->getDestroySpeed(tile); - return speed; +float Inventory::getDestroySpeed(Tile* tile) { + float speed = 1.0f; + if (items[selected] != NULL) + speed *= items[selected]->getDestroySpeed(tile); + return speed; } -ListTag *Inventory::save(ListTag *listTag) -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - items[i]->save(tag); - listTag->add(tag); - } - } - for (unsigned int i = 0; i < armor.length; i++) - { - if (armor[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) (i + 100)); - armor[i]->save(tag); - listTag->add(tag); - } - } - return listTag; +ListTag* Inventory::save(ListTag* listTag) { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + items[i]->save(tag); + listTag->add(tag); + } + } + for (unsigned int i = 0; i < armor.length; i++) { + if (armor[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)(i + 100)); + armor[i]->save(tag); + listTag->add(tag); + } + } + return listTag; } -void Inventory::load(ListTag *inventoryList) -{ - if( items.data != NULL) - { - delete[] items.data; - items.data = NULL; - } - if( armor.data != NULL) - { - delete[] armor.data; - armor.data = NULL; - - } - items = ItemInstanceArray( INVENTORY_SIZE ); - armor = ItemInstanceArray( 4 ); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = inventoryList->get(i); - unsigned int slot = tag->getByte(L"Slot") & 0xff; - std::shared_ptr item = std::shared_ptr( ItemInstance::fromTag(tag) ); - if (item != NULL) - { - if (slot >= 0 && slot < items.length) items[slot] = item; - if (slot >= 100 && slot < armor.length + 100) armor[slot - 100] = item; - } - } +void Inventory::load(ListTag* inventoryList) { + if (items.data != NULL) { + delete[] items.data; + items.data = NULL; + } + if (armor.data != NULL) { + delete[] armor.data; + armor.data = NULL; + } + items = ItemInstanceArray(INVENTORY_SIZE); + armor = ItemInstanceArray(4); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = inventoryList->get(i); + unsigned int slot = tag->getByte(L"Slot") & 0xff; + std::shared_ptr item = + std::shared_ptr(ItemInstance::fromTag(tag)); + if (item != NULL) { + if (slot >= 0 && slot < items.length) items[slot] = item; + if (slot >= 100 && slot < armor.length + 100) + armor[slot - 100] = item; + } + } } -unsigned int Inventory::getContainerSize() -{ - return items.length + 4; +unsigned int Inventory::getContainerSize() { return items.length + 4; } + +std::shared_ptr Inventory::getItem(unsigned int slot) { + // 4J Stu - Changed this a little from the Java so it's less funny + if (slot >= items.length) { + return armor[slot - items.length]; + } else { + return items[slot]; + } + /* + ItemInstanceArray pile = items; + if (slot >= pile.length) + { + slot -= pile.length; + pile = armor; + } + + return pile[slot]; + */ } -std::shared_ptr Inventory::getItem(unsigned int slot) -{ - // 4J Stu - Changed this a little from the Java so it's less funny - if( slot >= items.length ) - { - return armor[ slot - items.length ]; - } - else - { - return items[ slot ]; - } - /* - ItemInstanceArray pile = items; - if (slot >= pile.length) - { - slot -= pile.length; - pile = armor; - } +int Inventory::getName() { return IDS_INVENTORY; } - return pile[slot]; - */ +int Inventory::getMaxStackSize() { return MAX_INVENTORY_STACK_SIZE; } + +int Inventory::getAttackDamage(std::shared_ptr entity) { + std::shared_ptr item = getItem(selected); + if (item != NULL) return item->getAttackDamage(entity); + return 1; } -int Inventory::getName() -{ - return IDS_INVENTORY; +bool Inventory::canDestroy(Tile* tile) { + if (tile->material->isAlwaysDestroyable()) return true; + + std::shared_ptr item = getItem(selected); + if (item != NULL) return item->canDestroySpecial(tile); + return false; } -int Inventory::getMaxStackSize() -{ - return MAX_INVENTORY_STACK_SIZE; +std::shared_ptr Inventory::getArmor(int layer) { + return armor[layer]; } -int Inventory::getAttackDamage(std::shared_ptr entity) -{ - std::shared_ptr item = getItem(selected); - if (item != NULL) return item->getAttackDamage(entity); - return 1; +int Inventory::getArmorValue() { + int val = 0; + for (unsigned int i = 0; i < armor.length; i++) { + if (armor[i] != NULL && + dynamic_cast(armor[i]->getItem()) != NULL) { + int baseProtection = + dynamic_cast(armor[i]->getItem())->defense; + + val += baseProtection; + } + } + return val; } -bool Inventory::canDestroy(Tile *tile) -{ - if (tile->material->isAlwaysDestroyable()) return true; - - std::shared_ptr item = getItem(selected); - if (item != NULL) return item->canDestroySpecial(tile); - return false; +void Inventory::hurtArmor(int dmg) { + dmg = dmg / 4; + if (dmg < 1) { + dmg = 1; + } + for (unsigned int i = 0; i < armor.length; i++) { + if (armor[i] != NULL && + dynamic_cast(armor[i]->getItem()) != NULL) { + armor[i]->hurt(dmg, std::dynamic_pointer_cast( + player->shared_from_this())); + if (armor[i]->count == 0) { + armor[i] = nullptr; + } + } + } } -std::shared_ptr Inventory::getArmor(int layer) -{ - return armor[layer]; +void Inventory::dropAll() { + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL) { + player->drop(items[i], true); + items[i] = nullptr; + } + } + for (unsigned int i = 0; i < armor.length; i++) { + if (armor[i] != NULL) { + player->drop(armor[i], true); + armor[i] = nullptr; + } + } } -int Inventory::getArmorValue() -{ - int val = 0; - for (unsigned int i = 0; i < armor.length; i++) - { - if (armor[i] != NULL && dynamic_cast( armor[i]->getItem() ) != NULL ) - { - int baseProtection = dynamic_cast(armor[i]->getItem())->defense; +void Inventory::setChanged() { changed = true; } - val += baseProtection; - } - } - return val; +bool Inventory::isSame(std::shared_ptr copy) { + for (unsigned int i = 0; i < items.length; i++) { + if (!isSame(copy->items[i], items[i])) return false; + } + for (unsigned int i = 0; i < armor.length; i++) { + if (!isSame(copy->armor[i], armor[i])) return false; + } + return true; } -void Inventory::hurtArmor(int dmg) -{ - dmg = dmg / 4; - if (dmg < 1) - { - dmg = 1; - } - for (unsigned int i = 0; i < armor.length; i++) - { - if (armor[i] != NULL && dynamic_cast( armor[i]->getItem() ) != NULL ) - { - armor[i]->hurt(dmg, std::dynamic_pointer_cast( player->shared_from_this() ) ); - if (armor[i]->count == 0) - { - armor[i] = nullptr; - } - } - } +bool Inventory::isSame(std::shared_ptr a, + std::shared_ptr b) { + if (a == NULL && b == NULL) return true; + if (a == NULL || b == NULL) return false; + + return a->id == b->id && a->count == b->count && + a->getAuxValue() == b->getAuxValue(); } -void Inventory::dropAll() -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL) - { - player->drop(items[i], true); - items[i] = nullptr; - } - } - for (unsigned int i = 0; i < armor.length; i++) - { - if (armor[i] != NULL) - { - player->drop(armor[i], true); - armor[i] = nullptr; - } - } +std::shared_ptr Inventory::copy() { + std::shared_ptr copy = + std::shared_ptr(new Inventory(NULL)); + for (unsigned int i = 0; i < items.length; i++) { + copy->items[i] = items[i] != NULL ? items[i]->copy() : nullptr; + } + for (unsigned int i = 0; i < armor.length; i++) { + copy->armor[i] = armor[i] != NULL ? armor[i]->copy() : nullptr; + } + return copy; } -void Inventory::setChanged() -{ - changed = true; +void Inventory::setCarried(std::shared_ptr carried) { + this->carried = carried; + player->handleCollectItem(carried); } -bool Inventory::isSame(std::shared_ptr copy) -{ - for (unsigned int i = 0; i < items.length; i++) - { - if (!isSame( copy->items[i], items[i])) return false; - } - for (unsigned int i = 0; i < armor.length; i++) - { - if (!isSame( copy->armor[i], armor[i])) return false; - } - return true; +std::shared_ptr Inventory::getCarried() { return carried; } + +bool Inventory::stillValid(std::shared_ptr player) { + if (this->player->removed) return false; + if (player->distanceToSqr(this->player->shared_from_this()) > 8 * 8) + return false; + return true; } - -bool Inventory::isSame(std::shared_ptr a, std::shared_ptr b) -{ - if (a == NULL && b == NULL) return true; - if (a == NULL || b == NULL) return false; - - return a->id == b->id && a->count == b->count && a->getAuxValue() == b->getAuxValue(); +bool Inventory::contains(std::shared_ptr itemInstance) { + for (unsigned int i = 0; i < armor.length; i++) { + if (armor[i] != NULL && armor[i]->equals(itemInstance)) return true; + } + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->equals(itemInstance)) return true; + } + return false; } - -std::shared_ptr Inventory::copy() -{ - std::shared_ptr copy = std::shared_ptr( new Inventory(NULL) ); - for (unsigned int i = 0; i < items.length; i++) - { - copy->items[i] = items[i] != NULL ? items[i]->copy() : nullptr; - } - for (unsigned int i = 0; i < armor.length; i++) - { - copy->armor[i] = armor[i] != NULL ? armor[i]->copy() : nullptr; - } - return copy; +void Inventory::startOpen() { + // TODO Auto-generated method stub } -void Inventory::setCarried(std::shared_ptr carried) -{ - this->carried = carried; - player->handleCollectItem(carried); +void Inventory::stopOpen() { + // TODO Auto-generated method stub } -std::shared_ptr Inventory::getCarried() -{ - return carried; +void Inventory::replaceWith(std::shared_ptr other) { + for (int i = 0; i < items.length; i++) { + items[i] = ItemInstance::clone(other->items[i]); + } + for (int i = 0; i < armor.length; i++) { + armor[i] = ItemInstance::clone(other->armor[i]); + } } -bool Inventory::stillValid(std::shared_ptr player) -{ - if (this->player->removed) return false; - if (player->distanceToSqr(this->player->shared_from_this()) > 8 * 8) return false; - return true; -} - -bool Inventory::contains(std::shared_ptr itemInstance) -{ - for (unsigned int i = 0; i < armor.length; i++) - { - if (armor[i] != NULL && armor[i]->equals(itemInstance)) return true; - } - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->equals(itemInstance)) return true; - } - return false; -} - -void Inventory::startOpen() -{ - // TODO Auto-generated method stub -} - -void Inventory::stopOpen() -{ - // TODO Auto-generated method stub -} - -void Inventory::replaceWith(std::shared_ptr other) -{ - for (int i = 0; i < items.length; i++) - { - items[i] = ItemInstance::clone(other->items[i]); - } - for (int i = 0; i < armor.length; i++) - { - armor[i] = ItemInstance::clone(other->armor[i]); - } -} - -int Inventory::countMatches(std::shared_ptr itemInstance) -{ - if(itemInstance == NULL) return 0; - int count = 0; - //for (unsigned int i = 0; i < armor.length; i++) - //{ - // if (armor[i] != NULL && armor[i]->sameItem(itemInstance)) count += items[i]->count; - //} - for (unsigned int i = 0; i < items.length; i++) - { - if (items[i] != NULL && items[i]->sameItemWithTags(itemInstance)) count += items[i]->count; - } - return count; +int Inventory::countMatches(std::shared_ptr itemInstance) { + if (itemInstance == NULL) return 0; + int count = 0; + // for (unsigned int i = 0; i < armor.length; i++) + //{ + // if (armor[i] != NULL && armor[i]->sameItem(itemInstance)) count += + //items[i]->count; + // } + for (unsigned int i = 0; i < items.length; i++) { + if (items[i] != NULL && items[i]->sameItemWithTags(itemInstance)) + count += items[i]->count; + } + return count; } diff --git a/Minecraft.World/Containers/Inventory.h b/Minecraft.World/Containers/Inventory.h index f03afa9c0..9ffbcacb0 100644 --- a/Minecraft.World/Containers/Inventory.h +++ b/Minecraft.World/Containers/Inventory.h @@ -7,130 +7,133 @@ class Player; class CompoundTag; -class Inventory : public Container -{ +class Inventory : public Container { public: - static const int POP_TIME_DURATION ; - static const int MAX_INVENTORY_STACK_SIZE; + static const int POP_TIME_DURATION; + static const int MAX_INVENTORY_STACK_SIZE; private: - static const int INVENTORY_SIZE; - static const int SELECTION_SIZE; + static const int INVENTORY_SIZE; + static const int SELECTION_SIZE; public: - ItemInstanceArray items; - ItemInstanceArray armor; + ItemInstanceArray items; + ItemInstanceArray armor; - int selected; - Player *player; // This is owned by std::shared_ptrs, but we are owned by it + int selected; + Player* + player; // This is owned by std::shared_ptrs, but we are owned by it private: - std::shared_ptr heldItem; - std::shared_ptr carried; + std::shared_ptr heldItem; + std::shared_ptr carried; public: - bool changed; + bool changed; - Inventory(Player *player); - ~Inventory(); + Inventory(Player* player); + ~Inventory(); - std::shared_ptr getSelected(); - // 4J-PB - Added for the in-game tooltips - bool IsHeldItem(); + std::shared_ptr getSelected(); + // 4J-PB - Added for the in-game tooltips + bool IsHeldItem(); - static int getSelectionSize(); + static int getSelectionSize(); private: - int getSlot(int tileId); - int getSlot(int tileId, int data); + int getSlot(int tileId); + int getSlot(int tileId, int data); + + int getSlotWithRemainingSpace(std::shared_ptr item); - int getSlotWithRemainingSpace(std::shared_ptr item); - public: - int getFreeSlot(); + int getFreeSlot(); - void grabTexture(int id, int data, bool checkData, bool mayReplace); + void grabTexture(int id, int data, bool checkData, bool mayReplace); - void swapPaint(int wheel); + void swapPaint(int wheel); - void clearInventory(); + void clearInventory(); - void replaceSlot(Item *item, int data); + void replaceSlot(Item* item, int data); private: - int addResource(std::shared_ptr itemInstance); + int addResource(std::shared_ptr itemInstance); public: - void tick(); + void tick(); - bool removeResource(int type); + bool removeResource(int type); - // 4J-PB added to get the right resource from the inventory for removal - bool removeResource(int type,int iAuxVal); - void removeResources(std::shared_ptr item); // 4J Added for trading - - // 4J-Stu added to the get the item that would be affected by the removeResource functions - std::shared_ptr getResourceItem(int type); - std::shared_ptr getResourceItem(int type,int iAuxVal); + // 4J-PB added to get the right resource from the inventory for removal + bool removeResource(int type, int iAuxVal); + void removeResources( + std::shared_ptr item); // 4J Added for trading - bool hasResource(int type); + // 4J-Stu added to the get the item that would be affected by the + // removeResource functions + std::shared_ptr getResourceItem(int type); + std::shared_ptr getResourceItem(int type, int iAuxVal); - void swapSlots(int from, int to); + bool hasResource(int type); - bool add(std::shared_ptr item); + void swapSlots(int from, int to); - std::shared_ptr removeItem(unsigned int slot, int count); - virtual std::shared_ptr removeItemNoUpdate(int slot); + bool add(std::shared_ptr item); - void setItem(unsigned int slot, std::shared_ptr item); + std::shared_ptr removeItem(unsigned int slot, int count); + virtual std::shared_ptr removeItemNoUpdate(int slot); - float getDestroySpeed(Tile *tile); + void setItem(unsigned int slot, std::shared_ptr item); - ListTag *save(ListTag *listTag); + float getDestroySpeed(Tile* tile); - void load(ListTag *inventoryList); + ListTag* save(ListTag* listTag); - unsigned int getContainerSize(); + void load(ListTag* inventoryList); - std::shared_ptr getItem(unsigned int slot); + unsigned int getContainerSize(); - int getName(); + std::shared_ptr getItem(unsigned int slot); - int getMaxStackSize(); + int getName(); - int getAttackDamage(std::shared_ptr entity); + int getMaxStackSize(); - bool canDestroy(Tile *tile); + int getAttackDamage(std::shared_ptr entity); - std::shared_ptr getArmor(int layer); + bool canDestroy(Tile* tile); - int getArmorValue(); + std::shared_ptr getArmor(int layer); - void hurtArmor(int dmg); + int getArmorValue(); - void dropAll(); + void hurtArmor(int dmg); - void setChanged(); + void dropAll(); - bool isSame(std::shared_ptr copy); + void setChanged(); + + bool isSame(std::shared_ptr copy); private: - bool isSame(std::shared_ptr a, std::shared_ptr b); + bool isSame(std::shared_ptr a, + std::shared_ptr b); public: - std::shared_ptr copy(); + std::shared_ptr copy(); - void setCarried(std::shared_ptr carried); + void setCarried(std::shared_ptr carried); - std::shared_ptr getCarried(); + std::shared_ptr getCarried(); - bool stillValid(std::shared_ptr player); + bool stillValid(std::shared_ptr player); - bool contains(std::shared_ptr itemInstance); + bool contains(std::shared_ptr itemInstance); - virtual void startOpen(); - virtual void stopOpen(); - void replaceWith(std::shared_ptr other); + virtual void startOpen(); + virtual void stopOpen(); + void replaceWith(std::shared_ptr other); - int countMatches(std::shared_ptr itemInstance); // 4J Added + int countMatches(std::shared_ptr itemInstance); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/InventoryMenu.cpp b/Minecraft.World/Containers/InventoryMenu.cpp index e2d365fa2..2a83d89bf 100644 --- a/Minecraft.World/Containers/InventoryMenu.cpp +++ b/Minecraft.World/Containers/InventoryMenu.cpp @@ -18,230 +18,219 @@ const int InventoryMenu::ARMOR_SLOT_END = InventoryMenu::ARMOR_SLOT_START + 4; const int InventoryMenu::INV_SLOT_START = InventoryMenu::ARMOR_SLOT_END; const int InventoryMenu::INV_SLOT_END = InventoryMenu::INV_SLOT_START + 9 * 3; const int InventoryMenu::USE_ROW_SLOT_START = InventoryMenu::INV_SLOT_END; -const int InventoryMenu::USE_ROW_SLOT_END = InventoryMenu::USE_ROW_SLOT_START + 9; +const int InventoryMenu::USE_ROW_SLOT_END = + InventoryMenu::USE_ROW_SLOT_START + 9; -InventoryMenu::InventoryMenu(std::shared_ptr inventory, bool active, Player *player) : AbstractContainerMenu() -{ - owner = player; - _init( inventory, active ); +InventoryMenu::InventoryMenu(std::shared_ptr inventory, bool active, + Player* player) + : AbstractContainerMenu() { + owner = player; + _init(inventory, active); } -void InventoryMenu::_init(std::shared_ptr inventory, bool active) -{ - craftSlots = std::shared_ptr( new CraftingContainer(this, 2, 2) ); - resultSlots = std::shared_ptr( new ResultContainer() ); +void InventoryMenu::_init(std::shared_ptr inventory, bool active) { + craftSlots = + std::shared_ptr(new CraftingContainer(this, 2, 2)); + resultSlots = std::shared_ptr(new ResultContainer()); - this->active = active; - addSlot(new ResultSlot( inventory->player, craftSlots, resultSlots, 0, 144, 36)); + this->active = active; + addSlot( + new ResultSlot(inventory->player, craftSlots, resultSlots, 0, 144, 36)); - for (int y = 0; y < 2; y++) - { - for (int x = 0; x < 2; x++) - { - addSlot(new Slot(craftSlots, x + y * 2, 88 + x * 18, 26 + y * 18)); - } - } + for (int y = 0; y < 2; y++) { + for (int x = 0; x < 2; x++) { + addSlot(new Slot(craftSlots, x + y * 2, 88 + x * 18, 26 + y * 18)); + } + } - for (int i = 0; i < 4; i++) - { - // 4J Stu I removed an anonymous class that was here whose only purpose seemed to be a way of using the - // loop counter i within the functions, rather than making it a member of the object. I have moved all that - // out to the ArmorSlot class - addSlot(new ArmorSlot(i, inventory, inventory->getContainerSize() - 1 - i, 8, 8 + i * 18) ); - } - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + (y + 1) * 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int i = 0; i < 4; i++) { + // 4J Stu I removed an anonymous class that was here whose only purpose + // seemed to be a way of using the loop counter i within the functions, + // rather than making it a member of the object. I have moved all that + // out to the ArmorSlot class + addSlot(new ArmorSlot(i, inventory, + inventory->getContainerSize() - 1 - i, 8, + 8 + i * 18)); + } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + (y + 1) * 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } - slotsChanged(); // 4J removed craftSlots parameter, see comment below + slotsChanged(); // 4J removed craftSlots parameter, see comment below } -void InventoryMenu::slotsChanged() // 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things +void InventoryMenu::slotsChanged() // 4J used to take a + // std::shared_ptr but wasn't + // using it, so removed to simplify things { - MemSect(23); - resultSlots->setItem(0, Recipes::getInstance()->getItemFor(craftSlots, owner->level) ); - MemSect(0); + MemSect(23); + resultSlots->setItem( + 0, Recipes::getInstance()->getItemFor(craftSlots, owner->level)); + MemSect(0); } -void InventoryMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - for (int i = 0; i < 4; i++) - { - std::shared_ptr item = craftSlots->removeItemNoUpdate(i); - if (item != NULL) - { - player->drop(item); - craftSlots->setItem(i, nullptr); - } - } - resultSlots->setItem(0, nullptr); +void InventoryMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + for (int i = 0; i < 4; i++) { + std::shared_ptr item = craftSlots->removeItemNoUpdate(i); + if (item != NULL) { + player->drop(item); + craftSlots->setItem(i, nullptr); + } + } + resultSlots->setItem(0, nullptr); } -bool InventoryMenu::stillValid(std::shared_ptr player) -{ - return true; +bool InventoryMenu::stillValid(std::shared_ptr player) { return true; } + +std::shared_ptr InventoryMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + + Slot* HelmetSlot = slots->at(ARMOR_SLOT_START); + Slot* ChestplateSlot = slots->at(ARMOR_SLOT_START + 1); + Slot* LeggingsSlot = slots->at(ARMOR_SLOT_START + 2); + Slot* BootsSlot = slots->at(ARMOR_SLOT_START + 3); + + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); + + if (slotIndex == RESULT_SLOT) { + // 4J Stu - Brought forward change from 1.2 + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + // 4J-PB - added for quick equip + if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Helmet && + (!HelmetSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START, + ARMOR_SLOT_START + 1, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Chestplate && + (!ChestplateSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 1, + ARMOR_SLOT_START + 2, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Leggings && + (!LeggingsSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 2, + ARMOR_SLOT_START + 3, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Boots && + (!BootsSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 3, + ARMOR_SLOT_START + 4, false)) { + return nullptr; + } + } + // 4J Stu - Brought forward change from 1.2 + else if (!moveItemStackTo(stack, USE_ROW_SLOT_START, + USE_ROW_SLOT_END, false)) { + return nullptr; + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + // ArmorRecipes::_eArmorType + // eArmourType=ArmorRecipes::GetArmorType(stack->id); + + if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Helmet && + (!HelmetSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START, + ARMOR_SLOT_START + 1, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Chestplate && + (!ChestplateSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 1, + ARMOR_SLOT_START + 2, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Leggings && + (!LeggingsSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 2, + ARMOR_SLOT_START + 3, false)) { + return nullptr; + } + } else if (ArmorRecipes::GetArmorType(stack->id) == + ArmorRecipes::eArmorType_Boots && + (!BootsSlot->hasItem())) { + if (!moveItemStackTo(stack, ARMOR_SLOT_START + 3, + ARMOR_SLOT_START + 4, false)) { + return nullptr; + } + } + // 4J Stu - Brought forward change from 1.2 + else if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, + false)) { + return nullptr; + } + } else { + // 4J Stu - Brought forward change from 1.2 + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + // nothing moved + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } -std::shared_ptr InventoryMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - - Slot *HelmetSlot = slots->at(ARMOR_SLOT_START); - Slot *ChestplateSlot = slots->at(ARMOR_SLOT_START+1); - Slot *LeggingsSlot = slots->at(ARMOR_SLOT_START+2); - Slot *BootsSlot = slots->at(ARMOR_SLOT_START+3); - - - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); - - if (slotIndex == RESULT_SLOT) - { - // 4J Stu - Brought forward change from 1.2 - if(!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); - } - else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - // 4J-PB - added for quick equip - if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Helmet && (!HelmetSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START, ARMOR_SLOT_START+1, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Chestplate && (!ChestplateSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+1, ARMOR_SLOT_START+2, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Leggings && (!LeggingsSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+2, ARMOR_SLOT_START+3, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Boots && (!BootsSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+3, ARMOR_SLOT_START+4, false)) - { - return nullptr; - } - } - // 4J Stu - Brought forward change from 1.2 - else if(!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - //ArmorRecipes::_eArmorType eArmourType=ArmorRecipes::GetArmorType(stack->id); - - if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Helmet && (!HelmetSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START, ARMOR_SLOT_START+1, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Chestplate && (!ChestplateSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+1, ARMOR_SLOT_START+2, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Leggings && (!LeggingsSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+2, ARMOR_SLOT_START+3, false)) - { - return nullptr; - } - } - else if(ArmorRecipes::GetArmorType(stack->id)==ArmorRecipes::eArmorType_Boots && (!BootsSlot->hasItem() ) ) - { - if(!moveItemStackTo(stack, ARMOR_SLOT_START+3, ARMOR_SLOT_START+4, false)) - { - return nullptr; - } - } - // 4J Stu - Brought forward change from 1.2 - else if(!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - else - { - // 4J Stu - Brought forward change from 1.2 - if(!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - // nothing moved - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; -} - -bool InventoryMenu::mayCombine(Slot *slot, std::shared_ptr item) -{ - return slot->mayCombine(item); +bool InventoryMenu::mayCombine(Slot* slot, std::shared_ptr item) { + return slot->mayCombine(item); } // 4J-JEV: Added for achievement 'Iron Man'. -std::shared_ptr InventoryMenu::clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player) -{ - std::shared_ptr out = AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); +std::shared_ptr InventoryMenu::clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player) { + std::shared_ptr out = + AbstractContainerMenu::clicked(slotIndex, buttonNum, clickType, player); #ifdef _EXTENDED_ACHIEVEMENTS - static int ironItems[4] = {Item::helmet_iron_Id,Item::chestplate_iron_Id,Item::leggings_iron_Id,Item::boots_iron_Id}; - for (int i = ARMOR_SLOT_START; i < ARMOR_SLOT_END; i++) - { - Slot *slot = slots->at(i); - if ( (slot==NULL) || (!slot->hasItem()) || (slot->getItem()->getItem()->id != ironItems[i-ARMOR_SLOT_START]) ) - { - return out; - } - } - player->awardStat(GenericStats::ironMan(),GenericStats::param_ironMan()); + static int ironItems[4] = {Item::helmet_iron_Id, Item::chestplate_iron_Id, + Item::leggings_iron_Id, Item::boots_iron_Id}; + for (int i = ARMOR_SLOT_START; i < ARMOR_SLOT_END; i++) { + Slot* slot = slots->at(i); + if ((slot == NULL) || (!slot->hasItem()) || + (slot->getItem()->getItem()->id != + ironItems[i - ARMOR_SLOT_START])) { + return out; + } + } + player->awardStat(GenericStats::ironMan(), GenericStats::param_ironMan()); #endif - return out; + return out; } diff --git a/Minecraft.World/Containers/InventoryMenu.h b/Minecraft.World/Containers/InventoryMenu.h index cd18f95f7..de96f4bd7 100644 --- a/Minecraft.World/Containers/InventoryMenu.h +++ b/Minecraft.World/Containers/InventoryMenu.h @@ -5,40 +5,45 @@ class CraftingContainer; class Container; -class InventoryMenu : public AbstractContainerMenu -{ +class InventoryMenu : public AbstractContainerMenu { private: - Player *owner; + Player* owner; - // 4J Stu Made these public for UI menus, perhaps should make friend class? + // 4J Stu Made these public for UI menus, perhaps should make friend class? public: - static const int RESULT_SLOT; - static const int CRAFT_SLOT_START; - static const int CRAFT_SLOT_END; - static const int ARMOR_SLOT_START; - static const int ARMOR_SLOT_END; - static const int INV_SLOT_START; - static const int INV_SLOT_END; - static const int USE_ROW_SLOT_START; - static const int USE_ROW_SLOT_END; + static const int RESULT_SLOT; + static const int CRAFT_SLOT_START; + static const int CRAFT_SLOT_END; + static const int ARMOR_SLOT_START; + static const int ARMOR_SLOT_END; + static const int INV_SLOT_START; + static const int INV_SLOT_END; + static const int USE_ROW_SLOT_START; + static const int USE_ROW_SLOT_END; public: - std::shared_ptr craftSlots; - std::shared_ptr resultSlots; - bool active; + std::shared_ptr craftSlots; + std::shared_ptr resultSlots; + bool active; - InventoryMenu(std::shared_ptr inventory, bool active, Player *player); + InventoryMenu(std::shared_ptr inventory, bool active, + Player* player); private: - void _init(std::shared_ptr inventory, bool active); + void _init(std::shared_ptr inventory, bool active); public: - virtual void slotsChanged(); // 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things - virtual void removed(std::shared_ptr player); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); - virtual bool mayCombine(Slot *slot, std::shared_ptr item); + virtual void + slotsChanged(); // 4J used to take a std::shared_ptr but wasn't + // using it, so removed to simplify things + virtual void removed(std::shared_ptr player); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); + virtual bool mayCombine(Slot* slot, std::shared_ptr item); - // 4J ADDED, - virtual std::shared_ptr clicked(int slotIndex, int buttonNum, int clickType, std::shared_ptr player); + // 4J ADDED, + virtual std::shared_ptr clicked( + int slotIndex, int buttonNum, int clickType, + std::shared_ptr player); }; diff --git a/Minecraft.World/Containers/MenuBackup.cpp b/Minecraft.World/Containers/MenuBackup.cpp index 86e717dd4..b64e5145d 100644 --- a/Minecraft.World/Containers/MenuBackup.cpp +++ b/Minecraft.World/Containers/MenuBackup.cpp @@ -5,43 +5,38 @@ #include "Slot.h" #include "MenuBackup.h" -MenuBackup::MenuBackup(std::shared_ptr inventory, AbstractContainerMenu *menu) -{ - backups = new std::unordered_map(); +MenuBackup::MenuBackup(std::shared_ptr inventory, + AbstractContainerMenu* menu) { + backups = new std::unordered_map(); - this->inventory = inventory; - this->menu = menu; + this->inventory = inventory; + this->menu = menu; } -void MenuBackup::save(short changeUid) -{ - ItemInstanceArray *backup = new ItemInstanceArray( (int)menu->slots->size() + 1 ); - (*backup)[0] = ItemInstance::clone(inventory->getCarried()); - for (unsigned int i = 0; i < menu->slots->size(); i++) - { - (*backup)[i + 1] = ItemInstance::clone(menu->slots->at(i)->getItem()); - } - // TODO Is std::unordered_map use correct? - // Was backups.put(changeUid, backup); - (*backups)[changeUid] = backup; +void MenuBackup::save(short changeUid) { + ItemInstanceArray* backup = + new ItemInstanceArray((int)menu->slots->size() + 1); + (*backup)[0] = ItemInstance::clone(inventory->getCarried()); + for (unsigned int i = 0; i < menu->slots->size(); i++) { + (*backup)[i + 1] = ItemInstance::clone(menu->slots->at(i)->getItem()); + } + // TODO Is std::unordered_map use correct? + // Was backups.put(changeUid, backup); + (*backups)[changeUid] = backup; } // Cannot use delete as function name as it is a reserved keyword -void MenuBackup::deleteBackup(short changeUid) -{ - // TODO Is the std::unordered_map use correct? - // 4J Was backups.remove(changeUid); - backups->erase(changeUid); +void MenuBackup::deleteBackup(short changeUid) { + // TODO Is the std::unordered_map use correct? + // 4J Was backups.remove(changeUid); + backups->erase(changeUid); } -void MenuBackup::rollback(short changeUid) -{ - ItemInstanceArray *backup = backups->at(changeUid); - backups->clear(); - inventory->setCarried( (*backup)[0] ); - for (unsigned int i = 0; i < menu->slots->size(); i++) - { - menu->slots->at(i)->set( (*backup)[i + 1] ); - } - +void MenuBackup::rollback(short changeUid) { + ItemInstanceArray* backup = backups->at(changeUid); + backups->clear(); + inventory->setCarried((*backup)[0]); + for (unsigned int i = 0; i < menu->slots->size(); i++) { + menu->slots->at(i)->set((*backup)[i + 1]); + } } \ No newline at end of file diff --git a/Minecraft.World/Containers/MenuBackup.h b/Minecraft.World/Containers/MenuBackup.h index b29453a63..e2f4ea083 100644 --- a/Minecraft.World/Containers/MenuBackup.h +++ b/Minecraft.World/Containers/MenuBackup.h @@ -3,19 +3,19 @@ class AbstractContainerMenu; class Inventory; -class MenuBackup -{ +class MenuBackup { private: - std::unordered_map *backups; - std::shared_ptr inventory; - AbstractContainerMenu *menu; + std::unordered_map* backups; + std::shared_ptr inventory; + AbstractContainerMenu* menu; public: - MenuBackup(std::shared_ptr inventory, AbstractContainerMenu *menu); + MenuBackup(std::shared_ptr inventory, + AbstractContainerMenu* menu); - void save(short changeUid); + void save(short changeUid); - // Cannot use delete as function name as it is a reserved keyword - void deleteBackup(short changeUid); - void rollback(short changeUid); + // Cannot use delete as function name as it is a reserved keyword + void deleteBackup(short changeUid); + void rollback(short changeUid); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/Merchant.h b/Minecraft.World/Containers/Merchant.h index 6c700c7ff..e2c6b34ac 100644 --- a/Minecraft.World/Containers/Merchant.h +++ b/Minecraft.World/Containers/Merchant.h @@ -4,15 +4,15 @@ class MerchantRecipeList; class MerchantRecipe; class Player; -class Merchant -{ +class Merchant { public: - virtual ~Merchant(){} - virtual void setTradingPlayer(std::shared_ptr player) = 0; - virtual std::shared_ptr getTradingPlayer() = 0; - virtual MerchantRecipeList *getOffers(std::shared_ptr forPlayer) = 0; - virtual void overrideOffers(MerchantRecipeList *recipeList) = 0; - virtual void notifyTrade(MerchantRecipe *activeRecipe) = 0; - virtual void notifyTradeUpdated(std::shared_ptr item) = 0; - virtual int getDisplayName() = 0; + virtual ~Merchant() {} + virtual void setTradingPlayer(std::shared_ptr player) = 0; + virtual std::shared_ptr getTradingPlayer() = 0; + virtual MerchantRecipeList* getOffers( + std::shared_ptr forPlayer) = 0; + virtual void overrideOffers(MerchantRecipeList* recipeList) = 0; + virtual void notifyTrade(MerchantRecipe* activeRecipe) = 0; + virtual void notifyTradeUpdated(std::shared_ptr item) = 0; + virtual int getDisplayName() = 0; }; diff --git a/Minecraft.World/Containers/MerchantContainer.cpp b/Minecraft.World/Containers/MerchantContainer.cpp index dafc81d54..5f12e4cd8 100644 --- a/Minecraft.World/Containers/MerchantContainer.cpp +++ b/Minecraft.World/Containers/MerchantContainer.cpp @@ -3,181 +3,139 @@ #include "MerchantMenu.h" #include "MerchantContainer.h" -MerchantContainer::MerchantContainer(std::shared_ptr player, std::shared_ptr villager) -{ - this->player = player; - merchant = villager; - items = ItemInstanceArray(3); - items[0] = nullptr; - items[1] = nullptr; - items[2] = nullptr; - activeRecipe = NULL; - selectionHint = 0; +MerchantContainer::MerchantContainer(std::shared_ptr player, + std::shared_ptr villager) { + this->player = player; + merchant = villager; + items = ItemInstanceArray(3); + items[0] = nullptr; + items[1] = nullptr; + items[2] = nullptr; + activeRecipe = NULL; + selectionHint = 0; } -MerchantContainer::~MerchantContainer() -{ - delete [] items.data; +MerchantContainer::~MerchantContainer() { delete[] items.data; } + +unsigned int MerchantContainer::getContainerSize() { return items.length; } + +std::shared_ptr MerchantContainer::getItem(unsigned int slot) { + return items[slot]; } -unsigned int MerchantContainer::getContainerSize() -{ - return items.length; +std::shared_ptr MerchantContainer::removeItem(unsigned int slot, + int count) { + if (items[slot] != NULL) { + if (slot == MerchantMenu::RESULT_SLOT) { + std::shared_ptr item = items[slot]; + items[slot] = nullptr; + return item; + } + if (items[slot]->count <= count) { + std::shared_ptr item = items[slot]; + items[slot] = nullptr; + if (isPaymentSlot(slot)) { + updateSellItem(); + } + return item; + } else { + std::shared_ptr i = items[slot]->remove(count); + if (items[slot]->count == 0) items[slot] = nullptr; + if (isPaymentSlot(slot)) { + updateSellItem(); + } + return i; + } + } + return nullptr; } -std::shared_ptr MerchantContainer::getItem(unsigned int slot) -{ - return items[slot]; +bool MerchantContainer::isPaymentSlot(int slot) { + return slot == MerchantMenu::PAYMENT1_SLOT || + slot == MerchantMenu::PAYMENT2_SLOT; } -std::shared_ptr MerchantContainer::removeItem(unsigned int slot, int count) -{ - if (items[slot] != NULL) - { - if (slot == MerchantMenu::RESULT_SLOT) - { - std::shared_ptr item = items[slot]; - items[slot] = nullptr; - return item; - } - if (items[slot]->count <= count) - { - std::shared_ptr item = items[slot]; - items[slot] = nullptr; - if (isPaymentSlot(slot)) - { - updateSellItem(); - } - return item; - } - else - { - std::shared_ptr i = items[slot]->remove(count); - if (items[slot]->count == 0) items[slot] = nullptr; - if (isPaymentSlot(slot)) - { - updateSellItem(); - } - return i; - } - } - return nullptr; +std::shared_ptr MerchantContainer::removeItemNoUpdate(int slot) { + if (items[slot] != NULL) { + std::shared_ptr item = items[slot]; + items[slot] = nullptr; + return item; + } + return nullptr; } -bool MerchantContainer::isPaymentSlot(int slot) -{ - return slot == MerchantMenu::PAYMENT1_SLOT || slot == MerchantMenu::PAYMENT2_SLOT; +void MerchantContainer::setItem(unsigned int slot, + std::shared_ptr item) { + items[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); + if (isPaymentSlot(slot)) { + updateSellItem(); + } } -std::shared_ptr MerchantContainer::removeItemNoUpdate(int slot) -{ - if (items[slot] != NULL) - { - std::shared_ptr item = items[slot]; - items[slot] = nullptr; - return item; - } - return nullptr; +int MerchantContainer::getName() { return merchant->getDisplayName(); } + +int MerchantContainer::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -void MerchantContainer::setItem(unsigned int slot, std::shared_ptr item) -{ - items[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); - if (isPaymentSlot(slot)) - { - updateSellItem(); - } +bool MerchantContainer::stillValid(std::shared_ptr player) { + return merchant->getTradingPlayer() == player; } -int MerchantContainer::getName() -{ - return merchant->getDisplayName(); +void MerchantContainer::startOpen() {} + +void MerchantContainer::stopOpen() {} + +void MerchantContainer::setChanged() { updateSellItem(); } + +void MerchantContainer::updateSellItem() { + activeRecipe = NULL; + + std::shared_ptr buyItem1 = items[MerchantMenu::PAYMENT1_SLOT]; + std::shared_ptr buyItem2 = items[MerchantMenu::PAYMENT2_SLOT]; + + if (buyItem1 == NULL) { + buyItem1 = buyItem2; + buyItem2 = nullptr; + } + + if (buyItem1 == NULL) { + setItem(MerchantMenu::RESULT_SLOT, nullptr); + } else { + MerchantRecipeList* offers = merchant->getOffers(player); + if (offers != NULL) { + MerchantRecipe* recipeFor = + offers->getRecipeFor(buyItem1, buyItem2, selectionHint); + if (recipeFor != NULL && !recipeFor->isDeprecated()) { + activeRecipe = recipeFor; + setItem(MerchantMenu::RESULT_SLOT, + recipeFor->getSellItem()->copy()); + } else if (buyItem2 != NULL) { + // try to switch + recipeFor = + offers->getRecipeFor(buyItem2, buyItem1, selectionHint); + if (recipeFor != NULL && !recipeFor->isDeprecated()) { + activeRecipe = recipeFor; + setItem(MerchantMenu::RESULT_SLOT, + recipeFor->getSellItem()->copy()); + } else { + setItem(MerchantMenu::RESULT_SLOT, nullptr); + } + + } else { + setItem(MerchantMenu::RESULT_SLOT, nullptr); + } + } + } + + merchant->notifyTradeUpdated(getItem(MerchantMenu::RESULT_SLOT)); } -int MerchantContainer::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; -} +MerchantRecipe* MerchantContainer::getActiveRecipe() { return activeRecipe; } -bool MerchantContainer::stillValid(std::shared_ptr player) -{ - return merchant->getTradingPlayer() == player; -} - -void MerchantContainer::startOpen() -{ -} - -void MerchantContainer::stopOpen() -{ -} - -void MerchantContainer::setChanged() -{ - updateSellItem(); -} - -void MerchantContainer::updateSellItem() -{ - activeRecipe = NULL; - - std::shared_ptr buyItem1 = items[MerchantMenu::PAYMENT1_SLOT]; - std::shared_ptr buyItem2 = items[MerchantMenu::PAYMENT2_SLOT]; - - if (buyItem1 == NULL) - { - buyItem1 = buyItem2; - buyItem2 = nullptr; - } - - if (buyItem1 == NULL) - { - setItem(MerchantMenu::RESULT_SLOT, nullptr); - } - else - { - MerchantRecipeList *offers = merchant->getOffers(player); - if (offers != NULL) - { - MerchantRecipe *recipeFor = offers->getRecipeFor(buyItem1, buyItem2, selectionHint); - if (recipeFor != NULL && !recipeFor->isDeprecated()) - { - activeRecipe = recipeFor; - setItem(MerchantMenu::RESULT_SLOT, recipeFor->getSellItem()->copy()); - } - else if (buyItem2 != NULL) - { - // try to switch - recipeFor = offers->getRecipeFor(buyItem2, buyItem1, selectionHint); - if (recipeFor != NULL && !recipeFor->isDeprecated()) - { - activeRecipe = recipeFor; - setItem(MerchantMenu::RESULT_SLOT, recipeFor->getSellItem()->copy()); - } - else - { - setItem(MerchantMenu::RESULT_SLOT, nullptr); - } - - } - else - { - setItem(MerchantMenu::RESULT_SLOT, nullptr); - } - } - } - - merchant->notifyTradeUpdated(getItem(MerchantMenu::RESULT_SLOT)); -} - -MerchantRecipe *MerchantContainer::getActiveRecipe() -{ - return activeRecipe; -} - -void MerchantContainer::setSelectionHint(int selectionHint) -{ - this->selectionHint = selectionHint; - updateSellItem(); +void MerchantContainer::setSelectionHint(int selectionHint) { + this->selectionHint = selectionHint; + updateSellItem(); } \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantContainer.h b/Minecraft.World/Containers/MerchantContainer.h index 9fa80f3df..173490f83 100644 --- a/Minecraft.World/Containers/MerchantContainer.h +++ b/Minecraft.World/Containers/MerchantContainer.h @@ -7,36 +7,36 @@ class Merchant; class Player; class MerchantRecipe; -class MerchantContainer : public Container -{ +class MerchantContainer : public Container { private: - std::shared_ptr merchant; - ItemInstanceArray items; - std::shared_ptr player; - MerchantRecipe *activeRecipe; - int selectionHint; + std::shared_ptr merchant; + ItemInstanceArray items; + std::shared_ptr player; + MerchantRecipe* activeRecipe; + int selectionHint; public: - MerchantContainer(std::shared_ptr player, std::shared_ptr villager); - ~MerchantContainer(); + MerchantContainer(std::shared_ptr player, + std::shared_ptr villager); + ~MerchantContainer(); - unsigned int getContainerSize(); - std::shared_ptr getItem(unsigned int slot); - std::shared_ptr removeItem(unsigned int slot, int count); + unsigned int getContainerSize(); + std::shared_ptr getItem(unsigned int slot); + std::shared_ptr removeItem(unsigned int slot, int count); private: - bool isPaymentSlot(int slot); + bool isPaymentSlot(int slot); public: - std::shared_ptr removeItemNoUpdate(int slot); - void setItem(unsigned int slot, std::shared_ptr item); - int getName(); - int getMaxStackSize(); - bool stillValid(std::shared_ptr player); - void startOpen(); - void stopOpen(); - void setChanged(); - void updateSellItem(); - MerchantRecipe *getActiveRecipe(); - void setSelectionHint(int selectionHint); + std::shared_ptr removeItemNoUpdate(int slot); + void setItem(unsigned int slot, std::shared_ptr item); + int getName(); + int getMaxStackSize(); + bool stillValid(std::shared_ptr player); + void startOpen(); + void stopOpen(); + void setChanged(); + void updateSellItem(); + MerchantRecipe* getActiveRecipe(); + void setSelectionHint(int selectionHint); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantMenu.cpp b/Minecraft.World/Containers/MerchantMenu.cpp index 470a7d565..34a95d5ef 100644 --- a/Minecraft.World/Containers/MerchantMenu.cpp +++ b/Minecraft.World/Containers/MerchantMenu.cpp @@ -5,146 +5,122 @@ #include "../Headers/net.minecraft.world.level.h" #include "MerchantMenu.h" -MerchantMenu::MerchantMenu(std::shared_ptr inventory, std::shared_ptr merchant, Level *level) -{ - trader = merchant; - this->level = level; +MerchantMenu::MerchantMenu(std::shared_ptr inventory, + std::shared_ptr merchant, Level* level) { + trader = merchant; + this->level = level; - tradeContainer = std::shared_ptr( new MerchantContainer(std::dynamic_pointer_cast(inventory->player->shared_from_this()), merchant) ); - addSlot(new Slot(tradeContainer, PAYMENT1_SLOT, SELLSLOT1_X, ROW2_Y)); - addSlot(new Slot(tradeContainer, PAYMENT2_SLOT, SELLSLOT2_X, ROW2_Y)); - addSlot(new MerchantResultSlot(inventory->player, merchant, tradeContainer, RESULT_SLOT, BUYSLOT_X, ROW2_Y)); + tradeContainer = std::shared_ptr( + new MerchantContainer(std::dynamic_pointer_cast( + inventory->player->shared_from_this()), + merchant)); + addSlot(new Slot(tradeContainer, PAYMENT1_SLOT, SELLSLOT1_X, ROW2_Y)); + addSlot(new Slot(tradeContainer, PAYMENT2_SLOT, SELLSLOT2_X, ROW2_Y)); + addSlot(new MerchantResultSlot(inventory->player, merchant, tradeContainer, + RESULT_SLOT, BUYSLOT_X, ROW2_Y)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } } -std::shared_ptr MerchantMenu::getTradeContainer() -{ - return tradeContainer; +std::shared_ptr MerchantMenu::getTradeContainer() { + return tradeContainer; } -void MerchantMenu::addSlotListener(ContainerListener *listener) -{ - AbstractContainerMenu::addSlotListener(listener); +void MerchantMenu::addSlotListener(ContainerListener* listener) { + AbstractContainerMenu::addSlotListener(listener); } -void MerchantMenu::broadcastChanges() -{ - AbstractContainerMenu::broadcastChanges(); +void MerchantMenu::broadcastChanges() { + AbstractContainerMenu::broadcastChanges(); } -// 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things -void MerchantMenu::slotsChanged() -{ - tradeContainer->updateSellItem(); - AbstractContainerMenu::slotsChanged(); +// 4J used to take a std::shared_ptr but wasn't using it, so removed +// to simplify things +void MerchantMenu::slotsChanged() { + tradeContainer->updateSellItem(); + AbstractContainerMenu::slotsChanged(); } -void MerchantMenu::setSelectionHint(int hint) -{ - tradeContainer->setSelectionHint(hint); +void MerchantMenu::setSelectionHint(int hint) { + tradeContainer->setSelectionHint(hint); } -void MerchantMenu::setData(int id, int value) -{ +void MerchantMenu::setData(int id, int value) {} + +bool MerchantMenu::stillValid(std::shared_ptr player) { + return trader->getTradingPlayer() == player; } -bool MerchantMenu::stillValid(std::shared_ptr player) -{ - return trader->getTradingPlayer() == player; +std::shared_ptr MerchantMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = NULL; + + if (slotIndex < slots->size()) slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); + + if (slotIndex == RESULT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); + } else if (slotIndex == PAYMENT1_SLOT || slotIndex == PAYMENT2_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) { + if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (slotIndex >= USE_ROW_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } -std::shared_ptr MerchantMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = NULL; - - if(slotIndex < slots->size()) slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); +void MerchantMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + trader->setTradingPlayer(nullptr); - if (slotIndex == RESULT_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); - } - else if (slotIndex == PAYMENT1_SLOT || slotIndex == PAYMENT2_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= INV_SLOT_START && slotIndex < INV_SLOT_END) - { - if (!moveItemStackTo(stack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= USE_ROW_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - if (!moveItemStackTo(stack, INV_SLOT_START, INV_SLOT_END, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + AbstractContainerMenu::removed(player); + if (level->isClientSide) return; + + std::shared_ptr item = + tradeContainer->removeItemNoUpdate(PAYMENT1_SLOT); + if (item) { + player->drop(item); + } + item = tradeContainer->removeItemNoUpdate(PAYMENT2_SLOT); + if (item != NULL) { + player->drop(item); + } } -void MerchantMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - trader->setTradingPlayer(nullptr); - - AbstractContainerMenu::removed(player); - if (level->isClientSide) return; - - std::shared_ptr item = tradeContainer->removeItemNoUpdate(PAYMENT1_SLOT); - if (item) - { - player->drop(item); - } - item = tradeContainer->removeItemNoUpdate(PAYMENT2_SLOT); - if (item != NULL) - { - player->drop(item); - } -} - -std::shared_ptr MerchantMenu::getMerchant() -{ - return trader; -} \ No newline at end of file +std::shared_ptr MerchantMenu::getMerchant() { return trader; } \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantMenu.h b/Minecraft.World/Containers/MerchantMenu.h index 23b639986..a98539c0b 100644 --- a/Minecraft.World/Containers/MerchantMenu.h +++ b/Minecraft.World/Containers/MerchantMenu.h @@ -4,43 +4,44 @@ class MerchantContainer; -class MerchantMenu : public AbstractContainerMenu -{ +class MerchantMenu : public AbstractContainerMenu { public: - static const int PAYMENT1_SLOT = 0; - static const int PAYMENT2_SLOT = 1; - static const int RESULT_SLOT = 2; + static const int PAYMENT1_SLOT = 0; + static const int PAYMENT2_SLOT = 1; + static const int RESULT_SLOT = 2; - static const int INV_SLOT_START = RESULT_SLOT + 1; - static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = INV_SLOT_END; - static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; + static const int INV_SLOT_START = RESULT_SLOT + 1; + static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = INV_SLOT_END; + static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; - static const int SELLSLOT1_X = 36; - static const int SELLSLOT2_X = SELLSLOT1_X + 26; - static const int BUYSLOT_X = 120; - - static const int ROW1_Y = 24; - static const int ROW2_Y = 53; + static const int SELLSLOT1_X = 36; + static const int SELLSLOT2_X = SELLSLOT1_X + 26; + static const int BUYSLOT_X = 120; + static const int ROW1_Y = 24; + static const int ROW2_Y = 53; private: - std::shared_ptr trader; - std::shared_ptr tradeContainer; - Level *level; + std::shared_ptr trader; + std::shared_ptr tradeContainer; + Level* level; public: - MerchantMenu(std::shared_ptr inventory, std::shared_ptr merchant, Level *level); + MerchantMenu(std::shared_ptr inventory, + std::shared_ptr merchant, Level* level); - std::shared_ptr getTradeContainer(); - void addSlotListener(ContainerListener *listener); - void broadcastChanges(); - void slotsChanged(); // 4J used to take a std::shared_ptr but wasn't using it, so removed to simplify things - void setSelectionHint(int hint); - void setData(int id, int value); - bool stillValid(std::shared_ptr player); - std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); - void removed(std::shared_ptr player); + std::shared_ptr getTradeContainer(); + void addSlotListener(ContainerListener* listener); + void broadcastChanges(); + void slotsChanged(); // 4J used to take a std::shared_ptr but + // wasn't using it, so removed to simplify things + void setSelectionHint(int hint); + void setData(int id, int value); + bool stillValid(std::shared_ptr player); + std::shared_ptr quickMoveStack(std::shared_ptr player, + int slotIndex); + void removed(std::shared_ptr player); - std::shared_ptr getMerchant(); // 4J Added + std::shared_ptr getMerchant(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantRecipe.cpp b/Minecraft.World/Containers/MerchantRecipe.cpp index 7e326e32a..aaa29e7a9 100644 --- a/Minecraft.World/Containers/MerchantRecipe.cpp +++ b/Minecraft.World/Containers/MerchantRecipe.cpp @@ -2,145 +2,107 @@ #include "MerchantRecipe.h" -void MerchantRecipe::_init(std::shared_ptr buyA, std::shared_ptr buyB, std::shared_ptr sell) -{ - this->buyA = buyA; - this->buyB = buyB; - this->sell = sell; - uses = 0; - maxUses = 7; +void MerchantRecipe::_init(std::shared_ptr buyA, + std::shared_ptr buyB, + std::shared_ptr sell) { + this->buyA = buyA; + this->buyB = buyB; + this->sell = sell; + uses = 0; + maxUses = 7; } -MerchantRecipe::MerchantRecipe(CompoundTag *tag) -{ - buyA = nullptr; - buyB = nullptr; - sell = nullptr; - uses = 0; - load(tag); +MerchantRecipe::MerchantRecipe(CompoundTag* tag) { + buyA = nullptr; + buyB = nullptr; + sell = nullptr; + uses = 0; + load(tag); } -MerchantRecipe::MerchantRecipe(std::shared_ptr buyA, std::shared_ptr buyB, std::shared_ptr sell, int uses, int maxUses) -{ - _init(buyA, buyB, sell); - this->uses = uses; - this->maxUses = maxUses; +MerchantRecipe::MerchantRecipe(std::shared_ptr buyA, + std::shared_ptr buyB, + std::shared_ptr sell, int uses, + int maxUses) { + _init(buyA, buyB, sell); + this->uses = uses; + this->maxUses = maxUses; } -MerchantRecipe::MerchantRecipe(std::shared_ptr buy, std::shared_ptr sell) -{ - _init(buy, nullptr, sell); +MerchantRecipe::MerchantRecipe(std::shared_ptr buy, + std::shared_ptr sell) { + _init(buy, nullptr, sell); } -MerchantRecipe::MerchantRecipe(std::shared_ptr buy, Item *sell) -{ - _init(buy, nullptr, std::shared_ptr(new ItemInstance(sell))); +MerchantRecipe::MerchantRecipe(std::shared_ptr buy, Item* sell) { + _init(buy, nullptr, std::shared_ptr(new ItemInstance(sell))); } -MerchantRecipe::MerchantRecipe(std::shared_ptr buy, Tile *sell) -{ - _init(buy, nullptr, std::shared_ptr(new ItemInstance(sell))); +MerchantRecipe::MerchantRecipe(std::shared_ptr buy, Tile* sell) { + _init(buy, nullptr, std::shared_ptr(new ItemInstance(sell))); } -std::shared_ptr MerchantRecipe::getBuyAItem() -{ - return buyA; +std::shared_ptr MerchantRecipe::getBuyAItem() { return buyA; } + +std::shared_ptr MerchantRecipe::getBuyBItem() { return buyB; } + +bool MerchantRecipe::hasSecondaryBuyItem() { return buyB != NULL; } + +std::shared_ptr MerchantRecipe::getSellItem() { return sell; } + +bool MerchantRecipe::isSame(MerchantRecipe* other) { + if (buyA->id != other->buyA->id || sell->id != other->sell->id) { + return false; + } + return (buyB == NULL && other->buyB == NULL) || + (buyB != NULL && other->buyB != NULL && buyB->id == other->buyB->id); } -std::shared_ptr MerchantRecipe::getBuyBItem() -{ - return buyB; +bool MerchantRecipe::isSameSameButBetter(MerchantRecipe* other) { + // same deal, but cheaper + return isSame(other) && + (buyA->count < other->buyA->count || + (buyB != NULL && buyB->count < other->buyB->count)); } -bool MerchantRecipe::hasSecondaryBuyItem() -{ - return buyB != NULL; +int MerchantRecipe::getUses() { return uses; } + +int MerchantRecipe::getMaxUses() { return maxUses; } + +void MerchantRecipe::increaseUses() { uses++; } + +void MerchantRecipe::increaseMaxUses(int amount) { maxUses += amount; } + +bool MerchantRecipe::isDeprecated() { return uses >= maxUses; } + +void MerchantRecipe::enforceDeprecated() { uses = maxUses; } + +void MerchantRecipe::load(CompoundTag* tag) { + CompoundTag* buyTag = tag->getCompound(L"buy"); + buyA = ItemInstance::fromTag(buyTag); + CompoundTag* sellTag = tag->getCompound(L"sell"); + sell = ItemInstance::fromTag(sellTag); + if (tag->contains(L"buyB")) { + buyB = ItemInstance::fromTag(tag->getCompound(L"buyB")); + } + if (tag->contains(L"uses")) { + uses = tag->getInt(L"uses"); + } + if (tag->contains(L"maxUses")) { + maxUses = tag->getInt(L"maxUses"); + } else { + maxUses = 7; + } } -std::shared_ptr MerchantRecipe::getSellItem() -{ - return sell; -} - -bool MerchantRecipe::isSame(MerchantRecipe *other) -{ - if (buyA->id != other->buyA->id || sell->id != other->sell->id) - { - return false; - } - return (buyB == NULL && other->buyB == NULL) || (buyB != NULL && other->buyB != NULL && buyB->id == other->buyB->id); -} - -bool MerchantRecipe::isSameSameButBetter(MerchantRecipe *other) -{ - // same deal, but cheaper - return isSame(other) && (buyA->count < other->buyA->count || (buyB != NULL && buyB->count < other->buyB->count)); -} - -int MerchantRecipe::getUses() -{ - return uses; -} - -int MerchantRecipe::getMaxUses() -{ - return maxUses; -} - -void MerchantRecipe::increaseUses() -{ - uses++; -} - -void MerchantRecipe::increaseMaxUses(int amount) -{ - maxUses += amount; -} - -bool MerchantRecipe::isDeprecated() -{ - return uses >= maxUses; -} - -void MerchantRecipe::enforceDeprecated() -{ - uses = maxUses; -} - -void MerchantRecipe::load(CompoundTag *tag) -{ - CompoundTag *buyTag = tag->getCompound(L"buy"); - buyA = ItemInstance::fromTag(buyTag); - CompoundTag *sellTag = tag->getCompound(L"sell"); - sell = ItemInstance::fromTag(sellTag); - if (tag->contains(L"buyB")) - { - buyB = ItemInstance::fromTag(tag->getCompound(L"buyB")); - } - if (tag->contains(L"uses")) - { - uses = tag->getInt(L"uses"); - } - if (tag->contains(L"maxUses")) - { - maxUses = tag->getInt(L"maxUses"); - } - else - { - maxUses = 7; - } -} - -CompoundTag *MerchantRecipe::createTag() -{ - CompoundTag *tag = new CompoundTag(); - tag->putCompound(L"buy", buyA->save(new CompoundTag(L"buy"))); - tag->putCompound(L"sell", sell->save(new CompoundTag(L"sell"))); - if (buyB != NULL) - { - tag->putCompound(L"buyB", buyB->save(new CompoundTag(L"buyB"))); - } - tag->putInt(L"uses", uses); - tag->putInt(L"maxUses", maxUses); - return tag; +CompoundTag* MerchantRecipe::createTag() { + CompoundTag* tag = new CompoundTag(); + tag->putCompound(L"buy", buyA->save(new CompoundTag(L"buy"))); + tag->putCompound(L"sell", sell->save(new CompoundTag(L"sell"))); + if (buyB != NULL) { + tag->putCompound(L"buyB", buyB->save(new CompoundTag(L"buyB"))); + } + tag->putInt(L"uses", uses); + tag->putInt(L"maxUses", maxUses); + return tag; } \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantRecipe.h b/Minecraft.World/Containers/MerchantRecipe.h index dd684b6a4..b9bc3d7eb 100644 --- a/Minecraft.World/Containers/MerchantRecipe.h +++ b/Minecraft.World/Containers/MerchantRecipe.h @@ -1,35 +1,40 @@ #pragma once -class MerchantRecipe -{ +class MerchantRecipe { private: - std::shared_ptr buyA; - std::shared_ptr buyB; - std::shared_ptr sell; - int uses; - int maxUses; + std::shared_ptr buyA; + std::shared_ptr buyB; + std::shared_ptr sell; + int uses; + int maxUses; - void _init(std::shared_ptr buyA, std::shared_ptr buyB, std::shared_ptr sell); + void _init(std::shared_ptr buyA, + std::shared_ptr buyB, + std::shared_ptr sell); public: - MerchantRecipe(CompoundTag *tag); - MerchantRecipe(std::shared_ptr buyA, std::shared_ptr buyB, std::shared_ptr sell, int uses = 0, int maxUses = 7); - MerchantRecipe(std::shared_ptr buy, std::shared_ptr sell); - MerchantRecipe(std::shared_ptr buy, Item *sell); - MerchantRecipe(std::shared_ptr buy, Tile *sell); + MerchantRecipe(CompoundTag* tag); + MerchantRecipe(std::shared_ptr buyA, + std::shared_ptr buyB, + std::shared_ptr sell, int uses = 0, + int maxUses = 7); + MerchantRecipe(std::shared_ptr buy, + std::shared_ptr sell); + MerchantRecipe(std::shared_ptr buy, Item* sell); + MerchantRecipe(std::shared_ptr buy, Tile* sell); - std::shared_ptr getBuyAItem(); - std::shared_ptr getBuyBItem(); - bool hasSecondaryBuyItem(); - std::shared_ptr getSellItem(); - bool isSame(MerchantRecipe *other); - bool isSameSameButBetter(MerchantRecipe *other); - int getUses(); - int getMaxUses(); - void increaseUses(); - void increaseMaxUses(int amount); - bool isDeprecated(); - void enforceDeprecated(); - void load(CompoundTag *tag); - CompoundTag *createTag(); + std::shared_ptr getBuyAItem(); + std::shared_ptr getBuyBItem(); + bool hasSecondaryBuyItem(); + std::shared_ptr getSellItem(); + bool isSame(MerchantRecipe* other); + bool isSameSameButBetter(MerchantRecipe* other); + int getUses(); + int getMaxUses(); + void increaseUses(); + void increaseMaxUses(int amount); + bool isDeprecated(); + void enforceDeprecated(); + void load(CompoundTag* tag); + CompoundTag* createTag(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantRecipeList.cpp b/Minecraft.World/Containers/MerchantRecipeList.cpp index f08225bbb..a30a3f818 100644 --- a/Minecraft.World/Containers/MerchantRecipeList.cpp +++ b/Minecraft.World/Containers/MerchantRecipeList.cpp @@ -2,194 +2,171 @@ #include "../Headers/net.minecraft.world.item.trading.h" #include "MerchantRecipeList.h" -MerchantRecipeList::MerchantRecipeList() -{ +MerchantRecipeList::MerchantRecipeList() {} + +MerchantRecipeList::MerchantRecipeList(CompoundTag* tag) { load(tag); } + +MerchantRecipeList::~MerchantRecipeList() { + for (AUTO_VAR(it, m_recipes.begin()); it != m_recipes.end(); ++it) { + delete (*it); + } } -MerchantRecipeList::MerchantRecipeList(CompoundTag *tag) -{ - load(tag); +MerchantRecipe* MerchantRecipeList::getRecipeFor( + std::shared_ptr buyA, std::shared_ptr buyB, + int selectionHint) { + if (selectionHint > 0 && selectionHint < m_recipes.size()) { + // attempt to match vs the hint + MerchantRecipe* r = m_recipes.at(selectionHint); + if (buyA->id == r->getBuyAItem()->id && + ((buyB == NULL && !r->hasSecondaryBuyItem()) || + (r->hasSecondaryBuyItem() && buyB != NULL && + r->getBuyBItem()->id == buyB->id))) { + if (buyA->count >= r->getBuyAItem()->count && + (!r->hasSecondaryBuyItem() || + buyB->count >= r->getBuyBItem()->count)) { + return r; + } + } + return NULL; + } + for (int i = 0; i < m_recipes.size(); i++) { + MerchantRecipe* r = m_recipes.at(i); + if (buyA->id == r->getBuyAItem()->id && + buyA->count >= r->getBuyAItem()->count && + ((!r->hasSecondaryBuyItem() && buyB == NULL) || + (r->hasSecondaryBuyItem() && buyB != NULL && + r->getBuyBItem()->id == buyB->id && + buyB->count >= r->getBuyBItem()->count))) { + return r; + } + } + return NULL; } -MerchantRecipeList::~MerchantRecipeList() -{ - for(AUTO_VAR(it, m_recipes.begin()); it != m_recipes.end(); ++it) - { - delete (*it); - } +bool MerchantRecipeList::addIfNewOrBetter(MerchantRecipe* recipe) { + bool added = false; + for (int i = 0; i < m_recipes.size(); i++) { + MerchantRecipe* r = m_recipes.at(i); + if (recipe->isSame(r)) { + if (recipe->isSameSameButBetter(r)) { + delete m_recipes[i]; + m_recipes[i] = recipe; + added = true; + } + return added; + } + } + m_recipes.push_back(recipe); + return true; } -MerchantRecipe *MerchantRecipeList::getRecipeFor(std::shared_ptr buyA, std::shared_ptr buyB, int selectionHint) -{ - if (selectionHint > 0 && selectionHint < m_recipes.size()) - { - // attempt to match vs the hint - MerchantRecipe *r = m_recipes.at(selectionHint); - if (buyA->id == r->getBuyAItem()->id && ((buyB == NULL && !r->hasSecondaryBuyItem()) || (r->hasSecondaryBuyItem() && buyB != NULL && r->getBuyBItem()->id == buyB->id))) - { - if (buyA->count >= r->getBuyAItem()->count && (!r->hasSecondaryBuyItem() || buyB->count >= r->getBuyBItem()->count)) - { - return r; - } - } - return NULL; - } - for (int i = 0; i < m_recipes.size(); i++) - { - MerchantRecipe *r = m_recipes.at(i); - if (buyA->id == r->getBuyAItem()->id && buyA->count >= r->getBuyAItem()->count - && ((!r->hasSecondaryBuyItem() && buyB == NULL) || (r->hasSecondaryBuyItem() && buyB != NULL && r->getBuyBItem()->id == buyB->id && buyB->count >= r->getBuyBItem()->count))) - { - return r; - } - } - return NULL; +MerchantRecipe* MerchantRecipeList::getMatchingRecipeFor( + std::shared_ptr buy, std::shared_ptr buyB, + std::shared_ptr sell) { + for (int i = 0; i < m_recipes.size(); i++) { + MerchantRecipe* r = m_recipes.at(i); + if (buy->id == r->getBuyAItem()->id && + buy->count >= r->getBuyAItem()->count && + sell->id == r->getSellItem()->id) { + if (!r->hasSecondaryBuyItem() || + (buyB != NULL && buyB->id == r->getBuyBItem()->id && + buyB->count >= r->getBuyBItem()->count)) { + return r; + } + } + } + return NULL; } -bool MerchantRecipeList::addIfNewOrBetter(MerchantRecipe *recipe) -{ - bool added = false; - for (int i = 0; i < m_recipes.size(); i++) - { - MerchantRecipe *r = m_recipes.at(i); - if (recipe->isSame(r)) - { - if (recipe->isSameSameButBetter(r)) - { - delete m_recipes[i]; - m_recipes[i] = recipe; - added = true; - } - return added; - } - } - m_recipes.push_back(recipe); - return true; +void MerchantRecipeList::writeToStream(DataOutputStream* stream) { + stream->writeByte((uint8_t)(m_recipes.size() & 0xff)); + for (int i = 0; i < m_recipes.size(); i++) { + MerchantRecipe* r = m_recipes.at(i); + Packet::writeItem(r->getBuyAItem(), stream); + Packet::writeItem(r->getSellItem(), stream); + + std::shared_ptr buyBItem = r->getBuyBItem(); + stream->writeBoolean(buyBItem != NULL); + if (buyBItem != NULL) { + Packet::writeItem(buyBItem, stream); + } + stream->writeBoolean(r->isDeprecated()); + stream->writeInt(r->getUses()); + stream->writeInt(r->getMaxUses()); + } } -MerchantRecipe *MerchantRecipeList::getMatchingRecipeFor(std::shared_ptr buy, std::shared_ptr buyB, std::shared_ptr sell) -{ - for (int i = 0; i < m_recipes.size(); i++) - { - MerchantRecipe *r = m_recipes.at(i); - if (buy->id == r->getBuyAItem()->id && buy->count >= r->getBuyAItem()->count && sell->id == r->getSellItem()->id) - { - if (!r->hasSecondaryBuyItem() || (buyB != NULL && buyB->id == r->getBuyBItem()->id && buyB->count >= r->getBuyBItem()->count)) - { - return r; - } - } - } - return NULL; +MerchantRecipeList* MerchantRecipeList::createFromStream( + DataInputStream* stream) { + MerchantRecipeList* list = new MerchantRecipeList(); + + int count = (int)(stream->readByte() & 0xff); + for (int i = 0; i < count; i++) { + std::shared_ptr buy = Packet::readItem(stream); + std::shared_ptr sell = Packet::readItem(stream); + + std::shared_ptr buyB = nullptr; + if (stream->readBoolean()) { + buyB = Packet::readItem(stream); + } + bool isDeprecated = stream->readBoolean(); + int uses = stream->readInt(); + int maxUses = stream->readInt(); + + MerchantRecipe* recipe = + new MerchantRecipe(buy, buyB, sell, uses, maxUses); + if (isDeprecated) { + recipe->enforceDeprecated(); + } + list->push_back(recipe); + } + return list; } -void MerchantRecipeList::writeToStream(DataOutputStream *stream) -{ - stream->writeByte((uint8_t) (m_recipes.size() & 0xff)); - for (int i = 0; i < m_recipes.size(); i++) - { - MerchantRecipe *r = m_recipes.at(i); - Packet::writeItem(r->getBuyAItem(), stream); - Packet::writeItem(r->getSellItem(), stream); +void MerchantRecipeList::load(CompoundTag* tag) { + ListTag* list = tag->getList(L"Recipes"); - std::shared_ptr buyBItem = r->getBuyBItem(); - stream->writeBoolean(buyBItem != NULL); - if (buyBItem != NULL) - { - Packet::writeItem(buyBItem, stream); - } - stream->writeBoolean(r->isDeprecated()); - stream->writeInt(r->getUses()); - stream->writeInt(r->getMaxUses()); - } + for (int i = 0; i < list->size(); i++) { + CompoundTag* recipeTag = (CompoundTag*)list->get(i); + m_recipes.push_back(new MerchantRecipe(recipeTag)); + } } -MerchantRecipeList *MerchantRecipeList::createFromStream(DataInputStream *stream) -{ - MerchantRecipeList *list = new MerchantRecipeList(); +CompoundTag* MerchantRecipeList::createTag() { + CompoundTag* tag = new CompoundTag(); - int count = (int) (stream->readByte() & 0xff); - for (int i = 0; i < count; i++) - { - std::shared_ptr buy = Packet::readItem(stream); - std::shared_ptr sell = Packet::readItem(stream); + ListTag* list = new ListTag(L"Recipes"); + for (int i = 0; i < m_recipes.size(); i++) { + MerchantRecipe* merchantRecipe = m_recipes.at(i); + list->add(merchantRecipe->createTag()); + } + tag->put(L"Recipes", list); - std::shared_ptr buyB = nullptr; - if (stream->readBoolean()) - { - buyB = Packet::readItem(stream); - } - bool isDeprecated = stream->readBoolean(); - int uses = stream->readInt(); - int maxUses = stream->readInt(); - - MerchantRecipe *recipe = new MerchantRecipe(buy, buyB, sell, uses, maxUses); - if (isDeprecated) - { - recipe->enforceDeprecated(); - } - list->push_back(recipe); - } - return list; + return tag; } -void MerchantRecipeList::load(CompoundTag *tag) -{ - ListTag *list = tag->getList(L"Recipes"); - - for (int i = 0; i < list->size(); i++) - { - CompoundTag *recipeTag = (CompoundTag*) list->get(i); - m_recipes.push_back(new MerchantRecipe(recipeTag)); - } +void MerchantRecipeList::push_back(MerchantRecipe* recipe) { + m_recipes.push_back(recipe); } -CompoundTag *MerchantRecipeList::createTag() -{ - CompoundTag *tag = new CompoundTag(); - - ListTag *list = new ListTag(L"Recipes"); - for (int i = 0; i < m_recipes.size(); i++) - { - MerchantRecipe *merchantRecipe = m_recipes.at(i); - list->add(merchantRecipe->createTag()); - } - tag->put(L"Recipes", list); - - return tag; +MerchantRecipe* MerchantRecipeList::at(size_t index) { + return m_recipes.at(index); } -void MerchantRecipeList::push_back(MerchantRecipe *recipe) -{ - m_recipes.push_back(recipe); +std::vector::iterator MerchantRecipeList::begin() { + return m_recipes.begin(); } -MerchantRecipe *MerchantRecipeList::at(size_t index) -{ - return m_recipes.at(index); +std::vector::iterator MerchantRecipeList::end() { + return m_recipes.end(); } -std::vector::iterator MerchantRecipeList::begin() -{ - return m_recipes.begin(); +std::vector::iterator MerchantRecipeList::erase( + std::vector::iterator it) { + return m_recipes.erase(it); } -std::vector::iterator MerchantRecipeList::end() -{ - return m_recipes.end(); -} +size_t MerchantRecipeList::size() { return m_recipes.size(); } -std::vector::iterator MerchantRecipeList::erase(std::vector::iterator it) -{ - return m_recipes.erase(it); -} - -size_t MerchantRecipeList::size() -{ - return m_recipes.size(); -} - -bool MerchantRecipeList::empty() -{ - return m_recipes.empty(); -} +bool MerchantRecipeList::empty() { return m_recipes.empty(); } diff --git a/Minecraft.World/Containers/MerchantRecipeList.h b/Minecraft.World/Containers/MerchantRecipeList.h index b3c0cd2b2..8d000e32a 100644 --- a/Minecraft.World/Containers/MerchantRecipeList.h +++ b/Minecraft.World/Containers/MerchantRecipeList.h @@ -7,29 +7,33 @@ class ItemInstance; class DataOutputStream; class DataInputStream; -class MerchantRecipeList -{ +class MerchantRecipeList { private: - std::vector m_recipes; + std::vector m_recipes; public: - MerchantRecipeList(); - MerchantRecipeList(CompoundTag *tag); - ~MerchantRecipeList(); + MerchantRecipeList(); + MerchantRecipeList(CompoundTag* tag); + ~MerchantRecipeList(); - MerchantRecipe *getRecipeFor(std::shared_ptr buyA, std::shared_ptr buyB, int selectionHint); - bool addIfNewOrBetter(MerchantRecipe *recipe); // 4J Added bool return - MerchantRecipe *getMatchingRecipeFor(std::shared_ptr buy, std::shared_ptr buyB, std::shared_ptr sell); - void writeToStream(DataOutputStream *stream); - static MerchantRecipeList *createFromStream(DataInputStream *stream); - void load(CompoundTag *tag); - CompoundTag *createTag(); + MerchantRecipe* getRecipeFor(std::shared_ptr buyA, + std::shared_ptr buyB, + int selectionHint); + bool addIfNewOrBetter(MerchantRecipe* recipe); // 4J Added bool return + MerchantRecipe* getMatchingRecipeFor(std::shared_ptr buy, + std::shared_ptr buyB, + std::shared_ptr sell); + void writeToStream(DataOutputStream* stream); + static MerchantRecipeList* createFromStream(DataInputStream* stream); + void load(CompoundTag* tag); + CompoundTag* createTag(); - void push_back(MerchantRecipe *recipe); - MerchantRecipe *at(size_t index); - std::vector::iterator begin(); - std::vector::iterator end(); - std::vector::iterator erase(std::vector::iterator it); - size_t size(); - bool empty(); + void push_back(MerchantRecipe* recipe); + MerchantRecipe* at(size_t index); + std::vector::iterator begin(); + std::vector::iterator end(); + std::vector::iterator erase( + std::vector::iterator it); + size_t size(); + bool empty(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantResultSlot.cpp b/Minecraft.World/Containers/MerchantResultSlot.cpp index bd100bf2c..a778447e0 100644 --- a/Minecraft.World/Containers/MerchantResultSlot.cpp +++ b/Minecraft.World/Containers/MerchantResultSlot.cpp @@ -3,92 +3,90 @@ #include "../Headers/net.minecraft.world.item.trading.h" #include "MerchantResultSlot.h" -MerchantResultSlot::MerchantResultSlot(Player *player, std::shared_ptr merchant, std::shared_ptr slots, int id, int x, int y) : Slot(slots, id, x, y) -{ - this->player = player; - this->merchant = merchant; - this->slots = slots; - removeCount = 0; +MerchantResultSlot::MerchantResultSlot(Player* player, + std::shared_ptr merchant, + std::shared_ptr slots, + int id, int x, int y) + : Slot(slots, id, x, y) { + this->player = player; + this->merchant = merchant; + this->slots = slots; + removeCount = 0; } -bool MerchantResultSlot::mayPlace(std::shared_ptr item) -{ - return false; +bool MerchantResultSlot::mayPlace(std::shared_ptr item) { + return false; } -std::shared_ptr MerchantResultSlot::remove(int c) -{ - if (hasItem()) - { - removeCount += std::min(c, getItem()->count); - } - return Slot::remove(c); +std::shared_ptr MerchantResultSlot::remove(int c) { + if (hasItem()) { + removeCount += std::min(c, getItem()->count); + } + return Slot::remove(c); } -void MerchantResultSlot::onQuickCraft(std::shared_ptr picked, int count) -{ - removeCount += count; - checkTakeAchievements(picked); +void MerchantResultSlot::onQuickCraft(std::shared_ptr picked, + int count) { + removeCount += count; + checkTakeAchievements(picked); } -void MerchantResultSlot::checkTakeAchievements(std::shared_ptr carried) -{ - carried->onCraftedBy(player->level, std::dynamic_pointer_cast(player->shared_from_this()), removeCount); - removeCount = 0; +void MerchantResultSlot::checkTakeAchievements( + std::shared_ptr carried) { + carried->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + removeCount); + removeCount = 0; } -void MerchantResultSlot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - checkTakeAchievements(carried); +void MerchantResultSlot::onTake(std::shared_ptr player, + std::shared_ptr carried) { + checkTakeAchievements(carried); - MerchantRecipe *activeRecipe = slots->getActiveRecipe(); - if (activeRecipe != NULL) - { - std::shared_ptr item1 = slots->getItem(MerchantMenu::PAYMENT1_SLOT); - std::shared_ptr item2 = slots->getItem(MerchantMenu::PAYMENT2_SLOT); + MerchantRecipe* activeRecipe = slots->getActiveRecipe(); + if (activeRecipe != NULL) { + std::shared_ptr item1 = + slots->getItem(MerchantMenu::PAYMENT1_SLOT); + std::shared_ptr item2 = + slots->getItem(MerchantMenu::PAYMENT2_SLOT); - // remove payment items, but remember slots may have switched - if (removePaymentItemsIfMatching(activeRecipe, item1, item2) || removePaymentItemsIfMatching(activeRecipe, item2, item1)) - { - merchant->notifyTrade(activeRecipe); + // remove payment items, but remember slots may have switched + if (removePaymentItemsIfMatching(activeRecipe, item1, item2) || + removePaymentItemsIfMatching(activeRecipe, item2, item1)) { + merchant->notifyTrade(activeRecipe); - if (item1 && item1->count <= 0) - { - item1 = nullptr; - } - if (item2 && item2->count <= 0) - { - item2 = nullptr; - } - slots->setItem(MerchantMenu::PAYMENT1_SLOT, item1); - slots->setItem(MerchantMenu::PAYMENT2_SLOT, item2); - } - } + if (item1 && item1->count <= 0) { + item1 = nullptr; + } + if (item2 && item2->count <= 0) { + item2 = nullptr; + } + slots->setItem(MerchantMenu::PAYMENT1_SLOT, item1); + slots->setItem(MerchantMenu::PAYMENT2_SLOT, item2); + } + } } -bool MerchantResultSlot::mayCombine(std::shared_ptr second) -{ - return false; +bool MerchantResultSlot::mayCombine(std::shared_ptr second) { + return false; } -bool MerchantResultSlot::removePaymentItemsIfMatching(MerchantRecipe *activeRecipe, std::shared_ptr a, std::shared_ptr b) -{ - std::shared_ptr buyA = activeRecipe->getBuyAItem(); - std::shared_ptr buyB = activeRecipe->getBuyBItem(); +bool MerchantResultSlot::removePaymentItemsIfMatching( + MerchantRecipe* activeRecipe, std::shared_ptr a, + std::shared_ptr b) { + std::shared_ptr buyA = activeRecipe->getBuyAItem(); + std::shared_ptr buyB = activeRecipe->getBuyBItem(); - if (a != NULL && a->id == buyA->id) - { - if (buyB != NULL && b != NULL && buyB->id == b->id) - { - a->count -= buyA->count; - b->count -= buyB->count; - return true; - } - else if (buyB == NULL && b == NULL) - { - a->count -= buyA->count; - return true; - } - } - return false; + if (a != NULL && a->id == buyA->id) { + if (buyB != NULL && b != NULL && buyB->id == b->id) { + a->count -= buyA->count; + b->count -= buyB->count; + return true; + } else if (buyB == NULL && b == NULL) { + a->count -= buyA->count; + return true; + } + } + return false; } \ No newline at end of file diff --git a/Minecraft.World/Containers/MerchantResultSlot.h b/Minecraft.World/Containers/MerchantResultSlot.h index 1b45082cb..41c0bd387 100644 --- a/Minecraft.World/Containers/MerchantResultSlot.h +++ b/Minecraft.World/Containers/MerchantResultSlot.h @@ -6,28 +6,32 @@ class MerchantContainer; class Player; class Merchant; -class MerchantResultSlot : public Slot -{ +class MerchantResultSlot : public Slot { private: - std::shared_ptr slots; - Player *player; - int removeCount; - std::shared_ptr merchant; + std::shared_ptr slots; + Player* player; + int removeCount; + std::shared_ptr merchant; public: - MerchantResultSlot(Player *player, std::shared_ptr merchant, std::shared_ptr slots, int id, int x, int y); + MerchantResultSlot(Player* player, std::shared_ptr merchant, + std::shared_ptr slots, int id, int x, + int y); - bool mayPlace(std::shared_ptr item); - std::shared_ptr remove(int c); + bool mayPlace(std::shared_ptr item); + std::shared_ptr remove(int c); protected: - void onQuickCraft(std::shared_ptr picked, int count); - void checkTakeAchievements(std::shared_ptr carried); + void onQuickCraft(std::shared_ptr picked, int count); + void checkTakeAchievements(std::shared_ptr carried); public: - void onTake(std::shared_ptr player, std::shared_ptr carried); - virtual bool mayCombine(std::shared_ptr item); // 4J Added + void onTake(std::shared_ptr player, + std::shared_ptr carried); + virtual bool mayCombine(std::shared_ptr item); // 4J Added private: - bool removePaymentItemsIfMatching(MerchantRecipe *activeRecipe, std::shared_ptr a, std::shared_ptr b); + bool removePaymentItemsIfMatching(MerchantRecipe* activeRecipe, + std::shared_ptr a, + std::shared_ptr b); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/MouseInventoryClickHandler.h b/Minecraft.World/Containers/MouseInventoryClickHandler.h index ab4516877..a9144ba3f 100644 --- a/Minecraft.World/Containers/MouseInventoryClickHandler.h +++ b/Minecraft.World/Containers/MouseInventoryClickHandler.h @@ -1,84 +1,86 @@ #pragma once -// 4J The body of this class was commented out in Java. Copying here for completeness +// 4J The body of this class was commented out in Java. Copying here for +// completeness -class MouseInventoryClickHandler -{ -/* public static void handle(int buttonNum, boolean clickedOutside, int slotId, Player player) { - Inventory inventory = player.inventory; - Slot slot = player.getInventorySlot(slotId); - if (slot != null) { - ItemInstance clicked = slot.getItem(); - if (clicked == null && inventory.carried == null) { - } else if (clicked != null && inventory.carried == null) { - int c = buttonNum == 0 ? clicked.count : (clicked.count + 1) / 2; - inventory.carried = slot.container.removeItem(slot.slot, c); - if (clicked.count == 0) slot.set(null); - slot.onTake(); - } else if (clicked == null && inventory.carried != null && slot.mayPlace(inventory.carried)) { - int c = buttonNum == 0 ? inventory.carried.count : 1; - if (c > slot.getMaxStackSize()) c = slot.getMaxStackSize(); - slot.set(inventory.carried.remove(c)); - if (inventory.carried.count == 0) inventory.carried = null; - } else if (clicked != null && inventory.carried != null) { +class MouseInventoryClickHandler { + /* public static void handle(int buttonNum, boolean clickedOutside, int + slotId, Player player) { Inventory inventory = player.inventory; Slot + slot = player.getInventorySlot(slotId); if (slot != null) { ItemInstance + clicked = slot.getItem(); if (clicked == null && inventory.carried == + null) { } else if (clicked != null && inventory.carried == null) { int c + = buttonNum == 0 ? clicked.count : (clicked.count + 1) / 2; + inventory.carried = + slot.container.removeItem(slot.slot, c); if (clicked.count == 0) + slot.set(null); slot.onTake(); } else if (clicked == null && + inventory.carried != null && slot.mayPlace(inventory.carried)) { int c = + buttonNum == 0 ? inventory.carried.count : 1; if (c > + slot.getMaxStackSize()) c = slot.getMaxStackSize(); + slot.set(inventory.carried.remove(c)); + if (inventory.carried.count == 0) + inventory.carried = null; } else if (clicked != null && inventory.carried + != null) { - if (slot.mayPlace(inventory.carried)) { - if (clicked.id != inventory.carried.id) { - if (inventory.carried.count <= slot.getMaxStackSize()) { - ItemInstance tmp = clicked; - slot.set(inventory.carried); - inventory.carried = tmp; - } - } else if (clicked.id == inventory.carried.id) { - if (buttonNum == 0) { - int c = inventory.carried.count; - if (c > slot.getMaxStackSize() - clicked.count) c = slot.getMaxStackSize() - clicked.count; - if (c > inventory.carried.getMaxStackSize() - clicked.count) c = inventory.carried.getMaxStackSize() - clicked.count; - inventory.carried.remove(c); - if (inventory.carried.count == 0) inventory.carried = null; - clicked.count += c; - } else if (buttonNum == 1) { - int c = 1; - if (c > slot.getMaxStackSize() - clicked.count) c = slot.getMaxStackSize() - clicked.count; - if (c > inventory.carried.getMaxStackSize() - clicked.count) c = inventory.carried.getMaxStackSize() - clicked.count; - inventory.carried.remove(c); - if (inventory.carried.count == 0) inventory.carried = null; - clicked.count += c; - } - } - } else { - if (clicked.id == inventory.carried.id && inventory.carried.getMaxStackSize() > 1) { - int c = clicked.count; - if (c > 0 && c + inventory.carried.count <= inventory.carried.getMaxStackSize()) { - inventory.carried.count += c; - clicked.remove(c); - if (clicked.count == 0) slot.set(null); - slot.onTake(); - } - } - } - } - slot.setChanged(); - } else if (inventory.carried != null) { - if (clickedOutside) { - if (buttonNum == 0) { - player.drop(inventory.carried); - inventory.carried = null; - } - if (buttonNum == 1) { - player.drop(inventory.carried.remove(1)); - if (inventory.carried.count == 0) inventory.carried = null; - } - } - } - } - - public static void handleClose(Player player) { - Inventory inventory = player.inventory; - if (inventory.carried != null) { - player.drop(inventory.carried); - inventory.carried = null; - } - }*/ + if (slot.mayPlace(inventory.carried)) { + if (clicked.id != + inventory.carried.id) { if (inventory.carried.count <= + slot.getMaxStackSize()) { ItemInstance tmp = clicked; + slot.set(inventory.carried); + inventory.carried = + tmp; + } + } else if (clicked.id == + inventory.carried.id) { if (buttonNum == 0) { int c = + inventory.carried.count; if (c > slot.getMaxStackSize() - clicked.count) + c = slot.getMaxStackSize() - clicked.count; if (c > + inventory.carried.getMaxStackSize() - clicked.count) c = + inventory.carried.getMaxStackSize() - clicked.count; + inventory.carried.remove(c); + if + (inventory.carried.count == 0) inventory.carried = null; clicked.count += + c; } else if (buttonNum == 1) { int c = 1; if (c > slot.getMaxStackSize() + - clicked.count) c = slot.getMaxStackSize() - clicked.count; if (c > + inventory.carried.getMaxStackSize() - clicked.count) c = + inventory.carried.getMaxStackSize() - clicked.count; + inventory.carried.remove(c); + if + (inventory.carried.count == 0) inventory.carried = null; clicked.count += + c; + } + } + } else { + if (clicked.id == + inventory.carried.id && inventory.carried.getMaxStackSize() > 1) { int c + = clicked.count; if (c > 0 && c + inventory.carried.count <= + inventory.carried.getMaxStackSize()) { inventory.carried.count += c; + clicked.remove(c); + if (clicked.count == + 0) slot.set(null); slot.onTake(); + } + } + } + } + slot.setChanged(); + } else if (inventory.carried != null) { + if (clickedOutside) { + if (buttonNum == 0) { + player.drop(inventory.carried); + inventory.carried = null; + } + if (buttonNum == 1) { + player.drop(inventory.carried.remove(1)); + if (inventory.carried.count == 0) + inventory.carried = null; + } + } + } + } + public static void handleClose(Player player) { + Inventory inventory = player.inventory; + if (inventory.carried != null) { + player.drop(inventory.carried); + inventory.carried = null; + } + }*/ }; \ No newline at end of file diff --git a/Minecraft.World/Containers/RepairContainer.cpp b/Minecraft.World/Containers/RepairContainer.cpp index ce9e37e15..464d5fd63 100644 --- a/Minecraft.World/Containers/RepairContainer.cpp +++ b/Minecraft.World/Containers/RepairContainer.cpp @@ -2,13 +2,12 @@ #include "RepairMenu.h" #include "RepairContainer.h" -RepairContainer::RepairContainer(RepairMenu *menu, int name, int size) : SimpleContainer(name, size) -{ - m_menu = menu; +RepairContainer::RepairContainer(RepairMenu* menu, int name, int size) + : SimpleContainer(name, size) { + m_menu = menu; } -void RepairContainer::setChanged() -{ - SimpleContainer::setChanged(); - m_menu->slotsChanged(shared_from_this()); +void RepairContainer::setChanged() { + SimpleContainer::setChanged(); + m_menu->slotsChanged(shared_from_this()); } \ No newline at end of file diff --git a/Minecraft.World/Containers/RepairContainer.h b/Minecraft.World/Containers/RepairContainer.h index c222f449f..33fb5c1b9 100644 --- a/Minecraft.World/Containers/RepairContainer.h +++ b/Minecraft.World/Containers/RepairContainer.h @@ -4,12 +4,12 @@ class RepairMenu; -class RepairContainer : public SimpleContainer, public std::enable_shared_from_this -{ +class RepairContainer : public SimpleContainer, + public std::enable_shared_from_this { private: - RepairMenu *m_menu; + RepairMenu* m_menu; public: - RepairContainer(RepairMenu *menu, int name, int size); - void setChanged(); + RepairContainer(RepairMenu* menu, int name, int size); + void setChanged(); }; \ No newline at end of file diff --git a/Minecraft.World/Containers/RepairMenu.cpp b/Minecraft.World/Containers/RepairMenu.cpp index 712a00979..487f91d41 100644 --- a/Minecraft.World/Containers/RepairMenu.cpp +++ b/Minecraft.World/Containers/RepairMenu.cpp @@ -6,398 +6,383 @@ #include "../Headers/net.minecraft.world.item.enchantment.h" #include "RepairMenu.h" -RepairMenu::RepairMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt, std::shared_ptr player) -{ - resultSlots = std::shared_ptr( new ResultContainer() ); - repairSlots = std::shared_ptr( new RepairContainer(this,IDS_REPAIR_AND_NAME, 2) ); - cost = 0; - repairItemCountCost = 0; +RepairMenu::RepairMenu(std::shared_ptr inventory, Level* level, + int xt, int yt, int zt, std::shared_ptr player) { + resultSlots = std::shared_ptr(new ResultContainer()); + repairSlots = std::shared_ptr( + new RepairContainer(this, IDS_REPAIR_AND_NAME, 2)); + cost = 0; + repairItemCountCost = 0; - this->level = level; - this->x = xt; - this->y = yt; - this->z = zt; - this->player = player; + this->level = level; + this->x = xt; + this->y = yt; + this->z = zt; + this->player = player; - addSlot(new Slot(repairSlots, INPUT_SLOT, 27, 43 + 4)); - addSlot(new Slot(repairSlots, ADDITIONAL_SLOT, 76, 43 + 4)); + addSlot(new Slot(repairSlots, INPUT_SLOT, 27, 43 + 4)); + addSlot(new Slot(repairSlots, ADDITIONAL_SLOT, 76, 43 + 4)); - // 4J Stu - Anonymous class here is now RepairResultSlot - addSlot(new RepairResultSlot(this, xt, yt, zt, resultSlots, RESULT_SLOT, 134, 43 + 4)); + // 4J Stu - Anonymous class here is now RepairResultSlot + addSlot(new RepairResultSlot(this, xt, yt, zt, resultSlots, RESULT_SLOT, + 134, 43 + 4)); - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 142)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 142)); + } } -void RepairMenu::slotsChanged(std::shared_ptr container) -{ - AbstractContainerMenu::slotsChanged(); +void RepairMenu::slotsChanged(std::shared_ptr container) { + AbstractContainerMenu::slotsChanged(); - if (container == repairSlots) createResult(); + if (container == repairSlots) createResult(); } -void RepairMenu::createResult() -{ - std::shared_ptr input = repairSlots->getItem(INPUT_SLOT); - cost = 0; - int price = 0; - int tax = 0; - int namingCost = 0; +void RepairMenu::createResult() { + std::shared_ptr input = repairSlots->getItem(INPUT_SLOT); + cost = 0; + int price = 0; + int tax = 0; + int namingCost = 0; - if (DEBUG_COST) app.DebugPrintf("----"); + if (DEBUG_COST) app.DebugPrintf("----"); - if (input == NULL) - { - resultSlots->setItem(0, nullptr); - cost = 0; - return; - } - else - { - std::shared_ptr result = input->copy(); - std::shared_ptr addition = repairSlots->getItem(ADDITIONAL_SLOT); - std::unordered_map *enchantments = EnchantmentHelper::getEnchantments(result); - bool usingBook = false; + if (input == NULL) { + resultSlots->setItem(0, nullptr); + cost = 0; + return; + } else { + std::shared_ptr result = input->copy(); + std::shared_ptr addition = + repairSlots->getItem(ADDITIONAL_SLOT); + std::unordered_map* enchantments = + EnchantmentHelper::getEnchantments(result); + bool usingBook = false; - tax += input->getBaseRepairCost() + (addition == NULL ? 0 : addition->getBaseRepairCost()); - if (DEBUG_COST) - { - app.DebugPrintf("Starting with base repair tax of %d (%d + %d)\n", tax, input->getBaseRepairCost(), (addition == NULL ? 0 : addition->getBaseRepairCost())); - } + tax += input->getBaseRepairCost() + + (addition == NULL ? 0 : addition->getBaseRepairCost()); + if (DEBUG_COST) { + app.DebugPrintf( + "Starting with base repair tax of %d (%d + %d)\n", tax, + input->getBaseRepairCost(), + (addition == NULL ? 0 : addition->getBaseRepairCost())); + } - repairItemCountCost = 0; + repairItemCountCost = 0; - if (addition != NULL) - { - usingBook = addition->id == Item::enchantedBook_Id && Item::enchantedBook->getEnchantments(addition)->size() > 0; + if (addition != NULL) { + usingBook = + addition->id == Item::enchantedBook_Id && + Item::enchantedBook->getEnchantments(addition)->size() > 0; - if (result->isDamageableItem() && Item::items[result->id]->isValidRepairItem(input, addition)) - { - int repairAmount = std::min(result->getDamageValue(), result->getMaxDamage() / 4); - if (repairAmount <= 0) - { - resultSlots->setItem(0, nullptr); - cost = 0; - return; - } - else - { - int count = 0; - while (repairAmount > 0 && count < addition->count) - { - int resultDamage = result->getDamageValue() - repairAmount; - result->setAuxValue(resultDamage); - price += std::max(1, repairAmount / 100) + enchantments->size(); + if (result->isDamageableItem() && + Item::items[result->id]->isValidRepairItem(input, addition)) { + int repairAmount = std::min(result->getDamageValue(), + result->getMaxDamage() / 4); + if (repairAmount <= 0) { + resultSlots->setItem(0, nullptr); + cost = 0; + return; + } else { + int count = 0; + while (repairAmount > 0 && count < addition->count) { + int resultDamage = + result->getDamageValue() - repairAmount; + result->setAuxValue(resultDamage); + price += std::max(1, repairAmount / 100) + + enchantments->size(); - repairAmount = std::min(result->getDamageValue(), result->getMaxDamage() / 4); - count++; - } - repairItemCountCost = count; - } - } - else if (!usingBook && (result->id != addition->id || !result->isDamageableItem())) - { - resultSlots->setItem(0, nullptr); - cost = 0; - return; - } - else - { - if (result->isDamageableItem() && !usingBook) - { - int remaining1 = input->getMaxDamage() - input->getDamageValue(); - int remaining2 = addition->getMaxDamage() - addition->getDamageValue(); - int additional = remaining2 + result->getMaxDamage() * 12 / 100; - int remaining = remaining1 + additional; - int resultDamage = result->getMaxDamage() - remaining; - if (resultDamage < 0) resultDamage = 0; + repairAmount = std::min(result->getDamageValue(), + result->getMaxDamage() / 4); + count++; + } + repairItemCountCost = count; + } + } else if (!usingBook && (result->id != addition->id || + !result->isDamageableItem())) { + resultSlots->setItem(0, nullptr); + cost = 0; + return; + } else { + if (result->isDamageableItem() && !usingBook) { + int remaining1 = + input->getMaxDamage() - input->getDamageValue(); + int remaining2 = + addition->getMaxDamage() - addition->getDamageValue(); + int additional = + remaining2 + result->getMaxDamage() * 12 / 100; + int remaining = remaining1 + additional; + int resultDamage = result->getMaxDamage() - remaining; + if (resultDamage < 0) resultDamage = 0; - if (resultDamage < result->getAuxValue()) - { - result->setAuxValue(resultDamage); - price += std::max(1, additional / 100); - if (DEBUG_COST) - { - app.DebugPrintf("Repairing; price is now %d (went up by %d)\n", price, std::max(1, additional / 100) ); - } - } - } + if (resultDamage < result->getAuxValue()) { + result->setAuxValue(resultDamage); + price += std::max(1, additional / 100); + if (DEBUG_COST) { + app.DebugPrintf( + "Repairing; price is now %d (went up by %d)\n", + price, std::max(1, additional / 100)); + } + } + } - std::unordered_map *additionalEnchantments = EnchantmentHelper::getEnchantments(addition); + std::unordered_map* additionalEnchantments = + EnchantmentHelper::getEnchantments(addition); - for(AUTO_VAR(it, additionalEnchantments->begin()); it != additionalEnchantments->end(); ++it) - { - int id = it->first; - Enchantment *enchantment = Enchantment::enchantments[id]; - AUTO_VAR(localIt, enchantments->find(id)); - int current = localIt != enchantments->end() ? localIt->second : 0; - int level = it->second; - level = (current == level) ? level += 1 : std::max(level, current); - int extra = level - current; - bool compatible = enchantment->canEnchant(input); + for (AUTO_VAR(it, additionalEnchantments->begin()); + it != additionalEnchantments->end(); ++it) { + int id = it->first; + Enchantment* enchantment = Enchantment::enchantments[id]; + AUTO_VAR(localIt, enchantments->find(id)); + int current = + localIt != enchantments->end() ? localIt->second : 0; + int level = it->second; + level = (current == level) ? level += 1 + : std::max(level, current); + int extra = level - current; + bool compatible = enchantment->canEnchant(input); - if (player->abilities.instabuild) compatible = true; + if (player->abilities.instabuild) compatible = true; - for(AUTO_VAR(it2, enchantments->begin()); it2 != enchantments->end(); ++it2) - { - int other = it2->first; - if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) - { - compatible = false; + for (AUTO_VAR(it2, enchantments->begin()); + it2 != enchantments->end(); ++it2) { + int other = it2->first; + if (other != id && + !enchantment->isCompatibleWith( + Enchantment::enchantments[other])) { + compatible = false; - price += extra; - if (DEBUG_COST) - { - app.DebugPrintf("Enchantment incompatibility fee; price is now %d (went up by %d)\n", price, extra); - } - } - } + price += extra; + if (DEBUG_COST) { + app.DebugPrintf( + "Enchantment incompatibility fee; price is " + "now %d (went up by %d)\n", + price, extra); + } + } + } - if (!compatible) continue; - if (level > enchantment->getMaxLevel()) level = enchantment->getMaxLevel(); - (*enchantments)[id] = level; - int fee = 0; + if (!compatible) continue; + if (level > enchantment->getMaxLevel()) + level = enchantment->getMaxLevel(); + (*enchantments)[id] = level; + int fee = 0; - switch (enchantment->getFrequency()) - { - case Enchantment::FREQ_COMMON: - fee = 1; - break; - case Enchantment::FREQ_UNCOMMON: - fee = 2; - break; - case Enchantment::FREQ_RARE: - fee = 4; - break; - case Enchantment::FREQ_VERY_RARE: - fee = 8; - break; - } + switch (enchantment->getFrequency()) { + case Enchantment::FREQ_COMMON: + fee = 1; + break; + case Enchantment::FREQ_UNCOMMON: + fee = 2; + break; + case Enchantment::FREQ_RARE: + fee = 4; + break; + case Enchantment::FREQ_VERY_RARE: + fee = 8; + break; + } - if (usingBook) fee = std::max(1, fee / 2); + if (usingBook) fee = std::max(1, fee / 2); - price += fee * extra; - if (DEBUG_COST) - { - app.DebugPrintf("Enchantment increase fee; price is now %d (went up by %d)\n", price, fee*extra); - } - } - delete additionalEnchantments; - } - } + price += fee * extra; + if (DEBUG_COST) { + app.DebugPrintf( + "Enchantment increase fee; price is now %d (went " + "up by %d)\n", + price, fee * extra); + } + } + delete additionalEnchantments; + } + } - if (itemName.length() > 0 && !equalsIgnoreCase(itemName, input->getHoverName()) && itemName.length() > 0) - { - namingCost = input->isDamageableItem() ? 7 : input->count * 5; + if (itemName.length() > 0 && + !equalsIgnoreCase(itemName, input->getHoverName()) && + itemName.length() > 0) { + namingCost = input->isDamageableItem() ? 7 : input->count * 5; - price += namingCost; - if (DEBUG_COST) - { - app.DebugPrintf("Naming cost; price is now %d (went up by %d)", price, namingCost); - } + price += namingCost; + if (DEBUG_COST) { + app.DebugPrintf("Naming cost; price is now %d (went up by %d)", + price, namingCost); + } - if (input->hasCustomHoverName()) - { - tax += namingCost / 2; + if (input->hasCustomHoverName()) { + tax += namingCost / 2; - if (DEBUG_COST) - { - app.DebugPrintf("Already-named tax; tax is now %d (went up by %d)", tax, (namingCost / 2)); - } - } + if (DEBUG_COST) { + app.DebugPrintf( + "Already-named tax; tax is now %d (went up by %d)", tax, + (namingCost / 2)); + } + } - result->setHoverName(itemName); - } + result->setHoverName(itemName); + } - int count = 0; - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) - { - int id = it->first; - Enchantment *enchantment = Enchantment::enchantments[id]; - int level = it->second; - int fee = 0; + int count = 0; + for (AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); + ++it) { + int id = it->first; + Enchantment* enchantment = Enchantment::enchantments[id]; + int level = it->second; + int fee = 0; - count++; + count++; - switch (enchantment->getFrequency()) - { - case Enchantment::FREQ_COMMON: - fee = 1; - break; - case Enchantment::FREQ_UNCOMMON: - fee = 2; - break; - case Enchantment::FREQ_RARE: - fee = 4; - break; - case Enchantment::FREQ_VERY_RARE: - fee = 8; - break; - } + switch (enchantment->getFrequency()) { + case Enchantment::FREQ_COMMON: + fee = 1; + break; + case Enchantment::FREQ_UNCOMMON: + fee = 2; + break; + case Enchantment::FREQ_RARE: + fee = 4; + break; + case Enchantment::FREQ_VERY_RARE: + fee = 8; + break; + } - if (usingBook) fee = std::max(1, fee / 2); + if (usingBook) fee = std::max(1, fee / 2); - tax += count + level * fee; - if (DEBUG_COST) - { - app.DebugPrintf("Enchantment tax; tax is now %d (went up by %d)", tax, (count + level * fee)); - } - } + tax += count + level * fee; + if (DEBUG_COST) { + app.DebugPrintf( + "Enchantment tax; tax is now %d (went up by %d)", tax, + (count + level * fee)); + } + } - if (usingBook) tax = std::max(1, tax / 2); + if (usingBook) tax = std::max(1, tax / 2); - cost = tax + price; - if (price <= 0) - { - if (DEBUG_COST) app.DebugPrintf("No purchase, only tax; aborting"); - result = nullptr; - } - if (namingCost == price && namingCost > 0 && cost >= 40) - { - if (DEBUG_COST) app.DebugPrintf("Cost is too high; aborting"); - app.DebugPrintf("Naming an item only, cost too high; giving discount to cap cost to 39 levels"); - cost = 39; - } - if (cost >= 40 && !player->abilities.instabuild) - { - if (DEBUG_COST) app.DebugPrintf("Cost is too high; aborting"); - result = nullptr; - } + cost = tax + price; + if (price <= 0) { + if (DEBUG_COST) app.DebugPrintf("No purchase, only tax; aborting"); + result = nullptr; + } + if (namingCost == price && namingCost > 0 && cost >= 40) { + if (DEBUG_COST) app.DebugPrintf("Cost is too high; aborting"); + app.DebugPrintf( + "Naming an item only, cost too high; giving discount to cap " + "cost to 39 levels"); + cost = 39; + } + if (cost >= 40 && !player->abilities.instabuild) { + if (DEBUG_COST) app.DebugPrintf("Cost is too high; aborting"); + result = nullptr; + } - if (result != NULL) - { - int baseCost = result->getBaseRepairCost(); - if (addition != NULL && baseCost < addition->getBaseRepairCost()) baseCost = addition->getBaseRepairCost(); - if (result->hasCustomHoverName()) baseCost -= 9; - if (baseCost < 0) baseCost = 0; - baseCost += 2; + if (result != NULL) { + int baseCost = result->getBaseRepairCost(); + if (addition != NULL && baseCost < addition->getBaseRepairCost()) + baseCost = addition->getBaseRepairCost(); + if (result->hasCustomHoverName()) baseCost -= 9; + if (baseCost < 0) baseCost = 0; + baseCost += 2; - result->setRepairCost(baseCost); - EnchantmentHelper::setEnchantments(enchantments, result); - } + result->setRepairCost(baseCost); + EnchantmentHelper::setEnchantments(enchantments, result); + } - resultSlots->setItem(0, result); - } + resultSlots->setItem(0, result); + } - broadcastChanges(); + broadcastChanges(); - if (DEBUG_COST) - { - if (level->isClientSide) - { - app.DebugPrintf("CLIENT Cost is %d (%d price, %d tax)\n", cost, price, tax); - } - else - { - app.DebugPrintf("SERVER Cost is %d (%d price, %d tax)\n", cost, price, tax); - } - } + if (DEBUG_COST) { + if (level->isClientSide) { + app.DebugPrintf("CLIENT Cost is %d (%d price, %d tax)\n", cost, + price, tax); + } else { + app.DebugPrintf("SERVER Cost is %d (%d price, %d tax)\n", cost, + price, tax); + } + } } -void RepairMenu::sendData(int id, int value) -{ - AbstractContainerMenu::sendData(id, value); +void RepairMenu::sendData(int id, int value) { + AbstractContainerMenu::sendData(id, value); } -void RepairMenu::addSlotListener(ContainerListener *listener) -{ - AbstractContainerMenu::addSlotListener(listener); - listener->setContainerData(this, DATA_TOTAL_COST, cost); +void RepairMenu::addSlotListener(ContainerListener* listener) { + AbstractContainerMenu::addSlotListener(listener); + listener->setContainerData(this, DATA_TOTAL_COST, cost); } -void RepairMenu::setData(int id, int value) -{ - if (id == DATA_TOTAL_COST) cost = value; +void RepairMenu::setData(int id, int value) { + if (id == DATA_TOTAL_COST) cost = value; } -void RepairMenu::removed(std::shared_ptr player) -{ - AbstractContainerMenu::removed(player); - if (level->isClientSide) return; +void RepairMenu::removed(std::shared_ptr player) { + AbstractContainerMenu::removed(player); + if (level->isClientSide) return; - for (int i = 0; i < repairSlots->getContainerSize(); i++) - { - std::shared_ptr item = repairSlots->removeItemNoUpdate(i); - if (item != NULL) - { - player->drop(item); - } - } + for (int i = 0; i < repairSlots->getContainerSize(); i++) { + std::shared_ptr item = repairSlots->removeItemNoUpdate(i); + if (item != NULL) { + player->drop(item); + } + } } -bool RepairMenu::stillValid(std::shared_ptr player) -{ - if (level->getTile(x, y, z) != Tile::anvil_Id) return false; - if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; - return true; +bool RepairMenu::stillValid(std::shared_ptr player) { + if (level->getTile(x, y, z) != Tile::anvil_Id) return false; + if (player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 8 * 8) return false; + return true; } -std::shared_ptr RepairMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); +std::shared_ptr RepairMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex == RESULT_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - slot->onQuickCraft(stack, clicked); - } - else if (slotIndex == INPUT_SLOT || slotIndex == ADDITIONAL_SLOT) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, false)) - { - return nullptr; - } - } - else if (slotIndex >= INV_SLOT_START && slotIndex < USE_ROW_SLOT_END) - { - if (!moveItemStackTo(stack, INPUT_SLOT, RESULT_SLOT, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + if (slotIndex == RESULT_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + slot->onQuickCraft(stack, clicked); + } else if (slotIndex == INPUT_SLOT || slotIndex == ADDITIONAL_SLOT) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + false)) { + return nullptr; + } + } else if (slotIndex >= INV_SLOT_START && + slotIndex < USE_ROW_SLOT_END) { + if (!moveItemStackTo(stack, INPUT_SLOT, RESULT_SLOT, false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } -void RepairMenu::setItemName(const std::wstring &name) -{ - this->itemName = name; - if (getSlot(RESULT_SLOT)->hasItem()) - { - getSlot(RESULT_SLOT)->getItem()->setHoverName(itemName); - } - createResult(); +void RepairMenu::setItemName(const std::wstring& name) { + this->itemName = name; + if (getSlot(RESULT_SLOT)->hasItem()) { + getSlot(RESULT_SLOT)->getItem()->setHoverName(itemName); + } + createResult(); } diff --git a/Minecraft.World/Containers/RepairMenu.h b/Minecraft.World/Containers/RepairMenu.h index f47f01a5f..4c9d3462e 100644 --- a/Minecraft.World/Containers/RepairMenu.h +++ b/Minecraft.World/Containers/RepairMenu.h @@ -2,54 +2,56 @@ #include "AbstractContainerMenu.h" -class RepairMenu : public AbstractContainerMenu -{ - friend class RepairResultSlot; -private: - static const bool DEBUG_COST = false; - -public: - static const int INPUT_SLOT = 0; - static const int ADDITIONAL_SLOT = 1; - static const int RESULT_SLOT = 2; - - static const int INV_SLOT_START = RESULT_SLOT + 1; - static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = INV_SLOT_END; - static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; - -public: - static const int DATA_TOTAL_COST = 0; +class RepairMenu : public AbstractContainerMenu { + friend class RepairResultSlot; private: - std::shared_ptr resultSlots; - - // 4J Stu - anonymous class here now RepairContainer - std::shared_ptr repairSlots; - - Level *level; - int x, y, z; + static const bool DEBUG_COST = false; public: - int cost; + static const int INPUT_SLOT = 0; + static const int ADDITIONAL_SLOT = 1; + static const int RESULT_SLOT = 2; + + static const int INV_SLOT_START = RESULT_SLOT + 1; + static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = INV_SLOT_END; + static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; + +public: + static const int DATA_TOTAL_COST = 0; private: - int repairItemCountCost; - std::wstring itemName; - std::shared_ptr player; + std::shared_ptr resultSlots; + + // 4J Stu - anonymous class here now RepairContainer + std::shared_ptr repairSlots; + + Level* level; + int x, y, z; public: - using AbstractContainerMenu::slotsChanged; + int cost; - RepairMenu(std::shared_ptr inventory, Level *level, int xt, int yt, int zt, std::shared_ptr player); +private: + int repairItemCountCost; + std::wstring itemName; + std::shared_ptr player; - void slotsChanged(std::shared_ptr container); - void createResult(); - void sendData(int id, int value); - void addSlotListener(ContainerListener *listener); - void setData(int id, int value); - void removed(std::shared_ptr player); - bool stillValid(std::shared_ptr player); - std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); - void setItemName(const std::wstring &name); +public: + using AbstractContainerMenu::slotsChanged; + + RepairMenu(std::shared_ptr inventory, Level* level, int xt, + int yt, int zt, std::shared_ptr player); + + void slotsChanged(std::shared_ptr container); + void createResult(); + void sendData(int id, int value); + void addSlotListener(ContainerListener* listener); + void setData(int id, int value); + void removed(std::shared_ptr player); + bool stillValid(std::shared_ptr player); + std::shared_ptr quickMoveStack(std::shared_ptr player, + int slotIndex); + void setItemName(const std::wstring& name); }; diff --git a/Minecraft.World/Containers/RepairResultSlot.cpp b/Minecraft.World/Containers/RepairResultSlot.cpp index 6c9e805ac..bbe228a23 100644 --- a/Minecraft.World/Containers/RepairResultSlot.cpp +++ b/Minecraft.World/Containers/RepairResultSlot.cpp @@ -5,71 +5,66 @@ #include "../Headers/net.minecraft.world.entity.player.h" #include "RepairResultSlot.h" -RepairResultSlot::RepairResultSlot(RepairMenu *menu, int xt, int yt, int zt, std::shared_ptr container, int slot, int x, int y) : Slot(container, slot, x, y) -{ - m_menu = menu; - this->xt = xt; - this->yt = yt; - this->zt = zt; +RepairResultSlot::RepairResultSlot(RepairMenu* menu, int xt, int yt, int zt, + std::shared_ptr container, + int slot, int x, int y) + : Slot(container, slot, x, y) { + m_menu = menu; + this->xt = xt; + this->yt = yt; + this->zt = zt; } -bool RepairResultSlot::mayPlace(std::shared_ptr item) -{ - return false; +bool RepairResultSlot::mayPlace(std::shared_ptr item) { + return false; } -bool RepairResultSlot::mayPickup(std::shared_ptr player) -{ - return (player->abilities.instabuild || player->experienceLevel >= m_menu->cost) && (m_menu->cost > 0 && hasItem()); +bool RepairResultSlot::mayPickup(std::shared_ptr player) { + return (player->abilities.instabuild || + player->experienceLevel >= m_menu->cost) && + (m_menu->cost > 0 && hasItem()); } -void RepairResultSlot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - if (!player->abilities.instabuild) player->withdrawExperienceLevels(m_menu->cost); - m_menu->repairSlots->setItem(RepairMenu::INPUT_SLOT, nullptr); - if (m_menu->repairItemCountCost > 0) - { - std::shared_ptr addition = m_menu->repairSlots->getItem(RepairMenu::ADDITIONAL_SLOT); - if (addition != NULL && addition->count > m_menu->repairItemCountCost) - { - addition->count -= m_menu->repairItemCountCost; - m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, addition); - } - else - { - m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, nullptr); - } - } - else - { - m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, nullptr); - } - m_menu->cost = 0; +void RepairResultSlot::onTake(std::shared_ptr player, + std::shared_ptr carried) { + if (!player->abilities.instabuild) + player->withdrawExperienceLevels(m_menu->cost); + m_menu->repairSlots->setItem(RepairMenu::INPUT_SLOT, nullptr); + if (m_menu->repairItemCountCost > 0) { + std::shared_ptr addition = + m_menu->repairSlots->getItem(RepairMenu::ADDITIONAL_SLOT); + if (addition != NULL && addition->count > m_menu->repairItemCountCost) { + addition->count -= m_menu->repairItemCountCost; + m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, addition); + } else { + m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, nullptr); + } + } else { + m_menu->repairSlots->setItem(RepairMenu::ADDITIONAL_SLOT, nullptr); + } + m_menu->cost = 0; - if (!player->abilities.instabuild && !m_menu->level->isClientSide && m_menu->level->getTile(xt, yt, zt) == Tile::anvil->id && player->getRandom()->nextFloat() < 0.12f) - { - int data = m_menu->level->getData(xt, yt, zt); - int dir = data & 0x3; - int dmg = data >> 2; + if (!player->abilities.instabuild && !m_menu->level->isClientSide && + m_menu->level->getTile(xt, yt, zt) == Tile::anvil->id && + player->getRandom()->nextFloat() < 0.12f) { + int data = m_menu->level->getData(xt, yt, zt); + int dir = data & 0x3; + int dmg = data >> 2; - if (++dmg > 2) - { - m_menu->level->setTile(xt, yt, zt, 0); - m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_BROKEN, xt, yt, zt, 0); - } - else - { - m_menu->level->setData(xt, yt, zt, dir | (dmg << 2)); - m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_USED, xt, yt, zt, 0); - } - } - else if (!m_menu->level->isClientSide) - { - m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_USED, xt, yt, zt, 0); - } + if (++dmg > 2) { + m_menu->level->setTile(xt, yt, zt, 0); + m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_BROKEN, xt, yt, + zt, 0); + } else { + m_menu->level->setData(xt, yt, zt, dir | (dmg << 2)); + m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_USED, xt, yt, zt, + 0); + } + } else if (!m_menu->level->isClientSide) { + m_menu->level->levelEvent(LevelEvent::SOUND_ANVIL_USED, xt, yt, zt, 0); + } } -bool RepairResultSlot::mayCombine(std::shared_ptr second) -{ - return false; +bool RepairResultSlot::mayCombine(std::shared_ptr second) { + return false; } \ No newline at end of file diff --git a/Minecraft.World/Containers/RepairResultSlot.h b/Minecraft.World/Containers/RepairResultSlot.h index 92af20feb..bbc6b6e3b 100644 --- a/Minecraft.World/Containers/RepairResultSlot.h +++ b/Minecraft.World/Containers/RepairResultSlot.h @@ -4,17 +4,19 @@ class RepairMenu; -class RepairResultSlot : public Slot -{ +class RepairResultSlot : public Slot { private: - RepairMenu *m_menu; - int xt, yt, zt; + RepairMenu* m_menu; + int xt, yt, zt; public: - RepairResultSlot(RepairMenu *menu, int xt, int yt, int zt, std::shared_ptr container, int slot, int x, int y); + RepairResultSlot(RepairMenu* menu, int xt, int yt, int zt, + std::shared_ptr container, int slot, int x, + int y); - bool mayPlace(std::shared_ptr item); - bool mayPickup(std::shared_ptr player); - void onTake(std::shared_ptr player, std::shared_ptr carried); - virtual bool mayCombine(std::shared_ptr item); // 4J Added + bool mayPlace(std::shared_ptr item); + bool mayPickup(std::shared_ptr player); + void onTake(std::shared_ptr player, + std::shared_ptr carried); + virtual bool mayCombine(std::shared_ptr item); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/ResultContainer.cpp b/Minecraft.World/Containers/ResultContainer.cpp index 8ba542995..fd38f5cbe 100644 --- a/Minecraft.World/Containers/ResultContainer.cpp +++ b/Minecraft.World/Containers/ResultContainer.cpp @@ -2,63 +2,48 @@ #include "../Headers/net.minecraft.world.entity.player.h" #include "ResultContainer.h" -ResultContainer::ResultContainer() : Container() -{ - items = new ItemInstanceArray(1); +ResultContainer::ResultContainer() : Container() { + items = new ItemInstanceArray(1); } -unsigned int ResultContainer::getContainerSize() -{ - return 1; +unsigned int ResultContainer::getContainerSize() { return 1; } + +std::shared_ptr ResultContainer::getItem(unsigned int slot) { + return (*items)[0]; } -std::shared_ptr ResultContainer::getItem(unsigned int slot) -{ - return (*items)[0]; +int ResultContainer::getName() { return 0; } + +std::shared_ptr ResultContainer::removeItem(unsigned int slot, + int count) { + if ((*items)[0] != NULL) { + std::shared_ptr item = (*items)[0]; + (*items)[0] = nullptr; + return item; + } + return nullptr; } -int ResultContainer::getName() -{ - return 0; +std::shared_ptr ResultContainer::removeItemNoUpdate(int slot) { + if ((*items)[0] != NULL) { + std::shared_ptr item = (*items)[0]; + (*items)[0] = nullptr; + return item; + } + return nullptr; } -std::shared_ptr ResultContainer::removeItem(unsigned int slot, int count) -{ - if ((*items)[0] != NULL) - { - std::shared_ptr item = (*items)[0]; - (*items)[0] = nullptr; - return item; - } - return nullptr; +void ResultContainer::setItem(unsigned int slot, + std::shared_ptr item) { + (*items)[0] = item; } -std::shared_ptr ResultContainer::removeItemNoUpdate(int slot) -{ - if ((*items)[0] != NULL) - { - std::shared_ptr item = (*items)[0]; - (*items)[0] = nullptr; - return item; - } - return nullptr; +int ResultContainer::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -void ResultContainer::setItem(unsigned int slot, std::shared_ptr item) -{ - (*items)[0] = item; -} +void ResultContainer::setChanged() {} -int ResultContainer::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; -} - -void ResultContainer::setChanged() -{ -} - -bool ResultContainer::stillValid(std::shared_ptr player) -{ - return true; +bool ResultContainer::stillValid(std::shared_ptr player) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Containers/ResultContainer.h b/Minecraft.World/Containers/ResultContainer.h index 8f83543d6..3f1e4a360 100644 --- a/Minecraft.World/Containers/ResultContainer.h +++ b/Minecraft.World/Containers/ResultContainer.h @@ -2,26 +2,26 @@ #include "Container.h" -class ResultContainer : public Container -{ +class ResultContainer : public Container { private: - ItemInstanceArray *items; + ItemInstanceArray* items; public: - // 4J Stu Added a ctor to init items - ResultContainer(); - virtual ~ResultContainer(){} + // 4J Stu Added a ctor to init items + ResultContainer(); + virtual ~ResultContainer() {} - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - virtual int getName(); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - virtual std::shared_ptr removeItemNoUpdate(int slot); - virtual void setItem(unsigned int slot, std::shared_ptr item); - virtual int getMaxStackSize(); - virtual void setChanged(); - virtual bool stillValid(std::shared_ptr player); + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + virtual int getName(); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual void setItem(unsigned int slot, std::shared_ptr item); + virtual int getMaxStackSize(); + virtual void setChanged(); + virtual bool stillValid(std::shared_ptr player); - void startOpen() { } // TODO Auto-generated method stub - void stopOpen() { } // TODO Auto-generated method stub + void startOpen() {} // TODO Auto-generated method stub + void stopOpen() {} // TODO Auto-generated method stub }; diff --git a/Minecraft.World/Containers/ResultSlot.cpp b/Minecraft.World/Containers/ResultSlot.cpp index ea4258969..1d661d84a 100644 --- a/Minecraft.World/Containers/ResultSlot.cpp +++ b/Minecraft.World/Containers/ResultSlot.cpp @@ -6,97 +6,111 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "ResultSlot.h" -ResultSlot::ResultSlot(Player *player, std::shared_ptr craftSlots, std::shared_ptr container, int id, int x, int y) : Slot( container, id, x, y ) -{ - this->player = player; - this->craftSlots = craftSlots; - removeCount = 0; +ResultSlot::ResultSlot(Player* player, std::shared_ptr craftSlots, + std::shared_ptr container, int id, int x, + int y) + : Slot(container, id, x, y) { + this->player = player; + this->craftSlots = craftSlots; + removeCount = 0; } -bool ResultSlot::mayPlace(std::shared_ptr item) -{ - return false; +bool ResultSlot::mayPlace(std::shared_ptr item) { return false; } + +std::shared_ptr ResultSlot::remove(int c) { + if (hasItem()) { + removeCount += std::min(c, getItem()->count); + } + return Slot::remove(c); } -std::shared_ptr ResultSlot::remove(int c) -{ - if (hasItem()) - { - removeCount += std::min(c, getItem()->count); - } - return Slot::remove(c); +void ResultSlot::onQuickCraft(std::shared_ptr picked, int count) { + removeCount += count; + checkTakeAchievements(picked); } -void ResultSlot::onQuickCraft(std::shared_ptr picked, int count) -{ - removeCount += count; - checkTakeAchievements(picked); +void ResultSlot::checkTakeAchievements(std::shared_ptr carried) { + carried->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + removeCount); + removeCount = 0; + + if (carried->id == Tile::workBench_Id) + player->awardStat(GenericStats::buildWorkbench(), + GenericStats::param_buildWorkbench()); + else if (carried->id == Item::pickAxe_wood_Id) + player->awardStat(GenericStats::buildPickaxe(), + GenericStats::param_buildPickaxe()); + else if (carried->id == Tile::furnace_Id) + player->awardStat(GenericStats::buildFurnace(), + GenericStats::param_buildFurnace()); + else if (carried->id == Item::hoe_wood_Id) + player->awardStat(GenericStats::buildHoe(), + GenericStats::param_buildHoe()); + else if (carried->id == Item::bread_Id) + player->awardStat(GenericStats::makeBread(), + GenericStats::param_makeBread()); + else if (carried->id == Item::cake_Id) + player->awardStat(GenericStats::bakeCake(), + GenericStats::param_bakeCake()); + else if (carried->id == Item::pickAxe_stone_Id) + player->awardStat(GenericStats::buildBetterPickaxe(), + GenericStats::param_buildBetterPickaxe()); + else if (carried->id == Item::sword_wood_Id) + player->awardStat(GenericStats::buildSword(), + GenericStats::param_buildSword()); + // else if (carried->id == Tile::enchantTable_Id) + // player->awardStat(GenericStats::enchantments(), + // GenericStats::param_achievement(eAward_)); + else if (carried->id == Tile::bookshelf_Id) + player->awardStat(GenericStats::bookcase(), + GenericStats::param_bookcase()); + + // 4J : WESTY : Added new acheivements. + else if (carried->id == Tile::dispenser_Id) + player->awardStat(GenericStats::dispenseWithThis(), + GenericStats::param_dispenseWithThis()); } -void ResultSlot::checkTakeAchievements(std::shared_ptr carried) -{ - carried->onCraftedBy(player->level, std::dynamic_pointer_cast( player->shared_from_this() ), removeCount); - removeCount = 0; +void ResultSlot::onTake(std::shared_ptr player, + std::shared_ptr carried) { + checkTakeAchievements(carried); - if (carried->id == Tile::workBench_Id) player->awardStat(GenericStats::buildWorkbench(), GenericStats::param_buildWorkbench()); - else if (carried->id == Item::pickAxe_wood_Id) player->awardStat(GenericStats::buildPickaxe(), GenericStats::param_buildPickaxe()); - else if (carried->id == Tile::furnace_Id) player->awardStat(GenericStats::buildFurnace(), GenericStats::param_buildFurnace()); - else if (carried->id == Item::hoe_wood_Id) player->awardStat(GenericStats::buildHoe(), GenericStats::param_buildHoe()); - else if (carried->id == Item::bread_Id) player->awardStat(GenericStats::makeBread(), GenericStats::param_makeBread()); - else if (carried->id == Item::cake_Id) player->awardStat(GenericStats::bakeCake(), GenericStats::param_bakeCake()); - else if (carried->id == Item::pickAxe_stone_Id) player->awardStat(GenericStats::buildBetterPickaxe(), GenericStats::param_buildBetterPickaxe()); - else if (carried->id == Item::sword_wood_Id) player->awardStat(GenericStats::buildSword(), GenericStats::param_buildSword()); - //else if (carried->id == Tile::enchantTable_Id) player->awardStat(GenericStats::enchantments(), GenericStats::param_achievement(eAward_)); - else if (carried->id == Tile::bookshelf_Id) player->awardStat(GenericStats::bookcase(), GenericStats::param_bookcase()); + for (unsigned int i = 0; i < craftSlots->getContainerSize(); i++) { + std::shared_ptr item = craftSlots->getItem(i); + if (item != NULL) { + craftSlots->removeItem(i, 1); - // 4J : WESTY : Added new acheivements. - else if (carried->id == Tile::dispenser_Id) player->awardStat(GenericStats::dispenseWithThis(), GenericStats::param_dispenseWithThis()); + if (item->getItem()->hasCraftingRemainingItem()) { + // (TheApathetic) + std::shared_ptr craftResult = + std::shared_ptr(new ItemInstance( + item->getItem()->getCraftingRemainingItem())); + + /* + * Try to place this in the player's inventory (See we.java + * for new method) + */ + if (item->getItem()->shouldMoveCraftingResultToInventory( + item) && + this->player->inventory->add(craftResult)) { + continue; + } + + // If this slot is now empty, place it there (current + // behavior) + if (craftSlots->getItem(i) == NULL) { + craftSlots->setItem(i, craftResult); + } else { + // Finally, if nothing else, just drop the item + this->player->drop(craftResult); + } + } + } + } } -void ResultSlot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - checkTakeAchievements(carried); - - for (unsigned int i = 0; i < craftSlots->getContainerSize(); i++) - { - std::shared_ptr item = craftSlots->getItem(i); - if (item != NULL) - { - craftSlots->removeItem(i, 1); - - if (item->getItem()->hasCraftingRemainingItem()) - { - - // (TheApathetic) - std::shared_ptr craftResult = std::shared_ptr(new ItemInstance(item->getItem()->getCraftingRemainingItem())); - - /* - * Try to place this in the player's inventory (See we.java - * for new method) - */ - if (item->getItem()->shouldMoveCraftingResultToInventory(item) && this->player->inventory->add(craftResult)) - { - continue; - } - - // If this slot is now empty, place it there (current - // behavior) - if (craftSlots->getItem(i) == NULL) - { - craftSlots->setItem(i, craftResult); - } - else - { - // Finally, if nothing else, just drop the item - this->player->drop(craftResult); - } - } - - } - } -} - -bool ResultSlot::mayCombine(std::shared_ptr second) -{ - return false; +bool ResultSlot::mayCombine(std::shared_ptr second) { + return false; } diff --git a/Minecraft.World/Containers/ResultSlot.h b/Minecraft.World/Containers/ResultSlot.h index b8308f663..b2a0347f4 100644 --- a/Minecraft.World/Containers/ResultSlot.h +++ b/Minecraft.World/Containers/ResultSlot.h @@ -2,25 +2,27 @@ #include "Slot.h" -class ResultSlot : public Slot -{ +class ResultSlot : public Slot { private: - std::shared_ptr craftSlots; - Player *player; // This can't be a std::shared_ptr, as we create a result slot in the inventorymenu in the Player ctor - int removeCount; + std::shared_ptr craftSlots; + Player* player; // This can't be a std::shared_ptr, as we create a result + // slot in the inventorymenu in the Player ctor + int removeCount; public: - ResultSlot(Player *player, std::shared_ptr craftSlots, std::shared_ptr container, int id, int x, int y); - virtual ~ResultSlot() {} + ResultSlot(Player* player, std::shared_ptr craftSlots, + std::shared_ptr container, int id, int x, int y); + virtual ~ResultSlot() {} - virtual bool mayPlace(std::shared_ptr item); - virtual std::shared_ptr remove(int c); + virtual bool mayPlace(std::shared_ptr item); + virtual std::shared_ptr remove(int c); protected: - virtual void onQuickCraft(std::shared_ptr picked, int count); - virtual void checkTakeAchievements(std::shared_ptr carried); + virtual void onQuickCraft(std::shared_ptr picked, int count); + virtual void checkTakeAchievements(std::shared_ptr carried); public: - virtual void onTake(std::shared_ptr player, std::shared_ptr carried); - virtual bool mayCombine(std::shared_ptr item); // 4J Added + virtual void onTake(std::shared_ptr player, + std::shared_ptr carried); + virtual bool mayCombine(std::shared_ptr item); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/SimpleContainer.cpp b/Minecraft.World/Containers/SimpleContainer.cpp index 0aeab342c..d0711c582 100644 --- a/Minecraft.World/Containers/SimpleContainer.cpp +++ b/Minecraft.World/Containers/SimpleContainer.cpp @@ -5,97 +5,86 @@ #include "SimpleContainer.h" -SimpleContainer::SimpleContainer(int name, int size) -{ - this->name = name; - this->size = size; - items = new ItemInstanceArray( size ); +SimpleContainer::SimpleContainer(int name, int size) { + this->name = name; + this->size = size; + items = new ItemInstanceArray(size); - listeners = NULL; + listeners = NULL; } -void SimpleContainer::addListener(net_minecraft_world::ContainerListener *listener) -{ - if (listeners == NULL) listeners = new std::vector(); - listeners->push_back(listener); +void SimpleContainer::addListener( + net_minecraft_world::ContainerListener* listener) { + if (listeners == NULL) + listeners = new std::vector(); + listeners->push_back(listener); } -void SimpleContainer::removeListener(net_minecraft_world::ContainerListener *listener) -{ - // 4J Java has a remove function on lists that will find the first occurence of - // an object and remove it. We need to replicate that ourselves +void SimpleContainer::removeListener( + net_minecraft_world::ContainerListener* listener) { + // 4J Java has a remove function on lists that will find the first occurence + // of an object and remove it. We need to replicate that ourselves - std::vector::iterator it = listeners->begin(); - std::vector::iterator itEnd = listeners->end(); - while( it != itEnd && *it != listener ) - it++; + std::vector::iterator it = + listeners->begin(); + std::vector::iterator itEnd = + listeners->end(); + while (it != itEnd && *it != listener) it++; - if( it != itEnd ) - listeners->erase( it ); + if (it != itEnd) listeners->erase(it); } -std::shared_ptr SimpleContainer::getItem(unsigned int slot) -{ - return (*items)[slot]; +std::shared_ptr SimpleContainer::getItem(unsigned int slot) { + return (*items)[slot]; } -std::shared_ptr SimpleContainer::removeItem(unsigned int slot, int count) -{ - if ((*items)[slot] != NULL) { - if ((*items)[slot]->count <= count) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - this->setChanged(); - return item; - } - else - { - std::shared_ptr i = (*items)[slot]->remove(count); - if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; - this->setChanged(); - return i; - } - } - return nullptr; +std::shared_ptr SimpleContainer::removeItem(unsigned int slot, + int count) { + if ((*items)[slot] != NULL) { + if ((*items)[slot]->count <= count) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + this->setChanged(); + return item; + } else { + std::shared_ptr i = (*items)[slot]->remove(count); + if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; + this->setChanged(); + return i; + } + } + return nullptr; } -std::shared_ptr SimpleContainer::removeItemNoUpdate(int slot) -{ - if ((*items)[slot] != NULL) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - return item; - } - return nullptr; +std::shared_ptr SimpleContainer::removeItemNoUpdate(int slot) { + if ((*items)[slot] != NULL) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + return item; + } + return nullptr; } -void SimpleContainer::setItem(unsigned int slot, std::shared_ptr item) -{ - (*items)[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); - this->setChanged(); +void SimpleContainer::setItem(unsigned int slot, + std::shared_ptr item) { + (*items)[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); + this->setChanged(); } -unsigned int SimpleContainer::getContainerSize() -{ - return size; +unsigned int SimpleContainer::getContainerSize() { return size; } + +int SimpleContainer::getName() { return name; } + +int SimpleContainer::getMaxStackSize() { + return Container::LARGE_MAX_STACK_SIZE; } -int SimpleContainer::getName() -{ - return name; -} - -int SimpleContainer::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; -} - -void SimpleContainer::setChanged() -{ - // 4J - removing this as we don't seem to have any implementation of a listener containerChanged function, and shared_from_this is proving tricky to add to containers +void SimpleContainer::setChanged() { + // 4J - removing this as we don't seem to have any implementation of a + // listener containerChanged function, and shared_from_this is proving + // tricky to add to containers #if 0 if (listeners != NULL) for (unsigned int i = 0; i < listeners->size(); i++) { @@ -104,7 +93,6 @@ void SimpleContainer::setChanged() #endif } -bool SimpleContainer::stillValid(std::shared_ptr player) -{ - return true; +bool SimpleContainer::stillValid(std::shared_ptr player) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Containers/SimpleContainer.h b/Minecraft.World/Containers/SimpleContainer.h index fd5af13e0..b13f08a9b 100644 --- a/Minecraft.World/Containers/SimpleContainer.h +++ b/Minecraft.World/Containers/SimpleContainer.h @@ -1,42 +1,39 @@ #pragma once - #include "Container.h" #include "../Headers/net.minecraft.world.ContainerListener.h" -class SimpleContainer : public Container -{ +class SimpleContainer : public Container { private: - int name; - int size; - ItemInstanceArray *items; - std::vector *listeners; + int name; + int size; + ItemInstanceArray* items; + std::vector* listeners; public: - SimpleContainer(int name, int size); + SimpleContainer(int name, int size); - void addListener(net_minecraft_world::ContainerListener *listener); + void addListener(net_minecraft_world::ContainerListener* listener); - void removeListener(net_minecraft_world::ContainerListener *listener); + void removeListener(net_minecraft_world::ContainerListener* listener); - std::shared_ptr getItem(unsigned int slot); + std::shared_ptr getItem(unsigned int slot); - std::shared_ptr removeItem(unsigned int slot, int count); - std::shared_ptr removeItemNoUpdate(int slot); + std::shared_ptr removeItem(unsigned int slot, int count); + std::shared_ptr removeItemNoUpdate(int slot); - void setItem(unsigned int slot, std::shared_ptr item); + void setItem(unsigned int slot, std::shared_ptr item); - unsigned int getContainerSize(); + unsigned int getContainerSize(); - int getName(); + int getName(); - int getMaxStackSize(); + int getMaxStackSize(); - void setChanged(); + void setChanged(); - bool stillValid(std::shared_ptr player); - - void startOpen() { } // TODO Auto-generated method stub - void stopOpen() { } // TODO Auto-generated method stub + bool stillValid(std::shared_ptr player); + void startOpen() {} // TODO Auto-generated method stub + void stopOpen() {} // TODO Auto-generated method stub }; \ No newline at end of file diff --git a/Minecraft.World/Containers/Slot.cpp b/Minecraft.World/Containers/Slot.cpp index 7a3db9171..fca1e6641 100644 --- a/Minecraft.World/Containers/Slot.cpp +++ b/Minecraft.World/Containers/Slot.cpp @@ -5,159 +5,128 @@ #include "../Headers/net.minecraft.world.item.crafting.h" #include "Slot.h" -Slot::Slot(std::shared_ptr container, int slot, int x, int y) : container( container ), slot( slot ) -{ - this->x = x; - this->y = y; +Slot::Slot(std::shared_ptr container, int slot, int x, int y) + : container(container), slot(slot) { + this->x = x; + this->y = y; - this->index = 0; + this->index = 0; } -void Slot::onQuickCraft(std::shared_ptr picked, std::shared_ptr original) -{ - if (picked == NULL || original == NULL) - { - return; - } - if (picked->id != original->id) - { - return; - } - int count = original->count - picked->count; - if (count > 0) - { - onQuickCraft(picked, count); - } +void Slot::onQuickCraft(std::shared_ptr picked, + std::shared_ptr original) { + if (picked == NULL || original == NULL) { + return; + } + if (picked->id != original->id) { + return; + } + int count = original->count - picked->count; + if (count > 0) { + onQuickCraft(picked, count); + } } +void Slot::onQuickCraft(std::shared_ptr picked, int count) {} -void Slot::onQuickCraft(std::shared_ptr picked, int count) -{ +void Slot::checkTakeAchievements(std::shared_ptr picked) {} + +void Slot::swap(Slot* other) { + std::shared_ptr item1 = container->getItem(slot); + std::shared_ptr item2 = + other->container->getItem(other->slot); + + if (item1 != NULL && item1->count > other->getMaxStackSize()) { + if (item2 != NULL) return; + item2 = item1->remove(item1->count - other->getMaxStackSize()); + } + if (item2 != NULL && item2->count > getMaxStackSize()) { + if (item1 != NULL) return; + item1 = item2->remove(item2->count - getMaxStackSize()); + } + other->container->setItem(other->slot, item1); + + container->setItem(slot, item2); + setChanged(); } -void Slot::checkTakeAchievements(std::shared_ptr picked) -{ +void Slot::onTake(std::shared_ptr player, + std::shared_ptr carried) { + setChanged(); } -void Slot::swap(Slot *other) -{ - std::shared_ptr item1 = container->getItem(slot); - std::shared_ptr item2 = other->container->getItem(other->slot); +bool Slot::mayPlace(std::shared_ptr item) { return true; } - if (item1 != NULL && item1->count > other->getMaxStackSize()) - { - if (item2 != NULL) return; - item2 = item1->remove(item1->count - other->getMaxStackSize()); - } - if (item2 != NULL && item2->count > getMaxStackSize()) - { - if (item1 != NULL) return; - item1 = item2->remove(item2->count - getMaxStackSize()); - } - other->container->setItem(other->slot, item1); - - container->setItem(slot, item2); - setChanged(); +std::shared_ptr Slot::getItem() { + return container->getItem(slot); } -void Slot::onTake(std::shared_ptr player, std::shared_ptr carried) -{ - setChanged(); +bool Slot::hasItem() { return getItem() != NULL; } + +void Slot::set(std::shared_ptr item) { + container->setItem(slot, item); + setChanged(); } -bool Slot::mayPlace(std::shared_ptr item) -{ - return true; +void Slot::setChanged() { container->setChanged(); } + +int Slot::getMaxStackSize() { return container->getMaxStackSize(); } + +Icon* Slot::getNoItemIcon() { return NULL; } + +std::shared_ptr Slot::remove(int c) { + return container->removeItem(slot, c); } -std::shared_ptr Slot::getItem() -{ - return container->getItem(slot); +bool Slot::isAt(std::shared_ptr c, int s) { + return c == container && s == slot; } -bool Slot::hasItem() -{ - return getItem() != NULL; +bool Slot::mayPickup(std::shared_ptr player) { return true; } + +bool Slot::mayCombine(std::shared_ptr second) { + std::shared_ptr first = getItem(); + + if (first == NULL || second == NULL) return false; + + ArmorItem* thisItem = dynamic_cast(first->getItem()); + if (thisItem) { + bool thisIsDyableArmor = + thisItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH; + bool itemIsDye = second->id == Item::dye_powder_Id; + return thisIsDyableArmor && itemIsDye; + } + // 4J Stu - This condition taken from Recipes::getItemFor to repair items, + // but added the damaged check to skip when the result is pointless + else if (first != NULL && second != NULL && first->id == second->id && + first->count == 1 && second->count == 1 && + Item::items[first->id]->canBeDepleted() && + (first->isDamaged() || second->isDamaged())) { + // 4J Stu - Don't allow combinining enchanted items, the enchantment + // will be lost. They can use the anvil for this + return !first->isEnchanted() && !second->isEnchanted(); + } + return false; } -void Slot::set(std::shared_ptr item) -{ - container->setItem(slot, item); - setChanged(); -} - -void Slot::setChanged() -{ - container->setChanged(); -} - -int Slot::getMaxStackSize() -{ - return container->getMaxStackSize(); -} - -Icon *Slot::getNoItemIcon() -{ - return NULL; -} - -std::shared_ptr Slot::remove(int c) -{ - return container->removeItem(slot, c); -} - -bool Slot::isAt(std::shared_ptr c, int s) -{ - return c == container && s == slot; -} - -bool Slot::mayPickup(std::shared_ptr player) -{ - return true; -} - -bool Slot::mayCombine(std::shared_ptr second) -{ - std::shared_ptr first = getItem(); - - if(first == NULL || second == NULL) return false; - - ArmorItem *thisItem = dynamic_cast(first->getItem()); - if(thisItem) - { - bool thisIsDyableArmor = thisItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH; - bool itemIsDye = second->id == Item::dye_powder_Id; - return thisIsDyableArmor && itemIsDye; - } - // 4J Stu - This condition taken from Recipes::getItemFor to repair items, but added the damaged check to skip when the result is pointless - else if (first != NULL && second != NULL && first->id == second->id && first->count == 1 && second->count == 1 && Item::items[first->id]->canBeDepleted() && (first->isDamaged() || second->isDamaged()) ) - { - // 4J Stu - Don't allow combinining enchanted items, the enchantment will be lost. They can use the anvil for this - return !first->isEnchanted() && !second->isEnchanted(); - } - return false; -} - -std::shared_ptr Slot::combine(std::shared_ptr item) -{ - std::shared_ptr result = nullptr; - std::shared_ptr first = getItem(); - - std::shared_ptr craftSlots = std::shared_ptr( new CraftingContainer(NULL, 2, 2) ); - craftSlots->setItem(0, item); - craftSlots->setItem(1, first); - - ArmorItem *thisItem = dynamic_cast(first->getItem()); - if(thisItem) - { - result = ArmorDyeRecipe::assembleDyedArmor(craftSlots); - } - else - { - result = Recipes::getInstance()->getItemFor(craftSlots, NULL); - } - - craftSlots->setItem(0, nullptr); - craftSlots->setItem(1, nullptr); - return result; +std::shared_ptr Slot::combine( + std::shared_ptr item) { + std::shared_ptr result = nullptr; + std::shared_ptr first = getItem(); + + std::shared_ptr craftSlots = + std::shared_ptr(new CraftingContainer(NULL, 2, 2)); + craftSlots->setItem(0, item); + craftSlots->setItem(1, first); + + ArmorItem* thisItem = dynamic_cast(first->getItem()); + if (thisItem) { + result = ArmorDyeRecipe::assembleDyedArmor(craftSlots); + } else { + result = Recipes::getInstance()->getItemFor(craftSlots, NULL); + } + + craftSlots->setItem(0, nullptr); + craftSlots->setItem(1, nullptr); + return result; } diff --git a/Minecraft.World/Containers/Slot.h b/Minecraft.World/Containers/Slot.h index 13827b5ad..e365217d8 100644 --- a/Minecraft.World/Containers/Slot.h +++ b/Minecraft.World/Containers/Slot.h @@ -2,40 +2,42 @@ class Container; -class Slot -{ +class Slot { private: - int slot; + int slot; public: - std::shared_ptr container; + std::shared_ptr container; public: - int index; - int x, y; + int index; + int x, y; - Slot(std::shared_ptr container, int slot, int x, int y); - virtual ~Slot() {} + Slot(std::shared_ptr container, int slot, int x, int y); + virtual ~Slot() {} - void onQuickCraft(std::shared_ptr picked, std::shared_ptr original); + void onQuickCraft(std::shared_ptr picked, + std::shared_ptr original); protected: - virtual void onQuickCraft(std::shared_ptr picked, int count); - virtual void checkTakeAchievements(std::shared_ptr picked); + virtual void onQuickCraft(std::shared_ptr picked, int count); + virtual void checkTakeAchievements(std::shared_ptr picked); public: - void swap(Slot *other); - virtual void onTake(std::shared_ptr player, std::shared_ptr carried); - virtual bool mayPlace(std::shared_ptr item); - virtual std::shared_ptr getItem(); - virtual bool hasItem(); - virtual void set(std::shared_ptr item); - virtual void setChanged(); - virtual int getMaxStackSize(); - virtual Icon *getNoItemIcon(); - virtual std::shared_ptr remove(int c); - virtual bool isAt(std::shared_ptr c, int s); - virtual bool mayPickup(std::shared_ptr player); - virtual bool mayCombine(std::shared_ptr item); // 4J Added - virtual std::shared_ptr combine(std::shared_ptr item); // 4J Added + void swap(Slot* other); + virtual void onTake(std::shared_ptr player, + std::shared_ptr carried); + virtual bool mayPlace(std::shared_ptr item); + virtual std::shared_ptr getItem(); + virtual bool hasItem(); + virtual void set(std::shared_ptr item); + virtual void setChanged(); + virtual int getMaxStackSize(); + virtual Icon* getNoItemIcon(); + virtual std::shared_ptr remove(int c); + virtual bool isAt(std::shared_ptr c, int s); + virtual bool mayPickup(std::shared_ptr player); + virtual bool mayCombine(std::shared_ptr item); // 4J Added + virtual std::shared_ptr combine( + std::shared_ptr item); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/Containers/TrapMenu.cpp b/Minecraft.World/Containers/TrapMenu.cpp index a1ea6d0ff..947a372e6 100644 --- a/Minecraft.World/Containers/TrapMenu.cpp +++ b/Minecraft.World/Containers/TrapMenu.cpp @@ -5,77 +5,61 @@ #include "Slot.h" #include "TrapMenu.h" -TrapMenu::TrapMenu(std::shared_ptr inventory, std::shared_ptr trap) -{ - this->trap = trap; +TrapMenu::TrapMenu(std::shared_ptr inventory, + std::shared_ptr trap) { + this->trap = trap; - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 3; x++) - { - addSlot(new Slot(trap, x + y * 3, 62 + x * 18, 17 + y * 18)); - } - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + addSlot(new Slot(trap, x + y * 3, 62 + x * 18, 17 + y * 18)); + } + } - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); - } - } - for (int x = 0; x < 9; x++) - { - addSlot(new Slot(inventory, x, 8 + x * 18, 70 + 4 * 18)); - } + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 9; x++) { + addSlot( + new Slot(inventory, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); + } + } + for (int x = 0; x < 9; x++) { + addSlot(new Slot(inventory, x, 8 + x * 18, 70 + 4 * 18)); + } } -bool TrapMenu::stillValid(std::shared_ptr player) -{ - return trap->stillValid(player); +bool TrapMenu::stillValid(std::shared_ptr player) { + return trap->stillValid(player); } // 4J Stu - Brought forward from 1.2 -std::shared_ptr TrapMenu::quickMoveStack(std::shared_ptr player, int slotIndex) -{ - std::shared_ptr clicked = nullptr; - Slot *slot = slots->at(slotIndex); - if (slot != NULL && slot->hasItem()) - { - std::shared_ptr stack = slot->getItem(); - clicked = stack->copy(); +std::shared_ptr TrapMenu::quickMoveStack( + std::shared_ptr player, int slotIndex) { + std::shared_ptr clicked = nullptr; + Slot* slot = slots->at(slotIndex); + if (slot != NULL && slot->hasItem()) { + std::shared_ptr stack = slot->getItem(); + clicked = stack->copy(); - if (slotIndex < INV_SLOT_START) - { - if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, true)) - { - return nullptr; - } - } - else - { - if (!moveItemStackTo(stack, 0, INV_SLOT_START, false)) - { - return nullptr; - } - } - if (stack->count == 0) - { - slot->set(nullptr); - } - else - { - slot->setChanged(); - } - if (stack->count == clicked->count) - { - // nothing moved - return nullptr; - } - else - { - slot->onTake(player, stack); - } - } - return clicked; + if (slotIndex < INV_SLOT_START) { + if (!moveItemStackTo(stack, INV_SLOT_START, USE_ROW_SLOT_END, + true)) { + return nullptr; + } + } else { + if (!moveItemStackTo(stack, 0, INV_SLOT_START, false)) { + return nullptr; + } + } + if (stack->count == 0) { + slot->set(nullptr); + } else { + slot->setChanged(); + } + if (stack->count == clicked->count) { + // nothing moved + return nullptr; + } else { + slot->onTake(player, stack); + } + } + return clicked; } \ No newline at end of file diff --git a/Minecraft.World/Containers/TrapMenu.h b/Minecraft.World/Containers/TrapMenu.h index 6e5cc5170..03b818380 100644 --- a/Minecraft.World/Containers/TrapMenu.h +++ b/Minecraft.World/Containers/TrapMenu.h @@ -4,19 +4,21 @@ class DispenserTileEntity; -class TrapMenu : public AbstractContainerMenu -{ +class TrapMenu : public AbstractContainerMenu { private: - static const int INV_SLOT_START = 9; - static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; - static const int USE_ROW_SLOT_START = INV_SLOT_END; - static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; + static const int INV_SLOT_START = 9; + static const int INV_SLOT_END = INV_SLOT_START + 9 * 3; + static const int USE_ROW_SLOT_START = INV_SLOT_END; + static const int USE_ROW_SLOT_END = USE_ROW_SLOT_START + 9; + private: - std::shared_ptr trap; + std::shared_ptr trap; public: - TrapMenu(std::shared_ptr inventory, std::shared_ptr trap); + TrapMenu(std::shared_ptr inventory, + std::shared_ptr trap); - virtual bool stillValid(std::shared_ptr player); - virtual std::shared_ptr quickMoveStack(std::shared_ptr player, int slotIndex); + virtual bool stillValid(std::shared_ptr player); + virtual std::shared_ptr quickMoveStack( + std::shared_ptr player, int slotIndex); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowDamageEnchantment.cpp b/Minecraft.World/Enchantments/ArrowDamageEnchantment.cpp index 75360c254..cde223b65 100644 --- a/Minecraft.World/Enchantments/ArrowDamageEnchantment.cpp +++ b/Minecraft.World/Enchantments/ArrowDamageEnchantment.cpp @@ -1,22 +1,17 @@ #include "../Platform/stdafx.h" #include "ArrowDamageEnchantment.h" -ArrowDamageEnchantment::ArrowDamageEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::bow) -{ - setDescriptionId(IDS_ENCHANTMENT_ARROW_DAMAGE); +ArrowDamageEnchantment::ArrowDamageEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::bow) { + setDescriptionId(IDS_ENCHANTMENT_ARROW_DAMAGE); } -int ArrowDamageEnchantment::getMinCost(int level) -{ - return 1 + (level - 1) * 10; +int ArrowDamageEnchantment::getMinCost(int level) { + return 1 + (level - 1) * 10; } -int ArrowDamageEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + 15; +int ArrowDamageEnchantment::getMaxCost(int level) { + return getMinCost(level) + 15; } -int ArrowDamageEnchantment::getMaxLevel() -{ - return 5; -} \ No newline at end of file +int ArrowDamageEnchantment::getMaxLevel() { return 5; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowDamageEnchantment.h b/Minecraft.World/Enchantments/ArrowDamageEnchantment.h index e5f1bb57d..fc5f77b2a 100644 --- a/Minecraft.World/Enchantments/ArrowDamageEnchantment.h +++ b/Minecraft.World/Enchantments/ArrowDamageEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class ArrowDamageEnchantment : public Enchantment -{ +class ArrowDamageEnchantment : public Enchantment { public: - ArrowDamageEnchantment(int id, int frequency); + ArrowDamageEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowFireEnchantment.cpp b/Minecraft.World/Enchantments/ArrowFireEnchantment.cpp index 74ab01425..d0e1208d7 100644 --- a/Minecraft.World/Enchantments/ArrowFireEnchantment.cpp +++ b/Minecraft.World/Enchantments/ArrowFireEnchantment.cpp @@ -1,22 +1,13 @@ #include "../Platform/stdafx.h" #include "ArrowFireEnchantment.h" -ArrowFireEnchantment::ArrowFireEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::bow) -{ - setDescriptionId(IDS_ENCHANTMENT_ARROW_FIRE); +ArrowFireEnchantment::ArrowFireEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::bow) { + setDescriptionId(IDS_ENCHANTMENT_ARROW_FIRE); } -int ArrowFireEnchantment::getMinCost(int level) -{ - return 20; -} +int ArrowFireEnchantment::getMinCost(int level) { return 20; } -int ArrowFireEnchantment::getMaxCost(int level) -{ - return 50; -} +int ArrowFireEnchantment::getMaxCost(int level) { return 50; } -int ArrowFireEnchantment::getMaxLevel() -{ - return 1; -} \ No newline at end of file +int ArrowFireEnchantment::getMaxLevel() { return 1; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowFireEnchantment.h b/Minecraft.World/Enchantments/ArrowFireEnchantment.h index 15d5ea11f..d251fecc8 100644 --- a/Minecraft.World/Enchantments/ArrowFireEnchantment.h +++ b/Minecraft.World/Enchantments/ArrowFireEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class ArrowFireEnchantment : public Enchantment -{ +class ArrowFireEnchantment : public Enchantment { public: - ArrowFireEnchantment(int id, int frequency); + ArrowFireEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.cpp b/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.cpp index 20f1e597f..29de1659a 100644 --- a/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.cpp +++ b/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.cpp @@ -1,22 +1,13 @@ #include "../Platform/stdafx.h" #include "ArrowInfiniteEnchantment.h" -ArrowInfiniteEnchantment::ArrowInfiniteEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::bow) -{ - setDescriptionId(IDS_ENCHANTMENT_ARROW_INFINITE); +ArrowInfiniteEnchantment::ArrowInfiniteEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::bow) { + setDescriptionId(IDS_ENCHANTMENT_ARROW_INFINITE); } -int ArrowInfiniteEnchantment::getMinCost(int level) -{ - return 20; -} +int ArrowInfiniteEnchantment::getMinCost(int level) { return 20; } -int ArrowInfiniteEnchantment::getMaxCost(int level) -{ - return 50; -} +int ArrowInfiniteEnchantment::getMaxCost(int level) { return 50; } -int ArrowInfiniteEnchantment::getMaxLevel() -{ - return 1; -} \ No newline at end of file +int ArrowInfiniteEnchantment::getMaxLevel() { return 1; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.h b/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.h index 906388fe7..a82591a60 100644 --- a/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.h +++ b/Minecraft.World/Enchantments/ArrowInfiniteEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class ArrowInfiniteEnchantment : public Enchantment -{ +class ArrowInfiniteEnchantment : public Enchantment { public: - ArrowInfiniteEnchantment(int id, int frequency); + ArrowInfiniteEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.cpp b/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.cpp index 17927bf93..a5d6cfcd9 100644 --- a/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.cpp +++ b/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.cpp @@ -1,22 +1,17 @@ #include "../Platform/stdafx.h" #include "ArrowKnockbackEnchantment.h" -ArrowKnockbackEnchantment::ArrowKnockbackEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::bow) -{ - setDescriptionId(IDS_ENCHANTMENT_ARROW_KNOCKBACK); +ArrowKnockbackEnchantment::ArrowKnockbackEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::bow) { + setDescriptionId(IDS_ENCHANTMENT_ARROW_KNOCKBACK); } -int ArrowKnockbackEnchantment::getMinCost(int level) -{ - return 12 + (level - 1) * 20; +int ArrowKnockbackEnchantment::getMinCost(int level) { + return 12 + (level - 1) * 20; } -int ArrowKnockbackEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + 25; +int ArrowKnockbackEnchantment::getMaxCost(int level) { + return getMinCost(level) + 25; } -int ArrowKnockbackEnchantment::getMaxLevel() -{ - return 2; -} \ No newline at end of file +int ArrowKnockbackEnchantment::getMaxLevel() { return 2; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.h b/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.h index ee42b9c33..09462e66b 100644 --- a/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.h +++ b/Minecraft.World/Enchantments/ArrowKnockbackEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class ArrowKnockbackEnchantment : public Enchantment -{ +class ArrowKnockbackEnchantment : public Enchantment { public: - ArrowKnockbackEnchantment(int id, int frequency); + ArrowKnockbackEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DamageEnchantment.cpp b/Minecraft.World/Enchantments/DamageEnchantment.cpp index f74b7fd5d..2d9ffaa35 100644 --- a/Minecraft.World/Enchantments/DamageEnchantment.cpp +++ b/Minecraft.World/Enchantments/DamageEnchantment.cpp @@ -3,60 +3,47 @@ #include "../Headers/net.minecraft.world.item.h" #include "DamageEnchantment.h" -const int DamageEnchantment::names[] = {IDS_ENCHANTMENT_DAMAGE_ALL, IDS_ENCHANTMENT_DAMAGE_UNDEAD, IDS_ENCHANTMENT_DAMAGE_ARTHROPODS}; +const int DamageEnchantment::names[] = {IDS_ENCHANTMENT_DAMAGE_ALL, + IDS_ENCHANTMENT_DAMAGE_UNDEAD, + IDS_ENCHANTMENT_DAMAGE_ARTHROPODS}; const int DamageEnchantment::minCost[] = {1, 5, 5}; const int DamageEnchantment::levelCost[] = {11, 8, 8}; const int DamageEnchantment::levelCostSpan[] = {20, 20, 20}; -DamageEnchantment::DamageEnchantment(int id, int frequency, int type) : Enchantment(id, frequency, EnchantmentCategory::weapon), type(type) -{ +DamageEnchantment::DamageEnchantment(int id, int frequency, int type) + : Enchantment(id, frequency, EnchantmentCategory::weapon), type(type) {} + +int DamageEnchantment::getMinCost(int level) { + return minCost[type] + (level - 1) * levelCost[type]; } -int DamageEnchantment::getMinCost(int level) -{ - return minCost[type] + (level - 1) * levelCost[type]; +int DamageEnchantment::getMaxCost(int level) { + return getMinCost(level) + levelCostSpan[type]; } -int DamageEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + levelCostSpan[type]; +int DamageEnchantment::getMaxLevel() { return 5; } + +int DamageEnchantment::getDamageBonus(int level, std::shared_ptr target) { + if (type == ALL) { + return Mth::floor(level * 2.75f); + } + if (type == UNDEAD && target->getMobType() == UNDEAD) { + return Mth::floor(level * 4.5f); + } + if (type == ARTHROPODS && target->getMobType() == ARTHROPOD) { + return Mth::floor(level * 4.5f); + } + return 0; } -int DamageEnchantment::getMaxLevel() -{ - return 5; +int DamageEnchantment::getDescriptionId() { return names[type]; } + +bool DamageEnchantment::isCompatibleWith(Enchantment* other) const { + return dynamic_cast(other) == NULL; } -int DamageEnchantment::getDamageBonus(int level, std::shared_ptr target) -{ - if (type == ALL) - { - return Mth::floor(level * 2.75f); - } - if (type == UNDEAD && target->getMobType() == UNDEAD) - { - return Mth::floor(level * 4.5f); - } - if (type == ARTHROPODS && target->getMobType() == ARTHROPOD) - { - return Mth::floor(level * 4.5f); - } - return 0; -} - -int DamageEnchantment::getDescriptionId() -{ - return names[type]; -} - -bool DamageEnchantment::isCompatibleWith(Enchantment *other) const -{ - return dynamic_cast(other) == NULL; -} - -bool DamageEnchantment::canEnchant(std::shared_ptr item) -{ - HatchetItem *hatchet = dynamic_cast(item->getItem()); - if (hatchet) return true; - return Enchantment::canEnchant(item); +bool DamageEnchantment::canEnchant(std::shared_ptr item) { + HatchetItem* hatchet = dynamic_cast(item->getItem()); + if (hatchet) return true; + return Enchantment::canEnchant(item); } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DamageEnchantment.h b/Minecraft.World/Enchantments/DamageEnchantment.h index 7d7a3fd93..71dcd4e5d 100644 --- a/Minecraft.World/Enchantments/DamageEnchantment.h +++ b/Minecraft.World/Enchantments/DamageEnchantment.h @@ -2,29 +2,28 @@ #include "Enchantment.h" -class DamageEnchantment : public Enchantment -{ +class DamageEnchantment : public Enchantment { public: - static const int ALL = 0; - static const int UNDEAD = 1; - static const int ARTHROPODS = 2; + static const int ALL = 0; + static const int UNDEAD = 1; + static const int ARTHROPODS = 2; private: - static const int names[]; - static const int minCost[]; - static const int levelCost[]; - static const int levelCostSpan[]; + static const int names[]; + static const int minCost[]; + static const int levelCost[]; + static const int levelCostSpan[]; public: - const int type; + const int type; - DamageEnchantment(int id, int frequency, int type); + DamageEnchantment(int id, int frequency, int type); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual int getDamageBonus(int level, std::shared_ptr target); - virtual int getDescriptionId(); - virtual bool isCompatibleWith(Enchantment *other) const; - virtual bool canEnchant(std::shared_ptr item); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual int getDamageBonus(int level, std::shared_ptr target); + virtual int getDescriptionId(); + virtual bool isCompatibleWith(Enchantment* other) const; + virtual bool canEnchant(std::shared_ptr item); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DigDurabilityEnchantment.cpp b/Minecraft.World/Enchantments/DigDurabilityEnchantment.cpp index b36eca66a..89bf00c5a 100644 --- a/Minecraft.World/Enchantments/DigDurabilityEnchantment.cpp +++ b/Minecraft.World/Enchantments/DigDurabilityEnchantment.cpp @@ -2,35 +2,29 @@ #include "../Headers/net.minecraft.world.item.h" #include "DigDurabilityEnchantment.h" -DigDurabilityEnchantment::DigDurabilityEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::digger) -{ - setDescriptionId(IDS_ENCHANTMENT_DURABILITY); +DigDurabilityEnchantment::DigDurabilityEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::digger) { + setDescriptionId(IDS_ENCHANTMENT_DURABILITY); } -int DigDurabilityEnchantment::getMinCost(int level) -{ - return 5 + (level - 1) * 8; +int DigDurabilityEnchantment::getMinCost(int level) { + return 5 + (level - 1) * 8; } -int DigDurabilityEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; +int DigDurabilityEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int DigDurabilityEnchantment::getMaxLevel() -{ - return 3; +int DigDurabilityEnchantment::getMaxLevel() { return 3; } + +bool DigDurabilityEnchantment::canEnchant(std::shared_ptr item) { + if (item->isDamageableItem()) return true; + return Enchantment::canEnchant(item); } -bool DigDurabilityEnchantment::canEnchant(std::shared_ptr item) -{ - if (item->isDamageableItem()) return true; - return Enchantment::canEnchant(item); -} - -bool DigDurabilityEnchantment::shouldIgnoreDurabilityDrop(std::shared_ptr item, int level, Random *random) -{ - ArmorItem *armor = dynamic_cast(item->getItem()); - if (armor && random->nextFloat() < 0.6f) return false; - return random->nextInt(level + 1) > 0; +bool DigDurabilityEnchantment::shouldIgnoreDurabilityDrop( + std::shared_ptr item, int level, Random* random) { + ArmorItem* armor = dynamic_cast(item->getItem()); + if (armor && random->nextFloat() < 0.6f) return false; + return random->nextInt(level + 1) > 0; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DigDurabilityEnchantment.h b/Minecraft.World/Enchantments/DigDurabilityEnchantment.h index 4751f3fe0..9cdadb5a4 100644 --- a/Minecraft.World/Enchantments/DigDurabilityEnchantment.h +++ b/Minecraft.World/Enchantments/DigDurabilityEnchantment.h @@ -2,14 +2,14 @@ #include "Enchantment.h" -class DigDurabilityEnchantment : public Enchantment -{ +class DigDurabilityEnchantment : public Enchantment { public: - DigDurabilityEnchantment(int id, int frequency); + DigDurabilityEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual bool canEnchant(std::shared_ptr item); - static bool shouldIgnoreDurabilityDrop(std::shared_ptr item, int level, Random *random); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual bool canEnchant(std::shared_ptr item); + static bool shouldIgnoreDurabilityDrop(std::shared_ptr item, + int level, Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DiggingEnchantment.cpp b/Minecraft.World/Enchantments/DiggingEnchantment.cpp index 341e7ebf5..dca6f603f 100644 --- a/Minecraft.World/Enchantments/DiggingEnchantment.cpp +++ b/Minecraft.World/Enchantments/DiggingEnchantment.cpp @@ -2,28 +2,20 @@ #include "../Headers/net.minecraft.world.item.h" #include "DiggingEnchantment.h" -DiggingEnchantment::DiggingEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::digger) -{ - setDescriptionId(IDS_ENCHANTMENT_DIGGING); +DiggingEnchantment::DiggingEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::digger) { + setDescriptionId(IDS_ENCHANTMENT_DIGGING); } -int DiggingEnchantment::getMinCost(int level) -{ - return 1 + 10 * (level - 1); +int DiggingEnchantment::getMinCost(int level) { return 1 + 10 * (level - 1); } + +int DiggingEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int DiggingEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; -} +int DiggingEnchantment::getMaxLevel() { return 5; } -int DiggingEnchantment::getMaxLevel() -{ - return 5; -} - -bool DiggingEnchantment::canEnchant(std::shared_ptr item) -{ - if (item->getItem()->id == Item::shears_Id) return true; - return Enchantment::canEnchant(item); +bool DiggingEnchantment::canEnchant(std::shared_ptr item) { + if (item->getItem()->id == Item::shears_Id) return true; + return Enchantment::canEnchant(item); } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/DiggingEnchantment.h b/Minecraft.World/Enchantments/DiggingEnchantment.h index 48b0fb0b5..c12c8cd8b 100644 --- a/Minecraft.World/Enchantments/DiggingEnchantment.h +++ b/Minecraft.World/Enchantments/DiggingEnchantment.h @@ -2,13 +2,12 @@ #include "Enchantment.h" -class DiggingEnchantment : public Enchantment -{ +class DiggingEnchantment : public Enchantment { public: - DiggingEnchantment(int id, int frequency); + DiggingEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual bool canEnchant(std::shared_ptr item); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual bool canEnchant(std::shared_ptr item); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/Enchantment.cpp b/Minecraft.World/Enchantments/Enchantment.cpp index 56d1426b1..4400e46dc 100644 --- a/Minecraft.World/Enchantments/Enchantment.cpp +++ b/Minecraft.World/Enchantments/Enchantment.cpp @@ -2,201 +2,183 @@ #include "../Headers/net.minecraft.world.item.enchantment.h" #include "Enchantment.h" -//Enchantment *Enchantment::enchantments[256]; -EnchantmentArray Enchantment::enchantments = EnchantmentArray( 256 ); -std::vector Enchantment::validEnchantments; +// Enchantment *Enchantment::enchantments[256]; +EnchantmentArray Enchantment::enchantments = EnchantmentArray(256); +std::vector Enchantment::validEnchantments; -Enchantment *Enchantment::allDamageProtection = NULL; -Enchantment *Enchantment::fireProtection = NULL; -Enchantment *Enchantment::fallProtection = NULL; -Enchantment *Enchantment::explosionProtection = NULL; -Enchantment *Enchantment::projectileProtection = NULL; -Enchantment *Enchantment::drownProtection = NULL; -Enchantment *Enchantment::waterWorker = NULL; -Enchantment *Enchantment::thorns = NULL; +Enchantment* Enchantment::allDamageProtection = NULL; +Enchantment* Enchantment::fireProtection = NULL; +Enchantment* Enchantment::fallProtection = NULL; +Enchantment* Enchantment::explosionProtection = NULL; +Enchantment* Enchantment::projectileProtection = NULL; +Enchantment* Enchantment::drownProtection = NULL; +Enchantment* Enchantment::waterWorker = NULL; +Enchantment* Enchantment::thorns = NULL; // weapon -Enchantment *Enchantment::damageBonus = NULL; -Enchantment *Enchantment::damageBonusUndead = NULL; -Enchantment *Enchantment::damageBonusArthropods = NULL; -Enchantment *Enchantment::knockback = NULL; -Enchantment *Enchantment::fireAspect = NULL; -Enchantment *Enchantment::lootBonus = NULL; +Enchantment* Enchantment::damageBonus = NULL; +Enchantment* Enchantment::damageBonusUndead = NULL; +Enchantment* Enchantment::damageBonusArthropods = NULL; +Enchantment* Enchantment::knockback = NULL; +Enchantment* Enchantment::fireAspect = NULL; +Enchantment* Enchantment::lootBonus = NULL; // digger -Enchantment *Enchantment::diggingBonus = NULL; -Enchantment *Enchantment::untouching = NULL; -Enchantment *Enchantment::digDurability = NULL; -Enchantment *Enchantment::resourceBonus = NULL; +Enchantment* Enchantment::diggingBonus = NULL; +Enchantment* Enchantment::untouching = NULL; +Enchantment* Enchantment::digDurability = NULL; +Enchantment* Enchantment::resourceBonus = NULL; // bows -Enchantment *Enchantment::arrowBonus = NULL; -Enchantment *Enchantment::arrowKnockback = NULL; -Enchantment *Enchantment::arrowFire = NULL; -Enchantment *Enchantment::arrowInfinite = NULL; +Enchantment* Enchantment::arrowBonus = NULL; +Enchantment* Enchantment::arrowKnockback = NULL; +Enchantment* Enchantment::arrowFire = NULL; +Enchantment* Enchantment::arrowInfinite = NULL; -void Enchantment::staticCtor() -{ - allDamageProtection = new ProtectionEnchantment(0, FREQ_COMMON, ProtectionEnchantment::ALL); - fireProtection = new ProtectionEnchantment(1, FREQ_UNCOMMON, ProtectionEnchantment::FIRE); - fallProtection = new ProtectionEnchantment(2, FREQ_UNCOMMON, ProtectionEnchantment::FALL); - explosionProtection = new ProtectionEnchantment(3, FREQ_RARE, ProtectionEnchantment::EXPLOSION); - projectileProtection = new ProtectionEnchantment(4, FREQ_UNCOMMON, ProtectionEnchantment::PROJECTILE); - drownProtection = new OxygenEnchantment(5, FREQ_RARE); - waterWorker = new WaterWorkerEnchantment(6, FREQ_RARE); - thorns = new ThornsEnchantment(7, FREQ_VERY_RARE); +void Enchantment::staticCtor() { + allDamageProtection = + new ProtectionEnchantment(0, FREQ_COMMON, ProtectionEnchantment::ALL); + fireProtection = new ProtectionEnchantment(1, FREQ_UNCOMMON, + ProtectionEnchantment::FIRE); + fallProtection = new ProtectionEnchantment(2, FREQ_UNCOMMON, + ProtectionEnchantment::FALL); + explosionProtection = new ProtectionEnchantment( + 3, FREQ_RARE, ProtectionEnchantment::EXPLOSION); + projectileProtection = new ProtectionEnchantment( + 4, FREQ_UNCOMMON, ProtectionEnchantment::PROJECTILE); + drownProtection = new OxygenEnchantment(5, FREQ_RARE); + waterWorker = new WaterWorkerEnchantment(6, FREQ_RARE); + thorns = new ThornsEnchantment(7, FREQ_VERY_RARE); - // weapon - damageBonus = new DamageEnchantment(16, FREQ_COMMON, DamageEnchantment::ALL); - damageBonusUndead = new DamageEnchantment(17, FREQ_UNCOMMON, DamageEnchantment::UNDEAD); - damageBonusArthropods = new DamageEnchantment(18, FREQ_UNCOMMON, DamageEnchantment::ARTHROPODS); - knockback = new KnockbackEnchantment(19, FREQ_UNCOMMON); - fireAspect = new FireAspectEnchantment(20, FREQ_RARE); - lootBonus = new LootBonusEnchantment(21, FREQ_RARE, EnchantmentCategory::weapon); + // weapon + damageBonus = + new DamageEnchantment(16, FREQ_COMMON, DamageEnchantment::ALL); + damageBonusUndead = + new DamageEnchantment(17, FREQ_UNCOMMON, DamageEnchantment::UNDEAD); + damageBonusArthropods = + new DamageEnchantment(18, FREQ_UNCOMMON, DamageEnchantment::ARTHROPODS); + knockback = new KnockbackEnchantment(19, FREQ_UNCOMMON); + fireAspect = new FireAspectEnchantment(20, FREQ_RARE); + lootBonus = + new LootBonusEnchantment(21, FREQ_RARE, EnchantmentCategory::weapon); - // digger - diggingBonus = new DiggingEnchantment(32, FREQ_COMMON); - untouching = new UntouchingEnchantment(33, FREQ_VERY_RARE); - digDurability = new DigDurabilityEnchantment(34, FREQ_UNCOMMON); - resourceBonus = new LootBonusEnchantment(35, FREQ_RARE, EnchantmentCategory::digger); + // digger + diggingBonus = new DiggingEnchantment(32, FREQ_COMMON); + untouching = new UntouchingEnchantment(33, FREQ_VERY_RARE); + digDurability = new DigDurabilityEnchantment(34, FREQ_UNCOMMON); + resourceBonus = + new LootBonusEnchantment(35, FREQ_RARE, EnchantmentCategory::digger); - // bows - arrowBonus = new ArrowDamageEnchantment(48, FREQ_COMMON); - arrowKnockback = new ArrowKnockbackEnchantment(49, FREQ_RARE); - arrowFire = new ArrowFireEnchantment(50, FREQ_RARE); - arrowInfinite = new ArrowInfiniteEnchantment(51, FREQ_VERY_RARE); + // bows + arrowBonus = new ArrowDamageEnchantment(48, FREQ_COMMON); + arrowKnockback = new ArrowKnockbackEnchantment(49, FREQ_RARE); + arrowFire = new ArrowFireEnchantment(50, FREQ_RARE); + arrowInfinite = new ArrowInfiniteEnchantment(51, FREQ_VERY_RARE); - for(unsigned int i = 0; i < 256; ++i) - { - Enchantment *enchantment = enchantments[i]; - if (enchantment != NULL) - { - validEnchantments.push_back(enchantment); - } - } + for (unsigned int i = 0; i < 256; ++i) { + Enchantment* enchantment = enchantments[i]; + if (enchantment != NULL) { + validEnchantments.push_back(enchantment); + } + } } -void Enchantment::_init(int id) -{ - if (enchantments[id] != NULL) - { - app.DebugPrintf("Duplicate enchantment id!"); +void Enchantment::_init(int id) { + if (enchantments[id] != NULL) { + app.DebugPrintf("Duplicate enchantment id!"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //throw new IllegalArgumentException("Duplicate enchantment id!"); - } - enchantments[id] = this; + // throw new IllegalArgumentException("Duplicate enchantment id!"); + } + enchantments[id] = this; } -Enchantment::Enchantment(int id, int frequency, const EnchantmentCategory *category) : id(id), frequency(frequency), category(category) -{ - _init(id); +Enchantment::Enchantment(int id, int frequency, + const EnchantmentCategory* category) + : id(id), frequency(frequency), category(category) { + _init(id); } -Enchantment::Enchantment(int id) : id(id), frequency(FREQ_COMMON), category(EnchantmentCategory::all) -{ - _init(id); +Enchantment::Enchantment(int id) + : id(id), frequency(FREQ_COMMON), category(EnchantmentCategory::all) { + _init(id); } -int Enchantment::getFrequency() -{ - return frequency; +int Enchantment::getFrequency() { return frequency; } + +int Enchantment::getMinLevel() { return 1; } + +int Enchantment::getMaxLevel() { return 1; } + +int Enchantment::getMinCost(int level) { return 1 + level * 10; } + +int Enchantment::getMaxCost(int level) { return getMinCost(level) + 5; } + +int Enchantment::getDamageProtection(int level, DamageSource* source) { + return 0; } -int Enchantment::getMinLevel() -{ - return 1; +int Enchantment::getDamageBonus(int level, std::shared_ptr target) { + return 0; } -int Enchantment::getMaxLevel() -{ - return 1; +bool Enchantment::isCompatibleWith(Enchantment* other) const { + return this != other; } -int Enchantment::getMinCost(int level) -{ - return 1 + level * 10; +Enchantment* Enchantment::setDescriptionId(int id) { + descriptionId = id; + return this; } -int Enchantment::getMaxCost(int level) -{ - return getMinCost(level) + 5; +int Enchantment::getDescriptionId() { return descriptionId; } + +std::wstring Enchantment::getFullname(int level, std::wstring& unformatted) { + wchar_t formatted[256]; + swprintf(formatted, 256, L"%ls %ls", app.GetString(getDescriptionId()), + getLevelString(level).c_str()); + unformatted = formatted; + swprintf(formatted, 256, L"%ls", + app.GetHTMLColour(eHTMLColor_f), unformatted.c_str()); + return formatted; } -int Enchantment::getDamageProtection(int level, DamageSource *source) -{ - return 0; -} - -int Enchantment::getDamageBonus(int level, std::shared_ptr target) -{ - return 0; -} - -bool Enchantment::isCompatibleWith(Enchantment *other) const -{ - return this != other; -} - -Enchantment *Enchantment::setDescriptionId(int id) -{ - descriptionId = id; - return this; -} - -int Enchantment::getDescriptionId() -{ - return descriptionId; -} - -std::wstring Enchantment::getFullname(int level,std::wstring &unformatted) -{ - wchar_t formatted[256]; - swprintf(formatted,256,L"%ls %ls",app.GetString( getDescriptionId() ), getLevelString(level).c_str()); - unformatted = formatted; - swprintf(formatted,256,L"%ls",app.GetHTMLColour(eHTMLColor_f),unformatted.c_str()); - return formatted; -} - -bool Enchantment::canEnchant(std::shared_ptr item) -{ - return category->canEnchant(item->getItem()); +bool Enchantment::canEnchant(std::shared_ptr item) { + return category->canEnchant(item->getItem()); } // 4J Added -std::wstring Enchantment::getLevelString(int level) -{ - int stringId = IDS_ENCHANTMENT_LEVEL_1; - switch(level) - { - case 2: - stringId = IDS_ENCHANTMENT_LEVEL_2; - break; - case 3: - stringId = IDS_ENCHANTMENT_LEVEL_3; - break; - case 4: - stringId = IDS_ENCHANTMENT_LEVEL_4; - break; - case 5: - stringId = IDS_ENCHANTMENT_LEVEL_5; - break; - case 6: - stringId = IDS_ENCHANTMENT_LEVEL_6; - break; - case 7: - stringId = IDS_ENCHANTMENT_LEVEL_7; - break; - case 8: - stringId = IDS_ENCHANTMENT_LEVEL_8; - break; - case 9: - stringId = IDS_ENCHANTMENT_LEVEL_9; - break; - case 10: - stringId = IDS_ENCHANTMENT_LEVEL_10; - break; - }; - return app.GetString(stringId); //I18n.get("enchantment.level." + level); +std::wstring Enchantment::getLevelString(int level) { + int stringId = IDS_ENCHANTMENT_LEVEL_1; + switch (level) { + case 2: + stringId = IDS_ENCHANTMENT_LEVEL_2; + break; + case 3: + stringId = IDS_ENCHANTMENT_LEVEL_3; + break; + case 4: + stringId = IDS_ENCHANTMENT_LEVEL_4; + break; + case 5: + stringId = IDS_ENCHANTMENT_LEVEL_5; + break; + case 6: + stringId = IDS_ENCHANTMENT_LEVEL_6; + break; + case 7: + stringId = IDS_ENCHANTMENT_LEVEL_7; + break; + case 8: + stringId = IDS_ENCHANTMENT_LEVEL_8; + break; + case 9: + stringId = IDS_ENCHANTMENT_LEVEL_9; + break; + case 10: + stringId = IDS_ENCHANTMENT_LEVEL_10; + break; + }; + return app.GetString(stringId); // I18n.get("enchantment.level." + level); } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/Enchantment.h b/Minecraft.World/Enchantments/Enchantment.h index 2b909a869..f6149b3b8 100644 --- a/Minecraft.World/Enchantments/Enchantment.h +++ b/Minecraft.World/Enchantments/Enchantment.h @@ -5,83 +5,84 @@ class DamageSource; class Mob; -class Enchantment //implements Descriptive { +class Enchantment // implements Descriptive { { -public : - //static Enchantment *enchantments[256]; - static EnchantmentArray enchantments; - static std::vector validEnchantments; +public: + // static Enchantment *enchantments[256]; + static EnchantmentArray enchantments; + static std::vector validEnchantments; - static const int FREQ_COMMON = 10; - static const int FREQ_UNCOMMON = 5; - static const int FREQ_RARE = 2; - static const int FREQ_VERY_RARE = 1; + static const int FREQ_COMMON = 10; + static const int FREQ_UNCOMMON = 5; + static const int FREQ_RARE = 2; + static const int FREQ_VERY_RARE = 1; - // armor - static Enchantment *allDamageProtection; - static Enchantment *fireProtection; - static Enchantment *fallProtection; - static Enchantment *explosionProtection; - static Enchantment *projectileProtection; - static Enchantment *drownProtection; - static Enchantment *waterWorker; - static Enchantment *thorns; + // armor + static Enchantment* allDamageProtection; + static Enchantment* fireProtection; + static Enchantment* fallProtection; + static Enchantment* explosionProtection; + static Enchantment* projectileProtection; + static Enchantment* drownProtection; + static Enchantment* waterWorker; + static Enchantment* thorns; - // weapon - static Enchantment *damageBonus; - static Enchantment *damageBonusUndead; - static Enchantment *damageBonusArthropods; - static Enchantment *knockback; - static Enchantment *fireAspect; - static Enchantment *lootBonus; + // weapon + static Enchantment* damageBonus; + static Enchantment* damageBonusUndead; + static Enchantment* damageBonusArthropods; + static Enchantment* knockback; + static Enchantment* fireAspect; + static Enchantment* lootBonus; - // digger - static Enchantment *diggingBonus; - static Enchantment *untouching; - static Enchantment *digDurability; - static Enchantment *resourceBonus; + // digger + static Enchantment* diggingBonus; + static Enchantment* untouching; + static Enchantment* digDurability; + static Enchantment* resourceBonus; - // bows - static Enchantment *arrowBonus; - static Enchantment *arrowKnockback; - static Enchantment *arrowFire; - static Enchantment *arrowInfinite; + // bows + static Enchantment* arrowBonus; + static Enchantment* arrowKnockback; + static Enchantment* arrowFire; + static Enchantment* arrowInfinite; - const int id; + const int id; - static void staticCtor(); + static void staticCtor(); private: - const int frequency; + const int frequency; public: - const EnchantmentCategory *category; + const EnchantmentCategory* category; protected: - int descriptionId; + int descriptionId; private: - void _init(int id); + void _init(int id); protected: - Enchantment(int id, int frequency, const EnchantmentCategory *category); - Enchantment(int id); + Enchantment(int id, int frequency, const EnchantmentCategory* category); + Enchantment(int id); public: - virtual int getFrequency(); - virtual int getMinLevel(); - virtual int getMaxLevel(); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getDamageProtection(int level, DamageSource *source); - virtual int getDamageBonus(int level, std::shared_ptr target); - virtual bool isCompatibleWith(Enchantment *other) const; - virtual Enchantment *setDescriptionId(int id); - virtual int getDescriptionId(); - virtual std::wstring getFullname(int level,std::wstring &unformatted); // 4J Stu added unformatted - virtual bool canEnchant(std::shared_ptr item); + virtual int getFrequency(); + virtual int getMinLevel(); + virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getDamageProtection(int level, DamageSource* source); + virtual int getDamageBonus(int level, std::shared_ptr target); + virtual bool isCompatibleWith(Enchantment* other) const; + virtual Enchantment* setDescriptionId(int id); + virtual int getDescriptionId(); + virtual std::wstring getFullname( + int level, std::wstring& unformatted); // 4J Stu added unformatted + virtual bool canEnchant(std::shared_ptr item); private: - // 4J Added - std::wstring getLevelString(int level); + // 4J Added + std::wstring getLevelString(int level); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentCategory.cpp b/Minecraft.World/Enchantments/EnchantmentCategory.cpp index 1f79ff3e1..41657390c 100644 --- a/Minecraft.World/Enchantments/EnchantmentCategory.cpp +++ b/Minecraft.World/Enchantments/EnchantmentCategory.cpp @@ -2,41 +2,40 @@ #include "../Headers/net.minecraft.world.item.h" #include "EnchantmentCategory.h" -const EnchantmentCategory *EnchantmentCategory::all = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::armor = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::armor_feet = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::armor_legs = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::armor_torso = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::armor_head = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::weapon = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::digger = new EnchantmentCategory(); -const EnchantmentCategory *EnchantmentCategory::bow = new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::all = new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::armor = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::armor_feet = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::armor_legs = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::armor_torso = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::armor_head = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::weapon = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::digger = + new EnchantmentCategory(); +const EnchantmentCategory* EnchantmentCategory::bow = new EnchantmentCategory(); -bool EnchantmentCategory::canEnchant(Item *item) const -{ - if (this == all) return true; +bool EnchantmentCategory::canEnchant(Item* item) const { + if (this == all) return true; - if (dynamic_cast( item ) != NULL) - { - if (this == armor) return true; - ArmorItem *ai = (ArmorItem *) item; - if (ai->slot == ArmorItem::SLOT_HEAD) return this == armor_head; - if (ai->slot == ArmorItem::SLOT_LEGS) return this == armor_legs; - if (ai->slot == ArmorItem::SLOT_TORSO) return this == armor_torso; - if (ai->slot == ArmorItem::SLOT_FEET) return this == armor_feet; - return false; - } - else if (dynamic_cast(item) != NULL) - { - return this == weapon; - } - else if (dynamic_cast(item) != NULL) - { - return this == digger; - } - else if (dynamic_cast(item) != NULL) - { - return this == bow; - } - return false; + if (dynamic_cast(item) != NULL) { + if (this == armor) return true; + ArmorItem* ai = (ArmorItem*)item; + if (ai->slot == ArmorItem::SLOT_HEAD) return this == armor_head; + if (ai->slot == ArmorItem::SLOT_LEGS) return this == armor_legs; + if (ai->slot == ArmorItem::SLOT_TORSO) return this == armor_torso; + if (ai->slot == ArmorItem::SLOT_FEET) return this == armor_feet; + return false; + } else if (dynamic_cast(item) != NULL) { + return this == weapon; + } else if (dynamic_cast(item) != NULL) { + return this == digger; + } else if (dynamic_cast(item) != NULL) { + return this == bow; + } + return false; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentCategory.h b/Minecraft.World/Enchantments/EnchantmentCategory.h index b5976307b..0428533bc 100644 --- a/Minecraft.World/Enchantments/EnchantmentCategory.h +++ b/Minecraft.World/Enchantments/EnchantmentCategory.h @@ -2,18 +2,17 @@ class Item; -class EnchantmentCategory -{ +class EnchantmentCategory { public: - static const EnchantmentCategory *all; - static const EnchantmentCategory *armor; - static const EnchantmentCategory *armor_feet; - static const EnchantmentCategory *armor_legs; - static const EnchantmentCategory *armor_torso; - static const EnchantmentCategory *armor_head; - static const EnchantmentCategory *weapon; - static const EnchantmentCategory *digger; - static const EnchantmentCategory *bow; + static const EnchantmentCategory* all; + static const EnchantmentCategory* armor; + static const EnchantmentCategory* armor_feet; + static const EnchantmentCategory* armor_legs; + static const EnchantmentCategory* armor_torso; + static const EnchantmentCategory* armor_head; + static const EnchantmentCategory* weapon; + static const EnchantmentCategory* digger; + static const EnchantmentCategory* bow; - bool canEnchant(Item *item) const; + bool canEnchant(Item* item) const; }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentHelper.cpp b/Minecraft.World/Enchantments/EnchantmentHelper.cpp index ab276723e..ee20e962c 100644 --- a/Minecraft.World/Enchantments/EnchantmentHelper.cpp +++ b/Minecraft.World/Enchantments/EnchantmentHelper.cpp @@ -9,469 +9,460 @@ Random EnchantmentHelper::random; -int EnchantmentHelper::getEnchantmentLevel(int enchantmentId, std::shared_ptr piece) -{ - if (piece == NULL) - { - return 0; - } - ListTag *enchantmentTags = piece->getEnchantmentTags(); - if (enchantmentTags == NULL) - { - return 0; - } - for (int i = 0; i < enchantmentTags->size(); i++) - { - int type = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - int level = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL); +int EnchantmentHelper::getEnchantmentLevel( + int enchantmentId, std::shared_ptr piece) { + if (piece == NULL) { + return 0; + } + ListTag* enchantmentTags = piece->getEnchantmentTags(); + if (enchantmentTags == NULL) { + return 0; + } + for (int i = 0; i < enchantmentTags->size(); i++) { + int type = enchantmentTags->get(i)->getShort( + (wchar_t*)ItemInstance::TAG_ENCH_ID); + int level = enchantmentTags->get(i)->getShort( + (wchar_t*)ItemInstance::TAG_ENCH_LEVEL); - if (type == enchantmentId) - { - return level; - } - } - return 0; + if (type == enchantmentId) { + return level; + } + } + return 0; } -std::unordered_map *EnchantmentHelper::getEnchantments(std::shared_ptr item) -{ - std::unordered_map *result = new std::unordered_map(); - ListTag *list = item->id == Item::enchantedBook_Id ? Item::enchantedBook->getEnchantments(item) : item->getEnchantmentTags(); +std::unordered_map* EnchantmentHelper::getEnchantments( + std::shared_ptr item) { + std::unordered_map* result = new std::unordered_map(); + ListTag* list = + item->id == Item::enchantedBook_Id + ? Item::enchantedBook->getEnchantments(item) + : item->getEnchantmentTags(); - if (list != NULL) - { - for (int i = 0; i < list->size(); i++) - { - int type = list->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - int level = list->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL); + if (list != NULL) { + for (int i = 0; i < list->size(); i++) { + int type = + list->get(i)->getShort((wchar_t*)ItemInstance::TAG_ENCH_ID); + int level = + list->get(i)->getShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL); - result->insert( std::unordered_map::value_type(type, level)); - } - } + result->insert( + std::unordered_map::value_type(type, level)); + } + } - return result; + return result; } -void EnchantmentHelper::setEnchantments(std::unordered_map *enchantments, std::shared_ptr item) -{ - ListTag *list = new ListTag(); +void EnchantmentHelper::setEnchantments( + std::unordered_map* enchantments, + std::shared_ptr item) { + ListTag* list = new ListTag(); - //for (int id : enchantments.keySet()) - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) - { - int id = it->first; - CompoundTag *tag = new CompoundTag(); + // for (int id : enchantments.keySet()) + for (AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) { + int id = it->first; + CompoundTag* tag = new CompoundTag(); - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_ID, (short) id); - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short)(int)it->second); + tag->putShort((wchar_t*)ItemInstance::TAG_ENCH_ID, (short)id); + tag->putShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL, + (short)(int)it->second); - list->add(tag); + list->add(tag); - if (item->id == Item::enchantedBook_Id) - { - Item::enchantedBook->addEnchantment(item, new EnchantmentInstance(id, it->second)); - } - } + if (item->id == Item::enchantedBook_Id) { + Item::enchantedBook->addEnchantment( + item, new EnchantmentInstance(id, it->second)); + } + } - if (list->size() > 0) - { - if (item->id != Item::enchantedBook_Id) - { - item->addTagElement(L"ench", list); - } - } - else if (item->hasTag()) - { - item->getTag()->remove(L"ench"); - } + if (list->size() > 0) { + if (item->id != Item::enchantedBook_Id) { + item->addTagElement(L"ench", list); + } + } else if (item->hasTag()) { + item->getTag()->remove(L"ench"); + } } -int EnchantmentHelper::getEnchantmentLevel(int enchantmentId, ItemInstanceArray inventory) -{ - int bestLevel = 0; - //for (ItemInstance piece : inventory) - for(unsigned int i = 0; i < inventory.length; ++i) - { - int newLevel = getEnchantmentLevel(enchantmentId, inventory[i]); - if (newLevel > bestLevel) - { - bestLevel = newLevel; - } - } - return bestLevel; +int EnchantmentHelper::getEnchantmentLevel(int enchantmentId, + ItemInstanceArray inventory) { + int bestLevel = 0; + // for (ItemInstance piece : inventory) + for (unsigned int i = 0; i < inventory.length; ++i) { + int newLevel = getEnchantmentLevel(enchantmentId, inventory[i]); + if (newLevel > bestLevel) { + bestLevel = newLevel; + } + } + return bestLevel; } -void EnchantmentHelper::runIterationOnItem(EnchantmentIterationMethod &method, std::shared_ptr piece) -{ - if (piece == NULL) - { - return; - } - ListTag *enchantmentTags = piece->getEnchantmentTags(); - if (enchantmentTags == NULL) - { - return; - } - for (int i = 0; i < enchantmentTags->size(); i++) - { - int type = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - int level = enchantmentTags->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL); +void EnchantmentHelper::runIterationOnItem( + EnchantmentIterationMethod& method, std::shared_ptr piece) { + if (piece == NULL) { + return; + } + ListTag* enchantmentTags = piece->getEnchantmentTags(); + if (enchantmentTags == NULL) { + return; + } + for (int i = 0; i < enchantmentTags->size(); i++) { + int type = enchantmentTags->get(i)->getShort( + (wchar_t*)ItemInstance::TAG_ENCH_ID); + int level = enchantmentTags->get(i)->getShort( + (wchar_t*)ItemInstance::TAG_ENCH_LEVEL); - if (Enchantment::enchantments[type] != NULL) - { - method.doEnchantment(Enchantment::enchantments[type], level); - } - } + if (Enchantment::enchantments[type] != NULL) { + method.doEnchantment(Enchantment::enchantments[type], level); + } + } } -void EnchantmentHelper::runIterationOnInventory(EnchantmentIterationMethod &method, ItemInstanceArray inventory) -{ - //for (ItemInstance piece : inventory) - for(unsigned int i = 0; i < inventory.length; ++i) - { - runIterationOnItem(method, inventory[i]); - } +void EnchantmentHelper::runIterationOnInventory( + EnchantmentIterationMethod& method, ItemInstanceArray inventory) { + // for (ItemInstance piece : inventory) + for (unsigned int i = 0; i < inventory.length; ++i) { + runIterationOnItem(method, inventory[i]); + } } -void EnchantmentHelper::GetDamageProtectionIteration::doEnchantment(Enchantment *enchantment, int level) -{ - sum += enchantment->getDamageProtection(level, source); +void EnchantmentHelper::GetDamageProtectionIteration::doEnchantment( + Enchantment* enchantment, int level) { + sum += enchantment->getDamageProtection(level, source); } -EnchantmentHelper::GetDamageProtectionIteration EnchantmentHelper::getDamageProtectionIteration; +EnchantmentHelper::GetDamageProtectionIteration + EnchantmentHelper::getDamageProtectionIteration; /** -* Fetches the protection value for enchanted items. -* -* @param inventory -* @param source -* @return -*/ -int EnchantmentHelper::getDamageProtection(std::shared_ptr inventory, DamageSource *source) -{ - getDamageProtectionIteration.sum = 0; - getDamageProtectionIteration.source = source; + * Fetches the protection value for enchanted items. + * + * @param inventory + * @param source + * @return + */ +int EnchantmentHelper::getDamageProtection(std::shared_ptr inventory, + DamageSource* source) { + getDamageProtectionIteration.sum = 0; + getDamageProtectionIteration.source = source; - runIterationOnInventory(getDamageProtectionIteration, inventory->armor); + runIterationOnInventory(getDamageProtectionIteration, inventory->armor); - if (getDamageProtectionIteration.sum > 25) - { - getDamageProtectionIteration.sum = 25; - } - // enchantment protection is on the scale of 0 to 25, where 20 or more - // will nullify nearly all damage (there will be damage spill) - return ((getDamageProtectionIteration.sum + 1) >> 1) + random.nextInt((getDamageProtectionIteration.sum >> 1) + 1); + if (getDamageProtectionIteration.sum > 25) { + getDamageProtectionIteration.sum = 25; + } + // enchantment protection is on the scale of 0 to 25, where 20 or more + // will nullify nearly all damage (there will be damage spill) + return ((getDamageProtectionIteration.sum + 1) >> 1) + + random.nextInt((getDamageProtectionIteration.sum >> 1) + 1); } -void EnchantmentHelper::GetDamageBonusIteration::doEnchantment(Enchantment *enchantment, int level) -{ - sum += enchantment->getDamageBonus(level, target); +void EnchantmentHelper::GetDamageBonusIteration::doEnchantment( + Enchantment* enchantment, int level) { + sum += enchantment->getDamageBonus(level, target); } - -EnchantmentHelper::GetDamageBonusIteration EnchantmentHelper::getDamageBonusIteration; +EnchantmentHelper::GetDamageBonusIteration + EnchantmentHelper::getDamageBonusIteration; /** -* -* @param inventory -* @param target -* @return -*/ -int EnchantmentHelper::getDamageBonus(std::shared_ptr inventory, std::shared_ptr target) -{ + * + * @param inventory + * @param target + * @return + */ +int EnchantmentHelper::getDamageBonus(std::shared_ptr inventory, + std::shared_ptr target) { + getDamageBonusIteration.sum = 0; + getDamageBonusIteration.target = target; - getDamageBonusIteration.sum = 0; - getDamageBonusIteration.target = target; + runIterationOnItem(getDamageBonusIteration, inventory->getSelected()); - runIterationOnItem(getDamageBonusIteration, inventory->getSelected()); - - if (getDamageBonusIteration.sum > 0) - { - return 1 + random.nextInt(getDamageBonusIteration.sum); - } - return 0; + if (getDamageBonusIteration.sum > 0) { + return 1 + random.nextInt(getDamageBonusIteration.sum); + } + return 0; } -int EnchantmentHelper::getKnockbackBonus(std::shared_ptr inventory, std::shared_ptr target) -{ - return getEnchantmentLevel(Enchantment::knockback->id, inventory->getSelected()); +int EnchantmentHelper::getKnockbackBonus(std::shared_ptr inventory, + std::shared_ptr target) { + return getEnchantmentLevel(Enchantment::knockback->id, + inventory->getSelected()); } -int EnchantmentHelper::getFireAspect(std::shared_ptr source) -{ - return getEnchantmentLevel(Enchantment::fireAspect->id, source->getCarriedItem()); +int EnchantmentHelper::getFireAspect(std::shared_ptr source) { + return getEnchantmentLevel(Enchantment::fireAspect->id, + source->getCarriedItem()); } -int EnchantmentHelper::getOxygenBonus(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::drownProtection->id, inventory->armor); +int EnchantmentHelper::getOxygenBonus(std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::drownProtection->id, + inventory->armor); } -int EnchantmentHelper::getDiggingBonus(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::diggingBonus->id, inventory->getSelected()); +int EnchantmentHelper::getDiggingBonus(std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::diggingBonus->id, + inventory->getSelected()); } -int EnchantmentHelper::getDigDurability(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::digDurability->id, inventory->getSelected()); +int EnchantmentHelper::getDigDurability(std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::digDurability->id, + inventory->getSelected()); } -bool EnchantmentHelper::hasSilkTouch(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::untouching->id, inventory->getSelected()) > 0; +bool EnchantmentHelper::hasSilkTouch(std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::untouching->id, + inventory->getSelected()) > 0; } -int EnchantmentHelper::getDiggingLootBonus(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::resourceBonus->id, inventory->getSelected()); +int EnchantmentHelper::getDiggingLootBonus( + std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::resourceBonus->id, + inventory->getSelected()); } -int EnchantmentHelper::getKillingLootBonus(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::lootBonus->id, inventory->getSelected()); +int EnchantmentHelper::getKillingLootBonus( + std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::lootBonus->id, + inventory->getSelected()); } -bool EnchantmentHelper::hasWaterWorkerBonus(std::shared_ptr inventory) -{ - return getEnchantmentLevel(Enchantment::waterWorker->id, inventory->armor) > 0; +bool EnchantmentHelper::hasWaterWorkerBonus( + std::shared_ptr inventory) { + return getEnchantmentLevel(Enchantment::waterWorker->id, inventory->armor) > + 0; } -int EnchantmentHelper::getArmorThorns(std::shared_ptr source) -{ - return getEnchantmentLevel(Enchantment::thorns->id, source->getEquipmentSlots()); +int EnchantmentHelper::getArmorThorns(std::shared_ptr source) { + return getEnchantmentLevel(Enchantment::thorns->id, + source->getEquipmentSlots()); } -std::shared_ptr EnchantmentHelper::getRandomItemWith(Enchantment *enchantment, std::shared_ptr source) -{ - ItemInstanceArray items = source->getEquipmentSlots(); - for(unsigned int i = 0; i < items.length; ++i) - { - std::shared_ptr item = items[i]; - if (item != NULL && getEnchantmentLevel(enchantment->id, item) > 0) - { - return item; - } - } +std::shared_ptr EnchantmentHelper::getRandomItemWith( + Enchantment* enchantment, std::shared_ptr source) { + ItemInstanceArray items = source->getEquipmentSlots(); + for (unsigned int i = 0; i < items.length; ++i) { + std::shared_ptr item = items[i]; + if (item != NULL && getEnchantmentLevel(enchantment->id, item) > 0) { + return item; + } + } - return nullptr; + return nullptr; } /** -* -* @param random -* @param slot -* The table slot, 0-2 -* @param bookcases -* How many book cases that are found around the table. -* @param itemInstance -* Which item that is being enchanted. -* @return The enchantment cost, 0 means unchantable, 50 is max. -*/ -int EnchantmentHelper::getEnchantmentCost(Random *random, int slot, int bookcases, std::shared_ptr itemInstance) -{ - Item *item = itemInstance->getItem(); - int itemValue = item->getEnchantmentValue(); + * + * @param random + * @param slot + * The table slot, 0-2 + * @param bookcases + * How many book cases that are found around the table. + * @param itemInstance + * Which item that is being enchanted. + * @return The enchantment cost, 0 means unchantable, 50 is max. + */ +int EnchantmentHelper::getEnchantmentCost( + Random* random, int slot, int bookcases, + std::shared_ptr itemInstance) { + Item* item = itemInstance->getItem(); + int itemValue = item->getEnchantmentValue(); - if (itemValue <= 0) - { - // not enchantable - return 0; - } + if (itemValue <= 0) { + // not enchantable + return 0; + } - // 4J Stu - Updated function to 1.3 version for TU7 - if (bookcases > 15) - { - bookcases = 15; - } + // 4J Stu - Updated function to 1.3 version for TU7 + if (bookcases > 15) { + bookcases = 15; + } - int selected = random->nextInt(8) + 1 + (bookcases >> 1) + random->nextInt(bookcases + 1); - if (slot == 0) - { - return std::max((selected / 3), 1); - } - if (slot == 1) - { - return std::max(selected, bookcases * 2); - } - return selected; + int selected = random->nextInt(8) + 1 + (bookcases >> 1) + + random->nextInt(bookcases + 1); + if (slot == 0) { + return std::max((selected / 3), 1); + } + if (slot == 1) { + return std::max(selected, bookcases * 2); + } + return selected; } -std::shared_ptr EnchantmentHelper::enchantItem(Random *random, std::shared_ptr itemInstance, int enchantmentCost) -{ - std::vector *newEnchantment = EnchantmentHelper::selectEnchantment(random, itemInstance, enchantmentCost); - bool isBook = itemInstance->id == Item::book_Id; +std::shared_ptr EnchantmentHelper::enchantItem( + Random* random, std::shared_ptr itemInstance, + int enchantmentCost) { + std::vector* newEnchantment = + EnchantmentHelper::selectEnchantment(random, itemInstance, + enchantmentCost); + bool isBook = itemInstance->id == Item::book_Id; - if (isBook) itemInstance->id = Item::enchantedBook_Id; + if (isBook) itemInstance->id = Item::enchantedBook_Id; - if (newEnchantment != NULL) - { - for(AUTO_VAR(it, newEnchantment->begin()); it != newEnchantment->end(); ++it) - { - EnchantmentInstance *e = *it; - if (isBook) - { - Item::enchantedBook->addEnchantment(itemInstance, e); - } - else - { - itemInstance->enchant(e->enchantment, e->level); - } - delete e; - } - delete newEnchantment; - } - return itemInstance; + if (newEnchantment != NULL) { + for (AUTO_VAR(it, newEnchantment->begin()); it != newEnchantment->end(); + ++it) { + EnchantmentInstance* e = *it; + if (isBook) { + Item::enchantedBook->addEnchantment(itemInstance, e); + } else { + itemInstance->enchant(e->enchantment, e->level); + } + delete e; + } + delete newEnchantment; + } + return itemInstance; } /** -* -* @param random -* @param itemInstance -* @param enchantmentCost -* @return -*/ -std::vector *EnchantmentHelper::selectEnchantment(Random *random, std::shared_ptr itemInstance, int enchantmentCost) -{ - // withdraw bonus from item - Item *item = itemInstance->getItem(); - int itemBonus = item->getEnchantmentValue(); + * + * @param random + * @param itemInstance + * @param enchantmentCost + * @return + */ +std::vector* EnchantmentHelper::selectEnchantment( + Random* random, std::shared_ptr itemInstance, + int enchantmentCost) { + // withdraw bonus from item + Item* item = itemInstance->getItem(); + int itemBonus = item->getEnchantmentValue(); - if (itemBonus <= 0) - { - return NULL; - } - // 4J Stu - Update function to 1.3 version for TU7 - itemBonus /= 2; - itemBonus = 1 + random->nextInt((itemBonus >> 1) + 1) + random->nextInt((itemBonus >> 1) + 1); + if (itemBonus <= 0) { + return NULL; + } + // 4J Stu - Update function to 1.3 version for TU7 + itemBonus /= 2; + itemBonus = 1 + random->nextInt((itemBonus >> 1) + 1) + + random->nextInt((itemBonus >> 1) + 1); - int enchantmentValue = itemBonus + enchantmentCost; + int enchantmentValue = itemBonus + enchantmentCost; - // the final enchantment cost will have another random span of +- 15% - float deviation = (random->nextFloat() + random->nextFloat() - 1.0f) * .15f; - int realValue = (int) ((float) enchantmentValue * (1.0f + deviation) + .5f); - if (realValue < 1) - { - realValue = 1; - } + // the final enchantment cost will have another random span of +- 15% + float deviation = (random->nextFloat() + random->nextFloat() - 1.0f) * .15f; + int realValue = (int)((float)enchantmentValue * (1.0f + deviation) + .5f); + if (realValue < 1) { + realValue = 1; + } - std::vector *results = NULL; + std::vector* results = NULL; - std::unordered_map *availableEnchantments = getAvailableEnchantmentResults(realValue, itemInstance); - if (availableEnchantments != NULL && !availableEnchantments->empty()) - { - std::vector values; - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) - { - values.push_back(it->second); - } - EnchantmentInstance *instance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); - values.clear(); + std::unordered_map* availableEnchantments = + getAvailableEnchantmentResults(realValue, itemInstance); + if (availableEnchantments != NULL && !availableEnchantments->empty()) { + std::vector values; + for (AUTO_VAR(it, availableEnchantments->begin()); + it != availableEnchantments->end(); ++it) { + values.push_back(it->second); + } + EnchantmentInstance* instance = + (EnchantmentInstance*)WeighedRandom::getRandomItem(random, &values); + values.clear(); - if (instance != NULL) - { - results = new std::vector(); - results->push_back( instance->copy() ); // 4J Stu - Inserting a copy so we can clear memory from the availableEnchantments collection + if (instance != NULL) { + results = new std::vector(); + results->push_back( + instance->copy()); // 4J Stu - Inserting a copy so we can clear + // memory from the availableEnchantments + // collection - int bonusChance = realValue; - while (random->nextInt(50) <= bonusChance) - { + int bonusChance = realValue; + while (random->nextInt(50) <= bonusChance) { + // remove incompatible enchantments from previous result + // final Iterator mapIter = + // availableEnchantments.keySet().iterator(); while + // (mapIter.hasNext()) + for (AUTO_VAR(it, availableEnchantments->begin()); + it != availableEnchantments->end();) { + int nextEnchantment = it->first; // mapIter.next(); + bool valid = true; + // for (EnchantmentInstance *current : results) + for (AUTO_VAR(resIt, results->begin()); + resIt != results->end(); ++resIt) { + EnchantmentInstance* current = *resIt; + if (!current->enchantment->isCompatibleWith( + Enchantment::enchantments[nextEnchantment])) { + valid = false; + break; + } + } + if (!valid) { + // mapIter.remove(); + delete it->second; + it = availableEnchantments->erase(it); + } else { + ++it; + } + } - // remove incompatible enchantments from previous result - //final Iterator mapIter = availableEnchantments.keySet().iterator(); - //while (mapIter.hasNext()) - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end();) - { - int nextEnchantment = it->first;//mapIter.next(); - bool valid = true; - //for (EnchantmentInstance *current : results) - for(AUTO_VAR(resIt, results->begin()); resIt != results->end(); ++resIt) - { - EnchantmentInstance *current = *resIt; - if (!current->enchantment->isCompatibleWith(Enchantment::enchantments[nextEnchantment])) - { - valid = false; - break; - } - } - if (!valid) - { - //mapIter.remove(); - delete it->second; - it = availableEnchantments->erase(it); - } - else - { - ++it; - } - } + if (!availableEnchantments->empty()) { + for (AUTO_VAR(it, availableEnchantments->begin()); + it != availableEnchantments->end(); ++it) { + values.push_back(it->second); + } + EnchantmentInstance* nextInstance = + (EnchantmentInstance*)WeighedRandom::getRandomItem( + random, &values); + values.clear(); + results->push_back( + nextInstance + ->copy()); // 4J Stu - Inserting a copy so we can + // clear memory from the + // availableEnchantments collection + } - if (!availableEnchantments->empty()) - { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) - { - values.push_back(it->second); - } - EnchantmentInstance *nextInstance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); - values.clear(); - results->push_back( nextInstance->copy() ); // 4J Stu - Inserting a copy so we can clear memory from the availableEnchantments collection - } + bonusChance >>= 1; + } + } + } + if (availableEnchantments != NULL) { + for (AUTO_VAR(it, availableEnchantments->begin()); + it != availableEnchantments->end(); ++it) { + delete it->second; + } + delete availableEnchantments; + } - bonusChance >>= 1; - } - } - } - if(availableEnchantments != NULL) - { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) - { - delete it->second; - } - delete availableEnchantments; - } - - return results; + return results; } -std::unordered_map *EnchantmentHelper::getAvailableEnchantmentResults(int value, std::shared_ptr itemInstance) -{ - Item *item = itemInstance->getItem(); - std::unordered_map *results = NULL; +std::unordered_map* +EnchantmentHelper::getAvailableEnchantmentResults( + int value, std::shared_ptr itemInstance) { + Item* item = itemInstance->getItem(); + std::unordered_map* results = NULL; - bool isBook = itemInstance->id == Item::book_Id; + bool isBook = itemInstance->id == Item::book_Id; - //for (Enchantment e : Enchantment.enchantments) - for(unsigned int i = 0; i < Enchantment::enchantments.length; ++i) - { - Enchantment *e = Enchantment::enchantments[i]; - if (e == NULL) - { - continue; - } + // for (Enchantment e : Enchantment.enchantments) + for (unsigned int i = 0; i < Enchantment::enchantments.length; ++i) { + Enchantment* e = Enchantment::enchantments[i]; + if (e == NULL) { + continue; + } - // Only picks "normal" enchantments, no specialcases - if (!e->category->canEnchant(item) && !isBook) - { - continue; - } + // Only picks "normal" enchantments, no specialcases + if (!e->category->canEnchant(item) && !isBook) { + continue; + } - for (int level = e->getMinLevel(); level <= e->getMaxLevel(); level++) - { - if (value >= e->getMinCost(level) && value <= e->getMaxCost(level)) - { - if (results == NULL) - { - results = new std::unordered_map(); - } - AUTO_VAR(it, results->find(e->id)); - if(it != results->end()) - { - delete it->second; - } - (*results)[e->id] = new EnchantmentInstance(e, level); - } - } - } + for (int level = e->getMinLevel(); level <= e->getMaxLevel(); level++) { + if (value >= e->getMinCost(level) && + value <= e->getMaxCost(level)) { + if (results == NULL) { + results = + new std::unordered_map(); + } + AUTO_VAR(it, results->find(e->id)); + if (it != results->end()) { + delete it->second; + } + (*results)[e->id] = new EnchantmentInstance(e, level); + } + } + } - return results; + return results; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentHelper.h b/Minecraft.World/Enchantments/EnchantmentHelper.h index 30f33df19..b526732f5 100644 --- a/Minecraft.World/Enchantments/EnchantmentHelper.h +++ b/Minecraft.World/Enchantments/EnchantmentHelper.h @@ -6,105 +6,116 @@ class DamageSource; class Enchantment; class EnchantmentInstance; -class EnchantmentHelper -{ +class EnchantmentHelper { private: - static Random random; + static Random random; public: - static int getEnchantmentLevel(int enchantmentId, std::shared_ptr piece); - static std::unordered_map *getEnchantments(std::shared_ptr item); - static void setEnchantments(std::unordered_map *enchantments, std::shared_ptr item); + static int getEnchantmentLevel(int enchantmentId, + std::shared_ptr piece); + static std::unordered_map* getEnchantments( + std::shared_ptr item); + static void setEnchantments(std::unordered_map* enchantments, + std::shared_ptr item); - static int getEnchantmentLevel(int enchantmentId, ItemInstanceArray inventory); + static int getEnchantmentLevel(int enchantmentId, + ItemInstanceArray inventory); private: + class EnchantmentIterationMethod { + public: + virtual void doEnchantment(Enchantment* enchantment, int level) = 0; + }; + static void runIterationOnItem(EnchantmentIterationMethod& method, + std::shared_ptr piece); + static void runIterationOnInventory(EnchantmentIterationMethod& method, + ItemInstanceArray inventory); - class EnchantmentIterationMethod - { - public: - virtual void doEnchantment(Enchantment *enchantment, int level) = 0; - }; + class GetDamageProtectionIteration : public EnchantmentIterationMethod { + public: + int sum; + DamageSource* source; - static void runIterationOnItem(EnchantmentIterationMethod &method, std::shared_ptr piece); - static void runIterationOnInventory(EnchantmentIterationMethod &method, ItemInstanceArray inventory); + virtual void doEnchantment(Enchantment* enchantment, int level); + }; - class GetDamageProtectionIteration : public EnchantmentIterationMethod - { - public: - int sum; - DamageSource *source; + static GetDamageProtectionIteration getDamageProtectionIteration; - virtual void doEnchantment(Enchantment *enchantment, int level); - }; - - static GetDamageProtectionIteration getDamageProtectionIteration; - - /** - * Fetches the protection value for enchanted items. - * - * @param inventory - * @param source - * @return - */ + /** + * Fetches the protection value for enchanted items. + * + * @param inventory + * @param source + * @return + */ public: - static int getDamageProtection(std::shared_ptr inventory, DamageSource *source); + static int getDamageProtection(std::shared_ptr inventory, + DamageSource* source); private: - class GetDamageBonusIteration : public EnchantmentIterationMethod - { - public: - int sum; - std::shared_ptr target; + class GetDamageBonusIteration : public EnchantmentIterationMethod { + public: + int sum; + std::shared_ptr target; - virtual void doEnchantment(Enchantment *enchantment, int level); - }; + virtual void doEnchantment(Enchantment* enchantment, int level); + }; - static GetDamageBonusIteration getDamageBonusIteration; + static GetDamageBonusIteration getDamageBonusIteration; - /** - * - * @param inventory - * @param target - * @return - */ + /** + * + * @param inventory + * @param target + * @return + */ public: - static int getDamageBonus(std::shared_ptr inventory, std::shared_ptr target); - static int getKnockbackBonus(std::shared_ptr inventory, std::shared_ptr target); - static int getFireAspect(std::shared_ptr source); - static int getOxygenBonus(std::shared_ptr inventory); - static int getDiggingBonus(std::shared_ptr inventory); - static int getDigDurability(std::shared_ptr inventory); - static bool hasSilkTouch(std::shared_ptr inventory); - static int getDiggingLootBonus(std::shared_ptr inventory); - static int getKillingLootBonus(std::shared_ptr inventory); - static bool hasWaterWorkerBonus(std::shared_ptr inventory); - static int getArmorThorns(std::shared_ptr source); - static std::shared_ptr getRandomItemWith(Enchantment *enchantment, std::shared_ptr source); + static int getDamageBonus(std::shared_ptr inventory, + std::shared_ptr target); + static int getKnockbackBonus(std::shared_ptr inventory, + std::shared_ptr target); + static int getFireAspect(std::shared_ptr source); + static int getOxygenBonus(std::shared_ptr inventory); + static int getDiggingBonus(std::shared_ptr inventory); + static int getDigDurability(std::shared_ptr inventory); + static bool hasSilkTouch(std::shared_ptr inventory); + static int getDiggingLootBonus(std::shared_ptr inventory); + static int getKillingLootBonus(std::shared_ptr inventory); + static bool hasWaterWorkerBonus(std::shared_ptr inventory); + static int getArmorThorns(std::shared_ptr source); + static std::shared_ptr getRandomItemWith( + Enchantment* enchantment, std::shared_ptr source); - /** - * - * @param random - * @param slot - * The table slot, 0-2 - * @param bookcases - * How many book cases that are found around the table. - * @param itemInstance - * Which item that is being enchanted. - * @return The enchantment cost, 0 means unchantable, 50 is max. - */ - static int getEnchantmentCost(Random *random, int slot, int bookcases, std::shared_ptr itemInstance); + /** + * + * @param random + * @param slot + * The table slot, 0-2 + * @param bookcases + * How many book cases that are found around the table. + * @param itemInstance + * Which item that is being enchanted. + * @return The enchantment cost, 0 means unchantable, 50 is max. + */ + static int getEnchantmentCost(Random* random, int slot, int bookcases, + std::shared_ptr itemInstance); - static std::shared_ptr enchantItem(Random *random, std::shared_ptr itemInstance, int enchantmentCost); + static std::shared_ptr enchantItem( + Random* random, std::shared_ptr itemInstance, + int enchantmentCost); - /** - * - * @param random - * @param itemInstance - * @param enchantmentCost - * @return - */ - static std::vector *selectEnchantment(Random *random, std::shared_ptr itemInstance, int enchantmentCost); - static std::unordered_map *getAvailableEnchantmentResults(int value, std::shared_ptr itemInstance); + /** + * + * @param random + * @param itemInstance + * @param enchantmentCost + * @return + */ + static std::vector* selectEnchantment( + Random* random, std::shared_ptr itemInstance, + int enchantmentCost); + static std::unordered_map* + getAvailableEnchantmentResults(int value, + std::shared_ptr itemInstance); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentInstance.cpp b/Minecraft.World/Enchantments/EnchantmentInstance.cpp index f32c68265..8538ec437 100644 --- a/Minecraft.World/Enchantments/EnchantmentInstance.cpp +++ b/Minecraft.World/Enchantments/EnchantmentInstance.cpp @@ -2,16 +2,17 @@ #include "../Headers/net.minecraft.world.item.enchantment.h" #include "EnchantmentInstance.h" -EnchantmentInstance::EnchantmentInstance(Enchantment *enchantment, int level) : WeighedRandomItem(enchantment->getFrequency()), enchantment(enchantment), level(level) -{ -} +EnchantmentInstance::EnchantmentInstance(Enchantment* enchantment, int level) + : WeighedRandomItem(enchantment->getFrequency()), + enchantment(enchantment), + level(level) {} -EnchantmentInstance::EnchantmentInstance(int id, int level) : WeighedRandomItem(Enchantment::enchantments[id]->getFrequency()), enchantment(Enchantment::enchantments[id]), level(level) -{ -} +EnchantmentInstance::EnchantmentInstance(int id, int level) + : WeighedRandomItem(Enchantment::enchantments[id]->getFrequency()), + enchantment(Enchantment::enchantments[id]), + level(level) {} // 4J Added -EnchantmentInstance *EnchantmentInstance::copy() -{ - return new EnchantmentInstance((Enchantment *)enchantment, (int)level); +EnchantmentInstance* EnchantmentInstance::copy() { + return new EnchantmentInstance((Enchantment*)enchantment, (int)level); } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/EnchantmentInstance.h b/Minecraft.World/Enchantments/EnchantmentInstance.h index f875fe762..4a62e764d 100644 --- a/Minecraft.World/Enchantments/EnchantmentInstance.h +++ b/Minecraft.World/Enchantments/EnchantmentInstance.h @@ -2,15 +2,14 @@ #include "../Util/WeighedRandom.h" -class EnchantmentInstance : public WeighedRandomItem -{ +class EnchantmentInstance : public WeighedRandomItem { public: - const Enchantment *enchantment; - const int level; + const Enchantment* enchantment; + const int level; - EnchantmentInstance(Enchantment *enchantment, int level); - EnchantmentInstance(int id, int level); + EnchantmentInstance(Enchantment* enchantment, int level); + EnchantmentInstance(int id, int level); - // 4J Added - EnchantmentInstance *copy(); + // 4J Added + EnchantmentInstance* copy(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/FireAspectEnchantment.cpp b/Minecraft.World/Enchantments/FireAspectEnchantment.cpp index a0401c006..d5bd5ef38 100644 --- a/Minecraft.World/Enchantments/FireAspectEnchantment.cpp +++ b/Minecraft.World/Enchantments/FireAspectEnchantment.cpp @@ -1,22 +1,17 @@ #include "../Platform/stdafx.h" #include "FireAspectEnchantment.h" -FireAspectEnchantment::FireAspectEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::weapon) -{ - setDescriptionId(IDS_ENCHANTMENT_FIRE); +FireAspectEnchantment::FireAspectEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::weapon) { + setDescriptionId(IDS_ENCHANTMENT_FIRE); } -int FireAspectEnchantment::getMinCost(int level) -{ - return 10 + 20 * (level - 1); +int FireAspectEnchantment::getMinCost(int level) { + return 10 + 20 * (level - 1); } -int FireAspectEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; +int FireAspectEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int FireAspectEnchantment::getMaxLevel() -{ - return 2; -} \ No newline at end of file +int FireAspectEnchantment::getMaxLevel() { return 2; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/FireAspectEnchantment.h b/Minecraft.World/Enchantments/FireAspectEnchantment.h index 78b536110..9af13b977 100644 --- a/Minecraft.World/Enchantments/FireAspectEnchantment.h +++ b/Minecraft.World/Enchantments/FireAspectEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class FireAspectEnchantment : public Enchantment -{ +class FireAspectEnchantment : public Enchantment { public: - FireAspectEnchantment(int id, int frequency); + FireAspectEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/KnockbackEnchantment.cpp b/Minecraft.World/Enchantments/KnockbackEnchantment.cpp index 562568e12..f7fca6bdd 100644 --- a/Minecraft.World/Enchantments/KnockbackEnchantment.cpp +++ b/Minecraft.World/Enchantments/KnockbackEnchantment.cpp @@ -1,22 +1,15 @@ #include "../Platform/stdafx.h" #include "KnockbackEnchantment.h" -KnockbackEnchantment::KnockbackEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::weapon) -{ - setDescriptionId(IDS_ENCHANTMENT_KNOCKBACK); +KnockbackEnchantment::KnockbackEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::weapon) { + setDescriptionId(IDS_ENCHANTMENT_KNOCKBACK); } -int KnockbackEnchantment::getMinCost(int level) -{ - return 5 + 20 * (level - 1); +int KnockbackEnchantment::getMinCost(int level) { return 5 + 20 * (level - 1); } + +int KnockbackEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int KnockbackEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; -} - -int KnockbackEnchantment::getMaxLevel() -{ - return 2; -} \ No newline at end of file +int KnockbackEnchantment::getMaxLevel() { return 2; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/KnockbackEnchantment.h b/Minecraft.World/Enchantments/KnockbackEnchantment.h index c7ecbe4df..2dcdfc0b7 100644 --- a/Minecraft.World/Enchantments/KnockbackEnchantment.h +++ b/Minecraft.World/Enchantments/KnockbackEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class KnockbackEnchantment : public Enchantment -{ +class KnockbackEnchantment : public Enchantment { public: - KnockbackEnchantment(int id, int frequency); + KnockbackEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/LootBonusEnchantment.cpp b/Minecraft.World/Enchantments/LootBonusEnchantment.cpp index 1f85c09b1..94ecde5e9 100644 --- a/Minecraft.World/Enchantments/LootBonusEnchantment.cpp +++ b/Minecraft.World/Enchantments/LootBonusEnchantment.cpp @@ -1,31 +1,23 @@ #include "../Platform/stdafx.h" #include "LootBonusEnchantment.h" -LootBonusEnchantment::LootBonusEnchantment(int id, int frequency, const EnchantmentCategory *cat) : Enchantment(id, frequency, cat) -{ - setDescriptionId(IDS_ENCHANTMENT_LOOT_BONUS); - if (cat == EnchantmentCategory::digger) - { - setDescriptionId(IDS_ENCHANTMENT_LOOT_BONUS_DIGGER); - } +LootBonusEnchantment::LootBonusEnchantment(int id, int frequency, + const EnchantmentCategory* cat) + : Enchantment(id, frequency, cat) { + setDescriptionId(IDS_ENCHANTMENT_LOOT_BONUS); + if (cat == EnchantmentCategory::digger) { + setDescriptionId(IDS_ENCHANTMENT_LOOT_BONUS_DIGGER); + } } -int LootBonusEnchantment::getMinCost(int level) -{ - return 15 + (level - 1) * 9; +int LootBonusEnchantment::getMinCost(int level) { return 15 + (level - 1) * 9; } + +int LootBonusEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int LootBonusEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; -} +int LootBonusEnchantment::getMaxLevel() { return 3; } -int LootBonusEnchantment::getMaxLevel() -{ - return 3; -} - -bool LootBonusEnchantment::isCompatibleWith(Enchantment *other) const -{ - return Enchantment::isCompatibleWith(other) && other->id != untouching->id; +bool LootBonusEnchantment::isCompatibleWith(Enchantment* other) const { + return Enchantment::isCompatibleWith(other) && other->id != untouching->id; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/LootBonusEnchantment.h b/Minecraft.World/Enchantments/LootBonusEnchantment.h index 134d2dce2..09c452974 100644 --- a/Minecraft.World/Enchantments/LootBonusEnchantment.h +++ b/Minecraft.World/Enchantments/LootBonusEnchantment.h @@ -2,13 +2,12 @@ #include "Enchantment.h" -class LootBonusEnchantment : public Enchantment -{ +class LootBonusEnchantment : public Enchantment { public: - LootBonusEnchantment(int id, int frequency, const EnchantmentCategory *cat); + LootBonusEnchantment(int id, int frequency, const EnchantmentCategory* cat); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual bool isCompatibleWith(Enchantment *other) const; + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual bool isCompatibleWith(Enchantment* other) const; }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/OxygenEnchantment.cpp b/Minecraft.World/Enchantments/OxygenEnchantment.cpp index 03dbf5a56..37df5c48d 100644 --- a/Minecraft.World/Enchantments/OxygenEnchantment.cpp +++ b/Minecraft.World/Enchantments/OxygenEnchantment.cpp @@ -1,22 +1,13 @@ #include "../Platform/stdafx.h" #include "OxygenEnchantment.h" -OxygenEnchantment::OxygenEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::armor_head) -{ - setDescriptionId(IDS_ENCHANTMENT_OXYGEN); +OxygenEnchantment::OxygenEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::armor_head) { + setDescriptionId(IDS_ENCHANTMENT_OXYGEN); } -int OxygenEnchantment::getMinCost(int level) -{ - return 10 * level; -} +int OxygenEnchantment::getMinCost(int level) { return 10 * level; } -int OxygenEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + 30; -} +int OxygenEnchantment::getMaxCost(int level) { return getMinCost(level) + 30; } -int OxygenEnchantment::getMaxLevel() -{ - return 3; -} \ No newline at end of file +int OxygenEnchantment::getMaxLevel() { return 3; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/OxygenEnchantment.h b/Minecraft.World/Enchantments/OxygenEnchantment.h index ef57652c0..386a77a73 100644 --- a/Minecraft.World/Enchantments/OxygenEnchantment.h +++ b/Minecraft.World/Enchantments/OxygenEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class OxygenEnchantment : public Enchantment -{ +class OxygenEnchantment : public Enchantment { public: - OxygenEnchantment(int id, int frequency); + OxygenEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ProtectionEnchantment.cpp b/Minecraft.World/Enchantments/ProtectionEnchantment.cpp index ca44c0b69..9607b755d 100644 --- a/Minecraft.World/Enchantments/ProtectionEnchantment.cpp +++ b/Minecraft.World/Enchantments/ProtectionEnchantment.cpp @@ -4,91 +4,84 @@ #include "../Headers/net.minecraft.world.entity.h" #include "ProtectionEnchantment.h" -const int ProtectionEnchantment::names[] = {IDS_ENCHANTMENT_PROTECT_ALL, IDS_ENCHANTMENT_PROTECT_FIRE, IDS_ENCHANTMENT_PROTECT_FALL, IDS_ENCHANTMENT_PROTECT_EXPLOSION, IDS_ENCHANTMENT_PROTECT_PROJECTILE}; +const int ProtectionEnchantment::names[] = { + IDS_ENCHANTMENT_PROTECT_ALL, IDS_ENCHANTMENT_PROTECT_FIRE, + IDS_ENCHANTMENT_PROTECT_FALL, IDS_ENCHANTMENT_PROTECT_EXPLOSION, + IDS_ENCHANTMENT_PROTECT_PROJECTILE}; const int ProtectionEnchantment::minCost[] = {1, 10, 5, 5, 3}; const int ProtectionEnchantment::levelCost[] = {11, 8, 6, 8, 6}; const int ProtectionEnchantment::levelCostSpan[] = {20, 12, 10, 12, 15}; -ProtectionEnchantment::ProtectionEnchantment(int id, int frequency, int type) : Enchantment(id, frequency, EnchantmentCategory::armor), type(type) -{ - if (type == FALL) - { - category = EnchantmentCategory::armor_feet; - } +ProtectionEnchantment::ProtectionEnchantment(int id, int frequency, int type) + : Enchantment(id, frequency, EnchantmentCategory::armor), type(type) { + if (type == FALL) { + category = EnchantmentCategory::armor_feet; + } } -int ProtectionEnchantment::getMinCost(int level) -{ - return minCost[type] + (level - 1) * levelCost[type]; +int ProtectionEnchantment::getMinCost(int level) { + return minCost[type] + (level - 1) * levelCost[type]; } -int ProtectionEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + levelCostSpan[type]; +int ProtectionEnchantment::getMaxCost(int level) { + return getMinCost(level) + levelCostSpan[type]; } -int ProtectionEnchantment::getMaxLevel() -{ - return 4; +int ProtectionEnchantment::getMaxLevel() { return 4; } + +int ProtectionEnchantment::getDamageProtection(int level, + DamageSource* source) { + if (source->isBypassInvul()) return 0; + + float protect = (6 + level * level) / 3.0f; + + if (type == ALL) return Mth::floor(protect * 0.75f); + if (type == FIRE && source->isFire()) return Mth::floor(protect * 1.25f); + if (type == FALL && source == DamageSource::fall) + return Mth::floor(protect * 2.5f); + if (type == EXPLOSION && source == DamageSource::explosion) + return Mth::floor(protect * 1.5f); + if (type == PROJECTILE && source->isProjectile()) + return Mth::floor(protect * 1.5f); + return 0; } -int ProtectionEnchantment::getDamageProtection(int level, DamageSource *source) -{ - if (source->isBypassInvul()) return 0; +int ProtectionEnchantment::getDescriptionId() { return names[type]; } - float protect = (6 + level * level) / 3.0f; - - if (type == ALL) return Mth::floor(protect * 0.75f); - if (type == FIRE && source->isFire()) return Mth::floor(protect * 1.25f); - if (type == FALL && source == DamageSource::fall) return Mth::floor(protect * 2.5f); - if (type == EXPLOSION && source == DamageSource::explosion) return Mth::floor(protect * 1.5f); - if (type == PROJECTILE && source->isProjectile()) return Mth::floor(protect * 1.5f); - return 0; +bool ProtectionEnchantment::isCompatibleWith(Enchantment* other) const { + ProtectionEnchantment* pe = dynamic_cast(other); + if (pe != NULL) { + if (pe->type == this->type) { + return false; + } + if (this->type == FALL || pe->type == FALL) { + return true; + } + return false; + } + return Enchantment::isCompatibleWith(other); } -int ProtectionEnchantment::getDescriptionId() -{ - return names[type]; +int ProtectionEnchantment::getFireAfterDampener(std::shared_ptr entity, + int time) { + int level = EnchantmentHelper::getEnchantmentLevel( + Enchantment::fireProtection->id, entity->getEquipmentSlots()); + + if (level > 0) { + time -= Mth::floor(time * (level * 0.15f)); + } + + return time; } -bool ProtectionEnchantment::isCompatibleWith(Enchantment *other) const -{ - ProtectionEnchantment *pe = dynamic_cast( other ); - if (pe != NULL) - { - if (pe->type == this->type) - { - return false; - } - if (this->type == FALL || pe->type == FALL) - { - return true; - } - return false; - } - return Enchantment::isCompatibleWith(other); -} +double ProtectionEnchantment::getExplosionKnockbackAfterDampener( + std::shared_ptr entity, double power) { + int level = EnchantmentHelper::getEnchantmentLevel( + Enchantment::explosionProtection->id, entity->getEquipmentSlots()); -int ProtectionEnchantment::getFireAfterDampener(std::shared_ptr entity, int time) -{ - int level = EnchantmentHelper::getEnchantmentLevel(Enchantment::fireProtection->id, entity->getEquipmentSlots()); + if (level > 0) { + power -= Mth::floor(power * (level * 0.15f)); + } - if (level > 0) - { - time -= Mth::floor(time * (level * 0.15f)); - } - - return time; -} - -double ProtectionEnchantment::getExplosionKnockbackAfterDampener(std::shared_ptr entity, double power) -{ - int level = EnchantmentHelper::getEnchantmentLevel(Enchantment::explosionProtection->id, entity->getEquipmentSlots()); - - if (level > 0) - { - power -= Mth::floor(power * (level * 0.15f)); - } - - return power; + return power; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ProtectionEnchantment.h b/Minecraft.World/Enchantments/ProtectionEnchantment.h index e97272546..70c44affb 100644 --- a/Minecraft.World/Enchantments/ProtectionEnchantment.h +++ b/Minecraft.World/Enchantments/ProtectionEnchantment.h @@ -2,32 +2,32 @@ #include "Enchantment.h" -class ProtectionEnchantment : public Enchantment -{ +class ProtectionEnchantment : public Enchantment { public: - static const int ALL = 0; - static const int FIRE = 1; - static const int FALL = 2; - static const int EXPLOSION = 3; - static const int PROJECTILE = 4; + static const int ALL = 0; + static const int FIRE = 1; + static const int FALL = 2; + static const int EXPLOSION = 3; + static const int PROJECTILE = 4; private: - static const int names[]; - static const int minCost[]; - static const int levelCost[]; - static const int levelCostSpan[]; + static const int names[]; + static const int minCost[]; + static const int levelCost[]; + static const int levelCostSpan[]; public: - const int type; + const int type; - ProtectionEnchantment(int id, int frequency, int type); + ProtectionEnchantment(int id, int frequency, int type); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual int getDamageProtection(int level, DamageSource *source); - virtual int getDescriptionId(); - virtual bool isCompatibleWith(Enchantment *other) const; - static int getFireAfterDampener(std::shared_ptr entity, int time); - static double getExplosionKnockbackAfterDampener(std::shared_ptr entity, double power); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual int getDamageProtection(int level, DamageSource* source); + virtual int getDescriptionId(); + virtual bool isCompatibleWith(Enchantment* other) const; + static int getFireAfterDampener(std::shared_ptr entity, int time); + static double getExplosionKnockbackAfterDampener( + std::shared_ptr entity, double power); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ThornsEnchantment.cpp b/Minecraft.World/Enchantments/ThornsEnchantment.cpp index a8459765b..4a3de3efe 100644 --- a/Minecraft.World/Enchantments/ThornsEnchantment.cpp +++ b/Minecraft.World/Enchantments/ThornsEnchantment.cpp @@ -7,71 +7,55 @@ const float ThornsEnchantment::CHANCE_PER_LEVEl = 0.15f; -ThornsEnchantment::ThornsEnchantment(int id, int freq) : Enchantment(id, freq, EnchantmentCategory::armor_torso) -{ - setDescriptionId(IDS_ENCHANTMENT_THORNS); +ThornsEnchantment::ThornsEnchantment(int id, int freq) + : Enchantment(id, freq, EnchantmentCategory::armor_torso) { + setDescriptionId(IDS_ENCHANTMENT_THORNS); } -int ThornsEnchantment::getMinCost(int level) -{ - return 10 + 20 * (level - 1); +int ThornsEnchantment::getMinCost(int level) { return 10 + 20 * (level - 1); } + +int ThornsEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int ThornsEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; +int ThornsEnchantment::getMaxLevel() { return 3; } + +bool ThornsEnchantment::canEnchant(std::shared_ptr item) { + ArmorItem* armor = dynamic_cast(item->getItem()); + if (armor) return true; + return Enchantment::canEnchant(item); } -int ThornsEnchantment::getMaxLevel() -{ - return 3; +bool ThornsEnchantment::shouldHit(int level, Random* random) { + if (level <= 0) return false; + return random->nextFloat() < CHANCE_PER_LEVEl * level; } -bool ThornsEnchantment::canEnchant(std::shared_ptr item) -{ - ArmorItem *armor = dynamic_cast(item->getItem()); - if (armor) return true; - return Enchantment::canEnchant(item); +int ThornsEnchantment::getDamage(int level, Random* random) { + if (level > 10) { + return level - 10; + } else { + return 1 + random->nextInt(4); + } } -bool ThornsEnchantment::shouldHit(int level, Random *random) -{ - if (level <= 0) return false; - return random->nextFloat() < CHANCE_PER_LEVEl * level; -} +void ThornsEnchantment::doThornsAfterAttack(std::shared_ptr source, + std::shared_ptr target, + Random* random) { + int level = EnchantmentHelper::getArmorThorns(target); + std::shared_ptr item = + EnchantmentHelper::getRandomItemWith(Enchantment::thorns, target); -int ThornsEnchantment::getDamage(int level, Random *random) -{ - if (level > 10) - { - return level - 10; - } - else - { - return 1 + random->nextInt(4); - } -} + if (shouldHit(level, random)) { + source->hurt(DamageSource::thorns(target), getDamage(level, random)); + source->playSound(eSoundType_DAMAGE_THORNS, .5f, 1.0f); -void ThornsEnchantment::doThornsAfterAttack(std::shared_ptr source, std::shared_ptr target, Random *random) -{ - int level = EnchantmentHelper::getArmorThorns(target); - std::shared_ptr item = EnchantmentHelper::getRandomItemWith(Enchantment::thorns, target); - - if (shouldHit(level, random)) - { - source->hurt(DamageSource::thorns(target), getDamage(level, random)); - source->playSound(eSoundType_DAMAGE_THORNS, .5f, 1.0f); - - if (item != NULL) - { - item->hurt(3, target); - } - } - else - { - if (item != NULL) - { - item->hurt(1, target); - } - } + if (item != NULL) { + item->hurt(3, target); + } + } else { + if (item != NULL) { + item->hurt(1, target); + } + } } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/ThornsEnchantment.h b/Minecraft.World/Enchantments/ThornsEnchantment.h index 240888a06..37af6cc21 100644 --- a/Minecraft.World/Enchantments/ThornsEnchantment.h +++ b/Minecraft.World/Enchantments/ThornsEnchantment.h @@ -2,19 +2,20 @@ #include "Enchantment.h" -class ThornsEnchantment : public Enchantment -{ +class ThornsEnchantment : public Enchantment { private: - static const float CHANCE_PER_LEVEl; + static const float CHANCE_PER_LEVEl; public: - ThornsEnchantment(int id, int freq); + ThornsEnchantment(int id, int freq); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual bool canEnchant(std::shared_ptr item); - static bool shouldHit(int level, Random *random); - static int getDamage(int level, Random *random); - static void doThornsAfterAttack(std::shared_ptr source, std::shared_ptr target, Random *random); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual bool canEnchant(std::shared_ptr item); + static bool shouldHit(int level, Random* random); + static int getDamage(int level, Random* random); + static void doThornsAfterAttack(std::shared_ptr source, + std::shared_ptr target, + Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/UntouchingEnchantment.cpp b/Minecraft.World/Enchantments/UntouchingEnchantment.cpp index 2ee61ac6a..c9041227c 100644 --- a/Minecraft.World/Enchantments/UntouchingEnchantment.cpp +++ b/Minecraft.World/Enchantments/UntouchingEnchantment.cpp @@ -2,33 +2,25 @@ #include "../Headers/net.minecraft.world.item.h" #include "UntouchingEnchantment.h" -UntouchingEnchantment::UntouchingEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::digger) -{ - setDescriptionId(IDS_ENCHANTMENT_UNTOUCHING); +UntouchingEnchantment::UntouchingEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::digger) { + setDescriptionId(IDS_ENCHANTMENT_UNTOUCHING); } -int UntouchingEnchantment::getMinCost(int level) -{ - return 15; +int UntouchingEnchantment::getMinCost(int level) { return 15; } + +int UntouchingEnchantment::getMaxCost(int level) { + return Enchantment::getMinCost(level) + 50; } -int UntouchingEnchantment::getMaxCost(int level) -{ - return Enchantment::getMinCost(level) + 50; +int UntouchingEnchantment::getMaxLevel() { return 1; } + +bool UntouchingEnchantment::isCompatibleWith(Enchantment* other) const { + return Enchantment::isCompatibleWith(other) && + other->id != resourceBonus->id; } -int UntouchingEnchantment::getMaxLevel() -{ - return 1; -} - -bool UntouchingEnchantment::isCompatibleWith(Enchantment *other) const -{ - return Enchantment::isCompatibleWith(other) && other->id != resourceBonus->id; -} - -bool UntouchingEnchantment::canEnchant(std::shared_ptr item) -{ - if (item->getItem()->id == Item::shears_Id) return true; - return Enchantment::canEnchant(item); +bool UntouchingEnchantment::canEnchant(std::shared_ptr item) { + if (item->getItem()->id == Item::shears_Id) return true; + return Enchantment::canEnchant(item); } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/UntouchingEnchantment.h b/Minecraft.World/Enchantments/UntouchingEnchantment.h index 14ce0b49e..92e8e3e15 100644 --- a/Minecraft.World/Enchantments/UntouchingEnchantment.h +++ b/Minecraft.World/Enchantments/UntouchingEnchantment.h @@ -2,14 +2,13 @@ #include "Enchantment.h" -class UntouchingEnchantment : public Enchantment -{ +class UntouchingEnchantment : public Enchantment { public: - UntouchingEnchantment(int id, int frequency); + UntouchingEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); - virtual bool isCompatibleWith(Enchantment *other) const; - virtual bool canEnchant(std::shared_ptr item); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); + virtual bool isCompatibleWith(Enchantment* other) const; + virtual bool canEnchant(std::shared_ptr item); }; \ No newline at end of file diff --git a/Minecraft.World/Enchantments/WaterWorkerEnchantment.cpp b/Minecraft.World/Enchantments/WaterWorkerEnchantment.cpp index c9a904949..3b497f137 100644 --- a/Minecraft.World/Enchantments/WaterWorkerEnchantment.cpp +++ b/Minecraft.World/Enchantments/WaterWorkerEnchantment.cpp @@ -1,22 +1,15 @@ #include "../Platform/stdafx.h" #include "WaterWorkerEnchantment.h" -WaterWorkerEnchantment::WaterWorkerEnchantment(int id, int frequency) : Enchantment(id, frequency, EnchantmentCategory::armor_head) -{ - setDescriptionId(IDS_ENCHANTMENT_WATER_WORKER); +WaterWorkerEnchantment::WaterWorkerEnchantment(int id, int frequency) + : Enchantment(id, frequency, EnchantmentCategory::armor_head) { + setDescriptionId(IDS_ENCHANTMENT_WATER_WORKER); } -int WaterWorkerEnchantment::getMinCost(int level) -{ - return 1; +int WaterWorkerEnchantment::getMinCost(int level) { return 1; } + +int WaterWorkerEnchantment::getMaxCost(int level) { + return getMinCost(level) + 40; } -int WaterWorkerEnchantment::getMaxCost(int level) -{ - return getMinCost(level) + 40; -} - -int WaterWorkerEnchantment::getMaxLevel() -{ - return 1; -} \ No newline at end of file +int WaterWorkerEnchantment::getMaxLevel() { return 1; } \ No newline at end of file diff --git a/Minecraft.World/Enchantments/WaterWorkerEnchantment.h b/Minecraft.World/Enchantments/WaterWorkerEnchantment.h index 29a5a53aa..cb0cc5ac2 100644 --- a/Minecraft.World/Enchantments/WaterWorkerEnchantment.h +++ b/Minecraft.World/Enchantments/WaterWorkerEnchantment.h @@ -2,12 +2,11 @@ #include "Enchantment.h" -class WaterWorkerEnchantment : public Enchantment -{ +class WaterWorkerEnchantment : public Enchantment { public: - WaterWorkerEnchantment(int id, int frequency); + WaterWorkerEnchantment(int id, int frequency); - virtual int getMinCost(int level); - virtual int getMaxCost(int level); - virtual int getMaxLevel(); + virtual int getMinCost(int level); + virtual int getMaxCost(int level); + virtual int getMaxLevel(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/BossMobPart.cpp b/Minecraft.World/Entities/BossMobPart.cpp index d86f6d6c4..bff38bceb 100644 --- a/Minecraft.World/Entities/BossMobPart.cpp +++ b/Minecraft.World/Entities/BossMobPart.cpp @@ -2,42 +2,30 @@ #include "Mobs/BossMob.h" #include "BossMobPart.h" +BossMobPart::BossMobPart(BossMob* bossMob, const std::wstring& id, float w, + float h) + : Entity(bossMob->level), bossMob(bossMob), id(id) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - -BossMobPart::BossMobPart(BossMob *bossMob, const std::wstring &id, float w, float h) : Entity(bossMob->level), bossMob( bossMob ), id( id ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - setSize(w, h); + setSize(w, h); } +void BossMobPart::defineSynchedData() {} -void BossMobPart::defineSynchedData() -{ +void BossMobPart::readAdditionalSaveData(CompoundTag* tag) {} + +void BossMobPart::addAdditonalSaveData(CompoundTag* tag) {} + +bool BossMobPart::isPickable() { return true; } + +bool BossMobPart::hurt(DamageSource* source, int damage) { + return bossMob->hurt( + std::dynamic_pointer_cast(shared_from_this()), source, + damage); } -void BossMobPart::readAdditionalSaveData(CompoundTag *tag) -{ -} - -void BossMobPart::addAdditonalSaveData(CompoundTag *tag) -{ -} - - -bool BossMobPart::isPickable() -{ - return true; -} - -bool BossMobPart::hurt(DamageSource *source, int damage) -{ - return bossMob->hurt( std::dynamic_pointer_cast( shared_from_this() ), source, damage); -} - -bool BossMobPart::is(std::shared_ptr other) -{ - return shared_from_this() == other || bossMob == other.get(); +bool BossMobPart::is(std::shared_ptr other) { + return shared_from_this() == other || bossMob == other.get(); } \ No newline at end of file diff --git a/Minecraft.World/Entities/BossMobPart.h b/Minecraft.World/Entities/BossMobPart.h index 3ed92112a..87952955c 100644 --- a/Minecraft.World/Entities/BossMobPart.h +++ b/Minecraft.World/Entities/BossMobPart.h @@ -5,23 +5,23 @@ class Level; class BossMob; -class BossMobPart : public Entity -{ +class BossMobPart : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_BOSS_MOB_PART; }; -public: - BossMob *bossMob; - const std::wstring id; + eINSTANCEOF GetType() { return eTYPE_BOSS_MOB_PART; }; - BossMobPart(BossMob *bossMob, const std::wstring &id, float w, float h); +public: + BossMob* bossMob; + const std::wstring id; + + BossMobPart(BossMob* bossMob, const std::wstring& id, float w, float h); protected: - virtual void defineSynchedData(); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void addAdditonalSaveData(CompoundTag *tag); + virtual void defineSynchedData(); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void addAdditonalSaveData(CompoundTag* tag); public: - virtual bool isPickable(); - virtual bool hurt(DamageSource *source, int damage); - virtual bool is(std::shared_ptr other); + virtual bool isPickable(); + virtual bool hurt(DamageSource* source, int damage); + virtual bool is(std::shared_ptr other); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/DoorInfo.cpp b/Minecraft.World/Entities/DoorInfo.cpp index 5cda36d0b..f1c06debf 100644 --- a/Minecraft.World/Entities/DoorInfo.cpp +++ b/Minecraft.World/Entities/DoorInfo.cpp @@ -2,68 +2,47 @@ #include "DoorInfo.h" -DoorInfo::DoorInfo(int x, int y, int z, int insideDx, int insideDy, int timeStamp) : x(x), y(y), z(z), insideDx(insideDx), insideDz(insideDy) -{ - removed = false; - bookings = 0; +DoorInfo::DoorInfo(int x, int y, int z, int insideDx, int insideDy, + int timeStamp) + : x(x), y(y), z(z), insideDx(insideDx), insideDz(insideDy) { + removed = false; + bookings = 0; - this->timeStamp = timeStamp; + this->timeStamp = timeStamp; } -int DoorInfo::distanceTo(int x2, int y2, int z2) -{ - return (int) sqrt((float)distanceToSqr(x2, y2, z2)); +int DoorInfo::distanceTo(int x2, int y2, int z2) { + return (int)sqrt((float)distanceToSqr(x2, y2, z2)); } -int DoorInfo::distanceToSqr(int x2, int y2, int z2) -{ - int dx = x2 - x; - int dy = y2 - y; - int dz = z2 - z; - return dx * dx + dy * dy + dz * dz; +int DoorInfo::distanceToSqr(int x2, int y2, int z2) { + int dx = x2 - x; + int dy = y2 - y; + int dz = z2 - z; + return dx * dx + dy * dy + dz * dz; } -int DoorInfo::distanceToInsideSqr(int x2, int y2, int z2) -{ - int dx = x2 - x - insideDx; - int dy = y2 - y; - int dz = z2 - z - insideDz; - return dx * dx + dy * dy + dz * dz; +int DoorInfo::distanceToInsideSqr(int x2, int y2, int z2) { + int dx = x2 - x - insideDx; + int dy = y2 - y; + int dz = z2 - z - insideDz; + return dx * dx + dy * dy + dz * dz; } -int DoorInfo::getIndoorX() -{ - return x + insideDx; +int DoorInfo::getIndoorX() { return x + insideDx; } + +int DoorInfo::getIndoorY() { return y; } + +int DoorInfo::getIndoorZ() { return z + insideDz; } + +bool DoorInfo::isInsideSide(int testX, int testZ) { + int vdx = testX - x; + int vdz = testZ - z; + return vdx * insideDx + vdz * insideDz >= 0; } -int DoorInfo::getIndoorY() -{ - return y; -} +void DoorInfo::resetBookingCount() { bookings = 0; } -int DoorInfo::getIndoorZ() -{ - return z + insideDz; -} +void DoorInfo::incBookingCount() { ++bookings; } -bool DoorInfo::isInsideSide(int testX, int testZ) -{ - int vdx = testX - x; - int vdz = testZ - z; - return vdx * insideDx + vdz * insideDz >= 0; -} - -void DoorInfo::resetBookingCount() -{ - bookings = 0; -} - -void DoorInfo::incBookingCount() -{ - ++bookings; -} - -int DoorInfo::getBookingsCount() -{ - return bookings; -} \ No newline at end of file +int DoorInfo::getBookingsCount() { return bookings; } \ No newline at end of file diff --git a/Minecraft.World/Entities/DoorInfo.h b/Minecraft.World/Entities/DoorInfo.h index b9382fcd0..f8befa43f 100644 --- a/Minecraft.World/Entities/DoorInfo.h +++ b/Minecraft.World/Entities/DoorInfo.h @@ -1,29 +1,28 @@ #pragma once -class DoorInfo -{ +class DoorInfo { public: - const int x, y, z; - const int insideDx, insideDz; - int timeStamp; - bool removed; + const int x, y, z; + const int insideDx, insideDz; + int timeStamp; + bool removed; private: - // this is used for mobs to see how many mobs are - // present, it's not 100% accurate but may be good enough - int bookings; + // this is used for mobs to see how many mobs are + // present, it's not 100% accurate but may be good enough + int bookings; public: - DoorInfo(int x, int y, int z, int insideDx, int insideDy, int timeStamp); + DoorInfo(int x, int y, int z, int insideDx, int insideDy, int timeStamp); - int distanceTo(int x2, int y2, int z2); - int distanceToSqr(int x2, int y2, int z2); - int distanceToInsideSqr(int x2, int y2, int z2); - int getIndoorX(); - int getIndoorY(); - int getIndoorZ(); - bool isInsideSide(int testX, int testZ); - void resetBookingCount(); - void incBookingCount(); - int getBookingsCount(); + int distanceTo(int x2, int y2, int z2); + int distanceToSqr(int x2, int y2, int z2); + int distanceToInsideSqr(int x2, int y2, int z2); + int getIndoorX(); + int getIndoorY(); + int getIndoorZ(); + bool isInsideSide(int testX, int testZ); + void resetBookingCount(); + void incBookingCount(); + int getBookingsCount(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Enemy.cpp b/Minecraft.World/Entities/Enemy.cpp index b8468d5f9..536121f1f 100644 --- a/Minecraft.World/Entities/Enemy.cpp +++ b/Minecraft.World/Entities/Enemy.cpp @@ -1,8 +1,6 @@ #include "../Platform/stdafx.h" #include "Enemy.h" - - const int Enemy::XP_REWARD_NONE = 0; const int Enemy::XP_REWARD_SMALL = 3; const int Enemy::XP_REWARD_MEDIUM = 5; diff --git a/Minecraft.World/Entities/Enemy.h b/Minecraft.World/Entities/Enemy.h index 252ab2f99..15eef2a35 100644 --- a/Minecraft.World/Entities/Enemy.h +++ b/Minecraft.World/Entities/Enemy.h @@ -3,12 +3,11 @@ class Level; -class Enemy : public Creature -{ +class Enemy : public Creature { public: - static const int XP_REWARD_NONE; - static const int XP_REWARD_SMALL; - static const int XP_REWARD_MEDIUM; - static const int XP_REWARD_LARGE; - static const int XP_REWARD_HUGE; + static const int XP_REWARD_NONE; + static const int XP_REWARD_SMALL; + static const int XP_REWARD_MEDIUM; + static const int XP_REWARD_LARGE; + static const int XP_REWARD_HUGE; }; diff --git a/Minecraft.World/Entities/Entity.cpp b/Minecraft.World/Entities/Entity.cpp index 1a9a927da..ffbef946b 100644 --- a/Minecraft.World/Entities/Entity.cpp +++ b/Minecraft.World/Entities/Entity.cpp @@ -23,41 +23,34 @@ #include "../../Minecraft.Client/Player/MultiPlayerLocalPlayer.h" #include -namespace -{ +namespace { #if defined(_WIN32) - inline void *EntityTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +inline void* EntityTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void EntityTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } +inline void EntityTlsSetValue(DWORD key, void* value) { + TlsSetValue(key, value); +} #else - pthread_key_t CreateEntityTlsKey() - { - pthread_key_t key; - const int result = pthread_key_create(&key, nullptr); - assert(result == 0); - return key; - } - - inline void *EntityTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void EntityTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } -#endif +pthread_key_t CreateEntityTlsKey() { + pthread_key_t key; + const int result = pthread_key_create(&key, nullptr); + assert(result == 0); + return key; } +inline void* EntityTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} -int Entity::entityCounter = 2048; // 4J - changed initialiser to 2048, as we are using range 0 - 2047 as special unique smaller ids for things that need network tracked +inline void EntityTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +#endif +} // namespace + +int Entity::entityCounter = + 2048; // 4J - changed initialiser to 2048, as we are using range 0 - 2047 + // as special unique smaller ids for things that need network tracked #if defined(_WIN32) DWORD Entity::tlsIdx = TlsAlloc(); #else @@ -65,332 +58,334 @@ pthread_key_t Entity::tlsIdx = CreateEntityTlsKey(); #endif // 4J - added getSmallId & freeSmallId methods -unsigned int Entity::entityIdUsedFlags[2048/32] = {0}; -unsigned int Entity::entityIdWanderFlags[2048/32] = {0}; -unsigned int Entity::entityIdRemovingFlags[2048/32] = {0}; +unsigned int Entity::entityIdUsedFlags[2048 / 32] = {0}; +unsigned int Entity::entityIdWanderFlags[2048 / 32] = {0}; +unsigned int Entity::entityIdRemovingFlags[2048 / 32] = {0}; int Entity::extraWanderIds[EXTRA_WANDER_MAX] = {0}; int Entity::extraWanderTicks = 0; int Entity::extraWanderCount = 0; -int Entity::getSmallId() -{ - unsigned int *puiUsedFlags = entityIdUsedFlags; - unsigned int *puiRemovedFlags = NULL; +int Entity::getSmallId() { + unsigned int* puiUsedFlags = entityIdUsedFlags; + unsigned int* puiRemovedFlags = NULL; - // If we are the server (we should be, if we are allocating small Ids), then check with the server if there are any small Ids which are - // still in the ServerPlayer's vectors of entities to be removed - these are used to gather up a set of entities into one network packet - // for final notification to the client that the entities are removed. We can't go re-using these small Ids yet, as otherwise we will - // potentially end up telling the client that the entity has been removed After we have already re-used its Id and created a new entity. - // This ends up with newly created client-side entities being removed by accident, causing invisible mobs. - if( reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0 ) - { - MinecraftServer *server = MinecraftServer::getInstance(); - if( server ) - { - // In some attempt to optimise this, flagEntitiesToBeRemoved most of the time shouldn't do anything at all, and in this case it - // doesn't even memset the entityIdRemovingFlags array, so we shouldn't use it if the return value is false. - bool removedFound = server->flagEntitiesToBeRemoved(entityIdRemovingFlags); - if( removedFound ) - { - // Has set up the entityIdRemovingFlags vector in this case, so we should check against this when allocating new ids -// app.DebugPrintf("getSmallId: Removed entities found\n"); - puiRemovedFlags = entityIdRemovingFlags; - } - } - } + // If we are the server (we should be, if we are allocating small Ids), then + // check with the server if there are any small Ids which are still in the + // ServerPlayer's vectors of entities to be removed - these are used to + // gather up a set of entities into one network packet for final + // notification to the client that the entities are removed. We can't go + // re-using these small Ids yet, as otherwise we will potentially end up + // telling the client that the entity has been removed After we have already + // re-used its Id and created a new entity. This ends up with newly created + // client-side entities being removed by accident, causing invisible mobs. + if (reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0) { + MinecraftServer* server = MinecraftServer::getInstance(); + if (server) { + // In some attempt to optimise this, flagEntitiesToBeRemoved most of + // the time shouldn't do anything at all, and in this case it + // doesn't even memset the entityIdRemovingFlags array, so we + // shouldn't use it if the return value is false. + bool removedFound = + server->flagEntitiesToBeRemoved(entityIdRemovingFlags); + if (removedFound) { + // Has set up the entityIdRemovingFlags vector in this case, so + // we should check against this when allocating new ids + // app.DebugPrintf("getSmallId: + //Removed entities found\n"); + puiRemovedFlags = entityIdRemovingFlags; + } + } + } - for( int i = 0; i < (2048 / 32 ); i++ ) - { - unsigned int uiFlags = *puiUsedFlags; - if( uiFlags != 0xffffffff ) - { - unsigned int uiMask = 0x80000000; - for( int j = 0; j < 32; j++ ) - { - // See comments above - now checking (if required) that these aren't newly removed entities that the clients still haven't been told about, - // so we don't reuse those ids before we should. - if( puiRemovedFlags ) - { - if( puiRemovedFlags[i] & uiMask ) - { -// app.DebugPrintf("Avoiding using ID %d (0x%x)\n", i * 32 + j,puiRemovedFlags[i]); - uiMask >>= 1; - continue; - } - } - if( ( uiFlags & uiMask ) == 0 ) - { - uiFlags |= uiMask; - *puiUsedFlags = uiFlags; - return i * 32 + j; - } - uiMask >>= 1; - } - } - puiUsedFlags++; - } + for (int i = 0; i < (2048 / 32); i++) { + unsigned int uiFlags = *puiUsedFlags; + if (uiFlags != 0xffffffff) { + unsigned int uiMask = 0x80000000; + for (int j = 0; j < 32; j++) { + // See comments above - now checking (if required) that these + // aren't newly removed entities that the clients still haven't + // been told about, so we don't reuse those ids before we + // should. + if (puiRemovedFlags) { + if (puiRemovedFlags[i] & uiMask) { + // app.DebugPrintf("Avoiding + //using ID %d (0x%x)\n", i * 32 + j,puiRemovedFlags[i]); + uiMask >>= 1; + continue; + } + } + if ((uiFlags & uiMask) == 0) { + uiFlags |= uiMask; + *puiUsedFlags = uiFlags; + return i * 32 + j; + } + uiMask >>= 1; + } + } + puiUsedFlags++; + } - app.DebugPrintf("Out of small entity Ids... possible leak?\n"); - __debugbreak(); - return -1; + app.DebugPrintf("Out of small entity Ids... possible leak?\n"); + __debugbreak(); + return -1; } -void Entity::countFlagsForPIX() -{ - int freecount = 0; - unsigned int *puiUsedFlags = entityIdUsedFlags; - for( int i = 0; i < (2048 / 32 ); i++ ) - { - unsigned int uiFlags = *puiUsedFlags; - if( uiFlags != 0xffffffff ) - { - unsigned int uiMask = 0x80000000; - for( int j = 0; j < 32; j++ ) - { - if( ( uiFlags & uiMask ) == 0 ) - { - freecount++; - } - uiMask >>= 1; - } - } - puiUsedFlags++; - } - PIXAddNamedCounter(freecount,"Small Ids free"); - PIXAddNamedCounter(2048 - freecount,"Small Ids used"); +void Entity::countFlagsForPIX() { + int freecount = 0; + unsigned int* puiUsedFlags = entityIdUsedFlags; + for (int i = 0; i < (2048 / 32); i++) { + unsigned int uiFlags = *puiUsedFlags; + if (uiFlags != 0xffffffff) { + unsigned int uiMask = 0x80000000; + for (int j = 0; j < 32; j++) { + if ((uiFlags & uiMask) == 0) { + freecount++; + } + uiMask >>= 1; + } + } + puiUsedFlags++; + } + PIXAddNamedCounter(freecount, "Small Ids free"); + PIXAddNamedCounter(2048 - freecount, "Small Ids used"); } -void Entity::resetSmallId() -{ - freeSmallId(entityId); - if( reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0 ) - { - entityId = getSmallId(); - } +void Entity::resetSmallId() { + freeSmallId(entityId); + if (reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0) { + entityId = getSmallId(); + } } -void Entity::freeSmallId(int index) -{ - if( reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0 ) return; // Don't do anything with small ids if this isn't the server thread - if( index >= 2048 ) return; // Don't do anything if this isn't a short id +void Entity::freeSmallId(int index) { + if (reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0) + return; // Don't do anything with small ids if this isn't the server + // thread + if (index >= 2048) return; // Don't do anything if this isn't a short id - unsigned int i = index / 32; - unsigned int j = index % 32; - unsigned int uiMask = ~(0x80000000 >> j); + unsigned int i = index / 32; + unsigned int j = index % 32; + unsigned int uiMask = ~(0x80000000 >> j); - entityIdUsedFlags[i] &= uiMask; - entityIdWanderFlags[i] &= uiMask; + entityIdUsedFlags[i] &= uiMask; + entityIdWanderFlags[i] &= uiMask; } -void Entity::useSmallIds() -{ - EntityTlsSetValue(tlsIdx, reinterpret_cast(static_cast(1))); +void Entity::useSmallIds() { + EntityTlsSetValue(tlsIdx, + reinterpret_cast(static_cast(1))); } -// Things also added here to be able to manage the concept of a number of extra "wandering" entities - normally path finding entities aren't allowed to -// randomly wander about once they are a certain distance away from any player, but we want to be able to (in a controlled fashion) allow some to be able -// to move so that we can determine whether they have been enclosed in some kind of farm, and so be able to better determine what shouldn't or shouldn't be despawned. +// Things also added here to be able to manage the concept of a number of extra +// "wandering" entities - normally path finding entities aren't allowed to +// randomly wander about once they are a certain distance away from any player, +// but we want to be able to (in a controlled fashion) allow some to be able to +// move so that we can determine whether they have been enclosed in some kind of +// farm, and so be able to better determine what shouldn't or shouldn't be +// despawned. -// Let the management system here know whether or not to consider this particular entity for some extra wandering -void Entity::considerForExtraWandering(bool enable) -{ - if( reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0 ) return; // Don't do anything with small ids if this isn't the server thread - if( entityId >= 2048 ) return; // Don't do anything if this isn't a short id +// Let the management system here know whether or not to consider this +// particular entity for some extra wandering +void Entity::considerForExtraWandering(bool enable) { + if (reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0) + return; // Don't do anything with small ids if this isn't the server + // thread + if (entityId >= 2048) return; // Don't do anything if this isn't a short id - unsigned int i = entityId / 32; - unsigned int j = entityId % 32; - if( enable ) - { - unsigned int uiMask = 0x80000000 >> j; - entityIdWanderFlags[i] |= uiMask; - } - else - { - unsigned int uiMask = ~(0x80000000 >> j); - entityIdWanderFlags[i] &= uiMask; - } + unsigned int i = entityId / 32; + unsigned int j = entityId % 32; + if (enable) { + unsigned int uiMask = 0x80000000 >> j; + entityIdWanderFlags[i] |= uiMask; + } else { + unsigned int uiMask = ~(0x80000000 >> j); + entityIdWanderFlags[i] &= uiMask; + } } -// Should this entity do wandering in addition to what the java code would have done? -bool Entity::isExtraWanderingEnabled() -{ - if( reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0 ) return false; // Don't do anything with small ids if this isn't the server thread - if( entityId >= 2048 ) return false; // Don't do anything if this isn't a short id +// Should this entity do wandering in addition to what the java code would have +// done? +bool Entity::isExtraWanderingEnabled() { + if (reinterpret_cast(EntityTlsGetValue(tlsIdx)) == 0) + return false; // Don't do anything with small ids if this isn't the + // server thread + if (entityId >= 2048) + return false; // Don't do anything if this isn't a short id - for( int i = 0; i < extraWanderCount; i++ ) - { - if( extraWanderIds[i] == entityId ) return true; - } - return false; + for (int i = 0; i < extraWanderCount; i++) { + if (extraWanderIds[i] == entityId) return true; + } + return false; } - -// Returns a quadrant of direction that a given entity should be moved in - this is to stop the randomness of the wandering/strolling from just making the entity double back -// on itself and thus making the determination of whether the entity has been enclosed take longer than it needs to. This function returns a quadrant from 0 to 3 -// that should be consistent within one period of an entity being considered for extra wandering, but should potentially vary between tries and between different entities. -int Entity::getWanderingQuadrant() -{ - return ( entityId + ( extraWanderTicks / EXTRA_WANDER_TICKS ) ) & 3; +// Returns a quadrant of direction that a given entity should be moved in - this +// is to stop the randomness of the wandering/strolling from just making the +// entity double back on itself and thus making the determination of whether the +// entity has been enclosed take longer than it needs to. This function returns +// a quadrant from 0 to 3 that should be consistent within one period of an +// entity being considered for extra wandering, but should potentially vary +// between tries and between different entities. +int Entity::getWanderingQuadrant() { + return (entityId + (extraWanderTicks / EXTRA_WANDER_TICKS)) & 3; } -// Every EXTRA_WANDER_TICKS ticks, attempt to find EXTRA_WANDER_MAX entity Ids from those that have been flagged as ones that should be considered for -// extra wandering -void Entity::tickExtraWandering() -{ - extraWanderTicks++; - // Time to move onto some new entities? +// Every EXTRA_WANDER_TICKS ticks, attempt to find EXTRA_WANDER_MAX entity Ids +// from those that have been flagged as ones that should be considered for extra +// wandering +void Entity::tickExtraWandering() { + extraWanderTicks++; + // Time to move onto some new entities? - if( ( extraWanderTicks % EXTRA_WANDER_TICKS == 0 ) ) - { - // printf("Updating extras: "); - // Start from the next Id after the one that we last found, or zero if we didn't find anything last time - int entityId = 0; - if( extraWanderCount ) - { - entityId = ( extraWanderIds[ extraWanderCount - 1 ] + 1 ) % 2048; - } + if ((extraWanderTicks % EXTRA_WANDER_TICKS == 0)) { + // printf("Updating extras: "); + // Start from the next Id after the one that we last found, or zero if + // we didn't find anything last time + int entityId = 0; + if (extraWanderCount) { + entityId = (extraWanderIds[extraWanderCount - 1] + 1) % 2048; + } - extraWanderCount = 0; + extraWanderCount = 0; - for( int k = 0; ( k < 2048 ) && ( extraWanderCount < EXTRA_WANDER_MAX); k++ ) - { - unsigned int i = entityId / 32; - unsigned int j = entityId % 32; - unsigned int uiMask = 0x80000000 >> j; + for (int k = 0; (k < 2048) && (extraWanderCount < EXTRA_WANDER_MAX); + k++) { + unsigned int i = entityId / 32; + unsigned int j = entityId % 32; + unsigned int uiMask = 0x80000000 >> j; - if( entityIdWanderFlags[i] & uiMask ) - { - extraWanderIds[ extraWanderCount++ ] = entityId; - // printf("%d, ", entityId); - } + if (entityIdWanderFlags[i] & uiMask) { + extraWanderIds[extraWanderCount++] = entityId; + // printf("%d, ", entityId); + } - entityId = ( entityId + 1 ) % 2048; - } - // printf("\n"); - } + entityId = (entityId + 1) % 2048; + } + // printf("\n"); + } } // 4J - added for common ctor code // Do all the default initialisations done in the java class -void Entity::_init(bool useSmallId) -{ - // 4J - changed to assign two different types of ids. A range from 0-2047 is used for things that we'll be wanting to identify over the network, - // so we should only need 11 bits rather than 32 to uniquely identify them. The rest of the range is used for anything we don't need to track like this, - // currently particles. We only ever want to allocate this type of id from the server thread, so using thread local storage to isolate this. - if( useSmallId && reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0 ) - { - entityId = getSmallId(); - } - else - { - entityId = Entity::entityCounter++; - if(entityCounter == 0x7ffffff ) entityCounter = 2048; - } +void Entity::_init(bool useSmallId) { + // 4J - changed to assign two different types of ids. A range from 0-2047 is + // used for things that we'll be wanting to identify over the network, so we + // should only need 11 bits rather than 32 to uniquely identify them. The + // rest of the range is used for anything we don't need to track like this, + // currently particles. We only ever want to allocate this type of id from + // the server thread, so using thread local storage to isolate this. + if (useSmallId && + reinterpret_cast(EntityTlsGetValue(tlsIdx)) != 0) { + entityId = getSmallId(); + } else { + entityId = Entity::entityCounter++; + if (entityCounter == 0x7ffffff) entityCounter = 2048; + } - viewScale = 1.0; + viewScale = 1.0; - blocksBuilding = false; - rider = std::weak_ptr(); - riding = nullptr; + blocksBuilding = false; + rider = std::weak_ptr(); + riding = nullptr; - //level = NULL; // Level is assigned to in the original c_tor code - xo = yo = zo = 0.0; - x = y = z = 0.0; - xd = yd = zd = 0.0; - yRot = xRot = 0.0f; - yRotO = xRotO = 0.0f; - bb = AABB::newPermanent(0, 0, 0, 0, 0, 0); // 4J Was final - onGround = false; - horizontalCollision = verticalCollision = false; - collision = false; - hurtMarked = false; - isStuckInWeb = false; + // level = NULL; // Level is assigned to in the original c_tor code + xo = yo = zo = 0.0; + x = y = z = 0.0; + xd = yd = zd = 0.0; + yRot = xRot = 0.0f; + yRotO = xRotO = 0.0f; + bb = AABB::newPermanent(0, 0, 0, 0, 0, 0); // 4J Was final + onGround = false; + horizontalCollision = verticalCollision = false; + collision = false; + hurtMarked = false; + isStuckInWeb = false; - slide = true; - removed = false; - heightOffset = 0 / 16.0f; + slide = true; + removed = false; + heightOffset = 0 / 16.0f; - bbWidth = 0.6f; - bbHeight = 1.8f; + bbWidth = 0.6f; + bbHeight = 1.8f; - walkDistO = 0; - walkDist = 0; + walkDistO = 0; + walkDist = 0; - fallDistance = 0; + fallDistance = 0; - nextStep = 1; + nextStep = 1; - xOld = yOld = zOld = 0.0; - ySlideOffset = 0; - footSize = 0.0f; - noPhysics = false; - pushthrough = 0.0f; + xOld = yOld = zOld = 0.0; + ySlideOffset = 0; + footSize = 0.0f; + noPhysics = false; + pushthrough = 0.0f; - random = new Random(); + random = new Random(); - tickCount = 0; - flameTime = 1; + tickCount = 0; + flameTime = 1; - onFire = 0; - wasInWater = false; + onFire = 0; + wasInWater = false; + invulnerableTime = 0; - invulnerableTime = 0; + firstTick = true; - firstTick = true; + customTextureUrl = L""; + customTextureUrl2 = L""; + fireImmune = false; - customTextureUrl = L""; - customTextureUrl2 = L""; + // values that need to be sent to clients in SMP + entityData = std::shared_ptr(new SynchedEntityData()); + xRideRotA = yRideRotA = 0.0; + inChunk = false; + xChunk = yChunk = zChunk = 0; + xp = yp = zp = 0; + xRotp = yRotp = 0; + noCulling = false; - fireImmune = false; + hasImpulse = false; - // values that need to be sent to clients in SMP - entityData = std::shared_ptr(new SynchedEntityData()); - - xRideRotA = yRideRotA = 0.0; - inChunk = false; - xChunk = yChunk = zChunk = 0; - xp = yp = zp = 0; - xRotp = yRotp = 0; - noCulling = false; - - hasImpulse = false; - - // 4J Added - m_ignoreVerticalCollisions = false; - m_uiAnimOverrideBitmask = 0L; + // 4J Added + m_ignoreVerticalCollisions = false; + m_uiAnimOverrideBitmask = 0L; } -Entity::Entity(Level *level, bool useSmallId) // 4J - added useSmallId parameter +Entity::Entity(Level* level, + bool useSmallId) // 4J - added useSmallId parameter { - MemSect(16); - _init(useSmallId); - MemSect(0); + MemSect(16); + _init(useSmallId); + MemSect(0); - this->level = level; - // resetPos(); - setPos(0, 0, 0); + this->level = level; + // resetPos(); + setPos(0, 0, 0); - entityData->define(DATA_SHARED_FLAGS_ID, (uint8_t) 0); - entityData->define(DATA_AIR_SUPPLY_ID, TOTAL_AIR_SUPPLY); // 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take damage when air bubbles are present if resuming game from load/autosave underwater. + entityData->define(DATA_SHARED_FLAGS_ID, (uint8_t)0); + entityData->define( + DATA_AIR_SUPPLY_ID, + TOTAL_AIR_SUPPLY); // 4J Stu - Brought forward from 1.2.3 to fix 38654 + // - Gameplay: Player will take damage when air + // bubbles are present if resuming game from + // load/autosave underwater. - // 4J Stu - We cannot call virtual functions in ctors, as at this point the object - // is of type Entity and not a derived class - //this->defineSynchedData(); + // 4J Stu - We cannot call virtual functions in ctors, as at this point the + // object is of type Entity and not a derived class + // this->defineSynchedData(); } -Entity::~Entity() -{ - freeSmallId(entityId); - delete random; - delete bb; +Entity::~Entity() { + freeSmallId(entityId); + delete random; + delete bb; } -std::shared_ptr Entity::getEntityData() -{ - return entityData; +std::shared_ptr Entity::getEntityData() { + return entityData; } /* @@ -406,1591 +401,1359 @@ return entityId; } */ -void Entity::resetPos() -{ - if (level == NULL) return; +void Entity::resetPos() { + if (level == NULL) return; - std::shared_ptr sharedThis = shared_from_this(); - while (true && y > 0) - { - setPos(x, y, z); - if (level->getCubes(sharedThis, bb)->empty()) break; - y += 1; - } + std::shared_ptr sharedThis = shared_from_this(); + while (true && y > 0) { + setPos(x, y, z); + if (level->getCubes(sharedThis, bb)->empty()) break; + y += 1; + } - xd = yd = zd = 0; - xRot = 0; + xd = yd = zd = 0; + xRot = 0; } -void Entity::remove() -{ - removed = true; +void Entity::remove() { removed = true; } + +void Entity::setSize(float w, float h) { + if (w != bbWidth || h != bbHeight) { + float oldW = bbWidth; + + bbWidth = w; + bbHeight = h; + + bb->x1 = bb->x0 + bbWidth; + bb->z1 = bb->z0 + bbWidth; + bb->y1 = bb->y0 + bbHeight; + + if (bbWidth > oldW && !firstTick && !level->isClientSide) { + move(oldW - bbWidth, 0, oldW - bbWidth); + } + } } +void Entity::setPos(EntityPos* pos) { + if (pos->move) + setPos(pos->x, pos->y, pos->z); + else + setPos(x, y, z); -void Entity::setSize(float w, float h) -{ - if (w != bbWidth || h != bbHeight) - { - float oldW = bbWidth; - - bbWidth = w; - bbHeight = h; - - bb->x1 = bb->x0 + bbWidth; - bb->z1 = bb->z0 + bbWidth; - bb->y1 = bb->y0 + bbHeight; - - if (bbWidth > oldW && !firstTick && !level->isClientSide) - { - move(oldW - bbWidth, 0, oldW - bbWidth); - } - } + if (pos->rot) + setRot(pos->yRot, pos->xRot); + else + setRot(yRot, xRot); } -void Entity::setPos(EntityPos *pos) -{ - if (pos->move) setPos(pos->x, pos->y, pos->z); - else setPos(x, y, z); +void Entity::setRot(float yRot, float xRot) { + /* JAVA: + this->yRot = yRot % 360.0f; + this->xRot = xRot % 360.0f; - if (pos->rot) setRot(pos->yRot, pos->xRot); - else setRot(yRot, xRot); + C++ Cannot do mod of non-integral type + */ + + while (yRot >= 360.0f) yRot -= 360.0f; + while (yRot < 0) yRot += 360.0f; + while (xRot >= 360.0f) xRot -= 360.0f; + + this->yRot = yRot; + this->xRot = xRot; } -void Entity::setRot(float yRot, float xRot) -{ - /* JAVA: - this->yRot = yRot % 360.0f; - this->xRot = xRot % 360.0f; - - C++ Cannot do mod of non-integral type - */ - - while( yRot >= 360.0f ) - yRot -= 360.0f; - while( yRot < 0 ) - yRot += 360.0f; - while( xRot >= 360.0f ) - xRot -= 360.0f; - - this->yRot = yRot; - this->xRot = xRot; +void Entity::setPos(double x, double y, double z) { + this->x = x; + this->y = y; + this->z = z; + float w = bbWidth / 2; + float h = bbHeight; + bb->set(x - w, y - heightOffset + ySlideOffset, z - w, x + w, + y - heightOffset + ySlideOffset + h, z + w); } +void Entity::turn(float xo, float yo) { + float xRotOld = xRot; + float yRotOld = yRot; -void Entity::setPos(double x, double y, double z) -{ - this->x = x; - this->y = y; - this->z = z; - float w = bbWidth / 2; - float h = bbHeight; - bb->set(x - w, y - heightOffset + ySlideOffset, z - w, x + w, y - heightOffset + ySlideOffset + h, z + w); + yRot += xo * 0.15f; + xRot -= yo * 0.15f; + if (xRot < -90) xRot = -90; + if (xRot > 90) xRot = 90; + + xRotO += xRot - xRotOld; + yRotO += yRot - yRotOld; } -void Entity::turn(float xo, float yo) -{ - float xRotOld = xRot; - float yRotOld = yRot; - - yRot += xo * 0.15f; - xRot -= yo * 0.15f; - if (xRot < -90) xRot = -90; - if (xRot > 90) xRot = 90; - - xRotO += xRot - xRotOld; - yRotO += yRot - yRotOld; +void Entity::interpolateTurn(float xo, float yo) { + yRot += xo * 0.15f; + xRot -= yo * 0.15f; + if (xRot < -90) xRot = -90; + if (xRot > 90) xRot = 90; } -void Entity::interpolateTurn(float xo, float yo) -{ - yRot += xo * 0.15f; - xRot -= yo * 0.15f; - if (xRot < -90) xRot = -90; - if (xRot > 90) xRot = 90; +void Entity::tick() { baseTick(); } + +void Entity::baseTick() { + // 4J Stu - Not needed + // util.Timer.push("entityBaseTick"); + + if (riding != NULL && riding->removed) riding = nullptr; + + tickCount++; + walkDistO = walkDist; + xo = x; + yo = y; + zo = z; + xRotO = xRot; + yRotO = yRot; + + if (isSprinting() && !isInWater() && canCreateParticles()) { + int xt = Mth::floor(x); + int yt = Mth::floor(y - 0.2f - this->heightOffset); + int zt = Mth::floor(z); + int t = level->getTile(xt, yt, zt); + int d = level->getData(xt, yt, zt); + if (t > 0) { + level->addParticle(PARTICLE_TILECRACK(t, d), + x + (random->nextFloat() - 0.5) * bbWidth, + bb->y0 + 0.1, + z + (random->nextFloat() - 0.5) * bbWidth, + -xd * 4, 1.5, -zd * 4); + } + } + + if (updateInWaterState()) { + if (!wasInWater && !firstTick && canCreateParticles()) { + float speed = + Mth::sqrt(xd * xd * 0.2f + yd * yd + zd * zd * 0.2f) * 0.2f; + if (speed > 1) speed = 1; + MemSect(31); + level->playSound( + shared_from_this(), eSoundType_RANDOM_SPLASH, speed, + 1 + (random->nextFloat() - random->nextFloat()) * 0.4f); + MemSect(0); + float yt = (float)Mth::floor(bb->y0); + for (int i = 0; i < 1 + bbWidth * 20; i++) { + float xo = (random->nextFloat() * 2 - 1) * bbWidth; + float zo = (random->nextFloat() * 2 - 1) * bbWidth; + level->addParticle(eParticleType_bubble, x + xo, yt + 1, z + zo, + xd, yd - random->nextFloat() * 0.2f, zd); + } + for (int i = 0; i < 1 + bbWidth * 20; i++) { + float xo = (random->nextFloat() * 2 - 1) * bbWidth; + float zo = (random->nextFloat() * 2 - 1) * bbWidth; + level->addParticle(eParticleType_splash, x + xo, yt + 1, z + zo, + xd, yd, zd); + } + } + fallDistance = 0; + wasInWater = true; + onFire = 0; + } else { + wasInWater = false; + } + + if (level->isClientSide) { + onFire = 0; + } else { + if (onFire > 0) { + if (fireImmune) { + onFire -= 4; + if (onFire < 0) onFire = 0; + } else { + if (onFire % 20 == 0) { + hurt(DamageSource::onFire, 1); + } + onFire--; + } + } + } + + if (isInLava()) { + lavaHurt(); + fallDistance *= .5f; + } + + if (y < -64) { + outOfWorld(); + } + + if (!level->isClientSide) { + setSharedFlag(FLAG_ONFIRE, onFire > 0); + setSharedFlag(FLAG_RIDING, riding != NULL); + } + + firstTick = false; + + // 4J Stu - Unused + // util.Timer.pop(); } -void Entity::tick() -{ - baseTick(); +void Entity::lavaHurt() { + if (fireImmune) { + } else { + hurt(DamageSource::lava, 4); + setOnFire(15); + } } -void Entity::baseTick() -{ - // 4J Stu - Not needed - //util.Timer.push("entityBaseTick"); - - if (riding != NULL && riding->removed) riding = nullptr; - - tickCount++; - walkDistO = walkDist; - xo = x; - yo = y; - zo = z; - xRotO = xRot; - yRotO = yRot; - - if (isSprinting() && !isInWater() && canCreateParticles()) - { - int xt = Mth::floor(x); - int yt = Mth::floor(y - 0.2f - this->heightOffset); - int zt = Mth::floor(z); - int t = level->getTile(xt, yt, zt); - int d = level->getData(xt, yt, zt); - if (t > 0) - { - level->addParticle(PARTICLE_TILECRACK(t,d), x + (random->nextFloat() - 0.5) * bbWidth, bb->y0 + 0.1, z + (random->nextFloat() - 0.5) * bbWidth, -xd * 4, 1.5, -zd * 4); - } - } - - if (updateInWaterState()) - { - if (!wasInWater && !firstTick && canCreateParticles()) - { - float speed = Mth::sqrt(xd * xd * 0.2f + yd * yd + zd * zd * 0.2f) * 0.2f; - if (speed > 1) speed = 1; - MemSect(31); - level->playSound(shared_from_this(), eSoundType_RANDOM_SPLASH, speed, 1 + (random->nextFloat() - random->nextFloat()) * 0.4f); - MemSect(0); - float yt = (float) Mth::floor(bb->y0); - for (int i = 0; i < 1 + bbWidth * 20; i++) - { - float xo = (random->nextFloat() * 2 - 1) * bbWidth; - float zo = (random->nextFloat() * 2 - 1) * bbWidth; - level->addParticle(eParticleType_bubble, x + xo, yt + 1, z + zo, xd, yd - random->nextFloat() * 0.2f, zd); - } - for (int i = 0; i < 1 + bbWidth * 20; i++) - { - float xo = (random->nextFloat() * 2 - 1) * bbWidth; - float zo = (random->nextFloat() * 2 - 1) * bbWidth; - level->addParticle(eParticleType_splash, x + xo, yt + 1, z + zo, xd, yd, zd); - } - } - fallDistance = 0; - wasInWater = true; - onFire = 0; - } - else - { - wasInWater = false; - } - - if (level->isClientSide) - { - onFire = 0; - } - else - { - if (onFire > 0) - { - if (fireImmune) - { - onFire -= 4; - if (onFire < 0) onFire = 0; - } - else - { - if (onFire % 20 == 0) - { - hurt(DamageSource::onFire, 1); - } - onFire--; - } - } - } - - if (isInLava()) - { - lavaHurt(); - fallDistance *= .5f; - } - - if (y < -64) - { - outOfWorld(); - } - - if (!level->isClientSide) - { - setSharedFlag(FLAG_ONFIRE, onFire > 0); - setSharedFlag(FLAG_RIDING, riding != NULL); - } - - firstTick = false; - - // 4J Stu - Unused - //util.Timer.pop(); +void Entity::setOnFire(int numberOfSeconds) { + int newValue = numberOfSeconds * SharedConstants::TICKS_PER_SECOND; + newValue = ProtectionEnchantment::getFireAfterDampener(shared_from_this(), + newValue); + if (onFire < newValue) { + onFire = newValue; + } } +void Entity::clearFire() { onFire = 0; } -void Entity::lavaHurt() -{ - if (fireImmune) - { - } - else - { - hurt(DamageSource::lava, 4); - setOnFire(15); - } +void Entity::outOfWorld() { remove(); } + +bool Entity::isFree(float xa, float ya, float za, float grow) { + AABB* box = bb->grow(grow, grow, grow)->cloneMove(xa, ya, za); + AABBList* aABBs = level->getCubes(shared_from_this(), box); + if (!aABBs->empty()) return false; + if (level->containsAnyLiquid(box)) return false; + return true; } -void Entity::setOnFire(int numberOfSeconds) -{ - int newValue = numberOfSeconds * SharedConstants::TICKS_PER_SECOND; - newValue = ProtectionEnchantment::getFireAfterDampener(shared_from_this(), newValue); - if (onFire < newValue) - { - onFire = newValue; - } +bool Entity::isFree(double xa, double ya, double za) { + AABB* box = bb->cloneMove(xa, ya, za); + AABBList* aABBs = level->getCubes(shared_from_this(), box); + if (!aABBs->empty()) return false; + if (level->containsAnyLiquid(box)) return false; + return true; } -void Entity::clearFire() +void Entity::move(double xa, double ya, double za, + bool noEntityCubes) // 4J - added noEntityCubes parameter { - onFire = 0; -} + if (noPhysics) { + bb->move(xa, ya, za); + x = (bb->x0 + bb->x1) / 2.0f; + y = bb->y0 + heightOffset - ySlideOffset; + z = (bb->z0 + bb->z1) / 2.0f; + return; + } -void Entity::outOfWorld() -{ - remove(); -} + ySlideOffset *= 0.4f; + double xo = x; + double zo = z; -bool Entity::isFree(float xa, float ya, float za, float grow) -{ - AABB *box = bb->grow(grow, grow, grow)->cloneMove(xa, ya, za); - AABBList *aABBs = level->getCubes(shared_from_this(), box); - if (!aABBs->empty()) return false; - if (level->containsAnyLiquid(box)) return false; - return true; -} + if (isStuckInWeb) { + isStuckInWeb = false; -bool Entity::isFree(double xa, double ya, double za) -{ - AABB *box = bb->cloneMove(xa, ya, za); - AABBList *aABBs = level->getCubes(shared_from_this(), box); - if (!aABBs->empty()) return false; - if (level->containsAnyLiquid(box)) return false; - return true; -} + xa *= 0.25f; + ya *= 0.05f; + za *= 0.25f; + xd = 0.0f; + yd = 0.0f; + zd = 0.0f; + } -void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - added noEntityCubes parameter -{ - if (noPhysics) - { - bb->move(xa, ya, za); - x = (bb->x0 + bb->x1) / 2.0f; - y = bb->y0 + heightOffset - ySlideOffset; - z = (bb->z0 + bb->z1) / 2.0f; - return; - } + double xaOrg = xa; + double yaOrg = ya; + double zaOrg = za; - ySlideOffset *= 0.4f; + AABB* bbOrg = bb->copy(); - double xo = x; - double zo = z; + bool isPlayerSneaking = + onGround && isSneaking() && + std::dynamic_pointer_cast(shared_from_this()) != NULL; - if (isStuckInWeb) - { - isStuckInWeb = false; + if (isPlayerSneaking) { + double d = 0.05; + while (xa != 0 && + level->getCubes(shared_from_this(), bb->cloneMove(xa, -1.0, 0)) + ->empty()) { + if (xa < d && xa >= -d) + xa = 0; + else if (xa > 0) + xa -= d; + else + xa += d; + xaOrg = xa; + } + while (za != 0 && + level->getCubes(shared_from_this(), bb->cloneMove(0, -1.0, za)) + ->empty()) { + if (za < d && za >= -d) + za = 0; + else if (za > 0) + za -= d; + else + za += d; + zaOrg = za; + } + while (xa != 0 && za != 0 && + level->getCubes(shared_from_this(), bb->cloneMove(xa, -1.0, za)) + ->empty()) { + if (xa < d && xa >= -d) + xa = 0; + else if (xa > 0) + xa -= d; + else + xa += d; + if (za < d && za >= -d) + za = 0; + else if (za > 0) + za -= d; + else + za += d; + xaOrg = xa; + zaOrg = za; + } + } - xa *= 0.25f; - ya *= 0.05f; - za *= 0.25f; - xd = 0.0f; - yd = 0.0f; - zd = 0.0f; - } + AABBList* aABBs = level->getCubes( + shared_from_this(), bb->expand(xa, ya, za), noEntityCubes, true); - double xaOrg = xa; - double yaOrg = ya; - double zaOrg = za; + // LAND FIRST, then x and z + AUTO_VAR(itEndAABB, aABBs->end()); - AABB *bbOrg = bb->copy(); - - bool isPlayerSneaking = onGround && isSneaking() && std::dynamic_pointer_cast(shared_from_this()) != NULL; - - if (isPlayerSneaking) - { - double d = 0.05; - while (xa != 0 && level->getCubes(shared_from_this(), bb->cloneMove(xa, -1.0, 0))->empty()) - { - if (xa < d && xa >= -d) xa = 0; - else if (xa > 0) xa -= d; - else xa += d; - xaOrg = xa; - } - while (za != 0 && level->getCubes(shared_from_this(), bb->cloneMove(0, -1.0, za))->empty()) - { - if (za < d && za >= -d) za = 0; - else if (za > 0) za -= d; - else za += d; - zaOrg = za; - } - while (xa != 0 && za != 0 && level->getCubes(shared_from_this(), bb->cloneMove(xa, -1.0, za))->empty()) - { - if (xa < d && xa >= -d) xa = 0; - else if (xa > 0) xa -= d; - else xa += d; - if (za < d && za >= -d) za = 0; - else if (za > 0) za -= d; - else za += d; - xaOrg = xa; - zaOrg = za; - } - } - - AABBList *aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za), noEntityCubes, true); - - - // LAND FIRST, then x and z - AUTO_VAR(itEndAABB, aABBs->end()); - - // 4J Stu - Particles (and possibly other entities) don't have xChunk and zChunk set, so calculate the chunk instead + // 4J Stu - Particles (and possibly other entities) don't have xChunk and + // zChunk set, so calculate the chunk instead int xc = Mth::floor(x / 16); int zc = Mth::floor(z / 16); - if(!level->isClientSide || level->reallyHasChunk(xc, zc)) - { - // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk - // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); - bb->move(0, ya, 0); - } + if (!level->isClientSide || level->reallyHasChunk(xc, zc)) { + // 4J Stu - It's horrible that the client is doing any movement at all! + // But if we don't have the chunk data then all the collision info will + // be incorrect as well + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + ya = (*it)->clipYCollide(bb, ya); + bb->move(0, ya, 0); + } - if (!slide && yaOrg != ya) - { - xa = ya = za = 0; - } + if (!slide && yaOrg != ya) { + xa = ya = za = 0; + } - bool og = onGround || (yaOrg != ya && yaOrg < 0); + bool og = onGround || (yaOrg != ya && yaOrg < 0); - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); + itEndAABB = aABBs->end(); + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + xa = (*it)->clipXCollide(bb, xa); - bb->move(xa, 0, 0); + bb->move(xa, 0, 0); - if (!slide && xaOrg != xa) - { - xa = ya = za = 0; - } + if (!slide && xaOrg != xa) { + xa = ya = za = 0; + } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); - bb->move(0, 0, za); + itEndAABB = aABBs->end(); + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + za = (*it)->clipZCollide(bb, za); + bb->move(0, 0, za); - if (!slide && zaOrg != za) - { - xa = ya = za = 0; - } + if (!slide && zaOrg != za) { + xa = ya = za = 0; + } - if (footSize > 0 && og && (isPlayerSneaking || ySlideOffset < 0.05f) && ((xaOrg != xa) || (zaOrg != za))) - { - double xaN = xa; - double yaN = ya; - double zaN = za; + if (footSize > 0 && og && (isPlayerSneaking || ySlideOffset < 0.05f) && + ((xaOrg != xa) || (zaOrg != za))) { + double xaN = xa; + double yaN = ya; + double zaN = za; - xa = xaOrg; - ya = footSize; - za = zaOrg; + xa = xaOrg; + ya = footSize; + za = zaOrg; - AABB *normal = bb->copy(); - bb->set(bbOrg); - // 4J - added extra expand, as if we don't move up by footSize by hitting a block above us, then overall we could be trying to move as much as footSize downwards, - // so we'd better include cubes under our feet in this list of things we might possibly collide with - aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za)->expand(0,-ya,0),false,true); + AABB* normal = bb->copy(); + bb->set(bbOrg); + // 4J - added extra expand, as if we don't move up by footSize by + // hitting a block above us, then overall we could be trying to move as + // much as footSize downwards, so we'd better include cubes under our + // feet in this list of things we might possibly collide with + aABBs = level->getCubes(shared_from_this(), + bb->expand(xa, ya, za)->expand(0, -ya, 0), + false, true); - // LAND FIRST, then x and z - itEndAABB = aABBs->end(); + // LAND FIRST, then x and z + itEndAABB = aABBs->end(); - if(!level->isClientSide || level->reallyHasChunk(xc, zc)) - { - // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk - // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); - bb->move(0, ya, 0); - } + if (!level->isClientSide || level->reallyHasChunk(xc, zc)) { + // 4J Stu - It's horrible that the client is doing any movement at + // all! But if we don't have the chunk data then all the collision + // info will be incorrect as well + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + ya = (*it)->clipYCollide(bb, ya); + bb->move(0, ya, 0); + } - if (!slide && yaOrg != ya) - { - xa = ya = za = 0; - } + if (!slide && yaOrg != ya) { + xa = ya = za = 0; + } + itEndAABB = aABBs->end(); + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + xa = (*it)->clipXCollide(bb, xa); + bb->move(xa, 0, 0); - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); - bb->move(xa, 0, 0); + if (!slide && xaOrg != xa) { + xa = ya = za = 0; + } - if (!slide && xaOrg != xa) - { - xa = ya = za = 0; - } + itEndAABB = aABBs->end(); + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + za = (*it)->clipZCollide(bb, za); + bb->move(0, 0, za); - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); - bb->move(0, 0, za); + if (!slide && zaOrg != za) { + xa = ya = za = 0; + } - if (!slide && zaOrg != za) - { - xa = ya = za = 0; - } + if (!slide && yaOrg != ya) { + xa = ya = za = 0; + } else { + ya = -footSize; + // LAND FIRST, then x and z + itEndAABB = aABBs->end(); + for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) + ya = (*it)->clipYCollide(bb, ya); + bb->move(0, ya, 0); + } + if (xaN * xaN + zaN * zaN >= xa * xa + za * za) { + xa = xaN; + ya = yaN; + za = zaN; + bb->set(normal); + } else { + double ss = bb->y0 - (int)bb->y0; + if (ss > 0) { + ySlideOffset += (float)(ss + 0.01); + } + } + } - if (!slide && yaOrg != ya) - { - xa = ya = za = 0; - } - else - { - ya = -footSize; - // LAND FIRST, then x and z - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); - bb->move(0, ya, 0); - } + x = (bb->x0 + bb->x1) / 2.0f; + y = bb->y0 + heightOffset - ySlideOffset; + z = (bb->z0 + bb->z1) / 2.0f; - if (xaN * xaN + zaN * zaN >= xa * xa + za * za) - { - xa = xaN; - ya = yaN; - za = zaN; - bb->set(normal); - } - else - { - double ss = bb->y0 - (int) bb->y0; - if (ss > 0) { - ySlideOffset += (float) (ss + 0.01); - } - } - } + horizontalCollision = (xaOrg != xa) || (zaOrg != za); + verticalCollision = !m_ignoreVerticalCollisions && (yaOrg != ya); + onGround = !m_ignoreVerticalCollisions && yaOrg != ya && yaOrg < 0; + collision = horizontalCollision || verticalCollision; + checkFallDamage(ya, onGround); + if (xaOrg != xa) xd = 0; + if (yaOrg != ya) yd = 0; + if (zaOrg != za) zd = 0; - x = (bb->x0 + bb->x1) / 2.0f; - y = bb->y0 + heightOffset - ySlideOffset; - z = (bb->z0 + bb->z1) / 2.0f; + double xm = x - xo; + double zm = z - zo; - horizontalCollision = (xaOrg != xa) || (zaOrg != za); - verticalCollision = !m_ignoreVerticalCollisions && (yaOrg != ya); - onGround = !m_ignoreVerticalCollisions && yaOrg != ya && yaOrg < 0; - collision = horizontalCollision || verticalCollision; - checkFallDamage(ya, onGround); + if (makeStepSound() && !isPlayerSneaking && riding == NULL) { + walkDist += (float)(sqrt(xm * xm + zm * zm) * 0.6); + int xt = Mth::floor(x); + int yt = Mth::floor(y - 0.2f - this->heightOffset); + int zt = Mth::floor(z); + int t = level->getTile(xt, yt, zt); + if (t == 0) { + int renderShape = level->getTileRenderShape(xt, yt - 1, zt); + if (renderShape == Tile::SHAPE_FENCE || + renderShape == Tile::SHAPE_WALL || + renderShape == Tile::SHAPE_FENCE_GATE) { + t = level->getTile(xt, yt - 1, zt); + } + } - if (xaOrg != xa) xd = 0; - if (yaOrg != ya) yd = 0; - if (zaOrg != za) zd = 0; + if (walkDist > nextStep && t > 0) { + nextStep = (int)walkDist + 1; + playStepSound(xt, yt, zt, t); + Tile::tiles[t]->stepOn(level, xt, yt, zt, shared_from_this()); + } + } - double xm = x - xo; - double zm = z - zo; + checkInsideTiles(); + bool water = this->isInWaterOrRain(); + if (level->containsFireTile(bb->shrink(0.001, 0.001, 0.001))) { + burn(1); + if (!water) { + onFire++; + if (onFire == 0) setOnFire(8); + } + } else { + if (onFire <= 0) { + onFire = -flameTime; + } + } - if (makeStepSound() && !isPlayerSneaking && riding == NULL) - { - walkDist += (float) ( sqrt(xm * xm + zm * zm) * 0.6 ); - int xt = Mth::floor(x); - int yt = Mth::floor(y - 0.2f - this->heightOffset); - int zt = Mth::floor(z); - int t = level->getTile(xt, yt, zt); - if (t == 0) - { - int renderShape = level->getTileRenderShape(xt, yt - 1, zt); - if (renderShape == Tile::SHAPE_FENCE || renderShape == Tile::SHAPE_WALL || renderShape == Tile::SHAPE_FENCE_GATE) - { - t = level->getTile(xt, yt - 1, zt); - } - } - - if (walkDist > nextStep && t > 0) - { - nextStep = (int) walkDist + 1; - playStepSound(xt, yt, zt, t); - Tile::tiles[t]->stepOn(level, xt, yt, zt, shared_from_this()); - } - } - - checkInsideTiles(); - - - bool water = this->isInWaterOrRain(); - if (level->containsFireTile(bb->shrink(0.001, 0.001, 0.001))) - { - burn(1); - if (!water) - { - onFire++; - if (onFire == 0) setOnFire(8); - } - } - else - { - if (onFire <= 0) - { - onFire = -flameTime; - } - } - - if (water && onFire > 0) - { - level->playSound(shared_from_this(), eSoundType_RANDOM_FIZZ, 0.7f, 1.6f + (random->nextFloat() - random->nextFloat()) * 0.4f); - onFire = -flameTime; - } + if (water && onFire > 0) { + level->playSound( + shared_from_this(), eSoundType_RANDOM_FIZZ, 0.7f, + 1.6f + (random->nextFloat() - random->nextFloat()) * 0.4f); + onFire = -flameTime; + } } -void Entity::checkInsideTiles() -{ - int x0 = Mth::floor(bb->x0 + 0.001); - int y0 = Mth::floor(bb->y0 + 0.001); - int z0 = Mth::floor(bb->z0 + 0.001); - int x1 = Mth::floor(bb->x1 - 0.001); - int y1 = Mth::floor(bb->y1 - 0.001); - int z1 = Mth::floor(bb->z1 - 0.001); +void Entity::checkInsideTiles() { + int x0 = Mth::floor(bb->x0 + 0.001); + int y0 = Mth::floor(bb->y0 + 0.001); + int z0 = Mth::floor(bb->z0 + 0.001); + int x1 = Mth::floor(bb->x1 - 0.001); + int y1 = Mth::floor(bb->y1 - 0.001); + int z1 = Mth::floor(bb->z1 - 0.001); - if (level->hasChunksAt(x0, y0, z0, x1, y1, z1)) - { - for (int x = x0; x <= x1; x++) - for (int y = y0; y <= y1; y++) - for (int z = z0; z <= z1; z++) - { - int t = level->getTile(x, y, z); - if (t > 0) - { - Tile::tiles[t]->entityInside(level, x, y, z, shared_from_this()); - } - } - } + if (level->hasChunksAt(x0, y0, z0, x1, y1, z1)) { + for (int x = x0; x <= x1; x++) + for (int y = y0; y <= y1; y++) + for (int z = z0; z <= z1; z++) { + int t = level->getTile(x, y, z); + if (t > 0) { + Tile::tiles[t]->entityInside(level, x, y, z, + shared_from_this()); + } + } + } } +void Entity::playStepSound(int xt, int yt, int zt, int t) { + const Tile::SoundType* soundType = Tile::tiles[t]->soundType; + MemSect(31); + if (GetType() == eTYPE_PLAYER) { + // should we turn off step sounds? + unsigned int uiAnimOverrideBitmask = + getAnimOverrideBitmask(); // this is masked for custom anim off, + // and force anim -void Entity::playStepSound(int xt, int yt, int zt, int t) -{ - const Tile::SoundType *soundType = Tile::tiles[t]->soundType; - MemSect(31); - if(GetType() == eTYPE_PLAYER) - { - // should we turn off step sounds? - unsigned int uiAnimOverrideBitmask=getAnimOverrideBitmask(); // this is masked for custom anim off, and force anim + if ((uiAnimOverrideBitmask & (1 << HumanoidModel::eAnim_NoLegAnim)) != + 0) { + return; + } - if(( uiAnimOverrideBitmask& (1<getTile(xt, yt + 1, zt) == Tile::topSnow_Id) - { - soundType = Tile::topSnow->soundType; - mplevel->playLocalSound((double)xt+0.5,(double)yt,(double)zt+0.5,soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - else if (!Tile::tiles[t]->material->isLiquid()) - { - mplevel->playLocalSound((double)xt+0.5,(double)yt,(double)zt+0.5,soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - } - else - { - if (level->getTile(xt, yt + 1, zt) == Tile::topSnow_Id) - { - soundType = Tile::topSnow->soundType; - level->playLocalSound((double)xt+0.5,(double)yt,(double)zt+0.5,soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - else if (!Tile::tiles[t]->material->isLiquid()) - { - level->playLocalSound((double)xt+0.5,(double)yt,(double)zt+0.5,soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - } - } - else - { - if (level->getTile(xt, yt + 1, zt) == Tile::topSnow_Id) - { - soundType = Tile::topSnow->soundType; - level->playSound(shared_from_this(), soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - else if (!Tile::tiles[t]->material->isLiquid()) - { - level->playSound(shared_from_this(), soundType->getStepSound(), soundType->getVolume() * 0.15f, soundType->getPitch()); - } - } - MemSect(0); + if (mplevel) { + if (level->getTile(xt, yt + 1, zt) == Tile::topSnow_Id) { + soundType = Tile::topSnow->soundType; + mplevel->playLocalSound( + (double)xt + 0.5, (double)yt, (double)zt + 0.5, + soundType->getStepSound(), soundType->getVolume() * 0.15f, + soundType->getPitch()); + } else if (!Tile::tiles[t]->material->isLiquid()) { + mplevel->playLocalSound( + (double)xt + 0.5, (double)yt, (double)zt + 0.5, + soundType->getStepSound(), soundType->getVolume() * 0.15f, + soundType->getPitch()); + } + } else { + if (level->getTile(xt, yt + 1, zt) == Tile::topSnow_Id) { + soundType = Tile::topSnow->soundType; + level->playLocalSound( + (double)xt + 0.5, (double)yt, (double)zt + 0.5, + soundType->getStepSound(), soundType->getVolume() * 0.15f, + soundType->getPitch()); + } else if (!Tile::tiles[t]->material->isLiquid()) { + level->playLocalSound( + (double)xt + 0.5, (double)yt, (double)zt + 0.5, + soundType->getStepSound(), soundType->getVolume() * 0.15f, + soundType->getPitch()); + } + } + } else { + if (level->getTile(xt, yt + 1, zt) == Tile::topSnow_Id) { + soundType = Tile::topSnow->soundType; + level->playSound(shared_from_this(), soundType->getStepSound(), + soundType->getVolume() * 0.15f, + soundType->getPitch()); + } else if (!Tile::tiles[t]->material->isLiquid()) { + level->playSound(shared_from_this(), soundType->getStepSound(), + soundType->getVolume() * 0.15f, + soundType->getPitch()); + } + } + MemSect(0); } -void Entity::playSound(int iSound, float volume, float pitch) -{ - level->playSound(shared_from_this(), iSound, volume, pitch); +void Entity::playSound(int iSound, float volume, float pitch) { + level->playSound(shared_from_this(), iSound, volume, pitch); } -bool Entity::makeStepSound() -{ - return true; +bool Entity::makeStepSound() { return true; } + +void Entity::checkFallDamage(double ya, bool onGround) { + if (onGround) { + if (fallDistance > 0) { + if (std::dynamic_pointer_cast(shared_from_this()) != NULL) { + int xt = Mth::floor(x); + int yt = Mth::floor(y - 0.2f - this->heightOffset); + int zt = Mth::floor(z); + int t = level->getTile(xt, yt, zt); + if (t == 0 && + level->getTile(xt, yt - 1, zt) == Tile::fence_Id) { + t = level->getTile(xt, yt - 1, zt); + } + + if (t > 0) { + Tile::tiles[t]->fallOn(level, xt, yt, zt, + shared_from_this(), fallDistance); + } + } + causeFallDamage(fallDistance); + fallDistance = 0; + } + } else { + if (ya < 0) fallDistance -= (float)ya; + } } -void Entity::checkFallDamage(double ya, bool onGround) -{ - if (onGround) - { - if (fallDistance > 0) - { - if (std::dynamic_pointer_cast(shared_from_this()) != NULL) - { - int xt = Mth::floor(x); - int yt = Mth::floor(y - 0.2f - this->heightOffset); - int zt = Mth::floor(z); - int t = level->getTile(xt, yt, zt); - if (t == 0 && level->getTile(xt, yt - 1, zt) == Tile::fence_Id) - { - t = level->getTile(xt, yt - 1, zt); - } +AABB* Entity::getCollideBox() { return NULL; } - if (t > 0) - { - Tile::tiles[t]->fallOn(level, xt, yt, zt, shared_from_this(), fallDistance); - } - } - causeFallDamage(fallDistance); - fallDistance = 0; - } - } - else - { - if (ya < 0) fallDistance -= (float) ya; - } +void Entity::burn(int dmg) { + if (!fireImmune) { + hurt(DamageSource::inFire, dmg); + } } -AABB *Entity::getCollideBox() -{ - return NULL; +bool Entity::isFireImmune() { return fireImmune; } + +void Entity::causeFallDamage(float distance) { + if (rider.lock() != NULL) rider.lock()->causeFallDamage(distance); } -void Entity::burn(int dmg) -{ - if (!fireImmune) - { - hurt(DamageSource::inFire, dmg); - } +bool Entity::isInWaterOrRain() { + return wasInWater || + (level->isRainingAt(Mth::floor(x), Mth::floor(y), Mth::floor(z))); } -bool Entity::isFireImmune() -{ - return fireImmune; +bool Entity::isInWater() { return wasInWater; } + +bool Entity::updateInWaterState() { + return level->checkAndHandleWater( + bb->grow(0, -0.4f, 0)->shrink(0.001, 0.001, 0.001), Material::water, + shared_from_this()); } -void Entity::causeFallDamage(float distance) -{ - if (rider.lock() != NULL) rider.lock()->causeFallDamage(distance); +bool Entity::isUnderLiquid(Material* material) { + double yp = y + getHeadHeight(); + int xt = Mth::floor(x); + int yt = Mth::floor( + yp); // 4J - this used to be a nested pair of floors for some reason + int zt = Mth::floor(z); + int t = level->getTile(xt, yt, zt); + if (t != 0 && Tile::tiles[t]->material == material) { + float hh = LiquidTile::getHeight(level->getData(xt, yt, zt)) - 1 / 9.0f; + float h = yt + 1 - hh; + return yp < h; + } + return false; } +float Entity::getHeadHeight() { return 0; } -bool Entity::isInWaterOrRain() -{ - return wasInWater || (level->isRainingAt( Mth::floor(x), Mth::floor(y), Mth::floor(z))); +bool Entity::isInLava() { + return level->containsMaterial(bb->grow(-0.1f, -0.4f, -0.1f), + Material::lava); } -bool Entity::isInWater() -{ - return wasInWater; -} +void Entity::moveRelative(float xa, float za, float speed) { + float dist = xa * xa + za * za; + if (dist < 0.01f * 0.01f) return; -bool Entity::updateInWaterState() -{ - return level->checkAndHandleWater(bb->grow(0, -0.4f, 0)->shrink(0.001, 0.001, 0.001), Material::water, shared_from_this()); -} + dist = sqrt(dist); + if (dist < 1) dist = 1; + dist = speed / dist; + xa *= dist; + za *= dist; -bool Entity::isUnderLiquid(Material *material) -{ - double yp = y + getHeadHeight(); - int xt = Mth::floor(x); - int yt = Mth::floor(yp); // 4J - this used to be a nested pair of floors for some reason - int zt = Mth::floor(z); - int t = level->getTile(xt, yt, zt); - if (t != 0 && Tile::tiles[t]->material == material) { - float hh = LiquidTile::getHeight(level->getData(xt, yt, zt)) - 1 / 9.0f; - float h = yt + 1 - hh; - return yp < h; - } - return false; -} + float sinVar = Mth::sin(yRot * PI / 180); + float cosVar = Mth::cos(yRot * PI / 180); -float Entity::getHeadHeight() -{ - return 0; -} - -bool Entity::isInLava() -{ - return level->containsMaterial(bb->grow(-0.1f, -0.4f, -0.1f), Material::lava); -} - -void Entity::moveRelative(float xa, float za, float speed) -{ - float dist = xa * xa + za * za; - if (dist < 0.01f * 0.01f) return; - - dist = sqrt(dist); - if (dist < 1) dist = 1; - dist = speed / dist; - xa *= dist; - za *= dist; - - float sinVar = Mth::sin(yRot * PI / 180); - float cosVar = Mth::cos(yRot * PI / 180); - - xd += xa * cosVar - za * sinVar; - zd += za * cosVar + xa * sinVar; + xd += xa * cosVar - za * sinVar; + zd += za * cosVar + xa * sinVar; } // 4J - change brought forward from 1.8.2 -int Entity::getLightColor(float a) -{ - int xTile = Mth::floor(x); - int zTile = Mth::floor(z); +int Entity::getLightColor(float a) { + int xTile = Mth::floor(x); + int zTile = Mth::floor(z); - if (level->hasChunkAt(xTile, 0, zTile)) - { - double hh = (bb->y1 - bb->y0) * 0.66; - int yTile = Mth::floor(y - this->heightOffset + hh); - return level->getLightColor(xTile, yTile, zTile, 0); - } - return 0; + if (level->hasChunkAt(xTile, 0, zTile)) { + double hh = (bb->y1 - bb->y0) * 0.66; + int yTile = Mth::floor(y - this->heightOffset + hh); + return level->getLightColor(xTile, yTile, zTile, 0); + } + return 0; } // 4J - changes brought forward from 1.8.2 -float Entity::getBrightness(float a) -{ - int xTile = Mth::floor(x); - int zTile = Mth::floor(z); - if (level->hasChunkAt(xTile, 0, zTile)) - { - double hh = (bb->y1 - bb->y0) * 0.66; - int yTile = Mth::floor(y - this->heightOffset + hh); - return level->getBrightness(xTile, yTile, zTile); - } - return 0; +float Entity::getBrightness(float a) { + int xTile = Mth::floor(x); + int zTile = Mth::floor(z); + if (level->hasChunkAt(xTile, 0, zTile)) { + double hh = (bb->y1 - bb->y0) * 0.66; + int yTile = Mth::floor(y - this->heightOffset + hh); + return level->getBrightness(xTile, yTile, zTile); + } + return 0; } -void Entity::setLevel(Level *level) -{ - this->level = level; +void Entity::setLevel(Level* level) { this->level = level; } + +void Entity::absMoveTo(double x, double y, double z, float yRot, float xRot) { + this->xo = this->x = x; + this->yo = this->y = y; + this->zo = this->z = z; + this->yRotO = this->yRot = yRot; + this->xRotO = this->xRot = xRot; + ySlideOffset = 0; + + double yRotDiff = yRotO - yRot; + if (yRotDiff < -180) yRotO += 360; + if (yRotDiff >= 180) yRotO -= 360; + this->setPos(this->x, this->y, this->z); + this->setRot(yRot, xRot); } -void Entity::absMoveTo(double x, double y, double z, float yRot, float xRot) -{ - this->xo = this->x = x; - this->yo = this->y = y; - this->zo = this->z = z; - this->yRotO = this->yRot = yRot; - this->xRotO = this->xRot = xRot; - ySlideOffset = 0; - - double yRotDiff = yRotO - yRot; - if (yRotDiff < -180) yRotO += 360; - if (yRotDiff >= 180) yRotO -= 360; - this->setPos(this->x, this->y, this->z); - this->setRot(yRot, xRot); +void Entity::moveTo(double x, double y, double z, float yRot, float xRot) { + this->xOld = this->xo = this->x = x; + this->yOld = this->yo = this->y = y + heightOffset; + this->zOld = this->zo = this->z = z; + this->yRot = yRot; + this->xRot = xRot; + this->setPos(this->x, this->y, this->z); } -void Entity::moveTo(double x, double y, double z, float yRot, float xRot) -{ - this->xOld = this->xo = this->x = x; - this->yOld = this->yo = this->y = y + heightOffset; - this->zOld = this->zo = this->z = z; - this->yRot = yRot; - this->xRot = xRot; - this->setPos(this->x, this->y, this->z); +float Entity::distanceTo(std::shared_ptr e) { + float xd = (float)(x - e->x); + float yd = (float)(y - e->y); + float zd = (float)(z - e->z); + return sqrt(xd * xd + yd * yd + zd * zd); } -float Entity::distanceTo(std::shared_ptr e) -{ - float xd = (float) (x - e->x); - float yd = (float) (y - e->y); - float zd = (float) (z - e->z); - return sqrt(xd * xd + yd * yd + zd * zd); +double Entity::distanceToSqr(double x2, double y2, double z2) { + double xd = (x - x2); + double yd = (y - y2); + double zd = (z - z2); + return xd * xd + yd * yd + zd * zd; } -double Entity::distanceToSqr(double x2, double y2, double z2) -{ - double xd = (x - x2); - double yd = (y - y2); - double zd = (z - z2); - return xd * xd + yd * yd + zd * zd; +double Entity::distanceTo(double x2, double y2, double z2) { + double xd = (x - x2); + double yd = (y - y2); + double zd = (z - z2); + return sqrt(xd * xd + yd * yd + zd * zd); } -double Entity::distanceTo(double x2, double y2, double z2) -{ - double xd = (x - x2); - double yd = (y - y2); - double zd = (z - z2); - return sqrt(xd * xd + yd * yd + zd * zd); +double Entity::distanceToSqr(std::shared_ptr e) { + double xd = x - e->x; + double yd = y - e->y; + double zd = z - e->z; + return xd * xd + yd * yd + zd * zd; } -double Entity::distanceToSqr(std::shared_ptr e) -{ - double xd = x - e->x; - double yd = y - e->y; - double zd = z - e->z; - return xd * xd + yd * yd + zd * zd; +void Entity::playerTouch(std::shared_ptr player) {} + +void Entity::push(std::shared_ptr e) { + if (e->rider.lock().get() == this || e->riding.get() == this) return; + + double xa = e->x - x; + double za = e->z - z; + + double dd = Mth::asbMax(xa, za); + + if (dd >= 0.01f) { + dd = sqrt(dd); + xa /= dd; + za /= dd; + + double pow = 1 / dd; + if (pow > 1) pow = 1; + xa *= pow; + za *= pow; + + xa *= 0.05f; + za *= 0.05f; + + xa *= 1 - pushthrough; + za *= 1 - pushthrough; + + this->push(-xa, 0, -za); + e->push(xa, 0, za); + } } -void Entity::playerTouch(std::shared_ptr player) -{ +void Entity::push(double xa, double ya, double za) { + xd += xa; + yd += ya; + zd += za; + this->hasImpulse = true; } -void Entity::push(std::shared_ptr e) -{ - if (e->rider.lock().get() == this || e->riding.get() == this) return; +void Entity::markHurt() { this->hurtMarked = true; } - double xa = e->x - x; - double za = e->z - z; - - double dd = Mth::asbMax(xa, za); - - if (dd >= 0.01f) - { - dd = sqrt(dd); - xa /= dd; - za /= dd; - - double pow = 1 / dd; - if (pow > 1) pow = 1; - xa *= pow; - za *= pow; - - xa *= 0.05f; - za *= 0.05f; - - xa *= 1 - pushthrough; - za *= 1 - pushthrough; - - this->push(-xa, 0, -za); - e->push(xa, 0, za); - } +bool Entity::hurt(DamageSource* source, int damage) { + markHurt(); + return false; } -void Entity::push(double xa, double ya, double za) -{ - xd += xa; - yd += ya; - zd += za; - this->hasImpulse = true; +bool Entity::intersects(double x0, double y0, double z0, double x1, double y1, + double z1) { + return bb->intersects(x0, y0, z0, x1, y1, z1); } +bool Entity::isPickable() { return false; } -void Entity::markHurt() -{ - this->hurtMarked = true; +bool Entity::isPushable() { return false; } + +bool Entity::isShootable() { return false; } + +void Entity::awardKillScore(std::shared_ptr victim, int score) {} + +bool Entity::shouldRender(Vec3* c) { + double xd = x - c->x; + double yd = y - c->y; + double zd = z - c->z; + double distance = xd * xd + yd * yd + zd * zd; + return shouldRenderAtSqrDistance(distance); } - -bool Entity::hurt(DamageSource *source, int damage) -{ - markHurt(); - return false; -} - -bool Entity::intersects(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return bb->intersects(x0, y0, z0, x1, y1, z1); -} - -bool Entity::isPickable() -{ - return false; -} - -bool Entity::isPushable() -{ - return false; -} - -bool Entity::isShootable() -{ - return false; -} - -void Entity::awardKillScore(std::shared_ptr victim, int score) -{ -} - -bool Entity::shouldRender(Vec3 *c) -{ - double xd = x - c->x; - double yd = y - c->y; - double zd = z - c->z; - double distance = xd * xd + yd * yd + zd * zd; - return shouldRenderAtSqrDistance(distance); -} - -bool Entity::shouldRenderAtSqrDistance(double distance) -{ - double size = bb->getSize(); - size *= 64.0f * viewScale; - return distance < size * size; +bool Entity::shouldRenderAtSqrDistance(double distance) { + double size = bb->getSize(); + size *= 64.0f * viewScale; + return distance < size * size; } // 4J - used to be std::wstring return type, returning L"" -int Entity::getTexture() +int Entity::getTexture() { return -1; } + +bool Entity::isCreativeModeAllowed() { return false; } + +bool Entity::save(CompoundTag* entityTag) { + std::wstring id = getEncodeId(); + if (removed || id.empty()) { + return false; + } + // TODO Is this fine to be casting to a non-const char pointer? + entityTag->putString(L"id", id); + saveWithoutId(entityTag); + return true; +} + +void Entity::saveWithoutId(CompoundTag* entityTag) { + entityTag->put(L"Pos", newDoubleList(3, x, y + ySlideOffset, z)); + entityTag->put(L"Motion", newDoubleList(3, xd, yd, zd)); + entityTag->put(L"Rotation", newFloatList(2, yRot, xRot)); + + entityTag->putFloat(L"FallDistance", fallDistance); + entityTag->putShort(L"Fire", (short)onFire); + entityTag->putShort(L"Air", (short)getAirSupply()); + entityTag->putBoolean(L"OnGround", onGround); + + addAdditonalSaveData(entityTag); +} + +void Entity::load(CompoundTag* tag) { + // 4jcraft changed c style cast of templated class + // to getting the actual type and casting when needed + ListTag* pos = tag->getList(L"Pos"); + ListTag* motion = tag->getList(L"Motion"); + ListTag* rotation = tag->getList(L"Rotation"); + + xd = ((DoubleTag*)motion->get(0))->data; + yd = ((DoubleTag*)motion->get(1))->data; + zd = ((DoubleTag*)motion->get(2))->data; + + if (abs(xd) > 10.0) { + xd = 0; + } + if (abs(yd) > 10.0) { + yd = 0; + } + if (abs(zd) > 10.0) { + zd = 0; + } + + xo = xOld = x = ((DoubleTag*)pos->get(0))->data; + yo = yOld = y = ((DoubleTag*)pos->get(1))->data; + zo = zOld = z = ((DoubleTag*)pos->get(2))->data; + + yRotO = yRot = ((FloatTag*)rotation->get(0))->data; + xRotO = xRot = ((FloatTag*)rotation->get(1))->data; + + fallDistance = tag->getFloat(L"FallDistance"); + onFire = tag->getShort(L"Fire"); + setAirSupply(tag->getShort(L"Air")); + onGround = tag->getBoolean(L"OnGround"); + + setPos(x, y, z); + setRot(yRot, xRot); + + readAdditionalSaveData(tag); +} + +const std::wstring Entity::getEncodeId() { + return EntityIO::getEncodeId(shared_from_this()); +} + +ListTag* Entity::newDoubleList(unsigned int number, + double firstValue, ...) { + ListTag* res = new ListTag(); + + // Add the first parameter to the ListTag + res->add(new DoubleTag(L"", firstValue)); + + va_list vl; + va_start(vl, firstValue); + + double val; + + for (unsigned int i = 1; i < number; i++) { + val = va_arg(vl, double); + res->add(new DoubleTag(L"", val)); + } + + va_end(vl); + + return res; +} + +ListTag* Entity::newFloatList(unsigned int number, float firstValue, + float secondValue) { + ListTag* res = new ListTag(); + + // Add the first parameter to the ListTag + res->add(new FloatTag(L"", firstValue)); + + // TODO - 4J Stu For some reason the va_list wasn't working correctly here + // We only make a list of two floats so just overriding and not using + // va_list + res->add(new FloatTag(L"", secondValue)); + + /* + va_list vl; + va_start(vl,firstValue); + + float val; + + for (unsigned int i = 1; i < number; i++) + { + val = va_arg(vl,float); + res->add(new FloatTag(val)); + } + va_end(vl); + */ + return res; +} + +float Entity::getShadowHeightOffs() { return bbHeight / 2; } + +std::shared_ptr Entity::spawnAtLocation(int resource, int count) { + return spawnAtLocation(resource, count, 0); +} + +std::shared_ptr Entity::spawnAtLocation(int resource, int count, + float yOffs) { + return spawnAtLocation( + std::shared_ptr(new ItemInstance(resource, count, 0)), + yOffs); +} + +std::shared_ptr Entity::spawnAtLocation( + std::shared_ptr itemInstance, float yOffs) { + std::shared_ptr ie = std::shared_ptr( + new ItemEntity(level, x, y + yOffs, z, itemInstance)); + ie->throwTime = 10; + level->addEntity(ie); + return ie; +} + +bool Entity::isAlive() { return !removed; } + +bool Entity::isInWall() { + for (int i = 0; i < 8; i++) { + float xo = ((i >> 0) % 2 - 0.5f) * bbWidth * 0.8f; + float yo = ((i >> 1) % 2 - 0.5f) * 0.1f; + float zo = ((i >> 2) % 2 - 0.5f) * bbWidth * 0.8f; + int xt = Mth::floor(x + xo); + int yt = Mth::floor(y + this->getHeadHeight() + yo); + int zt = Mth::floor(z + zo); + if (level->isSolidBlockingTile(xt, yt, zt)) { + return true; + } + } + return false; +} + +bool Entity::interact(std::shared_ptr player) { return false; } + +AABB* Entity::getCollideAgainstBox(std::shared_ptr entity) { + return NULL; +} + +void Entity::rideTick() { + if (riding->removed) { + riding = nullptr; + return; + } + xd = yd = zd = 0; + tick(); + + if (riding == NULL) return; + + // Sets riders old&new position to it's mount's old&new position (plus the + // ride y-seperatation). + riding->positionRider(); + + yRideRotA += (riding->yRot - riding->yRotO); + xRideRotA += (riding->xRot - riding->xRotO); + + // Wrap rotation angles. + while (yRideRotA >= 180) yRideRotA -= 360; + while (yRideRotA < -180) yRideRotA += 360; + while (xRideRotA >= 180) xRideRotA -= 360; + while (xRideRotA < -180) xRideRotA += 360; + + double yra = yRideRotA * 0.5; + double xra = xRideRotA * 0.5; + + // Cap rotation speed. + float max = 10; + if (yra > max) yra = max; + if (yra < -max) yra = -max; + if (xra > max) xra = max; + if (xra < -max) xra = -max; + + yRideRotA -= yra; + xRideRotA -= xra; + + yRot += (float)yra; + xRot += (float)xra; +} + +void Entity::positionRider() { + std::shared_ptr lockedRider = rider.lock(); + if (lockedRider) { + std::shared_ptr player = + std::dynamic_pointer_cast(lockedRider); + if (!(player && player->isLocalPlayer())) { + lockedRider->xOld = xOld; + lockedRider->yOld = + yOld + getRideHeight() + lockedRider->getRidingHeight(); + lockedRider->zOld = zOld; + } + lockedRider->setPos( + x, y + getRideHeight() + lockedRider->getRidingHeight(), z); + } +} + +double Entity::getRidingHeight() { return heightOffset; } + +double Entity::getRideHeight() { return bbHeight * .75; } + +void Entity::ride(std::shared_ptr e) { + xRideRotA = 0; + yRideRotA = 0; + + if (e == NULL) { + if (riding != NULL) { + // 4J Stu - Position should already be updated before the + // SetRidingPacket comes in + if (!level->isClientSide) + moveTo(riding->x, riding->bb->y0 + riding->bbHeight, riding->z, + yRot, xRot); + riding->rider = std::weak_ptr(); + } + riding = nullptr; + return; + } + if (riding != NULL) { + riding->rider = std::weak_ptr(); + } + riding = e; + e->rider = shared_from_this(); +} + +// 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting +// the minecart in a tight corridor damages the player +void Entity::findStandUpPosition(std::shared_ptr vehicle) { + AABB* boundingBox; + double fallbackX = vehicle->x; + double fallbackY = vehicle->bb->y0 + vehicle->bbHeight; + double fallbackZ = vehicle->z; + + for (double xDiff = -1.5; xDiff < 2; xDiff += 1.5) { + for (double zDiff = -1.5; zDiff < 2; zDiff += 1.5) { + if (xDiff == 0 && zDiff == 0) { + continue; + } + + int xToInt = (int)(this->x + xDiff); + int zToInt = (int)(this->z + zDiff); + + // 4J Stu - Added loop over y to restaring the bb into 2 block high + // spaces if required (eg the track block plus 1 air block above it + // for minecarts) + for (double yDiff = 1.0; yDiff >= 0; yDiff -= 0.5) { + boundingBox = this->bb->cloneMove(xDiff, yDiff, zDiff); + + if (level->getTileCubes(boundingBox, true)->size() == 0) { + if (level->isTopSolidBlocking( + xToInt, (int)(y - (1 - yDiff)), zToInt)) { + this->moveTo(this->x + xDiff, this->y + yDiff, + this->z + zDiff, yRot, xRot); + return; + } else if (level->isTopSolidBlocking( + xToInt, (int)(y - (1 - yDiff)) - 1, + zToInt) || + level->getMaterial(xToInt, + (int)(y - (1 - yDiff)) - 1, + zToInt) == Material::water) { + fallbackX = x + xDiff; + fallbackY = y + yDiff; + fallbackZ = z + zDiff; + } + } + } + } + } + + this->moveTo(fallbackX, fallbackY, fallbackZ, yRot, xRot); +} + +void Entity::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + setPos(x, y, z); + setRot(yRot, xRot); + + // 4J - don't know what this special y collision is specifically for, but + // its definitely bad news for arrows as they are actually Meant to + // intersect the geometry they land in slightly. + if (GetType() != eTYPE_ARROW) { + AABBList* collisions = level->getCubes( + shared_from_this(), bb->shrink(1 / 32.0, 0, 1 / 32.0)); + if (!collisions->empty()) { + double yTop = 0; + AUTO_VAR(itEnd, collisions->end()); + for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) { + AABB* ab = *it; // collisions->at(i); + if (ab->y1 > yTop) yTop = ab->y1; + } + + y += yTop - bb->y0; + setPos(x, y, z); + } + } +} + +float Entity::getPickRadius() { return 0.1f; } + +Vec3* Entity::getLookAngle() { return NULL; } + +void Entity::handleInsidePortal() {} + +void Entity::lerpMotion(double xd, double yd, double zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; +} + +void Entity::handleEntityEvent(uint8_t eventId) {} + +void Entity::animateHurt() {} + +void Entity::prepareCustomTextures() {} + +ItemInstanceArray Entity::getEquipmentSlots() // ItemInstance[] { - return -1; + return ItemInstanceArray(); // Default ctor creates NULL internal array } -bool Entity::isCreativeModeAllowed() -{ - return false; -} - -bool Entity::save(CompoundTag *entityTag) -{ - std::wstring id = getEncodeId(); - if (removed || id.empty() ) - { - return false; - } - // TODO Is this fine to be casting to a non-const char pointer? - entityTag->putString(L"id", id ); - saveWithoutId(entityTag); - return true; -} - -void Entity::saveWithoutId(CompoundTag *entityTag) -{ - entityTag->put(L"Pos", newDoubleList(3, x, y + ySlideOffset, z)); - entityTag->put(L"Motion", newDoubleList(3, xd, yd, zd)); - entityTag->put(L"Rotation", newFloatList(2, yRot, xRot)); - - entityTag->putFloat(L"FallDistance", fallDistance); - entityTag->putShort(L"Fire", (short) onFire); - entityTag->putShort(L"Air", (short) getAirSupply()); - entityTag->putBoolean(L"OnGround", onGround); - - addAdditonalSaveData(entityTag); -} - -void Entity::load(CompoundTag *tag) -{ - // 4jcraft changed c style cast of templated class - // to getting the actual type and casting when needed - ListTag *pos = tag->getList(L"Pos"); - ListTag *motion = tag->getList(L"Motion"); - ListTag *rotation = tag->getList(L"Rotation"); - - xd = ((DoubleTag*)motion->get(0))->data; - yd = ((DoubleTag*)motion->get(1))->data; - zd = ((DoubleTag*)motion->get(2))->data; - - if (abs(xd) > 10.0) - { - xd = 0; - } - if (abs(yd) > 10.0) - { - yd = 0; - } - if (abs(zd) > 10.0) - { - zd = 0; - } - - xo = xOld = x = ((DoubleTag*)pos->get(0))->data; - yo = yOld = y = ((DoubleTag*)pos->get(1))->data; - zo = zOld = z = ((DoubleTag*)pos->get(2))->data; - - yRotO = yRot = ((FloatTag*)rotation->get(0))->data; - xRotO = xRot = ((FloatTag*)rotation->get(1))->data; - - fallDistance = tag->getFloat(L"FallDistance"); - onFire = tag->getShort(L"Fire"); - setAirSupply(tag->getShort(L"Air")); - onGround = tag->getBoolean(L"OnGround"); - - setPos(x, y, z); - setRot(yRot, xRot); - - readAdditionalSaveData(tag); -} - - -const std::wstring Entity::getEncodeId() -{ - return EntityIO::getEncodeId( shared_from_this() ); -} - -ListTag *Entity::newDoubleList(unsigned int number, double firstValue, ...) -{ - ListTag *res = new ListTag(); - - // Add the first parameter to the ListTag - res->add( new DoubleTag(L"", firstValue ) ); - - va_list vl; - va_start(vl,firstValue); - - double val; - - for (unsigned int i=1;iadd(new DoubleTag(L"", val)); - } - - va_end(vl); - - return res; -} - -ListTag *Entity::newFloatList(unsigned int number, float firstValue, float secondValue) -{ - ListTag *res = new ListTag(); - - // Add the first parameter to the ListTag - res->add( new FloatTag( L"", firstValue ) ); - - // TODO - 4J Stu For some reason the va_list wasn't working correctly here - // We only make a list of two floats so just overriding and not using va_list - res->add( new FloatTag( L"", secondValue ) ); - - /* - va_list vl; - va_start(vl,firstValue); - - float val; - - for (unsigned int i = 1; i < number; i++) - { - val = va_arg(vl,float); - res->add(new FloatTag(val)); - } - va_end(vl); - */ - return res; -} - -float Entity::getShadowHeightOffs() -{ - return bbHeight / 2; -} - -std::shared_ptr Entity::spawnAtLocation(int resource, int count) -{ - return spawnAtLocation(resource, count, 0); -} - -std::shared_ptr Entity::spawnAtLocation(int resource, int count, float yOffs) -{ - return spawnAtLocation(std::shared_ptr( new ItemInstance(resource, count, 0) ), yOffs); -} - -std::shared_ptr Entity::spawnAtLocation(std::shared_ptr itemInstance, float yOffs) -{ - std::shared_ptr ie = std::shared_ptr( new ItemEntity(level, x, y + yOffs, z, itemInstance) ); - ie->throwTime = 10; - level->addEntity(ie); - return ie; -} - -bool Entity::isAlive() -{ - return !removed; -} - -bool Entity::isInWall() -{ - for (int i = 0; i < 8; i++) - { - float xo = ((i >> 0) % 2 - 0.5f) * bbWidth * 0.8f; - float yo = ((i >> 1) % 2 - 0.5f) * 0.1f; - float zo = ((i >> 2) % 2 - 0.5f) * bbWidth * 0.8f; - int xt = Mth::floor(x + xo); - int yt = Mth::floor(y + this->getHeadHeight() + yo); - int zt = Mth::floor(z + zo); - if (level->isSolidBlockingTile(xt, yt, zt)) - { - return true; - } - } - return false; -} - -bool Entity::interact(std::shared_ptr player) -{ - return false; -} - -AABB *Entity::getCollideAgainstBox(std::shared_ptr entity) -{ - return NULL; -} - -void Entity::rideTick() -{ - if (riding->removed) - { - riding = nullptr; - return; - } - xd = yd = zd = 0; - tick(); - - if (riding == NULL) return; - - // Sets riders old&new position to it's mount's old&new position (plus the ride y-seperatation). - riding->positionRider(); - - yRideRotA += (riding->yRot - riding->yRotO); - xRideRotA += (riding->xRot - riding->xRotO); - - // Wrap rotation angles. - while (yRideRotA >= 180) yRideRotA -= 360; - while (yRideRotA < -180) yRideRotA += 360; - while (xRideRotA >= 180) xRideRotA -= 360; - while (xRideRotA < -180) xRideRotA += 360; - - double yra = yRideRotA * 0.5; - double xra = xRideRotA * 0.5; - - // Cap rotation speed. - float max = 10; - if (yra > max) yra = max; - if (yra < -max) yra = -max; - if (xra > max) xra = max; - if (xra < -max) xra = -max; - - yRideRotA -= yra; - xRideRotA -= xra; - - yRot += (float) yra; - xRot += (float) xra; -} - -void Entity::positionRider() -{ - std::shared_ptr lockedRider = rider.lock(); - if( lockedRider ) - { - std::shared_ptr player = std::dynamic_pointer_cast(lockedRider); - if (!(player && player->isLocalPlayer())) - { - lockedRider->xOld = xOld; - lockedRider->yOld = yOld + getRideHeight() + lockedRider->getRidingHeight(); - lockedRider->zOld = zOld; - } - lockedRider->setPos(x, y + getRideHeight() + lockedRider->getRidingHeight(), z); - } -} - -double Entity::getRidingHeight() -{ - return heightOffset; -} - -double Entity::getRideHeight() -{ - return bbHeight * .75; -} +// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer +// Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for +// other players in online game +void Entity::setEquippedSlot(int slot, std::shared_ptr item) {} -void Entity::ride(std::shared_ptr e) -{ - xRideRotA = 0; - yRideRotA = 0; - - if (e == NULL) - { - if (riding != NULL) - { - // 4J Stu - Position should already be updated before the SetRidingPacket comes in - if(!level->isClientSide) moveTo(riding->x, riding->bb->y0 + riding->bbHeight, riding->z, yRot, xRot); - riding->rider = std::weak_ptr(); - } - riding = nullptr; - return; - } - if (riding != NULL) - { - riding->rider = std::weak_ptr(); - } - riding = e; - e->rider = shared_from_this(); -} +bool Entity::isOnFire() { return onFire > 0 || getSharedFlag(FLAG_ONFIRE); } -// 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting the minecart in a tight corridor damages the player -void Entity::findStandUpPosition(std::shared_ptr vehicle) -{ - AABB *boundingBox; - double fallbackX = vehicle->x; - double fallbackY = vehicle->bb->y0 + vehicle->bbHeight; - double fallbackZ = vehicle->z; - - for (double xDiff = -1.5; xDiff < 2; xDiff += 1.5) - { - for (double zDiff = -1.5; zDiff < 2; zDiff += 1.5) - { - if (xDiff == 0 && zDiff == 0) - { - continue; - } - - int xToInt = (int) (this->x + xDiff); - int zToInt = (int) (this->z + zDiff); - - // 4J Stu - Added loop over y to restaring the bb into 2 block high spaces if required (eg the track block plus 1 air block above it for minecarts) - for(double yDiff = 1.0; yDiff >= 0; yDiff -= 0.5) - { - boundingBox = this->bb->cloneMove(xDiff, yDiff, zDiff); - - if (level->getTileCubes(boundingBox,true)->size() == 0) - { - if (level->isTopSolidBlocking(xToInt, (int) (y - (1-yDiff)), zToInt)) - { - this->moveTo(this->x + xDiff, this->y + yDiff, this->z + zDiff, yRot, xRot); - return; - } - else if (level->isTopSolidBlocking(xToInt, (int) (y - (1-yDiff)) - 1, zToInt) || level->getMaterial(xToInt, (int) (y - (1-yDiff)) - 1, zToInt) == Material::water) - { - fallbackX = x + xDiff; - fallbackY = y + yDiff; - fallbackZ = z + zDiff; - } - } - } - } - } - - this->moveTo(fallbackX, fallbackY, fallbackZ, yRot, xRot); -} +bool Entity::isRiding() { return riding != NULL || getSharedFlag(FLAG_RIDING); } -void Entity::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - setPos(x, y, z); - setRot(yRot, xRot); - - // 4J - don't know what this special y collision is specifically for, but its definitely bad news - // for arrows as they are actually Meant to intersect the geometry they land in slightly. - if( GetType() != eTYPE_ARROW ) - { - AABBList *collisions = level->getCubes(shared_from_this(), bb->shrink(1 / 32.0, 0, 1 / 32.0)); - if (!collisions->empty()) - { - double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) - { - AABB *ab = *it; //collisions->at(i); - if (ab->y1 > yTop) yTop = ab->y1; - } - - y += yTop - bb->y0; - setPos(x, y, z); - } - } -} +bool Entity::isSneaking() { return getSharedFlag(FLAG_SNEAKING); } -float Entity::getPickRadius() -{ - return 0.1f; -} +void Entity::setSneaking(bool value) { setSharedFlag(FLAG_SNEAKING, value); } -Vec3 *Entity::getLookAngle() -{ - return NULL; -} +bool Entity::isIdle() { return getSharedFlag(FLAG_IDLEANIM); } -void Entity::handleInsidePortal() -{ -} +void Entity::setIsIdle(bool value) { setSharedFlag(FLAG_IDLEANIM, value); } -void Entity::lerpMotion(double xd, double yd, double zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; -} +bool Entity::isSprinting() { return getSharedFlag(FLAG_SPRINTING); } -void Entity::handleEntityEvent(uint8_t eventId) -{ -} - -void Entity::animateHurt() -{ -} +void Entity::setSprinting(bool value) { setSharedFlag(FLAG_SPRINTING, value); } -void Entity::prepareCustomTextures() -{ -} - -ItemInstanceArray Entity::getEquipmentSlots() // ItemInstance[] -{ - return ItemInstanceArray(); // Default ctor creates NULL internal array -} +bool Entity::isInvisible() { return getSharedFlag(FLAG_INVISIBLE); } -// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game -void Entity::setEquippedSlot(int slot, std::shared_ptr item) -{ +bool Entity::isInvisibleTo(std::shared_ptr plr) { + return isInvisible(); } -bool Entity::isOnFire() -{ - return onFire > 0 || getSharedFlag(FLAG_ONFIRE); -} +void Entity::setInvisible(bool value) { setSharedFlag(FLAG_INVISIBLE, value); } -bool Entity::isRiding() -{ - return riding != NULL || getSharedFlag(FLAG_RIDING); -} +bool Entity::isWeakened() { return getSharedFlag(FLAG_EFFECT_WEAKENED); } -bool Entity::isSneaking() -{ - return getSharedFlag(FLAG_SNEAKING); +void Entity::setWeakened(bool value) { + setSharedFlag(FLAG_EFFECT_WEAKENED, value); } -void Entity::setSneaking(bool value) -{ - setSharedFlag(FLAG_SNEAKING, value); -} +bool Entity::isUsingItemFlag() { return getSharedFlag(FLAG_USING_ITEM); } -bool Entity::isIdle() -{ - return getSharedFlag(FLAG_IDLEANIM); +void Entity::setUsingItemFlag(bool value) { + setSharedFlag(FLAG_USING_ITEM, value); } -void Entity::setIsIdle(bool value) -{ - setSharedFlag(FLAG_IDLEANIM, value); +bool Entity::getSharedFlag(int flag) { + return (entityData->getByte(DATA_SHARED_FLAGS_ID) & (1 << flag)) != 0; } -bool Entity::isSprinting() -{ - return getSharedFlag(FLAG_SPRINTING); +void Entity::setSharedFlag(int flag, bool value) { + uint8_t currentValue = entityData->getByte(DATA_SHARED_FLAGS_ID); + if (value) { + entityData->set(DATA_SHARED_FLAGS_ID, + (uint8_t)(currentValue | (1 << flag))); + } else { + entityData->set(DATA_SHARED_FLAGS_ID, + (uint8_t)(currentValue & ~(1 << flag))); + } } -void Entity::setSprinting(bool value) -{ - setSharedFlag(FLAG_SPRINTING, value); -} +// 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take +// damage when air bubbles are present if resuming game from load/autosave +// underwater. +int Entity::getAirSupply() { return entityData->getShort(DATA_AIR_SUPPLY_ID); } -bool Entity::isInvisible() -{ - return getSharedFlag(FLAG_INVISIBLE); +// 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take +// damage when air bubbles are present if resuming game from load/autosave +// underwater. +void Entity::setAirSupply(int supply) { + entityData->set(DATA_AIR_SUPPLY_ID, (short)supply); } -bool Entity::isInvisibleTo(std::shared_ptr plr) -{ - return isInvisible(); +void Entity::thunderHit(const LightningBolt* lightningBolt) { + burn(5); + onFire++; + if (onFire == 0) setOnFire(8); } -void Entity::setInvisible(bool value) -{ - setSharedFlag(FLAG_INVISIBLE, value); -} +void Entity::killed(std::shared_ptr mob) {} -bool Entity::isWeakened() -{ - return getSharedFlag(FLAG_EFFECT_WEAKENED); -} +bool Entity::checkInTile(double x, double y, double z) { + int xTile = Mth::floor(x); + int yTile = Mth::floor(y); + int zTile = Mth::floor(z); -void Entity::setWeakened(bool value) -{ - setSharedFlag(FLAG_EFFECT_WEAKENED, value); -} + double xd = x - (xTile); + double yd = y - (yTile); + double zd = z - (zTile); -bool Entity::isUsingItemFlag() -{ - return getSharedFlag(FLAG_USING_ITEM); -} + if (level->isSolidBlockingTile(xTile, yTile, zTile)) { + bool west = !level->isSolidBlockingTile(xTile - 1, yTile, zTile); + bool east = !level->isSolidBlockingTile(xTile + 1, yTile, zTile); + bool up = !level->isSolidBlockingTile(xTile, yTile - 1, zTile); + bool down = !level->isSolidBlockingTile(xTile, yTile + 1, zTile); + bool north = !level->isSolidBlockingTile(xTile, yTile, zTile - 1); + bool south = !level->isSolidBlockingTile(xTile, yTile, zTile + 1); -void Entity::setUsingItemFlag(bool value) -{ - setSharedFlag(FLAG_USING_ITEM, value); -} + int dir = -1; + double closest = 9999; + if (west && xd < closest) { + closest = xd; + dir = 0; + } + if (east && 1 - xd < closest) { + closest = 1 - xd; + dir = 1; + } + if (up && yd < closest) { + closest = yd; + dir = 2; + } + if (down && 1 - yd < closest) { + closest = 1 - yd; + dir = 3; + } + if (north && zd < closest) { + closest = zd; + dir = 4; + } + if (south && 1 - zd < closest) { + closest = 1 - zd; + dir = 5; + } -bool Entity::getSharedFlag(int flag) -{ - return (entityData->getByte(DATA_SHARED_FLAGS_ID) & (1 << flag)) != 0; -} + float speed = random->nextFloat() * 0.2f + 0.1f; + if (dir == 0) this->xd = -speed; + if (dir == 1) this->xd = +speed; -void Entity::setSharedFlag(int flag, bool value) -{ - uint8_t currentValue = entityData->getByte(DATA_SHARED_FLAGS_ID); - if (value) - { - entityData->set(DATA_SHARED_FLAGS_ID, (uint8_t) (currentValue | (1 << flag))); - } - else - { - entityData->set(DATA_SHARED_FLAGS_ID, (uint8_t) (currentValue & ~(1 << flag))); - } -} + if (dir == 2) this->yd = -speed; + if (dir == 3) this->yd = +speed; -// 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take damage when air bubbles are present if resuming game from load/autosave underwater. -int Entity::getAirSupply() -{ - return entityData->getShort(DATA_AIR_SUPPLY_ID); -} + if (dir == 4) this->zd = -speed; + if (dir == 5) this->zd = +speed; + return true; + } -// 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take damage when air bubbles are present if resuming game from load/autosave underwater. -void Entity::setAirSupply(int supply) -{ - entityData->set(DATA_AIR_SUPPLY_ID, (short) supply); + return false; } -void Entity::thunderHit(const LightningBolt *lightningBolt) -{ - burn(5); - onFire++; - if (onFire == 0) setOnFire(8); -} - -void Entity::killed(std::shared_ptr mob) -{ -} - - -bool Entity::checkInTile(double x, double y, double z) -{ - int xTile = Mth::floor(x); - int yTile = Mth::floor(y); - int zTile = Mth::floor(z); - - double xd = x - (xTile); - double yd = y - (yTile); - double zd = z - (zTile); - - if (level->isSolidBlockingTile(xTile, yTile, zTile)) - { - bool west = !level->isSolidBlockingTile(xTile - 1, yTile, zTile); - bool east = !level->isSolidBlockingTile(xTile + 1, yTile, zTile); - bool up = !level->isSolidBlockingTile(xTile, yTile - 1, zTile); - bool down = !level->isSolidBlockingTile(xTile, yTile + 1, zTile); - bool north = !level->isSolidBlockingTile(xTile, yTile, zTile - 1); - bool south = !level->isSolidBlockingTile(xTile, yTile, zTile + 1); - - int dir = -1; - double closest = 9999; - if (west && xd < closest) - { - closest = xd; - dir = 0; - } - if (east && 1 - xd < closest) - { - closest = 1 - xd; - dir = 1; - } - if (up && yd < closest) - { - closest = yd; - dir = 2; - } - if (down && 1 - yd < closest) - { - closest = 1 - yd; - dir = 3; - } - if (north && zd < closest) - { - closest = zd; - dir = 4; - } - if (south && 1 - zd < closest) - { - closest = 1 - zd; - dir = 5; - } - - float speed = random->nextFloat() * 0.2f + 0.1f; - if (dir == 0) this->xd = -speed; - if (dir == 1) this->xd = +speed; - - if (dir == 2) this->yd = -speed; - if (dir == 3) this->yd = +speed; - - if (dir == 4) this->zd = -speed; - if (dir == 5) this->zd = +speed; - return true; - } - - return false; -} - -void Entity::makeStuckInWeb() -{ - isStuckInWeb = true; - fallDistance = 0; -} - -std::wstring Entity::getAName() -{ - std::wstring id = EntityIO::getEncodeId(shared_from_this()); - if (id.empty()) id = L"generic"; - return L"entity." + id + _toString(entityId); - //return I18n.get("entity." + id + ".name"); -} - -std::vector > *Entity::getSubEntities() -{ - return NULL; -} - -bool Entity::is(std::shared_ptr other) -{ - return shared_from_this() == other; -} - -float Entity::getYHeadRot() -{ - return 0; -} - -void Entity::setYHeadRot(float yHeadRot) -{ -} - -bool Entity::isAttackable() -{ - return true; -} - -bool Entity::isInvulnerable() -{ - return false; -} - -void Entity::copyPosition(std::shared_ptr target) -{ - moveTo(target->x, target->y, target->z, target->yRot, target->xRot); -} - -void Entity::setAnimOverrideBitmask(unsigned int uiBitmask) -{ - m_uiAnimOverrideBitmask=uiBitmask; - app.DebugPrintf("!!! Setting anim override bitmask to %d\n",uiBitmask); -} -unsigned int Entity::getAnimOverrideBitmask() -{ - if(app.GetGameSettings(eGameSetting_CustomSkinAnim)==0 ) - { - // We have a force animation for some skins (claptrap) - // 4J-PB - treat all the eAnim_Disable flags as a force anim - unsigned int uiIgnoreUserCustomSkinAnimSettingMask=(1< >* Entity::getSubEntities() { return NULL; } + +bool Entity::is(std::shared_ptr other) { + return shared_from_this() == other; +} + +float Entity::getYHeadRot() { return 0; } + +void Entity::setYHeadRot(float yHeadRot) {} + +bool Entity::isAttackable() { return true; } + +bool Entity::isInvulnerable() { return false; } + +void Entity::copyPosition(std::shared_ptr target) { + moveTo(target->x, target->y, target->z, target->yRot, target->xRot); +} + +void Entity::setAnimOverrideBitmask(unsigned int uiBitmask) { + m_uiAnimOverrideBitmask = uiBitmask; + app.DebugPrintf("!!! Setting anim override bitmask to %d\n", uiBitmask); +} +unsigned int Entity::getAnimOverrideBitmask() { + if (app.GetGameSettings(eGameSetting_CustomSkinAnim) == 0) { + // We have a force animation for some skins (claptrap) + // 4J-PB - treat all the eAnim_Disable flags as a force anim + unsigned int uiIgnoreUserCustomSkinAnimSettingMask = + (1 << HumanoidModel::eAnim_ForceAnim) | + (1 << HumanoidModel::eAnim_DisableRenderArm0) | + (1 << HumanoidModel::eAnim_DisableRenderArm1) | + (1 << HumanoidModel::eAnim_DisableRenderTorso) | + (1 << HumanoidModel::eAnim_DisableRenderLeg0) | + (1 << HumanoidModel::eAnim_DisableRenderLeg1) | + (1 << HumanoidModel::eAnim_DisableRenderHair); + + if ((m_uiAnimOverrideBitmask & + HumanoidModel::m_staticBitmaskIgnorePlayerCustomAnimSetting) != + 0) { + return m_uiAnimOverrideBitmask; + } + return 0; + } + + return m_uiAnimOverrideBitmask; } diff --git a/Minecraft.World/Entities/Entity.h b/Minecraft.World/Entities/Entity.h index 10cc1553c..bf4fb0fe1 100644 --- a/Minecraft.World/Entities/Entity.h +++ b/Minecraft.World/Entities/Entity.h @@ -22,383 +22,417 @@ class CompoundTag; class DamageSource; // 4J Stu Added this mainly to allow is to record telemetry for player deaths -enum EEntityDamageType -{ - eEntityDamageType_Entity, - eEntityDamageType_Fall, - eEntityDamageType_Fire, - eEntityDamageType_Lava, - eEntityDamageType_Water, - eEntityDamageType_Suffocate, - eEntityDamageType_OutOfWorld, - eEntityDamageType_Cactus, +enum EEntityDamageType { + eEntityDamageType_Entity, + eEntityDamageType_Fall, + eEntityDamageType_Fire, + eEntityDamageType_Lava, + eEntityDamageType_Water, + eEntityDamageType_Suffocate, + eEntityDamageType_OutOfWorld, + eEntityDamageType_Cactus, }; -class Entity : public std::enable_shared_from_this -{ -friend class Gui; // 4J Stu - Added to be able to access the shared flag functions and constants, without making them publicly available to everything +class Entity : public std::enable_shared_from_this { + friend class Gui; // 4J Stu - Added to be able to access the shared flag + // functions and constants, without making them publicly + // available to everything public: - // 4J-PB - added to replace (e instanceof Type), avoiding dynamic casts - virtual eINSTANCEOF GetType() = 0; + // 4J-PB - added to replace (e instanceof Type), avoiding dynamic casts + virtual eINSTANCEOF GetType() = 0; public: - - static const short TOTAL_AIR_SUPPLY = 20 * 15; + static const short TOTAL_AIR_SUPPLY = 20 * 15; private: - static int entityCounter; + static int entityCounter; public: - int entityId; + int entityId; - double viewScale; + double viewScale; - bool blocksBuilding; - std::weak_ptr rider; // Changed to weak to avoid circular dependency between rider/riding entity - std::shared_ptr riding; + bool blocksBuilding; + std::weak_ptr rider; // Changed to weak to avoid circular + // dependency between rider/riding entity + std::shared_ptr riding; - Level *level; - double xo, yo, zo; - double x, y, z; - double xd, yd, zd; - float yRot, xRot; - float yRotO, xRotO; - /*const*/ AABB *bb; // 4J Was final - bool onGround; - bool horizontalCollision, verticalCollision; - bool collision; - bool hurtMarked; + Level* level; + double xo, yo, zo; + double x, y, z; + double xd, yd, zd; + float yRot, xRot; + float yRotO, xRotO; + /*const*/ AABB* bb; // 4J Was final + bool onGround; + bool horizontalCollision, verticalCollision; + bool collision; + bool hurtMarked; protected: - bool isStuckInWeb; + bool isStuckInWeb; public: - bool slide; - bool removed; - float heightOffset; + bool slide; + bool removed; + float heightOffset; - float bbWidth; - float bbHeight; + float bbWidth; + float bbHeight; - float walkDistO; - float walkDist; - float fallDistance; + float walkDistO; + float walkDist; + float fallDistance; private: - int nextStep; + int nextStep; public: - double xOld, yOld, zOld; - float ySlideOffset; - float footSize; - bool noPhysics; - float pushthrough; + double xOld, yOld, zOld; + float ySlideOffset; + float footSize; + bool noPhysics; + float pushthrough; protected: - Random *random; + Random* random; public: - int tickCount; - int flameTime; + int tickCount; + int flameTime; private: - int onFire; + int onFire; protected: - bool wasInWater; + bool wasInWater; public: - int invulnerableTime; + int invulnerableTime; private: - bool firstTick; + bool firstTick; public: - std::wstring customTextureUrl; - std::wstring customTextureUrl2; + std::wstring customTextureUrl; + std::wstring customTextureUrl2; protected: - bool fireImmune; + bool fireImmune; - // values that need to be sent to clients in SMP - std::shared_ptr entityData; + // values that need to be sent to clients in SMP + std::shared_ptr entityData; private: - // shared flags that are sent to clients (max 8) - static const int DATA_SHARED_FLAGS_ID = 0; - static const int FLAG_ONFIRE = 0; - static const int FLAG_SNEAKING = 1; - static const int FLAG_RIDING = 2; - static const int FLAG_SPRINTING = 3; - static const int FLAG_USING_ITEM = 4; - static const int FLAG_INVISIBLE = 5; - static const int FLAG_IDLEANIM = 6; - static const int FLAG_EFFECT_WEAKENED = 7; //4J ADDED, needed for cure villager tooltip. - static const int DATA_AIR_SUPPLY_ID = 1; + // shared flags that are sent to clients (max 8) + static const int DATA_SHARED_FLAGS_ID = 0; + static const int FLAG_ONFIRE = 0; + static const int FLAG_SNEAKING = 1; + static const int FLAG_RIDING = 2; + static const int FLAG_SPRINTING = 3; + static const int FLAG_USING_ITEM = 4; + static const int FLAG_INVISIBLE = 5; + static const int FLAG_IDLEANIM = 6; + static const int FLAG_EFFECT_WEAKENED = + 7; // 4J ADDED, needed for cure villager tooltip. + static const int DATA_AIR_SUPPLY_ID = 1; private: - double xRideRotA, yRideRotA; + double xRideRotA, yRideRotA; public: - bool inChunk; + bool inChunk; int xChunk, yChunk, zChunk; int xp, yp, zp, xRotp, yRotp; bool noCulling; bool hasImpulse; protected: - // 4J Added so that client side simulations on the host are not affected by zero-lag - bool m_ignoreVerticalCollisions; + // 4J Added so that client side simulations on the host are not affected by + // zero-lag + bool m_ignoreVerticalCollisions; public: - Entity(Level *level, bool useSmallId = true); // 4J - added useSmallId parameter - virtual ~Entity(); + Entity(Level* level, + bool useSmallId = true); // 4J - added useSmallId parameter + virtual ~Entity(); protected: - // 4J - added for common ctor code - void _init(bool useSmallId); + // 4J - added for common ctor code + void _init(bool useSmallId); protected: - virtual void defineSynchedData() = 0; + virtual void defineSynchedData() = 0; public: - std::shared_ptr getEntityData(); + std::shared_ptr getEntityData(); - /* - public bool equals(Object obj) { - if (obj instanceof Entity) { - return ((Entity) obj).entityId == entityId; - } - return false; - } + /* + public bool equals(Object obj) { + if (obj instanceof Entity) { + return ((Entity) obj).entityId == entityId; + } + return false; + } - public int hashCode() { - return entityId; - } - */ + public int hashCode() { + return entityId; + } + */ protected: - virtual void resetPos(); + virtual void resetPos(); public: - virtual void remove(); + virtual void remove(); protected: - virtual void setSize(float w, float h); - void setPos(EntityPos *pos); - void setRot(float yRot, float xRot); + virtual void setSize(float w, float h); + void setPos(EntityPos* pos); + void setRot(float yRot, float xRot); public: - void setPos(double x, double y, double z); - void turn(float xo, float yo); - void interpolateTurn(float xo, float yo); - virtual void tick(); - virtual void baseTick(); + void setPos(double x, double y, double z); + void turn(float xo, float yo); + void interpolateTurn(float xo, float yo); + virtual void tick(); + virtual void baseTick(); protected: - void lavaHurt(); + void lavaHurt(); public: - virtual void setOnFire(int numberOfSeconds); - virtual void clearFire(); + virtual void setOnFire(int numberOfSeconds); + virtual void clearFire(); protected: - virtual void outOfWorld(); + virtual void outOfWorld(); public: - bool isFree(float xa, float ya, float za, float grow); - bool isFree(double xa, double ya, double za); - virtual void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter + bool isFree(float xa, float ya, float za, float grow); + bool isFree(double xa, double ya, double za); + virtual void move( + double xa, double ya, double za, + bool noEntityCubes = false); // 4J - added noEntityCubes parameter protected: - virtual void checkInsideTiles(); - virtual void playStepSound(int xt, int yt, int zt, int t); + virtual void checkInsideTiles(); + virtual void playStepSound(int xt, int yt, int zt, int t); public: - virtual void playSound(int iSound, float volume, float pitch); + virtual void playSound(int iSound, float volume, float pitch); protected: - virtual bool makeStepSound(); - virtual void checkFallDamage(double ya, bool onGround); + virtual bool makeStepSound(); + virtual void checkFallDamage(double ya, bool onGround); public: - virtual AABB *getCollideBox(); + virtual AABB* getCollideBox(); protected: - virtual void burn(int dmg); + virtual void burn(int dmg); public: - bool isFireImmune(); + bool isFireImmune(); protected: - virtual void causeFallDamage(float distance); + virtual void causeFallDamage(float distance); public: - bool isInWaterOrRain(); - virtual bool isInWater(); - virtual bool updateInWaterState(); - bool isUnderLiquid(Material *material); - virtual float getHeadHeight(); - bool isInLava(); - void moveRelative(float xa, float za, float speed); - virtual int getLightColor(float a); // 4J - change brought forward from 1.8.2 - virtual float getBrightness(float a); - virtual void setLevel(Level *level); - void absMoveTo(double x, double y, double z, float yRot, float xRot); - void moveTo(double x, double y, double z, float yRot, float xRot); - float distanceTo(std::shared_ptr e); - double distanceToSqr(double x2, double y2, double z2); - double distanceTo(double x2, double y2, double z2); - double distanceToSqr(std::shared_ptr e); - virtual void playerTouch(std::shared_ptr player); - virtual void push(std::shared_ptr e); - virtual void push(double xa, double ya, double za); + bool isInWaterOrRain(); + virtual bool isInWater(); + virtual bool updateInWaterState(); + bool isUnderLiquid(Material* material); + virtual float getHeadHeight(); + bool isInLava(); + void moveRelative(float xa, float za, float speed); + virtual int getLightColor( + float a); // 4J - change brought forward from 1.8.2 + virtual float getBrightness(float a); + virtual void setLevel(Level* level); + void absMoveTo(double x, double y, double z, float yRot, float xRot); + void moveTo(double x, double y, double z, float yRot, float xRot); + float distanceTo(std::shared_ptr e); + double distanceToSqr(double x2, double y2, double z2); + double distanceTo(double x2, double y2, double z2); + double distanceToSqr(std::shared_ptr e); + virtual void playerTouch(std::shared_ptr player); + virtual void push(std::shared_ptr e); + virtual void push(double xa, double ya, double za); protected: - void markHurt(); + void markHurt(); public: - // 4J Added damageSource param to enable telemetry on player deaths - virtual bool hurt(DamageSource *source, int damage); - bool intersects(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool isPickable(); - virtual bool isPushable(); - virtual bool isShootable(); - virtual void awardKillScore(std::shared_ptr victim, int score); - virtual bool shouldRender(Vec3 *c); - virtual bool shouldRenderAtSqrDistance(double distance); - virtual int getTexture(); // 4J - changed from std::wstring to int - virtual bool isCreativeModeAllowed(); - bool save(CompoundTag *entityTag); - void saveWithoutId(CompoundTag *entityTag); - virtual void load(CompoundTag *tag); + // 4J Added damageSource param to enable telemetry on player deaths + virtual bool hurt(DamageSource* source, int damage); + bool intersects(double x0, double y0, double z0, double x1, double y1, + double z1); + virtual bool isPickable(); + virtual bool isPushable(); + virtual bool isShootable(); + virtual void awardKillScore(std::shared_ptr victim, int score); + virtual bool shouldRender(Vec3* c); + virtual bool shouldRenderAtSqrDistance(double distance); + virtual int getTexture(); // 4J - changed from std::wstring to int + virtual bool isCreativeModeAllowed(); + bool save(CompoundTag* entityTag); + void saveWithoutId(CompoundTag* entityTag); + virtual void load(CompoundTag* tag); protected: - const std::wstring getEncodeId(); + const std::wstring getEncodeId(); public: - virtual void readAdditionalSaveData(CompoundTag *tag) = 0; - virtual void addAdditonalSaveData(CompoundTag *tag) = 0; + virtual void readAdditionalSaveData(CompoundTag* tag) = 0; + virtual void addAdditonalSaveData(CompoundTag* tag) = 0; protected: - ListTag *newDoubleList(unsigned int number, double firstValue, ...); - ListTag *newFloatList(unsigned int number, float firstValue, float secondValue); + ListTag* newDoubleList(unsigned int number, double firstValue, + ...); + ListTag* newFloatList(unsigned int number, float firstValue, + float secondValue); public: - virtual float getShadowHeightOffs(); - std::shared_ptr spawnAtLocation(int resource, int count); - std::shared_ptr spawnAtLocation(int resource, int count, float yOffs); - std::shared_ptr spawnAtLocation(std::shared_ptr itemInstance, float yOffs); - virtual bool isAlive(); - virtual bool isInWall(); - virtual bool interact(std::shared_ptr player); - virtual AABB *getCollideAgainstBox(std::shared_ptr entity); + virtual float getShadowHeightOffs(); + std::shared_ptr spawnAtLocation(int resource, int count); + std::shared_ptr spawnAtLocation(int resource, int count, + float yOffs); + std::shared_ptr spawnAtLocation( + std::shared_ptr itemInstance, float yOffs); + virtual bool isAlive(); + virtual bool isInWall(); + virtual bool interact(std::shared_ptr player); + virtual AABB* getCollideAgainstBox(std::shared_ptr entity); - virtual void rideTick(); - virtual void positionRider(); - virtual double getRidingHeight(); - virtual double getRideHeight(); - virtual void ride(std::shared_ptr e); - virtual void findStandUpPosition(std::shared_ptr vehicle); // 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting the minecart in a tight corridor damages the player - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); - virtual float getPickRadius(); - virtual Vec3 *getLookAngle(); - virtual void handleInsidePortal(); - virtual void lerpMotion(double xd, double yd, double zd); - virtual void handleEntityEvent(uint8_t eventId); - virtual void animateHurt(); - virtual void prepareCustomTextures(); - virtual ItemInstanceArray getEquipmentSlots(); // ItemInstance[] - virtual void setEquippedSlot(int slot, std::shared_ptr item); // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - virtual bool isOnFire(); - virtual bool isRiding(); - virtual bool isSneaking(); - virtual void setSneaking(bool value); - virtual bool isIdle(); - virtual void setIsIdle(bool value); - virtual bool isSprinting(); - virtual void setSprinting(bool value); - virtual bool isInvisible(); - virtual bool isInvisibleTo(std::shared_ptr plr); - virtual void setInvisible(bool value); - virtual bool isUsingItemFlag(); - virtual void setUsingItemFlag(bool value); + virtual void rideTick(); + virtual void positionRider(); + virtual double getRidingHeight(); + virtual double getRideHeight(); + virtual void ride(std::shared_ptr e); + virtual void findStandUpPosition( + std::shared_ptr + vehicle); // 4J Stu - Brought forward from 12w36 to fix #46282 - + // TU5: Gameplay: Exiting the minecart in a tight + // corridor damages the player + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); + virtual float getPickRadius(); + virtual Vec3* getLookAngle(); + virtual void handleInsidePortal(); + virtual void lerpMotion(double xd, double yd, double zd); + virtual void handleEntityEvent(uint8_t eventId); + virtual void animateHurt(); + virtual void prepareCustomTextures(); + virtual ItemInstanceArray getEquipmentSlots(); // ItemInstance[] + virtual void setEquippedSlot( + int slot, std::shared_ptr + item); // 4J Stu - Brought forward change from 1.3 to fix + // #64688 - Customer Encountered: TU7: Content: + // Art: Aura of enchanted item is not displayed + // for other players in online game + virtual bool isOnFire(); + virtual bool isRiding(); + virtual bool isSneaking(); + virtual void setSneaking(bool value); + virtual bool isIdle(); + virtual void setIsIdle(bool value); + virtual bool isSprinting(); + virtual void setSprinting(bool value); + virtual bool isInvisible(); + virtual bool isInvisibleTo(std::shared_ptr plr); + virtual void setInvisible(bool value); + virtual bool isUsingItemFlag(); + virtual void setUsingItemFlag(bool value); - // 4J-ADDED, we need to see if this is weakened - // on the client for the cure villager tooltip. - bool isWeakened(); - void setWeakened(bool value); + // 4J-ADDED, we need to see if this is weakened + // on the client for the cure villager tooltip. + bool isWeakened(); + void setWeakened(bool value); protected: - bool getSharedFlag(int flag); - void setSharedFlag(int flag, bool value); + bool getSharedFlag(int flag); + void setSharedFlag(int flag, bool value); public: - // 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will take damage when air bubbles are present if resuming game from load/autosave underwater. - int getAirSupply(); - void setAirSupply(int supply); + // 4J Stu - Brought forward from 1.2.3 to fix 38654 - Gameplay: Player will + // take damage when air bubbles are present if resuming game from + // load/autosave underwater. + int getAirSupply(); + void setAirSupply(int supply); - virtual void thunderHit(const LightningBolt *lightningBolt); - virtual void killed(std::shared_ptr mob); + virtual void thunderHit(const LightningBolt* lightningBolt); + virtual void killed(std::shared_ptr mob); protected: - bool checkInTile(double x, double y, double z); + bool checkInTile(double x, double y, double z); public: - virtual void makeStuckInWeb(); + virtual void makeStuckInWeb(); - virtual std::wstring getAName(); + virtual std::wstring getAName(); - // TU9 - bool skipAttackInteraction(std::shared_ptr source) {return false;} + // TU9 + bool skipAttackInteraction(std::shared_ptr source) { return false; } - // 4J - added to manage allocation of small ids + // 4J - added to manage allocation of small ids private: - // Things also added here to be able to manage the concept of a number of extra "wandering" entities - normally path finding entities aren't allowed to - // randomly wander about once they are a certain distance away from any player, but we want to be able to (in a controlled fashion) allow some to be able - // to move so that we can determine whether they have been enclosed in some kind of farm, and so be able to better determine what shouldn't or shouldn't be despawned. - static const int EXTRA_WANDER_MAX = 3; // Number of entities that can simultaneously wander (in addition to the ones that would be wandering in java) - static const int EXTRA_WANDER_TICKS = 20 * 30; // Number of ticks each extra entity will be allowed to wander for. This should be enough for it to realistically be able to walk further than the biggest enclosure we want to consider + // Things also added here to be able to manage the concept of a number of + // extra "wandering" entities - normally path finding entities aren't + // allowed to randomly wander about once they are a certain distance away + // from any player, but we want to be able to (in a controlled fashion) + // allow some to be able to move so that we can determine whether they have + // been enclosed in some kind of farm, and so be able to better determine + // what shouldn't or shouldn't be despawned. + static const int EXTRA_WANDER_MAX = + 3; // Number of entities that can simultaneously wander (in addition to + // the ones that would be wandering in java) + static const int EXTRA_WANDER_TICKS = + 20 * + 30; // Number of ticks each extra entity will be allowed to wander for. + // This should be enough for it to realistically be able to walk + // further than the biggest enclosure we want to consider - int getSmallId(); - void freeSmallId(int index); - static unsigned int entityIdUsedFlags[2048/32]; - static unsigned int entityIdWanderFlags[2048/32]; - static unsigned int entityIdRemovingFlags[2048/32]; - static int extraWanderIds[EXTRA_WANDER_MAX]; - static int extraWanderCount; - static int extraWanderTicks; + int getSmallId(); + void freeSmallId(int index); + static unsigned int entityIdUsedFlags[2048 / 32]; + static unsigned int entityIdWanderFlags[2048 / 32]; + static unsigned int entityIdRemovingFlags[2048 / 32]; + static int extraWanderIds[EXTRA_WANDER_MAX]; + static int extraWanderCount; + static int extraWanderTicks; #if defined(_WIN32) - static DWORD tlsIdx; + static DWORD tlsIdx; #else - static pthread_key_t tlsIdx; + static pthread_key_t tlsIdx; #endif public: - static void tickExtraWandering(); - static void countFlagsForPIX(); - void resetSmallId(); - static void useSmallIds(); - void considerForExtraWandering(bool enable); - bool isExtraWanderingEnabled(); - int getWanderingQuadrant(); - - virtual std::vector > *getSubEntities(); - virtual bool is(std::shared_ptr other); - virtual float getYHeadRot(); - virtual void setYHeadRot(float yHeadRot); - virtual bool isAttackable(); - virtual bool isInvulnerable(); - virtual void copyPosition(std::shared_ptr target); + static void tickExtraWandering(); + static void countFlagsForPIX(); + void resetSmallId(); + static void useSmallIds(); + void considerForExtraWandering(bool enable); + bool isExtraWanderingEnabled(); + int getWanderingQuadrant(); + + virtual std::vector >* getSubEntities(); + virtual bool is(std::shared_ptr other); + virtual float getYHeadRot(); + virtual void setYHeadRot(float yHeadRot); + virtual bool isAttackable(); + virtual bool isInvulnerable(); + virtual void copyPosition(std::shared_ptr target); private: - unsigned int m_uiAnimOverrideBitmask; -public: - void setAnimOverrideBitmask(unsigned int uiBitmask); - unsigned int getAnimOverrideBitmask(); + unsigned int m_uiAnimOverrideBitmask; - // 4J added - virtual bool isDespawnProtected() { return false; } - virtual void setDespawnProtected() {} - virtual bool couldWander() { return false; } - virtual bool canCreateParticles() { return true; } +public: + void setAnimOverrideBitmask(unsigned int uiBitmask); + unsigned int getAnimOverrideBitmask(); + + // 4J added + virtual bool isDespawnProtected() { return false; } + virtual void setDespawnProtected() {} + virtual bool couldWander() { return false; } + virtual bool canCreateParticles() { return true; } }; diff --git a/Minecraft.World/Entities/EntityDamageSource.cpp b/Minecraft.World/Entities/EntityDamageSource.cpp index 5c62c088c..288838962 100644 --- a/Minecraft.World/Entities/EntityDamageSource.cpp +++ b/Minecraft.World/Entities/EntityDamageSource.cpp @@ -4,35 +4,36 @@ #include "../Headers/net.minecraft.world.damagesource.h" #include "../Headers/net.minecraft.network.packet.h" -//EntityDamageSource::EntityDamageSource(const std::wstring &msgId, std::shared_ptr entity) : DamageSource(msgId) -EntityDamageSource::EntityDamageSource(ChatPacket::EChatPacketMessage msgId, std::shared_ptr entity) : DamageSource(msgId) -{ - this->entity = entity; +// EntityDamageSource::EntityDamageSource(const std::wstring &msgId, +// std::shared_ptr entity) : DamageSource(msgId) +EntityDamageSource::EntityDamageSource(ChatPacket::EChatPacketMessage msgId, + std::shared_ptr entity) + : DamageSource(msgId) { + this->entity = entity; } -std::shared_ptr EntityDamageSource::getEntity() -{ - return entity; -} +std::shared_ptr EntityDamageSource::getEntity() { return entity; } -//std::wstring EntityDamageSource::getLocalizedDeathMessage(std::shared_ptr player) +// std::wstring +// EntityDamageSource::getLocalizedDeathMessage(std::shared_ptr player) //{ // return L"death." + msgId + player->name + entity->getAName(); // //return I18n.get("death." + msgId, player.name, entity.getAName()); -//} +// } -std::shared_ptr EntityDamageSource::getDeathMessagePacket(std::shared_ptr player) -{ - std::wstring additional = L""; - if(entity->GetType() == eTYPE_SERVERPLAYER) - { - std::shared_ptr sourcePlayer = std::dynamic_pointer_cast(entity); - if(sourcePlayer != NULL) additional = sourcePlayer->name; - } - return std::shared_ptr( new ChatPacket(player->name, m_msgId, entity->GetType(), additional ) ); +std::shared_ptr EntityDamageSource::getDeathMessagePacket( + std::shared_ptr player) { + std::wstring additional = L""; + if (entity->GetType() == eTYPE_SERVERPLAYER) { + std::shared_ptr sourcePlayer = + std::dynamic_pointer_cast(entity); + if (sourcePlayer != NULL) additional = sourcePlayer->name; + } + return std::shared_ptr( + new ChatPacket(player->name, m_msgId, entity->GetType(), additional)); } -bool EntityDamageSource::scalesWithDifficulty() -{ - return entity != NULL && std::dynamic_pointer_cast(entity) && !(std::dynamic_pointer_cast(entity)); +bool EntityDamageSource::scalesWithDifficulty() { + return entity != NULL && std::dynamic_pointer_cast(entity) && + !(std::dynamic_pointer_cast(entity)); } \ No newline at end of file diff --git a/Minecraft.World/Entities/EntityDamageSource.h b/Minecraft.World/Entities/EntityDamageSource.h index 745bc4268..04c4ecadc 100644 --- a/Minecraft.World/Entities/EntityDamageSource.h +++ b/Minecraft.World/Entities/EntityDamageSource.h @@ -1,26 +1,28 @@ #pragma once - #include "../Util/DamageSource.h" class Entity; class Player; -class EntityDamageSource : public DamageSource -{ +class EntityDamageSource : public DamageSource { protected: - std::shared_ptr entity; + std::shared_ptr entity; public: - //EntityDamageSource(const std::wstring &msgId, std::shared_ptr entity); - EntityDamageSource(ChatPacket::EChatPacketMessage msgId, std::shared_ptr entity); - virtual ~EntityDamageSource() { } + // EntityDamageSource(const std::wstring &msgId, std::shared_ptr + // entity); + EntityDamageSource(ChatPacket::EChatPacketMessage msgId, + std::shared_ptr entity); + virtual ~EntityDamageSource() {} std::shared_ptr getEntity(); - // 4J Stu - Made return a packet - //virtual std::wstring getLocalizedDeathMessage(std::shared_ptr player); - virtual std::shared_ptr getDeathMessagePacket(std::shared_ptr player); + // 4J Stu - Made return a packet + // virtual std::wstring getLocalizedDeathMessage(std::shared_ptr + // player); + virtual std::shared_ptr getDeathMessagePacket( + std::shared_ptr player); - virtual bool scalesWithDifficulty(); + virtual bool scalesWithDifficulty(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/EntityEvent.h b/Minecraft.World/Entities/EntityEvent.h index 8e94bac1c..302a4eb20 100644 --- a/Minecraft.World/Entities/EntityEvent.h +++ b/Minecraft.World/Entities/EntityEvent.h @@ -1,30 +1,29 @@ #pragma once #include -class EntityEvent -{ +class EntityEvent { public: - static const std::uint8_t JUMP = 1; - static const std::uint8_t HURT = 2; - static const std::uint8_t DEATH = 3; - static const std::uint8_t START_ATTACKING = 4; - static const std::uint8_t STOP_ATTACKING = 5; + static const std::uint8_t JUMP = 1; + static const std::uint8_t HURT = 2; + static const std::uint8_t DEATH = 3; + static const std::uint8_t START_ATTACKING = 4; + static const std::uint8_t STOP_ATTACKING = 5; - static const std::uint8_t TAMING_FAILED = 6; - static const std::uint8_t TAMING_SUCCEEDED = 7; - static const std::uint8_t SHAKE_WETNESS = 8; + static const std::uint8_t TAMING_FAILED = 6; + static const std::uint8_t TAMING_SUCCEEDED = 7; + static const std::uint8_t SHAKE_WETNESS = 8; - static const std::uint8_t USE_ITEM_COMPLETE = 9; + static const std::uint8_t USE_ITEM_COMPLETE = 9; - static const std::uint8_t EAT_GRASS = 10; - static const std::uint8_t OFFER_FLOWER = 11; - static const std::uint8_t LOVE_HEARTS = 12; - static const std::uint8_t VILLAGER_ANGRY = 13; - static const std::uint8_t VILLAGER_HAPPY = 14; - static const std::uint8_t WITCH_HAT_MAGIC = 15; - static const std::uint8_t ZOMBIE_CONVERTING = 16; + static const std::uint8_t EAT_GRASS = 10; + static const std::uint8_t OFFER_FLOWER = 11; + static const std::uint8_t LOVE_HEARTS = 12; + static const std::uint8_t VILLAGER_ANGRY = 13; + static const std::uint8_t VILLAGER_HAPPY = 14; + static const std::uint8_t WITCH_HAT_MAGIC = 15; + static const std::uint8_t ZOMBIE_CONVERTING = 16; - static const std::uint8_t FIREWORKS_EXPLODE = 17; + static const std::uint8_t FIREWORKS_EXPLODE = 17; - static const std::uint8_t IN_LOVE_HEARTS = 18; + static const std::uint8_t IN_LOVE_HEARTS = 18; }; diff --git a/Minecraft.World/Entities/EntityPos.cpp b/Minecraft.World/Entities/EntityPos.cpp index b086cc2a5..2535900aa 100644 --- a/Minecraft.World/Entities/EntityPos.cpp +++ b/Minecraft.World/Entities/EntityPos.cpp @@ -2,61 +2,54 @@ #include "Entity.h" #include "EntityPos.h" -EntityPos::EntityPos(double x, double y, double z, float yRot, float xRot) -{ - this->x = x; - this->y = y; - this->z = z; - this->yRot = yRot; - this->xRot = xRot; - rot = true; - move = true; +EntityPos::EntityPos(double x, double y, double z, float yRot, float xRot) { + this->x = x; + this->y = y; + this->z = z; + this->yRot = yRot; + this->xRot = xRot; + rot = true; + move = true; } -EntityPos::EntityPos(double x, double y, double z) -{ - yRot = xRot = 0.0f; +EntityPos::EntityPos(double x, double y, double z) { + yRot = xRot = 0.0f; - this->x = x; - this->y = y; - this->z = z; - move = true; - rot = false; + this->x = x; + this->y = y; + this->z = z; + move = true; + rot = false; } -EntityPos::EntityPos(float yRot, float xRot) -{ - x = y = z = 0.0; +EntityPos::EntityPos(float yRot, float xRot) { + x = y = z = 0.0; - this->yRot = yRot; - this->xRot = xRot; - rot = true; - move = false; + this->yRot = yRot; + this->xRot = xRot; + rot = true; + move = false; } -EntityPos *EntityPos::lerp(std::shared_ptr e, float f) -{ - double xd = e->x+(x-e->x)*f; - double yd = e->y+(y-e->y)*f; - double zd = e->z+(z-e->z)*f; +EntityPos* EntityPos::lerp(std::shared_ptr e, float f) { + double xd = e->x + (x - e->x) * f; + double yd = e->y + (y - e->y) * f; + double zd = e->z + (z - e->z) * f; - float yrdd = Mth::wrapDegrees(yRot - e->yRot); - float xrdd = Mth::wrapDegrees(xRot - e->xRot); + float yrdd = Mth::wrapDegrees(yRot - e->yRot); + float xrdd = Mth::wrapDegrees(xRot - e->xRot); - float yrd = Mth::wrapDegrees(e->yRot + yrdd * f); - float xrd = Mth::wrapDegrees(e->xRot + xrdd * f); + float yrd = Mth::wrapDegrees(e->yRot + yrdd * f); + float xrd = Mth::wrapDegrees(e->xRot + xrdd * f); - if (rot && move) - { - return new EntityPos(xd, yd, zd, yrd, xrd); - } - if (move) - { - return new EntityPos(xd, yd, zd); - } - if (rot) - { - return new EntityPos(yrd, xrd); - } - return NULL; + if (rot && move) { + return new EntityPos(xd, yd, zd, yrd, xrd); + } + if (move) { + return new EntityPos(xd, yd, zd); + } + if (rot) { + return new EntityPos(yrd, xrd); + } + return NULL; } \ No newline at end of file diff --git a/Minecraft.World/Entities/EntityPos.h b/Minecraft.World/Entities/EntityPos.h index 6b82af01e..f5df74be1 100644 --- a/Minecraft.World/Entities/EntityPos.h +++ b/Minecraft.World/Entities/EntityPos.h @@ -1,15 +1,14 @@ #pragma once -class EntityPos -{ +class EntityPos { public: - double x, y, z; - float yRot, xRot; - bool rot; - bool move; + double x, y, z; + float yRot, xRot; + bool rot; + bool move; - EntityPos(double x, double y, double z, float yRot, float xRot); - EntityPos(double x, double y, double z); - EntityPos(float yRot, float xRot); - EntityPos *lerp(std::shared_ptr e, float f); + EntityPos(double x, double y, double z, float yRot, float xRot); + EntityPos(double x, double y, double z); + EntityPos(float yRot, float xRot); + EntityPos* lerp(std::shared_ptr e, float f); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/FlyingMob.cpp b/Minecraft.World/Entities/FlyingMob.cpp index 4e5127b1a..e3dddf6b3 100644 --- a/Minecraft.World/Entities/FlyingMob.cpp +++ b/Minecraft.World/Entities/FlyingMob.cpp @@ -4,78 +4,65 @@ #include "../Headers/net.minecraft.world.phys.h" #include "FlyingMob.h" -FlyingMob::FlyingMob(Level *level) : Mob( level ) -{ +FlyingMob::FlyingMob(Level* level) : Mob(level) {} + +void FlyingMob::causeFallDamage(float distance) { + // this method is empty because flying creatures should + // not trigger the "fallOn" tile calls (such as trampling crops) } -void FlyingMob::causeFallDamage(float distance) -{ - // this method is empty because flying creatures should - // not trigger the "fallOn" tile calls (such as trampling crops) +void FlyingMob::travel(float xa, float ya) { + if (isInWater()) { + moveRelative(xa, ya, 0.02f); + move(xd, yd, zd); + + xd *= 0.80f; + yd *= 0.80f; + zd *= 0.80f; + } else if (isInLava()) { + moveRelative(xa, ya, 0.02f); + move(xd, yd, zd); + xd *= 0.50f; + yd *= 0.50f; + zd *= 0.50f; + } else { + float friction = 0.91f; + if (onGround) { + friction = 0.6f * 0.91f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.91f; + } + } + + float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / + (friction * friction * friction); + moveRelative(xa, ya, (onGround ? 0.1f * friction2 : 0.02f)); + + friction = 0.91f; + if (onGround) { + friction = 0.6f * 0.91f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.91f; + } + } + + move(xd, yd, zd); + + xd *= friction; + yd *= friction; + zd *= friction; + } + walkAnimSpeedO = walkAnimSpeed; + double xxd = x - xo; + double zzd = z - zo; + float wst = (float)sqrt(xxd * xxd + zzd * zzd) * 4; + if (wst > 1) wst = 1; + walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; + walkAnimPos += walkAnimSpeed; } -void FlyingMob::travel(float xa, float ya) -{ - if (isInWater()) - { - moveRelative(xa, ya, 0.02f); - move(xd, yd, zd); - - xd *= 0.80f; - yd *= 0.80f; - zd *= 0.80f; - } - else if (isInLava()) - { - moveRelative(xa, ya, 0.02f); - move(xd, yd, zd); - xd *= 0.50f; - yd *= 0.50f; - zd *= 0.50f; - } - else - { - float friction = 0.91f; - if (onGround) - { - friction = 0.6f * 0.91f; - int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.91f; - } - } - - float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / (friction * friction * friction); - moveRelative(xa, ya, (onGround ? 0.1f * friction2 : 0.02f)); - - friction = 0.91f; - if (onGround) - { - friction = 0.6f * 0.91f; - int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.91f; - } - } - - move(xd, yd, zd); - - xd *= friction; - yd *= friction; - zd *= friction; - } - walkAnimSpeedO = walkAnimSpeed; - double xxd = x - xo; - double zzd = z - zo; - float wst = (float) sqrt(xxd * xxd + zzd * zzd) * 4; - if (wst > 1) wst = 1; - walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; - walkAnimPos += walkAnimSpeed; -} - -bool FlyingMob::onLadder() -{ - return false; -} \ No newline at end of file +bool FlyingMob::onLadder() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Entities/FlyingMob.h b/Minecraft.World/Entities/FlyingMob.h index f3bb2a036..8169997e5 100644 --- a/Minecraft.World/Entities/FlyingMob.h +++ b/Minecraft.World/Entities/FlyingMob.h @@ -4,15 +4,14 @@ class Level; -class FlyingMob : public Mob -{ +class FlyingMob : public Mob { public: - FlyingMob(Level *level); + FlyingMob(Level* level); protected: - virtual void causeFallDamage(float distance); + virtual void causeFallDamage(float distance); public: - virtual void travel(float xa, float ya); - virtual bool onLadder(); + virtual void travel(float xa, float ya); + virtual bool onLadder(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/GlobalEntity.cpp b/Minecraft.World/Entities/GlobalEntity.cpp index 7c825e2d0..beb18c0f5 100644 --- a/Minecraft.World/Entities/GlobalEntity.cpp +++ b/Minecraft.World/Entities/GlobalEntity.cpp @@ -1,3 +1,2 @@ #include "../Platform/stdafx.h" #include "GlobalEntity.h" - diff --git a/Minecraft.World/Entities/GlobalEntity.h b/Minecraft.World/Entities/GlobalEntity.h index 3d0892baa..ff9cf7a33 100644 --- a/Minecraft.World/Entities/GlobalEntity.h +++ b/Minecraft.World/Entities/GlobalEntity.h @@ -3,9 +3,8 @@ class Level; -//class GlobalEntity : public Entity -class GlobalEntity : public Entity -{ +// class GlobalEntity : public Entity +class GlobalEntity : public Entity { public: - GlobalEntity(Level *level) : Entity( level ) {}; + GlobalEntity(Level* level) : Entity(level) {}; }; \ No newline at end of file diff --git a/Minecraft.World/Entities/HangingEntity.cpp b/Minecraft.World/Entities/HangingEntity.cpp index bf59ac681..d78258a30 100644 --- a/Minecraft.World/Entities/HangingEntity.cpp +++ b/Minecraft.World/Entities/HangingEntity.cpp @@ -7,286 +7,249 @@ #include "../Headers/com.mojang.nbt.h" #include "HangingEntity.h" - - -void HangingEntity::_init(Level *level) -{ - checkInterval = 0; - dir = 0; - xTile = yTile = zTile = 0; +void HangingEntity::_init(Level* level) { + checkInterval = 0; + dir = 0; + xTile = yTile = zTile = 0; } -HangingEntity::HangingEntity(Level *level) : Entity( level ) -{ - _init(level); +HangingEntity::HangingEntity(Level* level) : Entity(level) { + _init(level); - this->heightOffset = 0; - this->setSize(0.5f, 0.5f); + this->heightOffset = 0; + this->setSize(0.5f, 0.5f); } -HangingEntity::HangingEntity(Level *level, int xTile, int yTile, int zTile, int dir) : Entity( level ) -{ - _init(level); - //motive = NULL; - this->heightOffset = 0; - this->setSize(0.5f, 0.5f); - this->xTile = xTile; - this->yTile = yTile; - this->zTile = zTile; +HangingEntity::HangingEntity(Level* level, int xTile, int yTile, int zTile, + int dir) + : Entity(level) { + _init(level); + // motive = NULL; + this->heightOffset = 0; + this->setSize(0.5f, 0.5f); + this->xTile = xTile; + this->yTile = yTile; + this->zTile = zTile; } -void HangingEntity::setDir(int dir) -{ - this->dir = dir; - this->yRotO = this->yRot = (float)(dir * 90); +void HangingEntity::setDir(int dir) { + this->dir = dir; + this->yRotO = this->yRot = (float)(dir * 90); - float w = (float)getWidth(); - float h = (float)getHeight(); - float d = (float)getWidth(); + float w = (float)getWidth(); + float h = (float)getHeight(); + float d = (float)getWidth(); - if (dir == Direction::NORTH || dir == Direction::SOUTH) - { - d = 0.5f; - yRot = yRotO = (float)(Direction::DIRECTION_OPPOSITE[dir] * 90); - } - else - { - w = 0.5f; - } + if (dir == Direction::NORTH || dir == Direction::SOUTH) { + d = 0.5f; + yRot = yRotO = (float)(Direction::DIRECTION_OPPOSITE[dir] * 90); + } else { + w = 0.5f; + } - w /= 32.0f; - h /= 32.0f; - d /= 32.0f; + w /= 32.0f; + h /= 32.0f; + d /= 32.0f; - float x = xTile + 0.5f; - float y = yTile + 0.5f; - float z = zTile + 0.5f; + float x = xTile + 0.5f; + float y = yTile + 0.5f; + float z = zTile + 0.5f; - float fOffs = 0.5f + 1.0f / 16.0f; + float fOffs = 0.5f + 1.0f / 16.0f; - if (dir == Direction::NORTH) z -= fOffs; - if (dir == Direction::WEST) x -= fOffs; - if (dir == Direction::SOUTH) z += fOffs; - if (dir == Direction::EAST) x += fOffs; + if (dir == Direction::NORTH) z -= fOffs; + if (dir == Direction::WEST) x -= fOffs; + if (dir == Direction::SOUTH) z += fOffs; + if (dir == Direction::EAST) x += fOffs; - if (dir == Direction::NORTH) x -= offs(getWidth()); - if (dir == Direction::WEST) z += offs(getWidth()); - if (dir == Direction::SOUTH) x += offs(getWidth()); - if (dir == Direction::EAST) z -= offs(getWidth()); - y += offs(getHeight()); + if (dir == Direction::NORTH) x -= offs(getWidth()); + if (dir == Direction::WEST) z += offs(getWidth()); + if (dir == Direction::SOUTH) x += offs(getWidth()); + if (dir == Direction::EAST) z -= offs(getWidth()); + y += offs(getHeight()); - this->setPos(x, y, z); + this->setPos(x, y, z); - float ss = -(0.5f / 16.0f); + float ss = -(0.5f / 16.0f); - // 4J Stu - Due to rotations the bb couold be set with a lower bound x/z being higher than the higher bound - float x0 = x - w - ss; - float x1 = x + w + ss; - float y0 = y - h - ss; - float y1 = y + h + ss; - float z0 = z - d - ss; - float z1 = z + d + ss; - bb->set(std::min(x0,x1), std::min(y0,y1), std::min(z0,z1), std::max(x0,x1), std::max(y0,y1), std::max(z0,z1)); + // 4J Stu - Due to rotations the bb couold be set with a lower bound x/z + // being higher than the higher bound + float x0 = x - w - ss; + float x1 = x + w + ss; + float y0 = y - h - ss; + float y1 = y + h + ss; + float z0 = z - d - ss; + float z1 = z + d + ss; + bb->set(std::min(x0, x1), std::min(y0, y1), std::min(z0, z1), + std::max(x0, x1), std::max(y0, y1), std::max(z0, z1)); } -float HangingEntity::offs(int w) -{ - if (w == 32) return 0.5f; - if (w == 64) return 0.5f; - return 0.0f; +float HangingEntity::offs(int w) { + if (w == 32) return 0.5f; + if (w == 64) return 0.5f; + return 0.0f; } -void HangingEntity::tick() -{ - if (checkInterval++ == 20 * 5 && !level->isClientSide)//isClientSide) - { - checkInterval = 0; - if (!removed && !survives()) - { - remove(); - dropItem(); - } - } +void HangingEntity::tick() { + if (checkInterval++ == 20 * 5 && !level->isClientSide) // isClientSide) + { + checkInterval = 0; + if (!removed && !survives()) { + remove(); + dropItem(); + } + } } -bool HangingEntity::survives() -{ - if (level->getCubes(shared_from_this(), bb)->size()!=0)//isEmpty()) - { - return false; - } - else - { - int ws = std::max(1, getWidth() / 16); - int hs = std::max(1, getHeight() / 16); +bool HangingEntity::survives() { + if (level->getCubes(shared_from_this(), bb)->size() != 0) // isEmpty()) + { + return false; + } else { + int ws = std::max(1, getWidth() / 16); + int hs = std::max(1, getHeight() / 16); - int xt = xTile; - int yt = yTile; - int zt = zTile; - if (dir == Direction::NORTH) xt = Mth::floor(x - getWidth() / 32.0f); - if (dir == Direction::WEST) zt = Mth::floor(z - getWidth() / 32.0f); - if (dir == Direction::SOUTH) xt = Mth::floor(x - getWidth() / 32.0f); - if (dir == Direction::EAST) zt = Mth::floor(z - getWidth() / 32.0f); - yt = Mth::floor(y - getHeight() / 32.0f); + int xt = xTile; + int yt = yTile; + int zt = zTile; + if (dir == Direction::NORTH) xt = Mth::floor(x - getWidth() / 32.0f); + if (dir == Direction::WEST) zt = Mth::floor(z - getWidth() / 32.0f); + if (dir == Direction::SOUTH) xt = Mth::floor(x - getWidth() / 32.0f); + if (dir == Direction::EAST) zt = Mth::floor(z - getWidth() / 32.0f); + yt = Mth::floor(y - getHeight() / 32.0f); - for (int ss = 0; ss < ws; ss++) - { - for (int yy = 0; yy < hs; yy++) - { - Material *m; - if (dir == Direction::NORTH || dir == Direction::SOUTH) - { - m = level->getMaterial(xt + ss, yt + yy, zTile); - } - else - { - m = level->getMaterial(xTile, yt + yy, zt + ss); - } - if (!m->isSolid()) - { - return false; - } - } + for (int ss = 0; ss < ws; ss++) { + for (int yy = 0; yy < hs; yy++) { + Material* m; + if (dir == Direction::NORTH || dir == Direction::SOUTH) { + m = level->getMaterial(xt + ss, yt + yy, zTile); + } else { + m = level->getMaterial(xTile, yt + yy, zt + ss); + } + if (!m->isSolid()) { + return false; + } + } - std::vector > *entities = level->getEntities(shared_from_this(), bb); + std::vector >* entities = + level->getEntities(shared_from_this(), bb); - if (entities != NULL && entities->size() > 0) - { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = (*it); - if(std::dynamic_pointer_cast(e) != NULL) - { - return false; - } - } - } - } - } - return true; + if (entities != NULL && entities->size() > 0) { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = (*it); + if (std::dynamic_pointer_cast(e) != NULL) { + return false; + } + } + } + } + } + return true; } -bool HangingEntity::isPickable() -{ - return true; +bool HangingEntity::isPickable() { return true; } + +bool HangingEntity::skipAttackInteraction(std::shared_ptr source) { + if (source->GetType() == eTYPE_PLAYER) { + return hurt(DamageSource::playerAttack( + std::dynamic_pointer_cast(source)), + 0); + } + return false; } -bool HangingEntity::skipAttackInteraction(std::shared_ptr source) -{ - if(source->GetType()==eTYPE_PLAYER) - { - return hurt(DamageSource::playerAttack(std::dynamic_pointer_cast( source)), 0); - } - return false; -} +bool HangingEntity::hurt(DamageSource* source, int damage) { + if (!removed && !level->isClientSide) { + if (dynamic_cast(source) != NULL) { + std::shared_ptr sourceEntity = source->getDirectEntity(); -bool HangingEntity::hurt(DamageSource *source, int damage) -{ - if (!removed && !level->isClientSide) - { - if (dynamic_cast(source) != NULL) - { - std::shared_ptr sourceEntity = source->getDirectEntity(); + if (std::dynamic_pointer_cast(sourceEntity) != NULL && + !std::dynamic_pointer_cast(sourceEntity) + ->isAllowedToHurtEntity(shared_from_this())) { + return false; + } + } - if (std::dynamic_pointer_cast(sourceEntity) != NULL && !std::dynamic_pointer_cast(sourceEntity)->isAllowedToHurtEntity(shared_from_this()) ) - { - return false; - } - } + remove(); + markHurt(); - remove(); - markHurt(); + std::shared_ptr player = nullptr; + std::shared_ptr e = source->getEntity(); + if (e != NULL && ((e->GetType() & eTYPE_PLAYER) != + 0)) // check if it's serverplayer or player + { + player = std::dynamic_pointer_cast(e); + } - std::shared_ptr player = nullptr; - std::shared_ptr e = source->getEntity(); - if (e!=NULL && ((e->GetType() & eTYPE_PLAYER)!=0) ) // check if it's serverplayer or player - { - player = std::dynamic_pointer_cast( e ); - } + if (player != NULL && player->abilities.instabuild) { + return true; + } - if (player != NULL && player->abilities.instabuild) - { - return true; - } - - dropItem(); - } - return true; + dropItem(); + } + return true; } // 4J - added noEntityCubes parameter -void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) -{ - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) - { - remove(); - dropItem(); - } +void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) { + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { + remove(); + dropItem(); + } } -void HangingEntity::push(double xa, double ya, double za) -{ - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) - { - remove(); - dropItem(); - } +void HangingEntity::push(double xa, double ya, double za) { + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { + remove(); + dropItem(); + } } -void HangingEntity::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putByte(L"Direction", (uint8_t) dir); - tag->putInt(L"TileX", xTile); - tag->putInt(L"TileY", yTile); - tag->putInt(L"TileZ", zTile); +void HangingEntity::addAdditonalSaveData(CompoundTag* tag) { + tag->putByte(L"Direction", (uint8_t)dir); + tag->putInt(L"TileX", xTile); + tag->putInt(L"TileY", yTile); + tag->putInt(L"TileZ", zTile); - // Back compat - switch (dir) - { - case Direction::NORTH: - tag->putByte(L"Dir", (uint8_t) 0); - break; - case Direction::WEST: - tag->putByte(L"Dir", (uint8_t) 1); - break; - case Direction::SOUTH: - tag->putByte(L"Dir", (uint8_t) 2); - break; - case Direction::EAST: - tag->putByte(L"Dir", (uint8_t) 3); - break; - } + // Back compat + switch (dir) { + case Direction::NORTH: + tag->putByte(L"Dir", (uint8_t)0); + break; + case Direction::WEST: + tag->putByte(L"Dir", (uint8_t)1); + break; + case Direction::SOUTH: + tag->putByte(L"Dir", (uint8_t)2); + break; + case Direction::EAST: + tag->putByte(L"Dir", (uint8_t)3); + break; + } } -void HangingEntity::readAdditionalSaveData(CompoundTag *tag) -{ - if (tag->contains(L"Direction")) - { - dir = tag->getByte(L"Direction"); - } - else - { - switch (tag->getByte(L"Dir")) - { - case 0: - dir = Direction::NORTH; - break; - case 1: - dir = Direction::WEST; - break; - case 2: - dir = Direction::SOUTH; - break; - case 3: - dir = Direction::EAST; - break; - } - } - xTile = tag->getInt(L"TileX"); - yTile = tag->getInt(L"TileY"); - zTile = tag->getInt(L"TileZ"); - setDir(dir); +void HangingEntity::readAdditionalSaveData(CompoundTag* tag) { + if (tag->contains(L"Direction")) { + dir = tag->getByte(L"Direction"); + } else { + switch (tag->getByte(L"Dir")) { + case 0: + dir = Direction::NORTH; + break; + case 1: + dir = Direction::WEST; + break; + case 2: + dir = Direction::SOUTH; + break; + case 3: + dir = Direction::EAST; + break; + } + } + xTile = tag->getInt(L"TileX"); + yTile = tag->getInt(L"TileY"); + zTile = tag->getInt(L"TileZ"); + setDir(dir); } - - diff --git a/Minecraft.World/Entities/HangingEntity.h b/Minecraft.World/Entities/HangingEntity.h index e03bd6fe9..622148519 100644 --- a/Minecraft.World/Entities/HangingEntity.h +++ b/Minecraft.World/Entities/HangingEntity.h @@ -3,40 +3,41 @@ #include "Entity.h" -class HangingEntity : public Entity -{ +class HangingEntity : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_HANGING_ENTITY; } + eINSTANCEOF GetType() { return eTYPE_HANGING_ENTITY; } + private: + void _init(Level* level); + float offs(int w); - void _init(Level *level); - float offs(int w); + int checkInterval; + // eINSTANCEOF eType; - int checkInterval; - //eINSTANCEOF eType; - -protected: - virtual void defineSynchedData() {}; +protected: + virtual void defineSynchedData() {}; public: - int dir; - int xTile, yTile, zTile; + int dir; + int xTile, yTile, zTile; - HangingEntity(Level *level); - HangingEntity(Level *level, int xTile, int yTile, int zTile, int dir); - void setDir(int dir); - bool survives(); + HangingEntity(Level* level); + HangingEntity(Level* level, int xTile, int yTile, int zTile, int dir); + void setDir(int dir); + bool survives(); - virtual void tick(); - virtual bool isPickable(); - virtual bool skipAttackInteraction(std::shared_ptr source); - virtual bool hurt(DamageSource *source, int damage); - virtual void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter - virtual void push(double xa, double ya, double za); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void tick(); + virtual bool isPickable(); + virtual bool skipAttackInteraction(std::shared_ptr source); + virtual bool hurt(DamageSource* source, int damage); + virtual void move( + double xa, double ya, double za, + bool noEntityCubes = false); // 4J - added noEntityCubes parameter + virtual void push(double xa, double ya, double za); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); - virtual int getWidth()=0; - virtual int getHeight()=0; - virtual void dropItem()=0; + virtual int getWidth() = 0; + virtual int getHeight() = 0; + virtual void dropItem() = 0; }; diff --git a/Minecraft.World/Entities/IndirectEntityDamageSource.cpp b/Minecraft.World/Entities/IndirectEntityDamageSource.cpp index a1fc6ae95..73646db66 100644 --- a/Minecraft.World/Entities/IndirectEntityDamageSource.cpp +++ b/Minecraft.World/Entities/IndirectEntityDamageSource.cpp @@ -4,45 +4,47 @@ #include "../Headers/net.minecraft.world.damagesource.h" #include "../Headers/net.minecraft.network.packet.h" -//IndirectEntityDamageSource::IndirectEntityDamageSource(const std::wstring &msgId, std::shared_ptr entity, std::shared_ptr owner) : EntityDamageSource(msgId, entity) -IndirectEntityDamageSource::IndirectEntityDamageSource(ChatPacket::EChatPacketMessage msgId, std::shared_ptr entity, std::shared_ptr owner) : EntityDamageSource(msgId, entity) -{ - this->owner = owner; +// IndirectEntityDamageSource::IndirectEntityDamageSource(const std::wstring +// &msgId, std::shared_ptr entity, std::shared_ptr owner) : +// EntityDamageSource(msgId, entity) +IndirectEntityDamageSource::IndirectEntityDamageSource( + ChatPacket::EChatPacketMessage msgId, std::shared_ptr entity, + std::shared_ptr owner) + : EntityDamageSource(msgId, entity) { + this->owner = owner; } // 4J Stu - Brought forward from 1.2.3 to fix #46422 -std::shared_ptr IndirectEntityDamageSource::getDirectEntity() -{ - return entity; +std::shared_ptr IndirectEntityDamageSource::getDirectEntity() { + return entity; } -std::shared_ptr IndirectEntityDamageSource::getEntity() -{ - return owner; +std::shared_ptr IndirectEntityDamageSource::getEntity() { + return owner; } -//std::wstring IndirectEntityDamageSource::getLocalizedDeathMessage(std::shared_ptr player) +// std::wstring +// IndirectEntityDamageSource::getLocalizedDeathMessage(std::shared_ptr +// player) //{ // return L"death." + msgId + player->name + owner->getAName(); // //return I18n.get("death." + msgId, player.name, owner.getAName()); -//} +// } -std::shared_ptr IndirectEntityDamageSource::getDeathMessagePacket(std::shared_ptr player) -{ - std::wstring additional = L""; - int type; - if(owner != NULL) - { - type = owner->GetType(); - if(type == eTYPE_SERVERPLAYER) - { - std::shared_ptr sourcePlayer = std::dynamic_pointer_cast(owner); - if(sourcePlayer != NULL) additional = sourcePlayer->name; - } - } - else - { - type = entity->GetType(); - } - return std::shared_ptr( new ChatPacket(player->name, m_msgId, type, additional ) ); +std::shared_ptr IndirectEntityDamageSource::getDeathMessagePacket( + std::shared_ptr player) { + std::wstring additional = L""; + int type; + if (owner != NULL) { + type = owner->GetType(); + if (type == eTYPE_SERVERPLAYER) { + std::shared_ptr sourcePlayer = + std::dynamic_pointer_cast(owner); + if (sourcePlayer != NULL) additional = sourcePlayer->name; + } + } else { + type = entity->GetType(); + } + return std::shared_ptr( + new ChatPacket(player->name, m_msgId, type, additional)); } \ No newline at end of file diff --git a/Minecraft.World/Entities/IndirectEntityDamageSource.h b/Minecraft.World/Entities/IndirectEntityDamageSource.h index 83c461171..ae7ffd16a 100644 --- a/Minecraft.World/Entities/IndirectEntityDamageSource.h +++ b/Minecraft.World/Entities/IndirectEntityDamageSource.h @@ -1,25 +1,29 @@ #pragma once - #include "EntityDamageSource.h" class Entity; class Player; -class IndirectEntityDamageSource : public EntityDamageSource -{ +class IndirectEntityDamageSource : public EntityDamageSource { private: - std::shared_ptr owner; + std::shared_ptr owner; public: - //IndirectEntityDamageSource(const std::wstring &msgId, std::shared_ptr entity, std::shared_ptr owner); - IndirectEntityDamageSource(ChatPacket::EChatPacketMessage msgId, std::shared_ptr entity, std::shared_ptr owner); - virtual ~IndirectEntityDamageSource() { } + // IndirectEntityDamageSource(const std::wstring &msgId, + // std::shared_ptr entity, std::shared_ptr owner); + IndirectEntityDamageSource(ChatPacket::EChatPacketMessage msgId, + std::shared_ptr entity, + std::shared_ptr owner); + virtual ~IndirectEntityDamageSource() {} - virtual std::shared_ptr getDirectEntity(); // 4J Stu - Brought forward from 1.2.3 to fix #46422 - virtual std::shared_ptr getEntity(); + virtual std::shared_ptr + getDirectEntity(); // 4J Stu - Brought forward from 1.2.3 to fix #46422 + virtual std::shared_ptr getEntity(); - // 4J Stu - Made return a packet - //virtual std::wstring getLocalizedDeathMessage(std::shared_ptr player); - virtual std::shared_ptr getDeathMessagePacket(std::shared_ptr player); + // 4J Stu - Made return a packet + // virtual std::wstring getLocalizedDeathMessage(std::shared_ptr + // player); + virtual std::shared_ptr getDeathMessagePacket( + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/InstantaneousMobEffect.cpp b/Minecraft.World/Entities/InstantaneousMobEffect.cpp index 247049831..6821f59b3 100644 --- a/Minecraft.World/Entities/InstantaneousMobEffect.cpp +++ b/Minecraft.World/Entities/InstantaneousMobEffect.cpp @@ -1,16 +1,13 @@ #include "../Platform/stdafx.h" #include "../Headers/net.minecraft.world.effect.h" -InstantenousMobEffect::InstantenousMobEffect(int id, bool isHarmful, eMinecraftColour color) : MobEffect(id, isHarmful, color) -{ -} +InstantenousMobEffect::InstantenousMobEffect(int id, bool isHarmful, + eMinecraftColour color) + : MobEffect(id, isHarmful, color) {} -bool InstantenousMobEffect::isInstantenous() -{ - return true; -} +bool InstantenousMobEffect::isInstantenous() { return true; } -bool InstantenousMobEffect::isDurationEffectTick(int remainingDuration, int amplification) -{ - return remainingDuration >= 1; +bool InstantenousMobEffect::isDurationEffectTick(int remainingDuration, + int amplification) { + return remainingDuration >= 1; } \ No newline at end of file diff --git a/Minecraft.World/Entities/InstantaneousMobEffect.h b/Minecraft.World/Entities/InstantaneousMobEffect.h index 8da32820a..186dff9bb 100644 --- a/Minecraft.World/Entities/InstantaneousMobEffect.h +++ b/Minecraft.World/Entities/InstantaneousMobEffect.h @@ -2,10 +2,9 @@ #include "MobEffect.h" -class InstantenousMobEffect : public MobEffect -{ +class InstantenousMobEffect : public MobEffect { public: - InstantenousMobEffect(int id, bool isHarmful, eMinecraftColour color); - bool isInstantenous(); - bool isDurationEffectTick(int remainingDuration, int amplification); + InstantenousMobEffect(int id, bool isHarmful, eMinecraftColour color); + bool isInstantenous(); + bool isDurationEffectTick(int remainingDuration, int amplification); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/ItemEntity.cpp b/Minecraft.World/Entities/ItemEntity.cpp index fc303034c..6b9824ea1 100644 --- a/Minecraft.World/Entities/ItemEntity.cpp +++ b/Minecraft.World/Entities/ItemEntity.cpp @@ -13,294 +13,270 @@ #include "ItemEntity.h" #include "../Util/SoundTypes.h" +void ItemEntity::_init() { + age = 0; + throwTime = 0; + health = 5; + bobOffs = (float)(Math::random() * PI * 2); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); -void ItemEntity::_init() -{ - age = 0; - throwTime = 0; - health = 5; - bobOffs = (float) (Math::random() * PI * 2); - - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - setSize(0.25f, 0.25f); - heightOffset = bbHeight / 2.0f; + setSize(0.25f, 0.25f); + heightOffset = bbHeight / 2.0f; } -void ItemEntity::_init(Level *level, double x, double y, double z) -{ - _init(); +void ItemEntity::_init(Level* level, double x, double y, double z) { + _init(); - setPos(x, y, z); + setPos(x, y, z); - yRot = (float) (Math::random() * 360); + yRot = (float)(Math::random() * 360); - xd = (float) (Math::random() * 0.2f - 0.1f); - yd = +0.2f; - zd = (float) (Math::random() * 0.2f - 0.1f); + xd = (float)(Math::random() * 0.2f - 0.1f); + yd = +0.2f; + zd = (float)(Math::random() * 0.2f - 0.1f); } -ItemEntity::ItemEntity(Level *level, double x, double y, double z) : Entity(level) -{ - _init(level,x,y,z); +ItemEntity::ItemEntity(Level* level, double x, double y, double z) + : Entity(level) { + _init(level, x, y, z); } -ItemEntity::ItemEntity(Level *level, double x, double y, double z, std::shared_ptr item) : Entity( level ) -{ - _init(level,x,y,z); - setItem(item); +ItemEntity::ItemEntity(Level* level, double x, double y, double z, + std::shared_ptr item) + : Entity(level) { + _init(level, x, y, z); + setItem(item); } -bool ItemEntity::makeStepSound() -{ - return false; +bool ItemEntity::makeStepSound() { return false; } + +ItemEntity::ItemEntity(Level* level) : Entity(level) { _init(); } + +void ItemEntity::defineSynchedData() { + getEntityData()->defineNULL(DATA_ITEM, NULL); } -ItemEntity::ItemEntity(Level *level) : Entity( level ) -{ - _init(); +void ItemEntity::tick() { + Entity::tick(); + + if (throwTime > 0) throwTime--; + xo = x; + yo = y; + zo = z; + + yd -= 0.04f; + noPhysics = checkInTile(x, (bb->y0 + bb->y1) / 2, z); + + // 4J - added parameter here so that these don't care about colliding with + // other entities + move(xd, yd, zd, true); + + bool moved = (int)xo != (int)x || (int)yo != (int)y || (int)zo != (int)z; + + if (moved || tickCount % 25 == 0) { + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) == + Material::lava) { + yd = 0.2f; + xd = (random->nextFloat() - random->nextFloat()) * 0.2f; + zd = (random->nextFloat() - random->nextFloat()) * 0.2f; + MemSect(31); + level->playSound(shared_from_this(), eSoundType_RANDOM_FIZZ, 0.4f, + 2.0f + random->nextFloat() * 0.4f); + MemSect(0); + } + + if (!level->isClientSide) { + mergeWithNeighbours(); + } + } + + float friction = 0.98f; + if (onGround) { + friction = 0.6f * 0.98f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.98f; + } + } + + xd *= friction; + yd *= 0.98f; + zd *= friction; + + if (onGround) { + yd *= -0.5f; + } + + tickCount++; + age++; + if (!level->isClientSide && age >= LIFETIME) { + remove(); + } } -void ItemEntity::defineSynchedData() -{ - getEntityData()->defineNULL(DATA_ITEM, NULL); +void ItemEntity::mergeWithNeighbours() { + std::vector >* neighbours = + level->getEntitiesOfClass(typeid(*this), bb->grow(0.5, 0, 0.5)); + for (AUTO_VAR(it, neighbours->begin()); it != neighbours->end(); ++it) { + std::shared_ptr entity = + std::dynamic_pointer_cast(*it); + merge(entity); + } + delete neighbours; } -void ItemEntity::tick() -{ - Entity::tick(); - - if (throwTime > 0) throwTime--; - xo = x; - yo = y; - zo = z; +bool ItemEntity::merge(std::shared_ptr target) { + if (target == shared_from_this()) return false; + if (!target->isAlive() || !this->isAlive()) return false; + std::shared_ptr myItem = this->getItem(); + std::shared_ptr targetItem = target->getItem(); - yd -= 0.04f; - noPhysics = checkInTile(x, (bb->y0 + bb->y1) / 2, z); - - // 4J - added parameter here so that these don't care about colliding with other entities - move(xd, yd, zd, true); + if (targetItem->getItem() != myItem->getItem()) return false; + if (targetItem->hasTag() ^ myItem->hasTag()) return false; + if (targetItem->hasTag() && !targetItem->getTag()->equals(myItem->getTag())) + return false; + if (targetItem->getItem()->isStackedByData() && + targetItem->getAuxValue() != myItem->getAuxValue()) + return false; + if (targetItem->count < myItem->count) + return target->merge( + std::dynamic_pointer_cast(shared_from_this())); + if (targetItem->count + myItem->count > targetItem->getMaxStackSize()) + return false; - bool moved = (int) xo != (int) x || (int) yo != (int) y || (int) zo != (int) z; + targetItem->count += myItem->count; + target->throwTime = std::max(target->throwTime, this->throwTime); + target->age = std::min(target->age, this->age); + target->setItem(targetItem); + remove(); - if (moved || tickCount % 25 == 0) - { - if (level->getMaterial( Mth::floor(x), Mth::floor(y), Mth::floor(z)) == Material::lava) - { - yd = 0.2f; - xd = (random->nextFloat() - random->nextFloat()) * 0.2f; - zd = (random->nextFloat() - random->nextFloat()) * 0.2f; - MemSect(31); - level->playSound(shared_from_this(), eSoundType_RANDOM_FIZZ, 0.4f, 2.0f + random->nextFloat() * 0.4f); - MemSect(0); - } - - if (!level->isClientSide) - { - mergeWithNeighbours(); - } - } - - float friction = 0.98f; - if (onGround) - { - friction = 0.6f * 0.98f; - int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z) ); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.98f; - } - } - - xd *= friction; - yd *= 0.98f; - zd *= friction; - - if (onGround) - { - yd *= -0.5f; - } - - tickCount++; - age++; - if (!level->isClientSide && age >= LIFETIME) - { - remove(); - } + return true; } -void ItemEntity::mergeWithNeighbours() -{ - std::vector > *neighbours = level->getEntitiesOfClass(typeid(*this), bb->grow(0.5, 0, 0.5)); - for(AUTO_VAR(it, neighbours->begin()); it != neighbours->end(); ++it) - { - std::shared_ptr entity = std::dynamic_pointer_cast(*it); - merge(entity); - } - delete neighbours; +void ItemEntity::setShortLifeTime() { + // reduce lifetime to one minute + age = LIFETIME - (60 * SharedConstants::TICKS_PER_SECOND); } -bool ItemEntity::merge(std::shared_ptr target) -{ - if (target == shared_from_this()) return false; - if (!target->isAlive() || !this->isAlive()) return false; - std::shared_ptr myItem = this->getItem(); - std::shared_ptr targetItem = target->getItem(); - - if (targetItem->getItem() != myItem->getItem()) return false; - if (targetItem->hasTag() ^ myItem->hasTag()) return false; - if (targetItem->hasTag() && !targetItem->getTag()->equals(myItem->getTag())) return false; - if (targetItem->getItem()->isStackedByData() && targetItem->getAuxValue() != myItem->getAuxValue()) return false; - if (targetItem->count < myItem->count) return target->merge(std::dynamic_pointer_cast(shared_from_this())); - if (targetItem->count + myItem->count > targetItem->getMaxStackSize()) return false; - - targetItem->count += myItem->count; - target->throwTime = std::max(target->throwTime, this->throwTime); - target->age = std::min(target->age, this->age); - target->setItem(targetItem); - remove(); - - return true; +bool ItemEntity::updateInWaterState() { + return level->checkAndHandleWater(bb, Material::water, shared_from_this()); } -void ItemEntity::setShortLifeTime() -{ - // reduce lifetime to one minute - age = LIFETIME - (60 * SharedConstants::TICKS_PER_SECOND); +void ItemEntity::burn(int dmg) { hurt(DamageSource::inFire, dmg); } + +bool ItemEntity::hurt(DamageSource* source, int damage) { + // 4J - added next line: found whilst debugging an issue with item entities + // getting into a bad state when being created by a cactus, since entities + // insides cactuses get hurt and therefore depending on the timing of things + // they could get removed from the client when they weren't supposed to be. + // Are there really any cases were we would want an itemEntity to be locally + // hurt? + if (level->isClientSide) return false; + + markHurt(); + health -= damage; + if (health <= 0) { + remove(); + } + return false; } -bool ItemEntity::updateInWaterState() -{ - return level->checkAndHandleWater(bb, Material::water, shared_from_this()); +void ItemEntity::addAdditonalSaveData(CompoundTag* entityTag) { + entityTag->putShort(L"Health", (uint8_t)health); + entityTag->putShort(L"Age", (short)age); + if (getItem() != NULL) + entityTag->putCompound(L"Item", getItem()->save(new CompoundTag())); } - -void ItemEntity::burn(int dmg) -{ - hurt(DamageSource::inFire, dmg); +void ItemEntity::readAdditionalSaveData(CompoundTag* tag) { + health = tag->getShort(L"Health") & 0xff; + age = tag->getShort(L"Age"); + CompoundTag* itemTag = tag->getCompound(L"Item"); + setItem(ItemInstance::fromTag(itemTag)); + if (getItem() == NULL) remove(); } +void ItemEntity::playerTouch(std::shared_ptr player) { + if (level->isClientSide) return; -bool ItemEntity::hurt(DamageSource *source, int damage) -{ - // 4J - added next line: found whilst debugging an issue with item entities getting into a bad state when being created by a cactus, since entities insides cactuses get hurt - // and therefore depending on the timing of things they could get removed from the client when they weren't supposed to be. Are there really any cases were we would want - // an itemEntity to be locally hurt? - if (level->isClientSide ) return false; + std::shared_ptr item = getItem(); - markHurt(); - health -= damage; - if (health <= 0) - { - remove(); - } - return false; -} + // 4J Stu - Fix for duplication glitch + if (item->count <= 0) { + remove(); + return; + } -void ItemEntity::addAdditonalSaveData(CompoundTag *entityTag) -{ - entityTag->putShort(L"Health", (uint8_t) health); - entityTag->putShort(L"Age", (short) age); - if (getItem() != NULL) entityTag->putCompound(L"Item", getItem()->save(new CompoundTag())); -} - -void ItemEntity::readAdditionalSaveData(CompoundTag *tag) -{ - health = tag->getShort(L"Health") & 0xff; - age = tag->getShort(L"Age"); - CompoundTag *itemTag = tag->getCompound(L"Item"); - setItem(ItemInstance::fromTag(itemTag)); - if (getItem() == NULL) remove(); -} - -void ItemEntity::playerTouch(std::shared_ptr player) -{ - if (level->isClientSide) return; - - std::shared_ptr item = getItem(); - - // 4J Stu - Fix for duplication glitch - if(item->count <= 0) - { - remove(); - return; - } - - int orgCount = item->count; - if (throwTime == 0 && player->inventory->add(item)) - { - //if (item.id == Tile.treeTrunk.id) player.awardStat(Achievements.mineWood); - //if (item.id == Item.leather.id) player.awardStat(Achievements.killCow); - //if (item.id == Item.diamond.id) player.awardStat(Achievements.diamonds); - //if (item.id == Item.blazeRod.id) player.awardStat(Achievements.blazeRod); - if (item->id == Item::diamond_Id) - { - player->awardStat(GenericStats::diamonds(), GenericStats::param_diamonds()); + int orgCount = item->count; + if (throwTime == 0 && player->inventory->add(item)) { + // if (item.id == Tile.treeTrunk.id) + // player.awardStat(Achievements.mineWood); if (item.id == + // Item.leather.id) player.awardStat(Achievements.killCow); if (item.id + // == Item.diamond.id) player.awardStat(Achievements.diamonds); if + // (item.id == Item.blazeRod.id) + // player.awardStat(Achievements.blazeRod); + if (item->id == Item::diamond_Id) { + player->awardStat(GenericStats::diamonds(), + GenericStats::param_diamonds()); #ifdef _EXTENDED_ACHIEVEMENTS - if ( getItem()->getItem()->id ) - { - std::shared_ptr pThrower = level->getPlayerByName(getThrower()); - if ( (pThrower != nullptr) && (pThrower != player) ) - { - pThrower->awardStat(GenericStats::diamondsToYou(), GenericStats::param_diamondsToYou()); - } - } + if (getItem()->getItem()->id) { + std::shared_ptr pThrower = + level->getPlayerByName(getThrower()); + if ((pThrower != nullptr) && (pThrower != player)) { + pThrower->awardStat(GenericStats::diamondsToYou(), + GenericStats::param_diamondsToYou()); + } + } #endif - } - if (item->id == Item::blazeRod_Id) - player->awardStat(GenericStats::blazeRod(), GenericStats::param_blazeRod()); + } + if (item->id == Item::blazeRod_Id) + player->awardStat(GenericStats::blazeRod(), + GenericStats::param_blazeRod()); - level->playSound(shared_from_this(), eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - player->take(shared_from_this(), orgCount); - // System.out.println(item.count + ", " + orgCount); - if (item->count <= 0) remove(); - } + level->playSound( + shared_from_this(), eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); + player->take(shared_from_this(), orgCount); + // System.out.println(item.count + ", " + orgCount); + if (item->count <= 0) remove(); + } } -std::wstring ItemEntity::getAName() -{ - return L"";//L"item." + getItem()->getDescriptionId(); - //return I18n.get("item." + item.getDescriptionId()); +std::wstring ItemEntity::getAName() { + return L""; // L"item." + getItem()->getDescriptionId(); + // return I18n.get("item." + item.getDescriptionId()); } -std::shared_ptr ItemEntity::getItem() -{ - std::shared_ptr result = getEntityData()->getItemInstance(DATA_ITEM); +std::shared_ptr ItemEntity::getItem() { + std::shared_ptr result = + getEntityData()->getItemInstance(DATA_ITEM); - if (result == NULL) - { - if (level != NULL) - { - app.DebugPrintf("Item entity %d has no item?!\n", entityId); - //level.getLogger().severe("Item entity " + entityId + " has no item?!"); - } - return std::shared_ptr(new ItemInstance(Tile::rock)); - } + if (result == NULL) { + if (level != NULL) { + app.DebugPrintf("Item entity %d has no item?!\n", entityId); + // level.getLogger().severe("Item entity " + entityId + " has no + // item?!"); + } + return std::shared_ptr(new ItemInstance(Tile::rock)); + } - return result; + return result; } -void ItemEntity::setItem(std::shared_ptr item) -{ - getEntityData()->set(DATA_ITEM, item); - getEntityData()->markDirty(DATA_ITEM); +void ItemEntity::setItem(std::shared_ptr item) { + getEntityData()->set(DATA_ITEM, item); + getEntityData()->markDirty(DATA_ITEM); } -bool ItemEntity::isAttackable() -{ - return false; +bool ItemEntity::isAttackable() { return false; } + +void ItemEntity::setThrower(const std::wstring& thrower) { + this->thrower = thrower; } -void ItemEntity::setThrower(const std::wstring &thrower) -{ - this->thrower = thrower; -} - -std::wstring ItemEntity::getThrower() -{ - return this->thrower; -} +std::wstring ItemEntity::getThrower() { return this->thrower; } diff --git a/Minecraft.World/Entities/ItemEntity.h b/Minecraft.World/Entities/ItemEntity.h index 65c6fbe05..08d779d23 100644 --- a/Minecraft.World/Entities/ItemEntity.h +++ b/Minecraft.World/Entities/ItemEntity.h @@ -4,71 +4,72 @@ class Player; -class ItemEntity : public Entity -{ +class ItemEntity : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_ITEMENTITY;} - static Entity *create(Level *level) { return new ItemEntity(level); } + eINSTANCEOF GetType() { return eTYPE_ITEMENTITY; } + static Entity* create(Level* level) { return new ItemEntity(level); } private: - static const int DATA_ITEM = 10; + static const int DATA_ITEM = 10; - static const int LIFETIME = 5 * 60 * SharedConstants::TICKS_PER_SECOND; // Five miniutes. + static const int LIFETIME = + 5 * 60 * SharedConstants::TICKS_PER_SECOND; // Five miniutes. - std::wstring thrower; + std::wstring thrower; - // 4J Added - void _init(); - void _init(Level *level, double x, double y, double z); + // 4J Added + void _init(); + void _init(Level* level, double x, double y, double z); public: - int age; - int throwTime; + int age; + int throwTime; private: - int health; + int health; public: - float bobOffs; - - ItemEntity(Level *level, double x, double y, double z); - ItemEntity(Level *level, double x, double y, double z, std::shared_ptr item); + float bobOffs; + + ItemEntity(Level* level, double x, double y, double z); + ItemEntity(Level* level, double x, double y, double z, + std::shared_ptr item); protected: - virtual bool makeStepSound(); + virtual bool makeStepSound(); public: - ItemEntity(Level *level); + ItemEntity(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void tick(); + virtual void tick(); private: - void mergeWithNeighbours(); + void mergeWithNeighbours(); public: - bool merge(std::shared_ptr target); - void setShortLifeTime(); - virtual bool updateInWaterState(); + bool merge(std::shared_ptr target); + void setShortLifeTime(); + virtual bool updateInWaterState(); protected: - virtual void burn(int dmg); + virtual void burn(int dmg); public: - virtual bool hurt(DamageSource *source, int damage); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void playerTouch(std::shared_ptr player); + virtual bool hurt(DamageSource* source, int damage); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void playerTouch(std::shared_ptr player); - virtual std::wstring getAName(); + virtual std::wstring getAName(); - std::shared_ptr getItem(); - void setItem(std::shared_ptr item); - virtual bool isAttackable(); + std::shared_ptr getItem(); + void setItem(std::shared_ptr item); + virtual bool isAttackable(); - void setThrower(const std::wstring &thrower); - std::wstring getThrower(); + void setThrower(const std::wstring& thrower); + std::wstring getThrower(); }; diff --git a/Minecraft.World/Entities/Mob.cpp b/Minecraft.World/Entities/Mob.cpp index 44e733151..c7dc40594 100644 --- a/Minecraft.World/Entities/Mob.cpp +++ b/Minecraft.World/Entities/Mob.cpp @@ -27,1917 +27,1583 @@ const double Mob::MIN_MOVEMENT_DISTANCE = 0.005; -void Mob::_init() -{ - invulnerableDuration = 20; - timeOffs = 0.0f; +void Mob::_init() { + invulnerableDuration = 20; + timeOffs = 0.0f; - yBodyRot = 0; - yBodyRotO = 0; - yHeadRot = 0; - yHeadRotO = 0; + yBodyRot = 0; + yBodyRotO = 0; + yHeadRot = 0; + yHeadRotO = 0; - oRun = 0.0f; - run = 0.0f; + oRun = 0.0f; + run = 0.0f; - animStep = 0.0f; - animStepO = 0.0f; + animStep = 0.0f; + animStepO = 0.0f; - MemSect(31); - hasHair = true; - textureIdx = TN_MOB_CHAR; // 4J was L"/mob/char.png"; - allowAlpha = true; - rotOffs = 0; - modelName = L""; - bobStrength = 1; - deathScore = 0; - renderOffset = 0; - MemSect(0); + MemSect(31); + hasHair = true; + textureIdx = TN_MOB_CHAR; // 4J was L"/mob/char.png"; + allowAlpha = true; + rotOffs = 0; + modelName = L""; + bobStrength = 1; + deathScore = 0; + renderOffset = 0; + MemSect(0); - walkingSpeed = 0.1f; - flyingSpeed = 0.02f; + walkingSpeed = 0.1f; + flyingSpeed = 0.02f; - oAttackAnim = 0.0f; - attackAnim = 0.0f; + oAttackAnim = 0.0f; + attackAnim = 0.0f; - lastHealth = 0; - dmgSpill = 0; + lastHealth = 0; + dmgSpill = 0; - ambientSoundTime = 0; + ambientSoundTime = 0; - hurtTime = 0; - hurtDuration = 0; - hurtDir = 0; - deathTime = 0; - attackTime = 0; - oTilt = 0; - tilt = 0; + hurtTime = 0; + hurtDuration = 0; + hurtDir = 0; + deathTime = 0; + attackTime = 0; + oTilt = 0; + tilt = 0; - dead = false; - xpReward = 0; + dead = false; + xpReward = 0; - modelNum = -1; - animSpeed = (float) (Math::random() * 0.9f + 0.1f); + modelNum = -1; + animSpeed = (float)(Math::random() * 0.9f + 0.1f); - walkAnimSpeedO = 0.0f; - walkAnimSpeed = 0.0f; - walkAnimPos = 0.0f; + walkAnimSpeedO = 0.0f; + walkAnimSpeed = 0.0f; + walkAnimPos = 0.0f; - lastHurtByPlayer = nullptr; - lastHurtByPlayerTime = 0; - lastHurtByMob = nullptr; - lastHurtByMobTime = 0; - lastHurtMob = nullptr; + lastHurtByPlayer = nullptr; + lastHurtByPlayerTime = 0; + lastHurtByMob = nullptr; + lastHurtByMobTime = 0; + lastHurtMob = nullptr; - arrowCount = 0; - removeArrowTime = 0; + arrowCount = 0; + removeArrowTime = 0; - lSteps = 0; - lx = ly = lz = lyr = lxr = 0.0; + lSteps = 0; + lx = ly = lz = lyr = lxr = 0.0; - fallTime = 0.0f; + fallTime = 0.0f; - lastHurt = 0; + lastHurt = 0; - noActionTime = 0; - xxa = yya = yRotA = 0.0f; - jumping = false; - defaultLookAngle = 0.0f; - runSpeed = 0.7f; - noJumpDelay = 0; + noActionTime = 0; + xxa = yya = yRotA = 0.0f; + jumping = false; + defaultLookAngle = 0.0f; + runSpeed = 0.7f; + noJumpDelay = 0; - lookingAt = nullptr; - lookTime = 0; + lookingAt = nullptr; + lookTime = 0; - effectsDirty = true; - effectColor = 0; + effectsDirty = true; + effectColor = 0; - target = nullptr; - sensing = NULL; - speed = 0.0f; + target = nullptr; + sensing = NULL; + speed = 0.0f; - restrictCenter = new Pos(0, 0, 0); - restrictRadius = -1.0f; + restrictCenter = new Pos(0, 0, 0); + restrictRadius = -1.0f; } -Mob::Mob( Level* level) : Entity(level) -{ - _init(); +Mob::Mob(Level* level) : Entity(level) { + _init(); - // 4J Stu - This will not call the correct derived function, so moving to each derived class - //health = getMaxHealth(); - health = 0; + // 4J Stu - This will not call the correct derived function, so moving to + // each derived class + // health = getMaxHealth(); + health = 0; - blocksBuilding = true; + blocksBuilding = true; - lookControl = new LookControl(this); - moveControl = new MoveControl(this); - jumpControl = new JumpControl(this); - bodyControl = new BodyControl(this); - navigation = new PathNavigation(this, level, 16); - sensing = new Sensing(this); + lookControl = new LookControl(this); + moveControl = new MoveControl(this); + jumpControl = new JumpControl(this); + bodyControl = new BodyControl(this); + navigation = new PathNavigation(this, level, 16); + sensing = new Sensing(this); - rotA = (float) (Math::random() + 1) * 0.01f; - setPos(x, y, z); - timeOffs = (float) Math::random() * 12398; - yRot = (float) (Math::random() * PI * 2); - yHeadRot = yRot; + rotA = (float)(Math::random() + 1) * 0.01f; + setPos(x, y, z); + timeOffs = (float)Math::random() * 12398; + yRot = (float)(Math::random() * PI * 2); + yHeadRot = yRot; - this->footSize = 0.5f; + this->footSize = 0.5f; } -Mob::~Mob() -{ - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) - { - delete it->second; - } +Mob::~Mob() { + for (AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) { + delete it->second; + } - if(lookControl != NULL) delete lookControl; - if(moveControl != NULL) delete moveControl; - if(jumpControl != NULL) delete jumpControl; - if(bodyControl != NULL) delete bodyControl; - if(navigation != NULL) delete navigation; - if(sensing != NULL) delete sensing; + if (lookControl != NULL) delete lookControl; + if (moveControl != NULL) delete moveControl; + if (jumpControl != NULL) delete jumpControl; + if (bodyControl != NULL) delete bodyControl; + if (navigation != NULL) delete navigation; + if (sensing != NULL) delete sensing; - delete restrictCenter; + delete restrictCenter; } -LookControl *Mob::getLookControl() -{ - return lookControl; +LookControl* Mob::getLookControl() { return lookControl; } + +MoveControl* Mob::getMoveControl() { return moveControl; } + +JumpControl* Mob::getJumpControl() { return jumpControl; } + +PathNavigation* Mob::getNavigation() { return navigation; } + +Sensing* Mob::getSensing() { return sensing; } + +Random* Mob::getRandom() { return random; } + +std::shared_ptr Mob::getLastHurtByMob() { return lastHurtByMob; } + +std::shared_ptr Mob::getLastHurtMob() { return lastHurtMob; } + +void Mob::setLastHurtMob(std::shared_ptr target) { + std::shared_ptr mob = std::dynamic_pointer_cast(target); + if (mob != NULL) lastHurtMob = mob; } -MoveControl *Mob::getMoveControl() -{ - return moveControl; +int Mob::getNoActionTime() { return noActionTime; } + +float Mob::getYHeadRot() { return yHeadRot; } + +void Mob::setYHeadRot(float yHeadRot) { this->yHeadRot = yHeadRot; } + +float Mob::getSpeed() { return speed; } + +void Mob::setSpeed(float speed) { + this->speed = speed; + setYya(speed); } -JumpControl *Mob::getJumpControl() -{ - return jumpControl; +bool Mob::doHurtTarget(std::shared_ptr target) { + setLastHurtMob(target); + return false; } -PathNavigation *Mob::getNavigation() -{ - return navigation; -} +std::shared_ptr Mob::getTarget() { return target; } -Sensing *Mob::getSensing() -{ - return sensing; -} +void Mob::setTarget(std::shared_ptr target) { this->target = target; } -Random *Mob::getRandom() -{ - return random; -} - -std::shared_ptr Mob::getLastHurtByMob() -{ - return lastHurtByMob; -} - -std::shared_ptr Mob::getLastHurtMob() -{ - return lastHurtMob; -} - -void Mob::setLastHurtMob(std::shared_ptr target) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(target); - if (mob != NULL) lastHurtMob = mob; -} - -int Mob::getNoActionTime() -{ - return noActionTime; -} - -float Mob::getYHeadRot() -{ - return yHeadRot; -} - -void Mob::setYHeadRot(float yHeadRot) -{ - this->yHeadRot = yHeadRot; -} - -float Mob::getSpeed() -{ - return speed; -} - -void Mob::setSpeed(float speed) -{ - this->speed = speed; - setYya(speed); -} - -bool Mob::doHurtTarget(std::shared_ptr target) -{ - setLastHurtMob(target); - return false; -} - -std::shared_ptr Mob::getTarget() -{ - return target; -} - -void Mob::setTarget(std::shared_ptr target) -{ - this->target = target; -} - -bool Mob::canAttackType(eINSTANCEOF targetType) -{ - return !(targetType == eTYPE_CREEPER || targetType == eTYPE_GHAST); +bool Mob::canAttackType(eINSTANCEOF targetType) { + return !(targetType == eTYPE_CREEPER || targetType == eTYPE_GHAST); } // Called by eatTileGoal -void Mob::ate() -{ -} +void Mob::ate() {} // might move to navigation, might make area -bool Mob::isWithinRestriction() -{ - return isWithinRestriction(Mth::floor(x), Mth::floor(y), Mth::floor(z)); +bool Mob::isWithinRestriction() { + return isWithinRestriction(Mth::floor(x), Mth::floor(y), Mth::floor(z)); } -bool Mob::isWithinRestriction(int x, int y, int z) -{ - if (restrictRadius == -1) return true; - return restrictCenter->distSqr(x, y, z) < restrictRadius * restrictRadius; +bool Mob::isWithinRestriction(int x, int y, int z) { + if (restrictRadius == -1) return true; + return restrictCenter->distSqr(x, y, z) < restrictRadius * restrictRadius; } -void Mob::restrictTo(int x, int y, int z, int radius) -{ - restrictCenter->set(x, y, z); - restrictRadius = radius; +void Mob::restrictTo(int x, int y, int z, int radius) { + restrictCenter->set(x, y, z); + restrictRadius = radius; } -Pos *Mob::getRestrictCenter() -{ - return restrictCenter; +Pos* Mob::getRestrictCenter() { return restrictCenter; } + +float Mob::getRestrictRadius() { return restrictRadius; } + +void Mob::clearRestriction() { restrictRadius = -1; } + +bool Mob::hasRestriction() { return restrictRadius != -1; } + +void Mob::setLastHurtByMob(std::shared_ptr hurtBy) { + lastHurtByMob = hurtBy; + lastHurtByMobTime = lastHurtByMob != NULL ? PLAYER_HURT_EXPERIENCE_TIME : 0; } -float Mob::getRestrictRadius() -{ - return restrictRadius; +void Mob::defineSynchedData() { + entityData->define(DATA_EFFECT_COLOR_ID, effectColor); } -void Mob::clearRestriction() -{ - restrictRadius = -1; +bool Mob::canSee(std::shared_ptr target) { + HitResult* hres = level->clip( + Vec3::newTemp(x, y + getHeadHeight(), z), + Vec3::newTemp(target->x, target->y + target->getHeadHeight(), + target->z)); + bool retVal = (hres == NULL); + delete hres; + return retVal; } -bool Mob::hasRestriction() -{ - return restrictRadius != -1; +int Mob::getTexture() { return textureIdx; } + +bool Mob::isPickable() { return !removed; } + +bool Mob::isPushable() { return !removed; } + +float Mob::getHeadHeight() { return bbHeight * 0.85f; } + +int Mob::getAmbientSoundInterval() { return 20 * 4; } + +void Mob::playAmbientSound() { + MemSect(31); + int ambient = getAmbientSound(); + if (ambient != -1) { + level->playSound(shared_from_this(), ambient, getSoundVolume(), + getVoicePitch()); + } + MemSect(0); } -void Mob::setLastHurtByMob(std::shared_ptr hurtBy) -{ - lastHurtByMob = hurtBy; - lastHurtByMobTime = lastHurtByMob != NULL ? PLAYER_HURT_EXPERIENCE_TIME : 0; +void Mob::baseTick() { + oAttackAnim = attackAnim; + Entity::baseTick(); + + if (isAlive() && random->nextInt(1000) < ambientSoundTime++) { + ambientSoundTime = -getAmbientSoundInterval(); + + playAmbientSound(); + } + + if (isAlive() && isInWall()) { + hurt(DamageSource::inWall, 1); + } + + if (isFireImmune() || level->isClientSide) clearFire(); + + if (isAlive() && isUnderLiquid(Material::water) && !isWaterMob() && + activeEffects.find(MobEffect::waterBreathing->id) == + activeEffects.end()) { + setAirSupply(decreaseAirSupply(getAirSupply())); + if (getAirSupply() == -20) { + setAirSupply(0); + if (canCreateParticles()) { + for (int i = 0; i < 8; i++) { + float xo = random->nextFloat() - random->nextFloat(); + float yo = random->nextFloat() - random->nextFloat(); + float zo = random->nextFloat() - random->nextFloat(); + level->addParticle(eParticleType_bubble, x + xo, y + yo, + z + zo, xd, yd, zd); + } + } + hurt(DamageSource::drown, 2); + } + + clearFire(); + } else { + setAirSupply(TOTAL_AIR_SUPPLY); + } + + oTilt = tilt; + + if (attackTime > 0) attackTime--; + if (hurtTime > 0) hurtTime--; + if (invulnerableTime > 0) invulnerableTime--; + if (health <= 0) { + tickDeath(); + } + + if (lastHurtByPlayerTime > 0) + lastHurtByPlayerTime--; + else { + // Note - this used to just set to nullptr, but that has to create a new + // std::shared_ptr and free an old one, when generally this won't be + // doing anything at all. This is the lightweight but ugly alternative + if (lastHurtByPlayer) { + lastHurtByPlayer.reset(); + } + } + if (lastHurtMob != NULL && !lastHurtMob->isAlive()) lastHurtMob = nullptr; + + if (lastHurtByMob != NULL) { + if (!lastHurtByMob->isAlive()) + setLastHurtByMob(nullptr); + else if (lastHurtByMobTime > 0) + lastHurtByMobTime--; + else + setLastHurtByMob(nullptr); + } + + // update effects + tickEffects(); + + animStepO = animStep; + + yBodyRotO = yBodyRot; + yHeadRotO = yHeadRot; + yRotO = yRot; + xRotO = xRot; } -void Mob::defineSynchedData() -{ - entityData->define(DATA_EFFECT_COLOR_ID, effectColor); +void Mob::tickDeath() { + deathTime++; + if (deathTime == 20) { + // 4J Stu - Added level->isClientSide check from 1.2 to fix XP orbs + // being created client side + if (!level->isClientSide && + (lastHurtByPlayerTime > 0 || isAlwaysExperienceDropper())) { + if (!isBaby()) { + int xpCount = this->getExperienceReward(lastHurtByPlayer); + while (xpCount > 0) { + int newCount = ExperienceOrb::getExperienceValue(xpCount); + xpCount -= newCount; + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x, y, z, newCount))); + } + } + } + + remove(); + for (int i = 0; i < 20; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle(eParticleType_explode, + x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, + xa, ya, za); + } + } } -bool Mob::canSee(std::shared_ptr target) -{ - HitResult *hres = level->clip(Vec3::newTemp(x, y + getHeadHeight(), z), Vec3::newTemp(target->x, target->y + target->getHeadHeight(), target->z)); - bool retVal = (hres == NULL); - delete hres; - return retVal; +int Mob::decreaseAirSupply(int currentSupply) { return currentSupply - 1; } + +int Mob::getExperienceReward(std::shared_ptr killedBy) { + return xpReward; } -int Mob::getTexture() -{ - return textureIdx; +bool Mob::isAlwaysExperienceDropper() { return false; } + +void Mob::spawnAnim() { + for (int i = 0; i < 20; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + double dd = 10; + level->addParticle( + eParticleType_explode, + x + random->nextFloat() * bbWidth * 2 - bbWidth - xa * dd, + y + random->nextFloat() * bbHeight - ya * dd, + z + random->nextFloat() * bbWidth * 2 - bbWidth - za * dd, xa, ya, + za); + } } -bool Mob::isPickable() -{ - return !removed; +void Mob::rideTick() { + Entity::rideTick(); + oRun = run; + run = 0; + fallDistance = 0; } -bool Mob::isPushable() -{ - return !removed; +void Mob::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + heightOffset = 0; + lx = x; + ly = y; + lz = z; + lyr = yRot; + lxr = xRot; + + lSteps = steps; } -float Mob::getHeadHeight() -{ - return bbHeight * 0.85f; +void Mob::superTick() { Entity::tick(); } + +void Mob::tick() { + Entity::tick(); + + if (arrowCount > 0) { + if (removeArrowTime <= 0) { + removeArrowTime = 20 * 3; + } + removeArrowTime--; + if (removeArrowTime <= 0) { + arrowCount--; + } + } + + aiStep(); + + double xd = x - xo; + double zd = z - zo; + + float sideDist = xd * xd + zd * zd; + + float yBodyRotT = yBodyRot; + + float walkSpeed = 0; + oRun = run; + float tRun = 0; + if (sideDist <= 0.05f * 0.05f) { + // animStep = 0; + } else { + tRun = 1; + walkSpeed = sqrt(sideDist) * 3; + yBodyRotT = ((float)atan2(zd, xd) * 180 / (float)PI - 90); + } + if (attackAnim > 0) { + yBodyRotT = yRot; + } + if (!onGround) { + tRun = 0; + } + run = run + (tRun - run) * 0.3f; + + /* + * float yBodyRotD = yRot-yBodyRot; while (yBodyRotD < -180) yBodyRotD + * += 360; while (yBodyRotD >= 180) yBodyRotD -= 360; yBodyRot += + * yBodyRotD * 0.1f; + */ + + if (useNewAi()) { + bodyControl->clientTick(); + } else { + float yBodyRotD = Mth::wrapDegrees(yBodyRotT - yBodyRot); + yBodyRot += yBodyRotD * 0.3f; + + float headDiff = Mth::wrapDegrees(yRot - yBodyRot); + bool behind = headDiff < -90 || headDiff >= 90; + if (headDiff < -75) headDiff = -75; + if (headDiff >= 75) headDiff = +75; + yBodyRot = yRot - headDiff; + if (headDiff * headDiff > 50 * 50) { + yBodyRot += headDiff * 0.2f; + } + + if (behind) { + walkSpeed *= -1; + } + } + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; + + while (yBodyRot - yBodyRotO < -180) yBodyRotO -= 360; + while (yBodyRot - yBodyRotO >= 180) yBodyRotO += 360; + + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; + + while (yHeadRot - yHeadRotO < -180) yHeadRotO -= 360; + while (yHeadRot - yHeadRotO >= 180) yHeadRotO += 360; + + animStep += walkSpeed; } -int Mob::getAmbientSoundInterval() -{ - return 20 * 4; +void Mob::heal(int heal) { + if (health <= 0) return; + health += heal; + if (health > getMaxHealth()) health = getMaxHealth(); + invulnerableTime = invulnerableDuration / 2; } -void Mob::playAmbientSound() -{ - MemSect(31); - int ambient = getAmbientSound(); - if (ambient != -1) - { - level->playSound(shared_from_this(), ambient, getSoundVolume(), getVoicePitch()); - } - MemSect(0); +int Mob::getHealth() { return health; } + +void Mob::setHealth(int health) { + this->health = health; + if (health > getMaxHealth()) { + health = getMaxHealth(); + } } -void Mob::baseTick() -{ - oAttackAnim = attackAnim; - Entity::baseTick(); +bool Mob::hurt(DamageSource* source, int dmg) { + // 4J Stu - Reworked this function a bit to show hurt damage on the client + // before the server responds. Fix for #8823 - Gameplay: Confirmation that a + // monster or animal has taken damage from an attack is highly delayed 4J + // Stu - Change to the fix to only show damage when attacked, rather than + // collision damage Fix for #10299 - When in corners, passive mobs may show + // that they are taking damage. 4J Stu - Change to the fix for TU6, as + // source is never NULL due to changes in 1.8.2 to what source actually is + if (level->isClientSide && + dynamic_cast(source) == NULL) + return false; + noActionTime = 0; + if (health <= 0) return false; - if (isAlive() && random->nextInt(1000) < ambientSoundTime++) - { - ambientSoundTime = -getAmbientSoundInterval(); + if (source->isFire() && hasEffect(MobEffect::fireResistance)) { + // 4J-JEV, for new achievement Stayin'Frosty, TODO merge with Java + // version. + std::shared_ptr plr = + std::dynamic_pointer_cast(shared_from_this()); + if (plr != NULL && + source == + DamageSource::lava) // Only award when in lava (not any fire). + { + plr->awardStat(GenericStats::stayinFrosty(), + GenericStats::param_stayinFrosty()); + } + return false; + } - playAmbientSound(); - } + this->walkAnimSpeed = 1.5f; - if (isAlive() && isInWall()) - { - hurt(DamageSource::inWall, 1); - } + bool sound = true; + if (invulnerableTime > invulnerableDuration / 2.0f) { + if (dmg <= lastHurt) return false; + if (!level->isClientSide) actuallyHurt(source, dmg - lastHurt); + lastHurt = dmg; + sound = false; + } else { + lastHurt = dmg; + lastHealth = health; + invulnerableTime = invulnerableDuration; + if (!level->isClientSide) actuallyHurt(source, dmg); + hurtTime = hurtDuration = 10; + } - if (isFireImmune() || level->isClientSide) clearFire(); + hurtDir = 0; - if (isAlive() && isUnderLiquid(Material::water) && !isWaterMob() && activeEffects.find(MobEffect::waterBreathing->id) == activeEffects.end()) - { - setAirSupply(decreaseAirSupply(getAirSupply())); - if (getAirSupply() == -20) - { - setAirSupply(0); - if(canCreateParticles()) - { - for (int i = 0; i < 8; i++) - { - float xo = random->nextFloat() - random->nextFloat(); - float yo = random->nextFloat() - random->nextFloat(); - float zo = random->nextFloat() - random->nextFloat(); - level->addParticle(eParticleType_bubble, x + xo, y + yo, z + zo, xd, yd, zd); - } - } - hurt(DamageSource::drown, 2); - } + std::shared_ptr sourceEntity = source->getEntity(); + if (sourceEntity != NULL) { + if (std::dynamic_pointer_cast(sourceEntity) != NULL) { + setLastHurtByMob(std::dynamic_pointer_cast(sourceEntity)); + } + if (std::dynamic_pointer_cast(sourceEntity) != NULL) { + lastHurtByPlayerTime = PLAYER_HURT_EXPERIENCE_TIME; + lastHurtByPlayer = std::dynamic_pointer_cast(sourceEntity); + } else if (std::dynamic_pointer_cast(sourceEntity)) { + std::shared_ptr w = + std::dynamic_pointer_cast(sourceEntity); + if (w->isTame()) { + lastHurtByPlayerTime = PLAYER_HURT_EXPERIENCE_TIME; + lastHurtByPlayer = nullptr; + } + } + } - clearFire(); - } - else - { - setAirSupply(TOTAL_AIR_SUPPLY); - } + if (sound && level->isClientSide) { + return false; + } - oTilt = tilt; + if (sound) { + level->broadcastEntityEvent(shared_from_this(), EntityEvent::HURT); + if (source != DamageSource::drown && + source != DamageSource::controlledExplosion) + markHurt(); + if (sourceEntity != NULL) { + double xd = sourceEntity->x - x; + double zd = sourceEntity->z - z; + while (xd * xd + zd * zd < 0.0001) { + xd = (Math::random() - Math::random()) * 0.01; + zd = (Math::random() - Math::random()) * 0.01; + } + hurtDir = (float)(atan2(zd, xd) * 180 / PI) - yRot; + knockback(sourceEntity, dmg, xd, zd); + } else { + hurtDir = (float)(int)((Math::random() * 2) * + 180); // 4J This cast is the same as Java + } + } - if (attackTime > 0) attackTime--; - if (hurtTime > 0) hurtTime--; - if (invulnerableTime > 0) invulnerableTime--; - if (health <= 0) - { - tickDeath(); - } + MemSect(31); + if (health <= 0) { + if (sound) + level->playSound(shared_from_this(), getDeathSound(), + getSoundVolume(), getVoicePitch()); + die(source); + } else { + if (sound) + level->playSound(shared_from_this(), getHurtSound(), + getSoundVolume(), getVoicePitch()); + } + MemSect(0); - if (lastHurtByPlayerTime > 0) lastHurtByPlayerTime--; - else - { - // Note - this used to just set to nullptr, but that has to create a new std::shared_ptr and free an old one, when generally this won't be doing anything at all. This - // is the lightweight but ugly alternative - if( lastHurtByPlayer ) - { - lastHurtByPlayer.reset(); - } - } - if (lastHurtMob != NULL && !lastHurtMob->isAlive()) lastHurtMob = nullptr; - - if (lastHurtByMob != NULL) - { - if (!lastHurtByMob->isAlive()) setLastHurtByMob(nullptr); - else if (lastHurtByMobTime > 0) lastHurtByMobTime--; - else setLastHurtByMob(nullptr); - } - - // update effects - tickEffects(); - - animStepO = animStep; - - yBodyRotO = yBodyRot; - yHeadRotO = yHeadRot; - yRotO = yRot; - xRotO = xRot; + return true; } -void Mob::tickDeath() -{ - deathTime++; - if (deathTime == 20) - { - // 4J Stu - Added level->isClientSide check from 1.2 to fix XP orbs being created client side - if(!level->isClientSide && (lastHurtByPlayerTime > 0 || isAlwaysExperienceDropper()) ) - { - if (!isBaby()) - { - int xpCount = this->getExperienceReward(lastHurtByPlayer); - while (xpCount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(xpCount); - xpCount -= newCount; - level->addEntity(std::shared_ptr( new ExperienceOrb(level, x, y, z, newCount) ) ); - } - } - } - - remove(); - for (int i = 0; i < 20; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(eParticleType_explode, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } - } +float Mob::getVoicePitch() { + if (isBaby()) { + return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.5f; + } + return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f; } -int Mob::decreaseAirSupply(int currentSupply) -{ - return currentSupply - 1; +void Mob::animateHurt() { + hurtTime = hurtDuration = 10; + hurtDir = 0; } -int Mob::getExperienceReward(std::shared_ptr killedBy) -{ - return xpReward; +int Mob::getArmorValue() { return 0; } + +void Mob::hurtArmor(int damage) {} + +int Mob::getDamageAfterArmorAbsorb(DamageSource* damageSource, int damage) { + if (!damageSource->isBypassArmor()) { + int absorb = 25 - getArmorValue(); + int v = (damage)*absorb + dmgSpill; + hurtArmor(damage); + damage = v / 25; + dmgSpill = v % 25; + } + return damage; } -bool Mob::isAlwaysExperienceDropper() -{ - return false; +int Mob::getDamageAfterMagicAbsorb(DamageSource* damageSource, int damage) { + if (hasEffect(MobEffect::damageResistance)) { + int absorbValue = + (getEffect(MobEffect::damageResistance)->getAmplifier() + 1) * 5; + int absorb = 25 - absorbValue; + int v = (damage)*absorb + dmgSpill; + damage = v / 25; + dmgSpill = v % 25; + } + return damage; } -void Mob::spawnAnim() -{ - for (int i = 0; i < 20; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - double dd = 10; - level->addParticle(eParticleType_explode, x + random->nextFloat() * bbWidth * 2 - bbWidth - xa * dd, y + random->nextFloat() * bbHeight - ya * dd, z + random->nextFloat() * bbWidth * 2 - bbWidth - za - * dd, xa, ya, za); - } +void Mob::actuallyHurt(DamageSource* source, int dmg) { + dmg = getDamageAfterArmorAbsorb(source, dmg); + dmg = getDamageAfterMagicAbsorb(source, dmg); + health -= dmg; } -void Mob::rideTick() -{ - Entity::rideTick(); - oRun = run; - run = 0; - fallDistance = 0; +float Mob::getSoundVolume() { return 1; } + +int Mob::getAmbientSound() { return -1; } + +int Mob::getHurtSound() { return eSoundType_DAMAGE_HURT; } + +int Mob::getDeathSound() { return eSoundType_DAMAGE_HURT; } + +void Mob::knockback(std::shared_ptr source, int dmg, double xd, + double zd) { + hasImpulse = true; + float dd = (float)sqrt(xd * xd + zd * zd); + float pow = 0.4f; + + this->xd /= 2; + this->yd /= 2; + this->zd /= 2; + + this->xd -= xd / dd * pow; + this->yd += pow; + this->zd -= zd / dd * pow; + + if (this->yd > 0.4f) this->yd = 0.4f; } -void Mob::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - heightOffset = 0; - lx = x; - ly = y; - lz = z; - lyr = yRot; - lxr = xRot; +void Mob::die(DamageSource* source) { + std::shared_ptr sourceEntity = source->getEntity(); + if (deathScore >= 0 && sourceEntity != NULL) + sourceEntity->awardKillScore(shared_from_this(), deathScore); - lSteps = steps; -} + if (sourceEntity != NULL) + sourceEntity->killed( + std::dynamic_pointer_cast(shared_from_this())); -void Mob::superTick() -{ - Entity::tick(); -} + dead = true; -void Mob::tick() -{ - Entity::tick(); + if (!level->isClientSide) { + int playerBonus = 0; + std::shared_ptr player = + std::dynamic_pointer_cast(sourceEntity); + if (player != NULL) { + playerBonus = + EnchantmentHelper::getKillingLootBonus(player->inventory); + } + if (!isBaby()) { + dropDeathLoot(lastHurtByPlayerTime > 0, playerBonus); + if (lastHurtByPlayerTime > 0) { + int rareLoot = random->nextInt(200) - playerBonus; + if (rareLoot < 5) { + dropRareDeathLoot((rareLoot <= 0) ? 1 : 0); + } + } + } - if (arrowCount > 0) - { - if (removeArrowTime <= 0) - { - removeArrowTime = 20 * 3; - } - removeArrowTime--; - if (removeArrowTime <= 0) - { - arrowCount--; - } - } + // 4J-JEV, hook for Durango mobKill event. + if (player != NULL) { + player->awardStat( + GenericStats::killMob(), + GenericStats::param_mobKill( + player, std::dynamic_pointer_cast(shared_from_this()), + source)); + } + } - aiStep(); - - double xd = x - xo; - double zd = z - zo; - - float sideDist = xd * xd + zd * zd; - - float yBodyRotT = yBodyRot; - - float walkSpeed = 0; - oRun = run; - float tRun = 0; - if (sideDist <= 0.05f * 0.05f) - { - // animStep = 0; - } - else - { - tRun = 1; - walkSpeed = sqrt(sideDist) * 3; - yBodyRotT = ((float) atan2(zd, xd) * 180 / (float) PI - 90); - } - if (attackAnim > 0) - { - yBodyRotT = yRot; - } - if (!onGround) - { - tRun = 0; - } - run = run + (tRun - run) * 0.3f; - - /* - * float yBodyRotD = yRot-yBodyRot; while (yBodyRotD < -180) yBodyRotD - * += 360; while (yBodyRotD >= 180) yBodyRotD -= 360; yBodyRot += - * yBodyRotD * 0.1f; - */ - - if (useNewAi()) - { - bodyControl->clientTick(); - } - else - { - float yBodyRotD = Mth::wrapDegrees(yBodyRotT - yBodyRot); - yBodyRot += yBodyRotD * 0.3f; - - float headDiff = Mth::wrapDegrees(yRot - yBodyRot); - bool behind = headDiff < -90 || headDiff >= 90; - if (headDiff < -75) headDiff = -75; - if (headDiff >= 75) headDiff = +75; - yBodyRot = yRot - headDiff; - if (headDiff * headDiff > 50 * 50) - { - yBodyRot += headDiff * 0.2f; - } - - if (behind) - { - walkSpeed *= -1; - } - } - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; - - while (yBodyRot - yBodyRotO < -180) - yBodyRotO -= 360; - while (yBodyRot - yBodyRotO >= 180) - yBodyRotO += 360; - - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; - - while (yHeadRot - yHeadRotO < -180) - yHeadRotO -= 360; - while (yHeadRot - yHeadRotO >= 180) - yHeadRotO += 360; - - animStep += walkSpeed; -} - -void Mob::heal(int heal) -{ - if (health <= 0) return; - health += heal; - if (health > getMaxHealth()) health = getMaxHealth(); - invulnerableTime = invulnerableDuration / 2; -} - -int Mob::getHealth() -{ - return health; -} - -void Mob::setHealth(int health) -{ - this->health = health; - if (health > getMaxHealth()) - { - health = getMaxHealth(); - } -} - -bool Mob::hurt(DamageSource *source, int dmg) -{ - // 4J Stu - Reworked this function a bit to show hurt damage on the client before the server responds. - // Fix for #8823 - Gameplay: Confirmation that a monster or animal has taken damage from an attack is highly delayed - // 4J Stu - Change to the fix to only show damage when attacked, rather than collision damage - // Fix for #10299 - When in corners, passive mobs may show that they are taking damage. - // 4J Stu - Change to the fix for TU6, as source is never NULL due to changes in 1.8.2 to what source actually is - if (level->isClientSide && dynamic_cast(source) == NULL) return false; - noActionTime = 0; - if (health <= 0) return false; - - if ( source->isFire() && hasEffect(MobEffect::fireResistance) ) - { - // 4J-JEV, for new achievement Stayin'Frosty, TODO merge with Java version. - std::shared_ptr plr = std::dynamic_pointer_cast(shared_from_this()); - if ( plr != NULL && source == DamageSource::lava ) // Only award when in lava (not any fire). - { - plr->awardStat(GenericStats::stayinFrosty(),GenericStats::param_stayinFrosty()); - } - return false; - } - - this->walkAnimSpeed = 1.5f; - - bool sound = true; - if (invulnerableTime > invulnerableDuration / 2.0f) - { - if (dmg <= lastHurt) return false; - if(!level->isClientSide) actuallyHurt(source, dmg - lastHurt); - lastHurt = dmg; - sound = false; - } - else - { - lastHurt = dmg; - lastHealth = health; - invulnerableTime = invulnerableDuration; - if (!level->isClientSide) actuallyHurt(source, dmg); - hurtTime = hurtDuration = 10; - } - - hurtDir = 0; - - std::shared_ptr sourceEntity = source->getEntity(); - if (sourceEntity != NULL) - { - if (std::dynamic_pointer_cast(sourceEntity) != NULL) { - setLastHurtByMob(std::dynamic_pointer_cast(sourceEntity)); - - } - if (std::dynamic_pointer_cast(sourceEntity) != NULL) - { - lastHurtByPlayerTime = PLAYER_HURT_EXPERIENCE_TIME; - lastHurtByPlayer = std::dynamic_pointer_cast(sourceEntity); - } - else if (std::dynamic_pointer_cast(sourceEntity)) - { - std::shared_ptr w = std::dynamic_pointer_cast(sourceEntity); - if (w->isTame()) - { - lastHurtByPlayerTime = PLAYER_HURT_EXPERIENCE_TIME; - lastHurtByPlayer = nullptr; - } - } - } - - if (sound && level->isClientSide) - { - return false; - } - - if (sound) - { - level->broadcastEntityEvent(shared_from_this(), EntityEvent::HURT); - if (source != DamageSource::drown && source != DamageSource::controlledExplosion) markHurt(); - if (sourceEntity != NULL) - { - double xd = sourceEntity->x - x; - double zd = sourceEntity->z - z; - while (xd * xd + zd * zd < 0.0001) - { - xd = (Math::random() - Math::random()) * 0.01; - zd = (Math::random() - Math::random()) * 0.01; - } - hurtDir = (float) (atan2(zd, xd) * 180 / PI) - yRot; - knockback(sourceEntity, dmg, xd, zd); - } - else - { - hurtDir = (float) (int) ((Math::random() * 2) * 180); // 4J This cast is the same as Java - } - } - - MemSect(31); - if (health <= 0) - { - if (sound) level->playSound(shared_from_this(), getDeathSound(), getSoundVolume(), getVoicePitch()); - die(source); - } - else - { - if (sound) level->playSound(shared_from_this(), getHurtSound(), getSoundVolume(), getVoicePitch()); - } - MemSect(0); - - return true; -} - -float Mob::getVoicePitch() -{ - if (isBaby()) - { - return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.5f; - - } - return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f; -} - -void Mob::animateHurt() -{ - hurtTime = hurtDuration = 10; - hurtDir = 0; -} - -int Mob::getArmorValue() -{ - return 0; -} - -void Mob::hurtArmor(int damage) -{ -} - -int Mob::getDamageAfterArmorAbsorb(DamageSource *damageSource, int damage) -{ - if (!damageSource->isBypassArmor()) - { - int absorb = 25 - getArmorValue(); - int v = (damage) * absorb + dmgSpill; - hurtArmor(damage); - damage = v / 25; - dmgSpill = v % 25; - } - return damage; -} - -int Mob::getDamageAfterMagicAbsorb(DamageSource *damageSource, int damage) -{ - if (hasEffect(MobEffect::damageResistance)) - { - int absorbValue = (getEffect(MobEffect::damageResistance)->getAmplifier() + 1) * 5; - int absorb = 25 - absorbValue; - int v = (damage) * absorb + dmgSpill; - damage = v / 25; - dmgSpill = v % 25; - } - return damage; -} - -void Mob::actuallyHurt(DamageSource *source, int dmg) -{ - dmg = getDamageAfterArmorAbsorb(source, dmg); - dmg = getDamageAfterMagicAbsorb(source, dmg); - health -= dmg; -} - - -float Mob::getSoundVolume() -{ - return 1; -} - -int Mob::getAmbientSound() -{ - return -1; -} - -int Mob::getHurtSound() -{ - return eSoundType_DAMAGE_HURT; -} - -int Mob::getDeathSound() -{ - return eSoundType_DAMAGE_HURT; -} - -void Mob::knockback(std::shared_ptr source, int dmg, double xd, double zd) -{ - hasImpulse = true; - float dd = (float) sqrt(xd * xd + zd * zd); - float pow = 0.4f; - - this->xd /= 2; - this->yd /= 2; - this->zd /= 2; - - this->xd -= xd / dd * pow; - this->yd += pow; - this->zd -= zd / dd * pow; - - if (this->yd > 0.4f) this->yd = 0.4f; -} - -void Mob::die(DamageSource *source) -{ - std::shared_ptr sourceEntity = source->getEntity(); - if (deathScore >= 0 && sourceEntity != NULL) sourceEntity->awardKillScore(shared_from_this(), deathScore); - - if (sourceEntity != NULL) sourceEntity->killed( std::dynamic_pointer_cast( shared_from_this() ) ); - - dead = true; - - if (!level->isClientSide) - { - int playerBonus = 0; - std::shared_ptr player = std::dynamic_pointer_cast(sourceEntity); - if (player != NULL) - { - playerBonus = EnchantmentHelper::getKillingLootBonus(player->inventory); - } - if (!isBaby()) - { - dropDeathLoot(lastHurtByPlayerTime > 0, playerBonus); - if (lastHurtByPlayerTime > 0) - { - int rareLoot = random->nextInt(200) - playerBonus; - if (rareLoot < 5) - { - dropRareDeathLoot((rareLoot <= 0) ? 1 : 0); - } - } - } - - // 4J-JEV, hook for Durango mobKill event. - if (player != NULL) - { - player->awardStat(GenericStats::killMob(),GenericStats::param_mobKill(player, std::dynamic_pointer_cast(shared_from_this()), source)); - } - } - - level->broadcastEntityEvent(shared_from_this(), EntityEvent::DEATH); + level->broadcastEntityEvent(shared_from_this(), EntityEvent::DEATH); } /** -* Drop extra rare loot. Only occurs roughly 5% of the time, rareRootLevel -* is set to 1 (otherwise 0) 1% of the time. -* -* @param rareLootLevel -*/ -void Mob::dropRareDeathLoot(int rareLootLevel) -{ + * Drop extra rare loot. Only occurs roughly 5% of the time, rareRootLevel + * is set to 1 (otherwise 0) 1% of the time. + * + * @param rareLootLevel + */ +void Mob::dropRareDeathLoot(int rareLootLevel) {} +void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int loot = getDeathLoot(); + if (loot > 0) { + int count = random->nextInt(3); + if (playerBonusLevel > 0) { + count += random->nextInt(playerBonusLevel + 1); + } + for (int i = 0; i < count; i++) spawnAtLocation(loot, 1); + } } -void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int loot = getDeathLoot(); - if (loot > 0) - { - int count = random->nextInt(3); - if (playerBonusLevel > 0) - { - count += random->nextInt(playerBonusLevel + 1); - } - for (int i = 0; i < count; i++) - spawnAtLocation(loot, 1); - } +int Mob::getDeathLoot() { return 0; } + +void Mob::causeFallDamage(float distance) { + Entity::causeFallDamage(distance); + int dmg = (int)ceil(distance - 3); + if (dmg > 0) { + // 4J - new sounds here brought forward from 1.2.3 + if (dmg > 4) { + level->playSound(shared_from_this(), eSoundType_DAMAGE_FALL_BIG, 1, + 1); + } else { + level->playSound(shared_from_this(), eSoundType_DAMAGE_FALL_SMALL, + 1, 1); + } + hurt(DamageSource::fall, dmg); + + int t = level->getTile(Mth::floor(x), + Mth::floor(y - 0.2f - this->heightOffset), + Mth::floor(z)); + if (t > 0) { + const Tile::SoundType* soundType = Tile::tiles[t]->soundType; + MemSect(31); + level->playSound(shared_from_this(), soundType->getStepSound(), + soundType->getVolume() * 0.5f, + soundType->getPitch() * 0.75f); + MemSect(0); + } + } } -int Mob::getDeathLoot() -{ - return 0; -} - -void Mob::causeFallDamage(float distance) -{ - Entity::causeFallDamage(distance); - int dmg = (int) ceil(distance - 3); - if (dmg > 0) - { - // 4J - new sounds here brought forward from 1.2.3 - if (dmg > 4) - { - level->playSound(shared_from_this(), eSoundType_DAMAGE_FALL_BIG, 1, 1); - } - else - { - level->playSound(shared_from_this(), eSoundType_DAMAGE_FALL_SMALL, 1, 1); - } - hurt(DamageSource::fall, dmg); - - int t = level->getTile( Mth::floor(x), Mth::floor(y - 0.2f - this->heightOffset), Mth::floor(z)); - if (t > 0) - { - const Tile::SoundType *soundType = Tile::tiles[t]->soundType; - MemSect(31); - level->playSound(shared_from_this(), soundType->getStepSound(), soundType->getVolume() * 0.5f, soundType->getPitch() * 0.75f); - MemSect(0); - } - } -} - -void Mob::travel(float xa, float ya) -{ +void Mob::travel(float xa, float ya) { #ifdef __PSVITA__ - // AP - std::dynamic_pointer_cast is a non-trivial call - Player *thisPlayer = NULL; - if( (GetType() & eTYPE_PLAYER) == eTYPE_PLAYER ) - { - thisPlayer = (Player*) this; - } + // AP - std::dynamic_pointer_cast is a non-trivial call + Player* thisPlayer = NULL; + if ((GetType() & eTYPE_PLAYER) == eTYPE_PLAYER) { + thisPlayer = (Player*)this; + } #else - std::shared_ptr thisPlayer = std::dynamic_pointer_cast(shared_from_this()); + std::shared_ptr thisPlayer = + std::dynamic_pointer_cast(shared_from_this()); #endif - if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying) ) - { - double yo = y; - moveRelative(xa, ya, useNewAi() ? 0.04f : 0.02f); - move(xd, yd, zd); + if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying)) { + double yo = y; + moveRelative(xa, ya, useNewAi() ? 0.04f : 0.02f); + move(xd, yd, zd); - xd *= 0.80f; - yd *= 0.80f; - zd *= 0.80f; - yd -= 0.02; + xd *= 0.80f; + yd *= 0.80f; + zd *= 0.80f; + yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) - { - yd = 0.3f; - } - } - else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying) ) - { - double yo = y; - moveRelative(xa, ya, 0.02f); - move(xd, yd, zd); - xd *= 0.50f; - yd *= 0.50f; - zd *= 0.50f; - yd -= 0.02; + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { + yd = 0.3f; + } + } else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying)) { + double yo = y; + moveRelative(xa, ya, 0.02f); + move(xd, yd, zd); + xd *= 0.50f; + yd *= 0.50f; + zd *= 0.50f; + yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) - { - yd = 0.3f; - } - } - else - { - float friction = 0.91f; - if (onGround) - { - friction = 0.6f * 0.91f; - int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.91f; - } - } + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { + yd = 0.3f; + } + } else { + float friction = 0.91f; + if (onGround) { + friction = 0.6f * 0.91f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.91f; + } + } - float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / (friction * friction * friction); + float friction2 = (0.6f * 0.6f * 0.91f * 0.91f * 0.6f * 0.91f) / + (friction * friction * friction); - float speed; - if (onGround) - { - if (useNewAi()) speed = getSpeed(); - else speed = walkingSpeed; - speed *= friction2; - } - else speed = flyingSpeed; + float speed; + if (onGround) { + if (useNewAi()) + speed = getSpeed(); + else + speed = walkingSpeed; + speed *= friction2; + } else + speed = flyingSpeed; - moveRelative(xa, ya, speed); + moveRelative(xa, ya, speed); - friction = 0.91f; - if (onGround) - { - friction = 0.6f * 0.91f; - int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.91f; - } - } - if (onLadder()) - { - float max = 0.15f; - if (xd < -max) xd = -max; - if (xd > max) xd = max; - if (zd < -max) zd = -max; - if (zd > max) zd = max; - this->fallDistance = 0; - if (yd < -0.15) yd = -0.15; - bool playerSneaking = isSneaking() && std::dynamic_pointer_cast(shared_from_this()) != NULL; - if (playerSneaking && yd < 0) yd = 0; - } + friction = 0.91f; + if (onGround) { + friction = 0.6f * 0.91f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.91f; + } + } + if (onLadder()) { + float max = 0.15f; + if (xd < -max) xd = -max; + if (xd > max) xd = max; + if (zd < -max) zd = -max; + if (zd > max) zd = max; + this->fallDistance = 0; + if (yd < -0.15) yd = -0.15; + bool playerSneaking = + isSneaking() && + std::dynamic_pointer_cast(shared_from_this()) != NULL; + if (playerSneaking && yd < 0) yd = 0; + } - move(xd, yd, zd); + move(xd, yd, zd); - if (horizontalCollision && onLadder()) - { - yd = 0.2; - } + if (horizontalCollision && onLadder()) { + yd = 0.2; + } - yd -= 0.08; - yd *= 0.98f; - xd *= friction; - zd *= friction; - } + yd -= 0.08; + yd *= 0.98f; + xd *= friction; + zd *= friction; + } - walkAnimSpeedO = walkAnimSpeed; - double xxd = x - xo; - double zzd = z - zo; - float wst = Mth::sqrt(xxd * xxd + zzd * zzd) * 4; - if (wst > 1) wst = 1; - walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; - walkAnimPos += walkAnimSpeed; + walkAnimSpeedO = walkAnimSpeed; + double xxd = x - xo; + double zzd = z - zo; + float wst = Mth::sqrt(xxd * xxd + zzd * zzd) * 4; + if (wst > 1) wst = 1; + walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; + walkAnimPos += walkAnimSpeed; } -bool Mob::onLadder() -{ - int xt = Mth::floor(x); - int yt = Mth::floor(bb->y0); - int zt = Mth::floor(z); +bool Mob::onLadder() { + int xt = Mth::floor(x); + int yt = Mth::floor(bb->y0); + int zt = Mth::floor(z); - // 4J-PB - TU9 - add climbable vines - int iTile = level->getTile(xt, yt, zt); - return (iTile== Tile::ladder_Id) || (iTile== Tile::vine_Id); + // 4J-PB - TU9 - add climbable vines + int iTile = level->getTile(xt, yt, zt); + return (iTile == Tile::ladder_Id) || (iTile == Tile::vine_Id); } +bool Mob::isShootable() { return true; } -bool Mob::isShootable() -{ - return true; +void Mob::addAdditonalSaveData(CompoundTag* entityTag) { + entityTag->putShort(L"Health", (short)health); + entityTag->putShort(L"HurtTime", (short)hurtTime); + entityTag->putShort(L"DeathTime", (short)deathTime); + entityTag->putShort(L"AttackTime", (short)attackTime); + + if (!activeEffects.empty()) { + ListTag* listTag = new ListTag(); + + for (AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); + ++it) { + MobEffectInstance* effect = it->second; + + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Id", static_cast(effect->getId())); + tag->putByte(L"Amplifier", (char)effect->getAmplifier()); + tag->putInt(L"Duration", effect->getDuration()); + listTag->add(tag); + } + entityTag->put(L"ActiveEffects", listTag); + } } -void Mob::addAdditonalSaveData(CompoundTag *entityTag) -{ - entityTag->putShort(L"Health", (short) health); - entityTag->putShort(L"HurtTime", (short) hurtTime); - entityTag->putShort(L"DeathTime", (short) deathTime); - entityTag->putShort(L"AttackTime", (short) attackTime); +void Mob::readAdditionalSaveData(CompoundTag* tag) { + if (health < Short::MIN_VALUE) health = Short::MIN_VALUE; + health = tag->getShort(L"Health"); + if (!tag->contains(L"Health")) health = getMaxHealth(); + hurtTime = tag->getShort(L"HurtTime"); + deathTime = tag->getShort(L"DeathTime"); + attackTime = tag->getShort(L"AttackTime"); - if (!activeEffects.empty()) - { - ListTag *listTag = new ListTag(); + if (tag->contains(L"ActiveEffects")) { + ListTag* effects = + (ListTag*)tag->getList(L"ActiveEffects"); + for (int i = 0; i < effects->size(); i++) { + CompoundTag* effectTag = effects->get(i); + int id = effectTag->getByte(L"Id"); + int amplifier = effectTag->getByte(L"Amplifier"); + int duration = effectTag->getInt(L"Duration"); - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) - { - MobEffectInstance *effect = it->second; - - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Id", static_cast(effect->getId())); - tag->putByte(L"Amplifier", (char) effect->getAmplifier()); - tag->putInt(L"Duration", effect->getDuration()); - listTag->add(tag); - } - entityTag->put(L"ActiveEffects", listTag); - } + activeEffects.insert( + std::unordered_map::value_type( + id, new MobEffectInstance(id, duration, amplifier))); + } + } } -void Mob::readAdditionalSaveData(CompoundTag *tag) -{ - if (health < Short::MIN_VALUE) health = Short::MIN_VALUE; - health = tag->getShort(L"Health"); - if (!tag->contains(L"Health")) health = getMaxHealth(); - hurtTime = tag->getShort(L"HurtTime"); - deathTime = tag->getShort(L"DeathTime"); - attackTime = tag->getShort(L"AttackTime"); +bool Mob::isAlive() { return !removed && health > 0; } - if (tag->contains(L"ActiveEffects")) - { - ListTag *effects = (ListTag *) tag->getList(L"ActiveEffects"); - for (int i = 0; i < effects->size(); i++) - { - CompoundTag *effectTag = effects->get(i); - int id = effectTag->getByte(L"Id"); - int amplifier = effectTag->getByte(L"Amplifier"); - int duration = effectTag->getInt(L"Duration"); +bool Mob::isWaterMob() { return false; } - activeEffects.insert( std::unordered_map::value_type( id, new MobEffectInstance(id, duration, amplifier) ) ); - } - } +// 4J - added for more accurate lighting of mobs. Takes a weighted average of +// all tiles touched by the bounding volume of the entity - the method in the +// Entity class (which used to be used for mobs too) simply gets a single tile's +// lighting value causing sudden changes of lighting values when entities go in +// and out of lit areas, for example when bobbing in the water. +int Mob::getLightColor(float a) { + float accum[2] = {0, 0}; + float totVol = (bb->x1 - bb->x0) * (bb->y1 - bb->y0) * (bb->z1 - bb->z0); + int xmin = Mth::floor(bb->x0); + int xmax = Mth::floor(bb->x1); + int ymin = Mth::floor(bb->y0); + int ymax = Mth::floor(bb->y1); + int zmin = Mth::floor(bb->z0); + int zmax = Mth::floor(bb->z1); + for (int xt = xmin; xt <= xmax; xt++) + for (int yt = ymin; yt <= ymax; yt++) + for (int zt = zmin; zt <= zmax; zt++) { + float tilexmin = (float)xt; + float tilexmax = (float)(xt + 1); + float tileymin = (float)yt; + float tileymax = (float)(yt + 1); + float tilezmin = (float)zt; + float tilezmax = (float)(zt + 1); + if (tilexmin < bb->x0) tilexmin = bb->x0; + if (tilexmax > bb->x1) tilexmax = bb->x1; + if (tileymin < bb->y0) tileymin = bb->y0; + if (tileymax > bb->y1) tileymax = bb->y1; + if (tilezmin < bb->z0) tilezmin = bb->z0; + if (tilezmax > bb->z1) tilezmax = bb->z1; + float tileVol = (tilexmax - tilexmin) * (tileymax - tileymin) * + (tilezmax - tilezmin); + float frac = tileVol / totVol; + int lc = level->getLightColor(xt, yt, zt, 0); + accum[0] += frac * (float)(lc & 0xffff); + accum[1] += frac * (float)(lc >> 16); + } + + if (accum[0] > 240.0f) accum[0] = 240.0f; + if (accum[1] > 240.0f) accum[1] = 240.0f; + + return (((int)accum[1]) << 16) | ((int)accum[0]); } -bool Mob::isAlive() -{ - return !removed && health > 0; +void Mob::setYya(float yya) { this->yya = yya; } + +void Mob::setJumping(bool jump) { jumping = jump; } + +void Mob::aiStep() { + if (noJumpDelay > 0) noJumpDelay--; + if (lSteps > 0) { + double xt = x + (lx - x) / lSteps; + double yt = y + (ly - y) / lSteps; + double zt = z + (lz - z) / lSteps; + + double yrd = Mth::wrapDegrees(lyr - yRot); + double xrd = Mth::wrapDegrees(lxr - xRot); + + yRot += (float)((yrd) / lSteps); + xRot += (float)((xrd) / lSteps); + + lSteps--; + this->setPos(xt, yt, zt); + this->setRot(yRot, xRot); + + // 4J - this collision is carried out to try and stop the lerping push + // the mob through the floor, in which case gravity can then carry on + // moving the mob because the collision just won't work anymore. BB for + // collision used to be calculated as: bb->shrink(1 / 32.0, 0, 1 / 32.0) + // now using a reduced BB to try and get rid of some issues where mobs + // pop up the sides of walls, undersides of trees etc. + AABB* shrinkbb = bb->shrink(0.1, 0, 0.1); + shrinkbb->y1 = shrinkbb->y0 + 0.1; + AABBList* collisions = level->getCubes(shared_from_this(), shrinkbb); + if (collisions->size() > 0) { + double yTop = 0; + AUTO_VAR(itEnd, collisions->end()); + for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) { + AABB* ab = *it; // collisions->at(i); + if (ab->y1 > yTop) yTop = ab->y1; + } + + yt += yTop - bb->y0; + setPos(xt, yt, zt); + } + if (abs(xd) < MIN_MOVEMENT_DISTANCE) xd = 0; + if (abs(yd) < MIN_MOVEMENT_DISTANCE) yd = 0; + if (abs(zd) < MIN_MOVEMENT_DISTANCE) zd = 0; + } + + if (isImmobile()) { + jumping = false; + xxa = 0; + yya = 0; + yRotA = 0; + } else { + MemSect(25); + if (isEffectiveAI()) { + if (useNewAi()) { + newServerAiStep(); + } else { + serverAiStep(); + yHeadRot = yRot; + } + } + MemSect(0); + } + + if (jumping) { + if (isInWater() || isInLava()) { + yd += 0.04f; + } else if (onGround) { + if (noJumpDelay == 0) { + jumpFromGround(); + noJumpDelay = 10; + } + } + } else { + noJumpDelay = 0; + } + + xxa *= 0.98f; + yya *= 0.98f; + yRotA *= 0.9f; + + float normalSpeed = walkingSpeed; + walkingSpeed *= getWalkingSpeedModifier(); + travel(xxa, yya); + walkingSpeed = normalSpeed; + + if (!level->isClientSide) { + std::vector >* entities = level->getEntities( + shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); + if (entities != NULL && !entities->empty()) { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); + if (e->isPushable()) e->push(shared_from_this()); + } + } + } } -bool Mob::isWaterMob() -{ - return false; +bool Mob::useNewAi() { return false; } + +bool Mob::isEffectiveAI() { return !level->isClientSide; } + +bool Mob::isImmobile() { return health <= 0; } + +bool Mob::isBlocking() { return false; } + +void Mob::jumpFromGround() { + yd = 0.42f; + if (hasEffect(MobEffect::jump)) { + yd += (getEffect(MobEffect::jump)->getAmplifier() + 1) * .1f; + } + if (isSprinting()) { + float rr = yRot * Mth::RAD_TO_GRAD; + + xd -= Mth::sin(rr) * 0.2f; + zd += Mth::cos(rr) * 0.2f; + } + this->hasImpulse = true; } -// 4J - added for more accurate lighting of mobs. Takes a weighted average of all tiles touched by the bounding volume of the entity - the method in the Entity class (which used to be used for -// mobs too) simply gets a single tile's lighting value causing sudden changes of lighting values when entities go in and out of lit areas, for example when bobbing in the water. -int Mob::getLightColor(float a) -{ - float accum[2] = {0,0}; - float totVol = ( bb->x1 - bb->x0 ) * ( bb->y1 - bb->y0 ) * ( bb->z1 - bb->z0 ); - int xmin = Mth::floor(bb->x0); - int xmax = Mth::floor(bb->x1); - int ymin = Mth::floor(bb->y0); - int ymax = Mth::floor(bb->y1); - int zmin = Mth::floor(bb->z0); - int zmax = Mth::floor(bb->z1); - for( int xt = xmin; xt <= xmax; xt++ ) - for( int yt = ymin; yt <= ymax; yt++ ) - for( int zt = zmin; zt <= zmax; zt++ ) - { - float tilexmin = (float)xt; - float tilexmax = (float)(xt+1); - float tileymin = (float)yt; - float tileymax = (float)(yt+1); - float tilezmin = (float)zt; - float tilezmax = (float)(zt+1); - if( tilexmin < bb->x0 ) tilexmin = bb->x0; - if( tilexmax > bb->x1 ) tilexmax = bb->x1; - if( tileymin < bb->y0 ) tileymin = bb->y0; - if( tileymax > bb->y1 ) tileymax = bb->y1; - if( tilezmin < bb->z0 ) tilezmin = bb->z0; - if( tilezmax > bb->z1 ) tilezmax = bb->z1; - float tileVol = ( tilexmax - tilexmin ) * ( tileymax - tileymin ) * ( tilezmax - tilezmin ); - float frac = tileVol / totVol; - int lc = level->getLightColor(xt, yt, zt, 0); - accum[0] += frac * (float)( lc & 0xffff ); - accum[1] += frac * (float)( lc >> 16 ); - } +bool Mob::removeWhenFarAway() { return true; } - if( accum[0] > 240.0f ) accum[0] = 240.0f; - if( accum[1] > 240.0f ) accum[1] = 240.0f; +void Mob::checkDespawn() { + std::shared_ptr player = + level->getNearestPlayer(shared_from_this(), -1); + if (player != NULL) { + double xd = player->x - x; + double yd = player->y - y; + double zd = player->z - z; + double sd = xd * xd + yd * yd + zd * zd; - return ( ( (int)accum[1])<<16) | ((int)accum[0]); + if (removeWhenFarAway() && sd > 128 * 128) { + remove(); + } + + if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && + sd > 32 * 32 && removeWhenFarAway()) { + remove(); + } else if (sd < 32 * 32) { + noActionTime = 0; + } + } } -void Mob::setYya(float yya) -{ - this->yya = yya; +void Mob::newServerAiStep() { + MemSect(51); + noActionTime++; + checkDespawn(); + sensing->tick(); + targetSelector.tick(); + goalSelector.tick(); + navigation->tick(); + serverAiMobStep(); + moveControl->tick(); + lookControl->tick(); + jumpControl->tick(); + // Consider this for extra strolling if it is protected against despawning. + // We aren't interested in ones that aren't protected as the whole point of + // this extra wandering is to potentially transition from protected to not + // protected. + considerForExtraWandering(isDespawnProtected()); + MemSect(0); } -void Mob::setJumping(bool jump) -{ - jumping = jump; +void Mob::serverAiMobStep() {} + +void Mob::serverAiStep() { + noActionTime++; + + checkDespawn(); + + xxa = 0; + yya = 0; + + float lookDistance = 8; + if (random->nextFloat() < 0.02f) { + std::shared_ptr player = + level->getNearestPlayer(shared_from_this(), lookDistance); + if (player != NULL) { + lookingAt = player; + lookTime = 10 + random->nextInt(20); + } else { + yRotA = (random->nextFloat() - 0.5f) * 20; + } + } + + if (lookingAt != NULL) { + lookAt(lookingAt, 10.0f, (float)getMaxHeadXRot()); + if (lookTime-- <= 0 || lookingAt->removed || + lookingAt->distanceToSqr(shared_from_this()) > + lookDistance * lookDistance) { + lookingAt = nullptr; + } + } else { + if (random->nextFloat() < 0.05f) { + yRotA = (random->nextFloat() - 0.5f) * 20; + } + yRot += yRotA; + xRot = defaultLookAngle; + } + + bool inWater = isInWater(); + bool inLava = isInLava(); + if (inWater || inLava) jumping = random->nextFloat() < 0.8f; } -void Mob::aiStep() -{ - if (noJumpDelay > 0) noJumpDelay--; - if (lSteps > 0) - { - double xt = x + (lx - x) / lSteps; - double yt = y + (ly - y) / lSteps; - double zt = z + (lz - z) / lSteps; +int Mob::getMaxHeadXRot() { return 40; } - double yrd = Mth::wrapDegrees(lyr - yRot); - double xrd = Mth::wrapDegrees(lxr - xRot); +void Mob::lookAt(std::shared_ptr e, float yMax, float xMax) { + double xd = e->x - x; + double yd; + double zd = e->z - z; - yRot += (float) ( (yrd) / lSteps ); - xRot += (float) ( (xrd) / lSteps ); + std::shared_ptr mob = std::dynamic_pointer_cast(e); + if (mob != NULL) { + yd = (y + getHeadHeight()) - (mob->y + mob->getHeadHeight()); + } else { + yd = (e->bb->y0 + e->bb->y1) / 2 - (y + getHeadHeight()); + } - lSteps--; - this->setPos(xt, yt, zt); - this->setRot(yRot, xRot); + double sd = Mth::sqrt(xd * xd + zd * zd); - // 4J - this collision is carried out to try and stop the lerping push the mob through the floor, - // in which case gravity can then carry on moving the mob because the collision just won't work anymore. - // BB for collision used to be calculated as: bb->shrink(1 / 32.0, 0, 1 / 32.0) - // now using a reduced BB to try and get rid of some issues where mobs pop up the sides of walls, undersides of - // trees etc. - AABB *shrinkbb = bb->shrink(0.1, 0, 0.1); - shrinkbb->y1 = shrinkbb->y0 + 0.1; - AABBList *collisions = level->getCubes(shared_from_this(), shrinkbb); - if (collisions->size() > 0) - { - double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) - { - AABB *ab = *it; //collisions->at(i); - if (ab->y1 > yTop) yTop = ab->y1; - } - - yt += yTop - bb->y0; - setPos(xt, yt, zt); - } - if (abs(xd) < MIN_MOVEMENT_DISTANCE) xd = 0; - if (abs(yd) < MIN_MOVEMENT_DISTANCE) yd = 0; - if (abs(zd) < MIN_MOVEMENT_DISTANCE) zd = 0; - } - - if (isImmobile()) - { - jumping = false; - xxa = 0; - yya = 0; - yRotA = 0; - } - else - { - MemSect(25); - if (isEffectiveAI()) - { - if (useNewAi()) - { - newServerAiStep(); - } - else - { - serverAiStep(); - yHeadRot = yRot; - } - } - MemSect(0); - } - - if (jumping) - { - if (isInWater() || isInLava() ) - { - yd += 0.04f; - } - else if (onGround) - { - if (noJumpDelay == 0) - { - jumpFromGround(); - noJumpDelay = 10; - } - } - } - else - { - noJumpDelay = 0; - } - - - xxa *= 0.98f; - yya *= 0.98f; - yRotA *= 0.9f; - - float normalSpeed = walkingSpeed; - walkingSpeed *= getWalkingSpeedModifier(); - travel(xxa, yya); - walkingSpeed = normalSpeed; - - if(!level->isClientSide) - { - std::vector > *entities = level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) - { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); - if (e->isPushable()) e->push(shared_from_this()); - } - } - } + float yRotD = (float)(atan2(zd, xd) * 180 / PI) - 90; + float xRotD = (float)-(atan2(yd, sd) * 180 / PI); + xRot = -rotlerp(xRot, xRotD, xMax); + yRot = rotlerp(yRot, yRotD, yMax); } -bool Mob::useNewAi() -{ - return false; +bool Mob::isLookingAtAnEntity() { return lookingAt != NULL; } + +std::shared_ptr Mob::getLookingAt() { return lookingAt; } + +float Mob::rotlerp(float a, float b, float max) { + float diff = Mth::wrapDegrees(b - a); + if (diff > max) { + diff = max; + } + if (diff < -max) { + diff = -max; + } + return a + diff; } -bool Mob::isEffectiveAI() -{ - return !level->isClientSide; +bool Mob::canSpawn() { + // 4J - altered to use special containsAnyLiquid variant + return level->isUnobstructed(bb) && + level->getCubes(shared_from_this(), bb)->empty() && + !level->containsAnyLiquid_NoLoad(bb); } -bool Mob::isImmobile() -{ - return health <= 0; +void Mob::outOfWorld() { hurt(DamageSource::outOfWorld, 4); } + +float Mob::getAttackAnim(float a) { + float diff = attackAnim - oAttackAnim; + if (diff < 0) diff += 1; + return oAttackAnim + diff * a; } -bool Mob::isBlocking() -{ - return false; +Vec3* Mob::getPos(float a) { + if (a == 1) { + return Vec3::newTemp(x, y, z); + } + double x = xo + (this->x - xo) * a; + double y = yo + (this->y - yo) * a; + double z = zo + (this->z - zo) * a; + + return Vec3::newTemp(x, y, z); } -void Mob::jumpFromGround() -{ - yd = 0.42f; - if (hasEffect(MobEffect::jump)) - { - yd += (getEffect(MobEffect::jump)->getAmplifier() + 1) * .1f; - } - if (isSprinting()) - { - float rr = yRot * Mth::RAD_TO_GRAD; +Vec3* Mob::getLookAngle() { return getViewVector(1); } - xd -= Mth::sin(rr) * 0.2f; - zd += Mth::cos(rr) * 0.2f; - } - this->hasImpulse = true; +Vec3* Mob::getViewVector(float a) { + if (a == 1) { + float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); + float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); + float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); + float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); + + return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); + } + float xRot = xRotO + (this->xRot - xRotO) * a; + float yRot = yRotO + (this->yRot - yRotO) * a; + + float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); + float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); + float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); + float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); + + return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); } -bool Mob::removeWhenFarAway() -{ - return true; +float Mob::getSizeScale() { return 1.0f; } + +float Mob::getHeadSizeScale() { return 1.0f; } + +HitResult* Mob::pick(double range, float a) { + Vec3* from = getPos(a); + Vec3* b = getViewVector(a); + Vec3* to = from->add(b->x * range, b->y * range, b->z * range); + return level->clip(from, to); } -void Mob::checkDespawn() -{ - std::shared_ptr player = level->getNearestPlayer(shared_from_this(), -1); - if (player != NULL) - { - double xd = player->x - x; - double yd = player->y - y; - double zd = player->z - z; - double sd = xd * xd + yd * yd + zd * zd; +int Mob::getMaxSpawnClusterSize() { return 4; } - if (removeWhenFarAway() && sd > 128 * 128) - { - remove(); - } +std::shared_ptr Mob::getCarriedItem() { return nullptr; } - if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && sd > 32 * 32 && removeWhenFarAway()) - { - remove(); - } - else if (sd < 32 * 32) - { - noActionTime = 0; - } - } +std::shared_ptr Mob::getArmor(int pos) { + // 4J Stu - Not implemented yet + return nullptr; + // return equipment[pos + 1]; } -void Mob::newServerAiStep() -{ - MemSect(51); - noActionTime++; - checkDespawn(); - sensing->tick(); - targetSelector.tick(); - goalSelector.tick(); - navigation->tick(); - serverAiMobStep(); - moveControl->tick(); - lookControl->tick(); - jumpControl->tick(); - // Consider this for extra strolling if it is protected against despawning. We aren't interested in ones that aren't protected as the whole point of this - // extra wandering is to potentially transition from protected to not protected. - considerForExtraWandering( isDespawnProtected() ); - MemSect(0); +void Mob::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::HURT) { + this->walkAnimSpeed = 1.5f; + + invulnerableTime = invulnerableDuration; + hurtTime = hurtDuration = 10; + hurtDir = 0; + + MemSect(31); + // 4J-PB -added because villagers have no sounds + int iHurtSound = getHurtSound(); + if (iHurtSound != -1) { + level->playSound( + shared_from_this(), iHurtSound, getSoundVolume(), + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + } + MemSect(0); + hurt(DamageSource::genericSource, 0); + } else if (id == EntityEvent::DEATH) { + MemSect(31); + // 4J-PB -added because villagers have no sounds + int iDeathSound = getDeathSound(); + if (iDeathSound != -1) { + level->playSound( + shared_from_this(), iDeathSound, getSoundVolume(), + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + } + MemSect(0); + health = 0; + die(DamageSource::genericSource); + } else { + Entity::handleEntityEvent(id); + } } -void Mob::serverAiMobStep() -{ +bool Mob::isSleeping() { return false; } + +Icon* Mob::getItemInHandIcon(std::shared_ptr item, int layer) { + return item->getIcon(); } -void Mob::serverAiStep() -{ - noActionTime++; - - checkDespawn(); - - xxa = 0; - yya = 0; - - float lookDistance = 8; - if (random->nextFloat() < 0.02f) - { - std::shared_ptr player = level->getNearestPlayer(shared_from_this(), lookDistance); - if (player != NULL) - { - lookingAt = player; - lookTime = 10 + random->nextInt(20); - } - else - { - yRotA = (random->nextFloat() - 0.5f) * 20; - } - } - - if (lookingAt != NULL) - { - lookAt(lookingAt, 10.0f, (float) getMaxHeadXRot()); - if (lookTime-- <= 0 || lookingAt->removed || lookingAt->distanceToSqr(shared_from_this()) > lookDistance * lookDistance) - { - lookingAt = nullptr; - } - } - else - { - if (random->nextFloat() < 0.05f) - { - yRotA = (random->nextFloat() - 0.5f) * 20; - } - yRot += yRotA; - xRot = defaultLookAngle; - } - - bool inWater = isInWater(); - bool inLava = isInLava(); - if (inWater || inLava) jumping = random->nextFloat() < 0.8f; +// 4J added so we can not render mobs before their chunks are loaded - to +// resolve bug 10327 :Gameplay: NPCs can spawn over chunks that have not yet +// been streamed and display jitter. +bool Mob::shouldRender(Vec3* c) { + if (!level->reallyHasChunksAt(Mth::floor(bb->x0), Mth::floor(bb->y0), + Mth::floor(bb->z0), Mth::floor(bb->x1), + Mth::floor(bb->y1), Mth::floor(bb->z1))) { + return false; + } + return Entity::shouldRender(c); } -int Mob::getMaxHeadXRot() -{ - return 40; +void Mob::tickEffects() { + bool removed = false; + for (AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();) { + MobEffectInstance* effect = it->second; + removed = false; + if (!effect->tick(std::dynamic_pointer_cast(shared_from_this()))) { + if (!level->isClientSide) { + it = activeEffects.erase(it); + onEffectRemoved(effect); + delete effect; + removed = true; + } + } + if (!removed) { + ++it; + } + } + if (effectsDirty) { + if (!level->isClientSide) { + if (activeEffects.empty()) { + entityData->set(DATA_EFFECT_COLOR_ID, (int)0); + setInvisible(false); + setWeakened(false); + } else { + std::vector values; + for (AUTO_VAR(it, activeEffects.begin()); + it != activeEffects.end(); ++it) { + values.push_back(it->second); + } + int colorValue = PotionBrewing::getColorValue(&values); + values.clear(); + entityData->set(DATA_EFFECT_COLOR_ID, colorValue); + setInvisible(hasEffect(MobEffect::invisibility->id)); + setWeakened(hasEffect(MobEffect::weakness->id)); + } + } + effectsDirty = false; + } + if (random->nextBoolean()) { + int colorValue = entityData->getInteger(DATA_EFFECT_COLOR_ID); + if (colorValue > 0) { + double red = (double)((colorValue >> 16) & 0xff) / 255.0; + double green = (double)((colorValue >> 8) & 0xff) / 255.0; + double blue = (double)((colorValue >> 0) & 0xff) / 255.0; + + level->addParticle( + eParticleType_mobSpell, + x + (random->nextDouble() - 0.5) * bbWidth, + y + random->nextDouble() * bbHeight - heightOffset, + z + (random->nextDouble() - 0.5) * bbWidth, red, green, blue); + } + } } -void Mob::lookAt(std::shared_ptr e, float yMax, float xMax) -{ - double xd = e->x - x; - double yd; - double zd = e->z - z; - - std::shared_ptr mob = std::dynamic_pointer_cast(e); - if(mob != NULL) - { - yd = (y + getHeadHeight()) - (mob->y + mob->getHeadHeight()); - } - else - { - yd = (e->bb->y0 + e->bb->y1) / 2 - (y + getHeadHeight()); - } +void Mob::removeAllEffects() { + // Iterator effectIdIterator = activeEffects.keySet().iterator(); + // while (effectIdIterator.hasNext()) + for (AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();) { + // Integer effectId = effectIdIterator.next(); + MobEffectInstance* effect = it->second; // activeEffects.get(effectId); - double sd = Mth::sqrt(xd * xd + zd * zd); - - float yRotD = (float) (atan2(zd, xd) * 180 / PI) - 90; - float xRotD = (float) -(atan2(yd, sd) * 180 / PI); - xRot = -rotlerp(xRot, xRotD, xMax); - yRot = rotlerp(yRot, yRotD, yMax); + if (!level->isClientSide) { + // effectIdIterator.remove(); + it = activeEffects.erase(it); + onEffectRemoved(effect); + delete effect; + } else { + ++it; + } + } } -bool Mob::isLookingAtAnEntity() -{ - return lookingAt != NULL; +std::vector* Mob::getActiveEffects() { + std::vector* active = + new std::vector(); + + for (AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) { + active->push_back(it->second); + } + + return active; } -std::shared_ptr Mob::getLookingAt() -{ - return lookingAt; +bool Mob::hasEffect(int id) { + return activeEffects.find(id) != activeEffects.end(); + ; } -float Mob::rotlerp(float a, float b, float max) -{ - float diff = Mth::wrapDegrees(b - a); - if (diff > max) - { - diff = max; - } - if (diff < -max) - { - diff = -max; - } - return a + diff; +bool Mob::hasEffect(MobEffect* effect) { + return activeEffects.find(effect->id) != activeEffects.end(); } -bool Mob::canSpawn() -{ - // 4J - altered to use special containsAnyLiquid variant - return level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid_NoLoad(bb); +MobEffectInstance* Mob::getEffect(MobEffect* effect) { + MobEffectInstance* effectInst = NULL; + + AUTO_VAR(it, activeEffects.find(effect->id)); + if (it != activeEffects.end()) effectInst = it->second; + + return effectInst; } -void Mob::outOfWorld() -{ - hurt(DamageSource::outOfWorld, 4); -} +void Mob::addEffect(MobEffectInstance* newEffect) { + if (!canBeAffected(newEffect)) { + return; + } -float Mob::getAttackAnim(float a) -{ - float diff = attackAnim - oAttackAnim; - if (diff < 0) diff += 1; - return oAttackAnim + diff * a; -} - - -Vec3 *Mob::getPos(float a) -{ - if (a == 1) - { - return Vec3::newTemp(x, y, z); - } - double x = xo + (this->x - xo) * a; - double y = yo + (this->y - yo) * a; - double z = zo + (this->z - zo) * a; - - return Vec3::newTemp(x, y, z); -} - -Vec3 *Mob::getLookAngle() -{ - return getViewVector(1); -} - -Vec3 *Mob::getViewVector(float a) -{ - if (a == 1) - { - float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); - float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); - float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); - float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); - - return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); - } - float xRot = xRotO + (this->xRot - xRotO) * a; - float yRot = yRotO + (this->yRot - yRotO) * a; - - float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); - float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); - float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); - float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); - - return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); -} - -float Mob::getSizeScale() -{ - return 1.0f; -} - -float Mob::getHeadSizeScale() -{ - return 1.0f; -} - -HitResult *Mob::pick(double range, float a) -{ - Vec3 *from = getPos(a); - Vec3 *b = getViewVector(a); - Vec3 *to = from->add(b->x * range, b->y * range, b->z * range); - return level->clip(from, to); -} - -int Mob::getMaxSpawnClusterSize() -{ - return 4; -} - -std::shared_ptr Mob::getCarriedItem() -{ - return nullptr; -} - -std::shared_ptr Mob::getArmor(int pos) -{ - // 4J Stu - Not implemented yet - return nullptr; - //return equipment[pos + 1]; -} - -void Mob::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::HURT) - { - this->walkAnimSpeed = 1.5f; - - invulnerableTime = invulnerableDuration; - hurtTime = hurtDuration = 10; - hurtDir = 0; - - MemSect(31); - // 4J-PB -added because villagers have no sounds - int iHurtSound=getHurtSound(); - if(iHurtSound!=-1) - { - level->playSound(shared_from_this(), iHurtSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - } - MemSect(0); - hurt(DamageSource::genericSource, 0); - } - else if (id == EntityEvent::DEATH) - { - MemSect(31); - // 4J-PB -added because villagers have no sounds - int iDeathSound=getDeathSound(); - if(iDeathSound!=-1) - { - level->playSound(shared_from_this(), iDeathSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - } - MemSect(0); - health = 0; - die(DamageSource::genericSource); - } - else - { - Entity::handleEntityEvent(id); - } -} - -bool Mob::isSleeping() -{ - return false; -} - -Icon *Mob::getItemInHandIcon(std::shared_ptr item, int layer) -{ - return item->getIcon(); -} - -// 4J added so we can not render mobs before their chunks are loaded - to resolve bug 10327 :Gameplay: NPCs can spawn over chunks that have not yet been streamed and display jitter. -bool Mob::shouldRender(Vec3 *c) -{ - if( !level->reallyHasChunksAt( Mth::floor(bb->x0), Mth::floor(bb->y0), Mth::floor(bb->z0), Mth::floor(bb->x1), Mth::floor(bb->y1), Mth::floor(bb->z1))) - { - return false; - } - return Entity::shouldRender(c); -} - -void Mob::tickEffects() -{ - bool removed = false; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();) - { - MobEffectInstance *effect = it->second; - removed = false; - if (!effect->tick(std::dynamic_pointer_cast(shared_from_this()))) - { - if (!level->isClientSide) - { - it = activeEffects.erase( it ); - onEffectRemoved(effect); - delete effect; - removed = true; - } - } - if(!removed) - { - ++it; - } - } - if (effectsDirty) - { - if (!level->isClientSide) - { - if (activeEffects.empty()) - { - entityData->set(DATA_EFFECT_COLOR_ID, (int) 0); - setInvisible(false); - setWeakened(false); - } - else - { - std::vector values; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();++it) - { - values.push_back(it->second); - } - int colorValue = PotionBrewing::getColorValue(&values); - values.clear(); - entityData->set(DATA_EFFECT_COLOR_ID, colorValue); - setInvisible(hasEffect(MobEffect::invisibility->id)); - setWeakened(hasEffect(MobEffect::weakness->id)); - } - } - effectsDirty = false; - } - if (random->nextBoolean()) - { - int colorValue = entityData->getInteger(DATA_EFFECT_COLOR_ID); - if (colorValue > 0) - { - double red = (double) ((colorValue >> 16) & 0xff) / 255.0; - double green = (double) ((colorValue >> 8) & 0xff) / 255.0; - double blue = (double) ((colorValue >> 0) & 0xff) / 255.0; - - level->addParticle(eParticleType_mobSpell, x + (random->nextDouble() - 0.5) * bbWidth, y + random->nextDouble() * bbHeight - heightOffset, z + (random->nextDouble() - 0.5) * bbWidth, red, green, blue); - } - } -} - -void Mob::removeAllEffects() -{ - //Iterator effectIdIterator = activeEffects.keySet().iterator(); - //while (effectIdIterator.hasNext()) - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ) - { - //Integer effectId = effectIdIterator.next(); - MobEffectInstance *effect = it->second;//activeEffects.get(effectId); - - if (!level->isClientSide) - { - //effectIdIterator.remove(); - it = activeEffects.erase(it); - onEffectRemoved(effect); - delete effect; - } - else - { - ++it; - } - } -} - -std::vector *Mob::getActiveEffects() -{ - std::vector *active = new std::vector(); - - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) - { - active->push_back(it->second); - } - - return active; -} - -bool Mob::hasEffect(int id) -{ - return activeEffects.find(id) != activeEffects.end();; -} - -bool Mob::hasEffect(MobEffect *effect) -{ - return activeEffects.find(effect->id) != activeEffects.end(); -} - -MobEffectInstance *Mob::getEffect(MobEffect *effect) -{ - MobEffectInstance *effectInst = NULL; - - AUTO_VAR(it, activeEffects.find(effect->id)); - if(it != activeEffects.end() ) effectInst = it->second; - - return effectInst; -} - -void Mob::addEffect(MobEffectInstance *newEffect) -{ - if (!canBeAffected(newEffect)) - { - return; - } - - if (activeEffects.find(newEffect->getId()) != activeEffects.end() ) - { - // replace effect and update - MobEffectInstance *effectInst = activeEffects.find(newEffect->getId())->second; - effectInst->update(newEffect); - onEffectUpdated(effectInst); - } - else - { - activeEffects.insert( std::unordered_map::value_type( newEffect->getId(), newEffect ) ); - onEffectAdded(newEffect); - } + if (activeEffects.find(newEffect->getId()) != activeEffects.end()) { + // replace effect and update + MobEffectInstance* effectInst = + activeEffects.find(newEffect->getId())->second; + effectInst->update(newEffect); + onEffectUpdated(effectInst); + } else { + activeEffects.insert( + std::unordered_map::value_type( + newEffect->getId(), newEffect)); + onEffectAdded(newEffect); + } } // 4J Added -void Mob::addEffectNoUpdate(MobEffectInstance *newEffect) -{ - if (!canBeAffected(newEffect)) - { - return; - } +void Mob::addEffectNoUpdate(MobEffectInstance* newEffect) { + if (!canBeAffected(newEffect)) { + return; + } - if (activeEffects.find(newEffect->getId()) != activeEffects.end() ) - { - // replace effect and update - MobEffectInstance *effectInst = activeEffects.find(newEffect->getId())->second; - effectInst->update(newEffect); - } - else - { - activeEffects.insert( std::unordered_map::value_type( newEffect->getId(), newEffect ) ); - } + if (activeEffects.find(newEffect->getId()) != activeEffects.end()) { + // replace effect and update + MobEffectInstance* effectInst = + activeEffects.find(newEffect->getId())->second; + effectInst->update(newEffect); + } else { + activeEffects.insert( + std::unordered_map::value_type( + newEffect->getId(), newEffect)); + } } -bool Mob::canBeAffected(MobEffectInstance *newEffect) -{ - if (getMobType() == UNDEAD) - { - int id = newEffect->getId(); - if (id == MobEffect::regeneration->id || id == MobEffect::poison->id) - { - return false; - } - } +bool Mob::canBeAffected(MobEffectInstance* newEffect) { + if (getMobType() == UNDEAD) { + int id = newEffect->getId(); + if (id == MobEffect::regeneration->id || id == MobEffect::poison->id) { + return false; + } + } - return true; + return true; } -bool Mob::isInvertedHealAndHarm() -{ - return getMobType() == UNDEAD; +bool Mob::isInvertedHealAndHarm() { return getMobType() == UNDEAD; } + +void Mob::removeEffectNoUpdate(int effectId) { + AUTO_VAR(it, activeEffects.find(effectId)); + if (it != activeEffects.end()) { + MobEffectInstance* effect = it->second; + if (effect != NULL) { + delete effect; + } + activeEffects.erase(it); + } } -void Mob::removeEffectNoUpdate(int effectId) -{ - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) - { - MobEffectInstance *effect = it->second; - if(effect != NULL) - { - delete effect; - } - activeEffects.erase(it); - } +void Mob::removeEffect(int effectId) { + AUTO_VAR(it, activeEffects.find(effectId)); + if (it != activeEffects.end()) { + MobEffectInstance* effect = it->second; + if (effect != NULL) { + onEffectRemoved(effect); + delete effect; + } + activeEffects.erase(it); + } } -void Mob::removeEffect(int effectId) -{ - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) - { - MobEffectInstance *effect = it->second; - if(effect != NULL) - { - onEffectRemoved(effect); - delete effect; - } - activeEffects.erase(it); - } +void Mob::onEffectAdded(MobEffectInstance* effect) { effectsDirty = true; } + +void Mob::onEffectUpdated(MobEffectInstance* effect) { effectsDirty = true; } + +void Mob::onEffectRemoved(MobEffectInstance* effect) { effectsDirty = true; } + +float Mob::getWalkingSpeedModifier() { + float speed = 1.0f; + if (hasEffect(MobEffect::movementSpeed)) { + speed *= + 1.0f + + .2f * (getEffect(MobEffect::movementSpeed)->getAmplifier() + 1); + } + if (hasEffect(MobEffect::movementSlowdown)) { + speed *= + 1.0f - + .15f * (getEffect(MobEffect::movementSlowdown)->getAmplifier() + 1); + } + return speed; } -void Mob::onEffectAdded(MobEffectInstance *effect) -{ - effectsDirty = true; +void Mob::teleportTo(double x, double y, double z) { + moveTo(x, y, z, yRot, xRot); } -void Mob::onEffectUpdated(MobEffectInstance *effect) -{ - effectsDirty = true; +bool Mob::isBaby() { return false; } + +MobType Mob::getMobType() { return UNDEFINED; } + +void Mob::breakItem(std::shared_ptr itemInstance) { + level->playSound(shared_from_this(), eSoundType_RANDOM_BREAK, 0.8f, + 0.8f + level->random->nextFloat() * 0.4f); + + for (int i = 0; i < 5; i++) { + Vec3* d = Vec3::newTemp((random->nextFloat() - 0.5) * 0.1, + Math::random() * 0.1 + 0.1, 0); + d->xRot(-xRot * PI / 180); + d->yRot(-yRot * PI / 180); + + Vec3* p = Vec3::newTemp((random->nextFloat() - 0.5) * 0.3, + -random->nextFloat() * 0.6 - 0.3, 0.6); + p->xRot(-xRot * PI / 180); + p->yRot(-yRot * PI / 180); + p = p->add(x, y + getHeadHeight(), z); + level->addParticle(PARTICLE_ICONCRACK(itemInstance->getItem()->id, 0), + p->x, p->y, p->z, d->x, d->y + 0.05, d->z); + } } -void Mob::onEffectRemoved(MobEffectInstance *effect) -{ - effectsDirty = true; +bool Mob::isInvulnerable() { + // 4J-JEV: I have no idea what was going on here (it gets changed in a later + // java version). + return invulnerableTime > 0; // invulnerableTime <= invulnerableTime / 2; } -float Mob::getWalkingSpeedModifier() -{ - float speed = 1.0f; - if (hasEffect(MobEffect::movementSpeed)) - { - speed *= 1.0f + .2f * (getEffect(MobEffect::movementSpeed)->getAmplifier() + 1); - } - if (hasEffect(MobEffect::movementSlowdown)) - { - speed *= 1.0f - .15f * (getEffect(MobEffect::movementSlowdown)->getAmplifier() + 1); - } - return speed; +void Mob::setLevel(Level* level) { + Entity::setLevel(level); + navigation->setLevel(level); + goalSelector.setLevel(level); + targetSelector.setLevel(level); } -void Mob::teleportTo(double x, double y, double z) -{ - moveTo(x, y, z, yRot, xRot); -} +void Mob::finalizeMobSpawn() {} -bool Mob::isBaby() -{ - return false; -} - -MobType Mob::getMobType() -{ - return UNDEFINED; -} - -void Mob::breakItem(std::shared_ptr itemInstance) -{ - level->playSound(shared_from_this(), eSoundType_RANDOM_BREAK, 0.8f, 0.8f + level->random->nextFloat() * 0.4f); - - for (int i = 0; i < 5; i++) - { - Vec3 *d = Vec3::newTemp((random->nextFloat() - 0.5) * 0.1, Math::random() * 0.1 + 0.1, 0); - d->xRot(-xRot * PI / 180); - d->yRot(-yRot * PI / 180); - - Vec3 *p = Vec3::newTemp((random->nextFloat() - 0.5) * 0.3, -random->nextFloat() * 0.6 - 0.3, 0.6); - p->xRot(-xRot * PI / 180); - p->yRot(-yRot * PI / 180); - p = p->add(x, y + getHeadHeight(), z); - level->addParticle(PARTICLE_ICONCRACK(itemInstance->getItem()->id,0), p->x, p->y, p->z, d->x, d->y + 0.05, d->z); - } -} - -bool Mob::isInvulnerable() -{ - // 4J-JEV: I have no idea what was going on here (it gets changed in a later java version). - return invulnerableTime > 0; // invulnerableTime <= invulnerableTime / 2; -} - -void Mob::setLevel(Level *level) -{ - Entity::setLevel(level); - navigation->setLevel(level); - goalSelector.setLevel(level); - targetSelector.setLevel(level); -} - -void Mob::finalizeMobSpawn() -{ - -} - -bool Mob::canBeControlledByRider() -{ - return false; -} +bool Mob::canBeControlledByRider() { return false; } diff --git a/Minecraft.World/Entities/Mob.h b/Minecraft.World/Entities/Mob.h index 432ede5d0..de1f12ef1 100644 --- a/Minecraft.World/Entities/Mob.h +++ b/Minecraft.World/Entities/Mob.h @@ -1,6 +1,5 @@ #pragma once - #include "Entity.h" #include "MobType.h" #include "../AI/Goals/GoalSelector.h" @@ -20,350 +19,358 @@ class Sensing; class Icon; class Pos; -class Mob : public Entity -{ - friend class MobSpawner; +class Mob : public Entity { + friend class MobSpawner; + protected: - // 4J - added for common ctor code - void _init(); -public: - Mob(Level* level); - virtual ~Mob(); - - // 4J-PB - added to replace (e instanceof Type), avoiding dynamic casts - eINSTANCEOF GetType() { return eTYPE_MOB;} - static Entity *create(Level *level) { return NULL; } + // 4J - added for common ctor code + void _init(); public: - static const int ATTACK_DURATION = 5; - static const int PLAYER_HURT_EXPERIENCE_TIME = 20 * 3; + Mob(Level* level); + virtual ~Mob(); -public: // 4J Stu - Made public - static const int DATA_EFFECT_COLOR_ID = 8; + // 4J-PB - added to replace (e instanceof Type), avoiding dynamic casts + eINSTANCEOF GetType() { return eTYPE_MOB; } + static Entity* create(Level* level) { return NULL; } + +public: + static const int ATTACK_DURATION = 5; + static const int PLAYER_HURT_EXPERIENCE_TIME = 20 * 3; + +public: // 4J Stu - Made public + static const int DATA_EFFECT_COLOR_ID = 8; private: - static const double MIN_MOVEMENT_DISTANCE; + static const double MIN_MOVEMENT_DISTANCE; public: - int invulnerableDuration; - float timeOffs; - float rotA; - float yBodyRot, yBodyRotO; - float yHeadRot, yHeadRotO; + int invulnerableDuration; + float timeOffs; + float rotA; + float yBodyRot, yBodyRotO; + float yHeadRot, yHeadRotO; protected: - float oRun, run; - float animStep, animStepO; - bool hasHair; - // std::wstring textureName; - int textureIdx; // 4J changed from std::wstring textureName - bool allowAlpha; - float rotOffs; - std::wstring modelName; - float bobStrength; - int deathScore; - float renderOffset; + float oRun, run; + float animStep, animStepO; + bool hasHair; + // std::wstring textureName; + int textureIdx; // 4J changed from std::wstring textureName + bool allowAlpha; + float rotOffs; + std::wstring modelName; + float bobStrength; + int deathScore; + float renderOffset; public: - float walkingSpeed; - float flyingSpeed; - float oAttackAnim, attackAnim; + float walkingSpeed; + float flyingSpeed; + float oAttackAnim, attackAnim; protected: - int health; + int health; public: - int lastHealth; + int lastHealth; protected: - int dmgSpill; + int dmgSpill; public: - int ambientSoundTime; - int hurtTime; - int hurtDuration; - float hurtDir; - int deathTime; - int attackTime; - float oTilt, tilt; + int ambientSoundTime; + int hurtTime; + int hurtDuration; + float hurtDir; + int deathTime; + int attackTime; + float oTilt, tilt; protected: - bool dead; - int xpReward; + bool dead; + int xpReward; public: - int modelNum; - float animSpeed; - float walkAnimSpeedO; - float walkAnimSpeed; - float walkAnimPos; + int modelNum; + float animSpeed; + float walkAnimSpeedO; + float walkAnimSpeed; + float walkAnimPos; protected: - std::shared_ptr lastHurtByPlayer; - int lastHurtByPlayerTime; + std::shared_ptr lastHurtByPlayer; + int lastHurtByPlayerTime; private: - std::shared_ptr lastHurtByMob; - int lastHurtByMobTime; - std::shared_ptr lastHurtMob; + std::shared_ptr lastHurtByMob; + int lastHurtByMobTime; + std::shared_ptr lastHurtMob; public: - int arrowCount; - int removeArrowTime; + int arrowCount; + int removeArrowTime; protected: - std::map activeEffects; + std::map activeEffects; private: - bool effectsDirty; - int effectColor; + bool effectsDirty; + int effectColor; - LookControl *lookControl; - MoveControl *moveControl; - JumpControl *jumpControl; - BodyControl *bodyControl; - PathNavigation *navigation; + LookControl* lookControl; + MoveControl* moveControl; + JumpControl* jumpControl; + BodyControl* bodyControl; + PathNavigation* navigation; protected: - GoalSelector goalSelector; - GoalSelector targetSelector; + GoalSelector goalSelector; + GoalSelector targetSelector; private: - std::shared_ptr target; - Sensing *sensing; - float speed; + std::shared_ptr target; + Sensing* sensing; + float speed; - Pos *restrictCenter; - float restrictRadius; + Pos* restrictCenter; + float restrictRadius; public: - virtual LookControl *getLookControl(); - virtual MoveControl *getMoveControl(); - virtual JumpControl *getJumpControl(); - virtual PathNavigation *getNavigation(); - virtual Sensing *getSensing(); - virtual Random *getRandom(); - virtual std::shared_ptr getLastHurtByMob(); - virtual std::shared_ptr getLastHurtMob(); - void setLastHurtMob(std::shared_ptr target); - virtual int getNoActionTime(); - float getYHeadRot(); - void setYHeadRot(float yHeadRot); - float getSpeed(); - void setSpeed(float speed); - virtual bool doHurtTarget(std::shared_ptr target); - std::shared_ptr getTarget(); - virtual void setTarget(std::shared_ptr target); - virtual bool canAttackType(eINSTANCEOF targetType); - virtual void ate(); + virtual LookControl* getLookControl(); + virtual MoveControl* getMoveControl(); + virtual JumpControl* getJumpControl(); + virtual PathNavigation* getNavigation(); + virtual Sensing* getSensing(); + virtual Random* getRandom(); + virtual std::shared_ptr getLastHurtByMob(); + virtual std::shared_ptr getLastHurtMob(); + void setLastHurtMob(std::shared_ptr target); + virtual int getNoActionTime(); + float getYHeadRot(); + void setYHeadRot(float yHeadRot); + float getSpeed(); + void setSpeed(float speed); + virtual bool doHurtTarget(std::shared_ptr target); + std::shared_ptr getTarget(); + virtual void setTarget(std::shared_ptr target); + virtual bool canAttackType(eINSTANCEOF targetType); + virtual void ate(); - bool isWithinRestriction(); - bool isWithinRestriction(int x, int y, int z); - void restrictTo(int x, int y, int z, int radius); - Pos *getRestrictCenter(); - float getRestrictRadius(); - void clearRestriction(); - bool hasRestriction(); + bool isWithinRestriction(); + bool isWithinRestriction(int x, int y, int z); + void restrictTo(int x, int y, int z, int radius); + Pos* getRestrictCenter(); + float getRestrictRadius(); + void clearRestriction(); + bool hasRestriction(); - virtual void setLastHurtByMob(std::shared_ptr hurtBy); + virtual void setLastHurtByMob(std::shared_ptr hurtBy); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - bool canSee(std::shared_ptr target); - virtual int getTexture(); // 4J - changed from std::wstring to int - virtual bool isPickable() ; - virtual bool isPushable(); - virtual float getHeadHeight(); - virtual int getAmbientSoundInterval(); - void playAmbientSound(); - virtual void baseTick(); + bool canSee(std::shared_ptr target); + virtual int getTexture(); // 4J - changed from std::wstring to int + virtual bool isPickable(); + virtual bool isPushable(); + virtual float getHeadHeight(); + virtual int getAmbientSoundInterval(); + void playAmbientSound(); + virtual void baseTick(); protected: - virtual void tickDeath(); - virtual int decreaseAirSupply(int currentSupply); - virtual int getExperienceReward(std::shared_ptr killedBy); - virtual bool isAlwaysExperienceDropper(); + virtual void tickDeath(); + virtual int decreaseAirSupply(int currentSupply); + virtual int getExperienceReward(std::shared_ptr killedBy); + virtual bool isAlwaysExperienceDropper(); public: - void spawnAnim(); - virtual void rideTick(); + void spawnAnim(); + virtual void rideTick(); protected: - int lSteps; - double lx, ly, lz, lyr, lxr; + int lSteps; + double lx, ly, lz, lyr, lxr; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); private: - float fallTime; + float fallTime; public: - void superTick(); - virtual void tick(); - virtual void heal(int heal); - virtual int getMaxHealth() = 0; - virtual int getHealth(); - virtual void setHealth(int health); + void superTick(); + virtual void tick(); + virtual void heal(int heal); + virtual int getMaxHealth() = 0; + virtual int getHealth(); + virtual void setHealth(int health); protected: - int lastHurt; + int lastHurt; public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); protected: - float getVoicePitch(); + float getVoicePitch(); public: - virtual void animateHurt(); + virtual void animateHurt(); - /** - * Fetches the mob's armor value, from 0 (no armor) to 20 (full armor) - * - * @return - */ - virtual int getArmorValue(); + /** + * Fetches the mob's armor value, from 0 (no armor) to 20 (full armor) + * + * @return + */ + virtual int getArmorValue(); protected: - virtual void hurtArmor(int damage); - virtual int getDamageAfterArmorAbsorb(DamageSource *damageSource, int damage); - virtual int getDamageAfterMagicAbsorb(DamageSource *damageSource, int damage); + virtual void hurtArmor(int damage); + virtual int getDamageAfterArmorAbsorb(DamageSource* damageSource, + int damage); + virtual int getDamageAfterMagicAbsorb(DamageSource* damageSource, + int damage); - virtual void actuallyHurt(DamageSource *source, int dmg); - virtual float getSoundVolume(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual void actuallyHurt(DamageSource* source, int dmg); + virtual float getSoundVolume(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - void knockback(std::shared_ptr source, int dmg, double xd, double zd); - virtual void die(DamageSource *source); + void knockback(std::shared_ptr source, int dmg, double xd, + double zd); + virtual void die(DamageSource* source); protected: - virtual void dropRareDeathLoot(int rareLootLevel); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); - virtual int getDeathLoot(); - virtual void causeFallDamage(float distance); + virtual void dropRareDeathLoot(int rareLootLevel); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getDeathLoot(); + virtual void causeFallDamage(float distance); public: - virtual void travel(float xa, float ya); - virtual bool onLadder(); - virtual bool isShootable(); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual bool isAlive(); - virtual bool isWaterMob(); - virtual int getLightColor(float a); // 4J - added + virtual void travel(float xa, float ya); + virtual bool onLadder(); + virtual bool isShootable(); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual bool isAlive(); + virtual bool isWaterMob(); + virtual int getLightColor(float a); // 4J - added protected: - int noActionTime; - float xxa, yya, yRotA; - bool jumping; - float defaultLookAngle; - float runSpeed; + int noActionTime; + float xxa, yya, yRotA; + bool jumping; + float defaultLookAngle; + float runSpeed; + protected: - int noJumpDelay; + int noJumpDelay; public: - virtual void setYya(float yya); - virtual void setJumping(bool jump); + virtual void setYya(float yya); + virtual void setJumping(bool jump); - virtual void aiStep(); + virtual void aiStep(); protected: - virtual bool useNewAi(); - virtual bool isEffectiveAI(); - virtual bool isImmobile(); + virtual bool useNewAi(); + virtual bool isEffectiveAI(); + virtual bool isImmobile(); public: - virtual bool isBlocking(); + virtual bool isBlocking(); protected: - virtual void jumpFromGround(); - virtual bool removeWhenFarAway(); + virtual void jumpFromGround(); + virtual bool removeWhenFarAway(); private: - std::shared_ptr lookingAt; + std::shared_ptr lookingAt; protected: - int lookTime; + int lookTime; - virtual void checkDespawn(); - virtual void newServerAiStep(); - virtual void serverAiMobStep(); - virtual void serverAiStep(); + virtual void checkDespawn(); + virtual void newServerAiStep(); + virtual void serverAiMobStep(); + virtual void serverAiStep(); public: - virtual int getMaxHeadXRot(); + virtual int getMaxHeadXRot(); protected: - void lookAt(std::shared_ptr e, float yMax, float xMax); - bool isLookingAtAnEntity(); - std::shared_ptr getLookingAt(); + void lookAt(std::shared_ptr e, float yMax, float xMax); + bool isLookingAtAnEntity(); + std::shared_ptr getLookingAt(); private: - float rotlerp(float a, float b, float max); + float rotlerp(float a, float b, float max); public: - virtual bool canSpawn(); + virtual bool canSpawn(); protected: - virtual void outOfWorld(); + virtual void outOfWorld(); public: - float getAttackAnim(float a); - virtual Vec3 *getPos(float a); - virtual Vec3 *getLookAngle(); - Vec3 *getViewVector(float a); - virtual float getSizeScale(); - virtual float getHeadSizeScale(); - HitResult *pick(double range, float a); - virtual int getMaxSpawnClusterSize(); - virtual std::shared_ptr getCarriedItem(); - virtual std::shared_ptr getArmor(int pos); - virtual void handleEntityEvent(uint8_t id); - virtual bool isSleeping(); - virtual Icon *getItemInHandIcon(std::shared_ptr item, int layer); - virtual bool shouldRender(Vec3 *c); + float getAttackAnim(float a); + virtual Vec3* getPos(float a); + virtual Vec3* getLookAngle(); + Vec3* getViewVector(float a); + virtual float getSizeScale(); + virtual float getHeadSizeScale(); + HitResult* pick(double range, float a); + virtual int getMaxSpawnClusterSize(); + virtual std::shared_ptr getCarriedItem(); + virtual std::shared_ptr getArmor(int pos); + virtual void handleEntityEvent(uint8_t id); + virtual bool isSleeping(); + virtual Icon* getItemInHandIcon(std::shared_ptr item, + int layer); + virtual bool shouldRender(Vec3* c); protected: - void tickEffects(); + void tickEffects(); public: - void removeAllEffects(); - std::vector *getActiveEffects(); - bool hasEffect(int id); - bool hasEffect(MobEffect *effect); - MobEffectInstance *getEffect(MobEffect *effect); - void addEffect(MobEffectInstance *newEffect); - void addEffectNoUpdate(MobEffectInstance *newEffect); // 4J Added - virtual bool canBeAffected(MobEffectInstance *newEffect); - virtual bool isInvertedHealAndHarm(); - void removeEffectNoUpdate(int effectId); - void removeEffect(int effectId); + void removeAllEffects(); + std::vector* getActiveEffects(); + bool hasEffect(int id); + bool hasEffect(MobEffect* effect); + MobEffectInstance* getEffect(MobEffect* effect); + void addEffect(MobEffectInstance* newEffect); + void addEffectNoUpdate(MobEffectInstance* newEffect); // 4J Added + virtual bool canBeAffected(MobEffectInstance* newEffect); + virtual bool isInvertedHealAndHarm(); + void removeEffectNoUpdate(int effectId); + void removeEffect(int effectId); protected: - virtual void onEffectAdded(MobEffectInstance *effect); - virtual void onEffectUpdated(MobEffectInstance *effect); - virtual void onEffectRemoved(MobEffectInstance *effect); + virtual void onEffectAdded(MobEffectInstance* effect); + virtual void onEffectUpdated(MobEffectInstance* effect); + virtual void onEffectRemoved(MobEffectInstance* effect); public: - virtual float getWalkingSpeedModifier(); + virtual float getWalkingSpeedModifier(); - // 4J-Pb added (from 1.2.3) - virtual void teleportTo(double x, double y, double z); - virtual bool isBaby(); - virtual MobType getMobType(); - virtual void breakItem(std::shared_ptr itemInstance); + // 4J-Pb added (from 1.2.3) + virtual void teleportTo(double x, double y, double z); + virtual bool isBaby(); + virtual MobType getMobType(); + virtual void breakItem(std::shared_ptr itemInstance); - virtual bool isInvulnerable(); + virtual bool isInvulnerable(); - virtual void finalizeMobSpawn(); - virtual bool canBeControlledByRider(); + virtual void finalizeMobSpawn(); + virtual bool canBeControlledByRider(); - // 4J Added override to update ai elements when loading entity from schematics - virtual void setLevel(Level *level); + // 4J Added override to update ai elements when loading entity from + // schematics + virtual void setLevel(Level* level); }; diff --git a/Minecraft.World/Entities/MobCategory.cpp b/Minecraft.World/Entities/MobCategory.cpp index 8c41b7610..ac39cceb7 100644 --- a/Minecraft.World/Entities/MobCategory.cpp +++ b/Minecraft.World/Entities/MobCategory.cpp @@ -5,67 +5,67 @@ #include "../Blocks/Material.h" #include "MobCategory.h" -MobCategory *MobCategory::monster = NULL; -MobCategory *MobCategory::creature = NULL; -MobCategory *MobCategory::waterCreature = NULL; +MobCategory* MobCategory::monster = NULL; +MobCategory* MobCategory::creature = NULL; +MobCategory* MobCategory::waterCreature = NULL; // 4J - added these extra categories -MobCategory *MobCategory::creature_wolf = NULL; -MobCategory *MobCategory::creature_chicken = NULL; -MobCategory *MobCategory::creature_mushroomcow = NULL; +MobCategory* MobCategory::creature_wolf = NULL; +MobCategory* MobCategory::creature_chicken = NULL; +MobCategory* MobCategory::creature_mushroomcow = NULL; MobCategoryArray MobCategory::values = MobCategoryArray(6); -void MobCategory::staticCtor() -{ - // 4J - adjusted the max levels here for the xbox version, which now represent the max levels in the whole world - monster = new MobCategory(70, Material::air, false, eTYPE_MONSTER, false, CONSOLE_MONSTERS_HARD_LIMIT); - creature = new MobCategory(10, Material::air, true, eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false, CONSOLE_ANIMALS_HARD_LIMIT); - waterCreature = new MobCategory(5, Material::water, true, eTYPE_WATERANIMAL, false, CONSOLE_SQUID_HARD_LIMIT); +void MobCategory::staticCtor() { + // 4J - adjusted the max levels here for the xbox version, which now + // represent the max levels in the whole world + monster = new MobCategory(70, Material::air, false, eTYPE_MONSTER, false, + CONSOLE_MONSTERS_HARD_LIMIT); + creature = new MobCategory(10, Material::air, true, + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false, + CONSOLE_ANIMALS_HARD_LIMIT); + waterCreature = new MobCategory(5, Material::water, true, eTYPE_WATERANIMAL, + false, CONSOLE_SQUID_HARD_LIMIT); - values[0] = monster; - values[1] = creature; - values[2] = waterCreature; - // 4J - added 2 new categories to give us better control over spawning wolves & chickens - creature_wolf = new MobCategory(3, Material::air, true, eTYPE_WOLF, true, MAX_XBOX_WOLVES); - creature_chicken = new MobCategory( 2, Material::air, true, eTYPE_CHICKEN, true, MAX_XBOX_CHICKENS); - creature_mushroomcow = new MobCategory(2, Material::air, true, eTYPE_MUSHROOMCOW, true, MAX_XBOX_MUSHROOMCOWS); - values[3] = creature_wolf; - values[4] = creature_chicken; - values[5] = creature_mushroomcow; + values[0] = monster; + values[1] = creature; + values[2] = waterCreature; + // 4J - added 2 new categories to give us better control over spawning + // wolves & chickens + creature_wolf = new MobCategory(3, Material::air, true, eTYPE_WOLF, true, + MAX_XBOX_WOLVES); + creature_chicken = new MobCategory(2, Material::air, true, eTYPE_CHICKEN, + true, MAX_XBOX_CHICKENS); + creature_mushroomcow = new MobCategory( + 2, Material::air, true, eTYPE_MUSHROOMCOW, true, MAX_XBOX_MUSHROOMCOWS); + values[3] = creature_wolf; + values[4] = creature_chicken; + values[5] = creature_mushroomcow; } -MobCategory::MobCategory(int maxVar, Material *spawnPositionMaterial, bool isFriendly, eINSTANCEOF eBase, bool isSingleType, int maxPerLevel) - : m_max(maxVar), spawnPositionMaterial(spawnPositionMaterial), m_isFriendly(isFriendly), m_eBase(eBase), m_isSingleType(isSingleType), m_maxPerLevel(maxPerLevel) -{ -} +MobCategory::MobCategory(int maxVar, Material* spawnPositionMaterial, + bool isFriendly, eINSTANCEOF eBase, bool isSingleType, + int maxPerLevel) + : m_max(maxVar), + spawnPositionMaterial(spawnPositionMaterial), + m_isFriendly(isFriendly), + m_eBase(eBase), + m_isSingleType(isSingleType), + m_maxPerLevel(maxPerLevel) {} // 4J - added -const eINSTANCEOF MobCategory::getEnumBaseClass() +const eINSTANCEOF MobCategory::getEnumBaseClass() { return m_eBase; } + +int MobCategory::getMaxInstancesPerChunk() { return m_max; } + +int MobCategory::getMaxInstancesPerLevel() // 4J added { - return m_eBase; + return m_maxPerLevel; } -int MobCategory::getMaxInstancesPerChunk() -{ - return m_max; +Material* MobCategory::getSpawnPositionMaterial() { + return (Material*)spawnPositionMaterial; } -int MobCategory::getMaxInstancesPerLevel() // 4J added -{ - return m_maxPerLevel; -} +bool MobCategory::isFriendly() { return m_isFriendly; } -Material *MobCategory::getSpawnPositionMaterial() -{ - return (Material *) spawnPositionMaterial; -} - -bool MobCategory::isFriendly() -{ - return m_isFriendly; -} - -bool MobCategory::isSingleType() -{ - return m_isSingleType; -} +bool MobCategory::isSingleType() { return m_isSingleType; } diff --git a/Minecraft.World/Entities/MobCategory.h b/Minecraft.World/Entities/MobCategory.h index 8649970d0..5aadbb954 100644 --- a/Minecraft.World/Entities/MobCategory.h +++ b/Minecraft.World/Entities/MobCategory.h @@ -1,82 +1,111 @@ #pragma once - class Material; -class MobCategory -{ +class MobCategory { public: - // 4J - putting constants for xbox spawning in one place to tidy things up a bit - all numbers are per level - static const int CONSOLE_MONSTERS_HARD_LIMIT = 50; // Max number of enemies (skeleton, zombie, creeper etc) that the mob spawner will produce - static const int CONSOLE_ANIMALS_HARD_LIMIT = 50; // Max number of animals (cows, sheep, pigs) that the mob spawner will produce + // 4J - putting constants for xbox spawning in one place to tidy things up a + // bit - all numbers are per level + static const int CONSOLE_MONSTERS_HARD_LIMIT = + 50; // Max number of enemies (skeleton, zombie, creeper etc) that the + // mob spawner will produce + static const int CONSOLE_ANIMALS_HARD_LIMIT = + 50; // Max number of animals (cows, sheep, pigs) that the mob spawner + // will produce - static const int MAX_XBOX_CHICKENS = 8; // Max number of chickens that the mob spawner will produce - static const int MAX_XBOX_WOLVES = 8; // Max number of wolves that the mob spawner will produce - static const int MAX_XBOX_MUSHROOMCOWS = 2; // Max number of mushroom cows that the mob spawner will produce - static const int MAX_XBOX_SNOWMEN = 16; // Max number of snow golems that can be created by placing blocks - 4J-PB increased limit due to player requests - static const int MAX_XBOX_IRONGOLEM = 16; // Max number of iron golems that can be created by placing blocks - 4J-PB increased limit due to player requests - static const int CONSOLE_SQUID_HARD_LIMIT = 5; - - static const int MAX_XBOX_ANIMALS_WITH_BREEDING = CONSOLE_ANIMALS_HARD_LIMIT + 20; // Max number of animals that we can produce (in total), when breeding - static const int MAX_XBOX_CHICKENS_WITH_BREEDING = MAX_XBOX_CHICKENS + 8; // Max number of chickens that we can produce (in total), when breeding/hatching - static const int MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING = MAX_XBOX_MUSHROOMCOWS + 20; // Max number of mushroom cows that we can produce (in total), when breeding - static const int MAX_XBOX_WOLVES_WITH_BREEDING = MAX_XBOX_WOLVES + 8; // Max number of wolves that we can produce (in total), when breeding - static const int MAX_VILLAGERS_WITH_BREEDING = 35; + static const int MAX_XBOX_CHICKENS = + 8; // Max number of chickens that the mob spawner will produce + static const int MAX_XBOX_WOLVES = + 8; // Max number of wolves that the mob spawner will produce + static const int MAX_XBOX_MUSHROOMCOWS = + 2; // Max number of mushroom cows that the mob spawner will produce + static const int MAX_XBOX_SNOWMEN = + 16; // Max number of snow golems that can be created by placing blocks + // - 4J-PB increased limit due to player requests + static const int MAX_XBOX_IRONGOLEM = + 16; // Max number of iron golems that can be created by placing blocks + // - 4J-PB increased limit due to player requests + static const int CONSOLE_SQUID_HARD_LIMIT = 5; - static const int MAX_XBOX_ANIMALS_WITH_SPAWN_EGG = MAX_XBOX_ANIMALS_WITH_BREEDING + 20; - static const int MAX_XBOX_CHICKENS_WITH_SPAWN_EGG = MAX_XBOX_CHICKENS_WITH_BREEDING + 10; - static const int MAX_XBOX_WOLVES_WITH_SPAWN_EGG = MAX_XBOX_WOLVES_WITH_BREEDING + 10; - static const int MAX_XBOX_MONSTERS_WITH_SPAWN_EGG = CONSOLE_MONSTERS_HARD_LIMIT + 20; - static const int MAX_XBOX_VILLAGERS_WITH_SPAWN_EGG = MAX_VILLAGERS_WITH_BREEDING + 15; // 4J-PB - increased this limit due to player requests - static const int MAX_XBOX_MUSHROOMCOWS_WITH_SPAWN_EGG = MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING + 8; - static const int MAX_XBOX_SQUIDS_WITH_SPAWN_EGG = CONSOLE_SQUID_HARD_LIMIT + 8; + static const int MAX_XBOX_ANIMALS_WITH_BREEDING = + CONSOLE_ANIMALS_HARD_LIMIT + 20; // Max number of animals that we can + // produce (in total), when breeding + static const int MAX_XBOX_CHICKENS_WITH_BREEDING = + MAX_XBOX_CHICKENS + 8; // Max number of chickens that we can produce + // (in total), when breeding/hatching + static const int MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING = + MAX_XBOX_MUSHROOMCOWS + 20; // Max number of mushroom cows that we can + // produce (in total), when breeding + static const int MAX_XBOX_WOLVES_WITH_BREEDING = + MAX_XBOX_WOLVES + 8; // Max number of wolves that we can produce (in + // total), when breeding + static const int MAX_VILLAGERS_WITH_BREEDING = 35; - /* - Maximum animals = 50 + 20 + 20 = 90 - Maximum monsters = 50 + 20 = 70 - Maximum chickens = 8 + 8 + 10 = 26 - Maximum wolves = 8 + 8 + 10 = 26 - Maximum mooshrooms = 2 + 20 + 8 = 30 - Maximum snowmen = 16 - Maximum iron golem = 16 - Maximum squid = 5 + 8 = 13 - Maximum villagers = 35 + 15 = 50 + static const int MAX_XBOX_ANIMALS_WITH_SPAWN_EGG = + MAX_XBOX_ANIMALS_WITH_BREEDING + 20; + static const int MAX_XBOX_CHICKENS_WITH_SPAWN_EGG = + MAX_XBOX_CHICKENS_WITH_BREEDING + 10; + static const int MAX_XBOX_WOLVES_WITH_SPAWN_EGG = + MAX_XBOX_WOLVES_WITH_BREEDING + 10; + static const int MAX_XBOX_MONSTERS_WITH_SPAWN_EGG = + CONSOLE_MONSTERS_HARD_LIMIT + 20; + static const int MAX_XBOX_VILLAGERS_WITH_SPAWN_EGG = + MAX_VILLAGERS_WITH_BREEDING + + 15; // 4J-PB - increased this limit due to player requests + static const int MAX_XBOX_MUSHROOMCOWS_WITH_SPAWN_EGG = + MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING + 8; + static const int MAX_XBOX_SQUIDS_WITH_SPAWN_EGG = + CONSOLE_SQUID_HARD_LIMIT + 8; - Maximum natural = 50 + 50 + 8 + 8 + 2 + 5 + 35 = 158 - Total maxium = 90 + 70 + 26 + 26 + 30 + 16 + 16 + 13 + 50 = 337 - */ + /* + Maximum animals = 50 + 20 + 20 = 90 + Maximum monsters = 50 + 20 = 70 + Maximum chickens = 8 + 8 + 10 = 26 + Maximum wolves = 8 + 8 + 10 = 26 + Maximum mooshrooms = 2 + 20 + 8 = 30 + Maximum snowmen = 16 + Maximum iron golem = 16 + Maximum squid = 5 + 8 = 13 + Maximum villagers = 35 + 15 = 50 - static MobCategory *monster; - static MobCategory *creature; - static MobCategory *waterCreature; - // 4J added extra categories, to break these out of general creatures & give us more control of levels - static MobCategory *creature_wolf; - static MobCategory *creature_chicken; - static MobCategory *creature_mushroomcow; + Maximum natural = 50 + 50 + 8 + 8 + 2 + 5 + 35 = 158 + Total maxium = 90 + 70 + 26 + 26 + 30 + 16 + 16 + 13 + 50 = 337 + */ - // 4J Stu Sometimes we want to access the values by name, other times iterate over all values - // Added these arrays so we can static initialise a collection which we can iterate over - static MobCategoryArray values; + static MobCategory* monster; + static MobCategory* creature; + static MobCategory* waterCreature; + // 4J added extra categories, to break these out of general creatures & give + // us more control of levels + static MobCategory* creature_wolf; + static MobCategory* creature_chicken; + static MobCategory* creature_mushroomcow; + // 4J Stu Sometimes we want to access the values by name, other times + // iterate over all values Added these arrays so we can static initialise a + // collection which we can iterate over + static MobCategoryArray values; private: - const int m_max; - const int m_maxPerLevel; - const Material *spawnPositionMaterial; - const bool m_isFriendly; - const bool m_isSingleType; // 4J Added - const eINSTANCEOF m_eBase; // 4J added + const int m_max; + const int m_maxPerLevel; + const Material* spawnPositionMaterial; + const bool m_isFriendly; + const bool m_isSingleType; // 4J Added + const eINSTANCEOF m_eBase; // 4J added - MobCategory(int maxVar, Material *spawnPositionMaterial, bool isFriendly, eINSTANCEOF eBase, bool isSingleType, int maxPerLevel); + MobCategory(int maxVar, Material* spawnPositionMaterial, bool isFriendly, + eINSTANCEOF eBase, bool isSingleType, int maxPerLevel); public: - const std::type_info getBaseClass(); - const eINSTANCEOF getEnumBaseClass(); // 4J added - int getMaxInstancesPerChunk(); - int getMaxInstancesPerLevel(); // 4J added - Material *getSpawnPositionMaterial(); - bool isFriendly(); - bool isSingleType(); + const std::type_info getBaseClass(); + const eINSTANCEOF getEnumBaseClass(); // 4J added + int getMaxInstancesPerChunk(); + int getMaxInstancesPerLevel(); // 4J added + Material* getSpawnPositionMaterial(); + bool isFriendly(); + bool isSingleType(); + public: - static void staticCtor(); + static void staticCtor(); }; diff --git a/Minecraft.World/Entities/MobEffect.cpp b/Minecraft.World/Entities/MobEffect.cpp index 38eacbc6e..568ce679a 100644 --- a/Minecraft.World/Entities/MobEffect.cpp +++ b/Minecraft.World/Entities/MobEffect.cpp @@ -5,266 +5,289 @@ #include "../Headers/net.minecraft.world.effect.h" #include "../Util/SharedConstants.h" -MobEffect *MobEffect::effects[NUM_EFFECTS]; +MobEffect* MobEffect::effects[NUM_EFFECTS]; -MobEffect *MobEffect::voidEffect = NULL; -MobEffect *MobEffect::movementSpeed = (new MobEffect(1, false, eMinecraftColour_Effect_MovementSpeed)) ->setDescriptionId(IDS_POTION_MOVESPEED) ->setPostfixDescriptionId(IDS_POTION_MOVESPEED_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Speed); //setIcon(0, 0); -MobEffect *MobEffect::movementSlowdown = (new MobEffect(2, true, eMinecraftColour_Effect_MovementSlowDown)) ->setDescriptionId(IDS_POTION_MOVESLOWDOWN) ->setPostfixDescriptionId(IDS_POTION_MOVESLOWDOWN_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Slowness); //->setIcon(1, 0); -MobEffect *MobEffect::digSpeed = (new MobEffect(3, false, eMinecraftColour_Effect_DigSpeed)) ->setDescriptionId(IDS_POTION_DIGSPEED) ->setPostfixDescriptionId(IDS_POTION_DIGSPEED_POSTFIX)->setDurationModifier(1.5)->setIcon(MobEffect::e_MobEffectIcon_Haste); //->setIcon(2, 0); -MobEffect *MobEffect::digSlowdown = (new MobEffect(4, true, eMinecraftColour_Effect_DigSlowdown)) ->setDescriptionId(IDS_POTION_DIGSLOWDOWN) ->setPostfixDescriptionId(IDS_POTION_DIGSLOWDOWN_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_MiningFatigue); //->setIcon(3, 0); -MobEffect *MobEffect::damageBoost = (new MobEffect(5, false, eMinecraftColour_Effect_DamageBoost)) ->setDescriptionId(IDS_POTION_DAMAGEBOOST) ->setPostfixDescriptionId(IDS_POTION_DAMAGEBOOST_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Strength); //->setIcon(4, 0); -MobEffect *MobEffect::heal = (new InstantenousMobEffect(6, false, eMinecraftColour_Effect_Heal)) ->setDescriptionId(IDS_POTION_HEAL) ->setPostfixDescriptionId(IDS_POTION_HEAL_POSTFIX); -MobEffect *MobEffect::harm = (new InstantenousMobEffect(7, true, eMinecraftColour_Effect_Harm)) ->setDescriptionId(IDS_POTION_HARM) ->setPostfixDescriptionId(IDS_POTION_HARM_POSTFIX); -MobEffect *MobEffect::jump = (new MobEffect(8, false, eMinecraftColour_Effect_Jump)) ->setDescriptionId(IDS_POTION_JUMP) ->setPostfixDescriptionId(IDS_POTION_JUMP_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_JumpBoost); //->setIcon(2, 1); -MobEffect *MobEffect::confusion = (new MobEffect(9, true, eMinecraftColour_Effect_Confusion)) ->setDescriptionId(IDS_POTION_CONFUSION) ->setPostfixDescriptionId(IDS_POTION_CONFUSION_POSTFIX)->setDurationModifier(.25)->setIcon(MobEffect::e_MobEffectIcon_Nausea); //->setIcon(3, 1); -MobEffect *MobEffect::regeneration = (new MobEffect(10, false, eMinecraftColour_Effect_Regeneration)) ->setDescriptionId(IDS_POTION_REGENERATION) ->setPostfixDescriptionId(IDS_POTION_REGENERATION_POSTFIX)->setDurationModifier(.25)->setIcon(MobEffect::e_MobEffectIcon_Regeneration); //->setIcon(7, 0); -MobEffect *MobEffect::damageResistance = (new MobEffect(11, false, eMinecraftColour_Effect_DamageResistance))->setDescriptionId(IDS_POTION_RESISTANCE) ->setPostfixDescriptionId(IDS_POTION_RESISTANCE_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Resistance); //->setIcon(6, 1); -MobEffect *MobEffect::fireResistance = (new MobEffect(12, false, eMinecraftColour_Effect_FireResistance)) ->setDescriptionId(IDS_POTION_FIRERESISTANCE) ->setPostfixDescriptionId(IDS_POTION_FIRERESISTANCE_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_FireResistance); //->setIcon(7, 1); -MobEffect *MobEffect::waterBreathing = (new MobEffect(13, false, eMinecraftColour_Effect_WaterBreathing)) ->setDescriptionId(IDS_POTION_WATERBREATHING) ->setPostfixDescriptionId(IDS_POTION_WATERBREATHING_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_WaterBreathing); //->setIcon(0, 2); -MobEffect *MobEffect::invisibility = (new MobEffect(14, false, eMinecraftColour_Effect_Invisiblity)) ->setDescriptionId(IDS_POTION_INVISIBILITY) ->setPostfixDescriptionId(IDS_POTION_INVISIBILITY_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Invisiblity); //->setIcon(0, 1); -MobEffect *MobEffect::blindness = (new MobEffect(15, true, eMinecraftColour_Effect_Blindness)) ->setDescriptionId(IDS_POTION_BLINDNESS) ->setPostfixDescriptionId(IDS_POTION_BLINDNESS_POSTFIX)->setDurationModifier(.25)->setIcon(MobEffect::e_MobEffectIcon_Blindness); //->setIcon(5, 1); -MobEffect *MobEffect::nightVision = (new MobEffect(16, false, eMinecraftColour_Effect_NightVision)) ->setDescriptionId(IDS_POTION_NIGHTVISION) ->setPostfixDescriptionId(IDS_POTION_NIGHTVISION_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_NightVision); //->setIcon(4, 1); -MobEffect *MobEffect::hunger = (new MobEffect(17, true, eMinecraftColour_Effect_Hunger)) ->setDescriptionId(IDS_POTION_HUNGER) ->setPostfixDescriptionId(IDS_POTION_HUNGER_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Hunger); //->setIcon(1, 1); -MobEffect *MobEffect::weakness = (new MobEffect(18, true, eMinecraftColour_Effect_Weakness)) ->setDescriptionId(IDS_POTION_WEAKNESS) ->setPostfixDescriptionId(IDS_POTION_WEAKNESS_POSTFIX)->setIcon(MobEffect::e_MobEffectIcon_Weakness); //->setIcon(5, 0); -MobEffect *MobEffect::poison = (new MobEffect(19, true, eMinecraftColour_Effect_Poison)) ->setDescriptionId(IDS_POTION_POISON) ->setPostfixDescriptionId(IDS_POTION_POISON_POSTFIX)->setDurationModifier(.25)->setIcon(MobEffect::e_MobEffectIcon_Poison); //->setIcon(6, 0); -MobEffect *MobEffect::reserved_20 = NULL; -MobEffect *MobEffect::reserved_21 = NULL; -MobEffect *MobEffect::reserved_22 = NULL; -MobEffect *MobEffect::reserved_23 = NULL; -MobEffect *MobEffect::reserved_24 = NULL; -MobEffect *MobEffect::reserved_25 = NULL; -MobEffect *MobEffect::reserved_26 = NULL; -MobEffect *MobEffect::reserved_27 = NULL; -MobEffect *MobEffect::reserved_28 = NULL; -MobEffect *MobEffect::reserved_29 = NULL; -MobEffect *MobEffect::reserved_30 = NULL; -MobEffect *MobEffect::reserved_31 = NULL; +MobEffect* MobEffect::voidEffect = NULL; +MobEffect* MobEffect::movementSpeed = + (new MobEffect(1, false, eMinecraftColour_Effect_MovementSpeed)) + ->setDescriptionId(IDS_POTION_MOVESPEED) + ->setPostfixDescriptionId(IDS_POTION_MOVESPEED_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Speed); // setIcon(0, 0); +MobEffect* MobEffect::movementSlowdown = + (new MobEffect(2, true, eMinecraftColour_Effect_MovementSlowDown)) + ->setDescriptionId(IDS_POTION_MOVESLOWDOWN) + ->setPostfixDescriptionId(IDS_POTION_MOVESLOWDOWN_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Slowness); //->setIcon(1, 0); +MobEffect* MobEffect::digSpeed = + (new MobEffect(3, false, eMinecraftColour_Effect_DigSpeed)) + ->setDescriptionId(IDS_POTION_DIGSPEED) + ->setPostfixDescriptionId(IDS_POTION_DIGSPEED_POSTFIX) + ->setDurationModifier(1.5) + ->setIcon(MobEffect::e_MobEffectIcon_Haste); //->setIcon(2, 0); +MobEffect* MobEffect::digSlowdown = + (new MobEffect(4, true, eMinecraftColour_Effect_DigSlowdown)) + ->setDescriptionId(IDS_POTION_DIGSLOWDOWN) + ->setPostfixDescriptionId(IDS_POTION_DIGSLOWDOWN_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_MiningFatigue); //->setIcon(3, 0); +MobEffect* MobEffect::damageBoost = + (new MobEffect(5, false, eMinecraftColour_Effect_DamageBoost)) + ->setDescriptionId(IDS_POTION_DAMAGEBOOST) + ->setPostfixDescriptionId(IDS_POTION_DAMAGEBOOST_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Strength); //->setIcon(4, 0); +MobEffect* MobEffect::heal = + (new InstantenousMobEffect(6, false, eMinecraftColour_Effect_Heal)) + ->setDescriptionId(IDS_POTION_HEAL) + ->setPostfixDescriptionId(IDS_POTION_HEAL_POSTFIX); +MobEffect* MobEffect::harm = + (new InstantenousMobEffect(7, true, eMinecraftColour_Effect_Harm)) + ->setDescriptionId(IDS_POTION_HARM) + ->setPostfixDescriptionId(IDS_POTION_HARM_POSTFIX); +MobEffect* MobEffect::jump = + (new MobEffect(8, false, eMinecraftColour_Effect_Jump)) + ->setDescriptionId(IDS_POTION_JUMP) + ->setPostfixDescriptionId(IDS_POTION_JUMP_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_JumpBoost); //->setIcon(2, 1); +MobEffect* MobEffect::confusion = + (new MobEffect(9, true, eMinecraftColour_Effect_Confusion)) + ->setDescriptionId(IDS_POTION_CONFUSION) + ->setPostfixDescriptionId(IDS_POTION_CONFUSION_POSTFIX) + ->setDurationModifier(.25) + ->setIcon(MobEffect::e_MobEffectIcon_Nausea); //->setIcon(3, 1); +MobEffect* MobEffect::regeneration = + (new MobEffect(10, false, eMinecraftColour_Effect_Regeneration)) + ->setDescriptionId(IDS_POTION_REGENERATION) + ->setPostfixDescriptionId(IDS_POTION_REGENERATION_POSTFIX) + ->setDurationModifier(.25) + ->setIcon(MobEffect::e_MobEffectIcon_Regeneration); //->setIcon(7, 0); +MobEffect* MobEffect::damageResistance = + (new MobEffect(11, false, eMinecraftColour_Effect_DamageResistance)) + ->setDescriptionId(IDS_POTION_RESISTANCE) + ->setPostfixDescriptionId(IDS_POTION_RESISTANCE_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Resistance); //->setIcon(6, 1); +MobEffect* MobEffect::fireResistance = + (new MobEffect(12, false, eMinecraftColour_Effect_FireResistance)) + ->setDescriptionId(IDS_POTION_FIRERESISTANCE) + ->setPostfixDescriptionId(IDS_POTION_FIRERESISTANCE_POSTFIX) + ->setIcon( + MobEffect::e_MobEffectIcon_FireResistance); //->setIcon(7, 1); +MobEffect* MobEffect::waterBreathing = + (new MobEffect(13, false, eMinecraftColour_Effect_WaterBreathing)) + ->setDescriptionId(IDS_POTION_WATERBREATHING) + ->setPostfixDescriptionId(IDS_POTION_WATERBREATHING_POSTFIX) + ->setIcon( + MobEffect::e_MobEffectIcon_WaterBreathing); //->setIcon(0, 2); +MobEffect* MobEffect::invisibility = + (new MobEffect(14, false, eMinecraftColour_Effect_Invisiblity)) + ->setDescriptionId(IDS_POTION_INVISIBILITY) + ->setPostfixDescriptionId(IDS_POTION_INVISIBILITY_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Invisiblity); //->setIcon(0, 1); +MobEffect* MobEffect::blindness = + (new MobEffect(15, true, eMinecraftColour_Effect_Blindness)) + ->setDescriptionId(IDS_POTION_BLINDNESS) + ->setPostfixDescriptionId(IDS_POTION_BLINDNESS_POSTFIX) + ->setDurationModifier(.25) + ->setIcon(MobEffect::e_MobEffectIcon_Blindness); //->setIcon(5, 1); +MobEffect* MobEffect::nightVision = + (new MobEffect(16, false, eMinecraftColour_Effect_NightVision)) + ->setDescriptionId(IDS_POTION_NIGHTVISION) + ->setPostfixDescriptionId(IDS_POTION_NIGHTVISION_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_NightVision); //->setIcon(4, 1); +MobEffect* MobEffect::hunger = + (new MobEffect(17, true, eMinecraftColour_Effect_Hunger)) + ->setDescriptionId(IDS_POTION_HUNGER) + ->setPostfixDescriptionId(IDS_POTION_HUNGER_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Hunger); //->setIcon(1, 1); +MobEffect* MobEffect::weakness = + (new MobEffect(18, true, eMinecraftColour_Effect_Weakness)) + ->setDescriptionId(IDS_POTION_WEAKNESS) + ->setPostfixDescriptionId(IDS_POTION_WEAKNESS_POSTFIX) + ->setIcon(MobEffect::e_MobEffectIcon_Weakness); //->setIcon(5, 0); +MobEffect* MobEffect::poison = + (new MobEffect(19, true, eMinecraftColour_Effect_Poison)) + ->setDescriptionId(IDS_POTION_POISON) + ->setPostfixDescriptionId(IDS_POTION_POISON_POSTFIX) + ->setDurationModifier(.25) + ->setIcon(MobEffect::e_MobEffectIcon_Poison); //->setIcon(6, 0); +MobEffect* MobEffect::reserved_20 = NULL; +MobEffect* MobEffect::reserved_21 = NULL; +MobEffect* MobEffect::reserved_22 = NULL; +MobEffect* MobEffect::reserved_23 = NULL; +MobEffect* MobEffect::reserved_24 = NULL; +MobEffect* MobEffect::reserved_25 = NULL; +MobEffect* MobEffect::reserved_26 = NULL; +MobEffect* MobEffect::reserved_27 = NULL; +MobEffect* MobEffect::reserved_28 = NULL; +MobEffect* MobEffect::reserved_29 = NULL; +MobEffect* MobEffect::reserved_30 = NULL; +MobEffect* MobEffect::reserved_31 = NULL; +MobEffect::MobEffect(int id, bool isHarmful, eMinecraftColour color) + : id(id), _isHarmful(isHarmful), color(color) { + descriptionId = -1; + m_postfixDescriptionId = -1; + icon = e_MobEffectIcon_None; + _isDisabled = false; -MobEffect::MobEffect(int id, bool isHarmful, eMinecraftColour color) : id(id), _isHarmful(isHarmful), color(color) -{ - descriptionId = -1; - m_postfixDescriptionId = -1; - icon = e_MobEffectIcon_None; - _isDisabled = false; + effects[id] = this; - effects[id] = this; - - if (isHarmful) - { - durationModifier = .5; - } - else - { - durationModifier = 1.0; - } + if (isHarmful) { + durationModifier = .5; + } else { + durationModifier = 1.0; + } } // 4J Removed as using different value for icon -//MobEffect *MobEffect::setIcon(int xPos, int yPos) +// MobEffect *MobEffect::setIcon(int xPos, int yPos) //{ // icon = xPos + yPos * 8; // return this; //} -MobEffect *MobEffect::setIcon(EMobEffectIcon icon) -{ - this->icon = icon; - return this; +MobEffect* MobEffect::setIcon(EMobEffectIcon icon) { + this->icon = icon; + return this; } -int MobEffect::getId() -{ - return id; -} +int MobEffect::getId() { return id; } /** -* This method should perform periodic updates on the player. Mainly used -* for regeneration effects and the like. Other effects, such as blindness, -* are in effect for the whole duration of the effect. -* -* @param mob -* @param amplification -*/ -void MobEffect::applyEffectTick(std::shared_ptr mob, int amplification) -{ - - // Maybe move this to separate class implementations in the future? - if (id == regeneration->id) - { - if (mob->getHealth() < mob->getMaxHealth()) - { - mob->heal(1); - } - } - else if (id == poison->id) - { - if (mob->getHealth() > 1) - { - mob->hurt(DamageSource::magic, 1); - } - } - else if (id == hunger->id && std::dynamic_pointer_cast(mob) != NULL) - { - // every tick, cause the same amount of exhaustion as when removing - // a block, times amplification - std::dynamic_pointer_cast(mob)->causeFoodExhaustion(FoodConstants::EXHAUSTION_MINE * (amplification + 1)); - } - else if ((id == heal->id && !mob->isInvertedHealAndHarm()) || (id == harm->id && mob->isInvertedHealAndHarm())) - { - mob->heal(6 << amplification); - } - else if ((id == harm->id && !mob->isInvertedHealAndHarm()) || (id == heal->id && mob->isInvertedHealAndHarm())) - { - mob->hurt(DamageSource::magic, 6 << amplification); - } + * This method should perform periodic updates on the player. Mainly used + * for regeneration effects and the like. Other effects, such as blindness, + * are in effect for the whole duration of the effect. + * + * @param mob + * @param amplification + */ +void MobEffect::applyEffectTick(std::shared_ptr mob, int amplification) { + // Maybe move this to separate class implementations in the future? + if (id == regeneration->id) { + if (mob->getHealth() < mob->getMaxHealth()) { + mob->heal(1); + } + } else if (id == poison->id) { + if (mob->getHealth() > 1) { + mob->hurt(DamageSource::magic, 1); + } + } else if (id == hunger->id && + std::dynamic_pointer_cast(mob) != NULL) { + // every tick, cause the same amount of exhaustion as when removing + // a block, times amplification + std::dynamic_pointer_cast(mob)->causeFoodExhaustion( + FoodConstants::EXHAUSTION_MINE * (amplification + 1)); + } else if ((id == heal->id && !mob->isInvertedHealAndHarm()) || + (id == harm->id && mob->isInvertedHealAndHarm())) { + mob->heal(6 << amplification); + } else if ((id == harm->id && !mob->isInvertedHealAndHarm()) || + (id == heal->id && mob->isInvertedHealAndHarm())) { + mob->hurt(DamageSource::magic, 6 << amplification); + } } -void MobEffect::applyInstantenousEffect(std::shared_ptr source, std::shared_ptr mob, int amplification, double scale) -{ - if ((id == heal->id && !mob->isInvertedHealAndHarm()) || (id == harm->id && mob->isInvertedHealAndHarm())) - { - int amount = (int) (scale * (double) (6 << amplification) + .5); - mob->heal(amount); - } - else if ((id == harm->id && !mob->isInvertedHealAndHarm()) || (id == heal->id && mob->isInvertedHealAndHarm())) - { - int amount = (int) (scale * (double) (6 << amplification) + .5); - if (source == NULL) - { - mob->hurt(DamageSource::magic, amount); - } - else - { - DamageSource *damageSource = DamageSource::indirectMagic(mob, source); - mob->hurt(damageSource, amount); - delete damageSource; - } - } +void MobEffect::applyInstantenousEffect(std::shared_ptr source, + std::shared_ptr mob, + int amplification, double scale) { + if ((id == heal->id && !mob->isInvertedHealAndHarm()) || + (id == harm->id && mob->isInvertedHealAndHarm())) { + int amount = (int)(scale * (double)(6 << amplification) + .5); + mob->heal(amount); + } else if ((id == harm->id && !mob->isInvertedHealAndHarm()) || + (id == heal->id && mob->isInvertedHealAndHarm())) { + int amount = (int)(scale * (double)(6 << amplification) + .5); + if (source == NULL) { + mob->hurt(DamageSource::magic, amount); + } else { + DamageSource* damageSource = + DamageSource::indirectMagic(mob, source); + mob->hurt(damageSource, amount); + delete damageSource; + } + } } -bool MobEffect::isInstantenous() -{ - return false; -} +bool MobEffect::isInstantenous() { return false; } /** -* This parameter says if the applyEffect method should be called depending -* on the remaining duration ticker. For instance, the regeneration will be -* activated every 8 ticks, healing one point of health. -* -* @param remainingDuration -* @param amplification -* Effect amplification, starts at 0 (weakest) -* @return -*/ -bool MobEffect::isDurationEffectTick(int remainingDuration, int amplification) -{ + * This parameter says if the applyEffect method should be called depending + * on the remaining duration ticker. For instance, the regeneration will be + * activated every 8 ticks, healing one point of health. + * + * @param remainingDuration + * @param amplification + * Effect amplification, starts at 0 (weakest) + * @return + */ +bool MobEffect::isDurationEffectTick(int remainingDuration, int amplification) { + // Maybe move this to separate class implementations in the future? + if (id == regeneration->id || id == poison->id) { + // tick intervals are 25, 12, 6.. + int interval = 25 >> amplification; + if (interval > 0) { + return (remainingDuration % interval) == 0; + } + return true; + } else if (id == hunger->id) { + return true; + } - // Maybe move this to separate class implementations in the future? - if (id == regeneration->id || id == poison->id) - { - // tick intervals are 25, 12, 6.. - int interval = 25 >> amplification; - if (interval > 0) - { - return (remainingDuration % interval) == 0; - } - return true; - } - else if (id == hunger->id) - { - return true; - } - - return false; + return false; } -MobEffect *MobEffect::setDescriptionId(unsigned int id) -{ - descriptionId = id; - return this; +MobEffect* MobEffect::setDescriptionId(unsigned int id) { + descriptionId = id; + return this; } -unsigned int MobEffect::getDescriptionId(int iData) -{ - return descriptionId; +unsigned int MobEffect::getDescriptionId(int iData) { return descriptionId; } + +MobEffect* MobEffect::setPostfixDescriptionId(unsigned int id) { + m_postfixDescriptionId = id; + return this; } -MobEffect *MobEffect::setPostfixDescriptionId(unsigned int id) -{ - m_postfixDescriptionId = id; - return this; +unsigned int MobEffect::getPostfixDescriptionId(int iData) { + return m_postfixDescriptionId; } -unsigned int MobEffect::getPostfixDescriptionId(int iData) -{ - return m_postfixDescriptionId; +bool MobEffect::hasIcon() { return icon != e_MobEffectIcon_None; } + +MobEffect::EMobEffectIcon MobEffect::getIcon() { return icon; } + +bool MobEffect::isHarmful() { return _isHarmful; } + +std::wstring MobEffect::formatDuration(MobEffectInstance* instance) { + int duration = instance->getDuration(); + + int seconds = duration / SharedConstants::TICKS_PER_SECOND; + int minutes = seconds / 60; + seconds %= 60; + + wchar_t temp[8]; + ZeroMemory(&temp, 8 * (sizeof(wchar_t))); + + if (seconds < 10) { + swprintf(temp, 8, L"%d:0%d", minutes, seconds); + // return minutes + ":0" + seconds; + } else { + swprintf(temp, 8, L"%d:%d", minutes, seconds); + // return minutes + ":" + seconds; + } + + return temp; } -bool MobEffect::hasIcon() -{ - return icon != e_MobEffectIcon_None; +MobEffect* MobEffect::setDurationModifier(double durationModifier) { + this->durationModifier = durationModifier; + return this; } -MobEffect::EMobEffectIcon MobEffect::getIcon() -{ - return icon; +double MobEffect::getDurationModifier() { return durationModifier; } + +MobEffect* MobEffect::setDisabled() { + this->_isDisabled = true; + return this; } -bool MobEffect::isHarmful() -{ - return _isHarmful; -} +bool MobEffect::isDisabled() { return _isDisabled; } -std::wstring MobEffect::formatDuration(MobEffectInstance *instance) -{ - int duration = instance->getDuration(); - - int seconds = duration / SharedConstants::TICKS_PER_SECOND; - int minutes = seconds / 60; - seconds %= 60; - - wchar_t temp[8]; - ZeroMemory(&temp,8*(sizeof(wchar_t))); - - if (seconds < 10) - { - swprintf(temp, 8, L"%d:0%d",minutes,seconds); - //return minutes + ":0" + seconds; - } - else - { - swprintf(temp, 8, L"%d:%d",minutes,seconds); - //return minutes + ":" + seconds; - } - - return temp; -} - -MobEffect *MobEffect::setDurationModifier(double durationModifier) -{ - this->durationModifier = durationModifier; - return this; -} - -double MobEffect::getDurationModifier() -{ - return durationModifier; -} - -MobEffect *MobEffect::setDisabled() -{ - this->_isDisabled = true; - return this; -} - -bool MobEffect::isDisabled() -{ - return _isDisabled; -} - -eMinecraftColour MobEffect::getColor() -{ - return color; -} +eMinecraftColour MobEffect::getColor() { return color; } diff --git a/Minecraft.World/Entities/MobEffect.h b/Minecraft.World/Entities/MobEffect.h index 6c5ae44ff..3138fc66a 100644 --- a/Minecraft.World/Entities/MobEffect.h +++ b/Minecraft.World/Entities/MobEffect.h @@ -1,114 +1,113 @@ #pragma once - class Mob; class MobEffectInstance; -class MobEffect -{ +class MobEffect { public: - enum EMobEffectIcon - { - e_MobEffectIcon_None, - e_MobEffectIcon_Blindness, - e_MobEffectIcon_FireResistance, - e_MobEffectIcon_Haste, - e_MobEffectIcon_Hunger, - e_MobEffectIcon_Invisiblity, - e_MobEffectIcon_JumpBoost, - e_MobEffectIcon_MiningFatigue, - e_MobEffectIcon_Nausea, - e_MobEffectIcon_NightVision, - e_MobEffectIcon_Poison, - e_MobEffectIcon_Regeneration, - e_MobEffectIcon_Resistance, - e_MobEffectIcon_Slowness, - e_MobEffectIcon_Speed, - e_MobEffectIcon_Strength, - e_MobEffectIcon_WaterBreathing, - e_MobEffectIcon_Weakness, + enum EMobEffectIcon { + e_MobEffectIcon_None, + e_MobEffectIcon_Blindness, + e_MobEffectIcon_FireResistance, + e_MobEffectIcon_Haste, + e_MobEffectIcon_Hunger, + e_MobEffectIcon_Invisiblity, + e_MobEffectIcon_JumpBoost, + e_MobEffectIcon_MiningFatigue, + e_MobEffectIcon_Nausea, + e_MobEffectIcon_NightVision, + e_MobEffectIcon_Poison, + e_MobEffectIcon_Regeneration, + e_MobEffectIcon_Resistance, + e_MobEffectIcon_Slowness, + e_MobEffectIcon_Speed, + e_MobEffectIcon_Strength, + e_MobEffectIcon_WaterBreathing, + e_MobEffectIcon_Weakness, - e_MobEffectIcon_COUNT, - }; + e_MobEffectIcon_COUNT, + }; - static const int NUM_EFFECTS = 32; - static MobEffect *effects[NUM_EFFECTS]; + static const int NUM_EFFECTS = 32; + static MobEffect* effects[NUM_EFFECTS]; - static MobEffect *voidEffect; - static MobEffect *movementSpeed; - static MobEffect *movementSlowdown; - static MobEffect *digSpeed; - static MobEffect *digSlowdown; - static MobEffect *damageBoost; - static MobEffect *heal; - static MobEffect *harm; - static MobEffect *jump; - static MobEffect *confusion; - static MobEffect *regeneration; - static MobEffect *damageResistance; - static MobEffect *fireResistance; - static MobEffect *waterBreathing; - static MobEffect *invisibility; - static MobEffect *blindness; - static MobEffect *nightVision; - static MobEffect *hunger; - static MobEffect *weakness; - static MobEffect *poison; - static MobEffect *reserved_20; - static MobEffect *reserved_21; - static MobEffect *reserved_22; - static MobEffect *reserved_23; - static MobEffect *reserved_24; - static MobEffect *reserved_25; - static MobEffect *reserved_26; - static MobEffect *reserved_27; - static MobEffect *reserved_28; - static MobEffect *reserved_29; - static MobEffect *reserved_30; - static MobEffect *reserved_31; + static MobEffect* voidEffect; + static MobEffect* movementSpeed; + static MobEffect* movementSlowdown; + static MobEffect* digSpeed; + static MobEffect* digSlowdown; + static MobEffect* damageBoost; + static MobEffect* heal; + static MobEffect* harm; + static MobEffect* jump; + static MobEffect* confusion; + static MobEffect* regeneration; + static MobEffect* damageResistance; + static MobEffect* fireResistance; + static MobEffect* waterBreathing; + static MobEffect* invisibility; + static MobEffect* blindness; + static MobEffect* nightVision; + static MobEffect* hunger; + static MobEffect* weakness; + static MobEffect* poison; + static MobEffect* reserved_20; + static MobEffect* reserved_21; + static MobEffect* reserved_22; + static MobEffect* reserved_23; + static MobEffect* reserved_24; + static MobEffect* reserved_25; + static MobEffect* reserved_26; + static MobEffect* reserved_27; + static MobEffect* reserved_28; + static MobEffect* reserved_29; + static MobEffect* reserved_30; + static MobEffect* reserved_31; const int id; private: - int descriptionId; - int m_postfixDescriptionId; // 4J added - EMobEffectIcon icon; // 4J changed type - const bool _isHarmful; - double durationModifier; - bool _isDisabled; - const eMinecraftColour color; + int descriptionId; + int m_postfixDescriptionId; // 4J added + EMobEffectIcon icon; // 4J changed type + const bool _isHarmful; + double durationModifier; + bool _isDisabled; + const eMinecraftColour color; protected: - MobEffect(int id, bool isHarmful, eMinecraftColour color); + MobEffect(int id, bool isHarmful, eMinecraftColour color); - //MobEffect *setIcon(int xPos, int yPos); - MobEffect *setIcon(EMobEffectIcon icon); + // MobEffect *setIcon(int xPos, int yPos); + MobEffect* setIcon(EMobEffectIcon icon); public: - int getId(); + int getId(); void applyEffectTick(std::shared_ptr mob, int amplification); - void applyInstantenousEffect(std::shared_ptr source, std::shared_ptr mob, int amplification, double scale); + void applyInstantenousEffect(std::shared_ptr source, + std::shared_ptr mob, int amplification, + double scale); virtual bool isInstantenous(); virtual bool isDurationEffectTick(int remainingDuration, int amplification); - MobEffect *setDescriptionId(unsigned int id); - unsigned int getDescriptionId(int iData = -1); - - // 4J Added - MobEffect *setPostfixDescriptionId(unsigned int id); - unsigned int getPostfixDescriptionId(int iData = -1); + MobEffect* setDescriptionId(unsigned int id); + unsigned int getDescriptionId(int iData = -1); - bool hasIcon(); - EMobEffectIcon getIcon(); // 4J changed return type - bool isHarmful(); - static std::wstring formatDuration(MobEffectInstance *instance); + // 4J Added + MobEffect* setPostfixDescriptionId(unsigned int id); + unsigned int getPostfixDescriptionId(int iData = -1); + + bool hasIcon(); + EMobEffectIcon getIcon(); // 4J changed return type + bool isHarmful(); + static std::wstring formatDuration(MobEffectInstance* instance); protected: - MobEffect *setDurationModifier(double durationModifier); + MobEffect* setDurationModifier(double durationModifier); public: - double getDurationModifier(); - MobEffect *setDisabled(); - bool isDisabled(); - eMinecraftColour getColor(); + double getDurationModifier(); + MobEffect* setDisabled(); + bool isDisabled(); + eMinecraftColour getColor(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/MobEffectInstance.cpp b/Minecraft.World/Entities/MobEffectInstance.cpp index a2f3a4713..e30393e12 100644 --- a/Minecraft.World/Entities/MobEffectInstance.cpp +++ b/Minecraft.World/Entities/MobEffectInstance.cpp @@ -1,139 +1,112 @@ #include "../Platform/stdafx.h" #include "../Headers/net.minecraft.world.effect.h" -void MobEffectInstance::_init(int id, int duration, int amplifier) -{ - this->id = id; - this->duration = duration; - this->amplifier = amplifier; +void MobEffectInstance::_init(int id, int duration, int amplifier) { + this->id = id; + this->duration = duration; + this->amplifier = amplifier; } -MobEffectInstance::MobEffectInstance(int id) -{ - _init(id, 0, 0); +MobEffectInstance::MobEffectInstance(int id) { _init(id, 0, 0); } + +MobEffectInstance::MobEffectInstance(int id, int duration) { + _init(id, duration, 0); } -MobEffectInstance::MobEffectInstance(int id, int duration) -{ - _init(id, duration, 0); +MobEffectInstance::MobEffectInstance(int id, int duration, int amplifier) { + _init(id, duration, amplifier); } -MobEffectInstance::MobEffectInstance(int id, int duration, int amplifier) -{ - _init(id,duration,amplifier); +MobEffectInstance::MobEffectInstance(MobEffectInstance* copy) { + this->id = copy->id; + this->duration = copy->duration; + this->amplifier = copy->amplifier; } -MobEffectInstance::MobEffectInstance(MobEffectInstance *copy) -{ - this->id = copy->id; - this->duration = copy->duration; - this->amplifier = copy->amplifier; +void MobEffectInstance::update(MobEffectInstance* takeOver) { + if (this->id != takeOver->id) { + app.DebugPrintf( + "This method should only be called for matching effects!"); + } + if (takeOver->amplifier > this->amplifier) { + this->amplifier = takeOver->amplifier; + this->duration = takeOver->duration; + } else if (takeOver->amplifier == this->amplifier && + this->duration < takeOver->duration) { + this->duration = takeOver->duration; + } } -void MobEffectInstance::update(MobEffectInstance *takeOver) -{ - if (this->id != takeOver->id) - { - app.DebugPrintf("This method should only be called for matching effects!"); - } - if (takeOver->amplifier > this->amplifier) - { - this->amplifier = takeOver->amplifier; - this->duration = takeOver->duration; - } - else if (takeOver->amplifier == this->amplifier && this->duration < takeOver->duration) - { - this->duration = takeOver->duration; - } -} +int MobEffectInstance::getId() { return id; } -int MobEffectInstance::getId() -{ - return id; -} +int MobEffectInstance::getDuration() { return duration; } -int MobEffectInstance::getDuration() -{ - return duration; -} - -int MobEffectInstance::getAmplifier() -{ - return amplifier; -} +int MobEffectInstance::getAmplifier() { return amplifier; } /** -* Runs the effect on a Mob target. -* -* @param target -* @return True if the effect is still active. -*/ -bool MobEffectInstance::tick(std::shared_ptr target) -{ - if (duration > 0) - { - if (MobEffect::effects[id]->isDurationEffectTick(duration, amplifier)) - { - applyEffect(target); - } - tickDownDuration(); - } - return duration > 0; + * Runs the effect on a Mob target. + * + * @param target + * @return True if the effect is still active. + */ +bool MobEffectInstance::tick(std::shared_ptr target) { + if (duration > 0) { + if (MobEffect::effects[id]->isDurationEffectTick(duration, amplifier)) { + applyEffect(target); + } + tickDownDuration(); + } + return duration > 0; } -int MobEffectInstance::tickDownDuration() -{ - return --duration; +int MobEffectInstance::tickDownDuration() { return --duration; } + +void MobEffectInstance::applyEffect(std::shared_ptr mob) { + if (duration > 0) { + MobEffect::effects[id]->applyEffectTick(mob, amplifier); + } } -void MobEffectInstance::applyEffect(std::shared_ptr mob) -{ - if (duration > 0) - { - MobEffect::effects[id]->applyEffectTick(mob, amplifier); - } -} - -int MobEffectInstance::getDescriptionId() -{ - return MobEffect::effects[id]->getDescriptionId(); +int MobEffectInstance::getDescriptionId() { + return MobEffect::effects[id]->getDescriptionId(); } // 4J Added -int MobEffectInstance::getPostfixDescriptionId() -{ - return MobEffect::effects[id]->getPostfixDescriptionId(); +int MobEffectInstance::getPostfixDescriptionId() { + return MobEffect::effects[id]->getPostfixDescriptionId(); } -int MobEffectInstance::hashCode() -{ - //return id; +int MobEffectInstance::hashCode() { + // return id; - // 4J Stu - Changed this to return a value that represents id, amp and duration - return (id & 0xff) | ( (amplifier & 0xff) << 8) | ( (duration & 0xffff) << 16); + // 4J Stu - Changed this to return a value that represents id, amp and + // duration + return (id & 0xff) | ((amplifier & 0xff) << 8) | + ((duration & 0xffff) << 16); } -std::wstring MobEffectInstance::toString() -{ - std::wstring result = L"MobEffectInstance::toString - NON IMPLEMENTED OR LOCALISED FUNCTION"; - //std::wstring result = ""; - //if (getAmplifier() > 0) - //{ - // result = getDescriptionId() + " x " + (getAmplifier() + 1) + ", Duration: " + getDuration(); - //} - //else - //{ - // result = getDescriptionId() + ", Duration: " + getDuration(); - //} - //if (MobEffect.effects[id].isDisabled()) - //{ - // return "(" + result + ")"; - //} - return result; +std::wstring MobEffectInstance::toString() { + std::wstring result = + L"MobEffectInstance::toString - NON IMPLEMENTED OR LOCALISED FUNCTION"; + // std::wstring result = ""; + // if (getAmplifier() > 0) + //{ + // result = getDescriptionId() + " x " + (getAmplifier() + 1) + ", + //Duration: " + getDuration(); + // } + // else + //{ + // result = getDescriptionId() + ", Duration: " + getDuration(); + // } + // if (MobEffect.effects[id].isDisabled()) + //{ + // return "(" + result + ")"; + // } + return result; } // Was bool equals(Object obj) -bool MobEffectInstance::equals(MobEffectInstance *obj) -{ - return this->id == obj->id && this->amplifier == obj->amplifier && this->duration == obj->duration; +bool MobEffectInstance::equals(MobEffectInstance* obj) { + return this->id == obj->id && this->amplifier == obj->amplifier && + this->duration == obj->duration; } diff --git a/Minecraft.World/Entities/MobEffectInstance.h b/Minecraft.World/Entities/MobEffectInstance.h index 4f6b6ef00..eb8dd2a27 100644 --- a/Minecraft.World/Entities/MobEffectInstance.h +++ b/Minecraft.World/Entities/MobEffectInstance.h @@ -2,41 +2,40 @@ class Mob; -class MobEffectInstance -{ +class MobEffectInstance { private: - // sent as byte - int id; - // sent as short - int duration; - // sent as byte - int amplifier; + // sent as byte + int id; + // sent as short + int duration; + // sent as byte + int amplifier; - void _init(int id, int duration, int amplifier); + void _init(int id, int duration, int amplifier); public: - MobEffectInstance(int id); - MobEffectInstance(int id, int duration); - MobEffectInstance(int id, int duration, int amplifier); - MobEffectInstance(MobEffectInstance *copy); + MobEffectInstance(int id); + MobEffectInstance(int id, int duration); + MobEffectInstance(int id, int duration, int amplifier); + MobEffectInstance(MobEffectInstance* copy); - void update(MobEffectInstance *takeOver); - int getId(); - int getDuration(); - int getAmplifier(); - bool tick(std::shared_ptr target); + void update(MobEffectInstance* takeOver); + int getId(); + int getDuration(); + int getAmplifier(); + bool tick(std::shared_ptr target); private: - int tickDownDuration(); + int tickDownDuration(); public: - void applyEffect(std::shared_ptr mob); - int getDescriptionId(); - int getPostfixDescriptionId(); // 4J Added - int hashCode(); + void applyEffect(std::shared_ptr mob); + int getDescriptionId(); + int getPostfixDescriptionId(); // 4J Added + int hashCode(); - std::wstring toString(); + std::wstring toString(); - // Was bool equals(Object obj) - bool equals(MobEffectInstance *obj); + // Was bool equals(Object obj) + bool equals(MobEffectInstance* obj); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/MobType.h b/Minecraft.World/Entities/MobType.h index 40ba118b5..8efde12df 100644 --- a/Minecraft.World/Entities/MobType.h +++ b/Minecraft.World/Entities/MobType.h @@ -1,9 +1,8 @@ #pragma once -enum MobType -{ - UNDEFINED, +enum MobType { + UNDEFINED, - UNDEAD, - ARTHROPOD + UNDEAD, + ARTHROPOD }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/AgeableMob.cpp b/Minecraft.World/Entities/Mobs/AgeableMob.cpp index 7118f8e61..bd236aa6d 100644 --- a/Minecraft.World/Entities/Mobs/AgeableMob.cpp +++ b/Minecraft.World/Entities/Mobs/AgeableMob.cpp @@ -7,125 +7,103 @@ #include "../../Stats/GenericStats.h" #include "AgeableMob.h" -AgableMob::AgableMob(Level *level) : PathfinderMob(level) -{ - registeredBBWidth = -1; - registeredBBHeight = 0; +AgableMob::AgableMob(Level* level) : PathfinderMob(level) { + registeredBBWidth = -1; + registeredBBHeight = 0; } -bool AgableMob::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); +bool AgableMob::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); - if (item != NULL && item->id == Item::monsterPlacer_Id) - { - if (!level->isClientSide) - { - eINSTANCEOF classToSpawn = EntityIO::getClass(item->getAuxValue()); - if (classToSpawn != eTYPE_NOTSET && (classToSpawn & eTYPE_AGABLE_MOB) == eTYPE_AGABLE_MOB && classToSpawn == GetType() ) // 4J Added GetType() check to only spawn same type - { - std::shared_ptr offspring = getBreedOffspring(std::dynamic_pointer_cast(shared_from_this())); - if (offspring != NULL) - { - offspring->setAge(-20 * 60 * 20); - offspring->moveTo(x, y, z, 0, 0); + if (item != NULL && item->id == Item::monsterPlacer_Id) { + if (!level->isClientSide) { + eINSTANCEOF classToSpawn = EntityIO::getClass(item->getAuxValue()); + if (classToSpawn != eTYPE_NOTSET && + (classToSpawn & eTYPE_AGABLE_MOB) == eTYPE_AGABLE_MOB && + classToSpawn == GetType()) // 4J Added GetType() check to only + // spawn same type + { + std::shared_ptr offspring = getBreedOffspring( + std::dynamic_pointer_cast(shared_from_this())); + if (offspring != NULL) { + offspring->setAge(-20 * 60 * 20); + offspring->moveTo(x, y, z, 0, 0); - level->addEntity(offspring); + level->addEntity(offspring); - if (!player->abilities.instabuild) - { - item->count--; + if (!player->abilities.instabuild) { + item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - } - } - } - } + if (item->count <= 0) { + player->inventory->setItem( + player->inventory->selected, nullptr); + } + } + } + } + } + } - return PathfinderMob::interact(player); + return PathfinderMob::interact(player); } -void AgableMob::defineSynchedData() -{ - PathfinderMob::defineSynchedData(); - entityData->define(DATA_AGE_ID, 0); +void AgableMob::defineSynchedData() { + PathfinderMob::defineSynchedData(); + entityData->define(DATA_AGE_ID, 0); } -int AgableMob::getAge() -{ - return entityData->getInteger(DATA_AGE_ID); +int AgableMob::getAge() { return entityData->getInteger(DATA_AGE_ID); } + +void AgableMob::setAge(int age) { + entityData->set(DATA_AGE_ID, age); + updateSize(isBaby()); } -void AgableMob::setAge(int age) -{ - entityData->set(DATA_AGE_ID, age); - updateSize(isBaby()); +void AgableMob::addAdditonalSaveData(CompoundTag* tag) { + PathfinderMob::addAdditonalSaveData(tag); + tag->putInt(L"Age", getAge()); } -void AgableMob::addAdditonalSaveData(CompoundTag *tag) -{ - PathfinderMob::addAdditonalSaveData(tag); - tag->putInt(L"Age", getAge()); +void AgableMob::readAdditionalSaveData(CompoundTag* tag) { + PathfinderMob::readAdditionalSaveData(tag); + setAge(tag->getInt(L"Age")); } -void AgableMob::readAdditionalSaveData(CompoundTag *tag) -{ - PathfinderMob::readAdditionalSaveData(tag); - setAge(tag->getInt(L"Age")); +void AgableMob::aiStep() { + PathfinderMob::aiStep(); + + if (level->isClientSide) { + updateSize(isBaby()); + } else { + int age = getAge(); + if (age < 0) { + age++; + setAge(age); + } else if (age > 0) { + age--; + setAge(age); + } + } } -void AgableMob::aiStep() -{ - PathfinderMob::aiStep(); +bool AgableMob::isBaby() { return getAge() < 0; } - if(level->isClientSide) - { - updateSize(isBaby()); - } - else - { - int age = getAge(); - if (age < 0) - { - age++; - setAge(age); - } - else if (age > 0) - { - age--; - setAge(age); - } - } +void AgableMob::updateSize(bool isBaby) { + internalSetSize(isBaby ? .5f : 1.0f); } -bool AgableMob::isBaby() -{ - return getAge() < 0; +void AgableMob::setSize(float w, float h) { + bool inited = registeredBBWidth > 0; + + registeredBBWidth = w; + registeredBBHeight = h; + + if (!inited) { + internalSetSize(1.0f); + } } -void AgableMob::updateSize(bool isBaby) -{ - internalSetSize(isBaby ? .5f : 1.0f); -} - -void AgableMob::setSize(float w, float h) -{ - bool inited = registeredBBWidth > 0; - - registeredBBWidth = w; - registeredBBHeight = h; - - if (!inited) - { - internalSetSize(1.0f); - } -} - -void AgableMob::internalSetSize(float scale) -{ - PathfinderMob::setSize(registeredBBWidth * scale, registeredBBHeight * scale); +void AgableMob::internalSetSize(float scale) { + PathfinderMob::setSize(registeredBBWidth * scale, + registeredBBHeight * scale); } diff --git a/Minecraft.World/Entities/Mobs/AgeableMob.h b/Minecraft.World/Entities/Mobs/AgeableMob.h index 49b3a8dc2..933dc349f 100644 --- a/Minecraft.World/Entities/Mobs/AgeableMob.h +++ b/Minecraft.World/Entities/Mobs/AgeableMob.h @@ -2,33 +2,33 @@ #include "../PathfinderMob.h" -class AgableMob : public PathfinderMob -{ +class AgableMob : public PathfinderMob { private: - static const int DATA_AGE_ID = 12; + static const int DATA_AGE_ID = 12; - float registeredBBWidth; - float registeredBBHeight; + float registeredBBWidth; + float registeredBBHeight; public: - AgableMob(Level *level); + AgableMob(Level* level); - virtual bool interact(std::shared_ptr player); + virtual bool interact(std::shared_ptr player); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target) = 0; - virtual int getAge(); - virtual void setAge(int age); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void aiStep(); - virtual bool isBaby(); - virtual void updateSize(bool isBaby); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target) = 0; + virtual int getAge(); + virtual void setAge(int age); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void aiStep(); + virtual bool isBaby(); + virtual void updateSize(bool isBaby); protected: - virtual void setSize(float w, float h); - void internalSetSize(float scale); + virtual void setSize(float w, float h); + void internalSetSize(float scale); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Animal.cpp b/Minecraft.World/Entities/Mobs/Animal.cpp index 1ad221c01..c1be81155 100644 --- a/Minecraft.World/Entities/Mobs/Animal.cpp +++ b/Minecraft.World/Entities/Mobs/Animal.cpp @@ -12,446 +12,395 @@ #include "../../Util/Random.h" #include "Animal.h" -Animal::Animal(Level *level) : AgableMob( level ) -{ -// inLove = 0; // 4J removed - now synched data - loveTime = 0; - loveCause = std::shared_ptr(); +Animal::Animal(Level* level) : AgableMob(level) { + // inLove = 0; + //// 4J removed - now synched data + loveTime = 0; + loveCause = std::shared_ptr(); - setDespawnProtected(); + setDespawnProtected(); } -void Animal::defineSynchedData() -{ - AgableMob::defineSynchedData(); +void Animal::defineSynchedData() { + AgableMob::defineSynchedData(); - entityData->define(DATA_IN_LOVE, (int)0); // 4J added + entityData->define(DATA_IN_LOVE, (int)0); // 4J added } -void Animal::serverAiMobStep() -{ - if (getAge() != 0) setInLoveValue(0); - AgableMob::serverAiMobStep(); +void Animal::serverAiMobStep() { + if (getAge() != 0) setInLoveValue(0); + AgableMob::serverAiMobStep(); } +void Animal::aiStep() { + AgableMob::aiStep(); -void Animal::aiStep() -{ - AgableMob::aiStep(); + if (getAge() != 0) setInLoveValue(0); - if (getAge() != 0) setInLoveValue(0); + if (getInLoveValue() > 0) { + setInLoveValue(getInLoveValue() - 1); + if (getInLoveValue() % 10 == 0) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle(eParticleType_heart, + x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + .5f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, + xa, ya, za); + } + } else { + loveTime = 0; + } - if (getInLoveValue() > 0) - { - setInLoveValue(getInLoveValue()-1); - if (getInLoveValue() % 10 == 0) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(eParticleType_heart, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + .5f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } - } - else - { - loveTime = 0; - } - - updateDespawnProtectedState(); // 4J added + updateDespawnProtectedState(); // 4J added } -void Animal::checkHurtTarget(std::shared_ptr target, float d) -{ - if (std::dynamic_pointer_cast(target) != NULL) - { - if (d < 3) - { - double xd = target->x - x; - double zd = target->z - z; - yRot = (float) (atan2(zd, xd) * 180 / PI) - 90; +void Animal::checkHurtTarget(std::shared_ptr target, float d) { + if (std::dynamic_pointer_cast(target) != NULL) { + if (d < 3) { + double xd = target->x - x; + double zd = target->z - z; + yRot = (float)(atan2(zd, xd) * 180 / PI) - 90; - holdGround = true; - } + holdGround = true; + } - std::shared_ptr p = std::dynamic_pointer_cast(target); - if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) - { - } - else - { - attackTarget = nullptr; - } + std::shared_ptr p = std::dynamic_pointer_cast(target); + if (p->getSelectedItem() != NULL && + this->isFood(p->getSelectedItem())) { + } else { + attackTarget = nullptr; + } - } - else if (std::dynamic_pointer_cast(target) != NULL) - { - std::shared_ptr a = std::dynamic_pointer_cast(target); - if (getAge() > 0 && a->getAge() < 0) - { - if (d < 2.5) - { - holdGround = true; - } - } - else if (getInLoveValue() > 0 && a->getInLoveValue() > 0) - { - if (a->attackTarget == NULL) a->attackTarget = shared_from_this(); + } else if (std::dynamic_pointer_cast(target) != NULL) { + std::shared_ptr a = std::dynamic_pointer_cast(target); + if (getAge() > 0 && a->getAge() < 0) { + if (d < 2.5) { + holdGround = true; + } + } else if (getInLoveValue() > 0 && a->getInLoveValue() > 0) { + if (a->attackTarget == NULL) a->attackTarget = shared_from_this(); - if (a->attackTarget == shared_from_this() && d < 3.5) - { - a->setInLoveValue(a->getInLoveValue()+1); - setInLoveValue(getInLoveValue()+1); - loveTime++; - if (loveTime % 4 == 0) - { - level->addParticle(eParticleType_heart, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + .5f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, 0, 0, 0); - } + if (a->attackTarget == shared_from_this() && d < 3.5) { + a->setInLoveValue(a->getInLoveValue() + 1); + setInLoveValue(getInLoveValue() + 1); + loveTime++; + if (loveTime % 4 == 0) { + level->addParticle( + eParticleType_heart, + x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + .5f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, 0, 0, + 0); + } - if (loveTime == 20 * 3) breedWith(a); - } - else loveTime = 0; - } - else - { - loveTime = 0; - attackTarget = nullptr; - } - - } + if (loveTime == 20 * 3) breedWith(a); + } else + loveTime = 0; + } else { + loveTime = 0; + attackTarget = nullptr; + } + } } +void Animal::breedWith(std::shared_ptr target) { + std::shared_ptr offspring = getBreedOffspring(target); -void Animal::breedWith(std::shared_ptr target) -{ - std::shared_ptr offspring = getBreedOffspring(target); + setInLoveValue(0); + loveTime = 0; + attackTarget = nullptr; + target->attackTarget = nullptr; + target->loveTime = 0; + target->setInLoveValue(0); - setInLoveValue(0); - loveTime = 0; - attackTarget = nullptr; - target->attackTarget = nullptr; - target->loveTime = 0; - target->setInLoveValue(0); + // 4J - we have offspring of NULL returned when we have hit our limits of + // spawning any particular type of animal. In these cases try and do + // everything we can apart from actually spawning the entity. + if (offspring != NULL) { + // Only want to set the age to this +ve value if something is actually + // spawned, as during this period the animal will attempt to follow + // offspring and ignore players. + setAge(5 * 60 * 20); + target->setAge(5 * 60 * 20); - // 4J - we have offspring of NULL returned when we have hit our limits of spawning any particular type of animal. In these cases try and do everything we can apart from actually - // spawning the entity. - if (offspring != NULL) - { - // Only want to set the age to this +ve value if something is actually spawned, as during this period the animal will attempt to follow offspring and ignore players. - setAge(5 * 60 * 20); - target->setAge(5 * 60 * 20); + offspring->setAge(-20 * 60 * 20); + offspring->moveTo(x, y, z, yRot, xRot); + offspring->setDespawnProtected(); + for (int i = 0; i < 7; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle(eParticleType_heart, + x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + .5f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, + xa, ya, za); + } + level->addEntity(offspring); - offspring->setAge(-20 * 60 * 20); - offspring->moveTo(x, y, z, yRot, xRot); - offspring->setDespawnProtected(); - for (int i = 0; i < 7; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(eParticleType_heart, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + .5f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } - level->addEntity(offspring); + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x, y, z, random->nextInt(4) + 1))); + } - level->addEntity( std::shared_ptr( new ExperienceOrb(level, x, y, z, random->nextInt(4) + 1) ) ); - } - - setDespawnProtected(); + setDespawnProtected(); } -float Animal::getWalkTargetValue(int x, int y, int z) -{ - if (level->getTile(x, y - 1, z) == Tile::grass_Id) return 10; - return level->getBrightness(x, y, z) - 0.5f; +float Animal::getWalkTargetValue(int x, int y, int z) { + if (level->getTile(x, y - 1, z) == Tile::grass_Id) return 10; + return level->getBrightness(x, y, z) - 0.5f; } -bool Animal::hurt(DamageSource *dmgSource, int dmg) -{ - if (dynamic_cast(dmgSource) != NULL) - { - std::shared_ptr source = dmgSource->getDirectEntity(); +bool Animal::hurt(DamageSource* dmgSource, int dmg) { + if (dynamic_cast(dmgSource) != NULL) { + std::shared_ptr source = dmgSource->getDirectEntity(); - if (std::dynamic_pointer_cast(source) != NULL && !std::dynamic_pointer_cast(source)->isAllowedToAttackAnimals() ) - { - return false; - } + if (std::dynamic_pointer_cast(source) != NULL && + !std::dynamic_pointer_cast(source) + ->isAllowedToAttackAnimals()) { + return false; + } - if (source != NULL && source->GetType() == eTYPE_ARROW) - { - std::shared_ptr arrow = std::dynamic_pointer_cast(source); - if (std::dynamic_pointer_cast(arrow->owner) != NULL && ! std::dynamic_pointer_cast(arrow->owner)->isAllowedToAttackAnimals() ) - { - return false; - } - } - } + if (source != NULL && source->GetType() == eTYPE_ARROW) { + std::shared_ptr arrow = + std::dynamic_pointer_cast(source); + if (std::dynamic_pointer_cast(arrow->owner) != NULL && + !std::dynamic_pointer_cast(arrow->owner) + ->isAllowedToAttackAnimals()) { + return false; + } + } + } - fleeTime = 20 * 3; - attackTarget = nullptr; - setInLoveValue(0); + fleeTime = 20 * 3; + attackTarget = nullptr; + setInLoveValue(0); - return AgableMob::hurt(dmgSource, dmg); + return AgableMob::hurt(dmgSource, dmg); } -void Animal::addAdditonalSaveData(CompoundTag *tag) -{ - AgableMob::addAdditonalSaveData(tag); - tag->putInt(L"InLove", getInLoveValue()); +void Animal::addAdditonalSaveData(CompoundTag* tag) { + AgableMob::addAdditonalSaveData(tag); + tag->putInt(L"InLove", getInLoveValue()); } -void Animal::readAdditionalSaveData(CompoundTag *tag) -{ - AgableMob::readAdditionalSaveData(tag); - setInLoveValue(tag->getInt(L"InLove")); - setDespawnProtected(); +void Animal::readAdditionalSaveData(CompoundTag* tag) { + AgableMob::readAdditionalSaveData(tag); + setInLoveValue(tag->getInt(L"InLove")); + setDespawnProtected(); } -std::shared_ptr Animal::findAttackTarget() -{ - if (fleeTime > 0) return nullptr; +std::shared_ptr Animal::findAttackTarget() { + if (fleeTime > 0) return nullptr; - float r = 8; - if (getInLoveValue() > 0) - { - std::vector > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others->size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) - { - std::shared_ptr p = std::dynamic_pointer_cast(*it); - if (p != shared_from_this() && p->getInLoveValue() > 0) - { - delete others; - return p; - } - } - delete others; - } - else - { - if (getAge() == 0) - { - std::vector > *players = level->getEntitiesOfClass(typeid(Player), bb->grow(r, r, r)); - //for (int i = 0; i < players.size(); i++) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) - { - setDespawnProtected(); + float r = 8; + if (getInLoveValue() > 0) { + std::vector >* others = + level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); + // for (int i = 0; i < others->size(); i++) + for (AUTO_VAR(it, others->begin()); it != others->end(); ++it) { + std::shared_ptr p = std::dynamic_pointer_cast(*it); + if (p != shared_from_this() && p->getInLoveValue() > 0) { + delete others; + return p; + } + } + delete others; + } else { + if (getAge() == 0) { + std::vector >* players = + level->getEntitiesOfClass(typeid(Player), bb->grow(r, r, r)); + // for (int i = 0; i < players.size(); i++) + for (AUTO_VAR(it, players->begin()); it != players->end(); ++it) { + setDespawnProtected(); - std::shared_ptr p = std::dynamic_pointer_cast(*it); - if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) - { - delete players; - return p; - } - } - delete players; - } - else if (getAge() > 0) - { - std::vector > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others.size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) - { - std::shared_ptr p = std::dynamic_pointer_cast(*it); - if (p != shared_from_this() && p->getAge() < 0) - { - delete others; - return p; - } - } - delete others; - } - } - return nullptr; + std::shared_ptr p = + std::dynamic_pointer_cast(*it); + if (p->getSelectedItem() != NULL && + this->isFood(p->getSelectedItem())) { + delete players; + return p; + } + } + delete players; + } else if (getAge() > 0) { + std::vector >* others = + level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); + // for (int i = 0; i < others.size(); i++) + for (AUTO_VAR(it, others->begin()); it != others->end(); ++it) { + std::shared_ptr p = + std::dynamic_pointer_cast(*it); + if (p != shared_from_this() && p->getAge() < 0) { + delete others; + return p; + } + } + delete others; + } + } + return nullptr; } -bool Animal::canSpawn() -{ - int xt = Mth::floor(x); - int yt = Mth::floor(bb->y0); - int zt = Mth::floor(z); - return level->getTile(xt, yt - 1, zt) == Tile::grass_Id && level->getDaytimeRawBrightness(xt, yt, zt) > 8 && AgableMob::canSpawn(); +bool Animal::canSpawn() { + int xt = Mth::floor(x); + int yt = Mth::floor(bb->y0); + int zt = Mth::floor(z); + return level->getTile(xt, yt - 1, zt) == Tile::grass_Id && + level->getDaytimeRawBrightness(xt, yt, zt) > 8 && + AgableMob::canSpawn(); } -int Animal::getAmbientSoundInterval() -{ - return 20 * 6; +int Animal::getAmbientSoundInterval() { return 20 * 6; } + +bool Animal::removeWhenFarAway() { + return !isDespawnProtected(); // 4J changed - was false } -bool Animal::removeWhenFarAway() -{ - return !isDespawnProtected(); // 4J changed - was false +int Animal::getExperienceReward(std::shared_ptr killedBy) { + return 1 + level->random->nextInt(3); } -int Animal::getExperienceReward(std::shared_ptr killedBy) -{ - return 1 + level->random->nextInt(3); +bool Animal::isFood(std::shared_ptr itemInstance) { + return itemInstance->id == Item::wheat_Id; } -bool Animal::isFood(std::shared_ptr itemInstance) -{ - return itemInstance->id == Item::wheat_Id; -} +bool Animal::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); + if (item != NULL && isFood(item) && getAge() == 0) { + if (!player->abilities.instabuild) { + item->count--; + if (item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } + } -bool Animal::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (item != NULL && isFood(item) && getAge() == 0) - { - if (!player->abilities.instabuild) - { - item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - + // 4J-PB - If we can't produce another animal through breeding because + // of the spawn limits, display a message here + if (!level->isClientSide) { + switch (GetType()) { + case eTYPE_CHICKEN: + if (!level->canCreateMore(eTYPE_CHICKEN, + Level::eSpawnType_Breed)) { + player->displayClientMessage(IDS_MAX_CHICKENS_BRED); + return false; + } + break; + case eTYPE_WOLF: + if (!level->canCreateMore(eTYPE_WOLF, + Level::eSpawnType_Breed)) { + player->displayClientMessage(IDS_MAX_WOLVES_BRED); + return false; + } + break; + case eTYPE_MUSHROOMCOW: + if (!level->canCreateMore(eTYPE_MUSHROOMCOW, + Level::eSpawnType_Breed)) { + player->displayClientMessage(IDS_MAX_MUSHROOMCOWS_BRED); + return false; + } + break; + default: + if ((GetType() & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) { + if (!level->canCreateMore(GetType(), + Level::eSpawnType_Breed)) { + player->displayClientMessage( + IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED); - // 4J-PB - If we can't produce another animal through breeding because of the spawn limits, display a message here - if(!level->isClientSide) - { - switch(GetType()) - { - case eTYPE_CHICKEN: - if( !level->canCreateMore(eTYPE_CHICKEN, Level::eSpawnType_Breed) ) - { - player->displayClientMessage(IDS_MAX_CHICKENS_BRED ); - return false; - } - break; - case eTYPE_WOLF: - if( !level->canCreateMore(eTYPE_WOLF, Level::eSpawnType_Breed) ) - { - player->displayClientMessage(IDS_MAX_WOLVES_BRED ); - return false; - } - break; - case eTYPE_MUSHROOMCOW: - if( !level->canCreateMore(eTYPE_MUSHROOMCOW, Level::eSpawnType_Breed) ) - { - player->displayClientMessage(IDS_MAX_MUSHROOMCOWS_BRED ); - return false; - } - break; - default: - if((GetType() & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) - { - if( !level->canCreateMore(GetType(), Level::eSpawnType_Breed) ) - { - player->displayClientMessage(IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED ); + return false; + } + } else if ((GetType() & eTYPE_MONSTER) == eTYPE_MONSTER) { + } + break; + } + setInLove(player); + } - return false; - } - } - else if( (GetType() & eTYPE_MONSTER) == eTYPE_MONSTER) - { + attackTarget = nullptr; + for (int i = 0; i < 7; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle(eParticleType_heart, + x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + .5f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, + xa, ya, za); + } - } - break; - } - setInLove(player); - } - - - attackTarget = nullptr; - for (int i = 0; i < 7; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(eParticleType_heart, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + .5f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } - - return true; - } - return AgableMob::interact(player); + return true; + } + return AgableMob::interact(player); } // 4J added -int Animal::getInLoveValue() -{ - return entityData->getInteger(DATA_IN_LOVE); -} +int Animal::getInLoveValue() { return entityData->getInteger(DATA_IN_LOVE); } -void Animal::setInLoveValue(int value) -{ - entityData->set(DATA_IN_LOVE, value); -} +void Animal::setInLoveValue(int value) { entityData->set(DATA_IN_LOVE, value); } // 4J added -void Animal::setInLove(std::shared_ptr player) -{ - loveCause = player; - setInLoveValue(20*30); +void Animal::setInLove(std::shared_ptr player) { + loveCause = player; + setInLoveValue(20 * 30); } -std::shared_ptr Animal::getLoveCause() -{ - return loveCause.lock(); +std::shared_ptr Animal::getLoveCause() { return loveCause.lock(); } + +bool Animal::isInLove() { return entityData->getInteger(DATA_IN_LOVE) > 0; } + +void Animal::resetLove() { entityData->set(DATA_IN_LOVE, 0); } + +bool Animal::canMate(std::shared_ptr partner) { + if (partner == shared_from_this()) return false; + Animal* partnerPtr = partner.get(); + if (partnerPtr == NULL || typeid(*partnerPtr) != typeid(*this)) + return false; + return isInLove() && partner->isInLove(); } -bool Animal::isInLove() -{ - return entityData->getInteger(DATA_IN_LOVE) > 0; +void Animal::updateDespawnProtectedState() { + if (level->isClientSide) return; + + if (m_isDespawnProtected) { + int xt = Mth::floor(x); + int zt = Mth::floor(z); + + if (xt > m_maxWanderX) m_maxWanderX = xt; + if (xt < m_minWanderX) m_minWanderX = xt; + if (zt > m_maxWanderZ) m_maxWanderZ = zt; + if (zt < m_minWanderZ) m_minWanderZ = zt; + + if (((m_maxWanderX - m_minWanderX) > MAX_WANDER_DISTANCE) || + ((m_maxWanderZ - m_minWanderZ) > MAX_WANDER_DISTANCE)) { + // printf("Unprotecting : %d to %d, %d to %d\n", + //m_minWanderX, m_maxWanderX, m_minWanderZ, m_maxWanderZ ); + m_isDespawnProtected = false; + } + + /* + if( isExtraWanderingEnabled() ) + { + printf("%d: %d %d, %d\n",entityId,m_maxWanderX - + m_minWanderX, m_maxWanderZ - m_minWanderZ, getWanderingQuadrant()); + } + */ + } } -void Animal::resetLove() { - entityData->set(DATA_IN_LOVE, 0); -} - -bool Animal::canMate(std::shared_ptr partner) -{ - if (partner == shared_from_this()) return false; - Animal *partnerPtr = partner.get(); - if (partnerPtr == NULL || typeid(*partnerPtr) != typeid(*this)) return false; - return isInLove() && partner->isInLove(); -} - -void Animal::updateDespawnProtectedState() -{ - if( level->isClientSide ) return; - - if( m_isDespawnProtected ) - { - int xt = Mth::floor(x); - int zt = Mth::floor(z); - - if ( xt > m_maxWanderX ) m_maxWanderX = xt; - if ( xt < m_minWanderX ) m_minWanderX = xt; - if ( zt > m_maxWanderZ ) m_maxWanderZ = zt; - if ( zt < m_minWanderZ ) m_minWanderZ = zt; - - if( ( ( m_maxWanderX - m_minWanderX ) > MAX_WANDER_DISTANCE ) || - ( ( m_maxWanderZ - m_minWanderZ ) > MAX_WANDER_DISTANCE ) ) - { -// printf("Unprotecting : %d to %d, %d to %d\n", m_minWanderX, m_maxWanderX, m_minWanderZ, m_maxWanderZ ); - m_isDespawnProtected = false; - } - -/* - if( isExtraWanderingEnabled() ) - { - printf("%d: %d %d, %d\n",entityId,m_maxWanderX - m_minWanderX, m_maxWanderZ - m_minWanderZ, getWanderingQuadrant()); - } - */ - } -} - -bool Animal::isDespawnProtected() -{ - return m_isDespawnProtected; -} - -void Animal::setDespawnProtected() -{ - if( level && level->isClientSide ) return; - - int xt = Mth::floor(x); - int zt = Mth::floor(z); - - m_minWanderX = xt; - m_maxWanderX = xt; - m_minWanderZ = zt; - m_maxWanderZ = zt; - - m_isDespawnProtected = true; +bool Animal::isDespawnProtected() { return m_isDespawnProtected; } + +void Animal::setDespawnProtected() { + if (level && level->isClientSide) return; + + int xt = Mth::floor(x); + int zt = Mth::floor(z); + + m_minWanderX = xt; + m_maxWanderX = xt; + m_minWanderZ = zt; + m_maxWanderZ = zt; + + m_isDespawnProtected = true; } diff --git a/Minecraft.World/Entities/Mobs/Animal.h b/Minecraft.World/Entities/Mobs/Animal.h index 468108392..f9a366b3c 100644 --- a/Minecraft.World/Entities/Mobs/Animal.h +++ b/Minecraft.World/Entities/Mobs/Animal.h @@ -6,75 +6,83 @@ class Level; class CompoundTag; class DamageSource; -class Animal : public AgableMob, public Creature -{ +class Animal : public AgableMob, public Creature { private: - static const int DATA_IN_LOVE = 13; // 4J added + static const int DATA_IN_LOVE = 13; // 4J added -// int inLove; // 4J removed - now synched data - int loveTime; - std::weak_ptr loveCause; + // int inLove; // 4J + //removed - now synched data + int loveTime; + std::weak_ptr loveCause; public: - Animal(Level *level); + Animal(Level* level); protected: - virtual void defineSynchedData(); - virtual void serverAiMobStep(); + virtual void defineSynchedData(); + virtual void serverAiMobStep(); public: - virtual void aiStep(); + virtual void aiStep(); protected: - virtual void checkHurtTarget(std::shared_ptr target, float d); + virtual void checkHurtTarget(std::shared_ptr target, float d); private: - virtual void breedWith(std::shared_ptr target); + virtual void breedWith(std::shared_ptr target); public: - virtual float getWalkTargetValue(int x, int y, int z); + virtual float getWalkTargetValue(int x, int y, int z); public: - virtual bool hurt(DamageSource *source, int dmg); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual bool hurt(DamageSource* source, int dmg); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual std::shared_ptr findAttackTarget(); + virtual std::shared_ptr findAttackTarget(); public: - virtual bool canSpawn(); - virtual int getAmbientSoundInterval(); + virtual bool canSpawn(); + virtual int getAmbientSoundInterval(); protected: - virtual bool removeWhenFarAway(); - virtual int getExperienceReward(std::shared_ptr killedBy); + virtual bool removeWhenFarAway(); + virtual int getExperienceReward(std::shared_ptr killedBy); public: - virtual bool isFood(std::shared_ptr itemInstance); - virtual bool interact(std::shared_ptr player); + virtual bool isFood(std::shared_ptr itemInstance); + virtual bool interact(std::shared_ptr player); protected: - int getInLoveValue(); // 4J added + int getInLoveValue(); // 4J added public: - void setInLoveValue(int value); // 4J added - void setInLove(std::shared_ptr player); // 4J added, then modified to match latest Java for XboxOne achievements - std::shared_ptr getLoveCause(); - bool isInLove(); + void setInLoveValue(int value); // 4J added + void setInLove(std::shared_ptr + player); // 4J added, then modified to match latest Java + // for XboxOne achievements + std::shared_ptr getLoveCause(); + bool isInLove(); void resetLove(); virtual bool canMate(std::shared_ptr partner); - // 4J added for determining whether animals are enclosed or not + // 4J added for determining whether animals are enclosed or not private: - bool m_isDespawnProtected; + bool m_isDespawnProtected; + + static const int MAX_WANDER_DISTANCE = + 20; // Maximum distance that the entity can wander before being + // considered as not enclosed & therefore not protected (in tiles) + short m_minWanderX, + m_maxWanderX; // Bounding x values that this has moved since last being + // set to protected ( in tiles ) + short m_minWanderZ, + m_maxWanderZ; // Bounding z values that this has moved since last being + // set to protected ( in tiles ) + void updateDespawnProtectedState(); - static const int MAX_WANDER_DISTANCE = 20; // Maximum distance that the entity can wander before being considered as not enclosed & therefore not protected (in tiles) - short m_minWanderX, m_maxWanderX; // Bounding x values that this has moved since last being set to protected ( in tiles ) - short m_minWanderZ, m_maxWanderZ; // Bounding z values that this has moved since last being set to protected ( in tiles ) - void updateDespawnProtectedState(); public: - virtual bool isDespawnProtected(); - virtual void setDespawnProtected(); - + virtual bool isDespawnProtected(); + virtual void setDespawnProtected(); }; diff --git a/Minecraft.World/Entities/Mobs/Arrow.cpp b/Minecraft.World/Entities/Mobs/Arrow.cpp index 5a0029c1d..f57bb4845 100644 --- a/Minecraft.World/Entities/Mobs/Arrow.cpp +++ b/Minecraft.World/Entities/Mobs/Arrow.cpp @@ -15,517 +15,460 @@ #include "../../Headers/net.minecraft.stats.h" #include "../../Util/SoundTypes.h" - - // base damage, multiplied with velocity const double Arrow::ARROW_BASE_DAMAGE = 2.0f; // 4J - added common ctor code. -void Arrow::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void Arrow::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - xTile = -1; - yTile = -1; - zTile = -1; - lastTile = 0; - lastData = 0; - inGround = false; - pickup = PICKUP_DISALLOWED; - shakeTime = 0; - flightTime = 0; + xTile = -1; + yTile = -1; + zTile = -1; + lastTile = 0; + lastData = 0; + inGround = false; + pickup = PICKUP_DISALLOWED; + shakeTime = 0; + flightTime = 0; - owner = nullptr; - life = 0; + owner = nullptr; + life = 0; - baseDamage = ARROW_BASE_DAMAGE; - knockback = 0; + baseDamage = ARROW_BASE_DAMAGE; + knockback = 0; } +Arrow::Arrow(Level* level) : Entity(level) { + _init(); -Arrow::Arrow(Level *level) : Entity( level ) -{ - _init(); - - this->setSize(0.5f, 0.5f); + this->setSize(0.5f, 0.5f); } -Arrow::Arrow(Level *level, std::shared_ptr mob, std::shared_ptr target, float power, float uncertainty) : Entity( level ) -{ - _init(); +Arrow::Arrow(Level* level, std::shared_ptr mob, + std::shared_ptr target, float power, float uncertainty) + : Entity(level) { + _init(); - this->owner = mob; - if ( std::dynamic_pointer_cast( mob ) != NULL) pickup = PICKUP_ALLOWED; + this->owner = mob; + if (std::dynamic_pointer_cast(mob) != NULL) pickup = PICKUP_ALLOWED; - y = mob->y + mob->getHeadHeight() - 0.1f; + y = mob->y + mob->getHeadHeight() - 0.1f; - double xd = target->x - mob->x; - double yd = (target->y + target->getHeadHeight() - 0.7f) - y; - double zd = target->z - mob->z; - double sd = sqrt(xd * xd + zd * zd); - if (sd < 0.0000001) return; + double xd = target->x - mob->x; + double yd = (target->y + target->getHeadHeight() - 0.7f) - y; + double zd = target->z - mob->z; + double sd = sqrt(xd * xd + zd * zd); + if (sd < 0.0000001) return; - float yRot = (float) (atan2(zd, xd) * 180 / PI) - 90; - float xRot = (float) -(atan2(yd, sd) * 180 / PI); + float yRot = (float)(atan2(zd, xd) * 180 / PI) - 90; + float xRot = (float)-(atan2(yd, sd) * 180 / PI); - double xdn = xd / sd; - double zdn = zd / sd; - moveTo(mob->x + xdn, y, mob->z + zdn, yRot, xRot); - heightOffset = 0; + double xdn = xd / sd; + double zdn = zd / sd; + moveTo(mob->x + xdn, y, mob->z + zdn, yRot, xRot); + heightOffset = 0; - float yo = (float) sd * 0.2f; - shoot(xd, yd + yo, zd, power, uncertainty); + float yo = (float)sd * 0.2f; + shoot(xd, yd + yo, zd, power, uncertainty); } -Arrow::Arrow(Level *level, double x, double y, double z) : Entity( level ) -{ - _init(); +Arrow::Arrow(Level* level, double x, double y, double z) : Entity(level) { + _init(); - this->setSize(0.5f, 0.5f); + this->setSize(0.5f, 0.5f); - this->setPos(x, y, z); - this->heightOffset = 0; -} - -Arrow::Arrow(Level *level, std::shared_ptr mob, float power) : Entity( level ) -{ - _init(); - - this->owner = mob; - if ( std::dynamic_pointer_cast( mob ) != NULL) pickup = PICKUP_ALLOWED; - - setSize(0.5f, 0.5f); - - this->moveTo(mob->x, mob->y + mob->getHeadHeight(), mob->z, mob->yRot, mob->xRot); - - x -= Mth::cos(yRot / 180 * PI) * 0.16f; - y -= 0.1f; - z -= Mth::sin(yRot / 180 * PI) * 0.16f; - this->setPos(x, y, z); - this->heightOffset = 0; - - xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - yd = -Mth::sin(xRot / 180 * PI); - - shoot(xd, yd, zd, power * 1.5f, 1); + this->setPos(x, y, z); + this->heightOffset = 0; } +Arrow::Arrow(Level* level, std::shared_ptr mob, float power) + : Entity(level) { + _init(); -void Arrow::defineSynchedData() -{ - entityData->define(ID_FLAGS, (uint8_t) 0); + this->owner = mob; + if (std::dynamic_pointer_cast(mob) != NULL) pickup = PICKUP_ALLOWED; + + setSize(0.5f, 0.5f); + + this->moveTo(mob->x, mob->y + mob->getHeadHeight(), mob->z, mob->yRot, + mob->xRot); + + x -= Mth::cos(yRot / 180 * PI) * 0.16f; + y -= 0.1f; + z -= Mth::sin(yRot / 180 * PI) * 0.16f; + this->setPos(x, y, z); + this->heightOffset = 0; + + xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + yd = -Mth::sin(xRot / 180 * PI); + + shoot(xd, yd, zd, power * 1.5f, 1); } +void Arrow::defineSynchedData() { entityData->define(ID_FLAGS, (uint8_t)0); } -void Arrow::shoot(double xd, double yd, double zd, float pow, float uncertainty) -{ - float dist = (float) sqrt(xd * xd + yd * yd + zd * zd); +void Arrow::shoot(double xd, double yd, double zd, float pow, + float uncertainty) { + float dist = (float)sqrt(xd * xd + yd * yd + zd * zd); - xd /= dist; - yd /= dist; - zd /= dist; + xd /= dist; + yd /= dist; + zd /= dist; - xd += (random->nextGaussian()) * 0.0075f * uncertainty; - yd += (random->nextGaussian()) * 0.0075f * uncertainty; - zd += (random->nextGaussian()) * 0.0075f * uncertainty; + xd += (random->nextGaussian()) * 0.0075f * uncertainty; + yd += (random->nextGaussian()) * 0.0075f * uncertainty; + zd += (random->nextGaussian()) * 0.0075f * uncertainty; - xd *= pow; - yd *= pow; - zd *= pow; + xd *= pow; + yd *= pow; + zd *= pow; - this->xd = xd; - this->yd = yd; - this->zd = zd; + this->xd = xd; + this->yd = yd; + this->zd = zd; - double sd = sqrt(xd * xd + zd * zd); + double sd = sqrt(xd * xd + zd * zd); - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, sd) * 180 / PI); - life = 0; + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, sd) * 180 / PI); + life = 0; } -void Arrow::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - setPos(x, y, z); - setRot(yRot, xRot); +void Arrow::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + setPos(x, y, z); + setRot(yRot, xRot); } -void Arrow::lerpMotion(double xd, double yd, double zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; - if (xRotO == 0 && yRotO == 0) - { - double sd = sqrt(xd * xd + zd * zd); - yRotO = this->yRot = (float) (atan2( xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2( yd, sd) * 180 / PI); - xRotO = xRot; - yRotO = yRot; - app.DebugPrintf("%f %f : 0x%x\n",xRot,yRot,&yRot); - moveTo(x, y, z, yRot, xRot); - life = 0; - } +void Arrow::lerpMotion(double xd, double yd, double zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; + if (xRotO == 0 && yRotO == 0) { + double sd = sqrt(xd * xd + zd * zd); + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, sd) * 180 / PI); + xRotO = xRot; + yRotO = yRot; + app.DebugPrintf("%f %f : 0x%x\n", xRot, yRot, &yRot); + moveTo(x, y, z, yRot, xRot); + life = 0; + } } -void Arrow::tick() -{ - Entity::tick(); +void Arrow::tick() { + Entity::tick(); + if (xRotO == 0 && yRotO == 0) { + double sd = sqrt(xd * xd + zd * zd); + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, sd) * 180 / PI); + } - if (xRotO == 0 && yRotO == 0) - { - double sd = sqrt(xd * xd + zd * zd); - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, sd) * 180 / PI); - } + { + int t = level->getTile(xTile, yTile, zTile); + if (t > 0) { + Tile::tiles[t]->updateShape(level, xTile, yTile, zTile); + AABB* aabb = Tile::tiles[t]->getAABB(level, xTile, yTile, zTile); + if (aabb != NULL && aabb->contains(Vec3::newTemp(x, y, z))) { + inGround = true; + } + } + } + if (shakeTime > 0) shakeTime--; - { - int t = level->getTile(xTile, yTile, zTile); - if (t > 0) - { - Tile::tiles[t]->updateShape(level, xTile, yTile, zTile); - AABB *aabb = Tile::tiles[t]->getAABB(level, xTile, yTile, zTile); - if (aabb != NULL && aabb->contains(Vec3::newTemp(x, y, z))) - { - inGround = true; - } - } + if (inGround) { + int tile = level->getTile(xTile, yTile, zTile); + int data = level->getData(xTile, yTile, zTile); + if (tile != lastTile || data != lastData) { + inGround = false; - } + xd *= random->nextFloat() * 0.2f; + yd *= random->nextFloat() * 0.2f; + zd *= random->nextFloat() * 0.2f; + life = 0; + flightTime = 0; + return; + } - if (shakeTime > 0) shakeTime--; + else { + life++; + if (life == 20 * 60) remove(); + return; + } + } - if (inGround) - { - int tile = level->getTile(xTile, yTile, zTile); - int data = level->getData(xTile, yTile, zTile); - if (tile != lastTile || data != lastData) - { - inGround = false; + else { + flightTime++; + } - xd *= random->nextFloat() * 0.2f; - yd *= random->nextFloat() * 0.2f; - zd *= random->nextFloat() * 0.2f; - life = 0; - flightTime = 0; - return; - } + Vec3* from = Vec3::newTemp(x, y, z); + Vec3* to = Vec3::newTemp(x + xd, y + yd, z + zd); + HitResult* res = level->clip(from, to, false, true); - else - { - life++; - if (life == 20 * 60) remove(); - return; - } - } - - else - { - flightTime++; - } + from = Vec3::newTemp(x, y, z); + to = Vec3::newTemp(x + xd, y + yd, z + zd); + if (res != NULL) { + to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); + } + std::shared_ptr hitEntity = nullptr; + std::vector >* objects = level->getEntities( + shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); + double nearest = 0; + AUTO_VAR(itEnd, objects->end()); + for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // objects->at(i); + if (!e->isPickable() || (e == owner && flightTime < 5)) continue; - Vec3 *from = Vec3::newTemp(x, y, z); - Vec3 *to = Vec3::newTemp(x + xd, y + yd, z + zd); - HitResult *res = level->clip(from, to, false, true); + float rr = 0.3f; + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (p != NULL) { + double dd = from->distanceTo(p->pos); + if (dd < nearest || nearest == 0) { + hitEntity = e; + nearest = dd; + } + delete p; + } + } - from = Vec3::newTemp(x, y, z); - to = Vec3::newTemp(x + xd, y + yd, z + zd); - if (res != NULL) - { - to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); - } - std::shared_ptr hitEntity = nullptr; - std::vector > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); - double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //objects->at(i); - if (!e->isPickable() || (e == owner && flightTime < 5)) continue; + if (hitEntity != NULL) { + delete res; + res = new HitResult(hitEntity); + } - float rr = 0.3f; - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (p != NULL) - { - double dd = from->distanceTo(p->pos); - if (dd < nearest || nearest == 0) - { - hitEntity = e; - nearest = dd; - } - delete p; - } - } + if (res != NULL) { + if (res->entity != NULL) { + float pow = Mth::sqrt(xd * xd + yd * yd + zd * zd); + int dmg = (int)Mth::ceil((float)(pow * baseDamage)); - if (hitEntity != NULL) - { - delete res; - res = new HitResult(hitEntity); - } + if (isCritArrow()) dmg += random->nextInt(dmg / 2 + 2); - if (res != NULL) - { - if (res->entity != NULL) - { - float pow = Mth::sqrt(xd * xd + yd * yd + zd * zd); - int dmg = (int) Mth::ceil((float)(pow * baseDamage)); + DamageSource* damageSource = NULL; + if (owner == NULL) { + damageSource = DamageSource::arrow( + std::dynamic_pointer_cast(shared_from_this()), + shared_from_this()); + } else { + damageSource = DamageSource::arrow( + std::dynamic_pointer_cast(shared_from_this()), + owner); + } - if(isCritArrow()) dmg += random->nextInt(dmg / 2 + 2); + if (res->entity->hurt(damageSource, dmg)) { + // Firx for #67839 - Customer Encountered: Bows enchanted with + // "Flame" still set things on fire if pvp/attack animals is + // turned off 4J Stu - We should not set the entity on fire + // unless we can cause some damage (this doesn't necessarily + // mean that the arrow hit lowered their health) set targets on + // fire first because we want cooked pork/chicken/steak + if (this->isOnFire()) { + res->entity->setOnFire(5); + } - DamageSource *damageSource = NULL; - if (owner == NULL) - { - damageSource = DamageSource::arrow(std::dynamic_pointer_cast(shared_from_this()), shared_from_this()); - } - else - { - damageSource = DamageSource::arrow(std::dynamic_pointer_cast(shared_from_this()), owner); - } + std::shared_ptr mob = + std::dynamic_pointer_cast(res->entity); + if (mob != NULL) { + mob->arrowCount++; + if (knockback > 0) { + float pushLen = sqrt(xd * xd + zd * zd); + if (pushLen > 0) { + res->entity->push(xd * knockback * .6f / pushLen, + 0.1, + zd * knockback * .6f / pushLen); + } + } - if(res->entity->hurt(damageSource, dmg)) - { - // Firx for #67839 - Customer Encountered: Bows enchanted with "Flame" still set things on fire if pvp/attack animals is turned off - // 4J Stu - We should not set the entity on fire unless we can cause some damage (this doesn't necessarily mean that the arrow hit lowered their health) - // set targets on fire first because we want cooked - // pork/chicken/steak - if (this->isOnFire()) - { - res->entity->setOnFire(5); - } + if (owner != NULL) { + ThornsEnchantment::doThornsAfterAttack(owner, mob, + random); + } + } - std::shared_ptr mob = std::dynamic_pointer_cast(res->entity); - if (mob != NULL) - { - mob->arrowCount++; - if (knockback > 0) - { - float pushLen = sqrt(xd * xd + zd * zd); - if (pushLen > 0) - { - res->entity->push(xd * knockback * .6f / pushLen, 0.1, zd * knockback * .6f / pushLen); - } - } + // 4J : WESTY : For award, need to track if creeper was killed + // by arrow from the player. + if ((std::dynamic_pointer_cast(owner) != + NULL) && // arrow owner is a player + (res->entity->isAlive() == false) && // target is now dead + (std::dynamic_pointer_cast(res->entity) != + NULL)) // target is a creeper - if (owner != NULL) - { - ThornsEnchantment::doThornsAfterAttack(owner, mob, random); - } - } + { + std::dynamic_pointer_cast(owner)->awardStat( + GenericStats::arrowKillCreeper(), + GenericStats::param_arrowKillCreeper()); + } - // 4J : WESTY : For award, need to track if creeper was killed by arrow from the player. - if ( (std::dynamic_pointer_cast(owner) != NULL ) && // arrow owner is a player - ( res->entity->isAlive() == false ) && // target is now dead - ( std::dynamic_pointer_cast( res->entity ) != NULL ) ) // target is a creeper + // 4J - sound change brought forward from 1.2.3 + level->playSound(shared_from_this(), eSoundType_RANDOM_BOW_HIT, + 1.0f, + 1.2f / (random->nextFloat() * 0.2f + 0.9f)); + remove(); + } else { + xd *= -0.1f; + yd *= -0.1f; + zd *= -0.1f; + yRot += 180; + yRotO += 180; + flightTime = 0; + } - { - std::dynamic_pointer_cast(owner)->awardStat( - GenericStats::arrowKillCreeper(), - GenericStats::param_arrowKillCreeper() - ); - } + delete damageSource; + } else { + xTile = res->x; + yTile = res->y; + zTile = res->z; + lastTile = level->getTile(xTile, yTile, zTile); + lastData = level->getData(xTile, yTile, zTile); + xd = (float)(res->pos->x - x); + yd = (float)(res->pos->y - y); + zd = (float)(res->pos->z - z); + float dd = (float)sqrt(xd * xd + yd * yd + zd * zd); + // 4J added check - zero dd here was creating NaNs + if (dd > 0.0001f) { + x -= (xd / dd) * 0.05f; + y -= (yd / dd) * 0.05f; + z -= (zd / dd) * 0.05f; + } - // 4J - sound change brought forward from 1.2.3 - level->playSound(shared_from_this(), eSoundType_RANDOM_BOW_HIT, 1.0f, 1.2f / (random->nextFloat() * 0.2f + 0.9f)); - remove(); - } - else - { - xd *= -0.1f; - yd *= -0.1f; - zd *= -0.1f; - yRot += 180; - yRotO += 180; - flightTime = 0; - } - - delete damageSource; - } - else - { - xTile = res->x; - yTile = res->y; - zTile = res->z; - lastTile = level->getTile(xTile, yTile, zTile); - lastData = level->getData(xTile, yTile, zTile); - xd = (float) (res->pos->x - x); - yd = (float) (res->pos->y - y); - zd = (float) (res->pos->z - z); - float dd = (float) sqrt(xd * xd + yd * yd + zd * zd); - // 4J added check - zero dd here was creating NaNs - if( dd > 0.0001f ) - { - x -= (xd / dd) * 0.05f; - y -= (yd / dd) * 0.05f; - z -= (zd / dd) * 0.05f; - } + // 4J - sound change brought forward from 1.2.3 + level->playSound(shared_from_this(), eSoundType_RANDOM_BOW_HIT, + 1.0f, 1.2f / (random->nextFloat() * 0.2f + 0.9f)); + inGround = true; + shakeTime = 7; + setCritArrow(false); + } + } + delete res; - // 4J - sound change brought forward from 1.2.3 - level->playSound(shared_from_this(), eSoundType_RANDOM_BOW_HIT, 1.0f, 1.2f / (random->nextFloat() * 0.2f + 0.9f)); - inGround = true; - shakeTime = 7; - setCritArrow(false); - } - } - delete res; + if (isCritArrow()) { + for (int i = 0; i < 4; i++) { + level->addParticle(eParticleType_crit, x + xd * i / 4.0f, + y + yd * i / 4.0f, z + zd * i / 4.0f, -xd, + -yd + 0.2, -zd); + } + } - if(isCritArrow()) - { - for (int i = 0; i < 4; i++) - { - level->addParticle(eParticleType_crit, x + xd * i / 4.0f, y + yd * i / 4.0f, z + zd * i / 4.0f, -xd, -yd + 0.2, -zd); - } - } + x += xd; + y += yd; + z += zd; - x += xd; - y += yd; - z += zd; + double sd = sqrt(xd * xd + zd * zd); + yRot = (float)(atan2(xd, zd) * 180 / PI); + xRot = (float)(atan2(yd, sd) * 180 / PI); - double sd = sqrt(xd * xd + zd * zd); - yRot = (float) (atan2(xd, zd) * 180 / PI); - xRot = (float) (atan2(yd, sd) * 180 / PI); + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; + xRot = xRotO + (xRot - xRotO) * 0.2f; + yRot = yRotO + (yRot - yRotO) * 0.2f; - xRot = xRotO + (xRot - xRotO) * 0.2f; - yRot = yRotO + (yRot - yRotO) * 0.2f; + float inertia = 0.99f; + float gravity = 0.05f; + if (isInWater()) { + for (int i = 0; i < 4; i++) { + float s = 1 / 4.0f; + level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, + z - zd * s, xd, yd, zd); + } + inertia = 0.80f; + } - float inertia = 0.99f; - float gravity = 0.05f; + xd *= inertia; + yd *= inertia; + zd *= inertia; + yd -= gravity; - if (isInWater()) - { - for (int i = 0; i < 4; i++) - { - float s = 1 / 4.0f; - level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, z - zd * s, xd, yd, zd); - } - inertia = 0.80f; - } + setPos(x, y, z); - xd *= inertia; - yd *= inertia; - zd *= inertia; - yd -= gravity; - - setPos(x, y, z); - - checkInsideTiles(); + checkInsideTiles(); } -void Arrow::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putShort(L"xTile", (short) xTile); - tag->putShort(L"yTile", (short) yTile); - tag->putShort(L"zTile", (short) zTile); - tag->putByte(L"inTile", (uint8_t) lastTile); - tag->putByte(L"inData", (uint8_t) lastData); - tag->putByte(L"shake", (uint8_t) shakeTime); - tag->putByte(L"inGround", (uint8_t) (inGround ? 1 : 0)); - tag->putByte(L"pickup", (uint8_t) pickup); - tag->putDouble(L"damage", baseDamage); +void Arrow::addAdditonalSaveData(CompoundTag* tag) { + tag->putShort(L"xTile", (short)xTile); + tag->putShort(L"yTile", (short)yTile); + tag->putShort(L"zTile", (short)zTile); + tag->putByte(L"inTile", (uint8_t)lastTile); + tag->putByte(L"inData", (uint8_t)lastData); + tag->putByte(L"shake", (uint8_t)shakeTime); + tag->putByte(L"inGround", (uint8_t)(inGround ? 1 : 0)); + tag->putByte(L"pickup", (uint8_t)pickup); + tag->putDouble(L"damage", baseDamage); } -void Arrow::readAdditionalSaveData(CompoundTag *tag) -{ - xTile = tag->getShort(L"xTile"); - yTile = tag->getShort(L"yTile"); - zTile = tag->getShort(L"zTile"); - lastTile = tag->getByte(L"inTile") & 0xff; - lastData = tag->getByte(L"inData") & 0xff; - shakeTime = tag->getByte(L"shake") & 0xff; - inGround = tag->getByte(L"inGround") == 1; - if (tag->contains(L"damage")) - { - baseDamage = tag->getDouble(L"damage"); - } +void Arrow::readAdditionalSaveData(CompoundTag* tag) { + xTile = tag->getShort(L"xTile"); + yTile = tag->getShort(L"yTile"); + zTile = tag->getShort(L"zTile"); + lastTile = tag->getByte(L"inTile") & 0xff; + lastData = tag->getByte(L"inData") & 0xff; + shakeTime = tag->getByte(L"shake") & 0xff; + inGround = tag->getByte(L"inGround") == 1; + if (tag->contains(L"damage")) { + baseDamage = tag->getDouble(L"damage"); + } - if (tag->contains(L"pickup")) - { - pickup = tag->getByte(L"pickup"); - } - else if (tag->contains(L"player")) - { - pickup = tag->getBoolean(L"player") ? PICKUP_ALLOWED : PICKUP_DISALLOWED; - } + if (tag->contains(L"pickup")) { + pickup = tag->getByte(L"pickup"); + } else if (tag->contains(L"player")) { + pickup = + tag->getBoolean(L"player") ? PICKUP_ALLOWED : PICKUP_DISALLOWED; + } } -void Arrow::playerTouch(std::shared_ptr player) -{ - if (level->isClientSide || !inGround || shakeTime > 0) return; +void Arrow::playerTouch(std::shared_ptr player) { + if (level->isClientSide || !inGround || shakeTime > 0) return; - bool bRemove = pickup == PICKUP_ALLOWED || (pickup == PICKUP_CREATIVE_ONLY && player->abilities.instabuild); + bool bRemove = + pickup == PICKUP_ALLOWED || + (pickup == PICKUP_CREATIVE_ONLY && player->abilities.instabuild); - if (pickup == PICKUP_ALLOWED) - { - if (!player->inventory->add( std::shared_ptr( new ItemInstance(Item::arrow, 1) ) )) - { - bRemove = false; - } - } + if (pickup == PICKUP_ALLOWED) { + if (!player->inventory->add(std::shared_ptr( + new ItemInstance(Item::arrow, 1)))) { + bRemove = false; + } + } - if (bRemove) - { - level->playSound(shared_from_this(), eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - player->take(shared_from_this(), 1); - remove(); - } + if (bRemove) { + level->playSound( + shared_from_this(), eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); + player->take(shared_from_this(), 1); + remove(); + } } -float Arrow::getShadowHeightOffs() -{ - return 0; +float Arrow::getShadowHeightOffs() { return 0; } + +void Arrow::setBaseDamage(double baseDamage) { this->baseDamage = baseDamage; } + +double Arrow::getBaseDamage() { return baseDamage; } + +void Arrow::setKnockback(int knockback) { this->knockback = knockback; } + +bool Arrow::isAttackable() { return false; } + +void Arrow::setCritArrow(bool critArrow) { + uint8_t flags = entityData->getByte(ID_FLAGS); + if (critArrow) { + entityData->set(ID_FLAGS, (uint8_t)(flags | FLAG_CRIT)); + } else { + entityData->set(ID_FLAGS, (uint8_t)(flags & ~FLAG_CRIT)); + } } -void Arrow::setBaseDamage(double baseDamage) -{ - this->baseDamage = baseDamage; -} - -double Arrow::getBaseDamage() -{ - return baseDamage; -} - -void Arrow::setKnockback(int knockback) -{ - this->knockback = knockback; -} - -bool Arrow::isAttackable() -{ - return false; -} - -void Arrow::setCritArrow(bool critArrow) -{ - uint8_t flags = entityData->getByte(ID_FLAGS); - if (critArrow) - { - entityData->set(ID_FLAGS, (uint8_t) (flags | FLAG_CRIT)); - } - else - { - entityData->set(ID_FLAGS, (uint8_t) (flags & ~FLAG_CRIT)); - } -} - -bool Arrow::isCritArrow() -{ - uint8_t flags = entityData->getByte(ID_FLAGS); - return (flags & FLAG_CRIT) != 0; +bool Arrow::isCritArrow() { + uint8_t flags = entityData->getByte(ID_FLAGS); + return (flags & FLAG_CRIT) != 0; } diff --git a/Minecraft.World/Entities/Mobs/Arrow.h b/Minecraft.World/Entities/Mobs/Arrow.h index c8f168492..cf85a4ac2 100644 --- a/Minecraft.World/Entities/Mobs/Arrow.h +++ b/Minecraft.World/Entities/Mobs/Arrow.h @@ -1,29 +1,27 @@ #pragma once - #include "../Entity.h" class Level; class CompoundTag; -class Arrow : public Entity -{ +class Arrow : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_ARROW; } - static Entity *create(Level *level) { return new Arrow(level); } + eINSTANCEOF GetType() { return eTYPE_ARROW; } + static Entity* create(Level* level) { return new Arrow(level); } private: - // base damage, multiplied with velocity - static const double ARROW_BASE_DAMAGE; + // base damage, multiplied with velocity + static const double ARROW_BASE_DAMAGE; public: - static const int PICKUP_DISALLOWED = 0; - static const int PICKUP_ALLOWED = 1; - static const int PICKUP_CREATIVE_ONLY = 2; + static const int PICKUP_DISALLOWED = 0; + static const int PICKUP_ALLOWED = 1; + static const int PICKUP_CREATIVE_ONLY = 2; private: - static const int ID_FLAGS = 16; - static const int FLAG_CRIT = 1; + static const int ID_FLAGS = 16; + static const int FLAG_CRIT = 1; private: int xTile; @@ -34,45 +32,47 @@ private: bool inGround; public: - int pickup; + int pickup; int shakeTime; std::shared_ptr owner; private: - double baseDamage; + double baseDamage; int knockback; private: - int life; + int life; int flightTime; - // 4J - added common ctor code. - void _init(); + // 4J - added common ctor code. + void _init(); public: - Arrow(Level *level); - Arrow(Level *level, std::shared_ptr mob, std::shared_ptr target, float power, float uncertainty); - Arrow(Level *level, double x, double y, double z); - Arrow(Level *level, std::shared_ptr mob, float power); + Arrow(Level* level); + Arrow(Level* level, std::shared_ptr mob, std::shared_ptr target, + float power, float uncertainty); + Arrow(Level* level, double x, double y, double z); + Arrow(Level* level, std::shared_ptr mob, float power); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - void shoot(double xd, double yd, double zd, float pow, float uncertainty); - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); - virtual void lerpMotion(double xd, double yd, double zd); + void shoot(double xd, double yd, double zd, float pow, float uncertainty); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); + virtual void lerpMotion(double xd, double yd, double zd); virtual void tick(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); virtual void playerTouch(std::shared_ptr player); virtual float getShadowHeightOffs(); - void setBaseDamage(double baseDamage); - double getBaseDamage(); - void setKnockback(int knockback); - virtual bool isAttackable(); - void setCritArrow(bool critArrow); - bool isCritArrow(); + void setBaseDamage(double baseDamage); + double getBaseDamage(); + void setKnockback(int knockback); + virtual bool isAttackable(); + void setCritArrow(bool critArrow); + bool isCritArrow(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Blaze.cpp b/Minecraft.World/Entities/Mobs/Blaze.cpp index 176099117..24f479585 100644 --- a/Minecraft.World/Entities/Mobs/Blaze.cpp +++ b/Minecraft.World/Entities/Mobs/Blaze.cpp @@ -11,217 +11,175 @@ #include "Blaze.h" #include "../../Util/SoundTypes.h" +Blaze::Blaze(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Blaze::Blaze(Level *level) : Monster(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + this->textureIdx = TN_MOB_BLAZE; // 4J Was "/mob/fire.png"; - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + fireImmune = true; + attackDamage = 6; + xpReward = XP_REWARD_LARGE; + // this.setSize(1.2f, 1.8f); - this->textureIdx = TN_MOB_BLAZE; // 4J Was "/mob/fire.png"; - - fireImmune = true; - attackDamage = 6; - xpReward = XP_REWARD_LARGE; - // this.setSize(1.2f, 1.8f); - - // 4J Default inits - allowedHeightOffset = 0.5f; - nextHeightOffsetChangeTick = 0; - attackCounter = 0; + // 4J Default inits + allowedHeightOffset = 0.5f; + nextHeightOffsetChangeTick = 0; + attackCounter = 0; } -int Blaze::getMaxHealth() -{ - return 20; +int Blaze::getMaxHealth() { return 20; } + +void Blaze::defineSynchedData() { + Monster::defineSynchedData(); + + entityData->define(DATA_FLAGS_ID, (uint8_t)0); } -void Blaze::defineSynchedData() -{ - Monster::defineSynchedData(); +int Blaze::getAmbientSound() { return eSoundType_MOB_BLAZE_BREATHE; } - entityData->define(DATA_FLAGS_ID, (uint8_t) 0); +int Blaze::getHurtSound() { return eSoundType_MOB_BLAZE_HURT; } + +int Blaze::getDeathSound() { return eSoundType_MOB_BLAZE_DEATH; } + +int Blaze::getLightColor(float a) { + return SharedConstants::FULLBRIGHT_LIGHTVALUE; } -int Blaze::getAmbientSound() -{ - return eSoundType_MOB_BLAZE_BREATHE; +float Blaze::getBrightness(float a) { return 1.0f; } + +void Blaze::aiStep() { + if (!level->isClientSide) { + if (isInWaterOrRain()) { + hurt(DamageSource::drown, 1); + } + + nextHeightOffsetChangeTick--; + if (nextHeightOffsetChangeTick <= 0) { + nextHeightOffsetChangeTick = SharedConstants::TICKS_PER_SECOND * 5; + allowedHeightOffset = .5f + (float)random->nextGaussian() * 3; + } + + if (getAttackTarget() != NULL && + (getAttackTarget()->y + getAttackTarget()->getHeadHeight()) > + (this->y + getHeadHeight() + allowedHeightOffset)) { + yd = yd + (.3f - yd) * .3f; + } + } + + if (random->nextInt(24) == 0) { + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_FIRE_FIRE, + 1 + random->nextFloat(), + random->nextFloat() * 0.7f + 0.3f); + } + + // slow falling, like chicken + if (!onGround && yd < 0) { + yd *= 0.6; + } + + for (int i = 0; i < 2; i++) { + level->addParticle(eParticleType_largesmoke, + x + (random->nextDouble() - 0.5) * bbWidth, + y + random->nextDouble() * bbHeight, + z + (random->nextDouble() - 0.5) * bbWidth, 0, 0, 0); + } + + Monster::aiStep(); } -int Blaze::getHurtSound() -{ - return eSoundType_MOB_BLAZE_HURT; +void Blaze::checkHurtTarget(std::shared_ptr target, float d) { + if (attackTime <= 0 && d < 2.0f && target->bb->y1 > bb->y0 && + target->bb->y0 < bb->y1) { + attackTime = 20; + doHurtTarget(target); + } else if (d < 30) { + double xd = target->x - x; + double yd = + (target->bb->y0 + target->bbHeight / 2) - (y + bbHeight / 2); + double zd = target->z - z; + + if (attackTime == 0) { + attackCounter++; + if (attackCounter == 1) { + attackTime = SharedConstants::TICKS_PER_SECOND * 3; + setCharged(true); + } else if (attackCounter <= 4) { + attackTime = SharedConstants::TICKS_PER_SECOND / 3; + } else { + attackTime = SharedConstants::TICKS_PER_SECOND * 5; + attackCounter = 0; + setCharged(false); + } + + if (attackCounter > 1) { + float sqd = sqrt(d) * .5f; + + level->levelEvent(nullptr, LevelEvent::SOUND_BLAZE_FIREBALL, + (int)x, (int)y, (int)z, 0); + // level.playSound(this, + // "mob.ghast.fireball", getSoundVolume(), + // (random.nextFloat() - random.nextFloat()) + // * 0.2f + 1.0f); + for (int i = 0; i < 1; i++) { + std::shared_ptr ie = + std::shared_ptr(new SmallFireball( + level, + std::dynamic_pointer_cast(shared_from_this()), + xd + random->nextGaussian() * sqd, yd, + zd + random->nextGaussian() * sqd)); + // Vec3 v = getViewVector(1); + // ie.x = x + v.x * 1.5; + ie->y = y + bbHeight / 2 + 0.5f; + // ie.z = z + v.z * 1.5; + level->addEntity(ie); + } + } + } + yRot = (float)(atan2(zd, xd) * 180 / PI) - 90; + + holdGround = true; + } } -int Blaze::getDeathSound() -{ - return eSoundType_MOB_BLAZE_DEATH; +void Blaze::causeFallDamage(float distance) {} + +int Blaze::getDeathLoot() { return Item::blazeRod_Id; } + +bool Blaze::isOnFire() { return isCharged(); } + +void Blaze::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + if (wasKilledByPlayer) { + int count = random->nextInt(2 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::blazeRod_Id, 1); + } + // 4J-PB - added to the XBLA version due to our limited amount of + // glowstone in the Nether - drop 0-2 glowstone dust + count = random->nextInt(3 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::yellowDust_Id, 1); + } + } } -int Blaze::getLightColor(float a) -{ - return SharedConstants::FULLBRIGHT_LIGHTVALUE; +bool Blaze::isCharged() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x1) != 0; } -float Blaze::getBrightness(float a) -{ - return 1.0f; +void Blaze::setCharged(bool value) { + uint8_t flags = entityData->getByte(DATA_FLAGS_ID); + if (value) { + flags |= 0x1; + } else { + flags &= ~0x1; + } + entityData->set(DATA_FLAGS_ID, flags); } -void Blaze::aiStep() -{ - if (!level->isClientSide) - { - - if (isInWaterOrRain()) - { - hurt(DamageSource::drown, 1); - } - - nextHeightOffsetChangeTick--; - if (nextHeightOffsetChangeTick <= 0) - { - nextHeightOffsetChangeTick = SharedConstants::TICKS_PER_SECOND * 5; - allowedHeightOffset = .5f + (float) random->nextGaussian() * 3; - } - - if (getAttackTarget() != NULL && (getAttackTarget()->y + getAttackTarget()->getHeadHeight()) > (this->y + getHeadHeight() + allowedHeightOffset)) - { - yd = yd + (.3f - yd) * .3f; - } - - } - - if (random->nextInt(24) == 0) - { - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_FIRE_FIRE, 1 + random->nextFloat(), random->nextFloat() * 0.7f + 0.3f); - } - - // slow falling, like chicken - if (!onGround && yd < 0) - { - yd *= 0.6; - } - - for (int i = 0; i < 2; i++) - { - level->addParticle(eParticleType_largesmoke, x + (random->nextDouble() - 0.5) * bbWidth, y + random->nextDouble() * bbHeight, z + (random->nextDouble() - 0.5) * bbWidth, 0, 0, 0); - } - - Monster::aiStep(); -} - -void Blaze::checkHurtTarget(std::shared_ptr target, float d) -{ - if (attackTime <= 0 && d < 2.0f && target->bb->y1 > bb->y0 && target->bb->y0 < bb->y1) - { - attackTime = 20; - doHurtTarget(target); - } - else if (d < 30) - { - double xd = target->x - x; - double yd = (target->bb->y0 + target->bbHeight / 2) - (y + bbHeight / 2); - double zd = target->z - z; - - if (attackTime == 0) - { - attackCounter++; - if (attackCounter == 1) - { - attackTime = SharedConstants::TICKS_PER_SECOND * 3; - setCharged(true); - } - else if (attackCounter <= 4) - { - attackTime = SharedConstants::TICKS_PER_SECOND / 3; - } - else - { - attackTime = SharedConstants::TICKS_PER_SECOND * 5; - attackCounter = 0; - setCharged(false); - } - - if (attackCounter > 1) - { - float sqd = sqrt(d) * .5f; - - level->levelEvent(nullptr, LevelEvent::SOUND_BLAZE_FIREBALL, (int) x, (int) y, (int) z, 0); - // level.playSound(this, "mob.ghast.fireball", getSoundVolume(), (random.nextFloat() - random.nextFloat()) * 0.2f + 1.0f); - for (int i = 0; i < 1; i++) { - std::shared_ptr ie = std::shared_ptr( new SmallFireball(level, std::dynamic_pointer_cast( shared_from_this() ), xd + random->nextGaussian() * sqd, yd, zd + random->nextGaussian() * sqd) ); - // Vec3 v = getViewVector(1); - // ie.x = x + v.x * 1.5; - ie->y = y + bbHeight / 2 + 0.5f; - // ie.z = z + v.z * 1.5; - level->addEntity(ie); - } - } - - } - yRot = (float) (atan2(zd, xd) * 180 / PI) - 90; - - holdGround = true; - } -} - -void Blaze::causeFallDamage(float distance) -{ -} - -int Blaze::getDeathLoot() -{ - return Item::blazeRod_Id; -} - -bool Blaze::isOnFire() -{ - return isCharged(); -} - -void Blaze::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - if (wasKilledByPlayer) - { - int count = random->nextInt(2 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::blazeRod_Id, 1); - } - // 4J-PB - added to the XBLA version due to our limited amount of glowstone in the Nether - drop 0-2 glowstone dust - count = random->nextInt(3 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::yellowDust_Id, 1); - } - } -} - -bool Blaze::isCharged() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x1) != 0; -} - -void Blaze::setCharged(bool value) -{ - uint8_t flags = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - flags |= 0x1; - } - else - { - flags &= ~0x1; - } - entityData->set(DATA_FLAGS_ID, flags); -} - -bool Blaze::isDarkEnoughToSpawn() -{ - return true; -} \ No newline at end of file +bool Blaze::isDarkEnoughToSpawn() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Blaze.h b/Minecraft.World/Entities/Mobs/Blaze.h index 2ac4b89b3..3770bd87e 100644 --- a/Minecraft.World/Entities/Mobs/Blaze.h +++ b/Minecraft.World/Entities/Mobs/Blaze.h @@ -2,50 +2,49 @@ #include "../Monster.h" -class Blaze : public Monster -{ +class Blaze : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_BLAZE; } - static Entity *create(Level *level) { return new Blaze(level); } + eINSTANCEOF GetType() { return eTYPE_BLAZE; } + static Entity* create(Level* level) { return new Blaze(level); } - // private int nextBurnNeighborsTick; + // private int nextBurnNeighborsTick; private: - float allowedHeightOffset; - int nextHeightOffsetChangeTick; - int attackCounter; + float allowedHeightOffset; + int nextHeightOffsetChangeTick; + int attackCounter; - static const int DATA_FLAGS_ID = 16; + static const int DATA_FLAGS_ID = 16; public: - Blaze(Level *level); - virtual int getMaxHealth(); + Blaze(Level* level); + virtual int getMaxHealth(); protected: - virtual void defineSynchedData(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual void defineSynchedData(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - virtual int getLightColor(float a); - virtual float getBrightness(float a); - virtual void aiStep(); + virtual int getLightColor(float a); + virtual float getBrightness(float a); + virtual void aiStep(); protected: - virtual void checkHurtTarget(std::shared_ptr target, float d); - virtual void causeFallDamage(float distance); - virtual int getDeathLoot(); + virtual void checkHurtTarget(std::shared_ptr target, float d); + virtual void causeFallDamage(float distance); + virtual int getDeathLoot(); public: - virtual bool isOnFire(); + virtual bool isOnFire(); protected: - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - bool isCharged(); - void setCharged(bool value); + bool isCharged(); + void setCharged(bool value); protected: - bool isDarkEnoughToSpawn(); + bool isDarkEnoughToSpawn(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Boat.cpp b/Minecraft.World/Entities/Mobs/Boat.cpp index 7a9b84322..127e88e3e 100644 --- a/Minecraft.World/Entities/Mobs/Boat.cpp +++ b/Minecraft.World/Entities/Mobs/Boat.cpp @@ -16,504 +16,406 @@ const double Boat::MIN_ACCELERATION = 0.07; const double Boat::MAX_ACCELERATION = 0.35; // 4J - added for common ctor code -void Boat::_init() -{ - doLerp = true; - acceleration = MIN_ACCELERATION; +void Boat::_init() { + doLerp = true; + acceleration = MIN_ACCELERATION; - lSteps = 0; - lx = ly = lz = lyr = lxr = 0.0; - lxd = lyd = lzd = 0.0; + lSteps = 0; + lx = ly = lz = lyr = lxr = 0.0; + lxd = lyd = lzd = 0.0; - blocksBuilding = true; - setSize(1.5f, 0.6f); - heightOffset = bbHeight / 2.0f; + blocksBuilding = true; + setSize(1.5f, 0.6f); + heightOffset = bbHeight / 2.0f; - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } +Boat::Boat(Level* level) : Entity(level) { _init(); } +bool Boat::makeStepSound() { return false; } -Boat::Boat(Level *level) : Entity( level ) -{ - - _init(); +void Boat::defineSynchedData() { + entityData->define(DATA_ID_HURT, 0); + entityData->define(DATA_ID_HURTDIR, 1); + entityData->define(DATA_ID_DAMAGE, 0); } - -bool Boat::makeStepSound() -{ - return false; +AABB* Boat::getCollideAgainstBox(std::shared_ptr entity) { + return entity->bb; } -void Boat::defineSynchedData() -{ - entityData->define(DATA_ID_HURT, 0); - entityData->define(DATA_ID_HURTDIR, 1); - entityData->define(DATA_ID_DAMAGE, 0); +AABB* Boat::getCollideBox() { return bb; } + +bool Boat::isPushable() { return true; } + +Boat::Boat(Level* level, double x, double y, double z) : Entity(level) { + _init(); + setPos(x, y + heightOffset, z); + + xd = 0; + yd = 0; + zd = 0; + + xo = x; + yo = y; + zo = z; } +double Boat::getRideHeight() { return bbHeight * 0.0f - 0.3f; } -AABB *Boat::getCollideAgainstBox(std::shared_ptr entity) -{ - return entity->bb; +bool Boat::hurt(DamageSource* source, int hurtDamage) { + if (level->isClientSide || removed) return true; + + // 4J-JEV: Fix for #88212, + // Untrusted players shouldn't be able to damage minecarts or boats. + if (dynamic_cast(source) != NULL) { + std::shared_ptr attacker = source->getDirectEntity(); + + if (std::dynamic_pointer_cast(attacker) != NULL && + !std::dynamic_pointer_cast(attacker)->isAllowedToHurtEntity( + shared_from_this())) + return false; + } + + setHurtDir(-getHurtDir()); + setHurtTime(10); + + // 4J Stu - If someone is riding in this, then it can tick multiple times + // which causes the damage to decrease too quickly. So just make the damage + // a bit higher to start with for similar behaviour to an unridden one. Only + // do this change if the riding player is attacking it. + if (rider.lock() != NULL && rider.lock() == source->getEntity()) + hurtDamage += 1; + + setDamage(getDamage() + hurtDamage * 10); + markHurt(); + + // 4J Stu - Brought froward from 12w36 to fix #46611 - TU5: Gameplay: + // Minecarts and boat requires more hits than one to be destroyed in + // creative mode + std::shared_ptr player = + std::dynamic_pointer_cast(source->getEntity()); + if (player != NULL && player->abilities.instabuild) setDamage(100); + + if (getDamage() > 20 * 2) { + if (rider.lock() != NULL) rider.lock()->ride(shared_from_this()); + spawnAtLocation(Item::boat_Id, 1, 0); + remove(); + } + return true; } -AABB *Boat::getCollideBox() -{ - return bb; +void Boat::animateHurt() { + setHurtDir(-getHurtDir()); + setHurtTime(10); + setDamage(getDamage() * 11); } -bool Boat::isPushable() -{ - return true; +bool Boat::isPickable() { return !removed; } + +void Boat::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + if (doLerp) { + lSteps = steps + 5; + } else { + double xdiff = x - this->x; + double ydiff = y - this->y; + double zdiff = z - this->z; + double diff = xdiff * xdiff + ydiff * ydiff + zdiff * zdiff; + + if (diff > 1) { + lSteps = 3; + } else { + return; + } + } + + lx = x; + ly = y; + lz = z; + lyr = yRot; + lxr = xRot; + + this->xd = lxd; + this->yd = lyd; + this->zd = lzd; } -Boat::Boat(Level *level, double x, double y, double z) : Entity( level ) -{ - _init(); - setPos(x, y + heightOffset, z); - - xd = 0; - yd = 0; - zd = 0; - - xo = x; - yo = y; - zo = z; +void Boat::lerpMotion(double xd, double yd, double zd) { + lxd = this->xd = xd; + lyd = this->yd = yd; + lzd = this->zd = zd; } -double Boat::getRideHeight() -{ - return bbHeight * 0.0f - 0.3f; -} +void Boat::tick() { + Entity::tick(); + if (getHurtTime() > 0) setHurtTime(getHurtTime() - 1); + if (getDamage() > 0) setDamage(getDamage() - 1); + xo = x; + yo = y; + zo = z; -bool Boat::hurt(DamageSource *source, int hurtDamage) -{ - if (level->isClientSide || removed) return true; + int steps = 5; + double waterPercentage = 0; + for (int i = 0; i < steps; i++) { + double y0 = bb->y0 + (bb->y1 - bb->y0) * (i + 0) / steps - 2 / 16.0f; + double y1 = bb->y0 + (bb->y1 - bb->y0) * (i + 1) / steps - 2 / 16.0f; + AABB* bb2 = AABB::newTemp(bb->x0, y0, bb->z0, bb->x1, y1, bb->z1); + if (level->containsLiquid(bb2, Material::water)) { + waterPercentage += 1.0 / steps; + } + } - // 4J-JEV: Fix for #88212, - // Untrusted players shouldn't be able to damage minecarts or boats. - if (dynamic_cast(source) != NULL) - { - std::shared_ptr attacker = source->getDirectEntity(); + double lastSpeed = sqrt(xd * xd + zd * zd); + if (lastSpeed > MAX_COLLISION_SPEED) { + double xa = cos(yRot * PI / 180); + double za = sin(yRot * PI / 180); - if (std::dynamic_pointer_cast(attacker) != NULL && - !std::dynamic_pointer_cast(attacker)->isAllowedToHurtEntity( shared_from_this() )) - return false; - } + for (int i = 0; i < 1 + lastSpeed * 60; i++) { + double side = (random->nextFloat() * 2 - 1); - setHurtDir(-getHurtDir()); - setHurtTime(10); + double side2 = (random->nextInt(2) * 2 - 1) * 0.7; + if (random->nextBoolean()) { + double xx = x - xa * side * 0.8 + za * side2; + double zz = z - za * side * 0.8 - xa * side2; + level->addParticle(eParticleType_splash, xx, y - 2 / 16.0f, zz, + +xd, yd, +zd); + } else { + double xx = x + xa + za * side * 0.7; + double zz = z + za - xa * side * 0.7; + level->addParticle(eParticleType_splash, xx, y - 2 / 16.0f, zz, + +xd, yd, +zd); + } + } + } - // 4J Stu - If someone is riding in this, then it can tick multiple times which causes the damage to - // decrease too quickly. So just make the damage a bit higher to start with for similar behaviour - // to an unridden one. Only do this change if the riding player is attacking it. - if( rider.lock() != NULL && rider.lock() == source->getEntity() ) hurtDamage += 1; + if (level->isClientSide && doLerp) { + if (lSteps > 0) { + double xt = x + (lx - x) / lSteps; + double yt = y + (ly - y) / lSteps; + double zt = z + (lz - z) / lSteps; - setDamage(getDamage() + hurtDamage * 10); - markHurt(); + double yrd = Mth::wrapDegrees(lyr - yRot); - // 4J Stu - Brought froward from 12w36 to fix #46611 - TU5: Gameplay: Minecarts and boat requires more hits than one to be destroyed in creative mode - std::shared_ptr player = std::dynamic_pointer_cast(source->getEntity()); - if (player != NULL && player->abilities.instabuild) setDamage(100); + yRot += (float)((yrd) / lSteps); + xRot += (float)((lxr - xRot) / lSteps); - if (getDamage() > 20 * 2) - { - if (rider.lock() != NULL) rider.lock()->ride( shared_from_this() ); - spawnAtLocation(Item::boat_Id, 1, 0); - remove(); - } - return true; -} - -void Boat::animateHurt() -{ - setHurtDir(-getHurtDir()); - setHurtTime(10); - setDamage(getDamage() * 11); -} - -bool Boat::isPickable() -{ - return !removed; -} - - -void Boat::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - if (doLerp) - { - lSteps = steps + 5; - } - else - { - double xdiff = x - this->x; - double ydiff = y - this->y; - double zdiff = z - this->z; - double diff = xdiff * xdiff + ydiff * ydiff + zdiff * zdiff; - - if (diff > 1) - { - lSteps = 3; - } - else - { - return; - } - } - - lx = x; - ly = y; - lz = z; - lyr = yRot; - lxr = xRot; - - this->xd = lxd; - this->yd = lyd; - this->zd = lzd; -} - -void Boat::lerpMotion(double xd, double yd, double zd) -{ - lxd = this->xd = xd; - lyd = this->yd = yd; - lzd = this->zd = zd; -} - -void Boat::tick() -{ - Entity::tick(); - if (getHurtTime() > 0) setHurtTime(getHurtTime() - 1); - if (getDamage() > 0) setDamage(getDamage() - 1); - xo = x; - yo = y; - zo = z; - - - int steps = 5; - double waterPercentage = 0; - for (int i = 0; i < steps; i++) - { - double y0 = bb->y0 + (bb->y1 - bb->y0) * (i + 0) / steps - 2 / 16.0f; - double y1 = bb->y0 + (bb->y1 - bb->y0) * (i + 1) / steps - 2 / 16.0f; - AABB *bb2 = AABB::newTemp(bb->x0, y0, bb->z0, bb->x1, y1, bb->z1); - if (level->containsLiquid(bb2, Material::water)) - { - waterPercentage += 1.0 / steps; - } - } - - double lastSpeed = sqrt(xd * xd + zd * zd); - if (lastSpeed > MAX_COLLISION_SPEED) - { - double xa = cos(yRot * PI / 180); - double za = sin(yRot * PI / 180); - - for (int i = 0; i < 1 + lastSpeed * 60; i++) - { - - double side = (random->nextFloat() * 2 - 1); - - double side2 = (random->nextInt(2) * 2 - 1) * 0.7; - if (random->nextBoolean()) - { - double xx = x - xa * side * 0.8 + za * side2; - double zz = z - za * side * 0.8 - xa * side2; - level->addParticle(eParticleType_splash, xx, y - 2 / 16.0f, zz, +xd, yd, +zd); - } - else - { - double xx = x + xa + za * side * 0.7; - double zz = z + za - xa * side * 0.7; - level->addParticle(eParticleType_splash, xx, y - 2 / 16.0f, zz, +xd, yd, +zd); - } - } - } - - if (level->isClientSide && doLerp) - { - if (lSteps > 0) - { - double xt = x + (lx - x) / lSteps; - double yt = y + (ly - y) / lSteps; - double zt = z + (lz - z) / lSteps; - - double yrd = Mth::wrapDegrees(lyr - yRot); - - yRot += (float) ( (yrd) / lSteps ); - xRot += (float) ( (lxr - xRot) / lSteps ); - - lSteps--; - this->setPos(xt, yt, zt); - this->setRot(yRot, xRot); - } - else - { + lSteps--; + this->setPos(xt, yt, zt); + this->setRot(yRot, xRot); + } else { #if 1 - // Original - //double xt = x + xd; - //double yt = y + yd; - //double zt = z + zd; - //this->setPos(xt, yt, zt); + // Original + // double xt = x + xd; + // double yt = y + yd; + // double zt = z + zd; + // this->setPos(xt, yt, zt); - // 4J Stu - Fix for various boat bugs, ensure that we check collision on client-side movement - this->move(xd,yd,zd); + // 4J Stu - Fix for various boat bugs, ensure that we check + // collision on client-side movement + this->move(xd, yd, zd); - if (onGround) - { - xd *= 0.5f; - yd *= 0.5f; - zd *= 0.5f; - } - xd *= 0.99f; - yd *= 0.95f; - zd *= 0.99f; + if (onGround) { + xd *= 0.5f; + yd *= 0.5f; + zd *= 0.5f; + } + xd *= 0.99f; + yd *= 0.95f; + zd *= 0.99f; #else - // 4J Stu - Fix for #8280 - Gameplay : Boats behave erratically when exited next to land. - // The client shouldn't change the position of the boat - double xt = x;// + xd; - double yt = y + yd; - double zt = z;// + zd; - this->setPos(xt, yt, zt); + // 4J Stu - Fix for #8280 - Gameplay : Boats behave erratically when + // exited next to land. The client shouldn't change the position of + // the boat + double xt = x; // + xd; + double yt = y + yd; + double zt = z; // + zd; + this->setPos(xt, yt, zt); - // 4J Stu - Fix for #9579 - GAMEPLAY: Boats with a player in them slowly sink under the water over time, and with no player in them they float into the sky. - // Just make the boats bob up and down rather than any other client-side movement when not receiving packets from server - if (waterPercentage < 1) - { - double bob = waterPercentage * 2 - 1; - yd += 0.04f * bob; - } - else - { - if (yd < 0) yd /= 2; - yd += 0.007f; - } - //if (onGround) - //{ - xd *= 0.5f; - yd *= 0.5f; - zd *= 0.5f; - //} - //xd *= 0.99f; - //yd *= 0.95f; - //zd *= 0.99f; + // 4J Stu - Fix for #9579 - GAMEPLAY: Boats with a player in them + // slowly sink under the water over time, and with no player in them + // they float into the sky. Just make the boats bob up and down + // rather than any other client-side movement when not receiving + // packets from server + if (waterPercentage < 1) { + double bob = waterPercentage * 2 - 1; + yd += 0.04f * bob; + } else { + if (yd < 0) yd /= 2; + yd += 0.007f; + } + // if (onGround) + //{ + xd *= 0.5f; + yd *= 0.5f; + zd *= 0.5f; + //} + // xd *= 0.99f; + // yd *= 0.95f; + // zd *= 0.99f; #endif - } - return; - } + } + return; + } - if (waterPercentage < 1) - { - double bob = waterPercentage * 2 - 1; - yd += 0.04f * bob; - } - else - { - if (yd < 0) yd /= 2; - yd += 0.007f; - } + if (waterPercentage < 1) { + double bob = waterPercentage * 2 - 1; + yd += 0.04f * bob; + } else { + if (yd < 0) yd /= 2; + yd += 0.007f; + } + if (rider.lock() != NULL) { + xd += rider.lock()->xd * acceleration; + zd += rider.lock()->zd * acceleration; + } - if (rider.lock() != NULL) - { - xd += rider.lock()->xd * acceleration; - zd += rider.lock()->zd * acceleration; - } + double curSpeed = sqrt(xd * xd + zd * zd); - double curSpeed = sqrt(xd * xd + zd * zd); + if (curSpeed > MAX_SPEED) { + double ratio = MAX_SPEED / curSpeed; - if (curSpeed > MAX_SPEED) - { - double ratio = MAX_SPEED / curSpeed; + xd *= ratio; + zd *= ratio; + curSpeed = MAX_SPEED; + } - xd *= ratio; - zd *= ratio; - curSpeed = MAX_SPEED; - } + if (curSpeed > lastSpeed && acceleration < MAX_ACCELERATION) { + acceleration += (MAX_ACCELERATION - acceleration) / 35; + if (acceleration > MAX_ACCELERATION) acceleration = MAX_ACCELERATION; + } else { + acceleration -= (acceleration - MIN_ACCELERATION) / 35; + if (acceleration < MIN_ACCELERATION) acceleration = MIN_ACCELERATION; + } - if (curSpeed > lastSpeed && acceleration < MAX_ACCELERATION) - { - acceleration += (MAX_ACCELERATION - acceleration) / 35; - if (acceleration > MAX_ACCELERATION) acceleration = MAX_ACCELERATION; - } - else - { - acceleration -= (acceleration - MIN_ACCELERATION) / 35; - if (acceleration < MIN_ACCELERATION) acceleration = MIN_ACCELERATION; - } + if (onGround) { + xd *= 0.5f; + yd *= 0.5f; + zd *= 0.5f; + } + move(xd, yd, zd); - if (onGround) - { - xd *= 0.5f; - yd *= 0.5f; - zd *= 0.5f; - } - move(xd, yd, zd); + if ((horizontalCollision && lastSpeed > 0.20)) { + if (!level->isClientSide) { + remove(); + for (int i = 0; i < 3; i++) { + spawnAtLocation(Tile::wood_Id, 1, 0); + } + for (int i = 0; i < 2; i++) { + spawnAtLocation(Item::stick->id, 1, 0); + } + } + } else { + xd *= 0.99f; + yd *= 0.95f; + zd *= 0.99f; + } - if ((horizontalCollision && lastSpeed > 0.20)) - { - if (!level->isClientSide) - { - remove(); - for (int i = 0; i < 3; i++) - { - spawnAtLocation(Tile::wood_Id, 1, 0); - } - for (int i = 0; i < 2; i++) - { - spawnAtLocation(Item::stick->id, 1, 0); - } - } - } - else - { - xd *= 0.99f; - yd *= 0.95f; - zd *= 0.99f; - } + xRot = 0; + double yRotT = yRot; + double xDiff = xo - x; + double zDiff = zo - z; + if (xDiff * xDiff + zDiff * zDiff > 0.001) { + yRotT = (float)(atan2(zDiff, xDiff) * 180 / PI); + } - xRot = 0; - double yRotT = yRot; - double xDiff = xo - x; - double zDiff = zo - z; - if (xDiff * xDiff + zDiff * zDiff > 0.001) - { - yRotT = (float) (atan2(zDiff, xDiff) * 180 / PI); - } + double rotDiff = Mth::wrapDegrees(yRotT - yRot); - double rotDiff = Mth::wrapDegrees(yRotT - yRot); + if (rotDiff > 20) rotDiff = 20; + if (rotDiff < -20) rotDiff = -20; - if (rotDiff > 20) rotDiff = 20; - if (rotDiff < -20) rotDiff = -20; + yRot += (float)rotDiff; + setRot(yRot, xRot); - yRot += (float) rotDiff; - setRot(yRot, xRot); + if (level->isClientSide) return; - if(level->isClientSide) return; + std::vector >* entities = + level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); + if (entities != NULL && !entities->empty()) { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = (*it); // entities->at(i); + if (e != rider.lock() && e->isPushable() && + e->GetType() == eTYPE_BOAT) { + e->push(shared_from_this()); + } + } + } - std::vector > *entities = level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) - { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = (*it); // entities->at(i); - if (e != rider.lock() && e->isPushable() && e->GetType() == eTYPE_BOAT) - { - e->push(shared_from_this()); - } - } - } + for (int i = 0; i < 4; i++) { + int xx = Mth::floor(x + ((i % 2) - 0.5) * 0.8); + int zz = Mth::floor(z + ((i / 2) - 0.5) * 0.8); - for (int i = 0; i < 4; i++) - { - int xx = Mth::floor(x + ((i % 2) - 0.5) * 0.8); - int zz = Mth::floor(z + ((i / 2) - 0.5) * 0.8); + for (int j = 0; j < 2; j++) { + int yy = Mth::floor(y) + j; + int tile = level->getTile(xx, yy, zz); + int data = level->getData(xx, yy, zz); - for (int j = 0; j < 2; j++) - { - int yy = Mth::floor(y) + j; - int tile = level->getTile(xx, yy, zz); - int data = level->getData(xx, yy, zz); + if (tile == Tile::topSnow_Id) { + level->setTile(xx, yy, zz, 0); + } else if (tile == Tile::waterLily_Id) { + Tile::waterLily->spawnResources(level, xx, yy, zz, data, 0.3f, + 0); + level->setTile(xx, yy, zz, 0); + } + } + } - if (tile == Tile::topSnow_Id) - { - level->setTile(xx, yy, zz, 0); - } - else if (tile == Tile::waterLily_Id) - { - Tile::waterLily->spawnResources(level, xx, yy, zz, data, 0.3f, 0); - level->setTile(xx, yy, zz, 0); - } - } - - } - - if (rider.lock() != NULL) - { - if (rider.lock()->removed) rider = std::weak_ptr(); - } + if (rider.lock() != NULL) { + if (rider.lock()->removed) rider = std::weak_ptr(); + } } -void Boat::positionRider() -{ - if (rider.lock() == NULL) return; +void Boat::positionRider() { + if (rider.lock() == NULL) return; - double xa = cos(yRot * PI / 180) * 0.4; - double za = sin(yRot * PI / 180) * 0.4; - rider.lock()->setPos(x + xa, y + getRideHeight() + rider.lock()->getRidingHeight(), z + za); + double xa = cos(yRot * PI / 180) * 0.4; + double za = sin(yRot * PI / 180) * 0.4; + rider.lock()->setPos( + x + xa, y + getRideHeight() + rider.lock()->getRidingHeight(), z + za); } +void Boat::addAdditonalSaveData(CompoundTag* base) {} -void Boat::addAdditonalSaveData(CompoundTag *base) -{ +void Boat::readAdditionalSaveData(CompoundTag* base) {} + +float Boat::getShadowHeightOffs() { return 0; } + +std::wstring Boat::getName() { return L"Boat"; } + +bool Boat::interact(std::shared_ptr player) { + if (rider.lock() != NULL && + std::dynamic_pointer_cast(rider.lock()) != NULL && + rider.lock() != player) + return true; + if (!level->isClientSide) { + // 4J HEG - Fixed issue with player not being able to dismount boat + // (issue #4446) + player->ride(rider.lock() == player ? nullptr : shared_from_this()); + } + return true; } -void Boat::readAdditionalSaveData(CompoundTag *base) -{ +void Boat::setDamage(int damage) { entityData->set(DATA_ID_DAMAGE, damage); } + +int Boat::getDamage() { return entityData->getInteger(DATA_ID_DAMAGE); } + +void Boat::setHurtTime(int hurtTime) { + entityData->set(DATA_ID_HURT, hurtTime); } +int Boat::getHurtTime() { return entityData->getInteger(DATA_ID_HURT); } -float Boat::getShadowHeightOffs() -{ - return 0; +void Boat::setHurtDir(int hurtDir) { + entityData->set(DATA_ID_HURTDIR, hurtDir); } -std::wstring Boat::getName() -{ - return L"Boat"; -} +int Boat::getHurtDir() { return entityData->getInteger(DATA_ID_HURTDIR); } -bool Boat::interact(std::shared_ptr player) -{ - if (rider.lock() != NULL && std::dynamic_pointer_cast(rider.lock())!=NULL && rider.lock() != player) return true; - if (!level->isClientSide) - { - // 4J HEG - Fixed issue with player not being able to dismount boat (issue #4446) - player->ride( rider.lock() == player ? nullptr : shared_from_this() ); - } - return true; -} +bool Boat::getDoLerp() { return doLerp; } -void Boat::setDamage(int damage) -{ - entityData->set(DATA_ID_DAMAGE, damage); -} - -int Boat::getDamage() -{ - return entityData->getInteger(DATA_ID_DAMAGE); -} - -void Boat::setHurtTime(int hurtTime) -{ - entityData->set(DATA_ID_HURT, hurtTime); -} - -int Boat::getHurtTime() -{ - return entityData->getInteger(DATA_ID_HURT); -} - -void Boat::setHurtDir(int hurtDir) -{ - entityData->set(DATA_ID_HURTDIR, hurtDir); -} - -int Boat::getHurtDir() -{ - return entityData->getInteger(DATA_ID_HURTDIR); -} - -bool Boat::getDoLerp() -{ - return doLerp; -} - -void Boat::setDoLerp(bool doLerp) -{ - this->doLerp = doLerp; -} +void Boat::setDoLerp(bool doLerp) { this->doLerp = doLerp; } diff --git a/Minecraft.World/Entities/Mobs/Boat.h b/Minecraft.World/Entities/Mobs/Boat.h index f0bc81959..14f61751d 100644 --- a/Minecraft.World/Entities/Mobs/Boat.h +++ b/Minecraft.World/Entities/Mobs/Boat.h @@ -1,6 +1,5 @@ #pragma once - #include "../Entity.h" class Player; @@ -8,76 +7,77 @@ class Level; class CompoundTag; class DamageSource; -class Boat : public Entity -{ +class Boat : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_BOAT; }; - static Entity *create(Level *level) { return new Boat(level); } + eINSTANCEOF GetType() { return eTYPE_BOAT; }; + static Entity* create(Level* level) { return new Boat(level); } private: - // 4J - added for common ctor code - void _init(); + // 4J - added for common ctor code + void _init(); + public: - static const int serialVersionUID = 0; + static const int serialVersionUID = 0; private: - static const int DATA_ID_HURT = 17; - static const int DATA_ID_HURTDIR = 18; - static const int DATA_ID_DAMAGE = 19; - static const double MAX_SPEED; - static const double MAX_COLLISION_SPEED; - static const double MIN_ACCELERATION; - static const double MAX_ACCELERATION; + static const int DATA_ID_HURT = 17; + static const int DATA_ID_HURTDIR = 18; + static const int DATA_ID_DAMAGE = 19; + static const double MAX_SPEED; + static const double MAX_COLLISION_SPEED; + static const double MIN_ACCELERATION; + static const double MAX_ACCELERATION; - bool doLerp; - double acceleration; + bool doLerp; + double acceleration; public: - Boat(Level *level); + Boat(Level* level); protected: - virtual bool makeStepSound(); - virtual void defineSynchedData(); + virtual bool makeStepSound(); + virtual void defineSynchedData(); public: - virtual AABB *getCollideAgainstBox(std::shared_ptr entity); - virtual AABB *getCollideBox(); - virtual bool isPushable(); + virtual AABB* getCollideAgainstBox(std::shared_ptr entity); + virtual AABB* getCollideBox(); + virtual bool isPushable(); - Boat(Level *level, double x, double y, double z); + Boat(Level* level, double x, double y, double z); - virtual double getRideHeight(); - virtual bool hurt(DamageSource *source, int damage); - virtual void animateHurt(); - virtual bool isPickable(); + virtual double getRideHeight(); + virtual bool hurt(DamageSource* source, int damage); + virtual void animateHurt(); + virtual bool isPickable(); private: - int lSteps; - double lx, ly, lz, lyr, lxr; - double lxd, lyd, lzd; + int lSteps; + double lx, ly, lz, lyr, lxr; + double lxd, lyd, lzd; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); - virtual void lerpMotion(double xd, double yd, double zd); - virtual void tick(); - virtual void positionRider(); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); + virtual void lerpMotion(double xd, double yd, double zd); + virtual void tick(); + virtual void positionRider(); protected: - virtual void addAdditonalSaveData(CompoundTag *base); - virtual void readAdditionalSaveData(CompoundTag *base); + virtual void addAdditonalSaveData(CompoundTag* base); + virtual void readAdditionalSaveData(CompoundTag* base); public: - virtual float getShadowHeightOffs(); - std::wstring getName(); - virtual bool interact(std::shared_ptr player); + virtual float getShadowHeightOffs(); + std::wstring getName(); + virtual bool interact(std::shared_ptr player); - virtual void setDamage(int damage); - virtual int getDamage(); - virtual void setHurtTime(int hurtTime); - virtual int getHurtTime(); - virtual void setHurtDir(int hurtDir); - virtual int getHurtDir(); + virtual void setDamage(int damage); + virtual int getDamage(); + virtual void setHurtTime(int hurtTime); + virtual int getHurtTime(); + virtual void setHurtDir(int hurtDir); + virtual int getHurtDir(); - bool getDoLerp(); - void setDoLerp(bool doLerp); + bool getDoLerp(); + void setDoLerp(bool doLerp); }; diff --git a/Minecraft.World/Entities/Mobs/BossMob.cpp b/Minecraft.World/Entities/Mobs/BossMob.cpp index 39ca70e4d..a93129cf3 100644 --- a/Minecraft.World/Entities/Mobs/BossMob.cpp +++ b/Minecraft.World/Entities/Mobs/BossMob.cpp @@ -2,35 +2,23 @@ #include "../BossMobPart.h" #include "BossMob.h" +BossMob::BossMob(Level* level) : Mob(level) { + maxHealth = 100; - -BossMob::BossMob(Level *level) : Mob( level ) -{ - - maxHealth = 100; - - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); } -int BossMob::getMaxHealth() -{ - return maxHealth; +int BossMob::getMaxHealth() { return maxHealth; } + +bool BossMob::hurt(std::shared_ptr bossMobPart, + DamageSource* source, int damage) { + return hurt(source, damage); } -bool BossMob::hurt(std::shared_ptr bossMobPart, DamageSource *source, int damage) -{ - return hurt(source, damage); -} - -bool BossMob::hurt(DamageSource *source, int damage) -{ - return false; -} - -bool BossMob::reallyHurt(DamageSource *source, int damage) -{ - - return Mob::hurt(source, damage); +bool BossMob::hurt(DamageSource* source, int damage) { return false; } +bool BossMob::reallyHurt(DamageSource* source, int damage) { + return Mob::hurt(source, damage); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/BossMob.h b/Minecraft.World/Entities/Mobs/BossMob.h index 2ed072f0f..b53d92021 100644 --- a/Minecraft.World/Entities/Mobs/BossMob.h +++ b/Minecraft.World/Entities/Mobs/BossMob.h @@ -5,18 +5,18 @@ class Level; class BossMobPart; -class BossMob : public Mob -{ +class BossMob : public Mob { protected: - int maxHealth; + int maxHealth; public: - BossMob(Level *level); + BossMob(Level* level); - virtual int getMaxHealth(); - virtual bool hurt(std::shared_ptr bossMobPart, DamageSource *source, int damage); - virtual bool hurt(DamageSource *source, int damage); + virtual int getMaxHealth(); + virtual bool hurt(std::shared_ptr bossMobPart, + DamageSource* source, int damage); + virtual bool hurt(DamageSource* source, int damage); protected: - virtual bool reallyHurt(DamageSource *source, int damage); + virtual bool reallyHurt(DamageSource* source, int damage); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/CaveSpider.cpp b/Minecraft.World/Entities/Mobs/CaveSpider.cpp index a52d5254f..68d87fb52 100644 --- a/Minecraft.World/Entities/Mobs/CaveSpider.cpp +++ b/Minecraft.World/Entities/Mobs/CaveSpider.cpp @@ -6,59 +6,44 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "CaveSpider.h" +CaveSpider::CaveSpider(Level* level) : Spider(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - -CaveSpider::CaveSpider(Level *level) : Spider(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_CAVE_SPIDER; // 4J was "/mob/cavespider.png"; - this->setSize(0.7f, 0.5f); + this->textureIdx = TN_MOB_CAVE_SPIDER; // 4J was "/mob/cavespider.png"; + this->setSize(0.7f, 0.5f); } -int CaveSpider::getMaxHealth() -{ - return 12; +int CaveSpider::getMaxHealth() { return 12; } + +float CaveSpider::getModelScale() { return .7f; } + +bool CaveSpider::doHurtTarget(std::shared_ptr target) { + if (Spider::doHurtTarget(target)) { + if (std::dynamic_pointer_cast(target) != NULL) { + int poisonTime = 0; + if (level->difficulty <= Difficulty::EASY) { + // No poison! + } else if (level->difficulty == Difficulty::NORMAL) { + poisonTime = 7; + } else if (level->difficulty == Difficulty::HARD) { + poisonTime = 15; + } + + if (poisonTime > 0) { + std::dynamic_pointer_cast(target)->addEffect( + new MobEffectInstance( + MobEffect::poison->id, + poisonTime * SharedConstants::TICKS_PER_SECOND, 0)); + } + } + + return true; + } + return false; } -float CaveSpider::getModelScale() -{ - return .7f; -} - - -bool CaveSpider::doHurtTarget(std::shared_ptr target) -{ - if (Spider::doHurtTarget(target)) - { - if ( std::dynamic_pointer_cast(target) != NULL) - { - int poisonTime = 0; - if (level->difficulty <= Difficulty::EASY) - { - // No poison! - } - else if (level->difficulty == Difficulty::NORMAL) - { - poisonTime = 7; - } - else if (level->difficulty == Difficulty::HARD) - { - poisonTime = 15; - } - - if (poisonTime > 0) { - std::dynamic_pointer_cast(target)->addEffect(new MobEffectInstance(MobEffect::poison->id, poisonTime * SharedConstants::TICKS_PER_SECOND, 0)); - } - } - - return true; - } - return false; -} - -void CaveSpider::finalizeMobSpawn() -{ - // do nothing +void CaveSpider::finalizeMobSpawn() { + // do nothing } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/CaveSpider.h b/Minecraft.World/Entities/Mobs/CaveSpider.h index de9cf370c..9bda83e3c 100644 --- a/Minecraft.World/Entities/Mobs/CaveSpider.h +++ b/Minecraft.World/Entities/Mobs/CaveSpider.h @@ -2,17 +2,16 @@ #include "Spider.h" -class CaveSpider : public Spider -{ - public: - eINSTANCEOF GetType() { return eTYPE_CAVESPIDER; } - static Entity *create(Level *level) { return new CaveSpider(level); } +class CaveSpider : public Spider { +public: + eINSTANCEOF GetType() { return eTYPE_CAVESPIDER; } + static Entity* create(Level* level) { return new CaveSpider(level); } - public: - CaveSpider(Level *level); +public: + CaveSpider(Level* level); - virtual int getMaxHealth(); - virtual float getModelScale(); - virtual bool doHurtTarget(std::shared_ptr target); - void finalizeMobSpawn(); + virtual int getMaxHealth(); + virtual float getModelScale(); + virtual bool doHurtTarget(std::shared_ptr target); + void finalizeMobSpawn(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Chicken.cpp b/Minecraft.World/Entities/Mobs/Chicken.cpp index d962ee501..be8cf5c60 100644 --- a/Minecraft.World/Entities/Mobs/Chicken.cpp +++ b/Minecraft.World/Entities/Mobs/Chicken.cpp @@ -10,141 +10,112 @@ #include "../../Util/SoundTypes.h" #include "../MobCategory.h" -void Chicken::_init() -{ - sheared = false; - flap = 0; - flapSpeed = 0; - flapping = 1; - oFlapSpeed = oFlap = 0.0f; - eggTime = 0; +void Chicken::_init() { + sheared = false; + flap = 0; + flapSpeed = 0; + flapping = 1; + oFlapSpeed = oFlap = 0.0f; + eggTime = 0; } -Chicken::Chicken(Level *level) : Animal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - this->defineSynchedData(); +Chicken::Chicken(Level* level) : Animal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - _init(); - this->textureIdx = TN_MOB_CHICKEN; // 4J - was L"/mob/chicken.png"; - this->setSize(0.3f, 0.7f); // 4J Changed from 0.4 to 0.7 in 1.8.2 - eggTime = random->nextInt(20 * 60 * 5) + 20 * 60 * 5; + _init(); + this->textureIdx = TN_MOB_CHICKEN; // 4J - was L"/mob/chicken.png"; + this->setSize(0.3f, 0.7f); // 4J Changed from 0.4 to 0.7 in 1.8.2 + eggTime = random->nextInt(20 * 60 * 5) + 20 * 60 * 5; - float walkSpeed = 0.25f; - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); - goalSelector.addGoal(2, new BreedGoal(this, walkSpeed)); - goalSelector.addGoal(3, new TemptGoal(this, 0.25f, Item::seeds_wheat_Id, false)); - goalSelector.addGoal(4, new FollowParentGoal(this, 0.28f)); - goalSelector.addGoal(5, new RandomStrollGoal(this, walkSpeed)); - goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(7, new RandomLookAroundGoal(this)); + float walkSpeed = 0.25f; + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); + goalSelector.addGoal(2, new BreedGoal(this, walkSpeed)); + goalSelector.addGoal( + 3, new TemptGoal(this, 0.25f, Item::seeds_wheat_Id, false)); + goalSelector.addGoal(4, new FollowParentGoal(this, 0.28f)); + goalSelector.addGoal(5, new RandomStrollGoal(this, walkSpeed)); + goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(7, new RandomLookAroundGoal(this)); } -bool Chicken::useNewAi() -{ - return true; +bool Chicken::useNewAi() { return true; } + +int Chicken::getMaxHealth() { return 4; } + +void Chicken::aiStep() { + Animal::aiStep(); + + oFlap = flap; + oFlapSpeed = flapSpeed; + + flapSpeed += (onGround ? -1 : 4) * 0.3f; + if (flapSpeed < 0) flapSpeed = 0; + if (flapSpeed > 1) flapSpeed = 1; + + if (!onGround && flapping < 1) flapping = 1; + flapping *= 0.9; + + if (!onGround && yd < 0) { + yd *= 0.6; + } + + flap += flapping * 2; + + if (!isBaby()) { + if (!level->isClientSide && --eggTime <= 0) { + level->playSound( + shared_from_this(), eSoundType_MOB_CHICKENPLOP, 1.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + spawnAtLocation(Item::egg->id, 1); + eggTime = random->nextInt(20 * 60 * 5) + 20 * 60 * 5; + } + } } -int Chicken::getMaxHealth() -{ - return 4; +void Chicken::causeFallDamage(float distance) {} + +int Chicken::getAmbientSound() { return eSoundType_MOB_CHICKEN_AMBIENT; } + +int Chicken::getHurtSound() { return eSoundType_MOB_CHICKEN_HURT; } + +int Chicken::getDeathSound() { return eSoundType_MOB_CHICKEN_HURT; } + +int Chicken::getDeathLoot() { return Item::feather->id; } + +void Chicken::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + // drop some feathers + int count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::feather_Id, 1); + } + // and some meat + if (this->isOnFire()) { + spawnAtLocation(Item::chicken_cooked_Id, 1); + } else { + spawnAtLocation(Item::chicken_raw_Id, 1); + } } -void Chicken::aiStep() -{ - Animal::aiStep(); - - oFlap = flap; - oFlapSpeed = flapSpeed; - - flapSpeed += (onGround ? -1 : 4) * 0.3f; - if (flapSpeed < 0) flapSpeed = 0; - if (flapSpeed > 1) flapSpeed = 1; - - if (!onGround && flapping < 1) flapping = 1; - flapping *= 0.9; - - if (!onGround && yd < 0) - { - yd *= 0.6; - } - - flap += flapping * 2; - - if (!isBaby()) - { - if (!level->isClientSide && --eggTime <= 0) - { - level->playSound(shared_from_this(), eSoundType_MOB_CHICKENPLOP, 1.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - spawnAtLocation(Item::egg->id, 1); - eggTime = random->nextInt(20 * 60 * 5) + 20 * 60 * 5; - } - } - +std::shared_ptr Chicken::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to chickens that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + return std::shared_ptr(new Chicken(level)); + } else { + return nullptr; + } } -void Chicken::causeFallDamage(float distance) -{ -} - - -int Chicken::getAmbientSound() -{ - return eSoundType_MOB_CHICKEN_AMBIENT; -} - -int Chicken::getHurtSound() -{ - return eSoundType_MOB_CHICKEN_HURT; -} - -int Chicken::getDeathSound() -{ - return eSoundType_MOB_CHICKEN_HURT; -} - -int Chicken::getDeathLoot() -{ - return Item::feather->id; -} - -void Chicken::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - // drop some feathers - int count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::feather_Id, 1); - } - // and some meat - if (this->isOnFire()) - { - spawnAtLocation(Item::chicken_cooked_Id, 1); - } - else - { - spawnAtLocation(Item::chicken_raw_Id, 1); - } -} - -std::shared_ptr Chicken::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to chickens that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - return std::shared_ptr(new Chicken(level)); - } - else - { - return nullptr; - } -} - -bool Chicken::isFood(std::shared_ptr itemInstance) -{ - return (itemInstance->id == Item::seeds_wheat_Id) || (itemInstance->id == Item::netherStalkSeeds_Id) || (itemInstance->id == Item::seeds_melon_Id) || (itemInstance->id == Item::seeds_pumpkin_Id); +bool Chicken::isFood(std::shared_ptr itemInstance) { + return (itemInstance->id == Item::seeds_wheat_Id) || + (itemInstance->id == Item::netherStalkSeeds_Id) || + (itemInstance->id == Item::seeds_melon_Id) || + (itemInstance->id == Item::seeds_pumpkin_Id); } diff --git a/Minecraft.World/Entities/Mobs/Chicken.h b/Minecraft.World/Entities/Mobs/Chicken.h index 49b4e368f..83b8a44f9 100644 --- a/Minecraft.World/Entities/Mobs/Chicken.h +++ b/Minecraft.World/Entities/Mobs/Chicken.h @@ -1,16 +1,14 @@ #pragma once - #include "Animal.h" class Level; class CompoundTag; -class Chicken : public Animal -{ +class Chicken : public Animal { public: - eINSTANCEOF GetType() { return eTYPE_CHICKEN; } - static Entity *create(Level *level) { return new Chicken(level); } + eINSTANCEOF GetType() { return eTYPE_CHICKEN; } + static Entity* create(Level* level) { return new Chicken(level); } bool sheared; float flap; float flapSpeed; @@ -18,25 +16,25 @@ public: float flapping; int eggTime; -private: - void _init(); +private: + void _init(); public: - Chicken(Level *level); - virtual bool useNewAi(); - virtual int getMaxHealth(); - virtual void aiStep(); + Chicken(Level* level); + virtual bool useNewAi(); + virtual int getMaxHealth(); + virtual void aiStep(); protected: - virtual void causeFallDamage(float distance); - virtual int getAmbientSound(); + virtual void causeFallDamage(float distance); + virtual int getAmbientSound(); virtual int getHurtSound(); virtual int getDeathSound(); virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); - virtual bool isFood(std::shared_ptr itemInstance); - + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); + virtual bool isFood(std::shared_ptr itemInstance); }; diff --git a/Minecraft.World/Entities/Mobs/Cow.cpp b/Minecraft.World/Entities/Mobs/Cow.cpp index 0d8719716..b759cb3fd 100644 --- a/Minecraft.World/Entities/Mobs/Cow.cpp +++ b/Minecraft.World/Entities/Mobs/Cow.cpp @@ -12,119 +12,87 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../MobCategory.h" +Cow::Cow(Level* level) : Animal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Cow::Cow(Level *level) : Animal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + this->textureIdx = TN_MOB_COW; // 4J was L"/mob/cow.png"; + this->setSize(0.9f, 1.3f); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_COW; // 4J was L"/mob/cow.png"; - this->setSize(0.9f, 1.3f); - - getNavigation()->setAvoidWater(true); - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); - goalSelector.addGoal(2, new BreedGoal(this, 0.2f)); - goalSelector.addGoal(3, new TemptGoal(this, 0.25f, Item::wheat_Id, false)); - goalSelector.addGoal(4, new FollowParentGoal(this, 0.25f)); - goalSelector.addGoal(5, new RandomStrollGoal(this, 0.2f)); - goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(7, new RandomLookAroundGoal(this)); + getNavigation()->setAvoidWater(true); + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); + goalSelector.addGoal(2, new BreedGoal(this, 0.2f)); + goalSelector.addGoal(3, new TemptGoal(this, 0.25f, Item::wheat_Id, false)); + goalSelector.addGoal(4, new FollowParentGoal(this, 0.25f)); + goalSelector.addGoal(5, new RandomStrollGoal(this, 0.2f)); + goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(7, new RandomLookAroundGoal(this)); } -bool Cow::useNewAi() -{ - return true; +bool Cow::useNewAi() { return true; } + +int Cow::getMaxHealth() { return 10; } + +int Cow::getAmbientSound() { return eSoundType_MOB_COW_AMBIENT; } + +int Cow::getHurtSound() { return eSoundType_MOB_COW_HURT; } + +int Cow::getDeathSound() { return eSoundType_MOB_COW_HURT; } + +float Cow::getSoundVolume() { return 0.4f; } + +int Cow::getDeathLoot() { return Item::leather->id; } + +void Cow::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + // drop some leather + int count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::leather_Id, 1); + } + // and some meat + count = random->nextInt(3) + 1 + random->nextInt(1 + playerBonusLevel); + for (int i = 0; i < count; i++) { + if (isOnFire()) { + spawnAtLocation(Item::beef_cooked_Id, 1); + } else { + spawnAtLocation(Item::beef_raw_Id, 1); + } + } } -int Cow::getMaxHealth() -{ - return 10; +bool Cow::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); + if (item != NULL && item->id == Item::bucket_empty->id) { + player->awardStat(GenericStats::cowsMilked(), + GenericStats::param_cowsMilked()); + + if (--item->count <= 0) { + player->inventory->setItem( + player->inventory->selected, + std::shared_ptr(new ItemInstance(Item::milk))); + } else if (!player->inventory->add(std::shared_ptr( + new ItemInstance(Item::milk)))) { + player->drop( + std::shared_ptr(new ItemInstance(Item::milk))); + } + + return true; + } + return Animal::interact(player); } -int Cow::getAmbientSound() -{ - return eSoundType_MOB_COW_AMBIENT; -} - -int Cow::getHurtSound() -{ - return eSoundType_MOB_COW_HURT; -} - -int Cow::getDeathSound() -{ - return eSoundType_MOB_COW_HURT; -} - -float Cow::getSoundVolume() -{ - return 0.4f; -} - -int Cow::getDeathLoot() -{ - return Item::leather->id; -} - -void Cow::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - // drop some leather - int count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::leather_Id, 1); - } - // and some meat - count = random->nextInt(3) + 1 + random->nextInt(1 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - if (isOnFire()) - { - spawnAtLocation(Item::beef_cooked_Id, 1); - } - else - { - spawnAtLocation(Item::beef_raw_Id, 1); - } - } -} - -bool Cow::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (item != NULL && item->id == Item::bucket_empty->id) - { - player->awardStat(GenericStats::cowsMilked(),GenericStats::param_cowsMilked()); - - if (--item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, std::shared_ptr( new ItemInstance(Item::milk) ) ); - } - else if (!player->inventory->add(std::shared_ptr( new ItemInstance(Item::milk) ))) - { - player->drop(std::shared_ptr( new ItemInstance(Item::milk) )); - } - - return true; - } - return Animal::interact(player); -} - -std::shared_ptr Cow::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to number of animals that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - return std::shared_ptr( new Cow(level) ); - } - else - { - return nullptr; - } +std::shared_ptr Cow::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + return std::shared_ptr(new Cow(level)); + } else { + return nullptr; + } } diff --git a/Minecraft.World/Entities/Mobs/Cow.h b/Minecraft.World/Entities/Mobs/Cow.h index bd718ee4a..f7e1f4b42 100644 --- a/Minecraft.World/Entities/Mobs/Cow.h +++ b/Minecraft.World/Entities/Mobs/Cow.h @@ -1,32 +1,30 @@ #pragma once - - #include "Animal.h" class Player; class Level; -class Cow : public Animal -{ +class Cow : public Animal { public: - eINSTANCEOF GetType() { return eTYPE_COW; } - static Entity *create(Level *level) { return new Cow(level); } + eINSTANCEOF GetType() { return eTYPE_COW; } + static Entity* create(Level* level) { return new Cow(level); } public: - Cow(Level *level); - virtual bool useNewAi(); - virtual int getMaxHealth(); + Cow(Level* level); + virtual bool useNewAi(); + virtual int getMaxHealth(); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual float getSoundVolume(); - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual float getSoundVolume(); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual bool interact(std::shared_ptr player); - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); + virtual bool interact(std::shared_ptr player); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); }; diff --git a/Minecraft.World/Entities/Mobs/Creature.cpp b/Minecraft.World/Entities/Mobs/Creature.cpp index cb4245cfd..fb5ede2d2 100644 --- a/Minecraft.World/Entities/Mobs/Creature.cpp +++ b/Minecraft.World/Entities/Mobs/Creature.cpp @@ -1,3 +1,2 @@ #include "../../Platform/stdafx.h" #include "Creature.h" - diff --git a/Minecraft.World/Entities/Mobs/Creature.h b/Minecraft.World/Entities/Mobs/Creature.h index 4186187be..0e542690c 100644 --- a/Minecraft.World/Entities/Mobs/Creature.h +++ b/Minecraft.World/Entities/Mobs/Creature.h @@ -3,8 +3,7 @@ class Level; -class Creature -{ +class Creature { public: - Creature() {} + Creature() {} }; diff --git a/Minecraft.World/Entities/Mobs/Creeper.cpp b/Minecraft.World/Entities/Mobs/Creeper.cpp index 2ce90035d..9cda242ab 100644 --- a/Minecraft.World/Entities/Mobs/Creeper.cpp +++ b/Minecraft.World/Entities/Mobs/Creeper.cpp @@ -16,154 +16,127 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" - - -void Creeper::_init() -{ - swell = 0; - oldSwell = 0; +void Creeper::_init() { + swell = 0; + oldSwell = 0; } -Creeper::Creeper(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Creeper::Creeper(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - _init(); - - this->textureIdx = TN_MOB_CREEPER; // 4J was L"/mob/creeper.png"; + _init(); - goalSelector.addGoal(1, new FloatGoal(this)); - goalSelector.addGoal(2, new SwellGoal(this)); - goalSelector.addGoal(3, new AvoidPlayerGoal(this, typeid(Ozelot), 6, 0.25f, 0.30f)); - goalSelector.addGoal(4, new MeleeAttackGoal(this, 0.25f, false)); - goalSelector.addGoal(5, new RandomStrollGoal(this, 0.20f)); - goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 8)); - goalSelector.addGoal(6, new RandomLookAroundGoal(this)); + this->textureIdx = TN_MOB_CREEPER; // 4J was L"/mob/creeper.png"; - targetSelector.addGoal(1, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); - targetSelector.addGoal(2, new HurtByTargetGoal(this, false)); + goalSelector.addGoal(1, new FloatGoal(this)); + goalSelector.addGoal(2, new SwellGoal(this)); + goalSelector.addGoal( + 3, new AvoidPlayerGoal(this, typeid(Ozelot), 6, 0.25f, 0.30f)); + goalSelector.addGoal(4, new MeleeAttackGoal(this, 0.25f, false)); + goalSelector.addGoal(5, new RandomStrollGoal(this, 0.20f)); + goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 8)); + goalSelector.addGoal(6, new RandomLookAroundGoal(this)); + + targetSelector.addGoal( + 1, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); + targetSelector.addGoal(2, new HurtByTargetGoal(this, false)); } -bool Creeper::useNewAi() -{ - return true; -} +bool Creeper::useNewAi() { return true; } -int Creeper::getMaxHealth() -{ - return 20; -} +int Creeper::getMaxHealth() { return 20; } -void Creeper::defineSynchedData() -{ +void Creeper::defineSynchedData() { Monster::defineSynchedData(); - entityData->define(DATA_SWELL_DIR, (uint8_t) -1); - entityData->define(DATA_IS_POWERED, (uint8_t) 0); + entityData->define(DATA_SWELL_DIR, (uint8_t)-1); + entityData->define(DATA_IS_POWERED, (uint8_t)0); } -void Creeper::addAdditonalSaveData(CompoundTag *entityTag) -{ +void Creeper::addAdditonalSaveData(CompoundTag* entityTag) { Monster::addAdditonalSaveData(entityTag); - if (entityData->getByte(DATA_IS_POWERED) == 1) entityTag->putBoolean(L"powered", true); + if (entityData->getByte(DATA_IS_POWERED) == 1) + entityTag->putBoolean(L"powered", true); } -void Creeper::readAdditionalSaveData(CompoundTag *tag) -{ +void Creeper::readAdditionalSaveData(CompoundTag* tag) { Monster::readAdditionalSaveData(tag); - entityData->set(DATA_IS_POWERED, (uint8_t) (tag->getBoolean(L"powered") ? 1 : 0)); + entityData->set(DATA_IS_POWERED, + (uint8_t)(tag->getBoolean(L"powered") ? 1 : 0)); } -void Creeper::tick() -{ +void Creeper::tick() { oldSwell = swell; - if (isAlive()) - { + if (isAlive()) { int swellDir = getSwellDir(); - if (swellDir > 0 && swell == 0) - { - level->playSound(shared_from_this(), eSoundType_RANDOM_FUSE, 1, 0.5f); + if (swellDir > 0 && swell == 0) { + level->playSound(shared_from_this(), eSoundType_RANDOM_FUSE, 1, + 0.5f); } swell += swellDir; if (swell < 0) swell = 0; - if (swell >= MAX_SWELL) - { - swell = MAX_SWELL; - if (!level->isClientSide) - { - bool destroyBlocks = true; //level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); - if (isPowered()) level->explode(shared_from_this(), x, y, z, 6, destroyBlocks); - else level->explode(shared_from_this(), x, y, z, 3,destroyBlocks); - remove(); - } - } + if (swell >= MAX_SWELL) { + swell = MAX_SWELL; + if (!level->isClientSide) { + bool destroyBlocks = + true; // level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); + if (isPowered()) + level->explode(shared_from_this(), x, y, z, 6, + destroyBlocks); + else + level->explode(shared_from_this(), x, y, z, 3, + destroyBlocks); + remove(); + } + } } Monster::tick(); } -int Creeper::getHurtSound() -{ - return eSoundType_MOB_CREEPER_HURT; -} +int Creeper::getHurtSound() { return eSoundType_MOB_CREEPER_HURT; } -int Creeper::getDeathSound() -{ - return eSoundType_MOB_CREEPER_DEATH; -} +int Creeper::getDeathSound() { return eSoundType_MOB_CREEPER_DEATH; } -void Creeper::die(DamageSource *source) -{ +void Creeper::die(DamageSource* source) { Monster::die(source); - if ( std::dynamic_pointer_cast(source->getEntity()) != NULL ) - { + if (std::dynamic_pointer_cast(source->getEntity()) != NULL) { spawnAtLocation(Item::record_01_Id + random->nextInt(12), 1); } - std::shared_ptr player = std::dynamic_pointer_cast(source->getEntity()); - if ( (std::dynamic_pointer_cast(source->getDirectEntity()) != NULL) && (player != NULL) ) - { - player->awardStat(GenericStats::archer(), GenericStats::param_archer()); - } + std::shared_ptr player = + std::dynamic_pointer_cast(source->getEntity()); + if ((std::dynamic_pointer_cast(source->getDirectEntity()) != NULL) && + (player != NULL)) { + player->awardStat(GenericStats::archer(), GenericStats::param_archer()); + } } -bool Creeper::doHurtTarget(std::shared_ptr target) -{ - return true; -} +bool Creeper::doHurtTarget(std::shared_ptr target) { return true; } -bool Creeper::isPowered() -{ - return entityData->getByte(DATA_IS_POWERED) == 1; -} +bool Creeper::isPowered() { return entityData->getByte(DATA_IS_POWERED) == 1; } -float Creeper::getSwelling(float a) -{ +float Creeper::getSwelling(float a) { return (oldSwell + (swell - oldSwell) * a) / (MAX_SWELL - 2); } -int Creeper::getDeathLoot() -{ - return Item::sulphur->id; +int Creeper::getDeathLoot() { return Item::sulphur->id; } + +int Creeper::getSwellDir() { + return (int)(char)entityData->getByte(DATA_SWELL_DIR); } -int Creeper::getSwellDir() -{ - return (int) (char) entityData->getByte(DATA_SWELL_DIR); +void Creeper::setSwellDir(int dir) { + entityData->set(DATA_SWELL_DIR, (uint8_t)dir); } -void Creeper::setSwellDir(int dir) -{ - entityData->set(DATA_SWELL_DIR, (uint8_t) dir); -} - -void Creeper::thunderHit(const LightningBolt *lightningBolt) -{ +void Creeper::thunderHit(const LightningBolt* lightningBolt) { Monster::thunderHit(lightningBolt); - entityData->set(DATA_IS_POWERED, (uint8_t) 1); + entityData->set(DATA_IS_POWERED, (uint8_t)1); } diff --git a/Minecraft.World/Entities/Mobs/Creeper.h b/Minecraft.World/Entities/Mobs/Creeper.h index 7da061984..1762f65e9 100644 --- a/Minecraft.World/Entities/Mobs/Creeper.h +++ b/Minecraft.World/Entities/Mobs/Creeper.h @@ -1,59 +1,57 @@ #pragma once - #include "../Monster.h" class Level; class DamageSource; -class Creeper : public Monster -{ +class Creeper : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_CREEPER; } - static Entity *create(Level *level) { return new Creeper(level); } + eINSTANCEOF GetType() { return eTYPE_CREEPER; } + static Entity* create(Level* level) { return new Creeper(level); } private: - static const int DATA_SWELL_DIR = 16; + static const int DATA_SWELL_DIR = 16; static const int DATA_IS_POWERED = 17; int swell; int oldSwell; - static const int MAX_SWELL = 30; + static const int MAX_SWELL = 30; - void _init(); + void _init(); public: - Creeper(Level *level); + Creeper(Level* level); - virtual bool useNewAi(); - virtual int getMaxHealth(); + virtual bool useNewAi(); + virtual int getMaxHealth(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: virtual void tick(); protected: - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - virtual void die(DamageSource *source); - virtual bool doHurtTarget(std::shared_ptr target); - virtual bool isPowered(); + virtual void die(DamageSource* source); + virtual bool doHurtTarget(std::shared_ptr target); + virtual bool isPowered(); float getSwelling(float a); protected: - int getDeathLoot(); + int getDeathLoot(); public: - int getSwellDir(); - void setSwellDir(int dir); - void thunderHit(const LightningBolt *lightningBolt) ; + int getSwellDir(); + void setSwellDir(int dir); + void thunderHit(const LightningBolt* lightningBolt); }; diff --git a/Minecraft.World/Entities/Mobs/DragonFireball.cpp b/Minecraft.World/Entities/Mobs/DragonFireball.cpp index 96dc9bdac..b352f5246 100644 --- a/Minecraft.World/Entities/Mobs/DragonFireball.cpp +++ b/Minecraft.World/Entities/Mobs/DragonFireball.cpp @@ -7,80 +7,65 @@ #include "../../Util/JavaMath.h" #include "DragonFireball.h" - - const double DragonFireball::SPLASH_RANGE = 4.0; -const double DragonFireball::SPLASH_RANGE_SQ = DragonFireball::SPLASH_RANGE * DragonFireball::SPLASH_RANGE; +const double DragonFireball::SPLASH_RANGE_SQ = + DragonFireball::SPLASH_RANGE * DragonFireball::SPLASH_RANGE; -DragonFireball::DragonFireball(Level *level) : Fireball(level) -{ - setSize(5 / 16.0f, 5 / 16.0f); +DragonFireball::DragonFireball(Level* level) : Fireball(level) { + setSize(5 / 16.0f, 5 / 16.0f); } -DragonFireball::DragonFireball(Level *level, std::shared_ptr mob, double xa, double ya, double za) : Fireball(level, mob, xa, ya, za) -{ - setSize(5 / 16.0f, 5 / 16.0f); +DragonFireball::DragonFireball(Level* level, std::shared_ptr mob, + double xa, double ya, double za) + : Fireball(level, mob, xa, ya, za) { + setSize(5 / 16.0f, 5 / 16.0f); } -DragonFireball::DragonFireball(Level *level, double x, double y, double z, double xa, double ya, double za) : Fireball(level, x, y, z, xa, ya, za) -{ - setSize(5 / 16.0f, 5 / 16.0f); +DragonFireball::DragonFireball(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Fireball(level, x, y, z, xa, ya, za) { + setSize(5 / 16.0f, 5 / 16.0f); } -void DragonFireball::onHit(HitResult *res) -{ - if (!level->isClientSide) - { - AABB *aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); - std::vector > *entitiesOfClass = level->getEntitiesOfClass(typeid(Mob), aoe); +void DragonFireball::onHit(HitResult* res) { + if (!level->isClientSide) { + AABB* aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); + std::vector >* entitiesOfClass = + level->getEntitiesOfClass(typeid(Mob), aoe); - if (entitiesOfClass != NULL && !entitiesOfClass->empty()) - { - //for (Entity e : entitiesOfClass) - for( AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) - { - //std::shared_ptr e = *it; - std::shared_ptr e = std::dynamic_pointer_cast( *it ); - double dist = distanceToSqr(e); - if (dist < SPLASH_RANGE_SQ) - { - double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); - if (e == res->entity) - { - scale = 1; - } - e->hurt(DamageSource::dragonbreath, 8*scale); - } - } - } - delete entitiesOfClass; - level->levelEvent(LevelEvent::ENDERDRAGON_FIREBALL_SPLASH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), 0); + if (entitiesOfClass != NULL && !entitiesOfClass->empty()) { + // for (Entity e : entitiesOfClass) + for (AUTO_VAR(it, entitiesOfClass->begin()); + it != entitiesOfClass->end(); ++it) { + // std::shared_ptr e = *it; + std::shared_ptr e = std::dynamic_pointer_cast(*it); + double dist = distanceToSqr(e); + if (dist < SPLASH_RANGE_SQ) { + double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); + if (e == res->entity) { + scale = 1; + } + e->hurt(DamageSource::dragonbreath, 8 * scale); + } + } + } + delete entitiesOfClass; + level->levelEvent(LevelEvent::ENDERDRAGON_FIREBALL_SPLASH, + (int)Math::round(x), (int)Math::round(y), + (int)Math::round(z), 0); - remove(); - } + remove(); + } } -bool DragonFireball::isPickable() -{ - return false; -} +bool DragonFireball::isPickable() { return false; } -bool DragonFireball::hurt(DamageSource *source, int damage) -{ - return false; -} +bool DragonFireball::hurt(DamageSource* source, int damage) { return false; } -bool DragonFireball::shouldBurn() -{ - return false; -} +bool DragonFireball::shouldBurn() { return false; } -int DragonFireball::getIcon() -{ - return 15 + 14 * 16; -} +int DragonFireball::getIcon() { return 15 + 14 * 16; } -ePARTICLE_TYPE DragonFireball::getTrailParticleType() -{ - return eParticleType_dragonbreath; +ePARTICLE_TYPE DragonFireball::getTrailParticleType() { + return eParticleType_dragonbreath; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/DragonFireball.h b/Minecraft.World/Entities/Mobs/DragonFireball.h index 96ab6d9f4..6d2ad5d2d 100644 --- a/Minecraft.World/Entities/Mobs/DragonFireball.h +++ b/Minecraft.World/Entities/Mobs/DragonFireball.h @@ -4,34 +4,35 @@ class HitResult; -class DragonFireball : public Fireball -{ +class DragonFireball : public Fireball { public: - eINSTANCEOF GetType() { return eTYPE_DRAGON_FIREBALL; } - static Entity *create(Level *level) { return new DragonFireball(level); } + eINSTANCEOF GetType() { return eTYPE_DRAGON_FIREBALL; } + static Entity* create(Level* level) { return new DragonFireball(level); } public: - static const double SPLASH_RANGE; + static const double SPLASH_RANGE; private: - static const double SPLASH_RANGE_SQ; + static const double SPLASH_RANGE_SQ; public: - DragonFireball(Level *level); - DragonFireball(Level *level, std::shared_ptr mob, double xa, double ya, double za); - DragonFireball(Level *level, double x, double y, double z, double xa, double ya, double za); + DragonFireball(Level* level); + DragonFireball(Level* level, std::shared_ptr mob, double xa, double ya, + double za); + DragonFireball(Level* level, double x, double y, double z, double xa, + double ya, double za); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); public: - virtual bool isPickable(); - virtual bool hurt(DamageSource *source, int damage); + virtual bool isPickable(); + virtual bool hurt(DamageSource* source, int damage); - virtual bool shouldBurn(); - virtual int getIcon(); + virtual bool shouldBurn(); + virtual int getIcon(); protected: -// 4J Added TU9 - virtual ePARTICLE_TYPE getTrailParticleType(); + // 4J Added TU9 + virtual ePARTICLE_TYPE getTrailParticleType(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/EnderCrystal.cpp b/Minecraft.World/Entities/Mobs/EnderCrystal.cpp index 5fb34ec26..d0458f079 100644 --- a/Minecraft.World/Entities/Mobs/EnderCrystal.cpp +++ b/Minecraft.World/Entities/Mobs/EnderCrystal.cpp @@ -6,123 +6,94 @@ #include "EnderCrystal.h" #include "../../Util/DamageSource.h" +void EnderCrystal::_init(Level* level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + blocksBuilding = true; + setSize(2.0f, 2.0f); + heightOffset = bbHeight / 2.0f; + life = MAX_LIFE; -void EnderCrystal::_init(Level *level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - blocksBuilding = true; - setSize(2.0f, 2.0f); - heightOffset = bbHeight / 2.0f; - life = MAX_LIFE; - - time = random->nextInt(100000); + time = random->nextInt(100000); } -EnderCrystal::EnderCrystal(Level *level) : Entity( level ) -{ - _init(level); +EnderCrystal::EnderCrystal(Level* level) : Entity(level) { _init(level); } +EnderCrystal::EnderCrystal(Level* level, double x, double y, double z) + : Entity(level) { + _init(level); + setPos(x, y, z); } -EnderCrystal::EnderCrystal(Level *level, double x, double y, double z) : Entity( level ) -{ - _init(level); - setPos(x, y, z); +bool EnderCrystal::makeStepSound() { return false; } +void EnderCrystal::defineSynchedData() { + entityData->define(DATA_REMAINING_LIFE, life); } -bool EnderCrystal::makeStepSound() -{ - return false; +void EnderCrystal::tick() { + xo = x; + yo = y; + zo = z; + time++; + + entityData->set(DATA_REMAINING_LIFE, life); + + // Don't set the tile directly on the client, as this can end up in the + // updatesToReset queue in the MultiPlayerLevel, and the perpetually end up + // removing/adding these fire tiles causing timing glitches from the + // lighting changes requried. + if (!level->isClientSide) { + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + if (level->getTile(xt, yt, zt) != Tile::fire_Id) { + level->setTile(xt, yt, zt, Tile::fire_Id); + } + } } -void EnderCrystal::defineSynchedData() -{ - entityData->define(DATA_REMAINING_LIFE, life); -} +void EnderCrystal::addAdditonalSaveData(CompoundTag* tag) {} -void EnderCrystal::tick() -{ - xo = x; - yo = y; - zo = z; - time++; +void EnderCrystal::readAdditionalSaveData(CompoundTag* tag) {} - entityData->set(DATA_REMAINING_LIFE, life); +float EnderCrystal::getShadowHeightOffs() { return 0; } - // Don't set the tile directly on the client, as this can end up in the updatesToReset queue in the MultiPlayerLevel, and the perpetually end up removing/adding these fire tiles causing timing - // glitches from the lighting changes requried. - if (!level->isClientSide) - { - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - if (level->getTile(xt, yt, zt) != Tile::fire_Id) - { - level->setTile(xt, yt, zt, Tile::fire_Id); - } - } -} +bool EnderCrystal::isPickable() { return true; } +bool EnderCrystal::hurt(DamageSource* source, int damage) { + // 4J-PB - if the owner of the source is the enderdragon, then ignore it + // (where the dragon's fireball hits an endercrystal) + std::shared_ptr sourceIsDragon = + std::dynamic_pointer_cast(source->getEntity()); -void EnderCrystal::addAdditonalSaveData(CompoundTag *tag) -{ -} + if (sourceIsDragon != NULL) { + return false; + } -void EnderCrystal::readAdditionalSaveData(CompoundTag *tag) -{ -} + if (!removed && !level->isClientSide) { + life = 0; + if (life <= 0) { + remove(); + if (!level->isClientSide) { + level->explode(nullptr, x, y, z, 6, true); - -float EnderCrystal::getShadowHeightOffs() -{ - return 0; -} - -bool EnderCrystal::isPickable() -{ - return true; -} - -bool EnderCrystal::hurt(DamageSource *source, int damage) -{ - // 4J-PB - if the owner of the source is the enderdragon, then ignore it (where the dragon's fireball hits an endercrystal) - std::shared_ptr sourceIsDragon = std::dynamic_pointer_cast(source->getEntity()); - - if(sourceIsDragon!=NULL) - { - return false; - } - - if (!removed && !level->isClientSide) - { - life = 0; - if (life <= 0) - { - remove(); - if (!level->isClientSide) - { - level->explode(nullptr, x, y, z, 6, true); - - std::vector > entities = level->getAllEntities(); - std::shared_ptr dragon = nullptr; - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); - dragon = std::dynamic_pointer_cast(e); - if(dragon != NULL) - { - dragon->handleCrystalDestroyed(source); - break; - } - } - } - } - } - return true; + std::vector > entities = + level->getAllEntities(); + std::shared_ptr dragon = nullptr; + AUTO_VAR(itEnd, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); + dragon = std::dynamic_pointer_cast(e); + if (dragon != NULL) { + dragon->handleCrystalDestroyed(source); + break; + } + } + } + } + } + return true; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/EnderCrystal.h b/Minecraft.World/Entities/Mobs/EnderCrystal.h index 41c7d4f08..402b583fc 100644 --- a/Minecraft.World/Entities/Mobs/EnderCrystal.h +++ b/Minecraft.World/Entities/Mobs/EnderCrystal.h @@ -2,41 +2,41 @@ #include "../Entity.h" -class EnderCrystal : public Entity -{ +class EnderCrystal : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_ENDER_CRYSTAL; }; - static Entity *create(Level *level) { return new EnderCrystal(level); } -private: - static const int MAX_LIFE = 5; - -public: - static const int serialVersionUID = 0; - int time; - int life; + eINSTANCEOF GetType() { return eTYPE_ENDER_CRYSTAL; }; + static Entity* create(Level* level) { return new EnderCrystal(level); } private: - static const int DATA_REMAINING_LIFE = 8; - - void _init(Level *level); + static const int MAX_LIFE = 5; public: - EnderCrystal(Level *level); - EnderCrystal(Level *level, double x, double y, double z); + static const int serialVersionUID = 0; + int time; + int life; + +private: + static const int DATA_REMAINING_LIFE = 8; + + void _init(Level* level); + +public: + EnderCrystal(Level* level); + EnderCrystal(Level* level, double x, double y, double z); protected: - virtual bool makeStepSound(); - virtual void defineSynchedData(); + virtual bool makeStepSound(); + virtual void defineSynchedData(); public: - void tick(); + void tick(); protected: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); public: - virtual float getShadowHeightOffs(); - virtual bool isPickable(); - virtual bool hurt(DamageSource *source, int damage); + virtual float getShadowHeightOffs(); + virtual bool isPickable(); + virtual bool hurt(DamageSource* source, int damage); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/EnderDragon.cpp b/Minecraft.World/Entities/Mobs/EnderDragon.cpp index d739879bd..81d6ec4c1 100644 --- a/Minecraft.World/Entities/Mobs/EnderDragon.cpp +++ b/Minecraft.World/Entities/Mobs/EnderDragon.cpp @@ -15,1662 +15,1587 @@ #define PRINT_DRAGON_STATE_CHANGE_MESSAGES 1 - - // 4J Added for new dragon behaviour const int EnderDragon::CRYSTAL_COUNT = 8; const int EnderDragon::FLAME_TICKS = 60; const float EnderDragon::FLAME_ANGLE = 22.5f; -const int EnderDragon::FLAME_PASSES = 4; // How many times it covers FLAME_ANGLE in FLAME_TICKS -const int EnderDragon::FLAME_FREQUENCY = 2; // Every FLAME_FREQUENCY ticks it sets fire to blocks while doing a flame pass +const int EnderDragon::FLAME_PASSES = + 4; // How many times it covers FLAME_ANGLE in FLAME_TICKS +const int EnderDragon::FLAME_FREQUENCY = + 2; // Every FLAME_FREQUENCY ticks it sets fire to blocks while doing a + // flame pass const int EnderDragon::FLAME_RANGE = 10; -const int EnderDragon::ATTACK_TICKS = SharedConstants::TICKS_PER_SECOND * 2; // Time for the dragon roar to play +const int EnderDragon::ATTACK_TICKS = + SharedConstants::TICKS_PER_SECOND * 2; // Time for the dragon roar to play -const int EnderDragon::SITTING_ATTACK_Y_VIEW_RANGE = 10; // The player must be now lower and no higher than the dragon by this amount +const int EnderDragon::SITTING_ATTACK_Y_VIEW_RANGE = + 10; // The player must be now lower and no higher than the dragon by this + // amount const int EnderDragon::SITTING_ATTACK_VIEW_RANGE = EnderDragon::FLAME_RANGE * 2; const int EnderDragon::SITTING_ATTACK_RANGE = EnderDragon::FLAME_RANGE * 2; const int EnderDragon::SITTING_POST_ATTACK_IDLE_TICKS = 40; const int EnderDragon::SITTING_SCANNING_IDLE_TICKS = 100; -const int EnderDragon::SITTING_FLAME_ATTACKS_COUNT = 4; // How many times the dragons does the scan/roar/flame cycle before flying off +const int EnderDragon::SITTING_FLAME_ATTACKS_COUNT = + 4; // How many times the dragons does the scan/roar/flame cycle before + // flying off -// The percentage of max health that the dragon will take while in the "Sitting" states before flying away +// The percentage of max health that the dragon will take while in the "Sitting" +// states before flying away const float EnderDragon::SITTING_ALLOWED_DAMAGE_PERCENTAGE = 0.25f; -void EnderDragon::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void EnderDragon::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - xTarget = yTarget = zTarget = 0.0; - posPointer = -1; - oFlapTime = 0; - flapTime = 0; - newTarget = false; - inWall = false; - attackTarget = nullptr; - dragonDeathTime = 0; - nearestCrystal = nullptr; + xTarget = yTarget = zTarget = 0.0; + posPointer = -1; + oFlapTime = 0; + flapTime = 0; + newTarget = false; + inWall = false; + attackTarget = nullptr; + dragonDeathTime = 0; + nearestCrystal = nullptr; - // 4J Stu - Added for new dragon behaviour - m_remainingCrystalsCount = CRYSTAL_COUNT; - m_fireballCharge = 0; - m_holdingPatternAngle = 0.0f; - m_holdingPatternClockwise = true; - setSynchedAction(e_EnderdragonAction_HoldingPattern); - m_actionTicks = 0; - m_sittingDamageReceived = 0; - m_headYRot = 0.0; - m_acidArea = AABB::newPermanent(-4,-10,-3,6,3,3); - m_flameAttacks = 0; + // 4J Stu - Added for new dragon behaviour + m_remainingCrystalsCount = CRYSTAL_COUNT; + m_fireballCharge = 0; + m_holdingPatternAngle = 0.0f; + m_holdingPatternClockwise = true; + setSynchedAction(e_EnderdragonAction_HoldingPattern); + m_actionTicks = 0; + m_sittingDamageReceived = 0; + m_headYRot = 0.0; + m_acidArea = AABB::newPermanent(-4, -10, -3, 6, 3, 3); + m_flameAttacks = 0; - for (int i = 0; i < positionsLength; i++) - { - positions[i][0] = 0; - positions[i][1] = 0; - positions[i][2] = 0; - } + for (int i = 0; i < positionsLength; i++) { + positions[i][0] = 0; + positions[i][1] = 0; + positions[i][2] = 0; + } - m_nodes = new NodeArray(24); - openSet = new BinaryHeap(); - m_currentPath = NULL; + m_nodes = new NodeArray(24); + openSet = new BinaryHeap(); + m_currentPath = NULL; } -EnderDragon::EnderDragon(Level *level) : BossMob(level) -{ - _init(); +EnderDragon::EnderDragon(Level* level) : BossMob(level) { + _init(); - head = std::shared_ptr( new BossMobPart(this, L"head", 6, 6) ); - neck = std::shared_ptr( new BossMobPart(this, L"neck", 6, 6) ); // 4J Added - body = std::shared_ptr( new BossMobPart(this, L"body", 8, 8) ); - tail1 = std::shared_ptr( new BossMobPart(this, L"tail", 4, 4) ); - tail2 = std::shared_ptr( new BossMobPart(this, L"tail", 4, 4) ); - tail3 = std::shared_ptr( new BossMobPart(this, L"tail", 4, 4) ); - wing1 = std::shared_ptr( new BossMobPart(this, L"wing", 4, 4) ); - wing2 = std::shared_ptr( new BossMobPart(this, L"wing", 4, 4) ); + head = std::shared_ptr(new BossMobPart(this, L"head", 6, 6)); + neck = std::shared_ptr( + new BossMobPart(this, L"neck", 6, 6)); // 4J Added + body = std::shared_ptr(new BossMobPart(this, L"body", 8, 8)); + tail1 = std::shared_ptr(new BossMobPart(this, L"tail", 4, 4)); + tail2 = std::shared_ptr(new BossMobPart(this, L"tail", 4, 4)); + tail3 = std::shared_ptr(new BossMobPart(this, L"tail", 4, 4)); + wing1 = std::shared_ptr(new BossMobPart(this, L"wing", 4, 4)); + wing2 = std::shared_ptr(new BossMobPart(this, L"wing", 4, 4)); - subEntities.push_back(head); - subEntities.push_back(neck); // 4J Added - subEntities.push_back(body); - subEntities.push_back(tail1); - subEntities.push_back(tail2); - subEntities.push_back(tail3); - subEntities.push_back(wing1); - subEntities.push_back(wing2); + subEntities.push_back(head); + subEntities.push_back(neck); // 4J Added + subEntities.push_back(body); + subEntities.push_back(tail1); + subEntities.push_back(tail2); + subEntities.push_back(tail3); + subEntities.push_back(wing1); + subEntities.push_back(wing2); - maxHealth = 200; - setHealth(maxHealth); + maxHealth = 200; + setHealth(maxHealth); - this->textureIdx = TN_MOB_ENDERDRAGON; // 4J was "/mob/enderdragon/ender.png"; - setSize(16, 8); + this->textureIdx = + TN_MOB_ENDERDRAGON; // 4J was "/mob/enderdragon/ender.png"; + setSize(16, 8); - noPhysics = true; - fireImmune = true; + noPhysics = true; + fireImmune = true; - yTarget = 100; + yTarget = 100; - m_iGrowlTimer=100; + m_iGrowlTimer = 100; - noCulling = true; + noCulling = true; } -EnderDragon::~EnderDragon() -{ - if(m_nodes->data != NULL) - { - for(unsigned int i = 0; i < m_nodes->length; ++i) - { - if(m_nodes->data[i]!=NULL) delete m_nodes->data[i]; - } - delete [] m_nodes->data; - } - delete openSet; - if( m_currentPath != NULL ) delete m_currentPath; +EnderDragon::~EnderDragon() { + if (m_nodes->data != NULL) { + for (unsigned int i = 0; i < m_nodes->length; ++i) { + if (m_nodes->data[i] != NULL) delete m_nodes->data[i]; + } + delete[] m_nodes->data; + } + delete openSet; + if (m_currentPath != NULL) delete m_currentPath; } -void EnderDragon::defineSynchedData() -{ - BossMob::defineSynchedData(); +void EnderDragon::defineSynchedData() { + BossMob::defineSynchedData(); - entityData->define(DATA_ID_SYNCHED_HEALTH, maxHealth); + entityData->define(DATA_ID_SYNCHED_HEALTH, maxHealth); - // 4J Added for new dragon behaviour - entityData->define(DATA_ID_SYNCHED_ACTION, e_EnderdragonAction_HoldingPattern); + // 4J Added for new dragon behaviour + entityData->define(DATA_ID_SYNCHED_ACTION, + e_EnderdragonAction_HoldingPattern); } -void EnderDragon::getLatencyPos(doubleArray result, int step, float a) -{ - if (health <= 0) - { - a = 0; - } +void EnderDragon::getLatencyPos(doubleArray result, int step, float a) { + if (health <= 0) { + a = 0; + } - a = 1 - a; + a = 1 - a; - int p0 = (posPointer - step * 1) & 63; - int p1 = (posPointer - step * 1 - 1) & 63; + int p0 = (posPointer - step * 1) & 63; + int p1 = (posPointer - step * 1 - 1) & 63; - // positions is a ring buffer of size positionsLength (64) storing positional information per tick - // positions[i][0] is y rotation - // positions[i][1] is y position - // positions[i][2] is currently always 0 + // positions is a ring buffer of size positionsLength (64) storing + // positional information per tick positions[i][0] is y rotation + // positions[i][1] is y position + // positions[i][2] is currently always 0 - double yr0 = positions[p0][0]; - double yrd = Mth::wrapDegrees(positions[p1][0] - yr0); - result[0] = yr0 + yrd * a; + double yr0 = positions[p0][0]; + double yrd = Mth::wrapDegrees(positions[p1][0] - yr0); + result[0] = yr0 + yrd * a; - yr0 = positions[p0][1]; - yrd = positions[p1][1] - yr0; + yr0 = positions[p0][1]; + yrd = positions[p1][1] - yr0; - result[1] = yr0 + yrd * a; - result[2] = positions[p0][2] + (positions[p1][2] - positions[p0][2]) * a; + result[1] = yr0 + yrd * a; + result[2] = positions[p0][2] + (positions[p1][2] - positions[p0][2]) * a; } -void EnderDragon::aiStep() -{ - if (!level->isClientSide) - { - entityData->set(DATA_ID_SYNCHED_HEALTH, health); - } - else - { - // 4J Stu - If saved when dead we need to make sure that the actual health is updated correctly on the client - // Fix for TU9: Content: Gameplay: Enderdragon respawns after loading game which was previously saved at point of hes death - health = getSynchedHealth(); +void EnderDragon::aiStep() { + if (!level->isClientSide) { + entityData->set(DATA_ID_SYNCHED_HEALTH, health); + } else { + // 4J Stu - If saved when dead we need to make sure that the actual + // health is updated correctly on the client Fix for TU9: Content: + // Gameplay: Enderdragon respawns after loading game which was + // previously saved at point of hes death + health = getSynchedHealth(); - float flap = Mth::cos(flapTime * PI * 2); - float oldFlap = Mth::cos(oFlapTime * PI * 2); + float flap = Mth::cos(flapTime * PI * 2); + float oldFlap = Mth::cos(oFlapTime * PI * 2); - if (oldFlap <= -0.3f && flap >= -0.3f) - { - level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_MOVE, 1, 0.8f + random->nextFloat() * .3f, 100.0f); - } - // play a growl every now and then - if(! (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking)) - { - m_iGrowlTimer--; - if(m_iGrowlTimer<0) - { - level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_GROWL, 0.5f, 0.8f + random->nextFloat() * .3f, 100.0f); - m_iGrowlTimer=200+(random->nextInt(200)); - } - } - } + if (oldFlap <= -0.3f && flap >= -0.3f) { + level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_MOVE, 1, + 0.8f + random->nextFloat() * .3f, 100.0f); + } + // play a growl every now and then + if (!(getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking)) { + m_iGrowlTimer--; + if (m_iGrowlTimer < 0) { + level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_GROWL, + 0.5f, 0.8f + random->nextFloat() * .3f, + 100.0f); + m_iGrowlTimer = 200 + (random->nextInt(200)); + } + } + } - oFlapTime = flapTime; + oFlapTime = flapTime; - if (health <= 0) - { - // level.addParticle("explode", x + random.nextFloat() * bbWidth * 2 - bbWidth, y + random.nextFloat() * bbHeight, z + random.nextFloat() * bbWidth * 2 - bbWidth, 0, 0, 0); - float xo = (random->nextFloat() - 0.5f) * 8; - float yo = (random->nextFloat() - 0.5f) * 4; - float zo = (random->nextFloat() - 0.5f) * 8; - level->addParticle(eParticleType_largeexplode, x + xo, y + 2 + yo, z + zo, 0, 0, 0); - return; - } + if (health <= 0) { + // level.addParticle("explode", x + random.nextFloat() * + // bbWidth * 2 - bbWidth, y + random.nextFloat() * bbHeight, + // z + random.nextFloat() * bbWidth * 2 - bbWidth, 0, 0, 0); + float xo = (random->nextFloat() - 0.5f) * 8; + float yo = (random->nextFloat() - 0.5f) * 4; + float zo = (random->nextFloat() - 0.5f) * 8; + level->addParticle(eParticleType_largeexplode, x + xo, y + 2 + yo, + z + zo, 0, 0, 0); + return; + } - checkCrystals(); + checkCrystals(); - float flapSpeed = 0.2f / (sqrt(xd * xd + zd * zd) * 10.0f + 1); - flapSpeed *= (float) pow(2.0, yd); - if ( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - { - //app.DebugPrintf("flapSpeed is %f\n", flapSpeed); - //flapTime += flapSpeed * 2; - flapTime += 0.1f; - } - else if (inWall) - { - flapTime += flapSpeed * 0.5f; - } - else - { - flapTime += flapSpeed; - } + float flapSpeed = 0.2f / (sqrt(xd * xd + zd * zd) * 10.0f + 1); + flapSpeed *= (float)pow(2.0, yd); + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) { + // app.DebugPrintf("flapSpeed is %f\n", flapSpeed); + // flapTime += flapSpeed * 2; + flapTime += 0.1f; + } else if (inWall) { + flapTime += flapSpeed * 0.5f; + } else { + flapTime += flapSpeed; + } - yRot = Mth::wrapDegrees(yRot); + yRot = Mth::wrapDegrees(yRot); - if (posPointer < 0) - { - for (int i = 0; i < positionsLength; i++) - { - positions[i][0] = yRot; - positions[i][1] = y; - } - } + if (posPointer < 0) { + for (int i = 0; i < positionsLength; i++) { + positions[i][0] = yRot; + positions[i][1] = y; + } + } - if (++posPointer == positionsLength) posPointer = 0; - positions[posPointer][0] = yRot; - positions[posPointer][1] = y; + if (++posPointer == positionsLength) posPointer = 0; + positions[posPointer][0] = yRot; + positions[posPointer][1] = y; + if (level->isClientSide) { + if (lSteps > 0) { + double xt = x + (lx - x) / lSteps; + double yt = y + (ly - y) / lSteps; + double zt = z + (lz - z) / lSteps; - if (level->isClientSide) - { - if (lSteps > 0) - { - double xt = x + (lx - x) / lSteps; - double yt = y + (ly - y) / lSteps; - double zt = z + (lz - z) / lSteps; + // 4J Stu - The movement is so small that this head animation + // doesn't look good + // if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming ) + //{ + // double yrd = lyr - (yRot + m_headYRot); + // while (yrd < -180) + // yrd += 360; + // while (yrd >= 180) + // yrd -= 360; - // 4J Stu - The movement is so small that this head animation doesn't look good - //if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming ) - //{ - // double yrd = lyr - (yRot + m_headYRot); - // while (yrd < -180) - // yrd += 360; - // while (yrd >= 180) - // yrd -= 360; + // m_headYRot += (yrd) / lSteps; + //} + // else + { + double yrd = Mth::wrapDegrees(lyr - yRot); - // m_headYRot += (yrd) / lSteps; - //} - //else - { - double yrd = Mth::wrapDegrees(lyr - yRot); + m_headYRot = 0.0; + yRot += (yrd) / lSteps; + } + xRot += (lxr - xRot) / lSteps; - m_headYRot = 0.0; - yRot += (yrd) / lSteps; - } - xRot += (lxr - xRot) / lSteps; + lSteps--; + this->setPos(xt, yt, zt); + this->setRot(yRot, xRot); - lSteps--; - this->setPos(xt, yt, zt); - this->setRot(yRot, xRot); + /* + * List collisions = level.getCubes(this, bb.shrink(1 / 32.0, + * 0, 1 / 32.0)); if (collisions.size() > 0) { double yTop = 0; for + * (int i = 0; i < collisions.size(); i++) { AABB ab = + * collisions.get(i); if (ab.y1 > yTop) yTop = ab.y1; } yt += yTop - + * bb.y0; setPos(xt, yt, zt); } + */ + } - /* - * List collisions = level.getCubes(this, bb.shrink(1 / 32.0, 0, 1 / - * 32.0)); if (collisions.size() > 0) { double yTop = 0; for (int i = 0; i < - * collisions.size(); i++) { AABB ab = collisions.get(i); if (ab.y1 > yTop) yTop - * = ab.y1; } yt += yTop - bb.y0; setPos(xt, yt, zt); } - */ + if (getSynchedAction() == e_EnderdragonAction_Landing || + (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming && + tickCount % 2 == 0)) { + double xP = 0.0; + double yP = 0.0; + double zP = 0.0; + Vec3* v = getHeadLookVector(1); // getViewVector(1); + // app.DebugPrintf("View vector is (%f,%f,%f) - lsteps %d\n", v->x, + // v->y, v->z, lSteps); unsigned int d = 0; for(unsigned int d = 1; + // d < 3; ++d) + { + Vec3* vN = v->normalize(); + vN->yRot(-PI / 4); + for (unsigned int i = 0; i < 8; ++i) { + if (getSynchedAction() == e_EnderdragonAction_Landing) { + // for(unsigned int j = 0; j < 6; ++j) + { + xP = head->x; // - vN->x * d; + yP = + head->bb->y0 + + head->bbHeight / + 2; // - vN->y * d; //head->y + + // head->bbHeight / 2 + 0.5f - v->y * d; + zP = head->z; // - vN->z * d; + xP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + yP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + zP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + level->addParticle(eParticleType_dragonbreath, xP, + yP, zP, (-vN->x * 0.08) + xd, + (-vN->y * 0.3) + yd, + (-vN->z * 0.08) + zd); + } + } else { + double yVelocity = 0.6; + double xzVelocity = 0.08; + for (unsigned int j = 0; j < 6; ++j) { + xP = head->x; // - vN->x * d; + yP = + head->bb->y0 + + head->bbHeight / + 2; // - vN->y * d; //head->y + + // head->bbHeight / 2 + 0.5f - v->y * d; + zP = head->z; // - vN->z * d; + xP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + yP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + zP += (level->random->nextBoolean() ? 1 : -1) * + level->random->nextFloat() / 2; + level->addParticle(eParticleType_dragonbreath, xP, + yP, zP, -vN->x * xzVelocity * j, + -vN->y * yVelocity, + -vN->z * xzVelocity * j); + } + } + vN->yRot(PI / (2 * 8)); + } + } + } else if (getSynchedAction() == + e_EnderdragonAction_Sitting_Attacking) { + // AP - changed this to use playLocalSound because no sound could be + // heard with playSound (cos it's a stub function) + level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_GROWL, + 0.5f, 0.8f + random->nextFloat() * .3f, + 100.0f); + } + } else { + double xdd = xTarget - x; + double ydd = yTarget - y; + double zdd = zTarget - z; - } + double dist = xdd * xdd + ydd * ydd + zdd * zdd; - if( getSynchedAction() == e_EnderdragonAction_Landing || (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming && tickCount%2==0) ) - { - double xP = 0.0; - double yP = 0.0; - double zP = 0.0; - Vec3 *v = getHeadLookVector(1); //getViewVector(1); - //app.DebugPrintf("View vector is (%f,%f,%f) - lsteps %d\n", v->x, v->y, v->z, lSteps); - //unsigned int d = 0; - //for(unsigned int d = 1; d < 3; ++d) - { - Vec3 *vN = v->normalize(); - vN->yRot(-PI/4); - for(unsigned int i = 0; i < 8; ++i) - { - if(getSynchedAction() == e_EnderdragonAction_Landing) - { - //for(unsigned int j = 0; j < 6; ++j) - { - xP = head->x;// - vN->x * d; - yP = head->bb->y0 + head->bbHeight / 2;// - vN->y * d; //head->y + head->bbHeight / 2 + 0.5f - v->y * d; - zP = head->z;// - vN->z * d; - xP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - yP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - zP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - level->addParticle(eParticleType_dragonbreath, xP, yP, zP, (-vN->x * 0.08) + xd, (-vN->y * 0.3) + yd, (-vN->z * 0.08) + zd); - } - } - else - { - double yVelocity = 0.6; - double xzVelocity = 0.08; - for(unsigned int j = 0; j < 6; ++j) - { - xP = head->x;// - vN->x * d; - yP = head->bb->y0 + head->bbHeight / 2;// - vN->y * d; //head->y + head->bbHeight / 2 + 0.5f - v->y * d; - zP = head->z;// - vN->z * d; - xP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - yP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - zP += (level->random->nextBoolean()?1:-1) * level->random->nextFloat()/2; - level->addParticle(eParticleType_dragonbreath, xP, yP, zP, -vN->x * xzVelocity*j, -vN->y * yVelocity, -vN->z * xzVelocity*j); - } - } - vN->yRot(PI/(2*8) ); - } - } - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Attacking ) - { - // AP - changed this to use playLocalSound because no sound could be heard with playSound (cos it's a stub function) - level->playLocalSound(x, y, z, eSoundType_MOB_ENDERDRAGON_GROWL, 0.5f, 0.8f + random->nextFloat() * .3f, 100.0f); - } - } - else - { - double xdd = xTarget - x; - double ydd = yTarget - y; - double zdd = zTarget - z; - - double dist = xdd * xdd + ydd * ydd + zdd * zdd; - - if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming ) - { - --m_actionTicks; - if(m_actionTicks <= 0) - { - if( m_flameAttacks >= SITTING_FLAME_ATTACKS_COUNT) - { - setSynchedAction(e_EnderdragonAction_Takeoff); + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming) { + --m_actionTicks; + if (m_actionTicks <= 0) { + if (m_flameAttacks >= SITTING_FLAME_ATTACKS_COUNT) { + setSynchedAction(e_EnderdragonAction_Takeoff); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: Takeoff\n"); + app.DebugPrintf("Dragon action is now: Takeoff\n"); #endif - newTarget = true; - } - else - { - setSynchedAction(e_EnderdragonAction_Sitting_Scanning); - attackTarget = level->getNearestPlayer( shared_from_this(), SITTING_ATTACK_VIEW_RANGE, SITTING_ATTACK_Y_VIEW_RANGE ); + newTarget = true; + } else { + setSynchedAction(e_EnderdragonAction_Sitting_Scanning); + attackTarget = level->getNearestPlayer( + shared_from_this(), SITTING_ATTACK_VIEW_RANGE, + SITTING_ATTACK_Y_VIEW_RANGE); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: SittingScanning\n"); + app.DebugPrintf("Dragon action is now: SittingScanning\n"); #endif - } - } - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Scanning ) - { - attackTarget = level->getNearestPlayer( shared_from_this(), SITTING_ATTACK_VIEW_RANGE, SITTING_ATTACK_Y_VIEW_RANGE ); - - ++m_actionTicks; - if( attackTarget != NULL ) - { - if(m_actionTicks > SITTING_SCANNING_IDLE_TICKS/4) - { - setSynchedAction(e_EnderdragonAction_Sitting_Attacking); + } + } + } else if (getSynchedAction() == e_EnderdragonAction_Sitting_Scanning) { + attackTarget = level->getNearestPlayer(shared_from_this(), + SITTING_ATTACK_VIEW_RANGE, + SITTING_ATTACK_Y_VIEW_RANGE); + + ++m_actionTicks; + if (attackTarget != NULL) { + if (m_actionTicks > SITTING_SCANNING_IDLE_TICKS / 4) { + setSynchedAction(e_EnderdragonAction_Sitting_Attacking); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: SittingAttacking\n"); + app.DebugPrintf("Dragon action is now: SittingAttacking\n"); #endif - m_actionTicks = ATTACK_TICKS; - } - } - else - { - if(m_actionTicks >= SITTING_SCANNING_IDLE_TICKS) - { - setSynchedAction(e_EnderdragonAction_Takeoff); + m_actionTicks = ATTACK_TICKS; + } + } else { + if (m_actionTicks >= SITTING_SCANNING_IDLE_TICKS) { + setSynchedAction(e_EnderdragonAction_Takeoff); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: Takeoff\n"); + app.DebugPrintf("Dragon action is now: Takeoff\n"); #endif - newTarget = true; - } - } - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Attacking ) - { - --m_actionTicks; - if(m_actionTicks <= 0) - { - ++m_flameAttacks; - setSynchedAction(e_EnderdragonAction_Sitting_Flaming); - attackTarget = level->getNearestPlayer( shared_from_this(), SITTING_ATTACK_VIEW_RANGE, SITTING_ATTACK_Y_VIEW_RANGE ); + newTarget = true; + } + } + } else if (getSynchedAction() == + e_EnderdragonAction_Sitting_Attacking) { + --m_actionTicks; + if (m_actionTicks <= 0) { + ++m_flameAttacks; + setSynchedAction(e_EnderdragonAction_Sitting_Flaming); + attackTarget = level->getNearestPlayer( + shared_from_this(), SITTING_ATTACK_VIEW_RANGE, + SITTING_ATTACK_Y_VIEW_RANGE); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: SittingFlaming\n"); + app.DebugPrintf("Dragon action is now: SittingFlaming\n"); #endif - m_actionTicks = FLAME_TICKS; - } - } - else if( !newTarget && getSynchedAction() == e_EnderdragonAction_Takeoff) - { - int eggHeight = level->getTopSolidBlock(PODIUM_X_POS,PODIUM_Z_POS); //level->getHeightmap(4,4); + m_actionTicks = FLAME_TICKS; + } + } else if (!newTarget && + getSynchedAction() == e_EnderdragonAction_Takeoff) { + int eggHeight = level->getTopSolidBlock( + PODIUM_X_POS, PODIUM_Z_POS); // level->getHeightmap(4,4); - float dist = distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS); - if(dist > (10.0f * 10.0f) ) - { - setSynchedAction(e_EnderdragonAction_HoldingPattern); + float dist = distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS); + if (dist > (10.0f * 10.0f)) { + setSynchedAction(e_EnderdragonAction_HoldingPattern); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: HoldingPattern\n"); + app.DebugPrintf("Dragon action is now: HoldingPattern\n"); #endif - } - } - else if (newTarget || ( (getSynchedAction() != e_EnderdragonAction_Landing && dist < 10 * 10) || dist < 1) || dist > 150 * 150 || horizontalCollision || verticalCollision) - { - findNewTarget(); - } + } + } else if (newTarget || + ((getSynchedAction() != e_EnderdragonAction_Landing && + dist < 10 * 10) || + dist < 1) || + dist > 150 * 150 || horizontalCollision || + verticalCollision) { + findNewTarget(); + } - if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || getSynchedAction() == e_EnderdragonAction_Landing ) - { - if( m_actionTicks < (FLAME_TICKS - 10) ) - { - std::vector > *targets = level->getEntities(shared_from_this(), m_acidArea); + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Landing) { + if (m_actionTicks < (FLAME_TICKS - 10)) { + std::vector >* targets = + level->getEntities(shared_from_this(), m_acidArea); - for( AUTO_VAR(it, targets->begin() ); it != targets->end(); ++it) - { - std::shared_ptr e = std::dynamic_pointer_cast( *it ); - if (e != NULL) - { - //app.DebugPrintf("Attacking entity with acid\n"); - e->hurt(DamageSource::dragonbreath, 2); - } - } - } - } - if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming ) - { - // No movement - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Scanning ) - { - if( attackTarget != NULL) - { - Vec3 *aim = Vec3::newTemp((attackTarget->x - x), 0, (attackTarget->z - z))->normalize(); - Vec3 *dir = Vec3::newTemp(sin(yRot * PI / 180), 0, -cos(yRot * PI / 180))->normalize(); - float dot = (float)dir->dot(aim); - float angleDegs = acos(dot)*180/PI; - angleDegs = angleDegs + 0.5f; + for (AUTO_VAR(it, targets->begin()); it != targets->end(); + ++it) { + std::shared_ptr e = + std::dynamic_pointer_cast(*it); + if (e != NULL) { + // app.DebugPrintf("Attacking entity with acid\n"); + e->hurt(DamageSource::dragonbreath, 2); + } + } + } + } + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming) { + // No movement + } else if (getSynchedAction() == e_EnderdragonAction_Sitting_Scanning) { + if (attackTarget != NULL) { + Vec3* aim = Vec3::newTemp((attackTarget->x - x), 0, + (attackTarget->z - z)) + ->normalize(); + Vec3* dir = Vec3::newTemp(sin(yRot * PI / 180), 0, + -cos(yRot * PI / 180)) + ->normalize(); + float dot = (float)dir->dot(aim); + float angleDegs = acos(dot) * 180 / PI; + angleDegs = angleDegs + 0.5f; - if( angleDegs < 0 || angleDegs > 10 ) - { - double xdd = attackTarget->x - head->x; - //double ydd = (attackTarget->bb->y0 + attackTarget->bbHeight / 2) - (head->y + head->bbHeight / 2); - double zdd = attackTarget->z - head->z; + if (angleDegs < 0 || angleDegs > 10) { + double xdd = attackTarget->x - head->x; + // double ydd = (attackTarget->bb->y0 + + // attackTarget->bbHeight / 2) - (head->y + head->bbHeight / + // 2); + double zdd = attackTarget->z - head->z; - double yRotT = (180) - atan2(xdd, zdd) * 180 / PI; - double yRotD = Mth::wrapDegrees(yRotT - yRot); + double yRotT = (180) - atan2(xdd, zdd) * 180 / PI; + double yRotD = Mth::wrapDegrees(yRotT - yRot); - if (yRotD > 50) yRotD = 50; - if (yRotD < -50) yRotD = -50; + if (yRotD > 50) yRotD = 50; + if (yRotD < -50) yRotD = -50; - double xd = xTarget - x; - double zd = zTarget - z; - yRotA *= 0.80f; + double xd = xTarget - x; + double zd = zTarget - z; + yRotA *= 0.80f; - float rotSpeed = sqrt(xd * xd + zd * zd) * 1 + 1; - double distToTarget = sqrt(xd * xd + zd * zd) * 1 + 1; - if (distToTarget > 40) distToTarget = 40; - yRotA += yRotD * ((0.7f / distToTarget) / rotSpeed); - yRot += yRotA; - } - else - { - //setSynchedAction(e_EnderdragonAction_Sitting_Flaming); + float rotSpeed = sqrt(xd * xd + zd * zd) * 1 + 1; + double distToTarget = sqrt(xd * xd + zd * zd) * 1 + 1; + if (distToTarget > 40) distToTarget = 40; + yRotA += yRotD * ((0.7f / distToTarget) / rotSpeed); + yRot += yRotA; + } else { + // setSynchedAction(e_EnderdragonAction_Sitting_Flaming); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - //app.DebugPrintf("Dragon action is now : SittingFlaming\n"); + // app.DebugPrintf("Dragon action is now : + // SittingFlaming\n"); #endif - //m_actionTicks = FLAME_TICKS; - } - } - else - { - //setSynchedAction(e_EnderdragonAction_Sitting_Flaming); - //app.DebugPrintf("Dragon action is now : SittingFlaming\n"); - //m_actionTicks = 0; - } - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Attacking ) - { + // m_actionTicks = FLAME_TICKS; + } + } else { + // setSynchedAction(e_EnderdragonAction_Sitting_Flaming); + // app.DebugPrintf("Dragon action is now : SittingFlaming\n"); + // m_actionTicks = 0; + } + } else if (getSynchedAction() == + e_EnderdragonAction_Sitting_Attacking) { + } else { + // double xTargetO = xTarget; + // double yTargetO = yTarget; + // double zTargetO = zTarget; + if (getSynchedAction() == e_EnderdragonAction_StrafePlayer && + attackTarget != NULL && m_currentPath != NULL && + m_currentPath->isDone()) { + xTarget = attackTarget->x; + zTarget = attackTarget->z; - } - else - { -// double xTargetO = xTarget; -// double yTargetO = yTarget; -// double zTargetO = zTarget; - if (getSynchedAction() == e_EnderdragonAction_StrafePlayer && attackTarget != NULL && m_currentPath != NULL && m_currentPath->isDone()) - { - xTarget = attackTarget->x; - zTarget = attackTarget->z; + double xd = xTarget - x; + double zd = zTarget - z; + double sd = sqrt(xd * xd + zd * zd); + double ho = 0.4f + sd / 80.0f - 1; + if (ho > 10) ho = 10; + yTarget = attackTarget->bb->y0 + ho; + } else { + // xTarget += random->nextGaussian() * 2; + // zTarget += random->nextGaussian() * 2; + } + ydd = ydd / (sqrt(xdd * xdd + zdd * zdd)); + float max = 0.6f; + if (getSynchedAction() == e_EnderdragonAction_Landing) max = 1.5f; + if (ydd < -max) ydd = -max; + if (ydd > max) ydd = max; + yd += (ydd) * 0.1f; + while (yRot < -180) yRot += 180 * 2; + while (yRot >= 180) yRot -= 180 * 2; - double xd = xTarget - x; - double zd = zTarget - z; - double sd = sqrt(xd * xd + zd * zd); - double ho = 0.4f + sd / 80.0f - 1; - if (ho > 10) ho = 10; - yTarget = attackTarget->bb->y0 + ho; - } - else - { - //xTarget += random->nextGaussian() * 2; - //zTarget += random->nextGaussian() * 2; - } - ydd = ydd / (sqrt(xdd * xdd + zdd * zdd)); - float max = 0.6f; - if(getSynchedAction() == e_EnderdragonAction_Landing) max = 1.5f; - if (ydd < -max) ydd = -max; - if (ydd > max) ydd = max; - yd += (ydd) * 0.1f; - while (yRot < -180) - yRot += 180 * 2; - while (yRot >= 180) - yRot -= 180 * 2; + double yRotT = (180) - atan2(xdd, zdd) * 180 / PI; + double yRotD = yRotT - yRot; + while (yRotD < -180) yRotD += 180 * 2; + while (yRotD >= 180) yRotD -= 180 * 2; + if (yRotD > 50) yRotD = 50; + if (yRotD < -50) yRotD = -50; - double yRotT = (180) - atan2(xdd, zdd) * 180 / PI; - double yRotD = yRotT - yRot; - while (yRotD < -180) - yRotD += 180 * 2; - while (yRotD >= 180) - yRotD -= 180 * 2; + Vec3* aim = + Vec3::newTemp((xTarget - x), (yTarget - y), (zTarget - z)) + ->normalize(); + Vec3* dir = + Vec3::newTemp(sin(yRot * PI / 180), yd, -cos(yRot * PI / 180)) + ->normalize(); + float dot = (float)(dir->dot(aim) + 0.5f) / 1.5f; + if (dot < 0) dot = 0; + yRotA *= 0.80f; - if (yRotD > 50) yRotD = 50; - if (yRotD < -50) yRotD = -50; + float rotSpeed = sqrt(xd * xd + zd * zd) * 1 + 1; + double distToTarget = sqrt(xd * xd + zd * zd) * 1 + 1; + if (distToTarget > 40) distToTarget = 40; + if (getSynchedAction() == e_EnderdragonAction_Landing) { + yRotA += yRotD * (distToTarget / rotSpeed); + } else { + yRotA += yRotD * ((0.7f / distToTarget) / rotSpeed); + } + yRot += yRotA * 0.1f; - Vec3 *aim = Vec3::newTemp((xTarget - x), (yTarget - y), (zTarget - z))->normalize(); - Vec3 *dir = Vec3::newTemp(sin(yRot * PI / 180), yd, -cos(yRot * PI / 180))->normalize(); - float dot = (float) (dir->dot(aim) + 0.5f) / 1.5f; - if (dot < 0) dot = 0; + float span = (float)(2.0f / (distToTarget + 1)); + float speed = 0.06f; + moveRelative(0, -1, speed * (dot * span + (1 - span))); + if (inWall) { + move(xd * 0.8f, yd * 0.8f, zd * 0.8f); + } else { + move(xd, yd, zd); + } - yRotA *= 0.80f; + Vec3* actual = Vec3::newTemp(xd, yd, zd)->normalize(); + float slide = (float)(actual->dot(dir) + 1) / 2.0f; + slide = 0.8f + 0.15f * slide; - float rotSpeed = sqrt(xd * xd + zd * zd) * 1 + 1; - double distToTarget = sqrt(xd * xd + zd * zd) * 1 + 1; - if (distToTarget > 40) distToTarget = 40; - if(getSynchedAction() == e_EnderdragonAction_Landing) - { - yRotA += yRotD * (distToTarget / rotSpeed); - } - else - { - yRotA += yRotD * ((0.7f / distToTarget) / rotSpeed); - } - yRot += yRotA * 0.1f; + xd *= slide; + zd *= slide; + yd *= 0.91f; + } + } - float span = (float) (2.0f / (distToTarget + 1)); - float speed = 0.06f; - moveRelative(0, -1, speed * (dot * span + (1 - span))); - if (inWall) - { - move(xd * 0.8f, yd * 0.8f, zd * 0.8f); - } - else - { - move(xd, yd, zd); + yBodyRot = yRot; - } + head->bbWidth = head->bbHeight = + 1; // 4J Stu - Replaced what was "head" with "neck" //3; + neck->bbWidth = neck->bbHeight = 3; + tail1->bbWidth = tail1->bbHeight = 2; + tail2->bbWidth = tail2->bbHeight = 2; + tail3->bbWidth = tail3->bbHeight = 2; + body->bbHeight = 3; + body->bbWidth = 5; + wing1->bbHeight = 2; + wing1->bbWidth = 4; + wing2->bbHeight = 3; + wing2->bbWidth = 4; - Vec3 *actual = Vec3::newTemp(xd, yd, zd)->normalize(); - float slide = (float) (actual->dot(dir) + 1) / 2.0f; - slide = 0.8f + 0.15f * slide; + // double latencyPosAcomponents[3],latencyPosBcomponents[3]; + // doubleArray latencyPosA = doubleArray(latencyPosAcomponents,3); + // doubleArray latencyPosB = doubleArray(latencyPosBcomponents,3); + // getLatencyPos(latencyPosA, 5, 1); + // getLatencyPos(latencyPosB, 10, 1); + // float tilt = (float) (latencyPosA[1] - latencyPosB[1]) * 10 / 180.0f * + // PI; + float tilt = (float)getTilt(1) / 180.0f * PI; + float ccTilt = cos(tilt); - xd *= slide; - zd *= slide; - yd *= 0.91f; - } - } + // 4J Stu - ssTilt was negative sin(tilt), but this causes the bounding + // boxes of the parts to head in the wrong y direction i.e. head moves up + // when tilting forward, and down when tilting backwards + float ssTilt = sin(tilt); - yBodyRot = yRot; + float rot1 = yRot * PI / 180; + float ss1 = sin(rot1); + float cc1 = cos(rot1); - head->bbWidth = head->bbHeight = 1; // 4J Stu - Replaced what was "head" with "neck" //3; - neck->bbWidth = neck->bbHeight = 3; - tail1->bbWidth = tail1->bbHeight = 2; - tail2->bbWidth = tail2->bbHeight = 2; - tail3->bbWidth = tail3->bbHeight = 2; - body->bbHeight = 3; - body->bbWidth = 5; - wing1->bbHeight = 2; - wing1->bbWidth = 4; - wing2->bbHeight = 3; - wing2->bbWidth = 4; + body->tick(); + body->moveTo(x + ss1 * 0.5f, y, z - cc1 * 0.5f, 0, 0); + wing1->tick(); + wing1->moveTo(x + cc1 * 4.5f, y + 2, z + ss1 * 4.5f, 0, 0); + wing2->tick(); + wing2->moveTo(x - cc1 * 4.5f, y + 2, z - ss1 * 4.5f, 0, 0); - //double latencyPosAcomponents[3],latencyPosBcomponents[3]; - //doubleArray latencyPosA = doubleArray(latencyPosAcomponents,3); - //doubleArray latencyPosB = doubleArray(latencyPosBcomponents,3); - //getLatencyPos(latencyPosA, 5, 1); - //getLatencyPos(latencyPosB, 10, 1); + if (!level->isClientSide) checkAttack(); + if (!level->isClientSide && hurtDuration == 0) { + knockBack(level->getEntities(shared_from_this(), + wing1->bb->grow(4, 2, 4)->move(0, -2, 0))); + knockBack(level->getEntities(shared_from_this(), + wing2->bb->grow(4, 2, 4)->move(0, -2, 0))); + hurt(level->getEntities(shared_from_this(), neck->bb->grow(1, 1, 1))); + hurt(level->getEntities(shared_from_this(), head->bb->grow(1, 1, 1))); + } - //float tilt = (float) (latencyPosA[1] - latencyPosB[1]) * 10 / 180.0f * PI; - float tilt = (float) getTilt(1) / 180.0f * PI; - float ccTilt = cos(tilt); + double p1components[3]; + doubleArray p1 = doubleArray(p1components, 3); + getLatencyPos(p1, 5, 1); - // 4J Stu - ssTilt was negative sin(tilt), but this causes the bounding boxes of the parts to head in the wrong y direction - // i.e. head moves up when tilting forward, and down when tilting backwards - float ssTilt = sin(tilt); + { + // double p0components[3]; + // doubleArray p0 = doubleArray(p0components, 3); + // getLatencyPos(p0, 0, 1); + double yRotDiff = getHeadYRotDiff(1); - float rot1 = yRot * PI / 180; - float ss1 = sin(rot1); - float cc1 = cos(rot1); + float ss = sin((yRot + yRotDiff) * PI / 180 - yRotA * 0.01f); + float cc = cos((yRot + yRotDiff) * PI / 180 - yRotA * 0.01f); + head->tick(); + neck->tick(); + double yOffset = getHeadYOffset(1); // (p0[1] - p1[1]) * 1 - body->tick(); - body->moveTo(x + ss1 * 0.5f, y, z - cc1 * 0.5f, 0, 0); - wing1->tick(); - wing1->moveTo(x + cc1 * 4.5f, y + 2, z + ss1 * 4.5f, 0, 0); - wing2->tick(); - wing2->moveTo(x - cc1 * 4.5f, y + 2, z - ss1 * 4.5f, 0, 0); + // 4J Stu - Changed the head entity to only be the head, and not include + // the neck parts + head->moveTo(x + ss * 6.5f * ccTilt, y + yOffset + ssTilt * 6.5f, + z - cc * 6.5f * ccTilt, 0, 0); - if (!level->isClientSide) checkAttack(); - if (!level->isClientSide && hurtDuration == 0) - { - knockBack(level->getEntities(shared_from_this(), wing1->bb->grow(4, 2, 4)->move(0, -2, 0))); - knockBack(level->getEntities(shared_from_this(), wing2->bb->grow(4, 2, 4)->move(0, -2, 0))); - hurt(level->getEntities(shared_from_this(), neck->bb->grow(1, 1, 1))); - hurt(level->getEntities(shared_from_this(), head->bb->grow(1, 1, 1))); - } + // Neck position is where the java code used to move the "head" object + // which was head and neck + neck->moveTo(x + ss * 5.5f * ccTilt, y + yOffset + ssTilt * 5.5f, + z - cc * 5.5f * ccTilt, 0, 0); - double p1components[3]; - doubleArray p1 = doubleArray(p1components, 3); - getLatencyPos(p1, 5, 1); + double acidX = x + ss * 9.5f * ccTilt; + double acidY = y + yOffset + ssTilt * 10.5f; + double acidZ = z - cc * 9.5f * ccTilt; + m_acidArea->set(acidX - 5, acidY - 17, acidZ - 5, acidX + 5, acidY + 4, + acidZ + 5); - { - //double p0components[3]; - //doubleArray p0 = doubleArray(p0components, 3); - //getLatencyPos(p0, 0, 1); + // app.DebugPrintf("\nDragon is %s, yRot = %f, yRotA = %f, ss = %f, cc = + // %f, ccTilt = %f\n",level->isClientSide?"client":"server", yRot, + // yRotA, ss, cc, ccTilt); app.DebugPrintf("Body (%f,%f,%f) to + // (%f,%f,%f)\n", body->bb->x0, body->bb->y0, body->bb->z0, + // body->bb->x1, body->bb->y1, body->bb->z1); app.DebugPrintf("Neck + // (%f,%f,%f) to (%f,%f,%f)\n", neck->bb->x0, neck->bb->y0, + // neck->bb->z0, neck->bb->x1, neck->bb->y1, neck->bb->z1); + // app.DebugPrintf("Head (%f,%f,%f) to (%f,%f,%f)\n", head->bb->x0, + // head->bb->y0, head->bb->z0, head->bb->x1, head->bb->y1, + // head->bb->z1); app.DebugPrintf("Acid (%f,%f,%f) to (%f,%f,%f)\n\n", + // m_acidArea->x0, m_acidArea->y0, m_acidArea->z0, m_acidArea->x1, + // m_acidArea->y1, m_acidArea->z1); + } - double yRotDiff = getHeadYRotDiff(1); + // Curls/straightens the tail + for (int i = 0; i < 3; i++) { + std::shared_ptr part = nullptr; - float ss = sin((yRot + yRotDiff) * PI / 180 - yRotA * 0.01f); - float cc = cos((yRot + yRotDiff) * PI / 180 - yRotA * 0.01f); - head->tick(); - neck->tick(); - double yOffset = getHeadYOffset(1); // (p0[1] - p1[1]) * 1 + if (i == 0) part = tail1; + if (i == 1) part = tail2; + if (i == 2) part = tail3; - // 4J Stu - Changed the head entity to only be the head, and not include the neck parts - head->moveTo(x + ss * 6.5f * ccTilt, y + yOffset + ssTilt * 6.5f, z - cc * 6.5f * ccTilt, 0, 0); + double p0components[3]; + doubleArray p0 = doubleArray(p0components, 3); + getLatencyPos(p0, 12 + i * 2, 1); - // Neck position is where the java code used to move the "head" object which was head and neck - neck->moveTo(x + ss * 5.5f * ccTilt, y + yOffset + ssTilt * 5.5f, z - cc * 5.5f * ccTilt, 0, 0); + float rot = yRot * PI / 180 + rotWrap(p0[0] - p1[0]) * PI / 180 * (1); + float ss = sin(rot); + float cc = cos(rot); - double acidX = x + ss * 9.5f * ccTilt; - double acidY = y + yOffset + ssTilt * 10.5f; - double acidZ = z - cc * 9.5f * ccTilt; - m_acidArea->set(acidX - 5, acidY - 17, acidZ - 5, acidX + 5, acidY + 4, acidZ + 5); + float dd1 = 1.5f; + float dd = (i + 1) * 2.0f; + part->tick(); + part->moveTo(x - (ss1 * dd1 + ss * dd) * ccTilt, + y + (p0[1] - p1[1]) * 1 - (dd + dd1) * ssTilt + 1.5f, + z + (cc1 * dd1 + cc * dd) * ccTilt, 0, 0); + } - //app.DebugPrintf("\nDragon is %s, yRot = %f, yRotA = %f, ss = %f, cc = %f, ccTilt = %f\n",level->isClientSide?"client":"server", yRot, yRotA, ss, cc, ccTilt); - //app.DebugPrintf("Body (%f,%f,%f) to (%f,%f,%f)\n", body->bb->x0, body->bb->y0, body->bb->z0, body->bb->x1, body->bb->y1, body->bb->z1); - //app.DebugPrintf("Neck (%f,%f,%f) to (%f,%f,%f)\n", neck->bb->x0, neck->bb->y0, neck->bb->z0, neck->bb->x1, neck->bb->y1, neck->bb->z1); - //app.DebugPrintf("Head (%f,%f,%f) to (%f,%f,%f)\n", head->bb->x0, head->bb->y0, head->bb->z0, head->bb->x1, head->bb->y1, head->bb->z1); - //app.DebugPrintf("Acid (%f,%f,%f) to (%f,%f,%f)\n\n", m_acidArea->x0, m_acidArea->y0, m_acidArea->z0, m_acidArea->x1, m_acidArea->y1, m_acidArea->z1); - } + // 4J Stu - Fireball attack taken from Ghast + if (!level->isClientSide) { + double maxDist = 64.0f; + if (getSynchedAction() == e_EnderdragonAction_StrafePlayer && + attackTarget != NULL && + attackTarget->distanceToSqr(shared_from_this()) < + maxDist * maxDist) { + if (this->canSee(attackTarget)) { + m_fireballCharge++; + Vec3* aim = Vec3::newTemp((attackTarget->x - x), 0, + (attackTarget->z - z)) + ->normalize(); + Vec3* dir = Vec3::newTemp(sin(yRot * PI / 180), 0, + -cos(yRot * PI / 180)) + ->normalize(); + float dot = (float)dir->dot(aim); + float angleDegs = acos(dot) * 180 / PI; + angleDegs = angleDegs + 0.5f; - // Curls/straightens the tail - for (int i = 0; i < 3; i++) - { - std::shared_ptr part = nullptr; + if (m_fireballCharge >= 20 && + (angleDegs >= 0 && angleDegs < 10)) { + double d = 1; + Vec3* v = getViewVector(1); + float startingX = head->x - v->x * d; + float startingY = head->y + head->bbHeight / 2 + 0.5f; + float startingZ = head->z - v->z * d; - if (i == 0) part = tail1; - if (i == 1) part = tail2; - if (i == 2) part = tail3; + double xdd = attackTarget->x - startingX; + double ydd = + (attackTarget->bb->y0 + attackTarget->bbHeight / 2) - + (startingY + head->bbHeight / 2); + double zdd = attackTarget->z - startingZ; - double p0components[3]; - doubleArray p0 = doubleArray(p0components, 3); - getLatencyPos(p0, 12 + i * 2, 1); + level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_FIREBALL, + (int)x, (int)y, (int)z, 0); + std::shared_ptr ie = + std::shared_ptr(new DragonFireball( + level, + std::dynamic_pointer_cast(shared_from_this()), + xdd, ydd, zdd)); + ie->x = startingX; + ie->y = startingY; + ie->z = startingZ; + level->addEntity(ie); + m_fireballCharge = 0; - float rot = yRot * PI / 180 + rotWrap(p0[0] - p1[0]) * PI / 180 * (1); - float ss = sin(rot); - float cc = cos(rot); + app.DebugPrintf( + "Finding new target due to having fired a fireball\n"); + if (m_currentPath != NULL) { + while (!m_currentPath->isDone()) { + m_currentPath->next(); + } + } + newTarget = true; + findNewTarget(); + } + } else { + if (m_fireballCharge > 0) m_fireballCharge--; + } + } else { + if (m_fireballCharge > 0) m_fireballCharge--; + } + } + // End fireball attack - float dd1 = 1.5f; - float dd = (i + 1) * 2.0f; - part->tick(); - part->moveTo(x - (ss1 * dd1 + ss * dd) * ccTilt, y + (p0[1] - p1[1]) * 1 - (dd + dd1) * ssTilt + 1.5f, z + (cc1 * dd1 + cc * dd) * ccTilt, 0, 0); - } - - -// 4J Stu - Fireball attack taken from Ghast - if (!level->isClientSide) - { - double maxDist = 64.0f; - if (getSynchedAction() == e_EnderdragonAction_StrafePlayer && attackTarget != NULL && attackTarget->distanceToSqr(shared_from_this()) < maxDist * maxDist) - { - if (this->canSee(attackTarget)) - { - m_fireballCharge++; - Vec3 *aim = Vec3::newTemp((attackTarget->x - x), 0, (attackTarget->z - z))->normalize(); - Vec3 *dir = Vec3::newTemp(sin(yRot * PI / 180), 0, -cos(yRot * PI / 180))->normalize(); - float dot = (float)dir->dot(aim); - float angleDegs = acos(dot)*180/PI; - angleDegs = angleDegs + 0.5f; - - if (m_fireballCharge >= 20 && ( angleDegs >= 0 && angleDegs < 10 )) - { - double d = 1; - Vec3 *v = getViewVector(1); - float startingX = head->x - v->x * d; - float startingY = head->y + head->bbHeight / 2 + 0.5f; - float startingZ = head->z - v->z * d; - - double xdd = attackTarget->x - startingX; - double ydd = (attackTarget->bb->y0 + attackTarget->bbHeight / 2) - (startingY + head->bbHeight / 2); - double zdd = attackTarget->z - startingZ; - - level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_FIREBALL, (int) x, (int) y, (int) z, 0); - std::shared_ptr ie = std::shared_ptr( new DragonFireball(level, std::dynamic_pointer_cast( shared_from_this() ), xdd, ydd, zdd) ); - ie->x = startingX; - ie->y = startingY; - ie->z = startingZ; - level->addEntity(ie); - m_fireballCharge = 0; - - app.DebugPrintf("Finding new target due to having fired a fireball\n"); - if( m_currentPath != NULL ) - { - while(!m_currentPath->isDone()) - { - m_currentPath->next(); - } - } - newTarget = true; - findNewTarget(); - } - } - else - { - if (m_fireballCharge > 0) m_fireballCharge--; - } - } - else - { - if (m_fireballCharge > 0) m_fireballCharge--; - } - } -// End fireball attack - - if (!level->isClientSide) - { - inWall = checkWalls(head->bb) | checkWalls(neck->bb) | checkWalls(body->bb); - } + if (!level->isClientSide) { + inWall = + checkWalls(head->bb) | checkWalls(neck->bb) | checkWalls(body->bb); + } } -void EnderDragon::checkCrystals() -{ - if (nearestCrystal != NULL) - { - if (nearestCrystal->removed) - { - if (!level->isClientSide) - { - hurt(head, DamageSource::explosion, 10); - } +void EnderDragon::checkCrystals() { + if (nearestCrystal != NULL) { + if (nearestCrystal->removed) { + if (!level->isClientSide) { + hurt(head, DamageSource::explosion, 10); + } - nearestCrystal = nullptr; - } - else if (tickCount % 10 == 0) - { - if (health < maxHealth) health++; - } - } + nearestCrystal = nullptr; + } else if (tickCount % 10 == 0) { + if (health < maxHealth) health++; + } + } - if (random->nextInt(10) == 0) - { - float maxDist = 32; - std::vector > *crystals = level->getEntitiesOfClass(typeid(EnderCrystal), bb->grow(maxDist, maxDist, maxDist)); + if (random->nextInt(10) == 0) { + float maxDist = 32; + std::vector >* crystals = + level->getEntitiesOfClass(typeid(EnderCrystal), + bb->grow(maxDist, maxDist, maxDist)); - std::shared_ptr crystal = nullptr; - double nearest = Double::MAX_VALUE; - //for (Entity ec : crystals) - for(AUTO_VAR(it, crystals->begin()); it != crystals->end(); ++it) - { - std::shared_ptr ec = std::dynamic_pointer_cast( *it ); - double dist = ec->distanceToSqr(shared_from_this() ); - if (dist < nearest) - { - nearest = dist; - crystal = ec; - } - } - delete crystals; - + std::shared_ptr crystal = nullptr; + double nearest = Double::MAX_VALUE; + // for (Entity ec : crystals) + for (AUTO_VAR(it, crystals->begin()); it != crystals->end(); ++it) { + std::shared_ptr ec = + std::dynamic_pointer_cast(*it); + double dist = ec->distanceToSqr(shared_from_this()); + if (dist < nearest) { + nearest = dist; + crystal = ec; + } + } + delete crystals; - nearestCrystal = crystal; - } + nearestCrystal = crystal; + } } -void EnderDragon::checkAttack() -{ - //if (tickCount % 20 == 0) - { -// Vec3 *v = getViewVector(1); -// double xdd = 0; -// double ydd = -1; -// double zdd = 0; +void EnderDragon::checkAttack() { + // if (tickCount % 20 == 0) + { + // Vec3 *v = getViewVector(1); + // double xdd = 0; + // double ydd = -1; + // double zdd = 0; - // double x = (body.bb.x0 + body.bb.x1) / 2; - // double y = (body.bb.y0 + body.bb.y1) / 2 - 2; - // double z = (body.bb.z0 + body.bb.z1) / 2; - - } + // double x = (body.bb.x0 + body.bb.x1) / 2; + // double y = (body.bb.y0 + body.bb.y1) / 2 - 2; + // double z = (body.bb.z0 + body.bb.z1) / 2; + } } -void EnderDragon::knockBack(std::vector > *entities) -{ - double xm = (body->bb->x0 + body->bb->x1) / 2; - // double ym = (body.bb.y0 + body.bb.y1) / 2; - double zm = (body->bb->z0 + body->bb->z1) / 2; +void EnderDragon::knockBack(std::vector >* entities) { + double xm = (body->bb->x0 + body->bb->x1) / 2; + // double ym = (body.bb.y0 + body.bb.y1) / 2; + double zm = (body->bb->z0 + body->bb->z1) / 2; - //for (Entity e : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - std::shared_ptr e = std::dynamic_pointer_cast( *it ); - if (e != NULL)//(e instanceof Mob) - { - double xd = e->x - xm; - double zd = e->z - zm; - double dd = xd * xd + zd * zd; - e->push(xd / dd * 4, 0.2f, zd / dd * 4); - } - } + // for (Entity e : entities) + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + std::shared_ptr e = std::dynamic_pointer_cast(*it); + if (e != NULL) //(e instanceof Mob) + { + double xd = e->x - xm; + double zd = e->z - zm; + double dd = xd * xd + zd * zd; + e->push(xd / dd * 4, 0.2f, zd / dd * 4); + } + } } -void EnderDragon::hurt(std::vector > *entities) -{ - //for (int i = 0; i < entities->size(); i++) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - std::shared_ptr e = std::dynamic_pointer_cast( *it );//entities.get(i); - if (e != NULL) //(e instanceof Mob) - { - DamageSource *damageSource = DamageSource::mobAttack( std::dynamic_pointer_cast( shared_from_this() )); - e->hurt(damageSource, 10); - delete damageSource; - } - } +void EnderDragon::hurt(std::vector >* entities) { + // for (int i = 0; i < entities->size(); i++) + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + std::shared_ptr e = + std::dynamic_pointer_cast(*it); // entities.get(i); + if (e != NULL) //(e instanceof Mob) + { + DamageSource* damageSource = DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())); + e->hurt(damageSource, 10); + delete damageSource; + } + } } -void EnderDragon::findNewTarget() -{ - std::shared_ptr playerNearestToEgg = nullptr; +void EnderDragon::findNewTarget() { + std::shared_ptr playerNearestToEgg = nullptr; - // Update current action - switch(getSynchedAction()) - { - case e_EnderdragonAction_Takeoff: - case e_EnderdragonAction_HoldingPattern: - { - if(!newTarget && m_currentPath != NULL && m_currentPath->isDone()) - { - // Distance is 64, which is the radius of the circle - int eggHeight = std::max(level->seaLevel + 5, level->getTopSolidBlock(PODIUM_X_POS,PODIUM_Z_POS)); //level->getHeightmap(4,4); - playerNearestToEgg = level->getNearestPlayer(PODIUM_X_POS, eggHeight, PODIUM_Z_POS, 64.0); - double dist = 64.0f; - if(playerNearestToEgg != NULL) - { - dist = playerNearestToEgg->distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS); - dist /= (8*8*8); - } - //app.DebugPrintf("Adjusted dist is %f\n", dist); + // Update current action + switch (getSynchedAction()) { + case e_EnderdragonAction_Takeoff: + case e_EnderdragonAction_HoldingPattern: { + if (!newTarget && m_currentPath != NULL && + m_currentPath->isDone()) { + // Distance is 64, which is the radius of the circle + int eggHeight = + std::max(level->seaLevel + 5, + level->getTopSolidBlock( + PODIUM_X_POS, + PODIUM_Z_POS)); // level->getHeightmap(4,4); + playerNearestToEgg = level->getNearestPlayer( + PODIUM_X_POS, eggHeight, PODIUM_Z_POS, 64.0); + double dist = 64.0f; + if (playerNearestToEgg != NULL) { + dist = playerNearestToEgg->distanceToSqr( + PODIUM_X_POS, eggHeight, PODIUM_Z_POS); + dist /= (8 * 8 * 8); + } + // app.DebugPrintf("Adjusted dist is %f\n", dist); - if( random->nextInt(m_remainingCrystalsCount + 3) == 0 ) - { - setSynchedAction(e_EnderdragonAction_LandingApproach); + if (random->nextInt(m_remainingCrystalsCount + 3) == 0) { + setSynchedAction(e_EnderdragonAction_LandingApproach); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: LandingApproach\n"); + app.DebugPrintf("Dragon action is now: LandingApproach\n"); #endif - } - // More likely to strafe a player if they are close to the egg, or there are not many crystals remaining - else if( playerNearestToEgg != NULL && (random->nextInt( abs(dist) + 2 ) == 0 || random->nextInt( m_remainingCrystalsCount + 2 ) == 0) ) - { - setSynchedAction(e_EnderdragonAction_StrafePlayer); + } + // More likely to strafe a player if they are close to the egg, + // or there are not many crystals remaining + else if (playerNearestToEgg != NULL && + (random->nextInt(abs(dist) + 2) == 0 || + random->nextInt(m_remainingCrystalsCount + 2) == 0)) { + setSynchedAction(e_EnderdragonAction_StrafePlayer); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: StrafePlayer\n"); + app.DebugPrintf("Dragon action is now: StrafePlayer\n"); #endif - } - } - } - break; - case e_EnderdragonAction_StrafePlayer: - // Always return to the holding pattern after strafing - if(m_currentPath == NULL || (m_currentPath->isDone() && newTarget) ) - { - setSynchedAction(e_EnderdragonAction_HoldingPattern); + } + } + } break; + case e_EnderdragonAction_StrafePlayer: + // Always return to the holding pattern after strafing + if (m_currentPath == NULL || + (m_currentPath->isDone() && newTarget)) { + setSynchedAction(e_EnderdragonAction_HoldingPattern); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: HoldingPattern\n"); + app.DebugPrintf("Dragon action is now: HoldingPattern\n"); #endif - } - break; - case e_EnderdragonAction_Landing: -// setSynchedAction(e_EnderdragonAction_Sitting_Flaming); -//#if PRINT_DRAGON_STATE_CHANGE_MESSAGES -// app.DebugPrintf("Dragon action is now: SittingFlaming\n"); -//#endif -// m_actionTicks = FLAME_TICKS; - - m_flameAttacks = 0; - setSynchedAction(e_EnderdragonAction_Sitting_Scanning); - attackTarget = level->getNearestPlayer( shared_from_this(), SITTING_ATTACK_VIEW_RANGE, SITTING_ATTACK_Y_VIEW_RANGE ); + } + break; + case e_EnderdragonAction_Landing: + // setSynchedAction(e_EnderdragonAction_Sitting_Flaming); + // #if PRINT_DRAGON_STATE_CHANGE_MESSAGES + // app.DebugPrintf("Dragon action is now: + //SittingFlaming\n"); #endif m_actionTicks = FLAME_TICKS; + + m_flameAttacks = 0; + setSynchedAction(e_EnderdragonAction_Sitting_Scanning); + attackTarget = level->getNearestPlayer(shared_from_this(), + SITTING_ATTACK_VIEW_RANGE, + SITTING_ATTACK_Y_VIEW_RANGE); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: SittingScanning\n"); + app.DebugPrintf("Dragon action is now: SittingScanning\n"); #endif - m_actionTicks = 0; - break; - default: - break; - }; + m_actionTicks = 0; + break; + default: + break; + }; - newTarget = false; + newTarget = false; - //if (random->nextInt(2) == 0 && level->players.size() > 0) - if(getSynchedAction() == e_EnderdragonAction_StrafePlayer && playerNearestToEgg != NULL) - { - attackTarget = playerNearestToEgg; - strafeAttackTarget(); - } - else if(getSynchedAction() == e_EnderdragonAction_LandingApproach) - { - // Generate a new path if we don't currently have one - if( m_currentPath == NULL || m_currentPath->isDone() ) - { - int currentNodeIndex = findClosestNode(); - - // To get the angle to the player correct when landing, head to a node diametrically opposite the player, then swoop in to 4,4 - int eggHeight = std::max( level->seaLevel + 5, level->getTopSolidBlock(PODIUM_X_POS,PODIUM_Z_POS) ); //level->getHeightmap(4,4); - playerNearestToEgg = level->getNearestPlayer(PODIUM_X_POS, eggHeight, PODIUM_Z_POS, 128.0); + // if (random->nextInt(2) == 0 && level->players.size() > 0) + if (getSynchedAction() == e_EnderdragonAction_StrafePlayer && + playerNearestToEgg != NULL) { + attackTarget = playerNearestToEgg; + strafeAttackTarget(); + } else if (getSynchedAction() == e_EnderdragonAction_LandingApproach) { + // Generate a new path if we don't currently have one + if (m_currentPath == NULL || m_currentPath->isDone()) { + int currentNodeIndex = findClosestNode(); - int targetNodeIndex = 0 ; - if(playerNearestToEgg != NULL) - { - Vec3 *aim = Vec3::newTemp(playerNearestToEgg->x, 0, playerNearestToEgg->z)->normalize(); - //app.DebugPrintf("Final marker node near (%f,%d,%f)\n", -aim->x*40,105,-aim->z*40 ); - targetNodeIndex = findClosestNode(-aim->x*40,105.0,-aim->z*40); - } - else - { - targetNodeIndex = findClosestNode(40.0, eggHeight, 0.0); - } - Node finalNode(PODIUM_X_POS, eggHeight, PODIUM_Z_POS); + // To get the angle to the player correct when landing, head to a + // node diametrically opposite the player, then swoop in to 4,4 + int eggHeight = std::max( + level->seaLevel + 5, + level->getTopSolidBlock( + PODIUM_X_POS, PODIUM_Z_POS)); // level->getHeightmap(4,4); + playerNearestToEgg = level->getNearestPlayer( + PODIUM_X_POS, eggHeight, PODIUM_Z_POS, 128.0); - if(m_currentPath != NULL) delete m_currentPath; - m_currentPath = findPath(currentNodeIndex,targetNodeIndex, &finalNode); + int targetNodeIndex = 0; + if (playerNearestToEgg != NULL) { + Vec3* aim = Vec3::newTemp(playerNearestToEgg->x, 0, + playerNearestToEgg->z) + ->normalize(); + // app.DebugPrintf("Final marker node near (%f,%d,%f)\n", + // -aim->x*40,105,-aim->z*40 ); + targetNodeIndex = + findClosestNode(-aim->x * 40, 105.0, -aim->z * 40); + } else { + targetNodeIndex = findClosestNode(40.0, eggHeight, 0.0); + } + Node finalNode(PODIUM_X_POS, eggHeight, PODIUM_Z_POS); - // Always skip the first node (as that's where we are already) - if(m_currentPath != NULL) m_currentPath->next(); - } + if (m_currentPath != NULL) delete m_currentPath; + m_currentPath = + findPath(currentNodeIndex, targetNodeIndex, &finalNode); - m_actionTicks = 0; + // Always skip the first node (as that's where we are already) + if (m_currentPath != NULL) m_currentPath->next(); + } - navigateToNextPathNode(); + m_actionTicks = 0; - if(m_currentPath != NULL && m_currentPath->isDone()) - { - setSynchedAction(e_EnderdragonAction_Landing); + navigateToNextPathNode(); + + if (m_currentPath != NULL && m_currentPath->isDone()) { + setSynchedAction(e_EnderdragonAction_Landing); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: Landing\n"); + app.DebugPrintf("Dragon action is now: Landing\n"); #endif - } - } - else if(getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning) - { - // Does no movement - } - else - { - // Default is e_EnderdragonAction_HoldingPattern - // Generate a new path if we don't currently have one - if(m_currentPath == NULL || m_currentPath->isDone() ) - { - int currentNodeIndex = findClosestNode(); - int targetNodeIndex = currentNodeIndex; - //if(random->nextInt(4) == 0) m_holdingPatternClockwise = !m_holdingPatternClockwise; + } + } else if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning) { + // Does no movement + } else { + // Default is e_EnderdragonAction_HoldingPattern + // Generate a new path if we don't currently have one + if (m_currentPath == NULL || m_currentPath->isDone()) { + int currentNodeIndex = findClosestNode(); + int targetNodeIndex = currentNodeIndex; + // if(random->nextInt(4) == 0) m_holdingPatternClockwise = + // !m_holdingPatternClockwise; - if( getSynchedAction() == e_EnderdragonAction_Takeoff) - { - Vec3 *v = getHeadLookVector(1); - targetNodeIndex = findClosestNode(-v->x*40,105.0,-v->z*40); - } - else - { - if(random->nextInt(8) == 0) - { - m_holdingPatternClockwise = !m_holdingPatternClockwise; - targetNodeIndex = targetNodeIndex + 6; - } + if (getSynchedAction() == e_EnderdragonAction_Takeoff) { + Vec3* v = getHeadLookVector(1); + targetNodeIndex = + findClosestNode(-v->x * 40, 105.0, -v->z * 40); + } else { + if (random->nextInt(8) == 0) { + m_holdingPatternClockwise = !m_holdingPatternClockwise; + targetNodeIndex = targetNodeIndex + 6; + } - if(m_holdingPatternClockwise) targetNodeIndex = targetNodeIndex + 1; - else targetNodeIndex = targetNodeIndex - 1; - } + if (m_holdingPatternClockwise) + targetNodeIndex = targetNodeIndex + 1; + else + targetNodeIndex = targetNodeIndex - 1; + } - if(m_remainingCrystalsCount <= 0) - { - // If no crystals left, navigate only between nodes 12-19 - targetNodeIndex -= 12; - targetNodeIndex = targetNodeIndex&7; // 4J-RR - was %8, but that could create a result of -1 here when targetNodeIndex was 11 - targetNodeIndex += 12; - } - else - { - // If crystals are left, navigate only between nodes 0-11 - targetNodeIndex = targetNodeIndex%12; - if(targetNodeIndex < 0) targetNodeIndex += 12; - } + if (m_remainingCrystalsCount <= 0) { + // If no crystals left, navigate only between nodes 12-19 + targetNodeIndex -= 12; + targetNodeIndex = + targetNodeIndex & + 7; // 4J-RR - was %8, but that could create a result of -1 + // here when targetNodeIndex was 11 + targetNodeIndex += 12; + } else { + // If crystals are left, navigate only between nodes 0-11 + targetNodeIndex = targetNodeIndex % 12; + if (targetNodeIndex < 0) targetNodeIndex += 12; + } - if(m_currentPath != NULL) delete m_currentPath; - m_currentPath = findPath(currentNodeIndex,targetNodeIndex); + if (m_currentPath != NULL) delete m_currentPath; + m_currentPath = findPath(currentNodeIndex, targetNodeIndex); - // Always skip the first node (as that's where we are already) - if(m_currentPath != NULL) m_currentPath->next(); - } + // Always skip the first node (as that's where we are already) + if (m_currentPath != NULL) m_currentPath->next(); + } - navigateToNextPathNode(); + navigateToNextPathNode(); - if(getSynchedAction() != e_EnderdragonAction_StrafePlayer) attackTarget = nullptr; - } + if (getSynchedAction() != e_EnderdragonAction_StrafePlayer) + attackTarget = nullptr; + } } -float EnderDragon::rotWrap(double d) -{ - while (d >= 180) - d -= 360; - while (d < -180) - d += 360; - return (float) d; +float EnderDragon::rotWrap(double d) { + while (d >= 180) d -= 360; + while (d < -180) d += 360; + return (float)d; } -bool EnderDragon::checkWalls(AABB *bb) -{ - int x0 = Mth::floor(bb->x0); - int y0 = Mth::floor(bb->y0); - int z0 = Mth::floor(bb->z0); - int x1 = Mth::floor(bb->x1); - int y1 = Mth::floor(bb->y1); - int z1 = Mth::floor(bb->z1); - bool hitWall = false; - bool destroyedTile = false; - for (int x = x0; x <= x1; x++) - { - for (int y = y0; y <= y1; y++) - { - for (int z = z0; z <= z1; z++) - { - int t = level->getTile(x, y, z); - // 4J Stu - Don't remove fire - if (t == 0 || t == Tile::fire_Id) - { +bool EnderDragon::checkWalls(AABB* bb) { + int x0 = Mth::floor(bb->x0); + int y0 = Mth::floor(bb->y0); + int z0 = Mth::floor(bb->z0); + int x1 = Mth::floor(bb->x1); + int y1 = Mth::floor(bb->y1); + int z1 = Mth::floor(bb->z1); + bool hitWall = false; + bool destroyedTile = false; + for (int x = x0; x <= x1; x++) { + for (int y = y0; y <= y1; y++) { + for (int z = z0; z <= z1; z++) { + int t = level->getTile(x, y, z); + // 4J Stu - Don't remove fire + if (t == 0 || t == Tile::fire_Id) { + } else if (t == Tile::obsidian_Id || t == Tile::whiteStone_Id || + t == Tile::unbreakable_Id) { + hitWall = true; + } else { + destroyedTile = true; + level->setTile(x, y, z, 0); + } + } + } + } - } - else if (t == Tile::obsidian_Id || t == Tile::whiteStone_Id || t == Tile::unbreakable_Id) - { - hitWall = true; - } - else - { - destroyedTile = true; - level->setTile(x, y, z, 0); - } - } - } - } + if (destroyedTile) { + double x = bb->x0 + (bb->x1 - bb->x0) * random->nextFloat(); + double y = bb->y0 + (bb->y1 - bb->y0) * random->nextFloat(); + double z = bb->z0 + (bb->z1 - bb->z0) * random->nextFloat(); + level->addParticle(eParticleType_largeexplode, x, y, z, 0, 0, 0); + } - if (destroyedTile) - { - double x = bb->x0 + (bb->x1 - bb->x0) * random->nextFloat(); - double y = bb->y0 + (bb->y1 - bb->y0) * random->nextFloat(); - double z = bb->z0 + (bb->z1 - bb->z0) * random->nextFloat(); - level->addParticle(eParticleType_largeexplode, x, y, z, 0, 0, 0); - } - - return hitWall; + return hitWall; } -bool EnderDragon::hurt(std::shared_ptr bossMobPart, DamageSource *source, int damage) -{ - if (bossMobPart != head) - { - damage = damage / 4 + 1; - } +bool EnderDragon::hurt(std::shared_ptr bossMobPart, + DamageSource* source, int damage) { + if (bossMobPart != head) { + damage = damage / 4 + 1; + } - //float rot1 = yRot * PI / 180; - //float ss1 = sin(rot1); - //float cc1 = cos(rot1); + // float rot1 = yRot * PI / 180; + // float ss1 = sin(rot1); + // float cc1 = cos(rot1); - //xTarget = x + ss1 * 5 + (random->nextFloat() - 0.5f) * 2; - //yTarget = y + random->nextFloat() * 3 + 1; - //zTarget = z - cc1 * 5 + (random->nextFloat() - 0.5f) * 2; - //attackTarget = NULL; + // xTarget = x + ss1 * 5 + (random->nextFloat() - 0.5f) * 2; + // yTarget = y + random->nextFloat() * 3 + 1; + // zTarget = z - cc1 * 5 + (random->nextFloat() - 0.5f) * 2; + // attackTarget = NULL; - if (source == DamageSource::explosion || (std::dynamic_pointer_cast(source->getEntity()) != NULL)) - { - int healthBefore = health; - reallyHurt(source, damage); + if (source == DamageSource::explosion || + (std::dynamic_pointer_cast(source->getEntity()) != NULL)) { + int healthBefore = health; + reallyHurt(source, damage); - //if(!level->isClientSide) app.DebugPrintf("Health is now %d\n", health); - if( health <= 0 && - !( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) ) - { - health = 1; + // if(!level->isClientSide) app.DebugPrintf("Health is now %d\n", + // health); + if (health <= 0 && + !(getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking)) { + health = 1; - if( setSynchedAction(e_EnderdragonAction_LandingApproach) ) - { - if( m_currentPath != NULL ) - { - while(!m_currentPath->isDone()) - { - m_currentPath->next(); - } - } - app.DebugPrintf("Dragon should be dead, so landing.\n"); + if (setSynchedAction(e_EnderdragonAction_LandingApproach)) { + if (m_currentPath != NULL) { + while (!m_currentPath->isDone()) { + m_currentPath->next(); + } + } + app.DebugPrintf("Dragon should be dead, so landing.\n"); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: LandingApproach\n"); + app.DebugPrintf("Dragon action is now: LandingApproach\n"); #endif - findNewTarget(); - } - } + findNewTarget(); + } + } - if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - { - m_sittingDamageReceived += healthBefore - health; + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) { + m_sittingDamageReceived += healthBefore - health; - if(m_sittingDamageReceived > (SITTING_ALLOWED_DAMAGE_PERCENTAGE*getMaxHealth() ) ) - { - m_sittingDamageReceived = 0; - setSynchedAction(e_EnderdragonAction_Takeoff); - newTarget = true; + if (m_sittingDamageReceived > + (SITTING_ALLOWED_DAMAGE_PERCENTAGE * getMaxHealth())) { + m_sittingDamageReceived = 0; + setSynchedAction(e_EnderdragonAction_Takeoff); + newTarget = true; #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: Takeoff\n"); + app.DebugPrintf("Dragon action is now: Takeoff\n"); #endif - } - } - } - return true; + } + } + } + return true; } -void EnderDragon::tickDeath() -{ - if( getSynchedAction() != e_EnderdragonAction_Sitting_Flaming && - getSynchedAction() != e_EnderdragonAction_Sitting_Scanning && - getSynchedAction() != e_EnderdragonAction_Sitting_Attacking) - { - if(!level->isClientSide) health = 1; - return; - } +void EnderDragon::tickDeath() { + if (getSynchedAction() != e_EnderdragonAction_Sitting_Flaming && + getSynchedAction() != e_EnderdragonAction_Sitting_Scanning && + getSynchedAction() != e_EnderdragonAction_Sitting_Attacking) { + if (!level->isClientSide) health = 1; + return; + } - dragonDeathTime++; - if (dragonDeathTime >= 180 && dragonDeathTime <= 200) - { - float xo = (random->nextFloat() - 0.5f) * 8; - float yo = (random->nextFloat() - 0.5f) * 4; - float zo = (random->nextFloat() - 0.5f) * 8; - level->addParticle(eParticleType_hugeexplosion, x + xo, y + 2 + yo, z + zo, 0, 0, 0); - } - if (!level->isClientSide) - { - if (dragonDeathTime > 150 && dragonDeathTime % 5 == 0) - { - int xpCount = 1000; - while (xpCount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(xpCount); - xpCount -= newCount; - level->addEntity(std::shared_ptr( new ExperienceOrb(level, x, y, z, newCount) )); - } - } - if (dragonDeathTime == 1) - { - //level->globalLevelEvent(LevelEvent::SOUND_DRAGON_DEATH, (int) x, (int) y, (int) z, 0); - level->levelEvent(LevelEvent::SOUND_DRAGON_DEATH, (int) x, (int) y, (int) z, 0); - } - } - move(0, 0.1f, 0); - yBodyRot = yRot += 20.0f; + dragonDeathTime++; + if (dragonDeathTime >= 180 && dragonDeathTime <= 200) { + float xo = (random->nextFloat() - 0.5f) * 8; + float yo = (random->nextFloat() - 0.5f) * 4; + float zo = (random->nextFloat() - 0.5f) * 8; + level->addParticle(eParticleType_hugeexplosion, x + xo, y + 2 + yo, + z + zo, 0, 0, 0); + } + if (!level->isClientSide) { + if (dragonDeathTime > 150 && dragonDeathTime % 5 == 0) { + int xpCount = 1000; + while (xpCount > 0) { + int newCount = ExperienceOrb::getExperienceValue(xpCount); + xpCount -= newCount; + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x, y, z, newCount))); + } + } + if (dragonDeathTime == 1) { + // level->globalLevelEvent(LevelEvent::SOUND_DRAGON_DEATH, (int) x, + // (int) y, (int) z, 0); + level->levelEvent(LevelEvent::SOUND_DRAGON_DEATH, (int)x, (int)y, + (int)z, 0); + } + } + move(0, 0.1f, 0); + yBodyRot = yRot += 20.0f; - if (dragonDeathTime == 200 && !level->isClientSide) - { - //level->levelEvent(NULL, LevelEvent::ENDERDRAGON_KILLED, (int) x, (int) y, (int) z, 0); + if (dragonDeathTime == 200 && !level->isClientSide) { + // level->levelEvent(NULL, LevelEvent::ENDERDRAGON_KILLED, (int) x, + // (int) y, (int) z, 0); - int xpCount = 2000; - while (xpCount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(xpCount); - xpCount -= newCount; - level->addEntity(std::shared_ptr( new ExperienceOrb(level, x, y, z, newCount))); - } - int xo = 5 + random->nextInt(2) * 2 - 1; - int zo = 5 + random->nextInt(2) * 2 - 1; - if (random->nextInt(2) == 0) - { - xo = 0; - } - else - { - zo = 0; - } - // 4J-PB changed to center this between the pillars - spawnExitPortal(0,0);//Mth::floor(x), Mth::floor(z)); - remove(); - } + int xpCount = 2000; + while (xpCount > 0) { + int newCount = ExperienceOrb::getExperienceValue(xpCount); + xpCount -= newCount; + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x, y, z, newCount))); + } + int xo = 5 + random->nextInt(2) * 2 - 1; + int zo = 5 + random->nextInt(2) * 2 - 1; + if (random->nextInt(2) == 0) { + xo = 0; + } else { + zo = 0; + } + // 4J-PB changed to center this between the pillars + spawnExitPortal(0, 0); // Mth::floor(x), Mth::floor(z)); + remove(); + } } -void EnderDragon::spawnExitPortal(int x, int z) -{ - int y = level->seaLevel; +void EnderDragon::spawnExitPortal(int x, int z) { + int y = level->seaLevel; - TheEndPortal::allowAnywhere(true); + TheEndPortal::allowAnywhere(true); - int r = 4; - for (int yy = y - 1; yy <= y + 32; yy++) - { - for (int xx = x - r; xx <= x + r; xx++) - { - for (int zz = z - r; zz <= z + r; zz++) - { - double xd = xx - x; - double zd = zz - z; - double d = sqrt(xd * xd + zd * zd); - if (d <= r - 0.5) - { - if (yy < y) - { - if (d > r - 1 - 0.5) - { - } - else - { - level->setTile(xx, yy, zz, Tile::unbreakable_Id); - } - } - else if (yy > y) - { - level->setTile(xx, yy, zz, 0); - } - else - { - if (d > r - 1 - 0.5) - { - level->setTile(xx, yy, zz, Tile::unbreakable_Id); - } - else - { - level->setTile(xx, yy, zz, Tile::endPortalTile_Id); - } - } - } - } - } - } + int r = 4; + for (int yy = y - 1; yy <= y + 32; yy++) { + for (int xx = x - r; xx <= x + r; xx++) { + for (int zz = z - r; zz <= z + r; zz++) { + double xd = xx - x; + double zd = zz - z; + double d = sqrt(xd * xd + zd * zd); + if (d <= r - 0.5) { + if (yy < y) { + if (d > r - 1 - 0.5) { + } else { + level->setTile(xx, yy, zz, Tile::unbreakable_Id); + } + } else if (yy > y) { + level->setTile(xx, yy, zz, 0); + } else { + if (d > r - 1 - 0.5) { + level->setTile(xx, yy, zz, Tile::unbreakable_Id); + } else { + level->setTile(xx, yy, zz, Tile::endPortalTile_Id); + } + } + } + } + } + } - level->setTile(x, y + 0, z, Tile::unbreakable_Id); - level->setTile(x, y + 1, z, Tile::unbreakable_Id); - level->setTile(x, y + 2, z, Tile::unbreakable_Id); - level->setTile(x - 1, y + 2, z, Tile::torch_Id); - level->setTile(x + 1, y + 2, z, Tile::torch_Id); - level->setTile(x, y + 2, z - 1, Tile::torch_Id); - level->setTile(x, y + 2, z + 1, Tile::torch_Id); - level->setTile(x, y + 3, z, Tile::unbreakable_Id); - level->setTile(x, y + 4, z, Tile::dragonEgg_Id); + level->setTile(x, y + 0, z, Tile::unbreakable_Id); + level->setTile(x, y + 1, z, Tile::unbreakable_Id); + level->setTile(x, y + 2, z, Tile::unbreakable_Id); + level->setTile(x - 1, y + 2, z, Tile::torch_Id); + level->setTile(x + 1, y + 2, z, Tile::torch_Id); + level->setTile(x, y + 2, z - 1, Tile::torch_Id); + level->setTile(x, y + 2, z + 1, Tile::torch_Id); + level->setTile(x, y + 3, z, Tile::unbreakable_Id); + level->setTile(x, y + 4, z, Tile::dragonEgg_Id); - // 4J-PB - The podium can be floating with nothing under it, so put some whiteStone under it if this is the case - for (int yy = y - 5; yy < y - 1; yy++) - { - for (int xx = x - (r - 1); xx <= x + (r - 1); xx++) - { - for (int zz = z - (r - 1); zz <= z + (r - 1); zz++) - { - if(level->isEmptyTile(xx,yy,zz)) - { - level->setTile(xx, yy, zz, Tile::whiteStone_Id); - } - } - } - } + // 4J-PB - The podium can be floating with nothing under it, so put some + // whiteStone under it if this is the case + for (int yy = y - 5; yy < y - 1; yy++) { + for (int xx = x - (r - 1); xx <= x + (r - 1); xx++) { + for (int zz = z - (r - 1); zz <= z + (r - 1); zz++) { + if (level->isEmptyTile(xx, yy, zz)) { + level->setTile(xx, yy, zz, Tile::whiteStone_Id); + } + } + } + } - TheEndPortal::allowAnywhere(false); + TheEndPortal::allowAnywhere(false); } -void EnderDragon::checkDespawn() -{ +void EnderDragon::checkDespawn() {} + +std::vector >* EnderDragon::getSubEntities() { + return &subEntities; } -std::vector > *EnderDragon::getSubEntities() -{ - return &subEntities; -} +bool EnderDragon::isPickable() { return false; } -bool EnderDragon::isPickable() -{ - return false; -} +// Fix for TU9 Enderdragon sound hits being the player sound hits - moved this +// forward from later version +int EnderDragon::getHurtSound() { return eSoundType_MOB_ENDERDRAGON_HIT; } -// Fix for TU9 Enderdragon sound hits being the player sound hits - moved this forward from later version -int EnderDragon::getHurtSound() -{ - return eSoundType_MOB_ENDERDRAGON_HIT; -} - -int EnderDragon::getSynchedHealth() -{ - return entityData->getInteger(DATA_ID_SYNCHED_HEALTH); +int EnderDragon::getSynchedHealth() { + return entityData->getInteger(DATA_ID_SYNCHED_HEALTH); } // 4J Added for new dragon behaviour -bool EnderDragon::setSynchedAction(EEnderdragonAction action, bool force /*= false*/) -{ - bool validTransition = false; - // Check if this is a valid state transition - switch(getSynchedAction()) - { - case e_EnderdragonAction_HoldingPattern: - switch(action) - { - case e_EnderdragonAction_StrafePlayer: - case e_EnderdragonAction_LandingApproach: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_StrafePlayer: - switch(action) - { - case e_EnderdragonAction_HoldingPattern: - case e_EnderdragonAction_LandingApproach: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_LandingApproach: - switch(action) - { - case e_EnderdragonAction_Landing: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_Landing: - switch(action) - { - case e_EnderdragonAction_Sitting_Flaming: - case e_EnderdragonAction_Sitting_Scanning: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_Takeoff: - switch(action) - { - case e_EnderdragonAction_HoldingPattern: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_Sitting_Flaming: - switch(action) - { - case e_EnderdragonAction_Sitting_Scanning: - case e_EnderdragonAction_Sitting_Attacking: - case e_EnderdragonAction_Takeoff: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_Sitting_Scanning: - switch(action) - { - case e_EnderdragonAction_Sitting_Flaming: - case e_EnderdragonAction_Sitting_Attacking: - case e_EnderdragonAction_Takeoff: - validTransition = true; - break; - default: - break; - }; - break; - case e_EnderdragonAction_Sitting_Attacking: - switch(action) - { - case e_EnderdragonAction_Sitting_Flaming: - case e_EnderdragonAction_Sitting_Scanning: - case e_EnderdragonAction_Takeoff: - validTransition = true; - break; - default: - break; - }; - break; - default: - break; - }; +bool EnderDragon::setSynchedAction(EEnderdragonAction action, + bool force /*= false*/) { + bool validTransition = false; + // Check if this is a valid state transition + switch (getSynchedAction()) { + case e_EnderdragonAction_HoldingPattern: + switch (action) { + case e_EnderdragonAction_StrafePlayer: + case e_EnderdragonAction_LandingApproach: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_StrafePlayer: + switch (action) { + case e_EnderdragonAction_HoldingPattern: + case e_EnderdragonAction_LandingApproach: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_LandingApproach: + switch (action) { + case e_EnderdragonAction_Landing: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_Landing: + switch (action) { + case e_EnderdragonAction_Sitting_Flaming: + case e_EnderdragonAction_Sitting_Scanning: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_Takeoff: + switch (action) { + case e_EnderdragonAction_HoldingPattern: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_Sitting_Flaming: + switch (action) { + case e_EnderdragonAction_Sitting_Scanning: + case e_EnderdragonAction_Sitting_Attacking: + case e_EnderdragonAction_Takeoff: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_Sitting_Scanning: + switch (action) { + case e_EnderdragonAction_Sitting_Flaming: + case e_EnderdragonAction_Sitting_Attacking: + case e_EnderdragonAction_Takeoff: + validTransition = true; + break; + default: + break; + }; + break; + case e_EnderdragonAction_Sitting_Attacking: + switch (action) { + case e_EnderdragonAction_Sitting_Flaming: + case e_EnderdragonAction_Sitting_Scanning: + case e_EnderdragonAction_Takeoff: + validTransition = true; + break; + default: + break; + }; + break; + default: + break; + }; - if( force || validTransition ) - { - entityData->set(DATA_ID_SYNCHED_ACTION, action); - } - else - { - app.DebugPrintf("EnderDragon: Invalid state transition from %d to %d\n", getSynchedAction(), action); - } + if (force || validTransition) { + entityData->set(DATA_ID_SYNCHED_ACTION, action); + } else { + app.DebugPrintf("EnderDragon: Invalid state transition from %d to %d\n", + getSynchedAction(), action); + } - return force || validTransition; + return force || validTransition; } -EnderDragon::EEnderdragonAction EnderDragon::getSynchedAction() -{ - return (EEnderdragonAction)entityData->getInteger(DATA_ID_SYNCHED_ACTION); +EnderDragon::EEnderdragonAction EnderDragon::getSynchedAction() { + return (EEnderdragonAction)entityData->getInteger(DATA_ID_SYNCHED_ACTION); } -void EnderDragon::handleCrystalDestroyed(DamageSource *source) -{ - AABB *tempBB = AABB::newTemp(PODIUM_X_POS,84.0,PODIUM_Z_POS,PODIUM_X_POS+1.0,85.0,PODIUM_Z_POS+1.0); - std::vector > *crystals = level->getEntitiesOfClass(typeid(EnderCrystal), tempBB->grow(48, 40, 48)); - m_remainingCrystalsCount = (int)crystals->size() - 1; - if(m_remainingCrystalsCount < 0) m_remainingCrystalsCount = 0; - delete crystals; +void EnderDragon::handleCrystalDestroyed(DamageSource* source) { + AABB* tempBB = AABB::newTemp(PODIUM_X_POS, 84.0, PODIUM_Z_POS, + PODIUM_X_POS + 1.0, 85.0, PODIUM_Z_POS + 1.0); + std::vector >* crystals = level->getEntitiesOfClass( + typeid(EnderCrystal), tempBB->grow(48, 40, 48)); + m_remainingCrystalsCount = (int)crystals->size() - 1; + if (m_remainingCrystalsCount < 0) m_remainingCrystalsCount = 0; + delete crystals; - app.DebugPrintf("Crystal count is now %d\n",m_remainingCrystalsCount); + app.DebugPrintf("Crystal count is now %d\n", m_remainingCrystalsCount); - //--m_remainingCrystalsCount; + //--m_remainingCrystalsCount; - if(m_remainingCrystalsCount%2 == 0) - { - if(setSynchedAction(e_EnderdragonAction_LandingApproach)) - { - if( m_currentPath != NULL ) - { - while(!m_currentPath->isDone()) - { - m_currentPath->next(); - } - } - m_actionTicks = 1; + if (m_remainingCrystalsCount % 2 == 0) { + if (setSynchedAction(e_EnderdragonAction_LandingApproach)) { + if (m_currentPath != NULL) { + while (!m_currentPath->isDone()) { + m_currentPath->next(); + } + } + m_actionTicks = 1; #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: LandingApproach\n"); + app.DebugPrintf("Dragon action is now: LandingApproach\n"); #endif - } - } - else if(std::dynamic_pointer_cast(source->getEntity()) != NULL) - { - if(setSynchedAction(e_EnderdragonAction_StrafePlayer)) - { - attackTarget = std::dynamic_pointer_cast(source->getEntity()); + } + } else if (std::dynamic_pointer_cast(source->getEntity()) != NULL) { + if (setSynchedAction(e_EnderdragonAction_StrafePlayer)) { + attackTarget = + std::dynamic_pointer_cast(source->getEntity()); #if PRINT_DRAGON_STATE_CHANGE_MESSAGES - app.DebugPrintf("Dragon action is now: StrafePlayer\n"); + app.DebugPrintf("Dragon action is now: StrafePlayer\n"); #endif - strafeAttackTarget(); - } - } + strafeAttackTarget(); + } + } } -void EnderDragon::strafeAttackTarget() -{ - app.DebugPrintf("Setting path to strafe attack target\n"); - int currentNodeIndex = findClosestNode(); - int targetNodeIndex = findClosestNode(attackTarget->x,attackTarget->y,attackTarget->z); +void EnderDragon::strafeAttackTarget() { + app.DebugPrintf("Setting path to strafe attack target\n"); + int currentNodeIndex = findClosestNode(); + int targetNodeIndex = + findClosestNode(attackTarget->x, attackTarget->y, attackTarget->z); - int finalXTarget = attackTarget->x; - int finalZTarget = attackTarget->z; + int finalXTarget = attackTarget->x; + int finalZTarget = attackTarget->z; - double xd = finalXTarget - x; - double zd = finalZTarget - z; - double sd = sqrt(xd * xd + zd * zd); - double ho = 0.4f + sd / 80.0f - 1; - if (ho > 10) ho = 10; - int finalYTarget = attackTarget->bb->y0 + ho; + double xd = finalXTarget - x; + double zd = finalZTarget - z; + double sd = sqrt(xd * xd + zd * zd); + double ho = 0.4f + sd / 80.0f - 1; + if (ho > 10) ho = 10; + int finalYTarget = attackTarget->bb->y0 + ho; - Node finalNode(finalXTarget, finalYTarget, finalZTarget); + Node finalNode(finalXTarget, finalYTarget, finalZTarget); - if(m_currentPath != NULL) delete m_currentPath; - m_currentPath = findPath(currentNodeIndex,targetNodeIndex, &finalNode); + if (m_currentPath != NULL) delete m_currentPath; + m_currentPath = findPath(currentNodeIndex, targetNodeIndex, &finalNode); - if(m_currentPath != NULL) - { - // Always skip the first node (as that's where we are already) - m_currentPath->next(); + if (m_currentPath != NULL) { + // Always skip the first node (as that's where we are already) + m_currentPath->next(); - navigateToNextPathNode(); - } + navigateToNextPathNode(); + } } -void EnderDragon::navigateToNextPathNode() -{ - if(m_currentPath != NULL && !m_currentPath->isDone()) - { - Vec3 *curr = m_currentPath->currentPos(); +void EnderDragon::navigateToNextPathNode() { + if (m_currentPath != NULL && !m_currentPath->isDone()) { + Vec3* curr = m_currentPath->currentPos(); - m_currentPath->next(); - xTarget = curr->x; + m_currentPath->next(); + xTarget = curr->x; - if(getSynchedAction() == e_EnderdragonAction_LandingApproach && m_currentPath->isDone()) - { - // When heading to the last node on the landing approach, we want the yCoord to be exact - yTarget = curr->y; - } - else - { - do - { - yTarget = curr->y + random->nextFloat() * 20; - } while( yTarget < (curr->y) ); - } - zTarget = curr->z; - app.DebugPrintf("Path node pos is (%f,%f,%f)\n",curr->x,curr->y,curr->z); - app.DebugPrintf("Setting new target to (%f,%f,%f)\n",xTarget, yTarget, zTarget); - } + if (getSynchedAction() == e_EnderdragonAction_LandingApproach && + m_currentPath->isDone()) { + // When heading to the last node on the landing approach, we want + // the yCoord to be exact + yTarget = curr->y; + } else { + do { + yTarget = curr->y + random->nextFloat() * 20; + } while (yTarget < (curr->y)); + } + zTarget = curr->z; + app.DebugPrintf("Path node pos is (%f,%f,%f)\n", curr->x, curr->y, + curr->z); + app.DebugPrintf("Setting new target to (%f,%f,%f)\n", xTarget, yTarget, + zTarget); + } } -int EnderDragon::findClosestNode() -{ - // Setup all the nodes on the first time this is called - if(m_nodes->data[0] == NULL) - { - // Path nodes for navigation - // 0 - 11 are the outer ring at 60 blocks from centre - // 12 - 19 are the middle ring at 40 blocks from centre - // 20 - 23 are the inner ring at 20 blocks from centre - int nodeX=0; - int nodeY=0; - int nodeZ=0; - int multiplier = 0; - for(unsigned int i = 0; i < 24; ++i) - { - int yAdjustment = 5; - multiplier = i; - if(i < 12) - { - nodeX=60 * Mth::cos(2*(-PI+(PI/12)*multiplier)); - nodeZ=60 * Mth::sin(2*(-PI+(PI/12)*multiplier)); - } - else if(i < 20) - { - multiplier -= 12; - nodeX=40 * Mth::cos(2*(-PI+(PI/8)*multiplier)); - nodeZ=40 * Mth::sin(2*(-PI+(PI/8)*multiplier)); - yAdjustment += 10; // Make the target well above the top of the towers - } - else - { - multiplier -= 20; - nodeX=20 * Mth::cos(2*(-PI+(PI/4)*multiplier)); - nodeZ=20 * Mth::sin(2*(-PI+(PI/4)*multiplier)); - } - // Fix for #77202 - TU9: Content: Gameplay: The Ender Dragon sometimes flies through terrain - // Add minimum height - nodeY = std::max( (level->seaLevel + 10), level->getTopSolidBlock(nodeX, nodeZ) + yAdjustment ); +int EnderDragon::findClosestNode() { + // Setup all the nodes on the first time this is called + if (m_nodes->data[0] == NULL) { + // Path nodes for navigation + // 0 - 11 are the outer ring at 60 blocks from centre + // 12 - 19 are the middle ring at 40 blocks from centre + // 20 - 23 are the inner ring at 20 blocks from centre + int nodeX = 0; + int nodeY = 0; + int nodeZ = 0; + int multiplier = 0; + for (unsigned int i = 0; i < 24; ++i) { + int yAdjustment = 5; + multiplier = i; + if (i < 12) { + nodeX = 60 * Mth::cos(2 * (-PI + (PI / 12) * multiplier)); + nodeZ = 60 * Mth::sin(2 * (-PI + (PI / 12) * multiplier)); + } else if (i < 20) { + multiplier -= 12; + nodeX = 40 * Mth::cos(2 * (-PI + (PI / 8) * multiplier)); + nodeZ = 40 * Mth::sin(2 * (-PI + (PI / 8) * multiplier)); + yAdjustment += + 10; // Make the target well above the top of the towers + } else { + multiplier -= 20; + nodeX = 20 * Mth::cos(2 * (-PI + (PI / 4) * multiplier)); + nodeZ = 20 * Mth::sin(2 * (-PI + (PI / 4) * multiplier)); + } + // Fix for #77202 - TU9: Content: Gameplay: The Ender Dragon + // sometimes flies through terrain Add minimum height + nodeY = + std::max((level->seaLevel + 10), + level->getTopSolidBlock(nodeX, nodeZ) + yAdjustment); - app.DebugPrintf("Node %d is at (%d,%d,%d)\n", i, nodeX, nodeY, nodeZ); + app.DebugPrintf("Node %d is at (%d,%d,%d)\n", i, nodeX, nodeY, + nodeZ); - m_nodes->data[i] = new Node(nodeX,nodeY,nodeZ); + m_nodes->data[i] = new Node(nodeX, nodeY, nodeZ); - //level->setTile(nodeX,nodeY,nodeZ,Tile::obsidian_Id); - } + // level->setTile(nodeX,nodeY,nodeZ,Tile::obsidian_Id); + } - m_nodeAdjacency[0] = (1<<11) | (1<<1) | (1<<12); - m_nodeAdjacency[1] = (1<<0) | (1<<2) | (1<<13); - m_nodeAdjacency[2] = (1<<1) | (1<<3) | (1<<13); - m_nodeAdjacency[3] = (1<<2) | (1<<4) | (1<<14); - m_nodeAdjacency[4] = (1<<3) | (1<<5) | (1<<15); - m_nodeAdjacency[5] = (1<<4) | (1<<6) | (1<<15); - m_nodeAdjacency[6] = (1<<5) | (1<<7) | (1<<16); - m_nodeAdjacency[7] = (1<<6) | (1<<8) | (1<<17); - m_nodeAdjacency[8] = (1<<7) | (1<<9) | (1<<17); - m_nodeAdjacency[9] = (1<<8) | (1<<10) | (1<<18); - m_nodeAdjacency[10] = (1<<9) | (1<<11) | (1<<19); - m_nodeAdjacency[11] = (1<<10) | (1<<0) | (1<<19); + m_nodeAdjacency[0] = (1 << 11) | (1 << 1) | (1 << 12); + m_nodeAdjacency[1] = (1 << 0) | (1 << 2) | (1 << 13); + m_nodeAdjacency[2] = (1 << 1) | (1 << 3) | (1 << 13); + m_nodeAdjacency[3] = (1 << 2) | (1 << 4) | (1 << 14); + m_nodeAdjacency[4] = (1 << 3) | (1 << 5) | (1 << 15); + m_nodeAdjacency[5] = (1 << 4) | (1 << 6) | (1 << 15); + m_nodeAdjacency[6] = (1 << 5) | (1 << 7) | (1 << 16); + m_nodeAdjacency[7] = (1 << 6) | (1 << 8) | (1 << 17); + m_nodeAdjacency[8] = (1 << 7) | (1 << 9) | (1 << 17); + m_nodeAdjacency[9] = (1 << 8) | (1 << 10) | (1 << 18); + m_nodeAdjacency[10] = (1 << 9) | (1 << 11) | (1 << 19); + m_nodeAdjacency[11] = (1 << 10) | (1 << 0) | (1 << 19); - m_nodeAdjacency[12] = (1<<0) | (1<<13) | (1<<20) | (1<<19); - m_nodeAdjacency[13] = (1<<1) | (1<<2) | (1<<14) | (1<<21) | (1<<20) | (1<<12); - m_nodeAdjacency[14] = (1<<3) | (1<<15) | (1<<21) | (1<<13); - m_nodeAdjacency[15] = (1<<4) | (1<<5) | (1<<16) | (1<<22) | (1<<21) | (1<<14); - m_nodeAdjacency[16] = (1<<6) | (1<<17) | (1<<22) | (1<<15); - m_nodeAdjacency[17] = (1<<7) | (1<<8) | (1<<18) | (1<<23) | (1<<22) | (1<<16); - m_nodeAdjacency[18] = (1<<9) | (1<<19) | (1<<23) | (1<<17); - m_nodeAdjacency[19] = (1<<10) | (1<<11) | (1<<12) | (1<<20) | (1<<23) | (1<<18); + m_nodeAdjacency[12] = (1 << 0) | (1 << 13) | (1 << 20) | (1 << 19); + m_nodeAdjacency[13] = + (1 << 1) | (1 << 2) | (1 << 14) | (1 << 21) | (1 << 20) | (1 << 12); + m_nodeAdjacency[14] = (1 << 3) | (1 << 15) | (1 << 21) | (1 << 13); + m_nodeAdjacency[15] = + (1 << 4) | (1 << 5) | (1 << 16) | (1 << 22) | (1 << 21) | (1 << 14); + m_nodeAdjacency[16] = (1 << 6) | (1 << 17) | (1 << 22) | (1 << 15); + m_nodeAdjacency[17] = + (1 << 7) | (1 << 8) | (1 << 18) | (1 << 23) | (1 << 22) | (1 << 16); + m_nodeAdjacency[18] = (1 << 9) | (1 << 19) | (1 << 23) | (1 << 17); + m_nodeAdjacency[19] = (1 << 10) | (1 << 11) | (1 << 12) | (1 << 20) | + (1 << 23) | (1 << 18); - m_nodeAdjacency[20] = (1<<12) | (1<<13) | (1<<21) | (1<<22) | (1<<23) | (1<<19); - m_nodeAdjacency[21] = (1<<14) | (1<<15) | (1<<22) | (1<<23) | (1<<20) | (1<<13); - m_nodeAdjacency[22] = (1<<15) | (1<<16) | (1<<17) | (1<<23) | (1<<20) | (1<<21); - m_nodeAdjacency[23] = (1<<17) | (1<<18) | (1<<19) | (1<<20) | (1<<21) | (1<<22); - } + m_nodeAdjacency[20] = (1 << 12) | (1 << 13) | (1 << 21) | (1 << 22) | + (1 << 23) | (1 << 19); + m_nodeAdjacency[21] = (1 << 14) | (1 << 15) | (1 << 22) | (1 << 23) | + (1 << 20) | (1 << 13); + m_nodeAdjacency[22] = (1 << 15) | (1 << 16) | (1 << 17) | (1 << 23) | + (1 << 20) | (1 << 21); + m_nodeAdjacency[23] = (1 << 17) | (1 << 18) | (1 << 19) | (1 << 20) | + (1 << 21) | (1 << 22); + } - return findClosestNode(x,y,z); + return findClosestNode(x, y, z); } -int EnderDragon::findClosestNode(double tX, double tY, double tZ) -{ - float closestDist = 100.0f; - int closestIndex = 0; - Node *currentPos = new Node((int) floor(tX), (int) floor(tY), (int) floor(tZ)); - int startIndex = 0; - if(m_remainingCrystalsCount <= 0) - { - // If not crystals are left then we try and stay in the middle ring and avoid the outer ring - startIndex = 12; - } - for(unsigned int i = startIndex; i < 24; ++i) - { - if( m_nodes->data[i] != NULL ) - { - float dist = m_nodes->data[i]->distanceTo(currentPos); - if(dist < closestDist) - { - closestDist = dist; - closestIndex = i; - } - } - } - delete currentPos; - return closestIndex; +int EnderDragon::findClosestNode(double tX, double tY, double tZ) { + float closestDist = 100.0f; + int closestIndex = 0; + Node* currentPos = new Node((int)floor(tX), (int)floor(tY), (int)floor(tZ)); + int startIndex = 0; + if (m_remainingCrystalsCount <= 0) { + // If not crystals are left then we try and stay in the middle ring and + // avoid the outer ring + startIndex = 12; + } + for (unsigned int i = startIndex; i < 24; ++i) { + if (m_nodes->data[i] != NULL) { + float dist = m_nodes->data[i]->distanceTo(currentPos); + if (dist < closestDist) { + closestDist = dist; + closestIndex = i; + } + } + } + delete currentPos; + return closestIndex; } // 4J Stu - A* taken from PathFinder and modified -Path *EnderDragon::findPath(int startIndex, int endIndex, Node *finalNode /* = NULL */) -{ - for(unsigned int i = 0; i < 24; ++i) - { - Node *n = m_nodes->data[i]; - n->closed = false; - n->f = 0; - n->g = 0; - n->h = 0; - n->cameFrom = NULL; - n->heapIdx = -1; - } +Path* EnderDragon::findPath(int startIndex, int endIndex, + Node* finalNode /* = NULL */) { + for (unsigned int i = 0; i < 24; ++i) { + Node* n = m_nodes->data[i]; + n->closed = false; + n->f = 0; + n->g = 0; + n->h = 0; + n->cameFrom = NULL; + n->heapIdx = -1; + } - Node *from = m_nodes->data[startIndex]; - Node *to = m_nodes->data[endIndex]; + Node* from = m_nodes->data[startIndex]; + Node* to = m_nodes->data[endIndex]; from->g = 0; from->h = from->distanceTo(to); @@ -1679,91 +1604,77 @@ Path *EnderDragon::findPath(int startIndex, int endIndex, Node *finalNode /* = N openSet->clear(); openSet->insert(from); - Node *closest = from; + Node* closest = from; - int minimumNodeIndex = 0; - if(m_remainingCrystalsCount <= 0) - { - // If not crystals are left then we try and stay in the middle ring and avoid the outer ring - minimumNodeIndex = 12; - } + int minimumNodeIndex = 0; + if (m_remainingCrystalsCount <= 0) { + // If not crystals are left then we try and stay in the middle ring and + // avoid the outer ring + minimumNodeIndex = 12; + } - while (!openSet->isEmpty()) - { - Node *x = openSet->pop(); + while (!openSet->isEmpty()) { + Node* x = openSet->pop(); - if (x->equals(to)) - { - app.DebugPrintf("Found path from %d to %d\n", startIndex, endIndex); - if(finalNode != NULL) - { - finalNode->cameFrom = to; - to = finalNode; - } + if (x->equals(to)) { + app.DebugPrintf("Found path from %d to %d\n", startIndex, endIndex); + if (finalNode != NULL) { + finalNode->cameFrom = to; + to = finalNode; + } return reconstruct_path(from, to); } - if (x->distanceTo(to) < closest->distanceTo(to)) - { + if (x->distanceTo(to) < closest->distanceTo(to)) { closest = x; } x->closed = true; - unsigned int xIndex = 0; - for(unsigned int i = 0; i < 24; ++i) - { - if(m_nodes->data[i] == x) - { - xIndex = i; - break; - } - } + unsigned int xIndex = 0; + for (unsigned int i = 0; i < 24; ++i) { + if (m_nodes->data[i] == x) { + xIndex = i; + break; + } + } - for (int i = minimumNodeIndex; i < 24; i++) - { - if(m_nodeAdjacency[xIndex] & (1<data[i]; + for (int i = minimumNodeIndex; i < 24; i++) { + if (m_nodeAdjacency[xIndex] & (1 << i)) { + Node* y = m_nodes->data[i]; - if(y->closed) continue; + if (y->closed) continue; - float tentative_g_score = x->g + x->distanceTo(y); - if (!y->inOpenSet() || tentative_g_score < y->g) - { - y->cameFrom = x; - y->g = tentative_g_score; - y->h = y->distanceTo(to); - if (y->inOpenSet()) - { - openSet->changeCost(y, y->g + y->h); - } - else - { - y->f = y->g + y->h; - openSet->insert(y); - } - } - } + float tentative_g_score = x->g + x->distanceTo(y); + if (!y->inOpenSet() || tentative_g_score < y->g) { + y->cameFrom = x; + y->g = tentative_g_score; + y->h = y->distanceTo(to); + if (y->inOpenSet()) { + openSet->changeCost(y, y->g + y->h); + } else { + y->f = y->g + y->h; + openSet->insert(y); + } + } + } } } if (closest == from) return NULL; - app.DebugPrintf("Failed to find path from %d to %d\n", startIndex, endIndex); - if(finalNode != NULL) - { - finalNode->cameFrom = closest; - closest = finalNode; - } + app.DebugPrintf("Failed to find path from %d to %d\n", startIndex, + endIndex); + if (finalNode != NULL) { + finalNode->cameFrom = closest; + closest = finalNode; + } return reconstruct_path(from, closest); } // function reconstruct_path(came_from,current_node) -Path *EnderDragon::reconstruct_path(Node *from, Node *to) -{ +Path* EnderDragon::reconstruct_path(Node* from, Node* to) { int count = 1; - Node *n = to; - while (n->cameFrom != NULL) - { + Node* n = to; + while (n->cameFrom != NULL) { count++; n = n->cameFrom; } @@ -1771,191 +1682,177 @@ Path *EnderDragon::reconstruct_path(Node *from, Node *to) NodeArray nodes = NodeArray(count); n = to; nodes.data[--count] = n; - while (n->cameFrom != NULL) - { + while (n->cameFrom != NULL) { n = n->cameFrom; nodes.data[--count] = n; } - Path *ret = new Path(nodes); - delete [] nodes.data; + Path* ret = new Path(nodes); + delete[] nodes.data; return ret; } -void EnderDragon::addAdditonalSaveData(CompoundTag *entityTag) -{ - app.DebugPrintf("Adding EnderDragon additional save data\n"); - entityTag->putShort(L"RemainingCrystals", m_remainingCrystalsCount); - entityTag->putInt(L"DragonState", (int)getSynchedAction() ); +void EnderDragon::addAdditonalSaveData(CompoundTag* entityTag) { + app.DebugPrintf("Adding EnderDragon additional save data\n"); + entityTag->putShort(L"RemainingCrystals", m_remainingCrystalsCount); + entityTag->putInt(L"DragonState", (int)getSynchedAction()); - BossMob::addAdditonalSaveData(entityTag); + BossMob::addAdditonalSaveData(entityTag); } -void EnderDragon::readAdditionalSaveData(CompoundTag *tag) -{ - app.DebugPrintf("Reading EnderDragon additional save data\n"); - m_remainingCrystalsCount = tag->getShort(L"RemainingCrystals"); - if(!tag->contains(L"RemainingCrystals")) m_remainingCrystalsCount = CRYSTAL_COUNT; +void EnderDragon::readAdditionalSaveData(CompoundTag* tag) { + app.DebugPrintf("Reading EnderDragon additional save data\n"); + m_remainingCrystalsCount = tag->getShort(L"RemainingCrystals"); + if (!tag->contains(L"RemainingCrystals")) + m_remainingCrystalsCount = CRYSTAL_COUNT; - if(tag->contains(L"DragonState")) setSynchedAction( (EEnderdragonAction)tag->getInt(L"DragonState"), true); + if (tag->contains(L"DragonState")) + setSynchedAction((EEnderdragonAction)tag->getInt(L"DragonState"), true); - BossMob::readAdditionalSaveData(tag); + BossMob::readAdditionalSaveData(tag); } -float EnderDragon::getTilt(float a) -{ - float tilt = 0.0f; - //if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - //{ - // tilt = -25.0f; - // xRot = -25.0f; - //} - //else - { - double latencyPosAcomponents[3],latencyPosBcomponents[3]; - doubleArray latencyPosA = doubleArray(latencyPosAcomponents,3); - doubleArray latencyPosB = doubleArray(latencyPosBcomponents,3); - getLatencyPos(latencyPosA, 5, a); - getLatencyPos(latencyPosB, 10, a); +float EnderDragon::getTilt(float a) { + float tilt = 0.0f; + // if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) + //{ + // tilt = -25.0f; + // xRot = -25.0f; + // } + // else + { + double latencyPosAcomponents[3], latencyPosBcomponents[3]; + doubleArray latencyPosA = doubleArray(latencyPosAcomponents, 3); + doubleArray latencyPosB = doubleArray(latencyPosBcomponents, 3); + getLatencyPos(latencyPosA, 5, a); + getLatencyPos(latencyPosB, 10, a); - tilt = (latencyPosA[1] - latencyPosB[1]) * 10; - } - //app.DebugPrintf("Tilt is %f\n", tilt); + tilt = (latencyPosA[1] - latencyPosB[1]) * 10; + } + // app.DebugPrintf("Tilt is %f\n", tilt); - return tilt; + return tilt; } -double EnderDragon::getHeadYOffset(float a) -{ - double headYOffset = 0.0; - if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - { - headYOffset = -1.0; - } - else - { - double p1components[3]; - doubleArray p1 = doubleArray(p1components, 3); - getLatencyPos(p1, 5, 1); +double EnderDragon::getHeadYOffset(float a) { + double headYOffset = 0.0; + if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) { + headYOffset = -1.0; + } else { + double p1components[3]; + doubleArray p1 = doubleArray(p1components, 3); + getLatencyPos(p1, 5, 1); - double p0components[3]; - doubleArray p0 = doubleArray(p0components, 3); - getLatencyPos(p0, 0, 1); + double p0components[3]; + doubleArray p0 = doubleArray(p0components, 3); + getLatencyPos(p0, 0, 1); - headYOffset = (p0[1] - p1[1]) * 1; - } - //app.DebugPrintf("headYOffset is %f\n", headYOffset); - return headYOffset; + headYOffset = (p0[1] - p1[1]) * 1; + } + // app.DebugPrintf("headYOffset is %f\n", headYOffset); + return headYOffset; } -double EnderDragon::getHeadYRotDiff(float a) -{ - double result = 0.0; - //if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - //{ - // result = m_headYRot; - //} - return result; +double EnderDragon::getHeadYRotDiff(float a) { + double result = 0.0; + // if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) + //{ + // result = m_headYRot; + // } + return result; } -double EnderDragon::getHeadPartYOffset(int partIndex, doubleArray bodyPos, doubleArray partPos) -{ - double result = 0.0; - if( getSynchedAction() == e_EnderdragonAction_Landing || getSynchedAction() == e_EnderdragonAction_Takeoff ) - { - int eggHeight = level->getTopSolidBlock(PODIUM_X_POS,PODIUM_Z_POS); //level->getHeightmap(4,4); - float dist = sqrt( distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS) )/4; - if( dist < 1.0f ) dist = 1.0f; - result = partIndex / dist; - //app.DebugPrintf("getHeadPartYOffset - dist = %f, result = %f (%d)\n", dist, result, partIndex); - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - { - result = partIndex; - } - else - { - if(partIndex == 6) - { - result = 0.0; - } - else - { - result = partPos[1] - bodyPos[1]; - } - } - //app.DebugPrintf("Part %d is at %f\n", partIndex, result); - return result; +double EnderDragon::getHeadPartYOffset(int partIndex, doubleArray bodyPos, + doubleArray partPos) { + double result = 0.0; + if (getSynchedAction() == e_EnderdragonAction_Landing || + getSynchedAction() == e_EnderdragonAction_Takeoff) { + int eggHeight = level->getTopSolidBlock( + PODIUM_X_POS, PODIUM_Z_POS); // level->getHeightmap(4,4); + float dist = + sqrt(distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS)) / 4; + if (dist < 1.0f) dist = 1.0f; + result = partIndex / dist; + // app.DebugPrintf("getHeadPartYOffset - dist = %f, result = %f (%d)\n", + // dist, result, partIndex); + } else if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) { + result = partIndex; + } else { + if (partIndex == 6) { + result = 0.0; + } else { + result = partPos[1] - bodyPos[1]; + } + } + // app.DebugPrintf("Part %d is at %f\n", partIndex, result); + return result; } -double EnderDragon::getHeadPartYRotDiff(int partIndex, doubleArray bodyPos, doubleArray partPos) -{ - double result = 0.0; - //if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - //{ - // result = m_headYRot / (7 - partIndex); - //} - //else - { - result = partPos[0] - bodyPos[0]; - } - //app.DebugPrintf("Part %d is at %f\n", partIndex, result); - return result; +double EnderDragon::getHeadPartYRotDiff(int partIndex, doubleArray bodyPos, + doubleArray partPos) { + double result = 0.0; + // if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + // getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + // getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) + //{ + // result = m_headYRot / (7 - partIndex); + // } + // else + { + result = partPos[0] - bodyPos[0]; + } + // app.DebugPrintf("Part %d is at %f\n", partIndex, result); + return result; } -Vec3 *EnderDragon::getHeadLookVector(float a) -{ - Vec3 *result = NULL; - - if( getSynchedAction() == e_EnderdragonAction_Landing || getSynchedAction() == e_EnderdragonAction_Takeoff ) - { - int eggHeight = level->getTopSolidBlock(PODIUM_X_POS,PODIUM_Z_POS); //level->getHeightmap(4,4); - float dist = sqrt(distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS))/4; - if( dist < 1.0f ) dist = 1.0f; - // The 6.0f is dragon->getHeadPartYOffset(6, start, p) - float yOffset = 6.0f / dist; - - double xRotTemp = xRot; - double rotScale = 1.5f; - xRot = -yOffset * rotScale * 5.0f; +Vec3* EnderDragon::getHeadLookVector(float a) { + Vec3* result = NULL; - double yRotTemp = yRot; - yRot += getHeadYRotDiff(a); + if (getSynchedAction() == e_EnderdragonAction_Landing || + getSynchedAction() == e_EnderdragonAction_Takeoff) { + int eggHeight = level->getTopSolidBlock( + PODIUM_X_POS, PODIUM_Z_POS); // level->getHeightmap(4,4); + float dist = + sqrt(distanceToSqr(PODIUM_X_POS, eggHeight, PODIUM_Z_POS)) / 4; + if (dist < 1.0f) dist = 1.0f; + // The 6.0f is dragon->getHeadPartYOffset(6, start, p) + float yOffset = 6.0f / dist; - result = getViewVector(a); + double xRotTemp = xRot; + double rotScale = 1.5f; + xRot = -yOffset * rotScale * 5.0f; - xRot = xRotTemp; - yRot = yRotTemp; - } - else if( getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || - getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || - getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) - { - double xRotTemp = xRot; - double rotScale = 1.5f; - // The 6.0f is dragon->getHeadPartYOffset(6, start, p) - xRot = -6.0f * rotScale * 5.0f; + double yRotTemp = yRot; + yRot += getHeadYRotDiff(a); - double yRotTemp = yRot; - yRot += getHeadYRotDiff(a); + result = getViewVector(a); - result = getViewVector(a); + xRot = xRotTemp; + yRot = yRotTemp; + } else if (getSynchedAction() == e_EnderdragonAction_Sitting_Flaming || + getSynchedAction() == e_EnderdragonAction_Sitting_Scanning || + getSynchedAction() == e_EnderdragonAction_Sitting_Attacking) { + double xRotTemp = xRot; + double rotScale = 1.5f; + // The 6.0f is dragon->getHeadPartYOffset(6, start, p) + xRot = -6.0f * rotScale * 5.0f; - xRot = xRotTemp; - yRot = yRotTemp; - } - else - { - result = getViewVector(a); - } - return result; + double yRotTemp = yRot; + yRot += getHeadYRotDiff(a); + + result = getViewVector(a); + + xRot = xRotTemp; + yRot = yRotTemp; + } else { + result = getViewVector(a); + } + return result; } diff --git a/Minecraft.World/Entities/Mobs/EnderDragon.h b/Minecraft.World/Entities/Mobs/EnderDragon.h index 6de06ff2a..1d9a0516e 100644 --- a/Minecraft.World/Entities/Mobs/EnderDragon.h +++ b/Minecraft.World/Entities/Mobs/EnderDragon.h @@ -8,170 +8,175 @@ class Node; class BinaryHeap; class Path; -class EnderDragon : public BossMob -{ +class EnderDragon : public BossMob { public: - eINSTANCEOF GetType() { return eTYPE_ENDERDRAGON; }; - static Entity *create(Level *level) { return new EnderDragon(level); } + eINSTANCEOF GetType() { return eTYPE_ENDERDRAGON; }; + static Entity* create(Level* level) { return new EnderDragon(level); } private: - static const int DATA_ID_SYNCHED_HEALTH = 16; - - // 4J Added for new behaviours - static const int DATA_ID_SYNCHED_ACTION = 17; + static const int DATA_ID_SYNCHED_HEALTH = 16; - static const int positionsLength = 64; // 4J Stu - Defined this so that we can keep the positions array as a basic type array + // 4J Added for new behaviours + static const int DATA_ID_SYNCHED_ACTION = 17; + + static const int positionsLength = + 64; // 4J Stu - Defined this so that we can keep the positions array as + // a basic type array public: - double xTarget, yTarget, zTarget; + double xTarget, yTarget, zTarget; - double positions[positionsLength][3]; - int posPointer; + double positions[positionsLength][3]; + int posPointer; - //BossMobPart[] subEntities; - std::vector > subEntities; - std::shared_ptr head; - std::shared_ptr neck; // 4J Added - std::shared_ptr body; - std::shared_ptr tail1; - std::shared_ptr tail2; - std::shared_ptr tail3; - std::shared_ptr wing1; - std::shared_ptr wing2; + // BossMobPart[] subEntities; + std::vector > subEntities; + std::shared_ptr head; + std::shared_ptr neck; // 4J Added + std::shared_ptr body; + std::shared_ptr tail1; + std::shared_ptr tail2; + std::shared_ptr tail3; + std::shared_ptr wing1; + std::shared_ptr wing2; - float oFlapTime; - float flapTime; - bool newTarget; - bool inWall; + float oFlapTime; + float flapTime; + bool newTarget; + bool inWall; - // 4J Stu - Added for new dragon behaviour + // 4J Stu - Added for new dragon behaviour private: - int m_fireballCharge; - float m_holdingPatternAngle; - bool m_holdingPatternClockwise; - int m_actionTicks; - int m_sittingDamageReceived; - int m_remainingCrystalsCount; - int m_flameAttacks; + int m_fireballCharge; + float m_holdingPatternAngle; + bool m_holdingPatternClockwise; + int m_actionTicks; + int m_sittingDamageReceived; + int m_remainingCrystalsCount; + int m_flameAttacks; - int m_iGrowlTimer; + int m_iGrowlTimer; - double m_headYRot; - AABB *m_acidArea; + double m_headYRot; + AABB* m_acidArea; - NodeArray *m_nodes; - int m_nodeAdjacency[24]; - BinaryHeap *openSet; - Path *m_currentPath; + NodeArray* m_nodes; + int m_nodeAdjacency[24]; + BinaryHeap* openSet; + Path* m_currentPath; - enum EEnderdragonAction - { - e_EnderdragonAction_HoldingPattern, - e_EnderdragonAction_StrafePlayer, - e_EnderdragonAction_LandingApproach, - e_EnderdragonAction_Landing, - e_EnderdragonAction_Takeoff, - e_EnderdragonAction_Sitting_Flaming, - e_EnderdragonAction_Sitting_Scanning, - e_EnderdragonAction_Sitting_Attacking, - }; + enum EEnderdragonAction { + e_EnderdragonAction_HoldingPattern, + e_EnderdragonAction_StrafePlayer, + e_EnderdragonAction_LandingApproach, + e_EnderdragonAction_Landing, + e_EnderdragonAction_Takeoff, + e_EnderdragonAction_Sitting_Flaming, + e_EnderdragonAction_Sitting_Scanning, + e_EnderdragonAction_Sitting_Attacking, + }; - static const int CRYSTAL_COUNT; + static const int CRYSTAL_COUNT; - static const int FLAME_TICKS; - static const float FLAME_ANGLE; - static const int FLAME_PASSES; - static const int FLAME_FREQUENCY; - static const int FLAME_RANGE; + static const int FLAME_TICKS; + static const float FLAME_ANGLE; + static const int FLAME_PASSES; + static const int FLAME_FREQUENCY; + static const int FLAME_RANGE; - static const int ATTACK_TICKS; + static const int ATTACK_TICKS; - static const int SITTING_ATTACK_Y_VIEW_RANGE; - static const int SITTING_ATTACK_VIEW_RANGE; - static const int SITTING_ATTACK_RANGE; - static const int SITTING_POST_ATTACK_IDLE_TICKS; - static const int SITTING_SCANNING_IDLE_TICKS; - static const int SITTING_FLAME_ATTACKS_COUNT; + static const int SITTING_ATTACK_Y_VIEW_RANGE; + static const int SITTING_ATTACK_VIEW_RANGE; + static const int SITTING_ATTACK_RANGE; + static const int SITTING_POST_ATTACK_IDLE_TICKS; + static const int SITTING_SCANNING_IDLE_TICKS; + static const int SITTING_FLAME_ATTACKS_COUNT; - // The percentage of max health that the dragon will take while in the "Sitting" states before flying away - static const float SITTING_ALLOWED_DAMAGE_PERCENTAGE; + // The percentage of max health that the dragon will take while in the + // "Sitting" states before flying away + static const float SITTING_ALLOWED_DAMAGE_PERCENTAGE; - static const int PODIUM_X_POS = 0; - static const int PODIUM_Z_POS = 0; + static const int PODIUM_X_POS = 0; + static const int PODIUM_Z_POS = 0; private: - std::shared_ptr attackTarget; + std::shared_ptr attackTarget; public: - int dragonDeathTime; + int dragonDeathTime; public: - std::shared_ptr nearestCrystal; + std::shared_ptr nearestCrystal; private: - void _init(); + void _init(); public: - EnderDragon(Level *level); - virtual ~EnderDragon(); + EnderDragon(Level* level); + virtual ~EnderDragon(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - void getLatencyPos(doubleArray result, int step, float a); - virtual void aiStep(); + void getLatencyPos(doubleArray result, int step, float a); + virtual void aiStep(); private: - using BossMob::hurt; + using BossMob::hurt; - void checkCrystals(); - void checkAttack(); - void knockBack(std::vector > *entities); - void hurt(std::vector > *entities); - void findNewTarget(); - float rotWrap(double d); - bool checkWalls(AABB *bb); + void checkCrystals(); + void checkAttack(); + void knockBack(std::vector >* entities); + void hurt(std::vector >* entities); + void findNewTarget(); + float rotWrap(double d); + bool checkWalls(AABB* bb); public: - virtual bool hurt(std::shared_ptr bossMobPart, DamageSource *source, int damage); + virtual bool hurt(std::shared_ptr bossMobPart, + DamageSource* source, int damage); protected: - virtual void tickDeath(); + virtual void tickDeath(); private: - void spawnExitPortal(int x, int z); + void spawnExitPortal(int x, int z); protected: - virtual void checkDespawn(); - virtual int getHurtSound(); + virtual void checkDespawn(); + virtual int getHurtSound(); + public: - virtual std::vector > *getSubEntities(); - virtual bool isPickable(); - virtual int getSynchedHealth(); + virtual std::vector >* getSubEntities(); + virtual bool isPickable(); + virtual int getSynchedHealth(); private: - // 4J added for new dragon behaviour - bool setSynchedAction(EEnderdragonAction action, bool force = false); - EEnderdragonAction getSynchedAction(); - int findClosestNode(double tX, double tY, double tZ); - int findClosestNode(); - Path *findPath(int startIndex, int endIndex, Node *finalNode = NULL); - Path *reconstruct_path(Node *from, Node *to); + // 4J added for new dragon behaviour + bool setSynchedAction(EEnderdragonAction action, bool force = false); + EEnderdragonAction getSynchedAction(); + int findClosestNode(double tX, double tY, double tZ); + int findClosestNode(); + Path* findPath(int startIndex, int endIndex, Node* finalNode = NULL); + Path* reconstruct_path(Node* from, Node* to); - void strafeAttackTarget(); - void navigateToNextPathNode(); + void strafeAttackTarget(); + void navigateToNextPathNode(); -public: - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); - public: - void handleCrystalDestroyed(DamageSource *source); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); - float getTilt(float a); - double getHeadYOffset(float a); - double getHeadYRotDiff(float a); - double getHeadPartYOffset(int partIndex, doubleArray bodyPos, doubleArray partPos); - double getHeadPartYRotDiff(int partIndex, doubleArray bodyPos, doubleArray partPos); - Vec3 *getHeadLookVector(float a); +public: + void handleCrystalDestroyed(DamageSource* source); + + float getTilt(float a); + double getHeadYOffset(float a); + double getHeadYRotDiff(float a); + double getHeadPartYOffset(int partIndex, doubleArray bodyPos, + doubleArray partPos); + double getHeadPartYRotDiff(int partIndex, doubleArray bodyPos, + doubleArray partPos); + Vec3* getHeadLookVector(float a); }; diff --git a/Minecraft.World/Entities/Mobs/EnderMan.cpp b/Minecraft.World/Entities/Mobs/EnderMan.cpp index 32c75a8a9..38480874e 100644 --- a/Minecraft.World/Entities/Mobs/EnderMan.cpp +++ b/Minecraft.World/Entities/Mobs/EnderMan.cpp @@ -10,401 +10,344 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "EnderMan.h" - bool EnderMan::MAY_TAKE[256]; -void EnderMan::staticCtor() -{ - ZeroMemory(MAY_TAKE, sizeof(bool) * 256); - MAY_TAKE[Tile::grass_Id] = true; - MAY_TAKE[Tile::dirt_Id] = true; - MAY_TAKE[Tile::sand_Id] = true; - MAY_TAKE[Tile::gravel_Id] = true; - MAY_TAKE[Tile::flower_Id] = true; - MAY_TAKE[Tile::rose_Id] = true; - MAY_TAKE[Tile::mushroom1_Id] = true; - MAY_TAKE[Tile::mushroom2_Id] = true; - MAY_TAKE[Tile::tnt_Id] = true; - MAY_TAKE[Tile::cactus_Id] = true; - MAY_TAKE[Tile::clay_Id] = true; - MAY_TAKE[Tile::pumpkin_Id] = true; - MAY_TAKE[Tile::melon_Id] = true; - MAY_TAKE[Tile::mycel_Id] = true; +void EnderMan::staticCtor() { + ZeroMemory(MAY_TAKE, sizeof(bool) * 256); + MAY_TAKE[Tile::grass_Id] = true; + MAY_TAKE[Tile::dirt_Id] = true; + MAY_TAKE[Tile::sand_Id] = true; + MAY_TAKE[Tile::gravel_Id] = true; + MAY_TAKE[Tile::flower_Id] = true; + MAY_TAKE[Tile::rose_Id] = true; + MAY_TAKE[Tile::mushroom1_Id] = true; + MAY_TAKE[Tile::mushroom2_Id] = true; + MAY_TAKE[Tile::tnt_Id] = true; + MAY_TAKE[Tile::cactus_Id] = true; + MAY_TAKE[Tile::clay_Id] = true; + MAY_TAKE[Tile::pumpkin_Id] = true; + MAY_TAKE[Tile::melon_Id] = true; + MAY_TAKE[Tile::mycel_Id] = true; } -EnderMan::EnderMan(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - // Brought forward from 1.2.3 - this->defineSynchedData(); +EnderMan::EnderMan(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called Brought forward + // from 1.2.3 + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - // 4J initialisors - teleportTime = 0; - aggroTime = 0; + // 4J initialisors + teleportTime = 0; + aggroTime = 0; - this->textureIdx = TN_MOB_ENDERMAN; // 4J was "/mob/enderman.png"; - runSpeed = 0.2f; - attackDamage = 7; - setSize(0.6f, 2.9f); - footSize = 1; + this->textureIdx = TN_MOB_ENDERMAN; // 4J was "/mob/enderman.png"; + runSpeed = 0.2f; + attackDamage = 7; + setSize(0.6f, 2.9f); + footSize = 1; } -int EnderMan::getMaxHealth() -{ - return 40; -} +int EnderMan::getMaxHealth() { return 40; } // Brought forward from 1.2.3 -void EnderMan::defineSynchedData() -{ - Monster::defineSynchedData(); +void EnderMan::defineSynchedData() { + Monster::defineSynchedData(); - entityData->define(DATA_CARRY_ITEM_ID, (uint8_t) 0); - entityData->define(DATA_CARRY_ITEM_DATA, (uint8_t) 0); - entityData->define(DATA_CREEPY, (uint8_t) 0); + entityData->define(DATA_CARRY_ITEM_ID, (uint8_t)0); + entityData->define(DATA_CARRY_ITEM_DATA, (uint8_t)0); + entityData->define(DATA_CREEPY, (uint8_t)0); } -void EnderMan::addAdditonalSaveData(CompoundTag *tag) -{ - Monster::addAdditonalSaveData(tag); - tag->putShort(L"carried", (short) getCarryingTile()); - tag->putShort(L"carriedData", (short) getCarryingData()); +void EnderMan::addAdditonalSaveData(CompoundTag* tag) { + Monster::addAdditonalSaveData(tag); + tag->putShort(L"carried", (short)getCarryingTile()); + tag->putShort(L"carriedData", (short)getCarryingData()); } -void EnderMan::readAdditionalSaveData(CompoundTag *tag) -{ - Monster::readAdditionalSaveData(tag); - setCarryingTile(tag->getShort(L"carried")); - setCarryingData(tag->getShort(L"carryingData")); +void EnderMan::readAdditionalSaveData(CompoundTag* tag) { + Monster::readAdditionalSaveData(tag); + setCarryingTile(tag->getShort(L"carried")); + setCarryingData(tag->getShort(L"carryingData")); } -std::shared_ptr EnderMan::findAttackTarget() -{ +std::shared_ptr EnderMan::findAttackTarget() { #ifndef _FINAL_BUILD - if(app.GetMobsDontAttackEnabled()) - { - return std::shared_ptr(); - } + if (app.GetMobsDontAttackEnabled()) { + return std::shared_ptr(); + } #endif - std::shared_ptr player = level->getNearestAttackablePlayer(shared_from_this(), 64); - if (player != NULL) - { - if (isLookingAtMe(player)) - { - if (aggroTime++ == 5) - { - aggroTime = 0; - setCreepy(true); - return player; - } - } - else - { - aggroTime = 0; - } - } - return nullptr; + std::shared_ptr player = + level->getNearestAttackablePlayer(shared_from_this(), 64); + if (player != NULL) { + if (isLookingAtMe(player)) { + if (aggroTime++ == 5) { + aggroTime = 0; + setCreepy(true); + return player; + } + } else { + aggroTime = 0; + } + } + return nullptr; } -bool EnderMan::isLookingAtMe(std::shared_ptr player) -{ - std::shared_ptr helmet = player->inventory->armor[3]; - if (helmet != NULL && helmet->id == Tile::pumpkin_Id) return false; +bool EnderMan::isLookingAtMe(std::shared_ptr player) { + std::shared_ptr helmet = player->inventory->armor[3]; + if (helmet != NULL && helmet->id == Tile::pumpkin_Id) return false; - Vec3 *look = player->getViewVector(1)->normalize(); - Vec3 *dir = Vec3::newTemp(x - player->x, (bb->y0 + bbHeight / 2) - (player->y + player->getHeadHeight()), z - player->z); - double dist = dir->length(); - dir = dir->normalize(); - double dot = look->dot(dir); - if (dot > 1 - 0.025 / dist) - { - return player->canSee(shared_from_this()); - } - return false; + Vec3* look = player->getViewVector(1)->normalize(); + Vec3* dir = Vec3::newTemp( + x - player->x, + (bb->y0 + bbHeight / 2) - (player->y + player->getHeadHeight()), + z - player->z); + double dist = dir->length(); + dir = dir->normalize(); + double dot = look->dot(dir); + if (dot > 1 - 0.025 / dist) { + return player->canSee(shared_from_this()); + } + return false; } -void EnderMan::aiStep() -{ - if (this->isInWaterOrRain()) hurt(DamageSource::drown, 1); +void EnderMan::aiStep() { + if (this->isInWaterOrRain()) hurt(DamageSource::drown, 1); - runSpeed = attackTarget != NULL ? 6.5f : 0.3f; + runSpeed = attackTarget != NULL ? 6.5f : 0.3f; - if (!level->isClientSide) - { - if (getCarryingTile() == 0) - { - if (random->nextInt(20) == 0) - { - int xt = Mth::floor(x - 2 + random->nextDouble() * 4); - int yt = Mth::floor(y + random->nextDouble() * 3); - int zt = Mth::floor(z - 2 + random->nextDouble() * 4); - int t = level->getTile(xt, yt, zt); - //if (t > 0 && Tile::tiles[t]->isCubeShaped()) - if(EnderMan::MAY_TAKE[t]) // 4J - Brought forward from 1.2.3 - { - setCarryingTile(level->getTile(xt, yt, zt)); - setCarryingData(level->getData(xt, yt, zt)); - level->setTile(xt, yt, zt, 0); - } - } - } - else - { - if (random->nextInt(2000) == 0) - { - int xt = Mth::floor(x - 1 + random->nextDouble() * 2); - int yt = Mth::floor(y + random->nextDouble() * 2); - int zt = Mth::floor(z - 1 + random->nextDouble() * 2); - int t = level->getTile(xt, yt, zt); - int bt = level->getTile(xt, yt - 1, zt); - if (t == 0 && bt > 0 && Tile::tiles[bt]->isCubeShaped()) - { - level->setTileAndData(xt, yt, zt, getCarryingTile(), getCarryingData()); - setCarryingTile(0); - } - } - } - } + if (!level->isClientSide) { + if (getCarryingTile() == 0) { + if (random->nextInt(20) == 0) { + int xt = Mth::floor(x - 2 + random->nextDouble() * 4); + int yt = Mth::floor(y + random->nextDouble() * 3); + int zt = Mth::floor(z - 2 + random->nextDouble() * 4); + int t = level->getTile(xt, yt, zt); + // if (t > 0 && Tile::tiles[t]->isCubeShaped()) + if (EnderMan::MAY_TAKE[t]) // 4J - Brought forward from 1.2.3 + { + setCarryingTile(level->getTile(xt, yt, zt)); + setCarryingData(level->getData(xt, yt, zt)); + level->setTile(xt, yt, zt, 0); + } + } + } else { + if (random->nextInt(2000) == 0) { + int xt = Mth::floor(x - 1 + random->nextDouble() * 2); + int yt = Mth::floor(y + random->nextDouble() * 2); + int zt = Mth::floor(z - 1 + random->nextDouble() * 2); + int t = level->getTile(xt, yt, zt); + int bt = level->getTile(xt, yt - 1, zt); + if (t == 0 && bt > 0 && Tile::tiles[bt]->isCubeShaped()) { + level->setTileAndData(xt, yt, zt, getCarryingTile(), + getCarryingData()); + setCarryingTile(0); + } + } + } + } - // 4J - Brought forward particles from 1.2.3 - for (int i = 0; i < 2; i++) - { - level->addParticle(eParticleType_ender, x + (random->nextDouble() - 0.5) * bbWidth, y + random->nextDouble() * bbHeight - 0.25f, z + (random->nextDouble() - 0.5) * bbWidth, - (random->nextDouble() - 0.5) * 2, -random->nextDouble(), (random->nextDouble() - 0.5) * 2); - } + // 4J - Brought forward particles from 1.2.3 + for (int i = 0; i < 2; i++) { + level->addParticle( + eParticleType_ender, x + (random->nextDouble() - 0.5) * bbWidth, + y + random->nextDouble() * bbHeight - 0.25f, + z + (random->nextDouble() - 0.5) * bbWidth, + (random->nextDouble() - 0.5) * 2, -random->nextDouble(), + (random->nextDouble() - 0.5) * 2); + } - if (level->isDay() && !level->isClientSide) - { - float br = getBrightness(1); - if (br > 0.5f) - { - if (level->canSeeSky(Mth::floor(x), Mth::floor(y), Mth::floor(z)) && random->nextFloat() * 30 < (br - 0.4f) * 2) - { - // 4J - Brought forward behaviour change from 1.2.3 - //onFire = 20 * 15; - attackTarget = nullptr; - setCreepy(false); - teleport(); - } - } - } - // 4J Brought forward behaviour change from 1.2.3 - if (isInWaterOrRain() || isOnFire()) - { - attackTarget = nullptr; - setCreepy(false); - teleport(); - } - jumping = false; - if (attackTarget != NULL) - { - this->lookAt(attackTarget, 100, 100); - } + if (level->isDay() && !level->isClientSide) { + float br = getBrightness(1); + if (br > 0.5f) { + if (level->canSeeSky(Mth::floor(x), Mth::floor(y), Mth::floor(z)) && + random->nextFloat() * 30 < (br - 0.4f) * 2) { + // 4J - Brought forward behaviour change from 1.2.3 + // onFire = 20 * 15; + attackTarget = nullptr; + setCreepy(false); + teleport(); + } + } + } + // 4J Brought forward behaviour change from 1.2.3 + if (isInWaterOrRain() || isOnFire()) { + attackTarget = nullptr; + setCreepy(false); + teleport(); + } + jumping = false; + if (attackTarget != NULL) { + this->lookAt(attackTarget, 100, 100); + } - if (!level->isClientSide && isAlive()) - { - if (attackTarget != NULL) - { - if ( std::dynamic_pointer_cast(attackTarget) != NULL && isLookingAtMe(std::dynamic_pointer_cast(attackTarget))) - { - xxa = yya = 0; - runSpeed = 0; - if (attackTarget->distanceToSqr(shared_from_this()) < 4 * 4) - { - teleport(); - } - teleportTime = 0; - } - else if (attackTarget->distanceToSqr(shared_from_this()) > 16 * 16) - { - if (teleportTime++ >= 30) - { - if (teleportTowards(attackTarget)) - { - teleportTime = 0; - } - } - } - } - else - { - setCreepy(false); - teleportTime = 0; - } - } + if (!level->isClientSide && isAlive()) { + if (attackTarget != NULL) { + if (std::dynamic_pointer_cast(attackTarget) != NULL && + isLookingAtMe( + std::dynamic_pointer_cast(attackTarget))) { + xxa = yya = 0; + runSpeed = 0; + if (attackTarget->distanceToSqr(shared_from_this()) < 4 * 4) { + teleport(); + } + teleportTime = 0; + } else if (attackTarget->distanceToSqr(shared_from_this()) > + 16 * 16) { + if (teleportTime++ >= 30) { + if (teleportTowards(attackTarget)) { + teleportTime = 0; + } + } + } + } else { + setCreepy(false); + teleportTime = 0; + } + } - Monster::aiStep(); + Monster::aiStep(); } -bool EnderMan::teleport() -{ - double xx = x + (random->nextDouble() - 0.5) * 64; - double yy = y + (random->nextInt(64) - 32); - double zz = z + (random->nextDouble() - 0.5) * 64; - return teleport(xx, yy, zz); +bool EnderMan::teleport() { + double xx = x + (random->nextDouble() - 0.5) * 64; + double yy = y + (random->nextInt(64) - 32); + double zz = z + (random->nextDouble() - 0.5) * 64; + return teleport(xx, yy, zz); } -bool EnderMan::teleportTowards(std::shared_ptr e) -{ - Vec3 *dir = Vec3::newTemp(x - e->x, bb->y0 + bbHeight / 2 - e->y + e->getHeadHeight(), z - e->z); - dir = dir->normalize(); - double d = 16; - double xx = x + (random->nextDouble() - 0.5) * 8 - dir->x * d; - double yy = y + (random->nextInt(16) - 8) - dir->y * d; - double zz = z + (random->nextDouble() - 0.5) * 8 - dir->z * d; - return teleport(xx, yy, zz); +bool EnderMan::teleportTowards(std::shared_ptr e) { + Vec3* dir = Vec3::newTemp( + x - e->x, bb->y0 + bbHeight / 2 - e->y + e->getHeadHeight(), z - e->z); + dir = dir->normalize(); + double d = 16; + double xx = x + (random->nextDouble() - 0.5) * 8 - dir->x * d; + double yy = y + (random->nextInt(16) - 8) - dir->y * d; + double zz = z + (random->nextDouble() - 0.5) * 8 - dir->z * d; + return teleport(xx, yy, zz); } -bool EnderMan::teleport(double xx, double yy, double zz) -{ - double xo = x; - double yo = y; - double zo = z; +bool EnderMan::teleport(double xx, double yy, double zz) { + double xo = x; + double yo = y; + double zo = z; - x = xx; - y = yy; - z = zz; - bool ok = false; - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); + x = xx; + y = yy; + z = zz; + bool ok = false; + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); - if (level->hasChunkAt(xt, yt, zt)) - { - bool landed = false; - while (!landed && yt > 0) - { - int t = level->getTile(xt, yt - 1, zt); - if (t == 0 || !(Tile::tiles[t]->material->blocksMotion())) - { - y--; - yt--; - } - else - { - landed = true; - } - } - if (landed) - { - setPos(x, y, z); - if (level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb)) - { - ok = true; - } - } - } + if (level->hasChunkAt(xt, yt, zt)) { + bool landed = false; + while (!landed && yt > 0) { + int t = level->getTile(xt, yt - 1, zt); + if (t == 0 || !(Tile::tiles[t]->material->blocksMotion())) { + y--; + yt--; + } else { + landed = true; + } + } + if (landed) { + setPos(x, y, z); + if (level->getCubes(shared_from_this(), bb)->empty() && + !level->containsAnyLiquid(bb)) { + ok = true; + } + } + } + if (ok) { + int count = 128; + for (int i = 0; i < count; i++) { + double d = i / (count - 1.0); + float xa = (random->nextFloat() - 0.5f) * 0.2f; + float ya = (random->nextFloat() - 0.5f) * 0.2f; + float za = (random->nextFloat() - 0.5f) * 0.2f; - if (ok) - { - int count = 128; - for (int i = 0; i < count; i++) - { - double d = i / (count - 1.0); - float xa = (random->nextFloat() - 0.5f) * 0.2f; - float ya = (random->nextFloat() - 0.5f) * 0.2f; - float za = (random->nextFloat() - 0.5f) * 0.2f; + double _x = + xo + (x - xo) * d + (random->nextDouble() - 0.5) * bbWidth * 2; + double _y = yo + (y - yo) * d + random->nextDouble() * bbHeight; + double _z = + zo + (z - zo) * d + (random->nextDouble() - 0.5) * bbWidth * 2; - double _x = xo + (x - xo) * d + (random->nextDouble() - 0.5) * bbWidth * 2; - double _y = yo + (y - yo) * d + random->nextDouble() * bbHeight; - double _z = zo + (z - zo) * d + (random->nextDouble() - 0.5) * bbWidth * 2; - - // 4J - Brought forward particle change from 1.2.3 - //level->addParticle(eParticleType_largesmoke, _x, _y, _z, xa, ya, za); - level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, za); - } - // 4J - moved sounds forward from 1.2.3 - level->playSound(xo, yo, zo, eSoundType_MOB_ENDERMEN_PORTAL, 1, 1); - level->playSound(shared_from_this(), eSoundType_MOB_ENDERMEN_PORTAL, 1, 1); - return true; - } - else - { - setPos(xo, yo, zo); - return false; - } + // 4J - Brought forward particle change from 1.2.3 + // level->addParticle(eParticleType_largesmoke, _x, _y, _z, xa, ya, + // za); + level->addParticle(eParticleType_ender, _x, _y, _z, xa, ya, za); + } + // 4J - moved sounds forward from 1.2.3 + level->playSound(xo, yo, zo, eSoundType_MOB_ENDERMEN_PORTAL, 1, 1); + level->playSound(shared_from_this(), eSoundType_MOB_ENDERMEN_PORTAL, 1, + 1); + return true; + } else { + setPos(xo, yo, zo); + return false; + } } -int EnderMan::getAmbientSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_ENDERMEN_IDLE; +int EnderMan::getAmbientSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_ENDERMEN_IDLE; } -int EnderMan::getHurtSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_ENDERMEN_HIT; +int EnderMan::getHurtSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_ENDERMEN_HIT; } -int EnderMan::getDeathSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_ENDERMEN_DEATH; +int EnderMan::getDeathSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_ENDERMEN_DEATH; } -int EnderMan::getDeathLoot() -{ - return Item::enderPearl_Id; -} +int EnderMan::getDeathLoot() { return Item::enderPearl_Id; } -void EnderMan::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int loot = getDeathLoot(); - if (loot > 0) - { - int count = random->nextInt(2 + playerBonusLevel); - for (int i = 0; i < count; i++) - spawnAtLocation(loot, 1); - } +void EnderMan::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int loot = getDeathLoot(); + if (loot > 0) { + int count = random->nextInt(2 + playerBonusLevel); + for (int i = 0; i < count; i++) spawnAtLocation(loot, 1); + } } // 4J Brought forward from 1.2.3 to help fix Enderman behaviour -void EnderMan::setCarryingTile(int carryingTile) -{ - entityData->set(DATA_CARRY_ITEM_ID, (uint8_t) (carryingTile & 0xff)); +void EnderMan::setCarryingTile(int carryingTile) { + entityData->set(DATA_CARRY_ITEM_ID, (uint8_t)(carryingTile & 0xff)); } -int EnderMan::getCarryingTile() -{ - return entityData->getByte(DATA_CARRY_ITEM_ID); +int EnderMan::getCarryingTile() { + return entityData->getByte(DATA_CARRY_ITEM_ID); } -void EnderMan::setCarryingData(int carryingData) -{ - entityData->set(DATA_CARRY_ITEM_DATA, (uint8_t) (carryingData & 0xff)); +void EnderMan::setCarryingData(int carryingData) { + entityData->set(DATA_CARRY_ITEM_DATA, (uint8_t)(carryingData & 0xff)); } -int EnderMan::getCarryingData() -{ - return entityData->getByte(DATA_CARRY_ITEM_DATA); +int EnderMan::getCarryingData() { + return entityData->getByte(DATA_CARRY_ITEM_DATA); } -bool EnderMan::hurt(DamageSource *source, int damage) -{ - if (dynamic_cast(source) != NULL) - { - for (int i = 0; i < 64; i++) - { - if (teleport()) return true; - } - return false; - } - return Monster::hurt(source, damage); +bool EnderMan::hurt(DamageSource* source, int damage) { + if (dynamic_cast(source) != NULL) { + for (int i = 0; i < 64; i++) { + if (teleport()) return true; + } + return false; + } + return Monster::hurt(source, damage); } -bool EnderMan::isCreepy() -{ - return entityData->getByte(DATA_CREEPY) > 0; -} +bool EnderMan::isCreepy() { return entityData->getByte(DATA_CREEPY) > 0; } -void EnderMan::setCreepy(bool creepy) -{ - entityData->set(DATA_CREEPY, (uint8_t)(creepy ? 1 : 0)); +void EnderMan::setCreepy(bool creepy) { + entityData->set(DATA_CREEPY, (uint8_t)(creepy ? 1 : 0)); } diff --git a/Minecraft.World/Entities/Mobs/EnderMan.h b/Minecraft.World/Entities/Mobs/EnderMan.h index a33077352..795d93e02 100644 --- a/Minecraft.World/Entities/Mobs/EnderMan.h +++ b/Minecraft.World/Entities/Mobs/EnderMan.h @@ -2,63 +2,64 @@ #include "../Monster.h" -class EnderMan : public Monster -{ +class EnderMan : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_ENDERMAN; } - static Entity *create(Level *level) { return new EnderMan(level); } -public: - static void staticCtor(); -private: - static bool MAY_TAKE[256]; + eINSTANCEOF GetType() { return eTYPE_ENDERMAN; } + static Entity* create(Level* level) { return new EnderMan(level); } - static const int DATA_CARRY_ITEM_ID = 16; - static const int DATA_CARRY_ITEM_DATA = 17; - static const int DATA_CREEPY = 18; +public: + static void staticCtor(); private: - int teleportTime; - int aggroTime; + static bool MAY_TAKE[256]; -public: - EnderMan(Level *level); - - virtual int getMaxHealth(); - -protected: - virtual void defineSynchedData(); - -public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - -protected: - virtual std::shared_ptr findAttackTarget(); + static const int DATA_CARRY_ITEM_ID = 16; + static const int DATA_CARRY_ITEM_DATA = 17; + static const int DATA_CREEPY = 18; private: - bool isLookingAtMe(std::shared_ptr player); + int teleportTime; + int aggroTime; public: - virtual void aiStep(); + EnderMan(Level* level); + + virtual int getMaxHealth(); protected: - bool teleport(); - bool teleportTowards(std::shared_ptr e); - bool teleport(double xx, double yy, double zz); - - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void defineSynchedData(); public: - // 4J Brought forward from 1.2.3 to help fix Enderman behaviour - void setCarryingTile(int carryingTile); - int getCarryingTile(); - void setCarryingData(int carryingData); - int getCarryingData(); - virtual bool hurt(DamageSource *source, int damage); - bool isCreepy(); - void setCreepy(bool creepy); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + +protected: + virtual std::shared_ptr findAttackTarget(); + +private: + bool isLookingAtMe(std::shared_ptr player); + +public: + virtual void aiStep(); + +protected: + bool teleport(); + bool teleportTowards(std::shared_ptr e); + bool teleport(double xx, double yy, double zz); + + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + +public: + // 4J Brought forward from 1.2.3 to help fix Enderman behaviour + void setCarryingTile(int carryingTile); + int getCarryingTile(); + void setCarryingData(int carryingData); + int getCarryingData(); + virtual bool hurt(DamageSource* source, int damage); + bool isCreepy(); + void setCreepy(bool creepy); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ExperienceOrb.cpp b/Minecraft.World/Entities/Mobs/ExperienceOrb.cpp index 92dc79f1a..e5697ce0d 100644 --- a/Minecraft.World/Entities/Mobs/ExperienceOrb.cpp +++ b/Minecraft.World/Entities/Mobs/ExperienceOrb.cpp @@ -10,321 +10,258 @@ #include "ExperienceOrb.h" #include "../../Util/SoundTypes.h" +const int ExperienceOrb::LIFETIME = + 5 * 60 * SharedConstants::TICKS_PER_SECOND; // Five minutes! +void ExperienceOrb::_init() { + tickCount = 0; + age = 0; -const int ExperienceOrb::LIFETIME = 5 * 60 * SharedConstants::TICKS_PER_SECOND; // Five minutes! + throwTime = 0; -void ExperienceOrb::_init() -{ - tickCount = 0; - age = 0; - - throwTime = 0; - - health = 5; - value = 0; - followingPlayer = nullptr; - followingTime = 0; + health = 5; + value = 0; + followingPlayer = nullptr; + followingTime = 0; } -ExperienceOrb::ExperienceOrb(Level *level, double x, double y, double z, int count) : Entity(level) -{ - _init(); +ExperienceOrb::ExperienceOrb(Level* level, double x, double y, double z, + int count) + : Entity(level) { + _init(); - setSize(0.5f, 0.5f); - heightOffset = bbHeight / 2.0f; - setPos(x, y, z); + setSize(0.5f, 0.5f); + heightOffset = bbHeight / 2.0f; + setPos(x, y, z); - yRot = (float) (Math::random() * 360); + yRot = (float)(Math::random() * 360); - xd = (float) (Math::random() * 0.2f - 0.1f) * 2; - yd = (float) (Math::random() * 0.2) * 2; - zd = (float) (Math::random() * 0.2f - 0.1f) * 2; + xd = (float)(Math::random() * 0.2f - 0.1f) * 2; + yd = (float)(Math::random() * 0.2) * 2; + zd = (float)(Math::random() * 0.2f - 0.1f) * 2; - value = count; + value = count; } -bool ExperienceOrb::makeStepSound() -{ - return false; +bool ExperienceOrb::makeStepSound() { return false; } + +ExperienceOrb::ExperienceOrb(Level* level) : Entity(level) { + _init(); + + setSize(0.25f, 0.25f); + heightOffset = bbHeight / 2.0f; } -ExperienceOrb::ExperienceOrb(Level *level) : Entity( level ) -{ - _init(); +void ExperienceOrb::defineSynchedData() {} - setSize(0.25f, 0.25f); - heightOffset = bbHeight / 2.0f; +int ExperienceOrb::getLightColor(float a) { + float l = 0.5f; + if (l < 0) l = 0; + if (l > 1) l = 1; + int br = Entity::getLightColor(a); + + int br1 = (br) & 0xff; + int br2 = (br >> 16) & 0xff; + br1 += (int)(l * 15 * 16); + if (br1 > 15 * 16) br1 = 15 * 16; + // br2 = 15*16; + return br1 | br2 << 16; } -void ExperienceOrb::defineSynchedData() -{ +void ExperienceOrb::tick() { + Entity::tick(); + if (throwTime > 0) throwTime--; + xo = x; + yo = y; + zo = z; + + yd -= 0.03f; + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) == + Material::lava) { + yd = 0.2f; + xd = (random->nextFloat() - random->nextFloat()) * 0.2f; + zd = (random->nextFloat() - random->nextFloat()) * 0.2f; + level->playSound(shared_from_this(), eSoundType_RANDOM_FIZZ, 0.4f, + 2.0f + random->nextFloat() * 0.4f); + } + checkInTile(x, (bb->y0 + bb->y1) / 2, z); + + double maxDist = 8; + // 4J - PC Comment + // Usually exp orbs will get created at the same time so smoothen the + // lagspikes + if (followingTime < + tickCount - SharedConstants::TICKS_PER_SECOND + (entityId % 100)) { + if (followingPlayer == NULL || + followingPlayer->distanceToSqr(shared_from_this()) > + maxDist * maxDist) { + followingPlayer = + level->getNearestPlayer(shared_from_this(), maxDist); + } + followingTime = tickCount; + } + if (followingPlayer != NULL) { + double xdd = (followingPlayer->x - x) / maxDist; + double ydd = + (followingPlayer->y + followingPlayer->getHeadHeight() - y) / + maxDist; + double zdd = (followingPlayer->z - z) / maxDist; + double dd = sqrt(xdd * xdd + ydd * ydd + zdd * zdd); + double power = 1 - dd; + if (power > 0) { + power = power * power; + xd += xdd / dd * power * 0.1; + yd += ydd / dd * power * 0.1; + zd += zdd / dd * power * 0.1; + } + } + + move(xd, yd, zd); + + float friction = 0.98f; + if (onGround) { + friction = 0.6f * 0.98f; + int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, + Mth::floor(z)); + if (t > 0) { + friction = Tile::tiles[t]->friction * 0.98f; + } + } + + xd *= friction; + yd *= 0.98f; + zd *= friction; + + if (onGround) { + yd *= -0.9f; + } + + tickCount++; + + age++; + if (age >= LIFETIME) { + remove(); + } } -int ExperienceOrb::getLightColor(float a) -{ - float l = 0.5f; - if (l < 0) l = 0; - if (l > 1) l = 1; - int br = Entity::getLightColor(a); - - int br1 = (br) & 0xff; - int br2 = (br >> 16) & 0xff; - br1 += (int) (l * 15 * 16); - if (br1 > 15 * 16) br1 = 15 * 16; - // br2 = 15*16; - return br1 | br2 << 16; +bool ExperienceOrb::updateInWaterState() { + return level->checkAndHandleWater(bb, Material::water, shared_from_this()); } -void ExperienceOrb::tick() -{ - Entity::tick(); - if (throwTime > 0) throwTime--; - xo = x; - yo = y; - zo = z; +void ExperienceOrb::burn(int dmg) { hurt(DamageSource::inFire, dmg); } - yd -= 0.03f; - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) == Material::lava) - { - yd = 0.2f; - xd = (random->nextFloat() - random->nextFloat()) * 0.2f; - zd = (random->nextFloat() - random->nextFloat()) * 0.2f; - level->playSound(shared_from_this(), eSoundType_RANDOM_FIZZ, 0.4f, 2.0f + random->nextFloat() * 0.4f); - } - checkInTile(x, (bb->y0 + bb->y1) / 2, z); - - double maxDist = 8; - // 4J - PC Comment - // Usually exp orbs will get created at the same time so smoothen the lagspikes - if (followingTime < tickCount - SharedConstants::TICKS_PER_SECOND + (entityId % 100)) - { - if (followingPlayer == NULL || followingPlayer->distanceToSqr(shared_from_this()) > maxDist * maxDist) - { - followingPlayer = level->getNearestPlayer(shared_from_this(), maxDist); - } - followingTime = tickCount; - } - if (followingPlayer != NULL) - { - double xdd = (followingPlayer->x - x) / maxDist; - double ydd = (followingPlayer->y + followingPlayer->getHeadHeight() - y) / maxDist; - double zdd = (followingPlayer->z - z) / maxDist; - double dd = sqrt(xdd * xdd + ydd * ydd + zdd * zdd); - double power = 1 - dd; - if (power > 0) - { - power = power * power; - xd += xdd / dd * power * 0.1; - yd += ydd / dd * power * 0.1; - zd += zdd / dd * power * 0.1; - } - } - - move(xd, yd, zd); - - float friction = 0.98f; - if (onGround) - { - friction = 0.6f * 0.98f; - int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) - { - friction = Tile::tiles[t]->friction * 0.98f; - } - } - - xd *= friction; - yd *= 0.98f; - zd *= friction; - - if (onGround) - { - yd *= -0.9f; - } - - tickCount++; - - age++; - if (age >= LIFETIME) - { - remove(); - } +bool ExperienceOrb::hurt(DamageSource* source, int damage) { + markHurt(); + health -= damage; + if (health <= 0) { + remove(); + } + return false; } -bool ExperienceOrb::updateInWaterState() -{ - return level->checkAndHandleWater(bb, Material::water, shared_from_this()); +void ExperienceOrb::addAdditonalSaveData(CompoundTag* entityTag) { + entityTag->putShort(L"Health", (uint8_t)health); + entityTag->putShort(L"Age", (short)age); + entityTag->putShort(L"Value", (short)value); } -void ExperienceOrb::burn(int dmg) -{ - hurt(DamageSource::inFire, dmg); +void ExperienceOrb::readAdditionalSaveData(CompoundTag* tag) { + health = tag->getShort(L"Health") & 0xff; + age = tag->getShort(L"Age"); + value = tag->getShort(L"Value"); } -bool ExperienceOrb::hurt(DamageSource *source, int damage) -{ - markHurt(); - health -= damage; - if (health <= 0) - { - remove(); - } - return false; +void ExperienceOrb::playerTouch(std::shared_ptr player) { + if (level->isClientSide) return; + + if (throwTime == 0 && player->takeXpDelay == 0) { + player->takeXpDelay = 2; + // 4J - sound change brought forward from 1.2.3 + level->playSound( + shared_from_this(), eSoundType_RANDOM_ORB, 0.1f, + 0.5f * ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.8f)); + player->take(shared_from_this(), 1); + player->increaseXp(value); + remove(); + } } -void ExperienceOrb::addAdditonalSaveData(CompoundTag *entityTag) -{ - entityTag->putShort(L"Health", (uint8_t) health); - entityTag->putShort(L"Age", (short) age); - entityTag->putShort(L"Value", (short) value); -} +int ExperienceOrb::getValue() { return value; } -void ExperienceOrb::readAdditionalSaveData(CompoundTag *tag) -{ - health = tag->getShort(L"Health") & 0xff; - age = tag->getShort(L"Age"); - value = tag->getShort(L"Value"); -} +int ExperienceOrb::getIcon() { + if (value >= 2477) { + return 10; + } else if (value >= 1237) { + return 9; + } else if (value >= 617) { + return 8; + } else if (value >= 307) { + return 7; + } else if (value >= 149) { + return 6; + } else if (value >= 73) { + return 5; + } else if (value >= 37) { + return 4; + } else if (value >= 17) { + return 3; + } else if (value >= 7) { + return 2; + } else if (value >= 3) { + return 1; + } -void ExperienceOrb::playerTouch(std::shared_ptr player) -{ - if (level->isClientSide) return; - - if (throwTime == 0 && player->takeXpDelay == 0) - { - player->takeXpDelay = 2; - // 4J - sound change brought forward from 1.2.3 - level->playSound(shared_from_this(), eSoundType_RANDOM_ORB, 0.1f, 0.5f * ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.8f)); - player->take(shared_from_this(), 1); - player->increaseXp(value); - remove(); - } -} - -int ExperienceOrb::getValue() -{ - return value; -} - -int ExperienceOrb::getIcon() -{ - - if (value >= 2477) - { - return 10; - } - else if (value >= 1237) - { - return 9; - } - else if (value >= 617) - { - return 8; - } - else if (value >= 307) - { - return 7; - } - else if (value >= 149) - { - return 6; - } - else if (value >= 73) - { - return 5; - } - else if (value >= 37) - { - return 4; - } - else if (value >= 17) - { - return 3; - } - else if (value >= 7) - { - return 2; - } - else if (value >= 3) - { - return 1; - } - - return 0; + return 0; } /** -* Fetches the biggest possible experience orb value based on a maximum -* value. The current algorithm is next prime which is at least twice more -* than the previous one. -* -* @param maxValue -* @return -*/ -int ExperienceOrb::getExperienceValue(int maxValue) -{ + * Fetches the biggest possible experience orb value based on a maximum + * value. The current algorithm is next prime which is at least twice more + * than the previous one. + * + * @param maxValue + * @return + */ +int ExperienceOrb::getExperienceValue(int maxValue) { + if (maxValue >= 2477) { + return 2477; + } else if (maxValue >= 1237) { + return 1237; + } else if (maxValue >= 617) { + return 617; + } else if (maxValue >= 307) { + return 307; + } else if (maxValue >= 149) { + return 149; + } else if (maxValue >= 73) { + return 73; + } else if (maxValue >= 37) { + return 37; + } else if (maxValue >= 17) { + return 17; + } else if (maxValue >= 7) { + return 7; + } else if (maxValue >= 3) { + return 3; + } - if (maxValue >= 2477) - { - return 2477; - } - else if (maxValue >= 1237) - { - return 1237; - } - else if (maxValue >= 617) - { - return 617; - } - else if (maxValue >= 307) - { - return 307; - } - else if (maxValue >= 149) - { - return 149; - } - else if (maxValue >= 73) - { - return 73; - } - else if (maxValue >= 37) - { - return 37; - } - else if (maxValue >= 17) - { - return 17; - } - else if (maxValue >= 7) - { - return 7; - } - else if (maxValue >= 3) - { - return 3; - } - - return 1; + return 1; } -bool ExperienceOrb::isAttackable() -{ - return false; -} +bool ExperienceOrb::isAttackable() { return false; } // 4J added -bool ExperienceOrb::shouldRender(Vec3 *c) -{ - double xd = x - c->x; - double yd = y - c->y; - double zd = z - c->z; - double distance = xd * xd + yd * yd + zd * zd; +bool ExperienceOrb::shouldRender(Vec3* c) { + double xd = x - c->x; + double yd = y - c->y; + double zd = z - c->z; + double distance = xd * xd + yd * yd + zd * zd; - // 4J - don't render experience orbs that are less than 2 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - issues when you go - // near a large pile of experience orbs that all rush towards the near clip plane - if( distance < 4 ) return false; + // 4J - don't render experience orbs that are less than 2 metres away, to + // try and avoid large particles that are causing us problems with + // photosensitivity testing - issues when you go near a large pile of + // experience orbs that all rush towards the near clip plane + if (distance < 4) return false; - return Entity::shouldRender(c); + return Entity::shouldRender(c); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ExperienceOrb.h b/Minecraft.World/Entities/Mobs/ExperienceOrb.h index 581dfdcb4..2d61f4649 100644 --- a/Minecraft.World/Entities/Mobs/ExperienceOrb.h +++ b/Minecraft.World/Entities/Mobs/ExperienceOrb.h @@ -2,59 +2,58 @@ #include "../Entity.h" -class ExperienceOrb : public Entity -{ +class ExperienceOrb : public Entity { public: - virtual eINSTANCEOF GetType() { return eTYPE_EXPERIENCEORB; } - static Entity *create(Level *level) { return new ExperienceOrb(level); } + virtual eINSTANCEOF GetType() { return eTYPE_EXPERIENCEORB; } + static Entity* create(Level* level) { return new ExperienceOrb(level); } private: - static const int LIFETIME; + static const int LIFETIME; public: - int tickCount; - int age; + int tickCount; + int age; - int throwTime; + int throwTime; private: - int health; - int value; - std::shared_ptr followingPlayer; - int followingTime; + int health; + int value; + std::shared_ptr followingPlayer; + int followingTime; - void _init(); + void _init(); public: - ExperienceOrb(Level *level, double x, double y, double z, int count); + ExperienceOrb(Level* level, double x, double y, double z, int count); protected: - virtual bool makeStepSound(); + virtual bool makeStepSound(); public: - ExperienceOrb(Level *level); + ExperienceOrb(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual int getLightColor(float a); - virtual void tick(); - virtual bool updateInWaterState(); + virtual int getLightColor(float a); + virtual void tick(); + virtual bool updateInWaterState(); protected: - virtual void burn(int dmg); + virtual void burn(int dmg); public: - virtual bool hurt(DamageSource *source, int damage); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void playerTouch(std::shared_ptr player); - int getValue(); - int getIcon(); + virtual bool hurt(DamageSource* source, int damage); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void playerTouch(std::shared_ptr player); + int getValue(); + int getIcon(); - static int getExperienceValue(int maxValue); - virtual bool isAttackable(); + static int getExperienceValue(int maxValue); + virtual bool isAttackable(); - virtual bool shouldRender(Vec3 *c); // 4J added + virtual bool shouldRender(Vec3* c); // 4J added }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.cpp b/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.cpp index 5e682f687..152c5f56e 100644 --- a/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.cpp +++ b/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.cpp @@ -8,199 +8,155 @@ #include "../../Util/JavaMath.h" #include "EyeOfEnderSignal.h" +void EyeOfEnderSignal::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - -void EyeOfEnderSignal::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - // Initialisors - shakeTime = 0; - tx = ty = tz = 0.0; - life = 0; - surviveAfterDeath = false; + // Initialisors + shakeTime = 0; + tx = ty = tz = 0.0; + life = 0; + surviveAfterDeath = false; } - -EyeOfEnderSignal::EyeOfEnderSignal(Level *level) : Entity(level) -{ - _init(); - setSize(0.25f, 0.25f); +EyeOfEnderSignal::EyeOfEnderSignal(Level* level) : Entity(level) { + _init(); + setSize(0.25f, 0.25f); } -void EyeOfEnderSignal::defineSynchedData() -{ +void EyeOfEnderSignal::defineSynchedData() {} + +bool EyeOfEnderSignal::shouldRenderAtSqrDistance(double distance) { + double size = bb->getSize() * 4; + size *= 64.0f; + return distance < size * size; } +EyeOfEnderSignal::EyeOfEnderSignal(Level* level, double x, double y, double z) + : Entity(level) { + _init(); + life = 0; -bool EyeOfEnderSignal::shouldRenderAtSqrDistance(double distance) -{ - double size = bb->getSize() * 4; - size *= 64.0f; - return distance < size * size; + setSize(0.25f, 0.25f); + + this->setPos(x, y, z); + this->heightOffset = 0; } -EyeOfEnderSignal::EyeOfEnderSignal(Level *level, double x, double y, double z) : Entity(level) -{ - _init(); - life = 0; +void EyeOfEnderSignal::signalTo(double tx, int ty, double tz) { + double dx = tx - x, dz = tz - z; + float dist = sqrt(dx * dx + dz * dz); - setSize(0.25f, 0.25f); + if (dist > 12) { + this->tx = x + (dx / dist) * 12; + this->tz = z + (dz / dist) * 12; + this->ty = y + 8; + } else { + this->tx = tx; + this->ty = ty; + this->tz = tz; + } - this->setPos(x, y, z); - this->heightOffset = 0; + life = 0; + surviveAfterDeath = random->nextInt(5) > 0; } -void EyeOfEnderSignal::signalTo(double tx, int ty, double tz) -{ - - - double dx = tx - x, dz = tz - z; - float dist = sqrt(dx * dx + dz * dz); - - if (dist > 12) - { - this->tx = x + (dx / dist) * 12; - this->tz = z + (dz / dist) * 12; - this->ty = y + 8; - } - else - { - this->tx = tx; - this->ty = ty; - this->tz = tz; - } - - life = 0; - surviveAfterDeath = random->nextInt(5) > 0; +void EyeOfEnderSignal::lerpMotion(double xd, double yd, double zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; + if (xRotO == 0 && yRotO == 0) { + float sd = (float)sqrt(xd * xd + zd * zd); + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, (double)sd) * 180 / PI); + } } -void EyeOfEnderSignal::lerpMotion(double xd, double yd, double zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; - if (xRotO == 0 && yRotO == 0) - { - float sd = (float) sqrt(xd * xd + zd * zd); - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, (double)sd) * 180 / PI); - } +void EyeOfEnderSignal::tick() { + xOld = x; + yOld = y; + zOld = z; + Entity::tick(); + + x += xd; + y += yd; + z += zd; + + float sd = (float)sqrt(xd * xd + zd * zd); + yRot = (float)(atan2(xd, zd) * 180 / PI); + xRot = (float)(atan2(yd, (double)sd) * 180 / PI); + + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; + + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; + + xRot = xRotO + (xRot - xRotO) * 0.2f; + yRot = yRotO + (yRot - yRotO) * 0.2f; + + if (!level->isClientSide) { + double dx = tx - x, dz = tz - z; + float tdist = (float)sqrt(dx * dx + dz * dz); + float angle = (float)atan2(dz, dx); + double tspeed = (sd + (tdist - sd) * .0025); + if (tdist < 1) { + tspeed *= .8; + yd *= .8; + } + xd = cos(angle) * tspeed; + zd = sin(angle) * tspeed; + + if (y < ty) { + yd = yd + (1 - yd) * .015f; + } else { + yd = yd + (-1 - yd) * .015f; + } + } + + float s = 1 / 4.0f; + if (isInWater()) { + for (int i = 0; i < 4; i++) { + level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, + z - zd * s, xd, yd, zd); + } + } else { + level->addParticle( + eParticleType_ender, x - xd * s + random->nextDouble() * .6 - .3, + y - yd * s - .5, z - zd * s + random->nextDouble() * .6 - .3, xd, + yd, zd); + } + + if (!level->isClientSide) { + setPos(x, y, z); + + life++; + if (life > SharedConstants::TICKS_PER_SECOND * 4 && + !level->isClientSide) { + remove(); + if (surviveAfterDeath) { + level->addEntity(std::shared_ptr( + new ItemEntity(level, x, y, z, + std::shared_ptr( + new ItemInstance(Item::eyeOfEnder))))); + } else { + level->levelEvent(LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH, + (int)Math::round(x), (int)Math::round(y), + (int)Math::round(z), 0); + } + } + } } -void EyeOfEnderSignal::tick() -{ - xOld = x; - yOld = y; - zOld = z; - Entity::tick(); +void EyeOfEnderSignal::addAdditonalSaveData(CompoundTag* tag) {} - x += xd; - y += yd; - z += zd; +void EyeOfEnderSignal::readAdditionalSaveData(CompoundTag* tag) {} - float sd = (float) sqrt(xd * xd + zd * zd); - yRot = (float) (atan2(xd, zd) * 180 / PI); - xRot = (float) (atan2(yd, (double)sd) * 180 / PI); +float EyeOfEnderSignal::getShadowHeightOffs() { return 0; } - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; +float EyeOfEnderSignal::getBrightness(float a) { return 1.0f; } - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; +int EyeOfEnderSignal::getLightColor(float a) { return 15 << 20 | 15 << 4; } - xRot = xRotO + (xRot - xRotO) * 0.2f; - yRot = yRotO + (yRot - yRotO) * 0.2f; - - if (!level->isClientSide) - { - double dx = tx - x, dz = tz - z; - float tdist = (float) sqrt(dx * dx + dz * dz); - float angle = (float) atan2(dz, dx); - double tspeed = (sd + (tdist - sd) * .0025); - if (tdist < 1) - { - tspeed *= .8; - yd *= .8; - } - xd = cos(angle) * tspeed; - zd = sin(angle) * tspeed; - - if (y < ty) - { - yd = yd + (1 - yd) * .015f; - } - else - { - yd = yd + (-1 - yd) * .015f; - } - - } - - float s = 1 / 4.0f; - if (isInWater()) - { - for (int i = 0; i < 4; i++) - { - level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, z - zd * s, xd, yd, zd); - } - } - else - { - level->addParticle(eParticleType_ender, x - xd * s + random->nextDouble() * .6 - .3, y - yd * s - .5, z - zd * s + random->nextDouble() * .6 - .3, xd, yd, zd); - } - - if (!level->isClientSide) - { - setPos(x, y, z); - - - life++; - if (life > SharedConstants::TICKS_PER_SECOND * 4 && !level->isClientSide) - { - remove(); - if (surviveAfterDeath) - { - level->addEntity(std::shared_ptr( new ItemEntity(level, x, y, z, std::shared_ptr(new ItemInstance(Item::eyeOfEnder))))); - } - else - { - level->levelEvent(LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), 0); - } - } - } -} - -void EyeOfEnderSignal::addAdditonalSaveData(CompoundTag *tag) -{ -} - -void EyeOfEnderSignal::readAdditionalSaveData(CompoundTag *tag) -{ -} - -float EyeOfEnderSignal::getShadowHeightOffs() -{ - return 0; -} - -float EyeOfEnderSignal::getBrightness(float a) -{ - return 1.0f; -} - -int EyeOfEnderSignal::getLightColor(float a) -{ - return 15 << 20 | 15 << 4; -} - -bool EyeOfEnderSignal::isAttackable() -{ - return false; -} \ No newline at end of file +bool EyeOfEnderSignal::isAttackable() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.h b/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.h index e1ec155b5..4026ab834 100644 --- a/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.h +++ b/Minecraft.World/Entities/Mobs/EyeOfEnderSignal.h @@ -2,40 +2,39 @@ #include "../Entity.h" -class EyeOfEnderSignal : public Entity -{ +class EyeOfEnderSignal : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_EYEOFENDERSIGNAL; } - static Entity *create(Level *level) { return new EyeOfEnderSignal(level); } + eINSTANCEOF GetType() { return eTYPE_EYEOFENDERSIGNAL; } + static Entity* create(Level* level) { return new EyeOfEnderSignal(level); } public: - int shakeTime; + int shakeTime; private: - double tx, ty, tz; - int life; - bool surviveAfterDeath; + double tx, ty, tz; + int life; + bool surviveAfterDeath; - void _init(); + void _init(); public: - EyeOfEnderSignal(Level *level); + EyeOfEnderSignal(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual bool shouldRenderAtSqrDistance(double distance); + virtual bool shouldRenderAtSqrDistance(double distance); - EyeOfEnderSignal(Level *level, double x, double y, double z); + EyeOfEnderSignal(Level* level, double x, double y, double z); - void signalTo(double tx, int ty, double tz); - virtual void lerpMotion(double xd, double yd, double zd); - virtual void tick(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual float getShadowHeightOffs(); - virtual float getBrightness(float a); - virtual int getLightColor(float a); - virtual bool isAttackable(); + void signalTo(double tx, int ty, double tz); + virtual void lerpMotion(double xd, double yd, double zd); + virtual void tick(); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual float getShadowHeightOffs(); + virtual float getBrightness(float a); + virtual int getLightColor(float a); + virtual bool isAttackable(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Fireball.cpp b/Minecraft.World/Entities/Mobs/Fireball.cpp index 5e329707a..a138dfe12 100644 --- a/Minecraft.World/Entities/Mobs/Fireball.cpp +++ b/Minecraft.World/Entities/Mobs/Fireball.cpp @@ -10,56 +10,48 @@ #include "../../Headers/net.minecraft.world.level.dimension.h" #include "../../Util/SharedConstants.h" - // 4J - added common ctor code. -void Fireball::_init() -{ - xTile = -1; - yTile = -1; - zTile = -1; - lastTile = 0; - inGround = false; - flightTime = 0; +void Fireball::_init() { + xTile = -1; + yTile = -1; + zTile = -1; + lastTile = 0; + inGround = false; + flightTime = 0; - life = 0; - owner = nullptr; - xPower = 0.0; - yPower = 0.0; - zPower = 0.0; + life = 0; + owner = nullptr; + xPower = 0.0; + yPower = 0.0; + zPower = 0.0; } -Fireball::Fireball(Level *level) : Entity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Fireball::Fireball(Level* level) : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - _init(); + _init(); setSize(16 / 16.0f, 16 / 16.0f); - } -void Fireball::defineSynchedData() -{ +void Fireball::defineSynchedData() {} -} - -bool Fireball::shouldRenderAtSqrDistance(double distance) -{ +bool Fireball::shouldRenderAtSqrDistance(double distance) { double size = bb->getSize() * 4; size *= 64.0f; return distance < size * size; } +Fireball::Fireball(Level* level, double x, double y, double z, double xa, + double ya, double za) + : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); -Fireball::Fireball(Level *level, double x, double y, double z, double xa, double ya, double za) : Entity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - _init(); + _init(); setSize(16 / 16.0f, 16 / 16.0f); @@ -68,29 +60,28 @@ Fireball::Fireball(Level *level, double x, double y, double z, double xa, double double dd = sqrt(xa * xa + ya * ya + za * za); - // Fix for #69150 - [CRASH] TU8: Code: Gameplay: Nether portal mechanics can become permanently broken, causing a hard lock upon usage. - // IF xa, ya and za are 0 then dd is 0 and the xa/dd etc return NAN - if(dd == 0.0) - { - xPower = 0.0; - yPower = 0.0; - zPower = 0.0; - } - else - { - xPower = xa / dd * 0.10; - yPower = ya / dd * 0.10; - zPower = za / dd * 0.10; - } + // Fix for #69150 - [CRASH] TU8: Code: Gameplay: Nether portal mechanics can + // become permanently broken, causing a hard lock upon usage. IF xa, ya and + // za are 0 then dd is 0 and the xa/dd etc return NAN + if (dd == 0.0) { + xPower = 0.0; + yPower = 0.0; + zPower = 0.0; + } else { + xPower = xa / dd * 0.10; + yPower = ya / dd * 0.10; + zPower = za / dd * 0.10; + } } -Fireball::Fireball(Level *level, std::shared_ptr mob, double xa, double ya, double za) : Entity ( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Fireball::Fireball(Level* level, std::shared_ptr mob, double xa, double ya, + double za) + : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - _init(); + _init(); this->owner = mob; @@ -100,7 +91,6 @@ Fireball::Fireball(Level *level, std::shared_ptr mob, double xa, double ya, this->setPos(x, y, z); this->heightOffset = 0; - xd = yd = zd = 0.0; xa += random->nextGaussian() * 0.4; @@ -108,70 +98,61 @@ Fireball::Fireball(Level *level, std::shared_ptr mob, double xa, double ya, za += random->nextGaussian() * 0.4; double dd = sqrt(xa * xa + ya * ya + za * za); - // Fix for #69150 - [CRASH] TU8: Code: Gameplay: Nether portal mechanics can become permanently broken, causing a hard lock upon usage. - // IF xa, ya and za are 0 then dd is 0 and the xa/dd etc return NAN - if(dd == 0.0) - { - xPower = 0.0; - yPower = 0.0; - zPower = 0.0; - } - else - { - xPower = xa / dd * 0.10; - yPower = ya / dd * 0.10; - zPower = za / dd * 0.10; - } + // Fix for #69150 - [CRASH] TU8: Code: Gameplay: Nether portal mechanics can + // become permanently broken, causing a hard lock upon usage. IF xa, ya and + // za are 0 then dd is 0 and the xa/dd etc return NAN + if (dd == 0.0) { + xPower = 0.0; + yPower = 0.0; + zPower = 0.0; + } else { + xPower = xa / dd * 0.10; + yPower = ya / dd * 0.10; + zPower = za / dd * 0.10; + } } -void Fireball::tick() -{ - // 4J-PB - Moved forward from 1.2.3 - //if (!level->isClientSide && (owner == NULL || owner->removed)) - if (!level->isClientSide) - { - if((owner != NULL && owner->removed) || !level->hasChunkAt((int) x, (int) y, (int) z)) - { - app.DebugPrintf("Fireball removed - owner is null or removed is true for owner\n"); - remove(); - return; - } - else - { - // 4J-PB - TU9 bug fix - fireballs can hit the edge of the world, and stay there - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; +void Fireball::tick() { + // 4J-PB - Moved forward from 1.2.3 + // if (!level->isClientSide && (owner == NULL || owner->removed)) + if (!level->isClientSide) { + if ((owner != NULL && owner->removed) || + !level->hasChunkAt((int)x, (int)y, (int)z)) { + app.DebugPrintf( + "Fireball removed - owner is null or removed is true for " + "owner\n"); + remove(); + return; + } else { + // 4J-PB - TU9 bug fix - fireballs can hit the edge of the world, + // and stay there + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; - if ((x<=minXZ) || (x>=maxXZ) || (z<=minXZ) || (z>=maxXZ)) - { - remove(); - app.DebugPrintf("Fireball removed - end of world\n"); - return; - } - } - } + if ((x <= minXZ) || (x >= maxXZ) || (z <= minXZ) || (z >= maxXZ)) { + remove(); + app.DebugPrintf("Fireball removed - end of world\n"); + return; + } + } + } Entity::tick(); - //app.DebugPrintf("Fireball x %d, y %d, z%d\n",(int)x,(int)y,(int)z); + // app.DebugPrintf("Fireball x %d, y %d, z%d\n",(int)x,(int)y,(int)z); - if(shouldBurn()) setOnFire(1); + if (shouldBurn()) setOnFire(1); - if (inGround) - { + if (inGround) { int tile = level->getTile(xTile, yTile, zTile); - if (tile == lastTile) - { + if (tile == lastTile) { life++; - if (life == SharedConstants::TICKS_PER_SECOND * 30) - { - remove(); - app.DebugPrintf("Fireball removed - life is 20*60\n"); - } + if (life == SharedConstants::TICKS_PER_SECOND * 30) { + remove(); + app.DebugPrintf("Fireball removed - life is 20*60\n"); + } return; - } - else - { + } else { inGround = false; xd *= random->nextFloat() * 0.2f; @@ -180,89 +161,77 @@ void Fireball::tick() life = 0; flightTime = 0; } - } - else - { - flightTime++; + } else { + flightTime++; } - MemSect(41); - Vec3 *from = Vec3::newTemp(x, y, z); - Vec3 *to = Vec3::newTemp(x + xd, y + yd, z + zd); - HitResult *res = level->clip(from, to); + MemSect(41); + Vec3* from = Vec3::newTemp(x, y, z); + Vec3* to = Vec3::newTemp(x + xd, y + yd, z + zd); + HitResult* res = level->clip(from, to); from = Vec3::newTemp(x, y, z); to = Vec3::newTemp(x + xd, y + yd, z + zd); - if (res != NULL) - { + if (res != NULL) { to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); } std::shared_ptr hitEntity = nullptr; - std::vector > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); + std::vector >* objects = level->getEntities( + shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //objects->at(i); - if (!e->isPickable() || (e->is(owner) )) continue; //4J Stu - Never collide with the owner (Enderdragon) // && flightTime < 25)) continue; + AUTO_VAR(itEnd, objects->end()); + for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // objects->at(i); + if (!e->isPickable() || (e->is(owner))) + continue; // 4J Stu - Never collide with the owner (Enderdragon) // + // && flightTime < 25)) continue; float rr = 0.3f; - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (p != NULL) - { + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (p != NULL) { double dd = from->distanceTo(p->pos); - if (dd < nearest || nearest == 0) - { + if (dd < nearest || nearest == 0) { hitEntity = e; nearest = dd; } - delete p; - } - + delete p; + } } - if (hitEntity != NULL) - { - delete res; + if (hitEntity != NULL) { + delete res; res = new HitResult(hitEntity); } - MemSect(0); + MemSect(0); - if (res != NULL) - { - onHit(res); + if (res != NULL) { + onHit(res); } - delete res; + delete res; x += xd; y += yd; z += zd; double sd = sqrt(xd * xd + zd * zd); - yRot = (float) (atan2(xd, zd) * 180 / PI); - xRot = (float) (atan2(yd, sd) * 180 / PI); + yRot = (float)(atan2(xd, zd) * 180 / PI); + xRot = (float)(atan2(yd, sd) * 180 / PI); - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; xRot = xRotO + (xRot - xRotO) * 0.2f; yRot = yRotO + (yRot - yRotO) * 0.2f; - float inertia = 0.95f; - if (isInWater()) - { - for (int i = 0; i < 4; i++) - { + if (isInWater()) { + for (int i = 0; i < 4; i++) { float s = 1 / 4.0f; - level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, z - zd * s, xd, yd, zd); + level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, + z - zd * s, xd, yd, zd); } inertia = 0.80f; } @@ -274,99 +243,82 @@ void Fireball::tick() yd *= inertia; zd *= inertia; - // 4J-PB - bug fix for the fireballs in a saved game - they are saved with no/very small velocity, so end up hanging around in the air - if (!level->isClientSide) - { - if((abs(xd)<0.002) && (abs(yd)<0.002) && (abs(zd)<0.002)) - { - xd=0.0; - zd=0.0; - yd=0.0; - app.DebugPrintf("Removing a fireball with zero velocity\n"); - remove(); - } - } + // 4J-PB - bug fix for the fireballs in a saved game - they are saved with + // no/very small velocity, so end up hanging around in the air + if (!level->isClientSide) { + if ((abs(xd) < 0.002) && (abs(yd) < 0.002) && (abs(zd) < 0.002)) { + xd = 0.0; + zd = 0.0; + yd = 0.0; + app.DebugPrintf("Removing a fireball with zero velocity\n"); + remove(); + } + } level->addParticle(getTrailParticleType(), x, y + 0.5f, z, 0, 0.01, 0); setPos(x, y, z); } -void Fireball::onHit(HitResult *res) -{ - if (!level->isClientSide) - { - if (res->entity != NULL) - { - DamageSource *damageSource = DamageSource::fireball(std::dynamic_pointer_cast( shared_from_this() ), owner); - if (res->entity->hurt(damageSource, 6)) - { - } - else - { - } - delete damageSource; - } +void Fireball::onHit(HitResult* res) { + if (!level->isClientSide) { + if (res->entity != NULL) { + DamageSource* damageSource = DamageSource::fireball( + std::dynamic_pointer_cast(shared_from_this()), owner); + if (res->entity->hurt(damageSource, 6)) { + } else { + } + delete damageSource; + } - bool destroyBlocks = true;//level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); - level->explode(nullptr, x, y, z, 1, true, destroyBlocks); + bool destroyBlocks = + true; // level.getGameRules().getBoolean(GameRules.RULE_MOBGRIEFING); + level->explode(nullptr, x, y, z, 1, true, destroyBlocks); - remove(); - } + remove(); + } } -void Fireball::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putShort(L"xTile", (short) xTile); - tag->putShort(L"yTile", (short) yTile); - tag->putShort(L"zTile", (short) zTile); - tag->putByte(L"inTile", (uint8_t) lastTile); - tag->putByte(L"inGround", (uint8_t) (inGround ? 1 : 0)); - tag->put(L"direction", this->newDoubleList(3, this->xd, this->yd, this->zd)); +void Fireball::addAdditonalSaveData(CompoundTag* tag) { + tag->putShort(L"xTile", (short)xTile); + tag->putShort(L"yTile", (short)yTile); + tag->putShort(L"zTile", (short)zTile); + tag->putByte(L"inTile", (uint8_t)lastTile); + tag->putByte(L"inGround", (uint8_t)(inGround ? 1 : 0)); + tag->put(L"direction", + this->newDoubleList(3, this->xd, this->yd, this->zd)); } -void Fireball::readAdditionalSaveData(CompoundTag *tag) -{ +void Fireball::readAdditionalSaveData(CompoundTag* tag) { xTile = tag->getShort(L"xTile"); yTile = tag->getShort(L"yTile"); zTile = tag->getShort(L"zTile"); lastTile = tag->getByte(L"inTile") & 0xff; inGround = tag->getByte(L"inGround") == 1; - // Load the stored direction and apply it to the fireball - // if it has no stored direction, remove it. - if (tag->contains(L"direction")) - { - ListTag *listTag = (ListTag *)tag->getList(L"direction"); - this->xd = ((DoubleTag *) listTag->get(0))->data; - this->yd = ((DoubleTag *) listTag->get(1))->data; - this->zd = ((DoubleTag *) listTag->get(2))->data; - } - else - { - this->remove(); - } + // Load the stored direction and apply it to the fireball + // if it has no stored direction, remove it. + if (tag->contains(L"direction")) { + ListTag* listTag = + (ListTag*)tag->getList(L"direction"); + this->xd = ((DoubleTag*)listTag->get(0))->data; + this->yd = ((DoubleTag*)listTag->get(1))->data; + this->zd = ((DoubleTag*)listTag->get(2))->data; + } else { + this->remove(); + } } -bool Fireball::isPickable() -{ - return true; -} +bool Fireball::isPickable() { return true; } -float Fireball::getPickRadius() -{ - return 1; -} +float Fireball::getPickRadius() { return 1; } -bool Fireball::hurt(DamageSource *source, int damage) -{ +bool Fireball::hurt(DamageSource* source, int damage) { markHurt(); - if (source->getEntity() != NULL) - { - Vec3 *lookAngle = source->getEntity()->getLookAngle(); - if (lookAngle != NULL) - { + if (source->getEntity() != NULL) { + Vec3* lookAngle = source->getEntity()->getLookAngle(); + if (lookAngle != NULL) { xd = lookAngle->x; yd = lookAngle->y; zd = lookAngle->z; @@ -374,42 +326,24 @@ bool Fireball::hurt(DamageSource *source, int damage) yPower = yd * 0.1; zPower = zd * 0.1; } - std::shared_ptr mob = std::dynamic_pointer_cast( source->getEntity() ); - if (mob != NULL) - { - owner = mob; - } + std::shared_ptr mob = + std::dynamic_pointer_cast(source->getEntity()); + if (mob != NULL) { + owner = mob; + } return true; } return false; } -float Fireball::getShadowHeightOffs() -{ - return 0; -} +float Fireball::getShadowHeightOffs() { return 0; } -float Fireball::getBrightness(float a) -{ - return 1.0f; -} +float Fireball::getBrightness(float a) { return 1.0f; } -int Fireball::getLightColor(float a) -{ - return 15 << 20 | 15 << 4; -} +int Fireball::getLightColor(float a) { return 15 << 20 | 15 << 4; } -bool Fireball::shouldBurn() -{ - return true; -} +bool Fireball::shouldBurn() { return true; } -int Fireball::getIcon() -{ - return 14 + 2 * 16; -} +int Fireball::getIcon() { return 14 + 2 * 16; } -ePARTICLE_TYPE Fireball::getTrailParticleType() -{ - return eParticleType_smoke; -} +ePARTICLE_TYPE Fireball::getTrailParticleType() { return eParticleType_smoke; } diff --git a/Minecraft.World/Entities/Mobs/Fireball.h b/Minecraft.World/Entities/Mobs/Fireball.h index 3d6e274d8..29534e61c 100644 --- a/Minecraft.World/Entities/Mobs/Fireball.h +++ b/Minecraft.World/Entities/Mobs/Fireball.h @@ -1,73 +1,71 @@ #pragma once - #include "../Entity.h" #include "../../Util/ParticleTypes.h" class HitResult; -class Fireball : public Entity -{ +class Fireball : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_FIREBALL; } - static Entity *create(Level *level) { return new Fireball(level); } + eINSTANCEOF GetType() { return eTYPE_FIREBALL; } + static Entity* create(Level* level) { return new Fireball(level); } private: - int xTile; - int yTile; - int zTile; - int lastTile; + int xTile; + int yTile; + int zTile; + int lastTile; private: - bool inGround; + bool inGround; public: - std::shared_ptr owner; + std::shared_ptr owner; private: - int life; - int flightTime; + int life; + int flightTime; - // 4J - added common ctor code. - void _init(); + // 4J - added common ctor code. + void _init(); public: - double xPower, yPower, zPower; + double xPower, yPower, zPower; - Fireball(Level *level); + Fireball(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual bool shouldRenderAtSqrDistance(double distance); + virtual bool shouldRenderAtSqrDistance(double distance); - Fireball(Level *level, double x, double y, double z, double xa, double ya, double za); - Fireball(Level *level, std::shared_ptr mob, double xa, double ya, double za); + Fireball(Level* level, double x, double y, double z, double xa, double ya, + double za); + Fireball(Level* level, std::shared_ptr mob, double xa, double ya, + double za); public: - virtual void tick(); + virtual void tick(); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual bool isPickable(); - virtual float getPickRadius(); - virtual bool hurt(DamageSource *source, int damage); - virtual float getShadowHeightOffs(); - virtual float getBrightness(float a); - virtual int getLightColor(float a); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual bool isPickable(); + virtual float getPickRadius(); + virtual bool hurt(DamageSource* source, int damage); + virtual float getShadowHeightOffs(); + virtual float getBrightness(float a); + virtual int getLightColor(float a); - // 4J Added TU9 - virtual bool shouldBurn(); - virtual int getIcon(); + // 4J Added TU9 + virtual bool shouldBurn(); + virtual int getIcon(); protected: -// 4J Added TU9 - virtual ePARTICLE_TYPE getTrailParticleType(); + // 4J Added TU9 + virtual ePARTICLE_TYPE getTrailParticleType(); }; - - diff --git a/Minecraft.World/Entities/Mobs/FishingHook.cpp b/Minecraft.World/Entities/Mobs/FishingHook.cpp index f7315bdd1..9a193ed7f 100644 --- a/Minecraft.World/Entities/Mobs/FishingHook.cpp +++ b/Minecraft.World/Entities/Mobs/FishingHook.cpp @@ -12,439 +12,404 @@ #include "FishingHook.h" #include "../../Util/SoundTypes.h" - - // 4J - added common ctor code. -void FishingHook::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void FishingHook::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - xTile = -1; - yTile = -1; - zTile = -1; - lastTile = 0; - inGround = false; - shakeTime = 0; - flightTime = 0; - nibble = 0; - hookedIn = nullptr; + xTile = -1; + yTile = -1; + zTile = -1; + lastTile = 0; + inGround = false; + shakeTime = 0; + flightTime = 0; + nibble = 0; + hookedIn = nullptr; - lSteps = 0; - lx = 0.0; - ly = 0.0; - lz = 0.0; - lyr = 0.0; - lxr = 0.0; - lxd = 0.0; - lyd = 0.0; - lzd = 0.0; - owner = nullptr; - life = 0; + lSteps = 0; + lx = 0.0; + ly = 0.0; + lz = 0.0; + lyr = 0.0; + lxr = 0.0; + lxd = 0.0; + lyd = 0.0; + lzd = 0.0; + owner = nullptr; + life = 0; - setSize(0.25f, 0.25f); - noCulling = true; + setSize(0.25f, 0.25f); + noCulling = true; } -FishingHook::FishingHook(Level *level) : Entity( level ) -{ - _init(); +FishingHook::FishingHook(Level* level) : Entity(level) { _init(); } + +FishingHook::FishingHook(Level* level, double x, double y, double z, + std::shared_ptr owner) + : Entity(level) { + _init(); + + this->owner = owner; + // 4J Stu - Moved this outside the ctor + // owner->fishing = std::dynamic_pointer_cast( + // shared_from_this() ); + + setPos(x, y, z); } -FishingHook::FishingHook(Level *level, double x, double y, double z, std::shared_ptr owner) : Entity( level ) -{ - _init(); +FishingHook::FishingHook(Level* level, std::shared_ptr mob) + : Entity(level) { + _init(); - this->owner = owner; - // 4J Stu - Moved this outside the ctor - //owner->fishing = std::dynamic_pointer_cast( shared_from_this() ); + this->owner = mob; + // 4J Stu - Moved this outside the ctor + // owner->fishing = std::dynamic_pointer_cast( + // shared_from_this() ); - setPos(x, y, z); + this->moveTo(mob->x, mob->y + 1.62 - mob->heightOffset, mob->z, mob->yRot, + mob->xRot); + + x -= Mth::cos(yRot / 180 * PI) * 0.16f; + y -= 0.1f; + z -= Mth::sin(yRot / 180 * PI) * 0.16f; + this->setPos(x, y, z); + this->heightOffset = 0; + + float speed = 0.4f; + xd = (-Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI)) * speed; + zd = (Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI)) * speed; + yd = (-Mth::sin(xRot / 180 * PI)) * speed; + + shoot(xd, yd, zd, 1.5f, 1); } -FishingHook::FishingHook(Level *level, std::shared_ptr mob) : Entity( level ) -{ - _init(); +void FishingHook::defineSynchedData() {} - this->owner = mob; - // 4J Stu - Moved this outside the ctor - //owner->fishing = std::dynamic_pointer_cast( shared_from_this() ); - - this->moveTo(mob->x, mob->y + 1.62 - mob->heightOffset, mob->z, mob->yRot, mob->xRot); - - - x -= Mth::cos(yRot / 180 * PI) * 0.16f; - y -= 0.1f; - z -= Mth::sin(yRot / 180 * PI) * 0.16f; - this->setPos(x, y, z); - this->heightOffset = 0; - - - float speed = 0.4f; - xd = (-Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI)) * speed; - zd = (Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI)) * speed; - yd = (-Mth::sin(xRot / 180 * PI)) * speed; - - shoot(xd, yd, zd, 1.5f, 1); +bool FishingHook::shouldRenderAtSqrDistance(double distance) { + double size = bb->getSize() * 4; + size *= 64.0f; + return distance < size * size; } -void FishingHook::defineSynchedData() -{ +void FishingHook::shoot(double xd, double yd, double zd, float pow, + float uncertainty) { + float dist = (float)sqrt(xd * xd + yd * yd + zd * zd); + + xd /= dist; + yd /= dist; + zd /= dist; + + xd += (random->nextGaussian()) * 0.0075f * uncertainty; + yd += (random->nextGaussian()) * 0.0075f * uncertainty; + zd += (random->nextGaussian()) * 0.0075f * uncertainty; + + xd *= pow; + yd *= pow; + zd *= pow; + + this->xd = xd; + this->yd = yd; + this->zd = zd; + + double sd = sqrt(xd * xd + zd * zd); + + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, sd) * 180 / PI); + life = 0; } -bool FishingHook::shouldRenderAtSqrDistance(double distance) -{ - double size = bb->getSize() * 4; - size *= 64.0f; - return distance < size * size; +void FishingHook::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + lx = x; + ly = y; + lz = z; + lyr = yRot; + lxr = xRot; + + lSteps = steps; + + this->xd = lxd; + this->yd = lyd; + this->zd = lzd; } -void FishingHook::shoot(double xd, double yd, double zd, float pow, float uncertainty) -{ - float dist = (float) sqrt(xd * xd + yd * yd + zd * zd); - - xd /= dist; - yd /= dist; - zd /= dist; - - xd += (random->nextGaussian()) * 0.0075f * uncertainty; - yd += (random->nextGaussian()) * 0.0075f * uncertainty; - zd += (random->nextGaussian()) * 0.0075f * uncertainty; - - xd *= pow; - yd *= pow; - zd *= pow; - - this->xd = xd; - this->yd = yd; - this->zd = zd; - - double sd = sqrt(xd * xd + zd * zd); - - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, sd) * 180 / PI); - life = 0; +void FishingHook::lerpMotion(double xd, double yd, double zd) { + lxd = this->xd = xd; + lyd = this->yd = yd; + lzd = this->zd = zd; } -void FishingHook::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - lx = x; - ly = y; - lz = z; - lyr = yRot; - lxr = xRot; +void FishingHook::tick() { + Entity::tick(); - lSteps = steps; + if (lSteps > 0) { + double xt = x + (lx - x) / lSteps; + double yt = y + (ly - y) / lSteps; + double zt = z + (lz - z) / lSteps; - this->xd = lxd; - this->yd = lyd; - this->zd = lzd; + double yrd = Mth::wrapDegrees(lyr - yRot); + + yRot += (float)((yrd) / lSteps); + xRot += (float)((lxr - xRot) / lSteps); + + lSteps--; + this->setPos(xt, yt, zt); + this->setRot(yRot, xRot); + return; + } + + if (!level->isClientSide) { + std::shared_ptr selectedItem = owner->getSelectedItem(); + if (owner->removed || !owner->isAlive() || selectedItem == NULL || + selectedItem->getItem() != Item::fishingRod || + this->distanceToSqr(owner) > 32 * 32) { + remove(); + owner->fishing = nullptr; + return; + } + + if (hookedIn != NULL) { + if (hookedIn->removed) + hookedIn = nullptr; + else { + x = hookedIn->x; + y = hookedIn->bb->y0 + hookedIn->bbHeight * 0.8; + z = hookedIn->z; + return; + } + } + } + + if (shakeTime > 0) shakeTime--; + + if (inGround) { + int tile = level->getTile(xTile, yTile, zTile); + if (tile != lastTile) { + life++; + if (life == 20 * 60) remove(); + return; + } else { + inGround = false; + + xd *= random->nextFloat() * 0.2f; + yd *= random->nextFloat() * 0.2f; + zd *= random->nextFloat() * 0.2f; + life = 0; + flightTime = 0; + } + } else { + flightTime++; + } + + Vec3* from = Vec3::newTemp(x, y, z); + Vec3* to = Vec3::newTemp(x + xd, y + yd, z + zd); + HitResult* res = level->clip(from, to); + + from = Vec3::newTemp(x, y, z); + to = Vec3::newTemp(x + xd, y + yd, z + zd); + if (res != NULL) { + to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); + } + std::shared_ptr hitEntity = nullptr; + std::vector >* objects = level->getEntities( + shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); + double nearest = 0; + AUTO_VAR(itEnd, objects->end()); + for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // objects->at(i); + if (!e->isPickable() || (e == owner && flightTime < 5)) continue; + + float rr = 0.3f; + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (p != NULL) { + double dd = from->distanceTo(p->pos); + if (dd < nearest || nearest == 0) { + hitEntity = e; + nearest = dd; + } + delete p; + } + } + + if (hitEntity != NULL) { + delete res; + res = new HitResult(hitEntity); + } + + if (res != NULL) { + if (res->entity != NULL) { + // 4J Stu Move fix for : fix for #48587 - CRASH: Code: Gameplay: + // Hitting another player with the fishing bobber crashes the game. + // [Fishing pole, line] Incorrect std::dynamic_pointer_cast used + // around the shared_from_this() + DamageSource* damageSource = + DamageSource::thrown(shared_from_this(), owner); + if (res->entity->hurt(damageSource, 0)) { + hookedIn = res->entity; + } + delete damageSource; + } else { + inGround = true; + } + } + delete res; + + if (inGround) return; + + move(xd, yd, zd); + + double sd = sqrt(xd * xd + zd * zd); + yRot = (float)(atan2(xd, zd) * 180 / PI); + xRot = (float)(atan2(yd, sd) * 180 / PI); + + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; + + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; + + xRot = xRotO + (xRot - xRotO) * 0.2f; + yRot = yRotO + (yRot - yRotO) * 0.2f; + + float inertia = 0.92f; + + if (onGround || horizontalCollision) { + inertia = 0.5f; + } + + int steps = 5; + double waterPercentage = 0; + for (int i = 0; i < steps; i++) { + double y0 = bb->y0 + (bb->y1 - bb->y0) * (i + 0) / steps - 2 / 16.0f + + 2 / 16.0f; + double y1 = bb->y0 + (bb->y1 - bb->y0) * (i + 1) / steps - 2 / 16.0f + + 2 / 16.0f; + AABB* bb2 = AABB::newTemp(bb->x0, y0, bb->z0, bb->x1, y1, bb->z1); + if (level->containsLiquid(bb2, Material::water)) { + waterPercentage += 1.0 / steps; + } + } + + if (waterPercentage > 0) { + if (nibble > 0) { + nibble--; + } else { + int nibbleOdds = 500; + if (level->isRainingAt(Mth::floor(x), Mth::floor(y) + 1, + Mth::floor(z))) + nibbleOdds = 300; + + if (random->nextInt(nibbleOdds) == 0) { + nibble = random->nextInt(30) + 10; + yd -= 0.2f; + level->playSound( + shared_from_this(), eSoundType_RANDOM_SPLASH, 0.25f, + 1 + (random->nextFloat() - random->nextFloat()) * 0.4f); + float yt = (float)Mth::floor(bb->y0); + for (int i = 0; i < 1 + bbWidth * 20; i++) { + float xo = (random->nextFloat() * 2 - 1) * bbWidth; + float zo = (random->nextFloat() * 2 - 1) * bbWidth; + level->addParticle(eParticleType_bubble, x + xo, yt + 1, + z + zo, xd, + yd - random->nextFloat() * 0.2f, zd); + } + for (int i = 0; i < 1 + bbWidth * 20; i++) { + float xo = (random->nextFloat() * 2 - 1) * bbWidth; + float zo = (random->nextFloat() * 2 - 1) * bbWidth; + level->addParticle(eParticleType_splash, x + xo, yt + 1, + z + zo, xd, yd, zd); + } + } + } + } + + if (nibble > 0) { + yd -= random->nextFloat() * random->nextFloat() * random->nextFloat() * + 0.2; + } + + double bob = waterPercentage * 2 - 1; + yd += 0.04f * bob; + if (waterPercentage > 0) { + inertia *= 0.9; + yd *= 0.8; + } + + xd *= inertia; + yd *= inertia; + zd *= inertia; + + setPos(x, y, z); } -void FishingHook::lerpMotion(double xd, double yd, double zd) -{ - lxd = this->xd = xd; - lyd = this->yd = yd; - lzd = this->zd = zd; +void FishingHook::addAdditonalSaveData(CompoundTag* tag) { + tag->putShort(L"xTile", (short)xTile); + tag->putShort(L"yTile", (short)yTile); + tag->putShort(L"zTile", (short)zTile); + tag->putByte(L"inTile", (uint8_t)lastTile); + tag->putByte(L"shake", (uint8_t)shakeTime); + tag->putByte(L"inGround", (uint8_t)(inGround ? 1 : 0)); } -void FishingHook::tick() -{ - Entity::tick(); - - if (lSteps > 0) - { - double xt = x + (lx - x) / lSteps; - double yt = y + (ly - y) / lSteps; - double zt = z + (lz - z) / lSteps; - - double yrd = Mth::wrapDegrees(lyr - yRot); - - yRot += (float) ( (yrd) / lSteps ); - xRot += (float) ( (lxr - xRot) / lSteps ); - - lSteps--; - this->setPos(xt, yt, zt); - this->setRot(yRot, xRot); - return; - } - - if (!level->isClientSide) - { - std::shared_ptr selectedItem = owner->getSelectedItem(); - if (owner->removed || !owner->isAlive() || selectedItem == NULL || selectedItem->getItem() != Item::fishingRod || this->distanceToSqr(owner) > 32 * 32) - { - remove(); - owner->fishing = nullptr; - return; - } - - if (hookedIn != NULL) - { - if (hookedIn->removed) hookedIn = nullptr; - else - { - x = hookedIn->x; - y = hookedIn->bb->y0 + hookedIn->bbHeight * 0.8; - z = hookedIn->z; - return; - } - } - } - - if (shakeTime > 0) shakeTime--; - - if (inGround) - { - int tile = level->getTile(xTile, yTile, zTile); - if (tile != lastTile) - { - life++; - if (life == 20 * 60) remove(); - return; - } - else - { - inGround = false; - - xd *= random->nextFloat() * 0.2f; - yd *= random->nextFloat() * 0.2f; - zd *= random->nextFloat() * 0.2f; - life = 0; - flightTime = 0; - } - } - else - { - flightTime++; - } - - Vec3 *from = Vec3::newTemp(x, y, z); - Vec3 *to = Vec3::newTemp(x + xd, y + yd, z + zd); - HitResult *res = level->clip(from, to); - - from = Vec3::newTemp(x, y, z); - to = Vec3::newTemp(x + xd, y + yd, z + zd); - if (res != NULL) - { - to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); - } - std::shared_ptr hitEntity = nullptr; - std::vector > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); - double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; // objects->at(i); - if (!e->isPickable() || (e == owner && flightTime < 5)) continue; - - float rr = 0.3f; - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (p != NULL) - { - double dd = from->distanceTo(p->pos); - if (dd < nearest || nearest == 0) - { - hitEntity = e; - nearest = dd; - } - delete p; - } - } - - if (hitEntity != NULL) - { - delete res; - res = new HitResult(hitEntity); - } - - if (res != NULL) - { - if (res->entity != NULL) - { - // 4J Stu Move fix for : fix for #48587 - CRASH: Code: Gameplay: Hitting another player with the fishing bobber crashes the game. [Fishing pole, line] - // Incorrect std::dynamic_pointer_cast used around the shared_from_this() - DamageSource *damageSource = DamageSource::thrown(shared_from_this(), owner); - if (res->entity->hurt(damageSource, 0)) - { - hookedIn = res->entity; - } - delete damageSource; - } - else - { - inGround = true; - } - } - delete res; - - if (inGround) return; - - move(xd, yd, zd); - - double sd = sqrt(xd * xd + zd * zd); - yRot = (float) (atan2(xd, zd) * 180 / PI); - xRot = (float) (atan2(yd, sd) * 180 / PI); - - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; - - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; - - xRot = xRotO + (xRot - xRotO) * 0.2f; - yRot = yRotO + (yRot - yRotO) * 0.2f; - - - float inertia = 0.92f; - - if (onGround || horizontalCollision) - { - inertia = 0.5f; - } - - int steps = 5; - double waterPercentage = 0; - for (int i = 0; i < steps; i++) - { - double y0 = bb->y0 + (bb->y1 - bb->y0) * (i + 0) / steps - 2 / 16.0f + 2 / 16.0f; - double y1 = bb->y0 + (bb->y1 - bb->y0) * (i + 1) / steps - 2 / 16.0f + 2 / 16.0f; - AABB *bb2 = AABB::newTemp(bb->x0, y0, bb->z0, bb->x1, y1, bb->z1); - if (level->containsLiquid(bb2, Material::water)) - { - waterPercentage += 1.0 / steps; - } - } - - if (waterPercentage > 0) - { - if (nibble > 0) - { - nibble--; - } - else - { - int nibbleOdds = 500; - if (level->isRainingAt( Mth::floor(x), Mth::floor(y) + 1, Mth::floor(z))) nibbleOdds = 300; - - if (random->nextInt(nibbleOdds) == 0) - { - nibble = random->nextInt(30) + 10; - yd -= 0.2f; - level->playSound(shared_from_this(), eSoundType_RANDOM_SPLASH, 0.25f, 1 + (random->nextFloat() - random->nextFloat()) * 0.4f); - float yt = (float) Mth::floor(bb->y0); - for (int i = 0; i < 1 + bbWidth * 20; i++) - { - float xo = (random->nextFloat() * 2 - 1) * bbWidth; - float zo = (random->nextFloat() * 2 - 1) * bbWidth; - level->addParticle(eParticleType_bubble, x + xo, yt + 1, z + zo, xd, yd - random->nextFloat() * 0.2f, zd); - } - for (int i = 0; i < 1 + bbWidth * 20; i++) - { - float xo = (random->nextFloat() * 2 - 1) * bbWidth; - float zo = (random->nextFloat() * 2 - 1) * bbWidth; - level->addParticle(eParticleType_splash, x + xo, yt + 1, z + zo, xd, yd, zd); - } - } - } - - } - - if (nibble > 0) - { - yd -= random->nextFloat() * random->nextFloat() * random->nextFloat() * 0.2; - } - - double bob = waterPercentage * 2 - 1; - yd += 0.04f * bob; - if (waterPercentage > 0) - { - inertia *= 0.9; - yd *= 0.8; - } - - xd *= inertia; - yd *= inertia; - zd *= inertia; - - setPos(x, y, z); +void FishingHook::readAdditionalSaveData(CompoundTag* tag) { + xTile = tag->getShort(L"xTile"); + yTile = tag->getShort(L"yTile"); + zTile = tag->getShort(L"zTile"); + lastTile = tag->getByte(L"inTile") & 0xff; + shakeTime = tag->getByte(L"shake") & 0xff; + inGround = tag->getByte(L"inGround") == 1; } -void FishingHook::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putShort(L"xTile", (short) xTile); - tag->putShort(L"yTile", (short) yTile); - tag->putShort(L"zTile", (short) zTile); - tag->putByte(L"inTile", (uint8_t) lastTile); - tag->putByte(L"shake", (uint8_t) shakeTime); - tag->putByte(L"inGround", (uint8_t) (inGround ? 1 : 0)); -} +float FishingHook::getShadowHeightOffs() { return 0; } -void FishingHook::readAdditionalSaveData(CompoundTag *tag) -{ - xTile = tag->getShort(L"xTile"); - yTile = tag->getShort(L"yTile"); - zTile = tag->getShort(L"zTile"); - lastTile = tag->getByte(L"inTile") & 0xff; - shakeTime = tag->getByte(L"shake") & 0xff; - inGround = tag->getByte(L"inGround") == 1; -} +int FishingHook::retrieve() { + if (level->isClientSide) return 0; -float FishingHook::getShadowHeightOffs() -{ - return 0; -} + int dmg = 0; + if (hookedIn != NULL) { + double xa = owner->x - x; + double ya = owner->y - y; + double za = owner->z - z; -int FishingHook::retrieve() -{ - if (level->isClientSide) return 0; + double dist = sqrt(xa * xa + ya * ya + za * za); + double speed = 0.1; + hookedIn->xd += xa * speed; + hookedIn->yd += ya * speed + sqrt(dist) * 0.08; + hookedIn->zd += za * speed; + dmg = 3; + } else if (nibble > 0) { + std::shared_ptr ie = std::shared_ptr( + new ItemEntity(this->Entity::level, x, y, z, + std::shared_ptr( + new ItemInstance(Item::fish_raw)))); + double xa = owner->x - x; + double ya = owner->y - y; + double za = owner->z - z; - int dmg = 0; - if (hookedIn != NULL) - { - double xa = owner->x - x; - double ya = owner->y - y; - double za = owner->z - z; + double dist = sqrt(xa * xa + ya * ya + za * za); + double speed = 0.1; + ie->Entity::xd = xa * speed; + ie->Entity::yd = ya * speed + sqrt(dist) * 0.08; + ie->Entity::zd = za * speed; + level->addEntity(ie); + owner->level->addEntity( + std::shared_ptr(new ExperienceOrb( + owner->level, owner->x, owner->y + 0.5f, owner->z + 0.5f, + random->nextInt(3) + 1))); // 4J Stu brought forward from 1.4 + dmg = 1; + } + if (inGround) dmg = 2; - double dist = sqrt(xa * xa + ya * ya + za * za); - double speed = 0.1; - hookedIn->xd += xa * speed; - hookedIn->yd += ya * speed + sqrt(dist) * 0.08; - hookedIn->zd += za * speed; - dmg = 3; - } - else if (nibble > 0) - { - std::shared_ptr ie = std::shared_ptr( new ItemEntity(this->Entity::level, x, y, z, std::shared_ptr( new ItemInstance(Item::fish_raw) ) ) ); - double xa = owner->x - x; - double ya = owner->y - y; - double za = owner->z - z; - - double dist = sqrt(xa * xa + ya * ya + za * za); - double speed = 0.1; - ie->Entity::xd = xa * speed; - ie->Entity::yd = ya * speed + sqrt(dist) * 0.08; - ie->Entity::zd = za * speed; - level->addEntity(ie); - owner->level->addEntity( std::shared_ptr( new ExperienceOrb(owner->level, owner->x, owner->y + 0.5f, owner->z + 0.5f, random->nextInt(3) + 1) ) ); // 4J Stu brought forward from 1.4 - dmg = 1; - } - if (inGround) dmg = 2; - - remove(); - owner->fishing = nullptr; - return dmg; + remove(); + owner->fishing = nullptr; + return dmg; } // 4J Stu - Brought forward from 1.4 -void FishingHook::remove() -{ - Entity::remove(); - if (owner != NULL) owner->fishing = nullptr; +void FishingHook::remove() { + Entity::remove(); + if (owner != NULL) owner->fishing = nullptr; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/FishingHook.h b/Minecraft.World/Entities/Mobs/FishingHook.h index d5c9a428a..2ee6c19f1 100644 --- a/Minecraft.World/Entities/Mobs/FishingHook.h +++ b/Minecraft.World/Entities/Mobs/FishingHook.h @@ -1,63 +1,63 @@ #pragma once - #include "../Entity.h" class Player; -class FishingHook : public Entity -{ +class FishingHook : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_FISHINGHOOK; } + eINSTANCEOF GetType() { return eTYPE_FISHINGHOOK; } private: - int xTile; - int yTile; - int zTile; - int lastTile; - bool inGround; + int xTile; + int yTile; + int zTile; + int lastTile; + bool inGround; public: - int shakeTime; - std::shared_ptr owner; + int shakeTime; + std::shared_ptr owner; private: - int life; - int flightTime; - int nibble; + int life; + int flightTime; + int nibble; public: - std::shared_ptr hookedIn; + std::shared_ptr hookedIn; private: - void _init(); + void _init(); public: - FishingHook(Level *level); - FishingHook(Level *level, double x, double y, double z, std::shared_ptr owner); - FishingHook(Level *level, std::shared_ptr mob); + FishingHook(Level* level); + FishingHook(Level* level, double x, double y, double z, + std::shared_ptr owner); + FishingHook(Level* level, std::shared_ptr mob); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - bool shouldRenderAtSqrDistance(double distance); - void shoot(double xd, double yd, double zd, float pow, float uncertainty); + bool shouldRenderAtSqrDistance(double distance); + void shoot(double xd, double yd, double zd, float pow, float uncertainty); private: - int lSteps; - double lx, ly, lz, lyr, lxr; - double lxd, lyd, lzd; + int lSteps; + double lx, ly, lz, lyr, lxr; + double lxd, lyd, lzd; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); - virtual void lerpMotion(double xd, double yd, double zd); - virtual void tick(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual float getShadowHeightOffs(); - int retrieve(); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); + virtual void lerpMotion(double xd, double yd, double zd); + virtual void tick(); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual float getShadowHeightOffs(); + int retrieve(); - // 4J Stu - Brought forward from 1.4 - virtual void remove(); + // 4J Stu - Brought forward from 1.4 + virtual void remove(); }; diff --git a/Minecraft.World/Entities/Mobs/Ghast.cpp b/Minecraft.World/Entities/Mobs/Ghast.cpp index 78813197c..8f4617ac9 100644 --- a/Minecraft.World/Entities/Mobs/Ghast.cpp +++ b/Minecraft.World/Entities/Mobs/Ghast.cpp @@ -13,78 +13,70 @@ #include "../../Level/Events/LevelEvent.h" #include "../../Util/SoundTypes.h" +void Ghast::_init() { + floatDuration = 0; + target = nullptr; + retargetTime = 0; + oCharge = 0; + charge = 0; - -void Ghast::_init() -{ - floatDuration = 0; - target = nullptr; - retargetTime = 0; - oCharge = 0; - charge = 0; - - xTarget = 0.0f; - yTarget = 0.0f; - zTarget = 0.0f; + xTarget = 0.0f; + yTarget = 0.0f; + zTarget = 0.0f; } -Ghast::Ghast(Level *level) : FlyingMob( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Ghast::Ghast(Level* level) : FlyingMob(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); _init(); - this->textureIdx = TN_MOB_GHAST; // 4J was L"/mob/ghast.png"; + this->textureIdx = TN_MOB_GHAST; // 4J was L"/mob/ghast.png"; this->setSize(4, 4); this->fireImmune = true; - xpReward = Enemy::XP_REWARD_MEDIUM; + xpReward = Enemy::XP_REWARD_MEDIUM; } -bool Ghast::hurt(DamageSource *source, int dmg) -{ - if (source->getMsgId() == ChatPacket::e_ChatDeathFireball) - { - std::shared_ptr player = std::dynamic_pointer_cast( source->getEntity() ); - if (player != NULL) - { - // reflected fireball, kill the ghast - FlyingMob::hurt(source, 1000); - player->awardStat(GenericStats::ghast(),GenericStats::param_ghast()); - return true; - } - } +bool Ghast::hurt(DamageSource* source, int dmg) { + if (source->getMsgId() == ChatPacket::e_ChatDeathFireball) { + std::shared_ptr player = + std::dynamic_pointer_cast(source->getEntity()); + if (player != NULL) { + // reflected fireball, kill the ghast + FlyingMob::hurt(source, 1000); + player->awardStat(GenericStats::ghast(), + GenericStats::param_ghast()); + return true; + } + } - return FlyingMob::hurt(source, dmg); + return FlyingMob::hurt(source, dmg); } -void Ghast::defineSynchedData() -{ +void Ghast::defineSynchedData() { FlyingMob::defineSynchedData(); - entityData->define(DATA_IS_CHARGING, (uint8_t) 0); + entityData->define(DATA_IS_CHARGING, (uint8_t)0); } -int Ghast::getMaxHealth() -{ - return 10; -} +int Ghast::getMaxHealth() { return 10; } -void Ghast::tick() -{ +void Ghast::tick() { FlyingMob::tick(); uint8_t current = entityData->getByte(DATA_IS_CHARGING); -// this->textureName = current == 1 ? L"/mob/ghast_fire.png" : L"/mob/ghast.png"; // 4J replaced with following line - this->textureIdx = current == 1 ? TN_MOB_GHAST_FIRE : TN_MOB_GHAST; + // this->textureName = current == 1 ? L"/mob/ghast_fire.png" : + // L"/mob/ghast.png"; // 4J replaced with following line + this->textureIdx = current == 1 ? TN_MOB_GHAST_FIRE : TN_MOB_GHAST; } -void Ghast::serverAiStep() -{ - if (!level->isClientSide && level->difficulty == Difficulty::PEACEFUL) remove(); +void Ghast::serverAiStep() { + if (!level->isClientSide && level->difficulty == Difficulty::PEACEFUL) + remove(); checkDespawn(); oCharge = charge; @@ -94,27 +86,22 @@ void Ghast::serverAiStep() double dd = xd * xd + yd * yd + zd * zd; - if (dd < 1 * 1 || dd > 60 * 60) - { + if (dd < 1 * 1 || dd > 60 * 60) { xTarget = x + (random->nextFloat() * 2 - 1) * 16; yTarget = y + (random->nextFloat() * 2 - 1) * 16; zTarget = z + (random->nextFloat() * 2 - 1) * 16; } - if (floatDuration-- <= 0) - { + if (floatDuration-- <= 0) { floatDuration += random->nextInt(5) + 2; - dd = sqrt(dd); + dd = sqrt(dd); - if (canReach(xTarget, yTarget, zTarget, dd)) - { + if (canReach(xTarget, yTarget, zTarget, dd)) { this->xd += xd / dd * 0.1; this->yd += yd / dd * 0.1; this->zd += zd / dd * 0.1; - } - else - { + } else { xTarget = x; yTarget = y; zTarget = z; @@ -122,128 +109,103 @@ void Ghast::serverAiStep() } if (target != NULL && target->removed) target = nullptr; - if (target == NULL || retargetTime-- <= 0) - { + if (target == NULL || retargetTime-- <= 0) { target = level->getNearestAttackablePlayer(shared_from_this(), 100); - if (target != NULL) - { + if (target != NULL) { retargetTime = 20; } } double maxDist = 64.0f; - if (target != NULL && target->distanceToSqr(shared_from_this()) < maxDist * maxDist) - { + if (target != NULL && + target->distanceToSqr(shared_from_this()) < maxDist * maxDist) { double xdd = target->x - x; - double ydd = (target->bb->y0 + target->bbHeight / 2) - (y + bbHeight / 2); + double ydd = + (target->bb->y0 + target->bbHeight / 2) - (y + bbHeight / 2); double zdd = target->z - z; - yBodyRot = yRot = -(float) atan2(xdd, zdd) * 180 / PI; + yBodyRot = yRot = -(float)atan2(xdd, zdd) * 180 / PI; - if (this->canSee(target)) - { - if (charge == 10) - { - // 4J - change brought forward from 1.2.3 - level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_WARNING, (int) x, (int) y, (int) z, 0); + if (this->canSee(target)) { + if (charge == 10) { + // 4J - change brought forward from 1.2.3 + level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_WARNING, + (int)x, (int)y, (int)z, 0); } charge++; - if (charge == 20) - { - // 4J - change brought forward from 1.2.3 - level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_FIREBALL, (int) x, (int) y, (int) z, 0); - std::shared_ptr ie = std::shared_ptr( new Fireball(level, std::dynamic_pointer_cast( shared_from_this() ), xdd, ydd, zdd) ); + if (charge == 20) { + // 4J - change brought forward from 1.2.3 + level->levelEvent(nullptr, LevelEvent::SOUND_GHAST_FIREBALL, + (int)x, (int)y, (int)z, 0); + std::shared_ptr ie = + std::shared_ptr(new Fireball( + level, + std::dynamic_pointer_cast(shared_from_this()), xdd, + ydd, zdd)); double d = 4; - Vec3 *v = getViewVector(1); + Vec3* v = getViewVector(1); ie->x = x + v->x * d; ie->y = y + bbHeight / 2 + 0.5f; ie->z = z + v->z * d; level->addEntity(ie); charge = -40; } - } - else - { + } else { if (charge > 0) charge--; } - } - else - { - yBodyRot = yRot = -(float) atan2(this->xd, this->zd) * 180 / PI; + } else { + yBodyRot = yRot = -(float)atan2(this->xd, this->zd) * 180 / PI; if (charge > 0) charge--; } - if (!level->isClientSide) - { + if (!level->isClientSide) { uint8_t old = entityData->getByte(DATA_IS_CHARGING); - uint8_t current = (uint8_t) (charge > 10 ? 1 : 0); - if (old != current) - { + uint8_t current = (uint8_t)(charge > 10 ? 1 : 0); + if (old != current) { entityData->set(DATA_IS_CHARGING, current); } } } -bool Ghast::canReach(double xt, double yt, double zt, double dist) -{ - double xd = (xTarget - x) / dist; - double yd = (yTarget - y) / dist; - double zd = (zTarget - z) / dist; +bool Ghast::canReach(double xt, double yt, double zt, double dist) { + double xd = (xTarget - x) / dist; + double yd = (yTarget - y) / dist; + double zd = (zTarget - z) / dist; - AABB *bb = this->bb->copy(); - for (int d = 1; d < dist; d++) - { - bb->move(xd, yd, zd); - if (!level->getCubes( shared_from_this(), bb)->empty()) return false; - } + AABB* bb = this->bb->copy(); + for (int d = 1; d < dist; d++) { + bb->move(xd, yd, zd); + if (!level->getCubes(shared_from_this(), bb)->empty()) return false; + } return true; } -int Ghast::getAmbientSound() -{ - return eSoundType_MOB_GHAST_MOAN; +int Ghast::getAmbientSound() { return eSoundType_MOB_GHAST_MOAN; } + +int Ghast::getHurtSound() { return eSoundType_MOB_GHAST_SCREAM; } + +int Ghast::getDeathSound() { return eSoundType_MOB_GHAST_DEATH; } + +int Ghast::getDeathLoot() { return Item::sulphur->id; } + +void Ghast::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int count = random->nextInt(2) + random->nextInt(1 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::ghastTear_Id, 1); + } + count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::sulphur_Id, 1); + } } -int Ghast::getHurtSound() -{ - return eSoundType_MOB_GHAST_SCREAM; +float Ghast::getSoundVolume() { + return 0.4f; // 10; 4J-PB - changing due to customer demands } -int Ghast::getDeathSound() -{ - return eSoundType_MOB_GHAST_DEATH; +bool Ghast::canSpawn() { + return (random->nextInt(20) == 0 && FlyingMob::canSpawn() && + level->difficulty > Difficulty::PEACEFUL); } -int Ghast::getDeathLoot() -{ - return Item::sulphur->id; -} - -void Ghast::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int count = random->nextInt(2) + random->nextInt(1 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::ghastTear_Id, 1); - } - count = random->nextInt(3) + random->nextInt(1 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::sulphur_Id, 1); - } -} - -float Ghast::getSoundVolume() -{ - return 0.4f;//10; 4J-PB - changing due to customer demands -} - -bool Ghast::canSpawn() -{ - return (random->nextInt(20) == 0 && FlyingMob::canSpawn() && level->difficulty > Difficulty::PEACEFUL); -} - -int Ghast::getMaxSpawnClusterSize() -{ - return 1; -} +int Ghast::getMaxSpawnClusterSize() { return 1; } diff --git a/Minecraft.World/Entities/Mobs/Ghast.h b/Minecraft.World/Entities/Mobs/Ghast.h index 9371572c1..ef00fa935 100644 --- a/Minecraft.World/Entities/Mobs/Ghast.h +++ b/Minecraft.World/Entities/Mobs/Ghast.h @@ -1,65 +1,63 @@ #pragma once - #include "../FlyingMob.h" #include "../Enemy.h" class GhastClass; class Level; -class Ghast : public FlyingMob, public Enemy -{ +class Ghast : public FlyingMob, public Enemy { public: - eINSTANCEOF GetType() { return eTYPE_GHAST; } - static Entity *create(Level *level) { return new Ghast(level); } + eINSTANCEOF GetType() { return eTYPE_GHAST; } + static Entity* create(Level* level) { return new Ghast(level); } private: - static const int DATA_IS_CHARGING = 16; + static const int DATA_IS_CHARGING = 16; public: - int floatDuration; + int floatDuration; double xTarget, yTarget, zTarget; -private: - std::shared_ptr target; +private: + std::shared_ptr target; int retargetTime; public: - int oCharge; + int oCharge; int charge; private: - void _init(); + void _init(); public: - Ghast(Level *level); + Ghast(Level* level); - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - int getMaxHealth(); + int getMaxHealth(); public: - virtual void tick(); + virtual void tick(); protected: - virtual void serverAiStep(); + virtual void serverAiStep(); private: - virtual bool canReach(double xt, double yt, double zt, double dist); + virtual bool canReach(double xt, double yt, double zt, double dist); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); virtual float getSoundVolume(); public: - virtual bool canSpawn(); + virtual bool canSpawn(); virtual int getMaxSpawnClusterSize(); }; diff --git a/Minecraft.World/Entities/Mobs/Giant.cpp b/Minecraft.World/Entities/Mobs/Giant.cpp index 307d6f6a2..415805739 100644 --- a/Minecraft.World/Entities/Mobs/Giant.cpp +++ b/Minecraft.World/Entities/Mobs/Giant.cpp @@ -3,30 +3,24 @@ #include "Giant.h" #include "../../../Minecraft.Client/Textures/Textures.h" +Giant::Giant(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Giant::Giant(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_ZOMBIE; // 4J was L"/mob/zombie.png"; - runSpeed = 0.5f; - attackDamage = 50; - this->heightOffset*=6; - this->setSize(bbWidth * 6, bbHeight * 6); + this->textureIdx = TN_MOB_ZOMBIE; // 4J was L"/mob/zombie.png"; + runSpeed = 0.5f; + attackDamage = 50; + this->heightOffset *= 6; + this->setSize(bbWidth * 6, bbHeight * 6); } -int Giant::getMaxHealth() -{ - return 100; -} +int Giant::getMaxHealth() { return 100; } -float Giant::getWalkTargetValue(int x, int y, int z) -{ - return level->getBrightness(x, y, z)-0.5f; +float Giant::getWalkTargetValue(int x, int y, int z) { + return level->getBrightness(x, y, z) - 0.5f; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Giant.h b/Minecraft.World/Entities/Mobs/Giant.h index 6743e616f..e0bad7012 100644 --- a/Minecraft.World/Entities/Mobs/Giant.h +++ b/Minecraft.World/Entities/Mobs/Giant.h @@ -1,18 +1,16 @@ #pragma once - #include "../Monster.h" class Level; -class Giant : public Monster -{ +class Giant : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_GIANT; } - static Entity *create(Level *level) { return new Giant(level); } + eINSTANCEOF GetType() { return eTYPE_GIANT; } + static Entity* create(Level* level) { return new Giant(level); } - Giant(Level *level); - - int getMaxHealth(); - virtual float getWalkTargetValue(int x, int y, int z); + Giant(Level* level); + + int getMaxHealth(); + virtual float getWalkTargetValue(int x, int y, int z); }; diff --git a/Minecraft.World/Entities/Mobs/Golem.cpp b/Minecraft.World/Entities/Mobs/Golem.cpp index f2efde840..92588af4b 100644 --- a/Minecraft.World/Entities/Mobs/Golem.cpp +++ b/Minecraft.World/Entities/Mobs/Golem.cpp @@ -2,38 +2,16 @@ #include "Golem.h" +Golem::Golem(Level* level) : PathfinderMob(level) {} +void Golem::causeFallDamage(float distance) {} -Golem::Golem(Level *level) : PathfinderMob(level) -{ -} +int Golem::getAmbientSound() { return -1; } +int Golem::getHurtSound() { return -1; } -void Golem::causeFallDamage(float distance) -{ -} +int Golem::getDeathSound() { return -1; } -int Golem::getAmbientSound() -{ - return -1; -} +int Golem::getAmbientSoundInterval() { return 20 * 6; } -int Golem::getHurtSound() -{ - return -1; -} - -int Golem::getDeathSound() -{ - return -1; -} - -int Golem::getAmbientSoundInterval() -{ - return 20 * 6; -} - -bool Golem::removeWhenFarAway() -{ - return false; -} \ No newline at end of file +bool Golem::removeWhenFarAway() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Golem.h b/Minecraft.World/Entities/Mobs/Golem.h index 7067ddd86..2ce7eaf77 100644 --- a/Minecraft.World/Entities/Mobs/Golem.h +++ b/Minecraft.World/Entities/Mobs/Golem.h @@ -6,20 +6,19 @@ class Level; class CompoundTag; -class Golem : public PathfinderMob, public Creature -{ +class Golem : public PathfinderMob, public Creature { public: - Golem(Level *level); + Golem(Level* level); protected: - virtual void causeFallDamage(float distance); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual void causeFallDamage(float distance); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - virtual int getAmbientSoundInterval(); + virtual int getAmbientSoundInterval(); protected: - virtual bool removeWhenFarAway(); + virtual bool removeWhenFarAway(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ItemFrame.cpp b/Minecraft.World/Entities/Mobs/ItemFrame.cpp index 8dcfed5aa..e3fa68c47 100644 --- a/Minecraft.World/Entities/Mobs/ItemFrame.cpp +++ b/Minecraft.World/Entities/Mobs/ItemFrame.cpp @@ -11,135 +11,111 @@ #include "../../Headers/com.mojang.nbt.h" #include "ItemFrame.h" - - - // 4J - added for common ctor code -void ItemFrame::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void ItemFrame::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -ItemFrame::ItemFrame(Level *level) : HangingEntity( level ) -{ - _init(); +ItemFrame::ItemFrame(Level* level) : HangingEntity(level) { _init(); } + +ItemFrame::ItemFrame(Level* level, int xTile, int yTile, int zTile, int dir) + : HangingEntity(level, xTile, yTile, zTile, dir) { + _init(); + setDir(dir); } -ItemFrame::ItemFrame(Level *level, int xTile, int yTile, int zTile, int dir) : HangingEntity( level, xTile, yTile, zTile, dir ) -{ - _init(); - setDir(dir); +void ItemFrame::defineSynchedData() { + getEntityData()->defineNULL(DATA_ITEM, NULL); + getEntityData()->define(DATA_ROTATION, (uint8_t)0); } -void ItemFrame::defineSynchedData() -{ - getEntityData()->defineNULL(DATA_ITEM, NULL); - getEntityData()->define(DATA_ROTATION, (uint8_t) 0); +void ItemFrame::dropItem() { + spawnAtLocation( + std::shared_ptr(new ItemInstance(Item::frame)), 0.0f); + std::shared_ptr item = getItem(); + if (item != NULL) { + std::shared_ptr data = + Item::map->getSavedData(item, level); + data->removeItemFrameDecoration(item); + + std::shared_ptr itemToDrop = item->copy(); + itemToDrop->setFramed(nullptr); + spawnAtLocation(itemToDrop, 0.0f); + } } -void ItemFrame::dropItem() -{ - spawnAtLocation(std::shared_ptr(new ItemInstance(Item::frame)), 0.0f); - std::shared_ptr item = getItem(); - if (item != NULL) - { - std::shared_ptr data = Item::map->getSavedData(item, level); - data->removeItemFrameDecoration(item); - - std::shared_ptr itemToDrop = item->copy(); - itemToDrop->setFramed(nullptr); - spawnAtLocation(itemToDrop, 0.0f); - } +std::shared_ptr ItemFrame::getItem() { + return getEntityData()->getItemInstance(DATA_ITEM); } -std::shared_ptr ItemFrame::getItem() -{ - return getEntityData()->getItemInstance(DATA_ITEM); +void ItemFrame::setItem(std::shared_ptr item) { + if (item != NULL) { + item = item->copy(); + item->count = 1; + + item->setFramed( + std::dynamic_pointer_cast(shared_from_this())); + } + getEntityData()->set(DATA_ITEM, item); + getEntityData()->markDirty(DATA_ITEM); } -void ItemFrame::setItem(std::shared_ptr item) -{ - if(item != NULL) - { - item = item->copy(); - item->count = 1; +int ItemFrame::getRotation() { return getEntityData()->getByte(DATA_ROTATION); } - item->setFramed(std::dynamic_pointer_cast( shared_from_this() )); - } - getEntityData()->set(DATA_ITEM, item); - getEntityData()->markDirty(DATA_ITEM); +void ItemFrame::setRotation(int rotation) { + getEntityData()->set(DATA_ROTATION, (uint8_t)(rotation % 4)); } -int ItemFrame::getRotation() -{ - return getEntityData()->getByte(DATA_ROTATION); +void ItemFrame::addAdditonalSaveData(CompoundTag* tag) { + if (getItem() != NULL) { + tag->putCompound(L"Item", getItem()->save(new CompoundTag())); + tag->putByte(L"ItemRotation", (uint8_t)getRotation()); + // tag->putFloat(L"ItemDropChance", dropChance); + } + HangingEntity::addAdditonalSaveData(tag); } -void ItemFrame::setRotation(int rotation) -{ - getEntityData()->set(DATA_ROTATION, (uint8_t) (rotation % 4)); +void ItemFrame::readAdditionalSaveData(CompoundTag* tag) { + CompoundTag* itemTag = tag->getCompound(L"Item"); + if (itemTag != NULL && !itemTag->isEmpty()) { + setItem(ItemInstance::fromTag(itemTag)); + setRotation(tag->getByte(L"ItemRotation")); + + // if (tag->contains(L"ItemDropChance")) dropChance = + // tag->getFloat(L"ItemDropChance"); + } + HangingEntity::readAdditionalSaveData(tag); } -void ItemFrame::addAdditonalSaveData(CompoundTag *tag) -{ - if (getItem() != NULL) - { - tag->putCompound(L"Item", getItem()->save(new CompoundTag())); - tag->putByte(L"ItemRotation", (uint8_t) getRotation()); - //tag->putFloat(L"ItemDropChance", dropChance); - } - HangingEntity::addAdditonalSaveData(tag); -} - -void ItemFrame::readAdditionalSaveData(CompoundTag *tag) -{ - CompoundTag *itemTag = tag->getCompound(L"Item"); - if (itemTag != NULL && !itemTag->isEmpty()) - { - setItem(ItemInstance::fromTag(itemTag)); - setRotation(tag->getByte(L"ItemRotation")); - - //if (tag->contains(L"ItemDropChance")) dropChance = tag->getFloat(L"ItemDropChance"); - } - HangingEntity::readAdditionalSaveData(tag); -} - -bool ItemFrame::interact(std::shared_ptr player) -{ - if(!player->isAllowedToInteract(shared_from_this())) - { - return false; - } - - if (getItem() == NULL) - { - std::shared_ptr item = player->getCarriedItem(); - - if (item != NULL) - { - if (!level->isClientSide)//isClientSide) - { - setItem(item); - - if (!player->abilities.instabuild) - { - if (--item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - } - } - } - else - { - if (!level->isClientSide)//isClientSide) - { - setRotation(getRotation() + 1); - } - } - - return true; +bool ItemFrame::interact(std::shared_ptr player) { + if (!player->isAllowedToInteract(shared_from_this())) { + return false; + } + + if (getItem() == NULL) { + std::shared_ptr item = player->getCarriedItem(); + + if (item != NULL) { + if (!level->isClientSide) // isClientSide) + { + setItem(item); + + if (!player->abilities.instabuild) { + if (--item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } + } + } + } + } else { + if (!level->isClientSide) // isClientSide) + { + setRotation(getRotation() + 1); + } + } + + return true; } diff --git a/Minecraft.World/Entities/Mobs/ItemFrame.h b/Minecraft.World/Entities/Mobs/ItemFrame.h index 6b4519aef..3f83b6e6f 100644 --- a/Minecraft.World/Entities/Mobs/ItemFrame.h +++ b/Minecraft.World/Entities/Mobs/ItemFrame.h @@ -5,37 +5,35 @@ class Level; -class ItemFrame : public HangingEntity -{ +class ItemFrame : public HangingEntity { public: - eINSTANCEOF GetType() { return eTYPE_ITEM_FRAME; }; - static Entity *create(Level *level) { return new ItemFrame(level); } -private: - static const int DATA_ITEM = 2; - static const int DATA_ROTATION = 3; + eINSTANCEOF GetType() { return eTYPE_ITEM_FRAME; }; + static Entity* create(Level* level) { return new ItemFrame(level); } private: + static const int DATA_ITEM = 2; + static const int DATA_ROTATION = 3; - void _init(); +private: + void _init(); public: - ItemFrame(Level *level); - ItemFrame(Level *level, int xTile, int yTile, int zTile, int dir); + ItemFrame(Level* level); + ItemFrame(Level* level, int xTile, int yTile, int zTile, int dir); protected: - virtual void defineSynchedData(); - virtual int getWidth() {return 9;} - virtual int getHeight() {return 9;} - virtual void dropItem(); + virtual void defineSynchedData(); + virtual int getWidth() { return 9; } + virtual int getHeight() { return 9; } + virtual void dropItem(); public: + std::shared_ptr getItem(); + void setItem(std::shared_ptr item); + int getRotation(); + void setRotation(int rotation); - std::shared_ptr getItem(); - void setItem(std::shared_ptr item); - int getRotation(); - void setRotation(int rotation); - - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual bool interact(std::shared_ptr player); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual bool interact(std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/LavaSlime.cpp b/Minecraft.World/Entities/Mobs/LavaSlime.cpp index d04e66f4e..143f64698 100644 --- a/Minecraft.World/Entities/Mobs/LavaSlime.cpp +++ b/Minecraft.World/Entities/Mobs/LavaSlime.cpp @@ -6,139 +6,91 @@ #include "LavaSlime.h" #include "../../Util/SoundTypes.h" +LavaSlime::LavaSlime(Level* level) : Slime(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called 4J Stu - The + // Slime ctor has already called this, and as we don't override it here + // don't need to call it + // this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -LavaSlime::LavaSlime(Level *level) : Slime(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - // 4J Stu - The Slime ctor has already called this, and as we don't override it here don't need to call it - //this->defineSynchedData(); - - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_LAVA; // 4J was "/mob/lava.png"; - fireImmune = true; - walkingSpeed = .2f; + this->textureIdx = TN_MOB_LAVA; // 4J was "/mob/lava.png"; + fireImmune = true; + walkingSpeed = .2f; } -bool LavaSlime::canSpawn() -{ - return level->difficulty > Difficulty::PEACEFUL && level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb); +bool LavaSlime::canSpawn() { + return level->difficulty > Difficulty::PEACEFUL && + level->isUnobstructed(bb) && + level->getCubes(shared_from_this(), bb)->empty() && + !level->containsAnyLiquid(bb); } -int LavaSlime::getArmorValue() -{ - return getSize() * 3; +int LavaSlime::getArmorValue() { return getSize() * 3; } + +int LavaSlime::getLightColor(float a) { return 15 << 20 | 15 << 4; } + +float LavaSlime::getBrightness(float a) { return 1.0f; } + +ePARTICLE_TYPE LavaSlime::getParticleName() { return eParticleType_flame; } + +std::shared_ptr LavaSlime::createChild() { + return std::shared_ptr(new LavaSlime(level)); } -int LavaSlime::getLightColor(float a) -{ - return 15 << 20 | 15 << 4; +int LavaSlime::getDeathLoot() { + // 4J-PB - brought forward the magma cream drops + return Item::magmaCream_Id; } -float LavaSlime::getBrightness(float a) -{ - return 1.0f; +void LavaSlime::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int loot = getDeathLoot(); + if (loot > 0 && getSize() > 1) { + int count = random->nextInt(4) - 2; + if (playerBonusLevel > 0) { + count += random->nextInt(playerBonusLevel + 1); + } + for (int i = 0; i < count; i++) { + spawnAtLocation(loot, 1); + } + } } -ePARTICLE_TYPE LavaSlime::getParticleName() -{ - return eParticleType_flame; +bool LavaSlime::isOnFire() { return false; } + +int LavaSlime::getJumpDelay() { return Slime::getJumpDelay() * 4; } + +void LavaSlime::decreaseSquish() { targetSquish = targetSquish * 0.90f; } + +void LavaSlime::jumpFromGround() { + yd = 0.42f + getSize() * .1f; + this->hasImpulse = true; } -std::shared_ptr LavaSlime::createChild() -{ - return std::shared_ptr( new LavaSlime(level) ); +void LavaSlime::causeFallDamage(float distance) {} + +bool LavaSlime::isDealsDamage() { return true; } + +int LavaSlime::getAttackDamage() { return Slime::getAttackDamage() + 2; } + +int LavaSlime::getHurtSound() { return eSoundType_MOB_SLIME; } + +int LavaSlime::getDeathSound() { return eSoundType_MOB_SLIME; } + +int LavaSlime::getSquishSound() { + if (getSize() > 1) { + return eSoundType_MOB_MAGMACUBE_BIG; + } + return eSoundType_MOB_MAGMACUBE_SMALL; } -int LavaSlime::getDeathLoot() -{ - // 4J-PB - brought forward the magma cream drops - return Item::magmaCream_Id; +bool LavaSlime::isInLava() { + // hack that makes the lava slimes move freely on the bottom of the lava + // oceans + return false; } -void LavaSlime::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int loot = getDeathLoot(); - if (loot > 0 && getSize() > 1) - { - int count = random->nextInt(4) - 2; - if (playerBonusLevel > 0) - { - count += random->nextInt(playerBonusLevel + 1); - } - for (int i = 0; i < count; i++) - { - spawnAtLocation(loot, 1); - } - } -} - -bool LavaSlime::isOnFire() -{ - return false; -} - - -int LavaSlime::getJumpDelay() -{ - return Slime::getJumpDelay() * 4; -} - -void LavaSlime::decreaseSquish() -{ - targetSquish = targetSquish * 0.90f; -} - -void LavaSlime::jumpFromGround() -{ - yd = 0.42f + getSize() * .1f; - this->hasImpulse = true; -} - -void LavaSlime::causeFallDamage(float distance) -{ -} - -bool LavaSlime::isDealsDamage() -{ - return true; -} - -int LavaSlime::getAttackDamage() -{ - return Slime::getAttackDamage() + 2; -} - -int LavaSlime::getHurtSound() -{ - return eSoundType_MOB_SLIME; -} - -int LavaSlime::getDeathSound() -{ - return eSoundType_MOB_SLIME; -} - -int LavaSlime::getSquishSound() -{ - if (getSize() > 1) - { - return eSoundType_MOB_MAGMACUBE_BIG; - } - return eSoundType_MOB_MAGMACUBE_SMALL; -} - -bool LavaSlime::isInLava() -{ - // hack that makes the lava slimes move freely on the bottom of the lava - // oceans - return false; -} - -bool LavaSlime::doPlayLandSound() -{ - return true; -} \ No newline at end of file +bool LavaSlime::doPlayLandSound() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/LavaSlime.h b/Minecraft.World/Entities/Mobs/LavaSlime.h index 8a2e5db9b..bb4ea66de 100644 --- a/Minecraft.World/Entities/Mobs/LavaSlime.h +++ b/Minecraft.World/Entities/Mobs/LavaSlime.h @@ -2,45 +2,44 @@ #include "Slime.h" -class LavaSlime : public Slime -{ +class LavaSlime : public Slime { public: - eINSTANCEOF GetType() { return eTYPE_LAVASLIME; } - static Entity *create(Level *level) { return new LavaSlime(level); } + eINSTANCEOF GetType() { return eTYPE_LAVASLIME; } + static Entity* create(Level* level) { return new LavaSlime(level); } public: - LavaSlime(Level *level); + LavaSlime(Level* level); - virtual bool canSpawn(); - virtual int getArmorValue(); + virtual bool canSpawn(); + virtual int getArmorValue(); public: - virtual int getLightColor(float a); - virtual float getBrightness(float a); + virtual int getLightColor(float a); + virtual float getBrightness(float a); protected: - virtual ePARTICLE_TYPE getParticleName(); - virtual std::shared_ptr createChild(); - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual ePARTICLE_TYPE getParticleName(); + virtual std::shared_ptr createChild(); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - bool isOnFire(); + bool isOnFire(); protected: - int getJumpDelay(); - virtual void decreaseSquish(); - virtual void jumpFromGround(); - virtual void causeFallDamage(float distance); - virtual bool isDealsDamage(); - virtual int getAttackDamage(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual int getSquishSound(); + int getJumpDelay(); + virtual void decreaseSquish(); + virtual void jumpFromGround(); + virtual void causeFallDamage(float distance); + virtual bool isDealsDamage(); + virtual int getAttackDamage(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual int getSquishSound(); public: - virtual bool isInLava(); + virtual bool isInLava(); protected: - virtual bool doPlayLandSound(); + virtual bool doPlayLandSound(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/LightningBolt.cpp b/Minecraft.World/Entities/Mobs/LightningBolt.cpp index 37c389f1e..3d6dd4b37 100644 --- a/Minecraft.World/Entities/Mobs/LightningBolt.cpp +++ b/Minecraft.World/Entities/Mobs/LightningBolt.cpp @@ -8,136 +8,127 @@ #include "../../../Minecraft.Client/Network/PlayerList.h" #include "../../Headers/net.minecraft.world.level.dimension.h" +LightningBolt::LightningBolt(Level* level, double x, double y, double z) + : life(0), seed(0), flashes(0), GlobalEntity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); -LightningBolt::LightningBolt(Level *level, double x, double y, double z) : - life( 0 ), - seed( 0 ), - flashes( 0 ), - GlobalEntity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + moveTo(x, y, z, 0, 0); + life = START_LIFE; + seed = random->nextLong(); + // 4J-PB - Microsoft request due to photosensitivity issue with multiple + // flashes of lightning + // flashes = random->nextInt(3) + 1; + flashes = 1; - moveTo(x, y, z, 0, 0); - life = START_LIFE; - seed = random->nextLong(); - // 4J-PB - Microsoft request due to photosensitivity issue with multiple flashes of lightning - //flashes = random->nextInt(3) + 1; - flashes = 1; + // 4J - added clientside check + if (!level->isClientSide) { + if (level->difficulty >= 2 && + level->hasChunksAt(Mth::floor(x), Mth::floor(y), Mth::floor(z), + 10)) { + { + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + // 4J added - don't go setting tiles if we aren't tracking them + // for network synchronisation + if (MinecraftServer::getInstance() + ->getPlayers() + ->isTrackingTile(xt, yt, zt, level->dimension->id)) { + if (level->getTile(xt, yt, zt) == 0 && + Tile::fire->mayPlace(level, xt, yt, zt)) + level->setTile(xt, yt, zt, Tile::fire_Id); + } + } - // 4J - added clientside check - if( !level->isClientSide ) - { - if (level->difficulty >= 2 && level->hasChunksAt( Mth::floor(x), Mth::floor(y), Mth::floor(z), 10)) - { - { - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - // 4J added - don't go setting tiles if we aren't tracking them for network synchronisation - if( MinecraftServer::getInstance()->getPlayers()->isTrackingTile(xt, yt, zt, level->dimension->id) ) - { - if (level->getTile(xt, yt, zt) == 0 && Tile::fire->mayPlace(level, xt, yt, zt)) level->setTile(xt, yt, zt, Tile::fire_Id); - } - } - - for (int i = 0; i < 4; i++) - { - int xt = Mth::floor(x) + random->nextInt(3) - 1; - int yt = Mth::floor(y) + random->nextInt(3) - 1; - int zt = Mth::floor(z) + random->nextInt(3) - 1; - // 4J added - don't go setting tiles if we aren't tracking them for network synchronisation - if( MinecraftServer::getInstance()->getPlayers()->isTrackingTile(xt, yt, zt, level->dimension->id) ) - { - if (level->getTile(xt, yt, zt) == 0 && Tile::fire->mayPlace(level, xt, yt, zt)) level->setTile(xt, yt, zt, Tile::fire_Id); - } - } - } - } + for (int i = 0; i < 4; i++) { + int xt = Mth::floor(x) + random->nextInt(3) - 1; + int yt = Mth::floor(y) + random->nextInt(3) - 1; + int zt = Mth::floor(z) + random->nextInt(3) - 1; + // 4J added - don't go setting tiles if we aren't tracking them + // for network synchronisation + if (MinecraftServer::getInstance() + ->getPlayers() + ->isTrackingTile(xt, yt, zt, level->dimension->id)) { + if (level->getTile(xt, yt, zt) == 0 && + Tile::fire->mayPlace(level, xt, yt, zt)) + level->setTile(xt, yt, zt, Tile::fire_Id); + } + } + } + } } -void LightningBolt::tick() -{ - GlobalEntity::tick(); +void LightningBolt::tick() { + GlobalEntity::tick(); - if (life == START_LIFE) { - // 4J-PB - this volume seems off the scale! But the volume is used to check the distance from the camera player - (volume*32) squared - // so we'll limit the sound in the sound engine - level->playSound(x, y, z, eSoundType_AMBIENT_WEATHER_THUNDER, 10000, 0.8f + random->nextFloat() * 0.2f); - level->playSound(x, y, z, eSoundType_RANDOM_EXPLODE, 2, 0.5f + random->nextFloat() * 0.2f); - } + if (life == START_LIFE) { + // 4J-PB - this volume seems off the scale! But the volume is used to + // check the distance from the camera player - (volume*32) squared so + // we'll limit the sound in the sound engine + level->playSound(x, y, z, eSoundType_AMBIENT_WEATHER_THUNDER, 10000, + 0.8f + random->nextFloat() * 0.2f); + level->playSound(x, y, z, eSoundType_RANDOM_EXPLODE, 2, + 0.5f + random->nextFloat() * 0.2f); + } - life--; - if (life < 0) - { - if (flashes == 0) - { - remove(); - } - else if (life < -random->nextInt(10)) - { - flashes--; - life = 1; - // 4J - added clientside check - if( !level->isClientSide ) - { - seed = random->nextLong(); - if (level->hasChunksAt( (int) floor(x), (int) floor(y), (int) floor(z), 10)) - { - int xt = (int) floor(x); - int yt = (int) floor(y); - int zt = (int) floor(z); + life--; + if (life < 0) { + if (flashes == 0) { + remove(); + } else if (life < -random->nextInt(10)) { + flashes--; + life = 1; + // 4J - added clientside check + if (!level->isClientSide) { + seed = random->nextLong(); + if (level->hasChunksAt((int)floor(x), (int)floor(y), + (int)floor(z), 10)) { + int xt = (int)floor(x); + int yt = (int)floor(y); + int zt = (int)floor(z); - // 4J added - don't go setting tiles if we aren't tracking them for network synchronisation - if( MinecraftServer::getInstance()->getPlayers()->isTrackingTile(xt, yt, zt, level->dimension->id) ) - { - if (level->getTile(xt, yt, zt) == 0 && Tile::fire->mayPlace(level, xt, yt, zt)) level->setTile(xt, yt, zt, Tile::fire_Id); - } - } - } - } - } + // 4J added - don't go setting tiles if we aren't tracking + // them for network synchronisation + if (MinecraftServer::getInstance() + ->getPlayers() + ->isTrackingTile(xt, yt, zt, + level->dimension->id)) { + if (level->getTile(xt, yt, zt) == 0 && + Tile::fire->mayPlace(level, xt, yt, zt)) + level->setTile(xt, yt, zt, Tile::fire_Id); + } + } + } + } + } - if (life >= 0) - { - double r = 3; - // 4J - added clientside check - if( !level->isClientSide ) - { - std::vector > *entities = level->getEntities(shared_from_this(), AABB::newTemp(x - r, y - r, z - r, x + r, y + 6 + r, z + r)); - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = (*it); //entities->at(i); - e->thunderHit(this); - } - } + if (life >= 0) { + double r = 3; + // 4J - added clientside check + if (!level->isClientSide) { + std::vector >* entities = + level->getEntities(shared_from_this(), + AABB::newTemp(x - r, y - r, z - r, x + r, + y + 6 + r, z + r)); + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = (*it); // entities->at(i); + e->thunderHit(this); + } + } - level->lightningBoltTime = 2; - } + level->lightningBoltTime = 2; + } } +void LightningBolt::defineSynchedData() {} -void LightningBolt::defineSynchedData() -{ -} +void LightningBolt::readAdditionalSaveData(CompoundTag* tag) {} -void LightningBolt::readAdditionalSaveData(CompoundTag *tag) -{ -} +void LightningBolt::addAdditonalSaveData(CompoundTag* tag) {} -void LightningBolt::addAdditonalSaveData(CompoundTag *tag) -{ -} +bool LightningBolt::shouldAlwaysRender() { return true; } - -bool LightningBolt::shouldAlwaysRender() -{ - return true; -} - -bool LightningBolt::shouldRender(Vec3 *c) -{ - return life >= 0; -} +bool LightningBolt::shouldRender(Vec3* c) { return life >= 0; } diff --git a/Minecraft.World/Entities/Mobs/LightningBolt.h b/Minecraft.World/Entities/Mobs/LightningBolt.h index 9868cfb0e..b80df6268 100644 --- a/Minecraft.World/Entities/Mobs/LightningBolt.h +++ b/Minecraft.World/Entities/Mobs/LightningBolt.h @@ -3,34 +3,32 @@ #include "../GlobalEntity.h" #include "../../Headers/net.minecraft.world.level.tile.h" - -//class LightningBolt : public GlobalEntity -class LightningBolt : public GlobalEntity -{ +// class LightningBolt : public GlobalEntity +class LightningBolt : public GlobalEntity { public: - eINSTANCEOF GetType() { return eTYPE_LIGHTNINGBOLT; } + eINSTANCEOF GetType() { return eTYPE_LIGHTNINGBOLT; } private: - static const int START_LIFE = 2; + static const int START_LIFE = 2; - int life; + int life; public: - __int64 seed; + __int64 seed; private: - int flashes; + int flashes; public: - LightningBolt(Level *level, double x, double y, double z); - virtual void tick(); + LightningBolt(Level* level, double x, double y, double z); + virtual void tick(); protected: - virtual void defineSynchedData(); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void addAdditonalSaveData(CompoundTag *tag); + virtual void defineSynchedData(); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void addAdditonalSaveData(CompoundTag* tag); public: - bool shouldAlwaysRender(); - virtual bool shouldRender(Vec3 *c); + bool shouldAlwaysRender(); + virtual bool shouldRender(Vec3* c); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Minecart.cpp b/Minecraft.World/Entities/Mobs/Minecart.cpp index 3ce618f12..e87abddc1 100644 --- a/Minecraft.World/Entities/Mobs/Minecart.cpp +++ b/Minecraft.World/Entities/Mobs/Minecart.cpp @@ -12,1198 +12,981 @@ #include "Minecart.h" #include "../../Util/SharedConstants.h" -const int Minecart::EXITS[][2][3] = { // - // - { - { - +0, +0, -1 - }, { - +0, +0, +1 - } - }, // 0 - { - { - -1, +0, +0 - }, { - +1, +0, +0 - } - }, // 1 - { - { - -1, -1, +0 - }, { - +1, +0, +0 - } - }, // 2 - { - { - -1, +0, +0 - }, { - +1, -1, +0 - } - }, // 3 - { - { - +0, +0, -1 - }, { - +0, -1, +1 - } - }, // 4 - { - { - +0, -1, -1 - }, { - +0, +0, +1 - } - }, // 5 +const int Minecart::EXITS[][2][3] = { + // + // + {{+0, +0, -1}, {+0, +0, +1}}, // 0 + {{-1, +0, +0}, {+1, +0, +0}}, // 1 + {{-1, -1, +0}, {+1, +0, +0}}, // 2 + {{-1, +0, +0}, {+1, -1, +0}}, // 3 + {{+0, +0, -1}, {+0, -1, +1}}, // 4 + {{+0, -1, -1}, {+0, +0, +1}}, // 5 - { - { - +0, +0, +1 - }, { - +1, +0, +0 - } - }, // 6 - { - { - +0, +0, +1 - }, { - -1, +0, +0 - } - }, // 7 - { - { - +0, +0, -1 - }, { - -1, +0, +0 - } - }, // 8 - { - { - +0, +0, -1 - }, { - +1, +0, +0 - } - }, // 9 + {{+0, +0, +1}, {+1, +0, +0}}, // 6 + {{+0, +0, +1}, {-1, +0, +0}}, // 7 + {{+0, +0, -1}, {-1, +0, +0}}, // 8 + {{+0, +0, -1}, {+1, +0, +0}}, // 9 }; -void Minecart::_init() -{ - // 4J TODO This gets replaced again later so should maybe be inited as NULL? - items = new ItemInstanceArray(9 * 4); +void Minecart::_init() { + // 4J TODO This gets replaced again later so should maybe be inited as NULL? + items = new ItemInstanceArray(9 * 4); - flipped = false; + flipped = false; - type = fuel = 0; - xPush = zPush = 0.0; + type = fuel = 0; + xPush = zPush = 0.0; - lSteps = 0; - lx = ly = lz = lyr = lxr = 0.0; - lxd = lyd = lzd = 0.0; + lSteps = 0; + lx = ly = lz = lyr = lxr = 0.0; + lxd = lyd = lzd = 0.0; - // Java default ctor - blocksBuilding = true; - setSize(0.98f, 0.7f); - heightOffset = bbHeight / 2.0f; - // + // Java default ctor + blocksBuilding = true; + setSize(0.98f, 0.7f); + heightOffset = bbHeight / 2.0f; + // - // 4J Added - m_bHasPushedCartThisTick = false; + // 4J Added + m_bHasPushedCartThisTick = false; } -Minecart::Minecart(Level *level) : Entity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Minecart::Minecart(Level* level) : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - _init(); + _init(); } +bool Minecart::makeStepSound() { return false; } -bool Minecart::makeStepSound() -{ - return false; +void Minecart::defineSynchedData() { + entityData->define(DATA_ID_FUEL, (uint8_t)0); + entityData->define(DATA_ID_HURT, 0); + entityData->define(DATA_ID_HURTDIR, 1); + entityData->define(DATA_ID_DAMAGE, 0); } -void Minecart::defineSynchedData() -{ - entityData->define(DATA_ID_FUEL, (uint8_t) 0); - entityData->define(DATA_ID_HURT, 0); - entityData->define(DATA_ID_HURTDIR, 1); - entityData->define(DATA_ID_DAMAGE, 0); +AABB* Minecart::getCollideAgainstBox(std::shared_ptr entity) { + return entity->bb; } - -AABB *Minecart::getCollideAgainstBox(std::shared_ptr entity) -{ - return entity->bb; +AABB* Minecart::getCollideBox() { + // if (level->isClientSide) return NULL; + return NULL; } -AABB *Minecart::getCollideBox() -{ - // if (level->isClientSide) return NULL; - return NULL; +bool Minecart::isPushable() { return true; } + +Minecart::Minecart(Level* level, double x, double y, double z, int type) + : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + + _init(); + setPos(x, y + heightOffset, z); + + xd = 0; + yd = 0; + zd = 0; + + xo = x; + yo = y; + zo = z; + this->type = type; } -bool Minecart::isPushable() -{ - return true; +double Minecart::getRideHeight() { return bbHeight * 0.0 - 0.3f; } + +bool Minecart::hurt(DamageSource* source, int hurtDamage) { + if (level->isClientSide || removed) return true; + + // 4J-JEV: Fix for #88212, + // Untrusted players shouldn't be able to damage minecarts or boats. + if (dynamic_cast(source) != NULL) { + std::shared_ptr attacker = source->getDirectEntity(); + + if (std::dynamic_pointer_cast(attacker) != NULL && + !std::dynamic_pointer_cast(attacker)->isAllowedToHurtEntity( + shared_from_this())) + return false; + } + + setHurtDir(-getHurtDir()); + setHurtTime(10); + markHurt(); + + // 4J Stu - If someone is riding in this, then it can tick multiple times + // which causes the damage to decrease too quickly. So just make the damage + // a bit higher to start with for similar behaviour to an unridden one. Only + // do this change if the riding player is attacking it. + if (rider.lock() != NULL && rider.lock() == source->getEntity()) + hurtDamage += 1; + + // 4J Stu - Brought froward from 12w36 to fix #46611 - TU5: Gameplay: + // Minecarts and boat requires more hits than one to be destroyed in + // creative mode + std::shared_ptr player = + std::dynamic_pointer_cast(source->getEntity()); + if (player != NULL && player->abilities.instabuild) this->setDamage(100); + + this->setDamage(getDamage() + (hurtDamage * 10)); + if (this->getDamage() > 20 * 2) { + // 4J HEG - Fixed issue with player falling through the ground on + // destroying a minecart while riding (issue #160607) + if (rider.lock() != NULL) rider.lock()->ride(nullptr); + remove(); + + spawnAtLocation(Item::minecart->id, 1, 0); + if (type == Minecart::CHEST) { + std::shared_ptr container = + std::dynamic_pointer_cast(shared_from_this()); + for (unsigned int i = 0; i < container->getContainerSize(); i++) { + std::shared_ptr item = container->getItem(i); + if (item != NULL) { + float xo = random->nextFloat() * 0.8f + 0.1f; + float yo = random->nextFloat() * 0.8f + 0.1f; + float zo = random->nextFloat() * 0.8f + 0.1f; + + while (item->count > 0) { + int count = random->nextInt(21) + 10; + if (count > item->count) count = item->count; + item->count -= count; + + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())))); + float pow = 0.05f; + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = + (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); + } + level->addEntity(itemEntity); + } + } + } + spawnAtLocation(Tile::chest_Id, 1, 0); + } else if (type == Minecart::FURNACE) { + spawnAtLocation(Tile::furnace_Id, 1, 0); + } + } + return true; } -Minecart::Minecart(Level *level, double x, double y, double z, int type) : Entity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - _init(); - setPos(x, y + heightOffset, z); - - xd = 0; - yd = 0; - zd = 0; - - xo = x; - yo = y; - zo = z; - this->type = type; +void Minecart::animateHurt() { + setHurtDir(-getHurtDir()); + setHurtTime(10); + this->setDamage(this->getDamage() + (getDamage() * 10)); } -double Minecart::getRideHeight() -{ - return bbHeight * 0.0 - 0.3f; +bool Minecart::isPickable() { return !removed; } + +void Minecart::remove() { + for (unsigned int i = 0; i < getContainerSize(); i++) { + std::shared_ptr item = getItem(i); + if (item != NULL) { + float xo = random->nextFloat() * 0.8f + 0.1f; + float yo = random->nextFloat() * 0.8f + 0.1f; + float zo = random->nextFloat() * 0.8f + 0.1f; + + while (item->count > 0) { + int count = random->nextInt(21) + 10; + if (count > item->count) count = item->count; + item->count -= count; + + std::shared_ptr itemEntity = + std::shared_ptr(new ItemEntity( + level, x + xo, y + yo, z + zo, + std::shared_ptr(new ItemInstance( + item->id, count, item->getAuxValue())))); + float pow = 0.05f; + itemEntity->xd = (float)random->nextGaussian() * pow; + itemEntity->yd = (float)random->nextGaussian() * pow + 0.2f; + itemEntity->zd = (float)random->nextGaussian() * pow; + if (item->hasTag()) { + itemEntity->getItem()->setTag( + (CompoundTag*)item->getTag()->copy()); + } + level->addEntity(itemEntity); + } + } + } + Entity::remove(); } -bool Minecart::hurt(DamageSource *source, int hurtDamage) -{ - if (level->isClientSide || removed) return true; - - // 4J-JEV: Fix for #88212, - // Untrusted players shouldn't be able to damage minecarts or boats. - if (dynamic_cast(source) != NULL) - { - std::shared_ptr attacker = source->getDirectEntity(); +void Minecart::tick() { + // 4J - make minecarts (server-side) tick twice, to put things back to how + // they were when we were accidently ticking them twice + for (int i = 0; i < 2; i++) { + if (getHurtTime() > 0) setHurtTime(getHurtTime() - 1); + if (getDamage() > 0) setDamage(getDamage() - 1); + if (y < -64) { + outOfWorld(); + } - if (std::dynamic_pointer_cast(attacker) != NULL && - !std::dynamic_pointer_cast(attacker)->isAllowedToHurtEntity( shared_from_this() )) - return false; - } + if (hasFuel() && random->nextInt(4) == 0) { + level->addParticle(eParticleType_largesmoke, x, y + 0.8, z, 0, 0, + 0); + } - setHurtDir(-getHurtDir()); - setHurtTime(10); - markHurt(); + // 4J Stu - Fix for #8284 - Gameplay: Collision: Minecart clips into/ + // through blocks at the end of the track, prevents player from riding + if (level->isClientSide) // && lSteps > 0) + { + if (lSteps > 0) { + double xt = x + (lx - x) / lSteps; + double yt = y + (ly - y) / lSteps; + double zt = z + (lz - z) / lSteps; - // 4J Stu - If someone is riding in this, then it can tick multiple times which causes the damage to - // decrease too quickly. So just make the damage a bit higher to start with for similar behaviour - // to an unridden one. Only do this change if the riding player is attacking it. - if( rider.lock() != NULL && rider.lock() == source->getEntity() ) hurtDamage += 1; + double yrd = Mth::wrapDegrees(lyr - yRot); - // 4J Stu - Brought froward from 12w36 to fix #46611 - TU5: Gameplay: Minecarts and boat requires more hits than one to be destroyed in creative mode - std::shared_ptr player = std::dynamic_pointer_cast(source->getEntity()); - if (player != NULL && player->abilities.instabuild) this->setDamage(100); + yRot += (float)((yrd) / lSteps); + xRot += (float)((lxr - xRot) / lSteps); - this->setDamage(getDamage() + (hurtDamage * 10)); - if (this->getDamage() > 20 * 2) - { - // 4J HEG - Fixed issue with player falling through the ground on destroying a minecart while riding (issue #160607) - if (rider.lock() != NULL) rider.lock()->ride(nullptr); - remove(); + lSteps--; + this->setPos(xt, yt, zt); + this->setRot(yRot, xRot); + } else { + this->setPos(x, y, z); + this->setRot(yRot, xRot); + } - spawnAtLocation(Item::minecart->id, 1, 0); - if (type == Minecart::CHEST) - { - std::shared_ptr container = std::dynamic_pointer_cast( shared_from_this() ); - for (unsigned int i = 0; i < container->getContainerSize(); i++) - { - std::shared_ptr item = container->getItem(i); - if (item != NULL) - { - float xo = random->nextFloat() * 0.8f + 0.1f; - float yo = random->nextFloat() * 0.8f + 0.1f; - float zo = random->nextFloat() * 0.8f + 0.1f; + return; // 4J - return here stops the client-side version of this + // from ticking twice + } + xo = x; + yo = y; + zo = z; - while (item->count > 0) - { - int count = random->nextInt(21) + 10; - if (count > item->count) count = item->count; - item->count -= count; + yd -= 0.04f; - std::shared_ptr itemEntity = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue()) ) ) ); - float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); - } - level->addEntity(itemEntity); - } - } - } - spawnAtLocation(Tile::chest_Id, 1, 0); - } - else if (type == Minecart::FURNACE) - { - spawnAtLocation(Tile::furnace_Id, 1, 0); - } - } - return true; + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + if (RailTile::isRail(level, xt, yt - 1, zt)) { + yt--; + } + + double max = 0.4; + + double slideSpeed = 1 / 128.0; + int tile = level->getTile(xt, yt, zt); + if (RailTile::isRail(tile)) { + Vec3* oldPos = getPos(x, y, z); + int data = level->getData(xt, yt, zt); + y = yt; + + bool powerTrack = false; + bool haltTrack = false; + if (tile == Tile::goldenRail_Id) { + powerTrack = (data & RailTile::RAIL_DATA_BIT) != 0; + haltTrack = !powerTrack; + } + if (((RailTile*)Tile::tiles[tile])->isUsesDataBit()) { + data &= RailTile::RAIL_DIRECTION_MASK; + } + + if (data >= 2 && data <= 5) { + y = yt + 1; + } + + if (data == 2) xd -= slideSpeed; + if (data == 3) xd += slideSpeed; + if (data == 4) zd += slideSpeed; + if (data == 5) zd -= slideSpeed; + + // 4J TODO Is this a good way to copy the bit of the array that we + // need? + int exits[2][3]; + memcpy(&exits, (void*)EXITS[data], sizeof(int) * 2 * 3); + // int exits[2][3] = EXITS[data]; + + double xD = exits[1][0] - exits[0][0]; + double zD = exits[1][2] - exits[0][2]; + double dd = sqrt(xD * xD + zD * zD); + + double flip = xd * xD + zd * zD; + if (flip < 0) { + xD = -xD; + zD = -zD; + } + + double pow = sqrt(xd * xd + zd * zd); + + xd = pow * xD / dd; + zd = pow * zD / dd; + + std::shared_ptr sharedRider = rider.lock(); + if (sharedRider != NULL) { + double riderDist = (sharedRider->xd * sharedRider->xd + + sharedRider->zd * sharedRider->zd); + double ownDist = xd * xd + zd * zd; + + if (riderDist > 0.0001 && ownDist < 0.01) { + xd += sharedRider->xd * 0.1; + zd += sharedRider->zd * 0.1; + + haltTrack = false; + } + } + + // on golden rails without power, stop the cart + if (haltTrack) { + double speedLength = sqrt(xd * xd + zd * zd); + if (speedLength < 0.03) { + xd *= 0; + yd *= 0; + zd *= 0; + } else { + xd *= 0.5f; + yd *= 0; + zd *= 0.5f; + } + } + + double progress = 0; + double x0 = xt + 0.5 + exits[0][0] * 0.5; + double z0 = zt + 0.5 + exits[0][2] * 0.5; + double x1 = xt + 0.5 + exits[1][0] * 0.5; + double z1 = zt + 0.5 + exits[1][2] * 0.5; + + xD = x1 - x0; + zD = z1 - z0; + + if (xD == 0) { + x = xt + 0.5; + progress = z - zt; + } else if (zD == 0) { + z = zt + 0.5; + progress = x - xt; + } else { + double xx = x - x0; + double zz = z - z0; + + progress = (xx * xD + zz * zD) * 2; + } + + x = x0 + xD * progress; + z = z0 + zD * progress; + + setPos(x, y + heightOffset, z); + + double xdd = xd; + double zdd = zd; + if (rider.lock() != NULL) { + xdd *= 0.75; + zdd *= 0.75; + } + if (xdd < -max) xdd = -max; + if (xdd > +max) xdd = +max; + if (zdd < -max) zdd = -max; + if (zdd > +max) zdd = +max; + move(xdd, 0, zdd); + + if (exits[0][1] != 0 && Mth::floor(x) - xt == exits[0][0] && + Mth::floor(z) - zt == exits[0][2]) { + setPos(x, y + exits[0][1], z); + } else if (exits[1][1] != 0 && Mth::floor(x) - xt == exits[1][0] && + Mth::floor(z) - zt == exits[1][2]) { + setPos(x, y + exits[1][1], z); + } else { + } + + if (rider.lock() != NULL) { + xd *= 0.997f; + yd *= 0; + zd *= 0.997f; + } else { + if (type == Minecart::FURNACE) { + double sd = xPush * xPush + zPush * zPush; + if (sd > 0.01 * 0.01) { + sd = sqrt(sd); + xPush /= sd; + zPush /= sd; + double speed = 0.04; + xd *= 0.8f; + yd *= 0; + zd *= 0.8f; + xd += xPush * speed; + zd += zPush * speed; + } else { + xd *= 0.9f; + yd *= 0; + zd *= 0.9f; + } + } + xd *= 0.96f; + yd *= 0; + zd *= 0.96f; + } + + Vec3* newPos = getPos(x, y, z); + if (newPos != NULL && oldPos != NULL) { + double speed = (oldPos->y - newPos->y) * 0.05; + + pow = sqrt(xd * xd + zd * zd); + if (pow > 0) { + xd = xd / pow * (pow + speed); + zd = zd / pow * (pow + speed); + } + setPos(x, newPos->y, z); + } + + int xn = Mth::floor(x); + int zn = Mth::floor(z); + if (xn != xt || zn != zt) { + pow = sqrt(xd * xd + zd * zd); + + xd = pow * (xn - xt); + zd = pow * (zn - zt); + } + + if (type == Minecart::FURNACE) { + double sd = xPush * xPush + zPush * zPush; + if (sd > 0.01 * 0.01 && xd * xd + zd * zd > 0.001) { + sd = sqrt(sd); + xPush /= sd; + zPush /= sd; + + if (xPush * xd + zPush * zd < 0) { + xPush = 0; + zPush = 0; + } else { + xPush = xd; + zPush = zd; + } + } + } + + // if on golden rail with power, increase speed + if (powerTrack) { + double speedLength = sqrt(xd * xd + zd * zd); + if (speedLength > .01) { + double speed = 0.06; + xd += xd / speedLength * speed; + zd += zd / speedLength * speed; + } else { + // if the minecart is standing still, accelerate it away + // from potentional walls + if (data == RailTile::DIR_FLAT_X) { + if (level->isSolidBlockingTile(xt - 1, yt, zt)) { + xd = .02; + } else if (level->isSolidBlockingTile(xt + 1, yt, zt)) { + xd = -.02; + } + } else if (data == RailTile::DIR_FLAT_Z) { + if (level->isSolidBlockingTile(xt, yt, zt - 1)) { + zd = .02; + } else if (level->isSolidBlockingTile(xt, yt, zt + 1)) { + zd = -.02; + } + } + } + } + + checkInsideTiles(); + } else { + if (xd < -max) xd = -max; + if (xd > +max) xd = +max; + if (zd < -max) zd = -max; + if (zd > +max) zd = +max; + if (onGround) { + xd *= 0.5f; + yd *= 0.5f; + zd *= 0.5f; + } + move(xd, yd, zd); + + if (onGround) { + } else { + xd *= 0.95f; + yd *= 0.95f; + zd *= 0.95f; + } + } + + xRot = 0; + double xDiff = xo - x; + double zDiff = zo - z; + if (xDiff * xDiff + zDiff * zDiff > 0.001) { + yRot = (float)(atan2(zDiff, xDiff) * 180 / PI); + if (flipped) yRot += 180; + } + + double rotDiff = Mth::wrapDegrees(yRot - yRotO); + + if (rotDiff < -170 || rotDiff >= 170) { + yRot += 180; + flipped = !flipped; + } + setRot(yRot, xRot); + + // if (!level->isClientSide) { + { + std::vector >* entities = + level->getEntities(shared_from_this(), + this->bb->grow(0.2f, 0, 0.2f)); + if (entities != NULL && !entities->empty()) { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = (*it); // entities->at(i); + if (e != rider.lock() && e->isPushable() && + e->GetType() == eTYPE_MINECART) { + std::shared_ptr cart = + std::dynamic_pointer_cast(e); + cart->m_bHasPushedCartThisTick = false; + cart->push(shared_from_this()); + + // 4J Added - We should only be pushed by one minecart + // per tick, the closest one Fix for #46937 - TU5: + // Gameplay: Crash/Freeze occurs when a minecart with an + // animal inside will be forced to despawn + if (cart->m_bHasPushedCartThisTick) break; + } + } + } + } + + if (rider.lock() != NULL) { + if (rider.lock()->removed) { + if (rider.lock()->riding == shared_from_this()) { + rider.lock()->riding = nullptr; + } + rider = std::weak_ptr(); + } + } + + if (fuel > 0) { + fuel--; + } + if (fuel <= 0) { + xPush = zPush = 0; + } + setHasFuel(fuel > 0); + } } -void Minecart::animateHurt() -{ - setHurtDir(-getHurtDir()); - setHurtTime(10); - this->setDamage(this->getDamage() + (getDamage() * 10)); +Vec3* Minecart::getPosOffs(double x, double y, double z, double offs) { + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + if (RailTile::isRail(level, xt, yt - 1, zt)) { + yt--; + } + + int tile = level->getTile(xt, yt, zt); + if (RailTile::isRail(tile)) { + int data = level->getData(xt, yt, zt); + + if (((RailTile*)Tile::tiles[tile])->isUsesDataBit()) { + data &= RailTile::RAIL_DIRECTION_MASK; + } + + y = yt; + if (data >= 2 && data <= 5) { + y = yt + 1; + } + + // 4J TODO Is this a good way to copy the bit of the array that we need? + int exits[2][3]; + memcpy(&exits, (void*)EXITS[data], sizeof(int) * 2 * 3); + // int exits[2][3] = EXITS[data]; + + double xD = exits[1][0] - exits[0][0]; + double zD = exits[1][2] - exits[0][2]; + double dd = sqrt(xD * xD + zD * zD); + xD /= dd; + zD /= dd; + + x += xD * offs; + z += zD * offs; + + if (exits[0][1] != 0 && Mth::floor(x) - xt == exits[0][0] && + Mth::floor(z) - zt == exits[0][2]) { + y += exits[0][1]; + } else if (exits[1][1] != 0 && Mth::floor(x) - xt == exits[1][0] && + Mth::floor(z) - zt == exits[1][2]) { + y += exits[1][1]; + } else { + } + + return getPos(x, y, z); + } + return NULL; } -bool Minecart::isPickable() -{ - return !removed; +Vec3* Minecart::getPos(double x, double y, double z) { + int xt = Mth::floor(x); + int yt = Mth::floor(y); + int zt = Mth::floor(z); + if (RailTile::isRail(level, xt, yt - 1, zt)) { + yt--; + } + + int tile = level->getTile(xt, yt, zt); + if (RailTile::isRail(tile)) { + int data = level->getData(xt, yt, zt); + y = yt; + + if (((RailTile*)Tile::tiles[tile])->isUsesDataBit()) { + data &= RailTile::RAIL_DIRECTION_MASK; + } + + if (data >= 2 && data <= 5) { + y = yt + 1; + } + + // 4J TODO Is this a good way to copy the bit of the array that we need? + int exits[2][3]; + memcpy(&exits, (void*)EXITS[data], sizeof(int) * 2 * 3); + // int exits[2][3] = EXITS[data]; + + double progress = 0; + double x0 = xt + 0.5 + exits[0][0] * 0.5; + double y0 = yt + 0.5 + exits[0][1] * 0.5; + double z0 = zt + 0.5 + exits[0][2] * 0.5; + double x1 = xt + 0.5 + exits[1][0] * 0.5; + double y1 = yt + 0.5 + exits[1][1] * 0.5; + double z1 = zt + 0.5 + exits[1][2] * 0.5; + + double xD = x1 - x0; + double yD = (y1 - y0) * 2; + double zD = z1 - z0; + + if (xD == 0) { + x = xt + 0.5; + progress = z - zt; + } else if (zD == 0) { + z = zt + 0.5; + progress = x - xt; + } else { + double xx = x - x0; + double zz = z - z0; + + progress = (xx * xD + zz * zD) * 2; + } + + x = x0 + xD * progress; + y = y0 + yD * progress; + z = z0 + zD * progress; + if (yD < 0) y += 1; + if (yD > 0) y += 0.5; + return Vec3::newTemp(x, y, z); + } + return NULL; } -void Minecart::remove() -{ - for (unsigned int i = 0; i < getContainerSize(); i++) - { - std::shared_ptr item = getItem(i); - if (item != NULL) - { - float xo = random->nextFloat() * 0.8f + 0.1f; - float yo = random->nextFloat() * 0.8f + 0.1f; - float zo = random->nextFloat() * 0.8f + 0.1f; +void Minecart::addAdditonalSaveData(CompoundTag* base) { + base->putInt(L"Type", type); - while (item->count > 0) - { - int count = random->nextInt(21) + 10; - if (count > item->count) count = item->count; - item->count -= count; + if (type == Minecart::FURNACE) { + base->putDouble(L"PushX", xPush); + base->putDouble(L"PushZ", zPush); + base->putShort(L"Fuel", (short)fuel); + } else if (type == Minecart::CHEST) { + ListTag* listTag = new ListTag(); - std::shared_ptr itemEntity = std::shared_ptr( new ItemEntity(level, x + xo, y + yo, z + zo, std::shared_ptr( new ItemInstance(item->id, count, item->getAuxValue()) ) ) ); - float pow = 0.05f; - itemEntity->xd = (float) random->nextGaussian() * pow; - itemEntity->yd = (float) random->nextGaussian() * pow + 0.2f; - itemEntity->zd = (float) random->nextGaussian() * pow; - if (item->hasTag()) - { - itemEntity->getItem()->setTag((CompoundTag *) item->getTag()->copy()); - } - level->addEntity(itemEntity); - } - } - } - Entity::remove(); + for (unsigned int i = 0; i < items->length; i++) { + if ((*items)[i] != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + (*items)[i]->save(tag); + listTag->add(tag); + } + } + base->put(L"Items", listTag); + } } - -void Minecart::tick() -{ - // 4J - make minecarts (server-side) tick twice, to put things back to how they were when we were accidently ticking them twice - for( int i = 0; i < 2; i++ ) - { - if (getHurtTime() > 0) setHurtTime(getHurtTime() - 1); - if (getDamage() > 0) setDamage(getDamage() - 1); - if(y < -64) - { - outOfWorld(); - } - - if (hasFuel() && random->nextInt(4) == 0) - { - level->addParticle(eParticleType_largesmoke, x, y + 0.8, z, 0, 0, 0); - } - - // 4J Stu - Fix for #8284 - Gameplay: Collision: Minecart clips into/ through blocks at the end of the track, prevents player from riding - if (level->isClientSide) // && lSteps > 0) - { - if (lSteps > 0) - { - double xt = x + (lx - x) / lSteps; - double yt = y + (ly - y) / lSteps; - double zt = z + (lz - z) / lSteps; - - double yrd = Mth::wrapDegrees(lyr - yRot); - - yRot += (float) ( (yrd) / lSteps ); - xRot += (float) ( (lxr - xRot) / lSteps ); - - lSteps--; - this->setPos(xt, yt, zt); - this->setRot(yRot, xRot); - } - else - { - this->setPos(x, y, z); - this->setRot(yRot, xRot); - } - - return; // 4J - return here stops the client-side version of this from ticking twice - } - xo = x; - yo = y; - zo = z; - - yd -= 0.04f; - - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - if (RailTile::isRail(level, xt, yt - 1, zt)) - { - yt--; - } - - double max = 0.4; - - double slideSpeed = 1 / 128.0; - int tile = level->getTile(xt, yt, zt); - if (RailTile::isRail(tile)) - { - Vec3 *oldPos = getPos(x, y, z); - int data = level->getData(xt, yt, zt); - y = yt; - - bool powerTrack = false; - bool haltTrack = false; - if (tile == Tile::goldenRail_Id) - { - powerTrack = (data & RailTile::RAIL_DATA_BIT) != 0; - haltTrack = !powerTrack; - } - if (((RailTile *) Tile::tiles[tile])->isUsesDataBit()) - { - data &= RailTile::RAIL_DIRECTION_MASK; - } - - if (data >= 2 && data <= 5) - { - y = yt + 1; - } - - if (data == 2) xd -= slideSpeed; - if (data == 3) xd += slideSpeed; - if (data == 4) zd += slideSpeed; - if (data == 5) zd -= slideSpeed; - - // 4J TODO Is this a good way to copy the bit of the array that we need? - int exits[2][3]; - memcpy( &exits, (void *)EXITS[data], sizeof(int) * 2 * 3); - //int exits[2][3] = EXITS[data]; - - double xD = exits[1][0] - exits[0][0]; - double zD = exits[1][2] - exits[0][2]; - double dd = sqrt(xD * xD + zD * zD); - - double flip = xd * xD + zd * zD; - if (flip < 0) - { - xD = -xD; - zD = -zD; - } - - double pow = sqrt(xd * xd + zd * zd); - - xd = pow * xD / dd; - zd = pow * zD / dd; - - std::shared_ptr sharedRider = rider.lock(); - if (sharedRider != NULL) - { - double riderDist = (sharedRider->xd * sharedRider->xd + sharedRider->zd * sharedRider->zd); - double ownDist = xd * xd + zd * zd; - - if (riderDist > 0.0001 && ownDist < 0.01) - { - xd += sharedRider->xd * 0.1; - zd += sharedRider->zd * 0.1; - - haltTrack = false; - } - } - - // on golden rails without power, stop the cart - if (haltTrack) - { - double speedLength = sqrt(xd * xd + zd * zd); - if (speedLength < 0.03) - { - xd *= 0; - yd *= 0; - zd *= 0; - } - else - { - xd *= 0.5f; - yd *= 0; - zd *= 0.5f; - } - } - - double progress = 0; - double x0 = xt + 0.5 + exits[0][0] * 0.5; - double z0 = zt + 0.5 + exits[0][2] * 0.5; - double x1 = xt + 0.5 + exits[1][0] * 0.5; - double z1 = zt + 0.5 + exits[1][2] * 0.5; - - xD = x1 - x0; - zD = z1 - z0; - - if (xD == 0) - { - x = xt + 0.5; - progress = z - zt; - } - else if (zD == 0) - { - z = zt + 0.5; - progress = x - xt; - } - else - { - - double xx = x - x0; - double zz = z - z0; - - progress = (xx * xD + zz * zD) * 2; - } - - x = x0 + xD * progress; - z = z0 + zD * progress; - - setPos(x, y + heightOffset, z); - - double xdd = xd; - double zdd = zd; - if (rider.lock() != NULL) - { - xdd *= 0.75; - zdd *= 0.75; - } - if (xdd < -max) xdd = -max; - if (xdd > +max) xdd = +max; - if (zdd < -max) zdd = -max; - if (zdd > +max) zdd = +max; - move(xdd, 0, zdd); - - if (exits[0][1] != 0 && Mth::floor(x) - xt == exits[0][0] && Mth::floor(z) - zt == exits[0][2]) - { - setPos(x, y + exits[0][1], z); - } - else if (exits[1][1] != 0 && Mth::floor(x) - xt == exits[1][0] && Mth::floor(z) - zt == exits[1][2]) - { - setPos(x, y + exits[1][1], z); - } - else - { - } - - if (rider.lock() != NULL) - { - xd *= 0.997f; - yd *= 0; - zd *= 0.997f; - } - else - { - if (type == Minecart::FURNACE) - { - double sd = xPush * xPush + zPush * zPush; - if (sd > 0.01 * 0.01) - { - sd = sqrt(sd); - xPush /= sd; - zPush /= sd; - double speed = 0.04; - xd *= 0.8f; - yd *= 0; - zd *= 0.8f; - xd += xPush * speed; - zd += zPush * speed; - } - else - { - xd *= 0.9f; - yd *= 0; - zd *= 0.9f; - } - } - xd *= 0.96f; - yd *= 0; - zd *= 0.96f; - - } - - Vec3 *newPos = getPos(x, y, z); - if (newPos != NULL && oldPos != NULL) - { - double speed = (oldPos->y - newPos->y) * 0.05; - - pow = sqrt(xd * xd + zd * zd); - if (pow > 0) - { - xd = xd / pow * (pow + speed); - zd = zd / pow * (pow + speed); - } - setPos(x, newPos->y, z); - } - - int xn = Mth::floor(x); - int zn = Mth::floor(z); - if (xn != xt || zn != zt) - { - pow = sqrt(xd * xd + zd * zd); - - xd = pow * (xn - xt); - zd = pow * (zn - zt); - } - - if (type == Minecart::FURNACE) - { - double sd = xPush * xPush + zPush * zPush; - if (sd > 0.01 * 0.01 && xd * xd + zd * zd > 0.001) - { - sd = sqrt(sd); - xPush /= sd; - zPush /= sd; - - if (xPush * xd + zPush * zd < 0) - { - xPush = 0; - zPush = 0; - } - else - { - xPush = xd; - zPush = zd; - } - } - } - - // if on golden rail with power, increase speed - if (powerTrack) - { - double speedLength = sqrt(xd * xd + zd * zd); - if (speedLength > .01) - { - double speed = 0.06; - xd += xd / speedLength * speed; - zd += zd / speedLength * speed; - } - else - { - // if the minecart is standing still, accelerate it away - // from potentional walls - if (data == RailTile::DIR_FLAT_X) - { - if (level->isSolidBlockingTile(xt - 1, yt, zt)) - { - xd = .02; - } - else if (level->isSolidBlockingTile(xt + 1, yt, zt)) - { - xd = -.02; - } - } - else if (data == RailTile::DIR_FLAT_Z) - { - if (level->isSolidBlockingTile(xt, yt, zt - 1)) - { - zd = .02; - } - else if (level->isSolidBlockingTile(xt, yt, zt + 1)) - { - zd = -.02; - } - } - } - } - - checkInsideTiles(); - } - else - { - if (xd < -max) xd = -max; - if (xd > +max) xd = +max; - if (zd < -max) zd = -max; - if (zd > +max) zd = +max; - if (onGround) - { - xd *= 0.5f; - yd *= 0.5f; - zd *= 0.5f; - } - move(xd, yd, zd); - - if (onGround) - { - } - else - { - xd *= 0.95f; - yd *= 0.95f; - zd *= 0.95f; - } - } - - xRot = 0; - double xDiff = xo - x; - double zDiff = zo - z; - if (xDiff * xDiff + zDiff * zDiff > 0.001) - { - yRot = (float) (atan2(zDiff, xDiff) * 180 / PI); - if (flipped) yRot += 180; - } - - double rotDiff = Mth::wrapDegrees(yRot - yRotO); - - if (rotDiff < -170 || rotDiff >= 170) - { - yRot += 180; - flipped = !flipped; - } - setRot(yRot, xRot); - - // if (!level->isClientSide) { - { - std::vector > *entities = level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) - { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = (*it); //entities->at(i); - if (e != rider.lock() && e->isPushable() && e->GetType() == eTYPE_MINECART) - { - std::shared_ptr cart = std::dynamic_pointer_cast(e); - cart->m_bHasPushedCartThisTick = false; - cart->push(shared_from_this()); - - // 4J Added - We should only be pushed by one minecart per tick, the closest one - // Fix for #46937 - TU5: Gameplay: Crash/Freeze occurs when a minecart with an animal inside will be forced to despawn - if( cart->m_bHasPushedCartThisTick ) break; - } - } - } - } - - if (rider.lock() != NULL) - { - if (rider.lock()->removed) - { - if (rider.lock()->riding == shared_from_this()) - { - rider.lock()->riding = nullptr; - } - rider = std::weak_ptr(); - } - } - - if (fuel > 0) - { - fuel--; - } - if (fuel <= 0) - { - xPush = zPush = 0; - } - setHasFuel(fuel > 0); - } +void Minecart::readAdditionalSaveData(CompoundTag* base) { + type = base->getInt(L"Type"); + if (type == Minecart::FURNACE) { + xPush = base->getDouble(L"PushX"); + zPush = base->getDouble(L"PushZ"); + fuel = base->getShort(L"Fuel"); + } else if (type == Minecart::CHEST) { + ListTag* inventoryList = + (ListTag*)base->getList(L"Items"); + items = new ItemInstanceArray(getContainerSize()); + for (int i = 0; i < inventoryList->size(); i++) { + CompoundTag* tag = inventoryList->get(i); + unsigned int slot = tag->getByte(L"Slot") & 0xff; + if (slot >= 0 && slot < items->length) + (*items)[slot] = + std::shared_ptr(ItemInstance::fromTag(tag)); + } + } } -Vec3 *Minecart::getPosOffs(double x, double y, double z, double offs) -{ - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - if (RailTile::isRail(level, xt, yt - 1, zt)) - { - yt--; - } +float Minecart::getShadowHeightOffs() { return 0; } - int tile = level->getTile(xt, yt, zt); - if (RailTile::isRail(tile)) - { - int data = level->getData(xt, yt, zt); +void Minecart::push(std::shared_ptr e) { + if (level->isClientSide) return; - if (((RailTile *) Tile::tiles[tile])->isUsesDataBit()) - { - data &= RailTile::RAIL_DIRECTION_MASK; - } + if (e == rider.lock()) return; + if ((std::dynamic_pointer_cast(e) != NULL) && + std::dynamic_pointer_cast(e) == NULL && + std::dynamic_pointer_cast(e) == NULL && + type == Minecart::RIDEABLE && xd * xd + zd * zd > 0.01) { + if (rider.lock() == NULL && e->riding == NULL) { + e->ride(shared_from_this()); + } + } - y = yt; - if (data >= 2 && data <= 5) - { - y = yt + 1; - } + double xa = e->x - x; + double za = e->z - z; - // 4J TODO Is this a good way to copy the bit of the array that we need? - int exits[2][3]; - memcpy( &exits, (void *)EXITS[data], sizeof(int) * 2 * 3); - //int exits[2][3] = EXITS[data]; + double dd = xa * xa + za * za; + if (dd >= 0.0001f) { + dd = sqrt(dd); + xa /= dd; + za /= dd; + double pow = 1 / dd; + if (pow > 1) pow = 1; + xa *= pow; + za *= pow; + xa *= 0.1f; + za *= 0.1f; - double xD = exits[1][0] - exits[0][0]; - double zD = exits[1][2] - exits[0][2]; - double dd = sqrt(xD * xD + zD * zD); - xD /= dd; - zD /= dd; + xa *= 1 - pushthrough; + za *= 1 - pushthrough; + xa *= 0.5; + za *= 0.5; - x += xD * offs; - z += zD * offs; + if (e->GetType() == eTYPE_MINECART) { + double xo = e->x - x; + double zo = e->z - z; - if (exits[0][1] != 0 && Mth::floor(x) - xt == exits[0][0] && Mth::floor(z) - zt == exits[0][2]) - { - y += exits[0][1]; - } - else if (exits[1][1] != 0 && Mth::floor(x) - xt == exits[1][0] && Mth::floor(z) - zt == exits[1][2]) - { - y += exits[1][1]; - } - else - { - } + // 4J Stu - Brought forward changes to fix minecarts pushing each + // other + // Fix for #38882 - TU5: Gameplay: Minecart with furnace is not + // able to move another minecart on the rail. + Vec3* dir = Vec3::newTemp(xo, 0, zo)->normalize(); + Vec3* facing = + Vec3::newTemp(cos(yRot * PI / 180), 0, sin(yRot * PI / 180)) + ->normalize(); - return getPos(x, y, z); - } - return NULL; + double dot = abs(dir->dot(facing)); + + if (dot < 0.8f) { + return; + } + + double xdd = (e->xd + xd); + double zdd = (e->zd + zd); + + std::shared_ptr cart = + std::dynamic_pointer_cast(e); + if (cart != NULL && cart->type == Minecart::FURNACE && + type != Minecart::FURNACE) { + xd *= 0.2f; + zd *= 0.2f; + this->Entity::push(e->xd - xa, 0, e->zd - za); + e->xd *= 0.95f; + e->zd *= 0.95f; + m_bHasPushedCartThisTick = true; + } else if (cart != NULL && cart->type != Minecart::FURNACE && + type == Minecart::FURNACE) { + e->xd *= 0.2f; + e->zd *= 0.2f; + e->push(xd + xa, 0, zd + za); + xd *= 0.95f; + zd *= 0.95f; + m_bHasPushedCartThisTick = true; + } else { + xdd /= 2; + zdd /= 2; + xd *= 0.2f; + zd *= 0.2f; + this->Entity::push(xdd - xa, 0, zdd - za); + e->xd *= 0.2f; + e->zd *= 0.2f; + e->push(xdd + xa, 0, zdd + za); + m_bHasPushedCartThisTick = true; + + // 4J Stu - Fix for #46937 - TU5: Gameplay: Crash/Freeze occurs + // when a minecart with an animal inside will be forced to + // despawn Minecarts can end up stuck inside each other, so if + // they are too close then they should separate quickly + double modifier = 1.0; + if (abs(xo) < 1 && abs(zo) < 1) { + modifier += 1 - ((abs(xo) + abs(zo)) / 2); + } + // 4J Stu - Decelerate the cart that is pushing this one if they + // are too close + e->xd /= modifier; + e->zd /= modifier; + + // 4J Backup fix for QNAN + if (!(xd == xd)) xd = 0; + if (!(zd == zd)) zd = 0; + if (!(e->xd == e->xd)) e->xd = 0; + if (!(e->zd == e->zd)) e->zd = 0; + } + + } else { + this->Entity::push(-xa, 0, -za); + e->push(xa / 4, 0, za / 4); + } + } } -Vec3 *Minecart::getPos(double x, double y, double z) -{ - int xt = Mth::floor(x); - int yt = Mth::floor(y); - int zt = Mth::floor(z); - if (RailTile::isRail(level, xt, yt - 1, zt)) - { - yt--; - } +unsigned int Minecart::getContainerSize() { return 9 * 3; } - int tile = level->getTile(xt, yt, zt); - if (RailTile::isRail(tile)) - { - int data = level->getData(xt, yt, zt); - y = yt; - - if (((RailTile *) Tile::tiles[tile])->isUsesDataBit()) - { - data &= RailTile::RAIL_DIRECTION_MASK; - } - - if (data >= 2 && data <= 5) - { - y = yt + 1; - } - - // 4J TODO Is this a good way to copy the bit of the array that we need? - int exits[2][3]; - memcpy( &exits, (void *)EXITS[data], sizeof(int) * 2 * 3); - //int exits[2][3] = EXITS[data]; - - double progress = 0; - double x0 = xt + 0.5 + exits[0][0] * 0.5; - double y0 = yt + 0.5 + exits[0][1] * 0.5; - double z0 = zt + 0.5 + exits[0][2] * 0.5; - double x1 = xt + 0.5 + exits[1][0] * 0.5; - double y1 = yt + 0.5 + exits[1][1] * 0.5; - double z1 = zt + 0.5 + exits[1][2] * 0.5; - - double xD = x1 - x0; - double yD = (y1 - y0) * 2; - double zD = z1 - z0; - - if (xD == 0) - { - x = xt + 0.5; - progress = z - zt; - } - else if (zD == 0) - { - z = zt + 0.5; - progress = x - xt; - } - else - { - - double xx = x - x0; - double zz = z - z0; - - progress = (xx * xD + zz * zD) * 2; - } - - x = x0 + xD * progress; - y = y0 + yD * progress; - z = z0 + zD * progress; - if (yD < 0) y += 1; - if (yD > 0) y += 0.5; - return Vec3::newTemp(x, y, z); - } - return NULL; +std::shared_ptr Minecart::getItem(unsigned int slot) { + return (*items)[slot]; } - -void Minecart::addAdditonalSaveData(CompoundTag *base) -{ - base->putInt(L"Type", type); - - if (type == Minecart::FURNACE) - { - base->putDouble(L"PushX", xPush); - base->putDouble(L"PushZ", zPush); - base->putShort(L"Fuel", (short) fuel); - } - else if (type == Minecart::CHEST) - { - ListTag *listTag = new ListTag(); - - for (unsigned int i = 0; i < items->length; i++) - { - if ( (*items)[i] != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - (*items)[i]->save(tag); - listTag->add(tag); - } - } - base->put(L"Items", listTag); - } +std::shared_ptr Minecart::removeItem(unsigned int slot, + int count) { + if ((*items)[slot] != NULL) { + if ((*items)[slot]->count <= count) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + return item; + } else { + std::shared_ptr i = (*items)[slot]->remove(count); + if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; + return i; + } + } + return nullptr; } -void Minecart::readAdditionalSaveData(CompoundTag *base) -{ - type = base->getInt(L"Type"); - if (type == Minecart::FURNACE) - { - xPush = base->getDouble(L"PushX"); - zPush = base->getDouble(L"PushZ"); - fuel = base->getShort(L"Fuel"); - } - else if (type == Minecart::CHEST) - { - ListTag *inventoryList = (ListTag *) base->getList(L"Items"); - items = new ItemInstanceArray( getContainerSize() ); - for (int i = 0; i < inventoryList->size(); i++) - { - CompoundTag *tag = inventoryList->get(i); - unsigned int slot = tag->getByte(L"Slot") & 0xff; - if (slot >= 0 && slot < items->length) (*items)[slot] = std::shared_ptr( ItemInstance::fromTag(tag) ); - } - } +std::shared_ptr Minecart::removeItemNoUpdate(int slot) { + if ((*items)[slot] != NULL) { + std::shared_ptr item = (*items)[slot]; + (*items)[slot] = nullptr; + return item; + } + return nullptr; } - -float Minecart::getShadowHeightOffs() -{ - return 0; +void Minecart::setItem(unsigned int slot, std::shared_ptr item) { + (*items)[slot] = item; + if (item != NULL && item->count > getMaxStackSize()) + item->count = getMaxStackSize(); } -void Minecart::push(std::shared_ptr e) -{ - if (level->isClientSide) return; +int Minecart::getName() { return IDS_ITEM_MINECART; } - if (e == rider.lock()) return; - if (( std::dynamic_pointer_cast(e)!=NULL) && std::dynamic_pointer_cast(e)==NULL && std::dynamic_pointer_cast(e) == NULL && type == Minecart::RIDEABLE && xd * xd + zd * zd > 0.01) - { - if (rider.lock() == NULL && e->riding == NULL) - { - e->ride( shared_from_this() ); - } - } +int Minecart::getMaxStackSize() { return Container::LARGE_MAX_STACK_SIZE; } - double xa = e->x - x; - double za = e->z - z; +void Minecart::setChanged() {} - double dd = xa * xa + za * za; - if (dd >= 0.0001f) - { - dd = sqrt(dd); - xa /= dd; - za /= dd; - double pow = 1 / dd; - if (pow > 1) pow = 1; - xa *= pow; - za *= pow; - xa *= 0.1f; - za *= 0.1f; - - xa *= 1 - pushthrough; - za *= 1 - pushthrough; - xa *= 0.5; - za *= 0.5; - - if (e->GetType() == eTYPE_MINECART) - { - double xo = e->x - x; - double zo = e->z - z; - - //4J Stu - Brought forward changes to fix minecarts pushing each other - // Fix for #38882 - TU5: Gameplay: Minecart with furnace is not able to move another minecart on the rail. - Vec3 *dir = Vec3::newTemp(xo, 0, zo)->normalize(); - Vec3 *facing = Vec3::newTemp(cos(yRot * PI / 180), 0, sin(yRot * PI / 180))->normalize(); - - double dot = abs(dir->dot(facing)); - - if (dot < 0.8f) - { - return; - } - - double xdd = (e->xd + xd); - double zdd = (e->zd + zd); - - std::shared_ptr cart = std::dynamic_pointer_cast(e); - if (cart != NULL && cart->type == Minecart::FURNACE && type != Minecart::FURNACE) - { - xd *= 0.2f; - zd *= 0.2f; - this->Entity::push( e->xd - xa, 0, e->zd - za); - e->xd *= 0.95f; - e->zd *= 0.95f; - m_bHasPushedCartThisTick = true; - } - else if (cart != NULL && cart->type != Minecart::FURNACE && type == Minecart::FURNACE) - { - e->xd *= 0.2f; - e->zd *= 0.2f; - e->push(xd + xa, 0, zd + za); - xd *= 0.95f; - zd *= 0.95f; - m_bHasPushedCartThisTick = true; - } - else - { - xdd /= 2; - zdd /= 2; - xd *= 0.2f; - zd *= 0.2f; - this->Entity::push(xdd - xa, 0, zdd - za); - e->xd *= 0.2f; - e->zd *= 0.2f; - e->push(xdd + xa, 0, zdd + za); - m_bHasPushedCartThisTick = true; - - // 4J Stu - Fix for #46937 - TU5: Gameplay: Crash/Freeze occurs when a minecart with an animal inside will be forced to despawn - // Minecarts can end up stuck inside each other, so if they are too close then they should separate quickly - double modifier = 1.0; - if( abs(xo) < 1 && abs(zo) < 1) - { - modifier += 1-( (abs(xo) + abs(zo))/2); - } - // 4J Stu - Decelerate the cart that is pushing this one if they are too close - e->xd /= modifier; - e->zd /= modifier; - - // 4J Backup fix for QNAN - if( !(xd==xd) ) xd = 0; - if( !(zd==zd) ) zd = 0; - if( !(e->xd == e->xd) ) e->xd = 0; - if( !(e->zd == e->zd) ) e->zd = 0; - } - - } - else - { - this->Entity::push(-xa, 0, -za); - e->push(xa / 4, 0, za / 4); - } - } +bool Minecart::interact(std::shared_ptr player) { + if (type == Minecart::RIDEABLE) { + if (rider.lock() != NULL && + std::dynamic_pointer_cast(rider.lock()) != NULL && + rider.lock() != player) + return true; + if (!level->isClientSide) { + // 4J HEG - Fixed issue with player not being able to dismount + // minecart (issue #4455) + player->ride(rider.lock() == player ? nullptr : shared_from_this()); + } + } else if (type == Minecart::CHEST) { + if (player->isAllowedToInteract(shared_from_this())) { + if (!level->isClientSide) + player->openContainer( + std::dynamic_pointer_cast(shared_from_this())); + } else { + return false; + } + } else if (type == Minecart::FURNACE) { + std::shared_ptr selected = + player->inventory->getSelected(); + if (selected != NULL && selected->id == Item::coal->id) { + if (--selected->count == 0) + player->inventory->setItem(player->inventory->selected, + nullptr); + fuel += SharedConstants::TICKS_PER_SECOND * 180; + } + xPush = x - player->x; + zPush = z - player->z; + } + return true; } -unsigned int Minecart::getContainerSize() -{ - return 9 * 3; +float Minecart::getLootContent() { + int count = 0; + for (unsigned int i = 0; i < items->length; i++) { + if ((*items)[i] != NULL) count++; + } + return count / (float)items->length; } -std::shared_ptr Minecart::getItem(unsigned int slot) -{ - return (*items)[slot]; +void Minecart::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + lx = x; + ly = y; + lz = z; + lyr = yRot; + lxr = xRot; + + lSteps = steps + 2; + + this->xd = lxd; + this->yd = lyd; + this->zd = lzd; } -std::shared_ptr Minecart::removeItem(unsigned int slot, int count) -{ - if ( (*items)[slot] != NULL) - { - if ( (*items)[slot]->count <= count) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - return item; - } - else - { - std::shared_ptr i = (*items)[slot]->remove(count); - if ((*items)[slot]->count == 0) (*items)[slot] = nullptr; - return i; - } - } - return nullptr; +void Minecart::lerpMotion(double xd, double yd, double zd) { + lxd = this->xd = xd; + lyd = this->yd = yd; + lzd = this->zd = zd; } -std::shared_ptr Minecart::removeItemNoUpdate(int slot) -{ - if ( (*items)[slot] != NULL) - { - std::shared_ptr item = (*items)[slot]; - (*items)[slot] = nullptr; - return item; - } - return nullptr; +bool Minecart::stillValid(std::shared_ptr player) { + if (this->removed) return false; + if (player->distanceToSqr(shared_from_this()) > 8 * 8) return false; + return true; } -void Minecart::setItem(unsigned int slot, std::shared_ptr item) -{ - (*items)[slot] = item; - if (item != NULL && item->count > getMaxStackSize()) item->count = getMaxStackSize(); +bool Minecart::hasFuel() { + return (entityData->getByte(DATA_ID_FUEL) & 1) != 0; } -int Minecart::getName() -{ - return IDS_ITEM_MINECART; +void Minecart::setHasFuel(bool fuel) { + if (fuel) { + entityData->set(DATA_ID_FUEL, + (uint8_t)(entityData->getByte(DATA_ID_FUEL) | 1)); + } else { + entityData->set(DATA_ID_FUEL, + (uint8_t)(entityData->getByte(DATA_ID_FUEL) & ~1)); + } } -int Minecart::getMaxStackSize() -{ - return Container::LARGE_MAX_STACK_SIZE; +void Minecart::startOpen() { + // TODO Auto-generated method stub } -void Minecart::setChanged() -{ +void Minecart::stopOpen() { + // TODO Auto-generated method stub } -bool Minecart::interact(std::shared_ptr player) -{ - if (type == Minecart::RIDEABLE) - { - if (rider.lock() != NULL && std::dynamic_pointer_cast(rider.lock())!=NULL && rider.lock() != player) return true; - if (!level->isClientSide) - { - // 4J HEG - Fixed issue with player not being able to dismount minecart (issue #4455) - player->ride( rider.lock() == player ? nullptr : shared_from_this() ); - } - } - else if (type == Minecart::CHEST) - { - if ( player->isAllowedToInteract(shared_from_this()) ) - { - if (!level->isClientSide) - player->openContainer( std::dynamic_pointer_cast( shared_from_this() ) ); - } - else - { - return false; - } - } - else if (type == Minecart::FURNACE) - { - std::shared_ptr selected = player->inventory->getSelected(); - if (selected != NULL && selected->id == Item::coal->id) - { - if (--selected->count == 0) player->inventory->setItem(player->inventory->selected, nullptr); - fuel += SharedConstants::TICKS_PER_SECOND * 180; - - } - xPush = x - player->x; - zPush = z - player->z; - } - return true; +void Minecart::setDamage(int damage) { + entityData->set(DATA_ID_DAMAGE, damage); } -float Minecart::getLootContent() -{ - int count = 0; - for (unsigned int i = 0; i < items->length; i++) - { - if ( (*items)[i] != NULL) count++; - } - return count / (float) items->length; +int Minecart::getDamage() { return entityData->getInteger(DATA_ID_DAMAGE); } + +void Minecart::setHurtTime(int hurtTime) { + entityData->set(DATA_ID_HURT, hurtTime); } +int Minecart::getHurtTime() { return entityData->getInteger(DATA_ID_HURT); } -void Minecart::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ - lx = x; - ly = y; - lz = z; - lyr = yRot; - lxr = xRot; - - lSteps = steps + 2; - - this->xd = lxd; - this->yd = lyd; - this->zd = lzd; +void Minecart::setHurtDir(int hurtDir) { + entityData->set(DATA_ID_HURTDIR, hurtDir); } -void Minecart::lerpMotion(double xd, double yd, double zd) -{ - lxd = this->xd = xd; - lyd = this->yd = yd; - lzd = this->zd = zd; -} - -bool Minecart::stillValid(std::shared_ptr player) -{ - if (this->removed) return false; - if (player->distanceToSqr(shared_from_this()) > 8 * 8) return false; - return true; -} - -bool Minecart::hasFuel() -{ - return (entityData->getByte(DATA_ID_FUEL) & 1) != 0; -} - -void Minecart::setHasFuel(bool fuel) -{ - if (fuel) - { - entityData->set(DATA_ID_FUEL, (uint8_t) (entityData->getByte(DATA_ID_FUEL) | 1)); - } - else - { - entityData->set(DATA_ID_FUEL, (uint8_t) (entityData->getByte(DATA_ID_FUEL) & ~1)); - } -} - -void Minecart::startOpen() -{ - // TODO Auto-generated method stub - -} - -void Minecart::stopOpen() -{ - // TODO Auto-generated method stub - -} - -void Minecart::setDamage(int damage) -{ - entityData->set(DATA_ID_DAMAGE, damage); -} - -int Minecart::getDamage() -{ - return entityData->getInteger(DATA_ID_DAMAGE); -} - -void Minecart::setHurtTime(int hurtTime) -{ - entityData->set(DATA_ID_HURT, hurtTime); -} - -int Minecart::getHurtTime() -{ - return entityData->getInteger(DATA_ID_HURT); -} - -void Minecart::setHurtDir(int hurtDir) -{ - entityData->set(DATA_ID_HURTDIR, hurtDir); -} - -int Minecart::getHurtDir() -{ - return entityData->getInteger(DATA_ID_HURTDIR); -} +int Minecart::getHurtDir() { return entityData->getInteger(DATA_ID_HURTDIR); } diff --git a/Minecraft.World/Entities/Mobs/Minecart.h b/Minecraft.World/Entities/Mobs/Minecart.h index ac42944d1..10efc94a6 100644 --- a/Minecraft.World/Entities/Mobs/Minecart.h +++ b/Minecraft.World/Entities/Mobs/Minecart.h @@ -4,111 +4,112 @@ class DamageSource; -class Minecart : public Entity, public Container -{ +class Minecart : public Entity, public Container { public: - eINSTANCEOF GetType() { return eTYPE_MINECART; }; - static Entity *create(Level *level) { return new Minecart(level); } + eINSTANCEOF GetType() { return eTYPE_MINECART; }; + static Entity* create(Level* level) { return new Minecart(level); } public: - static const int RIDEABLE = 0; - static const int CHEST = 1; - static const int FURNACE = 2; + static const int RIDEABLE = 0; + static const int CHEST = 1; + static const int FURNACE = 2; private: - ItemInstanceArray *items; // Array + ItemInstanceArray* items; // Array public: - static const int serialVersionUID = 0; + static const int serialVersionUID = 0; private: - static const int DATA_ID_FUEL = 16; - static const int DATA_ID_HURT = 17; - static const int DATA_ID_HURTDIR = 18; - static const int DATA_ID_DAMAGE = 19; + static const int DATA_ID_FUEL = 16; + static const int DATA_ID_HURT = 17; + static const int DATA_ID_HURTDIR = 18; + static const int DATA_ID_DAMAGE = 19; - int fuel; + int fuel; private: - bool flipped; + bool flipped; protected: - // 4J Added - bool m_bHasPushedCartThisTick; + // 4J Added + bool m_bHasPushedCartThisTick; public: - int type; - double xPush, zPush; + int type; + double xPush, zPush; - void _init(); + void _init(); - Minecart(Level *level); + Minecart(Level* level); protected: - virtual bool makeStepSound(); - virtual void defineSynchedData(); + virtual bool makeStepSound(); + virtual void defineSynchedData(); public: - virtual AABB *getCollideAgainstBox(std::shared_ptr entity); - virtual AABB *getCollideBox(); - virtual bool isPushable(); + virtual AABB* getCollideAgainstBox(std::shared_ptr entity); + virtual AABB* getCollideBox(); + virtual bool isPushable(); - Minecart(Level *level, double x, double y, double z, int type); + Minecart(Level* level, double x, double y, double z, int type); - virtual double getRideHeight(); - virtual bool hurt(DamageSource *source, int damage); - virtual void animateHurt(); - virtual bool isPickable(); - virtual void remove(); + virtual double getRideHeight(); + virtual bool hurt(DamageSource* source, int damage); + virtual void animateHurt(); + virtual bool isPickable(); + virtual void remove(); private: - static const int EXITS[][2][3]; + static const int EXITS[][2][3]; public: - virtual void tick(); - virtual Vec3 *getPosOffs(double x, double y, double z, double offs); - virtual Vec3 *getPos(double x, double y, double z); + virtual void tick(); + virtual Vec3* getPosOffs(double x, double y, double z, double offs); + virtual Vec3* getPos(double x, double y, double z); protected: - virtual void addAdditonalSaveData(CompoundTag *base); - virtual void readAdditionalSaveData(CompoundTag *base); + virtual void addAdditonalSaveData(CompoundTag* base); + virtual void readAdditionalSaveData(CompoundTag* base); public: - virtual float getShadowHeightOffs(); - virtual void push(std::shared_ptr e); - virtual unsigned int getContainerSize(); - virtual std::shared_ptr getItem(unsigned int slot); - virtual std::shared_ptr removeItem(unsigned int slot, int count); - virtual std::shared_ptr removeItemNoUpdate(int slot); - virtual void setItem(unsigned int slot, std::shared_ptr item); - int getName(); - virtual int getMaxStackSize(); - virtual void setChanged(); - virtual bool interact(std::shared_ptr player); - virtual float getLootContent(); + virtual float getShadowHeightOffs(); + virtual void push(std::shared_ptr e); + virtual unsigned int getContainerSize(); + virtual std::shared_ptr getItem(unsigned int slot); + virtual std::shared_ptr removeItem(unsigned int slot, + int count); + virtual std::shared_ptr removeItemNoUpdate(int slot); + virtual void setItem(unsigned int slot, std::shared_ptr item); + int getName(); + virtual int getMaxStackSize(); + virtual void setChanged(); + virtual bool interact(std::shared_ptr player); + virtual float getLootContent(); private: - int lSteps; - double lx, ly, lz, lyr, lxr; - double lxd, lyd, lzd; + int lSteps; + double lx, ly, lz, lyr, lxr; + double lxd, lyd, lzd; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); - virtual void lerpMotion(double xd, double yd, double zd); - virtual bool stillValid(std::shared_ptr player); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); + virtual void lerpMotion(double xd, double yd, double zd); + virtual bool stillValid(std::shared_ptr player); protected: - bool hasFuel(); - void setHasFuel(bool fuel); + bool hasFuel(); + void setHasFuel(bool fuel); public: - virtual void startOpen(); - virtual void stopOpen(); + virtual void startOpen(); + virtual void stopOpen(); - void setDamage(int damage); - int getDamage(); - void setHurtTime(int hurtTime); - int getHurtTime(); - void setHurtDir(int hurtDir); - int getHurtDir(); + void setDamage(int damage); + int getDamage(); + void setHurtTime(int hurtTime); + int getHurtTime(); + void setHurtDir(int hurtDir); + int getHurtDir(); }; diff --git a/Minecraft.World/Entities/Mobs/MushroomCow.cpp b/Minecraft.World/Entities/Mobs/MushroomCow.cpp index c405541e7..54a5921a6 100644 --- a/Minecraft.World/Entities/Mobs/MushroomCow.cpp +++ b/Minecraft.World/Entities/Mobs/MushroomCow.cpp @@ -9,76 +9,78 @@ #include "../MobCategory.h" #include "../../Util/AABB.h" +MushroomCow::MushroomCow(Level* level) : Cow(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - -MushroomCow::MushroomCow(Level *level) : Cow(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_RED_COW;// 4J was "/mob/redcow.png"; - this->setSize(0.9f, 1.3f); + this->textureIdx = TN_MOB_RED_COW; // 4J was "/mob/redcow.png"; + this->setSize(0.9f, 1.3f); } -bool MushroomCow::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (item != NULL && item->id == Item::bowl_Id && getAge() >= 0) - { - if (item->count == 1) - { - player->inventory->setItem(player->inventory->selected, std::shared_ptr( new ItemInstance(Item::mushroomStew) ) ); - return true; - } +bool MushroomCow::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); + if (item != NULL && item->id == Item::bowl_Id && getAge() >= 0) { + if (item->count == 1) { + player->inventory->setItem( + player->inventory->selected, + std::shared_ptr( + new ItemInstance(Item::mushroomStew))); + return true; + } - if (player->inventory->add(std::shared_ptr(new ItemInstance(Item::mushroomStew))) && !player->abilities.instabuild) - { - player->inventory->removeItem(player->inventory->selected, 1); - return true; - } - } - if (item != NULL && item->id == Item::shears_Id && getAge() >= 0) - { - remove(); - level->addParticle(eParticleType_largeexplode, x, y + bbHeight / 2, z, 0, 0, 0); - if(!level->isClientSide) - { - // 4J Stu - We don't need to check spawn limits when adding the new cow, as we are removing the MushroomCow - remove(); - std::shared_ptr cow = std::shared_ptr( new Cow(level) ); - cow->moveTo(x, y, z, yRot, xRot); - cow->setHealth(getHealth()); - cow->yBodyRot = yBodyRot; - level->addEntity(cow); - for (int i = 0; i < 5; i++) - { - level->addEntity( std::shared_ptr( new ItemEntity(level, x, y + bbHeight, z, std::shared_ptr( new ItemInstance(Tile::mushroom2))) )); - } - return true; - } - return true; - } - return Cow::interact(player); + if (player->inventory->add(std::shared_ptr( + new ItemInstance(Item::mushroomStew))) && + !player->abilities.instabuild) { + player->inventory->removeItem(player->inventory->selected, 1); + return true; + } + } + if (item != NULL && item->id == Item::shears_Id && getAge() >= 0) { + remove(); + level->addParticle(eParticleType_largeexplode, x, y + bbHeight / 2, z, + 0, 0, 0); + if (!level->isClientSide) { + // 4J Stu - We don't need to check spawn limits when adding the new + // cow, as we are removing the MushroomCow + remove(); + std::shared_ptr cow = std::shared_ptr(new Cow(level)); + cow->moveTo(x, y, z, yRot, xRot); + cow->setHealth(getHealth()); + cow->yBodyRot = yBodyRot; + level->addEntity(cow); + for (int i = 0; i < 5; i++) { + level->addEntity(std::shared_ptr( + new ItemEntity(level, x, y + bbHeight, z, + std::shared_ptr( + new ItemInstance(Tile::mushroom2))))); + } + return true; + } + return true; + } + return Cow::interact(player); } -// 4J - added so that mushroom cows have more of a chance of spawning, they can now spawn on mycelium as well as grass - seems a bit odd that they don't already really -bool MushroomCow::canSpawn() -{ - int xt = Mth::floor(x); - int yt = Mth::floor(bb->y0); - int zt = Mth::floor(z); - return ( level->getTile(xt, yt - 1, zt) == Tile::grass_Id || level->getTile(xt, yt - 1, zt) == Tile::mycel_Id ) && level->getDaytimeRawBrightness(xt, yt, zt) > 8 && PathfinderMob::canSpawn(); +// 4J - added so that mushroom cows have more of a chance of spawning, they can +// now spawn on mycelium as well as grass - seems a bit odd that they don't +// already really +bool MushroomCow::canSpawn() { + int xt = Mth::floor(x); + int yt = Mth::floor(bb->y0); + int zt = Mth::floor(z); + return (level->getTile(xt, yt - 1, zt) == Tile::grass_Id || + level->getTile(xt, yt - 1, zt) == Tile::mycel_Id) && + level->getDaytimeRawBrightness(xt, yt, zt) > 8 && + PathfinderMob::canSpawn(); } -std::shared_ptr MushroomCow::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to number of animals that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - return std::shared_ptr( new MushroomCow(level) ); - } - else - { - return nullptr; - } +std::shared_ptr MushroomCow::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + return std::shared_ptr(new MushroomCow(level)); + } else { + return nullptr; + } } diff --git a/Minecraft.World/Entities/Mobs/MushroomCow.h b/Minecraft.World/Entities/Mobs/MushroomCow.h index 27bc9e35e..aed6adc0f 100644 --- a/Minecraft.World/Entities/Mobs/MushroomCow.h +++ b/Minecraft.World/Entities/Mobs/MushroomCow.h @@ -2,16 +2,16 @@ #include "Cow.h" -class MushroomCow : public Cow -{ +class MushroomCow : public Cow { public: - eINSTANCEOF GetType() { return eTYPE_MUSHROOMCOW; } - static Entity *create(Level *level) { return new MushroomCow(level); } + eINSTANCEOF GetType() { return eTYPE_MUSHROOMCOW; } + static Entity* create(Level* level) { return new MushroomCow(level); } public: - MushroomCow(Level *level); + MushroomCow(Level* level); - virtual bool interact(std::shared_ptr player); - virtual bool canSpawn(); // 4J added - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); + virtual bool interact(std::shared_ptr player); + virtual bool canSpawn(); // 4J added + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Npc.cpp b/Minecraft.World/Entities/Mobs/Npc.cpp index bb6413618..7a0cbf996 100644 --- a/Minecraft.World/Entities/Mobs/Npc.cpp +++ b/Minecraft.World/Entities/Mobs/Npc.cpp @@ -1,4 +1,3 @@ #include "../../Platform/stdafx.h" #include "Npc.h" - diff --git a/Minecraft.World/Entities/Mobs/Npc.h b/Minecraft.World/Entities/Mobs/Npc.h index 2b20e6721..545daa1da 100644 --- a/Minecraft.World/Entities/Mobs/Npc.h +++ b/Minecraft.World/Entities/Mobs/Npc.h @@ -4,8 +4,7 @@ class Level; -class Npc : public Creature -{ +class Npc : public Creature { public: - Npc() {} + Npc() {} }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Ocelot.cpp b/Minecraft.World/Entities/Mobs/Ocelot.cpp index 0b15d9718..5b59b9bed 100644 --- a/Minecraft.World/Entities/Mobs/Ocelot.cpp +++ b/Minecraft.World/Entities/Mobs/Ocelot.cpp @@ -28,306 +28,249 @@ const int Ozelot::TYPE_BLACK = 1; const int Ozelot::TYPE_RED = 2; const int Ozelot::TYPE_SIAMESE = 3; -Ozelot::Ozelot(Level *level) : TamableAnimal(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Ozelot::Ozelot(Level* level) : TamableAnimal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - this->textureIdx = TN_MOB_OZELOT; // "/mob/ozelot.png"; - this->setSize(0.6f, 0.8f); + this->textureIdx = TN_MOB_OZELOT; // "/mob/ozelot.png"; + this->setSize(0.6f, 0.8f); - getNavigation()->setAvoidWater(true); - goalSelector.addGoal(1, new FloatGoal(this)); - goalSelector.addGoal(2, sitGoal, false); - goalSelector.addGoal(3, temptGoal = new TemptGoal(this, SNEAK_SPEED, Item::fish_raw_Id, true), false); - goalSelector.addGoal(4, new AvoidPlayerGoal(this, typeid(Player), 16, WALK_SPEED, SPRINT_SPEED)); - goalSelector.addGoal(5, new FollowOwnerGoal(this, FOLLOW_SPEED, 10, 5)); - goalSelector.addGoal(6, new OcelotSitOnTileGoal(this, SPRINT_SPEED)); - goalSelector.addGoal(7, new LeapAtTargetGoal(this, 0.3f)); - goalSelector.addGoal(8, new OzelotAttackGoal(this)); - goalSelector.addGoal(9, new BreedGoal(this, WALK_SPEED)); - goalSelector.addGoal(10, new RandomStrollGoal(this, WALK_SPEED)); - goalSelector.addGoal(11, new LookAtPlayerGoal(this, typeid(Player), 10)); + getNavigation()->setAvoidWater(true); + goalSelector.addGoal(1, new FloatGoal(this)); + goalSelector.addGoal(2, sitGoal, false); + goalSelector.addGoal( + 3, + temptGoal = new TemptGoal(this, SNEAK_SPEED, Item::fish_raw_Id, true), + false); + goalSelector.addGoal(4, new AvoidPlayerGoal(this, typeid(Player), 16, + WALK_SPEED, SPRINT_SPEED)); + goalSelector.addGoal(5, new FollowOwnerGoal(this, FOLLOW_SPEED, 10, 5)); + goalSelector.addGoal(6, new OcelotSitOnTileGoal(this, SPRINT_SPEED)); + goalSelector.addGoal(7, new LeapAtTargetGoal(this, 0.3f)); + goalSelector.addGoal(8, new OzelotAttackGoal(this)); + goalSelector.addGoal(9, new BreedGoal(this, WALK_SPEED)); + goalSelector.addGoal(10, new RandomStrollGoal(this, WALK_SPEED)); + goalSelector.addGoal(11, new LookAtPlayerGoal(this, typeid(Player), 10)); - targetSelector.addGoal(1, new NonTameRandomTargetGoal(this, typeid(Chicken), 14, 750, false)); + targetSelector.addGoal( + 1, new NonTameRandomTargetGoal(this, typeid(Chicken), 14, 750, false)); } -void Ozelot::defineSynchedData() -{ - TamableAnimal::defineSynchedData(); +void Ozelot::defineSynchedData() { + TamableAnimal::defineSynchedData(); - entityData->define(DATA_TYPE_ID, (uint8_t) TYPE_OZELOT); + entityData->define(DATA_TYPE_ID, (uint8_t)TYPE_OZELOT); } -void Ozelot::serverAiMobStep() -{ - if (getMoveControl()->hasWanted()) - { - float speed = getMoveControl()->getSpeed(); - if (speed == SNEAK_SPEED) - { - setSneaking(true); - setSprinting(false); - } - else if (speed == SPRINT_SPEED) - { - setSneaking(false); - setSprinting(true); - } - else - { - setSneaking(false); - setSprinting(false); - } - } - else - { - setSneaking(false); - setSprinting(false); - } +void Ozelot::serverAiMobStep() { + if (getMoveControl()->hasWanted()) { + float speed = getMoveControl()->getSpeed(); + if (speed == SNEAK_SPEED) { + setSneaking(true); + setSprinting(false); + } else if (speed == SPRINT_SPEED) { + setSneaking(false); + setSprinting(true); + } else { + setSneaking(false); + setSprinting(false); + } + } else { + setSneaking(false); + setSprinting(false); + } } -bool Ozelot::removeWhenFarAway() -{ - return Animal::removeWhenFarAway() && !isTame(); +bool Ozelot::removeWhenFarAway() { + return Animal::removeWhenFarAway() && !isTame(); } -int Ozelot::getTexture() -{ - switch (getCatType()) - { - case TYPE_OZELOT: - return TN_MOB_OZELOT; //"/mob/ozelot.png"; - case TYPE_BLACK: - return TN_MOB_CAT_BLACK; //"/mob/cat_black.png"; - case TYPE_RED: - return TN_MOB_CAT_RED; //"/mob/cat_red.png"; - case TYPE_SIAMESE: - return TN_MOB_CAT_SIAMESE; //"/mob/cat_siamese.png"; - } - return TamableAnimal::getTexture(); +int Ozelot::getTexture() { + switch (getCatType()) { + case TYPE_OZELOT: + return TN_MOB_OZELOT; //"/mob/ozelot.png"; + case TYPE_BLACK: + return TN_MOB_CAT_BLACK; //"/mob/cat_black.png"; + case TYPE_RED: + return TN_MOB_CAT_RED; //"/mob/cat_red.png"; + case TYPE_SIAMESE: + return TN_MOB_CAT_SIAMESE; //"/mob/cat_siamese.png"; + } + return TamableAnimal::getTexture(); } -bool Ozelot::useNewAi() -{ - return true; +bool Ozelot::useNewAi() { return true; } + +int Ozelot::getMaxHealth() { return 10; } + +void Ozelot::causeFallDamage(float distance) { + // do nothing } -int Ozelot::getMaxHealth() -{ - return 10; +void Ozelot::addAdditonalSaveData(CompoundTag* tag) { + TamableAnimal::addAdditonalSaveData(tag); + tag->putInt(L"CatType", getCatType()); } -void Ozelot::causeFallDamage(float distance) -{ - // do nothing +void Ozelot::readAdditionalSaveData(CompoundTag* tag) { + TamableAnimal::readAdditionalSaveData(tag); + if (isTame()) { + setCatType(tag->getInt(L"CatType")); + } else { + setCatType(TYPE_OZELOT); + } } -void Ozelot::addAdditonalSaveData(CompoundTag *tag) -{ - TamableAnimal::addAdditonalSaveData(tag); - tag->putInt(L"CatType", getCatType()); +int Ozelot::getAmbientSound() { + if (isTame()) { + if (isInLove()) { + return eSoundType_MOB_CAT_PURR; + } + if (random->nextInt(4) == 0) { + return eSoundType_MOB_CAT_PURREOW; + } + return eSoundType_MOB_CAT_MEOW; + } + + return -1; } -void Ozelot::readAdditionalSaveData(CompoundTag *tag) -{ - TamableAnimal::readAdditionalSaveData(tag); - if(isTame()) - { - setCatType(tag->getInt(L"CatType")); - } - else - { - setCatType(TYPE_OZELOT); - } +int Ozelot::getHurtSound() { return eSoundType_MOB_CAT_HITT; } + +int Ozelot::getDeathSound() { return eSoundType_MOB_CAT_HITT; } + +float Ozelot::getSoundVolume() { return 0.4f; } + +int Ozelot::getDeathLoot() { return Item::leather_Id; } + +bool Ozelot::doHurtTarget(std::shared_ptr target) { + return target->hurt(DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())), + 3); } -int Ozelot::getAmbientSound() -{ - if (isTame()) - { - if (isInLove()) - { - return eSoundType_MOB_CAT_PURR; - } - if (random->nextInt(4) == 0) - { - return eSoundType_MOB_CAT_PURREOW; - } - return eSoundType_MOB_CAT_MEOW; - } - - return -1; +bool Ozelot::hurt(DamageSource* source, int dmg) { + sitGoal->wantToSit(false); + return TamableAnimal::hurt(source, dmg); } -int Ozelot::getHurtSound() -{ - return eSoundType_MOB_CAT_HITT; +void Ozelot::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) {} + +bool Ozelot::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); + if (isTame()) { + if (equalsIgnoreCase(player->getUUID(), getOwnerUUID())) { + if (!level->isClientSide && !isFood(item)) { + sitGoal->wantToSit(!isSitting()); + } + } + } else { + if (temptGoal->isRunning() && item != NULL && + item->id == Item::fish_raw_Id && + player->distanceToSqr(shared_from_this()) < 3 * 3) { + // 4J-PB - don't lose the fish in creative mode + if (!player->abilities.instabuild) item->count--; + if (item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } + + if (!level->isClientSide) { + if (random->nextInt(3) == 0) { + setTame(true); + + // 4J-JEV, hook for durango event. + player->awardStat( + GenericStats::tamedEntity(eTYPE_OZELOT), + GenericStats::param_tamedEntity(eTYPE_OZELOT)); + + setCatType(1 + level->random->nextInt(3)); + setOwnerUUID(player->getUUID()); + spawnTamingParticles(true); + sitGoal->wantToSit(true); + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::TAMING_SUCCEEDED); + } else { + spawnTamingParticles(false); + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::TAMING_FAILED); + } + } + return true; + } + } + return TamableAnimal::interact(player); } -int Ozelot::getDeathSound() -{ - return eSoundType_MOB_CAT_HITT; +std::shared_ptr Ozelot::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + std::shared_ptr offspring = + std::shared_ptr(new Ozelot(level)); + if (isTame()) { + offspring->setOwnerUUID(getOwnerUUID()); + offspring->setTame(true); + offspring->setCatType(getCatType()); + } + return offspring; + } else { + return nullptr; + } } -float Ozelot::getSoundVolume() -{ - return 0.4f; +bool Ozelot::isFood(std::shared_ptr itemInstance) { + return itemInstance != NULL && itemInstance->id == Item::fish_raw_Id; } -int Ozelot::getDeathLoot() -{ - return Item::leather_Id; +bool Ozelot::canMate(std::shared_ptr animal) { + if (animal == shared_from_this()) return false; + if (!isTame()) return false; + + std::shared_ptr partner = std::dynamic_pointer_cast(animal); + if (partner == NULL) return false; + if (!partner->isTame()) return false; + + return isInLove() && partner->isInLove(); } -bool Ozelot::doHurtTarget(std::shared_ptr target) -{ - return target->hurt(DamageSource::mobAttack(std::dynamic_pointer_cast(shared_from_this())), 3); +int Ozelot::getCatType() { return entityData->getByte(DATA_TYPE_ID); } + +void Ozelot::setCatType(int type) { + entityData->set(DATA_TYPE_ID, (uint8_t)type); } -bool Ozelot::hurt(DamageSource *source, int dmg) -{ - sitGoal->wantToSit(false); - return TamableAnimal::hurt(source, dmg); +bool Ozelot::canSpawn() { + // artificially make ozelots more rare + if (level->random->nextInt(3) == 0) { + return false; + } + if (level->isUnobstructed(bb) && + level->getCubes(shared_from_this(), bb)->empty() && + !level->containsAnyLiquid(bb)) { + int xt = Mth::floor(x); + int yt = Mth::floor(bb->y0); + int zt = Mth::floor(z); + if (yt < level->seaLevel) { + return false; + } + + int tile = level->getTile(xt, yt - 1, zt); + if (tile == Tile::grass_Id || tile == Tile::leaves_Id) { + return true; + } + } + return false; } -void Ozelot::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ -} - -bool Ozelot::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - if (isTame()) - { - if (equalsIgnoreCase(player->getUUID(), getOwnerUUID())) - { - if (!level->isClientSide && !isFood(item)) - { - sitGoal->wantToSit(!isSitting()); - } - } - } - else - { - if (temptGoal->isRunning() && item != NULL && item->id == Item::fish_raw_Id && player->distanceToSqr(shared_from_this()) < 3 * 3) - { - // 4J-PB - don't lose the fish in creative mode - if (!player->abilities.instabuild) item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - - if (!level->isClientSide) - { - if (random->nextInt(3) == 0) - { - setTame(true); - - // 4J-JEV, hook for durango event. - player->awardStat(GenericStats::tamedEntity(eTYPE_OZELOT),GenericStats::param_tamedEntity(eTYPE_OZELOT)); - - setCatType(1 + level->random->nextInt(3)); - setOwnerUUID(player->getUUID()); - spawnTamingParticles(true); - sitGoal->wantToSit(true); - level->broadcastEntityEvent(shared_from_this(), EntityEvent::TAMING_SUCCEEDED); - } - else - { - spawnTamingParticles(false); - level->broadcastEntityEvent(shared_from_this(), EntityEvent::TAMING_FAILED); - } - } - return true; - } - } - return TamableAnimal::interact(player); -} - -std::shared_ptr Ozelot::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to number of animals that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - std::shared_ptr offspring = std::shared_ptr( new Ozelot(level) ); - if (isTame()) - { - offspring->setOwnerUUID(getOwnerUUID()); - offspring->setTame(true); - offspring->setCatType(getCatType()); - } - return offspring; - } - else - { - return nullptr; - } -} - -bool Ozelot::isFood(std::shared_ptr itemInstance) -{ - return itemInstance != NULL && itemInstance->id == Item::fish_raw_Id; -} - -bool Ozelot::canMate(std::shared_ptr animal) -{ - if (animal == shared_from_this()) return false; - if (!isTame()) return false; - - std::shared_ptr partner = std::dynamic_pointer_cast(animal); - if (partner == NULL) return false; - if (!partner->isTame()) return false; - - return isInLove() && partner->isInLove(); -} - -int Ozelot::getCatType() -{ - return entityData->getByte(DATA_TYPE_ID); -} - -void Ozelot::setCatType(int type) -{ - entityData->set(DATA_TYPE_ID, (uint8_t) type); -} - -bool Ozelot::canSpawn() -{ - // artificially make ozelots more rare - if (level->random->nextInt(3) == 0) - { - return false; - } - if (level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb)) - { - int xt = Mth::floor(x); - int yt = Mth::floor(bb->y0); - int zt = Mth::floor(z); - if (yt < level->seaLevel) - { - return false; - } - - int tile = level->getTile(xt, yt - 1, zt); - if (tile == Tile::grass_Id || tile == Tile::leaves_Id) - { - return true; - } - } - return false; -} - -std::wstring Ozelot::getAName() -{ - if (isTame()) - { - return L"entity.Cat.name"; - } - return TamableAnimal::getAName(); +std::wstring Ozelot::getAName() { + if (isTame()) { + return L"entity.Cat.name"; + } + return TamableAnimal::getAName(); } diff --git a/Minecraft.World/Entities/Mobs/Ocelot.h b/Minecraft.World/Entities/Mobs/Ocelot.h index bc557e317..ae3a52518 100644 --- a/Minecraft.World/Entities/Mobs/Ocelot.h +++ b/Minecraft.World/Entities/Mobs/Ocelot.h @@ -4,73 +4,73 @@ class TemptGoal; -class Ozelot : public TamableAnimal -{ +class Ozelot : public TamableAnimal { public: - eINSTANCEOF GetType() { return eTYPE_OZELOT; } - static Entity *create(Level *level) { return new Ozelot(level); } + eINSTANCEOF GetType() { return eTYPE_OZELOT; } + static Entity* create(Level* level) { return new Ozelot(level); } public: - static const float SNEAK_SPEED; - static const float WALK_SPEED; - static const float FOLLOW_SPEED; - static const float SPRINT_SPEED; + static const float SNEAK_SPEED; + static const float WALK_SPEED; + static const float FOLLOW_SPEED; + static const float SPRINT_SPEED; private: - static const int DATA_TYPE_ID; + static const int DATA_TYPE_ID; - static const int TYPE_OZELOT; - static const int TYPE_BLACK; - static const int TYPE_RED; - static const int TYPE_SIAMESE; + static const int TYPE_OZELOT; + static const int TYPE_BLACK; + static const int TYPE_RED; + static const int TYPE_SIAMESE; - TemptGoal *temptGoal; + TemptGoal* temptGoal; public: - Ozelot(Level *level); + Ozelot(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void serverAiMobStep(); + virtual void serverAiMobStep(); protected: - virtual bool removeWhenFarAway(); + virtual bool removeWhenFarAway(); public: - virtual int getTexture(); - virtual bool useNewAi(); - virtual int getMaxHealth(); + virtual int getTexture(); + virtual bool useNewAi(); + virtual int getMaxHealth(); protected: - virtual void causeFallDamage(float distance); + virtual void causeFallDamage(float distance); public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual float getSoundVolume(); - virtual int getDeathLoot(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual float getSoundVolume(); + virtual int getDeathLoot(); public: - virtual bool doHurtTarget(std::shared_ptr target); - virtual bool hurt(DamageSource *source, int dmg); + virtual bool doHurtTarget(std::shared_ptr target); + virtual bool hurt(DamageSource* source, int dmg); protected: - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual bool interact(std::shared_ptr player); - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); - virtual bool isFood(std::shared_ptr itemInstance); - virtual bool canMate(std::shared_ptr animal); - virtual int getCatType(); - virtual void setCatType(int type); - virtual bool canSpawn(); - virtual std::wstring getAName(); + virtual bool interact(std::shared_ptr player); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); + virtual bool isFood(std::shared_ptr itemInstance); + virtual bool canMate(std::shared_ptr animal); + virtual int getCatType(); + virtual void setCatType(int type); + virtual bool canSpawn(); + virtual std::wstring getAName(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Painting.cpp b/Minecraft.World/Entities/Mobs/Painting.cpp index 42ec18e5d..ea663b01b 100644 --- a/Minecraft.World/Entities/Mobs/Painting.cpp +++ b/Minecraft.World/Entities/Mobs/Painting.cpp @@ -9,140 +9,123 @@ #include "Painting.h" #include "../../Blocks/Material.h" - - typedef Painting::Motive _Motive; -const _Motive *Painting::Motive::values[] = { - new _Motive(L"Kebab", 16, 16, 0 * 16, 0 * 16), - new _Motive(L"Aztec", 16, 16, 1 * 16, 0 * 16), // - new _Motive(L"Alban", 16, 16, 2 * 16, 0 * 16), // - new _Motive(L"Aztec2", 16, 16, 3 * 16, 0 * 16), // - new _Motive(L"Bomb", 16, 16, 4 * 16, 0 * 16), // - new _Motive(L"Plant", 16, 16, 5 * 16, 0 * 16), // - new _Motive(L"Wasteland", 16, 16, 6 * 16, 0 * 16), // +const _Motive* Painting::Motive::values[] = { + new _Motive(L"Kebab", 16, 16, 0 * 16, 0 * 16), + new _Motive(L"Aztec", 16, 16, 1 * 16, 0 * 16), // + new _Motive(L"Alban", 16, 16, 2 * 16, 0 * 16), // + new _Motive(L"Aztec2", 16, 16, 3 * 16, 0 * 16), // + new _Motive(L"Bomb", 16, 16, 4 * 16, 0 * 16), // + new _Motive(L"Plant", 16, 16, 5 * 16, 0 * 16), // + new _Motive(L"Wasteland", 16, 16, 6 * 16, 0 * 16), // - new _Motive(L"Pool", 32, 16, 0 * 16, 2 * 16), // - new _Motive(L"Courbet", 32, 16, 2 * 16, 2 * 16), // - new _Motive(L"Sea", 32, 16, 4 * 16, 2 * 16), // - new _Motive(L"Sunset", 32, 16, 6 * 16, 2 * 16), // - new _Motive(L"Creebet", 32, 16, 8 * 16, 2 * 16), // + new _Motive(L"Pool", 32, 16, 0 * 16, 2 * 16), // + new _Motive(L"Courbet", 32, 16, 2 * 16, 2 * 16), // + new _Motive(L"Sea", 32, 16, 4 * 16, 2 * 16), // + new _Motive(L"Sunset", 32, 16, 6 * 16, 2 * 16), // + new _Motive(L"Creebet", 32, 16, 8 * 16, 2 * 16), // - new _Motive(L"Wanderer", 16, 32, 0 * 16, 4 * 16), // - new _Motive(L"Graham", 16, 32, 1 * 16, 4 * 16), // + new _Motive(L"Wanderer", 16, 32, 0 * 16, 4 * 16), // + new _Motive(L"Graham", 16, 32, 1 * 16, 4 * 16), // - new _Motive(L"Match", 32, 32, 0 * 16, 8 * 16), // - new _Motive(L"Bust", 32, 32, 2 * 16, 8 * 16), // - new _Motive(L"Stage", 32, 32, 4 * 16, 8 * 16), // - new _Motive(L"Void", 32, 32, 6 * 16, 8 * 16), // - new _Motive(L"SkullAndRoses", 32, 32, 8 * 16, 8 * 16), // - new _Motive(L"Wither", 32, 32, 10 * 16, 8 * 16), - new _Motive(L"Fighters", 64, 32, 0 * 16, 6 * 16), // + new _Motive(L"Match", 32, 32, 0 * 16, 8 * 16), // + new _Motive(L"Bust", 32, 32, 2 * 16, 8 * 16), // + new _Motive(L"Stage", 32, 32, 4 * 16, 8 * 16), // + new _Motive(L"Void", 32, 32, 6 * 16, 8 * 16), // + new _Motive(L"SkullAndRoses", 32, 32, 8 * 16, 8 * 16), // + new _Motive(L"Wither", 32, 32, 10 * 16, 8 * 16), + new _Motive(L"Fighters", 64, 32, 0 * 16, 6 * 16), // - new _Motive(L"Pointer", 64, 64, 0 * 16, 12 * 16), // - new _Motive(L"Pigscene", 64, 64, 4 * 16, 12 * 16), // - new _Motive(L"BurningSkull", 64, 64, 8 * 16, 12 * 16), // + new _Motive(L"Pointer", 64, 64, 0 * 16, 12 * 16), // + new _Motive(L"Pigscene", 64, 64, 4 * 16, 12 * 16), // + new _Motive(L"BurningSkull", 64, 64, 8 * 16, 12 * 16), // - new _Motive(L"Skeleton", 64, 48, 12 * 16, 4 * 16), // - new _Motive(L"DonkeyKong", 64, 48, 12 * 16, 7 * 16), // + new _Motive(L"Skeleton", 64, 48, 12 * 16, 4 * 16), // + new _Motive(L"DonkeyKong", 64, 48, 12 * 16, 7 * 16), // }; // 4J Stu - Rather than creating a new string object here I am just using the // actual number value of the characters in "SkullandRoses" which should be the // longest name from the above -const int Painting::Motive::MAX_MOTIVE_NAME_LENGTH = 13; //JAVA: "SkullAndRoses".length(); +const int Painting::Motive::MAX_MOTIVE_NAME_LENGTH = + 13; // JAVA: "SkullAndRoses".length(); // 4J - added for common ctor code -void Painting::_init( Level *level ) -{ - motive = NULL; -}; +void Painting::_init(Level* level) { motive = NULL; }; -Painting::Painting(Level *level) : HangingEntity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Painting::Painting(Level* level) : HangingEntity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - _init( level ); + _init(level); } -Painting::Painting(Level *level, int xTile, int yTile, int zTile, int dir) : HangingEntity( level , xTile, yTile, zTile, dir) -{ - _init(level); +Painting::Painting(Level* level, int xTile, int yTile, int zTile, int dir) + : HangingEntity(level, xTile, yTile, zTile, dir) { + _init(level); - // 4J Stu - If you use this ctor, then you need to call the PaintingPostConstructor + // 4J Stu - If you use this ctor, then you need to call the + // PaintingPostConstructor } -// 4J Stu - Added this so that we can use some std::shared_ptr functions that were needed in the ctor -void Painting::PaintingPostConstructor(int dir) -{ - std::vector *survivableMotives = new std::vector(); - for (int i = 0 ; i < LAST_VALUE; i++) - { - this->motive = (Motive *)Motive::values[i]; - setDir(dir); - if (survives()) - { - survivableMotives->push_back(this->motive); - } - } - if (!survivableMotives->empty()) - { - this->motive = survivableMotives->at(random->nextInt((int)survivableMotives->size())); - } - setDir(dir); +// 4J Stu - Added this so that we can use some std::shared_ptr functions that +// were needed in the ctor +void Painting::PaintingPostConstructor(int dir) { + std::vector* survivableMotives = new std::vector(); + for (int i = 0; i < LAST_VALUE; i++) { + this->motive = (Motive*)Motive::values[i]; + setDir(dir); + if (survives()) { + survivableMotives->push_back(this->motive); + } + } + if (!survivableMotives->empty()) { + this->motive = survivableMotives->at( + random->nextInt((int)survivableMotives->size())); + } + setDir(dir); } -Painting::Painting(Level *level, int x, int y, int z, int dir, std::wstring motiveName) : HangingEntity( level , x, y, z, dir ) -{ - _init(level); +Painting::Painting(Level* level, int x, int y, int z, int dir, + std::wstring motiveName) + : HangingEntity(level, x, y, z, dir) { + _init(level); - for (int i = 0 ; i < LAST_VALUE; i++) - { - if ( (Motive::values[i])->name.compare(motiveName) == 0) - { - this->motive = (Motive *)Motive::values[i]; - break; - } - } - setDir(dir); + for (int i = 0; i < LAST_VALUE; i++) { + if ((Motive::values[i])->name.compare(motiveName) == 0) { + this->motive = (Motive*)Motive::values[i]; + break; + } + } + setDir(dir); } -void Painting::addAdditonalSaveData(CompoundTag *tag) -{ - ///TODO Safe to cast to non-const type? - tag->putString(L"Motive", motive->name); +void Painting::addAdditonalSaveData(CompoundTag* tag) { + /// TODO Safe to cast to non-const type? + tag->putString(L"Motive", motive->name); - HangingEntity::addAdditonalSaveData(tag); - } - -void Painting::readAdditionalSaveData(CompoundTag *tag) -{ - std::wstring motiveName = tag->getString(L"Motive"); - std::vector::iterator it; - for (int i = 0 ; i < LAST_VALUE; i++) - { - if ( Motive::values[i]->name.compare(motiveName) == 0) - { - this->motive = (Motive *)Motive::values[i]; - } - } - if (this->motive == NULL) motive = (Motive *)Motive::values[ Kebab ]; - - HangingEntity::readAdditionalSaveData(tag); + HangingEntity::addAdditonalSaveData(tag); } -int Painting::getWidth() -{ - return motive->w; +void Painting::readAdditionalSaveData(CompoundTag* tag) { + std::wstring motiveName = tag->getString(L"Motive"); + std::vector::iterator it; + for (int i = 0; i < LAST_VALUE; i++) { + if (Motive::values[i]->name.compare(motiveName) == 0) { + this->motive = (Motive*)Motive::values[i]; + } + } + if (this->motive == NULL) motive = (Motive*)Motive::values[Kebab]; + + HangingEntity::readAdditionalSaveData(tag); } -int Painting::getHeight() -{ - return motive->h; -} +int Painting::getWidth() { return motive->w; } -void Painting::dropItem() -{ - spawnAtLocation(std::shared_ptr(new ItemInstance(Item::painting)), 0.0f); +int Painting::getHeight() { return motive->h; } + +void Painting::dropItem() { + spawnAtLocation( + std::shared_ptr(new ItemInstance(Item::painting)), 0.0f); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Painting.h b/Minecraft.World/Entities/Mobs/Painting.h index 7954b580c..5bba42c2e 100644 --- a/Minecraft.World/Entities/Mobs/Painting.h +++ b/Minecraft.World/Entities/Mobs/Painting.h @@ -1,6 +1,5 @@ #pragma once - #include "../Entity.h" #include "../HangingEntity.h" @@ -8,110 +7,111 @@ class Level; class CompoundTag; class DamageSource; -class Painting : public HangingEntity -{ - +class Painting : public HangingEntity { public: - eINSTANCEOF GetType() { return eTYPE_PAINTING; } - static Entity *create(Level *level) { return new Painting(level); } + eINSTANCEOF GetType() { return eTYPE_PAINTING; } + static Entity* create(Level* level) { return new Painting(level); } private: - //int checkInterval; + // int checkInterval; public: - enum MotiveEnum { - Kebab = 0, // - Aztec, // - Alban, // - Aztec2, // - Bomb, // - Plant, // - Wasteland, // + enum MotiveEnum { + Kebab = 0, // + Aztec, // + Alban, // + Aztec2, // + Bomb, // + Plant, // + Wasteland, // - Pool, // - Courbet, // - Sea, // - Sunset, // - Creebet, // + Pool, // + Courbet, // + Sea, // + Sunset, // + Creebet, // - Wanderer, // - Graham, // + Wanderer, // + Graham, // - Match, // - Bust, // - Stage, // - Void, // - SkullAndRoses, // - Wither, - Fighters, // + Match, // + Bust, // + Stage, // + Void, // + SkullAndRoses, // + Wither, + Fighters, // - Pointer, // - Pigscene, // - BurningSkull, // + Pointer, // + Pigscene, // + BurningSkull, // - Skeleton, // - DonkeyKong, // + Skeleton, // + DonkeyKong, // - LAST_VALUE - }; + LAST_VALUE + }; - // TODO 4J Replace the ENUM with static consts - class Motive - { - public: - static const Motive *values[]; + // TODO 4J Replace the ENUM with static consts + class Motive { + public: + static const Motive* values[]; - static const int MAX_MOTIVE_NAME_LENGTH; + static const int MAX_MOTIVE_NAME_LENGTH; - const std::wstring name; - const int w, h; - const int uo, vo; + const std::wstring name; + const int w, h; + const int uo, vo; - //private: - Motive(std::wstring name, int w, int h, int uo, int vo) : name( name ), w( w ), h( h ), uo( uo ), vo( vo ) {}; - }; + // private: + Motive(std::wstring name, int w, int h, int uo, int vo) + : name(name), w(w), h(h), uo(uo), vo(vo) {}; + }; public: -// int dir; -// -// int xTile, yTile, zTile; + // int dir; + // + // int xTile, yTile, zTile; - Motive *motive; + Motive* motive; private: - // 4J - added for common ctor code - void _init( Level *level ); + // 4J - added for common ctor code + void _init(Level* level); public: - Painting(Level *level); - Painting(Level *level, int xTile, int yTile, int zTile, int dir); - Painting(Level *level, int x, int y, int z, int dir, std::wstring motiveName); + Painting(Level* level); + Painting(Level* level, int xTile, int yTile, int zTile, int dir); + Painting(Level* level, int x, int y, int z, int dir, + std::wstring motiveName); - // 4J Stu - Added this so that we can use some std::shared_ptr functions that were needed in the ctor - void PaintingPostConstructor(int dir); + // 4J Stu - Added this so that we can use some std::shared_ptr functions + // that were needed in the ctor + void PaintingPostConstructor(int dir); protected: - //void defineSynchedData(); + // void defineSynchedData(); public: - //void setDir(int dir); + // void setDir(int dir); private: - //float offs(int w); + // float offs(int w); public: - //virtual void tick(); - //bool survives(); - //virtual bool isPickable(); - //virtual bool hurt(DamageSource *source, int damage); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - //static Motive *randomMotive(); + // virtual void tick(); + // bool survives(); + // virtual bool isPickable(); + // virtual bool hurt(DamageSource *source, int damage); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + // static Motive *randomMotive(); - //virtual void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter - //virtual void push(double xa, double ya, double za); + // virtual void move(double xa, double ya, double za, bool + // noEntityCubes=false); // 4J - added noEntityCubes parameter virtual + // void push(double xa, double ya, double za); - virtual int getWidth(); - virtual int getHeight(); - virtual void dropItem(); + virtual int getWidth(); + virtual int getHeight(); + virtual void dropItem(); }; diff --git a/Minecraft.World/Entities/Mobs/Pig.cpp b/Minecraft.World/Entities/Mobs/Pig.cpp index 38a67a66f..ffd017e02 100644 --- a/Minecraft.World/Entities/Mobs/Pig.cpp +++ b/Minecraft.World/Entities/Mobs/Pig.cpp @@ -16,177 +16,139 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../MobCategory.h" +Pig::Pig(Level* level) : Animal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Pig::Pig(Level *level) : Animal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + this->textureIdx = TN_MOB_PIG; // 4J - was L"/mob/pig.png"; + this->setSize(0.9f, 0.9f); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_PIG; // 4J - was L"/mob/pig.png"; - this->setSize(0.9f, 0.9f); - - getNavigation()->setAvoidWater(true); - float walkSpeed = 0.25f; - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); - goalSelector.addGoal(2, controlGoal = new ControlledByPlayerGoal(this, 0.34f, walkSpeed)); - goalSelector.addGoal(3, new BreedGoal(this, walkSpeed)); - goalSelector.addGoal(4, new TemptGoal(this, 0.3f, Item::carrotOnAStick_Id, false)); - goalSelector.addGoal(4, new TemptGoal(this, 0.25f, Item::carrots_Id, false)); - goalSelector.addGoal(5, new FollowParentGoal(this, 0.28f)); - goalSelector.addGoal(6, new RandomStrollGoal(this, walkSpeed)); - goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(8, new RandomLookAroundGoal(this)); + getNavigation()->setAvoidWater(true); + float walkSpeed = 0.25f; + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); + goalSelector.addGoal( + 2, controlGoal = new ControlledByPlayerGoal(this, 0.34f, walkSpeed)); + goalSelector.addGoal(3, new BreedGoal(this, walkSpeed)); + goalSelector.addGoal( + 4, new TemptGoal(this, 0.3f, Item::carrotOnAStick_Id, false)); + goalSelector.addGoal(4, + new TemptGoal(this, 0.25f, Item::carrots_Id, false)); + goalSelector.addGoal(5, new FollowParentGoal(this, 0.28f)); + goalSelector.addGoal(6, new RandomStrollGoal(this, walkSpeed)); + goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(8, new RandomLookAroundGoal(this)); } -bool Pig::useNewAi() -{ - return true; +bool Pig::useNewAi() { return true; } + +int Pig::getMaxHealth() { return 10; } + +bool Pig::canBeControlledByRider() { + std::shared_ptr item = + std::dynamic_pointer_cast(rider.lock())->getCarriedItem(); + + return item != NULL && item->id == Item::carrotOnAStick_Id; } -int Pig::getMaxHealth() -{ - return 10; +void Pig::defineSynchedData() { + Animal::defineSynchedData(); + entityData->define(DATA_SADDLE_ID, (uint8_t)0); } -bool Pig::canBeControlledByRider() -{ - std::shared_ptr item = std::dynamic_pointer_cast(rider.lock())->getCarriedItem(); - - return item != NULL && item->id == Item::carrotOnAStick_Id; +void Pig::addAdditonalSaveData(CompoundTag* tag) { + Animal::addAdditonalSaveData(tag); + tag->putBoolean(L"Saddle", hasSaddle()); } -void Pig::defineSynchedData() -{ - Animal::defineSynchedData(); - entityData->define(DATA_SADDLE_ID, (uint8_t) 0); +void Pig::readAdditionalSaveData(CompoundTag* tag) { + Animal::readAdditionalSaveData(tag); + setSaddle(tag->getBoolean(L"Saddle")); } -void Pig::addAdditonalSaveData(CompoundTag *tag) -{ - Animal::addAdditonalSaveData(tag); - tag->putBoolean(L"Saddle", hasSaddle()); +int Pig::getAmbientSound() { return eSoundType_MOB_PIG_AMBIENT; } + +int Pig::getHurtSound() { return eSoundType_MOB_PIG_AMBIENT; } + +int Pig::getDeathSound() { return eSoundType_MOB_PIG_DEATH; } + +bool Pig::interact(std::shared_ptr player) { + if (!Animal::interact(player)) { + if (hasSaddle() && !level->isClientSide && + (rider.lock() == NULL || rider.lock() == player)) { + // 4J HEG - Fixed issue with player not being able to dismount pig + // (issue #4479) + player->ride(rider.lock() == player ? nullptr : shared_from_this()); + return true; + } + return false; + } + return true; } -void Pig::readAdditionalSaveData(CompoundTag *tag) -{ - Animal::readAdditionalSaveData(tag); - setSaddle(tag->getBoolean(L"Saddle")); +int Pig::getDeathLoot() { + if (this->isOnFire()) return Item::porkChop_cooked->id; + return Item::porkChop_raw_Id; } -int Pig::getAmbientSound() -{ - return eSoundType_MOB_PIG_AMBIENT; +void Pig::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int count = random->nextInt(3) + 1 + random->nextInt(1 + playerBonusLevel); + + for (int i = 0; i < count; i++) { + if (isOnFire()) { + spawnAtLocation(Item::porkChop_cooked_Id, 1); + } else { + spawnAtLocation(Item::porkChop_raw_Id, 1); + } + } + if (hasSaddle()) spawnAtLocation(Item::saddle_Id, 1); } -int Pig::getHurtSound() -{ - return eSoundType_MOB_PIG_AMBIENT; +bool Pig::hasSaddle() { return (entityData->getByte(DATA_SADDLE_ID) & 1) != 0; } + +void Pig::setSaddle(bool value) { + if (value) { + entityData->set(DATA_SADDLE_ID, (uint8_t)1); + } else { + entityData->set(DATA_SADDLE_ID, (uint8_t)0); + } } -int Pig::getDeathSound() -{ - return eSoundType_MOB_PIG_DEATH; +void Pig::thunderHit(const LightningBolt* lightningBolt) { + if (level->isClientSide) return; + std::shared_ptr pz = + std::shared_ptr(new PigZombie(level)); + pz->moveTo(x, y, z, yRot, xRot); + level->addEntity(pz); + remove(); } -bool Pig::interact(std::shared_ptr player) -{ - if(!Animal::interact(player)) - { - if (hasSaddle() && !level->isClientSide && (rider.lock() == NULL || rider.lock() == player)) - { - // 4J HEG - Fixed issue with player not being able to dismount pig (issue #4479) - player->ride( rider.lock() == player ? nullptr : shared_from_this() ); - return true; - } - return false; - } - return true; +void Pig::causeFallDamage(float distance) { + Animal::causeFallDamage(distance); + if (distance > 5 && + std::dynamic_pointer_cast(rider.lock()) != NULL) { + (std::dynamic_pointer_cast(rider.lock())) + ->awardStat(GenericStats::flyPig(), GenericStats::param_flyPig()); + } } -int Pig::getDeathLoot() -{ - if (this->isOnFire() ) return Item::porkChop_cooked->id; - return Item::porkChop_raw_Id; +std::shared_ptr Pig::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + return std::shared_ptr(new Pig(level)); + } else { + return nullptr; + } } -void Pig::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int count = random->nextInt(3) + 1 + random->nextInt(1 + playerBonusLevel); - - for (int i = 0; i < count; i++) - { - if (isOnFire()) - { - spawnAtLocation(Item::porkChop_cooked_Id, 1); - } - else - { - spawnAtLocation(Item::porkChop_raw_Id, 1); - } - } - if (hasSaddle()) spawnAtLocation(Item::saddle_Id, 1); +bool Pig::isFood(std::shared_ptr itemInstance) { + return itemInstance != NULL && itemInstance->id == Item::carrots_Id; } -bool Pig::hasSaddle() -{ - return (entityData->getByte(DATA_SADDLE_ID) & 1) != 0; -} - -void Pig::setSaddle(bool value) -{ - if (value) - { - entityData->set(DATA_SADDLE_ID, (uint8_t) 1); - } - else - { - entityData->set(DATA_SADDLE_ID, (uint8_t) 0); - } -} - -void Pig::thunderHit(const LightningBolt *lightningBolt) -{ - if (level->isClientSide) return; - std::shared_ptr pz = std::shared_ptr( new PigZombie(level) ); - pz->moveTo(x, y, z, yRot, xRot); - level->addEntity(pz); - remove(); -} - -void Pig::causeFallDamage(float distance) -{ - Animal::causeFallDamage(distance); - if (distance > 5 && std::dynamic_pointer_cast( rider.lock() ) != NULL) - { - (std::dynamic_pointer_cast(rider.lock()))->awardStat(GenericStats::flyPig(),GenericStats::param_flyPig()); - } -} - -std::shared_ptr Pig::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to number of animals that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - return std::shared_ptr( new Pig(level) ); - } - else - { - return nullptr; - } -} - -bool Pig::isFood(std::shared_ptr itemInstance) -{ - return itemInstance != NULL && itemInstance->id == Item::carrots_Id; -} - -ControlledByPlayerGoal *Pig::getControlGoal() -{ - return controlGoal; -} +ControlledByPlayerGoal* Pig::getControlGoal() { return controlGoal; } diff --git a/Minecraft.World/Entities/Mobs/Pig.h b/Minecraft.World/Entities/Mobs/Pig.h index 9bf64348d..8ceefe513 100644 --- a/Minecraft.World/Entities/Mobs/Pig.h +++ b/Minecraft.World/Entities/Mobs/Pig.h @@ -1,58 +1,57 @@ #pragma once - - #include "Animal.h" class Player; class LightningBolt; class ControlledByPlayerGoal; -class Pig : public Animal -{ +class Pig : public Animal { public: - eINSTANCEOF GetType() { return eTYPE_PIG; } - static Entity *create(Level *level) { return new Pig(level); } + eINSTANCEOF GetType() { return eTYPE_PIG; } + static Entity* create(Level* level) { return new Pig(level); } + private: - static const int DATA_SADDLE_ID = 16; - ControlledByPlayerGoal *controlGoal; + static const int DATA_SADDLE_ID = 16; + ControlledByPlayerGoal* controlGoal; public: - Pig(Level *level); + Pig(Level* level); - virtual bool useNewAi(); - virtual int getMaxHealth(); - virtual bool canBeControlledByRider(); + virtual bool useNewAi(); + virtual int getMaxHealth(); + virtual bool canBeControlledByRider(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - virtual bool interact(std::shared_ptr player); + virtual bool interact(std::shared_ptr player); protected: - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - bool hasSaddle(); - void setSaddle(bool value); - virtual void thunderHit(const LightningBolt *lightningBolt); + bool hasSaddle(); + void setSaddle(bool value); + virtual void thunderHit(const LightningBolt* lightningBolt); protected: - virtual void causeFallDamage(float distance); + virtual void causeFallDamage(float distance); public: - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); - bool isFood(std::shared_ptr itemInstance); - ControlledByPlayerGoal *getControlGoal(); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); + bool isFood(std::shared_ptr itemInstance); + ControlledByPlayerGoal* getControlGoal(); }; diff --git a/Minecraft.World/Entities/Mobs/PigZombie.cpp b/Minecraft.World/Entities/Mobs/PigZombie.cpp index a522ca167..240b95008 100644 --- a/Minecraft.World/Entities/Mobs/PigZombie.cpp +++ b/Minecraft.World/Entities/Mobs/PigZombie.cpp @@ -12,88 +12,79 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" - - std::shared_ptr PigZombie::sword; -void PigZombie::staticCtor() -{ - PigZombie::sword = std::shared_ptr( new ItemInstance(Item::sword_gold, 1) ); +void PigZombie::staticCtor() { + PigZombie::sword = + std::shared_ptr(new ItemInstance(Item::sword_gold, 1)); } -void PigZombie::_init() -{ - angerTime = 0; - playAngrySoundIn = 0; +void PigZombie::_init() { + angerTime = 0; + playAngrySoundIn = 0; } -PigZombie::PigZombie(Level *level) : Zombie( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called +PigZombie::PigZombie(Level* level) : Zombie(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called - // 4J Stu - Zombie has already called this, and we don't override it so the Zombie one is the most derived version anyway - //this->defineSynchedData(); + // 4J Stu - Zombie has already called this, and we don't override it so the + // Zombie one is the most derived version anyway + // this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); _init(); - this->textureIdx = TN_MOB_PIGZOMBIE; // 4J was L"/mob/pigzombie.png"; + this->textureIdx = TN_MOB_PIGZOMBIE; // 4J was L"/mob/pigzombie.png"; runSpeed = 0.5f; attackDamage = 5; this->fireImmune = true; } -bool PigZombie::useNewAi() -{ - return false; -} +bool PigZombie::useNewAi() { return false; } -int PigZombie::getTexture() -{ - return textureIdx; -} +int PigZombie::getTexture() { return textureIdx; } -void PigZombie::tick() -{ +void PigZombie::tick() { runSpeed = attackTarget != NULL ? 0.95f : 0.5f; - if (playAngrySoundIn > 0) - { - if (--playAngrySoundIn == 0) - { - level->playSound(shared_from_this(), eSoundType_MOB_ZOMBIEPIG_ZPIGANGRY, getSoundVolume() * 2, ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) * 1.8f); + if (playAngrySoundIn > 0) { + if (--playAngrySoundIn == 0) { + level->playSound( + shared_from_this(), eSoundType_MOB_ZOMBIEPIG_ZPIGANGRY, + getSoundVolume() * 2, + ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) * + 1.8f); } } Zombie::tick(); } -bool PigZombie::canSpawn() -{ - return level->difficulty > Difficulty::PEACEFUL && level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb); +bool PigZombie::canSpawn() { + return level->difficulty > Difficulty::PEACEFUL && + level->isUnobstructed(bb) && + level->getCubes(shared_from_this(), bb)->empty() && + !level->containsAnyLiquid(bb); } -void PigZombie::addAdditonalSaveData(CompoundTag *tag) -{ +void PigZombie::addAdditonalSaveData(CompoundTag* tag) { Zombie::addAdditonalSaveData(tag); - tag->putShort(L"Anger", (short) angerTime); + tag->putShort(L"Anger", (short)angerTime); } -void PigZombie::readAdditionalSaveData(CompoundTag *tag) -{ +void PigZombie::readAdditionalSaveData(CompoundTag* tag) { Zombie::readAdditionalSaveData(tag); angerTime = tag->getShort(L"Anger"); } -std::shared_ptr PigZombie::findAttackTarget() -{ +std::shared_ptr PigZombie::findAttackTarget() { #ifndef _FINAL_BUILD #ifdef _DEBUG_MENUS_ENABLED - if(app.GetMobsDontAttackEnabled()) - { - return std::shared_ptr(); - } + if (app.GetMobsDontAttackEnabled()) { + return std::shared_ptr(); + } #endif #endif @@ -101,19 +92,17 @@ std::shared_ptr PigZombie::findAttackTarget() return Zombie::findAttackTarget(); } -bool PigZombie::hurt(DamageSource *source, int dmg) -{ - std::shared_ptr sourceEntity = source->getEntity(); - if (std::dynamic_pointer_cast(sourceEntity) != NULL) - { - std::vector > *nearby = level->getEntities( shared_from_this(), bb->grow(32, 32, 32)); - AUTO_VAR(itEnd, nearby->end()); - for (AUTO_VAR(it, nearby->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //nearby->at(i); - if (std::dynamic_pointer_cast(e) != NULL) - { - std::shared_ptr pigZombie = std::dynamic_pointer_cast(e); +bool PigZombie::hurt(DamageSource* source, int dmg) { + std::shared_ptr sourceEntity = source->getEntity(); + if (std::dynamic_pointer_cast(sourceEntity) != NULL) { + std::vector >* nearby = + level->getEntities(shared_from_this(), bb->grow(32, 32, 32)); + AUTO_VAR(itEnd, nearby->end()); + for (AUTO_VAR(it, nearby->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // nearby->at(i); + if (std::dynamic_pointer_cast(e) != NULL) { + std::shared_ptr pigZombie = + std::dynamic_pointer_cast(e); pigZombie->alert(sourceEntity); } } @@ -122,81 +111,55 @@ bool PigZombie::hurt(DamageSource *source, int dmg) return Zombie::hurt(source, dmg); } -void PigZombie::alert(std::shared_ptr target) -{ +void PigZombie::alert(std::shared_ptr target) { this->attackTarget = target; angerTime = 20 * 20 + random->nextInt(20 * 20); playAngrySoundIn = random->nextInt(20 * 2); } -int PigZombie::getAmbientSound() -{ - return eSoundType_MOB_ZOMBIEPIG_AMBIENT; +int PigZombie::getAmbientSound() { return eSoundType_MOB_ZOMBIEPIG_AMBIENT; } + +int PigZombie::getHurtSound() { return eSoundType_MOB_ZOMBIEPIG_HURT; } + +int PigZombie::getDeathSound() { return eSoundType_MOB_ZOMBIEPIG_DEATH; } + +void PigZombie::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int count = random->nextInt(2 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::rotten_flesh_Id, 1); + } + count = random->nextInt(2 + playerBonusLevel); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::goldNugget_Id, 1); + } } -int PigZombie::getHurtSound() -{ - return eSoundType_MOB_ZOMBIEPIG_HURT; +void PigZombie::dropRareDeathLoot(int rareLootLevel) { + if (rareLootLevel > 0) { + std::shared_ptr sword = + std::shared_ptr(new ItemInstance(Item::sword_gold)); + EnchantmentHelper::enchantItem(random, sword, 5); + spawnAtLocation(sword, 0); + } else { + int select = random->nextInt(3); + if (select == 0) { + spawnAtLocation(Item::goldIngot_Id, 1); + } else if (select == 1) { + spawnAtLocation(Item::sword_gold_Id, 1); + } else if (select == 2) { + spawnAtLocation(Item::helmet_gold_Id, 1); + } + } } -int PigZombie::getDeathSound() -{ - return eSoundType_MOB_ZOMBIEPIG_DEATH; +int PigZombie::getDeathLoot() { return Item::rotten_flesh_Id; } + +void PigZombie::finalizeMobSpawn() { + Zombie::finalizeMobSpawn(); + setVillager(false); } -void PigZombie::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int count = random->nextInt(2 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::rotten_flesh_Id, 1); - } - count = random->nextInt(2 + playerBonusLevel); - for (int i = 0; i < count; i++) - { - spawnAtLocation(Item::goldNugget_Id, 1); - } -} - -void PigZombie::dropRareDeathLoot(int rareLootLevel) -{ - if (rareLootLevel > 0) - { - std::shared_ptr sword = std::shared_ptr( new ItemInstance(Item::sword_gold) ); - EnchantmentHelper::enchantItem(random, sword, 5); - spawnAtLocation(sword, 0); - } - else - { - int select = random->nextInt(3); - if (select == 0) - { - spawnAtLocation(Item::goldIngot_Id, 1); - } - else if (select == 1) - { - spawnAtLocation(Item::sword_gold_Id, 1); - } - else if (select == 2) - { - spawnAtLocation(Item::helmet_gold_Id, 1); - } - } -} - -int PigZombie::getDeathLoot() -{ - return Item::rotten_flesh_Id; -} - -void PigZombie::finalizeMobSpawn() -{ - Zombie::finalizeMobSpawn(); - setVillager(false); -} - -std::shared_ptr PigZombie::getCarriedItem() -{ - // TODO 4J - could be of const std::shared_ptr type. - return (std::shared_ptr ) sword; +std::shared_ptr PigZombie::getCarriedItem() { + // TODO 4J - could be of const std::shared_ptr type. + return (std::shared_ptr)sword; } diff --git a/Minecraft.World/Entities/Mobs/PigZombie.h b/Minecraft.World/Entities/Mobs/PigZombie.h index 796c6ad9a..63bcfd98c 100644 --- a/Minecraft.World/Entities/Mobs/PigZombie.h +++ b/Minecraft.World/Entities/Mobs/PigZombie.h @@ -1,60 +1,58 @@ #pragma once - #include "Zombie.h" class DamageSource; -// SKIN BY XaPhobia Chris Beidler -class PigZombie : public Zombie -{ +// SKIN BY XaPhobia Chris Beidler +class PigZombie : public Zombie { public: - eINSTANCEOF GetType() { return eTYPE_PIGZOMBIE; } - static Entity *create(Level *level) { return new PigZombie(level); } + eINSTANCEOF GetType() { return eTYPE_PIGZOMBIE; } + static Entity* create(Level* level) { return new PigZombie(level); } private: - int angerTime; + int angerTime; int playAngrySoundIn; - void _init(); + void _init(); public: - PigZombie(Level *level); + PigZombie(Level* level); protected: - bool useNewAi(); + bool useNewAi(); public: - virtual int getTexture(); + virtual int getTexture(); virtual void tick(); virtual bool canSpawn(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual std::shared_ptr findAttackTarget(); + virtual std::shared_ptr findAttackTarget(); public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); private: - void alert(std::shared_ptr target); + void alert(std::shared_ptr target); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); - virtual void dropRareDeathLoot(int rareLootLevel); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual void dropRareDeathLoot(int rareLootLevel); virtual int getDeathLoot(); private: - static std::shared_ptr sword; + static std::shared_ptr sword; public: - virtual void finalizeMobSpawn(); + virtual void finalizeMobSpawn(); - std::shared_ptr getCarriedItem(); + std::shared_ptr getCarriedItem(); - static void staticCtor(); + static void staticCtor(); }; diff --git a/Minecraft.World/Entities/Mobs/PrimedTnt.cpp b/Minecraft.World/Entities/Mobs/PrimedTnt.cpp index 2c0c4062d..4eda5e6f4 100644 --- a/Minecraft.World/Entities/Mobs/PrimedTnt.cpp +++ b/Minecraft.World/Entities/Mobs/PrimedTnt.cpp @@ -4,113 +4,85 @@ #include "../../Headers/net.minecraft.world.level.h" #include "PrimedTnt.h" +void PrimedTnt::_init() { + life = 0; - -void PrimedTnt::_init() -{ - life = 0; - - // Original Java Ctor - blocksBuilding = true; - setSize(0.98f, 0.98f); - heightOffset = bbHeight / 2.0f; + // Original Java Ctor + blocksBuilding = true; + setSize(0.98f, 0.98f); + heightOffset = bbHeight / 2.0f; } -PrimedTnt::PrimedTnt(Level *level) : Entity( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +PrimedTnt::PrimedTnt(Level* level) : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - _init(); + _init(); } -PrimedTnt::PrimedTnt(Level *level, double x, double y, double z) : Entity( level ) -{ - _init(); +PrimedTnt::PrimedTnt(Level* level, double x, double y, double z) + : Entity(level) { + _init(); - setPos(x, y, z); + setPos(x, y, z); - float rot = (float) (Math::random() * PI * 2); - xd = -sin(rot) * 0.02f; - yd = +0.2f; - zd = -cos(rot) * 0.02f; + float rot = (float)(Math::random() * PI * 2); + xd = -sin(rot) * 0.02f; + yd = +0.2f; + zd = -cos(rot) * 0.02f; - life = 80; + life = 80; - xo = x; - yo = y; - zo = z; + xo = x; + yo = y; + zo = z; } -void PrimedTnt::defineSynchedData() -{ +void PrimedTnt::defineSynchedData() {} + +bool PrimedTnt::makeStepSound() { return false; } + +bool PrimedTnt::isPickable() { return !removed; } + +void PrimedTnt::tick() { + xo = x; + yo = y; + zo = z; + + yd -= 0.04f; + move(xd, yd, zd); + xd *= 0.98f; + yd *= 0.98f; + zd *= 0.98f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + yd *= -0.5f; + } + + if (life-- <= 0) { + remove(); + if (!level->isClientSide) { + explode(); + } + } else { + level->addParticle(eParticleType_smoke, x, y + 0.5f, z, 0, 0, 0); + } } -bool PrimedTnt::makeStepSound() -{ - return false; +void PrimedTnt::explode() { + float r = 4.0f; + level->explode(nullptr, x, y, z, r, true); } -bool PrimedTnt::isPickable() -{ - return !removed; +void PrimedTnt::addAdditonalSaveData(CompoundTag* entityTag) { + entityTag->putByte(L"Fuse", (uint8_t)life); } -void PrimedTnt::tick() -{ - xo = x; - yo = y; - zo = z; - - yd -= 0.04f; - move(xd, yd, zd); - xd *= 0.98f; - yd *= 0.98f; - zd *= 0.98f; - - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - yd *= -0.5f; - } - - if (life-- <= 0) - { - remove(); - if (!level->isClientSide) - { - explode(); - } - } - else - { - level->addParticle(eParticleType_smoke, x, y + 0.5f, z, 0, 0, 0); - } - +void PrimedTnt::readAdditionalSaveData(CompoundTag* tag) { + life = tag->getByte(L"Fuse"); } - -void PrimedTnt::explode() -{ - float r = 4.0f; - level->explode(nullptr, x, y, z, r, true); -} - - -void PrimedTnt::addAdditonalSaveData(CompoundTag *entityTag) -{ - entityTag->putByte(L"Fuse", (uint8_t) life); -} - -void PrimedTnt::readAdditionalSaveData(CompoundTag *tag) -{ - life = tag->getByte(L"Fuse"); -} - - -float PrimedTnt::getShadowHeightOffs() -{ - return 0; -} \ No newline at end of file +float PrimedTnt::getShadowHeightOffs() { return 0; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/PrimedTnt.h b/Minecraft.World/Entities/Mobs/PrimedTnt.h index d6b4f1564..abb4d3c94 100644 --- a/Minecraft.World/Entities/Mobs/PrimedTnt.h +++ b/Minecraft.World/Entities/Mobs/PrimedTnt.h @@ -1,37 +1,36 @@ #pragma once #include "../Entity.h" -class PrimedTnt : public Entity -{ +class PrimedTnt : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_PRIMEDTNT; }; - static Entity *create(Level *level) { return new PrimedTnt(level); } + eINSTANCEOF GetType() { return eTYPE_PRIMEDTNT; }; + static Entity* create(Level* level) { return new PrimedTnt(level); } public: - static const int serialVersionUID = 0; + static const int serialVersionUID = 0; - int life; + int life; - void _init(); + void _init(); - PrimedTnt(Level *level); - PrimedTnt(Level *level, double x, double y, double z); + PrimedTnt(Level* level); + PrimedTnt(Level* level, double x, double y, double z); protected: - virtual void defineSynchedData(); - virtual bool makeStepSound(); + virtual void defineSynchedData(); + virtual bool makeStepSound(); public: - virtual bool isPickable(); - virtual void tick(); + virtual bool isPickable(); + virtual void tick(); private: - void explode(); + void explode(); protected: - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); public: - virtual float getShadowHeightOffs(); + virtual float getShadowHeightOffs(); }; diff --git a/Minecraft.World/Entities/Mobs/Sheep.cpp b/Minecraft.World/Entities/Mobs/Sheep.cpp index 09692cbff..2fa6192cf 100644 --- a/Minecraft.World/Entities/Mobs/Sheep.cpp +++ b/Minecraft.World/Entities/Mobs/Sheep.cpp @@ -20,170 +20,154 @@ #include "../MobCategory.h" #include "../../Stats/GenericStats.h" -const float Sheep::COLOR[][3] = -{ - { 1.0f, 1.0f, 1.0f }, // white - { 0.85f, 0.5f, 0.2f }, // orange - { 0.7f, 0.3f, 0.85f }, // magenta - { 0.4f, 0.6f, 0.85f }, // light blue - { 0.9f, 0.9f, 0.2f }, // yellow - { 0.5f, 0.8f, 0.1f }, // light green - { 0.95f, 0.5f, 0.65f }, // pink - { 0.3f, 0.3f, 0.3f }, // gray - { 0.6f, 0.6f, 0.6f }, // silver - { 0.3f, 0.5f, 0.65f }, // cyan - { 0.5f, 0.25f, 0.7f }, // purple - { 0.2f, 0.3f, 0.7f }, // blue - { 0.4f, 0.3f, 0.2f }, // brown - { 0.4f, 0.5f, 0.2f }, // green - { 0.6f, 0.2f, 0.2f }, // red - { 0.1f, 0.1f, 0.1f }, // black +const float Sheep::COLOR[][3] = { + {1.0f, 1.0f, 1.0f}, // white + {0.85f, 0.5f, 0.2f}, // orange + {0.7f, 0.3f, 0.85f}, // magenta + {0.4f, 0.6f, 0.85f}, // light blue + {0.9f, 0.9f, 0.2f}, // yellow + {0.5f, 0.8f, 0.1f}, // light green + {0.95f, 0.5f, 0.65f}, // pink + {0.3f, 0.3f, 0.3f}, // gray + {0.6f, 0.6f, 0.6f}, // silver + {0.3f, 0.5f, 0.65f}, // cyan + {0.5f, 0.25f, 0.7f}, // purple + {0.2f, 0.3f, 0.7f}, // blue + {0.4f, 0.3f, 0.2f}, // brown + {0.4f, 0.5f, 0.2f}, // green + {0.6f, 0.2f, 0.2f}, // red + {0.1f, 0.1f, 0.1f}, // black }; -Sheep::Sheep(Level *level) : Animal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Sheep::Sheep(Level* level) : Animal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - this->textureIdx = TN_MOB_SHEEP; // 4J - was L"/mob/sheep.png"; - this->setSize(0.9f, 1.3f); + this->textureIdx = TN_MOB_SHEEP; // 4J - was L"/mob/sheep.png"; + this->setSize(0.9f, 1.3f); - eatAnimationTick = 0; + eatAnimationTick = 0; - eatTileGoal = new EatTileGoal(this); + eatTileGoal = new EatTileGoal(this); - float walkSpeed = 0.23f; - getNavigation()->setAvoidWater(true); - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); - goalSelector.addGoal(2, new BreedGoal(this, walkSpeed)); - goalSelector.addGoal(3, new TemptGoal(this, 0.25f, Item::wheat_Id, false)); - goalSelector.addGoal(4, new FollowParentGoal(this, 0.25f)); - goalSelector.addGoal(5, eatTileGoal, false); - goalSelector.addGoal(6, new RandomStrollGoal(this, walkSpeed)); - goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(8, new RandomLookAroundGoal(this)); + float walkSpeed = 0.23f; + getNavigation()->setAvoidWater(true); + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal(1, new PanicGoal(this, 0.38f)); + goalSelector.addGoal(2, new BreedGoal(this, walkSpeed)); + goalSelector.addGoal(3, new TemptGoal(this, 0.25f, Item::wheat_Id, false)); + goalSelector.addGoal(4, new FollowParentGoal(this, 0.25f)); + goalSelector.addGoal(5, eatTileGoal, false); + goalSelector.addGoal(6, new RandomStrollGoal(this, walkSpeed)); + goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(8, new RandomLookAroundGoal(this)); - container = std::shared_ptr(new CraftingContainer(new SheepContainer(), 2, 1)); - container->setItem(0, std::shared_ptr( new ItemInstance(Item::dye_powder, 1, 0))); - container->setItem(1, std::shared_ptr( new ItemInstance(Item::dye_powder, 1, 0))); + container = std::shared_ptr( + new CraftingContainer(new SheepContainer(), 2, 1)); + container->setItem(0, std::shared_ptr( + new ItemInstance(Item::dye_powder, 1, 0))); + container->setItem(1, std::shared_ptr( + new ItemInstance(Item::dye_powder, 1, 0))); } -bool Sheep::useNewAi() -{ - return true; +bool Sheep::useNewAi() { return true; } + +void Sheep::newServerAiStep() { + eatAnimationTick = eatTileGoal->getEatAnimationTick(); + Animal::newServerAiStep(); } -void Sheep::newServerAiStep() -{ - eatAnimationTick = eatTileGoal->getEatAnimationTick(); - Animal::newServerAiStep(); +void Sheep::aiStep() { + if (level->isClientSide) + eatAnimationTick = std::max(0, eatAnimationTick - 1); + Animal::aiStep(); } -void Sheep::aiStep() -{ - if (level->isClientSide) eatAnimationTick = std::max(0, eatAnimationTick - 1); - Animal::aiStep(); +int Sheep::getMaxHealth() { return 8; } + +void Sheep::defineSynchedData() { + Animal::defineSynchedData(); + + // sheared and color share a byte + entityData->define(DATA_WOOL_ID, + ((uint8_t)0)); // was new Byte((uint8_t), 0) } -int Sheep::getMaxHealth() -{ - return 8; +void Sheep::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + if (!isSheared()) { + // killing a non-sheared sheep will drop a single block of cloth + spawnAtLocation(std::shared_ptr( + new ItemInstance(Tile::cloth_Id, 1, getColor())), + 0.0f); + } } -void Sheep::defineSynchedData() -{ - Animal::defineSynchedData(); +int Sheep::getDeathLoot() { return Tile::cloth_Id; } - // sheared and color share a byte - entityData->define(DATA_WOOL_ID, ((uint8_t) 0)); //was new Byte((uint8_t), 0) +void Sheep::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::EAT_GRASS) { + eatAnimationTick = EAT_ANIMATION_TICKS; + } else { + Animal::handleEntityEvent(id); + } } -void Sheep::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - if(!isSheared()) - { - // killing a non-sheared sheep will drop a single block of cloth - spawnAtLocation(std::shared_ptr( new ItemInstance(Tile::cloth_Id, 1, getColor()) ), 0.0f); - } +float Sheep::getHeadEatPositionScale(float a) { + if (eatAnimationTick <= 0) { + return 0; + } + if (eatAnimationTick >= 4 && + eatAnimationTick <= (EAT_ANIMATION_TICKS - 4)) { + return 1; + } + if (eatAnimationTick < 4) { + return ((float)eatAnimationTick - a) / 4.0f; + } + return -((float)(eatAnimationTick - EAT_ANIMATION_TICKS) - a) / 4.0f; } -int Sheep::getDeathLoot() -{ - return Tile::cloth_Id; +float Sheep::getHeadEatAngleScale(float a) { + if (eatAnimationTick > 4 && eatAnimationTick <= (EAT_ANIMATION_TICKS - 4)) { + float scale = ((float)(eatAnimationTick - 4) - a) / + (float)(EAT_ANIMATION_TICKS - 8); + return PI * .20f + PI * .07f * Mth::sin(scale * 28.7f); + } + if (eatAnimationTick > 0) { + return PI * .20f; + } + return ((xRot / (180.0f / PI))); } -void Sheep::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::EAT_GRASS) - { - eatAnimationTick = EAT_ANIMATION_TICKS; - } - else - { - Animal::handleEntityEvent(id); - } -} - -float Sheep::getHeadEatPositionScale(float a) -{ - if (eatAnimationTick <= 0) - { - return 0; - } - if (eatAnimationTick >= 4 && eatAnimationTick <= (EAT_ANIMATION_TICKS - 4)) - { - return 1; - } - if (eatAnimationTick < 4) - { - return ((float) eatAnimationTick - a) / 4.0f; - } - return -((float) (eatAnimationTick - EAT_ANIMATION_TICKS) - a) / 4.0f; -} - -float Sheep::getHeadEatAngleScale(float a) -{ - if (eatAnimationTick > 4 && eatAnimationTick <= (EAT_ANIMATION_TICKS - 4)) - { - float scale = ((float) (eatAnimationTick - 4) - a) / (float) (EAT_ANIMATION_TICKS - 8); - return PI * .20f + PI * .07f * Mth::sin(scale * 28.7f); - } - if (eatAnimationTick > 0) - { - return PI * .20f; - } - return ((xRot / (180.0f / PI))); -} - -bool Sheep::interact(std::shared_ptr player) -{ +bool Sheep::interact(std::shared_ptr player) { std::shared_ptr item = player->inventory->getSelected(); - // 4J-JEV: Fix for #88212, - // Untrusted players shouldn't be able to sheer sheep. - if (!player->isAllowedToInteract( shared_from_this() )) - return false; //Animal::interact(player); + // 4J-JEV: Fix for #88212, + // Untrusted players shouldn't be able to sheer sheep. + if (!player->isAllowedToInteract(shared_from_this())) + return false; // Animal::interact(player); - if (item != NULL && item->id == Item::shears->id && !isSheared() && !isBaby()) - { - if (!level->isClientSide) - { + if (item != NULL && item->id == Item::shears->id && !isSheared() && + !isBaby()) { + if (!level->isClientSide) { setSheared(true); int count = 1 + random->nextInt(3); - for (int i = 0; i < count; i++) - { - std::shared_ptr ie = spawnAtLocation(std::shared_ptr( new ItemInstance(Tile::cloth_Id, 1, getColor()) ), 1.0f); + for (int i = 0; i < count; i++) { + std::shared_ptr ie = spawnAtLocation( + std::shared_ptr( + new ItemInstance(Tile::cloth_Id, 1, getColor())), + 1.0f); ie->yd += random->nextFloat() * 0.05f; ie->xd += (random->nextFloat() - random->nextFloat()) * 0.1f; ie->zd += (random->nextFloat() - random->nextFloat()) * 0.1f; } - player->awardStat( GenericStats::shearedEntity(eTYPE_SHEEP), GenericStats::param_shearedEntity(eTYPE_SHEEP) ); + player->awardStat(GenericStats::shearedEntity(eTYPE_SHEEP), + GenericStats::param_shearedEntity(eTYPE_SHEEP)); } item->hurt(1, player); } @@ -191,147 +175,115 @@ bool Sheep::interact(std::shared_ptr player) return Animal::interact(player); } -void Sheep::addAdditonalSaveData(CompoundTag *tag) -{ - Animal::addAdditonalSaveData(tag); - tag->putBoolean(L"Sheared", isSheared()); - tag->putByte(L"Color", (uint8_t) getColor()); +void Sheep::addAdditonalSaveData(CompoundTag* tag) { + Animal::addAdditonalSaveData(tag); + tag->putBoolean(L"Sheared", isSheared()); + tag->putByte(L"Color", (uint8_t)getColor()); } -void Sheep::readAdditionalSaveData(CompoundTag *tag) -{ - Animal::readAdditionalSaveData(tag); - setSheared(tag->getBoolean(L"Sheared")); - setColor((int) tag->getByte(L"Color")); +void Sheep::readAdditionalSaveData(CompoundTag* tag) { + Animal::readAdditionalSaveData(tag); + setSheared(tag->getBoolean(L"Sheared")); + setColor((int)tag->getByte(L"Color")); } -int Sheep::getAmbientSound() -{ - return eSoundType_MOB_SHEEP_AMBIENT; +int Sheep::getAmbientSound() { return eSoundType_MOB_SHEEP_AMBIENT; } + +int Sheep::getHurtSound() { return eSoundType_MOB_SHEEP_AMBIENT; } + +int Sheep::getDeathSound() { return eSoundType_MOB_SHEEP_AMBIENT; } + +int Sheep::getColor() { return (entityData->getByte(DATA_WOOL_ID) & 0x0f); } + +void Sheep::setColor(int color) { + uint8_t current = entityData->getByte(DATA_WOOL_ID); + entityData->set(DATA_WOOL_ID, (uint8_t)((current & 0xf0) | (color & 0x0f))); } -int Sheep::getHurtSound() -{ - return eSoundType_MOB_SHEEP_AMBIENT; +bool Sheep::isSheared() { + return (entityData->getByte(DATA_WOOL_ID) & 0x10) != 0; } -int Sheep::getDeathSound() -{ - return eSoundType_MOB_SHEEP_AMBIENT; +void Sheep::setSheared(bool value) { + uint8_t current = entityData->getByte(DATA_WOOL_ID); + if (value) { + entityData->set(DATA_WOOL_ID, (uint8_t)(current | 0x10)); + } else { + entityData->set(DATA_WOOL_ID, (uint8_t)(current & ~0x10)); + } } -int Sheep::getColor() -{ - return (entityData->getByte(DATA_WOOL_ID) & 0x0f); +int Sheep::getSheepColor(Random* random) { + int nextInt = random->nextInt(100); + if (nextInt < 5) { + return 15 - DyePowderItem::BLACK; + } + if (nextInt < 10) { + return 15 - DyePowderItem::GRAY; + } + if (nextInt < 15) { + return 15 - DyePowderItem::SILVER; + } + if (nextInt < 18) { + return 15 - DyePowderItem::BROWN; + } + if (random->nextInt(500) == 0) return 15 - DyePowderItem::PINK; + return 0; // white } -void Sheep::setColor(int color) -{ - uint8_t current = entityData->getByte(DATA_WOOL_ID); - entityData->set(DATA_WOOL_ID, (uint8_t) ((current & 0xf0) | (color & 0x0f))); +std::shared_ptr Sheep::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to number of animals that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + std::shared_ptr otherSheep = + std::dynamic_pointer_cast(target); + std::shared_ptr sheep = std::shared_ptr(new Sheep(level)); + int color = getOffspringColor( + std::dynamic_pointer_cast(shared_from_this()), otherSheep); + sheep->setColor(15 - color); + return sheep; + } else { + return nullptr; + } } -bool Sheep::isSheared() -{ - return (entityData->getByte(DATA_WOOL_ID) & 0x10) != 0; +void Sheep::ate() { + setSheared(false); + if (isBaby()) { + // remove a minute from aging + int age = getAge() + SharedConstants::TICKS_PER_SECOND * 60; + if (age > 0) { + age = 0; + } + setAge(age); + } } -void Sheep::setSheared(bool value) -{ - uint8_t current = entityData->getByte(DATA_WOOL_ID); - if (value) - { - entityData->set(DATA_WOOL_ID, (uint8_t) (current | 0x10)); - } - else - { - entityData->set(DATA_WOOL_ID, (uint8_t) (current & ~0x10)); - } +void Sheep::finalizeMobSpawn() { + setColor(Sheep::getSheepColor(level->random)); } -int Sheep::getSheepColor(Random *random) -{ - int nextInt = random->nextInt(100); - if (nextInt < 5) - { - return 15 - DyePowderItem::BLACK; - } - if (nextInt < 10) - { - return 15 - DyePowderItem::GRAY; - } - if (nextInt < 15) - { - return 15 - DyePowderItem::SILVER; - } - if (nextInt < 18) - { - return 15 - DyePowderItem::BROWN; - } - if (random->nextInt(500) == 0) return 15 - DyePowderItem::PINK; - return 0; // white +int Sheep::getOffspringColor(std::shared_ptr animal, + std::shared_ptr partner) { + int parent1DyeColor = getDyeColor(animal); + int parent2DyeColor = getDyeColor(partner); + + container->getItem(0)->setAuxValue(parent1DyeColor); + container->getItem(1)->setAuxValue(parent2DyeColor); + + std::shared_ptr instance = + Recipes::getInstance()->getItemFor(container, animal->level); + + int color = 0; + if (instance != NULL && instance->getItem()->id == Item::dye_powder_Id) { + color = instance->getAuxValue(); + } else { + color = + level->random->nextBoolean() ? parent1DyeColor : parent2DyeColor; + } + return color; } -std::shared_ptr Sheep::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to number of animals that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - std::shared_ptr otherSheep = std::dynamic_pointer_cast( target ); - std::shared_ptr sheep = std::shared_ptr( new Sheep(level) ); - int color = getOffspringColor(std::dynamic_pointer_cast(shared_from_this()), otherSheep); - sheep->setColor(15 - color); - return sheep; - } - else - { - return nullptr; - } -} - -void Sheep::ate() -{ - setSheared(false); - if (isBaby()) - { - // remove a minute from aging - int age = getAge() + SharedConstants::TICKS_PER_SECOND * 60; - if (age > 0) - { - age = 0; - } - setAge(age); - } -} - -void Sheep::finalizeMobSpawn() -{ - setColor(Sheep::getSheepColor(level->random)); -} - -int Sheep::getOffspringColor(std::shared_ptr animal, std::shared_ptr partner) -{ - int parent1DyeColor = getDyeColor(animal); - int parent2DyeColor = getDyeColor(partner); - - container->getItem(0)->setAuxValue(parent1DyeColor); - container->getItem(1)->setAuxValue(parent2DyeColor); - - std::shared_ptr instance = Recipes::getInstance()->getItemFor(container, animal->level); - - int color = 0; - if (instance != NULL && instance->getItem()->id == Item::dye_powder_Id) - { - color = instance->getAuxValue(); - } - else - { - color = level->random->nextBoolean() ? parent1DyeColor : parent2DyeColor; - } - return color; -} - -int Sheep::getDyeColor(std::shared_ptr animal) -{ - return 15 - std::dynamic_pointer_cast(animal)->getColor(); +int Sheep::getDyeColor(std::shared_ptr animal) { + return 15 - std::dynamic_pointer_cast(animal)->getColor(); } diff --git a/Minecraft.World/Entities/Mobs/Sheep.h b/Minecraft.World/Entities/Mobs/Sheep.h index 819d32e7b..02ae58050 100644 --- a/Minecraft.World/Entities/Mobs/Sheep.h +++ b/Minecraft.World/Entities/Mobs/Sheep.h @@ -1,7 +1,5 @@ #pragma once - - class Random; class EatTileGoal; class CraftingContainer; @@ -10,77 +8,79 @@ class CraftingContainer; #include "../../Util/SharedConstants.h" #include "../../Containers/AbstractContainerMenu.h" -class Sheep : public Animal -{ +class Sheep : public Animal { private: - class SheepContainer : public AbstractContainerMenu - { - bool stillValid(std::shared_ptr player) { return false; } - }; + class SheepContainer : public AbstractContainerMenu { + bool stillValid(std::shared_ptr player) { return false; } + }; + + std::shared_ptr container; - std::shared_ptr container; public: - eINSTANCEOF GetType() { return eTYPE_SHEEP; } - static Entity *create(Level *level) { return new Sheep(level); } + eINSTANCEOF GetType() { return eTYPE_SHEEP; } + static Entity* create(Level* level) { return new Sheep(level); } private: - static const int EAT_ANIMATION_TICKS = SharedConstants::TICKS_PER_SECOND * 2; - static const int DATA_WOOL_ID = 16; + static const int EAT_ANIMATION_TICKS = + SharedConstants::TICKS_PER_SECOND * 2; + static const int DATA_WOOL_ID = 16; - int eatAnimationTick; - EatTileGoal *eatTileGoal; + int eatAnimationTick; + EatTileGoal* eatTileGoal; public: - static const float COLOR[][3]; + static const float COLOR[][3]; public: - Sheep(Level *level); + Sheep(Level* level); protected: - virtual bool useNewAi(); - virtual void newServerAiStep(); + virtual bool useNewAi(); + virtual void newServerAiStep(); public: - void aiStep(); - virtual int getMaxHealth(); + void aiStep(); + virtual int getMaxHealth(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); - virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getDeathLoot(); public: - virtual void handleEntityEvent(uint8_t id); + virtual void handleEntityEvent(uint8_t id); public: - float getHeadEatPositionScale(float a); - float getHeadEatAngleScale(float a); + float getHeadEatPositionScale(float a); + float getHeadEatAngleScale(float a); - virtual bool interact(std::shared_ptr player); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual bool interact(std::shared_ptr player); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - int getColor(); - void setColor(int color); - bool isSheared(); - void setSheared(bool value); + int getColor(); + void setColor(int color); + bool isSheared(); + void setSheared(bool value); - static int getSheepColor(Random *random); - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); + static int getSheepColor(Random* random); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); - virtual void ate(); + virtual void ate(); - void finalizeMobSpawn(); + void finalizeMobSpawn(); private: - int getOffspringColor(std::shared_ptr animal, std::shared_ptr partner); - int getDyeColor(std::shared_ptr animal); + int getOffspringColor(std::shared_ptr animal, + std::shared_ptr partner); + int getDyeColor(std::shared_ptr animal); }; diff --git a/Minecraft.World/Entities/Mobs/Silverfish.cpp b/Minecraft.World/Entities/Mobs/Silverfish.cpp index 5af3777f5..733507b76 100644 --- a/Minecraft.World/Entities/Mobs/Silverfish.cpp +++ b/Minecraft.World/Entities/Mobs/Silverfish.cpp @@ -8,202 +8,178 @@ #include "Silverfish.h" #include "../../Util/SoundTypes.h" -Silverfish::Silverfish(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Silverfish::Silverfish(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - this->textureIdx = TN_MOB_SILVERFISH;// 4J was "/mob/silverfish.png"; - this->setSize(0.3f, 0.7f); - runSpeed = 0.6f; + this->textureIdx = TN_MOB_SILVERFISH; // 4J was "/mob/silverfish.png"; + this->setSize(0.3f, 0.7f); + runSpeed = 0.6f; - // 4J - Brought forward damage from 1.2.3 - attackDamage = 1; + // 4J - Brought forward damage from 1.2.3 + attackDamage = 1; } -int Silverfish::getMaxHealth() -{ - return 8; -} +int Silverfish::getMaxHealth() { return 8; } -bool Silverfish::makeStepSound() -{ - return false; -} +bool Silverfish::makeStepSound() { return false; } -std::shared_ptr Silverfish::findAttackTarget() -{ +std::shared_ptr Silverfish::findAttackTarget() { #ifndef _FINAL_BUILD - if(app.GetMobsDontAttackEnabled()) - { - return std::shared_ptr(); - } + if (app.GetMobsDontAttackEnabled()) { + return std::shared_ptr(); + } #endif - double maxDist = 8; - return level->getNearestAttackablePlayer(shared_from_this(), maxDist); + double maxDist = 8; + return level->getNearestAttackablePlayer(shared_from_this(), maxDist); } -int Silverfish::getAmbientSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_SILVERFISH_AMBIENT; +int Silverfish::getAmbientSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_SILVERFISH_AMBIENT; } -int Silverfish::getHurtSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_SILVERFISH_HURT; +int Silverfish::getHurtSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_SILVERFISH_HURT; } -int Silverfish::getDeathSound() -{ - // 4J - brought sound change forward from 1.2.3 - return eSoundType_MOB_SILVERFISH_DEATH; +int Silverfish::getDeathSound() { + // 4J - brought sound change forward from 1.2.3 + return eSoundType_MOB_SILVERFISH_DEATH; } - -bool Silverfish::hurt(DamageSource *source, int dmg) -{ - if (lookForFriends <= 0 && (dynamic_cast(source) != NULL || source == DamageSource::magic)) - { - // look for friends - lookForFriends = 20; - } - return Monster::hurt(source, dmg); +bool Silverfish::hurt(DamageSource* source, int dmg) { + if (lookForFriends <= 0 && + (dynamic_cast(source) != NULL || + source == DamageSource::magic)) { + // look for friends + lookForFriends = 20; + } + return Monster::hurt(source, dmg); } -void Silverfish::checkHurtTarget(std::shared_ptr target, float d) -{ - - // super.checkHurtTarget(target, d); - if (attackTime <= 0 && d < 1.2f && target->bb->y1 > bb->y0 && target->bb->y0 < bb->y1) - { - attackTime = 20; - DamageSource *damageSource = DamageSource::mobAttack( std::dynamic_pointer_cast( shared_from_this() ) ); - target->hurt(damageSource, attackDamage); - delete damageSource; - } - +void Silverfish::checkHurtTarget(std::shared_ptr target, float d) { + // super.checkHurtTarget(target, d); + if (attackTime <= 0 && d < 1.2f && target->bb->y1 > bb->y0 && + target->bb->y0 < bb->y1) { + attackTime = 20; + DamageSource* damageSource = DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())); + target->hurt(damageSource, attackDamage); + delete damageSource; + } } -void Silverfish::playStepSound(int xt, int yt, int zt, int t) -{ - level->playSound(shared_from_this(), eSoundType_MOB_SILVERFISH_STEP, 1, 1); +void Silverfish::playStepSound(int xt, int yt, int zt, int t) { + level->playSound(shared_from_this(), eSoundType_MOB_SILVERFISH_STEP, 1, 1); } -int Silverfish::getDeathLoot() -{ - return 0; +int Silverfish::getDeathLoot() { return 0; } + +void Silverfish::tick() { + // rotate the whole body to the same angle as the head + yBodyRot = yRot; + + Monster::tick(); } -void Silverfish::tick() -{ - // rotate the whole body to the same angle as the head - yBodyRot = yRot; +void Silverfish::serverAiStep() { + Monster::serverAiStep(); - Monster::tick(); + if (level->isClientSide) { + return; + } + + if (lookForFriends > 0) { + lookForFriends--; + if (lookForFriends == 0) { + // see if there are any friendly monster eggs nearby + int baseX = Mth::floor(x); + int baseY = Mth::floor(y); + int baseZ = Mth::floor(z); + bool doBreak = false; + + for (int yOff = 0; !doBreak && yOff <= 5 && yOff >= -5; + yOff = (yOff <= 0) ? 1 - yOff : 0 - yOff) { + for (int xOff = 0; !doBreak && xOff <= 10 && xOff >= -10; + xOff = (xOff <= 0) ? 1 - xOff : 0 - xOff) { + for (int zOff = 0; !doBreak && zOff <= 10 && zOff >= -10; + zOff = (zOff <= 0) ? 1 - zOff : 0 - zOff) { + int tile = level->getTile(baseX + xOff, baseY + yOff, + baseZ + zOff); + if (tile == Tile::monsterStoneEgg_Id) { + level->levelEvent( + LevelEvent::PARTICLES_DESTROY_BLOCK, + baseX + xOff, baseY + yOff, baseZ + zOff, + Tile::monsterStoneEgg_Id + + (level->getData(baseX + xOff, baseY + yOff, + baseZ + zOff) + << Tile::TILE_NUM_SHIFT)); + level->setTile(baseX + xOff, baseY + yOff, + baseZ + zOff, 0); + Tile::monsterStoneEgg->destroy(level, baseX + xOff, + baseY + yOff, + baseZ + zOff, 0); + + if (random->nextBoolean()) { + doBreak = true; + break; + } + } + } + } + } + } + } + + if (attackTarget == NULL && !isPathFinding()) { + // if the silverfish isn't doing anything special, it will merge + // with any rock tile it is nearby + int tileX = Mth::floor(x), tileY = Mth::floor(y + .5f), + tileZ = Mth::floor(z); + int facing = random->nextInt(6); + + int tile = level->getTile(tileX + Facing::STEP_X[facing], + tileY + Facing::STEP_Y[facing], + tileZ + Facing::STEP_Z[facing]); + if (StoneMonsterTile::isCompatibleHostBlock(tile)) { + level->setTileAndData( + tileX + Facing::STEP_X[facing], tileY + Facing::STEP_Y[facing], + tileZ + Facing::STEP_Z[facing], Tile::monsterStoneEgg_Id, + StoneMonsterTile::getDataForHostBlock(tile)); + spawnAnim(); + remove(); + } else { + findRandomStrollLocation(); + } + + } else if (attackTarget != NULL && !isPathFinding()) { + attackTarget = nullptr; + } } -void Silverfish::serverAiStep() -{ - Monster::serverAiStep(); - - if (level->isClientSide) - { - return; - } - - if (lookForFriends > 0) - { - lookForFriends--; - if (lookForFriends == 0) - { - // see if there are any friendly monster eggs nearby - int baseX = Mth::floor(x); - int baseY = Mth::floor(y); - int baseZ = Mth::floor(z); - bool doBreak = false; - - for (int yOff = 0; !doBreak && yOff <= 5 && yOff >= -5; yOff = (yOff <= 0) ? 1 - yOff : 0 - yOff) - { - for (int xOff = 0; !doBreak && xOff <= 10 && xOff >= -10; xOff = (xOff <= 0) ? 1 - xOff : 0 - xOff) - { - for (int zOff = 0; !doBreak && zOff <= 10 && zOff >= -10; zOff = (zOff <= 0) ? 1 - zOff : 0 - zOff) - { - int tile = level->getTile(baseX + xOff, baseY + yOff, baseZ + zOff); - if (tile == Tile::monsterStoneEgg_Id) - { - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, baseX + xOff, baseY + yOff, baseZ + zOff, - Tile::monsterStoneEgg_Id + (level->getData(baseX + xOff, baseY + yOff, baseZ + zOff) << Tile::TILE_NUM_SHIFT)); - level->setTile(baseX + xOff, baseY + yOff, baseZ + zOff, 0); - Tile::monsterStoneEgg->destroy(level, baseX + xOff, baseY + yOff, baseZ + zOff, 0); - - if (random->nextBoolean()) - { - doBreak = true; - break; - } - } - } - } - } - } - } - - if (attackTarget == NULL && !isPathFinding()) - { - // if the silverfish isn't doing anything special, it will merge - // with any rock tile it is nearby - int tileX = Mth::floor(x), tileY = Mth::floor(y + .5f), tileZ = Mth::floor(z); - int facing = random->nextInt(6); - - int tile = level->getTile(tileX + Facing::STEP_X[facing], tileY + Facing::STEP_Y[facing], tileZ + Facing::STEP_Z[facing]); - if (StoneMonsterTile::isCompatibleHostBlock(tile)) - { - level->setTileAndData(tileX + Facing::STEP_X[facing], tileY + Facing::STEP_Y[facing], tileZ + Facing::STEP_Z[facing], Tile::monsterStoneEgg_Id, StoneMonsterTile::getDataForHostBlock(tile)); - spawnAnim(); - remove(); - } - else - { - findRandomStrollLocation(); - } - - } - else if (attackTarget != NULL && !isPathFinding()) - { - attackTarget = nullptr; - } +float Silverfish::getWalkTargetValue(int x, int y, int z) { + // silverfish LOVES stone =) + if (level->getTile(x, y - 1, z) == Tile::rock_Id) return 10; + return Monster::getWalkTargetValue(x, y, z); } -float Silverfish::getWalkTargetValue(int x, int y, int z) -{ - // silverfish LOVES stone =) - if (level->getTile(x, y - 1, z) == Tile::rock_Id) return 10; - return Monster::getWalkTargetValue(x, y, z); +bool Silverfish::isDarkEnoughToSpawn() { return true; } + +bool Silverfish::canSpawn() { + if (Monster::canSpawn()) { + std::shared_ptr nearestPlayer = + level->getNearestPlayer(shared_from_this(), 5.0); + return nearestPlayer == NULL; + } + return false; } -bool Silverfish::isDarkEnoughToSpawn() -{ - return true; -} - -bool Silverfish::canSpawn() -{ - if (Monster::canSpawn()) - { - std::shared_ptr nearestPlayer = level->getNearestPlayer(shared_from_this(), 5.0); - return nearestPlayer == NULL; - } - return false; -} - -MobType Silverfish::getMobType() -{ - return ARTHROPOD; -} +MobType Silverfish::getMobType() { return ARTHROPOD; } diff --git a/Minecraft.World/Entities/Mobs/Silverfish.h b/Minecraft.World/Entities/Mobs/Silverfish.h index 4a98c688f..9d6171e92 100644 --- a/Minecraft.World/Entities/Mobs/Silverfish.h +++ b/Minecraft.World/Entities/Mobs/Silverfish.h @@ -2,48 +2,48 @@ #include "../Monster.h" -class Silverfish : public Monster -{ +class Silverfish : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_SILVERFISH; } - static Entity *create(Level *level) { return new Silverfish(level); } + eINSTANCEOF GetType() { return eTYPE_SILVERFISH; } + static Entity* create(Level* level) { return new Silverfish(level); } + private: - int lookForFriends; + int lookForFriends; public: - Silverfish(Level *level); + Silverfish(Level* level); - virtual int getMaxHealth(); + virtual int getMaxHealth(); protected: - virtual bool makeStepSound(); - virtual std::shared_ptr findAttackTarget(); + virtual bool makeStepSound(); + virtual std::shared_ptr findAttackTarget(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); protected: - virtual void checkHurtTarget(std::shared_ptr target, float d); - virtual void playStepSound(int xt, int yt, int zt, int t); - virtual int getDeathLoot(); + virtual void checkHurtTarget(std::shared_ptr target, float d); + virtual void playStepSound(int xt, int yt, int zt, int t); + virtual int getDeathLoot(); public: - virtual void tick(); + virtual void tick(); protected: - virtual void serverAiStep(); + virtual void serverAiStep(); public: - virtual float getWalkTargetValue(int x, int y, int z); + virtual float getWalkTargetValue(int x, int y, int z); protected: - virtual bool isDarkEnoughToSpawn(); + virtual bool isDarkEnoughToSpawn(); public: - virtual bool canSpawn(); - virtual MobType getMobType(); + virtual bool canSpawn(); + virtual MobType getMobType(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Skeleton.cpp b/Minecraft.World/Entities/Mobs/Skeleton.cpp index a146c215f..acaaa2ef3 100644 --- a/Minecraft.World/Entities/Mobs/Skeleton.cpp +++ b/Minecraft.World/Entities/Mobs/Skeleton.cpp @@ -16,80 +16,58 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" +Skeleton::Skeleton(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Skeleton::Skeleton(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + this->textureIdx = TN_MOB_SKELETON; // 4J was L"/mob/skeleton.png"; - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + runSpeed = 0.25f; - this->textureIdx = TN_MOB_SKELETON; // 4J was L"/mob/skeleton.png"; + goalSelector.addGoal(1, new FloatGoal(this)); + goalSelector.addGoal(2, new RestrictSunGoal(this)); + goalSelector.addGoal(3, new FleeSunGoal(this, runSpeed)); + goalSelector.addGoal( + 4, new ArrowAttackGoal(this, runSpeed, ArrowAttackGoal::ArrowType, + SharedConstants::TICKS_PER_SECOND * 3)); + goalSelector.addGoal(5, new RandomStrollGoal(this, runSpeed)); + goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 8)); + goalSelector.addGoal(6, new RandomLookAroundGoal(this)); - runSpeed = 0.25f; - - goalSelector.addGoal(1, new FloatGoal(this)); - goalSelector.addGoal(2, new RestrictSunGoal(this)); - goalSelector.addGoal(3, new FleeSunGoal(this, runSpeed)); - goalSelector.addGoal(4, new ArrowAttackGoal(this, runSpeed, ArrowAttackGoal::ArrowType, SharedConstants::TICKS_PER_SECOND * 3)); - goalSelector.addGoal(5, new RandomStrollGoal(this, runSpeed)); - goalSelector.addGoal(6, new LookAtPlayerGoal(this, typeid(Player), 8)); - goalSelector.addGoal(6, new RandomLookAroundGoal(this)); - - targetSelector.addGoal(1, new HurtByTargetGoal(this, false)); - targetSelector.addGoal(2, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); + targetSelector.addGoal(1, new HurtByTargetGoal(this, false)); + targetSelector.addGoal( + 2, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); } -bool Skeleton::useNewAi() -{ - return true; -} +bool Skeleton::useNewAi() { return true; } -int Skeleton::getMaxHealth() -{ - return 20; -} +int Skeleton::getMaxHealth() { return 20; } -int Skeleton::getAmbientSound() -{ - return eSoundType_MOB_SKELETON_AMBIENT; -} +int Skeleton::getAmbientSound() { return eSoundType_MOB_SKELETON_AMBIENT; } -int Skeleton::getHurtSound() -{ - return eSoundType_MOB_SKELETON_HURT; -} +int Skeleton::getHurtSound() { return eSoundType_MOB_SKELETON_HURT; } -int Skeleton::getDeathSound() -{ - return eSoundType_MOB_SKELETON_HURT; -} +int Skeleton::getDeathSound() { return eSoundType_MOB_SKELETON_HURT; } std::shared_ptr Skeleton::bow; -std::shared_ptr Skeleton::getCarriedItem() -{ - return bow; -} +std::shared_ptr Skeleton::getCarriedItem() { return bow; } -MobType Skeleton::getMobType() -{ - return UNDEAD; -} +MobType Skeleton::getMobType() { return UNDEAD; } -void Skeleton::aiStep() -{ - // isClientSide check brought forward from 1.8 (I assume it's related to the lighting changes) - if (level->isDay() && !level->isClientSide) - { +void Skeleton::aiStep() { + // isClientSide check brought forward from 1.8 (I assume it's related to + // the lighting changes) + if (level->isDay() && !level->isClientSide) { float br = getBrightness(1); - if (br > 0.5f) - { - if (level->canSeeSky( Mth::floor(x), Mth::floor(y), Mth::floor(z)) && random->nextFloat() * 30 < (br - 0.4f) * 2) - { + if (br > 0.5f) { + if (level->canSeeSky(Mth::floor(x), Mth::floor(y), Mth::floor(z)) && + random->nextFloat() * 30 < (br - 0.4f) * 2) { setOnFire(8); } } @@ -98,57 +76,48 @@ void Skeleton::aiStep() Monster::aiStep(); } -void Skeleton::die(DamageSource *source) -{ - Monster::die(source); - std::shared_ptr player = std::dynamic_pointer_cast( source->getEntity() ); - if ( std::dynamic_pointer_cast( source->getDirectEntity() ) != NULL && player != NULL) - { - double xd = player->x - x; - double zd = player->z - z; - if (xd * xd + zd * zd >= 50 * 50) - { - player->awardStat(GenericStats::snipeSkeleton(), GenericStats::param_snipeSkeleton()); - } - } +void Skeleton::die(DamageSource* source) { + Monster::die(source); + std::shared_ptr player = + std::dynamic_pointer_cast(source->getEntity()); + if (std::dynamic_pointer_cast(source->getDirectEntity()) != NULL && + player != NULL) { + double xd = player->x - x; + double zd = player->z - z; + if (xd * xd + zd * zd >= 50 * 50) { + player->awardStat(GenericStats::snipeSkeleton(), + GenericStats::param_snipeSkeleton()); + } + } } -int Skeleton::getDeathLoot() -{ - return Item::arrow->id; -} +int Skeleton::getDeathLoot() { return Item::arrow->id; } -void Skeleton::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ +void Skeleton::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { // drop some arrows int count = random->nextInt(3 + playerBonusLevel); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { spawnAtLocation(Item::arrow->id, 1); } // and some bones count = random->nextInt(3 + playerBonusLevel); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { spawnAtLocation(Item::bone->id, 1); } } -void Skeleton::dropRareDeathLoot(int rareLootLevel) -{ - if (rareLootLevel > 0) - { - std::shared_ptr bow = std::shared_ptr( new ItemInstance(Item::bow) ); - EnchantmentHelper::enchantItem(random, bow, 5); - spawnAtLocation(bow, 0); - } - else - { - spawnAtLocation(Item::bow_Id, 1); - } +void Skeleton::dropRareDeathLoot(int rareLootLevel) { + if (rareLootLevel > 0) { + std::shared_ptr bow = + std::shared_ptr(new ItemInstance(Item::bow)); + EnchantmentHelper::enchantItem(random, bow, 5); + spawnAtLocation(bow, 0); + } else { + spawnAtLocation(Item::bow_Id, 1); + } } -void Skeleton::staticCtor() -{ - Skeleton::bow = std::shared_ptr( new ItemInstance(Item::bow, 1) ); +void Skeleton::staticCtor() { + Skeleton::bow = + std::shared_ptr(new ItemInstance(Item::bow, 1)); } diff --git a/Minecraft.World/Entities/Mobs/Skeleton.h b/Minecraft.World/Entities/Mobs/Skeleton.h index faf1e41ce..7a38c77dd 100644 --- a/Minecraft.World/Entities/Mobs/Skeleton.h +++ b/Minecraft.World/Entities/Mobs/Skeleton.h @@ -1,39 +1,36 @@ #pragma once - #include "../Monster.h" -class Skeleton : public Monster -{ +class Skeleton : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_SKELETON; } - static Entity *create(Level *level) { return new Skeleton(level); } + eINSTANCEOF GetType() { return eTYPE_SKELETON; } + static Entity* create(Level* level) { return new Skeleton(level); } - Skeleton(Level *level); + Skeleton(Level* level); - virtual bool useNewAi(); - virtual int getMaxHealth(); + virtual bool useNewAi(); + virtual int getMaxHealth(); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: virtual std::shared_ptr getCarriedItem(); - virtual MobType getMobType(); - virtual void aiStep(); - virtual void die(DamageSource *source); + virtual MobType getMobType(); + virtual void aiStep(); + virtual void die(DamageSource* source); protected: - virtual int getDeathLoot(); + virtual int getDeathLoot(); virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); - virtual void dropRareDeathLoot(int rareLootLevel); + virtual void dropRareDeathLoot(int rareLootLevel); private: - static std::shared_ptr bow; + static std::shared_ptr bow; public: - - static void staticCtor(); + static void staticCtor(); }; diff --git a/Minecraft.World/Entities/Mobs/Slime.cpp b/Minecraft.World/Entities/Mobs/Slime.cpp index 27948d48e..db49dace1 100644 --- a/Minecraft.World/Entities/Mobs/Slime.cpp +++ b/Minecraft.World/Entities/Mobs/Slime.cpp @@ -14,274 +14,219 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" +void Slime::_init() { + jumpDelay = 0; - -void Slime::_init() -{ - jumpDelay = 0; - - targetSquish = 0; - squish = 0; - oSquish = 0; + targetSquish = 0; + squish = 0; + oSquish = 0; } -Slime::Slime(Level *level) : Mob( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Slime::Slime(Level* level) : Mob(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - _init(); + _init(); - this->textureIdx = TN_MOB_SLIME; // 4J was L"/mob/slime.png"; - int size = 1 << (random->nextInt(3)); - this->heightOffset = 0; - jumpDelay = random->nextInt(20) + 10; - setSize(size); + this->textureIdx = TN_MOB_SLIME; // 4J was L"/mob/slime.png"; + int size = 1 << (random->nextInt(3)); + this->heightOffset = 0; + jumpDelay = random->nextInt(20) + 10; + setSize(size); } -void Slime::defineSynchedData() -{ - Mob::defineSynchedData(); +void Slime::defineSynchedData() { + Mob::defineSynchedData(); - entityData->define(ID_SIZE, (uint8_t) 1); + entityData->define(ID_SIZE, (uint8_t)1); } -void Slime::setSize(int size) -{ - entityData->set(ID_SIZE, (uint8_t) size); - Mob::setSize(0.6f * size, 0.6f * size); - this->setPos(x, y, z); - setHealth(getMaxHealth()); - xpReward = size; +void Slime::setSize(int size) { + entityData->set(ID_SIZE, (uint8_t)size); + Mob::setSize(0.6f * size, 0.6f * size); + this->setPos(x, y, z); + setHealth(getMaxHealth()); + xpReward = size; } -int Slime::getMaxHealth() -{ - int size = getSize(); - return size * size; +int Slime::getMaxHealth() { + int size = getSize(); + return size * size; } -int Slime::getSize() -{ - return entityData->getByte(ID_SIZE); +int Slime::getSize() { return entityData->getByte(ID_SIZE); } + +void Slime::addAdditonalSaveData(CompoundTag* tag) { + Mob::addAdditonalSaveData(tag); + tag->putInt(L"Size", getSize() - 1); } -void Slime::addAdditonalSaveData(CompoundTag *tag) -{ - Mob::addAdditonalSaveData(tag); - tag->putInt(L"Size", getSize() - 1); +void Slime::readAdditionalSaveData(CompoundTag* tag) { + Mob::readAdditionalSaveData(tag); + setSize(tag->getInt(L"Size") + 1); } -void Slime::readAdditionalSaveData(CompoundTag *tag) -{ - Mob::readAdditionalSaveData(tag); - setSize(tag->getInt(L"Size") + 1); +ePARTICLE_TYPE Slime::getParticleName() { return eParticleType_slime; } + +int Slime::getSquishSound() { return eSoundType_MOB_SLIME; } + +void Slime::tick() { + if (!level->isClientSide && level->difficulty == Difficulty::PEACEFUL && + getSize() > 0) { + removed = true; + } + + squish = squish + (targetSquish - squish) * .5f; + + oSquish = squish; + bool wasOnGround = this->onGround; + Mob::tick(); + if (onGround && !wasOnGround) { + int size = getSize(); + for (int i = 0; i < size * 8; i++) { + float dir = random->nextFloat() * PI * 2; + float d = random->nextFloat() * 0.5f + 0.5f; + float xd = Mth::sin(dir) * size * 0.5f * d; + float zd = Mth::cos(dir) * size * 0.5f * d; + level->addParticle(getParticleName(), x + xd, bb->y0, z + zd, 0, 0, + 0); + } + + if (doPlayLandSound()) { + level->playSound( + shared_from_this(), getSquishSound(), getSoundVolume(), + ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) / + 0.8f); + } + targetSquish = -0.5f; + } + // 4J Stu - Brought forward from 1.3 in TU7 to fix lava slime render + else if (!onGround && wasOnGround) { + targetSquish = 1; + } + decreaseSquish(); } -ePARTICLE_TYPE Slime::getParticleName() -{ - return eParticleType_slime; +void Slime::serverAiStep() { + checkDespawn(); + std::shared_ptr player = + level->getNearestAttackablePlayer(shared_from_this(), 16); + if (player != NULL) { + lookAt(player, 10, 20); + } + if (onGround && jumpDelay-- <= 0) { + jumpDelay = getJumpDelay(); + if (player != NULL) { + jumpDelay /= 3; + } + jumping = true; + if (doPlayJumpSound()) { + level->playSound( + shared_from_this(), getSquishSound(), getSoundVolume(), + ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) * + 0.8f); + } + + // 4J Removed TU7 to bring forward change to fix lava slime render in MP + // targetSquish = 1; + xxa = 1 - random->nextFloat() * 2; + yya = (float)1 * getSize(); + } else { + jumping = false; + if (onGround) { + xxa = yya = 0; + } + } } -int Slime::getSquishSound() -{ - return eSoundType_MOB_SLIME; +void Slime::decreaseSquish() { targetSquish = targetSquish * 0.6f; } + +int Slime::getJumpDelay() { return random->nextInt(20) + 10; } + +std::shared_ptr Slime::createChild() { + return std::shared_ptr(new Slime(level)); } -void Slime::tick() -{ - if (!level->isClientSide && level->difficulty == Difficulty::PEACEFUL && getSize() > 0) - { - removed = true; - } - - squish = squish + (targetSquish - squish) * .5f; - - oSquish = squish; - bool wasOnGround = this->onGround; - Mob::tick(); - if (onGround && !wasOnGround) - { - int size = getSize(); - for (int i = 0; i < size * 8; i++) - { - float dir = random->nextFloat() * PI * 2; - float d = random->nextFloat() * 0.5f + 0.5f; - float xd = Mth::sin(dir) * size * 0.5f * d; - float zd = Mth::cos(dir) * size * 0.5f * d; - level->addParticle(getParticleName(), x + xd, bb->y0, z + zd, 0, 0, 0); - } - - if (doPlayLandSound()) - { - level->playSound(shared_from_this(), getSquishSound(), getSoundVolume(), ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) / 0.8f); - } - targetSquish = -0.5f; - } - // 4J Stu - Brought forward from 1.3 in TU7 to fix lava slime render - else if (!onGround && wasOnGround) - { - targetSquish = 1; - } - decreaseSquish(); +void Slime::remove() { + int size = getSize(); + if (!level->isClientSide && size > 1 && getHealth() <= 0) { + int count = 2 + random->nextInt(3); + for (int i = 0; i < count; i++) { + // The mob spawner can currently make a maximum of 25 slimes + // (limited to 50% of the total amount of monsters which is 50) and + // so limit to slightly more than this so we have some head room to + // make a few spawned children. Also always create at least one new + // slime since we are getting rid of this one anyway. + if (i == 0 || level->countInstanceOf(eTYPE_SLIME, true) < 35) { + float xd = (i % 2 - 0.5f) * size / 4.0f; + float zd = (i / 2 - 0.5f) * size / 4.0f; + std::shared_ptr slime = createChild(); + slime->setSize(size / 2); + slime->moveTo(x + xd, y + 0.5, z + zd, + random->nextFloat() * 360, 0); + level->addEntity(slime); + } + } + } + Mob::remove(); } -void Slime::serverAiStep() -{ - checkDespawn(); - std::shared_ptr player = level->getNearestAttackablePlayer(shared_from_this(), 16); - if (player != NULL) - { - lookAt(player, 10, 20); - } - if (onGround && jumpDelay-- <= 0) - { - jumpDelay = getJumpDelay(); - if (player != NULL) - { - jumpDelay /= 3; - } - jumping = true; - if (doPlayJumpSound()) - { - level->playSound(shared_from_this(), getSquishSound(), getSoundVolume(), ((random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f) * 0.8f); - } - - // 4J Removed TU7 to bring forward change to fix lava slime render in MP - //targetSquish = 1; - xxa = 1 - random->nextFloat() * 2; - yya = (float) 1 * getSize(); - } - else - { - jumping = false; - if (onGround) - { - xxa = yya = 0; - } - } +void Slime::playerTouch(std::shared_ptr player) { + if (isDealsDamage()) { + int size = getSize(); + if (canSee(player) && + this->distanceToSqr(player) < (0.6 * size) * (0.6 * size)) { + DamageSource* damageSource = DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())); + if (player->hurt(damageSource, getAttackDamage())) { + level->playSound( + shared_from_this(), eSoundType_MOB_SLIME_ATTACK, 1, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + } + delete damageSource; + } + } } -void Slime::decreaseSquish() -{ - targetSquish = targetSquish * 0.6f; +bool Slime::isDealsDamage() { return getSize() > 1; } + +int Slime::getAttackDamage() { return getSize(); } + +int Slime::getHurtSound() { return eSoundType_MOB_SLIME; } + +int Slime::getDeathSound() { return eSoundType_MOB_SLIME; } + +int Slime::getDeathLoot() { + if (getSize() == 1) return Item::slimeBall->id; + return 0; } -int Slime::getJumpDelay() -{ - return random->nextInt(20) + 10; +bool Slime::canSpawn() { + LevelChunk* lc = level->getChunkAt(Mth::floor(x), Mth::floor(z)); + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat && + random->nextInt(4) != 1) { + return false; + } + Random* lcr = + lc->getRandom(987234911l); // 4J - separated out so we can delete + if ((getSize() == 1 || level->difficulty > Difficulty::PEACEFUL) && + random->nextInt(10) == 0 && lcr->nextInt(10) == 0 && y < 40) { + delete lcr; + return Mob::canSpawn(); + } + delete lcr; + return false; } -std::shared_ptr Slime::createChild() -{ - return std::shared_ptr( new Slime(level) ); -} +float Slime::getSoundVolume() { return 0.4f * getSize(); } -void Slime::remove() -{ - int size = getSize(); - if (!level->isClientSide && size > 1 && getHealth() <= 0) - { - int count = 2 + random->nextInt(3); - for (int i = 0; i < count; i++) - { - // The mob spawner can currently make a maximum of 25 slimes (limited to 50% of the total amount of monsters which is 50) - // and so limit to slightly more than this so we have some head room to make a few spawned children. Also always create at least one - // new slime since we are getting rid of this one anyway. - if( i == 0 || level->countInstanceOf( eTYPE_SLIME, true) < 35 ) - { - float xd = (i % 2 - 0.5f) * size / 4.0f; - float zd = (i / 2 - 0.5f) * size / 4.0f; - std::shared_ptr slime = createChild(); - slime->setSize(size / 2); - slime->moveTo(x + xd, y + 0.5, z + zd, random->nextFloat() * 360, 0); - level->addEntity(slime); - } - } - } - Mob::remove(); -} +int Slime::getMaxHeadXRot() { return 0; } -void Slime::playerTouch(std::shared_ptr player) -{ - if (isDealsDamage()) - { - int size = getSize(); - if (canSee(player) && this->distanceToSqr(player) < (0.6 * size) * (0.6 * size)) - { - DamageSource *damageSource = DamageSource::mobAttack( std::dynamic_pointer_cast( shared_from_this() ) ); - if (player->hurt(damageSource, getAttackDamage())) - { - level->playSound(shared_from_this(), eSoundType_MOB_SLIME_ATTACK, 1, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - } - delete damageSource; - } - } -} +bool Slime::doPlayJumpSound() { return getSize() > 1; } -bool Slime::isDealsDamage() -{ - return getSize() > 1; -} - -int Slime::getAttackDamage() -{ - return getSize(); -} - -int Slime::getHurtSound() -{ - return eSoundType_MOB_SLIME; -} - -int Slime::getDeathSound() -{ - return eSoundType_MOB_SLIME; -} - -int Slime::getDeathLoot() -{ - if (getSize() == 1) return Item::slimeBall->id; - return 0; -} - -bool Slime::canSpawn() -{ - LevelChunk *lc = level->getChunkAt( Mth::floor(x), Mth::floor(z)); - if (level->getLevelData()->getGenerator() == LevelType::lvl_flat && random->nextInt(4) != 1) - { - return false; - } - Random *lcr = lc->getRandom(987234911l); // 4J - separated out so we can delete - if ((getSize() == 1 || level->difficulty > Difficulty::PEACEFUL) && random->nextInt(10) == 0 && lcr->nextInt(10) == 0 && y < 40) - { - delete lcr; - return Mob::canSpawn(); - } - delete lcr; - return false; -} - -float Slime::getSoundVolume() -{ - return 0.4f * getSize(); -} - -int Slime::getMaxHeadXRot() -{ - return 0; -} - -bool Slime::doPlayJumpSound() -{ - return getSize() > 1; -} - -bool Slime::doPlayLandSound() -{ - return getSize() > 2; -} \ No newline at end of file +bool Slime::doPlayLandSound() { return getSize() > 2; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Slime.h b/Minecraft.World/Entities/Mobs/Slime.h index 5b2bebd83..de0f87576 100644 --- a/Minecraft.World/Entities/Mobs/Slime.h +++ b/Minecraft.World/Entities/Mobs/Slime.h @@ -1,78 +1,76 @@ #pragma once - #include "../Mob.h" #include "../Enemy.h" #include "../../Util/ParticleTypes.h" -class Slime : public Mob, public Enemy -{ +class Slime : public Mob, public Enemy { public: - eINSTANCEOF GetType() { return eTYPE_SLIME; } - static Entity *create(Level *level) { return new Slime(level); } + eINSTANCEOF GetType() { return eTYPE_SLIME; } + static Entity* create(Level* level) { return new Slime(level); } private: - static const int ID_SIZE = 16; + static const int ID_SIZE = 16; public: - float targetSquish; - float squish; - float oSquish; + float targetSquish; + float squish; + float oSquish; private: - int jumpDelay; + int jumpDelay; - void _init(); + void _init(); public: - Slime(Level *level); - -protected: - virtual void defineSynchedData(); - -public: - using Entity::setSize; - - virtual void setSize(int size); - virtual int getMaxHealth(); - virtual int getSize(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + Slime(Level* level); protected: - virtual ePARTICLE_TYPE getParticleName(); - virtual int getSquishSound(); + virtual void defineSynchedData(); public: - virtual void tick(); + using Entity::setSize; + + virtual void setSize(int size); + virtual int getMaxHealth(); + virtual int getSize(); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual void serverAiStep(); - virtual void decreaseSquish(); - virtual int getJumpDelay(); - virtual std::shared_ptr createChild(); + virtual ePARTICLE_TYPE getParticleName(); + virtual int getSquishSound(); public: - virtual void remove(); - virtual void playerTouch(std::shared_ptr player); + virtual void tick(); protected: - virtual bool isDealsDamage(); - virtual int getAttackDamage(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual int getDeathLoot(); + virtual void serverAiStep(); + virtual void decreaseSquish(); + virtual int getJumpDelay(); + virtual std::shared_ptr createChild(); public: - virtual bool canSpawn(); + virtual void remove(); + virtual void playerTouch(std::shared_ptr player); protected: - virtual float getSoundVolume(); + virtual bool isDealsDamage(); + virtual int getAttackDamage(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual int getDeathLoot(); public: - virtual int getMaxHeadXRot(); + virtual bool canSpawn(); protected: - virtual bool doPlayJumpSound(); - virtual bool doPlayLandSound(); + virtual float getSoundVolume(); + +public: + virtual int getMaxHeadXRot(); + +protected: + virtual bool doPlayJumpSound(); + virtual bool doPlayLandSound(); }; diff --git a/Minecraft.World/Entities/Mobs/SmallFireball.cpp b/Minecraft.World/Entities/Mobs/SmallFireball.cpp index 59c131f17..f349dff2c 100644 --- a/Minecraft.World/Entities/Mobs/SmallFireball.cpp +++ b/Minecraft.World/Entities/Mobs/SmallFireball.cpp @@ -6,75 +6,64 @@ #include "../../Headers/net.minecraft.world.level.h" #include "SmallFireball.h" -SmallFireball::SmallFireball(Level *level) : Fireball(level) -{ - setSize(5 / 16.0f, 5 / 16.0f); +SmallFireball::SmallFireball(Level* level) : Fireball(level) { + setSize(5 / 16.0f, 5 / 16.0f); } -SmallFireball::SmallFireball(Level *level, std::shared_ptr mob, double xa, double ya, double za) : Fireball(level, mob, xa, ya, za) -{ - setSize(5 / 16.0f, 5 / 16.0f); +SmallFireball::SmallFireball(Level* level, std::shared_ptr mob, double xa, + double ya, double za) + : Fireball(level, mob, xa, ya, za) { + setSize(5 / 16.0f, 5 / 16.0f); } -SmallFireball::SmallFireball(Level *level, double x, double y, double z, double xa, double ya, double za) : Fireball(level, x, y, z, xa, ya, za) -{ - setSize(5 / 16.0f, 5 / 16.0f); +SmallFireball::SmallFireball(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Fireball(level, x, y, z, xa, ya, za) { + setSize(5 / 16.0f, 5 / 16.0f); } -void SmallFireball::onHit(HitResult *res) -{ - if (!level->isClientSide) - { - if (res->entity != NULL) - { - DamageSource *damageSource = DamageSource::fireball(std::dynamic_pointer_cast(shared_from_this()),owner); - if (!res->entity->isFireImmune() && res->entity->hurt(damageSource, 5)) - { - res->entity->setOnFire(5); - } - delete damageSource; - } - else - { - int tileX = res->x; - int tileY = res->y; - int tileZ = res->z; - switch (res->f) - { - case Facing::UP: - tileY++; - break; - case Facing::DOWN: - tileY--; - break; - case Facing::NORTH: - tileZ--; - break; - case Facing::SOUTH: - tileZ++; - break; - case Facing::EAST: - tileX++; - break; - case Facing::WEST: - tileX--; - break; - }; - if (level->isEmptyTile(tileX, tileY, tileZ)) - { - level->setTile(tileX, tileY, tileZ, Tile::fire_Id); - } - } - remove(); - } +void SmallFireball::onHit(HitResult* res) { + if (!level->isClientSide) { + if (res->entity != NULL) { + DamageSource* damageSource = DamageSource::fireball( + std::dynamic_pointer_cast(shared_from_this()), owner); + if (!res->entity->isFireImmune() && + res->entity->hurt(damageSource, 5)) { + res->entity->setOnFire(5); + } + delete damageSource; + } else { + int tileX = res->x; + int tileY = res->y; + int tileZ = res->z; + switch (res->f) { + case Facing::UP: + tileY++; + break; + case Facing::DOWN: + tileY--; + break; + case Facing::NORTH: + tileZ--; + break; + case Facing::SOUTH: + tileZ++; + break; + case Facing::EAST: + tileX++; + break; + case Facing::WEST: + tileX--; + break; + }; + if (level->isEmptyTile(tileX, tileY, tileZ)) { + level->setTile(tileX, tileY, tileZ, Tile::fire_Id); + } + } + remove(); + } } -bool SmallFireball::isPickable() -{ - return false; -} +bool SmallFireball::isPickable() { return false; } -bool SmallFireball::hurt(DamageSource *source, int damage) -{ - return false; -} \ No newline at end of file +bool SmallFireball::hurt(DamageSource* source, int damage) { return false; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/SmallFireball.h b/Minecraft.World/Entities/Mobs/SmallFireball.h index 3b63e2e08..bacdeaba9 100644 --- a/Minecraft.World/Entities/Mobs/SmallFireball.h +++ b/Minecraft.World/Entities/Mobs/SmallFireball.h @@ -4,21 +4,22 @@ class HitResult; -class SmallFireball : public Fireball -{ +class SmallFireball : public Fireball { public: - eINSTANCEOF GetType() { return eTYPE_SMALL_FIREBALL; } - static Entity *create(Level *level) { return new SmallFireball(level); } + eINSTANCEOF GetType() { return eTYPE_SMALL_FIREBALL; } + static Entity* create(Level* level) { return new SmallFireball(level); } public: - SmallFireball(Level *level); - SmallFireball(Level *level, std::shared_ptr mob, double xa, double ya, double za); - SmallFireball(Level *level, double x, double y, double z, double xa, double ya, double za); + SmallFireball(Level* level); + SmallFireball(Level* level, std::shared_ptr mob, double xa, double ya, + double za); + SmallFireball(Level* level, double x, double y, double z, double xa, + double ya, double za); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); public: - virtual bool isPickable(); - virtual bool hurt(DamageSource *source, int damage); + virtual bool isPickable(); + virtual bool hurt(DamageSource* source, int damage); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/SnowMan.cpp b/Minecraft.World/Entities/Mobs/SnowMan.cpp index 4a0648841..7a90ec6af 100644 --- a/Minecraft.World/Entities/Mobs/SnowMan.cpp +++ b/Minecraft.World/Entities/Mobs/SnowMan.cpp @@ -15,83 +15,67 @@ #include "SnowMan.h" #include "../../Util/SoundTypes.h" +SnowMan::SnowMan(Level* level) : Golem(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -SnowMan::SnowMan(Level *level) : Golem(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + this->textureIdx = TN_MOB_SNOWMAN; // 4J was "/mob/snowman.png"; + this->setSize(0.4f, 1.8f); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + getNavigation()->setAvoidWater(true); + goalSelector.addGoal( + 1, new ArrowAttackGoal(this, 0.25f, ArrowAttackGoal::SnowballType, + SharedConstants::TICKS_PER_SECOND * 1)); + goalSelector.addGoal(2, new RandomStrollGoal(this, 0.2f)); + goalSelector.addGoal(3, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(4, new RandomLookAroundGoal(this)); - this->textureIdx = TN_MOB_SNOWMAN;// 4J was "/mob/snowman.png"; - this->setSize(0.4f, 1.8f); - - getNavigation()->setAvoidWater(true); - goalSelector.addGoal(1, new ArrowAttackGoal(this, 0.25f, ArrowAttackGoal::SnowballType, SharedConstants::TICKS_PER_SECOND * 1)); - goalSelector.addGoal(2, new RandomStrollGoal(this, 0.2f)); - goalSelector.addGoal(3, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(4, new RandomLookAroundGoal(this)); - - targetSelector.addGoal(1, new NearestAttackableTargetGoal(this, typeid(Monster), 16, 0, true)); + targetSelector.addGoal( + 1, new NearestAttackableTargetGoal(this, typeid(Monster), 16, 0, true)); } -bool SnowMan::useNewAi() -{ - return true; +bool SnowMan::useNewAi() { return true; } + +int SnowMan::getMaxHealth() { return 4; } + +void SnowMan::aiStep() { + Golem::aiStep(); + + if (this->isInWaterOrRain()) hurt(DamageSource::drown, 1); + + { + int xx = Mth::floor(x); + int zz = Mth::floor(z); + if (level->getBiome(xx, zz)->getTemperature() > 1) { + hurt(DamageSource::onFire, 1); + } + } + + for (int i = 0; i < 4; i++) { + int xx = Mth::floor(x + (i % 2 * 2 - 1) * 0.25f); + int yy = Mth::floor(y); + int zz = Mth::floor(z + ((i / 2) % 2 * 2 - 1) * 0.25f); + if (level->getTile(xx, yy, zz) == 0) { + if (level->getBiome(xx, zz)->getTemperature() < 0.8f) { + if (Tile::topSnow->mayPlace(level, xx, yy, zz)) { + level->setTile(xx, yy, zz, Tile::topSnow_Id); + } + } + } + } } -int SnowMan::getMaxHealth() -{ - return 4; -} +int SnowMan::getDeathLoot() { return Item::snowBall_Id; } -void SnowMan::aiStep() -{ - Golem::aiStep(); - - if (this->isInWaterOrRain()) hurt(DamageSource::drown, 1); - - { - int xx = Mth::floor(x); - int zz = Mth::floor(z); - if (level->getBiome(xx, zz)->getTemperature() > 1) - { - hurt(DamageSource::onFire, 1); - } - } - - for (int i = 0; i < 4; i++) - { - int xx = Mth::floor(x + (i % 2 * 2 - 1) * 0.25f); - int yy = Mth::floor(y); - int zz = Mth::floor(z + ((i / 2) % 2 * 2 - 1) * 0.25f); - if (level->getTile(xx, yy, zz) == 0) - { - if (level->getBiome(xx, zz)->getTemperature() < 0.8f) - { - if (Tile::topSnow->mayPlace(level, xx, yy, zz)) - { - level->setTile(xx, yy, zz, Tile::topSnow_Id); - } - } - } - } -} - -int SnowMan::getDeathLoot() -{ - return Item::snowBall_Id; -} - - -void SnowMan::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - // drop some feathers - int count = random->nextInt(16); - for (int i = 0; i < count; i++) { - spawnAtLocation(Item::snowBall_Id, 1); - } +void SnowMan::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + // drop some feathers + int count = random->nextInt(16); + for (int i = 0; i < count; i++) { + spawnAtLocation(Item::snowBall_Id, 1); + } } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/SnowMan.h b/Minecraft.World/Entities/Mobs/SnowMan.h index cf6f094af..fe2a52f4f 100644 --- a/Minecraft.World/Entities/Mobs/SnowMan.h +++ b/Minecraft.World/Entities/Mobs/SnowMan.h @@ -2,20 +2,19 @@ #include "Golem.h" -class SnowMan : public Golem -{ +class SnowMan : public Golem { public: - eINSTANCEOF GetType() { return eTYPE_SNOWMAN; } - static Entity *create(Level *level) { return new SnowMan(level); } + eINSTANCEOF GetType() { return eTYPE_SNOWMAN; } + static Entity* create(Level* level) { return new SnowMan(level); } public: - SnowMan(Level *level); - virtual bool useNewAi(); + SnowMan(Level* level); + virtual bool useNewAi(); - virtual int getMaxHealth(); - virtual void aiStep(); + virtual int getMaxHealth(); + virtual void aiStep(); protected: - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Snowball.cpp b/Minecraft.World/Entities/Mobs/Snowball.cpp index 1543d13ce..52a67dbdc 100644 --- a/Minecraft.World/Entities/Mobs/Snowball.cpp +++ b/Minecraft.World/Entities/Mobs/Snowball.cpp @@ -5,48 +5,39 @@ #include "../../Headers/net.minecraft.world.entity.monster.h" #include "Snowball.h" - - -void Snowball::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void Snowball::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -Snowball::Snowball(Level *level) : Throwable(level) -{ - _init(); +Snowball::Snowball(Level* level) : Throwable(level) { _init(); } + +Snowball::Snowball(Level* level, std::shared_ptr mob) + : Throwable(level, mob) { + _init(); } -Snowball::Snowball(Level *level, std::shared_ptr mob) : Throwable(level,mob) -{ - _init(); +Snowball::Snowball(Level* level, double x, double y, double z) + : Throwable(level, x, y, z) { + _init(); } -Snowball::Snowball(Level *level, double x, double y, double z) : Throwable(level,x,y,z) -{ - _init(); -} +void Snowball::onHit(HitResult* res) { + if (res->entity != NULL) { + int damage = 0; + if (std::dynamic_pointer_cast(res->entity) != NULL) { + damage = 3; + } -void Snowball::onHit(HitResult *res) -{ - if (res->entity != NULL) - { - int damage = 0; - if (std::dynamic_pointer_cast(res->entity) != NULL) - { - damage = 3; - } - - DamageSource *damageSource = DamageSource::thrown(shared_from_this(), owner); - res->entity->hurt(damageSource, damage); - delete damageSource; - } - for (int i = 0; i < 8; i++) - level->addParticle(eParticleType_snowballpoof, x, y, z, 0, 0, 0); - if (!level->isClientSide) - { - remove(); - } + DamageSource* damageSource = + DamageSource::thrown(shared_from_this(), owner); + res->entity->hurt(damageSource, damage); + delete damageSource; + } + for (int i = 0; i < 8; i++) + level->addParticle(eParticleType_snowballpoof, x, y, z, 0, 0, 0); + if (!level->isClientSide) { + remove(); + } } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Snowball.h b/Minecraft.World/Entities/Mobs/Snowball.h index 145fb780d..a91978adb 100644 --- a/Minecraft.World/Entities/Mobs/Snowball.h +++ b/Minecraft.World/Entities/Mobs/Snowball.h @@ -1,24 +1,22 @@ #pragma once - #include "../Throwable.h" class HitResult; -class Snowball : public Throwable -{ +class Snowball : public Throwable { public: - eINSTANCEOF GetType() { return eTYPE_SNOWBALL; } - static Entity *create(Level *level) { return new Snowball(level); } + eINSTANCEOF GetType() { return eTYPE_SNOWBALL; } + static Entity* create(Level* level) { return new Snowball(level); } private: - void _init(); + void _init(); public: - Snowball(Level *level); - Snowball(Level *level, std::shared_ptr mob); - Snowball(Level *level, double x, double y, double z); + Snowball(Level* level); + Snowball(Level* level, std::shared_ptr mob); + Snowball(Level* level, double x, double y, double z); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Spider.cpp b/Minecraft.World/Entities/Mobs/Spider.cpp index 57c8348b0..ce721bbf9 100644 --- a/Minecraft.World/Entities/Mobs/Spider.cpp +++ b/Minecraft.World/Entities/Mobs/Spider.cpp @@ -11,131 +11,95 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" +Spider::Spider(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Spider::Spider(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); - - this->textureIdx = TN_MOB_SPIDER; // 4J was L"/mob/spider.png"; - this->setSize(1.4f, 0.9f); - runSpeed = 0.8f; + this->textureIdx = TN_MOB_SPIDER; // 4J was L"/mob/spider.png"; + this->setSize(1.4f, 0.9f); + runSpeed = 0.8f; } -void Spider::defineSynchedData() -{ - Monster::defineSynchedData(); +void Spider::defineSynchedData() { + Monster::defineSynchedData(); - entityData->define(DATA_FLAGS_ID, (uint8_t) 0); + entityData->define(DATA_FLAGS_ID, (uint8_t)0); } -void Spider::tick() -{ - Monster::tick(); +void Spider::tick() { + Monster::tick(); - if (!level->isClientSide) - { - // this is to synchronize the spiders' climb state - // in multiplayer (to stop them from "flashing") - setClimbing(horizontalCollision); - } + if (!level->isClientSide) { + // this is to synchronize the spiders' climb state + // in multiplayer (to stop them from "flashing") + setClimbing(horizontalCollision); + } } -int Spider::getMaxHealth() -{ - return 16; -} +int Spider::getMaxHealth() { return 16; } -double Spider::getRideHeight() -{ - return bbHeight * 0.75 - 0.5f; -} +double Spider::getRideHeight() { return bbHeight * 0.75 - 0.5f; } -bool Spider::makeStepSound() -{ - return false; -} +bool Spider::makeStepSound() { return false; } -std::shared_ptr Spider::findAttackTarget() -{ +std::shared_ptr Spider::findAttackTarget() { #ifndef _FINAL_BUILD #ifdef _DEBUG_MENUS_ENABLED - if(app.GetMobsDontAttackEnabled()) - { - return std::shared_ptr(); - } + if (app.GetMobsDontAttackEnabled()) { + return std::shared_ptr(); + } #endif #endif - float br = getBrightness(1); - if (br < 0.5f) - { - double maxDist = 16; - return level->getNearestAttackablePlayer(shared_from_this(), maxDist); - } - return std::shared_ptr(); + float br = getBrightness(1); + if (br < 0.5f) { + double maxDist = 16; + return level->getNearestAttackablePlayer(shared_from_this(), maxDist); + } + return std::shared_ptr(); } -int Spider::getAmbientSound() -{ - return eSoundType_MOB_SPIDER_AMBIENT; +int Spider::getAmbientSound() { return eSoundType_MOB_SPIDER_AMBIENT; } + +int Spider::getHurtSound() { return eSoundType_MOB_SPIDER_AMBIENT; } + +int Spider::getDeathSound() { return eSoundType_MOB_SPIDER_DEATH; } + +void Spider::checkHurtTarget(std::shared_ptr target, float d) { + float br = getBrightness(1); + if (br > 0.5f && random->nextInt(100) == 0) { + this->attackTarget = nullptr; + return; + } + + if (d > 2 && d < 6 && random->nextInt(10) == 0) { + if (onGround) { + double xdd = target->x - x; + double zdd = target->z - z; + float dd = (float)sqrt(xdd * xdd + zdd * zdd); + xd = (xdd / dd * 0.5f) * 0.8f + xd * 0.2f; + zd = (zdd / dd * 0.5f) * 0.8f + zd * 0.2f; + yd = 0.4f; + } + } else { + Monster::checkHurtTarget(target, d); + } } -int Spider::getHurtSound() -{ - return eSoundType_MOB_SPIDER_AMBIENT; -} +int Spider::getDeathLoot() { return Item::string->id; } -int Spider::getDeathSound() -{ - return eSoundType_MOB_SPIDER_DEATH; -} +void Spider::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + Monster::dropDeathLoot(wasKilledByPlayer, playerBonusLevel); -void Spider::checkHurtTarget(std::shared_ptr target, float d) -{ - float br = getBrightness(1); - if (br > 0.5f && random->nextInt(100) == 0) - { - this->attackTarget = nullptr; - return; - } - - if (d > 2 && d < 6 && random->nextInt(10) == 0) - { - if (onGround) - { - double xdd = target->x - x; - double zdd = target->z - z; - float dd = (float) sqrt(xdd * xdd + zdd * zdd); - xd = (xdd / dd * 0.5f) * 0.8f + xd * 0.2f; - zd = (zdd / dd * 0.5f) * 0.8f + zd * 0.2f; - yd = 0.4f; - } - } - else - { - Monster::checkHurtTarget(target, d); - } -} - -int Spider::getDeathLoot() -{ - return Item::string->id; -} - -void Spider::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - Monster::dropDeathLoot(wasKilledByPlayer, playerBonusLevel); - - if (wasKilledByPlayer && (random->nextInt(3) == 0 || random->nextInt(1 + playerBonusLevel) > 0)) - { - spawnAtLocation(Item::spiderEye_Id, 1); - } + if (wasKilledByPlayer && (random->nextInt(3) == 0 || + random->nextInt(1 + playerBonusLevel) > 0)) { + spawnAtLocation(Item::spiderEye_Id, 1); + } } /** @@ -143,50 +107,33 @@ void Spider::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) * to climb walls. */ -bool Spider::onLadder() -{ - return isClimbing(); -} - -void Spider::makeStuckInWeb() -{ - // do nothing - spiders don't get stuck in web +bool Spider::onLadder() { return isClimbing(); } + +void Spider::makeStuckInWeb() { + // do nothing - spiders don't get stuck in web } -float Spider::getModelScale() -{ - return 1.0f; +float Spider::getModelScale() { return 1.0f; } + +MobType Spider::getMobType() { return ARTHROPOD; } + +bool Spider::canBeAffected(MobEffectInstance* newEffect) { + if (newEffect->getId() == MobEffect::poison->id) { + return false; + } + return Monster::canBeAffected(newEffect); } -MobType Spider::getMobType() -{ - return ARTHROPOD; +bool Spider::isClimbing() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x1) != 0; } -bool Spider::canBeAffected(MobEffectInstance *newEffect) -{ - if (newEffect->getId() == MobEffect::poison->id) - { - return false; - } - return Monster::canBeAffected(newEffect); -} - -bool Spider::isClimbing() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x1) != 0; -} - -void Spider::setClimbing(bool value) -{ - uint8_t flags = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - flags |= 0x1; - } - else - { - flags &= ~0x1; - } - entityData->set(DATA_FLAGS_ID, flags); +void Spider::setClimbing(bool value) { + uint8_t flags = entityData->getByte(DATA_FLAGS_ID); + if (value) { + flags |= 0x1; + } else { + flags &= ~0x1; + } + entityData->set(DATA_FLAGS_ID, flags); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Spider.h b/Minecraft.World/Entities/Mobs/Spider.h index 13722f888..6642de01a 100644 --- a/Minecraft.World/Entities/Mobs/Spider.h +++ b/Minecraft.World/Entities/Mobs/Spider.h @@ -1,45 +1,43 @@ #pragma once - #include "../Monster.h" -class Spider : public Monster -{ +class Spider : public Monster { public: - eINSTANCEOF GetType() { return eTYPE_SPIDER; } - static Entity *create(Level *level) { return new Spider(level); } + eINSTANCEOF GetType() { return eTYPE_SPIDER; } + static Entity* create(Level* level) { return new Spider(level); } private: - static const int DATA_FLAGS_ID = 16; + static const int DATA_FLAGS_ID = 16; public: - Spider(Level *level); + Spider(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void tick(); - virtual int getMaxHealth(); + virtual void tick(); + virtual int getMaxHealth(); virtual double getRideHeight(); protected: - virtual bool makeStepSound(); - virtual std::shared_ptr findAttackTarget(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual bool makeStepSound(); + virtual std::shared_ptr findAttackTarget(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); virtual void checkHurtTarget(std::shared_ptr target, float d); - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual bool onLadder(); - - virtual void makeStuckInWeb(); - virtual float getModelScale(); - virtual MobType getMobType(); - virtual bool canBeAffected(MobEffectInstance *newEffect); - virtual bool isClimbing(); - virtual void setClimbing(bool value); + virtual bool onLadder(); + + virtual void makeStuckInWeb(); + virtual float getModelScale(); + virtual MobType getMobType(); + virtual bool canBeAffected(MobEffectInstance* newEffect); + virtual bool isClimbing(); + virtual void setClimbing(bool value); }; diff --git a/Minecraft.World/Entities/Mobs/Squid.cpp b/Minecraft.World/Entities/Mobs/Squid.cpp index 7fd618fd2..6eb0eba1b 100644 --- a/Minecraft.World/Entities/Mobs/Squid.cpp +++ b/Minecraft.World/Entities/Mobs/Squid.cpp @@ -10,180 +10,144 @@ #include "Squid.h" #include "../../../Minecraft.Client/Textures/Textures.h" +void Squid::_init() { + xBodyRot = xBodyRotO = 0.0f; + zBodyRot = zBodyRotO = 0.0f; + tentacleMovement = oldTentacleMovement = 0.0f; + tentacleAngle = oldTentacleAngle = 0.0f; -void Squid::_init() -{ - xBodyRot = xBodyRotO = 0.0f; - zBodyRot = zBodyRotO = 0.0f; + speed = 0.0f; + tentacleSpeed = 0.0f; + rotateSpeed = 0.0f; - tentacleMovement = oldTentacleMovement = 0.0f; - tentacleAngle = oldTentacleAngle = 0.0f; - - speed = 0.0f; - tentacleSpeed = 0.0f; - rotateSpeed = 0.0f; - - tx = ty = tz = 0.0f; + tx = ty = tz = 0.0f; } -Squid::Squid(Level *level) : WaterAnimal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Squid::Squid(Level* level) : WaterAnimal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - _init(); - this->textureIdx = TN_MOB_SQUID; // 4J - was L"/mob/squid.png"; - this->setSize(0.95f, 0.95f); - tentacleSpeed = 1 / (random->nextFloat() + 1) * 0.2f; + _init(); + this->textureIdx = TN_MOB_SQUID; // 4J - was L"/mob/squid.png"; + this->setSize(0.95f, 0.95f); + tentacleSpeed = 1 / (random->nextFloat() + 1) * 0.2f; } -int Squid::getMaxHealth() -{ - return 10; +int Squid::getMaxHealth() { return 10; } + +int Squid::getAmbientSound() { return -1; } + +int Squid::getHurtSound() { return -1; } + +int Squid::getDeathSound() { return -1; } + +float Squid::getSoundVolume() { return 0.4f; } + +int Squid::getDeathLoot() { return 0; } + +void Squid::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { + int count = random->nextInt(3 + playerBonusLevel) + 1; + for (int i = 0; i < count; i++) { + spawnAtLocation(std::shared_ptr(new ItemInstance( + Item::dye_powder, 1, DyePowderItem::BLACK)), + 0.0f); + } } -int Squid::getAmbientSound() -{ - return -1; +bool Squid::isInWater() { + return level->checkAndHandleWater(bb->grow(0, -0.6f, 0), Material::water, + shared_from_this()); } -int Squid::getHurtSound() -{ - return -1; +void Squid::aiStep() { + WaterAnimal::aiStep(); + + xBodyRotO = xBodyRot; + zBodyRotO = zBodyRot; + + oldTentacleMovement = tentacleMovement; + oldTentacleAngle = tentacleAngle; + + tentacleMovement += tentacleSpeed; + if (tentacleMovement > (float)PI * 2.0f) { + tentacleMovement -= (float)PI * 2.0f; + if (random->nextInt(10) == 0) + tentacleSpeed = 1 / (random->nextFloat() + 1) * 0.2f; + } + + if (isInWater()) { + if (tentacleMovement < PI) { + float tentacleScale = tentacleMovement / PI; + tentacleAngle = + Mth::sin(tentacleScale * tentacleScale * PI) * PI * 0.25f; + + if (tentacleScale > .75) { + speed = 1.0f; + rotateSpeed = 1.0f; + } else { + rotateSpeed = rotateSpeed * 0.8f; + } + } else { + tentacleAngle = 0.0f; + speed = speed * 0.9f; + rotateSpeed = rotateSpeed * 0.99f; + } + + if (!level->isClientSide) { + xd = tx * speed; + yd = ty * speed; + zd = tz * speed; + } + + double horizontalMovement = sqrt(xd * xd + zd * zd); + + yBodyRot += + ((-(float)atan2(this->xd, this->zd) * 180 / PI) - yBodyRot) * 0.1f; + yRot = yBodyRot; + zBodyRot = zBodyRot + (float)PI * rotateSpeed * 1.5f; + xBodyRot += ((-(float)atan2(horizontalMovement, this->yd) * 180 / PI) - + xBodyRot) * + 0.1f; + } else { + tentacleAngle = Mth::abs(Mth::sin(tentacleMovement)) * PI * 0.25f; + + if (!level->isClientSide) { + // unable to move, apply gravity + xd = 0.0f; + yd -= 0.08; + yd *= 0.98f; + zd = 0.0f; + } + + // fall over + xBodyRot += (-90 - xBodyRot) * 0.02f; + } } -int Squid::getDeathSound() -{ - return -1; +void Squid::travel(float xa, float ya) { move(xd, yd, zd); } + +void Squid::serverAiStep() { + noActionTime++; + + // ridiculous simple movement ai + if (noActionTime > SharedConstants::TICKS_PER_SECOND * 5) { + tx = ty = tz = 0; + } else if (random->nextInt(50) == 0 || !wasInWater || + (tx == 0 && ty == 0 && tz == 0)) { + float angle = random->nextFloat() * PI * 2.0f; + tx = Mth::cos(angle) * 0.2f; + ty = -0.1f + random->nextFloat() * 0.2f; + tz = Mth::sin(angle) * 0.2f; + } + checkDespawn(); // 4J - 1.7.0 fix } -float Squid::getSoundVolume() -{ - return 0.4f; -} - -int Squid::getDeathLoot() -{ - return 0; -} - -void Squid::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int count = random->nextInt(3 + playerBonusLevel) + 1; - for (int i = 0; i < count; i++) - { - spawnAtLocation(std::shared_ptr( new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLACK) ), 0.0f); - } -} - -bool Squid::isInWater() -{ - return level->checkAndHandleWater(bb->grow(0, -0.6f, 0), Material::water, shared_from_this() ); -} - -void Squid::aiStep() -{ - WaterAnimal::aiStep(); - - xBodyRotO = xBodyRot; - zBodyRotO = zBodyRot; - - oldTentacleMovement = tentacleMovement; - oldTentacleAngle = tentacleAngle; - - tentacleMovement += tentacleSpeed; - if (tentacleMovement > (float) PI * 2.0f) - { - tentacleMovement -= (float) PI * 2.0f; - if (random->nextInt(10) == 0) tentacleSpeed = 1 / (random->nextFloat() + 1) * 0.2f; - } - - if (isInWater()) - { - if (tentacleMovement < PI) - { - float tentacleScale = tentacleMovement / PI; - tentacleAngle = Mth::sin(tentacleScale * tentacleScale * PI) * PI * 0.25f; - - if (tentacleScale > .75) - { - speed = 1.0f; - rotateSpeed = 1.0f; - } - else - { - rotateSpeed = rotateSpeed * 0.8f; - } - } - else - { - tentacleAngle = 0.0f; - speed = speed * 0.9f; - rotateSpeed = rotateSpeed * 0.99f; - } - - if (!level->isClientSide) - { - xd = tx * speed; - yd = ty * speed; - zd = tz * speed; - } - - double horizontalMovement = sqrt(xd * xd + zd * zd); - - yBodyRot += ((-(float) atan2(this->xd, this->zd) * 180 / PI) - yBodyRot) * 0.1f; - yRot = yBodyRot; - zBodyRot = zBodyRot + (float) PI * rotateSpeed * 1.5f; - xBodyRot += ((-(float) atan2(horizontalMovement, this->yd) * 180 / PI) - xBodyRot) * 0.1f; - } - else - { - tentacleAngle = Mth::abs(Mth::sin(tentacleMovement)) * PI * 0.25f; - - if (!level->isClientSide) - { - // unable to move, apply gravity - xd = 0.0f; - yd -= 0.08; - yd *= 0.98f; - zd = 0.0f; - } - - // fall over - xBodyRot += (-90 - xBodyRot) * 0.02f; - } -} - -void Squid::travel(float xa, float ya) -{ - move(xd, yd, zd); -} - -void Squid::serverAiStep() -{ - noActionTime++; - - // ridiculous simple movement ai - if (noActionTime > SharedConstants::TICKS_PER_SECOND * 5) - { - tx = ty = tz = 0; - } - else if (random->nextInt(50) == 0 || !wasInWater || (tx == 0 && ty == 0 && tz == 0)) - { - float angle = random->nextFloat() * PI * 2.0f; - tx = Mth::cos(angle) * 0.2f; - ty = -0.1f + random->nextFloat() * 0.2f; - tz = Mth::sin(angle) * 0.2f; - } - checkDespawn(); // 4J - 1.7.0 fix -} - -bool Squid::canSpawn() -{ - return y > 45 && y < level->seaLevel && WaterAnimal::canSpawn(); +bool Squid::canSpawn() { + return y > 45 && y < level->seaLevel && WaterAnimal::canSpawn(); } diff --git a/Minecraft.World/Entities/Mobs/Squid.h b/Minecraft.World/Entities/Mobs/Squid.h index 2cf6d14f9..64991b11a 100644 --- a/Minecraft.World/Entities/Mobs/Squid.h +++ b/Minecraft.World/Entities/Mobs/Squid.h @@ -1,52 +1,49 @@ #pragma once - - #include "../WaterAnimal.h" class Player; -class Squid : public WaterAnimal -{ +class Squid : public WaterAnimal { public: - eINSTANCEOF GetType() { return eTYPE_SQUID; } - static Entity *create(Level *level) { return new Squid(level); } + eINSTANCEOF GetType() { return eTYPE_SQUID; } + static Entity* create(Level* level) { return new Squid(level); } - void _init(); + void _init(); - float xBodyRot, xBodyRotO; - float zBodyRot, zBodyRotO; + float xBodyRot, xBodyRotO; + float zBodyRot, zBodyRotO; - float tentacleMovement, oldTentacleMovement; - float tentacleAngle, oldTentacleAngle; + float tentacleMovement, oldTentacleMovement; + float tentacleAngle, oldTentacleAngle; private: - float speed; - float tentacleSpeed; - float rotateSpeed; + float speed; + float tentacleSpeed; + float rotateSpeed; - float tx, ty, tz; + float tx, ty, tz; public: - Squid(Level *level); - virtual int getMaxHealth(); + Squid(Level* level); + virtual int getMaxHealth(); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual float getSoundVolume(); - virtual int getDeathLoot(); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual float getSoundVolume(); + virtual int getDeathLoot(); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual bool isInWater(); - virtual void aiStep(); - virtual void travel(float xa, float ya); + virtual bool isInWater(); + virtual void aiStep(); + virtual void travel(float xa, float ya); protected: - virtual void serverAiStep(); + virtual void serverAiStep(); public: - virtual bool canSpawn(); + virtual bool canSpawn(); }; diff --git a/Minecraft.World/Entities/Mobs/ThrownEgg.cpp b/Minecraft.World/Entities/Mobs/ThrownEgg.cpp index b4ed80291..8c01266df 100644 --- a/Minecraft.World/Entities/Mobs/ThrownEgg.cpp +++ b/Minecraft.World/Entities/Mobs/ThrownEgg.cpp @@ -7,61 +7,56 @@ #include "ThrownEgg.h" #include "../MobCategory.h" - - -void ThrownEgg::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void ThrownEgg::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -ThrownEgg::ThrownEgg(Level *level) : Throwable(level) -{ - _init(); +ThrownEgg::ThrownEgg(Level* level) : Throwable(level) { _init(); } + +ThrownEgg::ThrownEgg(Level* level, std::shared_ptr mob) + : Throwable(level, mob) { + _init(); } -ThrownEgg::ThrownEgg(Level *level, std::shared_ptr mob) : Throwable(level,mob) -{ - _init(); +ThrownEgg::ThrownEgg(Level* level, double x, double y, double z) + : Throwable(level, x, y, z) { + _init(); } -ThrownEgg::ThrownEgg(Level *level, double x, double y, double z) : Throwable(level,x,y,z) -{ - _init(); -} - -void ThrownEgg::onHit(HitResult *res) -{ - if (res->entity != NULL) - { - DamageSource *damageSource = DamageSource::thrown(shared_from_this(), owner); - res->entity->hurt(damageSource, 0); - delete damageSource; - } - if (!level->isClientSide && random->nextInt(8) == 0) - { - if(level->canCreateMore( eTYPE_CHICKEN, Level::eSpawnType_Breed) ) // 4J - added limit for number of chickens in world - { - int count = 1; - if (random->nextInt(32) == 0) count = 4; - for (int i = 0; i < count; i++) - { - std::shared_ptr chicken = std::shared_ptr( new Chicken(level) ); - chicken->setAge(-20 * 60 * 20); - - chicken->moveTo(x, y, z, yRot, 0); - chicken->setDespawnProtected(); // 4J added, default to being protected against despawning - level->addEntity(chicken); - } - } - } - - for (int i = 0; i < 8; i++) - level->addParticle(eParticleType_snowballpoof, x, y, z, 0, 0, 0); - - if (!level->isClientSide) - { - remove(); - } +void ThrownEgg::onHit(HitResult* res) { + if (res->entity != NULL) { + DamageSource* damageSource = + DamageSource::thrown(shared_from_this(), owner); + res->entity->hurt(damageSource, 0); + delete damageSource; + } + if (!level->isClientSide && random->nextInt(8) == 0) { + if (level->canCreateMore( + eTYPE_CHICKEN, + Level::eSpawnType_Breed)) // 4J - added limit for number of + // chickens in world + { + int count = 1; + if (random->nextInt(32) == 0) count = 4; + for (int i = 0; i < count; i++) { + std::shared_ptr chicken = + std::shared_ptr(new Chicken(level)); + chicken->setAge(-20 * 60 * 20); + + chicken->moveTo(x, y, z, yRot, 0); + chicken->setDespawnProtected(); // 4J added, default to being + // protected against despawning + level->addEntity(chicken); + } + } + } + + for (int i = 0; i < 8; i++) + level->addParticle(eParticleType_snowballpoof, x, y, z, 0, 0, 0); + + if (!level->isClientSide) { + remove(); + } } diff --git a/Minecraft.World/Entities/Mobs/ThrownEgg.h b/Minecraft.World/Entities/Mobs/ThrownEgg.h index 830f9eae8..bda47e94d 100644 --- a/Minecraft.World/Entities/Mobs/ThrownEgg.h +++ b/Minecraft.World/Entities/Mobs/ThrownEgg.h @@ -1,23 +1,21 @@ #pragma once - #include "../Throwable.h" class HitResult; -class ThrownEgg : public Throwable -{ +class ThrownEgg : public Throwable { public: - eINSTANCEOF GetType() { return eTYPE_THROWNEGG; } + eINSTANCEOF GetType() { return eTYPE_THROWNEGG; } private: - void _init(); + void _init(); public: - ThrownEgg(Level *level); - ThrownEgg(Level *level, std::shared_ptr mob); - ThrownEgg(Level *level, double x, double y, double z); + ThrownEgg(Level* level); + ThrownEgg(Level* level, std::shared_ptr mob); + ThrownEgg(Level* level, double x, double y, double z); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); }; diff --git a/Minecraft.World/Entities/Mobs/ThrownEnderPearl.cpp b/Minecraft.World/Entities/Mobs/ThrownEnderPearl.cpp index a52358f68..1eb3f2370 100644 --- a/Minecraft.World/Entities/Mobs/ThrownEnderPearl.cpp +++ b/Minecraft.World/Entities/Mobs/ThrownEnderPearl.cpp @@ -7,56 +7,54 @@ #include "../../../Minecraft.Client/Network/PlayerConnection.h" #include "ThrownEnderPearl.h" - - -ThrownEnderpearl::ThrownEnderpearl(Level *level) : Throwable(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +ThrownEnderpearl::ThrownEnderpearl(Level* level) : Throwable(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -ThrownEnderpearl::ThrownEnderpearl(Level *level, std::shared_ptr mob) : Throwable(level,mob) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +ThrownEnderpearl::ThrownEnderpearl(Level* level, std::shared_ptr mob) + : Throwable(level, mob) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -ThrownEnderpearl::ThrownEnderpearl(Level *level, double x, double y, double z) : Throwable(level,x,y,z) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +ThrownEnderpearl::ThrownEnderpearl(Level* level, double x, double y, double z) + : Throwable(level, x, y, z) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); } -void ThrownEnderpearl::onHit(HitResult *res) -{ - if (res->entity != NULL) - { - DamageSource *damageSource = DamageSource::thrown(shared_from_this(), owner); - res->entity->hurt(damageSource, 0); - delete damageSource; - } - for (int i = 0; i < 32; i++) - { - level->addParticle(eParticleType_ender, x, y + random->nextDouble() * 2, z, random->nextGaussian(), 0, random->nextGaussian()); - } +void ThrownEnderpearl::onHit(HitResult* res) { + if (res->entity != NULL) { + DamageSource* damageSource = + DamageSource::thrown(shared_from_this(), owner); + res->entity->hurt(damageSource, 0); + delete damageSource; + } + for (int i = 0; i < 32; i++) { + level->addParticle(eParticleType_ender, x, y + random->nextDouble() * 2, + z, random->nextGaussian(), 0, + random->nextGaussian()); + } - if (!level->isClientSide) - { - // Fix for #67486 - TCR #001: BAS Game Stability: Customer Encountered: TU8: Code: Gameplay: The title crashes on Host's console when Client Player leaves the game before the Ender Pearl thrown by him touches the ground. - // If the owner has been removed, then ignore - std::shared_ptr serverPlayer = std::dynamic_pointer_cast(owner); - if (serverPlayer != NULL && !serverPlayer->removed) - { - if(!serverPlayer->connection->done && serverPlayer->level == this->level) - { - owner->teleportTo(x, y, z); - owner->fallDistance = 0; - owner->hurt(DamageSource::fall, 5); - } - } - remove(); - } + if (!level->isClientSide) { + // Fix for #67486 - TCR #001: BAS Game Stability: Customer Encountered: + // TU8: Code: Gameplay: The title crashes on Host's console when Client + // Player leaves the game before the Ender Pearl thrown by him touches + // the ground. If the owner has been removed, then ignore + std::shared_ptr serverPlayer = + std::dynamic_pointer_cast(owner); + if (serverPlayer != NULL && !serverPlayer->removed) { + if (!serverPlayer->connection->done && + serverPlayer->level == this->level) { + owner->teleportTo(x, y, z); + owner->fallDistance = 0; + owner->hurt(DamageSource::fall, 5); + } + } + remove(); + } } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ThrownEnderPearl.h b/Minecraft.World/Entities/Mobs/ThrownEnderPearl.h index bf24eb0b3..62d4f4598 100644 --- a/Minecraft.World/Entities/Mobs/ThrownEnderPearl.h +++ b/Minecraft.World/Entities/Mobs/ThrownEnderPearl.h @@ -4,16 +4,15 @@ class HitResult; -class ThrownEnderpearl : public Throwable -{ +class ThrownEnderpearl : public Throwable { public: - eINSTANCEOF GetType() { return eTYPE_THROWNENDERPEARL; } - static Entity *create(Level *level) { return new ThrownEnderpearl(level); } + eINSTANCEOF GetType() { return eTYPE_THROWNENDERPEARL; } + static Entity* create(Level* level) { return new ThrownEnderpearl(level); } - ThrownEnderpearl(Level *level); - ThrownEnderpearl(Level *level, std::shared_ptr mob); - ThrownEnderpearl(Level *level, double x, double y, double z); + ThrownEnderpearl(Level* level); + ThrownEnderpearl(Level* level, std::shared_ptr mob); + ThrownEnderpearl(Level* level, double x, double y, double z); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ThrownExpBottle.cpp b/Minecraft.World/Entities/Mobs/ThrownExpBottle.cpp index 3ecef731c..a2e5acfa0 100644 --- a/Minecraft.World/Entities/Mobs/ThrownExpBottle.cpp +++ b/Minecraft.World/Entities/Mobs/ThrownExpBottle.cpp @@ -5,51 +5,34 @@ #include "../../Util/JavaMath.h" #include "ThrownExpBottle.h" +ThrownExpBottle::ThrownExpBottle(Level* level) : Throwable(level) {} +ThrownExpBottle::ThrownExpBottle(Level* level, std::shared_ptr mob) + : Throwable(level, mob) {} -ThrownExpBottle::ThrownExpBottle(Level *level) : Throwable(level) -{ -} +ThrownExpBottle::ThrownExpBottle(Level* level, double x, double y, double z) + : Throwable(level, x, y, z) {} -ThrownExpBottle::ThrownExpBottle(Level *level, std::shared_ptr mob) : Throwable(level,mob) -{ -} +float ThrownExpBottle::getGravity() { return 0.07f; } -ThrownExpBottle::ThrownExpBottle(Level *level, double x, double y, double z) : Throwable(level, x, y, z) -{ -} +float ThrownExpBottle::getThrowPower() { return 0.7f; } +float ThrownExpBottle::getThrowUpAngleOffset() { return -20; } -float ThrownExpBottle::getGravity() -{ - return 0.07f; -} +void ThrownExpBottle::onHit(HitResult* res) { + if (!level->isClientSide) { + level->levelEvent(LevelEvent::PARTICLES_POTION_SPLASH, + (int)Math::round(x), (int)Math::round(y), + (int)Math::round(z), 0); -float ThrownExpBottle::getThrowPower() -{ - return 0.7f; -} + int xpCount = 3 + level->random->nextInt(5) + level->random->nextInt(5); + while (xpCount > 0) { + int newCount = ExperienceOrb::getExperienceValue(xpCount); + xpCount -= newCount; + level->addEntity(std::shared_ptr( + new ExperienceOrb(level, x, y, z, newCount))); + } -float ThrownExpBottle::getThrowUpAngleOffset() -{ - return -20; -} - -void ThrownExpBottle::onHit(HitResult *res) -{ - - if (!level->isClientSide) - { - level->levelEvent(LevelEvent::PARTICLES_POTION_SPLASH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), 0); - - int xpCount = 3 + level->random->nextInt(5) + level->random->nextInt(5); - while (xpCount > 0) - { - int newCount = ExperienceOrb::getExperienceValue(xpCount); - xpCount -= newCount; - level->addEntity(std::shared_ptr( new ExperienceOrb(level, x, y, z, newCount) ) ); - } - - remove(); - } + remove(); + } } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ThrownExpBottle.h b/Minecraft.World/Entities/Mobs/ThrownExpBottle.h index 7f533991b..262d3dd83 100644 --- a/Minecraft.World/Entities/Mobs/ThrownExpBottle.h +++ b/Minecraft.World/Entities/Mobs/ThrownExpBottle.h @@ -4,19 +4,19 @@ class HitResult; -class ThrownExpBottle : public Throwable -{ +class ThrownExpBottle : public Throwable { public: - eINSTANCEOF GetType() { return eTYPE_THROWNEXPBOTTLE; } - static Entity *create(Level *level) { return new ThrownExpBottle(level); } + eINSTANCEOF GetType() { return eTYPE_THROWNEXPBOTTLE; } + static Entity* create(Level* level) { return new ThrownExpBottle(level); } + public: - ThrownExpBottle(Level *level); - ThrownExpBottle(Level *level, std::shared_ptr mob); - ThrownExpBottle(Level *level, double x, double y, double z); + ThrownExpBottle(Level* level); + ThrownExpBottle(Level* level, std::shared_ptr mob); + ThrownExpBottle(Level* level, double x, double y, double z); protected: - virtual float getGravity(); - virtual float getThrowPower(); - virtual float getThrowUpAngleOffset(); - virtual void onHit(HitResult *res); + virtual float getGravity(); + virtual float getThrowPower(); + virtual float getThrowUpAngleOffset(); + virtual void onHit(HitResult* res); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ThrownPotion.cpp b/Minecraft.World/Entities/Mobs/ThrownPotion.cpp index 7a514d22b..57d625ccb 100644 --- a/Minecraft.World/Entities/Mobs/ThrownPotion.cpp +++ b/Minecraft.World/Entities/Mobs/ThrownPotion.cpp @@ -8,129 +8,113 @@ #include "../../Util/JavaMath.h" #include "ThrownPotion.h" - - const double ThrownPotion::SPLASH_RANGE = 4.0; -const double ThrownPotion::SPLASH_RANGE_SQ = ThrownPotion::SPLASH_RANGE * ThrownPotion::SPLASH_RANGE; +const double ThrownPotion::SPLASH_RANGE_SQ = + ThrownPotion::SPLASH_RANGE * ThrownPotion::SPLASH_RANGE; -void ThrownPotion::_init() -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void ThrownPotion::_init() { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - potionValue = 0; + potionValue = 0; } -ThrownPotion::ThrownPotion(Level *level) : Throwable(level) -{ - _init(); +ThrownPotion::ThrownPotion(Level* level) : Throwable(level) { _init(); } + +ThrownPotion::ThrownPotion(Level* level, std::shared_ptr mob, + int potionValue) + : Throwable(level, mob) { + _init(); + + this->potionValue = potionValue; } -ThrownPotion::ThrownPotion(Level *level, std::shared_ptr mob, int potionValue) : Throwable(level,mob) -{ - _init(); - - this->potionValue = potionValue; +ThrownPotion::ThrownPotion(Level* level, double x, double y, double z, + int potionValue) + : Throwable(level, x, y, z) { + _init(); + this->potionValue = potionValue; } -ThrownPotion::ThrownPotion(Level *level, double x, double y, double z, int potionValue) : Throwable(level,x,y,z) -{ - _init(); - this->potionValue = potionValue; +float ThrownPotion::getGravity() { return 0.05f; } + +float ThrownPotion::getThrowPower() { return 0.5f; } + +float ThrownPotion::getThrowUpAngleOffset() { return -20; } + +void ThrownPotion::setPotionValue(int potionValue) { + this->potionValue = potionValue; } -float ThrownPotion::getGravity() -{ - return 0.05f; +int ThrownPotion::getPotionValue() { return potionValue; } + +void ThrownPotion::onHit(HitResult* res) { + if (!level->isClientSide) { + std::vector* mobEffects = + Item::potion->getMobEffects(potionValue); + + if (mobEffects != NULL && !mobEffects->empty()) { + AABB* aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); + std::vector >* entitiesOfClass = + level->getEntitiesOfClass(typeid(Mob), aoe); + + if (entitiesOfClass != NULL && !entitiesOfClass->empty()) { + // for (Entity e : entitiesOfClass) + for (AUTO_VAR(it, entitiesOfClass->begin()); + it != entitiesOfClass->end(); ++it) { + // std::shared_ptr e = *it; + std::shared_ptr e = + std::dynamic_pointer_cast(*it); + double dist = distanceToSqr(e); + if (dist < SPLASH_RANGE_SQ) { + double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); + if (e == res->entity) { + scale = 1; + } + + // for (MobEffectInstance effect : mobEffects) + for (AUTO_VAR(itMEI, mobEffects->begin()); + itMEI != mobEffects->end(); ++itMEI) { + MobEffectInstance* effect = *itMEI; + int id = effect->getId(); + if (MobEffect::effects[id]->isInstantenous()) { + MobEffect::effects[id]->applyInstantenousEffect( + this->owner, e, effect->getAmplifier(), + scale); + } else { + int duration = + (int)(scale * + (double)effect->getDuration() + + .5); + if (duration > + SharedConstants::TICKS_PER_SECOND) { + e->addEffect(new MobEffectInstance( + id, duration, effect->getAmplifier())); + } + } + } + } + } + } + delete entitiesOfClass; + } + level->levelEvent(LevelEvent::PARTICLES_POTION_SPLASH, + (int)Math::round(x), (int)Math::round(y), + (int)Math::round(z), potionValue); + + remove(); + } } -float ThrownPotion::getThrowPower() -{ - return 0.5f; +void ThrownPotion::readAdditionalSaveData(CompoundTag* tag) { + Throwable::readAdditionalSaveData(tag); + + potionValue = tag->getInt(L"potionValue"); } -float ThrownPotion::getThrowUpAngleOffset() -{ - return -20; -} +void ThrownPotion::addAdditonalSaveData(CompoundTag* tag) { + Throwable::addAdditonalSaveData(tag); -void ThrownPotion::setPotionValue(int potionValue) -{ - this->potionValue = potionValue; -} - -int ThrownPotion::getPotionValue() -{ - return potionValue; -} - -void ThrownPotion::onHit(HitResult *res) -{ - if (!level->isClientSide) - { - std::vector *mobEffects = Item::potion->getMobEffects(potionValue); - - if (mobEffects != NULL && !mobEffects->empty()) - { - AABB *aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); - std::vector > *entitiesOfClass = level->getEntitiesOfClass(typeid(Mob), aoe); - - if (entitiesOfClass != NULL && !entitiesOfClass->empty()) - { - //for (Entity e : entitiesOfClass) - for(AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) - { - //std::shared_ptr e = *it; - std::shared_ptr e = std::dynamic_pointer_cast( *it ); - double dist = distanceToSqr(e); - if (dist < SPLASH_RANGE_SQ) - { - double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); - if (e == res->entity) - { - scale = 1; - } - - //for (MobEffectInstance effect : mobEffects) - for(AUTO_VAR(itMEI, mobEffects->begin()); itMEI != mobEffects->end(); ++itMEI) - { - MobEffectInstance *effect = *itMEI; - int id = effect->getId(); - if (MobEffect::effects[id]->isInstantenous()) - { - MobEffect::effects[id]->applyInstantenousEffect(this->owner, e, effect->getAmplifier(), scale); - } - else - { - int duration = (int) (scale * (double) effect->getDuration() + .5); - if (duration > SharedConstants::TICKS_PER_SECOND) - { - e->addEffect(new MobEffectInstance(id, duration, effect->getAmplifier())); - } - } - } - } - } - } - delete entitiesOfClass; - } - level->levelEvent(LevelEvent::PARTICLES_POTION_SPLASH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), potionValue); - - remove(); - } -} - -void ThrownPotion::readAdditionalSaveData(CompoundTag *tag) -{ - Throwable::readAdditionalSaveData(tag); - - potionValue = tag->getInt(L"potionValue"); -} - -void ThrownPotion::addAdditonalSaveData(CompoundTag *tag) -{ - Throwable::addAdditonalSaveData(tag); - - tag->putInt(L"potionValue", potionValue); + tag->putInt(L"potionValue", potionValue); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/ThrownPotion.h b/Minecraft.World/Entities/Mobs/ThrownPotion.h index 412d12a1b..71789c811 100644 --- a/Minecraft.World/Entities/Mobs/ThrownPotion.h +++ b/Minecraft.World/Entities/Mobs/ThrownPotion.h @@ -4,40 +4,39 @@ class HitResult; -class ThrownPotion : public Throwable -{ +class ThrownPotion : public Throwable { public: - eINSTANCEOF GetType() { return eTYPE_THROWNPOTION; } - static Entity *create(Level *level) { return new ThrownPotion(level); } + eINSTANCEOF GetType() { return eTYPE_THROWNPOTION; } + static Entity* create(Level* level) { return new ThrownPotion(level); } public: - static const double SPLASH_RANGE; + static const double SPLASH_RANGE; private: - static const double SPLASH_RANGE_SQ; + static const double SPLASH_RANGE_SQ; - int potionValue; + int potionValue; - void _init(); + void _init(); public: - ThrownPotion(Level *level); - ThrownPotion(Level *level, std::shared_ptr mob, int potionValue); - ThrownPotion(Level *level, double x, double y, double z, int potionValue); + ThrownPotion(Level* level); + ThrownPotion(Level* level, std::shared_ptr mob, int potionValue); + ThrownPotion(Level* level, double x, double y, double z, int potionValue); protected: - virtual float getGravity(); - virtual float getThrowPower(); - virtual float getThrowUpAngleOffset(); + virtual float getGravity(); + virtual float getThrowPower(); + virtual float getThrowUpAngleOffset(); public: - void setPotionValue(int potionValue); - int getPotionValue(); + void setPotionValue(int potionValue); + int getPotionValue(); protected: - virtual void onHit(HitResult *res); + virtual void onHit(HitResult* res); public: - void readAdditionalSaveData(CompoundTag *tag); - void addAdditonalSaveData(CompoundTag *tag); + void readAdditionalSaveData(CompoundTag* tag); + void addAdditonalSaveData(CompoundTag* tag); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Villager.cpp b/Minecraft.World/Entities/Mobs/Villager.cpp index a1f6e090c..5a3cb4a9c 100644 --- a/Minecraft.World/Entities/Mobs/Villager.cpp +++ b/Minecraft.World/Entities/Mobs/Villager.cpp @@ -17,768 +17,748 @@ #include "Villager.h" #include -std::unordered_map > Villager::MIN_MAX_VALUES; -std::unordered_map > Villager::MIN_MAX_PRICES; +std::unordered_map > Villager::MIN_MAX_VALUES; +std::unordered_map > Villager::MIN_MAX_PRICES; -void Villager::_init(int profession) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +void Villager::_init(int profession) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - setProfession(profession); - setSize(.6f, 1.8f); + setProfession(profession); + setSize(.6f, 1.8f); - runSpeed = 0.5f; + runSpeed = 0.5f; - villageUpdateInterval = 0; - inLove = false; - chasing = false; - village = std::weak_ptr(); + villageUpdateInterval = 0; + inLove = false; + chasing = false; + village = std::weak_ptr(); - tradingPlayer = std::weak_ptr(); - offers = NULL; - updateMerchantTimer = 0; - addRecipeOnUpdate = false; - riches = 0; + tradingPlayer = std::weak_ptr(); + offers = NULL; + updateMerchantTimer = 0; + addRecipeOnUpdate = false; + riches = 0; lastPlayerTradeName = L""; rewardPlayersOnFirstVillage = false; - baseRecipeChanceMod = 0.0f; + baseRecipeChanceMod = 0.0f; - getNavigation()->setCanOpenDoors(true); - getNavigation()->setAvoidWater(true); + getNavigation()->setCanOpenDoors(true); + getNavigation()->setAvoidWater(true); - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new AvoidPlayerGoal(this, typeid(Zombie), 8, 0.3f, 0.35f)); - goalSelector.addGoal(1, new TradeWithPlayerGoal(this)); - goalSelector.addGoal(1, new LookAtTradingPlayerGoal(this)); - goalSelector.addGoal(2, new MoveIndoorsGoal(this)); - goalSelector.addGoal(3, new RestrictOpenDoorGoal(this)); - goalSelector.addGoal(4, new OpenDoorGoal(this, true)); - goalSelector.addGoal(5, new MoveTowardsRestrictionGoal(this, 0.3f)); - goalSelector.addGoal(6, new MakeLoveGoal(this)); - goalSelector.addGoal(7, new TakeFlowerGoal(this)); - goalSelector.addGoal(8, new PlayGoal(this, 0.32f)); - goalSelector.addGoal(9, new InteractGoal(this, typeid(Player), 3, 1.f)); - goalSelector.addGoal(9, new InteractGoal(this, typeid(Villager), 5, 0.02f)); - goalSelector.addGoal(9, new RandomStrollGoal(this, 0.3f)); - goalSelector.addGoal(10, new LookAtPlayerGoal(this, typeid(Mob), 8)); + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal( + 1, new AvoidPlayerGoal(this, typeid(Zombie), 8, 0.3f, 0.35f)); + goalSelector.addGoal(1, new TradeWithPlayerGoal(this)); + goalSelector.addGoal(1, new LookAtTradingPlayerGoal(this)); + goalSelector.addGoal(2, new MoveIndoorsGoal(this)); + goalSelector.addGoal(3, new RestrictOpenDoorGoal(this)); + goalSelector.addGoal(4, new OpenDoorGoal(this, true)); + goalSelector.addGoal(5, new MoveTowardsRestrictionGoal(this, 0.3f)); + goalSelector.addGoal(6, new MakeLoveGoal(this)); + goalSelector.addGoal(7, new TakeFlowerGoal(this)); + goalSelector.addGoal(8, new PlayGoal(this, 0.32f)); + goalSelector.addGoal(9, new InteractGoal(this, typeid(Player), 3, 1.f)); + goalSelector.addGoal(9, new InteractGoal(this, typeid(Villager), 5, 0.02f)); + goalSelector.addGoal(9, new RandomStrollGoal(this, 0.3f)); + goalSelector.addGoal(10, new LookAtPlayerGoal(this, typeid(Mob), 8)); } -Villager::Villager(Level *level) : AgableMob(level) -{ - _init(0); +Villager::Villager(Level* level) : AgableMob(level) { _init(0); } + +Villager::Villager(Level* level, int profession) : AgableMob(level) { + _init(profession); } -Villager::Villager(Level *level, int profession) : AgableMob(level) -{ - _init(profession); +Villager::~Villager() { delete offers; } + +bool Villager::useNewAi() { return true; } + +void Villager::serverAiMobStep() { + if (--villageUpdateInterval <= 0) { + level->villages->queryUpdateAround(Mth::floor(x), Mth::floor(y), + Mth::floor(z)); + villageUpdateInterval = 70 + random->nextInt(50); + + std::shared_ptr _village = level->villages->getClosestVillage( + Mth::floor(x), Mth::floor(y), Mth::floor(z), Villages::MaxDoorDist); + village = _village; + if (_village == NULL) + clearRestriction(); + else { + Pos* center = _village->getCenter(); + restrictTo(center->x, center->y, center->z, + (int)((float)_village->getRadius() * 0.6f)); + if (rewardPlayersOnFirstVillage) { + rewardPlayersOnFirstVillage = false; + _village->rewardAllPlayers(5); + } + } + } + + if (!isTrading() && updateMerchantTimer > 0) { + updateMerchantTimer--; + if (updateMerchantTimer <= 0) { + if (addRecipeOnUpdate) { + // improve max uses for all obsolete recipes + if (offers->size() > 0) { + // for (MerchantRecipe recipe : offers) + for (AUTO_VAR(it, offers->begin()); it != offers->end(); + ++it) { + MerchantRecipe* recipe = *it; + if (recipe->isDeprecated()) { + recipe->increaseMaxUses(random->nextInt(6) + + random->nextInt(6) + 2); + } + } + } + addOffers(1); + addRecipeOnUpdate = false; + + if (village.lock() != NULL && !lastPlayerTradeName.empty()) { + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::VILLAGER_HAPPY); + village.lock()->modifyStanding(lastPlayerTradeName, 1); + } + } + addEffect(new MobEffectInstance( + MobEffect::regeneration->id, + SharedConstants::TICKS_PER_SECOND * 10, 0)); + } + } + + AgableMob::serverAiMobStep(); } -Villager::~Villager() -{ - delete offers; +bool Villager::interact(std::shared_ptr player) { + // [EB]: Truly dislike this code but I don't see another easy way + std::shared_ptr item = player->inventory->getSelected(); + bool holdingSpawnEgg = item != NULL && item->id == Item::monsterPlacer_Id; + + if (!holdingSpawnEgg && isAlive() && !isTrading() && !isBaby()) { + if (!level->isClientSide) { + // note: stop() logic is controlled by trading ai goal + setTradingPlayer(player); + player->openTrading( + std::dynamic_pointer_cast(shared_from_this())); + } + return true; + } + return AgableMob::interact(player); } -bool Villager::useNewAi() -{ - return true; +void Villager::defineSynchedData() { + AgableMob::defineSynchedData(); + entityData->define(DATA_PROFESSION_ID, 0); } -void Villager::serverAiMobStep() -{ - if (--villageUpdateInterval <= 0) - { - level->villages->queryUpdateAround(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - villageUpdateInterval = 70 + random->nextInt(50); +int Villager::getMaxHealth() { return 20; } - std::shared_ptr _village = level->villages->getClosestVillage(Mth::floor(x), Mth::floor(y), Mth::floor(z), Villages::MaxDoorDist); - village = _village; - if (_village == NULL) clearRestriction(); - else - { - Pos *center = _village->getCenter(); - restrictTo(center->x, center->y, center->z, (int)((float)_village->getRadius() * 0.6f)); - if (rewardPlayersOnFirstVillage) - { - rewardPlayersOnFirstVillage = false; - _village->rewardAllPlayers(5); - } - } - } - - if (!isTrading() && updateMerchantTimer > 0) - { - updateMerchantTimer--; - if (updateMerchantTimer <= 0) - { - if (addRecipeOnUpdate) - { - // improve max uses for all obsolete recipes - if (offers->size() > 0) - { - //for (MerchantRecipe recipe : offers) - for(AUTO_VAR(it, offers->begin()); it != offers->end(); ++it) - { - MerchantRecipe *recipe = *it; - if (recipe->isDeprecated()) - { - recipe->increaseMaxUses(random->nextInt(6) + random->nextInt(6) + 2); - } - } - } - addOffers(1); - addRecipeOnUpdate = false; - - if (village.lock() != NULL && !lastPlayerTradeName.empty()) - { - level->broadcastEntityEvent(shared_from_this(), EntityEvent::VILLAGER_HAPPY); - village.lock()->modifyStanding(lastPlayerTradeName, 1); - } - } - addEffect(new MobEffectInstance(MobEffect::regeneration->id, SharedConstants::TICKS_PER_SECOND * 10, 0)); - } - } - - AgableMob::serverAiMobStep(); +void Villager::addAdditonalSaveData(CompoundTag* tag) { + AgableMob::addAdditonalSaveData(tag); + tag->putInt(L"Profession", getProfession()); + tag->putInt(L"Riches", riches); + if (offers != NULL) { + tag->putCompound(L"Offers", offers->createTag()); + } } -bool Villager::interact(std::shared_ptr player) -{ - // [EB]: Truly dislike this code but I don't see another easy way - std::shared_ptr item = player->inventory->getSelected(); - bool holdingSpawnEgg = item != NULL && item->id == Item::monsterPlacer_Id; - - if (!holdingSpawnEgg && isAlive() && !isTrading() && !isBaby()) - { - if (!level->isClientSide) - { - // note: stop() logic is controlled by trading ai goal - setTradingPlayer(player); - player->openTrading(std::dynamic_pointer_cast(shared_from_this())); - } - return true; - } - return AgableMob::interact(player); +void Villager::readAdditionalSaveData(CompoundTag* tag) { + AgableMob::readAdditionalSaveData(tag); + setProfession(tag->getInt(L"Profession")); + riches = tag->getInt(L"Riches"); + if (tag->contains(L"Offers")) { + CompoundTag* compound = tag->getCompound(L"Offers"); + delete offers; + offers = new MerchantRecipeList(compound); + } } -void Villager::defineSynchedData() -{ - AgableMob::defineSynchedData(); - entityData->define(DATA_PROFESSION_ID, 0); +int Villager::getTexture() { + // 4J Made switch + switch (getProfession()) { + case PROFESSION_FARMER: + return TN_MOB_VILLAGER_FARMER; // 4J was + // "/mob/villager/farmer.png"; + break; + case PROFESSION_LIBRARIAN: + return TN_MOB_VILLAGER_LIBRARIAN; // 4J was + // "/mob/villager/librarian.png"; + break; + case PROFESSION_PRIEST: + return TN_MOB_VILLAGER_PRIEST; // 4J was + // "/mob/villager/priest.png"; + break; + case PROFESSION_SMITH: + return TN_MOB_VILLAGER_SMITH; // 4J was "/mob/villager/smith.png"; + break; + case PROFESSION_BUTCHER: + return TN_MOB_VILLAGER_BUTCHER; // 4J was + // "/mob/villager/butcher.png"; + break; + // default: + // return TN_MOB_VILLAGER_VILLAGER; // 4J was + //"/mob/villager/villager.png"; break; + } + + return AgableMob::getTexture(); } -int Villager::getMaxHealth() -{ - return 20; +bool Villager::removeWhenFarAway() { return false; } + +int Villager::getAmbientSound() { + if (isTrading()) { + return eSoundType_MOB_VILLAGER_HAGGLE; + } + return eSoundType_MOB_VILLAGER_IDLE; } -void Villager::addAdditonalSaveData(CompoundTag *tag) -{ - AgableMob::addAdditonalSaveData(tag); - tag->putInt(L"Profession", getProfession()); - tag->putInt(L"Riches", riches); - if (offers != NULL) - { - tag->putCompound(L"Offers", offers->createTag()); - } +int Villager::getHurtSound() { return eSoundType_MOB_VILLAGER_HIT; } + +int Villager::getDeathSound() { return eSoundType_MOB_VILLAGER_DEATH; } + +void Villager::setProfession(int profession) { + entityData->set(DATA_PROFESSION_ID, profession); } -void Villager::readAdditionalSaveData(CompoundTag *tag) -{ - AgableMob::readAdditionalSaveData(tag); - setProfession(tag->getInt(L"Profession")); - riches = tag->getInt(L"Riches"); - if (tag->contains(L"Offers")) - { - CompoundTag *compound = tag->getCompound(L"Offers"); - delete offers; - offers = new MerchantRecipeList(compound); - } +int Villager::getProfession() { + return entityData->getInteger(DATA_PROFESSION_ID); } -int Villager::getTexture() -{ - // 4J Made switch - switch(getProfession()) - { - case PROFESSION_FARMER: - return TN_MOB_VILLAGER_FARMER; // 4J was "/mob/villager/farmer.png"; - break; - case PROFESSION_LIBRARIAN: - return TN_MOB_VILLAGER_LIBRARIAN; // 4J was "/mob/villager/librarian.png"; - break; - case PROFESSION_PRIEST: - return TN_MOB_VILLAGER_PRIEST; // 4J was "/mob/villager/priest.png"; - break; - case PROFESSION_SMITH: - return TN_MOB_VILLAGER_SMITH; // 4J was "/mob/villager/smith.png"; - break; - case PROFESSION_BUTCHER: - return TN_MOB_VILLAGER_BUTCHER; // 4J was "/mob/villager/butcher.png"; - break; - //default: - // return TN_MOB_VILLAGER_VILLAGER; // 4J was "/mob/villager/villager.png"; - // break; - } +bool Villager::isInLove() { return inLove; } - return AgableMob::getTexture(); +void Villager::setInLove(bool inLove) { this->inLove = inLove; } + +void Villager::setChasing(bool chasing) { this->chasing = chasing; } + +bool Villager::isChasing() { return chasing; } + +void Villager::setLastHurtByMob(std::shared_ptr mob) { + AgableMob::setLastHurtByMob(mob); + std::shared_ptr _village = village.lock(); + if (_village != NULL && mob != NULL) { + _village->addAggressor(mob); + + std::shared_ptr player = std::dynamic_pointer_cast(mob); + if (player) { + int amount = -1; + if (isBaby()) { + amount = -3; + } + _village->modifyStanding(player->getName(), amount); + if (isAlive()) { + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::VILLAGER_ANGRY); + } + } + } } -bool Villager::removeWhenFarAway() -{ - return false; +void Villager::die(DamageSource* source) { + std::shared_ptr _village = village.lock(); + if (_village != NULL) { + std::shared_ptr sourceEntity = source->getEntity(); + if (sourceEntity != NULL) { + if ((sourceEntity->GetType() & eTYPE_PLAYER) == eTYPE_PLAYER) { + std::shared_ptr player = + std::dynamic_pointer_cast(sourceEntity); + _village->modifyStanding(player->getName(), -2); + } else if ((sourceEntity->GetType() & eTYPE_ENEMY) == eTYPE_ENEMY) { + _village->resetNoBreedTimer(); + } + } else if (sourceEntity == NULL) { + // if the villager was killed by the world (such as lava or + // falling), blame the nearest player by not reproducing for a while + std::shared_ptr nearestPlayer = + level->getNearestPlayer(shared_from_this(), 16.0f); + if (nearestPlayer != NULL) { + _village->resetNoBreedTimer(); + } + } + } + + AgableMob::die(source); } -int Villager::getAmbientSound() -{ - if(isTrading()) - { - return eSoundType_MOB_VILLAGER_HAGGLE; - } - return eSoundType_MOB_VILLAGER_IDLE; +void Villager::setTradingPlayer(std::shared_ptr player) { + tradingPlayer = std::weak_ptr(player); } -int Villager::getHurtSound() -{ - return eSoundType_MOB_VILLAGER_HIT; +std::shared_ptr Villager::getTradingPlayer() { + return tradingPlayer.lock(); } -int Villager::getDeathSound() -{ - return eSoundType_MOB_VILLAGER_DEATH; +bool Villager::isTrading() { return tradingPlayer.lock() != NULL; } + +void Villager::notifyTrade(MerchantRecipe* activeRecipe) { + activeRecipe->increaseUses(); + ambientSoundTime = -getAmbientSoundInterval(); + playSound(eSoundType_MOB_VILLAGER_YES, getSoundVolume(), getVoicePitch()); + + // when the player buys the latest item, we improve the merchant a little + // while later + if (activeRecipe->isSame(offers->at(offers->size() - 1))) { + updateMerchantTimer = SharedConstants::TICKS_PER_SECOND * 2; + addRecipeOnUpdate = true; + if (tradingPlayer.lock() != NULL) { + lastPlayerTradeName = tradingPlayer.lock()->getName(); + } else { + lastPlayerTradeName = L""; + } + } + + if (activeRecipe->getBuyAItem()->id == Item::emerald_Id) { + riches += activeRecipe->getBuyAItem()->count; + } } -void Villager::setProfession(int profession) -{ - entityData->set(DATA_PROFESSION_ID, profession); +void Villager::notifyTradeUpdated(std::shared_ptr item) { + if (!level->isClientSide && + (ambientSoundTime > + (-getAmbientSoundInterval() + SharedConstants::TICKS_PER_SECOND))) { + ambientSoundTime = -getAmbientSoundInterval(); + if (item != NULL) { + playSound(eSoundType_MOB_VILLAGER_YES, getSoundVolume(), + getVoicePitch()); + } else { + playSound(eSoundType_MOB_VILLAGER_NO, getSoundVolume(), + getVoicePitch()); + } + } } -int Villager::getProfession() -{ - return entityData->getInteger(DATA_PROFESSION_ID); +MerchantRecipeList* Villager::getOffers(std::shared_ptr forPlayer) { + if (offers == NULL) { + addOffers(1); + } + return offers; } -bool Villager::isInLove() -{ - return inLove; +float Villager::getRecipeChance(float baseChance) { + float newChance = baseChance + baseRecipeChanceMod; + if (newChance > .9f) { + return .9f - (newChance - .9f); + } + return newChance; } -void Villager::setInLove(bool inLove) -{ - this->inLove = inLove; +void Villager::addOffers(int addCount) { + MerchantRecipeList* newOffers = new MerchantRecipeList(); + switch (getProfession()) { + case PROFESSION_FARMER: + addItemForTradeIn(newOffers, Item::wheat_Id, random, + getRecipeChance(.9f)); + addItemForTradeIn(newOffers, Tile::cloth_Id, random, + getRecipeChance(.5f)); + addItemForTradeIn(newOffers, Item::chicken_raw_Id, random, + getRecipeChance(.5f)); + addItemForTradeIn(newOffers, Item::fish_cooked_Id, random, + getRecipeChance(.4f)); + addItemForPurchase(newOffers, Item::bread_Id, random, + getRecipeChance(.9f)); + addItemForPurchase(newOffers, Item::melon_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::apple_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::cookie_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::shears_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::flintAndSteel_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::chicken_cooked_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::arrow_Id, random, + getRecipeChance(.5f)); + if (random->nextFloat() < .5f) { + newOffers->push_back(new MerchantRecipe( + std::shared_ptr( + new ItemInstance(Tile::gravel, 10)), + std::shared_ptr( + new ItemInstance(Item::emerald)), + std::shared_ptr(new ItemInstance( + Item::flint_Id, 2 + random->nextInt(2), 0)))); + } + break; + case PROFESSION_BUTCHER: + addItemForTradeIn(newOffers, Item::coal_Id, random, + getRecipeChance(.7f)); + addItemForTradeIn(newOffers, Item::porkChop_raw_Id, random, + getRecipeChance(.5f)); + addItemForTradeIn(newOffers, Item::beef_raw_Id, random, + getRecipeChance(.5f)); + addItemForPurchase(newOffers, Item::saddle_Id, random, + getRecipeChance(.1f)); + addItemForPurchase(newOffers, Item::chestplate_cloth_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::boots_cloth_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::helmet_cloth_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::leggings_cloth_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::porkChop_cooked_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::beef_cooked_Id, random, + getRecipeChance(.3f)); + break; + case PROFESSION_SMITH: + addItemForTradeIn(newOffers, Item::coal_Id, random, + getRecipeChance(.7f)); + addItemForTradeIn(newOffers, Item::ironIngot_Id, random, + getRecipeChance(.5f)); + addItemForTradeIn(newOffers, Item::goldIngot_Id, random, + getRecipeChance(.5f)); + addItemForTradeIn(newOffers, Item::diamond_Id, random, + getRecipeChance(.5f)); + + addItemForPurchase(newOffers, Item::sword_iron_Id, random, + getRecipeChance(.5f)); + addItemForPurchase(newOffers, Item::sword_diamond_Id, random, + getRecipeChance(.5f)); + addItemForPurchase(newOffers, Item::hatchet_iron_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::hatchet_diamond_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::pickAxe_iron_Id, random, + getRecipeChance(.5f)); + addItemForPurchase(newOffers, Item::pickAxe_diamond_Id, random, + getRecipeChance(.5f)); + addItemForPurchase(newOffers, Item::shovel_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::shovel_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::hoe_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::hoe_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::boots_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::boots_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::helmet_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::helmet_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::chestplate_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::chestplate_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::leggings_iron_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::leggings_diamond_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::boots_chain_Id, random, + getRecipeChance(.1f)); + addItemForPurchase(newOffers, Item::helmet_chain_Id, random, + getRecipeChance(.1f)); + addItemForPurchase(newOffers, Item::chestplate_chain_Id, random, + getRecipeChance(.1f)); + addItemForPurchase(newOffers, Item::leggings_chain_Id, random, + getRecipeChance(.1f)); + break; + case PROFESSION_LIBRARIAN: + addItemForTradeIn(newOffers, Item::paper_Id, random, + getRecipeChance(.8f)); + addItemForTradeIn(newOffers, Item::book_Id, random, + getRecipeChance(.8f)); + // addItemForTradeIn(newOffers, Item::writtenBook_Id, random, + // getRecipeChance(0.3f)); + addItemForPurchase(newOffers, Tile::bookshelf_Id, random, + getRecipeChance(.8f)); + addItemForPurchase(newOffers, Tile::glass_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::compass_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::clock_Id, random, + getRecipeChance(.2f)); + + if (random->nextFloat() < getRecipeChance(0.07f)) { + Enchantment* enchantment = + Enchantment::validEnchantments[random->nextInt( + Enchantment::validEnchantments.size())]; + int level = Mth::nextInt(random, enchantment->getMinLevel(), + enchantment->getMaxLevel()); + std::shared_ptr book = + Item::enchantedBook->createForEnchantment( + new EnchantmentInstance(enchantment, level)); + int cost = 2 + random->nextInt(5 + (level * 10)) + 3 * level; + + newOffers->push_back(new MerchantRecipe( + std::shared_ptr(new ItemInstance(Item::book)), + std::shared_ptr( + new ItemInstance(Item::emerald, cost)), + book)); + } + break; + case PROFESSION_PRIEST: + addItemForPurchase(newOffers, Item::eyeOfEnder_Id, random, + getRecipeChance(.3f)); + addItemForPurchase(newOffers, Item::expBottle_Id, random, + getRecipeChance(.2f)); + addItemForPurchase(newOffers, Item::redStone_Id, random, + getRecipeChance(.4f)); + addItemForPurchase(newOffers, Tile::lightGem_Id, random, + getRecipeChance(.3f)); + { + int enchantItems[] = { + Item::sword_iron_Id, Item::sword_diamond_Id, + Item::chestplate_iron_Id, Item::chestplate_diamond_Id, + Item::hatchet_iron_Id, Item::hatchet_diamond_Id, + Item::pickAxe_iron_Id, Item::pickAxe_diamond_Id}; + for (unsigned int i = 0; i < 8; ++i) { + int id = enchantItems[i]; + if (random->nextFloat() < getRecipeChance(.05f)) { + newOffers->push_back(new MerchantRecipe( + std::shared_ptr( + new ItemInstance(id, 1, 0)), + std::shared_ptr(new ItemInstance( + Item::emerald, 2 + random->nextInt(3), 0)), + EnchantmentHelper::enchantItem( + random, + std::shared_ptr( + new ItemInstance(id, 1, 0)), + 5 + random->nextInt(15)))); + } + } + } + break; + } + + if (newOffers->empty()) { + addItemForTradeIn(newOffers, Item::goldIngot_Id, random, 1.0f); + } + + // shuffle the list to make it more interesting + static thread_local std::mt19937 g(std::random_device{}()); + std::shuffle(newOffers->begin(), newOffers->end(), g); + + if (offers == NULL) { + offers = new MerchantRecipeList(); + } + for (int i = 0; i < addCount && i < newOffers->size(); i++) { + if (offers->addIfNewOrBetter(newOffers->at(i))) { + // 4J Added so we can delete newOffers + newOffers->erase(newOffers->begin() + i); + } + } + delete newOffers; } -void Villager::setChasing(bool chasing) -{ - this->chasing = chasing; -} +void Villager::overrideOffers(MerchantRecipeList* recipeList) {} -bool Villager::isChasing() -{ - return chasing; -} +void Villager::staticCtor() { + MIN_MAX_VALUES[Item::coal_Id] = std::pair(16, 24); + MIN_MAX_VALUES[Item::ironIngot_Id] = std::pair(8, 10); + MIN_MAX_VALUES[Item::goldIngot_Id] = std::pair(8, 10); + MIN_MAX_VALUES[Item::diamond_Id] = std::pair(4, 6); + MIN_MAX_VALUES[Item::paper_Id] = std::pair(24, 36); + MIN_MAX_VALUES[Item::book_Id] = std::pair(11, 13); + // MIN_MAX_VALUES.insert(Item::writtenBook_Id, std::pair(1, 1)); + MIN_MAX_VALUES[Item::enderPearl_Id] = std::pair(3, 4); + MIN_MAX_VALUES[Item::eyeOfEnder_Id] = std::pair(2, 3); + MIN_MAX_VALUES[Item::porkChop_raw_Id] = std::pair(14, 18); + MIN_MAX_VALUES[Item::beef_raw_Id] = std::pair(14, 18); + MIN_MAX_VALUES[Item::chicken_raw_Id] = std::pair(14, 18); + MIN_MAX_VALUES[Item::fish_cooked_Id] = std::pair(9, 13); + MIN_MAX_VALUES[Item::seeds_wheat_Id] = std::pair(34, 48); + MIN_MAX_VALUES[Item::seeds_melon_Id] = std::pair(30, 38); + MIN_MAX_VALUES[Item::seeds_pumpkin_Id] = std::pair(30, 38); + MIN_MAX_VALUES[Item::wheat_Id] = std::pair(18, 22); + MIN_MAX_VALUES[Tile::cloth_Id] = std::pair(14, 22); + MIN_MAX_VALUES[Item::rotten_flesh_Id] = std::pair(36, 64); -void Villager::setLastHurtByMob(std::shared_ptr mob) -{ - AgableMob::setLastHurtByMob(mob); - std::shared_ptr _village = village.lock(); - if (_village != NULL && mob != NULL) - { - _village->addAggressor(mob); - - std::shared_ptr player = std::dynamic_pointer_cast(mob); - if (player) - { - int amount = -1; - if (isBaby()) - { - amount = -3; - } - _village->modifyStanding(player->getName(), amount); - if (isAlive()) - { - level->broadcastEntityEvent(shared_from_this(), EntityEvent::VILLAGER_ANGRY); - } - } - } -} - -void Villager::die(DamageSource *source) -{ - std::shared_ptr _village = village.lock(); - if (_village != NULL) - { - std::shared_ptr sourceEntity = source->getEntity(); - if (sourceEntity != NULL) - { - if ((sourceEntity->GetType() & eTYPE_PLAYER) == eTYPE_PLAYER) - { - std::shared_ptr player = std::dynamic_pointer_cast(sourceEntity); - _village->modifyStanding(player->getName(), -2); - } - else if ((sourceEntity->GetType() & eTYPE_ENEMY) == eTYPE_ENEMY) - { - _village->resetNoBreedTimer(); - } - } - else if (sourceEntity == NULL) - { - // if the villager was killed by the world (such as lava or falling), blame - // the nearest player by not reproducing for a while - std::shared_ptr nearestPlayer = level->getNearestPlayer(shared_from_this(), 16.0f); - if (nearestPlayer != NULL) - { - _village->resetNoBreedTimer(); - } - } - } - - AgableMob::die(source); -} - -void Villager::setTradingPlayer(std::shared_ptr player) -{ - tradingPlayer = std::weak_ptr(player); -} - -std::shared_ptr Villager::getTradingPlayer() -{ - return tradingPlayer.lock(); -} - -bool Villager::isTrading() -{ - return tradingPlayer.lock() != NULL; -} - -void Villager::notifyTrade(MerchantRecipe *activeRecipe) -{ - activeRecipe->increaseUses(); - ambientSoundTime = -getAmbientSoundInterval(); - playSound(eSoundType_MOB_VILLAGER_YES, getSoundVolume(), getVoicePitch()); - - // when the player buys the latest item, we improve the merchant a little while later - if (activeRecipe->isSame(offers->at(offers->size() - 1))) - { - updateMerchantTimer = SharedConstants::TICKS_PER_SECOND * 2; - addRecipeOnUpdate = true; - if (tradingPlayer.lock() != NULL) - { - lastPlayerTradeName = tradingPlayer.lock()->getName(); - } - else - { - lastPlayerTradeName = L""; - } - } - - if (activeRecipe->getBuyAItem()->id == Item::emerald_Id) - { - riches += activeRecipe->getBuyAItem()->count; - } -} - -void Villager::notifyTradeUpdated(std::shared_ptr item) -{ - if (!level->isClientSide && (ambientSoundTime > (-getAmbientSoundInterval() + SharedConstants::TICKS_PER_SECOND))) - { - ambientSoundTime = -getAmbientSoundInterval(); - if (item != NULL) - { - playSound(eSoundType_MOB_VILLAGER_YES, getSoundVolume(), getVoicePitch()); - } - else - { - playSound(eSoundType_MOB_VILLAGER_NO, getSoundVolume(), getVoicePitch()); - } - } -} - -MerchantRecipeList *Villager::getOffers(std::shared_ptr forPlayer) -{ - if (offers == NULL) - { - addOffers(1); - } - return offers; -} - -float Villager::getRecipeChance(float baseChance) -{ - float newChance = baseChance + baseRecipeChanceMod; - if (newChance > .9f) - { - return .9f - (newChance - .9f); - } - return newChance; -} - -void Villager::addOffers(int addCount) -{ - MerchantRecipeList *newOffers = new MerchantRecipeList(); - switch (getProfession()) - { - case PROFESSION_FARMER: - addItemForTradeIn(newOffers, Item::wheat_Id, random, getRecipeChance(.9f)); - addItemForTradeIn(newOffers, Tile::cloth_Id, random, getRecipeChance(.5f)); - addItemForTradeIn(newOffers, Item::chicken_raw_Id, random, getRecipeChance(.5f)); - addItemForTradeIn(newOffers, Item::fish_cooked_Id, random, getRecipeChance(.4f)); - addItemForPurchase(newOffers, Item::bread_Id, random, getRecipeChance(.9f)); - addItemForPurchase(newOffers, Item::melon_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::apple_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::cookie_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::shears_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::flintAndSteel_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::chicken_cooked_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::arrow_Id, random, getRecipeChance(.5f)); - if (random->nextFloat() < .5f) - { - newOffers->push_back(new MerchantRecipe(std::shared_ptr( new ItemInstance(Tile::gravel, 10) ), std::shared_ptr( new ItemInstance(Item::emerald) ), std::shared_ptr( new ItemInstance(Item::flint_Id, 2 + random->nextInt(2), 0)))); - } - break; - case PROFESSION_BUTCHER: - addItemForTradeIn(newOffers, Item::coal_Id, random, getRecipeChance(.7f)); - addItemForTradeIn(newOffers, Item::porkChop_raw_Id, random, getRecipeChance(.5f)); - addItemForTradeIn(newOffers, Item::beef_raw_Id, random, getRecipeChance(.5f)); - addItemForPurchase(newOffers, Item::saddle_Id, random, getRecipeChance(.1f)); - addItemForPurchase(newOffers, Item::chestplate_cloth_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::boots_cloth_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::helmet_cloth_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::leggings_cloth_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::porkChop_cooked_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::beef_cooked_Id, random, getRecipeChance(.3f)); - break; - case PROFESSION_SMITH: - addItemForTradeIn(newOffers, Item::coal_Id, random, getRecipeChance(.7f)); - addItemForTradeIn(newOffers, Item::ironIngot_Id, random, getRecipeChance(.5f)); - addItemForTradeIn(newOffers, Item::goldIngot_Id, random, getRecipeChance(.5f)); - addItemForTradeIn(newOffers, Item::diamond_Id, random, getRecipeChance(.5f)); - - addItemForPurchase(newOffers, Item::sword_iron_Id, random, getRecipeChance(.5f)); - addItemForPurchase(newOffers, Item::sword_diamond_Id, random, getRecipeChance(.5f)); - addItemForPurchase(newOffers, Item::hatchet_iron_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::hatchet_diamond_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::pickAxe_iron_Id, random, getRecipeChance(.5f)); - addItemForPurchase(newOffers, Item::pickAxe_diamond_Id, random, getRecipeChance(.5f)); - addItemForPurchase(newOffers, Item::shovel_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::shovel_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::hoe_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::hoe_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::boots_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::boots_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::helmet_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::helmet_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::chestplate_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::chestplate_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::leggings_iron_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::leggings_diamond_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::boots_chain_Id, random, getRecipeChance(.1f)); - addItemForPurchase(newOffers, Item::helmet_chain_Id, random, getRecipeChance(.1f)); - addItemForPurchase(newOffers, Item::chestplate_chain_Id, random, getRecipeChance(.1f)); - addItemForPurchase(newOffers, Item::leggings_chain_Id, random, getRecipeChance(.1f)); - break; - case PROFESSION_LIBRARIAN: - addItemForTradeIn(newOffers, Item::paper_Id, random, getRecipeChance(.8f)); - addItemForTradeIn(newOffers, Item::book_Id, random, getRecipeChance(.8f)); - //addItemForTradeIn(newOffers, Item::writtenBook_Id, random, getRecipeChance(0.3f)); - addItemForPurchase(newOffers, Tile::bookshelf_Id, random, getRecipeChance(.8f)); - addItemForPurchase(newOffers, Tile::glass_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::compass_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::clock_Id, random, getRecipeChance(.2f)); - - if (random->nextFloat() < getRecipeChance(0.07f)) - { - Enchantment *enchantment = Enchantment::validEnchantments[random->nextInt(Enchantment::validEnchantments.size())]; - int level = Mth::nextInt(random, enchantment->getMinLevel(), enchantment->getMaxLevel()); - std::shared_ptr book = Item::enchantedBook->createForEnchantment(new EnchantmentInstance(enchantment, level)); - int cost = 2 + random->nextInt(5 + (level * 10)) + 3 * level; - - newOffers->push_back(new MerchantRecipe(std::shared_ptr(new ItemInstance(Item::book)), std::shared_ptr(new ItemInstance(Item::emerald, cost)), book)); - } - break; - case PROFESSION_PRIEST: - addItemForPurchase(newOffers, Item::eyeOfEnder_Id, random, getRecipeChance(.3f)); - addItemForPurchase(newOffers, Item::expBottle_Id, random, getRecipeChance(.2f)); - addItemForPurchase(newOffers, Item::redStone_Id, random, getRecipeChance(.4f)); - addItemForPurchase(newOffers, Tile::lightGem_Id, random, getRecipeChance(.3f)); - { - int enchantItems[] = { - Item::sword_iron_Id, Item::sword_diamond_Id, Item::chestplate_iron_Id, Item::chestplate_diamond_Id, Item::hatchet_iron_Id, Item::hatchet_diamond_Id, Item::pickAxe_iron_Id, - Item::pickAxe_diamond_Id - }; - for (unsigned int i = 0; i < 8; ++i) - { - int id = enchantItems[i]; - if (random->nextFloat() < getRecipeChance(.05f)) - { - newOffers->push_back(new MerchantRecipe(std::shared_ptr(new ItemInstance(id, 1, 0)), - std::shared_ptr(new ItemInstance(Item::emerald, 2 + random->nextInt(3), 0)), - EnchantmentHelper::enchantItem(random, std::shared_ptr(new ItemInstance(id, 1, 0)), 5 + random->nextInt(15)))); - } - } - } - break; - } - - if (newOffers->empty()) - { - addItemForTradeIn(newOffers, Item::goldIngot_Id, random, 1.0f); - } - - // shuffle the list to make it more interesting - static thread_local std::mt19937 g(std::random_device{}()); - std::shuffle(newOffers->begin(), newOffers->end(), g); - - if (offers == NULL) - { - offers = new MerchantRecipeList(); - } - for (int i = 0; i < addCount && i < newOffers->size(); i++) - { - if( offers->addIfNewOrBetter(newOffers->at(i))) - { - // 4J Added so we can delete newOffers - newOffers->erase(newOffers->begin() + i); - } - } - delete newOffers; -} - -void Villager::overrideOffers(MerchantRecipeList *recipeList) -{ -} - - -void Villager::staticCtor() -{ - MIN_MAX_VALUES[Item::coal_Id] = std::pair(16, 24); - MIN_MAX_VALUES[Item::ironIngot_Id] = std::pair(8, 10); - MIN_MAX_VALUES[Item::goldIngot_Id] = std::pair(8, 10); - MIN_MAX_VALUES[Item::diamond_Id] = std::pair(4, 6); - MIN_MAX_VALUES[Item::paper_Id] = std::pair(24, 36); - MIN_MAX_VALUES[Item::book_Id] = std::pair(11, 13); - //MIN_MAX_VALUES.insert(Item::writtenBook_Id, std::pair(1, 1)); - MIN_MAX_VALUES[Item::enderPearl_Id] = std::pair(3, 4); - MIN_MAX_VALUES[Item::eyeOfEnder_Id] = std::pair(2, 3); - MIN_MAX_VALUES[Item::porkChop_raw_Id] = std::pair(14, 18); - MIN_MAX_VALUES[Item::beef_raw_Id] = std::pair(14, 18); - MIN_MAX_VALUES[Item::chicken_raw_Id] = std::pair(14, 18); - MIN_MAX_VALUES[Item::fish_cooked_Id] = std::pair(9, 13); - MIN_MAX_VALUES[Item::seeds_wheat_Id] = std::pair(34, 48); - MIN_MAX_VALUES[Item::seeds_melon_Id] = std::pair(30, 38); - MIN_MAX_VALUES[Item::seeds_pumpkin_Id] = std::pair(30, 38); - MIN_MAX_VALUES[Item::wheat_Id] = std::pair(18, 22); - MIN_MAX_VALUES[Tile::cloth_Id] = std::pair(14, 22); - MIN_MAX_VALUES[Item::rotten_flesh_Id] = std::pair(36, 64); - - MIN_MAX_PRICES[Item::flintAndSteel_Id] = std::pair(3, 4); - MIN_MAX_PRICES[Item::shears_Id] = std::pair(3, 4); - MIN_MAX_PRICES[Item::sword_iron_Id] = std::pair(7, 11); - MIN_MAX_PRICES[Item::sword_diamond_Id] = std::pair(12, 14); - MIN_MAX_PRICES[Item::hatchet_iron_Id] = std::pair(6, 8); - MIN_MAX_PRICES[Item::hatchet_diamond_Id] = std::pair(9, 12); - MIN_MAX_PRICES[Item::pickAxe_iron_Id] = std::pair(7, 9); - MIN_MAX_PRICES[Item::pickAxe_diamond_Id] = std::pair(10, 12); - MIN_MAX_PRICES[Item::shovel_iron_Id] = std::pair(4, 6); - MIN_MAX_PRICES[Item::shovel_diamond_Id] = std::pair(7, 8); - MIN_MAX_PRICES[Item::hoe_iron_Id] = std::pair(4, 6); - MIN_MAX_PRICES[Item::hoe_diamond_Id] = std::pair(7, 8); - MIN_MAX_PRICES[Item::boots_iron_Id] = std::pair(4, 6); - MIN_MAX_PRICES[Item::boots_diamond_Id] = std::pair(7, 8); - MIN_MAX_PRICES[Item::helmet_iron_Id] = std::pair(4, 6); - MIN_MAX_PRICES[Item::helmet_diamond_Id] = std::pair(7, 8); - MIN_MAX_PRICES[Item::chestplate_iron_Id] = std::pair(10, 14); - MIN_MAX_PRICES[Item::chestplate_diamond_Id] = std::pair(16, 19); - MIN_MAX_PRICES[Item::leggings_iron_Id] = std::pair(8, 10); - MIN_MAX_PRICES[Item::leggings_diamond_Id] = std::pair(11, 14); - MIN_MAX_PRICES[Item::boots_chain_Id] = std::pair(5, 7); - MIN_MAX_PRICES[Item::helmet_chain_Id] = std::pair(5, 7); - MIN_MAX_PRICES[Item::chestplate_chain_Id] = std::pair(11, 15); - MIN_MAX_PRICES[Item::leggings_chain_Id] = std::pair(9, 11); - MIN_MAX_PRICES[Item::bread_Id] = std::pair(-4, -2); - MIN_MAX_PRICES[Item::melon_Id] = std::pair(-8, -4); - MIN_MAX_PRICES[Item::apple_Id] = std::pair(-8, -4); - MIN_MAX_PRICES[Item::cookie_Id] = std::pair(-10, -7); - MIN_MAX_PRICES[Tile::glass_Id] = std::pair(-5, -3); - MIN_MAX_PRICES[Tile::bookshelf_Id] = std::pair(3, 4); - MIN_MAX_PRICES[Item::chestplate_cloth_Id] = std::pair(4, 5); - MIN_MAX_PRICES[Item::boots_cloth_Id] = std::pair(2, 4); - MIN_MAX_PRICES[Item::helmet_cloth_Id] = std::pair(2, 4); - MIN_MAX_PRICES[Item::leggings_cloth_Id] = std::pair(2, 4); - MIN_MAX_PRICES[Item::saddle_Id] = std::pair(6, 8); - MIN_MAX_PRICES[Item::expBottle_Id] = std::pair(-4, -1); - MIN_MAX_PRICES[Item::redStone_Id] = std::pair(-4, -1); - MIN_MAX_PRICES[Item::compass_Id] = std::pair(10, 12); - MIN_MAX_PRICES[Item::clock_Id] = std::pair(10, 12); - MIN_MAX_PRICES[Tile::lightGem_Id] = std::pair(-3, -1); - MIN_MAX_PRICES[Item::porkChop_cooked_Id] = std::pair(-7, -5); - MIN_MAX_PRICES[Item::beef_cooked_Id] = std::pair(-7, -5); - MIN_MAX_PRICES[Item::chicken_cooked_Id] = std::pair(-8, -6); - MIN_MAX_PRICES[Item::eyeOfEnder_Id] = std::pair(7, 11); - MIN_MAX_PRICES[Item::arrow_Id] = std::pair(-12, -8); + MIN_MAX_PRICES[Item::flintAndSteel_Id] = std::pair(3, 4); + MIN_MAX_PRICES[Item::shears_Id] = std::pair(3, 4); + MIN_MAX_PRICES[Item::sword_iron_Id] = std::pair(7, 11); + MIN_MAX_PRICES[Item::sword_diamond_Id] = std::pair(12, 14); + MIN_MAX_PRICES[Item::hatchet_iron_Id] = std::pair(6, 8); + MIN_MAX_PRICES[Item::hatchet_diamond_Id] = std::pair(9, 12); + MIN_MAX_PRICES[Item::pickAxe_iron_Id] = std::pair(7, 9); + MIN_MAX_PRICES[Item::pickAxe_diamond_Id] = std::pair(10, 12); + MIN_MAX_PRICES[Item::shovel_iron_Id] = std::pair(4, 6); + MIN_MAX_PRICES[Item::shovel_diamond_Id] = std::pair(7, 8); + MIN_MAX_PRICES[Item::hoe_iron_Id] = std::pair(4, 6); + MIN_MAX_PRICES[Item::hoe_diamond_Id] = std::pair(7, 8); + MIN_MAX_PRICES[Item::boots_iron_Id] = std::pair(4, 6); + MIN_MAX_PRICES[Item::boots_diamond_Id] = std::pair(7, 8); + MIN_MAX_PRICES[Item::helmet_iron_Id] = std::pair(4, 6); + MIN_MAX_PRICES[Item::helmet_diamond_Id] = std::pair(7, 8); + MIN_MAX_PRICES[Item::chestplate_iron_Id] = std::pair(10, 14); + MIN_MAX_PRICES[Item::chestplate_diamond_Id] = std::pair(16, 19); + MIN_MAX_PRICES[Item::leggings_iron_Id] = std::pair(8, 10); + MIN_MAX_PRICES[Item::leggings_diamond_Id] = std::pair(11, 14); + MIN_MAX_PRICES[Item::boots_chain_Id] = std::pair(5, 7); + MIN_MAX_PRICES[Item::helmet_chain_Id] = std::pair(5, 7); + MIN_MAX_PRICES[Item::chestplate_chain_Id] = std::pair(11, 15); + MIN_MAX_PRICES[Item::leggings_chain_Id] = std::pair(9, 11); + MIN_MAX_PRICES[Item::bread_Id] = std::pair(-4, -2); + MIN_MAX_PRICES[Item::melon_Id] = std::pair(-8, -4); + MIN_MAX_PRICES[Item::apple_Id] = std::pair(-8, -4); + MIN_MAX_PRICES[Item::cookie_Id] = std::pair(-10, -7); + MIN_MAX_PRICES[Tile::glass_Id] = std::pair(-5, -3); + MIN_MAX_PRICES[Tile::bookshelf_Id] = std::pair(3, 4); + MIN_MAX_PRICES[Item::chestplate_cloth_Id] = std::pair(4, 5); + MIN_MAX_PRICES[Item::boots_cloth_Id] = std::pair(2, 4); + MIN_MAX_PRICES[Item::helmet_cloth_Id] = std::pair(2, 4); + MIN_MAX_PRICES[Item::leggings_cloth_Id] = std::pair(2, 4); + MIN_MAX_PRICES[Item::saddle_Id] = std::pair(6, 8); + MIN_MAX_PRICES[Item::expBottle_Id] = std::pair(-4, -1); + MIN_MAX_PRICES[Item::redStone_Id] = std::pair(-4, -1); + MIN_MAX_PRICES[Item::compass_Id] = std::pair(10, 12); + MIN_MAX_PRICES[Item::clock_Id] = std::pair(10, 12); + MIN_MAX_PRICES[Tile::lightGem_Id] = std::pair(-3, -1); + MIN_MAX_PRICES[Item::porkChop_cooked_Id] = std::pair(-7, -5); + MIN_MAX_PRICES[Item::beef_cooked_Id] = std::pair(-7, -5); + MIN_MAX_PRICES[Item::chicken_cooked_Id] = std::pair(-8, -6); + MIN_MAX_PRICES[Item::eyeOfEnder_Id] = std::pair(7, 11); + MIN_MAX_PRICES[Item::arrow_Id] = std::pair(-12, -8); } /** -* Adds a merchant recipe that trades items for a single ruby. -* -* @param list -* @param itemId -* @param random -* @param likelyHood -*/ -void Villager::addItemForTradeIn(MerchantRecipeList *list, int itemId, Random *random, float likelyHood) -{ - if (random->nextFloat() < likelyHood) - { - list->push_back(new MerchantRecipe(getItemTradeInValue(itemId, random), Item::emerald)); - } + * Adds a merchant recipe that trades items for a single ruby. + * + * @param list + * @param itemId + * @param random + * @param likelyHood + */ +void Villager::addItemForTradeIn(MerchantRecipeList* list, int itemId, + Random* random, float likelyHood) { + if (random->nextFloat() < likelyHood) { + list->push_back(new MerchantRecipe(getItemTradeInValue(itemId, random), + Item::emerald)); + } } -std::shared_ptr Villager::getItemTradeInValue(int itemId, Random *random) -{ - return std::shared_ptr(new ItemInstance(itemId, getTradeInValue(itemId, random), 0)); +std::shared_ptr Villager::getItemTradeInValue(int itemId, + Random* random) { + return std::shared_ptr( + new ItemInstance(itemId, getTradeInValue(itemId, random), 0)); } -int Villager::getTradeInValue(int itemId, Random *random) -{ - AUTO_VAR(it,MIN_MAX_VALUES.find(itemId)); - if (it == MIN_MAX_VALUES.end()) - { - return 1; - } - std::pair minMax = it->second; - if (minMax.first >= minMax.second) - { - return minMax.first; - } - return minMax.first + random->nextInt(minMax.second - minMax.first); +int Villager::getTradeInValue(int itemId, Random* random) { + AUTO_VAR(it, MIN_MAX_VALUES.find(itemId)); + if (it == MIN_MAX_VALUES.end()) { + return 1; + } + std::pair minMax = it->second; + if (minMax.first >= minMax.second) { + return minMax.first; + } + return minMax.first + random->nextInt(minMax.second - minMax.first); } /** -* Adds a merchant recipe that trades rubies for an item. If the cost is -* negative, one ruby will give several of that item. -* -* @param list -* @param itemId -* @param random -* @param likelyHood -*/ -void Villager::addItemForPurchase(MerchantRecipeList *list, int itemId, Random *random, float likelyHood) -{ - if (random->nextFloat() < likelyHood) - { - int purchaseCost = getPurchaseCost(itemId, random); - std::shared_ptr rubyItem; - std::shared_ptr resultItem; - if (purchaseCost < 0) - { - rubyItem = std::shared_ptr( new ItemInstance(Item::emerald_Id, 1, 0) ); - resultItem = std::shared_ptr( new ItemInstance(itemId, -purchaseCost, 0) ); - } - else - { - rubyItem = std::shared_ptr( new ItemInstance(Item::emerald_Id, purchaseCost, 0) ); - resultItem = std::shared_ptr( new ItemInstance(itemId, 1, 0) ); - } - list->push_back(new MerchantRecipe(rubyItem, resultItem)); - } + * Adds a merchant recipe that trades rubies for an item. If the cost is + * negative, one ruby will give several of that item. + * + * @param list + * @param itemId + * @param random + * @param likelyHood + */ +void Villager::addItemForPurchase(MerchantRecipeList* list, int itemId, + Random* random, float likelyHood) { + if (random->nextFloat() < likelyHood) { + int purchaseCost = getPurchaseCost(itemId, random); + std::shared_ptr rubyItem; + std::shared_ptr resultItem; + if (purchaseCost < 0) { + rubyItem = std::shared_ptr( + new ItemInstance(Item::emerald_Id, 1, 0)); + resultItem = std::shared_ptr( + new ItemInstance(itemId, -purchaseCost, 0)); + } else { + rubyItem = std::shared_ptr( + new ItemInstance(Item::emerald_Id, purchaseCost, 0)); + resultItem = + std::shared_ptr(new ItemInstance(itemId, 1, 0)); + } + list->push_back(new MerchantRecipe(rubyItem, resultItem)); + } } -int Villager::getPurchaseCost(int itemId, Random *random) -{ - AUTO_VAR(it,MIN_MAX_PRICES.find(itemId)); - if (it == MIN_MAX_PRICES.end()) - { - return 1; - } - std::pair minMax = it->second; - if (minMax.first >= minMax.second) - { - return minMax.first; - } - return minMax.first + random->nextInt(minMax.second - minMax.first); +int Villager::getPurchaseCost(int itemId, Random* random) { + AUTO_VAR(it, MIN_MAX_PRICES.find(itemId)); + if (it == MIN_MAX_PRICES.end()) { + return 1; + } + std::pair minMax = it->second; + if (minMax.first >= minMax.second) { + return minMax.first; + } + return minMax.first + random->nextInt(minMax.second - minMax.first); } -void Villager::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::LOVE_HEARTS) - { - addParticlesAroundSelf(eParticleType_heart); - } - else if (id == EntityEvent::VILLAGER_ANGRY) - { - addParticlesAroundSelf(eParticleType_angryVillager); - } - else if (id == EntityEvent::VILLAGER_HAPPY) - { - addParticlesAroundSelf(eParticleType_happyVillager); - } - else - { - AgableMob::handleEntityEvent(id); - } +void Villager::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::LOVE_HEARTS) { + addParticlesAroundSelf(eParticleType_heart); + } else if (id == EntityEvent::VILLAGER_ANGRY) { + addParticlesAroundSelf(eParticleType_angryVillager); + } else if (id == EntityEvent::VILLAGER_HAPPY) { + addParticlesAroundSelf(eParticleType_happyVillager); + } else { + AgableMob::handleEntityEvent(id); + } } -void Villager::addParticlesAroundSelf(ePARTICLE_TYPE particle) -{ - for (int i = 0; i < 5; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(particle, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + 1.0f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } +void Villager::addParticlesAroundSelf(ePARTICLE_TYPE particle) { + for (int i = 0; i < 5; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle( + particle, x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + 1.0f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); + } } -void Villager::finalizeMobSpawn() -{ - setProfession(level->random->nextInt(Villager::PROFESSION_MAX)); +void Villager::finalizeMobSpawn() { + setProfession(level->random->nextInt(Villager::PROFESSION_MAX)); } -void Villager::setRewardPlayersInVillage() -{ - rewardPlayersOnFirstVillage = true; +void Villager::setRewardPlayersInVillage() { + rewardPlayersOnFirstVillage = true; } -std::shared_ptr Villager::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to villagers that can be bred - if(level->canCreateMore(GetType(), Level::eSpawnType_Breed) ) - { - std::shared_ptr villager = std::shared_ptr(new Villager(level)); - villager->finalizeMobSpawn(); - return villager; - } - else - { - return nullptr; - } +std::shared_ptr Villager::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to villagers that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + std::shared_ptr villager = + std::shared_ptr(new Villager(level)); + villager->finalizeMobSpawn(); + return villager; + } else { + return nullptr; + } } -int Villager::getDisplayName() -{ - int name = IDS_VILLAGER; - switch(getProfession()) - { - case PROFESSION_FARMER: - name = IDS_VILLAGER_FARMER; - break; - case PROFESSION_LIBRARIAN: - name = IDS_VILLAGER_LIBRARIAN; - break; - case PROFESSION_PRIEST: - name = IDS_VILLAGER_PRIEST; - break; - case PROFESSION_SMITH: - name = IDS_VILLAGER_SMITH; - break; - case PROFESSION_BUTCHER: - name = IDS_VILLAGER_BUTCHER; - break; - }; - return name; +int Villager::getDisplayName() { + int name = IDS_VILLAGER; + switch (getProfession()) { + case PROFESSION_FARMER: + name = IDS_VILLAGER_FARMER; + break; + case PROFESSION_LIBRARIAN: + name = IDS_VILLAGER_LIBRARIAN; + break; + case PROFESSION_PRIEST: + name = IDS_VILLAGER_PRIEST; + break; + case PROFESSION_SMITH: + name = IDS_VILLAGER_SMITH; + break; + case PROFESSION_BUTCHER: + name = IDS_VILLAGER_BUTCHER; + break; + }; + return name; } diff --git a/Minecraft.World/Entities/Mobs/Villager.h b/Minecraft.World/Entities/Mobs/Villager.h index 6ae03f90a..037e74c76 100644 --- a/Minecraft.World/Entities/Mobs/Villager.h +++ b/Minecraft.World/Entities/Mobs/Villager.h @@ -10,140 +10,143 @@ class Village; class MerchantRecipeList; class MerchantRecipe; -class Villager : public AgableMob, public Npc, public Merchant -{ +class Villager : public AgableMob, public Npc, public Merchant { public: - eINSTANCEOF GetType() { return eTYPE_VILLAGER; } - static Entity *create(Level *level) { return new Villager(level); } + eINSTANCEOF GetType() { return eTYPE_VILLAGER; } + static Entity* create(Level* level) { return new Villager(level); } - //public static final String comment = "No, I won't 'fix' these! They're fine!! - Notch"; + // public static final String comment = "No, I won't 'fix' these! They're + // fine!! - Notch"; public: - static const int PROFESSION_FARMER = 0; - static const int PROFESSION_LIBRARIAN = 1; - static const int PROFESSION_PRIEST = 2; - static const int PROFESSION_SMITH = 3; - static const int PROFESSION_BUTCHER = 4; - static const int PROFESSION_MAX = 5; + static const int PROFESSION_FARMER = 0; + static const int PROFESSION_LIBRARIAN = 1; + static const int PROFESSION_PRIEST = 2; + static const int PROFESSION_SMITH = 3; + static const int PROFESSION_BUTCHER = 4; + static const int PROFESSION_MAX = 5; private: - static const int DATA_PROFESSION_ID = 16; - int villageUpdateInterval; + static const int DATA_PROFESSION_ID = 16; + int villageUpdateInterval; - bool inLove; - bool chasing; - std::weak_ptr village; + bool inLove; + bool chasing; + std::weak_ptr village; - std::weak_ptr tradingPlayer; - MerchantRecipeList *offers; - int updateMerchantTimer; - bool addRecipeOnUpdate; - int riches; + std::weak_ptr tradingPlayer; + MerchantRecipeList* offers; + int updateMerchantTimer; + bool addRecipeOnUpdate; + int riches; std::wstring lastPlayerTradeName; bool rewardPlayersOnFirstVillage; private: - - void _init(int profession); + void _init(int profession); public: - Villager(Level *level); - Villager(Level *level, int profession); - ~Villager(); + Villager(Level* level); + Villager(Level* level, int profession); + ~Villager(); - virtual bool useNewAi(); + virtual bool useNewAi(); protected: - virtual void serverAiMobStep(); + virtual void serverAiMobStep(); public: - virtual bool interact(std::shared_ptr player); + virtual bool interact(std::shared_ptr player); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual int getMaxHealth(); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual int getMaxHealth(); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); - virtual int getTexture(); + virtual int getTexture(); protected: - virtual bool removeWhenFarAway(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); + virtual bool removeWhenFarAway(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); public: - void setProfession(int profession); - int getProfession(); - bool isInLove(); - void setInLove(bool inLove); - void setChasing(bool chasing); - bool isChasing(); - void setLastHurtByMob(std::shared_ptr mob); - void die(DamageSource *source); + void setProfession(int profession); + int getProfession(); + bool isInLove(); + void setInLove(bool inLove); + void setChasing(bool chasing); + bool isChasing(); + void setLastHurtByMob(std::shared_ptr mob); + void die(DamageSource* source); - void handleEntityEvent(uint8_t id); + void handleEntityEvent(uint8_t id); private: - void addParticlesAroundSelf(ePARTICLE_TYPE particle); + void addParticlesAroundSelf(ePARTICLE_TYPE particle); public: - void setTradingPlayer(std::shared_ptr player); - std::shared_ptr getTradingPlayer(); - bool isTrading(); - void notifyTrade(MerchantRecipe *activeRecipe); - void notifyTradeUpdated(std::shared_ptr item); - MerchantRecipeList *getOffers(std::shared_ptr forPlayer); + void setTradingPlayer(std::shared_ptr player); + std::shared_ptr getTradingPlayer(); + bool isTrading(); + void notifyTrade(MerchantRecipe* activeRecipe); + void notifyTradeUpdated(std::shared_ptr item); + MerchantRecipeList* getOffers(std::shared_ptr forPlayer); private: - float baseRecipeChanceMod; + float baseRecipeChanceMod; - float getRecipeChance(float baseChance); - void addOffers(int addCount); + float getRecipeChance(float baseChance); + void addOffers(int addCount); public: - void overrideOffers(MerchantRecipeList *recipeList); + void overrideOffers(MerchantRecipeList* recipeList); private: - static std::unordered_map > MIN_MAX_VALUES; - static std::unordered_map > MIN_MAX_PRICES; + static std::unordered_map > MIN_MAX_VALUES; + static std::unordered_map > MIN_MAX_PRICES; public: - static void staticCtor(); + static void staticCtor(); private: - /** - * Adds a merchant recipe that trades items for a single ruby. - * - * @param list - * @param itemId - * @param random - * @param likelyHood - */ - static void addItemForTradeIn(MerchantRecipeList *list, int itemId, Random *random, float likelyHood); - static std::shared_ptr getItemTradeInValue(int itemId, Random *random); - static int getTradeInValue(int itemId, Random *random); + /** + * Adds a merchant recipe that trades items for a single ruby. + * + * @param list + * @param itemId + * @param random + * @param likelyHood + */ + static void addItemForTradeIn(MerchantRecipeList* list, int itemId, + Random* random, float likelyHood); + static std::shared_ptr getItemTradeInValue(int itemId, + Random* random); + static int getTradeInValue(int itemId, Random* random); - /** - * Adds a merchant recipe that trades rubies for an item. If the cost is - * negative, one ruby will give several of that item. - * - * @param list - * @param itemId - * @param random - * @param likelyHood - */ - static void addItemForPurchase(MerchantRecipeList *list, int itemId, Random *random, float likelyHood); - static int getPurchaseCost(int itemId, Random *random); + /** + * Adds a merchant recipe that trades rubies for an item. If the cost is + * negative, one ruby will give several of that item. + * + * @param list + * @param itemId + * @param random + * @param likelyHood + */ + static void addItemForPurchase(MerchantRecipeList* list, int itemId, + Random* random, float likelyHood); + static int getPurchaseCost(int itemId, Random* random); public: - void finalizeMobSpawn(); - void setRewardPlayersInVillage(); - std::shared_ptr getBreedOffspring(std::shared_ptr target); + void finalizeMobSpawn(); + void setRewardPlayersInVillage(); + std::shared_ptr getBreedOffspring( + std::shared_ptr target); - virtual int getDisplayName(); + virtual int getDisplayName(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/VillagerGolem.cpp b/Minecraft.World/Entities/Mobs/VillagerGolem.cpp index dd3e977d1..e3c1f39b1 100644 --- a/Minecraft.World/Entities/Mobs/VillagerGolem.cpp +++ b/Minecraft.World/Entities/Mobs/VillagerGolem.cpp @@ -18,223 +18,188 @@ #include "VillagerGolem.h" #include "../../Util/ParticleTypes.h" -VillagerGolem::VillagerGolem(Level *level) : Golem(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +VillagerGolem::VillagerGolem(Level* level) : Golem(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - villageUpdateInterval = 0; - village = std::weak_ptr(); - attackAnimationTick = 0; - offerFlowerTick = 0; + villageUpdateInterval = 0; + village = std::weak_ptr(); + attackAnimationTick = 0; + offerFlowerTick = 0; - this->textureIdx = TN_MOB_VILLAGER_GOLEM; // "/mob/villager_golem.png"; - this->setSize(1.4f, 2.9f); + this->textureIdx = TN_MOB_VILLAGER_GOLEM; // "/mob/villager_golem.png"; + this->setSize(1.4f, 2.9f); - getNavigation()->setAvoidWater(true); + getNavigation()->setAvoidWater(true); - // 4J-JEV: These speed values are as they appear before 1.6.4 (1.5), - // as the movement speed system changes then. (Mob attributes added) - goalSelector.addGoal(1, new MeleeAttackGoal(this, 0.25f, true)); - goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.22f, 32)); - goalSelector.addGoal(3, new MoveThroughVillageGoal(this, 0.16f, true)); - goalSelector.addGoal(4, new MoveTowardsRestrictionGoal(this, 0.16f)); - goalSelector.addGoal(5, new OfferFlowerGoal(this)); - goalSelector.addGoal(6, new RandomStrollGoal(this, 0.16f)); - goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); - goalSelector.addGoal(8, new RandomLookAroundGoal(this)); + // 4J-JEV: These speed values are as they appear before 1.6.4 (1.5), + // as the movement speed system changes then. (Mob attributes added) + goalSelector.addGoal(1, new MeleeAttackGoal(this, 0.25f, true)); + goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.22f, 32)); + goalSelector.addGoal(3, new MoveThroughVillageGoal(this, 0.16f, true)); + goalSelector.addGoal(4, new MoveTowardsRestrictionGoal(this, 0.16f)); + goalSelector.addGoal(5, new OfferFlowerGoal(this)); + goalSelector.addGoal(6, new RandomStrollGoal(this, 0.16f)); + goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 6)); + goalSelector.addGoal(8, new RandomLookAroundGoal(this)); - targetSelector.addGoal(1, new DefendVillageTargetGoal(this)); - targetSelector.addGoal(2, new HurtByTargetGoal(this, false)); - targetSelector.addGoal(3, new NearestAttackableTargetGoal(this, typeid(Monster), 16, 0, false, true)); + targetSelector.addGoal(1, new DefendVillageTargetGoal(this)); + targetSelector.addGoal(2, new HurtByTargetGoal(this, false)); + targetSelector.addGoal(3, new NearestAttackableTargetGoal( + this, typeid(Monster), 16, 0, false, true)); } -void VillagerGolem::defineSynchedData() -{ - Golem::defineSynchedData(); - entityData->define(DATA_FLAGS_ID, (uint8_t) 0); +void VillagerGolem::defineSynchedData() { + Golem::defineSynchedData(); + entityData->define(DATA_FLAGS_ID, (uint8_t)0); } -bool VillagerGolem::useNewAi() -{ - return true; +bool VillagerGolem::useNewAi() { return true; } + +void VillagerGolem::serverAiMobStep() { + if (--villageUpdateInterval <= 0) { + villageUpdateInterval = 70 + random->nextInt(50); + std::shared_ptr _village = level->villages->getClosestVillage( + Mth::floor(x), Mth::floor(y), Mth::floor(z), Villages::MaxDoorDist); + village = _village; + if (_village == NULL) + clearRestriction(); + else { + Pos* center = _village->getCenter(); + restrictTo(center->x, center->y, center->z, + (int)((float)_village->getRadius()) * 0.6f); + } + } + + Golem::serverAiMobStep(); } -void VillagerGolem::serverAiMobStep() -{ - if (--villageUpdateInterval <= 0) - { - villageUpdateInterval = 70 + random->nextInt(50); - std::shared_ptr _village = level->villages->getClosestVillage(Mth::floor(x), Mth::floor(y), Mth::floor(z), Villages::MaxDoorDist); - village = _village; - if (_village == NULL) clearRestriction(); - else - { - Pos *center = _village->getCenter(); - restrictTo(center->x, center->y, center->z, (int)((float)_village->getRadius()) * 0.6f); - } - } +int VillagerGolem::getMaxHealth() { return 100; } - Golem::serverAiMobStep(); +int VillagerGolem::decreaseAirSupply(int currentSupply) { + // infinite air supply + return currentSupply; } -int VillagerGolem::getMaxHealth() -{ - return 100; +void VillagerGolem::aiStep() { + Golem::aiStep(); + + if (attackAnimationTick > 0) --attackAnimationTick; + if (offerFlowerTick > 0) --offerFlowerTick; + + if (xd * xd + zd * zd > MoveControl::MIN_SPEED_SQR && + random->nextInt(5) == 0) { + int xt = Mth::floor(x); + int yt = Mth::floor(y - 0.2f - this->heightOffset); + int zt = Mth::floor(z); + int t = level->getTile(xt, yt, zt); + int d = level->getData(xt, yt, zt); + if (t > 0) { + level->addParticle(PARTICLE_TILECRACK(t, d), + x + (random->nextFloat() - 0.5) * bbWidth, + bb->y0 + 0.1, + z + (random->nextFloat() - 0.5) * bbWidth, + 4 * (random->nextFloat() - 0.5), .5, + (random->nextFloat() - 0.5) * 4); + } + } } -int VillagerGolem::decreaseAirSupply(int currentSupply) -{ - // infinite air supply - return currentSupply; +bool VillagerGolem::canAttackType(eINSTANCEOF targetType) { + if (isPlayerCreated() && (eTYPE_PLAYER & targetType) == eTYPE_PLAYER) + return false; + return Golem::canAttackType(targetType); } -void VillagerGolem::aiStep() -{ - Golem::aiStep(); - - if (attackAnimationTick > 0) --attackAnimationTick; - if (offerFlowerTick > 0) --offerFlowerTick; - - if (xd * xd + zd * zd > MoveControl::MIN_SPEED_SQR && random->nextInt(5) == 0) - { - int xt = Mth::floor(x); - int yt = Mth::floor(y - 0.2f - this->heightOffset); - int zt = Mth::floor(z); - int t = level->getTile(xt, yt, zt); - int d = level->getData(xt, yt, zt); - if (t > 0) - { - level->addParticle(PARTICLE_TILECRACK(t,d), x + (random->nextFloat() - 0.5) * bbWidth, bb->y0 + 0.1, z + (random->nextFloat() - 0.5) * bbWidth, 4 * (random->nextFloat() - 0.5), .5, - (random->nextFloat() - 0.5) * 4); - } - } +void VillagerGolem::addAdditonalSaveData(CompoundTag* tag) { + Golem::addAdditonalSaveData(tag); + tag->putBoolean(L"PlayerCreated", isPlayerCreated()); } -bool VillagerGolem::canAttackType(eINSTANCEOF targetType) -{ - if (isPlayerCreated() && (eTYPE_PLAYER & targetType) == eTYPE_PLAYER ) return false; - return Golem::canAttackType(targetType); +void VillagerGolem::readAdditionalSaveData(CompoundTag* tag) { + Golem::readAdditionalSaveData(tag); + setPlayerCreated(tag->getBoolean(L"PlayerCreated")); } -void VillagerGolem::addAdditonalSaveData(CompoundTag *tag) -{ - Golem::addAdditonalSaveData(tag); - tag->putBoolean(L"PlayerCreated", isPlayerCreated()); +bool VillagerGolem::doHurtTarget(std::shared_ptr target) { + attackAnimationTick = 10; + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::START_ATTACKING); + bool hurt = + target->hurt(DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())), + 7 + random->nextInt(15)); + if (hurt) target->yd += 0.4f; + level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_THROW, 1, 1); + return hurt; } -void VillagerGolem::readAdditionalSaveData(CompoundTag *tag) -{ - Golem::readAdditionalSaveData(tag); - setPlayerCreated(tag->getBoolean(L"PlayerCreated")); +void VillagerGolem::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::START_ATTACKING) { + attackAnimationTick = 10; + level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_THROW, 1, + 1); + } else if (id == EntityEvent::OFFER_FLOWER) { + offerFlowerTick = OfferFlowerGoal::OFFER_TICKS; + } else + Golem::handleEntityEvent(id); } -bool VillagerGolem::doHurtTarget(std::shared_ptr target) -{ - attackAnimationTick = 10; - level->broadcastEntityEvent(shared_from_this(), EntityEvent::START_ATTACKING); - bool hurt = target->hurt(DamageSource::mobAttack(std::dynamic_pointer_cast(shared_from_this())), 7 + random->nextInt(15)); - if (hurt) target->yd += 0.4f; - level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_THROW, 1, 1); - return hurt; +std::shared_ptr VillagerGolem::getVillage() { return village.lock(); } + +int VillagerGolem::getAttackAnimationTick() { return attackAnimationTick; } + +void VillagerGolem::offerFlower(bool offer) { + offerFlowerTick = offer ? OfferFlowerGoal::OFFER_TICKS : 0; + level->broadcastEntityEvent(shared_from_this(), EntityEvent::OFFER_FLOWER); } -void VillagerGolem::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::START_ATTACKING) - { - attackAnimationTick = 10; - level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_THROW, 1, 1); - } - else if (id == EntityEvent::OFFER_FLOWER) - { - offerFlowerTick = OfferFlowerGoal::OFFER_TICKS; - } - else Golem::handleEntityEvent(id); +int VillagerGolem::getAmbientSound() { return -1; } + +int VillagerGolem::getHurtSound() { return eSoundType_MOB_IRONGOLEM_HIT; } + +int VillagerGolem::getDeathSound() { return eSoundType_MOB_IRONGOLEM_DEATH; } + +void VillagerGolem::playStepSound(int xt, int yt, int zt, int t) { + level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_WALK, 1, 1); } -std::shared_ptr VillagerGolem::getVillage() -{ - return village.lock(); +void VillagerGolem::dropDeathLoot(bool wasKilledByPlayer, + int playerBonusLevel) { + int roses = random->nextInt(3); + for (int i = 0; i < roses; i++) { + spawnAtLocation(Tile::rose_Id, 1); + } + int iron = 3 + random->nextInt(3); + for (int i = 0; i < iron; i++) { + spawnAtLocation(Item::ironIngot_Id, 1); + } } -int VillagerGolem::getAttackAnimationTick() -{ - return attackAnimationTick; +int VillagerGolem::getOfferFlowerTick() { return offerFlowerTick; } + +bool VillagerGolem::isPlayerCreated() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x01) != 0; } -void VillagerGolem::offerFlower(bool offer) -{ - offerFlowerTick = offer ? OfferFlowerGoal::OFFER_TICKS : 0; - level->broadcastEntityEvent(shared_from_this(), EntityEvent::OFFER_FLOWER); +void VillagerGolem::setPlayerCreated(bool value) { + uint8_t current = entityData->getByte(DATA_FLAGS_ID); + if (value) { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current | 0x01)); + } else { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current & ~0x01)); + } } -int VillagerGolem::getAmbientSound() -{ - return -1; -} - -int VillagerGolem::getHurtSound() -{ - return eSoundType_MOB_IRONGOLEM_HIT; -} - -int VillagerGolem::getDeathSound() -{ - return eSoundType_MOB_IRONGOLEM_DEATH; -} - -void VillagerGolem::playStepSound(int xt, int yt, int zt, int t) -{ - level->playSound(shared_from_this(), eSoundType_MOB_IRONGOLEM_WALK, 1, 1); -} - -void VillagerGolem::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) -{ - int roses = random->nextInt(3); - for (int i = 0; i < roses; i++) - { - spawnAtLocation(Tile::rose_Id, 1); - } - int iron = 3 + random->nextInt(3); - for (int i = 0; i < iron; i++) - { - spawnAtLocation(Item::ironIngot_Id, 1); - } -} - -int VillagerGolem::getOfferFlowerTick() -{ - return offerFlowerTick; -} - -bool VillagerGolem::isPlayerCreated() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x01) != 0; -} - -void VillagerGolem::setPlayerCreated(bool value) -{ - uint8_t current = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current | 0x01)); - } - else - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current & ~0x01)); - } -} - -void VillagerGolem::die(DamageSource *source) -{ - if (!isPlayerCreated() && lastHurtByPlayer != NULL && village.lock() != NULL) - { - village.lock()->modifyStanding(lastHurtByPlayer->getName(), -5); - } - Golem::die(source); +void VillagerGolem::die(DamageSource* source) { + if (!isPlayerCreated() && lastHurtByPlayer != NULL && + village.lock() != NULL) { + village.lock()->modifyStanding(lastHurtByPlayer->getName(), -5); + } + Golem::die(source); } \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/VillagerGolem.h b/Minecraft.World/Entities/Mobs/VillagerGolem.h index 4a71db541..b3b6ff370 100644 --- a/Minecraft.World/Entities/Mobs/VillagerGolem.h +++ b/Minecraft.World/Entities/Mobs/VillagerGolem.h @@ -5,60 +5,59 @@ class Village; class Level; -class VillagerGolem : public Golem -{ +class VillagerGolem : public Golem { public: - eINSTANCEOF GetType() { return eTYPE_VILLAGERGOLEM; } - static Entity *create(Level *level) { return new VillagerGolem(level); } + eINSTANCEOF GetType() { return eTYPE_VILLAGERGOLEM; } + static Entity* create(Level* level) { return new VillagerGolem(level); } protected: - static const int DATA_FLAGS_ID = 16; + static const int DATA_FLAGS_ID = 16; private: - int villageUpdateInterval; - std::weak_ptr village; - int attackAnimationTick; - int offerFlowerTick; + int villageUpdateInterval; + std::weak_ptr village; + int attackAnimationTick; + int offerFlowerTick; public: - VillagerGolem(Level *level); + VillagerGolem(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual bool useNewAi(); + virtual bool useNewAi(); protected: - virtual void serverAiMobStep(); + virtual void serverAiMobStep(); public: - virtual int getMaxHealth(); + virtual int getMaxHealth(); protected: - virtual int decreaseAirSupply(int currentSupply); + virtual int decreaseAirSupply(int currentSupply); public: - virtual void aiStep(); - virtual bool canAttackType(eINSTANCEOF targetType); - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual bool doHurtTarget(std::shared_ptr target); - virtual void handleEntityEvent(uint8_t id); - virtual std::shared_ptr getVillage(); - virtual int getAttackAnimationTick(); - virtual void offerFlower(bool offer); + virtual void aiStep(); + virtual bool canAttackType(eINSTANCEOF targetType); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual bool doHurtTarget(std::shared_ptr target); + virtual void handleEntityEvent(uint8_t id); + virtual std::shared_ptr getVillage(); + virtual int getAttackAnimationTick(); + virtual void offerFlower(bool offer); protected: - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual void playStepSound(int xt, int yt, int zt, int t); - virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual void playStepSound(int xt, int yt, int zt, int t); + virtual void dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel); public: - virtual int getOfferFlowerTick(); - virtual bool isPlayerCreated(); - virtual void setPlayerCreated(bool value); - virtual void die(DamageSource *source); + virtual int getOfferFlowerTick(); + virtual bool isPlayerCreated(); + virtual void setPlayerCreated(bool value); + virtual void die(DamageSource* source); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Mobs/Wolf.cpp b/Minecraft.World/Entities/Mobs/Wolf.cpp index 0220c78d0..bc88f97e7 100644 --- a/Minecraft.World/Entities/Mobs/Wolf.cpp +++ b/Minecraft.World/Entities/Mobs/Wolf.cpp @@ -18,533 +18,437 @@ #include "../../../Minecraft.Client/Textures/Textures.h" #include "../../Util/SoundTypes.h" +Wolf::Wolf(Level* level) : TamableAnimal(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); -Wolf::Wolf(Level *level) : TamableAnimal( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); + interestedAngle = interestedAngleO = 0.0f; + m_isWet = isShaking = false; + shakeAnim = shakeAnimO = 0.0f; - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + this->textureIdx = TN_MOB_WOLF; // 4J - was L"/mob/wolf.png"; + this->setSize(0.60f, 0.8f); + runSpeed = 0.3f; - interestedAngle = interestedAngleO = 0.0f; - m_isWet = isShaking = false; - shakeAnim = shakeAnimO = 0.0f; + getNavigation()->setAvoidWater(true); + goalSelector.addGoal(1, new FloatGoal(this)); + goalSelector.addGoal(2, sitGoal, false); + goalSelector.addGoal(3, new LeapAtTargetGoal(this, 0.4f)); + goalSelector.addGoal(4, new MeleeAttackGoal(this, runSpeed, true)); + goalSelector.addGoal(5, new FollowOwnerGoal(this, runSpeed, 10, 2)); + goalSelector.addGoal(6, new BreedGoal(this, runSpeed)); + goalSelector.addGoal(7, new RandomStrollGoal(this, runSpeed)); + goalSelector.addGoal(8, new BegGoal(this, 8)); + goalSelector.addGoal(9, new LookAtPlayerGoal(this, typeid(Player), 8)); + goalSelector.addGoal(9, new RandomLookAroundGoal(this)); - this->textureIdx = TN_MOB_WOLF; // 4J - was L"/mob/wolf.png"; - this->setSize(0.60f, 0.8f); - runSpeed = 0.3f; - - getNavigation()->setAvoidWater(true); - goalSelector.addGoal(1, new FloatGoal(this)); - goalSelector.addGoal(2, sitGoal, false); - goalSelector.addGoal(3, new LeapAtTargetGoal(this, 0.4f)); - goalSelector.addGoal(4, new MeleeAttackGoal(this, runSpeed, true)); - goalSelector.addGoal(5, new FollowOwnerGoal(this, runSpeed, 10, 2)); - goalSelector.addGoal(6, new BreedGoal(this, runSpeed)); - goalSelector.addGoal(7, new RandomStrollGoal(this, runSpeed)); - goalSelector.addGoal(8, new BegGoal(this, 8)); - goalSelector.addGoal(9, new LookAtPlayerGoal(this, typeid(Player), 8)); - goalSelector.addGoal(9, new RandomLookAroundGoal(this)); - - targetSelector.addGoal(1, new OwnerHurtByTargetGoal(this)); - targetSelector.addGoal(2, new OwnerHurtTargetGoal(this)); - targetSelector.addGoal(3, new HurtByTargetGoal(this, true)); - targetSelector.addGoal(4, new NonTameRandomTargetGoal(this, typeid(Sheep), 16, 200, false)); + targetSelector.addGoal(1, new OwnerHurtByTargetGoal(this)); + targetSelector.addGoal(2, new OwnerHurtTargetGoal(this)); + targetSelector.addGoal(3, new HurtByTargetGoal(this, true)); + targetSelector.addGoal( + 4, new NonTameRandomTargetGoal(this, typeid(Sheep), 16, 200, false)); } -bool Wolf::useNewAi() -{ - return true; +bool Wolf::useNewAi() { return true; } + +void Wolf::setTarget(std::shared_ptr target) { + TamableAnimal::setTarget(target); + if (std::dynamic_pointer_cast(target) == NULL) { + setAngry(false); + } else if (!isTame()) { + setAngry(true); + } } -void Wolf::setTarget(std::shared_ptr target) -{ - TamableAnimal::setTarget(target); - if ( std::dynamic_pointer_cast(target) == NULL ) - { - setAngry(false); - } - else if(!isTame()) - { - setAngry(true); - } +void Wolf::serverAiMobStep() { entityData->set(DATA_HEALTH_ID, getHealth()); } + +int Wolf::getMaxHealth() { + if (isTame()) { + return TAME_HEALTH; + } + return START_HEALTH; } -void Wolf::serverAiMobStep() -{ - entityData->set(DATA_HEALTH_ID, getHealth()); +void Wolf::defineSynchedData() { + TamableAnimal::defineSynchedData(); + entityData->define(DATA_HEALTH_ID, getHealth()); + entityData->define(DATA_INTERESTED_ID, (uint8_t)0); + entityData->define( + DATA_COLLAR_COLOR, + (uint8_t)ClothTile::getTileDataForItemAuxValue(DyePowderItem::RED)); } -int Wolf::getMaxHealth() -{ - if (isTame()) - { - return TAME_HEALTH; - } - return START_HEALTH; +bool Wolf::makeStepSound() { return false; } + +int Wolf::getTexture() { + if (isTame()) { + return TN_MOB_WOLF_TAME; // 4J was L"/mob/wolf_tame.png"; + } + if (isAngry()) { + return TN_MOB_WOLF_ANGRY; // 4J was L"/mob/wolf_angry.png"; + } + return TamableAnimal::getTexture(); } -void Wolf::defineSynchedData() -{ - TamableAnimal::defineSynchedData(); - entityData->define(DATA_HEALTH_ID, getHealth()); - entityData->define(DATA_INTERESTED_ID, (uint8_t)0); - entityData->define(DATA_COLLAR_COLOR, (uint8_t) ClothTile::getTileDataForItemAuxValue(DyePowderItem::RED)); +void Wolf::addAdditonalSaveData(CompoundTag* tag) { + TamableAnimal::addAdditonalSaveData(tag); + + tag->putBoolean(L"Angry", isAngry()); + tag->putByte(L"CollarColor", (uint8_t)getCollarColor()); } -bool Wolf::makeStepSound() -{ - return false; +void Wolf::readAdditionalSaveData(CompoundTag* tag) { + TamableAnimal::readAdditionalSaveData(tag); + + setAngry(tag->getBoolean(L"Angry")); + if (tag->contains(L"CollarColor")) + setCollarColor(tag->getByte(L"CollarColor")); } -int Wolf::getTexture() -{ - if (isTame()) - { - return TN_MOB_WOLF_TAME; // 4J was L"/mob/wolf_tame.png"; - } - if (isAngry()) - { - return TN_MOB_WOLF_ANGRY; // 4J was L"/mob/wolf_angry.png"; - } - return TamableAnimal::getTexture(); +bool Wolf::removeWhenFarAway() { return !isTame(); } + +int Wolf::getAmbientSound() { + if (isAngry()) { + return eSoundType_MOB_WOLF_GROWL; + } + if (random->nextInt(3) == 0) { + if (isTame() && entityData->getInteger(DATA_HEALTH_ID) < 10) { + return eSoundType_MOB_WOLF_WHINE; + } + return eSoundType_MOB_WOLF_PANTING; + } + return eSoundType_MOB_WOLF_BARK; } -void Wolf::addAdditonalSaveData(CompoundTag *tag) -{ - TamableAnimal::addAdditonalSaveData(tag); +int Wolf::getHurtSound() { return eSoundType_MOB_WOLF_HURT; } - tag->putBoolean(L"Angry", isAngry()); - tag->putByte(L"CollarColor", (uint8_t) getCollarColor()); +int Wolf::getDeathSound() { return eSoundType_MOB_WOLF_DEATH; } + +float Wolf::getSoundVolume() { return 0.4f; } + +int Wolf::getDeathLoot() { return -1; } + +void Wolf::aiStep() { + TamableAnimal::aiStep(); + + if (!level->isClientSide && m_isWet && !isShaking && !isPathFinding() && + onGround) { + isShaking = true; + shakeAnim = 0; + shakeAnimO = 0; + + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::SHAKE_WETNESS); + } } -void Wolf::readAdditionalSaveData(CompoundTag *tag) -{ - TamableAnimal::readAdditionalSaveData(tag); +void Wolf::tick() { + TamableAnimal::tick(); - setAngry(tag->getBoolean(L"Angry")); - if (tag->contains(L"CollarColor")) setCollarColor(tag->getByte(L"CollarColor")); + interestedAngleO = interestedAngle; + if (isInterested()) { + interestedAngle = interestedAngle + (1 - interestedAngle) * 0.4f; + } else { + interestedAngle = interestedAngle + (0 - interestedAngle) * 0.4f; + } + if (isInterested()) { + lookTime = 10; + } + + if (isInWaterOrRain()) { + m_isWet = true; + isShaking = false; + shakeAnim = 0; + shakeAnimO = 0; + } else if (m_isWet || isShaking) { + if (isShaking) { + if (shakeAnim == 0) { + level->playSound( + shared_from_this(), eSoundType_MOB_WOLF_SHAKE, + getSoundVolume(), + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + } + + shakeAnimO = shakeAnim; + shakeAnim += 0.05f; + + if (shakeAnimO >= 2) { + m_isWet = false; + isShaking = false; + shakeAnimO = 0; + shakeAnim = 0; + } + + if (shakeAnim > 0.4f) { + float yt = (float)bb->y0; + int shakeCount = + (int)(Mth::sin((shakeAnim - 0.4f) * PI) * 7.0f); + for (int i = 0; i < shakeCount; i++) { + float xo = (random->nextFloat() * 2 - 1) * bbWidth * 0.5f; + float zo = (random->nextFloat() * 2 - 1) * bbWidth * 0.5f; + level->addParticle(eParticleType_splash, x + xo, yt + 0.8f, + z + zo, xd, yd, zd); + } + } + } + } } -bool Wolf::removeWhenFarAway() -{ - return !isTame(); +bool Wolf::isWet() { return m_isWet; } + +float Wolf::getWetShade(float a) { + return 0.75f + ((shakeAnimO + (shakeAnim - shakeAnimO) * a) / 2.0f) * 0.25f; } -int Wolf::getAmbientSound() -{ - if (isAngry()) - { - return eSoundType_MOB_WOLF_GROWL; - } - if (random->nextInt(3) == 0) - { - if (isTame() && entityData->getInteger(DATA_HEALTH_ID) < 10) - { - return eSoundType_MOB_WOLF_WHINE; - } - return eSoundType_MOB_WOLF_PANTING; - } - return eSoundType_MOB_WOLF_BARK; +float Wolf::getBodyRollAngle(float a, float offset) { + float progress = + ((shakeAnimO + (shakeAnim - shakeAnimO) * a) + offset) / 1.8f; + if (progress < 0) { + progress = 0; + } else if (progress > 1) { + progress = 1; + } + return Mth::sin(progress * PI) * Mth::sin(progress * PI * 11.0f) * 0.15f * + PI; } -int Wolf::getHurtSound() -{ - return eSoundType_MOB_WOLF_HURT; +float Wolf::getHeadRollAngle(float a) { + return (interestedAngleO + (interestedAngle - interestedAngleO) * a) * + 0.15f * PI; } -int Wolf::getDeathSound() -{ - return eSoundType_MOB_WOLF_DEATH; +float Wolf::getHeadHeight() { return bbHeight * 0.8f; } + +int Wolf::getMaxHeadXRot() { + if (isSitting()) { + return 20; + } + return TamableAnimal::getMaxHeadXRot(); } -float Wolf::getSoundVolume() -{ - return 0.4f; +bool Wolf::hurt(DamageSource* source, int dmg) { + if (isInvulnerable()) return false; + std::shared_ptr sourceEntity = source->getEntity(); + sitGoal->wantToSit(false); + if (sourceEntity != NULL && + !(std::dynamic_pointer_cast(sourceEntity) != NULL || + std::dynamic_pointer_cast(sourceEntity) != NULL)) { + // take half damage from non-players and arrows + dmg = (dmg + 1) / 2; + } + return TamableAnimal::hurt(source, dmg); } -int Wolf::getDeathLoot() -{ - return -1; +bool Wolf::doHurtTarget(std::shared_ptr target) { + int damage = isTame() ? 4 : 2; + return target->hurt(DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())), + damage); } -void Wolf::aiStep() -{ - TamableAnimal::aiStep(); +void Wolf::tame(const std::wstring& wsOwnerUUID, bool bDisplayTamingParticles, + bool bSetSitting) { + setTame(true); + setPath(NULL); + setTarget(nullptr); + sitGoal->wantToSit(bSetSitting); + setHealth(TAME_HEALTH); - if (!level->isClientSide && m_isWet && !isShaking && !isPathFinding() && onGround) - { - isShaking = true; - shakeAnim = 0; - shakeAnimO = 0; + setOwnerUUID(wsOwnerUUID); - level->broadcastEntityEvent(shared_from_this(), EntityEvent::SHAKE_WETNESS); - } + // We'll not show the taming particles if this is a baby wolf + spawnTamingParticles(bDisplayTamingParticles); } -void Wolf::tick() -{ - TamableAnimal::tick(); +bool Wolf::interact(std::shared_ptr player) { + std::shared_ptr item = player->inventory->getSelected(); - interestedAngleO = interestedAngle; - if (isInterested()) - { - interestedAngle = interestedAngle + (1 - interestedAngle) * 0.4f; - } - else - { - interestedAngle = interestedAngle + (0 - interestedAngle) * 0.4f; - } - if (isInterested()) - { - lookTime = 10; - } + if (isTame()) { + if (item != NULL) { + if (dynamic_cast(Item::items[item->id]) != NULL) { + FoodItem* food = dynamic_cast(Item::items[item->id]); - if (isInWaterOrRain()) - { - m_isWet = true; - isShaking = false; - shakeAnim = 0; - shakeAnimO = 0; - } - else if (m_isWet || isShaking) - { - if (isShaking) - { + if (food->isMeat()) { + if (entityData->getInteger(DATA_HEALTH_ID) < MAX_HEALTH) { + heal(food->getNutrition()); + // 4J-PB - don't lose the bone in creative mode + if (player->abilities.instabuild == false) { + item->count--; + if (item->count <= 0) { + player->inventory->setItem( + player->inventory->selected, nullptr); + } + } + return true; + } else + return TamableAnimal::interact(player); + } + } else if (item->id == Item::dye_powder_Id) { + int color = + ClothTile::getTileDataForItemAuxValue(item->getAuxValue()); + if (color != getCollarColor()) { + setCollarColor(color); - if (shakeAnim == 0) - { - level->playSound(shared_from_this(), eSoundType_MOB_WOLF_SHAKE, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - } + if (!player->abilities.instabuild && --item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } - shakeAnimO = shakeAnim; - shakeAnim += 0.05f; + return true; + } + } + } + if (equalsIgnoreCase(player->getUUID(), getOwnerUUID())) { + if (!level->isClientSide && !isFood(item)) { + sitGoal->wantToSit(!isSitting()); + jumping = false; + setPath(NULL); + } + } + } else { + if (item != NULL && item->id == Item::bone->id && !isAngry()) { + // 4J-PB - don't lose the bone in creative mode + if (player->abilities.instabuild == false) { + item->count--; + if (item->count <= 0) { + player->inventory->setItem(player->inventory->selected, + nullptr); + } + } - if (shakeAnimO >= 2) - { - m_isWet = false; - isShaking = false; - shakeAnimO = 0; - shakeAnim = 0; - } + if (!level->isClientSide) { + if (random->nextInt(3) == 0) { + // 4J : WESTY: Added for new acheivements. + player->awardStat( + GenericStats::tamedEntity(eTYPE_WOLF), + GenericStats::param_tamedEntity(eTYPE_WOLF)); - if (shakeAnim > 0.4f) - { - float yt = (float) bb->y0; - int shakeCount = (int) (Mth::sin((shakeAnim - 0.4f) * PI) * 7.0f); - for (int i = 0; i < shakeCount; i++) - { - float xo = (random->nextFloat() * 2 - 1) * bbWidth * 0.5f; - float zo = (random->nextFloat() * 2 - 1) * bbWidth * 0.5f; - level->addParticle(eParticleType_splash, x + xo, yt + 0.8f, z + zo, xd, yd, zd); - } - } - } - } + // 4J Changed to this + tame(player->getUUID(), true, true); + + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::TAMING_SUCCEEDED); + } else { + spawnTamingParticles(false); + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::TAMING_FAILED); + } + } + + return true; + } + + // 4J-PB - stop wild wolves going in to Love Mode (even though they do + // on Java, but don't breed) + if ((item != NULL) && isFood(item)) { + return false; + } + } + return TamableAnimal::interact(player); } -bool Wolf::isWet() -{ - return m_isWet; +void Wolf::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::SHAKE_WETNESS) { + isShaking = true; + shakeAnim = 0; + shakeAnimO = 0; + } else { + TamableAnimal::handleEntityEvent(id); + } } -float Wolf::getWetShade(float a) -{ - return 0.75f + ((shakeAnimO + (shakeAnim - shakeAnimO) * a) / 2.0f) * 0.25f; +float Wolf::getTailAngle() { + if (isAngry()) { + return 0.49f * PI; + } else if (isTame()) { + return (0.55f - + (MAX_HEALTH - entityData->getInteger(DATA_HEALTH_ID)) * 0.02f) * + PI; + } + return 0.20f * PI; } -float Wolf::getBodyRollAngle(float a, float offset) -{ - float progress = ((shakeAnimO + (shakeAnim - shakeAnimO) * a) + offset) / 1.8f; - if (progress < 0) - { - progress = 0; - } - else if (progress > 1) - { - progress = 1; - } - return Mth::sin(progress * PI) * Mth::sin(progress * PI * 11.0f) * 0.15f * PI; +bool Wolf::isFood(std::shared_ptr item) { + if (item == NULL) return false; + if (dynamic_cast(Item::items[item->id]) == NULL) return false; + return ((FoodItem*)Item::items[item->id])->isMeat(); } -float Wolf::getHeadRollAngle(float a) -{ - return (interestedAngleO + (interestedAngle - interestedAngleO) * a) * 0.15f * PI; +int Wolf::getMaxSpawnClusterSize() { + // 4J - changed - was 8 but we have a limit of only 8 wolves in the world so + // doesn't seem right potentially spawning them all in once cluster + return 4; } -float Wolf::getHeadHeight() -{ - return bbHeight * 0.8f; +bool Wolf::isAngry() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x02) != 0; } -int Wolf::getMaxHeadXRot() -{ - if (isSitting()) - { - return 20; - } - return TamableAnimal::getMaxHeadXRot(); +void Wolf::setAngry(bool value) { + uint8_t current = entityData->getByte(DATA_FLAGS_ID); + if (value) { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current | 0x02)); + } else { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current & ~0x02)); + } } -bool Wolf::hurt(DamageSource *source, int dmg) -{ - if (isInvulnerable()) return false; - std::shared_ptr sourceEntity = source->getEntity(); - sitGoal->wantToSit(false); - if (sourceEntity != NULL && !(std::dynamic_pointer_cast(sourceEntity) != NULL || std::dynamic_pointer_cast(sourceEntity) != NULL)) - { - // take half damage from non-players and arrows - dmg = (dmg + 1) / 2; - } - return TamableAnimal::hurt(source, dmg); +int Wolf::getCollarColor() { + return entityData->getByte(DATA_COLLAR_COLOR) & 0xF; } -bool Wolf::doHurtTarget(std::shared_ptr target) -{ - int damage = isTame() ? 4 : 2; - return target->hurt(DamageSource::mobAttack(std::dynamic_pointer_cast(shared_from_this())), damage); -} - -void Wolf::tame(const std::wstring &wsOwnerUUID, bool bDisplayTamingParticles, bool bSetSitting) -{ - setTame(true); - setPath(NULL); - setTarget(nullptr); - sitGoal->wantToSit(bSetSitting); - setHealth(TAME_HEALTH); - - setOwnerUUID(wsOwnerUUID); - - // We'll not show the taming particles if this is a baby wolf - spawnTamingParticles(bDisplayTamingParticles); -} - -bool Wolf::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->inventory->getSelected(); - - if (isTame()) - { - if (item != NULL) - { - if(dynamic_cast(Item::items[item->id]) != NULL) - { - FoodItem *food = dynamic_cast( Item::items[item->id] ); - - if (food->isMeat()) - { - if(entityData->getInteger(DATA_HEALTH_ID) < MAX_HEALTH) - { - heal(food->getNutrition()); - // 4J-PB - don't lose the bone in creative mode - if (player->abilities.instabuild==false) - { - item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - return true; - } - else return TamableAnimal::interact(player); - } - } - else if (item->id == Item::dye_powder_Id) - { - int color = ClothTile::getTileDataForItemAuxValue(item->getAuxValue()); - if (color != getCollarColor()) - { - setCollarColor(color); - - if (!player->abilities.instabuild && --item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - - return true; - } - } - } - if (equalsIgnoreCase(player->getUUID(), getOwnerUUID())) - { - if (!level->isClientSide && !isFood(item)) - { - sitGoal->wantToSit(!isSitting()); - jumping = false; - setPath(NULL); - } - } - } - else - { - if (item != NULL && item->id == Item::bone->id && !isAngry()) - { - // 4J-PB - don't lose the bone in creative mode - if (player->abilities.instabuild==false) - { - item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } - } - - if (!level->isClientSide) - { - if (random->nextInt(3) == 0) - { - // 4J : WESTY: Added for new acheivements. - player->awardStat(GenericStats::tamedEntity(eTYPE_WOLF),GenericStats::param_tamedEntity(eTYPE_WOLF)); - - // 4J Changed to this - tame(player->getUUID(),true,true); - - level->broadcastEntityEvent(shared_from_this(), EntityEvent::TAMING_SUCCEEDED); - } - else - { - spawnTamingParticles(false); - level->broadcastEntityEvent(shared_from_this(), EntityEvent::TAMING_FAILED); - } - } - - return true; - } - - // 4J-PB - stop wild wolves going in to Love Mode (even though they do on Java, but don't breed) - if((item != NULL) && isFood(item)) - { - return false; - } - } - return TamableAnimal::interact(player); -} - -void Wolf::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::SHAKE_WETNESS) - { - isShaking = true; - shakeAnim = 0; - shakeAnimO = 0; - } - else - { - TamableAnimal::handleEntityEvent(id); - } -} - -float Wolf::getTailAngle() -{ - if (isAngry()) - { - return 0.49f * PI; - } - else if (isTame()) - { - return (0.55f - (MAX_HEALTH - entityData->getInteger(DATA_HEALTH_ID)) * 0.02f) * PI; - } - return 0.20f * PI; -} - -bool Wolf::isFood(std::shared_ptr item) -{ - if (item == NULL) return false; - if (dynamic_cast(Item::items[item->id]) == NULL) return false; - return ((FoodItem *) Item::items[item->id])->isMeat(); -} - -int Wolf::getMaxSpawnClusterSize() -{ - // 4J - changed - was 8 but we have a limit of only 8 wolves in the world so doesn't seem right potentially spawning them all in once cluster - return 4; -} - -bool Wolf::isAngry() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x02) != 0; -} - -void Wolf::setAngry(bool value) -{ - uint8_t current = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current | 0x02)); - } - else - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current & ~0x02)); - } -} - -int Wolf::getCollarColor() -{ - return entityData->getByte(DATA_COLLAR_COLOR) & 0xF; -} - -void Wolf::setCollarColor(int color) -{ - entityData->set(DATA_COLLAR_COLOR, (uint8_t) (color & 0xF)); +void Wolf::setCollarColor(int color) { + entityData->set(DATA_COLLAR_COLOR, (uint8_t)(color & 0xF)); } // 4J-PB added for tooltips -int Wolf::GetSynchedHealth() -{ - return getEntityData()->getInteger(DATA_HEALTH_ID); -} - -std::shared_ptr Wolf::getBreedOffspring(std::shared_ptr target) -{ - // 4J - added limit to wolves that can be bred - if( level->canCreateMore( GetType(), Level::eSpawnType_Breed) ) - { - std::shared_ptr pBabyWolf = std::shared_ptr( new Wolf(level) ); - - if(!getOwnerUUID().empty()) - { - // set the baby wolf to be tame, and assign the owner - pBabyWolf->tame(getOwnerUUID(),false,false); - } - return pBabyWolf; - } - else - { - return nullptr; - } +int Wolf::GetSynchedHealth() { + return getEntityData()->getInteger(DATA_HEALTH_ID); } -void Wolf::setIsInterested(bool value) -{ - //uint8_t current = entityData->getByte(DATA_INTERESTED_ID); +std::shared_ptr Wolf::getBreedOffspring( + std::shared_ptr target) { + // 4J - added limit to wolves that can be bred + if (level->canCreateMore(GetType(), Level::eSpawnType_Breed)) { + std::shared_ptr pBabyWolf = + std::shared_ptr(new Wolf(level)); - if (value) - { - entityData->set(DATA_INTERESTED_ID, (uint8_t) 1); - } - else - { - entityData->set(DATA_INTERESTED_ID, (uint8_t) 0); - } + if (!getOwnerUUID().empty()) { + // set the baby wolf to be tame, and assign the owner + pBabyWolf->tame(getOwnerUUID(), false, false); + } + return pBabyWolf; + } else { + return nullptr; + } } -bool Wolf::canMate(std::shared_ptr animal) -{ - if (animal == shared_from_this()) return false; - if (!isTame()) return false; - std::shared_ptr partner = std::dynamic_pointer_cast(animal); - if (partner == NULL) return false; - if (!partner->isTame()) return false; - if (partner->isSitting()) return false; +void Wolf::setIsInterested(bool value) { + // uint8_t current = entityData->getByte(DATA_INTERESTED_ID); - return isInLove() && partner->isInLove(); + if (value) { + entityData->set(DATA_INTERESTED_ID, (uint8_t)1); + } else { + entityData->set(DATA_INTERESTED_ID, (uint8_t)0); + } } -bool Wolf::isInterested() -{ - return entityData->getByte(DATA_INTERESTED_ID) == 1; +bool Wolf::canMate(std::shared_ptr animal) { + if (animal == shared_from_this()) return false; + if (!isTame()) return false; + std::shared_ptr partner = std::dynamic_pointer_cast(animal); + if (partner == NULL) return false; + if (!partner->isTame()) return false; + if (partner->isSitting()) return false; + + return isInLove() && partner->isInLove(); +} + +bool Wolf::isInterested() { + return entityData->getByte(DATA_INTERESTED_ID) == 1; } diff --git a/Minecraft.World/Entities/Mobs/Wolf.h b/Minecraft.World/Entities/Mobs/Wolf.h index b6b3e5528..8e7deb217 100644 --- a/Minecraft.World/Entities/Mobs/Wolf.h +++ b/Minecraft.World/Entities/Mobs/Wolf.h @@ -1,86 +1,86 @@ #pragma once - - #include "../TamableAnimal.h" class DamageSource; -class Wolf : public TamableAnimal -{ +class Wolf : public TamableAnimal { public: - eINSTANCEOF GetType() { return eTYPE_WOLF; } - static Entity *create(Level *level) { return new Wolf(level); } + eINSTANCEOF GetType() { return eTYPE_WOLF; } + static Entity* create(Level* level) { return new Wolf(level); } + private: - // synch health in a separate field to show tame wolves' health + // synch health in a separate field to show tame wolves' health static const int DATA_HEALTH_ID = 18; - static const int DATA_INTERESTED_ID = 19; - static const int DATA_COLLAR_COLOR = 20; + static const int DATA_INTERESTED_ID = 19; + static const int DATA_COLLAR_COLOR = 20; static const int START_HEALTH = 8; static const int MAX_HEALTH = 20; static const int TAME_HEALTH = 20; - float interestedAngle, interestedAngleO; - bool m_isWet, isShaking; - float shakeAnim, shakeAnimO; + float interestedAngle, interestedAngleO; + bool m_isWet, isShaking; + float shakeAnim, shakeAnimO; public: - Wolf(Level *level); - virtual bool useNewAi(); - virtual void setTarget(std::shared_ptr target); + Wolf(Level* level); + virtual bool useNewAi(); + virtual void setTarget(std::shared_ptr target); protected: - virtual void serverAiMobStep(); + virtual void serverAiMobStep(); public: - virtual int getMaxHealth(); + virtual int getMaxHealth(); protected: - virtual void defineSynchedData(); - virtual bool makeStepSound(); + virtual void defineSynchedData(); + virtual bool makeStepSound(); public: - virtual int getTexture(); // 4J - changed from std::wstring to ing - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual int getTexture(); // 4J - changed from std::wstring to ing + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); protected: - virtual bool removeWhenFarAway(); - virtual int getAmbientSound(); - virtual int getHurtSound(); - virtual int getDeathSound(); - virtual float getSoundVolume(); - virtual int getDeathLoot(); + virtual bool removeWhenFarAway(); + virtual int getAmbientSound(); + virtual int getHurtSound(); + virtual int getDeathSound(); + virtual float getSoundVolume(); + virtual int getDeathLoot(); public: - virtual void aiStep(); - virtual void tick(); - bool isWet(); - float getWetShade(float a); - float getBodyRollAngle(float a, float offset); - float getHeadRollAngle(float a); - float getHeadHeight(); - int getMaxHeadXRot(); - virtual bool hurt(DamageSource *source, int dmg); - virtual bool doHurtTarget(std::shared_ptr target); - virtual bool interact(std::shared_ptr player); - virtual void handleEntityEvent(uint8_t id); - float getTailAngle(); - virtual bool isFood(std::shared_ptr item); - virtual int getMaxSpawnClusterSize(); - bool isAngry(); - void setAngry(bool value); - int getCollarColor(); - void setCollarColor(int color); - void tame(const std::wstring &wsOwnerUUID, bool bDisplayTamingParticles, bool bSetSitting); + virtual void aiStep(); + virtual void tick(); + bool isWet(); + float getWetShade(float a); + float getBodyRollAngle(float a, float offset); + float getHeadRollAngle(float a); + float getHeadHeight(); + int getMaxHeadXRot(); + virtual bool hurt(DamageSource* source, int dmg); + virtual bool doHurtTarget(std::shared_ptr target); + virtual bool interact(std::shared_ptr player); + virtual void handleEntityEvent(uint8_t id); + float getTailAngle(); + virtual bool isFood(std::shared_ptr item); + virtual int getMaxSpawnClusterSize(); + bool isAngry(); + void setAngry(bool value); + int getCollarColor(); + void setCollarColor(int color); + void tame(const std::wstring& wsOwnerUUID, bool bDisplayTamingParticles, + bool bSetSitting); - // For tooltips - int GetSynchedHealth(); + // For tooltips + int GetSynchedHealth(); protected: - virtual std::shared_ptr getBreedOffspring(std::shared_ptr target); + virtual std::shared_ptr getBreedOffspring( + std::shared_ptr target); public: - virtual void setIsInterested(bool isInterested); - virtual bool canMate(std::shared_ptr animal); - bool isInterested(); + virtual void setIsInterested(bool isInterested); + virtual bool canMate(std::shared_ptr animal); + bool isInterested(); }; diff --git a/Minecraft.World/Entities/Mobs/Zombie.cpp b/Minecraft.World/Entities/Mobs/Zombie.cpp index 7d02f5505..ca2a612eb 100644 --- a/Minecraft.World/Entities/Mobs/Zombie.cpp +++ b/Minecraft.World/Entities/Mobs/Zombie.cpp @@ -15,236 +15,200 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "../../Util/SoundTypes.h" -Zombie::Zombie(Level *level) : Monster( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Zombie::Zombie(Level* level) : Monster(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - this->textureIdx = TN_MOB_ZOMBIE; // 4J was L"/mob/zombie.png"; - runSpeed = 0.23f; - attackDamage = 4; + this->textureIdx = TN_MOB_ZOMBIE; // 4J was L"/mob/zombie.png"; + runSpeed = 0.23f; + attackDamage = 4; - villagerConversionTime = 0; - - registeredBBWidth = -1; - registeredBBHeight = 0; + villagerConversionTime = 0; - setSize(bbWidth, bbHeight); + registeredBBWidth = -1; + registeredBBHeight = 0; - getNavigation()->setCanOpenDoors(true); - goalSelector.addGoal(0, new FloatGoal(this)); - goalSelector.addGoal(1, new BreakDoorGoal(this)); - goalSelector.addGoal(2, new MeleeAttackGoal(this, eTYPE_PLAYER, runSpeed, false)); - goalSelector.addGoal(3, new MeleeAttackGoal(this, eTYPE_VILLAGER, runSpeed, true)); - goalSelector.addGoal(4, new MoveTowardsRestrictionGoal(this, runSpeed)); - goalSelector.addGoal(5, new MoveThroughVillageGoal(this, runSpeed, false)); - goalSelector.addGoal(6, new RandomStrollGoal(this, runSpeed)); - goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 8)); - goalSelector.addGoal(7, new RandomLookAroundGoal(this)); + setSize(bbWidth, bbHeight); - targetSelector.addGoal(1, new HurtByTargetGoal(this, false)); - targetSelector.addGoal(2, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); - targetSelector.addGoal(2, new NearestAttackableTargetGoal(this, typeid(Villager), 16, 0, false)); + getNavigation()->setCanOpenDoors(true); + goalSelector.addGoal(0, new FloatGoal(this)); + goalSelector.addGoal(1, new BreakDoorGoal(this)); + goalSelector.addGoal( + 2, new MeleeAttackGoal(this, eTYPE_PLAYER, runSpeed, false)); + goalSelector.addGoal( + 3, new MeleeAttackGoal(this, eTYPE_VILLAGER, runSpeed, true)); + goalSelector.addGoal(4, new MoveTowardsRestrictionGoal(this, runSpeed)); + goalSelector.addGoal(5, new MoveThroughVillageGoal(this, runSpeed, false)); + goalSelector.addGoal(6, new RandomStrollGoal(this, runSpeed)); + goalSelector.addGoal(7, new LookAtPlayerGoal(this, typeid(Player), 8)); + goalSelector.addGoal(7, new RandomLookAroundGoal(this)); + + targetSelector.addGoal(1, new HurtByTargetGoal(this, false)); + targetSelector.addGoal( + 2, new NearestAttackableTargetGoal(this, typeid(Player), 16, 0, true)); + targetSelector.addGoal(2, new NearestAttackableTargetGoal( + this, typeid(Villager), 16, 0, false)); } -void Zombie::defineSynchedData() -{ - Monster::defineSynchedData(); +void Zombie::defineSynchedData() { + Monster::defineSynchedData(); - getEntityData()->define(DATA_BABY_ID, (uint8_t) 0); - getEntityData()->define(DATA_VILLAGER_ID, (uint8_t) 0); - getEntityData()->define(DATA_CONVERTING_ID, (uint8_t) 0); + getEntityData()->define(DATA_BABY_ID, (uint8_t)0); + getEntityData()->define(DATA_VILLAGER_ID, (uint8_t)0); + getEntityData()->define(DATA_CONVERTING_ID, (uint8_t)0); } -float Zombie::getWalkingSpeedModifier() -{ +float Zombie::getWalkingSpeedModifier() { return Monster::getWalkingSpeedModifier() * (isBaby() ? 1.5f : 1.0f); } -int Zombie::getTexture() -{ - return isVillager() ? TN_MOB_ZOMBIE_VILLAGER : TN_MOB_ZOMBIE; +int Zombie::getTexture() { + return isVillager() ? TN_MOB_ZOMBIE_VILLAGER : TN_MOB_ZOMBIE; } -int Zombie::getMaxHealth() -{ - return 20; +int Zombie::getMaxHealth() { return 20; } + +int Zombie::getArmorValue() { return 2; } + +bool Zombie::useNewAi() { return true; } + +bool Zombie::isBaby() { + return getEntityData()->getByte(DATA_BABY_ID) == (uint8_t)1; } -int Zombie::getArmorValue() -{ - return 2; +void Zombie::setBaby(bool baby) { + getEntityData()->set(DATA_BABY_ID, (uint8_t)1); + updateSize(isBaby()); } -bool Zombie::useNewAi() -{ - return true; +bool Zombie::isVillager() { + return getEntityData()->getByte(DATA_VILLAGER_ID) == (uint8_t)1; } -bool Zombie::isBaby() -{ - return getEntityData()->getByte(DATA_BABY_ID) == (uint8_t) 1; +void Zombie::setVillager(bool villager) { + getEntityData()->set(DATA_VILLAGER_ID, (uint8_t)(villager ? 1 : 0)); } -void Zombie::setBaby(bool baby) -{ - getEntityData()->set(DATA_BABY_ID, (uint8_t) 1); - updateSize(isBaby()); +void Zombie::aiStep() { + if (level->isClientSide) { + updateSize(isBaby()); + } else if (level->isDay() && !level->isClientSide && !isBaby()) { + float br = getBrightness(1); + if (br > 0.5f && random->nextFloat() * 30 < (br - 0.4f) * 2 && + level->canSeeSky(Mth::floor(x), Mth::floor(y), Mth::floor(z))) { + setOnFire(8); + } + } + Monster::aiStep(); } -bool Zombie::isVillager() -{ - return getEntityData()->getByte(DATA_VILLAGER_ID) == (uint8_t) 1; +void Zombie::tick() { + if (!level->isClientSide && isConverting()) { + int amount = getConversionProgress(); + + villagerConversionTime -= amount; + + if (villagerConversionTime <= 0) { + finishConversion(); + } + } + + Monster::tick(); } -void Zombie::setVillager(bool villager) -{ - getEntityData()->set(DATA_VILLAGER_ID, (uint8_t) (villager ? 1 : 0)); +int Zombie::getAmbientSound() { return eSoundType_MOB_ZOMBIE_AMBIENT; } + +int Zombie::getHurtSound() { return eSoundType_MOB_ZOMBIE_HURT; } + +int Zombie::getDeathSound() { return eSoundType_MOB_ZOMBIE_DEATH; } + +int Zombie::getDeathLoot() { return Item::rotten_flesh_Id; } + +MobType Zombie::getMobType() { return UNDEAD; } + +void Zombie::dropRareDeathLoot(int rareLootLevel) { + switch (random->nextInt(3)) { + /* case 0: + spawnAtLocation(Item::sword_iron_Id, 1); + break; + case 1: + spawnAtLocation(Item::helmet_iron_Id, 1); + break; + case 2: + spawnAtLocation(Item::ironIngot_Id, 1); + break; + case 3: + spawnAtLocation(Item::shovel_iron_Id, 1); + break;*/ + case 0: + spawnAtLocation(Item::ironIngot_Id, 1); + break; + case 1: + spawnAtLocation(Item::carrots_Id, 1); + break; + case 2: + spawnAtLocation(Item::potato_Id, 1); + break; + } } -void Zombie::aiStep() -{ - if(level->isClientSide) - { - updateSize(isBaby()); - } - else if (level->isDay() && !level->isClientSide && !isBaby()) - { - float br = getBrightness(1); - if (br > 0.5f && random->nextFloat() * 30 < (br - 0.4f) * 2 && level->canSeeSky( Mth::floor(x), Mth::floor(y), Mth::floor(z))) - { - setOnFire(8); - } - } - Monster::aiStep(); +void Zombie::addAdditonalSaveData(CompoundTag* tag) { + Monster::addAdditonalSaveData(tag); + + if (isBaby()) tag->putBoolean(L"IsBaby", true); + if (isVillager()) tag->putBoolean(L"IsVillager", true); + tag->putInt(L"ConversionTime", + isConverting() ? villagerConversionTime : -1); } -void Zombie::tick() -{ - if (!level->isClientSide && isConverting()) - { - int amount = getConversionProgress(); +void Zombie::readAdditionalSaveData(CompoundTag* tag) { + Monster::readAdditionalSaveData(tag); - villagerConversionTime -= amount; - - if (villagerConversionTime <= 0) - { - finishConversion(); - } - } - - Monster::tick(); + if (tag->getBoolean(L"IsBaby")) setBaby(true); + if (tag->getBoolean(L"IsVillager")) setVillager(true); + if (tag->contains(L"ConversionTime") && tag->getInt(L"ConversionTime") > -1) + startConverting(tag->getInt(L"ConversionTime")); } -int Zombie::getAmbientSound() -{ - return eSoundType_MOB_ZOMBIE_AMBIENT; +void Zombie::killed(std::shared_ptr mob) { + Monster::killed(mob); + + if (level->difficulty >= Difficulty::NORMAL && + ((mob->GetType() & eTYPE_VILLAGER) == eTYPE_VILLAGER)) { + if (!level->canCreateMore(GetType(), Level::eSpawnType_Egg)) return; + if (level->difficulty == Difficulty::NORMAL && random->nextBoolean()) + return; + + std::shared_ptr zombie = + std::shared_ptr(new Zombie(level)); + zombie->copyPosition(mob); + level->removeEntity(mob); + zombie->finalizeMobSpawn(); + zombie->setVillager(true); + if (mob->isBaby()) zombie->setBaby(true); + level->addEntity(zombie); + + level->levelEvent(nullptr, LevelEvent::SOUND_ZOMBIE_INFECTED, (int)x, + (int)y, (int)z, 0); + } } -int Zombie::getHurtSound() -{ - return eSoundType_MOB_ZOMBIE_HURT; -} - -int Zombie::getDeathSound() -{ - return eSoundType_MOB_ZOMBIE_DEATH; -} - -int Zombie::getDeathLoot() -{ - return Item::rotten_flesh_Id; -} - -MobType Zombie::getMobType() -{ - return UNDEAD; -} - -void Zombie::dropRareDeathLoot(int rareLootLevel) -{ - switch (random->nextInt(3)) - { -/* case 0: - spawnAtLocation(Item::sword_iron_Id, 1); - break; - case 1: - spawnAtLocation(Item::helmet_iron_Id, 1); - break; - case 2: - spawnAtLocation(Item::ironIngot_Id, 1); - break; - case 3: - spawnAtLocation(Item::shovel_iron_Id, 1); - break;*/ - case 0: - spawnAtLocation(Item::ironIngot_Id, 1); - break; - case 1: - spawnAtLocation(Item::carrots_Id, 1); - break; - case 2: - spawnAtLocation(Item::potato_Id, 1); - break; - } -} - -void Zombie::addAdditonalSaveData(CompoundTag *tag) -{ - Monster::addAdditonalSaveData(tag); - - if (isBaby()) tag->putBoolean(L"IsBaby", true); - if (isVillager()) tag->putBoolean(L"IsVillager", true); - tag->putInt(L"ConversionTime", isConverting() ? villagerConversionTime : -1); -} - -void Zombie::readAdditionalSaveData(CompoundTag *tag) -{ - Monster::readAdditionalSaveData(tag); - - if (tag->getBoolean(L"IsBaby")) setBaby(true); - if (tag->getBoolean(L"IsVillager")) setVillager(true); - if (tag->contains(L"ConversionTime") && tag->getInt(L"ConversionTime") > -1) startConverting(tag->getInt(L"ConversionTime")); -} - -void Zombie::killed(std::shared_ptr mob) -{ - Monster::killed(mob); - - if (level->difficulty >= Difficulty::NORMAL && ((mob->GetType() & eTYPE_VILLAGER) == eTYPE_VILLAGER)) - { - if( !level->canCreateMore( GetType(), Level::eSpawnType_Egg) ) return; - if (level->difficulty == Difficulty::NORMAL && random->nextBoolean()) return; - - std::shared_ptr zombie = std::shared_ptr(new Zombie(level)); - zombie->copyPosition(mob); - level->removeEntity(mob); - zombie->finalizeMobSpawn(); - zombie->setVillager(true); - if (mob->isBaby()) zombie->setBaby(true); - level->addEntity(zombie); - - level->levelEvent(nullptr, LevelEvent::SOUND_ZOMBIE_INFECTED, (int) x, (int) y, (int) z, 0); - } -} - -void Zombie::finalizeMobSpawn() -{ - // 4J Stu - TODO TU15 +void Zombie::finalizeMobSpawn() { + // 4J Stu - TODO TU15 #if 0 canPickUpLoot = random->nextFloat() < CAN_PICK_UP_LOOT_CHANCES[level->difficulty]; #endif - if (level->random->nextFloat() < 0.05f) - { - setVillager(true); - } + if (level->random->nextFloat() < 0.05f) { + setVillager(true); + } - // 4J Stu - TODO TU15 + // 4J Stu - TODO TU15 #if 0 populateDefaultEquipmentSlots(); populateDefaultEquipmentEnchantments(); @@ -263,121 +227,122 @@ void Zombie::finalizeMobSpawn() #endif } -bool Zombie::interact(std::shared_ptr player) -{ - std::shared_ptr item = player->getSelectedItem(); +bool Zombie::interact(std::shared_ptr player) { + std::shared_ptr item = player->getSelectedItem(); - if (item != NULL && item->getItem() == Item::apple_gold && item->getAuxValue() == 0 && isVillager() && hasEffect(MobEffect::weakness)) - { - if (!player->abilities.instabuild) item->count--; - if (item->count <= 0) - { - player->inventory->setItem(player->inventory->selected, nullptr); - } + if (item != NULL && item->getItem() == Item::apple_gold && + item->getAuxValue() == 0 && isVillager() && + hasEffect(MobEffect::weakness)) { + if (!player->abilities.instabuild) item->count--; + if (item->count <= 0) { + player->inventory->setItem(player->inventory->selected, nullptr); + } - if (!level->isClientSide) - { - startConverting(random->nextInt(VILLAGER_CONVERSION_WAIT_MAX - VILLAGER_CONVERSION_WAIT_MIN + 1) + VILLAGER_CONVERSION_WAIT_MIN); + if (!level->isClientSide) { + startConverting(random->nextInt(VILLAGER_CONVERSION_WAIT_MAX - + VILLAGER_CONVERSION_WAIT_MIN + 1) + + VILLAGER_CONVERSION_WAIT_MIN); - // 4J-JEV, award achievement here, as it is impractical to award when the zombie is actually cured. - player->awardStat(GenericStats::zombieDoctor(),GenericStats::param_zombieDoctor()); - } + // 4J-JEV, award achievement here, as it is impractical to award + // when the zombie is actually cured. + player->awardStat(GenericStats::zombieDoctor(), + GenericStats::param_zombieDoctor()); + } - return true; - } + return true; + } - return false; + return false; } -void Zombie::startConverting(int time) -{ - villagerConversionTime = time; - getEntityData()->set(DATA_CONVERTING_ID, (uint8_t) 1); +void Zombie::startConverting(int time) { + villagerConversionTime = time; + getEntityData()->set(DATA_CONVERTING_ID, (uint8_t)1); - removeEffect(MobEffect::weakness->id); - addEffect(new MobEffectInstance(MobEffect::damageBoost->id, time, std::min(level->difficulty - 1, 0))); + removeEffect(MobEffect::weakness->id); + addEffect(new MobEffectInstance(MobEffect::damageBoost->id, time, + std::min(level->difficulty - 1, 0))); - level->broadcastEntityEvent(shared_from_this(), EntityEvent::ZOMBIE_CONVERTING); + level->broadcastEntityEvent(shared_from_this(), + EntityEvent::ZOMBIE_CONVERTING); } -void Zombie::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::ZOMBIE_CONVERTING) - { - level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_MOB_ZOMBIE_REMEDY, 1 + random->nextFloat(), random->nextFloat() * 0.7f + 0.3f);//, false); - } - else - { - Monster::handleEntityEvent(id); - } +void Zombie::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::ZOMBIE_CONVERTING) { + level->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, + eSoundType_MOB_ZOMBIE_REMEDY, + 1 + random->nextFloat(), + random->nextFloat() * 0.7f + 0.3f); //, false); + } else { + Monster::handleEntityEvent(id); + } } -bool Zombie::isConverting() -{ - return getEntityData()->getByte(DATA_CONVERTING_ID) == (uint8_t) 1; +bool Zombie::isConverting() { + return getEntityData()->getByte(DATA_CONVERTING_ID) == (uint8_t)1; } -void Zombie::finishConversion() -{ - std::shared_ptr villager = std::shared_ptr(new Villager(level)); - villager->copyPosition(shared_from_this()); - villager->finalizeMobSpawn(); - villager->setRewardPlayersInVillage(); - if (isBaby()) villager->setAge(-20 * 60 * 20); - level->removeEntity(shared_from_this()); - level->addEntity(villager); +void Zombie::finishConversion() { + std::shared_ptr villager = + std::shared_ptr(new Villager(level)); + villager->copyPosition(shared_from_this()); + villager->finalizeMobSpawn(); + villager->setRewardPlayersInVillage(); + if (isBaby()) villager->setAge(-20 * 60 * 20); + level->removeEntity(shared_from_this()); + level->addEntity(villager); - villager->addEffect(new MobEffectInstance(MobEffect::confusion->id, SharedConstants::TICKS_PER_SECOND * 10, 0)); - level->levelEvent(nullptr, LevelEvent::SOUND_ZOMBIE_CONVERTED, (int) x, (int) y, (int) z, 0); + villager->addEffect(new MobEffectInstance( + MobEffect::confusion->id, SharedConstants::TICKS_PER_SECOND * 10, 0)); + level->levelEvent(nullptr, LevelEvent::SOUND_ZOMBIE_CONVERTED, (int)x, + (int)y, (int)z, 0); } -int Zombie::getConversionProgress() -{ - int amount = 1; +int Zombie::getConversionProgress() { + int amount = 1; - if (random->nextFloat() < 0.01f) - { - int specialBlocksCount = 0; + if (random->nextFloat() < 0.01f) { + int specialBlocksCount = 0; - for (int xx = (int) x - SPECIAL_BLOCK_RADIUS; xx < (int) x + SPECIAL_BLOCK_RADIUS && specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; xx++) - { - for (int yy = (int) y - SPECIAL_BLOCK_RADIUS; yy < (int) y + SPECIAL_BLOCK_RADIUS && specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; yy++) - { - for (int zz = (int) z - SPECIAL_BLOCK_RADIUS; zz < (int) z + SPECIAL_BLOCK_RADIUS && specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; zz++) - { - int tile = level->getTile(xx, yy, zz); + for (int xx = (int)x - SPECIAL_BLOCK_RADIUS; + xx < (int)x + SPECIAL_BLOCK_RADIUS && + specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; + xx++) { + for (int yy = (int)y - SPECIAL_BLOCK_RADIUS; + yy < (int)y + SPECIAL_BLOCK_RADIUS && + specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; + yy++) { + for (int zz = (int)z - SPECIAL_BLOCK_RADIUS; + zz < (int)z + SPECIAL_BLOCK_RADIUS && + specialBlocksCount < MAX_SPECIAL_BLOCKS_COUNT; + zz++) { + int tile = level->getTile(xx, yy, zz); - if (tile == Tile::ironFence_Id || tile == Tile::bed_Id) - { - if (random->nextFloat() < 0.3f) amount++; - specialBlocksCount++; - } - } - } - } - } - return amount; + if (tile == Tile::ironFence_Id || tile == Tile::bed_Id) { + if (random->nextFloat() < 0.3f) amount++; + specialBlocksCount++; + } + } + } + } + } + return amount; } -void Zombie::updateSize(bool isBaby) -{ - internalSetSize(isBaby ? .5f : 1.0f); +void Zombie::updateSize(bool isBaby) { internalSetSize(isBaby ? .5f : 1.0f); } + +void Zombie::setSize(float w, float h) { + bool inited = registeredBBWidth > 0; + + registeredBBWidth = w; + registeredBBHeight = h; + + if (!inited) { + internalSetSize(1.0f); + } } -void Zombie::setSize(float w, float h) -{ - bool inited = registeredBBWidth > 0; - - registeredBBWidth = w; - registeredBBHeight = h; - - if (!inited) - { - internalSetSize(1.0f); - } -} - -void Zombie::internalSetSize(float scale) -{ - PathfinderMob::setSize(registeredBBWidth * scale, registeredBBHeight * scale); +void Zombie::internalSetSize(float scale) { + PathfinderMob::setSize(registeredBBWidth * scale, + registeredBBHeight * scale); } diff --git a/Minecraft.World/Entities/Mobs/Zombie.h b/Minecraft.World/Entities/Mobs/Zombie.h index be6de5169..f84221528 100644 --- a/Minecraft.World/Entities/Mobs/Zombie.h +++ b/Minecraft.World/Entities/Mobs/Zombie.h @@ -1,88 +1,88 @@ #pragma once - #include "../Monster.h" #include "../../Util/SharedConstants.h" -class Zombie : public Monster -{ +class Zombie : public Monster { private: - static const int VILLAGER_CONVERSION_WAIT_MIN = SharedConstants::TICKS_PER_SECOND * 60 * 3; - static const int VILLAGER_CONVERSION_WAIT_MAX = SharedConstants::TICKS_PER_SECOND * 60 * 5; + static const int VILLAGER_CONVERSION_WAIT_MIN = + SharedConstants::TICKS_PER_SECOND * 60 * 3; + static const int VILLAGER_CONVERSION_WAIT_MAX = + SharedConstants::TICKS_PER_SECOND * 60 * 5; - static const int DATA_BABY_ID = 12; - static const int DATA_VILLAGER_ID = 13; - static const int DATA_CONVERTING_ID = 14; + static const int DATA_BABY_ID = 12; + static const int DATA_VILLAGER_ID = 13; + static const int DATA_CONVERTING_ID = 14; - int villagerConversionTime; + int villagerConversionTime; - float registeredBBWidth; - float registeredBBHeight; + float registeredBBWidth; + float registeredBBHeight; public: - static const int MAX_SPECIAL_BLOCKS_COUNT = 14; - static const int SPECIAL_BLOCK_RADIUS = 4; + static const int MAX_SPECIAL_BLOCKS_COUNT = 14; + static const int SPECIAL_BLOCK_RADIUS = 4; public: - eINSTANCEOF GetType() { return eTYPE_ZOMBIE; } - static Entity *create(Level *level) { return new Zombie(level); } + eINSTANCEOF GetType() { return eTYPE_ZOMBIE; } + static Entity* create(Level* level) { return new Zombie(level); } - Zombie(Level *level); - virtual float getWalkingSpeedModifier(); + Zombie(Level* level); + virtual float getWalkingSpeedModifier(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual int getTexture(); - virtual int getMaxHealth(); - int getArmorValue(); + virtual int getTexture(); + virtual int getMaxHealth(); + int getArmorValue(); protected: - virtual bool useNewAi(); + virtual bool useNewAi(); public: - bool isBaby(); - void setBaby(bool baby); - bool isVillager(); - void setVillager(bool villager); + bool isBaby(); + void setBaby(bool baby); + bool isVillager(); + void setVillager(bool villager); virtual void aiStep(); virtual void tick(); - + protected: - virtual int getAmbientSound(); + virtual int getAmbientSound(); virtual int getHurtSound(); virtual int getDeathSound(); virtual int getDeathLoot(); public: - MobType getMobType(); + MobType getMobType(); protected: - virtual void dropRareDeathLoot(int rareLootLevel); + virtual void dropRareDeathLoot(int rareLootLevel); public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - void killed(std::shared_ptr mob); - virtual void finalizeMobSpawn(); - bool interact(std::shared_ptr player); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + void killed(std::shared_ptr mob); + virtual void finalizeMobSpawn(); + bool interact(std::shared_ptr player); protected: - void startConverting(int time); + void startConverting(int time); public: - void handleEntityEvent(uint8_t id); - bool isConverting(); + void handleEntityEvent(uint8_t id); + bool isConverting(); protected: - void finishConversion(); - int getConversionProgress(); + void finishConversion(); + int getConversionProgress(); public: - virtual void updateSize(bool isBaby); + virtual void updateSize(bool isBaby); protected: - virtual void setSize(float w, float h); - void internalSetSize(float scale); + virtual void setSize(float w, float h); + void internalSetSize(float scale); }; diff --git a/Minecraft.World/Entities/Monster.cpp b/Minecraft.World/Entities/Monster.cpp index b631fe036..6a8616c0c 100644 --- a/Minecraft.World/Entities/Monster.cpp +++ b/Minecraft.World/Entities/Monster.cpp @@ -9,66 +9,55 @@ #include "Monster.h" #include "../../Minecraft.Client/Minecraft.h" +void Monster::_init() { attackDamage = 2; } +Monster::Monster(Level* level) : PathfinderMob(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called -void Monster::_init() -{ - attackDamage = 2; -} - -Monster::Monster(Level *level) : PathfinderMob( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - - // 4J Stu - Only the most derived classes should call this - //this->defineSynchedData(); + // 4J Stu - Only the most derived classes should call this + // this->defineSynchedData(); _init(); - xpReward = Enemy::XP_REWARD_MEDIUM; + xpReward = Enemy::XP_REWARD_MEDIUM; } -void Monster::aiStep() -{ +void Monster::aiStep() { float br = getBrightness(1); - if (br > 0.5f) - { + if (br > 0.5f) { noActionTime += 2; } PathfinderMob::aiStep(); } -void Monster::tick() -{ +void Monster::tick() { PathfinderMob::tick(); - if (!level->isClientSide && (level->difficulty == Difficulty::PEACEFUL || Minecraft::GetInstance()->isTutorial() ) ) remove(); + if (!level->isClientSide && (level->difficulty == Difficulty::PEACEFUL || + Minecraft::GetInstance()->isTutorial())) + remove(); } -std::shared_ptr Monster::findAttackTarget() -{ +std::shared_ptr Monster::findAttackTarget() { #ifndef _FINAL_BUILD - if(app.GetMobsDontAttackEnabled()) - { - return std::shared_ptr(); - } + if (app.GetMobsDontAttackEnabled()) { + return std::shared_ptr(); + } #endif - std::shared_ptr player = level->getNearestAttackablePlayer(shared_from_this(), 16); - if (player != NULL && canSee(player) ) return player; + std::shared_ptr player = + level->getNearestAttackablePlayer(shared_from_this(), 16); + if (player != NULL && canSee(player)) return player; return std::shared_ptr(); } -bool Monster::hurt(DamageSource *source, int dmg) -{ - if (PathfinderMob::hurt(source, dmg)) - { - std::shared_ptr sourceEntity = source->getEntity(); +bool Monster::hurt(DamageSource* source, int dmg) { + if (PathfinderMob::hurt(source, dmg)) { + std::shared_ptr sourceEntity = source->getEntity(); if (rider.lock() == sourceEntity || riding == sourceEntity) return true; - if (sourceEntity != shared_from_this()) - { + if (sourceEntity != shared_from_this()) { this->attackTarget = sourceEntity; } return true; @@ -77,70 +66,64 @@ bool Monster::hurt(DamageSource *source, int dmg) } /** -* Performs hurt action, returns if successful -* -* @param target -* @return -*/ -bool Monster::doHurtTarget(std::shared_ptr target) -{ - int dmg = attackDamage; - if (hasEffect(MobEffect::damageBoost)) - { - dmg += (3 << getEffect(MobEffect::damageBoost)->getAmplifier()); - } - if (hasEffect(MobEffect::weakness)) - { - dmg -= (2 << getEffect(MobEffect::weakness)->getAmplifier()); - } + * Performs hurt action, returns if successful + * + * @param target + * @return + */ +bool Monster::doHurtTarget(std::shared_ptr target) { + int dmg = attackDamage; + if (hasEffect(MobEffect::damageBoost)) { + dmg += (3 << getEffect(MobEffect::damageBoost)->getAmplifier()); + } + if (hasEffect(MobEffect::weakness)) { + dmg -= (2 << getEffect(MobEffect::weakness)->getAmplifier()); + } - DamageSource *damageSource = DamageSource::mobAttack(std::dynamic_pointer_cast( shared_from_this() ) ); - bool didHurt = target->hurt(damageSource, dmg); - delete damageSource; + DamageSource* damageSource = DamageSource::mobAttack( + std::dynamic_pointer_cast(shared_from_this())); + bool didHurt = target->hurt(damageSource, dmg); + delete damageSource; - if (didHurt) - { - int fireAspect = EnchantmentHelper::getFireAspect(std::dynamic_pointer_cast(shared_from_this())); - if (fireAspect > 0) - { - target->setOnFire(fireAspect * 4); - } + if (didHurt) { + int fireAspect = EnchantmentHelper::getFireAspect( + std::dynamic_pointer_cast(shared_from_this())); + if (fireAspect > 0) { + target->setOnFire(fireAspect * 4); + } - std::shared_ptr mob = std::dynamic_pointer_cast(target); - if (mob != NULL) - { - ThornsEnchantment::doThornsAfterAttack(shared_from_this(), mob, random); - } - } + std::shared_ptr mob = std::dynamic_pointer_cast(target); + if (mob != NULL) { + ThornsEnchantment::doThornsAfterAttack(shared_from_this(), mob, + random); + } + } - return didHurt; + return didHurt; } -void Monster::checkHurtTarget(std::shared_ptr target, float distance) -{ - if (attackTime <= 0 && distance < 2.0f && target->bb->y1 > bb->y0 && target->bb->y0 < bb->y1) - { +void Monster::checkHurtTarget(std::shared_ptr target, float distance) { + if (attackTime <= 0 && distance < 2.0f && target->bb->y1 > bb->y0 && + target->bb->y0 < bb->y1) { attackTime = 20; doHurtTarget(target); } } -float Monster::getWalkTargetValue(int x, int y, int z) -{ +float Monster::getWalkTargetValue(int x, int y, int z) { return 0.5f - level->getBrightness(x, y, z); } -bool Monster::isDarkEnoughToSpawn() -{ +bool Monster::isDarkEnoughToSpawn() { int xt = Mth::floor(x); int yt = Mth::floor(bb->y0); int zt = Mth::floor(z); - if (level->getBrightness(LightLayer::Sky, xt, yt, zt) > random->nextInt(32)) return false; + if (level->getBrightness(LightLayer::Sky, xt, yt, zt) > random->nextInt(32)) + return false; int br = level->getRawBrightness(xt, yt, zt); - if (level->isThundering()) - { + if (level->isThundering()) { int tmp = level->skyDarken; level->skyDarken = 10; br = level->getRawBrightness(xt, yt, zt); @@ -150,9 +133,10 @@ bool Monster::isDarkEnoughToSpawn() return br <= random->nextInt(8); } -bool Monster::canSpawn() -{ - // 4J Stu - // Fix for #8265 - AI: Monsters will flash briefly on the screen around Monster Spawners when the game settings are set to Peaceful. - return isDarkEnoughToSpawn() && PathfinderMob::canSpawn() && level->difficulty > Difficulty::PEACEFUL; +bool Monster::canSpawn() { + // 4J Stu + // Fix for #8265 - AI: Monsters will flash briefly on the screen around + // Monster Spawners when the game settings are set to Peaceful. + return isDarkEnoughToSpawn() && PathfinderMob::canSpawn() && + level->difficulty > Difficulty::PEACEFUL; } diff --git a/Minecraft.World/Entities/Monster.h b/Minecraft.World/Entities/Monster.h index 7129913bf..3bfad2f45 100644 --- a/Minecraft.World/Entities/Monster.h +++ b/Minecraft.World/Entities/Monster.h @@ -1,6 +1,5 @@ #pragma once - #include "PathfinderMob.h" #include "Enemy.h" @@ -8,33 +7,33 @@ class Level; class CompoundTag; class DamageSource; -class Monster : public PathfinderMob, public Enemy -{ +class Monster : public PathfinderMob, public Enemy { public: - eINSTANCEOF GetType() { return eTYPE_MONSTER; } - static Entity *create(Level *level) { return NULL; } + eINSTANCEOF GetType() { return eTYPE_MONSTER; } + static Entity* create(Level* level) { return NULL; } protected: - int attackDamage; + int attackDamage; private: - void _init(); + void _init(); public: - Monster(Level *level); + Monster(Level* level); virtual void aiStep(); virtual void tick(); protected: - virtual std::shared_ptr findAttackTarget(); + virtual std::shared_ptr findAttackTarget(); public: - virtual bool hurt(DamageSource *source, int dmg); - virtual bool doHurtTarget(std::shared_ptr target); + virtual bool hurt(DamageSource* source, int dmg); + virtual bool doHurtTarget(std::shared_ptr target); protected: - virtual void checkHurtTarget(std::shared_ptr target, float distance); + virtual void checkHurtTarget(std::shared_ptr target, + float distance); public: virtual float getWalkTargetValue(int x, int y, int z); @@ -43,6 +42,5 @@ protected: virtual bool isDarkEnoughToSpawn(); public: - virtual bool canSpawn(); + virtual bool canSpawn(); }; - diff --git a/Minecraft.World/Entities/PathfinderMob.cpp b/Minecraft.World/Entities/PathfinderMob.cpp index a06337e6c..c52d1971e 100644 --- a/Minecraft.World/Entities/PathfinderMob.cpp +++ b/Minecraft.World/Entities/PathfinderMob.cpp @@ -6,259 +6,225 @@ #include "../Util/SharedConstants.h" #include "PathfinderMob.h" - - -PathfinderMob::PathfinderMob(Level *level) : Mob( level ) -{ - path = NULL; - attackTarget = nullptr; - holdGround = false; - fleeTime = 0; +PathfinderMob::PathfinderMob(Level* level) : Mob(level) { + path = NULL; + attackTarget = nullptr; + holdGround = false; + fleeTime = 0; } -bool PathfinderMob::shouldHoldGround() -{ - return false; +bool PathfinderMob::shouldHoldGround() { return false; } + +PathfinderMob::~PathfinderMob() { delete path; } + +void PathfinderMob::serverAiStep() { + if (fleeTime > 0) fleeTime--; + holdGround = shouldHoldGround(); + float maxDist = 16; + + if (attackTarget == NULL) { + attackTarget = findAttackTarget(); + if (attackTarget != NULL) { + setPath(level->findPath( + shared_from_this(), attackTarget, maxDist, true, false, false, + true)); // 4J - changed to setPath from path = + } + } else { + if (attackTarget->isAlive()) { + float d = attackTarget->distanceTo(shared_from_this()); + if (canSee(attackTarget)) { + checkHurtTarget(attackTarget, d); + } + } else { + attackTarget = nullptr; + } + } + + /* + * if (holdGround) { xxa = 0; yya = 0; jumping = false; return; } + */ + + // 4J - a few changes here so that we can call findRandomStrollLocation for + // a sub-set of things that it normally wouldn't be in the java game. This + // is so that we can have entities wander around a little, in order that we + // can measure how far they wander and then determine (if they wander too + // far) that they aren't enclosed. We don't want the extra network overhead + // of just having Everything wandering round all the time, so have put a + // management system in place that selects a subset of entities which have + // had their flag set through the considerForExtraWandering method so that + // these can keep doing random strolling. + + if (!holdGround && + (attackTarget != NULL && (path == NULL || random->nextInt(20) == 0))) { + setPath(level->findPath(shared_from_this(), attackTarget, maxDist, true, + false, false, + true)); // 4J - changed to setPath from path = + } else if (!holdGround && + ((path == NULL && (random->nextInt(180) == 0) || fleeTime > 0) || + (random->nextInt(120) == 0 || fleeTime > 0))) { + if (noActionTime < SharedConstants::TICKS_PER_SECOND * 5) { + findRandomStrollLocation(); + } + } else if (!holdGround && (path == NULL)) { + if ((noActionTime >= SharedConstants::TICKS_PER_SECOND * 5) && + isExtraWanderingEnabled()) { + // This entity wouldn't normally be randomly strolling. However, if + // our management system says that it should do, then do. Don't + // bother waiting for random conditions to be met before picking a + // direction though as the point here is to see if it is possible to + // stroll out of a given area and so waiting around is just wasting + // time + findRandomStrollLocation(getWanderingQuadrant()); + } + } + + // Consider this for extra strolling if it is protected against despawning. + // We aren't interested in ones that aren't protected as the whole point of + // this extra wandering is to potentially transition from protected to not + // protected. + considerForExtraWandering(isDespawnProtected()); + + int yFloor = Mth::floor(bb->y0 + 0.5f); + + bool inWater = isInWater(); + bool inLava = isInLava(); + xRot = 0; + if (path == NULL || random->nextInt(100) == 0) { + this->Mob::serverAiStep(); + setPath(NULL); // 4J - changed to setPath from path = + return; + } + + Vec3* target = path->currentPos(shared_from_this()); + double r = bbWidth * 2; + while (target != NULL && target->distanceToSqr(x, target->y, z) < r * r) { + path->next(); + if (path->isDone()) { + target = NULL; + setPath(NULL); // 4J - changed to setPath from path = + } else + target = path->currentPos(shared_from_this()); + } + + jumping = false; + if (target != NULL) { + double xd = target->x - x; + double zd = target->z - z; + double yd = target->y - yFloor; + float yRotD = (float)(atan2(zd, xd) * 180 / PI) - 90; + float rotDiff = Mth::wrapDegrees(yRotD - yRot); + yya = runSpeed; + if (rotDiff > MAX_TURN) { + rotDiff = MAX_TURN; + } + if (rotDiff < -MAX_TURN) { + rotDiff = -MAX_TURN; + } + yRot += rotDiff; + + if (holdGround) { + if (attackTarget != NULL) { + double xd2 = attackTarget->x - x; + double zd2 = attackTarget->z - z; + + float oldyRot = yRot; + yRot = (float)(atan2(zd2, xd2) * 180 / PI) - 90; + + rotDiff = ((oldyRot - yRot) + 90) * PI / 180; + xxa = -Mth::sin(rotDiff) * yya * 1.0f; + yya = Mth::cos(rotDiff) * yya * 1.0f; + } + } + if (yd > 0) { + jumping = true; + } + } + + if (attackTarget != NULL) { + lookAt(attackTarget, 30, 30); + } + + if (this->horizontalCollision && !isPathFinding()) jumping = true; + if (random->nextFloat() < 0.8f && (inWater || inLava)) jumping = true; } -PathfinderMob::~PathfinderMob() +void PathfinderMob::findRandomStrollLocation( + int quadrant /*=-1*/) // 4J - added quadrant { - delete path; + bool hasBest = false; + int xBest = -1; + int yBest = -1; + int zBest = -1; + float best = -99999; + for (int i = 0; i < 10; i++) { + // 4J - added quadrant parameter to this method so that the caller can + // request that only stroll locations in one quadrant be found. If -1 is + // passed then behaviour is the same as the java game + int xt, zt; + int yt = Mth::floor(y + random->nextInt(7) - 3); + if (quadrant == -1) { + xt = Mth::floor(x + random->nextInt(13) - 6); + zt = Mth::floor(z + random->nextInt(13) - 6); + } else { + int sx = ((quadrant & 1) ? -1 : 1); + int sz = ((quadrant & 2) ? -1 : 1); + xt = Mth::floor(x + random->nextInt(7) * sx); + zt = Mth::floor(z + random->nextInt(7) * sz); + } + float value = getWalkTargetValue(xt, yt, zt); + if (value > best) { + best = value; + xBest = xt; + yBest = yt; + zBest = zt; + hasBest = true; + } + } + if (hasBest) { + setPath(level->findPath(shared_from_this(), xBest, yBest, zBest, 10, + true, false, false, + true)); // 4J - changed to setPath from path = + } } -void PathfinderMob::serverAiStep() -{ - if (fleeTime > 0) fleeTime--; - holdGround = shouldHoldGround(); - float maxDist = 16; +void PathfinderMob::checkHurtTarget(std::shared_ptr target, float d) {} - if (attackTarget == NULL) - { - attackTarget = findAttackTarget(); - if (attackTarget != NULL) - { - setPath(level->findPath(shared_from_this(), attackTarget, maxDist, true, false, false, true)); // 4J - changed to setPath from path = - } - } - else - { - if (attackTarget->isAlive()) - { - float d = attackTarget->distanceTo(shared_from_this()); - if (canSee(attackTarget)) - { - checkHurtTarget(attackTarget, d); - } - } - else - { - attackTarget = nullptr; - } - } +float PathfinderMob::getWalkTargetValue(int x, int y, int z) { return 0; } - /* - * if (holdGround) { xxa = 0; yya = 0; jumping = false; return; } - */ - - // 4J - a few changes here so that we can call findRandomStrollLocation for a sub-set of things that it normally wouldn't be in the java game. - // This is so that we can have entities wander around a little, in order that we can measure how far they wander and then determine (if they wander too far) that - // they aren't enclosed. We don't want the extra network overhead of just having Everything wandering round all the time, so have put a management system in place - // that selects a subset of entities which have had their flag set through the considerForExtraWandering method so that these can keep doing random strolling. - - if (!holdGround && (attackTarget != NULL && (path == NULL || random->nextInt(20) == 0))) - { - setPath(level->findPath(shared_from_this(), attackTarget, maxDist, true, false, false, true));// 4J - changed to setPath from path = - } - else if (!holdGround && ((path == NULL && (random->nextInt(180) == 0) || fleeTime > 0) || (random->nextInt(120) == 0 || fleeTime > 0))) - { - if(noActionTime < SharedConstants::TICKS_PER_SECOND * 5) - { - findRandomStrollLocation(); - } - } - else if (!holdGround && (path == NULL ) ) - { - if( ( noActionTime >= SharedConstants::TICKS_PER_SECOND * 5 ) && isExtraWanderingEnabled() ) - { - // This entity wouldn't normally be randomly strolling. However, if our management system says that it should do, then do. Don't - // bother waiting for random conditions to be met before picking a direction though as the point here is to see if it is possible to - // stroll out of a given area and so waiting around is just wasting time - findRandomStrollLocation(getWanderingQuadrant()); - } - } - - // Consider this for extra strolling if it is protected against despawning. We aren't interested in ones that aren't protected as the whole point of this - // extra wandering is to potentially transition from protected to not protected. - considerForExtraWandering( isDespawnProtected() ); - - int yFloor = Mth::floor(bb->y0 + 0.5f); - - bool inWater = isInWater(); - bool inLava = isInLava(); - xRot = 0; - if (path == NULL || random->nextInt(100) == 0) - { - this->Mob::serverAiStep(); - setPath(NULL);// 4J - changed to setPath from path = - return; - } - - Vec3 *target = path->currentPos(shared_from_this()); - double r = bbWidth * 2; - while (target != NULL && target->distanceToSqr(x, target->y, z) < r * r) - { - path->next(); - if (path->isDone()) - { - target = NULL; - setPath(NULL); // 4J - changed to setPath from path = - } - else target = path->currentPos(shared_from_this()); - } - - jumping = false; - if (target != NULL) - { - double xd = target->x - x; - double zd = target->z - z; - double yd = target->y - yFloor; - float yRotD = (float) (atan2(zd, xd) * 180 / PI) - 90; - float rotDiff = Mth::wrapDegrees(yRotD - yRot); - yya = runSpeed; - if (rotDiff > MAX_TURN) - { - rotDiff = MAX_TURN; - } - if (rotDiff < -MAX_TURN) - { - rotDiff = -MAX_TURN; - } - yRot += rotDiff; - - if (holdGround) - { - if (attackTarget != NULL) - { - double xd2 = attackTarget->x - x; - double zd2 = attackTarget->z - z; - - float oldyRot = yRot; - yRot = (float) (atan2(zd2, xd2) * 180 / PI) - 90; - - rotDiff = ((oldyRot - yRot) + 90) * PI / 180; - xxa = -Mth::sin(rotDiff) * yya * 1.0f; - yya = Mth::cos(rotDiff) * yya * 1.0f; - } - } - if (yd > 0) - { - jumping = true; - } - } - - if (attackTarget != NULL) - { - lookAt(attackTarget, 30, 30); - } - - if (this->horizontalCollision && !isPathFinding()) jumping = true; - if (random->nextFloat() < 0.8f && (inWater || inLava)) jumping = true; +std::shared_ptr PathfinderMob::findAttackTarget() { + return std::shared_ptr(); } -void PathfinderMob::findRandomStrollLocation(int quadrant/*=-1*/) // 4J - added quadrant -{ - bool hasBest = false; - int xBest = -1; - int yBest = -1; - int zBest = -1; - float best = -99999; - for (int i = 0; i < 10; i++) - { - // 4J - added quadrant parameter to this method so that the caller can request that only stroll locations in one quadrant be found. If -1 is passed then - // behaviour is the same as the java game - int xt, zt; - int yt = Mth::floor(y + random->nextInt(7) - 3); - if( quadrant == -1 ) - { - xt = Mth::floor(x + random->nextInt(13) - 6); - zt = Mth::floor(z + random->nextInt(13) - 6); - } - else - { - int sx = ( ( quadrant & 1 ) ? -1 : 1 ); - int sz = ( ( quadrant & 2 ) ? -1 : 1 ); - xt = Mth::floor(x + random->nextInt(7) * sx); - zt = Mth::floor(z + random->nextInt(7) * sz); - } - float value = getWalkTargetValue(xt, yt, zt); - if (value > best) - { - best = value; - xBest = xt; - yBest = yt; - zBest = zt; - hasBest = true; - } - } - if (hasBest) - { - setPath(level->findPath(shared_from_this(), xBest, yBest, zBest, 10, true, false, false, true)); // 4J - changed to setPath from path = - } +bool PathfinderMob::canSpawn() { + int xt = Mth::floor(x); + int yt = Mth::floor(bb->y0); + int zt = Mth::floor(z); + return this->Mob::canSpawn() && getWalkTargetValue(xt, yt, zt) >= 0; } -void PathfinderMob::checkHurtTarget(std::shared_ptr target, float d) -{ +bool PathfinderMob::isPathFinding() { return path != NULL; } + +void PathfinderMob::setPath(Path* path) { + delete this->path; + this->path = path; } -float PathfinderMob::getWalkTargetValue(int x, int y, int z) -{ - return 0; +std::shared_ptr PathfinderMob::getAttackTarget() { + return attackTarget; } -std::shared_ptr PathfinderMob::findAttackTarget() -{ - return std::shared_ptr(); +void PathfinderMob::setAttackTarget(std::shared_ptr attacker) { + attackTarget = attacker; } - -bool PathfinderMob::canSpawn() -{ - int xt = Mth::floor(x); - int yt = Mth::floor(bb->y0); - int zt = Mth::floor(z); - return this->Mob::canSpawn() && getWalkTargetValue(xt, yt, zt) >= 0; +float PathfinderMob::getWalkingSpeedModifier() { + if (useNewAi()) return 1.0f; + float speed = Mob::getWalkingSpeedModifier(); + if (fleeTime > 0) speed *= 2; + return speed; } -bool PathfinderMob::isPathFinding() -{ - return path != NULL; -} - -void PathfinderMob::setPath(Path *path) -{ - delete this->path; - this->path = path; -} - -std::shared_ptr PathfinderMob::getAttackTarget() -{ - return attackTarget; -} - -void PathfinderMob::setAttackTarget(std::shared_ptr attacker) -{ - attackTarget = attacker; -} - -float PathfinderMob::getWalkingSpeedModifier() -{ - if (useNewAi()) return 1.0f; - float speed = Mob::getWalkingSpeedModifier(); - if (fleeTime > 0) speed *= 2; - return speed; -} - -bool PathfinderMob::couldWander() -{ - return (noActionTime < SharedConstants::TICKS_PER_SECOND * 5) || ( isExtraWanderingEnabled() ); +bool PathfinderMob::couldWander() { + return (noActionTime < SharedConstants::TICKS_PER_SECOND * 5) || + (isExtraWanderingEnabled()); } \ No newline at end of file diff --git a/Minecraft.World/Entities/PathfinderMob.h b/Minecraft.World/Entities/PathfinderMob.h index df759f485..610031481 100644 --- a/Minecraft.World/Entities/PathfinderMob.h +++ b/Minecraft.World/Entities/PathfinderMob.h @@ -5,45 +5,44 @@ class Level; class Path; -class PathfinderMob : public Mob -{ +class PathfinderMob : public Mob { private: - static const int MAX_TURN = 30; + static const int MAX_TURN = 30; public: - PathfinderMob(Level *level); - virtual ~PathfinderMob(); + PathfinderMob(Level* level); + virtual ~PathfinderMob(); private: - Path *path; + Path* path; protected: - std::shared_ptr attackTarget; - bool holdGround; - int fleeTime; + std::shared_ptr attackTarget; + bool holdGround; + int fleeTime; - virtual bool shouldHoldGround(); - virtual void serverAiStep(); - virtual void findRandomStrollLocation(int quadrant = -1); - virtual void checkHurtTarget(std::shared_ptr target, float d); + virtual bool shouldHoldGround(); + virtual void serverAiStep(); + virtual void findRandomStrollLocation(int quadrant = -1); + virtual void checkHurtTarget(std::shared_ptr target, float d); public: - virtual float getWalkTargetValue(int x, int y, int z); + virtual float getWalkTargetValue(int x, int y, int z); protected: - virtual std::shared_ptr findAttackTarget(); + virtual std::shared_ptr findAttackTarget(); public: - virtual bool canSpawn(); - bool isPathFinding(); - void setPath(Path *path); - std::shared_ptr getAttackTarget(); - void setAttackTarget(std::shared_ptr attacker); + virtual bool canSpawn(); + bool isPathFinding(); + void setPath(Path* path); + std::shared_ptr getAttackTarget(); + void setAttackTarget(std::shared_ptr attacker); protected: - float getWalkingSpeedModifier(); + float getWalkingSpeedModifier(); - // 4J added + // 4J added public: - virtual bool couldWander(); + virtual bool couldWander(); }; diff --git a/Minecraft.World/Entities/SyncedEntityData.cpp b/Minecraft.World/Entities/SyncedEntityData.cpp index f14421c2a..c985da44f 100644 --- a/Minecraft.World/Entities/SyncedEntityData.cpp +++ b/Minecraft.World/Entities/SyncedEntityData.cpp @@ -7,69 +7,67 @@ #include "../Headers/net.minecraft.world.item.h" #include "SyncedEntityData.h" -SynchedEntityData::SynchedEntityData() -{ - m_isDirty = false; - m_isEmpty = true; +SynchedEntityData::SynchedEntityData() { + m_isDirty = false; + m_isEmpty = true; } -void SynchedEntityData::define(int id, int value) -{ - MemSect(17); - checkId(id); - int type = TYPE_INT; - std::shared_ptr dataItem = std::shared_ptr( new DataItem(type, id, value) ); - itemsById[id] = dataItem; - MemSect(0); - m_isEmpty = false; +void SynchedEntityData::define(int id, int value) { + MemSect(17); + checkId(id); + int type = TYPE_INT; + std::shared_ptr dataItem = + std::shared_ptr(new DataItem(type, id, value)); + itemsById[id] = dataItem; + MemSect(0); + m_isEmpty = false; } -void SynchedEntityData::define(int id, uint8_t value) -{ - MemSect(17); - checkId(id); - int type = TYPE_BYTE; - std::shared_ptr dataItem = std::shared_ptr( new DataItem(type, id, value) ); - itemsById[id] = dataItem; - MemSect(0); - m_isEmpty = false; +void SynchedEntityData::define(int id, uint8_t value) { + MemSect(17); + checkId(id); + int type = TYPE_BYTE; + std::shared_ptr dataItem = + std::shared_ptr(new DataItem(type, id, value)); + itemsById[id] = dataItem; + MemSect(0); + m_isEmpty = false; } -void SynchedEntityData::define(int id, short value) -{ - MemSect(17); - checkId(id); - int type = TYPE_SHORT; - std::shared_ptr dataItem = std::shared_ptr( new DataItem(type, id, value) ); - itemsById[id] = dataItem; - MemSect(0); - m_isEmpty = false; +void SynchedEntityData::define(int id, short value) { + MemSect(17); + checkId(id); + int type = TYPE_SHORT; + std::shared_ptr dataItem = + std::shared_ptr(new DataItem(type, id, value)); + itemsById[id] = dataItem; + MemSect(0); + m_isEmpty = false; } -void SynchedEntityData::define(int id, const std::wstring& value) -{ - MemSect(17); - checkId(id); - int type = TYPE_STRING; - std::shared_ptr dataItem = std::shared_ptr( new DataItem(type, id, value) ); - itemsById[id] = dataItem; - MemSect(0); - m_isEmpty = false; +void SynchedEntityData::define(int id, const std::wstring& value) { + MemSect(17); + checkId(id); + int type = TYPE_STRING; + std::shared_ptr dataItem = + std::shared_ptr(new DataItem(type, id, value)); + itemsById[id] = dataItem; + MemSect(0); + m_isEmpty = false; } -void SynchedEntityData::defineNULL(int id, void *pVal) -{ - MemSect(17); - checkId(id); - int type = TYPE_ITEMINSTANCE; - std::shared_ptr dataItem = std::shared_ptr( new DataItem(type, id, std::shared_ptr()) ); - itemsById[id] = dataItem; - MemSect(0); - m_isEmpty = false; +void SynchedEntityData::defineNULL(int id, void* pVal) { + MemSect(17); + checkId(id); + int type = TYPE_ITEMINSTANCE; + std::shared_ptr dataItem = std::shared_ptr( + new DataItem(type, id, std::shared_ptr())); + itemsById[id] = dataItem; + MemSect(0); + m_isEmpty = false; } -void SynchedEntityData::checkId(int id) -{ +void SynchedEntityData::checkId(int id) { #if 0 if (id > MAX_ID_VALUE) { @@ -82,476 +80,411 @@ void SynchedEntityData::checkId(int id) #endif } -uint8_t SynchedEntityData::getByte(int id) -{ - return itemsById[id]->getValue_byte(); +uint8_t SynchedEntityData::getByte(int id) { + return itemsById[id]->getValue_byte(); } -short SynchedEntityData::getShort(int id) -{ - return itemsById[id]->getValue_short(); +short SynchedEntityData::getShort(int id) { + return itemsById[id]->getValue_short(); } -int SynchedEntityData::getInteger(int id) -{ - return itemsById[id]->getValue_int(); +int SynchedEntityData::getInteger(int id) { + return itemsById[id]->getValue_int(); } -float SynchedEntityData::getFloat(int id) -{ - assert(false); // 4J - not currently implemented - return 0; +float SynchedEntityData::getFloat(int id) { + assert(false); // 4J - not currently implemented + return 0; } -std::wstring SynchedEntityData::getString(int id) -{ - return itemsById[id]->getValue_wstring(); +std::wstring SynchedEntityData::getString(int id) { + return itemsById[id]->getValue_wstring(); } -std::shared_ptr SynchedEntityData::getItemInstance(int id) -{ - //assert(false); // 4J - not currently implemented - return itemsById[id]->getValue_itemInstance(); +std::shared_ptr SynchedEntityData::getItemInstance(int id) { + // assert(false); // 4J - not currently implemented + return itemsById[id]->getValue_itemInstance(); } -Pos *SynchedEntityData::getPos(int id) -{ - assert(false); // 4J - not currently implemented - return NULL; +Pos* SynchedEntityData::getPos(int id) { + assert(false); // 4J - not currently implemented + return NULL; } -void SynchedEntityData::set(int id, int value) -{ - std::shared_ptr dataItem = itemsById[id]; +void SynchedEntityData::set(int id, int value) { + std::shared_ptr dataItem = itemsById[id]; - // update the value if it has changed - if (value != dataItem->getValue_int()) - { - dataItem->setValue(value); - dataItem->setDirty(true); - m_isDirty = true; - } + // update the value if it has changed + if (value != dataItem->getValue_int()) { + dataItem->setValue(value); + dataItem->setDirty(true); + m_isDirty = true; + } } -void SynchedEntityData::set(int id, uint8_t value) -{ - std::shared_ptr dataItem = itemsById[id]; +void SynchedEntityData::set(int id, uint8_t value) { + std::shared_ptr dataItem = itemsById[id]; - // update the value if it has changed - if (value != dataItem->getValue_byte()) - { - dataItem->setValue(value); - dataItem->setDirty(true); - m_isDirty = true; - } + // update the value if it has changed + if (value != dataItem->getValue_byte()) { + dataItem->setValue(value); + dataItem->setDirty(true); + m_isDirty = true; + } } -void SynchedEntityData::set(int id, short value) -{ - std::shared_ptr dataItem = itemsById[id]; +void SynchedEntityData::set(int id, short value) { + std::shared_ptr dataItem = itemsById[id]; - // update the value if it has changed - if (value != dataItem->getValue_short()) - { - dataItem->setValue(value); - dataItem->setDirty(true); - m_isDirty = true; - } + // update the value if it has changed + if (value != dataItem->getValue_short()) { + dataItem->setValue(value); + dataItem->setDirty(true); + m_isDirty = true; + } } -void SynchedEntityData::set(int id, const std::wstring& value) -{ - std::shared_ptr dataItem = itemsById[id]; +void SynchedEntityData::set(int id, const std::wstring& value) { + std::shared_ptr dataItem = itemsById[id]; - // update the value if it has changed - if (value != dataItem->getValue_wstring()) - { - dataItem->setValue(value); - dataItem->setDirty(true); - m_isDirty = true; - } + // update the value if it has changed + if (value != dataItem->getValue_wstring()) { + dataItem->setValue(value); + dataItem->setDirty(true); + m_isDirty = true; + } } -void SynchedEntityData::set(int id, std::shared_ptr value) -{ - std::shared_ptr dataItem = itemsById[id]; +void SynchedEntityData::set(int id, std::shared_ptr value) { + std::shared_ptr dataItem = itemsById[id]; - // update the value if it has changed - if (value != dataItem->getValue_itemInstance()) - { - dataItem->setValue(value); - dataItem->setDirty(true); - m_isDirty = true; - } + // update the value if it has changed + if (value != dataItem->getValue_itemInstance()) { + dataItem->setValue(value); + dataItem->setDirty(true); + m_isDirty = true; + } } -void SynchedEntityData::markDirty(int id) -{ - (*itemsById.find(id)).second->dirty = true; - m_isDirty = true; +void SynchedEntityData::markDirty(int id) { + (*itemsById.find(id)).second->dirty = true; + m_isDirty = true; } -bool SynchedEntityData::isDirty() +bool SynchedEntityData::isDirty() { return m_isDirty; } + +void SynchedEntityData::pack( + std::vector >* items, + DataOutputStream* output) // TODO throws IOException { - return m_isDirty; + if (items != NULL) { + AUTO_VAR(itEnd, items->end()); + for (AUTO_VAR(it, items->begin()); it != itEnd; it++) { + std::shared_ptr dataItem = *it; + writeDataItem(output, dataItem); + } + } + + // add an eof + output->writeByte(EOF_MARKER); } -void SynchedEntityData::pack(std::vector > *items, DataOutputStream *output) // TODO throws IOException -{ +std::vector >* +SynchedEntityData::packDirty() { + std::vector >* result = NULL; - if (items != NULL) - { - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) - { - std::shared_ptr dataItem = *it; - writeDataItem(output, dataItem); - } - } + if (m_isDirty) { + AUTO_VAR(itEnd, itemsById.end()); + for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++) { + std::shared_ptr dataItem = (*it).second; + if (dataItem->isDirty()) { + dataItem->setDirty(false); - // add an eof - output->writeByte(EOF_MARKER); + if (result == NULL) { + result = new std::vector >(); + } + result->push_back(dataItem); + } + } + } + m_isDirty = false; + + return result; } -std::vector > *SynchedEntityData::packDirty() +void SynchedEntityData::packAll(DataOutputStream* output) // throws IOException { + AUTO_VAR(itEnd, itemsById.end()); + for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++) { + std::shared_ptr dataItem = (*it).second; + writeDataItem(output, dataItem); + } - std::vector > *result = NULL; - - if (m_isDirty) - { - AUTO_VAR(itEnd, itemsById.end()); - for ( AUTO_VAR(it, itemsById.begin()); it != itEnd; it++ ) - { - std::shared_ptr dataItem = (*it).second; - if (dataItem->isDirty()) - { - dataItem->setDirty(false); - - if (result == NULL) - { - result = new std::vector >(); - } - result->push_back(dataItem); - } - } - } - m_isDirty = false; - - return result; + // add an eof + output->writeByte(EOF_MARKER); } -void SynchedEntityData::packAll(DataOutputStream *output) // throws IOException -{ - AUTO_VAR(itEnd, itemsById.end()); - for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++ ) - { - std::shared_ptr dataItem = (*it).second; - writeDataItem(output, dataItem); - } +std::vector >* +SynchedEntityData::getAll() { + std::vector >* result = NULL; - // add an eof - output->writeByte(EOF_MARKER); + AUTO_VAR(itEnd, itemsById.end()); + for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++) { + if (result == NULL) { + result = new std::vector >(); + } + std::shared_ptr dataItem = (*it).second; + result->push_back(dataItem); + } + + return result; } -std::vector > *SynchedEntityData::getAll() +void SynchedEntityData::writeDataItem( + DataOutputStream* output, + std::shared_ptr dataItem) // throws IOException { - std::vector > *result = NULL; + // pack type and id + int header = ((dataItem->getType() << TYPE_SHIFT) | + (dataItem->getId() & MAX_ID_VALUE)) & + 0xff; + output->writeByte(header); - AUTO_VAR(itEnd, itemsById.end()); - for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++ ) - { - if (result == NULL) - { - result = new std::vector >(); - } - std::shared_ptr dataItem = (*it).second; - result->push_back(dataItem); - } + // write value + switch (dataItem->getType()) { + case TYPE_BYTE: + output->writeByte(dataItem->getValue_byte()); + break; + case TYPE_INT: + output->writeInt(dataItem->getValue_int()); + break; + case TYPE_SHORT: + output->writeShort(dataItem->getValue_short()); + break; + case TYPE_STRING: + Packet::writeUtf(dataItem->getValue_wstring(), output); + break; + case TYPE_ITEMINSTANCE: { + std::shared_ptr instance = + (std::shared_ptr) + dataItem->getValue_itemInstance(); + Packet::writeItem(instance, output); + } break; - return result; + default: + assert(false); // 4J - not implemented + break; + } } - -void SynchedEntityData::writeDataItem(DataOutputStream *output, std::shared_ptr dataItem) //throws IOException +std::vector >* +SynchedEntityData::unpack(DataInputStream* input) // throws IOException { - // pack type and id - int header = ((dataItem->getType() << TYPE_SHIFT) | (dataItem->getId() & MAX_ID_VALUE)) & 0xff; - output->writeByte(header); + std::vector >* result = NULL; - // write value - switch (dataItem->getType()) - { - case TYPE_BYTE: - output->writeByte( dataItem->getValue_byte()); - break; - case TYPE_INT: - output->writeInt( dataItem->getValue_int()); - break; - case TYPE_SHORT: - output->writeShort( dataItem->getValue_short()); - break; - case TYPE_STRING: - Packet::writeUtf(dataItem->getValue_wstring(), output); - break; - case TYPE_ITEMINSTANCE: - { - std::shared_ptr instance = (std::shared_ptr )dataItem->getValue_itemInstance(); - Packet::writeItem(instance, output); - } - break; - - default: - assert(false); // 4J - not implemented - break; - } -} + int currentHeader = input->readByte(); -std::vector > *SynchedEntityData::unpack(DataInputStream *input) //throws IOException -{ + while (currentHeader != EOF_MARKER) { + if (result == NULL) { + result = new std::vector >(); + } - std::vector > *result = NULL; + // split type and id + int itemType = (currentHeader & TYPE_MASK) >> TYPE_SHIFT; + int itemId = (currentHeader & MAX_ID_VALUE); - int currentHeader = input->readByte(); + std::shared_ptr item = std::shared_ptr(); + switch (itemType) { + case TYPE_BYTE: { + uint8_t dataRead = input->readByte(); + item = std::shared_ptr( + new DataItem(itemType, itemId, dataRead)); + } break; + case TYPE_SHORT: { + short dataRead = input->readShort(); + item = std::shared_ptr( + new DataItem(itemType, itemId, dataRead)); + } break; + case TYPE_INT: { + int dataRead = input->readInt(); + item = std::shared_ptr( + new DataItem(itemType, itemId, dataRead)); + } break; + case TYPE_STRING: + item = std::shared_ptr(new DataItem( + itemType, itemId, + Packet::readUtf(input, MAX_STRING_DATA_LENGTH))); + break; + case TYPE_ITEMINSTANCE: { + item = std::shared_ptr( + new DataItem(itemType, itemId, Packet::readItem(input))); + } break; + default: + app.DebugPrintf( + " ------ garbage data, or early end of stream due to an " + "incomplete packet\n"); + delete result; + return NULL; + break; + } + result->push_back(item); - while (currentHeader != EOF_MARKER) - { + currentHeader = input->readByte(); + } - if (result == NULL) - { - result = new std::vector >(); - } - - // split type and id - int itemType = (currentHeader & TYPE_MASK) >> TYPE_SHIFT; - int itemId = (currentHeader & MAX_ID_VALUE); - - std::shared_ptr item = std::shared_ptr(); - switch (itemType) - { - case TYPE_BYTE: - { - uint8_t dataRead = input->readByte(); - item = std::shared_ptr( new DataItem(itemType, itemId, dataRead) ); - } - break; - case TYPE_SHORT: - { - short dataRead = input->readShort(); - item = std::shared_ptr( new DataItem(itemType, itemId, dataRead) ); - } - break; - case TYPE_INT: - { - int dataRead = input->readInt(); - item = std::shared_ptr( new DataItem(itemType, itemId, dataRead) ); - } - break; - case TYPE_STRING: - item = std::shared_ptr( new DataItem(itemType, itemId, Packet::readUtf(input, MAX_STRING_DATA_LENGTH)) ); - break; - case TYPE_ITEMINSTANCE: - { - item = std::shared_ptr(new DataItem(itemType, itemId, Packet::readItem(input))); - } - break; - default: - app.DebugPrintf(" ------ garbage data, or early end of stream due to an incomplete packet\n"); - delete result; - return NULL; - break; - } - result->push_back(item); - - currentHeader = input->readByte(); - } - - return result; + return result; } /** -* Assigns values from a list of data items. -* -* @param items -*/ + * Assigns values from a list of data items. + * + * @param items + */ -void SynchedEntityData::assignValues(std::vector > *items) -{ - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) - { - std::shared_ptr item = *it; - AUTO_VAR(itemFromId, itemsById.find(item->getId())); - if (itemFromId != itemsById.end() ) - { - switch(item->getType()) - { - case TYPE_BYTE: - itemFromId->second->setValue(item->getValue_byte()); - break; - case TYPE_SHORT: - itemFromId->second->setValue(item->getValue_short()); - break; - case TYPE_INT: - itemFromId->second->setValue(item->getValue_int()); - break; - case TYPE_STRING: - itemFromId->second->setValue(item->getValue_wstring()); - break; - case TYPE_ITEMINSTANCE: - itemFromId->second->setValue(item->getValue_itemInstance()); - break; - default: - assert(false); // 4J - not implemented - break; - } - } - } +void SynchedEntityData::assignValues( + std::vector >* items) { + AUTO_VAR(itEnd, items->end()); + for (AUTO_VAR(it, items->begin()); it != itEnd; it++) { + std::shared_ptr item = *it; + AUTO_VAR(itemFromId, itemsById.find(item->getId())); + if (itemFromId != itemsById.end()) { + switch (item->getType()) { + case TYPE_BYTE: + itemFromId->second->setValue(item->getValue_byte()); + break; + case TYPE_SHORT: + itemFromId->second->setValue(item->getValue_short()); + break; + case TYPE_INT: + itemFromId->second->setValue(item->getValue_int()); + break; + case TYPE_STRING: + itemFromId->second->setValue(item->getValue_wstring()); + break; + case TYPE_ITEMINSTANCE: + itemFromId->second->setValue(item->getValue_itemInstance()); + break; + default: + assert(false); // 4J - not implemented + break; + } + } + } } -bool SynchedEntityData::isEmpty() -{ - return m_isEmpty; +bool SynchedEntityData::isEmpty() { return m_isEmpty; } + +int SynchedEntityData::getSizeInBytes() { + int size = 1; + + AUTO_VAR(itEnd, itemsById.end()); + for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++) { + std::shared_ptr dataItem = (*it).second; + + size += 1; + + // write value + switch (dataItem->getType()) { + case TYPE_BYTE: + size += 1; + break; + case TYPE_SHORT: + size += 2; + break; + case TYPE_INT: + size += 4; + break; + case TYPE_STRING: + size += (int)dataItem->getValue_wstring().length() + + 2; // Estimate, assuming all ascii chars + break; + case TYPE_ITEMINSTANCE: + // short + byte + short + size += 2 + 1 + 2; // Estimate, assuming all ascii chars + break; + default: + break; + } + } + return size; } -int SynchedEntityData::getSizeInBytes() -{ - int size = 1; - - AUTO_VAR(itEnd, itemsById.end()); - for (AUTO_VAR(it, itemsById.begin()); it != itEnd; it++ ) - { - std::shared_ptr dataItem = (*it).second; - - size += 1; - - // write value - switch (dataItem->getType()) - { - case TYPE_BYTE: - size += 1; - break; - case TYPE_SHORT: - size += 2; - break; - case TYPE_INT: - size += 4; - break; - case TYPE_STRING: - size += (int)dataItem->getValue_wstring().length() + 2; // Estimate, assuming all ascii chars - break; - case TYPE_ITEMINSTANCE: - // short + byte + short - size += 2 + 1 + 2; // Estimate, assuming all ascii chars - break; - default: - break; - } - } - return size; -} - - ////////////////// // DataItem class ///////////////// -SynchedEntityData::DataItem::DataItem(int type, int id, int value) : type( type ), id( id ) -{ - this->value_int = value; - this->dirty = true; +SynchedEntityData::DataItem::DataItem(int type, int id, int value) + : type(type), id(id) { + this->value_int = value; + this->dirty = true; } -SynchedEntityData::DataItem::DataItem(int type, int id, uint8_t value) : type( type ), id( id ) -{ - this->value_byte = value; - this->dirty = true; +SynchedEntityData::DataItem::DataItem(int type, int id, uint8_t value) + : type(type), id(id) { + this->value_byte = value; + this->dirty = true; } -SynchedEntityData::DataItem::DataItem(int type, int id, short value) : type( type ), id( id ) -{ - this->value_short = value; - this->dirty = true; +SynchedEntityData::DataItem::DataItem(int type, int id, short value) + : type(type), id(id) { + this->value_short = value; + this->dirty = true; } -SynchedEntityData::DataItem::DataItem(int type, int id, const std::wstring& value) : type( type ), id( id ) -{ - this->value_wstring = value; - this->dirty = true; +SynchedEntityData::DataItem::DataItem(int type, int id, + const std::wstring& value) + : type(type), id(id) { + this->value_wstring = value; + this->dirty = true; } -SynchedEntityData::DataItem::DataItem(int type, int id, std::shared_ptr itemInstance) : type( type ), id( id ) -{ - this->value_itemInstance = itemInstance; - this->dirty = true; +SynchedEntityData::DataItem::DataItem( + int type, int id, std::shared_ptr itemInstance) + : type(type), id(id) { + this->value_itemInstance = itemInstance; + this->dirty = true; } -int SynchedEntityData::DataItem::getId() -{ - return id; +int SynchedEntityData::DataItem::getId() { return id; } + +void SynchedEntityData::DataItem::setValue(int value) { + this->value_int = value; } -void SynchedEntityData::DataItem::setValue(int value) -{ - this->value_int = value; +void SynchedEntityData::DataItem::setValue(uint8_t value) { + this->value_byte = value; } -void SynchedEntityData::DataItem::setValue(uint8_t value) -{ - this->value_byte = value; +void SynchedEntityData::DataItem::setValue(short value) { + this->value_short = value; } -void SynchedEntityData::DataItem::setValue(short value) -{ - this->value_short = value; +void SynchedEntityData::DataItem::setValue(const std::wstring& value) { + this->value_wstring = value; } -void SynchedEntityData::DataItem::setValue(const std::wstring& value) -{ - this->value_wstring = value; +void SynchedEntityData::DataItem::setValue( + std::shared_ptr itemInstance) { + this->value_itemInstance = itemInstance; } -void SynchedEntityData::DataItem::setValue(std::shared_ptr itemInstance) -{ - this->value_itemInstance = itemInstance; +int SynchedEntityData::DataItem::getValue_int() { return value_int; } + +short SynchedEntityData::DataItem::getValue_short() { return value_short; } + +uint8_t SynchedEntityData::DataItem::getValue_byte() { return value_byte; } + +std::wstring SynchedEntityData::DataItem::getValue_wstring() { + return value_wstring; } -int SynchedEntityData::DataItem::getValue_int() -{ - return value_int; +std::shared_ptr +SynchedEntityData::DataItem::getValue_itemInstance() { + return value_itemInstance; } -short SynchedEntityData::DataItem::getValue_short() -{ - return value_short; -} +int SynchedEntityData::DataItem::getType() { return type; } -uint8_t SynchedEntityData::DataItem::getValue_byte() -{ - return value_byte; -} +bool SynchedEntityData::DataItem::isDirty() { return dirty; } -std::wstring SynchedEntityData::DataItem::getValue_wstring() -{ - return value_wstring; -} - -std::shared_ptr SynchedEntityData::DataItem::getValue_itemInstance() -{ - return value_itemInstance; -} - -int SynchedEntityData::DataItem::getType() -{ - return type; -} - -bool SynchedEntityData::DataItem::isDirty() -{ - return dirty; -} - -void SynchedEntityData::DataItem::setDirty(bool dirty) -{ - this->dirty = dirty; -} +void SynchedEntityData::DataItem::setDirty(bool dirty) { this->dirty = dirty; } diff --git a/Minecraft.World/Entities/SyncedEntityData.h b/Minecraft.World/Entities/SyncedEntityData.h index 7726b60b0..d902f5c7c 100644 --- a/Minecraft.World/Entities/SyncedEntityData.h +++ b/Minecraft.World/Entities/SyncedEntityData.h @@ -1,127 +1,131 @@ #pragma once - class Pos; - -class SynchedEntityData -{ +class SynchedEntityData { public: - class DataItem - { - friend class SynchedEntityData; - private: - const int type; - const int id; - // 4J - there used to be one "value" type here of general type Object, just storing the different (used) varieties - // here separately for us - uint8_t value_byte; - int value_int; - short value_short; - std::wstring value_wstring; - std::shared_ptr value_itemInstance; - bool dirty; + class DataItem { + friend class SynchedEntityData; - public: - // There was one type here that took a generic Object type, using overloading here instead - DataItem(int type, int id, uint8_t value); - DataItem(int type, int id, int value); - DataItem(int type, int id, const std::wstring& value); - DataItem(int type, int id, std::shared_ptr itemInstance); - DataItem(int type, int id, short value); + private: + const int type; + const int id; + // 4J - there used to be one "value" type here of general type Object, + // just storing the different (used) varieties here separately for us + uint8_t value_byte; + int value_int; + short value_short; + std::wstring value_wstring; + std::shared_ptr value_itemInstance; + bool dirty; - int getId(); - void setValue(uint8_t value); - void setValue(int value); - void setValue(short value); - void setValue(const std::wstring& value); - void setValue(std::shared_ptr value); - uint8_t getValue_byte(); - int getValue_int(); - short getValue_short(); - std::wstring getValue_wstring(); - std::shared_ptr getValue_itemInstance(); - int getType(); - bool isDirty(); - void setDirty(bool dirty); - }; + public: + // There was one type here that took a generic Object type, using + // overloading here instead + DataItem(int type, int id, uint8_t value); + DataItem(int type, int id, int value); + DataItem(int type, int id, const std::wstring& value); + DataItem(int type, int id, std::shared_ptr itemInstance); + DataItem(int type, int id, short value); + + int getId(); + void setValue(uint8_t value); + void setValue(int value); + void setValue(short value); + void setValue(const std::wstring& value); + void setValue(std::shared_ptr value); + uint8_t getValue_byte(); + int getValue_int(); + short getValue_short(); + std::wstring getValue_wstring(); + std::shared_ptr getValue_itemInstance(); + int getType(); + bool isDirty(); + void setDirty(bool dirty); + }; public: - static const int MAX_STRING_DATA_LENGTH = 64; - static const int EOF_MARKER = 0x7f; + static const int MAX_STRING_DATA_LENGTH = 64; + static const int EOF_MARKER = 0x7f; private: - static const int TYPE_BYTE = 0; - static const int TYPE_SHORT = 1; - static const int TYPE_INT = 2; - static const int TYPE_FLOAT = 3; - static const int TYPE_STRING = 4; - // special types (max possible value is 7): - static const int TYPE_ITEMINSTANCE = 5; - static const int TYPE_POS = 6; + static const int TYPE_BYTE = 0; + static const int TYPE_SHORT = 1; + static const int TYPE_INT = 2; + static const int TYPE_FLOAT = 3; + static const int TYPE_STRING = 4; + // special types (max possible value is 7): + static const int TYPE_ITEMINSTANCE = 5; + static const int TYPE_POS = 6; private: - bool m_isEmpty; + bool m_isEmpty; - // must have enough bits to fit the type + // must have enough bits to fit the type private: - static const int TYPE_MASK = 0xe0; - static const int TYPE_SHIFT = 5; + static const int TYPE_MASK = 0xe0; + static const int TYPE_SHIFT = 5; - // the id value must fit in the remaining bits - static const int MAX_ID_VALUE = ~TYPE_MASK & 0xff; + // the id value must fit in the remaining bits + static const int MAX_ID_VALUE = ~TYPE_MASK & 0xff; - std::unordered_map > itemsById; - bool m_isDirty; + std::unordered_map > itemsById; + bool m_isDirty; public: - SynchedEntityData(); + SynchedEntityData(); - // 4J - this function used to be a template, but there's only 3 varieties of use I've found so just hard-coding now, as - // the original had some automatic Class to type sort of conversion that's a real pain for us to actually do - void define(int id, uint8_t value); - void define(int id, const std::wstring& value); - void define(int id, int value); - void define(int id, short value); - void defineNULL(int id, void *pVal); + // 4J - this function used to be a template, but there's only 3 varieties of + // use I've found so just hard-coding now, as the original had some + // automatic Class to type sort of conversion that's a real pain for us to + // actually do + void define(int id, uint8_t value); + void define(int id, const std::wstring& value); + void define(int id, int value); + void define(int id, short value); + void defineNULL(int id, void* pVal); - void checkId(int id); // 4J - added to contain common code from overloaded define functions above - uint8_t getByte(int id); - short getShort(int id); - int getInteger(int id); - float getFloat(int id); - std::wstring getString(int id); - std::shared_ptr getItemInstance(int id); - Pos *getPos(int id); - // 4J - using overloads rather than template here - void set(int id, uint8_t value); - void set(int id, int value); - void set(int id, short value); - void set(int id, const std::wstring& value); - void set(int id, std::shared_ptr); - void markDirty(int id); - bool isDirty(); - static void pack(std::vector > *items, DataOutputStream *output); // TODO throws IOException - std::vector > *packDirty(); - void packAll(DataOutputStream *output); // throws IOException - std::vector > *getAll(); + void checkId(int id); // 4J - added to contain common code from overloaded + // define functions above + uint8_t getByte(int id); + short getShort(int id); + int getInteger(int id); + float getFloat(int id); + std::wstring getString(int id); + std::shared_ptr getItemInstance(int id); + Pos* getPos(int id); + // 4J - using overloads rather than template here + void set(int id, uint8_t value); + void set(int id, int value); + void set(int id, short value); + void set(int id, const std::wstring& value); + void set(int id, std::shared_ptr); + void markDirty(int id); + bool isDirty(); + static void pack(std::vector >* items, + DataOutputStream* output); // TODO throws IOException + std::vector >* packDirty(); + void packAll(DataOutputStream* output); // throws IOException + std::vector >* getAll(); private: - static void writeDataItem(DataOutputStream *output, std::shared_ptr dataItem); //throws IOException - + static void writeDataItem( + DataOutputStream* output, + std::shared_ptr dataItem); // throws IOException public: - static std::vector > *unpack(DataInputStream *input); // throws IOException + static std::vector >* unpack( + DataInputStream* input); // throws IOException - /** - * Assigns values from a list of data items. - * - * @param items - */ + /** + * Assigns values from a list of data items. + * + * @param items + */ public: - void assignValues(std::vector > *items); - bool isEmpty(); + void assignValues(std::vector >* items); + bool isEmpty(); - // 4J Added - int getSizeInBytes(); + // 4J Added + int getSizeInBytes(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/TamableAnimal.cpp b/Minecraft.World/Entities/TamableAnimal.cpp index 0177adc2d..3a4693f3c 100644 --- a/Minecraft.World/Entities/TamableAnimal.cpp +++ b/Minecraft.World/Entities/TamableAnimal.cpp @@ -6,154 +6,121 @@ #include "../Util/ParticleTypes.h" #include "TamableAnimal.h" -TamableAnimal::TamableAnimal(Level *level) : Animal(level) -{ - sitGoal = new SitGoal(this); +TamableAnimal::TamableAnimal(Level* level) : Animal(level) { + sitGoal = new SitGoal(this); } -TamableAnimal::~TamableAnimal() -{ - if(sitGoal != NULL) delete sitGoal; +TamableAnimal::~TamableAnimal() { + if (sitGoal != NULL) delete sitGoal; } -void TamableAnimal::defineSynchedData() -{ - Animal::defineSynchedData(); - entityData->define(DATA_FLAGS_ID, (uint8_t) 0); - entityData->define(DATA_OWNERUUID_ID, L""); +void TamableAnimal::defineSynchedData() { + Animal::defineSynchedData(); + entityData->define(DATA_FLAGS_ID, (uint8_t)0); + entityData->define(DATA_OWNERUUID_ID, L""); } -void TamableAnimal::addAdditonalSaveData(CompoundTag *tag) -{ - Animal::addAdditonalSaveData(tag); +void TamableAnimal::addAdditonalSaveData(CompoundTag* tag) { + Animal::addAdditonalSaveData(tag); #ifdef _XBOX_ONE - // 4J Stu Added from later Java version to remove owners from save transfer saves. We will probably want this on other platforms in the future - if (getOwnerUUID().empty()) - { - tag->putString(L"OwnerUUID", L""); - } - else - { - tag->putString(L"OwnerUUID", getOwnerUUID()); - } + // 4J Stu Added from later Java version to remove owners from save transfer + // saves. We will probably want this on other platforms in the future + if (getOwnerUUID().empty()) { + tag->putString(L"OwnerUUID", L""); + } else { + tag->putString(L"OwnerUUID", getOwnerUUID()); + } #else - if (getOwnerUUID().empty()) - { - tag->putString(L"Owner", L""); - } - else - { - tag->putString(L"Owner", getOwnerUUID()); - } + if (getOwnerUUID().empty()) { + tag->putString(L"Owner", L""); + } else { + tag->putString(L"Owner", getOwnerUUID()); + } #endif - tag->putBoolean(L"Sitting", isSitting()); + tag->putBoolean(L"Sitting", isSitting()); } -void TamableAnimal::readAdditionalSaveData(CompoundTag *tag) -{ - Animal::readAdditionalSaveData(tag); +void TamableAnimal::readAdditionalSaveData(CompoundTag* tag) { + Animal::readAdditionalSaveData(tag); #ifdef _XBOX_ONE - // 4J Stu Added from later Java version to remove owners from save transfer saves. We will probably want this on other platforms in the future - std::wstring owner = L""; - if(tag->contains(L"OwnerUUID") ) - { - owner = tag->getString(L"OwnerUUID"); - } + // 4J Stu Added from later Java version to remove owners from save transfer + // saves. We will probably want this on other platforms in the future + std::wstring owner = L""; + if (tag->contains(L"OwnerUUID")) { + owner = tag->getString(L"OwnerUUID"); + } #else - std::wstring owner = tag->getString(L"Owner"); + std::wstring owner = tag->getString(L"Owner"); #endif - if (owner.length() > 0) - { - setOwnerUUID(owner); - setTame(true); - } - sitGoal->wantToSit(tag->getBoolean(L"Sitting")); + if (owner.length() > 0) { + setOwnerUUID(owner); + setTame(true); + } + sitGoal->wantToSit(tag->getBoolean(L"Sitting")); } -void TamableAnimal::spawnTamingParticles(bool success) -{ - ePARTICLE_TYPE particle = eParticleType_heart; - if (!success) - { - particle = eParticleType_smoke; - } - for (int i = 0; i < 7; i++) - { - double xa = random->nextGaussian() * 0.02; - double ya = random->nextGaussian() * 0.02; - double za = random->nextGaussian() * 0.02; - level->addParticle(particle, x + random->nextFloat() * bbWidth * 2 - bbWidth, y + .5f + random->nextFloat() * bbHeight, z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); - } +void TamableAnimal::spawnTamingParticles(bool success) { + ePARTICLE_TYPE particle = eParticleType_heart; + if (!success) { + particle = eParticleType_smoke; + } + for (int i = 0; i < 7; i++) { + double xa = random->nextGaussian() * 0.02; + double ya = random->nextGaussian() * 0.02; + double za = random->nextGaussian() * 0.02; + level->addParticle( + particle, x + random->nextFloat() * bbWidth * 2 - bbWidth, + y + .5f + random->nextFloat() * bbHeight, + z + random->nextFloat() * bbWidth * 2 - bbWidth, xa, ya, za); + } } -void TamableAnimal::handleEntityEvent(uint8_t id) -{ - if (id == EntityEvent::TAMING_SUCCEEDED) - { - spawnTamingParticles(true); - } - else if (id == EntityEvent::TAMING_FAILED) - { - spawnTamingParticles(false); - } - else - { - Animal::handleEntityEvent(id); - } +void TamableAnimal::handleEntityEvent(uint8_t id) { + if (id == EntityEvent::TAMING_SUCCEEDED) { + spawnTamingParticles(true); + } else if (id == EntityEvent::TAMING_FAILED) { + spawnTamingParticles(false); + } else { + Animal::handleEntityEvent(id); + } } -bool TamableAnimal::isTame() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x04) != 0; +bool TamableAnimal::isTame() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x04) != 0; } -void TamableAnimal::setTame(bool value) -{ - uint8_t current = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current | 0x04)); - } - else - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current & ~0x04)); - } +void TamableAnimal::setTame(bool value) { + uint8_t current = entityData->getByte(DATA_FLAGS_ID); + if (value) { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current | 0x04)); + } else { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current & ~0x04)); + } } -bool TamableAnimal::isSitting() -{ - return (entityData->getByte(DATA_FLAGS_ID) & 0x01) != 0; +bool TamableAnimal::isSitting() { + return (entityData->getByte(DATA_FLAGS_ID) & 0x01) != 0; } -void TamableAnimal::setSitting(bool value) -{ - uint8_t current = entityData->getByte(DATA_FLAGS_ID); - if (value) - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current | 0x01)); - } - else - { - entityData->set(DATA_FLAGS_ID, (uint8_t) (current & ~0x01)); - } +void TamableAnimal::setSitting(bool value) { + uint8_t current = entityData->getByte(DATA_FLAGS_ID); + if (value) { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current | 0x01)); + } else { + entityData->set(DATA_FLAGS_ID, (uint8_t)(current & ~0x01)); + } } -std::wstring TamableAnimal::getOwnerUUID() -{ - return entityData->getString(DATA_OWNERUUID_ID); +std::wstring TamableAnimal::getOwnerUUID() { + return entityData->getString(DATA_OWNERUUID_ID); } -void TamableAnimal::setOwnerUUID(const std::wstring &name) -{ - entityData->set(DATA_OWNERUUID_ID, name); +void TamableAnimal::setOwnerUUID(const std::wstring& name) { + entityData->set(DATA_OWNERUUID_ID, name); } -std::shared_ptr TamableAnimal::getOwner() -{ - return level->getPlayerByUUID(getOwnerUUID()); +std::shared_ptr TamableAnimal::getOwner() { + return level->getPlayerByUUID(getOwnerUUID()); } -SitGoal *TamableAnimal::getSitGoal() -{ - return sitGoal; -} \ No newline at end of file +SitGoal* TamableAnimal::getSitGoal() { return sitGoal; } \ No newline at end of file diff --git a/Minecraft.World/Entities/TamableAnimal.h b/Minecraft.World/Entities/TamableAnimal.h index 4955f0ff2..b7557eb47 100644 --- a/Minecraft.World/Entities/TamableAnimal.h +++ b/Minecraft.World/Entities/TamableAnimal.h @@ -4,35 +4,35 @@ class SitGoal; -class TamableAnimal : public Animal -{ +class TamableAnimal : public Animal { protected: - static const int DATA_FLAGS_ID = 16; - static const int DATA_OWNERUUID_ID = 17; + static const int DATA_FLAGS_ID = 16; + static const int DATA_OWNERUUID_ID = 17; - SitGoal *sitGoal; + SitGoal* sitGoal; public: - TamableAnimal(Level *level); - virtual ~TamableAnimal(); + TamableAnimal(Level* level); + virtual ~TamableAnimal(); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + protected: - virtual void spawnTamingParticles(bool success); + virtual void spawnTamingParticles(bool success); public: - virtual void handleEntityEvent(uint8_t id); - virtual bool isTame(); - virtual void setTame(bool value); - virtual bool isSitting(); - virtual void setSitting(bool value); - virtual std::wstring getOwnerUUID(); - virtual void setOwnerUUID(const std::wstring &name); - virtual std::shared_ptr getOwner(); - virtual SitGoal *getSitGoal(); + virtual void handleEntityEvent(uint8_t id); + virtual bool isTame(); + virtual void setTame(bool value); + virtual bool isSitting(); + virtual void setSitting(bool value); + virtual std::wstring getOwnerUUID(); + virtual void setOwnerUUID(const std::wstring& name); + virtual std::shared_ptr getOwner(); + virtual SitGoal* getSitGoal(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/Throwable.cpp b/Minecraft.World/Entities/Throwable.cpp index fc80068d9..06019f032 100644 --- a/Minecraft.World/Entities/Throwable.cpp +++ b/Minecraft.World/Entities/Throwable.cpp @@ -5,277 +5,231 @@ #include "../Headers/com.mojang.nbt.h" #include "Throwable.h" - - -void Throwable::_throwableInit() -{ - xTile = -1; - yTile = -1; - zTile = -1; - lastTile = 0; - inGround = false; - shakeTime = 0; - owner = nullptr; - life = 0; - flightTime = 0; +void Throwable::_throwableInit() { + xTile = -1; + yTile = -1; + zTile = -1; + lastTile = 0; + inGround = false; + shakeTime = 0; + owner = nullptr; + life = 0; + flightTime = 0; } -Throwable::Throwable(Level *level) : Entity(level) -{ - _throwableInit(); - setSize(0.25f, 0.25f); +Throwable::Throwable(Level* level) : Entity(level) { + _throwableInit(); + setSize(0.25f, 0.25f); } -void Throwable::defineSynchedData() -{ +void Throwable::defineSynchedData() {} + +bool Throwable::shouldRenderAtSqrDistance(double distance) { + double size = bb->getSize() * 4; + size *= 64.0f; + return distance < size * size; } -bool Throwable::shouldRenderAtSqrDistance(double distance) -{ - double size = bb->getSize() * 4; - size *= 64.0f; - return distance < size * size; +Throwable::Throwable(Level* level, std::shared_ptr mob) : Entity(level) { + _throwableInit(); + this->owner = mob; + + setSize(4 / 16.0f, 4 / 16.0f); + + this->moveTo(mob->x, mob->y + mob->getHeadHeight(), mob->z, mob->yRot, + mob->xRot); + + x -= cos(yRot / 180 * PI) * 0.16f; + y -= 0.1f; + z -= sin(yRot / 180 * PI) * 0.16f; + this->setPos(x, y, z); + this->heightOffset = 0; + + float speed = 0.4f; + xd = (-sin(yRot / 180 * PI) * cos(xRot / 180 * PI)) * speed; + zd = (cos(yRot / 180 * PI) * cos(xRot / 180 * PI)) * speed; + yd = (-sin((xRot + getThrowUpAngleOffset()) / 180 * PI)) * speed; + + shoot(xd, yd, zd, getThrowPower(), 1); } -Throwable::Throwable(Level *level, std::shared_ptr mob) : Entity(level) -{ - _throwableInit(); - this->owner = mob; +Throwable::Throwable(Level* level, double x, double y, double z) + : Entity(level) { + _throwableInit(); + life = 0; - setSize(4 / 16.0f, 4 / 16.0f); + setSize(4 / 16.0f, 4 / 16.0f); - this->moveTo(mob->x, mob->y + mob->getHeadHeight(), mob->z, mob->yRot, mob->xRot); - - - x -= cos(yRot / 180 * PI) * 0.16f; - y -= 0.1f; - z -= sin(yRot / 180 * PI) * 0.16f; - this->setPos(x, y, z); - this->heightOffset = 0; - - - float speed = 0.4f; - xd = (-sin(yRot / 180 * PI) * cos(xRot / 180 * PI)) * speed; - zd = (cos(yRot / 180 * PI) * cos(xRot / 180 * PI)) * speed; - yd = (-sin((xRot + getThrowUpAngleOffset()) / 180 * PI)) * speed; - - shoot(xd, yd, zd, getThrowPower(), 1); + this->setPos(x, y, z); + this->heightOffset = 0; } -Throwable::Throwable(Level *level, double x, double y, double z) : Entity(level) -{ - _throwableInit(); - life = 0; +float Throwable::getThrowPower() { return 1.5f; } - setSize(4 / 16.0f, 4 / 16.0f); +float Throwable::getThrowUpAngleOffset() { return 0; } - this->setPos(x, y, z); - this->heightOffset = 0; +void Throwable::shoot(double xd, double yd, double zd, float pow, + float uncertainty) { + float dist = sqrt(xd * xd + yd * yd + zd * zd); + + xd /= dist; + yd /= dist; + zd /= dist; + + xd += (random->nextGaussian()) * 0.0075f * uncertainty; + yd += (random->nextGaussian()) * 0.0075f * uncertainty; + zd += (random->nextGaussian()) * 0.0075f * uncertainty; + + xd *= pow; + yd *= pow; + zd *= pow; + + this->xd = xd; + this->yd = yd; + this->zd = zd; + + float sd = (float)sqrt(xd * xd + zd * zd); + + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, (double)sd) * 180 / PI); + life = 0; } - -float Throwable::getThrowPower() -{ - return 1.5f; +void Throwable::lerpMotion(double xd, double yd, double zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; + if (xRotO == 0 && yRotO == 0) { + float sd = (float)sqrt(xd * xd + zd * zd); + yRotO = this->yRot = (float)(atan2(xd, zd) * 180 / PI); + xRotO = this->xRot = (float)(atan2(yd, (double)sd) * 180 / PI); + } } -float Throwable::getThrowUpAngleOffset() -{ - return 0; +void Throwable::tick() { + xOld = x; + yOld = y; + zOld = z; + Entity::tick(); + + if (shakeTime > 0) shakeTime--; + + if (inGround) { + int tile = level->getTile(xTile, yTile, zTile); + if (tile == lastTile) { + life++; + if (life == 20 * 60) remove(); + return; + } else { + inGround = false; + + xd *= random->nextFloat() * 0.2f; + yd *= random->nextFloat() * 0.2f; + zd *= random->nextFloat() * 0.2f; + life = 0; + flightTime = 0; + } + } else { + flightTime++; + } + + Vec3* from = Vec3::newTemp(x, y, z); + Vec3* to = Vec3::newTemp(x + xd, y + yd, z + zd); + HitResult* res = level->clip(from, to); + + from = Vec3::newTemp(x, y, z); + to = Vec3::newTemp(x + xd, y + yd, z + zd); + if (res != NULL) { + to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); + } + + if (!level->isClientSide) { + std::shared_ptr hitEntity = nullptr; + std::vector >* objects = level->getEntities( + shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); + double nearest = 0; + for (int i = 0; i < objects->size(); i++) { + std::shared_ptr e = objects->at(i); + if (!e->isPickable() || (e == owner && flightTime < 5)) continue; + + float rr = 0.3f; + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (p != NULL) { + double dd = from->distanceTo(p->pos); + delete p; + if (dd < nearest || nearest == 0) { + hitEntity = e; + nearest = dd; + } + } + } + + if (hitEntity != NULL) { + if (res != NULL) delete res; + res = new HitResult(hitEntity); + } + } + + if (res != NULL) { + onHit(res); + delete res; + } + x += xd; + y += yd; + z += zd; + + float sd = (float)sqrt(xd * xd + zd * zd); + yRot = (float)(atan2(xd, zd) * 180 / PI); + xRot = (float)(atan2(yd, (double)sd) * 180 / PI); + + while (xRot - xRotO < -180) xRotO -= 360; + while (xRot - xRotO >= 180) xRotO += 360; + + while (yRot - yRotO < -180) yRotO -= 360; + while (yRot - yRotO >= 180) yRotO += 360; + + xRot = xRotO + (xRot - xRotO) * 0.2f; + yRot = yRotO + (yRot - yRotO) * 0.2f; + + float inertia = 0.99f; + float gravity = getGravity(); + + if (isInWater()) { + for (int i = 0; i < 4; i++) { + float s = 1 / 4.0f; + level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, + z - zd * s, xd, yd, zd); + } + inertia = 0.80f; + } + + xd *= inertia; + yd *= inertia; + zd *= inertia; + yd -= gravity; + + setPos(x, y, z); } -void Throwable::shoot(double xd, double yd, double zd, float pow, float uncertainty) -{ - float dist = sqrt(xd * xd + yd * yd + zd * zd); +float Throwable::getGravity() { return 0.03f; } - xd /= dist; - yd /= dist; - zd /= dist; - - xd += (random->nextGaussian()) * 0.0075f * uncertainty; - yd += (random->nextGaussian()) * 0.0075f * uncertainty; - zd += (random->nextGaussian()) * 0.0075f * uncertainty; - - xd *= pow; - yd *= pow; - zd *= pow; - - this->xd = xd; - this->yd = yd; - this->zd = zd; - - float sd = (float) sqrt(xd * xd + zd * zd); - - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, (double)sd) * 180 / PI); - life = 0; +void Throwable::addAdditonalSaveData(CompoundTag* tag) { + tag->putShort(L"xTile", (short)xTile); + tag->putShort(L"yTile", (short)yTile); + tag->putShort(L"zTile", (short)zTile); + tag->putByte(L"inTile", (uint8_t)lastTile); + tag->putByte(L"shake", (uint8_t)shakeTime); + tag->putByte(L"inGround", (uint8_t)(inGround ? 1 : 0)); } -void Throwable::lerpMotion(double xd, double yd, double zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; - if (xRotO == 0 && yRotO == 0) - { - float sd = (float) sqrt(xd * xd + zd * zd); - yRotO = this->yRot = (float) (atan2(xd, zd) * 180 / PI); - xRotO = this->xRot = (float) (atan2(yd, (double)sd) * 180 / PI); - } +void Throwable::readAdditionalSaveData(CompoundTag* tag) { + xTile = tag->getShort(L"xTile"); + yTile = tag->getShort(L"yTile"); + zTile = tag->getShort(L"zTile"); + lastTile = tag->getByte(L"inTile") & 0xff; + shakeTime = tag->getByte(L"shake") & 0xff; + inGround = tag->getByte(L"inGround") == 1; } -void Throwable::tick() -{ - xOld = x; - yOld = y; - zOld = z; - Entity::tick(); - - if (shakeTime > 0) shakeTime--; - - if (inGround) - { - int tile = level->getTile(xTile, yTile, zTile); - if (tile == lastTile) - { - life++; - if (life == 20 * 60) remove(); - return; - } - else - { - inGround = false; - - xd *= random->nextFloat() * 0.2f; - yd *= random->nextFloat() * 0.2f; - zd *= random->nextFloat() * 0.2f; - life = 0; - flightTime = 0; - } - } - else - { - flightTime++; - } - - Vec3 *from = Vec3::newTemp(x, y, z); - Vec3 *to = Vec3::newTemp(x + xd, y + yd, z + zd); - HitResult *res = level->clip(from, to); - - from = Vec3::newTemp(x, y, z); - to = Vec3::newTemp(x + xd, y + yd, z + zd); - if (res != NULL) - { - to = Vec3::newTemp(res->pos->x, res->pos->y, res->pos->z); - } - - if (!level->isClientSide) - { - std::shared_ptr hitEntity = nullptr; - std::vector > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); - double nearest = 0; - for (int i = 0; i < objects->size(); i++) - { - std::shared_ptr e = objects->at(i); - if (!e->isPickable() || (e == owner && flightTime < 5)) continue; - - float rr = 0.3f; - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (p != NULL) - { - double dd = from->distanceTo(p->pos); - delete p; - if (dd < nearest || nearest == 0) - { - hitEntity = e; - nearest = dd; - } - } - } - - if (hitEntity != NULL) - { - if(res != NULL) delete res; - res = new HitResult(hitEntity); - } - } - - if (res != NULL) - { - onHit(res); - delete res; - } - x += xd; - y += yd; - z += zd; - - float sd = (float) sqrt(xd * xd + zd * zd); - yRot = (float) (atan2(xd, zd) * 180 / PI); - xRot = (float) (atan2(yd, (double)sd) * 180 / PI); - - while (xRot - xRotO < -180) - xRotO -= 360; - while (xRot - xRotO >= 180) - xRotO += 360; - - while (yRot - yRotO < -180) - yRotO -= 360; - while (yRot - yRotO >= 180) - yRotO += 360; - - xRot = xRotO + (xRot - xRotO) * 0.2f; - yRot = yRotO + (yRot - yRotO) * 0.2f; - - - float inertia = 0.99f; - float gravity = getGravity(); - - if (isInWater()) - { - for (int i = 0; i < 4; i++) - { - float s = 1 / 4.0f; - level->addParticle(eParticleType_bubble, x - xd * s, y - yd * s, z - zd * s, xd, yd, zd); - } - inertia = 0.80f; - } - - xd *= inertia; - yd *= inertia; - zd *= inertia; - yd -= gravity; - - setPos(x, y, z); -} - -float Throwable::getGravity() -{ - return 0.03f; -} - - -void Throwable::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putShort(L"xTile", (short) xTile); - tag->putShort(L"yTile", (short) yTile); - tag->putShort(L"zTile", (short) zTile); - tag->putByte(L"inTile", (uint8_t) lastTile); - tag->putByte(L"shake", (uint8_t) shakeTime); - tag->putByte(L"inGround", (uint8_t) (inGround ? 1 : 0)); -} - -void Throwable::readAdditionalSaveData(CompoundTag *tag) -{ - xTile = tag->getShort(L"xTile"); - yTile = tag->getShort(L"yTile"); - zTile = tag->getShort(L"zTile"); - lastTile = tag->getByte(L"inTile") & 0xff; - shakeTime = tag->getByte(L"shake") & 0xff; - inGround = tag->getByte(L"inGround") == 1; -} - -float Throwable::getShadowHeightOffs() -{ - return 0; -} \ No newline at end of file +float Throwable::getShadowHeightOffs() { return 0; } \ No newline at end of file diff --git a/Minecraft.World/Entities/Throwable.h b/Minecraft.World/Entities/Throwable.h index 81f4caccd..33d5103ce 100644 --- a/Minecraft.World/Entities/Throwable.h +++ b/Minecraft.World/Entities/Throwable.h @@ -5,56 +5,56 @@ class Mob; class HitResult; -class Throwable : public Entity -{ +class Throwable : public Entity { private: - int xTile; - int yTile; - int zTile; - int lastTile; + int xTile; + int yTile; + int zTile; + int lastTile; protected: - bool inGround; + bool inGround; public: - int shakeTime; + int shakeTime; protected: - std::shared_ptr owner; + std::shared_ptr owner; private: - int life; - int flightTime; + int life; + int flightTime; - void _throwableInit(); + void _throwableInit(); public: - Throwable(Level *level); + Throwable(Level* level); protected: - virtual void defineSynchedData(); + virtual void defineSynchedData(); public: - virtual bool shouldRenderAtSqrDistance(double distance); + virtual bool shouldRenderAtSqrDistance(double distance); - Throwable(Level *level, std::shared_ptr mob); - Throwable(Level *level, double x, double y, double z); + Throwable(Level* level, std::shared_ptr mob); + Throwable(Level* level, double x, double y, double z); protected: - virtual float getThrowPower(); - virtual float getThrowUpAngleOffset(); + virtual float getThrowPower(); + virtual float getThrowUpAngleOffset(); public: - virtual void shoot(double xd, double yd, double zd, float pow, float uncertainty); - virtual void lerpMotion(double xd, double yd, double zd); - virtual void tick(); + virtual void shoot(double xd, double yd, double zd, float pow, + float uncertainty); + virtual void lerpMotion(double xd, double yd, double zd); + virtual void tick(); protected: - virtual float getGravity(); - virtual void onHit(HitResult *res) = 0; + virtual float getGravity(); + virtual void onHit(HitResult* res) = 0; public: - virtual void addAdditonalSaveData(CompoundTag *tag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual float getShadowHeightOffs(); + virtual void addAdditonalSaveData(CompoundTag* tag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual float getShadowHeightOffs(); }; \ No newline at end of file diff --git a/Minecraft.World/Entities/WaterAnimal.cpp b/Minecraft.World/Entities/WaterAnimal.cpp index a45d3fbbf..0815ed7bd 100644 --- a/Minecraft.World/Entities/WaterAnimal.cpp +++ b/Minecraft.World/Entities/WaterAnimal.cpp @@ -5,38 +5,24 @@ #include "../Headers/net.minecraft.world.level.h" #include "WaterAnimal.h" +WaterAnimal::WaterAnimal(Level* level) : PathfinderMob(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called - -WaterAnimal::WaterAnimal(Level *level) : PathfinderMob( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - - // This should only be called for the most derive classes - //this->defineSynchedData(); + // This should only be called for the most derive classes + // this->defineSynchedData(); } -bool WaterAnimal::isWaterMob() -{ - return true; //prevent drowning +bool WaterAnimal::isWaterMob() { + return true; // prevent drowning } -bool WaterAnimal::canSpawn() -{ - return level->isUnobstructed(bb); -} +bool WaterAnimal::canSpawn() { return level->isUnobstructed(bb); } -int WaterAnimal::getAmbientSoundInterval() -{ - return 20 * 6; -} +int WaterAnimal::getAmbientSoundInterval() { return 20 * 6; } -bool WaterAnimal::removeWhenFarAway() -{ - return true; -} +bool WaterAnimal::removeWhenFarAway() { return true; } -int WaterAnimal::getExperienceReward(std::shared_ptr killedBy) -{ - return 1 + level->random->nextInt(3); +int WaterAnimal::getExperienceReward(std::shared_ptr killedBy) { + return 1 + level->random->nextInt(3); } \ No newline at end of file diff --git a/Minecraft.World/Entities/WaterAnimal.h b/Minecraft.World/Entities/WaterAnimal.h index 59d1ed348..8fd66160b 100644 --- a/Minecraft.World/Entities/WaterAnimal.h +++ b/Minecraft.World/Entities/WaterAnimal.h @@ -4,15 +4,14 @@ class Player; -class WaterAnimal : public PathfinderMob, public Creature -{ +class WaterAnimal : public PathfinderMob, public Creature { public: - WaterAnimal(Level *level); - virtual bool isWaterMob(); - virtual bool canSpawn(); - virtual int getAmbientSoundInterval(); + WaterAnimal(Level* level); + virtual bool isWaterMob(); + virtual bool canSpawn(); + virtual int getAmbientSoundInterval(); protected: - virtual bool removeWhenFarAway(); - virtual int getExperienceReward(std::shared_ptr killedBy); + virtual bool removeWhenFarAway(); + virtual int getExperienceReward(std::shared_ptr killedBy); }; diff --git a/Minecraft.World/Headers/net.minecraft.network.packet.h b/Minecraft.World/Headers/net.minecraft.network.packet.h index 86951cbe7..a4837c3a4 100644 --- a/Minecraft.World/Headers/net.minecraft.network.packet.h +++ b/Minecraft.World/Headers/net.minecraft.network.packet.h @@ -99,4 +99,3 @@ #include "../Network/Packets/KickPlayerPacket.h" #include "../Network/Packets/XZPacket.h" #include "../Network/Packets/GameCommandPacket.h" - diff --git a/Minecraft.World/Headers/net.minecraft.world.ContainerListener.h b/Minecraft.World/Headers/net.minecraft.world.ContainerListener.h index c18b24d16..0e15abbe4 100644 --- a/Minecraft.World/Headers/net.minecraft.world.ContainerListener.h +++ b/Minecraft.World/Headers/net.minecraft.world.ContainerListener.h @@ -3,16 +3,17 @@ class SimpleContainer; // TODO 4J Stu -// There are 2 classes called ContainerListener. One in net.minecraft.world.inventory and -// another one in net.minecraft.world . To avoid clashes I have renamed both and put them in a namespace -// to avoid confusion. +// There are 2 classes called ContainerListener. One in +// net.minecraft.world.inventory and another one in net.minecraft.world . To +// avoid clashes I have renamed both and put them in a namespace to avoid +// confusion. -namespace net_minecraft_world -{ - class ContainerListener - { - friend class SimpleContainer; - private: - virtual void containerChanged(std::shared_ptr simpleContainer) = 0; - }; -} \ No newline at end of file +namespace net_minecraft_world { +class ContainerListener { + friend class SimpleContainer; + +private: + virtual void containerChanged( + std::shared_ptr simpleContainer) = 0; +}; +} // namespace net_minecraft_world \ No newline at end of file diff --git a/Minecraft.World/Headers/net.minecraft.world.entity.h b/Minecraft.World/Headers/net.minecraft.world.entity.h index f7084553d..9ed6f0223 100644 --- a/Minecraft.World/Headers/net.minecraft.world.entity.h +++ b/Minecraft.World/Headers/net.minecraft.world.entity.h @@ -19,7 +19,7 @@ // 1.0.1 #include "../Entities/MobType.h" -// TU9 +// TU9 #include "../Entities/Mobs/ItemFrame.h" // 1.2.3 diff --git a/Minecraft.World/Headers/net.minecraft.world.entity.projectile.h b/Minecraft.World/Headers/net.minecraft.world.entity.projectile.h index 152413e32..c04a67fce 100644 --- a/Minecraft.World/Headers/net.minecraft.world.entity.projectile.h +++ b/Minecraft.World/Headers/net.minecraft.world.entity.projectile.h @@ -12,7 +12,7 @@ #include "../Entities/Throwable.h" #include "../Entities/Mobs/ThrownEnderPearl.h" #include "../Entities/Mobs/ThrownPotion.h" -#include "../Entities/Mobs/ThrownExpBottle.h" // Brought forward from 1.2 +#include "../Entities/Mobs/ThrownExpBottle.h" // Brought forward from 1.2 // Added TU 9 #include "../Entities/Mobs/DragonFireball.h" \ No newline at end of file diff --git a/Minecraft.World/Headers/net.minecraft.world.inventory.ContainerListener.h b/Minecraft.World/Headers/net.minecraft.world.inventory.ContainerListener.h index b6908d624..c8cd968fb 100644 --- a/Minecraft.World/Headers/net.minecraft.world.inventory.ContainerListener.h +++ b/Minecraft.World/Headers/net.minecraft.world.inventory.ContainerListener.h @@ -3,19 +3,22 @@ class AbstractContainerMenu; // 4J Stu -// There are 2 classes called ContainerListener. Once here in net.minecraft.world.inventory and -// another once in net.minecraft.world . To avoid clashes I have renamed both and put them in a namespace -// to avoid confusion. +// There are 2 classes called ContainerListener. Once here in +// net.minecraft.world.inventory and another once in net.minecraft.world . To +// avoid clashes I have renamed both and put them in a namespace to avoid +// confusion. -namespace net_minecraft_world_inventory -{ - class ContainerListener - { - public: - virtual void refreshContainer(AbstractContainerMenu *container, std::vector > *items) = 0; +namespace net_minecraft_world_inventory { +class ContainerListener { +public: + virtual void refreshContainer( + AbstractContainerMenu* container, + std::vector >* items) = 0; - virtual void slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr item) = 0; + virtual void slotChanged(AbstractContainerMenu* container, int slotIndex, + std::shared_ptr item) = 0; - virtual void setContainerData(AbstractContainerMenu *container, int id, int value) = 0; - }; -} \ No newline at end of file + virtual void setContainerData(AbstractContainerMenu* container, int id, + int value) = 0; +}; +} // namespace net_minecraft_world_inventory \ No newline at end of file diff --git a/Minecraft.World/Headers/net.minecraft.world.item.h b/Minecraft.World/Headers/net.minecraft.world.item.h index 5e3c18667..97b310b3b 100644 --- a/Minecraft.World/Headers/net.minecraft.world.item.h +++ b/Minecraft.World/Headers/net.minecraft.world.item.h @@ -23,7 +23,7 @@ #include "../Items/TileItems/LeafTileItem.h" #include "../Items/MapItem.h" #include "../Items/MinecartItem.h" -//#include "PaintingItem.h" +// #include "PaintingItem.h" #include "../Items/PickaxeItem.h" #include "../Items/TileItems/PistonTileItem.h" #include "../Items/RecordingItem.h" @@ -56,8 +56,8 @@ #include "../Items/PotionItem.h" #include "../Util/Rarity.h" #include "../Items/TileItems/WaterLilyTileItem.h" -#include "../Items/ExperienceItem.h" // 4J Stu brought forward -#include "../Items/TileItems/SmoothStoneBrickTileItem.h" // 4J Stu brought forward +#include "../Items/ExperienceItem.h" // 4J Stu brought forward +#include "../Items/TileItems/SmoothStoneBrickTileItem.h" // 4J Stu brought forward // TU9 #include "../Items/FireChargeItem.h" diff --git a/Minecraft.World/Headers/net.minecraft.world.level.biome.h b/Minecraft.World/Headers/net.minecraft.world.level.biome.h index bd289c4c4..66861636e 100644 --- a/Minecraft.World/Headers/net.minecraft.world.level.biome.h +++ b/Minecraft.World/Headers/net.minecraft.world.level.biome.h @@ -1,6 +1,5 @@ #pragma once - #include "../WorldGen/Biomes/Biome.h" #include "../WorldGen/Biomes/ForestBiome.h" #include "../WorldGen/Biomes/HellBiome.h" @@ -28,5 +27,5 @@ // 1.1 #include "../WorldGen/Biomes/BeachBiome.h" -//1.2.3 +// 1.2.3 #include "../WorldGen/Biomes/JungleBiome.h" \ No newline at end of file diff --git a/Minecraft.World/Headers/net.minecraft.world.level.newbiome.layer.h b/Minecraft.World/Headers/net.minecraft.world.level.newbiome.layer.h index fbf356ca7..67dc6da9e 100644 --- a/Minecraft.World/Headers/net.minecraft.world.level.newbiome.layer.h +++ b/Minecraft.World/Headers/net.minecraft.world.level.newbiome.layer.h @@ -21,7 +21,7 @@ #include "../WorldGen/Layers/TemperatureMixerLayer.h" #include "../WorldGen/Layers/VoronoiZoom.h" #include "../WorldGen/Layers/ZoomLayer.h" -#include "../WorldGen/Layers/GrowMushroomIslandLayer.h" // 4J added +#include "../WorldGen/Layers/GrowMushroomIslandLayer.h" // 4J added // 1.1. #include "../WorldGen/Layers/RegionHillsLayer.h" diff --git a/Minecraft.World/Headers/net.minecraft.world.level.storage.h b/Minecraft.World/Headers/net.minecraft.world.level.storage.h index 69bd46c2e..7d9fc08d7 100644 --- a/Minecraft.World/Headers/net.minecraft.world.level.storage.h +++ b/Minecraft.World/Headers/net.minecraft.world.level.storage.h @@ -9,8 +9,9 @@ #include "../Level/Storage/LevelSummary.h" #include "../Level/Storage/McRegionLevelStorage.h" #include "../Level/Storage/McRegionLevelStorageSource.h" -//#include "../Level/Storage/MemoryLevelStorage.h" // 4J removed as unused -//#include "../Level/Storage/MemoryLevelStorageSource.h" // 4J removed as unused +// #include "../Level/Storage/MemoryLevelStorage.h" // 4J removed as unused +// #include "../Level/Storage/MemoryLevelStorageSource.h" // 4J removed as +// unused #include "../Level/Storage/MockedLevelStorage.h" #include "../Level/Storage/PlayerIO.h" #include "../Level/Storage/SavedDataStorage.h" diff --git a/Minecraft.World/Headers/net.minecraft.world.level.tile.h b/Minecraft.World/Headers/net.minecraft.world.level.tile.h index 06a1376a4..b28b21351 100644 --- a/Minecraft.World/Headers/net.minecraft.world.level.tile.h +++ b/Minecraft.World/Headers/net.minecraft.world.level.tile.h @@ -110,5 +110,3 @@ #include "../Blocks/HalfSlabTile.h" #include "../Blocks/WoodSlabTile.h" #include "../Blocks/WoolCarpetTile.h" - - diff --git a/Minecraft.World/IO/Files/ConsoleSaveFile.h b/Minecraft.World/IO/Files/ConsoleSaveFile.h index 63679bfac..0f9481ade 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFile.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFile.h @@ -3,62 +3,67 @@ #include "FileHeader.h" #include "ConsoleSavePath.h" -enum class SaveFileSeekOrigin -{ - Begin, - Current, - End -}; +enum class SaveFileSeekOrigin { Begin, Current, End }; -class ConsoleSaveFile -{ +class ConsoleSaveFile { public: - virtual ~ConsoleSaveFile() {}; + virtual ~ConsoleSaveFile() {}; - virtual FileEntry *createFile( const ConsoleSavePath &fileName ) = 0; - virtual void deleteFile( FileEntry *file ) = 0; - virtual void setFilePointer( FileEntry *file, unsigned int distanceToMove, SaveFileSeekOrigin seekOrigin ) = 0; - virtual bool writeFile( FileEntry *file, const void *lpBuffer, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) = 0; - virtual bool zeroFile(FileEntry *file, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) = 0; - virtual bool readFile( FileEntry *file, void *lpBuffer, unsigned int nNumberOfBytesToRead, unsigned int *lpNumberOfBytesRead ) = 0; - virtual bool closeHandle( FileEntry *file ) = 0; - virtual void finalizeWrite() = 0; - virtual void tick() {}; + virtual FileEntry* createFile(const ConsoleSavePath& fileName) = 0; + virtual void deleteFile(FileEntry* file) = 0; + virtual void setFilePointer(FileEntry* file, unsigned int distanceToMove, + SaveFileSeekOrigin seekOrigin) = 0; + virtual bool writeFile(FileEntry* file, const void* lpBuffer, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) = 0; + virtual bool zeroFile(FileEntry* file, unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) = 0; + virtual bool readFile(FileEntry* file, void* lpBuffer, + unsigned int nNumberOfBytesToRead, + unsigned int* lpNumberOfBytesRead) = 0; + virtual bool closeHandle(FileEntry* file) = 0; + virtual void finalizeWrite() = 0; + virtual void tick() {}; - virtual bool doesFileExist(ConsoleSavePath file) = 0; + virtual bool doesFileExist(ConsoleSavePath file) = 0; - virtual void Flush(bool autosave, bool updateThumbnail = true) = 0; + virtual void Flush(bool autosave, bool updateThumbnail = true) = 0; #ifndef _CONTENT_PACKAGE - virtual void DebugFlushToFile(void *compressedData = NULL, unsigned int compressedDataSize = 0) = 0; + virtual void DebugFlushToFile(void* compressedData = NULL, + unsigned int compressedDataSize = 0) = 0; #endif - virtual unsigned int getSizeOnDisk() = 0; - virtual std::wstring getFilename() = 0; - virtual std::vector *getFilesWithPrefix(const std::wstring &prefix) = 0; - virtual std::vector *getRegionFilesByDimension(unsigned int dimensionIndex) = 0; + virtual unsigned int getSizeOnDisk() = 0; + virtual std::wstring getFilename() = 0; + virtual std::vector* getFilesWithPrefix( + const std::wstring& prefix) = 0; + virtual std::vector* getRegionFilesByDimension( + unsigned int dimensionIndex) = 0; #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - virtual std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID) = 0; - virtual std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID) = 0; - virtual std::vector *getValidPlayerDatFiles() = 0; -#endif //__PS3__ + virtual std::wstring getPlayerDataFilenameForLoad( + const PlayerUID& pUID) = 0; + virtual std::wstring getPlayerDataFilenameForSave( + const PlayerUID& pUID) = 0; + virtual std::vector* getValidPlayerDatFiles() = 0; +#endif //__PS3__ - virtual int getSaveVersion() = 0; - virtual int getOriginalSaveVersion() = 0; + virtual int getSaveVersion() = 0; + virtual int getOriginalSaveVersion() = 0; - virtual void LockSaveAccess() = 0; - virtual void ReleaseSaveAccess() = 0; + virtual void LockSaveAccess() = 0; + virtual void ReleaseSaveAccess() = 0; - virtual ESavePlatform getSavePlatform() = 0; - virtual bool isSaveEndianDifferent() = 0; - virtual void setLocalPlatform() = 0; - virtual void setPlatform(ESavePlatform plat) = 0; - virtual ByteOrder getSaveEndian() = 0; - virtual ByteOrder getLocalEndian() = 0; - virtual void setEndian(ByteOrder endian) = 0; + virtual ESavePlatform getSavePlatform() = 0; + virtual bool isSaveEndianDifferent() = 0; + virtual void setLocalPlatform() = 0; + virtual void setPlatform(ESavePlatform plat) = 0; + virtual ByteOrder getSaveEndian() = 0; + virtual ByteOrder getLocalEndian() = 0; + virtual void setEndian(ByteOrder endian) = 0; - virtual void ConvertRegionFile(File sourceFile) = 0; - virtual void ConvertToLocalPlatform() = 0; + virtual void ConvertRegionFile(File sourceFile) = 0; + virtual void ConvertToLocalPlatform() = 0; - virtual void *getWritePointer(FileEntry *file) { return NULL; } + virtual void* getWritePointer(FileEntry* file) { return NULL; } }; diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileConverter.cpp b/Minecraft.World/IO/Files/ConsoleSaveFileConverter.cpp index 819156385..644c62f7d 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileConverter.cpp +++ b/Minecraft.World/IO/Files/ConsoleSaveFileConverter.cpp @@ -5,290 +5,305 @@ #include "ConsoleSaveFileConverter.h" #include "../../Util/ProgressListener.h" -void ConsoleSaveFileConverter::ProcessSimpleFile(ConsoleSaveFile *sourceSave, FileEntry *sourceFileEntry, ConsoleSaveFile *targetSave, FileEntry *targetFileEntry) -{ - unsigned int numberOfBytesRead = 0; - unsigned int numberOfBytesWritten = 0; +void ConsoleSaveFileConverter::ProcessSimpleFile(ConsoleSaveFile* sourceSave, + FileEntry* sourceFileEntry, + ConsoleSaveFile* targetSave, + FileEntry* targetFileEntry) { + unsigned int numberOfBytesRead = 0; + unsigned int numberOfBytesWritten = 0; - std::uint8_t *data = new std::uint8_t[sourceFileEntry->getFileSize()]; + std::uint8_t* data = new std::uint8_t[sourceFileEntry->getFileSize()]; - // Read from source - sourceSave->readFile(sourceFileEntry, data, sourceFileEntry->getFileSize(), &numberOfBytesRead); + // Read from source + sourceSave->readFile(sourceFileEntry, data, sourceFileEntry->getFileSize(), + &numberOfBytesRead); - // Write back to target - targetSave->writeFile(targetFileEntry, data, numberOfBytesRead, &numberOfBytesWritten); + // Write back to target + targetSave->writeFile(targetFileEntry, data, numberOfBytesRead, + &numberOfBytesWritten); - delete [] data; + delete[] data; } -void ConsoleSaveFileConverter::ProcessStandardRegionFile(ConsoleSaveFile *sourceSave, File sourceFile, ConsoleSaveFile *targetSave, File targetFile) -{ - unsigned int numberOfBytesWritten = 0; - unsigned int numberOfBytesRead = 0; +void ConsoleSaveFileConverter::ProcessStandardRegionFile( + ConsoleSaveFile* sourceSave, File sourceFile, ConsoleSaveFile* targetSave, + File targetFile) { + unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesRead = 0; - RegionFile sourceRegionFile(sourceSave, &sourceFile); - RegionFile targetRegionFile(targetSave, &targetFile); + RegionFile sourceRegionFile(sourceSave, &sourceFile); + RegionFile targetRegionFile(targetSave, &targetFile); - for(unsigned int x = 0; x < 32; ++x) - { - for(unsigned int z = 0; z < 32; ++z) - { - DataInputStream *dis = sourceRegionFile.getChunkDataInputStream(x,z); + for (unsigned int x = 0; x < 32; ++x) { + for (unsigned int z = 0; z < 32; ++z) { + DataInputStream* dis = + sourceRegionFile.getChunkDataInputStream(x, z); - if(dis) - { - int read = dis->read(); - DataOutputStream *dos = targetRegionFile.getChunkDataOutputStream(x,z); - while(read != -1) - { + if (dis) { + int read = dis->read(); + DataOutputStream* dos = + targetRegionFile.getChunkDataOutputStream(x, z); + while (read != -1) { + dos->write(read & 0xff); - dos->write( read & 0xff ); + read = dis->read(); + } + dos->close(); + dos->deleteChildStream(); + delete dos; + } - read = dis->read(); - } - dos->close(); - dos->deleteChildStream(); - delete dos; - } - - delete dis; - } - } + delete dis; + } + } } -void ConsoleSaveFileConverter::ConvertSave(ConsoleSaveFile *sourceSave, ConsoleSaveFile *targetSave, ProgressListener *progress) -{ - // Process level.dat - ConsoleSavePath ldatPath( std::wstring(L"level.dat") ); - FileEntry *sourceLdatFe = sourceSave->createFile( ldatPath ); - FileEntry *targetLdatFe = targetSave->createFile( ldatPath ); - printf("Processing level.dat\n"); - ProcessSimpleFile(sourceSave, sourceLdatFe, targetSave, targetLdatFe); +void ConsoleSaveFileConverter::ConvertSave(ConsoleSaveFile* sourceSave, + ConsoleSaveFile* targetSave, + ProgressListener* progress) { + // Process level.dat + ConsoleSavePath ldatPath(std::wstring(L"level.dat")); + FileEntry* sourceLdatFe = sourceSave->createFile(ldatPath); + FileEntry* targetLdatFe = targetSave->createFile(ldatPath); + printf("Processing level.dat\n"); + ProcessSimpleFile(sourceSave, sourceLdatFe, targetSave, targetLdatFe); - // Process game rules - { - ConsoleSavePath gameRulesPath( GAME_RULE_SAVENAME ); - if(sourceSave->doesFileExist(gameRulesPath) ) - { - FileEntry *sourceFe = sourceSave->createFile( gameRulesPath ); - FileEntry *targetFe = targetSave->createFile( gameRulesPath ); - printf("Processing game rules\n"); - ProcessSimpleFile(sourceSave, sourceFe, targetSave, targetFe); - } - } + // Process game rules + { + ConsoleSavePath gameRulesPath(GAME_RULE_SAVENAME); + if (sourceSave->doesFileExist(gameRulesPath)) { + FileEntry* sourceFe = sourceSave->createFile(gameRulesPath); + FileEntry* targetFe = targetSave->createFile(gameRulesPath); + printf("Processing game rules\n"); + ProcessSimpleFile(sourceSave, sourceFe, targetSave, targetFe); + } + } - // MGH added - find any player data files and copy them across + // MGH added - find any player data files and copy them across #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - std::vector* playerFiles = sourceSave->getValidPlayerDatFiles(); + std::vector* playerFiles = sourceSave->getValidPlayerDatFiles(); #else - std::vector *playerFiles = sourceSave->getFilesWithPrefix( DirectoryLevelStorage::getPlayerDir() ); + std::vector* playerFiles = + sourceSave->getFilesWithPrefix(DirectoryLevelStorage::getPlayerDir()); #endif - if(playerFiles != NULL) - { - for(int fileIdx = 0; fileIdx < playerFiles->size();fileIdx++) - { - ConsoleSavePath sourcePlayerDatPath( playerFiles->at(fileIdx)->data.filename ); + if (playerFiles != NULL) { + for (int fileIdx = 0; fileIdx < playerFiles->size(); fileIdx++) { + ConsoleSavePath sourcePlayerDatPath( + playerFiles->at(fileIdx)->data.filename); #ifdef _XBOX_ONE - // 4J Stu - As the XUIDs on X360 and X1 are different, we don't want to transfer these over. However as the first player - // file should be the owner of the save, we can move their data over to the current players XUID - if(fileIdx > 0) break; - PlayerUID xuid; - ProfileManager.GetXUID(ProfileManager.GetPrimaryPad(), &xuid, false); - ConsoleSavePath targetPlayerDatPath( L"players/" + xuid.toString() + L".dat" ); + // 4J Stu - As the XUIDs on X360 and X1 are different, we don't want + // to transfer these over. However as the first player file should + // be the owner of the save, we can move their data over to the + // current players XUID + if (fileIdx > 0) break; + PlayerUID xuid; + ProfileManager.GetXUID(ProfileManager.GetPrimaryPad(), &xuid, + false); + ConsoleSavePath targetPlayerDatPath(L"players/" + xuid.toString() + + L".dat"); #else - ConsoleSavePath targetPlayerDatPath( playerFiles->at(fileIdx)->data.filename ); + ConsoleSavePath targetPlayerDatPath( + playerFiles->at(fileIdx)->data.filename); #endif - { - FileEntry *sourceFe = sourceSave->createFile( sourcePlayerDatPath ); - FileEntry *targetFe = targetSave->createFile( targetPlayerDatPath ); - wprintf(L"Processing player dat file %ls\n", playerFiles->at(fileIdx)->data.filename); - ProcessSimpleFile(sourceSave, sourceFe, targetSave, targetFe); - - targetFe->data.lastModifiedTime = sourceFe->data.lastModifiedTime; - } - } - delete playerFiles; - } + { + FileEntry* sourceFe = + sourceSave->createFile(sourcePlayerDatPath); + FileEntry* targetFe = + targetSave->createFile(targetPlayerDatPath); + wprintf(L"Processing player dat file %ls\n", + playerFiles->at(fileIdx)->data.filename); + ProcessSimpleFile(sourceSave, sourceFe, targetSave, targetFe); + targetFe->data.lastModifiedTime = + sourceFe->data.lastModifiedTime; + } + } + delete playerFiles; + } #ifdef SPLIT_SAVES - int xzSize = LEVEL_LEGACY_WIDTH; - int hellScale = HELL_LEVEL_LEGACY_SCALE; - if ( sourceSave->doesFileExist( ldatPath ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(sourceSave, ldatPath); - CompoundTag *root = NbtIo::readCompressed(&fis); - CompoundTag *tag = root->getCompound(L"Data"); - LevelData ret(tag); + int xzSize = LEVEL_LEGACY_WIDTH; + int hellScale = HELL_LEVEL_LEGACY_SCALE; + if (sourceSave->doesFileExist(ldatPath)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(sourceSave, ldatPath); + CompoundTag* root = NbtIo::readCompressed(&fis); + CompoundTag* tag = root->getCompound(L"Data"); + LevelData ret(tag); - xzSize = ret.getXZSize(); - hellScale = ret.getHellScale(); + xzSize = ret.getXZSize(); + hellScale = ret.getHellScale(); - delete root; - } + delete root; + } - RegionFileCache sourceCache; - RegionFileCache targetCache; + RegionFileCache sourceCache; + RegionFileCache targetCache; - if(progress) - { - progress->progressStage(IDS_SAVETRANSFER_STAGE_CONVERTING); - } + if (progress) { + progress->progressStage(IDS_SAVETRANSFER_STAGE_CONVERTING); + } - // Overworld - { - printf("Processing the overworld\n"); - int halfXZSize = xzSize / 2; + // Overworld + { + printf("Processing the overworld\n"); + int halfXZSize = xzSize / 2; - int progressTarget = (xzSize) * (xzSize); - int currentProgress = 0; - if(progress) progress->progressStagePercentage((currentProgress*100)/progressTarget); + int progressTarget = (xzSize) * (xzSize); + int currentProgress = 0; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); - for(int x = -halfXZSize; x < halfXZSize; ++x) - { - for(int z = -halfXZSize; z < halfXZSize; ++z) - { - //printf("Processing overworld chunk %d,%d\n",x,z); - DataInputStream *dis = sourceCache._getChunkDataInputStream(sourceSave,L"",x,z); + for (int x = -halfXZSize; x < halfXZSize; ++x) { + for (int z = -halfXZSize; z < halfXZSize; ++z) { + // printf("Processing overworld chunk %d,%d\n",x,z); + DataInputStream* dis = + sourceCache._getChunkDataInputStream(sourceSave, L"", x, z); - if(dis) - { - int read = dis->read(); - DataOutputStream *dos = targetCache._getChunkDataOutputStream(targetSave,L"",x,z); - BufferedOutputStream bos(dos, 1024 * 1024); - while(read != -1) - { + if (dis) { + int read = dis->read(); + DataOutputStream* dos = + targetCache._getChunkDataOutputStream(targetSave, L"", + x, z); + BufferedOutputStream bos(dos, 1024 * 1024); + while (read != -1) { + bos.write(read & 0xff); - bos.write( read & 0xff ); + read = dis->read(); + } + bos.flush(); + dos->close(); + dos->deleteChildStream(); + delete dos; + } - read = dis->read(); - } - bos.flush(); - dos->close(); - dos->deleteChildStream(); - delete dos; - } + delete dis; - delete dis; + ++currentProgress; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); + } + } + } - ++currentProgress; - if(progress) progress->progressStagePercentage( (currentProgress*100)/progressTarget); + // Nether + { + printf("Processing the nether\n"); + int hellSize = xzSize / hellScale; + int halfXZSize = hellSize / 2; - } - } - } + int progressTarget = (hellSize) * (hellSize); + int currentProgress = 0; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); - // Nether - { - printf("Processing the nether\n"); - int hellSize = xzSize / hellScale; - int halfXZSize = hellSize / 2; + for (int x = -halfXZSize; x < halfXZSize; ++x) { + for (int z = -halfXZSize; z < halfXZSize; ++z) { + // printf("Processing nether chunk %d,%d\n",x,z); + DataInputStream* dis = sourceCache._getChunkDataInputStream( + sourceSave, L"DIM-1", x, z); - int progressTarget = (hellSize) * (hellSize); - int currentProgress = 0; - if(progress) progress->progressStagePercentage((currentProgress*100)/progressTarget); + if (dis) { + int read = dis->read(); + DataOutputStream* dos = + targetCache._getChunkDataOutputStream(targetSave, + L"DIM-1", x, z); + BufferedOutputStream bos(dos, 1024 * 1024); + while (read != -1) { + bos.write(read & 0xff); - for(int x = -halfXZSize; x < halfXZSize; ++x) - { - for(int z = -halfXZSize; z < halfXZSize; ++z) - { - //printf("Processing nether chunk %d,%d\n",x,z); - DataInputStream *dis = sourceCache._getChunkDataInputStream(sourceSave,L"DIM-1",x,z); + read = dis->read(); + } + bos.flush(); + dos->close(); + dos->deleteChildStream(); + delete dos; + } - if(dis) - { - int read = dis->read(); - DataOutputStream *dos = targetCache._getChunkDataOutputStream(targetSave,L"DIM-1",x,z); - BufferedOutputStream bos(dos, 1024 * 1024); - while(read != -1) - { + delete dis; - bos.write( read & 0xff ); + ++currentProgress; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); + } + } + } - read = dis->read(); - } - bos.flush(); - dos->close(); - dos->deleteChildStream(); - delete dos; - } + // End + { + printf("Processing the end\n"); + int halfXZSize = END_LEVEL_MAX_WIDTH / 2; - delete dis; + int progressTarget = (END_LEVEL_MAX_WIDTH) * (END_LEVEL_MAX_WIDTH); + int currentProgress = 0; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); - ++currentProgress; - if(progress) progress->progressStagePercentage((currentProgress*100)/progressTarget); - } - } - } + for (int x = -halfXZSize; x < halfXZSize; ++x) { + for (int z = -halfXZSize; z < halfXZSize; ++z) { + // printf("Processing end chunk %d,%d\n",x,z); + DataInputStream* dis = sourceCache._getChunkDataInputStream( + sourceSave, L"DIM1/", x, z); - // End - { - printf("Processing the end\n"); - int halfXZSize = END_LEVEL_MAX_WIDTH / 2; + if (dis) { + int read = dis->read(); + DataOutputStream* dos = + targetCache._getChunkDataOutputStream(targetSave, + L"DIM1/", x, z); + BufferedOutputStream bos(dos, 1024 * 1024); + while (read != -1) { + bos.write(read & 0xff); - int progressTarget = (END_LEVEL_MAX_WIDTH) * (END_LEVEL_MAX_WIDTH); - int currentProgress = 0; - if(progress) progress->progressStagePercentage((currentProgress*100)/progressTarget); + read = dis->read(); + } + bos.flush(); + dos->close(); + dos->deleteChildStream(); + delete dos; + } - for(int x = -halfXZSize; x < halfXZSize; ++x) - { - for(int z = -halfXZSize; z < halfXZSize; ++z) - { - //printf("Processing end chunk %d,%d\n",x,z); - DataInputStream *dis = sourceCache._getChunkDataInputStream(sourceSave,L"DIM1/",x,z); + delete dis; - if(dis) - { - int read = dis->read(); - DataOutputStream *dos = targetCache._getChunkDataOutputStream(targetSave,L"DIM1/",x,z); - BufferedOutputStream bos(dos, 1024 * 1024); - while(read != -1) - { - - bos.write( read & 0xff ); - - read = dis->read(); - } - bos.flush(); - dos->close(); - dos->deleteChildStream(); - delete dos; - } - - delete dis; - - ++currentProgress; - if(progress) progress->progressStagePercentage((currentProgress*100)/progressTarget); - } - } - } + ++currentProgress; + if (progress) + progress->progressStagePercentage((currentProgress * 100) / + progressTarget); + } + } + } #else - // 4J Stu - Old version that just changes the compression of chunks, not usable for XboxOne style split saves or compressed tile formats - // Process region files - std::vector *allFilesInSave = sourceSave->getFilesWithPrefix(std::wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) - { - FileEntry *fe = *it; - if( fe != sourceLdatFe ) - { - std::wstring fName( fe->data.filename ); - std::wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) - { + // 4J Stu - Old version that just changes the compression of chunks, not + // usable for XboxOne style split saves or compressed tile formats Process + // region files + std::vector* allFilesInSave = + sourceSave->getFilesWithPrefix(std::wstring(L"")); + for (AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); + ++it) { + FileEntry* fe = *it; + if (fe != sourceLdatFe) { + std::wstring fName(fe->data.filename); + std::wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), + suffix) == 0) { #ifndef _CONTENT_PACKAGE - wprintf(L"Processing a region file: %s\n", fe->data.filename); + wprintf(L"Processing a region file: %s\n", fe->data.filename); #endif - ProcessStandardRegionFile(sourceSave, File(fe->data.filename), targetSave, File(fe->data.filename) ); - } - else - { + ProcessStandardRegionFile(sourceSave, File(fe->data.filename), + targetSave, File(fe->data.filename)); + } else { #ifndef _CONTENT_PACKAGE - wprintf(L"%s is not a region file, ignoring\n", fe->data.filename); + wprintf(L"%s is not a region file, ignoring\n", + fe->data.filename); #endif - } - } - } + } + } + } #endif } diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileConverter.h b/Minecraft.World/IO/Files/ConsoleSaveFileConverter.h index e258b6523..e6005dde5 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileConverter.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFileConverter.h @@ -4,13 +4,21 @@ class FileEntry; class ConsoleSaveFile; class ProgressRenderer; -// 4J Stu - This code is taken from the standalone save converter tool, and modified slightly -class ConsoleSaveFileConverter -{ +// 4J Stu - This code is taken from the standalone save converter tool, and +// modified slightly +class ConsoleSaveFileConverter { private: - static void ProcessSimpleFile(ConsoleSaveFile *sourceSave, FileEntry *sourceFileEntry, ConsoleSaveFile *targetSave, FileEntry *targetFileEntry); - static void ProcessStandardRegionFile(ConsoleSaveFile *sourceSave, File sourceFile, ConsoleSaveFile *targetSave, File targetFile); + static void ProcessSimpleFile(ConsoleSaveFile* sourceSave, + FileEntry* sourceFileEntry, + ConsoleSaveFile* targetSave, + FileEntry* targetFileEntry); + static void ProcessStandardRegionFile(ConsoleSaveFile* sourceSave, + File sourceFile, + ConsoleSaveFile* targetSave, + File targetFile); public: - static void ConvertSave(ConsoleSaveFile *sourceSave, ConsoleSaveFile *targetSave, ProgressListener *progress); + static void ConvertSave(ConsoleSaveFile* sourceSave, + ConsoleSaveFile* targetSave, + ProgressListener* progress); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.cpp b/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.cpp index 7f60b210e..73cba98ad 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.cpp +++ b/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.cpp @@ -4,131 +4,117 @@ #include "ConsoleSaveFile.h" #include "ConsoleSaveFileInputStream.h" -ConsoleSaveFileInputStream::ConsoleSaveFileInputStream(ConsoleSaveFile *saveFile, const ConsoleSavePath &file) -{ - m_saveFile = saveFile; - m_file = m_saveFile->createFile( file ); +ConsoleSaveFileInputStream::ConsoleSaveFileInputStream( + ConsoleSaveFile* saveFile, const ConsoleSavePath& file) { + m_saveFile = saveFile; + m_file = m_saveFile->createFile(file); - m_saveFile->setFilePointer( m_file, 0, SaveFileSeekOrigin::Begin ); + m_saveFile->setFilePointer(m_file, 0, SaveFileSeekOrigin::Begin); } -ConsoleSaveFileInputStream::ConsoleSaveFileInputStream(ConsoleSaveFile *saveFile, FileEntry *file) -{ - m_saveFile = saveFile; - m_file = file; +ConsoleSaveFileInputStream::ConsoleSaveFileInputStream( + ConsoleSaveFile* saveFile, FileEntry* file) { + m_saveFile = saveFile; + m_file = file; - m_saveFile->setFilePointer( m_file, 0, SaveFileSeekOrigin::Begin ); + m_saveFile->setFilePointer(m_file, 0, SaveFileSeekOrigin::Begin); } -//Reads a byte of data from this input stream. This method blocks if no input is yet available. -//Returns: -//the next byte of data, or -1 if the end of the file is reached. -int ConsoleSaveFileInputStream::read() -{ - std::uint8_t byteRead = static_cast(0); - unsigned int numberOfBytesRead; +// Reads a byte of data from this input stream. This method blocks if no input +// is yet available. Returns: the next byte of data, or -1 if the end of the +// file is reached. +int ConsoleSaveFileInputStream::read() { + std::uint8_t byteRead = static_cast(0); + unsigned int numberOfBytesRead; - bool result = m_saveFile->readFile( - m_file, - &byteRead, // data buffer - 1, // number of bytes to read - &numberOfBytesRead // number of bytes read - ); + bool result = + m_saveFile->readFile(m_file, + &byteRead, // data buffer + 1, // number of bytes to read + &numberOfBytesRead // number of bytes read + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return static_cast(byteRead); + return static_cast(byteRead); } -//Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. -//Parameters: -//b - the buffer into which the data is read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. -int ConsoleSaveFileInputStream::read(byteArray b) -{ - unsigned int numberOfBytesRead; +// Reads up to b.length bytes of data from this input stream into an array of +// bytes. This method blocks until some input is available. Parameters: b - the +// buffer into which the data is read. Returns: the total number of bytes read +// into the buffer, or -1 if there is no more data because the end of the file +// has been reached. +int ConsoleSaveFileInputStream::read(byteArray b) { + unsigned int numberOfBytesRead; - bool result = m_saveFile->readFile( - m_file, - &b.data, // data buffer - b.length, // number of bytes to read - &numberOfBytesRead // number of bytes read - ); + bool result = + m_saveFile->readFile(m_file, + &b.data, // data buffer + b.length, // number of bytes to read + &numberOfBytesRead // number of bytes read + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return numberOfBytesRead; + return numberOfBytesRead; } -//Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input -//is available; otherwise, no bytes are read and 0 is returned. -//Parameters: -//b - the buffer into which the data is read. -//off - the start offset in the destination array b -//len - the maximum number of bytes read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. -int ConsoleSaveFileInputStream::read(byteArray b, unsigned int offset, unsigned int length) -{ - // 4J Stu - We don't want to read any more than the array buffer can hold - assert( length <= ( b.length - offset ) ); +// Reads up to len bytes of data from this input stream into an array of bytes. +// If len is not zero, the method blocks until some input is available; +// otherwise, no bytes are read and 0 is returned. Parameters: b - the buffer +// into which the data is read. off - the start offset in the destination array +// b len - the maximum number of bytes read. Returns: the total number of bytes +// read into the buffer, or -1 if there is no more data because the end of the +// file has been reached. +int ConsoleSaveFileInputStream::read(byteArray b, unsigned int offset, + unsigned int length) { + // 4J Stu - We don't want to read any more than the array buffer can hold + assert(length <= (b.length - offset)); - unsigned int numberOfBytesRead; + unsigned int numberOfBytesRead; - bool result = m_saveFile->readFile( - m_file, - &b[offset], // data buffer - length, // number of bytes to read - &numberOfBytesRead // number of bytes read - ); + bool result = + m_saveFile->readFile(m_file, + &b[offset], // data buffer + length, // number of bytes to read + &numberOfBytesRead // number of bytes read + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return numberOfBytesRead; + return numberOfBytesRead; } -//Closes this file input stream and releases any system resources associated with the stream. -//If this stream has an associated channel then the channel is closed as well. -void ConsoleSaveFileInputStream::close() -{ - if( m_saveFile != NULL ) - { - bool result = m_saveFile->closeHandle( m_file ); +// Closes this file input stream and releases any system resources associated +// with the stream. If this stream has an associated channel then the channel is +// closed as well. +void ConsoleSaveFileInputStream::close() { + if (m_saveFile != NULL) { + bool result = m_saveFile->closeHandle(m_file); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + } - // Stop the dtor from trying to close it again - m_saveFile = NULL; - } + // Stop the dtor from trying to close it again + m_saveFile = NULL; + } } diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.h b/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.h index c10b843ea..eb295878a 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFileInputStream.h @@ -1,5 +1,6 @@ #pragma once -// 4J Stu - Implements the Java InputStream but rather than writing directly to disc it writes through the save file +// 4J Stu - Implements the Java InputStream but rather than writing directly to +// disc it writes through the save file #include "../Streams/InputStream.h" @@ -8,19 +9,18 @@ class ConsoleSaveFile; class FileEntry; -class ConsoleSaveFileInputStream : public InputStream -{ +class ConsoleSaveFileInputStream : public InputStream { public: - ConsoleSaveFileInputStream(ConsoleSaveFile *saveFile, const ConsoleSavePath &file); - ConsoleSaveFileInputStream(ConsoleSaveFile *saveFile, FileEntry *file); - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual __int64 skip(__int64 n) { return n; } + ConsoleSaveFileInputStream(ConsoleSaveFile* saveFile, + const ConsoleSavePath& file); + ConsoleSaveFileInputStream(ConsoleSaveFile* saveFile, FileEntry* file); + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual __int64 skip(__int64 n) { return n; } private: - ConsoleSaveFile *m_saveFile; - FileEntry *m_file; - + ConsoleSaveFile* m_saveFile; + FileEntry* m_file; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.cpp b/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.cpp index d3030fdd4..f8bbd6d57 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.cpp +++ b/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.cpp @@ -14,1056 +14,1068 @@ #include "../../Headers/net.minecraft.world.level.chunk.storage.h" #ifdef _XBOX -#define RESERVE_ALLOCATION MEM_RESERVE | MEM_LARGE_PAGES -#define COMMIT_ALLOCATION MEM_COMMIT | MEM_LARGE_PAGES +#define RESERVE_ALLOCATION MEM_RESERVE | MEM_LARGE_PAGES +#define COMMIT_ALLOCATION MEM_COMMIT | MEM_LARGE_PAGES #else -#define RESERVE_ALLOCATION MEM_RESERVE -#define COMMIT_ALLOCATION MEM_COMMIT +#define RESERVE_ALLOCATION MEM_RESERVE +#define COMMIT_ALLOCATION MEM_COMMIT #endif unsigned int ConsoleSaveFileOriginal::pagesCommitted = 0; -void *ConsoleSaveFileOriginal::pvHeap = NULL; +void* ConsoleSaveFileOriginal::pvHeap = NULL; -ConsoleSaveFileOriginal::ConsoleSaveFileOriginal(const std::wstring &fileName, void *pvSaveData /*= NULL*/, unsigned int initialFileSize /*= 0*/, bool forceCleanSave /*= false*/, ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL*/) -{ - InitializeCriticalSectionAndSpinCount(&m_lock,5120); +ConsoleSaveFileOriginal::ConsoleSaveFileOriginal( + const std::wstring& fileName, void* pvSaveData /*= NULL*/, + unsigned int initialFileSize /*= 0*/, bool forceCleanSave /*= false*/, + ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL*/) { + InitializeCriticalSectionAndSpinCount(&m_lock, 5120); - // One time initialise of static stuff required for our storage - if( pvHeap == NULL ) - { - // Reserve a chunk of 64MB of virtual address space for our saves, using 64KB pages. - // We'll only be committing these as required to grow the storage we need, which will - // the storage to grow without having to use realloc. + // One time initialise of static stuff required for our storage + if (pvHeap == NULL) { + // Reserve a chunk of 64MB of virtual address space for our saves, using + // 64KB pages. We'll only be committing these as required to grow the + // storage we need, which will the storage to grow without having to use + // realloc. - // AP - The Vita doesn't have virtual memory so a pretend system has been implemented in PSVitaStubs.cpp. - // All access to the memory must be done via the access function as the pointer returned from VirtualAlloc - // can't be used directly. - pvHeap = VirtualAlloc(NULL, MAX_PAGE_COUNT * CSF_PAGE_SIZE, RESERVE_ALLOCATION, PAGE_READWRITE ); - } + // AP - The Vita doesn't have virtual memory so a pretend system has + // been implemented in PSVitaStubs.cpp. All access to the memory must be + // done via the access function as the pointer returned from + // VirtualAlloc can't be used directly. + pvHeap = VirtualAlloc(NULL, MAX_PAGE_COUNT * CSF_PAGE_SIZE, + RESERVE_ALLOCATION, PAGE_READWRITE); + } - pvSaveMem = pvHeap; - m_fileName = fileName; + pvSaveMem = pvHeap; + m_fileName = fileName; - unsigned int fileSize = initialFileSize; + unsigned int fileSize = initialFileSize; - // Load a save from the game rules - bool bLevelGenBaseSave = false; - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if( pvSaveData == NULL && levelGen != NULL && levelGen->requiresBaseSave()) - { - pvSaveData = levelGen->getBaseSaveData(fileSize); - if(pvSaveData && fileSize != 0) bLevelGenBaseSave = true; - } + // Load a save from the game rules + bool bLevelGenBaseSave = false; + LevelGenerationOptions* levelGen = app.getLevelGenerationOptions(); + if (pvSaveData == NULL && levelGen != NULL && + levelGen->requiresBaseSave()) { + pvSaveData = levelGen->getBaseSaveData(fileSize); + if (pvSaveData && fileSize != 0) bLevelGenBaseSave = true; + } - if( pvSaveData == NULL || fileSize == 0) - fileSize = StorageManager.GetSaveSize(); + if (pvSaveData == NULL || fileSize == 0) + fileSize = StorageManager.GetSaveSize(); - if( forceCleanSave ) - fileSize = 0; + if (forceCleanSave) fileSize = 0; - unsigned int heapSize = std::max(fileSize, 1024u * 1024u * 2u); // 4J Stu - Our files are going to be bigger than 2MB so allocate high to start with + unsigned int heapSize = std::max( + fileSize, + 1024u * 1024u * 2u); // 4J Stu - Our files are going to be bigger than + // 2MB so allocate high to start with - // Initially committ enough room to store headSize bytes (using CSF_PAGE_SIZE pages, so rounding up here). We should only ever have one save file at a time, - // and the pages should be decommitted in the dtor, so pages committed should always be zero at this point. - if( pagesCommitted != 0 ) - { + // Initially committ enough room to store headSize bytes (using + // CSF_PAGE_SIZE pages, so rounding up here). We should only ever have one + // save file at a time, and the pages should be decommitted in the dtor, so + // pages committed should always be zero at this point. + if (pagesCommitted != 0) { #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - } + } - unsigned int pagesRequired = ( heapSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; + unsigned int pagesRequired = + (heapSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { + void* pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { #ifndef _CONTENT_PACKAGE - // Out of physical memory - __debugbreak(); + // Out of physical memory + __debugbreak(); #endif - } - pagesCommitted = pagesRequired; + } + pagesCommitted = pagesRequired; - if( fileSize > 0) - { - bool AllocData = false; - if(pvSaveData != NULL) - { + if (fileSize > 0) { + bool AllocData = false; + if (pvSaveData != NULL) { #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyTo(pvSaveMem, pvSaveData, fileSize); + // AP - use this to access the virtual memory + VirtualCopyTo(pvSaveMem, pvSaveData, fileSize); #else - memcpy(pvSaveMem, pvSaveData, fileSize); - if(bLevelGenBaseSave) - { - levelGen->deleteBaseSaveData(); - } + memcpy(pvSaveMem, pvSaveData, fileSize); + if (bLevelGenBaseSave) { + levelGen->deleteBaseSaveData(); + } #endif - } - else - { - unsigned int storageLength; + } else { + unsigned int storageLength; #ifdef __PSVITA__ - // create a buffer to hold the compressed data - pvSaveData = malloc(fileSize); - AllocData = true; - StorageManager.GetSaveData( pvSaveData, &storageLength ); + // create a buffer to hold the compressed data + pvSaveData = malloc(fileSize); + AllocData = true; + StorageManager.GetSaveData(pvSaveData, &storageLength); #else - StorageManager.GetSaveData( pvSaveMem, &storageLength ); + StorageManager.GetSaveData(pvSaveMem, &storageLength); #endif #ifdef __PS3__ - StorageManager.FreeSaveData(); + StorageManager.FreeSaveData(); #endif - app.DebugPrintf("Filesize - %d, Adjusted size - %d\n",fileSize,storageLength); - fileSize = storageLength; - } + app.DebugPrintf("Filesize - %d, Adjusted size - %d\n", fileSize, + storageLength); + fileSize = storageLength; + } #ifdef __PSVITA__ - if(plat == SAVE_FILE_PLATFORM_PSVITA) - { - // AP - decompress via the access function. This uses a special RLE format - VirtualDecompress((unsigned char *)pvSaveData+8, fileSize-8 ); - if( AllocData ) - { - // free the compressed data buffer if required - free( pvSaveData ); - } - else if(bLevelGenBaseSave) - { - levelGen->deleteBaseSaveData(); - } - } - else + if (plat == SAVE_FILE_PLATFORM_PSVITA) { + // AP - decompress via the access function. This uses a special RLE + // format + VirtualDecompress((unsigned char*)pvSaveData + 8, fileSize - 8); + if (AllocData) { + // free the compressed data buffer if required + free(pvSaveData); + } else if (bLevelGenBaseSave) { + levelGen->deleteBaseSaveData(); + } + } else #endif - { + { #ifdef __PSVITA__ - void* pvSourceData = pvSaveData; + void* pvSourceData = pvSaveData; #else - void* pvSourceData = pvSaveMem; + void* pvSourceData = pvSaveMem; #endif - int compressed = *(int*)pvSourceData; - if( compressed == 0 ) - { - unsigned int decompSize = *( (int*)pvSourceData+1 ); - if(isLocalEndianDifferent(plat)) System::ReverseULONG(&decompSize); + int compressed = *(int*)pvSourceData; + if (compressed == 0) { + unsigned int decompSize = *((int*)pvSourceData + 1); + if (isLocalEndianDifferent(plat)) + System::ReverseULONG(&decompSize); - // An invalid save, so clear the memory and start from scratch - if(decompSize == 0) - { - // 4J Stu - Saves created between 2/12/2011 and 7/12/2011 will have this problem - app.DebugPrintf("Invalid save data format\n"); - ZeroMemory( pvSourceData, fileSize ); - // Clear the first 8 bytes that reference the header - header.WriteHeader( pvSourceData ); - } - else - { - unsigned char *buf = new unsigned char[decompSize]; + // An invalid save, so clear the memory and start from scratch + if (decompSize == 0) { + // 4J Stu - Saves created between 2/12/2011 and 7/12/2011 + // will have this problem + app.DebugPrintf("Invalid save data format\n"); + ZeroMemory(pvSourceData, fileSize); + // Clear the first 8 bytes that reference the header + header.WriteHeader(pvSourceData); + } else { + unsigned char* buf = new unsigned char[decompSize]; #ifndef _XBOX - if(plat == SAVE_FILE_PLATFORM_PSVITA) - { - Compression::VitaVirtualDecompress(buf, &decompSize, (unsigned char *)pvSourceData+8, fileSize-8 ); - } - else + if (plat == SAVE_FILE_PLATFORM_PSVITA) { + Compression::VitaVirtualDecompress( + buf, &decompSize, (unsigned char*)pvSourceData + 8, + fileSize - 8); + } else #endif - { - Compression::getCompression()->SetDecompressionType(plat); // if this save is from another platform, set the correct decompression type - Compression::getCompression()->Decompress(buf, &decompSize, (unsigned char *)pvSourceData+8, fileSize-8 ); - Compression::getCompression()->SetDecompressionType(SAVE_FILE_PLATFORM_LOCAL); // and then set the decompression back to the local machine's standard type - } + { + Compression::getCompression()->SetDecompressionType( + plat); // if this save is from another platform, + // set the correct decompression type + Compression::getCompression()->Decompress( + buf, &decompSize, (unsigned char*)pvSourceData + 8, + fileSize - 8); + Compression::getCompression()->SetDecompressionType( + SAVE_FILE_PLATFORM_LOCAL); // and then set the + // decompression back to + // the local machine's + // standard type + } - // Only ReAlloc if we need to (we might already have enough) and align to 512 byte boundaries - unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; + // Only ReAlloc if we need to (we might already have enough) + // and align to 512 byte boundaries + unsigned int currentHeapSize = + pagesCommitted * CSF_PAGE_SIZE; - unsigned int desiredSize = decompSize; + unsigned int desiredSize = decompSize; - if( desiredSize > currentHeapSize ) - { - unsigned int pagesRequired = ( desiredSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { - // Out of physical memory - __debugbreak(); - } - pagesCommitted = pagesRequired; - } + if (desiredSize > currentHeapSize) { + unsigned int pagesRequired = + (desiredSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; + void* pvRet = + VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { + // Out of physical memory + __debugbreak(); + } + pagesCommitted = pagesRequired; + } #ifdef __PSVITA__ - VirtualCopyTo(pvSaveMem, buf, decompSize); + VirtualCopyTo(pvSaveMem, buf, decompSize); #else - memcpy(pvSaveMem, buf, decompSize); + memcpy(pvSaveMem, buf, decompSize); #endif - delete[] buf; - } - } - } + delete[] buf; + } + } + } - header.ReadHeader( pvSaveMem, plat ); + header.ReadHeader(pvSaveMem, plat); - } - else - { - // Clear the first 8 bytes that reference the header - header.WriteHeader( pvSaveMem ); - } + } else { + // Clear the first 8 bytes that reference the header + header.WriteHeader(pvSaveMem); + } } -ConsoleSaveFileOriginal::~ConsoleSaveFileOriginal() -{ - VirtualFree( pvHeap, MAX_PAGE_COUNT * CSF_PAGE_SIZE, MEM_DECOMMIT ); - pagesCommitted = 0; - // Make sure we don't have any thumbnail data still waiting round - we can't need it now we've destroyed the save file anyway -#if defined _XBOX - app.GetSaveThumbnail(NULL,NULL); +ConsoleSaveFileOriginal::~ConsoleSaveFileOriginal() { + VirtualFree(pvHeap, MAX_PAGE_COUNT * CSF_PAGE_SIZE, MEM_DECOMMIT); + pagesCommitted = 0; + // Make sure we don't have any thumbnail data still waiting round - we can't + // need it now we've destroyed the save file anyway +#if defined _XBOX + app.GetSaveThumbnail(NULL, NULL); #elif defined __PS3__ - app.GetSaveThumbnail(NULL,NULL, NULL,NULL); + app.GetSaveThumbnail(NULL, NULL, NULL, NULL); #endif - DeleteCriticalSection(&m_lock); + DeleteCriticalSection(&m_lock); } // Add the file to our table of internal files if not already there -// Open our actual save file ready for reading/writing, and the set the file pointer to the start of this file -FileEntry *ConsoleSaveFileOriginal::createFile( const ConsoleSavePath &fileName ) -{ - LockSaveAccess(); - FileEntry *file = header.AddFile( fileName.getName() ); - ReleaseSaveAccess(); +// Open our actual save file ready for reading/writing, and the set the file +// pointer to the start of this file +FileEntry* ConsoleSaveFileOriginal::createFile( + const ConsoleSavePath& fileName) { + LockSaveAccess(); + FileEntry* file = header.AddFile(fileName.getName()); + ReleaseSaveAccess(); - return file; + return file; } -void ConsoleSaveFileOriginal::deleteFile( FileEntry *file ) -{ - if( file == NULL ) return; +void ConsoleSaveFileOriginal::deleteFile(FileEntry* file) { + if (file == NULL) return; - LockSaveAccess(); + LockSaveAccess(); - unsigned int numberOfBytesRead = 0; - unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesRead = 0; + unsigned int numberOfBytesWritten = 0; - const int bufferSize = 4096; - int amountToRead = bufferSize; - std::uint8_t buffer[bufferSize]; - unsigned int bufferDataSize = 0; + const int bufferSize = 4096; + int amountToRead = bufferSize; + std::uint8_t buffer[bufferSize]; + unsigned int bufferDataSize = 0; + char* readStartOffset = + (char*)pvSaveMem + file->data.startOffset + file->getFileSize(); - char *readStartOffset = (char *)pvSaveMem + file->data.startOffset + file->getFileSize(); + char* writeStartOffset = (char*)pvSaveMem + file->data.startOffset; - char *writeStartOffset = (char *)pvSaveMem + file->data.startOffset; + char* endOfDataOffset = (char*)pvSaveMem + header.GetStartOfNextData(); - char *endOfDataOffset = (char *)pvSaveMem + header.GetStartOfNextData(); + while (true) { + // Fill buffer from file + if (readStartOffset + bufferSize > endOfDataOffset) { + amountToRead = (int)(endOfDataOffset - readStartOffset); + } else { + amountToRead = bufferSize; + } - while(true) - { - // Fill buffer from file - if( readStartOffset + bufferSize > endOfDataOffset ) - { - amountToRead = (int)(endOfDataOffset - readStartOffset); - } - else - { - amountToRead = bufferSize; - } - - if( amountToRead == 0 ) - break; + if (amountToRead == 0) break; #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyFrom( buffer, readStartOffset, amountToRead ); + // AP - use this to access the virtual memory + VirtualCopyFrom(buffer, readStartOffset, amountToRead); #else - memcpy( buffer, readStartOffset, amountToRead ); + memcpy(buffer, readStartOffset, amountToRead); #endif - numberOfBytesRead = amountToRead; + numberOfBytesRead = amountToRead; - bufferDataSize = amountToRead; - readStartOffset += numberOfBytesRead; + bufferDataSize = amountToRead; + readStartOffset += numberOfBytesRead; - // Write buffer to file + // Write buffer to file #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyTo( (void *)writeStartOffset, buffer, bufferDataSize ); + // AP - use this to access the virtual memory + VirtualCopyTo((void*)writeStartOffset, buffer, bufferDataSize); #else - memcpy( (void *)writeStartOffset, buffer, bufferDataSize ); + memcpy((void*)writeStartOffset, buffer, bufferDataSize); #endif - numberOfBytesWritten = bufferDataSize; + numberOfBytesWritten = bufferDataSize; - writeStartOffset += numberOfBytesWritten; - } + writeStartOffset += numberOfBytesWritten; + } - header.RemoveFile( file ); + header.RemoveFile(file); - finalizeWrite(); + finalizeWrite(); - ReleaseSaveAccess(); + ReleaseSaveAccess(); } -void ConsoleSaveFileOriginal::setFilePointer(FileEntry *file, unsigned int distanceToMove, SaveFileSeekOrigin seekOrigin) -{ - LockSaveAccess(); +void ConsoleSaveFileOriginal::setFilePointer(FileEntry* file, + unsigned int distanceToMove, + SaveFileSeekOrigin seekOrigin) { + LockSaveAccess(); - switch( seekOrigin ) - { - case SaveFileSeekOrigin::Current: - file->currentFilePointer += distanceToMove; - break; - case SaveFileSeekOrigin::End: - file->currentFilePointer = file->data.startOffset + file->getFileSize() + distanceToMove; - break; - case SaveFileSeekOrigin::Begin: - default: - file->currentFilePointer = file->data.startOffset + distanceToMove; - break; - } + switch (seekOrigin) { + case SaveFileSeekOrigin::Current: + file->currentFilePointer += distanceToMove; + break; + case SaveFileSeekOrigin::End: + file->currentFilePointer = + file->data.startOffset + file->getFileSize() + distanceToMove; + break; + case SaveFileSeekOrigin::Begin: + default: + file->currentFilePointer = file->data.startOffset + distanceToMove; + break; + } - ReleaseSaveAccess(); + ReleaseSaveAccess(); } // If this file needs to grow, move the data after along -void ConsoleSaveFileOriginal::PrepareForWrite( FileEntry *file, unsigned int nNumberOfBytesToWrite ) -{ - int bytesToGrowBy = ( (file->currentFilePointer - file->data.startOffset) + nNumberOfBytesToWrite) - file->getFileSize(); - if( bytesToGrowBy <= 0 ) - return; +void ConsoleSaveFileOriginal::PrepareForWrite( + FileEntry* file, unsigned int nNumberOfBytesToWrite) { + int bytesToGrowBy = ((file->currentFilePointer - file->data.startOffset) + + nNumberOfBytesToWrite) - + file->getFileSize(); + if (bytesToGrowBy <= 0) return; - // 4J Stu - Not forcing a minimum size, it is up to the caller to write data in sensible amounts - // This lets us keep some of the smaller files small - //if( bytesToGrowBy < 1024 ) - // bytesToGrowBy = 1024; + // 4J Stu - Not forcing a minimum size, it is up to the caller to write data + // in sensible amounts This lets us keep some of the smaller files small + // if( bytesToGrowBy < 1024 ) + // bytesToGrowBy = 1024; - // Move all the data beyond us - MoveDataBeyond(file, bytesToGrowBy); + // Move all the data beyond us + MoveDataBeyond(file, bytesToGrowBy); - // Update our length - if( file->data.length < 0 ) - file->data.length = 0; - file->data.length += bytesToGrowBy; + // Update our length + if (file->data.length < 0) file->data.length = 0; + file->data.length += bytesToGrowBy; - // Write the header with the updated data - finalizeWrite(); + // Write the header with the updated data + finalizeWrite(); } -bool ConsoleSaveFileOriginal::writeFile(FileEntry *file,const void *lpBuffer, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) -{ - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileOriginal::writeFile(FileEntry* file, const void* lpBuffer, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) { + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - LockSaveAccess(); + LockSaveAccess(); - PrepareForWrite( file, nNumberOfBytesToWrite ); + PrepareForWrite(file, nNumberOfBytesToWrite); - char *writeStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, writeStartOffset); + char* writeStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, + // writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, + // writeStartOffset); #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyTo((void *)writeStartOffset, (void*)lpBuffer, nNumberOfBytesToWrite); + // AP - use this to access the virtual memory + VirtualCopyTo((void*)writeStartOffset, (void*)lpBuffer, + nNumberOfBytesToWrite); #else - memcpy( (void *)writeStartOffset, lpBuffer, nNumberOfBytesToWrite ); + memcpy((void*)writeStartOffset, lpBuffer, nNumberOfBytesToWrite); #endif - *lpNumberOfBytesWritten = nNumberOfBytesToWrite; + *lpNumberOfBytesWritten = nNumberOfBytesToWrite; - if(file->data.length < 0) - file->data.length = 0; + if (file->data.length < 0) file->data.length = 0; - file->currentFilePointer += *lpNumberOfBytesWritten; + file->currentFilePointer += *lpNumberOfBytesWritten; - //wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); + // wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", + // *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); - file->updateLastModifiedTime(); + file->updateLastModifiedTime(); - ReleaseSaveAccess(); + ReleaseSaveAccess(); - return true; + return true; } -bool ConsoleSaveFileOriginal::zeroFile(FileEntry *file, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) -{ - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileOriginal::zeroFile(FileEntry* file, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) { + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - LockSaveAccess(); + LockSaveAccess(); - PrepareForWrite( file, nNumberOfBytesToWrite ); + PrepareForWrite(file, nNumberOfBytesToWrite); - char *writeStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, writeStartOffset); + char* writeStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, + // writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, + // writeStartOffset); #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualMemset( (void *)writeStartOffset, 0, nNumberOfBytesToWrite ); + // AP - use this to access the virtual memory + VirtualMemset((void*)writeStartOffset, 0, nNumberOfBytesToWrite); #else - memset( (void *)writeStartOffset, 0, nNumberOfBytesToWrite ); + memset((void*)writeStartOffset, 0, nNumberOfBytesToWrite); #endif - *lpNumberOfBytesWritten = nNumberOfBytesToWrite; + *lpNumberOfBytesWritten = nNumberOfBytesToWrite; - if(file->data.length < 0) - file->data.length = 0; + if (file->data.length < 0) file->data.length = 0; - file->currentFilePointer += *lpNumberOfBytesWritten; + file->currentFilePointer += *lpNumberOfBytesWritten; - //wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); + // wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", + // *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); - file->updateLastModifiedTime(); + file->updateLastModifiedTime(); - ReleaseSaveAccess(); + ReleaseSaveAccess(); - return true; + return true; } -bool ConsoleSaveFileOriginal::readFile( FileEntry *file, void *lpBuffer, unsigned int nNumberOfBytesToRead, unsigned int *lpNumberOfBytesRead) -{ - unsigned int actualBytesToRead; - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileOriginal::readFile(FileEntry* file, void* lpBuffer, + unsigned int nNumberOfBytesToRead, + unsigned int* lpNumberOfBytesRead) { + unsigned int actualBytesToRead; + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - LockSaveAccess(); + LockSaveAccess(); - char *readStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Read: pvSaveMem = %0xd, currentFilePointer = %d, readStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, readStartOffset); + char* readStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Read: pvSaveMem = %0xd, currentFilePointer = %d, readStartOffset + // = %0xd\n", pvSaveMem, file->currentFilePointer, readStartOffset); - assert( nNumberOfBytesToRead <= file->getFileSize() ); + assert(nNumberOfBytesToRead <= file->getFileSize()); - actualBytesToRead = nNumberOfBytesToRead; - if( file->currentFilePointer + nNumberOfBytesToRead > file->data.startOffset + file->data.length ) - { - actualBytesToRead = (file->data.startOffset + file->data.length) - file->currentFilePointer; - } + actualBytesToRead = nNumberOfBytesToRead; + if (file->currentFilePointer + nNumberOfBytesToRead > + file->data.startOffset + file->data.length) { + actualBytesToRead = (file->data.startOffset + file->data.length) - + file->currentFilePointer; + } #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyFrom( lpBuffer, readStartOffset, actualBytesToRead ); + // AP - use this to access the virtual memory + VirtualCopyFrom(lpBuffer, readStartOffset, actualBytesToRead); #else - memcpy( lpBuffer, readStartOffset, actualBytesToRead ); + memcpy(lpBuffer, readStartOffset, actualBytesToRead); #endif - *lpNumberOfBytesRead = actualBytesToRead; + *lpNumberOfBytesRead = actualBytesToRead; - file->currentFilePointer += *lpNumberOfBytesRead; + file->currentFilePointer += *lpNumberOfBytesRead; - //wprintf(L"Read %d bytes from %s, new file pointer is %I64d\n", *lpNumberOfBytesRead, file->data.filename, file->currentFilePointer); + // wprintf(L"Read %d bytes from %s, new file pointer is %I64d\n", + // *lpNumberOfBytesRead, file->data.filename, file->currentFilePointer); - ReleaseSaveAccess(); + ReleaseSaveAccess(); - return true; + return true; } -bool ConsoleSaveFileOriginal::closeHandle( FileEntry *file ) -{ - LockSaveAccess(); - finalizeWrite(); - ReleaseSaveAccess(); +bool ConsoleSaveFileOriginal::closeHandle(FileEntry* file) { + LockSaveAccess(); + finalizeWrite(); + ReleaseSaveAccess(); - return true; + return true; } -void ConsoleSaveFileOriginal::finalizeWrite() -{ - LockSaveAccess(); - header.WriteHeader( pvSaveMem ); - ReleaseSaveAccess(); +void ConsoleSaveFileOriginal::finalizeWrite() { + LockSaveAccess(); + header.WriteHeader(pvSaveMem); + ReleaseSaveAccess(); } -void ConsoleSaveFileOriginal::MoveDataBeyond(FileEntry *file, unsigned int nNumberOfBytesToWrite) -{ - unsigned int numberOfBytesRead = 0; - unsigned int numberOfBytesWritten = 0; +void ConsoleSaveFileOriginal::MoveDataBeyond( + FileEntry* file, unsigned int nNumberOfBytesToWrite) { + unsigned int numberOfBytesRead = 0; + unsigned int numberOfBytesWritten = 0; - const unsigned int bufferSize = 4096; - unsigned int amountToRead = bufferSize; - //assert( nNumberOfBytesToWrite <= bufferSize ); - static std::uint8_t buffer1[bufferSize]; - static std::uint8_t buffer2[bufferSize]; - unsigned int buffer1Size = 0; - unsigned int buffer2Size = 0; + const unsigned int bufferSize = 4096; + unsigned int amountToRead = bufferSize; + // assert( nNumberOfBytesToWrite <= bufferSize ); + static std::uint8_t buffer1[bufferSize]; + static std::uint8_t buffer2[bufferSize]; + unsigned int buffer1Size = 0; + unsigned int buffer2Size = 0; - // Only ReAlloc if we need to (we might already have enough) and align to 512 byte boundaries - unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; + // Only ReAlloc if we need to (we might already have enough) and align to + // 512 byte boundaries + unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; - unsigned int desiredSize = header.GetFileSize() + nNumberOfBytesToWrite; + unsigned int desiredSize = header.GetFileSize() + nNumberOfBytesToWrite; - if( desiredSize > currentHeapSize ) - { - unsigned int pagesRequired = ( desiredSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { - // Out of physical memory - __debugbreak(); - } - pagesCommitted = pagesRequired; - } + if (desiredSize > currentHeapSize) { + unsigned int pagesRequired = + (desiredSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; + void* pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { + // Out of physical memory + __debugbreak(); + } + pagesCommitted = pagesRequired; + } - // This is the start of where we want the space to be, and the start of the data that we need to move - char *spaceStartOffset = (char *)pvSaveMem + file->data.startOffset + file->getFileSize(); + // This is the start of where we want the space to be, and the start of the + // data that we need to move + char* spaceStartOffset = + (char*)pvSaveMem + file->data.startOffset + file->getFileSize(); - // This is the end of where we want the space to be - char *spaceEndOffset = spaceStartOffset + nNumberOfBytesToWrite; + // This is the end of where we want the space to be + char* spaceEndOffset = spaceStartOffset + nNumberOfBytesToWrite; - // This is the current end of the data that we want to move - char *beginEndOfDataOffset = (char *)pvSaveMem + header.GetStartOfNextData(); + // This is the current end of the data that we want to move + char* beginEndOfDataOffset = (char*)pvSaveMem + header.GetStartOfNextData(); - // This is where the end of the data is going to be - char *finishEndOfDataOffset = beginEndOfDataOffset + nNumberOfBytesToWrite; + // This is where the end of the data is going to be + char* finishEndOfDataOffset = beginEndOfDataOffset + nNumberOfBytesToWrite; - // This is where we are going to read from (with the amount we want to read subtracted before we read) - char *readStartOffset = beginEndOfDataOffset; + // This is where we are going to read from (with the amount we want to read + // subtracted before we read) + char* readStartOffset = beginEndOfDataOffset; - // This is where we can safely write to (with the amount we want write subtracted before we write) - char *writeStartOffset = finishEndOfDataOffset; + // This is where we can safely write to (with the amount we want write + // subtracted before we write) + char* writeStartOffset = finishEndOfDataOffset; - //printf("\n******* MOVEDATABEYOND *******\n"); - //printf("Space start: %d, space end: %d\n", spaceStartOffset - (char *)pvSaveMem, spaceEndOffset - (char *)pvSaveMem); - //printf("Current end of data: %d, new end of data: %d\n", beginEndOfDataOffset - (char *)pvSaveMem, finishEndOfDataOffset - (char *)pvSaveMem); + // printf("\n******* MOVEDATABEYOND *******\n"); + // printf("Space start: %d, space end: %d\n", spaceStartOffset - (char + // *)pvSaveMem, spaceEndOffset - (char *)pvSaveMem); printf("Current end of + // data: %d, new end of data: %d\n", beginEndOfDataOffset - (char + // *)pvSaveMem, finishEndOfDataOffset - (char *)pvSaveMem); - // Optimisation for things that are being moved in whole region file sector (4K chunks). We could generalise this a bit more but seems safest at the moment to identify this particular type - // of move and code explicitly for this situation - if( ( nNumberOfBytesToWrite & 4095 ) == 0 ) - { - if( nNumberOfBytesToWrite > 0 ) - { - // Get addresses for start & end of the region we are copying from as uintptr_t, for easier maths - uintptr_t uiFromStart = (uintptr_t)spaceStartOffset; - uintptr_t uiFromEnd = (uintptr_t)beginEndOfDataOffset; + // Optimisation for things that are being moved in whole region file sector + // (4K chunks). We could generalise this a bit more but seems safest at the + // moment to identify this particular type of move and code explicitly for + // this situation + if ((nNumberOfBytesToWrite & 4095) == 0) { + if (nNumberOfBytesToWrite > 0) { + // Get addresses for start & end of the region we are copying from + // as uintptr_t, for easier maths + uintptr_t uiFromStart = (uintptr_t)spaceStartOffset; + uintptr_t uiFromEnd = (uintptr_t)beginEndOfDataOffset; - // Round both of these values to get 4096 byte chunks that we will need to at least partially move - uintptr_t uiFromStartChunk = uiFromStart & ~((uintptr_t)4095); - uintptr_t uiFromEndChunk = (uiFromEnd - 1 ) & ~((uintptr_t)4095); + // Round both of these values to get 4096 byte chunks that we will + // need to at least partially move + uintptr_t uiFromStartChunk = uiFromStart & ~((uintptr_t)4095); + uintptr_t uiFromEndChunk = (uiFromEnd - 1) & ~((uintptr_t)4095); - // Loop through all the affected source 4096 chunks, going backwards so we don't overwrite anything we'll need in the future - for( uintptr_t uiCurrentChunk = uiFromEndChunk; uiCurrentChunk >= uiFromStartChunk; uiCurrentChunk -= 4096 ) - { - // Establish chunk we'll need to copy - uintptr_t uiCopyStart = uiCurrentChunk; - uintptr_t uiCopyEnd = uiCurrentChunk + 4096; - // Clamp chunk to the bounds of the full region we are trying to copy - if( uiCopyStart < uiFromStart ) - { - // Needs to be clampged against the start of our region - uiCopyStart = uiFromStart; - } - if ( uiCopyEnd > uiFromEnd ) - { - // Needs to be clamped to the end of our region - uiCopyEnd = uiFromEnd; - } + // Loop through all the affected source 4096 chunks, going backwards + // so we don't overwrite anything we'll need in the future + for (uintptr_t uiCurrentChunk = uiFromEndChunk; + uiCurrentChunk >= uiFromStartChunk; uiCurrentChunk -= 4096) { + // Establish chunk we'll need to copy + uintptr_t uiCopyStart = uiCurrentChunk; + uintptr_t uiCopyEnd = uiCurrentChunk + 4096; + // Clamp chunk to the bounds of the full region we are trying to + // copy + if (uiCopyStart < uiFromStart) { + // Needs to be clampged against the start of our region + uiCopyStart = uiFromStart; + } + if (uiCopyEnd > uiFromEnd) { + // Needs to be clamped to the end of our region + uiCopyEnd = uiFromEnd; + } #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualMove( (void *)(uiCopyStart + nNumberOfBytesToWrite), ( void *)uiCopyStart, uiCopyEnd - uiCopyStart); + // AP - use this to access the virtual memory + VirtualMove((void*)(uiCopyStart + nNumberOfBytesToWrite), + (void*)uiCopyStart, uiCopyEnd - uiCopyStart); #else - XMemCpy( (void *)(uiCopyStart + nNumberOfBytesToWrite), ( void *)uiCopyStart, uiCopyEnd - uiCopyStart ); + XMemCpy((void*)(uiCopyStart + nNumberOfBytesToWrite), + (void*)uiCopyStart, uiCopyEnd - uiCopyStart); #endif - } - } - } - else - { - while(true) - { - // Copy buffer 1 to buffer 2 - memcpy( buffer2, buffer1, buffer1Size); - buffer2Size = buffer1Size; + } + } + } else { + while (true) { + // Copy buffer 1 to buffer 2 + memcpy(buffer2, buffer1, buffer1Size); + buffer2Size = buffer1Size; - // Fill buffer 1 from file - if( (readStartOffset - bufferSize) < spaceStartOffset ) - { - amountToRead = static_cast(readStartOffset - spaceStartOffset); - } - else - { - amountToRead = bufferSize; - } + // Fill buffer 1 from file + if ((readStartOffset - bufferSize) < spaceStartOffset) { + amountToRead = static_cast(readStartOffset - + spaceStartOffset); + } else { + amountToRead = bufferSize; + } - // Push the read point back by the amount of bytes that we are going to read - readStartOffset -= amountToRead; + // Push the read point back by the amount of bytes that we are going + // to read + readStartOffset -= amountToRead; - //printf("About to read %u from %d\n", amountToRead, readStartOffset - (char *)pvSaveMem ); + // printf("About to read %u from %d\n", amountToRead, + // readStartOffset - (char *)pvSaveMem ); #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyFrom(buffer1, readStartOffset, amountToRead); + // AP - use this to access the virtual memory + VirtualCopyFrom(buffer1, readStartOffset, amountToRead); #else - memcpy( buffer1, readStartOffset, amountToRead ); + memcpy(buffer1, readStartOffset, amountToRead); #endif - numberOfBytesRead = amountToRead; + numberOfBytesRead = amountToRead; - buffer1Size = amountToRead; + buffer1Size = amountToRead; - // Move back the write pointer by the amount of bytes we are going to write - writeStartOffset -= buffer2Size; + // Move back the write pointer by the amount of bytes we are going + // to write + writeStartOffset -= buffer2Size; - // Write buffer 2 to file - if( (writeStartOffset + buffer2Size) <= finishEndOfDataOffset) - { - //printf("About to write %u to %d\n", buffer2Size, writeStartOffset - (char *)pvSaveMem ); + // Write buffer 2 to file + if ((writeStartOffset + buffer2Size) <= finishEndOfDataOffset) { + // printf("About to write %u to %d\n", buffer2Size, + // writeStartOffset - (char *)pvSaveMem ); #ifdef __PSVITA__ - // AP - use this to access the virtual memory - VirtualCopyTo((void *)writeStartOffset, buffer2, buffer2Size); + // AP - use this to access the virtual memory + VirtualCopyTo((void*)writeStartOffset, buffer2, buffer2Size); #else - memcpy( (void *)writeStartOffset, buffer2, buffer2Size ); + memcpy((void*)writeStartOffset, buffer2, buffer2Size); #endif - numberOfBytesWritten = buffer2Size; - } - else - { - assert((writeStartOffset + buffer2Size) <= finishEndOfDataOffset); - numberOfBytesWritten = 0; - } + numberOfBytesWritten = buffer2Size; + } else { + assert((writeStartOffset + buffer2Size) <= + finishEndOfDataOffset); + numberOfBytesWritten = 0; + } - if( numberOfBytesRead == 0 ) - { - //printf("\n************** MOVE COMPLETED *************** \n\n"); - assert( writeStartOffset == spaceEndOffset ); - break; - } - } - } + if (numberOfBytesRead == 0) { + // printf("\n************** MOVE COMPLETED *************** + // \n\n"); + assert(writeStartOffset == spaceEndOffset); + break; + } + } + } - header.AdjustStartOffsets( file, nNumberOfBytesToWrite ); + header.AdjustStartOffsets(file, nNumberOfBytesToWrite); } -bool ConsoleSaveFileOriginal::doesFileExist(ConsoleSavePath file) -{ - LockSaveAccess(); - bool exists = header.fileExists( file.getName() ); - ReleaseSaveAccess(); +bool ConsoleSaveFileOriginal::doesFileExist(ConsoleSavePath file) { + LockSaveAccess(); + bool exists = header.fileExists(file.getName()); + ReleaseSaveAccess(); - return exists; + return exists; } -void ConsoleSaveFileOriginal::Flush(bool autosave, bool updateThumbnail ) -{ - LockSaveAccess(); +void ConsoleSaveFileOriginal::Flush(bool autosave, bool updateThumbnail) { + LockSaveAccess(); #ifdef __PSVITA__ - // On Vita we've had problems with saves being corrupted on rapid save/save-exiting so seems prudent to wait for idle - while( StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) - { - app.DebugPrintf("Flush wait\n"); - Sleep(10); - } + // On Vita we've had problems with saves being corrupted on rapid + // save/save-exiting so seems prudent to wait for idle + while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) { + app.DebugPrintf("Flush wait\n"); + Sleep(10); + } #endif - finalizeWrite(); + finalizeWrite(); - // Get the frequency of the timer - LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; - float fElapsedTime = 0.0f; - QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + // Get the frequency of the timer + LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; + float fElapsedTime = 0.0f; + QueryPerformanceFrequency(&qwTicksPerSec); + float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; - unsigned int fileSize = header.GetFileSize(); + unsigned int fileSize = header.GetFileSize(); - // Assume that the compression will make it smaller so initially attempt to allocate the current file size - // We add 4 bytes to the start so that we can signal compressed data - // And another 4 bytes to store the decompressed data size - unsigned int compLength = fileSize+8; + // Assume that the compression will make it smaller so initially attempt to + // allocate the current file size We add 4 bytes to the start so that we can + // signal compressed data And another 4 bytes to store the decompressed data + // size + unsigned int compLength = fileSize + 8; - // 4J Stu - Added TU-1 interim + // 4J Stu - Added TU-1 interim #ifdef __PS3__ - // On PS3, don't compress the data as we can't really afford the extra memory this requires for the output buffer. Instead we'll be writing - // directly from the save data. - StorageManager.SetSaveData(pvSaveMem,fileSize); - std::uint8_t *compData = (std::uint8_t *)pvSaveMem; + // On PS3, don't compress the data as we can't really afford the extra + // memory this requires for the output buffer. Instead we'll be writing + // directly from the save data. + StorageManager.SetSaveData(pvSaveMem, fileSize); + std::uint8_t* compData = (std::uint8_t*)pvSaveMem; #else - // Attempt to allocate the required memory - // We do not own this, it belongs to the StorageManager - std::uint8_t *compData = (std::uint8_t *)StorageManager.AllocateSaveData( compLength ); + // Attempt to allocate the required memory + // We do not own this, it belongs to the StorageManager + std::uint8_t* compData = + (std::uint8_t*)StorageManager.AllocateSaveData(compLength); #ifdef __PSVITA__ - // AP - make sure we always allocate just what is needed so it will only SAVE what is needed. - // If we don't do this the StorageManager will save a file of uncompressed size unnecessarily. - compData = NULL; + // AP - make sure we always allocate just what is needed so it will only + // SAVE what is needed. If we don't do this the StorageManager will save a + // file of uncompressed size unnecessarily. + compData = NULL; #endif - // If we failed to allocate then compData will be NULL - // Pre-calculate the compressed data size so that we can attempt to allocate a smaller buffer - if(compData == NULL) - { - // Length should be 0 here so that the compression call knows that we want to know the length back - compLength = 0; + // If we failed to allocate then compData will be NULL + // Pre-calculate the compressed data size so that we can attempt to allocate + // a smaller buffer + if (compData == NULL) { + // Length should be 0 here so that the compression call knows that we + // want to know the length back + compLength = 0; - // Pre-calculate the buffer size required for the compressed data - PIXBeginNamedEvent(0,"Pre-calc save compression"); - // Save the start time - QueryPerformanceCounter( &qwTime ); + // Pre-calculate the buffer size required for the compressed data + PIXBeginNamedEvent(0, "Pre-calc save compression"); + // Save the start time + QueryPerformanceCounter(&qwTime); #ifdef __PSVITA__ - // AP - get the compressed size via the access function. This uses a special RLE format - VirtualCompress(NULL,&compLength,pvSaveMem,fileSize); + // AP - get the compressed size via the access function. This uses a + // special RLE format + VirtualCompress(NULL, &compLength, pvSaveMem, fileSize); #else - Compression::getCompression()->Compress(NULL,&compLength,pvSaveMem,fileSize); + Compression::getCompression()->Compress(NULL, &compLength, pvSaveMem, + fileSize); #endif - QueryPerformanceCounter( &qwNewTime ); + QueryPerformanceCounter(&qwNewTime); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Check buffer size: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + app.DebugPrintf("Check buffer size: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); - // We add 4 bytes to the start so that we can signal compressed data - // And another 4 bytes to store the decompressed data size - compLength = compLength+8; + // We add 4 bytes to the start so that we can signal compressed data + // And another 4 bytes to store the decompressed data size + compLength = compLength + 8; - // Attempt to allocate the required memory - compData = (std::uint8_t *)StorageManager.AllocateSaveData( compLength ); - } + // Attempt to allocate the required memory + compData = (std::uint8_t*)StorageManager.AllocateSaveData(compLength); + } #endif - if(compData != NULL) - { - // No compression on PS3 - see comment above + if (compData != NULL) { + // No compression on PS3 - see comment above #ifndef __PS3__ - // Re-compress all save data before we save it to disk - PIXBeginNamedEvent(0,"Actual save compression"); - // Save the start time - QueryPerformanceCounter( &qwTime ); + // Re-compress all save data before we save it to disk + PIXBeginNamedEvent(0, "Actual save compression"); + // Save the start time + QueryPerformanceCounter(&qwTime); #ifdef __PSVITA__ - // AP - compress via the access function. This uses a special RLE format - VirtualCompress(compData+8,&compLength,pvSaveMem,fileSize); + // AP - compress via the access function. This uses a special RLE format + VirtualCompress(compData + 8, &compLength, pvSaveMem, fileSize); #else - Compression::getCompression()->Compress(compData+8,&compLength,pvSaveMem,fileSize); + Compression::getCompression()->Compress(compData + 8, &compLength, + pvSaveMem, fileSize); #endif - QueryPerformanceCounter( &qwNewTime ); + QueryPerformanceCounter(&qwNewTime); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Compress: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + app.DebugPrintf("Compress: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); - ZeroMemory(compData,8); - int saveVer = 0; - memcpy( compData, &saveVer, sizeof(int) ); - memcpy( compData+4, &fileSize, sizeof(int) ); + ZeroMemory(compData, 8); + int saveVer = 0; + memcpy(compData, &saveVer, sizeof(int)); + memcpy(compData + 4, &fileSize, sizeof(int)); - app.DebugPrintf("Save data compressed from %d to %d\n", fileSize, compLength); + app.DebugPrintf("Save data compressed from %d to %d\n", fileSize, + compLength); #endif - std::uint8_t *pbThumbnailData = NULL; - unsigned int dwThumbnailDataSize = 0; + std::uint8_t* pbThumbnailData = NULL; + unsigned int dwThumbnailDataSize = 0; - std::uint8_t *pbDataSaveImage = NULL; - unsigned int dwDataSizeSaveImage = 0; + std::uint8_t* pbDataSaveImage = NULL; + unsigned int dwDataSizeSaveImage = 0; -#if ( defined _XBOX || defined _DURANGO ) - app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); -#elif ( defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ ) - app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize,&pbDataSaveImage,&dwDataSizeSaveImage); +#if (defined _XBOX || defined _DURANGO) + app.GetSaveThumbnail(&pbThumbnailData, &dwThumbnailDataSize); +#elif (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) + app.GetSaveThumbnail(&pbThumbnailData, &dwThumbnailDataSize, + &pbDataSaveImage, &dwDataSizeSaveImage); #endif - std::uint8_t bTextMetadata[88]; - ZeroMemory(bTextMetadata,88); + std::uint8_t bTextMetadata[88]; + ZeroMemory(bTextMetadata, 88); - __int64 seed = 0; - bool hasSeed = false; - if(MinecraftServer::getInstance()!= NULL && MinecraftServer::getInstance()->levels[0]!=NULL) - { - seed = MinecraftServer::getInstance()->levels[0]->getLevelData()->getSeed(); - hasSeed = true; - } + __int64 seed = 0; + bool hasSeed = false; + if (MinecraftServer::getInstance() != NULL && + MinecraftServer::getInstance()->levels[0] != NULL) { + seed = MinecraftServer::getInstance() + ->levels[0] + ->getLevelData() + ->getSeed(); + hasSeed = true; + } - int iTextMetadataBytes = app.CreateImageTextData(bTextMetadata, seed, hasSeed, app.GetGameHostOption(eGameHostOption_All), Minecraft::GetInstance()->getCurrentTexturePackId()); + int iTextMetadataBytes = app.CreateImageTextData( + bTextMetadata, seed, hasSeed, + app.GetGameHostOption(eGameHostOption_All), + Minecraft::GetInstance()->getCurrentTexturePackId()); - INT saveOrCheckpointId = 0; - bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); - TelemetryManager->RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), saveOrCheckpointId, compLength+8); + INT saveOrCheckpointId = 0; + bool validSave = + StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); + TelemetryManager->RecordLevelSaveOrCheckpoint( + ProfileManager.GetPrimaryPad(), saveOrCheckpointId, compLength + 8); #ifdef _XBOX - StorageManager.SaveSaveData( compLength+8,pbThumbnailData,dwThumbnailDataSize,bTextMetadata,iTextMetadataBytes ); - delete [] pbThumbnailData; + StorageManager.SaveSaveData(compLength + 8, pbThumbnailData, + dwThumbnailDataSize, bTextMetadata, + iTextMetadataBytes); + delete[] pbThumbnailData; #ifndef _CONTENT_PACKAGE - if( app.DebugSettingsOn()) - { - if(app.GetWriteSavesToFolderEnabled() ) - { - DebugFlushToFile(compData, compLength+8); - } - } + if (app.DebugSettingsOn()) { + if (app.GetWriteSavesToFolderEnabled()) { + DebugFlushToFile(compData, compLength + 8); + } + } #endif - } - else - { - // We have failed to allocate the memory required to save this file. Now what? - } + } else { + // We have failed to allocate the memory required to save this file. Now + // what? + } - ReleaseSaveAccess(); -#elif (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined _DURANGO || defined _WINDOWS64) - // set the icon and save image - StorageManager.SetSaveImages(pbThumbnailData,dwThumbnailDataSize,pbDataSaveImage,dwDataSizeSaveImage,bTextMetadata,iTextMetadataBytes); - app.DebugPrintf("Save thumbnail size %d\n",dwThumbnailDataSize); + ReleaseSaveAccess(); +#elif (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined _DURANGO || defined _WINDOWS64) + // set the icon and save image + StorageManager.SetSaveImages(pbThumbnailData, dwThumbnailDataSize, + pbDataSaveImage, dwDataSizeSaveImage, + bTextMetadata, iTextMetadataBytes); + app.DebugPrintf("Save thumbnail size %d\n", dwThumbnailDataSize); - // save the data - StorageManager.SaveSaveData( &ConsoleSaveFileOriginal::SaveSaveDataCallback, this ); + // save the data + StorageManager.SaveSaveData( + &ConsoleSaveFileOriginal::SaveSaveDataCallback, this); #ifndef _CONTENT_PACKAGE - if( app.DebugSettingsOn()) - { - if(app.GetWriteSavesToFolderEnabled() ) - { - DebugFlushToFile(compData, compLength+8); - } - } + if (app.DebugSettingsOn()) { + if (app.GetWriteSavesToFolderEnabled()) { + DebugFlushToFile(compData, compLength + 8); + } + } #endif - ReleaseSaveAccess(); - } + ReleaseSaveAccess(); + } #else - } - ReleaseSaveAccess(); + } + ReleaseSaveAccess(); #endif } -#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined _DURANGO || defined _WINDOWS64) +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined _DURANGO || defined _WINDOWS64) -int ConsoleSaveFileOriginal::SaveSaveDataCallback(void *lpParam, bool bRes) -{ - ConsoleSaveFile *pClass=(ConsoleSaveFile *)lpParam; +int ConsoleSaveFileOriginal::SaveSaveDataCallback(void* lpParam, bool bRes) { + ConsoleSaveFile* pClass = (ConsoleSaveFile*)lpParam; - return 0; + return 0; } #endif #ifndef _CONTENT_PACKAGE -void ConsoleSaveFileOriginal::DebugFlushToFile(void *compressedData /*= NULL*/, unsigned int compressedDataSize /*= 0*/) -{ - LockSaveAccess(); +void ConsoleSaveFileOriginal::DebugFlushToFile( + void* compressedData /*= NULL*/, unsigned int compressedDataSize /*= 0*/) { + LockSaveAccess(); - finalizeWrite(); + finalizeWrite(); - unsigned int fileSize = header.GetFileSize(); + unsigned int fileSize = header.GetFileSize(); - unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesWritten = 0; #ifdef _XBOX - File targetFileDir(L"GAME:\\Saves"); + File targetFileDir(L"GAME:\\Saves"); #else - File targetFileDir(L"Saves"); -#endif // _XBOX + File targetFileDir(L"Saves"); +#endif // _XBOX - if(!targetFileDir.exists()) - targetFileDir.mkdir(); + if (!targetFileDir.exists()) targetFileDir.mkdir(); - wchar_t *fileName = new wchar_t[XCONTENT_MAX_FILENAME_LENGTH+1]; + wchar_t* fileName = new wchar_t[XCONTENT_MAX_FILENAME_LENGTH + 1]; - SYSTEMTIME t; - GetSystemTime( &t ); + SYSTEMTIME t; + GetSystemTime(&t); - //14 chars for the digits - //11 chars for the separators + suffix - //25 chars total - std::wstring cutFileName = m_fileName; - if(m_fileName.length() > XCONTENT_MAX_FILENAME_LENGTH - 25) - { - cutFileName = m_fileName.substr(0, XCONTENT_MAX_FILENAME_LENGTH - 25); - } - swprintf(fileName, XCONTENT_MAX_FILENAME_LENGTH+1, L"\\v%04d-%ls%02d.%02d.%02d.%02d.%02d.mcs",VER_PRODUCTBUILD,cutFileName.c_str(), t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); + // 14 chars for the digits + // 11 chars for the separators + suffix + // 25 chars total + std::wstring cutFileName = m_fileName; + if (m_fileName.length() > XCONTENT_MAX_FILENAME_LENGTH - 25) { + cutFileName = m_fileName.substr(0, XCONTENT_MAX_FILENAME_LENGTH - 25); + } + swprintf(fileName, XCONTENT_MAX_FILENAME_LENGTH + 1, + L"\\v%04d-%ls%02d.%02d.%02d.%02d.%02d.mcs", VER_PRODUCTBUILD, + cutFileName.c_str(), t.wMonth, t.wDay, t.wHour, t.wMinute, + t.wSecond); - const std::wstring outputPath = targetFileDir.getPath() + std::wstring(fileName); + const std::wstring outputPath = + targetFileDir.getPath() + std::wstring(fileName); #ifndef __PSVITA__ - bool writeSucceeded = false; + bool writeSucceeded = false; #endif - if(compressedData != NULL && compressedDataSize > 0) - { + if (compressedData != NULL && compressedDataSize > 0) { #ifdef __PSVITA__ - // AP - Use the access function to save - VirtualWriteFile( outputPath.c_str(), compressedData, compressedDataSize, &numberOfBytesWritten, NULL); + // AP - Use the access function to save + VirtualWriteFile(outputPath.c_str(), compressedData, compressedDataSize, + &numberOfBytesWritten, NULL); #else - writeSucceeded = PortableFileIO::WriteBinaryFile(outputPath, compressedData, compressedDataSize); - numberOfBytesWritten = writeSucceeded ? compressedDataSize : 0; + writeSucceeded = PortableFileIO::WriteBinaryFile( + outputPath, compressedData, compressedDataSize); + numberOfBytesWritten = writeSucceeded ? compressedDataSize : 0; #endif - assert(numberOfBytesWritten == compressedDataSize); - } - else - { + assert(numberOfBytesWritten == compressedDataSize); + } else { #ifdef __PSVITA__ - // AP - Use the access function to save - VirtualWriteFile( outputPath.c_str(), compressedData, compressedDataSize, &numberOfBytesWritten, NULL); + // AP - Use the access function to save + VirtualWriteFile(outputPath.c_str(), compressedData, compressedDataSize, + &numberOfBytesWritten, NULL); #else - writeSucceeded = PortableFileIO::WriteBinaryFile(outputPath, pvSaveMem, fileSize); - numberOfBytesWritten = writeSucceeded ? fileSize : 0; + writeSucceeded = + PortableFileIO::WriteBinaryFile(outputPath, pvSaveMem, fileSize); + numberOfBytesWritten = writeSucceeded ? fileSize : 0; #endif - assert(numberOfBytesWritten == fileSize); - } + assert(numberOfBytesWritten == fileSize); + } - delete[] fileName; + delete[] fileName; - ReleaseSaveAccess(); + ReleaseSaveAccess(); } #endif -unsigned int ConsoleSaveFileOriginal::getSizeOnDisk() -{ - return header.GetFileSize(); +unsigned int ConsoleSaveFileOriginal::getSizeOnDisk() { + return header.GetFileSize(); } -std::wstring ConsoleSaveFileOriginal::getFilename() -{ - return m_fileName; +std::wstring ConsoleSaveFileOriginal::getFilename() { return m_fileName; } + +std::vector* ConsoleSaveFileOriginal::getFilesWithPrefix( + const std::wstring& prefix) { + return header.getFilesWithPrefix(prefix); } -std::vector *ConsoleSaveFileOriginal::getFilesWithPrefix(const std::wstring &prefix) -{ - return header.getFilesWithPrefix( prefix ); -} - -std::vector *ConsoleSaveFileOriginal::getRegionFilesByDimension(unsigned int dimensionIndex) -{ - return NULL; +std::vector* ConsoleSaveFileOriginal::getRegionFilesByDimension( + unsigned int dimensionIndex) { + return NULL; } #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) -std::wstring ConsoleSaveFileOriginal::getPlayerDataFilenameForLoad(const PlayerUID& pUID) -{ - return header.getPlayerDataFilenameForLoad( pUID ); +std::wstring ConsoleSaveFileOriginal::getPlayerDataFilenameForLoad( + const PlayerUID& pUID) { + return header.getPlayerDataFilenameForLoad(pUID); } -std::wstring ConsoleSaveFileOriginal::getPlayerDataFilenameForSave(const PlayerUID& pUID) -{ - return header.getPlayerDataFilenameForSave( pUID ); +std::wstring ConsoleSaveFileOriginal::getPlayerDataFilenameForSave( + const PlayerUID& pUID) { + return header.getPlayerDataFilenameForSave(pUID); } -std::vector *ConsoleSaveFileOriginal::getValidPlayerDatFiles() -{ - return header.getValidPlayerDatFiles(); +std::vector* ConsoleSaveFileOriginal::getValidPlayerDatFiles() { + return header.getValidPlayerDatFiles(); } #endif -int ConsoleSaveFileOriginal::getSaveVersion() -{ - return header.getSaveVersion(); +int ConsoleSaveFileOriginal::getSaveVersion() { + return header.getSaveVersion(); } -int ConsoleSaveFileOriginal::getOriginalSaveVersion() -{ - return header.getOriginalSaveVersion(); +int ConsoleSaveFileOriginal::getOriginalSaveVersion() { + return header.getOriginalSaveVersion(); } -void ConsoleSaveFileOriginal::LockSaveAccess() -{ - EnterCriticalSection(&m_lock); +void ConsoleSaveFileOriginal::LockSaveAccess() { + EnterCriticalSection(&m_lock); } -void ConsoleSaveFileOriginal::ReleaseSaveAccess() -{ - LeaveCriticalSection(&m_lock); +void ConsoleSaveFileOriginal::ReleaseSaveAccess() { + LeaveCriticalSection(&m_lock); } -ESavePlatform ConsoleSaveFileOriginal::getSavePlatform() -{ - return header.getSavePlatform(); +ESavePlatform ConsoleSaveFileOriginal::getSavePlatform() { + return header.getSavePlatform(); } -bool ConsoleSaveFileOriginal::isSaveEndianDifferent() -{ - return header.isSaveEndianDifferent(); +bool ConsoleSaveFileOriginal::isSaveEndianDifferent() { + return header.isSaveEndianDifferent(); } -void ConsoleSaveFileOriginal::setLocalPlatform() -{ - header.setLocalPlatform(); +void ConsoleSaveFileOriginal::setLocalPlatform() { header.setLocalPlatform(); } + +void ConsoleSaveFileOriginal::setPlatform(ESavePlatform plat) { + header.setPlatform(plat); } -void ConsoleSaveFileOriginal::setPlatform(ESavePlatform plat) -{ - header.setPlatform(plat); +ByteOrder ConsoleSaveFileOriginal::getSaveEndian() { + return header.getSaveEndian(); } -ByteOrder ConsoleSaveFileOriginal::getSaveEndian() -{ - return header.getSaveEndian(); +ByteOrder ConsoleSaveFileOriginal::getLocalEndian() { + return header.getLocalEndian(); } -ByteOrder ConsoleSaveFileOriginal::getLocalEndian() -{ - return header.getLocalEndian(); +void ConsoleSaveFileOriginal::setEndian(ByteOrder endian) { + header.setEndian(endian); } -void ConsoleSaveFileOriginal::setEndian(ByteOrder endian) -{ - header.setEndian(endian); +bool ConsoleSaveFileOriginal::isLocalEndianDifferent(ESavePlatform plat) { + return getLocalEndian() != header.getEndian(plat); } -bool ConsoleSaveFileOriginal::isLocalEndianDifferent( ESavePlatform plat ) -{ - return getLocalEndian() != header.getEndian(plat); +void ConsoleSaveFileOriginal::ConvertRegionFile(File sourceFile) { + unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesRead = 0; + + RegionFile sourceRegionFile(this, &sourceFile); + + for (unsigned int x = 0; x < 32; ++x) { + for (unsigned int z = 0; z < 32; ++z) { + DataInputStream* dis = + sourceRegionFile.getChunkDataInputStream(x, z); + + if (dis) { + byteArray inData(1024 * 1024); + int read = dis->read(inData); + dis->close(); + dis->deleteChildStream(); + delete dis; + + DataOutputStream* dos = + sourceRegionFile.getChunkDataOutputStream(x, z); + dos->write(inData, 0, read); + + dos->close(); + dos->deleteChildStream(); + delete dos; + delete inData.data; + } + } + } + sourceRegionFile + .writeAllOffsets(); // saves all the endian swapped offsets back out to + // the file (not all of these are written in the + // above processing). } +void ConsoleSaveFileOriginal::ConvertToLocalPlatform() { + if (getSavePlatform() == SAVE_FILE_PLATFORM_LOCAL) { + // already in the correct format + return; + } + // convert each of the region files to the local platform + std::vector* allFilesInSave = + getFilesWithPrefix(std::wstring(L"")); + for (AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); + ++it) { + FileEntry* fe = *it; + std::wstring fName(fe->data.filename); + std::wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), + suffix) == 0) { + app.DebugPrintf("Processing a region file: %ls\n", fName.c_str()); + ConvertRegionFile(File(fe->data.filename)); + } else { + app.DebugPrintf("%ls is not a region file, ignoring\n", + fName.c_str()); + } + } -void ConsoleSaveFileOriginal::ConvertRegionFile(File sourceFile) -{ - unsigned int numberOfBytesWritten = 0; - unsigned int numberOfBytesRead = 0; - - RegionFile sourceRegionFile(this, &sourceFile); - - for(unsigned int x = 0; x < 32; ++x) - { - for(unsigned int z = 0; z < 32; ++z) - { - DataInputStream *dis = sourceRegionFile.getChunkDataInputStream(x,z); - - if(dis) - { - byteArray inData(1024*1024); - int read = dis->read(inData); - dis->close(); - dis->deleteChildStream(); - delete dis; - - DataOutputStream *dos = sourceRegionFile.getChunkDataOutputStream(x,z); - dos->write(inData, 0, read); - - - dos->close(); - dos->deleteChildStream(); - delete dos; - delete inData.data; - - } - - } - } - sourceRegionFile.writeAllOffsets(); // saves all the endian swapped offsets back out to the file (not all of these are written in the above processing). - + setLocalPlatform(); // set the platform of this save to the local platform, + // now that it's been coverted } -void ConsoleSaveFileOriginal::ConvertToLocalPlatform() -{ - if(getSavePlatform() == SAVE_FILE_PLATFORM_LOCAL) - { - // already in the correct format - return; - } - // convert each of the region files to the local platform - std::vector *allFilesInSave = getFilesWithPrefix(std::wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) - { - FileEntry *fe = *it; - std::wstring fName( fe->data.filename ); - std::wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) - { - app.DebugPrintf("Processing a region file: %ls\n",fName.c_str()); - ConvertRegionFile(File(fe->data.filename) ); - } - else - { - app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); - } - } - - setLocalPlatform(); // set the platform of this save to the local platform, now that it's been coverted -} - -void *ConsoleSaveFileOriginal::getWritePointer(FileEntry *file) -{ - return (char *)pvSaveMem + file->currentFilePointer;; +void* ConsoleSaveFileOriginal::getWritePointer(FileEntry* file) { + return (char*)pvSaveMem + file->currentFilePointer; + ; } diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.h b/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.h index 6cbf2ce4b..60f381289 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFileOriginal.h @@ -4,91 +4,105 @@ #include "ConsoleSavePath.h" #include "ConsoleSaveFile.h" -class ConsoleSaveFileOriginal : public ConsoleSaveFile -{ +class ConsoleSaveFileOriginal : public ConsoleSaveFile { private: - FileHeader header; + FileHeader header; - std::wstring m_fileName; + std::wstring m_fileName; -// HANDLE hHeap; - static void *pvHeap; - static unsigned int pagesCommitted; + // HANDLE hHeap; + static void* pvHeap; + static unsigned int pagesCommitted; #ifdef _LARGE_WORLDS - static const unsigned int CSF_PAGE_SIZE = 64 * 1024; - static const unsigned int MAX_PAGE_COUNT = 32 * 1024; // 2GB virtual allocation + static const unsigned int CSF_PAGE_SIZE = 64 * 1024; + static const unsigned int MAX_PAGE_COUNT = + 32 * 1024; // 2GB virtual allocation #elif defined(__PS3__) - static const unsigned int CSF_PAGE_SIZE = 1024 * 1024; - static const unsigned int MAX_PAGE_COUNT = 64; + static const unsigned int CSF_PAGE_SIZE = 1024 * 1024; + static const unsigned int MAX_PAGE_COUNT = 64; #else - static const unsigned int CSF_PAGE_SIZE = 64 * 1024; - static const unsigned int MAX_PAGE_COUNT = 1024; + static const unsigned int CSF_PAGE_SIZE = 64 * 1024; + static const unsigned int MAX_PAGE_COUNT = 1024; #endif - void *pvSaveMem; + void* pvSaveMem; - CRITICAL_SECTION m_lock; + CRITICAL_SECTION m_lock; - void PrepareForWrite( FileEntry *file, unsigned int nNumberOfBytesToWrite ); - void MoveDataBeyond(FileEntry *file, unsigned int nNumberOfBytesToWrite); + void PrepareForWrite(FileEntry* file, unsigned int nNumberOfBytesToWrite); + void MoveDataBeyond(FileEntry* file, unsigned int nNumberOfBytesToWrite); public: -#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined _DURANGO || defined _WINDOWS64) - static int SaveSaveDataCallback(void *lpParam, bool bRes); +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined _DURANGO || defined _WINDOWS64) + static int SaveSaveDataCallback(void* lpParam, bool bRes); #endif - ConsoleSaveFileOriginal(const std::wstring &fileName, void *pvSaveData = NULL, unsigned int fileSize = 0, bool forceCleanSave = false, ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); - virtual ~ConsoleSaveFileOriginal(); + ConsoleSaveFileOriginal(const std::wstring& fileName, + void* pvSaveData = NULL, unsigned int fileSize = 0, + bool forceCleanSave = false, + ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); + virtual ~ConsoleSaveFileOriginal(); - // 4J Stu - Initial implementation is intended to have a similar interface to the standard Xbox file access functions + // 4J Stu - Initial implementation is intended to have a similar interface + // to the standard Xbox file access functions - virtual FileEntry *createFile( const ConsoleSavePath &fileName ); - virtual void deleteFile( FileEntry *file ); + virtual FileEntry* createFile(const ConsoleSavePath& fileName); + virtual void deleteFile(FileEntry* file); - virtual void setFilePointer(FileEntry *file, unsigned int distanceToMove, SaveFileSeekOrigin seekOrigin); - virtual bool writeFile( FileEntry *file, const void *lpBuffer, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten ); - virtual bool zeroFile(FileEntry *file, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten); - virtual bool readFile( FileEntry *file, void *lpBuffer, unsigned int nNumberOfBytesToRead, unsigned int *lpNumberOfBytesRead ); - virtual bool closeHandle( FileEntry *file ); + virtual void setFilePointer(FileEntry* file, unsigned int distanceToMove, + SaveFileSeekOrigin seekOrigin); + virtual bool writeFile(FileEntry* file, const void* lpBuffer, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten); + virtual bool zeroFile(FileEntry* file, unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten); + virtual bool readFile(FileEntry* file, void* lpBuffer, + unsigned int nNumberOfBytesToRead, + unsigned int* lpNumberOfBytesRead); + virtual bool closeHandle(FileEntry* file); - virtual void finalizeWrite(); + virtual void finalizeWrite(); - virtual bool doesFileExist(ConsoleSavePath file); + virtual bool doesFileExist(ConsoleSavePath file); - virtual void Flush(bool autosave, bool updateThumbnail = true); + virtual void Flush(bool autosave, bool updateThumbnail = true); #ifndef _CONTENT_PACKAGE - virtual void DebugFlushToFile(void *compressedData = NULL, unsigned int compressedDataSize = 0); + virtual void DebugFlushToFile(void* compressedData = NULL, + unsigned int compressedDataSize = 0); #endif - virtual unsigned int getSizeOnDisk(); + virtual unsigned int getSizeOnDisk(); - virtual std::wstring getFilename(); + virtual std::wstring getFilename(); - virtual std::vector *getFilesWithPrefix(const std::wstring &prefix); - virtual std::vector *getRegionFilesByDimension(unsigned int dimensionIndex); + virtual std::vector* getFilesWithPrefix( + const std::wstring& prefix); + virtual std::vector* getRegionFilesByDimension( + unsigned int dimensionIndex); #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - virtual std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); - virtual std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); - virtual std::vector *getValidPlayerDatFiles(); -#endif //__PS3__ + virtual std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); + virtual std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); + virtual std::vector* getValidPlayerDatFiles(); +#endif //__PS3__ - virtual int getSaveVersion(); - virtual int getOriginalSaveVersion(); + virtual int getSaveVersion(); + virtual int getOriginalSaveVersion(); - virtual void LockSaveAccess(); - virtual void ReleaseSaveAccess(); + virtual void LockSaveAccess(); + virtual void ReleaseSaveAccess(); - virtual ESavePlatform getSavePlatform(); - virtual bool isSaveEndianDifferent(); - virtual void setLocalPlatform(); - virtual void setPlatform(ESavePlatform plat); - virtual ByteOrder getSaveEndian(); - virtual ByteOrder getLocalEndian(); - virtual void setEndian(ByteOrder endian); - virtual bool isLocalEndianDifferent(ESavePlatform plat); + virtual ESavePlatform getSavePlatform(); + virtual bool isSaveEndianDifferent(); + virtual void setLocalPlatform(); + virtual void setPlatform(ESavePlatform plat); + virtual ByteOrder getSaveEndian(); + virtual ByteOrder getLocalEndian(); + virtual void setEndian(ByteOrder endian); + virtual bool isLocalEndianDifferent(ESavePlatform plat); - virtual void ConvertRegionFile(File sourceFile); - virtual void ConvertToLocalPlatform(); + virtual void ConvertRegionFile(File sourceFile); + virtual void ConvertToLocalPlatform(); protected: - virtual void *getWritePointer(FileEntry *file); + virtual void* getWritePointer(FileEntry* file); }; diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.cpp b/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.cpp index 93a42efb7..adde9fa11 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.cpp +++ b/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.cpp @@ -4,127 +4,113 @@ #include "ConsoleSaveFile.h" -//Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is -//created to represent this file connection. -//First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument. +// Creates a file output stream to write to the file represented by the +// specified File object. A new FileDescriptor object is created to represent +// this file connection. First, if there is a security manager, its checkWrite +// method is called with the path represented by the file argument as its +// argument. // -//If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened -//for any other reason then a FileNotFoundException is thrown. +// If the file exists but is a directory rather than a regular file, does not +// exist but cannot be created, or cannot be opened for any other reason then a +// FileNotFoundException is thrown. // -//Parameters: -//file - the file to be opened for writing. -ConsoleSaveFileOutputStream::ConsoleSaveFileOutputStream(ConsoleSaveFile *saveFile, const ConsoleSavePath &file) -{ - m_saveFile = saveFile; +// Parameters: +// file - the file to be opened for writing. +ConsoleSaveFileOutputStream::ConsoleSaveFileOutputStream( + ConsoleSaveFile* saveFile, const ConsoleSavePath& file) { + m_saveFile = saveFile; - m_file = m_saveFile->createFile(file); + m_file = m_saveFile->createFile(file); - m_saveFile->setFilePointer( m_file, 0, SaveFileSeekOrigin::Begin ); + m_saveFile->setFilePointer(m_file, 0, SaveFileSeekOrigin::Begin); } -ConsoleSaveFileOutputStream::ConsoleSaveFileOutputStream(ConsoleSaveFile *saveFile, FileEntry *file) -{ - m_saveFile = saveFile; +ConsoleSaveFileOutputStream::ConsoleSaveFileOutputStream( + ConsoleSaveFile* saveFile, FileEntry* file) { + m_saveFile = saveFile; - m_file = file; + m_file = file; - m_saveFile->setFilePointer( m_file, 0, SaveFileSeekOrigin::Begin ); + m_saveFile->setFilePointer(m_file, 0, SaveFileSeekOrigin::Begin); } -//Writes the specified byte to this file output stream. Implements the write method of OutputStream. -//Parameters: -//b - the byte to be written. -void ConsoleSaveFileOutputStream::write(unsigned int b) -{ - unsigned int numberOfBytesWritten; +// Writes the specified byte to this file output stream. Implements the write +// method of OutputStream. Parameters: b - the byte to be written. +void ConsoleSaveFileOutputStream::write(unsigned int b) { + unsigned int numberOfBytesWritten; - std::uint8_t value = (std::uint8_t) b; + std::uint8_t value = (std::uint8_t)b; - bool result = m_saveFile->writeFile( - m_file, - &value, // data buffer - 1, // number of bytes to write - &numberOfBytesWritten // number of bytes written - ); + bool result = + m_saveFile->writeFile(m_file, + &value, // data buffer + 1, // number of bytes to write + &numberOfBytesWritten // number of bytes written + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 ) - { - // File pointer is past the end of the file - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0) { + // File pointer is past the end of the file + } } -//Writes b.length bytes from the specified byte array to this file output stream. -//Parameters: -//b - the data. -void ConsoleSaveFileOutputStream::write(byteArray b) -{ - unsigned int numberOfBytesWritten; +// Writes b.length bytes from the specified byte array to this file output +// stream. Parameters: b - the data. +void ConsoleSaveFileOutputStream::write(byteArray b) { + unsigned int numberOfBytesWritten; - bool result = m_saveFile->writeFile( - m_file, - &b.data, // data buffer - b.length, // number of bytes to write - &numberOfBytesWritten // number of bytes written - ); + bool result = + m_saveFile->writeFile(m_file, + &b.data, // data buffer + b.length, // number of bytes to write + &numberOfBytesWritten // number of bytes written + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 || numberOfBytesWritten != b.length ) - { - // File pointer is past the end of the file - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0 || numberOfBytesWritten != b.length) { + // File pointer is past the end of the file + } } -//Writes len bytes from the specified byte array starting at offset off to this file output stream. -//Parameters: -//b - the data. -//off - the start offset in the data. -//len - the number of bytes to write. -void ConsoleSaveFileOutputStream::write(byteArray b, unsigned int offset, unsigned int length) -{ - // 4J Stu - We don't want to write any more than the array buffer holds - assert( length <= ( b.length - offset ) ); +// Writes len bytes from the specified byte array starting at offset off to this +// file output stream. Parameters: b - the data. off - the start offset in the +// data. len - the number of bytes to write. +void ConsoleSaveFileOutputStream::write(byteArray b, unsigned int offset, + unsigned int length) { + // 4J Stu - We don't want to write any more than the array buffer holds + assert(length <= (b.length - offset)); - unsigned int numberOfBytesWritten; + unsigned int numberOfBytesWritten; - bool result = m_saveFile->writeFile( - m_file, - &b[offset], // data buffer - length, // number of bytes to write - &numberOfBytesWritten // number of bytes written - ); + bool result = + m_saveFile->writeFile(m_file, + &b[offset], // data buffer + length, // number of bytes to write + &numberOfBytesWritten // number of bytes written + ); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 || numberOfBytesWritten != length ) - { - // File pointer is past the end of the file - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0 || numberOfBytesWritten != length) { + // File pointer is past the end of the file + } } // -//Closes this file output stream and releases any system resources associated with this stream. -//This file output stream may no longer be used for writing bytes. -//If this stream has an associated channel then the channel is closed as well. -void ConsoleSaveFileOutputStream::close() -{ - if( m_saveFile != NULL ) - { - bool result = m_saveFile->closeHandle( m_file ); +// Closes this file output stream and releases any system resources associated +// with this stream. This file output stream may no longer be used for writing +// bytes. If this stream has an associated channel then the channel is closed as +// well. +void ConsoleSaveFileOutputStream::close() { + if (m_saveFile != NULL) { + bool result = m_saveFile->closeHandle(m_file); - if( !result ) - { - // TODO 4J Stu - Some kind of error handling - } + if (!result) { + // TODO 4J Stu - Some kind of error handling + } - // Stop the dtor from trying to close it again - m_saveFile = NULL; - } + // Stop the dtor from trying to close it again + m_saveFile = NULL; + } } diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.h b/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.h index b3d8224a8..4559cbd12 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFileOutputStream.h @@ -1,5 +1,6 @@ #pragma once -// 4J Stu - Implements the Java InputStream but rather than writing directly to disc it writes through the save file +// 4J Stu - Implements the Java InputStream but rather than writing directly to +// disc it writes through the save file #include "../Streams/OutputStream.h" @@ -8,18 +9,18 @@ class ConsoleSaveFile; class FileEntry; -class ConsoleSaveFileOutputStream : public OutputStream -{ +class ConsoleSaveFileOutputStream : public OutputStream { public: - ConsoleSaveFileOutputStream(ConsoleSaveFile *saveFile, const ConsoleSavePath &file); - ConsoleSaveFileOutputStream(ConsoleSaveFile *saveFile, FileEntry *file); - virtual void write(unsigned int b); - virtual void write(byteArray b); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual void flush() {} + ConsoleSaveFileOutputStream(ConsoleSaveFile* saveFile, + const ConsoleSavePath& file); + ConsoleSaveFileOutputStream(ConsoleSaveFile* saveFile, FileEntry* file); + virtual void write(unsigned int b); + virtual void write(byteArray b); + virtual void write(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual void flush() {} private: - ConsoleSaveFile *m_saveFile; - FileEntry *m_file; + ConsoleSaveFile* m_saveFile; + FileEntry* m_file; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileSplit.cpp b/Minecraft.World/IO/Files/ConsoleSaveFileSplit.cpp index 1c363bb48..a78000f75 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileSplit.cpp +++ b/Minecraft.World/IO/Files/ConsoleSaveFileSplit.cpp @@ -14,1189 +14,1146 @@ #include "../../../Minecraft.Client/Platform/Common/GameRules/LevelGenerationOptions.h" #include "../../Headers/net.minecraft.world.level.chunk.storage.h" -#define RESERVE_ALLOCATION MEM_RESERVE -#define COMMIT_ALLOCATION MEM_COMMIT +#define RESERVE_ALLOCATION MEM_RESERVE +#define COMMIT_ALLOCATION MEM_COMMIT unsigned int ConsoleSaveFileSplit::pagesCommitted = 0; -void *ConsoleSaveFileSplit::pvHeap = NULL; +void* ConsoleSaveFileSplit::pvHeap = NULL; -ConsoleSaveFileSplit::RegionFileReference::RegionFileReference(int index, unsigned int regionIndex, unsigned int length/*=0*/, unsigned char *data/*=NULL*/) -{ - fileEntry = new FileEntry(); - fileEntry->currentFilePointer = 0; - fileEntry->data.length = 0; - fileEntry->data.regionIndex = regionIndex; - this->data = 0; - this->index = index; - this->dirty = false; - this->dataCompressed = data; - this->dataCompressedSize = length; - this->lastWritten = 0; +ConsoleSaveFileSplit::RegionFileReference::RegionFileReference( + int index, unsigned int regionIndex, unsigned int length /*=0*/, + unsigned char* data /*=NULL*/) { + fileEntry = new FileEntry(); + fileEntry->currentFilePointer = 0; + fileEntry->data.length = 0; + fileEntry->data.regionIndex = regionIndex; + this->data = 0; + this->index = index; + this->dirty = false; + this->dataCompressed = data; + this->dataCompressedSize = length; + this->lastWritten = 0; } -ConsoleSaveFileSplit::RegionFileReference::~RegionFileReference() -{ - free(data); - delete fileEntry; +ConsoleSaveFileSplit::RegionFileReference::~RegionFileReference() { + free(data); + delete fileEntry; } -// Compress from data to dataCompressed. Uses a special compression method that is designed just to efficiently store runs of zeros, with little overhead on other stuff. -// Compresed format is a 4 byte uncompressed size, followed by data as follows: -// -// Byte value Meaning +// Compress from data to dataCompressed. Uses a special compression method that +// is designed just to efficiently store runs of zeros, with little overhead on +// other stuff. Compresed format is a 4 byte uncompressed size, followed by data +// as follows: // -// 1 - 255 Normal data -// 0 followed by 1 - 255 Run of 1 - 255 0s -// 0 followed by 0, followed by 256 to 65791 (as 2 bytes) Run of 256 to 65791 zeros +// Byte value +// Meaning +// +// 1 - 255 +// Normal data 0 followed by 1 - 255 +// Run of 1 - 255 0s 0 followed by 0, followed by 256 to 65791 (as 2 bytes) +// Run of 256 to 65791 zeros -void ConsoleSaveFileSplit::RegionFileReference::Compress() -{ - unsigned char *dataIn = data; - unsigned char *dataInLast = data + fileEntry->data.length; +void ConsoleSaveFileSplit::RegionFileReference::Compress() { + unsigned char* dataIn = data; + unsigned char* dataInLast = data + fileEntry->data.length; -// std::int64_t startTime = System::currentTimeMillis(); + // std::int64_t startTime = System::currentTimeMillis(); - // One pass through to work out storage space required for compressed data - unsigned int outputSize = 4; // 4 bytes required to store the uncompressed size for faster decompression - unsigned int runLength = 0; - while( dataIn != dataInLast ) - { - unsigned char thisByte = *dataIn++; - if( ( thisByte != 0 ) || ( runLength == ( 65535 + 256 ) ) ) - { - // We've got a non-zero value, or we've hit our maximum run length. - // If there was a preceeding run of zeros, encode that nwo - if( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - outputSize += 2; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - outputSize += 4; - } - // Run is now processed - runLength = 0; - } - // Now handle the current byte - if( thisByte == 0 ) - { - runLength++; - } - else - { - // Non-zero, just copy over to output - outputSize++; - } - } - else - { - // It's a zero - keep counting size of the run - runLength++; - } - } - // Handle any outstanding run - if ( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - outputSize += 2; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - outputSize += 4; - } - // Run is now processed - runLength = 0; - } + // One pass through to work out storage space required for compressed data + unsigned int outputSize = 4; // 4 bytes required to store the uncompressed + // size for faster decompression + unsigned int runLength = 0; + while (dataIn != dataInLast) { + unsigned char thisByte = *dataIn++; + if ((thisByte != 0) || (runLength == (65535 + 256))) { + // We've got a non-zero value, or we've hit our maximum run length. + // If there was a preceeding run of zeros, encode that nwo + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run + // length + outputSize += 2; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two + // bytes of run length - 256 + outputSize += 4; + } + // Run is now processed + runLength = 0; + } + // Now handle the current byte + if (thisByte == 0) { + runLength++; + } else { + // Non-zero, just copy over to output + outputSize++; + } + } else { + // It's a zero - keep counting size of the run + runLength++; + } + } + // Handle any outstanding run + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run length + outputSize += 2; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two bytes of + // run length - 256 + outputSize += 4; + } + // Run is now processed + runLength = 0; + } - // Now actually allocate & write the compress data. First 4 bytes store the uncompressed size - dataCompressed = (unsigned char *)malloc(outputSize); - *((unsigned int *)dataCompressed) = fileEntry->data.length; - unsigned char *dataOut = dataCompressed + 4; - dataIn = data; + // Now actually allocate & write the compress data. First 4 bytes store the + // uncompressed size + dataCompressed = (unsigned char*)malloc(outputSize); + *((unsigned int*)dataCompressed) = fileEntry->data.length; + unsigned char* dataOut = dataCompressed + 4; + dataIn = data; - // Now same process as before, but actually writing - while( dataIn != dataInLast ) - { - unsigned char thisByte = *dataIn++; - if( ( thisByte != 0 ) || ( runLength == ( 65535 + 256 ) ) ) - { - // We've got a non-zero value, or we've hit our maximum run length. - // If there was a preceeding run of zeros, encode that nwo - if( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - *dataOut++ = 0; - *dataOut++ = runLength; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - *dataOut++ = 0; - *dataOut++ = 0; - unsigned int largeRunLength = runLength - 256; - *dataOut++ = ( largeRunLength >> 8 ) & 0xff; - *dataOut++ = ( largeRunLength ) & 0xff; - } - // Run is now processed - runLength = 0; - } - // Now handle the current byte - if( thisByte == 0 ) - { - runLength++; - } - else - { - // Non-zero, just copy over to output - *dataOut++ = thisByte; - } - } - else - { - // It's a zero - keep counting size of the run - runLength++; - } - } - // Handle any outstanding run - if( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - *dataOut++ = 0; - *dataOut++ = runLength; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - *dataOut++ = 0; - *dataOut++ = 0; - unsigned int largeRunLength = runLength - 256; - *dataOut++ = ( largeRunLength >> 8 ) & 0xff; - *dataOut++ = ( largeRunLength ) & 0xff; - } - // Run is now processed - runLength = 0; - } - assert(( dataOut - dataCompressed ) == outputSize ); - dataCompressedSize = outputSize; -// std::int64_t endTime = System::currentTimeMillis(); -// app.DebugPrintf("Compressing region file 0x%.8x from %d to %d bytes - %dms\n", fileEntry->data.regionIndex, fileEntry->data.length, dataCompressedSize, endTime - startTime); + // Now same process as before, but actually writing + while (dataIn != dataInLast) { + unsigned char thisByte = *dataIn++; + if ((thisByte != 0) || (runLength == (65535 + 256))) { + // We've got a non-zero value, or we've hit our maximum run length. + // If there was a preceeding run of zeros, encode that nwo + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run + // length + *dataOut++ = 0; + *dataOut++ = runLength; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two + // bytes of run length - 256 + *dataOut++ = 0; + *dataOut++ = 0; + unsigned int largeRunLength = runLength - 256; + *dataOut++ = (largeRunLength >> 8) & 0xff; + *dataOut++ = (largeRunLength) & 0xff; + } + // Run is now processed + runLength = 0; + } + // Now handle the current byte + if (thisByte == 0) { + runLength++; + } else { + // Non-zero, just copy over to output + *dataOut++ = thisByte; + } + } else { + // It's a zero - keep counting size of the run + runLength++; + } + } + // Handle any outstanding run + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run length + *dataOut++ = 0; + *dataOut++ = runLength; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two bytes of + // run length - 256 + *dataOut++ = 0; + *dataOut++ = 0; + unsigned int largeRunLength = runLength - 256; + *dataOut++ = (largeRunLength >> 8) & 0xff; + *dataOut++ = (largeRunLength) & 0xff; + } + // Run is now processed + runLength = 0; + } + assert((dataOut - dataCompressed) == outputSize); + dataCompressedSize = outputSize; + // std::int64_t endTime = System::currentTimeMillis(); + // app.DebugPrintf("Compressing region file 0x%.8x from %d to %d bytes - + //%dms\n", fileEntry->data.regionIndex, fileEntry->data.length, + //dataCompressedSize, endTime - startTime); } -// Decompress from dataCompressed -> data. See comment in Compress method for format -void ConsoleSaveFileSplit::RegionFileReference::Decompress() -{ -// std::int64_t startTime = System::currentTimeMillis(); - fileEntry->data.length = *((unsigned int *)dataCompressed); +// Decompress from dataCompressed -> data. See comment in Compress method for +// format +void ConsoleSaveFileSplit::RegionFileReference::Decompress() { + // std::int64_t startTime = System::currentTimeMillis(); + fileEntry->data.length = *((unsigned int*)dataCompressed); - // If this is unusually large, then test how big it would be when expanded before trying to allocate. Matching the expanded size - // is (currently) our means of knowing that this file is ok - if( fileEntry->data.length > 1 * 1024 * 1024 ) - { - unsigned int uncompressedSize = 0; - unsigned char *dataIn = dataCompressed + 4; - unsigned char *dataInLast = dataCompressed + dataCompressedSize; + // If this is unusually large, then test how big it would be when expanded + // before trying to allocate. Matching the expanded size is (currently) our + // means of knowing that this file is ok + if (fileEntry->data.length > 1 * 1024 * 1024) { + unsigned int uncompressedSize = 0; + unsigned char* dataIn = dataCompressed + 4; + unsigned char* dataInLast = dataCompressed + dataCompressedSize; - while (dataIn != dataInLast) - { - unsigned char thisByte = *dataIn++; - if( thisByte == 0 ) - { - thisByte = *dataIn++; - if( thisByte == 0 ) - { - unsigned int runLength = (*dataIn++) << 8; - runLength |= (*dataIn++); - runLength += 256; - uncompressedSize += runLength; - } - else - { - unsigned int runLength = thisByte; - uncompressedSize += runLength; - } - } - else - { - uncompressedSize++; - } - } + while (dataIn != dataInLast) { + unsigned char thisByte = *dataIn++; + if (thisByte == 0) { + thisByte = *dataIn++; + if (thisByte == 0) { + unsigned int runLength = (*dataIn++) << 8; + runLength |= (*dataIn++); + runLength += 256; + uncompressedSize += runLength; + } else { + unsigned int runLength = thisByte; + uncompressedSize += runLength; + } + } else { + uncompressedSize++; + } + } - if( fileEntry->data.length != uncompressedSize ) - { - // Treat as if it was an empty region file - fileEntry->data.length = 0; - assert(0); - return; - } - } + if (fileEntry->data.length != uncompressedSize) { + // Treat as if it was an empty region file + fileEntry->data.length = 0; + assert(0); + return; + } + } + data = (unsigned char*)malloc(fileEntry->data.length); + unsigned char* dataIn = dataCompressed + 4; + unsigned char* dataInLast = dataCompressed + dataCompressedSize; + unsigned char* dataOut = data; - data = (unsigned char *)malloc(fileEntry->data.length); - unsigned char *dataIn = dataCompressed + 4; - unsigned char *dataInLast = dataCompressed + dataCompressedSize; - unsigned char *dataOut = data; - - while (dataIn != dataInLast) - { - unsigned char thisByte = *dataIn++; - if( thisByte == 0 ) - { - thisByte = *dataIn++; - if( thisByte == 0 ) - { - unsigned int runLength = (*dataIn++) << 8; - runLength |= (*dataIn++); - runLength += 256; - for( unsigned int i = 0; i < runLength; i++ ) - { - *dataOut++ = 0; - } - } - else - { - unsigned int runLength = thisByte; - for( unsigned int i = 0; i < runLength; i++ ) - { - *dataOut++ = 0; - } - } - } - else - { - *dataOut++ = thisByte; - } - } - // If we failed to correctly decompress, then treat as if it was an empty region file - if( ( dataOut - data ) != fileEntry->data.length ) - { - free(data); - fileEntry->data.length = 0; - data = NULL; - assert(0); - } -// std::int64_t endTime = System::currentTimeMillis(); -// app.DebugPrintf("Decompressing region file from 0x%.8x %d to %d bytes - %dms\n", fileEntry->data.regionIndex, dataCompressedSize, fileEntry->data.length, endTime - startTime);// + while (dataIn != dataInLast) { + unsigned char thisByte = *dataIn++; + if (thisByte == 0) { + thisByte = *dataIn++; + if (thisByte == 0) { + unsigned int runLength = (*dataIn++) << 8; + runLength |= (*dataIn++); + runLength += 256; + for (unsigned int i = 0; i < runLength; i++) { + *dataOut++ = 0; + } + } else { + unsigned int runLength = thisByte; + for (unsigned int i = 0; i < runLength; i++) { + *dataOut++ = 0; + } + } + } else { + *dataOut++ = thisByte; + } + } + // If we failed to correctly decompress, then treat as if it was an empty + // region file + if ((dataOut - data) != fileEntry->data.length) { + free(data); + fileEntry->data.length = 0; + data = NULL; + assert(0); + } + // std::int64_t endTime = System::currentTimeMillis(); + // app.DebugPrintf("Decompressing region file from 0x%.8x %d to %d bytes - + //%dms\n", fileEntry->data.regionIndex, dataCompressedSize, + //fileEntry->data.length, endTime - startTime);// } -unsigned int ConsoleSaveFileSplit::RegionFileReference::GetCompressedSize() -{ - unsigned char *dataIn = data; - unsigned char *dataInLast = data + fileEntry->data.length; +unsigned int ConsoleSaveFileSplit::RegionFileReference::GetCompressedSize() { + unsigned char* dataIn = data; + unsigned char* dataInLast = data + fileEntry->data.length; - unsigned int outputSize = 4; // 4 bytes required to store the uncompressed size for faster decompression - unsigned int runLength = 0; - while( dataIn != dataInLast ) - { - unsigned char thisByte = *dataIn++; - if( ( thisByte != 0 ) || ( runLength == ( 65535 + 256 ) ) ) - { - // We've got a non-zero value, or we've hit our maximum run length. - // If there was a preceeding run of zeros, encode that nwo - if( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - outputSize += 2; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - outputSize += 4; - } - // Run is now processed - runLength = 0; - } - // Now handle the current byte - if( thisByte == 0 ) - { - runLength++; - } - else - { - // Non-zero, just copy over to output - outputSize++; - } - } - else - { - // It's a zero - keep counting size of the run - runLength++; - } - } - // Handle any outstanding run - if ( runLength != 0 ) - { - if( runLength < 256 ) - { - // Runs of 1 to 255 encoded as 0 followed by one byte of run length - outputSize += 2; - } - else - { - // Runs of 256 to 65791 encoded as two 0s followed by two bytes of run length - 256 - outputSize += 4; - } - // Run is now processed - runLength = 0; - } - return outputSize; + unsigned int outputSize = 4; // 4 bytes required to store the uncompressed + // size for faster decompression + unsigned int runLength = 0; + while (dataIn != dataInLast) { + unsigned char thisByte = *dataIn++; + if ((thisByte != 0) || (runLength == (65535 + 256))) { + // We've got a non-zero value, or we've hit our maximum run length. + // If there was a preceeding run of zeros, encode that nwo + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run + // length + outputSize += 2; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two + // bytes of run length - 256 + outputSize += 4; + } + // Run is now processed + runLength = 0; + } + // Now handle the current byte + if (thisByte == 0) { + runLength++; + } else { + // Non-zero, just copy over to output + outputSize++; + } + } else { + // It's a zero - keep counting size of the run + runLength++; + } + } + // Handle any outstanding run + if (runLength != 0) { + if (runLength < 256) { + // Runs of 1 to 255 encoded as 0 followed by one byte of run length + outputSize += 2; + } else { + // Runs of 256 to 65791 encoded as two 0s followed by two bytes of + // run length - 256 + outputSize += 4; + } + // Run is now processed + runLength = 0; + } + return outputSize; } // Release dataCompressed -void ConsoleSaveFileSplit::RegionFileReference::ReleaseCompressed() -{ -// app.DebugPrintf("Releasing compressed data for region file from 0x%.8x\n", fileEntry->data.regionIndex ); - free(dataCompressed); - dataCompressed = NULL; - dataCompressedSize = 0; +void ConsoleSaveFileSplit::RegionFileReference::ReleaseCompressed() { + // app.DebugPrintf("Releasing compressed data for region file from + //0x%.8x\n", fileEntry->data.regionIndex ); + free(dataCompressed); + dataCompressed = NULL; + dataCompressedSize = 0; } -FileEntry *ConsoleSaveFileSplit::GetRegionFileEntry(unsigned int regionIndex) -{ - // Is a region file - determine if we've got it as a separate file - AUTO_VAR(it, regionFiles.find(regionIndex) ); - if( it != regionFiles.end() ) - { - // Already got it - return it->second->fileEntry; - } +FileEntry* ConsoleSaveFileSplit::GetRegionFileEntry(unsigned int regionIndex) { + // Is a region file - determine if we've got it as a separate file + AUTO_VAR(it, regionFiles.find(regionIndex)); + if (it != regionFiles.end()) { + // Already got it + return it->second->fileEntry; + } - int index = StorageManager.AddSubfile(regionIndex); - RegionFileReference *newRef = new RegionFileReference(index, regionIndex); - regionFiles[regionIndex] = newRef; - - return newRef->fileEntry; + int index = StorageManager.AddSubfile(regionIndex); + RegionFileReference* newRef = new RegionFileReference(index, regionIndex); + regionFiles[regionIndex] = newRef; + + return newRef->fileEntry; } -ConsoleSaveFileSplit::ConsoleSaveFileSplit(const std::wstring &fileName, void *pvSaveData /*= NULL*/, unsigned int initialFileSize /*= 0*/, bool forceCleanSave /*= false*/, ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL*/) -{ - unsigned int fileSize = initialFileSize; +ConsoleSaveFileSplit::ConsoleSaveFileSplit( + const std::wstring& fileName, void* pvSaveData /*= NULL*/, + unsigned int initialFileSize /*= 0*/, bool forceCleanSave /*= false*/, + ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL*/) { + unsigned int fileSize = initialFileSize; - // Load a save from the game rules - bool bLevelGenBaseSave = false; - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if( pvSaveData == NULL && levelGen != NULL && levelGen->requiresBaseSave()) - { - pvSaveData = levelGen->getBaseSaveData(fileSize); - if(pvSaveData && fileSize != 0) bLevelGenBaseSave = true; - } + // Load a save from the game rules + bool bLevelGenBaseSave = false; + LevelGenerationOptions* levelGen = app.getLevelGenerationOptions(); + if (pvSaveData == NULL && levelGen != NULL && + levelGen->requiresBaseSave()) { + pvSaveData = levelGen->getBaseSaveData(fileSize); + if (pvSaveData && fileSize != 0) bLevelGenBaseSave = true; + } - if( pvSaveData == NULL || fileSize == 0) - fileSize = StorageManager.GetSaveSize(); + if (pvSaveData == NULL || fileSize == 0) + fileSize = StorageManager.GetSaveSize(); - if( forceCleanSave ) - fileSize = 0; + if (forceCleanSave) fileSize = 0; - _init(fileName, pvSaveData, fileSize, plat); + _init(fileName, pvSaveData, fileSize, plat); - if(bLevelGenBaseSave) - { - levelGen->deleteBaseSaveData(); - } + if (bLevelGenBaseSave) { + levelGen->deleteBaseSaveData(); + } } -ConsoleSaveFileSplit::ConsoleSaveFileSplit(ConsoleSaveFile *sourceSave, bool alreadySmallRegions, ProgressListener *progress) -{ - _init(sourceSave->getFilename(), NULL, 0, sourceSave->getSavePlatform()); +ConsoleSaveFileSplit::ConsoleSaveFileSplit(ConsoleSaveFile* sourceSave, + bool alreadySmallRegions, + ProgressListener* progress) { + _init(sourceSave->getFilename(), NULL, 0, sourceSave->getSavePlatform()); - header.setOriginalSaveVersion(sourceSave->getOriginalSaveVersion()); - header.setSaveVersion(sourceSave->getSaveVersion()); + header.setOriginalSaveVersion(sourceSave->getOriginalSaveVersion()); + header.setSaveVersion(sourceSave->getSaveVersion()); - if(alreadySmallRegions) - { + if (alreadySmallRegions) { + std::vector* sourceFiles = + sourceSave->getFilesWithPrefix(L""); - std::vector *sourceFiles = sourceSave->getFilesWithPrefix(L""); + unsigned int bytesWritten = 0; + for (AUTO_VAR(it, sourceFiles->begin()); it != sourceFiles->end(); + ++it) { + FileEntry* sourceEntry = *it; + sourceSave->setFilePointer(sourceEntry, 0, + SaveFileSeekOrigin::Begin); - unsigned int bytesWritten = 0; - for(AUTO_VAR(it, sourceFiles->begin()); it != sourceFiles->end(); ++it) - { - FileEntry *sourceEntry = *it; - sourceSave->setFilePointer(sourceEntry, 0, SaveFileSeekOrigin::Begin); + FileEntry* targetEntry = + createFile(ConsoleSavePath(sourceEntry->data.filename)); - FileEntry *targetEntry = createFile(ConsoleSavePath(sourceEntry->data.filename)); + writeFile(targetEntry, sourceSave->getWritePointer(sourceEntry), + sourceEntry->getFileSize(), &bytesWritten); + } - writeFile(targetEntry, sourceSave->getWritePointer(sourceEntry), sourceEntry->getFileSize(), &bytesWritten); - } - - delete sourceFiles; - } - else - { - ConsoleSaveFileConverter::ConvertSave(sourceSave, this, progress); - } + delete sourceFiles; + } else { + ConsoleSaveFileConverter::ConvertSave(sourceSave, this, progress); + } } -void ConsoleSaveFileSplit::_init(const std::wstring &fileName, void *pvSaveData, unsigned int fileSize, ESavePlatform plat) -{ - InitializeCriticalSectionAndSpinCount(&m_lock,5120); +void ConsoleSaveFileSplit::_init(const std::wstring& fileName, void* pvSaveData, + unsigned int fileSize, ESavePlatform plat) { + InitializeCriticalSectionAndSpinCount(&m_lock, 5120); - m_lastTickTime = 0; + m_lastTickTime = 0; - // One time initialise of static stuff required for our storage - if( pvHeap == NULL ) - { - // Reserve a chunk of 64MB of virtual address space for our saves, using 64KB pages. - // We'll only be committing these as required to grow the storage we need, which will - // the storage to grow without having to use realloc. - pvHeap = VirtualAlloc(NULL, MAX_PAGE_COUNT * CSF_PAGE_SIZE, RESERVE_ALLOCATION, PAGE_READWRITE ); - } + // One time initialise of static stuff required for our storage + if (pvHeap == NULL) { + // Reserve a chunk of 64MB of virtual address space for our saves, using + // 64KB pages. We'll only be committing these as required to grow the + // storage we need, which will the storage to grow without having to use + // realloc. + pvHeap = VirtualAlloc(NULL, MAX_PAGE_COUNT * CSF_PAGE_SIZE, + RESERVE_ALLOCATION, PAGE_READWRITE); + } - pvSaveMem = pvHeap; - m_fileName = fileName; + pvSaveMem = pvHeap; + m_fileName = fileName; - // Get details of region files. From this point on we are responsible for the memory that the storage manager initially allocated for them - unsigned int regionCount = StorageManager.GetSubfileCount(); - for( unsigned int i = 0; i < regionCount; i++ ) - { - unsigned int regionIndex; - unsigned char *regionDataCompressed; - unsigned int regionSizeCompressed; + // Get details of region files. From this point on we are responsible for + // the memory that the storage manager initially allocated for them + unsigned int regionCount = StorageManager.GetSubfileCount(); + for (unsigned int i = 0; i < regionCount; i++) { + unsigned int regionIndex; + unsigned char* regionDataCompressed; + unsigned int regionSizeCompressed; - StorageManager.GetSubfileDetails(i, (int*)®ionIndex, (void**)®ionDataCompressed, ®ionSizeCompressed); + StorageManager.GetSubfileDetails(i, (int*)®ionIndex, + (void**)®ionDataCompressed, + ®ionSizeCompressed); - RegionFileReference *regionFileRef = new RegionFileReference(i, regionIndex, regionSizeCompressed, regionDataCompressed); - if( regionSizeCompressed > 0 ) - { - regionFileRef->Decompress(); - } - else - { - regionFileRef->fileEntry->data.length = 0; - } - regionFileRef->ReleaseCompressed(); - regionFiles[regionIndex] = regionFileRef; - } + RegionFileReference* regionFileRef = new RegionFileReference( + i, regionIndex, regionSizeCompressed, regionDataCompressed); + if (regionSizeCompressed > 0) { + regionFileRef->Decompress(); + } else { + regionFileRef->fileEntry->data.length = 0; + } + regionFileRef->ReleaseCompressed(); + regionFiles[regionIndex] = regionFileRef; + } - unsigned int heapSize = std::max(fileSize, 1024u * 1024u * 2u); // 4J Stu - Our files are going to be bigger than 2MB so allocate high to start with + unsigned int heapSize = std::max( + fileSize, + 1024u * 1024u * 2u); // 4J Stu - Our files are going to be bigger than + // 2MB so allocate high to start with - // Initially committ enough room to store headSize bytes (using CSF_PAGE_SIZE pages, so rounding up here). We should only ever have one save file at a time, - // and the pages should be decommitted in the dtor, so pages committed should always be zero at this point. - if( pagesCommitted != 0 ) - { + // Initially committ enough room to store headSize bytes (using + // CSF_PAGE_SIZE pages, so rounding up here). We should only ever have one + // save file at a time, and the pages should be decommitted in the dtor, so + // pages committed should always be zero at this point. + if (pagesCommitted != 0) { #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - } + } - unsigned int pagesRequired = ( heapSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; + unsigned int pagesRequired = + (heapSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { + void* pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { #ifndef _CONTENT_PACKAGE - // Out of physical memory - __debugbreak(); + // Out of physical memory + __debugbreak(); #endif - } - pagesCommitted = pagesRequired; + } + pagesCommitted = pagesRequired; - if( fileSize > 0) - { - if(pvSaveData != NULL) - { - memcpy(pvSaveMem, pvSaveData, fileSize); - } - else - { - unsigned int storageLength; - StorageManager.GetSaveData( pvSaveMem, &storageLength ); - app.DebugPrintf("Filesize - %d, Adjusted size - %d\n",fileSize,storageLength); - fileSize = storageLength; - } + if (fileSize > 0) { + if (pvSaveData != NULL) { + memcpy(pvSaveMem, pvSaveData, fileSize); + } else { + unsigned int storageLength; + StorageManager.GetSaveData(pvSaveMem, &storageLength); + app.DebugPrintf("Filesize - %d, Adjusted size - %d\n", fileSize, + storageLength); + fileSize = storageLength; + } - int compressed = *(int*)pvSaveMem; - if( compressed == 0 ) - { - unsigned int decompSize = *( (int*)pvSaveMem+1 ); + int compressed = *(int*)pvSaveMem; + if (compressed == 0) { + unsigned int decompSize = *((int*)pvSaveMem + 1); - // An invalid save, so clear the memory and start from scratch - if(decompSize == 0) - { - // 4J Stu - Saves created between 2/12/2011 and 7/12/2011 will have this problem - app.DebugPrintf("Invalid save data format\n"); - ZeroMemory( pvSaveMem, fileSize ); - // Clear the first 8 bytes that reference the header - header.WriteHeader( pvSaveMem ); - } - else - { - unsigned char *buf = new unsigned char[decompSize]; - - if( Compression::getCompression()->Decompress(buf, &decompSize, (unsigned char *)pvSaveMem+8, fileSize-8 ) == S_OK) - { + // An invalid save, so clear the memory and start from scratch + if (decompSize == 0) { + // 4J Stu - Saves created between 2/12/2011 and 7/12/2011 will + // have this problem + app.DebugPrintf("Invalid save data format\n"); + ZeroMemory(pvSaveMem, fileSize); + // Clear the first 8 bytes that reference the header + header.WriteHeader(pvSaveMem); + } else { + unsigned char* buf = new unsigned char[decompSize]; - // Only ReAlloc if we need to (we might already have enough) and align to 512 byte boundaries - unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; + if (Compression::getCompression()->Decompress( + buf, &decompSize, (unsigned char*)pvSaveMem + 8, + fileSize - 8) == S_OK) { + // Only ReAlloc if we need to (we might already have enough) + // and align to 512 byte boundaries + unsigned int currentHeapSize = + pagesCommitted * CSF_PAGE_SIZE; - unsigned int desiredSize = decompSize; + unsigned int desiredSize = decompSize; - if( desiredSize > currentHeapSize ) - { - unsigned int pagesRequired = ( desiredSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { - // Out of physical memory - __debugbreak(); - } - pagesCommitted = pagesRequired; - } + if (desiredSize > currentHeapSize) { + unsigned int pagesRequired = + (desiredSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; + void* pvRet = + VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { + // Out of physical memory + __debugbreak(); + } + pagesCommitted = pagesRequired; + } - memcpy(pvSaveMem, buf, decompSize); - } - else - { - // Corrupt save, although most of the terrain should actually be ok - app.DebugPrintf("Failed to decompress save data!\n"); + memcpy(pvSaveMem, buf, decompSize); + } else { + // Corrupt save, although most of the terrain should + // actually be ok + app.DebugPrintf("Failed to decompress save data!\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - ZeroMemory( pvSaveMem, fileSize ); - // Clear the first 8 bytes that reference the header - header.WriteHeader( pvSaveMem ); - } + ZeroMemory(pvSaveMem, fileSize); + // Clear the first 8 bytes that reference the header + header.WriteHeader(pvSaveMem); + } - delete[] buf; - } - } + delete[] buf; + } + } - header.ReadHeader( pvSaveMem, plat ); + header.ReadHeader(pvSaveMem, plat); - } - else - { - // Clear the first 8 bytes that reference the header - header.WriteHeader( pvSaveMem ); - } + } else { + // Clear the first 8 bytes that reference the header + header.WriteHeader(pvSaveMem); + } } -ConsoleSaveFileSplit::~ConsoleSaveFileSplit() -{ - VirtualFree( pvHeap, MAX_PAGE_COUNT * CSF_PAGE_SIZE, MEM_DECOMMIT ); - pagesCommitted = 0; - // Make sure we don't have any thumbnail data still waiting round - we can't need it now we've destroyed the save file anyway -#if defined _XBOX - app.GetSaveThumbnail(NULL,NULL); +ConsoleSaveFileSplit::~ConsoleSaveFileSplit() { + VirtualFree(pvHeap, MAX_PAGE_COUNT * CSF_PAGE_SIZE, MEM_DECOMMIT); + pagesCommitted = 0; + // Make sure we don't have any thumbnail data still waiting round - we can't + // need it now we've destroyed the save file anyway +#if defined _XBOX + app.GetSaveThumbnail(NULL, NULL); #elif defined __PS3__ - app.GetSaveThumbnail(NULL,NULL, NULL,NULL); + app.GetSaveThumbnail(NULL, NULL, NULL, NULL); #endif - for(AUTO_VAR(it,regionFiles.begin()); it != regionFiles.end(); it++ ) - { - delete it->second; - } + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++) { + delete it->second; + } - StorageManager.ResetSubfiles(); - DeleteCriticalSection(&m_lock); + StorageManager.ResetSubfiles(); + DeleteCriticalSection(&m_lock); } // Add the file to our table of internal files if not already there -// Open our actual save file ready for reading/writing, and the set the file pointer to the start of this file -FileEntry *ConsoleSaveFileSplit::createFile( const ConsoleSavePath &fileName ) -{ - LockSaveAccess(); - - // Determine if the file is a region file that should be split off into its own file - unsigned int regionFileIndex; - bool isRegionFile = GetNumericIdentifierFromName(fileName.getName(), ®ionFileIndex); - if( isRegionFile ) - { - // First, for backwards compatibility, check if it is already in the main file - will just use that if so - if( !header.fileExists( fileName.getName() ) ) - { - // Find or create a new region file - FileEntry *file = GetRegionFileEntry(regionFileIndex); - ReleaseSaveAccess(); - return file; - } - } +// Open our actual save file ready for reading/writing, and the set the file +// pointer to the start of this file +FileEntry* ConsoleSaveFileSplit::createFile(const ConsoleSavePath& fileName) { + LockSaveAccess(); - FileEntry *file = header.AddFile( fileName.getName() ); - ReleaseSaveAccess(); + // Determine if the file is a region file that should be split off into its + // own file + unsigned int regionFileIndex; + bool isRegionFile = + GetNumericIdentifierFromName(fileName.getName(), ®ionFileIndex); + if (isRegionFile) { + // First, for backwards compatibility, check if it is already in the + // main file - will just use that if so + if (!header.fileExists(fileName.getName())) { + // Find or create a new region file + FileEntry* file = GetRegionFileEntry(regionFileIndex); + ReleaseSaveAccess(); + return file; + } + } - return file; + FileEntry* file = header.AddFile(fileName.getName()); + ReleaseSaveAccess(); + + return file; } -void ConsoleSaveFileSplit::deleteFile( FileEntry *file ) -{ - if( file == NULL ) return; +void ConsoleSaveFileSplit::deleteFile(FileEntry* file) { + if (file == NULL) return; - assert( file->isRegionFile() == false ); + assert(file->isRegionFile() == false); - LockSaveAccess(); + LockSaveAccess(); - unsigned int numberOfBytesRead = 0; - unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesRead = 0; + unsigned int numberOfBytesWritten = 0; - const int bufferSize = 4096; - int amountToRead = bufferSize; - std::uint8_t buffer[bufferSize]; - unsigned int bufferDataSize = 0; + const int bufferSize = 4096; + int amountToRead = bufferSize; + std::uint8_t buffer[bufferSize]; + unsigned int bufferDataSize = 0; + char* readStartOffset = + (char*)pvSaveMem + file->data.startOffset + file->getFileSize(); - char *readStartOffset = (char *)pvSaveMem + file->data.startOffset + file->getFileSize(); + char* writeStartOffset = (char*)pvSaveMem + file->data.startOffset; - char *writeStartOffset = (char *)pvSaveMem + file->data.startOffset; + char* endOfDataOffset = (char*)pvSaveMem + header.GetStartOfNextData(); - char *endOfDataOffset = (char *)pvSaveMem + header.GetStartOfNextData(); + while (true) { + // Fill buffer from file + if (readStartOffset + bufferSize > endOfDataOffset) { + amountToRead = (int)(endOfDataOffset - readStartOffset); + } else { + amountToRead = bufferSize; + } - while(true) - { - // Fill buffer from file - if( readStartOffset + bufferSize > endOfDataOffset ) - { - amountToRead = (int)(endOfDataOffset - readStartOffset); - } - else - { - amountToRead = bufferSize; - } + if (amountToRead == 0) break; - if( amountToRead == 0 ) - break; + memcpy(buffer, readStartOffset, amountToRead); + numberOfBytesRead = amountToRead; - memcpy( buffer, readStartOffset, amountToRead ); - numberOfBytesRead = amountToRead; + bufferDataSize = amountToRead; + readStartOffset += numberOfBytesRead; - bufferDataSize = amountToRead; - readStartOffset += numberOfBytesRead; + // Write buffer to file + memcpy((void*)writeStartOffset, buffer, bufferDataSize); + numberOfBytesWritten = bufferDataSize; - // Write buffer to file - memcpy( (void *)writeStartOffset, buffer, bufferDataSize ); - numberOfBytesWritten = bufferDataSize; + writeStartOffset += numberOfBytesWritten; + } - writeStartOffset += numberOfBytesWritten; - } + header.RemoveFile(file); - header.RemoveFile( file ); + finalizeWrite(); - finalizeWrite(); - - ReleaseSaveAccess(); + ReleaseSaveAccess(); } -void ConsoleSaveFileSplit::setFilePointer(FileEntry *file, unsigned int distanceToMove, SaveFileSeekOrigin seekOrigin) -{ - LockSaveAccess(); +void ConsoleSaveFileSplit::setFilePointer(FileEntry* file, + unsigned int distanceToMove, + SaveFileSeekOrigin seekOrigin) { + LockSaveAccess(); - if( seekOrigin == SaveFileSeekOrigin::Current ) - { - file->currentFilePointer += distanceToMove; - } - else - { - if( file->isRegionFile() ) - { - file->currentFilePointer = distanceToMove; - } - else - { - file->currentFilePointer = file->data.startOffset + distanceToMove; - } + if (seekOrigin == SaveFileSeekOrigin::Current) { + file->currentFilePointer += distanceToMove; + } else { + if (file->isRegionFile()) { + file->currentFilePointer = distanceToMove; + } else { + file->currentFilePointer = file->data.startOffset + distanceToMove; + } - if( seekOrigin == SaveFileSeekOrigin::End ) - { - file->currentFilePointer += file->getFileSize(); - } - } + if (seekOrigin == SaveFileSeekOrigin::End) { + file->currentFilePointer += file->getFileSize(); + } + } - ReleaseSaveAccess(); + ReleaseSaveAccess(); } // If this file needs to grow, move the data after along -void ConsoleSaveFileSplit::PrepareForWrite( FileEntry *file, unsigned int nNumberOfBytesToWrite ) -{ - int bytesToGrowBy = ( (file->currentFilePointer - file->data.startOffset) + nNumberOfBytesToWrite) - file->getFileSize(); - if( bytesToGrowBy <= 0 ) - return; +void ConsoleSaveFileSplit::PrepareForWrite(FileEntry* file, + unsigned int nNumberOfBytesToWrite) { + int bytesToGrowBy = ((file->currentFilePointer - file->data.startOffset) + + nNumberOfBytesToWrite) - + file->getFileSize(); + if (bytesToGrowBy <= 0) return; - // 4J Stu - Not forcing a minimum size, it is up to the caller to write data in sensible amounts - // This lets us keep some of the smaller files small - //if( bytesToGrowBy < 1024 ) - // bytesToGrowBy = 1024; + // 4J Stu - Not forcing a minimum size, it is up to the caller to write data + // in sensible amounts This lets us keep some of the smaller files small + // if( bytesToGrowBy < 1024 ) + // bytesToGrowBy = 1024; - // Move all the data beyond us - PIXBeginNamedEvent(0,"Growing file by %d bytes", bytesToGrowBy); - MoveDataBeyond(file, bytesToGrowBy); - PIXEndNamedEvent(); + // Move all the data beyond us + PIXBeginNamedEvent(0, "Growing file by %d bytes", bytesToGrowBy); + MoveDataBeyond(file, bytesToGrowBy); + PIXEndNamedEvent(); - // Update our length - if( file->data.length < 0 ) - file->data.length = 0; - file->data.length += bytesToGrowBy; + // Update our length + if (file->data.length < 0) file->data.length = 0; + file->data.length += bytesToGrowBy; - // Write the header with the updated data - finalizeWrite(); + // Write the header with the updated data + finalizeWrite(); } -bool ConsoleSaveFileSplit::writeFile(FileEntry *file,const void *lpBuffer, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) -{ - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileSplit::writeFile(FileEntry* file, const void* lpBuffer, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) { + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - LockSaveAccess(); + LockSaveAccess(); - if( file->isRegionFile() ) - { - unsigned int sizeRequired = file->currentFilePointer + nNumberOfBytesToWrite; - RegionFileReference *fileRef = regionFiles[file->data.regionIndex]; - if( sizeRequired > file->getFileSize() ) - { - fileRef->data = (unsigned char *)realloc(fileRef->data, sizeRequired); - file->data.length = sizeRequired; - } + if (file->isRegionFile()) { + unsigned int sizeRequired = + file->currentFilePointer + nNumberOfBytesToWrite; + RegionFileReference* fileRef = regionFiles[file->data.regionIndex]; + if (sizeRequired > file->getFileSize()) { + fileRef->data = + (unsigned char*)realloc(fileRef->data, sizeRequired); + file->data.length = sizeRequired; + } - memcpy( fileRef->data + file->currentFilePointer, lpBuffer, nNumberOfBytesToWrite ); + memcpy(fileRef->data + file->currentFilePointer, lpBuffer, + nNumberOfBytesToWrite); -// app.DebugPrintf(">>>>>>>>>>>>>> writing a region file's data 0x%.8x, 0x%x offset %d of %d bytes (writing %d bytes)\n",file->data.regionIndex,fileRef->data,file->currentFilePointer, file->getFileSize(), nNumberOfBytesToWrite); + // app.DebugPrintf(">>>>>>>>>>>>>> writing a region file's + //data 0x%.8x, 0x%x offset %d of %d bytes (writing %d + //bytes)\n",file->data.regionIndex,fileRef->data,file->currentFilePointer, + //file->getFileSize(), nNumberOfBytesToWrite); - file->currentFilePointer += nNumberOfBytesToWrite; - file->updateLastModifiedTime(); - fileRef->dirty = true; - } - else - { - PrepareForWrite( file, nNumberOfBytesToWrite ); + file->currentFilePointer += nNumberOfBytesToWrite; + file->updateLastModifiedTime(); + fileRef->dirty = true; + } else { + PrepareForWrite(file, nNumberOfBytesToWrite); - char *writeStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, writeStartOffset); + char* writeStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, + // writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, + // writeStartOffset); - memcpy( (void *)writeStartOffset, lpBuffer, nNumberOfBytesToWrite ); - *lpNumberOfBytesWritten = nNumberOfBytesToWrite; + memcpy((void*)writeStartOffset, lpBuffer, nNumberOfBytesToWrite); + *lpNumberOfBytesWritten = nNumberOfBytesToWrite; - if(file->data.length < 0) - file->data.length = 0; + if (file->data.length < 0) file->data.length = 0; - file->currentFilePointer += *lpNumberOfBytesWritten; + file->currentFilePointer += *lpNumberOfBytesWritten; - //wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); + // wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", + // *lpNumberOfBytesWritten, file->data.filename, + // file->currentFilePointer); - file->updateLastModifiedTime(); - } + file->updateLastModifiedTime(); + } - ReleaseSaveAccess(); + ReleaseSaveAccess(); - return true; + return true; } -bool ConsoleSaveFileSplit::zeroFile(FileEntry *file, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten) -{ - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileSplit::zeroFile(FileEntry* file, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten) { + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - // 4jcraft added: memset(NULL + 0, 0, 0); was called - // no bytes need to be written, hence there you go - if(nNumberOfBytesToWrite == 0) { - if(lpNumberOfBytesWritten) { - *lpNumberOfBytesWritten = 0; - } - return 1; - } + // 4jcraft added: memset(NULL + 0, 0, 0); was called + // no bytes need to be written, hence there you go + if (nNumberOfBytesToWrite == 0) { + if (lpNumberOfBytesWritten) { + *lpNumberOfBytesWritten = 0; + } + return 1; + } - LockSaveAccess(); + LockSaveAccess(); - if( file->isRegionFile() ) - { - unsigned int sizeRequired = file->currentFilePointer + nNumberOfBytesToWrite; - RegionFileReference *fileRef = regionFiles[file->data.regionIndex]; - if( sizeRequired > file->getFileSize() ) - { - fileRef->data = (unsigned char *)realloc(fileRef->data, sizeRequired); - file->data.length = sizeRequired; - } + if (file->isRegionFile()) { + unsigned int sizeRequired = + file->currentFilePointer + nNumberOfBytesToWrite; + RegionFileReference* fileRef = regionFiles[file->data.regionIndex]; + if (sizeRequired > file->getFileSize()) { + fileRef->data = + (unsigned char*)realloc(fileRef->data, sizeRequired); + file->data.length = sizeRequired; + } - memset( fileRef->data + file->currentFilePointer, 0, nNumberOfBytesToWrite ); + memset(fileRef->data + file->currentFilePointer, 0, + nNumberOfBytesToWrite); -// app.DebugPrintf(">>>>>>>>>>>>>> writing a region file's data 0x%.8x, 0x%x offset %d of %d bytes (writing %d bytes)\n",file->data.regionIndex,fileRef->data,file->currentFilePointer, file->getFileSize(), nNumberOfBytesToWrite); + // app.DebugPrintf(">>>>>>>>>>>>>> writing a region file's + //data 0x%.8x, 0x%x offset %d of %d bytes (writing %d + //bytes)\n",file->data.regionIndex,fileRef->data,file->currentFilePointer, + //file->getFileSize(), nNumberOfBytesToWrite); - file->currentFilePointer += nNumberOfBytesToWrite; - file->updateLastModifiedTime(); - fileRef->dirty = true; - } - else - { - PrepareForWrite( file, nNumberOfBytesToWrite ); + file->currentFilePointer += nNumberOfBytesToWrite; + file->updateLastModifiedTime(); + fileRef->dirty = true; + } else { + PrepareForWrite(file, nNumberOfBytesToWrite); - char *writeStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, writeStartOffset); + char* writeStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Write: pvSaveMem = %0xd, currentFilePointer = %d, + // writeStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, + // writeStartOffset); - memset( (void *)writeStartOffset, 0, nNumberOfBytesToWrite ); - *lpNumberOfBytesWritten = nNumberOfBytesToWrite; + memset((void*)writeStartOffset, 0, nNumberOfBytesToWrite); + *lpNumberOfBytesWritten = nNumberOfBytesToWrite; - if(file->data.length < 0) - file->data.length = 0; + if (file->data.length < 0) file->data.length = 0; - file->currentFilePointer += *lpNumberOfBytesWritten; + file->currentFilePointer += *lpNumberOfBytesWritten; - //wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", *lpNumberOfBytesWritten, file->data.filename, file->currentFilePointer); + // wprintf(L"Wrote %d bytes to %s, new file pointer is %I64d\n", + // *lpNumberOfBytesWritten, file->data.filename, + // file->currentFilePointer); - file->updateLastModifiedTime(); - } + file->updateLastModifiedTime(); + } - ReleaseSaveAccess(); + ReleaseSaveAccess(); - return true; + return true; } -bool ConsoleSaveFileSplit::readFile( FileEntry *file, void *lpBuffer, unsigned int nNumberOfBytesToRead, unsigned int *lpNumberOfBytesRead) -{ - unsigned int actualBytesToRead; - assert( pvSaveMem != NULL ); - if( pvSaveMem == NULL ) - { - return false; - } +bool ConsoleSaveFileSplit::readFile(FileEntry* file, void* lpBuffer, + unsigned int nNumberOfBytesToRead, + unsigned int* lpNumberOfBytesRead) { + unsigned int actualBytesToRead; + assert(pvSaveMem != NULL); + if (pvSaveMem == NULL) { + return false; + } - LockSaveAccess(); + LockSaveAccess(); - if( file->isRegionFile() ) - { - actualBytesToRead = nNumberOfBytesToRead; - if( file->currentFilePointer + nNumberOfBytesToRead > file->data.length ) - { - actualBytesToRead = file->data.length - file->currentFilePointer; - } - RegionFileReference *fileRef = regionFiles[file->data.regionIndex]; - memcpy( lpBuffer, fileRef->data + file->currentFilePointer, actualBytesToRead ); - *lpNumberOfBytesRead = actualBytesToRead; + if (file->isRegionFile()) { + actualBytesToRead = nNumberOfBytesToRead; + if (file->currentFilePointer + nNumberOfBytesToRead > + file->data.length) { + actualBytesToRead = file->data.length - file->currentFilePointer; + } + RegionFileReference* fileRef = regionFiles[file->data.regionIndex]; + memcpy(lpBuffer, fileRef->data + file->currentFilePointer, + actualBytesToRead); + *lpNumberOfBytesRead = actualBytesToRead; - file->currentFilePointer += actualBytesToRead; - } - else - { - char *readStartOffset = (char *)pvSaveMem + file->currentFilePointer; - //printf("Read: pvSaveMem = %0xd, currentFilePointer = %d, readStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, readStartOffset); + file->currentFilePointer += actualBytesToRead; + } else { + char* readStartOffset = (char*)pvSaveMem + file->currentFilePointer; + // printf("Read: pvSaveMem = %0xd, currentFilePointer = %d, + // readStartOffset = %0xd\n", pvSaveMem, file->currentFilePointer, + // readStartOffset); - assert( nNumberOfBytesToRead <= file->getFileSize() ); + assert(nNumberOfBytesToRead <= file->getFileSize()); - actualBytesToRead = nNumberOfBytesToRead; - if( file->currentFilePointer + nNumberOfBytesToRead > file->data.startOffset + file->data.length ) - { - actualBytesToRead = (file->data.startOffset + file->data.length) - file->currentFilePointer; - } + actualBytesToRead = nNumberOfBytesToRead; + if (file->currentFilePointer + nNumberOfBytesToRead > + file->data.startOffset + file->data.length) { + actualBytesToRead = (file->data.startOffset + file->data.length) - + file->currentFilePointer; + } - memcpy( lpBuffer, readStartOffset, actualBytesToRead ); - *lpNumberOfBytesRead = actualBytesToRead; + memcpy(lpBuffer, readStartOffset, actualBytesToRead); + *lpNumberOfBytesRead = actualBytesToRead; - file->currentFilePointer += *lpNumberOfBytesRead; + file->currentFilePointer += *lpNumberOfBytesRead; - //wprintf(L"Read %d bytes from %s, new file pointer is %I64d\n", *lpNumberOfBytesRead, file->data.filename, file->currentFilePointer); - } + // wprintf(L"Read %d bytes from %s, new file pointer is %I64d\n", + // *lpNumberOfBytesRead, file->data.filename, file->currentFilePointer); + } + ReleaseSaveAccess(); - - ReleaseSaveAccess(); - - return true; + return true; } -bool ConsoleSaveFileSplit::closeHandle( FileEntry *file ) -{ - LockSaveAccess(); - finalizeWrite(); - ReleaseSaveAccess(); +bool ConsoleSaveFileSplit::closeHandle(FileEntry* file) { + LockSaveAccess(); + finalizeWrite(); + ReleaseSaveAccess(); - return true; + return true; } -// In this method, attempt to write any dirty region files, subject to maintaining a maximum write output rate. Writing is prioritised by time since the region was last written. -void ConsoleSaveFileSplit::tick() -{ - std::int64_t currentTime = System::currentTimeMillis(); +// In this method, attempt to write any dirty region files, subject to +// maintaining a maximum write output rate. Writing is prioritised by time since +// the region was last written. +void ConsoleSaveFileSplit::tick() { + std::int64_t currentTime = System::currentTimeMillis(); - // Don't do anything if the save system is up to something... - if( StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) - { - return; - } + // Don't do anything if the save system is up to something... + if (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) { + return; + } - // ...or we shouldn't be saving... - if( StorageManager.GetSaveDisabled() ) - { - return; - } + // ...or we shouldn't be saving... + if (StorageManager.GetSaveDisabled()) { + return; + } - // ... or we haven't passed the required time since last assessing what to do - if( ( currentTime - m_lastTickTime ) < WRITE_TICK_RATE_MS ) - { - return; - } + // ... or we haven't passed the required time since last assessing what to + // do + if ((currentTime - m_lastTickTime) < WRITE_TICK_RATE_MS) { + return; + } - LockSaveAccess(); + LockSaveAccess(); - m_lastTickTime = currentTime; + m_lastTickTime = currentTime; - // Get total amount of data written over the time period we are interested in averaging over. Remove any older data. - unsigned int bytesWritten = 0; - for( AUTO_VAR(it, writeHistory.begin()); it != writeHistory.end(); ) - { - if( ( currentTime - it->writeTime ) > ( WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS * 1000 ) ) - { - it = writeHistory.erase(it); - } - else - { - bytesWritten += it->writeSize; - it++; - } - } + // Get total amount of data written over the time period we are interested + // in averaging over. Remove any older data. + unsigned int bytesWritten = 0; + for (AUTO_VAR(it, writeHistory.begin()); it != writeHistory.end();) { + if ((currentTime - it->writeTime) > + (WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS * 1000)) { + it = writeHistory.erase(it); + } else { + bytesWritten += it->writeSize; + it++; + } + } - // Compile a vector of dirty regions. - std::vector dirtyRegions; - for( AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++ ) - { - DirtyRegionFile dirtyRegion; + // Compile a vector of dirty regions. + std::vector dirtyRegions; + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++) { + DirtyRegionFile dirtyRegion; - if( it->second->dirty ) - { - dirtyRegion.fileRef = it->second->fileEntry->getRegionFileIndex(); - dirtyRegion.lastWritten = it->second->lastWritten; - dirtyRegions.push_back( dirtyRegion ); - } - } + if (it->second->dirty) { + dirtyRegion.fileRef = it->second->fileEntry->getRegionFileIndex(); + dirtyRegion.lastWritten = it->second->lastWritten; + dirtyRegions.push_back(dirtyRegion); + } + } - // Sort into ascending order, by lastWritten time. First elements will therefore be the ones least recently saved - std::sort( dirtyRegions.begin(), dirtyRegions.end() ); + // Sort into ascending order, by lastWritten time. First elements will + // therefore be the ones least recently saved + std::sort(dirtyRegions.begin(), dirtyRegions.end()); - bool writeRequired = false; - unsigned int bytesInTimePeriod = bytesWritten; - unsigned int bytesAddedThisTick = 0; - for( int i = 0; i < dirtyRegions.size(); i++ ) - { - RegionFileReference *regionRef = regionFiles[dirtyRegions[i].fileRef]; - unsigned int compressedSize = regionRef->GetCompressedSize(); - bytesInTimePeriod += compressedSize; - bytesAddedThisTick += compressedSize; + bool writeRequired = false; + unsigned int bytesInTimePeriod = bytesWritten; + unsigned int bytesAddedThisTick = 0; + for (int i = 0; i < dirtyRegions.size(); i++) { + RegionFileReference* regionRef = regionFiles[dirtyRegions[i].fileRef]; + unsigned int compressedSize = regionRef->GetCompressedSize(); + bytesInTimePeriod += compressedSize; + bytesAddedThisTick += compressedSize; - // Always consider at least one item for writing, even if it breaks the rule on the maximum number of bytes we would like to send per tick - if( ( i > 0 ) && ( bytesAddedThisTick > WRITE_MAX_WRITE_PER_TICK ) ) - { - break; - } + // Always consider at least one item for writing, even if it breaks the + // rule on the maximum number of bytes we would like to send per tick + if ((i > 0) && (bytesAddedThisTick > WRITE_MAX_WRITE_PER_TICK)) { + break; + } - // Could we add this without breaking our bytes per second cap? - if ( ( bytesInTimePeriod / WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS ) > WRITE_BANDWIDTH_BYTESPERSECOND ) - { - break; - } + // Could we add this without breaking our bytes per second cap? + if ((bytesInTimePeriod / WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS) > + WRITE_BANDWIDTH_BYTESPERSECOND) { + break; + } - // Can add for writing - WriteHistory writeEvent; - writeEvent.writeSize = compressedSize; - writeEvent.writeTime = System::currentTimeMillis(); - writeHistory.push_back(writeEvent); + // Can add for writing + WriteHistory writeEvent; + writeEvent.writeSize = compressedSize; + writeEvent.writeTime = System::currentTimeMillis(); + writeHistory.push_back(writeEvent); - regionRef->Compress(); -// app.DebugPrintf("Tick: Writing region 0x%.8x, compressed as %d bytes\n",regionRef->fileEntry->getRegionFileIndex(), regionRef->dataCompressedSize); - StorageManager.UpdateSubfile(regionRef->index, regionRef->dataCompressed, regionRef->dataCompressedSize); - regionRef->dirty = false; - regionRef->lastWritten = System::currentTimeMillis(); + regionRef->Compress(); + // app.DebugPrintf("Tick: Writing region 0x%.8x, compressed + //as %d bytes\n",regionRef->fileEntry->getRegionFileIndex(), + //regionRef->dataCompressedSize); + StorageManager.UpdateSubfile(regionRef->index, + regionRef->dataCompressed, + regionRef->dataCompressedSize); + regionRef->dirty = false; + regionRef->lastWritten = System::currentTimeMillis(); - writeRequired = true; - } + writeRequired = true; + } #ifndef _CONTENT_PACKAGE - { - unsigned int totalDirty = 0; - unsigned int totalDirtyBytes = 0; - __int64 oldestDirty = currentTime; - for( AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++ ) - { - if( it->second->dirty ) - { - if( it->second->lastWritten < oldestDirty ) - { - oldestDirty = it->second->lastWritten; - } - totalDirty++; - totalDirtyBytes += it->second->fileEntry->getFileSize(); - } - } + { + unsigned int totalDirty = 0; + unsigned int totalDirtyBytes = 0; + __int64 oldestDirty = currentTime; + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++) { + if (it->second->dirty) { + if (it->second->lastWritten < oldestDirty) { + oldestDirty = it->second->lastWritten; + } + totalDirty++; + totalDirtyBytes += it->second->fileEntry->getFileSize(); + } + } #ifdef _DURANGO - PIXReportCounter(L"Dirty regions", (float)totalDirty); - PIXReportCounter(L"Dirty MB", (float)totalDirtyBytes / ( 1024 * 1024) ); - PIXReportCounter(L"Dirty oldest age", ((float) currentTime - oldestDirty ) ); - PIXReportCounter(L"Region writing bandwidth",((float)bytesInTimePeriod/ WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS) / ( 1024 * 1024)); + PIXReportCounter(L"Dirty regions", (float)totalDirty); + PIXReportCounter(L"Dirty MB", (float)totalDirtyBytes / (1024 * 1024)); + PIXReportCounter(L"Dirty oldest age", + ((float)currentTime - oldestDirty)); + PIXReportCounter(L"Region writing bandwidth", + ((float)bytesInTimePeriod / + WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS) / + (1024 * 1024)); #endif - } + } #endif - if( writeRequired ) - { - StorageManager.SaveSubfiles(SaveRegionFilesCallback, this); - } + if (writeRequired) { + StorageManager.SaveSubfiles(SaveRegionFilesCallback, this); + } - ReleaseSaveAccess(); + ReleaseSaveAccess(); } -void ConsoleSaveFileSplit::finalizeWrite() -{ - LockSaveAccess(); - header.WriteHeader( pvSaveMem ); - ReleaseSaveAccess(); +void ConsoleSaveFileSplit::finalizeWrite() { + LockSaveAccess(); + header.WriteHeader(pvSaveMem); + ReleaseSaveAccess(); } -void ConsoleSaveFileSplit::MoveDataBeyond(FileEntry *file, unsigned int nNumberOfBytesToWrite) -{ - unsigned int numberOfBytesRead = 0; - unsigned int numberOfBytesWritten = 0; +void ConsoleSaveFileSplit::MoveDataBeyond(FileEntry* file, + unsigned int nNumberOfBytesToWrite) { + unsigned int numberOfBytesRead = 0; + unsigned int numberOfBytesWritten = 0; - const unsigned int bufferSize = 4096; - unsigned int amountToRead = bufferSize; - //assert( nNumberOfBytesToWrite <= bufferSize ); - static std::uint8_t buffer1[bufferSize]; - static std::uint8_t buffer2[bufferSize]; - unsigned int buffer1Size = 0; - unsigned int buffer2Size = 0; + const unsigned int bufferSize = 4096; + unsigned int amountToRead = bufferSize; + // assert( nNumberOfBytesToWrite <= bufferSize ); + static std::uint8_t buffer1[bufferSize]; + static std::uint8_t buffer2[bufferSize]; + unsigned int buffer1Size = 0; + unsigned int buffer2Size = 0; - // Only ReAlloc if we need to (we might already have enough) and align to 512 byte boundaries - unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; - - unsigned int desiredSize = header.GetFileSize() + nNumberOfBytesToWrite; + // Only ReAlloc if we need to (we might already have enough) and align to + // 512 byte boundaries + unsigned int currentHeapSize = pagesCommitted * CSF_PAGE_SIZE; - if( desiredSize > currentHeapSize ) - { - unsigned int pagesRequired = ( desiredSize + (CSF_PAGE_SIZE - 1 ) ) / CSF_PAGE_SIZE; - void *pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, COMMIT_ALLOCATION, PAGE_READWRITE); - if( pvRet == NULL ) - { - // Out of physical memory - __debugbreak(); - } - pagesCommitted = pagesRequired; - } + unsigned int desiredSize = header.GetFileSize() + nNumberOfBytesToWrite; - // This is the start of where we want the space to be, and the start of the data that we need to move - char *spaceStartOffset = (char *)pvSaveMem + file->data.startOffset + file->getFileSize(); + if (desiredSize > currentHeapSize) { + unsigned int pagesRequired = + (desiredSize + (CSF_PAGE_SIZE - 1)) / CSF_PAGE_SIZE; + void* pvRet = VirtualAlloc(pvHeap, pagesRequired * CSF_PAGE_SIZE, + COMMIT_ALLOCATION, PAGE_READWRITE); + if (pvRet == NULL) { + // Out of physical memory + __debugbreak(); + } + pagesCommitted = pagesRequired; + } - // This is the end of where we want the space to be - char *spaceEndOffset = spaceStartOffset + nNumberOfBytesToWrite; + // This is the start of where we want the space to be, and the start of the + // data that we need to move + char* spaceStartOffset = + (char*)pvSaveMem + file->data.startOffset + file->getFileSize(); - // This is the current end of the data that we want to move - char *beginEndOfDataOffset = (char *)pvSaveMem + header.GetStartOfNextData(); + // This is the end of where we want the space to be + char* spaceEndOffset = spaceStartOffset + nNumberOfBytesToWrite; - // This is where the end of the data is going to be - char *finishEndOfDataOffset = beginEndOfDataOffset + nNumberOfBytesToWrite; + // This is the current end of the data that we want to move + char* beginEndOfDataOffset = (char*)pvSaveMem + header.GetStartOfNextData(); - // This is where we are going to read from (with the amount we want to read subtracted before we read) - char *readStartOffset = beginEndOfDataOffset; + // This is where the end of the data is going to be + char* finishEndOfDataOffset = beginEndOfDataOffset + nNumberOfBytesToWrite; - // This is where we can safely write to (with the amount we want write subtracted before we write) - char *writeStartOffset = finishEndOfDataOffset; + // This is where we are going to read from (with the amount we want to read + // subtracted before we read) + char* readStartOffset = beginEndOfDataOffset; - //printf("\n******* MOVEDATABEYOND *******\n"); - //printf("Space start: %d, space end: %d\n", spaceStartOffset - (char *)pvSaveMem, spaceEndOffset - (char *)pvSaveMem); - //printf("Current end of data: %d, new end of data: %d\n", beginEndOfDataOffset - (char *)pvSaveMem, finishEndOfDataOffset - (char *)pvSaveMem); + // This is where we can safely write to (with the amount we want write + // subtracted before we write) + char* writeStartOffset = finishEndOfDataOffset; - // Optimisation for things that are being moved in whole region file sector (4K chunks). We could generalise this a bit more but seems safest at the moment to identify this particular type - // of move and code explicitly for this situation - if( ( nNumberOfBytesToWrite & 4095 ) == 0 ) - { - if( nNumberOfBytesToWrite > 0 ) - { - // Get addresses for start & end of the region we are copying from as uintptr_t, for easier maths - uintptr_t uiFromStart = (uintptr_t)spaceStartOffset; - uintptr_t uiFromEnd = (uintptr_t)beginEndOfDataOffset; + // printf("\n******* MOVEDATABEYOND *******\n"); + // printf("Space start: %d, space end: %d\n", spaceStartOffset - (char + // *)pvSaveMem, spaceEndOffset - (char *)pvSaveMem); printf("Current end of + // data: %d, new end of data: %d\n", beginEndOfDataOffset - (char + // *)pvSaveMem, finishEndOfDataOffset - (char *)pvSaveMem); - // Round both of these values to get 4096 byte chunks that we will need to at least partially move - uintptr_t uiFromStartChunk = uiFromStart & ~((uintptr_t)4095); - uintptr_t uiFromEndChunk = (uiFromEnd - 1 ) & ~((uintptr_t)4095); + // Optimisation for things that are being moved in whole region file sector + // (4K chunks). We could generalise this a bit more but seems safest at the + // moment to identify this particular type of move and code explicitly for + // this situation + if ((nNumberOfBytesToWrite & 4095) == 0) { + if (nNumberOfBytesToWrite > 0) { + // Get addresses for start & end of the region we are copying from + // as uintptr_t, for easier maths + uintptr_t uiFromStart = (uintptr_t)spaceStartOffset; + uintptr_t uiFromEnd = (uintptr_t)beginEndOfDataOffset; - // Loop through all the affected source 4096 chunks, going backwards so we don't overwrite anything we'll need in the future - for( uintptr_t uiCurrentChunk = uiFromEndChunk; uiCurrentChunk >= uiFromStartChunk; uiCurrentChunk -= 4096 ) - { - // Establish chunk we'll need to copy - uintptr_t uiCopyStart = uiCurrentChunk; - uintptr_t uiCopyEnd = uiCurrentChunk + 4096; - // Clamp chunk to the bounds of the full region we are trying to copy - if( uiCopyStart < uiFromStart ) - { - // Needs to be clampged against the start of our region - uiCopyStart = uiFromStart; - } - if ( uiCopyEnd > uiFromEnd ) - { - // Needs to be clamped to the end of our region - uiCopyEnd = uiFromEnd; - } - XMemCpy( (void *)(uiCopyStart + nNumberOfBytesToWrite), ( void *)uiCopyStart, uiCopyEnd - uiCopyStart ); - } - } - } - else - { - while(true) - { - // Copy buffer 1 to buffer 2 - memcpy( buffer2, buffer1, buffer1Size); - buffer2Size = buffer1Size; + // Round both of these values to get 4096 byte chunks that we will + // need to at least partially move + uintptr_t uiFromStartChunk = uiFromStart & ~((uintptr_t)4095); + uintptr_t uiFromEndChunk = (uiFromEnd - 1) & ~((uintptr_t)4095); - // Fill buffer 1 from file - if( (readStartOffset - bufferSize) < spaceStartOffset ) - { - amountToRead = static_cast(readStartOffset - spaceStartOffset); - } - else - { - amountToRead = bufferSize; - } + // Loop through all the affected source 4096 chunks, going backwards + // so we don't overwrite anything we'll need in the future + for (uintptr_t uiCurrentChunk = uiFromEndChunk; + uiCurrentChunk >= uiFromStartChunk; uiCurrentChunk -= 4096) { + // Establish chunk we'll need to copy + uintptr_t uiCopyStart = uiCurrentChunk; + uintptr_t uiCopyEnd = uiCurrentChunk + 4096; + // Clamp chunk to the bounds of the full region we are trying to + // copy + if (uiCopyStart < uiFromStart) { + // Needs to be clampged against the start of our region + uiCopyStart = uiFromStart; + } + if (uiCopyEnd > uiFromEnd) { + // Needs to be clamped to the end of our region + uiCopyEnd = uiFromEnd; + } + XMemCpy((void*)(uiCopyStart + nNumberOfBytesToWrite), + (void*)uiCopyStart, uiCopyEnd - uiCopyStart); + } + } + } else { + while (true) { + // Copy buffer 1 to buffer 2 + memcpy(buffer2, buffer1, buffer1Size); + buffer2Size = buffer1Size; - // Push the read point back by the amount of bytes that we are going to read - readStartOffset -= amountToRead; + // Fill buffer 1 from file + if ((readStartOffset - bufferSize) < spaceStartOffset) { + amountToRead = static_cast(readStartOffset - + spaceStartOffset); + } else { + amountToRead = bufferSize; + } - //printf("About to read %u from %d\n", amountToRead, readStartOffset - (char *)pvSaveMem ); + // Push the read point back by the amount of bytes that we are going + // to read + readStartOffset -= amountToRead; - memcpy( buffer1, readStartOffset, amountToRead ); - numberOfBytesRead = amountToRead; + // printf("About to read %u from %d\n", amountToRead, + // readStartOffset - (char *)pvSaveMem ); - buffer1Size = amountToRead; + memcpy(buffer1, readStartOffset, amountToRead); + numberOfBytesRead = amountToRead; - // Move back the write pointer by the amount of bytes we are going to write - writeStartOffset -= buffer2Size; + buffer1Size = amountToRead; - // Write buffer 2 to file - if( (writeStartOffset + buffer2Size) <= finishEndOfDataOffset) - { - //printf("About to write %u to %d\n", buffer2Size, writeStartOffset - (char *)pvSaveMem ); - memcpy( (void *)writeStartOffset, buffer2, buffer2Size ); - numberOfBytesWritten = buffer2Size; - } - else - { - assert((writeStartOffset + buffer2Size) <= finishEndOfDataOffset); - numberOfBytesWritten = 0; - } + // Move back the write pointer by the amount of bytes we are going + // to write + writeStartOffset -= buffer2Size; - if( numberOfBytesRead == 0 ) - { - //printf("\n************** MOVE COMPLETED *************** \n\n"); - assert( writeStartOffset == spaceEndOffset ); - break; - } - } - } + // Write buffer 2 to file + if ((writeStartOffset + buffer2Size) <= finishEndOfDataOffset) { + // printf("About to write %u to %d\n", buffer2Size, + // writeStartOffset - (char *)pvSaveMem ); + memcpy((void*)writeStartOffset, buffer2, buffer2Size); + numberOfBytesWritten = buffer2Size; + } else { + assert((writeStartOffset + buffer2Size) <= + finishEndOfDataOffset); + numberOfBytesWritten = 0; + } - header.AdjustStartOffsets( file, nNumberOfBytesToWrite ); + if (numberOfBytesRead == 0) { + // printf("\n************** MOVE COMPLETED *************** + // \n\n"); + assert(writeStartOffset == spaceEndOffset); + break; + } + } + } + + header.AdjustStartOffsets(file, nNumberOfBytesToWrite); } -// Attempt to convert a filename into a numeric identifier, which we use for region files. File names supported are of the form: +// Attempt to convert a filename into a numeric identifier, which we use for +// region files. File names supported are of the form: // // Filename Encoded as // @@ -1204,77 +1161,76 @@ void ConsoleSaveFileSplit::MoveDataBeyond(FileEntry *file, unsigned int nNumberO // DIM-1r.x.z.mcr 00 01 xx zz // DIM1/r.x.z.mcr 00 02 xx zz -bool ConsoleSaveFileSplit::GetNumericIdentifierFromName(const std::wstring &fileName, unsigned int *idOut) -{ - // Determine whether it is one of our region file names if the file extension is ".mbr" - if( fileName.length() < 4 ) return false; - std::wstring extension = fileName.substr(fileName.length()-4,4); - if( extension != std::wstring(L".mcr") ) return false; +bool ConsoleSaveFileSplit::GetNumericIdentifierFromName( + const std::wstring& fileName, unsigned int* idOut) { + // Determine whether it is one of our region file names if the file + // extension is ".mbr" + if (fileName.length() < 4) return false; + std::wstring extension = fileName.substr(fileName.length() - 4, 4); + if (extension != std::wstring(L".mcr")) return false; - unsigned int id = 0; - int x, z; + unsigned int id = 0; + int x, z; - const wchar_t *cstr = fileName.c_str(); - const wchar_t *body = cstr + 2; + const wchar_t* cstr = fileName.c_str(); + const wchar_t* body = cstr + 2; - // If this filename starts with a "r" then assume it is of the format "r.x.z.mcr" - don't do anything as default value we've set are correct - if( cstr[0] != L'r' ) - { - // Must be prefixed by "DIM-1r." or "DIM1/r." - body = cstr + 7; - // Differentiate between these 2 options - if( cstr[3] == L'-' ) - { - // "DIM-1r." - id = 0x00010000; - } - else - { - // "DIM/1r." - id = 0x00020000; - } - } - // Get x/z coords - swscanf_s(body, L"%d.%d.mcr", &x, &z ); + // If this filename starts with a "r" then assume it is of the format + // "r.x.z.mcr" - don't do anything as default value we've set are correct + if (cstr[0] != L'r') { + // Must be prefixed by "DIM-1r." or "DIM1/r." + body = cstr + 7; + // Differentiate between these 2 options + if (cstr[3] == L'-') { + // "DIM-1r." + id = 0x00010000; + } else { + // "DIM/1r." + id = 0x00020000; + } + } + // Get x/z coords + swscanf_s(body, L"%d.%d.mcr", &x, &z); - // Pack full id - // 4jcraft added cast to unsigned - id |= ( ( (unsigned int) x << 8 ) & 0x0000ff00 ); - id |= ( z & 0x000000ff ); + // Pack full id + // 4jcraft added cast to unsigned + id |= (((unsigned int)x << 8) & 0x0000ff00); + id |= (z & 0x000000ff); - *idOut = id; + *idOut = id; - return true; + return true; } -// Convert a numeric file identifier (for region files) back into a normal filename. See comment above. +// Convert a numeric file identifier (for region files) back into a normal +// filename. See comment above. -std::wstring ConsoleSaveFileSplit::GetNameFromNumericIdentifier(unsigned int idIn) -{ - std::wstring prefix; +std::wstring ConsoleSaveFileSplit::GetNameFromNumericIdentifier( + unsigned int idIn) { + std::wstring prefix; - switch(idIn & 0x00ff0000 ) - { - case 0: - prefix = L""; - break; - case 1: - prefix = L"DIM-1"; - break; - case 2: - prefix = L"DIM1/"; - break; - } - signed char regionX = ( idIn >> 8 ) & 255; - signed char regionZ = idIn & 255; - std::wstring region = ( prefix + std::wstring(L"r.") + _toString(regionX) + L"." + _toString(regionZ) + L".mcr" ); + switch (idIn & 0x00ff0000) { + case 0: + prefix = L""; + break; + case 1: + prefix = L"DIM-1"; + break; + case 2: + prefix = L"DIM1/"; + break; + } + signed char regionX = (idIn >> 8) & 255; + signed char regionZ = idIn & 255; + std::wstring region = (prefix + std::wstring(L"r.") + _toString(regionX) + + L"." + _toString(regionZ) + L".mcr"); - return region; + return region; } -// Compress any dirty region files, and tell the storage manager about them so that it will process them when we ask it to save sub files -void ConsoleSaveFileSplit::processSubfilesForWrite() -{ +// Compress any dirty region files, and tell the storage manager about them so +// that it will process them when we ask it to save sub files +void ConsoleSaveFileSplit::processSubfilesForWrite() { #if 0 // 4J Stu - There are debug reasons where we want to force a save of all regions StorageManager.ResetSubfiles(); @@ -1291,434 +1247,415 @@ void ConsoleSaveFileSplit::processSubfilesForWrite() } } #else - for(AUTO_VAR(it,regionFiles.begin()); it != regionFiles.end(); it++ ) - { - RegionFileReference* region = it->second; - if( region->dirty ) - { - region->Compress(); - StorageManager.UpdateSubfile(region->index, region->dataCompressed, region->dataCompressedSize); - region->dirty = false; - region->lastWritten = System::currentTimeMillis(); - } - } + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++) { + RegionFileReference* region = it->second; + if (region->dirty) { + region->Compress(); + StorageManager.UpdateSubfile(region->index, region->dataCompressed, + region->dataCompressedSize); + region->dirty = false; + region->lastWritten = System::currentTimeMillis(); + } + } #endif } -// Clean up any memory allocated for compressed data when we have finished writing -void ConsoleSaveFileSplit::processSubfilesAfterWrite() -{ - // This is called from the StorageManager.Tick() which should always be on the main thread - for(AUTO_VAR(it,regionFiles.begin()); it != regionFiles.end(); it++ ) - { - RegionFileReference* region = it->second; - region->ReleaseCompressed(); - } +// Clean up any memory allocated for compressed data when we have finished +// writing +void ConsoleSaveFileSplit::processSubfilesAfterWrite() { + // This is called from the StorageManager.Tick() which should always be on + // the main thread + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); it++) { + RegionFileReference* region = it->second; + region->ReleaseCompressed(); + } } -bool ConsoleSaveFileSplit::doesFileExist(ConsoleSavePath file) -{ - LockSaveAccess(); - bool exists = header.fileExists( file.getName() ); - ReleaseSaveAccess(); +bool ConsoleSaveFileSplit::doesFileExist(ConsoleSavePath file) { + LockSaveAccess(); + bool exists = header.fileExists(file.getName()); + ReleaseSaveAccess(); - return exists; + return exists; } -void ConsoleSaveFileSplit::Flush(bool autosave, bool updateThumbnail) -{ - LockSaveAccess(); +void ConsoleSaveFileSplit::Flush(bool autosave, bool updateThumbnail) { + LockSaveAccess(); #ifdef _XBOX_ONE - MinecraftServer *server = MinecraftServer::getInstance(); + MinecraftServer* server = MinecraftServer::getInstance(); #endif - // The storage manage might potentially be busy doing a sub-file write initiated from the tick. Wait until this is totally processed. - while( StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) - { + // The storage manage might potentially be busy doing a sub-file write + // initiated from the tick. Wait until this is totally processed. + while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) { #ifdef _XBOX_ONE - if (server && server->IsSuspending()) - { - // If the server is mid-suspend we need to tick the storage manager ourselves - StorageManager.Tick(); - } + if (server && server->IsSuspending()) { + // If the server is mid-suspend we need to tick the storage manager + // ourselves + StorageManager.Tick(); + } #endif - app.DebugPrintf("Flush wait\n"); - Sleep(10); - } + app.DebugPrintf("Flush wait\n"); + Sleep(10); + } - finalizeWrite(); + finalizeWrite(); - m_autosave = autosave; - if(!m_autosave) processSubfilesForWrite(); + m_autosave = autosave; + if (!m_autosave) processSubfilesForWrite(); - // Get the frequency of the timer - LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; - float fElapsedTime = 0.0f; - QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + // Get the frequency of the timer + LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; + float fElapsedTime = 0.0f; + QueryPerformanceFrequency(&qwTicksPerSec); + float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; - unsigned int fileSize = header.GetFileSize(); + unsigned int fileSize = header.GetFileSize(); - // Assume that the compression will make it smaller so initially attempt to allocate the current file size - // We add 4 bytes to the start so that we can signal compressed data - // And another 4 bytes to store the decompressed data size - unsigned int compLength = fileSize+8; + // Assume that the compression will make it smaller so initially attempt to + // allocate the current file size We add 4 bytes to the start so that we can + // signal compressed data And another 4 bytes to store the decompressed data + // size + unsigned int compLength = fileSize + 8; - // 4J Stu - Added TU-1 interim + // 4J Stu - Added TU-1 interim - // Attempt to allocate the required memory - // We do not own this, it belongs to the StorageManager - std::uint8_t *compData = (std::uint8_t *)StorageManager.AllocateSaveData( compLength ); + // Attempt to allocate the required memory + // We do not own this, it belongs to the StorageManager + std::uint8_t* compData = + (std::uint8_t*)StorageManager.AllocateSaveData(compLength); - // If we failed to allocate then compData will be NULL - // Pre-calculate the compressed data size so that we can attempt to allocate a smaller buffer - if(compData == NULL) - { - // Length should be 0 here so that the compression call knows that we want to know the length back - compLength = 0; + // If we failed to allocate then compData will be NULL + // Pre-calculate the compressed data size so that we can attempt to allocate + // a smaller buffer + if (compData == NULL) { + // Length should be 0 here so that the compression call knows that we + // want to know the length back + compLength = 0; - // Pre-calculate the buffer size required for the compressed data - PIXBeginNamedEvent(0,"Pre-calc save compression"); - // Save the start time - QueryPerformanceCounter( &qwTime ); - Compression::getCompression()->Compress(NULL,&compLength,pvSaveMem,fileSize); - QueryPerformanceCounter( &qwNewTime ); + // Pre-calculate the buffer size required for the compressed data + PIXBeginNamedEvent(0, "Pre-calc save compression"); + // Save the start time + QueryPerformanceCounter(&qwTime); + Compression::getCompression()->Compress(NULL, &compLength, pvSaveMem, + fileSize); + QueryPerformanceCounter(&qwNewTime); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Check buffer size: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + app.DebugPrintf("Check buffer size: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); - // We add 4 bytes to the start so that we can signal compressed data - // And another 4 bytes to store the decompressed data size - compLength = compLength+8; + // We add 4 bytes to the start so that we can signal compressed data + // And another 4 bytes to store the decompressed data size + compLength = compLength + 8; - // Attempt to allocate the required memory - compData = (std::uint8_t *)StorageManager.AllocateSaveData( compLength ); - } - - if(compData != NULL) - { - // Re-compress all save data before we save it to disk - PIXBeginNamedEvent(0,"Actual save compression"); - // Save the start time - QueryPerformanceCounter( &qwTime ); - Compression::getCompression()->Compress(compData+8,&compLength,pvSaveMem,fileSize); - QueryPerformanceCounter( &qwNewTime ); + // Attempt to allocate the required memory + compData = (std::uint8_t*)StorageManager.AllocateSaveData(compLength); + } - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + if (compData != NULL) { + // Re-compress all save data before we save it to disk + PIXBeginNamedEvent(0, "Actual save compression"); + // Save the start time + QueryPerformanceCounter(&qwTime); + Compression::getCompression()->Compress(compData + 8, &compLength, + pvSaveMem, fileSize); + QueryPerformanceCounter(&qwNewTime); - app.DebugPrintf("Compress: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - ZeroMemory(compData,8); - int saveVer = 0; - memcpy( compData, &saveVer, sizeof(int) ); - memcpy( compData+4, &fileSize, sizeof(int) ); + app.DebugPrintf("Compress: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); - app.DebugPrintf("Save data compressed from %d to %d\n", fileSize, compLength); + ZeroMemory(compData, 8); + int saveVer = 0; + memcpy(compData, &saveVer, sizeof(int)); + memcpy(compData + 4, &fileSize, sizeof(int)); - if(updateThumbnail) - { - std::uint8_t *pbThumbnailData = NULL; - unsigned int dwThumbnailDataSize = 0; + app.DebugPrintf("Save data compressed from %d to %d\n", fileSize, + compLength); - std::uint8_t *pbDataSaveImage = NULL; - unsigned int dwDataSizeSaveImage = 0; + if (updateThumbnail) { + std::uint8_t* pbThumbnailData = NULL; + unsigned int dwThumbnailDataSize = 0; -#if ( defined _XBOX || defined _DURANGO ) - app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); -#elif ( defined __PS3__ || defined __ORBIS__ ) - app.GetSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize,&pbDataSaveImage,&dwDataSizeSaveImage); + std::uint8_t* pbDataSaveImage = NULL; + unsigned int dwDataSizeSaveImage = 0; + +#if (defined _XBOX || defined _DURANGO) + app.GetSaveThumbnail(&pbThumbnailData, &dwThumbnailDataSize); +#elif (defined __PS3__ || defined __ORBIS__) + app.GetSaveThumbnail(&pbThumbnailData, &dwThumbnailDataSize, + &pbDataSaveImage, &dwDataSizeSaveImage); #endif - std::uint8_t bTextMetadata[88]; - ZeroMemory(bTextMetadata,88); + std::uint8_t bTextMetadata[88]; + ZeroMemory(bTextMetadata, 88); - __int64 seed = 0; - bool hasSeed = false; - if(MinecraftServer::getInstance()!= NULL && MinecraftServer::getInstance()->levels[0]!=NULL) - { - seed = MinecraftServer::getInstance()->levels[0]->getLevelData()->getSeed(); - hasSeed = true; - } + __int64 seed = 0; + bool hasSeed = false; + if (MinecraftServer::getInstance() != NULL && + MinecraftServer::getInstance()->levels[0] != NULL) { + seed = MinecraftServer::getInstance() + ->levels[0] + ->getLevelData() + ->getSeed(); + hasSeed = true; + } - int iTextMetadataBytes = app.CreateImageTextData(bTextMetadata, seed, hasSeed, app.GetGameHostOption(eGameHostOption_All), Minecraft::GetInstance()->getCurrentTexturePackId()); + int iTextMetadataBytes = app.CreateImageTextData( + bTextMetadata, seed, hasSeed, + app.GetGameHostOption(eGameHostOption_All), + Minecraft::GetInstance()->getCurrentTexturePackId()); - // set the icon and save image - StorageManager.SetSaveImages(pbThumbnailData,dwThumbnailDataSize,pbDataSaveImage,dwDataSizeSaveImage,bTextMetadata,iTextMetadataBytes); - app.DebugPrintf("Save thumbnail size %d\n",dwThumbnailDataSize); + // set the icon and save image + StorageManager.SetSaveImages(pbThumbnailData, dwThumbnailDataSize, + pbDataSaveImage, dwDataSizeSaveImage, + bTextMetadata, iTextMetadataBytes); + app.DebugPrintf("Save thumbnail size %d\n", dwThumbnailDataSize); + } - } - - INT saveOrCheckpointId = 0; - bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); - TelemetryManager->RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), saveOrCheckpointId, compLength+8); + INT saveOrCheckpointId = 0; + bool validSave = + StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); + TelemetryManager->RecordLevelSaveOrCheckpoint( + ProfileManager.GetPrimaryPad(), saveOrCheckpointId, compLength + 8); - // save the data - StorageManager.SaveSaveData( &ConsoleSaveFileSplit::SaveSaveDataCallback, this ); + // save the data + StorageManager.SaveSaveData(&ConsoleSaveFileSplit::SaveSaveDataCallback, + this); #ifndef _CONTENT_PACKAGE - if( app.DebugSettingsOn()) - { - if(app.GetWriteSavesToFolderEnabled() ) - { - DebugFlushToFile(compData, compLength+8); - } - } + if (app.DebugSettingsOn()) { + if (app.GetWriteSavesToFolderEnabled()) { + DebugFlushToFile(compData, compLength + 8); + } + } #endif - ReleaseSaveAccess(); - } + ReleaseSaveAccess(); + } } -int ConsoleSaveFileSplit::SaveSaveDataCallback(void *lpParam, bool bRes) -{ - ConsoleSaveFileSplit *pClass=(ConsoleSaveFileSplit *)lpParam; - - // Don't save sub files on autosave (their always being saved anyway) - if (!pClass->m_autosave) - { - // This is called from the StorageManager.Tick() which should always be on the main thread - StorageManager.SaveSubfiles(SaveRegionFilesCallback, pClass); - } - return 0; +int ConsoleSaveFileSplit::SaveSaveDataCallback(void* lpParam, bool bRes) { + ConsoleSaveFileSplit* pClass = (ConsoleSaveFileSplit*)lpParam; + + // Don't save sub files on autosave (their always being saved anyway) + if (!pClass->m_autosave) { + // This is called from the StorageManager.Tick() which should always be + // on the main thread + StorageManager.SaveSubfiles(SaveRegionFilesCallback, pClass); + } + return 0; } -int ConsoleSaveFileSplit::SaveRegionFilesCallback(void *lpParam, bool bRes) -{ - ConsoleSaveFileSplit *pClass=(ConsoleSaveFileSplit *)lpParam; - - // This is called from the StorageManager.Tick() which should always be on the main thread - pClass->processSubfilesAfterWrite(); +int ConsoleSaveFileSplit::SaveRegionFilesCallback(void* lpParam, bool bRes) { + ConsoleSaveFileSplit* pClass = (ConsoleSaveFileSplit*)lpParam; - return 0; + // This is called from the StorageManager.Tick() which should always be on + // the main thread + pClass->processSubfilesAfterWrite(); + + return 0; } #ifndef _CONTENT_PACKAGE -void ConsoleSaveFileSplit::DebugFlushToFile(void *compressedData /*= NULL*/, unsigned int compressedDataSize /*= 0*/) -{ - LockSaveAccess(); +void ConsoleSaveFileSplit::DebugFlushToFile( + void* compressedData /*= NULL*/, unsigned int compressedDataSize /*= 0*/) { + LockSaveAccess(); - finalizeWrite(); + finalizeWrite(); - unsigned int fileSize = header.GetFileSize(); + unsigned int fileSize = header.GetFileSize(); - unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesWritten = 0; - File targetFileDir(L"Saves"); + File targetFileDir(L"Saves"); - if(!targetFileDir.exists()) - targetFileDir.mkdir(); + if (!targetFileDir.exists()) targetFileDir.mkdir(); - wchar_t *fileName = new wchar_t[XCONTENT_MAX_FILENAME_LENGTH+1]; + wchar_t* fileName = new wchar_t[XCONTENT_MAX_FILENAME_LENGTH + 1]; - SYSTEMTIME t; - GetSystemTime( &t ); + SYSTEMTIME t; + GetSystemTime(&t); - //14 chars for the digits - //11 chars for the separators + suffix - //25 chars total - std::wstring cutFileName = m_fileName; - if(m_fileName.length() > XCONTENT_MAX_FILENAME_LENGTH - 25) - { - cutFileName = m_fileName.substr(0, XCONTENT_MAX_FILENAME_LENGTH - 25); - } - swprintf(fileName, XCONTENT_MAX_FILENAME_LENGTH+1, L"\\v%04d-%ls%02d.%02d.%02d.%02d.%02d.mcs",VER_PRODUCTBUILD,cutFileName.c_str(), t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); + // 14 chars for the digits + // 11 chars for the separators + suffix + // 25 chars total + std::wstring cutFileName = m_fileName; + if (m_fileName.length() > XCONTENT_MAX_FILENAME_LENGTH - 25) { + cutFileName = m_fileName.substr(0, XCONTENT_MAX_FILENAME_LENGTH - 25); + } + swprintf(fileName, XCONTENT_MAX_FILENAME_LENGTH + 1, + L"\\v%04d-%ls%02d.%02d.%02d.%02d.%02d.mcs", VER_PRODUCTBUILD, + cutFileName.c_str(), t.wMonth, t.wDay, t.wHour, t.wMinute, + t.wSecond); - const std::wstring outputPath = targetFileDir.getPath() + std::wstring(fileName); - bool writeSucceeded = false; + const std::wstring outputPath = + targetFileDir.getPath() + std::wstring(fileName); + bool writeSucceeded = false; - if(compressedData != NULL && compressedDataSize > 0) - { - writeSucceeded = PortableFileIO::WriteBinaryFile(outputPath, compressedData, compressedDataSize); - numberOfBytesWritten = writeSucceeded ? compressedDataSize : 0; - assert(numberOfBytesWritten == compressedDataSize); - } - else - { - writeSucceeded = PortableFileIO::WriteBinaryFile(outputPath, pvSaveMem, fileSize); - numberOfBytesWritten = writeSucceeded ? fileSize : 0; - assert(numberOfBytesWritten == fileSize); - } + if (compressedData != NULL && compressedDataSize > 0) { + writeSucceeded = PortableFileIO::WriteBinaryFile( + outputPath, compressedData, compressedDataSize); + numberOfBytesWritten = writeSucceeded ? compressedDataSize : 0; + assert(numberOfBytesWritten == compressedDataSize); + } else { + writeSucceeded = + PortableFileIO::WriteBinaryFile(outputPath, pvSaveMem, fileSize); + numberOfBytesWritten = writeSucceeded ? fileSize : 0; + assert(numberOfBytesWritten == fileSize); + } - delete[] fileName; + delete[] fileName; - ReleaseSaveAccess(); + ReleaseSaveAccess(); } #endif -unsigned int ConsoleSaveFileSplit::getSizeOnDisk() -{ - return header.GetFileSize(); +unsigned int ConsoleSaveFileSplit::getSizeOnDisk() { + return header.GetFileSize(); } -std::wstring ConsoleSaveFileSplit::getFilename() -{ - return m_fileName; +std::wstring ConsoleSaveFileSplit::getFilename() { return m_fileName; } + +std::vector* ConsoleSaveFileSplit::getFilesWithPrefix( + const std::wstring& prefix) { + return header.getFilesWithPrefix(prefix); } -std::vector *ConsoleSaveFileSplit::getFilesWithPrefix(const std::wstring &prefix) -{ - return header.getFilesWithPrefix( prefix ); -} +std::vector* ConsoleSaveFileSplit::getRegionFilesByDimension( + unsigned int dimensionIndex) { + std::vector* files = NULL; -std::vector *ConsoleSaveFileSplit::getRegionFilesByDimension(unsigned int dimensionIndex) -{ - std::vector *files = NULL; + for (AUTO_VAR(it, regionFiles.begin()); it != regionFiles.end(); ++it) { + unsigned int entryDimension = ((it->first) >> 16) & 0xFF; - for( AUTO_VAR(it,regionFiles.begin()); it != regionFiles.end(); ++it ) - { - unsigned int entryDimension = ( (it->first) >> 16) & 0xFF; + if (entryDimension == dimensionIndex) { + if (files == NULL) { + files = new std::vector(); + } - if(entryDimension == dimensionIndex) - { - if( files == NULL ) - { - files = new std::vector(); - } + files->push_back(it->second->fileEntry); + } + } - files->push_back(it->second->fileEntry); - } - } - - return files; + return files; } #if defined(__PS3__) || defined(__ORBIS__) -std::wstring ConsoleSaveFileSplit::getPlayerDataFilenameForLoad(const PlayerUID& pUID) -{ - return header.getPlayerDataFilenameForLoad( pUID ); +std::wstring ConsoleSaveFileSplit::getPlayerDataFilenameForLoad( + const PlayerUID& pUID) { + return header.getPlayerDataFilenameForLoad(pUID); } -std::wstring ConsoleSaveFileSplit::getPlayerDataFilenameForSave(const PlayerUID& pUID) -{ - return header.getPlayerDataFilenameForSave( pUID ); +std::wstring ConsoleSaveFileSplit::getPlayerDataFilenameForSave( + const PlayerUID& pUID) { + return header.getPlayerDataFilenameForSave(pUID); } -std::vector *ConsoleSaveFileSplit::getValidPlayerDatFiles() -{ - return header.getValidPlayerDatFiles(); +std::vector* ConsoleSaveFileSplit::getValidPlayerDatFiles() { + return header.getValidPlayerDatFiles(); } #endif -int ConsoleSaveFileSplit::getSaveVersion() -{ - return header.getSaveVersion(); +int ConsoleSaveFileSplit::getSaveVersion() { return header.getSaveVersion(); } + +int ConsoleSaveFileSplit::getOriginalSaveVersion() { + return header.getOriginalSaveVersion(); } -int ConsoleSaveFileSplit::getOriginalSaveVersion() -{ - return header.getOriginalSaveVersion(); +void ConsoleSaveFileSplit::LockSaveAccess() { EnterCriticalSection(&m_lock); } + +void ConsoleSaveFileSplit::ReleaseSaveAccess() { + LeaveCriticalSection(&m_lock); } -void ConsoleSaveFileSplit::LockSaveAccess() -{ - EnterCriticalSection(&m_lock); +ESavePlatform ConsoleSaveFileSplit::getSavePlatform() { + return header.getSavePlatform(); } -void ConsoleSaveFileSplit::ReleaseSaveAccess() -{ - LeaveCriticalSection(&m_lock); +bool ConsoleSaveFileSplit::isSaveEndianDifferent() { + return header.isSaveEndianDifferent(); } -ESavePlatform ConsoleSaveFileSplit::getSavePlatform() -{ - return header.getSavePlatform(); +void ConsoleSaveFileSplit::setLocalPlatform() { header.setLocalPlatform(); } + +void ConsoleSaveFileSplit::setPlatform(ESavePlatform plat) { + header.setPlatform(plat); } -bool ConsoleSaveFileSplit::isSaveEndianDifferent() -{ - return header.isSaveEndianDifferent(); +ByteOrder ConsoleSaveFileSplit::getSaveEndian() { + return header.getSaveEndian(); } -void ConsoleSaveFileSplit::setLocalPlatform() -{ - header.setLocalPlatform(); +ByteOrder ConsoleSaveFileSplit::getLocalEndian() { + return header.getLocalEndian(); } -void ConsoleSaveFileSplit::setPlatform(ESavePlatform plat) -{ - header.setPlatform(plat); +void ConsoleSaveFileSplit::setEndian(ByteOrder endian) { + header.setEndian(endian); } -ByteOrder ConsoleSaveFileSplit::getSaveEndian() -{ - return header.getSaveEndian(); +void ConsoleSaveFileSplit::ConvertRegionFile(File sourceFile) { + unsigned int numberOfBytesWritten = 0; + unsigned int numberOfBytesRead = 0; + + RegionFile sourceRegionFile(this, &sourceFile); + + for (unsigned int x = 0; x < 32; ++x) { + for (unsigned int z = 0; z < 32; ++z) { + DataInputStream* dis = + sourceRegionFile.getChunkDataInputStream(x, z); + + if (dis) { + byteArray inData(1024 * 1024); + int read = dis->read(inData); + dis->close(); + dis->deleteChildStream(); + delete dis; + + DataOutputStream* dos = + sourceRegionFile.getChunkDataOutputStream(x, z); + dos->write(inData, 0, read); + + dos->close(); + dos->deleteChildStream(); + delete dos; + delete inData.data; + } + } + } + sourceRegionFile + .writeAllOffsets(); // saves all the endian swapped offsets back out to + // the file (not all of these are written in the + // above processing). } -ByteOrder ConsoleSaveFileSplit::getLocalEndian() -{ - return header.getLocalEndian(); -} - -void ConsoleSaveFileSplit::setEndian(ByteOrder endian) -{ - header.setEndian(endian); -} - -void ConsoleSaveFileSplit::ConvertRegionFile(File sourceFile) -{ - unsigned int numberOfBytesWritten = 0; - unsigned int numberOfBytesRead = 0; - - RegionFile sourceRegionFile(this, &sourceFile); - - for(unsigned int x = 0; x < 32; ++x) - { - for(unsigned int z = 0; z < 32; ++z) - { - DataInputStream *dis = sourceRegionFile.getChunkDataInputStream(x,z); - - if(dis) - { - byteArray inData(1024*1024); - int read = dis->read(inData); - dis->close(); - dis->deleteChildStream(); - delete dis; - - DataOutputStream *dos = sourceRegionFile.getChunkDataOutputStream(x,z); - dos->write(inData, 0, read); - - - dos->close(); - dos->deleteChildStream(); - delete dos; - delete inData.data; - - } - - } - } - sourceRegionFile.writeAllOffsets(); // saves all the endian swapped offsets back out to the file (not all of these are written in the above processing). - -} - -void ConsoleSaveFileSplit::ConvertToLocalPlatform() -{ - if(getSavePlatform() == SAVE_FILE_PLATFORM_LOCAL) - { - // already in the correct format - return; - } - // convert each of the region files to the local platform - std::vector *allFilesInSave = getFilesWithPrefix(std::wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) - { - FileEntry *fe = *it; - std::wstring fName( fe->data.filename ); - std::wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) - { - app.DebugPrintf("Processing a region file: %ls\n",fName.c_str()); - ConvertRegionFile(File(fe->data.filename) ); - } - else - { - app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); - } - } - - setLocalPlatform(); // set the platform of this save to the local platform, now that it's been coverted +void ConsoleSaveFileSplit::ConvertToLocalPlatform() { + if (getSavePlatform() == SAVE_FILE_PLATFORM_LOCAL) { + // already in the correct format + return; + } + // convert each of the region files to the local platform + std::vector* allFilesInSave = + getFilesWithPrefix(std::wstring(L"")); + for (AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); + ++it) { + FileEntry* fe = *it; + std::wstring fName(fe->data.filename); + std::wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), + suffix) == 0) { + app.DebugPrintf("Processing a region file: %ls\n", fName.c_str()); + ConvertRegionFile(File(fe->data.filename)); + } else { + app.DebugPrintf("%ls is not a region file, ignoring\n", + fName.c_str()); + } + } + + setLocalPlatform(); // set the platform of this save to the local platform, + // now that it's been coverted } diff --git a/Minecraft.World/IO/Files/ConsoleSaveFileSplit.h b/Minecraft.World/IO/Files/ConsoleSaveFileSplit.h index e0f1eeef9..b0b6c755f 100644 --- a/Minecraft.World/IO/Files/ConsoleSaveFileSplit.h +++ b/Minecraft.World/IO/Files/ConsoleSaveFileSplit.h @@ -6,138 +6,165 @@ class ProgressRenderer; -class ConsoleSaveFileSplit : public ConsoleSaveFile -{ +class ConsoleSaveFileSplit : public ConsoleSaveFile { private: - FileHeader header; + FileHeader header; - static const int WRITE_BANDWIDTH_BYTESPERSECOND = 1048576; // Average bytes per second we will cap to when writing region files during the tick() method - static const int WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS = 10; // Time period over which the bytes per second average is calculated - static const int WRITE_TICK_RATE_MS = 500; // Time between attempts to work out which regions we should write during the tick - static const int WRITE_MAX_WRITE_PER_TICK = WRITE_BANDWIDTH_BYTESPERSECOND; // Maximum number of bytes we can add in a single tick + static const int WRITE_BANDWIDTH_BYTESPERSECOND = + 1048576; // Average bytes per second we will cap to when writing region + // files during the tick() method + static const int WRITE_BANDWIDTH_MEASUREMENT_PERIOD_SECONDS = + 10; // Time period over which the bytes per second average is + // calculated + static const int WRITE_TICK_RATE_MS = + 500; // Time between attempts to work out which regions we should write + // during the tick + static const int WRITE_MAX_WRITE_PER_TICK = + WRITE_BANDWIDTH_BYTESPERSECOND; // Maximum number of bytes we can add + // in a single tick - class WriteHistory - { - public: - std::int64_t writeTime; - unsigned int writeSize; - } ; + class WriteHistory { + public: + std::int64_t writeTime; + unsigned int writeSize; + }; - class DirtyRegionFile - { - public: - std::int64_t lastWritten; - unsigned int fileRef; - bool operator<(const DirtyRegionFile& rhs) const { return lastWritten < rhs.lastWritten; } - }; + class DirtyRegionFile { + public: + std::int64_t lastWritten; + unsigned int fileRef; + bool operator<(const DirtyRegionFile& rhs) const { + return lastWritten < rhs.lastWritten; + } + }; - class RegionFileReference - { - public: - RegionFileReference(int index, unsigned int regionIndex, unsigned int length = 0, unsigned char *data = NULL); - ~RegionFileReference(); - void Compress(); // Compress from data to dataCompressed - void Decompress(); // Decompress from dataCompressed -> data - unsigned int GetCompressedSize(); // Gets byte size for what this region will compress to - void ReleaseCompressed(); // Release dataCompressed - FileEntry *fileEntry; - unsigned char *data; - unsigned char *dataCompressed; - unsigned int dataCompressedSize; - int index; - bool dirty; - std::int64_t lastWritten; - }; - std::unordered_map regionFiles; - std::vector writeHistory; - std::int64_t m_lastTickTime; + class RegionFileReference { + public: + RegionFileReference(int index, unsigned int regionIndex, + unsigned int length = 0, + unsigned char* data = NULL); + ~RegionFileReference(); + void Compress(); // Compress from data to dataCompressed + void Decompress(); // Decompress from dataCompressed -> data + unsigned int GetCompressedSize(); // Gets byte size for what this + // region will compress to + void ReleaseCompressed(); // Release dataCompressed + FileEntry* fileEntry; + unsigned char* data; + unsigned char* dataCompressed; + unsigned int dataCompressedSize; + int index; + bool dirty; + std::int64_t lastWritten; + }; + std::unordered_map regionFiles; + std::vector writeHistory; + std::int64_t m_lastTickTime; - FileEntry *GetRegionFileEntry(unsigned int regionIndex); + FileEntry* GetRegionFileEntry(unsigned int regionIndex); - std::wstring m_fileName; - bool m_autosave; + std::wstring m_fileName; + bool m_autosave; -// HANDLE hHeap; - static void *pvHeap; - static unsigned int pagesCommitted; + // HANDLE hHeap; + static void* pvHeap; + static unsigned int pagesCommitted; #ifdef _LARGE_WORLDS - static const unsigned int CSF_PAGE_SIZE = 64 * 1024; - static const unsigned int MAX_PAGE_COUNT = 32 * 1024; // 2GB virtual allocation + static const unsigned int CSF_PAGE_SIZE = 64 * 1024; + static const unsigned int MAX_PAGE_COUNT = + 32 * 1024; // 2GB virtual allocation #else - static const unsigned int CSF_PAGE_SIZE = 64 * 1024; - static const unsigned int MAX_PAGE_COUNT = 1024; + static const unsigned int CSF_PAGE_SIZE = 64 * 1024; + static const unsigned int MAX_PAGE_COUNT = 1024; #endif - void *pvSaveMem; + void* pvSaveMem; - CRITICAL_SECTION m_lock; + CRITICAL_SECTION m_lock; - void PrepareForWrite( FileEntry *file, unsigned int nNumberOfBytesToWrite ); - void MoveDataBeyond(FileEntry *file, unsigned int nNumberOfBytesToWrite); + void PrepareForWrite(FileEntry* file, unsigned int nNumberOfBytesToWrite); + void MoveDataBeyond(FileEntry* file, unsigned int nNumberOfBytesToWrite); + + bool GetNumericIdentifierFromName(const std::wstring& fileName, + unsigned int* idOut); + std::wstring GetNameFromNumericIdentifier(unsigned int idIn); + void processSubfilesForWrite(); + void processSubfilesAfterWrite(); - bool GetNumericIdentifierFromName(const std::wstring &fileName, unsigned int *idOut); - std::wstring GetNameFromNumericIdentifier(unsigned int idIn); - void processSubfilesForWrite(); - void processSubfilesAfterWrite(); public: - static int SaveSaveDataCallback(void *lpParam, bool bRes); - static int SaveRegionFilesCallback(void *lpParam, bool bRes); - + static int SaveSaveDataCallback(void* lpParam, bool bRes); + static int SaveRegionFilesCallback(void* lpParam, bool bRes); + private: - void _init(const std::wstring &fileName, void *pvSaveData, unsigned int fileSize, ESavePlatform plat); + void _init(const std::wstring& fileName, void* pvSaveData, + unsigned int fileSize, ESavePlatform plat); public: - ConsoleSaveFileSplit(const std::wstring &fileName, void *pvSaveData = NULL, unsigned int fileSize = 0, bool forceCleanSave = false, ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); - ConsoleSaveFileSplit(ConsoleSaveFile *sourceSave, bool alreadySmallRegions = true, ProgressListener *progress = NULL); - virtual ~ConsoleSaveFileSplit(); + ConsoleSaveFileSplit(const std::wstring& fileName, void* pvSaveData = NULL, + unsigned int fileSize = 0, bool forceCleanSave = false, + ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); + ConsoleSaveFileSplit(ConsoleSaveFile* sourceSave, + bool alreadySmallRegions = true, + ProgressListener* progress = NULL); + virtual ~ConsoleSaveFileSplit(); - // 4J Stu - Initial implementation is intended to have a similar interface to the standard Xbox file access functions + // 4J Stu - Initial implementation is intended to have a similar interface + // to the standard Xbox file access functions - virtual FileEntry *createFile( const ConsoleSavePath &fileName ); - virtual void deleteFile( FileEntry *file ); + virtual FileEntry* createFile(const ConsoleSavePath& fileName); + virtual void deleteFile(FileEntry* file); - virtual void setFilePointer(FileEntry *file, unsigned int distanceToMove, SaveFileSeekOrigin seekOrigin); - virtual bool writeFile( FileEntry *file, const void *lpBuffer, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten ); - virtual bool zeroFile(FileEntry *file, unsigned int nNumberOfBytesToWrite, unsigned int *lpNumberOfBytesWritten); - virtual bool readFile( FileEntry *file, void *lpBuffer, unsigned int nNumberOfBytesToRead, unsigned int *lpNumberOfBytesRead ); - virtual bool closeHandle( FileEntry *file ); + virtual void setFilePointer(FileEntry* file, unsigned int distanceToMove, + SaveFileSeekOrigin seekOrigin); + virtual bool writeFile(FileEntry* file, const void* lpBuffer, + unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten); + virtual bool zeroFile(FileEntry* file, unsigned int nNumberOfBytesToWrite, + unsigned int* lpNumberOfBytesWritten); + virtual bool readFile(FileEntry* file, void* lpBuffer, + unsigned int nNumberOfBytesToRead, + unsigned int* lpNumberOfBytesRead); + virtual bool closeHandle(FileEntry* file); - virtual void finalizeWrite(); - virtual void tick(); + virtual void finalizeWrite(); + virtual void tick(); - virtual bool doesFileExist(ConsoleSavePath file); + virtual bool doesFileExist(ConsoleSavePath file); - virtual void Flush(bool autosave, bool updateThumbnail = true); + virtual void Flush(bool autosave, bool updateThumbnail = true); #ifndef _CONTENT_PACKAGE - virtual void DebugFlushToFile(void *compressedData = NULL, unsigned int compressedDataSize = 0); + virtual void DebugFlushToFile(void* compressedData = NULL, + unsigned int compressedDataSize = 0); #endif - virtual unsigned int getSizeOnDisk(); + virtual unsigned int getSizeOnDisk(); - virtual std::wstring getFilename(); + virtual std::wstring getFilename(); - virtual std::vector *getFilesWithPrefix(const std::wstring &prefix); - virtual std::vector *getRegionFilesByDimension(unsigned int dimensionIndex); + virtual std::vector* getFilesWithPrefix( + const std::wstring& prefix); + virtual std::vector* getRegionFilesByDimension( + unsigned int dimensionIndex); #if defined(__PS3__) || defined(__ORBIS__) - virtual std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); - virtual std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); - virtual std::vector *getValidPlayerDatFiles(); -#endif //__PS3__ + virtual std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); + virtual std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); + virtual std::vector* getValidPlayerDatFiles(); +#endif //__PS3__ - virtual int getSaveVersion(); - virtual int getOriginalSaveVersion(); + virtual int getSaveVersion(); + virtual int getOriginalSaveVersion(); - virtual void LockSaveAccess(); - virtual void ReleaseSaveAccess(); + virtual void LockSaveAccess(); + virtual void ReleaseSaveAccess(); - virtual ESavePlatform getSavePlatform(); - virtual bool isSaveEndianDifferent(); - virtual void setLocalPlatform(); - virtual void setPlatform(ESavePlatform plat); - virtual ByteOrder getSaveEndian(); - virtual ByteOrder getLocalEndian(); - virtual void setEndian(ByteOrder endian); + virtual ESavePlatform getSavePlatform(); + virtual bool isSaveEndianDifferent(); + virtual void setLocalPlatform(); + virtual void setPlatform(ESavePlatform plat); + virtual ByteOrder getSaveEndian(); + virtual ByteOrder getLocalEndian(); + virtual void setEndian(ByteOrder endian); - virtual void ConvertRegionFile(File sourceFile); - virtual void ConvertToLocalPlatform(); + virtual void ConvertRegionFile(File sourceFile); + virtual void ConvertToLocalPlatform(); }; diff --git a/Minecraft.World/IO/Files/ConsoleSavePath.h b/Minecraft.World/IO/Files/ConsoleSavePath.h index 99f9837e0..1eaeb4cdc 100644 --- a/Minecraft.World/IO/Files/ConsoleSavePath.h +++ b/Minecraft.World/IO/Files/ConsoleSavePath.h @@ -1,15 +1,13 @@ #pragma once - -class ConsoleSavePath -{ +class ConsoleSavePath { private: - std::wstring path; + std::wstring path; public: - ConsoleSavePath( const std::wstring &newPath ) { path = newPath; } + ConsoleSavePath(const std::wstring& newPath) { path = newPath; } - std::wstring getName() const { return path; } + std::wstring getName() const { return path; } - std::wstring operator+( std::wstring &b ) { return path + b; } + std::wstring operator+(std::wstring& b) { return path + b; } }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/File.cpp b/Minecraft.World/IO/Files/File.cpp index 16064ff31..8f03fa15a 100644 --- a/Minecraft.World/IO/Files/File.cpp +++ b/Minecraft.World/IO/Files/File.cpp @@ -18,96 +18,99 @@ const wchar_t File::pathSeparator = L'/'; #ifdef _XBOX -const std::wstring File::pathRoot = L"GAME:"; // Path root after pathSeparator has been removed +const std::wstring File::pathRoot = + L"GAME:"; // Path root after pathSeparator has been removed #else -const std::wstring File::pathRoot = L""; // Path root after pathSeparator has been removed +const std::wstring File::pathRoot = + L""; // Path root after pathSeparator has been removed #endif #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) -namespace -{ - namespace fs = std::filesystem; +namespace { +namespace fs = std::filesystem; - fs::path ToFilesystemPath(const std::wstring& path) - { - const std::string nativePath = wstringtofilename(path); - return fs::u8path(nativePath); - } - - std::wstring ToFilename(const fs::path& path) - { - const std::string filename = path.filename().u8string(); - return filenametowstring(filename.c_str()); - } - - __int64 ToEpochMilliseconds(const fs::file_time_type& fileTime) - { - using namespace std::chrono; - - const auto systemTime = time_point_cast( - fileTime - fs::file_time_type::clock::now() + system_clock::now()); - return static_cast<__int64>(systemTime.time_since_epoch().count()); - } +fs::path ToFilesystemPath(const std::wstring& path) { + const std::string nativePath = wstringtofilename(path); + return fs::u8path(nativePath); } + +std::wstring ToFilename(const fs::path& path) { + const std::string filename = path.filename().u8string(); + return filenametowstring(filename.c_str()); +} + +__int64 ToEpochMilliseconds(const fs::file_time_type& fileTime) { + using namespace std::chrono; + + const auto systemTime = time_point_cast( + fileTime - fs::file_time_type::clock::now() + system_clock::now()); + return static_cast<__int64>(systemTime.time_since_epoch().count()); +} +} // namespace #endif -//Creates a new File instance from a parent abstract pathname and a child pathname string. -File::File( const File &parent, const std::wstring& child ) -{ - m_abstractPathName = parent.getPath() + pathSeparator + child; +// Creates a new File instance from a parent abstract pathname and a child +// pathname string. +File::File(const File& parent, const std::wstring& child) { + m_abstractPathName = parent.getPath() + pathSeparator + child; } -//Creates a new File instance by converting the given pathname string into an abstract pathname. -File::File( const std::wstring& pathname ) //: parent( NULL ) +// Creates a new File instance by converting the given pathname string into an +// abstract pathname. +File::File(const std::wstring& pathname) //: parent( NULL ) { - // #ifndef _CONTENT_PACKAGE - // char buf[256]; - // wcstombs(buf, pathname.c_str(), 256); - // printf("File::File - %s\n",buf); - // #endif - if( pathname.empty() ) - m_abstractPathName = std::wstring( L"" ); - else - m_abstractPathName = pathname; + // #ifndef _CONTENT_PACKAGE + // char buf[256]; + // wcstombs(buf, pathname.c_str(), 256); + // printf("File::File - %s\n",buf); + // #endif + if (pathname.empty()) + m_abstractPathName = std::wstring(L""); + else + m_abstractPathName = pathname; #ifdef _WINDOWS64 - std::string path = wstringtofilename(m_abstractPathName); - std::string finalPath = StorageManager.GetMountedPath(path.c_str()); - if(finalPath.size() == 0) finalPath = path; - m_abstractPathName = convStringToWstring(finalPath); + std::string path = wstringtofilename(m_abstractPathName); + std::string finalPath = StorageManager.GetMountedPath(path.c_str()); + if (finalPath.size() == 0) finalPath = path; + m_abstractPathName = convStringToWstring(finalPath); #elif defined(_DURANGO) - std::wstring finalPath = StorageManager.GetMountedPath(m_abstractPathName.c_str()); - if(finalPath.size() == 0) finalPath = m_abstractPathName; - m_abstractPathName = finalPath; + std::wstring finalPath = + StorageManager.GetMountedPath(m_abstractPathName.c_str()); + if (finalPath.size() == 0) finalPath = m_abstractPathName; + m_abstractPathName = finalPath; #endif - /* - std::vector path = stringSplit( pathname, pathSeparator ); + /* + std::vector path = stringSplit( pathname, pathSeparator ); - if( path.back().compare( pathRoot ) != 0 ) - m_abstractPathName = path.back(); - else - m_abstractPathName = L""; + if( path.back().compare( pathRoot ) != 0 ) + m_abstractPathName = path.back(); + else + m_abstractPathName = L""; - path.pop_back(); + path.pop_back(); - if( path.size() > 0 ) - { - // If the last member of the vector is the root then just stop - if( path.back().compare( pathRoot ) != 0 ) - this->parent = new File( &path ); - else - this->parent = NULL; - } - */ + if( path.size() > 0 ) + { + // If the last member of the vector is the root then just stop + if( path.back().compare( pathRoot ) != 0 ) + this->parent = new File( &path ); + else + this->parent = NULL; + } + */ } -File::File( const std::wstring& parent, const std::wstring& child ) //: m_abstractPathName( child ) +File::File(const std::wstring& parent, + const std::wstring& child) //: m_abstractPathName( child ) { - m_abstractPathName = pathRoot + pathSeparator + parent + pathSeparator + child; - //this->parent = new File( parent ); + m_abstractPathName = + pathRoot + pathSeparator + parent + pathSeparator + child; + // this->parent = new File( parent ); } -//Creates a new File instance by converting the given path vector into an abstract pathname. +// Creates a new File instance by converting the given path vector into an +// abstract pathname. /* File::File( std::vector *path ) : parent( NULL ) { @@ -125,754 +128,710 @@ this->parent = NULL; } */ -//Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, -//then the directory must be empty in order to be deleted. -//Returns: -//true if and only if the file or directory is successfully deleted; false otherwise -bool File::_delete() -{ +// Deletes the file or directory denoted by this abstract pathname. If this +// pathname denotes a directory, then the directory must be empty in order to be +// deleted. Returns: true if and only if the file or directory is successfully +// deleted; false otherwise +bool File::_delete() { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - const bool result = fs::remove(ToFilesystemPath(getPath()), error); + std::error_code error; + const bool result = fs::remove(ToFilesystemPath(getPath()), error); #if defined _UNICODE - if( !result || error ) - { + if (!result || error) { #ifndef _CONTENT_PACKAGE - printf( "File::_delete - Error code %d (%#0.8X)\n", error.value(), error.value() ); + printf("File::_delete - Error code %d (%#0.8X)\n", error.value(), + error.value()); #endif - return false; - } - return true; + return false; + } + return true; #elif defined(__linux__) - if( !result || error ) - { - printf("Unable to delete file :("); - return false; - } - return true; + if (!result || error) { + printf("Unable to delete file :("); + return false; + } + return true; #else - if( !result || error ) - { + if (!result || error) { #ifndef _CONTENT_PACKAGE - printf( "File::_delete - Error code %d (%#0.8X)\n", error.value(), error.value() ); + printf("File::_delete - Error code %d (%#0.8X)\n", error.value(), + error.value()); #endif - return false; - } - return true; + return false; + } + return true; #endif #elif defined _UNICODE - const bool result = DeleteFile( getPath().c_str() ) != 0; + const bool result = DeleteFile(getPath().c_str()) != 0; #elif defined(__linux__) - // FIXME - const bool result = false; + // FIXME + const bool result = false; #else - const bool result = DeleteFile( wstringtofilename(getPath()) ) != 0; + const bool result = DeleteFile(wstringtofilename(getPath())) != 0; #endif - if( !result ) - { + if (!result) { #if !defined(__linux__) - const unsigned int error = GetLastError(); + const unsigned int error = GetLastError(); #ifndef _CONTENT_PACKAGE - printf( "File::_delete - Error code %d (%#0.8X)\n", error, error ); + printf("File::_delete - Error code %d (%#0.8X)\n", error, error); #endif #else - printf("Unable to delete file :("); + printf("Unable to delete file :("); #endif - return false; - } - else - return true; + return false; + } else + return true; } -//Creates the directory named by this abstract pathname. -//Returns: -//true if and only if the directory was created; false otherwise -bool File::mkdir() const -{ +// Creates the directory named by this abstract pathname. +// Returns: +// true if and only if the directory was created; false otherwise +bool File::mkdir() const { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - return fs::create_directory(ToFilesystemPath(getPath()), error); -#elif defined (_UNICODE) - return CreateDirectory( getPath().c_str(), NULL) != 0; + std::error_code error; + return fs::create_directory(ToFilesystemPath(getPath()), error); +#elif defined(_UNICODE) + return CreateDirectory(getPath().c_str(), NULL) != 0; #elif defined(__linux__) - return ::mkdir(wstringtofilename(getPath()), 0777) == 0; + return ::mkdir(wstringtofilename(getPath()), 0777) == 0; #else - return CreateDirectory( wstringtofilename(getPath()), NULL) != 0; + return CreateDirectory(wstringtofilename(getPath()), NULL) != 0; #endif } - -//Creates the directory named by this abstract pathname, including any -//necessary but nonexistent parent directories. Note that if this -//operation fails it may have succeeded in creating some of the necessary -//parent directories. +// Creates the directory named by this abstract pathname, including any +// necessary but nonexistent parent directories. Note that if this +// operation fails it may have succeeded in creating some of the necessary +// parent directories. // //@return true if and only if the directory was created, -// along with all necessary parent directories; false -// otherwise +// along with all necessary parent directories; false +// otherwise // //@throws SecurityException -// If a security manager exists and its {@link -// java.lang.SecurityManager#checkRead(java.lang.String)} -// method does not permit verification of the existence of the -// named directory and all necessary parent directories; or if -// the {@link -// java.lang.SecurityManager#checkWrite(java.lang.String)} -// method does not permit the named directory and all necessary -// parent directories to be created +// If a security manager exists and its {@link +// java.lang.SecurityManager#checkRead(java.lang.String)} +// method does not permit verification of the existence of the +// named directory and all necessary parent directories; or if +// the {@link +// java.lang.SecurityManager#checkWrite(java.lang.String)} +// method does not permit the named directory and all necessary +// parent directories to be created // -bool File::mkdirs() const -{ +bool File::mkdirs() const { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - const fs::path path = ToFilesystemPath(getPath()); + std::error_code error; + const fs::path path = ToFilesystemPath(getPath()); - if( fs::exists(path, error) ) - { - return fs::is_directory(path, error); - } + if (fs::exists(path, error)) { + return fs::is_directory(path, error); + } - if( error ) - { - return false; - } + if (error) { + return false; + } - return fs::create_directories(path, error); + return fs::create_directories(path, error); #else - std::vector path = stringSplit( m_abstractPathName, pathSeparator ); + std::vector path = + stringSplit(m_abstractPathName, pathSeparator); - std::wstring pathToHere = L""; - AUTO_VAR(itEnd, path.end()); - for( AUTO_VAR(it, path.begin()); it != itEnd; it++ ) - { - // If this member of the vector is the root then just skip to the next - if( pathRoot.compare( *it ) == 0 ) - { - pathToHere = *it; - continue; - } + std::wstring pathToHere = L""; + AUTO_VAR(itEnd, path.end()); + for (AUTO_VAR(it, path.begin()); it != itEnd; it++) { + // If this member of the vector is the root then just skip to the next + if (pathRoot.compare(*it) == 0) { + pathToHere = *it; + continue; + } - pathToHere = pathToHere + pathSeparator + *it; + pathToHere = pathToHere + pathSeparator + *it; - // if not exists + // if not exists #ifdef _UNICODE - if( GetFileAttributes( pathToHere.c_str() ) == -1 ) - { - const bool result = CreateDirectory( pathToHere.c_str(), NULL) != 0; - if( !result ) - { - // Failed to create - return false; - } - } + if (GetFileAttributes(pathToHere.c_str()) == -1) { + const bool result = CreateDirectory(pathToHere.c_str(), NULL) != 0; + if (!result) { + // Failed to create + return false; + } + } #elif defined(__linux__) - const char *mkpath = wstringtofilename(getPath()); - struct stat info; - if (stat(mkpath, &info) != 0 || !(info.st_mode & S_IFDIR)) { - if (::mkdir(mkpath, 0777) != 0) { - return false; - } -} + const char* mkpath = wstringtofilename(getPath()); + struct stat info; + if (stat(mkpath, &info) != 0 || !(info.st_mode & S_IFDIR)) { + if (::mkdir(mkpath, 0777) != 0) { + return false; + } + } #else - if( GetFileAttributes( wstringtofilename(pathToHere) ) == -1 ) - { - const bool result = CreateDirectory( wstringtofilename(pathToHere), NULL) != 0; - if( !result ) - { - // Failed to create - return false; - } - } + if (GetFileAttributes(wstringtofilename(pathToHere)) == -1) { + const bool result = + CreateDirectory(wstringtofilename(pathToHere), NULL) != 0; + if (!result) { + // Failed to create + return false; + } + } #endif - } + } - // We should now exist - assert( exists() ); + // We should now exist + assert(exists()); - return true; + return true; #endif } /* -File *File::getParent() const +File *File::getParent() const { return (File *) parent; } */ -//Tests whether the file or directory denoted by this abstract pathname exists. -//Returns: -//true if and only if the file or directory denoted by this abstract pathname exists; false otherwise -bool File::exists() const -{ - // TODO 4J Stu - Possible we could get an error result from something other than the file not existing? +// Tests whether the file or directory denoted by this abstract pathname exists. +// Returns: +// true if and only if the file or directory denoted by this abstract pathname +// exists; false otherwise +bool File::exists() const { + // TODO 4J Stu - Possible we could get an error result from something other + // than the file not existing? #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - return fs::exists(ToFilesystemPath(getPath()), error); + std::error_code error; + return fs::exists(ToFilesystemPath(getPath()), error); #elif defined(_UNICODE) - return GetFileAttributes( getPath().c_str() ) != -1; + return GetFileAttributes(getPath().c_str()) != -1; #elif defined(__linux__) - // BAD DOBBY BAD DOBBY - return access(wstringtofilename(getPath()), F_OK) != -1; + // BAD DOBBY BAD DOBBY + return access(wstringtofilename(getPath()), F_OK) != -1; #else - return GetFileAttributes( wstringtofilename(getPath()) ) != -1; + return GetFileAttributes(wstringtofilename(getPath())) != -1; #endif } -//Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, -//in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. -//Returns: -//true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise -bool File::isFile() const -{ - return exists() && !isDirectory(); -} +// Tests whether the file denoted by this abstract pathname is a normal file. A +// file is normal if it is not a directory and, in addition, satisfies other +// system-dependent criteria. Any non-directory file created by a Java +// application is guaranteed to be a normal file. Returns: true if and only if +// the file denoted by this abstract pathname exists and is a normal file; false +// otherwise +bool File::isFile() const { return exists() && !isDirectory(); } -//Renames the file denoted by this abstract pathname. -//Whether or not this method can move a file from one filesystem to another is platform-dependent. -//The return value should always be checked to make sure that the rename operation was successful. +// Renames the file denoted by this abstract pathname. +// Whether or not this method can move a file from one filesystem to another is +// platform-dependent. The return value should always be checked to make sure +// that the rename operation was successful. // -//Parameters: -//dest - The new abstract pathname for the named file -//Returns: -//true if and only if the renaming succeeded; false otherwise -bool File::renameTo(File dest) -{ +// Parameters: +// dest - The new abstract pathname for the named file +// Returns: +// true if and only if the renaming succeeded; false otherwise +bool File::renameTo(File dest) { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - fs::rename(ToFilesystemPath(getPath()), ToFilesystemPath(dest.getPath()), error); - if(error) - { - perror("File::renameTo - Error renaming file"); - return false; - } - return true; + std::error_code error; + fs::rename(ToFilesystemPath(getPath()), ToFilesystemPath(dest.getPath()), + error); + if (error) { + perror("File::renameTo - Error renaming file"); + return false; + } + return true; #else - std::string sourcePath = wstringtofilename(getPath()); - std::string destPath = wstringtofilename(dest.getPath()); + std::string sourcePath = wstringtofilename(getPath()); + std::string destPath = wstringtofilename(dest.getPath()); - int result = rename(sourcePath.c_str(), destPath.c_str()); + int result = rename(sourcePath.c_str(), destPath.c_str()); - if(result != 0) - { - perror("File::renameTo - Error renaming file"); - return false; - } - else - { - return true; - } + if (result != 0) { + perror("File::renameTo - Error renaming file"); + return false; + } else { + return true; + } #endif } -//Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. -//If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, -//one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory -//are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using -//the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; -//if this pathname is relative then each resulting pathname will be relative to the same directory. +// Returns an array of abstract pathnames denoting the files in the directory +// denoted by this abstract pathname. If this abstract pathname does not denote +// a directory, then this method returns null. Otherwise an array of File +// objects is returned, one for each file or directory in the directory. +// Pathnames denoting the directory itself and the directory's parent directory +// are not included in the result. Each resulting abstract pathname is +// constructed from this abstract pathname using the File(File, String) +// constructor. Therefore if this pathname is absolute then each resulting +// pathname is absolute; if this pathname is relative then each resulting +// pathname will be relative to the same directory. // -//There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, -//in particular, guaranteed to appear in alphabetical order. +// There is no guarantee that the name strings in the resulting array will +// appear in any specific order; they are not, in particular, guaranteed to +// appear in alphabetical order. // -//Returns: -//An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. -//The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, -//or if an I/O error occurs. -std::vector *File::listFiles() const -{ - std::vector *vOutput = new std::vector(); +// Returns: +// An array of abstract pathnames denoting the files and directories in the +// directory denoted by this abstract pathname. The array will be empty if the +// directory is empty. Returns null if this abstract pathname does not denote a +// directory, or if an I/O error occurs. +std::vector* File::listFiles() const { + std::vector* vOutput = new std::vector(); - // TODO 4J Stu - Also need to check for I/O errors? - if( !isDirectory() ) - return vOutput; + // TODO 4J Stu - Also need to check for I/O errors? + if (!isDirectory()) return vOutput; #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - for( fs::directory_iterator it(ToFilesystemPath(getPath()), error); !error && it != fs::directory_iterator(); it.increment(error) ) - { - vOutput->push_back( new File( *this, ToFilename(it->path()) ) ); - } + std::error_code error; + for (fs::directory_iterator it(ToFilesystemPath(getPath()), error); + !error && it != fs::directory_iterator(); it.increment(error)) { + vOutput->push_back(new File(*this, ToFilename(it->path()))); + } #else #ifdef __PS3__ - const char *lpFileName=wstringtofilename(getPath()); - char filePath[256]; + const char* lpFileName = wstringtofilename(getPath()); + char filePath[256]; - std::string mountedPath = StorageManager.GetMountedPath(lpFileName); - if(mountedPath.length() > 0) - { - strcpy(filePath, mountedPath.c_str()); - } - else if(lpFileName[0] == '/') // already fully qualified path - strcpy(filePath, lpFileName ); - else - sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); - int fd; - CellFsErrno err = cellFsOpendir(filePath , &fd); + std::string mountedPath = StorageManager.GetMountedPath(lpFileName); + if (mountedPath.length() > 0) { + strcpy(filePath, mountedPath.c_str()); + } else if (lpFileName[0] == '/') // already fully qualified path + strcpy(filePath, lpFileName); + else + sprintf(filePath, "%s/%s", getUsrDirPath(), lpFileName); + int fd; + CellFsErrno err = cellFsOpendir(filePath, &fd); - CellFsDirectoryEntry de; - std::uint32_t count = 0; - err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), &count); - if(count != 0) - { - do - { - if(de.attribute.st_mode & CELL_FS_S_IFREG) vOutput->push_back( new File( *this, filenametowstring( de.entry_name.d_name ) ) ); - err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), &count); - } while( count ); - } - err = cellFsClose(fd); + CellFsDirectoryEntry de; + std::uint32_t count = 0; + err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), + &count); + if (count != 0) { + do { + if (de.attribute.st_mode & CELL_FS_S_IFREG) + vOutput->push_back( + new File(*this, filenametowstring(de.entry_name.d_name))); + err = cellFsGetDirectoryEntries( + fd, &de, sizeof(CellFsDirectoryEntry), &count); + } while (count); + } + err = cellFsClose(fd); #elif defined __ORBIS__ || defined __PSVITA__ - const char *lpFileName=wstringtofilename(getPath()); - char filePath[256]; + const char* lpFileName = wstringtofilename(getPath()); + char filePath[256]; - std::string mountedPath = StorageManager.GetMountedPath(lpFileName); - if(mountedPath.length() > 0) - { - strcpy(filePath, mountedPath.c_str()); - } - else if(lpFileName[0] == '/') // already fully qualified path - strcpy(filePath, lpFileName ); - else - sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); + std::string mountedPath = StorageManager.GetMountedPath(lpFileName); + if (mountedPath.length() > 0) { + strcpy(filePath, mountedPath.c_str()); + } else if (lpFileName[0] == '/') // already fully qualified path + strcpy(filePath, lpFileName); + else + sprintf(filePath, "%s/%s", getUsrDirPath(), lpFileName); - bool exists = sceFiosDirectoryExistsSync( NULL, filePath ); - if( !exists ) - { - app.DebugPrintf("\nsceFiosDirectoryExistsSync - Directory doesn't exist\n"); - } + bool exists = sceFiosDirectoryExistsSync(NULL, filePath); + if (!exists) { + app.DebugPrintf( + "\nsceFiosDirectoryExistsSync - Directory doesn't exist\n"); + } - //CD - Vita note: sceFiosDHOpenSync returns SCE_FIOS_ERROR_UNIMPLEMENTED - //CD - The Handle also returns as 0 [dh], sceFiosDHOpen could also be failing - //CD - Hence, this fails stating 0 files in directory + // CD - Vita note: sceFiosDHOpenSync returns SCE_FIOS_ERROR_UNIMPLEMENTED + // CD - The Handle also returns as 0 [dh], sceFiosDHOpen could also be + // failing CD - Hence, this fails stating 0 files in directory - SceFiosDH dh = SCE_FIOS_DH_INVALID; - SceFiosBuffer buf; - buf.length = 0; - SceFiosOp op = sceFiosDHOpen(NULL, &dh, filePath, buf); + SceFiosDH dh = SCE_FIOS_DH_INVALID; + SceFiosBuffer buf; + buf.length = 0; + SceFiosOp op = sceFiosDHOpen(NULL, &dh, filePath, buf); - int err = sceFiosOpWait(op); - if( err != SCE_FIOS_OK ) - { - app.DebugPrintf("\nsceFiosOpWait = 0x%x\n",err); - } - SceFiosSize size = sceFiosOpGetActualCount(op); - char *pBuf = new char[size]; - buf.set(pBuf, (size_t)size); + int err = sceFiosOpWait(op); + if (err != SCE_FIOS_OK) { + app.DebugPrintf("\nsceFiosOpWait = 0x%x\n", err); + } + SceFiosSize size = sceFiosOpGetActualCount(op); + char* pBuf = new char[size]; + buf.set(pBuf, (size_t)size); - sceFiosOpDelete( op ); - sceFiosDHClose(NULL, dh); + sceFiosOpDelete(op); + sceFiosDHClose(NULL, dh); - err = sceFiosDHOpenSync(NULL, &dh, filePath, buf); - if( err != SCE_FIOS_OK ) - { - app.DebugPrintf("\nsceFiosDHOpenSync = 0x%x\n",err); - } - SceFiosDirEntry entry; - ZeroMemory(&entry, sizeof(SceFiosDirEntry)); - err = sceFiosDHReadSync(NULL, dh, &entry); - while( err == SCE_FIOS_OK) - { - vOutput->push_back( new File( *this, filenametowstring( entry.fullPath + entry.offsetToName ) ) ); - ZeroMemory(&entry, sizeof(SceFiosDirEntry)); - err = sceFiosDHReadSync(NULL, dh, &entry); - }; + err = sceFiosDHOpenSync(NULL, &dh, filePath, buf); + if (err != SCE_FIOS_OK) { + app.DebugPrintf("\nsceFiosDHOpenSync = 0x%x\n", err); + } + SceFiosDirEntry entry; + ZeroMemory(&entry, sizeof(SceFiosDirEntry)); + err = sceFiosDHReadSync(NULL, dh, &entry); + while (err == SCE_FIOS_OK) { + vOutput->push_back(new File( + *this, filenametowstring(entry.fullPath + entry.offsetToName))); + ZeroMemory(&entry, sizeof(SceFiosDirEntry)); + err = sceFiosDHReadSync(NULL, dh, &entry); + }; - sceFiosDHClose(NULL, dh); - delete pBuf; + sceFiosDHClose(NULL, dh); + delete pBuf; #else #if defined(__linux__) - struct stat wfd; -#else // _WIN32 - WIN32_FIND_DATA wfd; -#endif // __linux__ + struct stat wfd; +#else // _WIN32 + WIN32_FIND_DATA wfd; +#endif // __linux__ #ifdef _UNICODE - WCHAR path[MAX_PATH]; - swprintf( path, L"%ls\\*", getPath().c_str() ); - HANDLE hFind = FindFirstFile( path, &wfd); - if(hFind != INVALID_HANDLE_VALUE) - { - int count = 0; - do - { - vOutput->push_back( new File( *this, wfd.cFileName ) ); - } - while( FindNextFile( hFind, &wfd) ); - FindClose( hFind); - } + WCHAR path[MAX_PATH]; + swprintf(path, L"%ls\\*", getPath().c_str()); + HANDLE hFind = FindFirstFile(path, &wfd); + if (hFind != INVALID_HANDLE_VALUE) { + int count = 0; + do { + vOutput->push_back(new File(*this, wfd.cFileName)); + } while (FindNextFile(hFind, &wfd)); + FindClose(hFind); + } #elif defined(__linux__) - char path[MAX_PATH]; - ::listFiles(path); + char path[MAX_PATH]; + ::listFiles(path); #else - char path[MAX_PATH]; - sprintf( path, "%s\\*", wstringtofilename( getPath() ) ); - HANDLE hFind = FindFirstFile( path, &wfd); - if(hFind != INVALID_HANDLE_VALUE) - { - //int count = 0; - do - { - vOutput->push_back( new File( *this, filenametowstring( wfd.cFileName ) ) ); - } - while( FindNextFile( hFind, &wfd) ); - FindClose( hFind); - } + char path[MAX_PATH]; + sprintf(path, "%s\\*", wstringtofilename(getPath())); + HANDLE hFind = FindFirstFile(path, &wfd); + if (hFind != INVALID_HANDLE_VALUE) { + // int count = 0; + do { + vOutput->push_back( + new File(*this, filenametowstring(wfd.cFileName))); + } while (FindNextFile(hFind, &wfd)); + FindClose(hFind); + } #endif #endif #endif - return vOutput; + return vOutput; } -//Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that -//satisfy the specified filter. The behavior of this method is the same as that of the listFiles() method, except that the pathnames -//in the returned array must satisfy the filter. If the given filter is null then all pathnames are accepted. Otherwise, a pathname -//satisfies the filter if and only if the value true results when the FileFilter.accept(java.io.File) method of the filter is invoked -//on the pathname. -//Parameters: -//filter - A file filter -//Returns: -//An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. -//The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs. -std::vector *File::listFiles(FileFilter *filter) const -{ - // TODO 4J Stu - Also need to check for I/O errors? - if( !isDirectory() ) - return NULL; +// Returns an array of abstract pathnames denoting the files and directories in +// the directory denoted by this abstract pathname that satisfy the specified +// filter. The behavior of this method is the same as that of the listFiles() +// method, except that the pathnames in the returned array must satisfy the +// filter. If the given filter is null then all pathnames are accepted. +// Otherwise, a pathname satisfies the filter if and only if the value true +// results when the FileFilter.accept(java.io.File) method of the filter is +// invoked on the pathname. Parameters: filter - A file filter Returns: An array +// of abstract pathnames denoting the files and directories in the directory +// denoted by this abstract pathname. The array will be empty if the directory +// is empty. Returns null if this abstract pathname does not denote a directory, +// or if an I/O error occurs. +std::vector* File::listFiles(FileFilter* filter) const { + // TODO 4J Stu - Also need to check for I/O errors? + if (!isDirectory()) return NULL; - std::vector *vOutput = new std::vector(); + std::vector* vOutput = new std::vector(); #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - for( fs::directory_iterator it(ToFilesystemPath(getPath()), error); !error && it != fs::directory_iterator(); it.increment(error) ) - { - File thisFile = File( *this, ToFilename(it->path()) ); - if( filter->accept( &thisFile ) ) - { - vOutput->push_back( new File( thisFile ) ); - } - } + std::error_code error; + for (fs::directory_iterator it(ToFilesystemPath(getPath()), error); + !error && it != fs::directory_iterator(); it.increment(error)) { + File thisFile = File(*this, ToFilename(it->path())); + if (filter->accept(&thisFile)) { + vOutput->push_back(new File(thisFile)); + } + } #else #ifdef __PS3__ - const char *lpFileName=wstringtofilename(getPath()); - char filePath[256]; + const char* lpFileName = wstringtofilename(getPath()); + char filePath[256]; - std::string mountedPath = StorageManager.GetMountedPath(lpFileName); - if(mountedPath.length() > 0) - { - strcpy(filePath, mountedPath.c_str()); - } - else if(lpFileName[0] == '/') // already fully qualified path - strcpy(filePath, lpFileName ); - else - sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); - int fd; - CellFsErrno err = cellFsOpendir(filePath, &fd); + std::string mountedPath = StorageManager.GetMountedPath(lpFileName); + if (mountedPath.length() > 0) { + strcpy(filePath, mountedPath.c_str()); + } else if (lpFileName[0] == '/') // already fully qualified path + strcpy(filePath, lpFileName); + else + sprintf(filePath, "%s/%s", getUsrDirPath(), lpFileName); + int fd; + CellFsErrno err = cellFsOpendir(filePath, &fd); - CellFsDirectoryEntry de; - std::uint32_t count = 0; - err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), &count); - if(count != 0) - { - do - { - File thisFile = File( *this, filenametowstring( de.entry_name.d_name ) ); - if( filter->accept( &thisFile ) ) - { - File storageFile = thisFile; - if(de.attribute.st_mode & CELL_FS_S_IFREG) vOutput->push_back( &storageFile ); - } - err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), &count); - } while( count ); - } - err = cellFsClose(fd); + CellFsDirectoryEntry de; + std::uint32_t count = 0; + err = cellFsGetDirectoryEntries(fd, &de, sizeof(CellFsDirectoryEntry), + &count); + if (count != 0) { + do { + File thisFile = + File(*this, filenametowstring(de.entry_name.d_name)); + if (filter->accept(&thisFile)) { + File storageFile = thisFile; + if (de.attribute.st_mode & CELL_FS_S_IFREG) + vOutput->push_back(&storageFile); + } + err = cellFsGetDirectoryEntries( + fd, &de, sizeof(CellFsDirectoryEntry), &count); + } while (count); + } + err = cellFsClose(fd); #else #ifdef _UNICODE - WCHAR path[MAX_PATH]; - WIN32_FIND_DATA wfd; + WCHAR path[MAX_PATH]; + WIN32_FIND_DATA wfd; - swprintf( path, L"%ls\\*", getPath().c_str() ); - HANDLE hFind = FindFirstFile( path, &wfd); - if(hFind != INVALID_HANDLE_VALUE) - { - int count = 0; - do - { - File thisFile = File( *this, wfd.cFileName ); - if( filter->accept( &thisFile ) ) - { - File storageFile = thisFile; - vOutput->push_back( &storageFile ); - } - } while( FindNextFile( hFind, &wfd) ); - FindClose( hFind); - } + swprintf(path, L"%ls\\*", getPath().c_str()); + HANDLE hFind = FindFirstFile(path, &wfd); + if (hFind != INVALID_HANDLE_VALUE) { + int count = 0; + do { + File thisFile = File(*this, wfd.cFileName); + if (filter->accept(&thisFile)) { + File storageFile = thisFile; + vOutput->push_back(&storageFile); + } + } while (FindNextFile(hFind, &wfd)); + FindClose(hFind); + } #elif defined(__linux__) - char path[MAX_PATH]; - ::listFiles(path); + char path[MAX_PATH]; + ::listFiles(path); #else - char path[MAX_PATH]; - WIN32_FIND_DATA wfd; + char path[MAX_PATH]; + WIN32_FIND_DATA wfd; - sprintf( path, "%s\\*", wstringtofilename( getPath() ) ); - HANDLE hFind = FindFirstFile( path, &wfd); - if(hFind != INVALID_HANDLE_VALUE) - { - //int count = 0; - do - { - File thisFile = File( *this, filenametowstring( wfd.cFileName ) ); - if( filter->accept( &thisFile ) ) - { - File storageFile = thisFile; - vOutput->push_back( &storageFile ); - } - } while( FindNextFile( hFind, &wfd) ); - FindClose( hFind); - } + sprintf(path, "%s\\*", wstringtofilename(getPath())); + HANDLE hFind = FindFirstFile(path, &wfd); + if (hFind != INVALID_HANDLE_VALUE) { + // int count = 0; + do { + File thisFile = File(*this, filenametowstring(wfd.cFileName)); + if (filter->accept(&thisFile)) { + File storageFile = thisFile; + vOutput->push_back(&storageFile); + } + } while (FindNextFile(hFind, &wfd)); + FindClose(hFind); + } #endif #endif #endif - return vOutput; + return vOutput; } -//Tests whether the file denoted by this abstract pathname is a directory. -//Returns: -//true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise -bool File::isDirectory() const -{ +// Tests whether the file denoted by this abstract pathname is a directory. +// Returns: +// true if and only if the file denoted by this abstract pathname exists and is +// a directory; false otherwise +bool File::isDirectory() const { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - return fs::is_directory(ToFilesystemPath(getPath()), error); + std::error_code error; + return fs::is_directory(ToFilesystemPath(getPath()), error); #elif defined(_UNICODE) - return exists() && ( GetFileAttributes( getPath().c_str() ) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; + return exists() && (GetFileAttributes(getPath().c_str()) & + FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; #elif defined(__linux__) - const char *dirpath = wstringtofilename(getPath()); - struct stat st; - return stat(dirpath, &st) == 0 && S_ISDIR(st.st_mode); + const char* dirpath = wstringtofilename(getPath()); + struct stat st; + return stat(dirpath, &st) == 0 && S_ISDIR(st.st_mode); #else - return exists() && ( GetFileAttributes( wstringtofilename(getPath()) ) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; + return exists() && (GetFileAttributes(wstringtofilename(getPath())) & + FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; #endif } -//Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. -//Returns: -//The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist -__int64 File::length() -{ +// Returns the length of the file denoted by this abstract pathname. The return +// value is unspecified if this pathname denotes a directory. Returns: The +// length, in bytes, of the file denoted by this abstract pathname, or 0L if the +// file does not exist +__int64 File::length() { #ifdef __PS3__ - //extern const char* getPS3HomePath(); - CellFsErrno err=0; - const char *lpFileName=wstringtofilename(getPath()); - char filePath[256]; + // extern const char* getPS3HomePath(); + CellFsErrno err = 0; + const char* lpFileName = wstringtofilename(getPath()); + char filePath[256]; - std::string mountedPath = StorageManager.GetMountedPath(lpFileName); - if(mountedPath.length() > 0) - { - strcpy(filePath, mountedPath.c_str()); - } - else if(lpFileName[0] == '/') // already fully qualified path - strcpy(filePath, lpFileName ); - else - sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); + std::string mountedPath = StorageManager.GetMountedPath(lpFileName); + if (mountedPath.length() > 0) { + strcpy(filePath, mountedPath.c_str()); + } else if (lpFileName[0] == '/') // already fully qualified path + strcpy(filePath, lpFileName); + else + sprintf(filePath, "%s/%s", getUsrDirPath(), lpFileName); #ifndef _CONTENT_PACKAGE - //printf("+++File::length - %s\n",filePath); + // printf("+++File::length - %s\n",filePath); #endif - // check if the file exists first - CellFsStat statData; - err=cellFsStat(filePath, &statData); + // check if the file exists first + CellFsStat statData; + err = cellFsStat(filePath, &statData); - if( err != CELL_FS_SUCCEEDED) - { - //printf("+++File::length FAILED with %d\n",err); - return 0; - } - if(statData.st_mode == CELL_FS_S_IFDIR) - { - //printf("+++File::length FAILED with %d\n",err); - return 0; - } + if (err != CELL_FS_SUCCEEDED) { + // printf("+++File::length FAILED with %d\n",err); + return 0; + } + if (statData.st_mode == CELL_FS_S_IFDIR) { + // printf("+++File::length FAILED with %d\n",err); + return 0; + } - //printf("+++File::length - %ll\n",statData.st_size); + // printf("+++File::length - %ll\n",statData.st_size); - return statData.st_size; + return statData.st_size; #elif defined __ORBIS__ || defined __PSVITA__ - char filePath[256]; - const char *lpFileName=wstringtofilename(getPath()); + char filePath[256]; + const char* lpFileName = wstringtofilename(getPath()); - std::string mountedPath = StorageManager.GetMountedPath(lpFileName); - if(mountedPath.length() > 0) - { - strcpy(filePath, mountedPath.c_str()); - } - else if(lpFileName[0] == '/') // already fully qualified path - strcpy(filePath, lpFileName ); - else - sprintf(filePath,"%s/%s",getUsrDirPath(), lpFileName ); + std::string mountedPath = StorageManager.GetMountedPath(lpFileName); + if (mountedPath.length() > 0) { + strcpy(filePath, mountedPath.c_str()); + } else if (lpFileName[0] == '/') // already fully qualified path + strcpy(filePath, lpFileName); + else + sprintf(filePath, "%s/%s", getUsrDirPath(), lpFileName); - // check if the file exists first - SceFiosStat statData; - if(sceFiosStatSync(NULL, filePath, &statData) != SCE_FIOS_OK) - { - return 0; - } - if(statData.statFlags & SCE_FIOS_STATUS_DIRECTORY ) - { - return 0; - } - return statData.fileSize; + // check if the file exists first + SceFiosStat statData; + if (sceFiosStatSync(NULL, filePath, &statData) != SCE_FIOS_OK) { + return 0; + } + if (statData.statFlags & SCE_FIOS_STATUS_DIRECTORY) { + return 0; + } + return statData.fileSize; #elif !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - const fs::path path = ToFilesystemPath(getPath()); + std::error_code error; + const fs::path path = ToFilesystemPath(getPath()); - if( fs::is_regular_file(path, error) ) - { - const auto size = fs::file_size(path, error); - if( !error ) - { - return static_cast<__int64>(size); - } - } + if (fs::is_regular_file(path, error)) { + const auto size = fs::file_size(path, error); + if (!error) { + return static_cast<__int64>(size); + } + } - return 0; + return 0; #else - WIN32_FILE_ATTRIBUTE_DATA fileInfoBuffer; + WIN32_FILE_ATTRIBUTE_DATA fileInfoBuffer; #ifdef _UNICODE - const bool result = GetFileAttributesEx( - getPath().c_str(), // file or directory name - GetFileExInfoStandard, // attribute - &fileInfoBuffer // attribute information - ) != 0; + const bool result = + GetFileAttributesEx(getPath().c_str(), // file or directory name + GetFileExInfoStandard, // attribute + &fileInfoBuffer // attribute information + ) != 0; #else - const bool result = GetFileAttributesEx( - wstringtofilename(getPath()), // file or directory name - GetFileExInfoStandard, // attribute - &fileInfoBuffer // attribute information - ) != 0; + const bool result = + GetFileAttributesEx( + wstringtofilename(getPath()), // file or directory name + GetFileExInfoStandard, // attribute + &fileInfoBuffer // attribute information + ) != 0; #endif - if( result && !( (fileInfoBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) ) - { - // Success - LARGE_INTEGER liFileSize; - liFileSize.HighPart = fileInfoBuffer.nFileSizeHigh; - liFileSize.LowPart = fileInfoBuffer.nFileSizeLow; + if (result && !((fileInfoBuffer.dwFileAttributes & + FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { + // Success + LARGE_INTEGER liFileSize; + liFileSize.HighPart = fileInfoBuffer.nFileSizeHigh; + liFileSize.LowPart = fileInfoBuffer.nFileSizeLow; - return liFileSize.QuadPart; - } - else - { - //Fail or a Directory - return 0l; - } + return liFileSize.QuadPart; + } else { + // Fail or a Directory + return 0l; + } #endif } -//Returns the time that the file denoted by this abstract pathname was last modified. -//Returns: -//A long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), -//or 0L if the file does not exist or if an I/O error occurs -__int64 File::lastModified() -{ +// Returns the time that the file denoted by this abstract pathname was last +// modified. Returns: A long value representing the time the file was last +// modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, +// 1970), or 0L if the file does not exist or if an I/O error occurs +__int64 File::lastModified() { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - std::error_code error; - const fs::path path = ToFilesystemPath(getPath()); + std::error_code error; + const fs::path path = ToFilesystemPath(getPath()); - if( fs::is_regular_file(path, error) ) - { - const fs::file_time_type lastWriteTime = fs::last_write_time(path, error); - if( !error ) - { - return ToEpochMilliseconds(lastWriteTime); - } - } + if (fs::is_regular_file(path, error)) { + const fs::file_time_type lastWriteTime = + fs::last_write_time(path, error); + if (!error) { + return ToEpochMilliseconds(lastWriteTime); + } + } - return 0l; + return 0l; #elif !defined(__linux__) - WIN32_FILE_ATTRIBUTE_DATA fileInfoBuffer; + WIN32_FILE_ATTRIBUTE_DATA fileInfoBuffer; #ifdef _UNICODE - const bool result = GetFileAttributesEx( - getPath().c_str(), // file or directory name - GetFileExInfoStandard, // attribute - &fileInfoBuffer // attribute information - ) != 0; + const bool result = + GetFileAttributesEx(getPath().c_str(), // file or directory name + GetFileExInfoStandard, // attribute + &fileInfoBuffer // attribute information + ) != 0; #else - const bool result = GetFileAttributesEx( - wstringtofilename(getPath()), // file or directory name - GetFileExInfoStandard, // attribute - &fileInfoBuffer // attribute information - ) != 0; + const bool result = + GetFileAttributesEx( + wstringtofilename(getPath()), // file or directory name + GetFileExInfoStandard, // attribute + &fileInfoBuffer // attribute information + ) != 0; #endif - if( result && !( (fileInfoBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) ) - { - // Success - LARGE_INTEGER liLastModified; - liLastModified.HighPart = fileInfoBuffer.ftLastWriteTime.dwHighDateTime; - liLastModified.LowPart = fileInfoBuffer.ftLastWriteTime.dwLowDateTime; + if (result && !((fileInfoBuffer.dwFileAttributes & + FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { + // Success + LARGE_INTEGER liLastModified; + liLastModified.HighPart = fileInfoBuffer.ftLastWriteTime.dwHighDateTime; + liLastModified.LowPart = fileInfoBuffer.ftLastWriteTime.dwLowDateTime; - return liLastModified.QuadPart; - } - else - { - //Fail or a Directory - return 0l; - } + return liLastModified.QuadPart; + } else { + // Fail or a Directory + return 0l; + } #else - struct stat fileStat; - if (stat(wstringtofilename(getPath()), &fileStat) == 0 && !S_ISDIR(fileStat.st_mode)) { - return static_cast<__int64>(fileStat.st_mtime); - } else { - return 0l; - } + struct stat fileStat; + if (stat(wstringtofilename(getPath()), &fileStat) == 0 && + !S_ISDIR(fileStat.st_mode)) { + return static_cast<__int64>(fileStat.st_mtime); + } else { + return 0l; + } #endif } -const std::wstring File::getPath() const -{ - /* - std::wstring path; - if ( parent != NULL) - path = parent->getPath(); - else - path = std::wstring(pathRoot); +const std::wstring File::getPath() const { + /* + std::wstring path; + if ( parent != NULL) + path = parent->getPath(); + else + path = std::wstring(pathRoot); - path.push_back( pathSeparator ); - path.append(m_abstractPathName); - */ - return m_abstractPathName; + path.push_back( pathSeparator ); + path.append(m_abstractPathName); + */ + return m_abstractPathName; } -std::wstring File::getName() const -{ - unsigned int sep = (unsigned int )(m_abstractPathName.find_last_of( this->pathSeparator )); - return m_abstractPathName.substr( sep + 1, m_abstractPathName.length() ); +std::wstring File::getName() const { + unsigned int sep = + (unsigned int)(m_abstractPathName.find_last_of(this->pathSeparator)); + return m_abstractPathName.substr(sep + 1, m_abstractPathName.length()); } -bool File::eq_test(const File &x, const File &y) -{ - return x.getPath().compare( y.getPath() ) == 0; +bool File::eq_test(const File& x, const File& y) { + return x.getPath().compare(y.getPath()) == 0; } // 4J TODO JEV, a better hash function may be nessesary. -int File::hash_fnct(const File &k) -{ - int hashCode = 0; +int File::hash_fnct(const File& k) { + int hashCode = 0; - //if (k->parent != NULL) - // hashCode = hash_fnct(k->getParent()); + // if (k->parent != NULL) + // hashCode = hash_fnct(k->getParent()); - wchar_t *ref = (wchar_t *) k.m_abstractPathName.c_str(); + wchar_t* ref = (wchar_t*)k.m_abstractPathName.c_str(); - for (unsigned int i = 0; i < k.m_abstractPathName.length(); i++) - { - hashCode += ((hashCode * 33) + ref[i]) % 149; - } + for (unsigned int i = 0; i < k.m_abstractPathName.length(); i++) { + hashCode += ((hashCode * 33) + ref[i]) % 149; + } - return (int) hashCode; + return (int)hashCode; } diff --git a/Minecraft.World/IO/Files/File.h b/Minecraft.World/IO/Files/File.h index b36dcbae4..ec39b6af2 100644 --- a/Minecraft.World/IO/Files/File.h +++ b/Minecraft.World/IO/Files/File.h @@ -4,51 +4,51 @@ class FileFilter; -class File -{ +class File { public: - //The system-dependent path-separator character - static const wchar_t pathSeparator; + // The system-dependent path-separator character + static const wchar_t pathSeparator; - // 4J Jev, the start of the file root - static const std::wstring pathRoot; + // 4J Jev, the start of the file root + static const std::wstring pathRoot; - File() { m_abstractPathName = L""; } + File() { m_abstractPathName = L""; } - File( const File &parent, const std::wstring& child ); - File( const std::wstring& pathname ); - File( const std::wstring& parent, const std::wstring& child ); - bool _delete(); - bool mkdir() const; - bool mkdirs() const; - bool exists() const; - bool isFile() const; - bool renameTo(File dest); - std::vector *listFiles() const; // Array - std::vector *listFiles(FileFilter *filter) const; - bool isDirectory() const; - __int64 length(); - __int64 lastModified(); - const std::wstring getPath() const; // 4J Jev: TODO - std::wstring getName() const; + File(const File& parent, const std::wstring& child); + File(const std::wstring& pathname); + File(const std::wstring& parent, const std::wstring& child); + bool _delete(); + bool mkdir() const; + bool mkdirs() const; + bool exists() const; + bool isFile() const; + bool renameTo(File dest); + std::vector* listFiles() const; // Array + std::vector* listFiles(FileFilter* filter) const; + bool isDirectory() const; + __int64 length(); + __int64 lastModified(); + const std::wstring getPath() const; // 4J Jev: TODO + std::wstring getName() const; - static int hash_fnct(const File &k); - static bool eq_test(const File &x, const File &y); + static int hash_fnct(const File& k); + static bool eq_test(const File& x, const File& y); private: - void _init(); - std::wstring m_abstractPathName; + void _init(); + std::wstring m_abstractPathName; - // 4J Jev, just helper functions, change between paths and std::vector - //File(std::vector *path); + // 4J Jev, just helper functions, change between paths and + // std::vector + // File(std::vector *path); }; -struct FileKeyHash -{ - int operator() (const File &k) const { return File::hash_fnct(k); } +struct FileKeyHash { + int operator()(const File& k) const { return File::hash_fnct(k); } }; -struct FileKeyEq -{ - bool operator() (const File &x, const File &y) const { return File::eq_test(x, y); } +struct FileKeyEq { + bool operator()(const File& x, const File& y) const { + return File::eq_test(x, y); + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/FileFilter.h b/Minecraft.World/IO/Files/FileFilter.h index 859fbb906..4b779c658 100644 --- a/Minecraft.World/IO/Files/FileFilter.h +++ b/Minecraft.World/IO/Files/FileFilter.h @@ -3,8 +3,7 @@ class File; // 4J Jev, java library interface. -class FileFilter -{ +class FileFilter { public: - virtual bool accept(File *dir) = 0; + virtual bool accept(File* dir) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Files/FileHeader.cpp b/Minecraft.World/IO/Files/FileHeader.cpp index 056345a1c..c3d080c4d 100644 --- a/Minecraft.World/IO/Files/FileHeader.cpp +++ b/Minecraft.World/IO/Files/FileHeader.cpp @@ -1,683 +1,646 @@ #include "../../Platform/stdafx.h" #include "FileHeader.h" -//#define _DEBUG_FILE_HEADER +// #define _DEBUG_FILE_HEADER extern CConsoleMinecraftApp app; -FileHeader::FileHeader() -{ - lastFile = NULL; - m_saveVersion = 0; +FileHeader::FileHeader() { + lastFile = NULL; + m_saveVersion = 0; - // New saves should have an original version set to the latest version. This will be overridden when we load a save - m_originalSaveVersion = SAVE_FILE_VERSION_NUMBER; - m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; - m_saveEndian = m_localEndian; + // New saves should have an original version set to the latest version. This + // will be overridden when we load a save + m_originalSaveVersion = SAVE_FILE_VERSION_NUMBER; + m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; + m_saveEndian = m_localEndian; } -FileHeader::~FileHeader() -{ - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - delete fileTable[i]; - } +FileHeader::~FileHeader() { + for (unsigned int i = 0; i < fileTable.size(); ++i) { + delete fileTable[i]; + } } -FileEntry *FileHeader::AddFile( const std::wstring &name, unsigned int length /* = 0 */ ) -{ - assert( name.length() < 64 ); - - wchar_t filename[64]; - memset( &filename, 0, sizeof( wchar_t ) * 64 ); - memcpy( &filename, name.c_str(), std::min( sizeof( wchar_t ) * 64, sizeof( wchar_t ) * name.length() ) ); +FileEntry* FileHeader::AddFile(const std::wstring& name, + unsigned int length /* = 0 */) { + assert(name.length() < 64); - // Would a map be more efficient? Our file tables probably won't be very big so better to avoid hashing all the time? - // Does the file exist? - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - if( wcscmp( fileTable[i]->data.filename, filename ) == 0 ) - { - // If so, return it - return fileTable[i]; - } - } + wchar_t filename[64]; + memset(&filename, 0, sizeof(wchar_t) * 64); + memcpy(&filename, name.c_str(), + std::min(sizeof(wchar_t) * 64, sizeof(wchar_t) * name.length())); - // Else, add it to our file table - fileTable.push_back( new FileEntry( filename, length, GetStartOfNextData() ) ); - lastFile = fileTable[ fileTable.size() - 1 ]; - return lastFile; + // Would a map be more efficient? Our file tables probably won't be very big + // so better to avoid hashing all the time? Does the file exist? + for (unsigned int i = 0; i < fileTable.size(); ++i) { + if (wcscmp(fileTable[i]->data.filename, filename) == 0) { + // If so, return it + return fileTable[i]; + } + } + + // Else, add it to our file table + fileTable.push_back(new FileEntry(filename, length, GetStartOfNextData())); + lastFile = fileTable[fileTable.size() - 1]; + return lastFile; } -void FileHeader::RemoveFile( FileEntry *file ) -{ - if( file == NULL ) return; +void FileHeader::RemoveFile(FileEntry* file) { + if (file == NULL) return; - AdjustStartOffsets(file, file->getFileSize(), true); + AdjustStartOffsets(file, file->getFileSize(), true); - AUTO_VAR(it, find(fileTable.begin(), fileTable.end(),file)); + AUTO_VAR(it, find(fileTable.begin(), fileTable.end(), file)); - if( it < fileTable.end() ) - { - fileTable.erase( it ); - } + if (it < fileTable.end()) { + fileTable.erase(it); + } #ifndef _CONTENT_PACKAGE - wprintf(L"Removed file %ls\n", file->data.filename); + wprintf(L"Removed file %ls\n", file->data.filename); #endif - - delete file; + + delete file; } -void FileHeader::WriteHeader(void *saveMem) -{ - unsigned int headerOffset = GetStartOfNextData(); +void FileHeader::WriteHeader(void* saveMem) { + unsigned int headerOffset = GetStartOfNextData(); - // 4J Changed for save version 2 to be the number of files rather than the size in bytes - unsigned int headerSize = (int)(fileTable.size()); - - //DWORD numberOfBytesWritten = 0; + // 4J Changed for save version 2 to be the number of files rather than the + // size in bytes + unsigned int headerSize = (int)(fileTable.size()); - // Write the offset of the header - //assert(numberOfBytesWritten == 4); - int *begin = (int *)saveMem; + // DWORD numberOfBytesWritten = 0; + + // Write the offset of the header + // assert(numberOfBytesWritten == 4); + int* begin = (int*)saveMem; #ifdef __PSVITA__ - VirtualCopyTo(begin, &headerOffset, sizeof(headerOffset)); + VirtualCopyTo(begin, &headerOffset, sizeof(headerOffset)); #else - *begin = headerOffset; + *begin = headerOffset; #endif - // Write the size of the header - //assert(numberOfBytesWritten == 4); + // Write the size of the header + // assert(numberOfBytesWritten == 4); #ifdef __PSVITA__ - VirtualCopyTo(begin + 1, &headerSize, sizeof(headerSize)); + VirtualCopyTo(begin + 1, &headerSize, sizeof(headerSize)); #else - *(begin + 1) = headerSize; + *(begin + 1) = headerSize; #endif - short *versions = (short *)(begin + 2); - // Write the original version number + short* versions = (short*)(begin + 2); + // Write the original version number #ifdef __PSVITA__ - VirtualCopyTo(versions, &m_originalSaveVersion, sizeof(m_originalSaveVersion)); + VirtualCopyTo(versions, &m_originalSaveVersion, + sizeof(m_originalSaveVersion)); #else - *versions = m_originalSaveVersion; + *versions = m_originalSaveVersion; #endif - // Write the version number - short versionNumber = SAVE_FILE_VERSION_NUMBER; - //assert(numberOfBytesWritten == 4); - //*(begin + 2) = versionNumber; + // Write the version number + short versionNumber = SAVE_FILE_VERSION_NUMBER; + // assert(numberOfBytesWritten == 4); + //*(begin + 2) = versionNumber; #ifdef __PSVITA__ - VirtualCopyTo(versions + 1, &versionNumber, sizeof(versionNumber)); + VirtualCopyTo(versions + 1, &versionNumber, sizeof(versionNumber)); #else - *(versions + 1) = versionNumber; + *(versions + 1) = versionNumber; #endif #ifdef _DEBUG_FILE_HEADER - app.DebugPrintf("Write save file with original version: %d, and current version %d\n", m_originalSaveVersion, versionNumber); + app.DebugPrintf( + "Write save file with original version: %d, and current version %d\n", + m_originalSaveVersion, versionNumber); #endif - char *headerPosition = (char *)saveMem + headerOffset; + char* headerPosition = (char*)saveMem + headerOffset; #ifdef _DEBUG_FILE_HEADER - app.DebugPrintf("\n\nWrite file Header: Offset = %d, Size = %d\n", headerOffset, headerSize); + app.DebugPrintf("\n\nWrite file Header: Offset = %d, Size = %d\n", + headerOffset, headerSize); #endif - // Write the header - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - //wprintf(L"File: %ls, Start = %d, Length = %d, End = %d\n", fileTable[i]->data.filename, fileTable[i]->data.startOffset, fileTable[i]->data.length, fileTable[i]->data.startOffset + fileTable[i]->data.length); + // Write the header + for (unsigned int i = 0; i < fileTable.size(); ++i) { + // wprintf(L"File: %ls, Start = %d, Length = %d, End = %d\n", + // fileTable[i]->data.filename, fileTable[i]->data.startOffset, + // fileTable[i]->data.length, fileTable[i]->data.startOffset + + // fileTable[i]->data.length); #ifdef __PSVITA__ - VirtualCopyTo((void *)headerPosition, &fileTable[i]->data, sizeof(FileEntrySaveData)); + VirtualCopyTo((void*)headerPosition, &fileTable[i]->data, + sizeof(FileEntrySaveData)); #else - memcpy( (void *)headerPosition, &fileTable[i]->data, sizeof(FileEntrySaveData) ); + memcpy((void*)headerPosition, &fileTable[i]->data, + sizeof(FileEntrySaveData)); #endif - //assert(numberOfBytesWritten == sizeof(FileEntrySaveData)); - headerPosition += sizeof(FileEntrySaveData); - } + // assert(numberOfBytesWritten == sizeof(FileEntrySaveData)); + headerPosition += sizeof(FileEntrySaveData); + } } -void FileHeader::ReadHeader(void *saveMem, ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL */ ) -{ - unsigned int headerOffset; - unsigned int headerSize; +void FileHeader::ReadHeader( + void* saveMem, ESavePlatform plat /*= SAVE_FILE_PLATFORM_LOCAL */) { + unsigned int headerOffset; + unsigned int headerSize; - m_savePlatform = plat; + m_savePlatform = plat; - switch(m_savePlatform) - { - case SAVE_FILE_PLATFORM_X360: - case SAVE_FILE_PLATFORM_PS3: - m_saveEndian = BIGENDIAN; - break; - case SAVE_FILE_PLATFORM_XBONE: - case SAVE_FILE_PLATFORM_WIN64: - case SAVE_FILE_PLATFORM_PS4: - case SAVE_FILE_PLATFORM_PSVITA: - m_saveEndian = LITTLEENDIAN; - break; - default: - assert(0); - m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; - m_saveEndian = m_localEndian; - break; - } + switch (m_savePlatform) { + case SAVE_FILE_PLATFORM_X360: + case SAVE_FILE_PLATFORM_PS3: + m_saveEndian = BIGENDIAN; + break; + case SAVE_FILE_PLATFORM_XBONE: + case SAVE_FILE_PLATFORM_WIN64: + case SAVE_FILE_PLATFORM_PS4: + case SAVE_FILE_PLATFORM_PSVITA: + m_saveEndian = LITTLEENDIAN; + break; + default: + assert(0); + m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; + m_saveEndian = m_localEndian; + break; + } - - // Read the offset of the header - //assert(numberOfBytesRead == 4); - int *begin = (int *)saveMem; + // Read the offset of the header + // assert(numberOfBytesRead == 4); + int* begin = (int*)saveMem; #ifdef __PSVITA__ - VirtualCopyFrom(&headerOffset, begin, sizeof(headerOffset)); + VirtualCopyFrom(&headerOffset, begin, sizeof(headerOffset)); #else - headerOffset = *begin; + headerOffset = *begin; #endif - if(isSaveEndianDifferent()) System::ReverseULONG(&headerOffset); + if (isSaveEndianDifferent()) System::ReverseULONG(&headerOffset); - // Read the size of the header - //assert(numberOfBytesRead == 4); + // Read the size of the header + // assert(numberOfBytesRead == 4); #ifdef __PSVITA__ - VirtualCopyFrom(&headerSize, begin + 1, sizeof(headerSize)); + VirtualCopyFrom(&headerSize, begin + 1, sizeof(headerSize)); #else - headerSize = *(begin + 1); + headerSize = *(begin + 1); #endif - if(isSaveEndianDifferent()) System::ReverseULONG(&headerSize); + if (isSaveEndianDifferent()) System::ReverseULONG(&headerSize); - - short *versions = (short *)(begin + 2); - // Read the original save version number + short* versions = (short*)(begin + 2); + // Read the original save version number #ifdef __PSVITA__ - VirtualCopyFrom(&m_originalSaveVersion, versions, sizeof(m_originalSaveVersion)); + VirtualCopyFrom(&m_originalSaveVersion, versions, + sizeof(m_originalSaveVersion)); #else - m_originalSaveVersion = *(versions); + m_originalSaveVersion = *(versions); #endif - if(isSaveEndianDifferent()) System::ReverseSHORT(&m_originalSaveVersion); + if (isSaveEndianDifferent()) System::ReverseSHORT(&m_originalSaveVersion); - // Read the save version number - //m_saveVersion = *(begin + 2); + // Read the save version number + // m_saveVersion = *(begin + 2); #ifdef __PSVITA__ - VirtualCopyFrom(&m_saveVersion, versions + 1, sizeof(m_saveVersion)); + VirtualCopyFrom(&m_saveVersion, versions + 1, sizeof(m_saveVersion)); #else - m_saveVersion = *(versions + 1); + m_saveVersion = *(versions + 1); #endif - if(isSaveEndianDifferent()) System::ReverseSHORT(&m_saveVersion); + if (isSaveEndianDifferent()) System::ReverseSHORT(&m_saveVersion); #ifdef _DEBUG_FILE_HEADER - app.DebugPrintf("Read save file with orignal version: %d, and current version %d\n", m_originalSaveVersion, m_saveVersion); - app.DebugPrintf("\n\nRead file Header: Offset = %d, Size = %d\n", headerOffset, headerSize); + app.DebugPrintf( + "Read save file with orignal version: %d, and current version %d\n", + m_originalSaveVersion, m_saveVersion); + app.DebugPrintf("\n\nRead file Header: Offset = %d, Size = %d\n", + headerOffset, headerSize); #endif - char *headerPosition = (char *)saveMem + headerOffset; + char* headerPosition = (char*)saveMem + headerOffset; - switch( m_saveVersion ) - { - //case SAVE_FILE_VERSION_NUMBER: - //case 8: // 4J Stu - SAVE_FILE_VERSION_NUMBER 2,3,4,5,6,7,8 are the same, but: - // : Bumped it to 3 in TU5 to force older builds (ie 0062) to generate a new world when trying to load new saves - // : Bumped it to 4 in TU9 to delete versions of The End that were generated in builds prior to TU9 - // : Bumped it to 5 in TU9 to update the map data that was only using 1 bit to determine dimension - // : Bumped it to 6 for PS3 v1 to update map data mappings to use larger PlayerUID - // : Bumped it to 7 for Durango v1 to update map data mappings to use string based PlayerUID - // : Bumped it to 8 for Durango v1 when to save the chunks in a different compressed format - case SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE: - case SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE: - case SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE: - case SAVE_FILE_VERSION_MOVED_STRONGHOLD: - case SAVE_FILE_VERSION_NEW_END: - case SAVE_FILE_VERSION_POST_LAUNCH: - case SAVE_FILE_VERSION_LAUNCH: - { - // Changes for save file version 2: - // headerSize is now a count of elements rather than a count of bytes - // The FileEntrySaveData struct has a lastModifiedTime member + switch (m_saveVersion) { + // case SAVE_FILE_VERSION_NUMBER: + // case 8: // 4J Stu - SAVE_FILE_VERSION_NUMBER 2,3,4,5,6,7,8 are the + // same, but: : Bumped it to 3 in TU5 to force older builds (ie 0062) to + //generate a new world when trying to load new saves : Bumped it to 4 in + //TU9 to delete versions of The End that were generated in builds prior + //to TU9 : Bumped it to 5 in TU9 to update the map data that was only + //using 1 bit to determine dimension : Bumped it to 6 for PS3 v1 to + //update map data mappings to use larger PlayerUID : Bumped it to 7 for + //Durango v1 to update map data mappings to use string based PlayerUID + // : Bumped it to 8 + //for Durango v1 when to save the chunks in a different compressed + //format + case SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE: + case SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE: + case SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE: + case SAVE_FILE_VERSION_MOVED_STRONGHOLD: + case SAVE_FILE_VERSION_NEW_END: + case SAVE_FILE_VERSION_POST_LAUNCH: + case SAVE_FILE_VERSION_LAUNCH: { + // Changes for save file version 2: + // headerSize is now a count of elements rather than a count of + // bytes The FileEntrySaveData struct has a lastModifiedTime member - // Read the header - FileEntrySaveData *fesdHeaderPosition = (FileEntrySaveData *)headerPosition; - for(unsigned int i = 0; i < headerSize; ++i) - { - FileEntry *entry = new FileEntry(); - //assert(numberOfBytesRead == sizeof(FileEntrySaveData)); - -#ifdef __PSVITA__ - VirtualCopyFrom( &entry->data, fesdHeaderPosition, sizeof(FileEntrySaveData) ); -#else - memcpy( &entry->data, fesdHeaderPosition, sizeof(FileEntrySaveData) ); -#endif - - if(isSaveEndianDifferent()) - { - // Reverse bytes - // System::ReverseWCHARA(entry->data.filename,64); - System::ReverseULONG(&entry->data.length); - System::ReverseULONG(&entry->data.startOffset); - System::ReverseULONGLONG(&entry->data.lastModifiedTime); - } - - - entry->currentFilePointer = entry->data.startOffset; - lastFile = entry; - fileTable.push_back( entry ); -#ifdef _DEBUG_FILE_HEADER - app.DebugPrintf("File: %ls, Start = %d, Length = %d, End = %d, Timestamp = %lld\n", entry->data.filename, entry->data.startOffset, entry->data.length, entry->data.startOffset + entry->data.length, entry->data.lastModifiedTime); -#endif - - fesdHeaderPosition++; - } - } - break; - - // Legacy save versions, with updated code to convert the FileEntrySaveData to the latest version - // 4J Stu - At time of writing, the tutorial save is V1 so need to keep this for compatibility - case SAVE_FILE_VERSION_PRE_LAUNCH: - { - // Read the header - // We can then make headerPosition a FileEntrySaveData pointer and just increment by one up to the number - unsigned int i = 0; - while( i < headerSize ) - { - FileEntry *entry = new FileEntry(); - //assert(numberOfBytesRead == sizeof(FileEntrySaveData)); + // Read the header + FileEntrySaveData* fesdHeaderPosition = + (FileEntrySaveData*)headerPosition; + for (unsigned int i = 0; i < headerSize; ++i) { + FileEntry* entry = new FileEntry(); + // assert(numberOfBytesRead == sizeof(FileEntrySaveData)); #ifdef __PSVITA__ - VirtualCopyFrom( &entry->data, headerPosition, sizeof(FileEntrySaveDataV1) ); + VirtualCopyFrom(&entry->data, fesdHeaderPosition, + sizeof(FileEntrySaveData)); #else - memcpy( &entry->data, headerPosition, sizeof(FileEntrySaveDataV1) ); + memcpy(&entry->data, fesdHeaderPosition, + sizeof(FileEntrySaveData)); #endif - entry->currentFilePointer = entry->data.startOffset; - lastFile = entry; - fileTable.push_back( entry ); + if (isSaveEndianDifferent()) { + // Reverse bytes + // System::ReverseWCHARA(entry->data.filename,64); + System::ReverseULONG(&entry->data.length); + System::ReverseULONG(&entry->data.startOffset); + System::ReverseULONGLONG(&entry->data.lastModifiedTime); + } + + entry->currentFilePointer = entry->data.startOffset; + lastFile = entry; + fileTable.push_back(entry); #ifdef _DEBUG_FILE_HEADER - app.DebugPrintf("File: %ls, Start = %d, Length = %d, End = %d\n", entry->data.filename, entry->data.startOffset, entry->data.length, entry->data.startOffset + entry->data.length); + app.DebugPrintf( + "File: %ls, Start = %d, Length = %d, End = %d, Timestamp = " + "%lld\n", + entry->data.filename, entry->data.startOffset, + entry->data.length, + entry->data.startOffset + entry->data.length, + entry->data.lastModifiedTime); #endif - i += sizeof(FileEntrySaveDataV1); - headerPosition += sizeof(FileEntrySaveDataV1); - } - } - break; - default: + fesdHeaderPosition++; + } + } break; + + // Legacy save versions, with updated code to convert the + // FileEntrySaveData to the latest version 4J Stu - At time of writing, + // the tutorial save is V1 so need to keep this for compatibility + case SAVE_FILE_VERSION_PRE_LAUNCH: { + // Read the header + // We can then make headerPosition a FileEntrySaveData pointer and + // just increment by one up to the number + unsigned int i = 0; + while (i < headerSize) { + FileEntry* entry = new FileEntry(); + // assert(numberOfBytesRead == sizeof(FileEntrySaveData)); + +#ifdef __PSVITA__ + VirtualCopyFrom(&entry->data, headerPosition, + sizeof(FileEntrySaveDataV1)); +#else + memcpy(&entry->data, headerPosition, + sizeof(FileEntrySaveDataV1)); +#endif + + entry->currentFilePointer = entry->data.startOffset; + lastFile = entry; + fileTable.push_back(entry); +#ifdef _DEBUG_FILE_HEADER + app.DebugPrintf( + "File: %ls, Start = %d, Length = %d, End = %d\n", + entry->data.filename, entry->data.startOffset, + entry->data.length, + entry->data.startOffset + entry->data.length); +#endif + + i += sizeof(FileEntrySaveDataV1); + headerPosition += sizeof(FileEntrySaveDataV1); + } + } break; + default: #ifndef _CONTENT_PACKAGE - app.DebugPrintf("********** Invalid save version %d\n",m_saveVersion); - __debugbreak(); + app.DebugPrintf("********** Invalid save version %d\n", + m_saveVersion); + __debugbreak(); #endif - break; - } + break; + } } -unsigned int FileHeader::GetStartOfNextData() -{ - // The first 4 bytes is the location of the header (the header itself is at the end of the file) - // Then 4 bytes for the size of the header - // Then 2 bytes for the version number at which this save was first generated - // Then 2 bytes for the version number that the save should now be at - unsigned int totalBytesSoFar = SAVE_FILE_HEADER_SIZE; - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - if( fileTable[i]->getFileSize() > 0 ) - totalBytesSoFar += fileTable[i]->getFileSize(); - } - return totalBytesSoFar; +unsigned int FileHeader::GetStartOfNextData() { + // The first 4 bytes is the location of the header (the header itself is at + // the end of the file) Then 4 bytes for the size of the header Then 2 bytes + // for the version number at which this save was first generated Then 2 + // bytes for the version number that the save should now be at + unsigned int totalBytesSoFar = SAVE_FILE_HEADER_SIZE; + for (unsigned int i = 0; i < fileTable.size(); ++i) { + if (fileTable[i]->getFileSize() > 0) + totalBytesSoFar += fileTable[i]->getFileSize(); + } + return totalBytesSoFar; } -unsigned int FileHeader::GetFileSize() -{ - return GetStartOfNextData() + ( sizeof(FileEntrySaveData) * (unsigned int)fileTable.size() ); +unsigned int FileHeader::GetFileSize() { + return GetStartOfNextData() + + (sizeof(FileEntrySaveData) * (unsigned int)fileTable.size()); } -void FileHeader::AdjustStartOffsets(FileEntry *file, unsigned int nNumberOfBytesToWrite, bool subtract /*= false*/) -{ - bool found = false; - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - if( found == true ) - { - if(subtract) - { - fileTable[i]->data.startOffset -= nNumberOfBytesToWrite; - fileTable[i]->currentFilePointer -= nNumberOfBytesToWrite; - } - else - { - fileTable[i]->data.startOffset += nNumberOfBytesToWrite; - fileTable[i]->currentFilePointer += nNumberOfBytesToWrite; - } - } - else if( fileTable[i] == file ) - { - found = true; - } - } +void FileHeader::AdjustStartOffsets(FileEntry* file, + unsigned int nNumberOfBytesToWrite, + bool subtract /*= false*/) { + bool found = false; + for (unsigned int i = 0; i < fileTable.size(); ++i) { + if (found == true) { + if (subtract) { + fileTable[i]->data.startOffset -= nNumberOfBytesToWrite; + fileTable[i]->currentFilePointer -= nNumberOfBytesToWrite; + } else { + fileTable[i]->data.startOffset += nNumberOfBytesToWrite; + fileTable[i]->currentFilePointer += nNumberOfBytesToWrite; + } + } else if (fileTable[i] == file) { + found = true; + } + } } -bool FileHeader::fileExists( const std::wstring &name ) -{ - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - if( wcscmp( fileTable[i]->data.filename, name.c_str() ) == 0 ) - { - // If so, return it - return true; - } - } - return false; +bool FileHeader::fileExists(const std::wstring& name) { + for (unsigned int i = 0; i < fileTable.size(); ++i) { + if (wcscmp(fileTable[i]->data.filename, name.c_str()) == 0) { + // If so, return it + return true; + } + } + return false; } -std::vector *FileHeader::getFilesWithPrefix(const std::wstring &prefix) -{ - std::vector *files = NULL; +std::vector* FileHeader::getFilesWithPrefix( + const std::wstring& prefix) { + std::vector* files = NULL; - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - if( wcsncmp( fileTable[i]->data.filename, prefix.c_str(), prefix.size() ) == 0 ) - { - if( files == NULL ) - { - files = new std::vector(); - } + for (unsigned int i = 0; i < fileTable.size(); ++i) { + if (wcsncmp(fileTable[i]->data.filename, prefix.c_str(), + prefix.size()) == 0) { + if (files == NULL) { + files = new std::vector(); + } - files->push_back(fileTable[i]); - } - } + files->push_back(fileTable[i]); + } + } - return files; + return files; } #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) -static bool isHexChar(wchar_t wc) -{ - if(wc >= L'0' && wc <= L'9') - return true; - if(wc >= L'a' && wc <= L'f') - return true; - return false; +static bool isHexChar(wchar_t wc) { + if (wc >= L'0' && wc <= L'9') return true; + if (wc >= L'a' && wc <= L'f') return true; + return false; } -static bool isHexString(wchar_t* ws, int size) -{ - for(int i=0;i= L'0' && wc <= L'9') - return true; - return false; +static bool isDecimalChar(wchar_t wc) { + if (wc >= L'0' && wc <= L'9') return true; + return false; } -static bool isDecimalString(wchar_t* ws, int size) -{ - for(int i=0;i* pFiles = getDatFilesWithOnlineID(pUID); - if(!pFiles) - { - // we didn't find a matching online dat file, so look for an offline version - pFiles = getDatFilesWithMacAndUserID(pUID); - } - if(!pFiles) - { - // and we didn't find an offline file, so check if we're the primary user, and grab the primary file if we are - if(pUID.isPrimaryUser()) - { - pFiles= getDatFilesWithPrimaryUser(); - } - } - if(pFiles) - { - // we've got something to load -// assert(pFiles->size() == 1); - retVal = pFiles->at(0)->data.filename; - delete pFiles; - } - return retVal; +std::wstring FileHeader::getPlayerDataFilenameForLoad(const PlayerUID& pUID) { + std::wstring retVal = L""; + std::vector* pFiles = getDatFilesWithOnlineID(pUID); + if (!pFiles) { + // we didn't find a matching online dat file, so look for an offline + // version + pFiles = getDatFilesWithMacAndUserID(pUID); + } + if (!pFiles) { + // and we didn't find an offline file, so check if we're the primary + // user, and grab the primary file if we are + if (pUID.isPrimaryUser()) { + pFiles = getDatFilesWithPrimaryUser(); + } + } + if (pFiles) { + // we've got something to load + // assert(pFiles->size() == 1); + retVal = pFiles->at(0)->data.filename; + delete pFiles; + } + return retVal; } -std::wstring FileHeader::getPlayerDataFilenameForSave(const PlayerUID& pUID) -{ - // check if we're online first - if(pUID.isSignedIntoPSN() == false) - { - // OK, we're not online, see if we can find another data file with matching mac and userID - std::vector* pFiles = getDatFilesWithMacAndUserID(pUID); - if(pFiles) - { - // we've found a previous save, use the filename from it, as it might have the online part too -// assert(pFiles->size() == 1); - std::wstring retVal = pFiles->at(0)->data.filename; - delete pFiles; - return retVal; - } - } +std::wstring FileHeader::getPlayerDataFilenameForSave(const PlayerUID& pUID) { + // check if we're online first + if (pUID.isSignedIntoPSN() == false) { + // OK, we're not online, see if we can find another data file with + // matching mac and userID + std::vector* pFiles = getDatFilesWithMacAndUserID(pUID); + if (pFiles) { + // we've found a previous save, use the filename from it, as it + // might have the online part too + // assert(pFiles->size() == 1); + std::wstring retVal = pFiles->at(0)->data.filename; + delete pFiles; + return retVal; + } + } - // we're either online, or we can't find a previous save, so use the standard filename - std::wstring retVal = pUID.toString() + L".dat"; - return retVal; + // we're either online, or we can't find a previous save, so use the + // standard filename + std::wstring retVal = pUID.toString() + L".dat"; + return retVal; } +std::vector* FileHeader::getValidPlayerDatFiles() { + std::vector* files = NULL; -std::vector *FileHeader::getValidPlayerDatFiles() -{ - std::vector *files = NULL; + // find filenames that match this pattern + // P_5e7ff8372ea9_00000004_Mark_4J - // find filenames that match this pattern - // P_5e7ff8372ea9_00000004_Mark_4J + for (unsigned int i = 0; i < fileTable.size(); ++i) { + wchar_t* filenameOnly = findFilenameStart(fileTable[i]->data.filename); - for( unsigned int i = 0; i < fileTable.size(); ++i ) - { - wchar_t* filenameOnly = findFilenameStart(fileTable[i]->data.filename); + int nameLen = wcslen(filenameOnly); + if (nameLen <= 4) continue; - int nameLen = wcslen(filenameOnly); - if(nameLen <= 4) - continue; + // make sure it's a ".dat" file + if (wcsncmp(&filenameOnly[nameLen - 4], L".dat", 4) != 0) continue; + // make sure we start with "P_" or "N_" + if ((wcsncmp(&filenameOnly[0], L"P_", 2) != 0) && + (wcsncmp(&filenameOnly[0], L"N_", 2) != 0)) + continue; + // check the next 12 chars are hex + if (!isHexString(&filenameOnly[2], 12)) continue; + // make sure character 14 is '_' + if (filenameOnly[14] != L'_') continue; + // check the next 8 chars are decimal + if (!isDecimalString(&filenameOnly[15], 8)) continue; - // make sure it's a ".dat" file - if( wcsncmp( &filenameOnly[nameLen-4], L".dat", 4 ) != 0 ) - continue; - // make sure we start with "P_" or "N_" - if( ( wcsncmp(&filenameOnly[0], L"P_", 2) != 0 ) && ( wcsncmp( &filenameOnly[0], L"N_", 2 ) != 0 ) ) - continue; - //check the next 12 chars are hex - if(!isHexString(&filenameOnly[2], 12)) - continue; - // make sure character 14 is '_' - if(filenameOnly[14] != L'_') - continue; - //check the next 8 chars are decimal - if(!isDecimalString(&filenameOnly[15], 8)) - continue; + // if we get here, it must be a valid filename + if (files == NULL) { + files = new std::vector(); + } + files->push_back(fileTable[i]); + } - // if we get here, it must be a valid filename - if( files == NULL ) - { - files = new std::vector(); - } - files->push_back(fileTable[i]); - } - - return files; + return files; } +std::vector* FileHeader::getDatFilesWithOnlineID( + const PlayerUID& pUID) { + if (pUID.isSignedIntoPSN() == false) return NULL; + std::vector* datFiles = getValidPlayerDatFiles(); + if (datFiles == NULL) return NULL; -std::vector *FileHeader::getDatFilesWithOnlineID(const PlayerUID& pUID) -{ - if(pUID.isSignedIntoPSN() == false) - return NULL; + // we're looking for the online name from the pUID in these types of + // filenames - P_5e7ff8372ea9_00000004_Mark_4J + wchar_t onlineIDW[64]; + mbstowcs(onlineIDW, pUID.getOnlineID(), 64); - std::vector* datFiles = getValidPlayerDatFiles(); - if(datFiles == NULL) - return NULL; + std::vector* files = NULL; + int onlineIDSize = wcslen(onlineIDW); + if (onlineIDSize == 0) return NULL; - // we're looking for the online name from the pUID in these types of filenames - - // P_5e7ff8372ea9_00000004_Mark_4J - wchar_t onlineIDW[64]; - mbstowcs(onlineIDW, pUID.getOnlineID(), 64); - - std::vector *files = NULL; - int onlineIDSize = wcslen(onlineIDW); - if(onlineIDSize == 0) - return NULL; - - wcscat(onlineIDW, L".dat"); + wcscat(onlineIDW, L".dat"); #ifdef __ORBIS__ - onlineIDSize = wcslen(onlineIDW); + onlineIDSize = wcslen(onlineIDW); #else - static const int onlineIDStart = 24; // 24 characters into the filename + static const int onlineIDStart = 24; // 24 characters into the filename #endif - char tempStr[128]; - for( unsigned int i = 0; i < datFiles->size(); ++i ) - { - wchar_t* filenameOnly = findFilenameStart(datFiles->at(i)->data.filename); - wcstombs(tempStr,filenameOnly, 128); - app.DebugPrintf("file : %s\n", tempStr); + char tempStr[128]; + for (unsigned int i = 0; i < datFiles->size(); ++i) { + wchar_t* filenameOnly = + findFilenameStart(datFiles->at(i)->data.filename); + wcstombs(tempStr, filenameOnly, 128); + app.DebugPrintf("file : %s\n", tempStr); #ifdef __ORBIS__ - int onlineIDStart = wcslen(filenameOnly) - onlineIDSize; - if(onlineIDStart > 0) + int onlineIDStart = wcslen(filenameOnly) - onlineIDSize; + if (onlineIDStart > 0) #else - if(wcslen(filenameOnly) > onlineIDStart) + if (wcslen(filenameOnly) > onlineIDStart) #endif - { - if(wcsncmp(&filenameOnly[onlineIDStart], onlineIDW, onlineIDSize) == 0) - { - if( files == NULL ) - { - files = new std::vector(); - } - files->push_back(datFiles->at(i)); - } - } - } - delete datFiles; + { + if (wcsncmp(&filenameOnly[onlineIDStart], onlineIDW, + onlineIDSize) == 0) { + if (files == NULL) { + files = new std::vector(); + } + files->push_back(datFiles->at(i)); + } + } + } + delete datFiles; - if(files) sort(files->begin(), files->end(), FileEntry::newestFirst ); - return files; + if (files) sort(files->begin(), files->end(), FileEntry::newestFirst); + return files; } -std::vector *FileHeader::getDatFilesWithMacAndUserID(const PlayerUID& pUID) -{ +std::vector* FileHeader::getDatFilesWithMacAndUserID( + const PlayerUID& pUID) { + std::vector* datFiles = getValidPlayerDatFiles(); + if (datFiles == NULL) return NULL; - std::vector* datFiles = getValidPlayerDatFiles(); - if(datFiles == NULL) - return NULL; + // we're looking for the mac address and userIDfrom the pUID in these types + // of filenames - P_5e7ff8372ea9_00000004_Mark_4J + std::wstring macStr = pUID.macAddressStr(); + std::wstring userStr = pUID.userIDStr(); + const wchar_t* pMacStr = macStr.c_str(); + const wchar_t* pUserStr = userStr.c_str(); - // we're looking for the mac address and userIDfrom the pUID in these types of filenames - - // P_5e7ff8372ea9_00000004_Mark_4J - std::wstring macStr = pUID.macAddressStr(); - std::wstring userStr = pUID.userIDStr(); - const wchar_t* pMacStr = macStr.c_str(); - const wchar_t* pUserStr = userStr.c_str(); + std::vector* files = NULL; + static const int macAddrStart = 2; // 2 characters into the filename + static const int userIDStart = 15; // 15 characters into the filename - std::vector *files = NULL; - static const int macAddrStart = 2; // 2 characters into the filename - static const int userIDStart = 15; // 15 characters into the filename + char tempStr[128]; + for (unsigned int i = 0; i < datFiles->size(); ++i) { + wchar_t* filenameOnly = + findFilenameStart(datFiles->at(i)->data.filename); + wcstombs(tempStr, filenameOnly, 128); + app.DebugPrintf("file : %s\n", tempStr); - char tempStr[128]; - for( unsigned int i = 0; i < datFiles->size(); ++i ) - { - wchar_t* filenameOnly = findFilenameStart(datFiles->at(i)->data.filename); - wcstombs(tempStr,filenameOnly, 128); - app.DebugPrintf("file : %s\n", tempStr); - - // check the mac address matches - if(wcsncmp(&filenameOnly[macAddrStart], pMacStr, macStr.size()) == 0) - { - // check the userID matches - if(wcsncmp(&filenameOnly[userIDStart], pUserStr, userStr.size()) == 0) - { - if( files == NULL ) - { - files = new std::vector(); - } - files->push_back(datFiles->at(i)); - } - } - } - delete datFiles; - if(files) sort(files->begin(), files->end(), FileEntry::newestFirst ); - return files; + // check the mac address matches + if (wcsncmp(&filenameOnly[macAddrStart], pMacStr, macStr.size()) == 0) { + // check the userID matches + if (wcsncmp(&filenameOnly[userIDStart], pUserStr, userStr.size()) == + 0) { + if (files == NULL) { + files = new std::vector(); + } + files->push_back(datFiles->at(i)); + } + } + } + delete datFiles; + if (files) sort(files->begin(), files->end(), FileEntry::newestFirst); + return files; } +std::vector* FileHeader::getDatFilesWithPrimaryUser() { + std::vector* datFiles = getValidPlayerDatFiles(); + if (datFiles == NULL) return NULL; -std::vector *FileHeader::getDatFilesWithPrimaryUser() -{ + // we're just looking for filenames starting with "P_" in these types of + // filenames - P_5e7ff8372ea9_00000004_Mark_4J + std::vector* files = NULL; - std::vector* datFiles = getValidPlayerDatFiles(); - if(datFiles == NULL) - return NULL; + char tempStr[128]; + for (unsigned int i = 0; i < datFiles->size(); ++i) { + wchar_t* filenameOnly = + findFilenameStart(datFiles->at(i)->data.filename); + wcstombs(tempStr, filenameOnly, 128); + app.DebugPrintf("file : %s\n", tempStr); - // we're just looking for filenames starting with "P_" in these types of filenames - - // P_5e7ff8372ea9_00000004_Mark_4J - std::vector *files = NULL; - - char tempStr[128]; - for( unsigned int i = 0; i < datFiles->size(); ++i ) - { - wchar_t* filenameOnly = findFilenameStart(datFiles->at(i)->data.filename); - wcstombs(tempStr,filenameOnly, 128); - app.DebugPrintf("file : %s\n", tempStr); - - // check for "P_" prefix - if(wcsncmp(&filenameOnly[0], L"P_", 2) == 0) - { - if( files == NULL ) - { - files = new std::vector(); - } - files->push_back(datFiles->at(i)); - } - } - delete datFiles; - if(files) sort(files->begin(), files->end(), FileEntry::newestFirst ); - return files; + // check for "P_" prefix + if (wcsncmp(&filenameOnly[0], L"P_", 2) == 0) { + if (files == NULL) { + files = new std::vector(); + } + files->push_back(datFiles->at(i)); + } + } + delete datFiles; + if (files) sort(files->begin(), files->end(), FileEntry::newestFirst); + return files; } -#endif // __PS3__ || __ORBIS__ +#endif // __PS3__ || __ORBIS__ -ByteOrder FileHeader::getEndian( ESavePlatform plat ) -{ - ByteOrder platEndian; - switch(plat) - { - case SAVE_FILE_PLATFORM_X360: - case SAVE_FILE_PLATFORM_PS3: - return BIGENDIAN; - break; +ByteOrder FileHeader::getEndian(ESavePlatform plat) { + ByteOrder platEndian; + switch (plat) { + case SAVE_FILE_PLATFORM_X360: + case SAVE_FILE_PLATFORM_PS3: + return BIGENDIAN; + break; - case SAVE_FILE_PLATFORM_NONE: - case SAVE_FILE_PLATFORM_XBONE: - case SAVE_FILE_PLATFORM_PS4: - case SAVE_FILE_PLATFORM_PSVITA: - case SAVE_FILE_PLATFORM_WIN64: - return LITTLEENDIAN; - break; - default: - assert(0); - break; - } - return LITTLEENDIAN; + case SAVE_FILE_PLATFORM_NONE: + case SAVE_FILE_PLATFORM_XBONE: + case SAVE_FILE_PLATFORM_PS4: + case SAVE_FILE_PLATFORM_PSVITA: + case SAVE_FILE_PLATFORM_WIN64: + return LITTLEENDIAN; + break; + default: + assert(0); + break; + } + return LITTLEENDIAN; } diff --git a/Minecraft.World/IO/Files/FileHeader.h b/Minecraft.World/IO/Files/FileHeader.h index e7e8c1e4d..9f5da6c04 100644 --- a/Minecraft.World/IO/Files/FileHeader.h +++ b/Minecraft.World/IO/Files/FileHeader.h @@ -1,206 +1,222 @@ #pragma once - #include "../../Platform/System.h" -// The first 4 bytes is the location of the header (the header itself is at the end of the file) -// Then 4 bytes for the size of the header -// Then 2 bytes for the version number at which this save was first generated -// Then 2 bytes for the version number that the save should now be at -// ( the rest of the header is actually a footer ) +// The first 4 bytes is the location of the header (the header itself is at the +// end of the file) Then 4 bytes for the size of the header Then 2 bytes for the +// version number at which this save was first generated Then 2 bytes for the +// version number that the save should now be at ( the rest of the header is +// actually a footer ) #define SAVE_FILE_HEADER_SIZE 12 -enum ESaveVersions -{ - // Pre-release version - SAVE_FILE_VERSION_PRE_LAUNCH = 1, +enum ESaveVersions { + // Pre-release version + SAVE_FILE_VERSION_PRE_LAUNCH = 1, - // This is the version at which we launched the Xbox360 version - SAVE_FILE_VERSION_LAUNCH = 2, + // This is the version at which we launched the Xbox360 version + SAVE_FILE_VERSION_LAUNCH = 2, - // This is the version at which we had made changes that broke older saves - SAVE_FILE_VERSION_POST_LAUNCH = 3, + // This is the version at which we had made changes that broke older saves + SAVE_FILE_VERSION_POST_LAUNCH = 3, - // This is the version at which we introduced the End, and any saves older than this will have their End data deleted - SAVE_FILE_VERSION_NEW_END = 4, + // This is the version at which we introduced the End, and any saves older + // than this will have their End data deleted + SAVE_FILE_VERSION_NEW_END = 4, - // This is the version at which we change the stronghold generation, and any saves older than this should should the original version - SAVE_FILE_VERSION_MOVED_STRONGHOLD = 5, + // This is the version at which we change the stronghold generation, and any + // saves older than this should should the original version + SAVE_FILE_VERSION_MOVED_STRONGHOLD = 5, - // This is the version at which we changed the playeruid format for PS3 - SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE = 6, + // This is the version at which we changed the playeruid format for PS3 + SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE = 6, - // This is the version at which we changed the playeruid format for Xbox One - SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE = 7, + // This is the version at which we changed the playeruid format for Xbox One + SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE = 7, - // This is the version at which we changed the chunk format to directly save the compressed storage formats - SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE, + // This is the version at which we changed the chunk format to directly save + // the compressed storage formats + SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE, - SAVE_FILE_VERSION_NEXT, + SAVE_FILE_VERSION_NEXT, }; // This is the version at which we changed the playeruid format for Xbox One #define SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE 7 -enum ESavePlatform -{ - SAVE_FILE_PLATFORM_NONE = MAKE_FOURCC('N', 'O', 'N', 'E') , - SAVE_FILE_PLATFORM_X360 = MAKE_FOURCC('X', '3', '6', '0') , - SAVE_FILE_PLATFORM_XBONE = MAKE_FOURCC('X', 'B', '1', '_') , - SAVE_FILE_PLATFORM_PS3 = MAKE_FOURCC('P', 'S', '3', '_') , - SAVE_FILE_PLATFORM_PS4 = MAKE_FOURCC('P', 'S', '4', '_') , - SAVE_FILE_PLATFORM_PSVITA = MAKE_FOURCC('P', 'S', 'V', '_') , - SAVE_FILE_PLATFORM_WIN64 = MAKE_FOURCC('W', 'I', 'N', '_') , +enum ESavePlatform { + SAVE_FILE_PLATFORM_NONE = MAKE_FOURCC('N', 'O', 'N', 'E'), + SAVE_FILE_PLATFORM_X360 = MAKE_FOURCC('X', '3', '6', '0'), + SAVE_FILE_PLATFORM_XBONE = MAKE_FOURCC('X', 'B', '1', '_'), + SAVE_FILE_PLATFORM_PS3 = MAKE_FOURCC('P', 'S', '3', '_'), + SAVE_FILE_PLATFORM_PS4 = MAKE_FOURCC('P', 'S', '4', '_'), + SAVE_FILE_PLATFORM_PSVITA = MAKE_FOURCC('P', 'S', 'V', '_'), + SAVE_FILE_PLATFORM_WIN64 = MAKE_FOURCC('W', 'I', 'N', '_'), #if defined _XBOX - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_X360 + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_X360 #elif defined _DURANGO - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_XBONE + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_XBONE #elif defined __PS3__ - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PS3 + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PS3 #elif defined __ORBIS__ - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PS4 + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PS4 #elif defined __PSVITA__ - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PSVITA + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_PSVITA #elif defined _WINDOWS64 - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_WIN64 + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_WIN64 #else - // DecalOverdose(HACK + TODO) - SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_WIN64 + // DecalOverdose(HACK + TODO) + SAVE_FILE_PLATFORM_LOCAL = SAVE_FILE_PLATFORM_WIN64 #endif }; #define SAVE_FILE_VERSION_NUMBER (SAVE_FILE_VERSION_NEXT - 1) -struct FileEntrySaveDataV1 -{ +struct FileEntrySaveDataV1 { public: - wchar_t filename[64]; // 64 * 2B - unsigned int length; // In bytes // 4B + wchar_t filename[64]; // 64 * 2B + unsigned int length; // In bytes // 4B - // This is only valid once the save file has been written/loaded at least once - unsigned int startOffset; // 4B + // This is only valid once the save file has been written/loaded at least + // once + unsigned int startOffset; // 4B }; -// It's important that we keep the order and size of the data here to smooth updating -// 4J Stu - As of writing the tutorial level uses a V1 save file -struct FileEntrySaveDataV2 -{ +// It's important that we keep the order and size of the data here to smooth +// updating 4J Stu - As of writing the tutorial level uses a V1 save file +struct FileEntrySaveDataV2 { public: - wchar_t filename[64]; // 64 * 2B - unsigned int length; // In bytes // 4B + wchar_t filename[64]; // 64 * 2B + unsigned int length; // In bytes // 4B - union - { - // This is only valid once the save file has been written/loaded at least once - unsigned int startOffset; // 4B - // For region files stored via ConsolveSaveFileSplit, these aren't stored within the normal save file, identified by not having a name (filename[0] is 0). - // Note: These won't be read or written as part of a file header, and should only exist wrapped up in a FileEntry class - unsigned int regionIndex; // 4B + union { + // This is only valid once the save file has been written/loaded at + // least once + unsigned int startOffset; // 4B + // For region files stored via ConsolveSaveFileSplit, these aren't + // stored within the normal save file, identified by not having a name + // (filename[0] is 0). Note: These won't be read or written as part of a + // file header, and should only exist wrapped up in a FileEntry class + unsigned int regionIndex; // 4B + }; - }; - - __int64 lastModifiedTime; // 8B + __int64 lastModifiedTime; // 8B }; typedef FileEntrySaveDataV2 FileEntrySaveData; -class FileEntry -{ +class FileEntry { public: - FileEntrySaveData data; + FileEntrySaveData data; - unsigned int currentFilePointer; + unsigned int currentFilePointer; - FileEntry() { ZeroMemory(&data, sizeof(FileEntrySaveData)); } + FileEntry() { ZeroMemory(&data, sizeof(FileEntrySaveData)); } - FileEntry( wchar_t name[64], unsigned int length, unsigned int startOffset ) - { - data.length = length; - data.startOffset = startOffset; - memset( &data.filename, 0, sizeof( wchar_t ) * 64 ); - memcpy( &data.filename, name, sizeof( wchar_t ) * 64 ); + FileEntry(wchar_t name[64], unsigned int length, unsigned int startOffset) { + data.length = length; + data.startOffset = startOffset; + memset(&data.filename, 0, sizeof(wchar_t) * 64); + memcpy(&data.filename, name, sizeof(wchar_t) * 64); - data.lastModifiedTime = 0; + data.lastModifiedTime = 0; - currentFilePointer = data.startOffset; - } + currentFilePointer = data.startOffset; + } - unsigned int getFileSize() { return data.length; } - bool isRegionFile() { return data.filename[0] == 0; } // When using ConsoleSaveFileSplit only - unsigned int getRegionFileIndex() { return data.regionIndex; } // When using ConsoleSaveFileSplit only + unsigned int getFileSize() { return data.length; } + bool isRegionFile() { + return data.filename[0] == 0; + } // When using ConsoleSaveFileSplit only + unsigned int getRegionFileIndex() { + return data.regionIndex; + } // When using ConsoleSaveFileSplit only - void updateLastModifiedTime() { data.lastModifiedTime = System::currentRealTimeMillis(); } + void updateLastModifiedTime() { + data.lastModifiedTime = System::currentRealTimeMillis(); + } - /* - Comparison function object that returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise. - Used in a call to std::sort in DirectoryLevelStorage.cpp - */ - static bool newestFirst( FileEntry *a, FileEntry *b ) { return a->data.lastModifiedTime > b->data.lastModifiedTime; } + /* + Comparison function object that returns true if the first argument goes + before the second argument in the specific strict weak ordering it defines, + and false otherwise. Used in a call to std::sort in + DirectoryLevelStorage.cpp + */ + static bool newestFirst(FileEntry* a, FileEntry* b) { + return a->data.lastModifiedTime > b->data.lastModifiedTime; + } }; // A class the represents the header of the save file -class FileHeader -{ - friend class ConsoleSaveFileOriginal; - friend class ConsoleSaveFileSplit; +class FileHeader { + friend class ConsoleSaveFileOriginal; + friend class ConsoleSaveFileSplit; + private: - std::vector fileTable; - ESavePlatform m_savePlatform; - ByteOrder m_saveEndian; + std::vector fileTable; + ESavePlatform m_savePlatform; + ByteOrder m_saveEndian; #if defined(__PS3__) || defined(_XBOX) - static const ByteOrder m_localEndian = BIGENDIAN; + static const ByteOrder m_localEndian = BIGENDIAN; #else - static const ByteOrder m_localEndian = LITTLEENDIAN; + static const ByteOrder m_localEndian = LITTLEENDIAN; #endif - short m_saveVersion; - short m_originalSaveVersion; + short m_saveVersion; + short m_originalSaveVersion; public: - FileEntry *lastFile; + FileEntry* lastFile; public: - FileHeader(); - ~FileHeader(); + FileHeader(); + ~FileHeader(); protected: - FileEntry *AddFile( const std::wstring &name, unsigned int length = 0 ); - void RemoveFile( FileEntry * ); - void WriteHeader(void *saveMem); - void ReadHeader(void *saveMem, ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); + FileEntry* AddFile(const std::wstring& name, unsigned int length = 0); + void RemoveFile(FileEntry*); + void WriteHeader(void* saveMem); + void ReadHeader(void* saveMem, + ESavePlatform plat = SAVE_FILE_PLATFORM_LOCAL); - unsigned int GetStartOfNextData(); + unsigned int GetStartOfNextData(); - unsigned int GetFileSize(); + unsigned int GetFileSize(); - void AdjustStartOffsets(FileEntry *file, unsigned int nNumberOfBytesToWrite, bool subtract = false); + void AdjustStartOffsets(FileEntry* file, unsigned int nNumberOfBytesToWrite, + bool subtract = false); - bool fileExists( const std::wstring &name ); + bool fileExists(const std::wstring& name); - std::vector *getFilesWithPrefix(const std::wstring &prefix); + std::vector* getFilesWithPrefix(const std::wstring& prefix); - std::vector *getValidPlayerDatFiles(); + std::vector* getValidPlayerDatFiles(); #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); - std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); - std::vector *getDatFilesWithOnlineID(const PlayerUID& pUID); - std::vector *getDatFilesWithMacAndUserID(const PlayerUID& pUID); - std::vector *getDatFilesWithPrimaryUser(); + std::wstring getPlayerDataFilenameForLoad(const PlayerUID& pUID); + std::wstring getPlayerDataFilenameForSave(const PlayerUID& pUID); + std::vector* getDatFilesWithOnlineID(const PlayerUID& pUID); + std::vector* getDatFilesWithMacAndUserID(const PlayerUID& pUID); + std::vector* getDatFilesWithPrimaryUser(); #endif - - void setSaveVersion(int version) { m_saveVersion = version; } - int getSaveVersion() { return m_saveVersion; } - void setOriginalSaveVersion(int version) { m_originalSaveVersion = version; } - int getOriginalSaveVersion() { return m_originalSaveVersion; } - ESavePlatform getSavePlatform() { return m_savePlatform; } - void setPlatform(ESavePlatform plat) { m_savePlatform = plat; } - bool isSaveEndianDifferent() { return m_saveEndian != m_localEndian; } - void setLocalPlatform() { m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; m_saveEndian = m_localEndian; } - ByteOrder getSaveEndian() { return m_saveEndian; } - static ByteOrder getLocalEndian() { return m_localEndian; } - void setEndian(ByteOrder endian) { m_saveEndian = endian; } - static ByteOrder getEndian(ESavePlatform plat); - bool isLocalEndianDifferent(ESavePlatform plat){return m_localEndian != getEndian(plat); } - + + void setSaveVersion(int version) { m_saveVersion = version; } + int getSaveVersion() { return m_saveVersion; } + void setOriginalSaveVersion(int version) { + m_originalSaveVersion = version; + } + int getOriginalSaveVersion() { return m_originalSaveVersion; } + ESavePlatform getSavePlatform() { return m_savePlatform; } + void setPlatform(ESavePlatform plat) { m_savePlatform = plat; } + bool isSaveEndianDifferent() { return m_saveEndian != m_localEndian; } + void setLocalPlatform() { + m_savePlatform = SAVE_FILE_PLATFORM_LOCAL; + m_saveEndian = m_localEndian; + } + ByteOrder getSaveEndian() { return m_saveEndian; } + static ByteOrder getLocalEndian() { return m_localEndian; } + void setEndian(ByteOrder endian) { m_saveEndian = endian; } + static ByteOrder getEndian(ESavePlatform plat); + bool isLocalEndianDifferent(ESavePlatform plat) { + return m_localEndian != getEndian(plat); + } }; diff --git a/Minecraft.World/IO/Files/FileInputStream.cpp b/Minecraft.World/IO/Files/FileInputStream.cpp index f3abe198c..17ca54346 100644 --- a/Minecraft.World/IO/Files/FileInputStream.cpp +++ b/Minecraft.World/IO/Files/FileInputStream.cpp @@ -6,216 +6,191 @@ extern CConsoleMinecraftApp app; -namespace -{ - __int64 FileTell(std::FILE *file) - { +namespace { +__int64 FileTell(std::FILE* file) { #if defined(_WIN32) - return _ftelli64(file); + return _ftelli64(file); #else - return static_cast<__int64>(ftello(file)); + return static_cast<__int64>(ftello(file)); #endif - } - - bool FileSeek(std::FILE *file, __int64 offset, int origin) - { -#if defined(_WIN32) - return _fseeki64(file, offset, origin) == 0; -#else - return fseeko(file, static_cast(offset), origin) == 0; -#endif - } } -//Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. -//A new FileDescriptor object is created to represent this file connection. -//First, if there is a security manager, its checkRead method is called with the path represented by the file argument as its argument. +bool FileSeek(std::FILE* file, __int64 offset, int origin) { +#if defined(_WIN32) + return _fseeki64(file, offset, origin) == 0; +#else + return fseeko(file, static_cast(offset), origin) == 0; +#endif +} +} // namespace + +// Creates a FileInputStream by opening a connection to an actual file, the file +// named by the File object file in the file system. A new FileDescriptor object +// is created to represent this file connection. First, if there is a security +// manager, its checkRead method is called with the path represented by the file +// argument as its argument. // -//If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading -//then a FileNotFoundException is thrown. +// If the named file does not exist, is a directory rather than a regular file, +// or for some other reason cannot be opened for reading then a +// FileNotFoundException is thrown. // -//Parameters: -//file - the file to be opened for reading. -//Throws: -//FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be -//opened for reading. -//SecurityException - if a security manager exists and its checkRead method denies read access to the file. -FileInputStream::FileInputStream(const File &file) : m_fileHandle(NULL) -{ +// Parameters: +// file - the file to be opened for reading. +// Throws: +// FileNotFoundException - if the file does not exist, is a directory rather +// than a regular file, or for some other reason cannot be opened for reading. +// SecurityException - if a security manager exists and its checkRead method +// denies read access to the file. +FileInputStream::FileInputStream(const File& file) : m_fileHandle(NULL) { #if defined(_WIN32) - m_fileHandle = _wfopen(file.getPath().c_str(), L"rb"); + m_fileHandle = _wfopen(file.getPath().c_str(), L"rb"); #else - const std::string nativePath = wstringtofilename(file.getPath()); - m_fileHandle = std::fopen(nativePath.c_str(), "rb"); + const std::string nativePath = wstringtofilename(file.getPath()); + m_fileHandle = std::fopen(nativePath.c_str(), "rb"); #endif - if( m_fileHandle == NULL ) - { - // TODO 4J Stu - Any form of error/exception handling - //__debugbreak(); - app.FatalLoadError(); - } + if (m_fileHandle == NULL) { + // TODO 4J Stu - Any form of error/exception handling + //__debugbreak(); + app.FatalLoadError(); + } } -FileInputStream::~FileInputStream() -{ - if( m_fileHandle != NULL ) - { - std::fclose( m_fileHandle ); - } +FileInputStream::~FileInputStream() { + if (m_fileHandle != NULL) { + std::fclose(m_fileHandle); + } } -//Reads a byte of data from this input stream. This method blocks if no input is yet available. -//Returns: -//the next byte of data, or -1 if the end of the file is reached. -int FileInputStream::read() -{ - if( m_fileHandle == NULL ) - { - return -1; - } +// Reads a byte of data from this input stream. This method blocks if no input +// is yet available. Returns: the next byte of data, or -1 if the end of the +// file is reached. +int FileInputStream::read() { + if (m_fileHandle == NULL) { + return -1; + } - std::uint8_t byteRead = static_cast(0); - const size_t numberOfBytesRead = std::fread(&byteRead, 1, 1, m_fileHandle); + std::uint8_t byteRead = static_cast(0); + const size_t numberOfBytesRead = std::fread(&byteRead, 1, 1, m_fileHandle); - if( std::ferror(m_fileHandle) != 0 ) - { - // TODO 4J Stu - Some kind of error handling - app.FatalLoadError(); - //return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (std::ferror(m_fileHandle) != 0) { + // TODO 4J Stu - Some kind of error handling + app.FatalLoadError(); + // return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return static_cast(byteRead); + return static_cast(byteRead); } -//Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. -//Parameters: -//b - the buffer into which the data is read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. -int FileInputStream::read(byteArray b) -{ - if( m_fileHandle == NULL ) - { - return -1; - } +// Reads up to b.length bytes of data from this input stream into an array of +// bytes. This method blocks until some input is available. Parameters: b - the +// buffer into which the data is read. Returns: the total number of bytes read +// into the buffer, or -1 if there is no more data because the end of the file +// has been reached. +int FileInputStream::read(byteArray b) { + if (m_fileHandle == NULL) { + return -1; + } - const size_t numberOfBytesRead = std::fread(b.data, 1, b.length, m_fileHandle); + const size_t numberOfBytesRead = + std::fread(b.data, 1, b.length, m_fileHandle); - if( std::ferror(m_fileHandle) != 0 ) - { - // TODO 4J Stu - Some kind of error handling - app.FatalLoadError(); - //return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (std::ferror(m_fileHandle) != 0) { + // TODO 4J Stu - Some kind of error handling + app.FatalLoadError(); + // return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return numberOfBytesRead; + return numberOfBytesRead; } -//Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input -//is available; otherwise, no bytes are read and 0 is returned. -//Parameters: -//b - the buffer into which the data is read. -//off - the start offset in the destination array b -//len - the maximum number of bytes read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. -int FileInputStream::read(byteArray b, unsigned int offset, unsigned int length) -{ - // 4J Stu - We don't want to read any more than the array buffer can hold - assert( length <= ( b.length - offset ) ); +// Reads up to len bytes of data from this input stream into an array of bytes. +// If len is not zero, the method blocks until some input is available; +// otherwise, no bytes are read and 0 is returned. Parameters: b - the buffer +// into which the data is read. off - the start offset in the destination array +// b len - the maximum number of bytes read. Returns: the total number of bytes +// read into the buffer, or -1 if there is no more data because the end of the +// file has been reached. +int FileInputStream::read(byteArray b, unsigned int offset, + unsigned int length) { + // 4J Stu - We don't want to read any more than the array buffer can hold + assert(length <= (b.length - offset)); - if( m_fileHandle == NULL ) - { - return -1; - } + if (m_fileHandle == NULL) { + return -1; + } - const size_t numberOfBytesRead = std::fread(&b[offset], 1, length, m_fileHandle); + const size_t numberOfBytesRead = + std::fread(&b[offset], 1, length, m_fileHandle); - if( std::ferror(m_fileHandle) != 0 ) - { - // TODO 4J Stu - Some kind of error handling - app.FatalLoadError(); - //return -1; - } - else if( numberOfBytesRead == 0 ) - { - // File pointer is past the end of the file - return -1; - } + if (std::ferror(m_fileHandle) != 0) { + // TODO 4J Stu - Some kind of error handling + app.FatalLoadError(); + // return -1; + } else if (numberOfBytesRead == 0) { + // File pointer is past the end of the file + return -1; + } - return numberOfBytesRead; + return numberOfBytesRead; } -//Closes this file input stream and releases any system resources associated with the stream. -//If this stream has an associated channel then the channel is closed as well. -void FileInputStream::close() -{ - if(m_fileHandle==NULL) - { - //printf("\n\nFileInputStream::close - TRYING TO CLOSE AN INVALID FILE HANDLE\n\n"); - return; - } - - int result = std::fclose( m_fileHandle ); +// Closes this file input stream and releases any system resources associated +// with the stream. If this stream has an associated channel then the channel is +// closed as well. +void FileInputStream::close() { + if (m_fileHandle == NULL) { + // printf("\n\nFileInputStream::close - TRYING TO CLOSE AN INVALID FILE + // HANDLE\n\n"); + return; + } - if( result != 0 ) - { - // TODO 4J Stu - Some kind of error handling - } + int result = std::fclose(m_fileHandle); - // Stop the dtor from trying to close it again - m_fileHandle = NULL; + if (result != 0) { + // TODO 4J Stu - Some kind of error handling + } + + // Stop the dtor from trying to close it again + m_fileHandle = NULL; } +// Skips n bytes of input from this input stream. Fewer bytes might be skipped +// if the end of the input stream is reached. The actual number k of bytes to be +// skipped is equal to the smaller of n and count-pos. The value k is added into +// pos and k is returned. Overrides: skip in class InputStream Parameters: n - +// the number of bytes to be skipped. Returns: the actual number of bytes +// skipped. +__int64 FileInputStream::skip(__int64 n) { + if (m_fileHandle == NULL || n <= 0) { + return 0; + } -//Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached. The actual number k of bytes to be skipped is equal to the smaller of n and count-pos. The value k is added into pos and k is returned. -//Overrides: -//skip in class InputStream -//Parameters: -//n - the number of bytes to be skipped. -//Returns: -//the actual number of bytes skipped. -__int64 FileInputStream::skip(__int64 n) -{ - if( m_fileHandle == NULL || n <= 0 ) - { - return 0; - } + const __int64 start = FileTell(m_fileHandle); + if (start < 0) { + return 0; + } - const __int64 start = FileTell(m_fileHandle); - if( start < 0 ) - { - return 0; - } + if (!FileSeek(m_fileHandle, 0, SEEK_END)) { + return 0; + } - if( !FileSeek(m_fileHandle, 0, SEEK_END) ) - { - return 0; - } + const __int64 end = FileTell(m_fileHandle); + if (end < 0) { + return 0; + } - const __int64 end = FileTell(m_fileHandle); - if( end < 0 ) - { - return 0; - } + const __int64 offset = std::min(n, std::max<__int64>(0, end - start)); + const __int64 target = start + offset; + if (!FileSeek(m_fileHandle, target, SEEK_SET)) { + return 0; + } - const __int64 offset = std::min(n, std::max<__int64>(0, end - start)); - const __int64 target = start + offset; - if( !FileSeek(m_fileHandle, target, SEEK_SET) ) - { - return 0; - } - - return offset; + return offset; } diff --git a/Minecraft.World/IO/Files/FileInputStream.h b/Minecraft.World/IO/Files/FileInputStream.h index 7afda60a2..2ec91391f 100644 --- a/Minecraft.World/IO/Files/FileInputStream.h +++ b/Minecraft.World/IO/Files/FileInputStream.h @@ -7,18 +7,16 @@ class File; -class FileInputStream : public InputStream -{ +class FileInputStream : public InputStream { public: - FileInputStream(const File &file); - virtual ~FileInputStream(); - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual __int64 skip(__int64 n); + FileInputStream(const File& file); + virtual ~FileInputStream(); + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual __int64 skip(__int64 n); private: - std::FILE *m_fileHandle; - + std::FILE* m_fileHandle; }; diff --git a/Minecraft.World/IO/Files/FileOutputStream.cpp b/Minecraft.World/IO/Files/FileOutputStream.cpp index 699f75101..8f55a851b 100644 --- a/Minecraft.World/IO/Files/FileOutputStream.cpp +++ b/Minecraft.World/IO/Files/FileOutputStream.cpp @@ -2,144 +2,122 @@ #include "File.h" #include "FileOutputStream.h" -//Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is -//created to represent this file connection. -//First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument. +// Creates a file output stream to write to the file represented by the +// specified File object. A new FileDescriptor object is created to represent +// this file connection. First, if there is a security manager, its checkWrite +// method is called with the path represented by the file argument as its +// argument. // -//If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened -//for any other reason then a FileNotFoundException is thrown. +// If the file exists but is a directory rather than a regular file, does not +// exist but cannot be created, or cannot be opened for any other reason then a +// FileNotFoundException is thrown. // -//Parameters: -//file - the file to be opened for writing. -FileOutputStream::FileOutputStream(const File &file) : m_fileHandle( NULL ) -{ - if( file.exists() && file.isDirectory()) - { - // TODO 4J Stu - FileNotFoundException - return; - } +// Parameters: +// file - the file to be opened for writing. +FileOutputStream::FileOutputStream(const File& file) : m_fileHandle(NULL) { + if (file.exists() && file.isDirectory()) { + // TODO 4J Stu - FileNotFoundException + return; + } #if defined(_WIN32) - m_fileHandle = _wfopen(file.getPath().c_str(), L"wb"); + m_fileHandle = _wfopen(file.getPath().c_str(), L"wb"); #else - const std::string nativePath = wstringtofilename(file.getPath()); - m_fileHandle = std::fopen(nativePath.c_str(), "wb"); + const std::string nativePath = wstringtofilename(file.getPath()); + m_fileHandle = std::fopen(nativePath.c_str(), "wb"); #endif - if( m_fileHandle == NULL ) - { - // TODO 4J Stu - Any form of error/exception handling - perror("FileOutputStream::FileOutputStream"); - } + if (m_fileHandle == NULL) { + // TODO 4J Stu - Any form of error/exception handling + perror("FileOutputStream::FileOutputStream"); + } } -FileOutputStream::~FileOutputStream() -{ - if( m_fileHandle != NULL ) - { - std::fclose( m_fileHandle ); - } +FileOutputStream::~FileOutputStream() { + if (m_fileHandle != NULL) { + std::fclose(m_fileHandle); + } } -//Writes the specified byte to this file output stream. Implements the write method of OutputStream. -//Parameters: -//b - the byte to be written. -void FileOutputStream::write(unsigned int b) -{ - if( m_fileHandle == NULL ) - { - return; - } +// Writes the specified byte to this file output stream. Implements the write +// method of OutputStream. Parameters: b - the byte to be written. +void FileOutputStream::write(unsigned int b) { + if (m_fileHandle == NULL) { + return; + } - std::uint8_t value = (std::uint8_t) b; - const size_t numberOfBytesWritten = std::fwrite(&value, 1, 1, m_fileHandle); - const int result = std::ferror(m_fileHandle); + std::uint8_t value = (std::uint8_t)b; + const size_t numberOfBytesWritten = std::fwrite(&value, 1, 1, m_fileHandle); + const int result = std::ferror(m_fileHandle); - if( result != 0 ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 ) - { - // File pointer is past the end of the file - } + if (result != 0) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0) { + // File pointer is past the end of the file + } } -//Writes b.length bytes from the specified byte array to this file output stream. -//Parameters: -//b - the data. -void FileOutputStream::write(byteArray b) -{ - if( m_fileHandle == NULL ) - { - return; - } +// Writes b.length bytes from the specified byte array to this file output +// stream. Parameters: b - the data. +void FileOutputStream::write(byteArray b) { + if (m_fileHandle == NULL) { + return; + } - const size_t numberOfBytesWritten = std::fwrite(b.data, 1, b.length, m_fileHandle); - const int result = std::ferror(m_fileHandle); + const size_t numberOfBytesWritten = + std::fwrite(b.data, 1, b.length, m_fileHandle); + const int result = std::ferror(m_fileHandle); - if( result != 0 ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 || numberOfBytesWritten != b.length ) - { - // File pointer is past the end of the file - } + if (result != 0) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0 || numberOfBytesWritten != b.length) { + // File pointer is past the end of the file + } } -//Writes len bytes from the specified byte array starting at offset off to this file output stream. -//Parameters: -//b - the data. -//off - the start offset in the data. -//len - the number of bytes to write. -void FileOutputStream::write(byteArray b, unsigned int offset, unsigned int length) -{ - // 4J Stu - We don't want to write any more than the array buffer holds - assert( length <= ( b.length - offset ) ); +// Writes len bytes from the specified byte array starting at offset off to this +// file output stream. Parameters: b - the data. off - the start offset in the +// data. len - the number of bytes to write. +void FileOutputStream::write(byteArray b, unsigned int offset, + unsigned int length) { + // 4J Stu - We don't want to write any more than the array buffer holds + assert(length <= (b.length - offset)); - if( m_fileHandle == NULL ) - { - return; - } + if (m_fileHandle == NULL) { + return; + } - const size_t numberOfBytesWritten = std::fwrite(&b[offset], 1, length, m_fileHandle); - const int result = std::ferror(m_fileHandle); + const size_t numberOfBytesWritten = + std::fwrite(&b[offset], 1, length, m_fileHandle); + const int result = std::ferror(m_fileHandle); - if( result != 0 ) - { - // TODO 4J Stu - Some kind of error handling - } - else if( numberOfBytesWritten == 0 || numberOfBytesWritten != length ) - { - // File pointer is past the end of the file - } + if (result != 0) { + // TODO 4J Stu - Some kind of error handling + } else if (numberOfBytesWritten == 0 || numberOfBytesWritten != length) { + // File pointer is past the end of the file + } } // -//Closes this file output stream and releases any system resources associated with this stream. -//This file output stream may no longer be used for writing bytes. -//If this stream has an associated channel then the channel is closed as well. -void FileOutputStream::close() -{ - if( m_fileHandle == NULL ) - { - return; - } +// Closes this file output stream and releases any system resources associated +// with this stream. This file output stream may no longer be used for writing +// bytes. If this stream has an associated channel then the channel is closed as +// well. +void FileOutputStream::close() { + if (m_fileHandle == NULL) { + return; + } - int result = std::fclose( m_fileHandle ); - if( result != 0 ) - { - // TODO 4J Stu - Some kind of error handling - } + int result = std::fclose(m_fileHandle); + if (result != 0) { + // TODO 4J Stu - Some kind of error handling + } - // Stop the dtor from trying to close it again - m_fileHandle = NULL; + // Stop the dtor from trying to close it again + m_fileHandle = NULL; } -void FileOutputStream::flush() -{ - if( m_fileHandle != NULL ) - { - std::fflush( m_fileHandle ); - } +void FileOutputStream::flush() { + if (m_fileHandle != NULL) { + std::fflush(m_fileHandle); + } } diff --git a/Minecraft.World/IO/Files/FileOutputStream.h b/Minecraft.World/IO/Files/FileOutputStream.h index 03734802c..988dc9222 100644 --- a/Minecraft.World/IO/Files/FileOutputStream.h +++ b/Minecraft.World/IO/Files/FileOutputStream.h @@ -7,17 +7,16 @@ class File; -class FileOutputStream : public OutputStream -{ +class FileOutputStream : public OutputStream { public: - FileOutputStream(const File &file); - virtual ~FileOutputStream(); - virtual void write(unsigned int b); - virtual void write(byteArray b); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual void flush(); + FileOutputStream(const File& file); + virtual ~FileOutputStream(); + virtual void write(unsigned int b); + virtual void write(byteArray b); + virtual void write(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual void flush(); private: - std::FILE *m_fileHandle; + std::FILE* m_fileHandle; }; diff --git a/Minecraft.World/IO/Files/FilenameFilter.h b/Minecraft.World/IO/Files/FilenameFilter.h index cc9441b87..1e475783d 100644 --- a/Minecraft.World/IO/Files/FilenameFilter.h +++ b/Minecraft.World/IO/Files/FilenameFilter.h @@ -1,13 +1,11 @@ #pragma once - #include "../../Platform/stdafx.h" class File; // 4J Jev, java lirary interface. -class FilenameFilter -{ +class FilenameFilter { public: - virtual bool accept(File *dir, const std::wstring& name) = 0; + virtual bool accept(File* dir, const std::wstring& name) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/ByteArrayTag.h b/Minecraft.World/IO/NBT/ByteArrayTag.h index e3889b6d0..d43c43d97 100644 --- a/Minecraft.World/IO/NBT/ByteArrayTag.h +++ b/Minecraft.World/IO/NBT/ByteArrayTag.h @@ -2,52 +2,49 @@ #include "Tag.h" #include "../../Platform/System.h" -class ByteArrayTag : public Tag -{ +class ByteArrayTag : public Tag { public: - byteArray data; - - ByteArrayTag(const std::wstring &name) : Tag(name) { } - ByteArrayTag(const std::wstring &name, byteArray data) : Tag(name) {this->data = data; } // 4J - added ownData param - - void write(DataOutput *dos) - { - dos->writeInt(data.length); - dos->write(data); - } + byteArray data; - void load(DataInput *dis) - { - int length = dis->readInt(); - - if ( data.data ) delete[] data.data; - data = byteArray(length); - dis->readFully(data); - } + ByteArrayTag(const std::wstring& name) : Tag(name) {} + ByteArrayTag(const std::wstring& name, byteArray data) : Tag(name) { + this->data = data; + } // 4J - added ownData param - uint8_t getId() { return TAG_Byte_Array; } + void write(DataOutput* dos) { + dos->writeInt(data.length); + dos->write(data); + } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf, 32, L"[%d bytes]",data.length); - return std::wstring( buf ); - } + void load(DataInput* dis) { + int length = dis->readInt(); - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - ByteArrayTag *o = (ByteArrayTag *) obj; - return ((data.data == NULL && o->data.data == NULL) || (data.data != NULL && data.length == o->data.length && memcmp(data.data, o->data.data, data.length) == 0) ); - } - return false; - } + if (data.data) delete[] data.data; + data = byteArray(length); + dis->readFully(data); + } - Tag *copy() - { - byteArray cp = byteArray(data.length); - System::arraycopy(data, 0, &cp, 0, data.length); - return new ByteArrayTag(getName(), cp); - } + uint8_t getId() { return TAG_Byte_Array; } + + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"[%d bytes]", data.length); + return std::wstring(buf); + } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + ByteArrayTag* o = (ByteArrayTag*)obj; + return ((data.data == NULL && o->data.data == NULL) || + (data.data != NULL && data.length == o->data.length && + memcmp(data.data, o->data.data, data.length) == 0)); + } + return false; + } + + Tag* copy() { + byteArray cp = byteArray(data.length); + System::arraycopy(data, 0, &cp, 0, data.length); + return new ByteArrayTag(getName(), cp); + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/ByteTag.h b/Minecraft.World/IO/NBT/ByteTag.h index 2e54755c9..6285eb7f9 100644 --- a/Minecraft.World/IO/NBT/ByteTag.h +++ b/Minecraft.World/IO/NBT/ByteTag.h @@ -1,36 +1,31 @@ #pragma once #include "Tag.h" -class ByteTag : public Tag -{ +class ByteTag : public Tag { public: - uint8_t data; - ByteTag(const std::wstring &name) : Tag(name) {} - ByteTag(const std::wstring &name, uint8_t data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeByte(data); } - void load(DataInput *dis) { data = dis->readByte(); } + uint8_t data; + ByteTag(const std::wstring& name) : Tag(name) {} + ByteTag(const std::wstring& name, uint8_t data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Byte; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf,32,L"%d",data); - return std::wstring( buf ); - } + void write(DataOutput* dos) { dos->writeByte(data); } + void load(DataInput* dis) { data = dis->readByte(); } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - ByteTag *o = (ByteTag *) obj; - return data == o->data; - } - return false; - } + uint8_t getId() { return TAG_Byte; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%d", data); + return std::wstring(buf); + } - Tag *copy() - { - return new ByteTag(getName(), data); - } + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + ByteTag* o = (ByteTag*)obj; + return data == o->data; + } + return false; + } + + Tag* copy() { return new ByteTag(getName(), data); } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/CompoundTag.h b/Minecraft.World/IO/NBT/CompoundTag.h index e41a7ce8f..a2d4ec695 100644 --- a/Minecraft.World/IO/NBT/CompoundTag.h +++ b/Minecraft.World/IO/NBT/CompoundTag.h @@ -11,285 +11,237 @@ #include "ByteArrayTag.h" #include "IntArrayTag.h" -class CompoundTag : public Tag -{ +class CompoundTag : public Tag { private: - std::unordered_map tags; + std::unordered_map tags; public: - CompoundTag() : Tag(L"") {} - CompoundTag(const std::wstring &name) : Tag(name) {} + CompoundTag() : Tag(L"") {} + CompoundTag(const std::wstring& name) : Tag(name) {} - void write(DataOutput *dos) - { - AUTO_VAR(itEnd, tags.end()); - for( std::unordered_map::iterator it = tags.begin(); it != itEnd; it++ ) - { - Tag::writeNamedTag(it->second, dos); - } - dos->writeByte(Tag::TAG_End); - } - - - void load(DataInput *dis) - { - tags.clear(); - Tag *tag; - while ((tag = Tag::readNamedTag(dis))->getId() != Tag::TAG_End) - { - tags[tag->getName()] = tag; + void write(DataOutput* dos) { + AUTO_VAR(itEnd, tags.end()); + for (std::unordered_map::iterator it = tags.begin(); + it != itEnd; it++) { + Tag::writeNamedTag(it->second, dos); } - delete tag; + dos->writeByte(Tag::TAG_End); } - std::vector *getAllTags() // 4J - was collection - { - // 4J - was return tags.values(); - std::vector *ret = new std::vector; - - AUTO_VAR(itEnd, tags.end()); - for( std::unordered_map::iterator it = tags.begin(); it != itEnd; it++ ) - { - ret->push_back(it->second); - } + void load(DataInput* dis) { + tags.clear(); + Tag* tag; + while ((tag = Tag::readNamedTag(dis))->getId() != Tag::TAG_End) { + tags[tag->getName()] = tag; + } + delete tag; + } + + std::vector* getAllTags() // 4J - was collection + { + // 4J - was return tags.values(); + std::vector* ret = new std::vector; + + AUTO_VAR(itEnd, tags.end()); + for (std::unordered_map::iterator it = tags.begin(); + it != itEnd; it++) { + ret->push_back(it->second); + } return ret; } - uint8_t getId() - { - return TAG_Compound; + uint8_t getId() { return TAG_Compound; } + + void put(const wchar_t* name, Tag* tag) { + tags[name] = tag->setName(std::wstring(name)); } - void put(const wchar_t *name, Tag *tag) - { - tags[name] = tag->setName(std::wstring( name )); + void putByte(const wchar_t* name, uint8_t value) { + tags[name] = (new ByteTag(name, value)); } - void putByte(const wchar_t * name, uint8_t value) - { - tags[name] = (new ByteTag(name,value)); + void putShort(const wchar_t* name, short value) { + tags[name] = (new ShortTag(name, value)); } - void putShort(const wchar_t * name, short value) - { - tags[name] = (new ShortTag(name,value)); + void putInt(const wchar_t* name, int value) { + tags[name] = (new IntTag(name, value)); } - void putInt(const wchar_t * name, int value) - { - tags[name] = (new IntTag(name,value)); + void putLong(const wchar_t* name, __int64 value) { + tags[name] = (new LongTag(name, value)); } - void putLong(const wchar_t * name, __int64 value) - { - tags[name] = (new LongTag(name,value)); + void putFloat(const wchar_t* name, float value) { + tags[name] = (new FloatTag(name, value)); } - void putFloat(const wchar_t * name, float value) - { - tags[name] = (new FloatTag(name,value)); + void putDouble(const wchar_t* name, double value) { + tags[name] = (new DoubleTag(name, value)); } - void putDouble(const wchar_t * name, double value) - { - tags[name] = (new DoubleTag(name,value)); + void putString(const wchar_t* name, const std::wstring& value) { + tags[name] = (new StringTag(name, value)); } - void putString(const wchar_t *name, const std::wstring& value) - { - tags[name] = (new StringTag(name,value)); + void putByteArray(const wchar_t* name, byteArray value) { + tags[name] = (new ByteArrayTag(name, value)); } - void putByteArray(const wchar_t * name, byteArray value) - { - tags[name] = (new ByteArrayTag(name,value)); + void putIntArray(const wchar_t* name, intArray value) { + tags[name] = (new IntArrayTag(name, value)); } - void putIntArray(const wchar_t * name, intArray value) - { - tags[name] = (new IntArrayTag(name, value)); - } - - void putCompound(const wchar_t * name, CompoundTag *value) - { - tags[name] = value->setName( std::wstring( name ) ); + void putCompound(const wchar_t* name, CompoundTag* value) { + tags[name] = value->setName(std::wstring(name)); } - void putBoolean(const wchar_t * string, bool val) - { - putByte(string, val?static_cast(1):static_cast(0)); + void putBoolean(const wchar_t* string, bool val) { + putByte(string, + val ? static_cast(1) : static_cast(0)); } - Tag *get(const wchar_t *name) - { - AUTO_VAR(it, tags.find(name)); - if(it != tags.end()) return it->second; - return NULL; - } - - bool contains(const wchar_t * name) - { - return tags.find(name) != tags.end(); + Tag* get(const wchar_t* name) { + AUTO_VAR(it, tags.find(name)); + if (it != tags.end()) return it->second; + return NULL; } - uint8_t getByte(const wchar_t * name) - { + bool contains(const wchar_t* name) { return tags.find(name) != tags.end(); } + + uint8_t getByte(const wchar_t* name) { if (tags.find(name) == tags.end()) return (uint8_t)0; - return ((ByteTag *) tags[name])->data; + return ((ByteTag*)tags[name])->data; } - short getShort(const wchar_t * name) - { + short getShort(const wchar_t* name) { if (tags.find(name) == tags.end()) return (short)0; - return ((ShortTag *) tags[name])->data; + return ((ShortTag*)tags[name])->data; } - int getInt(const wchar_t * name) - { + int getInt(const wchar_t* name) { if (tags.find(name) == tags.end()) return (int)0; - return ((IntTag *) tags[name])->data; + return ((IntTag*)tags[name])->data; } - __int64 getLong(const wchar_t * name) - { + __int64 getLong(const wchar_t* name) { if (tags.find(name) == tags.end()) return (__int64)0; - return ((LongTag *) tags[name])->data; + return ((LongTag*)tags[name])->data; } - float getFloat(const wchar_t * name) - { + float getFloat(const wchar_t* name) { if (tags.find(name) == tags.end()) return (float)0; - return ((FloatTag *) tags[name])->data; + return ((FloatTag*)tags[name])->data; } - double getDouble(const wchar_t * name) - { + double getDouble(const wchar_t* name) { if (tags.find(name) == tags.end()) return (double)0; - return ((DoubleTag *) tags[name])->data; + return ((DoubleTag*)tags[name])->data; } - std::wstring getString(const wchar_t * name) - { - if (tags.find(name) == tags.end()) return std::wstring( L"" ); - return ((StringTag *) tags[name])->data; + std::wstring getString(const wchar_t* name) { + if (tags.find(name) == tags.end()) return std::wstring(L""); + return ((StringTag*)tags[name])->data; } - byteArray getByteArray(const wchar_t * name) - { + byteArray getByteArray(const wchar_t* name) { if (tags.find(name) == tags.end()) return byteArray(); - return ((ByteArrayTag *) tags[name])->data; + return ((ByteArrayTag*)tags[name])->data; } - intArray getIntArray(const wchar_t * name) - { - if (tags.find(name) == tags.end()) return intArray(0); - return ((IntArrayTag *) tags[name])->data; - } + intArray getIntArray(const wchar_t* name) { + if (tags.find(name) == tags.end()) return intArray(0); + return ((IntArrayTag*)tags[name])->data; + } - CompoundTag *getCompound(const wchar_t * name) - { + CompoundTag* getCompound(const wchar_t* name) { if (tags.find(name) == tags.end()) return new CompoundTag(name); - return (CompoundTag *) tags[name]; + return (CompoundTag*)tags[name]; } - ListTag *getList(const wchar_t * name) - { - // 4jcraft changed this function to not do a c style cast - // of a templated class - auto it = tags.find(name); - if(it == tags.end()) return new ListTag(name); - return dynamic_cast*>(it->second); + ListTag* getList(const wchar_t* name) { + // 4jcraft changed this function to not do a c style cast + // of a templated class + auto it = tags.find(name); + if (it == tags.end()) return new ListTag(name); + return dynamic_cast*>(it->second); } - bool getBoolean(const wchar_t *string) - { + bool getBoolean(const wchar_t* string) { return getByte(string) != static_cast(0); } - void remove(const std::wstring &name) - { - AUTO_VAR(it, tags.find(name)); - if(it != tags.end()) tags.erase(it); - //tags.remove(name); - } - - std::wstring toString() - { - static const int bufSize = 32; - static wchar_t buf[bufSize]; - swprintf(buf,bufSize,L"%d entries",tags.size()); - return std::wstring( buf ); + void remove(const std::wstring& name) { + AUTO_VAR(it, tags.find(name)); + if (it != tags.end()) tags.erase(it); + // tags.remove(name); } - void print(char *prefix, std::ostream out) - { - /* - Tag::print(prefix, out); - out << prefix << "{" << std::endl; - - char *newPrefix = new char[ strlen(prefix) + 4 ]; - strcpy( newPrefix, prefix); - strcat( newPrefix, " "); - - AUTO_VAR(itEnd, tags.end()); - for( std::unordered_map::iterator it = tags.begin(); it != itEnd; it++ ) - { - it->second->print(newPrefix, out); - } - delete[] newPrefix; - out << prefix << "}" << std::endl; - */ + std::wstring toString() { + static const int bufSize = 32; + static wchar_t buf[bufSize]; + swprintf(buf, bufSize, L"%d entries", tags.size()); + return std::wstring(buf); } - bool isEmpty() - { - return tags.empty(); + void print(char* prefix, std::ostream out) { + /* +Tag::print(prefix, out); + out << prefix << "{" << std::endl; + + char *newPrefix = new char[ strlen(prefix) + 4 ]; + strcpy( newPrefix, prefix); + strcat( newPrefix, " "); + + AUTO_VAR(itEnd, tags.end()); + for( std::unordered_map::iterator it = tags.begin(); it +!= itEnd; it++ ) + { + it->second->print(newPrefix, out); + } + delete[] newPrefix; + out << prefix << "}" << std::endl; + */ } - virtual ~CompoundTag() - { - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) - { - delete it->second; - } - } + bool isEmpty() { return tags.empty(); } - Tag *copy() - { - CompoundTag *tag = new CompoundTag(getName()); - - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) - { - tag->put((wchar_t *)it->first.c_str(), it->second->copy()); - } - return tag; - } + virtual ~CompoundTag() { + AUTO_VAR(itEnd, tags.end()); + for (AUTO_VAR(it, tags.begin()); it != itEnd; it++) { + delete it->second; + } + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - CompoundTag *o = (CompoundTag *) obj; + Tag* copy() { + CompoundTag* tag = new CompoundTag(getName()); - if(tags.size() == o->tags.size()) - { - bool equal = true; - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) - { - AUTO_VAR(itFind, o->tags.find(it->first)); - if(itFind == o->tags.end() || !it->second->equals(itFind->second) ) - { - equal = false; - break; - } - } - return equal; - //return tags.entrySet().equals(o.tags.entrySet()); - } - } - return false; - } + AUTO_VAR(itEnd, tags.end()); + for (AUTO_VAR(it, tags.begin()); it != itEnd; it++) { + tag->put((wchar_t*)it->first.c_str(), it->second->copy()); + } + return tag; + } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + CompoundTag* o = (CompoundTag*)obj; + + if (tags.size() == o->tags.size()) { + bool equal = true; + AUTO_VAR(itEnd, tags.end()); + for (AUTO_VAR(it, tags.begin()); it != itEnd; it++) { + AUTO_VAR(itFind, o->tags.find(it->first)); + if (itFind == o->tags.end() || + !it->second->equals(itFind->second)) { + equal = false; + break; + } + } + return equal; + // return tags.entrySet().equals(o.tags.entrySet()); + } + } + return false; + } }; diff --git a/Minecraft.World/IO/NBT/DoubleTag.h b/Minecraft.World/IO/NBT/DoubleTag.h index 35e2713ac..5df0e1bb6 100644 --- a/Minecraft.World/IO/NBT/DoubleTag.h +++ b/Minecraft.World/IO/NBT/DoubleTag.h @@ -2,36 +2,31 @@ #include "../Streams/InputOutputStream.h" #include "Tag.h" -class DoubleTag : public Tag -{ +class DoubleTag : public Tag { public: - double data; - DoubleTag(const std::wstring &name) : Tag(name) {} - DoubleTag(const std::wstring &name, double data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeDouble(data); } - void load(DataInput *dis) { data = dis->readDouble(); } + double data; + DoubleTag(const std::wstring& name) : Tag(name) {} + DoubleTag(const std::wstring& name, double data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Double; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf,32,L"%f",data); - return std::wstring( buf ); - } + void write(DataOutput* dos) { dos->writeDouble(data); } + void load(DataInput* dis) { data = dis->readDouble(); } - Tag *copy() - { - return new DoubleTag(getName(), data); - } + uint8_t getId() { return TAG_Double; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%f", data); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - DoubleTag *o = (DoubleTag *) obj; - return data == o->data; - } - return false; - } + Tag* copy() { return new DoubleTag(getName(), data); } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + DoubleTag* o = (DoubleTag*)obj; + return data == o->data; + } + return false; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/EndTag.h b/Minecraft.World/IO/NBT/EndTag.h index 105c8c8fa..33ee95469 100644 --- a/Minecraft.World/IO/NBT/EndTag.h +++ b/Minecraft.World/IO/NBT/EndTag.h @@ -1,25 +1,18 @@ #pragma once #include "Tag.h" -class EndTag : public Tag -{ +class EndTag : public Tag { public: - EndTag() : Tag(L"") {} - EndTag(const std::wstring &name) : Tag(name) {} + EndTag() : Tag(L"") {} + EndTag(const std::wstring& name) : Tag(name) {} - void load(DataInput *dis) {}; - void write(DataOutput *dos) {}; + void load(DataInput* dis) {}; + void write(DataOutput* dos) {}; - uint8_t getId() { return TAG_End; } - std::wstring toString() { return std::wstring( L"END" ); } + uint8_t getId() { return TAG_End; } + std::wstring toString() { return std::wstring(L"END"); } - Tag *copy() - { - return new EndTag(); - } + Tag* copy() { return new EndTag(); } - bool equals(Tag *obj) - { - return Tag::equals(obj); - } + bool equals(Tag* obj) { return Tag::equals(obj); } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/FloatTag.h b/Minecraft.World/IO/NBT/FloatTag.h index 738f7e2ff..a61d2c54b 100644 --- a/Minecraft.World/IO/NBT/FloatTag.h +++ b/Minecraft.World/IO/NBT/FloatTag.h @@ -2,36 +2,31 @@ #include "../Streams/InputOutputStream.h" #include "Tag.h" -class FloatTag : public Tag -{ +class FloatTag : public Tag { public: - float data; - FloatTag(const std::wstring &name) : Tag(name) {} - FloatTag(const std::wstring &name, float data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeFloat(data); } - void load(DataInput *dis) { data = dis->readFloat(); } + float data; + FloatTag(const std::wstring& name) : Tag(name) {} + FloatTag(const std::wstring& name, float data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Float; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf, 32, L"%f",data); - return std::wstring( buf ); - } + void write(DataOutput* dos) { dos->writeFloat(data); } + void load(DataInput* dis) { data = dis->readFloat(); } - Tag *copy() - { - return new FloatTag(getName(), data); - } + uint8_t getId() { return TAG_Float; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%f", data); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - FloatTag *o = (FloatTag *) obj; - return data == o->data; - } - return false; - } + Tag* copy() { return new FloatTag(getName(), data); } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + FloatTag* o = (FloatTag*)obj; + return data == o->data; + } + return false; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/IntArrayTag.h b/Minecraft.World/IO/NBT/IntArrayTag.h index 2f25be676..9bce4b741 100644 --- a/Minecraft.World/IO/NBT/IntArrayTag.h +++ b/Minecraft.World/IO/NBT/IntArrayTag.h @@ -3,64 +3,54 @@ #include "Tag.h" #include "../../Platform/System.h" -class IntArrayTag : public Tag -{ +class IntArrayTag : public Tag { public: - intArray data; + intArray data; - IntArrayTag(const std::wstring &name) : Tag(name) - { - } + IntArrayTag(const std::wstring& name) : Tag(name) {} - IntArrayTag(const std::wstring &name, intArray data) : Tag(name) - { - this->data = data; - } + IntArrayTag(const std::wstring& name, intArray data) : Tag(name) { + this->data = data; + } - void write(DataOutput *dos) - { - dos->writeInt(data.length); - for (unsigned int i = 0; i < data.length; i++) - { - dos->writeInt(data[i]); - } - } + void write(DataOutput* dos) { + dos->writeInt(data.length); + for (unsigned int i = 0; i < data.length; i++) { + dos->writeInt(data[i]); + } + } - void load(DataInput *dis) - { - int length = dis->readInt(); + void load(DataInput* dis) { + int length = dis->readInt(); - if ( data.data ) delete[] data.data; - data = intArray(length); - for (int i = 0; i < length; i++) - { - data[i] = dis->readInt(); - } - } + if (data.data) delete[] data.data; + data = intArray(length); + for (int i = 0; i < length; i++) { + data[i] = dis->readInt(); + } + } - uint8_t getId() { return TAG_Int_Array; } + uint8_t getId() { return TAG_Int_Array; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf, 32, L"[%d bytes]",data.length); - return std::wstring( buf ); - } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"[%d bytes]", data.length); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - IntArrayTag *o = (IntArrayTag *) obj; - return ((data.data == NULL && o->data.data == NULL) || (data.data != NULL && data.length == o->data.length && memcmp(data.data, o->data.data, data.length) == 0) ); - } - return false; - } + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + IntArrayTag* o = (IntArrayTag*)obj; + return ((data.data == NULL && o->data.data == NULL) || + (data.data != NULL && data.length == o->data.length && + memcmp(data.data, o->data.data, data.length) == 0)); + } + return false; + } - Tag *copy() - { - intArray cp = intArray(data.length); - System::arraycopy(data, 0, &cp, 0, data.length); - return new IntArrayTag(getName(), cp); - } + Tag* copy() { + intArray cp = intArray(data.length); + System::arraycopy(data, 0, &cp, 0, data.length); + return new IntArrayTag(getName(), cp); + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/IntTag.h b/Minecraft.World/IO/NBT/IntTag.h index 9dc9aaf25..3ec50cf8c 100644 --- a/Minecraft.World/IO/NBT/IntTag.h +++ b/Minecraft.World/IO/NBT/IntTag.h @@ -1,36 +1,31 @@ #pragma once #include "Tag.h" -class IntTag : public Tag -{ +class IntTag : public Tag { public: - int data; - IntTag(const std::wstring &name) : Tag(name) {} - IntTag(const std::wstring &name, int data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeInt(data); } - void load(DataInput *dis) { data = dis->readInt(); } + int data; + IntTag(const std::wstring& name) : Tag(name) {} + IntTag(const std::wstring& name, int data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Int; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf, 32, L"%d", data); - return std::wstring( buf ); - } + void write(DataOutput* dos) { dos->writeInt(data); } + void load(DataInput* dis) { data = dis->readInt(); } - Tag *copy() - { - return new IntTag(getName(), data); - } + uint8_t getId() { return TAG_Int; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%d", data); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - IntTag *o = (IntTag *) obj; - return data == o->data; - } - return false; - } + Tag* copy() { return new IntTag(getName(), data); } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + IntTag* o = (IntTag*)obj; + return data == o->data; + } + return false; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/ListTag.h b/Minecraft.World/IO/NBT/ListTag.h index b78f194de..611aadb0a 100644 --- a/Minecraft.World/IO/NBT/ListTag.h +++ b/Minecraft.World/IO/NBT/ListTag.h @@ -2,104 +2,89 @@ #include "Tag.h" -template class ListTag : public Tag -{ +template +class ListTag : public Tag { private: - std::vector list; + std::vector list; uint8_t type; public: - ListTag() : Tag(L"") {} - ListTag(const std::wstring &name) : Tag(name) {} + ListTag() : Tag(L"") {} + ListTag(const std::wstring& name) : Tag(name) {} - void write(DataOutput *dos) - { - if (list.size() > 0) type = (list[0])->getId(); - else type = static_cast(1); + void write(DataOutput* dos) { + if (list.size() > 0) + type = (list[0])->getId(); + else + type = static_cast(1); dos->writeByte(type); dos->writeInt((int)list.size()); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - (*it)->write(dos); - } - void load(DataInput *dis) - { + AUTO_VAR(itEnd, list.end()); + for (AUTO_VAR(it, list.begin()); it != itEnd; it++) (*it)->write(dos); + } + void load(DataInput* dis) { type = dis->readByte(); int size = dis->readInt(); list.clear(); - for (int i = 0; i < size; i++) - { - Tag *tag = Tag::newTag(type, L""); + for (int i = 0; i < size; i++) { + Tag* tag = Tag::newTag(type, L""); tag->load(dis); list.push_back(tag); } - } + } - uint8_t getId() { return TAG_List; } + uint8_t getId() { return TAG_List; } - std::wstring toString() - { - static wchar_t buf[64]; - swprintf(buf,64,L"%d entries of type %ls",list.size(),Tag::getTagName(type)); - return std::wstring( buf ); - } + std::wstring toString() { + static wchar_t buf[64]; + swprintf(buf, 64, L"%d entries of type %ls", list.size(), + Tag::getTagName(type)); + return std::wstring(buf); + } - void print(char *prefix, std::ostream out) - { + void print(char* prefix, std::ostream out) { printf(prefix); - out << prefix << "{" << std::endl; + out << prefix << "{" << std::endl; - char *newPrefix = new char[ strlen(prefix) + 4 ]; - strcpy( newPrefix, prefix); - strcat( newPrefix, " "); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - printf(newPrefix); - delete[] newPrefix; - out << prefix << "}" << std::endl; - } + char* newPrefix = new char[strlen(prefix) + 4]; + strcpy(newPrefix, prefix); + strcat(newPrefix, " "); + AUTO_VAR(itEnd, list.end()); + for (AUTO_VAR(it, list.begin()); it != itEnd; it++) printf(newPrefix); + delete[] newPrefix; + out << prefix << "}" << std::endl; + } - void add(T *tag) - { + void add(T* tag) { type = tag->getId(); list.push_back(tag); - } + } - T *get(int index) - { - return (T *) list[index]; - } + T* get(int index) { return (T*)list[index]; } - int size() - { - return (int)list.size(); - } + int size() { return (int)list.size(); } - virtual ~ListTag() - { - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - { - delete *it; - } - } + virtual ~ListTag() { + AUTO_VAR(itEnd, list.end()); + for (AUTO_VAR(it, list.begin()); it != itEnd; it++) { + delete *it; + } + } - Tag *copy() - { - ListTag *res = new ListTag(getName()); - res->type = type; - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - { - T *copy = (T *) (*it)->copy(); - res->list.push_back(copy); - } - return res; - } + Tag* copy() { + ListTag* res = new ListTag(getName()); + res->type = type; + AUTO_VAR(itEnd, list.end()); + for (AUTO_VAR(it, list.begin()); it != itEnd; it++) { + T* copy = (T*)(*it)->copy(); + res->list.push_back(copy); + } + return res; + } #if 0 bool equals(Object obj) diff --git a/Minecraft.World/IO/NBT/LongTag.h b/Minecraft.World/IO/NBT/LongTag.h index 126a102f2..5e6e82c38 100644 --- a/Minecraft.World/IO/NBT/LongTag.h +++ b/Minecraft.World/IO/NBT/LongTag.h @@ -1,36 +1,31 @@ #pragma once #include "Tag.h" -class LongTag : public Tag -{ +class LongTag : public Tag { public: - __int64 data; - LongTag(const std::wstring &name) : Tag(name) {} - LongTag(const std::wstring &name, __int64 data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeLong(data); } - void load(DataInput *dis) { data = dis->readLong(); } + __int64 data; + LongTag(const std::wstring& name) : Tag(name) {} + LongTag(const std::wstring& name, __int64 data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Long; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf,32,L"%I64d",data); - return std::wstring(buf); - } + void write(DataOutput* dos) { dos->writeLong(data); } + void load(DataInput* dis) { data = dis->readLong(); } - Tag *copy() - { - return new LongTag(getName(), data); - } + uint8_t getId() { return TAG_Long; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%I64d", data); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - LongTag *o = (LongTag *) obj; - return data == o->data; - } - return false; - } + Tag* copy() { return new LongTag(getName(), data); } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + LongTag* o = (LongTag*)obj; + return data == o->data; + } + return false; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/NbtIO.cpp b/Minecraft.World/IO/NBT/NbtIO.cpp index 56db60780..fa51e350c 100644 --- a/Minecraft.World/IO/NBT/NbtIO.cpp +++ b/Minecraft.World/IO/NBT/NbtIO.cpp @@ -2,64 +2,65 @@ #include "../Streams/InputOutputStream.h" #include "NbtIO.h" -CompoundTag *NbtIo::readCompressed(InputStream *in) -{ - MemSect(26); - // 4J - this was using a try/finally block - DataInputStream dis = DataInputStream(in); // 4J - was new GZIPInputStream as well - CompoundTag *ret = NbtIo::read((DataInput *)&dis); - dis.close(); - MemSect(0); - return ret; +CompoundTag* NbtIo::readCompressed(InputStream* in) { + MemSect(26); + // 4J - this was using a try/finally block + DataInputStream dis = + DataInputStream(in); // 4J - was new GZIPInputStream as well + CompoundTag* ret = NbtIo::read((DataInput*)&dis); + dis.close(); + MemSect(0); + return ret; } -void NbtIo::writeCompressed(CompoundTag *tag, OutputStream *out) -{ - // 4J - this was using a try/finally block - // 4J Stu - Buffer output in 1024 byte chunks so that we can allocate properly in the save file - BufferedOutputStream bos = BufferedOutputStream( out, 1024 ); - DataOutputStream dos = DataOutputStream(&bos); // 4J - was new GZIPOutputStream as well - NbtIo::write(tag, &dos); - dos.close(); +void NbtIo::writeCompressed(CompoundTag* tag, OutputStream* out) { + // 4J - this was using a try/finally block + // 4J Stu - Buffer output in 1024 byte chunks so that we can allocate + // properly in the save file + BufferedOutputStream bos = BufferedOutputStream(out, 1024); + DataOutputStream dos = + DataOutputStream(&bos); // 4J - was new GZIPOutputStream as well + NbtIo::write(tag, &dos); + dos.close(); } -// Reads tags from a stream created from the input buffer. Doesn't free the data in the source buffer. -CompoundTag *NbtIo::decompress(byteArray buffer) -{ - ByteArrayInputStream bais = ByteArrayInputStream(buffer); - // 4J - this was using a try/finally block - DataInputStream in = DataInputStream(&bais); // 4J - was new GZIPInputStream as well - CompoundTag *ret = NbtIo::read((DataInput *)&in); - bais.reset(); // This stops the buffer referenced by the input stream from being freed when it goes out of context - in.close(); - return ret; +// Reads tags from a stream created from the input buffer. Doesn't free the data +// in the source buffer. +CompoundTag* NbtIo::decompress(byteArray buffer) { + ByteArrayInputStream bais = ByteArrayInputStream(buffer); + // 4J - this was using a try/finally block + DataInputStream in = + DataInputStream(&bais); // 4J - was new GZIPInputStream as well + CompoundTag* ret = NbtIo::read((DataInput*)&in); + bais.reset(); // This stops the buffer referenced by the input stream from + // being freed when it goes out of context + in.close(); + return ret; } -byteArray NbtIo::compress(CompoundTag *tag) -{ - // 4J - this was using a try/finally block +byteArray NbtIo::compress(CompoundTag* tag) { + // 4J - this was using a try/finally block ByteArrayOutputStream baos = ByteArrayOutputStream(); - DataOutputStream dos = DataOutputStream(&baos); // 4J - was new GZIPOutputStream as well - NbtIo::write(tag, &dos); + DataOutputStream dos = + DataOutputStream(&baos); // 4J - was new GZIPOutputStream as well + NbtIo::write(tag, &dos); - byteArray ret(baos.buf.length); - System::arraycopy(baos.buf,0,&ret,0,baos.buf.length); - dos.close(); - return ret; + byteArray ret(baos.buf.length); + System::arraycopy(baos.buf, 0, &ret, 0, baos.buf.length); + dos.close(); + return ret; } -CompoundTag *NbtIo::read(DataInput *dis) -{ - Tag *tag = Tag::readNamedTag(dis); +CompoundTag* NbtIo::read(DataInput* dis) { + Tag* tag = Tag::readNamedTag(dis); - if( tag->getId() == Tag::TAG_Compound ) return (CompoundTag *)tag; + if (tag->getId() == Tag::TAG_Compound) return (CompoundTag*)tag; - if(tag!=NULL) delete tag; - // Root tag must be a named compound tag - return NULL; + if (tag != NULL) delete tag; + // Root tag must be a named compound tag + return NULL; } -void NbtIo::write(CompoundTag *tag, DataOutput *dos) -{ - Tag::writeNamedTag(tag, dos); +void NbtIo::write(CompoundTag* tag, DataOutput* dos) { + Tag::writeNamedTag(tag, dos); } \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/NbtIO.h b/Minecraft.World/IO/NBT/NbtIO.h index c389afc42..2f5f72800 100644 --- a/Minecraft.World/IO/NBT/NbtIO.h +++ b/Minecraft.World/IO/NBT/NbtIO.h @@ -5,13 +5,12 @@ class InputStream; -class NbtIo -{ +class NbtIo { public: - static CompoundTag *readCompressed(InputStream *in); - static void writeCompressed(CompoundTag *tag, OutputStream *out); - static CompoundTag *decompress(byteArray buffer); - static byteArray compress(CompoundTag *tag); - static CompoundTag *read(DataInput *dis); - static void write(CompoundTag *tag, DataOutput *dos); + static CompoundTag* readCompressed(InputStream* in); + static void writeCompressed(CompoundTag* tag, OutputStream* out); + static CompoundTag* decompress(byteArray buffer); + static byteArray compress(CompoundTag* tag); + static CompoundTag* read(DataInput* dis); + static void write(CompoundTag* tag, DataOutput* dos); }; diff --git a/Minecraft.World/IO/NBT/NbtSlotFile.cpp b/Minecraft.World/IO/NBT/NbtSlotFile.cpp index a373667fe..6b80cc188 100644 --- a/Minecraft.World/IO/NBT/NbtSlotFile.cpp +++ b/Minecraft.World/IO/NBT/NbtSlotFile.cpp @@ -2,217 +2,194 @@ #include "../Files/File.h" #include "NbtSlotFile.h" -namespace -{ - std::FILE *OpenBinaryFileForReadWrite(const File &file) - { +namespace { +std::FILE* OpenBinaryFileForReadWrite(const File& file) { #if defined(_WIN32) - std::FILE *stream = _wfopen(file.getPath().c_str(), L"r+b"); - if (stream == NULL) - { - stream = _wfopen(file.getPath().c_str(), L"w+b"); - } + std::FILE* stream = _wfopen(file.getPath().c_str(), L"r+b"); + if (stream == NULL) { + stream = _wfopen(file.getPath().c_str(), L"w+b"); + } #else - const std::string nativePath = wstringtofilename(file.getPath()); - std::FILE *stream = std::fopen(nativePath.c_str(), "r+b"); - if (stream == NULL) - { - stream = std::fopen(nativePath.c_str(), "w+b"); - } + const std::string nativePath = wstringtofilename(file.getPath()); + std::FILE* stream = std::fopen(nativePath.c_str(), "r+b"); + if (stream == NULL) { + stream = std::fopen(nativePath.c_str(), "w+b"); + } #endif - return stream; - } - - bool SeekFile(std::FILE *file, __int64 offset) - { -#if defined(_WIN32) - return _fseeki64(file, offset, SEEK_SET) == 0; -#else - return fseeko(file, static_cast(offset), SEEK_SET) == 0; -#endif - } - - bool ReadExact(std::FILE *file, void *buffer, std::size_t size) - { - return std::fread(buffer, 1, size, file) == size; - } - - bool WriteExact(std::FILE *file, const void *buffer, std::size_t size) - { - return std::fwrite(buffer, 1, size, file) == size; - } + return stream; } +bool SeekFile(std::FILE* file, __int64 offset) { +#if defined(_WIN32) + return _fseeki64(file, offset, SEEK_SET) == 0; +#else + return fseeko(file, static_cast(offset), SEEK_SET) == 0; +#endif +} -byteArray NbtSlotFile::READ_BUFFER(1024*1024); +bool ReadExact(std::FILE* file, void* buffer, std::size_t size) { + return std::fread(buffer, 1, size, file) == size; +} + +bool WriteExact(std::FILE* file, const void* buffer, std::size_t size) { + return std::fwrite(buffer, 1, size, file) == size; +} +} // namespace + +byteArray NbtSlotFile::READ_BUFFER(1024 * 1024); __int64 NbtSlotFile::largest = 0; -NbtSlotFile::NbtSlotFile(File file) -{ - totalFileSlots = 0; - fileSlotMapLength = ZonedChunkStorage::CHUNKS_PER_ZONE * ZonedChunkStorage::CHUNKS_PER_ZONE; - fileSlotMap = new std::vector *[fileSlotMapLength]; +NbtSlotFile::NbtSlotFile(File file) { + totalFileSlots = 0; + fileSlotMapLength = + ZonedChunkStorage::CHUNKS_PER_ZONE * ZonedChunkStorage::CHUNKS_PER_ZONE; + fileSlotMap = new std::vector*[fileSlotMapLength]; - if ( !file.exists() || file.length() ) - { - raf = OpenBinaryFileForReadWrite(file); + if (!file.exists() || file.length()) { + raf = OpenBinaryFileForReadWrite(file); writeHeader(); - } - else - { - raf = OpenBinaryFileForReadWrite(file); + } else { + raf = OpenBinaryFileForReadWrite(file); } readHeader(); - for (int i = 0; i < fileSlotMapLength; i++) - { + for (int i = 0; i < fileSlotMapLength; i++) { fileSlotMap[i] = new std::vector; } - for (int fileSlot = 0; fileSlot < totalFileSlots; fileSlot++) - { + for (int fileSlot = 0; fileSlot < totalFileSlots; fileSlot++) { seekSlotHeader(fileSlot); - short slot; - ReadExact(raf, &slot, sizeof(slot)); - if (slot == 0) - { - freeFileSlots.push_back(fileSlot); - } else if (slot < 0) - { - fileSlotMap[(-slot) - 1]->push_back(fileSlot); + short slot; + ReadExact(raf, &slot, sizeof(slot)); + if (slot == 0) { + freeFileSlots.push_back(fileSlot); + } else if (slot < 0) { + fileSlotMap[(-slot) - 1]->push_back(fileSlot); } else { fileSlotMap[slot - 1]->push_back(fileSlot); } } } -void NbtSlotFile::readHeader() -{ - SeekFile(raf, 0); +void NbtSlotFile::readHeader() { + SeekFile(raf, 0); int magic; - ReadExact(raf, &magic, sizeof(magic)); -// if (magic != MAGIC_NUMBER) throw new IOException("Bad magic number: " + magic); // 4J - TODO + ReadExact(raf, &magic, sizeof(magic)); + // if (magic != MAGIC_NUMBER) throw new IOException("Bad magic number: " + // + magic); // 4J - TODO short version; - ReadExact(raf, &version, sizeof(version)); -// if (version != 0) throw new IOException("Bad version number: " + version); // 4J - TODO - ReadExact(raf, &totalFileSlots, sizeof(totalFileSlots)); + ReadExact(raf, &version, sizeof(version)); + // if (version != 0) throw new IOException("Bad version number: " + + // version); // 4J - TODO + ReadExact(raf, &totalFileSlots, sizeof(totalFileSlots)); } -void NbtSlotFile::writeHeader() -{ - short version = 0; - SeekFile(raf, 0); - WriteExact(raf, &MAGIC_NUMBER, sizeof(MAGIC_NUMBER)); - WriteExact(raf, &version, sizeof(version)); - WriteExact(raf, &totalFileSlots, sizeof(totalFileSlots)); +void NbtSlotFile::writeHeader() { + short version = 0; + SeekFile(raf, 0); + WriteExact(raf, &MAGIC_NUMBER, sizeof(MAGIC_NUMBER)); + WriteExact(raf, &version, sizeof(version)); + WriteExact(raf, &totalFileSlots, sizeof(totalFileSlots)); } -void NbtSlotFile::seekSlotHeader(int fileSlot) -{ - int target = FILE_HEADER_SIZE + fileSlot * (FILE_SLOT_SIZE + FILE_SLOT_HEADER_SIZE); - SeekFile(raf, target); +void NbtSlotFile::seekSlotHeader(int fileSlot) { + int target = + FILE_HEADER_SIZE + fileSlot * (FILE_SLOT_SIZE + FILE_SLOT_HEADER_SIZE); + SeekFile(raf, target); } -void NbtSlotFile::seekSlot(int fileSlot) -{ - int target = FILE_HEADER_SIZE + fileSlot * (FILE_SLOT_SIZE + FILE_SLOT_HEADER_SIZE); - SeekFile(raf, target + FILE_SLOT_HEADER_SIZE); +void NbtSlotFile::seekSlot(int fileSlot) { + int target = + FILE_HEADER_SIZE + fileSlot * (FILE_SLOT_SIZE + FILE_SLOT_HEADER_SIZE); + SeekFile(raf, target + FILE_SLOT_HEADER_SIZE); } -std::vector *NbtSlotFile::readAll(int slot) -{ - std::vector *tags = new std::vector; - std::vector *fileSlots = fileSlotMap[slot]; +std::vector* NbtSlotFile::readAll(int slot) { + std::vector* tags = new std::vector; + std::vector* fileSlots = fileSlotMap[slot]; int skipped = 0; - AUTO_VAR(itEnd, fileSlots->end()); - for (AUTO_VAR(it, fileSlots->begin()); it != itEnd; it++) - { - int c = *it; //fileSlots->at(i); + AUTO_VAR(itEnd, fileSlots->end()); + for (AUTO_VAR(it, fileSlots->begin()); it != itEnd; it++) { + int c = *it; // fileSlots->at(i); int pos = 0; int continuesAt = -1; int expectedSlot = slot + 1; - do - { + do { seekSlotHeader(c); short oldSlot; - ReadExact(raf, &oldSlot, sizeof(oldSlot)); + ReadExact(raf, &oldSlot, sizeof(oldSlot)); short size; - ReadExact(raf, &size, sizeof(size)); - ReadExact(raf, &continuesAt, sizeof(continuesAt)); - int lastSlot; - ReadExact(raf, &lastSlot, sizeof(lastSlot)); + ReadExact(raf, &size, sizeof(size)); + ReadExact(raf, &continuesAt, sizeof(continuesAt)); + int lastSlot; + ReadExact(raf, &lastSlot, sizeof(lastSlot)); seekSlot(c); - if (expectedSlot > 0 && oldSlot == -expectedSlot) - { + if (expectedSlot > 0 && oldSlot == -expectedSlot) { skipped++; - goto fileSlotLoop; // 4J - used to be continue fileSlotLoop, with for loop labelled as fileSlotLoop + goto fileSlotLoop; // 4J - used to be continue fileSlotLoop, + // with for loop labelled as fileSlotLoop } -// if (oldSlot != expectedSlot) throw new IOException("Wrong slot! Got " + oldSlot + ", expected " + expectedSlot); // 4J - TODO + // if (oldSlot != expectedSlot) throw new + // IOException("Wrong slot! Got " + oldSlot + ", expected + // " + expectedSlot); // 4J - TODO - ReadExact(raf, READ_BUFFER.data + pos, size); + ReadExact(raf, READ_BUFFER.data + pos, size); - if (continuesAt >= 0) - { + if (continuesAt >= 0) { pos += size; c = continuesAt; expectedSlot = -slot - 1; } } while (continuesAt >= 0); tags->push_back(NbtIo::decompress(READ_BUFFER)); -fileSlotLoop: - continue; + fileSlotLoop: + continue; } return tags; - } -int NbtSlotFile::getFreeSlot() -{ int fileSlot; +int NbtSlotFile::getFreeSlot() { + int fileSlot; -// 4J - removed - don't see how toReplace can ever have anything in here, and might not be initialised -// if (toReplace->size() > 0) -// { -// fileSlot = toReplace->back(); -// toReplace->pop_back(); -// } else - - if (freeFileSlots.size() > 0) - { + // 4J - removed - don't see how toReplace can ever have anything in here, + // and might not be initialised + // if (toReplace->size() > 0) + // { + // fileSlot = toReplace->back(); + // toReplace->pop_back(); + // } else + + if (freeFileSlots.size() > 0) { fileSlot = freeFileSlots.back(); - freeFileSlots.pop_back(); - } - else - { + freeFileSlots.pop_back(); + } else { fileSlot = totalFileSlots++; writeHeader(); } return fileSlot; - } -void NbtSlotFile::replaceSlot(int slot, std::vector *tags) -{ - toReplace = fileSlotMap[slot]; +void NbtSlotFile::replaceSlot(int slot, std::vector* tags) { + toReplace = fileSlotMap[slot]; fileSlotMap[slot] = new std::vector(); - - AUTO_VAR(itEndTags, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEndTags; it++) - { - CompoundTag *tag = *it; //tags->at(i); + + AUTO_VAR(itEndTags, tags->end()); + for (AUTO_VAR(it, tags->begin()); it != itEndTags; it++) { + CompoundTag* tag = *it; // tags->at(i); byteArray compressed = NbtIo::compress(tag); - if (compressed.length > largest) - { - wchar_t buf[256]; + if (compressed.length > largest) { + wchar_t buf[256]; largest = compressed.length; #ifndef _CONTENT_PACKAGE - swprintf(buf, 256, L"New largest: %I64d (%ls)\n",largest,tag->getString(L"id").c_str() ); - OutputDebugStringW(buf); + swprintf(buf, 256, L"New largest: %I64d (%ls)\n", largest, + tag->getString(L"id").c_str()); + OutputDebugStringW(buf); #endif } @@ -224,67 +201,57 @@ void NbtSlotFile::replaceSlot(int slot, std::vector *tags) short currentSlot = slot + 1; int lastFileSlot = -1; - while (remaining > 0) - { + while (remaining > 0) { int fileSlot = nextFileSlot; fileSlotMap[slot]->push_back(fileSlot); short toWrite = remaining; - if (toWrite > FILE_SLOT_SIZE) - { + if (toWrite > FILE_SLOT_SIZE) { toWrite = FILE_SLOT_SIZE; } remaining -= toWrite; - if (remaining > 0) - { + if (remaining > 0) { nextFileSlot = getFreeSlot(); - } - else - { + } else { nextFileSlot = -1; } seekSlotHeader(fileSlot); - WriteExact(raf, ¤tSlot, sizeof(currentSlot)); - WriteExact(raf, &toWrite, sizeof(toWrite)); - WriteExact(raf, &nextFileSlot, sizeof(nextFileSlot)); - WriteExact(raf, &lastFileSlot, sizeof(lastFileSlot)); + WriteExact(raf, ¤tSlot, sizeof(currentSlot)); + WriteExact(raf, &toWrite, sizeof(toWrite)); + WriteExact(raf, &nextFileSlot, sizeof(nextFileSlot)); + WriteExact(raf, &lastFileSlot, sizeof(lastFileSlot)); seekSlot(fileSlot); - WriteExact(raf, compressed.data + pos, toWrite); + WriteExact(raf, compressed.data + pos, toWrite); - if (remaining > 0) - { + if (remaining > 0) { lastFileSlot = fileSlot; pos += toWrite; currentSlot = -slot - 1; } } - delete[] compressed.data; + delete[] compressed.data; } - - AUTO_VAR(itEndToRep, toReplace->end()); - for (AUTO_VAR(it, toReplace->begin()); it != itEndToRep; it++) - { - int c = *it; //toReplace->at(i); - freeFileSlots.push_back(c); + AUTO_VAR(itEndToRep, toReplace->end()); + for (AUTO_VAR(it, toReplace->begin()); it != itEndToRep; it++) { + int c = *it; // toReplace->at(i); + + freeFileSlots.push_back(c); seekSlotHeader(c); - short zero = 0; - WriteExact(raf, &zero, sizeof(zero)); + short zero = 0; + WriteExact(raf, &zero, sizeof(zero)); } toReplace->clear(); - } -void NbtSlotFile::close() -{ - if (raf != NULL) - { - std::fclose(raf); - raf = NULL; - } +void NbtSlotFile::close() { + if (raf != NULL) { + std::fclose(raf); + raf = NULL; + } } diff --git a/Minecraft.World/IO/NBT/NbtSlotFile.h b/Minecraft.World/IO/NBT/NbtSlotFile.h index 0a613cab2..cf128f4a5 100644 --- a/Minecraft.World/IO/NBT/NbtSlotFile.h +++ b/Minecraft.World/IO/NBT/NbtSlotFile.h @@ -5,8 +5,7 @@ #include "../../Level/Storage/ZonedChunkStorage.h" #include "../../Headers/com.mojang.nbt.h" -class NbtSlotFile -{ +class NbtSlotFile { private: static byteArray READ_BUFFER; @@ -16,9 +15,9 @@ private: static const int FILE_SLOT_HEADER_SIZE = 12; static const int FILE_SLOT_SIZE = 500; - std::FILE *raf; - std::vector **fileSlotMap; - int fileSlotMapLength; + std::FILE* raf; + std::vector** fileSlotMap; + int fileSlotMapLength; std::vector freeFileSlots; int totalFileSlots; static __int64 largest; @@ -33,14 +32,14 @@ private: void seekSlot(int fileSlot); public: - std::vector *readAll(int slot); + std::vector* readAll(int slot); private: - std::vector *toReplace; + std::vector* toReplace; int getFreeSlot(); public: - void replaceSlot(int slot, std::vector *tags); + void replaceSlot(int slot, std::vector* tags); void close(); }; diff --git a/Minecraft.World/IO/NBT/ShortTag.h b/Minecraft.World/IO/NBT/ShortTag.h index 2f04501d6..be04c8c57 100644 --- a/Minecraft.World/IO/NBT/ShortTag.h +++ b/Minecraft.World/IO/NBT/ShortTag.h @@ -1,36 +1,31 @@ #pragma once #include "Tag.h" -class ShortTag : public Tag -{ +class ShortTag : public Tag { public: - short data; - ShortTag(const std::wstring &name) : Tag(name) {} - ShortTag(const std::wstring &name, int data) : Tag(name) {this->data = data; } - - void write(DataOutput *dos) { dos->writeShort(data); } - void load(DataInput *dis) { data = dis->readShort(); } + short data; + ShortTag(const std::wstring& name) : Tag(name) {} + ShortTag(const std::wstring& name, int data) : Tag(name) { + this->data = data; + } - uint8_t getId() { return TAG_Short; } - std::wstring toString() - { - static wchar_t buf[32]; - swprintf(buf,32,L"%d",data); - return std::wstring( buf ); - } + void write(DataOutput* dos) { dos->writeShort(data); } + void load(DataInput* dis) { data = dis->readShort(); } - Tag *copy() - { - return new ShortTag(getName(), data); - } + uint8_t getId() { return TAG_Short; } + std::wstring toString() { + static wchar_t buf[32]; + swprintf(buf, 32, L"%d", data); + return std::wstring(buf); + } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - ShortTag *o = (ShortTag *) obj; - return data == o->data; - } - return false; - } + Tag* copy() { return new ShortTag(getName(), data); } + + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + ShortTag* o = (ShortTag*)obj; + return data == o->data; + } + return false; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/NBT/StringTag.h b/Minecraft.World/IO/NBT/StringTag.h index 17a4a286b..bf5c2dcc9 100644 --- a/Minecraft.World/IO/NBT/StringTag.h +++ b/Minecraft.World/IO/NBT/StringTag.h @@ -1,42 +1,30 @@ #pragma once #include "Tag.h" -class StringTag : public Tag -{ +class StringTag : public Tag { public: - std::wstring data; - StringTag(const std::wstring &name) : Tag(name) {} - StringTag(const std::wstring &name, const std::wstring& data) : Tag(name) {this->data = data; } + std::wstring data; + StringTag(const std::wstring& name) : Tag(name) {} + StringTag(const std::wstring& name, const std::wstring& data) : Tag(name) { + this->data = data; + } - void write(DataOutput *dos) - { - dos->writeUTF(data); - } + void write(DataOutput* dos) { dos->writeUTF(data); } - void load(DataInput *dis) - { - data = dis->readUTF(); - } + void load(DataInput* dis) { data = dis->readUTF(); } - uint8_t getId() { return TAG_String; } + uint8_t getId() { return TAG_String; } - std::wstring toString() - { - return data; - } + std::wstring toString() { return data; } - Tag *copy() - { - return new StringTag(getName(), data); - } + Tag* copy() { return new StringTag(getName(), data); } - bool equals(Tag *obj) - { - if (Tag::equals(obj)) - { - StringTag *o = (StringTag *) obj; - return ((data.empty() && o->data.empty()) || (!data.empty() && data.compare(o->data) == 0)); - } - return false; - } + bool equals(Tag* obj) { + if (Tag::equals(obj)) { + StringTag* o = (StringTag*)obj; + return ((data.empty() && o->data.empty()) || + (!data.empty() && data.compare(o->data) == 0)); + } + return false; + } }; diff --git a/Minecraft.World/IO/NBT/Tag.cpp b/Minecraft.World/IO/NBT/Tag.cpp index 101ba4e28..9e157eef7 100644 --- a/Minecraft.World/IO/NBT/Tag.cpp +++ b/Minecraft.World/IO/NBT/Tag.cpp @@ -12,170 +12,148 @@ #include "ListTag.h" #include "CompoundTag.h" -Tag::Tag(const std::wstring &name) -{ - if (name.empty()) - { - this->name = L""; - } - else - { - this->name = name; - } +Tag::Tag(const std::wstring& name) { + if (name.empty()) { + this->name = L""; + } else { + this->name = name; + } } // 4J - Was Object obj -bool Tag::equals(Tag *obj) -{ - if (obj == NULL )// || !(obj instanceof Tag)) - { - return false; - } - Tag *o = (Tag *) obj; - if (getId() != o->getId()) - { - return false; - } - if ( (name.empty() && !o->name.empty()) || (!name.empty() && o->name.empty())) - { - return false; - } - if (!name.empty() && name.compare(o->name) != 0) - { - return false; - } - return true; +bool Tag::equals(Tag* obj) { + if (obj == NULL) // || !(obj instanceof Tag)) + { + return false; + } + Tag* o = (Tag*)obj; + if (getId() != o->getId()) { + return false; + } + if ((name.empty() && !o->name.empty()) || + (!name.empty() && o->name.empty())) { + return false; + } + if (!name.empty() && name.compare(o->name) != 0) { + return false; + } + return true; } -void Tag::print(std::ostream out) -{ - out << ""; +void Tag::print(std::ostream out) { out << ""; } + +void Tag::print(char* prefix, std::wostream out) { + std::wstring name = getName(); + + out << prefix; + out << getTagName(getId()); + if (name.length() > 0) { + out << L"(\"" << name << L"\")"; + } + out << L": "; + out << toString() << std::endl; } -void Tag::print(char *prefix, std::wostream out) -{ - std::wstring name = getName(); +std::wstring Tag::getName() { return name; } - out << prefix; - out << getTagName(getId()); - if ( name.length() > 0) - { - out << L"(\"" << name << L"\")"; - } - out << L": "; - out << toString() << std::endl; +Tag* Tag::setName(const std::wstring& name) { + this->name = name; + return this; } -std::wstring Tag::getName() -{ - return name; -} +Tag* Tag::readNamedTag(DataInput* dis) { + uint8_t type = dis->readByte(); + if (static_cast(type) == 0) return new EndTag(); -Tag *Tag::setName(const std::wstring& name) -{ - this->name = name; - return this; -} - -Tag *Tag::readNamedTag(DataInput *dis) -{ - uint8_t type = dis->readByte(); - if ( static_cast(type) == 0) return new EndTag(); - - // 4J Stu - readByte can return -1, so if it's that then also mark as the end tag - if(static_cast(type) == 255) - { - app.DebugPrintf("readNamedTag read a type of 255\n"); + // 4J Stu - readByte can return -1, so if it's that then also mark as the + // end tag + if (static_cast(type) == 255) { + app.DebugPrintf("readNamedTag read a type of 255\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - return new EndTag(); - } + return new EndTag(); + } - std::wstring name = dis->readUTF();//new String(bytes, "UTF-8"); + std::wstring name = dis->readUTF(); // new String(bytes, "UTF-8"); - Tag *tag = newTag(type, name); - // short length = dis.readShort(); - // byte[] bytes = new uint8_t[length]; - // dis.readFully(bytes); + Tag* tag = newTag(type, name); + // short length = dis.readShort(); + // byte[] bytes = new uint8_t[length]; + // dis.readFully(bytes); - tag->load(dis); - return tag; + tag->load(dis); + return tag; } -void Tag::writeNamedTag(Tag *tag, DataOutput *dos) -{ - dos->writeByte(tag->getId()); - if (tag->getId() == Tag::TAG_End) return; +void Tag::writeNamedTag(Tag* tag, DataOutput* dos) { + dos->writeByte(tag->getId()); + if (tag->getId() == Tag::TAG_End) return; - // byte[] bytes = tag.getName().getBytes("UTF-8"); - // dos.writeShort(bytes.length); - // dos.write(bytes); - dos->writeUTF(tag->getName()); + // byte[] bytes = tag.getName().getBytes("UTF-8"); + // dos.writeShort(bytes.length); + // dos.write(bytes); + dos->writeUTF(tag->getName()); - tag->write(dos); + tag->write(dos); } -Tag *Tag::newTag(uint8_t type, const std::wstring &name) -{ - switch (type) - { - case TAG_End: - return new EndTag(name); - case TAG_Byte: - return new ByteTag(name); - case TAG_Short: - return new ShortTag(name); - case TAG_Int: - return new IntTag(name); - case TAG_Long: - return new LongTag(name); - case TAG_Float: - return new FloatTag(name); - case TAG_Double: - return new DoubleTag(name); - case TAG_Byte_Array: - return new ByteArrayTag(name); - case TAG_Int_Array: - return new IntArrayTag(name); - case TAG_String: - return new StringTag(name); - case TAG_List: - return new ListTag(name); - case TAG_Compound: - return new CompoundTag(name); - } - return NULL; +Tag* Tag::newTag(uint8_t type, const std::wstring& name) { + switch (type) { + case TAG_End: + return new EndTag(name); + case TAG_Byte: + return new ByteTag(name); + case TAG_Short: + return new ShortTag(name); + case TAG_Int: + return new IntTag(name); + case TAG_Long: + return new LongTag(name); + case TAG_Float: + return new FloatTag(name); + case TAG_Double: + return new DoubleTag(name); + case TAG_Byte_Array: + return new ByteArrayTag(name); + case TAG_Int_Array: + return new IntArrayTag(name); + case TAG_String: + return new StringTag(name); + case TAG_List: + return new ListTag(name); + case TAG_Compound: + return new CompoundTag(name); + } + return NULL; } -const wchar_t *Tag::getTagName(uint8_t type) -{ - switch (type) - { - case TAG_End: - return L"TAG_End"; - case TAG_Byte: - return L"TAG_Byte"; - case TAG_Short: - return L"TAG_Short"; - case TAG_Int: - return L"TAG_Int"; - case TAG_Long: - return L"TAG_Long"; - case TAG_Float: - return L"TAG_Float"; - case TAG_Double: - return L"TAG_Double"; - case TAG_Byte_Array: - return L"TAG_Byte_Array"; - case TAG_Int_Array: - return L"TAG_Int_Array"; - case TAG_String: - return L"TAG_String"; - case TAG_List: - return L"TAG_List"; - case TAG_Compound: - return L"TAG_Compound"; - } - return L"UNKNOWN"; +const wchar_t* Tag::getTagName(uint8_t type) { + switch (type) { + case TAG_End: + return L"TAG_End"; + case TAG_Byte: + return L"TAG_Byte"; + case TAG_Short: + return L"TAG_Short"; + case TAG_Int: + return L"TAG_Int"; + case TAG_Long: + return L"TAG_Long"; + case TAG_Float: + return L"TAG_Float"; + case TAG_Double: + return L"TAG_Double"; + case TAG_Byte_Array: + return L"TAG_Byte_Array"; + case TAG_Int_Array: + return L"TAG_Int_Array"; + case TAG_String: + return L"TAG_String"; + case TAG_List: + return L"TAG_List"; + case TAG_Compound: + return L"TAG_Compound"; + } + return L"UNKNOWN"; } diff --git a/Minecraft.World/IO/NBT/Tag.h b/Minecraft.World/IO/NBT/Tag.h index dc4ab7306..68adeeda2 100644 --- a/Minecraft.World/IO/NBT/Tag.h +++ b/Minecraft.World/IO/NBT/Tag.h @@ -2,10 +2,7 @@ #include #include "../Streams/InputOutputStream.h" - - -class Tag -{ +class Tag { public: static const uint8_t TAG_End = static_cast(0); static const uint8_t TAG_Byte = static_cast(1); @@ -18,28 +15,28 @@ public: static const uint8_t TAG_String = static_cast(8); static const uint8_t TAG_List = static_cast(9); static const uint8_t TAG_Compound = static_cast(10); - static const uint8_t TAG_Int_Array = static_cast(11); + static const uint8_t TAG_Int_Array = static_cast(11); private: std::wstring name; protected: - Tag(const std::wstring &name); + Tag(const std::wstring& name); public: - virtual void write(DataOutput *dos) = 0; - virtual void load(DataInput *dis) = 0; + virtual void write(DataOutput* dos) = 0; + virtual void load(DataInput* dis) = 0; virtual std::wstring toString() = 0; virtual uint8_t getId() = 0; void print(std::ostream out); - void print(char *prefix, std::wostream out); + void print(char* prefix, std::wostream out); std::wstring getName(); - Tag *setName(const std::wstring& name); - static Tag *readNamedTag(DataInput *dis); - static void writeNamedTag(Tag *tag, DataOutput *dos); - static Tag *newTag(uint8_t type, const std::wstring &name); - static const wchar_t *getTagName(uint8_t type); - virtual ~Tag() {} - virtual bool equals(Tag *obj); // 4J Brought forward from 1.2 - virtual Tag *copy() = 0; // 4J Brought foward from 1.2 + Tag* setName(const std::wstring& name); + static Tag* readNamedTag(DataInput* dis); + static void writeNamedTag(Tag* tag, DataOutput* dos); + static Tag* newTag(uint8_t type, const std::wstring& name); + static const wchar_t* getTagName(uint8_t type); + virtual ~Tag() {} + virtual bool equals(Tag* obj); // 4J Brought forward from 1.2 + virtual Tag* copy() = 0; // 4J Brought foward from 1.2 }; diff --git a/Minecraft.World/IO/Streams/Buffer.cpp b/Minecraft.World/IO/Streams/Buffer.cpp index 7fab3bd90..e2705aa1b 100644 --- a/Minecraft.World/IO/Streams/Buffer.cpp +++ b/Minecraft.World/IO/Streams/Buffer.cpp @@ -1,73 +1,61 @@ #include "../../Platform/stdafx.h" #include "Buffer.h" -Buffer::Buffer( unsigned int capacity ) : m_capacity( capacity ), m_position( 0 ), m_limit( capacity ), hasBackingArray( false ) -{ -} +Buffer::Buffer(unsigned int capacity) + : m_capacity(capacity), + m_position(0), + m_limit(capacity), + hasBackingArray(false) {} -//Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. -//This method does not actually erase the data in the buffer, but it is named as if it did because it will most often -//be used in situations in which that might as well be the case. +// Clears this buffer. The position is set to zero, the limit is set to the +// capacity, and the mark is discarded. This method does not actually erase the +// data in the buffer, but it is named as if it did because it will most often +// be used in situations in which that might as well be the case. // -//Returns: -//This buffer -Buffer *Buffer::clear() -{ - m_position = 0; - m_limit = m_capacity; +// Returns: +// This buffer +Buffer* Buffer::clear() { + m_position = 0; + m_limit = m_capacity; - return this; + return this; } -//Sets this buffer's limit. If the position is larger than the new limit then it is set to the new limit. -//If the mark is defined and larger than the new limit then it is discarded. -//Parameters: -//newLimit - The new limit value; must be non-negative and no larger than this buffer's capacity -//Returns: -//This buffer -Buffer *Buffer::limit( unsigned int newLimit ) -{ - assert( newLimit <= m_capacity ); +// Sets this buffer's limit. If the position is larger than the new limit then +// it is set to the new limit. If the mark is defined and larger than the new +// limit then it is discarded. Parameters: newLimit - The new limit value; must +// be non-negative and no larger than this buffer's capacity Returns: This +// buffer +Buffer* Buffer::limit(unsigned int newLimit) { + assert(newLimit <= m_capacity); - m_limit = newLimit; + m_limit = newLimit; - if( m_position > newLimit ) - m_position = newLimit; + if (m_position > newLimit) m_position = newLimit; - return this; + return this; } -unsigned int Buffer::limit() -{ - return m_limit; +unsigned int Buffer::limit() { return m_limit; } + +// Sets this buffer's position. If the mark is defined and larger than the new +// position then it is discarded. Parameters: newPosition - The new position +// value; must be non-negative and no larger than the current limit Returns: +// This buffer +Buffer* Buffer::position(unsigned int newPosition) { + assert(newPosition <= m_limit); + + m_position = newPosition; + + return this; } -//Sets this buffer's position. If the mark is defined and larger than the new position then it is discarded. -//Parameters: -//newPosition - The new position value; must be non-negative and no larger than the current limit -//Returns: -//This buffer -Buffer *Buffer::position( unsigned int newPosition ) -{ - assert( newPosition <= m_limit ); +// Returns this buffer's position. +// Returns: +// The position of this buffer +unsigned int Buffer::position() { return m_position; } - m_position = newPosition; - - return this; -} - -//Returns this buffer's position. -//Returns: -//The position of this buffer -unsigned int Buffer::position() -{ - return m_position; -} - -//Returns the number of elements between the current position and the limit. -//Returns: -//The number of elements remaining in this buffer -unsigned int Buffer::remaining() -{ - return m_limit - m_position; -} \ No newline at end of file +// Returns the number of elements between the current position and the limit. +// Returns: +// The number of elements remaining in this buffer +unsigned int Buffer::remaining() { return m_limit - m_position; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/Buffer.h b/Minecraft.World/IO/Streams/Buffer.h index 1c66257b2..1cd162da9 100644 --- a/Minecraft.World/IO/Streams/Buffer.h +++ b/Minecraft.World/IO/Streams/Buffer.h @@ -1,34 +1,36 @@ #pragma once -//A buffer is a linear, finite sequence of elements of a specific primitive type. Aside from its content, -//the essential properties of a buffer are its capacity, limit, and position: +// A buffer is a linear, finite sequence of elements of a specific primitive +// type. Aside from its content, the essential properties of a buffer are its +// capacity, limit, and position: // -//A buffer's capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes. +// A buffer's capacity is the number of elements it contains. The capacity of a +// buffer is never negative and never changes. // -//A buffer's limit is the index of the first element that should not be read or written. -//A buffer's limit is never negative and is never greater than its capacity. +// A buffer's limit is the index of the first element that should not be read or +// written. A buffer's limit is never negative and is never greater than its +// capacity. // -//A buffer's position is the index of the next element to be read or written. -//A buffer's position is never negative and is never greater than its limit. -class Buffer -{ +// A buffer's position is the index of the next element to be read or written. +// A buffer's position is never negative and is never greater than its limit. +class Buffer { protected: - const unsigned int m_capacity; - unsigned int m_position; - unsigned int m_limit; - unsigned int m_mark; - bool hasBackingArray; + const unsigned int m_capacity; + unsigned int m_position; + unsigned int m_limit; + unsigned int m_mark; + bool hasBackingArray; public: - Buffer( unsigned int capacity ); - virtual ~Buffer() {} + Buffer(unsigned int capacity); + virtual ~Buffer() {} - Buffer *clear(); - Buffer *limit(unsigned int newLimit); - unsigned int limit(); - Buffer *position( unsigned int newPosition ); - unsigned int position(); - unsigned int remaining(); + Buffer* clear(); + Buffer* limit(unsigned int newLimit); + unsigned int limit(); + Buffer* position(unsigned int newPosition); + unsigned int position(); + unsigned int remaining(); - virtual Buffer *flip() = 0; + virtual Buffer* flip() = 0; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/BufferedOutputStream.cpp b/Minecraft.World/IO/Streams/BufferedOutputStream.cpp index 379686138..627c423c6 100644 --- a/Minecraft.World/IO/Streams/BufferedOutputStream.cpp +++ b/Minecraft.World/IO/Streams/BufferedOutputStream.cpp @@ -2,103 +2,97 @@ #include "BufferedOutputStream.h" -//Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size. -//Parameters: -//out - the underlying output stream. -//size - the buffer size. -BufferedOutputStream::BufferedOutputStream(OutputStream *out, int size) -{ - stream = out; - buf = byteArray( size ); - count = 0; +// Creates a new buffered output stream to write data to the specified +// underlying output stream with the specified buffer size. Parameters: out - +// the underlying output stream. size - the buffer size. +BufferedOutputStream::BufferedOutputStream(OutputStream* out, int size) { + stream = out; + buf = byteArray(size); + count = 0; } -BufferedOutputStream::~BufferedOutputStream() -{ - //4jcraft, changed to [], deallocates internal buffer - //TODO: ArrayWithLength.h doesnt have a destructor. - //this wouldnt need to be done manually. - //but for some reason the destructor is commented out in the source code? - delete[] buf.data; +BufferedOutputStream::~BufferedOutputStream() { + // 4jcraft, changed to [], deallocates internal buffer + // TODO: ArrayWithLength.h doesnt have a destructor. + // this wouldnt need to be done manually. + // but for some reason the destructor is commented out in the source code? + delete[] buf.data; } -//Flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream. -void BufferedOutputStream::flush() -{ - if (stream == NULL) - { - app.DebugPrintf("BufferedOutputStream::flush() called but underlying stream is NULL\n"); - return; - } +// Flushes this buffered output stream. This forces any buffered output bytes to +// be written out to the underlying output stream. +void BufferedOutputStream::flush() { + if (stream == NULL) { + app.DebugPrintf( + "BufferedOutputStream::flush() called but underlying stream is " + "NULL\n"); + return; + } - if (count > 0) - { - stream->write( buf, 0, count ); - count = 0; - } + if (count > 0) { + stream->write(buf, 0, count); + count = 0; + } } -//Closes this output stream and releases any system resources associated with the stream. -//The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream. -void BufferedOutputStream::close() -{ - flush(); - if (stream == NULL) - { - app.DebugPrintf("BufferedOutputStream::close() called but underlying stream is NULL\n"); - return; - } - stream->close(); +// Closes this output stream and releases any system resources associated with +// the stream. The close method of FilterOutputStream calls its flush method, +// and then calls the close method of its underlying output stream. +void BufferedOutputStream::close() { + flush(); + if (stream == NULL) { + app.DebugPrintf( + "BufferedOutputStream::close() called but underlying stream is " + "NULL\n"); + return; + } + stream->close(); } -//Writes len bytes from the specified byte array starting at offset off to this buffered output stream. -//Ordinarily this method stores bytes from the given array into this stream's buffer, flushing the buffer to the -//underlying output stream as needed. If the requested length is at least as large as this stream's buffer, however, -//then this method will flush the buffer and write the bytes directly to the underlying output stream. -//Thus redundant BufferedOutputStreams will not copy data unnecessarily. +// Writes len bytes from the specified byte array starting at offset off to this +// buffered output stream. Ordinarily this method stores bytes from the given +// array into this stream's buffer, flushing the buffer to the underlying output +// stream as needed. If the requested length is at least as large as this +// stream's buffer, however, then this method will flush the buffer and write +// the bytes directly to the underlying output stream. Thus redundant +// BufferedOutputStreams will not copy data unnecessarily. // -//Overrides: -//write in class FilterOutputStream -//Parameters: -//b - the data. -//off - the start offset in the data. -//len - the number of bytes to write. -void BufferedOutputStream::write(byteArray b, unsigned int offset, unsigned int length) -{ - // Over the length of what we can store in our buffer - just flush the buffer and output directly - if( length >= buf.length ) - { - flush(); - stream->write(b, offset, length); - } - else - { - for(unsigned int i = 0; i < length; i++ ) - { - write( static_cast(b[offset+i])); - } - } +// Overrides: +// write in class FilterOutputStream +// Parameters: +// b - the data. +// off - the start offset in the data. +// len - the number of bytes to write. +void BufferedOutputStream::write(byteArray b, unsigned int offset, + unsigned int length) { + // Over the length of what we can store in our buffer - just flush the + // buffer and output directly + if (length >= buf.length) { + flush(); + stream->write(b, offset, length); + } else { + for (unsigned int i = 0; i < length; i++) { + write(static_cast(b[offset + i])); + } + } } -//Writes b.length bytes to this output stream. -//The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length. +// Writes b.length bytes to this output stream. +// The write method of FilterOutputStream calls its write method of three +// arguments with the arguments b, 0, and b.length. // -//Note that this method does not call the one-argument write method of its underlying stream with the single argument b. -void BufferedOutputStream::write(byteArray b) -{ - write( b, 0, b.length ); -} +// Note that this method does not call the one-argument write method of its +// underlying stream with the single argument b. +void BufferedOutputStream::write(byteArray b) { write(b, 0, b.length); } -//Writes the specified byte to this buffered output stream. -//Overrides: -//write in class FilterOutputStream -//Parameters: -//b - the byte to be written. -void BufferedOutputStream::write(unsigned int b) -{ - buf[count++] = (uint8_t) b; - if( count == buf.length ) - { - flush(); - } +// Writes the specified byte to this buffered output stream. +// Overrides: +// write in class FilterOutputStream +// Parameters: +// b - the byte to be written. +void BufferedOutputStream::write(unsigned int b) { + buf[count++] = (uint8_t)b; + if (count == buf.length) { + flush(); + } } diff --git a/Minecraft.World/IO/Streams/BufferedOutputStream.h b/Minecraft.World/IO/Streams/BufferedOutputStream.h index 19c79d6c6..286879b33 100644 --- a/Minecraft.World/IO/Streams/BufferedOutputStream.h +++ b/Minecraft.World/IO/Streams/BufferedOutputStream.h @@ -2,22 +2,21 @@ #include "OutputStream.h" -class BufferedOutputStream : public OutputStream -{ +class BufferedOutputStream : public OutputStream { private: - OutputStream *stream; + OutputStream* stream; -protected : - byteArray buf; // The internal buffer where data is stored. - unsigned int count; // The number of valid bytes in the buffer. +protected: + byteArray buf; // The internal buffer where data is stored. + unsigned int count; // The number of valid bytes in the buffer. public: - BufferedOutputStream(OutputStream *out, int size); - ~BufferedOutputStream(); + BufferedOutputStream(OutputStream* out, int size); + ~BufferedOutputStream(); - virtual void flush(); - virtual void close(); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void write(byteArray b); - virtual void write(unsigned int b); + virtual void flush(); + virtual void close(); + virtual void write(byteArray b, unsigned int offset, unsigned int length); + virtual void write(byteArray b); + virtual void write(unsigned int b); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/BufferedReader.cpp b/Minecraft.World/IO/Streams/BufferedReader.cpp index 3b1038a9d..ab8996790 100644 --- a/Minecraft.World/IO/Streams/BufferedReader.cpp +++ b/Minecraft.World/IO/Streams/BufferedReader.cpp @@ -2,172 +2,159 @@ #include "BufferedReader.h" -//Creates a buffering character-input stream that uses a default-sized input buffer. -//Parameters: -//in - A Reader -BufferedReader::BufferedReader( Reader *in ) : reader( in ), readMark( 0 ), bufferedMark( 0 ), eofReached( false ) -{ - bufferSize = 64; - buffer = new wchar_t[bufferSize]; - memset( buffer,0,sizeof(wchar_t)*bufferSize); - bufferMore(); +// Creates a buffering character-input stream that uses a default-sized input +// buffer. Parameters: in - A Reader +BufferedReader::BufferedReader(Reader* in) + : reader(in), readMark(0), bufferedMark(0), eofReached(false) { + bufferSize = 64; + buffer = new wchar_t[bufferSize]; + memset(buffer, 0, sizeof(wchar_t) * bufferSize); + bufferMore(); } -BufferedReader::~BufferedReader() -{ - delete[] buffer; +BufferedReader::~BufferedReader() { delete[] buffer; } + +void BufferedReader::bufferMore() { + // Don't buffer more unless we are going to read at least twice as much as + // what is already left + if (bufferedMark - readMark > (BUFFER_MORE_AMOUNT / 2)) return; + + if (bufferSize < (bufferedMark + BUFFER_MORE_AMOUNT)) { + // Enlarge the buffer + wchar_t* temp = new wchar_t[bufferSize * 2]; + memset(temp, 0, sizeof(wchar_t) * bufferSize * 2); + std::copy(buffer, buffer + bufferSize, temp); + + delete[] buffer; + buffer = temp; + bufferSize = bufferSize * 2; + } + + int value = 0; + unsigned int newCharsBuffered = 0; + while (newCharsBuffered < BUFFER_MORE_AMOUNT && + (value = reader->read()) != -1) { + buffer[bufferedMark++] = value; + newCharsBuffered++; + } } -void BufferedReader::bufferMore() -{ - // Don't buffer more unless we are going to read at least twice as much as what is already left - if( bufferedMark - readMark > (BUFFER_MORE_AMOUNT / 2) ) - return; +// Closes the stream and releases any system resources associated with it. Once +// the stream has been closed, further read(), ready(), mark(), reset(), or +// skip() invocations will throw an IOException. Closing a previously closed +// stream has no effect. +void BufferedReader::close() { reader->close(); } - if( bufferSize < (bufferedMark + BUFFER_MORE_AMOUNT) ) - { - // Enlarge the buffer - wchar_t *temp = new wchar_t[bufferSize * 2]; - memset( temp,0,sizeof(wchar_t)*bufferSize*2); - std::copy( buffer, buffer+bufferSize, temp ); +// Reads a single character. +// Returns: +// The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or +// -1 if the end of the stream has been reached +int BufferedReader::read() { + // We should have buffered at least as much as we have read + assert(bufferedMark >= readMark); - delete[] buffer; - buffer = temp; - bufferSize = bufferSize * 2; - } + if (bufferedMark == readMark) { + int value = reader->read(); + if (value == -1) return -1; - int value = 0; - unsigned int newCharsBuffered = 0; - while( newCharsBuffered < BUFFER_MORE_AMOUNT && (value = reader->read() ) != -1 ) - { - buffer[bufferedMark++] = value; - newCharsBuffered++; - } + buffer[bufferedMark++] = value; + + bufferMore(); + } + + return buffer[readMark++]; } -//Closes the stream and releases any system resources associated with it. Once the stream has been closed, -//further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect. -void BufferedReader::close() -{ - reader->close(); -} - -//Reads a single character. -//Returns: -//The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached -int BufferedReader::read() -{ - // We should have buffered at least as much as we have read - assert( bufferedMark >= readMark ); - - if( bufferedMark == readMark ) - { - int value = reader->read(); - if( value == -1 ) - return -1; - - buffer[bufferedMark++] = value; - - bufferMore(); - } - - return buffer[readMark++]; -} - -//Reads characters into a portion of an array. -//This method implements the general contract of the corresponding read method of the Reader class. -//As an additional convenience, it attempts to read as many characters as possible by repeatedly invoking the read method -//of the underlying stream. This iterated read continues until one of the following conditions becomes true: +// Reads characters into a portion of an array. +// This method implements the general contract of the corresponding read method +// of the Reader class. As an additional convenience, it attempts to read as +// many characters as possible by repeatedly invoking the read method of the +// underlying stream. This iterated read continues until one of the following +// conditions becomes true: // -//The specified number of characters have been read, -//The read method of the underlying stream returns -1, indicating end-of-file, or -//The ready method of the underlying stream returns false, indicating that further input requests would block. -//If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. -//Otherwise this method returns the number of characters actually read. -//Subclasses of this class are encouraged, but not required, to attempt to read as many characters as possible in the same fashion. +// The specified number of characters have been read, +// The read method of the underlying stream returns -1, indicating end-of-file, +// or The ready method of the underlying stream returns false, indicating that +// further input requests would block. If the first read on the underlying +// stream returns -1 to indicate end-of-file then this method returns -1. +// Otherwise this method returns the number of characters actually read. +// Subclasses of this class are encouraged, but not required, to attempt to read +// as many characters as possible in the same fashion. // -//Ordinarily this method takes characters from this stream's character buffer, filling it from the underlying stream as necessary. -//If, however, the buffer is empty, the mark is not valid, and the requested length is at least as large as the buffer, -//then this method will read characters directly from the underlying stream into the given array. -//Thus redundant BufferedReaders will not copy data unnecessarily. +// Ordinarily this method takes characters from this stream's character buffer, +// filling it from the underlying stream as necessary. If, however, the buffer +// is empty, the mark is not valid, and the requested length is at least as +// large as the buffer, then this method will read characters directly from the +// underlying stream into the given array. Thus redundant BufferedReaders will +// not copy data unnecessarily. // -//Parameters: -//cbuf - Destination buffer -//off - Offset at which to start storing characters -//len - Maximum number of characters to read -//Returns: -//The number of characters read, or -1 if the end of the stream has been reached -int BufferedReader::read(wchar_t cbuf[], unsigned int off, unsigned int len) -{ - if( bufferSize < (bufferedMark + len) ) - { - // Enlarge the buffer - wchar_t *temp = new wchar_t[bufferSize * 2]; - memset( temp,0,sizeof(wchar_t)*bufferSize*2); - std::copy( buffer, buffer+bufferSize, temp ); +// Parameters: +// cbuf - Destination buffer +// off - Offset at which to start storing characters +// len - Maximum number of characters to read +// Returns: +// The number of characters read, or -1 if the end of the stream has been +// reached +int BufferedReader::read(wchar_t cbuf[], unsigned int off, unsigned int len) { + if (bufferSize < (bufferedMark + len)) { + // Enlarge the buffer + wchar_t* temp = new wchar_t[bufferSize * 2]; + memset(temp, 0, sizeof(wchar_t) * bufferSize * 2); + std::copy(buffer, buffer + bufferSize, temp); - delete[] buffer; - buffer = temp; - bufferSize = bufferSize * 2; - } - - unsigned int charsRead = 0; - while( charsRead < len && readMark <= bufferedMark ) - { - cbuf[off + charsRead] = buffer[ readMark++ ]; - charsRead++; - } + delete[] buffer; + buffer = temp; + bufferSize = bufferSize * 2; + } - int value = 0; - while( charsRead < len && (value = reader->read() ) != -1 ) - { - buffer[bufferedMark++] = value; - cbuf[off+charsRead] = value; - charsRead++; - readMark++; - } + unsigned int charsRead = 0; + while (charsRead < len && readMark <= bufferedMark) { + cbuf[off + charsRead] = buffer[readMark++]; + charsRead++; + } - bufferMore(); + int value = 0; + while (charsRead < len && (value = reader->read()) != -1) { + buffer[bufferedMark++] = value; + cbuf[off + charsRead] = value; + charsRead++; + readMark++; + } - return charsRead; + bufferMore(); + + return charsRead; } -//Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), -//or a carriage return followed immediately by a linefeed. -//Returns: -//A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached -std::wstring BufferedReader::readLine() -{ - std::wstring output = L""; - bool newLineCharFound = false; +// Reads a line of text. A line is considered to be terminated by any one of a +// line feed ('\n'), a carriage return ('\r'), or a carriage return followed +// immediately by a linefeed. Returns: A String containing the contents of the +// line, not including any line-termination characters, or null if the end of +// the stream has been reached +std::wstring BufferedReader::readLine() { + std::wstring output = L""; + bool newLineCharFound = false; - while( readMark < bufferedMark ) - { - wchar_t value = buffer[readMark++]; + while (readMark < bufferedMark) { + wchar_t value = buffer[readMark++]; - if( !newLineCharFound ) - { - if( ( value == '\n') || ( value == '\r') ) - { - newLineCharFound = true; - } - else - { - output.push_back(value); - } - } - else - { - if( ( value != '\n') && ( value != '\r') ) - { - readMark--; // Move back the read mark on char so we get this char again next time - break; - } - } + if (!newLineCharFound) { + if ((value == '\n') || (value == '\r')) { + newLineCharFound = true; + } else { + output.push_back(value); + } + } else { + if ((value != '\n') && (value != '\r')) { + readMark--; // Move back the read mark on char so we get this + // char again next time + break; + } + } - // This will only actually read more from the stream if we have less than half of the amount that - // will be added left to read - bufferMore(); - } - return output; + // This will only actually read more from the stream if we have less + // than half of the amount that will be added left to read + bufferMore(); + } + return output; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/BufferedReader.h b/Minecraft.World/IO/Streams/BufferedReader.h index 780a76b09..85f004af2 100644 --- a/Minecraft.World/IO/Streams/BufferedReader.h +++ b/Minecraft.World/IO/Streams/BufferedReader.h @@ -2,26 +2,25 @@ #include "Reader.h" -class BufferedReader : public Reader -{ +class BufferedReader : public Reader { private: - Reader *reader; - wchar_t *buffer; - - unsigned int readMark; - unsigned int bufferedMark; - unsigned int bufferSize; - bool eofReached; + Reader* reader; + wchar_t* buffer; - static const unsigned int BUFFER_MORE_AMOUNT = 64; - void bufferMore(); + unsigned int readMark; + unsigned int bufferedMark; + unsigned int bufferSize; + bool eofReached; + + static const unsigned int BUFFER_MORE_AMOUNT = 64; + void bufferMore(); public: - BufferedReader( Reader *in ); - virtual ~BufferedReader(); + BufferedReader(Reader* in); + virtual ~BufferedReader(); - virtual void close(); - virtual int read(); - virtual int read(wchar_t cbuf[], unsigned int off, unsigned int len); - std::wstring readLine(); + virtual void close(); + virtual int read(); + virtual int read(wchar_t cbuf[], unsigned int off, unsigned int len); + std::wstring readLine(); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/ByteArrayInputStream.cpp b/Minecraft.World/IO/Streams/ByteArrayInputStream.cpp index b23fdb3b2..18bc5b1f3 100644 --- a/Minecraft.World/IO/Streams/ByteArrayInputStream.cpp +++ b/Minecraft.World/IO/Streams/ByteArrayInputStream.cpp @@ -2,117 +2,110 @@ #include "InputOutputStream.h" -//Creates ByteArrayInputStream that uses buf as its buffer array. The initial value of pos is offset and -//the initial value of count is the minimum of offset+length and buf.length. The buffer array is not copied. -//The buffer's mark is set to the specified offset. -//Parameters: -//buf - the input buffer. -//offset - the offset in the buffer of the first byte to read. -//length - the maximum number of bytes to read from the buffer. -ByteArrayInputStream::ByteArrayInputStream(byteArray buf, unsigned int offset, unsigned int length) - : pos( offset ), count( std::min( offset+length, buf.length ) ), mark( offset ) -{ - this->buf = buf; +// Creates ByteArrayInputStream that uses buf as its buffer array. The initial +// value of pos is offset and the initial value of count is the minimum of +// offset+length and buf.length. The buffer array is not copied. The buffer's +// mark is set to the specified offset. Parameters: buf - the input buffer. +// offset - the offset in the buffer of the first byte to read. +// length - the maximum number of bytes to read from the buffer. +ByteArrayInputStream::ByteArrayInputStream(byteArray buf, unsigned int offset, + unsigned int length) + : pos(offset), count(std::min(offset + length, buf.length)), mark(offset) { + this->buf = buf; } -//Creates a ByteArrayInputStream so that it uses buf as its buffer array. The buffer array is not copied. -//The initial value of pos is 0 and the initial value of count is the length of buf. -//Parameters: -//buf - the input buffer. +// Creates a ByteArrayInputStream so that it uses buf as its buffer array. The +// buffer array is not copied. The initial value of pos is 0 and the initial +// value of count is the length of buf. Parameters: buf - the input buffer. ByteArrayInputStream::ByteArrayInputStream(byteArray buf) - : pos( 0 ), count( buf.length ), mark( 0 ) -{ - this->buf = buf; + : pos(0), count(buf.length), mark(0) { + this->buf = buf; } -//Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. -//If no byte is available because the end of the stream has been reached, the value -1 is returned. -//This read method cannot block. -//Returns: -//the next byte of data, or -1 if the end of the stream has been reached. -int ByteArrayInputStream::read() -{ - if( pos >= count ) - return -1; - else - return static_cast(buf[pos++]); +// Reads the next byte of data from this input stream. The value byte is +// returned as an int in the range 0 to 255. If no byte is available because the +// end of the stream has been reached, the value -1 is returned. This read +// method cannot block. Returns: the next byte of data, or -1 if the end of the +// stream has been reached. +int ByteArrayInputStream::read() { + if (pos >= count) + return -1; + else + return static_cast(buf[pos++]); } -//Reads some number of bytes from the input stream and stores them into the buffer array b. -//The number of bytes actually read is returned as an integer. This method blocks until input data is available, -//end of file is detected, or an exception is thrown. -//If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. -//If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, -//at least one byte is read and stored into b. +// Reads some number of bytes from the input stream and stores them into the +// buffer array b. The number of bytes actually read is returned as an integer. +// This method blocks until input data is available, end of file is detected, or +// an exception is thrown. If the length of b is zero, then no bytes are read +// and 0 is returned; otherwise, there is an attempt to read at least one byte. +// If no byte is available because the stream is at the end of the file, the +// value -1 is returned; otherwise, at least one byte is read and stored into b. // -//The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, -//at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], -//leaving elements b[k] through b[b.length-1] unaffected. +// The first byte read is stored into element b[0], the next one into b[1], and +// so on. The number of bytes read is, at most, equal to the length of b. Let k +// be the number of bytes actually read; these bytes will be stored in elements +// b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected. // -//The read(b) method for class InputStream has the same effect as: +// The read(b) method for class InputStream has the same effect as: // -// read(b, 0, b.length) -//Parameters: -//b - the buffer into which the data is read. -//Returns: -//the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached. -int ByteArrayInputStream::read(byteArray b) -{ - return read( b, 0, b.length ); +// read(b, 0, b.length) +// Parameters: +// b - the buffer into which the data is read. +// Returns: +// the total number of bytes read into the buffer, or -1 is there is no more +// data because the end of the stream has been reached. +int ByteArrayInputStream::read(byteArray b) { return read(b, 0, b.length); } + +// Reads up to len bytes of data into an array of bytes from this input stream. +// If pos equals count, then -1 is returned to indicate end of file. Otherwise, +// the number k of bytes read is equal to the smaller of len and count-pos. If k +// is positive, then bytes buf[pos] through buf[pos+k-1] are copied into b[off] +// through b[off+k-1] in the manner performed by System.arraycopy. The value k +// is added into pos and k is returned. This read method cannot block. +// Parameters: +// b - the buffer into which the data is read. +// off - the start offset in the destination array b +// len - the maximum number of bytes read. +// Returns: +// the total number of bytes read into the buffer, or -1 if there is no more +// data because the end of the stream has been reached. +int ByteArrayInputStream::read(byteArray b, unsigned int offset, + unsigned int length) { + if (pos == count) return -1; + + int k = std::min(length, count - pos); + XMemCpy(&b[offset], &buf[pos], k); + // std::copy( buf->data+pos, buf->data+pos+k, b->data + offset ); // Or this + // instead? + + pos += k; + + return k; } -//Reads up to len bytes of data into an array of bytes from this input stream. If pos equals count, -//then -1 is returned to indicate end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos. -//If k is positive, then bytes buf[pos] through buf[pos+k-1] are copied into b[off] through b[off+k-1] in the manner -//performed by System.arraycopy. The value k is added into pos and k is returned. -//This read method cannot block. -//Parameters: -//b - the buffer into which the data is read. -//off - the start offset in the destination array b -//len - the maximum number of bytes read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. -int ByteArrayInputStream::read(byteArray b, unsigned int offset, unsigned int length) -{ - if( pos == count ) - return -1; +// Closing a ByteArrayInputStream has no effect. +// The methods in this class can be called after the stream has been closed +// without generating an IOException. +void ByteArrayInputStream::close() { return; } - int k = std::min( length, count-pos ); - XMemCpy( &b[offset], &buf[pos], k ); - //std::copy( buf->data+pos, buf->data+pos+k, b->data + offset ); // Or this instead? +// Skips n bytes of input from this input stream. Fewer bytes might be skipped +// if the end of the input stream is reached. The actual number k of bytes to be +// skipped is equal to the smaller of n and count-pos. The value k is added into +// pos and k is returned. Overrides: skip in class InputStream Parameters: n - +// the number of bytes to be skipped. Returns: the actual number of bytes +// skipped. +__int64 ByteArrayInputStream::skip(__int64 n) { + int newPos = pos + n; - pos += k; + if (newPos > count) newPos = count; - return k; + int k = newPos - pos; + pos = newPos; + + return k; } -//Closing a ByteArrayInputStream has no effect. -//The methods in this class can be called after the stream has been closed without generating an IOException. -void ByteArrayInputStream::close() -{ - return; -} - -//Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached. The actual number k of bytes to be skipped is equal to the smaller of n and count-pos. The value k is added into pos and k is returned. -//Overrides: -//skip in class InputStream -//Parameters: -//n - the number of bytes to be skipped. -//Returns: -//the actual number of bytes skipped. -__int64 ByteArrayInputStream::skip(__int64 n) -{ - int newPos = pos + n; - - if(newPos > count) newPos = count; - - int k = newPos - pos; - pos = newPos; - - return k; -} - -ByteArrayInputStream::~ByteArrayInputStream() -{ - if(buf.data != NULL) delete [] buf.data; +ByteArrayInputStream::~ByteArrayInputStream() { + if (buf.data != NULL) delete[] buf.data; } diff --git a/Minecraft.World/IO/Streams/ByteArrayInputStream.h b/Minecraft.World/IO/Streams/ByteArrayInputStream.h index e74b1cf78..7c09c99f6 100644 --- a/Minecraft.World/IO/Streams/ByteArrayInputStream.h +++ b/Minecraft.World/IO/Streams/ByteArrayInputStream.h @@ -3,24 +3,33 @@ #include "InputStream.h" -class ByteArrayInputStream : public InputStream -{ +class ByteArrayInputStream : public InputStream { protected: - byteArray buf; //An array of bytes that was provided by the creator of the stream. - unsigned int count; //The index one greater than the last valid character in the input stream buffer. - unsigned int mark; //The currently marked position in the stream. - unsigned int pos; //The index of the next character to read from the input stream buffer. + byteArray buf; // An array of bytes that was provided by the creator of the + // stream. + unsigned int count; // The index one greater than the last valid character + // in the input stream buffer. + unsigned int mark; // The currently marked position in the stream. + unsigned int pos; // The index of the next character to read from the input + // stream buffer. public: - ByteArrayInputStream(byteArray buf, unsigned int offset, unsigned int length); - ByteArrayInputStream(byteArray buf); - virtual ~ByteArrayInputStream(); - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual __int64 skip(__int64 n); + ByteArrayInputStream(byteArray buf, unsigned int offset, + unsigned int length); + ByteArrayInputStream(byteArray buf); + virtual ~ByteArrayInputStream(); + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual __int64 skip(__int64 n); - // 4J Stu Added - Sometimes we don't want to delete the data on destroying this - void reset() { buf = byteArray(); count = 0; mark = 0; pos = 0; } + // 4J Stu Added - Sometimes we don't want to delete the data on destroying + // this + void reset() { + buf = byteArray(); + count = 0; + mark = 0; + pos = 0; + } }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/ByteArrayOutputStream.cpp b/Minecraft.World/IO/Streams/ByteArrayOutputStream.cpp index c51d433a3..2a9ba4297 100644 --- a/Minecraft.World/IO/Streams/ByteArrayOutputStream.cpp +++ b/Minecraft.World/IO/Streams/ByteArrayOutputStream.cpp @@ -2,79 +2,69 @@ #include "ByteArrayOutputStream.h" -// Creates a new byte array output stream. The buffer capacity is initially 32 bytes, though its size increases if necessary. -ByteArrayOutputStream::ByteArrayOutputStream() -{ - count = 0; - buf = byteArray( 32 ); +// Creates a new byte array output stream. The buffer capacity is initially 32 +// bytes, though its size increases if necessary. +ByteArrayOutputStream::ByteArrayOutputStream() { + count = 0; + buf = byteArray(32); } -//Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes. -//Parameters: -//size - the initial size. -ByteArrayOutputStream::ByteArrayOutputStream(unsigned int size) -{ - count = 0; - buf = byteArray( size ); +// Creates a new byte array output stream, with a buffer capacity of the +// specified size, in bytes. Parameters: size - the initial size. +ByteArrayOutputStream::ByteArrayOutputStream(unsigned int size) { + count = 0; + buf = byteArray(size); } -ByteArrayOutputStream::~ByteArrayOutputStream() -{ - if (buf.data != NULL) - delete[] buf.data; +ByteArrayOutputStream::~ByteArrayOutputStream() { + if (buf.data != NULL) delete[] buf.data; } -//Writes the specified byte to this byte array output stream. -//Parameters: -//b - the byte to be written. -void ByteArrayOutputStream::write(unsigned int b) -{ - // If we will fill the buffer we need to make it bigger - if( count + 1 >= buf.length ) - buf.resize( buf.length * 2 ); +// Writes the specified byte to this byte array output stream. +// Parameters: +// b - the byte to be written. +void ByteArrayOutputStream::write(unsigned int b) { + // If we will fill the buffer we need to make it bigger + if (count + 1 >= buf.length) buf.resize(buf.length * 2); - buf[count] = (uint8_t) b; - count++; + buf[count] = (uint8_t)b; + count++; } // Writes b.length bytes from the specified byte array to this output stream. -//The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length). -void ByteArrayOutputStream::write(byteArray b) -{ - write(b, 0, b.length); +// The general contract for write(b) is that it should have exactly the same +// effect as the call write(b, 0, b.length). +void ByteArrayOutputStream::write(byteArray b) { write(b, 0, b.length); } + +// Writes len bytes from the specified byte array starting at offset off to this +// byte array output stream. Parameters: b - the data. off - the start offset in +// the data. len - the number of bytes to write. +void ByteArrayOutputStream::write(byteArray b, unsigned int offset, + unsigned int length) { + assert(b.length >= offset + length); + + // If we will fill the buffer we need to make it bigger + if (count + length >= buf.length) + buf.resize(std::max(count + length + 1, buf.length * 2)); + + XMemCpy(&buf[count], &b[offset], length); + // std::copy( b->data+offset, b->data+offset+length, buf->data + count ); // + // Or this instead? + + count += length; } -//Writes len bytes from the specified byte array starting at offset off to this byte array output stream. -//Parameters: -//b - the data. -//off - the start offset in the data. -//len - the number of bytes to write. -void ByteArrayOutputStream::write(byteArray b, unsigned int offset, unsigned int length) -{ - assert( b.length >= offset + length ); +// Closing a ByteArrayOutputStream has no effect. +// The methods in this class can be called after the stream has been closed +// without generating an IOException. +void ByteArrayOutputStream::close() {} - // If we will fill the buffer we need to make it bigger - if( count + length >= buf.length ) - buf.resize( std::max( count + length + 1, buf.length * 2 ) ); - - XMemCpy( &buf[count], &b[offset], length ); - //std::copy( b->data+offset, b->data+offset+length, buf->data + count ); // Or this instead? - - count += length; -} - -//Closing a ByteArrayOutputStream has no effect. -//The methods in this class can be called after the stream has been closed without generating an IOException. -void ByteArrayOutputStream::close() -{ -} - -//Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it. -//Returns: -//the current contents of this output stream, as a byte array. -byteArray ByteArrayOutputStream::toByteArray() -{ - byteArray out(count); - memcpy(out.data,buf.data,count); - return out; +// Creates a newly allocated byte array. Its size is the current size of this +// output stream and the valid contents of the buffer have been copied into it. +// Returns: +// the current contents of this output stream, as a byte array. +byteArray ByteArrayOutputStream::toByteArray() { + byteArray out(count); + memcpy(out.data, buf.data, count); + return out; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/ByteArrayOutputStream.h b/Minecraft.World/IO/Streams/ByteArrayOutputStream.h index 9e0b498d7..e13fc201b 100644 --- a/Minecraft.World/IO/Streams/ByteArrayOutputStream.h +++ b/Minecraft.World/IO/Streams/ByteArrayOutputStream.h @@ -2,28 +2,27 @@ #include "OutputStream.h" -class ByteArrayOutputStream : public OutputStream -{ -// Note - when actually implementing, byteArray will need to grow as data is written +class ByteArrayOutputStream : public OutputStream { + // Note - when actually implementing, byteArray will need to grow as data is + // written public: - byteArray buf; //The buffer where data is stored. + byteArray buf; // The buffer where data is stored. protected: - unsigned int count; //The number of valid bytes in the buffer. + unsigned int count; // The number of valid bytes in the buffer. public: - ByteArrayOutputStream(); - ByteArrayOutputStream(unsigned int size); - virtual ~ByteArrayOutputStream(); + ByteArrayOutputStream(); + ByteArrayOutputStream(unsigned int size); + virtual ~ByteArrayOutputStream(); - virtual void flush() {} - virtual void write(unsigned int b); - virtual void write(byteArray b); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual byteArray toByteArray(); + virtual void flush() {} + virtual void write(unsigned int b); + virtual void write(byteArray b); + virtual void write(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual byteArray toByteArray(); - void reset() { count = 0; } - unsigned int size() { return count; } - + void reset() { count = 0; } + unsigned int size() { return count; } }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/ByteBuffer.cpp b/Minecraft.World/IO/Streams/ByteBuffer.cpp index 51a391e7f..09076fbca 100644 --- a/Minecraft.World/IO/Streams/ByteBuffer.cpp +++ b/Minecraft.World/IO/Streams/ByteBuffer.cpp @@ -4,475 +4,442 @@ #include "FloatBuffer.h" #include "ByteBuffer.h" -ByteBuffer::ByteBuffer( unsigned int capacity ) : Buffer( capacity ) -{ - hasBackingArray = false; - buffer = new uint8_t[capacity]; - memset( buffer,0,sizeof(uint8_t)*capacity); - byteOrder = BIGENDIAN; +ByteBuffer::ByteBuffer(unsigned int capacity) : Buffer(capacity) { + hasBackingArray = false; + buffer = new uint8_t[capacity]; + memset(buffer, 0, sizeof(uint8_t) * capacity); + byteOrder = BIGENDIAN; } -//Allocates a new direct byte buffer. -//The new buffer's position will be zero, its limit will be its capacity, and its mark will be undefined. Whether or not it has a backing array is unspecified. +// Allocates a new direct byte buffer. +// The new buffer's position will be zero, its limit will be its capacity, and +// its mark will be undefined. Whether or not it has a backing array is +// unspecified. // -//Parameters: -//capacity - The new buffer's capacity, in bytes -//Returns: -//The new byte buffer -ByteBuffer *ByteBuffer::allocateDirect(int capacity) -{ - return new ByteBuffer(capacity); +// Parameters: +// capacity - The new buffer's capacity, in bytes +// Returns: +// The new byte buffer +ByteBuffer* ByteBuffer::allocateDirect(int capacity) { + return new ByteBuffer(capacity); } - -ByteBuffer::ByteBuffer( unsigned int capacity, uint8_t *backingArray ) : Buffer( capacity ) -{ - hasBackingArray = true; - buffer = backingArray; +ByteBuffer::ByteBuffer(unsigned int capacity, uint8_t* backingArray) + : Buffer(capacity) { + hasBackingArray = true; + buffer = backingArray; } -ByteBuffer::~ByteBuffer() -{ - if( !hasBackingArray ) - delete[] buffer; +ByteBuffer::~ByteBuffer() { + if (!hasBackingArray) delete[] buffer; } -//Wraps a byte array into a buffer. -//The new buffer will be backed by the given uint8_t array; that is, modifications to the buffer will cause the array -//to be modified and vice versa. The new buffer's capacity and limit will be array.length, its position will be zero, -//and its mark will be undefined. Its backing array will be the given array, and its array offset will be zero. +// Wraps a byte array into a buffer. +// The new buffer will be backed by the given uint8_t array; that is, +// modifications to the buffer will cause the array to be modified and vice +// versa. The new buffer's capacity and limit will be array.length, its position +// will be zero, and its mark will be undefined. Its backing array will be the +// given array, and its array offset will be zero. // -//Parameters: -//array - The array that will back this buffer -//Returns: -//The new byte buffer -ByteBuffer *ByteBuffer::wrap(byteArray &b) -{ - return new ByteBuffer( b.length, b.data ); +// Parameters: +// array - The array that will back this buffer +// Returns: +// The new byte buffer +ByteBuffer* ByteBuffer::wrap(byteArray& b) { + return new ByteBuffer(b.length, b.data); } -//Allocates a new byte buffer. -//The new buffer's position will be zero, its limit will be its capacity, and its mark will be undefined. -//It will have a backing array, and its array offset will be zero. +// Allocates a new byte buffer. +// The new buffer's position will be zero, its limit will be its capacity, and +// its mark will be undefined. It will have a backing array, and its array +// offset will be zero. // -//Parameters: -//capacity - The new buffer's capacity, in bytes -//Returns: -//The new byte buffer -ByteBuffer *ByteBuffer::allocate(unsigned int capacity) -{ - return new ByteBuffer( capacity ); +// Parameters: +// capacity - The new buffer's capacity, in bytes +// Returns: +// The new byte buffer +ByteBuffer* ByteBuffer::allocate(unsigned int capacity) { + return new ByteBuffer(capacity); } -//Modifies this buffer's byte order. -//Parameters: -//bo - The new byte order, either BIGENDIAN or LITTLEENDIAN -void ByteBuffer::order(ByteOrder bo) -{ - byteOrder = bo; -} +// Modifies this buffer's byte order. +// Parameters: +// bo - The new byte order, either BIGENDIAN or LITTLEENDIAN +void ByteBuffer::order(ByteOrder bo) { byteOrder = bo; } -//Flips this buffer. The limit is set to the current position and then the position is set to zero. -//If the mark is defined then it is discarded. +// Flips this buffer. The limit is set to the current position and then the +// position is set to zero. If the mark is defined then it is discarded. // -//Returns: -//This buffer -ByteBuffer *ByteBuffer::flip() -{ - m_limit = m_position; - m_position = 0; - return this; +// Returns: +// This buffer +ByteBuffer* ByteBuffer::flip() { + m_limit = m_position; + m_position = 0; + return this; } // 4J Added so we can write this to a file -uint8_t *ByteBuffer::getBuffer() -{ - return buffer; -} +uint8_t* ByteBuffer::getBuffer() { return buffer; } -int ByteBuffer::getSize() -{ - // TODO 4J Stu - Should this be the capcity and not the limit? - return m_limit; +int ByteBuffer::getSize() { + // TODO 4J Stu - Should this be the capcity and not the limit? + return m_limit; } // End 4J -//Absolute get method. Reads the byte at the given index. -//Parameters: -//index - The index from which the byte will be read -//Returns: -//The byte at the given index -//Throws: -//IndexOutOfBoundsException - If index is negative or not smaller than the buffer's limit -uint8_t ByteBuffer::get(int index) -{ - assert( index < m_limit ); - assert( index >= 0 ); +// Absolute get method. Reads the byte at the given index. +// Parameters: +// index - The index from which the byte will be read +// Returns: +// The byte at the given index +// Throws: +// IndexOutOfBoundsException - If index is negative or not smaller than the +// buffer's limit +uint8_t ByteBuffer::get(int index) { + assert(index < m_limit); + assert(index >= 0); - return buffer[index]; + return buffer[index]; } -//Relative get method for reading an int value. -//Reads the next four bytes at this buffer's current position, composing them into an int value according to the -//current byte order, and then increments the position by four. +// Relative get method for reading an int value. +// Reads the next four bytes at this buffer's current position, composing them +// into an int value according to the current byte order, and then increments +// the position by four. // -//Returns: -//The int value at the buffer's current position -int ByteBuffer::getInt() -{ - assert( m_position+3 < m_limit ); +// Returns: +// The int value at the buffer's current position +int ByteBuffer::getInt() { + assert(m_position + 3 < m_limit); - int value = 0; + int value = 0; - int b1 = static_cast(buffer[ m_position ]); - int b2 = static_cast(buffer[ m_position+1 ]); - int b3 = static_cast(buffer[ m_position+2 ]); - int b4 = static_cast(buffer[ m_position+3 ]); + int b1 = static_cast(buffer[m_position]); + int b2 = static_cast(buffer[m_position + 1]); + int b3 = static_cast(buffer[m_position + 2]); + int b4 = static_cast(buffer[m_position + 3]); - m_position += 4; + m_position += 4; - if( byteOrder == BIGENDIAN ) - { - value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; - } - else if( byteOrder == LITTLEENDIAN ) - { - value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); - } - return value; + if (byteOrder == BIGENDIAN) { + value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; + } else if (byteOrder == LITTLEENDIAN) { + value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); + } + return value; } -//Absolute get method for reading an int value. -//Reads four bytes at the given index, composing them into a int value according to the current byte order. +// Absolute get method for reading an int value. +// Reads four bytes at the given index, composing them into a int value +// according to the current byte order. // -//Parameters: -//index - The index from which the bytes will be read -//Returns: -//The int value at the given index -int ByteBuffer::getInt(unsigned int index) -{ - assert( index+3 < m_limit ); - int value = 0; +// Parameters: +// index - The index from which the bytes will be read +// Returns: +// The int value at the given index +int ByteBuffer::getInt(unsigned int index) { + assert(index + 3 < m_limit); + int value = 0; - int b1 = static_cast(buffer[ index ]); - int b2 = static_cast(buffer[ index+1 ]); - int b3 = static_cast(buffer[ index+2 ]); - int b4 = static_cast(buffer[ index+3 ]); + int b1 = static_cast(buffer[index]); + int b2 = static_cast(buffer[index + 1]); + int b3 = static_cast(buffer[index + 2]); + int b4 = static_cast(buffer[index + 3]); - if( byteOrder == BIGENDIAN ) - { - value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; - } - else if( byteOrder == LITTLEENDIAN ) - { - value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); - } - return value; + if (byteOrder == BIGENDIAN) { + value = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; + } else if (byteOrder == LITTLEENDIAN) { + value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24); + } + return value; } -//Relative get method for reading a long value. -//Reads the next eight bytes at this buffer's current position, composing them into a long value according to the current byte order, -//and then increments the position by eight. +// Relative get method for reading a long value. +// Reads the next eight bytes at this buffer's current position, composing them +// into a long value according to the current byte order, and then increments +// the position by eight. // -//Returns: -//The long value at the buffer's current position -__int64 ByteBuffer::getLong() -{ - assert( m_position+8 < m_limit ); +// Returns: +// The long value at the buffer's current position +__int64 ByteBuffer::getLong() { + assert(m_position + 8 < m_limit); - __int64 value = 0; + __int64 value = 0; - __int64 b1 = static_cast<__int64>(buffer[ m_position ]); - __int64 b2 = static_cast<__int64>(buffer[ m_position+1 ]); - __int64 b3 = static_cast<__int64>(buffer[ m_position+2 ]); - __int64 b4 = static_cast<__int64>(buffer[ m_position+3 ]); - __int64 b5 = static_cast<__int64>(buffer[ m_position+4 ]); - __int64 b6 = static_cast<__int64>(buffer[ m_position+5 ]); - __int64 b7 = static_cast<__int64>(buffer[ m_position+6 ]); - __int64 b8 = static_cast<__int64>(buffer[ m_position+7 ]); + __int64 b1 = static_cast<__int64>(buffer[m_position]); + __int64 b2 = static_cast<__int64>(buffer[m_position + 1]); + __int64 b3 = static_cast<__int64>(buffer[m_position + 2]); + __int64 b4 = static_cast<__int64>(buffer[m_position + 3]); + __int64 b5 = static_cast<__int64>(buffer[m_position + 4]); + __int64 b6 = static_cast<__int64>(buffer[m_position + 5]); + __int64 b7 = static_cast<__int64>(buffer[m_position + 6]); + __int64 b8 = static_cast<__int64>(buffer[m_position + 7]); - m_position += 8; + m_position += 8; - if( byteOrder == BIGENDIAN ) - { - value = (b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) | (b5 << 24) | (b6 << 16) | (b7 << 8) | b8; - } - else if( byteOrder == LITTLEENDIAN ) - { - value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); - } - return value; + if (byteOrder == BIGENDIAN) { + value = (b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) | (b5 << 24) | + (b6 << 16) | (b7 << 8) | b8; + } else if (byteOrder == LITTLEENDIAN) { + value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | + (b6 << 40) | (b7 << 48) | (b8 << 56); + } + return value; } -//Relative get method for reading a short value. -//Reads the next two bytes at this buffer's current position, composing them into a short value according to the current -//byte order, and then increments the position by two. +// Relative get method for reading a short value. +// Reads the next two bytes at this buffer's current position, composing them +// into a short value according to the current byte order, and then increments +// the position by two. // -//Returns: -//The short value at the buffer's current position -short ByteBuffer::getShort() -{ - assert( m_position+1 < m_limit ); +// Returns: +// The short value at the buffer's current position +short ByteBuffer::getShort() { + assert(m_position + 1 < m_limit); - short value = 0; + short value = 0; - short b1 = static_cast(buffer[ m_position ]); - short b2 = static_cast(buffer[ m_position+1 ]); + short b1 = static_cast(buffer[m_position]); + short b2 = static_cast(buffer[m_position + 1]); - m_position += 2; + m_position += 2; - if( byteOrder == BIGENDIAN ) - { - value = (b1 << 8) | b2; - } - else if( byteOrder == LITTLEENDIAN ) - { - value = b1 | (b2 << 8); - } - return value; + if (byteOrder == BIGENDIAN) { + value = (b1 << 8) | b2; + } else if (byteOrder == LITTLEENDIAN) { + value = b1 | (b2 << 8); + } + return value; } -void ByteBuffer::getShortArray(shortArray &s) -{ - // TODO 4J Stu - Should this function be writing from the start of the buffer, or from position? - // And should it update position? - assert( s.length >= m_limit/2 ); +void ByteBuffer::getShortArray(shortArray& s) { + // TODO 4J Stu - Should this function be writing from the start of the + // buffer, or from position? And should it update position? + assert(s.length >= m_limit / 2); - // 4J Stu - Assumes big endian - memcpy( s.data, buffer, (m_limit-m_position) ); + // 4J Stu - Assumes big endian + memcpy(s.data, buffer, (m_limit - m_position)); } -//Absolute put method (optional operation). -//Writes the given byte into this buffer at the given index. +// Absolute put method (optional operation). +// Writes the given byte into this buffer at the given index. // -//Parameters: -//index - The index at which the byte will be written -//b - The byte value to be written -//Returns: -//This buffer -//Throws: -//IndexOutOfBoundsException - If index is negative or not smaller than the buffer's limit -//ReadOnlyBufferException - If this buffer is read-only -ByteBuffer *ByteBuffer::put(int index, uint8_t b) -{ - assert( index < m_limit ); - assert( index >= 0 ); +// Parameters: +// index - The index at which the byte will be written +// b - The byte value to be written +// Returns: +// This buffer +// Throws: +// IndexOutOfBoundsException - If index is negative or not smaller than the +// buffer's limit ReadOnlyBufferException - If this buffer is read-only +ByteBuffer* ByteBuffer::put(int index, uint8_t b) { + assert(index < m_limit); + assert(index >= 0); - buffer[index] = b; - return this; + buffer[index] = b; + return this; } - -//Relative put method for writing an int value (optional operation). -//Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, -//and then increments the position by four. +// Relative put method for writing an int value (optional operation). +// Writes four bytes containing the given int value, in the current byte order, +// into this buffer at the current position, and then increments the position by +// four. // -//Parameters: -//value - The int value to be written -//Returns: -//This buffer -ByteBuffer *ByteBuffer::putInt(int value) -{ - assert( m_position+3 < m_limit ); +// Parameters: +// value - The int value to be written +// Returns: +// This buffer +ByteBuffer* ByteBuffer::putInt(int value) { + assert(m_position + 3 < m_limit); - if( byteOrder == BIGENDIAN ) - { - buffer[m_position] = static_cast((value >> 24) & 0xFF); - buffer[m_position+1] = static_cast((value >> 16) & 0xFF); - buffer[m_position+2] = static_cast((value >> 8) & 0xFF); - buffer[m_position+3] = static_cast(value & 0xFF); - } - else if( byteOrder == LITTLEENDIAN ) - { - buffer[m_position] = static_cast(value & 0xFF); - buffer[m_position+1] = static_cast((value >> 8) & 0xFF); - buffer[m_position+2] = static_cast((value >> 16) & 0xFF); - buffer[m_position+3] = static_cast((value >> 24) & 0xFF); - } + if (byteOrder == BIGENDIAN) { + buffer[m_position] = static_cast((value >> 24) & 0xFF); + buffer[m_position + 1] = static_cast((value >> 16) & 0xFF); + buffer[m_position + 2] = static_cast((value >> 8) & 0xFF); + buffer[m_position + 3] = static_cast(value & 0xFF); + } else if (byteOrder == LITTLEENDIAN) { + buffer[m_position] = static_cast(value & 0xFF); + buffer[m_position + 1] = static_cast((value >> 8) & 0xFF); + buffer[m_position + 2] = static_cast((value >> 16) & 0xFF); + buffer[m_position + 3] = static_cast((value >> 24) & 0xFF); + } - m_position += 4; + m_position += 4; - return this; + return this; } -//Absolute put method for writing an int value (optional operation). -//Writes four bytes containing the given int value, in the current byte order, into this buffer at the given index. +// Absolute put method for writing an int value (optional operation). +// Writes four bytes containing the given int value, in the current byte order, +// into this buffer at the given index. // -//Parameters: -//index - The index at which the bytes will be written -//value - The int value to be written -//Returns: -//This buffer -ByteBuffer *ByteBuffer::putInt(unsigned int index, int value) -{ - assert( index+3 < m_limit ); +// Parameters: +// index - The index at which the bytes will be written +// value - The int value to be written +// Returns: +// This buffer +ByteBuffer* ByteBuffer::putInt(unsigned int index, int value) { + assert(index + 3 < m_limit); - if( byteOrder == BIGENDIAN ) - { - buffer[index] = static_cast((value >> 24) & 0xFF); - buffer[index+1] = static_cast((value >> 16) & 0xFF); - buffer[index+2] = static_cast((value >> 8) & 0xFF); - buffer[index+3] = static_cast(value & 0xFF); - } - else if( byteOrder == LITTLEENDIAN ) - { - buffer[index] = static_cast(value & 0xFF); - buffer[index+1] = static_cast((value >> 8) & 0xFF); - buffer[index+2] = static_cast((value >> 16) & 0xFF); - buffer[index+3] = static_cast((value >> 24) & 0xFF); - } + if (byteOrder == BIGENDIAN) { + buffer[index] = static_cast((value >> 24) & 0xFF); + buffer[index + 1] = static_cast((value >> 16) & 0xFF); + buffer[index + 2] = static_cast((value >> 8) & 0xFF); + buffer[index + 3] = static_cast(value & 0xFF); + } else if (byteOrder == LITTLEENDIAN) { + buffer[index] = static_cast(value & 0xFF); + buffer[index + 1] = static_cast((value >> 8) & 0xFF); + buffer[index + 2] = static_cast((value >> 16) & 0xFF); + buffer[index + 3] = static_cast((value >> 24) & 0xFF); + } - return this; + return this; } -//Relative put method for writing a short value (optional operation). -//Writes two bytes containing the given short value, in the current byte order, into this buffer at the current position, -//and then increments the position by two. +// Relative put method for writing a short value (optional operation). +// Writes two bytes containing the given short value, in the current byte order, +// into this buffer at the current position, and then increments the position by +// two. // -//Parameters: -//value - The short value to be written -//Returns: -//This buffer -ByteBuffer *ByteBuffer::putShort(short value) -{ - assert( m_position+1 < m_limit ); +// Parameters: +// value - The short value to be written +// Returns: +// This buffer +ByteBuffer* ByteBuffer::putShort(short value) { + assert(m_position + 1 < m_limit); - if( byteOrder == BIGENDIAN ) - { - buffer[m_position] = static_cast((value >> 8) & 0xFF); - buffer[m_position+1] = static_cast(value & 0xFF); - } - else if( byteOrder == LITTLEENDIAN ) - { - buffer[m_position] = static_cast(value & 0xFF); - buffer[m_position+1] = static_cast((value >> 8) & 0xFF); - } + if (byteOrder == BIGENDIAN) { + buffer[m_position] = static_cast((value >> 8) & 0xFF); + buffer[m_position + 1] = static_cast(value & 0xFF); + } else if (byteOrder == LITTLEENDIAN) { + buffer[m_position] = static_cast(value & 0xFF); + buffer[m_position + 1] = static_cast((value >> 8) & 0xFF); + } - m_position += 2; + m_position += 2; - return this; + return this; } -ByteBuffer *ByteBuffer::putShortArray(shortArray &s) -{ - // TODO 4J Stu - Should this function be writing from the start of the buffer, or from position? - // And should it update position? - assert( s.length*2 <= m_limit); - - // 4J Stu - Assumes big endian - memcpy( buffer, s.data, s.length*2 ); +ByteBuffer* ByteBuffer::putShortArray(shortArray& s) { + // TODO 4J Stu - Should this function be writing from the start of the + // buffer, or from position? And should it update position? + assert(s.length * 2 <= m_limit); - return this; + // 4J Stu - Assumes big endian + memcpy(buffer, s.data, s.length * 2); + + return this; } -//Relative put method for writing a long value (optional operation). -//Writes eight bytes containing the given long value, in the current byte order, into this buffer at the current position, -//and then increments the position by eight. +// Relative put method for writing a long value (optional operation). +// Writes eight bytes containing the given long value, in the current byte +// order, into this buffer at the current position, and then increments the +// position by eight. // -//Parameters: -//value - The long value to be written -//Returns: -//This buffer -ByteBuffer *ByteBuffer::putLong(__int64 value) -{ - assert( m_position+7 < m_limit ); +// Parameters: +// value - The long value to be written +// Returns: +// This buffer +ByteBuffer* ByteBuffer::putLong(__int64 value) { + assert(m_position + 7 < m_limit); - if( byteOrder == BIGENDIAN ) - { - buffer[m_position] = static_cast((value >> 56) & 0xFF); - buffer[m_position+1] = static_cast((value >> 48) & 0xFF); - buffer[m_position+2] = static_cast((value >> 40) & 0xFF); - buffer[m_position+3] = static_cast((value >> 32) & 0xFF); - buffer[m_position+4] = static_cast((value >> 24) & 0xFF); - buffer[m_position+5] = static_cast((value >> 16) & 0xFF); - buffer[m_position+6] = static_cast((value >> 8) & 0xFF); - buffer[m_position+7] = static_cast(value & 0xFF); - } - else if( byteOrder == LITTLEENDIAN ) - { - buffer[m_position] = static_cast((value & 0xFF)); - buffer[m_position+1] = static_cast((value >> 8) & 0xFF); - buffer[m_position+2] = static_cast((value >> 16) & 0xFF); - buffer[m_position+3] = static_cast((value >> 24) & 0xFF); - buffer[m_position+4] = static_cast((value >> 32) & 0xFF); - buffer[m_position+5] = static_cast((value >> 40) & 0xFF); - buffer[m_position+6] = static_cast((value >> 48) & 0xFF); - buffer[m_position+7] = static_cast((value >> 56) & 0xFF); - } + if (byteOrder == BIGENDIAN) { + buffer[m_position] = static_cast((value >> 56) & 0xFF); + buffer[m_position + 1] = static_cast((value >> 48) & 0xFF); + buffer[m_position + 2] = static_cast((value >> 40) & 0xFF); + buffer[m_position + 3] = static_cast((value >> 32) & 0xFF); + buffer[m_position + 4] = static_cast((value >> 24) & 0xFF); + buffer[m_position + 5] = static_cast((value >> 16) & 0xFF); + buffer[m_position + 6] = static_cast((value >> 8) & 0xFF); + buffer[m_position + 7] = static_cast(value & 0xFF); + } else if (byteOrder == LITTLEENDIAN) { + buffer[m_position] = static_cast((value & 0xFF)); + buffer[m_position + 1] = static_cast((value >> 8) & 0xFF); + buffer[m_position + 2] = static_cast((value >> 16) & 0xFF); + buffer[m_position + 3] = static_cast((value >> 24) & 0xFF); + buffer[m_position + 4] = static_cast((value >> 32) & 0xFF); + buffer[m_position + 5] = static_cast((value >> 40) & 0xFF); + buffer[m_position + 6] = static_cast((value >> 48) & 0xFF); + buffer[m_position + 7] = static_cast((value >> 56) & 0xFF); + } - return this; + return this; } -//Relative bulk put method (optional operation). -//This method transfers the entire content of the given source byte array into this buffer. -//An invocation of this method of the form dst.put(a) behaves in exactly the same way as the invocation +// Relative bulk put method (optional operation). +// This method transfers the entire content of the given source byte array into +// this buffer. An invocation of this method of the form dst.put(a) behaves in +// exactly the same way as the invocation // -// dst.put(a, 0, a.length) -//Returns: -//This buffer -ByteBuffer *ByteBuffer::put(byteArray inputArray) -{ - if( inputArray.length > remaining() ) - assert( false ); //TODO 4J Stu - Some kind of exception? +// dst.put(a, 0, a.length) +// Returns: +// This buffer +ByteBuffer* ByteBuffer::put(byteArray inputArray) { + if (inputArray.length > remaining()) + assert(false); // TODO 4J Stu - Some kind of exception? - std::copy( inputArray.data, inputArray.data + inputArray.length, buffer+m_position ); + std::copy(inputArray.data, inputArray.data + inputArray.length, + buffer + m_position); - m_position += inputArray.length; + m_position += inputArray.length; - return this; + return this; } -byteArray ByteBuffer::array() -{ - return byteArray( buffer, m_capacity ); +byteArray ByteBuffer::array() { return byteArray(buffer, m_capacity); } + +// Creates a view of this byte buffer as an int buffer. +// The content of the new buffer will start at this buffer's current position. +// Changes to this buffer's content will be visible in the new buffer, and vice +// versa; the two buffers' position, limit, and mark values will be independent. +// +// The new buffer's position will be zero, its capacity and its limit will be +// the number of bytes remaining in this buffer divided by four, and its mark +// will be undefined. The new buffer will be direct if, and only if, this buffer +// is direct, and it will be read-only if, and only if, this buffer is +// read-only. +// +// Returns: +// A new int buffer +IntBuffer* ByteBuffer::asIntBuffer() { + // TODO 4J Stu - Is it safe to just cast our byte array pointer to another + // type? + return new IntBuffer((m_limit - m_position) / 4, + (int*)(buffer + m_position)); } -//Creates a view of this byte buffer as an int buffer. -//The content of the new buffer will start at this buffer's current position. Changes to this buffer's content -//will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent. +// Creates a view of this byte buffer as a float buffer. +// The content of the new buffer will start at this buffer's current position. +// Changes to this buffer's content will be visible in the new buffer, and vice +// versa; the two buffers' position, limit, and mark values will be independent. // -//The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer -//divided by four, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, and -//it will be read-only if, and only if, this buffer is read-only. +// The new buffer's position will be zero, its capacity and its limit will be +// the number of bytes remaining in this buffer divided by four, and its mark +// will be undefined. The new buffer will be direct if, and only if, this buffer +// is direct, and it will be read-only if, and only if, this buffer is +// read-only. // -//Returns: -//A new int buffer -IntBuffer *ByteBuffer::asIntBuffer() -{ - // TODO 4J Stu - Is it safe to just cast our byte array pointer to another type? - return new IntBuffer( (m_limit-m_position)/4, (int *) (buffer+m_position) ); +// Returns: +// A new float buffer +FloatBuffer* ByteBuffer::asFloatBuffer() { + // TODO 4J Stu - Is it safe to just cast our byte array pointer to another + // type? + return new FloatBuffer((m_limit - m_position) / 4, + (float*)(buffer + m_position)); } -//Creates a view of this byte buffer as a float buffer. -//The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be -//visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent. -// -//The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer -//divided by four, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, -//and it will be read-only if, and only if, this buffer is read-only. -// -//Returns: -//A new float buffer -FloatBuffer *ByteBuffer::asFloatBuffer() -{ - // TODO 4J Stu - Is it safe to just cast our byte array pointer to another type? - return new FloatBuffer( (m_limit-m_position)/4, (float *) (buffer+m_position) ); -} - - - #ifdef __PS3__ -// we're using the RSX now to upload textures to vram, so we need th main ram textures allocated from io space -ByteBuffer_IO::ByteBuffer_IO( unsigned int capacity ) - : ByteBuffer(capacity, (uint8_t*)RenderManager.allocIOMem(capacity, 64)) -{ - memset( buffer,0,sizeof(uint8_t)*capacity); - byteOrder = BIGENDIAN; +// we're using the RSX now to upload textures to vram, so we need th main ram +// textures allocated from io space +ByteBuffer_IO::ByteBuffer_IO(unsigned int capacity) + : ByteBuffer(capacity, (uint8_t*)RenderManager.allocIOMem(capacity, 64)) { + memset(buffer, 0, sizeof(uint8_t) * capacity); + byteOrder = BIGENDIAN; } -ByteBuffer_IO::~ByteBuffer_IO() -{ -// delete buffer; - RenderManager.freeIOMem(buffer); +ByteBuffer_IO::~ByteBuffer_IO() { + // delete buffer; + RenderManager.freeIOMem(buffer); } -#endif // __PS3__ +#endif // __PS3__ diff --git a/Minecraft.World/IO/Streams/ByteBuffer.h b/Minecraft.World/IO/Streams/ByteBuffer.h index 11af68494..336eb7688 100644 --- a/Minecraft.World/IO/Streams/ByteBuffer.h +++ b/Minecraft.World/IO/Streams/ByteBuffer.h @@ -6,52 +6,49 @@ class IntBuffer; class FloatBuffer; -class ByteBuffer : public Buffer -{ +class ByteBuffer : public Buffer { protected: - uint8_t *buffer; - ByteOrder byteOrder; + uint8_t* buffer; + ByteOrder byteOrder; public: - ByteBuffer(unsigned int capacity); - static ByteBuffer *allocateDirect(int capacity); - ByteBuffer( unsigned int capacity, uint8_t *backingArray ); - virtual ~ByteBuffer(); - - static ByteBuffer *wrap(byteArray &b); - static ByteBuffer *allocate(unsigned int capacity); - void order(ByteOrder a); - ByteBuffer *flip(); - uint8_t *getBuffer(); - int getSize(); - int getInt(); - int getInt(unsigned int index); - void get(byteArray) {} // 4J - TODO - uint8_t get(int index); - __int64 getLong(); - short getShort(); - void getShortArray(shortArray &s); - ByteBuffer *put(int index, uint8_t b); - ByteBuffer *putInt(int value); - ByteBuffer *putInt(unsigned int index, int value); - ByteBuffer *putShort(short value); - ByteBuffer *putShortArray(shortArray &s); - ByteBuffer *putLong(__int64 value); - ByteBuffer *put(byteArray inputArray); - byteArray array(); - IntBuffer *asIntBuffer(); - FloatBuffer *asFloatBuffer(); + ByteBuffer(unsigned int capacity); + static ByteBuffer* allocateDirect(int capacity); + ByteBuffer(unsigned int capacity, uint8_t* backingArray); + virtual ~ByteBuffer(); + static ByteBuffer* wrap(byteArray& b); + static ByteBuffer* allocate(unsigned int capacity); + void order(ByteOrder a); + ByteBuffer* flip(); + uint8_t* getBuffer(); + int getSize(); + int getInt(); + int getInt(unsigned int index); + void get(byteArray) {} // 4J - TODO + uint8_t get(int index); + __int64 getLong(); + short getShort(); + void getShortArray(shortArray& s); + ByteBuffer* put(int index, uint8_t b); + ByteBuffer* putInt(int value); + ByteBuffer* putInt(unsigned int index, int value); + ByteBuffer* putShort(short value); + ByteBuffer* putShortArray(shortArray& s); + ByteBuffer* putLong(__int64 value); + ByteBuffer* put(byteArray inputArray); + byteArray array(); + IntBuffer* asIntBuffer(); + FloatBuffer* asFloatBuffer(); }; - #ifdef __PS3__ -// we're using the RSX now to upload textures to vram, so we need th main ram textures allocated from io space -class ByteBuffer_IO : public ByteBuffer -{ +// we're using the RSX now to upload textures to vram, so we need th main ram +// textures allocated from io space +class ByteBuffer_IO : public ByteBuffer { public: - ByteBuffer_IO(unsigned int capacity); - ~ByteBuffer_IO(); + ByteBuffer_IO(unsigned int capacity); + ~ByteBuffer_IO(); }; -#endif // __PS3__ \ No newline at end of file +#endif // __PS3__ \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/Compression.cpp b/Minecraft.World/IO/Streams/Compression.cpp index 899aae280..543f05296 100644 --- a/Minecraft.World/IO/Streams/Compression.cpp +++ b/Minecraft.World/IO/Streams/Compression.cpp @@ -1,6 +1,7 @@ #include "../../Platform/stdafx.h" #include "Compression.h" -#if defined __ORBIS__ || defined __PS3__ || defined _DURANGO || defined _WIN64 || defined __linux__ +#if defined __ORBIS__ || defined __PS3__ || defined _DURANGO || \ + defined _WIN64 || defined __linux__ // zconf.h defines "typedef unsigned char Byte" which conflicts with the // project's "class Byte" from BasicTypeContainers.h (via stdafx.h). // Rename zlib's Byte to zlib_Byte before the include so the typedef lands @@ -14,538 +15,501 @@ #include "../../../Minecraft.Client/Platform/PSVita/PSVitaExtras/zlib.h" #elif defined __PS3__ #include "../../../Minecraft.Client/Platform/PS3/PS3Extras/EdgeZLib.h" -#endif //__PS3__ +#endif //__PS3__ unsigned int Compression::tlsIdx = 0; -Compression::ThreadStorage *Compression::tlsDefault = NULL; +Compression::ThreadStorage* Compression::tlsDefault = NULL; -Compression::ThreadStorage::ThreadStorage() -{ - compression = new Compression(); +Compression::ThreadStorage::ThreadStorage() { compression = new Compression(); } + +Compression::ThreadStorage::~ThreadStorage() { delete compression; } + +void Compression::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + if (tlsDefault == nullptr) { + pthread_key_create(&tlsIdx, nullptr); + tlsDefault = tls; + } + pthread_setspecific(tlsIdx, tls); } -Compression::ThreadStorage::~ThreadStorage() -{ - delete compression; +void Compression::UseDefaultThreadStorage() { + pthread_setspecific(tlsIdx, tlsDefault); } -void Compression::CreateNewThreadStorage() -{ - ThreadStorage* tls = new ThreadStorage(); - if (tlsDefault == nullptr) - { - pthread_key_create(&tlsIdx, nullptr); - tlsDefault = tls; - } - pthread_setspecific(tlsIdx, tls); +void Compression::ReleaseThreadStorage() { + ThreadStorage* tls = + (ThreadStorage*)pthread_getspecific(tlsIdx); // POSIX equivalent + if (tls != tlsDefault) { + delete tls; + } } -void Compression::UseDefaultThreadStorage() -{ - pthread_setspecific(tlsIdx, tlsDefault); +Compression* Compression::getCompression() { + ThreadStorage* tls = (ThreadStorage*)pthread_getspecific(tlsIdx); + return tls->compression; } -void Compression::ReleaseThreadStorage() -{ - ThreadStorage* tls = (ThreadStorage*)pthread_getspecific(tlsIdx); // POSIX equivalent - if (tls != tlsDefault) - { - delete tls; - } +HRESULT Compression::CompressLZXRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize) { + EnterCriticalSection(&rleCompressLock); + // static unsigned char rleBuf[1024*100]; + + unsigned char* pucIn = (unsigned char*)pSource; + unsigned char* pucEnd = pucIn + SrcSize; + unsigned char* pucOut = (unsigned char*)rleCompressBuf; + + // Compress with RLE first: + // 0 - 254 - encodes a single byte + // 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s + // 255 followed by 3-255, followed by a byte - encodes a run of n + 1 bytes + PIXBeginNamedEvent(0, "RLE compression"); + do { + unsigned char thisOne = *pucIn++; + + unsigned int count = 1; + while ((pucIn != pucEnd) && (*pucIn == thisOne) && (count < 256)) { + pucIn++; + count++; + } + + if (count <= 3) { + if (thisOne == 255) { + *pucOut++ = 255; + *pucOut++ = count - 1; + } else { + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = thisOne; + } + } + } else { + *pucOut++ = 255; + *pucOut++ = count - 1; + *pucOut++ = thisOne; + } + } while (pucIn != pucEnd); + unsigned int rleSize = (unsigned int)(pucOut - rleCompressBuf); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Secondary compression"); + Compress(pDestination, pDestSize, rleCompressBuf, rleSize); + PIXEndNamedEvent(); + LeaveCriticalSection(&rleCompressLock); + // printf("Compressed from %d to %d to %d\n",SrcSize,rleSize,*pDestSize); + + return S_OK; } -Compression *Compression::getCompression() -{ - ThreadStorage *tls = (ThreadStorage *)pthread_getspecific(tlsIdx); - return tls->compression; -} +HRESULT Compression::CompressRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize) { + EnterCriticalSection(&rleCompressLock); + // static unsigned char rleBuf[1024*100]; -HRESULT Compression::CompressLZXRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - EnterCriticalSection(&rleCompressLock); - //static unsigned char rleBuf[1024*100]; + unsigned char* pucIn = (unsigned char*)pSource; + unsigned char* pucEnd = pucIn + SrcSize; + unsigned char* pucOut = (unsigned char*)rleCompressBuf; - unsigned char *pucIn = (unsigned char *)pSource; - unsigned char *pucEnd = pucIn + SrcSize; - unsigned char *pucOut = (unsigned char *)rleCompressBuf; + // Compress with RLE first: + // 0 - 254 - encodes a single byte + // 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s + // 255 followed by 3-255, followed by a byte - encodes a run of n + 1 bytes + PIXBeginNamedEvent(0, "RLE compression"); + do { + unsigned char thisOne = *pucIn++; - // Compress with RLE first: - // 0 - 254 - encodes a single byte - // 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s - // 255 followed by 3-255, followed by a byte - encodes a run of n + 1 bytes - PIXBeginNamedEvent(0,"RLE compression"); - do - { - unsigned char thisOne = *pucIn++; + unsigned int count = 1; + while ((pucIn != pucEnd) && (*pucIn == thisOne) && (count < 256)) { + pucIn++; + count++; + } - unsigned int count = 1; - while( ( pucIn != pucEnd ) && ( *pucIn == thisOne ) && ( count < 256 ) ) - { - pucIn++; - count++; - } + if (count <= 3) { + if (thisOne == 255) { + *pucOut++ = 255; + *pucOut++ = count - 1; + } else { + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = thisOne; + } + } + } else { + *pucOut++ = 255; + *pucOut++ = count - 1; + *pucOut++ = thisOne; + } + } while (pucIn != pucEnd); + unsigned int rleSize = (unsigned int)(pucOut - rleCompressBuf); + PIXEndNamedEvent(); + LeaveCriticalSection(&rleCompressLock); - if( count <= 3 ) - { - if( thisOne == 255 ) - { - *pucOut++ = 255; - *pucOut++ = count - 1; - } - else - { - for( unsigned int i = 0; i < count ; i++ ) - { - *pucOut++ = thisOne; - } - } - } - else - { - *pucOut++ = 255; - *pucOut++ = count - 1; - *pucOut++ = thisOne; - } - } while (pucIn != pucEnd); - unsigned int rleSize = (unsigned int)(pucOut - rleCompressBuf); - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Secondary compression"); - Compress(pDestination, pDestSize, rleCompressBuf, rleSize); - PIXEndNamedEvent(); - LeaveCriticalSection(&rleCompressLock); -// printf("Compressed from %d to %d to %d\n",SrcSize,rleSize,*pDestSize); - - return S_OK; -} - -HRESULT Compression::CompressRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - EnterCriticalSection(&rleCompressLock); - //static unsigned char rleBuf[1024*100]; - - unsigned char *pucIn = (unsigned char *)pSource; - unsigned char *pucEnd = pucIn + SrcSize; - unsigned char *pucOut = (unsigned char *)rleCompressBuf; - - // Compress with RLE first: - // 0 - 254 - encodes a single byte - // 255 followed by 0, 1, 2 - encodes a 1, 2, or 3 255s - // 255 followed by 3-255, followed by a byte - encodes a run of n + 1 bytes - PIXBeginNamedEvent(0,"RLE compression"); - do - { - unsigned char thisOne = *pucIn++; - - unsigned int count = 1; - while( ( pucIn != pucEnd ) && ( *pucIn == thisOne ) && ( count < 256 ) ) - { - pucIn++; - count++; - } - - if( count <= 3 ) - { - if( thisOne == 255 ) - { - *pucOut++ = 255; - *pucOut++ = count - 1; - } - else - { - for( unsigned int i = 0; i < count ; i++ ) - { - *pucOut++ = thisOne; - } - } - } - else - { - *pucOut++ = 255; - *pucOut++ = count - 1; - *pucOut++ = thisOne; - } - } while (pucIn != pucEnd); - unsigned int rleSize = (unsigned int)(pucOut - rleCompressBuf); - PIXEndNamedEvent(); - LeaveCriticalSection(&rleCompressLock); - - // Return - if (rleSize <= *pDestSize) - { - *pDestSize = rleSize; - memcpy(pDestination, rleCompressBuf, *pDestSize); - } - else - { + // Return + if (rleSize <= *pDestSize) { + *pDestSize = rleSize; + memcpy(pDestination, rleCompressBuf, *pDestSize); + } else { #ifndef _CONTENT_PACKAGE - assert(false); + assert(false); #endif - } + } - return S_OK; + return S_OK; } -HRESULT Compression::DecompressLZXRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - EnterCriticalSection(&rleDecompressLock); - // 4J Stu - Fix for #13676 - Crash: Crash while attempting to load a world after updating TU - // Some saves can have chunks that decompress into very large sizes, so I have doubled the size of this buffer - // Ideally we should be able to dynamically allocate the buffer if it's going to be too big, as most chunks - // only use 5% of this buffer +HRESULT Compression::DecompressLZXRLE(void* pDestination, + unsigned int* pDestSize, void* pSource, + unsigned int SrcSize) { + EnterCriticalSection(&rleDecompressLock); + // 4J Stu - Fix for #13676 - Crash: Crash while attempting to load a world + // after updating TU Some saves can have chunks that decompress into very + // large sizes, so I have doubled the size of this buffer Ideally we should + // be able to dynamically allocate the buffer if it's going to be too big, + // as most chunks only use 5% of this buffer - // 4J Stu - Changed this again to dynamically allocate a buffer if it's going to be too big - unsigned char *pucIn = NULL; + // 4J Stu - Changed this again to dynamically allocate a buffer if it's + // going to be too big + unsigned char* pucIn = NULL; - //const unsigned int staticRleSize = 1024*200; - //static unsigned char rleBuf[staticRleSize]; - unsigned int rleSize = staticRleSize; - unsigned char *dynamicRleBuf = NULL; + // const unsigned int staticRleSize = 1024*200; + // static unsigned char rleBuf[staticRleSize]; + unsigned int rleSize = staticRleSize; + unsigned char* dynamicRleBuf = NULL; - if(*pDestSize > rleSize) - { - rleSize = *pDestSize; - dynamicRleBuf = new unsigned char[rleSize]; - Decompress(dynamicRleBuf, &rleSize, pSource, SrcSize); - pucIn = (unsigned char *)dynamicRleBuf; - } - else - { - Decompress(rleDecompressBuf, &rleSize, pSource, SrcSize); - pucIn = (unsigned char *)rleDecompressBuf; - } + if (*pDestSize > rleSize) { + rleSize = *pDestSize; + dynamicRleBuf = new unsigned char[rleSize]; + Decompress(dynamicRleBuf, &rleSize, pSource, SrcSize); + pucIn = (unsigned char*)dynamicRleBuf; + } else { + Decompress(rleDecompressBuf, &rleSize, pSource, SrcSize); + pucIn = (unsigned char*)rleDecompressBuf; + } - //unsigned char *pucIn = (unsigned char *)rleDecompressBuf; - unsigned char *pucEnd = pucIn + rleSize; - unsigned char *pucOut = (unsigned char *)pDestination; + // unsigned char *pucIn = (unsigned char *)rleDecompressBuf; + unsigned char* pucEnd = pucIn + rleSize; + unsigned char* pucOut = (unsigned char*)pDestination; - while( pucIn != pucEnd ) - { - unsigned char thisOne = *pucIn++; - if( thisOne == 255 ) - { - unsigned int count = *pucIn++; - if( count < 3 ) - { - count++; - for( unsigned int i = 0; i < count; i++ ) - { - *pucOut++ = 255; - } - } - else - { - count++; - unsigned char data = *pucIn++; - for( unsigned int i = 0; i < count; i++ ) - { - *pucOut++ = data; - } - } - } - else - { - *pucOut++ = thisOne; - } - } - *pDestSize = (unsigned int)(pucOut - (unsigned char *)pDestination); + while (pucIn != pucEnd) { + unsigned char thisOne = *pucIn++; + if (thisOne == 255) { + unsigned int count = *pucIn++; + if (count < 3) { + count++; + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = 255; + } + } else { + count++; + unsigned char data = *pucIn++; + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = data; + } + } + } else { + *pucOut++ = thisOne; + } + } + *pDestSize = (unsigned int)(pucOut - (unsigned char*)pDestination); -// printf("Decompressed from %d to %d to %d\n",SrcSize,rleSize,*pDestSize); + // printf("Decompressed from %d to %d to %d\n",SrcSize,rleSize,*pDestSize); - if(dynamicRleBuf != NULL) delete [] dynamicRleBuf; + if (dynamicRleBuf != NULL) delete[] dynamicRleBuf; - LeaveCriticalSection(&rleDecompressLock); - return S_OK; + LeaveCriticalSection(&rleDecompressLock); + return S_OK; } -HRESULT Compression::DecompressRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - EnterCriticalSection(&rleDecompressLock); - - //unsigned char *pucIn = (unsigned char *)rleDecompressBuf; - unsigned char *pucIn = (unsigned char *)pSource; - unsigned char *pucEnd = pucIn + SrcSize; - unsigned char *pucOut = (unsigned char *)pDestination; +HRESULT Compression::DecompressRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize) { + EnterCriticalSection(&rleDecompressLock); - while( pucIn != pucEnd ) - { - unsigned char thisOne = *pucIn++; - if( thisOne == 255 ) - { - unsigned int count = *pucIn++; - if( count < 3 ) - { - count++; - for( unsigned int i = 0; i < count; i++ ) - { - *pucOut++ = 255; - } - } - else - { - count++; - unsigned char data = *pucIn++; - for( unsigned int i = 0; i < count; i++ ) - { - *pucOut++ = data; - } - } - } - else - { - *pucOut++ = thisOne; - } - } - *pDestSize = (unsigned int)(pucOut - (unsigned char *)pDestination); + // unsigned char *pucIn = (unsigned char *)rleDecompressBuf; + unsigned char* pucIn = (unsigned char*)pSource; + unsigned char* pucEnd = pucIn + SrcSize; + unsigned char* pucOut = (unsigned char*)pDestination; - LeaveCriticalSection(&rleDecompressLock); - return S_OK; + while (pucIn != pucEnd) { + unsigned char thisOne = *pucIn++; + if (thisOne == 255) { + unsigned int count = *pucIn++; + if (count < 3) { + count++; + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = 255; + } + } else { + count++; + unsigned char data = *pucIn++; + for (unsigned int i = 0; i < count; i++) { + *pucOut++ = data; + } + } + } else { + *pucOut++ = thisOne; + } + } + *pDestSize = (unsigned int)(pucOut - (unsigned char*)pDestination); + + LeaveCriticalSection(&rleDecompressLock); + return S_OK; } - -HRESULT Compression::Compress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - // Using zlib for x64 compression - 360 is using native 360 compression and PS3 a stubbed non-compressing version of this -#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || defined __PSVITA__ || defined __linux__ - SIZE_T destSize = (SIZE_T)(*pDestSize); - int res = ::compress((Bytef *)pDestination, (uLongf *)&destSize, (Bytef *)pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return ( ( res == Z_OK ) ? S_OK : -1 ); +HRESULT Compression::Compress(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize) { + // Using zlib for x64 compression - 360 is using native 360 compression and + // PS3 a stubbed non-compressing version of this +#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || \ + defined __PSVITA__ || defined __linux__ + SIZE_T destSize = (SIZE_T)(*pDestSize); + int res = ::compress((Bytef*)pDestination, (uLongf*)&destSize, + (Bytef*)pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return ((res == Z_OK) ? S_OK : -1); #elif defined __PS3__ - std::uint32_t destSize = (std::uint32_t)(*pDestSize); - bool res = EdgeZLib::Compress(pDestination, &destSize, pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return ( ( res ) ? S_OK : -1 ); + std::uint32_t destSize = (std::uint32_t)(*pDestSize); + bool res = EdgeZLib::Compress(pDestination, &destSize, pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return ((res) ? S_OK : -1); #else - SIZE_T destSize = (SIZE_T)(*pDestSize); - HRESULT res = XMemCompress(compressionContext, pDestination, &destSize, pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return res; + SIZE_T destSize = (SIZE_T)(*pDestSize); + HRESULT res = XMemCompress(compressionContext, pDestination, &destSize, + pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return res; #endif } -HRESULT Compression::Decompress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ +HRESULT Compression::Decompress(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize) { + if (m_decompressType != + m_localDecompressType) // check if we're decompressing data from a + // different platform + { + // only used for loading a save from a different platform (Sony cloud + // storage cross play) + return DecompressWithType(pDestination, pDestSize, pSource, SrcSize); + } - if(m_decompressType != m_localDecompressType) // check if we're decompressing data from a different platform - { - // only used for loading a save from a different platform (Sony cloud storage cross play) - return DecompressWithType(pDestination, pDestSize, pSource, SrcSize); - } - - // Using zlib for x64 compression - 360 is using native 360 compression and PS3 a stubbed non-compressing version of this -#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || defined __PSVITA__ || defined __linux__ - SIZE_T destSize = (SIZE_T)(*pDestSize); - int res = ::uncompress((Bytef *)pDestination, (uLongf *)&destSize, (Bytef *)pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return ( ( res == Z_OK ) ? S_OK : -1 ); + // Using zlib for x64 compression - 360 is using native 360 compression and + // PS3 a stubbed non-compressing version of this +#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || \ + defined __PSVITA__ || defined __linux__ + SIZE_T destSize = (SIZE_T)(*pDestSize); + int res = ::uncompress((Bytef*)pDestination, (uLongf*)&destSize, + (Bytef*)pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return ((res == Z_OK) ? S_OK : -1); #elif defined __PS3__ - std::uint32_t destSize = (std::uint32_t)(*pDestSize); - bool res = EdgeZLib::Decompress(pDestination, &destSize, pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return ( ( res ) ? S_OK : -1 ); + std::uint32_t destSize = (std::uint32_t)(*pDestSize); + bool res = EdgeZLib::Decompress(pDestination, &destSize, pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return ((res) ? S_OK : -1); #else - SIZE_T destSize = (SIZE_T)(*pDestSize); - HRESULT res = XMemDecompress(decompressionContext, pDestination, (SIZE_T *)&destSize, pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return res; + SIZE_T destSize = (SIZE_T)(*pDestSize); + HRESULT res = XMemDecompress(decompressionContext, pDestination, + (SIZE_T*)&destSize, pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return res; #endif } -// MGH - same as VirtualDecompress in PSVitaStubs, but for use on other platforms (so no virtual mem stuff) +// MGH - same as VirtualDecompress in PSVitaStubs, but for use on other +// platforms (so no virtual mem stuff) #ifndef _XBOX -void Compression::VitaVirtualDecompress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) // (LPVOID buf, SIZE_T dwSize, LPVOID dst) +void Compression::VitaVirtualDecompress( + void* pDestination, unsigned int* pDestSize, void* pSource, + unsigned int SrcSize) // (LPVOID buf, SIZE_T dwSize, LPVOID dst) { - std::uint8_t *pSrc = (std::uint8_t *)pSource; - int Offset = 0; - int Page = 0; - int Index = 0; - std::uint8_t* Data = (std::uint8_t*)pDestination; - while( Index != SrcSize ) - { - // is this a normal value - if( pSrc[Index] ) - { - // just copy it across - Data[Offset] = pSrc[Index]; - Offset += 1; - } - else - { - // how many zeros do we have - Index += 1; - int Count = pSrc[Index]; - // to do : this should really be a sequence of memsets - for( int i = 0;i < Count;i += 1 ) - { - Data[Offset] = 0; - Offset += 1; - } - } - Index += 1; - } - *pDestSize = Offset; + std::uint8_t* pSrc = (std::uint8_t*)pSource; + int Offset = 0; + int Page = 0; + int Index = 0; + std::uint8_t* Data = (std::uint8_t*)pDestination; + while (Index != SrcSize) { + // is this a normal value + if (pSrc[Index]) { + // just copy it across + Data[Offset] = pSrc[Index]; + Offset += 1; + } else { + // how many zeros do we have + Index += 1; + int Count = pSrc[Index]; + // to do : this should really be a sequence of memsets + for (int i = 0; i < Count; i += 1) { + Data[Offset] = 0; + Offset += 1; + } + } + Index += 1; + } + *pDestSize = Offset; } #endif - -HRESULT Compression::DecompressWithType(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize) -{ - switch(m_decompressType) - { - case eCompressionType_RLE: // 4J-JEV, RLE is just that; don't want to break here though. - case eCompressionType_None: - memcpy(pDestination,pSource,SrcSize); - *pDestSize = SrcSize; - return S_OK; - case eCompressionType_LZXRLE: - { +HRESULT Compression::DecompressWithType(void* pDestination, + unsigned int* pDestSize, void* pSource, + unsigned int SrcSize) { + switch (m_decompressType) { + case eCompressionType_RLE: // 4J-JEV, RLE is just that; don't want to + // break here though. + case eCompressionType_None: + memcpy(pDestination, pSource, SrcSize); + *pDestSize = SrcSize; + return S_OK; + case eCompressionType_LZXRLE: { #if (defined _XBOX || defined _DURANGO || defined _WIN64) - SIZE_T destSize = (SIZE_T)(*pDestSize); - HRESULT res = XMemDecompress(decompressionContext, pDestination, (SIZE_T *)&destSize, pSource, SrcSize); - *pDestSize = (unsigned int)destSize; - return res; + SIZE_T destSize = (SIZE_T)(*pDestSize); + HRESULT res = XMemDecompress(decompressionContext, pDestination, + (SIZE_T*)&destSize, pSource, SrcSize); + *pDestSize = (unsigned int)destSize; + return res; #else - assert(0); + assert(0); #endif - } - break; - case eCompressionType_ZLIBRLE: -#if (defined __ORBIS__ || defined __PS3__ || defined _DURANGO || defined _WIN64 || defined __linux__) - if (pDestination != NULL) - return ::uncompress((Bytef*)pDestination, (unsigned long *) pDestSize, (const Bytef*) pSource, SrcSize); // Decompress - else break; // Cannot decompress when destination is NULL + } break; + case eCompressionType_ZLIBRLE: +#if (defined __ORBIS__ || defined __PS3__ || defined _DURANGO || \ + defined _WIN64 || defined __linux__) + if (pDestination != NULL) + return ::uncompress( + (Bytef*)pDestination, (unsigned long*)pDestSize, + (const Bytef*)pSource, SrcSize); // Decompress + else + break; // Cannot decompress when destination is NULL #else - assert(0); - break; + assert(0); + break; #endif - case eCompressionType_PS3ZLIB: -#if (defined __ORBIS__ || defined __PSVITA__ || defined _DURANGO || defined _WIN64) - // Note that we're missing the normal zlib header and footer so we'll use inflate to - // decompress the payload and skip all the CRC checking, etc - if (pDestination != NULL) - { - // Read big-endian srcize from array - std::uint8_t* pbDestSize = reinterpret_cast(pDestSize); - std::uint8_t* pbSource = reinterpret_cast(pSource); - for (int i = 3; i >= 0; i--) { - pbDestSize[3-i] = pbSource[i]; - } + case eCompressionType_PS3ZLIB: +#if (defined __ORBIS__ || defined __PSVITA__ || defined _DURANGO || \ + defined _WIN64) + // Note that we're missing the normal zlib header and footer so + // we'll use inflate to decompress the payload and skip all the CRC + // checking, etc + if (pDestination != NULL) { + // Read big-endian srcize from array + std::uint8_t* pbDestSize = + reinterpret_cast(pDestSize); + std::uint8_t* pbSource = + reinterpret_cast(pSource); + for (int i = 3; i >= 0; i--) { + pbDestSize[3 - i] = pbSource[i]; + } - byteArray uncompr = byteArray(*pDestSize); + byteArray uncompr = byteArray(*pDestSize); - // Build decompression stream - z_stream strm; - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.next_out = uncompr.data; - strm.avail_out = uncompr.length; - // Skip those first 4 bytes - strm.next_in = reinterpret_cast(pSource) + 4; - strm.avail_in = SrcSize - 4; + // Build decompression stream + z_stream strm; + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.next_out = uncompr.data; + strm.avail_out = uncompr.length; + // Skip those first 4 bytes + strm.next_in = reinterpret_cast(pSource) + 4; + strm.avail_in = SrcSize - 4; - int hr = inflateInit2(&strm, -15); + int hr = inflateInit2(&strm, -15); - // Run inflate() on input until end of stream - do { - hr = inflate(&strm, Z_NO_FLUSH); + // Run inflate() on input until end of stream + do { + hr = inflate(&strm, Z_NO_FLUSH); - // Check - switch (hr) { - case Z_NEED_DICT: - case Z_DATA_ERROR: - case Z_MEM_ERROR: - case Z_STREAM_ERROR: - (void)inflateEnd(&strm); - assert(false); - } - } while (hr != Z_STREAM_END); + // Check + switch (hr) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + case Z_STREAM_ERROR: + (void)inflateEnd(&strm); + assert(false); + } + } while (hr != Z_STREAM_END); - inflateEnd(&strm); // MGH - added, to clean up zlib, was causing a leak on Vita when dowloading a PS3 save + inflateEnd( + &strm); // MGH - added, to clean up zlib, was causing a + // leak on Vita when dowloading a PS3 save - // Copy the uncompressed data to the destination - memcpy(pDestination, uncompr.data, uncompr.length); - *pDestSize = uncompr.length; + // Copy the uncompressed data to the destination + memcpy(pDestination, uncompr.data, uncompr.length); + *pDestSize = uncompr.length; - // Delete uncompressed data - delete uncompr.data; - return S_OK; - } - else break; // Cannot decompress when destination is NULL -#else - assert(0); + // Delete uncompressed data + delete uncompr.data; + return S_OK; + } else + break; // Cannot decompress when destination is NULL +#else + assert(0); #endif - } + } - assert(false); - return -1; + assert(false); + return -1; } - - -Compression::Compression() -{ - // Using zlib for x64 compression - 360 is using native 360 compression and PS3 a stubbed non-compressing version of this +Compression::Compression() { + // Using zlib for x64 compression - 360 is using native 360 compression and + // PS3 a stubbed non-compressing version of this #if !(defined __ORBIS__ || defined __PS3__) - // The default parameters for compression context allocated about 6.5MB, reducing the partition size here from the default 512KB to 128KB - // brings this down to about 3MB - XMEMCODEC_PARAMETERS_LZX params; - params.Flags = 0; - params.WindowSize = 128 * 1024; - params.CompressionPartitionSize = 128 * 1024; + // The default parameters for compression context allocated about 6.5MB, + // reducing the partition size here from the default 512KB to 128KB brings + // this down to about 3MB + XMEMCODEC_PARAMETERS_LZX params; + params.Flags = 0; + params.WindowSize = 128 * 1024; + params.CompressionPartitionSize = 128 * 1024; - XMemCreateCompressionContext(XMEMCODEC_LZX,¶ms,0,&compressionContext); - XMemCreateDecompressionContext(XMEMCODEC_LZX,¶ms,0,&decompressionContext); + XMemCreateCompressionContext(XMEMCODEC_LZX, ¶ms, 0, + &compressionContext); + XMemCreateDecompressionContext(XMEMCODEC_LZX, ¶ms, 0, + &decompressionContext); #endif #if defined _XBOX - m_localDecompressType = eCompressionType_LZXRLE; + m_localDecompressType = eCompressionType_LZXRLE; #elif defined __PS3__ - m_localDecompressType = eCompressionType_PS3ZLIB; + m_localDecompressType = eCompressionType_PS3ZLIB; #else - m_localDecompressType = eCompressionType_ZLIBRLE; + m_localDecompressType = eCompressionType_ZLIBRLE; #endif - m_decompressType = m_localDecompressType; + m_decompressType = m_localDecompressType; - InitializeCriticalSection(&rleCompressLock); - InitializeCriticalSection(&rleDecompressLock); + InitializeCriticalSection(&rleCompressLock); + InitializeCriticalSection(&rleDecompressLock); } -Compression::~Compression() -{ +Compression::~Compression() { #if !(defined __ORBIS__ || defined __PS3__ || defined __PSVITA__) - XMemDestroyCompressionContext(compressionContext); - XMemDestroyDecompressionContext(decompressionContext); + XMemDestroyCompressionContext(compressionContext); + XMemDestroyDecompressionContext(decompressionContext); #endif - DeleteCriticalSection(&rleCompressLock); - DeleteCriticalSection(&rleDecompressLock); + DeleteCriticalSection(&rleCompressLock); + DeleteCriticalSection(&rleDecompressLock); } - - -void Compression::SetDecompressionType(ESavePlatform platform) -{ - switch(platform) - { - case SAVE_FILE_PLATFORM_X360: - Compression::getCompression()->SetDecompressionType(Compression::eCompressionType_LZXRLE); - break; - case SAVE_FILE_PLATFORM_PS3: - Compression::getCompression()->SetDecompressionType(Compression::eCompressionType_PS3ZLIB); - break; - case SAVE_FILE_PLATFORM_XBONE: - case SAVE_FILE_PLATFORM_PS4: - case SAVE_FILE_PLATFORM_PSVITA: - case SAVE_FILE_PLATFORM_WIN64: - Compression::getCompression()->SetDecompressionType(Compression::eCompressionType_ZLIBRLE); - break; - default: - assert(0); - break; - } +void Compression::SetDecompressionType(ESavePlatform platform) { + switch (platform) { + case SAVE_FILE_PLATFORM_X360: + Compression::getCompression()->SetDecompressionType( + Compression::eCompressionType_LZXRLE); + break; + case SAVE_FILE_PLATFORM_PS3: + Compression::getCompression()->SetDecompressionType( + Compression::eCompressionType_PS3ZLIB); + break; + case SAVE_FILE_PLATFORM_XBONE: + case SAVE_FILE_PLATFORM_PS4: + case SAVE_FILE_PLATFORM_PSVITA: + case SAVE_FILE_PLATFORM_WIN64: + Compression::getCompression()->SetDecompressionType( + Compression::eCompressionType_ZLIBRLE); + break; + default: + assert(0); + break; + } } /*Compression gCompression;*/ - diff --git a/Minecraft.World/IO/Streams/Compression.h b/Minecraft.World/IO/Streams/Compression.h index 080e2b349..1b2529231 100644 --- a/Minecraft.World/IO/Streams/Compression.h +++ b/Minecraft.World/IO/Streams/Compression.h @@ -5,79 +5,91 @@ #include "../../../Minecraft.Client/Platform/Durango/DurangoExtras/xcompress.h" #endif -class Compression -{ +class Compression { public: - // Enum maps directly some external tools - enum ECompressionTypes - { - eCompressionType_None = 0, - eCompressionType_RLE = 1, - eCompressionType_LZXRLE = 2, - eCompressionType_ZLIBRLE = 3, - eCompressionType_PS3ZLIB = 4 - }; + // Enum maps directly some external tools + enum ECompressionTypes { + eCompressionType_None = 0, + eCompressionType_RLE = 1, + eCompressionType_LZXRLE = 2, + eCompressionType_ZLIBRLE = 3, + eCompressionType_PS3ZLIB = 4 + }; private: - // 4J added so we can have separate contexts and rleBuf for different threads - class ThreadStorage - { - public: - Compression *compression; - ThreadStorage(); - ~ThreadStorage(); - }; - static unsigned int tlsIdx; - static ThreadStorage *tlsDefault; -public: - // Each new thread that needs to use Compression will need to call one of the following 2 functions, to either create its own - // local storage, or share the default storage already allocated by the main thread - static void CreateNewThreadStorage(); - static void UseDefaultThreadStorage(); - static void ReleaseThreadStorage(); - - static Compression *getCompression(); + // 4J added so we can have separate contexts and rleBuf for different + // threads + class ThreadStorage { + public: + Compression* compression; + ThreadStorage(); + ~ThreadStorage(); + }; + static unsigned int tlsIdx; + static ThreadStorage* tlsDefault; public: - HRESULT Compress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); - HRESULT Decompress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); - HRESULT CompressLZXRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); - HRESULT DecompressLZXRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); - HRESULT CompressRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); - HRESULT DecompressRLE(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); + // Each new thread that needs to use Compression will need to call one of + // the following 2 functions, to either create its own local storage, or + // share the default storage already allocated by the main thread + static void CreateNewThreadStorage(); + static void UseDefaultThreadStorage(); + static void ReleaseThreadStorage(); + + static Compression* getCompression(); + +public: + HRESULT Compress(void* pDestination, unsigned int* pDestSize, void* pSource, + unsigned int SrcSize); + HRESULT Decompress(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); + HRESULT CompressLZXRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); + HRESULT DecompressLZXRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); + HRESULT CompressRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); + HRESULT DecompressRLE(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); #ifndef _XBOX - static void VitaVirtualDecompress(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); + static void VitaVirtualDecompress(void* pDestination, + unsigned int* pDestSize, void* pSource, + unsigned int SrcSize); #endif - void SetDecompressionType(ECompressionTypes type) { m_decompressType = type; } // for loading a save from a different platform (Sony cloud storage cross play) - ECompressionTypes GetDecompressionType() { return m_decompressType; } - void SetDecompressionType(ESavePlatform platform); + void SetDecompressionType(ECompressionTypes type) { + m_decompressType = type; + } // for loading a save from a different platform (Sony cloud storage cross + // play) + ECompressionTypes GetDecompressionType() { return m_decompressType; } + void SetDecompressionType(ESavePlatform platform); + + Compression(); + ~Compression(); - Compression(); - ~Compression(); private: - - HRESULT DecompressWithType(void *pDestination, unsigned int *pDestSize, void *pSource, unsigned int SrcSize); + HRESULT DecompressWithType(void* pDestination, unsigned int* pDestSize, + void* pSource, unsigned int SrcSize); #if defined __ORBIS__ || defined __PS3__ #else - XMEMCOMPRESSION_CONTEXT compressionContext; - XMEMDECOMPRESSION_CONTEXT decompressionContext; + XMEMCOMPRESSION_CONTEXT compressionContext; + XMEMDECOMPRESSION_CONTEXT decompressionContext; #endif - CRITICAL_SECTION rleCompressLock; - CRITICAL_SECTION rleDecompressLock; - - unsigned char rleCompressBuf[1024*100]; - static const unsigned int staticRleSize = 1024*200; - unsigned char rleDecompressBuf[staticRleSize]; - ECompressionTypes m_decompressType; - ECompressionTypes m_localDecompressType; + CRITICAL_SECTION rleCompressLock; + CRITICAL_SECTION rleDecompressLock; + unsigned char rleCompressBuf[1024 * 100]; + static const unsigned int staticRleSize = 1024 * 200; + unsigned char rleDecompressBuf[staticRleSize]; + ECompressionTypes m_decompressType; + ECompressionTypes m_localDecompressType; }; -//extern Compression gCompression; +// extern Compression gCompression; -#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || defined __PSVITA__ || defined __linux__ +#if defined __ORBIS__ || defined _DURANGO || defined _WIN64 || \ + defined __PSVITA__ || defined __linux__ #define APPROPRIATE_COMPRESSION_TYPE Compression::eCompressionType_ZLIBRLE #elif defined __PS3__ #define APPROPRIATE_COMPRESSION_TYPE Compression::eCompressionType_PS3ZLIB diff --git a/Minecraft.World/IO/Streams/DataInput.h b/Minecraft.World/IO/Streams/DataInput.h index 76a8075bc..2657ae1d9 100644 --- a/Minecraft.World/IO/Streams/DataInput.h +++ b/Minecraft.World/IO/Streams/DataInput.h @@ -1,22 +1,21 @@ #pragma once -class DataInput -{ +class DataInput { public: - virtual int read() = 0; - virtual int read(byteArray b) = 0; - virtual int read(byteArray b, unsigned int offset, unsigned int length) = 0; - virtual bool readBoolean() = 0; - virtual uint8_t readByte() = 0; - virtual unsigned char readUnsignedByte() = 0; - virtual bool readFully(byteArray a) = 0; - virtual double readDouble() = 0; - virtual float readFloat() = 0; - virtual int readInt() = 0; - virtual __int64 readLong() = 0; - virtual short readShort() = 0; - virtual wchar_t readChar() = 0; - virtual std::wstring readUTF() = 0; - virtual PlayerUID readPlayerUID() = 0; // 4J Added - virtual int skipBytes(int n) = 0; + virtual int read() = 0; + virtual int read(byteArray b) = 0; + virtual int read(byteArray b, unsigned int offset, unsigned int length) = 0; + virtual bool readBoolean() = 0; + virtual uint8_t readByte() = 0; + virtual unsigned char readUnsignedByte() = 0; + virtual bool readFully(byteArray a) = 0; + virtual double readDouble() = 0; + virtual float readFloat() = 0; + virtual int readInt() = 0; + virtual __int64 readLong() = 0; + virtual short readShort() = 0; + virtual wchar_t readChar() = 0; + virtual std::wstring readUTF() = 0; + virtual PlayerUID readPlayerUID() = 0; // 4J Added + virtual int skipBytes(int n) = 0; }; diff --git a/Minecraft.World/IO/Streams/DataInputStream.cpp b/Minecraft.World/IO/Streams/DataInputStream.cpp index 3809dfe58..5b459faba 100644 --- a/Minecraft.World/IO/Streams/DataInputStream.cpp +++ b/Minecraft.World/IO/Streams/DataInputStream.cpp @@ -3,619 +3,599 @@ #include "DataInputStream.h" -//Creates a DataInputStream that uses the specified underlying InputStream. -//Parameters: -//in - the specified input stream -DataInputStream::DataInputStream(InputStream *in) : stream( in ) -{ +// Creates a DataInputStream that uses the specified underlying InputStream. +// Parameters: +// in - the specified input stream +DataInputStream::DataInputStream(InputStream* in) : stream(in) {} + +// Reads the next byte of data from this input stream. The value byte is +// returned as an int in the range 0 to 255. If no byte is available because the +// end of the stream has been reached, the value -1 is returned. This method +// blocks until input data is available, the end of the stream is detected, or +// an exception is thrown. This method simply performs in.read() and returns the +// result. +int DataInputStream::read() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::read() called but underlying stream is NULL\n"); + return -1; + } + return stream->read(); } -//Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. -//If no byte is available because the end of the stream has been reached, the value -1 is returned. -//This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. -//This method simply performs in.read() and returns the result. -int DataInputStream::read() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::read() called but underlying stream is NULL\n"); - return -1; - } - return stream->read(); -} - -//Reads some number of bytes from the contained input stream and stores them into the buffer array b. -//The number of bytes actually read is returned as an integer. This method blocks until input data is available, -//end of file is detected, or an exception is thrown. -//If b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are read and 0 is returned; -//otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, -//the value -1 is returned; otherwise, at least one byte is read and stored into b. +// Reads some number of bytes from the contained input stream and stores them +// into the buffer array b. The number of bytes actually read is returned as an +// integer. This method blocks until input data is available, end of file is +// detected, or an exception is thrown. If b is null, a NullPointerException is +// thrown. If the length of b is zero, then no bytes are read and 0 is returned; +// otherwise, there is an attempt to read at least one byte. If no byte is +// available because the stream is at end of file, the value -1 is returned; +// otherwise, at least one byte is read and stored into b. // -//The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, -//equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], -//leaving elements b[k] through b[b.length-1] unaffected. +// The first byte read is stored into element b[0], the next one into b[1], and +// so on. The number of bytes read is, at most, equal to the length of b. Let k +// be the number of bytes actually read; these bytes will be stored in elements +// b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected. // -//The read(b) method has the same effect as: +// The read(b) method has the same effect as: // -// read(b, 0, b.length) -// -//Overrides: -//read in class FilterInputStream -//Parameters: -//b - the buffer into which the data is read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. -int DataInputStream::read(byteArray b) -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::read(byteArray) called but underlying stream is NULL\n"); - return -1; - } - return read( b, 0, b.length ); -} - -//Reads up to len bytes of data from the contained input stream into an array of bytes. An attempt is made to read as many as len bytes, -//but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer. -//This method blocks until input data is available, end of file is detected, or an exception is thrown. +// read(b, 0, b.length) // -//If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. -//If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b. +// Overrides: +// read in class FilterInputStream +// Parameters: +// b - the buffer into which the data is read. +// Returns: +// the total number of bytes read into the buffer, or -1 if there is no more +// data because the end of the stream has been reached. +int DataInputStream::read(byteArray b) { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::read(byteArray) called but underlying stream is " + "NULL\n"); + return -1; + } + return read(b, 0, b.length); +} + +// Reads up to len bytes of data from the contained input stream into an array +// of bytes. An attempt is made to read as many as len bytes, but a smaller +// number may be read, possibly zero. The number of bytes actually read is +// returned as an integer. This method blocks until input data is available, end +// of file is detected, or an exception is thrown. // -//The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, -//at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], -//leaving elements b[off+k] through b[off+len-1] unaffected. +// If len is zero, then no bytes are read and 0 is returned; otherwise, there is +// an attempt to read at least one byte. If no byte is available because the +// stream is at end of file, the value -1 is returned; otherwise, at least one +// byte is read and stored into b. // -//In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected. +// The first byte read is stored into element b[off], the next one into +// b[off+1], and so on. The number of bytes read is, at most, equal to len. Let +// k be the number of bytes actually read; these bytes will be stored in +// elements b[off] through b[off+k-1], leaving elements b[off+k] through +// b[off+len-1] unaffected. // -//Overrides: -//read in class FilterInputStream -//Parameters: -//b - the buffer into which the data is read. -//off - the start offset in the destination array b -//len - the maximum number of bytes read. -//Returns: -//the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. -int DataInputStream::read(byteArray b, unsigned int offset, unsigned int length) -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::read(byteArray,offset,length) called but underlying stream is NULL\n"); - return -1; - } - return stream->read( b, offset, length ); -} - -//Closes this input stream and releases any system resources associated with the stream. This method simply performs in.close() -void DataInputStream::close() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::close() called but underlying stream is NULL\n"); - return; - } - stream->close(); -} - -//Reads one input byte and returns true if that byte is nonzero, false if that byte is zero. This method is suitable for reading -//the byte written by the writeBoolean method of interface DataOutput. -//Returns: -//the boolean value read. -bool DataInputStream::readBoolean() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readBoolean() but underlying stream is NULL\n"); - return false; - } - return stream->read() != 0; -} - -//Reads and returns one input byte. The byte is treated as a signed value in the range -128 through 127, inclusive. -//This method is suitable for reading the byte written by the writeByte method of interface DataOutput. -//Returns: -//the 8-bit value read. -uint8_t DataInputStream::readByte() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readByte() but underlying stream is NULL\n"); - return 0; - } - return (uint8_t) stream->read(); -} - -unsigned char DataInputStream::readUnsignedByte() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readUnsignedByte() but underlying stream is NULL\n"); - return 0; - } - return (unsigned char) stream->read(); -} - -//Reads two input bytes and returns a char value. Let a be the first byte read and b be the second byte. The value returned is: -//(char)((a << 8) | (b & 0xff)) -// -//This method is suitable for reading bytes written by the writeChar method of interface DataOutput. -//Returns: -//the char value read. -wchar_t DataInputStream::readChar() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readChar() but underlying stream is NULL\n"); - return 0; - } - int a = stream->read(); - int b = stream->read(); - return (wchar_t)((a << 8) | (b & 0xff)); -} - -//Reads some bytes from an input stream and stores them into the buffer array b. The number of bytes read is equal to the length of b. -//This method blocks until one of the following conditions occurs: +// In every case, elements b[0] through b[off] and elements b[off+len] through +// b[b.length-1] are unaffected. // -//b.length bytes of input data are available, in which case a normal return is made. -//End of file is detected, in which case an EOFException is thrown. -//An I/O error occurs, in which case an IOException other than EOFException is thrown. -//If b is null, a NullPointerException is thrown. If b.length is zero, then no bytes are read. Otherwise, the first byte read is -//stored into element b[0], the next one into b[1], and so on. If an exception is thrown from this method, then it may be that some but -//not all bytes of b have been updated with data from the input stream. +// Overrides: +// read in class FilterInputStream +// Parameters: +// b - the buffer into which the data is read. +// off - the start offset in the destination array b +// len - the maximum number of bytes read. +// Returns: +// the total number of bytes read into the buffer, or -1 if there is no more +// data because the end of the stream has been reached. +int DataInputStream::read(byteArray b, unsigned int offset, + unsigned int length) { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::read(byteArray,offset,length) called but " + "underlying stream is NULL\n"); + return -1; + } + return stream->read(b, offset, length); +} + +// Closes this input stream and releases any system resources associated with +// the stream. This method simply performs in.close() +void DataInputStream::close() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::close() called but underlying stream is NULL\n"); + return; + } + stream->close(); +} + +// Reads one input byte and returns true if that byte is nonzero, false if that +// byte is zero. This method is suitable for reading the byte written by the +// writeBoolean method of interface DataOutput. Returns: the boolean value read. +bool DataInputStream::readBoolean() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readBoolean() but underlying stream is NULL\n"); + return false; + } + return stream->read() != 0; +} + +// Reads and returns one input byte. The byte is treated as a signed value in +// the range -128 through 127, inclusive. This method is suitable for reading +// the byte written by the writeByte method of interface DataOutput. Returns: +// the 8-bit value read. +uint8_t DataInputStream::readByte() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readByte() but underlying stream is NULL\n"); + return 0; + } + return (uint8_t)stream->read(); +} + +unsigned char DataInputStream::readUnsignedByte() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readUnsignedByte() but underlying stream is " + "NULL\n"); + return 0; + } + return (unsigned char)stream->read(); +} + +// Reads two input bytes and returns a char value. Let a be the first byte read +// and b be the second byte. The value returned is: (char)((a << 8) | (b & +//0xff)) // -//Parameters: -//b - the buffer into which the data is read. -bool DataInputStream::readFully(byteArray b) -{ - // TODO 4J Stu - I am not entirely sure if this matches the implementation of the Java library - // TODO 4J Stu - Need to handle exceptions here is we throw them in other InputStreams - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readFully(byteArray) but underlying stream is NULL\n"); - return false; - } - for(unsigned int i = 0; i < b.length ;i++) - { - int byteRead = stream->read(); - if( byteRead == -1 ) - { - return false; - } - else - { - b[i] = static_cast(byteRead); - } - } - return true; +// This method is suitable for reading bytes written by the writeChar method of +// interface DataOutput. Returns: the char value read. +wchar_t DataInputStream::readChar() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readChar() but underlying stream is NULL\n"); + return 0; + } + int a = stream->read(); + int b = stream->read(); + return (wchar_t)((a << 8) | (b & 0xff)); } -bool DataInputStream::readFully(charArray b) -{ - // TODO 4J Stu - I am not entirely sure if this matches the implementation of the Java library - // TODO 4J Stu - Need to handle exceptions here is we throw them in other InputStreams - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readFully(charArray) but underlying stream is NULL\n"); - return false; - } - for(unsigned int i = 0; i < b.length ;i++) - { - int byteRead = stream->read(); - if( byteRead == -1 ) - { - return false; - } - else - { - b[i] = byteRead; - } - } - return true; -} - -//Reads eight input bytes and returns a double value. It does this by first constructing a long value in exactly the manner -//of the readlong method, then converting this long value to a double in exactly the manner of the method Double.longBitsToDouble. -//This method is suitable for reading bytes written by the writeDouble method of interface DataOutput. -//Returns: -//the double value read. -double DataInputStream::readDouble() -{ - __int64 bits = readLong(); - - return Double::longBitsToDouble( bits ); -} - -//Reads four input bytes and returns a float value. It does this by first constructing an int value in exactly the manner -//of the readInt method, then converting this int value to a float in exactly the manner of the method Float.intBitsToFloat. -//This method is suitable for reading bytes written by the writeFloat method of interface DataOutput. -//Returns: -//the float value read. -float DataInputStream::readFloat() -{ - int bits = readInt(); - - return Float::intBitsToFloat( bits ); -} - -//Reads four input bytes and returns an int value. Let a-d be the first through fourth bytes read. The value returned is: -// -// (((a & 0xff) << 24) | ((b & 0xff) << 16) | -// ((c & 0xff) << 8) | (d & 0xff)) -// -//This method is suitable for reading bytes written by the writeInt method of interface DataOutput. -//Returns: -//the int value read. -int DataInputStream::readInt() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readInt() but underlying stream is NULL\n"); - return 0; - } - int a = stream->read(); - int b = stream->read(); - int c = stream->read(); - int d = stream->read(); - int bits = (((a & 0xff) << 24) | ((b & 0xff) << 16) | - ((c & 0xff) << 8) | (d & 0xff)); - return bits; -} - -//Reads eight input bytes and returns a long value. Let a-h be the first through eighth bytes read. The value returned is: -// -// (((long)(a & 0xff) << 56) | -// ((long)(b & 0xff) << 48) | -// ((long)(c & 0xff) << 40) | -// ((long)(d & 0xff) << 32) | -// ((long)(e & 0xff) << 24) | -// ((long)(f & 0xff) << 16) | -// ((long)(g & 0xff) << 8) | -// ((long)(h & 0xff))) -// -//This method is suitable for reading bytes written by the writeLong method of interface DataOutput. +// Reads some bytes from an input stream and stores them into the buffer array +// b. The number of bytes read is equal to the length of b. This method blocks +// until one of the following conditions occurs: // -//Returns: -//the long value read. -__int64 DataInputStream::readLong() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readLong() but underlying stream is NULL\n"); - return 0; - } - __int64 a = stream->read(); - __int64 b = stream->read(); - __int64 c = stream->read(); - __int64 d = stream->read(); - __int64 e = stream->read(); - __int64 f = stream->read(); - __int64 g = stream->read(); - __int64 h = stream->read(); - - __int64 bits = (((a & 0xff) << 56) | - ((b & 0xff) << 48) | - ((c & 0xff) << 40) | - ((d & 0xff) << 32) | - ((e & 0xff) << 24) | - ((f & 0xff) << 16) | - ((g & 0xff) << 8) | - ((h & 0xff))); - - return bits; +// b.length bytes of input data are available, in which case a normal return is +// made. End of file is detected, in which case an EOFException is thrown. An +// I/O error occurs, in which case an IOException other than EOFException is +// thrown. If b is null, a NullPointerException is thrown. If b.length is zero, +// then no bytes are read. Otherwise, the first byte read is stored into element +// b[0], the next one into b[1], and so on. If an exception is thrown from this +// method, then it may be that some but not all bytes of b have been updated +// with data from the input stream. +// +// Parameters: +// b - the buffer into which the data is read. +bool DataInputStream::readFully(byteArray b) { + // TODO 4J Stu - I am not entirely sure if this matches the implementation + // of the Java library + // TODO 4J Stu - Need to handle exceptions here is we throw them in other + // InputStreams + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readFully(byteArray) but underlying stream is " + "NULL\n"); + return false; + } + for (unsigned int i = 0; i < b.length; i++) { + int byteRead = stream->read(); + if (byteRead == -1) { + return false; + } else { + b[i] = static_cast(byteRead); + } + } + return true; } -//Reads two input bytes and returns a short value. Let a be the first byte read and b be the second byte. The value returned is: -//(short)((a << 8) | (b & 0xff)) -// -//This method is suitable for reading the bytes written by the writeShort method of interface DataOutput. -//Returns: -//the 16-bit value read. -short DataInputStream::readShort() -{ - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readShort() but underlying stream is NULL\n"); - return 0; - } - int a = stream->read(); - int b = stream->read(); - return (short)((a << 8) | (b & 0xff)); +bool DataInputStream::readFully(charArray b) { + // TODO 4J Stu - I am not entirely sure if this matches the implementation + // of the Java library + // TODO 4J Stu - Need to handle exceptions here is we throw them in other + // InputStreams + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readFully(charArray) but underlying stream is " + "NULL\n"); + return false; + } + for (unsigned int i = 0; i < b.length; i++) { + int byteRead = stream->read(); + if (byteRead == -1) { + return false; + } else { + b[i] = byteRead; + } + } + return true; } -//Reads in a string that has been encoded using a modified UTF-8 format. The general contract of readUTF is that it reads a representation -//of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String. -//First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . -//This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted -//to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. -//The byte following a group, if any, is the first byte of the next group. +// Reads eight input bytes and returns a double value. It does this by first +// constructing a long value in exactly the manner of the readlong method, then +// converting this long value to a double in exactly the manner of the method +// Double.longBitsToDouble. This method is suitable for reading bytes written by +// the writeDouble method of interface DataOutput. Returns: the double value +// read. +double DataInputStream::readDouble() { + __int64 bits = readLong(); + + return Double::longBitsToDouble(bits); +} + +// Reads four input bytes and returns a float value. It does this by first +// constructing an int value in exactly the manner of the readInt method, then +// converting this int value to a float in exactly the manner of the method +// Float.intBitsToFloat. This method is suitable for reading bytes written by +// the writeFloat method of interface DataOutput. Returns: the float value read. +float DataInputStream::readFloat() { + int bits = readInt(); + + return Float::intBitsToFloat(bits); +} + +// Reads four input bytes and returns an int value. Let a-d be the first through +// fourth bytes read. The value returned is: // -//If the first byte of a group matches the bit pattern 0xxxxxxx (where x means "may be 0 or 1"), then the group consists of just that byte. -//The byte is zero-extended to form a character. +// (((a & 0xff) << 24) | ((b & 0xff) << 16) | +// ((c & 0xff) << 8) | (d & 0xff)) // -//If the first byte of a group matches the bit pattern 110xxxxx, then the group consists of that byte a and a second byte b. -//If there is no byte b (because byte a was the last of the bytes to be read), or if byte b does not match the bit pattern 10xxxxxx, -//then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character: +// This method is suitable for reading bytes written by the writeInt method of +// interface DataOutput. Returns: the int value read. +int DataInputStream::readInt() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readInt() but underlying stream is NULL\n"); + return 0; + } + int a = stream->read(); + int b = stream->read(); + int c = stream->read(); + int d = stream->read(); + int bits = (((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | + (d & 0xff)); + return bits; +} + +// Reads eight input bytes and returns a long value. Let a-h be the first +// through eighth bytes read. The value returned is: +// +// (((long)(a & 0xff) << 56) | +// ((long)(b & 0xff) << 48) | +// ((long)(c & 0xff) << 40) | +// ((long)(d & 0xff) << 32) | +// ((long)(e & 0xff) << 24) | +// ((long)(f & 0xff) << 16) | +// ((long)(g & 0xff) << 8) | +// ((long)(h & 0xff))) +// +// This method is suitable for reading bytes written by the writeLong method of +// interface DataOutput. +// +// Returns: +// the long value read. +__int64 DataInputStream::readLong() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readLong() but underlying stream is NULL\n"); + return 0; + } + __int64 a = stream->read(); + __int64 b = stream->read(); + __int64 c = stream->read(); + __int64 d = stream->read(); + __int64 e = stream->read(); + __int64 f = stream->read(); + __int64 g = stream->read(); + __int64 h = stream->read(); + + __int64 bits = + (((a & 0xff) << 56) | ((b & 0xff) << 48) | ((c & 0xff) << 40) | + ((d & 0xff) << 32) | ((e & 0xff) << 24) | ((f & 0xff) << 16) | + ((g & 0xff) << 8) | ((h & 0xff))); + + return bits; +} + +// Reads two input bytes and returns a short value. Let a be the first byte read +// and b be the second byte. The value returned is: (short)((a << 8) | (b & +//0xff)) +// +// This method is suitable for reading the bytes written by the writeShort +// method of interface DataOutput. Returns: the 16-bit value read. +short DataInputStream::readShort() { + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readShort() but underlying stream is NULL\n"); + return 0; + } + int a = stream->read(); + int b = stream->read(); + return (short)((a << 8) | (b & 0xff)); +} + +// Reads in a string that has been encoded using a modified UTF-8 format. The +// general contract of readUTF is that it reads a representation of a Unicode +// character string encoded in modified UTF-8 format; this string of characters +// is then returned as a String. First, two bytes are read and used to construct +// an unsigned 16-bit integer in exactly the manner of the readUnsignedShort +// method . This integer value is called the UTF length and specifies the number +// of additional bytes to be read. These bytes are then converted to characters +// by considering them in groups. The length of each group is computed from the +// value of the first byte of the group. The byte following a group, if any, is +// the first byte of the next group. +// +// If the first byte of a group matches the bit pattern 0xxxxxxx (where x means +// "may be 0 or 1"), then the group consists of just that byte. The byte is +// zero-extended to form a character. +// +// If the first byte of a group matches the bit pattern 110xxxxx, then the group +// consists of that byte a and a second byte b. If there is no byte b (because +// byte a was the last of the bytes to be read), or if byte b does not match the +// bit pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the +// group is converted to the character: // //(char)(((a& 0x1F) << 6) | (b & 0x3F)) -// -//If the first byte of a group matches the bit pattern 1110xxxx, then the group consists of that byte a and two more bytes b and c. -//If there is no byte c (because byte a was one of the last two of the bytes to be read), or either byte b or byte c does not match the bit -//pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character: // -// (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)) -// -//If the first byte of a group matches the pattern 1111xxxx or the pattern 10xxxxxx, then a UTFDataFormatException is thrown. -//If end of file is encountered at any time during this entire process, then an EOFException is thrown. +// If the first byte of a group matches the bit pattern 1110xxxx, then the group +// consists of that byte a and two more bytes b and c. If there is no byte c +// (because byte a was one of the last two of the bytes to be read), or either +// byte b or byte c does not match the bit pattern 10xxxxxx, then a +// UTFDataFormatException is thrown. Otherwise, the group is converted to the +// character: // -//After every group has been converted to a character by this process, the characters are gathered, in the same order in which their -//corresponding groups were read from the input stream, to form a String, which is returned. +// (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)) // -//The writeUTF method of interface DataOutput may be used to write data that is suitable for reading by this method. +// If the first byte of a group matches the pattern 1111xxxx or the pattern +// 10xxxxxx, then a UTFDataFormatException is thrown. If end of file is +// encountered at any time during this entire process, then an EOFException is +// thrown. // -//Returns: -//a Unicode string. -std::wstring DataInputStream::readUTF() -{ - std::wstring outputString; - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readUTF() but underlying stream is NULL\n"); - return outputString; - } - int a = stream->read(); - int b = stream->read(); - unsigned short UTFLength = (unsigned short) (((a & 0xff) << 8) | (b & 0xff)); +// After every group has been converted to a character by this process, the +// characters are gathered, in the same order in which their corresponding +// groups were read from the input stream, to form a String, which is returned. +// +// The writeUTF method of interface DataOutput may be used to write data that is +// suitable for reading by this method. +// +// Returns: +// a Unicode string. +std::wstring DataInputStream::readUTF() { + std::wstring outputString; + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readUTF() but underlying stream is NULL\n"); + return outputString; + } + int a = stream->read(); + int b = stream->read(); + unsigned short UTFLength = (unsigned short)(((a & 0xff) << 8) | (b & 0xff)); - //// 4J Stu - I decided while writing DataOutputStream that we didn't need to bother using the UTF8 format - //// used in the java libs, and just write in/out as wchar_t all the time + //// 4J Stu - I decided while writing DataOutputStream that we didn't need + ///to bother using the UTF8 format / used in the java libs, and just write + ///in/out as wchar_t all the time - /*for( unsigned short i = 0; i < UTFLength; i++) - { - wchar_t theChar = readChar(); - outputString.push_back(theChar); - }*/ + /*for( unsigned short i = 0; i < UTFLength; i++) + { + wchar_t theChar = readChar(); + outputString.push_back(theChar); + }*/ - - unsigned short currentByteIndex = 0; - while( currentByteIndex < UTFLength ) - { - int firstByte = stream->read(); - currentByteIndex++; + unsigned short currentByteIndex = 0; + while (currentByteIndex < UTFLength) { + int firstByte = stream->read(); + currentByteIndex++; - if( firstByte == -1 ) - // TODO 4J Stu - EOFException - break; + if (firstByte == -1) + // TODO 4J Stu - EOFException + break; - // Masking patterns: - // 10000000 = 0x80 // Match only highest bit - // 11000000 = 0xC0 // Match only highest two bits - // 11100000 = 0xE0 // Match only highest three bits - // 11110000 = 0xF0 // Match only highest four bits + // Masking patterns: + // 10000000 = 0x80 // Match only highest bit + // 11000000 = 0xC0 // Match only highest two bits + // 11100000 = 0xE0 // Match only highest three bits + // 11110000 = 0xF0 // Match only highest four bits - // Matching patterns: - // 10xxxxxx = 0x80 // ERROR, or second/third byte - // 1111xxxx = 0xF0 //ERROR - // 0xxxxxxx = 0x00 // One byte UTF - // 110xxxxx = 0xC0 // Two byte UTF - // 1110xxxx = 0xE0 // Three byte UTF - if( ( (firstByte & 0xC0 ) == 0x80 ) || ( (firstByte & 0xF0) == 0xF0) ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } - else if( (firstByte & 0x80) == 0x00 ) - { - // One byte UTF - wchar_t readChar = (wchar_t)firstByte; - outputString.push_back( readChar ); - continue; - } - else if( (firstByte & 0xE0) == 0xC0 ) - { - // Two byte UTF + // Matching patterns: + // 10xxxxxx = 0x80 // ERROR, or second/third byte + // 1111xxxx = 0xF0 //ERROR + // 0xxxxxxx = 0x00 // One byte UTF + // 110xxxxx = 0xC0 // Two byte UTF + // 1110xxxx = 0xE0 // Three byte UTF + if (((firstByte & 0xC0) == 0x80) || ((firstByte & 0xF0) == 0xF0)) { + // TODO 4J Stu - UTFDataFormatException + break; + } else if ((firstByte & 0x80) == 0x00) { + // One byte UTF + wchar_t readChar = (wchar_t)firstByte; + outputString.push_back(readChar); + continue; + } else if ((firstByte & 0xE0) == 0xC0) { + // Two byte UTF - // No more bytes to read - if( !(currentByteIndex < UTFLength) ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } + // No more bytes to read + if (!(currentByteIndex < UTFLength)) { + // TODO 4J Stu - UTFDataFormatException + break; + } - int secondByte = stream->read(); - currentByteIndex++; + int secondByte = stream->read(); + currentByteIndex++; - // No second byte - if( secondByte == -1 ) - { - // TODO 4J Stu - EOFException - break; - } - // Incorrect second byte pattern - else if( (secondByte & 0xC0 ) != 0x80 ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } + // No second byte + if (secondByte == -1) { + // TODO 4J Stu - EOFException + break; + } + // Incorrect second byte pattern + else if ((secondByte & 0xC0) != 0x80) { + // TODO 4J Stu - UTFDataFormatException + break; + } - wchar_t readChar = (wchar_t)( ((firstByte& 0x1F) << 6) | (secondByte & 0x3F) ); - outputString.push_back( readChar ); - continue; - } - else if( (firstByte & 0xF0) == 0xE0 ) - { - // Three byte UTF + wchar_t readChar = + (wchar_t)(((firstByte & 0x1F) << 6) | (secondByte & 0x3F)); + outputString.push_back(readChar); + continue; + } else if ((firstByte & 0xF0) == 0xE0) { + // Three byte UTF - // No more bytes to read - if( !(currentByteIndex < UTFLength) ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } + // No more bytes to read + if (!(currentByteIndex < UTFLength)) { + // TODO 4J Stu - UTFDataFormatException + break; + } - int secondByte = stream->read(); - currentByteIndex++; + int secondByte = stream->read(); + currentByteIndex++; - // No second byte - if( secondByte == -1 ) - { - // TODO 4J Stu - EOFException - break; - } + // No second byte + if (secondByte == -1) { + // TODO 4J Stu - EOFException + break; + } - // No more bytes to read - if( !(currentByteIndex < UTFLength) ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } + // No more bytes to read + if (!(currentByteIndex < UTFLength)) { + // TODO 4J Stu - UTFDataFormatException + break; + } - int thirdByte = stream->read(); - currentByteIndex++; + int thirdByte = stream->read(); + currentByteIndex++; - // No third byte - if( thirdByte == -1 ) - { - // TODO 4J Stu - EOFException - break; - } - // Incorrect second or third byte pattern - else if( ( (secondByte & 0xC0 ) != 0x80 ) || ( (thirdByte & 0xC0 ) != 0x80 ) ) - { - // TODO 4J Stu - UTFDataFormatException - break; - } + // No third byte + if (thirdByte == -1) { + // TODO 4J Stu - EOFException + break; + } + // Incorrect second or third byte pattern + else if (((secondByte & 0xC0) != 0x80) || + ((thirdByte & 0xC0) != 0x80)) { + // TODO 4J Stu - UTFDataFormatException + break; + } - wchar_t readChar = (wchar_t)(((firstByte & 0x0F) << 12) | ((secondByte & 0x3F) << 6) | (thirdByte & 0x3F)); - outputString.push_back( readChar ); - continue; - } - } - - return outputString; + wchar_t readChar = + (wchar_t)(((firstByte & 0x0F) << 12) | + ((secondByte & 0x3F) << 6) | (thirdByte & 0x3F)); + outputString.push_back(readChar); + continue; + } + } + + return outputString; } -int DataInputStream::readUTFChar() -{ - int returnValue = -1; - if (stream == NULL) - { - app.DebugPrintf("DataInputStream::readUTFChar() but underlying stream is NULL\n"); - return returnValue; - } - int firstByte = stream->read(); +int DataInputStream::readUTFChar() { + int returnValue = -1; + if (stream == NULL) { + app.DebugPrintf( + "DataInputStream::readUTFChar() but underlying stream is NULL\n"); + return returnValue; + } + int firstByte = stream->read(); - if( firstByte == -1 ) - // TODO 4J Stu - EOFException - return returnValue; + if (firstByte == -1) + // TODO 4J Stu - EOFException + return returnValue; - // Masking patterns: - // 10000000 = 0x80 // Match only highest bit - // 11000000 = 0xC0 // Match only highest two bits - // 11100000 = 0xE0 // Match only highest three bits - // 11110000 = 0xF0 // Match only highest four bits + // Masking patterns: + // 10000000 = 0x80 // Match only highest bit + // 11000000 = 0xC0 // Match only highest two bits + // 11100000 = 0xE0 // Match only highest three bits + // 11110000 = 0xF0 // Match only highest four bits - // Matching patterns: - // 10xxxxxx = 0x80 // ERROR, or second/third byte - // 1111xxxx = 0xF0 //ERROR - // 0xxxxxxx = 0x00 // One byte UTF - // 110xxxxx = 0xC0 // Two byte UTF - // 1110xxxx = 0xE0 // Three byte UTF - if( ( (firstByte & 0xC0 ) == 0x80 ) || ( (firstByte & 0xF0) == 0xF0) ) - { - // TODO 4J Stu - UTFDataFormatException - return returnValue; - } - else if( (firstByte & 0x80) == 0x00 ) - { - // One byte UTF - returnValue = firstByte; - } - else if( (firstByte & 0xE0) == 0xC0 ) - { - // Two byte UTF - int secondByte = stream->read(); + // Matching patterns: + // 10xxxxxx = 0x80 // ERROR, or second/third byte + // 1111xxxx = 0xF0 //ERROR + // 0xxxxxxx = 0x00 // One byte UTF + // 110xxxxx = 0xC0 // Two byte UTF + // 1110xxxx = 0xE0 // Three byte UTF + if (((firstByte & 0xC0) == 0x80) || ((firstByte & 0xF0) == 0xF0)) { + // TODO 4J Stu - UTFDataFormatException + return returnValue; + } else if ((firstByte & 0x80) == 0x00) { + // One byte UTF + returnValue = firstByte; + } else if ((firstByte & 0xE0) == 0xC0) { + // Two byte UTF + int secondByte = stream->read(); - // No second byte - if( secondByte == -1 ) - { - // TODO 4J Stu - EOFException - return returnValue; - } - // Incorrect second byte pattern - else if( (secondByte & 0xC0 ) != 0x80 ) - { - // TODO 4J Stu - UTFDataFormatException - return returnValue; - } + // No second byte + if (secondByte == -1) { + // TODO 4J Stu - EOFException + return returnValue; + } + // Incorrect second byte pattern + else if ((secondByte & 0xC0) != 0x80) { + // TODO 4J Stu - UTFDataFormatException + return returnValue; + } - returnValue = ((firstByte& 0x1F) << 6) | (secondByte & 0x3F); - } - else if( (firstByte & 0xF0) == 0xE0 ) - { - // Three byte UTF + returnValue = ((firstByte & 0x1F) << 6) | (secondByte & 0x3F); + } else if ((firstByte & 0xF0) == 0xE0) { + // Three byte UTF - int secondByte = stream->read(); + int secondByte = stream->read(); - // No second byte - if( secondByte == -1 ) - { - // TODO 4J Stu - EOFException - return returnValue; - } + // No second byte + if (secondByte == -1) { + // TODO 4J Stu - EOFException + return returnValue; + } - int thirdByte = stream->read(); + int thirdByte = stream->read(); - // No third byte - if( thirdByte == -1 ) - { - // TODO 4J Stu - EOFException - return returnValue; - } - // Incorrect second or third byte pattern - else if( ( (secondByte & 0xC0 ) != 0x80 ) || ( (thirdByte & 0xC0 ) != 0x80 ) ) - { - // TODO 4J Stu - UTFDataFormatException - return returnValue; - } + // No third byte + if (thirdByte == -1) { + // TODO 4J Stu - EOFException + return returnValue; + } + // Incorrect second or third byte pattern + else if (((secondByte & 0xC0) != 0x80) || + ((thirdByte & 0xC0) != 0x80)) { + // TODO 4J Stu - UTFDataFormatException + return returnValue; + } - returnValue = (((firstByte & 0x0F) << 12) | ((secondByte & 0x3F) << 6) | (thirdByte & 0x3F)); - } - return returnValue; + returnValue = (((firstByte & 0x0F) << 12) | ((secondByte & 0x3F) << 6) | + (thirdByte & 0x3F)); + } + return returnValue; } // 4J Added -PlayerUID DataInputStream::readPlayerUID() -{ - PlayerUID returnValue; +PlayerUID DataInputStream::readPlayerUID() { + PlayerUID returnValue; #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - for(int idPos=0;idPosskip(n); -} +// Skips n bytes of input from this input stream. Fewer bytes might be skipped +// if the end of the input stream is reached. The actual number k of bytes to be +// skipped is equal to the smaller of n and count-pos. The value k is added into +// pos and k is returned. Overrides: skip in class InputStream Parameters: n - +// the number of bytes to be skipped. Returns: the actual number of bytes +// skipped. +__int64 DataInputStream::skip(__int64 n) { return stream->skip(n); } -int DataInputStream::skipBytes(int n) -{ - return skip(n); -} +int DataInputStream::skipBytes(int n) { return skip(n); } diff --git a/Minecraft.World/IO/Streams/DataInputStream.h b/Minecraft.World/IO/Streams/DataInputStream.h index fd039177e..0fd772129 100644 --- a/Minecraft.World/IO/Streams/DataInputStream.h +++ b/Minecraft.World/IO/Streams/DataInputStream.h @@ -1,35 +1,35 @@ #pragma once -// 4J Stu - Represents Java standard library class (although we miss out an intermediate inheritance class that we don't care about) +// 4J Stu - Represents Java standard library class (although we miss out an +// intermediate inheritance class that we don't care about) #include "InputStream.h" #include "DataInput.h" -class DataInputStream : public InputStream, public DataInput -{ +class DataInputStream : public InputStream, public DataInput { private: - InputStream *stream; + InputStream* stream; public: - DataInputStream(InputStream *in); - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual bool readBoolean(); - virtual uint8_t readByte(); - virtual unsigned char readUnsignedByte(); - virtual wchar_t readChar(); - virtual bool readFully(byteArray b); - virtual bool readFully(charArray b); - virtual double readDouble(); - virtual float readFloat(); - virtual int readInt(); - virtual __int64 readLong(); - virtual short readShort(); - virtual std::wstring readUTF(); - void deleteChildStream(); - virtual int readUTFChar(); - virtual PlayerUID readPlayerUID(); // 4J Added - virtual __int64 skip(__int64 n); - virtual int skipBytes(int n); + DataInputStream(InputStream* in); + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual bool readBoolean(); + virtual uint8_t readByte(); + virtual unsigned char readUnsignedByte(); + virtual wchar_t readChar(); + virtual bool readFully(byteArray b); + virtual bool readFully(charArray b); + virtual double readDouble(); + virtual float readFloat(); + virtual int readInt(); + virtual __int64 readLong(); + virtual short readShort(); + virtual std::wstring readUTF(); + void deleteChildStream(); + virtual int readUTFChar(); + virtual PlayerUID readPlayerUID(); // 4J Added + virtual __int64 skip(__int64 n); + virtual int skipBytes(int n); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/DataOutput.h b/Minecraft.World/IO/Streams/DataOutput.h index 183aa62ad..ef69149fc 100644 --- a/Minecraft.World/IO/Streams/DataOutput.h +++ b/Minecraft.World/IO/Streams/DataOutput.h @@ -1,20 +1,20 @@ #pragma once -class DataOutput -{ +class DataOutput { public: - virtual void write(unsigned int b) = 0; - virtual void write(byteArray b) = 0; - virtual void write(byteArray b, unsigned int offset, unsigned int length) = 0; - virtual void writeByte(uint8_t a) = 0; - virtual void writeDouble(double a) = 0; - virtual void writeFloat(float a) = 0; - virtual void writeInt(int a) = 0; - virtual void writeLong(__int64 a) = 0; - virtual void writeShort(short a) = 0; - virtual void writeBoolean(bool v) = 0; - virtual void writeChar(wchar_t v) = 0; - virtual void writeChars(const std::wstring& s) = 0; - virtual void writeUTF(const std::wstring& a) = 0; - virtual void writePlayerUID(PlayerUID player) = 0; // 4J Added + virtual void write(unsigned int b) = 0; + virtual void write(byteArray b) = 0; + virtual void write(byteArray b, unsigned int offset, + unsigned int length) = 0; + virtual void writeByte(uint8_t a) = 0; + virtual void writeDouble(double a) = 0; + virtual void writeFloat(float a) = 0; + virtual void writeInt(int a) = 0; + virtual void writeLong(__int64 a) = 0; + virtual void writeShort(short a) = 0; + virtual void writeBoolean(bool v) = 0; + virtual void writeChar(wchar_t v) = 0; + virtual void writeChars(const std::wstring& s) = 0; + virtual void writeUTF(const std::wstring& a) = 0; + virtual void writePlayerUID(PlayerUID player) = 0; // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/DataOutputStream.cpp b/Minecraft.World/IO/Streams/DataOutputStream.cpp index a977af841..4d2286003 100644 --- a/Minecraft.World/IO/Streams/DataOutputStream.cpp +++ b/Minecraft.World/IO/Streams/DataOutputStream.cpp @@ -3,286 +3,251 @@ #include "DataOutputStream.h" -//Creates a new data output stream to write data to the specified underlying output stream. The counter written is set to zero. -//Parameters: -//out - the underlying output stream, to be saved for later use. -DataOutputStream::DataOutputStream( OutputStream *out ) : stream( out ), written( 0 ) -{ +// Creates a new data output stream to write data to the specified underlying +// output stream. The counter written is set to zero. Parameters: out - the +// underlying output stream, to be saved for later use. +DataOutputStream::DataOutputStream(OutputStream* out) + : stream(out), written(0) {} + +// 4J Stu - We cannot always delete the stream when we are destroyed, but we +// want to clear it up as there are occasions when we don't have a handle to the +// child stream elsewhere and want to delete it +void DataOutputStream::deleteChildStream() { delete stream; } + +// Writes the specified byte (the low eight bits of the argument b) to the +// underlying output stream. If no exception is thrown, the counter written is +// incremented by 1. Implements the write method of OutputStream. Parameters: b +// - the byte to be written. +void DataOutputStream::write(unsigned int b) { + if (stream == NULL) { + app.DebugPrintf( + "DataOutputStream::write(unsigned int) called but underlying " + "stream is NULL\n"); + return; + } + stream->write(b); + // TODO 4J Stu - Exception handling? + written++; } -// 4J Stu - We cannot always delete the stream when we are destroyed, but we want to clear it up as there -// are occasions when we don't have a handle to the child stream elsewhere and want to delete it -void DataOutputStream::deleteChildStream() -{ - delete stream; +void DataOutputStream::flush() { + if (stream == NULL) { + app.DebugPrintf( + "DataOutputStream::flush() called but underlying stream is NULL\n"); + return; + } + stream->flush(); } -//Writes the specified byte (the low eight bits of the argument b) to the underlying output stream. -//If no exception is thrown, the counter written is incremented by 1. -//Implements the write method of OutputStream. -//Parameters: -//b - the byte to be written. -void DataOutputStream::write(unsigned int b) -{ - if (stream == NULL) - { - app.DebugPrintf("DataOutputStream::write(unsigned int) called but underlying stream is NULL\n"); - return; - } - stream->write( b ); - // TODO 4J Stu - Exception handling? - written++; +// Writes b.length bytes from the specified byte array to this output stream. +// The general contract for write(b) is that it should have exactly the same +// effect as the call write(b, 0, b.length). Parameters: b - the data. +void DataOutputStream::write(byteArray b) { write(b, 0, b.length); } + +// Writes len bytes from the specified byte array starting at offset off to the +// underlying output stream. If no exception is thrown, the counter written is +// incremented by len. Parameters: b - the data. off - the start offset in the +// data. len - the number of bytes to write. +void DataOutputStream::write(byteArray b, unsigned int offset, + unsigned int length) { + if (stream == NULL) { + app.DebugPrintf( + "DataOutputStream::write(byteArray,...) called but underlying " + "stream is NULL\n"); + return; + } + stream->write(b, offset, length); + // TODO 4J Stu - Some form of error checking? + written += length; } -void DataOutputStream::flush() -{ - if (stream == NULL) - { - app.DebugPrintf("DataOutputStream::flush() called but underlying stream is NULL\n"); - return; - } - stream->flush(); +// Closes this output stream and releases any system resources associated with +// the stream. The close method of FilterOutputStream calls its flush method, +// and then calls the close method of its underlying output stream. +void DataOutputStream::close() { + if (stream == NULL) { + app.DebugPrintf( + "DataOutputStream::close() called but underlying stream is NULL\n"); + return; + } + stream->close(); } -//Writes b.length bytes from the specified byte array to this output stream. -//The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length). -//Parameters: -//b - the data. -void DataOutputStream::write(byteArray b) -{ - write(b, 0, b.length); +// Writes out a byte to the underlying output stream as a 1-byte value. If no +// exception is thrown, the counter written is incremented by 1. Parameters: v - +// a byte value to be written. +void DataOutputStream::writeByte(uint8_t a) { + stream->write(static_cast(a)); } -//Writes len bytes from the specified byte array starting at offset off to the underlying output stream. -//If no exception is thrown, the counter written is incremented by len. -//Parameters: -//b - the data. -//off - the start offset in the data. -//len - the number of bytes to write. -void DataOutputStream::write(byteArray b, unsigned int offset, unsigned int length) -{ - if (stream == NULL) - { - app.DebugPrintf("DataOutputStream::write(byteArray,...) called but underlying stream is NULL\n"); - return; - } - stream->write(b, offset, length); - // TODO 4J Stu - Some form of error checking? - written += length; +// Converts the double argument to a long using the doubleToLongBits method in +// class Double, and then writes that long value to the underlying output stream +// as an 8-byte quantity, high byte first. If no exception is thrown, the +// counter written is incremented by 8. Parameters: v - a double value to be +// written. +void DataOutputStream::writeDouble(double a) { + __int64 bits = Double::doubleToLongBits(a); + + writeLong(bits); + // TODO 4J Stu - Error handling? + written += 8; } -//Closes this output stream and releases any system resources associated with the stream. -//The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream. -void DataOutputStream::close() -{ - if (stream == NULL) - { - app.DebugPrintf("DataOutputStream::close() called but underlying stream is NULL\n"); - return; - } - stream->close(); +// Converts the float argument to an int using the floatToIntBits method in +// class Float, and then writes that int value to the underlying output stream +// as a 4-byte quantity, high byte first. If no exception is thrown, the counter +// written is incremented by 4. Parameters: v - a float value to be written. +void DataOutputStream::writeFloat(float a) { + int bits = Float::floatToIntBits(a); + + writeInt(bits); + // TODO 4J Stu - Error handling? + written += 4; } -//Writes out a byte to the underlying output stream as a 1-byte value. If no exception is thrown, the counter written is incremented by 1. -//Parameters: -//v - a byte value to be written. -void DataOutputStream::writeByte(uint8_t a) -{ - stream->write( static_cast(a) ); +// Writes an int to the underlying output stream as four bytes, high byte first. +// If no exception is thrown, the counter written is incremented by 4. +// Parameters: +// v - an int to be written. +void DataOutputStream::writeInt(int a) { + stream->write((a >> 24) & 0xff); + stream->write((a >> 16) & 0xff); + stream->write((a >> 8) & 0xff); + stream->write(a & 0xff); + // TODO 4J Stu - Error handling? + written += 4; } -//Converts the double argument to a long using the doubleToLongBits method in class Double, -//and then writes that long value to the underlying output stream as an 8-byte quantity, -//high byte first. If no exception is thrown, the counter written is incremented by 8. -//Parameters: -//v - a double value to be written. -void DataOutputStream::writeDouble(double a) -{ - __int64 bits = Double::doubleToLongBits( a ); - - writeLong( bits ); - // TODO 4J Stu - Error handling? - written += 8; +// Writes a long to the underlying output stream as eight bytes, high byte +// first. In no exception is thrown, the counter written is incremented by 8. +// Parameters: +// v - a long to be written. +void DataOutputStream::writeLong(__int64 a) { + stream->write((a >> 56) & 0xff); + stream->write((a >> 48) & 0xff); + stream->write((a >> 40) & 0xff); + stream->write((a >> 32) & 0xff); + stream->write((a >> 24) & 0xff); + stream->write((a >> 16) & 0xff); + stream->write((a >> 8) & 0xff); + stream->write(a & 0xff); + // TODO 4J Stu - Error handling? + written += 4; } -//Converts the float argument to an int using the floatToIntBits method in class Float, -//and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first. -//If no exception is thrown, the counter written is incremented by 4. -//Parameters: -//v - a float value to be written. -void DataOutputStream::writeFloat(float a) -{ - int bits = Float::floatToIntBits( a ); - - writeInt( bits ); - // TODO 4J Stu - Error handling? - written += 4; +// Writes a short to the underlying output stream as two bytes, high byte first. +// If no exception is thrown, the counter written is incremented by 2. +// Parameters: +// v - a short to be written. +void DataOutputStream::writeShort(short a) { + stream->write((a >> 8) & 0xff); + stream->write(a & 0xff); + // TODO 4J Stu - Error handling? + written += 2; } -//Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter written is incremented by 4. -//Parameters: -//v - an int to be written. -void DataOutputStream::writeInt(int a) -{ - stream->write( (a >> 24) & 0xff ); - stream->write( (a >> 16) & 0xff ); - stream->write( (a >> 8) & 0xff ); - stream->write( a & 0xff ); - // TODO 4J Stu - Error handling? - written += 4; +// Writes a char to the underlying output stream as a 2-byte value, high byte +// first. If no exception is thrown, the counter written is incremented by 2. +// Parameters: +// v - a char value to be written. +void DataOutputStream::writeChar(wchar_t v) { + stream->write((v >> 8) & 0xff); + stream->write(v & 0xff); + // TODO 4J Stu - Error handling? + written += 2; } -//Writes a long to the underlying output stream as eight bytes, high byte first. -//In no exception is thrown, the counter written is incremented by 8. -//Parameters: -//v - a long to be written. -void DataOutputStream::writeLong(__int64 a) -{ - stream->write( (a >> 56) & 0xff ); - stream->write( (a >> 48) & 0xff ); - stream->write( (a >> 40) & 0xff ); - stream->write( (a >> 32) & 0xff ); - stream->write( (a >> 24) & 0xff ); - stream->write( (a >> 16) & 0xff ); - stream->write( (a >> 8) & 0xff ); - stream->write( a & 0xff ); - // TODO 4J Stu - Error handling? - written += 4; +// Writes a string to the underlying output stream as a sequence of characters. +// Each character is written to the data output stream as if by the writeChar +// method. If no exception is thrown, the counter written is incremented by +// twice the length of s. Parameters: s - a String value to be written. +void DataOutputStream::writeChars(const std::wstring& str) { + for (unsigned int i = 0; i < str.length(); i++) { + writeChar(str.at(i)); + // TODO 4J Stu - Error handling? + } + // Incrementing handled by the writeChar function } -//Writes a short to the underlying output stream as two bytes, high byte first. -//If no exception is thrown, the counter written is incremented by 2. -//Parameters: -//v - a short to be written. -void DataOutputStream::writeShort(short a) -{ - stream->write( (a >> 8) & 0xff ); - stream->write( a & 0xff ); - // TODO 4J Stu - Error handling? - written += 2; +// Writes a boolean to the underlying output stream as a 1-byte value. +// The value true is written out as the value (uint8_t)1; the value false is +// written out as the value (uint8_t)0. If no exception is thrown, the counter +// written is incremented by 1. Parameters: v - a boolean value to be written. +void DataOutputStream::writeBoolean(bool b) { + stream->write(b ? 1 : 0); + // TODO 4J Stu - Error handling? + written += 1; } -//Writes a char to the underlying output stream as a 2-byte value, high byte first. -//If no exception is thrown, the counter written is incremented by 2. -//Parameters: -//v - a char value to be written. -void DataOutputStream::writeChar( wchar_t v ) -{ - stream->write( (v >> 8) & 0xff ); - stream->write( v & 0xff ); - // TODO 4J Stu - Error handling? - written += 2; -} +// Writes a string to the underlying output stream using modified UTF-8 encoding +// in a machine-independent manner. First, two bytes are written to the output +// stream as if by the writeShort method giving the number of bytes to follow. +// This value is the number of bytes actually written out, not the length of the +// string. Following the length, each character of the string is output, in +// sequence, using the modified UTF-8 encoding for the character. If no +// exception is thrown, the counter written is incremented by the total number +// of bytes written to the output stream. This will be at least two plus the +// length of str, and at most two plus thrice the length of str. Parameters: str +// - a string to be written. +void DataOutputStream::writeUTF(const std::wstring& str) { + int strlen = (int)str.length(); + int utflen = 0; + int c, count = 0; -//Writes a string to the underlying output stream as a sequence of characters. -//Each character is written to the data output stream as if by the writeChar method. -//If no exception is thrown, the counter written is incremented by twice the length of s. -//Parameters: -//s - a String value to be written. -void DataOutputStream::writeChars(const std::wstring& str) -{ - for( unsigned int i = 0; i < str.length(); i++) - { - writeChar( str.at( i ) ); - // TODO 4J Stu - Error handling? - } - // Incrementing handled by the writeChar function -} + /* use charAt instead of copying String to char array */ + for (int i = 0; i < strlen; i++) { + c = str.at(i); + if ((c >= 0x0001) && (c <= 0x007F)) { + utflen++; + } else if (c > 0x07FF) { + utflen += 3; + } else { + utflen += 2; + } + } -//Writes a boolean to the underlying output stream as a 1-byte value. -//The value true is written out as the value (uint8_t)1; the value false is written out as the value (uint8_t)0. -//If no exception is thrown, the counter written is incremented by 1. -//Parameters: -//v - a boolean value to be written. -void DataOutputStream::writeBoolean(bool b) -{ - stream->write( b ? 1 : 0 ); - // TODO 4J Stu - Error handling? - written += 1; -} + // if (utflen > 65535) + // throw new UTFDataFormatException( + // "encoded string too long: " + utflen + " bytes"); -//Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner. -//First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. -//This value is the number of bytes actually written out, not the length of the string. Following the length, -//each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. -//If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. -//This will be at least two plus the length of str, and at most two plus thrice the length of str. -//Parameters: -//str - a string to be written. -void DataOutputStream::writeUTF(const std::wstring& str) -{ - int strlen = (int)str.length(); - int utflen = 0; - int c, count = 0; + byteArray bytearr(utflen + 2); - /* use charAt instead of copying String to char array */ - for (int i = 0; i < strlen; i++) - { - c = str.at(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - utflen++; - } - else if (c > 0x07FF) - { - utflen += 3; - } - else - { - utflen += 2; - } - } + bytearr[count++] = (uint8_t)((utflen >> 8) & 0xFF); + bytearr[count++] = (uint8_t)((utflen >> 0) & 0xFF); - //if (utflen > 65535) - // throw new UTFDataFormatException( - // "encoded string too long: " + utflen + " bytes"); + int i = 0; + for (i = 0; i < strlen; i++) { + c = str.at(i); + if (!((c >= 0x0001) && (c <= 0x007F))) break; + bytearr[count++] = (uint8_t)c; + } - byteArray bytearr(utflen+2); + for (; i < strlen; i++) { + c = str.at(i); + if ((c >= 0x0001) && (c <= 0x007F)) { + bytearr[count++] = (uint8_t)c; - bytearr[count++] = (uint8_t) ((utflen >> 8) & 0xFF); - bytearr[count++] = (uint8_t) ((utflen >> 0) & 0xFF); - - int i=0; - for (i=0; i= 0x0001) && (c <= 0x007F))) break; - bytearr[count++] = (uint8_t) c; - } - - for (;i < strlen; i++) - { - c = str.at(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - bytearr[count++] = (uint8_t) c; - - } - else if (c > 0x07FF) - { - bytearr[count++] = (uint8_t) (0xE0 | ((c >> 12) & 0x0F)); - bytearr[count++] = (uint8_t) (0x80 | ((c >> 6) & 0x3F)); - bytearr[count++] = (uint8_t) (0x80 | ((c >> 0) & 0x3F)); - } - else - { - bytearr[count++] = (uint8_t) (0xC0 | ((c >> 6) & 0x1F)); - bytearr[count++] = (uint8_t) (0x80 | ((c >> 0) & 0x3F)); - } - } - write(bytearr, 0, utflen+2); - delete[] bytearr.data; + } else if (c > 0x07FF) { + bytearr[count++] = (uint8_t)(0xE0 | ((c >> 12) & 0x0F)); + bytearr[count++] = (uint8_t)(0x80 | ((c >> 6) & 0x3F)); + bytearr[count++] = (uint8_t)(0x80 | ((c >> 0) & 0x3F)); + } else { + bytearr[count++] = (uint8_t)(0xC0 | ((c >> 6) & 0x1F)); + bytearr[count++] = (uint8_t)(0x80 | ((c >> 0) & 0x3F)); + } + } + write(bytearr, 0, utflen + 2); + delete[] bytearr.data; } // 4J Added -void DataOutputStream::writePlayerUID(PlayerUID player) -{ -#if defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) - for(int idPos=0;idPoslength <= m_capacity ); +// src.get(a, 0, a.length) +// Returns: +// This buffer +void FloatBuffer::get(floatArray* dst) { + assert(dst->length <= m_capacity); - for (unsigned int i = 0; i < dst->length; i++) - dst->data[i] = buffer[i]; + for (unsigned int i = 0; i < dst->length; i++) dst->data[i] = buffer[i]; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/FloatBuffer.h b/Minecraft.World/IO/Streams/FloatBuffer.h index bb9870ae1..db890c8d4 100644 --- a/Minecraft.World/IO/Streams/FloatBuffer.h +++ b/Minecraft.World/IO/Streams/FloatBuffer.h @@ -1,18 +1,17 @@ #pragma once #include "Buffer.h" -class FloatBuffer : public Buffer -{ +class FloatBuffer : public Buffer { private: - float *buffer; + float* buffer; public: - FloatBuffer(unsigned int capacity); - FloatBuffer( unsigned int capacity, float *backingArray ); - virtual ~FloatBuffer(); + FloatBuffer(unsigned int capacity); + FloatBuffer(unsigned int capacity, float* backingArray); + virtual ~FloatBuffer(); - FloatBuffer *flip(); - FloatBuffer *put(float f); - void get(floatArray *dst); - float *_getDataPointer() {return buffer;} + FloatBuffer* flip(); + FloatBuffer* put(float f); + void get(floatArray* dst); + float* _getDataPointer() { return buffer; } }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/GZIPInputStream.h b/Minecraft.World/IO/Streams/GZIPInputStream.h index f852518b8..a69432416 100644 --- a/Minecraft.World/IO/Streams/GZIPInputStream.h +++ b/Minecraft.World/IO/Streams/GZIPInputStream.h @@ -1,17 +1,20 @@ #pragma once -// 4J Stu - We are not using GZIP compression, so this is just a pass through class +// 4J Stu - We are not using GZIP compression, so this is just a pass through +// class #include "InputStream.h" -class GZIPInputStream : public InputStream -{ +class GZIPInputStream : public InputStream { private: - InputStream *stream; + InputStream* stream; + public: - GZIPInputStream( InputStream *out ) : stream( out ) {}; - virtual int read() { return stream->read(); }; - virtual int read(byteArray b) { return stream->read( b ); }; - virtual int read(byteArray b, unsigned int offset, unsigned int length) { return stream->read(b, offset, length); }; - virtual void close() { return stream->close(); }; - virtual __int64 skip(__int64 n) { return 0; }; + GZIPInputStream(InputStream* out) : stream(out) {}; + virtual int read() { return stream->read(); }; + virtual int read(byteArray b) { return stream->read(b); }; + virtual int read(byteArray b, unsigned int offset, unsigned int length) { + return stream->read(b, offset, length); + }; + virtual void close() { return stream->close(); }; + virtual __int64 skip(__int64 n) { return 0; }; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/GZIPOutputStream.h b/Minecraft.World/IO/Streams/GZIPOutputStream.h index dcb99c4db..017d6a6ea 100644 --- a/Minecraft.World/IO/Streams/GZIPOutputStream.h +++ b/Minecraft.World/IO/Streams/GZIPOutputStream.h @@ -1,17 +1,20 @@ #pragma once -// 4J Stu - We are not using GZIP compression, so this is just a pass through class +// 4J Stu - We are not using GZIP compression, so this is just a pass through +// class #include "OutputStream.h" -class GZIPOutputStream : public OutputStream -{ +class GZIPOutputStream : public OutputStream { private: - OutputStream *stream; + OutputStream* stream; + public: - GZIPOutputStream( OutputStream *out ) : stream( out ) {}; - virtual void write(unsigned int b) { stream->write( b ); }; - virtual void write(byteArray b) { stream->write( b ); } ; - virtual void write(byteArray b, unsigned int offset, unsigned int length) { stream->write(b, offset, length); }; - virtual void close() { stream->close(); }; - virtual void flush() {} + GZIPOutputStream(OutputStream* out) : stream(out) {}; + virtual void write(unsigned int b) { stream->write(b); }; + virtual void write(byteArray b) { stream->write(b); }; + virtual void write(byteArray b, unsigned int offset, unsigned int length) { + stream->write(b, offset, length); + }; + virtual void close() { stream->close(); }; + virtual void flush() {} }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/InputStream.cpp b/Minecraft.World/IO/Streams/InputStream.cpp index 98220b0c3..5fd4f06d2 100644 --- a/Minecraft.World/IO/Streams/InputStream.cpp +++ b/Minecraft.World/IO/Streams/InputStream.cpp @@ -3,7 +3,6 @@ #include "InputOutputStream.h" #include "InputStream.h" -InputStream *InputStream::getResourceAsStream(const std::wstring &fileName) -{ - return new FileInputStream( File( fileName ) ); +InputStream* InputStream::getResourceAsStream(const std::wstring& fileName) { + return new FileInputStream(File(fileName)); } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/InputStream.h b/Minecraft.World/IO/Streams/InputStream.h index 642b2c174..e191686ca 100644 --- a/Minecraft.World/IO/Streams/InputStream.h +++ b/Minecraft.World/IO/Streams/InputStream.h @@ -2,16 +2,15 @@ // 4J Stu - Represents Java standard lib abstract -class InputStream -{ +class InputStream { public: - virtual ~InputStream() {} + virtual ~InputStream() {} - virtual int read() = 0; - virtual int read(byteArray b) = 0; - virtual int read(byteArray b, unsigned int offset, unsigned int length) = 0; - virtual void close() = 0; - virtual __int64 skip(__int64 n) = 0; + virtual int read() = 0; + virtual int read(byteArray b) = 0; + virtual int read(byteArray b, unsigned int offset, unsigned int length) = 0; + virtual void close() = 0; + virtual __int64 skip(__int64 n) = 0; - static InputStream *getResourceAsStream(const std::wstring &fileName); + static InputStream* getResourceAsStream(const std::wstring& fileName); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/InputStreamReader.cpp b/Minecraft.World/IO/Streams/InputStreamReader.cpp index 74ab4469b..44af81283 100644 --- a/Minecraft.World/IO/Streams/InputStreamReader.cpp +++ b/Minecraft.World/IO/Streams/InputStreamReader.cpp @@ -4,49 +4,44 @@ #include "DataInputStream.h" #include "InputStreamReader.h" -//Creates an InputStreamReader that uses the default charset. -//Parameters: -//in - An InputStream -InputStreamReader::InputStreamReader(InputStream *in) : stream( new DataInputStream( in ) ) -{ -} +// Creates an InputStreamReader that uses the default charset. +// Parameters: +// in - An InputStream +InputStreamReader::InputStreamReader(InputStream* in) + : stream(new DataInputStream(in)) {} -//Closes the stream and releases any system resources associated with it. -//Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. -//Closing a previously closed stream has no effect. -void InputStreamReader::close() -{ - stream->close(); -} +// Closes the stream and releases any system resources associated with it. +// Once the stream has been closed, further read(), ready(), mark(), reset(), or +// skip() invocations will throw an IOException. Closing a previously closed +// stream has no effect. +void InputStreamReader::close() { stream->close(); } -//Reads a single character. -//Returns: -//The character read, or -1 if the end of the stream has been reached -int InputStreamReader::read() -{ - return stream->readUTFChar(); -} +// Reads a single character. +// Returns: +// The character read, or -1 if the end of the stream has been reached +int InputStreamReader::read() { return stream->readUTFChar(); } -//Reads characters into a portion of an array. -//Parameters: -//cbuf - Destination buffer -//offset - Offset at which to start storing characters -//length - Maximum number of characters to read -//Returns: -//The number of characters read, or -1 if the end of the stream has been reached -int InputStreamReader::read(wchar_t cbuf[], unsigned int offset, unsigned int length) -{ - unsigned int charsRead = 0; - for( unsigned int i = offset; i < offset + length; i++ ) - { - wchar_t value = (wchar_t)stream->readUTFChar(); - if( value != -1 ) - { - cbuf[i] = value; - charsRead++; - } - // TODO 4J Stu - The read might throw an exception? In which case we should return -1 - else break; - } - return charsRead; +// Reads characters into a portion of an array. +// Parameters: +// cbuf - Destination buffer +// offset - Offset at which to start storing characters +// length - Maximum number of characters to read +// Returns: +// The number of characters read, or -1 if the end of the stream has been +// reached +int InputStreamReader::read(wchar_t cbuf[], unsigned int offset, + unsigned int length) { + unsigned int charsRead = 0; + for (unsigned int i = offset; i < offset + length; i++) { + wchar_t value = (wchar_t)stream->readUTFChar(); + if (value != -1) { + cbuf[i] = value; + charsRead++; + } + // TODO 4J Stu - The read might throw an exception? In which case we + // should return -1 + else + break; + } + return charsRead; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/InputStreamReader.h b/Minecraft.World/IO/Streams/InputStreamReader.h index d26efb0f6..26fb7783c 100644 --- a/Minecraft.World/IO/Streams/InputStreamReader.h +++ b/Minecraft.World/IO/Streams/InputStreamReader.h @@ -4,15 +4,14 @@ class InputStream; -class InputStreamReader : public Reader -{ +class InputStreamReader : public Reader { private: - DataInputStream *stream; + DataInputStream* stream; public: - InputStreamReader(InputStream *in); + InputStreamReader(InputStream* in); - virtual void close(); - virtual int read(); - virtual int read(wchar_t cbuf[], unsigned int offset, unsigned int length); + virtual void close(); + virtual int read(); + virtual int read(wchar_t cbuf[], unsigned int offset, unsigned int length); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/IntBuffer.cpp b/Minecraft.World/IO/Streams/IntBuffer.cpp index 4c8eafc33..857866d10 100644 --- a/Minecraft.World/IO/Streams/IntBuffer.cpp +++ b/Minecraft.World/IO/Streams/IntBuffer.cpp @@ -2,112 +2,108 @@ #include "IntBuffer.h" -//Allocates a new int buffer. -//The new buffer's position will be zero, its limit will be its capacity, and its mark will be undefined. -//It will have a backing array, and its array offset will be zero. +// Allocates a new int buffer. +// The new buffer's position will be zero, its limit will be its capacity, and +// its mark will be undefined. It will have a backing array, and its array +// offset will be zero. // -//Parameters: -//capacity - The new buffer's capacity, in ints -IntBuffer::IntBuffer(unsigned int capacity) : Buffer( capacity ) -{ - buffer = new int[capacity]; - memset( buffer,0,sizeof(int)*capacity); +// Parameters: +// capacity - The new buffer's capacity, in ints +IntBuffer::IntBuffer(unsigned int capacity) : Buffer(capacity) { + buffer = new int[capacity]; + memset(buffer, 0, sizeof(int) * capacity); } -IntBuffer::IntBuffer( unsigned int capacity, int *backingArray ) : Buffer( capacity ) -{ - hasBackingArray = true; - buffer = backingArray; +IntBuffer::IntBuffer(unsigned int capacity, int* backingArray) + : Buffer(capacity) { + hasBackingArray = true; + buffer = backingArray; } -IntBuffer::~IntBuffer() -{ - if( !hasBackingArray ) - delete[] buffer; +IntBuffer::~IntBuffer() { + if (!hasBackingArray) delete[] buffer; } -int *IntBuffer::getBuffer() -{ - return buffer; -} +int* IntBuffer::getBuffer() { return buffer; } -//Flips this buffer. The limit is set to the current position and then the position is set to zero. -//If the mark is defined then it is discarded. +// Flips this buffer. The limit is set to the current position and then the +// position is set to zero. If the mark is defined then it is discarded. // -//Returns: -//This buffer -IntBuffer *IntBuffer::flip() -{ - m_limit = m_position; - m_position = 0; - return this; +// Returns: +// This buffer +IntBuffer* IntBuffer::flip() { + m_limit = m_position; + m_position = 0; + return this; } -//Absolute get method. Reads the int at the given index. -//Parameters: -//index - The index from which the int will be read -//Returns: -//The int at the given index -int IntBuffer::get(unsigned int index) -{ - assert( index < m_limit ); +// Absolute get method. Reads the int at the given index. +// Parameters: +// index - The index from which the int will be read +// Returns: +// The int at the given index +int IntBuffer::get(unsigned int index) { + assert(index < m_limit); - return buffer[index]; + return buffer[index]; } -//Relative bulk put method (optional operation). -//This method transfers ints into this buffer from the given source array. -//If there are more ints to be copied from the array than remain in this buffer, that is, if length > remaining(), -//then no ints are transferred and a BufferOverflowException is thrown. +// Relative bulk put method (optional operation). +// This method transfers ints into this buffer from the given source array. +// If there are more ints to be copied from the array than remain in this +// buffer, that is, if length > remaining(), then no ints are transferred and a +// BufferOverflowException is thrown. // -//Otherwise, this method copies length ints from the given array into this buffer, starting at the given offset in the array -//and at the current position of this buffer. The position of this buffer is then incremented by length. +// Otherwise, this method copies length ints from the given array into this +// buffer, starting at the given offset in the array and at the current position +// of this buffer. The position of this buffer is then incremented by length. // -//In other words, an invocation of this method of the form dst.put(src, off, len) has exactly the same effect as the loop +// In other words, an invocation of this method of the form dst.put(src, off, +// len) has exactly the same effect as the loop // -// for (int i = off; i < off + len; i++) -// dst.put(a[i]); -//except that it first checks that there is sufficient space in this buffer and it is potentially much more efficient. -//Parameters: -//src - The array from which ints are to be read -//offset - The offset within the array of the first int to be read; must be non-negative and no larger than array.length -//length - The number of ints to be read from the given array; must be non-negative and no larger than array.length - offset -//Returns: -//This buffer -IntBuffer *IntBuffer::put(intArray *inputArray, unsigned int offset, unsigned int length) -{ - assert( offset + length < inputArray->length ); +// for (int i = off; i < off + len; i++) +// dst.put(a[i]); +// except that it first checks that there is sufficient space in this buffer and +// it is potentially much more efficient. Parameters: src - The array from which +// ints are to be read offset - The offset within the array of the first int to +// be read; must be non-negative and no larger than array.length length - The +// number of ints to be read from the given array; must be non-negative and no +// larger than array.length - offset Returns: This buffer +IntBuffer* IntBuffer::put(intArray* inputArray, unsigned int offset, + unsigned int length) { + assert(offset + length < inputArray->length); - std::copy( inputArray->data +offset, inputArray->data +offset+length, buffer+m_position ); + std::copy(inputArray->data + offset, inputArray->data + offset + length, + buffer + m_position); - m_position += length; + m_position += length; - return this; + return this; } -IntBuffer *IntBuffer::put(intArray inputArray) -{ - if( inputArray.length > remaining() ) - assert( false ); //TODO 4J Stu - Some kind of exception? +IntBuffer* IntBuffer::put(intArray inputArray) { + if (inputArray.length > remaining()) + assert(false); // TODO 4J Stu - Some kind of exception? - std::copy( inputArray.data, inputArray.data + inputArray.length, buffer+m_position ); + std::copy(inputArray.data, inputArray.data + inputArray.length, + buffer + m_position); - m_position += inputArray.length; + m_position += inputArray.length; - return this; + return this; } -//Writes the given int into this buffer at the current position, and then increments the position. +// Writes the given int into this buffer at the current position, and then +// increments the position. // -//Parameters: -//i - The int to be written -//Returns: -//This buffer -IntBuffer *IntBuffer::put(int i) -{ - assert( m_position < m_limit ); +// Parameters: +// i - The int to be written +// Returns: +// This buffer +IntBuffer* IntBuffer::put(int i) { + assert(m_position < m_limit); - buffer[m_position++] = i; + buffer[m_position++] = i; - return this; + return this; } \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/IntBuffer.h b/Minecraft.World/IO/Streams/IntBuffer.h index 0d5d304c9..18dc5ae33 100644 --- a/Minecraft.World/IO/Streams/IntBuffer.h +++ b/Minecraft.World/IO/Streams/IntBuffer.h @@ -2,20 +2,20 @@ #include "Buffer.h" -class IntBuffer : public Buffer -{ +class IntBuffer : public Buffer { private: - int *buffer; + int* buffer; public: - IntBuffer(unsigned int capacity); - IntBuffer( unsigned int capacity, int *backingArray ); - virtual ~IntBuffer(); + IntBuffer(unsigned int capacity); + IntBuffer(unsigned int capacity, int* backingArray); + virtual ~IntBuffer(); - virtual IntBuffer *flip(); - int get(unsigned int index); - int *getBuffer(); - IntBuffer *put(intArray *inputArray, unsigned int offset, unsigned int length); - IntBuffer *put(intArray inputArray); - IntBuffer *put(int i); + virtual IntBuffer* flip(); + int get(unsigned int index); + int* getBuffer(); + IntBuffer* put(intArray* inputArray, unsigned int offset, + unsigned int length); + IntBuffer* put(intArray inputArray); + IntBuffer* put(int i); }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/OutputStream.h b/Minecraft.World/IO/Streams/OutputStream.h index f6d9bcf77..6abb3e4cf 100644 --- a/Minecraft.World/IO/Streams/OutputStream.h +++ b/Minecraft.World/IO/Streams/OutputStream.h @@ -1,14 +1,14 @@ #pragma once // 4J Stu - Represents Java standard lib abstract -class OutputStream -{ +class OutputStream { public: - virtual ~OutputStream() {} + virtual ~OutputStream() {} - virtual void write(unsigned int b) = 0; - virtual void write(byteArray b) = 0; - virtual void write(byteArray b, unsigned int offset, unsigned int length) = 0; - virtual void close() = 0; - virtual void flush() = 0; + virtual void write(unsigned int b) = 0; + virtual void write(byteArray b) = 0; + virtual void write(byteArray b, unsigned int offset, + unsigned int length) = 0; + virtual void close() = 0; + virtual void flush() = 0; }; \ No newline at end of file diff --git a/Minecraft.World/IO/Streams/Reader.h b/Minecraft.World/IO/Streams/Reader.h index 864eba2bc..48f881aba 100644 --- a/Minecraft.World/IO/Streams/Reader.h +++ b/Minecraft.World/IO/Streams/Reader.h @@ -1,11 +1,13 @@ #pragma once -class Reader -{ +class Reader { public: - virtual ~Reader() {} + virtual ~Reader() {} - virtual void close() = 0; //Closes the stream and releases any system resources associated with it. - virtual int read() = 0; //Reads a single character. - virtual int read(wchar_t cbuf[], unsigned int off, unsigned int len) = 0; //Reads characters into a portion of an array. + virtual void close() = 0; // Closes the stream and releases any system + // resources associated with it. + virtual int read() = 0; // Reads a single character. + virtual int read( + wchar_t cbuf[], unsigned int off, + unsigned int len) = 0; // Reads characters into a portion of an array. }; \ No newline at end of file diff --git a/Minecraft.World/Items/ArmorItem.cpp b/Minecraft.World/Items/ArmorItem.cpp index a753a8773..5713d16fd 100644 --- a/Minecraft.World/Items/ArmorItem.cpp +++ b/Minecraft.World/Items/ArmorItem.cpp @@ -5,225 +5,198 @@ #include "../Headers/com.mojang.nbt.h" #include "ArmorItem.h" -const int ArmorItem::healthPerSlot[] = { - 11, 16, 15, 13 -}; +const int ArmorItem::healthPerSlot[] = {11, 16, 15, 13}; const std::wstring ArmorItem::LEATHER_OVERLAYS[] = { - L"helmetCloth_overlay", L"chestplateCloth_overlay", L"leggingsCloth_overlay", L"bootsCloth_overlay" - }; + L"helmetCloth_overlay", L"chestplateCloth_overlay", + L"leggingsCloth_overlay", L"bootsCloth_overlay"}; const std::wstring ArmorItem::TEXTURE_EMPTY_SLOTS[] = { - L"slot_empty_helmet", L"slot_empty_chestplate", L"slot_empty_leggings", L"slot_empty_boots" - }; + L"slot_empty_helmet", L"slot_empty_chestplate", L"slot_empty_leggings", + L"slot_empty_boots"}; typedef ArmorItem::ArmorMaterial _ArmorMaterial; -const int _ArmorMaterial::clothArray[] = {1,3,2,1}; +const int _ArmorMaterial::clothArray[] = {1, 3, 2, 1}; const int _ArmorMaterial::chainArray[] = {2, 5, 4, 1}; const int _ArmorMaterial::ironArray[] = {2, 6, 5, 2}; const int _ArmorMaterial::goldArray[] = {2, 5, 3, 1}; const int _ArmorMaterial::diamondArray[] = {3, 8, 6, 3}; -const _ArmorMaterial *_ArmorMaterial::CLOTH = new _ArmorMaterial(5, _ArmorMaterial::clothArray, 15); -const _ArmorMaterial *_ArmorMaterial::CHAIN = new _ArmorMaterial(15, _ArmorMaterial::chainArray, 12); -const _ArmorMaterial *_ArmorMaterial::IRON = new _ArmorMaterial(15, _ArmorMaterial::ironArray, 9); -const _ArmorMaterial *_ArmorMaterial::GOLD = new _ArmorMaterial(7, _ArmorMaterial::goldArray, 25); -const _ArmorMaterial *_ArmorMaterial::DIAMOND = new _ArmorMaterial(33, _ArmorMaterial::diamondArray, 10); +const _ArmorMaterial* _ArmorMaterial::CLOTH = + new _ArmorMaterial(5, _ArmorMaterial::clothArray, 15); +const _ArmorMaterial* _ArmorMaterial::CHAIN = + new _ArmorMaterial(15, _ArmorMaterial::chainArray, 12); +const _ArmorMaterial* _ArmorMaterial::IRON = + new _ArmorMaterial(15, _ArmorMaterial::ironArray, 9); +const _ArmorMaterial* _ArmorMaterial::GOLD = + new _ArmorMaterial(7, _ArmorMaterial::goldArray, 25); +const _ArmorMaterial* _ArmorMaterial::DIAMOND = + new _ArmorMaterial(33, _ArmorMaterial::diamondArray, 10); -_ArmorMaterial::ArmorMaterial(int durabilityMultiplier, const int slotProtections[], int enchantmentValue) -{ - this->durabilityMultiplier = durabilityMultiplier; - this->slotProtections = (int *)slotProtections; - this->enchantmentValue = enchantmentValue; +_ArmorMaterial::ArmorMaterial(int durabilityMultiplier, + const int slotProtections[], + int enchantmentValue) { + this->durabilityMultiplier = durabilityMultiplier; + this->slotProtections = (int*)slotProtections; + this->enchantmentValue = enchantmentValue; } -_ArmorMaterial::~ArmorMaterial() -{ - delete [] slotProtections; +_ArmorMaterial::~ArmorMaterial() { delete[] slotProtections; } + +int _ArmorMaterial::getHealthForSlot(int slot) const { + return healthPerSlot[slot] * durabilityMultiplier; } -int _ArmorMaterial::getHealthForSlot(int slot) const -{ - return healthPerSlot[slot] * durabilityMultiplier; +int _ArmorMaterial::getDefenseForSlot(int slot) const { + return slotProtections[slot]; } -int _ArmorMaterial::getDefenseForSlot(int slot) const -{ - return slotProtections[slot]; +int _ArmorMaterial::getEnchantmentValue() const { return enchantmentValue; } + +int _ArmorMaterial::getTierItemId() const { + if (this == CLOTH) { + return Item::leather_Id; + } else if (this == CHAIN) { + return Item::ironIngot_Id; + } else if (this == GOLD) { + return Item::goldIngot_Id; + } else if (this == IRON) { + return Item::ironIngot_Id; + } else if (this == DIAMOND) { + return Item::diamond_Id; + } + return 0; } -int _ArmorMaterial::getEnchantmentValue() const -{ - return enchantmentValue; +ArmorItem::ArmorItem(int id, const ArmorMaterial* armorType, int icon, int slot) + : Item(id), + armorType(armorType), + slot(slot), + modelIndex(icon), + defense(armorType->getDefenseForSlot(slot)) { + setMaxDamage(armorType->getHealthForSlot(slot)); + maxStackSize = 1; } -int _ArmorMaterial::getTierItemId() const -{ - if (this == CLOTH) - { - return Item::leather_Id; - } - else if (this == CHAIN) - { - return Item::ironIngot_Id; - } - else if (this == GOLD) - { - return Item::goldIngot_Id; - } - else if (this == IRON) - { - return Item::ironIngot_Id; - } - else if (this == DIAMOND) - { - return Item::diamond_Id; - } - return 0; -} +int ArmorItem::getColor(std::shared_ptr item, int spriteLayer) { + if (spriteLayer > 0) { + return 0xFFFFFF; + } -ArmorItem::ArmorItem(int id, const ArmorMaterial *armorType, int icon, int slot) : Item( id ), armorType( armorType ), slot( slot ), modelIndex( icon ), defense( armorType->getDefenseForSlot(slot) ) -{ - setMaxDamage(armorType->getHealthForSlot(slot)); - maxStackSize = 1; -} - -int ArmorItem::getColor(std::shared_ptr item, int spriteLayer) -{ - if (spriteLayer > 0) - { - return 0xFFFFFF; - } - - int color = getColor(item); - if (color < 0) color = 0xFFFFFF; - return color; + int color = getColor(item); + if (color < 0) color = 0xFFFFFF; + return color; } //@Override -bool ArmorItem::hasMultipleSpriteLayers() -{ - return armorType == ArmorMaterial::CLOTH; +bool ArmorItem::hasMultipleSpriteLayers() { + return armorType == ArmorMaterial::CLOTH; } -int ArmorItem::getEnchantmentValue() -{ - return armorType->getEnchantmentValue(); +int ArmorItem::getEnchantmentValue() { + return armorType->getEnchantmentValue(); } -const _ArmorMaterial *ArmorItem::getMaterial() -{ - return armorType; +const _ArmorMaterial* ArmorItem::getMaterial() { return armorType; } + +bool ArmorItem::hasCustomColor(std::shared_ptr item) { + if (armorType != ArmorMaterial::CLOTH) return false; + if (!item->hasTag()) return false; + if (!item->getTag()->contains(L"display")) return false; + if (!item->getTag()->getCompound(L"display")->contains(L"color")) + return false; + + return true; } -bool ArmorItem::hasCustomColor(std::shared_ptr item) -{ - if (armorType != ArmorMaterial::CLOTH) return false; - if (!item->hasTag()) return false; - if (!item->getTag()->contains(L"display")) return false; - if (!item->getTag()->getCompound(L"display")->contains(L"color")) return false; +int ArmorItem::getColor(std::shared_ptr item) { + if (armorType != ArmorMaterial::CLOTH) return -1; - return true; -} + CompoundTag* tag = item->getTag(); + if (tag == NULL) + return Minecraft::GetInstance()->getColourTable()->getColor( + DEFAULT_LEATHER_COLOR); + CompoundTag* display = tag->getCompound(L"display"); + if (display == NULL) + return Minecraft::GetInstance()->getColourTable()->getColor( + DEFAULT_LEATHER_COLOR); -int ArmorItem::getColor(std::shared_ptr item) -{ - if (armorType != ArmorMaterial::CLOTH) return -1; - - CompoundTag *tag = item->getTag(); - if (tag == NULL) return Minecraft::GetInstance()->getColourTable()->getColor( DEFAULT_LEATHER_COLOR ); - CompoundTag *display = tag->getCompound(L"display"); - if (display == NULL) return Minecraft::GetInstance()->getColourTable()->getColor( DEFAULT_LEATHER_COLOR ); - - if (display->contains(L"color")) - { - return display->getInt(L"color"); - } - else - { - return Minecraft::GetInstance()->getColourTable()->getColor( DEFAULT_LEATHER_COLOR ); - } + if (display->contains(L"color")) { + return display->getInt(L"color"); + } else { + return Minecraft::GetInstance()->getColourTable()->getColor( + DEFAULT_LEATHER_COLOR); + } } //@Override -Icon *ArmorItem::getLayerIcon(int auxValue, int spriteLayer) -{ - if (spriteLayer == 1) - { - return overlayIcon; - } - return Item::getLayerIcon(auxValue, spriteLayer); +Icon* ArmorItem::getLayerIcon(int auxValue, int spriteLayer) { + if (spriteLayer == 1) { + return overlayIcon; + } + return Item::getLayerIcon(auxValue, spriteLayer); } -void ArmorItem::clearColor(std::shared_ptr item) -{ - if (armorType != ArmorMaterial::CLOTH) return; - CompoundTag *tag = item->getTag(); - if (tag == NULL) return; - CompoundTag *display = tag->getCompound(L"display"); - if (display->contains(L"color")) display->remove(L"color"); +void ArmorItem::clearColor(std::shared_ptr item) { + if (armorType != ArmorMaterial::CLOTH) return; + CompoundTag* tag = item->getTag(); + if (tag == NULL) return; + CompoundTag* display = tag->getCompound(L"display"); + if (display->contains(L"color")) display->remove(L"color"); } -void ArmorItem::setColor(std::shared_ptr item, int color) -{ - if (armorType != ArmorMaterial::CLOTH) - { +void ArmorItem::setColor(std::shared_ptr item, int color) { + if (armorType != ArmorMaterial::CLOTH) { #ifndef _CONTENT_PACKAGE - printf("Can't dye non-leather!"); - __debugbreak(); + printf("Can't dye non-leather!"); + __debugbreak(); #endif - //throw new UnsupportedOperationException("Can't dye non-leather!"); - } + // throw new UnsupportedOperationException("Can't dye non-leather!"); + } - CompoundTag *tag = item->getTag(); + CompoundTag* tag = item->getTag(); - if (tag == NULL) - { - tag = new CompoundTag(); - item->setTag(tag); - } + if (tag == NULL) { + tag = new CompoundTag(); + item->setTag(tag); + } - CompoundTag *display = tag->getCompound(L"display"); - if (!tag->contains(L"display")) tag->putCompound(L"display", display); + CompoundTag* display = tag->getCompound(L"display"); + if (!tag->contains(L"display")) tag->putCompound(L"display", display); - display->putInt(L"color", color); + display->putInt(L"color", color); } -bool ArmorItem::isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem) -{ - if (armorType->getTierItemId() == repairItem->id) - { - return true; - } - return Item::isValidRepairItem(source, repairItem); +bool ArmorItem::isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem) { + if (armorType->getTierItemId() == repairItem->id) { + return true; + } + return Item::isValidRepairItem(source, repairItem); } //@Override -void ArmorItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); +void ArmorItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); - if (armorType == ArmorMaterial::CLOTH) - { - overlayIcon = iconRegister->registerIcon(LEATHER_OVERLAYS[slot]); - } + if (armorType == ArmorMaterial::CLOTH) { + overlayIcon = iconRegister->registerIcon(LEATHER_OVERLAYS[slot]); + } - iconEmpty = iconRegister->registerIcon(TEXTURE_EMPTY_SLOTS[slot]); + iconEmpty = iconRegister->registerIcon(TEXTURE_EMPTY_SLOTS[slot]); } -Icon *ArmorItem::getEmptyIcon(int slot) -{ - switch (slot) - { - case 0: - return Item::helmet_diamond->iconEmpty; - case 1: - return Item::chestplate_diamond->iconEmpty; - case 2: - return Item::leggings_diamond->iconEmpty; - case 3: - return Item::boots_diamond->iconEmpty; - } +Icon* ArmorItem::getEmptyIcon(int slot) { + switch (slot) { + case 0: + return Item::helmet_diamond->iconEmpty; + case 1: + return Item::chestplate_diamond->iconEmpty; + case 2: + return Item::leggings_diamond->iconEmpty; + case 3: + return Item::boots_diamond->iconEmpty; + } - return NULL; + return NULL; } \ No newline at end of file diff --git a/Minecraft.World/Items/ArmorItem.h b/Minecraft.World/Items/ArmorItem.h index ed5746c7c..3bbbb453e 100644 --- a/Minecraft.World/Items/ArmorItem.h +++ b/Minecraft.World/Items/ArmorItem.h @@ -2,89 +2,91 @@ #include "Item.h" -class ArmorItem : public Item -{ +class ArmorItem : public Item { public: - static const int SLOT_HEAD = 0; - static const int SLOT_TORSO = 1; - static const int SLOT_LEGS = 2; - static const int SLOT_FEET = 3; - static const eMinecraftColour DEFAULT_LEATHER_COLOR = eMinecraftColour_Armour_Default_Leather_Colour; + static const int SLOT_HEAD = 0; + static const int SLOT_TORSO = 1; + static const int SLOT_LEGS = 2; + static const int SLOT_FEET = 3; + static const eMinecraftColour DEFAULT_LEATHER_COLOR = + eMinecraftColour_Armour_Default_Leather_Colour; private: - static const int healthPerSlot[]; - static const std::wstring LEATHER_OVERLAYS[] ; + static const int healthPerSlot[]; + static const std::wstring LEATHER_OVERLAYS[]; public: - static const std::wstring TEXTURE_EMPTY_SLOTS[]; + static const std::wstring TEXTURE_EMPTY_SLOTS[]; public: - class ArmorMaterial - { - public: - static const int clothArray[]; - static const int chainArray[]; - static const int ironArray[]; - static const int goldArray[]; - static const int diamondArray[]; - public: - static const ArmorMaterial *CLOTH; - static const ArmorMaterial *CHAIN; - static const ArmorMaterial *IRON; - static const ArmorMaterial *GOLD; - static const ArmorMaterial *DIAMOND; + class ArmorMaterial { + public: + static const int clothArray[]; + static const int chainArray[]; + static const int ironArray[]; + static const int goldArray[]; + static const int diamondArray[]; - private: - int durabilityMultiplier; - int *slotProtections; - int enchantmentValue; + public: + static const ArmorMaterial* CLOTH; + static const ArmorMaterial* CHAIN; + static const ArmorMaterial* IRON; + static const ArmorMaterial* GOLD; + static const ArmorMaterial* DIAMOND; - // 4J Stu - Had to make this public but was private - // We shouldn't be creating these except the static initialisation - public: - ArmorMaterial(int durabilityMultiplier, const int slotProtections[], int enchantmentValue); - ~ArmorMaterial(); + private: + int durabilityMultiplier; + int* slotProtections; + int enchantmentValue; - public: - int getHealthForSlot(int slot) const; - int getDefenseForSlot(int slot) const; - int getEnchantmentValue() const; - int getTierItemId() const; - }; + // 4J Stu - Had to make this public but was private + // We shouldn't be creating these except the static initialisation + public: + ArmorMaterial(int durabilityMultiplier, const int slotProtections[], + int enchantmentValue); + ~ArmorMaterial(); - const int slot; - const int defense; - const int modelIndex; + public: + int getHealthForSlot(int slot) const; + int getDefenseForSlot(int slot) const; + int getEnchantmentValue() const; + int getTierItemId() const; + }; + + const int slot; + const int defense; + const int modelIndex; private: - const ArmorMaterial *armorType; - Icon *overlayIcon; - Icon *iconEmpty; + const ArmorMaterial* armorType; + Icon* overlayIcon; + Icon* iconEmpty; public: - ArmorItem(int id, const ArmorMaterial *armorType, int icon, int slot); + ArmorItem(int id, const ArmorMaterial* armorType, int icon, int slot); - //@Override - int getColor(std::shared_ptr item, int spriteLayer); + //@Override + int getColor(std::shared_ptr item, int spriteLayer); - //@Override - bool hasMultipleSpriteLayers(); + //@Override + bool hasMultipleSpriteLayers(); - virtual int getEnchantmentValue(); + virtual int getEnchantmentValue(); - const ArmorMaterial *getMaterial(); - bool hasCustomColor(std::shared_ptr item); - int getColor(std::shared_ptr item); + const ArmorMaterial* getMaterial(); + bool hasCustomColor(std::shared_ptr item); + int getColor(std::shared_ptr item); - //@Override - Icon *getLayerIcon(int auxValue, int spriteLayer); - void clearColor(std::shared_ptr item); - void setColor(std::shared_ptr item, int color); + //@Override + Icon* getLayerIcon(int auxValue, int spriteLayer); + void clearColor(std::shared_ptr item); + void setColor(std::shared_ptr item, int color); - bool isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem); + bool isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); - static Icon *getEmptyIcon(int slot); + static Icon* getEmptyIcon(int slot); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BedItem.cpp b/Minecraft.World/Items/BedItem.cpp index a7f5874e4..bf587e2b9 100644 --- a/Minecraft.World/Items/BedItem.cpp +++ b/Minecraft.World/Items/BedItem.cpp @@ -8,52 +8,56 @@ #include "../Stats/GenericStats.h" #include "BedItem.h" -BedItem::BedItem(int id) : Item( id ) -{ -} - -bool BedItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (face != Facing::UP) - { - return false; - } - - // place on top of tile - y = y + 1; - - BedTile *tile = (BedTile *) Tile::bed; - - int dir = ( Mth::floor(player->yRot * 4 / (360) + 0.5f) ) & 3; - int xra = 0; - int zra = 0; - - if (dir == Direction::SOUTH) zra = 1; - if (dir == Direction::WEST) xra = -1; - if (dir == Direction::NORTH) zra = -1; - if (dir == Direction::EAST) xra = 1; - - if (!player->mayBuild(x, y, z) || !player->mayBuild(x + xra, y, z + zra)) return false; - - if (level->isEmptyTile(x, y, z) && level->isEmptyTile(x + xra, y, z + zra) && level->isTopSolidBlocking(x, y - 1, z) && level->isTopSolidBlocking(x + xra, y - 1, z + zra)) - { - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(!bTestUseOnOnly) - { - level->setTileAndData(x, y, z, tile->id, dir); - // double-check that the bed was successfully placed - if (level->getTile(x, y, z) == tile->id) - { - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat(GenericStats::blocksPlaced(tile->id), GenericStats::param_blocksPlaced(tile->id,itemInstance->getAuxValue(),1)); - - level->setTileAndData(x + xra, y, z + zra, tile->id, dir + BedTile::HEAD_PIECE_DATA); - } - - itemInstance->count--; - } - return true; - } - - return false; +BedItem::BedItem(int id) : Item(id) {} + +bool BedItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + if (face != Facing::UP) { + return false; + } + + // place on top of tile + y = y + 1; + + BedTile* tile = (BedTile*)Tile::bed; + + int dir = (Mth::floor(player->yRot * 4 / (360) + 0.5f)) & 3; + int xra = 0; + int zra = 0; + + if (dir == Direction::SOUTH) zra = 1; + if (dir == Direction::WEST) xra = -1; + if (dir == Direction::NORTH) zra = -1; + if (dir == Direction::EAST) xra = 1; + + if (!player->mayBuild(x, y, z) || !player->mayBuild(x + xra, y, z + zra)) + return false; + + if (level->isEmptyTile(x, y, z) && + level->isEmptyTile(x + xra, y, z + zra) && + level->isTopSolidBlocking(x, y - 1, z) && + level->isTopSolidBlocking(x + xra, y - 1, z + zra)) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (!bTestUseOnOnly) { + level->setTileAndData(x, y, z, tile->id, dir); + // double-check that the bed was successfully placed + if (level->getTile(x, y, z) == tile->id) { + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat( + GenericStats::blocksPlaced(tile->id), + GenericStats::param_blocksPlaced( + tile->id, itemInstance->getAuxValue(), 1)); + + level->setTileAndData(x + xra, y, z + zra, tile->id, + dir + BedTile::HEAD_PIECE_DATA); + } + + itemInstance->count--; + } + return true; + } + + return false; } diff --git a/Minecraft.World/Items/BedItem.h b/Minecraft.World/Items/BedItem.h index 261423b3a..36652cf04 100644 --- a/Minecraft.World/Items/BedItem.h +++ b/Minecraft.World/Items/BedItem.h @@ -5,11 +5,12 @@ class Player; class Level; -class BedItem : public Item -{ - +class BedItem : public Item { public: - BedItem(int id); + BedItem(int id); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BoatItem.cpp b/Minecraft.World/Items/BoatItem.cpp index 861703cd4..d9974e8b0 100644 --- a/Minecraft.World/Items/BoatItem.cpp +++ b/Minecraft.World/Items/BoatItem.cpp @@ -7,123 +7,119 @@ #include "ItemInstance.h" #include "BoatItem.h" -BoatItem::BoatItem(int id) : Item( id ) -{ - this->maxStackSize = 1; +BoatItem::BoatItem(int id) : Item(id) { this->maxStackSize = 1; } + +bool BoatItem::TestUse(Level* level, std::shared_ptr player) { + // 4J-PB - added for tooltips to test use + // 4J TODO really we should have the crosshair hitresult telling us if it + // hit water, and at what distance, so we don't need to do this again if the + // player happens to have a boat in their hand + + float xRot = player->xRotO + (player->xRot - player->xRotO); + float yRot = player->yRotO + (player->yRot - player->yRotO); + + double x = player->xo + (player->x - player->xo); + double y = + player->yo + (player->y - player->yo) + 1.62 - player->heightOffset; + double z = player->zo + (player->z - player->zo); + + Vec3* from = Vec3::newTemp(x, y, z); + + float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); + float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); + float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); + float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); + + float xa = ySin * xCos; + float ya = xSin; + float za = yCos * xCos; + + double range = 5; + Vec3* to = from->add(xa * range, ya * range, za * range); + HitResult* hr = level->clip(from, to, true); + if (hr == NULL) return false; + + if (hr->type == HitResult::TILE) { + delete hr; + return true; + } + delete hr; + return false; } +std::shared_ptr BoatItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + float a = 1; -bool BoatItem::TestUse(Level *level, std::shared_ptr player) -{ - // 4J-PB - added for tooltips to test use - // 4J TODO really we should have the crosshair hitresult telling us if it hit water, and at what distance, so we don't need to do this again - // if the player happens to have a boat in their hand + float xRot = player->xRotO + (player->xRot - player->xRotO) * a; + float yRot = player->yRotO + (player->yRot - player->yRotO) * a; - float xRot = player->xRotO + (player->xRot - player->xRotO); - float yRot = player->yRotO + (player->yRot - player->yRotO); + double x = player->xo + (player->x - player->xo) * a; + double y = + player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; + double z = player->zo + (player->z - player->zo) * a; - double x = player->xo + (player->x - player->xo); - double y = player->yo + (player->y - player->yo) + 1.62 - player->heightOffset; - double z = player->zo + (player->z - player->zo); + Vec3* from = Vec3::newTemp(x, y, z); - Vec3 *from = Vec3::newTemp(x, y, z); + float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); + float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); + float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); + float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); - float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); - float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); - float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); - float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); + float xa = ySin * xCos; + float ya = xSin; + float za = yCos * xCos; - float xa = ySin * xCos; - float ya = xSin; - float za = yCos * xCos; + double range = 5; + Vec3* to = from->add(xa * range, ya * range, za * range); + HitResult* hr = level->clip(from, to, true); + if (hr == NULL) return itemInstance; - double range = 5; - Vec3 *to = from->add(xa * range, ya * range, za * range); - HitResult *hr = level->clip(from, to, true); - if (hr == NULL) return false; + // check entity collision + Vec3* b = player->getViewVector(a); + bool hitEntity = false; + float overlap = 1; + std::vector >* objects = level->getEntities( + player, + player->bb->expand(b->x * (range), b->y * (range), b->z * (range)) + ->grow(overlap, overlap, overlap)); + // for (int i = 0; i < objects.size(); i++) { + for (AUTO_VAR(it, objects->begin()); it != objects->end(); ++it) { + std::shared_ptr e = *it; // objects.get(i); + if (!e->isPickable()) continue; - if (hr->type == HitResult::TILE) - { - delete hr; - return true; - } - delete hr; - return false; -} -std::shared_ptr BoatItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - float a = 1; + float rr = e->getPickRadius(); + AABB* bb = e->bb->grow(rr, rr, rr); + if (bb->contains(from)) { + hitEntity = true; + } + } + if (hitEntity) { + return itemInstance; + } - float xRot = player->xRotO + (player->xRot - player->xRotO) * a; - float yRot = player->yRotO + (player->yRot - player->yRotO) * a; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; - double x = player->xo + (player->x - player->xo) * a; - double y = player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; - double z = player->zo + (player->z - player->zo) * a; + if (!level->isClientSide) { + if (level->getTile(xt, yt, zt) == Tile::topSnow_Id) yt--; + if (level->countInstanceOf(eTYPE_BOAT, true) < + Level::MAX_XBOX_BOATS) // 4J - added limit + { + level->addEntity(std::shared_ptr( + new Boat(level, xt + 0.5f, yt + 1.0f, zt + 0.5f))); + if (!player->abilities.instabuild) { + itemInstance->count--; + } + } else { + // display a message to say max boats has been hit + player->displayClientMessage(IDS_MAX_BOATS); + } + } + } + delete hr; - Vec3 *from = Vec3::newTemp(x, y, z); - - float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); - float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); - float xCos = -Mth::cos(-xRot * Mth::RAD_TO_GRAD); - float xSin = Mth::sin(-xRot * Mth::RAD_TO_GRAD); - - float xa = ySin * xCos; - float ya = xSin; - float za = yCos * xCos; - - double range = 5; - Vec3 *to = from->add(xa * range, ya * range, za * range); - HitResult *hr = level->clip(from, to, true); - if (hr == NULL) return itemInstance; - - // check entity collision - Vec3 *b = player->getViewVector(a); - bool hitEntity = false; - float overlap = 1; - std::vector > *objects = level->getEntities(player, player->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); - //for (int i = 0; i < objects.size(); i++) { - for(AUTO_VAR(it, objects->begin()); it != objects->end(); ++it) - { - std::shared_ptr e = *it; //objects.get(i); - if (!e->isPickable()) continue; - - float rr = e->getPickRadius(); - AABB *bb = e->bb->grow(rr, rr, rr); - if (bb->contains(from)) - { - hitEntity = true; - } - } - if (hitEntity) - { - return itemInstance; - } - - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; - - if (!level->isClientSide) - { - if (level->getTile(xt, yt, zt) == Tile::topSnow_Id) yt--; - if( level->countInstanceOf(eTYPE_BOAT, true) < Level::MAX_XBOX_BOATS ) // 4J - added limit - { - level->addEntity( std::shared_ptr( new Boat(level, xt + 0.5f, yt + 1.0f, zt + 0.5f) ) ); - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - } - else - { - // display a message to say max boats has been hit - player->displayClientMessage(IDS_MAX_BOATS ); - } - } - } - delete hr; - - return itemInstance; + return itemInstance; } \ No newline at end of file diff --git a/Minecraft.World/Items/BoatItem.h b/Minecraft.World/Items/BoatItem.h index 08a2ccf71..060051b86 100644 --- a/Minecraft.World/Items/BoatItem.h +++ b/Minecraft.World/Items/BoatItem.h @@ -5,20 +5,20 @@ class Player; class Level; -class BoatItem : public Item -{ +class BoatItem : public Item { public: + BoatItem(int id); - BoatItem(int id); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - - /* - * public boolean useOn(ItemInstance instance, Player player, Level level, - * int x, int y, int z, int face) { // if (face != 1) return false; int - * targetType = level.getTile(x, y, z); if (targetType == Tile.rail.id) { - * level.addEntity(new Minecart(level, x + 0.5f, y + 0.5f, z + 0.5f)); - * instance.count--; return true; } return false; } - */ + /* + * public boolean useOn(ItemInstance instance, Player player, Level level, + * int x, int y, int z, int face) { // if (face != 1) return false; int + * targetType = level.getTile(x, y, z); if (targetType == Tile.rail.id) { + * level.addEntity(new Minecart(level, x + 0.5f, y + 0.5f, z + 0.5f)); + * instance.count--; return true; } return false; } + */ }; \ No newline at end of file diff --git a/Minecraft.World/Items/BookItem.cpp b/Minecraft.World/Items/BookItem.cpp index ba5245483..6ea875f3c 100644 --- a/Minecraft.World/Items/BookItem.cpp +++ b/Minecraft.World/Items/BookItem.cpp @@ -2,16 +2,10 @@ #include "BookItem.h" -BookItem::BookItem(int id) : Item(id) -{ +BookItem::BookItem(int id) : Item(id) {} + +bool BookItem::isEnchantable(std::shared_ptr itemInstance) { + return itemInstance->count == 1; } -bool BookItem::isEnchantable(std::shared_ptr itemInstance) -{ - return itemInstance->count == 1; -} - -int BookItem::getEnchantmentValue() -{ - return 1; -} \ No newline at end of file +int BookItem::getEnchantmentValue() { return 1; } \ No newline at end of file diff --git a/Minecraft.World/Items/BookItem.h b/Minecraft.World/Items/BookItem.h index 8bb5d1188..f488b5a62 100644 --- a/Minecraft.World/Items/BookItem.h +++ b/Minecraft.World/Items/BookItem.h @@ -2,11 +2,10 @@ #include "Item.h" -class BookItem : public Item -{ +class BookItem : public Item { public: - BookItem(int id); + BookItem(int id); - bool isEnchantable(std::shared_ptr itemInstance); - int getEnchantmentValue(); + bool isEnchantable(std::shared_ptr itemInstance); + int getEnchantmentValue(); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BottleItem.cpp b/Minecraft.World/Items/BottleItem.cpp index c125a4826..429933b50 100644 --- a/Minecraft.World/Items/BottleItem.cpp +++ b/Minecraft.World/Items/BottleItem.cpp @@ -6,94 +6,75 @@ #include "../Headers/net.minecraft.world.item.h" #include "BottleItem.h" -BottleItem::BottleItem(int id) : Item(id) -{ -} +BottleItem::BottleItem(int id) : Item(id) {} -Icon *BottleItem::getIcon(int auxValue) -{ - return Item::potion->getIcon(0); -} +Icon* BottleItem::getIcon(int auxValue) { return Item::potion->getIcon(0); } -std::shared_ptr BottleItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, true); - if (hr == NULL) return itemInstance; +std::shared_ptr BottleItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, true); + if (hr == NULL) return itemInstance; - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; - delete hr; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; + delete hr; - if (!level->mayInteract(player, xt, yt, zt, 0)) - { - return itemInstance; - } - if (!player->mayBuild(xt, yt, zt)) - { - return itemInstance; - } - if (level->getMaterial(xt, yt, zt) == Material::water) - { - itemInstance->count--; - if (itemInstance->count <= 0) - { - return std::shared_ptr( new ItemInstance( (Item *)Item::potion) ); - } - else - { - if (!player->inventory->add(std::shared_ptr( new ItemInstance( (Item *)Item::potion) ))) - { - player->drop( std::shared_ptr( new ItemInstance(Item::potion_Id, 1, 0) )); - } - } - } - } - else - { - delete hr; - } + if (!level->mayInteract(player, xt, yt, zt, 0)) { + return itemInstance; + } + if (!player->mayBuild(xt, yt, zt)) { + return itemInstance; + } + if (level->getMaterial(xt, yt, zt) == Material::water) { + itemInstance->count--; + if (itemInstance->count <= 0) { + return std::shared_ptr( + new ItemInstance((Item*)Item::potion)); + } else { + if (!player->inventory->add(std::shared_ptr( + new ItemInstance((Item*)Item::potion)))) { + player->drop(std::shared_ptr( + new ItemInstance(Item::potion_Id, 1, 0))); + } + } + } + } else { + delete hr; + } - return itemInstance; + return itemInstance; } // 4J-PB - added to allow tooltips -bool BottleItem::TestUse(Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, true); - if (hr == NULL) return false; +bool BottleItem::TestUse(Level* level, std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, true); + if (hr == NULL) return false; - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; - delete hr; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; + delete hr; - if (!level->mayInteract(player, xt, yt, zt, 0)) - { - return false; - } - if (!player->mayBuild(xt, yt, zt)) - { - return false; - } - if (level->getMaterial(xt, yt, zt) == Material::water) - { - return true; - } - } - else - { - delete hr; - } + if (!level->mayInteract(player, xt, yt, zt, 0)) { + return false; + } + if (!player->mayBuild(xt, yt, zt)) { + return false; + } + if (level->getMaterial(xt, yt, zt) == Material::water) { + return true; + } + } else { + delete hr; + } - return false; + return false; } -void BottleItem::registerIcons(IconRegister *iconRegister) -{ - // We reuse another texture. +void BottleItem::registerIcons(IconRegister* iconRegister) { + // We reuse another texture. } \ No newline at end of file diff --git a/Minecraft.World/Items/BottleItem.h b/Minecraft.World/Items/BottleItem.h index 400902e76..edaefb797 100644 --- a/Minecraft.World/Items/BottleItem.h +++ b/Minecraft.World/Items/BottleItem.h @@ -4,17 +4,18 @@ class Icon; -class BottleItem : public Item -{ +class BottleItem : public Item { public: - BottleItem(int id); + BottleItem(int id); - //@Override - Icon *getIcon(int auxValue); + //@Override + Icon* getIcon(int auxValue); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual bool TestUse(Level *level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); + virtual bool TestUse(Level* level, std::shared_ptr player); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BowItem.cpp b/Minecraft.World/Items/BowItem.cpp index a60034f7b..b126c3f3a 100644 --- a/Minecraft.World/Items/BowItem.cpp +++ b/Minecraft.World/Items/BowItem.cpp @@ -8,102 +8,96 @@ #include "BowItem.h" #include "../Util/SoundTypes.h" -const std::wstring BowItem::TEXTURE_PULL[] = {L"bow_pull_0", L"bow_pull_1", L"bow_pull_2"}; +const std::wstring BowItem::TEXTURE_PULL[] = {L"bow_pull_0", L"bow_pull_1", + L"bow_pull_2"}; -BowItem::BowItem(int id) : Item( id ) -{ - maxStackSize = 1; - setMaxDamage(384); +BowItem::BowItem(int id) : Item(id) { + maxStackSize = 1; + setMaxDamage(384); - icons = NULL; + icons = NULL; } -void BowItem::releaseUsing(std::shared_ptr itemInstance, Level *level, std::shared_ptr player, int durationLeft) -{ - bool infiniteArrows = player->abilities.instabuild || EnchantmentHelper::getEnchantmentLevel(Enchantment::arrowInfinite->id, itemInstance) > 0; +void BowItem::releaseUsing(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player, + int durationLeft) { + bool infiniteArrows = player->abilities.instabuild || + EnchantmentHelper::getEnchantmentLevel( + Enchantment::arrowInfinite->id, itemInstance) > 0; - if (infiniteArrows || player->inventory->hasResource(Item::arrow_Id)) - { - int timeHeld = getUseDuration(itemInstance) - durationLeft; - float pow = timeHeld / (float) MAX_DRAW_DURATION; - pow = ((pow * pow) + pow * 2) / 3; - if (pow < 0.1) return; - if (pow > 1) pow = 1; + if (infiniteArrows || player->inventory->hasResource(Item::arrow_Id)) { + int timeHeld = getUseDuration(itemInstance) - durationLeft; + float pow = timeHeld / (float)MAX_DRAW_DURATION; + pow = ((pow * pow) + pow * 2) / 3; + if (pow < 0.1) return; + if (pow > 1) pow = 1; - std::shared_ptr arrow = std::shared_ptr( new Arrow(level, player, pow * 2.0f) ); - if (pow == 1) arrow->setCritArrow(true); - int damageBonus = EnchantmentHelper::getEnchantmentLevel(Enchantment::arrowBonus->id, itemInstance); - if (damageBonus > 0) - { - arrow->setBaseDamage(arrow->getBaseDamage() + (double) damageBonus * .5 + .5); - } - int knockbackBonus = EnchantmentHelper::getEnchantmentLevel(Enchantment::arrowKnockback->id, itemInstance); - if (knockbackBonus > 0) - { - arrow->setKnockback(knockbackBonus); - } - if (EnchantmentHelper::getEnchantmentLevel(Enchantment::arrowFire->id, itemInstance) > 0) - { - arrow->setOnFire(100); - } - itemInstance->hurt(1, player); + std::shared_ptr arrow = + std::shared_ptr(new Arrow(level, player, pow * 2.0f)); + if (pow == 1) arrow->setCritArrow(true); + int damageBonus = EnchantmentHelper::getEnchantmentLevel( + Enchantment::arrowBonus->id, itemInstance); + if (damageBonus > 0) { + arrow->setBaseDamage(arrow->getBaseDamage() + + (double)damageBonus * .5 + .5); + } + int knockbackBonus = EnchantmentHelper::getEnchantmentLevel( + Enchantment::arrowKnockback->id, itemInstance); + if (knockbackBonus > 0) { + arrow->setKnockback(knockbackBonus); + } + if (EnchantmentHelper::getEnchantmentLevel(Enchantment::arrowFire->id, + itemInstance) > 0) { + arrow->setOnFire(100); + } + itemInstance->hurt(1, player); - level->playSound(player, eSoundType_RANDOM_BOW, 1.0f, 1 / (random->nextFloat() * 0.4f + 1.2f) + pow * 0.5f); + level->playSound(player, eSoundType_RANDOM_BOW, 1.0f, + 1 / (random->nextFloat() * 0.4f + 1.2f) + pow * 0.5f); - if (infiniteArrows) - { - arrow->pickup = Arrow::PICKUP_CREATIVE_ONLY; - } - else - { - player->inventory->removeResource(Item::arrow_Id); - } - if (!level->isClientSide) level->addEntity(arrow); - } + if (infiniteArrows) { + arrow->pickup = Arrow::PICKUP_CREATIVE_ONLY; + } else { + player->inventory->removeResource(Item::arrow_Id); + } + if (!level->isClientSide) level->addEntity(arrow); + } } -std::shared_ptr BowItem::useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - return instance; +std::shared_ptr BowItem::useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + return instance; } -int BowItem::getUseDuration(std::shared_ptr itemInstance) -{ - return 20 * 60 * 60; +int BowItem::getUseDuration(std::shared_ptr itemInstance) { + return 20 * 60 * 60; } -UseAnim BowItem::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_bow; +UseAnim BowItem::getUseAnimation(std::shared_ptr itemInstance) { + return UseAnim_bow; } -std::shared_ptr BowItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (player->abilities.instabuild || player->inventory->hasResource(Item::arrow_Id)) - { - player->startUsingItem(instance, getUseDuration(instance)); - } - return instance; +std::shared_ptr BowItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (player->abilities.instabuild || + player->inventory->hasResource(Item::arrow_Id)) { + player->startUsingItem(instance, getUseDuration(instance)); + } + return instance; } -int BowItem::getEnchantmentValue() -{ - return 1; +int BowItem::getEnchantmentValue() { return 1; } + +void BowItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); + + icons = new Icon*[BOW_ICONS_COUNT]; + + for (int i = 0; i < BOW_ICONS_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_PULL[i]); + } } -void BowItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - - icons = new Icon *[BOW_ICONS_COUNT]; - - for (int i = 0; i < BOW_ICONS_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_PULL[i]); - } -} - -Icon *BowItem::getDrawnIcon(int amount) -{ - return icons[amount]; -} \ No newline at end of file +Icon* BowItem::getDrawnIcon(int amount) { return icons[amount]; } \ No newline at end of file diff --git a/Minecraft.World/Items/BowItem.h b/Minecraft.World/Items/BowItem.h index 1c28494ca..809283ddd 100644 --- a/Minecraft.World/Items/BowItem.h +++ b/Minecraft.World/Items/BowItem.h @@ -5,27 +5,32 @@ class Player; class Level; -class BowItem : public Item -{ +class BowItem : public Item { public: - static const std::wstring TEXTURE_PULL[]; - static const int MAX_DRAW_DURATION = 20 * 1; + static const std::wstring TEXTURE_PULL[]; + static const int MAX_DRAW_DURATION = 20 * 1; private: - static const int BOW_ICONS_COUNT = 3; - Icon **icons; + static const int BOW_ICONS_COUNT = 3; + Icon** icons; public: - BowItem(int id); + BowItem(int id); - virtual void releaseUsing(std::shared_ptr itemInstance, Level *level, std::shared_ptr player, int durationLeft); - virtual std::shared_ptr useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual int getEnchantmentValue(); + virtual void releaseUsing(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player, + int durationLeft); + virtual std::shared_ptr useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual int getEnchantmentValue(); - //@Override - void registerIcons(IconRegister *iconRegister); - Icon *getDrawnIcon(int amount); + //@Override + void registerIcons(IconRegister* iconRegister); + Icon* getDrawnIcon(int amount); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BowlFoodItem.cpp b/Minecraft.World/Items/BowlFoodItem.cpp index b55887a70..f0e70e584 100644 --- a/Minecraft.World/Items/BowlFoodItem.cpp +++ b/Minecraft.World/Items/BowlFoodItem.cpp @@ -3,14 +3,15 @@ #include "ItemInstance.h" #include "BowlFoodItem.h" -BowlFoodItem::BowlFoodItem(int id, int nutrition) : FoodItem( id, nutrition, false ) -{ - setMaxStackSize(1); +BowlFoodItem::BowlFoodItem(int id, int nutrition) + : FoodItem(id, nutrition, false) { + setMaxStackSize(1); } -std::shared_ptr BowlFoodItem::useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - FoodItem::useTimeDepleted(instance, level, player); +std::shared_ptr BowlFoodItem::useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + FoodItem::useTimeDepleted(instance, level, player); - return std::shared_ptr(new ItemInstance(Item::bowl)); + return std::shared_ptr(new ItemInstance(Item::bowl)); } \ No newline at end of file diff --git a/Minecraft.World/Items/BowlFoodItem.h b/Minecraft.World/Items/BowlFoodItem.h index 1c488c7e3..c5232b7da 100644 --- a/Minecraft.World/Items/BowlFoodItem.h +++ b/Minecraft.World/Items/BowlFoodItem.h @@ -5,10 +5,11 @@ class Player; class Level; -class BowlFoodItem : public FoodItem -{ +class BowlFoodItem : public FoodItem { public: - BowlFoodItem(int id, int nutrition); + BowlFoodItem(int id, int nutrition); - std::shared_ptr useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player); + std::shared_ptr useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/BucketItem.cpp b/Minecraft.World/Items/BucketItem.cpp index 17929346a..4cd80d2db 100644 --- a/Minecraft.World/Items/BucketItem.cpp +++ b/Minecraft.World/Items/BucketItem.cpp @@ -18,239 +18,214 @@ #include "../Network/Packets/ChatPacket.h" #include "../Util/SoundTypes.h" -BucketItem::BucketItem(int id, int content) : Item( id ) -{ - maxStackSize = 1; - this->content = content; +BucketItem::BucketItem(int id, int content) : Item(id) { + maxStackSize = 1; + this->content = content; } -bool BucketItem::TestUse(Level *level, std::shared_ptr player) -{ -// double x = player->xo + (player->x - player->xo); -// double y = player->yo + (player->y - player->yo) + 1.62 - player->heightOffset; -// double z = player->zo + (player->z - player->zo); +bool BucketItem::TestUse(Level* level, std::shared_ptr player) { + // double x = player->xo + (player->x - player->xo); + // double y = player->yo + (player->y - player->yo) + 1.62 - + // player->heightOffset; double z = player->zo + (player->z - player->zo); - bool pickLiquid = content == 0; - HitResult *hr = getPlayerPOVHitResult(level, player, pickLiquid); - if (hr == NULL) return false; + bool pickLiquid = content == 0; + HitResult* hr = getPlayerPOVHitResult(level, player, pickLiquid); + if (hr == NULL) return false; - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; - if (!level->mayInteract(player, xt, yt, zt, content)) - { - delete hr; - return false; - } + if (!level->mayInteract(player, xt, yt, zt, content)) { + delete hr; + return false; + } - if (content == 0) - { - if (!player->mayBuild(xt, yt, zt)) return false; - if (level->getMaterial(xt, yt, zt) == Material::water && level->getData(xt, yt, zt) == 0) - { - delete hr; - return true; - } - if (level->getMaterial(xt, yt, zt) == Material::lava && level->getData(xt, yt, zt) == 0) - { - delete hr; - return true; - } - } - else if (content < 0) - { - delete hr; - return true; - } - else - { - if (hr->f == 0) yt--; - if (hr->f == 1) yt++; - if (hr->f == 2) zt--; - if (hr->f == 3) zt++; - if (hr->f == 4) xt--; - if (hr->f == 5) xt++; - - if (!player->mayBuild(xt, yt, zt)) return false; + if (content == 0) { + if (!player->mayBuild(xt, yt, zt)) return false; + if (level->getMaterial(xt, yt, zt) == Material::water && + level->getData(xt, yt, zt) == 0) { + delete hr; + return true; + } + if (level->getMaterial(xt, yt, zt) == Material::lava && + level->getData(xt, yt, zt) == 0) { + delete hr; + return true; + } + } else if (content < 0) { + delete hr; + return true; + } else { + if (hr->f == 0) yt--; + if (hr->f == 1) yt++; + if (hr->f == 2) zt--; + if (hr->f == 3) zt++; + if (hr->f == 4) xt--; + if (hr->f == 5) xt++; - if (level->isEmptyTile(xt, yt, zt) || !level->getMaterial(xt, yt, zt)->isSolid()) - { - delete hr; - return true; - } - } - } - else - { - if (content == 0) - { - if (hr->entity->GetType() == eTYPE_COW) - { - delete hr; - return true; - } - } - } - delete hr; + if (!player->mayBuild(xt, yt, zt)) return false; - return false; + if (level->isEmptyTile(xt, yt, zt) || + !level->getMaterial(xt, yt, zt)->isSolid()) { + delete hr; + return true; + } + } + } else { + if (content == 0) { + if (hr->entity->GetType() == eTYPE_COW) { + delete hr; + return true; + } + } + } + delete hr; + + return false; } -std::shared_ptr BucketItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - float a = 1; +std::shared_ptr BucketItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + float a = 1; - double x = player->xo + (player->x - player->xo) * a; - double y = player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; - double z = player->zo + (player->z - player->zo) * a; + double x = player->xo + (player->x - player->xo) * a; + double y = + player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; + double z = player->zo + (player->z - player->zo) * a; - bool pickLiquid = content == 0; - HitResult *hr = getPlayerPOVHitResult(level, player, pickLiquid); - if (hr == NULL) return itemInstance; + bool pickLiquid = content == 0; + HitResult* hr = getPlayerPOVHitResult(level, player, pickLiquid); + if (hr == NULL) return itemInstance; - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; - if (!level->mayInteract(player, xt, yt, zt,content)) - { - app.DebugPrintf("!!!!!!!!!!! Can't place that here\n"); - std::shared_ptr servPlayer = std::dynamic_pointer_cast(player); - if( servPlayer != NULL ) - { - app.DebugPrintf("Sending ChatPacket::e_ChatCannotPlaceLava to player\n"); - servPlayer->connection->send( std::shared_ptr( new ChatPacket(L"", ChatPacket::e_ChatCannotPlaceLava ) ) ); - } - - delete hr; - return itemInstance; - } + if (!level->mayInteract(player, xt, yt, zt, content)) { + app.DebugPrintf("!!!!!!!!!!! Can't place that here\n"); + std::shared_ptr servPlayer = + std::dynamic_pointer_cast(player); + if (servPlayer != NULL) { + app.DebugPrintf( + "Sending ChatPacket::e_ChatCannotPlaceLava to player\n"); + servPlayer->connection->send(std::shared_ptr( + new ChatPacket(L"", ChatPacket::e_ChatCannotPlaceLava))); + } - if (content == 0) - { - if (!player->mayBuild(xt, yt, zt)) return itemInstance; - if (level->getMaterial(xt, yt, zt) == Material::water && level->getData(xt, yt, zt) == 0) - { - level->setTile(xt, yt, zt, 0); - delete hr; - if (player->abilities.instabuild) - { - return itemInstance; - } + delete hr; + return itemInstance; + } - if (--itemInstance->count <= 0) - { - return std::shared_ptr( new ItemInstance(Item::bucket_water) ); - } - else - { - if (!player->inventory->add(std::shared_ptr( new ItemInstance(Item::bucket_water)))) - { - player->drop(std::shared_ptr(new ItemInstance(Item::bucket_water_Id, 1, 0))); - } - return itemInstance; - } - } - if (level->getMaterial(xt, yt, zt) == Material::lava && level->getData(xt, yt, zt) == 0) - { - if( level->dimension->id == -1 ) - player->awardStat( - GenericStats::netherLavaCollected(), - GenericStats::param_noArgs() - ); + if (content == 0) { + if (!player->mayBuild(xt, yt, zt)) return itemInstance; + if (level->getMaterial(xt, yt, zt) == Material::water && + level->getData(xt, yt, zt) == 0) { + level->setTile(xt, yt, zt, 0); + delete hr; + if (player->abilities.instabuild) { + return itemInstance; + } - level->setTile(xt, yt, zt, 0); - delete hr; - if (player->abilities.instabuild) - { - return itemInstance; - } - if (--itemInstance->count <= 0) - { - return std::shared_ptr( new ItemInstance(Item::bucket_lava) ); - } - else - { - if (!player->inventory->add(std::shared_ptr( new ItemInstance(Item::bucket_lava)))) - { - player->drop(std::shared_ptr(new ItemInstance(Item::bucket_lava_Id, 1, 0))); - } - return itemInstance; - } - } - } - else if (content < 0) - { - delete hr; - return std::shared_ptr( new ItemInstance(Item::bucket_empty) ); - } - else - { - if (hr->f == 0) yt--; - if (hr->f == 1) yt++; - if (hr->f == 2) zt--; - if (hr->f == 3) zt++; - if (hr->f == 4) xt--; - if (hr->f == 5) xt++; - - if (!player->mayBuild(xt, yt, zt)) return itemInstance; + if (--itemInstance->count <= 0) { + return std::shared_ptr( + new ItemInstance(Item::bucket_water)); + } else { + if (!player->inventory->add(std::shared_ptr( + new ItemInstance(Item::bucket_water)))) { + player->drop(std::shared_ptr( + new ItemInstance(Item::bucket_water_Id, 1, 0))); + } + return itemInstance; + } + } + if (level->getMaterial(xt, yt, zt) == Material::lava && + level->getData(xt, yt, zt) == 0) { + if (level->dimension->id == -1) + player->awardStat(GenericStats::netherLavaCollected(), + GenericStats::param_noArgs()); + level->setTile(xt, yt, zt, 0); + delete hr; + if (player->abilities.instabuild) { + return itemInstance; + } + if (--itemInstance->count <= 0) { + return std::shared_ptr( + new ItemInstance(Item::bucket_lava)); + } else { + if (!player->inventory->add(std::shared_ptr( + new ItemInstance(Item::bucket_lava)))) { + player->drop(std::shared_ptr( + new ItemInstance(Item::bucket_lava_Id, 1, 0))); + } + return itemInstance; + } + } + } else if (content < 0) { + delete hr; + return std::shared_ptr( + new ItemInstance(Item::bucket_empty)); + } else { + if (hr->f == 0) yt--; + if (hr->f == 1) yt++; + if (hr->f == 2) zt--; + if (hr->f == 3) zt++; + if (hr->f == 4) xt--; + if (hr->f == 5) xt++; - if (emptyBucket(level, x, y, z, xt, yt, zt) && !player->abilities.instabuild) - { - return std::shared_ptr( new ItemInstance(Item::bucket_empty) ); - } + if (!player->mayBuild(xt, yt, zt)) return itemInstance; - } - } - else - { - if (content == 0) - { - if (hr->entity->GetType() == eTYPE_COW) - { - delete hr; - if (--itemInstance->count <= 0) - { - return std::shared_ptr( new ItemInstance(Item::milk) ); - } - else - { - if (!player->inventory->add(std::shared_ptr( new ItemInstance(Item::milk)))) - { - player->drop(std::shared_ptr(new ItemInstance(Item::milk_Id, 1, 0))); - } - return itemInstance; - } - } - } - } - delete hr; - return itemInstance; + if (emptyBucket(level, x, y, z, xt, yt, zt) && + !player->abilities.instabuild) { + return std::shared_ptr( + new ItemInstance(Item::bucket_empty)); + } + } + } else { + if (content == 0) { + if (hr->entity->GetType() == eTYPE_COW) { + delete hr; + if (--itemInstance->count <= 0) { + return std::shared_ptr( + new ItemInstance(Item::milk)); + } else { + if (!player->inventory->add(std::shared_ptr( + new ItemInstance(Item::milk)))) { + player->drop(std::shared_ptr( + new ItemInstance(Item::milk_Id, 1, 0))); + } + return itemInstance; + } + } + } + } + delete hr; + return itemInstance; } -bool BucketItem::emptyBucket(Level *level, double x, double y, double z, int xt, int yt, int zt) -{ +bool BucketItem::emptyBucket(Level* level, double x, double y, double z, int xt, + int yt, int zt) { if (content <= 0) return false; - if (level->isEmptyTile(xt, yt, zt) || !level->getMaterial(xt, yt, zt)->isSolid()) - { - if (level->dimension->ultraWarm && content == Tile::water_Id) - { - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, 2.6f + (level->random->nextFloat() - level->random->nextFloat()) * 0.8f); + if (level->isEmptyTile(xt, yt, zt) || + !level->getMaterial(xt, yt, zt)->isSolid()) { + if (level->dimension->ultraWarm && content == Tile::water_Id) { + level->playSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, + 2.6f + + (level->random->nextFloat() - level->random->nextFloat()) * + 0.8f); - for (int i = 0; i < 8; i++) - { - level->addParticle(eParticleType_largesmoke, xt + Math::random(), yt + Math::random(), zt + Math::random(), 0, 0, 0); + for (int i = 0; i < 8; i++) { + level->addParticle(eParticleType_largesmoke, + xt + Math::random(), yt + Math::random(), + zt + Math::random(), 0, 0, 0); } - } - else - { + } else { level->setTileAndData(xt, yt, zt, content, 0); } diff --git a/Minecraft.World/Items/BucketItem.h b/Minecraft.World/Items/BucketItem.h index f865ba21e..86ee30ed2 100644 --- a/Minecraft.World/Items/BucketItem.h +++ b/Minecraft.World/Items/BucketItem.h @@ -5,27 +5,29 @@ class Player; class Level; -class BucketItem : public Item -{ +class BucketItem : public Item { private: - int content; + int content; public: - BucketItem(int id, int content); + BucketItem(int id, int content); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); - // TU9 - bool emptyBucket(Level *level, double x, double y, double z, int xt, int yt, int zt); + // TU9 + bool emptyBucket(Level* level, double x, double y, double z, int xt, int yt, + int zt); - /* - * public boolean useOn(ItemInstance instance, Player player, Level level, - * int x, int y, int z, int face) { if (content == 0) { } else { if (face == - * 0) y--; if (face == 1) y++; if (face == 2) z--; if (face == 3) z++; if - * (face == 4) x--; if (face == 5) x++; int targetType = level.getTile(x, y, - * z); if (targetType == 0) { level.setTile(x, y, z, content); } - * player->inventory.items[player->inventory.selected] = new - * ItemInstance(Item.bucket_empty); } return true; } - */ + /* + * public boolean useOn(ItemInstance instance, Player player, Level level, + * int x, int y, int z, int face) { if (content == 0) { } else { if (face == + * 0) y--; if (face == 1) y++; if (face == 2) z--; if (face == 3) z++; if + * (face == 4) x--; if (face == 5) x++; int targetType = level.getTile(x, y, + * z); if (targetType == 0) { level.setTile(x, y, z, content); } + * player->inventory.items[player->inventory.selected] = new + * ItemInstance(Item.bucket_empty); } return true; } + */ }; \ No newline at end of file diff --git a/Minecraft.World/Items/CarrotOnAStickItem.cpp b/Minecraft.World/Items/CarrotOnAStickItem.cpp index a63e7c20c..8aef55b32 100644 --- a/Minecraft.World/Items/CarrotOnAStickItem.cpp +++ b/Minecraft.World/Items/CarrotOnAStickItem.cpp @@ -5,43 +5,38 @@ #include "../Headers/net.minecraft.world.item.h" #include "CarrotOnAStickItem.h" -CarrotOnAStickItem::CarrotOnAStickItem(int id) : Item(id) -{ - setMaxStackSize(1); - setMaxDamage(25); +CarrotOnAStickItem::CarrotOnAStickItem(int id) : Item(id) { + setMaxStackSize(1); + setMaxDamage(25); } -bool CarrotOnAStickItem::isHandEquipped() -{ - return true; -} +bool CarrotOnAStickItem::isHandEquipped() { return true; } -bool CarrotOnAStickItem::isMirroredArt() -{ - return true; -} +bool CarrotOnAStickItem::isMirroredArt() { return true; } -std::shared_ptr CarrotOnAStickItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - if (player->isRiding()) - { - std::shared_ptr pig = std::dynamic_pointer_cast(player->riding); - if(pig) - { - if (pig->getControlGoal()->canBoost() && itemInstance->getMaxDamage() - itemInstance->getAuxValue() >= 7) - { - pig->getControlGoal()->boost(); - itemInstance->hurt(7, player); +std::shared_ptr CarrotOnAStickItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + if (player->isRiding()) { + std::shared_ptr pig = + std::dynamic_pointer_cast(player->riding); + if (pig) { + if (pig->getControlGoal()->canBoost() && + itemInstance->getMaxDamage() - itemInstance->getAuxValue() >= + 7) { + pig->getControlGoal()->boost(); + itemInstance->hurt(7, player); - if (itemInstance->count == 0) - { - std::shared_ptr replacement = std::shared_ptr(new ItemInstance(Item::fishingRod)); - replacement->setTag(itemInstance->tag); - return replacement; - } - } - } - } + if (itemInstance->count == 0) { + std::shared_ptr replacement = + std::shared_ptr( + new ItemInstance(Item::fishingRod)); + replacement->setTag(itemInstance->tag); + return replacement; + } + } + } + } - return itemInstance; + return itemInstance; } \ No newline at end of file diff --git a/Minecraft.World/Items/CarrotOnAStickItem.h b/Minecraft.World/Items/CarrotOnAStickItem.h index ef58c40f3..e44a4fe9e 100644 --- a/Minecraft.World/Items/CarrotOnAStickItem.h +++ b/Minecraft.World/Items/CarrotOnAStickItem.h @@ -2,12 +2,13 @@ #include "Item.h" -class CarrotOnAStickItem : public Item -{ +class CarrotOnAStickItem : public Item { public: - CarrotOnAStickItem(int id); + CarrotOnAStickItem(int id); - bool isHandEquipped(); - bool isMirroredArt(); - std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); + bool isHandEquipped(); + bool isMirroredArt(); + std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/ClockItem.cpp b/Minecraft.World/Items/ClockItem.cpp index c18735c95..cb73ebc5f 100644 --- a/Minecraft.World/Items/ClockItem.cpp +++ b/Minecraft.World/Items/ClockItem.cpp @@ -5,37 +5,33 @@ #include "../Headers/net.minecraft.world.h" #ifdef __PSVITA__ -const std::wstring ClockItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = {L"clockP0"}; +const std::wstring ClockItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = { + L"clockP0"}; #else -const std::wstring ClockItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = {L"clockP0",L"clockP1",L"clockP2",L"clockP3"}; +const std::wstring ClockItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = { + L"clockP0", L"clockP1", L"clockP2", L"clockP3"}; #endif -ClockItem::ClockItem(int id) : Item(id) -{ - icons = NULL; +ClockItem::ClockItem(int id) : Item(id) { icons = NULL; } + +// 4J Added so that we can override the icon id used to calculate the texture +// UV's for each player +Icon* ClockItem::getIcon(int auxValue) { + Icon* icon = Item::getIcon(auxValue); + Minecraft* pMinecraft = Minecraft::GetInstance(); + + if (pMinecraft->player != NULL && auxValue == 0) { + icon = icons[pMinecraft->player->GetXboxPad()]; + } + return icon; } -// 4J Added so that we can override the icon id used to calculate the texture UV's for each player -Icon *ClockItem::getIcon(int auxValue) -{ - Icon *icon = Item::getIcon(auxValue); - Minecraft *pMinecraft = Minecraft::GetInstance(); +void ClockItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); - if( pMinecraft->player != NULL && auxValue == 0 ) - { - icon = icons[pMinecraft->player->GetXboxPad()]; - } - return icon; -} - -void ClockItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - - icons = new Icon *[XUSER_MAX_COUNT]; - - for (int i = 0; i < XUSER_MAX_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_PLAYER_ICON[i]); - } + icons = new Icon*[XUSER_MAX_COUNT]; + + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_PLAYER_ICON[i]); + } } diff --git a/Minecraft.World/Items/ClockItem.h b/Minecraft.World/Items/ClockItem.h index 3b268422b..f3022f5dc 100644 --- a/Minecraft.World/Items/ClockItem.h +++ b/Minecraft.World/Items/ClockItem.h @@ -1,19 +1,19 @@ #pragma once -// 4J Added so that we can override the icon id used to calculate the texture UV's for each player +// 4J Added so that we can override the icon id used to calculate the texture +// UV's for each player #include "Item.h" -class ClockItem : public Item -{ +class ClockItem : public Item { private: - Icon **icons; - static const std::wstring TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT]; + Icon** icons; + static const std::wstring TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT]; public: - ClockItem(int id); + ClockItem(int id); - virtual Icon *getIcon(int auxValue); + virtual Icon* getIcon(int auxValue); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/CoalItem.cpp b/Minecraft.World/Items/CoalItem.cpp index 9cb668152..3318e61dc 100644 --- a/Minecraft.World/Items/CoalItem.cpp +++ b/Minecraft.World/Items/CoalItem.cpp @@ -6,17 +6,15 @@ #include "../Headers/net.minecraft.world.entity.player.h" #include "CoalItem.h" -CoalItem::CoalItem(int id) : Item( id ) -{ - setStackedByData(true); - setMaxDamage(0); +CoalItem::CoalItem(int id) : Item(id) { + setStackedByData(true); + setMaxDamage(0); } -unsigned int CoalItem::getDescriptionId(std::shared_ptr instance) -{ - if (instance->getAuxValue() == CHAR_COAL) - { - return IDS_ITEM_CHARCOAL; - } - return IDS_ITEM_COAL; +unsigned int CoalItem::getDescriptionId( + std::shared_ptr instance) { + if (instance->getAuxValue() == CHAR_COAL) { + return IDS_ITEM_CHARCOAL; + } + return IDS_ITEM_COAL; } diff --git a/Minecraft.World/Items/CoalItem.h b/Minecraft.World/Items/CoalItem.h index ae3eda905..a21f5663a 100644 --- a/Minecraft.World/Items/CoalItem.h +++ b/Minecraft.World/Items/CoalItem.h @@ -1,17 +1,16 @@ #pragma once - #include "Item.h" class ItemInstance; -class CoalItem : public Item -{ +class CoalItem : public Item { public: - static const int STONE_COAL = 0; - static const int CHAR_COAL = 1; + static const int STONE_COAL = 0; + static const int CHAR_COAL = 1; - CoalItem(int id); + CoalItem(int id); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/CompassItem.cpp b/Minecraft.World/Items/CompassItem.cpp index 4eb9d1fd4..d66e3197b 100644 --- a/Minecraft.World/Items/CompassItem.cpp +++ b/Minecraft.World/Items/CompassItem.cpp @@ -5,38 +5,34 @@ #include "../Headers/net.minecraft.world.h" #ifdef __PSVITA__ -const std::wstring CompassItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = {L"compassP0"}; +const std::wstring CompassItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = { + L"compassP0"}; #else -const std::wstring CompassItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = {L"compassP0",L"compassP1",L"compassP2",L"compassP3"}; +const std::wstring CompassItem::TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT] = { + L"compassP0", L"compassP1", L"compassP2", L"compassP3"}; #endif -CompassItem::CompassItem(int id) : Item(id) -{ - icons = NULL; +CompassItem::CompassItem(int id) : Item(id) { icons = NULL; } + +// 4J Added so that we can override the icon id used to calculate the texture +// UV's for each player + +Icon* CompassItem::getIcon(int auxValue) { + Icon* icon = Item::getIcon(auxValue); + Minecraft* pMinecraft = Minecraft::GetInstance(); + + if (pMinecraft->player != NULL && auxValue == 0) { + icon = icons[pMinecraft->player->GetXboxPad()]; + } + return icon; } -// 4J Added so that we can override the icon id used to calculate the texture UV's for each player +void CompassItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); -Icon *CompassItem::getIcon(int auxValue) -{ - Icon *icon = Item::getIcon(auxValue); - Minecraft *pMinecraft = Minecraft::GetInstance(); + icons = new Icon*[XUSER_MAX_COUNT]; - if( pMinecraft->player != NULL && auxValue == 0 ) - { - icon = icons[pMinecraft->player->GetXboxPad()]; - } - return icon; -} - -void CompassItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - - icons = new Icon *[XUSER_MAX_COUNT]; - - for (int i = 0; i < XUSER_MAX_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(TEXTURE_PLAYER_ICON[i]); - } + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + icons[i] = iconRegister->registerIcon(TEXTURE_PLAYER_ICON[i]); + } } diff --git a/Minecraft.World/Items/CompassItem.h b/Minecraft.World/Items/CompassItem.h index 83399f609..96942373f 100644 --- a/Minecraft.World/Items/CompassItem.h +++ b/Minecraft.World/Items/CompassItem.h @@ -1,19 +1,19 @@ #pragma once -// 4J Added so that we can override the icon id used to calculate the texture UV's for each player +// 4J Added so that we can override the icon id used to calculate the texture +// UV's for each player #include "Item.h" -class CompassItem : public Item -{ +class CompassItem : public Item { private: - Icon **icons; - static const std::wstring TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT]; + Icon** icons; + static const std::wstring TEXTURE_PLAYER_ICON[XUSER_MAX_COUNT]; public: - CompassItem(int id); + CompassItem(int id); - virtual Icon *getIcon(int auxValue); + virtual Icon* getIcon(int auxValue); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/ComplexItem.cpp b/Minecraft.World/Items/ComplexItem.cpp index 14d24e216..45a563348 100644 --- a/Minecraft.World/Items/ComplexItem.cpp +++ b/Minecraft.World/Items/ComplexItem.cpp @@ -4,16 +4,12 @@ #include "../Headers/net.minecraft.world.level.h" #include "ComplexItem.h" -ComplexItem::ComplexItem(int id) : Item(id) -{ -} +ComplexItem::ComplexItem(int id) : Item(id) {} -bool ComplexItem::isComplex() -{ - return true; -} +bool ComplexItem::isComplex() { return true; } -std::shared_ptr ComplexItem::getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ +std::shared_ptr ComplexItem::getUpdatePacket( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { return nullptr; } \ No newline at end of file diff --git a/Minecraft.World/Items/ComplexItem.h b/Minecraft.World/Items/ComplexItem.h index 4657274f5..2467ea952 100644 --- a/Minecraft.World/Items/ComplexItem.h +++ b/Minecraft.World/Items/ComplexItem.h @@ -1,18 +1,18 @@ #pragma once - #include "Item.h" class Player; class Packet; class Level; -class ComplexItem : public Item -{ +class ComplexItem : public Item { protected: - ComplexItem(int id); + ComplexItem(int id); public: - virtual bool isComplex(); - virtual std::shared_ptr getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); + virtual bool isComplex(); + virtual std::shared_ptr getUpdatePacket( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); }; diff --git a/Minecraft.World/Items/DiggerItem.cpp b/Minecraft.World/Items/DiggerItem.cpp index 73f73a88f..a54e76bd1 100644 --- a/Minecraft.World/Items/DiggerItem.cpp +++ b/Minecraft.World/Items/DiggerItem.cpp @@ -4,61 +4,54 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "DiggerItem.h" -DiggerItem::DiggerItem(int id, int attackDamage, const Tier *tier, TileArray *tiles) : Item( id ), tier( tier ) -{ - //this->tier = tier; - this->tiles = tiles; - maxStackSize = 1; - setMaxDamage(tier->getUses()); - this->speed = tier->getSpeed(); - this->attackDamage = attackDamage + tier->getAttackDamageBonus(); +DiggerItem::DiggerItem(int id, int attackDamage, const Tier* tier, + TileArray* tiles) + : Item(id), tier(tier) { + // this->tier = tier; + this->tiles = tiles; + maxStackSize = 1; + setMaxDamage(tier->getUses()); + this->speed = tier->getSpeed(); + this->attackDamage = attackDamage + tier->getAttackDamageBonus(); } -float DiggerItem::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - for (unsigned int i = 0; i < tiles->length; i++) - if ( (*tiles)[i] == tile) return speed; - return 1; +float DiggerItem::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + for (unsigned int i = 0; i < tiles->length; i++) + if ((*tiles)[i] == tile) return speed; + return 1; } -bool DiggerItem::hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker) -{ - itemInstance->hurt(2, attacker); - return true; +bool DiggerItem::hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker) { + itemInstance->hurt(2, attacker); + return true; } -bool DiggerItem::mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner) -{ - // Don't damage tools if the tile can be destroyed in one hit. - if (Tile::tiles[tile]->getDestroySpeed(level, x, y, z) != 0.0) itemInstance->hurt(1, owner); - return true; +bool DiggerItem::mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner) { + // Don't damage tools if the tile can be destroyed in one hit. + if (Tile::tiles[tile]->getDestroySpeed(level, x, y, z) != 0.0) + itemInstance->hurt(1, owner); + return true; } -int DiggerItem::getAttackDamage(std::shared_ptr entity) -{ - return attackDamage; +int DiggerItem::getAttackDamage(std::shared_ptr entity) { + return attackDamage; } -bool DiggerItem::isHandEquipped() -{ - return true; -} +bool DiggerItem::isHandEquipped() { return true; } -int DiggerItem::getEnchantmentValue() -{ - return tier->getEnchantmentValue(); -} +int DiggerItem::getEnchantmentValue() { return tier->getEnchantmentValue(); } -const Item::Tier *DiggerItem::getTier() -{ - return tier; -} +const Item::Tier* DiggerItem::getTier() { return tier; } -bool DiggerItem::isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem) -{ - if (tier->getTierItemId() == repairItem->id) - { - return true; - } - return Item::isValidRepairItem(source, repairItem); +bool DiggerItem::isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem) { + if (tier->getTierItemId() == repairItem->id) { + return true; + } + return Item::isValidRepairItem(source, repairItem); } \ No newline at end of file diff --git a/Minecraft.World/Items/DiggerItem.h b/Minecraft.World/Items/DiggerItem.h index 747c755fe..2e01d1b69 100644 --- a/Minecraft.World/Items/DiggerItem.h +++ b/Minecraft.World/Items/DiggerItem.h @@ -4,28 +4,35 @@ class Mob; -class DiggerItem : public Item -{ +class DiggerItem : public Item { private: - TileArray *tiles; -protected: - float speed; -private: - int attackDamage; + TileArray* tiles; protected: - const Tier *tier; + float speed; - DiggerItem(int id, int attackDamage, const Tier *tier, TileArray *tiles); +private: + int attackDamage; + +protected: + const Tier* tier; + + DiggerItem(int id, int attackDamage, const Tier* tier, TileArray* tiles); public: - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); - virtual bool hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker); - virtual bool mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner); - virtual int getAttackDamage(std::shared_ptr entity); - virtual bool isHandEquipped(); - virtual int getEnchantmentValue(); + virtual float getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile); + virtual bool hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker); + virtual bool mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner); + virtual int getAttackDamage(std::shared_ptr entity); + virtual bool isHandEquipped(); + virtual int getEnchantmentValue(); - const Tier *getTier(); - bool isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem); + const Tier* getTier(); + bool isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem); }; \ No newline at end of file diff --git a/Minecraft.World/Items/DoorItem.cpp b/Minecraft.World/Items/DoorItem.cpp index 649e736df..e4cc4ef80 100644 --- a/Minecraft.World/Items/DoorItem.cpp +++ b/Minecraft.World/Items/DoorItem.cpp @@ -12,64 +12,74 @@ #include "../Stats/GenericStats.h" #include "DoorItem.h" -DoorItem::DoorItem(int id, Material *material) : Item(id) -{ - this->material = material; - maxStackSize = 1; +DoorItem::DoorItem(int id, Material* material) : Item(id) { + this->material = material; + maxStackSize = 1; } -bool DoorItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (face != Facing::UP) return false; - y++; +bool DoorItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + if (face != Facing::UP) return false; + y++; - Tile *tile; + Tile* tile; - if (material == Material::wood) tile = Tile::door_wood; - else tile = Tile::door_iron; + if (material == Material::wood) + tile = Tile::door_wood; + else + tile = Tile::door_iron; - if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) return false; - if (!tile->mayPlace(level, x, y, z)) return false; + if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) + return false; + if (!tile->mayPlace(level, x, y, z)) return false; - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(bTestUseOnOnly) return true; + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (bTestUseOnOnly) return true; - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat(GenericStats::blocksPlaced(tile->id),GenericStats::param_blocksPlaced(tile->id,instance->getAuxValue(),1)); + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat( + GenericStats::blocksPlaced(tile->id), + GenericStats::param_blocksPlaced(tile->id, instance->getAuxValue(), 1)); - int dir = Mth::floor(((player->yRot + 180) * 4) / 360 - 0.5) & 3; - place(level, x, y, z, dir, tile); + int dir = Mth::floor(((player->yRot + 180) * 4) / 360 - 0.5) & 3; + place(level, x, y, z, dir, tile); - instance->count--; - return true; + instance->count--; + return true; } -void DoorItem::place(Level *level, int x, int y, int z, int dir, Tile *tile) -{ +void DoorItem::place(Level* level, int x, int y, int z, int dir, Tile* tile) { + int xra = 0; + int zra = 0; + if (dir == 0) zra = +1; + if (dir == 1) xra = -1; + if (dir == 2) zra = -1; + if (dir == 3) xra = +1; - int xra = 0; - int zra = 0; - if (dir == 0) zra = +1; - if (dir == 1) xra = -1; - if (dir == 2) zra = -1; - if (dir == 3) xra = +1; + int solidLeft = + (level->isSolidBlockingTile(x - xra, y, z - zra) ? 1 : 0) + + (level->isSolidBlockingTile(x - xra, y + 1, z - zra) ? 1 : 0); + int solidRight = + (level->isSolidBlockingTile(x + xra, y, z + zra) ? 1 : 0) + + (level->isSolidBlockingTile(x + xra, y + 1, z + zra) ? 1 : 0); + bool doorLeft = (level->getTile(x - xra, y, z - zra) == tile->id) || + (level->getTile(x - xra, y + 1, z - zra) == tile->id); + bool doorRight = (level->getTile(x + xra, y, z + zra) == tile->id) || + (level->getTile(x + xra, y + 1, z + zra) == tile->id); - int solidLeft = (level->isSolidBlockingTile(x - xra, y, z - zra) ? 1 : 0) + (level->isSolidBlockingTile(x - xra, y + 1, z - zra) ? 1 : 0); - int solidRight = (level->isSolidBlockingTile(x + xra, y, z + zra) ? 1 : 0) + (level->isSolidBlockingTile(x + xra, y + 1, z + zra) ? 1 : 0); + bool flip = false; + if (doorLeft && !doorRight) + flip = true; + else if (solidRight > solidLeft) + flip = true; - bool doorLeft = (level->getTile(x - xra, y, z - zra) == tile->id) || (level->getTile(x - xra, y + 1, z - zra) == tile->id); - bool doorRight = (level->getTile(x + xra, y, z + zra) == tile->id) || (level->getTile(x + xra, y + 1, z + zra) == tile->id); - - bool flip = false; - if (doorLeft && !doorRight) flip = true; - else if (solidRight > solidLeft) flip = true; - - level->noNeighborUpdate = true; - level->setTileAndData(x, y, z, tile->id, dir); - level->setTileAndData(x, y + 1, z, tile->id, 8 | (flip ? 1 : 0)); - level->noNeighborUpdate = false; - level->updateNeighborsAt(x, y, z, tile->id); - level->updateNeighborsAt(x, y + 1, z, tile->id); + level->noNeighborUpdate = true; + level->setTileAndData(x, y, z, tile->id, dir); + level->setTileAndData(x, y + 1, z, tile->id, 8 | (flip ? 1 : 0)); + level->noNeighborUpdate = false; + level->updateNeighborsAt(x, y, z, tile->id); + level->updateNeighborsAt(x, y + 1, z, tile->id); } - diff --git a/Minecraft.World/Items/DoorItem.h b/Minecraft.World/Items/DoorItem.h index e3588280b..3f20fe06b 100644 --- a/Minecraft.World/Items/DoorItem.h +++ b/Minecraft.World/Items/DoorItem.h @@ -1,20 +1,21 @@ #pragma once - #include "Item.h" class Player; class Material; class Level; -class DoorItem : public Item -{ +class DoorItem : public Item { private: - Material *material; + Material* material; public: - DoorItem(int id, Material *material); + DoorItem(int id, Material* material); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - static void place(Level *level, int x, int y, int z, int dir, Tile *tile); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + static void place(Level* level, int x, int y, int z, int dir, Tile* tile); }; diff --git a/Minecraft.World/Items/DyePowderItem.cpp b/Minecraft.World/Items/DyePowderItem.cpp index d35ac0415..930755bb8 100644 --- a/Minecraft.World/Items/DyePowderItem.cpp +++ b/Minecraft.World/Items/DyePowderItem.cpp @@ -14,76 +14,42 @@ #include "../Blocks/Material.h" #include "DyePowderItem.h" -DyePowderItem::DyePowderItem(int id) : Item( id ) -{ - setStackedByData(true); - setMaxDamage(0); - icons = NULL; +DyePowderItem::DyePowderItem(int id) : Item(id) { + setStackedByData(true); + setMaxDamage(0); + icons = NULL; } -const unsigned int DyePowderItem::COLOR_DESCS[] = -{ - IDS_ITEM_DYE_POWDER_BLACK, - IDS_ITEM_DYE_POWDER_RED, - IDS_ITEM_DYE_POWDER_GREEN, - IDS_ITEM_DYE_POWDER_BROWN, - IDS_ITEM_DYE_POWDER_BLUE, - IDS_ITEM_DYE_POWDER_PURPLE, - IDS_ITEM_DYE_POWDER_CYAN, - IDS_ITEM_DYE_POWDER_SILVER, - IDS_ITEM_DYE_POWDER_GRAY, - IDS_ITEM_DYE_POWDER_PINK, - IDS_ITEM_DYE_POWDER_LIME, - IDS_ITEM_DYE_POWDER_YELLOW, - IDS_ITEM_DYE_POWDER_LIGHT_BLUE, - IDS_ITEM_DYE_POWDER_MAGENTA, - IDS_ITEM_DYE_POWDER_ORANGE, - IDS_ITEM_DYE_POWDER_WHITE -}; +const unsigned int DyePowderItem::COLOR_DESCS[] = { + IDS_ITEM_DYE_POWDER_BLACK, IDS_ITEM_DYE_POWDER_RED, + IDS_ITEM_DYE_POWDER_GREEN, IDS_ITEM_DYE_POWDER_BROWN, + IDS_ITEM_DYE_POWDER_BLUE, IDS_ITEM_DYE_POWDER_PURPLE, + IDS_ITEM_DYE_POWDER_CYAN, IDS_ITEM_DYE_POWDER_SILVER, + IDS_ITEM_DYE_POWDER_GRAY, IDS_ITEM_DYE_POWDER_PINK, + IDS_ITEM_DYE_POWDER_LIME, IDS_ITEM_DYE_POWDER_YELLOW, + IDS_ITEM_DYE_POWDER_LIGHT_BLUE, IDS_ITEM_DYE_POWDER_MAGENTA, + IDS_ITEM_DYE_POWDER_ORANGE, IDS_ITEM_DYE_POWDER_WHITE}; -const unsigned int DyePowderItem::COLOR_USE_DESCS[] = -{ - IDS_DESC_DYE_BLACK, - IDS_DESC_DYE_RED, - IDS_DESC_DYE_GREEN, - IDS_DESC_DYE_BROWN, - IDS_DESC_DYE_BLUE, - IDS_DESC_DYE_PURPLE, - IDS_DESC_DYE_CYAN, - IDS_DESC_DYE_LIGHTGRAY, - IDS_DESC_DYE_GRAY, - IDS_DESC_DYE_PINK, - IDS_DESC_DYE_LIME, - IDS_DESC_DYE_YELLOW, - IDS_DESC_DYE_LIGHTBLUE, - IDS_DESC_DYE_MAGENTA, - IDS_DESC_DYE_ORANGE, - IDS_DESC_DYE_WHITE -}; +const unsigned int DyePowderItem::COLOR_USE_DESCS[] = { + IDS_DESC_DYE_BLACK, IDS_DESC_DYE_RED, IDS_DESC_DYE_GREEN, + IDS_DESC_DYE_BROWN, IDS_DESC_DYE_BLUE, IDS_DESC_DYE_PURPLE, + IDS_DESC_DYE_CYAN, IDS_DESC_DYE_LIGHTGRAY, IDS_DESC_DYE_GRAY, + IDS_DESC_DYE_PINK, IDS_DESC_DYE_LIME, IDS_DESC_DYE_YELLOW, + IDS_DESC_DYE_LIGHTBLUE, IDS_DESC_DYE_MAGENTA, IDS_DESC_DYE_ORANGE, + IDS_DESC_DYE_WHITE}; -const std::wstring DyePowderItem::COLOR_TEXTURES[] = -{ L"dyePowder_black", L"dyePowder_red", L"dyePowder_green", L"dyePowder_brown", L"dyePowder_blue", L"dyePowder_purple", L"dyePowder_cyan", L"dyePowder_silver", L"dyePowder_gray", L"dyePowder_pink", -L"dyePowder_lime", L"dyePowder_yellow", L"dyePowder_lightBlue", L"dyePowder_magenta", L"dyePowder_orange", L"dyePowder_white"}; +const std::wstring DyePowderItem::COLOR_TEXTURES[] = { + L"dyePowder_black", L"dyePowder_red", L"dyePowder_green", + L"dyePowder_brown", L"dyePowder_blue", L"dyePowder_purple", + L"dyePowder_cyan", L"dyePowder_silver", L"dyePowder_gray", + L"dyePowder_pink", L"dyePowder_lime", L"dyePowder_yellow", + L"dyePowder_lightBlue", L"dyePowder_magenta", L"dyePowder_orange", + L"dyePowder_white"}; -const int DyePowderItem::COLOR_RGB[] = -{ - 0x1e1b1b, - 0xb3312c, - 0x3b511a, - 0x51301a, - 0x253192, - 0x7b2fbe, - 0xababab, - 0x287697, - 0x434343, - 0xd88198, - 0x41cd34, - 0xdecf2a, - 0x6689d3, - 0xc354cd, - 0xeb8844, - 0xf0f0f0 -}; +const int DyePowderItem::COLOR_RGB[] = {0x1e1b1b, 0xb3312c, 0x3b511a, 0x51301a, + 0x253192, 0x7b2fbe, 0xababab, 0x287697, + 0x434343, 0xd88198, 0x41cd34, 0xdecf2a, + 0x6689d3, 0xc354cd, 0xeb8844, 0xf0f0f0}; const int DyePowderItem::BLACK = 0; const int DyePowderItem::RED = 1; @@ -102,216 +68,189 @@ const int DyePowderItem::MAGENTA = 13; const int DyePowderItem::ORANGE = 14; const int DyePowderItem::WHITE = 15; -Icon *DyePowderItem::getIcon(int itemAuxValue) -{ - int colorValue = Mth::clamp(itemAuxValue, 0, 15); - return icons[colorValue]; +Icon* DyePowderItem::getIcon(int itemAuxValue) { + int colorValue = Mth::clamp(itemAuxValue, 0, 15); + return icons[colorValue]; } -unsigned int DyePowderItem::getDescriptionId(std::shared_ptr itemInstance) -{ - int colorValue = Mth::clamp(itemInstance->getAuxValue(), 0, 15); - return COLOR_DESCS[colorValue]; +unsigned int DyePowderItem::getDescriptionId( + std::shared_ptr itemInstance) { + int colorValue = Mth::clamp(itemInstance->getAuxValue(), 0, 15); + return COLOR_DESCS[colorValue]; } -unsigned int DyePowderItem::getUseDescriptionId(std::shared_ptr itemInstance) -{ - return COLOR_USE_DESCS[itemInstance->getAuxValue()]; +unsigned int DyePowderItem::getUseDescriptionId( + std::shared_ptr itemInstance) { + return COLOR_USE_DESCS[itemInstance->getAuxValue()]; } -bool DyePowderItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (!player->mayBuild(x, y, z)) return false; +bool DyePowderItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + if (!player->mayBuild(x, y, z)) return false; - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if (itemInstance->getAuxValue() == WHITE) - { - // bone meal is a fertilizer, so instantly grow trees and stuff + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (itemInstance->getAuxValue() == WHITE) { + // bone meal is a fertilizer, so instantly grow trees and stuff - int tile = level->getTile(x, y, z); - if (tile == Tile::sapling_Id) - { - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - ((Sapling *) Tile::sapling)->growTree(level, x, y, z, level->random); - itemInstance->count--; - } - } - return true; - } - else if (tile == Tile::mushroom1_Id || tile == Tile::mushroom2_Id) - { - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - if (((Mushroom *) Tile::tiles[tile])->growTree(level, x, y, z, level->random)) - { - itemInstance->count--; - } - } - } - return true; - } - else if (tile == Tile::melonStem_Id || tile == Tile::pumpkinStem_Id) - { - if (level->getData(x, y, z) == 7) return false; - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - ((StemTile *) Tile::tiles[tile])->growCropsToMax(level, x, y, z); - itemInstance->count--; - } - } - return true; - } - else if (tile == Tile::carrots_Id || tile == Tile::potatoes_Id) - { - if (level->getData(x, y, z) == 7) return false; - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - ((CropTile *) Tile::tiles[tile])->growCropsToMax(level, x, y, z); - itemInstance->count--; - } - } - return true; - } - else if (tile == Tile::crops_Id) - { - if (level->getData(x, y, z) == 7) return false; - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - ((CropTile *) Tile::crops)->growCropsToMax(level, x, y, z); - itemInstance->count--; - } - } - return true; - } - else if (tile == Tile::cocoa_Id) - { - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - level->setData(x, y, z, (2 << 2) | DirectionalTile::getDirection(level->getData(x, y, z))); - itemInstance->count--; - } - } - return true; - } - else if (tile == Tile::grass_Id) - { - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - itemInstance->count--; + int tile = level->getTile(x, y, z); + if (tile == Tile::sapling_Id) { + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + ((Sapling*)Tile::sapling) + ->growTree(level, x, y, z, level->random); + itemInstance->count--; + } + } + return true; + } else if (tile == Tile::mushroom1_Id || tile == Tile::mushroom2_Id) { + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + if (((Mushroom*)Tile::tiles[tile]) + ->growTree(level, x, y, z, level->random)) { + itemInstance->count--; + } + } + } + return true; + } else if (tile == Tile::melonStem_Id || tile == Tile::pumpkinStem_Id) { + if (level->getData(x, y, z) == 7) return false; + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + ((StemTile*)Tile::tiles[tile]) + ->growCropsToMax(level, x, y, z); + itemInstance->count--; + } + } + return true; + } else if (tile == Tile::carrots_Id || tile == Tile::potatoes_Id) { + if (level->getData(x, y, z) == 7) return false; + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + ((CropTile*)Tile::tiles[tile]) + ->growCropsToMax(level, x, y, z); + itemInstance->count--; + } + } + return true; + } else if (tile == Tile::crops_Id) { + if (level->getData(x, y, z) == 7) return false; + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + ((CropTile*)Tile::crops)->growCropsToMax(level, x, y, z); + itemInstance->count--; + } + } + return true; + } else if (tile == Tile::cocoa_Id) { + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + level->setData(x, y, z, + (2 << 2) | DirectionalTile::getDirection( + level->getData(x, y, z))); + itemInstance->count--; + } + } + return true; + } else if (tile == Tile::grass_Id) { + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + itemInstance->count--; - for (int j = 0; j < 128; j++) - { - int xx = x; - int yy = y + 1; - int zz = z; - for (int i = 0; i < j / 16; i++) - { - xx += random->nextInt(3) - 1; - yy += (random->nextInt(3) - 1) * random->nextInt(3) / 2; - zz += random->nextInt(3) - 1; - if (level->getTile(xx, yy - 1, zz) != Tile::grass_Id || level->isSolidBlockingTile(xx, yy, zz)) - { - goto mainloop; - } - } + for (int j = 0; j < 128; j++) { + int xx = x; + int yy = y + 1; + int zz = z; + for (int i = 0; i < j / 16; i++) { + xx += random->nextInt(3) - 1; + yy += (random->nextInt(3) - 1) * + random->nextInt(3) / 2; + zz += random->nextInt(3) - 1; + if (level->getTile(xx, yy - 1, zz) != + Tile::grass_Id || + level->isSolidBlockingTile(xx, yy, zz)) { + goto mainloop; + } + } - if (level->getTile(xx, yy, zz) == 0) - { - if (random->nextInt(10) != 0) - { - if (Tile::tallgrass->canSurvive(level, xx, yy, zz)) level->setTileAndData(xx, yy, zz, Tile::tallgrass_Id, TallGrass::TALL_GRASS); - } - else if (random->nextInt(3) != 0) - { - if (Tile::flower->canSurvive(level, xx, yy, zz)) level->setTile(xx, yy, zz, Tile::flower_Id); - } - else - { - if (Tile::rose->canSurvive(level, xx, yy, zz)) level->setTile(xx, yy, zz, Tile::rose_Id); - } - } + if (level->getTile(xx, yy, zz) == 0) { + if (random->nextInt(10) != 0) { + if (Tile::tallgrass->canSurvive(level, xx, yy, + zz)) + level->setTileAndData( + xx, yy, zz, Tile::tallgrass_Id, + TallGrass::TALL_GRASS); + } else if (random->nextInt(3) != 0) { + if (Tile::flower->canSurvive(level, xx, yy, zz)) + level->setTile(xx, yy, zz, Tile::flower_Id); + } else { + if (Tile::rose->canSurvive(level, xx, yy, zz)) + level->setTile(xx, yy, zz, Tile::rose_Id); + } + } - // 4J - Stops infinite loops. -mainloop: continue; - } - } - } + // 4J - Stops infinite loops. + mainloop: + continue; + } + } + } - return true; - } - } - else if (itemInstance->getAuxValue() == BROWN) - { - // plant cocoa + return true; + } + } else if (itemInstance->getAuxValue() == BROWN) { + // plant cocoa - int tile = level->getTile(x, y, z); - int data = level->getData(x, y, z); + int tile = level->getTile(x, y, z); + int data = level->getData(x, y, z); - if (tile == Tile::treeTrunk_Id && TreeTile::getWoodType(data) == TreeTile::JUNGLE_TRUNK) - { - if (face == 0) return false; - if (face == 1) return false; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; + if (tile == Tile::treeTrunk_Id && + TreeTile::getWoodType(data) == TreeTile::JUNGLE_TRUNK) { + if (face == 0) return false; + if (face == 1) return false; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - if(!bTestUseOnOnly) - { - if (level->isEmptyTile(x, y, z)) - { - int cocoaData = Tile::tiles[Tile::cocoa_Id]->getPlacedOnFaceDataValue(level, x, y, z, face, clickX, clickY, clickZ, 0); - level->setTileAndData(x, y, z, Tile::cocoa_Id, cocoaData); - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - } - } - return true; - } - } - return false; + if (!bTestUseOnOnly) { + if (level->isEmptyTile(x, y, z)) { + int cocoaData = + Tile::tiles[Tile::cocoa_Id]->getPlacedOnFaceDataValue( + level, x, y, z, face, clickX, clickY, clickZ, 0); + level->setTileAndData(x, y, z, Tile::cocoa_Id, cocoaData); + if (!player->abilities.instabuild) { + itemInstance->count--; + } + } + } + return true; + } + } + return false; } -bool DyePowderItem::interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob) -{ - if (std::dynamic_pointer_cast( mob ) != NULL) - { - std::shared_ptr sheep = std::dynamic_pointer_cast(mob); - // convert to tile-based color value (0 is white instead of black) - int newColor = ClothTile::getTileDataForItemAuxValue(itemInstance->getAuxValue()); - if (!sheep->isSheared() && sheep->getColor() != newColor) - { - sheep->setColor(newColor); - itemInstance->count--; - } - return true; - } - return false; +bool DyePowderItem::interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob) { + if (std::dynamic_pointer_cast(mob) != NULL) { + std::shared_ptr sheep = std::dynamic_pointer_cast(mob); + // convert to tile-based color value (0 is white instead of black) + int newColor = + ClothTile::getTileDataForItemAuxValue(itemInstance->getAuxValue()); + if (!sheep->isSheared() && sheep->getColor() != newColor) { + sheep->setColor(newColor); + itemInstance->count--; + } + return true; + } + return false; } -void DyePowderItem::registerIcons(IconRegister *iconRegister) -{ - icons = new Icon *[DYE_POWDER_ITEM_TEXTURE_COUNT]; +void DyePowderItem::registerIcons(IconRegister* iconRegister) { + icons = new Icon*[DYE_POWDER_ITEM_TEXTURE_COUNT]; - for (int i = 0; i < DYE_POWDER_ITEM_TEXTURE_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(COLOR_TEXTURES[i]); - } + for (int i = 0; i < DYE_POWDER_ITEM_TEXTURE_COUNT; i++) { + icons[i] = iconRegister->registerIcon(COLOR_TEXTURES[i]); + } } \ No newline at end of file diff --git a/Minecraft.World/Items/DyePowderItem.h b/Minecraft.World/Items/DyePowderItem.h index f016a1e94..9fc7fe036 100644 --- a/Minecraft.World/Items/DyePowderItem.h +++ b/Minecraft.World/Items/DyePowderItem.h @@ -1,50 +1,54 @@ #pragma once - #include "Item.h" class Player; class Mob; class Level; -class DyePowderItem : public Item -{ +class DyePowderItem : public Item { public: - static const unsigned int COLOR_DESCS[]; - static const unsigned int COLOR_USE_DESCS[]; - static const std::wstring COLOR_TEXTURES[]; - static const int COLOR_RGB[]; + static const unsigned int COLOR_DESCS[]; + static const unsigned int COLOR_USE_DESCS[]; + static const std::wstring COLOR_TEXTURES[]; + static const int COLOR_RGB[]; - static const int BLACK; - static const int RED; - static const int GREEN; - static const int BROWN; - static const int BLUE; - static const int PURPLE; - static const int CYAN; - static const int SILVER; - static const int GRAY; - static const int PINK; - static const int LIME; - static const int YELLOW; - static const int LIGHT_BLUE; - static const int MAGENTA; - static const int ORANGE; - static const int WHITE; + static const int BLACK; + static const int RED; + static const int GREEN; + static const int BROWN; + static const int BLUE; + static const int PURPLE; + static const int CYAN; + static const int SILVER; + static const int GRAY; + static const int PINK; + static const int LIME; + static const int YELLOW; + static const int LIGHT_BLUE; + static const int MAGENTA; + static const int ORANGE; + static const int WHITE; private: - static const int DYE_POWDER_ITEM_TEXTURE_COUNT = 16; - Icon **icons; + static const int DYE_POWDER_ITEM_TEXTURE_COUNT = 16; + Icon** icons; public: - DyePowderItem(int id); + DyePowderItem(int id); - virtual Icon *getIcon(int itemAuxValue); - virtual unsigned int getDescriptionId(std::shared_ptr itemInstance); - virtual unsigned int getUseDescriptionId(std::shared_ptr itemInstance); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual bool interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob); + virtual Icon* getIcon(int itemAuxValue); + virtual unsigned int getDescriptionId( + std::shared_ptr itemInstance); + virtual unsigned int getUseDescriptionId( + std::shared_ptr itemInstance); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual bool interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Items/EggItem.cpp b/Minecraft.World/Items/EggItem.cpp index 6a05607f1..d2b9ebc28 100644 --- a/Minecraft.World/Items/EggItem.cpp +++ b/Minecraft.World/Items/EggItem.cpp @@ -13,19 +13,19 @@ #include "EggItem.h" #include "../Util/SoundTypes.h" +EggItem::EggItem(int id) : Item(id) { this->maxStackSize = 16; } -EggItem::EggItem(int id) : Item( id ) -{ - this->maxStackSize = 16; -} - -std::shared_ptr EggItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (!player->abilities.instabuild) - { - instance->count--; - } - level->playSound( std::dynamic_pointer_cast(player), eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) level->addEntity( std::shared_ptr( new ThrownEgg(level, std::dynamic_pointer_cast( player )) )); +std::shared_ptr EggItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (!player->abilities.instabuild) { + instance->count--; + } + level->playSound(std::dynamic_pointer_cast(player), + eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) + level->addEntity(std::shared_ptr( + new ThrownEgg(level, std::dynamic_pointer_cast(player)))); return instance; } diff --git a/Minecraft.World/Items/EggItem.h b/Minecraft.World/Items/EggItem.h index aa1a5d4ab..9a76a9f07 100644 --- a/Minecraft.World/Items/EggItem.h +++ b/Minecraft.World/Items/EggItem.h @@ -1,15 +1,15 @@ #pragma once - #include "Item.h" class Player; class Level; -class EggItem : public Item -{ +class EggItem : public Item { public: - EggItem(int id); + EggItem(int id); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); }; diff --git a/Minecraft.World/Items/EnchantedBookItem.cpp b/Minecraft.World/Items/EnchantedBookItem.cpp index 0a26c118e..b111d0b3e 100644 --- a/Minecraft.World/Items/EnchantedBookItem.cpp +++ b/Minecraft.World/Items/EnchantedBookItem.cpp @@ -4,141 +4,150 @@ #include "../Util/WeighedTreasure.h" #include "EnchantedBookItem.h" -const std::wstring EnchantedBookItem::TAG_STORED_ENCHANTMENTS = L"StoredEnchantments"; +const std::wstring EnchantedBookItem::TAG_STORED_ENCHANTMENTS = + L"StoredEnchantments"; -EnchantedBookItem::EnchantedBookItem(int id) : Item(id) -{ +EnchantedBookItem::EnchantedBookItem(int id) : Item(id) {} + +bool EnchantedBookItem::isFoil(std::shared_ptr itemInstance) { + return true; } -bool EnchantedBookItem::isFoil(std::shared_ptr itemInstance) -{ - return true; +bool EnchantedBookItem::isEnchantable( + std::shared_ptr itemInstance) { + return false; } -bool EnchantedBookItem::isEnchantable(std::shared_ptr itemInstance) -{ - return false; +const Rarity* EnchantedBookItem::getRarity( + std::shared_ptr itemInstance) { + ListTag* enchantments = getEnchantments(itemInstance); + if (enchantments && enchantments->size() > 0) { + return Rarity::uncommon; + } else { + return Item::getRarity(itemInstance); + } } -const Rarity *EnchantedBookItem::getRarity(std::shared_ptr itemInstance) -{ - ListTag *enchantments = getEnchantments(itemInstance); - if (enchantments && enchantments->size() > 0) - { - return Rarity::uncommon; - } - else - { - return Item::getRarity(itemInstance); - } +ListTag* EnchantedBookItem::getEnchantments( + std::shared_ptr item) { + if (item->tag == NULL || + !item->tag->contains((wchar_t*)TAG_STORED_ENCHANTMENTS.c_str())) { + return new ListTag(); + } + + return (ListTag*)item->tag->get( + (wchar_t*)TAG_STORED_ENCHANTMENTS.c_str()); } -ListTag *EnchantedBookItem::getEnchantments(std::shared_ptr item) -{ - if (item->tag == NULL || !item->tag->contains((wchar_t *)TAG_STORED_ENCHANTMENTS.c_str())) - { - return new ListTag(); - } +void EnchantedBookItem::appendHoverText( + std::shared_ptr itemInstance, std::shared_ptr player, + std::vector* lines, bool advanced, + std::vector& unformattedStrings) { + Item::appendHoverText(itemInstance, player, lines, advanced, + unformattedStrings); - return (ListTag *) item->tag->get((wchar_t *)TAG_STORED_ENCHANTMENTS.c_str()); + ListTag* list = getEnchantments(itemInstance); + + if (list != NULL) { + std::wstring unformatted = L""; + for (int i = 0; i < list->size(); i++) { + int type = + list->get(i)->getShort((wchar_t*)ItemInstance::TAG_ENCH_ID); + int level = + list->get(i)->getShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL); + + if (Enchantment::enchantments[type] != NULL) { + lines->push_back(Enchantment::enchantments[type]->getFullname( + level, unformatted)); + unformattedStrings.push_back(unformatted); + } + } + } } -void EnchantedBookItem::appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings) -{ - Item::appendHoverText(itemInstance, player, lines, advanced, unformattedStrings); +void EnchantedBookItem::addEnchantment(std::shared_ptr item, + EnchantmentInstance* enchantment) { + ListTag* enchantments = getEnchantments(item); + bool add = true; - ListTag *list = getEnchantments(itemInstance); + for (int i = 0; i < enchantments->size(); i++) { + CompoundTag* tag = enchantments->get(i); - if (list != NULL) - { - std::wstring unformatted = L""; - for (int i = 0; i < list->size(); i++) - { - int type = list->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID); - int level = list->get(i)->getShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL); + if (tag->getShort((wchar_t*)ItemInstance::TAG_ENCH_ID) == + enchantment->enchantment->id) { + if (tag->getShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL) < + enchantment->level) { + tag->putShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL, + (short)enchantment->level); + } - if (Enchantment::enchantments[type] != NULL) - { - lines->push_back(Enchantment::enchantments[type]->getFullname(level, unformatted)); - unformattedStrings.push_back(unformatted); - } - } - } + add = false; + break; + } + } + + if (add) { + CompoundTag* tag = new CompoundTag(); + + tag->putShort((wchar_t*)ItemInstance::TAG_ENCH_ID, + (short)enchantment->enchantment->id); + tag->putShort((wchar_t*)ItemInstance::TAG_ENCH_LEVEL, + (short)enchantment->level); + + enchantments->add(tag); + } + + if (!item->hasTag()) item->setTag(new CompoundTag()); + item->getTag()->put((wchar_t*)TAG_STORED_ENCHANTMENTS.c_str(), + enchantments); } -void EnchantedBookItem::addEnchantment(std::shared_ptr item, EnchantmentInstance *enchantment) -{ - ListTag *enchantments = getEnchantments(item); - bool add = true; - - for (int i = 0; i < enchantments->size(); i++) - { - CompoundTag *tag = enchantments->get(i); - - if (tag->getShort((wchar_t *)ItemInstance::TAG_ENCH_ID) == enchantment->enchantment->id) - { - if (tag->getShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL) < enchantment->level) - { - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short) enchantment->level); - } - - add = false; - break; - } - } - - if (add) - { - CompoundTag *tag = new CompoundTag(); - - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_ID, (short) enchantment->enchantment->id); - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short) enchantment->level); - - enchantments->add(tag); - } - - if (!item->hasTag()) item->setTag(new CompoundTag()); - item->getTag()->put((wchar_t *)TAG_STORED_ENCHANTMENTS.c_str(), enchantments); +std::shared_ptr EnchantedBookItem::createForEnchantment( + EnchantmentInstance* enchant) { + std::shared_ptr item = + std::shared_ptr(new ItemInstance(this)); + addEnchantment(item, enchant); + return item; } -std::shared_ptr EnchantedBookItem::createForEnchantment(EnchantmentInstance *enchant) -{ - std::shared_ptr item = std::shared_ptr(new ItemInstance(this)); - addEnchantment(item, enchant); - return item; +void EnchantedBookItem::createForEnchantment( + Enchantment* enchant, std::vector >* items) { + for (int i = enchant->getMinLevel(); i <= enchant->getMaxLevel(); i++) { + items->push_back( + createForEnchantment(new EnchantmentInstance(enchant, i))); + } } -void EnchantedBookItem::createForEnchantment(Enchantment *enchant, std::vector > *items) -{ - for (int i = enchant->getMinLevel(); i <= enchant->getMaxLevel(); i++) - { - items->push_back(createForEnchantment(new EnchantmentInstance(enchant, i))); - } +std::shared_ptr EnchantedBookItem::createForRandomLoot( + Random* random) { + Enchantment* enchantment = Enchantment::validEnchantments[random->nextInt( + Enchantment::validEnchantments.size())]; + std::shared_ptr book = + std::shared_ptr(new ItemInstance(id, 1, 0)); + int level = Mth::nextInt(random, enchantment->getMinLevel(), + enchantment->getMaxLevel()); + + addEnchantment(book, new EnchantmentInstance(enchantment, level)); + + return book; } -std::shared_ptr EnchantedBookItem::createForRandomLoot(Random *random) -{ - Enchantment *enchantment = Enchantment::validEnchantments[random->nextInt(Enchantment::validEnchantments.size())]; - std::shared_ptr book = std::shared_ptr(new ItemInstance(id, 1, 0)); - int level = Mth::nextInt(random, enchantment->getMinLevel(), enchantment->getMaxLevel()); - - addEnchantment(book, new EnchantmentInstance(enchantment, level)); - - return book; +WeighedTreasure* EnchantedBookItem::createForRandomTreasure(Random* random) { + return createForRandomTreasure(random, 1, 1, 1); } -WeighedTreasure *EnchantedBookItem::createForRandomTreasure(Random *random) -{ - return createForRandomTreasure(random, 1, 1, 1); -} +WeighedTreasure* EnchantedBookItem::createForRandomTreasure(Random* random, + int minCount, + int maxCount, + int weight) { + Enchantment* enchantment = Enchantment::validEnchantments[random->nextInt( + Enchantment::validEnchantments.size())]; + std::shared_ptr book = + std::shared_ptr(new ItemInstance(id, 1, 0)); + int level = Mth::nextInt(random, enchantment->getMinLevel(), + enchantment->getMaxLevel()); -WeighedTreasure *EnchantedBookItem::createForRandomTreasure(Random *random, int minCount, int maxCount, int weight) -{ - Enchantment *enchantment = Enchantment::validEnchantments[random->nextInt(Enchantment::validEnchantments.size())]; - std::shared_ptr book = std::shared_ptr(new ItemInstance(id, 1, 0)); - int level = Mth::nextInt(random, enchantment->getMinLevel(), enchantment->getMaxLevel()); + addEnchantment(book, new EnchantmentInstance(enchantment, level)); - addEnchantment(book, new EnchantmentInstance(enchantment, level)); - - return new WeighedTreasure(book, minCount, maxCount, weight); + return new WeighedTreasure(book, minCount, maxCount, weight); } \ No newline at end of file diff --git a/Minecraft.World/Items/EnchantedBookItem.h b/Minecraft.World/Items/EnchantedBookItem.h index 680d9898f..459aae6a7 100644 --- a/Minecraft.World/Items/EnchantedBookItem.h +++ b/Minecraft.World/Items/EnchantedBookItem.h @@ -4,22 +4,29 @@ class EnchantmentInstance; -class EnchantedBookItem : public Item -{ +class EnchantedBookItem : public Item { public: - static const std::wstring TAG_STORED_ENCHANTMENTS; + static const std::wstring TAG_STORED_ENCHANTMENTS; - EnchantedBookItem(int id); + EnchantedBookItem(int id); - bool isFoil(std::shared_ptr itemInstance); - bool isEnchantable(std::shared_ptr itemInstance); - const Rarity *getRarity(std::shared_ptr itemInstance); - ListTag *getEnchantments(std::shared_ptr item); - void appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings); - void addEnchantment(std::shared_ptr item, EnchantmentInstance *enchantment); - std::shared_ptr createForEnchantment(EnchantmentInstance *enchant); - void createForEnchantment(Enchantment *enchant, std::vector > *items); - std::shared_ptr createForRandomLoot(Random *random); - WeighedTreasure *createForRandomTreasure(Random *random); - WeighedTreasure *createForRandomTreasure(Random *random, int minCount, int maxCount, int weight); + bool isFoil(std::shared_ptr itemInstance); + bool isEnchantable(std::shared_ptr itemInstance); + const Rarity* getRarity(std::shared_ptr itemInstance); + ListTag* getEnchantments(std::shared_ptr item); + void appendHoverText(std::shared_ptr itemInstance, + std::shared_ptr player, + std::vector* lines, bool advanced, + std::vector& unformattedStrings); + void addEnchantment(std::shared_ptr item, + EnchantmentInstance* enchantment); + std::shared_ptr createForEnchantment( + EnchantmentInstance* enchant); + void createForEnchantment( + Enchantment* enchant, + std::vector >* items); + std::shared_ptr createForRandomLoot(Random* random); + WeighedTreasure* createForRandomTreasure(Random* random); + WeighedTreasure* createForRandomTreasure(Random* random, int minCount, + int maxCount, int weight); }; \ No newline at end of file diff --git a/Minecraft.World/Items/EnderEyeItem.cpp b/Minecraft.World/Items/EnderEyeItem.cpp index 0071b5e94..3d2706d9f 100644 --- a/Minecraft.World/Items/EnderEyeItem.cpp +++ b/Minecraft.World/Items/EnderEyeItem.cpp @@ -9,230 +9,226 @@ #include "../Util/SoundTypes.h" #include "../Level/LevelData.h" -EnderEyeItem::EnderEyeItem(int id) : Item(id) -{ +EnderEyeItem::EnderEyeItem(int id) : Item(id) {} + +bool EnderEyeItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + int targetType = level->getTile(x, y, z); + int targetData = level->getData(x, y, z); + + if (player->mayBuild(x, y, z) && + targetType == Tile::endPortalFrameTile_Id && + !TheEndPortalFrameTile::hasEye(targetData)) { + if (bTestUseOnOnly) return true; + if (level->isClientSide) return true; + level->setData(x, y, z, targetData + TheEndPortalFrameTile::EYE_BIT); + instance->count--; + + for (int i = 0; i < 16; i++) { + double xp = x + (5.0f + random->nextFloat() * 6.0f) / 16.0f; + double yp = y + 13.0f / 16.0f; + double zp = z + (5.0f + random->nextFloat() * 6.0f) / 16.0f; + double xa = 0; + double ya = 0; + double za = 0; + + level->addParticle(eParticleType_smoke, xp, yp, zp, xa, ya, za); + } + + // scan if the circle is complete + int direction = targetData & 3; + + // find borders + int min = 0; + int max = 0; + bool firstFound = false; + bool valid = true; + int rightHandDirection = Direction::DIRECTION_CLOCKWISE[direction]; + for (int offset = -2; offset <= 2; offset++) { + int testX = x + Direction::STEP_X[rightHandDirection] * offset; + int testZ = z + Direction::STEP_Z[rightHandDirection] * offset; + + int tile = level->getTile(testX, y, testZ); + if (tile == Tile::endPortalFrameTile->id) { + int data = level->getData(testX, y, testZ); + if (!TheEndPortalFrameTile::hasEye(data)) { + valid = false; + break; + } + max = offset; + if (!firstFound) { + min = offset; + firstFound = true; + } + } + } + + // got a full frame? + if (valid && max == min + 2) { + // check if other edge is valid + for (int offset = min; offset <= max; offset++) { + int testX = x + Direction::STEP_X[rightHandDirection] * offset; + int testZ = z + Direction::STEP_Z[rightHandDirection] * offset; + testX += Direction::STEP_X[direction] * 4; + testZ += Direction::STEP_Z[direction] * 4; + + int tile = level->getTile(testX, y, testZ); + int data = level->getData(testX, y, testZ); + if (tile != Tile::endPortalFrameTile_Id || + !TheEndPortalFrameTile::hasEye(data)) { + valid = false; + break; + } + } + // check if edges on the sides are valid + for (int side = (min - 1); side <= (max + 1); side += 4) { + for (int offset = 1; offset <= 3; offset++) { + int testX = + x + Direction::STEP_X[rightHandDirection] * side; + int testZ = + z + Direction::STEP_Z[rightHandDirection] * side; + testX += Direction::STEP_X[direction] * offset; + testZ += Direction::STEP_Z[direction] * offset; + + int tile = level->getTile(testX, y, testZ); + int data = level->getData(testX, y, testZ); + if (tile != Tile::endPortalFrameTile_Id || + !TheEndPortalFrameTile::hasEye(data)) { + valid = false; + break; + } + } + } + if (valid) { + // fill portal + for (int px = min; px <= max; px++) { + for (int pz = 1; pz <= 3; pz++) { + int targetX = + x + Direction::STEP_X[rightHandDirection] * px; + int targetZ = + z + Direction::STEP_Z[rightHandDirection] * px; + targetX += Direction::STEP_X[direction] * pz; + targetZ += Direction::STEP_Z[direction] * pz; + + level->setTile(targetX, y, targetZ, + Tile::endPortalTile_Id); + } + } + } + } + + return true; + } + return false; } -bool EnderEyeItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - int targetType = level->getTile(x, y, z); - int targetData = level->getData(x, y, z); +bool EnderEyeItem::TestUse(Level* level, std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, false); + if (hr != NULL && hr->type == HitResult::TILE) { + int tile = level->getTile(hr->x, hr->y, hr->z); + delete hr; + if (tile == Tile::endPortalFrameTile_Id) { + return false; + } + } else if (hr != NULL) { + delete hr; + } - if (player->mayBuild(x, y, z) && targetType == Tile::endPortalFrameTile_Id && !TheEndPortalFrameTile::hasEye(targetData)) - { - if(bTestUseOnOnly) return true; - if (level->isClientSide) return true; - level->setData(x, y, z, targetData + TheEndPortalFrameTile::EYE_BIT); - instance->count--; - - for (int i = 0; i < 16; i++) - { - double xp = x + (5.0f + random->nextFloat() * 6.0f) / 16.0f; - double yp = y + 13.0f / 16.0f; - double zp = z + (5.0f + random->nextFloat() * 6.0f) / 16.0f; - double xa = 0; - double ya = 0; - double za = 0; - - level->addParticle(eParticleType_smoke, xp, yp, zp, xa, ya, za); - } - - // scan if the circle is complete - int direction = targetData & 3; - - // find borders - int min = 0; - int max = 0; - bool firstFound = false; - bool valid = true; - int rightHandDirection = Direction::DIRECTION_CLOCKWISE[direction]; - for (int offset = -2; offset <= 2; offset++) - { - int testX = x + Direction::STEP_X[rightHandDirection] * offset; - int testZ = z + Direction::STEP_Z[rightHandDirection] * offset; - - int tile = level->getTile(testX, y, testZ); - if (tile == Tile::endPortalFrameTile->id) - { - int data = level->getData(testX, y, testZ); - if (!TheEndPortalFrameTile::hasEye(data)) - { - valid = false; - break; - } - max = offset; - if (!firstFound) - { - min = offset; - firstFound = true; - } - } - } - - // got a full frame? - if (valid && max == min + 2) - { - - // check if other edge is valid - for (int offset = min; offset <= max; offset++) - { - int testX = x + Direction::STEP_X[rightHandDirection] * offset; - int testZ = z + Direction::STEP_Z[rightHandDirection] * offset; - testX += Direction::STEP_X[direction] * 4; - testZ += Direction::STEP_Z[direction] * 4; - - int tile = level->getTile(testX, y, testZ); - int data = level->getData(testX, y, testZ); - if (tile != Tile::endPortalFrameTile_Id || !TheEndPortalFrameTile::hasEye(data)) - { - valid = false; - break; - } - } - // check if edges on the sides are valid - for (int side = (min - 1); side <= (max + 1); side += 4) - { - for (int offset = 1; offset <= 3; offset++) - { - int testX = x + Direction::STEP_X[rightHandDirection] * side; - int testZ = z + Direction::STEP_Z[rightHandDirection] * side; - testX += Direction::STEP_X[direction] * offset; - testZ += Direction::STEP_Z[direction] * offset; - - int tile = level->getTile(testX, y, testZ); - int data = level->getData(testX, y, testZ); - if (tile != Tile::endPortalFrameTile_Id || !TheEndPortalFrameTile::hasEye(data)) - { - valid = false; - break; - } - } - } - if (valid) - { - - // fill portal - for (int px = min; px <= max; px++) - { - for (int pz = 1; pz <= 3; pz++) - { - int targetX = x + Direction::STEP_X[rightHandDirection] * px; - int targetZ = z + Direction::STEP_Z[rightHandDirection] * px; - targetX += Direction::STEP_X[direction] * pz; - targetZ += Direction::STEP_Z[direction] * pz; - - level->setTile(targetX, y, targetZ, Tile::endPortalTile_Id); - } - } - } - } - - return true; - } - return false; + // if (!level->isClientSide) + { + if ((level->dimension->id == LevelData::DIMENSION_OVERWORLD) && + level->getLevelData()->getHasStronghold()) { + return true; + } else { + // int x,z; + // if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) + // { + // level->getLevelData()->setXStronghold(x); + // level->getLevelData()->setZStronghold(z); + // level->getLevelData()->setHasStronghold(); + // + // app.DebugPrintf("=== FOUND stronghold in + // terrain features list\n"); + // + // app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_StrongholdPosition); + // } + // else + { + // can't find the stronghold position in the terrain feature + // list. Do we have to run a post-process? + app.DebugPrintf( + "=== Can't find stronghold in terrain features list\n"); + } + } + // TilePos *nearestMapFeature = + // level->findNearestMapFeature(LargeFeature::STRONGHOLD, (int) + // player->x, (int) player->y, (int) player->z); if (nearestMapFeature + // != NULL) + // { + // delete nearestMapFeature; + // return true; + // } + } + return false; } -bool EnderEyeItem::TestUse(Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, false); - if (hr != NULL && hr->type == HitResult::TILE) - { - int tile = level->getTile(hr->x, hr->y, hr->z); - delete hr; - if (tile == Tile::endPortalFrameTile_Id) - { - return false; - } - } - else if( hr != NULL ) - { - delete hr; - } +std::shared_ptr EnderEyeItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, false); + if (hr != NULL && hr->type == HitResult::TILE) { + int tile = level->getTile(hr->x, hr->y, hr->z); + delete hr; + if (tile == Tile::endPortalFrameTile_Id) { + return instance; + } + } else if (hr != NULL) { + delete hr; + } - //if (!level->isClientSide) - { - if((level->dimension->id==LevelData::DIMENSION_OVERWORLD) && level->getLevelData()->getHasStronghold()) - { - return true; - } - else - { -// int x,z; -// if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) -// { -// level->getLevelData()->setXStronghold(x); -// level->getLevelData()->setZStronghold(z); -// level->getLevelData()->setHasStronghold(); -// -// app.DebugPrintf("=== FOUND stronghold in terrain features list\n"); -// -// app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_StrongholdPosition); -// } -// else - { - // can't find the stronghold position in the terrain feature list. Do we have to run a post-process? - app.DebugPrintf("=== Can't find stronghold in terrain features list\n"); - } + if (!level->isClientSide) { + if ((level->dimension->id == LevelData::DIMENSION_OVERWORLD) && + level->getLevelData()->getHasStronghold()) { + std::shared_ptr eyeOfEnderSignal = + std::shared_ptr(new EyeOfEnderSignal( + level, player->x, player->y + 1.62 - player->heightOffset, + player->z)); + eyeOfEnderSignal->signalTo( + level->getLevelData()->getXStronghold() << 4, + player->y + 1.62 - player->heightOffset, + level->getLevelData()->getZStronghold() << 4); + level->addEntity(eyeOfEnderSignal); - } -// TilePos *nearestMapFeature = level->findNearestMapFeature(LargeFeature::STRONGHOLD, (int) player->x, (int) player->y, (int) player->z); -// if (nearestMapFeature != NULL) -// { -// delete nearestMapFeature; -// return true; -// } - } - return false; -} + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + level->levelEvent(nullptr, LevelEvent::SOUND_LAUNCH, (int)player->x, + (int)player->y, (int)player->z, 0); + if (!player->abilities.instabuild) { + instance->count--; + } + } -std::shared_ptr EnderEyeItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, false); - if (hr != NULL && hr->type == HitResult::TILE) - { - int tile = level->getTile(hr->x, hr->y, hr->z); - delete hr; - if (tile == Tile::endPortalFrameTile_Id) - { - return instance; - } - } - else if( hr != NULL ) - { - delete hr; - } + /*TilePos *nearestMapFeature = + level->findNearestMapFeature(LargeFeature::STRONGHOLD, (int) player->x, + (int) player->y, (int) player->z); if (nearestMapFeature != NULL) + { + std::shared_ptr eyeOfEnderSignal = + std::shared_ptr( new EyeOfEnderSignal(level, + player->x, player->y + 1.62 - player->heightOffset, player->z) ); + eyeOfEnderSignal->signalTo(nearestMapFeature->x, + nearestMapFeature->y, nearestMapFeature->z); delete nearestMapFeature; + level->addEntity(eyeOfEnderSignal); - if (!level->isClientSide) - { - if((level->dimension->id==LevelData::DIMENSION_OVERWORLD) && level->getLevelData()->getHasStronghold()) - { - std::shared_ptr eyeOfEnderSignal = std::shared_ptr( new EyeOfEnderSignal(level, player->x, player->y + 1.62 - player->heightOffset, player->z) ); - eyeOfEnderSignal->signalTo(level->getLevelData()->getXStronghold()<<4, player->y + 1.62 - player->heightOffset, level->getLevelData()->getZStronghold()<<4); - level->addEntity(eyeOfEnderSignal); - - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - level->levelEvent(nullptr, LevelEvent::SOUND_LAUNCH, (int) player->x, (int) player->y, (int) player->z, 0); - if (!player->abilities.instabuild) - { - instance->count--; - } - } - - /*TilePos *nearestMapFeature = level->findNearestMapFeature(LargeFeature::STRONGHOLD, (int) player->x, (int) player->y, (int) player->z); - if (nearestMapFeature != NULL) - { - std::shared_ptr eyeOfEnderSignal = std::shared_ptr( new EyeOfEnderSignal(level, player->x, player->y + 1.62 - player->heightOffset, player->z) ); - eyeOfEnderSignal->signalTo(nearestMapFeature->x, nearestMapFeature->y, nearestMapFeature->z); - delete nearestMapFeature; - level->addEntity(eyeOfEnderSignal); - - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - level->levelEvent(NULL, LevelEvent::SOUND_LAUNCH, (int) player->x, (int) player->y, (int) player->z, 0); - if (!player->abilities.instabuild) - { - instance->count--; - } - }*/ - } - return instance; + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / + (random->nextFloat() * 0.4f + 0.8f)); level->levelEvent(NULL, + LevelEvent::SOUND_LAUNCH, (int) player->x, (int) player->y, (int) + player->z, 0); if (!player->abilities.instabuild) + { + instance->count--; + } + }*/ + } + return instance; } \ No newline at end of file diff --git a/Minecraft.World/Items/EnderEyeItem.h b/Minecraft.World/Items/EnderEyeItem.h index cbe56cfb1..162879445 100644 --- a/Minecraft.World/Items/EnderEyeItem.h +++ b/Minecraft.World/Items/EnderEyeItem.h @@ -2,12 +2,16 @@ #include "Item.h" -class EnderEyeItem : public Item -{ +class EnderEyeItem : public Item { public: - EnderEyeItem(int id); + EnderEyeItem(int id); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/EnderPearlItem.cpp b/Minecraft.World/Items/EnderPearlItem.cpp index 797d98b1c..ee6dd7b60 100644 --- a/Minecraft.World/Items/EnderPearlItem.cpp +++ b/Minecraft.World/Items/EnderPearlItem.cpp @@ -5,30 +5,28 @@ #include "EnderPearlItem.h" #include "../Util/SoundTypes.h" -EnderpearlItem::EnderpearlItem(int id) : Item(id) -{ - this->maxStackSize = 16; +EnderpearlItem::EnderpearlItem(int id) : Item(id) { this->maxStackSize = 16; } + +bool EnderpearlItem::TestUse(Level* level, std::shared_ptr player) { + return true; } -bool EnderpearlItem::TestUse(Level *level, std::shared_ptr player) -{ - return true; -} +std::shared_ptr EnderpearlItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + // 4J-PB - Not sure why this was disabled for creative mode, so commenting + // out + // if (player->abilities.instabuild) return instance; + if (player->riding != NULL) return instance; + if (!player->abilities.instabuild) { + instance->count--; + } -std::shared_ptr EnderpearlItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - // 4J-PB - Not sure why this was disabled for creative mode, so commenting out - //if (player->abilities.instabuild) return instance; - if (player->riding != NULL) return instance; - if (!player->abilities.instabuild) - { - instance->count--; - } - - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) - { - level->addEntity( std::shared_ptr( new ThrownEnderpearl(level, player) ) ); - } - return instance; + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) { + level->addEntity(std::shared_ptr( + new ThrownEnderpearl(level, player))); + } + return instance; } \ No newline at end of file diff --git a/Minecraft.World/Items/EnderPearlItem.h b/Minecraft.World/Items/EnderPearlItem.h index 5dbcb619d..f0681faa9 100644 --- a/Minecraft.World/Items/EnderPearlItem.h +++ b/Minecraft.World/Items/EnderPearlItem.h @@ -2,12 +2,13 @@ #include "Item.h" -class EnderpearlItem : public Item -{ +class EnderpearlItem : public Item { public: - EnderpearlItem(int id); + EnderpearlItem(int id); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); - // 4J added - virtual bool TestUse(Level *level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + // 4J added + virtual bool TestUse(Level* level, std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/ExperienceItem.cpp b/Minecraft.World/Items/ExperienceItem.cpp index 201f5babb..891cb5884 100644 --- a/Minecraft.World/Items/ExperienceItem.cpp +++ b/Minecraft.World/Items/ExperienceItem.cpp @@ -6,27 +6,26 @@ #include "../Util/SoundTypes.h" #include "ExperienceItem.h" -ExperienceItem::ExperienceItem(int id) : Item(id) -{ +ExperienceItem::ExperienceItem(int id) : Item(id) {} + +bool ExperienceItem::isFoil(std::shared_ptr itemInstance) { + return true; } -bool ExperienceItem::isFoil(std::shared_ptr itemInstance) -{ - return true; +bool ExperienceItem::TestUse(Level* level, std::shared_ptr player) { + return true; } -bool ExperienceItem::TestUse(Level *level, std::shared_ptr player) -{ - return true; -} - -std::shared_ptr ExperienceItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) level->addEntity( std::shared_ptr( new ThrownExpBottle(level, player) )); - return itemInstance; +std::shared_ptr ExperienceItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + if (!player->abilities.instabuild) { + itemInstance->count--; + } + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) + level->addEntity(std::shared_ptr( + new ThrownExpBottle(level, player))); + return itemInstance; } \ No newline at end of file diff --git a/Minecraft.World/Items/ExperienceItem.h b/Minecraft.World/Items/ExperienceItem.h index c0d18dcf7..e1660cdba 100644 --- a/Minecraft.World/Items/ExperienceItem.h +++ b/Minecraft.World/Items/ExperienceItem.h @@ -4,12 +4,13 @@ class ItemInstance; -class ExperienceItem : public Item -{ +class ExperienceItem : public Item { public: - ExperienceItem(int id); + ExperienceItem(int id); - virtual bool isFoil(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual bool TestUse(Level *level, std::shared_ptr player); + virtual bool isFoil(std::shared_ptr itemInstance); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); + virtual bool TestUse(Level* level, std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/FireChargeItem.cpp b/Minecraft.World/Items/FireChargeItem.cpp index 44b550e5c..d23c46cdc 100644 --- a/Minecraft.World/Items/FireChargeItem.cpp +++ b/Minecraft.World/Items/FireChargeItem.cpp @@ -8,60 +8,54 @@ #include "FireChargeItem.h" #include "../Blocks/Tile.h" -FireChargeItem::FireChargeItem(int id) : Item(id) -{ - m_dragonFireballIcon = NULL; +FireChargeItem::FireChargeItem(int id) : Item(id) { + m_dragonFireballIcon = NULL; } -bool FireChargeItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (level->isClientSide) - { - return true; - } +bool FireChargeItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + if (level->isClientSide) { + return true; + } - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - if (!player->mayBuild(x, y, z)) - { - return false; - } + if (!player->mayBuild(x, y, z)) { + return false; + } - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(bTestUseOnOnly) - { - return true; - } + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (bTestUseOnOnly) { + return true; + } - int targetType = level->getTile(x, y, z); + int targetType = level->getTile(x, y, z); - if (targetType == 0) - { - level->playSound( x + 0.5, y + 0.5, z + 0.5,eSoundType_FIRE_IGNITE, 1, random->nextFloat() * 0.4f + 0.8f); - level->setTile(x, y, z, Tile::fire_Id); - } + if (targetType == 0) { + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_FIRE_IGNITE, 1, + random->nextFloat() * 0.4f + 0.8f); + level->setTile(x, y, z, Tile::fire_Id); + } - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - return true; + if (!player->abilities.instabuild) { + itemInstance->count--; + } + return true; } -Icon *FireChargeItem::getIcon(int itemAuxValue) -{ - if(itemAuxValue > 0) return m_dragonFireballIcon; - return Item::getIcon(itemAuxValue); +Icon* FireChargeItem::getIcon(int itemAuxValue) { + if (itemAuxValue > 0) return m_dragonFireballIcon; + return Item::getIcon(itemAuxValue); } -void FireChargeItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - m_dragonFireballIcon = iconRegister->registerIcon(L"dragonFireball"); +void FireChargeItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); + m_dragonFireballIcon = iconRegister->registerIcon(L"dragonFireball"); } - diff --git a/Minecraft.World/Items/FireChargeItem.h b/Minecraft.World/Items/FireChargeItem.h index 440222b4d..1efb9c1cc 100644 --- a/Minecraft.World/Items/FireChargeItem.h +++ b/Minecraft.World/Items/FireChargeItem.h @@ -6,15 +6,18 @@ class ItemInstance; class Player; class Level; -class FireChargeItem : public Item -{ +class FireChargeItem : public Item { private: - Icon *m_dragonFireballIcon; + Icon* m_dragonFireballIcon; + public: - FireChargeItem(int id); + FireChargeItem(int id); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly); - virtual Icon *getIcon(int itemAuxValue); - virtual void registerIcons(IconRegister *iconRegister); + virtual Icon* getIcon(int itemAuxValue); + virtual void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/FishingRodItem.cpp b/Minecraft.World/Items/FishingRodItem.cpp index 8221c67bb..818aed1f3 100644 --- a/Minecraft.World/Items/FishingRodItem.cpp +++ b/Minecraft.World/Items/FishingRodItem.cpp @@ -15,53 +15,42 @@ const std::wstring FishingRodItem::TEXTURE_EMPTY = L"fishingRod_empty"; -FishingRodItem::FishingRodItem(int id) : Item(id) -{ - setMaxDamage(64); - setMaxStackSize(1); - emptyIcon = NULL; +FishingRodItem::FishingRodItem(int id) : Item(id) { + setMaxDamage(64); + setMaxStackSize(1); + emptyIcon = NULL; } -bool FishingRodItem::isHandEquipped() -{ - return true; +bool FishingRodItem::isHandEquipped() { return true; } + +bool FishingRodItem::isMirroredArt() { return true; } + +std::shared_ptr FishingRodItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (player->fishing != NULL) { + int dmg = player->fishing->retrieve(); + instance->hurt(dmg, player); + player->swing(); + } else { + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) { + // 4J Stu - Move the player->fishing out of the ctor as we cannot + // reference 'this' + std::shared_ptr hook = + std::shared_ptr(new FishingHook(level, player)); + player->fishing = hook; + level->addEntity(std::shared_ptr(hook)); + } + player->swing(); + } + return instance; } -bool FishingRodItem::isMirroredArt() -{ - return true; +void FishingRodItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); + emptyIcon = iconRegister->registerIcon(TEXTURE_EMPTY); } -std::shared_ptr FishingRodItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (player->fishing != NULL) - { - int dmg = player->fishing->retrieve(); - instance->hurt(dmg, player); - player->swing(); - } - else - { - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) - { - // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' - std::shared_ptr hook = std::shared_ptr( new FishingHook(level, player) ); - player->fishing = hook; - level->addEntity( std::shared_ptr( hook ) ); - } - player->swing(); - } - return instance; -} - -void FishingRodItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - emptyIcon = iconRegister->registerIcon(TEXTURE_EMPTY); -} - -Icon *FishingRodItem::getEmptyIcon() -{ - return emptyIcon; -} +Icon* FishingRodItem::getEmptyIcon() { return emptyIcon; } diff --git a/Minecraft.World/Items/FishingRodItem.h b/Minecraft.World/Items/FishingRodItem.h index 4d6ce184e..4a71bcc9d 100644 --- a/Minecraft.World/Items/FishingRodItem.h +++ b/Minecraft.World/Items/FishingRodItem.h @@ -1,27 +1,27 @@ #pragma once - #include "Item.h" class Player; class Level; -class FishingRodItem : public Item -{ +class FishingRodItem : public Item { public: - static const std::wstring TEXTURE_EMPTY; + static const std::wstring TEXTURE_EMPTY; private: - Icon *emptyIcon; + Icon* emptyIcon; public: - FishingRodItem(int id); + FishingRodItem(int id); - virtual bool isHandEquipped(); - virtual bool isMirroredArt(); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual bool isHandEquipped(); + virtual bool isMirroredArt(); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); - //@Override - void registerIcons(IconRegister *iconRegister); - Icon *getEmptyIcon(); + //@Override + void registerIcons(IconRegister* iconRegister); + Icon* getEmptyIcon(); }; diff --git a/Minecraft.World/Items/FlintAndSteelItem.cpp b/Minecraft.World/Items/FlintAndSteelItem.cpp index 68e18821a..b4d4dc48a 100644 --- a/Minecraft.World/Items/FlintAndSteelItem.cpp +++ b/Minecraft.World/Items/FlintAndSteelItem.cpp @@ -9,64 +9,57 @@ #include "FlintAndSteelItem.h" #include "../Util/SoundTypes.h" -FlintAndSteelItem::FlintAndSteelItem(int id) : Item( id ) -{ - maxStackSize = 1; - setMaxDamage(64); +FlintAndSteelItem::FlintAndSteelItem(int id) : Item(id) { + maxStackSize = 1; + setMaxDamage(64); } -bool FlintAndSteelItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - - if (!player->mayBuild(x, y, z)) return false; +bool FlintAndSteelItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, + int x, int y, int z, int face, float clickX, + float clickY, float clickZ, bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - int targetType = level->getTile(x, y, z); + if (!player->mayBuild(x, y, z)) return false; - if(!bTestUseOnOnly) - { - if (targetType == 0) - { - if( level->getTile(x, y-1, z) == Tile::obsidian_Id ) - { - if( Tile::portalTile->trySpawnPortal(level, x, y, z, false) ) - { - player->awardStat( - GenericStats::portalsCreated(), - GenericStats::param_noArgs() - ); + int targetType = level->getTile(x, y, z); - // 4J : WESTY : Added for achievement. - player->awardStat(GenericStats::InToTheNether(),GenericStats::param_InToTheNether()); - } - } + if (!bTestUseOnOnly) { + if (targetType == 0) { + if (level->getTile(x, y - 1, z) == Tile::obsidian_Id) { + if (Tile::portalTile->trySpawnPortal(level, x, y, z, false)) { + player->awardStat(GenericStats::portalsCreated(), + GenericStats::param_noArgs()); - level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_FIRE_IGNITE, 1, random->nextFloat() * 0.4f + 0.8f); - level->setTile(x, y, z, Tile::fire_Id); - } + // 4J : WESTY : Added for achievement. + player->awardStat(GenericStats::InToTheNether(), + GenericStats::param_InToTheNether()); + } + } - instance->hurt(1, player); - } - else - { - if(targetType == 0) - { - return true; - } - else - { - return false; - } - } + level->playSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_FIRE_IGNITE, + 1, random->nextFloat() * 0.4f + 0.8f); + level->setTile(x, y, z, Tile::fire_Id); + } - // 4J-PB - this function shouldn't really return true all the time, but I've added a special case for my test use for the tooltips display - // and will leave it as is for the game use + instance->hurt(1, player); + } else { + if (targetType == 0) { + return true; + } else { + return false; + } + } - return true; + // 4J-PB - this function shouldn't really return true all the time, but I've + // added a special case for my test use for the tooltips display and will + // leave it as is for the game use + + return true; } diff --git a/Minecraft.World/Items/FlintAndSteelItem.h b/Minecraft.World/Items/FlintAndSteelItem.h index d8ddce651..591f44ab4 100644 --- a/Minecraft.World/Items/FlintAndSteelItem.h +++ b/Minecraft.World/Items/FlintAndSteelItem.h @@ -5,10 +5,12 @@ class Player; class Level; -class FlintAndSteelItem : public Item -{ +class FlintAndSteelItem : public Item { public: - FlintAndSteelItem(int id); + FlintAndSteelItem(int id); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; diff --git a/Minecraft.World/Items/FoodItem.cpp b/Minecraft.World/Items/FoodItem.cpp index 3f6a0f4ba..520fa2c77 100644 --- a/Minecraft.World/Items/FoodItem.cpp +++ b/Minecraft.World/Items/FoodItem.cpp @@ -11,110 +11,103 @@ // 4J : WESTY : Other award ... eating cooked pork chop. #include "../Headers/net.minecraft.stats.h" -void FoodItem::_init() -{ - // 4J Initialisers - canAlwaysEat = false; - effectId = 0; - effectDurationSeconds = 0; - effectAmplifier = 0; - effectProbability = 0.0f; +void FoodItem::_init() { + // 4J Initialisers + canAlwaysEat = false; + effectId = 0; + effectDurationSeconds = 0; + effectAmplifier = 0; + effectProbability = 0.0f; } FoodItem::FoodItem(int id, int nutrition, float saturationMod, bool isMeat) - : Item( id ), nutrition(nutrition), saturationModifier( saturationMod ), m_isMeat( isMeat ) -{ - _init(); + : Item(id), + nutrition(nutrition), + saturationModifier(saturationMod), + m_isMeat(isMeat) { + _init(); } FoodItem::FoodItem(int id, int nutrition, bool isMeat) - : Item( id ), nutrition(nutrition), saturationModifier( FoodConstants::FOOD_SATURATION_NORMAL ), m_isMeat( isMeat ) -{ - _init(); + : Item(id), + nutrition(nutrition), + saturationModifier(FoodConstants::FOOD_SATURATION_NORMAL), + m_isMeat(isMeat) { + _init(); } -std::shared_ptr FoodItem::useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - instance->count--; - player->getFoodData()->eat(this); - // 4J - new sound brought forward from 1.2.3 - level->playSound(player, eSoundType_RANDOM_BURP, 0.5f, level->random->nextFloat() * 0.1f + 0.9f); +std::shared_ptr FoodItem::useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + instance->count--; + player->getFoodData()->eat(this); + // 4J - new sound brought forward from 1.2.3 + level->playSound(player, eSoundType_RANDOM_BURP, 0.5f, + level->random->nextFloat() * 0.1f + 0.9f); - addEatEffect(instance, level, player); + addEatEffect(instance, level, player); - return instance; + return instance; } -void FoodItem::addEatEffect(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (!level->isClientSide && effectId > 0 && level->random->nextFloat() < effectProbability) - { - player->addEffect(new MobEffectInstance(effectId, effectDurationSeconds * SharedConstants::TICKS_PER_SECOND, effectAmplifier)); - } - +void FoodItem::addEatEffect(std::shared_ptr instance, + Level* level, std::shared_ptr player) { + if (!level->isClientSide && effectId > 0 && + level->random->nextFloat() < effectProbability) { + player->addEffect(new MobEffectInstance( + effectId, effectDurationSeconds * SharedConstants::TICKS_PER_SECOND, + effectAmplifier)); + } } -int FoodItem::getUseDuration(std::shared_ptr itemInstance) -{ - return EAT_DURATION; +int FoodItem::getUseDuration(std::shared_ptr itemInstance) { + return EAT_DURATION; } -UseAnim FoodItem::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_eat; +UseAnim FoodItem::getUseAnimation(std::shared_ptr itemInstance) { + return UseAnim_eat; } -std::shared_ptr FoodItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (player->canEat(canAlwaysEat)) - { - player->startUsingItem(instance, getUseDuration(instance)); - } +std::shared_ptr FoodItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (player->canEat(canAlwaysEat)) { + player->startUsingItem(instance, getUseDuration(instance)); + } - // 4J : WESTY : Other award ... eating cooked pork chop. - // 4J-JEV: This is just for an avatar award on the xbox. -#ifdef _XBOX - if ( instance->getItem() == Item::porkChop_cooked ) - { - player->awardStat(GenericStats::eatPorkChop(),GenericStats::param_eatPorkChop()); - } + // 4J : WESTY : Other award ... eating cooked pork chop. + // 4J-JEV: This is just for an avatar award on the xbox. +#ifdef _XBOX + if (instance->getItem() == Item::porkChop_cooked) { + player->awardStat(GenericStats::eatPorkChop(), + GenericStats::param_eatPorkChop()); + } #endif - return instance; + return instance; } -float FoodItem::getSaturationModifier() -{ - return saturationModifier; +float FoodItem::getSaturationModifier() { return saturationModifier; } + +int FoodItem::getNutrition() { return nutrition; } + +bool FoodItem::isMeat() { return m_isMeat; } + +FoodItem* FoodItem::setEatEffect(int id, int durationInSecods, int amplifier, + float effectProbability) { + effectId = id; + effectDurationSeconds = durationInSecods; + effectAmplifier = amplifier; + this->effectProbability = effectProbability; + return this; } -int FoodItem::getNutrition() -{ - return nutrition; -} - -bool FoodItem::isMeat() -{ - return m_isMeat; -} - -FoodItem *FoodItem::setEatEffect(int id, int durationInSecods, int amplifier, float effectProbability) -{ - effectId = id; - effectDurationSeconds = durationInSecods; - effectAmplifier = amplifier; - this->effectProbability = effectProbability; - return this; -} - -FoodItem *FoodItem::setCanAlwaysEat() -{ - canAlwaysEat = true; - return this; +FoodItem* FoodItem::setCanAlwaysEat() { + canAlwaysEat = true; + return this; } // 4J Added -bool FoodItem::canEat(std::shared_ptr player) -{ - return player->canEat(canAlwaysEat); +bool FoodItem::canEat(std::shared_ptr player) { + return player->canEat(canAlwaysEat); } diff --git a/Minecraft.World/Items/FoodItem.h b/Minecraft.World/Items/FoodItem.h index 2100a3b3e..35b8cfdac 100644 --- a/Minecraft.World/Items/FoodItem.h +++ b/Minecraft.World/Items/FoodItem.h @@ -5,45 +5,51 @@ class Player; class Level; -class FoodItem : public Item -{ +class FoodItem : public Item { public: - static const int EAT_DURATION = (int) (20 * 1.6); + static const int EAT_DURATION = (int)(20 * 1.6); private: - const int nutrition; - const float saturationModifier; - const bool m_isMeat; - bool canAlwaysEat; + const int nutrition; + const float saturationModifier; + const bool m_isMeat; + bool canAlwaysEat; - int effectId; - int effectDurationSeconds; - int effectAmplifier; - float effectProbability; + int effectId; + int effectDurationSeconds; + int effectAmplifier; + float effectProbability; + + void _init(); - void _init(); public: - FoodItem(int id, int nutrition, float saturationMod, bool isMeat); - FoodItem(int id, int nutrition, bool isMeat); + FoodItem(int id, int nutrition, float saturationMod, bool isMeat); + FoodItem(int id, int nutrition, bool isMeat); - virtual std::shared_ptr useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual std::shared_ptr useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player); protected: - virtual void addEatEffect(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual void addEatEffect(std::shared_ptr instance, + Level* level, std::shared_ptr player); public: - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); - int getNutrition(); - float getSaturationModifier(); - bool isMeat(); + int getNutrition(); + float getSaturationModifier(); + bool isMeat(); - FoodItem *setEatEffect(int id, int durationInSecods, int amplifier, float effectProbability); - FoodItem *setCanAlwaysEat(); + FoodItem* setEatEffect(int id, int durationInSecods, int amplifier, + float effectProbability); + FoodItem* setCanAlwaysEat(); - // 4J Added - bool canEat(std::shared_ptr player); + // 4J Added + bool canEat(std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/GoldenAppleItem.cpp b/Minecraft.World/Items/GoldenAppleItem.cpp index aa9bddc55..77e8efbb9 100644 --- a/Minecraft.World/Items/GoldenAppleItem.cpp +++ b/Minecraft.World/Items/GoldenAppleItem.cpp @@ -5,49 +5,52 @@ #include "../Util/SharedConstants.h" #include "GoldenAppleItem.h" -GoldenAppleItem::GoldenAppleItem(int id, int nutrition, float saturationMod, bool isMeat) : FoodItem(id, nutrition, saturationMod, isMeat) -{ - setStackedByData(true); +GoldenAppleItem::GoldenAppleItem(int id, int nutrition, float saturationMod, + bool isMeat) + : FoodItem(id, nutrition, saturationMod, isMeat) { + setStackedByData(true); } -bool GoldenAppleItem::isFoil(std::shared_ptr itemInstance) -{ - return itemInstance->getAuxValue() > 0; +bool GoldenAppleItem::isFoil(std::shared_ptr itemInstance) { + return itemInstance->getAuxValue() > 0; } -const Rarity *GoldenAppleItem::getRarity(std::shared_ptr itemInstance) -{ - if (itemInstance->getAuxValue() == 0) - { - return Rarity::rare; - } - return Rarity::epic; +const Rarity* GoldenAppleItem::getRarity( + std::shared_ptr itemInstance) { + if (itemInstance->getAuxValue() == 0) { + return Rarity::rare; + } + return Rarity::epic; } -void GoldenAppleItem::addEatEffect(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (instance->getAuxValue() > 0) - { - if (!level->isClientSide) - { - player->addEffect(new MobEffectInstance(MobEffect::regeneration->id, 30 * SharedConstants::TICKS_PER_SECOND, 3)); - player->addEffect(new MobEffectInstance(MobEffect::damageResistance->id, 300 * SharedConstants::TICKS_PER_SECOND, 0)); - player->addEffect(new MobEffectInstance(MobEffect::fireResistance->id, 300 * SharedConstants::TICKS_PER_SECOND, 0)); - } - } - else - { - FoodItem::addEatEffect(instance, level, player); - } +void GoldenAppleItem::addEatEffect(std::shared_ptr instance, + Level* level, + std::shared_ptr player) { + if (instance->getAuxValue() > 0) { + if (!level->isClientSide) { + player->addEffect(new MobEffectInstance( + MobEffect::regeneration->id, + 30 * SharedConstants::TICKS_PER_SECOND, 3)); + player->addEffect(new MobEffectInstance( + MobEffect::damageResistance->id, + 300 * SharedConstants::TICKS_PER_SECOND, 0)); + player->addEffect(new MobEffectInstance( + MobEffect::fireResistance->id, + 300 * SharedConstants::TICKS_PER_SECOND, 0)); + } + } else { + FoodItem::addEatEffect(instance, level, player); + } } -unsigned int GoldenAppleItem::getUseDescriptionId(int iData /*= -1*/) -{ - if (iData == 0) return IDS_DESC_GOLDENAPPLE; - else return IDS_DESC_ENCHANTED_GOLDENAPPLE; +unsigned int GoldenAppleItem::getUseDescriptionId(int iData /*= -1*/) { + if (iData == 0) + return IDS_DESC_GOLDENAPPLE; + else + return IDS_DESC_ENCHANTED_GOLDENAPPLE; } -unsigned int GoldenAppleItem::getUseDescriptionId(std::shared_ptr instance) -{ - return this->getUseDescriptionId(instance->getAuxValue()); +unsigned int GoldenAppleItem::getUseDescriptionId( + std::shared_ptr instance) { + return this->getUseDescriptionId(instance->getAuxValue()); } \ No newline at end of file diff --git a/Minecraft.World/Items/GoldenAppleItem.h b/Minecraft.World/Items/GoldenAppleItem.h index 052fcb49f..24f91fd36 100644 --- a/Minecraft.World/Items/GoldenAppleItem.h +++ b/Minecraft.World/Items/GoldenAppleItem.h @@ -2,20 +2,22 @@ #include "FoodItem.h" -class GoldenAppleItem : public FoodItem -{ +class GoldenAppleItem : public FoodItem { public: - using Item::getUseDescriptionId; + using Item::getUseDescriptionId; - GoldenAppleItem(int id, int nutrition, float saturationMod, bool isMeat); + GoldenAppleItem(int id, int nutrition, float saturationMod, bool isMeat); - virtual bool isFoil(std::shared_ptr itemInstance); - virtual const Rarity *getRarity(std::shared_ptr itemInstance); + virtual bool isFoil(std::shared_ptr itemInstance); + virtual const Rarity* getRarity(std::shared_ptr itemInstance); - // 4J-JEV: Enchanted goldenapples and goldenapples each require their own tooltips. - virtual unsigned int getUseDescriptionId(int iData /*= -1*/); - virtual unsigned int getUseDescriptionId(std::shared_ptr instance); + // 4J-JEV: Enchanted goldenapples and goldenapples each require their own + // tooltips. + virtual unsigned int getUseDescriptionId(int iData /*= -1*/); + virtual unsigned int getUseDescriptionId( + std::shared_ptr instance); protected: - void addEatEffect(std::shared_ptr instance, Level *level, std::shared_ptr player); + void addEatEffect(std::shared_ptr instance, Level* level, + std::shared_ptr player); }; diff --git a/Minecraft.World/Items/HangingEntityItem.cpp b/Minecraft.World/Items/HangingEntityItem.cpp index 3d22a8557..baf1571b7 100644 --- a/Minecraft.World/Items/HangingEntityItem.cpp +++ b/Minecraft.World/Items/HangingEntityItem.cpp @@ -10,79 +10,77 @@ #include "../Stats/GenericStats.h" #include "../Entities/Mobs/ItemFrame.h" - -HangingEntityItem::HangingEntityItem(int id, eINSTANCEOF eClassType) : Item(id) -{ - //super(id); - //this.clazz = clazz; - this->eType=eClassType; - // setItemCategory(CreativeModeTab.TAB_DECORATIONS); +HangingEntityItem::HangingEntityItem(int id, eINSTANCEOF eClassType) + : Item(id) { + // super(id); + // this.clazz = clazz; + this->eType = eClassType; + // setItemCategory(CreativeModeTab.TAB_DECORATIONS); } -bool HangingEntityItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int xt, int yt, int zt, int face, float clickX, float clickY, float clickZ, bool bTestOnly) -{ - if (face == Facing::DOWN) return false; - if (face == Facing::UP) return false; +bool HangingEntityItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, + int xt, int yt, int zt, int face, float clickX, + float clickY, float clickZ, bool bTestOnly) { + if (face == Facing::DOWN) return false; + if (face == Facing::UP) return false; - if(bTestOnly) - { - if (!player->mayBuild(xt, yt, zt)) return false; + if (bTestOnly) { + if (!player->mayBuild(xt, yt, zt)) return false; - return true; - } + return true; + } - int dir = Direction::FACING_DIRECTION[face]; + int dir = Direction::FACING_DIRECTION[face]; - std::shared_ptr entity = createEntity(level, xt, yt, zt, dir); + std::shared_ptr entity = + createEntity(level, xt, yt, zt, dir); - //if (!player->mayUseItemAt(xt, yt, zt, face, instance)) return false; - if (!player->mayBuild(xt, yt, zt)) return false; + // if (!player->mayUseItemAt(xt, yt, zt, face, instance)) return false; + if (!player->mayBuild(xt, yt, zt)) return false; - if (entity != NULL && entity->survives()) - { - if (!level->isClientSide) - { - if(level->addEntity(entity)==TRUE) - { - // 4J-JEV: Hook for durango 'BlockPlaced' event. - if (eType==eTYPE_PAINTING) player->awardStat(GenericStats::blocksPlaced(Item::painting_Id), GenericStats::param_blocksPlaced(Item::painting_Id,instance->getAuxValue(),1)); - else if (eType==eTYPE_ITEM_FRAME) player->awardStat(GenericStats::blocksPlaced(Item::itemFrame_Id), GenericStats::param_blocksPlaced(Item::itemFrame_Id,instance->getAuxValue(),1)); + if (entity != NULL && entity->survives()) { + if (!level->isClientSide) { + if (level->addEntity(entity) == TRUE) { + // 4J-JEV: Hook for durango 'BlockPlaced' event. + if (eType == eTYPE_PAINTING) + player->awardStat( + GenericStats::blocksPlaced(Item::painting_Id), + GenericStats::param_blocksPlaced( + Item::painting_Id, instance->getAuxValue(), 1)); + else if (eType == eTYPE_ITEM_FRAME) + player->awardStat( + GenericStats::blocksPlaced(Item::itemFrame_Id), + GenericStats::param_blocksPlaced( + Item::itemFrame_Id, instance->getAuxValue(), 1)); - instance->count--; - } - else - { - player->displayClientMessage(IDS_MAX_HANGINGENTITIES ); - return false; - } - } - else - { - instance->count--; - } - } - return true; + instance->count--; + } else { + player->displayClientMessage(IDS_MAX_HANGINGENTITIES); + return false; + } + } else { + instance->count--; + } + } + return true; } +std::shared_ptr HangingEntityItem::createEntity(Level* level, + int x, int y, + int z, int dir) { + if (eType == eTYPE_PAINTING) { + std::shared_ptr painting = + std::shared_ptr(new Painting(level, x, y, z, dir)); + painting->PaintingPostConstructor(dir); -std::shared_ptr HangingEntityItem::createEntity(Level *level, int x, int y, int z, int dir) -{ - if (eType == eTYPE_PAINTING) - { - std::shared_ptr painting = std::shared_ptr(new Painting(level, x, y, z, dir)); - painting->PaintingPostConstructor(dir); - - return std::dynamic_pointer_cast (painting); - } - else if (eType == eTYPE_ITEM_FRAME) - { - std::shared_ptr itemFrame = std::shared_ptr(new ItemFrame(level, x, y, z, dir)); + return std::dynamic_pointer_cast(painting); + } else if (eType == eTYPE_ITEM_FRAME) { + std::shared_ptr itemFrame = + std::shared_ptr(new ItemFrame(level, x, y, z, dir)); - return std::dynamic_pointer_cast (itemFrame); - } - else - { - return nullptr; - } + return std::dynamic_pointer_cast(itemFrame); + } else { + return nullptr; + } } - diff --git a/Minecraft.World/Items/HangingEntityItem.h b/Minecraft.World/Items/HangingEntityItem.h index 06bba50d0..ad48ecd2f 100644 --- a/Minecraft.World/Items/HangingEntityItem.h +++ b/Minecraft.World/Items/HangingEntityItem.h @@ -4,18 +4,21 @@ class HangingEntity; -class HangingEntityItem : public Item -{ +class HangingEntityItem : public Item { private: - //final Class clazz; - eINSTANCEOF eType; + // final Class clazz; + eINSTANCEOF eType; public: - HangingEntityItem(int id, eINSTANCEOF eClassType); + HangingEntityItem(int id, eINSTANCEOF eClassType); + + virtual bool useOn( + std::shared_ptr instance, std::shared_ptr player, + Level* level, int xt, int yt, int zt, int face, float clickX, + float clickY, float clickZ, + bool bTestUseOnOnly); //, float clickX, float clickY, float clickZ); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int xt, int yt, int zt, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly);//, float clickX, float clickY, float clickZ); - private: - std::shared_ptr createEntity(Level *level, int x, int y, int z, int dir) ; - + std::shared_ptr createEntity(Level* level, int x, int y, + int z, int dir); }; diff --git a/Minecraft.World/Items/HatchetItem.cpp b/Minecraft.World/Items/HatchetItem.cpp index 02c425938..a4bb36c58 100644 --- a/Minecraft.World/Items/HatchetItem.cpp +++ b/Minecraft.World/Items/HatchetItem.cpp @@ -2,31 +2,28 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "HatchetItem.h" -TileArray *HatchetItem::diggables = NULL; +TileArray* HatchetItem::diggables = NULL; -void HatchetItem::staticCtor() -{ - HatchetItem::diggables = new TileArray( HATCHET_DIGGABLES); - diggables->data[0] = Tile::wood; - diggables->data[1] = Tile::bookshelf; - diggables->data[2] = Tile::treeTrunk; - diggables->data[3] = Tile::chest; - // 4J - brought forward from 1.2.3 - diggables->data[4] = Tile::stoneSlab; - diggables->data[5] = Tile::stoneSlabHalf; - diggables->data[6] = Tile::pumpkin; - diggables->data[7] = Tile::litPumpkin; +void HatchetItem::staticCtor() { + HatchetItem::diggables = new TileArray(HATCHET_DIGGABLES); + diggables->data[0] = Tile::wood; + diggables->data[1] = Tile::bookshelf; + diggables->data[2] = Tile::treeTrunk; + diggables->data[3] = Tile::chest; + // 4J - brought forward from 1.2.3 + diggables->data[4] = Tile::stoneSlab; + diggables->data[5] = Tile::stoneSlabHalf; + diggables->data[6] = Tile::pumpkin; + diggables->data[7] = Tile::litPumpkin; } -HatchetItem::HatchetItem(int id, const Tier *tier) : DiggerItem (id, 3, tier, diggables) -{ -} +HatchetItem::HatchetItem(int id, const Tier* tier) + : DiggerItem(id, 3, tier, diggables) {} // 4J - brought forward from 1.2.3 -float HatchetItem::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - if (tile != NULL && tile->material == Material::wood) - { +float HatchetItem::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + if (tile != NULL && tile->material == Material::wood) { return speed; } return DiggerItem::getDestroySpeed(itemInstance, tile); diff --git a/Minecraft.World/Items/HatchetItem.h b/Minecraft.World/Items/HatchetItem.h index 2959e38b1..a07918cf3 100644 --- a/Minecraft.World/Items/HatchetItem.h +++ b/Minecraft.World/Items/HatchetItem.h @@ -3,13 +3,14 @@ #include "DiggerItem.h" #define HATCHET_DIGGABLES 8 -class HatchetItem : public DiggerItem -{ +class HatchetItem : public DiggerItem { private: - static TileArray *diggables; + static TileArray* diggables; public: - static void staticCtor(); - HatchetItem(int id, const Tier *tier); - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); // 4J - brought forward from 1.2.3 + static void staticCtor(); + HatchetItem(int id, const Tier* tier); + virtual float getDestroySpeed( + std::shared_ptr itemInstance, + Tile* tile); // 4J - brought forward from 1.2.3 }; diff --git a/Minecraft.World/Items/HoeItem.cpp b/Minecraft.World/Items/HoeItem.cpp index bbb6e7f75..8e1e9f059 100644 --- a/Minecraft.World/Items/HoeItem.cpp +++ b/Minecraft.World/Items/HoeItem.cpp @@ -5,47 +5,44 @@ #include "ItemInstance.h" #include "HoeItem.h" -HoeItem::HoeItem(int id, const Tier *tier) : Item(id) -{ - this->tier = tier; - maxStackSize = 1; - setMaxDamage(tier->getUses()); +HoeItem::HoeItem(int id, const Tier* tier) : Item(id) { + this->tier = tier; + maxStackSize = 1; + setMaxDamage(tier->getUses()); } -bool HoeItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (!player->mayBuild(x, y, z)) return false; +bool HoeItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + if (!player->mayBuild(x, y, z)) return false; - // 4J-PB - Adding a test only version to allow tooltips to be displayed + // 4J-PB - Adding a test only version to allow tooltips to be displayed - int targetType = level->getTile(x, y, z); - // Material above = level.getMaterial(x, y + 1, z); - int above = level->getTile(x, y + 1, z); + int targetType = level->getTile(x, y, z); + // Material above = level.getMaterial(x, y + 1, z); + int above = level->getTile(x, y + 1, z); - // 4J-PB - missing parentheses - if (face != 0 && above == 0 && (targetType == Tile::grass_Id || targetType == Tile::dirt_Id)) - { - if(!bTestUseOnOnly) - { - Tile *tile = Tile::farmland; - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, tile->soundType->getStepSound(), (tile->soundType->getVolume() + 1) / 2, tile->soundType->getPitch() * 0.8f); + // 4J-PB - missing parentheses + if (face != 0 && above == 0 && + (targetType == Tile::grass_Id || targetType == Tile::dirt_Id)) { + if (!bTestUseOnOnly) { + Tile* tile = Tile::farmland; + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + tile->soundType->getStepSound(), + (tile->soundType->getVolume() + 1) / 2, + tile->soundType->getPitch() * 0.8f); - if (level->isClientSide) return true; - level->setTile(x, y, z, tile->id); - instance->hurt(1, player); - } - return true; - } + if (level->isClientSide) return true; + level->setTile(x, y, z, tile->id); + instance->hurt(1, player); + } + return true; + } - return false; + return false; } -bool HoeItem::isHandEquipped() -{ - return true; -} +bool HoeItem::isHandEquipped() { return true; } -const Item::Tier *HoeItem::getTier() -{ - return tier; -} +const Item::Tier* HoeItem::getTier() { return tier; } diff --git a/Minecraft.World/Items/HoeItem.h b/Minecraft.World/Items/HoeItem.h index b7405803d..11c24e2e4 100644 --- a/Minecraft.World/Items/HoeItem.h +++ b/Minecraft.World/Items/HoeItem.h @@ -1,19 +1,21 @@ #pragma once - #include "Item.h" class Player; -class HoeItem : public Item -{ +class HoeItem : public Item { protected: - const Tier *tier; + const Tier* tier; + public: - HoeItem(int id, const Tier *tier); + HoeItem(int id, const Tier* tier); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual bool isHandEquipped(); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual bool isHandEquipped(); - const Tier *getTier(); + const Tier* getTier(); }; \ No newline at end of file diff --git a/Minecraft.World/Items/Item.cpp b/Minecraft.World/Items/Item.cpp index f77644996..756d12afd 100644 --- a/Minecraft.World/Items/Item.cpp +++ b/Minecraft.World/Items/Item.cpp @@ -19,1092 +19,1684 @@ typedef Item::Tier _Tier; std::wstring Item::ICON_DESCRIPTION_PREFIX = L"item."; -const _Tier *_Tier::WOOD = new _Tier(0, 59, 2, 0, 15); // -const _Tier *_Tier::STONE = new _Tier(1, 131, 4, 1, 5); // -const _Tier *_Tier::IRON = new _Tier(2, 250, 6, 2, 14); // -const _Tier *_Tier::DIAMOND = new _Tier(3, 1561, 8, 3, 10); // -const _Tier *_Tier::GOLD = new _Tier(0, 32, 12, 0, 22); +const _Tier* _Tier::WOOD = new _Tier(0, 59, 2, 0, 15); // +const _Tier* _Tier::STONE = new _Tier(1, 131, 4, 1, 5); // +const _Tier* _Tier::IRON = new _Tier(2, 250, 6, 2, 14); // +const _Tier* _Tier::DIAMOND = new _Tier(3, 1561, 8, 3, 10); // +const _Tier* _Tier::GOLD = new _Tier(0, 32, 12, 0, 22); -Random *Item::random = new Random(); +Random* Item::random = new Random(); -ItemArray Item::items = ItemArray( ITEM_NUM_COUNT ); +ItemArray Item::items = ItemArray(ITEM_NUM_COUNT); -Item *Item::shovel_iron = NULL; -Item *Item::pickAxe_iron = NULL; -Item *Item::hatchet_iron = NULL; -Item *Item::flintAndSteel = NULL; -Item *Item::apple = NULL; -BowItem *Item::bow = NULL; -Item *Item::arrow = NULL; -Item *Item::coal = NULL; -Item *Item::diamond = NULL; -Item *Item::ironIngot = NULL; -Item *Item::goldIngot = NULL; -Item *Item::sword_iron = NULL; +Item* Item::shovel_iron = NULL; +Item* Item::pickAxe_iron = NULL; +Item* Item::hatchet_iron = NULL; +Item* Item::flintAndSteel = NULL; +Item* Item::apple = NULL; +BowItem* Item::bow = NULL; +Item* Item::arrow = NULL; +Item* Item::coal = NULL; +Item* Item::diamond = NULL; +Item* Item::ironIngot = NULL; +Item* Item::goldIngot = NULL; +Item* Item::sword_iron = NULL; -Item *Item::sword_wood = NULL; -Item *Item::shovel_wood = NULL; -Item *Item::pickAxe_wood = NULL; -Item *Item::hatchet_wood = NULL; +Item* Item::sword_wood = NULL; +Item* Item::shovel_wood = NULL; +Item* Item::pickAxe_wood = NULL; +Item* Item::hatchet_wood = NULL; -Item *Item::sword_stone = NULL; -Item *Item::shovel_stone = NULL; -Item *Item::pickAxe_stone = NULL; -Item *Item::hatchet_stone = NULL; +Item* Item::sword_stone = NULL; +Item* Item::shovel_stone = NULL; +Item* Item::pickAxe_stone = NULL; +Item* Item::hatchet_stone = NULL; -Item *Item::sword_diamond = NULL; -Item *Item::shovel_diamond = NULL; -Item *Item::pickAxe_diamond = NULL; -Item *Item::hatchet_diamond = NULL; +Item* Item::sword_diamond = NULL; +Item* Item::shovel_diamond = NULL; +Item* Item::pickAxe_diamond = NULL; +Item* Item::hatchet_diamond = NULL; -Item *Item::stick = NULL; -Item *Item::bowl = NULL; -Item *Item::mushroomStew = NULL; +Item* Item::stick = NULL; +Item* Item::bowl = NULL; +Item* Item::mushroomStew = NULL; -Item *Item::sword_gold = NULL; -Item *Item::shovel_gold = NULL; -Item *Item::pickAxe_gold = NULL; -Item *Item::hatchet_gold = NULL; +Item* Item::sword_gold = NULL; +Item* Item::shovel_gold = NULL; +Item* Item::pickAxe_gold = NULL; +Item* Item::hatchet_gold = NULL; -Item *Item::string = NULL; -Item *Item::feather = NULL; -Item *Item::sulphur = NULL; +Item* Item::string = NULL; +Item* Item::feather = NULL; +Item* Item::sulphur = NULL; -Item *Item::hoe_wood = NULL; -Item *Item::hoe_stone = NULL; -Item *Item::hoe_iron = NULL; -Item *Item::hoe_diamond = NULL; -Item *Item::hoe_gold = NULL; +Item* Item::hoe_wood = NULL; +Item* Item::hoe_stone = NULL; +Item* Item::hoe_iron = NULL; +Item* Item::hoe_diamond = NULL; +Item* Item::hoe_gold = NULL; -Item *Item::seeds_wheat = NULL; -Item *Item::wheat = NULL; -Item *Item::bread = NULL; +Item* Item::seeds_wheat = NULL; +Item* Item::wheat = NULL; +Item* Item::bread = NULL; -ArmorItem *Item::helmet_cloth = NULL; -ArmorItem *Item::chestplate_cloth = NULL; -ArmorItem *Item::leggings_cloth = NULL; -ArmorItem *Item::boots_cloth = NULL; +ArmorItem* Item::helmet_cloth = NULL; +ArmorItem* Item::chestplate_cloth = NULL; +ArmorItem* Item::leggings_cloth = NULL; +ArmorItem* Item::boots_cloth = NULL; -ArmorItem *Item::helmet_chain = NULL; -ArmorItem *Item::chestplate_chain = NULL; -ArmorItem *Item::leggings_chain = NULL; -ArmorItem *Item::boots_chain = NULL; +ArmorItem* Item::helmet_chain = NULL; +ArmorItem* Item::chestplate_chain = NULL; +ArmorItem* Item::leggings_chain = NULL; +ArmorItem* Item::boots_chain = NULL; -ArmorItem *Item::helmet_iron = NULL; -ArmorItem *Item::chestplate_iron = NULL; -ArmorItem *Item::leggings_iron = NULL; -ArmorItem *Item::boots_iron = NULL; +ArmorItem* Item::helmet_iron = NULL; +ArmorItem* Item::chestplate_iron = NULL; +ArmorItem* Item::leggings_iron = NULL; +ArmorItem* Item::boots_iron = NULL; -ArmorItem *Item::helmet_diamond = NULL; -ArmorItem *Item::chestplate_diamond = NULL; -ArmorItem *Item::leggings_diamond = NULL; -ArmorItem *Item::boots_diamond = NULL; +ArmorItem* Item::helmet_diamond = NULL; +ArmorItem* Item::chestplate_diamond = NULL; +ArmorItem* Item::leggings_diamond = NULL; +ArmorItem* Item::boots_diamond = NULL; -ArmorItem *Item::helmet_gold = NULL; -ArmorItem *Item::chestplate_gold = NULL; -ArmorItem *Item::leggings_gold = NULL; -ArmorItem *Item::boots_gold = NULL; +ArmorItem* Item::helmet_gold = NULL; +ArmorItem* Item::chestplate_gold = NULL; +ArmorItem* Item::leggings_gold = NULL; +ArmorItem* Item::boots_gold = NULL; -Item *Item::flint = NULL; -Item *Item::porkChop_raw = NULL; -Item *Item::porkChop_cooked = NULL; -Item *Item::painting = NULL; +Item* Item::flint = NULL; +Item* Item::porkChop_raw = NULL; +Item* Item::porkChop_cooked = NULL; +Item* Item::painting = NULL; -Item *Item::apple_gold = NULL; +Item* Item::apple_gold = NULL; -Item *Item::sign = NULL; -Item *Item::door_wood = NULL; +Item* Item::sign = NULL; +Item* Item::door_wood = NULL; -Item *Item::bucket_empty = NULL; -Item *Item::bucket_water = NULL; -Item *Item::bucket_lava = NULL; +Item* Item::bucket_empty = NULL; +Item* Item::bucket_water = NULL; +Item* Item::bucket_lava = NULL; -Item *Item::minecart = NULL; -Item *Item::saddle = NULL; -Item *Item::door_iron = NULL; -Item *Item::redStone = NULL; -Item *Item::snowBall = NULL; +Item* Item::minecart = NULL; +Item* Item::saddle = NULL; +Item* Item::door_iron = NULL; +Item* Item::redStone = NULL; +Item* Item::snowBall = NULL; -Item *Item::boat = NULL; +Item* Item::boat = NULL; -Item *Item::leather = NULL; -Item *Item::milk = NULL; -Item *Item::brick = NULL; -Item *Item::clay = NULL; -Item *Item::reeds = NULL; -Item *Item::paper = NULL; -Item *Item::book = NULL; -Item *Item::slimeBall = NULL; -Item *Item::minecart_chest = NULL; -Item *Item::minecart_furnace = NULL; -Item *Item::egg = NULL; -Item *Item::compass = NULL; -FishingRodItem *Item::fishingRod = NULL; -Item *Item::clock = NULL; -Item *Item::yellowDust = NULL; -Item *Item::fish_raw = NULL; -Item *Item::fish_cooked = NULL; +Item* Item::leather = NULL; +Item* Item::milk = NULL; +Item* Item::brick = NULL; +Item* Item::clay = NULL; +Item* Item::reeds = NULL; +Item* Item::paper = NULL; +Item* Item::book = NULL; +Item* Item::slimeBall = NULL; +Item* Item::minecart_chest = NULL; +Item* Item::minecart_furnace = NULL; +Item* Item::egg = NULL; +Item* Item::compass = NULL; +FishingRodItem* Item::fishingRod = NULL; +Item* Item::clock = NULL; +Item* Item::yellowDust = NULL; +Item* Item::fish_raw = NULL; +Item* Item::fish_cooked = NULL; -Item *Item::dye_powder = NULL; -Item *Item::bone = NULL; -Item *Item::sugar = NULL; -Item *Item::cake = NULL; +Item* Item::dye_powder = NULL; +Item* Item::bone = NULL; +Item* Item::sugar = NULL; +Item* Item::cake = NULL; -Item *Item::bed = NULL; +Item* Item::bed = NULL; -Item *Item::diode = NULL; -Item *Item::cookie = NULL; +Item* Item::diode = NULL; +Item* Item::cookie = NULL; -MapItem *Item::map = NULL; +MapItem* Item::map = NULL; -Item *Item::record_01 = NULL; -Item *Item::record_02 = NULL; -Item *Item::record_03 = NULL; -Item *Item::record_04 = NULL; -Item *Item::record_05 = NULL; -Item *Item::record_06 = NULL; -Item *Item::record_07 = NULL; -Item *Item::record_08 = NULL; -Item *Item::record_09 = NULL; -Item *Item::record_10 = NULL; -Item *Item::record_11 = NULL; -Item *Item::record_12 = NULL; +Item* Item::record_01 = NULL; +Item* Item::record_02 = NULL; +Item* Item::record_03 = NULL; +Item* Item::record_04 = NULL; +Item* Item::record_05 = NULL; +Item* Item::record_06 = NULL; +Item* Item::record_07 = NULL; +Item* Item::record_08 = NULL; +Item* Item::record_09 = NULL; +Item* Item::record_10 = NULL; +Item* Item::record_11 = NULL; +Item* Item::record_12 = NULL; -ShearsItem *Item::shears = NULL; +ShearsItem* Item::shears = NULL; -Item *Item::melon = NULL; +Item* Item::melon = NULL; -Item *Item::seeds_pumpkin = NULL; -Item *Item::seeds_melon = NULL; +Item* Item::seeds_pumpkin = NULL; +Item* Item::seeds_melon = NULL; -Item *Item::beef_raw = NULL; -Item *Item::beef_cooked = NULL; -Item *Item::chicken_raw = NULL; -Item *Item::chicken_cooked = NULL; -Item *Item::rotten_flesh = NULL; +Item* Item::beef_raw = NULL; +Item* Item::beef_cooked = NULL; +Item* Item::chicken_raw = NULL; +Item* Item::chicken_cooked = NULL; +Item* Item::rotten_flesh = NULL; -Item *Item::enderPearl = NULL; +Item* Item::enderPearl = NULL; -Item *Item::blazeRod = NULL; -Item *Item::ghastTear = NULL; -Item *Item::goldNugget = NULL; -Item *Item::netherStalkSeeds = NULL; -PotionItem *Item::potion = NULL; -Item *Item::glassBottle = NULL; -Item *Item::spiderEye = NULL; -Item *Item::fermentedSpiderEye = NULL; -Item *Item::blazePowder = NULL; -Item *Item::magmaCream = NULL; -Item *Item::brewingStand = NULL; -Item *Item::cauldron = NULL; -Item *Item::eyeOfEnder = NULL; -Item *Item::speckledMelon = NULL; +Item* Item::blazeRod = NULL; +Item* Item::ghastTear = NULL; +Item* Item::goldNugget = NULL; +Item* Item::netherStalkSeeds = NULL; +PotionItem* Item::potion = NULL; +Item* Item::glassBottle = NULL; +Item* Item::spiderEye = NULL; +Item* Item::fermentedSpiderEye = NULL; +Item* Item::blazePowder = NULL; +Item* Item::magmaCream = NULL; +Item* Item::brewingStand = NULL; +Item* Item::cauldron = NULL; +Item* Item::eyeOfEnder = NULL; +Item* Item::speckledMelon = NULL; -Item *Item::monsterPlacer = NULL; +Item* Item::monsterPlacer = NULL; -Item *Item::expBottle = NULL; +Item* Item::expBottle = NULL; // TU9 -Item *Item::fireball = NULL; -Item *Item::frame = NULL; -Item *Item::netherbrick = NULL; - -Item *Item::skull = NULL; +Item* Item::fireball = NULL; +Item* Item::frame = NULL; +Item* Item::netherbrick = NULL; +Item* Item::skull = NULL; // TU14 -//Item *Item::writingBook = NULL; -//Item *Item::writtenBook = NULL; +// Item *Item::writingBook = NULL; +// Item *Item::writtenBook = NULL; -Item *Item::emerald = NULL; +Item* Item::emerald = NULL; -Item *Item::flowerPot = NULL; +Item* Item::flowerPot = NULL; -Item *Item::carrots = NULL; -Item *Item::potato = NULL; -Item *Item::potatoBaked = NULL; -Item *Item::potatoPoisonous = NULL; +Item* Item::carrots = NULL; +Item* Item::potato = NULL; +Item* Item::potatoBaked = NULL; +Item* Item::potatoPoisonous = NULL; -Item *Item::carrotGolden = NULL; +Item* Item::carrotGolden = NULL; -Item *Item::carrotOnAStick = NULL; -Item *Item::pumpkinPie = NULL; +Item* Item::carrotOnAStick = NULL; +Item* Item::pumpkinPie = NULL; -EnchantedBookItem *Item::enchantedBook = NULL; -Item *Item::netherQuartz = NULL; +EnchantedBookItem* Item::enchantedBook = NULL; +Item* Item::netherQuartz = NULL; +void Item::staticCtor() { + Item::sword_wood = + (new WeaponItem(12, _Tier::WOOD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_wood) + ->setTextureName(L"swordWood") + ->setDescriptionId(IDS_ITEM_SWORD_WOOD) + ->setUseDescriptionId(IDS_DESC_SWORD); + Item::sword_stone = + (new WeaponItem(16, _Tier::STONE)) + ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_stone) + ->setTextureName(L"swordStone") + ->setDescriptionId(IDS_ITEM_SWORD_STONE) + ->setUseDescriptionId(IDS_DESC_SWORD); + Item::sword_iron = + (new WeaponItem(11, _Tier::IRON)) + ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_iron) + ->setTextureName(L"swordIron") + ->setDescriptionId(IDS_ITEM_SWORD_IRON) + ->setUseDescriptionId(IDS_DESC_SWORD); + Item::sword_diamond = + (new WeaponItem(20, _Tier::DIAMOND)) + ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_diamond) + ->setTextureName(L"swordDiamond") + ->setDescriptionId(IDS_ITEM_SWORD_DIAMOND) + ->setUseDescriptionId(IDS_DESC_SWORD); + Item::sword_gold = + (new WeaponItem(27, _Tier::GOLD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_gold) + ->setTextureName(L"swordGold") + ->setDescriptionId(IDS_ITEM_SWORD_GOLD) + ->setUseDescriptionId(IDS_DESC_SWORD); -void Item::staticCtor() -{ + Item::shovel_wood = + (new ShovelItem(13, _Tier::WOOD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_wood) + ->setTextureName(L"shovelWood") + ->setDescriptionId(IDS_ITEM_SHOVEL_WOOD) + ->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::shovel_stone = + (new ShovelItem(17, _Tier::STONE)) + ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_stone) + ->setTextureName(L"shovelStone") + ->setDescriptionId(IDS_ITEM_SHOVEL_STONE) + ->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::shovel_iron = + (new ShovelItem(0, _Tier::IRON)) + ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_iron) + ->setTextureName(L"shovelIron") + ->setDescriptionId(IDS_ITEM_SHOVEL_IRON) + ->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::shovel_diamond = (new ShovelItem(21, _Tier::DIAMOND)) + ->setBaseItemTypeAndMaterial( + eBaseItemType_shovel, eMaterial_diamond) + ->setTextureName(L"shovelDiamond") + ->setDescriptionId(IDS_ITEM_SHOVEL_DIAMOND) + ->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::shovel_gold = + (new ShovelItem(28, _Tier::GOLD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_gold) + ->setTextureName(L"shovelGold") + ->setDescriptionId(IDS_ITEM_SHOVEL_GOLD) + ->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::pickAxe_wood = + (new PickaxeItem(14, _Tier::WOOD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_wood) + ->setTextureName(L"pickaxeWood") + ->setDescriptionId(IDS_ITEM_PICKAXE_WOOD) + ->setUseDescriptionId(IDS_DESC_PICKAXE); + Item::pickAxe_stone = + (new PickaxeItem(18, _Tier::STONE)) + ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_stone) + ->setTextureName(L"pickaxeStone") + ->setDescriptionId(IDS_ITEM_PICKAXE_STONE) + ->setUseDescriptionId(IDS_DESC_PICKAXE); + Item::pickAxe_iron = + (new PickaxeItem(1, _Tier::IRON)) + ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_iron) + ->setTextureName(L"pickaxeIron") + ->setDescriptionId(IDS_ITEM_PICKAXE_IRON) + ->setUseDescriptionId(IDS_DESC_PICKAXE); + Item::pickAxe_diamond = (new PickaxeItem(22, _Tier::DIAMOND)) + ->setBaseItemTypeAndMaterial( + eBaseItemType_pickaxe, eMaterial_diamond) + ->setTextureName(L"pickaxeDiamond") + ->setDescriptionId(IDS_ITEM_PICKAXE_DIAMOND) + ->setUseDescriptionId(IDS_DESC_PICKAXE); + Item::pickAxe_gold = + (new PickaxeItem(29, _Tier::GOLD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_gold) + ->setTextureName(L"pickaxeGold") + ->setDescriptionId(IDS_ITEM_PICKAXE_GOLD) + ->setUseDescriptionId(IDS_DESC_PICKAXE); - Item::sword_wood = ( new WeaponItem(12, _Tier::WOOD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_wood) ->setTextureName(L"swordWood")->setDescriptionId(IDS_ITEM_SWORD_WOOD)->setUseDescriptionId(IDS_DESC_SWORD); - Item::sword_stone = ( new WeaponItem(16, _Tier::STONE) ) ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_stone) ->setTextureName(L"swordStone")->setDescriptionId(IDS_ITEM_SWORD_STONE)->setUseDescriptionId(IDS_DESC_SWORD); - Item::sword_iron = ( new WeaponItem(11, _Tier::IRON) ) ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_iron) ->setTextureName(L"swordIron")->setDescriptionId(IDS_ITEM_SWORD_IRON)->setUseDescriptionId(IDS_DESC_SWORD); - Item::sword_diamond = ( new WeaponItem(20, _Tier::DIAMOND) ) ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_diamond) ->setTextureName(L"swordDiamond")->setDescriptionId(IDS_ITEM_SWORD_DIAMOND)->setUseDescriptionId(IDS_DESC_SWORD); - Item::sword_gold = ( new WeaponItem(27, _Tier::GOLD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_sword, eMaterial_gold) ->setTextureName(L"swordGold")->setDescriptionId(IDS_ITEM_SWORD_GOLD)->setUseDescriptionId(IDS_DESC_SWORD); + Item::hatchet_wood = + (new HatchetItem(15, _Tier::WOOD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_wood) + ->setTextureName(L"hatchetWood") + ->setDescriptionId(IDS_ITEM_HATCHET_WOOD) + ->setUseDescriptionId(IDS_DESC_HATCHET); + Item::hatchet_stone = + (new HatchetItem(19, _Tier::STONE)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_stone) + ->setTextureName(L"hatchetStone") + ->setDescriptionId(IDS_ITEM_HATCHET_STONE) + ->setUseDescriptionId(IDS_DESC_HATCHET); + Item::hatchet_iron = + (new HatchetItem(2, _Tier::IRON)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_iron) + ->setTextureName(L"hatchetIron") + ->setDescriptionId(IDS_ITEM_HATCHET_IRON) + ->setUseDescriptionId(IDS_DESC_HATCHET); + Item::hatchet_diamond = (new HatchetItem(23, _Tier::DIAMOND)) + ->setBaseItemTypeAndMaterial( + eBaseItemType_hatchet, eMaterial_diamond) + ->setTextureName(L"hatchetDiamond") + ->setDescriptionId(IDS_ITEM_HATCHET_DIAMOND) + ->setUseDescriptionId(IDS_DESC_HATCHET); + Item::hatchet_gold = + (new HatchetItem(30, _Tier::GOLD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_gold) + ->setTextureName(L"hatchetGold") + ->setDescriptionId(IDS_ITEM_HATCHET_GOLD) + ->setUseDescriptionId(IDS_DESC_HATCHET); - Item::shovel_wood = ( new ShovelItem(13, _Tier::WOOD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_wood) ->setTextureName(L"shovelWood")->setDescriptionId(IDS_ITEM_SHOVEL_WOOD)->setUseDescriptionId(IDS_DESC_SHOVEL); - Item::shovel_stone = ( new ShovelItem(17, _Tier::STONE) ) ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_stone) ->setTextureName(L"shovelStone")->setDescriptionId(IDS_ITEM_SHOVEL_STONE)->setUseDescriptionId(IDS_DESC_SHOVEL); - Item::shovel_iron = ( new ShovelItem(0, _Tier::IRON) ) ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_iron) ->setTextureName(L"shovelIron")->setDescriptionId(IDS_ITEM_SHOVEL_IRON)->setUseDescriptionId(IDS_DESC_SHOVEL); - Item::shovel_diamond = ( new ShovelItem(21, _Tier::DIAMOND) ) ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_diamond) ->setTextureName(L"shovelDiamond")->setDescriptionId(IDS_ITEM_SHOVEL_DIAMOND)->setUseDescriptionId(IDS_DESC_SHOVEL); - Item::shovel_gold = ( new ShovelItem(28, _Tier::GOLD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_shovel, eMaterial_gold) ->setTextureName(L"shovelGold")->setDescriptionId(IDS_ITEM_SHOVEL_GOLD)->setUseDescriptionId(IDS_DESC_SHOVEL); + Item::hoe_wood = + (new HoeItem(34, _Tier::WOOD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_wood) + ->setTextureName(L"hoeWood") + ->setDescriptionId(IDS_ITEM_HOE_WOOD) + ->setUseDescriptionId(IDS_DESC_HOE); + Item::hoe_stone = + (new HoeItem(35, _Tier::STONE)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_stone) + ->setTextureName(L"hoeStone") + ->setDescriptionId(IDS_ITEM_HOE_STONE) + ->setUseDescriptionId(IDS_DESC_HOE); + Item::hoe_iron = + (new HoeItem(36, _Tier::IRON)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_iron) + ->setTextureName(L"hoeIron") + ->setDescriptionId(IDS_ITEM_HOE_IRON) + ->setUseDescriptionId(IDS_DESC_HOE); + Item::hoe_diamond = + (new HoeItem(37, _Tier::DIAMOND)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_diamond) + ->setTextureName(L"hoeDiamond") + ->setDescriptionId(IDS_ITEM_HOE_DIAMOND) + ->setUseDescriptionId(IDS_DESC_HOE); + Item::hoe_gold = + (new HoeItem(38, _Tier::GOLD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_gold) + ->setTextureName(L"hoeGold") + ->setDescriptionId(IDS_ITEM_HOE_GOLD) + ->setUseDescriptionId(IDS_DESC_HOE); - Item::pickAxe_wood = ( new PickaxeItem(14, _Tier::WOOD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_wood) ->setTextureName(L"pickaxeWood")->setDescriptionId(IDS_ITEM_PICKAXE_WOOD)->setUseDescriptionId(IDS_DESC_PICKAXE); - Item::pickAxe_stone = ( new PickaxeItem(18, _Tier::STONE) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_stone) ->setTextureName(L"pickaxeStone")->setDescriptionId(IDS_ITEM_PICKAXE_STONE)->setUseDescriptionId(IDS_DESC_PICKAXE); - Item::pickAxe_iron = ( new PickaxeItem(1, _Tier::IRON) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_iron) ->setTextureName(L"pickaxeIron")->setDescriptionId(IDS_ITEM_PICKAXE_IRON)->setUseDescriptionId(IDS_DESC_PICKAXE); - Item::pickAxe_diamond = ( new PickaxeItem(22, _Tier::DIAMOND) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_diamond) ->setTextureName(L"pickaxeDiamond")->setDescriptionId(IDS_ITEM_PICKAXE_DIAMOND)->setUseDescriptionId(IDS_DESC_PICKAXE); - Item::pickAxe_gold = ( new PickaxeItem(29, _Tier::GOLD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pickaxe, eMaterial_gold) ->setTextureName(L"pickaxeGold")->setDescriptionId(IDS_ITEM_PICKAXE_GOLD)->setUseDescriptionId(IDS_DESC_PICKAXE); + Item::door_wood = + (new DoorItem(68, Material::wood)) + ->setBaseItemTypeAndMaterial(eBaseItemType_door, eMaterial_wood) + ->setTextureName(L"doorWood") + ->setDescriptionId(IDS_ITEM_DOOR_WOOD) + ->setUseDescriptionId(IDS_DESC_DOOR_WOOD); + Item::door_iron = + (new DoorItem(74, Material::metal)) + ->setBaseItemTypeAndMaterial(eBaseItemType_door, eMaterial_iron) + ->setTextureName(L"doorIron") + ->setDescriptionId(IDS_ITEM_DOOR_IRON) + ->setUseDescriptionId(IDS_DESC_DOOR_IRON); - Item::hatchet_wood = ( new HatchetItem(15, _Tier::WOOD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_wood) ->setTextureName(L"hatchetWood")->setDescriptionId(IDS_ITEM_HATCHET_WOOD)->setUseDescriptionId(IDS_DESC_HATCHET); - Item::hatchet_stone = ( new HatchetItem(19, _Tier::STONE) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_stone) ->setTextureName(L"hatchetStone")->setDescriptionId(IDS_ITEM_HATCHET_STONE)->setUseDescriptionId(IDS_DESC_HATCHET); - Item::hatchet_iron = ( new HatchetItem(2, _Tier::IRON) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_iron) ->setTextureName(L"hatchetIron")->setDescriptionId(IDS_ITEM_HATCHET_IRON)->setUseDescriptionId(IDS_DESC_HATCHET); - Item::hatchet_diamond = ( new HatchetItem(23, _Tier::DIAMOND) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_diamond) ->setTextureName(L"hatchetDiamond")->setDescriptionId(IDS_ITEM_HATCHET_DIAMOND)->setUseDescriptionId(IDS_DESC_HATCHET); - Item::hatchet_gold = ( new HatchetItem(30, _Tier::GOLD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hatchet, eMaterial_gold) ->setTextureName(L"hatchetGold")->setDescriptionId(IDS_ITEM_HATCHET_GOLD)->setUseDescriptionId(IDS_DESC_HATCHET); + Item::helmet_cloth = + (ArmorItem*)((new ArmorItem(42, ArmorItem::ArmorMaterial::CLOTH, 0, + ArmorItem::SLOT_HEAD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, + eMaterial_cloth) + ->setTextureName(L"helmetCloth") + ->setDescriptionId(IDS_ITEM_HELMET_CLOTH) + ->setUseDescriptionId(IDS_DESC_HELMET_LEATHER)); + Item::helmet_iron = + (ArmorItem*)((new ArmorItem(50, ArmorItem::ArmorMaterial::IRON, 2, + ArmorItem::SLOT_HEAD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, + eMaterial_iron) + ->setTextureName(L"helmetIron") + ->setDescriptionId(IDS_ITEM_HELMET_IRON) + ->setUseDescriptionId(IDS_DESC_HELMET_IRON)); + Item::helmet_diamond = + (ArmorItem*)((new ArmorItem(54, ArmorItem::ArmorMaterial::DIAMOND, 3, + ArmorItem::SLOT_HEAD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, + eMaterial_diamond) + ->setTextureName(L"helmetDiamond") + ->setDescriptionId(IDS_ITEM_HELMET_DIAMOND) + ->setUseDescriptionId(IDS_DESC_HELMET_DIAMOND)); + Item::helmet_gold = + (ArmorItem*)((new ArmorItem(58, ArmorItem::ArmorMaterial::GOLD, 4, + ArmorItem::SLOT_HEAD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, + eMaterial_gold) + ->setTextureName(L"helmetGold") + ->setDescriptionId(IDS_ITEM_HELMET_GOLD) + ->setUseDescriptionId(IDS_DESC_HELMET_GOLD)); - Item::hoe_wood = ( new HoeItem(34, _Tier::WOOD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_wood) ->setTextureName(L"hoeWood")->setDescriptionId(IDS_ITEM_HOE_WOOD)->setUseDescriptionId(IDS_DESC_HOE); - Item::hoe_stone = ( new HoeItem(35, _Tier::STONE) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_stone) ->setTextureName(L"hoeStone")->setDescriptionId(IDS_ITEM_HOE_STONE)->setUseDescriptionId(IDS_DESC_HOE); - Item::hoe_iron = ( new HoeItem(36, _Tier::IRON) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_iron) ->setTextureName(L"hoeIron")->setDescriptionId(IDS_ITEM_HOE_IRON)->setUseDescriptionId(IDS_DESC_HOE); - Item::hoe_diamond = ( new HoeItem(37, _Tier::DIAMOND) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_diamond) ->setTextureName(L"hoeDiamond")->setDescriptionId(IDS_ITEM_HOE_DIAMOND)->setUseDescriptionId(IDS_DESC_HOE); - Item::hoe_gold = ( new HoeItem(38, _Tier::GOLD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_hoe, eMaterial_gold) ->setTextureName(L"hoeGold")->setDescriptionId(IDS_ITEM_HOE_GOLD)->setUseDescriptionId(IDS_DESC_HOE); + Item::chestplate_cloth = + (ArmorItem*)((new ArmorItem(43, ArmorItem::ArmorMaterial::CLOTH, 0, + ArmorItem::SLOT_TORSO)) + ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, + eMaterial_cloth) + ->setTextureName(L"chestplateCloth") + ->setDescriptionId(IDS_ITEM_CHESTPLATE_CLOTH) + ->setUseDescriptionId(IDS_DESC_CHESTPLATE_LEATHER)); + Item::chestplate_iron = + (ArmorItem*)((new ArmorItem(51, ArmorItem::ArmorMaterial::IRON, 2, + ArmorItem::SLOT_TORSO)) + ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, + eMaterial_iron) + ->setTextureName(L"chestplateIron") + ->setDescriptionId(IDS_ITEM_CHESTPLATE_IRON) + ->setUseDescriptionId(IDS_DESC_CHESTPLATE_IRON)); + Item::chestplate_diamond = + (ArmorItem*)((new ArmorItem(55, ArmorItem::ArmorMaterial::DIAMOND, 3, + ArmorItem::SLOT_TORSO)) + ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, + eMaterial_diamond) + ->setTextureName(L"chestplateDiamond") + ->setDescriptionId(IDS_ITEM_CHESTPLATE_DIAMOND) + ->setUseDescriptionId(IDS_DESC_CHESTPLATE_DIAMOND)); + Item::chestplate_gold = + (ArmorItem*)((new ArmorItem(59, ArmorItem::ArmorMaterial::GOLD, 4, + ArmorItem::SLOT_TORSO)) + ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, + eMaterial_gold) + ->setTextureName(L"chestplateGold") + ->setDescriptionId(IDS_ITEM_CHESTPLATE_GOLD) + ->setUseDescriptionId(IDS_DESC_CHESTPLATE_GOLD)); - Item::door_wood = ( new DoorItem(68, Material::wood) ) ->setBaseItemTypeAndMaterial(eBaseItemType_door, eMaterial_wood)->setTextureName(L"doorWood")->setDescriptionId(IDS_ITEM_DOOR_WOOD)->setUseDescriptionId(IDS_DESC_DOOR_WOOD); - Item::door_iron = ( new DoorItem(74, Material::metal) ) ->setBaseItemTypeAndMaterial(eBaseItemType_door, eMaterial_iron)->setTextureName(L"doorIron")->setDescriptionId(IDS_ITEM_DOOR_IRON)->setUseDescriptionId(IDS_DESC_DOOR_IRON); + Item::leggings_cloth = + (ArmorItem*)((new ArmorItem(44, ArmorItem::ArmorMaterial::CLOTH, 0, + ArmorItem::SLOT_LEGS)) + ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, + eMaterial_cloth) + ->setTextureName(L"leggingsCloth") + ->setDescriptionId(IDS_ITEM_LEGGINGS_CLOTH) + ->setUseDescriptionId(IDS_DESC_LEGGINGS_LEATHER)); + Item::leggings_iron = + (ArmorItem*)((new ArmorItem(52, ArmorItem::ArmorMaterial::IRON, 2, + ArmorItem::SLOT_LEGS)) + ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, + eMaterial_iron) + ->setTextureName(L"leggingsIron") + ->setDescriptionId(IDS_ITEM_LEGGINGS_IRON) + ->setUseDescriptionId(IDS_DESC_LEGGINGS_IRON)); + Item::leggings_diamond = + (ArmorItem*)((new ArmorItem(56, ArmorItem::ArmorMaterial::DIAMOND, 3, + ArmorItem::SLOT_LEGS)) + ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, + eMaterial_diamond) + ->setTextureName(L"leggingsDiamond") + ->setDescriptionId(IDS_ITEM_LEGGINGS_DIAMOND) + ->setUseDescriptionId(IDS_DESC_LEGGINGS_DIAMOND)); + Item::leggings_gold = + (ArmorItem*)((new ArmorItem(60, ArmorItem::ArmorMaterial::GOLD, 4, + ArmorItem::SLOT_LEGS)) + ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, + eMaterial_gold) + ->setTextureName(L"leggingsGold") + ->setDescriptionId(IDS_ITEM_LEGGINGS_GOLD) + ->setUseDescriptionId(IDS_DESC_LEGGINGS_GOLD)); - Item::helmet_cloth = (ArmorItem *) ( ( new ArmorItem(42, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_cloth) ->setTextureName(L"helmetCloth")->setDescriptionId(IDS_ITEM_HELMET_CLOTH)->setUseDescriptionId(IDS_DESC_HELMET_LEATHER) ); - Item::helmet_iron = (ArmorItem *) ( ( new ArmorItem(50, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_iron) ->setTextureName(L"helmetIron")->setDescriptionId(IDS_ITEM_HELMET_IRON)->setUseDescriptionId(IDS_DESC_HELMET_IRON) ); - Item::helmet_diamond = (ArmorItem *) ( ( new ArmorItem(54, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_diamond) ->setTextureName(L"helmetDiamond")->setDescriptionId(IDS_ITEM_HELMET_DIAMOND)->setUseDescriptionId(IDS_DESC_HELMET_DIAMOND) ); - Item::helmet_gold = (ArmorItem *) ( ( new ArmorItem(58, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_gold) ->setTextureName(L"helmetGold")->setDescriptionId(IDS_ITEM_HELMET_GOLD)->setUseDescriptionId(IDS_DESC_HELMET_GOLD) ); - - Item::chestplate_cloth = (ArmorItem *) ( ( new ArmorItem(43, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_cloth) ->setTextureName(L"chestplateCloth")->setDescriptionId(IDS_ITEM_CHESTPLATE_CLOTH)->setUseDescriptionId(IDS_DESC_CHESTPLATE_LEATHER) ); - Item::chestplate_iron = (ArmorItem *) ( ( new ArmorItem(51, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_iron) ->setTextureName(L"chestplateIron")->setDescriptionId(IDS_ITEM_CHESTPLATE_IRON)->setUseDescriptionId(IDS_DESC_CHESTPLATE_IRON) ); - Item::chestplate_diamond = (ArmorItem *) ( ( new ArmorItem(55, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_diamond) ->setTextureName(L"chestplateDiamond")->setDescriptionId(IDS_ITEM_CHESTPLATE_DIAMOND)->setUseDescriptionId(IDS_DESC_CHESTPLATE_DIAMOND) ); - Item::chestplate_gold = (ArmorItem *) ( ( new ArmorItem(59, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_gold) ->setTextureName(L"chestplateGold")->setDescriptionId(IDS_ITEM_CHESTPLATE_GOLD)->setUseDescriptionId(IDS_DESC_CHESTPLATE_GOLD) ); - - Item::leggings_cloth = (ArmorItem *) ( ( new ArmorItem(44, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_cloth) ->setTextureName(L"leggingsCloth")->setDescriptionId(IDS_ITEM_LEGGINGS_CLOTH)->setUseDescriptionId(IDS_DESC_LEGGINGS_LEATHER) ); - Item::leggings_iron = (ArmorItem *) ( ( new ArmorItem(52, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_iron) ->setTextureName(L"leggingsIron")->setDescriptionId(IDS_ITEM_LEGGINGS_IRON)->setUseDescriptionId(IDS_DESC_LEGGINGS_IRON) ); - Item::leggings_diamond = (ArmorItem *) ( ( new ArmorItem(56, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_diamond) ->setTextureName(L"leggingsDiamond")->setDescriptionId(IDS_ITEM_LEGGINGS_DIAMOND)->setUseDescriptionId(IDS_DESC_LEGGINGS_DIAMOND) ); - Item::leggings_gold = (ArmorItem *) ( ( new ArmorItem(60, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_gold) ->setTextureName(L"leggingsGold")->setDescriptionId(IDS_ITEM_LEGGINGS_GOLD)->setUseDescriptionId(IDS_DESC_LEGGINGS_GOLD) ); + Item::helmet_chain = + (ArmorItem*)((new ArmorItem(46, ArmorItem::ArmorMaterial::CHAIN, 1, + ArmorItem::SLOT_HEAD)) + ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, + eMaterial_chain) + ->setTextureName(L"helmetChain") + ->setDescriptionId(IDS_ITEM_HELMET_CHAIN) + ->setUseDescriptionId(IDS_DESC_HELMET_CHAIN)); + Item::chestplate_chain = + (ArmorItem*)((new ArmorItem(47, ArmorItem::ArmorMaterial::CHAIN, 1, + ArmorItem::SLOT_TORSO)) + ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, + eMaterial_chain) + ->setTextureName(L"chestplateChain") + ->setDescriptionId(IDS_ITEM_CHESTPLATE_CHAIN) + ->setUseDescriptionId(IDS_DESC_CHESTPLATE_CHAIN)); + Item::leggings_chain = + (ArmorItem*)((new ArmorItem(48, ArmorItem::ArmorMaterial::CHAIN, 1, + ArmorItem::SLOT_LEGS)) + ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, + eMaterial_chain) + ->setTextureName(L"leggingsChain") + ->setDescriptionId(IDS_ITEM_LEGGINGS_CHAIN) + ->setUseDescriptionId(IDS_DESC_LEGGINGS_CHAIN)); + Item::boots_chain = + (ArmorItem*)((new ArmorItem(49, ArmorItem::ArmorMaterial::CHAIN, 1, + ArmorItem::SLOT_FEET)) + ->setBaseItemTypeAndMaterial(eBaseItemType_boots, + eMaterial_chain) + ->setTextureName(L"bootsChain") + ->setDescriptionId(IDS_ITEM_BOOTS_CHAIN) + ->setUseDescriptionId(IDS_DESC_BOOTS_CHAIN)); - Item::helmet_chain = (ArmorItem *) ( ( new ArmorItem(46, ArmorItem::ArmorMaterial::CHAIN, 1, ArmorItem::SLOT_HEAD) ) ->setBaseItemTypeAndMaterial(eBaseItemType_helmet, eMaterial_chain) ->setTextureName(L"helmetChain")->setDescriptionId(IDS_ITEM_HELMET_CHAIN)->setUseDescriptionId(IDS_DESC_HELMET_CHAIN) ); - Item::chestplate_chain = (ArmorItem *) ( ( new ArmorItem(47, ArmorItem::ArmorMaterial::CHAIN, 1, ArmorItem::SLOT_TORSO) ) ->setBaseItemTypeAndMaterial(eBaseItemType_chestplate, eMaterial_chain) ->setTextureName(L"chestplateChain")->setDescriptionId(IDS_ITEM_CHESTPLATE_CHAIN)->setUseDescriptionId(IDS_DESC_CHESTPLATE_CHAIN) ); - Item::leggings_chain = (ArmorItem *) ( ( new ArmorItem(48, ArmorItem::ArmorMaterial::CHAIN, 1, ArmorItem::SLOT_LEGS) ) ->setBaseItemTypeAndMaterial(eBaseItemType_leggings, eMaterial_chain) ->setTextureName(L"leggingsChain")->setDescriptionId(IDS_ITEM_LEGGINGS_CHAIN)->setUseDescriptionId(IDS_DESC_LEGGINGS_CHAIN) ); - Item::boots_chain = (ArmorItem *) ( ( new ArmorItem(49, ArmorItem::ArmorMaterial::CHAIN, 1, ArmorItem::SLOT_FEET) ) ->setBaseItemTypeAndMaterial(eBaseItemType_boots, eMaterial_chain) ->setTextureName(L"bootsChain")->setDescriptionId(IDS_ITEM_BOOTS_CHAIN)->setUseDescriptionId(IDS_DESC_BOOTS_CHAIN) ); + Item::boots_cloth = + (ArmorItem*)((new ArmorItem(45, ArmorItem::ArmorMaterial::CLOTH, 0, + ArmorItem::SLOT_FEET)) + ->setBaseItemTypeAndMaterial(eBaseItemType_boots, + eMaterial_cloth) + ->setTextureName(L"bootsCloth") + ->setDescriptionId(IDS_ITEM_BOOTS_CLOTH) + ->setUseDescriptionId(IDS_DESC_BOOTS_LEATHER)); + Item::boots_iron = + (ArmorItem*)((new ArmorItem(53, ArmorItem::ArmorMaterial::IRON, 2, + ArmorItem::SLOT_FEET)) + ->setBaseItemTypeAndMaterial(eBaseItemType_boots, + eMaterial_iron) + ->setTextureName(L"bootsIron") + ->setDescriptionId(IDS_ITEM_BOOTS_IRON) + ->setUseDescriptionId(IDS_DESC_BOOTS_IRON)); + Item::boots_diamond = + (ArmorItem*)((new ArmorItem(57, ArmorItem::ArmorMaterial::DIAMOND, 3, + ArmorItem::SLOT_FEET)) + ->setBaseItemTypeAndMaterial(eBaseItemType_boots, + eMaterial_diamond) + ->setTextureName(L"bootsDiamond") + ->setDescriptionId(IDS_ITEM_BOOTS_DIAMOND) + ->setUseDescriptionId(IDS_DESC_BOOTS_DIAMOND)); + Item::boots_gold = + (ArmorItem*)((new ArmorItem(61, ArmorItem::ArmorMaterial::GOLD, 4, + ArmorItem::SLOT_FEET)) + ->setBaseItemTypeAndMaterial(eBaseItemType_boots, + eMaterial_gold) + ->setTextureName(L"bootsGold") + ->setDescriptionId(IDS_ITEM_BOOTS_GOLD) + ->setUseDescriptionId(IDS_DESC_BOOTS_GOLD)); - Item::boots_cloth = (ArmorItem *) ( ( new ArmorItem(45, ArmorItem::ArmorMaterial::CLOTH, 0, ArmorItem::SLOT_FEET) ) ->setBaseItemTypeAndMaterial(eBaseItemType_boots, eMaterial_cloth) ->setTextureName(L"bootsCloth")->setDescriptionId(IDS_ITEM_BOOTS_CLOTH)->setUseDescriptionId(IDS_DESC_BOOTS_LEATHER) ); - Item::boots_iron = (ArmorItem *) ( ( new ArmorItem(53, ArmorItem::ArmorMaterial::IRON, 2, ArmorItem::SLOT_FEET) ) ->setBaseItemTypeAndMaterial(eBaseItemType_boots, eMaterial_iron) ->setTextureName(L"bootsIron")->setDescriptionId(IDS_ITEM_BOOTS_IRON)->setUseDescriptionId(IDS_DESC_BOOTS_IRON) ); - Item::boots_diamond = (ArmorItem *) ( ( new ArmorItem(57, ArmorItem::ArmorMaterial::DIAMOND, 3, ArmorItem::SLOT_FEET) ) ->setBaseItemTypeAndMaterial(eBaseItemType_boots, eMaterial_diamond) ->setTextureName(L"bootsDiamond")->setDescriptionId(IDS_ITEM_BOOTS_DIAMOND)->setUseDescriptionId(IDS_DESC_BOOTS_DIAMOND) ); - Item::boots_gold = (ArmorItem *) ( ( new ArmorItem(61, ArmorItem::ArmorMaterial::GOLD, 4, ArmorItem::SLOT_FEET) ) ->setBaseItemTypeAndMaterial(eBaseItemType_boots, eMaterial_gold) ->setTextureName(L"bootsGold")->setDescriptionId(IDS_ITEM_BOOTS_GOLD)->setUseDescriptionId(IDS_DESC_BOOTS_GOLD) ); + Item::ironIngot = + (new Item(9)) + ->setTextureName(L"ingotIron") + ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_iron) + ->setDescriptionId(IDS_ITEM_INGOT_IRON) + ->setUseDescriptionId(IDS_DESC_INGOT); + Item::goldIngot = + (new Item(10)) + ->setTextureName(L"ingotGold") + ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_gold) + ->setDescriptionId(IDS_ITEM_INGOT_GOLD) + ->setUseDescriptionId(IDS_DESC_INGOT); - Item::ironIngot = ( new Item(9) )->setTextureName(L"ingotIron") ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_iron)->setDescriptionId(IDS_ITEM_INGOT_IRON)->setUseDescriptionId(IDS_DESC_INGOT); - Item::goldIngot = ( new Item(10) )->setTextureName(L"ingotGold") ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_gold)->setDescriptionId(IDS_ITEM_INGOT_GOLD)->setUseDescriptionId(IDS_DESC_INGOT); + // 4J-PB - todo - add materials and base types to the ones below + Item::bucket_empty = + (new BucketItem(69, 0)) + ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_water) + ->setTextureName(L"bucket") + ->setDescriptionId(IDS_ITEM_BUCKET) + ->setUseDescriptionId(IDS_DESC_BUCKET) + ->setMaxStackSize(16); + Item::bowl = + (new Item(25)) + ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_wood) + ->setTextureName(L"bowl") + ->setDescriptionId(IDS_ITEM_BOWL) + ->setUseDescriptionId(IDS_DESC_BOWL) + ->setMaxStackSize(64); + Item::bucket_water = (new BucketItem(70, Tile::water_Id)) + ->setTextureName(L"bucketWater") + ->setDescriptionId(IDS_ITEM_BUCKET_WATER) + ->setCraftingRemainingItem(Item::bucket_empty) + ->setUseDescriptionId(IDS_DESC_BUCKET_WATER); + Item::bucket_lava = (new BucketItem(71, Tile::lava_Id)) + ->setTextureName(L"bucketLava") + ->setDescriptionId(IDS_ITEM_BUCKET_LAVA) + ->setCraftingRemainingItem(Item::bucket_empty) + ->setUseDescriptionId(IDS_DESC_BUCKET_LAVA); + Item::milk = (new MilkBucketItem(79)) + ->setTextureName(L"milk") + ->setDescriptionId(IDS_ITEM_BUCKET_MILK) + ->setCraftingRemainingItem(Item::bucket_empty) + ->setUseDescriptionId(IDS_DESC_BUCKET_MILK); - // 4J-PB - todo - add materials and base types to the ones below - Item::bucket_empty = ( new BucketItem(69, 0) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_water)->setTextureName(L"bucket")->setDescriptionId(IDS_ITEM_BUCKET)->setUseDescriptionId(IDS_DESC_BUCKET)->setMaxStackSize(16); - Item::bowl = ( new Item(25) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_wood)->setTextureName(L"bowl")->setDescriptionId(IDS_ITEM_BOWL)->setUseDescriptionId(IDS_DESC_BOWL)->setMaxStackSize(64); - - Item::bucket_water = ( new BucketItem(70, Tile::water_Id) ) ->setTextureName(L"bucketWater")->setDescriptionId(IDS_ITEM_BUCKET_WATER)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_WATER); - Item::bucket_lava = ( new BucketItem(71, Tile::lava_Id) ) ->setTextureName(L"bucketLava")->setDescriptionId(IDS_ITEM_BUCKET_LAVA)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_LAVA); - Item::milk = ( new MilkBucketItem(79) )->setTextureName(L"milk")->setDescriptionId(IDS_ITEM_BUCKET_MILK)->setCraftingRemainingItem(Item::bucket_empty)->setUseDescriptionId(IDS_DESC_BUCKET_MILK); + Item::bow = + (BowItem*)(new BowItem(5)) + ->setTextureName(L"bow") + ->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_bow) + ->setDescriptionId(IDS_ITEM_BOW) + ->setUseDescriptionId(IDS_DESC_BOW); + Item::arrow = + (new Item(6)) + ->setTextureName(L"arrow") + ->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_arrow) + ->setDescriptionId(IDS_ITEM_ARROW) + ->setUseDescriptionId(IDS_DESC_ARROW); - Item::bow = (BowItem *)( new BowItem(5) ) ->setTextureName(L"bow")->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_bow) ->setDescriptionId(IDS_ITEM_BOW)->setUseDescriptionId(IDS_DESC_BOW); - Item::arrow = ( new Item(6) ) ->setTextureName(L"arrow")->setBaseItemTypeAndMaterial(eBaseItemType_bow, eMaterial_arrow) ->setDescriptionId(IDS_ITEM_ARROW)->setUseDescriptionId(IDS_DESC_ARROW); - - Item::compass = ( new CompassItem(89) ) ->setTextureName(L"compass")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_compass) ->setDescriptionId(IDS_ITEM_COMPASS)->setUseDescriptionId(IDS_DESC_COMPASS); - Item::clock = ( new ClockItem(91) ) ->setTextureName(L"clock")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_clock) ->setDescriptionId(IDS_ITEM_CLOCK)->setUseDescriptionId(IDS_DESC_CLOCK); - Item::map = (MapItem *) ( new MapItem(102) ) ->setTextureName(L"map")->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_map) ->setDescriptionId(IDS_ITEM_MAP)->setUseDescriptionId(IDS_DESC_MAP); + Item::compass = (new CompassItem(89)) + ->setTextureName(L"compass") + ->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, + eMaterial_compass) + ->setDescriptionId(IDS_ITEM_COMPASS) + ->setUseDescriptionId(IDS_DESC_COMPASS); + Item::clock = (new ClockItem(91)) + ->setTextureName(L"clock") + ->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, + eMaterial_clock) + ->setDescriptionId(IDS_ITEM_CLOCK) + ->setUseDescriptionId(IDS_DESC_CLOCK); + Item::map = (MapItem*)(new MapItem(102)) + ->setTextureName(L"map") + ->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, + eMaterial_map) + ->setDescriptionId(IDS_ITEM_MAP) + ->setUseDescriptionId(IDS_DESC_MAP); - Item::flintAndSteel = ( new FlintAndSteelItem(3) ) ->setTextureName(L"flintAndSteel")->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, eMaterial_flintandsteel)->setDescriptionId(IDS_ITEM_FLINT_AND_STEEL)->setUseDescriptionId(IDS_DESC_FLINTANDSTEEL); - Item::apple = ( new FoodItem(4, 4, FoodConstants::FOOD_SATURATION_LOW, false) ) ->setTextureName(L"apple")->setDescriptionId(IDS_ITEM_APPLE)->setUseDescriptionId(IDS_DESC_APPLE); - Item::coal = ( new CoalItem(7) ) ->setTextureName(L"coal")->setDescriptionId(IDS_ITEM_COAL)->setUseDescriptionId(IDS_DESC_COAL); - Item::diamond = ( new Item(8) ) ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_diamond)->setTextureName(L"diamond")->setDescriptionId(IDS_ITEM_DIAMOND)->setUseDescriptionId(IDS_DESC_DIAMONDS); - Item::stick = ( new Item(24) ) ->setTextureName(L"stick")->handEquipped()->setDescriptionId(IDS_ITEM_STICK)->setUseDescriptionId(IDS_DESC_STICK); - Item::mushroomStew = ( new BowlFoodItem(26, 6) ) ->setTextureName(L"mushroomStew")->setDescriptionId(IDS_ITEM_MUSHROOM_STEW)->setUseDescriptionId(IDS_DESC_MUSHROOMSTEW); + Item::flintAndSteel = + (new FlintAndSteelItem(3)) + ->setTextureName(L"flintAndSteel") + ->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, + eMaterial_flintandsteel) + ->setDescriptionId(IDS_ITEM_FLINT_AND_STEEL) + ->setUseDescriptionId(IDS_DESC_FLINTANDSTEEL); + Item::apple = + (new FoodItem(4, 4, FoodConstants::FOOD_SATURATION_LOW, false)) + ->setTextureName(L"apple") + ->setDescriptionId(IDS_ITEM_APPLE) + ->setUseDescriptionId(IDS_DESC_APPLE); + Item::coal = (new CoalItem(7)) + ->setTextureName(L"coal") + ->setDescriptionId(IDS_ITEM_COAL) + ->setUseDescriptionId(IDS_DESC_COAL); + Item::diamond = (new Item(8)) + ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, + eMaterial_diamond) + ->setTextureName(L"diamond") + ->setDescriptionId(IDS_ITEM_DIAMOND) + ->setUseDescriptionId(IDS_DESC_DIAMONDS); + Item::stick = (new Item(24)) + ->setTextureName(L"stick") + ->handEquipped() + ->setDescriptionId(IDS_ITEM_STICK) + ->setUseDescriptionId(IDS_DESC_STICK); + Item::mushroomStew = (new BowlFoodItem(26, 6)) + ->setTextureName(L"mushroomStew") + ->setDescriptionId(IDS_ITEM_MUSHROOM_STEW) + ->setUseDescriptionId(IDS_DESC_MUSHROOMSTEW); - Item::string = ( new TilePlanterItem(31, Tile::tripWire) ) ->setTextureName(L"string")->setDescriptionId(IDS_ITEM_STRING)->setUseDescriptionId(IDS_DESC_STRING); - Item::feather = ( new Item(32) ) ->setTextureName(L"feather")->setDescriptionId(IDS_ITEM_FEATHER)->setUseDescriptionId(IDS_DESC_FEATHER); - Item::sulphur = ( new Item(33) ) ->setTextureName(L"sulphur")->setDescriptionId(IDS_ITEM_SULPHUR)->setUseDescriptionId(IDS_DESC_SULPHUR)->setPotionBrewingFormula(PotionBrewing::MOD_GUNPOWDER); + Item::string = (new TilePlanterItem(31, Tile::tripWire)) + ->setTextureName(L"string") + ->setDescriptionId(IDS_ITEM_STRING) + ->setUseDescriptionId(IDS_DESC_STRING); + Item::feather = (new Item(32)) + ->setTextureName(L"feather") + ->setDescriptionId(IDS_ITEM_FEATHER) + ->setUseDescriptionId(IDS_DESC_FEATHER); + Item::sulphur = (new Item(33)) + ->setTextureName(L"sulphur") + ->setDescriptionId(IDS_ITEM_SULPHUR) + ->setUseDescriptionId(IDS_DESC_SULPHUR) + ->setPotionBrewingFormula(PotionBrewing::MOD_GUNPOWDER); + Item::seeds_wheat = (new SeedItem(39, Tile::crops_Id, Tile::farmland_Id)) + ->setTextureName(L"seeds") + ->setDescriptionId(IDS_ITEM_WHEAT_SEEDS) + ->setUseDescriptionId(IDS_DESC_WHEAT_SEEDS); + Item::wheat = (new Item(40)) + ->setTextureName(L"wheat") + ->setDescriptionId(IDS_ITEM_WHEAT) + ->setUseDescriptionId(IDS_DESC_WHEAT); + Item::bread = + (new FoodItem(41, 5, FoodConstants::FOOD_SATURATION_NORMAL, false)) + ->setTextureName(L"bread") + ->setDescriptionId(IDS_ITEM_BREAD) + ->setUseDescriptionId(IDS_DESC_BREAD); - Item::seeds_wheat = ( new SeedItem(39, Tile::crops_Id, Tile::farmland_Id) ) ->setTextureName(L"seeds")->setDescriptionId(IDS_ITEM_WHEAT_SEEDS)->setUseDescriptionId(IDS_DESC_WHEAT_SEEDS); - Item::wheat = ( new Item(40) ) ->setTextureName(L"wheat")->setDescriptionId(IDS_ITEM_WHEAT)->setUseDescriptionId(IDS_DESC_WHEAT); - Item::bread = ( new FoodItem(41, 5, FoodConstants::FOOD_SATURATION_NORMAL, false) ) ->setTextureName(L"bread")->setDescriptionId(IDS_ITEM_BREAD)->setUseDescriptionId(IDS_DESC_BREAD); + Item::flint = (new Item(62)) + ->setTextureName(L"flint") + ->setDescriptionId(IDS_ITEM_FLINT) + ->setUseDescriptionId(IDS_DESC_FLINT); + Item::porkChop_raw = + (new FoodItem(63, 3, FoodConstants::FOOD_SATURATION_LOW, true)) + ->setTextureName(L"porkchopRaw") + ->setDescriptionId(IDS_ITEM_PORKCHOP_RAW) + ->setUseDescriptionId(IDS_DESC_PORKCHOP_RAW); + Item::porkChop_cooked = + (new FoodItem(64, 8, FoodConstants::FOOD_SATURATION_GOOD, true)) + ->setTextureName(L"porkchopCooked") + ->setDescriptionId(IDS_ITEM_PORKCHOP_COOKED) + ->setUseDescriptionId(IDS_DESC_PORKCHOP_COOKED); + Item::painting = (new HangingEntityItem(65, eTYPE_PAINTING)) + ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, + eMaterial_cloth) + ->setTextureName(L"painting") + ->setDescriptionId(IDS_ITEM_PAINTING) + ->setUseDescriptionId(IDS_DESC_PICTURE); + Item::apple_gold = + (new GoldenAppleItem(66, 4, FoodConstants::FOOD_SATURATION_SUPERNATURAL, + false)) + ->setCanAlwaysEat() + ->setEatEffect(MobEffect::regeneration->id, 5, 0, 1.0f) + ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit, + eMaterial_apple) + ->setTextureName(L"appleGold") + ->setDescriptionId( + IDS_ITEM_APPLE_GOLD); //->setUseDescriptionId(IDS_DESC_GOLDENAPPLE); - Item::flint = ( new Item(62) ) ->setTextureName(L"flint")->setDescriptionId(IDS_ITEM_FLINT)->setUseDescriptionId(IDS_DESC_FLINT); - Item::porkChop_raw = ( new FoodItem(63, 3, FoodConstants::FOOD_SATURATION_LOW, true) ) ->setTextureName(L"porkchopRaw")->setDescriptionId(IDS_ITEM_PORKCHOP_RAW)->setUseDescriptionId(IDS_DESC_PORKCHOP_RAW); - Item::porkChop_cooked = ( new FoodItem(64, 8, FoodConstants::FOOD_SATURATION_GOOD, true) ) ->setTextureName(L"porkchopCooked")->setDescriptionId(IDS_ITEM_PORKCHOP_COOKED)->setUseDescriptionId(IDS_DESC_PORKCHOP_COOKED); - Item::painting = ( new HangingEntityItem(65,eTYPE_PAINTING) ) ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, eMaterial_cloth)->setTextureName(L"painting")->setDescriptionId(IDS_ITEM_PAINTING)->setUseDescriptionId(IDS_DESC_PICTURE); + Item::sign = (new SignItem(67)) + ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, + eMaterial_wood) + ->setTextureName(L"sign") + ->setDescriptionId(IDS_ITEM_SIGN) + ->setUseDescriptionId(IDS_DESC_SIGN); - Item::apple_gold = ( new GoldenAppleItem(66, 4, FoodConstants::FOOD_SATURATION_SUPERNATURAL, false) )->setCanAlwaysEat()->setEatEffect(MobEffect::regeneration->id, 5, 0, 1.0f) - ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit,eMaterial_apple)->setTextureName(L"appleGold")->setDescriptionId(IDS_ITEM_APPLE_GOLD);//->setUseDescriptionId(IDS_DESC_GOLDENAPPLE); + Item::minecart = (new MinecartItem(72, Minecart::RIDEABLE)) + ->setTextureName(L"minecart") + ->setDescriptionId(IDS_ITEM_MINECART) + ->setUseDescriptionId(IDS_DESC_MINECART); + Item::saddle = (new SaddleItem(73)) + ->setTextureName(L"saddle") + ->setDescriptionId(IDS_ITEM_SADDLE) + ->setUseDescriptionId(IDS_DESC_SADDLE); + Item::redStone = (new RedStoneItem(75)) + ->setTextureName(L"redstone") + ->setDescriptionId(IDS_ITEM_REDSTONE) + ->setUseDescriptionId(IDS_DESC_REDSTONE_DUST) + ->setPotionBrewingFormula(PotionBrewing::MOD_REDSTONE); + Item::snowBall = (new SnowballItem(76)) + ->setTextureName(L"snowball") + ->setDescriptionId(IDS_ITEM_SNOWBALL) + ->setUseDescriptionId(IDS_DESC_SNOWBALL); - Item::sign = ( new SignItem(67) ) ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, eMaterial_wood)->setTextureName(L"sign")->setDescriptionId(IDS_ITEM_SIGN)->setUseDescriptionId(IDS_DESC_SIGN); - + Item::boat = (new BoatItem(77)) + ->setTextureName(L"boat") + ->setDescriptionId(IDS_ITEM_BOAT) + ->setUseDescriptionId(IDS_DESC_BOAT); + Item::leather = (new Item(78)) + ->setTextureName(L"leather") + ->setDescriptionId(IDS_ITEM_LEATHER) + ->setUseDescriptionId(IDS_DESC_LEATHER); + Item::brick = (new Item(80)) + ->setTextureName(L"brick") + ->setDescriptionId(IDS_ITEM_BRICK) + ->setUseDescriptionId(IDS_DESC_BRICK); + Item::clay = (new Item(81)) + ->setTextureName(L"clay") + ->setDescriptionId(IDS_ITEM_CLAY) + ->setUseDescriptionId(IDS_DESC_CLAY); + Item::reeds = (new TilePlanterItem(82, Tile::reeds)) + ->setTextureName(L"reeds") + ->setDescriptionId(IDS_ITEM_REEDS) + ->setUseDescriptionId(IDS_DESC_REEDS); + Item::paper = (new Item(83)) + ->setTextureName(L"paper") + ->setDescriptionId(IDS_ITEM_PAPER) + ->setUseDescriptionId(IDS_DESC_PAPER); + Item::book = (new BookItem(84)) + ->setTextureName(L"book") + ->setDescriptionId(IDS_ITEM_BOOK) + ->setUseDescriptionId(IDS_DESC_BOOK); + Item::slimeBall = (new Item(85)) + ->setTextureName(L"slimeball") + ->setDescriptionId(IDS_ITEM_SLIMEBALL) + ->setUseDescriptionId(IDS_DESC_SLIMEBALL); + Item::minecart_chest = + (new MinecartItem(86, Minecart::CHEST)) + ->setTextureName(L"minecartChest") + ->setDescriptionId(IDS_ITEM_MINECART_CHEST) + ->setUseDescriptionId(IDS_DESC_MINECARTWITHCHEST); + Item::minecart_furnace = + (new MinecartItem(87, Minecart::FURNACE)) + ->setTextureName(L"minecartFurnace") + ->setDescriptionId(IDS_ITEM_MINECART_FURNACE) + ->setUseDescriptionId(IDS_DESC_MINECARTWITHFURNACE); + Item::egg = (new EggItem(88)) + ->setTextureName(L"egg") + ->setDescriptionId(IDS_ITEM_EGG) + ->setUseDescriptionId(IDS_DESC_EGG); + Item::fishingRod = + (FishingRodItem*)(new FishingRodItem(90)) + ->setBaseItemTypeAndMaterial(eBaseItemType_rod, eMaterial_wood) + ->setTextureName(L"fishingRod") + ->setDescriptionId(IDS_ITEM_FISHING_ROD) + ->setUseDescriptionId(IDS_DESC_FISHINGROD); + Item::yellowDust = + (new Item(92)) + ->setTextureName(L"yellowDust") + ->setDescriptionId(IDS_ITEM_YELLOW_DUST) + ->setUseDescriptionId(IDS_DESC_YELLOW_DUST) + ->setPotionBrewingFormula(PotionBrewing::MOD_GLOWSTONE); + Item::fish_raw = + (new FoodItem(93, 2, FoodConstants::FOOD_SATURATION_LOW, false)) + ->setTextureName(L"fishRaw") + ->setDescriptionId(IDS_ITEM_FISH_RAW) + ->setUseDescriptionId(IDS_DESC_FISH_RAW); + Item::fish_cooked = + (new FoodItem(94, 5, FoodConstants::FOOD_SATURATION_NORMAL, false)) + ->setTextureName(L"fishCooked") + ->setDescriptionId(IDS_ITEM_FISH_COOKED) + ->setUseDescriptionId(IDS_DESC_FISH_COOKED); - Item::minecart = ( new MinecartItem(72, Minecart::RIDEABLE) ) ->setTextureName(L"minecart")->setDescriptionId(IDS_ITEM_MINECART)->setUseDescriptionId(IDS_DESC_MINECART); - Item::saddle = ( new SaddleItem(73) ) ->setTextureName(L"saddle")->setDescriptionId(IDS_ITEM_SADDLE)->setUseDescriptionId(IDS_DESC_SADDLE); - Item::redStone = ( new RedStoneItem(75) ) ->setTextureName(L"redstone")->setDescriptionId(IDS_ITEM_REDSTONE)->setUseDescriptionId(IDS_DESC_REDSTONE_DUST)->setPotionBrewingFormula(PotionBrewing::MOD_REDSTONE); - Item::snowBall = ( new SnowballItem(76) ) ->setTextureName(L"snowball")->setDescriptionId(IDS_ITEM_SNOWBALL)->setUseDescriptionId(IDS_DESC_SNOWBALL); + Item::dye_powder = + (new DyePowderItem(95)) + ->setBaseItemTypeAndMaterial(eBaseItemType_dyepowder, eMaterial_dye) + ->setTextureName(L"dyePowder") + ->setDescriptionId(IDS_ITEM_DYE_POWDER) + ->setUseDescriptionId(-1); - Item::boat = ( new BoatItem(77) ) ->setTextureName(L"boat")->setDescriptionId(IDS_ITEM_BOAT)->setUseDescriptionId(IDS_DESC_BOAT); + Item::bone = (new Item(96)) + ->setTextureName(L"bone") + ->setDescriptionId(IDS_ITEM_BONE) + ->handEquipped() + ->setUseDescriptionId(IDS_DESC_BONE); + Item::sugar = (new Item(97)) + ->setTextureName(L"sugar") + ->setDescriptionId(IDS_ITEM_SUGAR) + ->setUseDescriptionId(IDS_DESC_SUGAR) + ->setPotionBrewingFormula(PotionBrewing::MOD_SUGAR); + // 4J-PB - changing the cake to be stackable - Jens ok'ed this 23/10/12 + // Item::cake = ( new TilePlanterItem(98, Tile::cake) + // )->setMaxStackSize(1)->setIcon(13, + // 1)->setDescriptionId(IDS_ITEM_CAKE)->setUseDescriptionId(IDS_DESC_CAKE); + Item::cake = (new TilePlanterItem(98, Tile::cake)) + ->setTextureName(L"cake") + ->setDescriptionId(IDS_ITEM_CAKE) + ->setUseDescriptionId(IDS_DESC_CAKE); - Item::leather = ( new Item(78) ) ->setTextureName(L"leather")->setDescriptionId(IDS_ITEM_LEATHER)->setUseDescriptionId(IDS_DESC_LEATHER); - Item::brick = ( new Item(80) ) ->setTextureName(L"brick")->setDescriptionId(IDS_ITEM_BRICK)->setUseDescriptionId(IDS_DESC_BRICK); - Item::clay = ( new Item(81) ) ->setTextureName(L"clay")->setDescriptionId(IDS_ITEM_CLAY)->setUseDescriptionId(IDS_DESC_CLAY); - Item::reeds = ( new TilePlanterItem(82, Tile::reeds) ) ->setTextureName(L"reeds")->setDescriptionId(IDS_ITEM_REEDS)->setUseDescriptionId(IDS_DESC_REEDS); - Item::paper = ( new Item(83) ) ->setTextureName(L"paper")->setDescriptionId(IDS_ITEM_PAPER)->setUseDescriptionId(IDS_DESC_PAPER); - Item::book = ( new BookItem(84) ) ->setTextureName(L"book")->setDescriptionId(IDS_ITEM_BOOK)->setUseDescriptionId(IDS_DESC_BOOK); - Item::slimeBall = ( new Item(85) ) ->setTextureName(L"slimeball")->setDescriptionId(IDS_ITEM_SLIMEBALL)->setUseDescriptionId(IDS_DESC_SLIMEBALL); - Item::minecart_chest = ( new MinecartItem(86, Minecart::CHEST) ) ->setTextureName(L"minecartChest")->setDescriptionId(IDS_ITEM_MINECART_CHEST)->setUseDescriptionId(IDS_DESC_MINECARTWITHCHEST); - Item::minecart_furnace = ( new MinecartItem(87, Minecart::FURNACE) )->setTextureName(L"minecartFurnace")->setDescriptionId(IDS_ITEM_MINECART_FURNACE)->setUseDescriptionId(IDS_DESC_MINECARTWITHFURNACE); - Item::egg = ( new EggItem(88) ) ->setTextureName(L"egg")->setDescriptionId(IDS_ITEM_EGG)->setUseDescriptionId(IDS_DESC_EGG); - Item::fishingRod = (FishingRodItem *)( new FishingRodItem(90) ) ->setBaseItemTypeAndMaterial(eBaseItemType_rod, eMaterial_wood)->setTextureName(L"fishingRod")->setDescriptionId(IDS_ITEM_FISHING_ROD)->setUseDescriptionId(IDS_DESC_FISHINGROD); - Item::yellowDust = ( new Item(92) ) ->setTextureName(L"yellowDust")->setDescriptionId(IDS_ITEM_YELLOW_DUST)->setUseDescriptionId(IDS_DESC_YELLOW_DUST)->setPotionBrewingFormula(PotionBrewing::MOD_GLOWSTONE); - Item::fish_raw = ( new FoodItem(93, 2, FoodConstants::FOOD_SATURATION_LOW, false) ) ->setTextureName(L"fishRaw")->setDescriptionId(IDS_ITEM_FISH_RAW)->setUseDescriptionId(IDS_DESC_FISH_RAW); - Item::fish_cooked = ( new FoodItem(94, 5, FoodConstants::FOOD_SATURATION_NORMAL, false) ) ->setTextureName(L"fishCooked")->setDescriptionId(IDS_ITEM_FISH_COOKED)->setUseDescriptionId(IDS_DESC_FISH_COOKED); + Item::bed = (new BedItem(99)) + ->setMaxStackSize(1) + ->setTextureName(L"bed") + ->setDescriptionId(IDS_ITEM_BED) + ->setUseDescriptionId(IDS_DESC_BED); - Item::dye_powder = ( new DyePowderItem(95) ) ->setBaseItemTypeAndMaterial(eBaseItemType_dyepowder, eMaterial_dye)->setTextureName(L"dyePowder")->setDescriptionId(IDS_ITEM_DYE_POWDER)->setUseDescriptionId(-1); + Item::diode = (new TilePlanterItem(100, (Tile*)Tile::diode_off)) + ->setTextureName(L"diode") + ->setDescriptionId(IDS_ITEM_DIODE) + ->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER); + Item::cookie = + (new FoodItem(101, 2, FoodConstants::FOOD_SATURATION_POOR, false)) + ->setTextureName(L"cookie") + ->setDescriptionId(IDS_ITEM_COOKIE) + ->setUseDescriptionId(IDS_DESC_COOKIE); - Item::bone = ( new Item(96) ) ->setTextureName(L"bone")->setDescriptionId(IDS_ITEM_BONE)->handEquipped()->setUseDescriptionId(IDS_DESC_BONE); - Item::sugar = ( new Item(97) ) ->setTextureName(L"sugar")->setDescriptionId(IDS_ITEM_SUGAR)->setUseDescriptionId(IDS_DESC_SUGAR)->setPotionBrewingFormula(PotionBrewing::MOD_SUGAR); - // 4J-PB - changing the cake to be stackable - Jens ok'ed this 23/10/12 - //Item::cake = ( new TilePlanterItem(98, Tile::cake) )->setMaxStackSize(1)->setIcon(13, 1)->setDescriptionId(IDS_ITEM_CAKE)->setUseDescriptionId(IDS_DESC_CAKE); - Item::cake = ( new TilePlanterItem(98, Tile::cake) ) ->setTextureName(L"cake")->setDescriptionId(IDS_ITEM_CAKE)->setUseDescriptionId(IDS_DESC_CAKE); + Item::shears = (ShearsItem*)(new ShearsItem(103)) + ->setTextureName(L"shears") + ->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, + eMaterial_shears) + ->setDescriptionId(IDS_ITEM_SHEARS) + ->setUseDescriptionId(IDS_DESC_SHEARS); - Item::bed = ( new BedItem(99) ) ->setMaxStackSize(1)->setTextureName(L"bed")->setDescriptionId(IDS_ITEM_BED)->setUseDescriptionId(IDS_DESC_BED); + Item::melon = + (new FoodItem(104, 2, FoodConstants::FOOD_SATURATION_LOW, false)) + ->setTextureName(L"melon") + ->setDescriptionId(IDS_ITEM_MELON_SLICE) + ->setUseDescriptionId(IDS_DESC_MELON_SLICE); - Item::diode = ( new TilePlanterItem(100, (Tile *)Tile::diode_off) ) ->setTextureName(L"diode")->setDescriptionId(IDS_ITEM_DIODE)->setUseDescriptionId(IDS_DESC_REDSTONEREPEATER); - Item::cookie = ( new FoodItem(101, 2, FoodConstants::FOOD_SATURATION_POOR, false) ) ->setTextureName(L"cookie")->setDescriptionId(IDS_ITEM_COOKIE)->setUseDescriptionId(IDS_DESC_COOKIE); + Item::seeds_pumpkin = + (new SeedItem(105, Tile::pumpkinStem_Id, Tile::farmland_Id)) + ->setTextureName(L"seeds_pumpkin") + ->setBaseItemTypeAndMaterial(eBaseItemType_seed, eMaterial_pumpkin) + ->setDescriptionId(IDS_ITEM_PUMPKIN_SEEDS) + ->setUseDescriptionId(IDS_DESC_PUMPKIN_SEEDS); + Item::seeds_melon = + (new SeedItem(106, Tile::melonStem_Id, Tile::farmland_Id)) + ->setTextureName(L"seeds_melon") + ->setBaseItemTypeAndMaterial(eBaseItemType_seed, eMaterial_melon) + ->setDescriptionId(IDS_ITEM_MELON_SEEDS) + ->setUseDescriptionId(IDS_DESC_MELON_SEEDS); + Item::beef_raw = + (new FoodItem(107, 3, FoodConstants::FOOD_SATURATION_LOW, true)) + ->setTextureName(L"beefRaw") + ->setDescriptionId(IDS_ITEM_BEEF_RAW) + ->setUseDescriptionId(IDS_DESC_BEEF_RAW); + Item::beef_cooked = + (new FoodItem(108, 8, FoodConstants::FOOD_SATURATION_GOOD, true)) + ->setTextureName(L"beefCooked") + ->setDescriptionId(IDS_ITEM_BEEF_COOKED) + ->setUseDescriptionId(IDS_DESC_BEEF_COOKED); + Item::chicken_raw = + (new FoodItem(109, 2, FoodConstants::FOOD_SATURATION_LOW, true)) + ->setEatEffect(MobEffect::hunger->id, 30, 0, .3f) + ->setTextureName(L"chickenRaw") + ->setDescriptionId(IDS_ITEM_CHICKEN_RAW) + ->setUseDescriptionId(IDS_DESC_CHICKEN_RAW); + Item::chicken_cooked = + (new FoodItem(110, 6, FoodConstants::FOOD_SATURATION_NORMAL, true)) + ->setTextureName(L"chickenCooked") + ->setDescriptionId(IDS_ITEM_CHICKEN_COOKED) + ->setUseDescriptionId(IDS_DESC_CHICKEN_COOKED); + Item::rotten_flesh = + (new FoodItem(111, 4, FoodConstants::FOOD_SATURATION_POOR, true)) + ->setEatEffect(MobEffect::hunger->id, 30, 0, .8f) + ->setTextureName(L"rottenFlesh") + ->setDescriptionId(IDS_ITEM_ROTTEN_FLESH) + ->setUseDescriptionId(IDS_DESC_ROTTEN_FLESH); - Item::shears = (ShearsItem *)( new ShearsItem(103) ) ->setTextureName(L"shears")->setBaseItemTypeAndMaterial(eBaseItemType_devicetool, eMaterial_shears)->setDescriptionId(IDS_ITEM_SHEARS)->setUseDescriptionId(IDS_DESC_SHEARS); + Item::enderPearl = (new EnderpearlItem(112)) + ->setTextureName(L"enderPearl") + ->setDescriptionId(IDS_ITEM_ENDER_PEARL) + ->setUseDescriptionId(IDS_DESC_ENDER_PEARL); - Item::melon = (new FoodItem(104, 2, FoodConstants::FOOD_SATURATION_LOW, false)) ->setTextureName(L"melon")->setDescriptionId(IDS_ITEM_MELON_SLICE)->setUseDescriptionId(IDS_DESC_MELON_SLICE); + Item::blazeRod = (new Item(113)) + ->setTextureName(L"blazeRod") + ->setDescriptionId(IDS_ITEM_BLAZE_ROD) + ->setUseDescriptionId(IDS_DESC_BLAZE_ROD) + ->handEquipped(); + Item::ghastTear = + (new Item(114)) + ->setTextureName(L"ghastTear") + ->setDescriptionId(IDS_ITEM_GHAST_TEAR) + ->setUseDescriptionId(IDS_DESC_GHAST_TEAR) + ->setPotionBrewingFormula(PotionBrewing::MOD_GHASTTEARS); + Item::goldNugget = + (new Item(115)) + ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_gold) + ->setTextureName(L"goldNugget") + ->setDescriptionId(IDS_ITEM_GOLD_NUGGET) + ->setUseDescriptionId(IDS_DESC_GOLD_NUGGET); - Item::seeds_pumpkin = (new SeedItem(105, Tile::pumpkinStem_Id, Tile::farmland_Id)) ->setTextureName(L"seeds_pumpkin")->setBaseItemTypeAndMaterial(eBaseItemType_seed, eMaterial_pumpkin)->setDescriptionId(IDS_ITEM_PUMPKIN_SEEDS)->setUseDescriptionId(IDS_DESC_PUMPKIN_SEEDS); - Item::seeds_melon = (new SeedItem(106, Tile::melonStem_Id, Tile::farmland_Id)) ->setTextureName(L"seeds_melon")->setBaseItemTypeAndMaterial(eBaseItemType_seed, eMaterial_melon)->setDescriptionId(IDS_ITEM_MELON_SEEDS)->setUseDescriptionId(IDS_DESC_MELON_SEEDS); + Item::netherStalkSeeds = + (new SeedItem(116, Tile::netherStalk_Id, Tile::hellSand_Id)) + ->setTextureName(L"netherStalkSeeds") + ->setDescriptionId(IDS_ITEM_NETHER_STALK_SEEDS) + ->setUseDescriptionId(IDS_DESC_NETHER_STALK_SEEDS) + ->setPotionBrewingFormula(PotionBrewing::MOD_NETHERWART); - Item::beef_raw = (new FoodItem(107, 3, FoodConstants::FOOD_SATURATION_LOW, true)) ->setTextureName(L"beefRaw")->setDescriptionId(IDS_ITEM_BEEF_RAW)->setUseDescriptionId(IDS_DESC_BEEF_RAW); - Item::beef_cooked = (new FoodItem(108, 8, FoodConstants::FOOD_SATURATION_GOOD, true))->setTextureName(L"beefCooked")->setDescriptionId(IDS_ITEM_BEEF_COOKED)->setUseDescriptionId(IDS_DESC_BEEF_COOKED); - Item::chicken_raw = (new FoodItem(109, 2, FoodConstants::FOOD_SATURATION_LOW, true))->setEatEffect(MobEffect::hunger->id, 30, 0, .3f)->setTextureName(L"chickenRaw")->setDescriptionId(IDS_ITEM_CHICKEN_RAW)->setUseDescriptionId(IDS_DESC_CHICKEN_RAW); - Item::chicken_cooked = (new FoodItem(110, 6, FoodConstants::FOOD_SATURATION_NORMAL, true))->setTextureName(L"chickenCooked")->setDescriptionId(IDS_ITEM_CHICKEN_COOKED)->setUseDescriptionId(IDS_DESC_CHICKEN_COOKED); - Item::rotten_flesh = (new FoodItem(111, 4, FoodConstants::FOOD_SATURATION_POOR, true))->setEatEffect(MobEffect::hunger->id, 30, 0, .8f)->setTextureName(L"rottenFlesh")->setDescriptionId(IDS_ITEM_ROTTEN_FLESH)->setUseDescriptionId(IDS_DESC_ROTTEN_FLESH); + Item::potion = (PotionItem*)((new PotionItem(117)) + ->setTextureName(L"potion") + ->setDescriptionId(IDS_ITEM_POTION) + ->setUseDescriptionId(IDS_DESC_POTION)); + Item::glassBottle = + (new BottleItem(118)) + ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_glass) + ->setTextureName(L"glassBottle") + ->setDescriptionId(IDS_ITEM_GLASS_BOTTLE) + ->setUseDescriptionId(IDS_DESC_GLASS_BOTTLE); - Item::enderPearl = (new EnderpearlItem(112)) ->setTextureName(L"enderPearl")->setDescriptionId(IDS_ITEM_ENDER_PEARL)->setUseDescriptionId(IDS_DESC_ENDER_PEARL); + Item::spiderEye = + (new FoodItem(119, 2, FoodConstants::FOOD_SATURATION_GOOD, false)) + ->setEatEffect(MobEffect::poison->id, 5, 0, 1.0f) + ->setTextureName(L"spiderEye") + ->setDescriptionId(IDS_ITEM_SPIDER_EYE) + ->setUseDescriptionId(IDS_DESC_SPIDER_EYE) + ->setPotionBrewingFormula(PotionBrewing::MOD_SPIDEREYE); + Item::fermentedSpiderEye = + (new Item(120)) + ->setTextureName(L"fermentedSpiderEye") + ->setDescriptionId(IDS_ITEM_FERMENTED_SPIDER_EYE) + ->setUseDescriptionId(IDS_DESC_FERMENTED_SPIDER_EYE) + ->setPotionBrewingFormula(PotionBrewing::MOD_FERMENTEDEYE); - Item::blazeRod = (new Item(113) ) ->setTextureName(L"blazeRod")->setDescriptionId(IDS_ITEM_BLAZE_ROD)->setUseDescriptionId(IDS_DESC_BLAZE_ROD)->handEquipped(); - Item::ghastTear = (new Item(114) ) ->setTextureName(L"ghastTear")->setDescriptionId(IDS_ITEM_GHAST_TEAR)->setUseDescriptionId(IDS_DESC_GHAST_TEAR)->setPotionBrewingFormula(PotionBrewing::MOD_GHASTTEARS); - Item::goldNugget = (new Item(115) ) ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_gold)->setTextureName(L"goldNugget")->setDescriptionId(IDS_ITEM_GOLD_NUGGET)->setUseDescriptionId(IDS_DESC_GOLD_NUGGET); + Item::blazePowder = + (new Item(121)) + ->setTextureName(L"blazePowder") + ->setDescriptionId(IDS_ITEM_BLAZE_POWDER) + ->setUseDescriptionId(IDS_DESC_BLAZE_POWDER) + ->setPotionBrewingFormula(PotionBrewing::MOD_BLAZEPOWDER); + Item::magmaCream = + (new Item(122)) + ->setTextureName(L"magmaCream") + ->setDescriptionId(IDS_ITEM_MAGMA_CREAM) + ->setUseDescriptionId(IDS_DESC_MAGMA_CREAM) + ->setPotionBrewingFormula(PotionBrewing::MOD_MAGMACREAM); - Item::netherStalkSeeds = (new SeedItem(116, Tile::netherStalk_Id, Tile::hellSand_Id) ) ->setTextureName(L"netherStalkSeeds")->setDescriptionId(IDS_ITEM_NETHER_STALK_SEEDS)->setUseDescriptionId(IDS_DESC_NETHER_STALK_SEEDS)->setPotionBrewingFormula(PotionBrewing::MOD_NETHERWART); + Item::brewingStand = + (new TilePlanterItem(123, Tile::brewingStand)) + ->setBaseItemTypeAndMaterial(eBaseItemType_device, eMaterial_blaze) + ->setTextureName(L"brewingStand") + ->setDescriptionId(IDS_ITEM_BREWING_STAND) + ->setUseDescriptionId(IDS_DESC_BREWING_STAND); + Item::cauldron = + (new TilePlanterItem(124, Tile::cauldron)) + ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_iron) + ->setTextureName(L"cauldron") + ->setDescriptionId(IDS_ITEM_CAULDRON) + ->setUseDescriptionId(IDS_DESC_CAULDRON); + Item::eyeOfEnder = (new EnderEyeItem(125)) + ->setBaseItemTypeAndMaterial( + eBaseItemType_pockettool, eMaterial_ender) + ->setTextureName(L"eyeOfEnder") + ->setDescriptionId(IDS_ITEM_EYE_OF_ENDER) + ->setUseDescriptionId(IDS_DESC_EYE_OF_ENDER); + Item::speckledMelon = + (new Item(126)) + ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit, + eMaterial_melon) + ->setTextureName(L"speckledMelon") + ->setDescriptionId(IDS_ITEM_SPECKLED_MELON) + ->setUseDescriptionId(IDS_DESC_SPECKLED_MELON) + ->setPotionBrewingFormula(PotionBrewing::MOD_SPECKLEDMELON); - Item::potion = (PotionItem *) ( ( new PotionItem(117) ) ->setTextureName(L"potion")->setDescriptionId(IDS_ITEM_POTION)->setUseDescriptionId(IDS_DESC_POTION) ); - Item::glassBottle = (new BottleItem(118) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_glass)->setTextureName(L"glassBottle")->setDescriptionId(IDS_ITEM_GLASS_BOTTLE)->setUseDescriptionId(IDS_DESC_GLASS_BOTTLE); + Item::monsterPlacer = (new MonsterPlacerItem(127)) + ->setTextureName(L"monsterPlacer") + ->setDescriptionId(IDS_ITEM_MONSTER_SPAWNER) + ->setUseDescriptionId(IDS_DESC_MONSTER_SPAWNER); - Item::spiderEye = (new FoodItem(119, 2, FoodConstants::FOOD_SATURATION_GOOD, false) ) ->setEatEffect(MobEffect::poison->id, 5, 0, 1.0f)->setTextureName(L"spiderEye")->setDescriptionId(IDS_ITEM_SPIDER_EYE)->setUseDescriptionId(IDS_DESC_SPIDER_EYE)->setPotionBrewingFormula(PotionBrewing::MOD_SPIDEREYE); - Item::fermentedSpiderEye = (new Item(120) ) ->setTextureName(L"fermentedSpiderEye")->setDescriptionId(IDS_ITEM_FERMENTED_SPIDER_EYE)->setUseDescriptionId(IDS_DESC_FERMENTED_SPIDER_EYE)->setPotionBrewingFormula(PotionBrewing::MOD_FERMENTEDEYE); + // 4J Stu - Brought this forward + Item::expBottle = (new ExperienceItem(128)) + ->setTextureName(L"expBottle") + ->setDescriptionId(IDS_ITEM_EXP_BOTTLE) + ->setUseDescriptionId(IDS_DESC_EXP_BOTTLE); - Item::blazePowder = (new Item(121) ) ->setTextureName(L"blazePowder")->setDescriptionId(IDS_ITEM_BLAZE_POWDER)->setUseDescriptionId(IDS_DESC_BLAZE_POWDER)->setPotionBrewingFormula(PotionBrewing::MOD_BLAZEPOWDER); - Item::magmaCream = (new Item(122) ) ->setTextureName(L"magmaCream")->setDescriptionId(IDS_ITEM_MAGMA_CREAM)->setUseDescriptionId(IDS_DESC_MAGMA_CREAM)->setPotionBrewingFormula(PotionBrewing::MOD_MAGMACREAM); + Item::record_01 = (new RecordingItem(2000, L"13")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_01) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_02 = (new RecordingItem(2001, L"cat")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_02) + ->setUseDescriptionId(IDS_DESC_RECORD); - Item::brewingStand = (new TilePlanterItem(123, Tile::brewingStand) ) ->setBaseItemTypeAndMaterial(eBaseItemType_device, eMaterial_blaze)->setTextureName(L"brewingStand")->setDescriptionId(IDS_ITEM_BREWING_STAND)->setUseDescriptionId(IDS_DESC_BREWING_STAND); - Item::cauldron = (new TilePlanterItem(124, Tile::cauldron) ) ->setBaseItemTypeAndMaterial(eBaseItemType_utensil, eMaterial_iron)->setTextureName(L"cauldron")->setDescriptionId(IDS_ITEM_CAULDRON)->setUseDescriptionId(IDS_DESC_CAULDRON); - Item::eyeOfEnder = (new EnderEyeItem(125) ) ->setBaseItemTypeAndMaterial(eBaseItemType_pockettool, eMaterial_ender)->setTextureName(L"eyeOfEnder")->setDescriptionId(IDS_ITEM_EYE_OF_ENDER)->setUseDescriptionId(IDS_DESC_EYE_OF_ENDER); - Item::speckledMelon = (new Item(126) ) ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit, eMaterial_melon)->setTextureName(L"speckledMelon")->setDescriptionId(IDS_ITEM_SPECKLED_MELON)->setUseDescriptionId(IDS_DESC_SPECKLED_MELON)->setPotionBrewingFormula(PotionBrewing::MOD_SPECKLEDMELON); + // 4J - new records brought forward from 1.2.3 + Item::record_03 = (new RecordingItem(2002, L"blocks")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_03) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_04 = (new RecordingItem(2003, L"chirp")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_04) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_05 = (new RecordingItem(2004, L"far")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_05) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_06 = (new RecordingItem(2005, L"mall")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_06) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_07 = (new RecordingItem(2006, L"mellohi")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_07) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_09 = (new RecordingItem(2007, L"stal")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_08) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_10 = (new RecordingItem(2008, L"strad")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_09) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_11 = (new RecordingItem(2009, L"ward")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_10) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_12 = (new RecordingItem(2010, L"11")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_11) + ->setUseDescriptionId(IDS_DESC_RECORD); + Item::record_08 = (new RecordingItem(2011, L"where are we now")) + ->setTextureName(L"record") + ->setDescriptionId(IDS_ITEM_RECORD_12) + ->setUseDescriptionId(IDS_DESC_RECORD); - Item::monsterPlacer = (new MonsterPlacerItem(127)) ->setTextureName(L"monsterPlacer")->setDescriptionId(IDS_ITEM_MONSTER_SPAWNER)->setUseDescriptionId(IDS_DESC_MONSTER_SPAWNER); + // TU9 + // putting the fire charge in as a torch, so that it stacks without being + // near the middle of the selection boxes + Item::fireball = + (new FireChargeItem(129)) + ->setBaseItemTypeAndMaterial(eBaseItemType_torch, eMaterial_setfire) + ->setTextureName(L"fireball") + ->setDescriptionId(IDS_ITEM_FIREBALL) + ->setUseDescriptionId(IDS_DESC_FIREBALL); + Item::frame = (new HangingEntityItem(133, eTYPE_ITEM_FRAME)) + ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, + eMaterial_glass) + ->setTextureName(L"frame") + ->setDescriptionId(IDS_ITEM_ITEMFRAME) + ->setUseDescriptionId(IDS_DESC_ITEMFRAME); + Item::netherbrick = (new Item(149)) + ->setTextureName(L"netherbrick") + ->setDescriptionId(IDS_ITEM_NETHERBRICK) + ->setUseDescriptionId(IDS_DESC_ITEM_NETHERBRICK); - // 4J Stu - Brought this forward - Item::expBottle = (new ExperienceItem(128)) ->setTextureName(L"expBottle")->setDescriptionId(IDS_ITEM_EXP_BOTTLE)->setUseDescriptionId(IDS_DESC_EXP_BOTTLE); + // TU12 + Item::skull = (new SkullItem(141)) + ->setTextureName(L"skull") + ->setDescriptionId(IDS_ITEM_SKULL) + ->setUseDescriptionId(IDS_DESC_SKULL); - Item::record_01 = ( new RecordingItem(2000, L"13") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_01)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_02 = ( new RecordingItem(2001, L"cat") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_02)->setUseDescriptionId(IDS_DESC_RECORD); + // TU14 + // Item::writingBook = (new WritingBookItem(130))->setIcon(11, + // 11)->setDescriptionId("writingBook"); Item::writtenBook = (new + // WrittenBookItem(131))->setIcon(12, 11)->setDescriptionId("writtenBook"); - // 4J - new records brought forward from 1.2.3 - Item::record_03 = ( new RecordingItem(2002, L"blocks") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_03)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_04 = ( new RecordingItem(2003, L"chirp") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_04)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_05 = ( new RecordingItem(2004, L"far") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_05)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_06 = ( new RecordingItem(2005, L"mall") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_06)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_07 = ( new RecordingItem(2006, L"mellohi") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_07)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_09 = ( new RecordingItem(2007, L"stal") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_08)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_10 = ( new RecordingItem(2008, L"strad") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_09)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_11 = ( new RecordingItem(2009, L"ward") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_10)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_12 = ( new RecordingItem(2010, L"11") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_11)->setUseDescriptionId(IDS_DESC_RECORD); - Item::record_08 = ( new RecordingItem(2011, L"where are we now") ) ->setTextureName(L"record")->setDescriptionId(IDS_ITEM_RECORD_12)->setUseDescriptionId(IDS_DESC_RECORD); + Item::emerald = (new Item(132)) + ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, + eMaterial_emerald) + ->setTextureName(L"emerald") + ->setDescriptionId(IDS_ITEM_EMERALD) + ->setUseDescriptionId(IDS_DESC_EMERALD); + Item::flowerPot = (new TilePlanterItem(134, Tile::flowerPot)) + ->setTextureName(L"flowerPot") + ->setDescriptionId(IDS_FLOWERPOT) + ->setUseDescriptionId(IDS_DESC_FLOWERPOT); - // TU9 - // putting the fire charge in as a torch, so that it stacks without being near the middle of the selection boxes - Item::fireball = (new FireChargeItem(129)) ->setBaseItemTypeAndMaterial(eBaseItemType_torch, eMaterial_setfire)->setTextureName(L"fireball")->setDescriptionId(IDS_ITEM_FIREBALL)->setUseDescriptionId(IDS_DESC_FIREBALL); - Item::frame = (new HangingEntityItem(133,eTYPE_ITEM_FRAME)) ->setBaseItemTypeAndMaterial(eBaseItemType_HangingItem, eMaterial_glass)->setTextureName(L"frame")->setDescriptionId(IDS_ITEM_ITEMFRAME)->setUseDescriptionId(IDS_DESC_ITEMFRAME); - Item::netherbrick = (new Item(149)) ->setTextureName(L"netherbrick")->setDescriptionId(IDS_ITEM_NETHERBRICK)->setUseDescriptionId(IDS_DESC_ITEM_NETHERBRICK); + Item::carrots = + (new SeedFoodItem(135, 4, FoodConstants::FOOD_SATURATION_NORMAL, + Tile::carrots_Id, Tile::farmland_Id)) + ->setTextureName(L"carrots") + ->setDescriptionId(IDS_CARROTS) + ->setUseDescriptionId(IDS_DESC_CARROTS); + Item::potato = (new SeedFoodItem(136, 1, FoodConstants::FOOD_SATURATION_LOW, + Tile::potatoes_Id, Tile::farmland_Id)) + ->setTextureName(L"potato") + ->setDescriptionId(IDS_POTATO) + ->setUseDescriptionId(IDS_DESC_POTATO); + Item::potatoBaked = + (new FoodItem(137, 6, FoodConstants::FOOD_SATURATION_NORMAL, false)) + ->setTextureName(L"potatoBaked") + ->setDescriptionId(IDS_ITEM_POTATO_BAKED) + ->setUseDescriptionId(IDS_DESC_POTATO_BAKED); + Item::potatoPoisonous = + (new FoodItem(138, 2, FoodConstants::FOOD_SATURATION_LOW, false)) + ->setEatEffect(MobEffect::poison->id, 5, 0, .6f) + ->setTextureName(L"potatoPoisonous") + ->setDescriptionId(IDS_ITEM_POTATO_POISONOUS) + ->setUseDescriptionId(IDS_DESC_POTATO_POISONOUS); - // TU12 - Item::skull = (new SkullItem(141)) ->setTextureName(L"skull")->setDescriptionId(IDS_ITEM_SKULL)->setUseDescriptionId(IDS_DESC_SKULL); + Item::carrotGolden = + (new FoodItem(140, 6, FoodConstants::FOOD_SATURATION_SUPERNATURAL, + false)) + ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit, + eMaterial_carrot) + ->setTextureName(L"carrotGolden") + ->setPotionBrewingFormula(PotionBrewing::MOD_GOLDENCARROT) + ->setDescriptionId(IDS_ITEM_CARROT_GOLDEN) + ->setUseDescriptionId(IDS_DESC_CARROT_GOLDEN); - // TU14 - //Item::writingBook = (new WritingBookItem(130))->setIcon(11, 11)->setDescriptionId("writingBook"); - //Item::writtenBook = (new WrittenBookItem(131))->setIcon(12, 11)->setDescriptionId("writtenBook"); + Item::carrotOnAStick = + (new CarrotOnAStickItem(142)) + ->setBaseItemTypeAndMaterial(eBaseItemType_rod, eMaterial_carrot) + ->setTextureName(L"carrotOnAStick") + ->setDescriptionId(IDS_ITEM_CARROT_ON_A_STICK) + ->setUseDescriptionId(IDS_DESC_CARROT_ON_A_STICK); + Item::pumpkinPie = + (new FoodItem(144, 8, FoodConstants::FOOD_SATURATION_LOW, false)) + ->setTextureName(L"pumpkinPie") + ->setDescriptionId(IDS_ITEM_PUMPKIN_PIE) + ->setUseDescriptionId(IDS_DESC_PUMPKIN_PIE); - Item::emerald = (new Item(132)) ->setBaseItemTypeAndMaterial(eBaseItemType_treasure, eMaterial_emerald)->setTextureName(L"emerald")->setDescriptionId(IDS_ITEM_EMERALD)->setUseDescriptionId(IDS_DESC_EMERALD); - - Item::flowerPot = (new TilePlanterItem(134, Tile::flowerPot)) ->setTextureName(L"flowerPot")->setDescriptionId(IDS_FLOWERPOT)->setUseDescriptionId(IDS_DESC_FLOWERPOT); - - Item::carrots = (new SeedFoodItem(135, 4, FoodConstants::FOOD_SATURATION_NORMAL, Tile::carrots_Id, Tile::farmland_Id)) ->setTextureName(L"carrots")->setDescriptionId(IDS_CARROTS)->setUseDescriptionId(IDS_DESC_CARROTS); - Item::potato = (new SeedFoodItem(136, 1, FoodConstants::FOOD_SATURATION_LOW, Tile::potatoes_Id, Tile::farmland_Id)) ->setTextureName(L"potato")->setDescriptionId(IDS_POTATO)->setUseDescriptionId(IDS_DESC_POTATO); - Item::potatoBaked = (new FoodItem(137, 6, FoodConstants::FOOD_SATURATION_NORMAL, false)) ->setTextureName(L"potatoBaked")->setDescriptionId(IDS_ITEM_POTATO_BAKED)->setUseDescriptionId(IDS_DESC_POTATO_BAKED); - Item::potatoPoisonous = (new FoodItem(138, 2, FoodConstants::FOOD_SATURATION_LOW, false)) ->setEatEffect(MobEffect::poison->id, 5, 0, .6f)->setTextureName(L"potatoPoisonous")->setDescriptionId(IDS_ITEM_POTATO_POISONOUS)->setUseDescriptionId(IDS_DESC_POTATO_POISONOUS); - - Item::carrotGolden = (new FoodItem(140, 6, FoodConstants::FOOD_SATURATION_SUPERNATURAL, false)) ->setBaseItemTypeAndMaterial(eBaseItemType_giltFruit, eMaterial_carrot)->setTextureName(L"carrotGolden")->setPotionBrewingFormula(PotionBrewing::MOD_GOLDENCARROT)->setDescriptionId(IDS_ITEM_CARROT_GOLDEN)->setUseDescriptionId(IDS_DESC_CARROT_GOLDEN); - - Item::carrotOnAStick = (new CarrotOnAStickItem(142)) ->setBaseItemTypeAndMaterial(eBaseItemType_rod, eMaterial_carrot)->setTextureName(L"carrotOnAStick")->setDescriptionId(IDS_ITEM_CARROT_ON_A_STICK)->setUseDescriptionId(IDS_DESC_CARROT_ON_A_STICK); - Item::pumpkinPie = (new FoodItem(144, 8, FoodConstants::FOOD_SATURATION_LOW, false)) ->setTextureName(L"pumpkinPie")->setDescriptionId(IDS_ITEM_PUMPKIN_PIE)->setUseDescriptionId(IDS_DESC_PUMPKIN_PIE); - - EnchantedBookItem::enchantedBook = (EnchantedBookItem *)(new EnchantedBookItem(147)) ->setMaxStackSize(1)->setTextureName(L"enchantedBook")->setDescriptionId(IDS_ITEM_ENCHANTED_BOOK)->setUseDescriptionId(IDS_DESC_ENCHANTED_BOOK); - Item::netherQuartz = (new Item(150))->setTextureName(L"netherquartz")->setDescriptionId(IDS_ITEM_NETHER_QUARTZ)->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ); + EnchantedBookItem::enchantedBook = + (EnchantedBookItem*)(new EnchantedBookItem(147)) + ->setMaxStackSize(1) + ->setTextureName(L"enchantedBook") + ->setDescriptionId(IDS_ITEM_ENCHANTED_BOOK) + ->setUseDescriptionId(IDS_DESC_ENCHANTED_BOOK); + Item::netherQuartz = (new Item(150)) + ->setTextureName(L"netherquartz") + ->setDescriptionId(IDS_ITEM_NETHER_QUARTZ) + ->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ); } +// 4J Stu - We need to do this after the staticCtor AND after staticCtors for +// other class eg Recipes +void Item::staticInit() { Stats::buildItemStats(); } -// 4J Stu - We need to do this after the staticCtor AND after staticCtors for other class -// eg Recipes -void Item::staticInit() -{ - Stats::buildItemStats(); -} +_Tier::Tier(int level, int uses, float speed, int damage, int enchantmentValue) + : level(level), + uses(uses), + speed(speed), + damage(damage), + enchantmentValue(enchantmentValue) {} +int _Tier::getUses() const { return uses; } -_Tier::Tier(int level, int uses, float speed, int damage, int enchantmentValue) : -level( level ), - uses( uses ), - speed( speed ), - damage( damage ), - enchantmentValue( enchantmentValue ) -{ +float _Tier::getSpeed() const { return speed; } + +int _Tier::getAttackDamageBonus() const { return damage; } + +int _Tier::getLevel() const { return level; } + +int _Tier::getEnchantmentValue() const { return enchantmentValue; } + +int _Tier::getTierItemId() const { + if (this == Tier::WOOD) { + return Tile::wood_Id; + } else if (this == Tier::STONE) { + return Tile::stoneBrick_Id; + } else if (this == Tier::GOLD) { + return Item::goldIngot_Id; + } else if (this == Tier::IRON) { + return Item::ironIngot_Id; + } else if (this == Tier::DIAMOND) { + return Item::diamond_Id; + } + return 0; } +Item::Item(int id) : id(256 + id) { + maxStackSize = Item::MAX_STACK_SIZE; + maxDamage = 0; + icon = NULL; + m_handEquipped = false; + m_isStackedByData = false; -int _Tier::getUses() const -{ - return uses; + craftingRemainingItem = NULL; + potionBrewingFormula = L""; + + m_iMaterial = eMaterial_undefined; + m_iBaseItemType = eBaseItemType_undefined; + m_textureName = L""; + + // TODO Init this string + // string descriptionId; + + // this->id = 256 + id; + if (items[256 + id] != NULL) { + app.DebugPrintf("CONFLICT @ %d", id); + } + + items[256 + id] = this; } -float _Tier::getSpeed() const -{ - return speed; +// 4J-PB - adding so we can class different items together for the new crafting +// menu so pickaxe_stone would get tagged with pickaxe and stone +Item* Item::setBaseItemTypeAndMaterial(int iType, int iMaterial) { + this->m_iBaseItemType = iType; + this->m_iMaterial = iMaterial; + return this; } -int _Tier::getAttackDamageBonus() const -{ - return damage; +int Item::getBaseItemType() { return this->m_iBaseItemType; } + +int Item::getMaterial() { return this->m_iMaterial; } + +Item* Item::setTextureName(const std::wstring& name) { + m_textureName = name; + + return this; } -int _Tier::getLevel() const -{ - return level; +Item* Item::setMaxStackSize(int max) { + maxStackSize = max; + return this; } -int _Tier::getEnchantmentValue() const -{ - return enchantmentValue; +int Item::getIconType() { return Icon::TYPE_ITEM; } + +Icon* Item::getIcon(int auxValue) { return icon; } + +Icon* Item::getIcon(std::shared_ptr itemInstance) { + return getIcon(itemInstance->getAuxValue()); } -int _Tier::getTierItemId() const -{ - if (this == Tier::WOOD) - { - return Tile::wood_Id; - } - else if (this == Tier::STONE) - { - return Tile::stoneBrick_Id; - } - else if (this == Tier::GOLD) - { - return Item::goldIngot_Id; - } - else if (this == Tier::IRON) - { - return Item::ironIngot_Id; - } - else if (this == Tier::DIAMOND) - { - return Item::diamond_Id; - } - return 0; +const bool Item::useOn(std::shared_ptr itemInstance, Level* level, + int x, int y, int z, int face, bool bTestUseOnOnly) { + return false; } -Item::Item(int id) : id( 256 + id ) -{ - maxStackSize = Item::MAX_STACK_SIZE; - maxDamage = 0; - icon = NULL; - m_handEquipped = false; - m_isStackedByData = false; - - craftingRemainingItem = NULL; - potionBrewingFormula = L""; - - m_iMaterial=eMaterial_undefined; - m_iBaseItemType=eBaseItemType_undefined; - m_textureName = L""; - - // TODO Init this string - //string descriptionId; - - //this->id = 256 + id; - if (items[256 + id] != NULL) - { - app.DebugPrintf("CONFLICT @ %d" , id); - } - - items[256 + id] = this; +bool Item::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + return false; } -// 4J-PB - adding so we can class different items together for the new crafting menu -// so pickaxe_stone would get tagged with pickaxe and stone -Item *Item::setBaseItemTypeAndMaterial(int iType,int iMaterial) -{ - this->m_iBaseItemType = iType; - this->m_iMaterial = iMaterial; - return this; +float Item::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + return 1; } -int Item::getBaseItemType() -{ - return this->m_iBaseItemType; +bool Item::TestUse(Level* level, std::shared_ptr player) { + return false; } -int Item::getMaterial() -{ - return this->m_iMaterial; +std::shared_ptr Item::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + return itemInstance; } -Item *Item::setTextureName(const std::wstring &name) -{ - m_textureName = name; - - return this; +std::shared_ptr Item::useTimeDepleted( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + return itemInstance; } -Item *Item::setMaxStackSize(int max) -{ - maxStackSize = max; - return this; +int Item::getMaxStackSize() { return maxStackSize; } + +int Item::getLevelDataForAuxValue(int auxValue) { return 0; } + +bool Item::isStackedByData() { return m_isStackedByData; } + +Item* Item::setStackedByData(bool isStackedByData) { + this->m_isStackedByData = isStackedByData; + return this; } -int Item::getIconType() -{ - return Icon::TYPE_ITEM; +int Item::getMaxDamage() { return maxDamage; } + +Item* Item::setMaxDamage(int maxDamage) { + this->maxDamage = maxDamage; + return this; } -Icon *Item::getIcon(int auxValue) -{ - return icon; -} +bool Item::canBeDepleted() { return maxDamage > 0 && !m_isStackedByData; } -Icon *Item::getIcon(std::shared_ptr itemInstance) -{ - return getIcon(itemInstance->getAuxValue()); -} - -const bool Item::useOn(std::shared_ptr itemInstance, Level *level, int x, int y, int z, int face, bool bTestUseOnOnly) -{ - return false; -} - -bool Item::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - return false; -} - -float Item::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - return 1; -} - -bool Item::TestUse(Level *level, std::shared_ptr player) -{ - return false; -} - -std::shared_ptr Item::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - return itemInstance; -} - -std::shared_ptr Item::useTimeDepleted(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - return itemInstance; -} - -int Item::getMaxStackSize() -{ - return maxStackSize; -} - -int Item::getLevelDataForAuxValue(int auxValue) -{ - return 0; -} - -bool Item::isStackedByData() -{ - return m_isStackedByData; -} - - -Item *Item::setStackedByData(bool isStackedByData) -{ - this->m_isStackedByData = isStackedByData; - return this; -} - - -int Item::getMaxDamage() -{ - return maxDamage; -} - - -Item *Item::setMaxDamage(int maxDamage) -{ - this->maxDamage = maxDamage; - return this; -} - - -bool Item::canBeDepleted() -{ - return maxDamage > 0 && !m_isStackedByData; +/** + * Returns true when the item was used to deal more than default damage + * + * @param itemInstance + * @param mob + * @param attacker + * @return + */ +bool Item::hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, std::shared_ptr attacker) { + return false; } /** -* Returns true when the item was used to deal more than default damage -* -* @param itemInstance -* @param mob -* @param attacker -* @return -*/ -bool Item::hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker) -{ - return false; + * Returns true when the item was used to mine more efficiently + * + * @param itemInstance + * @param tile + * @param x + * @param y + * @param z + * @param owner + * @return + */ +bool Item::mineBlock(std::shared_ptr itemInstance, Level* level, + int tile, int x, int y, int z, + std::shared_ptr owner) { + return false; } -/** -* Returns true when the item was used to mine more efficiently -* -* @param itemInstance -* @param tile -* @param x -* @param y -* @param z -* @param owner -* @return -*/ -bool Item::mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner) -{ - return false; +int Item::getAttackDamage(std::shared_ptr entity) { return 1; } + +bool Item::canDestroySpecial(Tile* tile) { return false; } + +bool Item::interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob) { + return false; } -int Item::getAttackDamage(std::shared_ptr entity) -{ - return 1; +Item* Item::handEquipped() { + this->m_handEquipped = true; + return this; } -bool Item::canDestroySpecial(Tile *tile) -{ - return false; +bool Item::isHandEquipped() { return m_handEquipped; } + +bool Item::isMirroredArt() { return false; } + +Item* Item::setDescriptionId(unsigned int id) { + this->descriptionId = id; + return this; } -bool Item::interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob) -{ - return false; +const wchar_t* Item::getDescription() { + return app.GetString(getDescriptionId()); + // return I18n::get(getDescriptionId()); } -Item *Item::handEquipped() -{ - this->m_handEquipped = true; - return this; +const wchar_t* Item::getDescription(std::shared_ptr instance) { + return app.GetString(getDescriptionId(instance)); + // return I18n::get(getDescriptionId(instance)); } -bool Item::isHandEquipped() -{ - return m_handEquipped; +unsigned int Item::getDescriptionId(int iData /*= -1*/) { + return descriptionId; } -bool Item::isMirroredArt() -{ - return false; +unsigned int Item::getDescriptionId(std::shared_ptr instance) { + return descriptionId; } -Item *Item::setDescriptionId(unsigned int id) -{ - this->descriptionId = id; - return this; +Item* Item::setUseDescriptionId(unsigned int id) { + this->useDescriptionId = id; + return this; } -const wchar_t *Item::getDescription() -{ - return app.GetString(getDescriptionId()); - //return I18n::get(getDescriptionId()); +unsigned int Item::getUseDescriptionId() { return useDescriptionId; } + +unsigned int Item::getUseDescriptionId(std::shared_ptr instance) { + return useDescriptionId; } -const wchar_t *Item::getDescription(std::shared_ptr instance) -{ - return app.GetString(getDescriptionId(instance)); - //return I18n::get(getDescriptionId(instance)); +Item* Item::setCraftingRemainingItem(Item* craftingRemainingItem) { + this->craftingRemainingItem = craftingRemainingItem; + return this; } -unsigned int Item::getDescriptionId(int iData /*= -1*/) -{ - return descriptionId; +bool Item::shouldMoveCraftingResultToInventory( + std::shared_ptr instance) { + // Default is good for the vast majority of items + return true; } -unsigned int Item::getDescriptionId(std::shared_ptr instance) -{ - return descriptionId; +bool Item::shouldOverrideMultiplayerNBT() { return true; } + +Item* Item::getCraftingRemainingItem() { return craftingRemainingItem; } + +bool Item::hasCraftingRemainingItem() { return craftingRemainingItem != NULL; } + +std::wstring Item::getName() { + return L""; // I18n::get(getDescriptionId() + L".name"); } -Item *Item::setUseDescriptionId(unsigned int id) -{ - this->useDescriptionId = id; - return this; +int Item::getColor(std::shared_ptr item, int spriteLayer) { + return 0xffffff; } -unsigned int Item::getUseDescriptionId() -{ - return useDescriptionId; +void Item::inventoryTick(std::shared_ptr itemInstance, + Level* level, std::shared_ptr owner, int slot, + bool selected) {} + +void Item::onCraftedBy(std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) {} + +bool Item::isComplex() { return false; } + +UseAnim Item::getUseAnimation(std::shared_ptr itemInstance) { + return UseAnim_none; } -unsigned int Item::getUseDescriptionId(std::shared_ptr instance) -{ - return useDescriptionId; +int Item::getUseDuration(std::shared_ptr itemInstance) { + return 0; } -Item *Item::setCraftingRemainingItem(Item *craftingRemainingItem) -{ - this->craftingRemainingItem = craftingRemainingItem; - return this; +void Item::releaseUsing(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player, + int durationLeft) {} + +Item* Item::setPotionBrewingFormula(const std::wstring& potionBrewingFormula) { + this->potionBrewingFormula = potionBrewingFormula; + return this; } -bool Item::shouldMoveCraftingResultToInventory(std::shared_ptr instance) -{ - // Default is good for the vast majority of items - return true; +std::wstring Item::getPotionBrewingFormula() { return potionBrewingFormula; } + +bool Item::hasPotionBrewingFormula() { return !potionBrewingFormula.empty(); } + +void Item::appendHoverText(std::shared_ptr itemInstance, + std::shared_ptr player, + std::vector* lines, bool advanced, + std::vector& unformattedStrings) {} + +std::wstring Item::getHoverName(std::shared_ptr itemInstance) { + // String elementName = ("" + + // Language.getInstance().getElementName(getDescription(itemInstance))).trim(); + // return elementName; + return app.GetString(getDescriptionId(itemInstance)); } -bool Item::shouldOverrideMultiplayerNBT() -{ - return true; +bool Item::isFoil(std::shared_ptr itemInstance) { + if (itemInstance->isEnchanted()) return true; + return false; } -Item *Item::getCraftingRemainingItem() -{ - return craftingRemainingItem; +const Rarity* Item::getRarity(std::shared_ptr itemInstance) { + if (itemInstance->isEnchanted()) return Rarity::rare; + return Rarity::common; } -bool Item::hasCraftingRemainingItem() -{ - return craftingRemainingItem != NULL; +bool Item::isEnchantable(std::shared_ptr itemInstance) { + return getMaxStackSize() == 1 && canBeDepleted(); } -std::wstring Item::getName() -{ - return L"";//I18n::get(getDescriptionId() + L".name"); +HitResult* Item::getPlayerPOVHitResult(Level* level, + std::shared_ptr player, + bool alsoPickLiquid) { + float a = 1; + + float xRot = player->xRotO + (player->xRot - player->xRotO) * a; + float yRot = player->yRotO + (player->yRot - player->yRotO) * a; + + double x = player->xo + (player->x - player->xo) * a; + double y = + player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; + double z = player->zo + (player->z - player->zo) * a; + + Vec3* from = Vec3::newTemp(x, y, z); + + float yCos = (float)cos(-yRot * Mth::RAD_TO_GRAD - PI); + float ySin = (float)sin(-yRot * Mth::RAD_TO_GRAD - PI); + float xCos = (float)-cos(-xRot * Mth::RAD_TO_GRAD); + float xSin = (float)sin(-xRot * Mth::RAD_TO_GRAD); + + float xa = ySin * xCos; + float ya = xSin; + float za = yCos * xCos; + + double range = 5; + Vec3* to = from->add(xa * range, ya * range, za * range); + return level->clip(from, to, alsoPickLiquid, !alsoPickLiquid); } -int Item::getColor(std::shared_ptr item, int spriteLayer) -{ - return 0xffffff; +int Item::getEnchantmentValue() { return 0; } + +bool Item::hasMultipleSpriteLayers() { return false; } + +Icon* Item::getLayerIcon(int auxValue, int spriteLayer) { + return getIcon(auxValue); } -void Item::inventoryTick(std::shared_ptr itemInstance, Level *level, std::shared_ptr owner, int slot, bool selected) { +bool Item::isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem) { + return false; } -void Item::onCraftedBy(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ +void Item::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(m_textureName); } -bool Item::isComplex() -{ - return false; -} - -UseAnim Item::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_none; -} - -int Item::getUseDuration(std::shared_ptr itemInstance) -{ - return 0; -} - -void Item::releaseUsing(std::shared_ptr itemInstance, Level *level, std::shared_ptr player, int durationLeft) -{ -} - -Item *Item::setPotionBrewingFormula(const std::wstring &potionBrewingFormula) -{ - this->potionBrewingFormula = potionBrewingFormula; - return this; -} - -std::wstring Item::getPotionBrewingFormula() -{ - return potionBrewingFormula; -} - -bool Item::hasPotionBrewingFormula() -{ - return !potionBrewingFormula.empty(); -} - -void Item::appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings) -{ -} - -std::wstring Item::getHoverName(std::shared_ptr itemInstance) -{ - //String elementName = ("" + Language.getInstance().getElementName(getDescription(itemInstance))).trim(); - //return elementName; - return app.GetString(getDescriptionId(itemInstance)); -} - -bool Item::isFoil(std::shared_ptr itemInstance) -{ - if (itemInstance->isEnchanted()) return true; - return false; -} - -const Rarity *Item::getRarity(std::shared_ptr itemInstance) -{ - if (itemInstance->isEnchanted()) return Rarity::rare; - return Rarity::common; -} - -bool Item::isEnchantable(std::shared_ptr itemInstance) -{ - return getMaxStackSize() == 1 && canBeDepleted(); -} - -HitResult *Item::getPlayerPOVHitResult(Level *level, std::shared_ptr player, bool alsoPickLiquid) -{ - float a = 1; - - float xRot = player->xRotO + (player->xRot - player->xRotO) * a; - float yRot = player->yRotO + (player->yRot - player->yRotO) * a; - - - double x = player->xo + (player->x - player->xo) * a; - double y = player->yo + (player->y - player->yo) * a + 1.62 - player->heightOffset; - double z = player->zo + (player->z - player->zo) * a; - - Vec3 *from = Vec3::newTemp(x, y, z); - - float yCos = (float) cos(-yRot * Mth::RAD_TO_GRAD - PI); - float ySin = (float) sin(-yRot * Mth::RAD_TO_GRAD - PI); - float xCos = (float) -cos(-xRot * Mth::RAD_TO_GRAD); - float xSin = (float) sin(-xRot * Mth::RAD_TO_GRAD); - - float xa = ySin * xCos; - float ya = xSin; - float za = yCos * xCos; - - double range = 5; - Vec3 *to = from->add(xa * range, ya * range, za * range); - return level->clip(from, to, alsoPickLiquid, !alsoPickLiquid); -} - -int Item::getEnchantmentValue() -{ - return 0; -} - -bool Item::hasMultipleSpriteLayers() -{ - return false; -} - -Icon *Item::getLayerIcon(int auxValue, int spriteLayer) -{ - return getIcon(auxValue); -} - -bool Item::isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem) -{ - return false; -} - -void Item::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(m_textureName); -} - - /* - 4J: These are necesary on the PS3. - (and 4 and Vita). + 4J: These are necesary on the PS3. + (and 4 and Vita). */ -#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined __linux__) -const int Item::shovel_iron_Id ; -const int Item::pickAxe_iron_Id ; -const int Item::hatchet_iron_Id ; -const int Item::flintAndSteel_Id ; -const int Item::apple_Id ; -const int Item::bow_Id ; -const int Item::arrow_Id ; -const int Item::coal_Id ; -const int Item::diamond_Id ; -const int Item::ironIngot_Id ; -const int Item::goldIngot_Id ; -const int Item::sword_iron_Id ; -const int Item::sword_wood_Id ; -const int Item::shovel_wood_Id ; -const int Item::pickAxe_wood_Id ; -const int Item::hatchet_wood_Id ; -const int Item::sword_stone_Id ; -const int Item::shovel_stone_Id ; -const int Item::pickAxe_stone_Id ; -const int Item::hatchet_stone_Id ; -const int Item::sword_diamond_Id ; -const int Item::shovel_diamond_Id ; -const int Item::pickAxe_diamond_Id ; -const int Item::hatchet_diamond_Id ; -const int Item::stick_Id ; -const int Item::bowl_Id ; -const int Item::mushroomStew_Id ; -const int Item::sword_gold_Id ; -const int Item::shovel_gold_Id ; -const int Item::pickAxe_gold_Id ; -const int Item::hatchet_gold_Id ; -const int Item::string_Id ; -const int Item::feather_Id ; -const int Item::sulphur_Id ; -const int Item::hoe_wood_Id ; -const int Item::hoe_stone_Id ; -const int Item::hoe_iron_Id ; -const int Item::hoe_diamond_Id ; -const int Item::hoe_gold_Id ; -const int Item::seeds_wheat_Id ; -const int Item::wheat_Id ; -const int Item::bread_Id ; -const int Item::helmet_cloth_Id ; -const int Item::chestplate_cloth_Id ; -const int Item::leggings_cloth_Id ; -const int Item::boots_cloth_Id ; -const int Item::helmet_chain_Id ; -const int Item::chestplate_chain_Id ; -const int Item::leggings_chain_Id ; -const int Item::boots_chain_Id ; -const int Item::helmet_iron_Id ; -const int Item::chestplate_iron_Id ; -const int Item::leggings_iron_Id ; -const int Item::boots_iron_Id ; -const int Item::helmet_diamond_Id ; +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined __linux__) +const int Item::shovel_iron_Id; +const int Item::pickAxe_iron_Id; +const int Item::hatchet_iron_Id; +const int Item::flintAndSteel_Id; +const int Item::apple_Id; +const int Item::bow_Id; +const int Item::arrow_Id; +const int Item::coal_Id; +const int Item::diamond_Id; +const int Item::ironIngot_Id; +const int Item::goldIngot_Id; +const int Item::sword_iron_Id; +const int Item::sword_wood_Id; +const int Item::shovel_wood_Id; +const int Item::pickAxe_wood_Id; +const int Item::hatchet_wood_Id; +const int Item::sword_stone_Id; +const int Item::shovel_stone_Id; +const int Item::pickAxe_stone_Id; +const int Item::hatchet_stone_Id; +const int Item::sword_diamond_Id; +const int Item::shovel_diamond_Id; +const int Item::pickAxe_diamond_Id; +const int Item::hatchet_diamond_Id; +const int Item::stick_Id; +const int Item::bowl_Id; +const int Item::mushroomStew_Id; +const int Item::sword_gold_Id; +const int Item::shovel_gold_Id; +const int Item::pickAxe_gold_Id; +const int Item::hatchet_gold_Id; +const int Item::string_Id; +const int Item::feather_Id; +const int Item::sulphur_Id; +const int Item::hoe_wood_Id; +const int Item::hoe_stone_Id; +const int Item::hoe_iron_Id; +const int Item::hoe_diamond_Id; +const int Item::hoe_gold_Id; +const int Item::seeds_wheat_Id; +const int Item::wheat_Id; +const int Item::bread_Id; +const int Item::helmet_cloth_Id; +const int Item::chestplate_cloth_Id; +const int Item::leggings_cloth_Id; +const int Item::boots_cloth_Id; +const int Item::helmet_chain_Id; +const int Item::chestplate_chain_Id; +const int Item::leggings_chain_Id; +const int Item::boots_chain_Id; +const int Item::helmet_iron_Id; +const int Item::chestplate_iron_Id; +const int Item::leggings_iron_Id; +const int Item::boots_iron_Id; +const int Item::helmet_diamond_Id; const int Item::chestplate_diamond_Id; -const int Item::leggings_diamond_Id ; -const int Item::boots_diamond_Id ; -const int Item::helmet_gold_Id ; -const int Item::chestplate_gold_Id ; -const int Item::leggings_gold_Id ; -const int Item::boots_gold_Id ; -const int Item::flint_Id ; -const int Item::porkChop_raw_Id ; -const int Item::porkChop_cooked_Id ; -const int Item::painting_Id ; -const int Item::apple_gold_Id ; -const int Item::sign_Id ; -const int Item::door_wood_Id ; -const int Item::bucket_empty_Id ; -const int Item::bucket_water_Id ; -const int Item::bucket_lava_Id ; -const int Item::minecart_Id ; -const int Item::saddle_Id ; -const int Item::door_iron_Id ; -const int Item::redStone_Id ; -const int Item::snowBall_Id ; -const int Item::boat_Id ; -const int Item::leather_Id ; -const int Item::milk_Id ; -const int Item::brick_Id ; -const int Item::clay_Id ; -const int Item::reeds_Id ; -const int Item::paper_Id ; -const int Item::book_Id ; -const int Item::slimeBall_Id ; -const int Item::minecart_chest_Id ; -const int Item::minecart_furnace_Id ; -const int Item::egg_Id ; -const int Item::compass_Id ; -const int Item::fishingRod_Id ; -const int Item::clock_Id ; -const int Item::yellowDust_Id ; -const int Item::fish_raw_Id ; -const int Item::fish_cooked_Id ; -const int Item::dye_powder_Id ; -const int Item::bone_Id ; -const int Item::sugar_Id ; -const int Item::cake_Id ; -const int Item::bed_Id ; -const int Item::diode_Id ; -const int Item::cookie_Id ; -const int Item::map_Id ; -const int Item::shears_Id ; -const int Item::melon_Id ; -const int Item::seeds_pumpkin_Id ; -const int Item::seeds_melon_Id ; -const int Item::beef_raw_Id ; -const int Item::beef_cooked_Id ; -const int Item::chicken_raw_Id ; -const int Item::chicken_cooked_Id ; -const int Item::rotten_flesh_Id ; -const int Item::enderPearl_Id ; -const int Item::blazeRod_Id ; -const int Item::ghastTear_Id ; -const int Item::goldNugget_Id ; -const int Item::netherStalkSeeds_Id ; -const int Item::potion_Id ; -const int Item::glassBottle_Id ; -const int Item::spiderEye_Id ; +const int Item::leggings_diamond_Id; +const int Item::boots_diamond_Id; +const int Item::helmet_gold_Id; +const int Item::chestplate_gold_Id; +const int Item::leggings_gold_Id; +const int Item::boots_gold_Id; +const int Item::flint_Id; +const int Item::porkChop_raw_Id; +const int Item::porkChop_cooked_Id; +const int Item::painting_Id; +const int Item::apple_gold_Id; +const int Item::sign_Id; +const int Item::door_wood_Id; +const int Item::bucket_empty_Id; +const int Item::bucket_water_Id; +const int Item::bucket_lava_Id; +const int Item::minecart_Id; +const int Item::saddle_Id; +const int Item::door_iron_Id; +const int Item::redStone_Id; +const int Item::snowBall_Id; +const int Item::boat_Id; +const int Item::leather_Id; +const int Item::milk_Id; +const int Item::brick_Id; +const int Item::clay_Id; +const int Item::reeds_Id; +const int Item::paper_Id; +const int Item::book_Id; +const int Item::slimeBall_Id; +const int Item::minecart_chest_Id; +const int Item::minecart_furnace_Id; +const int Item::egg_Id; +const int Item::compass_Id; +const int Item::fishingRod_Id; +const int Item::clock_Id; +const int Item::yellowDust_Id; +const int Item::fish_raw_Id; +const int Item::fish_cooked_Id; +const int Item::dye_powder_Id; +const int Item::bone_Id; +const int Item::sugar_Id; +const int Item::cake_Id; +const int Item::bed_Id; +const int Item::diode_Id; +const int Item::cookie_Id; +const int Item::map_Id; +const int Item::shears_Id; +const int Item::melon_Id; +const int Item::seeds_pumpkin_Id; +const int Item::seeds_melon_Id; +const int Item::beef_raw_Id; +const int Item::beef_cooked_Id; +const int Item::chicken_raw_Id; +const int Item::chicken_cooked_Id; +const int Item::rotten_flesh_Id; +const int Item::enderPearl_Id; +const int Item::blazeRod_Id; +const int Item::ghastTear_Id; +const int Item::goldNugget_Id; +const int Item::netherStalkSeeds_Id; +const int Item::potion_Id; +const int Item::glassBottle_Id; +const int Item::spiderEye_Id; const int Item::fermentedSpiderEye_Id; -const int Item::blazePowder_Id ; -const int Item::magmaCream_Id ; -const int Item::brewingStand_Id ; -const int Item::cauldron_Id ; -const int Item::eyeOfEnder_Id ; -const int Item::speckledMelon_Id ; -const int Item::monsterPlacer_Id ; -const int Item::expBottle_Id ; -const int Item::skull_Id ; -const int Item::record_01_Id ; -const int Item::record_02_Id ; -const int Item::record_03_Id ; -const int Item::record_04_Id ; -const int Item::record_05_Id ; -const int Item::record_06_Id ; -const int Item::record_07_Id ; -const int Item::record_09_Id ; -const int Item::record_10_Id ; -const int Item::record_11_Id ; -const int Item::record_12_Id ; -const int Item::record_08_Id ; -const int Item::fireball_Id ; -const int Item::itemFrame_Id ; -const int Item::netherbrick_Id ; -const int Item::emerald_Id ; -const int Item::flowerPot_Id ; -const int Item::carrots_Id ; -const int Item::potato_Id ; -const int Item::potatoBaked_Id ; -const int Item::potatoPoisonous_Id ; -const int Item::carrotGolden_Id ; -const int Item::carrotOnAStick_Id ; -const int Item::pumpkinPie_Id ; -const int Item::enchantedBook_Id ; -const int Item::netherQuartz_Id ; +const int Item::blazePowder_Id; +const int Item::magmaCream_Id; +const int Item::brewingStand_Id; +const int Item::cauldron_Id; +const int Item::eyeOfEnder_Id; +const int Item::speckledMelon_Id; +const int Item::monsterPlacer_Id; +const int Item::expBottle_Id; +const int Item::skull_Id; +const int Item::record_01_Id; +const int Item::record_02_Id; +const int Item::record_03_Id; +const int Item::record_04_Id; +const int Item::record_05_Id; +const int Item::record_06_Id; +const int Item::record_07_Id; +const int Item::record_09_Id; +const int Item::record_10_Id; +const int Item::record_11_Id; +const int Item::record_12_Id; +const int Item::record_08_Id; +const int Item::fireball_Id; +const int Item::itemFrame_Id; +const int Item::netherbrick_Id; +const int Item::emerald_Id; +const int Item::flowerPot_Id; +const int Item::carrots_Id; +const int Item::potato_Id; +const int Item::potatoBaked_Id; +const int Item::potatoPoisonous_Id; +const int Item::carrotGolden_Id; +const int Item::carrotOnAStick_Id; +const int Item::pumpkinPie_Id; +const int Item::enchantedBook_Id; +const int Item::netherQuartz_Id; #endif diff --git a/Minecraft.World/Items/Item.h b/Minecraft.World/Items/Item.h index 4a20b7602..2d6013284 100644 --- a/Minecraft.World/Items/Item.h +++ b/Minecraft.World/Items/Item.h @@ -1,7 +1,5 @@ #pragma once - - #include "../Containers/Container.h" #include "../Util/UseAnim.h" #include "../Util/Rarity.h" @@ -23,696 +21,722 @@ class EnchantedBookItem; #define ITEM_ICON_COLUMNS 16 - -class Item : public std::enable_shared_from_this -{ +class Item : public std::enable_shared_from_this { public: - static const int ITEM_NUM_COUNT = 32000; + static const int ITEM_NUM_COUNT = 32000; - static void staticCtor(); - static void staticInit(); + static void staticCtor(); + static void staticInit(); - // 4J-PB - added for new crafting menu - enum - { - eMaterial_undefined=0, - eMaterial_wood, - eMaterial_stone, - eMaterial_iron, - eMaterial_gold, - eMaterial_diamond, - eMaterial_cloth, - eMaterial_chain, // 4J Stu - It's available in creative in 1.8 - eMaterial_detector, - eMaterial_lapis, - eMaterial_music, - eMaterial_dye, - eMaterial_sand, - eMaterial_brick, - eMaterial_clay, - eMaterial_snow, - eMaterial_bow, - eMaterial_arrow, - eMaterial_compass, - eMaterial_clock, - eMaterial_map, - eMaterial_pumpkin, - eMaterial_glowstone, - eMaterial_water, - eMaterial_trap, - eMaterial_flintandsteel, - eMaterial_shears, - eMaterial_piston, - eMaterial_stickypiston, - eMaterial_gate, - eMaterial_stoneSmooth, - eMaterial_netherbrick, - eMaterial_ender, - eMaterial_glass, - eMaterial_blaze, - eMaterial_magic, - eMaterial_melon, - eMaterial_setfire, - eMaterial_sprucewood, - eMaterial_birchwood, - eMaterial_junglewood, - eMaterial_emerald, - eMaterial_quartz, - eMaterial_apple, - eMaterial_carrot - } - eMaterial; + // 4J-PB - added for new crafting menu + enum { + eMaterial_undefined = 0, + eMaterial_wood, + eMaterial_stone, + eMaterial_iron, + eMaterial_gold, + eMaterial_diamond, + eMaterial_cloth, + eMaterial_chain, // 4J Stu - It's available in creative in 1.8 + eMaterial_detector, + eMaterial_lapis, + eMaterial_music, + eMaterial_dye, + eMaterial_sand, + eMaterial_brick, + eMaterial_clay, + eMaterial_snow, + eMaterial_bow, + eMaterial_arrow, + eMaterial_compass, + eMaterial_clock, + eMaterial_map, + eMaterial_pumpkin, + eMaterial_glowstone, + eMaterial_water, + eMaterial_trap, + eMaterial_flintandsteel, + eMaterial_shears, + eMaterial_piston, + eMaterial_stickypiston, + eMaterial_gate, + eMaterial_stoneSmooth, + eMaterial_netherbrick, + eMaterial_ender, + eMaterial_glass, + eMaterial_blaze, + eMaterial_magic, + eMaterial_melon, + eMaterial_setfire, + eMaterial_sprucewood, + eMaterial_birchwood, + eMaterial_junglewood, + eMaterial_emerald, + eMaterial_quartz, + eMaterial_apple, + eMaterial_carrot + } eMaterial; - enum - { - eBaseItemType_undefined=0, - eBaseItemType_sword, - eBaseItemType_shovel, - eBaseItemType_pickaxe, - eBaseItemType_hatchet, - eBaseItemType_hoe, - eBaseItemType_door, - eBaseItemType_helmet, - eBaseItemType_chestplate, - eBaseItemType_leggings, - eBaseItemType_boots, - eBaseItemType_ingot, - eBaseItemType_rail, - eBaseItemType_block, - eBaseItemType_pressureplate, - eBaseItemType_stairs, - eBaseItemType_cloth, - eBaseItemType_dyepowder, - eBaseItemType_structwoodstuff, - eBaseItemType_structblock, - eBaseItemType_slab, - eBaseItemType_halfslab, - eBaseItemType_torch, - eBaseItemType_bow, - eBaseItemType_pockettool, - eBaseItemType_utensil, - eBaseItemType_piston, - eBaseItemType_devicetool, - eBaseItemType_fence, - eBaseItemType_device, - eBaseItemType_treasure, - eBaseItemType_seed, - eBaseItemType_HangingItem, - eBaseItemType_button, - eBaseItemType_chest, - eBaseItemType_rod, - eBaseItemType_giltFruit, - eBaseItemType_carpet, - eBaseItemType_MAXTYPES, - } - eBaseItemType; + enum { + eBaseItemType_undefined = 0, + eBaseItemType_sword, + eBaseItemType_shovel, + eBaseItemType_pickaxe, + eBaseItemType_hatchet, + eBaseItemType_hoe, + eBaseItemType_door, + eBaseItemType_helmet, + eBaseItemType_chestplate, + eBaseItemType_leggings, + eBaseItemType_boots, + eBaseItemType_ingot, + eBaseItemType_rail, + eBaseItemType_block, + eBaseItemType_pressureplate, + eBaseItemType_stairs, + eBaseItemType_cloth, + eBaseItemType_dyepowder, + eBaseItemType_structwoodstuff, + eBaseItemType_structblock, + eBaseItemType_slab, + eBaseItemType_halfslab, + eBaseItemType_torch, + eBaseItemType_bow, + eBaseItemType_pockettool, + eBaseItemType_utensil, + eBaseItemType_piston, + eBaseItemType_devicetool, + eBaseItemType_fence, + eBaseItemType_device, + eBaseItemType_treasure, + eBaseItemType_seed, + eBaseItemType_HangingItem, + eBaseItemType_button, + eBaseItemType_chest, + eBaseItemType_rod, + eBaseItemType_giltFruit, + eBaseItemType_carpet, + eBaseItemType_MAXTYPES, + } eBaseItemType; protected: - static const int ICON_COLUMNS = ITEM_ICON_COLUMNS; - static std::wstring ICON_DESCRIPTION_PREFIX; // 4J Stu - Was const but we have to static initialise it outside of this class + static const int ICON_COLUMNS = ITEM_ICON_COLUMNS; + static std::wstring + ICON_DESCRIPTION_PREFIX; // 4J Stu - Was const but we have to static + // initialise it outside of this class public: + class Tier { + public: + static const Tier* WOOD; // + static const Tier* STONE; // + static const Tier* IRON; // + static const Tier* DIAMOND; // + static const Tier* GOLD; - class Tier - { - public: - static const Tier *WOOD; // - static const Tier *STONE; // - static const Tier *IRON; // - static const Tier *DIAMOND; // - static const Tier *GOLD; + private: + const int level; + const int uses; + const float speed; + const int damage; + const int enchantmentValue; - private: - const int level; - const int uses; - const float speed; - const int damage; - const int enchantmentValue; + // 4J Stu - Had to make this public but was protected + // We shouldn't be creating these except the static initialisation + public: + Tier(int level, int uses, float speed, int damage, + int enchantmentValue); - // 4J Stu - Had to make this public but was protected - // We shouldn't be creating these except the static initialisation - public: - Tier(int level, int uses, float speed, int damage, int enchantmentValue); + public: + int getUses() const; - public: - int getUses() const; + float getSpeed() const; - float getSpeed() const; + int getAttackDamageBonus() const; - int getAttackDamageBonus() const; + int getLevel() const; - int getLevel() const; + int getEnchantmentValue() const; - int getEnchantmentValue() const; - - int getTierItemId() const; - }; + int getTierItemId() const; + }; protected: - static Random *random; + static Random* random; private: - static const int MAX_STACK_SIZE = Container::LARGE_MAX_STACK_SIZE; + static const int MAX_STACK_SIZE = Container::LARGE_MAX_STACK_SIZE; public: - static ItemArray items; - - static Item *shovel_iron; - static Item *pickAxe_iron; - static Item *hatchet_iron; - static Item *flintAndSteel; - static Item *apple; - static BowItem *bow; - static Item *arrow; - static Item *coal; - static Item *diamond; - static Item *ironIngot; - static Item *goldIngot; - static Item *sword_iron; - - static Item *sword_wood; - static Item *shovel_wood; - static Item *pickAxe_wood; - static Item *hatchet_wood; - - static Item *sword_stone; - static Item *shovel_stone; - static Item *pickAxe_stone; - static Item *hatchet_stone; - - static Item *sword_diamond; - static Item *shovel_diamond; - static Item *pickAxe_diamond; - static Item *hatchet_diamond; - - static Item *stick; - static Item *bowl; - static Item *mushroomStew; - - static Item *sword_gold; - static Item *shovel_gold; - static Item *pickAxe_gold; - static Item *hatchet_gold; - - static Item *string; - static Item *feather; - static Item *sulphur; - - static Item *hoe_wood; - static Item *hoe_stone; - static Item *hoe_iron; - static Item *hoe_diamond; - static Item *hoe_gold; - - static Item *seeds_wheat; - static Item *wheat; - static Item *bread; - - static ArmorItem *helmet_cloth; - static ArmorItem *chestplate_cloth; - static ArmorItem *leggings_cloth; - static ArmorItem *boots_cloth; - - static ArmorItem *helmet_chain; - static ArmorItem *chestplate_chain; - static ArmorItem *leggings_chain; - static ArmorItem *boots_chain; - - static ArmorItem *helmet_iron; - static ArmorItem *chestplate_iron; - static ArmorItem *leggings_iron; - static ArmorItem *boots_iron; - - static ArmorItem *helmet_diamond; - static ArmorItem *chestplate_diamond; - static ArmorItem *leggings_diamond; - static ArmorItem *boots_diamond; - - static ArmorItem *helmet_gold; - static ArmorItem *chestplate_gold; - static ArmorItem *leggings_gold; - static ArmorItem *boots_gold; - - static Item *flint; - static Item *porkChop_raw; - static Item *porkChop_cooked; - static Item *painting; - - static Item *apple_gold; - - static Item *sign; - static Item *door_wood; - - static Item *bucket_empty; - static Item *bucket_water; - static Item *bucket_lava; - - static Item *minecart; - static Item *saddle; - static Item *door_iron; - static Item *redStone; - static Item *snowBall; - - static Item *boat; - - static Item *leather; - static Item *milk; - static Item *brick; - static Item *clay; - static Item *reeds; - static Item *paper; - static Item *book; - static Item *slimeBall; - static Item *minecart_chest; - static Item *minecart_furnace; - static Item *egg; - static Item *compass; - static FishingRodItem *fishingRod; - static Item *clock; - static Item *yellowDust; - static Item *fish_raw; - static Item *fish_cooked; - - static Item *dye_powder; - static Item *bone; - static Item *sugar; - static Item *cake; - - static Item *bed; - - static Item *diode; - static Item *cookie; - - static MapItem *map; - - static ShearsItem *shears; - - static Item *melon; - - static Item *seeds_pumpkin; - static Item *seeds_melon; - - static Item *beef_raw; - static Item *beef_cooked; - static Item *chicken_raw; - static Item *chicken_cooked; - static Item *rotten_flesh; - - static Item *enderPearl; - - static Item *blazeRod; - static Item *ghastTear; - static Item *goldNugget; - - static Item *netherStalkSeeds; - - static PotionItem *potion; - static Item *glassBottle; - - static Item *spiderEye; - static Item *fermentedSpiderEye; - - static Item *blazePowder; - static Item *magmaCream; - - static Item *brewingStand; - static Item *cauldron; - static Item *eyeOfEnder; - static Item *speckledMelon; - - static Item *monsterPlacer; - - static Item *expBottle; - - static Item *skull; - - static Item *record_01; - static Item *record_02; - static Item *record_03; - static Item *record_04; - static Item *record_05; - static Item *record_06; - static Item *record_07; - static Item *record_08; - static Item *record_09; - static Item *record_10; - static Item *record_11; - static Item *record_12; - - // TU9 - static Item *fireball; - static Item *frame; - static Item *netherbrick; - - // TU14 - //static Item writingBook; - //static Item writtenBook; - - static Item *emerald; - - static Item *flowerPot; - - static Item *carrots; - static Item *potato; - static Item *potatoBaked; - static Item *potatoPoisonous; - - static Item *carrotGolden; - - static Item *carrotOnAStick; - static Item *pumpkinPie; - static Item *netherQuartz; - - static EnchantedBookItem *enchantedBook; - - - static const int shovel_iron_Id = 256; - static const int pickAxe_iron_Id = 257; - static const int hatchet_iron_Id = 258; - static const int flintAndSteel_Id = 259; - static const int apple_Id = 260; - static const int bow_Id = 261; - static const int arrow_Id = 262; - static const int coal_Id = 263; - static const int diamond_Id = 264; - static const int ironIngot_Id = 265; - static const int goldIngot_Id = 266; - static const int sword_iron_Id = 267; - static const int sword_wood_Id = 268; - static const int shovel_wood_Id = 269; - static const int pickAxe_wood_Id = 270; - static const int hatchet_wood_Id = 271; - static const int sword_stone_Id = 272; - static const int shovel_stone_Id = 273; - static const int pickAxe_stone_Id = 274; - static const int hatchet_stone_Id = 275; - static const int sword_diamond_Id = 276; - static const int shovel_diamond_Id = 277; - static const int pickAxe_diamond_Id = 278; - static const int hatchet_diamond_Id = 279; - static const int stick_Id = 280; - static const int bowl_Id = 281; - static const int mushroomStew_Id = 282; - static const int sword_gold_Id = 283; - static const int shovel_gold_Id = 284; - static const int pickAxe_gold_Id = 285; - static const int hatchet_gold_Id = 286; - static const int string_Id = 287; - static const int feather_Id = 288; - static const int sulphur_Id = 289; - static const int hoe_wood_Id = 290; - static const int hoe_stone_Id = 291; - static const int hoe_iron_Id = 292; - static const int hoe_diamond_Id = 293; - static const int hoe_gold_Id = 294; - static const int seeds_wheat_Id = 295; - static const int wheat_Id = 296; - static const int bread_Id = 297; - - static const int helmet_cloth_Id = 298; - static const int chestplate_cloth_Id = 299; - static const int leggings_cloth_Id = 300; - static const int boots_cloth_Id = 301; - - static const int helmet_chain_Id = 302; - static const int chestplate_chain_Id = 303; - static const int leggings_chain_Id = 304; - static const int boots_chain_Id = 305; - - static const int helmet_iron_Id = 306; - static const int chestplate_iron_Id = 307; - static const int leggings_iron_Id = 308; - static const int boots_iron_Id = 309; - - static const int helmet_diamond_Id = 310; - static const int chestplate_diamond_Id = 311; - static const int leggings_diamond_Id = 312; - static const int boots_diamond_Id = 313; - - static const int helmet_gold_Id = 314; - static const int chestplate_gold_Id = 315; - static const int leggings_gold_Id = 316; - static const int boots_gold_Id = 317; - - static const int flint_Id = 318; - static const int porkChop_raw_Id = 319; - static const int porkChop_cooked_Id = 320; - static const int painting_Id = 321; - static const int apple_gold_Id = 322; - static const int sign_Id = 323; - static const int door_wood_Id = 324; - static const int bucket_empty_Id = 325; - static const int bucket_water_Id = 326; - static const int bucket_lava_Id = 327; - static const int minecart_Id = 328; - static const int saddle_Id = 329; - static const int door_iron_Id = 330; - static const int redStone_Id = 331; - static const int snowBall_Id = 332; - static const int boat_Id = 333; - static const int leather_Id = 334; - static const int milk_Id = 335; - static const int brick_Id = 336; - static const int clay_Id = 337; - static const int reeds_Id = 338; - static const int paper_Id = 339; - static const int book_Id = 340; - static const int slimeBall_Id = 341; - static const int minecart_chest_Id = 342; - static const int minecart_furnace_Id = 343; - static const int egg_Id = 344; - static const int compass_Id = 345; - static const int fishingRod_Id = 346; - static const int clock_Id = 347; - static const int yellowDust_Id = 348; - static const int fish_raw_Id = 349; - static const int fish_cooked_Id = 350; - static const int dye_powder_Id = 351; - static const int bone_Id = 352; - static const int sugar_Id = 353; - static const int cake_Id = 354; - static const int bed_Id = 355; - static const int diode_Id = 356; - static const int cookie_Id = 357; - static const int map_Id = 358; - - // 1.7.3 - static const int shears_Id = 359; - - // 1.8.2 - static const int melon_Id = 360; - static const int seeds_pumpkin_Id = 361; - static const int seeds_melon_Id = 362; - static const int beef_raw_Id = 363; - static const int beef_cooked_Id = 364; - static const int chicken_raw_Id = 365; - static const int chicken_cooked_Id = 366; - static const int rotten_flesh_Id = 367; - static const int enderPearl_Id = 368; - - // 1.0.1 - static const int blazeRod_Id = 369; - static const int ghastTear_Id = 370; - static const int goldNugget_Id = 371; - static const int netherStalkSeeds_Id = 372; - static const int potion_Id = 373; - static const int glassBottle_Id = 374; - static const int spiderEye_Id = 375; - static const int fermentedSpiderEye_Id = 376; - static const int blazePowder_Id = 377; - static const int magmaCream_Id = 378; - static const int brewingStand_Id = 379; - static const int cauldron_Id = 380; - static const int eyeOfEnder_Id = 381; - static const int speckledMelon_Id = 382; - - // 1.1 - static const int monsterPlacer_Id = 383; - - static const int expBottle_Id = 384; - - // TU 12 - static const int skull_Id = 397; - - static const int record_01_Id = 2256; - static const int record_02_Id = 2257; - static const int record_03_Id = 2258; - static const int record_04_Id = 2259; - static const int record_05_Id = 2260; - static const int record_06_Id = 2261; - static const int record_07_Id = 2262; - static const int record_09_Id = 2263; - static const int record_10_Id = 2264; - static const int record_11_Id = 2265; - static const int record_12_Id = 2266; - - // 4J-PB - this one isn't playable in the PC game, but is fine in ours - static const int record_08_Id = 2267; - - // TU9 - static const int fireball_Id = 385; - static const int itemFrame_Id = 389; - static const int netherbrick_Id = 405; - - // TU14 - //static const int writingBook_Id = 130; - //static const int writtenBook_Id = 131; - - static const int emerald_Id = 388; - - static const int flowerPot_Id = 390; - - static const int carrots_Id = 391; - static const int potato_Id = 392; - static const int potatoBaked_Id = 393; - static const int potatoPoisonous_Id = 394; - - - static const int carrotGolden_Id = 396; - - static const int carrotOnAStick_Id = 398; - static const int pumpkinPie_Id = 400; - - static const int enchantedBook_Id = 403; - static const int netherQuartz_Id = 406; + static ItemArray items; + + static Item* shovel_iron; + static Item* pickAxe_iron; + static Item* hatchet_iron; + static Item* flintAndSteel; + static Item* apple; + static BowItem* bow; + static Item* arrow; + static Item* coal; + static Item* diamond; + static Item* ironIngot; + static Item* goldIngot; + static Item* sword_iron; + + static Item* sword_wood; + static Item* shovel_wood; + static Item* pickAxe_wood; + static Item* hatchet_wood; + + static Item* sword_stone; + static Item* shovel_stone; + static Item* pickAxe_stone; + static Item* hatchet_stone; + + static Item* sword_diamond; + static Item* shovel_diamond; + static Item* pickAxe_diamond; + static Item* hatchet_diamond; + + static Item* stick; + static Item* bowl; + static Item* mushroomStew; + + static Item* sword_gold; + static Item* shovel_gold; + static Item* pickAxe_gold; + static Item* hatchet_gold; + + static Item* string; + static Item* feather; + static Item* sulphur; + + static Item* hoe_wood; + static Item* hoe_stone; + static Item* hoe_iron; + static Item* hoe_diamond; + static Item* hoe_gold; + + static Item* seeds_wheat; + static Item* wheat; + static Item* bread; + + static ArmorItem* helmet_cloth; + static ArmorItem* chestplate_cloth; + static ArmorItem* leggings_cloth; + static ArmorItem* boots_cloth; + + static ArmorItem* helmet_chain; + static ArmorItem* chestplate_chain; + static ArmorItem* leggings_chain; + static ArmorItem* boots_chain; + + static ArmorItem* helmet_iron; + static ArmorItem* chestplate_iron; + static ArmorItem* leggings_iron; + static ArmorItem* boots_iron; + + static ArmorItem* helmet_diamond; + static ArmorItem* chestplate_diamond; + static ArmorItem* leggings_diamond; + static ArmorItem* boots_diamond; + + static ArmorItem* helmet_gold; + static ArmorItem* chestplate_gold; + static ArmorItem* leggings_gold; + static ArmorItem* boots_gold; + + static Item* flint; + static Item* porkChop_raw; + static Item* porkChop_cooked; + static Item* painting; + + static Item* apple_gold; + + static Item* sign; + static Item* door_wood; + + static Item* bucket_empty; + static Item* bucket_water; + static Item* bucket_lava; + + static Item* minecart; + static Item* saddle; + static Item* door_iron; + static Item* redStone; + static Item* snowBall; + + static Item* boat; + + static Item* leather; + static Item* milk; + static Item* brick; + static Item* clay; + static Item* reeds; + static Item* paper; + static Item* book; + static Item* slimeBall; + static Item* minecart_chest; + static Item* minecart_furnace; + static Item* egg; + static Item* compass; + static FishingRodItem* fishingRod; + static Item* clock; + static Item* yellowDust; + static Item* fish_raw; + static Item* fish_cooked; + + static Item* dye_powder; + static Item* bone; + static Item* sugar; + static Item* cake; + + static Item* bed; + + static Item* diode; + static Item* cookie; + + static MapItem* map; + + static ShearsItem* shears; + + static Item* melon; + + static Item* seeds_pumpkin; + static Item* seeds_melon; + + static Item* beef_raw; + static Item* beef_cooked; + static Item* chicken_raw; + static Item* chicken_cooked; + static Item* rotten_flesh; + + static Item* enderPearl; + + static Item* blazeRod; + static Item* ghastTear; + static Item* goldNugget; + + static Item* netherStalkSeeds; + + static PotionItem* potion; + static Item* glassBottle; + + static Item* spiderEye; + static Item* fermentedSpiderEye; + + static Item* blazePowder; + static Item* magmaCream; + + static Item* brewingStand; + static Item* cauldron; + static Item* eyeOfEnder; + static Item* speckledMelon; + + static Item* monsterPlacer; + + static Item* expBottle; + + static Item* skull; + + static Item* record_01; + static Item* record_02; + static Item* record_03; + static Item* record_04; + static Item* record_05; + static Item* record_06; + static Item* record_07; + static Item* record_08; + static Item* record_09; + static Item* record_10; + static Item* record_11; + static Item* record_12; + + // TU9 + static Item* fireball; + static Item* frame; + static Item* netherbrick; + + // TU14 + // static Item writingBook; + // static Item writtenBook; + + static Item* emerald; + + static Item* flowerPot; + + static Item* carrots; + static Item* potato; + static Item* potatoBaked; + static Item* potatoPoisonous; + + static Item* carrotGolden; + + static Item* carrotOnAStick; + static Item* pumpkinPie; + static Item* netherQuartz; + + static EnchantedBookItem* enchantedBook; + + static const int shovel_iron_Id = 256; + static const int pickAxe_iron_Id = 257; + static const int hatchet_iron_Id = 258; + static const int flintAndSteel_Id = 259; + static const int apple_Id = 260; + static const int bow_Id = 261; + static const int arrow_Id = 262; + static const int coal_Id = 263; + static const int diamond_Id = 264; + static const int ironIngot_Id = 265; + static const int goldIngot_Id = 266; + static const int sword_iron_Id = 267; + static const int sword_wood_Id = 268; + static const int shovel_wood_Id = 269; + static const int pickAxe_wood_Id = 270; + static const int hatchet_wood_Id = 271; + static const int sword_stone_Id = 272; + static const int shovel_stone_Id = 273; + static const int pickAxe_stone_Id = 274; + static const int hatchet_stone_Id = 275; + static const int sword_diamond_Id = 276; + static const int shovel_diamond_Id = 277; + static const int pickAxe_diamond_Id = 278; + static const int hatchet_diamond_Id = 279; + static const int stick_Id = 280; + static const int bowl_Id = 281; + static const int mushroomStew_Id = 282; + static const int sword_gold_Id = 283; + static const int shovel_gold_Id = 284; + static const int pickAxe_gold_Id = 285; + static const int hatchet_gold_Id = 286; + static const int string_Id = 287; + static const int feather_Id = 288; + static const int sulphur_Id = 289; + static const int hoe_wood_Id = 290; + static const int hoe_stone_Id = 291; + static const int hoe_iron_Id = 292; + static const int hoe_diamond_Id = 293; + static const int hoe_gold_Id = 294; + static const int seeds_wheat_Id = 295; + static const int wheat_Id = 296; + static const int bread_Id = 297; + + static const int helmet_cloth_Id = 298; + static const int chestplate_cloth_Id = 299; + static const int leggings_cloth_Id = 300; + static const int boots_cloth_Id = 301; + + static const int helmet_chain_Id = 302; + static const int chestplate_chain_Id = 303; + static const int leggings_chain_Id = 304; + static const int boots_chain_Id = 305; + + static const int helmet_iron_Id = 306; + static const int chestplate_iron_Id = 307; + static const int leggings_iron_Id = 308; + static const int boots_iron_Id = 309; + + static const int helmet_diamond_Id = 310; + static const int chestplate_diamond_Id = 311; + static const int leggings_diamond_Id = 312; + static const int boots_diamond_Id = 313; + + static const int helmet_gold_Id = 314; + static const int chestplate_gold_Id = 315; + static const int leggings_gold_Id = 316; + static const int boots_gold_Id = 317; + + static const int flint_Id = 318; + static const int porkChop_raw_Id = 319; + static const int porkChop_cooked_Id = 320; + static const int painting_Id = 321; + static const int apple_gold_Id = 322; + static const int sign_Id = 323; + static const int door_wood_Id = 324; + static const int bucket_empty_Id = 325; + static const int bucket_water_Id = 326; + static const int bucket_lava_Id = 327; + static const int minecart_Id = 328; + static const int saddle_Id = 329; + static const int door_iron_Id = 330; + static const int redStone_Id = 331; + static const int snowBall_Id = 332; + static const int boat_Id = 333; + static const int leather_Id = 334; + static const int milk_Id = 335; + static const int brick_Id = 336; + static const int clay_Id = 337; + static const int reeds_Id = 338; + static const int paper_Id = 339; + static const int book_Id = 340; + static const int slimeBall_Id = 341; + static const int minecart_chest_Id = 342; + static const int minecart_furnace_Id = 343; + static const int egg_Id = 344; + static const int compass_Id = 345; + static const int fishingRod_Id = 346; + static const int clock_Id = 347; + static const int yellowDust_Id = 348; + static const int fish_raw_Id = 349; + static const int fish_cooked_Id = 350; + static const int dye_powder_Id = 351; + static const int bone_Id = 352; + static const int sugar_Id = 353; + static const int cake_Id = 354; + static const int bed_Id = 355; + static const int diode_Id = 356; + static const int cookie_Id = 357; + static const int map_Id = 358; + + // 1.7.3 + static const int shears_Id = 359; + + // 1.8.2 + static const int melon_Id = 360; + static const int seeds_pumpkin_Id = 361; + static const int seeds_melon_Id = 362; + static const int beef_raw_Id = 363; + static const int beef_cooked_Id = 364; + static const int chicken_raw_Id = 365; + static const int chicken_cooked_Id = 366; + static const int rotten_flesh_Id = 367; + static const int enderPearl_Id = 368; + + // 1.0.1 + static const int blazeRod_Id = 369; + static const int ghastTear_Id = 370; + static const int goldNugget_Id = 371; + static const int netherStalkSeeds_Id = 372; + static const int potion_Id = 373; + static const int glassBottle_Id = 374; + static const int spiderEye_Id = 375; + static const int fermentedSpiderEye_Id = 376; + static const int blazePowder_Id = 377; + static const int magmaCream_Id = 378; + static const int brewingStand_Id = 379; + static const int cauldron_Id = 380; + static const int eyeOfEnder_Id = 381; + static const int speckledMelon_Id = 382; + + // 1.1 + static const int monsterPlacer_Id = 383; + + static const int expBottle_Id = 384; + + // TU 12 + static const int skull_Id = 397; + + static const int record_01_Id = 2256; + static const int record_02_Id = 2257; + static const int record_03_Id = 2258; + static const int record_04_Id = 2259; + static const int record_05_Id = 2260; + static const int record_06_Id = 2261; + static const int record_07_Id = 2262; + static const int record_09_Id = 2263; + static const int record_10_Id = 2264; + static const int record_11_Id = 2265; + static const int record_12_Id = 2266; + + // 4J-PB - this one isn't playable in the PC game, but is fine in ours + static const int record_08_Id = 2267; + + // TU9 + static const int fireball_Id = 385; + static const int itemFrame_Id = 389; + static const int netherbrick_Id = 405; + + // TU14 + // static const int writingBook_Id = 130; + // static const int writtenBook_Id = 131; + + static const int emerald_Id = 388; + + static const int flowerPot_Id = 390; + + static const int carrots_Id = 391; + static const int potato_Id = 392; + static const int potatoBaked_Id = 393; + static const int potatoPoisonous_Id = 394; + + static const int carrotGolden_Id = 396; + + static const int carrotOnAStick_Id = 398; + static const int pumpkinPie_Id = 400; + + static const int enchantedBook_Id = 403; + static const int netherQuartz_Id = 406; public: - const int id; + const int id; protected: - int maxStackSize; + int maxStackSize; private: - int maxDamage; + int maxDamage; protected: - Icon *icon; - // 4J-PB - added for new crafting menu - int m_iBaseItemType; - int m_iMaterial; - bool m_handEquipped; - bool m_isStackedByData; + Icon* icon; + // 4J-PB - added for new crafting menu + int m_iBaseItemType; + int m_iMaterial; + bool m_handEquipped; + bool m_isStackedByData; private: - Item *craftingRemainingItem; - std::wstring potionBrewingFormula; + Item* craftingRemainingItem; + std::wstring potionBrewingFormula; - // 4J Stu - A value from strings.h, that is the name of the item - unsigned int descriptionId; + // 4J Stu - A value from strings.h, that is the name of the item + unsigned int descriptionId; - // 4J Stu - A value from strings.h that says what this does - unsigned int useDescriptionId; + // 4J Stu - A value from strings.h that says what this does + unsigned int useDescriptionId; - std::wstring m_textureName; + std::wstring m_textureName; protected: - Item(int id); + Item(int id); public: - // 4J Using per-item textures now - Item *setTextureName(const std::wstring &name); - Item *setMaxStackSize(int max); - Item *setBaseItemTypeAndMaterial(int iType,int iMaterial); - int getBaseItemType(); - int getMaterial(); + // 4J Using per-item textures now + Item* setTextureName(const std::wstring& name); + Item* setMaxStackSize(int max); + Item* setBaseItemTypeAndMaterial(int iType, int iMaterial); + int getBaseItemType(); + int getMaterial(); - virtual int getIconType(); - virtual Icon *getIcon(int auxValue); - Icon *getIcon(std::shared_ptr itemInstance); + virtual int getIconType(); + virtual Icon* getIcon(int auxValue); + Icon* getIcon(std::shared_ptr itemInstance); - const bool useOn(std::shared_ptr itemInstance, Level *level, int x, int y, int z, int face, bool bTestUseOnOnly=false); + const bool useOn(std::shared_ptr itemInstance, Level* level, + int x, int y, int z, int face, + bool bTestUseOnOnly = false); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual std::shared_ptr useTimeDepleted(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual int getMaxStackSize(); - virtual int getLevelDataForAuxValue(int auxValue); - bool isStackedByData(); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual float getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); + virtual std::shared_ptr useTimeDepleted( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); + virtual int getMaxStackSize(); + virtual int getLevelDataForAuxValue(int auxValue); + bool isStackedByData(); protected: - Item *setStackedByData(bool isStackedByData); + Item* setStackedByData(bool isStackedByData); public: - int getMaxDamage(); + int getMaxDamage(); protected: - Item *setMaxDamage(int maxDamage); + Item* setMaxDamage(int maxDamage); public: - bool canBeDepleted(); + bool canBeDepleted(); - /** - * Returns true when the item was used to deal more than default damage - * - * @param itemInstance - * @param mob - * @param attacker - * @return - */ - virtual bool hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker); + /** + * Returns true when the item was used to deal more than default damage + * + * @param itemInstance + * @param mob + * @param attacker + * @return + */ + virtual bool hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker); - /** - * Returns true when the item was used to mine more efficiently - * - * @param itemInstance - * @param tile - * @param x - * @param yf - * @param z - * @param owner - * @return - */ - virtual bool mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner); - virtual int getAttackDamage(std::shared_ptr entity); - virtual bool canDestroySpecial(Tile *tile); - virtual bool interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob); - Item *handEquipped(); - virtual bool isHandEquipped(); - virtual bool isMirroredArt(); - Item *setDescriptionId(unsigned int id); - const wchar_t *getDescription(); - const wchar_t *getDescription(std::shared_ptr instance); - virtual unsigned int getDescriptionId(int iData = -1); - virtual unsigned int getDescriptionId(std::shared_ptr instance); - Item *setUseDescriptionId(unsigned int id); - virtual unsigned int getUseDescriptionId(); - virtual unsigned int getUseDescriptionId(std::shared_ptr instance); - Item *setCraftingRemainingItem(Item *craftingRemainingItem); - virtual bool shouldMoveCraftingResultToInventory(std::shared_ptr instance); - virtual bool shouldOverrideMultiplayerNBT(); - Item *getCraftingRemainingItem(); - bool hasCraftingRemainingItem(); - std::wstring getName(); - virtual int getColor(std::shared_ptr item, int spriteLayer); - virtual void inventoryTick(std::shared_ptr itemInstance, Level *level, std::shared_ptr owner, int slot, bool selected); - virtual void onCraftedBy(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual bool isComplex(); + /** + * Returns true when the item was used to mine more efficiently + * + * @param itemInstance + * @param tile + * @param x + * @param yf + * @param z + * @param owner + * @return + */ + virtual bool mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner); + virtual int getAttackDamage(std::shared_ptr entity); + virtual bool canDestroySpecial(Tile* tile); + virtual bool interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob); + Item* handEquipped(); + virtual bool isHandEquipped(); + virtual bool isMirroredArt(); + Item* setDescriptionId(unsigned int id); + const wchar_t* getDescription(); + const wchar_t* getDescription(std::shared_ptr instance); + virtual unsigned int getDescriptionId(int iData = -1); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); + Item* setUseDescriptionId(unsigned int id); + virtual unsigned int getUseDescriptionId(); + virtual unsigned int getUseDescriptionId( + std::shared_ptr instance); + Item* setCraftingRemainingItem(Item* craftingRemainingItem); + virtual bool shouldMoveCraftingResultToInventory( + std::shared_ptr instance); + virtual bool shouldOverrideMultiplayerNBT(); + Item* getCraftingRemainingItem(); + bool hasCraftingRemainingItem(); + std::wstring getName(); + virtual int getColor(std::shared_ptr item, int spriteLayer); + virtual void inventoryTick(std::shared_ptr itemInstance, + Level* level, std::shared_ptr owner, + int slot, bool selected); + virtual void onCraftedBy(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player); + virtual bool isComplex(); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual void releaseUsing(std::shared_ptr itemInstance, Level *level, std::shared_ptr player, int durationLeft); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual void releaseUsing(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player, + int durationLeft); protected: - virtual Item *setPotionBrewingFormula(const std::wstring &potionBrewingFormula); + virtual Item* setPotionBrewingFormula( + const std::wstring& potionBrewingFormula); public: - virtual std::wstring getPotionBrewingFormula(); - virtual bool hasPotionBrewingFormula(); - virtual void appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings); // 4J Added unformattedStrings - virtual std::wstring getHoverName(std::shared_ptr itemInstance); - virtual bool isFoil(std::shared_ptr itemInstance); - virtual const Rarity *getRarity(std::shared_ptr itemInstance); - virtual bool isEnchantable(std::shared_ptr itemInstance); + virtual std::wstring getPotionBrewingFormula(); + virtual bool hasPotionBrewingFormula(); + virtual void appendHoverText( + std::shared_ptr itemInstance, + std::shared_ptr player, std::vector* lines, + bool advanced, + std::vector& + unformattedStrings); // 4J Added unformattedStrings + virtual std::wstring getHoverName( + std::shared_ptr itemInstance); + virtual bool isFoil(std::shared_ptr itemInstance); + virtual const Rarity* getRarity(std::shared_ptr itemInstance); + virtual bool isEnchantable(std::shared_ptr itemInstance); protected: - HitResult *getPlayerPOVHitResult(Level *level, std::shared_ptr player, bool alsoPickLiquid); + HitResult* getPlayerPOVHitResult(Level* level, + std::shared_ptr player, + bool alsoPickLiquid); public: - virtual int getEnchantmentValue(); - virtual bool hasMultipleSpriteLayers(); - virtual Icon *getLayerIcon(int auxValue, int spriteLayer); - virtual bool isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem); - virtual void registerIcons(IconRegister *iconRegister); + virtual int getEnchantmentValue(); + virtual bool hasMultipleSpriteLayers(); + virtual Icon* getLayerIcon(int auxValue, int spriteLayer); + virtual bool isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem); + virtual void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Items/ItemInstance.cpp b/Minecraft.World/Items/ItemInstance.cpp index 999c1a4e8..3c8b4857f 100644 --- a/Minecraft.World/Items/ItemInstance.cpp +++ b/Minecraft.World/Items/ItemInstance.cpp @@ -11,717 +11,599 @@ #include "Item.h" #include "ItemInstance.h" +const wchar_t* ItemInstance::TAG_ENCH_ID = L"id"; +const wchar_t* ItemInstance::TAG_ENCH_LEVEL = L"lvl"; - -const wchar_t *ItemInstance::TAG_ENCH_ID = L"id"; -const wchar_t *ItemInstance::TAG_ENCH_LEVEL = L"lvl"; - -void ItemInstance::_init(int id, int count, int auxValue) -{ - this->popTime = 0; - this->id = id; - this->count = count; - this->auxValue = auxValue; - this->tag = NULL; - this->frame = nullptr; - // 4J-PB - for trading menu - this->m_bForceNumberDisplay=false; +void ItemInstance::_init(int id, int count, int auxValue) { + this->popTime = 0; + this->id = id; + this->count = count; + this->auxValue = auxValue; + this->tag = NULL; + this->frame = nullptr; + // 4J-PB - for trading menu + this->m_bForceNumberDisplay = false; } -ItemInstance::ItemInstance(Tile *tile) -{ - _init(tile->id, 1, 0); -} +ItemInstance::ItemInstance(Tile* tile) { _init(tile->id, 1, 0); } -ItemInstance::ItemInstance(Tile *tile, int count) -{ - _init(tile->id, count, 0); -} +ItemInstance::ItemInstance(Tile* tile, int count) { _init(tile->id, count, 0); } // 4J-PB - added -ItemInstance::ItemInstance(MapItem *item, int count) -{ - _init(item->id, count, 0); -} - -ItemInstance::ItemInstance(Tile *tile, int count, int auxValue) -{ - _init(tile->id, count, auxValue); -} - -ItemInstance::ItemInstance(Item *item) -{ - _init(item->id, 1, 0); -} - - - -ItemInstance::ItemInstance(Item *item, int count) -{ +ItemInstance::ItemInstance(MapItem* item, int count) { _init(item->id, count, 0); } -ItemInstance::ItemInstance(Item *item, int count, int auxValue) -{ +ItemInstance::ItemInstance(Tile* tile, int count, int auxValue) { + _init(tile->id, count, auxValue); +} + +ItemInstance::ItemInstance(Item* item) { _init(item->id, 1, 0); } + +ItemInstance::ItemInstance(Item* item, int count) { _init(item->id, count, 0); } + +ItemInstance::ItemInstance(Item* item, int count, int auxValue) { _init(item->id, count, auxValue); } -ItemInstance::ItemInstance(int id, int count, int damage) -{ - _init(id,count,damage); +ItemInstance::ItemInstance(int id, int count, int damage) { + _init(id, count, damage); } -std::shared_ptr ItemInstance::fromTag(CompoundTag *itemTag) -{ - std::shared_ptr itemInstance = std::shared_ptr(new ItemInstance()); - itemInstance->load(itemTag); - return itemInstance->getItem() != NULL ? itemInstance : nullptr; +std::shared_ptr ItemInstance::fromTag(CompoundTag* itemTag) { + std::shared_ptr itemInstance = + std::shared_ptr(new ItemInstance()); + itemInstance->load(itemTag); + return itemInstance->getItem() != NULL ? itemInstance : nullptr; } -ItemInstance::~ItemInstance() -{ - if(tag != NULL) delete tag; +ItemInstance::~ItemInstance() { + if (tag != NULL) delete tag; } -std::shared_ptr ItemInstance::remove(int count) -{ - std::shared_ptr ii = std::shared_ptr( new ItemInstance(id, count, auxValue) ); - if (tag != NULL) ii->tag = (CompoundTag *) tag->copy(); - this->count -= count; +std::shared_ptr ItemInstance::remove(int count) { + std::shared_ptr ii = + std::shared_ptr(new ItemInstance(id, count, auxValue)); + if (tag != NULL) ii->tag = (CompoundTag*)tag->copy(); + this->count -= count; - // 4J Stu Fix for duplication glitch, make sure that item count is in range - if(this->count <= 0) - { - this->count = 0; - } - return ii; + // 4J Stu Fix for duplication glitch, make sure that item count is in range + if (this->count <= 0) { + this->count = 0; + } + return ii; } -Item *ItemInstance::getItem() const -{ - return Item::items[id]; +Item* ItemInstance::getItem() const { return Item::items[id]; } + +Icon* ItemInstance::getIcon() { return getItem()->getIcon(shared_from_this()); } + +int ItemInstance::getIconType() { return getItem()->getIconType(); } + +bool ItemInstance::useOn(std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + return getItem()->useOn(shared_from_this(), player, level, x, y, z, face, + clickX, clickY, clickZ, bTestUseOnOnly); } -Icon *ItemInstance::getIcon() -{ - return getItem()->getIcon(shared_from_this()); -} - -int ItemInstance::getIconType() -{ - return getItem()->getIconType(); -} - -bool ItemInstance::useOn(std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - return getItem()->useOn(shared_from_this(), player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); -} - -float ItemInstance::getDestroySpeed(Tile *tile) -{ +float ItemInstance::getDestroySpeed(Tile* tile) { return getItem()->getDestroySpeed(shared_from_this(), tile); } -bool ItemInstance::TestUse(Level *level, std::shared_ptr player) -{ - return getItem()->TestUse( level, player); +bool ItemInstance::TestUse(Level* level, std::shared_ptr player) { + return getItem()->TestUse(level, player); } -std::shared_ptr ItemInstance::use(Level *level, std::shared_ptr player) -{ +std::shared_ptr ItemInstance::use( + Level* level, std::shared_ptr player) { return getItem()->use(shared_from_this(), level, player); } -std::shared_ptr ItemInstance::useTimeDepleted(Level *level, std::shared_ptr player) -{ - return getItem()->useTimeDepleted(shared_from_this(), level, player); +std::shared_ptr ItemInstance::useTimeDepleted( + Level* level, std::shared_ptr player) { + return getItem()->useTimeDepleted(shared_from_this(), level, player); } -CompoundTag *ItemInstance::save(CompoundTag *compoundTag) -{ - compoundTag->putShort(L"id", (short) id); - compoundTag->putByte(L"Count", (uint8_t) count); - compoundTag->putShort(L"Damage", (short) auxValue); - if (this->tag != NULL) compoundTag->put(L"tag", tag->copy()); +CompoundTag* ItemInstance::save(CompoundTag* compoundTag) { + compoundTag->putShort(L"id", (short)id); + compoundTag->putByte(L"Count", (uint8_t)count); + compoundTag->putShort(L"Damage", (short)auxValue); + if (this->tag != NULL) compoundTag->put(L"tag", tag->copy()); return compoundTag; } -void ItemInstance::load(CompoundTag *compoundTag) -{ - popTime = 0; +void ItemInstance::load(CompoundTag* compoundTag) { + popTime = 0; id = compoundTag->getShort(L"id"); count = compoundTag->getByte(L"Count"); auxValue = compoundTag->getShort(L"Damage"); - if (compoundTag->contains(L"tag")) - { - tag = (CompoundTag *)compoundTag->getCompound(L"tag")->copy(); - } + if (compoundTag->contains(L"tag")) { + tag = (CompoundTag*)compoundTag->getCompound(L"tag")->copy(); + } } -int ItemInstance::getMaxStackSize() -{ - return getItem()->getMaxStackSize(); -} +int ItemInstance::getMaxStackSize() { return getItem()->getMaxStackSize(); } -bool ItemInstance::isStackable() -{ +bool ItemInstance::isStackable() { return getMaxStackSize() > 1 && (!isDamageableItem() || !isDamaged()); } -bool ItemInstance::isDamageableItem() -{ +bool ItemInstance::isDamageableItem() { return Item::items[id]->getMaxDamage() > 0; } /** * Returns true if this item type only can be stacked with items that have * the same auxValue data. - * + * * @return */ -bool ItemInstance::isStackedByData() -{ +bool ItemInstance::isStackedByData() { return Item::items[id]->isStackedByData(); } -bool ItemInstance::isDamaged() -{ - return isDamageableItem() && auxValue > 0; -} +bool ItemInstance::isDamaged() { return isDamageableItem() && auxValue > 0; } -int ItemInstance::getDamageValue() -{ - return auxValue; -} +int ItemInstance::getDamageValue() { return auxValue; } -int ItemInstance::getAuxValue() const -{ - return auxValue; -} +int ItemInstance::getAuxValue() const { return auxValue; } -void ItemInstance::setAuxValue(int value) -{ - auxValue = value; -} +void ItemInstance::setAuxValue(int value) { auxValue = value; } -int ItemInstance::getMaxDamage() -{ - return Item::items[id]->getMaxDamage(); -} +int ItemInstance::getMaxDamage() { return Item::items[id]->getMaxDamage(); } -void ItemInstance::hurt(int i, std::shared_ptr owner) -{ - if (!isDamageableItem()) - { +void ItemInstance::hurt(int i, std::shared_ptr owner) { + if (!isDamageableItem()) { return; } - std::shared_ptr player = std::dynamic_pointer_cast(owner); - if (i > 0 && player != NULL) - { - int enchanted = EnchantmentHelper::getDigDurability(player->inventory); - // Fix for #65233 - TU8: Content: Gameplay: Tools Enchanted with "Unbreaking" occasionally repair themselves. - // 4J Stu - If it's the clientside level, then always assume that no damage is done. This stops the case where the client random - // results in damage, but the server random does not - if (enchanted > 0 && (owner->level->isClientSide || owner->level->random->nextInt(enchanted + 1) > 0) ) - { - // enchantment prevents damage - return; - } - } + std::shared_ptr player = std::dynamic_pointer_cast(owner); + if (i > 0 && player != NULL) { + int enchanted = EnchantmentHelper::getDigDurability(player->inventory); + // Fix for #65233 - TU8: Content: Gameplay: Tools Enchanted with + // "Unbreaking" occasionally repair themselves. 4J Stu - If it's the + // clientside level, then always assume that no damage is done. This + // stops the case where the client random results in damage, but the + // server random does not + if (enchanted > 0 && + (owner->level->isClientSide || + owner->level->random->nextInt(enchanted + 1) > 0)) { + // enchantment prevents damage + return; + } + } - // 4J Stu - Changed in TU6 to not damage items in creative mode + // 4J Stu - Changed in TU6 to not damage items in creative mode if (!(owner != NULL && player->abilities.instabuild)) auxValue += i; - - if (auxValue > getMaxDamage()) - { - owner->breakItem(shared_from_this()); + + if (auxValue > getMaxDamage()) { + owner->breakItem(shared_from_this()); count--; if (count < 0) count = 0; auxValue = 0; } } -void ItemInstance::hurtEnemy(std::shared_ptr mob, std::shared_ptr attacker) -{ - //bool used = - Item::items[id]->hurtEnemy(shared_from_this(), mob, attacker); +void ItemInstance::hurtEnemy(std::shared_ptr mob, + std::shared_ptr attacker) { + // bool used = + Item::items[id]->hurtEnemy(shared_from_this(), mob, attacker); } -void ItemInstance::mineBlock(Level *level, int tile, int x, int y, int z, std::shared_ptr owner) -{ - //bool used = - Item::items[id]->mineBlock( shared_from_this(), level, tile, x, y, z, owner); +void ItemInstance::mineBlock(Level* level, int tile, int x, int y, int z, + std::shared_ptr owner) { + // bool used = + Item::items[id]->mineBlock(shared_from_this(), level, tile, x, y, z, owner); } -int ItemInstance::getAttackDamage(std::shared_ptr entity) -{ +int ItemInstance::getAttackDamage(std::shared_ptr entity) { return Item::items[id]->getAttackDamage(entity); } -bool ItemInstance::canDestroySpecial(Tile *tile) -{ +bool ItemInstance::canDestroySpecial(Tile* tile) { return Item::items[id]->canDestroySpecial(tile); } -bool ItemInstance::interactEnemy(std::shared_ptr mob) -{ +bool ItemInstance::interactEnemy(std::shared_ptr mob) { return Item::items[id]->interactEnemy(shared_from_this(), mob); } -std::shared_ptr ItemInstance::copy() const -{ - std::shared_ptr copy = std::shared_ptr( new ItemInstance(id, count, auxValue) ); - if (tag != NULL) - { - copy->tag = (CompoundTag *) tag->copy(); - } - return copy; +std::shared_ptr ItemInstance::copy() const { + std::shared_ptr copy = + std::shared_ptr(new ItemInstance(id, count, auxValue)); + if (tag != NULL) { + copy->tag = (CompoundTag*)tag->copy(); + } + return copy; } // 4J Stu - Added this as we need it in the recipe code -ItemInstance *ItemInstance::copy_not_shared() const -{ - ItemInstance *copy = new ItemInstance(id, count, auxValue); - if (tag != NULL) - { - copy->tag = (CompoundTag *) tag->copy(); - if (!copy->tag->equals(tag)) - { - return copy; - } - } - return copy; +ItemInstance* ItemInstance::copy_not_shared() const { + ItemInstance* copy = new ItemInstance(id, count, auxValue); + if (tag != NULL) { + copy->tag = (CompoundTag*)tag->copy(); + if (!copy->tag->equals(tag)) { + return copy; + } + } + return copy; } // 4J Brought forward from 1.2 -bool ItemInstance::tagMatches(std::shared_ptr a, std::shared_ptr b) -{ - if (a == NULL && b == NULL) return true; - if (a == NULL || b == NULL) return false; +bool ItemInstance::tagMatches(std::shared_ptr a, + std::shared_ptr b) { + if (a == NULL && b == NULL) return true; + if (a == NULL || b == NULL) return false; - if (a->tag == NULL && b->tag != NULL) - { - return false; - } - if (a->tag != NULL && !a->tag->equals(b->tag)) - { - return false; - } - return true; + if (a->tag == NULL && b->tag != NULL) { + return false; + } + if (a->tag != NULL && !a->tag->equals(b->tag)) { + return false; + } + return true; } -bool ItemInstance::matches(std::shared_ptr a, std::shared_ptr b) -{ +bool ItemInstance::matches(std::shared_ptr a, + std::shared_ptr b) { if (a == NULL && b == NULL) return true; if (a == NULL || b == NULL) return false; return a->matches(b); } -bool ItemInstance::matches(std::shared_ptr b) -{ +bool ItemInstance::matches(std::shared_ptr b) { if (count != b->count) return false; if (id != b->id) return false; if (auxValue != b->auxValue) return false; - if (tag == NULL && b->tag != NULL) - { - return false; - } - if (tag != NULL && !tag->equals(b->tag)) - { - return false; - } + if (tag == NULL && b->tag != NULL) { + return false; + } + if (tag != NULL && !tag->equals(b->tag)) { + return false; + } return true; } /** * Checks if this item is the same item as the other one, disregarding the * 'count' value. - * + * * @param b * @return */ -bool ItemInstance::sameItem(std::shared_ptr b) -{ +bool ItemInstance::sameItem(std::shared_ptr b) { return id == b->id && auxValue == b->auxValue; } -bool ItemInstance::sameItemWithTags(std::shared_ptr b) -{ +bool ItemInstance::sameItemWithTags(std::shared_ptr b) { if (id != b->id) return false; if (auxValue != b->auxValue) return false; - if (tag == NULL && b->tag != NULL) - { - return false; - } - if (tag != NULL && !tag->equals(b->tag)) - { - return false; - } + if (tag == NULL && b->tag != NULL) { + return false; + } + if (tag != NULL && !tag->equals(b->tag)) { + return false; + } return true; } -// 4J Stu - Added this for the one time when we compare with a non-shared pointer -bool ItemInstance::sameItem_not_shared(ItemInstance *b) -{ +// 4J Stu - Added this for the one time when we compare with a non-shared +// pointer +bool ItemInstance::sameItem_not_shared(ItemInstance* b) { return id == b->id && auxValue == b->auxValue; } -unsigned int ItemInstance::getUseDescriptionId() -{ +unsigned int ItemInstance::getUseDescriptionId() { return Item::items[id]->getUseDescriptionId(shared_from_this()); } -unsigned int ItemInstance::getDescriptionId(int iData /*= -1*/) -{ +unsigned int ItemInstance::getDescriptionId(int iData /*= -1*/) { return Item::items[id]->getDescriptionId(shared_from_this()); } -ItemInstance *ItemInstance::setDescriptionId(unsigned int id) -{ - // 4J Stu - I don't think this function is ever used. It if is, it should probably return shared_from_this() - assert(false); +ItemInstance* ItemInstance::setDescriptionId(unsigned int id) { + // 4J Stu - I don't think this function is ever used. It if is, it should + // probably return shared_from_this() + assert(false); return this; } -std::shared_ptr ItemInstance::clone(std::shared_ptr item) -{ +std::shared_ptr ItemInstance::clone( + std::shared_ptr item) { return item == NULL ? nullptr : item->copy(); } -std::wstring ItemInstance::toString() -{ - //return count + "x" + Item::items[id]->getDescriptionId() + "@" + auxValue; - - std::wostringstream oss; - // 4J-PB - TODO - temp fix until ore recipe issue is fixed - if(Item::items[id]==NULL) - { - oss << std::dec << count << L"x" << L" Item::items[id] is NULL " << L"@" << auxValue; - } - else - { - oss << std::dec << count << L"x" << Item::items[id]->getDescription(shared_from_this()) << L"@" << auxValue; - } - return oss.str(); +std::wstring ItemInstance::toString() { + // return count + "x" + Item::items[id]->getDescriptionId() + "@" + + // auxValue; + + std::wostringstream oss; + // 4J-PB - TODO - temp fix until ore recipe issue is fixed + if (Item::items[id] == NULL) { + oss << std::dec << count << L"x" << L" Item::items[id] is NULL " << L"@" + << auxValue; + } else { + oss << std::dec << count << L"x" + << Item::items[id]->getDescription(shared_from_this()) << L"@" + << auxValue; + } + return oss.str(); } -void ItemInstance::inventoryTick(Level *level, std::shared_ptr owner, int slot, bool selected) -{ +void ItemInstance::inventoryTick(Level* level, std::shared_ptr owner, + int slot, bool selected) { if (popTime > 0) popTime--; - Item::items[id]->inventoryTick(shared_from_this(), level, owner, slot, selected); + Item::items[id]->inventoryTick(shared_from_this(), level, owner, slot, + selected); } -void ItemInstance::onCraftedBy(Level *level, std::shared_ptr player, int craftCount) -{ - // 4J Stu Added for tutorial callback - player->onCrafted(shared_from_this()); +void ItemInstance::onCraftedBy(Level* level, std::shared_ptr player, + int craftCount) { + // 4J Stu Added for tutorial callback + player->onCrafted(shared_from_this()); - player->awardStat( - GenericStats::itemsCrafted(id), - GenericStats::param_itemsCrafted(id, auxValue, craftCount) - ); + player->awardStat( + GenericStats::itemsCrafted(id), + GenericStats::param_itemsCrafted(id, auxValue, craftCount)); Item::items[id]->onCraftedBy(shared_from_this(), level, player); } -bool ItemInstance::equals(std::shared_ptr ii) -{ +bool ItemInstance::equals(std::shared_ptr ii) { return id == ii->id && count == ii->count && auxValue == ii->auxValue; } -int ItemInstance::getUseDuration() -{ - return getItem()->getUseDuration(shared_from_this()); +int ItemInstance::getUseDuration() { + return getItem()->getUseDuration(shared_from_this()); } -UseAnim ItemInstance::getUseAnimation() -{ - return getItem()->getUseAnimation(shared_from_this()); +UseAnim ItemInstance::getUseAnimation() { + return getItem()->getUseAnimation(shared_from_this()); } -void ItemInstance::releaseUsing(Level *level, std::shared_ptr player, int durationLeft) -{ - getItem()->releaseUsing(shared_from_this(), level, player, durationLeft); +void ItemInstance::releaseUsing(Level* level, std::shared_ptr player, + int durationLeft) { + getItem()->releaseUsing(shared_from_this(), level, player, durationLeft); } // 4J Stu - Brought forward these functions for enchanting/game rules -bool ItemInstance::hasTag() -{ - return tag != NULL; +bool ItemInstance::hasTag() { return tag != NULL; } + +CompoundTag* ItemInstance::getTag() { return tag; } + +ListTag* ItemInstance::getEnchantmentTags() { + if (tag == NULL) { + return NULL; + } + return (ListTag*)tag->get(L"ench"); } -CompoundTag *ItemInstance::getTag() -{ - return tag; +void ItemInstance::setTag(CompoundTag* tag) { this->tag = tag; } + +std::wstring ItemInstance::getHoverName() { + std::wstring title = getItem()->getHoverName(shared_from_this()); + + if (tag != NULL && tag->contains(L"display")) { + CompoundTag* display = tag->getCompound(L"display"); + + if (display->contains(L"Name")) { + title = display->getString(L"Name"); + } + } + + return title; } -ListTag *ItemInstance::getEnchantmentTags() -{ - if (tag == NULL) - { - return NULL; - } - return (ListTag *) tag->get(L"ench"); +void ItemInstance::setHoverName(const std::wstring& name) { + if (tag == NULL) tag = new CompoundTag(); + if (!tag->contains(L"display")) + tag->putCompound(L"display", new CompoundTag()); + tag->getCompound(L"display")->putString(L"Name", name); } -void ItemInstance::setTag(CompoundTag *tag) -{ - this->tag = tag; +bool ItemInstance::hasCustomHoverName() { + if (tag == NULL) return false; + if (!tag->contains(L"display")) return false; + return tag->getCompound(L"display")->contains(L"Name"); } -std::wstring ItemInstance::getHoverName() -{ - std::wstring title = getItem()->getHoverName(shared_from_this()); +std::vector* ItemInstance::getHoverText( + std::shared_ptr player, bool advanced, + std::vector& unformattedStrings) { + std::vector* lines = new std::vector(); + Item* item = Item::items[id]; + std::wstring title = getHoverName(); - if (tag != NULL && tag->contains(L"display")) - { - CompoundTag *display = tag->getCompound(L"display"); + // 4J Stu - We don't do italics, but do change colour. But handle this later + // in the process due to text length measuring on the Xbox360 + // if (hasCustomHoverName()) + //{ + // title = L"" + title + L""; + //} - if (display->contains(L"Name")) - { - title = display->getString(L"Name"); - } - } + // 4J Stu - Don't currently have this + // if (advanced) + //{ + // String suffix = ""; - return title; -} + // if (title.length() > 0) { + // title += " ("; + // suffix = ")"; + // } -void ItemInstance::setHoverName(const std::wstring &name) -{ - if (tag == NULL) tag = new CompoundTag(); - if (!tag->contains(L"display")) tag->putCompound(L"display", new CompoundTag()); - tag->getCompound(L"display")->putString(L"Name", name); -} + // if (isStackedByData()) + // { + // title += String.format("#%04d/%d%s", id, auxValue, suffix); + // } + // else + // { + // title += String.format("#%04d%s", id, suffix); + // } + //} + // else + // if (!hasCustomHoverName()) + //{ + // if (id == Item::map_Id) + // { + // title += L" #" + _toString(auxValue); + // } + //} -bool ItemInstance::hasCustomHoverName() -{ - if (tag == NULL) return false; - if (!tag->contains(L"display")) return false; - return tag->getCompound(L"display")->contains(L"Name"); -} + lines->push_back(title); + unformattedStrings.push_back(title); + item->appendHoverText(shared_from_this(), player, lines, advanced, + unformattedStrings); -std::vector *ItemInstance::getHoverText(std::shared_ptr player, bool advanced, std::vector &unformattedStrings) -{ - std::vector *lines = new std::vector(); - Item *item = Item::items[id]; - std::wstring title = getHoverName(); + if (hasTag()) { + ListTag* list = getEnchantmentTags(); + if (list != NULL) { + for (int i = 0; i < list->size(); i++) { + int type = list->get(i)->getShort((wchar_t*)TAG_ENCH_ID); + int level = list->get(i)->getShort((wchar_t*)TAG_ENCH_LEVEL); - // 4J Stu - We don't do italics, but do change colour. But handle this later in the process due to text length measuring on the Xbox360 - //if (hasCustomHoverName()) - //{ - // title = L"" + title + L""; - //} - - // 4J Stu - Don't currently have this - //if (advanced) - //{ - // String suffix = ""; - - // if (title.length() > 0) { - // title += " ("; - // suffix = ")"; - // } - - // if (isStackedByData()) - // { - // title += String.format("#%04d/%d%s", id, auxValue, suffix); - // } - // else - // { - // title += String.format("#%04d%s", id, suffix); - // } - //} - //else - // if (!hasCustomHoverName()) - //{ - // if (id == Item::map_Id) - // { - // title += L" #" + _toString(auxValue); - // } - //} - - lines->push_back(title); - unformattedStrings.push_back(title); - item->appendHoverText(shared_from_this(), player, lines, advanced, unformattedStrings); - - if (hasTag()) - { - ListTag *list = getEnchantmentTags(); - if (list != NULL) - { - for (int i = 0; i < list->size(); i++) - { - int type = list->get(i)->getShort((wchar_t *)TAG_ENCH_ID); - int level = list->get(i)->getShort((wchar_t *)TAG_ENCH_LEVEL); - - if (Enchantment::enchantments[type] != NULL) - { - std::wstring unformatted = L""; - lines->push_back(Enchantment::enchantments[type]->getFullname(level, unformatted)); - unformattedStrings.push_back(unformatted); - } - } - } - } - return lines; + if (Enchantment::enchantments[type] != NULL) { + std::wstring unformatted = L""; + lines->push_back( + Enchantment::enchantments[type]->getFullname( + level, unformatted)); + unformattedStrings.push_back(unformatted); + } + } + } + } + return lines; } // 4J Added -std::vector *ItemInstance::getHoverTextOnly(std::shared_ptr player, bool advanced, std::vector &unformattedStrings) -{ - std::vector *lines = new std::vector(); - Item *item = Item::items[id]; +std::vector* ItemInstance::getHoverTextOnly( + std::shared_ptr player, bool advanced, + std::vector& unformattedStrings) { + std::vector* lines = new std::vector(); + Item* item = Item::items[id]; - item->appendHoverText(shared_from_this(), player, lines, advanced, unformattedStrings); + item->appendHoverText(shared_from_this(), player, lines, advanced, + unformattedStrings); - if (hasTag()) - { - ListTag *list = getEnchantmentTags(); - if (list != NULL) - { - for (int i = 0; i < list->size(); i++) - { - int type = list->get(i)->getShort((wchar_t *)TAG_ENCH_ID); - int level = list->get(i)->getShort((wchar_t *)TAG_ENCH_LEVEL); + if (hasTag()) { + ListTag* list = getEnchantmentTags(); + if (list != NULL) { + for (int i = 0; i < list->size(); i++) { + int type = list->get(i)->getShort((wchar_t*)TAG_ENCH_ID); + int level = list->get(i)->getShort((wchar_t*)TAG_ENCH_LEVEL); - if (Enchantment::enchantments[type] != NULL) - { - std::wstring unformatted = L""; - lines->push_back(Enchantment::enchantments[type]->getFullname(level,unformatted)); - unformattedStrings.push_back(unformatted); - } - } - } - } - return lines; + if (Enchantment::enchantments[type] != NULL) { + std::wstring unformatted = L""; + lines->push_back( + Enchantment::enchantments[type]->getFullname( + level, unformatted)); + unformattedStrings.push_back(unformatted); + } + } + } + } + return lines; } -bool ItemInstance::isFoil() -{ - return getItem()->isFoil(shared_from_this()); +bool ItemInstance::isFoil() { return getItem()->isFoil(shared_from_this()); } + +const Rarity* ItemInstance::getRarity() { + return getItem()->getRarity(shared_from_this()); } -const Rarity *ItemInstance::getRarity() -{ - return getItem()->getRarity(shared_from_this()); +bool ItemInstance::isEnchantable() { + if (!getItem()->isEnchantable(shared_from_this())) return false; + if (isEnchanted()) return false; + return true; } -bool ItemInstance::isEnchantable() -{ - if (!getItem()->isEnchantable(shared_from_this())) return false; - if (isEnchanted()) return false; - return true; +void ItemInstance::enchant(const Enchantment* enchantment, int level) { + if (tag == NULL) this->setTag(new CompoundTag()); + if (!tag->contains(L"ench")) + tag->put(L"ench", new ListTag(L"ench")); + + ListTag* list = (ListTag*)tag->get(L"ench"); + CompoundTag* ench = new CompoundTag(); + ench->putShort((wchar_t*)TAG_ENCH_ID, (short)enchantment->id); + ench->putShort((wchar_t*)TAG_ENCH_LEVEL, (uint8_t)level); + list->add(ench); } -void ItemInstance::enchant(const Enchantment *enchantment, int level) -{ - if (tag == NULL) this->setTag(new CompoundTag()); - if (!tag->contains(L"ench")) tag->put(L"ench", new ListTag(L"ench")); - - ListTag *list = (ListTag *) tag->get(L"ench"); - CompoundTag *ench = new CompoundTag(); - ench->putShort((wchar_t *)TAG_ENCH_ID, (short) enchantment->id); - ench->putShort((wchar_t *)TAG_ENCH_LEVEL, (uint8_t) level); - list->add(ench); +bool ItemInstance::isEnchanted() { + if (tag != NULL && tag->contains(L"ench")) return true; + return false; } -bool ItemInstance::isEnchanted() -{ - if (tag != NULL && tag->contains(L"ench")) return true; - return false; +void ItemInstance::addTagElement(std::wstring name, Tag* tag) { + if (this->tag == NULL) { + this->setTag(new CompoundTag()); + } + this->tag->put((wchar_t*)name.c_str(), tag); } -void ItemInstance::addTagElement(std::wstring name, Tag *tag) -{ - if (this->tag == NULL) - { - this->setTag(new CompoundTag()); - } - this->tag->put((wchar_t *)name.c_str(), tag); +void ItemInstance::set4JData(int data) { + if (tag == NULL && data == 0) return; + if (tag == NULL) this->setTag(new CompoundTag()); + + if (tag->contains(L"4jdata")) { + IntTag* dataTag = (IntTag*)tag->get(L"4jdata"); + dataTag->data = data; + } else if (data != 0) { + tag->put(L"4jdata", new IntTag(L"4jdata", data)); + } } -void ItemInstance::set4JData(int data) -{ - if(tag == NULL && data == 0) return; - if (tag == NULL) this->setTag(new CompoundTag()); - - if (tag->contains(L"4jdata")) - { - IntTag *dataTag = (IntTag *)tag->get(L"4jdata"); - dataTag->data = data; - } - else if(data != 0) - { - tag->put(L"4jdata", new IntTag(L"4jdata",data)); - } -} - -int ItemInstance::get4JData() -{ - if(tag == NULL || !tag->contains(L"4jdata")) return 0; - else - { - IntTag *dataTag = (IntTag *)tag->get(L"4jdata"); - return dataTag->data; - } +int ItemInstance::get4JData() { + if (tag == NULL || !tag->contains(L"4jdata")) + return 0; + else { + IntTag* dataTag = (IntTag*)tag->get(L"4jdata"); + return dataTag->data; + } } // 4J Added - to show strength on potions -bool ItemInstance::hasPotionStrengthBar() -{ - // exclude a bottle of water from this - if((id==Item::potion_Id) && (auxValue !=0))// && (!MACRO_POTION_IS_AKWARD(auxValue))) 4J-PB leaving the bar on an awkward potion so we can differentiate it from a water bottle - { - return true; - } +bool ItemInstance::hasPotionStrengthBar() { + // exclude a bottle of water from this + if ((id == Item::potion_Id) && + (auxValue != 0)) // && (!MACRO_POTION_IS_AKWARD(auxValue))) 4J-PB + // leaving the bar on an awkward potion so we can + // differentiate it from a water bottle + { + return true; + } - return false; + return false; } -int ItemInstance::GetPotionStrength() -{ - if(MACRO_POTION_IS_INSTANTDAMAGE(auxValue) || MACRO_POTION_IS_INSTANTHEALTH(auxValue) ) - { - // The two instant potions don't have extended versions - return (auxValue&MASK_LEVEL2)>>5; - } - else - { - return (auxValue&MASK_LEVEL2EXTENDED)>>5; - } +int ItemInstance::GetPotionStrength() { + if (MACRO_POTION_IS_INSTANTDAMAGE(auxValue) || + MACRO_POTION_IS_INSTANTHEALTH(auxValue)) { + // The two instant potions don't have extended versions + return (auxValue & MASK_LEVEL2) >> 5; + } else { + return (auxValue & MASK_LEVEL2EXTENDED) >> 5; + } } // TU9 -bool ItemInstance::isFramed() -{ - return frame != NULL; +bool ItemInstance::isFramed() { return frame != NULL; } + +void ItemInstance::setFramed(std::shared_ptr frame) { + this->frame = frame; } -void ItemInstance::setFramed(std::shared_ptr frame) -{ - this->frame = frame; +std::shared_ptr ItemInstance::getFrame() { return frame; } + +int ItemInstance::getBaseRepairCost() { + if (hasTag() && tag->contains(L"RepairCost")) { + return tag->getInt(L"RepairCost"); + } else { + return 0; + } } -std::shared_ptr ItemInstance::getFrame() -{ - return frame; -} - -int ItemInstance::getBaseRepairCost() -{ - if (hasTag() && tag->contains(L"RepairCost")) - { - return tag->getInt(L"RepairCost"); - } - else - { - return 0; - } -} - -void ItemInstance::setRepairCost(int cost) -{ - if (!hasTag()) tag = new CompoundTag(); - tag->putInt(L"RepairCost", cost); +void ItemInstance::setRepairCost(int cost) { + if (!hasTag()) tag = new CompoundTag(); + tag->putInt(L"RepairCost", cost); } diff --git a/Minecraft.World/Items/ItemInstance.h b/Minecraft.World/Items/ItemInstance.h index 6a706d0ad..9fb7bfebe 100644 --- a/Minecraft.World/Items/ItemInstance.h +++ b/Minecraft.World/Items/ItemInstance.h @@ -1,6 +1,5 @@ #pragma once - #include "../Util/UseAnim.h" #include "../Headers/com.mojang.nbt.h" @@ -16,20 +15,20 @@ class MapItem; class ItemFrame; class Icon; -// 4J Stu - While this is not really an abstract class, we don't want to make new instances of it, -// mainly because there are too many ctors and that doesn't fit well into out macroisation setup -class ItemInstance: public std::enable_shared_from_this -{ +// 4J Stu - While this is not really an abstract class, we don't want to make +// new instances of it, mainly because there are too many ctors and that doesn't +// fit well into out macroisation setup +class ItemInstance : public std::enable_shared_from_this { public: - static const wchar_t *TAG_ENCH_ID; - static const wchar_t *TAG_ENCH_LEVEL; + static const wchar_t* TAG_ENCH_ID; + static const wchar_t* TAG_ENCH_LEVEL; - int count; + int count; int popTime; int id; - // 4J Stu - Brought forward for enchanting/game rules - CompoundTag *tag; + // 4J Stu - Brought forward for enchanting/game rules + CompoundTag* tag; /** * This was previously the damage value, but is now used for different stuff @@ -37,118 +36,142 @@ public: * is interpreted correctly. */ private: - int auxValue; - // 4J-PB - added for trading menu - bool m_bForceNumberDisplay; + int auxValue; + // 4J-PB - added for trading menu + bool m_bForceNumberDisplay; - void _init(int id, int count, int auxValue); + void _init(int id, int count, int auxValue); - // TU9 - std::shared_ptr frame; + // TU9 + std::shared_ptr frame; public: - ItemInstance(Tile *tile); - ItemInstance(Tile *tile, int count); - ItemInstance(Tile *tile, int count, int auxValue); - ItemInstance(Item *item); - // 4J-PB - added - ItemInstance(MapItem *item, int count); + ItemInstance(Tile* tile); + ItemInstance(Tile* tile, int count); + ItemInstance(Tile* tile, int count, int auxValue); + ItemInstance(Item* item); + // 4J-PB - added + ItemInstance(MapItem* item, int count); - ItemInstance(Item *item, int count); - ItemInstance(Item *item, int count, int auxValue); - ItemInstance(int id, int count, int damage); + ItemInstance(Item* item, int count); + ItemInstance(Item* item, int count, int auxValue); + ItemInstance(int id, int count, int damage); - static std::shared_ptr fromTag(CompoundTag *itemTag); -private: - ItemInstance() { _init(-1,0,0); } - -public: - virtual ~ItemInstance(); - std::shared_ptr remove(int count); - - Item *getItem() const; - Icon *getIcon(); - int getIconType(); - bool useOn(std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX = 0.0f, float clickY = 0.0f, float clickZ = 0.0f, bool bTestUseOnOnly=false); - float getDestroySpeed(Tile *tile); - bool TestUse(Level *level, std::shared_ptr player); - std::shared_ptr use(Level *level, std::shared_ptr player); - std::shared_ptr useTimeDepleted(Level *level, std::shared_ptr player); - CompoundTag *save(CompoundTag *compoundTag); - void load(CompoundTag *compoundTag); - int getMaxStackSize(); - bool isStackable(); - bool isDamageableItem(); - bool isStackedByData(); - bool isDamaged(); - int getDamageValue(); - int getAuxValue() const; - void setAuxValue(int value); - int getMaxDamage(); - void hurt(int i, std::shared_ptr owner); - void hurtEnemy(std::shared_ptr mob, std::shared_ptr attacker); - void mineBlock(Level *level, int tile, int x, int y, int z, std::shared_ptr owner); - int getAttackDamage(std::shared_ptr entity); - bool canDestroySpecial(Tile *tile); - bool interactEnemy(std::shared_ptr mob); - std::shared_ptr copy() const; - ItemInstance *copy_not_shared() const; // 4J Stu - Added for use in recipes - static bool tagMatches(std::shared_ptr a, std::shared_ptr b); // 4J Brought forward from 1.2 - static bool matches(std::shared_ptr a, std::shared_ptr b); - - // 4J-PB - int GetCount() {return count;} - void ForceNumberDisplay(bool bForce) {m_bForceNumberDisplay=bForce;} // to force the display of 0 and 1 on the required trading items when you have o or 1 of the item - bool GetForceNumberDisplay() {return m_bForceNumberDisplay;} // to force the display of 0 and 1 on the required trading items when you have o or 1 of the item + static std::shared_ptr fromTag(CompoundTag* itemTag); private: - bool matches(std::shared_ptr b); + ItemInstance() { _init(-1, 0, 0); } public: - bool sameItem(std::shared_ptr b); - bool sameItemWithTags(std::shared_ptr b); //4J Added - bool sameItem_not_shared(ItemInstance *b); // 4J Stu - Added this for the one time I need it - virtual unsigned int getUseDescriptionId(); // 4J Added - virtual unsigned int getDescriptionId(int iData = -1); - virtual ItemInstance *setDescriptionId(unsigned int id); - static std::shared_ptr clone(std::shared_ptr item); - std::wstring toString(); - void inventoryTick(Level *level, std::shared_ptr owner, int slot, bool selected); - void onCraftedBy(Level *level, std::shared_ptr player, int craftCount); - bool equals(std::shared_ptr ii); + virtual ~ItemInstance(); + std::shared_ptr remove(int count); - int getUseDuration(); - UseAnim getUseAnimation(); - void releaseUsing(Level *level, std::shared_ptr player, int durationLeft); + Item* getItem() const; + Icon* getIcon(); + int getIconType(); + bool useOn(std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX = 0.0f, float clickY = 0.0f, + float clickZ = 0.0f, bool bTestUseOnOnly = false); + float getDestroySpeed(Tile* tile); + bool TestUse(Level* level, std::shared_ptr player); + std::shared_ptr use(Level* level, + std::shared_ptr player); + std::shared_ptr useTimeDepleted( + Level* level, std::shared_ptr player); + CompoundTag* save(CompoundTag* compoundTag); + void load(CompoundTag* compoundTag); + int getMaxStackSize(); + bool isStackable(); + bool isDamageableItem(); + bool isStackedByData(); + bool isDamaged(); + int getDamageValue(); + int getAuxValue() const; + void setAuxValue(int value); + int getMaxDamage(); + void hurt(int i, std::shared_ptr owner); + void hurtEnemy(std::shared_ptr mob, std::shared_ptr attacker); + void mineBlock(Level* level, int tile, int x, int y, int z, + std::shared_ptr owner); + int getAttackDamage(std::shared_ptr entity); + bool canDestroySpecial(Tile* tile); + bool interactEnemy(std::shared_ptr mob); + std::shared_ptr copy() const; + ItemInstance* copy_not_shared() const; // 4J Stu - Added for use in recipes + static bool tagMatches( + std::shared_ptr a, + std::shared_ptr b); // 4J Brought forward from 1.2 + static bool matches(std::shared_ptr a, + std::shared_ptr b); - // 4J Stu - Brought forward these functions for enchanting/game rules - bool hasTag(); - CompoundTag *getTag(); - ListTag *getEnchantmentTags(); - void setTag(CompoundTag *tag); - std::wstring getHoverName(); - void setHoverName(const std::wstring &name); - bool hasCustomHoverName(); - std::vector *getHoverText(std::shared_ptr player, bool advanced, std::vector &unformattedStrings); - std::vector *getHoverTextOnly(std::shared_ptr player, bool advanced, std::vector &unformattedStrings); // 4J Added - bool isFoil(); - const Rarity *getRarity(); - bool isEnchantable(); - void enchant(const Enchantment *enchantment, int level); - bool isEnchanted(); - void addTagElement(std::wstring name, Tag *tag); + // 4J-PB + int GetCount() { return count; } + void ForceNumberDisplay(bool bForce) { + m_bForceNumberDisplay = bForce; + } // to force the display of 0 and 1 on the required trading items when you + // have o or 1 of the item + bool GetForceNumberDisplay() { + return m_bForceNumberDisplay; + } // to force the display of 0 and 1 on the required trading items when you + // have o or 1 of the item - // 4J Added - void set4JData(int data); - int get4JData(); - bool hasPotionStrengthBar(); - int GetPotionStrength(); +private: + bool matches(std::shared_ptr b); - // TU9 - bool isFramed(); - void setFramed(std::shared_ptr frame); - std::shared_ptr getFrame(); +public: + bool sameItem(std::shared_ptr b); + bool sameItemWithTags(std::shared_ptr b); // 4J Added + bool sameItem_not_shared( + ItemInstance* b); // 4J Stu - Added this for the one time I need it + virtual unsigned int getUseDescriptionId(); // 4J Added + virtual unsigned int getDescriptionId(int iData = -1); + virtual ItemInstance* setDescriptionId(unsigned int id); + static std::shared_ptr clone( + std::shared_ptr item); + std::wstring toString(); + void inventoryTick(Level* level, std::shared_ptr owner, int slot, + bool selected); + void onCraftedBy(Level* level, std::shared_ptr player, + int craftCount); + bool equals(std::shared_ptr ii); - int getBaseRepairCost(); - void setRepairCost(int cost); + int getUseDuration(); + UseAnim getUseAnimation(); + void releaseUsing(Level* level, std::shared_ptr player, + int durationLeft); + + // 4J Stu - Brought forward these functions for enchanting/game rules + bool hasTag(); + CompoundTag* getTag(); + ListTag* getEnchantmentTags(); + void setTag(CompoundTag* tag); + std::wstring getHoverName(); + void setHoverName(const std::wstring& name); + bool hasCustomHoverName(); + std::vector* getHoverText( + std::shared_ptr player, bool advanced, + std::vector& unformattedStrings); + std::vector* getHoverTextOnly( + std::shared_ptr player, bool advanced, + std::vector& unformattedStrings); // 4J Added + bool isFoil(); + const Rarity* getRarity(); + bool isEnchantable(); + void enchant(const Enchantment* enchantment, int level); + bool isEnchanted(); + void addTagElement(std::wstring name, Tag* tag); + + // 4J Added + void set4JData(int data); + int get4JData(); + bool hasPotionStrengthBar(); + int GetPotionStrength(); + + // TU9 + bool isFramed(); + void setFramed(std::shared_ptr frame); + std::shared_ptr getFrame(); + + int getBaseRepairCost(); + void setRepairCost(int cost); }; diff --git a/Minecraft.World/Items/MapItem.cpp b/Minecraft.World/Items/MapItem.cpp index 908d0f776..2c11e6593 100644 --- a/Minecraft.World/Items/MapItem.cpp +++ b/Minecraft.World/Items/MapItem.cpp @@ -14,334 +14,336 @@ #include "../Headers/net.minecraft.world.inventory.h" #include "../Util/JavaMath.h" -MapItem::MapItem(int id) : ComplexItem(id) -{ - this->setMaxStackSize(1); +MapItem::MapItem(int id) : ComplexItem(id) { this->setMaxStackSize(1); } + +std::shared_ptr MapItem::getSavedData(short idNum, + Level* level) { + std::wstring id = std::wstring(L"map_") + _toString(idNum); + std::shared_ptr mapItemSavedData = + std::dynamic_pointer_cast( + level->getSavedData(typeid(MapItemSavedData), id)); + + if (mapItemSavedData == NULL) { + // 4J Stu - This call comes from ClientConnection, but i don't see why + // we should be trying to work out the id again when it's passed as a + // param. In any case that won't work with the new map setup + // int aux = level->getFreeAuxValueFor(L"map"); + int aux = idNum; + + id = std::wstring(L"map_") + _toString(aux); + mapItemSavedData = + std::shared_ptr(new MapItemSavedData(id)); + + level->setSavedData(id, (std::shared_ptr)mapItemSavedData); + } + + return mapItemSavedData; } -std::shared_ptr MapItem::getSavedData(short idNum, Level *level) -{ - std::wstring id = std::wstring( L"map_" ) + _toString(idNum); - std::shared_ptr mapItemSavedData = std::dynamic_pointer_cast(level->getSavedData(typeid(MapItemSavedData), id)); +std::shared_ptr MapItem::getSavedData( + std::shared_ptr itemInstance, Level* level) { + MemSect(31); + std::wstring id = + std::wstring(L"map_") + _toString(itemInstance->getAuxValue()); + MemSect(0); + std::shared_ptr mapItemSavedData = + std::dynamic_pointer_cast( + level->getSavedData(typeid(MapItemSavedData), id)); - if (mapItemSavedData == NULL) - { - // 4J Stu - This call comes from ClientConnection, but i don't see why we should be trying to work out - // the id again when it's passed as a param. In any case that won't work with the new map setup - //int aux = level->getFreeAuxValueFor(L"map"); - int aux = idNum; + bool newData = false; + if (mapItemSavedData == NULL) { + // 4J Stu - I don't see why we should be trying to work out the id again + // when it's passed as a param. In any case that won't work with the new + // map setup + // itemInstance->setAuxValue(level->getFreeAuxValueFor(L"map")); - id = std::wstring( L"map_" ) + _toString(aux); - mapItemSavedData = std::shared_ptr( new MapItemSavedData(id) ); + id = std::wstring(L"map_") + _toString(itemInstance->getAuxValue()); + mapItemSavedData = + std::shared_ptr(new MapItemSavedData(id)); - level->setSavedData(id, (std::shared_ptr ) mapItemSavedData); - } + newData = true; + } - return mapItemSavedData; -} - -std::shared_ptr MapItem::getSavedData(std::shared_ptr itemInstance, Level *level) -{ - MemSect(31); - std::wstring id = std::wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); - MemSect(0); - std::shared_ptr mapItemSavedData = std::dynamic_pointer_cast( level->getSavedData(typeid(MapItemSavedData), id ) ); - - bool newData = false; - if (mapItemSavedData == NULL) - { - // 4J Stu - I don't see why we should be trying to work out the id again when it's passed as a param. - // In any case that won't work with the new map setup - //itemInstance->setAuxValue(level->getFreeAuxValueFor(L"map")); - - id = std::wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); - mapItemSavedData = std::shared_ptr( new MapItemSavedData(id) ); - - newData = true; - } - - mapItemSavedData->scale = 3; + mapItemSavedData->scale = 3; #ifndef _LARGE_WORLDS - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - mapItemSavedData->x = 0; - mapItemSavedData->z = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, + // since we can fit the whole world in our map + mapItemSavedData->x = 0; + mapItemSavedData->z = 0; #endif - if( newData ) - { + if (newData) { #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapItemSavedData->scale); - mapItemSavedData->x = Math::round((float) level->getLevelData()->getXSpawn() / scale) * scale; - mapItemSavedData->z = Math::round(level->getLevelData()->getZSpawn() / scale) * scale; + int scale = + MapItemSavedData::MAP_SIZE * 2 * (1 << mapItemSavedData->scale); + mapItemSavedData->x = + Math::round((float)level->getLevelData()->getXSpawn() / scale) * + scale; + mapItemSavedData->z = + Math::round(level->getLevelData()->getZSpawn() / scale) * scale; #endif - mapItemSavedData->dimension = (uint8_t) level->dimension->id; - - mapItemSavedData->setDirty(); + mapItemSavedData->dimension = (uint8_t)level->dimension->id; - level->setSavedData(id, (std::shared_ptr ) mapItemSavedData); - } + mapItemSavedData->setDirty(); - return mapItemSavedData; + level->setSavedData(id, (std::shared_ptr)mapItemSavedData); + } + + return mapItemSavedData; } -void MapItem::update(Level *level, std::shared_ptr player, std::shared_ptr data) -{ - if (level->dimension->id != data->dimension) - { - // Wrong dimension, abort - return; - } +void MapItem::update(Level* level, std::shared_ptr player, + std::shared_ptr data) { + if (level->dimension->id != data->dimension) { + // Wrong dimension, abort + return; + } - int w = MapItem::IMAGE_WIDTH; - int h = MapItem::IMAGE_HEIGHT; + int w = MapItem::IMAGE_WIDTH; + int h = MapItem::IMAGE_HEIGHT; - int scale = 1 << data->scale; + int scale = 1 << data->scale; - int xo = data->x; - int zo = data->z; + int xo = data->x; + int zo = data->z; - int xp = Mth::floor(player->x - xo) / scale + w / 2; - int zp = Mth::floor(player->z - zo) / scale + h / 2; + int xp = Mth::floor(player->x - xo) / scale + w / 2; + int zp = Mth::floor(player->z - zo) / scale + h / 2; - int rad = 128 / scale; - if (level->dimension->hasCeiling) - { - rad /= 2; - } - data->step++; + int rad = 128 / scale; + if (level->dimension->hasCeiling) { + rad /= 2; + } + data->step++; - for (int x = xp - rad + 1; x < xp + rad; x++) - { - if ((x & 15) != (data->step & 15)) continue; + for (int x = xp - rad + 1; x < xp + rad; x++) { + if ((x & 15) != (data->step & 15)) continue; - int yd0 = 255; - int yd1 = 0; + int yd0 = 255; + int yd1 = 0; - double ho = 0; - for (int z = zp - rad - 1; z < zp + rad; z++) - { - if (x < 0 || z < -1 || x >= w || z >= h) continue; + double ho = 0; + for (int z = zp - rad - 1; z < zp + rad; z++) { + if (x < 0 || z < -1 || x >= w || z >= h) continue; - int xd = x - xp; - int zd = z - zp; + int xd = x - xp; + int zd = z - zp; - bool ditherBlack = xd * xd + zd * zd > (rad - 2) * (rad - 2); + bool ditherBlack = xd * xd + zd * zd > (rad - 2) * (rad - 2); - int xx = (xo / scale + x - w / 2) * scale; - int zz = (zo / scale + z - h / 2) * scale; + int xx = (xo / scale + x - w / 2) * scale; + int zz = (zo / scale + z - h / 2) * scale; - int r = 0; - int g = 0; - int b = 0; + int r = 0; + int g = 0; + int b = 0; + int count[256]; + memset(count, 0, sizeof(int) * 256); - int count[256]; - memset( count,0,sizeof(int)*256); + LevelChunk* lc = level->getChunkAt(xx, zz); + if (lc->isEmpty()) continue; + int xso = ((xx)) & 15; + int zso = ((zz)) & 15; + int liquidDepth = 0; - LevelChunk *lc = level->getChunkAt(xx, zz); - if(lc->isEmpty()) continue; - int xso = ((xx)) & 15; - int zso = ((zz)) & 15; - int liquidDepth = 0; + double hh = 0; + if (level->dimension->hasCeiling) { + int ss = xx + zz * 231871; + ss = ss * ss * 31287121 + ss * 11; + if (((ss >> 20) & 1) == 0) + count[Tile::dirt_Id] += 10; + else + count[Tile::rock_Id] += 10; + hh = 100; + } else { + for (int xs = 0; xs < scale; xs++) { + for (int zs = 0; zs < scale; zs++) { + int yy = lc->getHeightmap(xs + xso, zs + zso) + 1; + int t = 0; + if (yy > 1) { + bool ok = false; + do { + ok = true; + t = lc->getTile(xs + xso, yy - 1, zs + zso); + if (t == 0) + ok = false; + else if (yy > 0 && t > 0 && + Tile::tiles[t]->material->color == + MaterialColor::none) { + ok = false; + } - double hh = 0; - if (level->dimension->hasCeiling) - { - int ss = xx + zz * 231871; - ss = ss * ss * 31287121 + ss * 11; - if (((ss >> 20) & 1) == 0) count[Tile::dirt_Id] += 10; - else count[Tile::rock_Id] += 10; - hh = 100; - } - else - { - for (int xs = 0; xs < scale; xs++) - { - for (int zs = 0; zs < scale; zs++) - { - int yy = lc->getHeightmap(xs + xso, zs + zso) + 1; - int t = 0; - if (yy > 1) - { - bool ok = false; - do - { - ok = true; - t = lc->getTile(xs + xso, yy - 1, zs + zso); - if (t == 0) ok = false; - else if (yy > 0 && t > 0 && Tile::tiles[t]->material->color == MaterialColor::none) - { - ok = false; - } + if (!ok) { + yy--; + if (yy <= 0) break; + t = lc->getTile(xs + xso, yy - 1, zs + zso); + } - if (!ok) - { - yy--; - if (yy <= 0) break; - t = lc->getTile(xs + xso, yy - 1, zs + zso); - } + } while (yy > 0 && !ok); - } while (yy > 0 && !ok); + if (yy > 0 && t != 0 && + Tile::tiles[t]->material->isLiquid()) { + int y = yy - 1; + int below = 0; + do { + below = + lc->getTile(xs + xso, y--, zs + zso); + liquidDepth++; + } while ( + y > 0 && below != 0 && + Tile::tiles[below]->material->isLiquid()); + } + } + hh += yy / (double)(scale * scale); - if (yy > 0 && t != 0 && Tile::tiles[t]->material->isLiquid()) - { - int y = yy - 1; - int below = 0; - do - { - below = lc->getTile(xs + xso, y--, zs + zso); - liquidDepth++; - } while (y > 0 && below != 0 && Tile::tiles[below]->material->isLiquid()); - } - } - hh += yy / (double) (scale * scale); + count[t]++; + } + } + } + liquidDepth /= scale * scale; + r /= scale * scale; + g /= scale * scale; + b /= scale * scale; - count[t]++; - } - } - } - liquidDepth /= scale * scale; - r /= scale * scale; - g /= scale * scale; - b /= scale * scale; + int best = 0; + int tBest = 0; + for (int j = 0; j < 256; j++) { + if (count[j] > best) { + tBest = j; + best = count[j]; + } + } - int best = 0; - int tBest = 0; - for (int j = 0; j < 256; j++) - { - if (count[j] > best) - { - tBest = j; - best = count[j]; - } - } + double diff = + ((hh - ho) * 4 / (scale + 4)) + (((x + z) & 1) - 0.5) * 0.4; + int br = 1; + if (diff > +0.6) br = 2; + if (diff < -0.6) br = 0; - double diff = ((hh - ho) * 4 / (scale + 4)) + (((x + z) & 1) - 0.5) * 0.4; - int br = 1; - if (diff > +0.6) br = 2; - if (diff < -0.6) br = 0; + int col = 0; + if (tBest > 0) { + MaterialColor* mc = Tile::tiles[tBest]->material->color; + if (mc == MaterialColor::water) { + diff = (liquidDepth * 0.1) + ((x + z) & 1) * 0.2; + br = 1; + if (diff < 0.5) br = 2; + if (diff > 0.9) br = 0; + } + col = mc->id; + } - int col = 0; - if (tBest > 0) - { - MaterialColor *mc = Tile::tiles[tBest]->material->color; - if (mc == MaterialColor::water) - { - diff = (liquidDepth * 0.1) + ((x + z) & 1) * 0.2; - br = 1; - if (diff < 0.5) br = 2; - if (diff > 0.9) br = 0; - } - col = mc->id; - } + ho = hh; - ho = hh; - - if (z < 0) continue; - if (xd * xd + zd * zd >= rad * rad) continue; - if (ditherBlack && ((x + z) & 1) == 0) - { - continue; - } - uint8_t oldColor = data->colors[x + z * w]; - uint8_t newColor = (uint8_t) (col * 4 + br); - if (oldColor != newColor) - { - if (yd0 > z) yd0 = z; - if (yd1 < z) yd1 = z; - data->colors[x + z * w] = newColor; - } - } - if (yd0 <= yd1) - { - data->setDirty(x, yd0, yd1); - } - } + if (z < 0) continue; + if (xd * xd + zd * zd >= rad * rad) continue; + if (ditherBlack && ((x + z) & 1) == 0) { + continue; + } + uint8_t oldColor = data->colors[x + z * w]; + uint8_t newColor = (uint8_t)(col * 4 + br); + if (oldColor != newColor) { + if (yd0 > z) yd0 = z; + if (yd1 < z) yd1 = z; + data->colors[x + z * w] = newColor; + } + } + if (yd0 <= yd1) { + data->setDirty(x, yd0, yd1); + } + } } -void MapItem::inventoryTick(std::shared_ptr itemInstance, Level *level, std::shared_ptr owner, int slot, bool selected) -{ - if (level->isClientSide) return; +void MapItem::inventoryTick(std::shared_ptr itemInstance, + Level* level, std::shared_ptr owner, + int slot, bool selected) { + if (level->isClientSide) return; - std::shared_ptr data = getSavedData(itemInstance, level); - if (std::dynamic_pointer_cast(owner) != NULL) - { - std::shared_ptr player = std::dynamic_pointer_cast(owner); + std::shared_ptr data = getSavedData(itemInstance, level); + if (std::dynamic_pointer_cast(owner) != NULL) { + std::shared_ptr player = + std::dynamic_pointer_cast(owner); - // 4J Stu - If the player has a map that belongs to another player, then merge the data over and change this map id to the owners id - int ownersAuxValue = level->getAuxValueForMap(player->getXuid(), data->dimension, data->x, data->z, data->scale); - if(ownersAuxValue != itemInstance->getAuxValue() ) - { - std::shared_ptr ownersData = getSavedData(ownersAuxValue,level); + // 4J Stu - If the player has a map that belongs to another player, then + // merge the data over and change this map id to the owners id + int ownersAuxValue = level->getAuxValueForMap( + player->getXuid(), data->dimension, data->x, data->z, data->scale); + if (ownersAuxValue != itemInstance->getAuxValue()) { + std::shared_ptr ownersData = + getSavedData(ownersAuxValue, level); - ownersData->x = data->x; - ownersData->z = data->z; - ownersData->scale = data->scale; - ownersData->dimension = data->dimension; + ownersData->x = data->x; + ownersData->z = data->z; + ownersData->scale = data->scale; + ownersData->dimension = data->dimension; - itemInstance->setAuxValue( ownersAuxValue ); - ownersData->tickCarriedBy(player, itemInstance ); - ownersData->mergeInMapData(data); - player->inventoryMenu->broadcastChanges(); - - data = ownersData; - } - else - { - data->tickCarriedBy(player, itemInstance); - } - } + itemInstance->setAuxValue(ownersAuxValue); + ownersData->tickCarriedBy(player, itemInstance); + ownersData->mergeInMapData(data); + player->inventoryMenu->broadcastChanges(); - if (selected) - { - update(level, owner, data); - } + data = ownersData; + } else { + data->tickCarriedBy(player, itemInstance); + } + } + + if (selected) { + update(level, owner, data); + } } -void MapItem::onCraftedBy(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - wchar_t buf[64]; +void MapItem::onCraftedBy(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player) { + wchar_t buf[64]; - int mapScale = 3; + int mapScale = 3; #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); + int centreXC = (int)(Math::round(player->x / scale) * scale); + int centreZC = (int)(Math::round(player->z / scale) * scale); #else - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - int centreXC = 0; - int centreZC = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, + // since we can fit the whole world in our map + int centreXC = 0; + int centreZC = 0; #endif - itemInstance->setAuxValue(level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale)); - - swprintf(buf,64,L"map_%d", itemInstance->getAuxValue()); - std::wstring id = std::wstring(buf); + itemInstance->setAuxValue(level->getAuxValueForMap( + player->getXuid(), player->dimension, centreXC, centreZC, mapScale)); - std::shared_ptr data = getSavedData(itemInstance->getAuxValue(), level); - // 4J Stu - We only have one map per player per dimension, so don't reset the one that they have - // when a new one is created - if( data == NULL ) - { - data = std::shared_ptr( new MapItemSavedData(id) ); - } - level->setSavedData(id, (std::shared_ptr ) data); - - data->scale = mapScale; - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - data->x = centreXC; - data->z = centreZC; - data->dimension = (uint8_t) level->dimension->id; - data->setDirty(); + swprintf(buf, 64, L"map_%d", itemInstance->getAuxValue()); + std::wstring id = std::wstring(buf); + + std::shared_ptr data = + getSavedData(itemInstance->getAuxValue(), level); + // 4J Stu - We only have one map per player per dimension, so don't reset + // the one that they have when a new one is created + if (data == NULL) { + data = std::shared_ptr(new MapItemSavedData(id)); + } + level->setSavedData(id, (std::shared_ptr)data); + + data->scale = mapScale; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, + // since we can fit the whole world in our map + data->x = centreXC; + data->z = centreZC; + data->dimension = (uint8_t)level->dimension->id; + data->setDirty(); } -std::shared_ptr MapItem::getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - charArray data = MapItem::getSavedData(itemInstance, level)->getUpdatePacket(itemInstance, level, player); +std::shared_ptr MapItem::getUpdatePacket( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + charArray data = MapItem::getSavedData(itemInstance, level) + ->getUpdatePacket(itemInstance, level, player); - if (data.data == NULL || data.length == 0) return nullptr; + if (data.data == NULL || data.length == 0) return nullptr; - std::shared_ptr retval = std::shared_ptr(new ComplexItemDataPacket((short) Item::map->id, (short) itemInstance->getAuxValue(), data)); - delete[] data.data; //4jcraft, changed to [] - return retval; + std::shared_ptr retval = + std::shared_ptr(new ComplexItemDataPacket( + (short)Item::map->id, (short)itemInstance->getAuxValue(), data)); + delete[] data.data; // 4jcraft, changed to [] + return retval; } diff --git a/Minecraft.World/Items/MapItem.h b/Minecraft.World/Items/MapItem.h index 80aa857b9..1b6cee88f 100644 --- a/Minecraft.World/Items/MapItem.h +++ b/Minecraft.World/Items/MapItem.h @@ -1,23 +1,30 @@ #pragma once - #include "ComplexItem.h" class MapItemSavedData; -class MapItem : public ComplexItem -{ +class MapItem : public ComplexItem { public: - static const int IMAGE_WIDTH = 128; - static const int IMAGE_HEIGHT = 128; + static const int IMAGE_WIDTH = 128; + static const int IMAGE_HEIGHT = 128; -public: // 4J Stu - Was protected in Java, but then we can't access it where we need it - MapItem(int id); +public: // 4J Stu - Was protected in Java, but then we can't access it where we + // need it + MapItem(int id); - static std::shared_ptr getSavedData(short idNum, Level *level); - std::shared_ptr getSavedData(std::shared_ptr itemInstance, Level *level); - void update(Level *level, std::shared_ptr player, std::shared_ptr data); - virtual void inventoryTick(std::shared_ptr itemInstance, Level *level, std::shared_ptr owner, int slot, bool selected); - virtual void onCraftedBy(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - std::shared_ptr getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); + static std::shared_ptr getSavedData(short idNum, + Level* level); + std::shared_ptr getSavedData( + std::shared_ptr itemInstance, Level* level); + void update(Level* level, std::shared_ptr player, + std::shared_ptr data); + virtual void inventoryTick(std::shared_ptr itemInstance, + Level* level, std::shared_ptr owner, + int slot, bool selected); + virtual void onCraftedBy(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player); + std::shared_ptr getUpdatePacket( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); }; diff --git a/Minecraft.World/Items/MilkBucketItem.cpp b/Minecraft.World/Items/MilkBucketItem.cpp index 3e213dc3a..719c2898b 100644 --- a/Minecraft.World/Items/MilkBucketItem.cpp +++ b/Minecraft.World/Items/MilkBucketItem.cpp @@ -3,39 +3,36 @@ #include "../Headers/net.minecraft.world.entity.player.h" #include "MilkBucketItem.h" -MilkBucketItem::MilkBucketItem(int id) : Item( id ) -{ - setMaxStackSize(1); +MilkBucketItem::MilkBucketItem(int id) : Item(id) { setMaxStackSize(1); } + +std::shared_ptr MilkBucketItem::useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (!player->abilities.instabuild) instance->count--; + + if (!level->isClientSide) { + player->removeAllEffects(); + } + + if (instance->count <= 0) { + return std::shared_ptr( + new ItemInstance(Item::bucket_empty)); + } + return instance; } -std::shared_ptr MilkBucketItem::useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (!player->abilities.instabuild) instance->count--; - - if (!level->isClientSide) - { - player->removeAllEffects(); - } - - if (instance->count <= 0) - { - return std::shared_ptr( new ItemInstance(Item::bucket_empty) ); - } - return instance; +int MilkBucketItem::getUseDuration(std::shared_ptr itemInstance) { + return DRINK_DURATION; } -int MilkBucketItem::getUseDuration(std::shared_ptr itemInstance) -{ - return DRINK_DURATION; +UseAnim MilkBucketItem::getUseAnimation( + std::shared_ptr itemInstance) { + return UseAnim_drink; } -UseAnim MilkBucketItem::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_drink; -} - -std::shared_ptr MilkBucketItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - player->startUsingItem(instance, getUseDuration(instance)); - return instance; +std::shared_ptr MilkBucketItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + player->startUsingItem(instance, getUseDuration(instance)); + return instance; } \ No newline at end of file diff --git a/Minecraft.World/Items/MilkBucketItem.h b/Minecraft.World/Items/MilkBucketItem.h index 32c9a2155..cb4e2f065 100644 --- a/Minecraft.World/Items/MilkBucketItem.h +++ b/Minecraft.World/Items/MilkBucketItem.h @@ -2,16 +2,19 @@ #include "Item.h" -class MilkBucketItem : public Item -{ +class MilkBucketItem : public Item { private: - static const int DRINK_DURATION = (int) (20 * 1.6); + static const int DRINK_DURATION = (int)(20 * 1.6); public: - MilkBucketItem(int id); + MilkBucketItem(int id); - virtual std::shared_ptr useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual std::shared_ptr useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/MinecartItem.cpp b/Minecraft.World/Items/MinecartItem.cpp index ccf87fb99..95dc3545f 100644 --- a/Minecraft.World/Items/MinecartItem.cpp +++ b/Minecraft.World/Items/MinecartItem.cpp @@ -6,28 +6,27 @@ #include "ItemInstance.h" #include "MinecartItem.h" -MinecartItem::MinecartItem(int id, int type) : Item(id) -{ - this->maxStackSize = 1; - this->type = type; +MinecartItem::MinecartItem(int id, int type) : Item(id) { + this->maxStackSize = 1; + this->type = type; } -bool MinecartItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - int targetType = level->getTile(x, y, z); +bool MinecartItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + int targetType = level->getTile(x, y, z); - if (RailTile::isRail(targetType)) - { - if(!bTestUseOnOnly) - { - if (!level->isClientSide) - { - level->addEntity(std::shared_ptr( new Minecart(level, x + 0.5f, y + 0.5f, z + 0.5f, type) ) ); - } - instance->count--; - } - return true; - } - return false; + if (RailTile::isRail(targetType)) { + if (!bTestUseOnOnly) { + if (!level->isClientSide) { + level->addEntity(std::shared_ptr( + new Minecart(level, x + 0.5f, y + 0.5f, z + 0.5f, type))); + } + instance->count--; + } + return true; + } + return false; } \ No newline at end of file diff --git a/Minecraft.World/Items/MinecartItem.h b/Minecraft.World/Items/MinecartItem.h index d097fd5c4..f9d572fed 100644 --- a/Minecraft.World/Items/MinecartItem.h +++ b/Minecraft.World/Items/MinecartItem.h @@ -1,14 +1,15 @@ #pragma once - #include "Item.h" -class MinecartItem : public Item -{ +class MinecartItem : public Item { public: - int type; + int type; - MinecartItem(int id, int type); + MinecartItem(int id, int type); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/MonsterPlacerItem.cpp b/Minecraft.World/Items/MonsterPlacerItem.cpp index d0aee2507..b0a35abad 100644 --- a/Minecraft.World/Items/MonsterPlacerItem.cpp +++ b/Minecraft.World/Items/MonsterPlacerItem.cpp @@ -10,282 +10,253 @@ #include "MonsterPlacerItem.h" #include "../Util/Difficulty.h" - -MonsterPlacerItem::MonsterPlacerItem(int id) : Item(id) -{ - setMaxStackSize(16); // 4J-PB brought forward. It is 64 on PC, but we'll never be able to place that many - setStackedByData(true); - overlay = NULL; +MonsterPlacerItem::MonsterPlacerItem(int id) : Item(id) { + setMaxStackSize(16); // 4J-PB brought forward. It is 64 on PC, but we'll + // never be able to place that many + setStackedByData(true); + overlay = NULL; } -std::wstring MonsterPlacerItem::getHoverName(std::shared_ptr itemInstance) -{ - std::wstring elementName = getDescription(); +std::wstring MonsterPlacerItem::getHoverName( + std::shared_ptr itemInstance) { + std::wstring elementName = getDescription(); - int nameId = EntityIO::getNameId(itemInstance->getAuxValue()); - if (nameId >= 0) - { - elementName = replaceAll(elementName,L"{*CREATURE*}",app.GetString(nameId)); - //elementName += " " + I18n.get("entity." + encodeId + ".name"); - } - else - { - elementName = replaceAll(elementName,L"{*CREATURE*}",L""); - } + int nameId = EntityIO::getNameId(itemInstance->getAuxValue()); + if (nameId >= 0) { + elementName = + replaceAll(elementName, L"{*CREATURE*}", app.GetString(nameId)); + // elementName += " " + I18n.get("entity." + encodeId + ".name"); + } else { + elementName = replaceAll(elementName, L"{*CREATURE*}", L""); + } - return elementName; + return elementName; } -int MonsterPlacerItem::getColor(std::shared_ptr item, int spriteLayer) -{ - AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); - if (it != EntityIO::idsSpawnableInCreative.end()) - { - EntityIO::SpawnableMobInfo *spawnableMobInfo = it->second; - if (spriteLayer == 0) { - return Minecraft::GetInstance()->getColourTable()->getColor( spawnableMobInfo->eggColor1 ); - } - return Minecraft::GetInstance()->getColourTable()->getColor( spawnableMobInfo->eggColor2 ); - } - return 0xffffff; +int MonsterPlacerItem::getColor(std::shared_ptr item, + int spriteLayer) { + AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); + if (it != EntityIO::idsSpawnableInCreative.end()) { + EntityIO::SpawnableMobInfo* spawnableMobInfo = it->second; + if (spriteLayer == 0) { + return Minecraft::GetInstance()->getColourTable()->getColor( + spawnableMobInfo->eggColor1); + } + return Minecraft::GetInstance()->getColourTable()->getColor( + spawnableMobInfo->eggColor2); + } + return 0xffffff; } -bool MonsterPlacerItem::hasMultipleSpriteLayers() -{ - return true; -} +bool MonsterPlacerItem::hasMultipleSpriteLayers() { return true; } -Icon *MonsterPlacerItem::getLayerIcon(int auxValue, int spriteLayer) -{ - if (spriteLayer > 0) - { - return overlay; - } - return Item::getLayerIcon(auxValue, spriteLayer); +Icon* MonsterPlacerItem::getLayerIcon(int auxValue, int spriteLayer) { + if (spriteLayer > 0) { + return overlay; + } + return Item::getLayerIcon(auxValue, spriteLayer); } // 4J-PB - added for dispenser -std::shared_ptr MonsterPlacerItem::canSpawn(int iAuxVal, Level *level, int *piResult) -{ - std::shared_ptr newEntity = EntityIO::newById(iAuxVal, level); - if (newEntity != NULL) - { - bool canSpawn = false; +std::shared_ptr MonsterPlacerItem::canSpawn(int iAuxVal, Level* level, + int* piResult) { + std::shared_ptr newEntity = EntityIO::newById(iAuxVal, level); + if (newEntity != NULL) { + bool canSpawn = false; - switch(newEntity->GetType()) - { - case eTYPE_CHICKEN: - if(level->canCreateMore( eTYPE_CHICKEN, Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManyChickens; - } - break; - case eTYPE_WOLF: - if(level->canCreateMore( eTYPE_WOLF, Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManyWolves; - } - break; - case eTYPE_VILLAGER: - if(level->canCreateMore( eTYPE_VILLAGER, Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManyVillagers; - } - break; - case eTYPE_MUSHROOMCOW: - if(level->canCreateMore(eTYPE_MUSHROOMCOW, Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManyMooshrooms; - } - break; - case eTYPE_SQUID: - if(level->canCreateMore( eTYPE_SQUID, Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManySquid; - } - break; - default: - if( (newEntity->GetType() & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) - { - if( level->canCreateMore( newEntity->GetType(), Level::eSpawnType_Egg ) ) - { - canSpawn = true; - } - else - { - // different message for each animal + switch (newEntity->GetType()) { + case eTYPE_CHICKEN: + if (level->canCreateMore(eTYPE_CHICKEN, + Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManyChickens; + } + break; + case eTYPE_WOLF: + if (level->canCreateMore(eTYPE_WOLF, Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManyWolves; + } + break; + case eTYPE_VILLAGER: + if (level->canCreateMore(eTYPE_VILLAGER, + Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManyVillagers; + } + break; + case eTYPE_MUSHROOMCOW: + if (level->canCreateMore(eTYPE_MUSHROOMCOW, + Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManyMooshrooms; + } + break; + case eTYPE_SQUID: + if (level->canCreateMore(eTYPE_SQUID, Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManySquid; + } + break; + default: + if ((newEntity->GetType() & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) { + if (level->canCreateMore(newEntity->GetType(), + Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + // different message for each animal - *piResult=eSpawnResult_FailTooManyPigsCowsSheepCats; - } - } - else if( (newEntity->GetType() & eTYPE_MONSTER) == eTYPE_MONSTER) - { - // 4J-PB - check if the player is trying to spawn an enemy in peaceful mode - if(level->difficulty==Difficulty::PEACEFUL) - { - *piResult=eSpawnResult_FailCantSpawnInPeaceful; - } - else if(level->canCreateMore( newEntity->GetType(), Level::eSpawnType_Egg) ) - { - canSpawn = true; - } - else - { - *piResult=eSpawnResult_FailTooManyMonsters; - } - } - break; - } + *piResult = eSpawnResult_FailTooManyPigsCowsSheepCats; + } + } else if ((newEntity->GetType() & eTYPE_MONSTER) == + eTYPE_MONSTER) { + // 4J-PB - check if the player is trying to spawn an enemy + // in peaceful mode + if (level->difficulty == Difficulty::PEACEFUL) { + *piResult = eSpawnResult_FailCantSpawnInPeaceful; + } else if (level->canCreateMore(newEntity->GetType(), + Level::eSpawnType_Egg)) { + canSpawn = true; + } else { + *piResult = eSpawnResult_FailTooManyMonsters; + } + } + break; + } - if(canSpawn) - { - return newEntity; - } - } + if (canSpawn) { + return newEntity; + } + } - return nullptr; + return nullptr; } -bool MonsterPlacerItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (level->isClientSide) - { - return true; - } +bool MonsterPlacerItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, + int x, int y, int z, int face, float clickX, + float clickY, float clickZ, bool bTestUseOnOnly) { + if (level->isClientSide) { + return true; + } - int tile = level->getTile(x, y, z); + int tile = level->getTile(x, y, z); #ifndef _CONTENT_PACKAGE - if(app.DebugSettingsOn() && tile == Tile::mobSpawner_Id) - { - // 4J Stu - Force adding this as a tile update - level->setTile(x,y,z,0); - level->setTile(x,y,z,Tile::mobSpawner_Id); - std::shared_ptr mste = std::dynamic_pointer_cast( level->getTileEntity(x,y,z) ); - if(mste != NULL) - { - mste->setEntityId( EntityIO::getEncodeId(itemInstance->getAuxValue()) ); - return true; - } - } + if (app.DebugSettingsOn() && tile == Tile::mobSpawner_Id) { + // 4J Stu - Force adding this as a tile update + level->setTile(x, y, z, 0); + level->setTile(x, y, z, Tile::mobSpawner_Id); + std::shared_ptr mste = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (mste != NULL) { + mste->setEntityId( + EntityIO::getEncodeId(itemInstance->getAuxValue())); + return true; + } + } #endif - x += Facing::STEP_X[face]; - y += Facing::STEP_Y[face]; - z += Facing::STEP_Z[face]; - - double yOff = 0; - // 4J-PB - missing parentheses added - if (face == Facing::UP && (tile == Tile::fence_Id || tile == Tile::netherFence_Id)) - { - // special case - yOff = .5; - } + x += Facing::STEP_X[face]; + y += Facing::STEP_Y[face]; + z += Facing::STEP_Z[face]; - int iResult=0; - bool spawned = spawnMobAt(level, itemInstance->getAuxValue(), x + .5, y + yOff, z + .5, &iResult) != NULL; + double yOff = 0; + // 4J-PB - missing parentheses added + if (face == Facing::UP && + (tile == Tile::fence_Id || tile == Tile::netherFence_Id)) { + // special case + yOff = .5; + } - if(bTestUseOnOnly) - { - return spawned; - } + int iResult = 0; + bool spawned = spawnMobAt(level, itemInstance->getAuxValue(), x + .5, + y + yOff, z + .5, &iResult) != NULL; - if (spawned) - { - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - } - else - { - // some negative sound effect? - //level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); - switch(iResult) - { - case eSpawnResult_FailTooManyPigsCowsSheepCats: - player->displayClientMessage(IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED ); - break; - case eSpawnResult_FailTooManyChickens: - player->displayClientMessage(IDS_MAX_CHICKENS_SPAWNED ); - break; - case eSpawnResult_FailTooManySquid: - player->displayClientMessage(IDS_MAX_SQUID_SPAWNED ); - break; - case eSpawnResult_FailTooManyWolves: - player->displayClientMessage(IDS_MAX_WOLVES_SPAWNED ); - break; - case eSpawnResult_FailTooManyMooshrooms: - player->displayClientMessage(IDS_MAX_MOOSHROOMS_SPAWNED ); - break; - case eSpawnResult_FailTooManyMonsters: - player->displayClientMessage(IDS_MAX_ENEMIES_SPAWNED ); - break; - case eSpawnResult_FailTooManyVillagers: - player->displayClientMessage(IDS_MAX_VILLAGERS_SPAWNED ); - break; - case eSpawnResult_FailCantSpawnInPeaceful: - player->displayClientMessage(IDS_CANT_SPAWN_IN_PEACEFUL ); - break; + if (bTestUseOnOnly) { + return spawned; + } - } - } + if (spawned) { + if (!player->abilities.instabuild) { + itemInstance->count--; + } + } else { + // some negative sound effect? + // level->levelEvent(LevelEvent::SOUND_CLICK_FAIL, x, y, z, 0); + switch (iResult) { + case eSpawnResult_FailTooManyPigsCowsSheepCats: + player->displayClientMessage( + IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED); + break; + case eSpawnResult_FailTooManyChickens: + player->displayClientMessage(IDS_MAX_CHICKENS_SPAWNED); + break; + case eSpawnResult_FailTooManySquid: + player->displayClientMessage(IDS_MAX_SQUID_SPAWNED); + break; + case eSpawnResult_FailTooManyWolves: + player->displayClientMessage(IDS_MAX_WOLVES_SPAWNED); + break; + case eSpawnResult_FailTooManyMooshrooms: + player->displayClientMessage(IDS_MAX_MOOSHROOMS_SPAWNED); + break; + case eSpawnResult_FailTooManyMonsters: + player->displayClientMessage(IDS_MAX_ENEMIES_SPAWNED); + break; + case eSpawnResult_FailTooManyVillagers: + player->displayClientMessage(IDS_MAX_VILLAGERS_SPAWNED); + break; + case eSpawnResult_FailCantSpawnInPeaceful: + player->displayClientMessage(IDS_CANT_SPAWN_IN_PEACEFUL); + break; + } + } - return true; + return true; } -std::shared_ptr MonsterPlacerItem::spawnMobAt(Level *level, int mobId, double x, double y, double z, int *piResult) -{ - if (EntityIO::idsSpawnableInCreative.find(mobId) == EntityIO::idsSpawnableInCreative.end()) - { - return nullptr; - } +std::shared_ptr MonsterPlacerItem::spawnMobAt(Level* level, int mobId, + double x, double y, + double z, int* piResult) { + if (EntityIO::idsSpawnableInCreative.find(mobId) == + EntityIO::idsSpawnableInCreative.end()) { + return nullptr; + } - std::shared_ptr newEntity = nullptr; + std::shared_ptr newEntity = nullptr; - for (int i = 0; i < SPAWN_COUNT; i++) - { - newEntity = canSpawn(mobId, level, piResult); + for (int i = 0; i < SPAWN_COUNT; i++) { + newEntity = canSpawn(mobId, level, piResult); - std::shared_ptr mob = std::dynamic_pointer_cast(newEntity); - if (mob) - { - newEntity->moveTo(x, y, z, Mth::wrapDegrees(level->random->nextFloat() * 360), 0); - newEntity->setDespawnProtected(); // 4J added, default to being protected against despawning (has to be done after initial position is set) - mob->yHeadRot = mob->yRot; - mob->yBodyRot = mob->yRot; + std::shared_ptr mob = std::dynamic_pointer_cast(newEntity); + if (mob) { + newEntity->moveTo( + x, y, z, Mth::wrapDegrees(level->random->nextFloat() * 360), 0); + newEntity->setDespawnProtected(); // 4J added, default to being + // protected against despawning + // (has to be done after initial + // position is set) + mob->yHeadRot = mob->yRot; + mob->yBodyRot = mob->yRot; - mob->finalizeMobSpawn(); - level->addEntity(newEntity); - mob->playAmbientSound(); - } - } + mob->finalizeMobSpawn(); + level->addEntity(newEntity); + mob->playAmbientSound(); + } + } - return newEntity; + return newEntity; } -void MonsterPlacerItem::registerIcons(IconRegister *iconRegister) -{ - Item::registerIcons(iconRegister); - overlay = iconRegister->registerIcon(L"monsterPlacer_overlay"); +void MonsterPlacerItem::registerIcons(IconRegister* iconRegister) { + Item::registerIcons(iconRegister); + overlay = iconRegister->registerIcon(L"monsterPlacer_overlay"); } diff --git a/Minecraft.World/Items/MonsterPlacerItem.h b/Minecraft.World/Items/MonsterPlacerItem.h index 9f4c5a7e4..bc1c47359 100644 --- a/Minecraft.World/Items/MonsterPlacerItem.h +++ b/Minecraft.World/Items/MonsterPlacerItem.h @@ -2,41 +2,45 @@ #include "Item.h" -class MonsterPlacerItem : public Item -{ +class MonsterPlacerItem : public Item { private: - static const int SPAWN_COUNT = 1; + static const int SPAWN_COUNT = 1; - Icon *overlay; + Icon* overlay; public: + enum _eSpawnResult { + eSpawnResult_OK = 0, + eSpawnResult_FailTooManyPigsCowsSheepCats, + eSpawnResult_FailTooManyChickens, + eSpawnResult_FailTooManySquid, + eSpawnResult_FailTooManyWolves, + eSpawnResult_FailTooManyMooshrooms, + eSpawnResult_FailTooManyAnimals, + eSpawnResult_FailTooManyMonsters, + eSpawnResult_FailTooManyVillagers, + eSpawnResult_FailCantSpawnInPeaceful, + }; - enum _eSpawnResult - { - eSpawnResult_OK=0, - eSpawnResult_FailTooManyPigsCowsSheepCats, - eSpawnResult_FailTooManyChickens, - eSpawnResult_FailTooManySquid, - eSpawnResult_FailTooManyWolves, - eSpawnResult_FailTooManyMooshrooms, - eSpawnResult_FailTooManyAnimals, - eSpawnResult_FailTooManyMonsters, - eSpawnResult_FailTooManyVillagers, - eSpawnResult_FailCantSpawnInPeaceful, - }; + MonsterPlacerItem(int id); - MonsterPlacerItem(int id); + virtual std::wstring getHoverName( + std::shared_ptr itemInstance); + virtual int getColor(std::shared_ptr item, int spriteLayer); + virtual bool hasMultipleSpriteLayers(); + virtual Icon* getLayerIcon(int auxValue, int spriteLayer); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + static std::shared_ptr spawnMobAt( + Level* level, int mobId, double x, double y, double z, + int* piResult); // 4J Added piResult param - virtual std::wstring getHoverName(std::shared_ptr itemInstance); - virtual int getColor(std::shared_ptr item, int spriteLayer); - virtual bool hasMultipleSpriteLayers(); - virtual Icon *getLayerIcon(int auxValue, int spriteLayer); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - static std::shared_ptr spawnMobAt(Level *level, int mobId, double x, double y, double z, int *piResult); // 4J Added piResult param + // 4J-PB added for dispenser + static std::shared_ptr canSpawn(int iAuxVal, Level* level, + int* piResult); - // 4J-PB added for dispenser - static std::shared_ptr canSpawn(int iAuxVal, Level *level, int *piResult); - - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/PickaxeItem.cpp b/Minecraft.World/Items/PickaxeItem.cpp index dd72b05b9..b591c0de3 100644 --- a/Minecraft.World/Items/PickaxeItem.cpp +++ b/Minecraft.World/Items/PickaxeItem.cpp @@ -2,60 +2,64 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "PickaxeItem.h" -TileArray *PickaxeItem::diggables = NULL; +TileArray* PickaxeItem::diggables = NULL; -void PickaxeItem::staticCtor() -{ - PickaxeItem::diggables = new TileArray( PICKAXE_DIGGABLES); - diggables->data[0] = Tile::stoneBrick; - diggables->data[1] = Tile::stoneSlab; - diggables->data[2] = Tile::stoneSlabHalf; - diggables->data[3] = Tile::rock; - diggables->data[4] = Tile::sandStone; - diggables->data[5] = Tile::mossStone; - diggables->data[6] = Tile::ironOre; - diggables->data[7] = Tile::ironBlock; - diggables->data[8] = Tile::coalOre; - diggables->data[9] = Tile::goldBlock; - diggables->data[10] = Tile::goldOre; - diggables->data[11] = Tile::diamondOre; - diggables->data[12] = Tile::diamondBlock; - diggables->data[13] = Tile::ice; - diggables->data[14] = Tile::hellRock; - diggables->data[15] = Tile::lapisOre; - diggables->data[16] = Tile::lapisBlock; - // 4J - brought forward from 1.2.3 - diggables->data[17] = Tile::redStoneOre; - diggables->data[18] = Tile::redStoneOre_lit; - diggables->data[19] = Tile::rail; - diggables->data[20] = Tile::detectorRail; - diggables->data[21] = Tile::goldenRail; +void PickaxeItem::staticCtor() { + PickaxeItem::diggables = new TileArray(PICKAXE_DIGGABLES); + diggables->data[0] = Tile::stoneBrick; + diggables->data[1] = Tile::stoneSlab; + diggables->data[2] = Tile::stoneSlabHalf; + diggables->data[3] = Tile::rock; + diggables->data[4] = Tile::sandStone; + diggables->data[5] = Tile::mossStone; + diggables->data[6] = Tile::ironOre; + diggables->data[7] = Tile::ironBlock; + diggables->data[8] = Tile::coalOre; + diggables->data[9] = Tile::goldBlock; + diggables->data[10] = Tile::goldOre; + diggables->data[11] = Tile::diamondOre; + diggables->data[12] = Tile::diamondBlock; + diggables->data[13] = Tile::ice; + diggables->data[14] = Tile::hellRock; + diggables->data[15] = Tile::lapisOre; + diggables->data[16] = Tile::lapisBlock; + // 4J - brought forward from 1.2.3 + diggables->data[17] = Tile::redStoneOre; + diggables->data[18] = Tile::redStoneOre_lit; + diggables->data[19] = Tile::rail; + diggables->data[20] = Tile::detectorRail; + diggables->data[21] = Tile::goldenRail; } -PickaxeItem::PickaxeItem(int id, const Tier *tier) : DiggerItem(id, 2, tier, diggables) -{ -} +PickaxeItem::PickaxeItem(int id, const Tier* tier) + : DiggerItem(id, 2, tier, diggables) {} -bool PickaxeItem::canDestroySpecial(Tile *tile) -{ - if (tile == Tile::obsidian) return tier->getLevel() == 3; - if (tile == Tile::diamondBlock || tile == Tile::diamondOre) return tier->getLevel() >= 2; - if (tile == Tile::emeraldBlock || tile == Tile::emeraldOre) return tier->getLevel() >= 2; - if (tile == Tile::goldBlock || tile == Tile::goldOre) return tier->getLevel() >= 2; - if (tile == Tile::ironBlock || tile == Tile::ironOre) return tier->getLevel() >= 1; - if (tile == Tile::lapisBlock || tile == Tile::lapisOre) return tier->getLevel() >= 1; - if (tile == Tile::redStoneOre || tile == Tile::redStoneOre_lit) return tier->getLevel() >= 2; - if (tile->material == Material::stone) return true; - if (tile->material == Material::metal) return true; - if (tile->material == Material::heavyMetal) return true; - return false; +bool PickaxeItem::canDestroySpecial(Tile* tile) { + if (tile == Tile::obsidian) return tier->getLevel() == 3; + if (tile == Tile::diamondBlock || tile == Tile::diamondOre) + return tier->getLevel() >= 2; + if (tile == Tile::emeraldBlock || tile == Tile::emeraldOre) + return tier->getLevel() >= 2; + if (tile == Tile::goldBlock || tile == Tile::goldOre) + return tier->getLevel() >= 2; + if (tile == Tile::ironBlock || tile == Tile::ironOre) + return tier->getLevel() >= 1; + if (tile == Tile::lapisBlock || tile == Tile::lapisOre) + return tier->getLevel() >= 1; + if (tile == Tile::redStoneOre || tile == Tile::redStoneOre_lit) + return tier->getLevel() >= 2; + if (tile->material == Material::stone) return true; + if (tile->material == Material::metal) return true; + if (tile->material == Material::heavyMetal) return true; + return false; } // 4J - brought forward from 1.2.3 -float PickaxeItem::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - if (tile != NULL && (tile->material == Material::metal || tile->material == Material::heavyMetal || tile->material == Material::stone)) - { +float PickaxeItem::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + if (tile != NULL && (tile->material == Material::metal || + tile->material == Material::heavyMetal || + tile->material == Material::stone)) { return speed; } return DiggerItem::getDestroySpeed(itemInstance, tile); diff --git a/Minecraft.World/Items/PickaxeItem.h b/Minecraft.World/Items/PickaxeItem.h index f13c8d341..4e9dc2d4a 100644 --- a/Minecraft.World/Items/PickaxeItem.h +++ b/Minecraft.World/Items/PickaxeItem.h @@ -4,17 +4,18 @@ #define PICKAXE_DIGGABLES 22 -class PickaxeItem : public DiggerItem -{ +class PickaxeItem : public DiggerItem { private: - static TileArray *diggables; + static TileArray* diggables; -public: // - static void staticCtor(); +public: // + static void staticCtor(); - PickaxeItem(int id, const Tier *tier); + PickaxeItem(int id, const Tier* tier); public: - virtual bool canDestroySpecial(Tile *tile); - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); // 4J - brought forward from 1.2.3 + virtual bool canDestroySpecial(Tile* tile); + virtual float getDestroySpeed( + std::shared_ptr itemInstance, + Tile* tile); // 4J - brought forward from 1.2.3 }; diff --git a/Minecraft.World/Items/PotionItem.cpp b/Minecraft.World/Items/PotionItem.cpp index 4626c4af0..898aa7e77 100644 --- a/Minecraft.World/Items/PotionItem.cpp +++ b/Minecraft.World/Items/PotionItem.cpp @@ -17,356 +17,350 @@ const std::wstring PotionItem::THROWABLE_ICON = L"potion_splash"; const std::wstring PotionItem::CONTENTS_ICON = L"potion_contents"; // 4J Added -std::vector > PotionItem::s_uniquePotionValues; +std::vector > PotionItem::s_uniquePotionValues; -PotionItem::PotionItem(int id) : Item(id) -{ - setMaxStackSize(1); - setStackedByData(true); - setMaxDamage(0); +PotionItem::PotionItem(int id) : Item(id) { + setMaxStackSize(1); + setStackedByData(true); + setMaxDamage(0); - iconThrowable = NULL; - iconDrinkable = NULL; - iconOverlay = NULL; + iconThrowable = NULL; + iconDrinkable = NULL; + iconOverlay = NULL; } -std::vector *PotionItem::getMobEffects(std::shared_ptr potion) -{ - return getMobEffects(potion->getAuxValue()); +std::vector* PotionItem::getMobEffects( + std::shared_ptr potion) { + return getMobEffects(potion->getAuxValue()); } -std::vector *PotionItem::getMobEffects(int auxValue) -{ - std::vector *effects = NULL; - AUTO_VAR(it, cachedMobEffects.find(auxValue)); - if(it != cachedMobEffects.end()) effects = it->second; - if (effects == NULL) - { - effects = PotionBrewing::getEffects(auxValue, false); - if(effects != NULL) cachedMobEffects.insert( std::pair *>(auxValue, effects) ); - } - return effects; +std::vector* PotionItem::getMobEffects(int auxValue) { + std::vector* effects = NULL; + AUTO_VAR(it, cachedMobEffects.find(auxValue)); + if (it != cachedMobEffects.end()) effects = it->second; + if (effects == NULL) { + effects = PotionBrewing::getEffects(auxValue, false); + if (effects != NULL) + cachedMobEffects.insert( + std::pair*>(auxValue, + effects)); + } + return effects; } -std::shared_ptr PotionItem::useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (!player->abilities.instabuild) instance->count--; +std::shared_ptr PotionItem::useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (!player->abilities.instabuild) instance->count--; - if (!level->isClientSide) - { - std::vector *effects = getMobEffects(instance); - if (effects != NULL) - { - //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) - { - player->addEffect(new MobEffectInstance(*it)); - } - } - } - if (!player->abilities.instabuild) - { - if (instance->count <= 0) - { - return std::shared_ptr( new ItemInstance(Item::glassBottle) ); - } - else - { - player->inventory->add( std::shared_ptr( new ItemInstance(Item::glassBottle) ) ); - } - } + if (!level->isClientSide) { + std::vector* effects = getMobEffects(instance); + if (effects != NULL) { + // for (MobEffectInstance effect : effects) + for (AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) { + player->addEffect(new MobEffectInstance(*it)); + } + } + } + if (!player->abilities.instabuild) { + if (instance->count <= 0) { + return std::shared_ptr( + new ItemInstance(Item::glassBottle)); + } else { + player->inventory->add(std::shared_ptr( + new ItemInstance(Item::glassBottle))); + } + } - return instance; + return instance; } -int PotionItem::getUseDuration(std::shared_ptr itemInstance) -{ - return DRINK_DURATION; +int PotionItem::getUseDuration(std::shared_ptr itemInstance) { + return DRINK_DURATION; } -UseAnim PotionItem::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_drink; +UseAnim PotionItem::getUseAnimation( + std::shared_ptr itemInstance) { + return UseAnim_drink; } -bool PotionItem::TestUse(Level *level, std::shared_ptr player) -{ - return true; +bool PotionItem::TestUse(Level* level, std::shared_ptr player) { + return true; } -std::shared_ptr PotionItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (isThrowable(instance->getAuxValue())) - { - if (!player->abilities.instabuild) instance->count--; - level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) level->addEntity(std::shared_ptr( new ThrownPotion(level, player, instance->getAuxValue()) )); - return instance; - } - player->startUsingItem(instance, getUseDuration(instance)); - return instance; +std::shared_ptr PotionItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (isThrowable(instance->getAuxValue())) { + if (!player->abilities.instabuild) instance->count--; + level->playSound(player, eSoundType_RANDOM_BOW, 0.5f, + 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) + level->addEntity(std::shared_ptr( + new ThrownPotion(level, player, instance->getAuxValue()))); + return instance; + } + player->startUsingItem(instance, getUseDuration(instance)); + return instance; } -bool PotionItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - return false; +bool PotionItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + return false; } -Icon *PotionItem::getIcon(int auxValue) -{ - if (isThrowable(auxValue)) - { - return iconThrowable; - } - return iconDrinkable; +Icon* PotionItem::getIcon(int auxValue) { + if (isThrowable(auxValue)) { + return iconThrowable; + } + return iconDrinkable; } -Icon *PotionItem::getLayerIcon(int auxValue, int spriteLayer) -{ - if (spriteLayer == 0) - { - return iconOverlay; - } - return Item::getLayerIcon(auxValue, spriteLayer); +Icon* PotionItem::getLayerIcon(int auxValue, int spriteLayer) { + if (spriteLayer == 0) { + return iconOverlay; + } + return Item::getLayerIcon(auxValue, spriteLayer); } -bool PotionItem::isThrowable(int auxValue) -{ - return ((auxValue & PotionBrewing::THROWABLE_MASK) != 0); +bool PotionItem::isThrowable(int auxValue) { + return ((auxValue & PotionBrewing::THROWABLE_MASK) != 0); } -int PotionItem::getColor(int data) -{ - return PotionBrewing::getColorValue(data, false); +int PotionItem::getColor(int data) { + return PotionBrewing::getColorValue(data, false); } -int PotionItem::getColor(std::shared_ptr item, int spriteLayer) -{ - if (spriteLayer > 0) - { - return 0xffffff; - } - return PotionBrewing::getColorValue(item->getAuxValue(), false); +int PotionItem::getColor(std::shared_ptr item, int spriteLayer) { + if (spriteLayer > 0) { + return 0xffffff; + } + return PotionBrewing::getColorValue(item->getAuxValue(), false); } -bool PotionItem::hasMultipleSpriteLayers() -{ - return true; +bool PotionItem::hasMultipleSpriteLayers() { return true; } + +bool PotionItem::hasInstantenousEffects(int itemAuxValue) { + std::vector* mobEffects = getMobEffects(itemAuxValue); + if (mobEffects == NULL || mobEffects->empty()) { + return false; + } + // for (MobEffectInstance effect : mobEffects) { + for (AUTO_VAR(it, mobEffects->begin()); it != mobEffects->end(); ++it) { + MobEffectInstance* effect = *it; + if (MobEffect::effects[effect->getId()]->isInstantenous()) { + return true; + } + } + return false; } -bool PotionItem::hasInstantenousEffects(int itemAuxValue) -{ - std::vector *mobEffects = getMobEffects(itemAuxValue); - if (mobEffects == NULL || mobEffects->empty()) - { - return false; - } - //for (MobEffectInstance effect : mobEffects) { - for(AUTO_VAR(it, mobEffects->begin()); it != mobEffects->end(); ++it) - { - MobEffectInstance *effect = *it; - if (MobEffect::effects[effect->getId()]->isInstantenous()) - { - return true; - } - } - return false; +std::wstring PotionItem::getHoverName( + std::shared_ptr itemInstance) { + if (itemInstance->getAuxValue() == 0) { + return app.GetString( + IDS_ITEM_WATER_BOTTLE); // I18n.get("item.emptyPotion.name").trim(); + } + + std::wstring elementName = Item::getHoverName(itemInstance); + if (isThrowable(itemInstance->getAuxValue())) { + // elementName = I18n.get("potion.prefix.grenade").trim() + " " + + // elementName; + elementName = replaceAll(elementName, L"{*splash*}", + app.GetString(IDS_POTION_PREFIX_GRENADE)); + } else { + elementName = replaceAll(elementName, L"{*splash*}", L""); + } + + std::vector* effects = + ((PotionItem*)Item::potion)->getMobEffects(itemInstance); + if (effects != NULL && !effects->empty()) { + // String postfixString = effects.get(0).getDescriptionId(); + // postfixString += ".postfix"; + // return elementName + " " + I18n.get(postfixString).trim(); + + elementName = replaceAll(elementName, L"{*prefix*}", L""); + elementName = replaceAll( + elementName, L"{*postfix*}", + app.GetString(effects->at(0)->getPostfixDescriptionId())); + } else { + // String appearanceName = + // PotionBrewing.getAppearanceName(itemInstance.getAuxValue()); return + // I18n.get(appearanceName).trim() + " " + elementName; + + elementName = replaceAll(elementName, L"{*prefix*}", + app.GetString(PotionBrewing::getAppearanceName( + itemInstance->getAuxValue()))); + elementName = replaceAll(elementName, L"{*postfix*}", L""); + } + return elementName; } -std::wstring PotionItem::getHoverName(std::shared_ptr itemInstance) -{ - if (itemInstance->getAuxValue() == 0) - { - return app.GetString(IDS_ITEM_WATER_BOTTLE); // I18n.get("item.emptyPotion.name").trim(); - } - - std::wstring elementName = Item::getHoverName(itemInstance); - if (isThrowable(itemInstance->getAuxValue())) - { - //elementName = I18n.get("potion.prefix.grenade").trim() + " " + elementName; - elementName = replaceAll(elementName,L"{*splash*}",app.GetString(IDS_POTION_PREFIX_GRENADE)); - } - else - { - elementName = replaceAll(elementName,L"{*splash*}",L""); - } - - std::vector *effects = ((PotionItem *) Item::potion)->getMobEffects(itemInstance); - if (effects != NULL && !effects->empty()) - { - //String postfixString = effects.get(0).getDescriptionId(); - //postfixString += ".postfix"; - //return elementName + " " + I18n.get(postfixString).trim(); - - elementName = replaceAll(elementName,L"{*prefix*}",L""); - elementName = replaceAll(elementName,L"{*postfix*}",app.GetString(effects->at(0)->getPostfixDescriptionId())); - } - else - { - //String appearanceName = PotionBrewing.getAppearanceName(itemInstance.getAuxValue()); - //return I18n.get(appearanceName).trim() + " " + elementName; - - elementName = replaceAll(elementName,L"{*prefix*}",app.GetString( PotionBrewing::getAppearanceName(itemInstance->getAuxValue()))); - elementName = replaceAll(elementName,L"{*postfix*}",L""); - } - return elementName; +void PotionItem::appendHoverText( + std::shared_ptr itemInstance, std::shared_ptr player, + std::vector* lines, bool advanced, + std::vector& unformattedStrings) { + if (itemInstance->getAuxValue() == 0) { + return; + } + std::vector* effects = + ((PotionItem*)Item::potion)->getMobEffects(itemInstance); + if (effects != NULL && !effects->empty()) { + // for (MobEffectInstance effect : effects) + for (AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) { + MobEffectInstance* effect = *it; + std::wstring effectString = app.GetString( + effect + ->getDescriptionId()); // I18n.get(effect.getDescriptionId()).trim(); + if (effect->getAmplifier() > 0) { + std::wstring potencyString = L""; + switch (effect->getAmplifier()) { + case 1: + potencyString = L" "; + potencyString += app.GetString(IDS_POTION_POTENCY_1); + break; + case 2: + potencyString = L" "; + potencyString += app.GetString(IDS_POTION_POTENCY_2); + break; + case 3: + potencyString = L" "; + potencyString += app.GetString(IDS_POTION_POTENCY_3); + break; + default: + potencyString = app.GetString(IDS_POTION_POTENCY_0); + break; + } + effectString += + potencyString; // + I18n.get("potion.potency." + + // effect.getAmplifier()).trim(); + } + if (effect->getDuration() > SharedConstants::TICKS_PER_SECOND) { + effectString += + L" (" + MobEffect::formatDuration(effect) + L")"; + } + unformattedStrings.push_back(effectString); + wchar_t formatted[256]; + ZeroMemory(formatted, 256 * sizeof(wchar_t)); + eMinecraftColour colour = eMinecraftColour_NOT_SET; + if (MobEffect::effects[effect->getId()]->isHarmful()) { + colour = eHTMLColor_c; + // lines->push_back(L"�c + effectString); //"�c" + } else { + colour = eHTMLColor_7; + // lines->push_back(L"�7" + effectString); //"�7" + } + swprintf(formatted, 256, L"%ls", + app.GetHTMLColour(colour), effectString.c_str()); + lines->push_back(formatted); + } + } else { + std::wstring effectString = app.GetString( + IDS_POTION_EMPTY); // I18n.get("potion.empty").trim(); + // eHTMLColor_7 + wchar_t formatted[256]; + swprintf(formatted, 256, L"%ls", + app.GetHTMLColour(eHTMLColor_7), effectString.c_str()); + lines->push_back(formatted); //"�7" + } } -void PotionItem::appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings) -{ - if (itemInstance->getAuxValue() == 0) - { - return; - } - std::vector *effects = ((PotionItem *) Item::potion)->getMobEffects(itemInstance); - if (effects != NULL && !effects->empty()) - { - //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) - { - MobEffectInstance *effect = *it; - std::wstring effectString = app.GetString( effect->getDescriptionId() );//I18n.get(effect.getDescriptionId()).trim(); - if (effect->getAmplifier() > 0) - { - std::wstring potencyString = L""; - switch(effect->getAmplifier()) - { - case 1: - potencyString = L" "; - potencyString += app.GetString( IDS_POTION_POTENCY_1 ); - break; - case 2: - potencyString = L" "; - potencyString += app.GetString( IDS_POTION_POTENCY_2 ); - break; - case 3: - potencyString = L" "; - potencyString += app.GetString( IDS_POTION_POTENCY_3 ); - break; - default: - potencyString = app.GetString( IDS_POTION_POTENCY_0 ); - break; - } - effectString += potencyString;// + I18n.get("potion.potency." + effect.getAmplifier()).trim(); - } - if (effect->getDuration() > SharedConstants::TICKS_PER_SECOND) - { - effectString += L" (" + MobEffect::formatDuration(effect) + L")"; - } - unformattedStrings.push_back(effectString); - wchar_t formatted[256]; - ZeroMemory(formatted, 256 * sizeof(wchar_t)); - eMinecraftColour colour = eMinecraftColour_NOT_SET; - if (MobEffect::effects[effect->getId()]->isHarmful()) - { - colour = eHTMLColor_c; - //lines->push_back(L"�c + effectString); //"�c" - } - else - { - colour = eHTMLColor_7; - //lines->push_back(L"�7" + effectString); //"�7" - } - swprintf(formatted, 256, L"%ls",app.GetHTMLColour(colour),effectString.c_str()); - lines->push_back(formatted); - } - } - else - { - std::wstring effectString = app.GetString(IDS_POTION_EMPTY); //I18n.get("potion.empty").trim(); - //eHTMLColor_7 - wchar_t formatted[256]; - swprintf(formatted,256,L"%ls",app.GetHTMLColour(eHTMLColor_7),effectString.c_str()); - lines->push_back(formatted); //"�7" - } +bool PotionItem::isFoil(std::shared_ptr itemInstance) { + std::vector* mobEffects = getMobEffects(itemInstance); + return mobEffects != NULL && !mobEffects->empty(); } -bool PotionItem::isFoil(std::shared_ptr itemInstance) -{ - std::vector *mobEffects = getMobEffects(itemInstance); - return mobEffects != NULL && !mobEffects->empty(); +unsigned int PotionItem::getUseDescriptionId( + std::shared_ptr instance) { + int brew = instance->getAuxValue(); + +#define MACRO_POTION_IS_NIGHTVISION(aux) ((aux & 0x200F) == MASK_NIGHTVISION) +#define MACRO_POTION_IS_INVISIBILITY(aux) ((aux & 0x200F) == MASK_INVISIBILITY) + + if (brew == 0) + return IDS_POTION_DESC_WATER_BOTTLE; + else if (MACRO_POTION_IS_REGENERATION(brew)) + return IDS_POTION_DESC_REGENERATION; + else if (MACRO_POTION_IS_SPEED(brew)) + return IDS_POTION_DESC_MOVESPEED; + else if (MACRO_POTION_IS_FIRE_RESISTANCE(brew)) + return IDS_POTION_DESC_FIRERESISTANCE; + else if (MACRO_POTION_IS_INSTANTHEALTH(brew)) + return IDS_POTION_DESC_HEAL; + else if (MACRO_POTION_IS_NIGHTVISION(brew)) + return IDS_POTION_DESC_NIGHTVISION; + else if (MACRO_POTION_IS_INVISIBILITY(brew)) + return IDS_POTION_DESC_INVISIBILITY; + else if (MACRO_POTION_IS_WEAKNESS(brew)) + return IDS_POTION_DESC_WEAKNESS; + else if (MACRO_POTION_IS_STRENGTH(brew)) + return IDS_POTION_DESC_DAMAGEBOOST; + else if (MACRO_POTION_IS_SLOWNESS(brew)) + return IDS_POTION_DESC_MOVESLOWDOWN; + else if (MACRO_POTION_IS_POISON(brew)) + return IDS_POTION_DESC_POISON; + else if (MACRO_POTION_IS_INSTANTDAMAGE(brew)) + return IDS_POTION_DESC_HARM; + return IDS_POTION_DESC_EMPTY; } -unsigned int PotionItem::getUseDescriptionId(std::shared_ptr instance) -{ - int brew = instance->getAuxValue(); - - -#define MACRO_POTION_IS_NIGHTVISION(aux) ((aux & 0x200F) == MASK_NIGHTVISION) -#define MACRO_POTION_IS_INVISIBILITY(aux) ((aux & 0x200F) == MASK_INVISIBILITY) - - if(brew == 0) return IDS_POTION_DESC_WATER_BOTTLE; - else if( MACRO_POTION_IS_REGENERATION(brew)) return IDS_POTION_DESC_REGENERATION; - else if( MACRO_POTION_IS_SPEED(brew) ) return IDS_POTION_DESC_MOVESPEED; - else if( MACRO_POTION_IS_FIRE_RESISTANCE(brew)) return IDS_POTION_DESC_FIRERESISTANCE; - else if( MACRO_POTION_IS_INSTANTHEALTH(brew)) return IDS_POTION_DESC_HEAL; - else if( MACRO_POTION_IS_NIGHTVISION(brew)) return IDS_POTION_DESC_NIGHTVISION; - else if( MACRO_POTION_IS_INVISIBILITY(brew)) return IDS_POTION_DESC_INVISIBILITY; - else if( MACRO_POTION_IS_WEAKNESS(brew)) return IDS_POTION_DESC_WEAKNESS; - else if( MACRO_POTION_IS_STRENGTH(brew)) return IDS_POTION_DESC_DAMAGEBOOST; - else if( MACRO_POTION_IS_SLOWNESS(brew)) return IDS_POTION_DESC_MOVESLOWDOWN; - else if( MACRO_POTION_IS_POISON(brew)) return IDS_POTION_DESC_POISON; - else if( MACRO_POTION_IS_INSTANTDAMAGE(brew)) return IDS_POTION_DESC_HARM; - return IDS_POTION_DESC_EMPTY; +void PotionItem::registerIcons(IconRegister* iconRegister) { + iconDrinkable = iconRegister->registerIcon(DEFAULT_ICON); + iconThrowable = iconRegister->registerIcon(THROWABLE_ICON); + iconOverlay = iconRegister->registerIcon(CONTENTS_ICON); } -void PotionItem::registerIcons(IconRegister *iconRegister) -{ - iconDrinkable = iconRegister->registerIcon(DEFAULT_ICON); - iconThrowable = iconRegister->registerIcon(THROWABLE_ICON); - iconOverlay = iconRegister->registerIcon(CONTENTS_ICON); +Icon* PotionItem::getTexture(const std::wstring& name) { + if (name.compare(DEFAULT_ICON) == 0) return Item::potion->iconDrinkable; + if (name.compare(THROWABLE_ICON) == 0) return Item::potion->iconThrowable; + if (name.compare(CONTENTS_ICON) == 0) return Item::potion->iconOverlay; + return NULL; } -Icon *PotionItem::getTexture(const std::wstring &name) -{ - if (name.compare(DEFAULT_ICON) == 0) return Item::potion->iconDrinkable; - if (name.compare(THROWABLE_ICON) == 0) return Item::potion->iconThrowable; - if (name.compare(CONTENTS_ICON) == 0) return Item::potion->iconOverlay; - return NULL; -} +// 4J Stu - Based loosely on a function that gets added in java much later on +// (1.3) +std::vector >* PotionItem::getUniquePotionValues() { + if (s_uniquePotionValues.empty()) { + for (int brew = 0; brew <= PotionBrewing::BREW_MASK; ++brew) { + std::vector* effects = + PotionBrewing::getEffects(brew, false); + if (effects != NULL) { + if (!effects->empty()) { + // 4J Stu - Based on implementation of Java List.hashCode() + // at + // http://docs.oracle.com/javase/6/docs/api/java/util/List.html#hashCode() + // and adding deleting to clear up as we go + int effectsHashCode = 1; + for (AUTO_VAR(it, effects->begin()); it != effects->end(); + ++it) { + MobEffectInstance* mei = *it; + effectsHashCode = 31 * effectsHashCode + + (mei == NULL ? 0 : mei->hashCode()); + delete (*it); + } -// 4J Stu - Based loosely on a function that gets added in java much later on (1.3) -std::vector > *PotionItem::getUniquePotionValues() -{ - if (s_uniquePotionValues.empty()) - { - for (int brew = 0; brew <= PotionBrewing::BREW_MASK; ++brew) - { - std::vector *effects = PotionBrewing::getEffects(brew, false); - - if (effects != NULL) - { - if(!effects->empty()) - { - // 4J Stu - Based on implementation of Java List.hashCode() at http://docs.oracle.com/javase/6/docs/api/java/util/List.html#hashCode() - // and adding deleting to clear up as we go - int effectsHashCode = 1; - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) - { - MobEffectInstance *mei = *it; - effectsHashCode = 31*effectsHashCode + (mei==NULL ? 0 : mei->hashCode()); - delete (*it); - } - - bool toAdd = true; - for(AUTO_VAR(it, s_uniquePotionValues.begin()); it != s_uniquePotionValues.end(); ++it) - { - // Some potions hash the same (identical effects) but are throwable so account for that - if(it->first == effectsHashCode && !(!isThrowable(it->second) && isThrowable(brew)) ) - { - toAdd = false; - break; - } - } - if( toAdd ) - { - s_uniquePotionValues.push_back(std::pair(effectsHashCode, brew) ); - } - } - delete effects; - } - } - } - return &s_uniquePotionValues; + bool toAdd = true; + for (AUTO_VAR(it, s_uniquePotionValues.begin()); + it != s_uniquePotionValues.end(); ++it) { + // Some potions hash the same (identical effects) but + // are throwable so account for that + if (it->first == effectsHashCode && + !(!isThrowable(it->second) && isThrowable(brew))) { + toAdd = false; + break; + } + } + if (toAdd) { + s_uniquePotionValues.push_back( + std::pair(effectsHashCode, brew)); + } + } + delete effects; + } + } + } + return &s_uniquePotionValues; } \ No newline at end of file diff --git a/Minecraft.World/Items/PotionItem.h b/Minecraft.World/Items/PotionItem.h index c620a812a..60d34f247 100644 --- a/Minecraft.World/Items/PotionItem.h +++ b/Minecraft.World/Items/PotionItem.h @@ -4,54 +4,70 @@ class MobEffectInstance; -class PotionItem : public Item -{ +class PotionItem : public Item { private: - static const int DRINK_DURATION = (int) (20 * 1.6); + static const int DRINK_DURATION = (int)(20 * 1.6); public: - static const std::wstring DEFAULT_ICON; - static const std::wstring THROWABLE_ICON; - static const std::wstring CONTENTS_ICON; + static const std::wstring DEFAULT_ICON; + static const std::wstring THROWABLE_ICON; + static const std::wstring CONTENTS_ICON; private: - std::unordered_map *> cachedMobEffects; + std::unordered_map*> cachedMobEffects; - Icon *iconThrowable; - Icon *iconDrinkable; - Icon *iconOverlay; + Icon* iconThrowable; + Icon* iconDrinkable; + Icon* iconOverlay; public: - PotionItem(int id); + PotionItem(int id); - virtual std::vector *getMobEffects(std::shared_ptr potion); - virtual std::vector *getMobEffects(int auxValue); - virtual std::shared_ptr useTimeDepleted(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual Icon *getIcon(int auxValue); - virtual Icon *getLayerIcon(int auxValue, int spriteLayer); - static bool isThrowable(int auxValue); - int getColor(int data); - virtual int getColor(std::shared_ptr item, int spriteLayer); - virtual bool hasMultipleSpriteLayers(); - virtual bool hasInstantenousEffects(int itemAuxValue); - virtual std::wstring getHoverName(std::shared_ptr itemInstance); - virtual void appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings); - virtual bool isFoil(std::shared_ptr itemInstance); + virtual std::vector* getMobEffects( + std::shared_ptr potion); + virtual std::vector* getMobEffects(int auxValue); + virtual std::shared_ptr useTimeDepleted( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual Icon* getIcon(int auxValue); + virtual Icon* getLayerIcon(int auxValue, int spriteLayer); + static bool isThrowable(int auxValue); + int getColor(int data); + virtual int getColor(std::shared_ptr item, int spriteLayer); + virtual bool hasMultipleSpriteLayers(); + virtual bool hasInstantenousEffects(int itemAuxValue); + virtual std::wstring getHoverName( + std::shared_ptr itemInstance); + virtual void appendHoverText(std::shared_ptr itemInstance, + std::shared_ptr player, + std::vector* lines, + bool advanced, + std::vector& unformattedStrings); + virtual bool isFoil(std::shared_ptr itemInstance); - virtual unsigned int getUseDescriptionId(std::shared_ptr instance); + virtual unsigned int getUseDescriptionId( + std::shared_ptr instance); - //@Override - void registerIcons(IconRegister *iconRegister); - static Icon *getTexture(const std::wstring &name); + //@Override + void registerIcons(IconRegister* iconRegister); + static Icon* getTexture(const std::wstring& name); + + // 4J Stu - Based loosely on a function that gets added in java much later + // on (1.3) + static std::vector >* getUniquePotionValues(); - // 4J Stu - Based loosely on a function that gets added in java much later on (1.3) - static std::vector > *getUniquePotionValues(); private: - // 4J Stu - Added to support function above, different from Java implementation - static std::vector > s_uniquePotionValues; + // 4J Stu - Added to support function above, different from Java + // implementation + static std::vector > s_uniquePotionValues; }; \ No newline at end of file diff --git a/Minecraft.World/Items/RecordingItem.cpp b/Minecraft.World/Items/RecordingItem.cpp index f672e4383..741b3b702 100644 --- a/Minecraft.World/Items/RecordingItem.cpp +++ b/Minecraft.World/Items/RecordingItem.cpp @@ -7,58 +7,59 @@ #include "RecordingItem.h" #include "../Stats/GenericStats.h" -RecordingItem::RecordingItem(int id, const std::wstring& recording) : Item(id), recording( recording ) -{ - this->maxStackSize = 1; +RecordingItem::RecordingItem(int id, const std::wstring& recording) + : Item(id), recording(recording) { + this->maxStackSize = 1; } -Icon *RecordingItem::getIcon(int auxValue) -{ - return icon; +Icon* RecordingItem::getIcon(int auxValue) { return icon; } + +bool RecordingItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (level->getTile(x, y, z) == Tile::recordPlayer_Id && + level->getData(x, y, z) == 0) { + if (!bTestUseOnOnly) { + if (level->isClientSide) return true; + + ((RecordPlayerTile*)Tile::recordPlayer) + ->setRecord(level, x, y, z, id); + level->levelEvent(nullptr, LevelEvent::SOUND_PLAY_RECORDING, x, y, + z, id); + itemInstance->count--; + + player->awardStat(GenericStats::musicToMyEars(), + GenericStats::param_musicToMyEars(id)); + } + return true; + } + return false; } -bool RecordingItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if (level->getTile(x, y, z) == Tile::recordPlayer_Id && level->getData(x, y, z) == 0) - { - if(!bTestUseOnOnly) - { - if (level->isClientSide) return true; +void RecordingItem::appendHoverText( + std::shared_ptr itemInstance, std::shared_ptr player, + std::vector* lines, bool advanced, + std::vector& unformattedStrings) { + eMinecraftColour rarityColour = + getRarity(std::shared_ptr())->color; + int colour = app.GetHTMLColour(rarityColour); + wchar_t formatted[256]; - ((RecordPlayerTile *) Tile::recordPlayer)->setRecord(level, x, y, z, id); - level->levelEvent(nullptr, LevelEvent::SOUND_PLAY_RECORDING, x, y, z, id); - itemInstance->count--; + swprintf(formatted, 256, L"%ls", colour, + L"C418 - ", recording.c_str()); - player->awardStat( - GenericStats::musicToMyEars(), - GenericStats::param_musicToMyEars(id) - ); - } - return true; - } - return false; + lines->push_back(formatted); + + unformattedStrings.push_back(recording); } -void RecordingItem::appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings) -{ - eMinecraftColour rarityColour = getRarity(std::shared_ptr())->color; - int colour = app.GetHTMLColour(rarityColour); - wchar_t formatted[256]; - - swprintf(formatted, 256, L"%ls",colour,L"C418 - ", recording.c_str()); - - lines->push_back(formatted); - - unformattedStrings.push_back(recording); +const Rarity* RecordingItem::getRarity( + std::shared_ptr itemInstance) { + return (Rarity*)Rarity::rare; } -const Rarity *RecordingItem::getRarity(std::shared_ptr itemInstance) -{ - return (Rarity *)Rarity::rare; -} - -void RecordingItem::registerIcons(IconRegister *iconRegister) -{ - icon = iconRegister->registerIcon(L"record_" + recording); +void RecordingItem::registerIcons(IconRegister* iconRegister) { + icon = iconRegister->registerIcon(L"record_" + recording); } diff --git a/Minecraft.World/Items/RecordingItem.h b/Minecraft.World/Items/RecordingItem.h index 389e0b51c..e1c1e8235 100644 --- a/Minecraft.World/Items/RecordingItem.h +++ b/Minecraft.World/Items/RecordingItem.h @@ -1,23 +1,29 @@ #pragma once - #include "Item.h" -class RecordingItem : public Item -{ +class RecordingItem : public Item { public: - const std::wstring recording; + const std::wstring recording; -public: // 4J Stu - Was protected in Java, but the can't access it where we need - RecordingItem(int id, const std::wstring& recording); +public + : // 4J Stu - Was protected in Java, but the can't access it where we need + RecordingItem(int id, const std::wstring& recording); - //@Override - Icon *getIcon(int auxValue); - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + //@Override + Icon* getIcon(int auxValue); + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); - virtual void appendHoverText(std::shared_ptr itemInstance, std::shared_ptr player, std::vector *lines, bool advanced, std::vector &unformattedStrings); - virtual const Rarity *getRarity(std::shared_ptr itemInstance); + virtual void appendHoverText(std::shared_ptr itemInstance, + std::shared_ptr player, + std::vector* lines, + bool advanced, + std::vector& unformattedStrings); + virtual const Rarity* getRarity(std::shared_ptr itemInstance); - //@Override - void registerIcons(IconRegister *iconRegister); + //@Override + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/RedstoneItem.cpp b/Minecraft.World/Items/RedstoneItem.cpp index 20dca9c38..bacfd7d6e 100644 --- a/Minecraft.World/Items/RedstoneItem.cpp +++ b/Minecraft.World/Items/RedstoneItem.cpp @@ -6,35 +6,35 @@ #include "../Stats/GenericStats.h" #include "RedstoneItem.h" -RedStoneItem::RedStoneItem(int id) : Item(id) -{ -} - -bool RedStoneItem::useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if (level->getTile(x, y, z) != Tile::topSnow_Id) - { - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - if (!level->isEmptyTile(x, y, z)) return false; - } - if (!player->mayBuild(x, y, z)) return false; - if (Tile::redStoneDust->mayPlace(level, x, y, z)) - { - if(!bTestUseOnOnly) - { - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat(GenericStats::blocksPlaced(Tile::redStoneDust_Id), GenericStats::param_blocksPlaced(Tile::redStoneDust_Id,itemInstance->getAuxValue(),1)); - - itemInstance->count--; - level->setTile(x, y, z, Tile::redStoneDust_Id); - } - } - - return true; +RedStoneItem::RedStoneItem(int id) : Item(id) {} + +bool RedStoneItem::useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (level->getTile(x, y, z) != Tile::topSnow_Id) { + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; + if (!level->isEmptyTile(x, y, z)) return false; + } + if (!player->mayBuild(x, y, z)) return false; + if (Tile::redStoneDust->mayPlace(level, x, y, z)) { + if (!bTestUseOnOnly) { + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat( + GenericStats::blocksPlaced(Tile::redStoneDust_Id), + GenericStats::param_blocksPlaced( + Tile::redStoneDust_Id, itemInstance->getAuxValue(), 1)); + + itemInstance->count--; + level->setTile(x, y, z, Tile::redStoneDust_Id); + } + } + + return true; } diff --git a/Minecraft.World/Items/RedstoneItem.h b/Minecraft.World/Items/RedstoneItem.h index a02273931..96bbbd4fb 100644 --- a/Minecraft.World/Items/RedstoneItem.h +++ b/Minecraft.World/Items/RedstoneItem.h @@ -1,13 +1,14 @@ #pragma once - #include "Item.h" - class RedStoneItem : public Item - { - public: - RedStoneItem(int id); +class RedStoneItem : public Item { +public: + RedStoneItem(int id); - public: - virtual bool useOn(std::shared_ptr itemInstance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); +public: + virtual bool useOn(std::shared_ptr itemInstance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/SaddleItem.cpp b/Minecraft.World/Items/SaddleItem.cpp index f0e2194ea..e2ec5a500 100644 --- a/Minecraft.World/Items/SaddleItem.cpp +++ b/Minecraft.World/Items/SaddleItem.cpp @@ -4,28 +4,24 @@ #include "../Headers/net.minecraft.world.entity.h" #include "SaddleItem.h" -SaddleItem::SaddleItem(int id) : Item(id) -{ - maxStackSize = 1; -} +SaddleItem::SaddleItem(int id) : Item(id) { maxStackSize = 1; } -bool SaddleItem::interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob) -{ - if ( std::dynamic_pointer_cast(mob) ) - { +bool SaddleItem::interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob) { + if (std::dynamic_pointer_cast(mob)) { std::shared_ptr pig = std::dynamic_pointer_cast(mob); - if (!pig->hasSaddle() && !pig->isBaby()) - { + if (!pig->hasSaddle() && !pig->isBaby()) { pig->setSaddle(true); itemInstance->count--; } - return true; + return true; } - return false; + return false; } -bool SaddleItem::hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker) -{ +bool SaddleItem::hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker) { interactEnemy(itemInstance, mob); return true; } \ No newline at end of file diff --git a/Minecraft.World/Items/SaddleItem.h b/Minecraft.World/Items/SaddleItem.h index b7f668e93..6c124ec88 100644 --- a/Minecraft.World/Items/SaddleItem.h +++ b/Minecraft.World/Items/SaddleItem.h @@ -1,13 +1,14 @@ #pragma once - #include "Item.h" -class SaddleItem : public Item -{ +class SaddleItem : public Item { public: - SaddleItem(int id); + SaddleItem(int id); - virtual bool interactEnemy(std::shared_ptr itemInstance, std::shared_ptr mob); - virtual bool hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker); + virtual bool interactEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob); + virtual bool hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker); }; \ No newline at end of file diff --git a/Minecraft.World/Items/SeedFoodItem.cpp b/Minecraft.World/Items/SeedFoodItem.cpp index 7526d9df8..b610b00fd 100644 --- a/Minecraft.World/Items/SeedFoodItem.cpp +++ b/Minecraft.World/Items/SeedFoodItem.cpp @@ -4,28 +4,29 @@ #include "../Headers/net.minecraft.world.level.h" #include "SeedFoodItem.h" -SeedFoodItem::SeedFoodItem(int id, int nutrition, float saturationMod, int resultId, int targetLand) : FoodItem(id, nutrition, saturationMod, false) -{ - this->resultId = resultId; - this->targetLand = targetLand; - +SeedFoodItem::SeedFoodItem(int id, int nutrition, float saturationMod, + int resultId, int targetLand) + : FoodItem(id, nutrition, saturationMod, false) { + this->resultId = resultId; + this->targetLand = targetLand; } -bool SeedFoodItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (face != Facing::UP) return false; +bool SeedFoodItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + if (face != Facing::UP) return false; - if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) return false; - int targetType = level->getTile(x, y, z); + if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) + return false; + int targetType = level->getTile(x, y, z); - if (targetType == targetLand && level->isEmptyTile(x, y + 1, z)) - { - if(!bTestUseOnOnly) - { - level->setTile(x, y + 1, z, resultId); - instance->count--; - } - return true; - } - return false; + if (targetType == targetLand && level->isEmptyTile(x, y + 1, z)) { + if (!bTestUseOnOnly) { + level->setTile(x, y + 1, z, resultId); + instance->count--; + } + return true; + } + return false; } \ No newline at end of file diff --git a/Minecraft.World/Items/SeedFoodItem.h b/Minecraft.World/Items/SeedFoodItem.h index 0b9b79b5d..9b12a579a 100644 --- a/Minecraft.World/Items/SeedFoodItem.h +++ b/Minecraft.World/Items/SeedFoodItem.h @@ -2,14 +2,17 @@ #include "FoodItem.h" -class SeedFoodItem : public FoodItem -{ +class SeedFoodItem : public FoodItem { private: - int resultId; - int targetLand; + int resultId; + int targetLand; public: - SeedFoodItem(int id, int nutrition, float saturationMod, int resultId, int targetLand); + SeedFoodItem(int id, int nutrition, float saturationMod, int resultId, + int targetLand); - bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly); + bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly); }; \ No newline at end of file diff --git a/Minecraft.World/Items/SeedItem.cpp b/Minecraft.World/Items/SeedItem.cpp index 5d6cf11cb..841cf12b5 100644 --- a/Minecraft.World/Items/SeedItem.cpp +++ b/Minecraft.World/Items/SeedItem.cpp @@ -8,28 +8,28 @@ #include "ItemInstance.h" #include "SeedItem.h" -SeedItem::SeedItem(int id, int resultId, int targetLand) : Item(id) -{ +SeedItem::SeedItem(int id, int resultId, int targetLand) : Item(id) { this->resultId = resultId; - this->targetLand = targetLand; + this->targetLand = targetLand; } -bool SeedItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed +bool SeedItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed if (face != 1) return false; - if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) return false; + if (!player->mayBuild(x, y, z) || !player->mayBuild(x, y + 1, z)) + return false; int targetType = level->getTile(x, y, z); - if (targetType == targetLand && level->isEmptyTile(x, y + 1, z)) - { - if(!bTestUseOnOnly) - { - level->setTile(x, y + 1, z, resultId); - instance->count--; - } + if (targetType == targetLand && level->isEmptyTile(x, y + 1, z)) { + if (!bTestUseOnOnly) { + level->setTile(x, y + 1, z, resultId); + instance->count--; + } return true; } return false; diff --git a/Minecraft.World/Items/SeedItem.h b/Minecraft.World/Items/SeedItem.h index f29b69260..40fe9aecb 100644 --- a/Minecraft.World/Items/SeedItem.h +++ b/Minecraft.World/Items/SeedItem.h @@ -1,16 +1,17 @@ #pragma once - #include "Item.h" -class SeedItem : public Item -{ +class SeedItem : public Item { private: - int resultId; - int targetLand; + int resultId; + int targetLand; public: - SeedItem(int id, int resultId, int targetLand); + SeedItem(int id, int resultId, int targetLand); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/ShearsItem.cpp b/Minecraft.World/Items/ShearsItem.cpp index 225c0801b..7cd73f72b 100644 --- a/Minecraft.World/Items/ShearsItem.cpp +++ b/Minecraft.World/Items/ShearsItem.cpp @@ -3,35 +3,34 @@ #include "../Blocks/Tile.h" #include "../Headers/net.minecraft.world.entity.h" -ShearsItem::ShearsItem(int itemId) : Item(itemId) -{ - setMaxStackSize(1); - setMaxDamage(238); +ShearsItem::ShearsItem(int itemId) : Item(itemId) { + setMaxStackSize(1); + setMaxDamage(238); } -bool ShearsItem::mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner) -{ - if (tile == Tile::leaves_Id || tile == Tile::web_Id || tile == Tile::tallgrass_Id || tile == Tile::vine_Id || tile == Tile::tripWire_Id) - { +bool ShearsItem::mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner) { + if (tile == Tile::leaves_Id || tile == Tile::web_Id || + tile == Tile::tallgrass_Id || tile == Tile::vine_Id || + tile == Tile::tripWire_Id) { itemInstance->hurt(1, owner); - return true; + return true; } return Item::mineBlock(itemInstance, level, tile, x, y, z, owner); } -bool ShearsItem::canDestroySpecial(Tile *tile) -{ - return tile->id == Tile::web_Id || tile->id == Tile::redStoneDust_Id || tile->id == Tile::tripWire_Id; +bool ShearsItem::canDestroySpecial(Tile* tile) { + return tile->id == Tile::web_Id || tile->id == Tile::redStoneDust_Id || + tile->id == Tile::tripWire_Id; } -float ShearsItem::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - if (tile->id == Tile::web_Id || tile->id == Tile::leaves_Id) - { +float ShearsItem::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + if (tile->id == Tile::web_Id || tile->id == Tile::leaves_Id) { return 15; } - if (tile->id == Tile::cloth_Id) - { + if (tile->id == Tile::cloth_Id) { return 5; } return Item::getDestroySpeed(itemInstance, tile); diff --git a/Minecraft.World/Items/ShearsItem.h b/Minecraft.World/Items/ShearsItem.h index deaeb8dd4..bbf49dd2f 100644 --- a/Minecraft.World/Items/ShearsItem.h +++ b/Minecraft.World/Items/ShearsItem.h @@ -1,13 +1,14 @@ #pragma once - #include "Item.h" -class ShearsItem : public Item -{ +class ShearsItem : public Item { public: - ShearsItem(int itemId); - virtual bool mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner); - virtual bool canDestroySpecial(Tile *tile); - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); + ShearsItem(int itemId); + virtual bool mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner); + virtual bool canDestroySpecial(Tile* tile); + virtual float getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile); }; \ No newline at end of file diff --git a/Minecraft.World/Items/ShovelItem.cpp b/Minecraft.World/Items/ShovelItem.cpp index c249bf9c4..e4af1a969 100644 --- a/Minecraft.World/Items/ShovelItem.cpp +++ b/Minecraft.World/Items/ShovelItem.cpp @@ -3,31 +3,28 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "ShovelItem.h" -TileArray *ShovelItem::diggables = NULL; +TileArray* ShovelItem::diggables = NULL; -void ShovelItem::staticCtor() -{ - ShovelItem::diggables = new TileArray( SHOVEL_DIGGABLES); - diggables->data[0] = Tile::grass; - diggables->data[1] = Tile::dirt; - diggables->data[2] = Tile::sand; - diggables->data[3] = Tile::gravel; - diggables->data[4] = Tile::topSnow; - diggables->data[5] = Tile::snow; - diggables->data[6] = Tile::clay; - diggables->data[7] = Tile::farmland; - // 4J - brought forward from 1.2.3 - diggables->data[8] = Tile::hellSand; - diggables->data[9] = Tile::mycel; +void ShovelItem::staticCtor() { + ShovelItem::diggables = new TileArray(SHOVEL_DIGGABLES); + diggables->data[0] = Tile::grass; + diggables->data[1] = Tile::dirt; + diggables->data[2] = Tile::sand; + diggables->data[3] = Tile::gravel; + diggables->data[4] = Tile::topSnow; + diggables->data[5] = Tile::snow; + diggables->data[6] = Tile::clay; + diggables->data[7] = Tile::farmland; + // 4J - brought forward from 1.2.3 + diggables->data[8] = Tile::hellSand; + diggables->data[9] = Tile::mycel; } -ShovelItem::ShovelItem(int id, const Tier *tier) : DiggerItem(id, 1, tier, diggables) -{ -} +ShovelItem::ShovelItem(int id, const Tier* tier) + : DiggerItem(id, 1, tier, diggables) {} -bool ShovelItem::canDestroySpecial(Tile *tile) -{ - if (tile == Tile::topSnow) return true; - if (tile == Tile::snow) return true; - return false; +bool ShovelItem::canDestroySpecial(Tile* tile) { + if (tile == Tile::topSnow) return true; + if (tile == Tile::snow) return true; + return false; } \ No newline at end of file diff --git a/Minecraft.World/Items/ShovelItem.h b/Minecraft.World/Items/ShovelItem.h index c9c422405..ac9211f91 100644 --- a/Minecraft.World/Items/ShovelItem.h +++ b/Minecraft.World/Items/ShovelItem.h @@ -2,14 +2,13 @@ #include "DiggerItem.h" #define SHOVEL_DIGGABLES 10 -class ShovelItem : public DiggerItem -{ +class ShovelItem : public DiggerItem { private: - static TileArray *diggables; + static TileArray* diggables; public: - static void staticCtor(); - ShovelItem(int id, const Tier *tier); + static void staticCtor(); + ShovelItem(int id, const Tier* tier); - bool canDestroySpecial(Tile *tile); + bool canDestroySpecial(Tile* tile); }; \ No newline at end of file diff --git a/Minecraft.World/Items/SignItem.cpp b/Minecraft.World/Items/SignItem.cpp index 88a4d2315..6d3a62dc4 100644 --- a/Minecraft.World/Items/SignItem.cpp +++ b/Minecraft.World/Items/SignItem.cpp @@ -7,53 +7,49 @@ #include "SignItem.h" #include "../Stats/GenericStats.h" -SignItem::SignItem(int id) : Item(id) -{ - // 4J-PB - Changed for TU9 - maxStackSize = 16; +SignItem::SignItem(int id) : Item(id) { + // 4J-PB - Changed for TU9 + maxStackSize = 16; } -bool SignItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if (face == 0) return false; - if (!level->getMaterial(x, y, z)->isSolid()) return false; +bool SignItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (face == 0) return false; + if (!level->getMaterial(x, y, z)->isSolid()) return false; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; + if (!player->mayBuild(x, y, z)) return false; - if (!player->mayBuild(x, y, z)) return false; + if (!Tile::sign->mayPlace(level, x, y, z)) return false; - if (!Tile::sign->mayPlace(level, x, y, z)) return false; + if (!bTestUseOnOnly) { + if (face == 1) { + int rot = Mth::floor(((player->yRot + 180) * 16) / 360 + 0.5) & 15; + level->setTileAndData(x, y, z, Tile::sign_Id, rot); + } else { + level->setTileAndData(x, y, z, Tile::wallSign_Id, face); + } - if(!bTestUseOnOnly) - { - if (face == 1) - { - int rot = Mth::floor(((player->yRot + 180) * 16) / 360 + 0.5) & 15; - level->setTileAndData(x, y, z, Tile::sign_Id, rot); - } - else - { - level->setTileAndData(x, y, z, Tile::wallSign_Id, face); - } + instance->count--; + std::shared_ptr ste = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (ste != NULL) player->openTextEdit(ste); - instance->count--; - std::shared_ptr ste = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (ste != NULL) player->openTextEdit(ste); - - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat( - GenericStats::blocksPlaced((face==1) ? Tile::sign_Id : Tile::wallSign_Id), - GenericStats::param_blocksPlaced( - (face==1) ? Tile::sign_Id : Tile::wallSign_Id, - instance->getAuxValue(), - 1) - ); - } - return true; + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat(GenericStats::blocksPlaced( + (face == 1) ? Tile::sign_Id : Tile::wallSign_Id), + GenericStats::param_blocksPlaced( + (face == 1) ? Tile::sign_Id : Tile::wallSign_Id, + instance->getAuxValue(), 1)); + } + return true; } diff --git a/Minecraft.World/Items/SignItem.h b/Minecraft.World/Items/SignItem.h index 4b9c32a12..d2dcb2bd6 100644 --- a/Minecraft.World/Items/SignItem.h +++ b/Minecraft.World/Items/SignItem.h @@ -1,12 +1,13 @@ #pragma once - #include "Item.h" -class SignItem : public Item -{ +class SignItem : public Item { public: - SignItem(int id); + SignItem(int id); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/SnowballItem.cpp b/Minecraft.World/Items/SnowballItem.cpp index a79c75218..b5799b2d9 100644 --- a/Minecraft.World/Items/SnowballItem.cpp +++ b/Minecraft.World/Items/SnowballItem.cpp @@ -6,18 +6,18 @@ #include "SnowballItem.h" #include "../Util/SoundTypes.h" -SnowballItem::SnowballItem(int id) : Item(id) -{ - this->maxStackSize = 16; -} +SnowballItem::SnowballItem(int id) : Item(id) { this->maxStackSize = 16; } -std::shared_ptr SnowballItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - if (!player->abilities.instabuild) - { - instance->count--; - } - level->playSound((std::shared_ptr ) player, eSoundType_RANDOM_BOW, 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); - if (!level->isClientSide) level->addEntity( std::shared_ptr( new Snowball(level, player) ) ); +std::shared_ptr SnowballItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + if (!player->abilities.instabuild) { + instance->count--; + } + level->playSound((std::shared_ptr)player, eSoundType_RANDOM_BOW, + 0.5f, 0.4f / (random->nextFloat() * 0.4f + 0.8f)); + if (!level->isClientSide) + level->addEntity( + std::shared_ptr(new Snowball(level, player))); return instance; } \ No newline at end of file diff --git a/Minecraft.World/Items/SnowballItem.h b/Minecraft.World/Items/SnowballItem.h index 5e3bae509..19add7a00 100644 --- a/Minecraft.World/Items/SnowballItem.h +++ b/Minecraft.World/Items/SnowballItem.h @@ -1,12 +1,12 @@ #pragma once - #include "Item.h" -class SnowballItem : public Item -{ +class SnowballItem : public Item { public: - SnowballItem(int id); + SnowballItem(int id); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/AnvilTileItem.cpp b/Minecraft.World/Items/TileItems/AnvilTileItem.cpp index 4dd93890e..44381fb3c 100644 --- a/Minecraft.World/Items/TileItems/AnvilTileItem.cpp +++ b/Minecraft.World/Items/TileItems/AnvilTileItem.cpp @@ -2,17 +2,15 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "AnvilTileItem.h" -AnvilTileItem::AnvilTileItem(Tile *tile) : MultiTextureTileItem(tile->id - 256, tile, (int *)AnvilTile::ANVIL_NAMES, 3) -{ +AnvilTileItem::AnvilTileItem(Tile* tile) + : MultiTextureTileItem(tile->id - 256, tile, (int*)AnvilTile::ANVIL_NAMES, + 3) {} + +int AnvilTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue << 2; } -int AnvilTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue << 2; -} - -unsigned int AnvilTileItem::getDescriptionId(int iData) -{ - int damage = iData >> 2; - return MultiTextureTileItem::getDescriptionId(damage); +unsigned int AnvilTileItem::getDescriptionId(int iData) { + int damage = iData >> 2; + return MultiTextureTileItem::getDescriptionId(damage); } diff --git a/Minecraft.World/Items/TileItems/AnvilTileItem.h b/Minecraft.World/Items/TileItems/AnvilTileItem.h index 0604f11d4..40c6b7e13 100644 --- a/Minecraft.World/Items/TileItems/AnvilTileItem.h +++ b/Minecraft.World/Items/TileItems/AnvilTileItem.h @@ -2,12 +2,12 @@ #include "MultiTextureTileItem.h" -class AnvilTileItem : public MultiTextureTileItem -{ +class AnvilTileItem : public MultiTextureTileItem { public: - AnvilTileItem(Tile *tile); + AnvilTileItem(Tile* tile); + + int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId(int iData); - int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(int iData); private: }; diff --git a/Minecraft.World/Items/TileItems/AuxDataTileItem.cpp b/Minecraft.World/Items/TileItems/AuxDataTileItem.cpp index bbc073b2d..3522706f4 100644 --- a/Minecraft.World/Items/TileItems/AuxDataTileItem.cpp +++ b/Minecraft.World/Items/TileItems/AuxDataTileItem.cpp @@ -2,20 +2,15 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "AuxDataTileItem.h" -AuxDataTileItem::AuxDataTileItem(int id, Tile *parentTile) : TileItem(id) -{ - this->parentTile = parentTile; +AuxDataTileItem::AuxDataTileItem(int id, Tile* parentTile) : TileItem(id) { + this->parentTile = parentTile; - setMaxDamage(0); - setStackedByData(true); + setMaxDamage(0); + setStackedByData(true); } -Icon *AuxDataTileItem::getIcon(int itemAuxValue) -{ - return parentTile->getTexture(2, itemAuxValue); +Icon* AuxDataTileItem::getIcon(int itemAuxValue) { + return parentTile->getTexture(2, itemAuxValue); } -int AuxDataTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; -} \ No newline at end of file +int AuxDataTileItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/AuxDataTileItem.h b/Minecraft.World/Items/TileItems/AuxDataTileItem.h index cd264e35d..ab77d238d 100644 --- a/Minecraft.World/Items/TileItems/AuxDataTileItem.h +++ b/Minecraft.World/Items/TileItems/AuxDataTileItem.h @@ -4,14 +4,13 @@ class Tile; -class AuxDataTileItem : public TileItem -{ +class AuxDataTileItem : public TileItem { private: - Tile *parentTile; + Tile* parentTile; public: - AuxDataTileItem(int id, Tile *parentTile); + AuxDataTileItem(int id, Tile* parentTile); - Icon *getIcon(int itemAuxValue); - int getLevelDataForAuxValue(int auxValue); + Icon* getIcon(int itemAuxValue); + int getLevelDataForAuxValue(int auxValue); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/ClothTileItem.cpp b/Minecraft.World/Items/TileItems/ClothTileItem.cpp index 9a5878a86..44652f138 100644 --- a/Minecraft.World/Items/TileItems/ClothTileItem.cpp +++ b/Minecraft.World/Items/TileItems/ClothTileItem.cpp @@ -4,65 +4,40 @@ #include "../DyePowderItem.h" #include "ClothTileItem.h" -const unsigned int ClothTileItem::COLOR_DESCS[] = -{ - IDS_TILE_CLOTH_BLACK, - IDS_TILE_CLOTH_RED, - IDS_TILE_CLOTH_GREEN, - IDS_TILE_CLOTH_BROWN, - IDS_TILE_CLOTH_BLUE, - IDS_TILE_CLOTH_PURPLE, - IDS_TILE_CLOTH_CYAN, - IDS_TILE_CLOTH_SILVER, - IDS_TILE_CLOTH_GRAY, - IDS_TILE_CLOTH_PINK, - IDS_TILE_CLOTH_LIME, - IDS_TILE_CLOTH_YELLOW, - IDS_TILE_CLOTH_LIGHT_BLUE, - IDS_TILE_CLOTH_MAGENTA, - IDS_TILE_CLOTH_ORANGE, - IDS_TILE_CLOTH_WHITE -}; +const unsigned int ClothTileItem::COLOR_DESCS[] = { + IDS_TILE_CLOTH_BLACK, IDS_TILE_CLOTH_RED, IDS_TILE_CLOTH_GREEN, + IDS_TILE_CLOTH_BROWN, IDS_TILE_CLOTH_BLUE, IDS_TILE_CLOTH_PURPLE, + IDS_TILE_CLOTH_CYAN, IDS_TILE_CLOTH_SILVER, IDS_TILE_CLOTH_GRAY, + IDS_TILE_CLOTH_PINK, IDS_TILE_CLOTH_LIME, IDS_TILE_CLOTH_YELLOW, + IDS_TILE_CLOTH_LIGHT_BLUE, IDS_TILE_CLOTH_MAGENTA, IDS_TILE_CLOTH_ORANGE, + IDS_TILE_CLOTH_WHITE}; -const unsigned int ClothTileItem::CARPET_COLOR_DESCS[] = -{ - IDS_TILE_CARPET_BLACK, - IDS_TILE_CARPET_RED, - IDS_TILE_CARPET_GREEN, - IDS_TILE_CARPET_BROWN, - IDS_TILE_CARPET_BLUE, - IDS_TILE_CARPET_PURPLE, - IDS_TILE_CARPET_CYAN, - IDS_TILE_CARPET_SILVER, - IDS_TILE_CARPET_GRAY, - IDS_TILE_CARPET_PINK, - IDS_TILE_CARPET_LIME, - IDS_TILE_CARPET_YELLOW, - IDS_TILE_CARPET_LIGHT_BLUE, - IDS_TILE_CARPET_MAGENTA, - IDS_TILE_CARPET_ORANGE, - IDS_TILE_CARPET_WHITE -}; +const unsigned int ClothTileItem::CARPET_COLOR_DESCS[] = { + IDS_TILE_CARPET_BLACK, IDS_TILE_CARPET_RED, IDS_TILE_CARPET_GREEN, + IDS_TILE_CARPET_BROWN, IDS_TILE_CARPET_BLUE, IDS_TILE_CARPET_PURPLE, + IDS_TILE_CARPET_CYAN, IDS_TILE_CARPET_SILVER, IDS_TILE_CARPET_GRAY, + IDS_TILE_CARPET_PINK, IDS_TILE_CARPET_LIME, IDS_TILE_CARPET_YELLOW, + IDS_TILE_CARPET_LIGHT_BLUE, IDS_TILE_CARPET_MAGENTA, IDS_TILE_CARPET_ORANGE, + IDS_TILE_CARPET_WHITE}; -ClothTileItem::ClothTileItem(int id) : TileItem(id) -{ - setMaxDamage(0); - setStackedByData(true); +ClothTileItem::ClothTileItem(int id) : TileItem(id) { + setMaxDamage(0); + setStackedByData(true); } -Icon *ClothTileItem::getIcon(int itemAuxValue) -{ - return Tile::cloth->getTexture(2, ClothTile::getTileDataForItemAuxValue(itemAuxValue)); - +Icon* ClothTileItem::getIcon(int itemAuxValue) { + return Tile::cloth->getTexture( + 2, ClothTile::getTileDataForItemAuxValue(itemAuxValue)); } -int ClothTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; -} +int ClothTileItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } -unsigned int ClothTileItem::getDescriptionId(std::shared_ptr instance) -{ - if(getTileId() == Tile::woolCarpet_Id) return CARPET_COLOR_DESCS[ClothTile::getTileDataForItemAuxValue(instance->getAuxValue())]; - else return COLOR_DESCS[ClothTile::getTileDataForItemAuxValue(instance->getAuxValue())]; +unsigned int ClothTileItem::getDescriptionId( + std::shared_ptr instance) { + if (getTileId() == Tile::woolCarpet_Id) + return CARPET_COLOR_DESCS[ClothTile::getTileDataForItemAuxValue( + instance->getAuxValue())]; + else + return COLOR_DESCS[ClothTile::getTileDataForItemAuxValue( + instance->getAuxValue())]; } diff --git a/Minecraft.World/Items/TileItems/ClothTileItem.h b/Minecraft.World/Items/TileItems/ClothTileItem.h index 502c69a5d..b9a72291c 100644 --- a/Minecraft.World/Items/TileItems/ClothTileItem.h +++ b/Minecraft.World/Items/TileItems/ClothTileItem.h @@ -1,17 +1,16 @@ #pragma once - #include "TileItem.h" -class ClothTileItem : public TileItem -{ -public: - static const unsigned int COLOR_DESCS[]; - static const unsigned int CARPET_COLOR_DESCS[]; +class ClothTileItem : public TileItem { +public: + static const unsigned int COLOR_DESCS[]; + static const unsigned int CARPET_COLOR_DESCS[]; - ClothTileItem(int id); - - virtual Icon *getIcon(int itemAuxValue); - virtual int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + ClothTileItem(int id); + + virtual Icon* getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/ColoredTileItem.cpp b/Minecraft.World/Items/TileItems/ColoredTileItem.cpp index c32ead9ac..e0c767032 100644 --- a/Minecraft.World/Items/TileItems/ColoredTileItem.cpp +++ b/Minecraft.World/Items/TileItems/ColoredTileItem.cpp @@ -2,59 +2,51 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "ColoredTileItem.h" -ColoredTileItem::ColoredTileItem(int id, bool stackedByData) : TileItem(id) -{ - this->colorTile = Tile::tiles[getTileId()]; +ColoredTileItem::ColoredTileItem(int id, bool stackedByData) : TileItem(id) { + this->colorTile = Tile::tiles[getTileId()]; - if (stackedByData) - { - setMaxDamage(0); - setStackedByData(true); - } + if (stackedByData) { + setMaxDamage(0); + setStackedByData(true); + } } -ColoredTileItem::~ColoredTileItem() -{ - if(descriptionPostfixes.data != NULL) delete [] descriptionPostfixes.data; +ColoredTileItem::~ColoredTileItem() { + if (descriptionPostfixes.data != NULL) delete[] descriptionPostfixes.data; } -int ColoredTileItem::getColor(std::shared_ptr item, int spriteLayer) -{ - return colorTile->getColor(item->getAuxValue()); +int ColoredTileItem::getColor(std::shared_ptr item, + int spriteLayer) { + return colorTile->getColor(item->getAuxValue()); } -Icon *ColoredTileItem::getIcon(int auxValue) -{ - return colorTile->getTexture(0, auxValue); +Icon* ColoredTileItem::getIcon(int auxValue) { + return colorTile->getTexture(0, auxValue); } -int ColoredTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int ColoredTileItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } + +ColoredTileItem* ColoredTileItem::setDescriptionPostfixes( + intArray descriptionPostfixes) { + if (this->descriptionPostfixes.data != NULL) + delete this->descriptionPostfixes.data; + this->descriptionPostfixes = intArray(descriptionPostfixes.length); + for (unsigned int i = 0; i < descriptionPostfixes.length; ++i) { + this->descriptionPostfixes[i] = descriptionPostfixes[i]; + } + + return this; } -ColoredTileItem *ColoredTileItem::setDescriptionPostfixes(intArray descriptionPostfixes) -{ - if(this->descriptionPostfixes.data != NULL) delete this->descriptionPostfixes.data; - this->descriptionPostfixes = intArray(descriptionPostfixes.length); - for(unsigned int i = 0; i < descriptionPostfixes.length; ++i ) - { - this->descriptionPostfixes[i] = descriptionPostfixes[i]; - } - - return this; -} - -unsigned int ColoredTileItem::getDescriptionId(std::shared_ptr instance) -{ - if (descriptionPostfixes.data == NULL) - { - return TileItem::getDescriptionId(instance); - } - int id = instance->getAuxValue(); - if (id >= 0 && id < descriptionPostfixes.length) - { - return descriptionPostfixes[id]; //TileItem::getDescriptionId(instance) + "." + descriptionPostfixes[id]; - } - return TileItem::getDescriptionId(instance); +unsigned int ColoredTileItem::getDescriptionId( + std::shared_ptr instance) { + if (descriptionPostfixes.data == NULL) { + return TileItem::getDescriptionId(instance); + } + int id = instance->getAuxValue(); + if (id >= 0 && id < descriptionPostfixes.length) { + return descriptionPostfixes[id]; // TileItem::getDescriptionId(instance) + // + "." + descriptionPostfixes[id]; + } + return TileItem::getDescriptionId(instance); } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/ColoredTileItem.h b/Minecraft.World/Items/TileItems/ColoredTileItem.h index dfe5ebe64..db41bfabe 100644 --- a/Minecraft.World/Items/TileItems/ColoredTileItem.h +++ b/Minecraft.World/Items/TileItems/ColoredTileItem.h @@ -4,22 +4,23 @@ class ItemInstance; -class ColoredTileItem : public TileItem -{ +class ColoredTileItem : public TileItem { private: - // Was const, but removing that so we don't have to make all the functions const as well! - Tile *colorTile; - intArray descriptionPostfixes; + // Was const, but removing that so we don't have to make all the functions + // const as well! + Tile* colorTile; + intArray descriptionPostfixes; public: - using TileItem::getColor; - ColoredTileItem(int id, bool stackedByData); - ~ColoredTileItem(); + using TileItem::getColor; + ColoredTileItem(int id, bool stackedByData); + ~ColoredTileItem(); - virtual int getColor(std::shared_ptr item, int spriteLayer); - virtual Icon *getIcon(int auxValue); - virtual int getLevelDataForAuxValue(int auxValue); + virtual int getColor(std::shared_ptr item, int spriteLayer); + virtual Icon* getIcon(int auxValue); + virtual int getLevelDataForAuxValue(int auxValue); - ColoredTileItem *setDescriptionPostfixes(intArray descriptionPostfixes); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + ColoredTileItem* setDescriptionPostfixes(intArray descriptionPostfixes); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; diff --git a/Minecraft.World/Items/TileItems/LeafTileItem.cpp b/Minecraft.World/Items/TileItems/LeafTileItem.cpp index f649d20c1..b7961636c 100644 --- a/Minecraft.World/Items/TileItems/LeafTileItem.cpp +++ b/Minecraft.World/Items/TileItems/LeafTileItem.cpp @@ -4,44 +4,36 @@ #include "LeafTileItem.h" #include "../../Util/FoliageColor.h" -LeafTileItem::LeafTileItem(int id) : TileItem(id) -{ - setMaxDamage(0); - setStackedByData(true); +LeafTileItem::LeafTileItem(int id) : TileItem(id) { + setMaxDamage(0); + setStackedByData(true); } -int LeafTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue | LeafTile::PERSISTENT_LEAF_BIT; - +int LeafTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue | LeafTile::PERSISTENT_LEAF_BIT; } -Icon *LeafTileItem::getIcon(int itemAuxValue) -{ - return Tile::leaves->getTexture(0, itemAuxValue); +Icon* LeafTileItem::getIcon(int itemAuxValue) { + return Tile::leaves->getTexture(0, itemAuxValue); } - -int LeafTileItem::getColor(std::shared_ptr item, int spriteLayer) -{ - int data = item->getAuxValue(); - if ((data & LeafTile::EVERGREEN_LEAF) == LeafTile::EVERGREEN_LEAF) - { +int LeafTileItem::getColor(std::shared_ptr item, + int spriteLayer) { + int data = item->getAuxValue(); + if ((data & LeafTile::EVERGREEN_LEAF) == LeafTile::EVERGREEN_LEAF) { return FoliageColor::getEvergreenColor(); } - if ((data & LeafTile::BIRCH_LEAF) == LeafTile::BIRCH_LEAF) - { + if ((data & LeafTile::BIRCH_LEAF) == LeafTile::BIRCH_LEAF) { return FoliageColor::getBirchColor(); } return FoliageColor::getDefaultColor(); } -unsigned int LeafTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= LeafTile::LEAF_NAMES_LENGTH) - { - auxValue = 0; - } - return LeafTile::LEAF_NAMES[auxValue]; +unsigned int LeafTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || auxValue >= LeafTile::LEAF_NAMES_LENGTH) { + auxValue = 0; + } + return LeafTile::LEAF_NAMES[auxValue]; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/LeafTileItem.h b/Minecraft.World/Items/TileItems/LeafTileItem.h index c7de7b94d..3a2ff5be7 100644 --- a/Minecraft.World/Items/TileItems/LeafTileItem.h +++ b/Minecraft.World/Items/TileItems/LeafTileItem.h @@ -1,17 +1,17 @@ #pragma once - #include "TileItem.h" -class LeafTileItem : public TileItem -{ - using TileItem::getColor; +class LeafTileItem : public TileItem { + using TileItem::getColor; + public: - LeafTileItem(int id); + LeafTileItem(int id); - virtual int getLevelDataForAuxValue(int auxValue); - virtual Icon *getIcon(int itemAuxValue); - virtual int getColor(std::shared_ptr item, int spriteLayer); + virtual int getLevelDataForAuxValue(int auxValue); + virtual Icon* getIcon(int itemAuxValue); + virtual int getColor(std::shared_ptr item, int spriteLayer); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; diff --git a/Minecraft.World/Items/TileItems/MultiTextureTileItem.cpp b/Minecraft.World/Items/TileItems/MultiTextureTileItem.cpp index 638e8bfc1..9a702b76c 100644 --- a/Minecraft.World/Items/TileItems/MultiTextureTileItem.cpp +++ b/Minecraft.World/Items/TileItems/MultiTextureTileItem.cpp @@ -2,45 +2,39 @@ #include "../../Blocks/Tile.h" #include "MultiTextureTileItem.h" +MultiTextureTileItem::MultiTextureTileItem(int id, Tile* parentTile, + int* nameExtensions, int iLength) + : TileItem(id) { + this->parentTile = parentTile; + this->nameExtensions = nameExtensions; + this->m_iNameExtensionsLength = iLength; -MultiTextureTileItem::MultiTextureTileItem(int id, Tile *parentTile, int *nameExtensions, int iLength) : TileItem(id) -{ - this->parentTile = parentTile; - this->nameExtensions = nameExtensions; - this->m_iNameExtensionsLength=iLength; - - setMaxDamage(0); - setStackedByData(true); + setMaxDamage(0); + setStackedByData(true); } -Icon *MultiTextureTileItem::getIcon(int itemAuxValue) -{ - return parentTile->getTexture(2, itemAuxValue); +Icon* MultiTextureTileItem::getIcon(int itemAuxValue) { + return parentTile->getTexture(2, itemAuxValue); } -int MultiTextureTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int MultiTextureTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue; } -unsigned int MultiTextureTileItem::getDescriptionId(int iData) -{ - if (iData < 0 || iData >= m_iNameExtensionsLength) - { - iData = 0; - } - //return super.getDescriptionId() + "." + nameExtensions[auxValue]; - return nameExtensions[iData]; +unsigned int MultiTextureTileItem::getDescriptionId(int iData) { + if (iData < 0 || iData >= m_iNameExtensionsLength) { + iData = 0; + } + // return super.getDescriptionId() + "." + nameExtensions[auxValue]; + return nameExtensions[iData]; } -unsigned int MultiTextureTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= m_iNameExtensionsLength) - { - auxValue = 0; - } - //return super.getDescriptionId() + "." + nameExtensions[auxValue]; - return nameExtensions[auxValue]; +unsigned int MultiTextureTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || auxValue >= m_iNameExtensionsLength) { + auxValue = 0; + } + // return super.getDescriptionId() + "." + nameExtensions[auxValue]; + return nameExtensions[auxValue]; } - diff --git a/Minecraft.World/Items/TileItems/MultiTextureTileItem.h b/Minecraft.World/Items/TileItems/MultiTextureTileItem.h index f2a4fdd35..13e271811 100644 --- a/Minecraft.World/Items/TileItems/MultiTextureTileItem.h +++ b/Minecraft.World/Items/TileItems/MultiTextureTileItem.h @@ -4,19 +4,20 @@ class Tile; -class MultiTextureTileItem : public TileItem -{ +class MultiTextureTileItem : public TileItem { private: - Tile *parentTile; - //private final String[] nameExtensions; - int *nameExtensions; - int m_iNameExtensionsLength; + Tile* parentTile; + // private final String[] nameExtensions; + int* nameExtensions; + int m_iNameExtensionsLength; public: - MultiTextureTileItem(int id, Tile *parentTile,int *nameExtensions, int iLength); + MultiTextureTileItem(int id, Tile* parentTile, int* nameExtensions, + int iLength); - virtual Icon *getIcon(int itemAuxValue); - virtual int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(int iData = -1); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual Icon* getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId(int iData = -1); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; diff --git a/Minecraft.World/Items/TileItems/PistonTileItem.cpp b/Minecraft.World/Items/TileItems/PistonTileItem.cpp index d343aef4e..1d3eae892 100644 --- a/Minecraft.World/Items/TileItems/PistonTileItem.cpp +++ b/Minecraft.World/Items/TileItems/PistonTileItem.cpp @@ -3,12 +3,9 @@ #include "../../Headers/net.minecraft.world.item.h" #include "PistonTileItem.h" -PistonTileItem::PistonTileItem(int id) : TileItem(id) -{ -} +PistonTileItem::PistonTileItem(int id) : TileItem(id) {} -int PistonTileItem::getLevelDataForAuxValue(int auxValue) -{ - // return an undefined facing until the setPlacedBy method is called - return PistonBaseTile::UNDEFINED_FACING; +int PistonTileItem::getLevelDataForAuxValue(int auxValue) { + // return an undefined facing until the setPlacedBy method is called + return PistonBaseTile::UNDEFINED_FACING; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/PistonTileItem.h b/Minecraft.World/Items/TileItems/PistonTileItem.h index cd289e897..948a537f5 100644 --- a/Minecraft.World/Items/TileItems/PistonTileItem.h +++ b/Minecraft.World/Items/TileItems/PistonTileItem.h @@ -1,12 +1,10 @@ #pragma once - #include "TileItem.h" -class PistonTileItem : public TileItem -{ +class PistonTileItem : public TileItem { public: - PistonTileItem(int id); + PistonTileItem(int id); - virtual int getLevelDataForAuxValue(int auxValue); + virtual int getLevelDataForAuxValue(int auxValue); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/PlanterTileItem.cpp b/Minecraft.World/Items/TileItems/PlanterTileItem.cpp index 56d2def02..a5454ae64 100644 --- a/Minecraft.World/Items/TileItems/PlanterTileItem.cpp +++ b/Minecraft.World/Items/TileItems/PlanterTileItem.cpp @@ -10,24 +10,22 @@ #include #include -TilePlanterItem::TilePlanterItem(int id, Tile *tile) : Item(id) -{ +TilePlanterItem::TilePlanterItem(int id, Tile* tile) : Item(id) { this->tileId = tile->id; } -bool TilePlanterItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - int currentTile = level->getTile(x, y, z); - if (currentTile == Tile::topSnow_Id) - { +bool TilePlanterItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + int currentTile = level->getTile(x, y, z); + if (currentTile == Tile::topSnow_Id) { face = Facing::UP; - } - else if (currentTile == Tile::vine_Id || currentTile == Tile::tallgrass_Id || currentTile == Tile::deadBush_Id) - { - } - else - { + } else if (currentTile == Tile::vine_Id || + currentTile == Tile::tallgrass_Id || + currentTile == Tile::deadBush_Id) { + } else { if (face == 0) y--; if (face == 1) y++; if (face == 2) z--; @@ -36,45 +34,48 @@ bool TilePlanterItem::useOn(std::shared_ptr instance, std::shared_ if (face == 5) x++; } - if (!player->mayBuild(x, y, z)) return false; + if (!player->mayBuild(x, y, z)) return false; if (instance->count == 0) return false; - if (level->mayPlace(tileId, x, y, z, false, face, nullptr)) - { - if(!bTestUseOnOnly) - { - Tile *tile = Tile::tiles[tileId]; - int dataValue = tile->getPlacedOnFaceDataValue(level, x, y, z, face, clickX, clickY, clickZ, 0); - if (level->setTileAndData(x, y, z, tileId, dataValue)) - { - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat(GenericStats::blocksPlaced(tileId),GenericStats::param_blocksPlaced(tileId,instance->getAuxValue(),1)); + if (level->mayPlace(tileId, x, y, z, false, face, nullptr)) { + if (!bTestUseOnOnly) { + Tile* tile = Tile::tiles[tileId]; + int dataValue = tile->getPlacedOnFaceDataValue( + level, x, y, z, face, clickX, clickY, clickZ, 0); + if (level->setTileAndData(x, y, z, tileId, dataValue)) { + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat(GenericStats::blocksPlaced(tileId), + GenericStats::param_blocksPlaced( + tileId, instance->getAuxValue(), 1)); - // 4J Original comment - // ok this may look stupid, but neighbor updates can cause the - // placed block to become something else before these methods - // are called - if (level->getTile(x, y, z) == tileId) - { - Tile::tiles[tileId]->setPlacedBy(level, x, y, z, player); - Tile::tiles[tileId]->finalizePlacement(level, x, y, z, dataValue); - } - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, tile->soundType->getStepSound(), (tile->soundType->getVolume() + 1) / 2, tile->soundType->getPitch() * 0.8f); - // 4J-PB - If we have the debug option on, don't reduce the number of this item - #ifndef _FINAL_BUILD - if(!(app.DebugSettingsOn() && app.GetGameSettingsDebugMask()&(1L<count--; - } - - } - } - } - else - { - // Can't place, so return false - if(bTestUseOnOnly) return false; - } + // 4J Original comment + // ok this may look stupid, but neighbor updates can cause the + // placed block to become something else before these methods + // are called + if (level->getTile(x, y, z) == tileId) { + Tile::tiles[tileId]->setPlacedBy(level, x, y, z, player); + Tile::tiles[tileId]->finalizePlacement(level, x, y, z, + dataValue); + } + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + tile->soundType->getStepSound(), + (tile->soundType->getVolume() + 1) / 2, + tile->soundType->getPitch() * 0.8f); + // 4J-PB - If we have the debug option on, don't reduce the + // number of this item +#ifndef _FINAL_BUILD + if (!(app.DebugSettingsOn() && + app.GetGameSettingsDebugMask() & + (1L << eDebugSetting_CraftAnything))) +#endif + { + instance->count--; + } + } + } + } else { + // Can't place, so return false + if (bTestUseOnOnly) return false; + } return true; } diff --git a/Minecraft.World/Items/TileItems/PlanterTileItem.h b/Minecraft.World/Items/TileItems/PlanterTileItem.h index 2b16b7373..35f157a2f 100644 --- a/Minecraft.World/Items/TileItems/PlanterTileItem.h +++ b/Minecraft.World/Items/TileItems/PlanterTileItem.h @@ -1,15 +1,16 @@ #pragma once - #include "../Item.h" -class TilePlanterItem : public Item -{ +class TilePlanterItem : public Item { private: - int tileId; + int tileId; public: - TilePlanterItem(int id, Tile *tile); + TilePlanterItem(int id, Tile* tile); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SaplingTileItem.cpp b/Minecraft.World/Items/TileItems/SaplingTileItem.cpp index f9bb4f522..86fda0381 100644 --- a/Minecraft.World/Items/TileItems/SaplingTileItem.cpp +++ b/Minecraft.World/Items/TileItems/SaplingTileItem.cpp @@ -3,29 +3,23 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "SaplingTileItem.h" -SaplingTileItem::SaplingTileItem(int id) : TileItem(id) -{ - setMaxDamage(0); - setStackedByData(true); +SaplingTileItem::SaplingTileItem(int id) : TileItem(id) { + setMaxDamage(0); + setStackedByData(true); } -int SaplingTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; -} +int SaplingTileItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } -Icon *SaplingTileItem::getIcon(int itemAuxValue) -{ - return Tile::sapling->getTexture(0, itemAuxValue); +Icon* SaplingTileItem::getIcon(int itemAuxValue) { + return Tile::sapling->getTexture(0, itemAuxValue); } // 4J brought forward to have unique names for different sapling types -unsigned int SaplingTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= Sapling::SAPLING_NAMES_SIZE) - { - auxValue = 0; - } - return Sapling::SAPLING_NAMES[auxValue]; +unsigned int SaplingTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || auxValue >= Sapling::SAPLING_NAMES_SIZE) { + auxValue = 0; + } + return Sapling::SAPLING_NAMES[auxValue]; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SaplingTileItem.h b/Minecraft.World/Items/TileItems/SaplingTileItem.h index 22546e816..117135cdb 100644 --- a/Minecraft.World/Items/TileItems/SaplingTileItem.h +++ b/Minecraft.World/Items/TileItems/SaplingTileItem.h @@ -1,16 +1,15 @@ #pragma once - #include "TileItem.h" -class SaplingTileItem : public TileItem -{ +class SaplingTileItem : public TileItem { public: - SaplingTileItem(int id); + SaplingTileItem(int id); - virtual int getLevelDataForAuxValue(int auxValue); - virtual Icon *getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); + virtual Icon* getIcon(int itemAuxValue); - // 4J brought forward to have unique names for different sapling types - virtual unsigned int getDescriptionId(std::shared_ptr instance); + // 4J brought forward to have unique names for different sapling types + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SkullItem.cpp b/Minecraft.World/Items/TileItems/SkullItem.cpp index a04dd209f..d092da5b6 100644 --- a/Minecraft.World/Items/TileItems/SkullItem.cpp +++ b/Minecraft.World/Items/TileItems/SkullItem.cpp @@ -7,119 +7,118 @@ #include "../../Headers/net.minecraft.world.h" #include "SkullItem.h" -const unsigned int SkullItem::NAMES[SKULL_COUNT] = {IDS_ITEM_SKULL_SKELETON, IDS_ITEM_SKULL_WITHER, IDS_ITEM_SKULL_ZOMBIE, IDS_ITEM_SKULL_CHARACTER, IDS_ITEM_SKULL_CREEPER}; +const unsigned int SkullItem::NAMES[SKULL_COUNT] = { + IDS_ITEM_SKULL_SKELETON, IDS_ITEM_SKULL_WITHER, IDS_ITEM_SKULL_ZOMBIE, + IDS_ITEM_SKULL_CHARACTER, IDS_ITEM_SKULL_CREEPER}; -std::wstring SkullItem::ICON_NAMES[SKULL_COUNT] = {L"skull_skeleton", L"skull_wither", L"skull_zombie", L"skull_char", L"skull_creeper"}; +std::wstring SkullItem::ICON_NAMES[SKULL_COUNT] = { + L"skull_skeleton", L"skull_wither", L"skull_zombie", L"skull_char", + L"skull_creeper"}; -SkullItem::SkullItem(int id) : Item(id) -{ - //setItemCategory(CreativeModeTab.TAB_DECORATIONS); - setMaxDamage(0); - setStackedByData(true); +SkullItem::SkullItem(int id) : Item(id) { + // setItemCategory(CreativeModeTab.TAB_DECORATIONS); + setMaxDamage(0); + setStackedByData(true); } -bool SkullItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) //float clickX, float clickY, float clickZ) +bool SkullItem::useOn( + std::shared_ptr instance, std::shared_ptr player, + Level* level, int x, int y, int z, int face, float clickX, float clickY, + float clickZ, + bool bTestUseOnOnly) // float clickX, float clickY, float clickZ) { - if (face == 0) return false; - if (!level->getMaterial(x, y, z)->isSolid()) return false; + if (face == 0) return false; + if (!level->getMaterial(x, y, z)->isSolid()) return false; - if (face == 1) y++; + if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - //if (!player->mayUseItemAt(x, y, z, face, instance)) return false; - if (!player->mayBuild(x, y, z)) return false; + // if (!player->mayUseItemAt(x, y, z, face, instance)) return false; + if (!player->mayBuild(x, y, z)) return false; - if (!Tile::skull->mayPlace(level, x, y, z)) return false; + if (!Tile::skull->mayPlace(level, x, y, z)) return false; - if(!bTestUseOnOnly) - { - level->setTileAndData(x, y, z, Tile::skull_Id, face) ;//, Tile.UPDATE_CLIENTS); + if (!bTestUseOnOnly) { + level->setTileAndData(x, y, z, Tile::skull_Id, + face); //, Tile.UPDATE_CLIENTS); - int rot = 0; - if (face == Facing::UP) - { - rot = Mth::floor(((player->yRot) * 16) / 360 + 0.5) & 15; - } + int rot = 0; + if (face == Facing::UP) { + rot = Mth::floor(((player->yRot) * 16) / 360 + 0.5) & 15; + } - std::shared_ptr skullTE = level->getTileEntity(x, y, z); - std::shared_ptr skull = std::dynamic_pointer_cast(skullTE); + std::shared_ptr skullTE = level->getTileEntity(x, y, z); + std::shared_ptr skull = + std::dynamic_pointer_cast(skullTE); - if (skull != NULL) - { - std::wstring extra = L""; - if (instance->hasTag() && instance->getTag()->contains(L"SkullOwner")) - { - extra = instance->getTag()->getString(L"SkullOwner"); - } - skull->setSkullType(instance->getAuxValue(), extra); - skull->setRotation(rot); - ((SkullTile *) Tile::skull)->checkMobSpawn(level, x, y, z, skull); - } + if (skull != NULL) { + std::wstring extra = L""; + if (instance->hasTag() && + instance->getTag()->contains(L"SkullOwner")) { + extra = instance->getTag()->getString(L"SkullOwner"); + } + skull->setSkullType(instance->getAuxValue(), extra); + skull->setRotation(rot); + ((SkullTile*)Tile::skull)->checkMobSpawn(level, x, y, z, skull); + } - instance->count--; - } - return true; + instance->count--; + } + return true; } -bool SkullItem::mayPlace(Level *level, int x, int y, int z, int face, std::shared_ptr player, std::shared_ptr item) -{ - int currentTile = level->getTile(x, y, z); - if (currentTile == Tile::topSnow_Id) - { - face = Facing::UP; - } - else if (currentTile != Tile::vine_Id && currentTile != Tile::tallgrass_Id && currentTile != Tile::deadBush_Id) - { - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - } +bool SkullItem::mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item) { + int currentTile = level->getTile(x, y, z); + if (currentTile == Tile::topSnow_Id) { + face = Facing::UP; + } else if (currentTile != Tile::vine_Id && + currentTile != Tile::tallgrass_Id && + currentTile != Tile::deadBush_Id) { + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; + } - return level->mayPlace(Tile::skull_Id, x, y, z, false, face, nullptr) ;//, item); + return level->mayPlace(Tile::skull_Id, x, y, z, false, face, + nullptr); //, item); } -Icon *SkullItem::getIcon(int itemAuxValue) -{ - if (itemAuxValue < 0 || itemAuxValue >= SKULL_COUNT) - { - itemAuxValue = 0; - } - return icons[itemAuxValue]; +Icon* SkullItem::getIcon(int itemAuxValue) { + if (itemAuxValue < 0 || itemAuxValue >= SKULL_COUNT) { + itemAuxValue = 0; + } + return icons[itemAuxValue]; } -int SkullItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int SkullItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } + +unsigned int SkullItem::getDescriptionId(int iData) { + if (iData < 0 || iData >= SKULL_COUNT) { + iData = 0; + } + return NAMES[iData]; } -unsigned int SkullItem::getDescriptionId(int iData) -{ - if (iData < 0 || iData >= SKULL_COUNT) - { - iData = 0; - } - return NAMES[iData]; +unsigned int SkullItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || auxValue >= SKULL_COUNT) { + auxValue = 0; + } + return NAMES[auxValue]; } -unsigned int SkullItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= SKULL_COUNT) - { - auxValue = 0; - } - return NAMES[auxValue]; -} - -std::wstring SkullItem::getHoverName(std::shared_ptr itemInstance) -{ +std::wstring SkullItem::getHoverName( + std::shared_ptr itemInstance) { #if 0 if (itemInstance->getAuxValue() == SkullTileEntity::TYPE_CHAR && itemInstance->hasTag() && itemInstance->getTag()->contains(L"SkullOwner")) { @@ -127,15 +126,13 @@ std::wstring SkullItem::getHoverName(std::shared_ptr itemInstance) } else #endif - { - return Item::getHoverName(itemInstance); - } + { + return Item::getHoverName(itemInstance); + } } -void SkullItem::registerIcons(IconRegister *iconRegister) -{ - for (int i = 0; i < SKULL_COUNT; i++) - { - icons[i] = iconRegister->registerIcon(ICON_NAMES[i]); - } +void SkullItem::registerIcons(IconRegister* iconRegister) { + for (int i = 0; i < SKULL_COUNT; i++) { + icons[i] = iconRegister->registerIcon(ICON_NAMES[i]); + } } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SkullItem.h b/Minecraft.World/Items/TileItems/SkullItem.h index 24d65472e..abc741a1c 100644 --- a/Minecraft.World/Items/TileItems/SkullItem.h +++ b/Minecraft.World/Items/TileItems/SkullItem.h @@ -2,28 +2,32 @@ #include "../Item.h" -class SkullItem : public Item -{ +class SkullItem : public Item { private: - static const int SKULL_COUNT = 5; + static const int SKULL_COUNT = 5; - static const unsigned int NAMES[SKULL_COUNT]; + static const unsigned int NAMES[SKULL_COUNT]; public: - static std::wstring ICON_NAMES[SKULL_COUNT]; + static std::wstring ICON_NAMES[SKULL_COUNT]; private: - Icon *icons[SKULL_COUNT]; + Icon* icons[SKULL_COUNT]; public: - SkullItem(int id); + SkullItem(int id); - bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - bool mayPlace(Level *level, int x, int y, int z, int face, std::shared_ptr player, std::shared_ptr item); - Icon *getIcon(int itemAuxValue); - int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(int iData = -1); - unsigned int getDescriptionId(std::shared_ptr instance); - std::wstring getHoverName(std::shared_ptr itemInstance); - void registerIcons(IconRegister *iconRegister); + bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly = false); + bool mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item); + Icon* getIcon(int itemAuxValue); + int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId(int iData = -1); + unsigned int getDescriptionId(std::shared_ptr instance); + std::wstring getHoverName(std::shared_ptr itemInstance); + void registerIcons(IconRegister* iconRegister); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.cpp b/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.cpp index cc279148f..295a447aa 100644 --- a/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.cpp +++ b/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.cpp @@ -3,30 +3,28 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "SmoothStoneBrickTileItem.h" -SmoothStoneBrickTileItem::SmoothStoneBrickTileItem(int id, Tile *parentTile) : TileItem(id) -{ - this->parentTile = parentTile; +SmoothStoneBrickTileItem::SmoothStoneBrickTileItem(int id, Tile* parentTile) + : TileItem(id) { + this->parentTile = parentTile; - setMaxDamage(0); - setStackedByData(true); + setMaxDamage(0); + setStackedByData(true); } -Icon *SmoothStoneBrickTileItem::getIcon(int itemAuxValue) -{ - return parentTile->getTexture(2, itemAuxValue); +Icon* SmoothStoneBrickTileItem::getIcon(int itemAuxValue) { + return parentTile->getTexture(2, itemAuxValue); } -int SmoothStoneBrickTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int SmoothStoneBrickTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue; } -unsigned int SmoothStoneBrickTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES_LENGTH) - { - auxValue = 0; - } - return SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES[auxValue]; +unsigned int SmoothStoneBrickTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || + auxValue >= SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES_LENGTH) { + auxValue = 0; + } + return SmoothStoneBrickTile::SMOOTH_STONE_BRICK_NAMES[auxValue]; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.h b/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.h index bad7a17b8..c5d989d7c 100644 --- a/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.h +++ b/Minecraft.World/Items/TileItems/SmoothStoneBrickTileItem.h @@ -1,17 +1,16 @@ #pragma once - #include "TileItem.h" -class SmoothStoneBrickTileItem : public TileItem -{ +class SmoothStoneBrickTileItem : public TileItem { private: - Tile *parentTile; + Tile* parentTile; public: - SmoothStoneBrickTileItem(int id, Tile *parentTile); + SmoothStoneBrickTileItem(int id, Tile* parentTile); - virtual Icon *getIcon(int itemAuxValue); - virtual int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual Icon* getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/StoneMonsterTileItem.cpp b/Minecraft.World/Items/TileItems/StoneMonsterTileItem.cpp index 3a178cf82..e44b16749 100644 --- a/Minecraft.World/Items/TileItems/StoneMonsterTileItem.cpp +++ b/Minecraft.World/Items/TileItems/StoneMonsterTileItem.cpp @@ -3,28 +3,25 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "StoneMonsterTileItem.h" -StoneMonsterTileItem::StoneMonsterTileItem(int id) : TileItem(id) -{ - setMaxDamage(0); - setStackedByData(true); +StoneMonsterTileItem::StoneMonsterTileItem(int id) : TileItem(id) { + setMaxDamage(0); + setStackedByData(true); } -int StoneMonsterTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int StoneMonsterTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue; } -Icon *StoneMonsterTileItem::getIcon(int itemAuxValue) -{ - return Tile::monsterStoneEgg->getTexture(0, itemAuxValue); +Icon* StoneMonsterTileItem::getIcon(int itemAuxValue) { + return Tile::monsterStoneEgg->getTexture(0, itemAuxValue); } -unsigned int StoneMonsterTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= StoneMonsterTile::STONE_MONSTER_NAMES_LENGTH) - { - auxValue = 0; - } - return StoneMonsterTile::STONE_MONSTER_NAMES[auxValue]; +unsigned int StoneMonsterTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || + auxValue >= StoneMonsterTile::STONE_MONSTER_NAMES_LENGTH) { + auxValue = 0; + } + return StoneMonsterTile::STONE_MONSTER_NAMES[auxValue]; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/StoneMonsterTileItem.h b/Minecraft.World/Items/TileItems/StoneMonsterTileItem.h index 75b5aea5e..3a2b755e6 100644 --- a/Minecraft.World/Items/TileItems/StoneMonsterTileItem.h +++ b/Minecraft.World/Items/TileItems/StoneMonsterTileItem.h @@ -1,16 +1,16 @@ #pragma once - #include "TileItem.h" -// 4J Stu - Class brought forward from 12w36 to fix stacking problem with silverfish stones +// 4J Stu - Class brought forward from 12w36 to fix stacking problem with +// silverfish stones -class StoneMonsterTileItem : public TileItem -{ +class StoneMonsterTileItem : public TileItem { public: - StoneMonsterTileItem(int id); + StoneMonsterTileItem(int id); - virtual int getLevelDataForAuxValue(int auxValue); - virtual Icon *getIcon(int itemAuxValue); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual int getLevelDataForAuxValue(int auxValue); + virtual Icon* getIcon(int itemAuxValue); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/StoneSlabTileItem.cpp b/Minecraft.World/Items/TileItems/StoneSlabTileItem.cpp index f011618a1..3e2eecbb5 100644 --- a/Minecraft.World/Items/TileItems/StoneSlabTileItem.cpp +++ b/Minecraft.World/Items/TileItems/StoneSlabTileItem.cpp @@ -7,134 +7,143 @@ #include "../../Headers/net.minecraft.h" #include "StoneSlabTileItem.h" -StoneSlabTileItem::StoneSlabTileItem(int id, HalfSlabTile *halfTile, HalfSlabTile *fullTile, bool full) : TileItem(id) -{ - this->halfTile = halfTile; - this->fullTile = fullTile; +StoneSlabTileItem::StoneSlabTileItem(int id, HalfSlabTile* halfTile, + HalfSlabTile* fullTile, bool full) + : TileItem(id) { + this->halfTile = halfTile; + this->fullTile = fullTile; - this->isFull = full; - setMaxDamage(0); - setStackedByData(true); + this->isFull = full; + setMaxDamage(0); + setStackedByData(true); } -Icon *StoneSlabTileItem::getIcon(int itemAuxValue) -{ - return Tile::tiles[id]->getTexture(2, itemAuxValue); +Icon* StoneSlabTileItem::getIcon(int itemAuxValue) { + return Tile::tiles[id]->getTexture(2, itemAuxValue); } -int StoneSlabTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; +int StoneSlabTileItem::getLevelDataForAuxValue(int auxValue) { + return auxValue; } -unsigned int StoneSlabTileItem::getDescriptionId(std::shared_ptr instance) -{ - return halfTile->getAuxName(instance->getAuxValue()); +unsigned int StoneSlabTileItem::getDescriptionId( + std::shared_ptr instance) { + return halfTile->getAuxName(instance->getAuxValue()); } -bool StoneSlabTileItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - if (isFull) - { - return TileItem::useOn(instance, player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); - } +bool StoneSlabTileItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, + int x, int y, int z, int face, float clickX, + float clickY, float clickZ, bool bTestUseOnOnly) { + if (isFull) { + return TileItem::useOn(instance, player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnOnly); + } - if (instance->count == 0) return false; - if (!player->mayBuild(x, y, z)) return false; + if (instance->count == 0) return false; + if (!player->mayBuild(x, y, z)) return false; - int currentTile = level->getTile(x, y, z); - int currentData = level->getData(x, y, z); - int slabType = currentData & HalfSlabTile::TYPE_MASK; - bool isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; + int currentTile = level->getTile(x, y, z); + int currentData = level->getData(x, y, z); + int slabType = currentData & HalfSlabTile::TYPE_MASK; + bool isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; - if (((face == Facing::UP && !isUpper) || (face == Facing::DOWN && isUpper)) && currentTile == halfTile->id && slabType == instance->getAuxValue()) - { - if(bTestUseOnOnly) - { - return true; - } + if (((face == Facing::UP && !isUpper) || + (face == Facing::DOWN && isUpper)) && + currentTile == halfTile->id && slabType == instance->getAuxValue()) { + if (bTestUseOnOnly) { + return true; + } - if (level->isUnobstructed(fullTile->getAABB(level, x, y, z)) && level->setTileAndData(x, y, z, fullTile->id, slabType)) - { -// level.playSound(x + 0.5f, y + 0.5f, z + 0.5f, fullTile.soundType.getPlaceSound(), (fullTile.soundType.getVolume() + 1) / 2, fullTile.soundType.getPitch() * 0.8f); -// instance.count--; - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, fullTile->soundType->getStepSound(), (fullTile->soundType->getVolume() + 1) / 2, fullTile->soundType->getPitch() * 0.8f); - instance->count--; - } - return true; - } - else if (tryConvertTargetTile(instance, player, level, x, y, z, face, bTestUseOnOnly)) - { - return true; - } - else - { - return TileItem::useOn(instance, player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); - } + if (level->isUnobstructed(fullTile->getAABB(level, x, y, z)) && + level->setTileAndData(x, y, z, fullTile->id, slabType)) { + // level.playSound(x + 0.5f, y + 0.5f, z + 0.5f, + // fullTile.soundType.getPlaceSound(), + // (fullTile.soundType.getVolume() + 1) / 2, + // fullTile.soundType.getPitch() * 0.8f); instance.count--; + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + fullTile->soundType->getStepSound(), + (fullTile->soundType->getVolume() + 1) / 2, + fullTile->soundType->getPitch() * 0.8f); + instance->count--; + } + return true; + } else if (tryConvertTargetTile(instance, player, level, x, y, z, face, + bTestUseOnOnly)) { + return true; + } else { + return TileItem::useOn(instance, player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnOnly); + } } +bool StoneSlabTileItem::mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item) { + int ox = x, oy = y, oz = z; -bool StoneSlabTileItem::mayPlace(Level *level, int x, int y, int z, int face,std::shared_ptr player, std::shared_ptr item) -{ - int ox = x, oy = y, oz = z; + int currentTile = level->getTile(x, y, z); + int currentData = level->getData(x, y, z); + int slabType = currentData & HalfSlabTile::TYPE_MASK; + boolean isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; - int currentTile = level->getTile(x, y, z); - int currentData = level->getData(x, y, z); - int slabType = currentData & HalfSlabTile::TYPE_MASK; - boolean isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; + if (((face == Facing::UP && !isUpper) || + (face == Facing::DOWN && isUpper)) && + currentTile == halfTile->id && slabType == item->getAuxValue()) { + return true; + } - if (((face == Facing::UP && !isUpper) || (face == Facing::DOWN && isUpper)) && currentTile == halfTile->id && slabType == item->getAuxValue()) - { - return true; - } + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; + currentTile = level->getTile(x, y, z); + currentData = level->getData(x, y, z); + slabType = currentData & HalfSlabTile::TYPE_MASK; + isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; - currentTile = level->getTile(x, y, z); - currentData = level->getData(x, y, z); - slabType = currentData & HalfSlabTile::TYPE_MASK; - isUpper = (currentData & HalfSlabTile::TOP_SLOT_BIT) != 0; + if (currentTile == halfTile->id && slabType == item->getAuxValue()) { + return true; + } - if (currentTile == halfTile->id && slabType == item->getAuxValue()) - { - return true; - } - - return TileItem::mayPlace(level, ox, oy, oz, face, player, item); + return TileItem::mayPlace(level, ox, oy, oz, face, player, item); } -bool StoneSlabTileItem::tryConvertTargetTile(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, bool bTestUseOnOnly) -{ - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; +bool StoneSlabTileItem::tryConvertTargetTile( + std::shared_ptr instance, std::shared_ptr player, + Level* level, int x, int y, int z, int face, bool bTestUseOnOnly) { + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - int currentTile = level->getTile(x, y, z); - int currentData = level->getData(x, y, z); - int slabType = currentData & HalfSlabTile::TYPE_MASK; + int currentTile = level->getTile(x, y, z); + int currentData = level->getData(x, y, z); + int slabType = currentData & HalfSlabTile::TYPE_MASK; - if (currentTile == halfTile->id && slabType == instance->getAuxValue()) - { - if(bTestUseOnOnly) - { - return true; - } - if (level->isUnobstructed(fullTile->getAABB(level, x, y, z)) && level->setTileAndData(x, y, z, fullTile->id, slabType)) - { - //level.playSound(x + 0.5f, y + 0.5f, z + 0.5f, fullTile.soundType.getPlaceSound(), (fullTile.soundType.getVolume() + 1) / 2, fullTile.soundType.getPitch() * 0.8f); - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, fullTile->soundType->getStepSound(), (fullTile->soundType->getVolume() + 1) / 2, fullTile->soundType->getPitch() * 0.8f); - instance->count--; - } - return true; - } + if (currentTile == halfTile->id && slabType == instance->getAuxValue()) { + if (bTestUseOnOnly) { + return true; + } + if (level->isUnobstructed(fullTile->getAABB(level, x, y, z)) && + level->setTileAndData(x, y, z, fullTile->id, slabType)) { + // level.playSound(x + 0.5f, y + 0.5f, z + 0.5f, + // fullTile.soundType.getPlaceSound(), + // (fullTile.soundType.getVolume() + 1) / 2, + // fullTile.soundType.getPitch() * 0.8f); + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + fullTile->soundType->getStepSound(), + (fullTile->soundType->getVolume() + 1) / 2, + fullTile->soundType->getPitch() * 0.8f); + instance->count--; + } + return true; + } - return false; + return false; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/StoneSlabTileItem.h b/Minecraft.World/Items/TileItems/StoneSlabTileItem.h index cb4f2370b..2de07147e 100644 --- a/Minecraft.World/Items/TileItems/StoneSlabTileItem.h +++ b/Minecraft.World/Items/TileItems/StoneSlabTileItem.h @@ -1,24 +1,34 @@ #pragma once - #include "TileItem.h" #include "../../Blocks/HalfSlabTile.h" -class StoneSlabTileItem : public TileItem -{ +class StoneSlabTileItem : public TileItem { private: - bool isFull; - HalfSlabTile *halfTile; - HalfSlabTile *fullTile; + bool isFull; + HalfSlabTile* halfTile; + HalfSlabTile* fullTile; + public: - StoneSlabTileItem(int id, HalfSlabTile *halfTile, HalfSlabTile *fullTile, bool full); + StoneSlabTileItem(int id, HalfSlabTile* halfTile, HalfSlabTile* fullTile, + bool full); - virtual Icon *getIcon(int itemAuxValue); - virtual int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(std::shared_ptr instance); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); + virtual Icon* getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + + virtual bool mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item); - virtual bool mayPlace(Level *level, int x, int y, int z, int face,std::shared_ptr player, std::shared_ptr item); private: - bool tryConvertTargetTile(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, bool bTestUseOnOnly); + bool tryConvertTargetTile(std::shared_ptr instance, + std::shared_ptr player, Level* level, + int x, int y, int z, int face, + bool bTestUseOnOnly); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/TileItem.cpp b/Minecraft.World/Items/TileItems/TileItem.cpp index 1220e6193..8e4481b6f 100644 --- a/Minecraft.World/Items/TileItems/TileItem.cpp +++ b/Minecraft.World/Items/TileItems/TileItem.cpp @@ -16,49 +16,39 @@ #include #include - -TileItem::TileItem(int id) : Item(id) -{ - this->tileId = id + 256; - itemIcon = NULL; +TileItem::TileItem(int id) : Item(id) { + this->tileId = id + 256; + itemIcon = NULL; } -int TileItem::getTileId() -{ - return tileId; +int TileItem::getTileId() { return tileId; } + +int TileItem::getIconType() { + if (!Tile::tiles[tileId]->getTileItemIconName().empty()) { + return Icon::TYPE_ITEM; + } + return Icon::TYPE_TERRAIN; } -int TileItem::getIconType() -{ - if (!Tile::tiles[tileId]->getTileItemIconName().empty()) - { - return Icon::TYPE_ITEM; - } - return Icon::TYPE_TERRAIN; +Icon* TileItem::getIcon(int auxValue) { + if (itemIcon != NULL) { + return itemIcon; + } + return Tile::tiles[tileId]->getTexture(Facing::UP, auxValue); } -Icon *TileItem::getIcon(int auxValue) -{ - if (itemIcon != NULL) - { - return itemIcon; - } - return Tile::tiles[tileId]->getTexture(Facing::UP, auxValue); -} - -bool TileItem::useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - int currentTile = level->getTile(x, y, z); - if (currentTile == Tile::topSnow_Id) - { +bool TileItem::useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, int y, + int z, int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + int currentTile = level->getTile(x, y, z); + if (currentTile == Tile::topSnow_Id) { face = Facing::UP; - } - else if (currentTile == Tile::vine_Id || currentTile == Tile::tallgrass_Id || currentTile == Tile::deadBush_Id) - { - } - else - { + } else if (currentTile == Tile::vine_Id || + currentTile == Tile::tallgrass_Id || + currentTile == Tile::deadBush_Id) { + } else { if (face == 0) y--; if (face == 1) y++; if (face == 2) z--; @@ -68,154 +58,167 @@ bool TileItem::useOn(std::shared_ptr instance, std::shared_ptrcount == 0) return false; - if (!player->mayBuild(x, y, z)) return false; + if (!player->mayBuild(x, y, z)) return false; + if (y == Level::maxBuildHeight - 1 && + Tile::tiles[tileId]->material->isSolid()) + return false; - if (y == Level::maxBuildHeight - 1 && Tile::tiles[tileId]->material->isSolid()) return false; + int undertile = + level->getTile(x, y - 1, z); // For 'BodyGuard' achievement. - int undertile = level->getTile(x,y-1,z); // For 'BodyGuard' achievement. - - if (level->mayPlace(tileId, x, y, z, false, face, player)) - { - if(!bTestUseOnOnly) - { - Tile *tile = Tile::tiles[tileId]; - // 4J - Adding this from 1.6 + if (level->mayPlace(tileId, x, y, z, false, face, player)) { + if (!bTestUseOnOnly) { + Tile* tile = Tile::tiles[tileId]; + // 4J - Adding this from 1.6 int itemValue = getLevelDataForAuxValue(instance->getAuxValue()); - int dataValue = Tile::tiles[tileId]->getPlacedOnFaceDataValue(level, x, y, z, face, clickX, clickY, clickZ, itemValue); - if (level->setTileAndData(x, y, z, tileId, dataValue)) - { - // 4J-JEV: Snow/Iron Golems do not have owners apparently. - int newTileId = level->getTile(x,y,z); - if ( (tileId == Tile::pumpkin_Id || tileId == Tile::litPumpkin_Id) && newTileId == 0 ) - { - eINSTANCEOF golemType; - switch (undertile) - { - case Tile::ironBlock_Id: golemType = eTYPE_VILLAGERGOLEM; break; - case Tile::snow_Id: golemType = eTYPE_SNOWMAN; break; - default: golemType = eTYPE_NOTSET; break; - } + int dataValue = Tile::tiles[tileId]->getPlacedOnFaceDataValue( + level, x, y, z, face, clickX, clickY, clickZ, itemValue); + if (level->setTileAndData(x, y, z, tileId, dataValue)) { + // 4J-JEV: Snow/Iron Golems do not have owners apparently. + int newTileId = level->getTile(x, y, z); + if ((tileId == Tile::pumpkin_Id || + tileId == Tile::litPumpkin_Id) && + newTileId == 0) { + eINSTANCEOF golemType; + switch (undertile) { + case Tile::ironBlock_Id: + golemType = eTYPE_VILLAGERGOLEM; + break; + case Tile::snow_Id: + golemType = eTYPE_SNOWMAN; + break; + default: + golemType = eTYPE_NOTSET; + break; + } - if (golemType != eTYPE_NOTSET) - { - player->awardStat(GenericStats::craftedEntity(golemType),GenericStats::param_craftedEntity(golemType)); - } - } + if (golemType != eTYPE_NOTSET) { + player->awardStat( + GenericStats::craftedEntity(golemType), + GenericStats::param_craftedEntity(golemType)); + } + } - // 4J-JEV: Hook for durango 'BlockPlaced' event. - player->awardStat(GenericStats::blocksPlaced(tileId),GenericStats::param_blocksPlaced(tileId,instance->getAuxValue(),1)); + // 4J-JEV: Hook for durango 'BlockPlaced' event. + player->awardStat(GenericStats::blocksPlaced(tileId), + GenericStats::param_blocksPlaced( + tileId, instance->getAuxValue(), 1)); - // 4J - Original comment - // ok this may look stupid, but neighbor updates can cause the + // 4J - Original comment + // ok this may look stupid, but neighbor updates can cause the // placed block to become something else before these methods // are called - if (level->getTile(x, y, z) == tileId) - { - Tile::tiles[tileId]->setPlacedBy(level, x, y, z, player); - Tile::tiles[tileId]->finalizePlacement(level, x, y, z, dataValue); - } - - // 4J-PB - Java 1.4 change - getStepSound replaced with getPlaceSound - //level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, tile->soundType->getStepSound(), (tile->soundType->getVolume() + 1) / 2, tile->soundType->getPitch() * 0.8f); + if (level->getTile(x, y, z) == tileId) { + Tile::tiles[tileId]->setPlacedBy(level, x, y, z, player); + Tile::tiles[tileId]->finalizePlacement(level, x, y, z, + dataValue); + } + + // 4J-PB - Java 1.4 change - getStepSound replaced with + // getPlaceSound + // level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + // tile->soundType->getStepSound(), + // (tile->soundType->getVolume() + 1) / 2, + // tile->soundType->getPitch() * 0.8f); #ifdef _DEBUG - int iPlaceSound=tile->soundType->getPlaceSound(); - int iStepSound=tile->soundType->getStepSound(); + int iPlaceSound = tile->soundType->getPlaceSound(); + int iStepSound = tile->soundType->getStepSound(); -// char szPlaceSoundName[256]; -// char szStepSoundName[256]; -// Minecraft *pMinecraft = Minecraft::GetInstance(); -// -// if(iPlaceSound==-1) -// { -// strcpy(szPlaceSoundName,"NULL"); -// } -// else -// { -// pMinecraft->soundEngine->GetSoundName(szPlaceSoundName,iPlaceSound); -// } -// if(iStepSound==-1) -// { -// strcpy(szStepSoundName,"NULL"); -// } -// else -// { -// pMinecraft->soundEngine->GetSoundName(szStepSoundName,iStepSound); -// } + // char szPlaceSoundName[256]; + // char szStepSoundName[256]; + // Minecraft *pMinecraft = + // Minecraft::GetInstance(); + // + // if(iPlaceSound==-1) + // { + // strcpy(szPlaceSoundName,"NULL"); + // } + // else + // { + // pMinecraft->soundEngine->GetSoundName(szPlaceSoundName,iPlaceSound); + // } + // if(iStepSound==-1) + // { + // strcpy(szStepSoundName,"NULL"); + // } + // else + // { + // pMinecraft->soundEngine->GetSoundName(szStepSoundName,iStepSound); + // } - //app.DebugPrintf("Place Sound - %s, Step Sound - %s\n",szPlaceSoundName,szStepSoundName); - app.DebugPrintf("Place Sound - %d, Step Sound - %d\n",iPlaceSound,iStepSound); + // app.DebugPrintf("Place Sound - %s, Step Sound - + // %s\n",szPlaceSoundName,szStepSoundName); + app.DebugPrintf("Place Sound - %d, Step Sound - %d\n", + iPlaceSound, iStepSound); #endif - level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, tile->soundType->getPlaceSound(), (tile->soundType->getVolume() + 1) / 2, tile->soundType->getPitch() * 0.8f); + level->playSound(x + 0.5f, y + 0.5f, z + 0.5f, + tile->soundType->getPlaceSound(), + (tile->soundType->getVolume() + 1) / 2, + tile->soundType->getPitch() * 0.8f); #ifndef _FINAL_BUILD - // 4J-PB - If we have the debug option on, don't reduce the number of this item - if(!(app.DebugSettingsOn() && app.GetGameSettingsDebugMask()&(1L<count--; - } - } - } + { + instance->count--; + } + } + } return true; } return false; } +bool TileItem::mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item) { + int currentTile = level->getTile(x, y, z); + if (currentTile == Tile::topSnow_Id) { + face = Facing::UP; + } else if (currentTile != Tile::vine_Id && + currentTile != Tile::tallgrass_Id && + currentTile != Tile::deadBush_Id) { + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; + } -bool TileItem::mayPlace(Level *level, int x, int y, int z, int face, std::shared_ptr player, std::shared_ptr item) -{ - int currentTile = level->getTile(x, y, z); - if (currentTile == Tile::topSnow_Id) - { - face = Facing::UP; - } - else if (currentTile != Tile::vine_Id && currentTile != Tile::tallgrass_Id && currentTile != Tile::deadBush_Id) - { - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - } - - return level->mayPlace(getTileId(), x, y, z, false, face, nullptr); + return level->mayPlace(getTileId(), x, y, z, false, face, nullptr); } // 4J Added to colourise some tile types in the hint popups -int TileItem::getColor(int itemAuxValue, int spriteLayer) -{ - return Tile::tiles[tileId]->getColor(); +int TileItem::getColor(int itemAuxValue, int spriteLayer) { + return Tile::tiles[tileId]->getColor(); } -unsigned int TileItem::getDescriptionId(std::shared_ptr instance) -{ +unsigned int TileItem::getDescriptionId( + std::shared_ptr instance) { return Tile::tiles[tileId]->getDescriptionId(); } - -unsigned int TileItem::getDescriptionId(int iData /*= -1*/) -{ - return Tile::tiles[tileId]->getDescriptionId(iData); +unsigned int TileItem::getDescriptionId(int iData /*= -1*/) { + return Tile::tiles[tileId]->getDescriptionId(iData); } - -unsigned int TileItem::getUseDescriptionId(std::shared_ptr instance) -{ +unsigned int TileItem::getUseDescriptionId( + std::shared_ptr instance) { return Tile::tiles[tileId]->getUseDescriptionId(); } - -unsigned int TileItem::getUseDescriptionId() -{ - return Tile::tiles[tileId]->getUseDescriptionId(); +unsigned int TileItem::getUseDescriptionId() { + return Tile::tiles[tileId]->getUseDescriptionId(); } -void TileItem::registerIcons(IconRegister *iconRegister) -{ - std::wstring iconName = Tile::tiles[tileId]->getTileItemIconName(); - if (!iconName.empty()) - { - itemIcon = iconRegister->registerIcon(iconName); - } +void TileItem::registerIcons(IconRegister* iconRegister) { + std::wstring iconName = Tile::tiles[tileId]->getTileItemIconName(); + if (!iconName.empty()) { + itemIcon = iconRegister->registerIcon(iconName); + } } diff --git a/Minecraft.World/Items/TileItems/TileItem.h b/Minecraft.World/Items/TileItems/TileItem.h index ac835c94f..8688f2c08 100644 --- a/Minecraft.World/Items/TileItems/TileItem.h +++ b/Minecraft.World/Items/TileItems/TileItem.h @@ -1,44 +1,50 @@ #pragma once - #include "../Item.h" class Player; class Level; -class TileItem : public Item -{ -public: static const int _class = 0; -using Item::getColor; +class TileItem : public Item { +public: + static const int _class = 0; + using Item::getColor; -private: - int tileId; - Icon *itemIcon; +private: + int tileId; + Icon* itemIcon; public: - TileItem(int id); - - virtual int getTileId(); + TileItem(int id); - //@Override - int getIconType(); + virtual int getTileId(); - //@Override - Icon *getIcon(int auxValue); + //@Override + int getIconType(); - virtual bool useOn(std::shared_ptr instance, std::shared_ptr player, Level *level, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false); - virtual unsigned int getDescriptionId(std::shared_ptr instance); - virtual unsigned int getDescriptionId(int iData = -1); + //@Override + Icon* getIcon(int auxValue); - // 4J Added - virtual int getColor(int itemAuxValue, int spriteLayer); + virtual bool useOn(std::shared_ptr instance, + std::shared_ptr player, Level* level, int x, + int y, int z, int face, float clickX, float clickY, + float clickZ, bool bTestUseOnOnly = false); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); + virtual unsigned int getDescriptionId(int iData = -1); - // 4J Added - virtual unsigned int getUseDescriptionId(std::shared_ptr instance); - virtual unsigned int getUseDescriptionId(); + // 4J Added + virtual int getColor(int itemAuxValue, int spriteLayer); - virtual bool mayPlace(Level *level, int x, int y, int z, int face, std::shared_ptr player, std::shared_ptr item); + // 4J Added + virtual unsigned int getUseDescriptionId( + std::shared_ptr instance); + virtual unsigned int getUseDescriptionId(); - //@Override - virtual void registerIcons(IconRegister *iconRegister); + virtual bool mayPlace(Level* level, int x, int y, int z, int face, + std::shared_ptr player, + std::shared_ptr item); + + //@Override + virtual void registerIcons(IconRegister* iconRegister); }; diff --git a/Minecraft.World/Items/TileItems/TreeTileItem.cpp b/Minecraft.World/Items/TileItems/TreeTileItem.cpp index 12de84cc9..29e403e08 100644 --- a/Minecraft.World/Items/TileItems/TreeTileItem.cpp +++ b/Minecraft.World/Items/TileItems/TreeTileItem.cpp @@ -2,30 +2,24 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "TreeTileItem.h" -TreeTileItem::TreeTileItem(int id, Tile *parentTile) : TileItem(id) -{ - this->parentTile = parentTile; +TreeTileItem::TreeTileItem(int id, Tile* parentTile) : TileItem(id) { + this->parentTile = parentTile; - setMaxDamage(0); - setStackedByData(true); + setMaxDamage(0); + setStackedByData(true); } -Icon *TreeTileItem::getIcon(int itemAuxValue) -{ - return parentTile->getTexture(2, itemAuxValue); +Icon* TreeTileItem::getIcon(int itemAuxValue) { + return parentTile->getTexture(2, itemAuxValue); } -int TreeTileItem::getLevelDataForAuxValue(int auxValue) -{ - return auxValue; -} +int TreeTileItem::getLevelDataForAuxValue(int auxValue) { return auxValue; } -unsigned int TreeTileItem::getDescriptionId(std::shared_ptr instance) -{ - int auxValue = instance->getAuxValue(); - if (auxValue < 0 || auxValue >= TreeTile::TREE_NAMES_LENGTH) - { - auxValue = 0; - } - return TreeTile::TREE_NAMES[auxValue]; +unsigned int TreeTileItem::getDescriptionId( + std::shared_ptr instance) { + int auxValue = instance->getAuxValue(); + if (auxValue < 0 || auxValue >= TreeTile::TREE_NAMES_LENGTH) { + auxValue = 0; + } + return TreeTile::TREE_NAMES[auxValue]; } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/TreeTileItem.h b/Minecraft.World/Items/TileItems/TreeTileItem.h index 0fcf9ff12..6ecbc6995 100644 --- a/Minecraft.World/Items/TileItems/TreeTileItem.h +++ b/Minecraft.World/Items/TileItems/TreeTileItem.h @@ -1,18 +1,17 @@ #pragma once - #include "TileItem.h" -class TreeTileItem : public TileItem -{ +class TreeTileItem : public TileItem { private: - Tile *parentTile; + Tile* parentTile; public: - TreeTileItem(int id, Tile *parentTile); + TreeTileItem(int id, Tile* parentTile); - virtual Icon *getIcon(int itemAuxValue); - virtual int getLevelDataForAuxValue(int auxValue); + virtual Icon* getIcon(int itemAuxValue); + virtual int getLevelDataForAuxValue(int auxValue); - virtual unsigned int getDescriptionId(std::shared_ptr instance); + virtual unsigned int getDescriptionId( + std::shared_ptr instance); }; \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/WaterLilyTileItem.cpp b/Minecraft.World/Items/TileItems/WaterLilyTileItem.cpp index 3103a66fc..3e5134b2f 100644 --- a/Minecraft.World/Items/TileItems/WaterLilyTileItem.cpp +++ b/Minecraft.World/Items/TileItems/WaterLilyTileItem.cpp @@ -6,73 +6,63 @@ #include "../../Headers/net.minecraft.world.entity.player.h" #include "WaterLilyTileItem.h" -WaterLilyTileItem::WaterLilyTileItem(int id) : ColoredTileItem(id, false) -{ +WaterLilyTileItem::WaterLilyTileItem(int id) : ColoredTileItem(id, false) {} + +bool WaterLilyTileItem::TestUse(Level* level, std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, true); + if (hr == NULL) return false; + + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; + delete hr; + if (!level->mayInteract(player, xt, yt, zt, 0)) { + return false; + } + if (!player->mayBuild(xt, yt, zt)) return false; + + if (level->getMaterial(xt, yt, zt) == Material::water && + level->getData(xt, yt, zt) == 0 && + level->isEmptyTile(xt, yt + 1, zt)) { + return true; + } + } else { + delete hr; + } + return false; } -bool WaterLilyTileItem::TestUse(Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, true); - if (hr == NULL) return false; +std::shared_ptr WaterLilyTileItem::use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + HitResult* hr = getPlayerPOVHitResult(level, player, true); + if (hr == NULL) return itemInstance; - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; - delete hr; - if (!level->mayInteract(player, xt, yt, zt, 0)) - { - return false; - } - if (!player->mayBuild(xt, yt, zt)) return false; + if (hr->type == HitResult::TILE) { + int xt = hr->x; + int yt = hr->y; + int zt = hr->z; + delete hr; + if (!level->mayInteract(player, xt, yt, zt, 0)) { + return itemInstance; + } + if (!player->mayBuild(xt, yt, zt)) return itemInstance; - if (level->getMaterial(xt, yt, zt) == Material::water && level->getData(xt, yt, zt) == 0 && level->isEmptyTile(xt, yt + 1, zt)) - { - return true; - } - } - else - { - delete hr; - } - return false; + if (level->getMaterial(xt, yt, zt) == Material::water && + level->getData(xt, yt, zt) == 0 && + level->isEmptyTile(xt, yt + 1, zt)) { + level->setTile(xt, yt + 1, zt, Tile::waterLily->id); + if (!player->abilities.instabuild) { + itemInstance->count--; + } + } + } else { + delete hr; + } + return itemInstance; } -std::shared_ptr WaterLilyTileItem::use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - HitResult *hr = getPlayerPOVHitResult(level, player, true); - if (hr == NULL) return itemInstance; - - if (hr->type == HitResult::TILE) - { - int xt = hr->x; - int yt = hr->y; - int zt = hr->z; - delete hr; - if (!level->mayInteract(player, xt, yt, zt, 0)) - { - return itemInstance; - } - if (!player->mayBuild(xt, yt, zt)) return itemInstance; - - if (level->getMaterial(xt, yt, zt) == Material::water && level->getData(xt, yt, zt) == 0 && level->isEmptyTile(xt, yt + 1, zt)) - { - level->setTile(xt, yt + 1, zt, Tile::waterLily->id); - if (!player->abilities.instabuild) - { - itemInstance->count--; - } - } - } - else - { - delete hr; - } - return itemInstance; -} - -int WaterLilyTileItem::getColor(int data, int spriteLayer) -{ - return Tile::waterLily->getColor(data); +int WaterLilyTileItem::getColor(int data, int spriteLayer) { + return Tile::waterLily->getColor(data); } \ No newline at end of file diff --git a/Minecraft.World/Items/TileItems/WaterLilyTileItem.h b/Minecraft.World/Items/TileItems/WaterLilyTileItem.h index 3fc233142..8a8db8b80 100644 --- a/Minecraft.World/Items/TileItems/WaterLilyTileItem.h +++ b/Minecraft.World/Items/TileItems/WaterLilyTileItem.h @@ -2,13 +2,14 @@ #include "ColoredTileItem.h" -class WaterLilyTileItem : public ColoredTileItem -{ +class WaterLilyTileItem : public ColoredTileItem { public: - using ColoredTileItem::getColor; - WaterLilyTileItem(int id); + using ColoredTileItem::getColor; + WaterLilyTileItem(int id); - virtual std::shared_ptr use(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); - virtual bool TestUse(Level *level, std::shared_ptr player); - virtual int getColor(int data, int spriteLayer); + virtual std::shared_ptr use( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player); + virtual bool TestUse(Level* level, std::shared_ptr player); + virtual int getColor(int data, int spriteLayer); }; diff --git a/Minecraft.World/Items/WeaponItem.cpp b/Minecraft.World/Items/WeaponItem.cpp index 2f1f51872..3d54e8f14 100644 --- a/Minecraft.World/Items/WeaponItem.cpp +++ b/Minecraft.World/Items/WeaponItem.cpp @@ -5,83 +5,72 @@ #include "../Headers/net.minecraft.world.level.tile.h" #include "WeaponItem.h" -WeaponItem::WeaponItem(int id, const Tier *tier) : Item(id), tier( tier ) -{ +WeaponItem::WeaponItem(int id, const Tier* tier) : Item(id), tier(tier) { maxStackSize = 1; setMaxDamage(tier->getUses()); damage = 4 + tier->getAttackDamageBonus(); } -float WeaponItem::getDestroySpeed(std::shared_ptr itemInstance, Tile *tile) -{ - if (tile->id == Tile::web_Id) - { +float WeaponItem::getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile) { + if (tile->id == Tile::web_Id) { // swords can quickly cut web return 15; } return 1.5f; } -bool WeaponItem::hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker) -{ - itemInstance->hurt(1, attacker); +bool WeaponItem::hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker) { + itemInstance->hurt(1, attacker); return true; } -bool WeaponItem::mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner) -{ - // Don't damage weapons if the tile can be destroyed in one hit. - if (Tile::tiles[tile]->getDestroySpeed(level, x, y, z) != 0.0) itemInstance->hurt(2, owner); - return true; +bool WeaponItem::mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner) { + // Don't damage weapons if the tile can be destroyed in one hit. + if (Tile::tiles[tile]->getDestroySpeed(level, x, y, z) != 0.0) + itemInstance->hurt(2, owner); + return true; } -int WeaponItem::getAttackDamage(std::shared_ptr entity) -{ +int WeaponItem::getAttackDamage(std::shared_ptr entity) { return damage; } -bool WeaponItem::isHandEquipped() -{ - return true; +bool WeaponItem::isHandEquipped() { return true; } + +UseAnim WeaponItem::getUseAnimation( + std::shared_ptr itemInstance) { + return UseAnim_block; } -UseAnim WeaponItem::getUseAnimation(std::shared_ptr itemInstance) -{ - return UseAnim_block; -} - -int WeaponItem::getUseDuration(std::shared_ptr itemInstance) -{ - return 20 * 60 * 60; // Block for a maximum of one hour! +int WeaponItem::getUseDuration(std::shared_ptr itemInstance) { + return 20 * 60 * 60; // Block for a maximum of one hour! } -std::shared_ptr WeaponItem::use(std::shared_ptr instance, Level *level, std::shared_ptr player) -{ - player->startUsingItem(instance, getUseDuration(instance)); - return instance; +std::shared_ptr WeaponItem::use( + std::shared_ptr instance, Level* level, + std::shared_ptr player) { + player->startUsingItem(instance, getUseDuration(instance)); + return instance; } -bool WeaponItem::canDestroySpecial(Tile *tile) -{ +bool WeaponItem::canDestroySpecial(Tile* tile) { return tile->id == Tile::web_Id; } -int WeaponItem::getEnchantmentValue() -{ - return tier->getEnchantmentValue(); -} +int WeaponItem::getEnchantmentValue() { return tier->getEnchantmentValue(); } -const Item::Tier *WeaponItem::getTier() -{ - return tier; -} +const Item::Tier* WeaponItem::getTier() { return tier; } -bool WeaponItem::isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem) -{ - if (tier->getTierItemId() == repairItem->id) - { - return true; - } - return Item::isValidRepairItem(source, repairItem); +bool WeaponItem::isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem) { + if (tier->getTierItemId() == repairItem->id) { + return true; + } + return Item::isValidRepairItem(source, repairItem); } \ No newline at end of file diff --git a/Minecraft.World/Items/WeaponItem.h b/Minecraft.World/Items/WeaponItem.h index 92d5473c5..d2ecda71a 100644 --- a/Minecraft.World/Items/WeaponItem.h +++ b/Minecraft.World/Items/WeaponItem.h @@ -1,28 +1,34 @@ #pragma once - #include "Item.h" -class WeaponItem : public Item -{ +class WeaponItem : public Item { private: - int damage; - const Tier *tier; + int damage; + const Tier* tier; public: - WeaponItem(int id, const Tier *tier); + WeaponItem(int id, const Tier* tier); - virtual float getDestroySpeed(std::shared_ptr itemInstance, Tile *tile); - virtual bool hurtEnemy(std::shared_ptr itemInstance, std::shared_ptr mob, std::shared_ptr attacker); - virtual bool mineBlock(std::shared_ptr itemInstance, Level *level, int tile, int x, int y, int z, std::shared_ptr owner); - virtual int getAttackDamage(std::shared_ptr entity); - virtual bool isHandEquipped(); - virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); - virtual int getUseDuration(std::shared_ptr itemInstance); - virtual std::shared_ptr use(std::shared_ptr instance, Level *level, std::shared_ptr player); - virtual bool canDestroySpecial(Tile *tile); - virtual int getEnchantmentValue(); + virtual float getDestroySpeed(std::shared_ptr itemInstance, + Tile* tile); + virtual bool hurtEnemy(std::shared_ptr itemInstance, + std::shared_ptr mob, + std::shared_ptr attacker); + virtual bool mineBlock(std::shared_ptr itemInstance, + Level* level, int tile, int x, int y, int z, + std::shared_ptr owner); + virtual int getAttackDamage(std::shared_ptr entity); + virtual bool isHandEquipped(); + virtual UseAnim getUseAnimation(std::shared_ptr itemInstance); + virtual int getUseDuration(std::shared_ptr itemInstance); + virtual std::shared_ptr use( + std::shared_ptr instance, Level* level, + std::shared_ptr player); + virtual bool canDestroySpecial(Tile* tile); + virtual int getEnchantmentValue(); - const Tier *getTier(); - bool isValidRepairItem(std::shared_ptr source, std::shared_ptr repairItem); + const Tier* getTier(); + bool isValidRepairItem(std::shared_ptr source, + std::shared_ptr repairItem); }; \ No newline at end of file diff --git a/Minecraft.World/Level/BlockDestructionProgress.cpp b/Minecraft.World/Level/BlockDestructionProgress.cpp index 7e320558e..c56a4de29 100644 --- a/Minecraft.World/Level/BlockDestructionProgress.cpp +++ b/Minecraft.World/Level/BlockDestructionProgress.cpp @@ -1,57 +1,38 @@ #include "../Platform/stdafx.h" #include "BlockDestructionProgress.h" -BlockDestructionProgress::BlockDestructionProgress(int id, int x, int y, int z) -{ - this->id = id; - this->x = x; - this->y = y; - this->z = z; +BlockDestructionProgress::BlockDestructionProgress(int id, int x, int y, + int z) { + this->id = id; + this->x = x; + this->y = y; + this->z = z; - progress = 0; - updatedRenderTick = 0; + progress = 0; + updatedRenderTick = 0; } -int BlockDestructionProgress::getId() -{ - return id; +int BlockDestructionProgress::getId() { return id; } + +int BlockDestructionProgress::getX() { return x; } + +int BlockDestructionProgress::getY() { return y; } + +int BlockDestructionProgress::getZ() { return z; } + +void BlockDestructionProgress::setProgress(int progress) { + if (progress > 10) { + progress = 10; + } + this->progress = progress; } -int BlockDestructionProgress::getX() -{ - return x; +int BlockDestructionProgress::getProgress() { return progress; } + +void BlockDestructionProgress::updateTick(int tick) { + this->updatedRenderTick = tick; } -int BlockDestructionProgress::getY() -{ - return y; -} - -int BlockDestructionProgress::getZ() -{ - return z; -} - -void BlockDestructionProgress::setProgress(int progress) -{ - if (progress > 10) - { - progress = 10; - } - this->progress = progress; -} - -int BlockDestructionProgress::getProgress() -{ - return progress; -} - -void BlockDestructionProgress::updateTick(int tick) -{ - this->updatedRenderTick = tick; -} - -int BlockDestructionProgress::getUpdatedRenderTick() -{ - return updatedRenderTick; +int BlockDestructionProgress::getUpdatedRenderTick() { + return updatedRenderTick; } \ No newline at end of file diff --git a/Minecraft.World/Level/BlockDestructionProgress.h b/Minecraft.World/Level/BlockDestructionProgress.h index 4c599e83d..21411b2e4 100644 --- a/Minecraft.World/Level/BlockDestructionProgress.h +++ b/Minecraft.World/Level/BlockDestructionProgress.h @@ -1,24 +1,23 @@ #pragma once -class BlockDestructionProgress -{ +class BlockDestructionProgress { private: - int id; - int x; - int y; - int z; - int progress; - int updatedRenderTick; + int id; + int x; + int y; + int z; + int progress; + int updatedRenderTick; public: - BlockDestructionProgress(int id, int x, int y, int z); + BlockDestructionProgress(int id, int x, int y, int z); - int getId(); - int getX(); - int getY(); - int getZ(); - void setProgress(int progress); - int getProgress(); - void updateTick(int tick); - int getUpdatedRenderTick(); + int getId(); + int getX(); + int getY(); + int getZ(); + void setProgress(int progress); + int getProgress(); + void updateTick(int tick); + int getUpdatedRenderTick(); }; \ No newline at end of file diff --git a/Minecraft.World/Level/BlockGenMethods.cpp b/Minecraft.World/Level/BlockGenMethods.cpp index e5799f50a..4c47ecdfe 100644 --- a/Minecraft.World/Level/BlockGenMethods.cpp +++ b/Minecraft.World/Level/BlockGenMethods.cpp @@ -3,222 +3,187 @@ #include "../Headers/net.minecraft.world.level.h" #include "BlockGenMethods.h" -void BlockGenMethods::generateBox(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, std::uint8_t edge, std::uint8_t filling) -{ +void BlockGenMethods::generateBox(Level* level, byteArray blocks, int sx, + int sy, int sz, int ex, int ey, int ez, + std::uint8_t edge, std::uint8_t filling) { + sx = Mth::clamp(sx, 0, 15); + sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); + sz = Mth::clamp(sz, 0, 15); + ex = Mth::clamp(ex, 0, 15); + ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); + ez = Mth::clamp(ez, 0, 15); - sx = Mth::clamp(sx, 0, 15); - sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); - sz = Mth::clamp(sz, 0, 15); - ex = Mth::clamp(ex, 0, 15); - ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); - ez = Mth::clamp(ez, 0, 15); + for (int x = sx; x <= ex; x++) { + for (int y = sy; y <= ey; y++) { + for (int z = sz; z <= ez; z++) { + int p = (x * 16 + z) * Level::genDepth + y; - for (int x = sx; x <= ex; x++) - { - for (int y = sy; y <= ey; y++) - { - for (int z = sz; z <= ez; z++) - { - int p = (x * 16 + z) * Level::genDepth + y; - - if (x == sx || x == ex || y == sy || y == ey || z == sz || z == ez) - { - blocks[p] = edge; - } - else - { - blocks[p] = filling; - } - } - } - } + if (x == sx || x == ex || y == sy || y == ey || z == sz || + z == ez) { + blocks[p] = edge; + } else { + blocks[p] = filling; + } + } + } + } } -void BlockGenMethods::generateFrame(Level *level, byteArray blocks, int sx, int sy, int ex, int ey, int flatZ, int direction, std::uint8_t edge, std::uint8_t filling) -{ +void BlockGenMethods::generateFrame(Level* level, byteArray blocks, int sx, + int sy, int ex, int ey, int flatZ, + int direction, std::uint8_t edge, + std::uint8_t filling) { + sx = Mth::clamp(sx, 0, 15); + sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); + ex = Mth::clamp(ex, 0, 15); + ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); + int sz = Mth::clamp(flatZ, 0, 15); + int ez = sz; - sx = Mth::clamp(sx, 0, 15); - sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); - ex = Mth::clamp(ex, 0, 15); - ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); - int sz = Mth::clamp(flatZ, 0, 15); - int ez = sz; + bool alongX = true; - bool alongX = true; + switch (direction) { + case Direction::WEST: { + // rotate counter-clockwise + int temp = sz; + sz = 15 - ex; + ez = 15 - sx; + sx = ex = temp; + alongX = false; + } break; + case Direction::EAST: { + // rotate clockwise + int temp = sz; + sz = sx; + ez = ex; + sx = ex = 15 - temp; + alongX = false; + } break; + case Direction::SOUTH: { + // rotate 180 + sz = ez = 15 - sz; + int temp = sx; + sx = 15 - ex; + ex = 15 - temp; + } break; + } - switch (direction) - { - case Direction::WEST: - { - // rotate counter-clockwise - int temp = sz; - sz = 15 - ex; - ez = 15 - sx; - sx = ex = temp; - alongX = false; - } - break; - case Direction::EAST: - { - // rotate clockwise - int temp = sz; - sz = sx; - ez = ex; - sx = ex = 15 - temp; - alongX = false; - } - break; - case Direction::SOUTH: - { - // rotate 180 - sz = ez = 15 - sz; - int temp = sx; - sx = 15 - ex; - ex = 15 - temp; - } - break; - } + for (int x = sx; x <= ex; x++) { + for (int y = sy; y <= ey; y++) { + for (int z = sz; z <= ez; z++) { + int p = (x * 16 + z) * Level::genDepth + y; - for (int x = sx; x <= ex; x++) - { - for (int y = sy; y <= ey; y++) - { - for (int z = sz; z <= ez; z++) - { - int p = (x * 16 + z) * Level::genDepth + y; - - if (y == sy || y == ey || (alongX && (x == sx || x == ex)) || (!alongX && (z == sz || z == ez))) - { - blocks[p] = edge; - } - else - { - blocks[p] = filling; - } - } - } - } + if (y == sy || y == ey || (alongX && (x == sx || x == ex)) || + (!alongX && (z == sz || z == ez))) { + blocks[p] = edge; + } else { + blocks[p] = filling; + } + } + } + } } -void BlockGenMethods::generateDirectionLine(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, int startDirection, int endDirection, std::uint8_t block) -{ +void BlockGenMethods::generateDirectionLine(Level* level, byteArray blocks, + int sx, int sy, int sz, int ex, + int ey, int ez, int startDirection, + int endDirection, + std::uint8_t block) { + sx = Mth::clamp(sx, 0, 15); + sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); + sz = Mth::clamp(sz, 0, 15); + ex = Mth::clamp(ex, 0, 15); + ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); + ez = Mth::clamp(ez, 0, 15); - sx = Mth::clamp(sx, 0, 15); - sy = Mth::clamp(sy, 0, Level::genDepthMinusOne); - sz = Mth::clamp(sz, 0, 15); - ex = Mth::clamp(ex, 0, 15); - ey = Mth::clamp(ey, 0, Level::genDepthMinusOne); - ez = Mth::clamp(ez, 0, 15); + switch (startDirection) { + case Direction::WEST: { + // rotate counter-clockwise + int temp = sz; + sz = 15 - sx; + sx = temp; + } break; + case Direction::EAST: { + // rotate clockwise + int temp = sz; + sz = sx; + sx = 15 - temp; + } break; + case Direction::SOUTH: { + // rotate 180 + sz = 15 - sz; + sx = 15 - sx; + } break; + } - switch (startDirection) - { - case Direction::WEST: - { - // rotate counter-clockwise - int temp = sz; - sz = 15 - sx; - sx = temp; - } - break; - case Direction::EAST: - { - // rotate clockwise - int temp = sz; - sz = sx; - sx = 15 - temp; - } - break; - case Direction::SOUTH: - { - // rotate 180 - sz = 15 - sz; - sx = 15 - sx; - } - break; - } + switch (endDirection) { + case Direction::WEST: { + // rotate counter-clockwise + int temp = ez; + ez = 15 - ex; + ex = temp; + } break; + case Direction::EAST: { + // rotate clockwise + int temp = ez; + ez = ex; + ex = 15 - temp; + } break; + case Direction::SOUTH: { + // rotate 180 + ez = 15 - ez; + ex = 15 - ex; + } break; + } - switch (endDirection) - { - case Direction::WEST: - { - // rotate counter-clockwise - int temp = ez; - ez = 15 - ex; - ex = temp; - } - break; - case Direction::EAST: - { - // rotate clockwise - int temp = ez; - ez = ex; - ex = 15 - temp; - } - break; - case Direction::SOUTH: - { - // rotate 180 - ez = 15 - ez; - ex = 15 - ex; - } - break; - } + int dx = Mth::abs(ex - sx); + int dz = Mth::abs(ez - sz); + int dy = Mth::abs(ey - sy); - int dx = Mth::abs(ex - sx); - int dz = Mth::abs(ez - sz); - int dy = Mth::abs(ey - sy); + int slopeX = sx < ex ? 1 : -1; + int slopeZ = sz < ez ? 1 : -1; + int slopeY = sy < ey ? 1 : -1; - int slopeX = sx < ex ? 1 : -1; - int slopeZ = sz < ez ? 1 : -1; - int slopeY = sy < ey ? 1 : -1; + int err = dx - dz; + int yOppositeDelta = (dz > dx) ? dz : dx; + int yErr = dy - yOppositeDelta; + bool doYMovement = true; - int err = dx - dz; - int yOppositeDelta = (dz > dx) ? dz : dx; - int yErr = dy - yOppositeDelta; - bool doYMovement = true; + while (true) { + blocks[(sx * 16 + sz) * Level::genDepth + sy] = block; - while (true) - { - blocks[(sx * 16 + sz) * Level::genDepth + sy] = block; + if (sx == ex && sz == ez) { + break; + } + if (sy == ey) { + doYMovement = false; + } + int e2 = 2 * err; + if (e2 > -dz) { + err = err - dz; + sx = sx + slopeX; + } + if (e2 < dx) { + err = err + dx; + sz = sz + slopeZ; + } - if (sx == ex && sz == ez) - { - break; - } - if (sy == ey) - { - doYMovement = false; - } - int e2 = 2 * err; - if (e2 > -dz) - { - err = err - dz; - sx = sx + slopeX; - } - if (e2 < dx) - { - err = err + dx; - sz = sz + slopeZ; - } - - if (doYMovement) - { - e2 = 2 * yErr; - if (e2 > -yOppositeDelta) - { - yErr = yErr - yOppositeDelta; - sy = sy + slopeY; - } - if (e2 < dy) - { - yErr = yErr + dy; - // don't modify sz here, let the plane decide - } - } - } + if (doYMovement) { + e2 = 2 * yErr; + if (e2 > -yOppositeDelta) { + yErr = yErr - yOppositeDelta; + sy = sy + slopeY; + } + if (e2 < dy) { + yErr = yErr + dy; + // don't modify sz here, let the plane decide + } + } + } } -void BlockGenMethods::generateLine(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, std::uint8_t block) -{ - generateDirectionLine(level, blocks, sx, sy, sz, ex, ey, ez, 0, 0, block); +void BlockGenMethods::generateLine(Level* level, byteArray blocks, int sx, + int sy, int sz, int ex, int ey, int ez, + std::uint8_t block) { + generateDirectionLine(level, blocks, sx, sy, sz, ex, ey, ez, 0, 0, block); } diff --git a/Minecraft.World/Level/BlockGenMethods.h b/Minecraft.World/Level/BlockGenMethods.h index f0e6027c6..5d84207b8 100644 --- a/Minecraft.World/Level/BlockGenMethods.h +++ b/Minecraft.World/Level/BlockGenMethods.h @@ -3,11 +3,19 @@ #include "../Util/ArrayWithLength.h" -class BlockGenMethods -{ +class BlockGenMethods { public: - static void generateBox(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, std::uint8_t edge, std::uint8_t filling); - static void generateFrame(Level *level, byteArray blocks, int sx, int sy, int ex, int ey, int flatZ, int direction, std::uint8_t edge, std::uint8_t filling); - static void generateDirectionLine(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, int startDirection, int endDirection, std::uint8_t block); - static void generateLine(Level *level, byteArray blocks, int sx, int sy, int sz, int ex, int ey, int ez, std::uint8_t block); + static void generateBox(Level* level, byteArray blocks, int sx, int sy, + int sz, int ex, int ey, int ez, std::uint8_t edge, + std::uint8_t filling); + static void generateFrame(Level* level, byteArray blocks, int sx, int sy, + int ex, int ey, int flatZ, int direction, + std::uint8_t edge, std::uint8_t filling); + static void generateDirectionLine(Level* level, byteArray blocks, int sx, + int sy, int sz, int ex, int ey, int ez, + int startDirection, int endDirection, + std::uint8_t block); + static void generateLine(Level* level, byteArray blocks, int sx, int sy, + int sz, int ex, int ey, int ez, + std::uint8_t block); }; diff --git a/Minecraft.World/Level/BlockReplacements.cpp b/Minecraft.World/Level/BlockReplacements.cpp index e47d8ee86..1dd785ece 100644 --- a/Minecraft.World/Level/BlockReplacements.cpp +++ b/Minecraft.World/Level/BlockReplacements.cpp @@ -4,23 +4,18 @@ byteArray BlockReplacements::replacements = byteArray(256); -void BlockReplacements::staticCtor() -{ - for (int i = 0; i < 256; i++) - { - uint8_t b = (uint8_t) i; - if (b != 0 && Tile::tiles[b & 0xff] == NULL) - { +void BlockReplacements::staticCtor() { + for (int i = 0; i < 256; i++) { + uint8_t b = (uint8_t)i; + if (b != 0 && Tile::tiles[b & 0xff] == NULL) { b = 0; } BlockReplacements::replacements[i] = b; } } -void BlockReplacements::replace(byteArray blocks) -{ - for (unsigned int i = 0; i < blocks.length; i++) - { +void BlockReplacements::replace(byteArray blocks) { + for (unsigned int i = 0; i < blocks.length; i++) { blocks[i] = replacements[blocks[i] & 0xff]; } } \ No newline at end of file diff --git a/Minecraft.World/Level/BlockReplacements.h b/Minecraft.World/Level/BlockReplacements.h index c87015207..20fadd63f 100644 --- a/Minecraft.World/Level/BlockReplacements.h +++ b/Minecraft.World/Level/BlockReplacements.h @@ -1,9 +1,8 @@ #pragma once -class BlockReplacements -{ +class BlockReplacements { public: - static void staticCtor(); + static void staticCtor(); private: static byteArray replacements; diff --git a/Minecraft.World/Level/ChunkPos.cpp b/Minecraft.World/Level/ChunkPos.cpp index 56925e3ba..e527b6a12 100644 --- a/Minecraft.World/Level/ChunkPos.cpp +++ b/Minecraft.World/Level/ChunkPos.cpp @@ -2,74 +2,55 @@ #include "../Headers/net.minecraft.world.entity.h" #include "ChunkPos.h" -ChunkPos::ChunkPos(int x, int z) : x( x ), z( z ) -{ +ChunkPos::ChunkPos(int x, int z) : x(x), z(z) {} + +__int64 ChunkPos::hashCode(int x, int z) { + __int64 xx = x; + __int64 zz = z; + return (xx & 0xffffffffl) | ((zz & 0xffffffffl) << 32l); } -__int64 ChunkPos::hashCode(int x, int z) -{ - __int64 xx = x; - __int64 zz = z; - return (xx & 0xffffffffl) | ((zz & 0xffffffffl) << 32l); +int ChunkPos::hashCode() { + __int64 hash = hashCode(x, z); + int h1 = (int)(hash); + int h2 = (int)(hash >> 32l); + return h1 ^ h2; } -int ChunkPos::hashCode() -{ - __int64 hash = hashCode(x, z); - int h1 = (int) (hash); - int h2 = (int) (hash >> 32l); - return h1 ^ h2; +double ChunkPos::distanceToSqr(std::shared_ptr e) { + double xPos = x * 16 + 8; + double zPos = z * 16 + 8; + + double xd = xPos - e->x; + double zd = zPos - e->z; + + return xd * xd + zd * zd; } -double ChunkPos::distanceToSqr(std::shared_ptr e) -{ - double xPos = x * 16 + 8; - double zPos = z * 16 + 8; +double ChunkPos::distanceToSqr(double px, double pz) { + double xPos = x * 16 + 8; + double zPos = z * 16 + 8; - double xd = xPos - e->x; - double zd = zPos - e->z; + double xd = xPos - px; + double zd = zPos - pz; - return xd * xd + zd * zd; + return xd * xd + zd * zd; } -double ChunkPos::distanceToSqr(double px, double pz) -{ - double xPos = x * 16 + 8; - double zPos = z * 16 + 8; +int ChunkPos::getMiddleBlockX() { return (x << 4) + 8; } - double xd = xPos - px; - double zd = zPos - pz; +int ChunkPos::getMiddleBlockZ() { return (z << 4) + 8; } - return xd * xd + zd * zd; +TilePos ChunkPos::getMiddleBlockPosition(int y) { + return TilePos(getMiddleBlockX(), y, getMiddleBlockZ()); } -int ChunkPos::getMiddleBlockX() -{ - return ( x << 4 ) + 8; -} - -int ChunkPos::getMiddleBlockZ() -{ - return ( z << 4 ) + 8; -} - -TilePos ChunkPos::getMiddleBlockPosition(int y) -{ - return TilePos(getMiddleBlockX(), y, getMiddleBlockZ()); -} - -std::wstring ChunkPos::toString() -{ +std::wstring ChunkPos::toString() { return L"[" + _toString(x) + L", " + _toString(z) + L"]"; } -__int64 ChunkPos::hash_fnct(const ChunkPos &k) -{ - return k.hashCode(k.x,k.z); -} +__int64 ChunkPos::hash_fnct(const ChunkPos& k) { return k.hashCode(k.x, k.z); } -bool ChunkPos::eq_test(const ChunkPos &x, const ChunkPos &y) -{ - return x.x == y.x && x.z == y.z; +bool ChunkPos::eq_test(const ChunkPos& x, const ChunkPos& y) { + return x.x == y.x && x.z == y.z; } - diff --git a/Minecraft.World/Level/ChunkPos.h b/Minecraft.World/Level/ChunkPos.h index d5adaa20b..cfdae48f5 100644 --- a/Minecraft.World/Level/ChunkPos.h +++ b/Minecraft.World/Level/ChunkPos.h @@ -3,37 +3,45 @@ class Entity; class TilePos; -class ChunkPos -{ +class ChunkPos { public: - int x, z; // 4J - these were const but needed to make an assignment operator so we could make a vector of ChunkPos + int x, z; // 4J - these were const but needed to make an assignment + // operator so we could make a vector of ChunkPos - ChunkPos(int x, int z); + ChunkPos(int x, int z); - static __int64 hashCode(int x, int z); - int hashCode(); + static __int64 hashCode(int x, int z); + int hashCode(); - double distanceToSqr(std::shared_ptr e); - double distanceToSqr(double px, double pz); // 4J added + double distanceToSqr(std::shared_ptr e); + double distanceToSqr(double px, double pz); // 4J added - int getMiddleBlockX(); - int getMiddleBlockZ(); + int getMiddleBlockX(); + int getMiddleBlockZ(); - TilePos getMiddleBlockPosition(int y); - std::wstring toString(); + TilePos getMiddleBlockPosition(int y); + std::wstring toString(); - static __int64 hash_fnct(const ChunkPos &k); - static bool eq_test(const ChunkPos &x, const ChunkPos &y); - bool operator == (const ChunkPos &k) const { return (this->x == k.x) && ( this->z == k.z); } - ChunkPos & operator= (const ChunkPos & other) { x = other.x; z = other.z; return *this; } + static __int64 hash_fnct(const ChunkPos& k); + static bool eq_test(const ChunkPos& x, const ChunkPos& y); + bool operator==(const ChunkPos& k) const { + return (this->x == k.x) && (this->z == k.z); + } + ChunkPos& operator=(const ChunkPos& other) { + x = other.x; + z = other.z; + return *this; + } }; -struct ChunkPosKeyHash -{ - __int64 operator() (const ChunkPos &k) const { return ChunkPos::hash_fnct(k); } +struct ChunkPosKeyHash { + __int64 operator()(const ChunkPos& k) const { + return ChunkPos::hash_fnct(k); + } }; -struct ChunkPosKeyEq -{ - bool operator() (const ChunkPos &x, const ChunkPos &y) const { return ChunkPos::eq_test(x, y); } +struct ChunkPosKeyEq { + bool operator()(const ChunkPos& x, const ChunkPos& y) const { + return ChunkPos::eq_test(x, y); + } }; \ No newline at end of file diff --git a/Minecraft.World/Level/ChunkSource.h b/Minecraft.World/Level/ChunkSource.h index c9c5e97f9..42f5b25db 100644 --- a/Minecraft.World/Level/ChunkSource.h +++ b/Minecraft.World/Level/ChunkSource.h @@ -7,7 +7,7 @@ class TilePos; // The maximum number of chunks that we can store #ifdef _LARGE_WORLDS // 4J Stu - Our default map (at zoom level 3) is 1024x1024 blocks (or 64 chunks) -#define LEVEL_MAX_WIDTH (5*64) //(6*54) +#define LEVEL_MAX_WIDTH (5 * 64) //(6*54) #else #define LEVEL_MAX_WIDTH 54 #endif @@ -15,7 +15,8 @@ class TilePos; #define LEVEL_LEGACY_WIDTH 54 // Scale was 8 in the Java game, but that would make our nether tiny -// Every 1 block you move in the nether maps to HELL_LEVEL_SCALE blocks in the overworld +// Every 1 block you move in the nether maps to HELL_LEVEL_SCALE blocks in the +// overworld #ifdef _LARGE_WORLDS #define HELL_LEVEL_MAX_SCALE 8 #else @@ -32,36 +33,40 @@ class TilePos; // 54 / 3 = 18 #define END_LEVEL_MAX_WIDTH 18 #define END_LEVEL_MIN_WIDTH 18 -//#define END_LEVEL_MAX_WIDTH (LEVEL_MAX_WIDTH / END_LEVEL_SCALE) +// #define END_LEVEL_MAX_WIDTH (LEVEL_MAX_WIDTH / END_LEVEL_SCALE) -class ChunkSource -{ +class ChunkSource { public: - // 4J Added so that we can store the maximum dimensions of this world - int m_XZSize; + // 4J Added so that we can store the maximum dimensions of this world + int m_XZSize; public: - virtual ~ChunkSource() {} + virtual ~ChunkSource() {} virtual bool hasChunk(int x, int y) = 0; - virtual bool reallyHasChunk(int x, int y) { return hasChunk(x,y); } // 4J added - virtual LevelChunk *getChunk(int x, int z) = 0; - virtual void lightChunk(LevelChunk *lc) {} // 4J added - virtual LevelChunk *create(int x, int z) = 0; - virtual void postProcess(ChunkSource *parent, int x, int z) = 0; - virtual bool saveAllEntities() { return false; } // 4J Added - virtual bool save(bool force, ProgressListener *progressListener) = 0; + virtual bool reallyHasChunk(int x, int y) { + return hasChunk(x, y); + } // 4J added + virtual LevelChunk* getChunk(int x, int z) = 0; + virtual void lightChunk(LevelChunk* lc) {} // 4J added + virtual LevelChunk* create(int x, int z) = 0; + virtual void postProcess(ChunkSource* parent, int x, int z) = 0; + virtual bool saveAllEntities() { return false; } // 4J Added + virtual bool save(bool force, ProgressListener* progressListener) = 0; virtual bool tick() = 0; virtual bool shouldSave() = 0; - virtual LevelChunk **getCache() { return NULL; } // 4J added - virtual void dataReceived(int x, int z) {} // 4J added + virtual LevelChunk** getCache() { return NULL; } // 4J added + virtual void dataReceived(int x, int z) {} // 4J added /** * Returns some stats that are rendered when the user holds F3. */ virtual std::wstring gatherStats() = 0; - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z) = 0; - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) = 0; + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z) = 0; + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z) = 0; }; diff --git a/Minecraft.World/Level/CustomLevelSource.cpp b/Minecraft.World/Level/CustomLevelSource.cpp index e9e029ff7..428dd7a6a 100644 --- a/Minecraft.World/Level/CustomLevelSource.cpp +++ b/Minecraft.World/Level/CustomLevelSource.cpp @@ -13,471 +13,495 @@ const double CustomLevelSource::SNOW_SCALE = 0.3; const double CustomLevelSource::SNOW_CUTOFF = 0.5; -CustomLevelSource::CustomLevelSource(Level *level, __int64 seed, bool generateStructures) : generateStructures( generateStructures ) -{ +CustomLevelSource::CustomLevelSource(Level* level, __int64 seed, + bool generateStructures) + : generateStructures(generateStructures) { #ifdef _OVERRIDE_HEIGHTMAP - m_XZSize = level->getLevelData()->getXZSize(); + m_XZSize = level->getLevelData()->getXZSize(); - m_heightmapOverride = byteArray( (m_XZSize*16) * (m_XZSize*16) ); + m_heightmapOverride = byteArray((m_XZSize * 16) * (m_XZSize * 16)); #ifdef _WINDOWS64 - const std::wstring path = L"GameRules\\heightmap.bin"; + const std::wstring path = L"GameRules\\heightmap.bin"; #else - const std::wstring path = L"GAME:\\GameRules\\heightmap.bin"; + const std::wstring path = L"GAME:\\GameRules\\heightmap.bin"; #endif - const PortableFileIO::BinaryReadResult heightmapReadResult = PortableFileIO::ReadBinaryFile(path, m_heightmapOverride.data, m_heightmapOverride.length); - if(heightmapReadResult.status == PortableFileIO::BinaryReadStatus::not_found) - { - app.FatalLoadError(); - assert(false); - } - else if(heightmapReadResult.status == PortableFileIO::BinaryReadStatus::too_large) - { - app.DebugPrintf("Heightmap binary is too large!!\n"); - __debugbreak(); - } - else if(heightmapReadResult.status != PortableFileIO::BinaryReadStatus::ok) - { - app.FatalLoadError(); - } + const PortableFileIO::BinaryReadResult heightmapReadResult = + PortableFileIO::ReadBinaryFile(path, m_heightmapOverride.data, + m_heightmapOverride.length); + if (heightmapReadResult.status == + PortableFileIO::BinaryReadStatus::not_found) { + app.FatalLoadError(); + assert(false); + } else if (heightmapReadResult.status == + PortableFileIO::BinaryReadStatus::too_large) { + app.DebugPrintf("Heightmap binary is too large!!\n"); + __debugbreak(); + } else if (heightmapReadResult.status != + PortableFileIO::BinaryReadStatus::ok) { + app.FatalLoadError(); + } - m_waterheightOverride = byteArray( (m_XZSize*16) * (m_XZSize*16) ); + m_waterheightOverride = byteArray((m_XZSize * 16) * (m_XZSize * 16)); #ifdef _WINDOWS64 - const std::wstring waterHeightPath = L"GameRules\\waterheight.bin"; + const std::wstring waterHeightPath = L"GameRules\\waterheight.bin"; #else - const std::wstring waterHeightPath = L"GAME:\\GameRules\\waterheight.bin"; + const std::wstring waterHeightPath = L"GAME:\\GameRules\\waterheight.bin"; #endif - const PortableFileIO::BinaryReadResult waterHeightReadResult = PortableFileIO::ReadBinaryFile(waterHeightPath, m_waterheightOverride.data, m_waterheightOverride.length); - if(waterHeightReadResult.status == PortableFileIO::BinaryReadStatus::not_found) - { - memset(m_waterheightOverride.data, level->seaLevel, m_waterheightOverride.length); - } - else if(waterHeightReadResult.status == PortableFileIO::BinaryReadStatus::too_large) - { - app.DebugPrintf("waterheight binary is too large!!\n"); - __debugbreak(); - } - else if(waterHeightReadResult.status != PortableFileIO::BinaryReadStatus::ok) - { - app.FatalLoadError(); - } + const PortableFileIO::BinaryReadResult waterHeightReadResult = + PortableFileIO::ReadBinaryFile(waterHeightPath, + m_waterheightOverride.data, + m_waterheightOverride.length); + if (waterHeightReadResult.status == + PortableFileIO::BinaryReadStatus::not_found) { + memset(m_waterheightOverride.data, level->seaLevel, + m_waterheightOverride.length); + } else if (waterHeightReadResult.status == + PortableFileIO::BinaryReadStatus::too_large) { + app.DebugPrintf("waterheight binary is too large!!\n"); + __debugbreak(); + } else if (waterHeightReadResult.status != + PortableFileIO::BinaryReadStatus::ok) { + app.FatalLoadError(); + } - caveFeature = new LargeCaveFeature(); - strongholdFeature = new StrongholdFeature(); - villageFeature = new VillageFeature(0,m_XZSize); - mineShaftFeature = new MineShaftFeature(); - canyonFeature = new CanyonFeature(); + caveFeature = new LargeCaveFeature(); + strongholdFeature = new StrongholdFeature(); + villageFeature = new VillageFeature(0, m_XZSize); + mineShaftFeature = new MineShaftFeature(); + canyonFeature = new CanyonFeature(); - this->level = level; + this->level = level; - random = new Random(seed); - pprandom = new Random(seed); // 4J - added, so that we can have a separate random for doing post-processing in parallel with creation + random = new Random(seed); + pprandom = new Random( + seed); // 4J - added, so that we can have a separate random for doing + // post-processing in parallel with creation perlinNoise3 = new PerlinNoise(random, 4); #endif } -CustomLevelSource::~CustomLevelSource() -{ +CustomLevelSource::~CustomLevelSource() { #ifdef _OVERRIDE_HEIGHTMAP - delete caveFeature; - delete strongholdFeature; - delete villageFeature; - delete mineShaftFeature; - delete canyonFeature; + delete caveFeature; + delete strongholdFeature; + delete villageFeature; + delete mineShaftFeature; + delete canyonFeature; - delete random; + delete random; delete perlinNoise3; #endif } -void CustomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) -{ +void CustomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) { #ifdef _OVERRIDE_HEIGHTMAP - int xChunks = 16 / CHUNK_WIDTH; - int yChunks = Level::maxBuildHeight / CHUNK_HEIGHT; - int waterHeight = level->seaLevel; + int xChunks = 16 / CHUNK_WIDTH; + int yChunks = Level::maxBuildHeight / CHUNK_HEIGHT; + int waterHeight = level->seaLevel; - int xSize = xChunks + 1; - int ySize = Level::maxBuildHeight / CHUNK_HEIGHT + 1; - int zSize = xChunks + 1; + int xSize = xChunks + 1; + int ySize = Level::maxBuildHeight / CHUNK_HEIGHT + 1; + int zSize = xChunks + 1; - int xMapStart = xOffs + m_XZSize/2; - int zMapStart = zOffs + m_XZSize/2; - for (int xc = 0; xc < xChunks; xc++) - { - for (int zc = 0; zc < xChunks; zc++) - { - for (int yc = 0; yc < yChunks; yc++) - { - for (int y = 0; y < CHUNK_HEIGHT; y++) - { - for (int x = 0; x < CHUNK_WIDTH; x++) - { - for (int z = 0; z < CHUNK_WIDTH; z++) - { - int mapIndex = (zMapStart * 16 + z + ( zc * CHUNK_WIDTH )) * (m_XZSize * 16) + (xMapStart * 16 + x + ( xc * CHUNK_WIDTH )); - int mapHeight = m_heightmapOverride[mapIndex]; - waterHeight = m_waterheightOverride[mapIndex]; - //app.DebugPrintf("MapHeight = %d, y = %d\n", mapHeight, yc * CHUNK_HEIGHT + y); - /////////////////////////////////////////////////////////////////// - // 4J - add this chunk of code to make land "fall-off" at the edges of - // a finite world - size of that world is currently hard-coded in here - const int worldSize = m_XZSize * 16; - const int falloffStart = 32; // chunks away from edge were we start doing fall-off - const float falloffMax = 128.0f; // max value we need to get to falloff by the edge of the map + int xMapStart = xOffs + m_XZSize / 2; + int zMapStart = zOffs + m_XZSize / 2; + for (int xc = 0; xc < xChunks; xc++) { + for (int zc = 0; zc < xChunks; zc++) { + for (int yc = 0; yc < yChunks; yc++) { + for (int y = 0; y < CHUNK_HEIGHT; y++) { + for (int x = 0; x < CHUNK_WIDTH; x++) { + for (int z = 0; z < CHUNK_WIDTH; z++) { + int mapIndex = + (zMapStart * 16 + z + (zc * CHUNK_WIDTH)) * + (m_XZSize * 16) + + (xMapStart * 16 + x + (xc * CHUNK_WIDTH)); + int mapHeight = m_heightmapOverride[mapIndex]; + waterHeight = m_waterheightOverride[mapIndex]; + // app.DebugPrintf("MapHeight = %d, y = %d\n", + // mapHeight, yc * CHUNK_HEIGHT + y); + /////////////////////////////////////////////////////////////////// + // 4J - add this chunk of code to make land + // "fall-off" at the edges of a finite world - size + // of that world is currently hard-coded in here + const int worldSize = m_XZSize * 16; + const int falloffStart = + 32; // chunks away from edge were we start + // doing fall-off + const float falloffMax = + 128.0f; // max value we need to get to falloff + // by the edge of the map - int xxx = ( ( xOffs * 16 ) + x + ( xc * CHUNK_WIDTH ) ); - int zzz = ( ( zOffs * 16 ) + z + ( zc * CHUNK_WIDTH ) ); + int xxx = ((xOffs * 16) + x + (xc * CHUNK_WIDTH)); + int zzz = ((zOffs * 16) + z + (zc * CHUNK_WIDTH)); - // Get distance to edges of world in x - int xxx0 = xxx + ( worldSize / 2 ); - if( xxx0 < 0 ) xxx0 = 0; - int xxx1 = ( ( worldSize / 2 ) - 1 ) - xxx; - if( xxx1 < 0 ) xxx1 = 0; + // Get distance to edges of world in x + int xxx0 = xxx + (worldSize / 2); + if (xxx0 < 0) xxx0 = 0; + int xxx1 = ((worldSize / 2) - 1) - xxx; + if (xxx1 < 0) xxx1 = 0; - // Get distance to edges of world in z - int zzz0 = zzz + ( worldSize / 2 ); - if( zzz0 < 0 ) zzz0 = 0; - int zzz1 = ( ( worldSize / 2 ) - 1 ) - zzz; - if( zzz1 < 0 ) zzz1 = 0; + // Get distance to edges of world in z + int zzz0 = zzz + (worldSize / 2); + if (zzz0 < 0) zzz0 = 0; + int zzz1 = ((worldSize / 2) - 1) - zzz; + if (zzz1 < 0) zzz1 = 0; - // Get min distance to any edge - int emin = xxx0; - if (xxx1 < emin ) emin = xxx1; - if (zzz0 < emin ) emin = zzz0; - if (zzz1 < emin ) emin = zzz1; + // Get min distance to any edge + int emin = xxx0; + if (xxx1 < emin) emin = xxx1; + if (zzz0 < emin) emin = zzz0; + if (zzz1 < emin) emin = zzz1; - float comp = 0.0f; + float comp = 0.0f; - // Calculate how much we want the world to fall away, if we're in the defined region to do so - if( emin < falloffStart ) - { - int falloff = falloffStart - emin; - comp = ((float)falloff / (float)falloffStart ) * falloffMax; - } - // 4J - end of extra code - /////////////////////////////////////////////////////////////////// - int tileId = 0; - // 4J - this comparison used to just be with 0.0f but is now varied by block above - if (yc * CHUNK_HEIGHT + y < mapHeight) - { - tileId = (std::uint8_t) Tile::rock_Id; - } - else if (yc * CHUNK_HEIGHT + y < waterHeight) - { - tileId = (std::uint8_t) Tile::calmWater_Id; - } + // Calculate how much we want the world to fall + // away, if we're in the defined region to do so + if (emin < falloffStart) { + int falloff = falloffStart - emin; + comp = ((float)falloff / (float)falloffStart) * + falloffMax; + } + // 4J - end of extra code + /////////////////////////////////////////////////////////////////// + int tileId = 0; + // 4J - this comparison used to just be with 0.0f + // but is now varied by block above + if (yc * CHUNK_HEIGHT + y < mapHeight) { + tileId = (std::uint8_t)Tile::rock_Id; + } else if (yc * CHUNK_HEIGHT + y < waterHeight) { + tileId = (std::uint8_t)Tile::calmWater_Id; + } - // 4J - more extra code to make sure that the column at the edge of the world is just water & rock, to match the infinite sea that - // continues on after the edge of the world. + // 4J - more extra code to make sure that the column + // at the edge of the world is just water & rock, to + // match the infinite sea that continues on after + // the edge of the world. - if( emin == 0 ) - { - // This matches code in MultiPlayerChunkCache that makes the geometry which continues at the edge of the world - if( yc * CHUNK_HEIGHT + y <= ( level->getSeaLevel() - 10 ) ) tileId = Tile::rock_Id; - else if( yc * CHUNK_HEIGHT + y < level->getSeaLevel() ) tileId = Tile::calmWater_Id; - } + if (emin == 0) { + // This matches code in MultiPlayerChunkCache + // that makes the geometry which continues at + // the edge of the world + if (yc * CHUNK_HEIGHT + y <= + (level->getSeaLevel() - 10)) + tileId = Tile::rock_Id; + else if (yc * CHUNK_HEIGHT + y < + level->getSeaLevel()) + tileId = Tile::calmWater_Id; + } - int indexY = (yc * CHUNK_HEIGHT + y); - int offsAdjustment = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offsAdjustment = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - int offs = ( (x + xc * CHUNK_WIDTH) << Level::genDepthBitsPlusFour | (z + zc * CHUNK_WIDTH) << Level::genDepthBits | indexY) + offsAdjustment; - blocks[offs] = tileId; - } - } - } - } - } - } + int indexY = (yc * CHUNK_HEIGHT + y); + int offsAdjustment = 0; + if (indexY >= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offsAdjustment = + Level::COMPRESSED_CHUNK_SECTION_TILES; + } + int offs = + ((x + xc * CHUNK_WIDTH) + << Level::genDepthBitsPlusFour | + (z + zc * CHUNK_WIDTH) << Level::genDepthBits | + indexY) + + offsAdjustment; + blocks[offs] = tileId; + } + } + } + } + } + } #endif } - -void CustomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes) -{ +void CustomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes) { #ifdef _OVERRIDE_HEIGHTMAP - int waterHeight = level->seaLevel; - int xMapStart = xOffs + m_XZSize/2; - int zMapStart = zOffs + m_XZSize/2; + int waterHeight = level->seaLevel; + int xMapStart = xOffs + m_XZSize / 2; + int zMapStart = zOffs + m_XZSize / 2; - double s = 1 / 32.0; + double s = 1 / 32.0; - doubleArray depthBuffer(16*16); // 4J - used to be declared with class level scope but moved here for thread safety + doubleArray depthBuffer(16 * + 16); // 4J - used to be declared with class level + // scope but moved here for thread safety - depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, 0, 16, 16, 1, s * 2, s * 2, s * 2); + depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, + 0, 16, 16, 1, s * 2, s * 2, s * 2); - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { - int mapIndex = (zMapStart * 16 + z) * (m_XZSize * 16) + (xMapStart * 16 + x); - waterHeight = m_waterheightOverride[mapIndex]; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + int mapIndex = + (zMapStart * 16 + z) * (m_XZSize * 16) + (xMapStart * 16 + x); + waterHeight = m_waterheightOverride[mapIndex]; - Biome *b = biomes[z + x * 16]; - float temp = b->getTemperature(); - int runDepth = (int) (depthBuffer[x + z * 16] / 3 + 3 + random->nextDouble() * 0.25); + Biome* b = biomes[z + x * 16]; + float temp = b->getTemperature(); + int runDepth = (int)(depthBuffer[x + z * 16] / 3 + 3 + + random->nextDouble() * 0.25); - int run = -1; + int run = -1; - std::uint8_t top = b->topMaterial; - std::uint8_t material = b->material; + std::uint8_t top = b->topMaterial; + std::uint8_t material = b->material; - LevelGenerationOptions *lgo = app.getLevelGenerationOptions(); - if(lgo != NULL) - { - lgo->getBiomeOverride(b->id,material,top); - } + LevelGenerationOptions* lgo = app.getLevelGenerationOptions(); + if (lgo != NULL) { + lgo->getBiomeOverride(b->id, material, top); + } - for (int y = Level::maxBuildHeight - 1; y >= 0; y--) - { + for (int y = Level::maxBuildHeight - 1; y >= 0; y--) { + int indexY = y; + int offsAdjustment = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offsAdjustment = Level::COMPRESSED_CHUNK_SECTION_TILES; + } + int offs = (x << Level::genDepthBitsPlusFour | + z << Level::genDepthBits | indexY) + + offsAdjustment; - int indexY = y; - int offsAdjustment = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offsAdjustment = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - int offs = (x << Level::genDepthBitsPlusFour | z << Level::genDepthBits | indexY) + offsAdjustment; + if (y <= 1 + random->nextInt( + 2)) // 4J - changed to make the bedrock not + // have bits you can get stuck in + // if (y <= 0 + + // random->nextInt(5)) + { + blocks[offs] = (std::uint8_t)Tile::unbreakable_Id; + } else { + int old = blocks[offs]; - if (y <= 1 + random->nextInt(2)) // 4J - changed to make the bedrock not have bits you can get stuck in - // if (y <= 0 + random->nextInt(5)) - { - blocks[offs] = (std::uint8_t) Tile::unbreakable_Id; - } - else - { - int old = blocks[offs]; + if (old == 0) { + run = -1; + } else if (old == Tile::rock_Id) { + if (run == -1) { + if (runDepth <= 0) { + top = 0; + material = (std::uint8_t)Tile::rock_Id; + } else if (y >= waterHeight - 4 && + y <= waterHeight + 1) { + top = b->topMaterial; + material = b->material; + if (lgo != NULL) { + lgo->getBiomeOverride(b->id, material, top); + } + } - if (old == 0) - { - run = -1; - } - else if (old == Tile::rock_Id) - { - if (run == -1) - { - if (runDepth <= 0) - { - top = 0; - material = (std::uint8_t) Tile::rock_Id; - } - else if (y >= waterHeight - 4 && y <= waterHeight + 1) - { - top = b->topMaterial; - material = b->material; - if(lgo != NULL) - { - lgo->getBiomeOverride(b->id,material,top); - } - } + if (y < waterHeight && top == 0) { + if (temp < 0.15f) + top = (std::uint8_t)Tile::ice_Id; + else + top = (std::uint8_t)Tile::calmWater_Id; + } - if (y < waterHeight && top == 0) - { - if (temp < 0.15f) top = (std::uint8_t) Tile::ice_Id; - else top = (std::uint8_t) Tile::calmWater_Id; - } + run = runDepth; + if (y >= waterHeight - 1) + blocks[offs] = top; + else + blocks[offs] = material; + } else if (run > 0) { + run--; + blocks[offs] = material; - run = runDepth; - if (y >= waterHeight - 1) blocks[offs] = top; - else blocks[offs] = material; - } - else if (run > 0) - { - run--; - blocks[offs] = material; + // place a few sandstone blocks beneath sand + // runs + if (run == 0 && material == Tile::sand_Id) { + run = random->nextInt(4); + material = (std::uint8_t)Tile::sandStone_Id; + } + } + } + } + } + } + } - // place a few sandstone blocks beneath sand - // runs - if (run == 0 && material == Tile::sand_Id) - { - run = random->nextInt(4); - material = (std::uint8_t) Tile::sandStone_Id; - } - } - } - } - } - } - } - - delete [] depthBuffer.data; + delete[] depthBuffer.data; #endif } -LevelChunk *CustomLevelSource::create(int x, int z) -{ +LevelChunk* CustomLevelSource::create(int x, int z) { #ifdef _OVERRIDE_HEIGHTMAP - return getChunk(x,z); + return getChunk(x, z); #else - return NULL; + return NULL; #endif } -LevelChunk *CustomLevelSource::getChunk(int xOffs, int zOffs) -{ +LevelChunk* CustomLevelSource::getChunk(int xOffs, int zOffs) { #ifdef _OVERRIDE_HEIGHTMAP - random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); + random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - int blocksSize = Level::maxBuildHeight * 16 * 16; - std::uint8_t *tileData = (std::uint8_t *)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,blocksSize); - byteArray blocks = byteArray(tileData,blocksSize); - // byteArray blocks = byteArray(16 * level->depth * 16); + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + int blocksSize = Level::maxBuildHeight * 16 * 16; + std::uint8_t* tileData = (std::uint8_t*)XPhysicalAlloc( + blocksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); + XMemSet128(tileData, 0, blocksSize); + byteArray blocks = byteArray(tileData, blocksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); - // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); // 4J - moved to below + // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + // // 4J - moved to below - prepareHeights(xOffs, zOffs, blocks); + prepareHeights(xOffs, zOffs, blocks); - // 4J - Some changes made here to how biomes, temperatures and downfalls are passed around for thread safety - BiomeArray biomes; - level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, 16, true); + // 4J - Some changes made here to how biomes, temperatures and downfalls are + // passed around for thread safety + BiomeArray biomes; + level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, + 16, true); - buildSurfaces(xOffs, zOffs, blocks, biomes); + buildSurfaces(xOffs, zOffs, blocks, biomes); - delete [] biomes.data; + delete[] biomes.data; - caveFeature->apply(this, level, xOffs, zOffs, blocks); - // 4J Stu Design Change - 1.8 gen goes stronghold, mineshaft, village, canyon - // this changed in 1.2 to canyon, mineshaft, village, stronghold - // This change makes sense as it stops canyons running through other structures - canyonFeature->apply(this, level, xOffs, zOffs, blocks); - if (generateStructures) - { - mineShaftFeature->apply(this, level, xOffs, zOffs, blocks); - villageFeature->apply(this, level, xOffs, zOffs, blocks); - strongholdFeature->apply(this, level, xOffs, zOffs, blocks); - } - // canyonFeature.apply(this, level, xOffs, zOffs, blocks); - // townFeature.apply(this, level, xOffs, zOffs, blocks); - // addCaves(xOffs, zOffs, blocks); - // addTowns(xOffs, zOffs, blocks); + caveFeature->apply(this, level, xOffs, zOffs, blocks); + // 4J Stu Design Change - 1.8 gen goes stronghold, mineshaft, village, + // canyon this changed in 1.2 to canyon, mineshaft, village, stronghold This + // change makes sense as it stops canyons running through other structures + canyonFeature->apply(this, level, xOffs, zOffs, blocks); + if (generateStructures) { + mineShaftFeature->apply(this, level, xOffs, zOffs, blocks); + villageFeature->apply(this, level, xOffs, zOffs, blocks); + strongholdFeature->apply(this, level, xOffs, zOffs, blocks); + } + // canyonFeature.apply(this, level, xOffs, zOffs, blocks); + // townFeature.apply(this, level, xOffs, zOffs, blocks); + // addCaves(xOffs, zOffs, blocks); + // addTowns(xOffs, zOffs, blocks); - // levelChunk->recalcHeightmap(); // 4J - removed & moved into its own method + // levelChunk->recalcHeightmap(); // 4J - removed & moved + // into its own method - // 4J - this now creates compressed block data from the blocks array passed in, so moved it until after the blocks are actually finalised. We also - // now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - XPhysicalFree(tileData); + // 4J - this now creates compressed block data from the blocks array passed + // in, so moved it until after the blocks are actually finalised. We also + // now need to free the passed in blocks as the LevelChunk doesn't use the + // passed in allocation anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + XPhysicalFree(tileData); - return levelChunk; + return levelChunk; #else - return NULL; + return NULL; #endif } -// 4J - removed & moved into its own method from getChunk, so we can call recalcHeightmap after the chunk is added into the cache. Without -// doing this, then loads of the lightgaps() calls will fail to add any lights, because adding a light checks if the cache has this chunk in. -// lightgaps also does light 1 block into the neighbouring chunks, and maybe that is somehow enough to get lighting to propagate round the world, -// but this just doesn't seem right - this isn't a new fault in the 360 version, have checked that java does the same. -void CustomLevelSource::lightChunk(LevelChunk *lc) -{ +// 4J - removed & moved into its own method from getChunk, so we can call +// recalcHeightmap after the chunk is added into the cache. Without doing this, +// then loads of the lightgaps() calls will fail to add any lights, because +// adding a light checks if the cache has this chunk in. lightgaps also does +// light 1 block into the neighbouring chunks, and maybe that is somehow enough +// to get lighting to propagate round the world, but this just doesn't seem +// right - this isn't a new fault in the 360 version, have checked that java +// does the same. +void CustomLevelSource::lightChunk(LevelChunk* lc) { #ifdef _OVERRIDE_HEIGHTMAP - lc->recalcHeightmap(); + lc->recalcHeightmap(); #endif } -bool CustomLevelSource::hasChunk(int x, int y) -{ - return true; -} +bool CustomLevelSource::hasChunk(int x, int y) { return true; } -void CustomLevelSource::calcWaterDepths(ChunkSource *parent, int xt, int zt) -{ +void CustomLevelSource::calcWaterDepths(ChunkSource* parent, int xt, int zt) { #ifdef _OVERRIDE_HEIGHTMAP - int xo = xt * 16; - int zo = zt * 16; - for (int x = 0; x < 16; x++) - { - int y = level->getSeaLevel(); - for (int z = 0; z < 16; z++) - { - int xp = xo + x + 7; - int zp = zo + z + 7; - int h = level->getHeightmap(xp, zp); - if (h <= 0) - { - if (level->getHeightmap(xp - 1, zp) > 0 || level->getHeightmap(xp + 1, zp) > 0 || level->getHeightmap(xp, zp - 1) > 0 || level->getHeightmap(xp, zp + 1) > 0) - { - bool hadWater = false; - if (hadWater || (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && level->getData(xp - 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && level->getData(xp + 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && level->getData(xp, y, zp - 1) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && level->getData(xp, y, zp + 1) < 7)) hadWater = true; - if (hadWater) - { - for (int x2 = -5; x2 <= 5; x2++) - { - for (int z2 = -5; z2 <= 5; z2++) - { - int d = (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); + int xo = xt * 16; + int zo = zt * 16; + for (int x = 0; x < 16; x++) { + int y = level->getSeaLevel(); + for (int z = 0; z < 16; z++) { + int xp = xo + x + 7; + int zp = zo + z + 7; + int h = level->getHeightmap(xp, zp); + if (h <= 0) { + if (level->getHeightmap(xp - 1, zp) > 0 || + level->getHeightmap(xp + 1, zp) > 0 || + level->getHeightmap(xp, zp - 1) > 0 || + level->getHeightmap(xp, zp + 1) > 0) { + bool hadWater = false; + if (hadWater || + (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && + level->getData(xp - 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && + level->getData(xp + 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && + level->getData(xp, y, zp - 1) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && + level->getData(xp, y, zp + 1) < 7)) + hadWater = true; + if (hadWater) { + for (int x2 = -5; x2 <= 5; x2++) { + for (int z2 = -5; z2 <= 5; z2++) { + int d = + (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); - if (d <= 5) - { - d = 6 - d; - if (level->getTile(xp + x2, y, zp + z2) == Tile::calmWater_Id) - { - int od = level->getData(xp + x2, y, zp + z2); - if (od < 7 && od < d) - { - level->setData(xp + x2, y, zp + z2, d); - } - } - } - } - } - if (hadWater) - { - level->setTileAndDataNoUpdate(xp, y, zp, Tile::calmWater_Id, 7); - for (int y2 = 0; y2 < y; y2++) - { - level->setTileAndDataNoUpdate(xp, y2, zp, Tile::calmWater_Id, 8); - } - } - } - } - } - } - } + if (d <= 5) { + d = 6 - d; + if (level->getTile(xp + x2, y, zp + z2) == + Tile::calmWater_Id) { + int od = + level->getData(xp + x2, y, zp + z2); + if (od < 7 && od < d) { + level->setData(xp + x2, y, zp + z2, + d); + } + } + } + } + } + if (hadWater) { + level->setTileAndDataNoUpdate( + xp, y, zp, Tile::calmWater_Id, 7); + for (int y2 = 0; y2 < y; y2++) { + level->setTileAndDataNoUpdate( + xp, y2, zp, Tile::calmWater_Id, 8); + } + } + } + } + } + } + } #endif } -// 4J - changed this to used pprandom rather than random, so that we can run it concurrently with getChunk -void CustomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ +// 4J - changed this to used pprandom rather than random, so that we can run it +// concurrently with getChunk +void CustomLevelSource::postProcess(ChunkSource* parent, int xt, int zt) { #ifdef _OVERRIDE_HEIGHTMAP - HeavyTile::instaFall = true; - int xo = xt * 16; - int zo = zt * 16; + HeavyTile::instaFall = true; + int xo = xt * 16; + int zo = zt * 16; - Biome *biome = level->getBiome(xo + 16, zo + 16); + Biome* biome = level->getBiome(xo + 16, zo + 16); - if (CustomLevelSource::FLOATING_ISLANDS) - { - calcWaterDepths(parent, xt, zt); - } + if (CustomLevelSource::FLOATING_ISLANDS) { + calcWaterDepths(parent, xt, zt); + } - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); - bool hasVillage = false; + bool hasVillage = false; - PIXBeginNamedEvent(0,"Structure postprocessing"); - if (generateStructures) - { - mineShaftFeature->postProcess(level, pprandom, xt, zt); - hasVillage = villageFeature->postProcess(level, pprandom, xt, zt); - strongholdFeature->postProcess(level, pprandom, xt, zt); - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Structure postprocessing"); + if (generateStructures) { + mineShaftFeature->postProcess(level, pprandom, xt, zt); + hasVillage = villageFeature->postProcess(level, pprandom, xt, zt); + strongholdFeature->postProcess(level, pprandom, xt, zt); + } + PIXEndNamedEvent(); #if 0 PIXBeginNamedEvent(0,"Lakes"); @@ -509,92 +533,80 @@ void CustomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) PIXEndNamedEvent(); #endif - PIXBeginNamedEvent(0,"Monster rooms"); - for (int i = 0; i < 8; i++) { - int x = xo + pprandom->nextInt(16) + 8; - int y = pprandom->nextInt(Level::maxBuildHeight); - int z = zo + pprandom->nextInt(16) + 8; - MonsterRoomFeature *mrf = new MonsterRoomFeature(); - if (mrf->place(level, pprandom, x, y, z)) - { - } - delete mrf; - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Monster rooms"); + for (int i = 0; i < 8; i++) { + int x = xo + pprandom->nextInt(16) + 8; + int y = pprandom->nextInt(Level::maxBuildHeight); + int z = zo + pprandom->nextInt(16) + 8; + MonsterRoomFeature* mrf = new MonsterRoomFeature(); + if (mrf->place(level, pprandom, x, y, z)) { + } + delete mrf; + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Biome decorate"); - biome->decorate(level, pprandom, xo, zo); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Biome decorate"); + biome->decorate(level, pprandom, xo, zo); + PIXEndNamedEvent(); - app.processSchematics(parent->getChunk(xt,zt)); + app.processSchematics(parent->getChunk(xt, zt)); - MobSpawner::postProcessSpawnMobs(level, biome, xo + 8, zo + 8, 16, 16, pprandom); + MobSpawner::postProcessSpawnMobs(level, biome, xo + 8, zo + 8, 16, 16, + pprandom); - // 4J - brought forward from 1.2.3 to get snow back in taiga biomes - xo += 8; - zo += 8; - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { - int y = level->getTopRainBlock(xo + x, zo + z); + // 4J - brought forward from 1.2.3 to get snow back in taiga biomes + xo += 8; + zo += 8; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + int y = level->getTopRainBlock(xo + x, zo + z); - if (level->shouldFreezeIgnoreNeighbors(x + xo, y - 1, z + zo)) - { - level->setTileNoUpdate(x + xo, y - 1, z + zo, Tile::ice_Id); // 4J - changed from setTile, otherwise we end up creating a *lot* of dynamic water tiles as these ice tiles are set - } - if (level->shouldSnow(x + xo, y, z + zo)) - { - level->setTile(x + xo, y, z + zo, Tile::topSnow_Id); - } - } - } + if (level->shouldFreezeIgnoreNeighbors(x + xo, y - 1, z + zo)) { + level->setTileNoUpdate( + x + xo, y - 1, z + zo, + Tile::ice_Id); // 4J - changed from setTile, otherwise we + // end up creating a *lot* of dynamic water + // tiles as these ice tiles are set + } + if (level->shouldSnow(x + xo, y, z + zo)) { + level->setTile(x + xo, y, z + zo, Tile::topSnow_Id); + } + } + } - HeavyTile::instaFall = false; + HeavyTile::instaFall = false; #endif } -bool CustomLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; +bool CustomLevelSource::save(bool force, ProgressListener* progressListener) { + return true; } -bool CustomLevelSource::tick() -{ - return false; -} +bool CustomLevelSource::tick() { return false; } -bool CustomLevelSource::shouldSave() -{ - return true; -} +bool CustomLevelSource::shouldSave() { return true; } -std::wstring CustomLevelSource::gatherStats() -{ - return L"CustomLevelSource"; -} +std::wstring CustomLevelSource::gatherStats() { return L"CustomLevelSource"; } -std::vector *CustomLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ +std::vector* CustomLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { #ifdef _OVERRIDE_HEIGHTMAP - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { - return NULL; - } - return biome->getMobs(mobCategory); + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { + return NULL; + } + return biome->getMobs(mobCategory); #else - return NULL; + return NULL; #endif } -TilePos *CustomLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ +TilePos* CustomLevelSource::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { #ifdef _OVERRIDE_HEIGHTMAP - if (LargeFeature::STRONGHOLD == featureName && strongholdFeature != NULL) - { - return strongholdFeature->getNearestGeneratedFeature(level, x, y, z); - } + if (LargeFeature::STRONGHOLD == featureName && strongholdFeature != NULL) { + return strongholdFeature->getNearestGeneratedFeature(level, x, y, z); + } #endif - return NULL; + return NULL; } diff --git a/Minecraft.World/Level/CustomLevelSource.h b/Minecraft.World/Level/CustomLevelSource.h index ed7cd5699..2d7980d08 100644 --- a/Minecraft.World/Level/CustomLevelSource.h +++ b/Minecraft.World/Level/CustomLevelSource.h @@ -1,6 +1,5 @@ #pragma once - #include "ChunkSource.h" #ifndef _CONTENT_PACKAGE @@ -13,8 +12,7 @@ class StrongholdFeature; class VillageFeature; class MineShaftFeature; -class CustomLevelSource : public ChunkSource -{ +class CustomLevelSource : public ChunkSource { public: static const double SNOW_CUTOFF; static const double SNOW_SCALE; @@ -23,57 +21,59 @@ public: static const int CHUNK_WIDTH = 4; private: - #ifdef _OVERRIDE_HEIGHTMAP - Random *random; - Random *pprandom; // 4J - added - PerlinNoise *perlinNoise3; - LargeFeature *caveFeature; - StrongholdFeature *strongholdFeature; - VillageFeature *villageFeature; - MineShaftFeature *mineShaftFeature; - LargeFeature *canyonFeature; - Level *level; + Random* random; + Random* pprandom; // 4J - added + PerlinNoise* perlinNoise3; + LargeFeature* caveFeature; + StrongholdFeature* strongholdFeature; + VillageFeature* villageFeature; + MineShaftFeature* mineShaftFeature; + LargeFeature* canyonFeature; + Level* level; #endif - byteArray m_heightmapOverride; - byteArray m_waterheightOverride; + byteArray m_heightmapOverride; + byteArray m_waterheightOverride; private: - - const bool generateStructures; + const bool generateStructures; public: - CustomLevelSource(Level *level, __int64 seed, bool generateStructures); - ~CustomLevelSource(); + CustomLevelSource(Level* level, __int64 seed, bool generateStructures); + ~CustomLevelSource(); public: - void prepareHeights(int xOffs, int zOffs, byteArray blocks); + void prepareHeights(int xOffs, int zOffs, byteArray blocks); public: - void buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes); + void buildSurfaces(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes); private: - virtual LevelChunk *create(int x, int z); + virtual LevelChunk* create(int x, int z); public: - virtual LevelChunk *getChunk(int xOffs, int zOffs); - virtual void lightChunk(LevelChunk *lc); // 4J added + virtual LevelChunk* getChunk(int xOffs, int zOffs); + virtual void lightChunk(LevelChunk* lc); // 4J added public: - virtual bool hasChunk(int x, int y); + virtual bool hasChunk(int x, int y); private: - void calcWaterDepths(ChunkSource *parent, int xt, int zt); + void calcWaterDepths(ChunkSource* parent, int xt, int zt); public: - virtual void postProcess(ChunkSource *parent, int xt, int zt); - virtual bool save(bool force, ProgressListener *progressListener); + virtual void postProcess(ChunkSource* parent, int xt, int zt); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); public: - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/Level/DerivedLevelData.cpp b/Minecraft.World/Level/DerivedLevelData.cpp index 38b92836f..d97943579 100644 --- a/Minecraft.World/Level/DerivedLevelData.cpp +++ b/Minecraft.World/Level/DerivedLevelData.cpp @@ -2,208 +2,107 @@ #include "DerivedLevelData.h" -DerivedLevelData::DerivedLevelData(LevelData *wrapped) -{ - this->wrapped = wrapped; +DerivedLevelData::DerivedLevelData(LevelData* wrapped) { + this->wrapped = wrapped; } -void DerivedLevelData::setTagData(CompoundTag *tag) -{ - wrapped->setTagData(tag); +void DerivedLevelData::setTagData(CompoundTag* tag) { + wrapped->setTagData(tag); } -CompoundTag *DerivedLevelData::createTag() -{ - return wrapped->createTag(); +CompoundTag* DerivedLevelData::createTag() { return wrapped->createTag(); } + +CompoundTag* DerivedLevelData::createTag( + std::vector >* players) { + return wrapped->createTag(players); } -CompoundTag *DerivedLevelData::createTag(std::vector > *players) -{ - return wrapped->createTag(players); +__int64 DerivedLevelData::getSeed() { return wrapped->getSeed(); } + +int DerivedLevelData::getXSpawn() { return wrapped->getXSpawn(); } + +int DerivedLevelData::getYSpawn() { return wrapped->getYSpawn(); } + +int DerivedLevelData::getZSpawn() { return wrapped->getZSpawn(); } + +__int64 DerivedLevelData::getTime() { return wrapped->getTime(); } + +__int64 DerivedLevelData::getSizeOnDisk() { return wrapped->getSizeOnDisk(); } + +CompoundTag* DerivedLevelData::getLoadedPlayerTag() { + return wrapped->getLoadedPlayerTag(); } -__int64 DerivedLevelData::getSeed() -{ - return wrapped->getSeed(); +std::wstring DerivedLevelData::getLevelName() { + return wrapped->getLevelName(); } -int DerivedLevelData::getXSpawn() -{ - return wrapped->getXSpawn(); +int DerivedLevelData::getVersion() { return wrapped->getVersion(); } + +__int64 DerivedLevelData::getLastPlayed() { return wrapped->getLastPlayed(); } + +bool DerivedLevelData::isThundering() { return wrapped->isThundering(); } + +int DerivedLevelData::getThunderTime() { return wrapped->getThunderTime(); } + +bool DerivedLevelData::isRaining() { return wrapped->isRaining(); } + +int DerivedLevelData::getRainTime() { return wrapped->getRainTime(); } + +GameType* DerivedLevelData::getGameType() { return wrapped->getGameType(); } + +void DerivedLevelData::setSeed(__int64 seed) {} + +void DerivedLevelData::setXSpawn(int xSpawn) {} + +void DerivedLevelData::setYSpawn(int ySpawn) {} + +void DerivedLevelData::setZSpawn(int zSpawn) {} + +void DerivedLevelData::setTime(__int64 time) {} + +void DerivedLevelData::setSizeOnDisk(__int64 sizeOnDisk) {} + +void DerivedLevelData::setLoadedPlayerTag(CompoundTag* loadedPlayerTag) {} + +void DerivedLevelData::setDimension(int dimension) {} + +void DerivedLevelData::setSpawn(int xSpawn, int ySpawn, int zSpawn) {} + +void DerivedLevelData::setLevelName(const std::wstring& levelName) {} + +void DerivedLevelData::setVersion(int version) {} + +void DerivedLevelData::setThundering(bool thundering) {} + +void DerivedLevelData::setThunderTime(int thunderTime) {} + +void DerivedLevelData::setRaining(bool raining) {} + +void DerivedLevelData::setRainTime(int rainTime) {} + +bool DerivedLevelData::isGenerateMapFeatures() { + return wrapped->isGenerateMapFeatures(); } +void DerivedLevelData::setGameType(GameType* gameType) {} -int DerivedLevelData::getYSpawn() -{ - return wrapped->getYSpawn(); +bool DerivedLevelData::isHardcore() { return wrapped->isHardcore(); } + +LevelType* DerivedLevelData::getGenerator() { return wrapped->getGenerator(); } + +void DerivedLevelData::setGenerator(LevelType* generator) {} + +bool DerivedLevelData::getAllowCommands() { + return wrapped->getAllowCommands(); } -int DerivedLevelData::getZSpawn() -{ - return wrapped->getZSpawn(); -} +void DerivedLevelData::setAllowCommands(bool allowCommands) {} -__int64 DerivedLevelData::getTime() -{ - return wrapped->getTime(); -} +bool DerivedLevelData::isInitialized() { return wrapped->isInitialized(); } -__int64 DerivedLevelData::getSizeOnDisk() -{ - return wrapped->getSizeOnDisk(); -} +void DerivedLevelData::setInitialized(bool initialized) {} -CompoundTag *DerivedLevelData::getLoadedPlayerTag() -{ - return wrapped->getLoadedPlayerTag(); -} +int DerivedLevelData::getXZSize() { return wrapped->getXZSize(); } -std::wstring DerivedLevelData::getLevelName() -{ - return wrapped->getLevelName(); -} - -int DerivedLevelData::getVersion() -{ - return wrapped->getVersion(); -} - -__int64 DerivedLevelData::getLastPlayed() -{ - return wrapped->getLastPlayed(); -} - -bool DerivedLevelData::isThundering() -{ - return wrapped->isThundering(); -} - -int DerivedLevelData::getThunderTime() -{ - return wrapped->getThunderTime(); -} - -bool DerivedLevelData::isRaining() -{ - return wrapped->isRaining(); -} - -int DerivedLevelData::getRainTime() -{ - return wrapped->getRainTime(); -} - -GameType *DerivedLevelData::getGameType() -{ - return wrapped->getGameType(); -} - -void DerivedLevelData::setSeed(__int64 seed) -{ -} - -void DerivedLevelData::setXSpawn(int xSpawn) -{ -} - -void DerivedLevelData::setYSpawn(int ySpawn) -{ -} - -void DerivedLevelData::setZSpawn(int zSpawn) -{ -} - -void DerivedLevelData::setTime(__int64 time) -{ -} - -void DerivedLevelData::setSizeOnDisk(__int64 sizeOnDisk) -{ -} - -void DerivedLevelData::setLoadedPlayerTag(CompoundTag *loadedPlayerTag) -{ -} - -void DerivedLevelData::setDimension(int dimension) -{ -} - -void DerivedLevelData::setSpawn(int xSpawn, int ySpawn, int zSpawn) -{ -} - -void DerivedLevelData::setLevelName(const std::wstring &levelName) -{ -} - -void DerivedLevelData::setVersion(int version) -{ -} - -void DerivedLevelData::setThundering(bool thundering) -{ -} - -void DerivedLevelData::setThunderTime(int thunderTime) -{ -} - -void DerivedLevelData::setRaining(bool raining) -{ -} - -void DerivedLevelData::setRainTime(int rainTime) -{ -} - -bool DerivedLevelData::isGenerateMapFeatures() -{ - return wrapped->isGenerateMapFeatures(); -} - -void DerivedLevelData::setGameType(GameType *gameType) { -} - -bool DerivedLevelData::isHardcore() -{ - return wrapped->isHardcore(); -} - -LevelType *DerivedLevelData::getGenerator() -{ - return wrapped->getGenerator(); -} - -void DerivedLevelData::setGenerator(LevelType *generator) -{ -} - -bool DerivedLevelData::getAllowCommands() -{ - return wrapped->getAllowCommands(); -} - -void DerivedLevelData::setAllowCommands(bool allowCommands) -{ -} - -bool DerivedLevelData::isInitialized() -{ - return wrapped->isInitialized(); -} - -void DerivedLevelData::setInitialized(bool initialized) -{ -} - -int DerivedLevelData::getXZSize() -{ - return wrapped->getXZSize(); -} - -int DerivedLevelData::getHellScale() -{ - return wrapped->getHellScale(); -} +int DerivedLevelData::getHellScale() { return wrapped->getHellScale(); } diff --git a/Minecraft.World/Level/DerivedLevelData.h b/Minecraft.World/Level/DerivedLevelData.h index d62c91ec8..0c633d176 100644 --- a/Minecraft.World/Level/DerivedLevelData.h +++ b/Minecraft.World/Level/DerivedLevelData.h @@ -2,59 +2,58 @@ #include "LevelData.h" -class DerivedLevelData : public LevelData -{ +class DerivedLevelData : public LevelData { private: - LevelData *wrapped; + LevelData* wrapped; public: - DerivedLevelData(LevelData *wrapped); + DerivedLevelData(LevelData* wrapped); protected: - virtual void setTagData(CompoundTag *tag); // 4J Added + virtual void setTagData(CompoundTag* tag); // 4J Added public: - CompoundTag *createTag(); - CompoundTag *createTag(std::vector > *players); - __int64 getSeed(); - int getXSpawn(); - int getYSpawn(); - int getZSpawn(); - __int64 getTime(); - __int64 getSizeOnDisk(); - CompoundTag *getLoadedPlayerTag(); - std::wstring getLevelName(); - int getVersion(); - __int64 getLastPlayed(); - bool isThundering(); - int getThunderTime(); - bool isRaining(); - int getRainTime(); - GameType *getGameType(); - void setSeed(__int64 seed); - void setXSpawn(int xSpawn); - void setYSpawn(int ySpawn); - void setZSpawn(int zSpawn); - void setTime(__int64 time); - void setSizeOnDisk(__int64 sizeOnDisk); - void setLoadedPlayerTag(CompoundTag *loadedPlayerTag); - void setDimension(int dimension); - void setSpawn(int xSpawn, int ySpawn, int zSpawn); - void setLevelName(const std::wstring &levelName); - void setVersion(int version); - void setThundering(bool thundering); - void setThunderTime(int thunderTime); - void setRaining(bool raining); - void setRainTime(int rainTime); - bool isGenerateMapFeatures(); - void setGameType(GameType *gameType); - bool isHardcore(); - LevelType *getGenerator(); - void setGenerator(LevelType *generator); - bool getAllowCommands(); - void setAllowCommands(bool allowCommands); - bool isInitialized(); - void setInitialized(bool initialized); - int getXZSize(); // 4J Added - int getHellScale(); // 4J Addded + CompoundTag* createTag(); + CompoundTag* createTag(std::vector >* players); + __int64 getSeed(); + int getXSpawn(); + int getYSpawn(); + int getZSpawn(); + __int64 getTime(); + __int64 getSizeOnDisk(); + CompoundTag* getLoadedPlayerTag(); + std::wstring getLevelName(); + int getVersion(); + __int64 getLastPlayed(); + bool isThundering(); + int getThunderTime(); + bool isRaining(); + int getRainTime(); + GameType* getGameType(); + void setSeed(__int64 seed); + void setXSpawn(int xSpawn); + void setYSpawn(int ySpawn); + void setZSpawn(int zSpawn); + void setTime(__int64 time); + void setSizeOnDisk(__int64 sizeOnDisk); + void setLoadedPlayerTag(CompoundTag* loadedPlayerTag); + void setDimension(int dimension); + void setSpawn(int xSpawn, int ySpawn, int zSpawn); + void setLevelName(const std::wstring& levelName); + void setVersion(int version); + void setThundering(bool thundering); + void setThunderTime(int thunderTime); + void setRaining(bool raining); + void setRainTime(int rainTime); + bool isGenerateMapFeatures(); + void setGameType(GameType* gameType); + bool isHardcore(); + LevelType* getGenerator(); + void setGenerator(LevelType* generator); + bool getAllowCommands(); + void setAllowCommands(bool allowCommands); + bool isInitialized(); + void setInitialized(bool initialized); + int getXZSize(); // 4J Added + int getHellScale(); // 4J Addded }; diff --git a/Minecraft.World/Level/Dimensions/Dimension.cpp b/Minecraft.World/Level/Dimensions/Dimension.cpp index e9ec5db0d..ce97f0872 100644 --- a/Minecraft.World/Level/Dimensions/Dimension.cpp +++ b/Minecraft.World/Level/Dimensions/Dimension.cpp @@ -13,92 +13,85 @@ #include "../../../Minecraft.Client/Minecraft.h" #include "../../../Minecraft.Client/Platform/Common/Colours/ColourTable.h" -void Dimension::init(Level *level) -{ +void Dimension::init(Level* level) { this->level = level; - this->levelType = level->getLevelData()->getGenerator(); + this->levelType = level->getLevelData()->getGenerator(); init(); updateLightRamp(); } -void Dimension::updateLightRamp() -{ +void Dimension::updateLightRamp() { float ambientLight = 0.00f; - for (int i = 0; i <= Level::MAX_BRIGHTNESS; i++) - { - float v = (1 - i / (float) (Level::MAX_BRIGHTNESS)); - brightnessRamp[i] = ((1 - v) / (v * 3 + 1)) * (1 - ambientLight) + ambientLight; + for (int i = 0; i <= Level::MAX_BRIGHTNESS; i++) { + float v = (1 - i / (float)(Level::MAX_BRIGHTNESS)); + brightnessRamp[i] = + ((1 - v) / (v * 3 + 1)) * (1 - ambientLight) + ambientLight; } } -void Dimension::init() -{ +void Dimension::init() { #ifdef _OVERRIDE_HEIGHTMAP - // 4J Stu - Added to enable overriding the heightmap from a loaded in data file - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getLevelData()->getGenerator() == LevelType::lvl_flat) - { - biomeSource = new FixedBiomeSource(Biome::plains, 0.5f, 0.5f); - } - else - { - biomeSource = new BiomeSource(level); - } + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) { + biomeSource = new FixedBiomeSource(Biome::plains, 0.5f, 0.5f); + } else { + biomeSource = new BiomeSource(level); + } } -Dimension::Dimension() -{ - ultraWarm = false; - hasCeiling = false; - brightnessRamp = new float[Level::MAX_BRIGHTNESS + 1]; - id = 0; +Dimension::Dimension() { + ultraWarm = false; + hasCeiling = false; + brightnessRamp = new float[Level::MAX_BRIGHTNESS + 1]; + id = 0; } -Dimension::~Dimension() -{ - delete[] brightnessRamp; +Dimension::~Dimension() { + delete[] brightnessRamp; - if(biomeSource != NULL) - delete biomeSource; + if (biomeSource != NULL) delete biomeSource; } -ChunkSource *Dimension::createRandomLevelSource() const -{ +ChunkSource* Dimension::createRandomLevelSource() const { #ifdef _OVERRIDE_HEIGHTMAP - // 4J Stu - Added to enable overriding the heightmap from a loaded in data file - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getSeed(), level->getLevelData()->isGenerateMapFeatures()); - } - else + // 4J Stu - Added to enable overriding the heightmap from a loaded in data + // file + if (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_EnableHeightWaterBiomeOverride)) { + return new CustomLevelSource( + level, level->getSeed(), + level->getLevelData()->isGenerateMapFeatures()); + } else #endif - if (levelType == LevelType::lvl_flat) - { - return new FlatLevelSource(level, level->getSeed(), level->getLevelData()->isGenerateMapFeatures()); - } - else - { - return new RandomLevelSource(level, level->getSeed(), level->getLevelData()->isGenerateMapFeatures()); - } + if (levelType == LevelType::lvl_flat) { + return new FlatLevelSource( + level, level->getSeed(), + level->getLevelData()->isGenerateMapFeatures()); + } else { + return new RandomLevelSource( + level, level->getSeed(), + level->getLevelData()->isGenerateMapFeatures()); + } } -ChunkSource *Dimension::createFlatLevelSource() const -{ - return new FlatLevelSource(level, level->getSeed(), level->getLevelData()->isGenerateMapFeatures()); +ChunkSource* Dimension::createFlatLevelSource() const { + return new FlatLevelSource(level, level->getSeed(), + level->getLevelData()->isGenerateMapFeatures()); } -ChunkStorage *Dimension::createStorage(File dir) -{ - return new OldChunkStorage(dir, true); +ChunkStorage* Dimension::createStorage(File dir) { + return new OldChunkStorage(dir, true); } -bool Dimension::isValidSpawn(int x, int z) const -{ +bool Dimension::isValidSpawn(int x, int z) const { int topTile = level->getTopTile(x, z); if (topTile != Tile::grass_Id) return false; @@ -106,50 +99,47 @@ bool Dimension::isValidSpawn(int x, int z) const return true; } -float Dimension::getTimeOfDay(__int64 time, float a) const -{ - int dayStep = (int) (time % Level::TICKS_PER_DAY); +float Dimension::getTimeOfDay(__int64 time, float a) const { + int dayStep = (int)(time % Level::TICKS_PER_DAY); float td = (dayStep + a) / Level::TICKS_PER_DAY - 0.25f; if (td < 0) td += 1; if (td > 1) td -= 1; float tdo = td; - td = 1 - (float) ((cos(td * PI) + 1) / 2); + td = 1 - (float)((cos(td * PI) + 1) / 2); td = tdo + (td - tdo) / 3.0f; return td; } -int Dimension::getMoonPhase(__int64 time, float a) const -{ - return ((int) (time / Level::TICKS_PER_DAY)) % 8; +int Dimension::getMoonPhase(__int64 time, float a) const { + return ((int)(time / Level::TICKS_PER_DAY)) % 8; } -bool Dimension::isNaturalDimension() -{ - return true; -} +bool Dimension::isNaturalDimension() { return true; } -float *Dimension::getSunriseColor(float td, float a) -{ - unsigned int clr1 = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Sky_Dawn_Dark ); // 0xB23333 - double r1 = ( (clr1>>16)&0xFF )/255.0f, g1 = ( (clr1>>8)&0xFF )/255.0, b1 = ( clr1&0xFF )/255.0; +float* Dimension::getSunriseColor(float td, float a) { + unsigned int clr1 = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Sky_Dawn_Dark); // 0xB23333 + double r1 = ((clr1 >> 16) & 0xFF) / 255.0f, + g1 = ((clr1 >> 8) & 0xFF) / 255.0, b1 = (clr1 & 0xFF) / 255.0; - unsigned int clr2 = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Sky_Dawn_Bright ); // 0xFFE533 - double r2 = ( (clr2>>16)&0xFF )/255.0f, g2 = ( (clr2>>8)&0xFF )/255.0, b2 = ( clr2&0xFF )/255.0; + unsigned int clr2 = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Sky_Dawn_Bright); // 0xFFE533 + double r2 = ((clr2 >> 16) & 0xFF) / 255.0f, + g2 = ((clr2 >> 8) & 0xFF) / 255.0, b2 = (clr2 & 0xFF) / 255.0; float span = 0.4f; float tt = Mth::cos(td * PI * 2) - 0.0f; float mid = -0.0f; - if (tt >= mid - span && tt <= mid + span) - { + if (tt >= mid - span && tt <= mid + span) { float aa = ((tt - mid) / span) * 0.5f + 0.5f; float mix = 1 - (((1 - sin(aa * PI))) * 0.99f); mix = mix * mix; - //sunriseCol[0] = (aa * 0.3f + 0.7f); - //sunriseCol[1] = (aa * aa * 0.7f + 0.2f); - //sunriseCol[2] = (aa * aa * 0.0f + 0.2f); - sunriseCol[0] = (aa * (r2-r1) + r1); - sunriseCol[1] = (aa * (g2-g1) + g1); - sunriseCol[2] = (aa * (b2-b1) + b1); + // sunriseCol[0] = (aa * 0.3f + 0.7f); + // sunriseCol[1] = (aa * aa * 0.7f + 0.2f); + // sunriseCol[2] = (aa * aa * 0.0f + 0.2f); + sunriseCol[0] = (aa * (r2 - r1) + r1); + sunriseCol[1] = (aa * (g2 - g1) + g1); + sunriseCol[2] = (aa * (b2 - b1) + b1); sunriseCol[3] = mix; return sunriseCol; } @@ -157,13 +147,14 @@ float *Dimension::getSunriseColor(float td, float a) return NULL; } -Vec3 *Dimension::getFogColor(float td, float a) const -{ +Vec3* Dimension::getFogColor(float td, float a) const { float br = Mth::cos(td * PI * 2) * 2 + 0.5f; if (br < 0.0f) br = 0.0f; if (br > 1.0f) br = 1.0f; - - unsigned int baseFogColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Default_Fog_Colour ); + + unsigned int baseFogColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Default_Fog_Colour); float r = ((baseFogColour >> 16) & 0xff) / 255.0f; float g = ((baseFogColour >> 8) & 0xff) / 255.0f; float b = ((baseFogColour) & 0xff) / 255.0f; @@ -174,13 +165,9 @@ Vec3 *Dimension::getFogColor(float td, float a) const return Vec3::newTemp(r, g, b); } -bool Dimension::mayRespawn() const -{ - return true; -} +bool Dimension::mayRespawn() const { return true; } -Dimension *Dimension::getNew(int id) -{ +Dimension* Dimension::getNew(int id) { if (id == -1) return new HellDimension(); if (id == 0) return new NormalDimension(); if (id == 1) return new TheEndDimension(); @@ -188,56 +175,35 @@ Dimension *Dimension::getNew(int id) return NULL; } -float Dimension::getCloudHeight() -{ - return (float)Level::genDepth; +float Dimension::getCloudHeight() { return (float)Level::genDepth; } + +bool Dimension::hasGround() { return true; } + +Pos* Dimension::getSpawnPos() { return NULL; } + +int Dimension::getSpawnYPosition() { + if (levelType == LevelType::lvl_flat) { + return 4; + } + return Level::genDepth / 2; } -bool Dimension::hasGround() -{ - return true; +bool Dimension::hasBedrockFog() { + // 4J-PB - turn off bedrock fog if the host player doesn't want it + if (app.GetGameHostOption(eGameHostOption_BedrockFog) == 0) { + return false; + } + + return (levelType != LevelType::lvl_flat && !hasCeiling); } -Pos *Dimension::getSpawnPos() -{ - return NULL; +double Dimension::getClearColorScale() { + if (levelType == LevelType::lvl_flat) { + return 1.0; + } + return 1.0 / 32.0; } -int Dimension::getSpawnYPosition() -{ - if (levelType == LevelType::lvl_flat) - { - return 4; - } - return Level::genDepth / 2; -} +bool Dimension::isFoggyAt(int x, int z) { return false; } -bool Dimension::hasBedrockFog() -{ - // 4J-PB - turn off bedrock fog if the host player doesn't want it - if(app.GetGameHostOption(eGameHostOption_BedrockFog)==0) - { - return false; - } - - return (levelType != LevelType::lvl_flat && !hasCeiling); -} - -double Dimension::getClearColorScale() -{ - if (levelType == LevelType::lvl_flat) - { - return 1.0; - } - return 1.0 / 32.0; -} - -bool Dimension::isFoggyAt(int x, int z) -{ - return false; -} - -int Dimension::getXZSize() -{ - return level->getLevelData()->getXZSize(); -} +int Dimension::getXZSize() { return level->getLevelData()->getXZSize(); } diff --git a/Minecraft.World/Level/Dimensions/Dimension.h b/Minecraft.World/Level/Dimensions/Dimension.h index 9d79c990f..a9e342c59 100644 --- a/Minecraft.World/Level/Dimensions/Dimension.h +++ b/Minecraft.World/Level/Dimensions/Dimension.h @@ -9,54 +9,54 @@ class LevelType; #include "../../Util/Vec3.h" #include "../../Util/Pos.h" -class Dimension -{ +class Dimension { public: - Level *level; - LevelType *levelType; - BiomeSource *biomeSource; - bool ultraWarm ; + Level* level; + LevelType* levelType; + BiomeSource* biomeSource; + bool ultraWarm; bool hasCeiling; - float *brightnessRamp; + float* brightnessRamp; int id; - virtual void init(Level *level); + virtual void init(Level* level); protected: virtual void updateLightRamp(); virtual void init(); public: - Dimension(); - virtual ~Dimension(); - virtual ChunkSource *createRandomLevelSource() const; - virtual ChunkSource *createFlatLevelSource() const; - virtual ChunkStorage *createStorage(File dir); + Dimension(); + virtual ~Dimension(); + virtual ChunkSource* createRandomLevelSource() const; + virtual ChunkSource* createFlatLevelSource() const; + virtual ChunkStorage* createStorage(File dir); virtual bool isValidSpawn(int x, int z) const; virtual float getTimeOfDay(__int64 time, float a) const; - virtual int getMoonPhase(__int64 time, float a) const; - virtual bool isNaturalDimension(); + virtual int getMoonPhase(__int64 time, float a) const; + virtual bool isNaturalDimension(); + private: static const int fogColor = 0xc0d8ff; float sunriseCol[4]; public: - virtual float *getSunriseColor(float td, float a); - virtual Vec3 *getFogColor(float td, float a) const; + virtual float* getSunriseColor(float td, float a); + virtual Vec3* getFogColor(float td, float a) const; virtual bool mayRespawn() const; - static Dimension *getNew(int id); + static Dimension* getNew(int id); virtual float getCloudHeight(); virtual bool hasGround(); - virtual Pos *getSpawnPos(); + virtual Pos* getSpawnPos(); - int getSpawnYPosition(); - virtual bool hasBedrockFog(); - double getClearColorScale(); - virtual bool isFoggyAt(int x, int z); + int getSpawnYPosition(); + virtual bool hasBedrockFog(); + double getClearColorScale(); + virtual bool isFoggyAt(int x, int z); - // 4J Added - virtual int getXZSize(); + // 4J Added + virtual int getXZSize(); }; diff --git a/Minecraft.World/Level/Dimensions/HellDimension.cpp b/Minecraft.World/Level/Dimensions/HellDimension.cpp index 8ad5bea3c..21639afde 100644 --- a/Minecraft.World/Level/Dimensions/HellDimension.cpp +++ b/Minecraft.World/Level/Dimensions/HellDimension.cpp @@ -8,82 +8,61 @@ #include "../../../Minecraft.Client/Minecraft.h" #include "../../../Minecraft.Client/Platform/Common/Colours/ColourTable.h" -void HellDimension::init() -{ +void HellDimension::init() { biomeSource = new FixedBiomeSource(Biome::hell, 1, 0); ultraWarm = true; hasCeiling = true; id = -1; } -Vec3 *HellDimension::getFogColor(float td, float a) const -{ - int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Nether_Fog_Colour ); - uint8_t redComponent = ((colour>>16)&0xFF); - uint8_t greenComponent = ((colour>>8)&0xFF); - uint8_t blueComponent = ((colour)&0xFF); +Vec3* HellDimension::getFogColor(float td, float a) const { + int colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Nether_Fog_Colour); + uint8_t redComponent = ((colour >> 16) & 0xFF); + uint8_t greenComponent = ((colour >> 8) & 0xFF); + uint8_t blueComponent = ((colour) & 0xFF); - float rr = (float)redComponent/256;//0.2f; - float gg = (float)greenComponent/256;//0.03f; - float bb = (float)blueComponent/256;//0.03f; - return Vec3::newTemp(rr, gg, bb); + float rr = (float)redComponent / 256; // 0.2f; + float gg = (float)greenComponent / 256; // 0.03f; + float bb = (float)blueComponent / 256; // 0.03f; + return Vec3::newTemp(rr, gg, bb); } -void HellDimension::updateLightRamp() -{ +void HellDimension::updateLightRamp() { float ambientLight = 0.10f; - for (int i = 0; i <= Level::MAX_BRIGHTNESS; i++) - { - float v = (1 - i / (float) (Level::MAX_BRIGHTNESS)); - brightnessRamp[i] = ((1 - v) / (v * 3 + 1)) * (1 - ambientLight) + ambientLight; + for (int i = 0; i <= Level::MAX_BRIGHTNESS; i++) { + float v = (1 - i / (float)(Level::MAX_BRIGHTNESS)); + brightnessRamp[i] = + ((1 - v) / (v * 3 + 1)) * (1 - ambientLight) + ambientLight; } } -ChunkSource *HellDimension::createRandomLevelSource() const -{ +ChunkSource* HellDimension::createRandomLevelSource() const { #ifdef _DEBUG_MENUS_ENABLED - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getSeed()); - } - else + if (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_SuperflatNether)) { + return new HellFlatLevelSource(level, level->getSeed()); + } else #endif - if (levelType == LevelType::lvl_flat) - { - return new HellFlatLevelSource(level, level->getSeed()); - } - else - { - return new HellRandomLevelSource(level, level->getSeed()); - } + if (levelType == LevelType::lvl_flat) { + return new HellFlatLevelSource(level, level->getSeed()); + } else { + return new HellRandomLevelSource(level, level->getSeed()); + } } -bool HellDimension::isNaturalDimension() -{ - return false; -} +bool HellDimension::isNaturalDimension() { return false; } -bool HellDimension::isValidSpawn(int x, int z) const -{ - return false; -} +bool HellDimension::isValidSpawn(int x, int z) const { return false; } -float HellDimension::getTimeOfDay(__int64 time, float a) const -{ - return 0.5f; -} +float HellDimension::getTimeOfDay(__int64 time, float a) const { return 0.5f; } -bool HellDimension::mayRespawn() const -{ - return false; -} +bool HellDimension::mayRespawn() const { return false; } -bool HellDimension::isFoggyAt(int x, int z) -{ - return true; -} +bool HellDimension::isFoggyAt(int x, int z) { return true; } -int HellDimension::getXZSize() -{ - return ceil((float)level->getLevelData()->getXZSize() / level->getLevelData()->getHellScale()); +int HellDimension::getXZSize() { + return ceil((float)level->getLevelData()->getXZSize() / + level->getLevelData()->getHellScale()); } diff --git a/Minecraft.World/Level/Dimensions/HellDimension.h b/Minecraft.World/Level/Dimensions/HellDimension.h index b37f2b53b..863398cbc 100644 --- a/Minecraft.World/Level/Dimensions/HellDimension.h +++ b/Minecraft.World/Level/Dimensions/HellDimension.h @@ -1,23 +1,22 @@ #pragma once #include "Dimension.h" -class HellDimension : public Dimension -{ +class HellDimension : public Dimension { public: - virtual void init(); - virtual Vec3 *getFogColor(float td, float a) const; + virtual void init(); + virtual Vec3* getFogColor(float td, float a) const; protected: - virtual void updateLightRamp(); + virtual void updateLightRamp(); public: - virtual ChunkSource *createRandomLevelSource() const; - virtual bool isNaturalDimension(); - virtual bool isValidSpawn(int x, int y) const; - virtual float getTimeOfDay(__int64 time, float a) const; - virtual bool mayRespawn() const; - virtual bool isFoggyAt(int x, int z); + virtual ChunkSource* createRandomLevelSource() const; + virtual bool isNaturalDimension(); + virtual bool isValidSpawn(int x, int y) const; + virtual float getTimeOfDay(__int64 time, float a) const; + virtual bool mayRespawn() const; + virtual bool isFoggyAt(int x, int z); - // 4J Added - virtual int getXZSize(); + // 4J Added + virtual int getXZSize(); }; diff --git a/Minecraft.World/Level/Dimensions/NormalDimension.h b/Minecraft.World/Level/Dimensions/NormalDimension.h index 357ff04e3..7cef887ae 100644 --- a/Minecraft.World/Level/Dimensions/NormalDimension.h +++ b/Minecraft.World/Level/Dimensions/NormalDimension.h @@ -1,6 +1,4 @@ #pragma once #include "Dimension.h" -class NormalDimension : public Dimension -{ -}; \ No newline at end of file +class NormalDimension : public Dimension {}; \ No newline at end of file diff --git a/Minecraft.World/Level/Dimensions/SkyIslandDimension.cpp b/Minecraft.World/Level/Dimensions/SkyIslandDimension.cpp index a92fd0e24..7715de778 100644 --- a/Minecraft.World/Level/Dimensions/SkyIslandDimension.cpp +++ b/Minecraft.World/Level/Dimensions/SkyIslandDimension.cpp @@ -5,29 +5,22 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Headers/net.minecraft.world.level.levelgen.h" -void SkyIslandDimension::init() -{ +void SkyIslandDimension::init() { biomeSource = new FixedBiomeSource(Biome::sky, 0.5f, 0); id = 1; } -ChunkSource *SkyIslandDimension::createRandomLevelSource() const -{ - return new SkyIslandRandomLevelSource(level, level->getSeed()); +ChunkSource* SkyIslandDimension::createRandomLevelSource() const { + return new SkyIslandRandomLevelSource(level, level->getSeed()); } -float SkyIslandDimension::getTimeOfDay(__int64 time, float a) const -{ - return 0.0f; +float SkyIslandDimension::getTimeOfDay(__int64 time, float a) const { + return 0.0f; } -float *SkyIslandDimension::getSunriseColor(float td, float a) -{ - return NULL; -} +float* SkyIslandDimension::getSunriseColor(float td, float a) { return NULL; } -Vec3 *SkyIslandDimension::getFogColor(float td, float a) const -{ +Vec3* SkyIslandDimension::getFogColor(float td, float a) const { int fogColor = 0x8080a0; float br = Mth::cos(td * PI * 2) * 2 + 0.5f; if (br < 0.0f) br = 0.0f; @@ -43,18 +36,11 @@ Vec3 *SkyIslandDimension::getFogColor(float td, float a) const return Vec3::newTemp(r, g, b); } -bool SkyIslandDimension::hasGround() -{ - return false; -} +bool SkyIslandDimension::hasGround() { return false; } -float SkyIslandDimension::getCloudHeight() -{ - return 8; -} +float SkyIslandDimension::getCloudHeight() { return 8; } -bool SkyIslandDimension::isValidSpawn(int x, int z) const -{ +bool SkyIslandDimension::isValidSpawn(int x, int z) const { int topTile = level->getTopTile(x, z); if (topTile == 0) return false; diff --git a/Minecraft.World/Level/Dimensions/TheEndDimension.cpp b/Minecraft.World/Level/Dimensions/TheEndDimension.cpp index 3c726eeec..50c09e1e7 100644 --- a/Minecraft.World/Level/Dimensions/TheEndDimension.cpp +++ b/Minecraft.World/Level/Dimensions/TheEndDimension.cpp @@ -7,67 +7,48 @@ #include "../../../Minecraft.Client/Minecraft.h" #include "../../../Minecraft.Client/Platform/Common/Colours/ColourTable.h" -void TheEndDimension::init() -{ +void TheEndDimension::init() { biomeSource = new FixedBiomeSource(Biome::sky, 0.5f, 0); id = 1; hasCeiling = true; } -ChunkSource *TheEndDimension::createRandomLevelSource() const -{ - return new TheEndLevelRandomLevelSource(level, level->getSeed()); +ChunkSource* TheEndDimension::createRandomLevelSource() const { + return new TheEndLevelRandomLevelSource(level, level->getSeed()); } -float TheEndDimension::getTimeOfDay(__int64 time, float a) const -{ - return 0.0f; +float TheEndDimension::getTimeOfDay(__int64 time, float a) const { + return 0.0f; } -float *TheEndDimension::getSunriseColor(float td, float a) -{ - return NULL; +float* TheEndDimension::getSunriseColor(float td, float a) { return NULL; } + +Vec3* TheEndDimension::getFogColor(float td, float a) const { + int fogColor = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_End_Fog_Colour); // 0xa080a0; + float br = Mth::cos(td * PI * 2) * 2 + 0.5f; + if (br < 0.0f) br = 0.0f; + if (br > 1.0f) br = 1.0f; + + float r = ((fogColor >> 16) & 0xff) / 255.0f; + float g = ((fogColor >> 8) & 0xff) / 255.0f; + float b = ((fogColor) & 0xff) / 255.0f; + r *= br * 0.0f + 0.15f; + g *= br * 0.0f + 0.15f; + b *= br * 0.0f + 0.15f; + + return Vec3::newTemp(r, g, b); } -Vec3 *TheEndDimension::getFogColor(float td, float a) const -{ - int fogColor = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_End_Fog_Colour ); //0xa080a0; - float br = Mth::cos(td * PI * 2) * 2 + 0.5f; - if (br < 0.0f) br = 0.0f; - if (br > 1.0f) br = 1.0f; +bool TheEndDimension::hasGround() { return false; } - float r = ((fogColor >> 16) & 0xff) / 255.0f; - float g = ((fogColor >> 8) & 0xff) / 255.0f; - float b = ((fogColor) & 0xff) / 255.0f; - r *= br * 0.0f + 0.15f; - g *= br * 0.0f + 0.15f; - b *= br * 0.0f + 0.15f; +bool TheEndDimension::mayRespawn() const { return false; } - return Vec3::newTemp(r, g, b); -} +bool TheEndDimension::isNaturalDimension() { return false; } -bool TheEndDimension::hasGround() -{ - return false; -} +float TheEndDimension::getCloudHeight() { return 8; } -bool TheEndDimension::mayRespawn() const -{ - return false; -} - -bool TheEndDimension::isNaturalDimension() -{ - return false; -} - -float TheEndDimension::getCloudHeight() -{ - return 8; -} - -bool TheEndDimension::isValidSpawn(int x, int z) const -{ +bool TheEndDimension::isValidSpawn(int x, int z) const { int topTile = level->getTopTile(x, z); if (topTile == 0) return false; @@ -75,17 +56,8 @@ bool TheEndDimension::isValidSpawn(int x, int z) const return Tile::tiles[topTile]->material->blocksMotion(); } -Pos *TheEndDimension::getSpawnPos() -{ - return new Pos(100, 50, 0); -} +Pos* TheEndDimension::getSpawnPos() { return new Pos(100, 50, 0); } -bool TheEndDimension::isFoggyAt(int x, int z) -{ - return true; -} +bool TheEndDimension::isFoggyAt(int x, int z) { return true; } -int TheEndDimension::getSpawnYPosition() -{ - return 50; -} \ No newline at end of file +int TheEndDimension::getSpawnYPosition() { return 50; } \ No newline at end of file diff --git a/Minecraft.World/Level/Dimensions/TheEndDimension.h b/Minecraft.World/Level/Dimensions/TheEndDimension.h index 95bd6980a..52e9824ee 100644 --- a/Minecraft.World/Level/Dimensions/TheEndDimension.h +++ b/Minecraft.World/Level/Dimensions/TheEndDimension.h @@ -1,20 +1,19 @@ #pragma once #include "Dimension.h" -class TheEndDimension : public Dimension -{ +class TheEndDimension : public Dimension { public: - virtual void init(); - virtual ChunkSource *createRandomLevelSource() const; - virtual float getTimeOfDay(__int64 time, float a) const; - virtual float *getSunriseColor(float td, float a); - virtual Vec3 *getFogColor(float td, float a) const; - virtual bool hasGround(); - virtual bool mayRespawn() const; - virtual bool isNaturalDimension(); - virtual float getCloudHeight(); - virtual bool isValidSpawn(int x, int z) const; - virtual Pos *getSpawnPos(); - virtual int getSpawnYPosition(); - virtual bool isFoggyAt(int x, int z); + virtual void init(); + virtual ChunkSource* createRandomLevelSource() const; + virtual float getTimeOfDay(__int64 time, float a) const; + virtual float* getSunriseColor(float td, float a); + virtual Vec3* getFogColor(float td, float a) const; + virtual bool hasGround(); + virtual bool mayRespawn() const; + virtual bool isNaturalDimension(); + virtual float getCloudHeight(); + virtual bool isValidSpawn(int x, int z) const; + virtual Pos* getSpawnPos(); + virtual int getSpawnYPosition(); + virtual bool isFoggyAt(int x, int z); }; diff --git a/Minecraft.World/Level/EmptyLevelChunk.cpp b/Minecraft.World/Level/EmptyLevelChunk.cpp index c0be1a7e4..a0fad8077 100644 --- a/Minecraft.World/Level/EmptyLevelChunk.cpp +++ b/Minecraft.World/Level/EmptyLevelChunk.cpp @@ -4,219 +4,163 @@ #include "../Headers/net.minecraft.world.phys.h" #include "EmptyLevelChunk.h" -EmptyLevelChunk::EmptyLevelChunk(Level *level, int x, int z) : LevelChunk(level,x,z) -{ - dontSave = true; - // Set this as fully post-processed, so we don't try and run post-processing on any edge chunks that will overlap into real chunks - terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; +EmptyLevelChunk::EmptyLevelChunk(Level* level, int x, int z) + : LevelChunk(level, x, z) { + dontSave = true; + // Set this as fully post-processed, so we don't try and run post-processing + // on any edge chunks that will overlap into real chunks + terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | + LevelChunk::sTerrainPostPostProcessed; } -EmptyLevelChunk::EmptyLevelChunk(Level *level, byteArray blocks, int x, int z): LevelChunk(level,blocks,x,z) -{ - dontSave = true; - delete [] blocks.data; - // Set this as fully post-processed, so we don't try and run post-processing on any edge chunks that will overlap into real chunks - terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; +EmptyLevelChunk::EmptyLevelChunk(Level* level, byteArray blocks, int x, int z) + : LevelChunk(level, blocks, x, z) { + dontSave = true; + delete[] blocks.data; + // Set this as fully post-processed, so we don't try and run post-processing + // on any edge chunks that will overlap into real chunks + terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | + LevelChunk::sTerrainPostPostProcessed; } -bool EmptyLevelChunk::isAt(int x, int z) -{ - return x == this->x && z == this->z; +bool EmptyLevelChunk::isAt(int x, int z) { + return x == this->x && z == this->z; } -int EmptyLevelChunk::getHeightmap(int x, int z) -{ - return 0; +int EmptyLevelChunk::getHeightmap(int x, int z) { return 0; } + +void EmptyLevelChunk::recalcBlockLights() {} + +void EmptyLevelChunk::recalcHeightmapOnly() {} + +void EmptyLevelChunk::recalcHeightmap() {} + +void EmptyLevelChunk::lightLava() {} + +int EmptyLevelChunk::getTile(int x, int y, int z) { return 0; } + +bool EmptyLevelChunk::setTileAndData(int x, int y, int z, int _tile, + int _data) { + return true; } -void EmptyLevelChunk::recalcBlockLights() -{ +bool EmptyLevelChunk::setTile(int x, int y, int z, int _tile) { return true; } + +int EmptyLevelChunk::getData(int x, int y, int z) { return 0; } + +bool EmptyLevelChunk::setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged) { + *maskedBitsChanged = true; + return false; } -void EmptyLevelChunk::recalcHeightmapOnly() -{ -} - -void EmptyLevelChunk::recalcHeightmap() -{ -} - -void EmptyLevelChunk::lightLava() -{ -} - -int EmptyLevelChunk::getTile(int x, int y, int z) -{ - return 0; -} - -bool EmptyLevelChunk::setTileAndData(int x, int y, int z, int _tile, int _data) -{ - return true; -} - -bool EmptyLevelChunk::setTile(int x, int y, int z, int _tile) -{ - return true; -} - -int EmptyLevelChunk::getData(int x, int y, int z) -{ - return 0; -} - -bool EmptyLevelChunk::setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged) -{ - *maskedBitsChanged = true; - return false; -} - -int EmptyLevelChunk::getBrightness(LightLayer::variety layer, int x, int y, int z) -{ - return 0; +int EmptyLevelChunk::getBrightness(LightLayer::variety layer, int x, int y, + int z) { + return 0; } // 4J added -void EmptyLevelChunk::getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z) -{ - for(int i = 0; i < 6; i++ ) - { - brightnesses[i] = 0; - } +void EmptyLevelChunk::getNeighbourBrightnesses(int* brightnesses, + LightLayer::variety layer, int x, + int y, int z) { + for (int i = 0; i < 6; i++) { + brightnesses[i] = 0; + } } -void EmptyLevelChunk::setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness) -{ +void EmptyLevelChunk::setBrightness(LightLayer::variety layer, int x, int y, + int z, int brightness) {} + +int EmptyLevelChunk::getRawBrightness(int x, int y, int z, int skyDampen) { + return 0; } -int EmptyLevelChunk::getRawBrightness(int x, int y, int z, int skyDampen) -{ - return 0; +void EmptyLevelChunk::addEntity(std::shared_ptr e) {} + +void EmptyLevelChunk::removeEntity(std::shared_ptr e) {} + +void EmptyLevelChunk::removeEntity(std::shared_ptr e, int yc) {} + +bool EmptyLevelChunk::isSkyLit(int x, int y, int z) { return false; } + +void EmptyLevelChunk::skyBrightnessChanged() {} + +std::shared_ptr EmptyLevelChunk::getTileEntity(int x, int y, + int z) { + return std::shared_ptr(); } -void EmptyLevelChunk::addEntity(std::shared_ptr e) -{ -} +void EmptyLevelChunk::addTileEntity(std::shared_ptr te) {} -void EmptyLevelChunk::removeEntity(std::shared_ptr e) -{ -} +void EmptyLevelChunk::setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity) {} -void EmptyLevelChunk::removeEntity(std::shared_ptr e, int yc) -{ -} +void EmptyLevelChunk::removeTileEntity(int x, int y, int z) {} -bool EmptyLevelChunk::isSkyLit(int x, int y, int z) -{ - return false; -} +void EmptyLevelChunk::load() {} -void EmptyLevelChunk::skyBrightnessChanged() -{ -} +void EmptyLevelChunk::unload(bool unloadTileEntities) // 4J - added parameter +{} -std::shared_ptr EmptyLevelChunk::getTileEntity(int x, int y, int z) -{ - return std::shared_ptr(); -} +void EmptyLevelChunk::markUnsaved() {} -void EmptyLevelChunk::addTileEntity(std::shared_ptr te) -{ -} +void EmptyLevelChunk::getEntities(std::shared_ptr except, AABB bb, + std::vector >& es) {} -void EmptyLevelChunk::setTileEntity(int x, int y, int z, std::shared_ptr tileEntity) -{ -} +void EmptyLevelChunk::getEntitiesOfClass( + const std::type_info& ec, AABB bb, + std::vector >& es) {} -void EmptyLevelChunk::removeTileEntity(int x, int y, int z) -{ -} +int EmptyLevelChunk::countEntities() { return 0; } -void EmptyLevelChunk::load() -{ -} +bool EmptyLevelChunk::shouldSave(bool force) { return false; } -void EmptyLevelChunk::unload(bool unloadTileEntities) // 4J - added parameter -{ -} +void EmptyLevelChunk::setBlocks(byteArray newBlocks, int sub) {} -void EmptyLevelChunk::markUnsaved() -{ -} - -void EmptyLevelChunk::getEntities(std::shared_ptr except, AABB bb, std::vector > &es) -{ -} - -void EmptyLevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB bb, std::vector > &es) -{ -} - -int EmptyLevelChunk::countEntities() -{ - return 0; -} - -bool EmptyLevelChunk::shouldSave(bool force) -{ - return false; -} - -void EmptyLevelChunk::setBlocks(byteArray newBlocks, int sub) -{ -} - -int EmptyLevelChunk::getBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting/* = true*/) -{ +int EmptyLevelChunk::getBlocksAndData(byteArray data, int x0, int y0, int z0, + int x1, int y1, int z1, int p, + bool includeLighting /* = true*/) { int xs = x1 - x0; int ys = y1 - y0; int zs = z1 - z0; int s = xs * ys * zs; int len; - if( includeLighting ) - { - len = s + s / 2 * 3; - } - else - { - len = s + s / 2; - } + if (includeLighting) { + len = s + s / 2 * 3; + } else { + len = s + s / 2; + } - - Arrays::fill(data, p, p + len, (uint8_t) 0); + Arrays::fill(data, p, p + len, (uint8_t)0); return len; } -int EmptyLevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting/* = true*/) -{ +int EmptyLevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, + int x1, int y1, int z1, int p, + bool includeLighting /* = true*/) { int xs = x1 - x0; int ys = y1 - y0; int zs = z1 - z0; int s = xs * ys * zs; - if( includeLighting ) - { - return s + s / 2 * 3; - } - else - { - return s + s / 2; - } + if (includeLighting) { + return s + s / 2 * 3; + } else { + return s + s / 2; + } } -bool EmptyLevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p) -{ - return false; +bool EmptyLevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, + int z0, int x1, int y1, int z1, + int p) { + return false; } -Random *EmptyLevelChunk::getRandom(__int64 l) -{ - return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + z * z * 4392871l + z * 389711) ^ l); -} - -bool EmptyLevelChunk::isEmpty() -{ - return true; +Random* EmptyLevelChunk::getRandom(__int64 l) { + return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + + z * z * 4392871l + z * 389711) ^ + l); } +bool EmptyLevelChunk::isEmpty() { return true; } diff --git a/Minecraft.World/Level/EmptyLevelChunk.h b/Minecraft.World/Level/EmptyLevelChunk.h index 4c5d2657a..6f32dfcd2 100644 --- a/Minecraft.World/Level/EmptyLevelChunk.h +++ b/Minecraft.World/Level/EmptyLevelChunk.h @@ -4,51 +4,61 @@ class Level; -class EmptyLevelChunk: public LevelChunk -{ +class EmptyLevelChunk : public LevelChunk { public: - using LevelChunk::getBlocksAndData; - using LevelChunk::getEntities; - using LevelChunk::getEntitiesOfClass; + using LevelChunk::getBlocksAndData; + using LevelChunk::getEntities; + using LevelChunk::getEntitiesOfClass; - EmptyLevelChunk(Level *level, int x, int z); - EmptyLevelChunk(Level *level, byteArray blocks, int x, int z); - bool isAt(int x, int z); - int getHeightmap(int x, int z); - void recalcBlockLights(); - void recalcHeightmapOnly(); - void recalcHeightmap(); - void lightLava(); - int getTile(int x, int y, int z); - bool setTileAndData(int x, int y, int z, int _tile, int _data); - bool setTile(int x, int y, int z, int _tile); - int getData(int x, int y, int z); - bool setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged); // 4J added mask - int getBrightness(LightLayer::variety layer, int x, int y, int z); - void getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z); // 4J added - void setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness); - int getRawBrightness(int x, int y, int z, int skyDampen); - void addEntity(std::shared_ptr e); - void removeEntity(std::shared_ptr e); - void removeEntity(std::shared_ptr e, int yc); - bool isSkyLit(int x, int y, int z); - void skyBrightnessChanged(); - std::shared_ptr getTileEntity(int x, int y, int z); - void addTileEntity(std::shared_ptr te); - void setTileEntity(int x, int y, int z, std::shared_ptr tileEntity); - void removeTileEntity(int x, int y, int z); - void load(); - void unload(bool unloadTileEntities) ; // 4J - added parameter - void markUnsaved(); - void getEntities(std::shared_ptr except, AABB bb, std::vector > &es); - void getEntitiesOfClass(const std::type_info& ec, AABB bb, std::vector > &es); - int countEntities(); - bool shouldSave(bool force); - void setBlocks(byteArray newBlocks, int sub); - int getBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting = true); // 4J - added includeLighting parameter - int setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting = true); // 4J - added includeLighting parameter - bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p); // 4J added - Random *getRandom(__int64 l); - bool isEmpty(); - virtual void reSyncLighting() {}; // 4J added + EmptyLevelChunk(Level* level, int x, int z); + EmptyLevelChunk(Level* level, byteArray blocks, int x, int z); + bool isAt(int x, int z); + int getHeightmap(int x, int z); + void recalcBlockLights(); + void recalcHeightmapOnly(); + void recalcHeightmap(); + void lightLava(); + int getTile(int x, int y, int z); + bool setTileAndData(int x, int y, int z, int _tile, int _data); + bool setTile(int x, int y, int z, int _tile); + int getData(int x, int y, int z); + bool setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged); // 4J added mask + int getBrightness(LightLayer::variety layer, int x, int y, int z); + void getNeighbourBrightnesses(int* brightnesses, LightLayer::variety layer, + int x, int y, int z); // 4J added + void setBrightness(LightLayer::variety layer, int x, int y, int z, + int brightness); + int getRawBrightness(int x, int y, int z, int skyDampen); + void addEntity(std::shared_ptr e); + void removeEntity(std::shared_ptr e); + void removeEntity(std::shared_ptr e, int yc); + bool isSkyLit(int x, int y, int z); + void skyBrightnessChanged(); + std::shared_ptr getTileEntity(int x, int y, int z); + void addTileEntity(std::shared_ptr te); + void setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity); + void removeTileEntity(int x, int y, int z); + void load(); + void unload(bool unloadTileEntities); // 4J - added parameter + void markUnsaved(); + void getEntities(std::shared_ptr except, AABB bb, + std::vector >& es); + void getEntitiesOfClass(const std::type_info& ec, AABB bb, + std::vector >& es); + int countEntities(); + bool shouldSave(bool force); + void setBlocks(byteArray newBlocks, int sub); + int getBlocksAndData( + byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, + bool includeLighting = true); // 4J - added includeLighting parameter + int setBlocksAndData( + byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, + bool includeLighting = true); // 4J - added includeLighting parameter + bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, + int y1, int z1, int p); // 4J added + Random* getRandom(__int64 l); + bool isEmpty(); + virtual void reSyncLighting() {}; // 4J added }; diff --git a/Minecraft.World/Level/Events/LevelEvent.h b/Minecraft.World/Level/Events/LevelEvent.h index c78c35698..c9fea56e8 100644 --- a/Minecraft.World/Level/Events/LevelEvent.h +++ b/Minecraft.World/Level/Events/LevelEvent.h @@ -1,15 +1,14 @@ #pragma once // 4J - brought forward new sound events from 1.2.3 -class LevelEvent -{ +class LevelEvent { public: static const int SOUND_CLICK = 1000; static const int SOUND_CLICK_FAIL = 1001; static const int SOUND_LAUNCH = 1002; static const int SOUND_OPEN_DOOR = 1003; static const int SOUND_FIZZ = 1004; - static const int SOUND_PLAY_RECORDING = 1005; + static const int SOUND_PLAY_RECORDING = 1005; static const int SOUND_GHAST_WARNING = 1007; static const int SOUND_GHAST_FIREBALL = 1008; @@ -18,16 +17,16 @@ public: static const int SOUND_ZOMBIE_WOODEN_DOOR = 1010; static const int SOUND_ZOMBIE_IRON_DOOR = 1011; static const int SOUND_ZOMBIE_DOOR_CRASH = 1012; - static const int SOUND_WITHER_BOSS_SPAWN = 1013; - static const int SOUND_WITHER_BOSS_SHOOT = 1014; - static const int SOUND_BAT_LIFTOFF = 1015; - static const int SOUND_ZOMBIE_INFECTED = 1016; - static const int SOUND_ZOMBIE_CONVERTED = 1017; - static const int SOUND_DRAGON_DEATH = 1018; + static const int SOUND_WITHER_BOSS_SPAWN = 1013; + static const int SOUND_WITHER_BOSS_SHOOT = 1014; + static const int SOUND_BAT_LIFTOFF = 1015; + static const int SOUND_ZOMBIE_INFECTED = 1016; + static const int SOUND_ZOMBIE_CONVERTED = 1017; + static const int SOUND_DRAGON_DEATH = 1018; - static const int SOUND_ANVIL_BROKEN = 1020; - static const int SOUND_ANVIL_USED = 1021; - static const int SOUND_ANVIL_LAND = 1022; + static const int SOUND_ANVIL_BROKEN = 1020; + static const int SOUND_ANVIL_USED = 1021; + static const int SOUND_ANVIL_LAND = 1022; static const int PARTICLES_SHOOT = 2000; static const int PARTICLES_DESTROY_BLOCK = 2001; @@ -35,7 +34,8 @@ public: static const int PARTICLES_EYE_OF_ENDER_DEATH = 2003; static const int PARTICLES_MOBTILE_SPAWN = 2004; - //static const int ENDERDRAGON_KILLED = 9000; // 4J Added to signal the the enderdragon was killed - static const int ENDERDRAGON_FIREBALL_SPLASH = 9001; - static const int END_EGG_TELEPORT = 9002; + // static const int ENDERDRAGON_KILLED = 9000; // 4J Added to signal the the + // enderdragon was killed + static const int ENDERDRAGON_FIREBALL_SPLASH = 9001; + static const int END_EGG_TELEPORT = 9002; }; \ No newline at end of file diff --git a/Minecraft.World/Level/Events/LevelListener.h b/Minecraft.World/Level/Events/LevelListener.h index d2597dd45..d4e6e4b5e 100644 --- a/Minecraft.World/Level/Events/LevelListener.h +++ b/Minecraft.World/Level/Events/LevelListener.h @@ -1,40 +1,52 @@ #pragma once - class TileEntity; #include "../../Player/Player.h" #include "../../Util/ParticleTypes.h" -class LevelListener -{ +class LevelListener { public: - virtual void tileChanged(int x, int y, int z) = 0; + virtual void tileChanged(int x, int y, int z) = 0; - virtual void tileLightChanged(int x, int y, int z) = 0; + virtual void tileLightChanged(int x, int y, int z) = 0; - virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) = 0; // 4J - added level param + virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level) = 0; // 4J - added level param - virtual void allChanged() = 0; + virtual void allChanged() = 0; - //virtual void playSound(const std::wstring& name, double x, double y, double z, float volume, float pitch) = 0; - virtual void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f) = 0; - virtual void playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f) = 0; + // virtual void playSound(const std::wstring& name, double x, double y, + // double z, float volume, float pitch) = 0; + virtual void playSound(int iSound, double x, double y, double z, + float volume, float pitch, + float fSoundClipDist = 16.0f) = 0; + virtual void playSound(std::shared_ptr entity, int iSound, double x, + double y, double z, float volume, float pitch, + float fSoundClipDist = 16.0f) = 0; - // 4J removed - virtual void addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) = 0; + // 4J removed - virtual void addParticle(const std::wstring& name, double x, + // double y, double z, double xa, double ya, double za) = 0; - virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za) = 0; // 4J added + virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, + double xa, double ya, double za) = 0; // 4J added - virtual void entityAdded(std::shared_ptr entity) = 0; + virtual void entityAdded(std::shared_ptr entity) = 0; - virtual void entityRemoved(std::shared_ptr entity) = 0; + virtual void entityRemoved(std::shared_ptr entity) = 0; - virtual void playerRemoved(std::shared_ptr entity) = 0; // 4J added - for when a player is removed from the level's player array, not just the entity storage + virtual void playerRemoved( + std::shared_ptr + entity) = 0; // 4J added - for when a player is removed from the + // level's player array, not just the entity storage - virtual void skyColorChanged() = 0; + virtual void skyColorChanged() = 0; - virtual void playStreamingMusic(const std::wstring& name, int x, int y, int z) = 0; + virtual void playStreamingMusic(const std::wstring& name, int x, int y, + int z) = 0; - virtual void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) = 0; + virtual void levelEvent(std::shared_ptr source, int type, int x, + int y, int z, int data) = 0; - virtual void destroyTileProgress(int id, int x, int y, int z, int progress) = 0; + virtual void destroyTileProgress(int id, int x, int y, int z, + int progress) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Level/Events/LevelObjectInputStream.h b/Minecraft.World/Level/Events/LevelObjectInputStream.h index 41f3fc8f9..58a7f3d89 100644 --- a/Minecraft.World/Level/Events/LevelObjectInputStream.h +++ b/Minecraft.World/Level/Events/LevelObjectInputStream.h @@ -20,7 +20,8 @@ class LevelObjectInputStream : ObjectInputStream } protected: - ObjectStreamClass readClassDescriptor() // 4J - throws IOException, ClassNotFoundException + ObjectStreamClass readClassDescriptor() // 4J - throws IOException, +ClassNotFoundException { ObjectStreamClass osc = super.readClassDescriptor(); diff --git a/Minecraft.World/Level/Events/VillageSiege.cpp b/Minecraft.World/Level/Events/VillageSiege.cpp index d8cfe8952..97c9b6646 100644 --- a/Minecraft.World/Level/Events/VillageSiege.cpp +++ b/Minecraft.World/Level/Events/VillageSiege.cpp @@ -5,165 +5,156 @@ #include "../../Headers/net.minecraft.world.level.h" #include "VillageSiege.h" -VillageSiege::VillageSiege(Level *level) -{ - hasSetupSiege = false; - siegeState = SIEGE_NOT_INITED; - siegeCount = 0; - nextSpawnTime = 0; - village = std::weak_ptr(); - spawnX = spawnY = spawnZ = 0; +VillageSiege::VillageSiege(Level* level) { + hasSetupSiege = false; + siegeState = SIEGE_NOT_INITED; + siegeCount = 0; + nextSpawnTime = 0; + village = std::weak_ptr(); + spawnX = spawnY = spawnZ = 0; - this->level = level; + this->level = level; } -void VillageSiege::tick() -{ - bool debug = false; - if (debug) - { - if (siegeState == SIEGE_DONE) - { - siegeCount = 100; - return; - } - // return; - } - else - { - if (level->isDay()) - { - siegeState = SIEGE_CAN_ACTIVATE; - return; - } +void VillageSiege::tick() { + bool debug = false; + if (debug) { + if (siegeState == SIEGE_DONE) { + siegeCount = 100; + return; + } + // return; + } else { + if (level->isDay()) { + siegeState = SIEGE_CAN_ACTIVATE; + return; + } - if (siegeState == SIEGE_DONE) return; + if (siegeState == SIEGE_DONE) return; - if (siegeState == SIEGE_CAN_ACTIVATE) - { - float timeOfDay = level->getTimeOfDay(0); - if (timeOfDay < 0.50 || timeOfDay > 0.501) return; - siegeState = level->random->nextInt(10) == 0 ? SIEGE_TONIGHT : SIEGE_DONE; - hasSetupSiege = false; - if (siegeState == SIEGE_DONE) return; - } - } + if (siegeState == SIEGE_CAN_ACTIVATE) { + float timeOfDay = level->getTimeOfDay(0); + if (timeOfDay < 0.50 || timeOfDay > 0.501) return; + siegeState = + level->random->nextInt(10) == 0 ? SIEGE_TONIGHT : SIEGE_DONE; + hasSetupSiege = false; + if (siegeState == SIEGE_DONE) return; + } + } - if (!hasSetupSiege) - { - if (tryToSetupSiege()) hasSetupSiege = true; - else return; - } + if (!hasSetupSiege) { + if (tryToSetupSiege()) + hasSetupSiege = true; + else + return; + } - // Siege! - if (nextSpawnTime > 0) - { - --nextSpawnTime; - return; - } - - nextSpawnTime = 2; // 50 + level.random.nextInt(100); - if (siegeCount > 0) - { - trySpawn(); - --siegeCount; - } - else - { - siegeState = SIEGE_DONE; - } + // Siege! + if (nextSpawnTime > 0) { + --nextSpawnTime; + return; + } + nextSpawnTime = 2; // 50 + level.random.nextInt(100); + if (siegeCount > 0) { + trySpawn(); + --siegeCount; + } else { + siegeState = SIEGE_DONE; + } } -bool VillageSiege::tryToSetupSiege() -{ - std::vector > *players = &level->players; - //for (Player player : players) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) - { - std::shared_ptr player = *it; - std::shared_ptr _village = level->villages->getClosestVillage((int) player->x, (int) player->y, (int) player->z, 1); - village = _village; +bool VillageSiege::tryToSetupSiege() { + std::vector >* players = &level->players; + // for (Player player : players) + for (AUTO_VAR(it, players->begin()); it != players->end(); ++it) { + std::shared_ptr player = *it; + std::shared_ptr _village = level->villages->getClosestVillage( + (int)player->x, (int)player->y, (int)player->z, 1); + village = _village; - if (_village == NULL) continue; - if (_village->getDoorCount() < 10) continue; - if (_village->getStableAge() < 20) continue; - if (_village->getPopulationSize() < 20) continue; + if (_village == NULL) continue; + if (_village->getDoorCount() < 10) continue; + if (_village->getStableAge() < 20) continue; + if (_village->getPopulationSize() < 20) continue; - // setup siege origin - Pos *center = _village->getCenter(); - float radius = _village->getRadius(); + // setup siege origin + Pos* center = _village->getCenter(); + float radius = _village->getRadius(); - bool overlaps = false; - for (int i = 0; i < 10; ++i) - { - spawnX = center->x + (int) (Mth::cos(level->random->nextFloat() * PI * 2.f) * radius * 0.9); - spawnY = center->y; - spawnZ = center->z + (int) (Mth::sin(level->random->nextFloat() * PI * 2.f) * radius * 0.9); - overlaps = false; - std::vector > *villages = level->villages->getVillages(); - //for (Village v : level.villages.getVillages()) - for(AUTO_VAR(itV, villages->begin()); itV != villages->end(); ++itV) - { - std::shared_ptrv = *itV; - if (v == _village) continue; - if (v->isInside(spawnX, spawnY, spawnZ)) - { - overlaps = true; - break; - } - } - if (!overlaps) break; - } - if (overlaps) return false; + bool overlaps = false; + for (int i = 0; i < 10; ++i) { + spawnX = center->x + + (int)(Mth::cos(level->random->nextFloat() * PI * 2.f) * + radius * 0.9); + spawnY = center->y; + spawnZ = center->z + + (int)(Mth::sin(level->random->nextFloat() * PI * 2.f) * + radius * 0.9); + overlaps = false; + std::vector >* villages = + level->villages->getVillages(); + // for (Village v : level.villages.getVillages()) + for (AUTO_VAR(itV, villages->begin()); itV != villages->end(); + ++itV) { + std::shared_ptr v = *itV; + if (v == _village) continue; + if (v->isInside(spawnX, spawnY, spawnZ)) { + overlaps = true; + break; + } + } + if (!overlaps) break; + } + if (overlaps) return false; - Vec3 *spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); - if (spawnPos == NULL) continue; + Vec3* spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); + if (spawnPos == NULL) continue; - nextSpawnTime = 0; - siegeCount = 20; - return true; - } - return false; + nextSpawnTime = 0; + siegeCount = 20; + return true; + } + return false; } -bool VillageSiege::trySpawn() -{ - Vec3 *spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); - if (spawnPos == NULL) return false; - std::shared_ptr mob; - //try - { - mob = std::shared_ptr( new Zombie(level) ); - mob->finalizeMobSpawn(); - mob->setVillager(false); - } - //catch (Exception e) { - // e.printStackTrace(); - // return false; - //} - mob->moveTo(spawnPos->x, spawnPos->y, spawnPos->z, level->random->nextFloat() * 360, 0); - level->addEntity(mob); - std::shared_ptr _village = village.lock(); - if( _village == NULL ) return false; +bool VillageSiege::trySpawn() { + Vec3* spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); + if (spawnPos == NULL) return false; + std::shared_ptr mob; + // try + { + mob = std::shared_ptr(new Zombie(level)); + mob->finalizeMobSpawn(); + mob->setVillager(false); + } + // catch (Exception e) { + // e.printStackTrace(); + // return false; + // } + mob->moveTo(spawnPos->x, spawnPos->y, spawnPos->z, + level->random->nextFloat() * 360, 0); + level->addEntity(mob); + std::shared_ptr _village = village.lock(); + if (_village == NULL) return false; - Pos *center = _village->getCenter(); - mob->restrictTo(center->x, center->y, center->z, _village->getRadius()); - return true; + Pos* center = _village->getCenter(); + mob->restrictTo(center->x, center->y, center->z, _village->getRadius()); + return true; } -Vec3 *VillageSiege::findRandomSpawnPos(int x, int y, int z) -{ - std::shared_ptr _village = village.lock(); - if( _village == NULL ) return NULL; +Vec3* VillageSiege::findRandomSpawnPos(int x, int y, int z) { + std::shared_ptr _village = village.lock(); + if (_village == NULL) return NULL; - for (int i = 0; i < 10; ++i) - { - int xx = x + level->random->nextInt(16) - 8; - int yy = y + level->random->nextInt(6) - 3; - int zz = z + level->random->nextInt(16) - 8; - if (!_village->isInside(xx, yy, zz)) continue; - if (MobSpawner::isSpawnPositionOk(MobCategory::monster, level, xx, yy, zz)) return Vec3::newTemp(xx, yy, zz); - } - return NULL; + for (int i = 0; i < 10; ++i) { + int xx = x + level->random->nextInt(16) - 8; + int yy = y + level->random->nextInt(6) - 3; + int zz = z + level->random->nextInt(16) - 8; + if (!_village->isInside(xx, yy, zz)) continue; + if (MobSpawner::isSpawnPositionOk(MobCategory::monster, level, xx, yy, + zz)) + return Vec3::newTemp(xx, yy, zz); + } + return NULL; } \ No newline at end of file diff --git a/Minecraft.World/Level/Events/VillageSiege.h b/Minecraft.World/Level/Events/VillageSiege.h index c2b67c5a3..f6a978824 100644 --- a/Minecraft.World/Level/Events/VillageSiege.h +++ b/Minecraft.World/Level/Events/VillageSiege.h @@ -1,28 +1,27 @@ #pragma once -class VillageSiege -{ +class VillageSiege { private: - Level *level; - bool hasSetupSiege; - int siegeState; - int siegeCount; - int nextSpawnTime; - std::weak_ptr village; - int spawnX, spawnY, spawnZ; + Level* level; + bool hasSetupSiege; + int siegeState; + int siegeCount; + int nextSpawnTime; + std::weak_ptr village; + int spawnX, spawnY, spawnZ; - static const int SIEGE_NOT_INITED = -1; - static const int SIEGE_CAN_ACTIVATE = 0; - static const int SIEGE_TONIGHT = 1; - static const int SIEGE_DONE = 2; + static const int SIEGE_NOT_INITED = -1; + static const int SIEGE_CAN_ACTIVATE = 0; + static const int SIEGE_TONIGHT = 1; + static const int SIEGE_DONE = 2; public: - VillageSiege(Level *level); + VillageSiege(Level* level); - void tick(); + void tick(); private: - bool tryToSetupSiege(); - bool trySpawn(); - Vec3 *findRandomSpawnPos(int x, int y, int z); + bool tryToSetupSiege(); + bool trySpawn(); + Vec3* findRandomSpawnPos(int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Explosion.cpp b/Minecraft.World/Level/Explosion.cpp index ba66c6739..387865028 100644 --- a/Minecraft.World/Level/Explosion.cpp +++ b/Minecraft.World/Level/Explosion.cpp @@ -8,258 +8,263 @@ #include "Explosion.h" #include "../Util/SoundTypes.h" -Explosion::Explosion(Level *level, std::shared_ptr source, double x, double y, double z, float r) -{ - fire = false; - random = new Random(); +Explosion::Explosion(Level* level, std::shared_ptr source, double x, + double y, double z, float r) { + fire = false; + random = new Random(); - this->level = level; - this->source = source; - this->r = r; - this->x = x; - this->y = y; - this->z = z; + this->level = level; + this->source = source; + this->r = r; + this->x = x; + this->y = y; + this->z = z; - destroyBlocks = true; - size = 16; + destroyBlocks = true; + size = 16; } -Explosion::~Explosion() -{ - delete random; - for(AUTO_VAR(it, hitPlayers.begin()); it != hitPlayers.end(); ++it) - { - delete it->second; - } +Explosion::~Explosion() { + delete random; + for (AUTO_VAR(it, hitPlayers.begin()); it != hitPlayers.end(); ++it) { + delete it->second; + } } -void Explosion::explode() -{ - float oR = r; +void Explosion::explode() { + float oR = r; - int size = 16; - for (int xx = 0; xx < size; xx++) - { - for (int yy = 0; yy < size; yy++) - { - for (int zz = 0; zz < size; zz++) - { - if ((xx != 0 && xx != size - 1) && (yy != 0 && yy != size - 1) && (zz != 0 && zz != size - 1)) continue; + int size = 16; + for (int xx = 0; xx < size; xx++) { + for (int yy = 0; yy < size; yy++) { + for (int zz = 0; zz < size; zz++) { + if ((xx != 0 && xx != size - 1) && + (yy != 0 && yy != size - 1) && (zz != 0 && zz != size - 1)) + continue; - double xd = xx / (size - 1.0f) * 2 - 1; - double yd = yy / (size - 1.0f) * 2 - 1; - double zd = zz / (size - 1.0f) * 2 - 1; - double d = sqrt(xd * xd + yd * yd + zd * zd); + double xd = xx / (size - 1.0f) * 2 - 1; + double yd = yy / (size - 1.0f) * 2 - 1; + double zd = zz / (size - 1.0f) * 2 - 1; + double d = sqrt(xd * xd + yd * yd + zd * zd); - xd /= d; - yd /= d; - zd /= d; + xd /= d; + yd /= d; + zd /= d; - float remainingPower = r * (0.7f + level->random->nextFloat() * 0.6f); - double xp = x; - double yp = y; - double zp = z; + float remainingPower = + r * (0.7f + level->random->nextFloat() * 0.6f); + double xp = x; + double yp = y; + double zp = z; - float stepSize = 0.3f; - while (remainingPower > 0) - { - int xt = Mth::floor(xp); - int yt = Mth::floor(yp); - int zt = Mth::floor(zp); - int t = level->getTile(xt, yt, zt); - if (t > 0) - { - remainingPower -= (Tile::tiles[t]->getExplosionResistance(source) + 0.3f) * stepSize; - } - if (remainingPower > 0) - { - toBlow.insert(TilePos(xt, yt, zt)); - } + float stepSize = 0.3f; + while (remainingPower > 0) { + int xt = Mth::floor(xp); + int yt = Mth::floor(yp); + int zt = Mth::floor(zp); + int t = level->getTile(xt, yt, zt); + if (t > 0) { + remainingPower -= + (Tile::tiles[t]->getExplosionResistance(source) + + 0.3f) * + stepSize; + } + if (remainingPower > 0) { + toBlow.insert(TilePos(xt, yt, zt)); + } - xp += xd * stepSize; - yp += yd * stepSize; - zp += zd * stepSize; - remainingPower -= stepSize * 0.75f; - } - // if (xd*xd+yd*yd+zd*zd>1) continue; - } - } - } + xp += xd * stepSize; + yp += yd * stepSize; + zp += zd * stepSize; + remainingPower -= stepSize * 0.75f; + } + // if (xd*xd+yd*yd+zd*zd>1) continue; + } + } + } - r *= 2.0f; - int x0 = Mth::floor(x - r - 1); - int x1 = Mth::floor(x + r + 1); - int y0 = Mth::floor(y - r - 1); - int y1 = Mth::floor(y + r + 1); - int z0 = Mth::floor(z - r - 1); - int z1 = Mth::floor(z + r + 1); + r *= 2.0f; + int x0 = Mth::floor(x - r - 1); + int x1 = Mth::floor(x + r + 1); + int y0 = Mth::floor(y - r - 1); + int y1 = Mth::floor(y + r + 1); + int z0 = Mth::floor(z - r - 1); + int z1 = Mth::floor(z + r + 1); - // Fix for 360 #123866 - [CRASH] TU13: Code: Compliance: Placing the TNT next to Ender Crystals will crash the title after a certain amount of time. - // If we explode something next to an EnderCrystal then it creates a new explosion that overwrites the shared vector in the level - // So copy it here instead of directly using the shared one - std::vector > *levelEntities = level->getEntities(source, AABB::newTemp(x0, y0, z0, x1, y1, z1)); - std::vector > entities(levelEntities->begin(), levelEntities->end() ); - Vec3 *center = Vec3::newTemp(x, y, z); + // Fix for 360 #123866 - [CRASH] TU13: Code: Compliance: Placing the TNT + // next to Ender Crystals will crash the title after a certain amount of + // time. If we explode something next to an EnderCrystal then it creates a + // new explosion that overwrites the shared vector in the level So copy it + // here instead of directly using the shared one + std::vector >* levelEntities = + level->getEntities(source, AABB::newTemp(x0, y0, z0, x1, y1, z1)); + std::vector > entities(levelEntities->begin(), + levelEntities->end()); + Vec3* center = Vec3::newTemp(x, y, z); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); + AUTO_VAR(itEnd, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); - // 4J Stu - If the entity is not in a block that would be blown up, then they should not be damaged - // Fix for #46606 - TU5: Content: Gameplay: The player can be damaged and killed by explosions behind obsidian walls - bool canDamage = false; - for(AUTO_VAR(it2, toBlow.begin()); it2 != toBlow.end(); ++it2) - { - if(e->bb->intersects(it2->x,it2->y,it2->z,it2->x + 1,it2->y + 1,it2->z + 1)) - { - canDamage = true; - break; - } - } + // 4J Stu - If the entity is not in a block that would be blown up, then + // they should not be damaged Fix for #46606 - TU5: Content: Gameplay: + // The player can be damaged and killed by explosions behind obsidian + // walls + bool canDamage = false; + for (AUTO_VAR(it2, toBlow.begin()); it2 != toBlow.end(); ++it2) { + if (e->bb->intersects(it2->x, it2->y, it2->z, it2->x + 1, + it2->y + 1, it2->z + 1)) { + canDamage = true; + break; + } + } - double dist = e->distanceTo(x, y, z) / r; - if (dist <= 1) - { - double xa = e->x - x; - double ya = e->y + e->getHeadHeight() - y; - double za = e->z - z; + double dist = e->distanceTo(x, y, z) / r; + if (dist <= 1) { + double xa = e->x - x; + double ya = e->y + e->getHeadHeight() - y; + double za = e->z - z; - double da = sqrt(xa * xa + ya * ya + za * za); + double da = sqrt(xa * xa + ya * ya + za * za); - // 4J Stu - Added this check to remove divide by zero errors (or rather the issues caused by - // the values being set to NaN and used in comparisons a bit later on e.g. fireball) - if( da == 0 ) - { - xa = ya = za = 0.0; - } - else - { - xa /= da; - ya /= da; - za /= da; - } + // 4J Stu - Added this check to remove divide by zero errors (or + // rather the issues caused by the values being set to NaN and used + // in comparisons a bit later on e.g. fireball) + if (da == 0) { + xa = ya = za = 0.0; + } else { + xa /= da; + ya /= da; + za /= da; + } - double sp = level->getSeenPercent(center, e->bb); - double pow = (1 - dist) * sp; - if(canDamage) e->hurt(DamageSource::explosion, (int) ((pow * pow + pow) / 2 * 8 * r + 1)); + double sp = level->getSeenPercent(center, e->bb); + double pow = (1 - dist) * sp; + if (canDamage) + e->hurt(DamageSource::explosion, + (int)((pow * pow + pow) / 2 * 8 * r + 1)); - double push = pow; - e->xd += xa * push; - e->yd += ya * push; - e->zd += za * push; + double push = pow; + e->xd += xa * push; + e->yd += ya * push; + e->zd += za * push; - std::shared_ptr player = std::dynamic_pointer_cast(e); - if (player != NULL) - { - //app.DebugPrintf("Adding player knockback (%f,%f,%f)\n", xa * pow, ya * pow, za * pow); - hitPlayers.insert( playerVec3Map::value_type( player, Vec3::newPermanent(xa * pow, ya * pow, za * pow))); - } - } - } - r = oR; + std::shared_ptr player = + std::dynamic_pointer_cast(e); + if (player != NULL) { + // app.DebugPrintf("Adding player knockback (%f,%f,%f)\n", xa * + // pow, ya * pow, za * pow); + hitPlayers.insert(playerVec3Map::value_type( + player, Vec3::newPermanent(xa * pow, ya * pow, za * pow))); + } + } + } + r = oR; } - -void Explosion::finalizeExplosion(bool generateParticles, std::vector *toBlowDirect/*=NULL*/) // 4J - added toBlowDirect parameter +void Explosion::finalizeExplosion( + bool generateParticles, + std::vector* + toBlowDirect /*=NULL*/) // 4J - added toBlowDirect parameter { - level->playSound(x, y, z, eSoundType_RANDOM_EXPLODE, 4, (1 + (level->random->nextFloat() - level->random->nextFloat()) * 0.2f) * 0.7f); - level->addParticle(eParticleType_hugeexplosion, x, y, z, 0, 0, 0); + level->playSound( + x, y, z, eSoundType_RANDOM_EXPLODE, 4, + (1 + (level->random->nextFloat() - level->random->nextFloat()) * 0.2f) * + 0.7f); + level->addParticle(eParticleType_hugeexplosion, x, y, z, 0, 0, 0); - // 4J - use pointer to vector directly passed in if this is available - used to speed up calling this from an incoming packet - std::vector *toBlowArray = toBlowDirect ? toBlowDirect : new std::vector( toBlow.begin(), toBlow.end() ); - //toBlowArray.addAll(toBlow); - // TODO 4J Stu - Reverse iterator - PIXBeginNamedEvent(0,"Finalizing explosion size %d",toBlow.size()); - app.DebugPrintf("Finalizing explosion size %d\n",toBlow.size()); - static const int MAX_EXPLODE_PARTICLES = 50; - // 4J - try and make at most MAX_EXPLODE_PARTICLES pairs of particles - int fraction = (int)toBlowArray->size() / MAX_EXPLODE_PARTICLES; - if( fraction == 0 ) fraction = 1; - size_t j = toBlowArray->size() - 1; - //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) - { - TilePos *tp = &(*it); //&toBlowArray->at(j); - int xt = tp->x; - int yt = tp->y; - int zt = tp->z; - // if (xt >= 0 && yt >= 0 && zt >= 0 && xt < width && yt < depth && - // zt < height) { - int t = level->getTile(xt, yt, zt); + // 4J - use pointer to vector directly passed in if this is available - used + // to speed up calling this from an incoming packet + std::vector* toBlowArray = + toBlowDirect ? toBlowDirect + : new std::vector(toBlow.begin(), toBlow.end()); + // toBlowArray.addAll(toBlow); + // TODO 4J Stu - Reverse iterator + PIXBeginNamedEvent(0, "Finalizing explosion size %d", toBlow.size()); + app.DebugPrintf("Finalizing explosion size %d\n", toBlow.size()); + static const int MAX_EXPLODE_PARTICLES = 50; + // 4J - try and make at most MAX_EXPLODE_PARTICLES pairs of particles + int fraction = (int)toBlowArray->size() / MAX_EXPLODE_PARTICLES; + if (fraction == 0) fraction = 1; + size_t j = toBlowArray->size() - 1; + // for (size_t j = toBlowArray->size() - 1; j >= 0; j--) + for (AUTO_VAR(it, toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) { + TilePos* tp = &(*it); //&toBlowArray->at(j); + int xt = tp->x; + int yt = tp->y; + int zt = tp->z; + // if (xt >= 0 && yt >= 0 && zt >= 0 && xt < width && yt < depth && + // zt < height) { + int t = level->getTile(xt, yt, zt); - if (generateParticles) - { - if( ( j % fraction ) == 0 ) - { - double xa = xt + level->random->nextFloat(); - double ya = yt + level->random->nextFloat(); - double za = zt + level->random->nextFloat(); + if (generateParticles) { + if ((j % fraction) == 0) { + double xa = xt + level->random->nextFloat(); + double ya = yt + level->random->nextFloat(); + double za = zt + level->random->nextFloat(); - double xd = xa - x; - double yd = ya - y; - double zd = za - z; + double xd = xa - x; + double yd = ya - y; + double zd = za - z; - double dd = sqrt(xd * xd + yd * yd + zd * zd); + double dd = sqrt(xd * xd + yd * yd + zd * zd); - xd /= dd; - yd /= dd; - zd /= dd; + xd /= dd; + yd /= dd; + zd /= dd; - double speed = 0.5 / (dd / r + 0.1); - speed *= (level->random->nextFloat() * level->random->nextFloat() + 0.3f); - xd *= speed; - yd *= speed; - zd *= speed; + double speed = 0.5 / (dd / r + 0.1); + speed *= + (level->random->nextFloat() * level->random->nextFloat() + + 0.3f); + xd *= speed; + yd *= speed; + zd *= speed; - level->addParticle(eParticleType_explode, (xa + x * 1) / 2, (ya + y * 1) / 2, (za + z * 1) / 2, xd, yd, zd); - level->addParticle(eParticleType_smoke, xa, ya, za, xd, yd, zd); - } - } + level->addParticle(eParticleType_explode, (xa + x * 1) / 2, + (ya + y * 1) / 2, (za + z * 1) / 2, xd, yd, + zd); + level->addParticle(eParticleType_smoke, xa, ya, za, xd, yd, zd); + } + } - if (t > 0) - { - Tile::tiles[t]->spawnResources(level, xt, yt, zt, level->getData(xt, yt, zt), 0.3f, 0); - level->setTile(xt, yt, zt, 0); - Tile::tiles[t]->wasExploded(level, xt, yt, zt); - } - // } + if (t > 0) { + Tile::tiles[t]->spawnResources(level, xt, yt, zt, + level->getData(xt, yt, zt), 0.3f, 0); + level->setTile(xt, yt, zt, 0); + Tile::tiles[t]->wasExploded(level, xt, yt, zt); + } + // } - --j; - } + --j; + } - if (fire) - { - //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) - { - TilePos *tp = &(*it); //&toBlowArray->at(j); - int xt = tp->x; - int yt = tp->y; - int zt = tp->z; - int t = level->getTile(xt, yt, zt); - int b = level->getTile(xt, yt - 1, zt); - if (t == 0 && Tile::solid[b] && random->nextInt(3) == 0) - { - level->setTile(xt, yt, zt, Tile::fire_Id); - } - } - } + if (fire) { + // for (size_t j = toBlowArray->size() - 1; j >= 0; j--) + for (AUTO_VAR(it, toBlowArray->rbegin()); it != toBlowArray->rend(); + ++it) { + TilePos* tp = &(*it); //&toBlowArray->at(j); + int xt = tp->x; + int yt = tp->y; + int zt = tp->z; + int t = level->getTile(xt, yt, zt); + int b = level->getTile(xt, yt - 1, zt); + if (t == 0 && Tile::solid[b] && random->nextInt(3) == 0) { + level->setTile(xt, yt, zt, Tile::fire_Id); + } + } + } - PIXEndNamedEvent(); - if( toBlowDirect == NULL ) delete toBlowArray; + PIXEndNamedEvent(); + if (toBlowDirect == NULL) delete toBlowArray; } -Explosion::playerVec3Map *Explosion::getHitPlayers() -{ - return &hitPlayers; -} +Explosion::playerVec3Map* Explosion::getHitPlayers() { return &hitPlayers; } -Vec3 *Explosion::getHitPlayerKnockback( std::shared_ptr player ) -{ - AUTO_VAR(it, hitPlayers.find(player)); +Vec3* Explosion::getHitPlayerKnockback(std::shared_ptr player) { + AUTO_VAR(it, hitPlayers.find(player)); - if(it == hitPlayers.end() ) return Vec3::newTemp(0.0,0.0,0.0); + if (it == hitPlayers.end()) return Vec3::newTemp(0.0, 0.0, 0.0); - return it->second; + return it->second; } \ No newline at end of file diff --git a/Minecraft.World/Level/Explosion.h b/Minecraft.World/Level/Explosion.h index ca1cb3357..39c1e96a6 100644 --- a/Minecraft.World/Level/Explosion.h +++ b/Minecraft.World/Level/Explosion.h @@ -5,38 +5,42 @@ class Random; class Level; -class Explosion -{ +class Explosion { public: - bool fire; - bool destroyBlocks; + bool fire; + bool destroyBlocks; private: - int size; + int size; - Random *random; - Level *level; + Random* random; + Level* level; public: - double x, y, z; - std::shared_ptr source; - float r; + double x, y, z; + std::shared_ptr source; + float r; + + std::unordered_set toBlow; - std::unordered_set toBlow; - private: - typedef std::unordered_map, Vec3 * , PlayerKeyHash, PlayerKeyEq> playerVec3Map; - playerVec3Map hitPlayers; + typedef std::unordered_map, Vec3*, PlayerKeyHash, + PlayerKeyEq> + playerVec3Map; + playerVec3Map hitPlayers; public: - Explosion(Level *level, std::shared_ptr source, double x, double y, double z, float r); - ~Explosion(); + Explosion(Level* level, std::shared_ptr source, double x, double y, + double z, float r); + ~Explosion(); public: - void explode(); + void explode(); public: - void finalizeExplosion(bool generateParticles, std::vector *toBlowDirect = NULL); // 4J - added toBlow parameter - playerVec3Map *getHitPlayers(); - Vec3 *getHitPlayerKnockback( std::shared_ptr player ); + void finalizeExplosion(bool generateParticles, + std::vector* toBlowDirect = + NULL); // 4J - added toBlow parameter + playerVec3Map* getHitPlayers(); + Vec3* getHitPlayerKnockback(std::shared_ptr player); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Level.cpp b/Minecraft.World/Level/Level.cpp index b4026d890..bb0e4343d 100644 --- a/Minecraft.World/Level/Level.cpp +++ b/Minecraft.World/Level/Level.cpp @@ -43,38 +43,29 @@ #include "../../Minecraft.Client/Platform/PS3/PS3Extras/ShutdownManager.h" #include - -namespace -{ +namespace { #if defined(_WIN32) - inline void *LevelTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +inline void* LevelTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void LevelTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } -#else - pthread_key_t CreateLevelTlsKey() - { - pthread_key_t key; - pthread_key_create(&key, NULL); - return key; - } - - inline void *LevelTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void LevelTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } -#endif +inline void LevelTlsSetValue(DWORD key, void* value) { + TlsSetValue(key, value); } +#else +pthread_key_t CreateLevelTlsKey() { + pthread_key_t key; + pthread_key_create(&key, NULL); + return key; +} + +inline void* LevelTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} + +inline void LevelTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +#endif +} // namespace #if defined(_WIN32) DWORD Level::tlsIdx = TlsAlloc(); @@ -87,16 +78,22 @@ pthread_key_t Level::tlsIdxLightCache = CreateLevelTlsKey(); // 4J : WESTY : Added for time played stats. #include "../Headers/net.minecraft.stats.h" -// 4J - Caching of lighting data added. This is implemented as a 16x16x16 cache of ints (ie 16K storage in total). The index of the element to be used in the array is determined by the lower -// four bits of each x/y/z position, and the upper 7/4/7 bits of the x/y/z positions are stored within the element itself along with the cached values etc. The cache can be enabled per thread by -// calling enableLightingCache, otherwise standard non-cached accesses are performed. General method for using caching if enabled on a thread is: -// (1) Call initCache, this invalidates any previous data in the cache -// (2) Use setBrightnessCached, getBrightnessCached, getEmissionCached, getBlockingCached methods to get and set data -// (3) Call flushCache, which writes through any dirty values in cache +// 4J - Caching of lighting data added. This is implemented as a 16x16x16 cache +// of ints (ie 16K storage in total). The index of the element to be used in the +// array is determined by the lower four bits of each x/y/z position, and the +// upper 7/4/7 bits of the x/y/z positions are stored within the element itself +// along with the cached values etc. The cache can be enabled per thread by +// calling enableLightingCache, otherwise standard non-cached accesses are +// performed. General method for using caching if enabled on a thread is: (1) +// Call initCache, this invalidates any previous data in the cache (2) Use +// setBrightnessCached, getBrightnessCached, getEmissionCached, +// getBlockingCached methods to get and set data (3) Call flushCache, which +// writes through any dirty values in cache #ifdef _LARGE_WORLDS // Packing for cache entries in large worlds is as follows ( 64 bits per entry) -// Add the extra x and z data into the top 32 bits, to keep all the masks and code for everything else the same +// Add the extra x and z data into the top 32 bits, to keep all the masks and +// code for everything else the same // xxxxxxxxxxxxxxxxzzzzzzzzzzzzzzzzWEBLllllbbbbeeeexxxxxxyyyyzzzzzz // // xxxxxx - middle 6 bits of x position @@ -127,1171 +124,1067 @@ pthread_key_t Level::tlsIdxLightCache = CreateLevelTlsKey(); // W - lighting value requires write #endif - -void Level::enableLightingCache() -{ - // Allocate 16K (needs 32K for large worlds) for a 16x16x16x4 byte cache of results, plus 128K required for toCheck array. Rounding up to 256 to keep as multiple of alignement - aligning to 128K boundary for possible cache locking. - void *cache = (unsigned char *)XPhysicalAlloc(256 * 1024, MAXULONG_PTR, 128 * 1024, PAGE_READWRITE | MEM_LARGE_PAGES); - LevelTlsSetValue(tlsIdxLightCache, cache); +void Level::enableLightingCache() { + // Allocate 16K (needs 32K for large worlds) for a 16x16x16x4 byte cache of + // results, plus 128K required for toCheck array. Rounding up to 256 to keep + // as multiple of alignement - aligning to 128K boundary for possible cache + // locking. + void* cache = (unsigned char*)XPhysicalAlloc( + 256 * 1024, MAXULONG_PTR, 128 * 1024, PAGE_READWRITE | MEM_LARGE_PAGES); + LevelTlsSetValue(tlsIdxLightCache, cache); } -void Level::destroyLightingCache() -{ - lightCache_t *cache = static_cast(LevelTlsGetValue(tlsIdxLightCache)); - XPhysicalFree(cache); +void Level::destroyLightingCache() { + lightCache_t* cache = + static_cast(LevelTlsGetValue(tlsIdxLightCache)); + XPhysicalFree(cache); } -void Level::initCache(lightCache_t *cache) -{ - cachewritten = false; - if( cache == NULL ) return; +void Level::initCache(lightCache_t* cache) { + cachewritten = false; + if (cache == NULL) return; - XMemSet128(cache,0,16*16*16*sizeof(lightCache_t)); + XMemSet128(cache, 0, 16 * 16 * 16 * sizeof(lightCache_t)); } // Set a brightness value, going through the cache if enabled for this thread -void inline Level::setBrightnessCached(lightCache_t *cache, __uint64 *cacheUse, LightLayer::variety layer, int x, int y, int z, int brightness) -{ - if( cache == NULL ) - { - setBrightness(layer, x, y, z, brightness, true); - return; - } - if( y & 0xffffff00 ) return; // Eliminate -ve ys and values > 255 +void inline Level::setBrightnessCached(lightCache_t* cache, __uint64* cacheUse, + LightLayer::variety layer, int x, int y, + int z, int brightness) { + if (cache == NULL) { + setBrightness(layer, x, y, z, brightness, true); + return; + } + if (y & 0xffffff00) return; // Eliminate -ve ys and values > 255 - int idx = ( ( x & 15 ) << 8 ) | - ( ( y & 15 ) << 4 ) | - ( z & 15 ); - lightCache_t posbits = ( ( x & 0x3f0 ) << 6 ) | - ( ( y & 0x0f0 ) << 2 ) | - ( ( z & 0x3f0 ) >> 4 ); + int idx = ((x & 15) << 8) | ((y & 15) << 4) | (z & 15); + lightCache_t posbits = + ((x & 0x3f0) << 6) | ((y & 0x0f0) << 2) | ((z & 0x3f0) >> 4); #ifdef _LARGE_WORLDS - // Add in the higher bits for x and z - posbits |= ( ( ((__uint64)x) & 0x3FFFC00L) << 38) | - ( ( ((__uint64)z) & 0x3FFFC00L) << 22); + // Add in the higher bits for x and z + posbits |= ((((__uint64)x) & 0x3FFFC00L) << 38) | + ((((__uint64)z) & 0x3FFFC00L) << 22); #endif - lightCache_t cacheValue = cache[idx]; + lightCache_t cacheValue = cache[idx]; - // If this cache entry doesn't refer to the same thing... - if( ( cacheValue & POSITION_MASK ) != posbits ) - { - /// and it has been written to... - if( cacheValue & LIGHTING_WRITEBACK ) - { - // Then we need to flush - int val = ( cacheValue >> LIGHTING_SHIFT ) & 15; - int xx = ( (cacheValue >> 6 ) & 0x3f0 ) | ( x & 15 ); + // If this cache entry doesn't refer to the same thing... + if ((cacheValue & POSITION_MASK) != posbits) { + /// and it has been written to... + if (cacheValue & LIGHTING_WRITEBACK) { + // Then we need to flush + int val = (cacheValue >> LIGHTING_SHIFT) & 15; + int xx = ((cacheValue >> 6) & 0x3f0) | (x & 15); #ifdef _LARGE_WORLDS - xx |= ( (cacheValue >> 38) & 0x3FFFC00); - xx = ( xx << 6 ) >> 6; // sign extend + xx |= ((cacheValue >> 38) & 0x3FFFC00); + xx = (xx << 6) >> 6; // sign extend #else - xx = ( xx << 22 ) >> 22; // sign extend + xx = (xx << 22) >> 22; // sign extend #endif - int yy = ( (cacheValue >> 2 ) & 0x0f0 ) | ( y & 15 ); - int zz = ( (cacheValue << 4 ) & 0x3f0 ) | ( z & 15 ); + int yy = ((cacheValue >> 2) & 0x0f0) | (y & 15); + int zz = ((cacheValue << 4) & 0x3f0) | (z & 15); #ifdef _LARGE_WORLDS - zz |= ( (cacheValue >> 22) & 0x3FFFC00); - zz = ( zz << 6 ) >> 6; // sign extend + zz |= ((cacheValue >> 22) & 0x3FFFC00); + zz = (zz << 6) >> 6; // sign extend #else - zz = ( zz << 22 ) >> 22; // sign extend + zz = (zz << 22) >> 22; // sign extend #endif - setBrightness(layer, xx, yy, zz, val, true); - } - cacheValue = posbits; - } + setBrightness(layer, xx, yy, zz, val, true); + } + cacheValue = posbits; + } - // Just written to it, so value is valid & requires writing back - cacheValue &= ~(15 << LIGHTING_SHIFT ); - cacheValue |= brightness << LIGHTING_SHIFT; - cacheValue |= ( LIGHTING_WRITEBACK | LIGHTING_VALID ); + // Just written to it, so value is valid & requires writing back + cacheValue &= ~(15 << LIGHTING_SHIFT); + cacheValue |= brightness << LIGHTING_SHIFT; + cacheValue |= (LIGHTING_WRITEBACK | LIGHTING_VALID); - // cacheUse has a single bit for each x, y and z to say whether anything with that x, y or z has been written to - (*cacheUse) |= ( ( 1LL << ( x & 15 ) ) | ( 0x10000LL << ( y & 15 ) ) | ( 0x100000000LL << ( z & 15 ) ) ); + // cacheUse has a single bit for each x, y and z to say whether anything + // with that x, y or z has been written to + (*cacheUse) |= ((1LL << (x & 15)) | (0x10000LL << (y & 15)) | + (0x100000000LL << (z & 15))); - cache[idx] = cacheValue; + cache[idx] = cacheValue; } // Get a brightness value, going through the cache if enabled for this thread -inline int Level::getBrightnessCached(lightCache_t *cache, LightLayer::variety layer, int x, int y, int z) -{ - if( cache == NULL ) return getBrightness(layer, x, y, z); - if( y & 0xffffff00 ) return getBrightness(layer, x, y, z); // Fall back on original method for out-of-bounds y +inline int Level::getBrightnessCached(lightCache_t* cache, + LightLayer::variety layer, int x, int y, + int z) { + if (cache == NULL) return getBrightness(layer, x, y, z); + if (y & 0xffffff00) + return getBrightness( + layer, x, y, + z); // Fall back on original method for out-of-bounds y - int idx = ( ( x & 15 ) << 8 ) | - ( ( y & 15 ) << 4 ) | - ( z & 15 ); - lightCache_t posbits = ( ( x & 0x3f0 ) << 6 ) | - ( ( y & 0x0f0 ) << 2 ) | - ( ( z & 0x3f0 ) >> 4 ); + int idx = ((x & 15) << 8) | ((y & 15) << 4) | (z & 15); + lightCache_t posbits = + ((x & 0x3f0) << 6) | ((y & 0x0f0) << 2) | ((z & 0x3f0) >> 4); #ifdef _LARGE_WORLDS - // Add in the higher bits for x and z - posbits |= ( ( ((__uint64)x) & 0x3FFFC00L) << 38) | - ( ( ((__uint64)z) & 0x3FFFC00L) << 22); + // Add in the higher bits for x and z + posbits |= ((((__uint64)x) & 0x3FFFC00L) << 38) | + ((((__uint64)z) & 0x3FFFC00L) << 22); #endif - lightCache_t cacheValue = cache[idx]; + lightCache_t cacheValue = cache[idx]; - if( ( cacheValue & POSITION_MASK ) != posbits ) - { - // Position differs - need to evict this cache entry - if( cacheValue & LIGHTING_WRITEBACK ) - { - // Then we need to flush - int val = ( cacheValue >> LIGHTING_SHIFT ) & 15; - int xx = ( (cacheValue >> 6 ) & 0x3f0 ) | ( x & 15 ); + if ((cacheValue & POSITION_MASK) != posbits) { + // Position differs - need to evict this cache entry + if (cacheValue & LIGHTING_WRITEBACK) { + // Then we need to flush + int val = (cacheValue >> LIGHTING_SHIFT) & 15; + int xx = ((cacheValue >> 6) & 0x3f0) | (x & 15); #ifdef _LARGE_WORLDS - xx |= ( (cacheValue >> 38) & 0x3FFFC00); - xx = ( xx << 6 ) >> 6; // sign extend + xx |= ((cacheValue >> 38) & 0x3FFFC00); + xx = (xx << 6) >> 6; // sign extend #else - xx = ( xx << 22 ) >> 22; // sign extend + xx = (xx << 22) >> 22; // sign extend #endif - int yy = ( (cacheValue >> 2 ) & 0x0f0 ) | ( y & 15 ); - int zz = ( (cacheValue << 4 ) & 0x3f0 ) | ( z & 15 ); + int yy = ((cacheValue >> 2) & 0x0f0) | (y & 15); + int zz = ((cacheValue << 4) & 0x3f0) | (z & 15); #ifdef _LARGE_WORLDS - zz |= ( (cacheValue >> 22) & 0x3FFFC00); - zz = ( zz << 6 ) >> 6; // sign extend + zz |= ((cacheValue >> 22) & 0x3FFFC00); + zz = (zz << 6) >> 6; // sign extend #else - zz = ( zz << 22 ) >> 22; // sign extend + zz = (zz << 22) >> 22; // sign extend #endif - setBrightness(layer, xx, yy, zz, val, true); - } - cacheValue = posbits | LIGHTING_VALID; - int val = getBrightness(layer, x, y, z); - cacheValue |= val << LIGHTING_SHIFT; - } - else - { - // The position matches - will incurr a read miss if the lighting value isn't valid - if( ( cacheValue & LIGHTING_VALID ) == 0 ) - { - int val = getBrightness(layer, x, y, z); - cacheValue |= val << LIGHTING_SHIFT; - cacheValue |= LIGHTING_VALID; - } - else - { - // All valid - just return value - return ( cacheValue >> LIGHTING_SHIFT ) & 15; - } - } + setBrightness(layer, xx, yy, zz, val, true); + } + cacheValue = posbits | LIGHTING_VALID; + int val = getBrightness(layer, x, y, z); + cacheValue |= val << LIGHTING_SHIFT; + } else { + // The position matches - will incurr a read miss if the lighting value + // isn't valid + if ((cacheValue & LIGHTING_VALID) == 0) { + int val = getBrightness(layer, x, y, z); + cacheValue |= val << LIGHTING_SHIFT; + cacheValue |= LIGHTING_VALID; + } else { + // All valid - just return value + return (cacheValue >> LIGHTING_SHIFT) & 15; + } + } - cache[idx] = cacheValue; - return ( cacheValue >> LIGHTING_SHIFT ) & 15; + cache[idx] = cacheValue; + return (cacheValue >> LIGHTING_SHIFT) & 15; } -// Get a block emission value, going through the cache if enabled for this thread -inline int Level::getEmissionCached(lightCache_t *cache, int ct, int x, int y, int z) -{ - if( cache == NULL ) return Tile::lightEmission[ct]; +// Get a block emission value, going through the cache if enabled for this +// thread +inline int Level::getEmissionCached(lightCache_t* cache, int ct, int x, int y, + int z) { + if (cache == NULL) return Tile::lightEmission[ct]; - int idx = ( ( x & 15 ) << 8 ) | - ( ( y & 15 ) << 4 ) | - ( z & 15 ); - lightCache_t posbits = ( ( x & 0x3f0 ) << 6 ) | - ( ( y & 0x0f0 ) << 2 ) | - ( ( z & 0x3f0 ) >> 4 ); + int idx = ((x & 15) << 8) | ((y & 15) << 4) | (z & 15); + lightCache_t posbits = + ((x & 0x3f0) << 6) | ((y & 0x0f0) << 2) | ((z & 0x3f0) >> 4); #ifdef _LARGE_WORLDS - // Add in the higher bits for x and z - posbits |= ( ( ((__uint64)x) & 0x3FFFC00) << 38) | - ( ( ((__uint64)z) & 0x3FFFC00) << 22); + // Add in the higher bits for x and z + posbits |= ((((__uint64)x) & 0x3FFFC00) << 38) | + ((((__uint64)z) & 0x3FFFC00) << 22); #endif - lightCache_t cacheValue = cache[idx]; + lightCache_t cacheValue = cache[idx]; - if( ( cacheValue & POSITION_MASK ) != posbits ) - { - // Position differs - need to evict this cache entry - if( cacheValue & LIGHTING_WRITEBACK ) - { - // Then we need to flush - int val = ( cacheValue >> LIGHTING_SHIFT ) & 15; - int xx = ( (cacheValue >> 6 ) & 0x3f0 ) | ( x & 15 ); + if ((cacheValue & POSITION_MASK) != posbits) { + // Position differs - need to evict this cache entry + if (cacheValue & LIGHTING_WRITEBACK) { + // Then we need to flush + int val = (cacheValue >> LIGHTING_SHIFT) & 15; + int xx = ((cacheValue >> 6) & 0x3f0) | (x & 15); #ifdef _LARGE_WORLDS - xx |= ( (cacheValue >> 38) & 0x3FFFC00); - xx = ( xx << 6 ) >> 6; // sign extend + xx |= ((cacheValue >> 38) & 0x3FFFC00); + xx = (xx << 6) >> 6; // sign extend #else - xx = ( xx << 22 ) >> 22; // sign extend + xx = (xx << 22) >> 22; // sign extend #endif - int yy = ( (cacheValue >> 2 ) & 0x0f0 ) | ( y & 15 ); - int zz = ( (cacheValue << 4 ) & 0x3f0 ) | ( z & 15 ); + int yy = ((cacheValue >> 2) & 0x0f0) | (y & 15); + int zz = ((cacheValue << 4) & 0x3f0) | (z & 15); #ifdef _LARGE_WORLDS - zz |= ( (cacheValue >> 22) & 0x3FFFC00); - zz = ( zz << 6 ) >> 6; // sign extend + zz |= ((cacheValue >> 22) & 0x3FFFC00); + zz = (zz << 6) >> 6; // sign extend #else - zz = ( zz << 22 ) >> 22; // sign extend + zz = (zz << 22) >> 22; // sign extend #endif - setBrightness(LightLayer::Block, xx, yy, zz, val, true); - } - - // Update both emission & blocking values whilst we are here - cacheValue = posbits | EMISSION_VALID | BLOCKING_VALID; - int t = getTile(x,y,z); - cacheValue |= ( Tile::lightEmission[t] & 15 ) << EMISSION_SHIFT; - cacheValue |= ( Tile::lightBlock[t] & 15 ) << BLOCKING_SHIFT; - } - else - { - // The position matches - will incurr a read miss if the lighting value isn't valid - if( ( cacheValue & EMISSION_VALID ) == 0 ) - { - // Update both emission & blocking values whilst we are here - cacheValue |= EMISSION_VALID | BLOCKING_VALID; - int t = getTile(x,y,z); - cacheValue |= ( Tile::lightEmission[t] & 15 ) << EMISSION_SHIFT; - cacheValue |= ( Tile::lightBlock[t] & 15 ) << BLOCKING_SHIFT; - } - else - { - // All valid - just return value - return ( cacheValue >> EMISSION_SHIFT ) & 15; - } - } - cache[idx] = cacheValue; - return ( cacheValue >> EMISSION_SHIFT ) & 15; + setBrightness(LightLayer::Block, xx, yy, zz, val, true); + } + + // Update both emission & blocking values whilst we are here + cacheValue = posbits | EMISSION_VALID | BLOCKING_VALID; + int t = getTile(x, y, z); + cacheValue |= (Tile::lightEmission[t] & 15) << EMISSION_SHIFT; + cacheValue |= (Tile::lightBlock[t] & 15) << BLOCKING_SHIFT; + } else { + // The position matches - will incurr a read miss if the lighting value + // isn't valid + if ((cacheValue & EMISSION_VALID) == 0) { + // Update both emission & blocking values whilst we are here + cacheValue |= EMISSION_VALID | BLOCKING_VALID; + int t = getTile(x, y, z); + cacheValue |= (Tile::lightEmission[t] & 15) << EMISSION_SHIFT; + cacheValue |= (Tile::lightBlock[t] & 15) << BLOCKING_SHIFT; + } else { + // All valid - just return value + return (cacheValue >> EMISSION_SHIFT) & 15; + } + } + cache[idx] = cacheValue; + return (cacheValue >> EMISSION_SHIFT) & 15; } -// Get a tile light blocking value, going through cache if enabled for this thread -inline int Level::getBlockingCached(lightCache_t *cache, LightLayer::variety layer, int *ct, int x, int y, int z) -{ - if( cache == NULL ) - { - int t = getTile(x,y,z); - if(ct) *ct = t; - return Tile::lightBlock[t]; - } +// Get a tile light blocking value, going through cache if enabled for this +// thread +inline int Level::getBlockingCached(lightCache_t* cache, + LightLayer::variety layer, int* ct, int x, + int y, int z) { + if (cache == NULL) { + int t = getTile(x, y, z); + if (ct) *ct = t; + return Tile::lightBlock[t]; + } - int idx = ( ( x & 15 ) << 8 ) | - ( ( y & 15 ) << 4 ) | - ( z & 15 ); - lightCache_t posbits = ( ( x & 0x3f0 ) << 6 ) | - ( ( y & 0x0f0 ) << 2 ) | - ( ( z & 0x3f0 ) >> 4 ); + int idx = ((x & 15) << 8) | ((y & 15) << 4) | (z & 15); + lightCache_t posbits = + ((x & 0x3f0) << 6) | ((y & 0x0f0) << 2) | ((z & 0x3f0) >> 4); #ifdef _LARGE_WORLDS - // Add in the higher bits for x and z - posbits |= ( ( ((__uint64)x) & 0x3FFFC00L) << 38) | - ( ( ((__uint64)z) & 0x3FFFC00L) << 22); + // Add in the higher bits for x and z + posbits |= ((((__uint64)x) & 0x3FFFC00L) << 38) | + ((((__uint64)z) & 0x3FFFC00L) << 22); #endif - lightCache_t cacheValue = cache[idx]; + lightCache_t cacheValue = cache[idx]; - if( ( cacheValue & POSITION_MASK ) != posbits ) - { - // Position differs - need to evict this cache entry - if( cacheValue & LIGHTING_WRITEBACK ) - { - // Then we need to flush - int val = ( cacheValue >> LIGHTING_SHIFT ) & 15; - int xx = ( (cacheValue >> 6 ) & 0x3f0 ) | ( x & 15 ); + if ((cacheValue & POSITION_MASK) != posbits) { + // Position differs - need to evict this cache entry + if (cacheValue & LIGHTING_WRITEBACK) { + // Then we need to flush + int val = (cacheValue >> LIGHTING_SHIFT) & 15; + int xx = ((cacheValue >> 6) & 0x3f0) | (x & 15); #ifdef _LARGE_WORLDS - xx |= ( (cacheValue >> 38) & 0x3FFFC00); - xx = ( xx << 6 ) >> 6; // sign extend + xx |= ((cacheValue >> 38) & 0x3FFFC00); + xx = (xx << 6) >> 6; // sign extend #else - xx = ( xx << 22 ) >> 22; // sign extend + xx = (xx << 22) >> 22; // sign extend #endif - int yy = ( (cacheValue >> 2 ) & 0x0f0 ) | ( y & 15 ); - int zz = ( (cacheValue << 4 ) & 0x3f0 ) | ( z & 15 ); + int yy = ((cacheValue >> 2) & 0x0f0) | (y & 15); + int zz = ((cacheValue << 4) & 0x3f0) | (z & 15); #ifdef _LARGE_WORLDS - zz |= ( (cacheValue >> 22) & 0x3FFFC00); - zz = ( zz << 6 ) >> 6; // sign extend + zz |= ((cacheValue >> 22) & 0x3FFFC00); + zz = (zz << 6) >> 6; // sign extend #else - zz = ( zz << 22 ) >> 22; // sign extend + zz = (zz << 22) >> 22; // sign extend #endif - setBrightness(layer, xx, yy, zz, val, true); - } - - // Update both emission & blocking values whilst we are here - cacheValue = posbits | EMISSION_VALID | BLOCKING_VALID; - int t = getTile(x,y,z); - cacheValue |= ( Tile::lightEmission[t] & 15 ) << EMISSION_SHIFT; - cacheValue |= ( Tile::lightBlock[t] & 15 ) << BLOCKING_SHIFT; - } - else - { - // The position matches - will incurr a read miss if the lighting value isn't valid - if( ( cacheValue & EMISSION_VALID ) == 0 ) - { - // Update both emission & blocking values whilst we are here - cacheValue |= EMISSION_VALID | BLOCKING_VALID; - int t = getTile(x,y,z); - cacheValue |= ( Tile::lightEmission[t] & 15 ) << EMISSION_SHIFT; - cacheValue |= ( Tile::lightBlock[t] & 15 ) << BLOCKING_SHIFT; - } - else - { - // All valid - just return value - return ( cacheValue >> BLOCKING_SHIFT ) & 15; - } - } + setBrightness(layer, xx, yy, zz, val, true); + } - cache[idx] = cacheValue; - return ( cacheValue >> BLOCKING_SHIFT ) & 15; + // Update both emission & blocking values whilst we are here + cacheValue = posbits | EMISSION_VALID | BLOCKING_VALID; + int t = getTile(x, y, z); + cacheValue |= (Tile::lightEmission[t] & 15) << EMISSION_SHIFT; + cacheValue |= (Tile::lightBlock[t] & 15) << BLOCKING_SHIFT; + } else { + // The position matches - will incurr a read miss if the lighting value + // isn't valid + if ((cacheValue & EMISSION_VALID) == 0) { + // Update both emission & blocking values whilst we are here + cacheValue |= EMISSION_VALID | BLOCKING_VALID; + int t = getTile(x, y, z); + cacheValue |= (Tile::lightEmission[t] & 15) << EMISSION_SHIFT; + cacheValue |= (Tile::lightBlock[t] & 15) << BLOCKING_SHIFT; + } else { + // All valid - just return value + return (cacheValue >> BLOCKING_SHIFT) & 15; + } + } + + cache[idx] = cacheValue; + return (cacheValue >> BLOCKING_SHIFT) & 15; } -// Write back any dirty entries in the lighting cache. Also calls the setTilesDirty method on the region which has been updated during this lighting update, since -// this hasn't been updated (for client threads) for each individual lighting update as would have been the case with the non-cached lighting. There's two reasons for this -// (1) it's more efficient, since we aren't doing so many individual calls to the level listener to let the renderer know what has been updated -// (2) it lets the lighting actually complete before we get any visual representation of the update, otherwise we end up seeing some strange partial updates -void Level::flushCache(lightCache_t *cache, __uint64 cacheUse, LightLayer::variety layer) -{ - // cacheUse has a single bit for each x, y and z to say whether anything with that x, y or z has been written to - if( cacheUse == 0 ) return; - if( cache ) - { - lightCache_t *pcache = cache; - for( int x = 0; x < 16; x++ ) - { - if( ( cacheUse & ( 1LL << x ) ) == 0 ) - { - pcache += 16 * 16; - continue; - } - for( int y = 0; y < 16; y++ ) - { - if( ( cacheUse & ( 0x10000LL << y ) ) == 0 ) - { - pcache += 16; - continue; - } - for( int z = 0; z < 16; z++ ) - { - if( ( cacheUse & ( 0x100000000LL << z ) ) == 0 ) - { - pcache++; - continue; - } - lightCache_t cacheValue = *pcache++; - if( cacheValue & LIGHTING_WRITEBACK ) - { - int val = ( cacheValue >> LIGHTING_SHIFT ) & 15; - int xx = ( (cacheValue >> 6 ) & 0x3f0 ) | ( x & 15 ); +// Write back any dirty entries in the lighting cache. Also calls the +// setTilesDirty method on the region which has been updated during this +// lighting update, since this hasn't been updated (for client threads) for each +// individual lighting update as would have been the case with the non-cached +// lighting. There's two reasons for this (1) it's more efficient, since we +// aren't doing so many individual calls to the level listener to let the +// renderer know what has been updated (2) it lets the lighting actually +// complete before we get any visual representation of the update, otherwise we +// end up seeing some strange partial updates +void Level::flushCache(lightCache_t* cache, __uint64 cacheUse, + LightLayer::variety layer) { + // cacheUse has a single bit for each x, y and z to say whether anything + // with that x, y or z has been written to + if (cacheUse == 0) return; + if (cache) { + lightCache_t* pcache = cache; + for (int x = 0; x < 16; x++) { + if ((cacheUse & (1LL << x)) == 0) { + pcache += 16 * 16; + continue; + } + for (int y = 0; y < 16; y++) { + if ((cacheUse & (0x10000LL << y)) == 0) { + pcache += 16; + continue; + } + for (int z = 0; z < 16; z++) { + if ((cacheUse & (0x100000000LL << z)) == 0) { + pcache++; + continue; + } + lightCache_t cacheValue = *pcache++; + if (cacheValue & LIGHTING_WRITEBACK) { + int val = (cacheValue >> LIGHTING_SHIFT) & 15; + int xx = ((cacheValue >> 6) & 0x3f0) | (x & 15); #ifdef _LARGE_WORLDS - xx |= ( (cacheValue >> 38) & 0x3FFFC00); - xx = ( xx << 6 ) >> 6; // sign extend + xx |= ((cacheValue >> 38) & 0x3FFFC00); + xx = (xx << 6) >> 6; // sign extend #else - xx = ( xx << 22 ) >> 22; // sign extend + xx = (xx << 22) >> 22; // sign extend #endif - int yy = ( (cacheValue >> 2 ) & 0x0f0 ) | ( y & 15 ); - int zz = ( (cacheValue << 4 ) & 0x3f0 ) | ( z & 15 ); + int yy = ((cacheValue >> 2) & 0x0f0) | (y & 15); + int zz = ((cacheValue << 4) & 0x3f0) | (z & 15); #ifdef _LARGE_WORLDS - zz |= ( (cacheValue >> 22) & 0x3FFFC00); - zz = ( zz << 6 ) >> 6; // sign extend + zz |= ((cacheValue >> 22) & 0x3FFFC00); + zz = (zz << 6) >> 6; // sign extend #else - zz = ( zz << 22 ) >> 22; // sign extend + zz = (zz << 22) >> 22; // sign extend #endif - setBrightness(layer, xx, yy, zz, val, true); - } - } - } - } - } - // For client side (which has the renderer attached) we haven't been updating with each individual update, but have been gathering them up. - // Let the renderer know now the region that has been updated. - if( isClientSide && cachewritten) - { - setTilesDirty(cacheminx, cacheminy, cacheminz,cachemaxx,cachemaxy,cachemaxz); - } + setBrightness(layer, xx, yy, zz, val, true); + } + } + } + } + } + // For client side (which has the renderer attached) we haven't been + // updating with each individual update, but have been gathering them up. + // Let the renderer know now the region that has been updated. + if (isClientSide && cachewritten) { + setTilesDirty(cacheminx, cacheminy, cacheminz, cachemaxx, cachemaxy, + cachemaxz); + } } -// 4J - added following 2 functions to move instaBuild flag from being a class member, to TLS -bool Level::getInstaTick() -{ - return reinterpret_cast(LevelTlsGetValue(tlsIdx)) != 0; +// 4J - added following 2 functions to move instaBuild flag from being a class +// member, to TLS +bool Level::getInstaTick() { + return reinterpret_cast(LevelTlsGetValue(tlsIdx)) != 0; } -void Level::setInstaTick(bool enable) -{ - void *value = 0; - if( enable ) value = (void *)1; - LevelTlsSetValue(tlsIdx, value); +void Level::setInstaTick(bool enable) { + void* value = 0; + if (enable) value = (void*)1; + LevelTlsSetValue(tlsIdx, value); } // 4J - added -bool Level::hasEntitiesToRemove() -{ - return !entitiesToRemove.empty(); -} +bool Level::hasEntitiesToRemove() { return !entitiesToRemove.empty(); } -void Level::_init() -{ - cloudColor = 0xffffff; +void Level::_init() { + cloudColor = 0xffffff; - skyDarken = 0; + skyDarken = 0; - randValue = (new Random())->nextInt(); + randValue = (new Random())->nextInt(); - addend = 1013904223; + addend = 1013904223; - oRainLevel = rainLevel = 0.0f; + oRainLevel = rainLevel = 0.0f; - oThunderLevel = thunderLevel = 0.0f; + oThunderLevel = thunderLevel = 0.0f; - lightningTime = 0; + lightningTime = 0; - lightningBoltTime = 0; + lightningBoltTime = 0; - noNeighborUpdate = false; + noNeighborUpdate = false; - difficulty = 0; + difficulty = 0; - random = new Random(); - isNew = false; + random = new Random(); + isNew = false; - dimension = NULL; + dimension = NULL; - chunkSource = NULL; + chunkSource = NULL; - levelStorage = nullptr; + levelStorage = nullptr; - levelData = NULL; + levelData = NULL; - isFindingSpawn = false; + isFindingSpawn = false; - savedDataStorage = NULL; + savedDataStorage = NULL; - spawnEnemies = true; + spawnEnemies = true; - spawnFriendlies = true; + spawnFriendlies = true; - delayUntilNextMoodSound = random->nextInt(20 * 60 * 10); + delayUntilNextMoodSound = random->nextInt(20 * 60 * 10); - isClientSide = false; + isClientSide = false; - InitializeCriticalSection(&m_entitiesCS); - InitializeCriticalSection(&m_tileEntityListCS); + InitializeCriticalSection(&m_entitiesCS); + InitializeCriticalSection(&m_tileEntityListCS); - m_timeOfDayOverride = -1; + m_timeOfDayOverride = -1; - updatingTileEntities = false; + updatingTileEntities = false; - villageSiege = new VillageSiege(this); + villageSiege = new VillageSiege(this); - toCheckLevel = new int[ 32 * 32 * 32]; // 4J - brought forward from 1.8.2 - InitializeCriticalSectionAndSpinCount(&m_checkLightCS, 5120); // 4J - added for 1.8.2 lighting + toCheckLevel = new int[32 * 32 * 32]; // 4J - brought forward from 1.8.2 + InitializeCriticalSectionAndSpinCount( + &m_checkLightCS, 5120); // 4J - added for 1.8.2 lighting - // 4J Added - m_bDisableAddNewTileEntities = false; - m_iHighestY=-1000; - m_unsavedChunkCount = 0; + // 4J Added + m_bDisableAddNewTileEntities = false; + m_iHighestY = -1000; + m_unsavedChunkCount = 0; } // 4J - brought forward from 1.8.2 -Biome *Level::getBiome(int x, int z) -{ - if (hasChunkAt(x, 0, z)) - { - LevelChunk *lc = getChunkAt(x, z); - if (lc != NULL) - { - // Water chunks at the edge of the world return NULL for their biome as they can't store it, so should fall back on the normal method below - Biome *biome = lc->getBiome(x & 0xf, z & 0xf, dimension->biomeSource); - if( biome ) return biome; +Biome* Level::getBiome(int x, int z) { + if (hasChunkAt(x, 0, z)) { + LevelChunk* lc = getChunkAt(x, z); + if (lc != NULL) { + // Water chunks at the edge of the world return NULL for their biome + // as they can't store it, so should fall back on the normal method + // below + Biome* biome = + lc->getBiome(x & 0xf, z & 0xf, dimension->biomeSource); + if (biome) return biome; } } return dimension->biomeSource->getBiome(x, z); } -BiomeSource *Level::getBiomeSource() -{ - return dimension->biomeSource; +BiomeSource* Level::getBiomeSource() { return dimension->biomeSource; } + +Level::Level(std::shared_ptr levelStorage, + const std::wstring& name, Dimension* dimension, + LevelSettings* levelSettings, bool doCreateChunkSource) + : seaLevel(constSeaLevel) { + _init(); + this->levelStorage = + levelStorage; // std::shared_ptr(levelStorage); + this->dimension = dimension; + this->levelData = new LevelData(levelSettings, name); + if (!this->levelData->useNewSeaLevel()) + seaLevel = Level::genDepth / + 2; // 4J added - sea level is one unit lower since 1.8.2, + // maintain older height for old levels + this->savedDataStorage = new SavedDataStorage(levelStorage.get()); + + std::shared_ptr savedVillages = + std::dynamic_pointer_cast( + savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); + if (savedVillages == NULL) { + villages = std::shared_ptr(new Villages(this)); + savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); + } else { + villages = savedVillages; + villages->setLevel(this); + } + + dimension->init(this); + chunkSource = NULL; // 4J - added flag so chunk source can be called from + // derived class instead + + updateSkyBrightness(); + prepareWeather(); } -Level::Level(std::shared_ptr levelStorage, const std::wstring& name, Dimension *dimension, LevelSettings *levelSettings, bool doCreateChunkSource) - : seaLevel(constSeaLevel) -{ - _init(); - this->levelStorage = levelStorage;//std::shared_ptr(levelStorage); - this->dimension = dimension; - this->levelData = new LevelData(levelSettings, name); - if( !this->levelData->useNewSeaLevel() ) seaLevel = Level::genDepth / 2; // 4J added - sea level is one unit lower since 1.8.2, maintain older height for old levels - this->savedDataStorage = new SavedDataStorage(levelStorage.get()); +Level::Level(Level* level, Dimension* dimension) : seaLevel(constSeaLevel) { + _init(); + this->levelStorage = level->levelStorage; + this->levelData = new LevelData(level->levelData); + if (!this->levelData->useNewSeaLevel()) + seaLevel = Level::genDepth / + 2; // 4J added - sea level is one unit lower since 1.8.2, + // maintain older height for old levels + this->savedDataStorage = new SavedDataStorage(levelStorage.get()); - std::shared_ptr savedVillages = std::dynamic_pointer_cast(savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); - if (savedVillages == NULL) - { - villages = std::shared_ptr(new Villages(this)); - savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); - } - else - { - villages = savedVillages; - villages->setLevel(this); - } + std::shared_ptr savedVillages = + std::dynamic_pointer_cast( + savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); + if (savedVillages == NULL) { + villages = std::shared_ptr(new Villages(this)); + savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); + } else { + villages = savedVillages; + villages->setLevel(this); + } - dimension->init(this); - chunkSource = NULL; // 4J - added flag so chunk source can be called from derived class instead - - updateSkyBrightness(); - prepareWeather(); + this->dimension = dimension; + dimension->init(this); + chunkSource = NULL; + updateSkyBrightness(); + prepareWeather(); } - -Level::Level(Level *level, Dimension *dimension) - :seaLevel( constSeaLevel ) -{ - _init(); - this->levelStorage = level->levelStorage; - this->levelData = new LevelData(level->levelData); - if( !this->levelData->useNewSeaLevel() ) seaLevel = Level::genDepth / 2; // 4J added - sea level is one unit lower since 1.8.2, maintain older height for old levels - this->savedDataStorage = new SavedDataStorage( levelStorage.get() ); - - std::shared_ptr savedVillages = std::dynamic_pointer_cast(savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); - if (savedVillages == NULL) - { - villages = std::shared_ptr(new Villages(this)); - savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); - } - else - { - villages = savedVillages; - villages->setLevel(this); - } - - this->dimension = dimension; - dimension->init(this); - chunkSource = NULL; - updateSkyBrightness(); - prepareWeather(); +Level::Level(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings) + : seaLevel(constSeaLevel) { + _init(levelStorage, levelName, levelSettings, NULL, true); } - -Level::Level(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings) - : seaLevel( constSeaLevel ) -{ - _init(levelStorage, levelName, levelSettings, NULL, true); +Level::Level(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings, + Dimension* fixedDimension, bool doCreateChunkSource) + : seaLevel(constSeaLevel) { + _init(levelStorage, levelName, levelSettings, fixedDimension, + doCreateChunkSource); } +void Level::_init(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings, + Dimension* fixedDimension, bool doCreateChunkSource) { + _init(); + this->levelStorage = + levelStorage; // std::shared_ptr(levelStorage); + this->savedDataStorage = new SavedDataStorage(levelStorage.get()); -Level::Level(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings, Dimension *fixedDimension, bool doCreateChunkSource) - : seaLevel( constSeaLevel ) -{ - _init( levelStorage, levelName, levelSettings, fixedDimension, doCreateChunkSource ); + std::shared_ptr savedVillages = + std::dynamic_pointer_cast( + savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); + if (savedVillages == NULL) { + villages = std::shared_ptr(new Villages(this)); + savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); + } else { + villages = savedVillages; + villages->setLevel(this); + } + + levelData = levelStorage->prepareLevel(); + isNew = levelData == NULL; + + if (fixedDimension != NULL) { + dimension = fixedDimension; + } + // 4J Remove TU9 as getDimensions was never accurate. This path was never + // used anyway as we always set fixedDimension + // else if (levelData != NULL && levelData->getDimension() != 0) + //{ + // dimension = Dimension::getNew(levelData->getDimension()); + //} + else { + dimension = Dimension::getNew(0); + } + + if (levelData == NULL) { + levelData = new LevelData(levelSettings, levelName); + } else { + levelData->setLevelName(levelName); + } + if (!this->levelData->useNewSeaLevel()) + seaLevel = Level::genDepth / + 2; // 4J added - sea level is one unit lower since 1.8.2, + // maintain older height for old levels + + ((Dimension*)dimension)->init(this); + + chunkSource = doCreateChunkSource + ? createChunkSource() + : NULL; // 4J - added flag so chunk source can be called + // from derived class instead + + // 4J Stu- Moved to derived classes + // if (!levelData->isInitialized()) + //{ + // initializeLevel(levelSettings); + // levelData->setInitialized(true); + //} + + updateSkyBrightness(); + prepareWeather(); } -void Level::_init(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings, Dimension *fixedDimension, bool doCreateChunkSource) -{ - _init(); - this->levelStorage = levelStorage;//std::shared_ptr(levelStorage); - this->savedDataStorage = new SavedDataStorage(levelStorage.get()); +Level::~Level() { + delete random; + delete dimension; + delete chunkSource; + delete levelData; + delete toCheckLevel; - std::shared_ptr savedVillages = std::dynamic_pointer_cast(savedDataStorage->get(typeid(Villages), Villages::VILLAGE_FILE_ID)); - if (savedVillages == NULL) - { - villages = std::shared_ptr(new Villages(this)); - savedDataStorage->set(Villages::VILLAGE_FILE_ID, villages); - } - else - { - villages = savedVillages; - villages->setLevel(this); - } + if (!isClientSide) { + NotGateTile::removeLevelReferences(this); // 4J added + } - levelData = levelStorage->prepareLevel(); - isNew = levelData == NULL; + DeleteCriticalSection(&m_checkLightCS); - if (fixedDimension != NULL) - { - dimension = fixedDimension; - } - // 4J Remove TU9 as getDimensions was never accurate. This path was never used anyway as we always set fixedDimension - //else if (levelData != NULL && levelData->getDimension() != 0) - //{ - // dimension = Dimension::getNew(levelData->getDimension()); - //} - else - { - dimension = Dimension::getNew(0); - } + // 4J-PB - savedDataStorage is shared between overworld and nether levels in + // the server, so it will already have been deleted on the first level + // delete + if (savedDataStorage != NULL) delete savedDataStorage; - if (levelData == NULL) - { - levelData = new LevelData(levelSettings, levelName); - } - else - { - levelData->setLevelName(levelName); - } - if( !this->levelData->useNewSeaLevel() ) seaLevel = Level::genDepth / 2; // 4J added - sea level is one unit lower since 1.8.2, maintain older height for old levels - - ((Dimension *) dimension)->init( this ); - - chunkSource = doCreateChunkSource ? createChunkSource() : NULL; // 4J - added flag so chunk source can be called from derived class instead - - // 4J Stu- Moved to derived classes - //if (!levelData->isInitialized()) - //{ - // initializeLevel(levelSettings); - // levelData->setInitialized(true); - //} - - updateSkyBrightness(); - prepareWeather(); + DeleteCriticalSection(&m_entitiesCS); + DeleteCriticalSection(&m_tileEntityListCS); + // 4J Stu - At least one of the listeners is something we cannot delete, the + // LevelRenderer + /* + for(int i = 0; i < listeners.size(); i++) + delete listeners[i]; + */ } -Level::~Level() -{ - delete random; - delete dimension; - delete chunkSource; - delete levelData; - delete toCheckLevel; - - if( !isClientSide ) - { - NotGateTile::removeLevelReferences(this); // 4J added - } - - DeleteCriticalSection(&m_checkLightCS); - - // 4J-PB - savedDataStorage is shared between overworld and nether levels in the server, so it will already have been deleted on the first level delete - if(savedDataStorage!=NULL) delete savedDataStorage; - - DeleteCriticalSection(&m_entitiesCS); - DeleteCriticalSection(&m_tileEntityListCS); - - // 4J Stu - At least one of the listeners is something we cannot delete, the LevelRenderer - /* - for(int i = 0; i < listeners.size(); i++) - delete listeners[i]; - */ +void Level::initializeLevel(LevelSettings* settings) { + levelData->setInitialized(true); } -void Level::initializeLevel(LevelSettings *settings) -{ - levelData->setInitialized(true); +void Level::validateSpawn() { setSpawnPos(8, 64, 8); } + +int Level::getTopTile(int x, int z) { + // 4J added - was breaking spawning as not finding ground in superflat + // worlds + if (levelData->getGenerator() == LevelType::lvl_flat) { + return Tile::grass_Id; + } + + int y = seaLevel; + while (!isEmptyTile(x, y + 1, z)) { + y++; + } + return getTile(x, y, z); +} +int Level::getTile(int x, int y, int z) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return 0; + } + if (y < minBuildHeight) return 0; + if (y >= maxBuildHeight) return 0; + return getChunk(x >> 4, z >> 4)->getTile(x & 15, y, z & 15); } -void Level::validateSpawn() -{ - setSpawnPos(8, 64, 8); +int Level::getTileLightBlock(int x, int y, int z) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return 0; + } + if (y < minBuildHeight) return 0; + if (y >= maxBuildHeight) return 0; + return getChunk(x >> 4, z >> 4)->getTileLightBlock(x & 15, y, z & 15); } -int Level::getTopTile(int x, int z) -{ - // 4J added - was breaking spawning as not finding ground in superflat worlds - if( levelData->getGenerator() == LevelType::lvl_flat ) - { - return Tile::grass_Id; - } +bool Level::isEmptyTile(int x, int y, int z) { return getTile(x, y, z) == 0; } - int y = seaLevel; - while (!isEmptyTile(x, y + 1, z)) - { - y++; - } - return getTile(x, y, z); -} -int Level::getTile(int x, int y, int z) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return 0; - } - if (y < minBuildHeight) return 0; - if (y >= maxBuildHeight) return 0; - return getChunk(x >> 4, z >> 4)->getTile(x & 15, y, z & 15); +bool Level::isEntityTile(int x, int y, int z) { + int t = getTile(x, y, z); + if (Tile::tiles[t] != NULL && Tile::tiles[t]->isEntityTile()) { + return true; + } + return false; } -int Level::getTileLightBlock(int x, int y, int z) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return 0; - } - if (y < minBuildHeight) return 0; - if (y >= maxBuildHeight) return 0; - return getChunk(x >> 4, z >> 4)->getTileLightBlock(x & 15, y, z & 15); +int Level::getTileRenderShape(int x, int y, int z) { + int t = getTile(x, y, z); + if (Tile::tiles[t] != NULL) { + return Tile::tiles[t]->getRenderShape(); + } + return Tile::SHAPE_INVISIBLE; } -bool Level::isEmptyTile(int x, int y, int z) -{ - return getTile(x, y, z) == 0; -} - -bool Level::isEntityTile(int x, int y, int z) -{ - int t = getTile(x, y, z); - if (Tile::tiles[t] != NULL && Tile::tiles[t]->isEntityTile()) - { - return true; - } - return false; -} - -int Level::getTileRenderShape(int x, int y, int z) -{ - int t = getTile(x, y, z); - if (Tile::tiles[t] != NULL) - { - return Tile::tiles[t]->getRenderShape(); - } - return Tile::SHAPE_INVISIBLE; -} - -bool Level::hasChunkAt(int x, int y, int z) -{ - if (y < minBuildHeight || y >= maxBuildHeight) return false; - return hasChunk(x >> 4, z >> 4); +bool Level::hasChunkAt(int x, int y, int z) { + if (y < minBuildHeight || y >= maxBuildHeight) return false; + return hasChunk(x >> 4, z >> 4); } // 4J added -bool Level::reallyHasChunkAt(int x, int y, int z) -{ - if (y < minBuildHeight || y >= maxBuildHeight) return false; - return reallyHasChunk(x >> 4, z >> 4); +bool Level::reallyHasChunkAt(int x, int y, int z) { + if (y < minBuildHeight || y >= maxBuildHeight) return false; + return reallyHasChunk(x >> 4, z >> 4); } -bool Level::hasChunksAt(int x, int y, int z, int r) -{ - return hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r); +bool Level::hasChunksAt(int x, int y, int z, int r) { + return hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r); } // 4J added -bool Level::reallyHasChunksAt(int x, int y, int z, int r) -{ - return reallyHasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r); +bool Level::reallyHasChunksAt(int x, int y, int z, int r) { + return reallyHasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r); } +bool Level::hasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1) { + if (y1 < minBuildHeight || y0 >= maxBuildHeight) return false; -bool Level::hasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1) -{ - if (y1 < minBuildHeight || y0 >= maxBuildHeight) return false; + x0 >>= 4; + z0 >>= 4; + x1 >>= 4; + z1 >>= 4; - x0 >>= 4; - z0 >>= 4; - x1 >>= 4; - z1 >>= 4; + for (int x = x0; x <= x1; x++) + for (int z = z0; z <= z1; z++) + if (!hasChunk(x, z)) return false; - for (int x = x0; x <= x1; x++) - for (int z = z0; z <= z1; z++) - if (!hasChunk(x, z)) return false; - - return true; + return true; } // 4J added -bool Level::reallyHasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1) -{ - x0 >>= 4; - z0 >>= 4; - x1 >>= 4; - z1 >>= 4; +bool Level::reallyHasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1) { + x0 >>= 4; + z0 >>= 4; + x1 >>= 4; + z1 >>= 4; - for (int x = x0; x <= x1; x++) - for (int z = z0; z <= z1; z++) - if (!reallyHasChunk(x, z)) return false; + for (int x = x0; x <= x1; x++) + for (int z = z0; z <= z1; z++) + if (!reallyHasChunk(x, z)) return false; - return true; + return true; } -bool Level::hasChunk(int x, int z) -{ - return this->chunkSource->hasChunk(x, z); -} +bool Level::hasChunk(int x, int z) { return this->chunkSource->hasChunk(x, z); } // 4J added -bool Level::reallyHasChunk(int x, int z) -{ - return this->chunkSource->reallyHasChunk(x, z); +bool Level::reallyHasChunk(int x, int z) { + return this->chunkSource->reallyHasChunk(x, z); } +LevelChunk* Level::getChunkAt(int x, int z) { return getChunk(x >> 4, z >> 4); } -LevelChunk *Level::getChunkAt(int x, int z) -{ - return getChunk(x >> 4, z >> 4); +LevelChunk* Level::getChunk(int x, int z) { + return this->chunkSource->getChunk(x, z); } - -LevelChunk *Level::getChunk(int x, int z) -{ - return this->chunkSource->getChunk(x, z); +bool Level::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) { + return setTileAndDataNoUpdate(x, y, z, tile, data, true); } - -bool Level::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) -{ - return setTileAndDataNoUpdate(x, y, z, tile, data, true); -} - -bool Level::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data, bool informClients) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return false; - } - if (y < 0) return false; - if (y >= maxBuildHeight) return false; - LevelChunk *c = getChunk(x >> 4, z >> 4); - // 4J - changes for lighting brought forward from 1.8.2 - bool result; +bool Level::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data, + bool informClients) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return false; + } + if (y < 0) return false; + if (y >= maxBuildHeight) return false; + LevelChunk* c = getChunk(x >> 4, z >> 4); + // 4J - changes for lighting brought forward from 1.8.2 + bool result; #ifndef _CONTENT_PACKAGE - int old = c->getTile(x & 15, y, z & 15); - int olddata = c->getData( x & 15, y, z & 15); + int old = c->getTile(x & 15, y, z & 15); + int olddata = c->getData(x & 15, y, z & 15); #endif - result = c->setTileAndData(x & 15, y, z & 15, tile, data); + result = c->setTileAndData(x & 15, y, z & 15, tile, data); #ifndef _CONTENT_PACKAGE - PIXBeginNamedEvent(0,"Checking light %d %d %d",x,y,z); - PIXBeginNamedEvent(0,"was %d, %d now %d, %d",old,olddata,tile,data); + PIXBeginNamedEvent(0, "Checking light %d %d %d", x, y, z); + PIXBeginNamedEvent(0, "was %d, %d now %d, %d", old, olddata, tile, data); #endif - this->checkLight(x, y, z); - PIXEndNamedEvent(); - PIXEndNamedEvent(); - if (informClients && result && (isClientSide || c->seenByPlayer)) sendTileUpdated(x, y, z); - return result; + this->checkLight(x, y, z); + PIXEndNamedEvent(); + PIXEndNamedEvent(); + if (informClients && result && (isClientSide || c->seenByPlayer)) + sendTileUpdated(x, y, z); + return result; } - -bool Level::setTileNoUpdate(int x, int y, int z, int tile) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return false; - } - if (y < 0) return false; - if (y >= maxBuildHeight) return false; - LevelChunk *c = getChunk(x >> 4, z >> 4); - // 4J - changes for lighting brought forward from 1.8.2 - bool result = c->setTile(x & 15, y, z & 15, tile); - this->checkLight(x, y, z); - if (result && (isClientSide || c->seenByPlayer)) sendTileUpdated(x, y, z); - return result; +bool Level::setTileNoUpdate(int x, int y, int z, int tile) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return false; + } + if (y < 0) return false; + if (y >= maxBuildHeight) return false; + LevelChunk* c = getChunk(x >> 4, z >> 4); + // 4J - changes for lighting brought forward from 1.8.2 + bool result = c->setTile(x & 15, y, z & 15, tile); + this->checkLight(x, y, z); + if (result && (isClientSide || c->seenByPlayer)) sendTileUpdated(x, y, z); + return result; } -bool Level::setTileNoUpdateNoLightCheck(int x, int y, int z, int tile) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return false; - } - if (y < 0) return false; - if (y >= maxBuildHeight) return false; - LevelChunk *c = getChunk(x >> 4, z >> 4); - // 4J - changes for lighting brought forward from 1.8.2 - bool result = c->setTile(x & 15, y, z & 15, tile); - return result; +bool Level::setTileNoUpdateNoLightCheck(int x, int y, int z, int tile) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return false; + } + if (y < 0) return false; + if (y >= maxBuildHeight) return false; + LevelChunk* c = getChunk(x >> 4, z >> 4); + // 4J - changes for lighting brought forward from 1.8.2 + bool result = c->setTile(x & 15, y, z & 15, tile); + return result; } - -Material *Level::getMaterial(int x, int y, int z) -{ - int t = getTile(x, y, z); - if (t == 0) return Material::air; - return Tile::tiles[t]->material; +Material* Level::getMaterial(int x, int y, int z) { + int t = getTile(x, y, z); + if (t == 0) return Material::air; + return Tile::tiles[t]->material; } - -int Level::getData(int x, int y, int z) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return 0; - } - if (y < 0) return 0; - if (y >= maxBuildHeight) return 0; - LevelChunk *c = getChunk(x >> 4, z >> 4); - x &= 15; - z &= 15; - return c->getData(x, y, z); +int Level::getData(int x, int y, int z) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return 0; + } + if (y < 0) return 0; + if (y >= maxBuildHeight) return 0; + LevelChunk* c = getChunk(x >> 4, z >> 4); + x &= 15; + z &= 15; + return c->getData(x, y, z); } - -void Level::setData(int x, int y, int z, int data, bool forceUpdate/*=false*/) // 4J added forceUpdate +void Level::setData(int x, int y, int z, int data, + bool forceUpdate /*=false*/) // 4J added forceUpdate { - if (setDataNoUpdate(x, y, z, data) || forceUpdate) - { - tileUpdated(x, y, z, getTile(x, y, z)); - } + if (setDataNoUpdate(x, y, z, data) || forceUpdate) { + tileUpdated(x, y, z, getTile(x, y, z)); + } } -bool Level::setDataNoUpdate(int x, int y, int z, int data) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return false; - } - if (y < 0) return false; - if (y >= maxBuildHeight) return false; - LevelChunk *c = getChunk(x >> 4, z >> 4); - int cx = x & 15; - int cz = z & 15; - // 4J - have changed _sendTileData to encode a bitfield of which bits are important to be sent. This will be zero where the original flag was false, and non-zero where the original - // flag was true - hence recreating the original flag as sendTileData here. For nearly all tiles this will be 15 for the case where this used to be true (ie all bits are important) so - // there should be absolutely to change in behaviour. However, for leaf tiles, bits have been masked so we don't bother doing sendTileUpdated if a non-visual thing has changed in the data - unsigned char importantMask = Tile::_sendTileData[c->getTile(cx, y, cz) & Tile::TILE_NUM_MASK]; - bool sendTileData = importantMask != 0; +bool Level::setDataNoUpdate(int x, int y, int z, int data) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return false; + } + if (y < 0) return false; + if (y >= maxBuildHeight) return false; + LevelChunk* c = getChunk(x >> 4, z >> 4); + int cx = x & 15; + int cz = z & 15; + // 4J - have changed _sendTileData to encode a bitfield of which bits are + // important to be sent. This will be zero where the original flag was + // false, and non-zero where the original flag was true - hence recreating + // the original flag as sendTileData here. For nearly all tiles this will be + // 15 for the case where this used to be true (ie all bits are important) so + // there should be absolutely to change in behaviour. However, for leaf + // tiles, bits have been masked so we don't bother doing sendTileUpdated if + // a non-visual thing has changed in the data + unsigned char importantMask = + Tile::_sendTileData[c->getTile(cx, y, cz) & Tile::TILE_NUM_MASK]; + bool sendTileData = importantMask != 0; - bool maskedBitsChanged; - bool result = c->setData(cx, y, cz, data, importantMask, &maskedBitsChanged); - if (result && (isClientSide || (c->seenByPlayer && sendTileData && maskedBitsChanged))) sendTileUpdated(x, y, z); - return result; + bool maskedBitsChanged; + bool result = + c->setData(cx, y, cz, data, importantMask, &maskedBitsChanged); + if (result && (isClientSide || + (c->seenByPlayer && sendTileData && maskedBitsChanged))) + sendTileUpdated(x, y, z); + return result; } - -bool Level::setTile(int x, int y, int z, int tile) -{ - if (setTileNoUpdate(x, y, z, tile)) - { - tileUpdated(x, y, z, tile); - return true; - } - return false; +bool Level::setTile(int x, int y, int z, int tile) { + if (setTileNoUpdate(x, y, z, tile)) { + tileUpdated(x, y, z, tile); + return true; + } + return false; } - -bool Level::setTileAndData(int x, int y, int z, int tile, int data) -{ - if (setTileAndDataNoUpdate(x, y, z, tile, data)) - { - tileUpdated(x, y, z, tile); - return true; - } - return false; +bool Level::setTileAndData(int x, int y, int z, int tile, int data) { + if (setTileAndDataNoUpdate(x, y, z, tile, data)) { + tileUpdated(x, y, z, tile); + return true; + } + return false; } -void Level::sendTileUpdated(int x, int y, int z) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->tileChanged(x, y, z); - } +void Level::sendTileUpdated(int x, int y, int z) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->tileChanged(x, y, z); + } } -void Level::tileUpdated(int x, int y, int z, int tile) -{ - this->updateNeighborsAt(x, y, z, tile); +void Level::tileUpdated(int x, int y, int z, int tile) { + this->updateNeighborsAt(x, y, z, tile); } +void Level::lightColumnChanged(int x, int z, int y0, int y1) { + PIXBeginNamedEvent(0, "LightColumnChanged (%d,%d) %d to %d", x, z, y0, y1); + if (y0 > y1) { + int tmp = y1; + y1 = y0; + y0 = tmp; + } -void Level::lightColumnChanged(int x, int z, int y0, int y1) -{ - PIXBeginNamedEvent(0,"LightColumnChanged (%d,%d) %d to %d",x,z,y0,y1); - if (y0 > y1) - { - int tmp = y1; - y1 = y0; - y0 = tmp; - } - - if (!dimension->hasCeiling) - { - PIXBeginNamedEvent(0,"Checking lights"); - for (int y = y0; y <= y1; y++) - { - PIXBeginNamedEvent(0,"Checking light %d", y); - checkLight(LightLayer::Sky, x, y, z); - PIXEndNamedEvent(); - } - PIXEndNamedEvent(); - } - PIXBeginNamedEvent(0,"Setting tiles dirty"); - setTilesDirty(x, y0, z, x, y1, z); - PIXEndNamedEvent(); - PIXEndNamedEvent(); + if (!dimension->hasCeiling) { + PIXBeginNamedEvent(0, "Checking lights"); + for (int y = y0; y <= y1; y++) { + PIXBeginNamedEvent(0, "Checking light %d", y); + checkLight(LightLayer::Sky, x, y, z); + PIXEndNamedEvent(); + } + PIXEndNamedEvent(); + } + PIXBeginNamedEvent(0, "Setting tiles dirty"); + setTilesDirty(x, y0, z, x, y1, z); + PIXEndNamedEvent(); + PIXEndNamedEvent(); } - -void Level::setTileDirty(int x, int y, int z) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->setTilesDirty(x, y, z, x, y, z, this); - } +void Level::setTileDirty(int x, int y, int z) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->setTilesDirty(x, y, z, x, y, z, this); + } } - -void Level::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->setTilesDirty(x0, y0, z0, x1, y1, z1, this); - } +void Level::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->setTilesDirty(x0, y0, z0, x1, y1, z1, this); + } } +void Level::swap(int x1, int y1, int z1, int x2, int y2, int z2) { + int t1 = getTile(x1, y1, z1); + int d1 = getData(x1, y1, z1); + int t2 = getTile(x2, y2, z2); + int d2 = getData(x2, y2, z2); -void Level::swap(int x1, int y1, int z1, int x2, int y2, int z2) -{ - int t1 = getTile(x1, y1, z1); - int d1 = getData(x1, y1, z1); - int t2 = getTile(x2, y2, z2); - int d2 = getData(x2, y2, z2); + setTileAndDataNoUpdate(x1, y1, z1, t2, d2); + setTileAndDataNoUpdate(x2, y2, z2, t1, d1); - setTileAndDataNoUpdate(x1, y1, z1, t2, d2); - setTileAndDataNoUpdate(x2, y2, z2, t1, d1); - - updateNeighborsAt(x1, y1, z1, t2); - updateNeighborsAt(x2, y2, z2, t1); + updateNeighborsAt(x1, y1, z1, t2); + updateNeighborsAt(x2, y2, z2, t1); } - -void Level::updateNeighborsAt(int x, int y, int z, int tile) -{ - neighborChanged(x - 1, y, z, tile); - neighborChanged(x + 1, y, z, tile); - neighborChanged(x, y - 1, z, tile); - neighborChanged(x, y + 1, z, tile); - neighborChanged(x, y, z - 1, tile); - neighborChanged(x, y, z + 1, tile); +void Level::updateNeighborsAt(int x, int y, int z, int tile) { + neighborChanged(x - 1, y, z, tile); + neighborChanged(x + 1, y, z, tile); + neighborChanged(x, y - 1, z, tile); + neighborChanged(x, y + 1, z, tile); + neighborChanged(x, y, z - 1, tile); + neighborChanged(x, y, z + 1, tile); } - -void Level::neighborChanged(int x, int y, int z, int type) -{ - if (noNeighborUpdate || isClientSide) return; - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL) tile->neighborChanged(this, x, y, z, type); +void Level::neighborChanged(int x, int y, int z, int type) { + if (noNeighborUpdate || isClientSide) return; + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL) tile->neighborChanged(this, x, y, z, type); } - - -bool Level::canSeeSky(int x, int y, int z) -{ - return getChunk(x >> 4, z >> 4)->isSkyLit(x & 15, y, z & 15); +bool Level::canSeeSky(int x, int y, int z) { + return getChunk(x >> 4, z >> 4)->isSkyLit(x & 15, y, z & 15); } - -int Level::getDaytimeRawBrightness(int x, int y, int z) -{ - if (y < 0) return 0; - if (y >= maxBuildHeight) y = maxBuildHeight - 1; - return getChunk(x >> 4, z >> 4)->getRawBrightness(x & 15, y, z & 15, 0); +int Level::getDaytimeRawBrightness(int x, int y, int z) { + if (y < 0) return 0; + if (y >= maxBuildHeight) y = maxBuildHeight - 1; + return getChunk(x >> 4, z >> 4)->getRawBrightness(x & 15, y, z & 15, 0); } - -int Level::getRawBrightness(int x, int y, int z) -{ - return getRawBrightness(x, y, z, true); +int Level::getRawBrightness(int x, int y, int z) { + return getRawBrightness(x, y, z, true); } +int Level::getRawBrightness(int x, int y, int z, bool propagate) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return MAX_BRIGHTNESS; + } -int Level::getRawBrightness(int x, int y, int z, bool propagate) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return MAX_BRIGHTNESS; - } + if (propagate) { + int id = getTile(x, y, z); + switch (id) { + case Tile::stoneSlabHalf_Id: + case Tile::woodSlabHalf_Id: + case Tile::farmland_Id: + case Tile::stairs_stone_Id: + case Tile::stairs_wood_Id: { + int br = getRawBrightness(x, y + 1, z, false); + int br1 = getRawBrightness(x + 1, y, z, false); + int br2 = getRawBrightness(x - 1, y, z, false); + int br3 = getRawBrightness(x, y, z + 1, false); + int br4 = getRawBrightness(x, y, z - 1, false); + if (br1 > br) br = br1; + if (br2 > br) br = br2; + if (br3 > br) br = br3; + if (br4 > br) br = br4; + return br; + } break; + } + } - if (propagate) - { - int id = getTile(x, y, z); - switch(id) - { - case Tile::stoneSlabHalf_Id: - case Tile::woodSlabHalf_Id: - case Tile::farmland_Id: - case Tile::stairs_stone_Id: - case Tile::stairs_wood_Id: - { - int br = getRawBrightness(x, y + 1, z, false); - int br1 = getRawBrightness(x + 1, y, z, false); - int br2 = getRawBrightness(x - 1, y, z, false); - int br3 = getRawBrightness(x, y, z + 1, false); - int br4 = getRawBrightness(x, y, z - 1, false); - if (br1 > br) br = br1; - if (br2 > br) br = br2; - if (br3 > br) br = br3; - if (br4 > br) br = br4; - return br; - } - break; - } - } + if (y < 0) return 0; + if (y >= maxBuildHeight) y = maxBuildHeight - 1; - if (y < 0) return 0; - if (y >= maxBuildHeight) y = maxBuildHeight - 1; - - LevelChunk *c = getChunk(x >> 4, z >> 4); - x &= 15; - z &= 15; - return c->getRawBrightness(x, y, z, skyDarken); + LevelChunk* c = getChunk(x >> 4, z >> 4); + x &= 15; + z &= 15; + return c->getRawBrightness(x, y, z, skyDarken); } +bool Level::isSkyLit(int x, int y, int z) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return false; + } + if (dimension->hasCeiling) return false; -bool Level::isSkyLit(int x, int y, int z) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return false; - } - if (dimension->hasCeiling) return false; + if (y < 0) return false; + if (y >= maxBuildHeight) return true; + if (!hasChunk(x >> 4, z >> 4)) return false; - if (y < 0) return false; - if (y >= maxBuildHeight) return true; - if (!hasChunk(x >> 4, z >> 4)) return false; - - LevelChunk *c = getChunk(x >> 4, z >> 4); - x &= 15; - z &= 15; - return c->isSkyLit(x, y, z); + LevelChunk* c = getChunk(x >> 4, z >> 4); + x &= 15; + z &= 15; + return c->isSkyLit(x, y, z); } +int Level::getHeightmap(int x, int z) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return 0; + } + if (!hasChunk(x >> 4, z >> 4)) return 0; -int Level::getHeightmap(int x, int z) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return 0; - } - if (!hasChunk(x >> 4, z >> 4)) return 0; - - LevelChunk *c = getChunk(x >> 4, z >> 4); - return c->getHeightmap(x & 15, z & 15); + LevelChunk* c = getChunk(x >> 4, z >> 4); + return c->getHeightmap(x & 15, z & 15); } +void Level::updateLightIfOtherThan(LightLayer::variety layer, int x, int y, + int z, int expected) { + if (dimension->hasCeiling && layer == LightLayer::Sky) return; -void Level::updateLightIfOtherThan(LightLayer::variety layer, int x, int y, int z, int expected) -{ - if (dimension->hasCeiling && layer == LightLayer::Sky) return; + if (!hasChunkAt(x, y, z)) return; - if (!hasChunkAt(x, y, z)) return; + if (layer == LightLayer::Sky) { + if (isSkyLit(x, y, z)) expected = 15; + } else if (layer == LightLayer::Block) { + int t = getTile(x, y, z); + if (Tile::lightEmission[t] > expected) + expected = Tile::lightEmission[t]; + } - if (layer == LightLayer::Sky) - { - if (isSkyLit(x, y, z)) expected = 15; - } - else if (layer == LightLayer::Block) - { - int t = getTile(x, y, z); - if (Tile::lightEmission[t] > expected) expected = Tile::lightEmission[t]; - } - - if (getBrightness(layer, x, y, z) != expected) - { - setBrightness(layer, x, y, z, expected); - } + if (getBrightness(layer, x, y, z) != expected) { + setBrightness(layer, x, y, z, expected); + } } // 4J - update brought forward from 1.8.2 -int Level::getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, int tileId) -{ - if (dimension->hasCeiling && layer == LightLayer::Sky) return 0; +int Level::getBrightnessPropagate(LightLayer::variety layer, int x, int y, + int z, int tileId) { + if (dimension->hasCeiling && layer == LightLayer::Sky) return 0; if (y < 0) y = 0; - if (y >= maxBuildHeight && layer == LightLayer::Sky) - { - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - return (int)layer; + if (y >= maxBuildHeight && layer == LightLayer::Sky) { + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + return (int)layer; } - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - return (int)layer; + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + return (int)layer; } int xc = x >> 4; int zc = z >> 4; if (!hasChunk(xc, zc)) return (int)layer; { - int id = tileId > -1 ? tileId : getTile(x,y,z); - if (Tile::propagate[id]) - { + int id = tileId > -1 ? tileId : getTile(x, y, z); + if (Tile::propagate[id]) { int br = getBrightness(layer, x, y + 1, z); int br1 = getBrightness(layer, x + 1, y, z); int br2 = getBrightness(layer, x - 1, y, z); @@ -1305,708 +1198,647 @@ int Level::getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z } } - LevelChunk *c = getChunk(xc, zc); + LevelChunk* c = getChunk(xc, zc); return c->getBrightness(layer, x & 15, y, z & 15); } -int Level::getBrightness(LightLayer::variety layer, int x, int y, int z) -{ - // 4J - optimised. Not doing checks on x/z that are no longer necessary, and directly checking the cache within - // the ServerChunkCache/MultiplayerChunkCache rather than going through wrappers & virtual functions. - int xc = x >> 4; - int zc = z >> 4; +int Level::getBrightness(LightLayer::variety layer, int x, int y, int z) { + // 4J - optimised. Not doing checks on x/z that are no longer necessary, and + // directly checking the cache within the + // ServerChunkCache/MultiplayerChunkCache rather than going through wrappers + // & virtual functions. + int xc = x >> 4; + int zc = z >> 4; - int ix = xc + (chunkSourceXZSize/2); - int iz = zc + (chunkSourceXZSize/2); + int ix = xc + (chunkSourceXZSize / 2); + int iz = zc + (chunkSourceXZSize / 2); - if( ( ix < 0 ) || ( ix >= chunkSourceXZSize ) ) return 0; - if( ( iz < 0 ) || ( iz >= chunkSourceXZSize ) ) return 0; - int idx = ix * chunkSourceXZSize + iz; - LevelChunk *c = chunkSourceCache[idx]; + if ((ix < 0) || (ix >= chunkSourceXZSize)) return 0; + if ((iz < 0) || (iz >= chunkSourceXZSize)) return 0; + int idx = ix * chunkSourceXZSize + iz; + LevelChunk* c = chunkSourceCache[idx]; - if( c == NULL ) return (int)layer; + if (c == NULL) return (int)layer; if (y < 0) y = 0; if (y >= maxBuildHeight) y = maxBuildHeight - 1; - return c->getBrightness(layer, x & 15, y, z & 15); + return c->getBrightness(layer, x & 15, y, z & 15); } -// 4J added as optimisation - if all the neighbouring brightesses are going to be in the one chunk, just get -// the level chunk once -void Level::getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z) -{ - if( ( ( ( x & 15 ) == 0 ) || ( ( x & 15 ) == 15 ) ) || - ( ( ( z & 15 ) == 0 ) || ( ( z & 15 ) == 15 ) ) || - ( ( y <= 0 ) || ( y >= 127 ) ) ) - { - // We're spanning more than one chunk, just fall back on original java method here - brightnesses[0] = getBrightness(layer, x - 1, y, z); - brightnesses[1] = getBrightness(layer, x + 1, y, z); - brightnesses[2] = getBrightness(layer, x, y - 1, z); - brightnesses[3] = getBrightness(layer, x, y + 1, z); - brightnesses[4] = getBrightness(layer, x, y, z - 1); - brightnesses[5] = getBrightness(layer, x, y, z + 1); - } - else - { - // All in one chunk - just get the chunk once, and do a single call to get the results - int xc = x >> 4; - int zc = z >> 4; +// 4J added as optimisation - if all the neighbouring brightesses are going to +// be in the one chunk, just get the level chunk once +void Level::getNeighbourBrightnesses(int* brightnesses, + LightLayer::variety layer, int x, int y, + int z) { + if ((((x & 15) == 0) || ((x & 15) == 15)) || + (((z & 15) == 0) || ((z & 15) == 15)) || ((y <= 0) || (y >= 127))) { + // We're spanning more than one chunk, just fall back on original java + // method here + brightnesses[0] = getBrightness(layer, x - 1, y, z); + brightnesses[1] = getBrightness(layer, x + 1, y, z); + brightnesses[2] = getBrightness(layer, x, y - 1, z); + brightnesses[3] = getBrightness(layer, x, y + 1, z); + brightnesses[4] = getBrightness(layer, x, y, z - 1); + brightnesses[5] = getBrightness(layer, x, y, z + 1); + } else { + // All in one chunk - just get the chunk once, and do a single call to + // get the results + int xc = x >> 4; + int zc = z >> 4; - int ix = xc + (chunkSourceXZSize/2); - int iz = zc + (chunkSourceXZSize/2); + int ix = xc + (chunkSourceXZSize / 2); + int iz = zc + (chunkSourceXZSize / 2); - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - if( ( ( ix < 0 ) || ( ix >= chunkSourceXZSize ) ) || - ( ( iz < 0 ) || ( iz >= chunkSourceXZSize ) ) ) - { - for( int i = 0; i < 6; i++ ) - { - brightnesses[i] = (int)layer; - } - return; - } + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + if (((ix < 0) || (ix >= chunkSourceXZSize)) || + ((iz < 0) || (iz >= chunkSourceXZSize))) { + for (int i = 0; i < 6; i++) { + brightnesses[i] = (int)layer; + } + return; + } - int idx = ix * chunkSourceXZSize + iz; - LevelChunk *c = chunkSourceCache[idx]; + int idx = ix * chunkSourceXZSize + iz; + LevelChunk* c = chunkSourceCache[idx]; - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - if( c == NULL ) - { - for( int i = 0; i < 6; i++ ) - { - brightnesses[i] = (int)layer; - } - return; - } + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + if (c == NULL) { + for (int i = 0; i < 6; i++) { + brightnesses[i] = (int)layer; + } + return; + } - // Single call to the levelchunk too to avoid overhead of virtual fn calls - c->getNeighbourBrightnesses(brightnesses, layer, x & 15, y, z & 15); - } + // Single call to the levelchunk too to avoid overhead of virtual fn + // calls + c->getNeighbourBrightnesses(brightnesses, layer, x & 15, y, z & 15); + } } -void Level::setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness, bool noUpdateOnClient/*=false*/) // 4J added noUpdateOnClient +void Level::setBrightness( + LightLayer::variety layer, int x, int y, int z, int brightness, + bool noUpdateOnClient /*=false*/) // 4J added noUpdateOnClient { - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { - return; - } - if (y < 0) return; - if (y >= maxBuildHeight) return; - if (!hasChunk(x >> 4, z >> 4)) return; - LevelChunk *c = getChunk(x >> 4, z >> 4); + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { + return; + } + if (y < 0) return; + if (y >= maxBuildHeight) return; + if (!hasChunk(x >> 4, z >> 4)) return; + LevelChunk* c = getChunk(x >> 4, z >> 4); - c->setBrightness(layer, x & 15, y, z & 15, brightness); + c->setBrightness(layer, x & 15, y, z & 15, brightness); - // 4J added - if( isClientSide && noUpdateOnClient ) - { - if( cachewritten ) - { - if( x < cacheminx ) cacheminx = x; - if( x > cachemaxx ) cachemaxx = x; - if( y < cacheminy ) cacheminy = y; - if( y > cachemaxy ) cachemaxy = y; - if( z < cacheminz ) cacheminz = z; - if( z > cachemaxz ) cachemaxz = z; - } - else - { - cachewritten = true; - cacheminx = x; - cachemaxx = x; - cacheminy = y; - cachemaxy = y; - cacheminz = z; - cachemaxz = z; - } - } - else - { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->tileLightChanged(x, y, z); - } - } + // 4J added + if (isClientSide && noUpdateOnClient) { + if (cachewritten) { + if (x < cacheminx) cacheminx = x; + if (x > cachemaxx) cachemaxx = x; + if (y < cacheminy) cacheminy = y; + if (y > cachemaxy) cachemaxy = y; + if (z < cacheminz) cacheminz = z; + if (z > cachemaxz) cachemaxz = z; + } else { + cachewritten = true; + cacheminx = x; + cachemaxx = x; + cacheminy = y; + cachemaxy = y; + cacheminz = z; + cachemaxz = z; + } + } else { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->tileLightChanged(x, y, z); + } + } } -void Level::setTileBrightnessChanged(int x, int y, int z) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->tileLightChanged(x, y, z); - } +void Level::setTileBrightnessChanged(int x, int y, int z) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->tileLightChanged(x, y, z); + } } -int Level::getLightColor(int x, int y, int z, int emitt, int tileId/*=-1*/) -{ - int s = getBrightnessPropagate(LightLayer::Sky, x, y, z, tileId); +int Level::getLightColor(int x, int y, int z, int emitt, int tileId /*=-1*/) { + int s = getBrightnessPropagate(LightLayer::Sky, x, y, z, tileId); int b = getBrightnessPropagate(LightLayer::Block, x, y, z, tileId); if (b < emitt) b = emitt; return s << 20 | b << 4; } -float Level::getBrightness(int x, int y, int z, int emitt) -{ - int n = getRawBrightness(x, y, z); - if (n < emitt) n = emitt; - return dimension->brightnessRamp[n]; +float Level::getBrightness(int x, int y, int z, int emitt) { + int n = getRawBrightness(x, y, z); + if (n < emitt) n = emitt; + return dimension->brightnessRamp[n]; } - -float Level::getBrightness(int x, int y, int z) -{ - return dimension->brightnessRamp[getRawBrightness(x, y, z)]; +float Level::getBrightness(int x, int y, int z) { + return dimension->brightnessRamp[getRawBrightness(x, y, z)]; } +bool Level::isDay() { return this->skyDarken < 4; } -bool Level::isDay() -{ - return this->skyDarken < 4; +HitResult* Level::clip(Vec3* a, Vec3* b) { return clip(a, b, false, false); } + +HitResult* Level::clip(Vec3* a, Vec3* b, bool liquid) { + return clip(a, b, liquid, false); } +HitResult* Level::clip(Vec3* a, Vec3* b, bool liquid, bool solidOnly) { + if (Double::isNaN(a->x) || Double::isNaN(a->y) || Double::isNaN(a->z)) + return NULL; + if (Double::isNaN(b->x) || Double::isNaN(b->y) || Double::isNaN(b->z)) + return NULL; -HitResult *Level::clip(Vec3 *a, Vec3 *b) -{ - return clip(a, b, false, false); + int xTile1 = Mth::floor(b->x); + int yTile1 = Mth::floor(b->y); + int zTile1 = Mth::floor(b->z); + + int xTile0 = Mth::floor(a->x); + int yTile0 = Mth::floor(a->y); + int zTile0 = Mth::floor(a->z); + + { + int t = getTile(xTile0, yTile0, zTile0); + int data = getData(xTile0, yTile0, zTile0); + Tile* tile = Tile::tiles[t]; + if (solidOnly && tile != NULL && + tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) { + // No collision + + } else if (t > 0 && tile->mayPick(data, liquid)) { + HitResult* r = tile->clip(this, xTile0, yTile0, zTile0, a, b); + if (r != NULL) return r; + } + } + + int maxIterations = 200; + while (maxIterations-- >= 0) { + if (Double::isNaN(a->x) || Double::isNaN(a->y) || Double::isNaN(a->z)) + return NULL; + if (xTile0 == xTile1 && yTile0 == yTile1 && zTile0 == zTile1) + return NULL; + + bool xClipped = true; + bool yClipped = true; + bool zClipped = true; + + double xClip = 999; + double yClip = 999; + double zClip = 999; + + if (xTile1 > xTile0) + xClip = xTile0 + 1.000; + else if (xTile1 < xTile0) + xClip = xTile0 + 0.000; + else + xClipped = false; + + if (yTile1 > yTile0) + yClip = yTile0 + 1.000; + else if (yTile1 < yTile0) + yClip = yTile0 + 0.000; + else + yClipped = false; + + if (zTile1 > zTile0) + zClip = zTile0 + 1.000; + else if (zTile1 < zTile0) + zClip = zTile0 + 0.000; + else + zClipped = false; + + double xDist = 999; + double yDist = 999; + double zDist = 999; + + double xd = b->x - a->x; + double yd = b->y - a->y; + double zd = b->z - a->z; + + if (xClipped) xDist = (xClip - a->x) / xd; + if (yClipped) yDist = (yClip - a->y) / yd; + if (zClipped) zDist = (zClip - a->z) / zd; + + int face = 0; + if (xDist < yDist && xDist < zDist) { + if (xTile1 > xTile0) + face = 4; + else + face = 5; + + a->x = xClip; + a->y += yd * xDist; + a->z += zd * xDist; + } else if (yDist < zDist) { + if (yTile1 > yTile0) + face = 0; + else + face = 1; + + a->x += xd * yDist; + a->y = yClip; + a->z += zd * yDist; + } else { + if (zTile1 > zTile0) + face = 2; + else + face = 3; + + a->x += xd * zDist; + a->y += yd * zDist; + a->z = zClip; + } + + Vec3* tPos = Vec3::newTemp(a->x, a->y, a->z); + xTile0 = (int)(tPos->x = floor(a->x)); + if (face == 5) { + xTile0--; + tPos->x++; + } + yTile0 = (int)(tPos->y = floor(a->y)); + if (face == 1) { + yTile0--; + tPos->y++; + } + zTile0 = (int)(tPos->z = floor(a->z)); + if (face == 3) { + zTile0--; + tPos->z++; + } + + int t = getTile(xTile0, yTile0, zTile0); + int data = getData(xTile0, yTile0, zTile0); + Tile* tile = Tile::tiles[t]; + if (solidOnly && tile != NULL && + tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) { + // No collision + + } else if (t > 0 && tile->mayPick(data, liquid)) { + HitResult* r = tile->clip(this, xTile0, yTile0, zTile0, a, b); + if (r != NULL) return r; + } + } + return NULL; } +void Level::playSound(std::shared_ptr entity, int iSound, float volume, + float pitch) { + if (entity == NULL) return; + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + // 4J-PB - if the entity is a local player, don't play the sound + if (entity->GetType() == eTYPE_SERVERPLAYER) { + // app.DebugPrintf("ENTITY is serverplayer\n"); -HitResult *Level::clip(Vec3 *a, Vec3 *b, bool liquid) -{ - return clip(a, b, liquid, false); + (*it)->playSound(entity, iSound, entity->x, + entity->y - entity->heightOffset, entity->z, + volume, pitch); + } else { + (*it)->playSound(iSound, entity->x, + entity->y - entity->heightOffset, entity->z, + volume, pitch); + } + } } - -HitResult *Level::clip(Vec3 *a, Vec3 *b, bool liquid, bool solidOnly) -{ - if (Double::isNaN(a->x) || Double::isNaN(a->y) || Double::isNaN(a->z)) return NULL; - if (Double::isNaN(b->x) || Double::isNaN(b->y) || Double::isNaN(b->z)) return NULL; - - int xTile1 = Mth::floor(b->x); - int yTile1 = Mth::floor(b->y); - int zTile1 = Mth::floor(b->z); - - int xTile0 = Mth::floor(a->x); - int yTile0 = Mth::floor(a->y); - int zTile0 = Mth::floor(a->z); - - { - int t = getTile(xTile0, yTile0, zTile0); - int data = getData(xTile0, yTile0, zTile0); - Tile *tile = Tile::tiles[t]; - if (solidOnly && tile != NULL && tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) - { - // No collision - - } - else if (t > 0 && tile->mayPick(data, liquid)) - { - HitResult *r = tile->clip(this, xTile0, yTile0, zTile0, a, b); - if (r != NULL) return r; - } - } - - int maxIterations = 200; - while (maxIterations-- >= 0) - { - if (Double::isNaN(a->x) || Double::isNaN(a->y) || Double::isNaN(a->z)) return NULL; - if (xTile0 == xTile1 && yTile0 == yTile1 && zTile0 == zTile1) return NULL; - - bool xClipped = true; - bool yClipped = true; - bool zClipped = true; - - double xClip = 999; - double yClip = 999; - double zClip = 999; - - if (xTile1 > xTile0) xClip = xTile0 + 1.000; - else if (xTile1 < xTile0) xClip = xTile0 + 0.000; - else xClipped = false; - - if (yTile1 > yTile0) yClip = yTile0 + 1.000; - else if (yTile1 < yTile0) yClip = yTile0 + 0.000; - else yClipped = false; - - if (zTile1 > zTile0) zClip = zTile0 + 1.000; - else if (zTile1 < zTile0) zClip = zTile0 + 0.000; - else zClipped = false; - - double xDist = 999; - double yDist = 999; - double zDist = 999; - - double xd = b->x - a->x; - double yd = b->y - a->y; - double zd = b->z - a->z; - - if (xClipped) xDist = (xClip - a->x) / xd; - if (yClipped) yDist = (yClip - a->y) / yd; - if (zClipped) zDist = (zClip - a->z) / zd; - - int face = 0; - if (xDist < yDist && xDist < zDist) - { - if (xTile1 > xTile0) face = 4; - else face = 5; - - a->x = xClip; - a->y += yd * xDist; - a->z += zd * xDist; - } - else if (yDist < zDist) - { - if (yTile1 > yTile0) face = 0; - else face = 1; - - a->x += xd * yDist; - a->y = yClip; - a->z += zd * yDist; - } - else - { - if (zTile1 > zTile0) face = 2; - else face = 3; - - a->x += xd * zDist; - a->y += yd * zDist; - a->z = zClip; - } - - Vec3 *tPos = Vec3::newTemp(a->x, a->y, a->z); - xTile0 = (int) (tPos->x = floor(a->x)); - if (face == 5) - { - xTile0--; - tPos->x++; - } - yTile0 = (int) (tPos->y = floor(a->y)); - if (face == 1) - { - yTile0--; - tPos->y++; - } - zTile0 = (int) (tPos->z = floor(a->z)); - if (face == 3) - { - zTile0--; - tPos->z++; - } - - int t = getTile(xTile0, yTile0, zTile0); - int data = getData(xTile0, yTile0, zTile0); - Tile *tile = Tile::tiles[t]; - if (solidOnly && tile != NULL && tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) - { - // No collision - - } - else if (t > 0 && tile->mayPick(data, liquid)) - { - HitResult *r = tile->clip(this, xTile0, yTile0, zTile0, a, b); - if (r != NULL) return r; - } - } - return NULL; +// void Level::playSound(double x, double y, double z, const std::wstring& name, +// float volume, float pitch) +void Level::playSound(double x, double y, double z, int iSound, float volume, + float pitch, float fClipSoundDist) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); + } } +void Level::playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, float fClipSoundDist) {} -void Level::playSound(std::shared_ptr entity, int iSound, float volume, float pitch) -{ - if(entity == NULL) return; - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - // 4J-PB - if the entity is a local player, don't play the sound - if(entity->GetType() == eTYPE_SERVERPLAYER) - { - //app.DebugPrintf("ENTITY is serverplayer\n"); - - (*it)->playSound(entity,iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); - } - else - { - (*it)->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); - } - } +void Level::playStreamingMusic(const std::wstring& name, int x, int y, int z) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->playStreamingMusic(name, x, y, z); + } } +void Level::playMusic(double x, double y, double z, const std::wstring& string, + float volume) {} -//void Level::playSound(double x, double y, double z, const std::wstring& name, float volume, float pitch) -void Level::playSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); - } -} - -void Level::playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) -{ -} - -void Level::playStreamingMusic(const std::wstring& name, int x, int y, int z) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->playStreamingMusic(name, x, y, z); - } -} - - -void Level::playMusic(double x, double y, double z, const std::wstring& string, float volume) -{ -} - -// 4J removed - +// 4J removed - /* -void Level::addParticle(const std::wstring& id, double x, double y, double z, double xd, double yd, double zd) +void Level::addParticle(const std::wstring& id, double x, double y, double z, +double xd, double yd, double zd) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - (*it)->addParticle(id, x, y, z, xd, yd, zd); + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + (*it)->addParticle(id, x, y, z, xd, yd, zd); } */ // 4J-PB added -void Level::addParticle(ePARTICLE_TYPE id, double x, double y, double z, double xd, double yd, double zd) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - (*it)->addParticle(id, x, y, z, xd, yd, zd); +void Level::addParticle(ePARTICLE_TYPE id, double x, double y, double z, + double xd, double yd, double zd) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + (*it)->addParticle(id, x, y, z, xd, yd, zd); } -bool Level::addGlobalEntity(std::shared_ptr e) -{ - globalEntities.push_back(e); - return true; +bool Level::addGlobalEntity(std::shared_ptr e) { + globalEntities.push_back(e); + return true; } -#pragma optimize( "", off ) +#pragma optimize("", off) -bool Level::addEntity(std::shared_ptr e) -{ - int xc = Mth::floor(e->x / 16); - int zc = Mth::floor(e->z / 16); +bool Level::addEntity(std::shared_ptr e) { + int xc = Mth::floor(e->x / 16); + int zc = Mth::floor(e->z / 16); - if(e == NULL) - { - return false; - } + if (e == NULL) { + return false; + } - bool forced = false; - if (std::dynamic_pointer_cast( e ) != NULL) - { - forced = true; - } + bool forced = false; + if (std::dynamic_pointer_cast(e) != NULL) { + forced = true; + } - if (forced || hasChunk(xc, zc)) - { - if (std::dynamic_pointer_cast( e ) != NULL) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); + if (forced || hasChunk(xc, zc)) { + if (std::dynamic_pointer_cast(e) != NULL) { + std::shared_ptr player = + std::dynamic_pointer_cast(e); - // 4J Stu - Added so we don't continually add the player to the players list while they are dead - if( find( players.begin(), players.end(), e ) == players.end() ) - { - players.push_back(player); - } + // 4J Stu - Added so we don't continually add the player to the + // players list while they are dead + if (find(players.begin(), players.end(), e) == players.end()) { + players.push_back(player); + } - updateSleepingPlayerList(); - } - MemSect(42); - getChunk(xc, zc)->addEntity(e); - MemSect(0); - EnterCriticalSection(&m_entitiesCS); - MemSect(43); - entities.push_back(e); - MemSect(0); - LeaveCriticalSection(&m_entitiesCS); - MemSect(44); - entityAdded(e); - MemSect(0); - return true; - } - return false; + updateSleepingPlayerList(); + } + MemSect(42); + getChunk(xc, zc)->addEntity(e); + MemSect(0); + EnterCriticalSection(&m_entitiesCS); + MemSect(43); + entities.push_back(e); + MemSect(0); + LeaveCriticalSection(&m_entitiesCS); + MemSect(44); + entityAdded(e); + MemSect(0); + return true; + } + return false; } -#pragma optimize( "", on ) +#pragma optimize("", on) -void Level::entityAdded(std::shared_ptr e) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->entityAdded(e); - } +void Level::entityAdded(std::shared_ptr e) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->entityAdded(e); + } } - -void Level::entityRemoved(std::shared_ptr e) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->entityRemoved(e); - } +void Level::entityRemoved(std::shared_ptr e) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->entityRemoved(e); + } } // 4J added -void Level::playerRemoved(std::shared_ptr e) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->playerRemoved(e); - } +void Level::playerRemoved(std::shared_ptr e) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->playerRemoved(e); + } } -void Level::removeEntity(std::shared_ptr e) -{ - if (e->rider.lock() != NULL) - { - e->rider.lock()->ride(nullptr); - } - if (e->riding != NULL) - { - e->ride(nullptr); - } - e->remove(); - if (std::dynamic_pointer_cast( e ) != NULL) - { - std::vector >::iterator it = players.begin(); - std::vector >::iterator itEnd = players.end(); - while( it != itEnd && *it != std::dynamic_pointer_cast(e) ) - it++; +void Level::removeEntity(std::shared_ptr e) { + if (e->rider.lock() != NULL) { + e->rider.lock()->ride(nullptr); + } + if (e->riding != NULL) { + e->ride(nullptr); + } + e->remove(); + if (std::dynamic_pointer_cast(e) != NULL) { + std::vector >::iterator it = players.begin(); + std::vector >::iterator itEnd = players.end(); + while (it != itEnd && *it != std::dynamic_pointer_cast(e)) it++; - if( it != itEnd ) - { - players.erase( it ); - } + if (it != itEnd) { + players.erase(it); + } - updateSleepingPlayerList(); - playerRemoved(e); // 4J added - this will let the entity tracker know that we have actually removed the player from the level's player list - } + updateSleepingPlayerList(); + playerRemoved(e); // 4J added - this will let the entity tracker know + // that we have actually removed the player from the + // level's player list + } } +void Level::removeEntityImmediately(std::shared_ptr e) { + e->remove(); -void Level::removeEntityImmediately(std::shared_ptr e) -{ - e->remove(); + if (std::dynamic_pointer_cast(e) != NULL) { + std::vector >::iterator it = players.begin(); + std::vector >::iterator itEnd = players.end(); + while (it != itEnd && *it != std::dynamic_pointer_cast(e)) it++; - if (std::dynamic_pointer_cast( e ) != NULL) - { - std::vector >::iterator it = players.begin(); - std::vector >::iterator itEnd = players.end(); - while( it != itEnd && *it != std::dynamic_pointer_cast(e) ) - it++; + if (it != itEnd) { + players.erase(it); + } - if( it != itEnd ) - { - players.erase( it ); - } + updateSleepingPlayerList(); + playerRemoved(e); // 4J added - this will let the entity tracker know + // that we have actually removed the player from the + // level's player list + } - updateSleepingPlayerList(); - playerRemoved(e); // 4J added - this will let the entity tracker know that we have actually removed the player from the level's player list - } + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } + EnterCriticalSection(&m_entitiesCS); + std::vector >::iterator it = entities.begin(); + std::vector >::iterator endIt = entities.end(); + while (it != endIt && *it != e) it++; - EnterCriticalSection(&m_entitiesCS); - std::vector >::iterator it = entities.begin(); - std::vector >::iterator endIt = entities.end(); - while( it != endIt && *it != e) - it++; - - if( it != endIt ) - { - entities.erase( it ); - } - LeaveCriticalSection(&m_entitiesCS); - entityRemoved(e); + if (it != endIt) { + entities.erase(it); + } + LeaveCriticalSection(&m_entitiesCS); + entityRemoved(e); } - -void Level::addListener(LevelListener *listener) -{ - listeners.push_back(listener); +void Level::addListener(LevelListener* listener) { + listeners.push_back(listener); } +void Level::removeListener(LevelListener* listener) { + std::vector::iterator it = listeners.begin(); + std::vector::iterator itEnd = listeners.end(); + while (it != itEnd && *it != listener) it++; -void Level::removeListener(LevelListener *listener) -{ - std::vector::iterator it = listeners.begin(); - std::vector::iterator itEnd = listeners.end(); - while( it != itEnd && *it != listener ) - it++; - - if( it != itEnd ) - listeners.erase( it ); + if (it != itEnd) listeners.erase(it); } - // 4J - added noEntities and blockAtEdge parameter -AABBList *Level::getCubes(std::shared_ptr source, AABB *box, bool noEntities, bool blockAtEdge) -{ - boxes.clear(); - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); +AABBList* Level::getCubes(std::shared_ptr source, AABB* box, + bool noEntities, bool blockAtEdge) { + boxes.clear(); + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); - int maxxz = ( dimension->getXZSize() * 16 ) / 2; - int minxz = -maxxz; - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - // 4J - If we are outside the map, return solid AABBs (rock is a bit of an arbitrary choice here, just need a correct AABB) - if( blockAtEdge && ( ( x < minxz ) || ( x >= maxxz ) || ( z < minxz ) || ( z >= maxxz ) ) ) - { - for (int y = y0 - 1; y < y1; y++) - { - Tile::rock->addAABBs(this, x, y, z, box, &boxes, source); - } - } - else - { - if (hasChunkAt(x, 64, z)) - { - for (int y = y0 - 1; y < y1; y++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL) - { - tile->addAABBs(this, x, y, z, box, &boxes, source); - } - } - } - } - } - // 4J - also stop player falling out of the bottom of the map if blockAtEdge is true. Again, rock is an arbitrary choice here - // 4J Stu - Don't stop entities falling into the void while in The End (it has no bedrock) - if( blockAtEdge && ( ( y0 - 1 ) < 0 ) && dimension->id != 1 ) - { - for (int y = y0 - 1; y < 0; y++) - { - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - Tile::rock->addAABBs(this, x, y, z, box, &boxes, source ); - } - } - } - // 4J - final bounds check - limit vertical movement so we can't move above maxMovementHeight - if( blockAtEdge && ( y1 > maxMovementHeight ) ) - { - for (int y = maxMovementHeight; y < y1; y++) - { - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - Tile::rock->addAABBs(this, x, y, z, box, &boxes, source ); - } - } - } - // 4J - now add in collision for any blocks which have actually been removed, but haven't had their render data updated to reflect this yet. This is to stop the player - // being able to move the view position inside a tile which is (visually) still there, and see out of the world. This is particularly a problem when moving upwards in - // creative mode as the player can get very close to the edge of tiles whilst looking upwards and can therefore very quickly move inside one. - Minecraft::GetInstance()->levelRenderer->destroyedTileManager->addAABBs( this, box, &boxes); + int maxxz = (dimension->getXZSize() * 16) / 2; + int minxz = -maxxz; + for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) { + // 4J - If we are outside the map, return solid AABBs (rock is a bit + // of an arbitrary choice here, just need a correct AABB) + if (blockAtEdge && + ((x < minxz) || (x >= maxxz) || (z < minxz) || (z >= maxxz))) { + for (int y = y0 - 1; y < y1; y++) { + Tile::rock->addAABBs(this, x, y, z, box, &boxes, source); + } + } else { + if (hasChunkAt(x, 64, z)) { + for (int y = y0 - 1; y < y1; y++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL) { + tile->addAABBs(this, x, y, z, box, &boxes, source); + } + } + } + } + } + // 4J - also stop player falling out of the bottom of the map if blockAtEdge + // is true. Again, rock is an arbitrary choice here 4J Stu - Don't stop + // entities falling into the void while in The End (it has no bedrock) + if (blockAtEdge && ((y0 - 1) < 0) && dimension->id != 1) { + for (int y = y0 - 1; y < 0; y++) { + for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) { + Tile::rock->addAABBs(this, x, y, z, box, &boxes, source); + } + } + } + // 4J - final bounds check - limit vertical movement so we can't move above + // maxMovementHeight + if (blockAtEdge && (y1 > maxMovementHeight)) { + for (int y = maxMovementHeight; y < y1; y++) { + for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) { + Tile::rock->addAABBs(this, x, y, z, box, &boxes, source); + } + } + } + // 4J - now add in collision for any blocks which have actually been + // removed, but haven't had their render data updated to reflect this yet. + // This is to stop the player being able to move the view position inside a + // tile which is (visually) still there, and see out of the world. This is + // particularly a problem when moving upwards in creative mode as the player + // can get very close to the edge of tiles whilst looking upwards and can + // therefore very quickly move inside one. + Minecraft::GetInstance()->levelRenderer->destroyedTileManager->addAABBs( + this, box, &boxes); - // 4J - added - if( noEntities ) return &boxes; + // 4J - added + if (noEntities) return &boxes; - double r = 0.25; - std::vector > *ee = getEntities(source, box->grow(r, r, r)); - std::vector >::iterator itEnd = ee->end(); - for (AUTO_VAR(it, ee->begin()); it != itEnd; it++) - { - AABB *collideBox = (*it)->getCollideBox(); - if (collideBox != NULL && collideBox->intersects(box)) - { - boxes.push_back(collideBox); - } + double r = 0.25; + std::vector >* ee = + getEntities(source, box->grow(r, r, r)); + std::vector >::iterator itEnd = ee->end(); + for (AUTO_VAR(it, ee->begin()); it != itEnd; it++) { + AABB* collideBox = (*it)->getCollideBox(); + if (collideBox != NULL && collideBox->intersects(box)) { + boxes.push_back(collideBox); + } - collideBox = source->getCollideAgainstBox(*it); - if (collideBox != NULL && collideBox->intersects(box)) - { - boxes.push_back(collideBox); - } - } + collideBox = source->getCollideAgainstBox(*it); + if (collideBox != NULL && collideBox->intersects(box)) { + boxes.push_back(collideBox); + } + } - return &boxes; + return &boxes; } -// 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting the minecart in a tight corridor damages the player -AABBList *Level::getTileCubes(AABB *box, bool blockAtEdge) -{ - return getCubes(nullptr, box, true, blockAtEdge); - //boxes.clear(); - //int x0 = Mth::floor(box->x0); - //int x1 = Mth::floor(box->x1 + 1); - //int y0 = Mth::floor(box->y0); - //int y1 = Mth::floor(box->y1 + 1); - //int z0 = Mth::floor(box->z0); - //int z1 = Mth::floor(box->z1 + 1); +// 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting +// the minecart in a tight corridor damages the player +AABBList* Level::getTileCubes(AABB* box, bool blockAtEdge) { + return getCubes(nullptr, box, true, blockAtEdge); + // boxes.clear(); + // int x0 = Mth::floor(box->x0); + // int x1 = Mth::floor(box->x1 + 1); + // int y0 = Mth::floor(box->y0); + // int y1 = Mth::floor(box->y1 + 1); + // int z0 = Mth::floor(box->z0); + // int z1 = Mth::floor(box->z1 + 1); - //for (int x = x0; x < x1; x++) - //{ - // for (int z = z0; z < z1; z++) - // { - // if (hasChunkAt(x, 64, z)) - // { - // for (int y = y0 - 1; y < y1; y++) - // { - // Tile *tile = Tile::tiles[getTile(x, y, z)]; + // for (int x = x0; x < x1; x++) + //{ + // for (int z = z0; z < z1; z++) + // { + // if (hasChunkAt(x, 64, z)) + // { + // for (int y = y0 - 1; y < y1; y++) + // { + // Tile *tile = Tile::tiles[getTile(x, y, z)]; - // if (tile != NULL) - // { - // tile->addAABBs(this, x, y, z, box, &boxes); - // } - // } - // } - // } - //} + // if (tile != NULL) + // { + // tile->addAABBs(this, x, y, z, box, + //&boxes); + // } + // } + // } + // } + //} - //return boxes; + // return boxes; } -//4J - change brought forward from 1.8.2 -int Level::getOldSkyDarken(float a) -{ - float td = getTimeOfDay(a); +// 4J - change brought forward from 1.8.2 +int Level::getOldSkyDarken(float a) { + float td = getTimeOfDay(a); - float br = 1 - (Mth::cos(td * PI * 2) * 2 + 0.5f); - if (br < 0.0f) br = 0.0f; - if (br > 1.0f) br = 1.0f; + float br = 1 - (Mth::cos(td * PI * 2) * 2 + 0.5f); + if (br < 0.0f) br = 0.0f; + if (br > 1.0f) br = 1.0f; - br = 1 - br; + br = 1 - br; - br *= 1 - (getRainLevel(a) * 5 / 16.0f); - br *= 1 - (getThunderLevel(a) * 5 / 16.0f); - br = 1 - br; - return ((int) (br * 11)); + br *= 1 - (getRainLevel(a) * 5 / 16.0f); + br *= 1 - (getThunderLevel(a) * 5 / 16.0f); + br = 1 - br; + return ((int)(br * 11)); } -//4J - change brought forward from 1.8.2 -float Level::getSkyDarken(float a) -{ +// 4J - change brought forward from 1.8.2 +float Level::getSkyDarken(float a) { float td = getTimeOfDay(a); float br = 1 - (Mth::cos(td * PI * 2) * 2 + 0.2f); @@ -2022,1181 +1854,1012 @@ float Level::getSkyDarken(float a) return br * 0.8f + 0.2f; } +Vec3* Level::getSkyColor(std::shared_ptr source, float a) { + float td = getTimeOfDay(a); + float br = Mth::cos(td * PI * 2) * 2 + 0.5f; + if (br < 0.0f) br = 0.0f; + if (br > 1.0f) br = 1.0f; -Vec3 *Level::getSkyColor(std::shared_ptr source, float a) -{ - float td = getTimeOfDay(a); + int xx = Mth::floor(source->x); + int zz = Mth::floor(source->z); + Biome* biome = getBiome(xx, zz); + float temp = biome->getTemperature(); + int skyColor = biome->getSkyColor(temp); - float br = Mth::cos(td * PI * 2) * 2 + 0.5f; - if (br < 0.0f) br = 0.0f; - if (br > 1.0f) br = 1.0f; + float r = ((skyColor >> 16) & 0xff) / 255.0f; + float g = ((skyColor >> 8) & 0xff) / 255.0f; + float b = ((skyColor) & 0xff) / 255.0f; + r *= br; + g *= br; + b *= br; - int xx = Mth::floor(source->x); - int zz = Mth::floor(source->z); - Biome *biome = getBiome(xx, zz); - float temp = biome->getTemperature(); - int skyColor = biome->getSkyColor(temp); + float rainLevel = getRainLevel(a); + if (rainLevel > 0) { + float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.6f; - float r = ((skyColor >> 16) & 0xff) / 255.0f; - float g = ((skyColor >> 8) & 0xff) / 255.0f; - float b = ((skyColor) & 0xff) / 255.0f; - r *= br; - g *= br; - b *= br; + float ba = 1 - rainLevel * 0.75f; + r = r * ba + mid * (1 - ba); + g = g * ba + mid * (1 - ba); + b = b * ba + mid * (1 - ba); + } + float thunderLevel = getThunderLevel(a); + if (thunderLevel > 0) { + float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.2f; - float rainLevel = getRainLevel(a); - if (rainLevel > 0) - { - float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.6f; + float ba = 1 - thunderLevel * 0.75f; + r = r * ba + mid * (1 - ba); + g = g * ba + mid * (1 - ba); + b = b * ba + mid * (1 - ba); + } - float ba = 1 - rainLevel * 0.75f; - r = r * ba + mid * (1 - ba); - g = g * ba + mid * (1 - ba); - b = b * ba + mid * (1 - ba); - } - float thunderLevel = getThunderLevel(a); - if (thunderLevel > 0) - { - float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.2f; + if (lightningBoltTime > 0) { + float f = (lightningBoltTime - a); + if (f > 1) f = 1; + f = f * 0.45f; + r = r * (1 - f) + 0.8f * f; + g = g * (1 - f) + 0.8f * f; + b = b * (1 - f) + 1 * f; + } - float ba = 1 - thunderLevel * 0.75f; - r = r * ba + mid * (1 - ba); - g = g * ba + mid * (1 - ba); - b = b * ba + mid * (1 - ba); - } - - if (lightningBoltTime > 0) - { - float f = (lightningBoltTime - a); - if (f > 1) f = 1; - f = f * 0.45f; - r = r * (1 - f) + 0.8f * f; - g = g * (1 - f) + 0.8f * f; - b = b * (1 - f) + 1 * f; - } - - return Vec3::newTemp(r, g, b); + return Vec3::newTemp(r, g, b); } +float Level::getTimeOfDay(float a) { + /* + * 4J-PB removed line below - notch committed 1.6.6 with the incorrect + * getTimeOfDay and changed it before releasing (without + * re-committing)... that should be the only difference // jeb + */ + /* if (this != NULL) return 0.5f; */ -float Level::getTimeOfDay(float a) -{ - /* - * 4J-PB removed line below - notch committed 1.6.6 with the incorrect - * getTimeOfDay and changed it before releasing (without - * re-committing)... that should be the only difference // jeb - */ - /* if (this != NULL) return 0.5f; */ - - // 4J Added if so we can override timeOfDay without changing the time that affects ticking of things - if( m_timeOfDayOverride >= 0 ) - { - return dimension->getTimeOfDay(m_timeOfDayOverride, a); - } - else - { - return dimension->getTimeOfDay(levelData->getTime(), a);; - } + // 4J Added if so we can override timeOfDay without changing the time that + // affects ticking of things + if (m_timeOfDayOverride >= 0) { + return dimension->getTimeOfDay(m_timeOfDayOverride, a); + } else { + return dimension->getTimeOfDay(levelData->getTime(), a); + ; + } } -int Level::getMoonPhase(float a) -{ - return dimension->getMoonPhase(levelData->getTime(), a); +int Level::getMoonPhase(float a) { + return dimension->getMoonPhase(levelData->getTime(), a); } -float Level::getSunAngle(float a) -{ - float td = getTimeOfDay(a); - return td * PI * 2; +float Level::getSunAngle(float a) { + float td = getTimeOfDay(a); + return td * PI * 2; } +Vec3* Level::getCloudColor(float a) { + float td = getTimeOfDay(a); -Vec3 *Level::getCloudColor(float a) -{ - float td = getTimeOfDay(a); + float br = Mth::cos(td * PI * 2) * 2.0f + 0.5f; + if (br < 0.0f) br = 0.0f; + if (br > 1.0f) br = 1.0f; - float br = Mth::cos(td * PI * 2) * 2.0f + 0.5f; - if (br < 0.0f) br = 0.0f; - if (br > 1.0f) br = 1.0f; + int baseCloudColour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_In_Cloud_Base_Colour); - int baseCloudColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_In_Cloud_Base_Colour ); + float r = ((baseCloudColour >> 16) & 0xff) / 255.0f; + float g = ((baseCloudColour >> 8) & 0xff) / 255.0f; + float b = ((baseCloudColour) & 0xff) / 255.0f; - float r = ((baseCloudColour >> 16) & 0xff) / 255.0f; - float g = ((baseCloudColour >> 8) & 0xff) / 255.0f; - float b = ((baseCloudColour) & 0xff) / 255.0f; + float rainLevel = getRainLevel(a); + if (rainLevel > 0) { + float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.6f; - float rainLevel = getRainLevel(a); - if (rainLevel > 0) - { - float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.6f; + float ba = 1 - rainLevel * 0.95f; + r = r * ba + mid * (1 - ba); + g = g * ba + mid * (1 - ba); + b = b * ba + mid * (1 - ba); + } - float ba = 1 - rainLevel * 0.95f; - r = r * ba + mid * (1 - ba); - g = g * ba + mid * (1 - ba); - b = b * ba + mid * (1 - ba); - } + r *= br * 0.90f + 0.10f; + g *= br * 0.90f + 0.10f; + b *= br * 0.85f + 0.15f; - r *= br * 0.90f + 0.10f; - g *= br * 0.90f + 0.10f; - b *= br * 0.85f + 0.15f; + float thunderLevel = getThunderLevel(a); + if (thunderLevel > 0) { + float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.2f; - float thunderLevel = getThunderLevel(a); - if (thunderLevel > 0) - { - float mid = (r * 0.30f + g * 0.59f + b * 0.11f) * 0.2f; + float ba = 1 - thunderLevel * 0.95f; + r = r * ba + mid * (1 - ba); + g = g * ba + mid * (1 - ba); + b = b * ba + mid * (1 - ba); + } - float ba = 1 - thunderLevel * 0.95f; - r = r * ba + mid * (1 - ba); - g = g * ba + mid * (1 - ba); - b = b * ba + mid * (1 - ba); - } - - return Vec3::newTemp(r, g, b); + return Vec3::newTemp(r, g, b); } - -Vec3 *Level::getFogColor(float a) -{ - float td = getTimeOfDay(a); - return dimension->getFogColor(td, a); +Vec3* Level::getFogColor(float a) { + float td = getTimeOfDay(a); + return dimension->getFogColor(td, a); } - -int Level::getTopRainBlock(int x, int z) -{ - // 4J - optimisation brought forward from 1.8.2 - used to do full calculation here but result is now cached in LevelChunk - return getChunkAt(x, z)->getTopRainBlock(x & 15, z & 15); +int Level::getTopRainBlock(int x, int z) { + // 4J - optimisation brought forward from 1.8.2 - used to do full + // calculation here but result is now cached in LevelChunk + return getChunkAt(x, z)->getTopRainBlock(x & 15, z & 15); } // 4J added -bool Level::biomeHasRain(int x, int z) -{ - return getChunkAt(x, z)->biomeHasRain(x & 15, z & 15); +bool Level::biomeHasRain(int x, int z) { + return getChunkAt(x, z)->biomeHasRain(x & 15, z & 15); } // 4J added -bool Level::biomeHasSnow(int x, int z) -{ - return getChunkAt(x, z)->biomeHasSnow(x & 15, z & 15); +bool Level::biomeHasSnow(int x, int z) { + return getChunkAt(x, z)->biomeHasSnow(x & 15, z & 15); } -int Level::getTopSolidBlock(int x, int z) -{ - LevelChunk *levelChunk = getChunkAt(x, z); +int Level::getTopSolidBlock(int x, int z) { + LevelChunk* levelChunk = getChunkAt(x, z); - int y = levelChunk->getHighestSectionPosition() + 15; + int y = levelChunk->getHighestSectionPosition() + 15; - x &= 15; - z &= 15; + x &= 15; + z &= 15; - while (y > 0) - { - int t = levelChunk->getTile(x, y, z); - if (t == 0 || !(Tile::tiles[t]->material->blocksMotion()) || Tile::tiles[t]->material == Material::leaves) - { - y--; - } - else - { - return y + 1; - } - } - return -1; + while (y > 0) { + int t = levelChunk->getTile(x, y, z); + if (t == 0 || !(Tile::tiles[t]->material->blocksMotion()) || + Tile::tiles[t]->material == Material::leaves) { + y--; + } else { + return y + 1; + } + } + return -1; } - -int Level::getLightDepth(int x, int z) -{ - return getChunkAt(x, z)->getHeightmap(x & 15, z & 15); +int Level::getLightDepth(int x, int z) { + return getChunkAt(x, z)->getHeightmap(x & 15, z & 15); } +float Level::getStarBrightness(float a) { + float td = getTimeOfDay(a); -float Level::getStarBrightness(float a) -{ - float td = getTimeOfDay(a); + float br = 1 - (Mth::cos(td * PI * 2) * 2 + 0.25f); + if (br < 0.0f) br = 0.0f; + if (br > 1.0f) br = 1.0f; - float br = 1 - (Mth::cos(td * PI * 2) * 2 + 0.25f); - if (br < 0.0f) br = 0.0f; - if (br > 1.0f) br = 1.0f; - - return br * br * 0.5f; + return br * br * 0.5f; } +void Level::addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) {} -void Level::addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) -{ -} +void Level::forceAddTileTick(int x, int y, int z, int tileId, int tickDelay) {} -void Level::forceAddTileTick(int x, int y, int z, int tileId, int tickDelay) -{ -} +void Level::tickEntities() { + // for (int i = 0; i < globalEntities.size(); i++) + std::vector >::iterator itGE = + globalEntities.begin(); + while (itGE != globalEntities.end()) { + std::shared_ptr e = *itGE; // globalEntities.at(i); + e->tick(); + if (e->removed) { + // globalEntities.remove(i--); + itGE = globalEntities.erase(itGE); + } else { + itGE++; + } + } -void Level::tickEntities() -{ - //for (int i = 0; i < globalEntities.size(); i++) - std::vector >::iterator itGE = globalEntities.begin(); - while( itGE != globalEntities.end() ) - { - std::shared_ptr e = *itGE;//globalEntities.at(i); - e->tick(); - if (e->removed) - { - //globalEntities.remove(i--); - itGE = globalEntities.erase( itGE ); - } - else - { - itGE++; - } - } + // entities.removeAll(entitiesToRemove); + EnterCriticalSection(&m_entitiesCS); - //entities.removeAll(entitiesToRemove); - EnterCriticalSection(&m_entitiesCS); + for (AUTO_VAR(it, entities.begin()); it != entities.end();) { + bool found = false; + for (AUTO_VAR(it2, entitiesToRemove.begin()); + it2 != entitiesToRemove.end(); it2++) { + if ((*it) == (*it2)) { + found = true; + break; + } + } + if (found) { + it = entities.erase(it); + } else { + it++; + } + } + LeaveCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { - bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) - { - if( (*it) == (*it2) ) - { - found = true; - break; - } - } - if( found ) - { - it = entities.erase(it); - } - else - { - it++; - } - } - LeaveCriticalSection(&m_entitiesCS); + AUTO_VAR(itETREnd, entitiesToRemove.end()); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) { + std::shared_ptr e = *it; // entitiesToRemove.at(j); + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + } - AUTO_VAR(itETREnd, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) - { - std::shared_ptr e = *it;//entitiesToRemove.at(j); - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - } + itETREnd = entitiesToRemove.end(); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) { + entityRemoved(*it); + } + // + entitiesToRemove.clear(); - itETREnd = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) - { - entityRemoved(*it); - } - // - entitiesToRemove.clear(); + // for (int i = 0; i < entities.size(); i++) - //for (int i = 0; i < entities.size(); i++) + /* 4J Jev, using an iterator causes problems here as + * the vector is modified from inside this loop. + */ + EnterCriticalSection(&m_entitiesCS); - /* 4J Jev, using an iterator causes problems here as - * the vector is modified from inside this loop. - */ - EnterCriticalSection(&m_entitiesCS); + for (unsigned int i = 0; i < entities.size();) { + std::shared_ptr e = entities.at(i); - for (unsigned int i = 0; i < entities.size(); ) - { - std::shared_ptr e = entities.at(i); - - if (e->riding != NULL) - { - if (e->riding->removed || e->riding->rider.lock() != e) - { - e->riding->rider = std::weak_ptr(); - e->riding = nullptr; - } - else - { - i++; - continue; - } - } + if (e->riding != NULL) { + if (e->riding->removed || e->riding->rider.lock() != e) { + e->riding->rider = std::weak_ptr(); + e->riding = nullptr; + } else { + i++; + continue; + } + } - if (!e->removed) - { + if (!e->removed) { #ifndef _FINAL_BUILD - if(!( app.DebugSettingsOn() && app.GetMobsDontTickEnabled() && (std::dynamic_pointer_cast(e) != NULL) && (std::dynamic_pointer_cast(e) == NULL))) -#endif - { - tick(e); - } - } - - if (e->removed) - { - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - //entities.remove(i--); - //itE = entities.erase( itE ); - - // 4J Find the entity again before deleting, as things might have moved in the entity array eg - // from the explosion created by tnt - AUTO_VAR(it, find(entities.begin(), entities.end(), e)); - if( it != entities.end() ) - { - entities.erase(it); - } - - entityRemoved(e); - } - else - { - i++; - } - } - LeaveCriticalSection(&m_entitiesCS); - - EnterCriticalSection(&m_tileEntityListCS); - - updatingTileEntities = true; - for (AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end();) - { - std::shared_ptr te = *it;//tilestd::vector >.at(i); - if( !te->isRemoved() && te->hasLevel() ) - { - if (hasChunkAt(te->x, te->y, te->z)) - { -#ifdef _LARGE_WORLDS - LevelChunk *lc = getChunk(te->x >> 4, te->z >> 4); - if(!isClientSide || !lc->isUnloaded()) + if (!(app.DebugSettingsOn() && app.GetMobsDontTickEnabled() && + (std::dynamic_pointer_cast(e) != NULL) && + (std::dynamic_pointer_cast(e) == NULL))) #endif - { - te->tick(); - } - } - } + { + tick(e); + } + } - if( te->isRemoved() ) - { - it = tileEntityList.erase(it); - if (hasChunk(te->x >> 4, te->z >> 4)) - { - LevelChunk *lc = getChunk(te->x >> 4, te->z >> 4); - if (lc != NULL) lc->removeTileEntity(te->x & 15, te->y, te->z & 15); - } - } - else - { - it++; - } - } - updatingTileEntities = false; + if (e->removed) { + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + // entities.remove(i--); + // itE = entities.erase( itE ); -// 4J-PB - Stuart - check this is correct here + // 4J Find the entity again before deleting, as things might have + // moved in the entity array eg from the explosion created by tnt + AUTO_VAR(it, find(entities.begin(), entities.end(), e)); + if (it != entities.end()) { + entities.erase(it); + } - if (!tileEntitiesToUnload.empty()) - { - //tileEntityList.removeAll(tileEntitiesToUnload); + entityRemoved(e); + } else { + i++; + } + } + LeaveCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end(); ) - { - bool found = false; - for( AUTO_VAR(it2, tileEntitiesToUnload.begin()); it2 != tileEntitiesToUnload.end(); it2++ ) - { - if( (*it) == (*it2) ) - { - found = true; - break; - } - } - if( found ) - { - if(isClientSide) - { - __debugbreak(); - } - it = tileEntityList.erase(it); - } - else - { - it++; - } - } - tileEntitiesToUnload.clear(); - } + EnterCriticalSection(&m_tileEntityListCS); - if( !pendingTileEntities.empty() ) - { - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) - { - std::shared_ptr e = *it; - if( !e->isRemoved() ) - { - if( find(tileEntityList.begin(),tileEntityList.end(),e) == tileEntityList.end() ) - { - tileEntityList.push_back(e); - } - if (hasChunk(e->x >> 4, e->z >> 4)) - { - LevelChunk *lc = getChunk(e->x >> 4, e->z >> 4); - if (lc != NULL) lc->setTileEntity(e->x & 15, e->y, e->z & 15, e); - } + updatingTileEntities = true; + for (AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end();) { + std::shared_ptr te = + *it; // tilestd::vector >.at(i); + if (!te->isRemoved() && te->hasLevel()) { + if (hasChunkAt(te->x, te->y, te->z)) { +#ifdef _LARGE_WORLDS + LevelChunk* lc = getChunk(te->x >> 4, te->z >> 4); + if (!isClientSide || !lc->isUnloaded()) +#endif + { + te->tick(); + } + } + } + + if (te->isRemoved()) { + it = tileEntityList.erase(it); + if (hasChunk(te->x >> 4, te->z >> 4)) { + LevelChunk* lc = getChunk(te->x >> 4, te->z >> 4); + if (lc != NULL) + lc->removeTileEntity(te->x & 15, te->y, te->z & 15); + } + } else { + it++; + } + } + updatingTileEntities = false; + + // 4J-PB - Stuart - check this is correct here + + if (!tileEntitiesToUnload.empty()) { + // tileEntityList.removeAll(tileEntitiesToUnload); + + for (AUTO_VAR(it, tileEntityList.begin()); + it != tileEntityList.end();) { + bool found = false; + for (AUTO_VAR(it2, tileEntitiesToUnload.begin()); + it2 != tileEntitiesToUnload.end(); it2++) { + if ((*it) == (*it2)) { + found = true; + break; + } + } + if (found) { + if (isClientSide) { + __debugbreak(); + } + it = tileEntityList.erase(it); + } else { + it++; + } + } + tileEntitiesToUnload.clear(); + } + + if (!pendingTileEntities.empty()) { + for (AUTO_VAR(it, pendingTileEntities.begin()); + it != pendingTileEntities.end(); it++) { + std::shared_ptr e = *it; + if (!e->isRemoved()) { + if (find(tileEntityList.begin(), tileEntityList.end(), e) == + tileEntityList.end()) { + tileEntityList.push_back(e); + } + if (hasChunk(e->x >> 4, e->z >> 4)) { + LevelChunk* lc = getChunk(e->x >> 4, e->z >> 4); + if (lc != NULL) + lc->setTileEntity(e->x & 15, e->y, e->z & 15, e); + } sendTileUpdated(e->x, e->y, e->z); - } - } - pendingTileEntities.clear(); - } - LeaveCriticalSection(&m_tileEntityListCS); + } + } + pendingTileEntities.clear(); + } + LeaveCriticalSection(&m_tileEntityListCS); } -void Level::addAllPendingTileEntities(std::vector< std::shared_ptr >& entities) -{ - EnterCriticalSection(&m_tileEntityListCS); - if( updatingTileEntities ) - { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - pendingTileEntities.push_back(*it); - } - } - else - { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - tileEntityList.push_back(*it); - } - } - LeaveCriticalSection(&m_tileEntityListCS); +void Level::addAllPendingTileEntities( + std::vector >& entities) { + EnterCriticalSection(&m_tileEntityListCS); + if (updatingTileEntities) { + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + pendingTileEntities.push_back(*it); + } + } else { + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + tileEntityList.push_back(*it); + } + } + LeaveCriticalSection(&m_tileEntityListCS); } -void Level::tick(std::shared_ptr e) -{ - tick(e, true); -} +void Level::tick(std::shared_ptr e) { tick(e, true); } - -void Level::tick(std::shared_ptr e, bool actual) -{ - int xc = Mth::floor(e->x); - int zc = Mth::floor(e->z); - int r = 32; +void Level::tick(std::shared_ptr e, bool actual) { + int xc = Mth::floor(e->x); + int zc = Mth::floor(e->z); + int r = 32; #ifdef __PSVITA__ - // AP - make sure the dragon ticks all the time, even when there aren't any chunks. - if (actual && e->GetType() != eTYPE_ENDERDRAGON && !hasChunksAt(xc - r, 0, zc - r, xc + r, 0, zc + r)) + // AP - make sure the dragon ticks all the time, even when there aren't any + // chunks. + if (actual && e->GetType() != eTYPE_ENDERDRAGON && + !hasChunksAt(xc - r, 0, zc - r, xc + r, 0, zc + r)) #else - if (actual && !hasChunksAt(xc - r, 0, zc - r, xc + r, 0, zc + r)) + if (actual && !hasChunksAt(xc - r, 0, zc - r, xc + r, 0, zc + r)) #endif - { - return; - } + { + return; + } - e->xOld = e->x; - e->yOld = e->y; - e->zOld = e->z; - e->yRotO = e->yRot; - e->xRotO = e->xRot; + e->xOld = e->x; + e->yOld = e->y; + e->zOld = e->z; + e->yRotO = e->yRot; + e->xRotO = e->xRot; #ifdef __PSVITA__ - // AP - make sure the dragon ticks all the time, even when there aren't any chunks. - if (actual && (e->GetType() == eTYPE_ENDERDRAGON || e->inChunk) ) + // AP - make sure the dragon ticks all the time, even when there aren't any + // chunks. + if (actual && (e->GetType() == eTYPE_ENDERDRAGON || e->inChunk)) #else - if (actual && e->inChunk ) + if (actual && e->inChunk) #endif - { - if (e->riding != NULL) - { - e->rideTick(); - } - else - { - e->tick(); - } - } + { + if (e->riding != NULL) { + e->rideTick(); + } else { + e->tick(); + } + } - // SANTITY!! - if (Double::isNaN(e->x) || Double::isInfinite(e->x)) e->x = e->xOld; - if (Double::isNaN(e->y) || Double::isInfinite(e->y)) e->y = e->yOld; - if (Double::isNaN(e->z) || Double::isInfinite(e->z)) e->z = e->zOld; - if (Double::isNaN(e->xRot) || Double::isInfinite(e->xRot)) e->xRot = e->xRotO; - if (Double::isNaN(e->yRot) || Double::isInfinite(e->yRot)) e->yRot = e->yRotO; + // SANTITY!! + if (Double::isNaN(e->x) || Double::isInfinite(e->x)) e->x = e->xOld; + if (Double::isNaN(e->y) || Double::isInfinite(e->y)) e->y = e->yOld; + if (Double::isNaN(e->z) || Double::isInfinite(e->z)) e->z = e->zOld; + if (Double::isNaN(e->xRot) || Double::isInfinite(e->xRot)) + e->xRot = e->xRotO; + if (Double::isNaN(e->yRot) || Double::isInfinite(e->yRot)) + e->yRot = e->yRotO; - int xcn = Mth::floor(e->x / 16); - int ycn = Mth::floor(e->y / 16); - int zcn = Mth::floor(e->z / 16); + int xcn = Mth::floor(e->x / 16); + int ycn = Mth::floor(e->y / 16); + int zcn = Mth::floor(e->z / 16); + if (!e->inChunk || + (e->xChunk != xcn || e->yChunk != ycn || e->zChunk != zcn)) { + if (e->inChunk && hasChunk(e->xChunk, e->zChunk)) { + getChunk(e->xChunk, e->zChunk)->removeEntity(e, e->yChunk); + } + if (hasChunk(xcn, zcn)) { + e->inChunk = true; + MemSect(39); + getChunk(xcn, zcn)->addEntity(e); + MemSect(0); + } else { + e->inChunk = false; + // e.remove(); + } + } - if (!e->inChunk || (e->xChunk != xcn || e->yChunk != ycn || e->zChunk != zcn)) - { - if (e->inChunk && hasChunk(e->xChunk, e->zChunk)) - { - getChunk(e->xChunk, e->zChunk)->removeEntity(e, e->yChunk); - } - - if (hasChunk(xcn, zcn)) - { - - e->inChunk = true; - MemSect(39); - getChunk(xcn, zcn)->addEntity(e); - MemSect(0); - } - else - { - e->inChunk = false; - // e.remove(); - } - } - - if (actual && e->inChunk) - { - if (e->rider.lock() != NULL) - { - if (e->rider.lock()->removed || e->rider.lock()->riding != e) - { - e->rider.lock()->riding = nullptr; - e->rider = std::weak_ptr(); - } - else - { - tick(e->rider.lock()); - } - } - } + if (actual && e->inChunk) { + if (e->rider.lock() != NULL) { + if (e->rider.lock()->removed || e->rider.lock()->riding != e) { + e->rider.lock()->riding = nullptr; + e->rider = std::weak_ptr(); + } else { + tick(e->rider.lock()); + } + } + } } +bool Level::isUnobstructed(AABB* aabb) { return isUnobstructed(aabb, nullptr); } -bool Level::isUnobstructed(AABB *aabb) -{ - return isUnobstructed(aabb, nullptr); +bool Level::isUnobstructed(AABB* aabb, std::shared_ptr ignore) { + std::vector >* ents = getEntities(nullptr, aabb); + AUTO_VAR(itEnd, ents->end()); + for (AUTO_VAR(it, ents->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; + if (!e->removed && e->blocksBuilding && e != ignore) return false; + } + return true; } -bool Level::isUnobstructed(AABB *aabb, std::shared_ptr ignore) -{ - std::vector > *ents = getEntities(nullptr, aabb); - AUTO_VAR(itEnd, ents->end()); - for (AUTO_VAR(it, ents->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; - if (!e->removed && e->blocksBuilding && e != ignore) return false; - } - return true; +bool Level::containsAnyBlocks(AABB* box) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); + + if (box->x0 < 0) x0--; + if (box->y0 < 0) y0--; + if (box->z0 < 0) z0--; + + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL) { + return true; + } + } + return false; } +bool Level::containsAnyLiquid(AABB* box) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); -bool Level::containsAnyBlocks(AABB *box) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); + if (box->x0 < 0) x0--; + if (box->y0 < 0) y0--; + if (box->z0 < 0) z0--; - if (box->x0 < 0) x0--; - if (box->y0 < 0) y0--; - if (box->z0 < 0) z0--; - - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL) - { - return true; - } - } - return false; + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL && tile->material->isLiquid()) { + return true; + } + } + return false; } +// 4J - added this to be used during mob spawning, and it returns true if +// there's any liquid in the bounding box, or might be because we don't have a +// loaded chunk that we'd need to determine whether it really did. The overall +// aim is to not load or create any chunk we haven't already got, and be +// cautious about placing the mob's. +bool Level::containsAnyLiquid_NoLoad(AABB* box) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); -bool Level::containsAnyLiquid(AABB *box) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); + if (box->x0 < 0) x0--; + if (box->y0 < 0) y0--; + if (box->z0 < 0) z0--; - if (box->x0 < 0) x0--; - if (box->y0 < 0) y0--; - if (box->z0 < 0) z0--; - - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL && tile->material->isLiquid()) - { - return true; - } - } - return false; + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + if (!hasChunkAt(x, y, z)) + return true; // If we don't have it, it might be liquid... + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL && tile->material->isLiquid()) { + return true; + } + } + return false; } -// 4J - added this to be used during mob spawning, and it returns true if there's any liquid in the bounding box, or might be because -// we don't have a loaded chunk that we'd need to determine whether it really did. The overall aim is to not load or create any chunk -// we haven't already got, and be cautious about placing the mob's. -bool Level::containsAnyLiquid_NoLoad(AABB *box) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); +bool Level::containsFireTile(AABB* box) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); - if (box->x0 < 0) x0--; - if (box->y0 < 0) y0--; - if (box->z0 < 0) z0--; + if (hasChunksAt(x0, y0, z0, x1, y1, z1)) { + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + int t = getTile(x, y, z); - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - if( !hasChunkAt(x,y,z) ) return true; // If we don't have it, it might be liquid... - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL && tile->material->isLiquid()) - { - return true; - } - } - return false; + if (t == Tile::fire_Id || t == Tile::lava_Id || + t == Tile::calmLava_Id) + return true; + } + } + return false; } +bool Level::checkAndHandleWater(AABB* box, Material* material, + std::shared_ptr e) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); -bool Level::containsFireTile(AABB *box) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); - if (hasChunksAt(x0, y0, z0, x1, y1, z1)) - { - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - int t = getTile(x, y, z); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); - if (t == Tile::fire_Id || t == Tile::lava_Id || t == Tile::calmLava_Id) return true; - } - } - return false; + if (!hasChunksAt(x0, y0, z0, x1, y1, z1)) { + return false; + } + + bool ok = false; + Vec3* current = Vec3::newTemp(0, 0, 0); + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL && tile->material == material) { + double yt0 = + y + 1 - LiquidTile::getHeight(getData(x, y, z)); + if (y1 >= yt0) { + ok = true; + tile->handleEntityInside(this, x, y, z, e, current); + } + } + } + if (current->length() > 0) { + current = current->normalize(); + double pow = 0.014; + e->xd += current->x * pow; + e->yd += current->y * pow; + e->zd += current->z * pow; + } + return ok; } +bool Level::containsMaterial(AABB* box, Material* material) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); -bool Level::checkAndHandleWater(AABB *box, Material *material, std::shared_ptr e) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); - - if (!hasChunksAt(x0, y0, z0, x1, y1, z1)) - { - return false; - } - - bool ok = false; - Vec3 *current = Vec3::newTemp(0, 0, 0); - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL && tile->material == material) - { - double yt0 = y + 1 - LiquidTile::getHeight(getData(x, y, z)); - if (y1 >= yt0) - { - ok = true; - tile->handleEntityInside(this, x, y, z, e, current); - } - } - } - if (current->length() > 0) - { - current = current->normalize(); - double pow = 0.014; - e->xd += current->x * pow; - e->yd += current->y * pow; - e->zd += current->z * pow; - } - return ok; + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL && tile->material == material) { + return true; + } + } + return false; } +bool Level::containsLiquid(AABB* box, Material* material) { + int x0 = Mth::floor(box->x0); + int x1 = Mth::floor(box->x1 + 1); + int y0 = Mth::floor(box->y0); + int y1 = Mth::floor(box->y1 + 1); + int z0 = Mth::floor(box->z0); + int z1 = Mth::floor(box->z1 + 1); -bool Level::containsMaterial(AABB *box, Material *material) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); - - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL && tile->material == material) - { - return true; - } - } - return false; + for (int x = x0; x < x1; x++) + for (int y = y0; y < y1; y++) + for (int z = z0; z < z1; z++) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile != NULL && tile->material == material) { + int data = getData(x, y, z); + double yh1 = y + 1; + if (data < 8) { + yh1 = y + 1 - data / 8.0; + } + if (yh1 >= box->y0) { + return true; + } + } + } + return false; } - -bool Level::containsLiquid(AABB *box, Material *material) -{ - int x0 = Mth::floor(box->x0); - int x1 = Mth::floor(box->x1 + 1); - int y0 = Mth::floor(box->y0); - int y1 = Mth::floor(box->y1 + 1); - int z0 = Mth::floor(box->z0); - int z1 = Mth::floor(box->z1 + 1); - - for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - for (int z = z0; z < z1; z++) - { - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile != NULL && tile->material == material) - { - int data = getData(x, y, z); - double yh1 = y + 1; - if (data < 8) - { - yh1 = y + 1 - data / 8.0; - } - if (yh1 >= box->y0) - { - return true; - } - } - } - return false; +std::shared_ptr Level::explode(std::shared_ptr source, + double x, double y, double z, float r, + bool destroyBlocks) { + return explode(source, x, y, z, r, false, destroyBlocks); } - -std::shared_ptr Level::explode(std::shared_ptr source, double x, double y, double z, float r, bool destroyBlocks) -{ - return explode(source, x, y, z, r, false, destroyBlocks); +std::shared_ptr Level::explode(std::shared_ptr source, + double x, double y, double z, float r, + bool fire, bool destroyBlocks) { + std::shared_ptr explosion = + std::shared_ptr(new Explosion(this, source, x, y, z, r)); + explosion->fire = fire; + explosion->destroyBlocks = destroyBlocks; + explosion->explode(); + explosion->finalizeExplosion(true); + return explosion; } +float Level::getSeenPercent(Vec3* center, AABB* bb) { + double xs = 1.0 / ((bb->x1 - bb->x0) * 2 + 1); + double ys = 1.0 / ((bb->y1 - bb->y0) * 2 + 1); + double zs = 1.0 / ((bb->z1 - bb->z0) * 2 + 1); + int hits = 0; + int count = 0; + for (double xx = 0; xx <= 1; + xx += xs) // 4J Stu - xx, yy and zz were floats, made them doubles to + // remove warnings + for (double yy = 0; yy <= 1; yy += ys) + for (double zz = 0; zz <= 1; zz += zs) { + double x = bb->x0 + (bb->x1 - bb->x0) * xx; + double y = bb->y0 + (bb->y1 - bb->y0) * yy; + double z = bb->z0 + (bb->z1 - bb->z0) * zz; + HitResult* res = clip(Vec3::newTemp(x, y, z), center); + if (res == NULL) hits++; + delete res; + count++; + } -std::shared_ptr Level::explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks) -{ - std::shared_ptr explosion = std::shared_ptr( new Explosion(this, source, x, y, z, r) ); - explosion->fire = fire; - explosion->destroyBlocks = destroyBlocks; - explosion->explode(); - explosion->finalizeExplosion(true); - return explosion; + return hits / (float)count; } +bool Level::extinguishFire(std::shared_ptr player, int x, int y, int z, + int face) { + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; -float Level::getSeenPercent(Vec3 *center, AABB *bb) -{ - double xs = 1.0 / ((bb->x1 - bb->x0) * 2 + 1); - double ys = 1.0 / ((bb->y1 - bb->y0) * 2 + 1); - double zs = 1.0 / ((bb->z1 - bb->z0) * 2 + 1); - int hits = 0; - int count = 0; - for (double xx = 0; xx <= 1; xx += xs) // 4J Stu - xx, yy and zz were floats, made them doubles to remove warnings - for (double yy = 0; yy <= 1; yy += ys) - for (double zz = 0; zz <= 1; zz += zs) - { - double x = bb->x0 + (bb->x1 - bb->x0) * xx; - double y = bb->y0 + (bb->y1 - bb->y0) * yy; - double z = bb->z0 + (bb->z1 - bb->z0) * zz; - HitResult *res = clip(Vec3::newTemp(x, y, z), center); - if ( res == NULL) hits++; - delete res; - count++; - } - - return hits / (float) count; -} - - -bool Level::extinguishFire(std::shared_ptr player, int x, int y, int z, int face) -{ - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - - if (getTile(x, y, z) == Tile::fire_Id) - { - levelEvent(player, LevelEvent::SOUND_FIZZ, x, y, z, 0); - setTile(x, y, z, 0); - return true; - } - return false; + if (getTile(x, y, z) == Tile::fire_Id) { + levelEvent(player, LevelEvent::SOUND_FIZZ, x, y, z, 0); + setTile(x, y, z, 0); + return true; + } + return false; } /* std::shared_ptr Level::findSubclassOf(Entity::Class *entityClass) { - return std::shared_ptr(); + return std::shared_ptr(); } */ - -std::wstring Level::gatherStats() -{ - wchar_t buf[64]; - EnterCriticalSection(&m_entitiesCS); - swprintf(buf,64,L"All:%d",this->entities.size()); - LeaveCriticalSection(&m_entitiesCS); - return std::wstring(buf); +std::wstring Level::gatherStats() { + wchar_t buf[64]; + EnterCriticalSection(&m_entitiesCS); + swprintf(buf, 64, L"All:%d", this->entities.size()); + LeaveCriticalSection(&m_entitiesCS); + return std::wstring(buf); } - -std::wstring Level::gatherChunkSourceStats() -{ - return chunkSource->gatherStats(); +std::wstring Level::gatherChunkSourceStats() { + return chunkSource->gatherStats(); } +std::shared_ptr Level::getTileEntity(int x, int y, int z) { + if (y >= Level::maxBuildHeight) { + return nullptr; + } + LevelChunk* lc = getChunk(x >> 4, z >> 4); + if (lc != NULL) return lc->getTileEntity(x & 15, y, z & 15); -std::shared_ptr Level::getTileEntity(int x, int y, int z) -{ - if (y >= Level::maxBuildHeight) - { - return nullptr; - } - LevelChunk *lc = getChunk(x >> 4, z >> 4); - if (lc != NULL) return lc->getTileEntity(x & 15, y, z & 15); + if (lc != NULL) { + std::shared_ptr tileEntity = + lc->getTileEntity(x & 15, y, z & 15); - if (lc != NULL) - { - std::shared_ptr tileEntity = lc->getTileEntity(x & 15, y, z & 15); + if (tileEntity == NULL) { + EnterCriticalSection(&m_tileEntityListCS); + for (AUTO_VAR(it, pendingTileEntities.begin()); + it != pendingTileEntities.end(); it++) { + std::shared_ptr e = *it; - if (tileEntity == NULL) - { - EnterCriticalSection(&m_tileEntityListCS); - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) - { - std::shared_ptr e = *it; - - if (!e->isRemoved() && e->x == x && e->y == y && e->z == z) - { + if (!e->isRemoved() && e->x == x && e->y == y && e->z == z) { tileEntity = e; break; } } - LeaveCriticalSection(&m_tileEntityListCS); + LeaveCriticalSection(&m_tileEntityListCS); } return tileEntity; } - return nullptr; + return nullptr; } - -void Level::setTileEntity(int x, int y, int z, std::shared_ptr tileEntity) -{ - if (tileEntity != NULL && !tileEntity->isRemoved()) - { - EnterCriticalSection(&m_tileEntityListCS); - if (updatingTileEntities) - { +void Level::setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity) { + if (tileEntity != NULL && !tileEntity->isRemoved()) { + EnterCriticalSection(&m_tileEntityListCS); + if (updatingTileEntities) { tileEntity->x = x; tileEntity->y = y; tileEntity->z = z; pendingTileEntities.push_back(tileEntity); - } - else - { + } else { tileEntityList.push_back(tileEntity); - LevelChunk *lc = getChunk(x >> 4, z >> 4); - if (lc != NULL) lc->setTileEntity(x & 15, y, z & 15, tileEntity); - } - LeaveCriticalSection(&m_tileEntityListCS); - } - - -} - - -void Level::removeTileEntity(int x, int y, int z) -{ - EnterCriticalSection(&m_tileEntityListCS); - std::shared_ptr te = getTileEntity(x, y, z); - if (te != NULL && updatingTileEntities) - { - te->setRemoved(); - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) - { - pendingTileEntities.erase(it); - } - } - else - { - if (te != NULL) - { - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) - { - pendingTileEntities.erase(it); - } - AUTO_VAR(it2, find(tileEntityList.begin(), tileEntityList.end(), te)); - if( it2 != tileEntityList.end() ) - { - tileEntityList.erase(it2); - } + LevelChunk* lc = getChunk(x >> 4, z >> 4); + if (lc != NULL) lc->setTileEntity(x & 15, y, z & 15, tileEntity); } - LevelChunk *lc = getChunk(x >> 4, z >> 4); - if (lc != NULL) lc->removeTileEntity(x & 15, y, z & 15); - } - LeaveCriticalSection(&m_tileEntityListCS); + LeaveCriticalSection(&m_tileEntityListCS); + } } -void Level::markForRemoval(std::shared_ptr entity) -{ - tileEntitiesToUnload.push_back(entity); +void Level::removeTileEntity(int x, int y, int z) { + EnterCriticalSection(&m_tileEntityListCS); + std::shared_ptr te = getTileEntity(x, y, z); + if (te != NULL && updatingTileEntities) { + te->setRemoved(); + AUTO_VAR(it, find(pendingTileEntities.begin(), + pendingTileEntities.end(), te)); + if (it != pendingTileEntities.end()) { + pendingTileEntities.erase(it); + } + } else { + if (te != NULL) { + AUTO_VAR(it, find(pendingTileEntities.begin(), + pendingTileEntities.end(), te)); + if (it != pendingTileEntities.end()) { + pendingTileEntities.erase(it); + } + AUTO_VAR(it2, + find(tileEntityList.begin(), tileEntityList.end(), te)); + if (it2 != tileEntityList.end()) { + tileEntityList.erase(it2); + } + } + LevelChunk* lc = getChunk(x >> 4, z >> 4); + if (lc != NULL) lc->removeTileEntity(x & 15, y, z & 15); + } + LeaveCriticalSection(&m_tileEntityListCS); } -bool Level::isSolidRenderTile(int x, int y, int z) -{ - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile == NULL) return false; - - // 4J - addition here to make rendering big blocks of leaves more efficient. Normally leaves never consider themselves as solid, so - // blocks of leaves will have all sides of each block completely visible. Changing to consider as solid if this block is surrounded by - // other leaves (or solid things). This is paired with another change in Tile::getTexture which makes such solid tiles actually visibly solid (these - // textures exist already for non-fancy graphics). Note: this tile-specific code is here rather than making some new virtual method in the tiles, - // for the sake of efficiency - I don't imagine we'll be doing much more of this sort of thing - - if( tile->id == Tile::leaves_Id ) - { - int axo[6] = { 1,-1, 0, 0, 0, 0}; - int ayo[6] = { 0, 0, 1,-1, 0, 0}; - int azo[6] = { 0, 0, 0, 0, 1,-1}; - for( int i = 0; i < 6; i++ ) - { - int t = getTile(x + axo[i], y + ayo[i] , z + azo[i]); - if( ( t != Tile::leaves_Id ) && ( ( Tile::tiles[t] == NULL ) || !Tile::tiles[t]->isSolidRender() ) ) - { - return false; - } - } - - return true; - } - return tile->isSolidRender(!isClientSide); +void Level::markForRemoval(std::shared_ptr entity) { + tileEntitiesToUnload.push_back(entity); } +bool Level::isSolidRenderTile(int x, int y, int z) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile == NULL) return false; -bool Level::isSolidBlockingTile(int x, int y, int z) -{ - return Tile::isSolidBlockingTile(getTile(x, y, z)); + // 4J - addition here to make rendering big blocks of leaves more efficient. + // Normally leaves never consider themselves as solid, so blocks of leaves + // will have all sides of each block completely visible. Changing to + // consider as solid if this block is surrounded by other leaves (or solid + // things). This is paired with another change in Tile::getTexture which + // makes such solid tiles actually visibly solid (these textures exist + // already for non-fancy graphics). Note: this tile-specific code is here + // rather than making some new virtual method in the tiles, for the sake of + // efficiency - I don't imagine we'll be doing much more of this sort of + // thing + + if (tile->id == Tile::leaves_Id) { + int axo[6] = {1, -1, 0, 0, 0, 0}; + int ayo[6] = {0, 0, 1, -1, 0, 0}; + int azo[6] = {0, 0, 0, 0, 1, -1}; + for (int i = 0; i < 6; i++) { + int t = getTile(x + axo[i], y + ayo[i], z + azo[i]); + if ((t != Tile::leaves_Id) && ((Tile::tiles[t] == NULL) || + !Tile::tiles[t]->isSolidRender())) { + return false; + } + } + + return true; + } + return tile->isSolidRender(!isClientSide); +} + +bool Level::isSolidBlockingTile(int x, int y, int z) { + return Tile::isSolidBlockingTile(getTile(x, y, z)); } /** - * This method does the same as isSolidBlockingTile, except it will not - * check the tile if the coordinates is in an unloaded or empty chunk. This - * is to help vs the problem of "popping" torches in SMP. - */ + * This method does the same as isSolidBlockingTile, except it will not + * check the tile if the coordinates is in an unloaded or empty chunk. This + * is to help vs the problem of "popping" torches in SMP. + */ -bool Level::isSolidBlockingTileInLoadedChunk(int x, int y, int z, bool valueIfNotLoaded) -{ - if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || z >= MAX_LEVEL_SIZE) - { +bool Level::isSolidBlockingTileInLoadedChunk(int x, int y, int z, + bool valueIfNotLoaded) { + if (x < -MAX_LEVEL_SIZE || z < -MAX_LEVEL_SIZE || x >= MAX_LEVEL_SIZE || + z >= MAX_LEVEL_SIZE) { return valueIfNotLoaded; } - LevelChunk *chunk = chunkSource->getChunk(x >> 4, z >> 4); - if (chunk == NULL || chunk->isEmpty()) - { + LevelChunk* chunk = chunkSource->getChunk(x >> 4, z >> 4); + if (chunk == NULL || chunk->isEmpty()) { return valueIfNotLoaded; } - Tile *tile = Tile::tiles[getTile(x, y, z)]; + Tile* tile = Tile::tiles[getTile(x, y, z)]; if (tile == NULL) return false; return tile->material->isSolidBlocking() && tile->isCubeShaped(); } // 4J - brought forward from 1.3.2 -bool Level::isTopSolidBlocking(int x, int y, int z) -{ +bool Level::isTopSolidBlocking(int x, int y, int z) { // Temporary workaround until tahgs per-face solidity is finished - Tile *tile = Tile::tiles[getTile(x, y, z)]; + Tile* tile = Tile::tiles[getTile(x, y, z)]; if (tile == NULL) return false; if (tile->material->isSolidBlocking() && tile->isCubeShaped()) return true; - if (dynamic_cast(tile) != NULL) - { - return (getData(x, y, z) & StairTile::UPSIDEDOWN_BIT) == StairTile::UPSIDEDOWN_BIT; - } - if (dynamic_cast(tile) != NULL) - { - return (getData(x, y, z) & HalfSlabTile::TOP_SLOT_BIT) == HalfSlabTile::TOP_SLOT_BIT; - } - if (dynamic_cast(tile) != NULL) return (getData(x, y, z) & TopSnowTile::HEIGHT_MASK) == TopSnowTile::MAX_HEIGHT + 1; + if (dynamic_cast(tile) != NULL) { + return (getData(x, y, z) & StairTile::UPSIDEDOWN_BIT) == + StairTile::UPSIDEDOWN_BIT; + } + if (dynamic_cast(tile) != NULL) { + return (getData(x, y, z) & HalfSlabTile::TOP_SLOT_BIT) == + HalfSlabTile::TOP_SLOT_BIT; + } + if (dynamic_cast(tile) != NULL) + return (getData(x, y, z) & TopSnowTile::HEIGHT_MASK) == + TopSnowTile::MAX_HEIGHT + 1; return false; } -void Level::updateSkyBrightness() -{ - int newDark = this->getOldSkyDarken(1); - if (newDark != skyDarken) - { - skyDarken = newDark; - } +void Level::updateSkyBrightness() { + int newDark = this->getOldSkyDarken(1); + if (newDark != skyDarken) { + skyDarken = newDark; + } } -void Level::setSpawnSettings(bool spawnEnemies, bool spawnFriendlies) -{ - this->spawnEnemies = spawnEnemies; - this->spawnFriendlies = spawnFriendlies; +void Level::setSpawnSettings(bool spawnEnemies, bool spawnFriendlies) { + this->spawnEnemies = spawnEnemies; + this->spawnFriendlies = spawnFriendlies; } -void Level::tick() -{ - PIXBeginNamedEvent(0,"Weather tick"); - tickWeather(); - PIXEndNamedEvent(); +void Level::tick() { + PIXBeginNamedEvent(0, "Weather tick"); + tickWeather(); + PIXEndNamedEvent(); } -void Level::prepareWeather() -{ - if (levelData->isRaining()) - { - this->rainLevel = 1; - if (levelData->isThundering()) - { - this->thunderLevel = 1; - } - } +void Level::prepareWeather() { + if (levelData->isRaining()) { + this->rainLevel = 1; + if (levelData->isThundering()) { + this->thunderLevel = 1; + } + } } - -void Level::tickWeather() -{ - if (dimension->hasCeiling) return; +void Level::tickWeather() { + if (dimension->hasCeiling) return; #ifndef _FINAL_BUILD - // debug setting added to disable weather - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<setThundering(false); - levelData->setThunderTime(random->nextInt(TICKS_PER_DAY * 7) + TICKS_PER_DAY / 2); - levelData->setRaining(false); - levelData->setRainTime(random->nextInt(TICKS_PER_DAY * 7) + TICKS_PER_DAY / 2); - } - } + // debug setting added to disable weather + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_DisableWeather)) { + levelData->setThundering(false); + levelData->setThunderTime(random->nextInt(TICKS_PER_DAY * 7) + + TICKS_PER_DAY / 2); + levelData->setRaining(false); + levelData->setRainTime(random->nextInt(TICKS_PER_DAY * 7) + + TICKS_PER_DAY / 2); + } + } #endif - if (lightningTime > 0) - { - lightningTime--; - } + if (lightningTime > 0) { + lightningTime--; + } - int thunderTime = levelData->getThunderTime(); - if (thunderTime <= 0) - { - if (levelData->isThundering()) - { - levelData->setThunderTime(random->nextInt(20 * 60 * 10) + 20 * 60 * 3); - } - else - { - levelData->setThunderTime(random->nextInt(TICKS_PER_DAY * 7) + TICKS_PER_DAY / 2); - } - } - else - { - thunderTime--; - levelData->setThunderTime(thunderTime); - if (thunderTime <= 0) - { - levelData->setThundering(!levelData->isThundering()); - } - } + int thunderTime = levelData->getThunderTime(); + if (thunderTime <= 0) { + if (levelData->isThundering()) { + levelData->setThunderTime(random->nextInt(20 * 60 * 10) + + 20 * 60 * 3); + } else { + levelData->setThunderTime(random->nextInt(TICKS_PER_DAY * 7) + + TICKS_PER_DAY / 2); + } + } else { + thunderTime--; + levelData->setThunderTime(thunderTime); + if (thunderTime <= 0) { + levelData->setThundering(!levelData->isThundering()); + } + } - int rainTime = levelData->getRainTime(); - if (rainTime <= 0) - { - if (levelData->isRaining()) - { - levelData->setRainTime(random->nextInt(TICKS_PER_DAY / 2) + TICKS_PER_DAY / 2); - } - else - { - levelData->setRainTime(random->nextInt(TICKS_PER_DAY * 7) + TICKS_PER_DAY / 2); - } - } - else - { - rainTime--; - levelData->setRainTime(rainTime); - if (rainTime <= 0) - { - levelData->setRaining(!levelData->isRaining()); - } -/* if( !levelData->isRaining() ) - { - levelData->setRaining(true); - }*/ - } + int rainTime = levelData->getRainTime(); + if (rainTime <= 0) { + if (levelData->isRaining()) { + levelData->setRainTime(random->nextInt(TICKS_PER_DAY / 2) + + TICKS_PER_DAY / 2); + } else { + levelData->setRainTime(random->nextInt(TICKS_PER_DAY * 7) + + TICKS_PER_DAY / 2); + } + } else { + rainTime--; + levelData->setRainTime(rainTime); + if (rainTime <= 0) { + levelData->setRaining(!levelData->isRaining()); + } + /* if( !levelData->isRaining() ) + { + levelData->setRaining(true); + }*/ + } - oRainLevel = rainLevel; - if (levelData->isRaining()) - { - rainLevel += 0.01; - } - else - { - rainLevel -= 0.01; - } - if (rainLevel < 0) rainLevel = 0; - if (rainLevel > 1) rainLevel = 1; + oRainLevel = rainLevel; + if (levelData->isRaining()) { + rainLevel += 0.01; + } else { + rainLevel -= 0.01; + } + if (rainLevel < 0) rainLevel = 0; + if (rainLevel > 1) rainLevel = 1; - oThunderLevel = thunderLevel; - if (levelData->isThundering()) - { - thunderLevel += 0.01; - } - else - { - thunderLevel -= 0.01; - } - if (thunderLevel < 0) thunderLevel = 0; - if (thunderLevel > 1) thunderLevel = 1; + oThunderLevel = thunderLevel; + if (levelData->isThundering()) { + thunderLevel += 0.01; + } else { + thunderLevel -= 0.01; + } + if (thunderLevel < 0) thunderLevel = 0; + if (thunderLevel > 1) thunderLevel = 1; } -void Level::toggleDownfall() -{ +void Level::toggleDownfall() { // this will trick the tickWeather method to toggle rain next tick levelData->setRainTime(1); } -void Level::buildAndPrepareChunksToPoll() -{ +void Level::buildAndPrepareChunksToPoll() { #if 0 AUTO_VAR(itEnd, players.end()); for (AUTO_VAR(it, players.begin()); it != itEnd; it++) @@ -3213,142 +2876,146 @@ void Level::buildAndPrepareChunksToPoll() } } #else - // 4J - rewritten to add chunks interleaved by player, and to add them from the centre outwards. We're going to be - // potentially adding less creatures than the original so that our count stays consistent with number of players added, so - // we want to make sure as best we can that the ones we do add are near the active players - int playerCount = (int)players.size(); - int *xx = new int[playerCount]; - int *zz = new int[playerCount]; - for (int i = 0; i < playerCount; i++) - { - std::shared_ptr player = players[i]; - xx[i] = Mth::floor(player->x / 16); - zz[i] = Mth::floor(player->z / 16); - chunksToPoll.insert(ChunkPos(xx[i], zz[i] )); - } + // 4J - rewritten to add chunks interleaved by player, and to add them from + // the centre outwards. We're going to be potentially adding less creatures + // than the original so that our count stays consistent with number of + // players added, so we want to make sure as best we can that the ones we do + // add are near the active players + int playerCount = (int)players.size(); + int* xx = new int[playerCount]; + int* zz = new int[playerCount]; + for (int i = 0; i < playerCount; i++) { + std::shared_ptr player = players[i]; + xx[i] = Mth::floor(player->x / 16); + zz[i] = Mth::floor(player->z / 16); + chunksToPoll.insert(ChunkPos(xx[i], zz[i])); + } - for( int r = 1; r <= 9; r++ ) - { - for( int l = 0; l < ( r * 2 ) ; l++ ) - { - for( int i = 0; i < playerCount; i++ ) - { - chunksToPoll.insert(ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r ) ) ); - chunksToPoll.insert(ChunkPos( ( xx[i] + r ) , ( zz[i] - r ) + l ) ); - chunksToPoll.insert(ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r ) ) ); - chunksToPoll.insert(ChunkPos( ( xx[i] - r ) , ( zz[i] + r ) - l ) ); - } - } - } - delete [] xx; - delete [] zz; + for (int r = 1; r <= 9; r++) { + for (int l = 0; l < (r * 2); l++) { + for (int i = 0; i < playerCount; i++) { + chunksToPoll.insert(ChunkPos((xx[i] - r) + l, (zz[i] - r))); + chunksToPoll.insert(ChunkPos((xx[i] + r), (zz[i] - r) + l)); + chunksToPoll.insert(ChunkPos((xx[i] + r) - l, (zz[i] + r))); + chunksToPoll.insert(ChunkPos((xx[i] - r), (zz[i] + r) - l)); + } + } + } + delete[] xx; + delete[] zz; #endif - - if (delayUntilNextMoodSound > 0) delayUntilNextMoodSound--; - // 4J Stu - Added 1.2.3, but not sure if we want to do it - //util.Timer.push("playerCheckLight"); - //// randomly check areas around the players - //if (!players.isEmpty()) { - // int select = random.nextInt(players.size()); - // Player player = players.get(select); - // int px = Mth.floor(player.x) + random.nextInt(11) - 5; - // int py = Mth.floor(player.y) + random.nextInt(11) - 5; - // int pz = Mth.floor(player.z) + random.nextInt(11) - 5; - // checkLight(px, py, pz); - //} - //util.Timer.pop(); + if (delayUntilNextMoodSound > 0) delayUntilNextMoodSound--; + + // 4J Stu - Added 1.2.3, but not sure if we want to do it + // util.Timer.push("playerCheckLight"); + //// randomly check areas around the players + // if (!players.isEmpty()) { + // int select = random.nextInt(players.size()); + // Player player = players.get(select); + // int px = Mth.floor(player.x) + random.nextInt(11) - 5; + // int py = Mth.floor(player.y) + random.nextInt(11) - 5; + // int pz = Mth.floor(player.z) + random.nextInt(11) - 5; + // checkLight(px, py, pz); + // } + // util.Timer.pop(); } -void Level::tickClientSideTiles(int xo, int zo, LevelChunk *lc) -{ - //lc->tick(); // 4J - brought this lighting update forward from 1.8.2 +void Level::tickClientSideTiles(int xo, int zo, LevelChunk* lc) { + // lc->tick(); // 4J - brought this lighting update forward from 1.8.2 - if (delayUntilNextMoodSound == 0) - { - randValue = (unsigned) randValue * 3 + (unsigned) addend; - int val = (randValue >> 2); - int x = (val & 15); - int z = ((val >> 8) & 15); - int y = ((val >> 16) & genDepthMinusOne); + if (delayUntilNextMoodSound == 0) { + randValue = (unsigned)randValue * 3 + (unsigned)addend; + int val = (randValue >> 2); + int x = (val & 15); + int z = ((val >> 8) & 15); + int y = ((val >> 16) & genDepthMinusOne); - int id = lc->getTile(x, y, z); - x += xo; - z += zo; - if (id == 0 && this->getDaytimeRawBrightness(x, y, z) <= random->nextInt(8) && getBrightness(LightLayer::Sky, x, y, z) <= 0) - { - std::shared_ptr player = getNearestPlayer(x + 0.5, y + 0.5, z + 0.5, 8); - if (player != NULL && player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 2 * 2) - { - // 4J-PB - Fixed issue with cave audio event having 2 sounds at 192k + int id = lc->getTile(x, y, z); + x += xo; + z += zo; + if (id == 0 && + this->getDaytimeRawBrightness(x, y, z) <= random->nextInt(8) && + getBrightness(LightLayer::Sky, x, y, z) <= 0) { + std::shared_ptr player = + getNearestPlayer(x + 0.5, y + 0.5, z + 0.5, 8); + if (player != NULL && + player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) > 2 * 2) { + // 4J-PB - Fixed issue with cave audio event having 2 sounds at + // 192k #ifdef _XBOX - this->playSound(x + 0.5, y + 0.5, z + 0.5,eSoundType_AMBIENT_CAVE_CAVE2, 0.7f, 0.8f + random->nextFloat() * 0.2f); + this->playSound(x + 0.5, y + 0.5, z + 0.5, + eSoundType_AMBIENT_CAVE_CAVE2, 0.7f, + 0.8f + random->nextFloat() * 0.2f); #else - this->playSound(x + 0.5, y + 0.5, z + 0.5,eSoundType_AMBIENT_CAVE_CAVE, 0.7f, 0.8f + random->nextFloat() * 0.2f); + this->playSound(x + 0.5, y + 0.5, z + 0.5, + eSoundType_AMBIENT_CAVE_CAVE, 0.7f, + 0.8f + random->nextFloat() * 0.2f); #endif - delayUntilNextMoodSound = random->nextInt(20 * 60 * 10) + 20 * 60 * 5; - } - } - } + delayUntilNextMoodSound = + random->nextInt(20 * 60 * 10) + 20 * 60 * 5; + } + } + } - // 4J Stu - Added 1.2.3, but do we need it? - //lc->checkNextLight(); + // 4J Stu - Added 1.2.3, but do we need it? + // lc->checkNextLight(); } -void Level::tickTiles() -{ - buildAndPrepareChunksToPoll(); -} +void Level::tickTiles() { buildAndPrepareChunksToPoll(); } -bool Level::shouldFreezeIgnoreNeighbors(int x, int y, int z) -{ +bool Level::shouldFreezeIgnoreNeighbors(int x, int y, int z) { return shouldFreeze(x, y, z, false); } -bool Level::shouldFreeze(int x, int y, int z) -{ +bool Level::shouldFreeze(int x, int y, int z) { return shouldFreeze(x, y, z, true); } -bool Level::shouldFreeze(int x, int y, int z, bool checkNeighbors) -{ - Biome *biome = getBiome(x, z); +bool Level::shouldFreeze(int x, int y, int z, bool checkNeighbors) { + Biome* biome = getBiome(x, z); float temp = biome->getTemperature(); if (temp > 0.15f) return false; - if (y >= 0 && y < maxBuildHeight && getBrightness(LightLayer::Block, x, y, z) < 10) - { + if (y >= 0 && y < maxBuildHeight && + getBrightness(LightLayer::Block, x, y, z) < 10) { int current = getTile(x, y, z); - if ((current == Tile::calmWater_Id || current == Tile::water_Id) && getData(x, y, z) == 0) - { + if ((current == Tile::calmWater_Id || current == Tile::water_Id) && + getData(x, y, z) == 0) { if (!checkNeighbors) return true; bool surroundedByWater = true; - if (surroundedByWater && getMaterial(x - 1, y, z) != Material::water) surroundedByWater = false; - if (surroundedByWater && getMaterial(x + 1, y, z) != Material::water) surroundedByWater = false; - if (surroundedByWater && getMaterial(x, y, z - 1) != Material::water) surroundedByWater = false; - if (surroundedByWater && getMaterial(x, y, z + 1) != Material::water) surroundedByWater = false; + if (surroundedByWater && + getMaterial(x - 1, y, z) != Material::water) + surroundedByWater = false; + if (surroundedByWater && + getMaterial(x + 1, y, z) != Material::water) + surroundedByWater = false; + if (surroundedByWater && + getMaterial(x, y, z - 1) != Material::water) + surroundedByWater = false; + if (surroundedByWater && + getMaterial(x, y, z + 1) != Material::water) + surroundedByWater = false; if (!surroundedByWater) return true; } } return false; } -bool Level::shouldSnow(int x, int y, int z) -{ - Biome *biome = getBiome(x, z); +bool Level::shouldSnow(int x, int y, int z) { + Biome* biome = getBiome(x, z); float temp = biome->getTemperature(); if (temp > 0.15f) return false; - - if (y >= 0 && y < maxBuildHeight && getBrightness(LightLayer::Block, x, y, z) < 10) - { + if (y >= 0 && y < maxBuildHeight && + getBrightness(LightLayer::Block, x, y, z) < 10) { int below = getTile(x, y - 1, z); int current = getTile(x, y, z); - if (current == 0) - { - if (Tile::topSnow->mayPlace(this, x, y, z) && (below != 0 && below != Tile::ice_Id && Tile::tiles[below]->material->blocksMotion())) - { + if (current == 0) { + if (Tile::topSnow->mayPlace(this, x, y, z) && + (below != 0 && below != Tile::ice_Id && + Tile::tiles[below]->material->blocksMotion())) { return true; } } @@ -3357,86 +3024,85 @@ bool Level::shouldSnow(int x, int y, int z) return false; } - -void Level::checkLight(int x, int y, int z, bool force, bool rootOnlyEmissive) // 4J added force, rootOnlyEmissive parameters +void Level::checkLight( + int x, int y, int z, bool force, + bool rootOnlyEmissive) // 4J added force, rootOnlyEmissive parameters { - if (!dimension->hasCeiling) checkLight(LightLayer::Sky, x, y, z, force, false); + if (!dimension->hasCeiling) + checkLight(LightLayer::Sky, x, y, z, force, false); checkLight(LightLayer::Block, x, y, z, force, rootOnlyEmissive); } -int Level::getExpectedSkyColor(lightCache_t *cache, int oc, int x, int y , int z, int ct, int block) -{ +int Level::getExpectedSkyColor(lightCache_t* cache, int oc, int x, int y, int z, + int ct, int block) { int expected = 0; - if( block == 255 ) return 0; // 4J added as optimisation + if (block == 255) return 0; // 4J added as optimisation - if (canSeeSky(x, y, z)) - { + if (canSeeSky(x, y, z)) { expected = 15; - } - else - { + } else { if (block == 0) block = 1; - // 4J - changed this to attempt to get all 6 brightnesses of neighbours in a single call, as an optimisation - int b[6]; - b[0] = getBrightnessCached(cache, LightLayer::Sky, x - 1, y, z); - b[1] = getBrightnessCached(cache, LightLayer::Sky, x + 1, y, z); - b[2] = getBrightnessCached(cache, LightLayer::Sky, x, y - 1, z); - b[3] = getBrightnessCached(cache, LightLayer::Sky, x, y + 1, z); - b[4] = getBrightnessCached(cache, LightLayer::Sky, x, y, z - 1); - b[5] = getBrightnessCached(cache, LightLayer::Sky, x, y, z + 1); - for( int i = 0; i < 6; i++ ) - { - if( ( b[i] - block ) > expected ) expected = b[i] - block; - } + // 4J - changed this to attempt to get all 6 brightnesses of neighbours + // in a single call, as an optimisation + int b[6]; + b[0] = getBrightnessCached(cache, LightLayer::Sky, x - 1, y, z); + b[1] = getBrightnessCached(cache, LightLayer::Sky, x + 1, y, z); + b[2] = getBrightnessCached(cache, LightLayer::Sky, x, y - 1, z); + b[3] = getBrightnessCached(cache, LightLayer::Sky, x, y + 1, z); + b[4] = getBrightnessCached(cache, LightLayer::Sky, x, y, z - 1); + b[5] = getBrightnessCached(cache, LightLayer::Sky, x, y, z + 1); + for (int i = 0; i < 6; i++) { + if ((b[i] - block) > expected) expected = b[i] - block; + } } return expected; } -int Level::getExpectedBlockColor(lightCache_t *cache, int oc, int x, int y, int z, int ct, int block, bool propagatedOnly) -{ +int Level::getExpectedBlockColor(lightCache_t* cache, int oc, int x, int y, + int z, int ct, int block, + bool propagatedOnly) { int expected = propagatedOnly ? 0 : getEmissionCached(cache, ct, x, y, z); - if( block >= 15 ) return expected; // 4J added as optimisation + if (block >= 15) return expected; // 4J added as optimisation - // 4J - changed this to attempt to get all 6 brightnesses of neighbours in a single call, as an optimisation - int b[6]; - b[0] = getBrightnessCached(cache, LightLayer::Block, x - 1, y, z); - b[1] = getBrightnessCached(cache, LightLayer::Block, x + 1, y, z); - b[2] = getBrightnessCached(cache, LightLayer::Block, x, y - 1, z); - b[3] = getBrightnessCached(cache, LightLayer::Block, x, y + 1, z); - b[4] = getBrightnessCached(cache, LightLayer::Block, x, y, z - 1); - b[5] = getBrightnessCached(cache, LightLayer::Block, x, y, z + 1); - for( int i = 0; i < 6; i++ ) - { - if( ( b[i] - block ) > expected ) expected = b[i] - block; - } + // 4J - changed this to attempt to get all 6 brightnesses of neighbours in a + // single call, as an optimisation + int b[6]; + b[0] = getBrightnessCached(cache, LightLayer::Block, x - 1, y, z); + b[1] = getBrightnessCached(cache, LightLayer::Block, x + 1, y, z); + b[2] = getBrightnessCached(cache, LightLayer::Block, x, y - 1, z); + b[3] = getBrightnessCached(cache, LightLayer::Block, x, y + 1, z); + b[4] = getBrightnessCached(cache, LightLayer::Block, x, y, z - 1); + b[5] = getBrightnessCached(cache, LightLayer::Block, x, y, z + 1); + for (int i = 0; i < 6; i++) { + if ((b[i] - block) > expected) expected = b[i] - block; + } return expected; } -inline int GetIndex(int x, int y, int z) -{ - return ( ( x & 15 ) << 8 ) | ( ( y & 15 ) << 4 ) | ( z & 15 ); +inline int GetIndex(int x, int y, int z) { + return ((x & 15) << 8) | ((y & 15) << 4) | (z & 15); } -// 4J - Made changes here so that lighting goes through a cache, if enabled for this thread -void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool force, bool rootOnlyEmissive) -{ - lightCache_t *cache = static_cast(LevelTlsGetValue(tlsIdxLightCache)); - __uint64 cacheUse = 0; +// 4J - Made changes here so that lighting goes through a cache, if enabled for +// this thread +void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, + bool force, bool rootOnlyEmissive) { + lightCache_t* cache = + static_cast(LevelTlsGetValue(tlsIdxLightCache)); + __uint64 cacheUse = 0; - if( force ) - { - // 4J - special mode added so we can do lava lighting updates without having all neighbouring chunks loaded in - if (!hasChunksAt(xc, yc, zc, 0)) return; - } - else - { - // 4J - this is normal java behaviour - if (!hasChunksAt(xc, yc, zc, 17)) return; - } + if (force) { + // 4J - special mode added so we can do lava lighting updates without + // having all neighbouring chunks loaded in + if (!hasChunksAt(xc, yc, zc, 0)) return; + } else { + // 4J - this is normal java behaviour + if (!hasChunksAt(xc, yc, zc, 17)) return; + } #if 0 ///////////////////////////////////////////////////////////////////////////////////////////// @@ -3451,278 +3117,321 @@ void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool f ///////////////////////////////////////////////////////////////////////////////////////////// #endif - EnterCriticalSection(&m_checkLightCS); + EnterCriticalSection(&m_checkLightCS); #ifdef __PSVITA__ - // AP - only clear the one array element required to check if something has changed - cachewritten = false; - if( cache != NULL ) - { - int idx; - if( !(yc & 0xffffff00) ) - { - idx = GetIndex(xc, yc, zc); - cache[idx] = 0; - idx = GetIndex(xc - 1, yc, zc); - cache[idx] = 0; - idx = GetIndex(xc + 1, yc, zc); - cache[idx] = 0; - idx = GetIndex(xc, yc, zc - 1); - cache[idx] = 0; - idx = GetIndex(xc, yc, zc + 1); - cache[idx] = 0; - } - if( !((yc-1) & 0xffffff00) ) - { - idx = GetIndex(xc, yc - 1, zc); - cache[idx] = 0; - } - if( !((yc+1) & 0xffffff00) ) - { - idx = GetIndex(xc, yc + 1, zc); - cache[idx] = 0; - } - } + // AP - only clear the one array element required to check if something has + // changed + cachewritten = false; + if (cache != NULL) { + int idx; + if (!(yc & 0xffffff00)) { + idx = GetIndex(xc, yc, zc); + cache[idx] = 0; + idx = GetIndex(xc - 1, yc, zc); + cache[idx] = 0; + idx = GetIndex(xc + 1, yc, zc); + cache[idx] = 0; + idx = GetIndex(xc, yc, zc - 1); + cache[idx] = 0; + idx = GetIndex(xc, yc, zc + 1); + cache[idx] = 0; + } + if (!((yc - 1) & 0xffffff00)) { + idx = GetIndex(xc, yc - 1, zc); + cache[idx] = 0; + } + if (!((yc + 1) & 0xffffff00)) { + idx = GetIndex(xc, yc + 1, zc); + cache[idx] = 0; + } + } #else - initCache(cache); + initCache(cache); #endif - // If we're in cached mode, then use memory allocated after the cached data itself for the toCheck array, in an attempt to make both that & the other cached data sit on the CPU L2 cache better. - - int *toCheck; - if( cache == NULL ) - { - toCheck = toCheckLevel; - } - else - { - toCheck = (int *)(cache + (16*16*16)); - } + // If we're in cached mode, then use memory allocated after the cached data + // itself for the toCheck array, in an attempt to make both that & the other + // cached data sit on the CPU L2 cache better. + + int* toCheck; + if (cache == NULL) { + toCheck = toCheckLevel; + } else { + toCheck = (int*)(cache + (16 * 16 * 16)); + } int tcp = 0; int tcc = 0; - //int darktcc = 0; + // int darktcc = 0; + // 4J - added + int minXZ = -(dimension->getXZSize() * 16) / 2; + int maxXZ = (dimension->getXZSize() * 16) / 2 - 1; + if ((xc > maxXZ) || (xc < minXZ) || (zc > maxXZ) || (zc < minXZ)) { + LeaveCriticalSection(&m_checkLightCS); + return; + } - // 4J - added - int minXZ = - (dimension->getXZSize() * 16 ) / 2; - int maxXZ = (dimension->getXZSize() * 16 ) / 2 - 1; - if( ( xc > maxXZ ) || ( xc < minXZ ) || ( zc > maxXZ ) || ( zc < minXZ ) ) - { - LeaveCriticalSection(&m_checkLightCS); - return; - } + // Lock 128K of cache (containing all the lighting cache + first 112K of + // toCheck array) on L2 to try and stop any cached data getting knocked out + // of L2 by other non-cached reads (or vice-versa) + // if( cache ) XLockL2(XLOCKL2_INDEX_TITLE, cache, 128 * 1024, + //XLOCKL2_LOCK_SIZE_1_WAY, 0 ); - // Lock 128K of cache (containing all the lighting cache + first 112K of toCheck array) on L2 to try and stop any cached data getting knocked out of L2 by other non-cached reads (or vice-versa) -// if( cache ) XLockL2(XLOCKL2_INDEX_TITLE, cache, 128 * 1024, XLOCKL2_LOCK_SIZE_1_WAY, 0 ); - { int cc = getBrightnessCached(cache, layer, xc, yc, zc); int ex = 0; { - int ct = 0; - int block = getBlockingCached(cache, layer, &ct, xc, yc, zc); + int ct = 0; + int block = getBlockingCached(cache, layer, &ct, xc, yc, zc); if (block == 0) block = 1; int expected = 0; - if (layer == LightLayer::Sky) - { - expected = getExpectedSkyColor(cache, cc, xc, yc, zc, ct, block); - } - else - { - expected = getExpectedBlockColor(cache, cc, xc, yc, zc, ct, block, false); + if (layer == LightLayer::Sky) { + expected = + getExpectedSkyColor(cache, cc, xc, yc, zc, ct, block); + } else { + expected = getExpectedBlockColor(cache, cc, xc, yc, zc, ct, + block, false); } ex = expected; - } #ifdef __PSVITA__ - // AP - we only need to memset the entire array if we discover something has changed - if( ex != cc && cache ) - { - lightCache_t old[7]; - if( !(yc & 0xffffff00) ) - { - old[0] = cache[GetIndex(xc, yc, zc)]; - old[1] = cache[GetIndex(xc - 1, yc, zc)]; - old[2] = cache[GetIndex(xc + 1, yc, zc)]; - old[5] = cache[GetIndex(xc, yc, zc - 1)]; - old[6] = cache[GetIndex(xc, yc, zc + 1)]; - } - if( !((yc-1) & 0xffffff00) ) - { - old[3] = cache[GetIndex(xc, yc - 1, zc)]; - } - if( !((yc+1) & 0xffffff00) ) - { - old[4] = cache[GetIndex(xc, yc + 1, zc)]; - } + // AP - we only need to memset the entire array if we discover something + // has changed + if (ex != cc && cache) { + lightCache_t old[7]; + if (!(yc & 0xffffff00)) { + old[0] = cache[GetIndex(xc, yc, zc)]; + old[1] = cache[GetIndex(xc - 1, yc, zc)]; + old[2] = cache[GetIndex(xc + 1, yc, zc)]; + old[5] = cache[GetIndex(xc, yc, zc - 1)]; + old[6] = cache[GetIndex(xc, yc, zc + 1)]; + } + if (!((yc - 1) & 0xffffff00)) { + old[3] = cache[GetIndex(xc, yc - 1, zc)]; + } + if (!((yc + 1) & 0xffffff00)) { + old[4] = cache[GetIndex(xc, yc + 1, zc)]; + } - XMemSet128(cache,0,16*16*16*sizeof(lightCache_t)); + XMemSet128(cache, 0, 16 * 16 * 16 * sizeof(lightCache_t)); - if( !(yc & 0xffffff00) ) - { - cache[GetIndex(xc, yc, zc)] = old[0]; - cache[GetIndex(xc - 1, yc, zc)] = old[1]; - cache[GetIndex(xc + 1, yc, zc)] = old[2]; - cache[GetIndex(xc, yc, zc - 1)] = old[5]; - cache[GetIndex(xc, yc, zc + 1)] = old[6]; - } - if( !((yc-1) & 0xffffff00) ) - { - cache[GetIndex(xc, yc - 1, zc)] = old[3]; - } - if( !((yc+1) & 0xffffff00) ) - { - cache[GetIndex(xc, yc + 1, zc)] = old[4]; - } - } + if (!(yc & 0xffffff00)) { + cache[GetIndex(xc, yc, zc)] = old[0]; + cache[GetIndex(xc - 1, yc, zc)] = old[1]; + cache[GetIndex(xc + 1, yc, zc)] = old[2]; + cache[GetIndex(xc, yc, zc - 1)] = old[5]; + cache[GetIndex(xc, yc, zc + 1)] = old[6]; + } + if (!((yc - 1) & 0xffffff00)) { + cache[GetIndex(xc, yc - 1, zc)] = old[3]; + } + if (!((yc + 1) & 0xffffff00)) { + cache[GetIndex(xc, yc + 1, zc)] = old[4]; + } + } #endif - if (ex > cc) - { + if (ex > cc) { toCheck[tcc++] = ((32)) + ((32) << 6) + ((32) << 12); - } - else if (ex < cc) - { - // 4J - added tcn. This is the code that is run when checkLight has been called for a light source that has got darker / turned off. - // In the original version, after zeroing tiles brightnesses that are deemed to come from this light source, all the zeroed tiles are then passed to the next - // stage of the function to potentially have their brightnesses put back up again. We shouldn't need to consider All these tiles as starting points for this process, now just - // considering the edge tiles (defined as a tile where we have a neighbour that is brightner than can be explained by the original light source we are turning off) - int tcn = 0; - if (layer == LightLayer::Block || true) - { - toCheck[tcc++] = ((32)) + ((32) << 6) + ((32) << 12) + (cc << 18); - while (tcp < tcc) - { + } else if (ex < cc) { + // 4J - added tcn. This is the code that is run when checkLight has + // been called for a light source that has got darker / turned off. + // In the original version, after zeroing tiles brightnesses that + // are deemed to come from this light source, all the zeroed tiles + // are then passed to the next stage of the function to potentially + // have their brightnesses put back up again. We shouldn't need to + // consider All these tiles as starting points for this process, now + // just considering the edge tiles (defined as a tile where we have + // a neighbour that is brightner than can be explained by the + // original light source we are turning off) + int tcn = 0; + if (layer == LightLayer::Block || true) { + toCheck[tcc++] = + ((32)) + ((32) << 6) + ((32) << 12) + (cc << 18); + while (tcp < tcc) { int p = toCheck[tcp++]; int x = ((p) & 63) - 32 + xc; int y = ((p >> 6) & 63) - 32 + yc; int z = ((p >> 12) & 63) - 32 + zc; int cexp = ((p >> 18) & 15); int o = getBrightnessCached(cache, layer, x, y, z); - if (o == cexp) - { - setBrightnessCached(cache, &cacheUse, layer, x, y, z, 0); - // cexp--; // 4J - removed, change from 1.2.3 - if (cexp > 0) - { + if (o == cexp) { + setBrightnessCached(cache, &cacheUse, layer, x, y, z, + 0); + // cexp--; // 4J - removed, change + // from 1.2.3 + if (cexp > 0) { int xd = x - xc; int yd = y - yc; int zd = z - zc; if (xd < 0) xd = -xd; if (yd < 0) yd = -yd; if (zd < 0) zd = -zd; - if (xd + yd + zd < 17) - { - bool edge = false; - for (int j = 0; j < 6; j++) - { + if (xd + yd + zd < 17) { + bool edge = false; + for (int j = 0; j < 6; j++) { int flip = j % 2 * 2 - 1; int xx = x + ((j / 2) % 3 / 2) * flip; int yy = y + ((j / 2 + 1) % 3 / 2) * flip; int zz = z + ((j / 2 + 2) % 3 / 2) * flip; - // 4J - added - don't let this lighting creep out of the normal fixed world and into the infinite water chunks beyond - if( ( xx > maxXZ ) || ( xx < minXZ ) || ( zz > maxXZ ) || ( zz < minXZ ) ) continue; - if( ( yy < 0 ) || ( yy >= maxBuildHeight ) ) continue; + // 4J - added - don't let this lighting + // creep out of the normal fixed world and + // into the infinite water chunks beyond + if ((xx > maxXZ) || (xx < minXZ) || + (zz > maxXZ) || (zz < minXZ)) + continue; + if ((yy < 0) || (yy >= maxBuildHeight)) + continue; - o = getBrightnessCached(cache, layer, xx, yy, zz); - // 4J - some changes here brought forward from 1.2.3 - int block = getBlockingCached(cache, layer, NULL, xx, yy, zz); + o = getBrightnessCached(cache, layer, xx, + yy, zz); + // 4J - some changes here brought forward + // from 1.2.3 + int block = getBlockingCached( + cache, layer, NULL, xx, yy, zz); if (block == 0) block = 1; - if ((o == cexp - block) && (tcc < (32 * 32 * 32))) // 4J - 32 * 32 * 32 was toCheck.length - { - toCheck[tcc++] = (((xx - xc) + 32)) + (((yy - yc) + 32) << 6) + (((zz - zc) + 32) << 12) + ((cexp - block) << 18); - } - else - { - // 4J - added - keep track of which tiles form the edge of the region we are zeroing - if( o > ( cexp - block ) ) - { - edge = true; - } - } + if ((o == cexp - block) && + (tcc < + (32 * 32 * 32))) // 4J - 32 * 32 * 32 + // was toCheck.length + { + toCheck[tcc++] = + (((xx - xc) + 32)) + + (((yy - yc) + 32) << 6) + + (((zz - zc) + 32) << 12) + + ((cexp - block) << 18); + } else { + // 4J - added - keep track of which + // tiles form the edge of the region we + // are zeroing + if (o > (cexp - block)) { + edge = true; + } + } + } + // 4J - added - keep track of which tiles form + // the edge of the region we are zeroing - can + // store over the original elements in the array + // because tcn must be <= tcp + if (edge == true) { + toCheck[tcn++] = p; } - // 4J - added - keep track of which tiles form the edge of the region we are zeroing - can store over the original elements in the array because tcn must be <= tcp - if( edge == true ) - { - toCheck[tcn++] = p; - } } } - } } } - tcp = 0; -// darktcc = tcc; /////////////////////////////////////////////////// - tcc = tcn; // 4J added - we've moved all the edge tiles to the start of the array, so only need to process these now. The original processes all tcc tiles again in the next section + tcp = 0; + // darktcc = tcc; + ///////////////////////////////////////////////////// + tcc = tcn; // 4J added - we've moved all the edge tiles to the + // start of the array, so only need to process these + // now. The original processes all tcc tiles again in + // the next section } } - while (tcp < tcc) - { + while (tcp < tcc) { int p = toCheck[tcp++]; int x = ((p) & 63) - 32 + xc; int y = ((p >> 6) & 63) - 32 + yc; int z = ((p >> 12) & 63) - 32 + zc; - // If force is set, then this is being used to in a special mode to try and light lava tiles as chunks are being loaded in. In this case, we - // don't want a lighting update to drag in any neighbouring chunks that aren't loaded yet. - if( force ) - { - if( !hasChunkAt(x,y,z) ) - { - continue; - } - } + // If force is set, then this is being used to in a special mode to try + // and light lava tiles as chunks are being loaded in. In this case, we + // don't want a lighting update to drag in any neighbouring chunks that + // aren't loaded yet. + if (force) { + if (!hasChunkAt(x, y, z)) { + continue; + } + } int c = getBrightnessCached(cache, layer, x, y, z); - int ct = 0; - int block = getBlockingCached(cache, layer, &ct, x, y, z); + int ct = 0; + int block = getBlockingCached(cache, layer, &ct, x, y, z); if (block == 0) block = 1; int expected = 0; - if (layer == LightLayer::Sky) - { + if (layer == LightLayer::Sky) { expected = getExpectedSkyColor(cache, c, x, y, z, ct, block); - } - else - { - // If rootOnlyEmissive flag is set, then only consider the starting tile to be possibly emissive. - bool propagatedOnly = false; - if( rootOnlyEmissive ) - { - propagatedOnly = ( x != xc ) || ( y != yc ) || ( z != zc ); - } - expected = getExpectedBlockColor(cache, c, x, y, z, ct, block, propagatedOnly); + } else { + // If rootOnlyEmissive flag is set, then only consider the starting + // tile to be possibly emissive. + bool propagatedOnly = false; + if (rootOnlyEmissive) { + propagatedOnly = (x != xc) || (y != yc) || (z != zc); + } + expected = getExpectedBlockColor(cache, c, x, y, z, ct, block, + propagatedOnly); } - if (expected != c) - { + if (expected != c) { setBrightnessCached(cache, &cacheUse, layer, x, y, z, expected); - if (expected > c) - { + if (expected > c) { int xd = x - xc; int yd = y - yc; int zd = z - zc; if (xd < 0) xd = -xd; if (yd < 0) yd = -yd; if (zd < 0) zd = -zd; - if (xd + yd + zd < 17 && tcc < (32 * 32 * 32) - 6) // 4J - 32 * 32 * 32 was toCheck.length - { - // 4J - added extra checks here to stop lighting updates moving out of the actual fixed world and into the infinite water chunks - if( ( x - 1 ) >= minXZ ) { if (getBrightnessCached(cache, layer, x - 1, y, z) < expected) toCheck[tcc++] = (((x - 1 - xc) + 32)) + (((y - yc) + 32) << 6) + (((z - zc) + 32) << 12); } - if( ( x + 1 ) <= maxXZ ) { if (getBrightnessCached(cache, layer, x + 1, y, z) < expected) toCheck[tcc++] = (((x + 1 - xc) + 32)) + (((y - yc) + 32) << 6) + (((z - zc) + 32) << 12); } - if( ( y - 1 ) >= 0 ) { if (getBrightnessCached(cache, layer, x, y - 1, z) < expected) toCheck[tcc++] = (((x - xc) + 32)) + (((y - 1 - yc) + 32) << 6) + (((z - zc) + 32) << 12); } - if( ( y + 1 ) < maxBuildHeight ) { if (getBrightnessCached(cache, layer, x, y + 1, z) < expected) toCheck[tcc++] = (((x - xc) + 32)) + (((y + 1 - yc) + 32) << 6) + (((z - zc) + 32) << 12); } - if( ( z - 1 ) >= minXZ ) { if (getBrightnessCached(cache, layer, x, y, z - 1) < expected) toCheck[tcc++] = (((x - xc) + 32)) + (((y - yc) + 32) << 6) + (((z - 1 - zc) + 32) << 12); } - if( ( z + 1 ) <= maxXZ ) { if (getBrightnessCached(cache, layer, x, y, z + 1) < expected) toCheck[tcc++] = (((x - xc) + 32)) + (((y - yc) + 32) << 6) + (((z + 1 - zc) + 32) << 12); } + if (xd + yd + zd < 17 && + tcc < (32 * 32 * 32) - + 6) // 4J - 32 * 32 * 32 was toCheck.length + { + // 4J - added extra checks here to stop lighting updates + // moving out of the actual fixed world and into the + // infinite water chunks + if ((x - 1) >= minXZ) { + if (getBrightnessCached(cache, layer, x - 1, y, z) < + expected) + toCheck[tcc++] = (((x - 1 - xc) + 32)) + + (((y - yc) + 32) << 6) + + (((z - zc) + 32) << 12); + } + if ((x + 1) <= maxXZ) { + if (getBrightnessCached(cache, layer, x + 1, y, z) < + expected) + toCheck[tcc++] = (((x + 1 - xc) + 32)) + + (((y - yc) + 32) << 6) + + (((z - zc) + 32) << 12); + } + if ((y - 1) >= 0) { + if (getBrightnessCached(cache, layer, x, y - 1, z) < + expected) + toCheck[tcc++] = (((x - xc) + 32)) + + (((y - 1 - yc) + 32) << 6) + + (((z - zc) + 32) << 12); + } + if ((y + 1) < maxBuildHeight) { + if (getBrightnessCached(cache, layer, x, y + 1, z) < + expected) + toCheck[tcc++] = (((x - xc) + 32)) + + (((y + 1 - yc) + 32) << 6) + + (((z - zc) + 32) << 12); + } + if ((z - 1) >= minXZ) { + if (getBrightnessCached(cache, layer, x, y, z - 1) < + expected) + toCheck[tcc++] = (((x - xc) + 32)) + + (((y - yc) + 32) << 6) + + (((z - 1 - zc) + 32) << 12); + } + if ((z + 1) <= maxXZ) { + if (getBrightnessCached(cache, layer, x, y, z + 1) < + expected) + toCheck[tcc++] = (((x - xc) + 32)) + + (((y - yc) + 32) << 6) + + (((z + 1 - zc) + 32) << 12); + } } } } @@ -3734,7 +3443,7 @@ void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool f qwTime = qwNewTime; #endif - flushCache(cache, cacheUse, layer); + flushCache(cache, cacheUse, layer); #if 0 ///////////////////////////////////////////////////////////////// if( cache ) @@ -3750,133 +3459,122 @@ void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool f } ///////////////////////////////////////////////////////////////// #endif - LeaveCriticalSection(&m_checkLightCS); - + LeaveCriticalSection(&m_checkLightCS); } +bool Level::tickPendingTicks(bool force) { return false; } -bool Level::tickPendingTicks(bool force) -{ - return false; +std::vector* Level::fetchTicksInChunk(LevelChunk* chunk, + bool remove) { + return NULL; } -std::vector *Level::fetchTicksInChunk(LevelChunk *chunk, bool remove) -{ - return NULL; -} - - -std::vector > *Level::getEntities(std::shared_ptr except, AABB *bb) -{ - MemSect(40); - es.clear(); - int xc0 = Mth::floor((bb->x0 - 2) / 16); - int xc1 = Mth::floor((bb->x1 + 2) / 16); - int zc0 = Mth::floor((bb->z0 - 2) / 16); - int zc1 = Mth::floor((bb->z1 + 2) / 16); +std::vector >* Level::getEntities( + std::shared_ptr except, AABB* bb) { + MemSect(40); + es.clear(); + int xc0 = Mth::floor((bb->x0 - 2) / 16); + int xc1 = Mth::floor((bb->x1 + 2) / 16); + int zc0 = Mth::floor((bb->z0 - 2) / 16); + int zc1 = Mth::floor((bb->z1 + 2) / 16); #ifdef __PSVITA__ #ifdef _ENTITIES_RW_SECTION - // AP - RW critical sections are expensive so enter it here so we only have to call it once instead of X times - EnterCriticalRWSection(&LevelChunk::m_csEntities, false); + // AP - RW critical sections are expensive so enter it here so we only have + // to call it once instead of X times + EnterCriticalRWSection(&LevelChunk::m_csEntities, false); #else - EnterCriticalSection(&LevelChunk::m_csEntities); + EnterCriticalSection(&LevelChunk::m_csEntities); #endif #endif - for (int xc = xc0; xc <= xc1; xc++) - for (int zc = zc0; zc <= zc1; zc++) - { - if (hasChunk(xc, zc)) - { - getChunk(xc, zc)->getEntities(except, bb, es); - } - } - MemSect(0); + for (int xc = xc0; xc <= xc1; xc++) + for (int zc = zc0; zc <= zc1; zc++) { + if (hasChunk(xc, zc)) { + getChunk(xc, zc)->getEntities(except, bb, es); + } + } + MemSect(0); #ifdef __PSVITA__ #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&LevelChunk::m_csEntities, false); + LeaveCriticalRWSection(&LevelChunk::m_csEntities, false); #else - LeaveCriticalSection(&LevelChunk::m_csEntities); + LeaveCriticalSection(&LevelChunk::m_csEntities); #endif #endif - return &es; + return &es; } - -std::vector > *Level::getEntitiesOfClass(const std::type_info& baseClass, AABB *bb) -{ - int xc0 = Mth::floor((bb->x0 - 2) / 16); - int xc1 = Mth::floor((bb->x1 + 2) / 16); - int zc0 = Mth::floor((bb->z0 - 2) / 16); - int zc1 = Mth::floor((bb->z1 + 2) / 16); - std::vector > *es = new std::vector >(); +std::vector >* Level::getEntitiesOfClass( + const std::type_info& baseClass, AABB* bb) { + int xc0 = Mth::floor((bb->x0 - 2) / 16); + int xc1 = Mth::floor((bb->x1 + 2) / 16); + int zc0 = Mth::floor((bb->z0 - 2) / 16); + int zc1 = Mth::floor((bb->z1 + 2) / 16); + std::vector >* es = + new std::vector >(); #ifdef __PSVITA__ #ifdef _ENTITIES_RW_SECTION - // AP - RW critical sections are expensive so enter it here so we only have to call it once instead of X times - EnterCriticalRWSection(&LevelChunk::m_csEntities, false); + // AP - RW critical sections are expensive so enter it here so we only have + // to call it once instead of X times + EnterCriticalRWSection(&LevelChunk::m_csEntities, false); #else - EnterCriticalSection(&LevelChunk::m_csEntities); + EnterCriticalSection(&LevelChunk::m_csEntities); #endif #endif - for (int xc = xc0; xc <= xc1; xc++) - for (int zc = zc0; zc <= zc1; zc++) - { - if (hasChunk(xc, zc)) - { - getChunk(xc, zc)->getEntitiesOfClass(baseClass, bb, *es); - } - } + for (int xc = xc0; xc <= xc1; xc++) + for (int zc = zc0; zc <= zc1; zc++) { + if (hasChunk(xc, zc)) { + getChunk(xc, zc)->getEntitiesOfClass(baseClass, bb, *es); + } + } #ifdef __PSVITA__ #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&LevelChunk::m_csEntities, false); + LeaveCriticalRWSection(&LevelChunk::m_csEntities, false); #else - LeaveCriticalSection(&LevelChunk::m_csEntities); + LeaveCriticalSection(&LevelChunk::m_csEntities); #endif #endif - return es; + return es; } -std::shared_ptr Level::getClosestEntityOfClass(const std::type_info& baseClass, AABB *bb, std::shared_ptr source) -{ - std::vector > *entities = getEntitiesOfClass(baseClass, bb); - std::shared_ptr closest = nullptr; - double closestDistSqr = Double::MAX_VALUE; - //for (Entity entity : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - std::shared_ptr entity = *it; - if (entity == source) continue; - double distSqr = source->distanceToSqr(entity); - if (distSqr > closestDistSqr) continue; - closest = entity; - closestDistSqr = distSqr; - } - delete entities; - return closest; +std::shared_ptr Level::getClosestEntityOfClass( + const std::type_info& baseClass, AABB* bb, std::shared_ptr source) { + std::vector >* entities = + getEntitiesOfClass(baseClass, bb); + std::shared_ptr closest = nullptr; + double closestDistSqr = Double::MAX_VALUE; + // for (Entity entity : entities) + for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) { + std::shared_ptr entity = *it; + if (entity == source) continue; + double distSqr = source->distanceToSqr(entity); + if (distSqr > closestDistSqr) continue; + closest = entity; + closestDistSqr = distSqr; + } + delete entities; + return closest; } -std::vector > Level::getAllEntities() -{ - EnterCriticalSection(&m_entitiesCS); - std::vector > retVec = entities; - LeaveCriticalSection(&m_entitiesCS); - return retVec; +std::vector > Level::getAllEntities() { + EnterCriticalSection(&m_entitiesCS); + std::vector > retVec = entities; + LeaveCriticalSection(&m_entitiesCS); + return retVec; } - -void Level::tileEntityChanged(int x, int y, int z, std::shared_ptr te) -{ - if (this->hasChunkAt(x, y, z)) - { - getChunkAt(x, z)->markUnsaved(); - } +void Level::tileEntityChanged(int x, int y, int z, + std::shared_ptr te) { + if (this->hasChunkAt(x, y, z)) { + getChunkAt(x, z)->markUnsaved(); + } } #if 0 @@ -3896,331 +3594,255 @@ unsigned int Level::countInstanceOf(BaseObject::Class *clas) } #endif -// 4J - added - more limited (but faster) version of above, used to count water animals, animals, monsters for the mob spawner -// singleType flag should be true if we are just trying to match eINSTANCEOF exactly, and false if it is a eINSTANCEOF from a group (eTYPE_WATERANIMAL, eTYPE_ANIMAL, eTYPE_MONSTER) -unsigned int Level::countInstanceOf(eINSTANCEOF clas, bool singleType, unsigned int *protectedCount/* = NULL*/, unsigned int *couldWanderCount/* = NULL*/) -{ - unsigned int count = 0; - if( protectedCount ) *protectedCount = 0; - if( couldWanderCount ) *couldWanderCount = 0; - EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) - { - std::shared_ptr e = *it;//entities.at(i); - if( singleType ) - { - if (e->GetType() == clas) - { - if ( protectedCount && e->isDespawnProtected() ) - { - (*protectedCount)++; - } +// 4J - added - more limited (but faster) version of above, used to count water +// animals, animals, monsters for the mob spawner singleType flag should be true +// if we are just trying to match eINSTANCEOF exactly, and false if it is a +// eINSTANCEOF from a group (eTYPE_WATERANIMAL, eTYPE_ANIMAL, eTYPE_MONSTER) +unsigned int Level::countInstanceOf( + eINSTANCEOF clas, bool singleType, unsigned int* protectedCount /* = NULL*/, + unsigned int* couldWanderCount /* = NULL*/) { + unsigned int count = 0; + if (protectedCount) *protectedCount = 0; + if (couldWanderCount) *couldWanderCount = 0; + EnterCriticalSection(&m_entitiesCS); + AUTO_VAR(itEnd, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities.at(i); + if (singleType) { + if (e->GetType() == clas) { + if (protectedCount && e->isDespawnProtected()) { + (*protectedCount)++; + } - if ( couldWanderCount && e->couldWander() ) - { - (*couldWanderCount)++; - } + if (couldWanderCount && e->couldWander()) { + (*couldWanderCount)++; + } - count++; - } - } - else - { - if (e->GetType() & clas) count++; - } - } - LeaveCriticalSection(&m_entitiesCS); - - return count; -} - -unsigned int Level::countInstanceOfInRange(eINSTANCEOF clas, bool singleType, int range, int x, int y, int z) -{ - unsigned int count = 0; - EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) - { - std::shared_ptr e = *it;//entities.at(i); - - float sd = e->distanceTo(x,y,z); - if (sd * sd > range * range) - { - continue; - } - - if( singleType ) - { - if (e->GetType() == clas) - { - count++; - } - } - else - { - if (e->GetType() & clas) - { - count++; - } - } - } - LeaveCriticalSection(&m_entitiesCS); - - return count; -} - -void Level::addEntities(std::vector > *list) -{ - //entities.addAll(list); - EnterCriticalSection(&m_entitiesCS); - entities.insert(entities.end(), list->begin(), list->end()); - AUTO_VAR(itEnd, list->end()); - bool deleteDragons = false; - for (AUTO_VAR(it, list->begin()); it != itEnd; it++) - { - entityAdded(*it); - - // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) - { - deleteDragons = true; - } - } - - if(deleteDragons) - { - deleteDragons = false; - for(AUTO_VAR(it, entities.begin()); it != entities.end(); ++it) - { - // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) - { - if(deleteDragons) - { - (*it)->remove(); - } - else - { - deleteDragons = true; - } - } - } - } - LeaveCriticalSection(&m_entitiesCS); -} - - -void Level::removeEntities(std::vector > *list) -{ - //entitiesToRemove.addAll(list); - entitiesToRemove.insert(entitiesToRemove.end(), list->begin(), list->end()); -} - -bool Level::mayPlace(int tileId, int x, int y, int z, bool ignoreEntities, int face, std::shared_ptr ignoreEntity) -{ - int targetType = getTile(x, y, z); - Tile *targetTile = Tile::tiles[targetType]; - - Tile *tile = Tile::tiles[tileId]; - - AABB *aabb = tile->getAABB(this, x, y, z); - if (ignoreEntities) aabb = NULL; - if (aabb != NULL && !isUnobstructed(aabb, ignoreEntity)) return false; - if (targetTile != NULL && - (targetTile == Tile::water || targetTile == Tile::calmWater || targetTile == Tile::lava || - targetTile == Tile::calmLava || targetTile == Tile::fire || targetTile->material->isReplaceable())) targetTile = NULL; - if (targetTile != NULL && targetTile->material == Material::decoration && tile == Tile::anvil) return true; - if (tileId > 0 && targetTile == NULL) - { - if (tile->mayPlace(this, x, y, z, face)) - { - return true; - } - } - return false; -} - - -int Level::getSeaLevel() -{ - return seaLevel; -} - - -Path *Level::findPath(std::shared_ptr from, std::shared_ptr to, float maxDist, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat) -{ - int x = Mth::floor(from->x); - int y = Mth::floor(from->y + 1); - int z = Mth::floor(from->z); - - int r = (int) (maxDist + 16); - int x1 = x - r; - int y1 = y - r; - int z1 = z - r; - int x2 = x + r; - int y2 = y + r; - int z2 = z + r; - Region region = Region(this, x1, y1, z1, x2, y2, z2); - Path *path = (PathFinder(®ion, canPassDoors, canOpenDoors, avoidWater, canFloat)).findPath(from.get(), to.get(), maxDist); - return path; -} - - -Path *Level::findPath(std::shared_ptr from, int xBest, int yBest, int zBest, float maxDist, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat) -{ - int x = Mth::floor(from->x); - int y = Mth::floor(from->y); - int z = Mth::floor(from->z); - - int r = (int) (maxDist + 8); - int x1 = x - r; - int y1 = y - r; - int z1 = z - r; - int x2 = x + r; - int y2 = y + r; - int z2 = z + r; - Region region = Region(this, x1, y1, z1, x2, y2, z2); - Path *path = (PathFinder(®ion, canPassDoors, canOpenDoors, avoidWater, canFloat)).findPath(from.get(), xBest, yBest, zBest, maxDist); - return path; -} - - -bool Level::getDirectSignal(int x, int y, int z, int dir) -{ - int t = getTile(x, y, z); - if (t == 0) return false; - return Tile::tiles[t]->getDirectSignal(this, x, y, z, dir); -} - - -bool Level::hasDirectSignal(int x, int y, int z) -{ - if (getDirectSignal(x, y - 1, z, 0)) return true; - if (getDirectSignal(x, y + 1, z, 1)) return true; - if (getDirectSignal(x, y, z - 1, 2)) return true; - if (getDirectSignal(x, y, z + 1, 3)) return true; - if (getDirectSignal(x - 1, y, z, 4)) return true; - if (getDirectSignal(x + 1, y, z, 5)) return true; - return false; -} - - -bool Level::getSignal(int x, int y, int z, int dir) -{ - if (isSolidBlockingTile(x, y, z)) - { - return hasDirectSignal(x, y, z); - } - int t = getTile(x, y, z); - if (t == 0) return false; - return Tile::tiles[t]->getSignal(this, x, y, z, dir); -} - - -bool Level::hasNeighborSignal(int x, int y, int z) -{ - if (getSignal(x, y - 1, z, 0)) return true; - if (getSignal(x, y + 1, z, 1)) return true; - if (getSignal(x, y, z - 1, 2)) return true; - if (getSignal(x, y, z + 1, 3)) return true; - if (getSignal(x - 1, y, z, 4)) return true; - if (getSignal(x + 1, y, z, 5)) return true; - return false; -} - -// 4J Stu - Added maxYDist param -std::shared_ptr Level::getNearestPlayer(std::shared_ptr source, double maxDist, double maxYDist /*= -1*/) -{ - return getNearestPlayer(source->x, source->y, source->z, maxDist, maxYDist); -} - -// 4J Stu - Added maxYDist param -std::shared_ptr Level::getNearestPlayer(double x, double y, double z, double maxDist, double maxYDist /*= -1*/) -{ - MemSect(21); - double best = -1; - std::shared_ptr result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) - { - std::shared_ptr p = *it;//players.at(i); - double dist = p->distanceToSqr(x, y, z); - - // Allow specifying shorter distances in the vertical - if(maxYDist > 0 && abs(p->y - y) > maxYDist) continue; - - // 4J Stu - Added check that this player is still alive - if ((maxDist < 0 || dist < maxDist * maxDist) && (best == -1 || dist < best) && p->isAlive() ) - { - best = dist; - result = p; - } - } - MemSect(0); - return result; -} - -std::shared_ptr Level::getNearestPlayer(double x, double z, double maxDist) -{ - double best = -1; - std::shared_ptr result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) - { - std::shared_ptr p = *it; - double dist = p->distanceToSqr(x, p->y, z); - if ((maxDist < 0 || dist < maxDist * maxDist) && (best == -1 || dist < best)) - { - best = dist; - result = p; - } - } - return result; -} - -std::shared_ptr Level::getNearestAttackablePlayer(std::shared_ptr source, double maxDist) -{ - return getNearestAttackablePlayer(source->x, source->y, source->z, maxDist); -} - -std::shared_ptr Level::getNearestAttackablePlayer(double x, double y, double z, double maxDist) -{ - double best = -1; - - std::shared_ptr result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) - { - std::shared_ptr p = *it; - - if (p->abilities.invulnerable) - { - continue; - } - - double dist = p->distanceToSqr(x, y, z); - double visibleDist = maxDist; - - // decrease the max attackable distance if the target player - // is sneaking or invisible - if (p->isSneaking()) - { - visibleDist *= .8f; - } - if (p->isInvisible()) - { - float coverPercentage = p->getArmorCoverPercentage(); - if (coverPercentage < .1f) - { - coverPercentage = .1f; + count++; } - visibleDist *= (.7f * coverPercentage); + } else { + if (e->GetType() & clas) count++; } - - // 4J Stu - Added check that this player is still alive and privilege check - if ((visibleDist < 0 || dist < visibleDist * visibleDist) && (best == -1 || dist < best) && p->isAlive() && !p->hasInvisiblePrivilege()) - { + } + LeaveCriticalSection(&m_entitiesCS); + + return count; +} + +unsigned int Level::countInstanceOfInRange(eINSTANCEOF clas, bool singleType, + int range, int x, int y, int z) { + unsigned int count = 0; + EnterCriticalSection(&m_entitiesCS); + AUTO_VAR(itEnd, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities.at(i); + + float sd = e->distanceTo(x, y, z); + if (sd * sd > range * range) { + continue; + } + + if (singleType) { + if (e->GetType() == clas) { + count++; + } + } else { + if (e->GetType() & clas) { + count++; + } + } + } + LeaveCriticalSection(&m_entitiesCS); + + return count; +} + +void Level::addEntities(std::vector >* list) { + // entities.addAll(list); + EnterCriticalSection(&m_entitiesCS); + entities.insert(entities.end(), list->begin(), list->end()); + AUTO_VAR(itEnd, list->end()); + bool deleteDragons = false; + for (AUTO_VAR(it, list->begin()); it != itEnd; it++) { + entityAdded(*it); + + // 4J Stu - Special change to remove duplicate enderdragons that a + // previous bug might have produced + if ((*it)->GetType() == eTYPE_ENDERDRAGON) { + deleteDragons = true; + } + } + + if (deleteDragons) { + deleteDragons = false; + for (AUTO_VAR(it, entities.begin()); it != entities.end(); ++it) { + // 4J Stu - Special change to remove duplicate enderdragons that a + // previous bug might have produced + if ((*it)->GetType() == eTYPE_ENDERDRAGON) { + if (deleteDragons) { + (*it)->remove(); + } else { + deleteDragons = true; + } + } + } + } + LeaveCriticalSection(&m_entitiesCS); +} + +void Level::removeEntities(std::vector >* list) { + // entitiesToRemove.addAll(list); + entitiesToRemove.insert(entitiesToRemove.end(), list->begin(), list->end()); +} + +bool Level::mayPlace(int tileId, int x, int y, int z, bool ignoreEntities, + int face, std::shared_ptr ignoreEntity) { + int targetType = getTile(x, y, z); + Tile* targetTile = Tile::tiles[targetType]; + + Tile* tile = Tile::tiles[tileId]; + + AABB* aabb = tile->getAABB(this, x, y, z); + if (ignoreEntities) aabb = NULL; + if (aabb != NULL && !isUnobstructed(aabb, ignoreEntity)) return false; + if (targetTile != NULL && + (targetTile == Tile::water || targetTile == Tile::calmWater || + targetTile == Tile::lava || targetTile == Tile::calmLava || + targetTile == Tile::fire || targetTile->material->isReplaceable())) + targetTile = NULL; + if (targetTile != NULL && targetTile->material == Material::decoration && + tile == Tile::anvil) + return true; + if (tileId > 0 && targetTile == NULL) { + if (tile->mayPlace(this, x, y, z, face)) { + return true; + } + } + return false; +} + +int Level::getSeaLevel() { return seaLevel; } + +Path* Level::findPath(std::shared_ptr from, std::shared_ptr to, + float maxDist, bool canPassDoors, bool canOpenDoors, + bool avoidWater, bool canFloat) { + int x = Mth::floor(from->x); + int y = Mth::floor(from->y + 1); + int z = Mth::floor(from->z); + + int r = (int)(maxDist + 16); + int x1 = x - r; + int y1 = y - r; + int z1 = z - r; + int x2 = x + r; + int y2 = y + r; + int z2 = z + r; + Region region = Region(this, x1, y1, z1, x2, y2, z2); + Path* path = + (PathFinder(®ion, canPassDoors, canOpenDoors, avoidWater, canFloat)) + .findPath(from.get(), to.get(), maxDist); + return path; +} + +Path* Level::findPath(std::shared_ptr from, int xBest, int yBest, + int zBest, float maxDist, bool canPassDoors, + bool canOpenDoors, bool avoidWater, bool canFloat) { + int x = Mth::floor(from->x); + int y = Mth::floor(from->y); + int z = Mth::floor(from->z); + + int r = (int)(maxDist + 8); + int x1 = x - r; + int y1 = y - r; + int z1 = z - r; + int x2 = x + r; + int y2 = y + r; + int z2 = z + r; + Region region = Region(this, x1, y1, z1, x2, y2, z2); + Path* path = + (PathFinder(®ion, canPassDoors, canOpenDoors, avoidWater, canFloat)) + .findPath(from.get(), xBest, yBest, zBest, maxDist); + return path; +} + +bool Level::getDirectSignal(int x, int y, int z, int dir) { + int t = getTile(x, y, z); + if (t == 0) return false; + return Tile::tiles[t]->getDirectSignal(this, x, y, z, dir); +} + +bool Level::hasDirectSignal(int x, int y, int z) { + if (getDirectSignal(x, y - 1, z, 0)) return true; + if (getDirectSignal(x, y + 1, z, 1)) return true; + if (getDirectSignal(x, y, z - 1, 2)) return true; + if (getDirectSignal(x, y, z + 1, 3)) return true; + if (getDirectSignal(x - 1, y, z, 4)) return true; + if (getDirectSignal(x + 1, y, z, 5)) return true; + return false; +} + +bool Level::getSignal(int x, int y, int z, int dir) { + if (isSolidBlockingTile(x, y, z)) { + return hasDirectSignal(x, y, z); + } + int t = getTile(x, y, z); + if (t == 0) return false; + return Tile::tiles[t]->getSignal(this, x, y, z, dir); +} + +bool Level::hasNeighborSignal(int x, int y, int z) { + if (getSignal(x, y - 1, z, 0)) return true; + if (getSignal(x, y + 1, z, 1)) return true; + if (getSignal(x, y, z - 1, 2)) return true; + if (getSignal(x, y, z + 1, 3)) return true; + if (getSignal(x - 1, y, z, 4)) return true; + if (getSignal(x + 1, y, z, 5)) return true; + return false; +} + +// 4J Stu - Added maxYDist param +std::shared_ptr Level::getNearestPlayer(std::shared_ptr source, + double maxDist, + double maxYDist /*= -1*/) { + return getNearestPlayer(source->x, source->y, source->z, maxDist, maxYDist); +} + +// 4J Stu - Added maxYDist param +std::shared_ptr Level::getNearestPlayer(double x, double y, double z, + double maxDist, + double maxYDist /*= -1*/) { + MemSect(21); + double best = -1; + std::shared_ptr result = nullptr; + AUTO_VAR(itEnd, players.end()); + for (AUTO_VAR(it, players.begin()); it != itEnd; it++) { + std::shared_ptr p = *it; // players.at(i); + double dist = p->distanceToSqr(x, y, z); + + // Allow specifying shorter distances in the vertical + if (maxYDist > 0 && abs(p->y - y) > maxYDist) continue; + + // 4J Stu - Added check that this player is still alive + if ((maxDist < 0 || dist < maxDist * maxDist) && + (best == -1 || dist < best) && p->isAlive()) { + best = dist; + result = p; + } + } + MemSect(0); + return result; +} + +std::shared_ptr Level::getNearestPlayer(double x, double z, + double maxDist) { + double best = -1; + std::shared_ptr result = nullptr; + AUTO_VAR(itEnd, players.end()); + for (AUTO_VAR(it, players.begin()); it != itEnd; it++) { + std::shared_ptr p = *it; + double dist = p->distanceToSqr(x, p->y, z); + if ((maxDist < 0 || dist < maxDist * maxDist) && + (best == -1 || dist < best)) { best = dist; result = p; } @@ -4228,346 +3850,324 @@ std::shared_ptr Level::getNearestAttackablePlayer(double x, double y, do return result; } -std::shared_ptr Level::getPlayerByName(const std::wstring& name) -{ - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) - { - if (name.compare( (*it)->name) == 0) - { - return *it; //players.at(i); - } - } - return std::shared_ptr(); +std::shared_ptr Level::getNearestAttackablePlayer( + std::shared_ptr source, double maxDist) { + return getNearestAttackablePlayer(source->x, source->y, source->z, maxDist); } -std::shared_ptr Level::getPlayerByUUID(const std::wstring& name) -{ - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) - { - if (name.compare( (*it)->getUUID() ) == 0) - { - return *it; //players.at(i); - } - } - return std::shared_ptr(); +std::shared_ptr Level::getNearestAttackablePlayer(double x, double y, + double z, + double maxDist) { + double best = -1; + + std::shared_ptr result = nullptr; + AUTO_VAR(itEnd, players.end()); + for (AUTO_VAR(it, players.begin()); it != itEnd; it++) { + std::shared_ptr p = *it; + + if (p->abilities.invulnerable) { + continue; + } + + double dist = p->distanceToSqr(x, y, z); + double visibleDist = maxDist; + + // decrease the max attackable distance if the target player + // is sneaking or invisible + if (p->isSneaking()) { + visibleDist *= .8f; + } + if (p->isInvisible()) { + float coverPercentage = p->getArmorCoverPercentage(); + if (coverPercentage < .1f) { + coverPercentage = .1f; + } + visibleDist *= (.7f * coverPercentage); + } + + // 4J Stu - Added check that this player is still alive and privilege + // check + if ((visibleDist < 0 || dist < visibleDist * visibleDist) && + (best == -1 || dist < best) && p->isAlive() && + !p->hasInvisiblePrivilege()) { + best = dist; + result = p; + } + } + return result; +} + +std::shared_ptr Level::getPlayerByName(const std::wstring& name) { + AUTO_VAR(itEnd, players.end()); + for (AUTO_VAR(it, players.begin()); it != itEnd; it++) { + if (name.compare((*it)->name) == 0) { + return *it; // players.at(i); + } + } + return std::shared_ptr(); +} + +std::shared_ptr Level::getPlayerByUUID(const std::wstring& name) { + AUTO_VAR(itEnd, players.end()); + for (AUTO_VAR(it, players.begin()); it != itEnd; it++) { + if (name.compare((*it)->getUUID()) == 0) { + return *it; // players.at(i); + } + } + return std::shared_ptr(); } // 4J Stu - Removed in 1.2.3 ? -byteArray Level::getBlocksAndData(int x, int y, int z, int xs, int ys, int zs, bool includeLighting/* = true*/) -{ - byteArray result( xs * ys * zs * 5 / 2 ); - int xc0 = x >> 4; - int zc0 = z >> 4; - int xc1 = (x + xs - 1) >> 4; - int zc1 = (z + zs - 1) >> 4; +byteArray Level::getBlocksAndData(int x, int y, int z, int xs, int ys, int zs, + bool includeLighting /* = true*/) { + byteArray result(xs * ys * zs * 5 / 2); + int xc0 = x >> 4; + int zc0 = z >> 4; + int xc1 = (x + xs - 1) >> 4; + int zc1 = (z + zs - 1) >> 4; - int p = 0; + int p = 0; - int y0 = y; - int y1 = y + ys; - if (y0 < 0) y0 = 0; - if (y1 > Level::maxBuildHeight) y1 = Level::maxBuildHeight; - for (int xc = xc0; xc <= xc1; xc++) - { - int x0 = x - xc * 16; - int x1 = x + xs - xc * 16; - if (x0 < 0) x0 = 0; - if (x1 > 16) x1 = 16; - for (int zc = zc0; zc <= zc1; zc++) - { - int z0 = z - zc * 16; - int z1 = z + zs - zc * 16; - if (z0 < 0) z0 = 0; - if (z1 > 16) z1 = 16; - p = getChunk(xc, zc)->getBlocksAndData(&result, x0, y0, z0, x1, y1, z1, p, includeLighting); - } - } + int y0 = y; + int y1 = y + ys; + if (y0 < 0) y0 = 0; + if (y1 > Level::maxBuildHeight) y1 = Level::maxBuildHeight; + for (int xc = xc0; xc <= xc1; xc++) { + int x0 = x - xc * 16; + int x1 = x + xs - xc * 16; + if (x0 < 0) x0 = 0; + if (x1 > 16) x1 = 16; + for (int zc = zc0; zc <= zc1; zc++) { + int z0 = z - zc * 16; + int z1 = z + zs - zc * 16; + if (z0 < 0) z0 = 0; + if (z1 > 16) z1 = 16; + p = getChunk(xc, zc)->getBlocksAndData(&result, x0, y0, z0, x1, y1, + z1, p, includeLighting); + } + } - return result; + return result; } // 4J Stu - Removed in 1.2.3 ? -void Level::setBlocksAndData(int x, int y, int z, int xs, int ys, int zs, byteArray data, bool includeLighting/* = true*/) -{ - int xc0 = x >> 4; - int zc0 = z >> 4; - int xc1 = (x + xs - 1) >> 4; - int zc1 = (z + zs - 1) >> 4; +void Level::setBlocksAndData(int x, int y, int z, int xs, int ys, int zs, + byteArray data, bool includeLighting /* = true*/) { + int xc0 = x >> 4; + int zc0 = z >> 4; + int xc1 = (x + xs - 1) >> 4; + int zc1 = (z + zs - 1) >> 4; - int p = 0; + int p = 0; - int y0 = y; - int y1 = y + ys; - if (y0 < 0) y0 = 0; - if (y1 > Level::maxBuildHeight) y1 = Level::maxBuildHeight; - for (int xc = xc0; xc <= xc1; xc++) - { - int x0 = x - xc * 16; - int x1 = x + xs - xc * 16; - if (x0 < 0) x0 = 0; - if (x1 > 16) x1 = 16; - for (int zc = zc0; zc <= zc1; zc++) - { - int z0 = z - zc * 16; - int z1 = z + zs - zc * 16; - if (z0 < 0) z0 = 0; - if (z1 > 16) z1 = 16; - LevelChunk *lc = getChunk(xc, zc); - // 4J Stu - Unshare before we make any changes incase the server is already another step ahead of us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - // This is quite expensive so only actually do it if we are hosting, online, and the update will actually - // change something - bool forceUnshare = false; - if( g_NetworkManager.IsHost() && isClientSide ) - { - forceUnshare = lc->testSetBlocksAndData(data, x0, y0, z0, x1, y1, z1, p); - } - if( forceUnshare ) - { - int size = (x1 - x0 ) * ( y1 - y0 ) * ( z1 - z0 ); - PIXBeginNamedEvent(0,"Chunk data unsharing %d\n", size); - lc->stopSharingTilesAndData(); - PIXEndNamedEvent(); - } - if(p < data.length) p = lc->setBlocksAndData(data, x0, y0, z0, x1, y1, z1, p, includeLighting); - setTilesDirty(xc * 16 + x0, y0, zc * 16 + z0, xc * 16 + x1, y1, zc * 16 + z1); + int y0 = y; + int y1 = y + ys; + if (y0 < 0) y0 = 0; + if (y1 > Level::maxBuildHeight) y1 = Level::maxBuildHeight; + for (int xc = xc0; xc <= xc1; xc++) { + int x0 = x - xc * 16; + int x1 = x + xs - xc * 16; + if (x0 < 0) x0 = 0; + if (x1 > 16) x1 = 16; + for (int zc = zc0; zc <= zc1; zc++) { + int z0 = z - zc * 16; + int z1 = z + zs - zc * 16; + if (z0 < 0) z0 = 0; + if (z1 > 16) z1 = 16; + LevelChunk* lc = getChunk(xc, zc); + // 4J Stu - Unshare before we make any changes incase the server is + // already another step ahead of us Fix for #7904 - Gameplay: + // Players can dupe torches by throwing them repeatedly into water. + // This is quite expensive so only actually do it if we are hosting, + // online, and the update will actually change something + bool forceUnshare = false; + if (g_NetworkManager.IsHost() && isClientSide) { + forceUnshare = + lc->testSetBlocksAndData(data, x0, y0, z0, x1, y1, z1, p); + } + if (forceUnshare) { + int size = (x1 - x0) * (y1 - y0) * (z1 - z0); + PIXBeginNamedEvent(0, "Chunk data unsharing %d\n", size); + lc->stopSharingTilesAndData(); + PIXEndNamedEvent(); + } + if (p < data.length) + p = lc->setBlocksAndData(data, x0, y0, z0, x1, y1, z1, p, + includeLighting); + setTilesDirty(xc * 16 + x0, y0, zc * 16 + z0, xc * 16 + x1, y1, + zc * 16 + z1); - PIXBeginNamedEvent(0,"Chunk data sharing\n"); - if( g_NetworkManager.IsHost() && isClientSide ) - { - lc->startSharingTilesAndData(); - } - PIXEndNamedEvent(); - } - } + PIXBeginNamedEvent(0, "Chunk data sharing\n"); + if (g_NetworkManager.IsHost() && isClientSide) { + lc->startSharingTilesAndData(); + } + PIXEndNamedEvent(); + } + } } +void Level::disconnect(bool sendDisconnect /*= true*/) {} -void Level::disconnect(bool sendDisconnect /*= true*/) -{ -} +void Level::checkSession() { levelStorage->checkSession(); } +void Level::setTime(__int64 time) { + // 4J : WESTY : Added to track game time played by players for other awards. + if (time != 0) // Ignore setting time to 0, done at level start and during + // tutorial. + { + // Determine step in time and ensure it is reasonable ( we only have an + // int to store the player stat). + __int64 timeDiff = time - levelData->getTime(); -void Level::checkSession() -{ - levelStorage->checkSession(); -} - - -void Level::setTime(__int64 time) -{ - // 4J : WESTY : Added to track game time played by players for other awards. - if (time != 0) // Ignore setting time to 0, done at level start and during tutorial. - { - // Determine step in time and ensure it is reasonable ( we only have an int to store the player stat). - __int64 timeDiff = time - levelData->getTime(); - - // debug setting added to keep it at day time -#ifndef _FINAL_BUILD - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getTime(); - } - } + // debug setting added to keep it at day time +#ifndef _FINAL_BUILD + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_FreezeTime)) { + timeDiff = 0; + time = levelData->getTime(); + } + } #endif - if (timeDiff < 0) - { - timeDiff = 0; - } - else if (timeDiff > 100) - { - // Time differences of more than ~5 seconds are generally not real time passing so ignore (moving dimensions does this) - app.DebugPrintf("Level::setTime: Massive time difference, ignoring for time passed stat (%lli)\n", timeDiff); - timeDiff = 0; - } + if (timeDiff < 0) { + timeDiff = 0; + } else if (timeDiff > 100) { + // Time differences of more than ~5 seconds are generally not real + // time passing so ignore (moving dimensions does this) + app.DebugPrintf( + "Level::setTime: Massive time difference, ignoring for time " + "passed stat (%lli)\n", + timeDiff); + timeDiff = 0; + } - // Apply stat to each player. - if ( timeDiff > 0 && levelData->getTime() != -1 ) - { - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++) - { - (*it)->awardStat( GenericStats::timePlayed(), GenericStats::param_time(timeDiff) ); - } - } - } + // Apply stat to each player. + if (timeDiff > 0 && levelData->getTime() != -1) { + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = + players.begin(); + it != itEnd; it++) { + (*it)->awardStat(GenericStats::timePlayed(), + GenericStats::param_time(timeDiff)); + } + } + } - this->levelData->setTime(time); + this->levelData->setTime(time); } -void Level::setOverrideTimeOfDay(__int64 time) -{ - m_timeOfDayOverride = time; +void Level::setOverrideTimeOfDay(__int64 time) { m_timeOfDayOverride = time; } + +__int64 Level::getSeed() { return levelData->getSeed(); } + +__int64 Level::getTime() { return levelData->getTime(); } + +Pos* Level::getSharedSpawnPos() { + return new Pos(levelData->getXSpawn(), levelData->getYSpawn(), + levelData->getZSpawn()); } -__int64 Level::getSeed() -{ - return levelData->getSeed(); +void Level::setSpawnPos(int x, int y, int z) { levelData->setSpawn(x, y, z); } + +void Level::setSpawnPos(Pos* spawnPos) { + setSpawnPos(spawnPos->x, spawnPos->y, spawnPos->z); } +void Level::ensureAdded(std::shared_ptr entity) { + int xc = Mth::floor(entity->x / 16); + int zc = Mth::floor(entity->z / 16); + int r = 2; + for (int x = xc - r; x <= xc + r; x++) { + for (int z = zc - r; z <= zc + r; z++) { + this->getChunk(x, z); + } + } -__int64 Level::getTime() -{ - return levelData->getTime(); + // if (!entities.contains(entity)) + EnterCriticalSection(&m_entitiesCS); + if (find(entities.begin(), entities.end(), entity) == entities.end()) { + entities.push_back(entity); + } + LeaveCriticalSection(&m_entitiesCS); } - -Pos *Level::getSharedSpawnPos() -{ - return new Pos(levelData->getXSpawn(), levelData->getYSpawn(), levelData->getZSpawn()); +bool Level::mayInteract(std::shared_ptr player, int xt, int yt, int zt, + int content) { + return true; } -void Level::setSpawnPos(int x, int y, int z) -{ - levelData->setSpawn(x, y, z); +void Level::broadcastEntityEvent(std::shared_ptr e, uint8_t event) {} + +ChunkSource* Level::getChunkSource() { return chunkSource; } + +void Level::tileEvent(int x, int y, int z, int tile, int b0, int b1) { + if (tile > 0) Tile::tiles[tile]->triggerEvent(this, x, y, z, b0, b1); } -void Level::setSpawnPos(Pos *spawnPos) -{ - setSpawnPos(spawnPos->x, spawnPos->y, spawnPos->z); +LevelStorage* Level::getLevelStorage() { return levelStorage.get(); } + +LevelData* Level::getLevelData() { return levelData; } + +void Level::updateSleepingPlayerList() {} + +float Level::getThunderLevel(float a) { + return (oThunderLevel + (thunderLevel - oThunderLevel) * a) * + getRainLevel(a); } - -void Level::ensureAdded(std::shared_ptr entity) -{ - int xc = Mth::floor(entity->x / 16); - int zc = Mth::floor(entity->z / 16); - int r = 2; - for (int x = xc - r; x <= xc + r; x++) - { - for (int z = zc - r; z <= zc + r; z++) - { - this->getChunk(x, z); - } - } - - //if (!entities.contains(entity)) - EnterCriticalSection(&m_entitiesCS); - if( find(entities.begin(), entities.end(), entity) == entities.end() ) - { - entities.push_back(entity); - } - LeaveCriticalSection(&m_entitiesCS); +float Level::getRainLevel(float a) { + return oRainLevel + (rainLevel - oRainLevel) * a; } - -bool Level::mayInteract(std::shared_ptr player, int xt, int yt, int zt, int content) -{ - return true; +void Level::setRainLevel(float rainLevel) { + this->oRainLevel = rainLevel; + this->rainLevel = rainLevel; } +bool Level::isThundering() { return getThunderLevel(1) > 0.9; } -void Level::broadcastEntityEvent(std::shared_ptr e, uint8_t event) -{ +bool Level::isRaining() { return getRainLevel(1) > 0.2; } + +bool Level::isRainingAt(int x, int y, int z) { + if (!isRaining()) return false; + if (!canSeeSky(x, y, z)) return false; + if (getTopRainBlock(x, z) > y) return false; + + // 4J - changed to use new method of getting biomedata that caches results + // of rain & snow + if (biomeHasSnow(x, z)) return false; + return biomeHasRain(x, z); } -ChunkSource *Level::getChunkSource() -{ - return chunkSource; +bool Level::isHumidAt(int x, int y, int z) { + Biome* biome = getBiome(x, z); + return biome->isHumid(); } - -void Level::tileEvent(int x, int y, int z, int tile, int b0, int b1) -{ - if (tile > 0) Tile::tiles[tile]->triggerEvent(this, x, y, z, b0, b1); +void Level::setSavedData(const std::wstring& id, + std::shared_ptr data) { + savedDataStorage->set(id, data); } - -LevelStorage *Level::getLevelStorage() -{ - return levelStorage.get(); +std::shared_ptr Level::getSavedData(const std::type_info& clazz, + const std::wstring& id) { + return savedDataStorage->get(clazz, id); } - -LevelData *Level::getLevelData() -{ - return levelData; -} - - -void Level::updateSleepingPlayerList() -{ -} - -float Level::getThunderLevel(float a) -{ - return (oThunderLevel + (thunderLevel - oThunderLevel) * a) * getRainLevel(a); -} - - -float Level::getRainLevel(float a) -{ - return oRainLevel + (rainLevel - oRainLevel) * a; -} - - -void Level::setRainLevel(float rainLevel) -{ - this->oRainLevel = rainLevel; - this->rainLevel = rainLevel; -} - - -bool Level::isThundering() -{ - return getThunderLevel(1) > 0.9; -} - - -bool Level::isRaining() -{ - return getRainLevel(1) > 0.2; -} - - -bool Level::isRainingAt(int x, int y, int z) -{ - if (!isRaining()) return false; - if (!canSeeSky(x, y, z)) return false; - if (getTopRainBlock(x, z) > y) return false; - -// 4J - changed to use new method of getting biomedata that caches results of rain & snow - if (biomeHasSnow(x, z)) return false; - return biomeHasRain(x, z); -} - -bool Level::isHumidAt(int x, int y, int z) -{ - Biome *biome = getBiome(x, z); - return biome->isHumid(); -} - - -void Level::setSavedData(const std::wstring& id, std::shared_ptr data) -{ - savedDataStorage->set(id, data); -} - - -std::shared_ptr Level::getSavedData(const std::type_info& clazz, const std::wstring& id) -{ - return savedDataStorage->get(clazz, id); -} - - -int Level::getFreeAuxValueFor(const std::wstring& id) -{ - return savedDataStorage->getFreeAuxValueFor(id); +int Level::getFreeAuxValueFor(const std::wstring& id) { + return savedDataStorage->getFreeAuxValueFor(id); } // 4J Added -int Level::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale) -{ - return savedDataStorage->getAuxValueForMap(xuid, dimension, centreXC, centreZC, scale); +int Level::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, + int centreZC, int scale) { + return savedDataStorage->getAuxValueForMap(xuid, dimension, centreXC, + centreZC, scale); } -// void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) +// void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, +// int data) // { // auto itEnd = listeners.end(); // for (auto it = listeners.begin(); it != itEnd; it++) @@ -4576,217 +4176,181 @@ int Level::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int ce // } // } -void Level::levelEvent(int type, int x, int y, int z, int data) -{ - levelEvent(nullptr, type, x, y, z, data); +void Level::levelEvent(int type, int x, int y, int z, int data) { + levelEvent(nullptr, type, x, y, z, data); } - -void Level::levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->levelEvent(source, type, x, y, z, data); - } +void Level::levelEvent(std::shared_ptr source, int type, int x, int y, + int z, int data) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->levelEvent(source, type, x, y, z, data); + } } -int Level::getMaxBuildHeight() -{ - return maxBuildHeight; +int Level::getMaxBuildHeight() { return maxBuildHeight; } + +int Level::getHeight() { + return dimension->hasCeiling ? genDepth : maxBuildHeight; } -int Level::getHeight() -{ - return dimension->hasCeiling ? genDepth : maxBuildHeight; +Random* Level::getRandomFor(int x, int z, int blend) { + __int64 seed = (x * 341873128712l + z * 132897987541l) + + getLevelData()->getSeed() + blend; + random->setSeed(seed); + return random; } -Random *Level::getRandomFor(int x, int z, int blend) -{ - __int64 seed = (x * 341873128712l + z * 132897987541l) + getLevelData()->getSeed() + blend; - random->setSeed(seed); - return random; -} +bool Level::updateLights() { return false; } -bool Level::updateLights() -{ - return false; -} - -TilePos *Level::findNearestMapFeature(const std::wstring& featureName, int x, int y, int z) -{ +TilePos* Level::findNearestMapFeature(const std::wstring& featureName, int x, + int y, int z) { return getChunkSource()->findNearestMapFeature(this, featureName, x, y, z); } -bool Level::isAllEmpty() -{ - return false; +bool Level::isAllEmpty() { return false; } + +double Level::getHorizonHeight() { + if (levelData->getGenerator() == LevelType::lvl_flat) { + return 0.0; + } + return 63.0; } -double Level::getHorizonHeight() -{ - if (levelData->getGenerator() == LevelType::lvl_flat) - { - return 0.0; - } - return 63.0; +void Level::destroyTileProgress(int id, int x, int y, int z, int progress) { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->destroyTileProgress(id, x, y, z, progress); + } } -void Level::destroyTileProgress(int id, int x, int y, int z, int progress) -{ - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->destroyTileProgress(id, x, y, z, progress); - } +bool Level::useNewSeaLevel() { return levelData->useNewSeaLevel(); } + +bool Level::getHasBeenInCreative() { return levelData->getHasBeenInCreative(); } + +bool Level::isGenerateMapFeatures() { + return levelData->isGenerateMapFeatures(); } -bool Level::useNewSeaLevel() -{ - return levelData->useNewSeaLevel(); +int Level::getSaveVersion() { + return getLevelStorage()->getSaveFile()->getSaveVersion(); } -bool Level::getHasBeenInCreative() -{ - return levelData->getHasBeenInCreative(); +int Level::getOriginalSaveVersion() { + return getLevelStorage()->getSaveFile()->getOriginalSaveVersion(); } -bool Level::isGenerateMapFeatures() -{ - return levelData->isGenerateMapFeatures(); +// 4J - determine if a chunk has been done the post-post-processing stage. This +// happens when *its* neighbours have each been post-processed, and does some +// final lighting that can only really be done when the post-processing has +// placed all possible tiles into this chunk. +bool Level::isChunkPostPostProcessed(int x, int z) { + if (!hasChunk(x, z)) + return false; // This will occur for non-loaded chunks, not for edge + // chunks + + LevelChunk* lc = getChunk(x, z); + if (lc->isEmpty()) + return true; // Since we've already eliminated non-loaded chunks, this + // should only occur for edge chunks. Consider those as + // fully processed + + return ((lc->terrainPopulated & LevelChunk::sTerrainPostPostProcessed) == + LevelChunk::sTerrainPostPostProcessed); } -int Level::getSaveVersion() -{ - return getLevelStorage()->getSaveFile()->getSaveVersion(); +// 4J added - returns true if a chunk is fully, fully finalised - in that it can +// be sent to another machine. This is the case when all 8 neighbours of this +// chunk have not only been post-processed, but also had the +// post-post-processing done that they themselves can only do once Their 8 +// neighbours have been post-processed. +bool Level::isChunkFinalised(int x, int z) { + for (int xo = -1; xo <= 1; xo++) + for (int zo = -1; zo <= 1; zo++) { + if (!isChunkPostPostProcessed(x + xo, z + zo)) return false; + } + + return true; } -int Level::getOriginalSaveVersion() -{ - return getLevelStorage()->getSaveFile()->getOriginalSaveVersion(); -} - -// 4J - determine if a chunk has been done the post-post-processing stage. This happens when *its* neighbours have each been post-processed, and does some final lighting that can -// only really be done when the post-processing has placed all possible tiles into this chunk. -bool Level::isChunkPostPostProcessed(int x, int z) -{ - if( !hasChunk(x, z) ) return false; // This will occur for non-loaded chunks, not for edge chunks - - LevelChunk *lc = getChunk(x, z); - if( lc->isEmpty() ) return true; // Since we've already eliminated non-loaded chunks, this should only occur for edge chunks. Consider those as fully processed - - return (( lc->terrainPopulated & LevelChunk::sTerrainPostPostProcessed ) == LevelChunk::sTerrainPostPostProcessed); -} - -// 4J added - returns true if a chunk is fully, fully finalised - in that it can be sent to another machine. This is the case when all 8 neighbours of this chunk -// have not only been post-processed, but also had the post-post-processing done that they themselves can only do once Their 8 neighbours have been post-processed. -bool Level::isChunkFinalised(int x, int z) -{ - for( int xo = -1; xo <= 1; xo++ ) - for( int zo = -1; zo <= 1; zo++ ) - { - if( !isChunkPostPostProcessed(x + xo, z + zo) ) return false; - } - - return true; -} - -int Level::getUnsavedChunkCount() -{ - return m_unsavedChunkCount; -} - -void Level::incrementUnsavedChunkCount() -{ - ++m_unsavedChunkCount; -} - -void Level::decrementUnsavedChunkCount() -{ - --m_unsavedChunkCount; -} - -bool Level::canCreateMore(eINSTANCEOF type, ESPAWN_TYPE spawnType) -{ - int count = 0; - int max = 0; - if(spawnType == eSpawnType_Egg) - { - switch(type) - { - case eTYPE_VILLAGER: - count = countInstanceOf( eTYPE_VILLAGER, true); - max = MobCategory::MAX_XBOX_VILLAGERS_WITH_SPAWN_EGG; - break; - case eTYPE_CHICKEN: - count = countInstanceOf( eTYPE_CHICKEN, true); - max = MobCategory::MAX_XBOX_CHICKENS_WITH_SPAWN_EGG; - break; - case eTYPE_WOLF: - count = countInstanceOf( eTYPE_WOLF, true); - max = MobCategory::MAX_XBOX_WOLVES_WITH_SPAWN_EGG; - break; - case eTYPE_MUSHROOMCOW: - count = countInstanceOf( eTYPE_MUSHROOMCOW, true); - max = MobCategory::MAX_XBOX_MUSHROOMCOWS_WITH_SPAWN_EGG; - break; - case eTYPE_SQUID: - count = countInstanceOf( eTYPE_SQUID, true); - max = MobCategory::MAX_XBOX_SQUIDS_WITH_SPAWN_EGG; - break; - case eTYPE_SNOWMAN: - count = countInstanceOf( eTYPE_SNOWMAN, true); - max = MobCategory::MAX_XBOX_SNOWMEN; - break; - case eTYPE_VILLAGERGOLEM: - count = countInstanceOf( eTYPE_VILLAGERGOLEM, true); - max = MobCategory::MAX_XBOX_IRONGOLEM; - break; - default: - if((type & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) - { - count = countInstanceOf( eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false); - max = MobCategory::MAX_XBOX_ANIMALS_WITH_SPAWN_EGG; - } - else if( (type & eTYPE_MONSTER) == eTYPE_MONSTER) - { - count = countInstanceOf( eTYPE_MONSTER, false); - max = MobCategory::MAX_XBOX_MONSTERS_WITH_SPAWN_EGG; - } - }; - } - else if(spawnType == eSpawnType_Breed) - { - switch(type) - { - case eTYPE_VILLAGER: - count = countInstanceOf( eTYPE_VILLAGER, true); - max = MobCategory::MAX_VILLAGERS_WITH_BREEDING; - break; - case eTYPE_CHICKEN: - count = countInstanceOf( eTYPE_CHICKEN, true); - max = MobCategory::MAX_XBOX_CHICKENS_WITH_BREEDING; - break; - case eTYPE_WOLF: - count = countInstanceOf( eTYPE_WOLF, true); - max = MobCategory::MAX_XBOX_WOLVES_WITH_BREEDING; - break; - case eTYPE_MUSHROOMCOW: - count = countInstanceOf( eTYPE_MUSHROOMCOW, true); - max = MobCategory::MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING; - break; - default: - if((type & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) - { - count = countInstanceOf( eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false); - max = MobCategory::MAX_XBOX_ANIMALS_WITH_BREEDING; - } - else if( (type & eTYPE_MONSTER) == eTYPE_MONSTER) - { - - } - break; - } - } - return count < max; +int Level::getUnsavedChunkCount() { return m_unsavedChunkCount; } + +void Level::incrementUnsavedChunkCount() { ++m_unsavedChunkCount; } + +void Level::decrementUnsavedChunkCount() { --m_unsavedChunkCount; } + +bool Level::canCreateMore(eINSTANCEOF type, ESPAWN_TYPE spawnType) { + int count = 0; + int max = 0; + if (spawnType == eSpawnType_Egg) { + switch (type) { + case eTYPE_VILLAGER: + count = countInstanceOf(eTYPE_VILLAGER, true); + max = MobCategory::MAX_XBOX_VILLAGERS_WITH_SPAWN_EGG; + break; + case eTYPE_CHICKEN: + count = countInstanceOf(eTYPE_CHICKEN, true); + max = MobCategory::MAX_XBOX_CHICKENS_WITH_SPAWN_EGG; + break; + case eTYPE_WOLF: + count = countInstanceOf(eTYPE_WOLF, true); + max = MobCategory::MAX_XBOX_WOLVES_WITH_SPAWN_EGG; + break; + case eTYPE_MUSHROOMCOW: + count = countInstanceOf(eTYPE_MUSHROOMCOW, true); + max = MobCategory::MAX_XBOX_MUSHROOMCOWS_WITH_SPAWN_EGG; + break; + case eTYPE_SQUID: + count = countInstanceOf(eTYPE_SQUID, true); + max = MobCategory::MAX_XBOX_SQUIDS_WITH_SPAWN_EGG; + break; + case eTYPE_SNOWMAN: + count = countInstanceOf(eTYPE_SNOWMAN, true); + max = MobCategory::MAX_XBOX_SNOWMEN; + break; + case eTYPE_VILLAGERGOLEM: + count = countInstanceOf(eTYPE_VILLAGERGOLEM, true); + max = MobCategory::MAX_XBOX_IRONGOLEM; + break; + default: + if ((type & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) { + count = + countInstanceOf(eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false); + max = MobCategory::MAX_XBOX_ANIMALS_WITH_SPAWN_EGG; + } else if ((type & eTYPE_MONSTER) == eTYPE_MONSTER) { + count = countInstanceOf(eTYPE_MONSTER, false); + max = MobCategory::MAX_XBOX_MONSTERS_WITH_SPAWN_EGG; + } + }; + } else if (spawnType == eSpawnType_Breed) { + switch (type) { + case eTYPE_VILLAGER: + count = countInstanceOf(eTYPE_VILLAGER, true); + max = MobCategory::MAX_VILLAGERS_WITH_BREEDING; + break; + case eTYPE_CHICKEN: + count = countInstanceOf(eTYPE_CHICKEN, true); + max = MobCategory::MAX_XBOX_CHICKENS_WITH_BREEDING; + break; + case eTYPE_WOLF: + count = countInstanceOf(eTYPE_WOLF, true); + max = MobCategory::MAX_XBOX_WOLVES_WITH_BREEDING; + break; + case eTYPE_MUSHROOMCOW: + count = countInstanceOf(eTYPE_MUSHROOMCOW, true); + max = MobCategory::MAX_XBOX_MUSHROOMCOWS_WITH_BREEDING; + break; + default: + if ((type & eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) == + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK) { + count = + countInstanceOf(eTYPE_ANIMALS_SPAWN_LIMIT_CHECK, false); + max = MobCategory::MAX_XBOX_ANIMALS_WITH_BREEDING; + } else if ((type & eTYPE_MONSTER) == eTYPE_MONSTER) { + } + break; + } + } + return count < max; } diff --git a/Minecraft.World/Level/Level.h b/Minecraft.World/Level/Level.h index f6b60ec6f..4a99c5c8b 100644 --- a/Minecraft.World/Level/Level.h +++ b/Minecraft.World/Level/Level.h @@ -17,9 +17,10 @@ #include "../../Minecraft.Client/Platform/PSVita/PSVitaExtras/CustomSet.h" #endif -// 4J Stu - This value should be big enough that we don't get any crashes causes by memory overwrites, -// however it does seem way too large for what is actually needed. Needs further investigation -#define LEVEL_CHUNKS_TO_UPDATE_MAX (19*19*8) +// 4J Stu - This value should be big enough that we don't get any crashes causes +// by memory overwrites, however it does seem way too large for what is actually +// needed. Needs further investigation +#define LEVEL_CHUNKS_TO_UPDATE_MAX (19 * 19 * 8) class Vec3; class ChunkSource; @@ -45,501 +46,601 @@ class Biome; class Villages; class VillageSiege; -class Level : public LevelSource -{ +class Level : public LevelSource { public: - static const int MAX_TICK_TILES_PER_TICK = 1000; - - // 4J Added - static const int MAX_GRASS_TICKS = 100; - static const int MAX_LAVA_TICKS = 100; + static const int MAX_TICK_TILES_PER_TICK = 1000; + // 4J Added + static const int MAX_GRASS_TICKS = 100; + static const int MAX_LAVA_TICKS = 100; public: - static const int MAX_XBOX_BOATS = 40; // Max number of boats - static const int MAX_CONSOLE_MINECARTS = 40; - static const int MAX_DISPENSABLE_FIREBALLS = 200; - static const int MAX_DISPENSABLE_PROJECTILES = 300; + static const int MAX_XBOX_BOATS = 40; // Max number of boats + static const int MAX_CONSOLE_MINECARTS = 40; + static const int MAX_DISPENSABLE_FIREBALLS = 200; + static const int MAX_DISPENSABLE_PROJECTILES = 300; - static const int MAX_LEVEL_SIZE = 30000000; - static const int maxMovementHeight = 512; // 4J added + static const int MAX_LEVEL_SIZE = 30000000; + static const int maxMovementHeight = 512; // 4J added - static const int minBuildHeight = 0; // 4J - brought forward from 1.2.3 - static const int maxBuildHeight = 256; // 4J - brought forward from 1.2.3 - static const int genDepthBits = 7; - static const int genDepthBitsPlusFour = genDepthBits + 4; - static const int genDepth = 1 << genDepthBits; - static const int genDepthMinusOne = genDepth - 1; - static const int constSeaLevel = genDepth / 2 - 1; + static const int minBuildHeight = 0; // 4J - brought forward from 1.2.3 + static const int maxBuildHeight = 256; // 4J - brought forward from 1.2.3 + static const int genDepthBits = 7; + static const int genDepthBitsPlusFour = genDepthBits + 4; + static const int genDepth = 1 << genDepthBits; + static const int genDepthMinusOne = genDepth - 1; + static const int constSeaLevel = genDepth / 2 - 1; - static const int CHUNK_TILE_COUNT = maxBuildHeight * 16 * 16; - static const int HALF_CHUNK_TILE_COUNT = CHUNK_TILE_COUNT/2; - static const int COMPRESSED_CHUNK_SECTION_HEIGHT = 128; - static const int COMPRESSED_CHUNK_SECTION_TILES = COMPRESSED_CHUNK_SECTION_HEIGHT * 16 * 16; // 4J Stu - Fixed size + static const int CHUNK_TILE_COUNT = maxBuildHeight * 16 * 16; + static const int HALF_CHUNK_TILE_COUNT = CHUNK_TILE_COUNT / 2; + static const int COMPRESSED_CHUNK_SECTION_HEIGHT = 128; + static const int COMPRESSED_CHUNK_SECTION_TILES = + COMPRESSED_CHUNK_SECTION_HEIGHT * 16 * 16; // 4J Stu - Fixed size - int seaLevel; + int seaLevel; - // 4J - added, making instaTick flag use TLS so we can set it in the chunk rebuilding thread without upsetting the main game thread + // 4J - added, making instaTick flag use TLS so we can set it in the chunk + // rebuilding thread without upsetting the main game thread #if defined(_WIN32) - static DWORD tlsIdx; - static DWORD tlsIdxLightCache; + static DWORD tlsIdx; + static DWORD tlsIdxLightCache; #else - static pthread_key_t tlsIdx; - static pthread_key_t tlsIdxLightCache; + static pthread_key_t tlsIdx; + static pthread_key_t tlsIdxLightCache; #endif - static void enableLightingCache(); - static void destroyLightingCache(); - static bool getCacheTestEnabled(); - static bool getInstaTick(); - static void setInstaTick(bool enable); -// bool instaTick; // 4J - removed + static void enableLightingCache(); + static void destroyLightingCache(); + static bool getCacheTestEnabled(); + static bool getInstaTick(); + static void setInstaTick(bool enable); + // bool instaTick; // 4J - removed - static const int MAX_BRIGHTNESS = 15; - static const int TICKS_PER_DAY = 20 * 60 * 20; // ORG:20*60*20 + static const int MAX_BRIGHTNESS = 15; + static const int TICKS_PER_DAY = 20 * 60 * 20; // ORG:20*60*20 public: - CRITICAL_SECTION m_entitiesCS; // 4J added + CRITICAL_SECTION m_entitiesCS; // 4J added - std::vector > entities; + std::vector > entities; protected: - std::vector > entitiesToRemove; + std::vector > entitiesToRemove; + public: - bool hasEntitiesToRemove(); // 4J added - bool m_bDisableAddNewTileEntities; // 4J Added - CRITICAL_SECTION m_tileEntityListCS; // 4J added - std::vector > tileEntityList; -private: - std::vector > pendingTileEntities; - std::vector > tileEntitiesToUnload; - bool updatingTileEntities; -public: - std::vector > players; - std::vector > globalEntities; + bool hasEntitiesToRemove(); // 4J added + bool m_bDisableAddNewTileEntities; // 4J Added + CRITICAL_SECTION m_tileEntityListCS; // 4J added + std::vector > tileEntityList; private: - int cloudColor; + std::vector > pendingTileEntities; + std::vector > tileEntitiesToUnload; + bool updatingTileEntities; public: - int skyDarken; - -protected: - int randValue; - -public: - int addend; - -protected: - float oRainLevel, rainLevel; - float oThunderLevel, thunderLevel; - int lightningTime; - -public: - int lightningBoltTime; - bool noNeighborUpdate; - int difficulty; - Random *random; - bool isNew; - Dimension *dimension; - -protected: - std::vector listeners; - -public: - ChunkSource *chunkSource; // 4J - changed to public -protected: - // This is the only std::shared_ptr ref to levelStorage - we need to keep this as long as at least one Level references it, - // to be able to cope with moving from dimension to dimension where the Level(Level *level, Dimension *dimension) ctor is used - std::shared_ptr levelStorage; - - LevelData *levelData; - -public: - bool isFindingSpawn; - SavedDataStorage *savedDataStorage; - std::shared_ptr villages; - VillageSiege *villageSiege; - -public: - Biome *getBiome(int x, int z); // 4J - brought forward from 1.2.3 - virtual BiomeSource *getBiomeSource(); + std::vector > players; + std::vector > globalEntities; private: - - // 4J Stu - Added these ctors to handle init of member variables - void _init(); - void _init(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings, Dimension *fixedDimension, bool doCreateChunkSource = true); + int cloudColor; public: - Level(std::shared_ptrlevelStorage, const std::wstring& name, Dimension *dimension, LevelSettings *levelSettings, bool doCreateChunkSource = true); - Level(Level *level, Dimension *dimension); - Level(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings); - Level(std::shared_ptrlevelStorage, const std::wstring& levelName, LevelSettings *levelSettings, Dimension *fixedDimension, bool doCreateChunkSource = true); - - virtual ~Level(); + int skyDarken; protected: - virtual ChunkSource *createChunkSource() = 0; - - virtual void initializeLevel(LevelSettings *settings); + int randValue; public: - virtual bool AllPlayersAreSleeping() { return false; } // 4J Added + int addend; - virtual void validateSpawn(); - int getTopTile(int x, int z); +protected: + float oRainLevel, rainLevel; + float oThunderLevel, thunderLevel; + int lightningTime; public: - virtual int getTile(int x, int y, int z); - virtual int getTileLightBlock(int x, int y, int z); - bool isEmptyTile(int x, int y, int z); - virtual bool isEntityTile(int x, int y, int z); - int getTileRenderShape(int x, int y, int z); - bool hasChunkAt(int x, int y, int z); - bool hasChunksAt(int x, int y, int z, int r); - bool hasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1); - bool reallyHasChunkAt(int x, int y, int z); // 4J added - bool reallyHasChunksAt(int x, int y, int z, int r); // 4J added - bool reallyHasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1); // 4J added + int lightningBoltTime; + bool noNeighborUpdate; + int difficulty; + Random* random; + bool isNew; + Dimension* dimension; + +protected: + std::vector listeners; public: - bool hasChunk(int x, int z); - bool reallyHasChunk(int x, int z ); // 4J added + ChunkSource* chunkSource; // 4J - changed to public +protected: + // This is the only std::shared_ptr ref to levelStorage - we need to keep + // this as long as at least one Level references it, to be able to cope with + // moving from dimension to dimension where the Level(Level *level, + // Dimension *dimension) ctor is used + std::shared_ptr levelStorage; + + LevelData* levelData; public: - LevelChunk *getChunkAt(int x, int z); - LevelChunk *getChunk(int x, int z); - virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data); - virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data, bool informClients); - virtual bool setTileNoUpdate(int x, int y, int z, int tile); - bool setTileNoUpdateNoLightCheck(int x, int y, int z, int tile); // 4J added - Material *getMaterial(int x, int y, int z); - virtual int getData(int x, int y, int z); - void setData(int x, int y, int z, int data, bool forceUpdate=false); // 4J added forceUpdate - virtual bool setDataNoUpdate(int x, int y, int z, int data); - bool setTile(int x, int y, int z, int tile); - bool setTileAndData(int x, int y, int z, int tile, int data); - void sendTileUpdated(int x, int y, int z); + bool isFindingSpawn; + SavedDataStorage* savedDataStorage; + std::shared_ptr villages; + VillageSiege* villageSiege; public: - virtual void tileUpdated(int x, int y, int z, int tile); - void lightColumnChanged(int x, int z, int y0, int y1); - void setTileDirty(int x, int y, int z); - void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1); - void swap(int x1, int y1, int z1, int x2, int y2, int z2); - void updateNeighborsAt(int x, int y, int z, int tile); + Biome* getBiome(int x, int z); // 4J - brought forward from 1.2.3 + virtual BiomeSource* getBiomeSource(); private: - void neighborChanged(int x, int y, int z, int type); + // 4J Stu - Added these ctors to handle init of member variables + void _init(); + void _init(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings, + Dimension* fixedDimension, bool doCreateChunkSource = true); public: - bool canSeeSky(int x, int y, int z); - int getDaytimeRawBrightness(int x, int y, int z); - int getRawBrightness(int x, int y, int z); - int getRawBrightness(int x, int y, int z, bool propagate); - bool isSkyLit(int x, int y, int z); - int getHeightmap(int x, int z); - void updateLightIfOtherThan(LightLayer::variety layer, int x, int y, int z, int expected); - int getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, int tileId); // 4J added tileId - void getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z); // 4J added - int getBrightness(LightLayer::variety layer, int x, int y, int z); - void setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness, bool noUpdateOnClient=false); // 4J added noUpdateOnClient - void setBrightnessNoUpdateOnClient(LightLayer::variety layer, int x, int y, int z, int brightness); // 4J added + Level(std::shared_ptr levelStorage, const std::wstring& name, + Dimension* dimension, LevelSettings* levelSettings, + bool doCreateChunkSource = true); + Level(Level* level, Dimension* dimension); + Level(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings); + Level(std::shared_ptr levelStorage, + const std::wstring& levelName, LevelSettings* levelSettings, + Dimension* fixedDimension, bool doCreateChunkSource = true); + + virtual ~Level(); + +protected: + virtual ChunkSource* createChunkSource() = 0; + + virtual void initializeLevel(LevelSettings* settings); + +public: + virtual bool AllPlayersAreSleeping() { return false; } // 4J Added + + virtual void validateSpawn(); + int getTopTile(int x, int z); + +public: + virtual int getTile(int x, int y, int z); + virtual int getTileLightBlock(int x, int y, int z); + bool isEmptyTile(int x, int y, int z); + virtual bool isEntityTile(int x, int y, int z); + int getTileRenderShape(int x, int y, int z); + bool hasChunkAt(int x, int y, int z); + bool hasChunksAt(int x, int y, int z, int r); + bool hasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1); + bool reallyHasChunkAt(int x, int y, int z); // 4J added + bool reallyHasChunksAt(int x, int y, int z, int r); // 4J added + bool reallyHasChunksAt(int x0, int y0, int z0, int x1, int y1, + int z1); // 4J added + +public: + bool hasChunk(int x, int z); + bool reallyHasChunk(int x, int z); // 4J added + +public: + LevelChunk* getChunkAt(int x, int z); + LevelChunk* getChunk(int x, int z); + virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, + int data); + virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data, + bool informClients); + virtual bool setTileNoUpdate(int x, int y, int z, int tile); + bool setTileNoUpdateNoLightCheck(int x, int y, int z, + int tile); // 4J added + Material* getMaterial(int x, int y, int z); + virtual int getData(int x, int y, int z); + void setData(int x, int y, int z, int data, + bool forceUpdate = false); // 4J added forceUpdate + virtual bool setDataNoUpdate(int x, int y, int z, int data); + bool setTile(int x, int y, int z, int tile); + bool setTileAndData(int x, int y, int z, int tile, int data); + void sendTileUpdated(int x, int y, int z); + +public: + virtual void tileUpdated(int x, int y, int z, int tile); + void lightColumnChanged(int x, int z, int y0, int y1); + void setTileDirty(int x, int y, int z); + void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1); + void swap(int x1, int y1, int z1, int x2, int y2, int z2); + void updateNeighborsAt(int x, int y, int z, int tile); + +private: + void neighborChanged(int x, int y, int z, int type); + +public: + bool canSeeSky(int x, int y, int z); + int getDaytimeRawBrightness(int x, int y, int z); + int getRawBrightness(int x, int y, int z); + int getRawBrightness(int x, int y, int z, bool propagate); + bool isSkyLit(int x, int y, int z); + int getHeightmap(int x, int z); + void updateLightIfOtherThan(LightLayer::variety layer, int x, int y, int z, + int expected); + int getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, + int tileId); // 4J added tileId + void getNeighbourBrightnesses(int* brightnesses, LightLayer::variety layer, + int x, int y, int z); // 4J added + int getBrightness(LightLayer::variety layer, int x, int y, int z); + void setBrightness( + LightLayer::variety layer, int x, int y, int z, int brightness, + bool noUpdateOnClient = false); // 4J added noUpdateOnClient + void setBrightnessNoUpdateOnClient(LightLayer::variety layer, int x, int y, + int z, int brightness); // 4J added #ifdef _LARGE_WORLDS - typedef __uint64 lightCache_t; + typedef __uint64 lightCache_t; #else - typedef unsigned int lightCache_t; + typedef unsigned int lightCache_t; #endif - inline void setBrightnessCached(lightCache_t *cache, __uint64 *cacheUse, LightLayer::variety layer, int x, int y, int z, int brightness); - inline int getBrightnessCached(lightCache_t *cache, LightLayer::variety layer, int x, int y, int z); - inline int getEmissionCached(lightCache_t *cache, int ct, int x, int y, int z); - inline int getBlockingCached(lightCache_t *cache, LightLayer::variety layer, int *ct, int x, int y, int z); - void initCache(lightCache_t *cache); - void flushCache(lightCache_t *cache, __uint64 cacheUse, LightLayer::variety layer); + inline void setBrightnessCached(lightCache_t* cache, __uint64* cacheUse, + LightLayer::variety layer, int x, int y, + int z, int brightness); + inline int getBrightnessCached(lightCache_t* cache, + LightLayer::variety layer, int x, int y, + int z); + inline int getEmissionCached(lightCache_t* cache, int ct, int x, int y, + int z); + inline int getBlockingCached(lightCache_t* cache, LightLayer::variety layer, + int* ct, int x, int y, int z); + void initCache(lightCache_t* cache); + void flushCache(lightCache_t* cache, __uint64 cacheUse, + LightLayer::variety layer); - bool cachewritten; - static const int LIGHTING_SHIFT = 24; - static const int BLOCKING_SHIFT = 20; - static const int EMISSION_SHIFT = 16; + bool cachewritten; + static const int LIGHTING_SHIFT = 24; + static const int BLOCKING_SHIFT = 20; + static const int EMISSION_SHIFT = 16; #ifdef _LARGE_WORLDS - static const __int64 LIGHTING_WRITEBACK = 0x80000000LL; - static const __int64 EMISSION_VALID = 0x40000000LL; - static const __int64 BLOCKING_VALID = 0x20000000LL; - static const __int64 LIGHTING_VALID = 0x10000000LL; - static const lightCache_t POSITION_MASK = 0xffffffff0000ffffLL; + static const __int64 LIGHTING_WRITEBACK = 0x80000000LL; + static const __int64 EMISSION_VALID = 0x40000000LL; + static const __int64 BLOCKING_VALID = 0x20000000LL; + static const __int64 LIGHTING_VALID = 0x10000000LL; + static const lightCache_t POSITION_MASK = 0xffffffff0000ffffLL; #else - static const int LIGHTING_WRITEBACK = 0x80000000; - static const int EMISSION_VALID = 0x40000000; - static const int BLOCKING_VALID = 0x20000000; - static const int LIGHTING_VALID = 0x10000000; - static const lightCache_t POSITION_MASK = 0x0000ffff; + static const int LIGHTING_WRITEBACK = 0x80000000; + static const int EMISSION_VALID = 0x40000000; + static const int BLOCKING_VALID = 0x20000000; + static const int LIGHTING_VALID = 0x10000000; + static const lightCache_t POSITION_MASK = 0x0000ffff; #endif - int cacheminx, cachemaxx, cacheminy, cachemaxy, cacheminz, cachemaxz; - void setTileBrightnessChanged(int x, int y, int z); - virtual int getLightColor(int x, int y, int z, int emitt, int tileId = -1); // 4J - brought forward from 1.8.2 - virtual float getBrightness(int x, int y, int z, int emitt); - virtual float getBrightness(int x, int y, int z); - bool isDay(); - HitResult *clip(Vec3 *a, Vec3 *b); - HitResult *clip(Vec3 *a, Vec3 *b, bool liquid); - HitResult *clip(Vec3 *a, Vec3 *b, bool liquid, bool solidOnly); + int cacheminx, cachemaxx, cacheminy, cachemaxy, cacheminz, cachemaxz; + void setTileBrightnessChanged(int x, int y, int z); + virtual int getLightColor( + int x, int y, int z, int emitt, + int tileId = -1); // 4J - brought forward from 1.8.2 + virtual float getBrightness(int x, int y, int z, int emitt); + virtual float getBrightness(int x, int y, int z); + bool isDay(); + HitResult* clip(Vec3* a, Vec3* b); + HitResult* clip(Vec3* a, Vec3* b, bool liquid); + HitResult* clip(Vec3* a, Vec3* b, bool liquid, bool solidOnly); - virtual void playSound(std::shared_ptr entity, int iSound, float volume, float pitch); - virtual void playSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist=16.0f); + virtual void playSound(std::shared_ptr entity, int iSound, + float volume, float pitch); + virtual void playSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist = 16.0f); - virtual void playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist=16.0f); + virtual void playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist = 16.0f); - void playStreamingMusic(const std::wstring& name, int x, int y, int z); - void playMusic(double x, double y, double z, const std::wstring& string, float volume); - // 4J removed - void addParticle(const std::wstring& id, double x, double y, double z, double xd, double yd, double zd); - void addParticle(ePARTICLE_TYPE id, double x, double y, double z, double xd, double yd, double zd); // 4J added - virtual bool addGlobalEntity(std::shared_ptr e); - virtual bool addEntity(std::shared_ptr e); + void playStreamingMusic(const std::wstring& name, int x, int y, int z); + void playMusic(double x, double y, double z, const std::wstring& string, + float volume); + // 4J removed - void addParticle(const std::wstring& id, double x, double y, + // double z, double xd, double yd, double zd); + void addParticle(ePARTICLE_TYPE id, double x, double y, double z, double xd, + double yd, double zd); // 4J added + virtual bool addGlobalEntity(std::shared_ptr e); + virtual bool addEntity(std::shared_ptr e); protected: - virtual void entityAdded(std::shared_ptr e); - virtual void entityRemoved(std::shared_ptr e); - virtual void playerRemoved(std::shared_ptr e); // 4J added + virtual void entityAdded(std::shared_ptr e); + virtual void entityRemoved(std::shared_ptr e); + virtual void playerRemoved(std::shared_ptr e); // 4J added public: - virtual void removeEntity(std::shared_ptr e); - void removeEntityImmediately(std::shared_ptr e); - void addListener(LevelListener *listener); - void removeListener(LevelListener *listener); + virtual void removeEntity(std::shared_ptr e); + void removeEntityImmediately(std::shared_ptr e); + void addListener(LevelListener* listener); + void removeListener(LevelListener* listener); private: - AABBList boxes; + AABBList boxes; public: - AABBList *getCubes(std::shared_ptr source, AABB *box, bool noEntities=false, bool blockAtEdge=false); // 4J - added noEntities & blockAtEdge parameters - AABBList *getTileCubes(AABB *box, bool blockAtEdge); // 4J Stu - Brought forward from 12w36 to fix #46282 - TU5: Gameplay: Exiting the minecart in a tight corridor damages the player - int getOldSkyDarken(float a); // 4J - change brought forward from 1.8.2 - float getSkyDarken(float a); // 4J - change brought forward from 1.8.2 - Vec3 *getSkyColor(std::shared_ptr source, float a); - float getTimeOfDay(float a); - int getMoonPhase(float a); - float getSunAngle(float a); - Vec3 *getCloudColor(float a); - Vec3 *getFogColor(float a); - int getTopRainBlock(int x, int z); - int getTopSolidBlock(int x, int z); - bool biomeHasRain(int x, int z); // 4J added - bool biomeHasSnow(int x, int z); // 4J added - int getLightDepth(int x, int z); - float getStarBrightness(float a); - virtual void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); - virtual void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); - virtual void tickEntities(); - void addAllPendingTileEntities(std::vector< std::shared_ptr >& entities); - void tick(std::shared_ptr e); - virtual void tick(std::shared_ptr e, bool actual); - bool isUnobstructed(AABB *aabb); - bool isUnobstructed(AABB *aabb, std::shared_ptr ignore); - bool containsAnyBlocks(AABB *box); - bool containsAnyLiquid(AABB *box); - bool containsAnyLiquid_NoLoad(AABB *box); // 4J added - bool containsFireTile(AABB *box); - bool checkAndHandleWater(AABB *box, Material *material, std::shared_ptr e); - bool containsMaterial(AABB *box, Material *material); - bool containsLiquid(AABB *box, Material *material); - // 4J Stu - destroyBlocks param brought forward as part of fix for tnt cannons - std::shared_ptr explode(std::shared_ptr source, double x, double y, double z, float r, bool destroyBlocks); - virtual std::shared_ptr explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks); - float getSeenPercent(Vec3 *center, AABB *bb); - bool extinguishFire(std::shared_ptr player, int x, int y, int z, int face); - std::wstring gatherStats(); - std::wstring gatherChunkSourceStats(); - virtual std::shared_ptr getTileEntity(int x, int y, int z); - void setTileEntity(int x, int y, int z, std::shared_ptr tileEntity); - void removeTileEntity(int x, int y, int z); - void markForRemoval(std::shared_ptr entity); - virtual bool isSolidRenderTile(int x, int y, int z); - virtual bool isSolidBlockingTile(int x, int y, int z); - bool isSolidBlockingTileInLoadedChunk(int x, int y, int z, bool valueIfNotLoaded); - virtual bool isTopSolidBlocking(int x, int y, int z); // 4J - brought forward from 1.3.2 + AABBList* getCubes( + std::shared_ptr source, AABB* box, bool noEntities = false, + bool blockAtEdge = + false); // 4J - added noEntities & blockAtEdge parameters + AABBList* getTileCubes( + AABB* box, + bool blockAtEdge); // 4J Stu - Brought forward from 12w36 to fix #46282 + // - TU5: Gameplay: Exiting the minecart in a tight + // corridor damages the player + int getOldSkyDarken(float a); // 4J - change brought forward from 1.8.2 + float getSkyDarken(float a); // 4J - change brought forward from 1.8.2 + Vec3* getSkyColor(std::shared_ptr source, float a); + float getTimeOfDay(float a); + int getMoonPhase(float a); + float getSunAngle(float a); + Vec3* getCloudColor(float a); + Vec3* getFogColor(float a); + int getTopRainBlock(int x, int z); + int getTopSolidBlock(int x, int z); + bool biomeHasRain(int x, int z); // 4J added + bool biomeHasSnow(int x, int z); // 4J added + int getLightDepth(int x, int z); + float getStarBrightness(float a); + virtual void addToTickNextTick(int x, int y, int z, int tileId, + int tickDelay); + virtual void forceAddTileTick(int x, int y, int z, int tileId, + int tickDelay); + virtual void tickEntities(); + void addAllPendingTileEntities( + std::vector >& entities); + void tick(std::shared_ptr e); + virtual void tick(std::shared_ptr e, bool actual); + bool isUnobstructed(AABB* aabb); + bool isUnobstructed(AABB* aabb, std::shared_ptr ignore); + bool containsAnyBlocks(AABB* box); + bool containsAnyLiquid(AABB* box); + bool containsAnyLiquid_NoLoad(AABB* box); // 4J added + bool containsFireTile(AABB* box); + bool checkAndHandleWater(AABB* box, Material* material, + std::shared_ptr e); + bool containsMaterial(AABB* box, Material* material); + bool containsLiquid(AABB* box, Material* material); + // 4J Stu - destroyBlocks param brought forward as part of fix for tnt + // cannons + std::shared_ptr explode(std::shared_ptr source, double x, + double y, double z, float r, + bool destroyBlocks); + virtual std::shared_ptr explode(std::shared_ptr source, + double x, double y, double z, + float r, bool fire, + bool destroyBlocks); + float getSeenPercent(Vec3* center, AABB* bb); + bool extinguishFire(std::shared_ptr player, int x, int y, int z, + int face); + std::wstring gatherStats(); + std::wstring gatherChunkSourceStats(); + virtual std::shared_ptr getTileEntity(int x, int y, int z); + void setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity); + void removeTileEntity(int x, int y, int z); + void markForRemoval(std::shared_ptr entity); + virtual bool isSolidRenderTile(int x, int y, int z); + virtual bool isSolidBlockingTile(int x, int y, int z); + bool isSolidBlockingTileInLoadedChunk(int x, int y, int z, + bool valueIfNotLoaded); + virtual bool isTopSolidBlocking(int x, int y, + int z); // 4J - brought forward from 1.3.2 protected: - bool spawnEnemies; - bool spawnFriendlies; + bool spawnEnemies; + bool spawnFriendlies; public: - // int xxo, yyo, zzo; + // int xxo, yyo, zzo; - void updateSkyBrightness(); - void setSpawnSettings(bool spawnEnemies, bool spawnFriendlies); - virtual void tick(); + void updateSkyBrightness(); + void setSpawnSettings(bool spawnEnemies, bool spawnFriendlies); + virtual void tick(); private: - void prepareWeather(); + void prepareWeather(); protected: - virtual void tickWeather(); + virtual void tickWeather(); private: - void stopWeather(); + void stopWeather(); public: - void toggleDownfall(); + void toggleDownfall(); protected: #ifdef __PSVITA__ - // AP - See CustomSet.h for an explanation of this - CustomSet chunksToPoll; + // AP - See CustomSet.h for an explanation of this + CustomSet chunksToPoll; #else - std::unordered_set chunksToPoll; + std::unordered_set chunksToPoll; #endif private: - int delayUntilNextMoodSound; - static const int CHUNK_POLL_RANGE = 9; + int delayUntilNextMoodSound; + static const int CHUNK_POLL_RANGE = 9; static const int CHUNK_TILE_TICK_COUNT = 80; - static const int CHUNK_SECTION_TILE_TICK_COUNT = (CHUNK_TILE_TICK_COUNT / 8) + 1; + static const int CHUNK_SECTION_TILE_TICK_COUNT = + (CHUNK_TILE_TICK_COUNT / 8) + 1; protected: - virtual void buildAndPrepareChunksToPoll(); - virtual void tickClientSideTiles(int xo, int zo, LevelChunk *lc); - virtual void tickTiles(); + virtual void buildAndPrepareChunksToPoll(); + virtual void tickClientSideTiles(int xo, int zo, LevelChunk* lc); + virtual void tickTiles(); - // 4J - snow & ice checks brought forward from 1.2.3 + // 4J - snow & ice checks brought forward from 1.2.3 public: - bool shouldFreezeIgnoreNeighbors(int x, int y, int z); - bool shouldFreeze(int x, int y, int z); - bool shouldFreeze(int x, int y, int z, bool checkNeighbors); - bool shouldSnow(int x, int y, int z); - void checkLight(int x, int y, int z, bool force = false, bool rootOnlyEmissive = false); // 4J added force, rootOnlySource parameters + bool shouldFreezeIgnoreNeighbors(int x, int y, int z); + bool shouldFreeze(int x, int y, int z); + bool shouldFreeze(int x, int y, int z, bool checkNeighbors); + bool shouldSnow(int x, int y, int z); + void checkLight(int x, int y, int z, bool force = false, + bool rootOnlyEmissive = + false); // 4J added force, rootOnlySource parameters private: - int *toCheckLevel; - int getExpectedSkyColor(lightCache_t *cache, int oc, int x, int y , int z, int ct, int block); - int getExpectedBlockColor(lightCache_t *cache, int oc, int x, int y, int z, int ct, int block, bool propagatedOnly); // 4J added parameter + int* toCheckLevel; + int getExpectedSkyColor(lightCache_t* cache, int oc, int x, int y, int z, + int ct, int block); + int getExpectedBlockColor(lightCache_t* cache, int oc, int x, int y, int z, + int ct, int block, + bool propagatedOnly); // 4J added parameter public: - void checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool force = false, bool rootOnlyEmissive = false); // 4J added force, rootOnlySource parameters + void checkLight(LightLayer::variety layer, int xc, int yc, int zc, + bool force = false, + bool rootOnlyEmissive = + false); // 4J added force, rootOnlySource parameters public: - virtual bool tickPendingTicks(bool force); - virtual std::vector *fetchTicksInChunk(LevelChunk *chunk, bool remove); + virtual bool tickPendingTicks(bool force); + virtual std::vector* fetchTicksInChunk(LevelChunk* chunk, + bool remove); private: - std::vector > es; + std::vector > es; public: - bool isClientSide; + bool isClientSide; - std::vector > *getEntities(std::shared_ptr except, AABB *bb); - std::vector > *getEntitiesOfClass(const std::type_info& baseClass, AABB *bb); - std::shared_ptr getClosestEntityOfClass(const std::type_info& baseClass, AABB *bb, std::shared_ptr source); - std::vector > getAllEntities(); - void tileEntityChanged(int x, int y, int z, std::shared_ptr te); -// unsigned int countInstanceOf(BaseObject::Class *clas); - unsigned int countInstanceOf(eINSTANCEOF clas, bool singleType, unsigned int *protectedCount = NULL, unsigned int *couldWanderCount = NULL); // 4J added - unsigned int countInstanceOfInRange(eINSTANCEOF clas, bool singleType, int range, int x, int y, int z); // 4J Added - void addEntities(std::vector > *list); - virtual void removeEntities(std::vector > *list); - bool mayPlace(int tileId, int x, int y, int z, bool ignoreEntities, int face, std::shared_ptr ignoreEntity); - int getSeaLevel(); - Path *findPath(std::shared_ptr from, std::shared_ptr to, float maxDist, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat); - Path *findPath(std::shared_ptr from, int xBest, int yBest, int zBest, float maxDist, bool canPassDoors, bool canOpenDoors, bool avoidWater, bool canFloat); - bool getDirectSignal(int x, int y, int z, int dir); - bool hasDirectSignal(int x, int y, int z); - bool getSignal(int x, int y, int z, int dir); - bool hasNeighborSignal(int x, int y, int z); - // 4J Added maxYDist param - std::shared_ptr getNearestPlayer(std::shared_ptr source, double maxDist, double maxYDist = -1); - std::shared_ptr getNearestPlayer(double x, double y, double z, double maxDist, double maxYDist = -1); - std::shared_ptr getNearestPlayer(double x, double z, double maxDist); - std::shared_ptr getNearestAttackablePlayer(std::shared_ptr source, double maxDist); - std::shared_ptr getNearestAttackablePlayer(double x, double y, double z, double maxDist); + std::vector >* getEntities( + std::shared_ptr except, AABB* bb); + std::vector >* getEntitiesOfClass( + const std::type_info& baseClass, AABB* bb); + std::shared_ptr getClosestEntityOfClass( + const std::type_info& baseClass, AABB* bb, + std::shared_ptr source); + std::vector > getAllEntities(); + void tileEntityChanged(int x, int y, int z, std::shared_ptr te); + // unsigned int countInstanceOf(BaseObject::Class *clas); + unsigned int countInstanceOf( + eINSTANCEOF clas, bool singleType, unsigned int* protectedCount = NULL, + unsigned int* couldWanderCount = NULL); // 4J added + unsigned int countInstanceOfInRange(eINSTANCEOF clas, bool singleType, + int range, int x, int y, + int z); // 4J Added + void addEntities(std::vector >* list); + virtual void removeEntities(std::vector >* list); + bool mayPlace(int tileId, int x, int y, int z, bool ignoreEntities, + int face, std::shared_ptr ignoreEntity); + int getSeaLevel(); + Path* findPath(std::shared_ptr from, std::shared_ptr to, + float maxDist, bool canPassDoors, bool canOpenDoors, + bool avoidWater, bool canFloat); + Path* findPath(std::shared_ptr from, int xBest, int yBest, + int zBest, float maxDist, bool canPassDoors, + bool canOpenDoors, bool avoidWater, bool canFloat); + bool getDirectSignal(int x, int y, int z, int dir); + bool hasDirectSignal(int x, int y, int z); + bool getSignal(int x, int y, int z, int dir); + bool hasNeighborSignal(int x, int y, int z); + // 4J Added maxYDist param + std::shared_ptr getNearestPlayer(std::shared_ptr source, + double maxDist, + double maxYDist = -1); + std::shared_ptr getNearestPlayer(double x, double y, double z, + double maxDist, + double maxYDist = -1); + std::shared_ptr getNearestPlayer(double x, double z, + double maxDist); + std::shared_ptr getNearestAttackablePlayer( + std::shared_ptr source, double maxDist); + std::shared_ptr getNearestAttackablePlayer(double x, double y, + double z, + double maxDist); - std::shared_ptr getPlayerByName(const std::wstring& name); - std::shared_ptr getPlayerByUUID(const std::wstring& name); // 4J Added - byteArray getBlocksAndData(int x, int y, int z, int xs, int ys, int zs, bool includeLighting = true); - void setBlocksAndData(int x, int y, int z, int xs, int ys, int zs, byteArray data, bool includeLighting = true); - virtual void disconnect(bool sendDisconnect = true); - void checkSession(); - void setTime(__int64 time); - void setOverrideTimeOfDay(__int64 time); // 4J Added so we can override timeOfDay without changing tick time - __int64 getSeed(); - __int64 getTime(); - Pos *getSharedSpawnPos(); - void setSpawnPos(int x, int y, int z); - void setSpawnPos(Pos *spawnPos); - void ensureAdded(std::shared_ptr entity); - virtual bool mayInteract(std::shared_ptr player, int xt, int yt, int zt, int content); - virtual void broadcastEntityEvent(std::shared_ptr e, uint8_t event); - ChunkSource *getChunkSource(); - virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1); - LevelStorage *getLevelStorage(); - LevelData *getLevelData(); - virtual void updateSleepingPlayerList(); - bool useNewSeaLevel(); // 4J added - bool getHasBeenInCreative(); // 4J Added - bool isGenerateMapFeatures(); // 4J Added - int getSaveVersion(); - int getOriginalSaveVersion(); - float getThunderLevel(float a); - float getRainLevel(float a); - void setRainLevel(float rainLevel); - bool isThundering(); - bool isRaining(); - bool isRainingAt(int x, int y, int z); - bool isHumidAt(int x, int y, int z); - void setSavedData(const std::wstring& id, std::shared_ptr data); - std::shared_ptr getSavedData(const std::type_info& clazz, const std::wstring& id); - int getFreeAuxValueFor(const std::wstring& id); - void levelEvent(int type, int x, int y, int z, int data); - void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data); - int getMaxBuildHeight(); - int getHeight(); - Random *getRandomFor(int x, int z, int blend); - bool updateLights(); - virtual bool isAllEmpty(); - double getHorizonHeight() ; - void destroyTileProgress(int id, int x, int y, int z, int progress); - TilePos *findNearestMapFeature(const std::wstring& featureName, int x, int y, int z); + std::shared_ptr getPlayerByName(const std::wstring& name); + std::shared_ptr getPlayerByUUID( + const std::wstring& name); // 4J Added + byteArray getBlocksAndData(int x, int y, int z, int xs, int ys, int zs, + bool includeLighting = true); + void setBlocksAndData(int x, int y, int z, int xs, int ys, int zs, + byteArray data, bool includeLighting = true); + virtual void disconnect(bool sendDisconnect = true); + void checkSession(); + void setTime(__int64 time); + void setOverrideTimeOfDay( + __int64 time); // 4J Added so we can override timeOfDay without + // changing tick time + __int64 getSeed(); + __int64 getTime(); + Pos* getSharedSpawnPos(); + void setSpawnPos(int x, int y, int z); + void setSpawnPos(Pos* spawnPos); + void ensureAdded(std::shared_ptr entity); + virtual bool mayInteract(std::shared_ptr player, int xt, int yt, + int zt, int content); + virtual void broadcastEntityEvent(std::shared_ptr e, uint8_t event); + ChunkSource* getChunkSource(); + virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1); + LevelStorage* getLevelStorage(); + LevelData* getLevelData(); + virtual void updateSleepingPlayerList(); + bool useNewSeaLevel(); // 4J added + bool getHasBeenInCreative(); // 4J Added + bool isGenerateMapFeatures(); // 4J Added + int getSaveVersion(); + int getOriginalSaveVersion(); + float getThunderLevel(float a); + float getRainLevel(float a); + void setRainLevel(float rainLevel); + bool isThundering(); + bool isRaining(); + bool isRainingAt(int x, int y, int z); + bool isHumidAt(int x, int y, int z); + void setSavedData(const std::wstring& id, std::shared_ptr data); + std::shared_ptr getSavedData(const std::type_info& clazz, + const std::wstring& id); + int getFreeAuxValueFor(const std::wstring& id); + void levelEvent(int type, int x, int y, int z, int data); + void levelEvent(std::shared_ptr source, int type, int x, int y, + int z, int data); + int getMaxBuildHeight(); + int getHeight(); + Random* getRandomFor(int x, int z, int blend); + bool updateLights(); + virtual bool isAllEmpty(); + double getHorizonHeight(); + void destroyTileProgress(int id, int x, int y, int z, int progress); + TilePos* findNearestMapFeature(const std::wstring& featureName, int x, + int y, int z); - // 4J Added - int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale); + // 4J Added + int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, + int centreZC, int scale); - // 4J added + // 4J added + __int64 m_timeOfDayOverride; - __int64 m_timeOfDayOverride; + // 4J - optimisation - keep direct reference of underlying cache here + LevelChunk** chunkSourceCache; + int chunkSourceXZSize; - // 4J - optimisation - keep direct reference of underlying cache here - LevelChunk **chunkSourceCache; - int chunkSourceXZSize; - - // 4J - added for implementation of finite limit to number of item entities, tnt and falling block entities + // 4J - added for implementation of finite limit to number of item entities, + // tnt and falling block entities public: - virtual bool newPrimedTntAllowed() { return true; } - virtual bool newFallingTileAllowed() { return true; } + virtual bool newPrimedTntAllowed() { return true; } + virtual bool newFallingTileAllowed() { return true; } - // 4J - added for new lighting from 1.8.2 - CRITICAL_SECTION m_checkLightCS; + // 4J - added for new lighting from 1.8.2 + CRITICAL_SECTION m_checkLightCS; private: - int m_iHighestY; // 4J-PB - for the end portal in The End + int m_iHighestY; // 4J-PB - for the end portal in The End public: - int GetHighestY() { return m_iHighestY;} - void SetHighestY(int iVal) { m_iHighestY=iVal;} + int GetHighestY() { return m_iHighestY; } + void SetHighestY(int iVal) { m_iHighestY = iVal; } - bool isChunkFinalised(int x, int z); // 4J added - bool isChunkPostPostProcessed(int x, int z); // 4J added + bool isChunkFinalised(int x, int z); // 4J added + bool isChunkPostPostProcessed(int x, int z); // 4J added private: - int m_unsavedChunkCount; + int m_unsavedChunkCount; public: - int getUnsavedChunkCount(); - void incrementUnsavedChunkCount(); // 4J Added - void decrementUnsavedChunkCount(); // 4J Added + int getUnsavedChunkCount(); + void incrementUnsavedChunkCount(); // 4J Added + void decrementUnsavedChunkCount(); // 4J Added - enum ESPAWN_TYPE - { - eSpawnType_Egg, - eSpawnType_Breed, - }; + enum ESPAWN_TYPE { + eSpawnType_Egg, + eSpawnType_Breed, + }; - bool canCreateMore(eINSTANCEOF type, ESPAWN_TYPE spawnType); + bool canCreateMore(eINSTANCEOF type, ESPAWN_TYPE spawnType); }; diff --git a/Minecraft.World/Level/LevelChunk.cpp b/Minecraft.World/Level/LevelChunk.cpp index 2c9bdeee3..ba8937cb5 100644 --- a/Minecraft.World/Level/LevelChunk.cpp +++ b/Minecraft.World/Level/LevelChunk.cpp @@ -18,618 +18,655 @@ #ifdef __PS3__ #include "../../Minecraft.Client/Platform/PS3/PS3Extras/C4JSpursJob.h" -#endif //__PS3__ - +#endif //__PS3__ #ifdef SHARING_ENABLED CRITICAL_SECTION LevelChunk::m_csSharing; #endif #ifdef _ENTITIES_RW_SECTION - // AP - use a RW critical section so we can have multiple threads reading the same data to avoid a clash - CRITICAL_RW_SECTION LevelChunk::m_csEntities; +// AP - use a RW critical section so we can have multiple threads reading the +// same data to avoid a clash +CRITICAL_RW_SECTION LevelChunk::m_csEntities; #else - CRITICAL_SECTION LevelChunk::m_csEntities; +CRITICAL_SECTION LevelChunk::m_csEntities; #endif CRITICAL_SECTION LevelChunk::m_csTileEntities; bool LevelChunk::touchedSky = false; -void LevelChunk::staticCtor() -{ +void LevelChunk::staticCtor() { #ifdef SHARING_ENABLED - InitializeCriticalSection(&m_csSharing); + InitializeCriticalSection(&m_csSharing); #endif #ifdef _ENTITIES_RW_SECTION - InitializeCriticalRWSection(&m_csEntities); + InitializeCriticalRWSection(&m_csEntities); #else - InitializeCriticalSection(&m_csEntities); + InitializeCriticalSection(&m_csEntities); #endif - InitializeCriticalSection(&m_csTileEntities); + InitializeCriticalSection(&m_csTileEntities); } -void LevelChunk::init(Level *level, int x, int z) -{ - biomes = byteArray(16 * 16); - for(int i = 0; i < 16 * 16; i++ ) - { - biomes[i] = 0xff; - } +void LevelChunk::init(Level* level, int x, int z) { + biomes = byteArray(16 * 16); + for (int i = 0; i < 16 * 16; i++) { + biomes[i] = 0xff; + } #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - entityBlocks = new std::vector > *[ENTITY_BLOCKS_LENGTH]; + entityBlocks = + new std::vector >*[ENTITY_BLOCKS_LENGTH]; #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif - terrainPopulated = 0; - m_unsaved = false; - lastSaveHadEntities = false; - lastSaveTime = 0; - dontSave = false; - loaded = false; - minHeight = 0; - hasGapsToCheck = false; - seenByPlayer = true; // 4J Stu - Always true + terrainPopulated = 0; + m_unsaved = false; + lastSaveHadEntities = false; + lastSaveTime = 0; + dontSave = false; + loaded = false; + minHeight = 0; + hasGapsToCheck = false; + seenByPlayer = true; // 4J Stu - Always true - // 4J Stu - Not using this - checkLightPosition = 0; //LIGHT_CHECK_MAX_POS; + // 4J Stu - Not using this + checkLightPosition = 0; // LIGHT_CHECK_MAX_POS; this->level = level; this->x = x; this->z = z; - MemSect(1); + MemSect(1); heightmap = byteArray(16 * 16); #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) - { + for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { entityBlocks[i] = new std::vector >(); } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif - MemSect(0); + MemSect(0); - // Optimisation brought forward from 1.8.2, change from int to unsigned char & this special value changed from -999 to 255 - for(int i = 0; i < 16 * 16; i++ ) - { - rainHeights[i] = 255; - } - // 4J - lighting change brought forward from 1.8.2, introduced an array of bools called gapsToRecheck, which are now a single bit in array of nybble flags in this version - for(int i = 0; i < 8 * 16; i++ ) - { - columnFlags[i] = 0; - } + // Optimisation brought forward from 1.8.2, change from int to unsigned char + // & this special value changed from -999 to 255 + for (int i = 0; i < 16 * 16; i++) { + rainHeights[i] = 255; + } + // 4J - lighting change brought forward from 1.8.2, introduced an array of + // bools called gapsToRecheck, which are now a single bit in array of nybble + // flags in this version + for (int i = 0; i < 8 * 16; i++) { + columnFlags[i] = 0; + } - // 4J added - to flag if any emissive tile has been added to this chunk (will be cleared when lighting has been successfully completed for this chunk). Defaulting to true - // as emissive things can be made and passed in the the initialisation block array. - emissiveAdded = true; + // 4J added - to flag if any emissive tile has been added to this chunk + // (will be cleared when lighting has been successfully completed for this + // chunk). Defaulting to true as emissive things can be made and passed in + // the the initialisation block array. + emissiveAdded = true; #ifdef _LARGE_WORLDS - m_bUnloaded = false; // 4J Added - m_unloadedEntitiesTag = NULL; + m_bUnloaded = false; // 4J Added + m_unloadedEntitiesTag = NULL; #endif } // This ctor is used for loading a save into -LevelChunk::LevelChunk(Level *level, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) -{ +LevelChunk::LevelChunk(Level* level, int x, int z) + : ENTITY_BLOCKS_LENGTH(Level::maxBuildHeight / 16) { init(level, x, z); - lowerBlocks = new CompressedTileStorage(); + lowerBlocks = new CompressedTileStorage(); lowerData = NULL; lowerSkyLight = NULL; lowerBlockLight = NULL; - serverTerrainPopulated = NULL; + serverTerrainPopulated = NULL; - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - // Create all these as empty, as we may not be loading any data into them - upperBlocks = new CompressedTileStorage(true); - upperData = new SparseDataStorage(true); - upperSkyLight = new SparseLightStorage(true, true); - upperBlockLight = new SparseLightStorage(false, true); - } - else - { - upperBlocks = NULL; - upperData = NULL; - upperSkyLight = NULL; - upperBlockLight = NULL; - } + if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + // Create all these as empty, as we may not be loading any data into + // them + upperBlocks = new CompressedTileStorage(true); + upperData = new SparseDataStorage(true); + upperSkyLight = new SparseLightStorage(true, true); + upperBlockLight = new SparseLightStorage(false, true); + } else { + upperBlocks = NULL; + upperData = NULL; + upperSkyLight = NULL; + upperBlockLight = NULL; + } #ifdef SHARING_ENABLED - sharingTilesAndData = false; + sharingTilesAndData = false; #endif } -// 4J - note that since we now compress the block storage, the parameter blocks is used as a source of data, but doesn't get used As the source data so needs +// 4J - note that since we now compress the block storage, the parameter blocks +// is used as a source of data, but doesn't get used As the source data so needs // to be deleted after calling this ctor. -LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) -{ - init(level, x, z); - - // We'll be creating this as "empty" when this ctor is called on the client, as a result of a chunk becoming visible (but we don't have the data yet for it). - // In this case, we want to keep memory usage down and so create all data as empty/compressed as possible. On the client we get the full data for the chunk as a single - // update in a block region update packet, and so there is a single point where it is good to compress the data. - bool createEmpty = ( blocks.data == NULL ); - - if( createEmpty ) - { - lowerBlocks = new CompressedTileStorage(true); - lowerData = new SparseDataStorage(true); - - lowerSkyLight = new SparseLightStorage(true, true); - lowerBlockLight = new SparseLightStorage(false, true); - } - else - { - lowerBlocks = new CompressedTileStorage(blocks,0); - lowerData = new SparseDataStorage(); - - // 4J - changed to new SpareLightStorage class for these - lowerSkyLight = new SparseLightStorage(true); - lowerBlockLight = new SparseLightStorage(false); - } -// skyLight = new DataLayer(blocks.length, level->depthBits); -// blockLight = new DataLayer(blocks.length, level->depthBits); - - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - if(blocks.length > Level::COMPRESSED_CHUNK_SECTION_TILES) upperBlocks = new CompressedTileStorage(blocks,Level::COMPRESSED_CHUNK_SECTION_TILES); - else upperBlocks = new CompressedTileStorage(true); - upperData = new SparseDataStorage(true); - upperSkyLight = new SparseLightStorage(true, true); - upperBlockLight = new SparseLightStorage(false, true); - } - else - { - upperBlocks = NULL; - upperData = NULL; - upperSkyLight = NULL; - upperBlockLight = NULL; - } - - serverTerrainPopulated = NULL; -#ifdef SHARING_ENABLED - sharingTilesAndData = false; -#endif -} - -// 4J - this ctor added to be able to make a levelchunk that shares its underlying block data between the server chunk cache & the multiplayer chunk cache. -// The original version this is shared from owns all the data that is shared into this copy, so it isn't deleted in the dtor. -LevelChunk::LevelChunk(Level *level, int x, int z, LevelChunk *lc) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) -{ +LevelChunk::LevelChunk(Level* level, byteArray blocks, int x, int z) + : ENTITY_BLOCKS_LENGTH(Level::maxBuildHeight / 16) { init(level, x, z); - // 4J Stu - Copy over the biome data - memcpy(biomes.data,lc->biomes.data,biomes.length); + // We'll be creating this as "empty" when this ctor is called on the client, + // as a result of a chunk becoming visible (but we don't have the data yet + // for it). In this case, we want to keep memory usage down and so create + // all data as empty/compressed as possible. On the client we get the full + // data for the chunk as a single update in a block region update packet, + // and so there is a single point where it is good to compress the data. + bool createEmpty = (blocks.data == NULL); + + if (createEmpty) { + lowerBlocks = new CompressedTileStorage(true); + lowerData = new SparseDataStorage(true); + + lowerSkyLight = new SparseLightStorage(true, true); + lowerBlockLight = new SparseLightStorage(false, true); + } else { + lowerBlocks = new CompressedTileStorage(blocks, 0); + lowerData = new SparseDataStorage(); + + // 4J - changed to new SpareLightStorage class for these + lowerSkyLight = new SparseLightStorage(true); + lowerBlockLight = new SparseLightStorage(false); + } + // skyLight = new DataLayer(blocks.length, level->depthBits); + // blockLight = new DataLayer(blocks.length, level->depthBits); + + if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + if (blocks.length > Level::COMPRESSED_CHUNK_SECTION_TILES) + upperBlocks = new CompressedTileStorage( + blocks, Level::COMPRESSED_CHUNK_SECTION_TILES); + else + upperBlocks = new CompressedTileStorage(true); + upperData = new SparseDataStorage(true); + upperSkyLight = new SparseLightStorage(true, true); + upperBlockLight = new SparseLightStorage(false, true); + } else { + upperBlocks = NULL; + upperData = NULL; + upperSkyLight = NULL; + upperBlockLight = NULL; + } + + serverTerrainPopulated = NULL; +#ifdef SHARING_ENABLED + sharingTilesAndData = false; +#endif +} + +// 4J - this ctor added to be able to make a levelchunk that shares its +// underlying block data between the server chunk cache & the multiplayer chunk +// cache. The original version this is shared from owns all the data that is +// shared into this copy, so it isn't deleted in the dtor. +LevelChunk::LevelChunk(Level* level, int x, int z, LevelChunk* lc) + : ENTITY_BLOCKS_LENGTH(Level::maxBuildHeight / 16) { + init(level, x, z); + + // 4J Stu - Copy over the biome data + memcpy(biomes.data, lc->biomes.data, biomes.length); #ifdef SHARING_ENABLED lowerBlocks = lc->lowerBlocks; lowerData = lc->lowerData; - lowerSkyLight = new SparseLightStorage( lc->lowerSkyLight ); - lowerBlockLight = new SparseLightStorage( lc->lowerBlockLight ); - upperBlocks = lc->upperBlocks; - upperData = lc->upperData; - upperSkyLight = new SparseLightStorage( lc->upperSkyLight ); - upperBlockLight = new SparseLightStorage( lc->upperBlockLight ); + lowerSkyLight = new SparseLightStorage(lc->lowerSkyLight); + lowerBlockLight = new SparseLightStorage(lc->lowerBlockLight); + upperBlocks = lc->upperBlocks; + upperData = lc->upperData; + upperSkyLight = new SparseLightStorage(lc->upperSkyLight); + upperBlockLight = new SparseLightStorage(lc->upperBlockLight); - sharingTilesAndData = true; - serverTerrainPopulated = &lc->terrainPopulated; + sharingTilesAndData = true; + serverTerrainPopulated = &lc->terrainPopulated; #else - this->blocks = new CompressedTileStorage(lc->blocks); - this->data = new SparseDataStorage(lc->data); - this->skyLight = new SparseLightStorage(lc->skyLight); - this->blockLight = new SparseLightStorage(lc->blockLight); - serverTerrainPopulated = NULL; + this->blocks = new CompressedTileStorage(lc->blocks); + this->data = new SparseDataStorage(lc->data); + this->skyLight = new SparseLightStorage(lc->skyLight); + this->blockLight = new SparseLightStorage(lc->blockLight); + serverTerrainPopulated = NULL; #endif } // 4J Added so we can track unsaved chunks better -void LevelChunk::setUnsaved(bool unsaved) -{ +void LevelChunk::setUnsaved(bool unsaved) { #ifdef _LARGE_WORLDS - if(m_unsaved != unsaved) - { - if(unsaved) level->incrementUnsavedChunkCount(); - else level->decrementUnsavedChunkCount(); - } + if (m_unsaved != unsaved) { + if (unsaved) + level->incrementUnsavedChunkCount(); + else + level->decrementUnsavedChunkCount(); + } #endif - m_unsaved = unsaved; + m_unsaved = unsaved; } -void LevelChunk::stopSharingTilesAndData() -{ +void LevelChunk::stopSharingTilesAndData() { #ifdef SHARING_ENABLED - EnterCriticalSection(&m_csSharing); - lastUnsharedTime = System::currentTimeMillis(); - if( !sharingTilesAndData ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + EnterCriticalSection(&m_csSharing); + lastUnsharedTime = System::currentTimeMillis(); + if (!sharingTilesAndData) { + LeaveCriticalSection(&m_csSharing); + return; + } - // If we've got a reference to a server chunk's terrainPopulated flag that this LevelChunk is sharing with, then don't consider unsharing - // if it hasn't been set. This is because post-processing things that update the server chunks won't actually cause the server to send any updates - // to the tiles that they alter, so they completely depend on the data not being shared for it to get from the server to here - if( ( serverTerrainPopulated ) && ( ( (*serverTerrainPopulated) & sTerrainPopulatedAllAffecting ) != sTerrainPopulatedAllAffecting ) ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + // If we've got a reference to a server chunk's terrainPopulated flag that + // this LevelChunk is sharing with, then don't consider unsharing if it + // hasn't been set. This is because post-processing things that update the + // server chunks won't actually cause the server to send any updates to the + // tiles that they alter, so they completely depend on the data not being + // shared for it to get from the server to here + if ((serverTerrainPopulated) && + (((*serverTerrainPopulated) & sTerrainPopulatedAllAffecting) != + sTerrainPopulatedAllAffecting)) { + LeaveCriticalSection(&m_csSharing); + return; + } - // If this is the empty chunk, then it will have a x & z of 0,0 - if we don't drop out here we'll end up unsharing the chunk at this location for no reason - if( isEmpty() ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + // If this is the empty chunk, then it will have a x & z of 0,0 - if we + // don't drop out here we'll end up unsharing the chunk at this location for + // no reason + if (isEmpty()) { + LeaveCriticalSection(&m_csSharing); + return; + } - MemSect(47); + MemSect(47); - // Changed to used compressed storage - these CTORs make deep copies of the storage passed as a parameter - lowerBlocks = new CompressedTileStorage( lowerBlocks ); + // Changed to used compressed storage - these CTORs make deep copies of the + // storage passed as a parameter + lowerBlocks = new CompressedTileStorage(lowerBlocks); - // Changed to use new sparse data storage - this CTOR makes a deep copy of the storage passed as a parameter - lowerData = new SparseDataStorage(lowerData); + // Changed to use new sparse data storage - this CTOR makes a deep copy of + // the storage passed as a parameter + lowerData = new SparseDataStorage(lowerData); - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - upperBlocks = new CompressedTileStorage( upperBlocks ); - upperData = new SparseDataStorage(upperData); - } - else - { - upperBlocks = NULL; - upperData = NULL; - } + if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + upperBlocks = new CompressedTileStorage(upperBlocks); + upperData = new SparseDataStorage(upperData); + } else { + upperBlocks = NULL; + upperData = NULL; + } - /* - newDataLayer = new DataLayer(skyLight->data.length*2, level->depthBits); - XMemCpy(newDataLayer->data.data, skyLight->data.data, skyLight->data.length); - skyLight = newDataLayer; + /* + newDataLayer = new DataLayer(skyLight->data.length*2, level->depthBits); + XMemCpy(newDataLayer->data.data, skyLight->data.data, + skyLight->data.length); skyLight = newDataLayer; - newDataLayer = new DataLayer(blockLight->data.length*2, level->depthBits); - XMemCpy(newDataLayer->data.data, blockLight->data.data, blockLight->data.length); - blockLight = newDataLayer; - */ + newDataLayer = new DataLayer(blockLight->data.length*2, level->depthBits); + XMemCpy(newDataLayer->data.data, blockLight->data.data, + blockLight->data.length); blockLight = newDataLayer; + */ - sharingTilesAndData = false; - MemSect(0); - LeaveCriticalSection(&m_csSharing); + sharingTilesAndData = false; + MemSect(0); + LeaveCriticalSection(&m_csSharing); #endif } -// This is a slight variation on the normal start/stop sharing methods here as in general we aren't sharing lighting anymore. This method -// discards the client lighting information, and sets up new (non-shared) lighting to match the server. So generally like stop sharing, -// for the case where we're already not sharing -void LevelChunk::reSyncLighting() -{ +// This is a slight variation on the normal start/stop sharing methods here as +// in general we aren't sharing lighting anymore. This method discards the +// client lighting information, and sets up new (non-shared) lighting to match +// the server. So generally like stop sharing, for the case where we're already +// not sharing +void LevelChunk::reSyncLighting() { #ifdef SHARING_ENABLED - EnterCriticalSection(&m_csSharing); + EnterCriticalSection(&m_csSharing); - if( isEmpty() ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + if (isEmpty()) { + LeaveCriticalSection(&m_csSharing); + return; + } #ifdef _LARGE_WORLDS - LevelChunk *lc = MinecraftServer::getInstance()->getLevel( level->dimension->id )->cache->getChunkLoadedOrUnloaded(x,z); + LevelChunk* lc = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunkLoadedOrUnloaded(x, z); #else - LevelChunk *lc = MinecraftServer::getInstance()->getLevel( level->dimension->id )->cache->getChunk(x,z); + LevelChunk* lc = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunk(x, z); #endif - GameRenderer::AddForDelete(lowerSkyLight); - lowerSkyLight = new SparseLightStorage( lc->lowerSkyLight ); - GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(lowerBlockLight); - lowerBlockLight = new SparseLightStorage( lc->lowerBlockLight ); - GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(lowerSkyLight); + lowerSkyLight = new SparseLightStorage(lc->lowerSkyLight); + GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(lowerBlockLight); + lowerBlockLight = new SparseLightStorage(lc->lowerBlockLight); + GameRenderer::FinishedReassigning(); - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - GameRenderer::AddForDelete(upperSkyLight); - upperSkyLight = new SparseLightStorage( lc->upperSkyLight ); - GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(upperBlockLight); - upperBlockLight = new SparseLightStorage( lc->upperBlockLight ); - GameRenderer::FinishedReassigning(); - } - LeaveCriticalSection(&m_csSharing); + if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + GameRenderer::AddForDelete(upperSkyLight); + upperSkyLight = new SparseLightStorage(lc->upperSkyLight); + GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(upperBlockLight); + upperBlockLight = new SparseLightStorage(lc->upperBlockLight); + GameRenderer::FinishedReassigning(); + } + LeaveCriticalSection(&m_csSharing); #endif } -void LevelChunk::startSharingTilesAndData(int forceMs) -{ +void LevelChunk::startSharingTilesAndData(int forceMs) { #ifdef SHARING_ENABLED - EnterCriticalSection(&m_csSharing); - if( sharingTilesAndData ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + EnterCriticalSection(&m_csSharing); + if (sharingTilesAndData) { + LeaveCriticalSection(&m_csSharing); + return; + } - // If this is the empty chunk, then it will have a x & z of 0,0 - we'll end up potentially loading the 0,0 block if we proceed. And it obviously - // doesn't make sense to go resharing the 0,0 block on behalf of an empty chunk either - if( isEmpty() ) - { - LeaveCriticalSection(&m_csSharing); - return; - } + // If this is the empty chunk, then it will have a x & z of 0,0 - we'll end + // up potentially loading the 0,0 block if we proceed. And it obviously + // doesn't make sense to go resharing the 0,0 block on behalf of an empty + // chunk either + if (isEmpty()) { + LeaveCriticalSection(&m_csSharing); + return; + } #ifdef _LARGE_WORLDS - LevelChunk *lc = MinecraftServer::getInstance()->getLevel( level->dimension->id )->cache->getChunkLoadedOrUnloaded(x,z); + LevelChunk* lc = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunkLoadedOrUnloaded(x, z); #else - LevelChunk *lc = MinecraftServer::getInstance()->getLevel( level->dimension->id )->cache->getChunk(x,z); + LevelChunk* lc = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunk(x, z); #endif - // In normal usage, chunks should only reshare if their local data matched that on the server. The forceMs parameter though can - // be used to force a share if resharing hasn't happened after a period of time - if( forceMs == 0 ) - { - // Normal behaviour - just check that the data matches, and don't start sharing data if it doesn't (yet) - if( !lowerBlocks->isSameAs(lc->lowerBlocks) || (upperBlocks && lc->upperBlocks && !upperBlocks->isSameAs(lc->upperBlocks) ) ) - { - LeaveCriticalSection(&m_csSharing); - return; - } - } - else - { - // Only force if it has been more than forceMs milliseconds since we last wanted to unshare this chunk - __int64 timenow = System::currentTimeMillis(); - if( ( timenow - lastUnsharedTime ) < forceMs ) - { - LeaveCriticalSection(&m_csSharing); - return; - } - } + // In normal usage, chunks should only reshare if their local data matched + // that on the server. The forceMs parameter though can be used to force a + // share if resharing hasn't happened after a period of time + if (forceMs == 0) { + // Normal behaviour - just check that the data matches, and don't start + // sharing data if it doesn't (yet) + if (!lowerBlocks->isSameAs(lc->lowerBlocks) || + (upperBlocks && lc->upperBlocks && + !upperBlocks->isSameAs(lc->upperBlocks))) { + LeaveCriticalSection(&m_csSharing); + return; + } + } else { + // Only force if it has been more than forceMs milliseconds since we + // last wanted to unshare this chunk + __int64 timenow = System::currentTimeMillis(); + if ((timenow - lastUnsharedTime) < forceMs) { + LeaveCriticalSection(&m_csSharing); + return; + } + } - // Note - data that was shared isn't directly deleted here, as it might still be in use in the game render update thread. Let that thread - // delete it when it is safe to do so instead. - GameRenderer::AddForDelete(lowerBlocks); - lowerBlocks = lc->lowerBlocks; - GameRenderer::FinishedReassigning(); + // Note - data that was shared isn't directly deleted here, as it might + // still be in use in the game render update thread. Let that thread delete + // it when it is safe to do so instead. + GameRenderer::AddForDelete(lowerBlocks); + lowerBlocks = lc->lowerBlocks; + GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(lowerData); - lowerData = lc->lowerData; - GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(lowerData); + lowerData = lc->lowerData; + GameRenderer::FinishedReassigning(); - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - GameRenderer::AddForDelete(upperBlocks); - upperBlocks = lc->upperBlocks; - GameRenderer::FinishedReassigning(); + if (Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + GameRenderer::AddForDelete(upperBlocks); + upperBlocks = lc->upperBlocks; + GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(upperData); - upperData = lc->upperData; - GameRenderer::FinishedReassigning(); - } + GameRenderer::AddForDelete(upperData); + upperData = lc->upperData; + GameRenderer::FinishedReassigning(); + } - sharingTilesAndData = true; - LeaveCriticalSection(&m_csSharing); + sharingTilesAndData = true; + LeaveCriticalSection(&m_csSharing); #endif } -LevelChunk::~LevelChunk() -{ +LevelChunk::~LevelChunk() { #ifdef SHARING_ENABLED - if( !sharingTilesAndData ) + if (!sharingTilesAndData) #endif - { - delete lowerData; - delete lowerBlocks; - if(upperData) delete upperData; - if(upperBlocks) delete upperBlocks; - } + { + delete lowerData; + delete lowerBlocks; + if (upperData) delete upperData; + if (upperBlocks) delete upperBlocks; + } - delete lowerSkyLight; - delete lowerBlockLight; - if(upperSkyLight) delete upperSkyLight; - if(upperBlockLight) delete upperBlockLight; + delete lowerSkyLight; + delete lowerBlockLight; + if (upperSkyLight) delete upperSkyLight; + if (upperBlockLight) delete upperBlockLight; - delete[] heightmap.data; + delete[] heightmap.data; - for(int i = 0; i < ENTITY_BLOCKS_LENGTH; ++i) - delete entityBlocks[i]; - delete[] entityBlocks; + for (int i = 0; i < ENTITY_BLOCKS_LENGTH; ++i) delete entityBlocks[i]; + delete[] entityBlocks; - delete[] biomes.data; + delete[] biomes.data; #ifdef _LARGE_WORLDS - delete m_unloadedEntitiesTag; + delete m_unloadedEntitiesTag; #endif } -bool LevelChunk::isAt(int x, int z) -{ - return x == this->x && z == this->z; +bool LevelChunk::isAt(int x, int z) { return x == this->x && z == this->z; } + +int LevelChunk::getHeightmap(int x, int z) { + return heightmap[(unsigned)z << 4 | x] & 0xff; } -int LevelChunk::getHeightmap(int x, int z) -{ - return heightmap[(unsigned) z << 4 | x] & 0xff; +int LevelChunk::getHighestSectionPosition() { + return Level::maxBuildHeight - 16; + // 4J Stu - Unused + // for (int i = sections.length - 1; i >= 0; i--) { + // if (sections[i] != null) { // && !sections[i].isEmpty()) { + // return sections[i].getYPosition(); + // } + //} + // return 0; } -int LevelChunk::getHighestSectionPosition() -{ - return Level::maxBuildHeight - 16; - // 4J Stu - Unused - //for (int i = sections.length - 1; i >= 0; i--) { - // if (sections[i] != null) { // && !sections[i].isEmpty()) { - // return sections[i].getYPosition(); - // } - //} - //return 0; -} +void LevelChunk::recalcBlockLights() {} -void LevelChunk::recalcBlockLights() -{ -} - - - -void LevelChunk::recalcHeightmapOnly() -{ +void LevelChunk::recalcHeightmapOnly() { #ifdef __PSVITA__ - // AP - lets fetch ALL the chunk data at the same time for a good speed up - byteArray blockData = byteArray(Level::CHUNK_TILE_COUNT); - getBlockData(blockData); -#endif - - int min = Level::maxBuildHeight - 1; - for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - { - rainHeights[x + ((unsigned) z << 4)] = 255; // 4J - changed from int to unsigned char & this special value changed from -999 to 255 - - int y = Level::maxBuildHeight - 1; - // int p = x << level->depthBitsPlusFour | z << level->depthBits; // 4J - removed -#ifdef __PSVITA__ - int Index = ( (unsigned) x << 11 ) + ( (unsigned) z << 7 ); - int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - y = 127; - while (y > 0 && Tile::lightBlock[blockData[Index + offset + (y - 1)]] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { - y--; - } - if( y == 0 ) - { - offset = 0; - y = 127; - while (y > 0 && Tile::lightBlock[blockData[Index + offset + (y - 1)]] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { - y--; - } - } - else - { - y += 128; - } -#else - CompressedTileStorage *blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - while (y > 0 && Tile::lightBlock[blocks->get(x,(y - 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z) & 0xff] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { - y--; - blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - } -#endif - heightmap[(unsigned) z << 4 | x] = (uint8_t) y; - if (y < min) min = y; - } - - this->minHeight = min; - this->setUnsaved(true); - -#ifdef __PSVITA__ - delete blockData.data; -#endif -} - -void LevelChunk::recalcHeightmap() -{ -#ifdef __PSVITA__ - // AP - lets fetch ALL the chunk data at the same time for a good speed up - byteArray blockData = byteArray(Level::CHUNK_TILE_COUNT); - getBlockData(blockData); + // AP - lets fetch ALL the chunk data at the same time for a good speed up + byteArray blockData = byteArray(Level::CHUNK_TILE_COUNT); + getBlockData(blockData); #endif int min = Level::maxBuildHeight - 1; for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - { + for (int z = 0; z < 16; z++) { + rainHeights[x + ((unsigned)z << 4)] = + 255; // 4J - changed from int to unsigned char & this special + // value changed from -999 to 255 + int y = Level::maxBuildHeight - 1; -// int p = x << level->depthBitsPlusFour | z << level->depthBits; // 4J - removed - + // int p = x << level->depthBitsPlusFour | z << + // level->depthBits; // 4J - removed #ifdef __PSVITA__ - int Index = ( (unsigned) x << 11 ) + ( (unsigned) z << 7 ); - int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + int Index = ((unsigned)x << 11) + ((unsigned)z << 7); + int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; y = 127; - while (y > 0 && Tile::lightBlock[blockData[Index + offset + (y - 1)]] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { - y--; - } - if( y == 0 ) - { - offset = 0; - y = 127; - while (y > 0 && Tile::lightBlock[blockData[Index + offset + (y - 1)]] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { - y--; - } - } - else - { - y += 128; - } -#else - CompressedTileStorage *blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - while (y > 0 && Tile::lightBlock[blocks->get(x,(y-1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z) & 0xff] == 0) // 4J - was blocks->get() was blocks[p + y - 1] - { + while (y > 0 && + Tile::lightBlock[blockData[Index + offset + (y - 1)]] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { y--; - blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - } + } + if (y == 0) { + offset = 0; + y = 127; + while (y > 0 && + Tile::lightBlock[blockData[Index + offset + (y - 1)]] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { + y--; + } + } else { + y += 128; + } +#else + CompressedTileStorage* blocks = + (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks + : lowerBlocks; + while ( + y > 0 && + Tile::lightBlock[blocks->get( + x, + (y - 1) % + Level::COMPRESSED_CHUNK_SECTION_HEIGHT, + z) & + 0xff] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { + y--; + blocks = (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlocks + : lowerBlocks; + } #endif - heightmap[(unsigned) z << 4 | x] = (uint8_t) y; + heightmap[(unsigned)z << 4 | x] = (uint8_t)y; + if (y < min) min = y; + } + + this->minHeight = min; + this->setUnsaved(true); + +#ifdef __PSVITA__ + delete blockData.data; +#endif +} + +void LevelChunk::recalcHeightmap() { +#ifdef __PSVITA__ + // AP - lets fetch ALL the chunk data at the same time for a good speed up + byteArray blockData = byteArray(Level::CHUNK_TILE_COUNT); + getBlockData(blockData); +#endif + + int min = Level::maxBuildHeight - 1; + for (int x = 0; x < 16; x++) + for (int z = 0; z < 16; z++) { + int y = Level::maxBuildHeight - 1; + // int p = x << level->depthBitsPlusFour | z << + // level->depthBits; // 4J - removed + +#ifdef __PSVITA__ + int Index = ((unsigned)x << 11) + ((unsigned)z << 7); + int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + y = 127; + while (y > 0 && + Tile::lightBlock[blockData[Index + offset + (y - 1)]] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { + y--; + } + if (y == 0) { + offset = 0; + y = 127; + while (y > 0 && + Tile::lightBlock[blockData[Index + offset + (y - 1)]] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { + y--; + } + } else { + y += 128; + } +#else + CompressedTileStorage* blocks = + (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks + : lowerBlocks; + while ( + y > 0 && + Tile::lightBlock[blocks->get( + x, + (y - 1) % + Level::COMPRESSED_CHUNK_SECTION_HEIGHT, + z) & + 0xff] == + 0) // 4J - was blocks->get() was blocks[p + y - 1] + { + y--; + blocks = (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlocks + : lowerBlocks; + } +#endif + heightmap[(unsigned)z << 4 | x] = (uint8_t)y; if (y < min) min = y; - if (!level->dimension->hasCeiling) - { + if (!level->dimension->hasCeiling) { int br = Level::MAX_BRIGHTNESS; - int yy = Level::maxBuildHeight - 1; + int yy = Level::maxBuildHeight - 1; #ifdef __PSVITA__ - int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - SparseLightStorage *skyLight = upperSkyLight; - yy = 127; - do - { - br -= Tile::lightBlock[blockData[Index + offset + yy]]; // 4J - blocks->get() was blocks[p + yy] - if (br > 0) - { + int offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + SparseLightStorage* skyLight = upperSkyLight; + yy = 127; + do { + br -= + Tile::lightBlock[blockData[Index + offset + + yy]]; // 4J - blocks->get() + // was blocks[p + yy] + if (br > 0) { skyLight->set(x, yy, z, br); } yy--; } while (yy > 0 && br > 0); - if( yy == 0 && br > 0 ) - { - offset = 0; - skyLight = lowerSkyLight; - yy = 127; - do - { - br -= Tile::lightBlock[blockData[Index + offset + yy]]; // 4J - blocks->get() was blocks[p + yy] - if (br > 0) - { - skyLight->set(x, yy, z, br); - } - yy--; - } while (yy > 0 && br > 0); - } + if (yy == 0 && br > 0) { + offset = 0; + skyLight = lowerSkyLight; + yy = 127; + do { + br -= Tile::lightBlock + [blockData[Index + offset + + yy]]; // 4J - blocks->get() was blocks[p + // + yy] + if (br > 0) { + skyLight->set(x, yy, z, br); + } + yy--; + } while (yy > 0 && br > 0); + } #else - CompressedTileStorage *blocks = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - SparseLightStorage *skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - do - { - br -= Tile::lightBlock[blocks->get(x,(yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT),z) & 0xff]; // 4J - blocks->get() was blocks[p + yy] - if (br > 0) - { - skyLight->set(x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, br); + CompressedTileStorage* blocks = + yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks + : lowerBlocks; + SparseLightStorage* skyLight = + yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + do { + br -= Tile::lightBlock + [blocks->get( + x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), + z) & + 0xff]; // 4J - blocks->get() was blocks[p + yy] + if (br > 0) { + skyLight->set( + x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, + br); } yy--; - blocks = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; + blocks = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlocks + : lowerBlocks; + skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; } while (yy > 0 && br > 0); #endif } @@ -638,147 +675,151 @@ void LevelChunk::recalcHeightmap() this->minHeight = min; for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - { + for (int z = 0; z < 16; z++) { lightGaps(x, z); } this->setUnsaved(true); #ifdef __PSVITA__ - delete blockData.data; + delete blockData.data; #endif } -// 4J - this code is fully commented out in the java version, but we have reimplemented something here to try and light -// lava as chunks are created, as otherwise they get shared before being lit, and then their lighting gets updated on the client -// and causes framerate stutters. -void LevelChunk::lightLava() -{ - if( !emissiveAdded ) return; - - for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - { -// int p = x << 11 | z << 7; // 4J - removed - int ymax = getHeightmap(x,z); - for (int y = 0; y < Level::COMPRESSED_CHUNK_SECTION_HEIGHT; y++) - { - CompressedTileStorage *blocks = lowerBlocks; - int emit = Tile::lightEmission[blocks->get(x,y,z)]; // 4J - blocks->get() was blocks[p + y] - if( emit > 0 ) - { -// printf("(%d,%d,%d)",this->x * 16 + x, y, this->z * 16 + z); - // We'll be calling this function for a lot of chunks as they are post-processed. For every chunk that is - // post-processed we're calling this for each of its neighbours in case some post-processing also created something - // that needed lighting outside the starting chunk. Because of this, do a quick test on any emissive blocks that have - // been added to see if checkLight has already been run on this particular block - this is straightforward to check - // as being emissive blocks they'll have their block brightness set to their lightEmission level in this case. - if( getBrightness(LightLayer::Block, x, y, z) < emit ) - { - level->checkLight( LightLayer::Block, this->x * 16 + x, y, this->z * 16 + z, true); - } - } - } - } - emissiveAdded = false; +// 4J - this code is fully commented out in the java version, but we have +// reimplemented something here to try and light lava as chunks are created, as +// otherwise they get shared before being lit, and then their lighting gets +// updated on the client and causes framerate stutters. +void LevelChunk::lightLava() { + if (!emissiveAdded) return; + + for (int x = 0; x < 16; x++) + for (int z = 0; z < 16; z++) { + // int p = x << 11 | z << 7; + //// 4J - removed + int ymax = getHeightmap(x, z); + for (int y = 0; y < Level::COMPRESSED_CHUNK_SECTION_HEIGHT; y++) { + CompressedTileStorage* blocks = lowerBlocks; + int emit = Tile::lightEmission[blocks->get( + x, y, z)]; // 4J - blocks->get() was blocks[p + y] + if (emit > 0) { + // printf("(%d,%d,%d)",this->x + //* 16 + x, y, this->z * 16 + z); + // We'll be calling this function for a lot of chunks as + // they are post-processed. For every chunk that is + // post-processed we're calling this for each of its + // neighbours in case some post-processing also created + // something that needed lighting outside the starting + // chunk. Because of this, do a quick test on any emissive + // blocks that have been added to see if checkLight has + // already been run on this particular block - this is + // straightforward to check as being emissive blocks they'll + // have their block brightness set to their lightEmission + // level in this case. + if (getBrightness(LightLayer::Block, x, y, z) < emit) { + level->checkLight(LightLayer::Block, this->x * 16 + x, + y, this->z * 16 + z, true); + } + } + } + } + emissiveAdded = false; } -void LevelChunk::lightGaps(int x, int z) -{ - // 4J - lighting change brought forward from 1.8.2, introduced an array of bools called gapsToRecheck, which are now a single bit in array of nybbles in this version - int slot = ( x >> 1 ) | (z * 8); - int shift = ( x & 1 ) * 4; - columnFlags[slot] |= ( eColumnFlag_recheck << shift ); - hasGapsToCheck = true; +void LevelChunk::lightGaps(int x, int z) { + // 4J - lighting change brought forward from 1.8.2, introduced an array of + // bools called gapsToRecheck, which are now a single bit in array of + // nybbles in this version + int slot = (x >> 1) | (z * 8); + int shift = (x & 1) * 4; + columnFlags[slot] |= (eColumnFlag_recheck << shift); + hasGapsToCheck = true; } -void LevelChunk::recheckGaps(bool bForce) -{ - // 4J added - otherwise we can end up doing a very broken kind of lighting since for an empty chunk, the heightmap is all zero, but it - // still has an x and z of 0 which means that the level->getHeightmap references in here find a real chunk near the origin, and then attempt - // to light massive gaps between the height of 0 and whatever heights are in those. - if( isEmpty() ) return; +void LevelChunk::recheckGaps(bool bForce) { + // 4J added - otherwise we can end up doing a very broken kind of lighting + // since for an empty chunk, the heightmap is all zero, but it still has an + // x and z of 0 which means that the level->getHeightmap references in here + // find a real chunk near the origin, and then attempt to light massive gaps + // between the height of 0 and whatever heights are in those. + if (isEmpty()) return; - // 4J added - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; + // 4J added + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; - // 4J - note - this test will currently return true for chunks at the edge of our world. Making further checks inside the loop now to address this issue. - if (level->hasChunksAt(x * 16 + 8, Level::maxBuildHeight / 2, z * 16 + 8, 16)) - { + // 4J - note - this test will currently return true for chunks at the edge + // of our world. Making further checks inside the loop now to address this + // issue. + if (level->hasChunksAt(x * 16 + 8, Level::maxBuildHeight / 2, z * 16 + 8, + 16)) { for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - { - int slot = ( x >> 1 ) | (z * 8); - int shift = ( x & 1 ) * 4; - if (bForce || ( columnFlags[slot] & ( eColumnFlag_recheck << shift ) ) ) - { - columnFlags[slot] &= ~( eColumnFlag_recheck << shift ); + for (int z = 0; z < 16; z++) { + int slot = (x >> 1) | (z * 8); + int shift = (x & 1) * 4; + if (bForce || + (columnFlags[slot] & (eColumnFlag_recheck << shift))) { + columnFlags[slot] &= ~(eColumnFlag_recheck << shift); int height = getHeightmap(x, z); int xOffs = (this->x * 16) + x; int zOffs = (this->z * 16) + z; - // 4J - rewritten this to make sure that the minimum neighbour height which is calculated doesn't involve getting any heights from beyond the edge of the world, - // which can lead to large, very expensive, non-existent cliff edges to be lit - int nmin = level->getHeightmap(xOffs, zOffs); - if( xOffs - 1 >= minXZ ) - { - int n = level->getHeightmap(xOffs - 1, zOffs); - if ( n < nmin ) nmin = n; - } - if( xOffs + 1 <= maxXZ ) - { - int n = level->getHeightmap(xOffs + 1, zOffs); - if ( n < nmin ) nmin = n; - } - if( zOffs - 1 >= minXZ ) - { - int n = level->getHeightmap(xOffs, zOffs - 1); - if ( n < nmin ) nmin = n; - } - if( zOffs + 1 <= maxXZ ) - { - int n = level->getHeightmap(xOffs, zOffs + 1); - if ( n < nmin ) nmin = n; - } + // 4J - rewritten this to make sure that the minimum + // neighbour height which is calculated doesn't involve + // getting any heights from beyond the edge of the world, + // which can lead to large, very expensive, non-existent + // cliff edges to be lit + int nmin = level->getHeightmap(xOffs, zOffs); + if (xOffs - 1 >= minXZ) { + int n = level->getHeightmap(xOffs - 1, zOffs); + if (n < nmin) nmin = n; + } + if (xOffs + 1 <= maxXZ) { + int n = level->getHeightmap(xOffs + 1, zOffs); + if (n < nmin) nmin = n; + } + if (zOffs - 1 >= minXZ) { + int n = level->getHeightmap(xOffs, zOffs - 1); + if (n < nmin) nmin = n; + } + if (zOffs + 1 <= maxXZ) { + int n = level->getHeightmap(xOffs, zOffs + 1); + if (n < nmin) nmin = n; + } lightGap(xOffs, zOffs, nmin); - if( !bForce ) // 4J - if doing a full forced thing over every single column, we don't need to do these offset checks too - { - if( xOffs - 1 >= minXZ ) lightGap(xOffs - 1, zOffs, height); - if( xOffs + 1 <= maxXZ ) lightGap(xOffs + 1, zOffs, height); - if( zOffs - 1 >= minXZ ) lightGap(xOffs, zOffs - 1, height); - if( zOffs + 1 <= maxXZ ) lightGap(xOffs, zOffs + 1, height); - } - hasGapsToCheck = false; + if (!bForce) // 4J - if doing a full forced thing over + // every single column, we don't need to do + // these offset checks too + { + if (xOffs - 1 >= minXZ) + lightGap(xOffs - 1, zOffs, height); + if (xOffs + 1 <= maxXZ) + lightGap(xOffs + 1, zOffs, height); + if (zOffs - 1 >= minXZ) + lightGap(xOffs, zOffs - 1, height); + if (zOffs + 1 <= maxXZ) + lightGap(xOffs, zOffs + 1, height); + } + hasGapsToCheck = false; } } } } - -void LevelChunk::lightGap(int x, int z, int source) -{ +void LevelChunk::lightGap(int x, int z, int source) { int height = level->getHeightmap(x, z); - if (height > source) - { + if (height > source) { lightGap(x, z, source, height + 1); - } - else if (height < source) - { + } else if (height < source) { lightGap(x, z, height, source + 1); } } -void LevelChunk::lightGap(int x, int z, int y1, int y2) -{ - if (y2 > y1) - { - if (level->hasChunksAt(x, Level::maxBuildHeight / 2, z, 16)) - { - for (int y = y1; y < y2; y++) - { +void LevelChunk::lightGap(int x, int z, int y1, int y2) { + if (y2 > y1) { + if (level->hasChunksAt(x, Level::maxBuildHeight / 2, z, 16)) { + for (int y = y1; y < y2; y++) { level->checkLight(LightLayer::Sky, x, y, z); } this->setUnsaved(true); @@ -786,471 +827,505 @@ void LevelChunk::lightGap(int x, int z, int y1, int y2) } } -void LevelChunk::recalcHeight(int x, int yStart, int z) -{ - int yOld = heightmap[(unsigned) z << 4 | x] & 0xff; +void LevelChunk::recalcHeight(int x, int yStart, int z) { + int yOld = heightmap[(unsigned)z << 4 | x] & 0xff; int y = yOld; if (yStart > yOld) y = yStart; -// int p = x << level->depthBitsPlusFour | z << level->depthBits; // 4J - removed - - CompressedTileStorage *blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - while (y > 0 && Tile::lightBlock[blocks->get(x,(y-1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z) & 0xff] == 0) // 4J - blocks->get() was blocks[p + y - 1] - { + // int p = x << level->depthBitsPlusFour | z << level->depthBits; + // // 4J - removed + + CompressedTileStorage* blocks = + (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks + : lowerBlocks; + while ( + y > 0 && + Tile::lightBlock + [blocks->get( + x, (y - 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z) & + 0xff] == 0) // 4J - blocks->get() was blocks[p + y - 1] + { y--; - blocks = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT?upperBlocks : lowerBlocks; - } + blocks = (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlocks + : lowerBlocks; + } if (y == yOld) return; -// level->lightColumnChanged(x, z, y, yOld); // 4J - this call moved below & corrected - see comment further down - heightmap[(unsigned) z << 4 | x] = (uint8_t) y; + // level->lightColumnChanged(x, z, y, yOld); // 4J - this + // call moved below & corrected - see comment further down + heightmap[(unsigned)z << 4 | x] = (uint8_t)y; - if (y < minHeight) - { + if (y < minHeight) { minHeight = y; - } - else - { + } else { int min = Level::maxBuildHeight - 1; for (int _x = 0; _x < 16; _x++) - for (int _z = 0; _z < 16; _z++) - { - if ((heightmap[(unsigned) _z << 4 | _x] & 0xff) < min) min = (heightmap[(unsigned) _z << 4 | _x] & 0xff); + for (int _z = 0; _z < 16; _z++) { + if ((heightmap[(unsigned)_z << 4 | _x] & 0xff) < min) + min = (heightmap[(unsigned)_z << 4 | _x] & 0xff); } this->minHeight = min; } int xOffs = (this->x * 16) + x; int zOffs = (this->z * 16) + z; - if (!level->dimension->hasCeiling) - { - if (y < yOld) - { - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - for (int yy = y; yy < yOld; yy++) - { - skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - skyLight->set(x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, 15); - } - } else - { - // 4J - lighting change brought forward from 1.8.2 - // level->updateLight(LightLayer::Sky, xOffs, yOld, zOffs, xOffs, y, zOffs); - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - for (int yy = yOld; yy < y; yy++) - { - skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - skyLight->set(x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, 0); - } - } + if (!level->dimension->hasCeiling) { + if (y < yOld) { + SparseLightStorage* skyLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + for (int yy = y; yy < yOld; yy++) { + skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + skyLight->set(x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), + z, 15); + } + } else { + // 4J - lighting change brought forward from 1.8.2 + // level->updateLight(LightLayer::Sky, xOffs, yOld, zOffs, + // xOffs, y, zOffs); + SparseLightStorage* skyLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + for (int yy = yOld; yy < y; yy++) { + skyLight = yy >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + skyLight->set(x, (yy % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), + z, 0); + } + } - int br = 15; - - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - while (y > 0 && br > 0) - { - y--; - skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT? upperSkyLight : lowerSkyLight; - int block = Tile::lightBlock[getTile(x, y, z)]; - if (block == 0) block = 1; - br -= block; - if (br < 0) br = 0; - skyLight->set(x, (y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, br); - // level.updateLightIfOtherThan(LightLayer.Sky, xOffs, y, zOffs, - // -1); - } - } - // 4J - changed to use xOffs and zOffs rather than the (incorrect) x and z it used to, and also moved so that it happens after all the lighting should be - // done by this stage, as this will trigger our asynchronous render updates immediately (potentially) so don't want to say that the lighting is done & then do it - level->lightColumnChanged(xOffs, zOffs, y, yOld); + int br = 15; - // 4J - lighting changes brought forward from 1.8.2 - int height = heightmap[(unsigned) z << 4 | x]; + SparseLightStorage* skyLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + while (y > 0 && br > 0) { + y--; + skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + int block = Tile::lightBlock[getTile(x, y, z)]; + if (block == 0) block = 1; + br -= block; + if (br < 0) br = 0; + skyLight->set(x, (y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT), z, + br); + // level.updateLightIfOtherThan(LightLayer.Sky, xOffs, y, zOffs, + // -1); + } + } + // 4J - changed to use xOffs and zOffs rather than the (incorrect) x and z + // it used to, and also moved so that it happens after all the lighting + // should be done by this stage, as this will trigger our asynchronous + // render updates immediately (potentially) so don't want to say that the + // lighting is done & then do it + level->lightColumnChanged(xOffs, zOffs, y, yOld); + + // 4J - lighting changes brought forward from 1.8.2 + int height = heightmap[(unsigned)z << 4 | x]; int y1 = yOld; int y2 = height; - if (y2 < y1) - { + if (y2 < y1) { int tmp = y1; y1 = y2; y2 = tmp; } - if (!level->dimension->hasCeiling) - { - PIXBeginNamedEvent(0,"Light gaps"); - lightGap(xOffs - 1, zOffs, y1, y2); - lightGap(xOffs + 1, zOffs, y1, y2); - lightGap(xOffs, zOffs - 1, y1, y2); - lightGap(xOffs, zOffs + 1, y1, y2); - lightGap(xOffs, zOffs, y1, y2); - PIXEndNamedEvent(); - } + if (!level->dimension->hasCeiling) { + PIXBeginNamedEvent(0, "Light gaps"); + lightGap(xOffs - 1, zOffs, y1, y2); + lightGap(xOffs + 1, zOffs, y1, y2); + lightGap(xOffs, zOffs - 1, y1, y2); + lightGap(xOffs, zOffs + 1, y1, y2); + lightGap(xOffs, zOffs, y1, y2); + PIXEndNamedEvent(); + } this->setUnsaved(true); } /** -* The purpose of this method is to allow the EmptyLevelChunk to be all air -* but still block light. See EmptyLevelChunk.java -* -* @param x -* @param y -* @param z -* @return -*/ -int LevelChunk::getTileLightBlock(int x, int y, int z) -{ - return Tile::lightBlock[getTile(x, y, z)]; + * The purpose of this method is to allow the EmptyLevelChunk to be all air + * but still block light. See EmptyLevelChunk.java + * + * @param x + * @param y + * @param z + * @return + */ +int LevelChunk::getTileLightBlock(int x, int y, int z) { + return Tile::lightBlock[getTile(x, y, z)]; } -int LevelChunk::getTile(int x, int y, int z) -{ - CompressedTileStorage *blocks = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks : lowerBlocks; - return blocks->get(x,y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z); +int LevelChunk::getTile(int x, int y, int z) { + CompressedTileStorage* blocks = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks : lowerBlocks; + return blocks->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); } -bool LevelChunk::setTileAndData(int x, int y, int z, int _tile, int _data) -{ - uint8_t tile = (uint8_t) _tile; +bool LevelChunk::setTileAndData(int x, int y, int z, int _tile, int _data) { + uint8_t tile = (uint8_t)_tile; - // Optimisation brought forward from 1.8.2, change from int to unsigned char & this special value changed from -999 to 255 - int slot = (unsigned) z << 4 | x; + // Optimisation brought forward from 1.8.2, change from int to unsigned char + // & this special value changed from -999 to 255 + int slot = (unsigned)z << 4 | x; - if (y >= ((int)rainHeights[slot]) - 1) - { + if (y >= ((int)rainHeights[slot]) - 1) { rainHeights[slot] = 255; } int oldHeight = heightmap[slot] & 0xff; - - CompressedTileStorage *blocks = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks : lowerBlocks; - SparseDataStorage *data = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; - int old = blocks->get(x,y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z); - int oldData = data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + + CompressedTileStorage* blocks = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlocks : lowerBlocks; + SparseDataStorage* data = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; + int old = blocks->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + int oldData = data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); if (old == _tile && oldData == _data) return false; int xOffs = this->x * 16 + x; int zOffs = this->z * 16 + z; - if (old != 0 && !level->isClientSide) - { - Tile::tiles[old]->onRemoving(level, xOffs, y, zOffs, oldData); - } - PIXBeginNamedEvent(0,"Chunk setting tile"); - blocks->set(x,y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z,tile); - PIXEndNamedEvent(); - if (old != 0) - { - if (!level->isClientSide) - { - Tile::tiles[old]->onRemove(level, xOffs, y, zOffs, old, oldData); - } - else if (Tile::tiles[old]->isEntityTile() && old != _tile ) - { - level->removeTileEntity(xOffs, y, zOffs); - } + if (old != 0 && !level->isClientSide) { + Tile::tiles[old]->onRemoving(level, xOffs, y, zOffs, oldData); } - PIXBeginNamedEvent(0,"Chunk setting data"); - data->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, _data); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Chunk setting tile"); + blocks->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, tile); + PIXEndNamedEvent(); + if (old != 0) { + if (!level->isClientSide) { + Tile::tiles[old]->onRemove(level, xOffs, y, zOffs, old, oldData); + } else if (Tile::tiles[old]->isEntityTile() && old != _tile) { + level->removeTileEntity(xOffs, y, zOffs); + } + } + PIXBeginNamedEvent(0, "Chunk setting data"); + data->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, _data); + PIXEndNamedEvent(); - // 4J added - flag if something emissive is being added. This is used during level creation to determine what chunks need extra lighting processing - if( Tile::lightEmission[tile & 0xff] > 0 ) - { - emissiveAdded = true; - } + // 4J added - flag if something emissive is being added. This is used during + // level creation to determine what chunks need extra lighting processing + if (Tile::lightEmission[tile & 0xff] > 0) { + emissiveAdded = true; + } - PIXBeginNamedEvent(0,"Updating lighting"); - // 4J - There isn't any point in recalculating heights or updating sky lighting if this tile has - // the same light-blocking capabilities as the one it is replacing - if( Tile::lightBlock[tile & 0xff] != Tile::lightBlock[old & 0xff] ) - { - if (!level->dimension->hasCeiling) - { - if (Tile::lightBlock[tile & 0xff] != 0) - { - if (y >= oldHeight) - { - PIXBeginNamedEvent(0,"Recalc height 1"); - recalcHeight(x, y + 1, z); - PIXEndNamedEvent(); - } - } else - { - if (y == oldHeight - 1) - { - PIXBeginNamedEvent(0,"Recalc height 2"); - recalcHeight(x, y, z); - PIXEndNamedEvent(); - } - } - } + PIXBeginNamedEvent(0, "Updating lighting"); + // 4J - There isn't any point in recalculating heights or updating sky + // lighting if this tile has the same light-blocking capabilities as the one + // it is replacing + if (Tile::lightBlock[tile & 0xff] != Tile::lightBlock[old & 0xff]) { + if (!level->dimension->hasCeiling) { + if (Tile::lightBlock[tile & 0xff] != 0) { + if (y >= oldHeight) { + PIXBeginNamedEvent(0, "Recalc height 1"); + recalcHeight(x, y + 1, z); + PIXEndNamedEvent(); + } + } else { + if (y == oldHeight - 1) { + PIXBeginNamedEvent(0, "Recalc height 2"); + recalcHeight(x, y, z); + PIXEndNamedEvent(); + } + } + } - // level.updateLight(LightLayer.Carried, xOffs, y, zOffs, xOffs, y, - // zOffs); - PIXBeginNamedEvent(0,"Lighting gaps"); - lightGaps(x, z); - PIXEndNamedEvent(); - } - PIXEndNamedEvent(); - data->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, _data); - if (_tile != 0) - { - if (!level->isClientSide) - { - Tile::tiles[_tile]->onPlace(level, xOffs, y, zOffs); - } - else - { - // 4J - in general we don't want to run the onPlace method on the client, but do a specific bit of the fireTile onPlace code here, - // otherwise we'll place fire on the client and if it isn't a suitable location then we have to wait a few frames before the server - // updates us to say it wasn't right. In the meantime, the client will have done some local lighting etc. and we can end up - // with errors when the update from the server comes in. - if( _tile == Tile::fire_Id ) - { - if(!Tile::tiles[_tile]->mayPlace(level, xOffs, y, zOffs )) - { - blocks->set(x,y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT,z,0); -// blocks[x << level->depthBitsPlusFour | z << level->depthBits | y] = 0; - } - } - } - // AP - changed the method of EntityTile detection cos it's well slow on Vita mate -// if (_tile > 0 && dynamic_cast(Tile::tiles[_tile]) != NULL) - if (_tile > 0 && Tile::tiles[_tile] != NULL && Tile::tiles[_tile]->isEntityTile()) - { - std::shared_ptr te = getTileEntity(x, y, z); - if (te == NULL) - { - te = ((EntityTile *) Tile::tiles[_tile])->newTileEntity(level); - //app.DebugPrintf("%s: Setting tile id %d, created tileEntity type %d\n", level->isClientSide?"Client":"Server", _tile, te->GetType()); - level->setTileEntity(xOffs, y, zOffs, te); - } - if (te != NULL) - { - //app.DebugPrintf("%s: Setting tile id %d, found tileEntity type %d\n", level->isClientSide?"Client":"Server", _tile, te->GetType()); - te->clearCache(); - } - } - } - // AP - changed the method of EntityTile detection cos it's well slow on Vita mate -// else if (old > 0 && dynamic_cast(Tile::tiles[old]) != NULL) - else if (old > 0 && Tile::tiles[_tile] != NULL && Tile::tiles[_tile]->isEntityTile()) - { - std::shared_ptr te = getTileEntity(x, y, z); - if (te != NULL) - { - te->clearCache(); - } + // level.updateLight(LightLayer.Carried, xOffs, y, zOffs, xOffs, y, + // zOffs); + PIXBeginNamedEvent(0, "Lighting gaps"); + lightGaps(x, z); + PIXEndNamedEvent(); + } + PIXEndNamedEvent(); + data->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, _data); + if (_tile != 0) { + if (!level->isClientSide) { + Tile::tiles[_tile]->onPlace(level, xOffs, y, zOffs); + } else { + // 4J - in general we don't want to run the onPlace method on the + // client, but do a specific bit of the fireTile onPlace code here, + // otherwise we'll place fire on the client and if it isn't a + // suitable location then we have to wait a few frames before the + // server updates us to say it wasn't right. In the meantime, the + // client will have done some local lighting etc. and we can end up + // with errors when the update from the server comes in. + if (_tile == Tile::fire_Id) { + if (!Tile::tiles[_tile]->mayPlace(level, xOffs, y, zOffs)) { + blocks->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, + z, 0); + // blocks[x << + //level->depthBitsPlusFour | z << level->depthBits | y] = 0; + } + } + } + // AP - changed the method of EntityTile detection cos it's well slow on + // Vita mate + // if (_tile > 0 && dynamic_cast(Tile::tiles[_tile]) != NULL) + if (_tile > 0 && Tile::tiles[_tile] != NULL && + Tile::tiles[_tile]->isEntityTile()) { + std::shared_ptr te = getTileEntity(x, y, z); + if (te == NULL) { + te = ((EntityTile*)Tile::tiles[_tile])->newTileEntity(level); + // app.DebugPrintf("%s: Setting tile id %d, created tileEntity + // type %d\n", level->isClientSide?"Client":"Server", _tile, + // te->GetType()); + level->setTileEntity(xOffs, y, zOffs, te); + } + if (te != NULL) { + // app.DebugPrintf("%s: Setting tile id %d, found tileEntity + // type %d\n", level->isClientSide?"Client":"Server", _tile, + // te->GetType()); + te->clearCache(); + } + } + } + // AP - changed the method of EntityTile detection cos it's well slow on + // Vita mate + // else if (old > 0 && dynamic_cast(Tile::tiles[old]) != + //NULL) + else if (old > 0 && Tile::tiles[_tile] != NULL && + Tile::tiles[_tile]->isEntityTile()) { + std::shared_ptr te = getTileEntity(x, y, z); + if (te != NULL) { + te->clearCache(); + } } this->setUnsaved(true); return true; } -bool LevelChunk::setTile(int x, int y, int z, int _tile) -{ - // 4J Stu - Now using setTileAndData (like in 1.5 Java) so there is only one place we have to fix things - return setTileAndData(x,y,z,_tile,0); +bool LevelChunk::setTile(int x, int y, int z, int _tile) { + // 4J Stu - Now using setTileAndData (like in 1.5 Java) so there is only one + // place we have to fix things + return setTileAndData(x, y, z, _tile, 0); } -int LevelChunk::getData(int x, int y, int z) -{ - SparseDataStorage *data = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; - return data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); +int LevelChunk::getData(int x, int y, int z) { + SparseDataStorage* data = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; + return data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); } -bool LevelChunk::setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged) -{ - SparseDataStorage *data = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; +bool LevelChunk::setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged) { + SparseDataStorage* data = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperData : lowerData; this->setUnsaved(true); - int old = data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + int old = data->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - *maskedBitsChanged = ( ( old & mask ) != ( val & mask ) ); + *maskedBitsChanged = ((old & mask) != (val & mask)); - if (old == val) - { + if (old == val) { return false; } data->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, val); - int _tile = getTile(x, y, z); - if (_tile > 0 && dynamic_cast( Tile::tiles[_tile] ) != NULL) - { - std::shared_ptr te = getTileEntity(x, y, z); - if (te != NULL) - { - te->clearCache(); - te->data = val; - } - } - return true; + int _tile = getTile(x, y, z); + if (_tile > 0 && dynamic_cast(Tile::tiles[_tile]) != NULL) { + std::shared_ptr te = getTileEntity(x, y, z); + if (te != NULL) { + te->clearCache(); + te->data = val; + } + } + return true; } -int LevelChunk::getBrightness(LightLayer::variety layer, int x, int y, int z) -{ - if (layer == LightLayer::Sky) - { - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - if(!skyLight) return 0; - return skyLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - } - else if (layer == LightLayer::Block) - { - SparseLightStorage *blockLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - if(!blockLight) return 0; - return blockLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - } - else return 0; +int LevelChunk::getBrightness(LightLayer::variety layer, int x, int y, int z) { + if (layer == LightLayer::Sky) { + SparseLightStorage* skyLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + if (!skyLight) return 0; + return skyLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + } else if (layer == LightLayer::Block) { + SparseLightStorage* blockLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight + : lowerBlockLight; + if (!blockLight) return 0; + return blockLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, + z); + } else + return 0; } // 4J added -void LevelChunk::getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z) -{ - SparseLightStorage *light; - if( layer == LightLayer::Sky ) light = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - else light = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - - if(light) - { - brightnesses[0] = light->get(x - 1, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - brightnesses[1] = light->get(x + 1, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - brightnesses[4] = light->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z - 1); - brightnesses[5] = light->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z + 1); - } - - - if( layer == LightLayer::Sky ) light = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - else light = (y-1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - if(light) brightnesses[2] = light->get(x, (y - 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); - - - if( layer == LightLayer::Sky ) light = (y+1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - else light = (y+1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - if(light) brightnesses[3] = light->get(x, (y + 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); -} - -void LevelChunk::setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness) -{ - this->setUnsaved(true); +void LevelChunk::getNeighbourBrightnesses(int* brightnesses, + LightLayer::variety layer, int x, + int y, int z) { + SparseLightStorage* light; if (layer == LightLayer::Sky) - { - if(!level->dimension->hasCeiling) - { - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - skyLight->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, brightness); - } - } - else if (layer == LightLayer::Block) - { - SparseLightStorage *blockLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - blockLight->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, brightness); - } + light = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + else + light = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight + : lowerBlockLight; + + if (light) { + brightnesses[0] = + light->get(x - 1, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + brightnesses[1] = + light->get(x + 1, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + brightnesses[4] = + light->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z - 1); + brightnesses[5] = + light->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z + 1); + } + + if (layer == LightLayer::Sky) + light = (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + else + light = (y - 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlockLight + : lowerBlockLight; + if (light) + brightnesses[2] = + light->get(x, (y - 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + + if (layer == LightLayer::Sky) + light = (y + 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + else + light = (y + 1) >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlockLight + : lowerBlockLight; + if (light) + brightnesses[3] = + light->get(x, (y + 1) % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); } -int LevelChunk::getRawBrightness(int x, int y, int z, int skyDampen) -{ - SparseLightStorage *skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight : lowerSkyLight; - int light = level->dimension->hasCeiling ? 0 : skyLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); +void LevelChunk::setBrightness(LightLayer::variety layer, int x, int y, int z, + int brightness) { + this->setUnsaved(true); + if (layer == LightLayer::Sky) { + if (!level->dimension->hasCeiling) { + SparseLightStorage* skyLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperSkyLight + : lowerSkyLight; + skyLight->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, + brightness); + } + } else if (layer == LightLayer::Block) { + SparseLightStorage* blockLight = + y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight + : lowerBlockLight; + blockLight->set(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z, + brightness); + } +} + +int LevelChunk::getRawBrightness(int x, int y, int z, int skyDampen) { + SparseLightStorage* skyLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperSkyLight + : lowerSkyLight; + int light = + level->dimension->hasCeiling + ? 0 + : skyLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); if (light > 0) LevelChunk::touchedSky = true; light -= skyDampen; - SparseLightStorage *blockLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ? upperBlockLight : lowerBlockLight; - int block = blockLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); + SparseLightStorage* blockLight = y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT + ? upperBlockLight + : lowerBlockLight; + int block = + blockLight->get(x, y % Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z); if (block > light) light = block; /* - * int xd = (absFloor(level.player.x-(this->x*16+x))); int yd = - * (absFloor(level.player.y-(y))); int zd = - * (absFloor(level.player.z-(this->z*16+z))); int dd = xd+yd+zd; if - * (dd<15){ int carried = 15-dd; if (carried<0) carried = 0; if - * (carried>15) carried = 15; if (carried > light) light = carried; } - */ + * int xd = (absFloor(level.player.x-(this->x*16+x))); int yd = + * (absFloor(level.player.y-(y))); int zd = + * (absFloor(level.player.z-(this->z*16+z))); int dd = xd+yd+zd; if + * (dd<15){ int carried = 15-dd; if (carried<0) carried = 0; if + * (carried>15) carried = 15; if (carried > light) light = carried; } + */ return light; } -void LevelChunk::addEntity(std::shared_ptr e) -{ +void LevelChunk::addEntity(std::shared_ptr e) { lastSaveHadEntities = true; int xc = Mth::floor(e->x / 16); int zc = Mth::floor(e->z / 16); - if (xc != this->x || zc != this->z) - { - app.DebugPrintf("Wrong location!"); -// System.out.println("Wrong location! " + e); -// Thread.dumpStack(); + if (xc != this->x || zc != this->z) { + app.DebugPrintf("Wrong location!"); + // System.out.println("Wrong location! " + e); + // Thread.dumpStack(); } int yc = Mth::floor(e->y / 16); if (yc < 0) yc = 0; - if (yc >= ENTITY_BLOCKS_LENGTH) yc = ENTITY_BLOCKS_LENGTH - 1; + if (yc >= ENTITY_BLOCKS_LENGTH) yc = ENTITY_BLOCKS_LENGTH - 1; e->inChunk = true; e->xChunk = x; e->yChunk = yc; e->zChunk = z; #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - entityBlocks[yc]->push_back(e); + entityBlocks[yc]->push_back(e); #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif } - -void LevelChunk::removeEntity(std::shared_ptr e) -{ +void LevelChunk::removeEntity(std::shared_ptr e) { removeEntity(e, e->yChunk); } -void LevelChunk::removeEntity(std::shared_ptr e, int yc) -{ +void LevelChunk::removeEntity(std::shared_ptr e, int yc) { if (yc < 0) yc = 0; if (yc >= ENTITY_BLOCKS_LENGTH) yc = ENTITY_BLOCKS_LENGTH - 1; #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - // 4J - was entityBlocks[yc]->remove(e); - AUTO_VAR(it, find(entityBlocks[yc]->begin(),entityBlocks[yc]->end(),e)); - if( it != entityBlocks[yc]->end() ) - { - entityBlocks[yc]->erase(it); - // 4J - we don't want storage creeping up here as thinkgs move round the world accumulating up spare space - MemSect(31); + // 4J - was entityBlocks[yc]->remove(e); + AUTO_VAR(it, find(entityBlocks[yc]->begin(), entityBlocks[yc]->end(), e)); + if (it != entityBlocks[yc]->end()) { + entityBlocks[yc]->erase(it); + // 4J - we don't want storage creeping up here as thinkgs move round the + // world accumulating up spare space + MemSect(31); #ifdef __PS3__ - // MGH - have to sort this C++11 code - static bool bShowMsg = true; - if(bShowMsg) - { - app.DebugPrintf("Need to add C++11 shrink_to_fit for PS3\n"); - bShowMsg = false; - } + // MGH - have to sort this C++11 code + static bool bShowMsg = true; + if (bShowMsg) { + app.DebugPrintf("Need to add C++11 shrink_to_fit for PS3\n"); + bShowMsg = false; + } #else - entityBlocks[yc]->shrink_to_fit(); + entityBlocks[yc]->shrink_to_fit(); #endif - MemSect(0); - } + MemSect(0); + } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif } -bool LevelChunk::isSkyLit(int x, int y, int z) -{ - return y >= (heightmap[(unsigned) z << 4 | x] & 0xff); +bool LevelChunk::isSkyLit(int x, int y, int z) { + return y >= (heightmap[(unsigned)z << 4 | x] & 0xff); } -void LevelChunk::skyBrightnessChanged() -{ +void LevelChunk::skyBrightnessChanged() { int x0 = this->x * 16; int y0 = this->minHeight - 16; int z0 = this->z * 16; @@ -1261,81 +1336,78 @@ void LevelChunk::skyBrightnessChanged() level->setTilesDirty(x0, y0, z0, x1, y1, z1); } -std::shared_ptr LevelChunk::getTileEntity(int x, int y, int z) -{ +std::shared_ptr LevelChunk::getTileEntity(int x, int y, int z) { TilePos pos(x, y, z); - // 4J Stu - Changed as we should not be using the [] accessor (causes an insert when we don't want one) - //std::shared_ptr tileEntity = tileEntities[pos]; - EnterCriticalSection(&m_csTileEntities); - std::shared_ptr tileEntity = nullptr; - AUTO_VAR(it, tileEntities.find(pos)); + // 4J Stu - Changed as we should not be using the [] accessor (causes an + // insert when we don't want one) + // std::shared_ptr tileEntity = tileEntities[pos]; + EnterCriticalSection(&m_csTileEntities); + std::shared_ptr tileEntity = nullptr; + AUTO_VAR(it, tileEntities.find(pos)); - if (it == tileEntities.end()) - { - LeaveCriticalSection(&m_csTileEntities); // Note: don't assume iterator is valid for tileEntities after this point + if (it == tileEntities.end()) { + LeaveCriticalSection( + &m_csTileEntities); // Note: don't assume iterator is valid for + // tileEntities after this point - // Fix for #48450 - All: Code Defect: Hang: Game hangs in tutorial, when player arrive at the particular coordinate - // 4J Stu - Chests try to get their neighbours when being destroyed, - // which then causes new tile entities to be created if the neighbour has already been destroyed - if(level->m_bDisableAddNewTileEntities) return nullptr; + // Fix for #48450 - All: Code Defect: Hang: Game hangs in tutorial, when + // player arrive at the particular coordinate 4J Stu - Chests try to get + // their neighbours when being destroyed, which then causes new tile + // entities to be created if the neighbour has already been destroyed + if (level->m_bDisableAddNewTileEntities) return nullptr; int t = getTile(x, y, z); if (t <= 0 || !Tile::tiles[t]->isEntityTile()) return nullptr; - - // 4J-PB changed from this in 1.7.3 - //EntityTile *et = (EntityTile *) Tile::tiles[t]; - //et->onPlace(level, this->x * 16 + x, y, this->z * 16 + z); - //if (tileEntity == NULL) - //{ - tileEntity = ((EntityTile *) Tile::tiles[t])->newTileEntity(level); - level->setTileEntity(this->x * 16 + x, y, this->z * 16 + z, tileEntity); - //} + // 4J-PB changed from this in 1.7.3 + // EntityTile *et = (EntityTile *) Tile::tiles[t]; + // et->onPlace(level, this->x * 16 + x, y, this->z * 16 + z); - //tileEntity = tileEntities[pos]; // 4J - TODO - this doesn't seem right - assignment wrong way? Check + // if (tileEntity == NULL) + //{ + tileEntity = ((EntityTile*)Tile::tiles[t])->newTileEntity(level); + level->setTileEntity(this->x * 16 + x, y, this->z * 16 + z, tileEntity); + //} - // 4J Stu - It should have been inserted by now, but check to be sure - EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(newIt, tileEntities.find(pos)); - if (newIt != tileEntities.end()) - { - tileEntity = newIt->second; - } - LeaveCriticalSection(&m_csTileEntities); + // tileEntity = tileEntities[pos]; // 4J - TODO - this + // doesn't seem right - assignment wrong way? Check + + // 4J Stu - It should have been inserted by now, but check to be sure + EnterCriticalSection(&m_csTileEntities); + AUTO_VAR(newIt, tileEntities.find(pos)); + if (newIt != tileEntities.end()) { + tileEntity = newIt->second; + } + LeaveCriticalSection(&m_csTileEntities); + } else { + tileEntity = it->second; + LeaveCriticalSection(&m_csTileEntities); } - else - { - tileEntity = it->second; - LeaveCriticalSection(&m_csTileEntities); - } - if (tileEntity != NULL && tileEntity->isRemoved()) - { - EnterCriticalSection(&m_csTileEntities); + if (tileEntity != NULL && tileEntity->isRemoved()) { + EnterCriticalSection(&m_csTileEntities); tileEntities.erase(pos); - LeaveCriticalSection(&m_csTileEntities); + LeaveCriticalSection(&m_csTileEntities); return nullptr; } - + return tileEntity; } -void LevelChunk::addTileEntity(std::shared_ptr te) -{ +void LevelChunk::addTileEntity(std::shared_ptr te) { int xx = (int)(te->x - this->x * 16); int yy = (int)te->y; int zz = (int)(te->z - this->z * 16); setTileEntity(xx, yy, zz, te); - if( loaded ) - { - EnterCriticalSection(&level->m_tileEntityListCS); - level->tileEntityList.push_back(te); - LeaveCriticalSection(&level->m_tileEntityListCS); - } + if (loaded) { + EnterCriticalSection(&level->m_tileEntityListCS); + level->tileEntityList.push_back(te); + LeaveCriticalSection(&level->m_tileEntityListCS); + } } -void LevelChunk::setTileEntity(int x, int y, int z, std::shared_ptr tileEntity) -{ +void LevelChunk::setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity) { TilePos pos(x, y, z); tileEntity->setLevel(level); @@ -1343,558 +1415,591 @@ void LevelChunk::setTileEntity(int x, int y, int z, std::shared_ptr tileEntity->y = y; tileEntity->z = this->z * 16 + z; - if (getTile(x, y, z) == 0 || !Tile::tiles[getTile(x, y, z)]->isEntityTile()) // 4J - was !(Tile.tiles[getTile(x, y, z)] instanceof EntityTile)) - { - app.DebugPrintf("Attempted to place a tile entity where there was no entity tile!\n"); + if (getTile(x, y, z) == 0 || + !Tile::tiles[getTile(x, y, z)] + ->isEntityTile()) // 4J - was !(Tile.tiles[getTile(x, y, z)] + // instanceof EntityTile)) + { + app.DebugPrintf( + "Attempted to place a tile entity where there was no entity " + "tile!\n"); return; } - tileEntity->clearRemoved(); + tileEntity->clearRemoved(); - EnterCriticalSection(&m_csTileEntities); + EnterCriticalSection(&m_csTileEntities); tileEntities[pos] = tileEntity; - LeaveCriticalSection(&m_csTileEntities); + LeaveCriticalSection(&m_csTileEntities); } -void LevelChunk::removeTileEntity(int x, int y, int z) -{ +void LevelChunk::removeTileEntity(int x, int y, int z) { TilePos pos(x, y, z); - if (loaded) - { - // 4J - was: - // TileEntity removeThis = tileEntities.remove(pos); + if (loaded) { + // 4J - was: + // TileEntity removeThis = tileEntities.remove(pos); // if (removeThis != null) { // removeThis.setRemoved(); // } - EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(it, tileEntities.find(pos)); - if( it != tileEntities.end() ) - { - std::shared_ptr te = tileEntities[pos]; - tileEntities.erase(pos); - if( te != NULL ) - { - if(level->isClientSide) - { - app.DebugPrintf("Removing tile entity of type %d\n", te->GetType()); - } - te->setRemoved(); - } - } - LeaveCriticalSection(&m_csTileEntities); - } + EnterCriticalSection(&m_csTileEntities); + AUTO_VAR(it, tileEntities.find(pos)); + if (it != tileEntities.end()) { + std::shared_ptr te = tileEntities[pos]; + tileEntities.erase(pos); + if (te != NULL) { + if (level->isClientSide) { + app.DebugPrintf("Removing tile entity of type %d\n", + te->GetType()); + } + te->setRemoved(); + } + } + LeaveCriticalSection(&m_csTileEntities); + } } -void LevelChunk::load() -{ - loaded = true; +void LevelChunk::load() { + loaded = true; - if(!level->isClientSide) - { + if (!level->isClientSide) { #ifdef _LARGE_WORLDS - if(m_bUnloaded && m_unloadedEntitiesTag) - { - ListTag *entityTags = (ListTag *) m_unloadedEntitiesTag->getList(L"Entities"); - if (entityTags != NULL) - { - for (int i = 0; i < entityTags->size(); i++) - { - CompoundTag *teTag = entityTags->get(i); - std::shared_ptr te = EntityIO::loadStatic(teTag, level); - if (te != NULL) - { - addEntity(te); - } - } - } + if (m_bUnloaded && m_unloadedEntitiesTag) { + ListTag* entityTags = + (ListTag*)m_unloadedEntitiesTag->getList( + L"Entities"); + if (entityTags != NULL) { + for (int i = 0; i < entityTags->size(); i++) { + CompoundTag* teTag = entityTags->get(i); + std::shared_ptr te = + EntityIO::loadStatic(teTag, level); + if (te != NULL) { + addEntity(te); + } + } + } - ListTag *tileEntityTags = (ListTag *) m_unloadedEntitiesTag->getList(L"TileEntities"); - if (tileEntityTags != NULL) - { - for (int i = 0; i < tileEntityTags->size(); i++) - { - CompoundTag *teTag = tileEntityTags->get(i); - std::shared_ptr te = TileEntity::loadStatic(teTag); - if (te != NULL) - { - addTileEntity(te); - } - } - } - delete m_unloadedEntitiesTag; - m_unloadedEntitiesTag = NULL; - m_bUnloaded = false; - } + ListTag* tileEntityTags = + (ListTag*)m_unloadedEntitiesTag->getList( + L"TileEntities"); + if (tileEntityTags != NULL) { + for (int i = 0; i < tileEntityTags->size(); i++) { + CompoundTag* teTag = tileEntityTags->get(i); + std::shared_ptr te = + TileEntity::loadStatic(teTag); + if (te != NULL) { + addTileEntity(te); + } + } + } + delete m_unloadedEntitiesTag; + m_unloadedEntitiesTag = NULL; + m_bUnloaded = false; + } #endif - std::vector< std::shared_ptr > values; - EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) - { - values.push_back(it->second); - } - LeaveCriticalSection(&m_csTileEntities); - level->addAllPendingTileEntities(values); + std::vector > values; + EnterCriticalSection(&m_csTileEntities); + for (AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); + it++) { + values.push_back(it->second); + } + LeaveCriticalSection(&m_csTileEntities); + level->addAllPendingTileEntities(values); #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) - { - level->addEntities(entityBlocks[i]); - } + for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { + level->addEntities(entityBlocks[i]); + } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif - } - else - { + } else { #ifdef _LARGE_WORLDS - m_bUnloaded = false; + m_bUnloaded = false; #endif - } + } } -void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter +void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter { loaded = false; - if( unloadTileEntities ) - { - EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) - { - // 4J-PB -m 1.7.3 was it->second->setRemoved(); - level->markForRemoval(it->second); - } - LeaveCriticalSection(&m_csTileEntities); - } + if (unloadTileEntities) { + EnterCriticalSection(&m_csTileEntities); + for (AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); + it++) { + // 4J-PB -m 1.7.3 was it->second->setRemoved(); + level->markForRemoval(it->second); + } + LeaveCriticalSection(&m_csTileEntities); + } #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, true); + EnterCriticalRWSection(&m_csEntities, true); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) - { - level->removeEntities(entityBlocks[i]); - } + for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { + level->removeEntities(entityBlocks[i]); + } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, true); + LeaveCriticalRWSection(&m_csEntities, true); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif - //app.DebugPrintf("Unloaded chunk %d, %d\n", x, z); + // app.DebugPrintf("Unloaded chunk %d, %d\n", x, z); #ifdef _LARGE_WORLDS - if ( !m_bUnloaded ) // 4J-JEV: If we unload a chunk twice, we delete all the entities/tile-entities its saved in the entitiesTag. - { - m_bUnloaded = true; - if(!level->isClientSide) - { - delete m_unloadedEntitiesTag; - // 4J Stu - Save out entities to a cached format that won't interfere with other systems - m_unloadedEntitiesTag = new CompoundTag(); - PIXBeginNamedEvent(0,"Saving entities"); - ListTag *entityTags = new ListTag(); + if (!m_bUnloaded) // 4J-JEV: If we unload a chunk twice, we delete all the + // entities/tile-entities its saved in the entitiesTag. + { + m_bUnloaded = true; + if (!level->isClientSide) { + delete m_unloadedEntitiesTag; + // 4J Stu - Save out entities to a cached format that won't + // interfere with other systems + m_unloadedEntitiesTag = new CompoundTag(); + PIXBeginNamedEvent(0, "Saving entities"); + ListTag* entityTags = new ListTag(); - EnterCriticalSection(&m_csEntities); - for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) - { - AUTO_VAR(itEnd, entityBlocks[i]->end()); - for( std::vector >::iterator it = entityBlocks[i]->begin(); it != itEnd; it++ ) - { - std::shared_ptr e = *it; - CompoundTag *teTag = new CompoundTag(); - if (e->save(teTag)) - { - entityTags->add(teTag); - } + EnterCriticalSection(&m_csEntities); + for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { + AUTO_VAR(itEnd, entityBlocks[i]->end()); + for (std::vector >::iterator it = + entityBlocks[i]->begin(); + it != itEnd; it++) { + std::shared_ptr e = *it; + CompoundTag* teTag = new CompoundTag(); + if (e->save(teTag)) { + entityTags->add(teTag); + } + } - } + // Clear out this list + entityBlocks[i]->clear(); + } + LeaveCriticalSection(&m_csEntities); - // Clear out this list - entityBlocks[i]->clear(); - } - LeaveCriticalSection(&m_csEntities); + m_unloadedEntitiesTag->put(L"Entities", entityTags); + PIXEndNamedEvent(); - m_unloadedEntitiesTag->put(L"Entities", entityTags); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Saving tile entities"); + ListTag* tileEntityTags = new ListTag(); - PIXBeginNamedEvent(0,"Saving tile entities"); - ListTag *tileEntityTags = new ListTag(); + AUTO_VAR(itEnd, tileEntities.end()); + for (std::unordered_map, + TilePosKeyHash, TilePosKeyEq>::iterator it = + tileEntities.begin(); + it != itEnd; it++) { + std::shared_ptr te = it->second; + CompoundTag* teTag = new CompoundTag(); + te->save(teTag); + tileEntityTags->add(teTag); + } + // Clear out the tileEntities list + tileEntities.clear(); - AUTO_VAR(itEnd,tileEntities.end()); - for( std::unordered_map, TilePosKeyHash, TilePosKeyEq>::iterator it = tileEntities.begin(); - it != itEnd; it++) - { - std::shared_ptr te = it->second; - CompoundTag *teTag = new CompoundTag(); - te->save(teTag); - tileEntityTags->add(teTag); - } - // Clear out the tileEntities list - tileEntities.clear(); - - m_unloadedEntitiesTag->put(L"TileEntities", tileEntityTags); - PIXEndNamedEvent(); - } - } + m_unloadedEntitiesTag->put(L"TileEntities", tileEntityTags); + PIXEndNamedEvent(); + } + } #endif } #ifdef _LARGE_WORLDS -bool LevelChunk::isUnloaded() -{ - return m_bUnloaded; -} +bool LevelChunk::isUnloaded() { return m_bUnloaded; } #endif -void LevelChunk::markUnsaved() -{ - this->setUnsaved(true); -} +void LevelChunk::markUnsaved() { this->setUnsaved(true); } - -void LevelChunk::getEntities(std::shared_ptr except, AABB *bb, std::vector > &es) -{ +void LevelChunk::getEntities(std::shared_ptr except, AABB* bb, + std::vector >& es) { int yc0 = Mth::floor((bb->y0 - 2) / 16); int yc1 = Mth::floor((bb->y1 + 2) / 16); if (yc0 < 0) yc0 = 0; if (yc1 >= ENTITY_BLOCKS_LENGTH) yc1 = ENTITY_BLOCKS_LENGTH - 1; #ifndef __PSVITA__ - // AP - RW critical sections are expensive so enter once in Level::getEntities - EnterCriticalSection(&m_csEntities); + // AP - RW critical sections are expensive so enter once in + // Level::getEntities + EnterCriticalSection(&m_csEntities); #endif - for (int yc = yc0; yc <= yc1; yc++) - { - std::vector > *entities = entityBlocks[yc]; + for (int yc = yc0; yc <= yc1; yc++) { + std::vector >* entities = entityBlocks[yc]; - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); - if (e != except && e->bb->intersects(bb)) - { - es.push_back(e); - std::vector > *subs = e->getSubEntities(); - if (subs != NULL) - { - for (int j = 0; j < subs->size(); j++) - { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); + if (e != except && e->bb->intersects(bb)) { + es.push_back(e); + std::vector >* subs = + e->getSubEntities(); + if (subs != NULL) { + for (int j = 0; j < subs->size(); j++) { e = subs->at(j); - if (e != except && e->bb->intersects(bb)) - { + if (e != except && e->bb->intersects(bb)) { es.push_back(e); } } } - } + } } } #ifndef __PSVITA__ - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif } -void LevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB *bb, std::vector > &es) -{ +void LevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB* bb, + std::vector >& es) { int yc0 = Mth::floor((bb->y0 - 2) / 16); int yc1 = Mth::floor((bb->y1 + 2) / 16); - if (yc0 < 0) - { + if (yc0 < 0) { yc0 = 0; - } - else if (yc0 >= ENTITY_BLOCKS_LENGTH) - { + } else if (yc0 >= ENTITY_BLOCKS_LENGTH) { yc0 = ENTITY_BLOCKS_LENGTH - 1; } - if (yc1 >= ENTITY_BLOCKS_LENGTH) - { + if (yc1 >= ENTITY_BLOCKS_LENGTH) { yc1 = ENTITY_BLOCKS_LENGTH - 1; - } - else if (yc1 < 0) - { + } else if (yc1 < 0) { yc1 = 0; } #ifndef __PSVITA__ - // AP - RW critical sections are expensive so enter once in Level::getEntitiesOfClass - EnterCriticalSection(&m_csEntities); + // AP - RW critical sections are expensive so enter once in + // Level::getEntitiesOfClass + EnterCriticalSection(&m_csEntities); #endif - for (int yc = yc0; yc <= yc1; yc++) - { - std::vector > *entities = entityBlocks[yc]; - - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); + for (int yc = yc0; yc <= yc1; yc++) { + std::vector >* entities = entityBlocks[yc]; - bool isAssignableFrom = false; - // Some special cases where the base class is a general type that our class may be derived from, otherwise do a direct comparison of std::type_info - if( ec == typeid(Player) ) { if( std::dynamic_pointer_cast(e) != NULL ) isAssignableFrom = true; } - else if ( ec == typeid(Mob) ) { if( std::dynamic_pointer_cast(e) != NULL ) isAssignableFrom = true; } - else if ( ec == typeid(Monster) ) { if( std::dynamic_pointer_cast(e) != NULL ) isAssignableFrom = true; } - else if ( ec == typeid(Zombie) ) { if( std::dynamic_pointer_cast(e) != NULL ) isAssignableFrom = true; } - else - { - Entity *entityPtr = e.get(); - if(entityPtr != NULL && ec == typeid(*entityPtr)) isAssignableFrom = true; - } + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); + + bool isAssignableFrom = false; + // Some special cases where the base class is a general type that + // our class may be derived from, otherwise do a direct comparison + // of std::type_info + if (ec == typeid(Player)) { + if (std::dynamic_pointer_cast(e) != NULL) + isAssignableFrom = true; + } else if (ec == typeid(Mob)) { + if (std::dynamic_pointer_cast(e) != NULL) + isAssignableFrom = true; + } else if (ec == typeid(Monster)) { + if (std::dynamic_pointer_cast(e) != NULL) + isAssignableFrom = true; + } else if (ec == typeid(Zombie)) { + if (std::dynamic_pointer_cast(e) != NULL) + isAssignableFrom = true; + } else { + Entity* entityPtr = e.get(); + if (entityPtr != NULL && ec == typeid(*entityPtr)) + isAssignableFrom = true; + } if (isAssignableFrom && e->bb->intersects(bb)) es.push_back(e); - // 4J - note needs to be equivalent to baseClass.isAssignableFrom(e.getClass()) + // 4J - note needs to be equivalent to + // baseClass.isAssignableFrom(e.getClass()) } } #ifndef __PSVITA__ - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif } -int LevelChunk::countEntities() -{ +int LevelChunk::countEntities() { int entityCount = 0; #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&m_csEntities, false); + EnterCriticalRWSection(&m_csEntities, false); #else - EnterCriticalSection(&m_csEntities); + EnterCriticalSection(&m_csEntities); #endif - for (int yc = 0; yc < ENTITY_BLOCKS_LENGTH; yc++) - { + for (int yc = 0; yc < ENTITY_BLOCKS_LENGTH; yc++) { entityCount += (int)entityBlocks[yc]->size(); } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&m_csEntities, false); + LeaveCriticalRWSection(&m_csEntities, false); #else - LeaveCriticalSection(&m_csEntities); + LeaveCriticalSection(&m_csEntities); #endif - return entityCount; + return entityCount; } -bool LevelChunk::shouldSave(bool force) -{ +bool LevelChunk::shouldSave(bool force) { if (dontSave) return false; - if (force) - { - if (lastSaveHadEntities && level->getTime() != lastSaveTime) return true; + if (force) { + if (lastSaveHadEntities && level->getTime() != lastSaveTime) + return true; } else { - if (lastSaveHadEntities && level->getTime() >= lastSaveTime + 20 * 30) return true; + if (lastSaveHadEntities && level->getTime() >= lastSaveTime + 20 * 30) + return true; } return m_unsaved; } -int LevelChunk::getBlocksAndData(byteArray *data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting/* = true*/) -{ +int LevelChunk::getBlocksAndData(byteArray* data, int x0, int y0, int z0, + int x1, int y1, int z1, int p, + bool includeLighting /* = true*/) { int xs = x1 - x0; int ys = y1 - y0; int zs = z1 - z0; - // 4J Stu - Added this because some "min" functions don't let us use our constants :( - int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + // 4J Stu - Added this because some "min" functions don't let us use our + // constants :( + int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - // 4J - replaced block storage as now using CompressedTileStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerBlocks->getDataRegion( *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperBlocks->getDataRegion( *data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + // 4J - replaced block storage as now using CompressedTileStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerBlocks->getDataRegion(*data, x0, y0, z0, x1, + std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperBlocks->getDataRegion( + *data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - // 4J - replaced data storage as now using SparseDataStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerData->getDataRegion( *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperData->getDataRegion( *data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + // 4J - replaced data storage as now using SparseDataStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerData->getDataRegion(*data, x0, y0, z0, x1, + std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperData->getDataRegion( + *data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - if( includeLighting ) - { - // 4J - replaced block and skylight storage as these now use our SparseLightStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerBlockLight->getDataRegion( *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperBlockLight->getDataRegion( *data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + if (includeLighting) { + // 4J - replaced block and skylight storage as these now use our + // SparseLightStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerBlockLight->getDataRegion( + *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperBlockLight->getDataRegion( + *data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerSkyLight->getDataRegion( *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperSkyLight->getDataRegion( *data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); - } + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerSkyLight->getDataRegion( + *data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperSkyLight->getDataRegion( + *data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); + } - /* - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) >> 1; - int len = (y1 - y0) / 2; - System::arraycopy(blockLight->data, slot, data, p, len); - p += len; - } + /* +for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) + { + int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) +>> 1; int len = (y1 - y0) / 2; System::arraycopy(blockLight->data, slot, data, +p, len); p += len; + } - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) >> 1; - int len = (y1 - y0) / 2; - System::arraycopy(skyLight->data, slot, data, p, len); - p += len; - } - */ +for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) + { + int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) +>> 1; int len = (y1 - y0) / 2; System::arraycopy(skyLight->data, slot, data, p, +len); p += len; + } + */ return p; } // 4J added - return true if setBlocksAndData would change any blocks -bool LevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p) -{ - bool changed = false; +bool LevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, int z0, + int x1, int y1, int z1, int p) { + bool changed = false; - // 4J Stu - Added this because some "min" functions don't let us use our constants :( - int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + // 4J Stu - Added this because some "min" functions don't let us use our + // constants :( + int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) changed = lowerBlocks->testSetDataRegion(data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) changed = changed || upperBlocks->testSetDataRegion(data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + changed = lowerBlocks->testSetDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + changed = + changed || upperBlocks->testSetDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - return changed; + return changed; } -void LevelChunk::tileUpdatedCallback(int x, int y, int z, void *param, int yparam) -{ - LevelChunk *lc = (LevelChunk *)param; - int xx = lc->x * 16 + x; - int yy = y + yparam; - int zz = lc->z * 16 + z; - lc->level->checkLight(xx, yy, zz); +void LevelChunk::tileUpdatedCallback(int x, int y, int z, void* param, + int yparam) { + LevelChunk* lc = (LevelChunk*)param; + int xx = lc->x * 16 + x; + int yy = y + yparam; + int zz = lc->z * 16 + z; + lc->level->checkLight(xx, yy, zz); } -int LevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting/* = true*/) -{ - // If includeLighting is set, then this is a full chunk's worth of data that we are receiving on the client. We'll have made this chunk initially as compressed, - // so throw that data away and make some fully uncompressed storage now to improve the speed up writing to it. Only doing this for lower chunks as quite likely - // that the upper chunk doesn't have anything in anyway. - if( includeLighting ) - { - GameRenderer::AddForDelete(lowerBlocks); - byteArray emptyByteArray; - lowerBlocks = new CompressedTileStorage(emptyByteArray,0); - GameRenderer::FinishedReassigning(); +int LevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, + int y1, int z1, int p, + bool includeLighting /* = true*/) { + // If includeLighting is set, then this is a full chunk's worth of data that + // we are receiving on the client. We'll have made this chunk initially as + // compressed, so throw that data away and make some fully uncompressed + // storage now to improve the speed up writing to it. Only doing this for + // lower chunks as quite likely that the upper chunk doesn't have anything + // in anyway. + if (includeLighting) { + GameRenderer::AddForDelete(lowerBlocks); + byteArray emptyByteArray; + lowerBlocks = new CompressedTileStorage(emptyByteArray, 0); + GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(lowerSkyLight); - lowerSkyLight = new SparseLightStorage(true,false); - GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(lowerSkyLight); + lowerSkyLight = new SparseLightStorage(true, false); + GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(lowerBlockLight); - lowerBlockLight = new SparseLightStorage(false,false); - GameRenderer::FinishedReassigning(); + GameRenderer::AddForDelete(lowerBlockLight); + lowerBlockLight = new SparseLightStorage(false, false); + GameRenderer::FinishedReassigning(); - GameRenderer::AddForDelete(lowerData); - lowerData = new SparseDataStorage(false); - GameRenderer::FinishedReassigning(); - } + GameRenderer::AddForDelete(lowerData); + lowerData = new SparseDataStorage(false); + GameRenderer::FinishedReassigning(); + } - // 4J Stu - Added this because some "min" functions don't let us use our constants :( - int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + // 4J Stu - Added this because some "min" functions don't let us use our + // constants :( + int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - // 4J - replaced block storage as now uses CompressedTileStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerBlocks->setDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p, includeLighting ? NULL : tileUpdatedCallback, this, 0 ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperBlocks->setDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p, includeLighting ? NULL : tileUpdatedCallback, this, Level::COMPRESSED_CHUNK_SECTION_HEIGHT ); - /* - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - int slot = x << level->depthBitsPlusFour | z << level->depthBits | y0; - int len = y1 - y0; - System::arraycopy(data, p, &blocks, slot, len); - p += len; - }*/ + // 4J - replaced block storage as now uses CompressedTileStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerBlocks->setDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p, + includeLighting ? NULL : tileUpdatedCallback, this, 0); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperBlocks->setDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p, + includeLighting ? NULL : tileUpdatedCallback, this, + Level::COMPRESSED_CHUNK_SECTION_HEIGHT); + /* +for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) + { + int slot = x << level->depthBitsPlusFour | z << level->depthBits | y0; + int len = y1 - y0; + System::arraycopy(data, p, &blocks, slot, len); + p += len; + }*/ recalcHeightmapOnly(); - // 4J - replaced data storage as now uses SparseDataStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerData->setDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p, includeLighting ? NULL : tileUpdatedCallback, this, 0 ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperData->setDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p, includeLighting ? NULL : tileUpdatedCallback, this, Level::COMPRESSED_CHUNK_SECTION_HEIGHT ); + // 4J - replaced data storage as now uses SparseDataStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerData->setDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p, + includeLighting ? NULL : tileUpdatedCallback, this, 0); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperData->setDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p, + includeLighting ? NULL : tileUpdatedCallback, this, + Level::COMPRESSED_CHUNK_SECTION_HEIGHT); - if( includeLighting ) - { - // 4J - replaced block and skylight storage as these now use our SparseLightStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerBlockLight->setDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperBlockLight->setDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + if (includeLighting) { + // 4J - replaced block and skylight storage as these now use our + // SparseLightStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerBlockLight->setDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperBlockLight->setDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerSkyLight->setDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperSkyLight->setDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerSkyLight->setDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperSkyLight->setDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - memcpy(biomes.data, &data.data[p],biomes.length); - p += biomes.length; - } - else - { - // Because the host's local client shares data with it, the lighting updates that are done via callbacks in the setDataRegion calls above when things don't work, as they - // don't detect changes because they've already happened just because the data was being shared when the server updated them. This will leave the lighting information out of sync on - // the client, so resync for this & surrounding chunks that might have been affected - if( level->isClientSide && g_NetworkManager.IsHost() ) - { - reSyncLighting(); - level->getChunk(x-1,z-1)->reSyncLighting(); - level->getChunk(x-0,z-1)->reSyncLighting(); - level->getChunk(x+1,z-1)->reSyncLighting(); - level->getChunk(x-1,z+0)->reSyncLighting(); - level->getChunk(x+1,z+0)->reSyncLighting(); - level->getChunk(x-1,z+1)->reSyncLighting(); - level->getChunk(x+0,z+1)->reSyncLighting(); - level->getChunk(x+1,z+1)->reSyncLighting(); - } - } - - /* - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) >> 1; - int len = (y1 - y0) / 2; - System::arraycopy(data, p, &blockLight->data, slot, len); - p += len; + memcpy(biomes.data, &data.data[p], biomes.length); + p += biomes.length; + } else { + // Because the host's local client shares data with it, the lighting + // updates that are done via callbacks in the setDataRegion calls above + // when things don't work, as they don't detect changes because they've + // already happened just because the data was being shared when the + // server updated them. This will leave the lighting information out of + // sync on the client, so resync for this & surrounding chunks that + // might have been affected + if (level->isClientSide && g_NetworkManager.IsHost()) { + reSyncLighting(); + level->getChunk(x - 1, z - 1)->reSyncLighting(); + level->getChunk(x - 0, z - 1)->reSyncLighting(); + level->getChunk(x + 1, z - 1)->reSyncLighting(); + level->getChunk(x - 1, z + 0)->reSyncLighting(); + level->getChunk(x + 1, z + 0)->reSyncLighting(); + level->getChunk(x - 1, z + 1)->reSyncLighting(); + level->getChunk(x + 0, z + 1)->reSyncLighting(); + level->getChunk(x + 1, z + 1)->reSyncLighting(); } + } - for (int x = x0; x < x1; x++) - for (int z = z0; z < z1; z++) - { - int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) >> 1; - int len = (y1 - y0) / 2; - System::arraycopy(data, p, &skyLight->data, slot, len); - p += len; - } - */ + /* +for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) + { + int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) +>> 1; int len = (y1 - y0) / 2; System::arraycopy(data, p, &blockLight->data, +slot, len); p += len; + } - for(AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); ++it) - { - it->second->clearCache(); - } -// recalcHeightmap(); +for (int x = x0; x < x1; x++) + for (int z = z0; z < z1; z++) + { + int slot = (x << level->depthBitsPlusFour | z << level->depthBits | y0) +>> 1; int len = (y1 - y0) / 2; System::arraycopy(data, p, &skyLight->data, slot, +len); p += len; + } + */ - // If the includeLighting flag is set, then this is a full chunk's worth of data. This is a good time to compress everything that we've just set up. - if( includeLighting ) - { - compressLighting(); - compressBlocks(); - compressData(); - } + for (AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); ++it) { + it->second->clearCache(); + } + // recalcHeightmap(); + + // If the includeLighting flag is set, then this is a full chunk's worth of + // data. This is a good time to compress everything that we've just set up. + if (includeLighting) { + compressLighting(); + compressBlocks(); + compressData(); + } return p; } -void LevelChunk::setCheckAllLight() -{ - checkLightPosition = 0; +void LevelChunk::setCheckAllLight() { checkLightPosition = 0; } + +Random* LevelChunk::getRandom(__int64 l) { + return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + + z * z * 4392871l + z * 389711) ^ + l); } -Random *LevelChunk::getRandom(__int64 l) -{ - return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + z * z * 4392871l + z * 389711) ^ l); -} - -bool LevelChunk::isEmpty() -{ - return false; -} -void LevelChunk::attemptCompression() -{ - // 4J - removed +bool LevelChunk::isEmpty() { return false; } +void LevelChunk::attemptCompression() { + // 4J - removed #if 0 try { ByteArrayOutputStream *baos = new ByteArrayOutputStream(); @@ -1908,561 +2013,578 @@ void LevelChunk::attemptCompression() #endif } -void LevelChunk::checkPostProcess(ChunkSource *source, ChunkSource *parent, int x, int z) -{ - if ( ( ( terrainPopulated & sTerrainPopulatedFromHere ) == 0 ) && source->hasChunk(x + 1, z + 1) && source->hasChunk(x, z + 1) && source->hasChunk(x + 1, z)) - { - source->postProcess(parent, x, z); - } - if (source->hasChunk(x - 1, z) && ( (source->getChunk(x - 1, z)->terrainPopulated & sTerrainPopulatedFromHere ) == 0 ) && source->hasChunk(x - 1, z + 1) && source->hasChunk(x, z + 1) && source->hasChunk(x - 1, z + 1)) - { - source->postProcess(parent, x - 1, z); - } - if (source->hasChunk(x, z - 1) && ( (source->getChunk(x, z - 1)->terrainPopulated & sTerrainPopulatedFromHere ) == 0 ) && source->hasChunk(x + 1, z - 1) && source->hasChunk(x + 1, z)) - { - source->postProcess(parent, x, z - 1); - } - if (source->hasChunk(x - 1, z - 1) && ( (source->getChunk(x - 1, z - 1)->terrainPopulated & sTerrainPopulatedFromHere ) == 0 ) && source->hasChunk(x, z - 1) && source->hasChunk(x - 1, z)) - { - source->postProcess(parent, x - 1, z - 1); - } +void LevelChunk::checkPostProcess(ChunkSource* source, ChunkSource* parent, + int x, int z) { + if (((terrainPopulated & sTerrainPopulatedFromHere) == 0) && + source->hasChunk(x + 1, z + 1) && source->hasChunk(x, z + 1) && + source->hasChunk(x + 1, z)) { + source->postProcess(parent, x, z); + } + if (source->hasChunk(x - 1, z) && + ((source->getChunk(x - 1, z)->terrainPopulated & + sTerrainPopulatedFromHere) == 0) && + source->hasChunk(x - 1, z + 1) && source->hasChunk(x, z + 1) && + source->hasChunk(x - 1, z + 1)) { + source->postProcess(parent, x - 1, z); + } + if (source->hasChunk(x, z - 1) && + ((source->getChunk(x, z - 1)->terrainPopulated & + sTerrainPopulatedFromHere) == 0) && + source->hasChunk(x + 1, z - 1) && source->hasChunk(x + 1, z)) { + source->postProcess(parent, x, z - 1); + } + if (source->hasChunk(x - 1, z - 1) && + ((source->getChunk(x - 1, z - 1)->terrainPopulated & + sTerrainPopulatedFromHere) == 0) && + source->hasChunk(x, z - 1) && source->hasChunk(x - 1, z)) { + source->postProcess(parent, x - 1, z - 1); + } } -// 4J added - check for any pre-1.8.2 chests in the chunk at (x,z), and calculate their facing direction & relight to bring up to date with the post 1.8.2 build -void LevelChunk::checkChests(ChunkSource *source, int x, int z ) -{ - LevelChunk *lc = source->getChunk( x, z ); +// 4J added - check for any pre-1.8.2 chests in the chunk at (x,z), and +// calculate their facing direction & relight to bring up to date with the +// post 1.8.2 build +void LevelChunk::checkChests(ChunkSource* source, int x, int z) { + LevelChunk* lc = source->getChunk(x, z); - for( int xx = 0; xx < 16; xx++ ) - for( int zz = 0; zz < 16; zz++ ) - for( int yy = 0; yy < 128; yy++ ) - { - if( lc->getTile( xx, yy, zz ) == Tile::chest_Id ) - { - if( lc->getData( xx, yy, zz ) == 0 ) - { - int xOffs = x * 16 + xx; - int zOffs = z * 16 + zz; - ChestTile *tile = (ChestTile *)Tile::tiles[Tile::chest_Id]; - tile->recalcLockDir( level, xOffs, yy, zOffs ); - level->checkLight(xOffs, yy, zOffs, true); - } - } - } + for (int xx = 0; xx < 16; xx++) + for (int zz = 0; zz < 16; zz++) + for (int yy = 0; yy < 128; yy++) { + if (lc->getTile(xx, yy, zz) == Tile::chest_Id) { + if (lc->getData(xx, yy, zz) == 0) { + int xOffs = x * 16 + xx; + int zOffs = z * 16 + zz; + ChestTile* tile = + (ChestTile*)Tile::tiles[Tile::chest_Id]; + tile->recalcLockDir(level, xOffs, yy, zOffs); + level->checkLight(xOffs, yy, zOffs, true); + } + } + } } // 4J - lighting change brought forward from 1.8.2 -void LevelChunk::tick() -{ - if (hasGapsToCheck && !level->dimension->hasCeiling) recheckGaps(); +void LevelChunk::tick() { + if (hasGapsToCheck && !level->dimension->hasCeiling) recheckGaps(); } -ChunkPos *LevelChunk::getPos() -{ - return new ChunkPos(x, z); +ChunkPos* LevelChunk::getPos() { return new ChunkPos(x, z); } + +bool LevelChunk::isYSpaceEmpty(int y1, int y2) { + return false; + // 4J Unused + /*if (y1 < 0) { + y1 = 0; + } + if (y2 >= Level.maxBuildHeight) { + y2 = Level.maxBuildHeight - 1; + } + for (int y = y1; y <= y2; y += 16) { + LevelChunkSection section = sections[y >> 4]; + if (section != null && !section.isEmpty()) { + return false; + } + } + return true;*/ } -bool LevelChunk::isYSpaceEmpty(int y1, int y2) -{ - return false; - // 4J Unused - /*if (y1 < 0) { - y1 = 0; - } - if (y2 >= Level.maxBuildHeight) { - y2 = Level.maxBuildHeight - 1; - } - for (int y = y1; y <= y2; y += 16) { - LevelChunkSection section = sections[y >> 4]; - if (section != null && !section.isEmpty()) { - return false; - } - } - return true;*/ +Biome* LevelChunk::getBiome(int x, int z, BiomeSource* biomeSource) { + int value = biomes[((unsigned)z << 4) | x] & 0xff; + if (value == 0xff) { + // 4jcraft added casts to u + Biome* biome = biomeSource->getBiome(((unsigned)this->x << 4) + x, + ((unsigned)this->z << 4) + z); + value = biome->id; + biomes[((unsigned)z << 4) | x] = (uint8_t)(value & 0xff); + } + if (Biome::biomes[value] == NULL) { + return Biome::plains; + } + return Biome::biomes[value]; } -Biome *LevelChunk::getBiome(int x, int z, BiomeSource *biomeSource) -{ - int value = biomes[((unsigned) z << 4) | x] & 0xff; - if (value == 0xff) - { - // 4jcraft added casts to u - Biome *biome = biomeSource->getBiome(((unsigned) this->x << 4) + x, ((unsigned) this->z << 4) + z); - value = biome->id; - biomes[((unsigned) z << 4) | x] = (uint8_t) (value & 0xff); - } - if (Biome::biomes[value] == NULL) - { - return Biome::plains; - } - return Biome::biomes[value]; -} +byteArray LevelChunk::getBiomes() { return biomes; } -byteArray LevelChunk::getBiomes() -{ - return biomes; -} - -void LevelChunk::setBiomes(byteArray biomes) -{ - if(this->biomes.data != NULL) delete[] this->biomes.data; - this->biomes = biomes; +void LevelChunk::setBiomes(byteArray biomes) { + if (this->biomes.data != NULL) delete[] this->biomes.data; + this->biomes = biomes; } // 4J - optimisation brought forward from 1.8.2 -int LevelChunk::getTopRainBlock(int x, int z) -{ - int slot = x | ((unsigned) z << 4); +int LevelChunk::getTopRainBlock(int x, int z) { + int slot = x | ((unsigned)z << 4); int h = rainHeights[slot]; - if (h == 255) - { + if (h == 255) { int y = Level::maxBuildHeight - 1; h = -1; - while (y > 0 && h == -1) - { + while (y > 0 && h == -1) { int t = getTile(x, y, z); - Material *m = t == 0 ? Material::air : Tile::tiles[t]->material; - if (!m->blocksMotion() && !m->isLiquid()) - { + Material* m = t == 0 ? Material::air : Tile::tiles[t]->material; + if (!m->blocksMotion() && !m->isLiquid()) { y--; - } - else - { + } else { h = y + 1; } } - // 255 indicates that the rain height needs recalculated. If the rain height ever actually Does get to 255, then it will just keep not being cached, so - // probably better just to let the rain height be 254 in this instance and suffer a slightly incorrect results - if( h == 255 ) h = 254; - rainHeights[slot] = h; + // 255 indicates that the rain height needs recalculated. If the rain + // height ever actually Does get to 255, then it will just keep not + // being cached, so probably better just to let the rain height be 254 + // in this instance and suffer a slightly incorrect results + if (h == 255) h = 254; + rainHeights[slot] = h; } return h; } -// 4J added as optimisation, these biome checks are expensive so caching through flags in levelchunk -bool LevelChunk::biomeHasRain(int x, int z) -{ - updateBiomeFlags(x, z); - int slot = ( x >> 1 ) | (z * 8); - int shift = ( x & 1 ) * 4; - return ( ( columnFlags[slot] & ( eColumnFlag_biomeHasRain << shift ) ) != 0 ); +// 4J added as optimisation, these biome checks are expensive so caching through +// flags in levelchunk +bool LevelChunk::biomeHasRain(int x, int z) { + updateBiomeFlags(x, z); + int slot = (x >> 1) | (z * 8); + int shift = (x & 1) * 4; + return ((columnFlags[slot] & (eColumnFlag_biomeHasRain << shift)) != 0); } -// 4J added as optimisation, these biome checks are expensive so caching through flags in levelchunk -bool LevelChunk::biomeHasSnow(int x, int z) -{ - updateBiomeFlags(x, z); - int slot = ( x >> 1 ) | (z * 8); - int shift = ( x & 1 ) * 4; - return ( ( columnFlags[slot] & ( eColumnFlag_biomeHasSnow << shift ) ) != 0 ); +// 4J added as optimisation, these biome checks are expensive so caching through +// flags in levelchunk +bool LevelChunk::biomeHasSnow(int x, int z) { + updateBiomeFlags(x, z); + int slot = (x >> 1) | (z * 8); + int shift = (x & 1) * 4; + return ((columnFlags[slot] & (eColumnFlag_biomeHasSnow << shift)) != 0); } -void LevelChunk::updateBiomeFlags(int x, int z) -{ - int slot = ( x >> 1 ) | (z * 8); - int shift = ( x & 1 ) * 4; - if( ( columnFlags[slot] & ( eColumnFlag_biomeOk << shift ) ) == 0 ) - { - int xOffs = (this->x * 16) + x; - int zOffs = (this->z * 16) + z; - BiomeArray biomes; - level->getBiomeSource()->getBiomeBlock(biomes, xOffs, zOffs, 1, 1, true); - if( biomes[0]->hasRain()) columnFlags[slot] |= ( eColumnFlag_biomeHasRain << shift ); - if( biomes[0]->hasSnow()) columnFlags[slot] |= ( eColumnFlag_biomeHasSnow << shift ); - columnFlags[slot] |= ( eColumnFlag_biomeOk << shift ); - delete biomes.data; - } +void LevelChunk::updateBiomeFlags(int x, int z) { + int slot = (x >> 1) | (z * 8); + int shift = (x & 1) * 4; + if ((columnFlags[slot] & (eColumnFlag_biomeOk << shift)) == 0) { + int xOffs = (this->x * 16) + x; + int zOffs = (this->z * 16) + z; + BiomeArray biomes; + level->getBiomeSource()->getBiomeBlock(biomes, xOffs, zOffs, 1, 1, + true); + if (biomes[0]->hasRain()) + columnFlags[slot] |= (eColumnFlag_biomeHasRain << shift); + if (biomes[0]->hasSnow()) + columnFlags[slot] |= (eColumnFlag_biomeHasSnow << shift); + columnFlags[slot] |= (eColumnFlag_biomeOk << shift); + delete biomes.data; + } } -// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing data. Ordering same as java version if originalOrder set; -void LevelChunk::getDataData(byteArray data) -{ - lowerData->getData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperData->getData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing data. +// Ordering same as java version if originalOrder set; +void LevelChunk::getDataData(byteArray data) { + lowerData->getData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperData->getData(data, Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } -// Set data to data passed in input byte array of length 16384. This data must be in original (java version) order if originalOrder set. -void LevelChunk::setDataData(byteArray data) -{ - if( lowerData == NULL ) lowerData = new SparseDataStorage(); - if( upperData == NULL ) upperData = new SparseDataStorage(true); - lowerData->setData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperData->setData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Set data to data passed in input byte array of length 16384. This data must +// be in original (java version) order if originalOrder set. +void LevelChunk::setDataData(byteArray data) { + if (lowerData == NULL) lowerData = new SparseDataStorage(); + if (upperData == NULL) upperData = new SparseDataStorage(true); + lowerData->setData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperData->setData(data, Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } -// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing sky light data. Ordering same as java version if originalOrder set; -void LevelChunk::getSkyLightData(byteArray data) -{ - lowerSkyLight->getData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperSkyLight->getData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing sky +// light data. Ordering same as java version if originalOrder set; +void LevelChunk::getSkyLightData(byteArray data) { + lowerSkyLight->getData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperSkyLight->getData(data, Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } -// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing block light data. Ordering same as java version if originalOrder set; -void LevelChunk::getBlockLightData(byteArray data) -{ - lowerBlockLight->getData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperBlockLight->getData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing block +// light data. Ordering same as java version if originalOrder set; +void LevelChunk::getBlockLightData(byteArray data) { + lowerBlockLight->getData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperBlockLight->getData(data, + Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } -// Set sky light data to data passed in input byte array of length 16384. This data must be in original (java version) order if originalOrder set. -void LevelChunk::setSkyLightData(byteArray data) -{ - if( lowerSkyLight == NULL ) lowerSkyLight = new SparseLightStorage(true); - if( upperSkyLight == NULL ) upperSkyLight = new SparseLightStorage(true,true); - lowerSkyLight->setData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperSkyLight->setData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Set sky light data to data passed in input byte array of length 16384. This +// data must be in original (java version) order if originalOrder set. +void LevelChunk::setSkyLightData(byteArray data) { + if (lowerSkyLight == NULL) lowerSkyLight = new SparseLightStorage(true); + if (upperSkyLight == NULL) + upperSkyLight = new SparseLightStorage(true, true); + lowerSkyLight->setData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperSkyLight->setData(data, Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } -// Set block light data to data passed in input byte array of length 16384. This data must be in original (java version) order if originalOrder set. -void LevelChunk::setBlockLightData(byteArray data) -{ - if( lowerBlockLight == NULL ) lowerBlockLight = new SparseLightStorage(false); - if( upperBlockLight == NULL ) upperBlockLight = new SparseLightStorage(false, true); - lowerBlockLight->setData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES/2) upperBlockLight->setData(data,Level::COMPRESSED_CHUNK_SECTION_TILES/2); +// Set block light data to data passed in input byte array of length 16384. This +// data must be in original (java version) order if originalOrder set. +void LevelChunk::setBlockLightData(byteArray data) { + if (lowerBlockLight == NULL) + lowerBlockLight = new SparseLightStorage(false); + if (upperBlockLight == NULL) + upperBlockLight = new SparseLightStorage(false, true); + lowerBlockLight->setData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES / 2) + upperBlockLight->setData(data, + Level::COMPRESSED_CHUNK_SECTION_TILES / 2); } // Set sky light data to be all fully lit -void LevelChunk::setSkyLightDataAllBright() -{ - lowerSkyLight->setAllBright(); - upperSkyLight->setAllBright(); +void LevelChunk::setSkyLightDataAllBright() { + lowerSkyLight->setAllBright(); + upperSkyLight->setAllBright(); } -// Attempt to compress lighting data. Doesn't make any guarantee that it will succeed - can only compress if the lighting data is being shared, and nothing else is trying to update it from another thread. -void LevelChunk::compressLighting() -{ - // The lighting data is now generally not shared between host & local client, but is for a while at the start of level creation (until the point where the chunk data would be transferred by network - // data for remote clients). We'll therefore either be compressing a shared copy here or one of the server or client copies depending on - lowerSkyLight->compress(); - upperSkyLight->compress(); - lowerBlockLight->compress(); - upperBlockLight->compress(); +// Attempt to compress lighting data. Doesn't make any guarantee that it will +// succeed - can only compress if the lighting data is being shared, and nothing +// else is trying to update it from another thread. +void LevelChunk::compressLighting() { + // The lighting data is now generally not shared between host & local + // client, but is for a while at the start of level creation (until the + // point where the chunk data would be transferred by network data for + // remote clients). We'll therefore either be compressing a shared copy here + // or one of the server or client copies depending on + lowerSkyLight->compress(); + upperSkyLight->compress(); + lowerBlockLight->compress(); + upperBlockLight->compress(); } -void LevelChunk::compressBlocks() -{ +void LevelChunk::compressBlocks() { #ifdef SHARING_ENABLED - CompressedTileStorage *blocksToCompressLower = NULL; - CompressedTileStorage *blocksToCompressUpper = NULL; + CompressedTileStorage* blocksToCompressLower = NULL; + CompressedTileStorage* blocksToCompressUpper = NULL; - // If we're the host machine, and this is the client level, then we only want to do this if we are sharing data. This means that we will be compressing the data that is shared from the server. - // No point trying to compress the local client copy of the data if the data is unshared, since we'll be throwing this data away again anyway once we share with the server again. - if( level->isClientSide && g_NetworkManager.IsHost() ) - { - // Note - only the extraction of the pointers needs to be done in the critical section, since even if the data is unshared whilst we are processing this data is still valid (for the server) - EnterCriticalSection(&m_csSharing); - if( sharingTilesAndData ) - { - blocksToCompressLower = lowerBlocks; - blocksToCompressUpper = upperBlocks; - } - LeaveCriticalSection(&m_csSharing); - } - else - { - // Not the host, simple case - blocksToCompressLower = lowerBlocks; - blocksToCompressUpper = upperBlocks; - } + // If we're the host machine, and this is the client level, then we only + // want to do this if we are sharing data. This means that we will be + // compressing the data that is shared from the server. No point trying to + // compress the local client copy of the data if the data is unshared, since + // we'll be throwing this data away again anyway once we share with the + // server again. + if (level->isClientSide && g_NetworkManager.IsHost()) { + // Note - only the extraction of the pointers needs to be done in the + // critical section, since even if the data is unshared whilst we are + // processing this data is still valid (for the server) + EnterCriticalSection(&m_csSharing); + if (sharingTilesAndData) { + blocksToCompressLower = lowerBlocks; + blocksToCompressUpper = upperBlocks; + } + LeaveCriticalSection(&m_csSharing); + } else { + // Not the host, simple case + blocksToCompressLower = lowerBlocks; + blocksToCompressUpper = upperBlocks; + } - // Attempt to do the actual compression - if( blocksToCompressLower ) blocksToCompressLower->compress(); - if( blocksToCompressUpper ) blocksToCompressUpper->compress(); + // Attempt to do the actual compression + if (blocksToCompressLower) blocksToCompressLower->compress(); + if (blocksToCompressUpper) blocksToCompressUpper->compress(); #else - blocks->compress(); + blocks->compress(); #endif } -bool LevelChunk::isLowerBlockStorageCompressed() -{ - return lowerBlocks->isCompressed(); +bool LevelChunk::isLowerBlockStorageCompressed() { + return lowerBlocks->isCompressed(); } -int LevelChunk::isLowerBlockLightStorageCompressed() -{ - return lowerBlockLight->isCompressed(); +int LevelChunk::isLowerBlockLightStorageCompressed() { + return lowerBlockLight->isCompressed(); } -int LevelChunk::isLowerDataStorageCompressed() -{ - return lowerData->isCompressed(); +int LevelChunk::isLowerDataStorageCompressed() { + return lowerData->isCompressed(); } -void LevelChunk::writeCompressedBlockData(DataOutputStream *dos) -{ - lowerBlocks->write(dos); - upperBlocks->write(dos); +void LevelChunk::writeCompressedBlockData(DataOutputStream* dos) { + lowerBlocks->write(dos); + upperBlocks->write(dos); } -void LevelChunk::writeCompressedDataData(DataOutputStream *dos) -{ - lowerData->write(dos); - upperData->write(dos); +void LevelChunk::writeCompressedDataData(DataOutputStream* dos) { + lowerData->write(dos); + upperData->write(dos); } -void LevelChunk::writeCompressedSkyLightData(DataOutputStream *dos) -{ - lowerSkyLight->write(dos); - upperSkyLight->write(dos); +void LevelChunk::writeCompressedSkyLightData(DataOutputStream* dos) { + lowerSkyLight->write(dos); + upperSkyLight->write(dos); } -void LevelChunk::writeCompressedBlockLightData(DataOutputStream *dos) -{ - lowerBlockLight->write(dos); - upperBlockLight->write(dos); +void LevelChunk::writeCompressedBlockLightData(DataOutputStream* dos) { + lowerBlockLight->write(dos); + upperBlockLight->write(dos); } -void LevelChunk::readCompressedBlockData(DataInputStream *dis) -{ - lowerBlocks->read(dis); - upperBlocks->read(dis); +void LevelChunk::readCompressedBlockData(DataInputStream* dis) { + lowerBlocks->read(dis); + upperBlocks->read(dis); } -void LevelChunk::readCompressedDataData(DataInputStream *dis) -{ - if( lowerData == NULL ) lowerData = new SparseDataStorage(); - if( upperData == NULL ) upperData = new SparseDataStorage(true); - lowerData->read(dis); - upperData->read(dis); +void LevelChunk::readCompressedDataData(DataInputStream* dis) { + if (lowerData == NULL) lowerData = new SparseDataStorage(); + if (upperData == NULL) upperData = new SparseDataStorage(true); + lowerData->read(dis); + upperData->read(dis); } -void LevelChunk::readCompressedSkyLightData(DataInputStream *dis) -{ - if( lowerSkyLight == NULL ) lowerSkyLight = new SparseLightStorage(true); - if( upperSkyLight == NULL ) upperSkyLight = new SparseLightStorage(true,true); - lowerSkyLight->read(dis); - upperSkyLight->read(dis); +void LevelChunk::readCompressedSkyLightData(DataInputStream* dis) { + if (lowerSkyLight == NULL) lowerSkyLight = new SparseLightStorage(true); + if (upperSkyLight == NULL) + upperSkyLight = new SparseLightStorage(true, true); + lowerSkyLight->read(dis); + upperSkyLight->read(dis); } -void LevelChunk::readCompressedBlockLightData(DataInputStream *dis) -{ - if( lowerBlockLight == NULL ) lowerBlockLight = new SparseLightStorage(false); - if( upperBlockLight == NULL ) upperBlockLight = new SparseLightStorage(false, true); - lowerBlockLight->read(dis); - upperBlockLight->read(dis); +void LevelChunk::readCompressedBlockLightData(DataInputStream* dis) { + if (lowerBlockLight == NULL) + lowerBlockLight = new SparseLightStorage(false); + if (upperBlockLight == NULL) + upperBlockLight = new SparseLightStorage(false, true); + lowerBlockLight->read(dis); + upperBlockLight->read(dis); } -// Attempt to compress data. Doesn't make any guarantee that it will succeed - can only compress if the data is being shared, and nothing else is trying to update it from another thread. -void LevelChunk::compressData() -{ +// Attempt to compress data. Doesn't make any guarantee that it will succeed - +// can only compress if the data is being shared, and nothing else is trying to +// update it from another thread. +void LevelChunk::compressData() { #ifdef SHARING_ENABLED - SparseDataStorage *dataToCompressLower = NULL; - SparseDataStorage *dataToCompressUpper = NULL; + SparseDataStorage* dataToCompressLower = NULL; + SparseDataStorage* dataToCompressUpper = NULL; - // If we're the host machine, and this is the client level, then we only want to do this if we are sharing data. This means that we will be compressing the data that is shared from the server. - // No point trying to compress the local client copy of the data if the data is unshared, since we'll be throwing this data away again anyway once we share with the server again. - if( level->isClientSide && g_NetworkManager.IsHost() ) - { - // Note - only the extraction of the pointers needs to be done in the critical section, since even if the data is unshared whilst we are processing this data is still valid (for the server) - EnterCriticalSection(&m_csSharing); - if( sharingTilesAndData ) - { - dataToCompressLower = lowerData; - dataToCompressUpper = upperData; - } - LeaveCriticalSection(&m_csSharing); - } - else - { - // Not the host, simple case - dataToCompressLower = lowerData; - dataToCompressUpper = upperData; - } + // If we're the host machine, and this is the client level, then we only + // want to do this if we are sharing data. This means that we will be + // compressing the data that is shared from the server. No point trying to + // compress the local client copy of the data if the data is unshared, since + // we'll be throwing this data away again anyway once we share with the + // server again. + if (level->isClientSide && g_NetworkManager.IsHost()) { + // Note - only the extraction of the pointers needs to be done in the + // critical section, since even if the data is unshared whilst we are + // processing this data is still valid (for the server) + EnterCriticalSection(&m_csSharing); + if (sharingTilesAndData) { + dataToCompressLower = lowerData; + dataToCompressUpper = upperData; + } + LeaveCriticalSection(&m_csSharing); + } else { + // Not the host, simple case + dataToCompressLower = lowerData; + dataToCompressUpper = upperData; + } - // Attempt to do the actual compression - if( dataToCompressLower ) dataToCompressLower->compress(); - if( dataToCompressUpper ) dataToCompressUpper->compress(); + // Attempt to do the actual compression + if (dataToCompressLower) dataToCompressLower->compress(); + if (dataToCompressUpper) dataToCompressUpper->compress(); #else - data->compress(); + data->compress(); #endif } -bool LevelChunk::isRenderChunkEmpty(int y) -{ - if( isEmpty() ) - { - return true; - } - if( y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT ) - { - return upperBlocks->isRenderChunkEmpty( y - Level::COMPRESSED_CHUNK_SECTION_HEIGHT ); - } - else - { - return lowerBlocks->isRenderChunkEmpty( y ); - } +bool LevelChunk::isRenderChunkEmpty(int y) { + if (isEmpty()) { + return true; + } + if (y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + return upperBlocks->isRenderChunkEmpty( + y - Level::COMPRESSED_CHUNK_SECTION_HEIGHT); + } else { + return lowerBlocks->isRenderChunkEmpty(y); + } } // Set block data to that passed in in the input array of size 32768 -void LevelChunk::setBlockData(byteArray data) -{ - lowerBlocks->setData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES) upperBlocks->setData(data,Level::COMPRESSED_CHUNK_SECTION_TILES); +void LevelChunk::setBlockData(byteArray data) { + lowerBlocks->setData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES) + upperBlocks->setData(data, Level::COMPRESSED_CHUNK_SECTION_TILES); } // Sets data in passed in array of size 32768, from the block data in this chunk -void LevelChunk::getBlockData(byteArray data) -{ - lowerBlocks->getData(data,0); - if(data.length > Level::COMPRESSED_CHUNK_SECTION_TILES) upperBlocks->getData(data,Level::COMPRESSED_CHUNK_SECTION_TILES); +void LevelChunk::getBlockData(byteArray data) { + lowerBlocks->getData(data, 0); + if (data.length > Level::COMPRESSED_CHUNK_SECTION_TILES) + upperBlocks->getData(data, Level::COMPRESSED_CHUNK_SECTION_TILES); } -int LevelChunk::getBlocksAllocatedSize(int *count0, int *count1, int *count2, int *count4, int *count8) -{ - return lowerBlocks->getAllocatedSize(count0, count1, count2, count4, count8); +int LevelChunk::getBlocksAllocatedSize(int* count0, int* count1, int* count2, + int* count4, int* count8) { + return lowerBlocks->getAllocatedSize(count0, count1, count2, count4, + count8); } -int LevelChunk::getHighestNonEmptyY() -{ - int highestNonEmptyY = -1; - if(upperBlocks) highestNonEmptyY = upperBlocks->getHighestNonEmptyY() + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - if(highestNonEmptyY < 0) highestNonEmptyY = lowerBlocks->getHighestNonEmptyY(); - if(highestNonEmptyY < 0) highestNonEmptyY = 0; +int LevelChunk::getHighestNonEmptyY() { + int highestNonEmptyY = -1; + if (upperBlocks) + highestNonEmptyY = upperBlocks->getHighestNonEmptyY() + + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + if (highestNonEmptyY < 0) + highestNonEmptyY = lowerBlocks->getHighestNonEmptyY(); + if (highestNonEmptyY < 0) highestNonEmptyY = 0; - return highestNonEmptyY; + return highestNonEmptyY; } -byteArray LevelChunk::getReorderedBlocksAndData(int x0, int y0, int z0, int xs, int &ys, int zs) -{ - int highestNonEmpty = getHighestNonEmptyY(); +byteArray LevelChunk::getReorderedBlocksAndData(int x0, int y0, int z0, int xs, + int& ys, int zs) { + int highestNonEmpty = getHighestNonEmptyY(); - ys = std::min(highestNonEmpty - y0, ys); - if(ys < 0 ) ys = 0; + ys = std::min(highestNonEmpty - y0, ys); + if (ys < 0) ys = 0; - int x1 = x0 + xs; - int y1 = y0 + ys; - int z1 = z0 + zs; + int x1 = x0 + xs; + int y1 = y0 + ys; + int z1 = z0 + zs; - unsigned int tileCount = xs * ys * zs; - unsigned int halfTileCount = tileCount/2; + unsigned int tileCount = xs * ys * zs; + unsigned int halfTileCount = tileCount / 2; - byteArray data = byteArray( tileCount + (3* halfTileCount) + biomes.length ); - for( int x = 0; x < xs; x++ ) - { - for( int z = 0; z < zs; z++ ) - { - for( int y = 0; y < ys; y++ ) - { - int slot = (y*xs*zs) + (z*xs) + x; + byteArray data = byteArray(tileCount + (3 * halfTileCount) + biomes.length); + for (int x = 0; x < xs; x++) { + for (int z = 0; z < zs; z++) { + for (int y = 0; y < ys; y++) { + int slot = (y * xs * zs) + (z * xs) + x; - data[slot] = getTile(x,y,z); - } - } - } + data[slot] = getTile(x, y, z); + } + } + } - int p = tileCount; + int p = tileCount; - // 4J Stu - Added this because some "min" functions don't let us use our constants :( - int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + // 4J Stu - Added this because some "min" functions don't let us use our + // constants :( + int compressedHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - // 4J - replaced data storage as now using SparseDataStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerData->getDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperData->getDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + // 4J - replaced data storage as now using SparseDataStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerData->getDataRegion(data, x0, y0, z0, x1, + std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperData->getDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - // 4J - replaced block and skylight storage as these now use our SparseLightStorage - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerBlockLight->getDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperBlockLight->getDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + // 4J - replaced block and skylight storage as these now use our + // SparseLightStorage + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerBlockLight->getDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperBlockLight->getDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - if(y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += lowerSkyLight->getDataRegion( data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p ); - if(y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) p += upperSkyLight->getDataRegion( data, x0, std::max(y0-compressedHeight,0), z0, x1, y1-Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p ); + if (y0 < Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += lowerSkyLight->getDataRegion( + data, x0, y0, z0, x1, std::min(compressedHeight, y1), z1, p); + if (y1 > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + p += upperSkyLight->getDataRegion( + data, x0, std::max(y0 - compressedHeight, 0), z0, x1, + y1 - Level::COMPRESSED_CHUNK_SECTION_HEIGHT, z1, p); - memcpy(&data.data[p],biomes.data,biomes.length); + memcpy(&data.data[p], biomes.data, biomes.length); - return data; + return data; - //byteArray rawBuffer = byteArray( Level::CHUNK_TILE_COUNT + (3* Level::HALF_CHUNK_TILE_COUNT) ); - //for( int x = 0; x < 16; x++ ) - //{ - // for( int z = 0; z < 16; z++ ) - // { - // for( int y = 0; y < Level::maxBuildHeight; y++ ) - // { - // int slot = y << 8 | z << 4 | x; + // byteArray rawBuffer = byteArray( Level::CHUNK_TILE_COUNT + (3* + // Level::HALF_CHUNK_TILE_COUNT) ); for( int x = 0; x < 16; x++ ) + //{ + // for( int z = 0; z < 16; z++ ) + // { + // for( int y = 0; y < Level::maxBuildHeight; y++ ) + // { + // int slot = y << 8 | z << 4 | x; - // rawBuffer[slot] = lc->getTile(x,y,z); - // } - // } - //} - // - //unsigned int offset = Level::CHUNK_TILE_COUNT; - //// Don't bother reordering block data, block light or sky light as they don't seem to make much difference - //byteArray dataData = byteArray(rawBuffer.data+offset, Level::HALF_CHUNK_TILE_COUNT); - //lc->getDataData(dataData); - //offset += Level::HALF_CHUNK_TILE_COUNT; - //byteArray blockLightData = byteArray(rawBuffer.data + offset, Level::HALF_CHUNK_TILE_COUNT); - //offset += Level::HALF_CHUNK_TILE_COUNT; - //byteArray skyLightData = byteArray(rawBuffer.data + offset, Level::HALF_CHUNK_TILE_COUNT); - //lc->getBlockLightData(blockLightData); - //lc->getSkyLightData(skyLightData); - //return rawBuffer; + // rawBuffer[slot] = lc->getTile(x,y,z); + // } + // } + //} + // + // unsigned int offset = Level::CHUNK_TILE_COUNT; + //// Don't bother reordering block data, block light or sky light as they + ///don't seem to make much difference + // byteArray dataData = byteArray(rawBuffer.data+offset, + // Level::HALF_CHUNK_TILE_COUNT); lc->getDataData(dataData); offset += + // Level::HALF_CHUNK_TILE_COUNT; byteArray blockLightData = + // byteArray(rawBuffer.data + offset, Level::HALF_CHUNK_TILE_COUNT); offset + // += Level::HALF_CHUNK_TILE_COUNT; byteArray skyLightData = + // byteArray(rawBuffer.data + offset, Level::HALF_CHUNK_TILE_COUNT); + // lc->getBlockLightData(blockLightData); + // lc->getSkyLightData(skyLightData); + // return rawBuffer; } -void LevelChunk::reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, byteArray *data) -{ - int y1 = y0 + ys; - unsigned int tileCount = xs * ys * zs; - unsigned int halfTileCount = tileCount/2; - - int sectionHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - int lowerYSpan = std::min(y1, sectionHeight) - y0; - int upperYSpan = ys - lowerYSpan; - int upperSlotOffset = xs * zs * lowerYSpan; +void LevelChunk::reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, + byteArray* data) { + int y1 = y0 + ys; + unsigned int tileCount = xs * ys * zs; + unsigned int halfTileCount = tileCount / 2; - int biomesLength = 16 * 16; - byteArray newBuffer = byteArray(tileCount + (3* halfTileCount) + biomesLength); - for( int x = 0; x < xs; x++ ) - { - for( int z = 0; z < zs; z++ ) - { - for( int y = 0; y < ys; y++ ) - { - int slotY = y; - unsigned int targetSlotOffset = 0; - int ySpan = lowerYSpan; - if(y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - slotY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - targetSlotOffset = upperSlotOffset; - ySpan = upperYSpan; - } - int slot = (x*zs*ySpan) + (z*ySpan) + slotY; - int slot2 = (y*xs*zs) + (z*xs) + x; + int sectionHeight = Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + int lowerYSpan = std::min(y1, sectionHeight) - y0; + int upperYSpan = ys - lowerYSpan; + int upperSlotOffset = xs * zs * lowerYSpan; - newBuffer[slot + targetSlotOffset] = data->data[slot2]; - } - } - } - // Copy over block data, block light, skylight and biomes as-is - memcpy(newBuffer.data + tileCount, data->data + tileCount, 3*halfTileCount + biomesLength); - delete [] data->data; - data->data = newBuffer.data; + int biomesLength = 16 * 16; + byteArray newBuffer = + byteArray(tileCount + (3 * halfTileCount) + biomesLength); + for (int x = 0; x < xs; x++) { + for (int z = 0; z < zs; z++) { + for (int y = 0; y < ys; y++) { + int slotY = y; + unsigned int targetSlotOffset = 0; + int ySpan = lowerYSpan; + if (y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + slotY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + targetSlotOffset = upperSlotOffset; + ySpan = upperYSpan; + } + int slot = (x * zs * ySpan) + (z * ySpan) + slotY; + int slot2 = (y * xs * zs) + (z * xs) + x; - //int p = 0; - //setBlocksAndData(*data, x0, y0, z0, x1, y1, z1, p); + newBuffer[slot + targetSlotOffset] = data->data[slot2]; + } + } + } + // Copy over block data, block light, skylight and biomes as-is + memcpy(newBuffer.data + tileCount, data->data + tileCount, + 3 * halfTileCount + biomesLength); + delete[] data->data; + data->data = newBuffer.data; - //// If it is a full chunk, we'll need to rearrange into the order the rest of the game expects - //if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) - //{ - // byteArray newBuffer = byteArray(81920); - // for( int x = 0; x < 16; x++ ) - // { - // for( int z = 0; z < 16; z++ ) - // { - // for( int y = 0; y < 128; y++ ) - // { - // int slot = x << 11 | z << 7 | y; - // int slot2 = y << 8 | z << 4 | x; + // int p = 0; + // setBlocksAndData(*data, x0, y0, z0, x1, y1, z1, p); - // newBuffer[slot] = buffer[slot2]; - // } - // } - // } - // // Copy over block data, block light & skylight as-is - // memcpy(newBuffer.data + 32768, buffer.data + 32768, 49152); - // delete buffer.data; - // buffer.data = newBuffer.data; - //} + //// If it is a full chunk, we'll need to rearrange into the order the rest + ///of the game expects + // if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 + // ) && ( ( z & 15 ) == 0 ) ) + //{ + // byteArray newBuffer = byteArray(81920); + // for( int x = 0; x < 16; x++ ) + // { + // for( int z = 0; z < 16; z++ ) + // { + // for( int y = 0; y < 128; y++ ) + // { + // int slot = x << 11 | z << 7 | y; + // int slot2 = y << 8 | z << 4 | x; + + // newBuffer[slot] = buffer[slot2]; + // } + // } + // } + // // Copy over block data, block light & skylight as-is + // memcpy(newBuffer.data + 32768, buffer.data + 32768, 49152); + // delete buffer.data; + // buffer.data = newBuffer.data; + //} } diff --git a/Minecraft.World/Level/LevelChunk.h b/Minecraft.World/Level/LevelChunk.h index 72aeb04f2..d6535ed4c 100644 --- a/Minecraft.World/Level/LevelChunk.h +++ b/Minecraft.World/Level/LevelChunk.h @@ -1,6 +1,5 @@ #pragma once - class DataLayer; class TileEntity; class Random; @@ -16,148 +15,182 @@ class ChunkSource; #define SHARING_ENABLED class TileCompressData_SPU; -#if 0//__PSVITA__ +#if 0 //__PSVITA__ #define _ENTITIES_RW_SECTION #endif -class LevelChunk -{ - friend class TileCompressData_SPU; - friend class LevelRenderer; -public: - byteArray biomes; // 4J Stu - Made public +class LevelChunk { + friend class TileCompressData_SPU; + friend class LevelRenderer; - // 4J Stu - No longer static in 1.8.2 - const int ENTITY_BLOCKS_LENGTH; - static const int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added +public: + byteArray biomes; // 4J Stu - Made public + + // 4J Stu - No longer static in 1.8.2 + const int ENTITY_BLOCKS_LENGTH; + static const int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added static bool touchedSky; - enum EColumnFlag - { - eColumnFlag_recheck = 1, - eColumnFlag_biomeOk = 2, - eColumnFlag_biomeHasSnow = 4, - eColumnFlag_biomeHasRain = 8, - }; + enum EColumnFlag { + eColumnFlag_recheck = 1, + eColumnFlag_biomeOk = 2, + eColumnFlag_biomeHasSnow = 4, + eColumnFlag_biomeHasRain = 8, + }; -// byteArray blocks; - // 4J - actual storage for blocks is now private with public methods to access it + // byteArray blocks; + // 4J - actual storage for blocks is now private with public methods to + // access it private: - CompressedTileStorage *lowerBlocks; // 0 - 127 - CompressedTileStorage *upperBlocks; // 128 - 255 + CompressedTileStorage* lowerBlocks; // 0 - 127 + CompressedTileStorage* upperBlocks; // 128 - 255 public: - bool isRenderChunkEmpty(int y); - void setBlockData(byteArray data); // Set block data to that passed in in the input array of size 32768 - void getBlockData(byteArray data); // Sets data in passed in array of size 32768, from the block data in this chunk - int getBlocksAllocatedSize(int *count0, int *count1, int *count2, int *count4, int *count8); + bool isRenderChunkEmpty(int y); + void setBlockData(byteArray data); // Set block data to that passed in in + // the input array of size 32768 + void getBlockData( + byteArray data); // Sets data in passed in array of size 32768, from + // the block data in this chunk + int getBlocksAllocatedSize(int* count0, int* count1, int* count2, + int* count4, int* count8); bool loaded; - unsigned char rainHeights[16*16]; // 4J - optimisation brought forward from 1.8.2 (was int arrayb in java though) - unsigned char columnFlags[16*8]; // 4J - lighting update brought forward from 1.8.2, was a bool array but now mixed with other flags in our version, and stored in nybbles - Level *level; + unsigned char + rainHeights[16 * 16]; // 4J - optimisation brought forward from 1.8.2 + // (was int arrayb in java though) + unsigned char columnFlags[16 * 8]; // 4J - lighting update brought forward + // from 1.8.2, was a bool array but now + // mixed with other flags in our + // version, and stored in nybbles + Level* level; - // 4J - actual storage for data is now private with public methods to access it + // 4J - actual storage for data is now private with public methods to access + // it private: - SparseDataStorage *lowerData; // 0 - 127 - SparseDataStorage *upperData; // 128 - 255 + SparseDataStorage* lowerData; // 0 - 127 + SparseDataStorage* upperData; // 128 - 255 public: - void setDataData(byteArray data); // Set data to that passed in in the input array of size 32768 - void getDataData(byteArray data); // Sets data in passed in array of size 16384, from the data in this chunk + void setDataData(byteArray data); // Set data to that passed in in the + // input array of size 32768 + void getDataData(byteArray data); // Sets data in passed in array of size + // 16384, from the data in this chunk -// DataLayer *data; + // DataLayer *data; private: - // 4J - actual storage for sky & block lights is now private with new methods to be able to access it. + // 4J - actual storage for sky & block lights is now private with new + // methods to be able to access it. - SparseLightStorage *lowerSkyLight; // 0 - 127 - SparseLightStorage *upperSkyLight; // 128 - 255 - SparseLightStorage *lowerBlockLight; // 0 - 127 - SparseLightStorage *upperBlockLight; // 128 - 255 + SparseLightStorage* lowerSkyLight; // 0 - 127 + SparseLightStorage* upperSkyLight; // 128 - 255 + SparseLightStorage* lowerBlockLight; // 0 - 127 + SparseLightStorage* upperBlockLight; // 128 - 255 public: - void getSkyLightData(byteArray data); // Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing sky light data. Ordering same as java version. - void getBlockLightData(byteArray data); // Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), containing block light data. Ordering same as java version. - void setSkyLightData(byteArray data); // Set sky light data to data passed in input byte array of length 16384. This data must be in original (java version) order - void setBlockLightData(byteArray data); // Set block light data to data passed in input byte array of length 16384. This data must be in original (java version) order - void setSkyLightDataAllBright(); // Set sky light data to be all fully lit - bool isLowerBlockStorageCompressed(); - int isLowerBlockLightStorageCompressed(); - int isLowerDataStorageCompressed(); + void getSkyLightData( + byteArray + data); // Get a byte array of length 16384 ( 128 x 16 x 16 x 0.5 ), + // containing sky light data. Ordering same as java version. + void getBlockLightData( + byteArray data); // Get a byte array of length 16384 ( 128 x 16 x 16 x + // 0.5 ), containing block light data. Ordering same + // as java version. + void setSkyLightData( + byteArray data); // Set sky light data to data passed in input byte + // array of length 16384. This data must be in + // original (java version) order + void setBlockLightData( + byteArray data); // Set block light data to data passed in input byte + // array of length 16384. This data must be in + // original (java version) order + void setSkyLightDataAllBright(); // Set sky light data to be all fully lit + bool isLowerBlockStorageCompressed(); + int isLowerBlockLightStorageCompressed(); + int isLowerDataStorageCompressed(); - void writeCompressedBlockData(DataOutputStream *dos); - void writeCompressedDataData(DataOutputStream *dos); - void writeCompressedSkyLightData(DataOutputStream *dos); - void writeCompressedBlockLightData(DataOutputStream *dos); + void writeCompressedBlockData(DataOutputStream* dos); + void writeCompressedDataData(DataOutputStream* dos); + void writeCompressedSkyLightData(DataOutputStream* dos); + void writeCompressedBlockLightData(DataOutputStream* dos); - void readCompressedBlockData(DataInputStream *dis); - void readCompressedDataData(DataInputStream *dis); - void readCompressedSkyLightData(DataInputStream *dis); - void readCompressedBlockLightData(DataInputStream *dis); + void readCompressedBlockData(DataInputStream* dis); + void readCompressedDataData(DataInputStream* dis); + void readCompressedSkyLightData(DataInputStream* dis); + void readCompressedBlockLightData(DataInputStream* dis); byteArray heightmap; int minHeight; int x, z; + private: - bool hasGapsToCheck; + bool hasGapsToCheck; + public: + std::unordered_map, TilePosKeyHash, + TilePosKeyEq> + tileEntities; + std::vector >** entityBlocks; - std::unordered_map, TilePosKeyHash, TilePosKeyEq> tileEntities; - std::vector > **entityBlocks; - - static const int sTerrainPopulatedFromHere = 2; - static const int sTerrainPopulatedFromW = 4; - static const int sTerrainPopulatedFromS = 8; - static const int sTerrainPopulatedFromSW = 16; - static const int sTerrainPopulatedAllAffecting = 30; // All the post-processing that can actually place tiles in this chunk are complete - static const int sTerrainPopulatedFromNW = 32; - static const int sTerrainPopulatedFromN = 64; - static const int sTerrainPopulatedFromNE = 128; - static const int sTerrainPopulatedFromE = 256; - static const int sTerrainPopulatedFromSE = 512; - static const int sTerrainPopulatedAllNeighbours = 1022; // The post-processing passes of all neighbours to this chunk are complete - static const int sTerrainPostPostProcessed = 1024; // This chunk has been post-post-processed, which is only done when all neighbours have been post-processed + static const int sTerrainPopulatedFromHere = 2; + static const int sTerrainPopulatedFromW = 4; + static const int sTerrainPopulatedFromS = 8; + static const int sTerrainPopulatedFromSW = 16; + static const int sTerrainPopulatedAllAffecting = + 30; // All the post-processing that can actually place tiles in this + // chunk are complete + static const int sTerrainPopulatedFromNW = 32; + static const int sTerrainPopulatedFromN = 64; + static const int sTerrainPopulatedFromNE = 128; + static const int sTerrainPopulatedFromE = 256; + static const int sTerrainPopulatedFromSE = 512; + static const int sTerrainPopulatedAllNeighbours = + 1022; // The post-processing passes of all neighbours to this chunk are + // complete + static const int sTerrainPostPostProcessed = + 1024; // This chunk has been post-post-processed, which is only done + // when all neighbours have been post-processed - short terrainPopulated; // 4J - changed from bool to bitfield within short - short *serverTerrainPopulated; // 4J added + short terrainPopulated; // 4J - changed from bool to bitfield within short + short* serverTerrainPopulated; // 4J added - void setUnsaved(bool unsaved); // 4J added + void setUnsaved(bool unsaved); // 4J added protected: - // 4J Stu - Stopped this being private so we can add some more logic to it + // 4J Stu - Stopped this being private so we can add some more logic to it bool m_unsaved; public: bool dontSave; bool lastSaveHadEntities; #ifdef SHARING_ENABLED - bool sharingTilesAndData; // 4J added + bool sharingTilesAndData; // 4J added #endif - bool emissiveAdded; // 4J added - void stopSharingTilesAndData(); // 4J added - virtual void reSyncLighting(); // 4J added - void startSharingTilesAndData(int forceMs = 0); // 4J added - __int64 lastUnsharedTime; // 4J added + bool emissiveAdded; // 4J added + void stopSharingTilesAndData(); // 4J added + virtual void reSyncLighting(); // 4J added + void startSharingTilesAndData(int forceMs = 0); // 4J added + __int64 lastUnsharedTime; // 4J added __int64 lastSaveTime; - bool seenByPlayer; + bool seenByPlayer; #ifdef _LARGE_WORLDS - bool m_bUnloaded; - CompoundTag *m_unloadedEntitiesTag; + bool m_bUnloaded; + CompoundTag* m_unloadedEntitiesTag; #endif - //static const int LIGHT_CHECK_MAX_POS = NUM_SECTIONS * 16 * 16; + // static const int LIGHT_CHECK_MAX_POS = NUM_SECTIONS * 16 * 16; private: - int checkLightPosition; + int checkLightPosition; public: - virtual void init(Level *level, int x, int z); - LevelChunk(Level *level, int x, int z); - LevelChunk(Level *level, byteArray blocks, int x, int z); - LevelChunk(Level *level, int x, int z, LevelChunk *lc); - virtual ~LevelChunk(); + virtual void init(Level* level, int x, int z); + LevelChunk(Level* level, int x, int z); + LevelChunk(Level* level, byteArray blocks, int x, int z); + LevelChunk(Level* level, int x, int z, LevelChunk* lc); + virtual ~LevelChunk(); virtual bool isAt(int x, int z); virtual int getHeightmap(int x, int z); - int getHighestSectionPosition(); + int getHighestSectionPosition(); virtual void recalcBlockLights(); virtual void recalcHeightmapOnly(); @@ -168,25 +201,29 @@ public: private: void lightGaps(int x, int z); - // 4J - changes for lighting brought forward from 1.8.2 + // 4J - changes for lighting brought forward from 1.8.2 public: - void recheckGaps(bool bForce = false); // 4J - added parameter, made public + void recheckGaps(bool bForce = false); // 4J - added parameter, made public private: void lightGap(int x, int z, int source); - void lightGap(int x, int z, int y1, int y2); + void lightGap(int x, int z, int y1, int y2); void recalcHeight(int x, int yStart, int z); public: - virtual int getTileLightBlock(int x, int y, int z); + virtual int getTileLightBlock(int x, int y, int z); virtual int getTile(int x, int y, int z); virtual bool setTileAndData(int x, int y, int z, int _tile, int _data); virtual bool setTile(int x, int y, int z, int _tile); virtual int getData(int x, int y, int z); - virtual bool setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged); // 4J added mask + virtual bool setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged); // 4J added mask virtual int getBrightness(LightLayer::variety layer, int x, int y, int z); - virtual void getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z); // 4J added - virtual void setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness); + virtual void getNeighbourBrightnesses(int* brightnesses, + LightLayer::variety layer, int x, + int y, int z); // 4J added + virtual void setBrightness(LightLayer::variety layer, int x, int y, int z, + int brightness); virtual int getRawBrightness(int x, int y, int z, int skyDampen); virtual void addEntity(std::shared_ptr e); virtual void removeEntity(std::shared_ptr e); @@ -195,66 +232,82 @@ public: virtual void skyBrightnessChanged(); virtual std::shared_ptr getTileEntity(int x, int y, int z); virtual void addTileEntity(std::shared_ptr te); - virtual void setTileEntity(int x, int y, int z, std::shared_ptr tileEntity); + virtual void setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity); virtual void removeTileEntity(int x, int y, int z); virtual void load(); - virtual void unload(bool unloadTileEntities) ; // 4J - added parameter + virtual void unload(bool unloadTileEntities); // 4J - added parameter #ifdef _LARGE_WORLDS - virtual bool isUnloaded(); + virtual bool isUnloaded(); #endif virtual void markUnsaved(); - virtual void getEntities(std::shared_ptr except, AABB *bb, std::vector > &es); - virtual void getEntitiesOfClass(const std::type_info& ec, AABB *bb, std::vector > &es); + virtual void getEntities(std::shared_ptr except, AABB* bb, + std::vector >& es); + virtual void getEntitiesOfClass(const std::type_info& ec, AABB* bb, + std::vector >& es); virtual int countEntities(); virtual bool shouldSave(bool force); - virtual int getBlocksAndData(byteArray *data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting = true); // 4J - added includeLighting parameter - static void tileUpdatedCallback(int x, int y, int z, void *param, int yparam); // 4J added - virtual int setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting = true); // 4J - added includeLighting parameter - virtual bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p); // 4J added - virtual void setCheckAllLight(); + virtual int getBlocksAndData( + byteArray* data, int x0, int y0, int z0, int x1, int y1, int z1, int p, + bool includeLighting = true); // 4J - added includeLighting parameter + static void tileUpdatedCallback(int x, int y, int z, void* param, + int yparam); // 4J added + virtual int setBlocksAndData( + byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, + bool includeLighting = true); // 4J - added includeLighting parameter + virtual bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, + int x1, int y1, int z1, + int p); // 4J added + virtual void setCheckAllLight(); - virtual Random *getRandom(__int64 l); + virtual Random* getRandom(__int64 l); virtual bool isEmpty(); virtual void attemptCompression(); #ifdef SHARING_ENABLED - static CRITICAL_SECTION m_csSharing; // 4J added + static CRITICAL_SECTION m_csSharing; // 4J added #endif - // 4J added + // 4J added #ifdef _ENTITIES_RW_SECTION - static CRITICAL_RW_SECTION m_csEntities; // AP - we're using a RW critical so we can do multiple reads without contention + static CRITICAL_RW_SECTION + m_csEntities; // AP - we're using a RW critical so we can do multiple + // reads without contention #else - static CRITICAL_SECTION m_csEntities; + static CRITICAL_SECTION m_csEntities; #endif - static CRITICAL_SECTION m_csTileEntities; // 4J added - static void staticCtor(); - void checkPostProcess(ChunkSource *source, ChunkSource *parent, int x, int z); - void checkChests(ChunkSource *source, int x, int z ); // 4J added - int getTopRainBlock(int x, int z); // 4J - optimisation brought forward from 1.8.2 - void tick(); // 4J - lighting change brought forward from 1.8.2 - ChunkPos *getPos(); - bool isYSpaceEmpty(int y1, int y2); - virtual Biome *getBiome(int x, int z, BiomeSource *biomeSource); - byteArray getBiomes(); - void setBiomes(byteArray biomes); - bool biomeHasRain(int x, int z); // 4J added - bool biomeHasSnow(int x, int z); // 4J added + static CRITICAL_SECTION m_csTileEntities; // 4J added + static void staticCtor(); + void checkPostProcess(ChunkSource* source, ChunkSource* parent, int x, + int z); + void checkChests(ChunkSource* source, int x, int z); // 4J added + int getTopRainBlock(int x, + int z); // 4J - optimisation brought forward from 1.8.2 + void tick(); // 4J - lighting change brought forward from 1.8.2 + ChunkPos* getPos(); + bool isYSpaceEmpty(int y1, int y2); + virtual Biome* getBiome(int x, int z, BiomeSource* biomeSource); + byteArray getBiomes(); + void setBiomes(byteArray biomes); + bool biomeHasRain(int x, int z); // 4J added + bool biomeHasSnow(int x, int z); // 4J added private: - void updateBiomeFlags(int x, int z); // 4J added + void updateBiomeFlags(int x, int z); // 4J added public: - void compressLighting(); // 4J added - void compressBlocks(); // 4J added - void compressData(); // 4J added - int getHighestNonEmptyY(); - byteArray getReorderedBlocksAndData(int x, int y, int z, int xs, int &ys, int zs); - static void reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, byteArray *data); + void compressLighting(); // 4J added + void compressBlocks(); // 4J added + void compressData(); // 4J added + int getHighestNonEmptyY(); + byteArray getReorderedBlocksAndData(int x, int y, int z, int xs, int& ys, + int zs); + static void reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, + byteArray* data); #ifdef LIGHT_COMPRESSION_STATS - int getBlockLightPlanesLower() { return lowerBlockLight->count; } - int getSkyLightPlanesLower() { return lowerSkyLight->count; } - int getBlockLightPlanesUpper() { return upperBlockLight->count; } - int getSkyLightPlanesUpper() { return upperSkyLight->count; } + int getBlockLightPlanesLower() { return lowerBlockLight->count; } + int getSkyLightPlanesLower() { return lowerSkyLight->count; } + int getBlockLightPlanesUpper() { return upperBlockLight->count; } + int getSkyLightPlanesUpper() { return upperSkyLight->count; } #endif #ifdef DATA_COMPRESSION_STATS - int getDataPlanes() { return data->count; } + int getDataPlanes() { return data->count; } #endif }; diff --git a/Minecraft.World/Level/LevelConflictException.cpp b/Minecraft.World/Level/LevelConflictException.cpp index 2c6711af8..18d0c1360 100644 --- a/Minecraft.World/Level/LevelConflictException.cpp +++ b/Minecraft.World/Level/LevelConflictException.cpp @@ -1,6 +1,5 @@ #include "../Platform/stdafx.h" #include "LevelConflictException.h" -LevelConflictException::LevelConflictException(const std::wstring& msg) : RuntimeException(msg) -{ -} \ No newline at end of file +LevelConflictException::LevelConflictException(const std::wstring& msg) + : RuntimeException(msg) {} \ No newline at end of file diff --git a/Minecraft.World/Level/LevelConflictException.h b/Minecraft.World/Level/LevelConflictException.h index ad7407d20..43697842c 100644 --- a/Minecraft.World/Level/LevelConflictException.h +++ b/Minecraft.World/Level/LevelConflictException.h @@ -1,13 +1,11 @@ #pragma once - #include "../Util/Exceptions.h" -class LevelConflictException : public RuntimeException -{ +class LevelConflictException : public RuntimeException { private: - static const __int32 serialVersionUID = 1L; - + static const __int32 serialVersionUID = 1L; + public: - LevelConflictException(const std::wstring& msg); + LevelConflictException(const std::wstring& msg); }; \ No newline at end of file diff --git a/Minecraft.World/Level/LevelData.cpp b/Minecraft.World/Level/LevelData.cpp index 03c475a46..3ddbaacc6 100644 --- a/Minecraft.World/Level/LevelData.cpp +++ b/Minecraft.World/Level/LevelData.cpp @@ -6,43 +6,33 @@ #include "Storage/LevelType.h" #include "Storage/LevelSettings.h" -LevelData::LevelData() -{ -} +LevelData::LevelData() {} -LevelData::LevelData(CompoundTag *tag) -{ +LevelData::LevelData(CompoundTag* tag) { seed = tag->getLong(L"RandomSeed"); - m_pGenerator = LevelType::lvl_normal; - if (tag->contains(L"generatorName")) - { - std::wstring generatorName = tag->getString(L"generatorName"); - m_pGenerator = LevelType::getLevelType(generatorName); - if (m_pGenerator == NULL) - { - m_pGenerator = LevelType::lvl_normal; - } - else if (m_pGenerator->hasReplacement()) - { - int generatorVersion = 0; - if (tag->contains(L"generatorVersion")) - { - generatorVersion = tag->getInt(L"generatorVersion"); - } - m_pGenerator = m_pGenerator->getReplacementForVersion(generatorVersion); - } - } + m_pGenerator = LevelType::lvl_normal; + if (tag->contains(L"generatorName")) { + std::wstring generatorName = tag->getString(L"generatorName"); + m_pGenerator = LevelType::getLevelType(generatorName); + if (m_pGenerator == NULL) { + m_pGenerator = LevelType::lvl_normal; + } else if (m_pGenerator->hasReplacement()) { + int generatorVersion = 0; + if (tag->contains(L"generatorVersion")) { + generatorVersion = tag->getInt(L"generatorVersion"); + } + m_pGenerator = + m_pGenerator->getReplacementForVersion(generatorVersion); + } + } - gameType = GameType::byId(tag->getInt(L"GameType")); - if (tag->contains(L"MapFeatures")) - { - generateMapFeatures = tag->getBoolean(L"MapFeatures"); + gameType = GameType::byId(tag->getInt(L"GameType")); + if (tag->contains(L"MapFeatures")) { + generateMapFeatures = tag->getBoolean(L"MapFeatures"); + } else { + generateMapFeatures = true; } - else - { - generateMapFeatures = true; - } - spawnBonusChest = tag->getBoolean(L"spawnBonusChest"); + spawnBonusChest = tag->getBoolean(L"spawnBonusChest"); xSpawn = tag->getInt(L"SpawnX"); ySpawn = tag->getInt(L"SpawnY"); @@ -56,158 +46,155 @@ LevelData::LevelData(CompoundTag *tag) raining = tag->getBoolean(L"raining"); thunderTime = tag->getInt(L"thunderTime"); thundering = tag->getBoolean(L"thundering"); - hardcore = tag->getBoolean(L"hardcore"); + hardcore = tag->getBoolean(L"hardcore"); - if (tag->contains(L"initialized")) - { - initialized = tag->getBoolean(L"initialized"); - } - else - { - initialized = true; - } - - if (tag->contains(L"allowCommands")) - { - allowCommands = tag->getBoolean(L"allowCommands"); - } - else - { - allowCommands = gameType == GameType::CREATIVE; - } - - newSeaLevel = tag->getBoolean(L"newSeaLevel"); // 4J added - only use new sea level for newly created maps. This read defaults to false. (sea level changes in 1.8.2) - hasBeenInCreative = tag->getBoolean(L"hasBeenInCreative"); // 4J added so we can not award achievements to levels modified in creative - - // 4J added - for stronghold position - bStronghold = tag->getBoolean(L"hasStronghold"); - - if(bStronghold==false) - { - // we need to generate the position - xStronghold=yStronghold=zStronghold=0; - } - else - { - xStronghold = tag->getInt(L"StrongholdX"); - yStronghold = tag->getInt(L"StrongholdY"); - zStronghold = tag->getInt(L"StrongholdZ"); - } - - // 4J added - for stronghold end portal position - bStrongholdEndPortal = tag->getBoolean(L"hasStrongholdEndPortal"); - - if(bStrongholdEndPortal==false) - { - // we need to generate the position - xStrongholdEndPortal=zStrongholdEndPortal=0; - } - else - { - xStrongholdEndPortal = tag->getInt(L"StrongholdEndPortalX"); - zStrongholdEndPortal = tag->getInt(L"StrongholdEndPortalZ"); - } - - // 4J Added - m_xzSize = tag->getInt(L"XZSize"); - m_hellScale = tag->getInt(L"HellScale"); - - m_xzSize = std::min(m_xzSize,LEVEL_MAX_WIDTH); - m_xzSize = std::max(m_xzSize,LEVEL_MIN_WIDTH); - - m_hellScale = std::min(m_hellScale,HELL_LEVEL_MAX_SCALE); - m_hellScale = std::max(m_hellScale,HELL_LEVEL_MIN_SCALE); - - int hellXZSize = m_xzSize / m_hellScale; - while(hellXZSize > HELL_LEVEL_MAX_WIDTH && m_hellScale < HELL_LEVEL_MAX_SCALE) - { - ++m_hellScale; - hellXZSize = m_xzSize / m_hellScale; - } - - /* 4J - we don't store this anymore - if (tag->contains(L"Player")) - { - loadedPlayerTag = tag->getCompound(L"Player"); - dimension = loadedPlayerTag->getInt(L"Dimension"); + if (tag->contains(L"initialized")) { + initialized = tag->getBoolean(L"initialized"); + } else { + initialized = true; } - else - { - this->loadedPlayerTag = NULL; - } - */ - dimension = 0; + + if (tag->contains(L"allowCommands")) { + allowCommands = tag->getBoolean(L"allowCommands"); + } else { + allowCommands = gameType == GameType::CREATIVE; + } + + newSeaLevel = tag->getBoolean( + L"newSeaLevel"); // 4J added - only use new sea level for newly created + // maps. This read defaults to false. (sea level + // changes in 1.8.2) + hasBeenInCreative = tag->getBoolean( + L"hasBeenInCreative"); // 4J added so we can not award achievements to + // levels modified in creative + + // 4J added - for stronghold position + bStronghold = tag->getBoolean(L"hasStronghold"); + + if (bStronghold == false) { + // we need to generate the position + xStronghold = yStronghold = zStronghold = 0; + } else { + xStronghold = tag->getInt(L"StrongholdX"); + yStronghold = tag->getInt(L"StrongholdY"); + zStronghold = tag->getInt(L"StrongholdZ"); + } + + // 4J added - for stronghold end portal position + bStrongholdEndPortal = tag->getBoolean(L"hasStrongholdEndPortal"); + + if (bStrongholdEndPortal == false) { + // we need to generate the position + xStrongholdEndPortal = zStrongholdEndPortal = 0; + } else { + xStrongholdEndPortal = tag->getInt(L"StrongholdEndPortalX"); + zStrongholdEndPortal = tag->getInt(L"StrongholdEndPortalZ"); + } + + // 4J Added + m_xzSize = tag->getInt(L"XZSize"); + m_hellScale = tag->getInt(L"HellScale"); + + m_xzSize = std::min(m_xzSize, LEVEL_MAX_WIDTH); + m_xzSize = std::max(m_xzSize, LEVEL_MIN_WIDTH); + + m_hellScale = std::min(m_hellScale, HELL_LEVEL_MAX_SCALE); + m_hellScale = std::max(m_hellScale, HELL_LEVEL_MIN_SCALE); + + int hellXZSize = m_xzSize / m_hellScale; + while (hellXZSize > HELL_LEVEL_MAX_WIDTH && + m_hellScale < HELL_LEVEL_MAX_SCALE) { + ++m_hellScale; + hellXZSize = m_xzSize / m_hellScale; + } + + /* 4J - we don't store this anymore +if (tag->contains(L"Player")) + { + loadedPlayerTag = tag->getCompound(L"Player"); + dimension = loadedPlayerTag->getInt(L"Dimension"); +} + else + { + this->loadedPlayerTag = NULL; + } + */ + dimension = 0; } -LevelData::LevelData(LevelSettings *levelSettings, const std::wstring& levelName) -{ +LevelData::LevelData(LevelSettings* levelSettings, + const std::wstring& levelName) { this->seed = levelSettings->getSeed(); this->gameType = levelSettings->getGameType(); this->generateMapFeatures = levelSettings->isGenerateMapFeatures(); - this->spawnBonusChest = levelSettings->hasStartingBonusItems(); + this->spawnBonusChest = levelSettings->hasStartingBonusItems(); this->levelName = levelName; - this->m_pGenerator = levelSettings->getLevelType(); - this->hardcore = levelSettings->isHardcore(); + this->m_pGenerator = levelSettings->getLevelType(); + this->hardcore = levelSettings->isHardcore(); - // 4J Stu - Default initers + // 4J Stu - Default initers this->xSpawn = 0; this->ySpawn = 0; this->zSpawn = 0; - this->time = -1; // 4J-JEV: Edited: To know when this is uninitialized. + this->time = -1; // 4J-JEV: Edited: To know when this is uninitialized. this->lastPlayed = 0; this->sizeOnDisk = 0; -// this->loadedPlayerTag = NULL; // 4J - we don't store this anymore + // this->loadedPlayerTag = NULL; // 4J - we don't store this anymore this->dimension = 0; this->version = 0; this->rainTime = 0; this->raining = false; this->thunderTime = 0; this->thundering = false; - this->allowCommands = levelSettings->getAllowCommands(); - this->initialized = false; - this->newSeaLevel = levelSettings->useNewSeaLevel(); // 4J added - only use new sea level for newly created maps (sea level changes in 1.8.2) - this->hasBeenInCreative = levelSettings->getGameType() == GameType::CREATIVE; // 4J added + this->allowCommands = levelSettings->getAllowCommands(); + this->initialized = false; + this->newSeaLevel = + levelSettings + ->useNewSeaLevel(); // 4J added - only use new sea level for newly + // created maps (sea level changes in 1.8.2) + this->hasBeenInCreative = + levelSettings->getGameType() == GameType::CREATIVE; // 4J added - // 4J-PB for the stronghold position - this->bStronghold=false; - this->xStronghold = 0; - this->yStronghold = 0; - this->zStronghold = 0; + // 4J-PB for the stronghold position + this->bStronghold = false; + this->xStronghold = 0; + this->yStronghold = 0; + this->zStronghold = 0; - this->xStrongholdEndPortal = 0; - this->zStrongholdEndPortal = 0; - this->bStrongholdEndPortal = false; - m_xzSize = levelSettings->getXZSize(); - m_hellScale = levelSettings->getHellScale(); - - m_xzSize = std::min(m_xzSize,LEVEL_MAX_WIDTH); - m_xzSize = std::max(m_xzSize,LEVEL_MIN_WIDTH); + this->xStrongholdEndPortal = 0; + this->zStrongholdEndPortal = 0; + this->bStrongholdEndPortal = false; + m_xzSize = levelSettings->getXZSize(); + m_hellScale = levelSettings->getHellScale(); - m_hellScale = std::min(m_hellScale,HELL_LEVEL_MAX_SCALE); - m_hellScale = std::max(m_hellScale,HELL_LEVEL_MIN_SCALE); + m_xzSize = std::min(m_xzSize, LEVEL_MAX_WIDTH); + m_xzSize = std::max(m_xzSize, LEVEL_MIN_WIDTH); - int hellXZSize = m_xzSize / m_hellScale; - while(hellXZSize > HELL_LEVEL_MAX_WIDTH && m_hellScale < HELL_LEVEL_MAX_SCALE) - { - ++m_hellScale; - hellXZSize = m_xzSize / m_hellScale; -} + m_hellScale = std::min(m_hellScale, HELL_LEVEL_MAX_SCALE); + m_hellScale = std::max(m_hellScale, HELL_LEVEL_MIN_SCALE); + + int hellXZSize = m_xzSize / m_hellScale; + while (hellXZSize > HELL_LEVEL_MAX_WIDTH && + m_hellScale < HELL_LEVEL_MAX_SCALE) { + ++m_hellScale; + hellXZSize = m_xzSize / m_hellScale; + } } -LevelData::LevelData(LevelData *copy) -{ +LevelData::LevelData(LevelData* copy) { this->seed = copy->seed; - this->m_pGenerator = copy->m_pGenerator; + this->m_pGenerator = copy->m_pGenerator; this->gameType = copy->gameType; this->generateMapFeatures = copy->generateMapFeatures; - this->spawnBonusChest = copy->spawnBonusChest; + this->spawnBonusChest = copy->spawnBonusChest; this->xSpawn = copy->xSpawn; this->ySpawn = copy->ySpawn; this->zSpawn = copy->zSpawn; this->time = copy->time; this->lastPlayed = copy->lastPlayed; this->sizeOnDisk = copy->sizeOnDisk; -// this->loadedPlayerTag = copy->loadedPlayerTag; // 4J - we don't store this anymore + // this->loadedPlayerTag = copy->loadedPlayerTag; // 4J - + // we don't store this anymore this->dimension = copy->dimension; this->levelName = copy->levelName; this->version = copy->version; @@ -215,48 +202,46 @@ LevelData::LevelData(LevelData *copy) this->raining = copy->raining; this->thunderTime = copy->thunderTime; this->thundering = copy->thundering; - this->hardcore = copy->hardcore; - this->allowCommands = copy->allowCommands; - this->initialized = copy->initialized; - this->newSeaLevel = copy->newSeaLevel; - this->hasBeenInCreative = copy->hasBeenInCreative; + this->hardcore = copy->hardcore; + this->allowCommands = copy->allowCommands; + this->initialized = copy->initialized; + this->newSeaLevel = copy->newSeaLevel; + this->hasBeenInCreative = copy->hasBeenInCreative; - // 4J-PB for the stronghold position - this->bStronghold=copy->bStronghold; - this->xStronghold = copy->xStronghold; - this->yStronghold = copy->yStronghold; - this->zStronghold = copy->zStronghold; + // 4J-PB for the stronghold position + this->bStronghold = copy->bStronghold; + this->xStronghold = copy->xStronghold; + this->yStronghold = copy->yStronghold; + this->zStronghold = copy->zStronghold; - this->xStrongholdEndPortal = copy->xStrongholdEndPortal; - this->zStrongholdEndPortal = copy->zStrongholdEndPortal; - this->bStrongholdEndPortal = copy->bStrongholdEndPortal; - m_xzSize = copy->m_xzSize; - m_hellScale = copy->m_hellScale; + this->xStrongholdEndPortal = copy->xStrongholdEndPortal; + this->zStrongholdEndPortal = copy->zStrongholdEndPortal; + this->bStrongholdEndPortal = copy->bStrongholdEndPortal; + m_xzSize = copy->m_xzSize; + m_hellScale = copy->m_hellScale; } -CompoundTag *LevelData::createTag() -{ - CompoundTag *tag = new CompoundTag(); +CompoundTag* LevelData::createTag() { + CompoundTag* tag = new CompoundTag(); setTagData(tag); return tag; } -CompoundTag *LevelData::createTag(std::vector > *players) -{ - // 4J - removed all code for storing tags for players - return createTag(); +CompoundTag* LevelData::createTag( + std::vector >* players) { + // 4J - removed all code for storing tags for players + return createTag(); } -void LevelData::setTagData(CompoundTag *tag) -{ +void LevelData::setTagData(CompoundTag* tag) { tag->putLong(L"RandomSeed", seed); - tag->putString(L"generatorName", m_pGenerator->getGeneratorName()); - tag->putInt(L"generatorVersion", m_pGenerator->getVersion()); + tag->putString(L"generatorName", m_pGenerator->getGeneratorName()); + tag->putInt(L"generatorVersion", m_pGenerator->getVersion()); tag->putInt(L"GameType", gameType->getId()); tag->putBoolean(L"MapFeatures", generateMapFeatures); - tag->putBoolean(L"spawnBonusChest",spawnBonusChest); + tag->putBoolean(L"spawnBonusChest", spawnBonusChest); tag->putInt(L"SpawnX", xSpawn); tag->putInt(L"SpawnY", ySpawn); tag->putInt(L"SpawnZ", zSpawn); @@ -269,321 +254,184 @@ void LevelData::setTagData(CompoundTag *tag) tag->putBoolean(L"raining", raining); tag->putInt(L"thunderTime", thunderTime); tag->putBoolean(L"thundering", thundering); - tag->putBoolean(L"hardcore", hardcore); - tag->putBoolean(L"allowCommands", allowCommands); - tag->putBoolean(L"initialized", initialized); - tag->putBoolean(L"newSeaLevel", newSeaLevel); - tag->putBoolean(L"hasBeenInCreative", hasBeenInCreative); - // store the stronghold position - tag->putBoolean(L"hasStronghold", bStronghold); - tag->putInt(L"StrongholdX", xStronghold); - tag->putInt(L"StrongholdY", yStronghold); - tag->putInt(L"StrongholdZ", zStronghold); - // store the stronghold end portal position - tag->putBoolean(L"hasStrongholdEndPortal", bStrongholdEndPortal); - tag->putInt(L"StrongholdEndPortalX", xStrongholdEndPortal); - tag->putInt(L"StrongholdEndPortalZ", zStrongholdEndPortal); - tag->putInt(L"XZSize", m_xzSize); - tag->putInt(L"HellScale", m_hellScale); + tag->putBoolean(L"hardcore", hardcore); + tag->putBoolean(L"allowCommands", allowCommands); + tag->putBoolean(L"initialized", initialized); + tag->putBoolean(L"newSeaLevel", newSeaLevel); + tag->putBoolean(L"hasBeenInCreative", hasBeenInCreative); + // store the stronghold position + tag->putBoolean(L"hasStronghold", bStronghold); + tag->putInt(L"StrongholdX", xStronghold); + tag->putInt(L"StrongholdY", yStronghold); + tag->putInt(L"StrongholdZ", zStronghold); + // store the stronghold end portal position + tag->putBoolean(L"hasStrongholdEndPortal", bStrongholdEndPortal); + tag->putInt(L"StrongholdEndPortalX", xStrongholdEndPortal); + tag->putInt(L"StrongholdEndPortalZ", zStrongholdEndPortal); + tag->putInt(L"XZSize", m_xzSize); + tag->putInt(L"HellScale", m_hellScale); } -__int64 LevelData::getSeed() -{ - return seed; -} +__int64 LevelData::getSeed() { return seed; } -int LevelData::getXSpawn() -{ - return xSpawn; -} +int LevelData::getXSpawn() { return xSpawn; } -int LevelData::getYSpawn() -{ - return ySpawn; -} +int LevelData::getYSpawn() { return ySpawn; } -int LevelData::getZSpawn() -{ - return zSpawn; -} +int LevelData::getZSpawn() { return zSpawn; } -int LevelData::getXStronghold() -{ - return xStronghold; -} +int LevelData::getXStronghold() { return xStronghold; } +int LevelData::getZStronghold() { return zStronghold; } -int LevelData::getZStronghold() -{ - return zStronghold; -} +int LevelData::getXStrongholdEndPortal() { return xStrongholdEndPortal; } -int LevelData::getXStrongholdEndPortal() -{ - return xStrongholdEndPortal; -} +int LevelData::getZStrongholdEndPortal() { return zStrongholdEndPortal; } +__int64 LevelData::getTime() { return time; } -int LevelData::getZStrongholdEndPortal() -{ - return zStrongholdEndPortal; -} +__int64 LevelData::getSizeOnDisk() { return sizeOnDisk; } -__int64 LevelData::getTime() -{ - return time; -} - -__int64 LevelData::getSizeOnDisk() -{ - return sizeOnDisk; -} - -CompoundTag *LevelData::getLoadedPlayerTag() -{ - return NULL; // 4J - we don't store this anymore +CompoundTag* LevelData::getLoadedPlayerTag() { + return NULL; // 4J - we don't store this anymore } // 4J Removed TU9 as it's never accurate due to the dimension never being set -//int LevelData::getDimension() +// int LevelData::getDimension() //{ // return dimension; //} -void LevelData::setSeed(__int64 seed) -{ - this->seed = seed; +void LevelData::setSeed(__int64 seed) { this->seed = seed; } + +void LevelData::setXSpawn(int xSpawn) { this->xSpawn = xSpawn; } + +void LevelData::setYSpawn(int ySpawn) { this->ySpawn = ySpawn; } + +void LevelData::setZSpawn(int zSpawn) { this->zSpawn = zSpawn; } + +void LevelData::setHasStronghold() { this->bStronghold = true; } + +bool LevelData::getHasStronghold() { return this->bStronghold; } + +void LevelData::setXStronghold(int xStronghold) { + this->xStronghold = xStronghold; } -void LevelData::setXSpawn(int xSpawn) -{ - this->xSpawn = xSpawn; +void LevelData::setZStronghold(int zStronghold) { + this->zStronghold = zStronghold; } -void LevelData::setYSpawn(int ySpawn) -{ - this->ySpawn = ySpawn; +void LevelData::setHasStrongholdEndPortal() { + this->bStrongholdEndPortal = true; } -void LevelData::setZSpawn(int zSpawn) -{ - this->zSpawn = zSpawn; +bool LevelData::getHasStrongholdEndPortal() { + return this->bStrongholdEndPortal; } -void LevelData::setHasStronghold() -{ - this->bStronghold = true; +void LevelData::setXStrongholdEndPortal(int xStrongholdEndPortal) { + this->xStrongholdEndPortal = xStrongholdEndPortal; } -bool LevelData::getHasStronghold() -{ - return this->bStronghold; +void LevelData::setZStrongholdEndPortal(int zStrongholdEndPortal) { + this->zStrongholdEndPortal = zStrongholdEndPortal; } +void LevelData::setTime(__int64 time) { this->time = time; } -void LevelData::setXStronghold(int xStronghold) -{ - this->xStronghold = xStronghold; -} - -void LevelData::setZStronghold(int zStronghold) -{ - this->zStronghold = zStronghold; -} - -void LevelData::setHasStrongholdEndPortal() -{ - this->bStrongholdEndPortal = true; -} - -bool LevelData::getHasStrongholdEndPortal() -{ - return this->bStrongholdEndPortal; -} - -void LevelData::setXStrongholdEndPortal(int xStrongholdEndPortal) -{ - this->xStrongholdEndPortal = xStrongholdEndPortal; -} - -void LevelData::setZStrongholdEndPortal(int zStrongholdEndPortal) -{ - this->zStrongholdEndPortal = zStrongholdEndPortal; -} - -void LevelData::setTime(__int64 time) -{ - this->time = time; -} - -void LevelData::setSizeOnDisk(__int64 sizeOnDisk) -{ +void LevelData::setSizeOnDisk(__int64 sizeOnDisk) { this->sizeOnDisk = sizeOnDisk; } -void LevelData::setLoadedPlayerTag(CompoundTag *loadedPlayerTag) -{ - // 4J - we don't store this anymore -// this->loadedPlayerTag = loadedPlayerTag; +void LevelData::setLoadedPlayerTag(CompoundTag* loadedPlayerTag) { + // 4J - we don't store this anymore + // this->loadedPlayerTag = loadedPlayerTag; } // 4J Remove TU9 as it's never used -//void LevelData::setDimension(int dimension) +// void LevelData::setDimension(int dimension) //{ // this->dimension = dimension; //} -void LevelData::setSpawn(int xSpawn, int ySpawn, int zSpawn) -{ +void LevelData::setSpawn(int xSpawn, int ySpawn, int zSpawn) { this->xSpawn = xSpawn; this->ySpawn = ySpawn; this->zSpawn = zSpawn; } -std::wstring LevelData::getLevelName() -{ - return levelName; -} +std::wstring LevelData::getLevelName() { return levelName; } -void LevelData::setLevelName(const std::wstring& levelName) -{ +void LevelData::setLevelName(const std::wstring& levelName) { this->levelName = levelName; } -int LevelData::getVersion() -{ - return version; -} +int LevelData::getVersion() { return version; } -void LevelData::setVersion(int version) -{ - this->version = version; -} +void LevelData::setVersion(int version) { this->version = version; } -__int64 LevelData::getLastPlayed() -{ - return lastPlayed; -} +__int64 LevelData::getLastPlayed() { return lastPlayed; } -bool LevelData::isThundering() -{ - return thundering; -} +bool LevelData::isThundering() { return thundering; } -void LevelData::setThundering(bool thundering) -{ +void LevelData::setThundering(bool thundering) { this->thundering = thundering; } -int LevelData::getThunderTime() -{ - return thunderTime; -} +int LevelData::getThunderTime() { return thunderTime; } -void LevelData::setThunderTime(int thunderTime) -{ +void LevelData::setThunderTime(int thunderTime) { this->thunderTime = thunderTime; } -bool LevelData::isRaining() -{ - return raining; +bool LevelData::isRaining() { return raining; } + +void LevelData::setRaining(bool raining) { this->raining = raining; } + +int LevelData::getRainTime() { return rainTime; } + +void LevelData::setRainTime(int rainTime) { this->rainTime = rainTime; } + +GameType* LevelData::getGameType() { return gameType; } + +bool LevelData::isGenerateMapFeatures() { return generateMapFeatures; } + +bool LevelData::getSpawnBonusChest() { return spawnBonusChest; } + +void LevelData::setGameType(GameType* gameType) { + this->gameType = gameType; + + // 4J Added + hasBeenInCreative = + hasBeenInCreative || (gameType == GameType::CREATIVE) || + app.GetGameHostOption(eGameHostOption_CheatsEnabled) > 0; } -void LevelData::setRaining(bool raining) -{ - this->raining = raining; +bool LevelData::useNewSeaLevel() { return newSeaLevel; } + +bool LevelData::getHasBeenInCreative() { return hasBeenInCreative; } + +void LevelData::setHasBeenInCreative(bool value) { hasBeenInCreative = value; } + +LevelType* LevelData::getGenerator() { return m_pGenerator; } + +void LevelData::setGenerator(LevelType* generator) { m_pGenerator = generator; } + +bool LevelData::isHardcore() { return hardcore; } + +bool LevelData::getAllowCommands() { return allowCommands; } + +void LevelData::setAllowCommands(bool allowCommands) { + this->allowCommands = allowCommands; } -int LevelData::getRainTime() -{ - return rainTime; +bool LevelData::isInitialized() { return initialized; } + +void LevelData::setInitialized(bool initialized) { + this->initialized = initialized; } -void LevelData::setRainTime(int rainTime) -{ - this->rainTime = rainTime; -} +int LevelData::getXZSize() { return m_xzSize; } -GameType *LevelData::getGameType() -{ - return gameType; -} - -bool LevelData::isGenerateMapFeatures() -{ - return generateMapFeatures; -} - -bool LevelData::getSpawnBonusChest() -{ - return spawnBonusChest; -} - -void LevelData::setGameType(GameType *gameType) -{ - this->gameType = gameType; - - // 4J Added - hasBeenInCreative = hasBeenInCreative || (gameType == GameType::CREATIVE) || app.GetGameHostOption(eGameHostOption_CheatsEnabled) > 0; -} - -bool LevelData::useNewSeaLevel() -{ - return newSeaLevel; -} - -bool LevelData::getHasBeenInCreative() -{ - return hasBeenInCreative; -} - -void LevelData::setHasBeenInCreative(bool value) -{ - hasBeenInCreative = value; -} - -LevelType *LevelData::getGenerator() -{ - return m_pGenerator; -} - -void LevelData::setGenerator(LevelType *generator) -{ - m_pGenerator = generator; -} - -bool LevelData::isHardcore() -{ - return hardcore; -} - -bool LevelData::getAllowCommands() -{ - return allowCommands; -} - -void LevelData::setAllowCommands(bool allowCommands) -{ - this->allowCommands = allowCommands; -} - -bool LevelData::isInitialized() -{ - return initialized; -} - -void LevelData::setInitialized(bool initialized) -{ - this->initialized = initialized; -} - -int LevelData::getXZSize() -{ - return m_xzSize; -} - -int LevelData::getHellScale() -{ - return m_hellScale; -} +int LevelData::getHellScale() { return m_hellScale; } diff --git a/Minecraft.World/Level/LevelData.h b/Minecraft.World/Level/LevelData.h index 8e8cb77a8..af065de6f 100644 --- a/Minecraft.World/Level/LevelData.h +++ b/Minecraft.World/Level/LevelData.h @@ -1,25 +1,24 @@ #pragma once - class Player; class CompoundTag; class LevelSettings; class LevelType; class GameType; -class LevelData -{ - friend class DerivedLevelData; +class LevelData { + friend class DerivedLevelData; + private: - __int64 seed; - LevelType *m_pGenerator;// = LevelType.normal; + __int64 seed; + LevelType* m_pGenerator; // = LevelType.normal; int xSpawn; int ySpawn; int zSpawn; __int64 time; __int64 lastPlayed; __int64 sizeOnDisk; -// CompoundTag *loadedPlayerTag; // 4J removed + // CompoundTag *loadedPlayerTag; // 4J removed int dimension; std::wstring levelName; int version; @@ -29,106 +28,102 @@ private: bool thundering; int thunderTime; - GameType *gameType; - bool generateMapFeatures; - bool hardcore; - bool allowCommands; - bool initialized; - bool newSeaLevel; // 4J added - bool hasBeenInCreative; // 4J added - bool spawnBonusChest; // 4J added - int m_xzSize; // 4J Added - int m_hellScale; // 4J Added + GameType* gameType; + bool generateMapFeatures; + bool hardcore; + bool allowCommands; + bool initialized; + bool newSeaLevel; // 4J added + bool hasBeenInCreative; // 4J added + bool spawnBonusChest; // 4J added + int m_xzSize; // 4J Added + int m_hellScale; // 4J Added - // 4J added - int xStronghold; - int yStronghold; - int zStronghold; - bool bStronghold; + // 4J added + int xStronghold; + int yStronghold; + int zStronghold; + bool bStronghold; - int xStrongholdEndPortal; - int zStrongholdEndPortal; - bool bStrongholdEndPortal; + int xStrongholdEndPortal; + int zStrongholdEndPortal; + bool bStrongholdEndPortal; protected: - LevelData(); + LevelData(); public: - LevelData(CompoundTag *tag); - LevelData(LevelSettings *levelSettings, const std::wstring& levelName); - LevelData(LevelData *copy); - CompoundTag *createTag(); - CompoundTag *createTag(std::vector > *players); + LevelData(CompoundTag* tag); + LevelData(LevelSettings* levelSettings, const std::wstring& levelName); + LevelData(LevelData* copy); + CompoundTag* createTag(); + CompoundTag* createTag(std::vector >* players); - enum - { - DIMENSION_NETHER=-1, - DIMENSION_OVERWORLD=0, - DIMENSION_END=1 - }; + enum { DIMENSION_NETHER = -1, DIMENSION_OVERWORLD = 0, DIMENSION_END = 1 }; protected: - virtual void setTagData(CompoundTag *tag); // 4J - removed CompoundTag *playerTag + virtual void setTagData( + CompoundTag* tag); // 4J - removed CompoundTag *playerTag public: - virtual ~LevelData(){} - virtual __int64 getSeed(); - virtual int getXSpawn(); - virtual int getYSpawn(); - virtual int getZSpawn(); - virtual int getXStronghold(); - virtual int getZStronghold(); - virtual int getXStrongholdEndPortal(); - virtual int getZStrongholdEndPortal(); - virtual __int64 getTime(); - virtual __int64 getSizeOnDisk(); - virtual CompoundTag *getLoadedPlayerTag(); - //int getDimension(); // 4J Removed TU 9 as it's never accurate - virtual void setSeed(__int64 seed); - virtual void setXSpawn(int xSpawn); - virtual void setYSpawn(int ySpawn); - virtual void setZSpawn(int zSpawn); - virtual void setHasStronghold(); - virtual bool getHasStronghold(); - virtual void setXStronghold(int xStronghold); - virtual void setZStronghold(int zStronghold); - virtual void setHasStrongholdEndPortal(); - virtual bool getHasStrongholdEndPortal(); - virtual void setXStrongholdEndPortal(int xStrongholdEndPortal); - virtual void setZStrongholdEndPortal(int zStrongholdEndPortal); + virtual ~LevelData() {} + virtual __int64 getSeed(); + virtual int getXSpawn(); + virtual int getYSpawn(); + virtual int getZSpawn(); + virtual int getXStronghold(); + virtual int getZStronghold(); + virtual int getXStrongholdEndPortal(); + virtual int getZStrongholdEndPortal(); + virtual __int64 getTime(); + virtual __int64 getSizeOnDisk(); + virtual CompoundTag* getLoadedPlayerTag(); + // int getDimension(); // 4J Removed TU 9 as it's never accurate + virtual void setSeed(__int64 seed); + virtual void setXSpawn(int xSpawn); + virtual void setYSpawn(int ySpawn); + virtual void setZSpawn(int zSpawn); + virtual void setHasStronghold(); + virtual bool getHasStronghold(); + virtual void setXStronghold(int xStronghold); + virtual void setZStronghold(int zStronghold); + virtual void setHasStrongholdEndPortal(); + virtual bool getHasStrongholdEndPortal(); + virtual void setXStrongholdEndPortal(int xStrongholdEndPortal); + virtual void setZStrongholdEndPortal(int zStrongholdEndPortal); - virtual void setTime(__int64 time); - virtual void setSizeOnDisk(__int64 sizeOnDisk); - virtual void setLoadedPlayerTag(CompoundTag *loadedPlayerTag); - //void setDimension(int dimension); // 4J Removed TU 9 as it's never used - virtual void setSpawn(int xSpawn, int ySpawn, int zSpawn); - virtual std::wstring getLevelName(); - virtual void setLevelName(const std::wstring& levelName); - virtual int getVersion(); - virtual void setVersion(int version); - virtual __int64 getLastPlayed(); - virtual bool isThundering(); - virtual void setThundering(bool thundering); - virtual int getThunderTime(); - virtual void setThunderTime(int thunderTime); - virtual bool isRaining(); - virtual void setRaining(bool raining); - virtual int getRainTime(); - virtual void setRainTime(int rainTime); - virtual GameType *getGameType(); - virtual bool isGenerateMapFeatures(); - virtual bool getSpawnBonusChest(); - virtual void setGameType(GameType *gameType); - virtual bool useNewSeaLevel(); - virtual bool getHasBeenInCreative(); // 4J Added - virtual void setHasBeenInCreative(bool value); // 4J Added - virtual LevelType *getGenerator(); - virtual void setGenerator(LevelType *generator); - virtual bool isHardcore(); - virtual bool getAllowCommands(); - virtual void setAllowCommands(bool allowCommands); - virtual bool isInitialized(); - virtual void setInitialized(bool initialized); - virtual int getXZSize(); // 4J Added - virtual int getHellScale(); // 4J Addded + virtual void setTime(__int64 time); + virtual void setSizeOnDisk(__int64 sizeOnDisk); + virtual void setLoadedPlayerTag(CompoundTag* loadedPlayerTag); + // void setDimension(int dimension); // 4J Removed TU 9 as it's never used + virtual void setSpawn(int xSpawn, int ySpawn, int zSpawn); + virtual std::wstring getLevelName(); + virtual void setLevelName(const std::wstring& levelName); + virtual int getVersion(); + virtual void setVersion(int version); + virtual __int64 getLastPlayed(); + virtual bool isThundering(); + virtual void setThundering(bool thundering); + virtual int getThunderTime(); + virtual void setThunderTime(int thunderTime); + virtual bool isRaining(); + virtual void setRaining(bool raining); + virtual int getRainTime(); + virtual void setRainTime(int rainTime); + virtual GameType* getGameType(); + virtual bool isGenerateMapFeatures(); + virtual bool getSpawnBonusChest(); + virtual void setGameType(GameType* gameType); + virtual bool useNewSeaLevel(); + virtual bool getHasBeenInCreative(); // 4J Added + virtual void setHasBeenInCreative(bool value); // 4J Added + virtual LevelType* getGenerator(); + virtual void setGenerator(LevelType* generator); + virtual bool isHardcore(); + virtual bool getAllowCommands(); + virtual void setAllowCommands(bool allowCommands); + virtual bool isInitialized(); + virtual void setInitialized(bool initialized); + virtual int getXZSize(); // 4J Added + virtual int getHellScale(); // 4J Addded }; diff --git a/Minecraft.World/Level/RandomLevelSource.cpp b/Minecraft.World/Level/RandomLevelSource.cpp index df7070bc9..eaea7a427 100644 --- a/Minecraft.World/Level/RandomLevelSource.cpp +++ b/Minecraft.World/Level/RandomLevelSource.cpp @@ -19,25 +19,27 @@ static PerlinNoise_DataIn g_scaleNoise_SPU __attribute__((__aligned__(16))); static PerlinNoise_DataIn g_depthNoise_SPU __attribute__((__aligned__(16))); #endif - const double RandomLevelSource::SNOW_SCALE = 0.3; const double RandomLevelSource::SNOW_CUTOFF = 0.5; -RandomLevelSource::RandomLevelSource(Level *level, __int64 seed, bool generateStructures) : generateStructures( generateStructures ) -{ - m_XZSize = level->getLevelData()->getXZSize(); +RandomLevelSource::RandomLevelSource(Level* level, __int64 seed, + bool generateStructures) + : generateStructures(generateStructures) { + m_XZSize = level->getLevelData()->getXZSize(); - caveFeature = new LargeCaveFeature(); - strongholdFeature = new StrongholdFeature(); - villageFeature = new VillageFeature(0,m_XZSize); + caveFeature = new LargeCaveFeature(); + strongholdFeature = new StrongholdFeature(); + villageFeature = new VillageFeature(0, m_XZSize); mineShaftFeature = new MineShaftFeature(); - scatteredFeature = new RandomScatteredLargeFeature(); - canyonFeature = new CanyonFeature(); + scatteredFeature = new RandomScatteredLargeFeature(); + canyonFeature = new CanyonFeature(); this->level = level; random = new Random(seed); - pprandom = new Random(seed); // 4J - added, so that we can have a separate random for doing post-processing in parallel with creation + pprandom = new Random( + seed); // 4J - added, so that we can have a separate random for doing + // post-processing in parallel with creation lperlinNoise1 = new PerlinNoise(random, 16); lperlinNoise2 = new PerlinNoise(random, 16); perlinNoise1 = new PerlinNoise(random, 8); @@ -46,30 +48,27 @@ RandomLevelSource::RandomLevelSource(Level *level, __int64 seed, bool generateSt scaleNoise = new PerlinNoise(random, 10); depthNoise = new PerlinNoise(random, 16); - if (FLOATING_ISLANDS) - { + if (FLOATING_ISLANDS) { floatingIslandScale = new PerlinNoise(random, 10); floatingIslandNoise = new PerlinNoise(random, 16); + } else { + floatingIslandScale = NULL; + floatingIslandNoise = NULL; } - else - { - floatingIslandScale = NULL; - floatingIslandNoise = NULL; - } forestNoise = new PerlinNoise(random, 8); } -RandomLevelSource::~RandomLevelSource() -{ - delete caveFeature; - delete strongholdFeature; - delete villageFeature; - delete mineShaftFeature; - delete scatteredFeature; - delete canyonFeature; +RandomLevelSource::~RandomLevelSource() { + delete caveFeature; + delete strongholdFeature; + delete villageFeature; + delete mineShaftFeature; + delete scatteredFeature; + delete canyonFeature; - delete random;; + delete random; + ; delete lperlinNoise1; delete lperlinNoise2; delete perlinNoise1; @@ -78,144 +77,172 @@ RandomLevelSource::~RandomLevelSource() delete scaleNoise; delete depthNoise; - if (FLOATING_ISLANDS) - { + if (FLOATING_ISLANDS) { delete floatingIslandScale; delete floatingIslandNoise; } delete forestNoise; - if( pows.data != NULL ) delete [] pows.data; + if (pows.data != NULL) delete[] pows.data; } - int g_numPrepareHeightCalls = 0; -LARGE_INTEGER g_totalPrepareHeightsTime = {0,0}; +LARGE_INTEGER g_totalPrepareHeightsTime = {0, 0}; LARGE_INTEGER g_averagePrepareHeightsTime = {0, 0}; - -void RandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) -{ - LARGE_INTEGER startTime; +void RandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) { + LARGE_INTEGER startTime; int xChunks = 16 / CHUNK_WIDTH; - int yChunks = Level::genDepth / CHUNK_HEIGHT; - int waterHeight = level->seaLevel; + int yChunks = Level::genDepth / CHUNK_HEIGHT; + int waterHeight = level->seaLevel; int xSize = xChunks + 1; int ySize = Level::genDepth / CHUNK_HEIGHT + 1; int zSize = xChunks + 1; - BiomeArray biomes; // 4J created locally here for thread safety, java has this as a class member + BiomeArray biomes; // 4J created locally here for thread safety, java has + // this as a class member - level->getBiomeSource()->getRawBiomeBlock(biomes, xOffs * CHUNK_WIDTH - 2, zOffs * CHUNK_WIDTH - 2, xSize + 5, zSize + 5); + level->getBiomeSource()->getRawBiomeBlock(biomes, xOffs * CHUNK_WIDTH - 2, + zOffs * CHUNK_WIDTH - 2, + xSize + 5, zSize + 5); - doubleArray buffer; // 4J - used to be declared with class level scope but tidying up for thread safety reasons - buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, ySize, zSize, biomes); + doubleArray buffer; // 4J - used to be declared with class level scope but + // tidying up for thread safety reasons + buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, + ySize, zSize, biomes); - QueryPerformanceCounter(&startTime); - for (int xc = 0; xc < xChunks; xc++) - { - for (int zc = 0; zc < xChunks; zc++) - { - for (int yc = 0; yc < yChunks; yc++) - { - double yStep = 1 / (double) CHUNK_HEIGHT; - double s0 = buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s1 = buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s2 = buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s3 = buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; + QueryPerformanceCounter(&startTime); + for (int xc = 0; xc < xChunks; xc++) { + for (int zc = 0; zc < xChunks; zc++) { + for (int yc = 0; yc < yChunks; yc++) { + double yStep = 1 / (double)CHUNK_HEIGHT; + double s0 = + buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s1 = + buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; + double s2 = + buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s3 = + buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s0a = (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - s0) * yStep; - double s1a = (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - s1) * yStep; - double s2a = (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - s2) * yStep; - double s3a = (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - s3) * yStep; + double s0a = + (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s0) * + yStep; + double s1a = + (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s1) * + yStep; + double s2a = + (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s2) * + yStep; + double s3a = + (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s3) * + yStep; - for (int y = 0; y < CHUNK_HEIGHT; y++) - { - double xStep = 1 / (double) CHUNK_WIDTH; + for (int y = 0; y < CHUNK_HEIGHT; y++) { + double xStep = 1 / (double)CHUNK_WIDTH; double _s0 = s0; double _s1 = s1; double _s0a = (s2 - s0) * xStep; double _s1a = (s3 - s1) * xStep; - for (int x = 0; x < CHUNK_WIDTH; x++) - { - int offs = (unsigned) (x + (unsigned) xc * CHUNK_WIDTH) << Level::genDepthBitsPlusFour | ((unsigned) zc * CHUNK_WIDTH) << Level::genDepthBits | (yc * CHUNK_HEIGHT + y); + for (int x = 0; x < CHUNK_WIDTH; x++) { + int offs = (unsigned)(x + (unsigned)xc * CHUNK_WIDTH) + << Level::genDepthBitsPlusFour | + ((unsigned)zc * CHUNK_WIDTH) + << Level::genDepthBits | + (yc * CHUNK_HEIGHT + y); int step = 1 << Level::genDepthBits; - offs -= step; - double zStep = 1 / (double) CHUNK_WIDTH; + offs -= step; + double zStep = 1 / (double)CHUNK_WIDTH; double val = _s0; double vala = (_s1 - _s0) * zStep; - val -= vala; - for (int z = 0; z < CHUNK_WIDTH; z++) - { - /////////////////////////////////////////////////////////////////// - // 4J - add this chunk of code to make land "fall-off" at the edges of - // a finite world - size of that world is currently hard-coded in here - const int worldSize = m_XZSize * 16; - const int falloffStart = 32; // chunks away from edge were we start doing fall-off - const float falloffMax = 128.0f; // max value we need to get to falloff by the edge of the map - - int xxx = ( ( xOffs * 16 ) + x + ( xc * CHUNK_WIDTH ) ); - int zzz = ( ( zOffs * 16 ) + z + ( zc * CHUNK_WIDTH ) ); + val -= vala; + for (int z = 0; z < CHUNK_WIDTH; z++) { + /////////////////////////////////////////////////////////////////// + // 4J - add this chunk of code to make land + // "fall-off" at the edges of a finite world - size + // of that world is currently hard-coded in here + const int worldSize = m_XZSize * 16; + const int falloffStart = + 32; // chunks away from edge were we start + // doing fall-off + const float falloffMax = + 128.0f; // max value we need to get to falloff + // by the edge of the map - // Get distance to edges of world in x - int xxx0 = xxx + ( worldSize / 2 ); - if( xxx0 < 0 ) xxx0 = 0; - int xxx1 = ( ( worldSize / 2 ) - 1 ) - xxx; - if( xxx1 < 0 ) xxx1 = 0; + int xxx = ((xOffs * 16) + x + (xc * CHUNK_WIDTH)); + int zzz = ((zOffs * 16) + z + (zc * CHUNK_WIDTH)); - // Get distance to edges of world in z - int zzz0 = zzz + ( worldSize / 2 ); - if( zzz0 < 0 ) zzz0 = 0; - int zzz1 = ( ( worldSize / 2 ) - 1 ) - zzz; - if( zzz1 < 0 ) zzz1 = 0; + // Get distance to edges of world in x + int xxx0 = xxx + (worldSize / 2); + if (xxx0 < 0) xxx0 = 0; + int xxx1 = ((worldSize / 2) - 1) - xxx; + if (xxx1 < 0) xxx1 = 0; - // Get min distance to any edge - int emin = xxx0; - if (xxx1 < emin ) emin = xxx1; - if (zzz0 < emin ) emin = zzz0; - if (zzz1 < emin ) emin = zzz1; + // Get distance to edges of world in z + int zzz0 = zzz + (worldSize / 2); + if (zzz0 < 0) zzz0 = 0; + int zzz1 = ((worldSize / 2) - 1) - zzz; + if (zzz1 < 0) zzz1 = 0; - float comp = 0.0f; + // Get min distance to any edge + int emin = xxx0; + if (xxx1 < emin) emin = xxx1; + if (zzz0 < emin) emin = zzz0; + if (zzz1 < emin) emin = zzz1; - // Calculate how much we want the world to fall away, if we're in the defined region to do so - if( emin < falloffStart ) - { - int falloff = falloffStart - emin; - comp = ((float)falloff / (float)falloffStart ) * falloffMax; - } - // 4J - end of extra code - /////////////////////////////////////////////////////////////////// + float comp = 0.0f; - // 4J - slightly rearranged this code (as of java 1.0.1 merge) to better fit with - // changes we've made edge-of-world things - original sets blocks[offs += step] directly - // here rather than setting a tileId - int tileId = 0; - // 4J - this comparison used to just be with 0.0f but is now varied by block above - if ((val += vala) > comp) - { - tileId = (uint8_t) Tile::rock_Id; + // Calculate how much we want the world to fall + // away, if we're in the defined region to do so + if (emin < falloffStart) { + int falloff = falloffStart - emin; + comp = ((float)falloff / (float)falloffStart) * + falloffMax; } - else if (yc * CHUNK_HEIGHT + y < waterHeight) - { - tileId = (uint8_t) Tile::calmWater_Id; + // 4J - end of extra code + /////////////////////////////////////////////////////////////////// + + // 4J - slightly rearranged this code (as of + // java 1.0.1 merge) to better fit with changes + // we've made edge-of-world things - original sets + // blocks[offs += step] directly here rather than + // setting a tileId + int tileId = 0; + // 4J - this comparison used to just be with 0.0f + // but is now varied by block above + if ((val += vala) > comp) { + tileId = (uint8_t)Tile::rock_Id; + } else if (yc * CHUNK_HEIGHT + y < waterHeight) { + tileId = (uint8_t)Tile::calmWater_Id; } - // 4J - more extra code to make sure that the column at the edge of the world is just water & rock, to match the infinite sea that - // continues on after the edge of the world. + // 4J - more extra code to make sure that the column + // at the edge of the world is just water & rock, to + // match the infinite sea that continues on after + // the edge of the world. - if( emin == 0 ) - { - // This matches code in MultiPlayerChunkCache that makes the geometry which continues at the edge of the world - if( yc * CHUNK_HEIGHT + y <= ( level->getSeaLevel() - 10 ) ) tileId = Tile::rock_Id; - else if( yc * CHUNK_HEIGHT + y < level->getSeaLevel() ) tileId = Tile::calmWater_Id; - } + if (emin == 0) { + // This matches code in MultiPlayerChunkCache + // that makes the geometry which continues at + // the edge of the world + if (yc * CHUNK_HEIGHT + y <= + (level->getSeaLevel() - 10)) + tileId = Tile::rock_Id; + else if (yc * CHUNK_HEIGHT + y < + level->getSeaLevel()) + tileId = Tile::calmWater_Id; + } - blocks[offs += step] = tileId; + blocks[offs += step] = tileId; } _s0 += _s0a; _s1 += _s1a; @@ -229,107 +256,98 @@ void RandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) } } } - LARGE_INTEGER endTime; - QueryPerformanceCounter(&endTime); - LARGE_INTEGER timeInFunc; - timeInFunc.QuadPart = endTime.QuadPart - startTime.QuadPart; - g_numPrepareHeightCalls++; - g_totalPrepareHeightsTime.QuadPart += timeInFunc.QuadPart; - g_averagePrepareHeightsTime.QuadPart = g_totalPrepareHeightsTime.QuadPart / g_numPrepareHeightCalls; - - delete [] buffer.data; - delete [] biomes.data; - + LARGE_INTEGER endTime; + QueryPerformanceCounter(&endTime); + LARGE_INTEGER timeInFunc; + timeInFunc.QuadPart = endTime.QuadPart - startTime.QuadPart; + g_numPrepareHeightCalls++; + g_totalPrepareHeightsTime.QuadPart += timeInFunc.QuadPart; + g_averagePrepareHeightsTime.QuadPart = + g_totalPrepareHeightsTime.QuadPart / g_numPrepareHeightCalls; + delete[] buffer.data; + delete[] biomes.data; } - -void RandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes) -{ +void RandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes) { int waterHeight = level->seaLevel; double s = 1 / 32.0; - doubleArray depthBuffer(16*16); // 4J - used to be declared with class level scope but moved here for thread safety + doubleArray depthBuffer(16 * + 16); // 4J - used to be declared with class level + // scope but moved here for thread safety - depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, 0, 16, 16, 1, s * 2, s * 2, s * 2); + depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, + 0, 16, 16, 1, s * 2, s * 2, s * 2); - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { - Biome *b = biomes[z + x * 16]; - float temp = b->getTemperature(); - int runDepth = (int) (depthBuffer[x + z * 16] / 3 + 3 + random->nextDouble() * 0.25); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + Biome* b = biomes[z + x * 16]; + float temp = b->getTemperature(); + int runDepth = (int)(depthBuffer[x + z * 16] / 3 + 3 + + random->nextDouble() * 0.25); int run = -1; uint8_t top = b->topMaterial; uint8_t material = b->material; - LevelGenerationOptions *lgo = app.getLevelGenerationOptions(); - if(lgo != NULL) - { - lgo->getBiomeOverride(b->id,material,top); - } + LevelGenerationOptions* lgo = app.getLevelGenerationOptions(); + if (lgo != NULL) { + lgo->getBiomeOverride(b->id, material, top); + } - for (int y = Level::genDepthMinusOne; y >= 0; y--) - { + for (int y = Level::genDepthMinusOne; y >= 0; y--) { int offs = (z * 16 + x) * Level::genDepth + y; - if (y <= 1 + random->nextInt(2)) // 4J - changed to make the bedrock not have bits you can get stuck in -// if (y <= 0 + random->nextInt(5)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - } - else - { + if (y <= 1 + random->nextInt( + 2)) // 4J - changed to make the bedrock not + // have bits you can get stuck in + // if (y <= 0 + random->nextInt(5)) + { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + } else { int old = blocks[offs]; - if (old == 0) - { + if (old == 0) { run = -1; - } - else if (old == Tile::rock_Id) - { - if (run == -1) - { - if (runDepth <= 0) - { + } else if (old == Tile::rock_Id) { + if (run == -1) { + if (runDepth <= 0) { top = 0; - material = (uint8_t) Tile::rock_Id; - } - else if (y >= waterHeight - 4 && y <= waterHeight + 1) - { + material = (uint8_t)Tile::rock_Id; + } else if (y >= waterHeight - 4 && + y <= waterHeight + 1) { top = b->topMaterial; - material = b->material; - if(lgo != NULL) - { - lgo->getBiomeOverride(b->id,material,top); - } + material = b->material; + if (lgo != NULL) { + lgo->getBiomeOverride(b->id, material, top); + } } - if (y < waterHeight && top == 0) - { - if (temp < 0.15f) top = (uint8_t) Tile::ice_Id; - else top = (uint8_t) Tile::calmWater_Id; + if (y < waterHeight && top == 0) { + if (temp < 0.15f) + top = (uint8_t)Tile::ice_Id; + else + top = (uint8_t)Tile::calmWater_Id; } run = runDepth; - if (y >= waterHeight - 1) blocks[offs] = top; - else blocks[offs] = material; - } - else if (run > 0) - { + if (y >= waterHeight - 1) + blocks[offs] = top; + else + blocks[offs] = material; + } else if (run > 0) { run--; blocks[offs] = material; // place a few sandstone blocks beneath sand // runs - if (run == 0 && material == Tile::sand_Id) - { + if (run == 0 && material == Tile::sand_Id) { run = random->nextInt(4); - material = (uint8_t) Tile::sandStone_Id; + material = (uint8_t)Tile::sandStone_Id; } } } @@ -338,203 +356,202 @@ void RandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, Bi } } - delete [] depthBuffer.data; - + delete[] depthBuffer.data; } -LevelChunk *RandomLevelSource::create(int x, int z) -{ - return getChunk(x,z); -} +LevelChunk* RandomLevelSource::create(int x, int z) { return getChunk(x, z); } -LevelChunk *RandomLevelSource::getChunk(int xOffs, int zOffs) -{ +LevelChunk* RandomLevelSource::getChunk(int xOffs, int zOffs) { random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - int blocksSize = Level::genDepth * 16 * 16; - uint8_t *tileData = (uint8_t *)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,blocksSize); - byteArray blocks = byteArray(tileData,blocksSize); -// byteArray blocks = byteArray(16 * level->depth * 16); + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + int blocksSize = Level::genDepth * 16 * 16; + uint8_t* tileData = (uint8_t*)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); + XMemSet128(tileData, 0, blocksSize); + byteArray blocks = byteArray(tileData, blocksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); - // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); // 4J - moved to below + // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + // // 4J - moved to below - prepareHeights(xOffs, zOffs, blocks); + prepareHeights(xOffs, zOffs, blocks); - // 4J - Some changes made here to how biomes, temperatures and downfalls are passed around for thread safety - BiomeArray biomes; - level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, 16, true); + // 4J - Some changes made here to how biomes, temperatures and downfalls are + // passed around for thread safety + BiomeArray biomes; + level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, + 16, true); buildSurfaces(xOffs, zOffs, blocks, biomes); - delete [] biomes.data; + delete[] biomes.data; caveFeature->apply(this, level, xOffs, zOffs, blocks); - // 4J Stu Design Change - 1.8 gen goes stronghold, mineshaft, village, canyon - // this changed in 1.2 to canyon, mineshaft, village, stronghold - // This change makes sense as it stops canyons running through other structures - canyonFeature->apply(this, level, xOffs, zOffs, blocks); - if (generateStructures) - { - mineShaftFeature->apply(this, level, xOffs, zOffs, blocks); - villageFeature->apply(this, level, xOffs, zOffs, blocks); - strongholdFeature->apply(this, level, xOffs, zOffs, blocks); - scatteredFeature->apply(this, level, xOffs, zOffs, blocks); - } -// canyonFeature.apply(this, level, xOffs, zOffs, blocks); + // 4J Stu Design Change - 1.8 gen goes stronghold, mineshaft, village, + // canyon this changed in 1.2 to canyon, mineshaft, village, stronghold This + // change makes sense as it stops canyons running through other structures + canyonFeature->apply(this, level, xOffs, zOffs, blocks); + if (generateStructures) { + mineShaftFeature->apply(this, level, xOffs, zOffs, blocks); + villageFeature->apply(this, level, xOffs, zOffs, blocks); + strongholdFeature->apply(this, level, xOffs, zOffs, blocks); + scatteredFeature->apply(this, level, xOffs, zOffs, blocks); + } + // canyonFeature.apply(this, level, xOffs, zOffs, blocks); // townFeature.apply(this, level, xOffs, zOffs, blocks); // addCaves(xOffs, zOffs, blocks); // addTowns(xOffs, zOffs, blocks); -// levelChunk->recalcHeightmap(); // 4J - removed & moved into its own method + // levelChunk->recalcHeightmap(); // 4J - removed & moved + // into its own method - // 4J - this now creates compressed block data from the blocks array passed in, so moved it until after the blocks are actually finalised. We also - // now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - XPhysicalFree(tileData); + // 4J - this now creates compressed block data from the blocks array passed + // in, so moved it until after the blocks are actually finalised. We also + // now need to free the passed in blocks as the LevelChunk doesn't use the + // passed in allocation anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + XPhysicalFree(tileData); return levelChunk; } -// 4J - removed & moved into its own method from getChunk, so we can call recalcHeightmap after the chunk is added into the cache. Without -// doing this, then loads of the lightgaps() calls will fail to add any lights, because adding a light checks if the cache has this chunk in. -// lightgaps also does light 1 block into the neighbouring chunks, and maybe that is somehow enough to get lighting to propagate round the world, -// but this just doesn't seem right - this isn't a new fault in the 360 version, have checked that java does the same. -void RandomLevelSource::lightChunk(LevelChunk *lc) -{ - lc->recalcHeightmap(); -} +// 4J - removed & moved into its own method from getChunk, so we can call +// recalcHeightmap after the chunk is added into the cache. Without doing this, +// then loads of the lightgaps() calls will fail to add any lights, because +// adding a light checks if the cache has this chunk in. lightgaps also does +// light 1 block into the neighbouring chunks, and maybe that is somehow enough +// to get lighting to propagate round the world, but this just doesn't seem +// right - this isn't a new fault in the 360 version, have checked that java +// does the same. +void RandomLevelSource::lightChunk(LevelChunk* lc) { lc->recalcHeightmap(); } - -doubleArray RandomLevelSource::getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize, BiomeArray& biomes) -{ - if (buffer.data == NULL) - { +doubleArray RandomLevelSource::getHeights(doubleArray buffer, int x, int y, + int z, int xSize, int ySize, + int zSize, BiomeArray& biomes) { + if (buffer.data == NULL) { buffer = doubleArray(xSize * ySize * zSize); } - if (pows.data == NULL) - { - pows = floatArray(5 * 5); - for (int xb = -2; xb <= 2; xb++) - { - for (int zb = -2; zb <= 2; zb++) - { - float ppp = 10.0f / Mth::sqrt(xb * xb + zb * zb + 0.2f); - pows[xb + 2 + (zb + 2) * 5] = ppp; - } - } - } + if (pows.data == NULL) { + pows = floatArray(5 * 5); + for (int xb = -2; xb <= 2; xb++) { + for (int zb = -2; zb <= 2; zb++) { + float ppp = 10.0f / Mth::sqrt(xb * xb + zb * zb + 0.2f); + pows[xb + 2 + (zb + 2) * 5] = ppp; + } + } + } double s = 1 * 684.412; double hs = 1 * 684.412; - doubleArray pnr, ar, br, sr, dr, fi, fis; // 4J - used to be declared with class level scope but moved here for thread safety + doubleArray pnr, ar, br, sr, dr, fi, + fis; // 4J - used to be declared with class level scope but moved here + // for thread safety - if (FLOATING_ISLANDS) - { - fis = floatingIslandScale->getRegion(fis, x, y, z, xSize, 1, zSize, 1.0, 0, 1.0); - fi = floatingIslandNoise->getRegion(fi, x, y, z, xSize, 1, zSize, 500.0, 0, 500.0); + if (FLOATING_ISLANDS) { + fis = floatingIslandScale->getRegion(fis, x, y, z, xSize, 1, zSize, 1.0, + 0, 1.0); + fi = floatingIslandNoise->getRegion(fi, x, y, z, xSize, 1, zSize, 500.0, + 0, 500.0); } #if defined __PS3__ && !defined DISABLE_SPU_CODE - C4JSpursJobQueue::Port port("C4JSpursJob_PerlinNoise"); - C4JSpursJob_PerlinNoise perlinJob1(&g_scaleNoise_SPU); - C4JSpursJob_PerlinNoise perlinJob2(&g_depthNoise_SPU); - C4JSpursJob_PerlinNoise perlinJob3(&g_perlinNoise1_SPU); - C4JSpursJob_PerlinNoise perlinJob4(&g_lperlinNoise1_SPU); - C4JSpursJob_PerlinNoise perlinJob5(&g_lperlinNoise2_SPU); + C4JSpursJobQueue::Port port("C4JSpursJob_PerlinNoise"); + C4JSpursJob_PerlinNoise perlinJob1(&g_scaleNoise_SPU); + C4JSpursJob_PerlinNoise perlinJob2(&g_depthNoise_SPU); + C4JSpursJob_PerlinNoise perlinJob3(&g_perlinNoise1_SPU); + C4JSpursJob_PerlinNoise perlinJob4(&g_lperlinNoise1_SPU); + C4JSpursJob_PerlinNoise perlinJob5(&g_lperlinNoise2_SPU); - g_scaleNoise_SPU.set(scaleNoise, sr, x, z, xSize, zSize, 1.121, 1.121, 0.5); - g_depthNoise_SPU.set(depthNoise, dr, x, z, xSize, zSize, 200.0, 200.0, 0.5); - g_perlinNoise1_SPU.set(perlinNoise1, pnr, x, y, z, xSize, ySize, zSize, s / 80.0, hs / 160.0, s / 80.0); - g_lperlinNoise1_SPU.set(lperlinNoise1, ar, x, y, z, xSize, ySize, zSize, s, hs, s); - g_lperlinNoise2_SPU.set(lperlinNoise2, br, x, y, z, xSize, ySize, zSize, s, hs, s); + g_scaleNoise_SPU.set(scaleNoise, sr, x, z, xSize, zSize, 1.121, 1.121, 0.5); + g_depthNoise_SPU.set(depthNoise, dr, x, z, xSize, zSize, 200.0, 200.0, 0.5); + g_perlinNoise1_SPU.set(perlinNoise1, pnr, x, y, z, xSize, ySize, zSize, + s / 80.0, hs / 160.0, s / 80.0); + g_lperlinNoise1_SPU.set(lperlinNoise1, ar, x, y, z, xSize, ySize, zSize, s, + hs, s); + g_lperlinNoise2_SPU.set(lperlinNoise2, br, x, y, z, xSize, ySize, zSize, s, + hs, s); - port.submitJob(&perlinJob1); - port.submitJob(&perlinJob2); - port.submitJob(&perlinJob3); - port.submitJob(&perlinJob4); - port.submitJob(&perlinJob5); - port.waitForCompletion(); - #else + port.submitJob(&perlinJob1); + port.submitJob(&perlinJob2); + port.submitJob(&perlinJob3); + port.submitJob(&perlinJob4); + port.submitJob(&perlinJob5); + port.waitForCompletion(); +#else sr = scaleNoise->getRegion(sr, x, z, xSize, zSize, 1.121, 1.121, 0.5); dr = depthNoise->getRegion(dr, x, z, xSize, zSize, 200.0, 200.0, 0.5); - pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, hs / 160.0, s / 80.0); + pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, + hs / 160.0, s / 80.0); ar = lperlinNoise1->getRegion(ar, x, y, z, xSize, ySize, zSize, s, hs, s); br = lperlinNoise2->getRegion(br, x, y, z, xSize, ySize, zSize, s, hs, s); #endif - x = z = 0; + x = z = 0; int p = 0; int pp = 0; - for (int xx = 0; xx < xSize; xx++) - { - for (int zz = 0; zz < zSize; zz++) - { - float sss = 0; - float ddd = 0; - float pow = 0; + for (int xx = 0; xx < xSize; xx++) { + for (int zz = 0; zz < zSize; zz++) { + float sss = 0; + float ddd = 0; + float pow = 0; - int rr = 2; + int rr = 2; - Biome *mb = biomes[(xx + 2) + (zz + 2) * (xSize + 5)]; - for (int xb = -rr; xb <= rr; xb++) - { - for (int zb = -rr; zb <= rr; zb++) - { - Biome *b = biomes[(xx + xb + 2) + (zz + zb + 2) * (xSize + 5)]; - float ppp = pows[xb + 2 + (zb + 2) * 5] / (b->depth + 2); - if (b->depth > mb->depth) - { - ppp /= 2; - } - sss += b->scale * ppp; - ddd += b->depth * ppp; - pow += ppp; - } - } - sss /= pow; - ddd /= pow; + Biome* mb = biomes[(xx + 2) + (zz + 2) * (xSize + 5)]; + for (int xb = -rr; xb <= rr; xb++) { + for (int zb = -rr; zb <= rr; zb++) { + Biome* b = + biomes[(xx + xb + 2) + (zz + zb + 2) * (xSize + 5)]; + float ppp = pows[xb + 2 + (zb + 2) * 5] / (b->depth + 2); + if (b->depth > mb->depth) { + ppp /= 2; + } + sss += b->scale * ppp; + ddd += b->depth * ppp; + pow += ppp; + } + } + sss /= pow; + ddd /= pow; + + sss = sss * 0.9f + 0.1f; + ddd = (ddd * 4 - 1) / 8.0f; - sss = sss * 0.9f + 0.1f; - ddd = (ddd * 4 - 1) / 8.0f; - double rdepth = (dr[pp] / 8000.0); if (rdepth < 0) rdepth = -rdepth * 0.3; rdepth = rdepth * 3.0 - 2.0; - if (rdepth < 0) - { - rdepth = rdepth / 2; + if (rdepth < 0) { + rdepth = rdepth / 2; if (rdepth < -1) rdepth = -1; rdepth = rdepth / 1.4; rdepth /= 2; - } - else - { + } else { if (rdepth > 1) rdepth = 1; rdepth = rdepth / 8; } pp++; - for (int yy = 0; yy < ySize; yy++) - { - double depth = ddd; - double scale = sss; + for (int yy = 0; yy < ySize; yy++) { + double depth = ddd; + double scale = sss; - depth += rdepth * 0.2; - depth = depth * ySize / 16.0; + depth += rdepth * 0.2; + depth = depth * ySize / 16.0; - double yCenter = ySize / 2.0 + depth * 4; + double yCenter = ySize / 2.0 + depth * 4; double val = 0; - double yOffs = (yy - (yCenter)) * 12 * 128 / Level::genDepth / scale; + double yOffs = + (yy - (yCenter)) * 12 * 128 / Level::genDepth / scale; if (yOffs < 0) yOffs *= 4; @@ -542,13 +559,15 @@ doubleArray RandomLevelSource::getHeights(doubleArray buffer, int x, int y, int double cc = br[p] / 512; double v = (pnr[p] / 10 + 1) / 2; - if (v < 0) val = bb; - else if (v > 1) val = cc; - else val = bb + (cc - bb) * v; + if (v < 0) + val = bb; + else if (v > 1) + val = cc; + else + val = bb + (cc - bb) * v; val -= yOffs; - if (yy > ySize - 4) - { + if (yy > ySize - 4) { double slide = (yy - (ySize - 4)) / (4 - 1.0f); val = val * (1 - slide) + -10 * slide; } @@ -559,72 +578,76 @@ doubleArray RandomLevelSource::getHeights(doubleArray buffer, int x, int y, int } } - delete [] pnr.data; - delete [] ar.data; - delete [] br.data; - delete [] sr.data; - delete [] dr.data; - delete [] fi.data; - delete [] fis.data; + delete[] pnr.data; + delete[] ar.data; + delete[] br.data; + delete[] sr.data; + delete[] dr.data; + delete[] fi.data; + delete[] fis.data; return buffer; - } -bool RandomLevelSource::hasChunk(int x, int y) -{ - return true; -} +bool RandomLevelSource::hasChunk(int x, int y) { return true; } -void RandomLevelSource::calcWaterDepths(ChunkSource *parent, int xt, int zt) -{ +void RandomLevelSource::calcWaterDepths(ChunkSource* parent, int xt, int zt) { int xo = xt * 16; int zo = zt * 16; - for (int x = 0; x < 16; x++) - { + for (int x = 0; x < 16; x++) { int y = level->getSeaLevel(); - for (int z = 0; z < 16; z++) - { + for (int z = 0; z < 16; z++) { int xp = xo + x + 7; int zp = zo + z + 7; int h = level->getHeightmap(xp, zp); - if (h <= 0) - { - if (level->getHeightmap(xp - 1, zp) > 0 || level->getHeightmap(xp + 1, zp) > 0 || level->getHeightmap(xp, zp - 1) > 0 || level->getHeightmap(xp, zp + 1) > 0) - { + if (h <= 0) { + if (level->getHeightmap(xp - 1, zp) > 0 || + level->getHeightmap(xp + 1, zp) > 0 || + level->getHeightmap(xp, zp - 1) > 0 || + level->getHeightmap(xp, zp + 1) > 0) { bool hadWater = false; - if (hadWater || (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && level->getData(xp - 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && level->getData(xp + 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && level->getData(xp, y, zp - 1) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && level->getData(xp, y, zp + 1) < 7)) hadWater = true; - if (hadWater) - { - for (int x2 = -5; x2 <= 5; x2++) - { - for (int z2 = -5; z2 <= 5; z2++) - { - int d = (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); + if (hadWater || + (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && + level->getData(xp - 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && + level->getData(xp + 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && + level->getData(xp, y, zp - 1) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && + level->getData(xp, y, zp + 1) < 7)) + hadWater = true; + if (hadWater) { + for (int x2 = -5; x2 <= 5; x2++) { + for (int z2 = -5; z2 <= 5; z2++) { + int d = + (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); - if (d <= 5) - { + if (d <= 5) { d = 6 - d; - if (level->getTile(xp + x2, y, zp + z2) == Tile::calmWater_Id) - { - int od = level->getData(xp + x2, y, zp + z2); - if (od < 7 && od < d) - { - level->setData(xp + x2, y, zp + z2, d); + if (level->getTile(xp + x2, y, zp + z2) == + Tile::calmWater_Id) { + int od = + level->getData(xp + x2, y, zp + z2); + if (od < 7 && od < d) { + level->setData(xp + x2, y, zp + z2, + d); } } } } } - if (hadWater) - { - level->setTileAndDataNoUpdate(xp, y, zp, Tile::calmWater_Id, 7); - for (int y2 = 0; y2 < y; y2++) - { - level->setTileAndDataNoUpdate(xp, y2, zp, Tile::calmWater_Id, 8); + if (hadWater) { + level->setTileAndDataNoUpdate( + xp, y, zp, Tile::calmWater_Id, 7); + for (int y2 = 0; y2 < y; y2++) { + level->setTileAndDataNoUpdate( + xp, y2, zp, Tile::calmWater_Id, 8); } } } @@ -632,105 +655,101 @@ void RandomLevelSource::calcWaterDepths(ChunkSource *parent, int xt, int zt) } } } - } -// 4J - changed this to used pprandom rather than random, so that we can run it concurrently with getChunk -void RandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ +// 4J - changed this to used pprandom rather than random, so that we can run it +// concurrently with getChunk +void RandomLevelSource::postProcess(ChunkSource* parent, int xt, int zt) { HeavyTile::instaFall = true; int xo = xt * 16; int zo = zt * 16; - Biome *biome = level->getBiome(xo + 16, zo + 16); + Biome* biome = level->getBiome(xo + 16, zo + 16); - if (RandomLevelSource::FLOATING_ISLANDS) - { + if (RandomLevelSource::FLOATING_ISLANDS) { calcWaterDepths(parent, xt, zt); } - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - // 4jcraft added casts to a higher int and unsigned - pprandom->setSeed((((uint64_t)xt * (uint64_t)xScale) + ((uint64_t)zt * (uint64_t)zScale)) ^ level->getSeed()); + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + // 4jcraft added casts to a higher int and unsigned + pprandom->setSeed((((uint64_t)xt * (uint64_t)xScale) + + ((uint64_t)zt * (uint64_t)zScale)) ^ + level->getSeed()); - bool hasVillage = false; + bool hasVillage = false; - PIXBeginNamedEvent(0,"Structure postprocessing"); - if (generateStructures) - { - mineShaftFeature->postProcess(level, pprandom, xt, zt); - hasVillage = villageFeature->postProcess(level, pprandom, xt, zt); - strongholdFeature->postProcess(level, pprandom, xt, zt); - scatteredFeature->postProcess(level, random, xt, zt); - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Structure postprocessing"); + if (generateStructures) { + mineShaftFeature->postProcess(level, pprandom, xt, zt); + hasVillage = villageFeature->postProcess(level, pprandom, xt, zt); + strongholdFeature->postProcess(level, pprandom, xt, zt); + scatteredFeature->postProcess(level, random, xt, zt); + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Lakes"); - if (!hasVillage && pprandom->nextInt(4) == 0) - { - int x = xo + pprandom->nextInt(16) + 8; - int y = pprandom->nextInt(Level::genDepth); - int z = zo + pprandom->nextInt(16) + 8; + PIXBeginNamedEvent(0, "Lakes"); + if (!hasVillage && pprandom->nextInt(4) == 0) { + int x = xo + pprandom->nextInt(16) + 8; + int y = pprandom->nextInt(Level::genDepth); + int z = zo + pprandom->nextInt(16) + 8; - LakeFeature *calmWater = new LakeFeature(Tile::calmWater_Id); - calmWater->place(level, pprandom, x, y, z); - delete calmWater; - } - PIXEndNamedEvent(); + LakeFeature* calmWater = new LakeFeature(Tile::calmWater_Id); + calmWater->place(level, pprandom, x, y, z); + delete calmWater; + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Lava"); - if (!hasVillage && pprandom->nextInt(8) == 0) - { - int x = xo + pprandom->nextInt(16) + 8; - int y = pprandom->nextInt(pprandom->nextInt(Level::genDepth - 8) + 8); - int z = zo + pprandom->nextInt(16) + 8; - if (y < level->seaLevel || pprandom->nextInt(10) == 0) - { - LakeFeature *calmLava = new LakeFeature(Tile::calmLava_Id); - calmLava->place(level, pprandom, x, y, z); - delete calmLava; - } - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Lava"); + if (!hasVillage && pprandom->nextInt(8) == 0) { + int x = xo + pprandom->nextInt(16) + 8; + int y = pprandom->nextInt(pprandom->nextInt(Level::genDepth - 8) + 8); + int z = zo + pprandom->nextInt(16) + 8; + if (y < level->seaLevel || pprandom->nextInt(10) == 0) { + LakeFeature* calmLava = new LakeFeature(Tile::calmLava_Id); + calmLava->place(level, pprandom, x, y, z); + delete calmLava; + } + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Monster rooms"); - for (int i = 0; i < 8; i++) { - int x = xo + pprandom->nextInt(16) + 8; - int y = pprandom->nextInt(Level::genDepth); - int z = zo + pprandom->nextInt(16) + 8; - MonsterRoomFeature *mrf = new MonsterRoomFeature(); - if (mrf->place(level, pprandom, x, y, z)) - { - } - delete mrf; - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Monster rooms"); + for (int i = 0; i < 8; i++) { + int x = xo + pprandom->nextInt(16) + 8; + int y = pprandom->nextInt(Level::genDepth); + int z = zo + pprandom->nextInt(16) + 8; + MonsterRoomFeature* mrf = new MonsterRoomFeature(); + if (mrf->place(level, pprandom, x, y, z)) { + } + delete mrf; + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Biome decorate"); - biome->decorate(level, pprandom, xo, zo); - PIXEndNamedEvent(); - - app.processSchematics(parent->getChunk(xt,zt)); + PIXBeginNamedEvent(0, "Biome decorate"); + biome->decorate(level, pprandom, xo, zo); + PIXEndNamedEvent(); - MobSpawner::postProcessSpawnMobs(level, biome, xo + 8, zo + 8, 16, 16, pprandom); + app.processSchematics(parent->getChunk(xt, zt)); - // 4J - brought forward from 1.2.3 to get snow back in taiga biomes + MobSpawner::postProcessSpawnMobs(level, biome, xo + 8, zo + 8, 16, 16, + pprandom); + + // 4J - brought forward from 1.2.3 to get snow back in taiga biomes xo += 8; zo += 8; - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { int y = level->getTopRainBlock(xo + x, zo + z); - if (level->shouldFreezeIgnoreNeighbors(x + xo, y - 1, z + zo)) - { - level->setTileNoUpdate(x + xo, y - 1, z + zo, Tile::ice_Id); // 4J - changed from setTile, otherwise we end up creating a *lot* of dynamic water tiles as these ice tiles are set + if (level->shouldFreezeIgnoreNeighbors(x + xo, y - 1, z + zo)) { + level->setTileNoUpdate( + x + xo, y - 1, z + zo, + Tile::ice_Id); // 4J - changed from setTile, otherwise we + // end up creating a *lot* of dynamic water + // tiles as these ice tiles are set } - if (level->shouldSnow(x + xo, y, z + zo)) - { + if (level->shouldSnow(x + xo, y, z + zo)) { level->setTile(x + xo, y, z + zo, Tile::topSnow_Id); } } @@ -739,40 +758,28 @@ void RandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) HeavyTile::instaFall = false; } -bool RandomLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; +bool RandomLevelSource::save(bool force, ProgressListener* progressListener) { + return true; } -bool RandomLevelSource::tick() -{ - return false; -} +bool RandomLevelSource::tick() { return false; } -bool RandomLevelSource::shouldSave() -{ - return true; -} +bool RandomLevelSource::shouldSave() { return true; } -std::wstring RandomLevelSource::gatherStats() -{ - return L"RandomLevelSource"; -} +std::wstring RandomLevelSource::gatherStats() { return L"RandomLevelSource"; } -std::vector *RandomLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { +std::vector* RandomLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { return NULL; } return biome->getMobs(mobCategory); } -TilePos *RandomLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - if (LargeFeature::STRONGHOLD == featureName && strongholdFeature != NULL) - { +TilePos* RandomLevelSource::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + if (LargeFeature::STRONGHOLD == featureName && strongholdFeature != NULL) { return strongholdFeature->getNearestGeneratedFeature(level, x, y, z); } return NULL; diff --git a/Minecraft.World/Level/RandomLevelSource.h b/Minecraft.World/Level/RandomLevelSource.h index a4e206fe5..3670a1cb2 100644 --- a/Minecraft.World/Level/RandomLevelSource.h +++ b/Minecraft.World/Level/RandomLevelSource.h @@ -1,6 +1,5 @@ #pragma once - #include "ChunkSource.h" class ProgressListener; @@ -11,8 +10,7 @@ class MineShaftFeature; class PerlinNoise; class RandomScatteredLargeFeature; -class RandomLevelSource : public ChunkSource -{ +class RandomLevelSource : public ChunkSource { public: static const double SNOW_CUTOFF; static const double SNOW_SCALE; @@ -21,72 +19,78 @@ public: static const int CHUNK_WIDTH = 4; private: - Random *random; - Random *pprandom; // 4J - added + Random* random; + Random* pprandom; // 4J - added - PerlinNoise *lperlinNoise1; - PerlinNoise *lperlinNoise2; - PerlinNoise *perlinNoise1; - PerlinNoise *perlinNoise3; + PerlinNoise* lperlinNoise1; + PerlinNoise* lperlinNoise2; + PerlinNoise* perlinNoise1; + PerlinNoise* perlinNoise3; public: - PerlinNoise *scaleNoise; - PerlinNoise *depthNoise; + PerlinNoise* scaleNoise; + PerlinNoise* depthNoise; private: - PerlinNoise *floatingIslandScale; - PerlinNoise *floatingIslandNoise; + PerlinNoise* floatingIslandScale; + PerlinNoise* floatingIslandNoise; public: - PerlinNoise *forestNoise; + PerlinNoise* forestNoise; private: - Level *level; - const bool generateStructures; + Level* level; + const bool generateStructures; - floatArray pows; + floatArray pows; public: - RandomLevelSource(Level *level, __int64 seed, bool generateStructures); - ~RandomLevelSource(); + RandomLevelSource(Level* level, __int64 seed, bool generateStructures); + ~RandomLevelSource(); public: - void prepareHeights(int xOffs, int zOffs, byteArray blocks); + void prepareHeights(int xOffs, int zOffs, byteArray blocks); public: - void buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes); + void buildSurfaces(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes); private: - LargeFeature *caveFeature; - StrongholdFeature *strongholdFeature; - VillageFeature *villageFeature; - MineShaftFeature *mineShaftFeature; - RandomScatteredLargeFeature *scatteredFeature; - LargeFeature *canyonFeature; -private: - virtual LevelChunk *create(int x, int z); - -public: - virtual LevelChunk *getChunk(int xOffs, int zOffs); - virtual void lightChunk(LevelChunk *lc); // 4J added + LargeFeature* caveFeature; + StrongholdFeature* strongholdFeature; + VillageFeature* villageFeature; + MineShaftFeature* mineShaftFeature; + RandomScatteredLargeFeature* scatteredFeature; + LargeFeature* canyonFeature; private: - doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize, BiomeArray& biomes); + virtual LevelChunk* create(int x, int z); public: - virtual bool hasChunk(int x, int y); + virtual LevelChunk* getChunk(int xOffs, int zOffs); + virtual void lightChunk(LevelChunk* lc); // 4J added private: - void calcWaterDepths(ChunkSource *parent, int xt, int zt); + doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, + int ySize, int zSize, BiomeArray& biomes); public: - virtual void postProcess(ChunkSource *parent, int xt, int zt); - virtual bool save(bool force, ProgressListener *progressListener); + virtual bool hasChunk(int x, int y); + +private: + void calcWaterDepths(ChunkSource* parent, int xt, int zt); + +public: + virtual void postProcess(ChunkSource* parent, int xt, int zt); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); public: - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/Level/Storage/ChunkStorage.h b/Minecraft.World/Level/Storage/ChunkStorage.h index 8e4c9c0d7..0daca9c74 100644 --- a/Minecraft.World/Level/Storage/ChunkStorage.h +++ b/Minecraft.World/Level/Storage/ChunkStorage.h @@ -2,14 +2,13 @@ class Level; -class ChunkStorage -{ +class ChunkStorage { public: - virtual LevelChunk *load(Level *level, int x, int z) = 0; - virtual void save(Level *level, LevelChunk *levelChunk) = 0; - virtual void saveEntities(Level *level, LevelChunk *levelChunk) = 0; + virtual LevelChunk* load(Level* level, int x, int z) = 0; + virtual void save(Level* level, LevelChunk* levelChunk) = 0; + virtual void saveEntities(Level* level, LevelChunk* levelChunk) = 0; virtual void tick() = 0; virtual void flush() = 0; - virtual void WaitForAll() {}; // 4J Added - virtual void WaitIfTooManyQueuedChunks() {}; // 4J Added + virtual void WaitForAll() {}; // 4J Added + virtual void WaitIfTooManyQueuedChunks() {}; // 4J Added }; diff --git a/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.cpp b/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.cpp index 840911ed7..20c0d6f42 100644 --- a/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.cpp +++ b/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.cpp @@ -2,74 +2,81 @@ #include "../../Platform/System.h" #include "ChunkStorageProfileDecorator.h" -ChunkStorageProfilerDecorator::ChunkStorageProfilerDecorator(ChunkStorage *capsulated) : - timeSpentLoading(0), loadCount(0), timeSpentSaving(0), saveCount(0), counter(0) -{ - this->capsulated = capsulated; +ChunkStorageProfilerDecorator::ChunkStorageProfilerDecorator( + ChunkStorage* capsulated) + : timeSpentLoading(0), + loadCount(0), + timeSpentSaving(0), + saveCount(0), + counter(0) { + this->capsulated = capsulated; } -LevelChunk *ChunkStorageProfilerDecorator::load(Level *level, int x, int z) -{ +LevelChunk* ChunkStorageProfilerDecorator::load(Level* level, int x, int z) { __int64 nanoTime = System::nanoTime(); - LevelChunk *chunk = capsulated->load(level, x, z); + LevelChunk* chunk = capsulated->load(level, x, z); timeSpentLoading += System::nanoTime() - nanoTime; loadCount++; return chunk; } -void ChunkStorageProfilerDecorator::save(Level *level, LevelChunk *levelChunk) -{ +void ChunkStorageProfilerDecorator::save(Level* level, LevelChunk* levelChunk) { __int64 nanoTime = System::nanoTime(); capsulated->save(level, levelChunk); timeSpentSaving += System::nanoTime() - nanoTime; saveCount++; } -void ChunkStorageProfilerDecorator::saveEntities(Level *level, LevelChunk *levelChunk) -{ - capsulated->saveEntities(level, levelChunk); +void ChunkStorageProfilerDecorator::saveEntities(Level* level, + LevelChunk* levelChunk) { + capsulated->saveEntities(level, levelChunk); } -void ChunkStorageProfilerDecorator::tick() -{ - char buf[256]; +void ChunkStorageProfilerDecorator::tick() { + char buf[256]; capsulated->tick(); counter++; - if (counter > 500) - { - if (loadCount > 0) - { + if (counter > 500) { + if (loadCount > 0) { #ifndef _CONTENT_PACKAGE #ifdef __PSVITA__ - sprintf(buf,"Average load time: %f (%lld)",0.000001 * (double) timeSpentLoading / (double) loadCount, loadCount); + sprintf(buf, "Average load time: %f (%lld)", + 0.000001 * (double)timeSpentLoading / (double)loadCount, + loadCount); #elif defined(__linux__) - sprintf(buf,"Average load time: %f (%lld)",0.000001 * (double) timeSpentLoading / (double) loadCount, (long long)loadCount); + sprintf(buf, "Average load time: %f (%lld)", + 0.000001 * (double)timeSpentLoading / (double)loadCount, + (long long)loadCount); #else - sprintf(buf,"Average load time: %f (%I64d)",0.000001 * (double) timeSpentLoading / (double) loadCount, loadCount); + sprintf(buf, "Average load time: %f (%I64d)", + 0.000001 * (double)timeSpentLoading / (double)loadCount, + loadCount); #endif - app.DebugPrintf(buf); + app.DebugPrintf(buf); #endif } - if (saveCount > 0) - { + if (saveCount > 0) { #ifndef _CONTENT_PACKAGE #ifdef __PSVITA__ - sprintf(buf,"Average save time: %f (%lld)",0.000001 * (double) timeSpentSaving / (double) loadCount, loadCount); + sprintf(buf, "Average save time: %f (%lld)", + 0.000001 * (double)timeSpentSaving / (double)loadCount, + loadCount); #elif defined(__linux__) - sprintf(buf,"Average save time: %f (%lld)",0.000001 * (double) timeSpentSaving / (double) loadCount, (long long)loadCount); + sprintf(buf, "Average save time: %f (%lld)", + 0.000001 * (double)timeSpentSaving / (double)loadCount, + (long long)loadCount); #else - sprintf(buf,"Average save time: %f (%I64d)",0.000001 * (double) timeSpentSaving / (double) loadCount, loadCount); + sprintf(buf, "Average save time: %f (%I64d)", + 0.000001 * (double)timeSpentSaving / (double)loadCount, + loadCount); #endif - app.DebugPrintf(buf); -#endif - } + app.DebugPrintf(buf); +#endif + } counter = 0; } } -void ChunkStorageProfilerDecorator::flush() -{ - capsulated->flush(); -} \ No newline at end of file +void ChunkStorageProfilerDecorator::flush() { capsulated->flush(); } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.h b/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.h index 67c582daf..0faae2965 100644 --- a/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.h +++ b/Minecraft.World/Level/Storage/ChunkStorageProfileDecorator.h @@ -3,23 +3,22 @@ class Level; -class ChunkStorageProfilerDecorator : public ChunkStorage -{ +class ChunkStorageProfilerDecorator : public ChunkStorage { private: - ChunkStorage *capsulated; + ChunkStorage* capsulated; - __int64 timeSpentLoading; - __int64 loadCount; - __int64 timeSpentSaving; - __int64 saveCount; + __int64 timeSpentLoading; + __int64 loadCount; + __int64 timeSpentSaving; + __int64 saveCount; - int counter; + int counter; public: - ChunkStorageProfilerDecorator(ChunkStorage *capsulated); - LevelChunk *load(Level *level, int x, int z); - void save(Level *level, LevelChunk *levelChunk); - void saveEntities(Level *level, LevelChunk *levelChunk); + ChunkStorageProfilerDecorator(ChunkStorage* capsulated); + LevelChunk* load(Level* level, int x, int z); + void save(Level* level, LevelChunk* levelChunk); + void saveEntities(Level* level, LevelChunk* levelChunk); void tick(); void flush(); }; diff --git a/Minecraft.World/Level/Storage/CompressedTileStorage.cpp b/Minecraft.World/Level/Storage/CompressedTileStorage.cpp index 473316e7a..7f42e331d 100644 --- a/Minecraft.World/Level/Storage/CompressedTileStorage.cpp +++ b/Minecraft.World/Level/Storage/CompressedTileStorage.cpp @@ -9,243 +9,236 @@ #include "../../../Minecraft.Client/Platform/PS3/SPU_Tasks/CompressedTileStorage_compress/CompressedTileStorage_compress.h" #include "../../../Minecraft.Client/Platform/PS3/PS3Extras/C4JSpursJob.h" static const int sc_maxCompressTiles = 64; -static CompressedTileStorage_compress_dataIn g_compressTileDataIn[sc_maxCompressTiles] __attribute__((__aligned__(16))); +static CompressedTileStorage_compress_dataIn + g_compressTileDataIn[sc_maxCompressTiles] __attribute__((__aligned__(16))); static int g_currentCompressTiles = 0; -#endif //__PS3__ +#endif //__PS3__ // Note: See header for an overview of this class int CompressedTileStorage::deleteQueueIndex; -XLockFreeStack CompressedTileStorage::deleteQueue[3]; +XLockFreeStack CompressedTileStorage::deleteQueue[3]; CRITICAL_SECTION CompressedTileStorage::cs_write; #ifdef PSVITA_PRECOMPUTED_TABLE // AP - this will create a precomputed table to speed up getData -static int *CompressedTile_StorageIndexTable = NULL; +static int* CompressedTile_StorageIndexTable = NULL; -void CompressedTileStorage_InitTable() -{ - if( CompressedTile_StorageIndexTable == NULL ) - { - CompressedTile_StorageIndexTable = (int*) malloc(sizeof(int) * 64); - for(int j = 0;j < 64;j += 1 ) - { - int index = ( ( j & 0x30 ) << 7) | ( ( j & 0x0c ) << 5 ) | ( j & 0x03 ); - CompressedTile_StorageIndexTable[j] = index; - } - } +void CompressedTileStorage_InitTable() { + if (CompressedTile_StorageIndexTable == NULL) { + CompressedTile_StorageIndexTable = (int*)malloc(sizeof(int) * 64); + for (int j = 0; j < 64; j += 1) { + int index = ((j & 0x30) << 7) | ((j & 0x0c) << 5) | (j & 0x03); + CompressedTile_StorageIndexTable[j] = index; + } + } } #endif -CompressedTileStorage::CompressedTileStorage() -{ - indicesAndData = NULL; - allocatedSize = 0; +CompressedTileStorage::CompressedTileStorage() { + indicesAndData = NULL; + allocatedSize = 0; #ifdef PSVITA_PRECOMPUTED_TABLE - CompressedTileStorage_InitTable(); + CompressedTileStorage_InitTable(); #endif } -CompressedTileStorage::CompressedTileStorage(CompressedTileStorage *copyFrom) -{ - EnterCriticalSection(&cs_write); - allocatedSize = copyFrom->allocatedSize; - if(allocatedSize > 0) - { - indicesAndData = (unsigned char *)XPhysicalAlloc(allocatedSize, MAXULONG_PTR, 4096, PAGE_READWRITE);//(unsigned char *)malloc(allocatedSize); - XMemCpy(indicesAndData, copyFrom->indicesAndData, allocatedSize); - } - else - { - indicesAndData = NULL; - } - LeaveCriticalSection(&cs_write); +CompressedTileStorage::CompressedTileStorage(CompressedTileStorage* copyFrom) { + EnterCriticalSection(&cs_write); + allocatedSize = copyFrom->allocatedSize; + if (allocatedSize > 0) { + indicesAndData = (unsigned char*)XPhysicalAlloc( + allocatedSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); //(unsigned char *)malloc(allocatedSize); + XMemCpy(indicesAndData, copyFrom->indicesAndData, allocatedSize); + } else { + indicesAndData = NULL; + } + LeaveCriticalSection(&cs_write); #ifdef PSVITA_PRECOMPUTED_TABLE - CompressedTileStorage_InitTable(); + CompressedTileStorage_InitTable(); #endif } -CompressedTileStorage::CompressedTileStorage(byteArray initFrom, unsigned int initOffset) -{ - indicesAndData = NULL; - allocatedSize = 0; +CompressedTileStorage::CompressedTileStorage(byteArray initFrom, + unsigned int initOffset) { + indicesAndData = NULL; + allocatedSize = 0; - // We need 32768 bytes for a fully uncompressed chunk, plus 1024 for the index. Rounding up to nearest 4096 bytes for allocation - indicesAndData = (unsigned char *)XPhysicalAlloc(32768+4096, MAXULONG_PTR, 4096, PAGE_READWRITE); + // We need 32768 bytes for a fully uncompressed chunk, plus 1024 for the + // index. Rounding up to nearest 4096 bytes for allocation + indicesAndData = (unsigned char*)XPhysicalAlloc(32768 + 4096, MAXULONG_PTR, + 4096, PAGE_READWRITE); - unsigned short *indices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; + unsigned short* indices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - int offset = 0; - for( int i = 0; i < 512; i++ ) - { - indices[i] = INDEX_TYPE_0_OR_8_BIT | ( offset << 1 ); + int offset = 0; + for (int i = 0; i < 512; i++) { + indices[i] = INDEX_TYPE_0_OR_8_BIT | (offset << 1); - if( initFrom.data ) - { - for( int j = 0; j < 64; j++ ) - { - *data++ = initFrom[getIndex(i,j) + initOffset]; - } - } - else - { - for( int j = 0; j < 64; j++ ) - { - *data++ = 0; - } - } + if (initFrom.data) { + for (int j = 0; j < 64; j++) { + *data++ = initFrom[getIndex(i, j) + initOffset]; + } + } else { + for (int j = 0; j < 64; j++) { + *data++ = 0; + } + } - offset += 64; - } + offset += 64; + } - allocatedSize = 32768 + 1024; // This is used for copying (see previous ctor), and as such it only needs to be the actual size of the data used rather than the one rounded up to a page size actually allocated + allocatedSize = + 32768 + + 1024; // This is used for copying (see previous ctor), and as such it + // only needs to be the actual size of the data used rather than + // the one rounded up to a page size actually allocated #ifdef PSVITA_PRECOMPUTED_TABLE - CompressedTileStorage_InitTable(); + CompressedTileStorage_InitTable(); #endif } -bool CompressedTileStorage::isCompressed() -{ - return allocatedSize != 32768 + 1024; +bool CompressedTileStorage::isCompressed() { + return allocatedSize != 32768 + 1024; } -CompressedTileStorage::CompressedTileStorage(bool isEmpty) -{ - indicesAndData = NULL; - allocatedSize = 0; +CompressedTileStorage::CompressedTileStorage(bool isEmpty) { + indicesAndData = NULL; + allocatedSize = 0; - // Empty and already compressed, so we only need 1K. Rounding up to nearest 4096 bytes for allocation + // Empty and already compressed, so we only need 1K. Rounding up to nearest + // 4096 bytes for allocation #ifdef __PS3__ - // XPhysicalAlloc just maps to malloc on PS3, so allocate the smallest amount - indicesAndData = (unsigned char *)XPhysicalAlloc(1024, MAXULONG_PTR, 4096, PAGE_READWRITE); + // XPhysicalAlloc just maps to malloc on PS3, so allocate the smallest + // amount + indicesAndData = (unsigned char*)XPhysicalAlloc(1024, MAXULONG_PTR, 4096, + PAGE_READWRITE); #else - indicesAndData = (unsigned char *)XPhysicalAlloc(4096, MAXULONG_PTR, 4096, PAGE_READWRITE); -#endif //__PS3__ - unsigned short *indices = (unsigned short *)indicesAndData; - //unsigned char *data = indicesAndData + 1024; + indicesAndData = (unsigned char*)XPhysicalAlloc(4096, MAXULONG_PTR, 4096, + PAGE_READWRITE); +#endif //__PS3__ + unsigned short* indices = (unsigned short*)indicesAndData; + // unsigned char *data = indicesAndData + 1024; - //int offset = 0; - for( int i = 0; i < 512; i++ ) - { - indices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; - } + // int offset = 0; + for (int i = 0; i < 512; i++) { + indices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; + } - allocatedSize = 1024; // This is used for copying (see previous ctor), and as such it only needs to be the actual size of the data used rather than the one rounded up to a page size actually allocated + allocatedSize = + 1024; // This is used for copying (see previous ctor), and as such it + // only needs to be the actual size of the data used rather than + // the one rounded up to a page size actually allocated #ifdef PSVITA_PRECOMPUTED_TABLE - CompressedTileStorage_InitTable(); + CompressedTileStorage_InitTable(); #endif } -bool CompressedTileStorage::isRenderChunkEmpty(int y) // y == 0, 16, 32... 112 (representing a 16 byte range) +bool CompressedTileStorage::isRenderChunkEmpty( + int y) // y == 0, 16, 32... 112 (representing a 16 byte range) { - int block; - unsigned short *blockIndices = (unsigned short *)indicesAndData; + int block; + unsigned short* blockIndices = (unsigned short*)indicesAndData; - for( int x = 0; x < 16; x += 4 ) - for( int z = 0; z < 16; z += 4 ) - { - getBlock(&block, x, y, z); - __uint64 *comp = (__uint64 *)&blockIndices[block]; - // Are the 4 y regions stored here all zero? (INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG ) - if( ( *comp ) != 0x0007000700070007L ) return false; - } - return true; + for (int x = 0; x < 16; x += 4) + for (int z = 0; z < 16; z += 4) { + getBlock(&block, x, y, z); + __uint64* comp = (__uint64*)&blockIndices[block]; + // Are the 4 y regions stored here all zero? (INDEX_TYPE_0_OR_8_BIT + // | INDEX_TYPE_0_BIT_FLAG ) + if ((*comp) != 0x0007000700070007L) return false; + } + return true; } -bool CompressedTileStorage::isSameAs(CompressedTileStorage *other) -{ - EnterCriticalSection(&cs_write); - if( allocatedSize != other->allocatedSize ) - { - LeaveCriticalSection(&cs_write); - return false; - } +bool CompressedTileStorage::isSameAs(CompressedTileStorage* other) { + EnterCriticalSection(&cs_write); + if (allocatedSize != other->allocatedSize) { + LeaveCriticalSection(&cs_write); + return false; + } - // Attempt to compare as much as we can in 64-byte chunks (8 groups of 8 bytes) - int quickCount = allocatedSize / 64; - __int64 *pOld = (__int64 *)indicesAndData; - __int64 *pNew = (__int64 *)other->indicesAndData; - for( int i = 0; i < quickCount; i++ ) - { - __int64 d0 = pOld[0] ^ pNew[0]; - __int64 d1 = pOld[1] ^ pNew[1]; - __int64 d2 = pOld[2] ^ pNew[2]; - __int64 d3 = pOld[3] ^ pNew[3]; - __int64 d4 = pOld[4] ^ pNew[4]; - __int64 d5 = pOld[5] ^ pNew[5]; - __int64 d6 = pOld[6] ^ pNew[6]; - __int64 d7 = pOld[7] ^ pNew[7]; - d0 |= d1; - d2 |= d3; - d4 |= d5; - d6 |= d7; - d0 |= d2; - d4 |= d6; - if( d0 | d4 ) - { - LeaveCriticalSection(&cs_write); - return false; - } - pOld += 8; - pNew += 8; - } + // Attempt to compare as much as we can in 64-byte chunks (8 groups of 8 + // bytes) + int quickCount = allocatedSize / 64; + __int64* pOld = (__int64*)indicesAndData; + __int64* pNew = (__int64*)other->indicesAndData; + for (int i = 0; i < quickCount; i++) { + __int64 d0 = pOld[0] ^ pNew[0]; + __int64 d1 = pOld[1] ^ pNew[1]; + __int64 d2 = pOld[2] ^ pNew[2]; + __int64 d3 = pOld[3] ^ pNew[3]; + __int64 d4 = pOld[4] ^ pNew[4]; + __int64 d5 = pOld[5] ^ pNew[5]; + __int64 d6 = pOld[6] ^ pNew[6]; + __int64 d7 = pOld[7] ^ pNew[7]; + d0 |= d1; + d2 |= d3; + d4 |= d5; + d6 |= d7; + d0 |= d2; + d4 |= d6; + if (d0 | d4) { + LeaveCriticalSection(&cs_write); + return false; + } + pOld += 8; + pNew += 8; + } - // Now test anything remaining just byte at a time - unsigned char *pucOld = (unsigned char *)pOld; - unsigned char *pucNew = (unsigned char *)pNew; - for( int i = 0; i < allocatedSize - (quickCount * 64); i++ ) - { - if( *pucOld++ != *pucNew++ ) - { - LeaveCriticalSection(&cs_write); - return false; - } - } + // Now test anything remaining just byte at a time + unsigned char* pucOld = (unsigned char*)pOld; + unsigned char* pucNew = (unsigned char*)pNew; + for (int i = 0; i < allocatedSize - (quickCount * 64); i++) { + if (*pucOld++ != *pucNew++) { + LeaveCriticalSection(&cs_write); + return false; + } + } - LeaveCriticalSection(&cs_write); - return true; + LeaveCriticalSection(&cs_write); + return true; } -CompressedTileStorage::~CompressedTileStorage() -{ +CompressedTileStorage::~CompressedTileStorage() { #if 1 - if(indicesAndData) XPhysicalFree(indicesAndData); + if (indicesAndData) XPhysicalFree(indicesAndData); #else - if( (unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE ) - { - if(indicesAndData) XPhysicalFree(indicesAndData); - } - else - { - if(indicesAndData) free(indicesAndData); - } + if ((unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE) { + if (indicesAndData) XPhysicalFree(indicesAndData); + } else { + if (indicesAndData) free(indicesAndData); + } #endif } -// Get an index into the normal ordering of tiles for the java game, given a block index (0 to 511) and a tile index (0 to 63) -inline int CompressedTileStorage::getIndex(int block, int tile) -{ - // bits for index into data is: xxxxzzzzyyyyyyy - // we want block(b) & tile(t) spread out as: - // from: ______bbbbbbbbb - // to: bb__bb__bbbbb__ - // - // from: _________tttttt - // to: __tt__tt_____tt +// Get an index into the normal ordering of tiles for the java game, given a +// block index (0 to 511) and a tile index (0 to 63) +inline int CompressedTileStorage::getIndex(int block, int tile) { + // bits for index into data is: xxxxzzzzyyyyyyy + // we want block(b) & tile(t) spread out as: + // from: ______bbbbbbbbb + // to: bb__bb__bbbbb__ + // + // from: _________tttttt + // to: __tt__tt_____tt - int index = ( ( block & 0x180) << 6 ) | ( ( block & 0x060 ) << 4 ) | ( ( block & 0x01f ) << 2 ); - index |= ( ( tile & 0x30 ) << 7) | ( ( tile & 0x0c ) << 5 ) | ( tile & 0x03 ); + int index = ((block & 0x180) << 6) | ((block & 0x060) << 4) | + ((block & 0x01f) << 2); + index |= ((tile & 0x30) << 7) | ((tile & 0x0c) << 5) | (tile & 0x03); - return index; + return index; } -// Get the block and tile (reversing getIndex above) for a given x, y, z coordinate +// Get the block and tile (reversing getIndex above) for a given x, y, z +// coordinate // // bits for index into data is: xxxxzzzzyyyyyyy // bbttbbttbbbbbtt @@ -261,1100 +254,1130 @@ inline int CompressedTileStorage::getIndex(int block, int tile) // and z is: ___________zzzz // and maps to this bit of b ________bb_____ // and this bit of t ___________tt__ -// +// -inline void CompressedTileStorage::getBlockAndTile(int *block, int *tile, int x, int y, int z) -{ - *block = ( ( x & 0x0c ) << 5 ) | ( ( z & 0x0c ) << 3 ) | ( y >> 2 ); - *tile = ( ( x & 0x03 ) << 4 ) | ( ( z & 0x03 ) << 2 ) | ( y & 0x03 ); +inline void CompressedTileStorage::getBlockAndTile(int* block, int* tile, int x, + int y, int z) { + *block = ((x & 0x0c) << 5) | ((z & 0x0c) << 3) | (y >> 2); + *tile = ((x & 0x03) << 4) | ((z & 0x03) << 2) | (y & 0x03); } -inline void CompressedTileStorage::getBlock(int *block, int x, int y, int z) -{ - *block = ( ( x & 0x0c ) << 5 ) | ( ( z & 0x0c ) << 3 ) | ( y >> 2 ); +inline void CompressedTileStorage::getBlock(int* block, int x, int y, int z) { + *block = ((x & 0x0c) << 5) | ((z & 0x0c) << 3) | (y >> 2); } // Set all tile values from a data array of length 32768 (128 x 16 x 16). -void CompressedTileStorage::setData(byteArray dataIn, unsigned int inOffset) -{ - unsigned short _blockIndices[512]; +void CompressedTileStorage::setData(byteArray dataIn, unsigned int inOffset) { + unsigned short _blockIndices[512]; - EnterCriticalSection(&cs_write); - unsigned char *data = dataIn.data + inOffset; + EnterCriticalSection(&cs_write); + unsigned char* data = dataIn.data + inOffset; - // Is the destination fully uncompressed? If so just write our data in - this happens when writing schematics and we don't want this setting of data to trigger compression - if( allocatedSize == ( 32768 + 1024 ) ) - { - //unsigned short *indices = (unsigned short *)indicesAndData; - unsigned char *dataOut = indicesAndData + 1024; + // Is the destination fully uncompressed? If so just write our data in - + // this happens when writing schematics and we don't want this setting of + // data to trigger compression + if (allocatedSize == (32768 + 1024)) { + // unsigned short *indices = (unsigned short *)indicesAndData; + unsigned char* dataOut = indicesAndData + 1024; - for( int i = 0; i < 512; i++ ) - { - for( int j = 0; j < 64; j++ ) - { - *dataOut++ = data[getIndex(i,j)]; - } - } - LeaveCriticalSection(&cs_write); - return; - } + for (int i = 0; i < 512; i++) { + for (int j = 0; j < 64; j++) { + *dataOut++ = data[getIndex(i, j)]; + } + } + LeaveCriticalSection(&cs_write); + return; + } - int offsets[512]; - int memToAlloc = 0; -// static int type0 = 0, type1 = 0, type2 = 0, type4 = 0, type8 = 0, chunkTotal = 0; - - // Loop round all blocks - for( int i = 0; i < 512; i++ ) - { - offsets[i] = memToAlloc; - // Count how many unique tile types are in the block - if unpacked_data isn't set then there isn't any data so we can't compress any further and require no storage. - // Store flags for each tile type used in an array of 4 64-bit flags. + int offsets[512]; + int memToAlloc = 0; + // static int type0 = 0, type1 = 0, type2 = 0, type4 = 0, type8 = 0, + //chunkTotal = 0; + + // Loop round all blocks + for (int i = 0; i < 512; i++) { + offsets[i] = memToAlloc; + // Count how many unique tile types are in the block - if unpacked_data + // isn't set then there isn't any data so we can't compress any further + // and require no storage. Store flags for each tile type used in an + // array of 4 64-bit flags. #ifdef __PSVITA__ - // AP - Vita isn't so great at shifting 64bits. The top biggest CPU time sink after profiling is __ashldi3 (64bit shift) at 3% - // Let's use 32bit instead - unsigned int usedFlags[8] = {0,0,0,0,0,0,0,0}; - __int32 i32_1 = 1; - for( int j = 0; j < 64; j++ ) // This loop of 64 is to go round the 4 x 4 tiles in the block - { - int tile = data[getIndex(i,j)]; - if( tile < (64<<2) ) - { - usedFlags[tile & 7] |= ( i32_1 << ( tile >> 3 ) ); - } - } - int count = 0; - for( int tile = 0; tile < 256; tile++ ) // This loop of 256 is to go round the 256 possible values that the tiles might have had to find how many are actually used - { - if( usedFlags[tile & 7] & ( i32_1 << ( tile >> 3 ) ) ) - { - count++; - } - } + // AP - Vita isn't so great at shifting 64bits. The top biggest CPU time + // sink after profiling is __ashldi3 (64bit shift) at 3% Let's use 32bit + // instead + unsigned int usedFlags[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + __int32 i32_1 = 1; + for (int j = 0; j < 64; j++) // This loop of 64 is to go round the 4 x + // 4 tiles in the block + { + int tile = data[getIndex(i, j)]; + if (tile < (64 << 2)) { + usedFlags[tile & 7] |= (i32_1 << (tile >> 3)); + } + } + int count = 0; + for (int tile = 0; tile < 256; + tile++) // This loop of 256 is to go round the 256 possible values + // that the tiles might have had to find how many are + // actually used + { + if (usedFlags[tile & 7] & (i32_1 << (tile >> 3))) { + count++; + } + } #else - __uint64 usedFlags[4] = {0,0,0,0}; - __int64 i64_1 = 1; // MGH - instead of 1i64, which is MS specific - for( int j = 0; j < 64; j++ ) // This loop of 64 is to go round the 4 x 4 tiles in the block - { - int tile = data[getIndex(i,j)]; + __uint64 usedFlags[4] = {0, 0, 0, 0}; + __int64 i64_1 = 1; // MGH - instead of 1i64, which is MS specific + for (int j = 0; j < 64; j++) // This loop of 64 is to go round the 4 x + // 4 tiles in the block + { + int tile = data[getIndex(i, j)]; - usedFlags[tile & 3] |= ( i64_1 << ( tile >> 2 ) ); - } - int count = 0; - for( int tile = 0; tile < 256; tile++ ) // This loop of 256 is to go round the 256 possible values that the tiles might have had to find how many are actually used - { - if( usedFlags[tile & 3] & ( i64_1 << ( tile >> 2 ) ) ) - { - count++; - } - } + usedFlags[tile & 3] |= (i64_1 << (tile >> 2)); + } + int count = 0; + for (int tile = 0; tile < 256; + tile++) // This loop of 256 is to go round the 256 possible values + // that the tiles might have had to find how many are + // actually used + { + if (usedFlags[tile & 3] & (i64_1 << (tile >> 2))) { + count++; + } + } #endif - if( count == 1 ) - { - _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; -// type0++; - } - else if( count == 2 ) - { - _blockIndices[i] = INDEX_TYPE_1_BIT; - memToAlloc += 10; // 8 bytes + 2 tile index -// type1++; - } - else if ( count <= 4 ) - { - _blockIndices[i] = INDEX_TYPE_2_BIT; - memToAlloc += 20; // 16 bytes + 4 tile index -// type2++; - } - else if ( count <= 16 ) - { - _blockIndices[i] = INDEX_TYPE_4_BIT; - memToAlloc += 48; // 32 bytes + 16 tile index -// type4++; - } - else - { - _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT; - memToAlloc = ( memToAlloc + 3 ) & 0xfffc; // Make sure we are 4-byte aligned for 8-bit storage - memToAlloc += 64; -// type8++; - } - } + if (count == 1) { + _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; + // type0++; + } else if (count == 2) { + _blockIndices[i] = INDEX_TYPE_1_BIT; + memToAlloc += 10; // 8 bytes + 2 tile index + // type1++; + } else if (count <= 4) { + _blockIndices[i] = INDEX_TYPE_2_BIT; + memToAlloc += 20; // 16 bytes + 4 tile index + // type2++; + } else if (count <= 16) { + _blockIndices[i] = INDEX_TYPE_4_BIT; + memToAlloc += 48; // 32 bytes + 16 tile index + // type4++; + } else { + _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT; + memToAlloc = + (memToAlloc + 3) & + 0xfffc; // Make sure we are 4-byte aligned for 8-bit storage + memToAlloc += 64; + // type8++; + } + } -// chunkTotal++; -// printf("%d: %d (0) %d (1) %d (2) %d (4) %d (8)\n", chunkTotal, type0 / chunkTotal, type1 / chunkTotal, type2 / chunkTotal, type4 / chunkTotal, type8 / chunkTotal); + // chunkTotal++; + // printf("%d: %d (0) %d (1) %d (2) %d (4) %d (8)\n", chunkTotal, type0 / + //chunkTotal, type1 / chunkTotal, type2 / chunkTotal, type4 / chunkTotal, + //type8 / chunkTotal); - memToAlloc += 1024; // For the indices - unsigned char *newIndicesAndData = (unsigned char *)XPhysicalAlloc(memToAlloc, MAXULONG_PTR, 4096, PAGE_READWRITE);//(unsigned char *)malloc( memToAlloc ); - unsigned char *pucData = newIndicesAndData + 1024; - unsigned short usDataOffset = 0; - unsigned short *newIndices = (unsigned short *) newIndicesAndData; + memToAlloc += 1024; // For the indices + unsigned char* newIndicesAndData = (unsigned char*)XPhysicalAlloc( + memToAlloc, MAXULONG_PTR, 4096, + PAGE_READWRITE); //(unsigned char *)malloc( memToAlloc ); + unsigned char* pucData = newIndicesAndData + 1024; + unsigned short usDataOffset = 0; + unsigned short* newIndices = (unsigned short*)newIndicesAndData; - // Now pass through again actually making the final compressed data - for( int i = 0; i < 512; i++ ) - { - unsigned short indexTypeNew = _blockIndices[i] & INDEX_TYPE_MASK; - newIndices[i] = indexTypeNew; + // Now pass through again actually making the final compressed data + for (int i = 0; i < 512; i++) { + unsigned short indexTypeNew = _blockIndices[i] & INDEX_TYPE_MASK; + newIndices[i] = indexTypeNew; - if( indexTypeNew == INDEX_TYPE_0_OR_8_BIT ) - { - if( _blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - newIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG | (((unsigned short)data[getIndex(i,0)]) << INDEX_TILE_SHIFT); - } - else - { - usDataOffset = (usDataOffset + 3 ) & 0xfffc; - for( int j = 0; j < 64; j++ ) // This loop of 64 is to go round the 4 x 4 x 4 tiles in the block - { - pucData[usDataOffset + j] = data[getIndex(i,j)]; - } - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - usDataOffset += 64; - } - } - else - { - // Need to repack - TODO - from here onwards! - unsigned char ucMappings[256] = {0}; - for( int j = 0; j < 256; j++ ) - { - ucMappings[j] = 255; - } + if (indexTypeNew == INDEX_TYPE_0_OR_8_BIT) { + if (_blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + newIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG | + (((unsigned short)data[getIndex(i, 0)]) + << INDEX_TILE_SHIFT); + } else { + usDataOffset = (usDataOffset + 3) & 0xfffc; + for (int j = 0; j < 64; + j++) // This loop of 64 is to go round the 4 x 4 x 4 tiles + // in the block + { + pucData[usDataOffset + j] = data[getIndex(i, j)]; + } + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + usDataOffset += 64; + } + } else { + // Need to repack - TODO - from here onwards! + unsigned char ucMappings[256] = {0}; + for (int j = 0; j < 256; j++) { + ucMappings[j] = 255; + } - unsigned char *repacked = NULL; + unsigned char* repacked = NULL; - int bitspertile = 1 << indexTypeNew; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - //int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int tiledatasize = 8 << indexTypeNew; // will be 8, 16 or 32 (from index values of 0, 1, 2) - int indexshift = 3 - indexTypeNew; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexTypeNew; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + int bitspertile = 1 << indexTypeNew; // will be 1, 2 or 4 (from + // index values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from + // index values of 0, 1, 2) + // int tiletypemask = tiletypecount - 1; // will be 1, 3 + // or 15 (from index values of 0, 1, 2) + int tiledatasize = 8 << indexTypeNew; // will be 8, 16 or 32 (from + // index values of 0, 1, 2) + int indexshift = 3 - indexTypeNew; // will be 3, 2 or 1 (from index + // values of 0, 1, 2) + int indexmask_bits = 7 >> indexTypeNew; // will be 7, 3 or 1 (from + // index values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index values of + // 0, 1, 2) - unsigned char *tile_types = pucData + usDataOffset; - repacked = tile_types + tiletypecount; - XMemSet(tile_types, 255, tiletypecount); - XMemSet(repacked, 0,tiledatasize); - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - usDataOffset += tiletypecount + tiledatasize; - int count = 0; - for( int j = 0; j < 64; j++ ) - { - int tile = data[getIndex(i,j)]; - if( ucMappings[tile] == 255 ) - { - ucMappings[tile] = count; - tile_types[count++] = tile; - } - int idx = (j >> indexshift) & indexmask_bytes; - int bit = ( j & indexmask_bits ) * bitspertile; - repacked[idx] |= ucMappings[tile] << bit; - } - } - } + unsigned char* tile_types = pucData + usDataOffset; + repacked = tile_types + tiletypecount; + XMemSet(tile_types, 255, tiletypecount); + XMemSet(repacked, 0, tiledatasize); + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + usDataOffset += tiletypecount + tiledatasize; + int count = 0; + for (int j = 0; j < 64; j++) { + int tile = data[getIndex(i, j)]; + if (ucMappings[tile] == 255) { + ucMappings[tile] = count; + tile_types[count++] = tile; + } + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) * bitspertile; + repacked[idx] |= ucMappings[tile] << bit; + } + } + } - if( indicesAndData ) - { - queueForDelete( indicesAndData ); - } - indicesAndData = newIndicesAndData; - allocatedSize = memToAlloc; - LeaveCriticalSection(&cs_write); + if (indicesAndData) { + queueForDelete(indicesAndData); + } + indicesAndData = newIndicesAndData; + allocatedSize = memToAlloc; + LeaveCriticalSection(&cs_write); } #ifdef PSVITA_PRECOMPUTED_TABLE -// AP - When called in pairs from LevelChunk::getBlockData this version of getData reduces the time from ~5.2ms to ~1.6ms on the Vita -// Gets all tile values into an array of length 32768. -void CompressedTileStorage::getData(byteArray retArray, unsigned int retOffset) -{ - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; +// AP - When called in pairs from LevelChunk::getBlockData this version of +// getData reduces the time from ~5.2ms to ~1.6ms on the Vita Gets all tile +// values into an array of length 32768. +void CompressedTileStorage::getData(byteArray retArray, + unsigned int retOffset) { + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - int k = 0; - unsigned char *Array = &retArray.data[retOffset]; - int *Table = CompressedTile_StorageIndexTable; - for( int i = 0; i < 512; i++ ) - { - int indexType = blockIndices[i] & INDEX_TYPE_MASK; + int k = 0; + unsigned char* Array = &retArray.data[retOffset]; + int* Table = CompressedTile_StorageIndexTable; + for (int i = 0; i < 512; i++) { + int indexType = blockIndices[i] & INDEX_TYPE_MASK; - int index = ( ( i & 0x180) << 6 ) | ( ( i & 0x060 ) << 4 ) | ( ( i & 0x01f ) << 2 ); - unsigned char *NewArray = &Array[index]; + int index = + ((i & 0x180) << 6) | ((i & 0x060) << 4) | ((i & 0x01f) << 2); + unsigned char* NewArray = &Array[index]; - if( indexType == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - unsigned char val = ( blockIndices[i] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK; - for( int j = 0; j < 64; j++ ) - { - NewArray[Table[j]] = val; - } - } - else - { - // 8-bit reads are just directly read from the 64 long array of values stored for the block - unsigned char *packed = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); + if (indexType == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + unsigned char val = + (blockIndices[i] >> INDEX_TILE_SHIFT) & INDEX_TILE_MASK; + for (int j = 0; j < 64; j++) { + NewArray[Table[j]] = val; + } + } else { + // 8-bit reads are just directly read from the 64 long array of + // values stored for the block + unsigned char* packed = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); - for( int j = 0; j < 64; j++ ) - { - NewArray[Table[j]] = packed[j]; - } - } - } - else - { - // 1, 2, or 4 bits per block packed format + for (int j = 0; j < 64; j++) { + NewArray[Table[j]] = packed[j]; + } + } + } else { + // 1, 2, or 4 bits per block packed format - int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int indexshift = 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index + // values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from + // index values of 0, 1, 2) + int tiletypemask = + tiletypecount - + 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) + int indexshift = + 3 - + indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) + int indexmask_bits = + 7 >> + indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index values of + // 0, 1, 2) - unsigned char *tile_types = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - unsigned char *packed = tile_types + tiletypecount; + unsigned char* tile_types = + data + + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & INDEX_OFFSET_MASK); + unsigned char* packed = tile_types + tiletypecount; - for( int j = 0; j < 64; j++ ) - { - int idx = ( j >> indexshift ) & indexmask_bytes; - int bit = ( j & indexmask_bits ) << indexType; - NewArray[Table[j]] = tile_types[( packed[idx] >> bit ) & tiletypemask]; - } - } - } + for (int j = 0; j < 64; j++) { + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) << indexType; + NewArray[Table[j]] = + tile_types[(packed[idx] >> bit) & tiletypemask]; + } + } + } } #else // Gets all tile values into an array of length 32768. -void CompressedTileStorage::getData(byteArray retArray, unsigned int retOffset) -{ - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; +void CompressedTileStorage::getData(byteArray retArray, + unsigned int retOffset) { + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - for( int i = 0; i < 512; i++ ) - { - int indexType = blockIndices[i] & INDEX_TYPE_MASK; - if( indexType == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - for( int j = 0; j < 64; j++ ) - { - retArray[getIndex(i,j) + retOffset] = ( blockIndices[i] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK; - } - } - else - { - // 8-bit reads are just directly read from the 64 long array of values stored for the block - unsigned char *packed = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); + for (int i = 0; i < 512; i++) { + int indexType = blockIndices[i] & INDEX_TYPE_MASK; + if (indexType == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + for (int j = 0; j < 64; j++) { + retArray[getIndex(i, j) + retOffset] = + (blockIndices[i] >> INDEX_TILE_SHIFT) & INDEX_TILE_MASK; + } + } else { + // 8-bit reads are just directly read from the 64 long array of + // values stored for the block + unsigned char* packed = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); - for( int j = 0; j < 64; j++ ) - { - retArray[getIndex(i,j) + retOffset] = packed[j]; - } - } - } - else - { - // 1, 2, or 4 bits per block packed format + for (int j = 0; j < 64; j++) { + retArray[getIndex(i, j) + retOffset] = packed[j]; + } + } + } else { + // 1, 2, or 4 bits per block packed format - int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int indexshift = 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index + // values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from + // index values of 0, 1, 2) + int tiletypemask = + tiletypecount - + 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) + int indexshift = + 3 - + indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) + int indexmask_bits = + 7 >> + indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index values of + // 0, 1, 2) - unsigned char *tile_types = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - unsigned char *packed = tile_types + tiletypecount; + unsigned char* tile_types = + data + + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & INDEX_OFFSET_MASK); + unsigned char* packed = tile_types + tiletypecount; - for( int j = 0; j < 64; j++ ) - { - int idx = ( j >> indexshift ) & indexmask_bytes; - int bit = ( j & indexmask_bits ) * bitspertile; - retArray[getIndex(i,j) + retOffset] = tile_types[( packed[idx] >> bit ) & tiletypemask]; - } - } - } + for (int j = 0; j < 64; j++) { + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) * bitspertile; + retArray[getIndex(i, j) + retOffset] = + tile_types[(packed[idx] >> bit) & tiletypemask]; + } + } + } } #endif // Get an individual tile value -int CompressedTileStorage::get(int x, int y, int z) -{ - if(!indicesAndData) return 0; +int CompressedTileStorage::get(int x, int y, int z) { + if (!indicesAndData) return 0; - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - int block, tile; - getBlockAndTile( &block, &tile, x, y, z ); - int indexType = blockIndices[block] & INDEX_TYPE_MASK; + int block, tile; + getBlockAndTile(&block, &tile, x, y, z); + int indexType = blockIndices[block] & INDEX_TYPE_MASK; - if( indexType == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[block] & INDEX_TYPE_0_BIT_FLAG ) - { - // 0 bit reads are easy - the value is packed in the index - return ( blockIndices[block] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK; - } - else - { - // 8-bit reads are just directly read from the 64 long array of values stored for the block - unsigned char *packed = data + ( ( blockIndices[block] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - return packed[tile]; - } - } - else - { - int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int indexshift = 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + if (indexType == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[block] & INDEX_TYPE_0_BIT_FLAG) { + // 0 bit reads are easy - the value is packed in the index + return (blockIndices[block] >> INDEX_TILE_SHIFT) & INDEX_TILE_MASK; + } else { + // 8-bit reads are just directly read from the 64 long array of + // values stored for the block + unsigned char* packed = + data + ((blockIndices[block] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + return packed[tile]; + } + } else { + int bitspertile = + 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index + // values of 0, 1, 2) + int tiletypemask = + tiletypecount - + 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) + int indexshift = + 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) + int indexmask_bits = + 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) + int indexmask_bytes = + 62 >> + indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) - unsigned char *tile_types = data + ( ( blockIndices[block] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - unsigned char *packed = tile_types + tiletypecount; - int idx = ( tile >> indexshift ) & indexmask_bytes; - int bit = ( tile & indexmask_bits ) * bitspertile; - return tile_types[( packed[idx] >> bit ) & tiletypemask]; - } - return 0; + unsigned char* tile_types = + data + + ((blockIndices[block] >> INDEX_OFFSET_SHIFT) & INDEX_OFFSET_MASK); + unsigned char* packed = tile_types + tiletypecount; + int idx = (tile >> indexshift) & indexmask_bytes; + int bit = (tile & indexmask_bits) * bitspertile; + return tile_types[(packed[idx] >> bit) & tiletypemask]; + } + return 0; } // Set an individual tile value -void CompressedTileStorage::set(int x, int y, int z, int val) -{ - EnterCriticalSection(&cs_write); - assert(val !=255 ); - int block, tile; - getBlockAndTile( &block, &tile, x, y, z ); +void CompressedTileStorage::set(int x, int y, int z, int val) { + EnterCriticalSection(&cs_write); + assert(val != 255); + int block, tile; + getBlockAndTile(&block, &tile, x, y, z); - // 2 passes - first pass will try and store within the current levels of compression, then if that fails will - // upgrade the block we are writing to (so more bits can be stored) to achieve the storage required - for( int pass = 0; pass < 2; pass++ ) - { - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; + // 2 passes - first pass will try and store within the current levels of + // compression, then if that fails will upgrade the block we are writing to + // (so more bits can be stored) to achieve the storage required + for (int pass = 0; pass < 2; pass++) { + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - int indexType = blockIndices[block] & INDEX_TYPE_MASK; + int indexType = blockIndices[block] & INDEX_TYPE_MASK; - if( indexType == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[block] & INDEX_TYPE_0_BIT_FLAG ) - { - // 0 bits - if its the value already, we're done, otherwise continue on to upgrade storage - if ( val == ( ( blockIndices[block] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK ) ) - { - LeaveCriticalSection(&cs_write); - return; - } - } - else - { - // 8 bits - just store directly and we're done - unsigned char *packed = data + ( ( blockIndices[block] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - packed[ tile ] = val; - LeaveCriticalSection(&cs_write); - return; - } - } - else - { - int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int indexshift = 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + if (indexType == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[block] & INDEX_TYPE_0_BIT_FLAG) { + // 0 bits - if its the value already, we're done, otherwise + // continue on to upgrade storage + if (val == ((blockIndices[block] >> INDEX_TILE_SHIFT) & + INDEX_TILE_MASK)) { + LeaveCriticalSection(&cs_write); + return; + } + } else { + // 8 bits - just store directly and we're done + unsigned char* packed = + data + ((blockIndices[block] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + packed[tile] = val; + LeaveCriticalSection(&cs_write); + return; + } + } else { + int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index + // values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from + // index values of 0, 1, 2) + int tiletypemask = + tiletypecount - + 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) + int indexshift = + 3 - + indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) + int indexmask_bits = + 7 >> + indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index values of + // 0, 1, 2) - unsigned char *tile_types = data + ( ( blockIndices[block] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); + unsigned char* tile_types = + data + ((blockIndices[block] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); - for( int i = 0; i < tiletypecount; i++ ) - { - if( ( tile_types[i] == val ) || ( tile_types[i] == 255 ) ) - { - tile_types[i] = val; - unsigned char *packed = tile_types + tiletypecount; - int idx = ( tile >> indexshift ) & indexmask_bytes; - int bit = ( tile & indexmask_bits ) * bitspertile; - packed[idx] &= ~( tiletypemask << bit ); - packed[idx] |= i << bit; - LeaveCriticalSection(&cs_write); - return; - } - } - } - if( pass == 0 ) - { - compress(block); - } - }; - LeaveCriticalSection(&cs_write); + for (int i = 0; i < tiletypecount; i++) { + if ((tile_types[i] == val) || (tile_types[i] == 255)) { + tile_types[i] = val; + unsigned char* packed = tile_types + tiletypecount; + int idx = (tile >> indexshift) & indexmask_bytes; + int bit = (tile & indexmask_bits) * bitspertile; + packed[idx] &= ~(tiletypemask << bit); + packed[idx] |= i << bit; + LeaveCriticalSection(&cs_write); + return; + } + } + } + if (pass == 0) { + compress(block); + } + }; + LeaveCriticalSection(&cs_write); } -// Sets a region of tile values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer -int CompressedTileStorage::setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset, tileUpdatedCallback callback, void *param, int yparam) -{ - unsigned char *pucIn = &dataIn.data[offset]; +// Sets a region of tile values with the data at offset position in the array +// dataIn - external ordering compatible with java DataLayer +int CompressedTileStorage::setDataRegion(byteArray dataIn, int x0, int y0, + int z0, int x1, int y1, int z1, + int offset, + tileUpdatedCallback callback, + void* param, int yparam) { + unsigned char* pucIn = &dataIn.data[offset]; - if( callback ) - { - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - for( int y = y0; y < y1; y++ ) - { - if(get(x, y, z) != *pucIn) - { - set(x, y, z, *pucIn); - callback(x, y, z, param, yparam); - } - pucIn++; - } - } - } - } - else - { - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - for( int y = y0; y < y1; y++ ) - { - set(x, y, z, *pucIn++); - } - } - } - } - ptrdiff_t count = pucIn - &dataIn.data[offset]; + if (callback) { + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + for (int y = y0; y < y1; y++) { + if (get(x, y, z) != *pucIn) { + set(x, y, z, *pucIn); + callback(x, y, z, param, yparam); + } + pucIn++; + } + } + } + } else { + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + for (int y = y0; y < y1; y++) { + set(x, y, z, *pucIn++); + } + } + } + } + ptrdiff_t count = pucIn - &dataIn.data[offset]; - return (int)count; + return (int)count; } // Tests whether setting data would actually change anything -bool CompressedTileStorage::testSetDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset) -{ - unsigned char *pucIn = &dataIn.data[offset]; - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - for( int y = y0; y < y1; y++ ) - { - if(get(x, y, z) != *pucIn++) - { - return true; - } - } - } - } - return false; +bool CompressedTileStorage::testSetDataRegion(byteArray dataIn, int x0, int y0, + int z0, int x1, int y1, int z1, + int offset) { + unsigned char* pucIn = &dataIn.data[offset]; + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + for (int y = y0; y < y1; y++) { + if (get(x, y, z) != *pucIn++) { + return true; + } + } + } + } + return false; } -// Updates the data at offset position dataInOut with a region of tile information - external ordering compatible with java DataLayer -int CompressedTileStorage::getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset) -{ - unsigned char *pucOut = &dataInOut.data[offset]; - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - for( int y = y0; y < y1; y++ ) - { - *pucOut++ = get(x, y, z); - } - } - } - ptrdiff_t count = pucOut - &dataInOut.data[offset]; +// Updates the data at offset position dataInOut with a region of tile +// information - external ordering compatible with java DataLayer +int CompressedTileStorage::getDataRegion(byteArray dataInOut, int x0, int y0, + int z0, int x1, int y1, int z1, + int offset) { + unsigned char* pucOut = &dataInOut.data[offset]; + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + for (int y = y0; y < y1; y++) { + *pucOut++ = get(x, y, z); + } + } + } + ptrdiff_t count = pucOut - &dataInOut.data[offset]; - return (int)count; + return (int)count; } -void CompressedTileStorage::staticCtor() -{ - InitializeCriticalSectionAndSpinCount(&cs_write, 5120); - for( int i = 0; i < 3; i++ ) - { - deleteQueue[i].Initialize(); - } +void CompressedTileStorage::staticCtor() { + InitializeCriticalSectionAndSpinCount(&cs_write, 5120); + for (int i = 0; i < 3; i++) { + deleteQueue[i].Initialize(); + } } -void CompressedTileStorage::queueForDelete(unsigned char *data) -{ - // Add this into a queue for deleting. This shouldn't be actually deleted until tick has been called twice from when - // the data went into the queue. - if( data ) - { - deleteQueue[deleteQueueIndex].Push( data ); - } +void CompressedTileStorage::queueForDelete(unsigned char* data) { + // Add this into a queue for deleting. This shouldn't be actually deleted + // until tick has been called twice from when the data went into the queue. + if (data) { + deleteQueue[deleteQueueIndex].Push(data); + } } -void CompressedTileStorage::tick() -{ - // We have 3 queues for deleting. Always delete from the next one after where we are writing to, so it should take 2 ticks - // before we ever delete something, from when the request to delete it came in - int freeIndex = ( deleteQueueIndex + 1 ) % 3; +void CompressedTileStorage::tick() { + // We have 3 queues for deleting. Always delete from the next one after + // where we are writing to, so it should take 2 ticks before we ever delete + // something, from when the request to delete it came in + int freeIndex = (deleteQueueIndex + 1) % 3; -// printf("Free queue: %d, %d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); - unsigned char *toFree = NULL; - do - { - toFree = deleteQueue[freeIndex].Pop(); + // printf("Free queue: %d, + //%d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); + unsigned char* toFree = NULL; + do { + toFree = deleteQueue[freeIndex].Pop(); // if( toFree ) printf("Deleting 0x%x\n", toFree); #if 1 - if( toFree ) XPhysicalFree(toFree); + if (toFree) XPhysicalFree(toFree); #else - // Determine correct means to free this data - could have been allocated either with XPhysicalAlloc or malloc - if( (unsigned int)toFree >= MM_PHYSICAL_4KB_BASE ) - { - XPhysicalFree(toFree); - } - else - { - free(toFree); - } + // Determine correct means to free this data - could have been allocated + // either with XPhysicalAlloc or malloc + if ((unsigned int)toFree >= MM_PHYSICAL_4KB_BASE) { + XPhysicalFree(toFree); + } else { + free(toFree); + } #endif - } while( toFree ); + } while (toFree); - deleteQueueIndex = ( deleteQueueIndex + 1 ) % 3; + deleteQueueIndex = (deleteQueueIndex + 1) % 3; } #ifdef __PS3__ -void CompressedTileStorage::compress_SPU(int upgradeBlock/*=-1*/) -{ - EnterCriticalSection(&cs_write); - static unsigned char compBuffer[32768+4096] __attribute__((__aligned__(16))); - CompressedTileStorage_compress_dataIn& dataIn = g_compressTileDataIn[0]; - dataIn.allocatedSize = allocatedSize; - dataIn.indicesAndData = indicesAndData; - dataIn.newIndicesAndData = compBuffer; - dataIn.upgradeBlock = upgradeBlock; +void CompressedTileStorage::compress_SPU(int upgradeBlock /*=-1*/) { + EnterCriticalSection(&cs_write); + static unsigned char compBuffer[32768 + 4096] + __attribute__((__aligned__(16))); + CompressedTileStorage_compress_dataIn& dataIn = g_compressTileDataIn[0]; + dataIn.allocatedSize = allocatedSize; + dataIn.indicesAndData = indicesAndData; + dataIn.newIndicesAndData = compBuffer; + dataIn.upgradeBlock = upgradeBlock; - static C4JSpursJobQueue::Port p("CompressedTileStorage::compress_SPU"); - C4JSpursJob_CompressedTileStorage_compress compressJob(&dataIn); - p.submitJob(&compressJob); - p.waitForCompletion(); + static C4JSpursJobQueue::Port p("CompressedTileStorage::compress_SPU"); + C4JSpursJob_CompressedTileStorage_compress compressJob(&dataIn); + p.submitJob(&compressJob); + p.waitForCompletion(); - if(dataIn.neededCompressed) - { - unsigned char *newIndicesAndData = (unsigned char *)XPhysicalAlloc(dataIn.newAllocatedSize, MAXULONG_PTR, 4096, PAGE_READWRITE);//(unsigned char *)malloc( memToAlloc ); - memcpy(newIndicesAndData, compBuffer, dataIn.newAllocatedSize); - queueForDelete( indicesAndData ); - indicesAndData = newIndicesAndData; - allocatedSize = dataIn.newAllocatedSize; - } - - LeaveCriticalSection(&cs_write); + if (dataIn.neededCompressed) { + unsigned char* newIndicesAndData = (unsigned char*)XPhysicalAlloc( + dataIn.newAllocatedSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); //(unsigned char *)malloc( memToAlloc ); + memcpy(newIndicesAndData, compBuffer, dataIn.newAllocatedSize); + queueForDelete(indicesAndData); + indicesAndData = newIndicesAndData; + allocatedSize = dataIn.newAllocatedSize; + } + LeaveCriticalSection(&cs_write); } #endif // Compresses the data currently stored in one of two ways: -// (1) Attempt to compresses every block as much as possible (if upgradeBlock is -1) -// (2) Copy all blocks as-is apart from the block specified by upgradeBlock ( if > -1 ), which is changed to be the next-most-accomodating storage from its current state -void CompressedTileStorage::compress(int upgradeBlock/*=-1*/) -{ +// (1) Attempt to compresses every block as much as possible (if upgradeBlock is +// -1) (2) Copy all blocks as-is apart from the block specified by upgradeBlock +// ( if > -1 ), which is changed to be the next-most-accomodating storage from +// its current state +void CompressedTileStorage::compress(int upgradeBlock /*=-1*/) { #if defined __PS3__ && !defined DISABLE_SPU_CODE - compress_SPU(upgradeBlock); - return; + compress_SPU(upgradeBlock); + return; #endif - unsigned char tempdata[64]; - unsigned short _blockIndices[512]; + unsigned char tempdata[64]; + unsigned short _blockIndices[512]; - // If this is already fully compressed, early out - if( ( allocatedSize == 1024 ) && ( upgradeBlock == -1 ) ) return; + // If this is already fully compressed, early out + if ((allocatedSize == 1024) && (upgradeBlock == -1)) return; - bool needsCompressed = ( upgradeBlock > -1 ); // If an upgrade block is specified, we'll always need to recompress - otherwise default to false + bool needsCompressed = + (upgradeBlock > -1); // If an upgrade block is specified, we'll always + // need to recompress - otherwise default to false - EnterCriticalSection(&cs_write); + EnterCriticalSection(&cs_write); - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned char *data = indicesAndData + 1024; + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned char* data = indicesAndData + 1024; - int memToAlloc = 0; - for( int i = 0; i < 512; i++ ) - { - unsigned short indexType = blockIndices[i] & INDEX_TYPE_MASK; + int memToAlloc = 0; + for (int i = 0; i < 512; i++) { + unsigned short indexType = blockIndices[i] & INDEX_TYPE_MASK; - unsigned char *unpacked_data = NULL; - unsigned char *packed_data; + unsigned char* unpacked_data = NULL; + unsigned char* packed_data; - // First task is to find out what type of storage each block needs. Need to unpack each where required. - // Note that we don't need to fully unpack the data at this stage since we are only interested in working out how many unique types of tiles are in each block, not - // what those actual tile ids are. - if( upgradeBlock == -1 ) - { - if( indexType == INDEX_TYPE_0_OR_8_BIT ) - { - // Note that we are only interested in data that can be packed further, so we don't need to consider things that are already at their most compressed - // (ie with INDEX_TYPE_0_BIT_FLAG set) - if( ( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) == 0 ) - { - unpacked_data = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - } - } - else - { - int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 - int indexshift = 3 - indexType; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexType; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + // First task is to find out what type of storage each block needs. Need + // to unpack each where required. Note that we don't need to fully + // unpack the data at this stage since we are only interested in working + // out how many unique types of tiles are in each block, not what those + // actual tile ids are. + if (upgradeBlock == -1) { + if (indexType == INDEX_TYPE_0_OR_8_BIT) { + // Note that we are only interested in data that can be packed + // further, so we don't need to consider things that are already + // at their most compressed (ie with INDEX_TYPE_0_BIT_FLAG set) + if ((blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) == 0) { + unpacked_data = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + } + } else { + int bitspertile = 1 << indexType; // will be 1, 2 or 4 (from + // index values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 + int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 + int indexshift = 3 - indexType; // will be 3, 2 or 1 (from + // index values of 0, 1, 2) + int indexmask_bits = + 7 >> indexType; // will be 7, 3 or 1 (from index values of + // 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index values + // of 0, 1, 2) - unpacked_data = tempdata; - packed_data = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ) + tiletypecount; + unpacked_data = tempdata; + packed_data = data + + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK) + + tiletypecount; - for( int j = 0; j < 64; j++ ) - { - int idx = (j >> indexshift) & indexmask_bytes; - int bit = ( j & indexmask_bits ) * bitspertile; + for (int j = 0; j < 64; j++) { + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) * bitspertile; - unpacked_data[j] = ( packed_data[idx] >> bit ) & tiletypemask; // Doesn't need the actual data for each tile, just unique values - } - } + unpacked_data[j] = + (packed_data[idx] >> bit) & + tiletypemask; // Doesn't need the actual data for each + // tile, just unique values + } + } - if( unpacked_data ) - { - // Now count how many unique tile types are in the block - if unpacked_data isn't set then there isn't any data so we can't compress any further and require no storage. - // Store flags for each tile type used in an array of 4 64-bit flags. + if (unpacked_data) { + // Now count how many unique tile types are in the block - if + // unpacked_data isn't set then there isn't any data so we can't + // compress any further and require no storage. Store flags for + // each tile type used in an array of 4 64-bit flags. #ifdef __PSVITA__ - // AP - Vita isn't so great at shifting 64bits. The top biggest CPU time sink after profiling is __ashldi3 (64bit shift) at 3% - // lets use 32bit values instead - unsigned int usedFlags[8] = {0,0,0,0,0,0,0,0}; - __int32 i32_1 = 1; - for( int j = 0; j < 64; j++ ) // This loop of 64 is to go round the 4x4x4 tiles in the block - { - int tiletype = unpacked_data[j]; - usedFlags[tiletype & 7] |= ( i32_1 << ( tiletype >> 3 ) ); - } - // count the number of bits set using the 'Hammering Weight' method. This reduces ::compress total thread cpu consumption from 10% to 4% - unsigned int count = 0; - for( int Index = 0;Index < 8;Index += 1 ) - { - unsigned int i = usedFlags[Index]; - i = i - ((i >> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >> 2) & 0x33333333); - count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; - } + // AP - Vita isn't so great at shifting 64bits. The top biggest + // CPU time sink after profiling is __ashldi3 (64bit shift) at + // 3% lets use 32bit values instead + unsigned int usedFlags[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + __int32 i32_1 = 1; + for (int j = 0; j < 64; j++) // This loop of 64 is to go round + // the 4x4x4 tiles in the block + { + int tiletype = unpacked_data[j]; + usedFlags[tiletype & 7] |= (i32_1 << (tiletype >> 3)); + } + // count the number of bits set using the 'Hammering Weight' + // method. This reduces ::compress total thread cpu consumption + // from 10% to 4% + unsigned int count = 0; + for (int Index = 0; Index < 8; Index += 1) { + unsigned int i = usedFlags[Index]; + i = i - ((i >> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >> 2) & 0x33333333); + count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; + } #else - __uint64 usedFlags[4] = {0,0,0,0}; - __int64 i64_1 = 1; // MGH - instead of 1i64, which is MS specific - for( int j = 0; j < 64; j++ ) // This loop of 64 is to go round the 4x4x4 tiles in the block - { - int tiletype = unpacked_data[j]; - usedFlags[tiletype & 3] |= ( i64_1 << ( tiletype >> 2 ) ); - } - int count = 0; - for( int tiletype = 0; tiletype < 256; tiletype++ ) // This loop of 256 is to go round the 256 possible values that the tiles might have had to find how many are actually used - { - if( usedFlags[tiletype & 3] & ( i64_1 << ( tiletype >> 2 ) ) ) - { - count++; - } - } + __uint64 usedFlags[4] = {0, 0, 0, 0}; + __int64 i64_1 = + 1; // MGH - instead of 1i64, which is MS specific + for (int j = 0; j < 64; j++) // This loop of 64 is to go round + // the 4x4x4 tiles in the block + { + int tiletype = unpacked_data[j]; + usedFlags[tiletype & 3] |= (i64_1 << (tiletype >> 2)); + } + int count = 0; + for (int tiletype = 0; tiletype < 256; + tiletype++) // This loop of 256 is to go round the 256 + // possible values that the tiles might have + // had to find how many are actually used + { + if (usedFlags[tiletype & 3] & (i64_1 << (tiletype >> 2))) { + count++; + } + } #endif - if( count == 1 ) - { - _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; + if (count == 1) { + _blockIndices[i] = + INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG; - // We'll need to compress if this isn't the same type as before. If it *was* a 0-bit one though, then unpacked_data wouldn't have been set and we wouldn't be here - needsCompressed = true; - } - else if( count == 2 ) - { - _blockIndices[i] = INDEX_TYPE_1_BIT; - if( indexType != INDEX_TYPE_1_BIT ) needsCompressed = true; - memToAlloc += 10; // 8 bytes + 2 tile index - } - else if ( count <= 4 ) - { - _blockIndices[i] = INDEX_TYPE_2_BIT; - if( indexType != INDEX_TYPE_2_BIT ) needsCompressed = true; - memToAlloc += 20; // 16 bytes + 4 tile index - } - else if ( count <= 16 ) - { - _blockIndices[i] = INDEX_TYPE_4_BIT; - if( indexType != INDEX_TYPE_4_BIT ) needsCompressed = true; - memToAlloc += 48; // 32 bytes + 16 tile index - } - else - { - _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT; - memToAlloc = ( memToAlloc + 3 ) & 0xfffc; // Make sure we are 4-byte aligned for 8-bit storage - memToAlloc += 64; - } - } - else - { - // Already will be 0 bits, so we can't do any further compression - just copy the index over. - _blockIndices[i] = blockIndices[i]; - } - } - else - { - if( i == upgradeBlock ) - { - // INDEX_TYPE_1_BIT (0) -> INDEX_TYPE_2_BIT (1) - // INDEX_TYPE_2_BIT (1) -> INDEX_TYPE_4_BIT (2) - // INDEX_TYPE_4_BIT (2) -> INDEX_TYPE_0_OR_8_BIT (3) (new will be 8-bit) - // INDEX_TYPE_0_OR_8_BIT (3) -> INDEX_TYPE_1_BIT (0) (assuming old was 0-bit) - _blockIndices[i] = ( ( blockIndices[i] & INDEX_TYPE_MASK ) + 1 ) & INDEX_TYPE_MASK; - } - else - { - // Copy over the index, without the offset. - _blockIndices[i] = blockIndices[i] & INDEX_TYPE_MASK; - if( _blockIndices[i] == INDEX_TYPE_0_OR_8_BIT ) - { - _blockIndices[i] |= ( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ); - } - } - switch(_blockIndices[i]) - { - case INDEX_TYPE_1_BIT: - memToAlloc += 10; - break; - case INDEX_TYPE_2_BIT: - memToAlloc += 20; - break; - case INDEX_TYPE_4_BIT: - memToAlloc += 48; - break; - case INDEX_TYPE_0_OR_8_BIT: - memToAlloc = ( memToAlloc + 3 ) & 0xfffc; // Make sure we are 4-byte aligned for 8-bit storage - memToAlloc += 64; - break; - // Note that INDEX_TYPE_8_BIT|INDEX_TYPE_0_BIT_FLAG not in here as it doesn't need any further allocation - } - } - } + // We'll need to compress if this isn't the same type as + // before. If it *was* a 0-bit one though, then + // unpacked_data wouldn't have been set and we wouldn't be + // here + needsCompressed = true; + } else if (count == 2) { + _blockIndices[i] = INDEX_TYPE_1_BIT; + if (indexType != INDEX_TYPE_1_BIT) needsCompressed = true; + memToAlloc += 10; // 8 bytes + 2 tile index + } else if (count <= 4) { + _blockIndices[i] = INDEX_TYPE_2_BIT; + if (indexType != INDEX_TYPE_2_BIT) needsCompressed = true; + memToAlloc += 20; // 16 bytes + 4 tile index + } else if (count <= 16) { + _blockIndices[i] = INDEX_TYPE_4_BIT; + if (indexType != INDEX_TYPE_4_BIT) needsCompressed = true; + memToAlloc += 48; // 32 bytes + 16 tile index + } else { + _blockIndices[i] = INDEX_TYPE_0_OR_8_BIT; + memToAlloc = + (memToAlloc + 3) & 0xfffc; // Make sure we are 4-byte + // aligned for 8-bit storage + memToAlloc += 64; + } + } else { + // Already will be 0 bits, so we can't do any further + // compression - just copy the index over. + _blockIndices[i] = blockIndices[i]; + } + } else { + if (i == upgradeBlock) { + // INDEX_TYPE_1_BIT (0) -> INDEX_TYPE_2_BIT (1) + // INDEX_TYPE_2_BIT (1) -> INDEX_TYPE_4_BIT (2) + // INDEX_TYPE_4_BIT (2) -> INDEX_TYPE_0_OR_8_BIT (3) (new + // will be 8-bit) INDEX_TYPE_0_OR_8_BIT (3) -> INDEX_TYPE_1_BIT + // (0) (assuming old was 0-bit) + _blockIndices[i] = + ((blockIndices[i] & INDEX_TYPE_MASK) + 1) & INDEX_TYPE_MASK; + } else { + // Copy over the index, without the offset. + _blockIndices[i] = blockIndices[i] & INDEX_TYPE_MASK; + if (_blockIndices[i] == INDEX_TYPE_0_OR_8_BIT) { + _blockIndices[i] |= + (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG); + } + } + switch (_blockIndices[i]) { + case INDEX_TYPE_1_BIT: + memToAlloc += 10; + break; + case INDEX_TYPE_2_BIT: + memToAlloc += 20; + break; + case INDEX_TYPE_4_BIT: + memToAlloc += 48; + break; + case INDEX_TYPE_0_OR_8_BIT: + memToAlloc = + (memToAlloc + 3) & 0xfffc; // Make sure we are 4-byte + // aligned for 8-bit storage + memToAlloc += 64; + break; + // Note that INDEX_TYPE_8_BIT|INDEX_TYPE_0_BIT_FLAG not in + // here as it doesn't need any further allocation + } + } + } - // If we need to do something here, then lets allocate some memory - if( needsCompressed ) - { - memToAlloc += 1024; // For the indices - unsigned char *newIndicesAndData = (unsigned char *)XPhysicalAlloc(memToAlloc, MAXULONG_PTR, 4096, PAGE_READWRITE);//(unsigned char *)malloc( memToAlloc ); - if( newIndicesAndData == NULL ) - { + // If we need to do something here, then lets allocate some memory + if (needsCompressed) { + memToAlloc += 1024; // For the indices + unsigned char* newIndicesAndData = (unsigned char*)XPhysicalAlloc( + memToAlloc, MAXULONG_PTR, 4096, + PAGE_READWRITE); //(unsigned char *)malloc( memToAlloc ); + if (newIndicesAndData == NULL) { #ifndef _DURANGO - MEMORYSTATUS memStatus; - GlobalMemoryStatus(&memStatus); - __debugbreak(); + MEMORYSTATUS memStatus; + GlobalMemoryStatus(&memStatus); + __debugbreak(); #endif - } - unsigned char *pucData = newIndicesAndData + 1024; - unsigned short usDataOffset = 0; - unsigned short *newIndices = (unsigned short *) newIndicesAndData; + } + unsigned char* pucData = newIndicesAndData + 1024; + unsigned short usDataOffset = 0; + unsigned short* newIndices = (unsigned short*)newIndicesAndData; - // Now pass through again actually making the final compressed data - for( int i = 0; i < 512; i++ ) - { - unsigned short indexTypeNew = _blockIndices[i] & INDEX_TYPE_MASK; - unsigned short indexTypeOld = blockIndices[i] & INDEX_TYPE_MASK; - newIndices[i] = indexTypeNew; + // Now pass through again actually making the final compressed data + for (int i = 0; i < 512; i++) { + unsigned short indexTypeNew = _blockIndices[i] & INDEX_TYPE_MASK; + unsigned short indexTypeOld = blockIndices[i] & INDEX_TYPE_MASK; + newIndices[i] = indexTypeNew; - // Is the type unmodifed? Then can just copy over - bool done = false; - if( indexTypeOld == indexTypeNew ) - { - unsigned char *packed_data; - if( indexTypeOld == INDEX_TYPE_0_OR_8_BIT ) - { - if( ( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) == ( _blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) ) - { - if( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - newIndices[i] = blockIndices[i]; - } - else - { - packed_data = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK); - usDataOffset = (usDataOffset + 3 ) & 0xfffc; - XMemCpy( pucData + usDataOffset, packed_data, 64 ); - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - usDataOffset += 64; - } - done = true; - } - } - else - { - packed_data = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK); - - int dataSize = 8 << indexTypeOld; // 8, 16 or 32 bytes of per-tile storage - dataSize += 1 << ( 1 << indexTypeOld ); // 2, 4 or 16 bytes to store each tile type - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - XMemCpy( pucData + usDataOffset, packed_data, dataSize ); - usDataOffset += dataSize; - done = true; - } - } + // Is the type unmodifed? Then can just copy over + bool done = false; + if (indexTypeOld == indexTypeNew) { + unsigned char* packed_data; + if (indexTypeOld == INDEX_TYPE_0_OR_8_BIT) { + if ((blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) == + (_blockIndices[i] & INDEX_TYPE_0_BIT_FLAG)) { + if (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + newIndices[i] = blockIndices[i]; + } else { + packed_data = data + ((blockIndices[i] >> + INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + usDataOffset = (usDataOffset + 3) & 0xfffc; + XMemCpy(pucData + usDataOffset, packed_data, 64); + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + usDataOffset += 64; + } + done = true; + } + } else { + packed_data = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + int dataSize = 8 << indexTypeOld; // 8, 16 or 32 bytes of + // per-tile storage + dataSize += 1 + << (1 << indexTypeOld); // 2, 4 or 16 bytes to + // store each tile type + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + XMemCpy(pucData + usDataOffset, packed_data, dataSize); + usDataOffset += dataSize; + done = true; + } + } - // If we're not done, then we actually need to recompress this block. First of all decompress from its current format. - if( !done ) - { - unsigned char *unpacked_data = NULL; - unsigned char *tile_types = NULL; - unsigned char *packed_data = NULL; - if( indexTypeOld == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - unpacked_data = tempdata; - int value = ( blockIndices[i] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK; - XMemSet( tempdata, value, 64 ); - } - else - { - unpacked_data = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - } - } - else - { - int bitspertile = 1 << indexTypeOld; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 - int indexshift = 3 - indexTypeOld; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexTypeOld; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + // If we're not done, then we actually need to recompress this + // block. First of all decompress from its current format. + if (!done) { + unsigned char* unpacked_data = NULL; + unsigned char* tile_types = NULL; + unsigned char* packed_data = NULL; + if (indexTypeOld == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + unpacked_data = tempdata; + int value = (blockIndices[i] >> INDEX_TILE_SHIFT) & + INDEX_TILE_MASK; + XMemSet(tempdata, value, 64); + } else { + unpacked_data = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + } + } else { + int bitspertile = + 1 << indexTypeOld; // will be 1, 2 or 4 (from index + // values of 0, 1, 2) + int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 + int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 + int indexshift = + 3 - indexTypeOld; // will be 3, 2 or 1 (from index + // values of 0, 1, 2) + int indexmask_bits = + 7 >> indexTypeOld; // will be 7, 3 or 1 (from index + // values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index + // values of 0, 1, 2) - unpacked_data = tempdata; - tile_types = data + ( ( blockIndices[i] >> INDEX_OFFSET_SHIFT ) & INDEX_OFFSET_MASK ); - packed_data = tile_types + tiletypecount; - for( int j = 0; j < 64; j++ ) - { - int idx = ( j >> indexshift ) & indexmask_bytes; - int bit = ( j & indexmask_bits ) * bitspertile; + unpacked_data = tempdata; + tile_types = + data + ((blockIndices[i] >> INDEX_OFFSET_SHIFT) & + INDEX_OFFSET_MASK); + packed_data = tile_types + tiletypecount; + for (int j = 0; j < 64; j++) { + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) * bitspertile; - unpacked_data[j] = tile_types[(packed_data[idx] >> bit) & tiletypemask]; - } - } + unpacked_data[j] = + tile_types[(packed_data[idx] >> bit) & + tiletypemask]; + } + } - // And finally repack - unsigned char ucMappings[256] = {0}; + // And finally repack + unsigned char ucMappings[256] = {0}; #ifdef __PSVITA__ - memset(ucMappings, 255, 256); + memset(ucMappings, 255, 256); #else - for( int j = 0; j < 256; j++ ) - { - ucMappings[j] = 255; - } + for (int j = 0; j < 256; j++) { + ucMappings[j] = 255; + } #endif - unsigned char *repacked = NULL; + unsigned char* repacked = NULL; - if( indexTypeNew == INDEX_TYPE_0_OR_8_BIT ) - { - if( _blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - newIndices[i] = INDEX_TYPE_0_OR_8_BIT | INDEX_TYPE_0_BIT_FLAG | (((unsigned short)unpacked_data[0]) << INDEX_TILE_SHIFT); - } - else - { - usDataOffset = (usDataOffset + 3 ) & 0xfffc; // Make sure offset is 4 byte aligned - XMemCpy( pucData + usDataOffset, unpacked_data, 64 ); - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - usDataOffset += 64; - } - } - else - { - int bitspertile = 1 << indexTypeNew; // will be 1, 2 or 4 (from index values of 0, 1, 2) - int tiletypecount = 1 << bitspertile; // will be 2, 4 or 16 (from index values of 0, 1, 2) - int tiletypemask = tiletypecount - 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) - int tiledatasize = 8 << indexTypeNew; // will be 8, 16 or 32 (from index values of 0, 1, 2) - int indexshift = 3 - indexTypeNew; // will be 3, 2 or 1 (from index values of 0, 1, 2) - int indexmask_bits = 7 >> indexTypeNew; // will be 7, 3 or 1 (from index values of 0, 1, 2) - int indexmask_bytes = 62 >> indexshift; // will be 7, 15 or 31 (from index values of 0, 1, 2) + if (indexTypeNew == INDEX_TYPE_0_OR_8_BIT) { + if (_blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + newIndices[i] = INDEX_TYPE_0_OR_8_BIT | + INDEX_TYPE_0_BIT_FLAG | + (((unsigned short)unpacked_data[0]) + << INDEX_TILE_SHIFT); + } else { + usDataOffset = + (usDataOffset + 3) & + 0xfffc; // Make sure offset is 4 byte aligned + XMemCpy(pucData + usDataOffset, unpacked_data, 64); + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + usDataOffset += 64; + } + } else { + int bitspertile = + 1 << indexTypeNew; // will be 1, 2 or 4 (from index + // values of 0, 1, 2) + int tiletypecount = + 1 << bitspertile; // will be 2, 4 or 16 (from index + // values of 0, 1, 2) + int tiletypemask = + tiletypecount - + 1; // will be 1, 3 or 15 (from index values of 0, 1, 2) + int tiledatasize = + 8 << indexTypeNew; // will be 8, 16 or 32 (from index + // values of 0, 1, 2) + int indexshift = + 3 - indexTypeNew; // will be 3, 2 or 1 (from index + // values of 0, 1, 2) + int indexmask_bits = + 7 >> indexTypeNew; // will be 7, 3 or 1 (from index + // values of 0, 1, 2) + int indexmask_bytes = + 62 >> indexshift; // will be 7, 15 or 31 (from index + // values of 0, 1, 2) - tile_types = pucData + usDataOffset; - repacked = tile_types + tiletypecount; - XMemSet(tile_types, 255, tiletypecount); - XMemSet(repacked, 0,tiledatasize); - newIndices[i] |= ( usDataOffset & INDEX_OFFSET_MASK) << INDEX_OFFSET_SHIFT; - usDataOffset += tiletypecount + tiledatasize; - int count = 0; - for( int j = 0; j < 64; j++ ) - { - int tile = unpacked_data[j]; - if( ucMappings[tile] == 255 ) - { - ucMappings[tile] = count; - tile_types[count++] = tile; - } - int idx = (j >> indexshift) & indexmask_bytes; - int bit = ( j & indexmask_bits ) * bitspertile; - repacked[idx] |= ucMappings[tile] << bit; - } - } - } - } + tile_types = pucData + usDataOffset; + repacked = tile_types + tiletypecount; + XMemSet(tile_types, 255, tiletypecount); + XMemSet(repacked, 0, tiledatasize); + newIndices[i] |= (usDataOffset & INDEX_OFFSET_MASK) + << INDEX_OFFSET_SHIFT; + usDataOffset += tiletypecount + tiledatasize; + int count = 0; + for (int j = 0; j < 64; j++) { + int tile = unpacked_data[j]; + if (ucMappings[tile] == 255) { + ucMappings[tile] = count; + tile_types[count++] = tile; + } + int idx = (j >> indexshift) & indexmask_bytes; + int bit = (j & indexmask_bits) * bitspertile; + repacked[idx] |= ucMappings[tile] << bit; + } + } + } + } - queueForDelete( indicesAndData ); - indicesAndData = newIndicesAndData; - allocatedSize = memToAlloc; - } - LeaveCriticalSection(&cs_write); + queueForDelete(indicesAndData); + indicesAndData = newIndicesAndData; + allocatedSize = memToAlloc; + } + LeaveCriticalSection(&cs_write); } -int CompressedTileStorage::getAllocatedSize(int *count0, int *count1, int *count2, int *count4, int *count8) -{ - *count0 = 0; - *count1 = 0; - *count2 = 0; - *count4 = 0; - *count8 = 0; +int CompressedTileStorage::getAllocatedSize(int* count0, int* count1, + int* count2, int* count4, + int* count8) { + *count0 = 0; + *count1 = 0; + *count2 = 0; + *count4 = 0; + *count8 = 0; - unsigned short *blockIndices = (unsigned short *)indicesAndData; - for(int i = 0; i < 512; i++ ) - { - unsigned short idxType = blockIndices[i] & INDEX_TYPE_MASK; - if( idxType == INDEX_TYPE_1_BIT ) - { - (*count1)++; - } - else if( idxType == INDEX_TYPE_2_BIT ) - { - (*count2)++; - } - else if( idxType == INDEX_TYPE_4_BIT ) - { - (*count4)++; - } - else if( idxType == INDEX_TYPE_0_OR_8_BIT ) - { - if( blockIndices[i] & INDEX_TYPE_0_BIT_FLAG ) - { - (*count0)++; - } - else - { - (*count8)++; - } - } - } - return allocatedSize; + unsigned short* blockIndices = (unsigned short*)indicesAndData; + for (int i = 0; i < 512; i++) { + unsigned short idxType = blockIndices[i] & INDEX_TYPE_MASK; + if (idxType == INDEX_TYPE_1_BIT) { + (*count1)++; + } else if (idxType == INDEX_TYPE_2_BIT) { + (*count2)++; + } else if (idxType == INDEX_TYPE_4_BIT) { + (*count4)++; + } else if (idxType == INDEX_TYPE_0_OR_8_BIT) { + if (blockIndices[i] & INDEX_TYPE_0_BIT_FLAG) { + (*count0)++; + } else { + (*count8)++; + } + } + } + return allocatedSize; } -int CompressedTileStorage::getHighestNonEmptyY() -{ - unsigned short *blockIndices = (unsigned short *)indicesAndData; - unsigned int highestYBlock = 0; - bool found = false; +int CompressedTileStorage::getHighestNonEmptyY() { + unsigned short* blockIndices = (unsigned short*)indicesAndData; + unsigned int highestYBlock = 0; + bool found = false; - // The 512 "blocks" (4x4x4 tiles) are arranged in 32 layers - for(int yBlock = 31; yBlock >= 0; --yBlock) - { - // Each layer has 16 blocks - for(unsigned int xzBlock = 0; xzBlock < 16; ++xzBlock) - { - // Blocks are ordered in columns - int index = yBlock + (xzBlock * 32); + // The 512 "blocks" (4x4x4 tiles) are arranged in 32 layers + for (int yBlock = 31; yBlock >= 0; --yBlock) { + // Each layer has 16 blocks + for (unsigned int xzBlock = 0; xzBlock < 16; ++xzBlock) { + // Blocks are ordered in columns + int index = yBlock + (xzBlock * 32); - int indexType = blockIndices[index] & INDEX_TYPE_MASK; - if( indexType == INDEX_TYPE_0_OR_8_BIT && blockIndices[index] & INDEX_TYPE_0_BIT_FLAG ) - { - int val = ( blockIndices[index] >> INDEX_TILE_SHIFT ) & INDEX_TILE_MASK; - if(val != 0) - { - highestYBlock = yBlock; - found = true; - break; - } - } - else - { - highestYBlock = yBlock; - found = true; - break; - } - } + int indexType = blockIndices[index] & INDEX_TYPE_MASK; + if (indexType == INDEX_TYPE_0_OR_8_BIT && + blockIndices[index] & INDEX_TYPE_0_BIT_FLAG) { + int val = + (blockIndices[index] >> INDEX_TILE_SHIFT) & INDEX_TILE_MASK; + if (val != 0) { + highestYBlock = yBlock; + found = true; + break; + } + } else { + highestYBlock = yBlock; + found = true; + break; + } + } - if(found) break; - } - - int highestNonEmptyY = -1; - if(found) - { - // Multiply by the number of vertical tiles in a block, and then add that again to be at the top of the block - highestNonEmptyY = (highestYBlock * 4) + 4; - } - return highestNonEmptyY; + if (found) break; + } + + int highestNonEmptyY = -1; + if (found) { + // Multiply by the number of vertical tiles in a block, and then add + // that again to be at the top of the block + highestNonEmptyY = (highestYBlock * 4) + 4; + } + return highestNonEmptyY; } -void CompressedTileStorage::write(DataOutputStream *dos) -{ - dos->writeInt(allocatedSize); - if(indicesAndData) - { - if(LOCALSYTEM_ENDIAN == BIGENDIAN) - { - // The first 1024 bytes are an array of shorts, so we need to reverse the endianness - byteArray indicesCopy(1024); - memcpy(indicesCopy.data, indicesAndData, 1024); - reverseIndices(indicesCopy.data); - dos->write(indicesCopy); - delete [] indicesCopy.data; +void CompressedTileStorage::write(DataOutputStream* dos) { + dos->writeInt(allocatedSize); + if (indicesAndData) { + if (LOCALSYTEM_ENDIAN == BIGENDIAN) { + // The first 1024 bytes are an array of shorts, so we need to + // reverse the endianness + byteArray indicesCopy(1024); + memcpy(indicesCopy.data, indicesAndData, 1024); + reverseIndices(indicesCopy.data); + dos->write(indicesCopy); + delete[] indicesCopy.data; - // Write the rest of the data - if(allocatedSize > 1024) - { - byteArray dataWrapper(indicesAndData + 1024, allocatedSize - 1024); - dos->write(dataWrapper); - } - } - else - { - byteArray wrapper(indicesAndData, allocatedSize); - dos->write(wrapper); - } - } + // Write the rest of the data + if (allocatedSize > 1024) { + byteArray dataWrapper(indicesAndData + 1024, + allocatedSize - 1024); + dos->write(dataWrapper); + } + } else { + byteArray wrapper(indicesAndData, allocatedSize); + dos->write(wrapper); + } + } } -void CompressedTileStorage::read(DataInputStream *dis) -{ - allocatedSize = dis->readInt(); - if(allocatedSize > 0) - { - // This delete should be safe to do in a non-thread safe way as the chunk is fully read before any external reference is available to it from another thread - if( indicesAndData ) - { - XPhysicalFree(indicesAndData); - } - indicesAndData = (unsigned char *)XPhysicalAlloc(allocatedSize, MAXULONG_PTR, 4096, PAGE_READWRITE); +void CompressedTileStorage::read(DataInputStream* dis) { + allocatedSize = dis->readInt(); + if (allocatedSize > 0) { + // This delete should be safe to do in a non-thread safe way as the + // chunk is fully read before any external reference is available to it + // from another thread + if (indicesAndData) { + XPhysicalFree(indicesAndData); + } + indicesAndData = (unsigned char*)XPhysicalAlloc( + allocatedSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - byteArray wrapper(indicesAndData, allocatedSize); - dis->readFully(wrapper); - if(LOCALSYTEM_ENDIAN == BIGENDIAN) - { - reverseIndices(indicesAndData); - } + byteArray wrapper(indicesAndData, allocatedSize); + dis->readFully(wrapper); + if (LOCALSYTEM_ENDIAN == BIGENDIAN) { + reverseIndices(indicesAndData); + } - compress(); - } + compress(); + } } -void CompressedTileStorage::reverseIndices(unsigned char *indices) -{ - unsigned short *blockIndices = (unsigned short *)indices; - for( int i = 0; i < 512; i++ ) - { - System::ReverseUSHORT(&blockIndices[i]); - } +void CompressedTileStorage::reverseIndices(unsigned char* indices) { + unsigned short* blockIndices = (unsigned short*)indices; + for (int i = 0; i < 512; i++) { + System::ReverseUSHORT(&blockIndices[i]); + } } diff --git a/Minecraft.World/Level/Storage/CompressedTileStorage.h b/Minecraft.World/Level/Storage/CompressedTileStorage.h index b0e694dd1..9f8ac8ffc 100644 --- a/Minecraft.World/Level/Storage/CompressedTileStorage.h +++ b/Minecraft.World/Level/Storage/CompressedTileStorage.h @@ -1,22 +1,36 @@ #pragma once #ifndef __linux__ #include "../../Platform/x64headers/xmcore.h" -#endif // __linux__ +#endif // __linux__ -// This class is used for the compressed storage of tile data. Unlike the SparseLightingStorage class, data is split into 512 blocks of 4x4x4 tiles. Then within each block, the -// data is compressed as described below, with a selection of bits per tile available, in a method similar to a palettised image. +// This class is used for the compressed storage of tile data. Unlike the +// SparseLightingStorage class, data is split into 512 blocks of 4x4x4 tiles. +// Then within each block, the data is compressed as described below, with a +// selection of bits per tile available, in a method similar to a palettised +// image. -// There are two elements to the storage... an index array (fixed size), and the actual storage required... +// There are two elements to the storage... an index array (fixed size), and the +// actual storage required... // The index: -// (1) Each index takes up 2 bytes, one for each 4x4x4 block ie 512 X 2 = 1024 bytes in total -// (2) The type of index is determined by the least significant 2 bits, the other 14 bits represent an offset for the data, stored divided by 2 -// 0 - the data for this block is represented at 1 bit per tile. Data pointed to is 2 bytes describing the 2 possible tiles stored in this block, followed by 32 bytes of data (total 34 bytes) -// 1 - the data for this block is represented at 2 bit per tile. Data pointed to is 4 bytes describing the 4 possible tiles stored in this block, followed by 64 bytes of data (total 68 bytes) -// 2 - the data for this block is represented at 4 bit per tile. Data pointed to is 16 bytes describing the 16 possible tiles stored in this block, followed by 128 bytes of data (total 144 bytes) -// 3 - if bit 2 is 0, then this block is represented at 8 bits per tile. Data pointed to is 64 bytes, offset must be a multiple of 4 (since bit 2 can also be thought of as being -// the low bit of the offset (divided by 2 as in the other cases), and is zero) -// - if bit 2 is 1, then this block is represented at 0 bits per tile. The upper 8 bits of the index store the tile value that is used by the entire block. +// (1) Each index takes up 2 bytes, one for each 4x4x4 block ie 512 X 2 = 1024 +// bytes in total (2) The type of index is determined by the least significant 2 +// bits, the other 14 bits represent an offset for the data, stored divided by 2 +// 0 - the data for this block is represented at 1 bit per +//tile. Data pointed to is 2 bytes describing the 2 possible tiles stored in +//this block, followed by 32 bytes of data (total 34 bytes) 1 - the data for +//this block is represented at 2 bit per tile. Data pointed to is 4 bytes +//describing the 4 possible tiles stored in this block, followed by 64 bytes of +//data (total 68 bytes) 2 - the data for this block is represented at 4 bit per +//tile. Data pointed to is 16 bytes describing the 16 possible tiles stored in +//this block, followed by 128 bytes of data (total 144 bytes) 3 - if bit 2 is 0, +//then this block is represented at 8 bits per tile. Data pointed to is 64 +//bytes, offset must be a multiple of 4 (since bit 2 can also be thought of as +//being the low bit of the offset (divided by 2 as in the other cases), and is +//zero) +// - if bit 2 is 1, then this block is represented at 0 +//bits per tile. The upper 8 bits of the index store the tile value that is used +//by the entire block. // So: // oooooooooooooo00 - 1 bit per tile, offset oooooooooooooo0 // oooooooooooooo01 - 2 bits per tile, offset oooooooooooooo0 @@ -25,89 +39,135 @@ // tttttttt-----111 - 0 bits per tile - tile is tttttttt // Some notes on the logic of all of this... -// (1) Large numbers of blocks in the world really don't need to be stored at a full 8 bits per tile. -// In a worst-case scenario, all planes would be 256 bytes and we'd have to store offsets of up to 32704 ( 64 x 511). This would require 15 bits per offset to store, but since in all cases -// the data can be stored with a 2 byte alignment, we can store offsets divided by 2, freeing up 2 bits to store the type of index for each plane. This allows us to encode 4 types, but we really have -// 5 types (0, 1, 2, 4 or 8 bits per tile). Since the 8-bit per tile planes are likely to be very rare, we can free up an extra bit in those by making their offset 4-byte aligned, and -// then use the extra bit to determine whether its a 0 or 8-bit per tile index. In the 0 bit case, we can use the bits used for the offset to store the actual tile value represented throughout the plane. -// (2) The compression is done per 4x4x4 block rather than planes like the lighting, as that gives many more regions that have a small number of tile types than per plane, and can therefore -// be compressed using less bits per tile. This is at the expense of a larger index, and more overhead from storing the tile types in each block (since there are more blocks than planes). However -// on balance this still was found to give much better compression - around 12.5% vs 19% by doing things per plane. -// (3) Another compromise is being made on how the memory is allocated. This is all currently done with physical allocations to bypass the general heap manager, in particular to allow the freeing -// of memory to actually free whole memory pages cleanly rather than leaving them as managed by the heap manager. The downside to this is that all storage is done in whole 4K pages. Annoyingly, -// a lot of our compressed chunks are just on the edge of fitting in 4K, so an awful lot of them end up being 8K when they are just a small amount over. However, in testing absolutely no chunks -// were seen that got close to going over 8K compressed, so doing things this way then we at least know that we are reliably getting 25% compression, and freeing things up cleanly. -// Note: see the comments on the getIndex and getBlockAndTile for an explanation of how the blocks themselves are organised in terms of mapping a chunk-wide x/y/z into a block and tile index. +// (1) Large numbers of blocks in the world really don't need to be stored at a +// full 8 bits per tile. In a worst-case scenario, all planes would be 256 bytes +// and we'd have to store offsets of up to 32704 ( 64 x 511). This would require +// 15 bits per offset to store, but since in all cases the data can be stored +// with a 2 byte alignment, we can store offsets divided by 2, freeing up 2 bits +// to store the type of index for each plane. This allows us to encode 4 types, +// but we really have 5 types (0, 1, 2, 4 or 8 bits per tile). Since the 8-bit +// per tile planes are likely to be very rare, we can free up an extra bit in +// those by making their offset 4-byte aligned, and then use the extra bit to +// determine whether its a 0 or 8-bit per tile index. In the 0 bit case, we can +// use the bits used for the offset to store the actual tile value represented +// throughout the plane. (2) The compression is done per 4x4x4 block rather than +// planes like the lighting, as that gives many more regions that have a small +// number of tile types than per plane, and can therefore be compressed using +// less bits per tile. This is at the expense of a larger index, and more +// overhead from storing the tile types in each block (since there are more +// blocks than planes). However on balance this still was found to give much +// better compression - around 12.5% vs 19% by doing things per plane. (3) +// Another compromise is being made on how the memory is allocated. This is all +// currently done with physical allocations to bypass the general heap manager, +// in particular to allow the freeing of memory to actually free whole memory +// pages cleanly rather than leaving them as managed by the heap manager. The +// downside to this is that all storage is done in whole 4K pages. Annoyingly, +// a lot of our compressed chunks are just on the edge of fitting in 4K, so an +// awful lot of them end up being 8K when they are just a small amount over. +// However, in testing absolutely no chunks were seen that got close to going +// over 8K compressed, so doing things this way then we at least know that we +// are reliably getting 25% compression, and freeing things up cleanly. Note: +// see the comments on the getIndex and getBlockAndTile for an explanation of +// how the blocks themselves are organised in terms of mapping a chunk-wide +// x/y/z into a block and tile index. -//#define BLOCK_COMPRESSION_STATS +// #define BLOCK_COMPRESSION_STATS class TileCompressData_SPU; -class CompressedTileStorage -{ - friend class TileCompressData_SPU; +class CompressedTileStorage { + friend class TileCompressData_SPU; + private: - unsigned char *indicesAndData; + unsigned char* indicesAndData; + public: - int allocatedSize; + int allocatedSize; + private: + static const int INDEX_OFFSET_MASK = 0x7ffe; + static const int INDEX_OFFSET_SHIFT = 1; + static const int INDEX_TILE_MASK = 0x00ff; + static const int INDEX_TILE_SHIFT = 8; + static const int INDEX_TYPE_MASK = 0x0003; + static const int INDEX_TYPE_1_BIT = 0x0000; + static const int INDEX_TYPE_2_BIT = 0x0001; + static const int INDEX_TYPE_4_BIT = 0x0002; + static const int INDEX_TYPE_0_OR_8_BIT = 0x0003; + static const int INDEX_TYPE_0_BIT_FLAG = 0x0004; - static const int INDEX_OFFSET_MASK = 0x7ffe; - static const int INDEX_OFFSET_SHIFT = 1; - static const int INDEX_TILE_MASK = 0x00ff; - static const int INDEX_TILE_SHIFT = 8; - static const int INDEX_TYPE_MASK = 0x0003; - static const int INDEX_TYPE_1_BIT = 0x0000; - static const int INDEX_TYPE_2_BIT = 0x0001; - static const int INDEX_TYPE_4_BIT = 0x0002; - static const int INDEX_TYPE_0_OR_8_BIT = 0x0003; - static const int INDEX_TYPE_0_BIT_FLAG = 0x0004; - - static const unsigned int MM_PHYSICAL_4KB_BASE = 0xE0000000; // Start of where 4KB page sized physical allocations are made + static const unsigned int MM_PHYSICAL_4KB_BASE = + 0xE0000000; // Start of where 4KB page sized physical allocations are + // made public: - CompressedTileStorage(); - CompressedTileStorage(CompressedTileStorage *copyFrom); // ctor with deep copy - CompressedTileStorage(byteArray dataIn, unsigned int initOffset); // Construct with data in passed in array of length 32768 (128 x 16 x 16) - CompressedTileStorage(bool isEmpty); - ~CompressedTileStorage(); - bool isSameAs(CompressedTileStorage *other); - bool isRenderChunkEmpty(int y); // Determine if 16x16x16 render-sized chunk is actually empty + CompressedTileStorage(); + CompressedTileStorage( + CompressedTileStorage* copyFrom); // ctor with deep copy + CompressedTileStorage( + byteArray dataIn, + unsigned int initOffset); // Construct with data in passed in array of + // length 32768 (128 x 16 x 16) + CompressedTileStorage(bool isEmpty); + ~CompressedTileStorage(); + bool isSameAs(CompressedTileStorage* other); + bool isRenderChunkEmpty( + int y); // Determine if 16x16x16 render-sized chunk is actually empty private: - inline static int getIndex(int block, int tile); - inline static void getBlockAndTile(int *block, int *tile, int x, int y, int z); - inline static void getBlock(int *block, int x, int y, int z); + inline static int getIndex(int block, int tile); + inline static void getBlockAndTile(int* block, int* tile, int x, int y, + int z); + inline static void getBlock(int* block, int x, int y, int z); + public: - void setData(byteArray dataIn, unsigned int inOffset); // Set all tile values from a data array of length 32768 (128 x 16 x 16). - void getData(byteArray retArray, unsigned int retOffset); // Gets all tile values into an array of length 32768. - int get(int x, int y, int z); // Get an individual tile value - void set(int x, int y, int z, int val); // Set an individual tile value - typedef void (*tileUpdatedCallback)(int x, int y , int z, void *param, int yparam); - int setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset, tileUpdatedCallback callback, void *param, int yparam); // Sets a region of tile values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer - bool testSetDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset); // Tests whether setting data would actually change anything - int getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset); // Updates the data at offset position dataInOut with a region of tile information - external ordering compatible with java DataLayer + void setData( + byteArray dataIn, + unsigned int inOffset); // Set all tile values from a data array of + // length 32768 (128 x 16 x 16). + void getData(byteArray retArray, + unsigned int retOffset); // Gets all tile values into an array + // of length 32768. + int get(int x, int y, int z); // Get an individual tile value + void set(int x, int y, int z, int val); // Set an individual tile value + typedef void (*tileUpdatedCallback)(int x, int y, int z, void* param, + int yparam); + int setDataRegion( + byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, + int offset, tileUpdatedCallback callback, void* param, + int yparam); // Sets a region of tile values with the data at offset + // position in the array dataIn - external ordering + // compatible with java DataLayer + bool testSetDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, + int y1, int z1, + int offset); // Tests whether setting data would + // actually change anything + int getDataRegion( + byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, + int offset); // Updates the data at offset position dataInOut with a + // region of tile information - external ordering + // compatible with java DataLayer - static void staticCtor(); + static void staticCtor(); - void compress(int upgradeBlock = -1); + void compress(int upgradeBlock = -1); #ifdef __PS3__ - void compress_SPU(int upgradeBlock = -1); + void compress_SPU(int upgradeBlock = -1); #endif public: - void queueForDelete(unsigned char *data); + void queueForDelete(unsigned char* data); - static void tick(); - static int deleteQueueIndex; - static XLockFreeStack deleteQueue[3]; + static void tick(); + static int deleteQueueIndex; + static XLockFreeStack deleteQueue[3]; - static unsigned char compressBuffer[32768 + 256]; + static unsigned char compressBuffer[32768 + 256]; - static CRITICAL_SECTION cs_write; + static CRITICAL_SECTION cs_write; - int getAllocatedSize(int *count0, int *count1, int *count2, int *count4, int *count8); - int getHighestNonEmptyY(); - bool isCompressed(); + int getAllocatedSize(int* count0, int* count1, int* count2, int* count4, + int* count8); + int getHighestNonEmptyY(); + bool isCompressed(); - void write(DataOutputStream *dos); - void read(DataInputStream *dis); - void reverseIndices(unsigned char *indices); + void write(DataOutputStream* dos); + void read(DataInputStream* dis); + void reverseIndices(unsigned char* indices); }; - diff --git a/Minecraft.World/Level/Storage/DataLayer.cpp b/Minecraft.World/Level/Storage/DataLayer.cpp index ce915666c..c8e2b264a 100644 --- a/Minecraft.World/Level/Storage/DataLayer.cpp +++ b/Minecraft.World/Level/Storage/DataLayer.cpp @@ -1,62 +1,48 @@ #include "../../Platform/stdafx.h" #include "DataLayer.h" -DataLayer::DataLayer(int length, int depthBits) : depthBits(depthBits), depthBitsPlusFour(depthBits + 4) -{ - data = byteArray(length >> 1); +DataLayer::DataLayer(int length, int depthBits) + : depthBits(depthBits), depthBitsPlusFour(depthBits + 4) { + data = byteArray(length >> 1); } -DataLayer::DataLayer(byteArray data, int depthBits) : depthBits(depthBits), depthBitsPlusFour(depthBits + 4) -{ - this->data = data; +DataLayer::DataLayer(byteArray data, int depthBits) + : depthBits(depthBits), depthBitsPlusFour(depthBits + 4) { + this->data = data; } -DataLayer::~DataLayer() -{ - delete[] data.data; -} +DataLayer::~DataLayer() { delete[] data.data; } -int DataLayer::get(int x, int y, int z) -{ +int DataLayer::get(int x, int y, int z) { int pos = (x << depthBitsPlusFour | z << depthBits | y); int slot = pos >> 1; int part = pos & 1; - if (part == 0) - { + if (part == 0) { return data[slot] & 0xf; - } else - { + } else { return (data[slot] >> 4) & 0xf; } } -void DataLayer::set(int x, int y, int z, int val) -{ +void DataLayer::set(int x, int y, int z, int val) { int pos = (x << depthBitsPlusFour | z << depthBits | y); int slot = pos >> 1; int part = pos & 1; - if (part == 0) - { - data[slot] = (uint8_t) ((data[slot] & 0xf0) | (val & 0xf)); - } else - { - data[slot] = (uint8_t) ((data[slot] & 0x0f) | ((val & 0xf) << 4)); + if (part == 0) { + data[slot] = (uint8_t)((data[slot] & 0xf0) | (val & 0xf)); + } else { + data[slot] = (uint8_t)((data[slot] & 0x0f) | ((val & 0xf) << 4)); } } -bool DataLayer::isValid() -{ - return data.data != NULL; -} +bool DataLayer::isValid() { return data.data != NULL; } -void DataLayer::setAll(int br) -{ - uint8_t val = (uint8_t) (br & (br << 4)); - for (unsigned int i = 0; i < data.length; i++) - { +void DataLayer::setAll(int br) { + uint8_t val = (uint8_t)(br & (br << 4)); + for (unsigned int i = 0; i < data.length; i++) { data[i] = val; } } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/DataLayer.h b/Minecraft.World/Level/Storage/DataLayer.h index 798215e68..f6e2ed9bf 100644 --- a/Minecraft.World/Level/Storage/DataLayer.h +++ b/Minecraft.World/Level/Storage/DataLayer.h @@ -1,18 +1,17 @@ #pragma once -class DataLayer -{ +class DataLayer { public: byteArray data; private: - const int depthBits; - const int depthBitsPlusFour; + const int depthBits; + const int depthBitsPlusFour; public: DataLayer(int length, int depthBits); DataLayer(byteArray data, int depthBits); - ~DataLayer(); + ~DataLayer(); int get(int x, int y, int z); diff --git a/Minecraft.World/Level/Storage/DirectoryLevelStorage.cpp b/Minecraft.World/Level/Storage/DirectoryLevelStorage.cpp index eee1b4068..7ce34e75d 100644 --- a/Minecraft.World/Level/Storage/DirectoryLevelStorage.cpp +++ b/Minecraft.World/Level/Storage/DirectoryLevelStorage.cpp @@ -14,819 +14,801 @@ const std::wstring DirectoryLevelStorage::sc_szPlayerDir(L"players/"); -_MapDataMappings::_MapDataMappings() -{ +_MapDataMappings::_MapDataMappings() { #ifndef _DURANGO - ZeroMemory(xuids,sizeof(PlayerUID)*MAXIMUM_MAP_SAVE_DATA); + ZeroMemory(xuids, sizeof(PlayerUID) * MAXIMUM_MAP_SAVE_DATA); #endif - ZeroMemory(dimensions,sizeof(std::uint8_t)*(MAXIMUM_MAP_SAVE_DATA/4)); + ZeroMemory(dimensions, sizeof(std::uint8_t) * (MAXIMUM_MAP_SAVE_DATA / 4)); } -int _MapDataMappings::getDimension(int id) -{ - int offset = (2*(id%4)); - int val = (dimensions[id>>2] & (3 << offset))>>offset; +int _MapDataMappings::getDimension(int id) { + int offset = (2 * (id % 4)); + int val = (dimensions[id >> 2] & (3 << offset)) >> offset; - int returnVal=0; + int returnVal = 0; - switch(val) - { - case 0: - returnVal = 0; // Overworld - break; - case 1: - returnVal = -1; // Nether - break; - case 2: - returnVal = 1; // End - break; - default: + switch (val) { + case 0: + returnVal = 0; // Overworld + break; + case 1: + returnVal = -1; // Nether + break; + case 2: + returnVal = 1; // End + break; + default: #ifndef _CONTENT_PACKAGE - printf("Read invalid dimension from MapDataMapping\n"); - __debugbreak(); + printf("Read invalid dimension from MapDataMapping\n"); + __debugbreak(); #endif - break; - } - return returnVal; + break; + } + return returnVal; } -void _MapDataMappings::setMapping(int id, PlayerUID xuid, int dimension) -{ - xuids[id] = xuid; +void _MapDataMappings::setMapping(int id, PlayerUID xuid, int dimension) { + xuids[id] = xuid; - int offset = (2*(id%4)); + int offset = (2 * (id % 4)); - // Reset it first - dimensions[id>>2] &= ~( 2 << offset ); - switch(dimension) - { - case 0: // Overworld - //dimensions[id>>2] &= ~( 2 << offset ); - break; - case -1: // Nether - dimensions[id>>2] |= ( 1 << offset ); - break; - case 1: // End - dimensions[id>>2] |= ( 2 << offset ); - break; - default: + // Reset it first + dimensions[id >> 2] &= ~(2 << offset); + switch (dimension) { + case 0: // Overworld + // dimensions[id>>2] &= ~( 2 << offset ); + break; + case -1: // Nether + dimensions[id >> 2] |= (1 << offset); + break; + case 1: // End + dimensions[id >> 2] |= (2 << offset); + break; + default: #ifndef _CONTENT_PACKAGE - printf("Trinyg to set a MapDataMapping for an invalid dimension.\n"); - __debugbreak(); + printf( + "Trinyg to set a MapDataMapping for an invalid dimension.\n"); + __debugbreak(); #endif - break; - } + break; + } } // Old version the only used 1 bit for dimension indexing -_MapDataMappings_old::_MapDataMappings_old() -{ +_MapDataMappings_old::_MapDataMappings_old() { #ifndef _DURANGO - ZeroMemory(xuids,sizeof(PlayerUID)*MAXIMUM_MAP_SAVE_DATA); + ZeroMemory(xuids, sizeof(PlayerUID) * MAXIMUM_MAP_SAVE_DATA); #endif - ZeroMemory(dimensions,sizeof(std::uint8_t)*(MAXIMUM_MAP_SAVE_DATA/8)); + ZeroMemory(dimensions, sizeof(std::uint8_t) * (MAXIMUM_MAP_SAVE_DATA / 8)); } -int _MapDataMappings_old::getDimension(int id) -{ - return dimensions[id>>3] & (128 >> (id%8) ) ? -1 : 0; +int _MapDataMappings_old::getDimension(int id) { + return dimensions[id >> 3] & (128 >> (id % 8)) ? -1 : 0; } -void _MapDataMappings_old::setMapping(int id, PlayerUID xuid, int dimension) -{ - xuids[id] = xuid; - if( dimension == 0 ) - { - dimensions[id>>3] &= ~( 128 >> (id%8) ); - } - else - { - dimensions[id>>3] |= ( 128 >> (id%8) ); - } +void _MapDataMappings_old::setMapping(int id, PlayerUID xuid, int dimension) { + xuids[id] = xuid; + if (dimension == 0) { + dimensions[id >> 3] &= ~(128 >> (id % 8)); + } else { + dimensions[id >> 3] |= (128 >> (id % 8)); + } } #ifdef _LARGE_WORLDS -void DirectoryLevelStorage::PlayerMappings::addMapping(int id, int centreX, int centreZ, int dimension, int scale) -{ - __int64 index = ( ((__int64)(centreZ & 0x1FFFFFFF)) << 34) | ( ((__int64)(centreX & 0x1FFFFFFF)) << 5) | ( (scale & 0x7) << 2) | (dimension & 0x3); - m_mappings[index] = id; - //app.DebugPrintf("Adding mapping: %d - (%d,%d)/%d/%d [%I64d - 0x%016llx]\n", id, centreX, centreZ, dimension, scale, index, index); +void DirectoryLevelStorage::PlayerMappings::addMapping(int id, int centreX, + int centreZ, + int dimension, + int scale) { + __int64 index = (((__int64)(centreZ & 0x1FFFFFFF)) << 34) | + (((__int64)(centreX & 0x1FFFFFFF)) << 5) | + ((scale & 0x7) << 2) | (dimension & 0x3); + m_mappings[index] = id; + // app.DebugPrintf("Adding mapping: %d - (%d,%d)/%d/%d [%I64d - + // 0x%016llx]\n", id, centreX, centreZ, dimension, scale, index, index); } -bool DirectoryLevelStorage::PlayerMappings::getMapping(int &id, int centreX, int centreZ, int dimension, int scale) -{ - //__int64 zMasked = centreZ & 0x1FFFFFFF; - //__int64 xMasked = centreX & 0x1FFFFFFF; - //__int64 zShifted = zMasked << 34; - //__int64 xShifted = xMasked << 5; - //app.DebugPrintf("xShifted = %d (0x%016x), zShifted = %I64d (0x%016llx)\n", xShifted, xShifted, zShifted, zShifted); - __int64 index = ( ((__int64)(centreZ & 0x1FFFFFFF)) << 34) | ( ((__int64)(centreX & 0x1FFFFFFF)) << 5) | ( (scale & 0x7) << 2) | (dimension & 0x3); - AUTO_VAR(it,m_mappings.find(index)); - if(it != m_mappings.end()) - { - id = it->second; - //app.DebugPrintf("Found mapping: %d - (%d,%d)/%d/%d [%I64d - 0x%016llx]\n", id, centreX, centreZ, dimension, scale, index, index); - return true; - } - else - { - //app.DebugPrintf("Failed to find mapping: (%d,%d)/%d/%d [%I64d - 0x%016llx]\n", centreX, centreZ, dimension, scale, index, index); - return false; - } +bool DirectoryLevelStorage::PlayerMappings::getMapping(int& id, int centreX, + int centreZ, + int dimension, + int scale) { + //__int64 zMasked = centreZ & 0x1FFFFFFF; + //__int64 xMasked = centreX & 0x1FFFFFFF; + //__int64 zShifted = zMasked << 34; + //__int64 xShifted = xMasked << 5; + // app.DebugPrintf("xShifted = %d (0x%016x), zShifted = %I64d + // (0x%016llx)\n", xShifted, xShifted, zShifted, zShifted); + __int64 index = (((__int64)(centreZ & 0x1FFFFFFF)) << 34) | + (((__int64)(centreX & 0x1FFFFFFF)) << 5) | + ((scale & 0x7) << 2) | (dimension & 0x3); + AUTO_VAR(it, m_mappings.find(index)); + if (it != m_mappings.end()) { + id = it->second; + // app.DebugPrintf("Found mapping: %d - (%d,%d)/%d/%d [%I64d - + // 0x%016llx]\n", id, centreX, centreZ, dimension, scale, index, index); + return true; + } else { + // app.DebugPrintf("Failed to find mapping: (%d,%d)/%d/%d [%I64d - + // 0x%016llx]\n", centreX, centreZ, dimension, scale, index, index); + return false; + } } -void DirectoryLevelStorage::PlayerMappings::writeMappings(DataOutputStream *dos) -{ - dos->writeInt(m_mappings.size()); - for(AUTO_VAR(it, m_mappings.begin()); it != m_mappings.end(); ++it) - { - app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it->first, it->first, it->second); - dos->writeLong(it->first); - dos->writeInt(it->second); - } +void DirectoryLevelStorage::PlayerMappings::writeMappings( + DataOutputStream* dos) { + dos->writeInt(m_mappings.size()); + for (AUTO_VAR(it, m_mappings.begin()); it != m_mappings.end(); ++it) { + app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it->first, it->first, + it->second); + dos->writeLong(it->first); + dos->writeInt(it->second); + } } -void DirectoryLevelStorage::PlayerMappings::readMappings(DataInputStream *dis) -{ - int count = dis->readInt(); - for(unsigned int i = 0; i < count; ++i) - { - __int64 index = dis->readLong(); - int id = dis->readInt(); - m_mappings[index] = id; - app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", index, index, id); - } +void DirectoryLevelStorage::PlayerMappings::readMappings(DataInputStream* dis) { + int count = dis->readInt(); + for (unsigned int i = 0; i < count; ++i) { + __int64 index = dis->readLong(); + int id = dis->readInt(); + m_mappings[index] = id; + app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", index, index, id); + } } #endif -DirectoryLevelStorage::DirectoryLevelStorage(ConsoleSaveFile *saveFile, const File dir, const std::wstring& levelId, bool createPlayerDir) : sessionId( System::currentTimeMillis() ), - dir( L"" ), playerDir( sc_szPlayerDir ), dataDir( std::wstring(L"data/") ), levelId(levelId) -{ - m_saveFile = saveFile; - m_bHasLoadedMapDataMappings = false; +DirectoryLevelStorage::DirectoryLevelStorage(ConsoleSaveFile* saveFile, + const File dir, + const std::wstring& levelId, + bool createPlayerDir) + : sessionId(System::currentTimeMillis()), + dir(L""), + playerDir(sc_szPlayerDir), + dataDir(std::wstring(L"data/")), + levelId(levelId) { + m_saveFile = saveFile; + m_bHasLoadedMapDataMappings = false; #ifdef _LARGE_WORLDS - m_usedMappings = byteArray(MAXIMUM_MAP_SAVE_DATA/8); + m_usedMappings = byteArray(MAXIMUM_MAP_SAVE_DATA / 8); #endif } -DirectoryLevelStorage::~DirectoryLevelStorage() -{ - delete m_saveFile; +DirectoryLevelStorage::~DirectoryLevelStorage() { + delete m_saveFile; - for(AUTO_VAR(it,m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) - { - delete it->second; - } - -#ifdef _LARGE_WORLDS - delete m_usedMappings.data; -#endif -} - -void DirectoryLevelStorage::initiateSession() -{ - // 4J Jev, removed try/catch. - - File dataFile = File( dir, std::wstring(L"session.lock") ); - FileOutputStream fos = FileOutputStream(dataFile); - DataOutputStream dos = DataOutputStream(&fos); - dos.writeLong(sessionId); - dos.close(); - -} - -File DirectoryLevelStorage::getFolder() -{ - return dir; -} - -void DirectoryLevelStorage::checkSession() -{ - // 4J-PB - Not in the Xbox game - - /* - File dataFile = File( dir, std::wstring(L"session.lock")); - FileInputStream fis = FileInputStream(dataFile); - DataInputStream dis = DataInputStream(&fis); - dis.close(); - */ -} - -ChunkStorage *DirectoryLevelStorage::createChunkStorage(Dimension *dimension) -{ - // 4J Jev, removed try/catch. - - if (dynamic_cast(dimension) != NULL) - { - File dir2 = File(dir, LevelStorage::NETHER_FOLDER); - //dir2.mkdirs(); // 4J Removed - return new OldChunkStorage(dir2, true); - } - if (dynamic_cast(dimension) != NULL) - { - File dir2 = File(dir, LevelStorage::ENDER_FOLDER); - //dir2.mkdirs(); // 4J Removed - return new OldChunkStorage(dir2, true); - } - - return new OldChunkStorage(dir, true); -} - -LevelData *DirectoryLevelStorage::prepareLevel() -{ - // 4J Stu Added -#ifdef _LARGE_WORLDS - ConsoleSavePath mapFile = getDataFile(L"largeMapDataMappings"); -#else - ConsoleSavePath mapFile = getDataFile(L"mapDataMappings"); -#endif - if (!m_bHasLoadedMapDataMappings && !mapFile.getName().empty() && getSaveFile()->doesFileExist( mapFile )) - { - unsigned int NumberOfBytesRead; - FileEntry *fileEntry = getSaveFile()->createFile(mapFile); - -#ifdef __PS3__ - // 4J Stu - This version changed happened before initial release - if(getSaveFile()->getSaveVersion() < SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE) - { - // Delete the old file - if(fileEntry) getSaveFile()->deleteFile( fileEntry ); - - // Save a new, blank version - saveMapIdLookup(); - } - else -#elif defined(_DURANGO) - // 4J Stu - This version changed happened before initial release - if(getSaveFile()->getSaveVersion() < SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE) - { - // Delete the old file - if(fileEntry) getSaveFile()->deleteFile( fileEntry ); - - // Save a new, blank version - saveMapIdLookup(); - } - else -#endif - { - getSaveFile()->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); - -#ifdef _LARGE_WORLDS - byteArray data(fileEntry->getFileSize()); - getSaveFile()->readFile( fileEntry, data.data, fileEntry->getFileSize(), &NumberOfBytesRead); - assert( NumberOfBytesRead == fileEntry->getFileSize() ); - - ByteArrayInputStream bais(data); - DataInputStream dis(&bais); - int count = dis.readInt(); - app.DebugPrintf("Loading %d mappings\n", count); - for(unsigned int i = 0; i < count; ++i) - { - PlayerUID playerUid = dis.readPlayerUID(); -#if defined(_WINDOWS64) || defined(__linux__) - app.DebugPrintf(" -- %d\n", playerUid); -#else - #ifdef __linux__ - app.DebugPrintf(" -- %d\n", playerUid); - #else - app.DebugPrintf(" -- %ls\n", playerUid.toString().c_str()); - #endif -#endif - m_playerMappings[playerUid].readMappings(&dis); - } - dis.readFully(m_usedMappings); -#else - - if(getSaveFile()->getSaveVersion() < END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) - { - MapDataMappings_old oldMapDataMappings; - getSaveFile()->readFile( fileEntry, - &oldMapDataMappings, // data buffer - sizeof(MapDataMappings_old), // number of bytes to read - &NumberOfBytesRead // number of bytes read - ); - assert( NumberOfBytesRead == sizeof(MapDataMappings_old) ); - - for(unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) - { - m_saveableMapDataMappings.setMapping(i,oldMapDataMappings.xuids[i],oldMapDataMappings.getDimension(i)); - } - } - else - { - getSaveFile()->readFile( fileEntry, - &m_saveableMapDataMappings, // data buffer - sizeof(MapDataMappings), // number of bytes to read - &NumberOfBytesRead // number of bytes read - ); - assert( NumberOfBytesRead == sizeof(MapDataMappings) ); - } - - memcpy(&m_mapDataMappings,&m_saveableMapDataMappings,sizeof(MapDataMappings)); -#endif - - - // Write out our changes now - if(getSaveFile()->getSaveVersion() < END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) saveMapIdLookup(); - } - - m_bHasLoadedMapDataMappings = true; + for (AUTO_VAR(it, m_cachedSaveData.begin()); it != m_cachedSaveData.end(); + ++it) { + delete it->second; } - // 4J Jev, removed try/catch +#ifdef _LARGE_WORLDS + delete m_usedMappings.data; +#endif +} - ConsoleSavePath dataFile = ConsoleSavePath( std::wstring( L"level.dat" ) ); +void DirectoryLevelStorage::initiateSession() { + // 4J Jev, removed try/catch. - if ( m_saveFile->doesFileExist( dataFile ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, dataFile); - CompoundTag *root = NbtIo::readCompressed(&fis); - CompoundTag *tag = root->getCompound(L"Data"); - LevelData *ret = new LevelData(tag); - delete root; - return ret; - } + File dataFile = File(dir, std::wstring(L"session.lock")); + FileOutputStream fos = FileOutputStream(dataFile); + DataOutputStream dos = DataOutputStream(&fos); + dos.writeLong(sessionId); + dos.close(); +} + +File DirectoryLevelStorage::getFolder() { return dir; } + +void DirectoryLevelStorage::checkSession() { + // 4J-PB - Not in the Xbox game + + /* + File dataFile = File( dir, std::wstring(L"session.lock")); + FileInputStream fis = FileInputStream(dataFile); + DataInputStream dis = DataInputStream(&fis); + dis.close(); + */ +} + +ChunkStorage* DirectoryLevelStorage::createChunkStorage(Dimension* dimension) { + // 4J Jev, removed try/catch. + + if (dynamic_cast(dimension) != NULL) { + File dir2 = File(dir, LevelStorage::NETHER_FOLDER); + // dir2.mkdirs(); // 4J Removed + return new OldChunkStorage(dir2, true); + } + if (dynamic_cast(dimension) != NULL) { + File dir2 = File(dir, LevelStorage::ENDER_FOLDER); + // dir2.mkdirs(); // 4J Removed + return new OldChunkStorage(dir2, true); + } + + return new OldChunkStorage(dir, true); +} + +LevelData* DirectoryLevelStorage::prepareLevel() { + // 4J Stu Added +#ifdef _LARGE_WORLDS + ConsoleSavePath mapFile = getDataFile(L"largeMapDataMappings"); +#else + ConsoleSavePath mapFile = getDataFile(L"mapDataMappings"); +#endif + if (!m_bHasLoadedMapDataMappings && !mapFile.getName().empty() && + getSaveFile()->doesFileExist(mapFile)) { + unsigned int NumberOfBytesRead; + FileEntry* fileEntry = getSaveFile()->createFile(mapFile); + +#ifdef __PS3__ + // 4J Stu - This version changed happened before initial release + if (getSaveFile()->getSaveVersion() < + SAVE_FILE_VERSION_CHANGE_MAP_DATA_MAPPING_SIZE) { + // Delete the old file + if (fileEntry) getSaveFile()->deleteFile(fileEntry); + + // Save a new, blank version + saveMapIdLookup(); + } else +#elif defined(_DURANGO) + // 4J Stu - This version changed happened before initial release + if (getSaveFile()->getSaveVersion() < + SAVE_FILE_VERSION_DURANGO_CHANGE_MAP_DATA_MAPPING_SIZE) { + // Delete the old file + if (fileEntry) getSaveFile()->deleteFile(fileEntry); + + // Save a new, blank version + saveMapIdLookup(); + } else +#endif + { + getSaveFile()->setFilePointer(fileEntry, 0, + SaveFileSeekOrigin::Begin); + +#ifdef _LARGE_WORLDS + byteArray data(fileEntry->getFileSize()); + getSaveFile()->readFile(fileEntry, data.data, + fileEntry->getFileSize(), + &NumberOfBytesRead); + assert(NumberOfBytesRead == fileEntry->getFileSize()); + + ByteArrayInputStream bais(data); + DataInputStream dis(&bais); + int count = dis.readInt(); + app.DebugPrintf("Loading %d mappings\n", count); + for (unsigned int i = 0; i < count; ++i) { + PlayerUID playerUid = dis.readPlayerUID(); +#if defined(_WINDOWS64) || defined(__linux__) + app.DebugPrintf(" -- %d\n", playerUid); +#else +#ifdef __linux__ + app.DebugPrintf(" -- %d\n", playerUid); +#else + app.DebugPrintf(" -- %ls\n", playerUid.toString().c_str()); +#endif +#endif + m_playerMappings[playerUid].readMappings(&dis); + } + dis.readFully(m_usedMappings); +#else + + if (getSaveFile()->getSaveVersion() < + END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) { + MapDataMappings_old oldMapDataMappings; + getSaveFile()->readFile( + fileEntry, + &oldMapDataMappings, // data buffer + sizeof(MapDataMappings_old), // number of bytes to read + &NumberOfBytesRead // number of bytes read + ); + assert(NumberOfBytesRead == sizeof(MapDataMappings_old)); + + for (unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) { + m_saveableMapDataMappings.setMapping( + i, oldMapDataMappings.xuids[i], + oldMapDataMappings.getDimension(i)); + } + } else { + getSaveFile()->readFile( + fileEntry, + &m_saveableMapDataMappings, // data buffer + sizeof(MapDataMappings), // number of bytes to read + &NumberOfBytesRead // number of bytes read + ); + assert(NumberOfBytesRead == sizeof(MapDataMappings)); + } + + memcpy(&m_mapDataMappings, &m_saveableMapDataMappings, + sizeof(MapDataMappings)); +#endif + + // Write out our changes now + if (getSaveFile()->getSaveVersion() < + END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) + saveMapIdLookup(); + } + + m_bHasLoadedMapDataMappings = true; + } + + // 4J Jev, removed try/catch + + ConsoleSavePath dataFile = ConsoleSavePath(std::wstring(L"level.dat")); + + if (m_saveFile->doesFileExist(dataFile)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(m_saveFile, dataFile); + CompoundTag* root = NbtIo::readCompressed(&fis); + CompoundTag* tag = root->getCompound(L"Data"); + LevelData* ret = new LevelData(tag); + delete root; + return ret; + } return NULL; } -void DirectoryLevelStorage::saveLevelData(LevelData *levelData, std::vector > *players) -{ - // 4J Jev, removed try/catch +void DirectoryLevelStorage::saveLevelData( + LevelData* levelData, std::vector >* players) { + // 4J Jev, removed try/catch - CompoundTag *dataTag = levelData->createTag(players); + CompoundTag* dataTag = levelData->createTag(players); - CompoundTag *root = new CompoundTag(); - root->put(L"Data", dataTag); + CompoundTag* root = new CompoundTag(); + root->put(L"Data", dataTag); - ConsoleSavePath currentFile = ConsoleSavePath( std::wstring( L"level.dat" ) ); + ConsoleSavePath currentFile = ConsoleSavePath(std::wstring(L"level.dat")); - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, currentFile ); - NbtIo::writeCompressed(root, &fos); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, currentFile); + NbtIo::writeCompressed(root, &fos); - delete root; + delete root; } -void DirectoryLevelStorage::saveLevelData(LevelData *levelData) -{ - // 4J Jev, removed try/catch +void DirectoryLevelStorage::saveLevelData(LevelData* levelData) { + // 4J Jev, removed try/catch - CompoundTag *dataTag = levelData->createTag(); + CompoundTag* dataTag = levelData->createTag(); - CompoundTag *root = new CompoundTag(); - root->put(L"Data", dataTag); + CompoundTag* root = new CompoundTag(); + root->put(L"Data", dataTag); - ConsoleSavePath currentFile = ConsoleSavePath( std::wstring( L"level.dat" ) ); + ConsoleSavePath currentFile = ConsoleSavePath(std::wstring(L"level.dat")); - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, currentFile ); - NbtIo::writeCompressed(root, &fos); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, currentFile); + NbtIo::writeCompressed(root, &fos); - delete root; + delete root; } -void DirectoryLevelStorage::save(std::shared_ptr player) -{ - // 4J Jev, removed try/catch. - PlayerUID playerXuid = player->getXuid(); +void DirectoryLevelStorage::save(std::shared_ptr player) { + // 4J Jev, removed try/catch. + PlayerUID playerXuid = player->getXuid(); #if defined(__PS3__) || defined(__ORBIS__) - if( playerXuid != INVALID_XUID ) + if (playerXuid != INVALID_XUID) #else - if( playerXuid != INVALID_XUID && !player->isGuest() ) + if (playerXuid != INVALID_XUID && !player->isGuest()) #endif - { - CompoundTag *tag = new CompoundTag(); - player->saveWithoutId(tag); + { + CompoundTag* tag = new CompoundTag(); + player->saveWithoutId(tag); #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - ConsoleSavePath realFile = ConsoleSavePath( m_saveFile->getPlayerDataFilenameForSave(playerXuid).c_str() ); + ConsoleSavePath realFile = ConsoleSavePath( + m_saveFile->getPlayerDataFilenameForSave(playerXuid).c_str()); #elif defined(_DURANGO) - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + player->getXuid().toString() + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( + playerDir.getName() + player->getXuid().toString() + L".dat"); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( player->getXuid() ) + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( + playerDir.getName() + _toString(player->getXuid()) + L".dat"); #endif - // If saves are disabled (e.g. because we are writing the save buffer to disk) then cache this player data - if(StorageManager.GetSaveDisabled()) - { - ByteArrayOutputStream *bos = new ByteArrayOutputStream(); - NbtIo::writeCompressed(tag,bos); + // If saves are disabled (e.g. because we are writing the save buffer to + // disk) then cache this player data + if (StorageManager.GetSaveDisabled()) { + ByteArrayOutputStream* bos = new ByteArrayOutputStream(); + NbtIo::writeCompressed(tag, bos); - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); - if(it != m_cachedSaveData.end() ) - { - delete it->second; - } - m_cachedSaveData[realFile.getName()] = bos; - app.DebugPrintf("Cached saving of file %ls due to saves being disabled\n", realFile.getName().c_str() ); - } - else - { - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, realFile ); - NbtIo::writeCompressed(tag, &fos); - } - delete tag; - } - else if( playerXuid != INVALID_XUID ) - { - app.DebugPrintf("Not saving player as their XUID is a guest\n"); - dontSaveMapMappingForPlayer(playerXuid); - } + AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + if (it != m_cachedSaveData.end()) { + delete it->second; + } + m_cachedSaveData[realFile.getName()] = bos; + app.DebugPrintf( + "Cached saving of file %ls due to saves being disabled\n", + realFile.getName().c_str()); + } else { + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, realFile); + NbtIo::writeCompressed(tag, &fos); + } + delete tag; + } else if (playerXuid != INVALID_XUID) { + app.DebugPrintf("Not saving player as their XUID is a guest\n"); + dontSaveMapMappingForPlayer(playerXuid); + } } - // 4J Changed return val to bool to check if new player or loaded player -bool DirectoryLevelStorage::load(std::shared_ptr player) -{ - bool newPlayer = true; - CompoundTag *tag = loadPlayerDataTag( player->getXuid() ); - if (tag != NULL) - { - newPlayer = false; - player->load(tag); - delete tag; - } - return newPlayer; +// 4J Changed return val to bool to check if new player or loaded player +bool DirectoryLevelStorage::load(std::shared_ptr player) { + bool newPlayer = true; + CompoundTag* tag = loadPlayerDataTag(player->getXuid()); + if (tag != NULL) { + newPlayer = false; + player->load(tag); + delete tag; + } + return newPlayer; } -CompoundTag *DirectoryLevelStorage::loadPlayerDataTag(PlayerUID xuid) -{ - // 4J Jev, removed try/catch. +CompoundTag* DirectoryLevelStorage::loadPlayerDataTag(PlayerUID xuid) { + // 4J Jev, removed try/catch. #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - ConsoleSavePath realFile = ConsoleSavePath( m_saveFile->getPlayerDataFilenameForLoad(xuid).c_str() ); + ConsoleSavePath realFile = + ConsoleSavePath(m_saveFile->getPlayerDataFilenameForLoad(xuid).c_str()); #elif defined(_DURANGO) - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + xuid.toString() + L".dat" ); + ConsoleSavePath realFile = + ConsoleSavePath(playerDir.getName() + xuid.toString() + L".dat"); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( xuid ) + L".dat" ); + ConsoleSavePath realFile = + ConsoleSavePath(playerDir.getName() + _toString(xuid) + L".dat"); #endif - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); - if(it != m_cachedSaveData.end() ) - { - ByteArrayOutputStream *bos = it->second; - ByteArrayInputStream bis(bos->buf, 0, bos->size()); - CompoundTag *tag = NbtIo::readCompressed(&bis); - bis.reset(); - app.DebugPrintf("Loaded player data from cached file %ls\n", realFile.getName().c_str() ); - return tag; - } - else if ( m_saveFile->doesFileExist( realFile ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, realFile); - return NbtIo::readCompressed(&fis); - } - return NULL; + AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + if (it != m_cachedSaveData.end()) { + ByteArrayOutputStream* bos = it->second; + ByteArrayInputStream bis(bos->buf, 0, bos->size()); + CompoundTag* tag = NbtIo::readCompressed(&bis); + bis.reset(); + app.DebugPrintf("Loaded player data from cached file %ls\n", + realFile.getName().c_str()); + return tag; + } else if (m_saveFile->doesFileExist(realFile)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(m_saveFile, realFile); + return NbtIo::readCompressed(&fis); + } + return NULL; } // 4J Added function -void DirectoryLevelStorage::clearOldPlayerFiles() -{ - if(StorageManager.GetSaveDisabled() ) return; +void DirectoryLevelStorage::clearOldPlayerFiles() { + if (StorageManager.GetSaveDisabled()) return; #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - std::vector *playerFiles = m_saveFile->getValidPlayerDatFiles(); + std::vector* playerFiles = m_saveFile->getValidPlayerDatFiles(); #else - std::vector *playerFiles = m_saveFile->getFilesWithPrefix( playerDir.getName() ); + std::vector* playerFiles = + m_saveFile->getFilesWithPrefix(playerDir.getName()); #endif - if( playerFiles != NULL ) - { + if (playerFiles != NULL) { #ifndef _FINAL_BUILD - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<size(); ++i ) - { - FileEntry *file = playerFiles->at(i); - std::wstring xuidStr = replaceAll( replaceAll(file->data.filename,playerDir.getName(),L""),L".dat",L""); + if (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_DistributableSave)) { + for (unsigned int i = 0; i < playerFiles->size(); ++i) { + FileEntry* file = playerFiles->at(i); + std::wstring xuidStr = replaceAll( + replaceAll(file->data.filename, playerDir.getName(), L""), + L".dat", L""); #if defined(__PS3__) || defined(__ORBIS__) || defined(_DURANGO) - PlayerUID xuid(xuidStr); + PlayerUID xuid(xuidStr); #else - PlayerUID xuid = _fromString(xuidStr); + PlayerUID xuid = _fromString(xuidStr); #endif - deleteMapFilesForPlayer(xuid); - m_saveFile->deleteFile( playerFiles->at(i) ); - } - } - else + deleteMapFilesForPlayer(xuid); + m_saveFile->deleteFile(playerFiles->at(i)); + } + } else #endif - if( playerFiles->size() > MAX_PLAYER_DATA_SAVES ) - { - sort(playerFiles->begin(), playerFiles->end(), FileEntry::newestFirst ); + if (playerFiles->size() > MAX_PLAYER_DATA_SAVES) { + sort(playerFiles->begin(), playerFiles->end(), + FileEntry::newestFirst); - for(unsigned int i = MAX_PLAYER_DATA_SAVES; i < playerFiles->size(); ++i ) - { - FileEntry *file = playerFiles->at(i); - std::wstring xuidStr = replaceAll( replaceAll(file->data.filename,playerDir.getName(),L""),L".dat",L""); + for (unsigned int i = MAX_PLAYER_DATA_SAVES; + i < playerFiles->size(); ++i) { + FileEntry* file = playerFiles->at(i); + std::wstring xuidStr = replaceAll( + replaceAll(file->data.filename, playerDir.getName(), L""), + L".dat", L""); #if defined(__PS3__) || defined(__ORBIS__) || defined(_DURANGO) - PlayerUID xuid(xuidStr); + PlayerUID xuid(xuidStr); #else - PlayerUID xuid = _fromString(xuidStr); + PlayerUID xuid = _fromString(xuidStr); #endif - deleteMapFilesForPlayer(xuid); - m_saveFile->deleteFile( playerFiles->at(i) ); - } - } + deleteMapFilesForPlayer(xuid); + m_saveFile->deleteFile(playerFiles->at(i)); + } + } - delete playerFiles; - } + delete playerFiles; + } } -PlayerIO *DirectoryLevelStorage::getPlayerIO() -{ - return this; +PlayerIO* DirectoryLevelStorage::getPlayerIO() { return this; } + +void DirectoryLevelStorage::closeAll() {} + +ConsoleSavePath DirectoryLevelStorage::getDataFile(const std::wstring& id) { + return ConsoleSavePath(dataDir.getName() + id + L".dat"); } -void DirectoryLevelStorage::closeAll() -{ -} +std::wstring DirectoryLevelStorage::getLevelId() { return levelId; } -ConsoleSavePath DirectoryLevelStorage::getDataFile(const std::wstring& id) -{ - return ConsoleSavePath( dataDir.getName() + id + L".dat" ); -} - -std::wstring DirectoryLevelStorage::getLevelId() -{ - return levelId; -} - -void DirectoryLevelStorage::flushSaveFile(bool autosave) -{ +void DirectoryLevelStorage::flushSaveFile(bool autosave) { #ifndef _CONTENT_PACKAGE - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<doesFileExist(gameRulesFiles)) - { - FileEntry *fe = m_saveFile->createFile(gameRulesFiles); - m_saveFile->deleteFile( fe ); - } - } + if (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_DistributableSave)) { + // Delete gamerules files if it exists + ConsoleSavePath gameRulesFiles(GAME_RULE_SAVENAME); + if (m_saveFile->doesFileExist(gameRulesFiles)) { + FileEntry* fe = m_saveFile->createFile(gameRulesFiles); + m_saveFile->deleteFile(fe); + } + } #endif - m_saveFile->Flush(autosave); + m_saveFile->Flush(autosave); } // 4J Added -void DirectoryLevelStorage::resetNetherPlayerPositions() -{ - if(app.GetResetNether()) - { +void DirectoryLevelStorage::resetNetherPlayerPositions() { + if (app.GetResetNether()) { #if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) - std::vector *playerFiles = m_saveFile->getValidPlayerDatFiles(); + std::vector* playerFiles = + m_saveFile->getValidPlayerDatFiles(); #else - std::vector *playerFiles = m_saveFile->getFilesWithPrefix( playerDir.getName() ); + std::vector* playerFiles = + m_saveFile->getFilesWithPrefix(playerDir.getName()); #endif - if( playerFiles != NULL ) - { - for( AUTO_VAR(it, playerFiles->begin()); it != playerFiles->end(); ++it) - { - FileEntry * realFile = *it; - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, realFile); - CompoundTag *tag = NbtIo::readCompressed(&fis); - if (tag != NULL) - { - // If the player is in the nether, set their y position above the top of the nether - // This will force the player to be spawned in a valid position in the overworld when they are loaded - if(tag->contains(L"Dimension") && tag->getInt(L"Dimension") == LevelData::DIMENSION_NETHER && tag->contains(L"Pos")) - { - ListTag *pos = (ListTag *) tag->getList(L"Pos"); - pos->get(1)->data = DBL_MAX; + if (playerFiles != NULL) { + for (AUTO_VAR(it, playerFiles->begin()); it != playerFiles->end(); + ++it) { + FileEntry* realFile = *it; + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(m_saveFile, realFile); + CompoundTag* tag = NbtIo::readCompressed(&fis); + if (tag != NULL) { + // If the player is in the nether, set their y position + // above the top of the nether This will force the player to + // be spawned in a valid position in the overworld when they + // are loaded + if (tag->contains(L"Dimension") && + tag->getInt(L"Dimension") == + LevelData::DIMENSION_NETHER && + tag->contains(L"Pos")) { + ListTag* pos = + (ListTag*)tag->getList(L"Pos"); + pos->get(1)->data = DBL_MAX; - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, realFile ); - NbtIo::writeCompressed(tag, &fos); - } - delete tag; - } - } - delete playerFiles; - } - } + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, realFile); + NbtIo::writeCompressed(tag, &fos); + } + delete tag; + } + } + delete playerFiles; + } + } } -int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale) -{ - int mapId = -1; - bool foundMapping = false; +int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, + int centreXC, int centreZC, + int scale) { + int mapId = -1; + bool foundMapping = false; #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); - if(it != m_playerMappings.end()) - { - foundMapping = it->second.getMapping(mapId, centreXC, centreZC, dimension, scale); - } + AUTO_VAR(it, m_playerMappings.find(xuid)); + if (it != m_playerMappings.end()) { + foundMapping = + it->second.getMapping(mapId, centreXC, centreZC, dimension, scale); + } - if(!foundMapping) - { - for(unsigned int i = 0; i < m_usedMappings.length; ++i) - { - if(m_usedMappings[i] < 0xFF) - { - unsigned int offset = 0; - for(; offset < 8; ++offset) - { - if( !(m_usedMappings[i] & (1<= 0 && mapId < MAXIMUM_MAP_SAVE_DATA ) - { - m_mapDataMappings.setMapping(mapId, xuid, dimension); - m_saveableMapDataMappings.setMapping(mapId, xuid, dimension); + for (unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) { + if (m_mapDataMappings.xuids[i] == xuid && + m_mapDataMappings.getDimension(i) == dimension) { + foundMapping = true; + mapId = i; + break; + } + if (mapId < 0 && m_mapDataMappings.xuids[i] == INVALID_XUID) { + mapId = i; + } + } + if (!foundMapping && mapId >= 0 && mapId < MAXIMUM_MAP_SAVE_DATA) { + m_mapDataMappings.setMapping(mapId, xuid, dimension); + m_saveableMapDataMappings.setMapping(mapId, xuid, dimension); - // If we had an old map file for a mapping that is no longer valid, delete it - std::wstring id = std::wstring( L"map_" ) + _toString(mapId); - ConsoleSavePath file = getDataFile(id); + // If we had an old map file for a mapping that is no longer valid, + // delete it + std::wstring id = std::wstring(L"map_") + _toString(mapId); + ConsoleSavePath file = getDataFile(id); - if(m_saveFile->doesFileExist(file) ) - { - AUTO_VAR(it, find(m_mapFilesToDelete.begin(), m_mapFilesToDelete.end(), mapId)); - if(it != m_mapFilesToDelete.end()) m_mapFilesToDelete.erase(it); + if (m_saveFile->doesFileExist(file)) { + AUTO_VAR(it, find(m_mapFilesToDelete.begin(), + m_mapFilesToDelete.end(), mapId)); + if (it != m_mapFilesToDelete.end()) m_mapFilesToDelete.erase(it); - m_saveFile->deleteFile( m_saveFile->createFile(file) ); - } - } + m_saveFile->deleteFile(m_saveFile->createFile(file)); + } + } #endif - return mapId; + return mapId; } -void DirectoryLevelStorage::saveMapIdLookup() -{ - if(StorageManager.GetSaveDisabled() ) return; +void DirectoryLevelStorage::saveMapIdLookup() { + if (StorageManager.GetSaveDisabled()) return; #ifdef _LARGE_WORLDS - ConsoleSavePath file = getDataFile(L"largeMapDataMappings"); + ConsoleSavePath file = getDataFile(L"largeMapDataMappings"); #else - ConsoleSavePath file = getDataFile(L"mapDataMappings"); + ConsoleSavePath file = getDataFile(L"mapDataMappings"); #endif - if (!file.getName().empty()) - { - unsigned int NumberOfBytesWritten; - FileEntry *fileEntry = m_saveFile->createFile(file); - m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); + if (!file.getName().empty()) { + unsigned int NumberOfBytesWritten; + FileEntry* fileEntry = m_saveFile->createFile(file); + m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); #ifdef _LARGE_WORLDS - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - dos.writeInt(m_playerMappings.size()); - app.DebugPrintf("Saving %d mappings\n", m_playerMappings.size()); - for(AUTO_VAR(it,m_playerMappings.begin()); it != m_playerMappings.end(); ++it) - { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); + dos.writeInt(m_playerMappings.size()); + app.DebugPrintf("Saving %d mappings\n", m_playerMappings.size()); + for (AUTO_VAR(it, m_playerMappings.begin()); + it != m_playerMappings.end(); ++it) { #if defined(_WINDOWS64) || defined(__linux__) - app.DebugPrintf(" -- %d\n", it->first); + app.DebugPrintf(" -- %d\n", it->first); #else - #ifdef __linux__ - app.DebugPrintf(" -- %d\n", it->first); - #else - app.DebugPrintf(" -- %ls\n", it->first.toString().c_str()); - #endif -#endif - dos.writePlayerUID(it->first); - it->second.writeMappings(&dos); - } - dos.write(m_usedMappings); - m_saveFile->writeFile( fileEntry, - baos.buf.data, // data buffer - baos.size(), // number of bytes to write - &NumberOfBytesWritten // number of bytes written - ); +#ifdef __linux__ + app.DebugPrintf(" -- %d\n", it->first); #else - m_saveFile->writeFile( fileEntry, - &m_saveableMapDataMappings, // data buffer - sizeof(MapDataMappings), // number of bytes to write - &NumberOfBytesWritten // number of bytes written - ); - assert( NumberOfBytesWritten == sizeof(MapDataMappings) ); + app.DebugPrintf(" -- %ls\n", it->first.toString().c_str()); #endif - } +#endif + dos.writePlayerUID(it->first); + it->second.writeMappings(&dos); + } + dos.write(m_usedMappings); + m_saveFile->writeFile(fileEntry, + baos.buf.data, // data buffer + baos.size(), // number of bytes to write + &NumberOfBytesWritten // number of bytes written + ); +#else + m_saveFile->writeFile( + fileEntry, + &m_saveableMapDataMappings, // data buffer + sizeof(MapDataMappings), // number of bytes to write + &NumberOfBytesWritten // number of bytes written + ); + assert(NumberOfBytesWritten == sizeof(MapDataMappings)); +#endif + } } -void DirectoryLevelStorage::dontSaveMapMappingForPlayer(PlayerUID xuid) -{ +void DirectoryLevelStorage::dontSaveMapMappingForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); - if(it != m_playerMappings.end()) - { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) - { - int index = itMap->second / 8; - int offset = itMap->second % 8; - m_usedMappings[index] &= ~(1<second.m_mappings.begin()); + itMap != it->second.m_mappings.end(); ++itMap) { + int index = itMap->second / 8; + int offset = itMap->second % 8; + m_usedMappings[index] &= ~(1 << offset); + } + m_playerMappings.erase(it); + } #else - for(unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) - { - if(m_saveableMapDataMappings.xuids[i] == xuid) - { - m_saveableMapDataMappings.setMapping(i,INVALID_XUID,0); - } - } + for (unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) { + if (m_saveableMapDataMappings.xuids[i] == xuid) { + m_saveableMapDataMappings.setMapping(i, INVALID_XUID, 0); + } + } #endif } -void DirectoryLevelStorage::deleteMapFilesForPlayer(std::shared_ptr player) -{ - PlayerUID playerXuid = player->getXuid(); - if(playerXuid != INVALID_XUID) deleteMapFilesForPlayer(playerXuid); +void DirectoryLevelStorage::deleteMapFilesForPlayer( + std::shared_ptr player) { + PlayerUID playerXuid = player->getXuid(); + if (playerXuid != INVALID_XUID) deleteMapFilesForPlayer(playerXuid); } -void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) -{ +void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); - if(it != m_playerMappings.end()) - { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) - { - std::wstring id = std::wstring( L"map_" ) + _toString(itMap->second); - ConsoleSavePath file = getDataFile(id); + AUTO_VAR(it, m_playerMappings.find(xuid)); + if (it != m_playerMappings.end()) { + for (AUTO_VAR(itMap, it->second.m_mappings.begin()); + itMap != it->second.m_mappings.end(); ++itMap) { + std::wstring id = std::wstring(L"map_") + _toString(itMap->second); + ConsoleSavePath file = getDataFile(id); - if(m_saveFile->doesFileExist(file) ) - { - // If we can't actually delete this file, store the name so we can delete it later - if(StorageManager.GetSaveDisabled()) m_mapFilesToDelete.push_back(itMap->second); - else m_saveFile->deleteFile( m_saveFile->createFile(file) ); - } + if (m_saveFile->doesFileExist(file)) { + // If we can't actually delete this file, store the name so we + // can delete it later + if (StorageManager.GetSaveDisabled()) + m_mapFilesToDelete.push_back(itMap->second); + else + m_saveFile->deleteFile(m_saveFile->createFile(file)); + } - int index = itMap->second / 8; - int offset = itMap->second % 8; - m_usedMappings[index] &= ~(1<second / 8; + int offset = itMap->second % 8; + m_usedMappings[index] &= ~(1 << offset); + } + m_playerMappings.erase(it); + } #else - bool changed = false; - for(unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) - { - if(m_mapDataMappings.xuids[i] == xuid) - { - changed = true; + bool changed = false; + for (unsigned int i = 0; i < MAXIMUM_MAP_SAVE_DATA; ++i) { + if (m_mapDataMappings.xuids[i] == xuid) { + changed = true; - std::wstring id = std::wstring( L"map_" ) + _toString(i); - ConsoleSavePath file = getDataFile(id); + std::wstring id = std::wstring(L"map_") + _toString(i); + ConsoleSavePath file = getDataFile(id); - if(m_saveFile->doesFileExist(file) ) - { - // If we can't actually delete this file, store the name so we can delete it later - if(StorageManager.GetSaveDisabled()) m_mapFilesToDelete.push_back(i); - else m_saveFile->deleteFile( m_saveFile->createFile(file) ); - } - m_mapDataMappings.setMapping(i,INVALID_XUID,0); - m_saveableMapDataMappings.setMapping(i,INVALID_XUID,0); - break; - } - } + if (m_saveFile->doesFileExist(file)) { + // If we can't actually delete this file, store the name so we + // can delete it later + if (StorageManager.GetSaveDisabled()) + m_mapFilesToDelete.push_back(i); + else + m_saveFile->deleteFile(m_saveFile->createFile(file)); + } + m_mapDataMappings.setMapping(i, INVALID_XUID, 0); + m_saveableMapDataMappings.setMapping(i, INVALID_XUID, 0); + break; + } + } #endif } -void DirectoryLevelStorage::saveAllCachedData() -{ - if(StorageManager.GetSaveDisabled() ) return; +void DirectoryLevelStorage::saveAllCachedData() { + if (StorageManager.GetSaveDisabled()) return; - // Save any files that were saved while saving was disabled - for(AUTO_VAR(it, m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) - { - ByteArrayOutputStream *bos = it->second; + // Save any files that were saved while saving was disabled + for (AUTO_VAR(it, m_cachedSaveData.begin()); it != m_cachedSaveData.end(); + ++it) { + ByteArrayOutputStream* bos = it->second; - ConsoleSavePath realFile = ConsoleSavePath( it->first ); - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, realFile ); + ConsoleSavePath realFile = ConsoleSavePath(it->first); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, realFile); - app.DebugPrintf("Actually writing cached file %ls\n",it->first.c_str() ); - fos.write(bos->buf, 0, bos->size() ); - delete bos; - } - m_cachedSaveData.clear(); + app.DebugPrintf("Actually writing cached file %ls\n", + it->first.c_str()); + fos.write(bos->buf, 0, bos->size()); + delete bos; + } + m_cachedSaveData.clear(); - for(AUTO_VAR(it, m_mapFilesToDelete.begin()); it != m_mapFilesToDelete.end(); ++it) - { - std::wstring id = std::wstring( L"map_" ) + _toString(*it); - ConsoleSavePath file = getDataFile(id); - if(m_saveFile->doesFileExist(file) ) - { - m_saveFile->deleteFile( m_saveFile->createFile(file) ); - } - } - m_mapFilesToDelete.clear(); + for (AUTO_VAR(it, m_mapFilesToDelete.begin()); + it != m_mapFilesToDelete.end(); ++it) { + std::wstring id = std::wstring(L"map_") + _toString(*it); + ConsoleSavePath file = getDataFile(id); + if (m_saveFile->doesFileExist(file)) { + m_saveFile->deleteFile(m_saveFile->createFile(file)); + } + } + m_mapFilesToDelete.clear(); } diff --git a/Minecraft.World/Level/Storage/DirectoryLevelStorage.h b/Minecraft.World/Level/Storage/DirectoryLevelStorage.h index c88649414..665704726 100644 --- a/Minecraft.World/Level/Storage/DirectoryLevelStorage.h +++ b/Minecraft.World/Level/Storage/DirectoryLevelStorage.h @@ -1,20 +1,22 @@ #pragma once - #ifdef _LARGE_WORLDS -// 51 maps per player (7x7 overworld, 1 nether, 1 end) * 100 players rounded up to power of 2 -#define MAXIMUM_MAP_SAVE_DATA 8192//65536 +// 51 maps per player (7x7 overworld, 1 nether, 1 end) * 100 players rounded up +// to power of 2 +#define MAXIMUM_MAP_SAVE_DATA 8192 // 65536 -// 4J Stu - These are special map slots that are used on local machines. They will never be an actual map, -// but are placeholders for when we get updated with the correct id +// 4J Stu - These are special map slots that are used on local machines. They +// will never be an actual map, but are placeholders for when we get updated +// with the correct id #define MAP_OVERWORLD_DEFAULT_INDEX 65535 #define MAP_NETHER_DEFAULT_INDEX 65534 #define MAP_END_DEFAULT_INDEX 65533 #else #define MAXIMUM_MAP_SAVE_DATA 256 -// 4J Stu - These are special map slots that are used on local machines. They will never be an actual map, -// but are placeholders for when we get updated with the correct id +// 4J Stu - These are special map slots that are used on local machines. They +// will never be an actual map, but are placeholders for when we get updated +// with the correct id #define MAP_OVERWORLD_DEFAULT_INDEX 255 #define MAP_NETHER_DEFAULT_INDEX 254 #define MAP_END_DEFAULT_INDEX 253 @@ -30,115 +32,124 @@ #include "../../IO/Files/ConsoleSavePath.h" class ConsoleSaveFile; -// 4J Stu - Added this which we will write out as a file. Map id's are stored in itemInstances -// as the auxValue, so we can have at most 65536 maps. As we currently have a limit of 80 players -// with 3 maps each we should not hit this limit. -typedef struct _MapDataMappings -{ - PlayerUID xuids[MAXIMUM_MAP_SAVE_DATA]; - uint8_t dimensions[MAXIMUM_MAP_SAVE_DATA/4]; +// 4J Stu - Added this which we will write out as a file. Map id's are stored in +// itemInstances as the auxValue, so we can have at most 65536 maps. As we +// currently have a limit of 80 players with 3 maps each we should not hit this +// limit. +typedef struct _MapDataMappings { + PlayerUID xuids[MAXIMUM_MAP_SAVE_DATA]; + uint8_t dimensions[MAXIMUM_MAP_SAVE_DATA / 4]; - _MapDataMappings(); - int getDimension(int id); - void setMapping(int id, PlayerUID xuid, int dimension); + _MapDataMappings(); + int getDimension(int id); + void setMapping(int id, PlayerUID xuid, int dimension); } MapDataMappings; // Old version the only used 1 bit for dimension indexing -typedef struct _MapDataMappings_old -{ - PlayerUID xuids[MAXIMUM_MAP_SAVE_DATA]; - uint8_t dimensions[MAXIMUM_MAP_SAVE_DATA/8]; +typedef struct _MapDataMappings_old { + PlayerUID xuids[MAXIMUM_MAP_SAVE_DATA]; + uint8_t dimensions[MAXIMUM_MAP_SAVE_DATA / 8]; - _MapDataMappings_old(); - int getDimension(int id); - void setMapping(int id, PlayerUID xuid, int dimension); + _MapDataMappings_old(); + int getDimension(int id); + void setMapping(int id, PlayerUID xuid, int dimension); } MapDataMappings_old; -class DirectoryLevelStorage : public LevelStorage, public PlayerIO -{ +class DirectoryLevelStorage : public LevelStorage, public PlayerIO { private: - /* 4J Jev, Probably no need for this as theres no exceptions being thrown. - static const Logger *logger = Logger::getLogger("Minecraft"); */ + /* 4J Jev, Probably no need for this as theres no exceptions being thrown. + static const Logger *logger = Logger::getLogger("Minecraft"); */ const File dir; - //const File playerDir; - const ConsoleSavePath playerDir; - //const File dataDir; - const ConsoleSavePath dataDir; + // const File playerDir; + const ConsoleSavePath playerDir; + // const File dataDir; + const ConsoleSavePath dataDir; const __int64 sessionId; - const std::wstring levelId; + const std::wstring levelId; - static const std::wstring sc_szPlayerDir; - // 4J Added + static const std::wstring sc_szPlayerDir; + // 4J Added #ifdef _LARGE_WORLDS - class PlayerMappings - { - friend class DirectoryLevelStorage; - private: - std::unordered_map<__int64, short> m_mappings; + class PlayerMappings { + friend class DirectoryLevelStorage; - public: - void addMapping(int id, int centreX, int centreZ, int dimension, int scale); - bool getMapping(int &id, int centreX, int centreZ, int dimension, int scale); - void writeMappings(DataOutputStream *dos); - void readMappings(DataInputStream *dis); - }; -#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) || defined(_DURANGO) - std::unordered_map m_playerMappings; + private: + std::unordered_map<__int64, short> m_mappings; + + public: + void addMapping(int id, int centreX, int centreZ, int dimension, + int scale); + bool getMapping(int& id, int centreX, int centreZ, int dimension, + int scale); + void writeMappings(DataOutputStream* dos); + void readMappings(DataInputStream* dis); + }; +#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) || \ + defined(_DURANGO) + std::unordered_map + m_playerMappings; #else - std::unordered_map m_playerMappings; + std::unordered_map m_playerMappings; #endif - byteArray m_usedMappings; + byteArray m_usedMappings; #else - MapDataMappings m_mapDataMappings; - MapDataMappings m_saveableMapDataMappings; -#endif - bool m_bHasLoadedMapDataMappings; + MapDataMappings m_mapDataMappings; + MapDataMappings m_saveableMapDataMappings; +#endif + bool m_bHasLoadedMapDataMappings; - std::unordered_map m_cachedSaveData; - std::vector m_mapFilesToDelete; // Temp list of files that couldn't be deleted immediately due to saving being disabled + std::unordered_map m_cachedSaveData; + std::vector + m_mapFilesToDelete; // Temp list of files that couldn't be deleted + // immediately due to saving being disabled protected: - ConsoleSaveFile *m_saveFile; + ConsoleSaveFile* m_saveFile; public: - virtual ConsoleSaveFile *getSaveFile() { return m_saveFile; } - virtual void flushSaveFile(bool autosave); + virtual ConsoleSaveFile* getSaveFile() { return m_saveFile; } + virtual void flushSaveFile(bool autosave); public: - DirectoryLevelStorage(ConsoleSaveFile *saveFile, const File dir, const std::wstring& levelId, bool createPlayerDir); - ~DirectoryLevelStorage(); + DirectoryLevelStorage(ConsoleSaveFile* saveFile, const File dir, + const std::wstring& levelId, bool createPlayerDir); + ~DirectoryLevelStorage(); private: - void initiateSession(); + void initiateSession(); protected: - File getFolder(); + File getFolder(); public: - void checkSession(); - virtual ChunkStorage *createChunkStorage(Dimension *dimension); - LevelData *prepareLevel(); - virtual void saveLevelData(LevelData *levelData, std::vector > *players); - virtual void saveLevelData(LevelData *levelData); + void checkSession(); + virtual ChunkStorage* createChunkStorage(Dimension* dimension); + LevelData* prepareLevel(); + virtual void saveLevelData(LevelData* levelData, + std::vector >* players); + virtual void saveLevelData(LevelData* levelData); virtual void save(std::shared_ptr player); - virtual bool load(std::shared_ptr player); // 4J Changed return val to bool to check if new player or loaded player - virtual CompoundTag *loadPlayerDataTag(PlayerUID xuid); - virtual void clearOldPlayerFiles(); // 4J Added - PlayerIO *getPlayerIO(); + virtual bool load(std::shared_ptr + player); // 4J Changed return val to bool to check if + // new player or loaded player + virtual CompoundTag* loadPlayerDataTag(PlayerUID xuid); + virtual void clearOldPlayerFiles(); // 4J Added + PlayerIO* getPlayerIO(); virtual void closeAll(); ConsoleSavePath getDataFile(const std::wstring& id); - std::wstring getLevelId(); + std::wstring getLevelId(); - // 4J Added - virtual int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale); - virtual void saveMapIdLookup(); - virtual void deleteMapFilesForPlayer(std::shared_ptr player); - virtual void saveAllCachedData(); - void resetNetherPlayerPositions(); // 4J Added - static std::wstring getPlayerDir() { return sc_szPlayerDir; } + // 4J Added + virtual int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, + int centreZC, int scale); + virtual void saveMapIdLookup(); + virtual void deleteMapFilesForPlayer(std::shared_ptr player); + virtual void saveAllCachedData(); + void resetNetherPlayerPositions(); // 4J Added + static std::wstring getPlayerDir() { return sc_szPlayerDir; } private: - void dontSaveMapMappingForPlayer(PlayerUID xuid); - void deleteMapFilesForPlayer(PlayerUID xuid); + void dontSaveMapMappingForPlayer(PlayerUID xuid); + void deleteMapFilesForPlayer(PlayerUID xuid); }; diff --git a/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.cpp b/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.cpp index 9349cb116..0776382e5 100644 --- a/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.cpp +++ b/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.cpp @@ -11,21 +11,17 @@ class LevelStorage; -DirectoryLevelStorageSource::DirectoryLevelStorageSource(const File dir) : baseDir( dir ) -{ - //if (!dir.exists()) dir.mkdirs(); // 4J Removed - //this->baseDir = dir; +DirectoryLevelStorageSource::DirectoryLevelStorageSource(const File dir) + : baseDir(dir) { + // if (!dir.exists()) dir.mkdirs(); // 4J Removed + // this->baseDir = dir; } -std::wstring DirectoryLevelStorageSource::getName() -{ - return L"Old Format"; -} +std::wstring DirectoryLevelStorageSource::getName() { return L"Old Format"; } -std::vector *DirectoryLevelStorageSource::getLevelList() -{ - // 4J Stu - We don't use directory list with the Xbox save locations - std::vector *levels = new std::vector; +std::vector* DirectoryLevelStorageSource::getLevelList() { + // 4J Stu - We don't use directory list with the Xbox save locations + std::vector* levels = new std::vector; #if 0 for (int i = 0; i < 5; i++) { @@ -38,102 +34,99 @@ std::vector *DirectoryLevelStorageSource::getLevelList() } } #endif - return levels; + return levels; } -void DirectoryLevelStorageSource::clearAll() -{ +void DirectoryLevelStorageSource::clearAll() {} + +LevelData* DirectoryLevelStorageSource::getDataTagFor( + ConsoleSaveFile* saveFile, const std::wstring& levelId) { + // File dataFile(dir, L"level.dat"); + ConsoleSavePath dataFile = ConsoleSavePath(std::wstring(L"level.dat")); + if (saveFile->doesFileExist(dataFile)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(saveFile, dataFile); + CompoundTag* root = NbtIo::readCompressed(&fis); + CompoundTag* tag = root->getCompound(L"Data"); + LevelData* ret = new LevelData(tag); + delete root; + return ret; + } + + return NULL; } -LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, const std::wstring& levelId) -{ - //File dataFile(dir, L"level.dat"); - ConsoleSavePath dataFile = ConsoleSavePath( std::wstring( L"level.dat" ) ); - if ( saveFile->doesFileExist( dataFile ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(saveFile, dataFile); - CompoundTag *root = NbtIo::readCompressed(&fis); - CompoundTag *tag = root->getCompound(L"Data"); - LevelData *ret = new LevelData(tag); - delete root; - return ret; - } +void DirectoryLevelStorageSource::renameLevel( + const std::wstring& levelId, const std::wstring& newLevelName) { + ConsoleSaveFileOriginal tempSave(levelId); - return NULL; + // File dataFile = File(dir, L"level.dat"); + ConsoleSavePath dataFile = ConsoleSavePath(std::wstring(L"level.dat")); + if (tempSave.doesFileExist(dataFile)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(&tempSave, dataFile); + CompoundTag* root = NbtIo::readCompressed(&fis); + CompoundTag* tag = root->getCompound(L"Data"); + tag->putString(L"LevelName", newLevelName); + + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(&tempSave, dataFile); + NbtIo::writeCompressed(root, &fos); + } } -void DirectoryLevelStorageSource::renameLevel(const std::wstring& levelId, const std::wstring& newLevelName) -{ - ConsoleSaveFileOriginal tempSave(levelId); +bool DirectoryLevelStorageSource::isNewLevelIdAcceptable( + const std::wstring& levelId) { + // 4J Jev, removed try/catch. - //File dataFile = File(dir, L"level.dat"); - ConsoleSavePath dataFile = ConsoleSavePath( std::wstring( L"level.dat" ) ); - if ( tempSave.doesFileExist( dataFile ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(&tempSave, dataFile); - CompoundTag *root = NbtIo::readCompressed(&fis); - CompoundTag *tag = root->getCompound(L"Data"); - tag->putString(L"LevelName", newLevelName); + File levelFolder = File(baseDir, levelId); + if (levelFolder.exists()) { + return false; + } - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream(&tempSave, dataFile); - NbtIo::writeCompressed(root, &fos); - } + levelFolder.mkdir(); + + return true; } -bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const std::wstring& levelId) -{ - // 4J Jev, removed try/catch. +void DirectoryLevelStorageSource::deleteLevel(const std::wstring& levelId) { + File dir = File(baseDir, levelId); + if (!dir.exists()) return; - File levelFolder = File(baseDir, levelId); - if (levelFolder.exists()) - { - return false; - } - - levelFolder.mkdir(); - - return true; + deleteRecursive(dir.listFiles()); + dir._delete(); } -void DirectoryLevelStorageSource::deleteLevel(const std::wstring& levelId) -{ - File dir = File(baseDir, levelId); - if (!dir.exists()) return; - - deleteRecursive(dir.listFiles()); - dir._delete(); +void DirectoryLevelStorageSource::deleteRecursive(std::vector* files) { + AUTO_VAR(itEnd, files->end()); + for (AUTO_VAR(it, files->begin()); it != itEnd; it++) { + File* file = *it; + if (file->isDirectory()) { + deleteRecursive(file->listFiles()); + } + file->_delete(); + } } -void DirectoryLevelStorageSource::deleteRecursive(std::vector *files) -{ - AUTO_VAR(itEnd, files->end()); - for (AUTO_VAR(it, files->begin()); it != itEnd; it++) - { - File *file = *it; - if (file->isDirectory()) - { - deleteRecursive(file->listFiles()); - } - file->_delete(); - } +std::shared_ptr DirectoryLevelStorageSource::selectLevel( + ConsoleSaveFile* saveFile, const std::wstring& levelId, + bool createPlayerDir) { + return std::shared_ptr( + new DirectoryLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); } -std::shared_ptr DirectoryLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, bool createPlayerDir) -{ - return std::shared_ptr (new DirectoryLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); +bool DirectoryLevelStorageSource::isConvertible(ConsoleSaveFile* saveFile, + const std::wstring& levelId) { + return false; } -bool DirectoryLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const std::wstring& levelId) -{ - return false; +bool DirectoryLevelStorageSource::requiresConversion( + ConsoleSaveFile* saveFile, const std::wstring& levelId) { + return false; } -bool DirectoryLevelStorageSource::requiresConversion(ConsoleSaveFile *saveFile, const std::wstring& levelId) -{ - return false; -} - -bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, ProgressListener *progress) -{ - return false; +bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + ProgressListener* progress) { + return false; } diff --git a/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.h b/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.h index 24a7c1968..25c9fc8a4 100644 --- a/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.h +++ b/Minecraft.World/Level/Storage/DirectoryLevelStorageSource.h @@ -1,6 +1,5 @@ #pragma once - #include "LevelStorageSource.h" #include "../../IO/Files/File.h" @@ -8,27 +7,34 @@ class ProgressListener; class LevelData; class ConsoleSaveFile; -class DirectoryLevelStorageSource : public LevelStorageSource -{ +class DirectoryLevelStorageSource : public LevelStorageSource { protected: - const File baseDir; + const File baseDir; public: - DirectoryLevelStorageSource(const File dir); - virtual std::wstring getName(); - virtual std::vector *getLevelList(); + DirectoryLevelStorageSource(const File dir); + virtual std::wstring getName(); + virtual std::vector* getLevelList(); virtual void clearAll(); - virtual LevelData *getDataTagFor(ConsoleSaveFile *saveFile, const std::wstring& levelId); - virtual void renameLevel(const std::wstring& levelId, const std::wstring& newLevelName); + virtual LevelData* getDataTagFor(ConsoleSaveFile* saveFile, + const std::wstring& levelId); + virtual void renameLevel(const std::wstring& levelId, + const std::wstring& newLevelName); virtual bool isNewLevelIdAcceptable(const std::wstring& levelId); virtual void deleteLevel(const std::wstring& levelId); protected: - static void deleteRecursive(std::vector *files); + static void deleteRecursive(std::vector* files); public: - virtual std::shared_ptr selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, bool createPlayerDir); - virtual bool isConvertible(ConsoleSaveFile *saveFile, const std::wstring& levelId); - virtual bool requiresConversion(ConsoleSaveFile *saveFile, const std::wstring& levelId); - virtual bool convertLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, ProgressListener *progress); + virtual std::shared_ptr selectLevel( + ConsoleSaveFile* saveFile, const std::wstring& levelId, + bool createPlayerDir); + virtual bool isConvertible(ConsoleSaveFile* saveFile, + const std::wstring& levelId); + virtual bool requiresConversion(ConsoleSaveFile* saveFile, + const std::wstring& levelId); + virtual bool convertLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + ProgressListener* progress); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/EntityIO.cpp b/Minecraft.World/Level/Storage/EntityIO.cpp index 714aa7229..37cb6d6cd 100644 --- a/Minecraft.World/Level/Storage/EntityIO.cpp +++ b/Minecraft.World/Level/Storage/EntityIO.cpp @@ -14,46 +14,71 @@ #include "../../Headers/com.mojang.nbt.h" #include "EntityIO.h" -std::unordered_map *EntityIO::idCreateMap = new std::unordered_map; -std::unordered_map *EntityIO::classIdMap = new std::unordered_map; -std::unordered_map *EntityIO::numCreateMap = new std::unordered_map; -std::unordered_map *EntityIO::numClassMap = new std::unordered_map; -std::unordered_map *EntityIO::classNumMap = new std::unordered_map; -std::unordered_map *EntityIO::idNumMap = new std::unordered_map; -std::unordered_map EntityIO::idsSpawnableInCreative; +std::unordered_map* EntityIO::idCreateMap = + new std::unordered_map; +std::unordered_map* EntityIO::classIdMap = + new std::unordered_map; +std::unordered_map* EntityIO::numCreateMap = + new std::unordered_map; +std::unordered_map* EntityIO::numClassMap = + new std::unordered_map; +std::unordered_map* + EntityIO::classNumMap = + new std::unordered_map; +std::unordered_map* EntityIO::idNumMap = + new std::unordered_map; +std::unordered_map + EntityIO::idsSpawnableInCreative; -void EntityIO::setId(entityCreateFn createFn, eINSTANCEOF clas, const std::wstring &id, int idNum) -{ - idCreateMap->insert( std::unordered_map::value_type(id, createFn) ); - classIdMap->insert( std::unordered_map::value_type(clas,id ) ); - numCreateMap->insert( std::unordered_map::value_type(idNum, createFn) ); - numClassMap->insert( std::unordered_map::value_type(idNum, clas) ); - classNumMap->insert( std::unordered_map::value_type(clas, idNum) ); - idNumMap->insert( std::unordered_map::value_type(id, idNum) ); +void EntityIO::setId(entityCreateFn createFn, eINSTANCEOF clas, + const std::wstring& id, int idNum) { + idCreateMap->insert( + std::unordered_map::value_type(id, + createFn)); + classIdMap->insert( + std::unordered_map::value_type(clas, id)); + numCreateMap->insert( + std::unordered_map::value_type(idNum, createFn)); + numClassMap->insert( + std::unordered_map::value_type(idNum, clas)); + classNumMap->insert( + std::unordered_map::value_type(clas, idNum)); + idNumMap->insert( + std::unordered_map::value_type(id, idNum)); } -void EntityIO::setId(entityCreateFn createFn, eINSTANCEOF clas, const std::wstring &id, int idNum, eMinecraftColour color1, eMinecraftColour color2, int nameId) -{ - setId(createFn, clas, id, idNum); +void EntityIO::setId(entityCreateFn createFn, eINSTANCEOF clas, + const std::wstring& id, int idNum, eMinecraftColour color1, + eMinecraftColour color2, int nameId) { + setId(createFn, clas, id, idNum); - idsSpawnableInCreative.insert( std::unordered_map::value_type( idNum, new SpawnableMobInfo(idNum, color1, color2, nameId) ) ); + idsSpawnableInCreative.insert( + std::unordered_map::value_type( + idNum, new SpawnableMobInfo(idNum, color1, color2, nameId))); } -void EntityIO::staticCtor() -{ - setId(ItemEntity::create, eTYPE_ITEMENTITY, L"Item", 1); - setId(ExperienceOrb::create, eTYPE_EXPERIENCEORB, L"XPOrb", 2); - +void EntityIO::staticCtor() { + setId(ItemEntity::create, eTYPE_ITEMENTITY, L"Item", 1); + setId(ExperienceOrb::create, eTYPE_EXPERIENCEORB, L"XPOrb", 2); + setId(Painting::create, eTYPE_PAINTING, L"Painting", 9); setId(Arrow::create, eTYPE_ARROW, L"Arrow", 10); setId(Snowball::create, eTYPE_SNOWBALL, L"Snowball", 11); - setId(Fireball::create, eTYPE_FIREBALL, L"Fireball", 12); - setId(SmallFireball::create, eTYPE_SMALL_FIREBALL, L"SmallFireball", 13); - setId(ThrownEnderpearl::create, eTYPE_THROWNENDERPEARL, L"ThrownEnderpearl", 14); - setId(EyeOfEnderSignal::create, eTYPE_EYEOFENDERSIGNAL, L"EyeOfEnderSignal", 15); - setId(ThrownPotion::create, eTYPE_THROWNPOTION, L"ThrownPotion", 16); - setId(ThrownExpBottle::create, eTYPE_THROWNEXPBOTTLE, L"ThrownExpBottle", 17); - setId(ItemFrame::create, eTYPE_ITEM_FRAME, L"ItemFrame", 18); + setId(Fireball::create, eTYPE_FIREBALL, L"Fireball", 12); + setId(SmallFireball::create, eTYPE_SMALL_FIREBALL, L"SmallFireball", 13); + setId(ThrownEnderpearl::create, eTYPE_THROWNENDERPEARL, L"ThrownEnderpearl", + 14); + setId(EyeOfEnderSignal::create, eTYPE_EYEOFENDERSIGNAL, L"EyeOfEnderSignal", + 15); + setId(ThrownPotion::create, eTYPE_THROWNPOTION, L"ThrownPotion", 16); + setId(ThrownExpBottle::create, eTYPE_THROWNEXPBOTTLE, L"ThrownExpBottle", + 17); + setId(ItemFrame::create, eTYPE_ITEM_FRAME, L"ItemFrame", 18); setId(PrimedTnt::create, eTYPE_PRIMEDTNT, L"PrimedTnt", 20); setId(FallingTile::create, eTYPE_FALLINGTILE, L"FallingSand", 21); @@ -64,201 +89,226 @@ void EntityIO::staticCtor() setId(Mob::create, eTYPE_MOB, L"Mob", 48); setId(Monster::create, eTYPE_MONSTER, L"Monster", 49); - setId(Creeper::create, eTYPE_CREEPER, L"Creeper", 50, eMinecraftColour_Mob_Creeper_Colour1, eMinecraftColour_Mob_Creeper_Colour2, IDS_CREEPER); - setId(Skeleton::create, eTYPE_SKELETON, L"Skeleton", 51, eMinecraftColour_Mob_Skeleton_Colour1, eMinecraftColour_Mob_Skeleton_Colour2, IDS_SKELETON); - setId(Spider::create, eTYPE_SPIDER, L"Spider", 52, eMinecraftColour_Mob_Spider_Colour1, eMinecraftColour_Mob_Spider_Colour2, IDS_SPIDER); + setId(Creeper::create, eTYPE_CREEPER, L"Creeper", 50, + eMinecraftColour_Mob_Creeper_Colour1, + eMinecraftColour_Mob_Creeper_Colour2, IDS_CREEPER); + setId(Skeleton::create, eTYPE_SKELETON, L"Skeleton", 51, + eMinecraftColour_Mob_Skeleton_Colour1, + eMinecraftColour_Mob_Skeleton_Colour2, IDS_SKELETON); + setId(Spider::create, eTYPE_SPIDER, L"Spider", 52, + eMinecraftColour_Mob_Spider_Colour1, + eMinecraftColour_Mob_Spider_Colour2, IDS_SPIDER); setId(Giant::create, eTYPE_GIANT, L"Giant", 53); - setId(Zombie::create, eTYPE_ZOMBIE, L"Zombie", 54, eMinecraftColour_Mob_Zombie_Colour1, eMinecraftColour_Mob_Zombie_Colour2, IDS_ZOMBIE); - setId(Slime::create, eTYPE_SLIME, L"Slime", 55, eMinecraftColour_Mob_Slime_Colour1, eMinecraftColour_Mob_Slime_Colour2, IDS_SLIME); - setId(Ghast::create, eTYPE_GHAST, L"Ghast", 56, eMinecraftColour_Mob_Ghast_Colour1, eMinecraftColour_Mob_Ghast_Colour2, IDS_GHAST); - setId(PigZombie::create, eTYPE_PIGZOMBIE, L"PigZombie", 57, eMinecraftColour_Mob_PigZombie_Colour1, eMinecraftColour_Mob_PigZombie_Colour2, IDS_PIGZOMBIE); - setId(EnderMan::create, eTYPE_ENDERMAN, L"Enderman", 58, eMinecraftColour_Mob_Enderman_Colour1, eMinecraftColour_Mob_Enderman_Colour2, IDS_ENDERMAN); - setId(CaveSpider::create, eTYPE_CAVESPIDER, L"CaveSpider", 59, eMinecraftColour_Mob_CaveSpider_Colour1, eMinecraftColour_Mob_CaveSpider_Colour2, IDS_CAVE_SPIDER); - setId(Silverfish::create, eTYPE_SILVERFISH, L"Silverfish", 60, eMinecraftColour_Mob_Silverfish_Colour1, eMinecraftColour_Mob_Silverfish_Colour2, IDS_SILVERFISH); - setId(Blaze::create, eTYPE_BLAZE, L"Blaze", 61, eMinecraftColour_Mob_Blaze_Colour1, eMinecraftColour_Mob_Blaze_Colour2, IDS_BLAZE); - setId(LavaSlime::create, eTYPE_LAVASLIME, L"LavaSlime", 62, eMinecraftColour_Mob_LavaSlime_Colour1, eMinecraftColour_Mob_LavaSlime_Colour2, IDS_LAVA_SLIME); - setId(EnderDragon::create, eTYPE_ENDERDRAGON, L"EnderDragon", 63); + setId(Zombie::create, eTYPE_ZOMBIE, L"Zombie", 54, + eMinecraftColour_Mob_Zombie_Colour1, + eMinecraftColour_Mob_Zombie_Colour2, IDS_ZOMBIE); + setId(Slime::create, eTYPE_SLIME, L"Slime", 55, + eMinecraftColour_Mob_Slime_Colour1, + eMinecraftColour_Mob_Slime_Colour2, IDS_SLIME); + setId(Ghast::create, eTYPE_GHAST, L"Ghast", 56, + eMinecraftColour_Mob_Ghast_Colour1, + eMinecraftColour_Mob_Ghast_Colour2, IDS_GHAST); + setId(PigZombie::create, eTYPE_PIGZOMBIE, L"PigZombie", 57, + eMinecraftColour_Mob_PigZombie_Colour1, + eMinecraftColour_Mob_PigZombie_Colour2, IDS_PIGZOMBIE); + setId(EnderMan::create, eTYPE_ENDERMAN, L"Enderman", 58, + eMinecraftColour_Mob_Enderman_Colour1, + eMinecraftColour_Mob_Enderman_Colour2, IDS_ENDERMAN); + setId(CaveSpider::create, eTYPE_CAVESPIDER, L"CaveSpider", 59, + eMinecraftColour_Mob_CaveSpider_Colour1, + eMinecraftColour_Mob_CaveSpider_Colour2, IDS_CAVE_SPIDER); + setId(Silverfish::create, eTYPE_SILVERFISH, L"Silverfish", 60, + eMinecraftColour_Mob_Silverfish_Colour1, + eMinecraftColour_Mob_Silverfish_Colour2, IDS_SILVERFISH); + setId(Blaze::create, eTYPE_BLAZE, L"Blaze", 61, + eMinecraftColour_Mob_Blaze_Colour1, + eMinecraftColour_Mob_Blaze_Colour2, IDS_BLAZE); + setId(LavaSlime::create, eTYPE_LAVASLIME, L"LavaSlime", 62, + eMinecraftColour_Mob_LavaSlime_Colour1, + eMinecraftColour_Mob_LavaSlime_Colour2, IDS_LAVA_SLIME); + setId(EnderDragon::create, eTYPE_ENDERDRAGON, L"EnderDragon", 63); - setId(Pig::create, eTYPE_PIG, L"Pig", 90, eMinecraftColour_Mob_Pig_Colour1, eMinecraftColour_Mob_Pig_Colour2, IDS_PIG); - setId(Sheep::create, eTYPE_SHEEP, L"Sheep", 91, eMinecraftColour_Mob_Sheep_Colour1, eMinecraftColour_Mob_Sheep_Colour2, IDS_SHEEP); - setId(Cow::create, eTYPE_COW, L"Cow", 92, eMinecraftColour_Mob_Cow_Colour1, eMinecraftColour_Mob_Cow_Colour2, IDS_COW); - setId(Chicken::create, eTYPE_CHICKEN, L"Chicken", 93, eMinecraftColour_Mob_Chicken_Colour1, eMinecraftColour_Mob_Chicken_Colour2, IDS_CHICKEN); - setId(Squid::create, eTYPE_SQUID, L"Squid", 94, eMinecraftColour_Mob_Squid_Colour1, eMinecraftColour_Mob_Squid_Colour2, IDS_SQUID); - setId(Wolf::create, eTYPE_WOLF, L"Wolf", 95, eMinecraftColour_Mob_Wolf_Colour1, eMinecraftColour_Mob_Wolf_Colour2, IDS_WOLF); - setId(MushroomCow::create, eTYPE_MUSHROOMCOW, L"MushroomCow", 96, eMinecraftColour_Mob_MushroomCow_Colour1, eMinecraftColour_Mob_MushroomCow_Colour2, IDS_MUSHROOM_COW); - setId(SnowMan::create, eTYPE_SNOWMAN, L"SnowMan", 97); - setId(Ozelot::create, eTYPE_OZELOT, L"Ozelot", 98, eMinecraftColour_Mob_Ocelot_Colour1, eMinecraftColour_Mob_Ocelot_Colour2, IDS_OZELOT); - setId(VillagerGolem::create, eTYPE_VILLAGERGOLEM, L"VillagerGolem", 99); + setId(Pig::create, eTYPE_PIG, L"Pig", 90, eMinecraftColour_Mob_Pig_Colour1, + eMinecraftColour_Mob_Pig_Colour2, IDS_PIG); + setId(Sheep::create, eTYPE_SHEEP, L"Sheep", 91, + eMinecraftColour_Mob_Sheep_Colour1, + eMinecraftColour_Mob_Sheep_Colour2, IDS_SHEEP); + setId(Cow::create, eTYPE_COW, L"Cow", 92, eMinecraftColour_Mob_Cow_Colour1, + eMinecraftColour_Mob_Cow_Colour2, IDS_COW); + setId(Chicken::create, eTYPE_CHICKEN, L"Chicken", 93, + eMinecraftColour_Mob_Chicken_Colour1, + eMinecraftColour_Mob_Chicken_Colour2, IDS_CHICKEN); + setId(Squid::create, eTYPE_SQUID, L"Squid", 94, + eMinecraftColour_Mob_Squid_Colour1, + eMinecraftColour_Mob_Squid_Colour2, IDS_SQUID); + setId(Wolf::create, eTYPE_WOLF, L"Wolf", 95, + eMinecraftColour_Mob_Wolf_Colour1, eMinecraftColour_Mob_Wolf_Colour2, + IDS_WOLF); + setId(MushroomCow::create, eTYPE_MUSHROOMCOW, L"MushroomCow", 96, + eMinecraftColour_Mob_MushroomCow_Colour1, + eMinecraftColour_Mob_MushroomCow_Colour2, IDS_MUSHROOM_COW); + setId(SnowMan::create, eTYPE_SNOWMAN, L"SnowMan", 97); + setId(Ozelot::create, eTYPE_OZELOT, L"Ozelot", 98, + eMinecraftColour_Mob_Ocelot_Colour1, + eMinecraftColour_Mob_Ocelot_Colour2, IDS_OZELOT); + setId(VillagerGolem::create, eTYPE_VILLAGERGOLEM, L"VillagerGolem", 99); - setId(Villager::create, eTYPE_VILLAGER, L"Villager", 120, eMinecraftColour_Mob_Villager_Colour1, eMinecraftColour_Mob_Villager_Colour2, IDS_VILLAGER); + setId(Villager::create, eTYPE_VILLAGER, L"Villager", 120, + eMinecraftColour_Mob_Villager_Colour1, + eMinecraftColour_Mob_Villager_Colour2, IDS_VILLAGER); - setId(EnderCrystal::create, eTYPE_ENDER_CRYSTAL, L"EnderCrystal", 200); + setId(EnderCrystal::create, eTYPE_ENDER_CRYSTAL, L"EnderCrystal", 200); - // 4J Added - setId(DragonFireball::create, eTYPE_DRAGON_FIREBALL, L"DragonFireball", 1000); + // 4J Added + setId(DragonFireball::create, eTYPE_DRAGON_FIREBALL, L"DragonFireball", + 1000); } -std::shared_ptr EntityIO::newEntity(const std::wstring& id, Level *level) -{ +std::shared_ptr EntityIO::newEntity(const std::wstring& id, + Level* level) { std::shared_ptr entity; - AUTO_VAR(it, idCreateMap->find(id)); - if(it != idCreateMap->end() ) - { - entityCreateFn create = it->second; - if (create != NULL) entity = std::shared_ptr(create(level)); - } + AUTO_VAR(it, idCreateMap->find(id)); + if (it != idCreateMap->end()) { + entityCreateFn create = it->second; + if (create != NULL) entity = std::shared_ptr(create(level)); + } return entity; } -std::shared_ptr EntityIO::loadStatic(CompoundTag *tag, Level *level) -{ +std::shared_ptr EntityIO::loadStatic(CompoundTag* tag, Level* level) { std::shared_ptr entity; - AUTO_VAR(it, idCreateMap->find(tag->getString(L"id"))); - if(it != idCreateMap->end() ) - { - entityCreateFn create = it->second; - if (create != NULL) entity = std::shared_ptr(create(level)); - } - - if (entity != NULL) - { - entity->load(tag); + AUTO_VAR(it, idCreateMap->find(tag->getString(L"id"))); + if (it != idCreateMap->end()) { + entityCreateFn create = it->second; + if (create != NULL) entity = std::shared_ptr(create(level)); } - else - { + + if (entity != NULL) { + entity->load(tag); + } else { #ifdef _DEBUG - app.DebugPrintf("Skipping Entity with id %ls\n", tag->getString(L"id").c_str() ); + app.DebugPrintf("Skipping Entity with id %ls\n", + tag->getString(L"id").c_str()); #endif } return entity; } -std::shared_ptr EntityIO::newById(int id, Level *level) -{ +std::shared_ptr EntityIO::newById(int id, Level* level) { std::shared_ptr entity; - AUTO_VAR(it, numCreateMap->find(id)); - if(it != numCreateMap->end() ) - { - entityCreateFn create = it->second; - if (create != NULL) entity = std::shared_ptr(create(level)); - } - - if (entity != NULL) - { + AUTO_VAR(it, numCreateMap->find(id)); + if (it != numCreateMap->end()) { + entityCreateFn create = it->second; + if (create != NULL) entity = std::shared_ptr(create(level)); } - else - { - //printf("Skipping Entity with id %d\n", id ) ; + + if (entity != NULL) { + } else { + // printf("Skipping Entity with id %d\n", id ) ; } return entity; } -std::shared_ptr EntityIO::newByEnumType(eINSTANCEOF eType, Level *level) -{ +std::shared_ptr EntityIO::newByEnumType(eINSTANCEOF eType, + Level* level) { std::shared_ptr entity; - std::unordered_map::iterator it = classNumMap->find( eType ); - if( it != classNumMap->end() ) - { - AUTO_VAR(it2, numCreateMap->find(it->second)); - if(it2 != numCreateMap->end() ) - { - entityCreateFn create = it2->second; - if (create != NULL) entity = std::shared_ptr(create(level)); - } - } + std::unordered_map::iterator it = + classNumMap->find(eType); + if (it != classNumMap->end()) { + AUTO_VAR(it2, numCreateMap->find(it->second)); + if (it2 != numCreateMap->end()) { + entityCreateFn create = it2->second; + if (create != NULL) entity = std::shared_ptr(create(level)); + } + } return entity; } -int EntityIO::getId(std::shared_ptr entity) -{ - std::unordered_map::iterator it = classNumMap->find( entity->GetType() ); - return (*it).second; +int EntityIO::getId(std::shared_ptr entity) { + std::unordered_map::iterator it = + classNumMap->find(entity->GetType()); + return (*it).second; } -std::wstring EntityIO::getEncodeId(std::shared_ptr entity) -{ - std::unordered_map::iterator it = classIdMap->find( entity->GetType() ); - if( it != classIdMap->end() ) - return (*it).second; - else - return L""; +std::wstring EntityIO::getEncodeId(std::shared_ptr entity) { + std::unordered_map::iterator it = + classIdMap->find(entity->GetType()); + if (it != classIdMap->end()) + return (*it).second; + else + return L""; } -int EntityIO::getId(const std::wstring &encodeId) -{ - AUTO_VAR(it, idNumMap->find(encodeId)); - if (it == idNumMap->end()) - { - // defaults to pig... - return 90; - } - return it->second; +int EntityIO::getId(const std::wstring& encodeId) { + AUTO_VAR(it, idNumMap->find(encodeId)); + if (it == idNumMap->end()) { + // defaults to pig... + return 90; + } + return it->second; } -std::wstring EntityIO::getEncodeId(int entityIoValue) -{ - //Class class1 = numClassMap.get(entityIoValue); - //if (class1 != null) - //{ - //return classIdMap.get(class1); - //} - - AUTO_VAR(it, numClassMap->find(entityIoValue)); - if(it != numClassMap->end() ) - { - std::unordered_map::iterator classIdIt = classIdMap->find( it->second ); - if( classIdIt != classIdMap->end() ) - return (*classIdIt).second; - else - return L""; - } +std::wstring EntityIO::getEncodeId(int entityIoValue) { + // Class class1 = numClassMap.get(entityIoValue); + // if (class1 != null) + //{ + // return classIdMap.get(class1); + // } - return L""; + AUTO_VAR(it, numClassMap->find(entityIoValue)); + if (it != numClassMap->end()) { + std::unordered_map::iterator classIdIt = + classIdMap->find(it->second); + if (classIdIt != classIdMap->end()) + return (*classIdIt).second; + else + return L""; + } + + return L""; } -int EntityIO::getNameId(int entityIoValue) -{ - int id = -1; +int EntityIO::getNameId(int entityIoValue) { + int id = -1; - AUTO_VAR(it, idsSpawnableInCreative.find(entityIoValue)); - if(it != idsSpawnableInCreative.end()) - { - id = it->second->nameId; - } + AUTO_VAR(it, idsSpawnableInCreative.find(entityIoValue)); + if (it != idsSpawnableInCreative.end()) { + id = it->second->nameId; + } - return id; + return id; } -eINSTANCEOF EntityIO::getType(const std::wstring &idString) -{ - AUTO_VAR(it, numClassMap->find(getId(idString))); - if(it != numClassMap->end() ) - { - return it->second; - } - return eTYPE_NOTSET; +eINSTANCEOF EntityIO::getType(const std::wstring& idString) { + AUTO_VAR(it, numClassMap->find(getId(idString))); + if (it != numClassMap->end()) { + return it->second; + } + return eTYPE_NOTSET; } -eINSTANCEOF EntityIO::getClass(int id) -{ - AUTO_VAR(it, numClassMap->find(id)); - if(it != numClassMap->end() ) - { - return it->second; - } - return eTYPE_NOTSET; +eINSTANCEOF EntityIO::getClass(int id) { + AUTO_VAR(it, numClassMap->find(id)); + if (it != numClassMap->end()) { + return it->second; + } + return eTYPE_NOTSET; } -int EntityIO::eTypeToIoid(eINSTANCEOF eType) -{ - std::unordered_map::iterator it = classNumMap->find( eType ); - if( it != classNumMap->end() ) - return it->second; - return -1; +int EntityIO::eTypeToIoid(eINSTANCEOF eType) { + std::unordered_map::iterator it = + classNumMap->find(eType); + if (it != classNumMap->end()) return it->second; + return -1; } diff --git a/Minecraft.World/Level/Storage/EntityIO.h b/Minecraft.World/Level/Storage/EntityIO.h index 3911c95eb..db7737405 100644 --- a/Minecraft.World/Level/Storage/EntityIO.h +++ b/Minecraft.World/Level/Storage/EntityIO.h @@ -1,61 +1,66 @@ #pragma once - #include "../../Entities/Entity.h" #include "../../Util/JavaIntHash.h" class Level; class CompoundTag; -typedef Entity *(*entityCreateFn)(Level *); -class EntityIO -{ +typedef Entity* (*entityCreateFn)(Level*); +class EntityIO { public: - class SpawnableMobInfo - { - public: - int id; - eMinecraftColour eggColor1; - eMinecraftColour eggColor2; - int nameId; // 4J Added + class SpawnableMobInfo { + public: + int id; + eMinecraftColour eggColor1; + eMinecraftColour eggColor2; + int nameId; // 4J Added - SpawnableMobInfo(int id, eMinecraftColour eggColor1, eMinecraftColour eggColor2, int nameId) - { - this->id = id; - this->eggColor1 = eggColor1; - this->eggColor2 = eggColor2; - this->nameId = nameId; - } - }; + SpawnableMobInfo(int id, eMinecraftColour eggColor1, + eMinecraftColour eggColor2, int nameId) { + this->id = id; + this->eggColor1 = eggColor1; + this->eggColor2 = eggColor2; + this->nameId = nameId; + } + }; private: - static std::unordered_map *idCreateMap; - static std::unordered_map *classIdMap; - static std::unordered_map *numCreateMap; - static std::unordered_map *numClassMap; - static std::unordered_map *classNumMap; - static std::unordered_map *idNumMap; + static std::unordered_map* idCreateMap; + static std::unordered_map* classIdMap; + static std::unordered_map* numCreateMap; + static std::unordered_map* numClassMap; + static std::unordered_map* classNumMap; + static std::unordered_map* idNumMap; public: - static std::unordered_map idsSpawnableInCreative; + static std::unordered_map idsSpawnableInCreative; private: - static void setId(entityCreateFn createFn, eINSTANCEOF clas, const std::wstring &id, int idNum); - static void setId(entityCreateFn createFn, eINSTANCEOF clas, const std::wstring &id, int idNum, eMinecraftColour color1, eMinecraftColour color2, int nameId); + static void setId(entityCreateFn createFn, eINSTANCEOF clas, + const std::wstring& id, int idNum); + static void setId(entityCreateFn createFn, eINSTANCEOF clas, + const std::wstring& id, int idNum, + eMinecraftColour color1, eMinecraftColour color2, + int nameId); public: - static void staticCtor(); - static std::shared_ptr newEntity(const std::wstring& id, Level *level); - static std::shared_ptr loadStatic(CompoundTag *tag, Level *level); - static std::shared_ptr newById(int id, Level *level); - static std::shared_ptr newByEnumType(eINSTANCEOF eType, Level *level); - static int getId(std::shared_ptr entity); - static std::wstring getEncodeId(std::shared_ptr entity); - static int getId(const std::wstring &encodeId); - static std::wstring getEncodeId(int entityIoValue); - static int getNameId(int entityIoValue); - static eINSTANCEOF getType(const std::wstring &idString); - static eINSTANCEOF getClass(int id); + static void staticCtor(); + static std::shared_ptr newEntity(const std::wstring& id, + Level* level); + static std::shared_ptr loadStatic(CompoundTag* tag, Level* level); + static std::shared_ptr newById(int id, Level* level); + static std::shared_ptr newByEnumType(eINSTANCEOF eType, + Level* level); + static int getId(std::shared_ptr entity); + static std::wstring getEncodeId(std::shared_ptr entity); + static int getId(const std::wstring& encodeId); + static std::wstring getEncodeId(int entityIoValue); + static int getNameId(int entityIoValue); + static eINSTANCEOF getType(const std::wstring& idString); + static eINSTANCEOF getClass(int id); - // 4J-JEV, added for enumerating mobs. - static int eTypeToIoid(eINSTANCEOF eType); + // 4J-JEV, added for enumerating mobs. + static int eTypeToIoid(eINSTANCEOF eType); }; diff --git a/Minecraft.World/Level/Storage/LevelSettings.cpp b/Minecraft.World/Level/Storage/LevelSettings.cpp index 2a6bcf73e..94557e120 100644 --- a/Minecraft.World/Level/Storage/LevelSettings.cpp +++ b/Minecraft.World/Level/Storage/LevelSettings.cpp @@ -3,183 +3,142 @@ #include "../../Headers/net.minecraft.world.level.storage.h" #include "LevelType.h" -GameType *GameType::NOT_SET = NULL; -GameType *GameType::SURVIVAL= NULL; -GameType *GameType::CREATIVE = NULL; -GameType *GameType::ADVENTURE = NULL; +GameType* GameType::NOT_SET = NULL; +GameType* GameType::SURVIVAL = NULL; +GameType* GameType::CREATIVE = NULL; +GameType* GameType::ADVENTURE = NULL; -void GameType::staticCtor() -{ - NOT_SET = new GameType(-1, L""); - SURVIVAL = new GameType(0, L"survival"); - CREATIVE = new GameType(1, L"creative"); - ADVENTURE = new GameType(2, L"adventure"); +void GameType::staticCtor() { + NOT_SET = new GameType(-1, L""); + SURVIVAL = new GameType(0, L"survival"); + CREATIVE = new GameType(1, L"creative"); + ADVENTURE = new GameType(2, L"adventure"); } -GameType::GameType(int id, const std::wstring &name) -{ - this->id = id; - this->name = name; +GameType::GameType(int id, const std::wstring& name) { + this->id = id; + this->name = name; } -int GameType::getId() -{ - return id; +int GameType::getId() { return id; } + +std::wstring GameType::getName() { return name; } + +void GameType::updatePlayerAbilities(Abilities* abilities) { + if (this == CREATIVE) { + abilities->mayfly = true; + abilities->instabuild = true; + abilities->invulnerable = true; + } else { + abilities->mayfly = false; + abilities->instabuild = false; + abilities->invulnerable = false; + abilities->flying = false; + } + abilities->mayBuild = !isReadOnly(); } -std::wstring GameType::getName() -{ - return name; +bool GameType::isReadOnly() { return this == ADVENTURE; } + +bool GameType::isCreative() { return this == CREATIVE; } + +bool GameType::isSurvival() { return this == SURVIVAL || this == ADVENTURE; } + +GameType* GameType::byId(int id) { + if (id == NOT_SET->id) + return NOT_SET; + else if (id == SURVIVAL->id) + return SURVIVAL; + else if (id == CREATIVE->id) + return CREATIVE; + else if (id == ADVENTURE->id) + return ADVENTURE; + + return SURVIVAL; } -void GameType::updatePlayerAbilities(Abilities *abilities) -{ - if (this == CREATIVE) - { - abilities->mayfly = true; - abilities->instabuild = true; - abilities->invulnerable = true; - } - else - { - abilities->mayfly = false; - abilities->instabuild = false; - abilities->invulnerable = false; - abilities->flying = false; - } - abilities->mayBuild = !isReadOnly(); +GameType* GameType::byName(const std::wstring& name) { + if (name.compare(NOT_SET->name) == 0) + return NOT_SET; + else if (name.compare(SURVIVAL->name) == 0) + return SURVIVAL; + else if (name.compare(CREATIVE->name) == 0) + return CREATIVE; + else if (name.compare(ADVENTURE->name) == 0) + return ADVENTURE; + + return SURVIVAL; } -bool GameType::isReadOnly() -{ - return this == ADVENTURE; +void LevelSettings::_init(__int64 seed, GameType* gameType, + bool generateMapFeatures, bool hardcore, + bool newSeaLevel, LevelType* levelType, int xzSize, + int hellScale) { + this->seed = seed; + this->gameType = gameType; + this->hardcore = hardcore; + this->generateMapFeatures = generateMapFeatures; + this->newSeaLevel = newSeaLevel; + this->levelType = levelType; + this->allowCommands = false; + this->startingBonusItems = false; + m_xzSize = xzSize; + m_hellScale = hellScale; } -bool GameType::isCreative() -{ - return this == CREATIVE; +LevelSettings::LevelSettings(__int64 seed, GameType* gameType, + bool generateMapFeatures, bool hardcore, + bool newSeaLevel, LevelType* levelType, int xzSize, + int hellScale) + : seed(seed), + gameType(gameType), + hardcore(hardcore), + generateMapFeatures(generateMapFeatures), + newSeaLevel(newSeaLevel), + levelType(levelType), + startingBonusItems(false) { + _init(seed, gameType, generateMapFeatures, hardcore, newSeaLevel, levelType, + xzSize, hellScale); } -bool GameType::isSurvival() -{ - return this == SURVIVAL || this == ADVENTURE; +LevelSettings::LevelSettings(LevelData* levelData) { + _init(levelData->getSeed(), levelData->getGameType(), + levelData->isGenerateMapFeatures(), levelData->isHardcore(), + levelData->useNewSeaLevel(), levelData->getGenerator(), + levelData->getXZSize(), levelData->getHellScale()); } -GameType *GameType::byId(int id) -{ - if(id == NOT_SET->id) return NOT_SET; - else if(id == SURVIVAL->id) return SURVIVAL; - else if(id == CREATIVE->id) return CREATIVE; - else if(id == ADVENTURE->id) return ADVENTURE; - - return SURVIVAL; +LevelSettings* LevelSettings::enableStartingBonusItems() { + startingBonusItems = true; + return this; } -GameType *GameType::byName(const std::wstring &name) -{ - if(name.compare(NOT_SET->name) == 0) return NOT_SET; - else if(name.compare(SURVIVAL->name) == 0) return SURVIVAL; - else if(name.compare(CREATIVE->name) == 0) return CREATIVE; - else if(name.compare(ADVENTURE->name) == 0) return ADVENTURE; - - return SURVIVAL; +LevelSettings* LevelSettings::enableSinglePlayerCommands() { + allowCommands = true; + return this; } -void LevelSettings::_init(__int64 seed, GameType *gameType, bool generateMapFeatures, bool hardcore, bool newSeaLevel, LevelType *levelType, int xzSize, int hellScale) -{ - this->seed = seed; - this->gameType = gameType; - this->hardcore = hardcore; - this->generateMapFeatures = generateMapFeatures; - this->newSeaLevel = newSeaLevel; - this->levelType = levelType; - this->allowCommands = false; - this->startingBonusItems = false; - m_xzSize = xzSize; - m_hellScale = hellScale; +bool LevelSettings::hasStartingBonusItems() { return startingBonusItems; } + +__int64 LevelSettings::getSeed() { return seed; } + +GameType* LevelSettings::getGameType() { return gameType; } + +bool LevelSettings::isHardcore() { return hardcore; } + +LevelType* LevelSettings::getLevelType() { return levelType; } + +bool LevelSettings::getAllowCommands() { return allowCommands; } + +bool LevelSettings::isGenerateMapFeatures() { return generateMapFeatures; } + +GameType* LevelSettings::validateGameType(int gameType) { + return GameType::byId(gameType); } -LevelSettings::LevelSettings(__int64 seed, GameType *gameType, bool generateMapFeatures, bool hardcore, bool newSeaLevel, LevelType *levelType, int xzSize, int hellScale) : - seed(seed), - gameType(gameType), - hardcore(hardcore), - generateMapFeatures(generateMapFeatures), - newSeaLevel(newSeaLevel), - levelType(levelType), - startingBonusItems(false) -{ - _init(seed, gameType, generateMapFeatures, hardcore, newSeaLevel, levelType, xzSize, hellScale); -} - -LevelSettings::LevelSettings(LevelData *levelData) -{ - _init(levelData->getSeed(), levelData->getGameType(), levelData->isGenerateMapFeatures(), levelData->isHardcore(), levelData->useNewSeaLevel(), levelData->getGenerator(), levelData->getXZSize(), levelData->getHellScale() ); -} - -LevelSettings *LevelSettings::enableStartingBonusItems() -{ - startingBonusItems = true; - return this; -} - -LevelSettings *LevelSettings::enableSinglePlayerCommands() -{ - allowCommands = true; - return this; -} - -bool LevelSettings::hasStartingBonusItems() -{ - return startingBonusItems; -} - -__int64 LevelSettings::getSeed() -{ - return seed; -} - -GameType *LevelSettings::getGameType() -{ - return gameType; -} - -bool LevelSettings::isHardcore() -{ - return hardcore; -} - -LevelType *LevelSettings::getLevelType() -{ - return levelType; -} - -bool LevelSettings::getAllowCommands() -{ - return allowCommands; -} - -bool LevelSettings::isGenerateMapFeatures() -{ - return generateMapFeatures; -} - -GameType *LevelSettings::validateGameType(int gameType) -{ - return GameType::byId(gameType); -} - -bool LevelSettings::useNewSeaLevel() -{ - return newSeaLevel; -} +bool LevelSettings::useNewSeaLevel() { return newSeaLevel; } // 4J Added -int LevelSettings::getXZSize() -{ - return m_xzSize; -} +int LevelSettings::getXZSize() { return m_xzSize; } -int LevelSettings::getHellScale() -{ - return m_hellScale; -} +int LevelSettings::getHellScale() { return m_hellScale; } diff --git a/Minecraft.World/Level/Storage/LevelSettings.h b/Minecraft.World/Level/Storage/LevelSettings.h index dd3d26a66..bf50f56b7 100644 --- a/Minecraft.World/Level/Storage/LevelSettings.h +++ b/Minecraft.World/Level/Storage/LevelSettings.h @@ -5,63 +5,68 @@ class Abilities; class LevelData; // 4J Stu - Was Java enum class -class GameType -{ +class GameType { public: - static GameType *NOT_SET; - static GameType *SURVIVAL; - static GameType *CREATIVE; - static GameType *ADVENTURE; + static GameType* NOT_SET; + static GameType* SURVIVAL; + static GameType* CREATIVE; + static GameType* ADVENTURE; - static void staticCtor(); + static void staticCtor(); private: - int id; - std::wstring name; + int id; + std::wstring name; - GameType(int id, const std::wstring &name); + GameType(int id, const std::wstring& name); public: - int getId(); - std::wstring getName(); - void updatePlayerAbilities(Abilities *abilities); - bool isReadOnly(); - bool isCreative(); - bool isSurvival(); - static GameType *byId(int id); - static GameType *byName(const std::wstring &name); + int getId(); + std::wstring getName(); + void updatePlayerAbilities(Abilities* abilities); + bool isReadOnly(); + bool isCreative(); + bool isSurvival(); + static GameType* byId(int id); + static GameType* byName(const std::wstring& name); }; -class LevelSettings -{ +class LevelSettings { private: - __int64 seed; - GameType *gameType; - bool generateMapFeatures; - bool hardcore; - bool newSeaLevel; - LevelType *levelType; - bool allowCommands; - bool startingBonusItems; // 4J - brought forward from 1.3.2 - int m_xzSize; // 4J Added - int m_hellScale; + __int64 seed; + GameType* gameType; + bool generateMapFeatures; + bool hardcore; + bool newSeaLevel; + LevelType* levelType; + bool allowCommands; + bool startingBonusItems; // 4J - brought forward from 1.3.2 + int m_xzSize; // 4J Added + int m_hellScale; - void _init(__int64 seed, GameType *gameType, bool generateMapFeatures, bool hardcore, bool newSeaLevel, LevelType *levelType, int xzSize, int hellScale); // 4J Added xzSize and hellScale param + void _init(__int64 seed, GameType* gameType, bool generateMapFeatures, + bool hardcore, bool newSeaLevel, LevelType* levelType, + int xzSize, + int hellScale); // 4J Added xzSize and hellScale param public: - LevelSettings(__int64 seed, GameType *gameType, bool generateMapFeatures, bool hardcore, bool newSeaLevel, LevelType *levelType, int xzSize, int hellScale); // 4J Added xzSize and hellScale param - LevelSettings(LevelData *levelData); - LevelSettings *enableStartingBonusItems(); // 4J - brought forward from 1.3.2 - LevelSettings *enableSinglePlayerCommands(); - bool hasStartingBonusItems(); // 4J - brought forward from 1.3.2 - __int64 getSeed(); - GameType *getGameType(); - bool isHardcore(); - LevelType *getLevelType(); - bool getAllowCommands(); - bool isGenerateMapFeatures(); - bool useNewSeaLevel(); - int getXZSize(); // 4J Added - int getHellScale(); // 4J Added - static GameType *validateGameType(int gameType); + LevelSettings(__int64 seed, GameType* gameType, bool generateMapFeatures, + bool hardcore, bool newSeaLevel, LevelType* levelType, + int xzSize, + int hellScale); // 4J Added xzSize and hellScale param + LevelSettings(LevelData* levelData); + LevelSettings* + enableStartingBonusItems(); // 4J - brought forward from 1.3.2 + LevelSettings* enableSinglePlayerCommands(); + bool hasStartingBonusItems(); // 4J - brought forward from 1.3.2 + __int64 getSeed(); + GameType* getGameType(); + bool isHardcore(); + LevelType* getLevelType(); + bool getAllowCommands(); + bool isGenerateMapFeatures(); + bool useNewSeaLevel(); + int getXZSize(); // 4J Added + int getHellScale(); // 4J Added + static GameType* validateGameType(int gameType); }; diff --git a/Minecraft.World/Level/Storage/LevelSource.h b/Minecraft.World/Level/Storage/LevelSource.h index b3071783e..bfc151090 100644 --- a/Minecraft.World/Level/Storage/LevelSource.h +++ b/Minecraft.World/Level/Storage/LevelSource.h @@ -6,24 +6,26 @@ class TileEntity; #include "../../Util/LightLayer.h" -class LevelSource -{ +class LevelSource { public: - virtual int getTile(int x, int y, int z) = 0; - virtual std::shared_ptr getTileEntity(int x, int y, int z) = 0; - virtual int getLightColor(int x, int y, int z, int emitt, int tileId = -1) = 0; // 4J - brought forward from 1.8.2, added tileId - virtual float getBrightness(int x, int y, int z, int emitt) = 0; - virtual float getBrightness(int x, int y, int z) = 0; - virtual int getData(int x, int y, int z) = 0; - virtual Material *getMaterial(int xx, int i, int zz) = 0; - virtual bool isSolidRenderTile(int x, int y, int z) = 0; - virtual bool isSolidBlockingTile(int x, int y, int z) = 0; - virtual bool isEmptyTile(int x, int y, int z) = 0; - virtual Biome *getBiome(int x, int z) = 0; - virtual BiomeSource *getBiomeSource() = 0; - virtual int getBrightness(LightLayer::variety layer, int x, int y, int z) = 0; - virtual int getMaxBuildHeight() = 0; - virtual bool isAllEmpty() = 0; - virtual bool isTopSolidBlocking(int x, int y, int z) = 0; - virtual ~LevelSource() {} + virtual int getTile(int x, int y, int z) = 0; + virtual std::shared_ptr getTileEntity(int x, int y, int z) = 0; + virtual int getLightColor( + int x, int y, int z, int emitt, + int tileId = -1) = 0; // 4J - brought forward from 1.8.2, added tileId + virtual float getBrightness(int x, int y, int z, int emitt) = 0; + virtual float getBrightness(int x, int y, int z) = 0; + virtual int getData(int x, int y, int z) = 0; + virtual Material* getMaterial(int xx, int i, int zz) = 0; + virtual bool isSolidRenderTile(int x, int y, int z) = 0; + virtual bool isSolidBlockingTile(int x, int y, int z) = 0; + virtual bool isEmptyTile(int x, int y, int z) = 0; + virtual Biome* getBiome(int x, int z) = 0; + virtual BiomeSource* getBiomeSource() = 0; + virtual int getBrightness(LightLayer::variety layer, int x, int y, + int z) = 0; + virtual int getMaxBuildHeight() = 0; + virtual bool isAllEmpty() = 0; + virtual bool isTopSolidBlocking(int x, int y, int z) = 0; + virtual ~LevelSource() {} }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/LevelStorage.h b/Minecraft.World/Level/Storage/LevelStorage.h index 1ed3f5b34..9029934ce 100644 --- a/Minecraft.World/Level/Storage/LevelStorage.h +++ b/Minecraft.World/Level/Storage/LevelStorage.h @@ -1,6 +1,5 @@ #pragma once - #include "../../IO/Files/ConsoleSavePath.h" class PlayerIO; @@ -12,27 +11,31 @@ class File; class ConsoleSaveFile; -class LevelStorage -{ +class LevelStorage { public: - static const std::wstring NETHER_FOLDER; - static const std::wstring ENDER_FOLDER; + static const std::wstring NETHER_FOLDER; + static const std::wstring ENDER_FOLDER; - virtual ~LevelStorage(){} - virtual LevelData *prepareLevel() = 0; + virtual ~LevelStorage() {} + virtual LevelData* prepareLevel() = 0; virtual void checkSession() = 0; - virtual ChunkStorage *createChunkStorage(Dimension *dimension) = 0; - virtual void saveLevelData(LevelData *levelData, std::vector > *players) = 0; - virtual void saveLevelData(LevelData *levelData) = 0; - virtual PlayerIO *getPlayerIO() = 0; + virtual ChunkStorage* createChunkStorage(Dimension* dimension) = 0; + virtual void saveLevelData( + LevelData* levelData, + std::vector >* players) = 0; + virtual void saveLevelData(LevelData* levelData) = 0; + virtual PlayerIO* getPlayerIO() = 0; virtual void closeAll() = 0; virtual ConsoleSavePath getDataFile(const std::wstring& id) = 0; - virtual std::wstring getLevelId() = 0; + virtual std::wstring getLevelId() = 0; public: - virtual ConsoleSaveFile *getSaveFile() { return NULL; } - virtual void flushSaveFile(bool autosave) {} + virtual ConsoleSaveFile* getSaveFile() { return NULL; } + virtual void flushSaveFile(bool autosave) {} - // 4J Added - virtual int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale) { return 0; } + // 4J Added + virtual int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, + int centreZC, int scale) { + return 0; + } }; diff --git a/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.cpp b/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.cpp index b815c991a..05fdd2427 100644 --- a/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.cpp +++ b/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.cpp @@ -7,51 +7,46 @@ #include "../../IO/Files/ConsoleSaveFileIO.h" -LevelStorageProfilerDecorator::LevelStorageProfilerDecorator(LevelStorage *capsulated) : capsulated ( capsulated ) -{ +LevelStorageProfilerDecorator::LevelStorageProfilerDecorator( + LevelStorage* capsulated) + : capsulated(capsulated) {} + +LevelData* LevelStorageProfilerDecorator::prepareLevel() { + return capsulated->prepareLevel(); } -LevelData *LevelStorageProfilerDecorator::prepareLevel() +void LevelStorageProfilerDecorator::checkSession() // throws + // LevelConflictException { - return capsulated->prepareLevel(); + capsulated->checkSession(); } -void LevelStorageProfilerDecorator::checkSession() // throws LevelConflictException -{ - capsulated->checkSession(); +ChunkStorage* LevelStorageProfilerDecorator::createChunkStorage( + Dimension* dimension) { + return new ChunkStorageProfilerDecorator( + capsulated->createChunkStorage(dimension)); } -ChunkStorage *LevelStorageProfilerDecorator::createChunkStorage(Dimension *dimension) -{ - return new ChunkStorageProfilerDecorator(capsulated->createChunkStorage(dimension)); +void LevelStorageProfilerDecorator::saveLevelData( + LevelData* levelData, std::vector >* players) { + capsulated->saveLevelData(levelData, players); } -void LevelStorageProfilerDecorator::saveLevelData(LevelData *levelData, std::vector > *players) -{ - capsulated->saveLevelData(levelData, players); +void LevelStorageProfilerDecorator::saveLevelData(LevelData* levelData) { + capsulated->saveLevelData(levelData); } -void LevelStorageProfilerDecorator::saveLevelData(LevelData *levelData) -{ - capsulated->saveLevelData(levelData); +PlayerIO* LevelStorageProfilerDecorator::getPlayerIO() { + return capsulated->getPlayerIO(); } -PlayerIO *LevelStorageProfilerDecorator::getPlayerIO() -{ - return capsulated->getPlayerIO(); +void LevelStorageProfilerDecorator::closeAll() { capsulated->closeAll(); } + +ConsoleSavePath LevelStorageProfilerDecorator::getDataFile( + const std::wstring& id) { + return capsulated->getDataFile(id); } -void LevelStorageProfilerDecorator::closeAll() -{ - capsulated->closeAll(); -} - -ConsoleSavePath LevelStorageProfilerDecorator::getDataFile(const std::wstring& id) -{ - return capsulated->getDataFile(id); -} - -std::wstring LevelStorageProfilerDecorator::getLevelId() -{ - return capsulated->getLevelId(); +std::wstring LevelStorageProfilerDecorator::getLevelId() { + return capsulated->getLevelId(); } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.h b/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.h index 477e141f7..7eb76a3f6 100644 --- a/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.h +++ b/Minecraft.World/Level/Storage/LevelStorageProfilerDecorator.h @@ -1,27 +1,26 @@ #pragma once - #include "LevelStorage.h" class ConsoleSaveFile; -class LevelStorageProfilerDecorator : public LevelStorage -{ +class LevelStorageProfilerDecorator : public LevelStorage { private: - /* final */ LevelStorage *capsulated; + /* final */ LevelStorage* capsulated; public: - virtual ConsoleSaveFile *getSaveFile() { return capsulated->getSaveFile(); } + virtual ConsoleSaveFile* getSaveFile() { return capsulated->getSaveFile(); } public: - LevelStorageProfilerDecorator(LevelStorage *capsulated); - LevelData *prepareLevel(); + LevelStorageProfilerDecorator(LevelStorage* capsulated); + LevelData* prepareLevel(); void checkSession(); - ChunkStorage *createChunkStorage(Dimension *dimension); - void saveLevelData(LevelData *levelData, std::vector > *players); - void saveLevelData(LevelData *levelData); - PlayerIO *getPlayerIO(); + ChunkStorage* createChunkStorage(Dimension* dimension); + void saveLevelData(LevelData* levelData, + std::vector >* players); + void saveLevelData(LevelData* levelData); + PlayerIO* getPlayerIO(); void closeAll(); ConsoleSavePath getDataFile(const std::wstring& id); - std::wstring getLevelId(); + std::wstring getLevelId(); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/LevelStorageSource.h b/Minecraft.World/Level/Storage/LevelStorageSource.h index 86a3ce247..8d3e84da6 100644 --- a/Minecraft.World/Level/Storage/LevelStorageSource.h +++ b/Minecraft.World/Level/Storage/LevelStorageSource.h @@ -1,6 +1,5 @@ #pragma once - #include "../../Platform/stdafx.h" class LevelSummary; @@ -9,14 +8,16 @@ class LevelData; class LevelStorage; class ConsoleSaveFile; -class LevelStorageSource -{ +class LevelStorageSource { public: - virtual std::wstring getName() = 0; - virtual std::shared_ptr selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, bool createPlayerDir) = 0; - virtual std::vector *getLevelList() = 0; + virtual std::wstring getName() = 0; + virtual std::shared_ptr selectLevel( + ConsoleSaveFile* saveFile, const std::wstring& levelId, + bool createPlayerDir) = 0; + virtual std::vector* getLevelList() = 0; virtual void clearAll() = 0; - virtual LevelData *getDataTagFor(ConsoleSaveFile *saveFile, const std::wstring& levelId) = 0; + virtual LevelData* getDataTagFor(ConsoleSaveFile* saveFile, + const std::wstring& levelId) = 0; /** * Tests if a levelId can be used to store a level. For example, a levelId @@ -24,14 +25,19 @@ public: * handle. *

* Also, a new levelId may not overwrite an existing one. - * + * * @param levelId * @return */ virtual bool isNewLevelIdAcceptable(const std::wstring& levelId) = 0; virtual void deleteLevel(const std::wstring& levelId) = 0; - virtual void renameLevel(const std::wstring& levelId, const std::wstring& newLevelName) = 0; - virtual bool isConvertible(ConsoleSaveFile *saveFile, const std::wstring& levelId) = 0; - virtual bool requiresConversion(ConsoleSaveFile *saveFile, const std::wstring& levelId) = 0; - virtual bool convertLevel(ConsoleSaveFile *saveFile, const std::wstring &levelId, ProgressListener *progress) = 0; + virtual void renameLevel(const std::wstring& levelId, + const std::wstring& newLevelName) = 0; + virtual bool isConvertible(ConsoleSaveFile* saveFile, + const std::wstring& levelId) = 0; + virtual bool requiresConversion(ConsoleSaveFile* saveFile, + const std::wstring& levelId) = 0; + virtual bool convertLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + ProgressListener* progress) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/LevelSummary.cpp b/Minecraft.World/Level/Storage/LevelSummary.cpp index 71d646261..88c82915f 100644 --- a/Minecraft.World/Level/Storage/LevelSummary.cpp +++ b/Minecraft.World/Level/Storage/LevelSummary.cpp @@ -1,69 +1,44 @@ #include "../../Platform/stdafx.h" #include "LevelSummary.h" -LevelSummary::LevelSummary(const std::wstring& levelId, const std::wstring& levelName, __int64 lastPlayed, __int64 sizeOnDisk, GameType *gameMode, bool requiresConversion, bool hardcore, bool hasCheats) : - levelId( levelId ), - levelName( levelName ), - lastPlayed( lastPlayed ), - sizeOnDisk( sizeOnDisk ), - gameMode( gameMode ), - requiresConversion( requiresConversion ), - hardcore( hardcore ), - _hasCheats( hasCheats ) -{ +LevelSummary::LevelSummary(const std::wstring& levelId, + const std::wstring& levelName, __int64 lastPlayed, + __int64 sizeOnDisk, GameType* gameMode, + bool requiresConversion, bool hardcore, + bool hasCheats) + : levelId(levelId), + levelName(levelName), + lastPlayed(lastPlayed), + sizeOnDisk(sizeOnDisk), + gameMode(gameMode), + requiresConversion(requiresConversion), + hardcore(hardcore), + _hasCheats(hasCheats) {} + +std::wstring LevelSummary::getLevelId() { return levelId; } + +std::wstring LevelSummary::getLevelName() { return levelName; } + +__int64 LevelSummary::getSizeOnDisk() { return sizeOnDisk; } + +bool LevelSummary::isRequiresConversion() { return requiresConversion; } + +__int64 LevelSummary::getLastPlayed() { return lastPlayed; } + +int LevelSummary::compareTo(LevelSummary* rhs) { + if (lastPlayed < rhs->lastPlayed) { + return 1; + } + if (lastPlayed > rhs->lastPlayed) { + return -1; + } + + // TODO 4J Jev, used to be compareTo in java, is this right? + return levelId.compare(rhs->levelId); } -std::wstring LevelSummary::getLevelId() -{ - return levelId; -} +GameType* LevelSummary::getGameMode() { return gameMode; } -std::wstring LevelSummary::getLevelName() -{ - return levelName; -} +bool LevelSummary::isHardcore() { return hardcore; } -__int64 LevelSummary::getSizeOnDisk() -{ - return sizeOnDisk; -} - -bool LevelSummary::isRequiresConversion() -{ - return requiresConversion; -} - -__int64 LevelSummary::getLastPlayed() -{ - return lastPlayed; -} - -int LevelSummary::compareTo(LevelSummary *rhs) -{ - if (lastPlayed < rhs->lastPlayed) - { - return 1; - } - if (lastPlayed > rhs->lastPlayed) - { - return -1; - } - - // TODO 4J Jev, used to be compareTo in java, is this right? - return levelId.compare(rhs->levelId); -} - -GameType *LevelSummary::getGameMode() -{ - return gameMode; -} - -bool LevelSummary::isHardcore() -{ - return hardcore; -} - -bool LevelSummary::hasCheats() -{ - return _hasCheats; -} \ No newline at end of file +bool LevelSummary::hasCheats() { return _hasCheats; } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/LevelSummary.h b/Minecraft.World/Level/Storage/LevelSummary.h index fbf0850c3..95ff7a5cb 100644 --- a/Minecraft.World/Level/Storage/LevelSummary.h +++ b/Minecraft.World/Level/Storage/LevelSummary.h @@ -1,28 +1,28 @@ #pragma once - class GameType; -class LevelSummary -{ - const std::wstring levelId; +class LevelSummary { + const std::wstring levelId; const std::wstring levelName; const __int64 lastPlayed; const __int64 sizeOnDisk; const bool requiresConversion; - GameType *gameMode; - const bool hardcore; - const bool _hasCheats; + GameType* gameMode; + const bool hardcore; + const bool _hasCheats; public: - LevelSummary(const std::wstring& levelId, const std::wstring& levelName, __int64 lastPlayed, __int64 sizeOnDisk, GameType *gameMode, bool requiresConversion, bool hardcore, bool hasCheats); + LevelSummary(const std::wstring& levelId, const std::wstring& levelName, + __int64 lastPlayed, __int64 sizeOnDisk, GameType* gameMode, + bool requiresConversion, bool hardcore, bool hasCheats); std::wstring getLevelId(); std::wstring getLevelName(); __int64 getSizeOnDisk(); bool isRequiresConversion(); __int64 getLastPlayed(); - int compareTo(LevelSummary *rhs); - GameType *getGameMode(); - bool isHardcore(); - bool hasCheats(); + int compareTo(LevelSummary* rhs); + GameType* getGameMode(); + bool isHardcore(); + bool hasCheats(); }; diff --git a/Minecraft.World/Level/Storage/LevelType.cpp b/Minecraft.World/Level/Storage/LevelType.cpp index e2c1f3f95..48b77d154 100644 --- a/Minecraft.World/Level/Storage/LevelType.cpp +++ b/Minecraft.World/Level/Storage/LevelType.cpp @@ -1,117 +1,92 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.h" - // public static final LevelType[] levelTypes = new LevelType[16]; -// -// +// +// -// -// +// +// // private final String generatorName; // private final int version; // private boolean selectable; // private boolean replacement; -LevelType *LevelType::levelTypes[16];// = new LevelType[16]; -LevelType *LevelType::lvl_normal=NULL;// = new LevelType(0, "default", 1).setHasReplacement(); -LevelType *LevelType::lvl_flat=NULL;// = new LevelType(1, "flat"); -LevelType *LevelType::lvl_largeBiomes = NULL;// = new LevelType(2, "largeBiomes"); -LevelType *LevelType::lvl_normal_1_1=NULL;// = new LevelType(8, "default_1_1", 0).setSelectableByUser(false); +LevelType* LevelType::levelTypes[16]; // = new LevelType[16]; +LevelType* LevelType::lvl_normal = + NULL; // = new LevelType(0, "default", 1).setHasReplacement(); +LevelType* LevelType::lvl_flat = NULL; // = new LevelType(1, "flat"); +LevelType* LevelType::lvl_largeBiomes = + NULL; // = new LevelType(2, "largeBiomes"); +LevelType* LevelType::lvl_normal_1_1 = + NULL; // = new LevelType(8, "default_1_1", 0).setSelectableByUser(false); -void LevelType::staticCtor() -{ - for(int i=0;i<16;i++) levelTypes[i]=NULL; - lvl_normal = new LevelType(0, L"default", 1); - lvl_normal->setHasReplacement(); - lvl_flat = new LevelType(1, L"flat"); - lvl_largeBiomes = new LevelType(2, L"largeBiomes"); - lvl_normal_1_1 = new LevelType(8, L"default_1_1", 0); - lvl_normal_1_1->setSelectableByUser(false); +void LevelType::staticCtor() { + for (int i = 0; i < 16; i++) levelTypes[i] = NULL; + lvl_normal = new LevelType(0, L"default", 1); + lvl_normal->setHasReplacement(); + lvl_flat = new LevelType(1, L"flat"); + lvl_largeBiomes = new LevelType(2, L"largeBiomes"); + lvl_normal_1_1 = new LevelType(8, L"default_1_1", 0); + lvl_normal_1_1->setSelectableByUser(false); } -LevelType::LevelType(int id, std::wstring generatorName) -{ - init(id, generatorName, 0); +LevelType::LevelType(int id, std::wstring generatorName) { + init(id, generatorName, 0); } -LevelType::LevelType(int id, std::wstring generatorName, int version) -{ - m_generatorName = generatorName; - m_version = version; - m_selectable = true; - levelTypes[id] = this; +LevelType::LevelType(int id, std::wstring generatorName, int version) { + m_generatorName = generatorName; + m_version = version; + m_selectable = true; + levelTypes[id] = this; } - -void LevelType::init(int id, std::wstring generatorName, int version) -{ - m_generatorName = generatorName; - m_version = version; - m_selectable = true; - levelTypes[id] = this; +void LevelType::init(int id, std::wstring generatorName, int version) { + m_generatorName = generatorName; + m_version = version; + m_selectable = true; + levelTypes[id] = this; } -std::wstring LevelType::getGeneratorName() -{ - return m_generatorName; +std::wstring LevelType::getGeneratorName() { return m_generatorName; } + +std::wstring LevelType::getDescriptionId() { + return L"generator." + m_generatorName; } -std::wstring LevelType::getDescriptionId() -{ - return L"generator." + m_generatorName; +int LevelType::getVersion() { return m_version; } + +LevelType* LevelType::getReplacementForVersion(int oldVersion) { + if (this == lvl_normal && oldVersion == 0) { + return lvl_normal_1_1; + } + return this; } -int LevelType::getVersion() -{ - return m_version; +LevelType* LevelType::setSelectableByUser(bool selectable) { + m_selectable = selectable; + return this; } -LevelType *LevelType::getReplacementForVersion(int oldVersion) -{ - if (this == lvl_normal && oldVersion == 0) - { - return lvl_normal_1_1; - } - return this; +bool LevelType::isSelectable() { return m_selectable; } + +LevelType* LevelType::setHasReplacement() { + m_replacement = true; + return this; } -LevelType *LevelType::setSelectableByUser(bool selectable) -{ - m_selectable = selectable; - return this; +bool LevelType::hasReplacement() { return m_replacement; } + +LevelType* LevelType::getLevelType(std::wstring name) { + if (name.length() > 0) { + for (int i = 0; i < 16; i++) { + // Fix: check NULL before accessing member to avoid null dereference + if (levelTypes[i] != NULL && + (levelTypes[i]->m_generatorName.compare(name) == 0)) { + return levelTypes[i]; + } + } + } + return NULL; } - -bool LevelType::isSelectable() -{ - return m_selectable; -} - -LevelType *LevelType::setHasReplacement() -{ - m_replacement = true; - return this; -} - -bool LevelType::hasReplacement() -{ - return m_replacement; -} - -LevelType *LevelType::getLevelType(std::wstring name) -{ - if(name.length()>0) - { - for (int i = 0; i < 16; i++) - { - // Fix: check NULL before accessing member to avoid null dereference - if (levelTypes[i] != NULL && (levelTypes[i]->m_generatorName.compare(name)==0)) - { - return levelTypes[i]; - } - } - } - return NULL; -} - - diff --git a/Minecraft.World/Level/Storage/LevelType.h b/Minecraft.World/Level/Storage/LevelType.h index a62b138d9..55bf7624a 100644 --- a/Minecraft.World/Level/Storage/LevelType.h +++ b/Minecraft.World/Level/Storage/LevelType.h @@ -2,38 +2,44 @@ #include "../../Headers/net.minecraft.world.level.h" -class LevelType -{ +class LevelType { public: - static LevelType *levelTypes[16];// = new LevelType[16]; - static LevelType *lvl_normal;// = new LevelType(0, "default", 1).setHasReplacement(); - static LevelType *lvl_flat;// = new LevelType(1, "flat"); - static LevelType *lvl_largeBiomes;// = new LevelType(2, "largeBiomes"); - static LevelType *lvl_normal_1_1;// = new LevelType(8, "default_1_1", 0).setSelectableByUser(false); + static LevelType* levelTypes[16]; // = new LevelType[16]; + static LevelType* + lvl_normal; // = new LevelType(0, "default", 1).setHasReplacement(); + static LevelType* lvl_flat; // = new LevelType(1, "flat"); + static LevelType* lvl_largeBiomes; // = new LevelType(2, "largeBiomes"); + static LevelType* lvl_normal_1_1; // = new LevelType(8, "default_1_1", + // 0).setSelectableByUser(false); - static void staticCtor(); + static void staticCtor(); private: - std::wstring m_generatorName; - int m_version; - bool m_selectable; - bool m_replacement; + std::wstring m_generatorName; + int m_version; + bool m_selectable; + bool m_replacement; + + LevelType(int id, std::wstring generatorName); + LevelType(int id, std::wstring generatorName, int version); + void init(int id, std::wstring generatorName, int version); - LevelType(int id, std::wstring generatorName); - LevelType(int id, std::wstring generatorName, int version); - void init(int id, std::wstring generatorName, int version); public: - std::wstring getGeneratorName(); - std::wstring getDescriptionId(); - int getVersion(); - LevelType *getReplacementForVersion(int oldVersion); + std::wstring getGeneratorName(); + std::wstring getDescriptionId(); + int getVersion(); + LevelType* getReplacementForVersion(int oldVersion); + private: - LevelType *setSelectableByUser(bool selectable); + LevelType* setSelectableByUser(bool selectable); + public: - bool isSelectable(); + bool isSelectable(); + private: - LevelType *setHasReplacement(); + LevelType* setHasReplacement(); + public: - bool hasReplacement(); - static LevelType *getLevelType(std::wstring name); + bool hasReplacement(); + static LevelType* getLevelType(std::wstring name); }; diff --git a/Minecraft.World/Level/Storage/MapItemSavedData.cpp b/Minecraft.World/Level/Storage/MapItemSavedData.cpp index ae98d8698..664b3fcb5 100644 --- a/Minecraft.World/Level/Storage/MapItemSavedData.cpp +++ b/Minecraft.World/Level/Storage/MapItemSavedData.cpp @@ -13,344 +13,346 @@ const int MapItemSavedData::END_PORTAL_DECORATION_KEY = -1; // 4J added entityId param -MapItemSavedData::MapDecoration::MapDecoration(char img, char x, char y, char rot, int entityId, bool visible) -{ - this->img = img; - this->x = x; - this->y = y; - this->rot = rot; - this->entityId = entityId; - this->visible = visible; +MapItemSavedData::MapDecoration::MapDecoration(char img, char x, char y, + char rot, int entityId, + bool visible) { + this->img = img; + this->x = x; + this->y = y; + this->rot = rot; + this->entityId = entityId; + this->visible = visible; } -MapItemSavedData::HoldingPlayer::HoldingPlayer(std::shared_ptr player, const MapItemSavedData *parent) : parent( parent ), player( player ) -{ - // inited outside of ctor - rowsDirtyMin = intArray(MapItem::IMAGE_WIDTH); - rowsDirtyMax = intArray(MapItem::IMAGE_WIDTH); +MapItemSavedData::HoldingPlayer::HoldingPlayer(std::shared_ptr player, + const MapItemSavedData* parent) + : parent(parent), player(player) { + // inited outside of ctor + rowsDirtyMin = intArray(MapItem::IMAGE_WIDTH); + rowsDirtyMax = intArray(MapItem::IMAGE_WIDTH); - tick = 0; - sendPosTick = 0; + tick = 0; + sendPosTick = 0; - // java ctor - //this->player = player; - for (unsigned int i = 0; i < rowsDirtyMin.length; i++) - { - rowsDirtyMin[i] = 0; - rowsDirtyMax[i] = MapItem::IMAGE_HEIGHT - 1; - } + // java ctor + // this->player = player; + for (unsigned int i = 0; i < rowsDirtyMin.length; i++) { + rowsDirtyMin[i] = 0; + rowsDirtyMax[i] = MapItem::IMAGE_HEIGHT - 1; + } } -MapItemSavedData::HoldingPlayer::~HoldingPlayer() -{ - delete rowsDirtyMin.data; - delete rowsDirtyMax.data; - delete lastSentDecorations.data; +MapItemSavedData::HoldingPlayer::~HoldingPlayer() { + delete rowsDirtyMin.data; + delete rowsDirtyMax.data; + delete lastSentDecorations.data; } -charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(std::shared_ptr itemInstance) -{ - if (--sendPosTick < 0) - { - sendPosTick = 4; - - unsigned int playerDecorationsSize = (int)parent->decorations.size(); - unsigned int nonPlayerDecorationsSize = (int)parent->nonPlayerDecorations.size(); - charArray data = charArray( (playerDecorationsSize + nonPlayerDecorationsSize ) * DEC_PACKET_BYTES + 1); - data[0] = 1; - for (unsigned int i = 0; i < parent->decorations.size(); i++) - { - MapDecoration *md = parent->decorations.at(i); +charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket( + std::shared_ptr itemInstance) { + if (--sendPosTick < 0) { + sendPosTick = 4; + + unsigned int playerDecorationsSize = (int)parent->decorations.size(); + unsigned int nonPlayerDecorationsSize = + (int)parent->nonPlayerDecorations.size(); + charArray data = + charArray((playerDecorationsSize + nonPlayerDecorationsSize) * + DEC_PACKET_BYTES + + 1); + data[0] = 1; + for (unsigned int i = 0; i < parent->decorations.size(); i++) { + MapDecoration* md = parent->decorations.at(i); #ifdef _LARGE_WORLDS - data[i * DEC_PACKET_BYTES + 1] = (char) (md->img); - data[i * DEC_PACKET_BYTES + 8] = (char) (md->rot & 0xF); + data[i * DEC_PACKET_BYTES + 1] = (char)(md->img); + data[i * DEC_PACKET_BYTES + 8] = (char)(md->rot & 0xF); #else - data[i * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); + data[i * DEC_PACKET_BYTES + 1] = + (char)((md->img << 4) | (md->rot & 0xF)); #endif - data[i * DEC_PACKET_BYTES + 2] = md->x; - data[i * DEC_PACKET_BYTES + 3] = md->y; - data[i * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; - data[i * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; - data[i * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; - data[i * DEC_PACKET_BYTES + 7] = (md->entityId>>24) & 0x7F; - data[i * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; - } - unsigned int dataIndex = playerDecorationsSize; - for(AUTO_VAR(it, parent->nonPlayerDecorations.begin()); it != parent->nonPlayerDecorations.end(); ++it) - { - MapDecoration *md = it->second; + data[i * DEC_PACKET_BYTES + 2] = md->x; + data[i * DEC_PACKET_BYTES + 3] = md->y; + data[i * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; + data[i * DEC_PACKET_BYTES + 5] = (md->entityId >> 8) & 0xFF; + data[i * DEC_PACKET_BYTES + 6] = (md->entityId >> 16) & 0xFF; + data[i * DEC_PACKET_BYTES + 7] = (md->entityId >> 24) & 0x7F; + data[i * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; + } + unsigned int dataIndex = playerDecorationsSize; + for (AUTO_VAR(it, parent->nonPlayerDecorations.begin()); + it != parent->nonPlayerDecorations.end(); ++it) { + MapDecoration* md = it->second; #ifdef _LARGE_WORLDS - data[dataIndex * DEC_PACKET_BYTES + 1] = (char) (md->img); - data[dataIndex * DEC_PACKET_BYTES + 8] = (char) (md->rot & 0xF); + data[dataIndex * DEC_PACKET_BYTES + 1] = (char)(md->img); + data[dataIndex * DEC_PACKET_BYTES + 8] = (char)(md->rot & 0xF); #else - data[dataIndex * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); + data[dataIndex * DEC_PACKET_BYTES + 1] = + (char)((md->img << 4) | (md->rot & 0xF)); #endif - data[dataIndex * DEC_PACKET_BYTES + 2] = md->x; - data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; - data[dataIndex * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; - data[dataIndex * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; - data[dataIndex * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; - data[dataIndex * DEC_PACKET_BYTES + 7] = (md->entityId>>24) & 0x7F; - data[dataIndex * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; + data[dataIndex * DEC_PACKET_BYTES + 2] = md->x; + data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; + data[dataIndex * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; + data[dataIndex * DEC_PACKET_BYTES + 5] = (md->entityId >> 8) & 0xFF; + data[dataIndex * DEC_PACKET_BYTES + 6] = + (md->entityId >> 16) & 0xFF; + data[dataIndex * DEC_PACKET_BYTES + 7] = + (md->entityId >> 24) & 0x7F; + data[dataIndex * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; - ++dataIndex; - } - bool thesame = !itemInstance->isFramed(); - if (lastSentDecorations.data == NULL || lastSentDecorations.length != data.length) - { - thesame = false; - } - else - { - for (unsigned int i = 0; i < data.length; i++) - { - if ( data[i] != lastSentDecorations[i]) - { - thesame = false; - break; - } - } - } + ++dataIndex; + } + bool thesame = !itemInstance->isFramed(); + if (lastSentDecorations.data == NULL || + lastSentDecorations.length != data.length) { + thesame = false; + } else { + for (unsigned int i = 0; i < data.length; i++) { + if (data[i] != lastSentDecorations[i]) { + thesame = false; + break; + } + } + } - if (!thesame) - { - if( lastSentDecorations.data != NULL ) - { - delete[] lastSentDecorations.data; - } - // Make a copy of data, as the calling function presumes it can destroy the returned data - lastSentDecorations = charArray(data.length); - memcpy(lastSentDecorations.data, data.data, data.length); - return data; - } - delete[] data.data; //4jcraft, changed to [] - } - std::shared_ptr servPlayer = std::dynamic_pointer_cast(player); - for (int d = 0; d < 10; d++) - { - int column = (tick * 11) % (MapItem::IMAGE_WIDTH); - tick++; + if (!thesame) { + if (lastSentDecorations.data != NULL) { + delete[] lastSentDecorations.data; + } + // Make a copy of data, as the calling function presumes it can + // destroy the returned data + lastSentDecorations = charArray(data.length); + memcpy(lastSentDecorations.data, data.data, data.length); + return data; + } + delete[] data.data; // 4jcraft, changed to [] + } + std::shared_ptr servPlayer = + std::dynamic_pointer_cast(player); + for (int d = 0; d < 10; d++) { + int column = (tick * 11) % (MapItem::IMAGE_WIDTH); + tick++; - if (rowsDirtyMin[column] >= 0) - { - int len = rowsDirtyMax[column] - rowsDirtyMin[column] + 1; - int min = rowsDirtyMin[column]; + if (rowsDirtyMin[column] >= 0) { + int len = rowsDirtyMax[column] - rowsDirtyMin[column] + 1; + int min = rowsDirtyMin[column]; - charArray data = charArray(len + 3); - data[0] = 0; - data[1] = (char) column; - data[2] = (char) min; - for (unsigned int y = 0; y < data.length - 3; y++) - { - data[y + 3] = parent->colors[(y + min) * MapItem::IMAGE_WIDTH + column]; - } - rowsDirtyMax[column] = -1; - rowsDirtyMin[column] = -1; - return data; - } - } - return charArray(); + charArray data = charArray(len + 3); + data[0] = 0; + data[1] = (char)column; + data[2] = (char)min; + for (unsigned int y = 0; y < data.length - 3; y++) { + data[y + 3] = + parent->colors[(y + min) * MapItem::IMAGE_WIDTH + column]; + } + rowsDirtyMax[column] = -1; + rowsDirtyMin[column] = -1; + return data; + } + } + return charArray(); } - -MapItemSavedData::MapItemSavedData(const std::wstring& id) : SavedData( id ) -{ - x = z = 0; - dimension = 0; - scale = 0; - colors = byteArray( MapItem::IMAGE_WIDTH * MapItem::IMAGE_HEIGHT ); - step = 0; +MapItemSavedData::MapItemSavedData(const std::wstring& id) : SavedData(id) { + x = z = 0; + dimension = 0; + scale = 0; + colors = byteArray(MapItem::IMAGE_WIDTH * MapItem::IMAGE_HEIGHT); + step = 0; } -MapItemSavedData::~MapItemSavedData() -{ - delete colors.data; - for( unsigned int i = 0; i < decorations.size(); i++ ) - { - delete decorations[i]; - } +MapItemSavedData::~MapItemSavedData() { + delete colors.data; + for (unsigned int i = 0; i < decorations.size(); i++) { + delete decorations[i]; + } } -void MapItemSavedData::load(CompoundTag *tag) -{ - dimension = tag->getByte(L"dimension"); - x = tag->getInt(L"xCenter"); - z = tag->getInt(L"zCenter"); - scale = tag->getByte(L"scale"); - if (scale < 0) scale = 0; - if (scale > 4) scale = 4; +void MapItemSavedData::load(CompoundTag* tag) { + dimension = tag->getByte(L"dimension"); + x = tag->getInt(L"xCenter"); + z = tag->getInt(L"zCenter"); + scale = tag->getByte(L"scale"); + if (scale < 0) scale = 0; + if (scale > 4) scale = 4; - int width = tag->getShort(L"width"); - int height = tag->getShort(L"height"); - if (width == MapItem::IMAGE_WIDTH && height == MapItem::IMAGE_HEIGHT) - { - colors = tag->getByteArray(L"colors"); - } - else - { - byteArray newColors = tag->getByteArray(L"colors"); - //4J - if(colors.data != NULL) - { - delete[] colors.data; - } - //End4J - colors = byteArray(MapItem::IMAGE_WIDTH * MapItem::IMAGE_HEIGHT); - int xo = (MapItem::IMAGE_WIDTH - width) / 2; - int yo = (MapItem::IMAGE_HEIGHT - height) / 2; - for (int y = 0; y < height; y++) - { - int yt = y + yo; - if (yt < 0 && yt >= MapItem::IMAGE_HEIGHT) continue; - for (int x = 0; x < width; x++) - { - int xt = x + xo; - if (xt < 0 && xt >= MapItem::IMAGE_WIDTH) continue; - colors[xt + yt * MapItem::IMAGE_WIDTH] = newColors[x + y * width]; - } - } - } + int width = tag->getShort(L"width"); + int height = tag->getShort(L"height"); + if (width == MapItem::IMAGE_WIDTH && height == MapItem::IMAGE_HEIGHT) { + colors = tag->getByteArray(L"colors"); + } else { + byteArray newColors = tag->getByteArray(L"colors"); + // 4J + if (colors.data != NULL) { + delete[] colors.data; + } + // End4J + colors = byteArray(MapItem::IMAGE_WIDTH * MapItem::IMAGE_HEIGHT); + int xo = (MapItem::IMAGE_WIDTH - width) / 2; + int yo = (MapItem::IMAGE_HEIGHT - height) / 2; + for (int y = 0; y < height; y++) { + int yt = y + yo; + if (yt < 0 && yt >= MapItem::IMAGE_HEIGHT) continue; + for (int x = 0; x < width; x++) { + int xt = x + xo; + if (xt < 0 && xt >= MapItem::IMAGE_WIDTH) continue; + colors[xt + yt * MapItem::IMAGE_WIDTH] = + newColors[x + y * width]; + } + } + } } -void MapItemSavedData::save(CompoundTag *tag) -{ - tag->putByte(L"dimension", dimension); - tag->putInt(L"xCenter", x); - tag->putInt(L"zCenter", z); - tag->putByte(L"scale", scale); - tag->putShort(L"width", (short) MapItem::IMAGE_WIDTH); - tag->putShort(L"height", (short) MapItem::IMAGE_HEIGHT); - tag->putByteArray(L"colors", colors); +void MapItemSavedData::save(CompoundTag* tag) { + tag->putByte(L"dimension", dimension); + tag->putInt(L"xCenter", x); + tag->putInt(L"zCenter", z); + tag->putByte(L"scale", scale); + tag->putShort(L"width", (short)MapItem::IMAGE_WIDTH); + tag->putShort(L"height", (short)MapItem::IMAGE_HEIGHT); + tag->putByteArray(L"colors", colors); } -void MapItemSavedData::tickCarriedBy(std::shared_ptr player, std::shared_ptr item) -{ - if (carriedByPlayers.find(player) == carriedByPlayers.end()) - { - std::shared_ptr hp = std::shared_ptr( new HoldingPlayer(player, this ) ); - carriedByPlayers.insert( playerHoldingPlayerMapType::value_type(player, hp) ); - carriedBy.push_back(hp); - } +void MapItemSavedData::tickCarriedBy(std::shared_ptr player, + std::shared_ptr item) { + if (carriedByPlayers.find(player) == carriedByPlayers.end()) { + std::shared_ptr hp = + std::shared_ptr(new HoldingPlayer(player, this)); + carriedByPlayers.insert( + playerHoldingPlayerMapType::value_type(player, hp)); + carriedBy.push_back(hp); + } - for( unsigned int i = 0; i < decorations.size(); i++ ) - { - delete decorations[i]; - } - decorations.clear(); - - // 4J Stu - Put this block back in if you want to display entity positions on a map (see below) + for (unsigned int i = 0; i < decorations.size(); i++) { + delete decorations[i]; + } + decorations.clear(); + + // 4J Stu - Put this block back in if you want to display entity positions + // on a map (see below) #if 0 nonPlayerDecorations.clear(); #endif - bool addedPlayers = false; - for (AUTO_VAR(it, carriedBy.begin()); it != carriedBy.end(); ) - { - std::shared_ptr hp = *it; + bool addedPlayers = false; + for (AUTO_VAR(it, carriedBy.begin()); it != carriedBy.end();) { + std::shared_ptr hp = *it; - // 4J Stu - Players in the same dimension as an item frame with a map need to be sent this data, so don't remove them - if (hp->player->removed ) //|| (!hp->player->inventory->contains(item) && !item->isFramed() )) - { - AUTO_VAR(it2, carriedByPlayers.find( (std::shared_ptr ) hp->player )); - if( it2 != carriedByPlayers.end() ) - { - carriedByPlayers.erase( it2 ); - } - it = carriedBy.erase( std::find(carriedBy.begin(), carriedBy.end(), hp) ); - } - else - { - ++it; + // 4J Stu - Players in the same dimension as an item frame with a map + // need to be sent this data, so don't remove them + if (hp->player->removed) //|| (!hp->player->inventory->contains(item) + //&& !item->isFramed() )) + { + AUTO_VAR(it2, carriedByPlayers.find( + (std::shared_ptr)hp->player)); + if (it2 != carriedByPlayers.end()) { + carriedByPlayers.erase(it2); + } + it = carriedBy.erase( + std::find(carriedBy.begin(), carriedBy.end(), hp)); + } else { + ++it; - Level *playerLevel = hp->player->level; - if(!playerLevel->isClientSide && hp->player->dimension == 0 && (playerLevel->getLevelData()->getHasStrongholdEndPortal() || playerLevel->getLevelData()->getHasStronghold() ) ) - { - bool atLeastOnePlayerInTheEnd = false; - PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) - { - std::shared_ptr serverPlayer = *it3; - if(serverPlayer->dimension == 1) - { - atLeastOnePlayerInTheEnd = true; - break; - } - } + Level* playerLevel = hp->player->level; + if (!playerLevel->isClientSide && hp->player->dimension == 0 && + (playerLevel->getLevelData()->getHasStrongholdEndPortal() || + playerLevel->getLevelData()->getHasStronghold())) { + bool atLeastOnePlayerInTheEnd = false; + PlayerList* players = + MinecraftServer::getInstance()->getPlayerList(); + for (AUTO_VAR(it3, players->players.begin()); + it3 != players->players.end(); ++it3) { + std::shared_ptr serverPlayer = *it3; + if (serverPlayer->dimension == 1) { + atLeastOnePlayerInTheEnd = true; + break; + } + } - AUTO_VAR(currentPortalDecoration, nonPlayerDecorations.find( END_PORTAL_DECORATION_KEY )); - if( currentPortalDecoration == nonPlayerDecorations.end() && atLeastOnePlayerInTheEnd) - { - float origX = 0.0f; - float origZ = 0.0f; + AUTO_VAR(currentPortalDecoration, + nonPlayerDecorations.find(END_PORTAL_DECORATION_KEY)); + if (currentPortalDecoration == nonPlayerDecorations.end() && + atLeastOnePlayerInTheEnd) { + float origX = 0.0f; + float origZ = 0.0f; - if(playerLevel->getLevelData()->getHasStrongholdEndPortal()) - { - origX = playerLevel->getLevelData()->getXStrongholdEndPortal(); - origZ = playerLevel->getLevelData()->getZStrongholdEndPortal(); - } - else - { - origX = playerLevel->getLevelData()->getXStronghold()<<4; - origZ = playerLevel->getLevelData()->getZStronghold()<<4; - } + if (playerLevel->getLevelData() + ->getHasStrongholdEndPortal()) { + origX = playerLevel->getLevelData() + ->getXStrongholdEndPortal(); + origZ = playerLevel->getLevelData() + ->getZStrongholdEndPortal(); + } else { + origX = playerLevel->getLevelData()->getXStronghold() + << 4; + origZ = playerLevel->getLevelData()->getZStronghold() + << 4; + } - float xd = (float) ( origX - x ) / (1 << scale); - float yd = (float) ( origZ - z ) / (1 << scale); - char x = (char) (xd * 2 + 0.5); - char y = (char) (yd * 2 + 0.5); - int size = MAP_SIZE - 1; + float xd = (float)(origX - x) / (1 << scale); + float yd = (float)(origZ - z) / (1 << scale); + char x = (char)(xd * 2 + 0.5); + char y = (char)(yd * 2 + 0.5); + int size = MAP_SIZE - 1; #ifdef _LARGE_WORLDS - if (xd < -size || yd < -size || xd > size || yd > size) - { - - if (xd <= -size) x = (uint8_t) (size * 2 + 2.5); - if (yd <= -size) y = (uint8_t) (size * 2 + 2.5); - if (xd >= size) x = (uint8_t) (size * 2 + 1); - if (yd >= size) y = (uint8_t) (size * 2 + 1); - } + if (xd < -size || yd < -size || xd > size || yd > size) { + if (xd <= -size) x = (uint8_t)(size * 2 + 2.5); + if (yd <= -size) y = (uint8_t)(size * 2 + 2.5); + if (xd >= size) x = (uint8_t)(size * 2 + 1); + if (yd >= size) y = (uint8_t)(size * 2 + 1); + } #endif - //decorations.push_back(new MapDecoration(4, x, y, 0)); - nonPlayerDecorations.insert( std::unordered_map::value_type( END_PORTAL_DECORATION_KEY, new MapDecoration(4, x, y, 0, END_PORTAL_DECORATION_KEY, true) ) ); - } - else if ( currentPortalDecoration != nonPlayerDecorations.end() && !atLeastOnePlayerInTheEnd ) - { - delete currentPortalDecoration->second; - nonPlayerDecorations.erase( currentPortalDecoration ); - } - } + // decorations.push_back(new MapDecoration(4, x, y, 0)); + nonPlayerDecorations.insert( + std::unordered_map::value_type( + END_PORTAL_DECORATION_KEY, + new MapDecoration( + 4, x, y, 0, END_PORTAL_DECORATION_KEY, true))); + } else if (currentPortalDecoration != + nonPlayerDecorations.end() && + !atLeastOnePlayerInTheEnd) { + delete currentPortalDecoration->second; + nonPlayerDecorations.erase(currentPortalDecoration); + } + } - if (item->isFramed()) - { - //addDecoration(1, player.level, "frame-" + item.getFrame().entityId, item.getFrame().xTile, item.getFrame().zTile, item.getFrame().dir * 90); - - if( nonPlayerDecorations.find( item->getFrame()->entityId ) == nonPlayerDecorations.end() ) - { - float xd = (float) ( item->getFrame()->xTile - x ) / (1 << scale); - float yd = (float) ( item->getFrame()->zTile - z ) / (1 << scale); - char x = (char) (xd * 2 + 0.5); - char y = (char) (yd * 2 + 0.5); - int size = MAP_SIZE - 1; - char rot = (char) ( (item->getFrame()->dir * 90) * 16 / 360); - if (dimension < 0) - { - int s = step / 10; - rot = (char) ((s * s * 34187121 + s * 121) >> 15 & 15); - } + if (item->isFramed()) { + // addDecoration(1, player.level, "frame-" + + // item.getFrame().entityId, item.getFrame().xTile, + // item.getFrame().zTile, item.getFrame().dir * 90); + + if (nonPlayerDecorations.find(item->getFrame()->entityId) == + nonPlayerDecorations.end()) { + float xd = + (float)(item->getFrame()->xTile - x) / (1 << scale); + float yd = + (float)(item->getFrame()->zTile - z) / (1 << scale); + char x = (char)(xd * 2 + 0.5); + char y = (char)(yd * 2 + 0.5); + int size = MAP_SIZE - 1; + char rot = (char)((item->getFrame()->dir * 90) * 16 / 360); + if (dimension < 0) { + int s = step / 10; + rot = (char)((s * s * 34187121 + s * 121) >> 15 & 15); + } #ifdef _LARGE_WORLDS - if (xd < -size || yd < -size || xd > size || yd > size) - { - - if (xd <= -size) x = (uint8_t) (size * 2 + 2.5); - if (yd <= -size) y = (uint8_t) (size * 2 + 2.5); - if (xd >= size) x = (uint8_t) (size * 2 + 1); - if (yd >= size) y = (uint8_t) (size * 2 + 1); - } + if (xd < -size || yd < -size || xd > size || yd > size) { + if (xd <= -size) x = (uint8_t)(size * 2 + 2.5); + if (yd <= -size) y = (uint8_t)(size * 2 + 2.5); + if (xd >= size) x = (uint8_t)(size * 2 + 1); + if (yd >= size) y = (uint8_t)(size * 2 + 1); + } #endif - //decorations.push_back(new MapDecoration(7, x, y, 0)); - nonPlayerDecorations.insert( std::unordered_map::value_type( item->getFrame()->entityId, new MapDecoration(12, x, y, rot, item->getFrame()->entityId, true) ) ); - } - } + // decorations.push_back(new MapDecoration(7, x, y, 0)); + nonPlayerDecorations.insert( + std::unordered_map::value_type( + item->getFrame()->entityId, + new MapDecoration(12, x, y, rot, + item->getFrame()->entityId, + true))); + } + } - // 4J Stu - Put this block back in if you want to display entity positions on a map (see above as well) + // 4J Stu - Put this block back in if you want to display entity + // positions on a map (see above as well) #if 0 for(AUTO_VAR(it,playerLevel->entities.begin()); it != playerLevel->entities.end(); ++it) { @@ -384,190 +386,203 @@ void MapItemSavedData::tickCarriedBy(std::shared_ptr player, std::shared } #endif - // 4J-PB - display all the players in the map - // For the xbox, x and z are 0 - if (hp->player->dimension == this->dimension && !addedPlayers) - { - addedPlayers = true; + // 4J-PB - display all the players in the map + // For the xbox, x and z are 0 + if (hp->player->dimension == this->dimension && !addedPlayers) { + addedPlayers = true; - PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) - { - std::shared_ptr decorationPlayer = *it3; - if(decorationPlayer!=NULL && decorationPlayer->dimension == this->dimension) - { - float xd = (float) (decorationPlayer->x - x) / (1 << scale); - float yd = (float) (decorationPlayer->z - z) / (1 << scale); - char x = (char) (xd * 2); - char y = (char) (yd * 2); - int size = MAP_SIZE; // - 1; - char rot; - char imgIndex; + PlayerList* players = + MinecraftServer::getInstance()->getPlayerList(); + for (AUTO_VAR(it3, players->players.begin()); + it3 != players->players.end(); ++it3) { + std::shared_ptr decorationPlayer = *it3; + if (decorationPlayer != NULL && + decorationPlayer->dimension == this->dimension) { + float xd = + (float)(decorationPlayer->x - x) / (1 << scale); + float yd = + (float)(decorationPlayer->z - z) / (1 << scale); + char x = (char)(xd * 2); + char y = (char)(yd * 2); + int size = MAP_SIZE; // - 1; + char rot; + char imgIndex; #ifdef _LARGE_WORLDS - if (xd > -size && yd > -size && xd <= size && yd <= size) - + if (xd > -size && yd > -size && xd <= size && + yd <= size) #endif - { - rot = (char) (decorationPlayer->yRot * 16 / 360 + 0.5); - if (dimension < 0) - { - int s = step / 10; - rot = (char) ((s * s * 34187121 + s * 121) >> 15 & 15); - } + { + rot = + (char)(decorationPlayer->yRot * 16 / 360 + 0.5); + if (dimension < 0) { + int s = step / 10; + rot = + (char)((s * s * 34187121 + s * 121) >> 15 & + 15); + } - // 4J Stu - As we have added new icons for players on a new row below - // other icons used in Java we need to move our index to the next row - imgIndex = (int)decorationPlayer->getPlayerIndex(); - if(imgIndex>3) imgIndex += 4; - } + // 4J Stu - As we have added new icons for players + // on a new row below other icons used in Java we + // need to move our index to the next row + imgIndex = (int)decorationPlayer->getPlayerIndex(); + if (imgIndex > 3) imgIndex += 4; + } #ifdef _LARGE_WORLDS - else //if (abs(xd) < MAP_SIZE * 5 && abs(yd) < MAP_SIZE * 5) - { - // 4J Stu - As we have added new icons for players on a new row below - // other icons used in Java we need to move our index to the next row - imgIndex = (int)decorationPlayer->getPlayerIndex(); - if(imgIndex>3) imgIndex += 4; - imgIndex += 16; // Add 16 to indicate that it's on the next texture + else // if (abs(xd) < MAP_SIZE * 5 && abs(yd) < + // MAP_SIZE * 5) + { + // 4J Stu - As we have added new icons for players + // on a new row below other icons used in Java we + // need to move our index to the next row + imgIndex = (int)decorationPlayer->getPlayerIndex(); + if (imgIndex > 3) imgIndex += 4; + imgIndex += 16; // Add 16 to indicate that it's on + // the next texture - rot = 0; - size--; // Added to match the old adjusted size - if (xd <= -size) x = (uint8_t) (size * 2 + 2.5); - if (yd <= -size) y = (uint8_t) (size * 2 + 2.5); - if (xd >= size) x = (uint8_t) (size * 2 + 1); - if (yd >= size) y = (uint8_t) (size * 2 + 1); - } + rot = 0; + size--; // Added to match the old adjusted size + if (xd <= -size) x = (uint8_t)(size * 2 + 2.5); + if (yd <= -size) y = (uint8_t)(size * 2 + 2.5); + if (xd >= size) x = (uint8_t)(size * 2 + 1); + if (yd >= size) y = (uint8_t)(size * 2 + 1); + } #endif - MemSect(45); - decorations.push_back(new MapDecoration(imgIndex, x, y, rot, decorationPlayer->entityId, (decorationPlayer == hp->player || decorationPlayer->canShowOnMaps()) )); - MemSect(0); - } - } - } + MemSect(45); + decorations.push_back(new MapDecoration( + imgIndex, x, y, rot, decorationPlayer->entityId, + (decorationPlayer == hp->player || + decorationPlayer->canShowOnMaps()))); + MemSect(0); + } + } + } -// float xd = (float) (hp->player->x - x) / (1 << scale); -// float yd = (float) (hp->player->z - z) / (1 << scale); -// int ww = 64; -// int hh = 64; -// if (xd >= -ww && yd >= -hh && xd <= ww && yd <= hh) -// { -// char img = 0; -// char x = (char) (xd * 2 + 0.5); -// char y = (char) (yd * 2 + 0.5); -// char rot = (char) (player->yRot * 16 / 360 + 0.5); -// if (dimension < 0) -// { -// int s = step / 10; -// rot = (char) ((s * s * 34187121 + s * 121) >> 15 & 15); -// } -// if (hp->player->dimension == this->dimension) -// { -// decorations.push_back(new MapDecoration(img, x, y, rot)); -// } -// } - } - } + // float xd = (float) (hp->player->x - x) / (1 << + // scale); float yd = (float) (hp->player->z - z) / (1 << scale); + // int ww = 64; + // int hh = 64; + // if (xd >= -ww && yd >= -hh && xd <= ww && yd <= + // hh) + // { + // char img = 0; + // char x = (char) (xd * 2 + 0.5); + // char y = (char) (yd * 2 + 0.5); + // char rot = (char) (player->yRot * 16 / + // 360 + 0.5); if (dimension < 0) + // { + // int s = step / 10; + // rot = (char) ((s * s * 34187121 + // + s * 121) >> 15 & 15); + // } + // if (hp->player->dimension == + // this->dimension) + // { + // decorations.push_back(new + // MapDecoration(img, x, y, rot)); + // } + // } + } + } } -charArray MapItemSavedData::getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player) -{ - AUTO_VAR(it, carriedByPlayers.find(player)); - if (it == carriedByPlayers.end() ) return charArray(); +charArray MapItemSavedData::getUpdatePacket( + std::shared_ptr itemInstance, Level* level, + std::shared_ptr player) { + AUTO_VAR(it, carriedByPlayers.find(player)); + if (it == carriedByPlayers.end()) return charArray(); - std::shared_ptr hp = it->second; - return hp->nextUpdatePacket(itemInstance); + std::shared_ptr hp = it->second; + return hp->nextUpdatePacket(itemInstance); } -void MapItemSavedData::setDirty(int x, int y0, int y1) -{ - SavedData::setDirty(); +void MapItemSavedData::setDirty(int x, int y0, int y1) { + SavedData::setDirty(); - AUTO_VAR(itEnd, carriedBy.end()); - for (AUTO_VAR(it, carriedBy.begin()); it != itEnd; it++) - { - std::shared_ptr hp = *it; //carriedBy.at(i); - if (hp->rowsDirtyMin[x] < 0 || hp->rowsDirtyMin[x] > y0) hp->rowsDirtyMin[x] = y0; - if (hp->rowsDirtyMax[x] < 0 || hp->rowsDirtyMax[x] < y1) hp->rowsDirtyMax[x] = y1; - } + AUTO_VAR(itEnd, carriedBy.end()); + for (AUTO_VAR(it, carriedBy.begin()); it != itEnd; it++) { + std::shared_ptr hp = *it; // carriedBy.at(i); + if (hp->rowsDirtyMin[x] < 0 || hp->rowsDirtyMin[x] > y0) + hp->rowsDirtyMin[x] = y0; + if (hp->rowsDirtyMax[x] < 0 || hp->rowsDirtyMax[x] < y1) + hp->rowsDirtyMax[x] = y1; + } } -void MapItemSavedData::handleComplexItemData(charArray &data) -{ - if (data[0] == 0) - { - int xx = data[1] & 0xff; - int yy = data[2] & 0xff; - for (unsigned int y = 0; y < data.length - 3; y++) - { - colors[(y + yy) * MapItem::IMAGE_WIDTH + xx] = data[y + 3]; - } - setDirty(); +void MapItemSavedData::handleComplexItemData(charArray& data) { + if (data[0] == 0) { + int xx = data[1] & 0xff; + int yy = data[2] & 0xff; + for (unsigned int y = 0; y < data.length - 3; y++) { + colors[(y + yy) * MapItem::IMAGE_WIDTH + xx] = data[y + 3]; + } + setDirty(); - } - else if (data[0] == 1) - { - for( unsigned int i = 0; i < decorations.size(); i++ ) - { - delete decorations[i]; - } - decorations.clear(); - for (unsigned int i = 0; i < (data.length - 1) / DEC_PACKET_BYTES; i++) - { + } else if (data[0] == 1) { + for (unsigned int i = 0; i < decorations.size(); i++) { + delete decorations[i]; + } + decorations.clear(); + for (unsigned int i = 0; i < (data.length - 1) / DEC_PACKET_BYTES; + i++) { #ifdef _LARGE_WORLDS - char img = data[i * DEC_PACKET_BYTES + 1]; - char rot = data[i * DEC_PACKET_BYTES + 8]; + char img = data[i * DEC_PACKET_BYTES + 1]; + char rot = data[i * DEC_PACKET_BYTES + 8]; #else - // 4J-PB - this gives the wrong result - char img = (char) ( (((int)data[i * DEC_PACKET_BYTES + 1])&0xF0) >> 4); - char rot = (char) (data[i * DEC_PACKET_BYTES + 1] & 0xF); + // 4J-PB - this gives the wrong result + char img = + (char)((((int)data[i * DEC_PACKET_BYTES + 1]) & 0xF0) >> 4); + char rot = (char)(data[i * DEC_PACKET_BYTES + 1] & 0xF); #endif - char x = data[i * DEC_PACKET_BYTES + 2]; - char y = data[i * DEC_PACKET_BYTES + 3]; - int entityId = (((int)data[i * DEC_PACKET_BYTES + 4])&0xFF) | ( (((int)data[i * DEC_PACKET_BYTES + 5])&0xFF)<<8) | ((((int)data[i * DEC_PACKET_BYTES + 6])&0xFF)<<16) | ((((int)data[i * DEC_PACKET_BYTES + 7])&0x7F)<<24); - bool visible = (data[i * DEC_PACKET_BYTES + 7] & 0x80) != 0; - decorations.push_back(new MapDecoration(img, x, y, rot, entityId, visible)); - } - } + char x = data[i * DEC_PACKET_BYTES + 2]; + char y = data[i * DEC_PACKET_BYTES + 3]; + int entityId = + (((int)data[i * DEC_PACKET_BYTES + 4]) & 0xFF) | + ((((int)data[i * DEC_PACKET_BYTES + 5]) & 0xFF) << 8) | + ((((int)data[i * DEC_PACKET_BYTES + 6]) & 0xFF) << 16) | + ((((int)data[i * DEC_PACKET_BYTES + 7]) & 0x7F) << 24); + bool visible = (data[i * DEC_PACKET_BYTES + 7] & 0x80) != 0; + decorations.push_back( + new MapDecoration(img, x, y, rot, entityId, visible)); + } + } } // 4J Added -// We only have one map per player per dimension, so if they pickup someone elses map we merge their map data with ours -// so that we can see everything that they discovered but still only have one map data ourself -void MapItemSavedData::mergeInMapData(std::shared_ptr dataToAdd) -{ - int w = MapItem::IMAGE_WIDTH; - int h = MapItem::IMAGE_HEIGHT; +// We only have one map per player per dimension, so if they pickup someone +// elses map we merge their map data with ours so that we can see everything +// that they discovered but still only have one map data ourself +void MapItemSavedData::mergeInMapData( + std::shared_ptr dataToAdd) { + int w = MapItem::IMAGE_WIDTH; + int h = MapItem::IMAGE_HEIGHT; - for (int x = 0; x < w; x++) - { - int yd0 = 255; - int yd1 = 0; + for (int x = 0; x < w; x++) { + int yd0 = 255; + int yd1 = 0; - for (int z = 0; z < h; z++) - { - uint8_t oldColor = colors[x + z * w]; - uint8_t newColor = dataToAdd->colors[x + z * w]; - if (oldColor == 0 && oldColor != newColor) - { - if (yd0 > z) yd0 = z; - if (yd1 < z) yd1 = z; - colors[x + z * w] = newColor; - } - } - if (yd0 <= yd1) - { - setDirty(x, yd0, yd1); - } - } + for (int z = 0; z < h; z++) { + uint8_t oldColor = colors[x + z * w]; + uint8_t newColor = dataToAdd->colors[x + z * w]; + if (oldColor == 0 && oldColor != newColor) { + if (yd0 > z) yd0 = z; + if (yd1 < z) yd1 = z; + colors[x + z * w] = newColor; + } + } + if (yd0 <= yd1) { + setDirty(x, yd0, yd1); + } + } } -void MapItemSavedData::removeItemFrameDecoration(std::shared_ptr item) -{ - AUTO_VAR(frameDecoration, nonPlayerDecorations.find( item->getFrame()->entityId ) ); - if ( frameDecoration != nonPlayerDecorations.end() ) - { - delete frameDecoration->second; - nonPlayerDecorations.erase( frameDecoration ); - } +void MapItemSavedData::removeItemFrameDecoration( + std::shared_ptr item) { + AUTO_VAR(frameDecoration, + nonPlayerDecorations.find(item->getFrame()->entityId)); + if (frameDecoration != nonPlayerDecorations.end()) { + delete frameDecoration->second; + nonPlayerDecorations.erase(frameDecoration); + } } diff --git a/Minecraft.World/Level/Storage/MapItemSavedData.h b/Minecraft.World/Level/Storage/MapItemSavedData.h index a8a70e677..37c392769 100644 --- a/Minecraft.World/Level/Storage/MapItemSavedData.h +++ b/Minecraft.World/Level/Storage/MapItemSavedData.h @@ -3,87 +3,91 @@ #include "../../Player/Player.h" #include "SavedData.h" -class MapItemSavedData : public SavedData -{ +class MapItemSavedData : public SavedData { public: - static const int MAP_SIZE = 64; - static const int MAX_SCALE = 4; + static const int MAP_SIZE = 64; + static const int MAX_SCALE = 4; #ifdef _LARGE_WORLDS - static const int DEC_PACKET_BYTES = 8; + static const int DEC_PACKET_BYTES = 8; #else - static const int DEC_PACKET_BYTES = 7; + static const int DEC_PACKET_BYTES = 7; #endif - class MapDecoration - { - public: - char img, x, y, rot; - int entityId; // 4J Added - bool visible; + class MapDecoration { + public: + char img, x, y, rot; + int entityId; // 4J Added + bool visible; - MapDecoration(char img, char x, char y, char rot, int entityId, bool visible); // 4J added entityId, visible param - }; + MapDecoration(char img, char x, char y, char rot, int entityId, + bool visible); // 4J added entityId, visible param + }; - class HoldingPlayer - { - public: - const std::shared_ptr player; - intArray rowsDirtyMin; - intArray rowsDirtyMax; + class HoldingPlayer { + public: + const std::shared_ptr player; + intArray rowsDirtyMin; + intArray rowsDirtyMax; - private: - int tick; - int sendPosTick; - charArray lastSentDecorations; + private: + int tick; + int sendPosTick; + charArray lastSentDecorations; - protected: - const MapItemSavedData *parent; + protected: + const MapItemSavedData* parent; - public: - // 4J Stu - Had to add a reference to the MapItemSavedData object that created us as we try to access it's member variables - HoldingPlayer(std::shared_ptr player, const MapItemSavedData *parent); - ~HoldingPlayer(); - charArray nextUpdatePacket(std::shared_ptr itemInstance); - }; + public: + // 4J Stu - Had to add a reference to the MapItemSavedData object that + // created us as we try to access it's member variables + HoldingPlayer(std::shared_ptr player, + const MapItemSavedData* parent); + ~HoldingPlayer(); + charArray nextUpdatePacket(std::shared_ptr itemInstance); + }; public: - int x, z; - char dimension; - uint8_t scale; - byteArray colors; - int step; - std::vector > carriedBy; + int x, z; + char dimension; + uint8_t scale; + byteArray colors; + int step; + std::vector > carriedBy; private: - typedef std::unordered_map , std::shared_ptr , PlayerKeyHash, PlayerKeyEq> playerHoldingPlayerMapType; - playerHoldingPlayerMapType carriedByPlayers; + typedef std::unordered_map, + std::shared_ptr, PlayerKeyHash, + PlayerKeyEq> + playerHoldingPlayerMapType; + playerHoldingPlayerMapType carriedByPlayers; public: - std::vector decorations; + std::vector decorations; private: - // 4J Stu added - std::unordered_map nonPlayerDecorations; - static const int END_PORTAL_DECORATION_KEY; - + // 4J Stu added + std::unordered_map nonPlayerDecorations; + static const int END_PORTAL_DECORATION_KEY; public: - MapItemSavedData(const std::wstring& id); - ~MapItemSavedData(); + MapItemSavedData(const std::wstring& id); + ~MapItemSavedData(); - virtual void load(CompoundTag *tag); - virtual void save(CompoundTag *tag); + virtual void load(CompoundTag* tag); + virtual void save(CompoundTag* tag); - void tickCarriedBy(std::shared_ptr player, std::shared_ptr item); + void tickCarriedBy(std::shared_ptr player, + std::shared_ptr item); - charArray getUpdatePacket(std::shared_ptr itemInstance, Level *level, std::shared_ptr player); + charArray getUpdatePacket(std::shared_ptr itemInstance, + Level* level, std::shared_ptr player); - using SavedData::setDirty; - void setDirty(int x, int y0, int y1); - void handleComplexItemData(charArray &data); + using SavedData::setDirty; + void setDirty(int x, int y0, int y1); + void handleComplexItemData(charArray& data); - // 4J Stu Added - void mergeInMapData(std::shared_ptr dataToAdd); - void removeItemFrameDecoration(std::shared_ptr item); + // 4J Stu Added + void mergeInMapData(std::shared_ptr dataToAdd); + void removeItemFrameDecoration(std::shared_ptr item); }; diff --git a/Minecraft.World/Level/Storage/McRegionChunkStorage.cpp b/Minecraft.World/Level/Storage/McRegionChunkStorage.cpp index 5c6d4489f..ebbbcdc6e 100644 --- a/Minecraft.World/Level/Storage/McRegionChunkStorage.cpp +++ b/Minecraft.World/Level/Storage/McRegionChunkStorage.cpp @@ -4,460 +4,443 @@ #include "../LevelData.h" #include "McRegionChunkStorage.h" -CRITICAL_SECTION McRegionChunkStorage::cs_memory; +CRITICAL_SECTION McRegionChunkStorage::cs_memory; -std::deque McRegionChunkStorage::s_chunkDataQueue; +std::deque McRegionChunkStorage::s_chunkDataQueue; int McRegionChunkStorage::s_runningThreadCount = 0; -C4JThread *McRegionChunkStorage::s_saveThreads[3]; +C4JThread* McRegionChunkStorage::s_saveThreads[3]; +McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile* saveFile, + const std::wstring& prefix) + : m_prefix(prefix) { + m_saveFile = saveFile; -McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const std::wstring &prefix) : m_prefix( prefix ) -{ - m_saveFile = saveFile; + // Make sure that if there are any files for regions to be created, that + // they are created in the order that suits us for making the initial level + // save work fast + if (prefix == L"") { + m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.0.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.0.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.0.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.0.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"r.-1.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"r.0.-1.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"r.0.0.mcr")); + m_saveFile->createFile(ConsoleSavePath(L"r.-1.0.mcr")); + } - // Make sure that if there are any files for regions to be created, that they are created in the order that suits us for making the initial level save work fast - if( prefix == L"" ) - { - m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.0.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.0.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.0.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.0.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"r.-1.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"r.0.-1.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"r.0.0.mcr")); - m_saveFile->createFile(ConsoleSavePath(L"r.-1.0.mcr")); - } - - #ifdef SPLIT_SAVES - ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + std::wstring( L"entities.dat" ) ); + ConsoleSavePath currentFile = + ConsoleSavePath(m_prefix + std::wstring(L"entities.dat")); - if(m_saveFile->doesFileExist(currentFile)) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream( m_saveFile, currentFile ); - DataInputStream dis(&fis); + if (m_saveFile->doesFileExist(currentFile)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(m_saveFile, currentFile); + DataInputStream dis(&fis); - int count = dis.readInt(); + int count = dis.readInt(); - for(int i = 0; i < count; ++i) - { - __int64 index = dis.readLong(); - CompoundTag *tag = NbtIo::read(&dis); + for (int i = 0; i < count; ++i) { + __int64 index = dis.readLong(); + CompoundTag* tag = NbtIo::read(&dis); - ByteArrayOutputStream bos; - DataOutputStream dos(&bos); - NbtIo::write(tag, &dos); - delete tag; + ByteArrayOutputStream bos; + DataOutputStream dos(&bos); + NbtIo::write(tag, &dos); + delete tag; - byteArray savedData(bos.size()); - memcpy(savedData.data, bos.buf.data, bos.size()); + byteArray savedData(bos.size()); + memcpy(savedData.data, bos.buf.data, bos.size()); - m_entityData[index] = savedData; - } - } + m_entityData[index] = savedData; + } + } #endif } -McRegionChunkStorage::~McRegionChunkStorage() -{ - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) - { - delete it->second.data; - } +McRegionChunkStorage::~McRegionChunkStorage() { + for (AUTO_VAR(it, m_entityData.begin()); it != m_entityData.end(); ++it) { + delete it->second.data; + } } -LevelChunk *McRegionChunkStorage::load(Level *level, int x, int z) -{ - DataInputStream *regionChunkInputStream = RegionFileCache::getChunkDataInputStream(m_saveFile, m_prefix, x, z); +LevelChunk* McRegionChunkStorage::load(Level* level, int x, int z) { + DataInputStream* regionChunkInputStream = + RegionFileCache::getChunkDataInputStream(m_saveFile, m_prefix, x, z); #ifdef SPLIT_SAVES - // If we can't find the chunk in the save file, then we should remove any entities we might have for that chunk - if(regionChunkInputStream == NULL) - { - // 4jcraft fixed cast from int to int64 and taking the mask of the upper bits - // and cast to unsigned - uint64_t index = ((uint64_t)(uint32_t)(x) << 32) | (((uint64_t)(uint32_t)(z))); + // If we can't find the chunk in the save file, then we should remove any + // entities we might have for that chunk + if (regionChunkInputStream == NULL) { + // 4jcraft fixed cast from int to int64 and taking the mask of the upper + // bits and cast to unsigned + uint64_t index = + ((uint64_t)(uint32_t)(x) << 32) | (((uint64_t)(uint32_t)(z))); - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) - { - delete it->second.data; - m_entityData.erase(it); - } - } + AUTO_VAR(it, m_entityData.find(index)); + if (it != m_entityData.end()) { + delete it->second.data; + m_entityData.erase(it); + } + } #endif - LevelChunk *levelChunk = NULL; + LevelChunk* levelChunk = NULL; - if(m_saveFile->getOriginalSaveVersion() >= SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE) - { - if (regionChunkInputStream != NULL) - { - MemSect(9); - levelChunk = OldChunkStorage::load(level, regionChunkInputStream); - loadEntities(level, levelChunk); - MemSect(0); - regionChunkInputStream->deleteChildStream(); - delete regionChunkInputStream; - } - } - else - { - CompoundTag *chunkData; - if (regionChunkInputStream != NULL) - { - MemSect(8); - chunkData = NbtIo::read((DataInput *)regionChunkInputStream); - MemSect(0); - } else - { - return NULL; - } + if (m_saveFile->getOriginalSaveVersion() >= + SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE) { + if (regionChunkInputStream != NULL) { + MemSect(9); + levelChunk = OldChunkStorage::load(level, regionChunkInputStream); + loadEntities(level, levelChunk); + MemSect(0); + regionChunkInputStream->deleteChildStream(); + delete regionChunkInputStream; + } + } else { + CompoundTag* chunkData; + if (regionChunkInputStream != NULL) { + MemSect(8); + chunkData = NbtIo::read((DataInput*)regionChunkInputStream); + MemSect(0); + } else { + return NULL; + } - regionChunkInputStream->deleteChildStream(); - delete regionChunkInputStream; + regionChunkInputStream->deleteChildStream(); + delete regionChunkInputStream; - if (!chunkData->contains(L"Level")) - { - char buf[256]; - sprintf(buf,"Chunk file at %d, %d is missing level data, skipping\n",x, z); - app.DebugPrintf(buf); - delete chunkData; - return NULL; - } - if (!chunkData->getCompound(L"Level")->contains(L"Blocks")) - { - char buf[256]; - sprintf(buf,"Chunk file at %d, %d is missing block data, skipping\n",x, z); - app.DebugPrintf(buf); - delete chunkData; - return NULL; - } - MemSect(9); - levelChunk = OldChunkStorage::load(level, chunkData->getCompound(L"Level")); - MemSect(0); - if (!levelChunk->isAt(x, z)) - { - char buf[256]; - sprintf(buf,"Chunk file at %d, %d is in the wrong location; relocating. Expected %d, %d, got %d, %d\n", - x, z, x, z, levelChunk->x, levelChunk->z); - app.DebugPrintf(buf); - delete levelChunk; - delete chunkData; - return NULL; + if (!chunkData->contains(L"Level")) { + char buf[256]; + sprintf(buf, + "Chunk file at %d, %d is missing level data, skipping\n", x, + z); + app.DebugPrintf(buf); + delete chunkData; + return NULL; + } + if (!chunkData->getCompound(L"Level")->contains(L"Blocks")) { + char buf[256]; + sprintf(buf, + "Chunk file at %d, %d is missing block data, skipping\n", x, + z); + app.DebugPrintf(buf); + delete chunkData; + return NULL; + } + MemSect(9); + levelChunk = + OldChunkStorage::load(level, chunkData->getCompound(L"Level")); + MemSect(0); + if (!levelChunk->isAt(x, z)) { + char buf[256]; + sprintf(buf, + "Chunk file at %d, %d is in the wrong location; " + "relocating. Expected %d, %d, got %d, %d\n", + x, z, x, z, levelChunk->x, levelChunk->z); + app.DebugPrintf(buf); + delete levelChunk; + delete chunkData; + return NULL; - // 4J Stu - We delete the data within OldChunkStorage::load, so we can never reload from it - //chunkData->putInt(L"xPos", x); - //chunkData->putInt(L"zPos", z); - //MemSect(10); - //levelChunk = OldChunkStorage::load(level, chunkData->getCompound(L"Level")); - //MemSect(0); - } + // 4J Stu - We delete the data within OldChunkStorage::load, so we + // can never reload from it + // chunkData->putInt(L"xPos", x); + // chunkData->putInt(L"zPos", z); + // MemSect(10); + // levelChunk = OldChunkStorage::load(level, + // chunkData->getCompound(L"Level")); MemSect(0); + } #ifdef SPLIT_SAVES - loadEntities(level, levelChunk); + loadEntities(level, levelChunk); #endif - delete chunkData; - } - return levelChunk; - + delete chunkData; + } + return levelChunk; } -void McRegionChunkStorage::save(Level *level, LevelChunk *levelChunk) -{ - level->checkSession(); +void McRegionChunkStorage::save(Level* level, LevelChunk* levelChunk) { + level->checkSession(); - // 4J - removed try/catch -// try { + // 4J - removed try/catch + // try { - // Note - have added use of a critical section round sections of code that do a lot of memory alloc/free operations. This is because - // when we are running saves on multiple threads these sections have a lot of contention and thrash the memory system's critical sections - // Better to let each thread have its turn at a higher level of granularity. - MemSect(30); - PIXBeginNamedEvent(0,"Getting output stream\n"); - DataOutputStream *output = RegionFileCache::getChunkDataOutputStream(m_saveFile, m_prefix, levelChunk->x, levelChunk->z); - PIXEndNamedEvent(); + // Note - have added use of a critical section round sections of code that + // do a lot of memory alloc/free operations. This is because when we are + // running saves on multiple threads these sections have a lot of contention + // and thrash the memory system's critical sections Better to let each + // thread have its turn at a higher level of granularity. + MemSect(30); + PIXBeginNamedEvent(0, "Getting output stream\n"); + DataOutputStream* output = RegionFileCache::getChunkDataOutputStream( + m_saveFile, m_prefix, levelChunk->x, levelChunk->z); + PIXEndNamedEvent(); - if(m_saveFile->getOriginalSaveVersion() >= SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE) - { - PIXBeginNamedEvent(0,"Writing chunk data"); - OldChunkStorage::save(levelChunk, level, output); - PIXEndNamedEvent(); + if (m_saveFile->getOriginalSaveVersion() >= + SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE) { + PIXBeginNamedEvent(0, "Writing chunk data"); + OldChunkStorage::save(levelChunk, level, output); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Updating chunk queue"); - EnterCriticalSection(&cs_memory); - s_chunkDataQueue.push_back(output); - LeaveCriticalSection(&cs_memory); - PIXEndNamedEvent(); - } - else - { - EnterCriticalSection(&cs_memory); - PIXBeginNamedEvent(0,"Creating tags\n"); - CompoundTag *tag = new CompoundTag(); - CompoundTag *levelData = new CompoundTag(); - tag->put(L"Level", levelData); - OldChunkStorage::save(levelChunk, level, levelData); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"NbtIo writing\n"); - NbtIo::write(tag, output); - PIXEndNamedEvent(); - LeaveCriticalSection(&cs_memory); - PIXBeginNamedEvent(0,"Output closing\n"); - output->close(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Updating chunk queue"); + EnterCriticalSection(&cs_memory); + s_chunkDataQueue.push_back(output); + LeaveCriticalSection(&cs_memory); + PIXEndNamedEvent(); + } else { + EnterCriticalSection(&cs_memory); + PIXBeginNamedEvent(0, "Creating tags\n"); + CompoundTag* tag = new CompoundTag(); + CompoundTag* levelData = new CompoundTag(); + tag->put(L"Level", levelData); + OldChunkStorage::save(levelChunk, level, levelData); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "NbtIo writing\n"); + NbtIo::write(tag, output); + PIXEndNamedEvent(); + LeaveCriticalSection(&cs_memory); + PIXBeginNamedEvent(0, "Output closing\n"); + output->close(); + PIXEndNamedEvent(); + // 4J Stu - getChunkDataOutputStream makes a new DataOutputStream that + // points to a new ChunkBuffer( ByteArrayOutputStream ) We should clean + // these up when we are done + EnterCriticalSection(&cs_memory); + PIXBeginNamedEvent(0, "Cleaning up\n"); + output->deleteChildStream(); + delete output; + delete tag; + LeaveCriticalSection(&cs_memory); + PIXEndNamedEvent(); + } + MemSect(0); - // 4J Stu - getChunkDataOutputStream makes a new DataOutputStream that points to a new ChunkBuffer( ByteArrayOutputStream ) - // We should clean these up when we are done - EnterCriticalSection(&cs_memory); - PIXBeginNamedEvent(0,"Cleaning up\n"); - output->deleteChildStream(); - delete output; - delete tag; - LeaveCriticalSection(&cs_memory); - PIXEndNamedEvent(); - } - MemSect(0); + LevelData* levelInfo = level->getLevelData(); - LevelData *levelInfo = level->getLevelData(); - - // 4J Stu - Override this with our save file size to stop all the RegionFileCache lookups - //levelInfo->setSizeOnDisk(levelInfo->getSizeOnDisk() + RegionFileCache::getSizeDelta(m_saveFile, m_prefix, levelChunk->x, levelChunk->z)); - levelInfo->setSizeOnDisk( this->m_saveFile->getSizeOnDisk() ); -// } catch (Exception e) { -// e.printStackTrace(); -// } + // 4J Stu - Override this with our save file size to stop all the + // RegionFileCache lookups + // levelInfo->setSizeOnDisk(levelInfo->getSizeOnDisk() + + // RegionFileCache::getSizeDelta(m_saveFile, m_prefix, levelChunk->x, + // levelChunk->z)); + levelInfo->setSizeOnDisk(this->m_saveFile->getSizeOnDisk()); + // } catch (Exception e) { + // e.printStackTrace(); + // } } -void McRegionChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk) -{ +void McRegionChunkStorage::saveEntities(Level* level, LevelChunk* levelChunk) { #ifdef SPLIT_SAVES - PIXBeginNamedEvent(0,"Saving entities"); - // 4j added cast to unsigned and changed index to u - uint64_t index = ((uint64_t)(uint32_t)(levelChunk->x) << 32) | (((uint64_t)(uint32_t)(levelChunk->z))); + PIXBeginNamedEvent(0, "Saving entities"); + // 4j added cast to unsigned and changed index to u + uint64_t index = ((uint64_t)(uint32_t)(levelChunk->x) << 32) | + (((uint64_t)(uint32_t)(levelChunk->z))); - delete m_entityData[index].data; + delete m_entityData[index].data; - CompoundTag *newTag = new CompoundTag(); - bool savedEntities = OldChunkStorage::saveEntities(levelChunk, level, newTag); + CompoundTag* newTag = new CompoundTag(); + bool savedEntities = + OldChunkStorage::saveEntities(levelChunk, level, newTag); - if(savedEntities) - { - ByteArrayOutputStream bos; - DataOutputStream dos(&bos); - NbtIo::write(newTag, &dos); + if (savedEntities) { + ByteArrayOutputStream bos; + DataOutputStream dos(&bos); + NbtIo::write(newTag, &dos); - byteArray savedData(bos.size()); - memcpy(savedData.data, bos.buf.data, bos.size()); + byteArray savedData(bos.size()); + memcpy(savedData.data, bos.buf.data, bos.size()); - m_entityData[index] = savedData; - } - else - { - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) - { - m_entityData.erase(it); - } - } - delete newTag; - PIXEndNamedEvent(); + m_entityData[index] = savedData; + } else { + AUTO_VAR(it, m_entityData.find(index)); + if (it != m_entityData.end()) { + m_entityData.erase(it); + } + } + delete newTag; + PIXEndNamedEvent(); #endif } -void McRegionChunkStorage::loadEntities(Level *level, LevelChunk *levelChunk) -{ +void McRegionChunkStorage::loadEntities(Level* level, LevelChunk* levelChunk) { #ifdef SPLIT_SAVES - __int64 index = ((__int64)(levelChunk->x) << 32) | (((__int64)(levelChunk->z))&0x00000000FFFFFFFF); - - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) - { - ByteArrayInputStream bais(it->second); - DataInputStream dis(&bais); - CompoundTag *tag = NbtIo::read(&dis); - OldChunkStorage::loadEntities(levelChunk, level, tag); - bais.reset(); - delete tag; - } + __int64 index = ((__int64)(levelChunk->x) << 32) | + (((__int64)(levelChunk->z)) & 0x00000000FFFFFFFF); + + AUTO_VAR(it, m_entityData.find(index)); + if (it != m_entityData.end()) { + ByteArrayInputStream bais(it->second); + DataInputStream dis(&bais); + CompoundTag* tag = NbtIo::read(&dis); + OldChunkStorage::loadEntities(levelChunk, level, tag); + bais.reset(); + delete tag; + } #endif } -void McRegionChunkStorage::tick() -{ - m_saveFile->tick(); -} +void McRegionChunkStorage::tick() { m_saveFile->tick(); } -void McRegionChunkStorage::flush() -{ +void McRegionChunkStorage::flush() { #ifdef SPLIT_SAVES - PIXBeginNamedEvent(0, "Flushing entity data"); - ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + std::wstring( L"entities.dat" ) ); - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, currentFile ); - BufferedOutputStream bos(&fos, 1024*1024); - DataOutputStream dos(&bos); + PIXBeginNamedEvent(0, "Flushing entity data"); + ConsoleSavePath currentFile = + ConsoleSavePath(m_prefix + std::wstring(L"entities.dat")); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(m_saveFile, currentFile); + BufferedOutputStream bos(&fos, 1024 * 1024); + DataOutputStream dos(&bos); - PIXBeginNamedEvent(0,"Writing to stream"); - dos.writeInt(m_entityData.size()); + PIXBeginNamedEvent(0, "Writing to stream"); + dos.writeInt(m_entityData.size()); - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) - { - dos.writeLong(it->first); - dos.write(it->second,0,it->second.length); - } - bos.flush(); - PIXEndNamedEvent(); - PIXEndNamedEvent(); + for (AUTO_VAR(it, m_entityData.begin()); it != m_entityData.end(); ++it) { + dos.writeLong(it->first); + dos.write(it->second, 0, it->second.length); + } + bos.flush(); + PIXEndNamedEvent(); + PIXEndNamedEvent(); #endif } +void McRegionChunkStorage::staticCtor() { + InitializeCriticalSectionAndSpinCount(&cs_memory, 5120); -void McRegionChunkStorage::staticCtor() -{ - InitializeCriticalSectionAndSpinCount(&cs_memory,5120); + for (unsigned int i = 0; i < 3; ++i) { + char threadName[256]; + sprintf(threadName, "McRegion Save thread %d\n", i); + SetThreadName(0, threadName); - for(unsigned int i = 0; i < 3; ++i) - { - char threadName[256]; - sprintf(threadName,"McRegion Save thread %d\n",i); - SetThreadName(0, threadName); + // saveThreads[j] = + // CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); + s_saveThreads[i] = new C4JThread(runSaveThreadProc, NULL, threadName); - //saveThreads[j] = CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); - s_saveThreads[i] = new C4JThread(runSaveThreadProc,NULL,threadName); + // app.DebugPrintf("Created new thread: %s\n",threadName); - - //app.DebugPrintf("Created new thread: %s\n",threadName); - - // Threads 1,3 and 5 are generally idle so use them - if(i == 0) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_A); - else if(i == 1) - { - s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_B); + // Threads 1,3 and 5 are generally idle so use them + if (i == 0) + s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_A); + else if (i == 1) { + s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_B); #ifdef __ORBIS__ - s_saveThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + s_saveThreads[i]->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also + // used for Matching 2, and that + // priority of that seems to be + // always at default no matter + // what we set it to. Prioritise + // this below Matching 2. #endif - } - else if(i == 2) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_C); + } else if (i == 2) + s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_C); - //ResumeThread( saveThreads[j] ); - s_saveThreads[i]->Run(); - } + // ResumeThread( saveThreads[j] ); + s_saveThreads[i]->Run(); + } } -int McRegionChunkStorage::runSaveThreadProc(void *lpParam) -{ - Compression::CreateNewThreadStorage(); +int McRegionChunkStorage::runSaveThreadProc(void* lpParam) { + Compression::CreateNewThreadStorage(); - bool running = true; - size_t lastQueueSize = 0; + bool running = true; + size_t lastQueueSize = 0; - DataOutputStream *dos = NULL; - while(running) - { - if( TryEnterCriticalSection(&cs_memory) ) - { - lastQueueSize = s_chunkDataQueue.size(); - if(lastQueueSize > 0) - { - dos = s_chunkDataQueue.front(); - s_chunkDataQueue.pop_front(); - } - s_runningThreadCount++; - LeaveCriticalSection(&cs_memory); + DataOutputStream* dos = NULL; + while (running) { + if (TryEnterCriticalSection(&cs_memory)) { + lastQueueSize = s_chunkDataQueue.size(); + if (lastQueueSize > 0) { + dos = s_chunkDataQueue.front(); + s_chunkDataQueue.pop_front(); + } + s_runningThreadCount++; + LeaveCriticalSection(&cs_memory); - if(dos) - { - PIXBeginNamedEvent(0,"Saving chunk"); - //app.DebugPrintf("Compressing chunk data (%d left)\n", lastQueueSize - 1); - dos->close(); - dos->deleteChildStream(); - PIXEndNamedEvent(); - } - delete dos; - dos = NULL; + if (dos) { + PIXBeginNamedEvent(0, "Saving chunk"); + // app.DebugPrintf("Compressing chunk data (%d left)\n", + // lastQueueSize - 1); + dos->close(); + dos->deleteChildStream(); + PIXEndNamedEvent(); + } + delete dos; + dos = NULL; - EnterCriticalSection(&cs_memory); - s_runningThreadCount--; - LeaveCriticalSection(&cs_memory); - } + EnterCriticalSection(&cs_memory); + s_runningThreadCount--; + LeaveCriticalSection(&cs_memory); + } - // If there was more than one thing in the queue last time we checked, then we want to spin round again soon - // Otherwise wait a bit longer - if( (lastQueueSize -1) > 0) Sleep(1); // Sleep 1 to yield - else Sleep(100); - } + // If there was more than one thing in the queue last time we checked, + // then we want to spin round again soon Otherwise wait a bit longer + if ((lastQueueSize - 1) > 0) + Sleep(1); // Sleep 1 to yield + else + Sleep(100); + } - Compression::ReleaseThreadStorage(); + Compression::ReleaseThreadStorage(); - return 0; + return 0; } -void McRegionChunkStorage::WaitForAll() -{ - WaitForAllSaves(); -} +void McRegionChunkStorage::WaitForAll() { WaitForAllSaves(); } -void McRegionChunkStorage::WaitIfTooManyQueuedChunks() -{ - WaitForSaves(); +void McRegionChunkStorage::WaitIfTooManyQueuedChunks() { WaitForSaves(); } + +// Static +void McRegionChunkStorage::WaitForAllSaves() { + // Wait for there to be no more tasks to be processed... + EnterCriticalSection(&cs_memory); + size_t queueSize = s_chunkDataQueue.size(); + LeaveCriticalSection(&cs_memory); + + while (queueSize > 0) { + Sleep(10); + + EnterCriticalSection(&cs_memory); + queueSize = s_chunkDataQueue.size(); + LeaveCriticalSection(&cs_memory); + } + + // And then wait for there to be no running threads that are processing + // these tasks + EnterCriticalSection(&cs_memory); + int runningThreadCount = s_runningThreadCount; + LeaveCriticalSection(&cs_memory); + + while (runningThreadCount > 0) { + Sleep(10); + + EnterCriticalSection(&cs_memory); + runningThreadCount = s_runningThreadCount; + LeaveCriticalSection(&cs_memory); + } } // Static -void McRegionChunkStorage::WaitForAllSaves() -{ - // Wait for there to be no more tasks to be processed... - EnterCriticalSection(&cs_memory); - size_t queueSize = s_chunkDataQueue.size(); - LeaveCriticalSection(&cs_memory); +void McRegionChunkStorage::WaitForSaves() { + static const int MAX_QUEUE_SIZE = 12; + static const int DESIRED_QUEUE_SIZE = 6; - while(queueSize > 0) - { - Sleep(10); + // Wait for the queue to reduce to a level where we should add more elements + EnterCriticalSection(&cs_memory); + size_t queueSize = s_chunkDataQueue.size(); + LeaveCriticalSection(&cs_memory); - EnterCriticalSection(&cs_memory); - queueSize = s_chunkDataQueue.size(); - LeaveCriticalSection(&cs_memory); - } + if (queueSize > MAX_QUEUE_SIZE) { + while (queueSize > DESIRED_QUEUE_SIZE) { + Sleep(10); - // And then wait for there to be no running threads that are processing these tasks - EnterCriticalSection(&cs_memory); - int runningThreadCount = s_runningThreadCount; - LeaveCriticalSection(&cs_memory); - - while(runningThreadCount > 0) - { - Sleep(10); - - EnterCriticalSection(&cs_memory); - runningThreadCount = s_runningThreadCount; - LeaveCriticalSection(&cs_memory); - } -} - -// Static -void McRegionChunkStorage::WaitForSaves() -{ - static const int MAX_QUEUE_SIZE = 12; - static const int DESIRED_QUEUE_SIZE = 6; - - // Wait for the queue to reduce to a level where we should add more elements - EnterCriticalSection(&cs_memory); - size_t queueSize = s_chunkDataQueue.size(); - LeaveCriticalSection(&cs_memory); - - if( queueSize > MAX_QUEUE_SIZE ) - { - while( queueSize > DESIRED_QUEUE_SIZE ) - { - Sleep(10); - - EnterCriticalSection(&cs_memory); - queueSize = s_chunkDataQueue.size(); - LeaveCriticalSection(&cs_memory); - } - } + EnterCriticalSection(&cs_memory); + queueSize = s_chunkDataQueue.size(); + LeaveCriticalSection(&cs_memory); + } + } } diff --git a/Minecraft.World/Level/Storage/McRegionChunkStorage.h b/Minecraft.World/Level/Storage/McRegionChunkStorage.h index 56fa2800c..8162d05b8 100644 --- a/Minecraft.World/Level/Storage/McRegionChunkStorage.h +++ b/Minecraft.World/Level/Storage/McRegionChunkStorage.h @@ -1,6 +1,5 @@ #pragma once - #include "ChunkStorage.h" #include "../LevelChunk.h" #include "RegionFileCache.h" @@ -9,35 +8,34 @@ class ConsoleSaveFile; -class McRegionChunkStorage : public ChunkStorage -{ +class McRegionChunkStorage : public ChunkStorage { private: - const std::wstring m_prefix; - ConsoleSaveFile *m_saveFile; - static CRITICAL_SECTION cs_memory; + const std::wstring m_prefix; + ConsoleSaveFile* m_saveFile; + static CRITICAL_SECTION cs_memory; - std::unordered_map<__int64, byteArray> m_entityData; + std::unordered_map<__int64, byteArray> m_entityData; - static std::deque s_chunkDataQueue; - static int s_runningThreadCount; - static C4JThread *s_saveThreads[3]; + static std::deque s_chunkDataQueue; + static int s_runningThreadCount; + static C4JThread* s_saveThreads[3]; public: - McRegionChunkStorage(ConsoleSaveFile *saveFile, const std::wstring &prefix); - ~McRegionChunkStorage(); - static void staticCtor(); + McRegionChunkStorage(ConsoleSaveFile* saveFile, const std::wstring& prefix); + ~McRegionChunkStorage(); + static void staticCtor(); - virtual LevelChunk *load(Level *level, int x, int z); - virtual void save(Level *level, LevelChunk *levelChunk); - virtual void saveEntities(Level *level, LevelChunk *levelChunk); - virtual void loadEntities(Level *level, LevelChunk *levelChunk); - virtual void tick(); - virtual void flush(); - virtual void WaitForAll(); // 4J Added - virtual void WaitIfTooManyQueuedChunks(); // 4J Added + virtual LevelChunk* load(Level* level, int x, int z); + virtual void save(Level* level, LevelChunk* levelChunk); + virtual void saveEntities(Level* level, LevelChunk* levelChunk); + virtual void loadEntities(Level* level, LevelChunk* levelChunk); + virtual void tick(); + virtual void flush(); + virtual void WaitForAll(); // 4J Added + virtual void WaitIfTooManyQueuedChunks(); // 4J Added private: - static void WaitForAllSaves(); - static void WaitForSaves(); - static int runSaveThreadProc(void *lpParam); + static void WaitForAllSaves(); + static void WaitForSaves(); + static int runSaveThreadProc(void* lpParam); }; diff --git a/Minecraft.World/Level/Storage/McRegionLevelStorage.cpp b/Minecraft.World/Level/Storage/McRegionLevelStorage.cpp index 336b2f372..1046da478 100644 --- a/Minecraft.World/Level/Storage/McRegionLevelStorage.cpp +++ b/Minecraft.World/Level/Storage/McRegionLevelStorage.cpp @@ -7,97 +7,96 @@ #include "../../IO/Files/File.h" #include "McRegionLevelStorage.h" -McRegionLevelStorage::McRegionLevelStorage(ConsoleSaveFile *saveFile, File dir, const std::wstring& levelName, bool createPlayerDir) - : DirectoryLevelStorage(saveFile, dir, levelName, createPlayerDir) -{ - RegionFileCache::clear(); +McRegionLevelStorage::McRegionLevelStorage(ConsoleSaveFile* saveFile, File dir, + const std::wstring& levelName, + bool createPlayerDir) + : DirectoryLevelStorage(saveFile, dir, levelName, createPlayerDir) { + RegionFileCache::clear(); } -McRegionLevelStorage::~McRegionLevelStorage() -{ - // Make sure cache is clear, as the DirectoryLevelStorage destructor is going to be deleting the underlying ConsoleSaveFile - // reference so we don't want the RegionFileCache to still be referencing it either - RegionFileCache::clear(); +McRegionLevelStorage::~McRegionLevelStorage() { + // Make sure cache is clear, as the DirectoryLevelStorage destructor is + // going to be deleting the underlying ConsoleSaveFile reference so we don't + // want the RegionFileCache to still be referencing it either + RegionFileCache::clear(); } -ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) -{ - //File folder = getFolder(); +ChunkStorage* McRegionLevelStorage::createChunkStorage(Dimension* dimension) { + // File folder = getFolder(); - if (dynamic_cast(dimension) != NULL) - { - - if(app.GetResetNether()) - { + if (dynamic_cast(dimension) != NULL) { + if (app.GetResetNether()) { #ifdef SPLIT_SAVES - std::vector *netherFiles = m_saveFile->getRegionFilesByDimension(1); - if(netherFiles!=NULL) - { - unsigned int bytesWritten = 0; - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) - { - m_saveFile->zeroFile(*it, (*it)->getFileSize(), &bytesWritten); - } - delete netherFiles; - } + std::vector* netherFiles = + m_saveFile->getRegionFilesByDimension(1); + if (netherFiles != NULL) { + unsigned int bytesWritten = 0; + for (AUTO_VAR(it, netherFiles->begin()); + it != netherFiles->end(); ++it) { + m_saveFile->zeroFile(*it, (*it)->getFileSize(), + &bytesWritten); + } + delete netherFiles; + } #else - std::vector *netherFiles = m_saveFile->getFilesWithPrefix(LevelStorage::NETHER_FOLDER); - if(netherFiles!=NULL) - { - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) - { - m_saveFile->deleteFile(*it); - } - delete netherFiles; - } + std::vector* netherFiles = + m_saveFile->getFilesWithPrefix(LevelStorage::NETHER_FOLDER); + if (netherFiles != NULL) { + for (AUTO_VAR(it, netherFiles->begin()); + it != netherFiles->end(); ++it) { + m_saveFile->deleteFile(*it); + } + delete netherFiles; + } #endif - resetNetherPlayerPositions(); - } + resetNetherPlayerPositions(); + } - return new McRegionChunkStorage(m_saveFile, LevelStorage::NETHER_FOLDER); + return new McRegionChunkStorage(m_saveFile, + LevelStorage::NETHER_FOLDER); } - - if (dynamic_cast(dimension)) - { - //File dir2 = new File(folder, LevelStorage.ENDER_FOLDER); - //dir2.mkdirs(); - //return new ThreadedMcRegionChunkStorage(dir2); - - // 4J-PB - save version 0 at this point means it's a create new world - int iSaveVersion=m_saveFile->getSaveVersion(); - if((iSaveVersion!=0) && (iSaveVersion < SAVE_FILE_VERSION_NEW_END)) - { - // For versions before TU9 (TU7 and 8) we generate a part of The End, but we want to scrap it if it exists so that it is replaced with the TU9+ version - app.DebugPrintf("Loaded save version number is: %d, required to keep The End is: %d\n",m_saveFile->getSaveVersion(), SAVE_FILE_VERSION_NEW_END); + if (dynamic_cast(dimension)) { + // File dir2 = new File(folder, LevelStorage.ENDER_FOLDER); + // dir2.mkdirs(); + // return new ThreadedMcRegionChunkStorage(dir2); - std::vector *endFiles = m_saveFile->getFilesWithPrefix(LevelStorage::ENDER_FOLDER); + // 4J-PB - save version 0 at this point means it's a create new world + int iSaveVersion = m_saveFile->getSaveVersion(); - // 4J-PB - There will be no End in early saves - if(endFiles!=NULL) - { - for(AUTO_VAR(it, endFiles->begin()); it != endFiles->end(); ++it) - { - m_saveFile->deleteFile(*it); - } - delete endFiles; - } - } - return new McRegionChunkStorage(m_saveFile, LevelStorage::ENDER_FOLDER); - } + if ((iSaveVersion != 0) && (iSaveVersion < SAVE_FILE_VERSION_NEW_END)) { + // For versions before TU9 (TU7 and 8) we generate a part of The + // End, but we want to scrap it if it exists so that it is replaced + // with the TU9+ version + app.DebugPrintf( + "Loaded save version number is: %d, required to keep The End " + "is: %d\n", + m_saveFile->getSaveVersion(), SAVE_FILE_VERSION_NEW_END); + + std::vector* endFiles = + m_saveFile->getFilesWithPrefix(LevelStorage::ENDER_FOLDER); + + // 4J-PB - There will be no End in early saves + if (endFiles != NULL) { + for (AUTO_VAR(it, endFiles->begin()); it != endFiles->end(); + ++it) { + m_saveFile->deleteFile(*it); + } + delete endFiles; + } + } + return new McRegionChunkStorage(m_saveFile, LevelStorage::ENDER_FOLDER); + } return new McRegionChunkStorage(m_saveFile, L""); } -void McRegionLevelStorage::saveLevelData(LevelData *levelData, std::vector > *players) -{ +void McRegionLevelStorage::saveLevelData( + LevelData* levelData, std::vector >* players) { levelData->setVersion(MCREGION_VERSION_ID); - MemSect(38); + MemSect(38); DirectoryLevelStorage::saveLevelData(levelData, players); - MemSect(0); + MemSect(0); } -void McRegionLevelStorage::closeAll() -{ - RegionFileCache::clear(); -} +void McRegionLevelStorage::closeAll() { RegionFileCache::clear(); } diff --git a/Minecraft.World/Level/Storage/McRegionLevelStorage.h b/Minecraft.World/Level/Storage/McRegionLevelStorage.h index d9b48e57c..9ba264ff5 100644 --- a/Minecraft.World/Level/Storage/McRegionLevelStorage.h +++ b/Minecraft.World/Level/Storage/McRegionLevelStorage.h @@ -1,22 +1,23 @@ #pragma once - #include "DirectoryLevelStorage.h" -class McRegionLevelStorage : public DirectoryLevelStorage -{ -// private static final Logger logger = Logger.getLogger("Minecraft"); +class McRegionLevelStorage : public DirectoryLevelStorage { + // private static final Logger logger = Logger.getLogger("Minecraft"); - friend class McRegionLevelStorageSource; // 4J Jev, needs access to protected members. + friend class McRegionLevelStorageSource; // 4J Jev, needs access to + // protected members. protected: - static const int MCREGION_VERSION_ID = 0x4abc; + static const int MCREGION_VERSION_ID = 0x4abc; public: - McRegionLevelStorage(ConsoleSaveFile *saveFile, File dir, const std::wstring& levelName, bool createPlayerDir); - ~McRegionLevelStorage(); + McRegionLevelStorage(ConsoleSaveFile* saveFile, File dir, + const std::wstring& levelName, bool createPlayerDir); + ~McRegionLevelStorage(); - virtual ChunkStorage *createChunkStorage(Dimension *dimension); - virtual void saveLevelData(LevelData *levelData, std::vector > *players); + virtual ChunkStorage* createChunkStorage(Dimension* dimension); + virtual void saveLevelData(LevelData* levelData, + std::vector >* players); virtual void closeAll(); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/McRegionLevelStorageSource.cpp b/Minecraft.World/Level/Storage/McRegionLevelStorageSource.cpp index f41b26396..aa485816f 100644 --- a/Minecraft.World/Level/Storage/McRegionLevelStorageSource.cpp +++ b/Minecraft.World/Level/Storage/McRegionLevelStorageSource.cpp @@ -23,19 +23,16 @@ const std::tr1::wregex McRegionLevelStorageSource::FolderFilter::chunkFolderPatt const std::tr1::wregex McRegionLevelStorageSource::ChunkFilter::chunkFilePattern = std::tr1::wregex(L"c\\.(-?[0-9a-z]+)\\.(-?[0-9a-z]+)\\.dat"); #endif -McRegionLevelStorageSource::McRegionLevelStorageSource(File dir) : DirectoryLevelStorageSource(dir) -{ +McRegionLevelStorageSource::McRegionLevelStorageSource(File dir) + : DirectoryLevelStorageSource(dir) {} + +std::wstring McRegionLevelStorageSource::getName() { + return L"Scaevolus' McRegion"; } -std::wstring McRegionLevelStorageSource::getName() -{ - return L"Scaevolus' McRegion"; -} - -std::vector *McRegionLevelStorageSource::getLevelList() -{ - // 4J Stu - We don't need to do directory lookups with the xbox save files - std::vector *levels = new std::vector; +std::vector* McRegionLevelStorageSource::getLevelList() { + // 4J Stu - We don't need to do directory lookups with the xbox save files + std::vector* levels = new std::vector; #if 0 std::vector *subFolders = baseDir.listFiles(); File *file; @@ -67,53 +64,53 @@ std::vector *McRegionLevelStorageSource::getLevelList() } } #endif - return levels; + return levels; } -void McRegionLevelStorageSource::clearAll() -{ +void McRegionLevelStorageSource::clearAll() {} + +std::shared_ptr McRegionLevelStorageSource::selectLevel( + ConsoleSaveFile* saveFile, const std::wstring& levelId, + bool createPlayerDir) { + // return new LevelStorageProfilerDecorator(new + // McRegionLevelStorage(baseDir, levelId, createPlayerDir)); + return std::shared_ptr( + new McRegionLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); } -std::shared_ptr McRegionLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, bool createPlayerDir) -{ - // return new LevelStorageProfilerDecorator(new McRegionLevelStorage(baseDir, levelId, createPlayerDir)); - return std::shared_ptr(new McRegionLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); +bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile* saveFile, + const std::wstring& levelId) { + // check if there is old file format level data + LevelData* levelData = getDataTagFor(saveFile, levelId); + if (levelData == NULL || levelData->getVersion() != 0) { + delete levelData; + return false; + } + delete levelData; + + return true; } -bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const std::wstring& levelId) -{ - // check if there is old file format level data - LevelData *levelData = getDataTagFor(saveFile, levelId); - if (levelData == NULL || levelData->getVersion() != 0) - { - delete levelData; - return false; - } - delete levelData; +bool McRegionLevelStorageSource::requiresConversion( + ConsoleSaveFile* saveFile, const std::wstring& levelId) { + LevelData* levelData = getDataTagFor(saveFile, levelId); + if (levelData == NULL || levelData->getVersion() != 0) { + delete levelData; + return false; + } + delete levelData; - return true; + return true; } -bool McRegionLevelStorageSource::requiresConversion(ConsoleSaveFile *saveFile, const std::wstring& levelId) -{ - LevelData *levelData = getDataTagFor(saveFile, levelId); - if (levelData == NULL || levelData->getVersion() != 0) - { - delete levelData; - return false; - } - delete levelData; - - return true; -} - -bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, ProgressListener *progress) -{ - assert(false); - // I removed this while updating the saves to use the single save file - // Will we ever use this convertLevel function anyway? The main issue is the check - // for the hellFolder.exists() which would require a slight change to the way our - // save files are structured +bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + ProgressListener* progress) { + assert(false); + // I removed this while updating the saves to use the single save file + // Will we ever use this convertLevel function anyway? The main issue is the + // check for the hellFolder.exists() which would require a slight change to + // the way our save files are structured #if 0 progress->progressStagePercentage(0); @@ -168,7 +165,7 @@ bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const s eraseFolders(netherBaseFolders, normalRegions->size() + netherRegions->size() + normalBaseFolders->size(), totalCount, progress); } #endif - return true; + return true; } #if 0 @@ -210,11 +207,12 @@ void McRegionLevelStorageSource::addRegions(File &baseFolder, std::vector *chunkFiles, int currentCount, int totalCount, ProgressListener *progress) -{ - assert( false ); +void McRegionLevelStorageSource::convertRegions( + File& baseFolder, std::vector* chunkFiles, int currentCount, + int totalCount, ProgressListener* progress) { + assert(false); - // 4J Stu - Removed, see comment in convertLevel above + // 4J Stu - Removed, see comment in convertLevel above #if 0 //Collections::sort(chunkFiles); std::sort( chunkFiles->begin(), chunkFiles->end() ); @@ -266,25 +264,25 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, std::vector *folders, int currentCount, int totalCount, ProgressListener *progress) -{ - File *folder; - AUTO_VAR(itEnd, folders->end()); - for (AUTO_VAR(it, folders->begin()); it != itEnd; it++) - { - folder = *it; //folders->at(i); +void McRegionLevelStorageSource::eraseFolders(std::vector* folders, + int currentCount, int totalCount, + ProgressListener* progress) { + File* folder; + AUTO_VAR(itEnd, folders->end()); + for (AUTO_VAR(it, folders->begin()); it != itEnd; it++) { + folder = *it; // folders->at(i); - std::vector *files = folder->listFiles(); - deleteRecursive(files); - folder->_delete(); + std::vector* files = folder->listFiles(); + deleteRecursive(files); + folder->_delete(); - currentCount++; - int percent = (int) Math::round(100.0 * (double) currentCount / (double) totalCount); - progress->progressStagePercentage(percent); - } + currentCount++; + int percent = + (int)Math::round(100.0 * (double)currentCount / (double)totalCount); + progress->progressStagePercentage(percent); + } } #if 0 diff --git a/Minecraft.World/Level/Storage/McRegionLevelStorageSource.h b/Minecraft.World/Level/Storage/McRegionLevelStorageSource.h index e0437c613..ed24d75f5 100644 --- a/Minecraft.World/Level/Storage/McRegionLevelStorageSource.h +++ b/Minecraft.World/Level/Storage/McRegionLevelStorageSource.h @@ -1,6 +1,5 @@ #pragma once - #include "DirectoryLevelStorageSource.h" #include "../../IO/Files/FileFilter.h" #include "../../IO/Files/FilenameFilter.h" @@ -8,27 +7,35 @@ class ProgressListener; class LevelStorage; -class McRegionLevelStorageSource : public DirectoryLevelStorageSource -{ +class McRegionLevelStorageSource : public DirectoryLevelStorageSource { public: - class ChunkFile; + class ChunkFile; - McRegionLevelStorageSource(File dir); + McRegionLevelStorageSource(File dir); virtual std::wstring getName(); - virtual std::vector *getLevelList(); + virtual std::vector* getLevelList(); virtual void clearAll(); - virtual std::shared_ptr selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, bool createPlayerDir); - virtual bool isConvertible(ConsoleSaveFile *saveFile, const std::wstring& levelId); - virtual bool requiresConversion(ConsoleSaveFile *saveFile, const std::wstring& levelId); - virtual bool convertLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, ProgressListener *progress); + virtual std::shared_ptr selectLevel( + ConsoleSaveFile* saveFile, const std::wstring& levelId, + bool createPlayerDir); + virtual bool isConvertible(ConsoleSaveFile* saveFile, + const std::wstring& levelId); + virtual bool requiresConversion(ConsoleSaveFile* saveFile, + const std::wstring& levelId); + virtual bool convertLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + ProgressListener* progress); private: #if 0 // 4J - not required anymore void addRegions(File &baseFolder, std::vector *dest, std::vector *firstLevelFolders); #endif - void convertRegions(File &baseFolder, std::vector *chunkFiles, int currentCount, int totalCount, ProgressListener *progress); - void eraseFolders(std::vector *folders, int currentCount, int totalCount, ProgressListener *progress); + void convertRegions(File& baseFolder, std::vector* chunkFiles, + int currentCount, int totalCount, + ProgressListener* progress); + void eraseFolders(std::vector* folders, int currentCount, + int totalCount, ProgressListener* progress); public: #if 0 diff --git a/Minecraft.World/Level/Storage/MemoryChunkStorage.cpp b/Minecraft.World/Level/Storage/MemoryChunkStorage.cpp index d8dd379a6..529a21899 100644 --- a/Minecraft.World/Level/Storage/MemoryChunkStorage.cpp +++ b/Minecraft.World/Level/Storage/MemoryChunkStorage.cpp @@ -3,23 +3,20 @@ #include "../../Headers/net.minecraft.world.level.chunk.h" #include "MemoryChunkStorage.h" -LevelChunk *MemoryChunkStorage::load(Level *level, int x, int z) //throws IOException +LevelChunk* MemoryChunkStorage::load(Level* level, int x, + int z) // throws IOException { - return NULL; + return NULL; } -void MemoryChunkStorage::save(Level *level, LevelChunk *levelChunk) //throws IOException -{ -} +void MemoryChunkStorage::save(Level* level, + LevelChunk* levelChunk) // throws IOException +{} -void MemoryChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk) //throws IOException -{ -} +void MemoryChunkStorage::saveEntities( + Level* level, LevelChunk* levelChunk) // throws IOException +{} -void MemoryChunkStorage::tick() -{ -} +void MemoryChunkStorage::tick() {} -void MemoryChunkStorage::flush() -{ -} \ No newline at end of file +void MemoryChunkStorage::flush() {} \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MemoryChunkStorage.h b/Minecraft.World/Level/Storage/MemoryChunkStorage.h index b3076c4bc..01bfca74e 100644 --- a/Minecraft.World/Level/Storage/MemoryChunkStorage.h +++ b/Minecraft.World/Level/Storage/MemoryChunkStorage.h @@ -1,14 +1,12 @@ #pragma once - #include "../ChunkSource.h" -class MemoryChunkStorage : public ChunkStorage -{ +class MemoryChunkStorage : public ChunkStorage { public: - virtual LevelChunk *load(Level *level, int x, int z); - virtual void save(Level *level, LevelChunk *levelChunk); - virtual void saveEntities(Level *level, LevelChunk *levelChunk); + virtual LevelChunk* load(Level* level, int x, int z); + virtual void save(Level* level, LevelChunk* levelChunk); + virtual void saveEntities(Level* level, LevelChunk* levelChunk); virtual void tick(); virtual void flush(); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MemoryLevelStorage.cpp b/Minecraft.World/Level/Storage/MemoryLevelStorage.cpp index 4b1ad47db..c35a58279 100644 --- a/Minecraft.World/Level/Storage/MemoryLevelStorage.cpp +++ b/Minecraft.World/Level/Storage/MemoryLevelStorage.cpp @@ -8,56 +8,34 @@ #include "../../IO/Files/ConsoleSaveFileIO.h" -MemoryLevelStorage::MemoryLevelStorage() -{ +MemoryLevelStorage::MemoryLevelStorage() {} + +LevelData* MemoryLevelStorage::prepareLevel() { return NULL; } + +void MemoryLevelStorage::checkSession() {} + +ChunkStorage* MemoryLevelStorage::createChunkStorage(Dimension* dimension) { + return new MemoryChunkStorage(); } -LevelData *MemoryLevelStorage::prepareLevel() -{ - return NULL; +void MemoryLevelStorage::saveLevelData( + LevelData* levelData, std::vector >* players) {} + +void MemoryLevelStorage::saveLevelData(LevelData* levelData) {} + +PlayerIO* MemoryLevelStorage::getPlayerIO() { return this; } + +void MemoryLevelStorage::closeAll() {} + +void MemoryLevelStorage::save(std::shared_ptr player) {} + +bool MemoryLevelStorage::load(std::shared_ptr player) { return false; } + +CompoundTag* MemoryLevelStorage::loadPlayerDataTag( + const std::wstring& playerName) { + return NULL; } -void MemoryLevelStorage::checkSession() -{ -} - -ChunkStorage *MemoryLevelStorage::createChunkStorage(Dimension *dimension) -{ - return new MemoryChunkStorage(); -} - -void MemoryLevelStorage::saveLevelData(LevelData *levelData, std::vector > *players) -{ -} - -void MemoryLevelStorage::saveLevelData(LevelData *levelData) -{ -} - -PlayerIO *MemoryLevelStorage::getPlayerIO() -{ - return this; -} - -void MemoryLevelStorage::closeAll() -{ -} - -void MemoryLevelStorage::save(std::shared_ptr player) -{ -} - -bool MemoryLevelStorage::load(std::shared_ptr player) -{ - return false; -} - -CompoundTag *MemoryLevelStorage::loadPlayerDataTag(const std::wstring& playerName) -{ - return NULL; -} - -ConsoleSavePath MemoryLevelStorage::getDataFile(const std::wstring& id) -{ - return ConsoleSaveFile(std::wstring(L"")); +ConsoleSavePath MemoryLevelStorage::getDataFile(const std::wstring& id) { + return ConsoleSaveFile(std::wstring(L"")); } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MemoryLevelStorage.h b/Minecraft.World/Level/Storage/MemoryLevelStorage.h index 307b08027..95577dbaf 100644 --- a/Minecraft.World/Level/Storage/MemoryLevelStorage.h +++ b/Minecraft.World/Level/Storage/MemoryLevelStorage.h @@ -1,6 +1,5 @@ #pragma once - #include "LevelStorage.h" #include "PlayerIO.h" @@ -13,19 +12,19 @@ #include "../../IO/Files/ConsoleSaveFile.h" -class MemoryLevelStorage : public LevelStorage, public PlayerIO -{ +class MemoryLevelStorage : public LevelStorage, public PlayerIO { public: MemoryLevelStorage(); - virtual LevelData *prepareLevel(); + virtual LevelData* prepareLevel(); virtual void checkSession(); - virtual ChunkStorage *createChunkStorage(Dimension *dimension); - virtual void saveLevelData(LevelData *levelData, std::vector > *players); - virtual void saveLevelData(LevelData *levelData); - virtual PlayerIO *getPlayerIO(); + virtual ChunkStorage* createChunkStorage(Dimension* dimension); + virtual void saveLevelData(LevelData* levelData, + std::vector >* players); + virtual void saveLevelData(LevelData* levelData); + virtual PlayerIO* getPlayerIO(); virtual void closeAll(); virtual void save(std::shared_ptr player); virtual bool load(std::shared_ptr player); - virtual CompoundTag *loadPlayerDataTag(const std::wstring& playerName); + virtual CompoundTag* loadPlayerDataTag(const std::wstring& playerName); virtual ConsoleSavePath getDataFile(const std::wstring& id); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MemoryLevelStorageSource.cpp b/Minecraft.World/Level/Storage/MemoryLevelStorageSource.cpp index e0e81d155..c51a10ebb 100644 --- a/Minecraft.World/Level/Storage/MemoryLevelStorageSource.cpp +++ b/Minecraft.World/Level/Storage/MemoryLevelStorageSource.cpp @@ -4,58 +4,45 @@ #include "LevelSummary.h" #include "MemoryLevelStorageSource.h" -MemoryLevelStorageSource::MemoryLevelStorageSource() -{ +MemoryLevelStorageSource::MemoryLevelStorageSource() {} + +std::wstring MemoryLevelStorageSource::getName() { return L"Memory Storage"; } + +std::shared_ptr MemoryLevelStorageSource::selectLevel( + const std::wstring& levelId, bool createPlayerDir) { + return std::shared_ptr () new MemoryLevelStorage()); } -std::wstring MemoryLevelStorageSource::getName() -{ - return L"Memory Storage"; +std::vector* MemoryLevelStorageSource::getLevelList() { + return new std::vector; } -std::shared_ptr MemoryLevelStorageSource::selectLevel(const std::wstring& levelId, bool createPlayerDir) -{ - return std::shared_ptr () new MemoryLevelStorage()); +void MemoryLevelStorageSource::clearAll() {} + +LevelData* MemoryLevelStorageSource::getDataTagFor( + const std::wstring& levelId) { + return NULL; } -std::vector *MemoryLevelStorageSource::getLevelList() -{ - return new std::vector; +bool MemoryLevelStorageSource::isNewLevelIdAcceptable( + const std::wstring& levelId) { + return true; } -void MemoryLevelStorageSource::clearAll() -{ +void MemoryLevelStorageSource::deleteLevel(const std::wstring& levelId) {} + +void MemoryLevelStorageSource::renameLevel(const std::wstring& levelId, + const std::wstring& newLevelName) {} + +bool MemoryLevelStorageSource::isConvertible(const std::wstring& levelId) { + return false; } -LevelData *MemoryLevelStorageSource::getDataTagFor(const std::wstring& levelId) -{ - return NULL; +bool MemoryLevelStorageSource::requiresConversion(const std::wstring& levelId) { + return false; } -bool MemoryLevelStorageSource::isNewLevelIdAcceptable(const std::wstring& levelId) -{ - return true; -} - -void MemoryLevelStorageSource::deleteLevel(const std::wstring& levelId) -{ -} - -void MemoryLevelStorageSource::renameLevel(const std::wstring& levelId, const std::wstring& newLevelName) -{ -} - -bool MemoryLevelStorageSource::isConvertible(const std::wstring& levelId) -{ - return false; -} - -bool MemoryLevelStorageSource::requiresConversion(const std::wstring& levelId) -{ - return false; -} - -bool MemoryLevelStorageSource::convertLevel(const std::wstring& levelId, ProgressListener *progress) -{ - return false; +bool MemoryLevelStorageSource::convertLevel(const std::wstring& levelId, + ProgressListener* progress) { + return false; } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MemoryLevelStorageSource.h b/Minecraft.World/Level/Storage/MemoryLevelStorageSource.h index 9e21429d9..827f29fe8 100644 --- a/Minecraft.World/Level/Storage/MemoryLevelStorageSource.h +++ b/Minecraft.World/Level/Storage/MemoryLevelStorageSource.h @@ -1,21 +1,21 @@ #pragma once - #include "LevelStorageSource.h" -class MemoryLevelStorageSource : public LevelStorageSource -{ +class MemoryLevelStorageSource : public LevelStorageSource { public: MemoryLevelStorageSource(); std::wstring getName(); - std::shared_ptr selectLevel(const std::wstring& levelId, bool createPlayerDir); - std::vector *getLevelList(); + std::shared_ptr selectLevel(const std::wstring& levelId, + bool createPlayerDir); + std::vector* getLevelList(); void clearAll(); - LevelData *getDataTagFor(const std::wstring& levelId); + LevelData* getDataTagFor(const std::wstring& levelId); bool isNewLevelIdAcceptable(const std::wstring& levelId); void deleteLevel(const std::wstring& levelId); - void renameLevel(const std::wstring& levelId, const std::wstring& newLevelName); + void renameLevel(const std::wstring& levelId, + const std::wstring& newLevelName); bool isConvertible(const std::wstring& levelId); bool requiresConversion(const std::wstring& levelId); - bool convertLevel(const std::wstring& levelId, ProgressListener *progress); + bool convertLevel(const std::wstring& levelId, ProgressListener* progress); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MockedLevelStorage.cpp b/Minecraft.World/Level/Storage/MockedLevelStorage.cpp index 86faefe1f..de6255ab1 100644 --- a/Minecraft.World/Level/Storage/MockedLevelStorage.cpp +++ b/Minecraft.World/Level/Storage/MockedLevelStorage.cpp @@ -7,43 +7,25 @@ #include "../../IO/Files/ConsoleSaveFileIO.h" -LevelData *MockedLevelStorage::prepareLevel() -{ +LevelData* MockedLevelStorage::prepareLevel() { return NULL; } + +void MockedLevelStorage::checkSession() {} + +ChunkStorage* MockedLevelStorage::createChunkStorage(Dimension* dimension) { return NULL; } -void MockedLevelStorage::checkSession() -{ -} +void MockedLevelStorage::saveLevelData( + LevelData* levelData, std::vector >* players) {} -ChunkStorage *MockedLevelStorage::createChunkStorage(Dimension *dimension) -{ - return NULL; -} +void MockedLevelStorage::saveLevelData(LevelData* levelData) {} -void MockedLevelStorage::saveLevelData(LevelData *levelData, std::vector > *players) -{ -} +PlayerIO* MockedLevelStorage::getPlayerIO() { return NULL; } -void MockedLevelStorage::saveLevelData(LevelData *levelData) -{ -} +void MockedLevelStorage::closeAll() {} -PlayerIO *MockedLevelStorage::getPlayerIO() -{ - return NULL; -} - -void MockedLevelStorage::closeAll() -{ -} - -ConsoleSavePath MockedLevelStorage::getDataFile(const std::wstring& id) -{ +ConsoleSavePath MockedLevelStorage::getDataFile(const std::wstring& id) { return ConsoleSavePath(std::wstring(L"")); } -std::wstring MockedLevelStorage::getLevelId() -{ - return L"none"; -} \ No newline at end of file +std::wstring MockedLevelStorage::getLevelId() { return L"none"; } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/MockedLevelStorage.h b/Minecraft.World/Level/Storage/MockedLevelStorage.h index 5c4736806..fcab5ec42 100644 --- a/Minecraft.World/Level/Storage/MockedLevelStorage.h +++ b/Minecraft.World/Level/Storage/MockedLevelStorage.h @@ -1,22 +1,22 @@ #pragma once - #include "LevelStorage.h" #include "../../IO/Files/ConsoleSavePath.h" -class MockedLevelStorage : public LevelStorage -{ +class MockedLevelStorage : public LevelStorage { public: - virtual LevelData *prepareLevel(); - virtual void checkSession(); - virtual ChunkStorage *createChunkStorage(Dimension *dimension); - virtual void saveLevelData(LevelData *levelData, std::vector > *players); - virtual void saveLevelData(LevelData *levelData); - virtual PlayerIO *getPlayerIO(); - virtual void closeAll(); - virtual ConsoleSavePath getDataFile(const std::wstring& id); - virtual std::wstring getLevelId(); + virtual LevelData* prepareLevel(); + virtual void checkSession(); + virtual ChunkStorage* createChunkStorage(Dimension* dimension); + virtual void saveLevelData(LevelData* levelData, + std::vector >* players); + virtual void saveLevelData(LevelData* levelData); + virtual PlayerIO* getPlayerIO(); + virtual void closeAll(); + virtual ConsoleSavePath getDataFile(const std::wstring& id); + virtual std::wstring getLevelId(); + public: - virtual ConsoleSaveFile *getSaveFile() { return NULL; } + virtual ConsoleSaveFile* getSaveFile() { return NULL; } }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/OldChunkStorage.cpp b/Minecraft.World/Level/Storage/OldChunkStorage.cpp index 14523a624..7eafbe21a 100644 --- a/Minecraft.World/Level/Storage/OldChunkStorage.cpp +++ b/Minecraft.World/Level/Storage/OldChunkStorage.cpp @@ -9,561 +9,562 @@ #include "../../IO/Files/FileHeader.h" #include "OldChunkStorage.h" #if defined(_WIN32) -namespace -{ - inline void *OldChunkStorageTlsGetValue(DWORD key) - { - return TlsGetValue(key); - } +namespace { +inline void* OldChunkStorageTlsGetValue(DWORD key) { return TlsGetValue(key); } - inline void OldChunkStorageTlsSetValue(DWORD key, void *value) - { - TlsSetValue(key, value); - } +inline void OldChunkStorageTlsSetValue(DWORD key, void* value) { + TlsSetValue(key, value); } +} // namespace DWORD OldChunkStorage::tlsIdx = TlsAlloc(); #else -namespace -{ - pthread_key_t CreateOldChunkStorageTlsKey() - { - pthread_key_t key; - const int result = pthread_key_create(&key, nullptr); - assert(result == 0); - return key; - } - - inline void *OldChunkStorageTlsGetValue(pthread_key_t key) - { - return pthread_getspecific(key); - } - - inline void OldChunkStorageTlsSetValue(pthread_key_t key, void *value) - { - pthread_setspecific(key, value); - } +namespace { +pthread_key_t CreateOldChunkStorageTlsKey() { + pthread_key_t key; + const int result = pthread_key_create(&key, nullptr); + assert(result == 0); + return key; } +inline void* OldChunkStorageTlsGetValue(pthread_key_t key) { + return pthread_getspecific(key); +} + +inline void OldChunkStorageTlsSetValue(pthread_key_t key, void* value) { + pthread_setspecific(key, value); +} +} // namespace + pthread_key_t OldChunkStorage::tlsIdx = CreateOldChunkStorageTlsKey(); #endif -OldChunkStorage::ThreadStorage *OldChunkStorage::tlsDefault = NULL; +OldChunkStorage::ThreadStorage* OldChunkStorage::tlsDefault = NULL; -OldChunkStorage::ThreadStorage::ThreadStorage() -{ - blockData = byteArray(Level::CHUNK_TILE_COUNT); - dataData = byteArray(Level::HALF_CHUNK_TILE_COUNT); - skyLightData = byteArray(Level::HALF_CHUNK_TILE_COUNT); - blockLightData = byteArray(Level::HALF_CHUNK_TILE_COUNT); +OldChunkStorage::ThreadStorage::ThreadStorage() { + blockData = byteArray(Level::CHUNK_TILE_COUNT); + dataData = byteArray(Level::HALF_CHUNK_TILE_COUNT); + skyLightData = byteArray(Level::HALF_CHUNK_TILE_COUNT); + blockLightData = byteArray(Level::HALF_CHUNK_TILE_COUNT); } -OldChunkStorage::ThreadStorage::~ThreadStorage() -{ - delete [] blockData.data; - delete [] dataData.data; - delete [] skyLightData.data; - delete [] blockLightData.data; +OldChunkStorage::ThreadStorage::~ThreadStorage() { + delete[] blockData.data; + delete[] dataData.data; + delete[] skyLightData.data; + delete[] blockLightData.data; } -void OldChunkStorage::CreateNewThreadStorage() -{ - ThreadStorage *tls = new ThreadStorage(); - if(tlsDefault == NULL ) - { - tlsDefault = tls; - } - OldChunkStorageTlsSetValue(tlsIdx, tls); +void OldChunkStorage::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + if (tlsDefault == NULL) { + tlsDefault = tls; + } + OldChunkStorageTlsSetValue(tlsIdx, tls); } -void OldChunkStorage::UseDefaultThreadStorage() -{ - OldChunkStorageTlsSetValue(tlsIdx, tlsDefault); +void OldChunkStorage::UseDefaultThreadStorage() { + OldChunkStorageTlsSetValue(tlsIdx, tlsDefault); } -void OldChunkStorage::ReleaseThreadStorage() -{ - ThreadStorage *tls = static_cast(OldChunkStorageTlsGetValue(tlsIdx)); - if( tls == tlsDefault ) return; +void OldChunkStorage::ReleaseThreadStorage() { + ThreadStorage* tls = + static_cast(OldChunkStorageTlsGetValue(tlsIdx)); + if (tls == tlsDefault) return; - delete tls; + delete tls; } -OldChunkStorage::OldChunkStorage(File dir, bool create) -{ - this->dir = dir; - this->create = create; +OldChunkStorage::OldChunkStorage(File dir, bool create) { + this->dir = dir; + this->create = create; } -File OldChunkStorage::getFile(int x, int z) -{ - wchar_t name[MAX_PATH_SIZE]; - wchar_t path1[MAX_PATH_SIZE]; - wchar_t path2[MAX_PATH_SIZE]; +File OldChunkStorage::getFile(int x, int z) { + wchar_t name[MAX_PATH_SIZE]; + wchar_t path1[MAX_PATH_SIZE]; + wchar_t path2[MAX_PATH_SIZE]; - wchar_t xRadix36[64]; - wchar_t zRadix36[64]; -#if ( defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined __linux__ ) - assert(0); // need a gcc verison of _itow ? + wchar_t xRadix36[64]; + wchar_t zRadix36[64]; +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined __linux__) + assert(0); // need a gcc verison of _itow ? #else - _itow(x,xRadix36,36); - _itow(z,zRadix36,36); - swprintf(name,MAX_PATH_SIZE,L"c.%ls.%ls.dat",xRadix36,zRadix36); - _itow(x & 63,path1,36); - _itow(z & 63,path2,36); + _itow(x, xRadix36, 36); + _itow(z, zRadix36, 36); + swprintf(name, MAX_PATH_SIZE, L"c.%ls.%ls.dat", xRadix36, zRadix36); + _itow(x & 63, path1, 36); + _itow(z & 63, path2, 36); #endif - //sprintf(file,"%s\\%s",dir,path1); - File file( dir, std::wstring( path1 ) ); - if( !file.exists() ) - { - if(create) file.mkdir(); - else - { - return File(L""); - } - } + // sprintf(file,"%s\\%s",dir,path1); + File file(dir, std::wstring(path1)); + if (!file.exists()) { + if (create) + file.mkdir(); + else { + return File(L""); + } + } - //strcat(file,"\\"); - //strcat(file,path2); - file = File( file, std::wstring( path2 ) ); - if( !file.exists() ) - { - if(create) file.mkdir(); - else - { - return File(L""); - } - } + // strcat(file,"\\"); + // strcat(file,path2); + file = File(file, std::wstring(path2)); + if (!file.exists()) { + if (create) + file.mkdir(); + else { + return File(L""); + } + } - //strcat(file,"\\"); - //strcat(file,name); - //sprintf(file,"%s\\%s",file,name); - file = File( file, std::wstring( name ) ); - if ( !file.exists() ) - { - if (!create) - { - return File(L""); - } - } - return file; + // strcat(file,"\\"); + // strcat(file,name); + // sprintf(file,"%s\\%s",file,name); + file = File(file, std::wstring(name)); + if (!file.exists()) { + if (!create) { + return File(L""); + } + } + return file; } -LevelChunk *OldChunkStorage::load(Level *level, int x, int z) -{ - File file = getFile(x, z); - if (!file.getPath().empty() && file.exists()) - { - // 4J - removed try/catch - // try { - // System.out.println("Loading chunk "+x+", "+z); - FileInputStream fis = FileInputStream(file); - CompoundTag *tag = NbtIo::readCompressed(&fis); - if (!tag->contains(L"Level")) - { - char buf[256]; - sprintf(buf,"Chunk file at %d, %d is missing level data, skipping\n",x,z); - app.DebugPrintf(buf); - return NULL; - } - if (!tag->getCompound(L"Level")->contains(L"Blocks")) - { - char buf[256]; - sprintf(buf,"Chunk file at %d, %d is missing block data, skipping\n",x,z); - app.DebugPrintf(buf); - return NULL; - } - LevelChunk *levelChunk = OldChunkStorage::load(level, tag->getCompound(L"Level")); - if (!levelChunk->isAt(x, z)) - { - char buf[256]; - sprintf(buf,"Chunk fileat %d, %d is in the wrong location; relocating. Expected %d, %d, got %d, %d\n", - x, z, x, z, levelChunk->x, levelChunk->z); - app.DebugPrintf(buf); - tag->putInt(L"xPos", x); - tag->putInt(L"zPos", z); - levelChunk = OldChunkStorage::load(level, tag->getCompound(L"Level")); - } +LevelChunk* OldChunkStorage::load(Level* level, int x, int z) { + File file = getFile(x, z); + if (!file.getPath().empty() && file.exists()) { + // 4J - removed try/catch + // try { + // System.out.println("Loading chunk "+x+", "+z); + FileInputStream fis = FileInputStream(file); + CompoundTag* tag = NbtIo::readCompressed(&fis); + if (!tag->contains(L"Level")) { + char buf[256]; + sprintf(buf, + "Chunk file at %d, %d is missing level data, skipping\n", x, + z); + app.DebugPrintf(buf); + return NULL; + } + if (!tag->getCompound(L"Level")->contains(L"Blocks")) { + char buf[256]; + sprintf(buf, + "Chunk file at %d, %d is missing block data, skipping\n", x, + z); + app.DebugPrintf(buf); + return NULL; + } + LevelChunk* levelChunk = + OldChunkStorage::load(level, tag->getCompound(L"Level")); + if (!levelChunk->isAt(x, z)) { + char buf[256]; + sprintf(buf, + "Chunk fileat %d, %d is in the wrong location; relocating. " + "Expected %d, %d, got %d, %d\n", + x, z, x, z, levelChunk->x, levelChunk->z); + app.DebugPrintf(buf); + tag->putInt(L"xPos", x); + tag->putInt(L"zPos", z); + levelChunk = + OldChunkStorage::load(level, tag->getCompound(L"Level")); + } - return levelChunk; - // } catch (Exception e) { - // e.printStackTrace(); - // } - } - return NULL; + return levelChunk; + // } catch (Exception e) { + // e.printStackTrace(); + // } + } + return NULL; } -void OldChunkStorage::save(Level *level, LevelChunk *levelChunk) -{ - level->checkSession(); - File file = getFile(levelChunk->x, levelChunk->z); - if (file.exists()) - { - LevelData *levelData = level->getLevelData(); - levelData->setSizeOnDisk( levelData->getSizeOnDisk() - file.length() ); - } +void OldChunkStorage::save(Level* level, LevelChunk* levelChunk) { + level->checkSession(); + File file = getFile(levelChunk->x, levelChunk->z); + if (file.exists()) { + LevelData* levelData = level->getLevelData(); + levelData->setSizeOnDisk(levelData->getSizeOnDisk() - file.length()); + } - // 4J - removed try/catch - // try { - //char tmpFileName[MAX_PATH_SIZE]; - //sprintf(tmpFileName,"%s\\%s",dir,"tmp_chunk.dat"); - File tmpFile( dir, L"tmp_chunk.dat" ); - // System.out.println("Saving chunk "+levelChunk.x+", "+levelChunk.z); + // 4J - removed try/catch + // try { + // char tmpFileName[MAX_PATH_SIZE]; + // sprintf(tmpFileName,"%s\\%s",dir,"tmp_chunk.dat"); + File tmpFile(dir, L"tmp_chunk.dat"); + // System.out.println("Saving chunk "+levelChunk.x+", + // "+levelChunk.z); - FileOutputStream fos = FileOutputStream(tmpFile); - CompoundTag *tag = new CompoundTag(); - CompoundTag *levelData = new CompoundTag(); - tag->put(L"Level", levelData); - OldChunkStorage::save(levelChunk, level, levelData); - NbtIo::writeCompressed(tag, &fos); - fos.close(); + FileOutputStream fos = FileOutputStream(tmpFile); + CompoundTag* tag = new CompoundTag(); + CompoundTag* levelData = new CompoundTag(); + tag->put(L"Level", levelData); + OldChunkStorage::save(levelChunk, level, levelData); + NbtIo::writeCompressed(tag, &fos); + fos.close(); - if (file.exists()) - { - //DeleteFile(file); - file._delete(); - } - //MoveFile(tmpFile,file); - tmpFile.renameTo( file ); + if (file.exists()) { + // DeleteFile(file); + file._delete(); + } + // MoveFile(tmpFile,file); + tmpFile.renameTo(file); - LevelData *levelInfo = level->getLevelData(); - levelInfo->setSizeOnDisk(levelInfo->getSizeOnDisk() + file.length() ); - // } catch (Exception e) { - // e.printStackTrace(); - // } + LevelData* levelInfo = level->getLevelData(); + levelInfo->setSizeOnDisk(levelInfo->getSizeOnDisk() + file.length()); + // } catch (Exception e) { + // e.printStackTrace(); + // } } -bool OldChunkStorage::saveEntities(LevelChunk *lc, Level *level, CompoundTag *tag) -{ - // If we saved and it had no entities, and nothing has been added since skip this one - if(!lc->lastSaveHadEntities) return false; +bool OldChunkStorage::saveEntities(LevelChunk* lc, Level* level, + CompoundTag* tag) { + // If we saved and it had no entities, and nothing has been added since skip + // this one + if (!lc->lastSaveHadEntities) return false; + + lc->lastSaveHadEntities = false; + ListTag* entityTags = new ListTag(); - lc->lastSaveHadEntities = false; - ListTag *entityTags = new ListTag(); - #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&lc->m_csEntities, true); + EnterCriticalRWSection(&lc->m_csEntities, true); #else - EnterCriticalSection(&lc->m_csEntities); + EnterCriticalSection(&lc->m_csEntities); #endif - for (int i = 0; i < lc->ENTITY_BLOCKS_LENGTH; i++) - { - AUTO_VAR(itEnd, lc->entityBlocks[i]->end()); - for( std::vector >::iterator it = lc->entityBlocks[i]->begin(); it != itEnd; it++ ) - { - std::shared_ptr e = *it; - lc->lastSaveHadEntities = true; - CompoundTag *teTag = new CompoundTag(); - if (e->save(teTag)) - { - entityTags->add(teTag); - } - - } - } + for (int i = 0; i < lc->ENTITY_BLOCKS_LENGTH; i++) { + AUTO_VAR(itEnd, lc->entityBlocks[i]->end()); + for (std::vector >::iterator it = + lc->entityBlocks[i]->begin(); + it != itEnd; it++) { + std::shared_ptr e = *it; + lc->lastSaveHadEntities = true; + CompoundTag* teTag = new CompoundTag(); + if (e->save(teTag)) { + entityTags->add(teTag); + } + } + } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&lc->m_csEntities, true); + LeaveCriticalRWSection(&lc->m_csEntities, true); #else - LeaveCriticalSection(&lc->m_csEntities); + LeaveCriticalSection(&lc->m_csEntities); #endif - tag->put(L"Entities", entityTags); + tag->put(L"Entities", entityTags); - return lc->lastSaveHadEntities; + return lc->lastSaveHadEntities; } -void OldChunkStorage::save(LevelChunk *lc, Level *level, DataOutputStream *dos) -{ - dos->writeShort(SAVE_FILE_VERSION_NUMBER); - dos->writeInt(lc->x); - dos->writeInt(lc->z); - dos->writeLong(level->getTime()); +void OldChunkStorage::save(LevelChunk* lc, Level* level, + DataOutputStream* dos) { + dos->writeShort(SAVE_FILE_VERSION_NUMBER); + dos->writeInt(lc->x); + dos->writeInt(lc->z); + dos->writeLong(level->getTime()); - PIXBeginNamedEvent(0,"Getting block data"); - lc->writeCompressedBlockData(dos); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting block data"); + lc->writeCompressedBlockData(dos); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Getting data data"); - lc->writeCompressedDataData(dos); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting data data"); + lc->writeCompressedDataData(dos); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Getting sky and block light data"); - lc->writeCompressedSkyLightData(dos); - lc->writeCompressedBlockLightData(dos); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting sky and block light data"); + lc->writeCompressedSkyLightData(dos); + lc->writeCompressedBlockLightData(dos); + PIXEndNamedEvent(); - dos->write(lc->heightmap); - dos->writeShort(lc->terrainPopulated); - dos->write(lc->getBiomes()); + dos->write(lc->heightmap); + dos->writeShort(lc->terrainPopulated); + dos->write(lc->getBiomes()); - PIXBeginNamedEvent(0,"Saving entities"); - CompoundTag *tag = new CompoundTag(); + PIXBeginNamedEvent(0, "Saving entities"); + CompoundTag* tag = new CompoundTag(); #ifndef SPLIT_SAVES - saveEntities(lc, level, tag); + saveEntities(lc, level, tag); #endif - - PIXBeginNamedEvent(0,"Saving tile entities"); - ListTag *tileEntityTags = new ListTag(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( std::unordered_map, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) - { - std::shared_ptr te = it->second; - CompoundTag *teTag = new CompoundTag(); - te->save(teTag); - tileEntityTags->add(teTag); - } - tag->put(L"TileEntities", tileEntityTags); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Saving tile entities"); + ListTag* tileEntityTags = new ListTag(); - PIXBeginNamedEvent(0,"Saving tile tick data"); - std::vector *ticksInChunk = level->fetchTicksInChunk(lc, false); - if (ticksInChunk != NULL) - { - __int64 levelTime = level->getTime(); + AUTO_VAR(itEnd, lc->tileEntities.end()); + for (std::unordered_map, + TilePosKeyHash, TilePosKeyEq>::iterator it = + lc->tileEntities.begin(); + it != itEnd; it++) { + std::shared_ptr te = it->second; + CompoundTag* teTag = new CompoundTag(); + te->save(teTag); + tileEntityTags->add(teTag); + } + tag->put(L"TileEntities", tileEntityTags); + PIXEndNamedEvent(); - ListTag *tickTags = new ListTag(); - for( int i = 0; i < ticksInChunk->size(); i++ ) - { - TickNextTickData td = ticksInChunk->at(i); - CompoundTag *teTag = new CompoundTag(); - teTag->putInt(L"i", td.tileId); - teTag->putInt(L"x", td.x); - teTag->putInt(L"y", td.y); - teTag->putInt(L"z", td.z); - teTag->putInt(L"t", (int) (td.m_delay - levelTime)); + PIXBeginNamedEvent(0, "Saving tile tick data"); + std::vector* ticksInChunk = + level->fetchTicksInChunk(lc, false); + if (ticksInChunk != NULL) { + __int64 levelTime = level->getTime(); - tickTags->add(teTag); - } - tag->put(L"TileTicks", tickTags); - } - delete ticksInChunk; - PIXEndNamedEvent(); + ListTag* tickTags = new ListTag(); + for (int i = 0; i < ticksInChunk->size(); i++) { + TickNextTickData td = ticksInChunk->at(i); + CompoundTag* teTag = new CompoundTag(); + teTag->putInt(L"i", td.tileId); + teTag->putInt(L"x", td.x); + teTag->putInt(L"y", td.y); + teTag->putInt(L"z", td.z); + teTag->putInt(L"t", (int)(td.m_delay - levelTime)); - NbtIo::write(tag,dos); - delete tag; - PIXEndNamedEvent(); + tickTags->add(teTag); + } + tag->put(L"TileTicks", tickTags); + } + delete ticksInChunk; + PIXEndNamedEvent(); + + NbtIo::write(tag, dos); + delete tag; + PIXEndNamedEvent(); } -void OldChunkStorage::save(LevelChunk *lc, Level *level, CompoundTag *tag) -{ - level->checkSession(); - tag->putInt(L"xPos", lc->x); - tag->putInt(L"zPos", lc->z); - tag->putLong(L"LastUpdate", level->getTime()); - // 4J - changes here for new storage. Now have static storage for getting lighting data for block, data, and sky & block lighting. This - // wasn't required in the original version as we could just reference the information in the level itself, but with our new storage system - // the full data doesn't normally exist & so getSkyLightData/getBlockLightData etc. need somewhere to output this data. Making this static so - // that we aren't dynamically allocating memory in the server thread when writing chunks as this causes serious stalling on the main thread. - // Will be fine so long as we only actually create tags for once chunk at a time. +void OldChunkStorage::save(LevelChunk* lc, Level* level, CompoundTag* tag) { + level->checkSession(); + tag->putInt(L"xPos", lc->x); + tag->putInt(L"zPos", lc->z); + tag->putLong(L"LastUpdate", level->getTime()); + // 4J - changes here for new storage. Now have static storage for getting + // lighting data for block, data, and sky & block lighting. This wasn't + // required in the original version as we could just reference the + // information in the level itself, but with our new storage system the full + // data doesn't normally exist & so getSkyLightData/getBlockLightData etc. + // need somewhere to output this data. Making this static so that we aren't + // dynamically allocating memory in the server thread when writing chunks as + // this causes serious stalling on the main thread. Will be fine so long as + // we only actually create tags for once chunk at a time. - // 4J Stu - As we now save on multiple threads, the static data has been moved to TLS - ThreadStorage *tls = static_cast(OldChunkStorageTlsGetValue(tlsIdx)); + // 4J Stu - As we now save on multiple threads, the static data has been + // moved to TLS + ThreadStorage* tls = + static_cast(OldChunkStorageTlsGetValue(tlsIdx)); - PIXBeginNamedEvent(0,"Getting block data"); - //static byteArray blockData = byteArray(32768); - lc->getBlockData(tls->blockData); - tag->putByteArray(L"Blocks", tls->blockData); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting block data"); + // static byteArray blockData = byteArray(32768); + lc->getBlockData(tls->blockData); + tag->putByteArray(L"Blocks", tls->blockData); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Getting data data"); - //static byteArray dataData = byteArray(16384); - lc->getDataData(tls->dataData); - tag->putByteArray(L"Data", tls->dataData); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting data data"); + // static byteArray dataData = byteArray(16384); + lc->getDataData(tls->dataData); + tag->putByteArray(L"Data", tls->dataData); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Getting sky and block light data"); - //static byteArray skyLightData = byteArray(16384); - //static byteArray blockLightData = byteArray(16384); - lc->getSkyLightData(tls->skyLightData); - lc->getBlockLightData(tls->blockLightData); - tag->putByteArray(L"SkyLight", tls->skyLightData); - tag->putByteArray(L"BlockLight", tls->blockLightData); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Getting sky and block light data"); + // static byteArray skyLightData = byteArray(16384); + // static byteArray blockLightData = byteArray(16384); + lc->getSkyLightData(tls->skyLightData); + lc->getBlockLightData(tls->blockLightData); + tag->putByteArray(L"SkyLight", tls->skyLightData); + tag->putByteArray(L"BlockLight", tls->blockLightData); + PIXEndNamedEvent(); - tag->putByteArray(L"HeightMap", lc->heightmap); - tag->putShort(L"TerrainPopulatedFlags", lc->terrainPopulated); // 4J - changed from "TerrainPopulated" to "TerrainPopulatedFlags" as now stores a bitfield, java stores a bool - tag->putByteArray(L"Biomes", lc->getBiomes()); + tag->putByteArray(L"HeightMap", lc->heightmap); + tag->putShort( + L"TerrainPopulatedFlags", + lc->terrainPopulated); // 4J - changed from "TerrainPopulated" to + // "TerrainPopulatedFlags" as now stores a + // bitfield, java stores a bool + tag->putByteArray(L"Biomes", lc->getBiomes()); - PIXBeginNamedEvent(0,"Saving entities"); + PIXBeginNamedEvent(0, "Saving entities"); #ifndef SPLIT_SAVES - saveEntities(lc, level, tag); + saveEntities(lc, level, tag); #endif - PIXBeginNamedEvent(0,"Saving tile entities"); - ListTag *tileEntityTags = new ListTag(); + PIXBeginNamedEvent(0, "Saving tile entities"); + ListTag* tileEntityTags = new ListTag(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( std::unordered_map, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) - { - std::shared_ptr te = it->second; - CompoundTag *teTag = new CompoundTag(); - te->save(teTag); - tileEntityTags->add(teTag); - } - tag->put(L"TileEntities", tileEntityTags); - PIXEndNamedEvent(); + AUTO_VAR(itEnd, lc->tileEntities.end()); + for (std::unordered_map, + TilePosKeyHash, TilePosKeyEq>::iterator it = + lc->tileEntities.begin(); + it != itEnd; it++) { + std::shared_ptr te = it->second; + CompoundTag* teTag = new CompoundTag(); + te->save(teTag); + tileEntityTags->add(teTag); + } + tag->put(L"TileEntities", tileEntityTags); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Saving tile tick data"); - std::vector *ticksInChunk = level->fetchTicksInChunk(lc, false); - if (ticksInChunk != NULL) - { - __int64 levelTime = level->getTime(); + PIXBeginNamedEvent(0, "Saving tile tick data"); + std::vector* ticksInChunk = + level->fetchTicksInChunk(lc, false); + if (ticksInChunk != NULL) { + __int64 levelTime = level->getTime(); - ListTag *tickTags = new ListTag(); - for( int i = 0; i < ticksInChunk->size(); i++ ) - { - TickNextTickData td = ticksInChunk->at(i); - CompoundTag *teTag = new CompoundTag(); - teTag->putInt(L"i", td.tileId); - teTag->putInt(L"x", td.x); - teTag->putInt(L"y", td.y); - teTag->putInt(L"z", td.z); - teTag->putInt(L"t", (int) (td.m_delay - levelTime)); + ListTag* tickTags = new ListTag(); + for (int i = 0; i < ticksInChunk->size(); i++) { + TickNextTickData td = ticksInChunk->at(i); + CompoundTag* teTag = new CompoundTag(); + teTag->putInt(L"i", td.tileId); + teTag->putInt(L"x", td.x); + teTag->putInt(L"y", td.y); + teTag->putInt(L"z", td.z); + teTag->putInt(L"t", (int)(td.m_delay - levelTime)); - tickTags->add(teTag); - } - tag->put(L"TileTicks", tickTags); - } - delete ticksInChunk; - PIXEndNamedEvent(); - PIXEndNamedEvent(); + tickTags->add(teTag); + } + tag->put(L"TileTicks", tickTags); + } + delete ticksInChunk; + PIXEndNamedEvent(); + PIXEndNamedEvent(); } -void OldChunkStorage::loadEntities(LevelChunk *lc, Level *level, CompoundTag *tag) -{ - ListTag *entityTags = (ListTag *) tag->getList(L"Entities"); - if (entityTags != NULL) - { - for (int i = 0; i < entityTags->size(); i++) - { - CompoundTag *teTag = entityTags->get(i); - std::shared_ptr te = EntityIO::loadStatic(teTag, level); - lc->lastSaveHadEntities = true; - if (te != NULL) - { - lc->addEntity(te); - } - } - } +void OldChunkStorage::loadEntities(LevelChunk* lc, Level* level, + CompoundTag* tag) { + ListTag* entityTags = + (ListTag*)tag->getList(L"Entities"); + if (entityTags != NULL) { + for (int i = 0; i < entityTags->size(); i++) { + CompoundTag* teTag = entityTags->get(i); + std::shared_ptr te = EntityIO::loadStatic(teTag, level); + lc->lastSaveHadEntities = true; + if (te != NULL) { + lc->addEntity(te); + } + } + } - ListTag *tileEntityTags = (ListTag *) tag->getList(L"TileEntities"); - if (tileEntityTags != NULL) - { - for (int i = 0; i < tileEntityTags->size(); i++) - { - CompoundTag *teTag = tileEntityTags->get(i); - std::shared_ptr te = TileEntity::loadStatic(teTag); - if (te != NULL) - { - lc->addTileEntity(te); - } - } - } + ListTag* tileEntityTags = + (ListTag*)tag->getList(L"TileEntities"); + if (tileEntityTags != NULL) { + for (int i = 0; i < tileEntityTags->size(); i++) { + CompoundTag* teTag = tileEntityTags->get(i); + std::shared_ptr te = TileEntity::loadStatic(teTag); + if (te != NULL) { + lc->addTileEntity(te); + } + } + } } -LevelChunk *OldChunkStorage::load(Level *level, DataInputStream *dis) -{ - short version = dis->readShort(); - int x = dis->readInt(); - int z = dis->readInt(); - int time = dis->readLong(); +LevelChunk* OldChunkStorage::load(Level* level, DataInputStream* dis) { + short version = dis->readShort(); + int x = dis->readInt(); + int z = dis->readInt(); + int time = dis->readLong(); - LevelChunk *levelChunk = new LevelChunk(level, x, z); + LevelChunk* levelChunk = new LevelChunk(level, x, z); - levelChunk->readCompressedBlockData(dis); - levelChunk->readCompressedDataData(dis); - levelChunk->readCompressedSkyLightData(dis); - levelChunk->readCompressedBlockLightData(dis); + levelChunk->readCompressedBlockData(dis); + levelChunk->readCompressedDataData(dis); + levelChunk->readCompressedSkyLightData(dis); + levelChunk->readCompressedBlockLightData(dis); - dis->readFully(levelChunk->heightmap); + dis->readFully(levelChunk->heightmap); - levelChunk->terrainPopulated = dis->readShort(); - // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able - // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps - // before this flag was added. - if( ( levelChunk->terrainPopulated & LevelChunk::sTerrainPopulatedAllNeighbours ) == LevelChunk::sTerrainPopulatedAllNeighbours ) - { - levelChunk->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; - } + levelChunk->terrainPopulated = dis->readShort(); + // If all neighbours have been post-processed, then we should have done the + // post-post-processing now. Check that this is set as if it isn't then we + // won't be able to send network data for chunks, and we won't ever try and + // set it again as all the directional flags are now already set - should + // only be an issue for old maps before this flag was added. + if ((levelChunk->terrainPopulated & + LevelChunk::sTerrainPopulatedAllNeighbours) == + LevelChunk::sTerrainPopulatedAllNeighbours) { + levelChunk->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; + } - dis->readFully(levelChunk->biomes); + dis->readFully(levelChunk->biomes); - CompoundTag *tag = NbtIo::read(dis); + CompoundTag* tag = NbtIo::read(dis); - loadEntities(levelChunk, level, tag); + loadEntities(levelChunk, level, tag); - if (tag->contains(L"TileTicks")) - { - ListTag *tileTicks = (ListTag *) tag->getList(L"TileTicks"); + if (tag->contains(L"TileTicks")) { + ListTag* tileTicks = + (ListTag*)tag->getList(L"TileTicks"); - if (tileTicks != NULL) - { - for (int i = 0; i < tileTicks->size(); i++) - { - CompoundTag *teTag = tileTicks->get(i); + if (tileTicks != NULL) { + for (int i = 0; i < tileTicks->size(); i++) { + CompoundTag* teTag = tileTicks->get(i); - level->forceAddTileTick(teTag->getInt(L"x"), teTag->getInt(L"y"), teTag->getInt(L"z"), teTag->getInt(L"i"), teTag->getInt(L"t")); - } - } - } + level->forceAddTileTick( + teTag->getInt(L"x"), teTag->getInt(L"y"), + teTag->getInt(L"z"), teTag->getInt(L"i"), + teTag->getInt(L"t")); + } + } + } - delete tag; + delete tag; - return levelChunk; + return levelChunk; } -LevelChunk *OldChunkStorage::load(Level *level, CompoundTag *tag) -{ - int x = tag->getInt(L"xPos"); - int z = tag->getInt(L"zPos"); +LevelChunk* OldChunkStorage::load(Level* level, CompoundTag* tag) { + int x = tag->getInt(L"xPos"); + int z = tag->getInt(L"zPos"); - LevelChunk *levelChunk = new LevelChunk(level, x, z); - // 4J - the original code uses the data in the tag directly, but this is now just used as a source when creating the compressed data, so - // we need to free up the data in the tag once we are done - levelChunk->setBlockData(tag->getByteArray(L"Blocks")); - delete [] tag->getByteArray(L"Blocks").data; - // levelChunk->blocks = tag->getByteArray(L"Blocks"); + LevelChunk* levelChunk = new LevelChunk(level, x, z); + // 4J - the original code uses the data in the tag directly, but this is now + // just used as a source when creating the compressed data, so we need to + // free up the data in the tag once we are done + levelChunk->setBlockData(tag->getByteArray(L"Blocks")); + delete[] tag->getByteArray(L"Blocks").data; + // levelChunk->blocks = tag->getByteArray(L"Blocks"); - // 4J - the original code uses the data in the tag directly, but this is now just used as a source when creating the compressed data, so - // we need to free up the data in the tag once we are done - levelChunk->setDataData(tag->getByteArray(L"Data")); - delete [] tag->getByteArray(L"Data").data; + // 4J - the original code uses the data in the tag directly, but this is now + // just used as a source when creating the compressed data, so we need to + // free up the data in the tag once we are done + levelChunk->setDataData(tag->getByteArray(L"Data")); + delete[] tag->getByteArray(L"Data").data; - // 4J - changed to use our new methods for accessing lighting - levelChunk->setSkyLightData(tag->getByteArray(L"SkyLight")); - levelChunk->setBlockLightData(tag->getByteArray(L"BlockLight")); + // 4J - changed to use our new methods for accessing lighting + levelChunk->setSkyLightData(tag->getByteArray(L"SkyLight")); + levelChunk->setBlockLightData(tag->getByteArray(L"BlockLight")); - // In the original code (commented out below) constructing DataLayers from these arrays uses the data directly and so it doesn't need deleted. The new - // setSkyLightData/setBlockLightData take a copy of the data so we need to delete the local one now - delete [] tag->getByteArray(L"SkyLight").data; - delete [] tag->getByteArray(L"BlockLight").data; + // In the original code (commented out below) constructing DataLayers from + // these arrays uses the data directly and so it doesn't need deleted. The + // new setSkyLightData/setBlockLightData take a copy of the data so we need + // to delete the local one now + delete[] tag->getByteArray(L"SkyLight").data; + delete[] tag->getByteArray(L"BlockLight").data; - // levelChunk->skyLight = new DataLayer(tag->getByteArray(L"SkyLight"), level->depthBits); - // levelChunk->blockLight = new DataLayer(tag->getByteArray(L"BlockLight"), level->depthBits); + // levelChunk->skyLight = new DataLayer(tag->getByteArray(L"SkyLight"), + //level->depthBits); levelChunk->blockLight = new + //DataLayer(tag->getByteArray(L"BlockLight"), level->depthBits); - delete [] levelChunk->heightmap.data; - levelChunk->heightmap = tag->getByteArray(L"HeightMap"); - // 4J - TerrainPopulated was a bool (java), then changed to be a byte bitfield, then replaced with TerrainPopulatedShort to store a wider bitfield - if( tag->get(L"TerrainPopulated") ) - { - // Java bool type or byte bitfield - levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); - if( levelChunk->terrainPopulated >= 1 ) levelChunk->terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; // Convert from old bool type to new bitfield - } - else - { - // New style short - levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); - // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able - // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps - // before this flag was added. - if( ( levelChunk->terrainPopulated & LevelChunk::sTerrainPopulatedAllNeighbours ) == LevelChunk::sTerrainPopulatedAllNeighbours ) - { - levelChunk->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; - } - } + delete[] levelChunk->heightmap.data; + levelChunk->heightmap = tag->getByteArray(L"HeightMap"); + // 4J - TerrainPopulated was a bool (java), then changed to be a byte + // bitfield, then replaced with TerrainPopulatedShort to store a wider + // bitfield + if (tag->get(L"TerrainPopulated")) { + // Java bool type or byte bitfield + levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); + if (levelChunk->terrainPopulated >= 1) + levelChunk->terrainPopulated = + LevelChunk::sTerrainPopulatedAllNeighbours | + LevelChunk::sTerrainPostPostProcessed; // Convert from old bool + // type to new bitfield + } else { + // New style short + levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); + // If all neighbours have been post-processed, then we should have done + // the post-post-processing now. Check that this is set as if it isn't + // then we won't be able to send network data for chunks, and we won't + // ever try and set it again as all the directional flags are now + // already set - should only be an issue for old maps before this flag + // was added. + if ((levelChunk->terrainPopulated & + LevelChunk::sTerrainPopulatedAllNeighbours) == + LevelChunk::sTerrainPopulatedAllNeighbours) { + levelChunk->terrainPopulated |= + LevelChunk::sTerrainPostPostProcessed; + } + } #if 0 // 4J - removed - we shouldn't need this any more @@ -573,7 +574,7 @@ LevelChunk *OldChunkStorage::load(Level *level, CompoundTag *tag) } #endif - // 4J removed - we shouldn't need this any more + // 4J removed - we shouldn't need this any more #if 0 if (levelChunk->heightmap.data == NULL || !levelChunk->skyLight->isValid()) { @@ -593,39 +594,33 @@ LevelChunk *OldChunkStorage::load(Level *level, CompoundTag *tag) } #endif - if (tag->contains(L"Biomes")) - { - levelChunk->setBiomes(tag->getByteArray(L"Biomes")); - } + if (tag->contains(L"Biomes")) { + levelChunk->setBiomes(tag->getByteArray(L"Biomes")); + } - loadEntities(levelChunk, level, tag); + loadEntities(levelChunk, level, tag); - if (tag->contains(L"TileTicks")) - { - ListTag *tileTicks = (ListTag *) tag->getList(L"TileTicks"); + if (tag->contains(L"TileTicks")) { + ListTag* tileTicks = + (ListTag*)tag->getList(L"TileTicks"); - if (tileTicks != NULL) - { - for (int i = 0; i < tileTicks->size(); i++) - { - CompoundTag *teTag = tileTicks->get(i); + if (tileTicks != NULL) { + for (int i = 0; i < tileTicks->size(); i++) { + CompoundTag* teTag = tileTicks->get(i); - level->forceAddTileTick(teTag->getInt(L"x"), teTag->getInt(L"y"), teTag->getInt(L"z"), teTag->getInt(L"i"), teTag->getInt(L"t")); - } - } - } + level->forceAddTileTick( + teTag->getInt(L"x"), teTag->getInt(L"y"), + teTag->getInt(L"z"), teTag->getInt(L"i"), + teTag->getInt(L"t")); + } + } + } - return levelChunk; + return levelChunk; } -void OldChunkStorage::tick() -{ -} +void OldChunkStorage::tick() {} -void OldChunkStorage::flush() -{ -} +void OldChunkStorage::flush() {} -void OldChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk) -{ -} +void OldChunkStorage::saveEntities(Level* level, LevelChunk* levelChunk) {} diff --git a/Minecraft.World/Level/Storage/OldChunkStorage.h b/Minecraft.World/Level/Storage/OldChunkStorage.h index 34d100720..2d55952c2 100644 --- a/Minecraft.World/Level/Storage/OldChunkStorage.h +++ b/Minecraft.World/Level/Storage/OldChunkStorage.h @@ -10,55 +10,58 @@ class Level; -class OldChunkStorage : public ChunkStorage -{ +class OldChunkStorage : public ChunkStorage { private: - // 4J added so we can have separate storage arrays for different threads - class ThreadStorage - { - public: - byteArray blockData; - byteArray dataData; - byteArray skyLightData; - byteArray blockLightData; + // 4J added so we can have separate storage arrays for different threads + class ThreadStorage { + public: + byteArray blockData; + byteArray dataData; + byteArray skyLightData; + byteArray blockLightData; - ThreadStorage(); - ~ThreadStorage(); - }; + ThreadStorage(); + ~ThreadStorage(); + }; #if defined(_WIN32) - static DWORD tlsIdx; + static DWORD tlsIdx; #else - static pthread_key_t tlsIdx; + static pthread_key_t tlsIdx; #endif - static ThreadStorage *tlsDefault; + static ThreadStorage* tlsDefault; + public: - // Each new thread that needs to use Compression will need to call one of the following 2 functions, to either create its own - // local storage, or share the default storage already allocated by the main thread - static void CreateNewThreadStorage(); - static void UseDefaultThreadStorage(); - static void ReleaseThreadStorage(); + // Each new thread that needs to use Compression will need to call one of + // the following 2 functions, to either create its own local storage, or + // share the default storage already allocated by the main thread + static void CreateNewThreadStorage(); + static void UseDefaultThreadStorage(); + static void ReleaseThreadStorage(); private: - File dir; - bool create; + File dir; + bool create; public: OldChunkStorage(File dir, bool create); + private: File getFile(int x, int z); - LevelChunk *load(Level *level, int x, int z); + LevelChunk* load(Level* level, int x, int z); public: - virtual void save(Level *level, LevelChunk *levelChunk); - - static bool saveEntities(LevelChunk *lc, Level *level, CompoundTag *tag); // 4J Added - static void save(LevelChunk *lc, Level *level, DataOutputStream *dos); // 4J Added - static void save(LevelChunk *lc, Level *level, CompoundTag *tag); - static void loadEntities(LevelChunk *lc, Level *level, CompoundTag *tag); - static LevelChunk *load(Level *level, CompoundTag *tag); - static LevelChunk *load(Level *level, DataInputStream *dis); // 4J Added + virtual void save(Level* level, LevelChunk* levelChunk); + + static bool saveEntities(LevelChunk* lc, Level* level, + CompoundTag* tag); // 4J Added + static void save(LevelChunk* lc, Level* level, + DataOutputStream* dos); // 4J Added + static void save(LevelChunk* lc, Level* level, CompoundTag* tag); + static void loadEntities(LevelChunk* lc, Level* level, CompoundTag* tag); + static LevelChunk* load(Level* level, CompoundTag* tag); + static LevelChunk* load(Level* level, DataInputStream* dis); // 4J Added virtual void tick(); virtual void flush(); - virtual void saveEntities(Level *level, LevelChunk *levelChunk); + virtual void saveEntities(Level* level, LevelChunk* levelChunk); }; diff --git a/Minecraft.World/Level/Storage/PlayerIO.h b/Minecraft.World/Level/Storage/PlayerIO.h index 141fb6b0a..11cc4e2c8 100644 --- a/Minecraft.World/Level/Storage/PlayerIO.h +++ b/Minecraft.World/Level/Storage/PlayerIO.h @@ -1,22 +1,24 @@ #pragma once - -// If we have more than MAX_PLAYER_DATA_SAVES player.dat's then we delete the oldest ones -// This value can be no higher than MAXIMUM_MAP_SAVE_DATA/3 (3 being the number of dimensions in future versions) +// If we have more than MAX_PLAYER_DATA_SAVES player.dat's then we delete the +// oldest ones This value can be no higher than MAXIMUM_MAP_SAVE_DATA/3 (3 being +// the number of dimensions in future versions) #define MAX_PLAYER_DATA_SAVES 80 class Player; -class PlayerIO -{ +class PlayerIO { public: - virtual void save(std::shared_ptr player) = 0; - virtual bool load(std::shared_ptr player) = 0; // 4J Changed return val to bool to check if new player or loaded player - virtual CompoundTag *loadPlayerDataTag(PlayerUID xuid) = 0; // 4J Changed from string name to xuid + virtual void save(std::shared_ptr player) = 0; + virtual bool load(std::shared_ptr + player) = 0; // 4J Changed return val to bool to + // check if new player or loaded player + virtual CompoundTag* loadPlayerDataTag( + PlayerUID xuid) = 0; // 4J Changed from string name to xuid - // 4J Added - virtual void clearOldPlayerFiles() = 0; - virtual void saveMapIdLookup() = 0; - virtual void deleteMapFilesForPlayer(std::shared_ptr player) = 0; - virtual void saveAllCachedData() = 0; + // 4J Added + virtual void clearOldPlayerFiles() = 0; + virtual void saveMapIdLookup() = 0; + virtual void deleteMapFilesForPlayer(std::shared_ptr player) = 0; + virtual void saveAllCachedData() = 0; }; diff --git a/Minecraft.World/Level/Storage/PortalForcer.cpp b/Minecraft.World/Level/Storage/PortalForcer.cpp index 9bb2ccd6b..d012694e6 100644 --- a/Minecraft.World/Level/Storage/PortalForcer.cpp +++ b/Minecraft.World/Level/Storage/PortalForcer.cpp @@ -5,28 +5,19 @@ #include "../../Headers/net.minecraft.world.level.dimension.h" #include "PortalForcer.h" -PortalForcer::PortalForcer() -{ - random = new Random(); -} +PortalForcer::PortalForcer() { random = new Random(); } - -void PortalForcer::force(Level *level, std::shared_ptr e) -{ - if (level->dimension->id == 1) - { +void PortalForcer::force(Level* level, std::shared_ptr e) { + if (level->dimension->id == 1) { int x = Mth::floor(e->x); int y = Mth::floor(e->y) - 1; int z = Mth::floor(e->z); int xa = 1; int za = 0; - for (int b = -2; b <= 2; b++) - { - for (int s = -2; s <= 2; s++) - { - for (int h = -1; h < 3; h++) - { + for (int b = -2; b <= 2; b++) { + for (int s = -2; s <= 2; s++) { + for (int h = -1; h < 3; h++) { int xt = x + s * xa + b * za; int yt = y + h; int zt = z + s * za - b * xa; @@ -44,338 +35,321 @@ void PortalForcer::force(Level *level, std::shared_ptr e) return; } - if (findPortal(level, e)) - { - return; - } + if (findPortal(level, e)) { + return; + } - createPortal(level, e); - findPortal(level, e); + createPortal(level, e); + findPortal(level, e); } - -bool PortalForcer::findPortal(Level *level, std::shared_ptr e) -{ - // 4J Stu - Decrease the range at which we search for a portal in the nether given our smaller nether - int r = 16;//* 8; - if(level->dimension->id == -1) - { - r *= 3; - } - else - { +bool PortalForcer::findPortal(Level* level, std::shared_ptr e) { + // 4J Stu - Decrease the range at which we search for a portal in the nether + // given our smaller nether + int r = 16; //* 8; + if (level->dimension->id == -1) { + r *= 3; + } else { #ifdef __PSVITA__ - // AP poor little Vita takes 30 seconds to leave the Nether. This should help - r *= 5; + // AP poor little Vita takes 30 seconds to leave the Nether. This should + // help + r *= 5; #else - r *= 8; + r *= 8; #endif - } - double closest = -1; - int xTarget = 0; - int yTarget = 0; - int zTarget = 0; + } + double closest = -1; + int xTarget = 0; + int yTarget = 0; + int zTarget = 0; - int xc = Mth::floor(e->x); - int zc = Mth::floor(e->z); + int xc = Mth::floor(e->x); + int zc = Mth::floor(e->z); - for (int x = xc - r; x <= xc + r; x++) - { - double xd = (x + 0.5) - e->x; - for (int z = zc - r; z <= zc + r; z++) - { - double zd = (z + 0.5) - e->z; - for (int y = level->getHeight() - 1; y >= 0; y--) - { - if (level->getTile(x, y, z) == Tile::portalTile_Id) - { - while (level->getTile(x, y - 1, z) == Tile::portalTile_Id) - { - y--; - } + for (int x = xc - r; x <= xc + r; x++) { + double xd = (x + 0.5) - e->x; + for (int z = zc - r; z <= zc + r; z++) { + double zd = (z + 0.5) - e->z; + for (int y = level->getHeight() - 1; y >= 0; y--) { + if (level->getTile(x, y, z) == Tile::portalTile_Id) { + while (level->getTile(x, y - 1, z) == Tile::portalTile_Id) { + y--; + } - double yd = (y + 0.5) - e->y; - double dist = xd * xd + yd * yd + zd * zd; - if (closest < 0 || dist < closest) - { - closest = dist; - xTarget = x; - yTarget = y; - zTarget = z; - } - } - } - } - } + double yd = (y + 0.5) - e->y; + double dist = xd * xd + yd * yd + zd * zd; + if (closest < 0 || dist < closest) { + closest = dist; + xTarget = x; + yTarget = y; + zTarget = z; + } + } + } + } + } - if (closest >= 0) - { - int x = xTarget; - int y = yTarget; - int z = zTarget; + if (closest >= 0) { + int x = xTarget; + int y = yTarget; + int z = zTarget; - double xt = x + 0.5; - double yt = y + 0.5; - double zt = z + 0.5; + double xt = x + 0.5; + double yt = y + 0.5; + double zt = z + 0.5; - if (level->getTile(x - 1, y, z) == Tile::portalTile_Id) xt -= 0.5; - if (level->getTile(x + 1, y, z) == Tile::portalTile_Id) xt += 0.5; + if (level->getTile(x - 1, y, z) == Tile::portalTile_Id) xt -= 0.5; + if (level->getTile(x + 1, y, z) == Tile::portalTile_Id) xt += 0.5; - if (level->getTile(x, y, z - 1) == Tile::portalTile_Id) zt -= 0.5; - if (level->getTile(x, y, z + 1) == Tile::portalTile_Id) zt += 0.5; + if (level->getTile(x, y, z - 1) == Tile::portalTile_Id) zt -= 0.5; + if (level->getTile(x, y, z + 1) == Tile::portalTile_Id) zt += 0.5; - e->moveTo(xt, yt, zt, e->yRot, 0); - e->xd = e->yd = e->zd = 0; - return true; - } + e->moveTo(xt, yt, zt, e->yRot, 0); + e->xd = e->yd = e->zd = 0; + return true; + } - return false; + return false; } +bool PortalForcer::createPortal(Level* level, std::shared_ptr e) { + // 4J Stu - Increase the range at which we try and create a portal to stop + // creating them floating in mid air over lava + int r = 16 * 3; + double closest = -1; -bool PortalForcer::createPortal(Level *level, std::shared_ptr e) -{ - // 4J Stu - Increase the range at which we try and create a portal to stop creating them floating in mid air over lava - int r = 16 * 3; - double closest = -1; + int xc = Mth::floor(e->x); + int yc = Mth::floor(e->y); + int zc = Mth::floor(e->z); - int xc = Mth::floor(e->x); - int yc = Mth::floor(e->y); - int zc = Mth::floor(e->z); + // 4J Stu - Changes to stop Portals being created at the border of the + // nether inside the bedrock + int XZSIZE = level->dimension->getXZSize() * + 16; // XZSize is chunks, convert to blocks + int XZOFFSET = + (XZSIZE / 2) - 4; // Subtract 4 to stay away from the edges // TODO + // Make the 4 a constant in HellRandomLevelSource - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock - int XZSIZE = level->dimension->getXZSize() * 16; // XZSize is chunks, convert to blocks - int XZOFFSET = (XZSIZE / 2) - 4; // Subtract 4 to stay away from the edges // TODO Make the 4 a constant in HellRandomLevelSource + // Move the positions that we want to check away from the edge of the world + if ((xc - r) < -XZOFFSET) { + app.DebugPrintf( + "Adjusting portal creation x due to being too close to the edge\n"); + xc -= ((xc - r) + XZOFFSET); + } else if ((xc + r) >= XZOFFSET) { + app.DebugPrintf( + "Adjusting portal creation x due to being too close to the edge\n"); + xc -= ((xc + r) - XZOFFSET); + } + if ((zc - r) < -XZOFFSET) { + app.DebugPrintf( + "Adjusting portal creation z due to being too close to the edge\n"); + zc -= ((zc - r) + XZOFFSET); + } else if ((zc + r) >= XZOFFSET) { + app.DebugPrintf( + "Adjusting portal creation z due to being too close to the edge\n"); + zc -= ((zc + r) - XZOFFSET); + } - // Move the positions that we want to check away from the edge of the world - if( (xc - r) < -XZOFFSET ) - { - app.DebugPrintf("Adjusting portal creation x due to being too close to the edge\n"); - xc -= ( (xc - r) + XZOFFSET); - } - else if ( (xc + r) >= XZOFFSET ) - { - app.DebugPrintf("Adjusting portal creation x due to being too close to the edge\n"); - xc -= ( (xc + r) - XZOFFSET); - } - if( (zc - r) < -XZOFFSET ) - { - app.DebugPrintf("Adjusting portal creation z due to being too close to the edge\n"); - zc -= ( (zc - r) + XZOFFSET); - } - else if ( (zc + r) >= XZOFFSET ) - { - app.DebugPrintf("Adjusting portal creation z due to being too close to the edge\n"); - zc -= ( (zc + r) - XZOFFSET); - } + int xTarget = xc; + int yTarget = yc; + int zTarget = zc; + int dirTarget = 0; - int xTarget = xc; - int yTarget = yc; - int zTarget = zc; - int dirTarget = 0; + int dirOffs = random->nextInt(4); - int dirOffs = random->nextInt(4); + { + for (int x = xc - r; x <= xc + r; x++) { + double xd = (x + 0.5) - e->x; + for (int z = zc - r; z <= zc + r; z++) { + double zd = (z + 0.5) - e->z; - { - for (int x = xc - r; x <= xc + r; x++) - { - double xd = (x + 0.5) - e->x; - for (int z = zc - r; z <= zc + r; z++) - { - double zd = (z + 0.5) - e->z; + for (int y = level->getHeight() - 1; y >= 0; y--) { + if (level->isEmptyTile(x, y, z)) { + while (y > 0 && level->isEmptyTile(x, y - 1, z)) { + y--; + } - for (int y = level->getHeight() - 1; y >= 0; y--) - { - if (level->isEmptyTile(x, y, z)) - { - while (y>0 && level->isEmptyTile(x, y - 1, z)) - { - y--; - } + for (int dir = dirOffs; dir < dirOffs + 4; dir++) { + int xa = dir % 2; + int za = 1 - xa; - for (int dir = dirOffs; dir < dirOffs + 4; dir++) - { - int xa = dir % 2; - int za = 1 - xa; + if (dir % 4 >= 2) { + xa = -xa; + za = -za; + } - if (dir % 4 >= 2) - { - xa = -xa; - za = -za; - } + for (int b = 0; b < 3; b++) { + for (int s = 0; s < 4; s++) { + for (int h = -1; h < 4; h++) { + int xt = x + (s - 1) * xa + b * za; + int yt = y + h; + int zt = z + (s - 1) * za - b * xa; + // 4J Stu - Changes to stop Portals + // being created at the border of the + // nether inside the bedrock + if ((xt < -XZOFFSET) || + (xt >= XZOFFSET) || + (zt < -XZOFFSET) || + (zt >= XZOFFSET)) { + app.DebugPrintf( + "Skipping possible portal " + "location as at least one " + "block is too close to the " + "edge\n"); + goto next_first; + } - for (int b = 0; b < 3; b++) - { - for (int s = 0; s < 4; s++) - { - for (int h = -1; h < 4; h++) - { - int xt = x + (s - 1) * xa + b * za; - int yt = y + h; - int zt = z + (s - 1) * za - b * xa; + if (h < 0 && + !level->getMaterial(xt, yt, zt) + ->isSolid()) + goto next_first; + if (h >= 0 && + !level->isEmptyTile(xt, yt, zt)) + goto next_first; + } + } + } - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock - if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) - { - app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); - goto next_first; - } + double yd = (y + 0.5) - e->y; + double dist = xd * xd + yd * yd + zd * zd; + if (closest < 0 || dist < closest) { + closest = dist; + xTarget = x; + yTarget = y; + zTarget = z; + dirTarget = dir % 4; + } + } + } + next_first: + continue; + } + } + } + } + if (closest < 0) { + for (int x = xc - r; x <= xc + r; x++) { + double xd = (x + 0.5) - e->x; + for (int z = zc - r; z <= zc + r; z++) { + double zd = (z + 0.5) - e->z; - if (h < 0 && !level->getMaterial(xt, yt, zt)->isSolid()) goto next_first; - if (h >= 0 && !level->isEmptyTile(xt, yt, zt)) goto next_first; - } - } - } + for (int y = level->getHeight() - 1; y >= 0; y--) { + if (level->isEmptyTile(x, y, z)) { + while (y > 0 && level->isEmptyTile(x, y - 1, z)) { + y--; + } - double yd = (y + 0.5) - e->y; - double dist = xd * xd + yd * yd + zd * zd; - if (closest < 0 || dist < closest) - { - closest = dist; - xTarget = x; - yTarget = y; - zTarget = z; - dirTarget = dir % 4; - } - } - } - next_first: continue; - } - } - } - } - if (closest < 0) - { - for (int x = xc - r; x <= xc + r; x++) - { - double xd = (x + 0.5) - e->x; - for (int z = zc - r; z <= zc + r; z++) - { - double zd = (z + 0.5) - e->z; + for (int dir = dirOffs; dir < dirOffs + 2; dir++) { + int xa = dir % 2; + int za = 1 - xa; + for (int s = 0; s < 4; s++) { + for (int h = -1; h < 4; h++) { + int xt = x + (s - 1) * xa; + int yt = y + h; + int zt = z + (s - 1) * za; - for (int y = level->getHeight() - 1; y >= 0; y--) - { - if (level->isEmptyTile(x, y, z)) - { - while (y > 0 && level->isEmptyTile(x, y - 1, z)) - { - y--; - } + // 4J Stu - Changes to stop Portals being + // created at the border of the nether + // inside the bedrock + if ((xt < -XZOFFSET) || (xt >= XZOFFSET) || + (zt < -XZOFFSET) || (zt >= XZOFFSET)) { + app.DebugPrintf( + "Skipping possible portal location " + "as at least one block is too " + "close to the edge\n"); + goto next_second; + } - for (int dir = dirOffs; dir < dirOffs + 2; dir++) - { - int xa = dir % 2; - int za = 1 - xa; - for (int s = 0; s < 4; s++) - { - for (int h = -1; h < 4; h++) - { - int xt = x + (s - 1) * xa; - int yt = y + h; - int zt = z + (s - 1) * za; + if (h < 0 && !level->getMaterial(xt, yt, zt) + ->isSolid()) + goto next_second; + if (h >= 0 && + !level->isEmptyTile(xt, yt, zt)) + goto next_second; + } + } - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock - if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) - { - app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); - goto next_second; - } + double yd = (y + 0.5) - e->y; + double dist = xd * xd + yd * yd + zd * zd; + if (closest < 0 || dist < closest) { + closest = dist; + xTarget = x; + yTarget = y; + zTarget = z; + dirTarget = dir % 2; + } + } + } + next_second: + continue; + } + } + } + } - if (h < 0 && !level->getMaterial(xt, yt, zt)->isSolid()) goto next_second; - if (h >= 0 && !level->isEmptyTile(xt, yt, zt)) goto next_second; - } - } + int dir = dirTarget; - double yd = (y + 0.5) - e->y; - double dist = xd * xd + yd * yd + zd * zd; - if (closest < 0 || dist < closest) - { - closest = dist; - xTarget = x; - yTarget = y; - zTarget = z; - dirTarget = dir % 2; - } - } - } - next_second: continue; - } - } - } - } + int x = xTarget; + int y = yTarget; + int z = zTarget; + int xa = dir % 2; + int za = 1 - xa; + if (dir % 4 >= 2) { + xa = -xa; + za = -za; + } - int dir = dirTarget; + if (closest < 0) { + if (yTarget < 70) yTarget = 70; + if (yTarget > level->getHeight() - 10) + yTarget = level->getHeight() - 10; + y = yTarget; - int x = xTarget; - int y = yTarget; - int z = zTarget; + for (int b = -1; b <= 1; b++) { + for (int s = 1; s < 3; s++) { + for (int h = -1; h < 3; h++) { + int xt = x + (s - 1) * xa + b * za; + int yt = y + h; + int zt = z + (s - 1) * za - b * xa; - int xa = dir % 2; - int za = 1 - xa; + bool border = h < 0; - if (dir % 4 >= 2) - { - xa = -xa; - za = -za; - } + level->setTile(xt, yt, zt, border ? Tile::obsidian_Id : 0); + } + } + } + } + for (int pass = 0; pass < 4; pass++) { + level->noNeighborUpdate = true; + for (int s = 0; s < 4; s++) { + for (int h = -1; h < 4; h++) { + int xt = x + (s - 1) * xa; + int yt = y + h; + int zt = z + (s - 1) * za; - if (closest < 0) - { - if (yTarget < 70) yTarget = 70; - if (yTarget > level->getHeight() - 10) yTarget = level->getHeight() - 10; - y = yTarget; + bool border = s == 0 || s == 3 || h == -1 || h == 3; + level->setTile( + xt, yt, zt, + border ? Tile::obsidian_Id : Tile::portalTile_Id); + } + } + level->noNeighborUpdate = false; - for (int b = -1; b <= 1; b++) - { - for (int s = 1; s < 3; s++) - { - for (int h = -1; h < 3; h++) - { - int xt = x + (s - 1) * xa + b * za; - int yt = y + h; - int zt = z + (s - 1) * za - b * xa; + for (int s = 0; s < 4; s++) { + for (int h = -1; h < 4; h++) { + int xt = x + (s - 1) * xa; + int yt = y + h; + int zt = z + (s - 1) * za; - bool border = h < 0; + level->updateNeighborsAt(xt, yt, zt, + level->getTile(xt, yt, zt)); + } + } + } - level->setTile(xt, yt, zt, border ? Tile::obsidian_Id : 0); - } - } - } - } - - for (int pass = 0; pass < 4; pass++) - { - level->noNeighborUpdate = true; - for (int s = 0; s < 4; s++) - { - for (int h = -1; h < 4; h++) - { - int xt = x + (s - 1) * xa; - int yt = y + h; - int zt = z + (s - 1) * za; - - bool border = s == 0 || s == 3 || h == -1 || h == 3; - level->setTile(xt, yt, zt, border ? Tile::obsidian_Id : Tile::portalTile_Id); - } - } - level->noNeighborUpdate = false; - - for (int s = 0; s < 4; s++) - { - for (int h = -1; h < 4; h++) - { - int xt = x + (s - 1) * xa; - int yt = y + h; - int zt = z + (s - 1) * za; - - level->updateNeighborsAt(xt, yt, zt, level->getTile(xt, yt, zt)); - } - } - } - - return true; + return true; } diff --git a/Minecraft.World/Level/Storage/PortalForcer.h b/Minecraft.World/Level/Storage/PortalForcer.h index b3dcd4e6b..af766ab50 100644 --- a/Minecraft.World/Level/Storage/PortalForcer.h +++ b/Minecraft.World/Level/Storage/PortalForcer.h @@ -2,20 +2,19 @@ class Random; -class PortalForcer -{ +class PortalForcer { private: - Random *random; + Random* random; public: - // 4J Stu Added - Java has no ctor, but we need to initialise random - PortalForcer(); + // 4J Stu Added - Java has no ctor, but we need to initialise random + PortalForcer(); - void force(Level *level, std::shared_ptr e); + void force(Level* level, std::shared_ptr e); public: - bool findPortal(Level *level, std::shared_ptr e); + bool findPortal(Level* level, std::shared_ptr e); public: - bool createPortal(Level *level, std::shared_ptr e); + bool createPortal(Level* level, std::shared_ptr e); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/ReadOnlyChunkCache.cpp b/Minecraft.World/Level/Storage/ReadOnlyChunkCache.cpp index a98aab5fe..169308b4b 100644 --- a/Minecraft.World/Level/Storage/ReadOnlyChunkCache.cpp +++ b/Minecraft.World/Level/Storage/ReadOnlyChunkCache.cpp @@ -3,98 +3,75 @@ #include "ReadOnlyChunkCache.h" #include "../../WorldGen/Biomes/Biome.h" -ReadOnlyChunkCache::ReadOnlyChunkCache(Level *level, ChunkStorage *storage) -{ - chunks = LevelChunkArray(LEN * LEN); - emptyPixels = byteArray(Level::CHUNK_TILE_COUNT); +ReadOnlyChunkCache::ReadOnlyChunkCache(Level* level, ChunkStorage* storage) { + chunks = LevelChunkArray(LEN * LEN); + emptyPixels = byteArray(Level::CHUNK_TILE_COUNT); this->level = level; this->storage = storage; } -ReadOnlyChunkCache::~ReadOnlyChunkCache() -{ - for(unsigned int i = 0; i < chunks.length; ++i) - delete chunks[i]; +ReadOnlyChunkCache::~ReadOnlyChunkCache() { + for (unsigned int i = 0; i < chunks.length; ++i) delete chunks[i]; - delete[] chunks.data; + delete[] chunks.data; - delete[] emptyPixels.data; + delete[] emptyPixels.data; } -bool ReadOnlyChunkCache::hasChunk(int x, int z) -{ +bool ReadOnlyChunkCache::hasChunk(int x, int z) { int slot = (x & LEN_MASK) | ((z & LEN_MASK) * LEN); return chunks[slot] != NULL && (chunks[slot]->isAt(x, z)); } -LevelChunk *ReadOnlyChunkCache::create(int x, int z) -{ - return getChunk(x, z); -} +LevelChunk* ReadOnlyChunkCache::create(int x, int z) { return getChunk(x, z); } -LevelChunk *ReadOnlyChunkCache::getChunk(int x, int z) -{ +LevelChunk* ReadOnlyChunkCache::getChunk(int x, int z) { int slot = (x & LEN_MASK) | ((z & LEN_MASK) * LEN); - // 4J - removed try/catch -// try { - if (!hasChunk(x, z)) - { - LevelChunk *newChunk = load(x, z); - if (newChunk == NULL) - { - newChunk = new EmptyLevelChunk(level, emptyPixels, x, z); - } - chunks[slot] = newChunk; + // 4J - removed try/catch + // try { + if (!hasChunk(x, z)) { + LevelChunk* newChunk = load(x, z); + if (newChunk == NULL) { + newChunk = new EmptyLevelChunk(level, emptyPixels, x, z); } - return chunks[slot]; -// } catch (Exception e) { -// e.printStackTrace(); -// return null; -// } + chunks[slot] = newChunk; + } + return chunks[slot]; + // } catch (Exception e) { + // e.printStackTrace(); + // return null; + // } } -LevelChunk *ReadOnlyChunkCache::load(int x, int z) -{ - // 4J - remove try/catch -// try { - return storage->load(level, x, z); -// } catch (IOException e) { -// e.printStackTrace(); -// return null; -// } +LevelChunk* ReadOnlyChunkCache::load(int x, int z) { + // 4J - remove try/catch + // try { + return storage->load(level, x, z); + // } catch (IOException e) { + // e.printStackTrace(); + // return null; + // } } - // 4J - TODO - was synchronized -void ReadOnlyChunkCache::postProcess(ChunkSource *parent, int x, int z) -{ +// 4J - TODO - was synchronized +void ReadOnlyChunkCache::postProcess(ChunkSource* parent, int x, int z) {} + +bool ReadOnlyChunkCache::save(bool force, ProgressListener* progressListener) { + return true; } -bool ReadOnlyChunkCache::save(bool force, ProgressListener *progressListener) -{ - return true; +bool ReadOnlyChunkCache::tick() { return false; } + +bool ReadOnlyChunkCache::shouldSave() { return false; } + +std::wstring ReadOnlyChunkCache::gatherStats() { return L"ReadOnlyChunkCache"; } + +std::vector* ReadOnlyChunkCache::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + return NULL; } -bool ReadOnlyChunkCache::tick() -{ - return false; -} - -bool ReadOnlyChunkCache::shouldSave() -{ - return false; -} - -std::wstring ReadOnlyChunkCache::gatherStats() -{ - return L"ReadOnlyChunkCache"; -} - -std::vector *ReadOnlyChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - return NULL; -} - -TilePos *ReadOnlyChunkCache::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - return NULL; +TilePos* ReadOnlyChunkCache::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } diff --git a/Minecraft.World/Level/Storage/ReadOnlyChunkCache.h b/Minecraft.World/Level/Storage/ReadOnlyChunkCache.h index 2eaa73f44..6d96389bf 100644 --- a/Minecraft.World/Level/Storage/ReadOnlyChunkCache.h +++ b/Minecraft.World/Level/Storage/ReadOnlyChunkCache.h @@ -6,34 +6,36 @@ class ProgressListener; -class ReadOnlyChunkCache : public ChunkSource -{ +class ReadOnlyChunkCache : public ChunkSource { private: static const int LEN = 16; static const int LEN_MASK = LEN - 1; LevelChunkArray chunks; - Level *level; - ChunkStorage *storage; + Level* level; + ChunkStorage* storage; public: - ReadOnlyChunkCache(Level *level, ChunkStorage *storage); - virtual ~ReadOnlyChunkCache(); + ReadOnlyChunkCache(Level* level, ChunkStorage* storage); + virtual ~ReadOnlyChunkCache(); virtual bool hasChunk(int x, int z); byteArray emptyPixels; - virtual LevelChunk *create(int x, int z); - virtual LevelChunk *getChunk(int x, int z); + virtual LevelChunk* create(int x, int z); + virtual LevelChunk* getChunk(int x, int z); private: - LevelChunk *load(int x, int z); // 4J - TODO - was synchronized + LevelChunk* load(int x, int z); // 4J - TODO - was synchronized public: - virtual void postProcess(ChunkSource *parent, int x, int z); - virtual bool save(bool force, ProgressListener *progressListener); + virtual void postProcess(ChunkSource* parent, int x, int z); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/Level/Storage/Region.cpp b/Minecraft.World/Level/Storage/Region.cpp index 74bd29ad8..484843e1b 100644 --- a/Minecraft.World/Level/Storage/Region.cpp +++ b/Minecraft.World/Level/Storage/Region.cpp @@ -8,349 +8,315 @@ #include "Region.h" +Region::~Region() { + for (unsigned int i = 0; i < chunks->length; ++i) { + LevelChunkArray* lca = (*chunks)[i]; + delete[] lca->data; + delete lca; + } + delete[] chunks->data; + delete chunks; -Region::~Region() -{ - for(unsigned int i = 0; i < chunks->length; ++i) - { - LevelChunkArray *lca = (*chunks)[i]; - delete [] lca->data; - delete lca; - } - delete [] chunks->data; - delete chunks; - - // AP - added a caching system for Chunk::rebuild to take advantage of - if( CachedTiles ) - { - free(CachedTiles); - } + // AP - added a caching system for Chunk::rebuild to take advantage of + if (CachedTiles) { + free(CachedTiles); + } } -Region::Region(Level *level, int x1, int y1, int z1, int x2, int y2, int z2) -{ - this->level = level; +Region::Region(Level* level, int x1, int y1, int z1, int x2, int y2, int z2) { + this->level = level; - xc1 = x1 >> 4; - zc1 = z1 >> 4; - int xc2 = x2 >> 4; - int zc2 = z2 >> 4; + xc1 = x1 >> 4; + zc1 = z1 >> 4; + int xc2 = x2 >> 4; + int zc2 = z2 >> 4; - chunks = new LevelChunk2DArray(xc2 - xc1 + 1, zc2 - zc1 + 1); + chunks = new LevelChunk2DArray(xc2 - xc1 + 1, zc2 - zc1 + 1); - allEmpty = true; - for (int xc = xc1; xc <= xc2; xc++) - { - for (int zc = zc1; zc <= zc2; zc++) - { - LevelChunk *chunk = level->getChunk(xc, zc); - if(chunk != NULL) - { - LevelChunkArray *lca = (*chunks)[xc - xc1]; - lca->data[zc - zc1] = chunk; - //(*chunks)[xc - xc1].data[zc - zc1] = level->getChunk(xc, zc); - if (!chunk->isYSpaceEmpty(y1, y2)) - { - allEmpty = false; - } - } - } - } + allEmpty = true; + for (int xc = xc1; xc <= xc2; xc++) { + for (int zc = zc1; zc <= zc2; zc++) { + LevelChunk* chunk = level->getChunk(xc, zc); + if (chunk != NULL) { + LevelChunkArray* lca = (*chunks)[xc - xc1]; + lca->data[zc - zc1] = chunk; + //(*chunks)[xc - xc1].data[zc - zc1] = level->getChunk(xc, zc); + if (!chunk->isYSpaceEmpty(y1, y2)) { + allEmpty = false; + } + } + } + } - // AP - added a caching system for Chunk::rebuild to take advantage of - xcCached = -1; - zcCached = -1; - CachedTiles = NULL; + // AP - added a caching system for Chunk::rebuild to take advantage of + xcCached = -1; + zcCached = -1; + CachedTiles = NULL; } -bool Region::isAllEmpty() -{ - return allEmpty; -} +bool Region::isAllEmpty() { return allEmpty; } -int Region::getTile(int x, int y, int z) -{ - if (y < 0) return 0; - if (y >= Level::maxBuildHeight) return 0; +int Region::getTile(int x, int y, int z) { + if (y < 0) return 0; + if (y >= Level::maxBuildHeight) return 0; - int xc = (x >> 4); - int zc = (z >> 4); + int xc = (x >> 4); + int zc = (z >> 4); #ifdef __PSVITA__ - // AP - added a caching system for Chunk::rebuild to take advantage of - if( CachedTiles && xc == xcCached && zc == zcCached ) - { - unsigned char* Tiles = CachedTiles; - Tiles += y; - if(y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - Tiles += Level::COMPRESSED_CHUNK_SECTION_TILES - Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - } + // AP - added a caching system for Chunk::rebuild to take advantage of + if (CachedTiles && xc == xcCached && zc == zcCached) { + unsigned char* Tiles = CachedTiles; + Tiles += y; + if (y >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + Tiles += Level::COMPRESSED_CHUNK_SECTION_TILES - + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + } - return Tiles[ ( (x & 15) << 11 ) | ( (z & 15) << 7 ) ]; - } + return Tiles[((x & 15) << 11) | ((z & 15) << 7)]; + } #endif - xc -= xc1; - zc -= zc1; + xc -= xc1; + zc -= zc1; - if (xc < 0 || xc >= (int)chunks->length || zc < 0 || zc >= (int)(*chunks)[xc]->length) - { - return 0; - } + if (xc < 0 || xc >= (int)chunks->length || zc < 0 || + zc >= (int)(*chunks)[xc]->length) { + return 0; + } - LevelChunk *lc = (*chunks)[xc]->data[zc]; - if (lc == NULL) return 0; + LevelChunk* lc = (*chunks)[xc]->data[zc]; + if (lc == NULL) return 0; - return lc->getTile(x & 15, y, z & 15); + return lc->getTile(x & 15, y, z & 15); } // AP - added a caching system for Chunk::rebuild to take advantage of -void Region::setCachedTiles(unsigned char *tiles, int xc, int zc) -{ - xcCached = xc; - zcCached = zc; - int size = 16 * 16 * Level::maxBuildHeight; - if( CachedTiles == NULL ) - { - CachedTiles = (unsigned char *) malloc(size); - } - memcpy(CachedTiles, tiles, size); +void Region::setCachedTiles(unsigned char* tiles, int xc, int zc) { + xcCached = xc; + zcCached = zc; + int size = 16 * 16 * Level::maxBuildHeight; + if (CachedTiles == NULL) { + CachedTiles = (unsigned char*)malloc(size); + } + memcpy(CachedTiles, tiles, size); } -LevelChunk* Region::getLevelChunk(int x, int y, int z) -{ - if (y < 0) return 0; - if (y >= Level::maxBuildHeight) return NULL; +LevelChunk* Region::getLevelChunk(int x, int y, int z) { + if (y < 0) return 0; + if (y >= Level::maxBuildHeight) return NULL; - int xc = (x >> 4) - xc1; - int zc = (z >> 4) - zc1; + int xc = (x >> 4) - xc1; + int zc = (z >> 4) - zc1; - if (xc < 0 || xc >= (int)chunks->length || zc < 0 || zc >= (int)(*chunks)[xc]->length) - { - return NULL; - } + if (xc < 0 || xc >= (int)chunks->length || zc < 0 || + zc >= (int)(*chunks)[xc]->length) { + return NULL; + } - LevelChunk *lc = (*chunks)[xc]->data[zc]; - return lc; + LevelChunk* lc = (*chunks)[xc]->data[zc]; + return lc; } +std::shared_ptr Region::getTileEntity(int x, int y, int z) { + int xc = (x >> 4) - xc1; + int zc = (z >> 4) - zc1; - -std::shared_ptr Region::getTileEntity(int x, int y, int z) -{ - int xc = (x >> 4) - xc1; - int zc = (z >> 4) - zc1; - - return (*chunks)[xc]->data[zc]->getTileEntity(x & 15, y, z & 15); + return (*chunks)[xc]->data[zc]->getTileEntity(x & 15, y, z & 15); } -int Region::getLightColor(int x, int y, int z, int emitt, int tileId/*=-1*/) -{ +int Region::getLightColor(int x, int y, int z, int emitt, int tileId /*=-1*/) { int s = getBrightnessPropagate(LightLayer::Sky, x, y, z, tileId); int b = getBrightnessPropagate(LightLayer::Block, x, y, z, tileId); if (b < emitt) b = emitt; return s << 20 | b << 4; } -float Region::getBrightness(int x, int y, int z, int emitt) -{ - int n = getRawBrightness(x, y, z); - if (n < emitt) n = emitt; - return level->dimension->brightnessRamp[n]; +float Region::getBrightness(int x, int y, int z, int emitt) { + int n = getRawBrightness(x, y, z); + if (n < emitt) n = emitt; + return level->dimension->brightnessRamp[n]; } - -float Region::getBrightness(int x, int y, int z) -{ - return level->dimension->brightnessRamp[getRawBrightness(x, y, z)]; +float Region::getBrightness(int x, int y, int z) { + return level->dimension->brightnessRamp[getRawBrightness(x, y, z)]; } - -int Region::getRawBrightness(int x, int y, int z) -{ - return getRawBrightness(x, y, z, true); +int Region::getRawBrightness(int x, int y, int z) { + return getRawBrightness(x, y, z, true); } - -int Region::getRawBrightness(int x, int y, int z, bool propagate) -{ - if (x < -Level::MAX_LEVEL_SIZE || z < -Level::MAX_LEVEL_SIZE || x >= Level::MAX_LEVEL_SIZE || z > Level::MAX_LEVEL_SIZE) - { - return Level::MAX_BRIGHTNESS; - } - - if (propagate) - { - int id = getTile(x, y, z); - switch(id) - { - case Tile::stoneSlabHalf_Id: - case Tile::woodSlabHalf_Id: - case Tile::farmland_Id: - case Tile::stairs_stone_Id: - case Tile::stairs_wood_Id: - { - int br = getRawBrightness(x, y + 1, z, false); - int br1 = getRawBrightness(x + 1, y, z, false); - int br2 = getRawBrightness(x - 1, y, z, false); - int br3 = getRawBrightness(x, y, z + 1, false); - int br4 = getRawBrightness(x, y, z - 1, false); - if (br1 > br) br = br1; - if (br2 > br) br = br2; - if (br3 > br) br = br3; - if (br4 > br) br = br4; - return br; - } - break; - } - } - - if (y < 0) return 0; - if (y >= Level::maxBuildHeight) - { - int br = Level::MAX_BRIGHTNESS - level->skyDarken; - if (br < 0) br = 0; - return br; - } - - int xc = (x >> 4) - xc1; - int zc = (z >> 4) - zc1; - - return (*chunks)[xc]->data[zc]->getRawBrightness(x & 15, y, z & 15, level->skyDarken); -} - - -int Region::getData(int x, int y, int z) -{ - if (y < 0) return 0; - if (y >= Level::maxBuildHeight) return 0; - int xc = (x >> 4) - xc1; - int zc = (z >> 4) - zc1; - - return (*chunks)[xc]->data[zc]->getData(x & 15, y, z & 15); -} - -Material *Region::getMaterial(int x, int y, int z) -{ - int t = getTile(x, y, z); - if (t == 0) return Material::air; - return Tile::tiles[t]->material; -} - - -BiomeSource *Region::getBiomeSource() -{ - return level->getBiomeSource(); -} - -Biome *Region::getBiome(int x, int z) -{ - return level->getBiome(x, z); -} - -bool Region::isSolidRenderTile(int x, int y, int z) -{ - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile == NULL) return false; - - // 4J - addition here to make rendering big blocks of leaves more efficient. Normally leaves never consider themselves as solid, so - // blocks of leaves will have all sides of each block completely visible. Changing to consider as solid if this block is surrounded by - // other leaves (or solid things). This is paired with another change in Tile::getTexture which makes such solid tiles actually visibly solid (these - // textures exist already for non-fancy graphics). Note: this tile-specific code is here rather than making some new virtual method in the tiles, - // for the sake of efficiency - I don't imagine we'll be doing much more of this sort of thing - if( tile->id == Tile::leaves_Id ) - { - int axo[6] = { 1,-1, 0, 0, 0, 0}; - int ayo[6] = { 0, 0, 1,-1, 0, 0}; - int azo[6] = { 0, 0, 0, 0, 1,-1}; - for( int i = 0; i < 6; i++ ) - { - int t = getTile(x + axo[i], y + ayo[i] , z + azo[i]); - if( ( t != Tile::leaves_Id ) && ( ( Tile::tiles[t] == NULL ) || !Tile::tiles[t]->isSolidRender() ) ) - { - return false; - } - } - - return true; - } - - return tile->isSolidRender(); -} - - -bool Region::isSolidBlockingTile(int x, int y, int z) -{ - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile == NULL) return false; - return tile->material->blocksMotion() && tile->isCubeShaped(); -} - -bool Region::isTopSolidBlocking(int x, int y, int z) -{ - // Temporary workaround until tahgs per-face solidity is finished - Tile *tile = Tile::tiles[getTile(x, y, z)]; - if (tile == NULL) return false; - - if (tile->material->isSolidBlocking() && tile->isCubeShaped()) return true; - if (dynamic_cast(tile)) return (getData(x, y, z) & StairTile::UPSIDEDOWN_BIT) == StairTile::UPSIDEDOWN_BIT; - if (dynamic_cast(tile)) return (getData(x, y, z) & HalfSlabTile::TOP_SLOT_BIT) == HalfSlabTile::TOP_SLOT_BIT; - return false; -} - -bool Region::isEmptyTile(int x, int y, int z) -{ - Tile *tile = Tile::tiles[getTile(x, y, z)]; - return (tile == NULL); -} - - -// 4J - brought forward from 1.8.2 -int Region::getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, int tileId) -{ - if (y < 0) y = 0; - if (y >= Level::maxBuildHeight) y = Level::maxBuildHeight - 1; - if (y < 0 || y >= Level::maxBuildHeight || x < -Level::MAX_LEVEL_SIZE || z < -Level::MAX_LEVEL_SIZE || x >= Level::MAX_LEVEL_SIZE || z > Level::MAX_LEVEL_SIZE) - { - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - return (int)layer; +int Region::getRawBrightness(int x, int y, int z, bool propagate) { + if (x < -Level::MAX_LEVEL_SIZE || z < -Level::MAX_LEVEL_SIZE || + x >= Level::MAX_LEVEL_SIZE || z > Level::MAX_LEVEL_SIZE) { + return Level::MAX_BRIGHTNESS; } - int id = tileId > -1 ? tileId : getTile(x, y, z); - if (Tile::propagate[id]) - { - int br = getBrightness(layer, x, y + 1, z); if( br == 15 ) return 15; - int br1 = getBrightness(layer, x + 1, y, z); if( br1 == 15 ) return 15; - int br2 = getBrightness(layer, x - 1, y, z); if( br2 == 15 ) return 15; - int br3 = getBrightness(layer, x, y, z + 1); if( br3 == 15 ) return 15; - int br4 = getBrightness(layer, x, y, z - 1); if( br4 == 15 ) return 15; - if (br1 > br) br = br1; - if (br2 > br) br = br2; - if (br3 > br) br = br3; - if (br4 > br) br = br4; - return br; - } + if (propagate) { + int id = getTile(x, y, z); + switch (id) { + case Tile::stoneSlabHalf_Id: + case Tile::woodSlabHalf_Id: + case Tile::farmland_Id: + case Tile::stairs_stone_Id: + case Tile::stairs_wood_Id: { + int br = getRawBrightness(x, y + 1, z, false); + int br1 = getRawBrightness(x + 1, y, z, false); + int br2 = getRawBrightness(x - 1, y, z, false); + int br3 = getRawBrightness(x, y, z + 1, false); + int br4 = getRawBrightness(x, y, z - 1, false); + if (br1 > br) br = br1; + if (br2 > br) br = br2; + if (br3 > br) br = br3; + if (br4 > br) br = br4; + return br; + } break; + } + } + + if (y < 0) return 0; + if (y >= Level::maxBuildHeight) { + int br = Level::MAX_BRIGHTNESS - level->skyDarken; + if (br < 0) br = 0; + return br; + } int xc = (x >> 4) - xc1; int zc = (z >> 4) - zc1; - return (*chunks)[xc]->data[zc]->getBrightness(layer, x & 15, y, z & 15); + return (*chunks)[xc]->data[zc]->getRawBrightness(x & 15, y, z & 15, + level->skyDarken); +} + +int Region::getData(int x, int y, int z) { + if (y < 0) return 0; + if (y >= Level::maxBuildHeight) return 0; + int xc = (x >> 4) - xc1; + int zc = (z >> 4) - zc1; + + return (*chunks)[xc]->data[zc]->getData(x & 15, y, z & 15); +} + +Material* Region::getMaterial(int x, int y, int z) { + int t = getTile(x, y, z); + if (t == 0) return Material::air; + return Tile::tiles[t]->material; +} + +BiomeSource* Region::getBiomeSource() { return level->getBiomeSource(); } + +Biome* Region::getBiome(int x, int z) { return level->getBiome(x, z); } + +bool Region::isSolidRenderTile(int x, int y, int z) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile == NULL) return false; + + // 4J - addition here to make rendering big blocks of leaves more efficient. + // Normally leaves never consider themselves as solid, so blocks of leaves + // will have all sides of each block completely visible. Changing to + // consider as solid if this block is surrounded by other leaves (or solid + // things). This is paired with another change in Tile::getTexture which + // makes such solid tiles actually visibly solid (these textures exist + // already for non-fancy graphics). Note: this tile-specific code is here + // rather than making some new virtual method in the tiles, for the sake of + // efficiency - I don't imagine we'll be doing much more of this sort of + // thing + if (tile->id == Tile::leaves_Id) { + int axo[6] = {1, -1, 0, 0, 0, 0}; + int ayo[6] = {0, 0, 1, -1, 0, 0}; + int azo[6] = {0, 0, 0, 0, 1, -1}; + for (int i = 0; i < 6; i++) { + int t = getTile(x + axo[i], y + ayo[i], z + azo[i]); + if ((t != Tile::leaves_Id) && ((Tile::tiles[t] == NULL) || + !Tile::tiles[t]->isSolidRender())) { + return false; + } + } + + return true; + } + + return tile->isSolidRender(); +} + +bool Region::isSolidBlockingTile(int x, int y, int z) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile == NULL) return false; + return tile->material->blocksMotion() && tile->isCubeShaped(); +} + +bool Region::isTopSolidBlocking(int x, int y, int z) { + // Temporary workaround until tahgs per-face solidity is finished + Tile* tile = Tile::tiles[getTile(x, y, z)]; + if (tile == NULL) return false; + + if (tile->material->isSolidBlocking() && tile->isCubeShaped()) return true; + if (dynamic_cast(tile)) + return (getData(x, y, z) & StairTile::UPSIDEDOWN_BIT) == + StairTile::UPSIDEDOWN_BIT; + if (dynamic_cast(tile)) + return (getData(x, y, z) & HalfSlabTile::TOP_SLOT_BIT) == + HalfSlabTile::TOP_SLOT_BIT; + return false; +} + +bool Region::isEmptyTile(int x, int y, int z) { + Tile* tile = Tile::tiles[getTile(x, y, z)]; + return (tile == NULL); } // 4J - brought forward from 1.8.2 -int Region::getBrightness(LightLayer::variety layer, int x, int y, int z) -{ +int Region::getBrightnessPropagate(LightLayer::variety layer, int x, int y, + int z, int tileId) { if (y < 0) y = 0; if (y >= Level::maxBuildHeight) y = Level::maxBuildHeight - 1; - if (y < 0 || y >= Level::maxBuildHeight || x < -Level::MAX_LEVEL_SIZE || z < -Level::MAX_LEVEL_SIZE || x >= Level::MAX_LEVEL_SIZE || z > Level::MAX_LEVEL_SIZE) - { - // 4J Stu - The java LightLayer was an enum class type with a member "surrounding" which is what we - // were returning here. Surrounding has the same value as the enum value in our C++ code, so just cast - // it to an int - return (int)layer; + if (y < 0 || y >= Level::maxBuildHeight || x < -Level::MAX_LEVEL_SIZE || + z < -Level::MAX_LEVEL_SIZE || x >= Level::MAX_LEVEL_SIZE || + z > Level::MAX_LEVEL_SIZE) { + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + return (int)layer; + } + + int id = tileId > -1 ? tileId : getTile(x, y, z); + if (Tile::propagate[id]) { + int br = getBrightness(layer, x, y + 1, z); + if (br == 15) return 15; + int br1 = getBrightness(layer, x + 1, y, z); + if (br1 == 15) return 15; + int br2 = getBrightness(layer, x - 1, y, z); + if (br2 == 15) return 15; + int br3 = getBrightness(layer, x, y, z + 1); + if (br3 == 15) return 15; + int br4 = getBrightness(layer, x, y, z - 1); + if (br4 == 15) return 15; + if (br1 > br) br = br1; + if (br2 > br) br = br2; + if (br3 > br) br = br3; + if (br4 > br) br = br4; + return br; + } + + int xc = (x >> 4) - xc1; + int zc = (z >> 4) - zc1; + + return (*chunks)[xc]->data[zc]->getBrightness(layer, x & 15, y, z & 15); +} + +// 4J - brought forward from 1.8.2 +int Region::getBrightness(LightLayer::variety layer, int x, int y, int z) { + if (y < 0) y = 0; + if (y >= Level::maxBuildHeight) y = Level::maxBuildHeight - 1; + if (y < 0 || y >= Level::maxBuildHeight || x < -Level::MAX_LEVEL_SIZE || + z < -Level::MAX_LEVEL_SIZE || x >= Level::MAX_LEVEL_SIZE || + z > Level::MAX_LEVEL_SIZE) { + // 4J Stu - The java LightLayer was an enum class type with a member + // "surrounding" which is what we were returning here. Surrounding has + // the same value as the enum value in our C++ code, so just cast it to + // an int + return (int)layer; } int xc = (x >> 4) - xc1; int zc = (z >> 4) - zc1; @@ -358,7 +324,4 @@ int Region::getBrightness(LightLayer::variety layer, int x, int y, int z) return (*chunks)[xc]->data[zc]->getBrightness(layer, x & 15, y, z & 15); } -int Region::getMaxBuildHeight() -{ - return Level::maxBuildHeight; -} \ No newline at end of file +int Region::getMaxBuildHeight() { return Level::maxBuildHeight; } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/Region.h b/Minecraft.World/Level/Storage/Region.h index fad828ee8..69b16ec49 100644 --- a/Minecraft.World/Level/Storage/Region.h +++ b/Minecraft.World/Level/Storage/Region.h @@ -6,46 +6,48 @@ class Material; class TileEntity; class BiomeSource; -class Region : public LevelSource -{ +class Region : public LevelSource { private: - int xc1, zc1; - LevelChunk2DArray *chunks; - Level *level; - bool allEmpty; + int xc1, zc1; + LevelChunk2DArray* chunks; + Level* level; + bool allEmpty; - // AP - added a caching system for Chunk::rebuild to take advantage of - int xcCached, zcCached; - unsigned char *CachedTiles; + // AP - added a caching system for Chunk::rebuild to take advantage of + int xcCached, zcCached; + unsigned char* CachedTiles; public: - Region(Level *level, int x1, int y1, int z1, int x2, int y2, int z2); - virtual ~Region(); - bool isAllEmpty(); - int getTile(int x, int y, int z); - std::shared_ptr getTileEntity(int x, int y, int z); - float getBrightness(int x, int y, int z, int emitt); - float getBrightness(int x, int y, int z); - int getLightColor(int x, int y, int z, int emitt, int tileId = -1); // 4J - change brought forward from 1.8.2 - int getRawBrightness(int x, int y, int z); - int getRawBrightness(int x, int y, int z, bool propagate); - int getData(int x, int y, int z); - Material *getMaterial(int x, int y, int z); - BiomeSource *getBiomeSource(); - Biome *getBiome(int x, int z); - bool isSolidRenderTile(int x, int y, int z); - bool isSolidBlockingTile(int x, int y, int z); - bool isTopSolidBlocking(int x, int y, int z); - bool isEmptyTile(int x, int y, int z); + Region(Level* level, int x1, int y1, int z1, int x2, int y2, int z2); + virtual ~Region(); + bool isAllEmpty(); + int getTile(int x, int y, int z); + std::shared_ptr getTileEntity(int x, int y, int z); + float getBrightness(int x, int y, int z, int emitt); + float getBrightness(int x, int y, int z); + int getLightColor( + int x, int y, int z, int emitt, + int tileId = -1); // 4J - change brought forward from 1.8.2 + int getRawBrightness(int x, int y, int z); + int getRawBrightness(int x, int y, int z, bool propagate); + int getData(int x, int y, int z); + Material* getMaterial(int x, int y, int z); + BiomeSource* getBiomeSource(); + Biome* getBiome(int x, int z); + bool isSolidRenderTile(int x, int y, int z); + bool isSolidBlockingTile(int x, int y, int z); + bool isTopSolidBlocking(int x, int y, int z); + bool isEmptyTile(int x, int y, int z); - // 4J - changes brought forward from 1.8.2 - int getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, int tileId); // 4J added tileId - int getBrightness(LightLayer::variety layer, int x, int y, int z); + // 4J - changes brought forward from 1.8.2 + int getBrightnessPropagate(LightLayer::variety layer, int x, int y, int z, + int tileId); // 4J added tileId + int getBrightness(LightLayer::variety layer, int x, int y, int z); - int getMaxBuildHeight(); + int getMaxBuildHeight(); - LevelChunk* getLevelChunk(int x, int y, int z); + LevelChunk* getLevelChunk(int x, int y, int z); - // AP - added a caching system for Chunk::rebuild to take advantage of - void setCachedTiles(unsigned char *tiles, int xc, int zc); + // AP - added a caching system for Chunk::rebuild to take advantage of + void setCachedTiles(unsigned char* tiles, int xc, int zc); }; \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/RegionFile.cpp b/Minecraft.World/Level/Storage/RegionFile.cpp index d47a0eddf..7f9291528 100644 --- a/Minecraft.World/Level/Storage/RegionFile.cpp +++ b/Minecraft.World/Level/Storage/RegionFile.cpp @@ -8,490 +8,498 @@ byteArray RegionFile::emptySector(SECTOR_BYTES); -RegionFile::RegionFile(ConsoleSaveFile *saveFile, File *path) -{ - _lastModified = 0; +RegionFile::RegionFile(ConsoleSaveFile* saveFile, File* path) { + _lastModified = 0; - m_saveFile = saveFile; + m_saveFile = saveFile; - offsets = new int[SECTOR_INTS]; - memset(offsets,0,SECTOR_BYTES); - chunkTimestamps = new int[SECTOR_INTS]; - memset(chunkTimestamps,0,SECTOR_BYTES); + offsets = new int[SECTOR_INTS]; + memset(offsets, 0, SECTOR_BYTES); + chunkTimestamps = new int[SECTOR_INTS]; + memset(chunkTimestamps, 0, SECTOR_BYTES); - /* 4J Jev, using files instead of strings: - strncpy(fileName,path,MAX_PATH_SIZE); */ + /* 4J Jev, using files instead of strings: + strncpy(fileName,path,MAX_PATH_SIZE); */ - fileName = path; + fileName = path; -// debugln("REGION LOAD " + fileName); + // debugln("REGION LOAD " + fileName); - sizeDelta = 0; + sizeDelta = 0; - // 4J - removed try/catch -// try { - - /* 4J - Removed as _lastModifed not used and this is always failing as checking wrong thing - if( path->exists() ) - { - _lastModified = path->lastModified(); - } - */ + // 4J - removed try/catch + // try { - fileEntry = m_saveFile->createFile( fileName->getName() ); - m_saveFile->setFilePointer( fileEntry, 0, SaveFileSeekOrigin::End ); + /* 4J - Removed as _lastModifed not used and this is always failing as + checking wrong thing if( path->exists() ) + { + _lastModified = path->lastModified(); + } + */ - if ( fileEntry->getFileSize() < SECTOR_BYTES) - { - // 4J altered - the original code used to write out 2 empty sectors here, which we don't want to do as we might be at a point where we shouldn't be touching the save file. - // This now happens in insertInitialSectors when we do a first write to the region - m_bIsEmpty = true; + fileEntry = m_saveFile->createFile(fileName->getName()); + m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::End); - sizeDelta += SECTOR_BYTES * 2; - } - else - { - m_bIsEmpty = false; - } + if (fileEntry->getFileSize() < SECTOR_BYTES) { + // 4J altered - the original code used to write out 2 empty sectors + // here, which we don't want to do as we might be at a point where we + // shouldn't be touching the save file. This now happens in + // insertInitialSectors when we do a first write to the region + m_bIsEmpty = true; - //if ((GetFileSize(file,NULL) & 0xfff) != 0) - if ((fileEntry->getFileSize() & 0xfff) != 0) - { - //std::uint8_t zero = 0; - unsigned int numberOfBytesWritten = 0; - unsigned int bytesToWrite = 0x1000 - (fileEntry->getFileSize() & 0xfff); - std::uint8_t *zeroBytes = new std::uint8_t[ bytesToWrite ]; - ZeroMemory(zeroBytes, bytesToWrite); + sizeDelta += SECTOR_BYTES * 2; + } else { + m_bIsEmpty = false; + } - /* the file size is not a multiple of 4KB, grow it */ - m_saveFile->writeFile(fileEntry,zeroBytes,bytesToWrite,&numberOfBytesWritten); + // if ((GetFileSize(file,NULL) & 0xfff) != 0) + if ((fileEntry->getFileSize() & 0xfff) != 0) { + // std::uint8_t zero = 0; + unsigned int numberOfBytesWritten = 0; + unsigned int bytesToWrite = 0x1000 - (fileEntry->getFileSize() & 0xfff); + std::uint8_t* zeroBytes = new std::uint8_t[bytesToWrite]; + ZeroMemory(zeroBytes, bytesToWrite); - delete [] zeroBytes; - } + /* the file size is not a multiple of 4KB, grow it */ + m_saveFile->writeFile(fileEntry, zeroBytes, bytesToWrite, + &numberOfBytesWritten); - /* set up the available sector map */ - - int nSectors; - if( m_bIsEmpty ) // 4J - added this case for our empty files that we now don't create - { - nSectors = 2; - } - else - { - nSectors = (int) fileEntry->getFileSize() / SECTOR_BYTES; - } - sectorFree = new std::vector; - sectorFree->reserve(nSectors); + delete[] zeroBytes; + } - for (int i = 0; i < nSectors; ++i) - { - sectorFree->push_back(true); - } + /* set up the available sector map */ - sectorFree->at(0) = false; // chunk offset table - sectorFree->at(1) = false; // for the last modified info + int nSectors; + if (m_bIsEmpty) // 4J - added this case for our empty files that we now + // don't create + { + nSectors = 2; + } else { + nSectors = (int)fileEntry->getFileSize() / SECTOR_BYTES; + } + sectorFree = new std::vector; + sectorFree->reserve(nSectors); - m_saveFile->setFilePointer( fileEntry, 0, SaveFileSeekOrigin::Begin ); - for (int i = 0; i < SECTOR_INTS; ++i) - { - unsigned int offset = 0; - unsigned int numberOfBytesRead = 0; - if( !m_bIsEmpty ) // 4J added condition, don't read back if we've just created an empty file as we don't immediately write this anymore - { - m_saveFile->readFile(fileEntry, &offset, 4, &numberOfBytesRead); + for (int i = 0; i < nSectors; ++i) { + sectorFree->push_back(true); + } - if(saveFile->isSaveEndianDifferent()) System::ReverseULONG(&offset); + sectorFree->at(0) = false; // chunk offset table + sectorFree->at(1) = false; // for the last modified info - } - offsets[i] = offset; - if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree->size()) - { - for (unsigned int sectorNum = 0; sectorNum < (offset & 0xFF); ++sectorNum) - { - sectorFree->at((offset >> 8) + sectorNum) = false; - } - } - } - for (int i = 0; i < SECTOR_INTS; ++i) - { - int lastModValue = 0; - unsigned int numberOfBytesRead = 0; - if( !m_bIsEmpty ) // 4J added condition, don't read back if we've just created an empty file as we don't immediately write this anymore - { - m_saveFile->readFile(fileEntry, &lastModValue, 4, &numberOfBytesRead); + m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); + for (int i = 0; i < SECTOR_INTS; ++i) { + unsigned int offset = 0; + unsigned int numberOfBytesRead = 0; + if (!m_bIsEmpty) // 4J added condition, don't read back if we've just + // created an empty file as we don't immediately write + // this anymore + { + m_saveFile->readFile(fileEntry, &offset, 4, &numberOfBytesRead); - if(saveFile->isSaveEndianDifferent()) System::ReverseINT(&lastModValue); - } - chunkTimestamps[i] = lastModValue; - } + if (saveFile->isSaveEndianDifferent()) + System::ReverseULONG(&offset); + } + offsets[i] = offset; + if (offset != 0 && + (offset >> 8) + (offset & 0xFF) <= sectorFree->size()) { + for (unsigned int sectorNum = 0; sectorNum < (offset & 0xFF); + ++sectorNum) { + sectorFree->at((offset >> 8) + sectorNum) = false; + } + } + } + for (int i = 0; i < SECTOR_INTS; ++i) { + int lastModValue = 0; + unsigned int numberOfBytesRead = 0; + if (!m_bIsEmpty) // 4J added condition, don't read back if we've just + // created an empty file as we don't immediately write + // this anymore + { + m_saveFile->readFile(fileEntry, &lastModValue, 4, + &numberOfBytesRead); + if (saveFile->isSaveEndianDifferent()) + System::ReverseINT(&lastModValue); + } + chunkTimestamps[i] = lastModValue; + } -// } catch (IOException e) { -// e.printStackTrace(); -// } + // } catch (IOException e) { + // e.printStackTrace(); + // } } -void RegionFile::writeAllOffsets() // used for the file ConsoleSaveFile conversion between platforms +void RegionFile::writeAllOffsets() // used for the file ConsoleSaveFile + // conversion between platforms { - if(m_bIsEmpty == false) - { - // save all the offsets and timestamps - m_saveFile->LockSaveAccess(); + if (m_bIsEmpty == false) { + // save all the offsets and timestamps + m_saveFile->LockSaveAccess(); - unsigned int numberOfBytesWritten = 0; - m_saveFile->setFilePointer( fileEntry, 0, SaveFileSeekOrigin::Begin ); - m_saveFile->writeFile(fileEntry,offsets, SECTOR_BYTES ,&numberOfBytesWritten); + unsigned int numberOfBytesWritten = 0; + m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); + m_saveFile->writeFile(fileEntry, offsets, SECTOR_BYTES, + &numberOfBytesWritten); - numberOfBytesWritten = 0; - m_saveFile->setFilePointer( fileEntry, SECTOR_BYTES, SaveFileSeekOrigin::Begin ); - m_saveFile->writeFile(fileEntry, chunkTimestamps, SECTOR_BYTES, &numberOfBytesWritten); - - m_saveFile->ReleaseSaveAccess(); - } + numberOfBytesWritten = 0; + m_saveFile->setFilePointer(fileEntry, SECTOR_BYTES, + SaveFileSeekOrigin::Begin); + m_saveFile->writeFile(fileEntry, chunkTimestamps, SECTOR_BYTES, + &numberOfBytesWritten); + m_saveFile->ReleaseSaveAccess(); + } } -RegionFile::~RegionFile() -{ - delete[] offsets; - delete[] chunkTimestamps; - delete sectorFree; - m_saveFile->closeHandle( fileEntry ); +RegionFile::~RegionFile() { + delete[] offsets; + delete[] chunkTimestamps; + delete sectorFree; + m_saveFile->closeHandle(fileEntry); } -__int64 RegionFile::lastModified() +__int64 RegionFile::lastModified() { return _lastModified; } + +int RegionFile::getSizeDelta() // TODO - was synchronized { - return _lastModified; + int ret = sizeDelta; + sizeDelta = 0; + return ret; } -int RegionFile::getSizeDelta() // TODO - was synchronized +DataInputStream* RegionFile::getChunkDataInputStream( + int x, int z) // TODO - was synchronized { - int ret = sizeDelta; - sizeDelta = 0; - return ret; + if (outOfBounds(x, z)) { + // debugln("READ", x, z, "out of bounds"); + return NULL; + } + + // 4J - removed try/catch + // try { + int offset = getOffset(x, z); + if (offset == 0) { + // debugln("READ", x, z, "miss"); + return NULL; + } + + unsigned int sectorNumber = offset >> 8; + unsigned int numSectors = offset & 0xFF; + + if (sectorNumber + numSectors > sectorFree->size()) { + // debugln("READ", x, z, "invalid sector"); + return NULL; + } + + m_saveFile->LockSaveAccess(); + + // SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); + m_saveFile->setFilePointer(fileEntry, sectorNumber * SECTOR_BYTES, + SaveFileSeekOrigin::Begin); + + unsigned int length; + unsigned int decompLength; + unsigned int readDecompLength; + + unsigned int numberOfBytesRead = 0; + + // 4J - this differs a bit from the java file format. Java has length stored + // as an int, then a type as a byte, then length-1 bytes of data We store + // length and decompression length as ints, then length bytes of xbox LZX + // compressed data + m_saveFile->readFile(fileEntry, &length, 4, &numberOfBytesRead); + + if (m_saveFile->isSaveEndianDifferent()) System::ReverseULONG(&length); + + // Using to bit of length to signify that this data was compressed with RLE + // method + bool useRLE = false; + if (length & 0x80000000) { + useRLE = true; + length &= 0x7fffffff; + } + m_saveFile->readFile(fileEntry, &decompLength, 4, &numberOfBytesRead); + + if (m_saveFile->isSaveEndianDifferent()) + System::ReverseULONG(&decompLength); + + if (length > SECTOR_BYTES * numSectors) { + // debugln("READ", x, z, "invalid length: " + length + " > 4096 * + // " + numSectors); + + m_saveFile->ReleaseSaveAccess(); + return NULL; + } + + MemSect(50); + std::uint8_t* data = new std::uint8_t[length]; + std::uint8_t* decomp = new std::uint8_t[decompLength]; + MemSect(0); + readDecompLength = decompLength; + m_saveFile->readFile(fileEntry, data, length, &numberOfBytesRead); + + m_saveFile->ReleaseSaveAccess(); + + Compression::getCompression()->SetDecompressionType( + m_saveFile + ->getSavePlatform()); // if this save is from another platform, set + // the correct decompression type + + if (useRLE) { + Compression::getCompression()->DecompressLZXRLE( + decomp, &readDecompLength, data, length); + } else { + Compression::getCompression()->Decompress(decomp, &readDecompLength, + data, length); + } + + Compression::getCompression()->SetDecompressionType( + SAVE_FILE_PLATFORM_LOCAL); // and then set the decompression back to + // the local machine's standard type + + delete[] data; + + // 4J - was InflaterInputStream in here too, but we've already decompressed + DataInputStream* ret = new DataInputStream( + new ByteArrayInputStream(byteArray(decomp, readDecompLength))); + return ret; + + // } catch (IOException e) { + // debugln("READ", x, z, "exception"); + // return null; + // } } -DataInputStream *RegionFile::getChunkDataInputStream(int x, int z) // TODO - was synchronized -{ - if (outOfBounds(x, z)) - { -// debugln("READ", x, z, "out of bounds"); - return NULL; - } - - // 4J - removed try/catch -// try { - int offset = getOffset(x, z); - if (offset == 0) - { - // debugln("READ", x, z, "miss"); - return NULL; - } - - unsigned int sectorNumber = offset >> 8; - unsigned int numSectors = offset & 0xFF; - - if (sectorNumber + numSectors > sectorFree->size()) - { -// debugln("READ", x, z, "invalid sector"); - return NULL; - } - - m_saveFile->LockSaveAccess(); - - //SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); - m_saveFile->setFilePointer( fileEntry, sectorNumber * SECTOR_BYTES, SaveFileSeekOrigin::Begin); - - unsigned int length; - unsigned int decompLength; - unsigned int readDecompLength; - - unsigned int numberOfBytesRead = 0; - - // 4J - this differs a bit from the java file format. Java has length stored as an int, then a type as a byte, then length-1 bytes of data - // We store length and decompression length as ints, then length bytes of xbox LZX compressed data - m_saveFile->readFile(fileEntry,&length,4,&numberOfBytesRead); - - if(m_saveFile->isSaveEndianDifferent()) System::ReverseULONG(&length); - - // Using to bit of length to signify that this data was compressed with RLE method - bool useRLE = false; - if( length & 0x80000000 ) - { - useRLE = true; - length &= 0x7fffffff; - } - m_saveFile->readFile(fileEntry,&decompLength,4,&numberOfBytesRead); - - if(m_saveFile->isSaveEndianDifferent()) System::ReverseULONG(&decompLength); - - if (length > SECTOR_BYTES * numSectors) - { -// debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors); - - m_saveFile->ReleaseSaveAccess(); - return NULL; - } - - MemSect(50); - std::uint8_t *data = new std::uint8_t[length]; - std::uint8_t *decomp = new std::uint8_t[decompLength]; - MemSect(0); - readDecompLength = decompLength; - m_saveFile->readFile(fileEntry,data,length,&numberOfBytesRead); - - m_saveFile->ReleaseSaveAccess(); - - Compression::getCompression()->SetDecompressionType(m_saveFile->getSavePlatform()); // if this save is from another platform, set the correct decompression type - - if( useRLE ) - { - Compression::getCompression()->DecompressLZXRLE(decomp, &readDecompLength, data, length ); - } - else - { - Compression::getCompression()->Decompress(decomp, &readDecompLength, data, length ); - } - - Compression::getCompression()->SetDecompressionType(SAVE_FILE_PLATFORM_LOCAL); // and then set the decompression back to the local machine's standard type - - delete [] data; - - // 4J - was InflaterInputStream in here too, but we've already decompressed - DataInputStream *ret = new DataInputStream(new ByteArrayInputStream( byteArray( decomp, readDecompLength) )); - return ret; - -// } catch (IOException e) { -// debugln("READ", x, z, "exception"); -// return null; -// } -} - -DataOutputStream *RegionFile::getChunkDataOutputStream(int x, int z) -{ - // 4J - was DeflatorOutputStream in here too, but we've already compressed - return new DataOutputStream( new ChunkBuffer(this, x, z)); +DataOutputStream* RegionFile::getChunkDataOutputStream(int x, int z) { + // 4J - was DeflatorOutputStream in here too, but we've already compressed + return new DataOutputStream(new ChunkBuffer(this, x, z)); } /* write a chunk at (x,z) with length bytes of data to disk */ -void RegionFile::write(int x, int z, std::uint8_t *data, int length) // TODO - was synchronized +void RegionFile::write(int x, int z, std::uint8_t* data, + int length) // TODO - was synchronized { - // 4J Stu - Do the compression here so that we know how much space we need to store the compressed data - std::uint8_t *compData = new std::uint8_t[length + 2048]; // presuming compression is going to make this smaller... UPDATE - for some really small things this isn't the case. Added 2K on here to cover those. - unsigned int compLength = length; - Compression::getCompression()->CompressLZXRLE(compData,&compLength,data,length); + // 4J Stu - Do the compression here so that we know how much space we need + // to store the compressed data + std::uint8_t* compData = + new std::uint8_t[length + + 2048]; // presuming compression is going to make this + // smaller... UPDATE - for some really small + // things this isn't the case. Added 2K on here + // to cover those. + unsigned int compLength = length; + Compression::getCompression()->CompressLZXRLE(compData, &compLength, data, + length); - int sectorsNeeded = (compLength + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1; + int sectorsNeeded = (compLength + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1; -// app.DebugPrintf(">>>>>>>>>>>>>> writing compressed data for 0x%.8x, %d %d\n",fileEntry->data.regionIndex,x,z); + // app.DebugPrintf(">>>>>>>>>>>>>> writing compressed data for 0x%.8x, %d + //%d\n",fileEntry->data.regionIndex,x,z); - // maximum chunk size is 1MB - if (sectorsNeeded >= 256) - { - return; - } + // maximum chunk size is 1MB + if (sectorsNeeded >= 256) { + return; + } - m_saveFile->LockSaveAccess(); - { - int offset = getOffset(x, z); - int sectorNumber = offset >> 8; - int sectorsAllocated = offset & 0xFF; + m_saveFile->LockSaveAccess(); + { + int offset = getOffset(x, z); + int sectorNumber = offset >> 8; + int sectorsAllocated = offset & 0xFF; #ifndef _CONTENT_PACKAGE - if(sectorNumber < 0) - { - __debugbreak(); - } + if (sectorNumber < 0) { + __debugbreak(); + } #endif - if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) - { - /* we can simply overwrite the old sectors */ - // debug("SAVE", x, z, length, "rewrite"); - #ifndef _CONTENT_PACKAGE - //wprintf(L"Writing chunk (%d,%d) in %ls from current sector %d to %d\n", x,z, fileEntry->data.filename, sectorNumber, sectorNumber + sectorsNeeded - 1); - #endif - write(sectorNumber, compData, length, compLength); - } - else - { - /* we need to allocate new sectors */ + if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) { + /* we can simply overwrite the old sectors */ +// debug("SAVE", x, z, length, "rewrite"); +#ifndef _CONTENT_PACKAGE + // wprintf(L"Writing chunk (%d,%d) in %ls from current sector %d to + // %d\n", x,z, fileEntry->data.filename, sectorNumber, sectorNumber + // + sectorsNeeded - 1); +#endif + write(sectorNumber, compData, length, compLength); + } else { + /* we need to allocate new sectors */ - /* mark the sectors previously used for this chunk as free */ - for (int i = 0; i < sectorsAllocated; ++i) - { - sectorFree->at(sectorNumber + i) = true; - } - // 4J added - zero this now unused region of the file, so it can be better compressed until it is reused - zero(sectorNumber, SECTOR_BYTES * sectorsAllocated); + /* mark the sectors previously used for this chunk as free */ + for (int i = 0; i < sectorsAllocated; ++i) { + sectorFree->at(sectorNumber + i) = true; + } + // 4J added - zero this now unused region of the file, so it can be + // better compressed until it is reused + zero(sectorNumber, SECTOR_BYTES * sectorsAllocated); - PIXBeginNamedEvent(0,"Scanning for free space\n"); - /* scan for a free space large enough to store this chunk */ - int runStart = (int)(find(sectorFree->begin(),sectorFree->end(),true) - sectorFree->begin()); // 4J - was sectorFree.indexOf(true) - int runLength = 0; - if (runStart != -1) - { - for (unsigned int i = runStart; i < sectorFree->size(); ++i) - { - if (runLength != 0) - { - if (sectorFree->at(i)) runLength++; - else runLength = 0; - } else if (sectorFree->at(i)) - { - runStart = i; - runLength = 1; - } - if (runLength >= sectorsNeeded) - { - break; - } - } - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Scanning for free space\n"); + /* scan for a free space large enough to store this chunk */ + int runStart = + (int)(find(sectorFree->begin(), sectorFree->end(), true) - + sectorFree + ->begin()); // 4J - was sectorFree.indexOf(true) + int runLength = 0; + if (runStart != -1) { + for (unsigned int i = runStart; i < sectorFree->size(); ++i) { + if (runLength != 0) { + if (sectorFree->at(i)) + runLength++; + else + runLength = 0; + } else if (sectorFree->at(i)) { + runStart = i; + runLength = 1; + } + if (runLength >= sectorsNeeded) { + break; + } + } + } + PIXEndNamedEvent(); - if (runLength >= sectorsNeeded) - { - /* we found a free space large enough */ - // debug("SAVE", x, z, length, "reuse"); - sectorNumber = runStart; - setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); - #ifndef _CONTENT_PACKAGE - //wprintf(L"Writing chunk (%d,%d) in %ls from old sector %d to %d\n", x,z, fileEntry->data.filename, sectorNumber, sectorNumber + sectorsNeeded - 1); - #endif - for (int i = 0; i < sectorsNeeded; ++i) - { - sectorFree->at(sectorNumber + i) = false; - } - write(sectorNumber, compData, length, compLength); - } - else - { - PIXBeginNamedEvent(0,"Expanding storage for %d sectors\n", sectorsNeeded); - /* - * no free space large enough found -- we need to grow the - * file - */ - // debug("SAVE", x, z, length, "grow"); - //SetFilePointer(file,0,0,FILE_END); - m_saveFile->setFilePointer( fileEntry, 0, SaveFileSeekOrigin::End ); + if (runLength >= sectorsNeeded) { + /* we found a free space large enough */ + // debug("SAVE", x, z, length, "reuse"); + sectorNumber = runStart; + setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); +#ifndef _CONTENT_PACKAGE + // wprintf(L"Writing chunk (%d,%d) in %ls from old sector %d to + // %d\n", x,z, fileEntry->data.filename, sectorNumber, + // sectorNumber + sectorsNeeded - 1); +#endif + for (int i = 0; i < sectorsNeeded; ++i) { + sectorFree->at(sectorNumber + i) = false; + } + write(sectorNumber, compData, length, compLength); + } else { + PIXBeginNamedEvent(0, "Expanding storage for %d sectors\n", + sectorsNeeded); + /* + * no free space large enough found -- we need to grow the + * file + */ + // debug("SAVE", x, z, length, "grow"); + // SetFilePointer(file,0,0,FILE_END); + m_saveFile->setFilePointer(fileEntry, 0, + SaveFileSeekOrigin::End); - sectorNumber = (int)sectorFree->size(); - #ifndef _CONTENT_PACAKGE - //wprintf(L"Writing chunk (%d,%d) in %ls from new sector %d to %d\n", x,z, fileEntry->data.filename, sectorNumber, sectorNumber + sectorsNeeded - 1); - #endif - unsigned int numberOfBytesWritten = 0; - for (int i = 0; i < sectorsNeeded; ++i) - { - //WriteFile(file,emptySector.data,SECTOR_BYTES,&numberOfBytesWritten,NULL); - m_saveFile->writeFile(fileEntry,emptySector.data,SECTOR_BYTES,&numberOfBytesWritten); - sectorFree->push_back(false); - } - sizeDelta += SECTOR_BYTES * sectorsNeeded; + sectorNumber = (int)sectorFree->size(); +#ifndef _CONTENT_PACAKGE + // wprintf(L"Writing chunk (%d,%d) in %ls from new sector %d to + // %d\n", x,z, fileEntry->data.filename, sectorNumber, + // sectorNumber + sectorsNeeded - 1); +#endif + unsigned int numberOfBytesWritten = 0; + for (int i = 0; i < sectorsNeeded; ++i) { + // WriteFile(file,emptySector.data,SECTOR_BYTES,&numberOfBytesWritten,NULL); + m_saveFile->writeFile(fileEntry, emptySector.data, + SECTOR_BYTES, &numberOfBytesWritten); + sectorFree->push_back(false); + } + sizeDelta += SECTOR_BYTES * sectorsNeeded; - write(sectorNumber, compData, length, compLength); - setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); - PIXEndNamedEvent(); - } - } - setTimestamp(x, z, (int) (System::currentTimeMillis() / 1000L)); - } - m_saveFile->ReleaseSaveAccess(); + write(sectorNumber, compData, length, compLength); + setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); + PIXEndNamedEvent(); + } + } + setTimestamp(x, z, (int)(System::currentTimeMillis() / 1000L)); + } + m_saveFile->ReleaseSaveAccess(); -// } catch (IOException e) { -// e.printStackTrace(); -// } + // } catch (IOException e) { + // e.printStackTrace(); + // } } /* write a chunk data to the region file at specified sector number */ -void RegionFile::write(int sectorNumber, std::uint8_t *data, int length, unsigned int compLength) -{ - unsigned int numberOfBytesWritten = 0; - //SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); - m_saveFile->setFilePointer( fileEntry, sectorNumber * SECTOR_BYTES, SaveFileSeekOrigin::Begin ); +void RegionFile::write(int sectorNumber, std::uint8_t* data, int length, + unsigned int compLength) { + unsigned int numberOfBytesWritten = 0; + // SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); + m_saveFile->setFilePointer(fileEntry, sectorNumber * SECTOR_BYTES, + SaveFileSeekOrigin::Begin); - // 4J - this differs a bit from the java file format. Java has length stored as an int, then a type as a byte, then length-1 bytes of data - // We store length and decompression length as ints, then length bytes of xbox LZX compressed data - - // 4J Stu - We need to do the compression at a level above this, where it is checking for free space + // 4J - this differs a bit from the java file format. Java has length stored + // as an int, then a type as a byte, then length-1 bytes of data We store + // length and decompression length as ints, then length bytes of xbox LZX + // compressed data - compLength |= 0x80000000; // 4J - signify that this has been encoded with RLE method ( see code in getChunkDataInputStream() for matching detection of this) - m_saveFile->writeFile(fileEntry,&compLength,4,&numberOfBytesWritten); - compLength &= 0x7fffffff; - m_saveFile->writeFile(fileEntry,&length,4,&numberOfBytesWritten); - m_saveFile->writeFile(fileEntry,data,compLength,&numberOfBytesWritten); - delete[] data; + // 4J Stu - We need to do the compression at a level above this, where it is + // checking for free space + + compLength |= + 0x80000000; // 4J - signify that this has been encoded with RLE method + // ( see code in getChunkDataInputStream() for matching + // detection of this) + m_saveFile->writeFile(fileEntry, &compLength, 4, &numberOfBytesWritten); + compLength &= 0x7fffffff; + m_saveFile->writeFile(fileEntry, &length, 4, &numberOfBytesWritten); + m_saveFile->writeFile(fileEntry, data, compLength, &numberOfBytesWritten); + delete[] data; } -void RegionFile::zero(int sectorNumber, int length) -{ - unsigned int numberOfBytesWritten = 0; - //SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); - m_saveFile->setFilePointer( fileEntry, sectorNumber * SECTOR_BYTES, SaveFileSeekOrigin::Begin ); - m_saveFile->zeroFile( fileEntry, length, &numberOfBytesWritten ); +void RegionFile::zero(int sectorNumber, int length) { + unsigned int numberOfBytesWritten = 0; + // SetFilePointer(file,sectorNumber * SECTOR_BYTES,0,FILE_BEGIN); + m_saveFile->setFilePointer(fileEntry, sectorNumber * SECTOR_BYTES, + SaveFileSeekOrigin::Begin); + m_saveFile->zeroFile(fileEntry, length, &numberOfBytesWritten); } /* is this an invalid chunk coordinate? */ -bool RegionFile::outOfBounds(int x, int z) -{ - return x < 0 || x >= 32 || z < 0 || z >= 32; +bool RegionFile::outOfBounds(int x, int z) { + return x < 0 || x >= 32 || z < 0 || z >= 32; } -int RegionFile::getOffset(int x, int z) -{ - return offsets[x + z * 32]; +int RegionFile::getOffset(int x, int z) { return offsets[x + z * 32]; } + +bool RegionFile::hasChunk(int x, int z) { return getOffset(x, z) != 0; } + +// 4J added - write the initial two sectors that used to be written in the ctor +// when the file was empty +void RegionFile::insertInitialSectors() { + m_saveFile->setFilePointer(fileEntry, 0, SaveFileSeekOrigin::Begin); + unsigned int numberOfBytesWritten = 0; + std::uint8_t zeroBytes[SECTOR_BYTES]; + ZeroMemory(zeroBytes, SECTOR_BYTES); + + /* we need to write the chunk offset table */ + m_saveFile->writeFile(fileEntry, zeroBytes, SECTOR_BYTES, + &numberOfBytesWritten); + + // write another sector for the timestamp info + m_saveFile->writeFile(fileEntry, zeroBytes, SECTOR_BYTES, + &numberOfBytesWritten); + + m_bIsEmpty = false; } -bool RegionFile::hasChunk(int x, int z) -{ - return getOffset(x, z) != 0; +void RegionFile::setOffset(int x, int z, int offset) { + if (m_bIsEmpty) { + insertInitialSectors(); // 4J added + } + + unsigned int numberOfBytesWritten = 0; + offsets[x + z * 32] = offset; + m_saveFile->setFilePointer(fileEntry, (x + z * 32) * 4, + SaveFileSeekOrigin::Begin); + + m_saveFile->writeFile(fileEntry, &offset, 4, &numberOfBytesWritten); } -// 4J added - write the initial two sectors that used to be written in the ctor when the file was empty -void RegionFile::insertInitialSectors() -{ - m_saveFile->setFilePointer( fileEntry, 0, SaveFileSeekOrigin::Begin ); - unsigned int numberOfBytesWritten = 0; - std::uint8_t zeroBytes[ SECTOR_BYTES ]; - ZeroMemory(zeroBytes, SECTOR_BYTES); +void RegionFile::setTimestamp(int x, int z, int value) { + if (m_bIsEmpty) { + insertInitialSectors(); // 4J added + } - /* we need to write the chunk offset table */ - m_saveFile->writeFile(fileEntry,zeroBytes,SECTOR_BYTES,&numberOfBytesWritten); + unsigned int numberOfBytesWritten = 0; + chunkTimestamps[x + z * 32] = value; + m_saveFile->setFilePointer(fileEntry, SECTOR_BYTES + (x + z * 32) * 4, + SaveFileSeekOrigin::Begin); - // write another sector for the timestamp info - m_saveFile->writeFile(fileEntry,zeroBytes,SECTOR_BYTES,&numberOfBytesWritten); - - m_bIsEmpty = false; + m_saveFile->writeFile(fileEntry, &value, 4, &numberOfBytesWritten); } -void RegionFile::setOffset(int x, int z, int offset) -{ - if( m_bIsEmpty ) - { - insertInitialSectors(); // 4J added - } - - unsigned int numberOfBytesWritten = 0; - offsets[x + z * 32] = offset; - m_saveFile->setFilePointer( fileEntry, (x + z * 32) * 4, SaveFileSeekOrigin::Begin ); - - m_saveFile->writeFile(fileEntry,&offset,4,&numberOfBytesWritten); -} - -void RegionFile::setTimestamp(int x, int z, int value) -{ - if( m_bIsEmpty ) - { - insertInitialSectors(); // 4J added - } - - unsigned int numberOfBytesWritten = 0; - chunkTimestamps[x + z * 32] = value; - m_saveFile->setFilePointer( fileEntry, SECTOR_BYTES + (x + z * 32) * 4, SaveFileSeekOrigin::Begin ); - - m_saveFile->writeFile(fileEntry,&value,4,&numberOfBytesWritten); -} - -void RegionFile::close() -{ - m_saveFile->closeHandle( fileEntry ); -} +void RegionFile::close() { m_saveFile->closeHandle(fileEntry); } diff --git a/Minecraft.World/Level/Storage/RegionFile.h b/Minecraft.World/Level/Storage/RegionFile.h index 8b6a3c872..d3a43a74e 100644 --- a/Minecraft.World/Level/Storage/RegionFile.h +++ b/Minecraft.World/Level/Storage/RegionFile.h @@ -2,41 +2,39 @@ #include "../../IO/Streams/Compression.h" #include "../../IO/Streams/InputOutputStream.h" - class FileEntry; class ConsoleSaveFile; -class RegionFile -{ -// 4J Stu TEMP FOR TESTING +class RegionFile { + // 4J Stu TEMP FOR TESTING private: - FileEntry *fileEntry; + FileEntry* fileEntry; private: - static const int VERSION_GZIP = 1; + static const int VERSION_GZIP = 1; static const int VERSION_DEFLATE = 2; - static const int VERSION_XBOX = 3; - + static const int VERSION_XBOX = 3; + static const int SECTOR_BYTES = 4096; static const int SECTOR_INTS = SECTOR_BYTES / 4; static const int CHUNK_HEADER_SIZE = 8; - static byteArray emptySector; + static byteArray emptySector; - File *fileName; - //HANDLE file; - ConsoleSaveFile *m_saveFile; + File* fileName; + // HANDLE file; + ConsoleSaveFile* m_saveFile; - int *offsets; - int *chunkTimestamps; - std::vector *sectorFree; - int sizeDelta; - __int64 _lastModified; - bool m_bIsEmpty; // 4J added + int* offsets; + int* chunkTimestamps; + std::vector* sectorFree; + int sizeDelta; + __int64 _lastModified; + bool m_bIsEmpty; // 4J added public: - RegionFile(ConsoleSaveFile *saveFile, File *path); - ~RegionFile(); + RegionFile(ConsoleSaveFile* saveFile, File* path); + ~RegionFile(); /* the modification date of the region file when it was first opened */ __int64 lastModified(); @@ -48,35 +46,33 @@ public: * gets an (uncompressed) stream representing the chunk data returns null if * the chunk is not found or an error occurs */ - DataInputStream *getChunkDataInputStream(int x, int z); - DataOutputStream *getChunkDataOutputStream(int x, int z); + DataInputStream* getChunkDataInputStream(int x, int z); + DataOutputStream* getChunkDataOutputStream(int x, int z); - class ChunkBuffer : public ByteArrayOutputStream - { - private: - RegionFile *rf; - int x, z; - public: - ChunkBuffer( RegionFile *rf, int x, int z ) : ByteArrayOutputStream(8096) - { - this->rf = rf; - this->x = x; - this->z = z; - } - void close() - { - rf->write(x,z,buf.data,count); - } - }; + class ChunkBuffer : public ByteArrayOutputStream { + private: + RegionFile* rf; + int x, z; + + public: + ChunkBuffer(RegionFile* rf, int x, int z) + : ByteArrayOutputStream(8096) { + this->rf = rf; + this->x = x; + this->z = z; + } + void close() { rf->write(x, z, buf.data, count); } + }; /* write a chunk at (x,z) with length bytes of data to disk */ protected: - void write(int x, int z, uint8_t *data, int length); + void write(int x, int z, uint8_t* data, int length); /* write a chunk data to the region file at specified sector number */ private: - void write(int sectorNumber, uint8_t *data, int length, unsigned int compLength); - void zero(int sectorNumber, int length); // 4J added + void write(int sectorNumber, uint8_t* data, int length, + unsigned int compLength); + void zero(int sectorNumber, int length); // 4J added /* is this an invalid chunk coordinate? */ bool outOfBounds(int x, int z); @@ -87,11 +83,11 @@ public: bool hasChunk(int x, int z); private: - void insertInitialSectors(); // 4J added + void insertInitialSectors(); // 4J added void setOffset(int x, int z, int offset); void setTimestamp(int x, int z, int value); public: - void writeAllOffsets(); + void writeAllOffsets(); void close(); }; diff --git a/Minecraft.World/Level/Storage/RegionFileCache.cpp b/Minecraft.World/Level/Storage/RegionFileCache.cpp index e5ec3e947..89965fd2d 100644 --- a/Minecraft.World/Level/Storage/RegionFileCache.cpp +++ b/Minecraft.World/Level/Storage/RegionFileCache.cpp @@ -5,118 +5,107 @@ RegionFileCache RegionFileCache::s_defaultCache; -bool RegionFileCache::useSplitSaves(ESavePlatform platform) -{ - switch(platform) - { - case SAVE_FILE_PLATFORM_XBONE: - case SAVE_FILE_PLATFORM_PS4: - return true; - default: - return false; - }; +bool RegionFileCache::useSplitSaves(ESavePlatform platform) { + switch (platform) { + case SAVE_FILE_PLATFORM_XBONE: + case SAVE_FILE_PLATFORM_PS4: + return true; + default: + return false; + }; } -RegionFile *RegionFileCache::_getRegionFile(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) // 4J - TODO was synchronized +RegionFile* RegionFileCache::_getRegionFile( + ConsoleSaveFile* saveFile, const std::wstring& prefix, int chunkX, + int chunkZ) // 4J - TODO was synchronized { - // 4J Jev - changed back to use of the File class. - //char file[MAX_PATH_SIZE]; - //sprintf(file,"%s\\region\\r.%d.%d.mcr",basePath,chunkX >> 5,chunkZ >> 5); + // 4J Jev - changed back to use of the File class. + // char file[MAX_PATH_SIZE]; + // sprintf(file,"%s\\region\\r.%d.%d.mcr",basePath,chunkX >> 5,chunkZ >> 5); - //File regionDir(basePath, L"region"); + // File regionDir(basePath, L"region"); - //File file(regionDir, std::wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); - MemSect(31); - File file; - if(useSplitSaves(saveFile->getSavePlatform())) - { - file = File( prefix + std::wstring(L"r.") + _toString(chunkX>>4) + L"." + _toString(chunkZ>>4) + L".mcr" ); - } - else - { - file = File( prefix + std::wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); - } - MemSect(0); + // File file(regionDir, std::wstring(L"r.") + _toString(chunkX>>5) + L"." + + // _toString(chunkZ>>5) + L".mcr" ); + MemSect(31); + File file; + if (useSplitSaves(saveFile->getSavePlatform())) { + file = File(prefix + std::wstring(L"r.") + _toString(chunkX >> 4) + + L"." + _toString(chunkZ >> 4) + L".mcr"); + } else { + file = File(prefix + std::wstring(L"r.") + _toString(chunkX >> 5) + + L"." + _toString(chunkZ >> 5) + L".mcr"); + } + MemSect(0); - RegionFile *ref = NULL; - AUTO_VAR(it, cache.find(file)); - if( it != cache.end() ) - ref = it->second; + RegionFile* ref = NULL; + AUTO_VAR(it, cache.find(file)); + if (it != cache.end()) ref = it->second; - // 4J Jev, put back in. - if (ref != NULL) - { - return ref; + // 4J Jev, put back in. + if (ref != NULL) { + return ref; } - // 4J Stu - Remove for new save files - /* - if (!regionDir.exists()) - { - regionDir.mkdirs(); - } - */ - if (cache.size() >= MAX_CACHE_SIZE) - { + // 4J Stu - Remove for new save files + /* +if (!regionDir.exists()) + { + regionDir.mkdirs(); +} + */ + if (cache.size() >= MAX_CACHE_SIZE) { _clear(); } - RegionFile *reg = new RegionFile(saveFile, &file); - cache[file] = reg; // 4J - this was originally a softReferenc + RegionFile* reg = new RegionFile(saveFile, &file); + cache[file] = reg; // 4J - this was originally a softReferenc return reg; - } -void RegionFileCache::_clear() // 4J - TODO was synchronized +void RegionFileCache::_clear() // 4J - TODO was synchronized { - AUTO_VAR(itEnd, cache.end()); - for( AUTO_VAR(it, cache.begin()); it != itEnd; it++ ) - { - // 4J - removed try/catch -// try { - RegionFile *regionFile = it->second; - if (regionFile != NULL) - { + AUTO_VAR(itEnd, cache.end()); + for (AUTO_VAR(it, cache.begin()); it != itEnd; it++) { + // 4J - removed try/catch + // try { + RegionFile* regionFile = it->second; + if (regionFile != NULL) { regionFile->close(); } - delete regionFile; -// } catch (IOException e) { -// e.printStackTrace(); -// } - } - cache.clear(); + delete regionFile; + // } catch (IOException e) { + // e.printStackTrace(); + // } + } + cache.clear(); } -int RegionFileCache::_getSizeDelta(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) -{ - RegionFile *r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); +int RegionFileCache::_getSizeDelta(ConsoleSaveFile* saveFile, + const std::wstring& prefix, int chunkX, + int chunkZ) { + RegionFile* r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); return r->getSizeDelta(); } -DataInputStream *RegionFileCache::_getChunkDataInputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) -{ - RegionFile* r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); - if(useSplitSaves(saveFile->getSavePlatform())) - { - return r->getChunkDataInputStream(chunkX & 15, chunkZ & 15); - } - else - { - - return r->getChunkDataInputStream(chunkX & 31, chunkZ & 31); - } +DataInputStream* RegionFileCache::_getChunkDataInputStream( + ConsoleSaveFile* saveFile, const std::wstring& prefix, int chunkX, + int chunkZ) { + RegionFile* r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); + if (useSplitSaves(saveFile->getSavePlatform())) { + return r->getChunkDataInputStream(chunkX & 15, chunkZ & 15); + } else { + return r->getChunkDataInputStream(chunkX & 31, chunkZ & 31); + } } -DataOutputStream *RegionFileCache::_getChunkDataOutputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) -{ - RegionFile* r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); - if(useSplitSaves(saveFile->getSavePlatform())) - { - return r->getChunkDataOutputStream(chunkX & 15, chunkZ & 15); - } - else - { - - return r->getChunkDataOutputStream(chunkX & 31, chunkZ & 31); - } +DataOutputStream* RegionFileCache::_getChunkDataOutputStream( + ConsoleSaveFile* saveFile, const std::wstring& prefix, int chunkX, + int chunkZ) { + RegionFile* r = _getRegionFile(saveFile, prefix, chunkX, chunkZ); + if (useSplitSaves(saveFile->getSavePlatform())) { + return r->getChunkDataOutputStream(chunkX & 15, chunkZ & 15); + } else { + return r->getChunkDataOutputStream(chunkX & 31, chunkZ & 31); + } } diff --git a/Minecraft.World/Level/Storage/RegionFileCache.h b/Minecraft.World/Level/Storage/RegionFileCache.h index 2115f9cf6..9e8586eeb 100644 --- a/Minecraft.World/Level/Storage/RegionFileCache.h +++ b/Minecraft.World/Level/Storage/RegionFileCache.h @@ -3,33 +3,59 @@ #include "../../Util/Reference.h" #include "../../IO/Files/File.h" -class RegionFileCache -{ - friend class ConsoleSaveFileOriginal; +class RegionFileCache { + friend class ConsoleSaveFileOriginal; + private: - static const int MAX_CACHE_SIZE = 256; + static const int MAX_CACHE_SIZE = 256; - std::unordered_map cache; + std::unordered_map cache; - static RegionFileCache s_defaultCache; + static RegionFileCache s_defaultCache; public: - // Made public and non-static so we can have a cache for input and output files - RegionFileCache() {} + // Made public and non-static so we can have a cache for input and output + // files + RegionFileCache() {} - RegionFile *_getRegionFile(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ); // 4J - TODO was synchronized - void _clear(); // 4J - TODO was synchronized - int _getSizeDelta(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ); - DataInputStream *_getChunkDataInputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ); - DataOutputStream *_getChunkDataOutputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ); + RegionFile* _getRegionFile(ConsoleSaveFile* saveFile, + const std::wstring& prefix, int chunkX, + int chunkZ); // 4J - TODO was synchronized + void _clear(); // 4J - TODO was synchronized + int _getSizeDelta(ConsoleSaveFile* saveFile, const std::wstring& prefix, + int chunkX, int chunkZ); + DataInputStream* _getChunkDataInputStream(ConsoleSaveFile* saveFile, + const std::wstring& prefix, + int chunkX, int chunkZ); + DataOutputStream* _getChunkDataOutputStream(ConsoleSaveFile* saveFile, + const std::wstring& prefix, + int chunkX, int chunkZ); - // Keep static version for general game usage - static RegionFile *getRegionFile(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) { return s_defaultCache._getRegionFile(saveFile, prefix, chunkX, chunkZ); } - static void clear() { s_defaultCache._clear(); } - static int getSizeDelta(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) { return s_defaultCache._getSizeDelta(saveFile, prefix, chunkX, chunkZ); } - static DataInputStream *getChunkDataInputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) { return s_defaultCache._getChunkDataInputStream(saveFile, prefix, chunkX, chunkZ); } - static DataOutputStream *getChunkDataOutputStream(ConsoleSaveFile *saveFile, const std::wstring &prefix, int chunkX, int chunkZ) { return s_defaultCache._getChunkDataOutputStream(saveFile, prefix, chunkX, chunkZ); } + // Keep static version for general game usage + static RegionFile* getRegionFile(ConsoleSaveFile* saveFile, + const std::wstring& prefix, int chunkX, + int chunkZ) { + return s_defaultCache._getRegionFile(saveFile, prefix, chunkX, chunkZ); + } + static void clear() { s_defaultCache._clear(); } + static int getSizeDelta(ConsoleSaveFile* saveFile, + const std::wstring& prefix, int chunkX, + int chunkZ) { + return s_defaultCache._getSizeDelta(saveFile, prefix, chunkX, chunkZ); + } + static DataInputStream* getChunkDataInputStream(ConsoleSaveFile* saveFile, + const std::wstring& prefix, + int chunkX, int chunkZ) { + return s_defaultCache._getChunkDataInputStream(saveFile, prefix, chunkX, + chunkZ); + } + static DataOutputStream* getChunkDataOutputStream( + ConsoleSaveFile* saveFile, const std::wstring& prefix, int chunkX, + int chunkZ) { + return s_defaultCache._getChunkDataOutputStream(saveFile, prefix, + chunkX, chunkZ); + } private: - bool useSplitSaves(ESavePlatform platform); + bool useSplitSaves(ESavePlatform platform); }; diff --git a/Minecraft.World/Level/Storage/SavedData.cpp b/Minecraft.World/Level/Storage/SavedData.cpp index 30f63bfe2..1cb534ffb 100644 --- a/Minecraft.World/Level/Storage/SavedData.cpp +++ b/Minecraft.World/Level/Storage/SavedData.cpp @@ -1,24 +1,10 @@ #include "../../Platform/stdafx.h" #include "SavedData.h" +SavedData::SavedData(const std::wstring& id) : id(id) { dirty = false; } +void SavedData::setDirty() { setDirty(true); } -SavedData::SavedData(const std::wstring& id) : id( id ) -{ - dirty = false; -} +void SavedData::setDirty(bool dirty) { this->dirty = dirty; } -void SavedData::setDirty() -{ - setDirty(true); -} - -void SavedData::setDirty(bool dirty) -{ - this->dirty = dirty; -} - -bool SavedData::isDirty() -{ - return dirty; -} \ No newline at end of file +bool SavedData::isDirty() { return dirty; } \ No newline at end of file diff --git a/Minecraft.World/Level/Storage/SavedData.h b/Minecraft.World/Level/Storage/SavedData.h index 37e9f2579..3c62bd4e8 100644 --- a/Minecraft.World/Level/Storage/SavedData.h +++ b/Minecraft.World/Level/Storage/SavedData.h @@ -1,26 +1,24 @@ #pragma once - #include "../../Util/Class.h" class CompoundTag; -class SavedData : public std::enable_shared_from_this -{ +class SavedData : public std::enable_shared_from_this { public: - const std::wstring id; + const std::wstring id; private: - bool dirty; + bool dirty; public: - SavedData(const std::wstring& id); - virtual ~SavedData(){} + SavedData(const std::wstring& id); + virtual ~SavedData() {} - virtual void load(CompoundTag *tag) = 0; - virtual void save(CompoundTag *tag) = 0; + virtual void load(CompoundTag* tag) = 0; + virtual void save(CompoundTag* tag) = 0; - void setDirty(); - void setDirty(bool dirty); - bool isDirty(); + void setDirty(); + void setDirty(bool dirty); + bool isDirty(); }; diff --git a/Minecraft.World/Level/Storage/SavedDataStorage.cpp b/Minecraft.World/Level/Storage/SavedDataStorage.cpp index 17d969dc0..4a6d02ba6 100644 --- a/Minecraft.World/Level/Storage/SavedDataStorage.cpp +++ b/Minecraft.World/Level/Storage/SavedDataStorage.cpp @@ -8,179 +8,169 @@ #include "../../IO/Files/ConsoleSaveFileIO.h" -SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) -{ - /* - cache = new std::unordered_map >; - savedDatas = new std::vector >; - usedAuxIds = new std::unordered_map; - */ +SavedDataStorage::SavedDataStorage(LevelStorage* levelStorage) { + /* + cache = new std::unordered_map >; + savedDatas = new std::vector >; + usedAuxIds = new std::unordered_map; + */ this->levelStorage = levelStorage; loadAuxValues(); } -std::shared_ptr SavedDataStorage::get(const std::type_info& clazz, const std::wstring& id) -{ - AUTO_VAR(it, cache.find( id )); - if (it != cache.end()) return (*it).second; +std::shared_ptr SavedDataStorage::get(const std::type_info& clazz, + const std::wstring& id) { + AUTO_VAR(it, cache.find(id)); + if (it != cache.end()) return (*it).second; - std::shared_ptr data = nullptr; - if (levelStorage != NULL) - { - //File file = levelStorage->getDataFile(id); - ConsoleSavePath file = levelStorage->getDataFile(id); - if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) - { - // mob = std::dynamic_pointer_cast(Mob::_class->newInstance( level )); - //data = clazz.getConstructor(String.class).newInstance(id); + std::shared_ptr data = nullptr; + if (levelStorage != NULL) { + // File file = levelStorage->getDataFile(id); + ConsoleSavePath file = levelStorage->getDataFile(id); + if (!file.getName().empty() && + levelStorage->getSaveFile()->doesFileExist(file)) { + // mob = std::dynamic_pointer_cast(Mob::_class->newInstance( + // level )); + // data = clazz.getConstructor(String.class).newInstance(id); - if( clazz == typeid(MapItemSavedData) ) - { - data = std::dynamic_pointer_cast( std::shared_ptr(new MapItemSavedData(id)) ); - } - else if( clazz == typeid(Villages) ) - { - data = std::dynamic_pointer_cast( std::shared_ptr(new Villages(id) ) ); - } - else - { - // Handling of new SavedData class required - __debugbreak(); - } + if (clazz == typeid(MapItemSavedData)) { + data = std::dynamic_pointer_cast( + std::shared_ptr( + new MapItemSavedData(id))); + } else if (clazz == typeid(Villages)) { + data = std::dynamic_pointer_cast( + std::shared_ptr(new Villages(id))); + } else { + // Handling of new SavedData class required + __debugbreak(); + } - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(levelStorage->getSaveFile(), file); - CompoundTag *root = NbtIo::readCompressed(&fis); - fis.close(); + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(levelStorage->getSaveFile(), file); + CompoundTag* root = NbtIo::readCompressed(&fis); + fis.close(); - data->load(root->getCompound(L"data")); - } + data->load(root->getCompound(L"data")); + } } - if (data != NULL) - { - cache.insert( std::unordered_map >::value_type( id , data ) ); + if (data != NULL) { + cache.insert( + std::unordered_map >::value_type(id, + data)); savedDatas.push_back(data); } return data; } -void SavedDataStorage::set(const std::wstring& id, std::shared_ptr data) -{ - if (data == NULL) - { - // TODO 4J Stu - throw new RuntimeException("Can't set null data"); - assert( false ); - } - AUTO_VAR(it, cache.find(id)); - if ( it != cache.end() ) - { - AUTO_VAR(it2, find( savedDatas.begin(), savedDatas.end(), it->second )); - if( it2 != savedDatas.end() ) - { - savedDatas.erase( it2 ); - } - cache.erase( it ); - } - cache.insert( cacheMapType::value_type(id, data) ); - savedDatas.push_back(data); +void SavedDataStorage::set(const std::wstring& id, + std::shared_ptr data) { + if (data == NULL) { + // TODO 4J Stu - throw new RuntimeException("Can't set null data"); + assert(false); + } + AUTO_VAR(it, cache.find(id)); + if (it != cache.end()) { + AUTO_VAR(it2, find(savedDatas.begin(), savedDatas.end(), it->second)); + if (it2 != savedDatas.end()) { + savedDatas.erase(it2); + } + cache.erase(it); + } + cache.insert(cacheMapType::value_type(id, data)); + savedDatas.push_back(data); } -void SavedDataStorage::save() -{ - AUTO_VAR(itEnd, savedDatas.end()); - for (AUTO_VAR(it, savedDatas.begin()); it != itEnd; it++) - { - std::shared_ptr data = *it; //savedDatas->at(i); - if (data->isDirty()) - { +void SavedDataStorage::save() { + AUTO_VAR(itEnd, savedDatas.end()); + for (AUTO_VAR(it, savedDatas.begin()); it != itEnd; it++) { + std::shared_ptr data = *it; // savedDatas->at(i); + if (data->isDirty()) { save(data); data->setDirty(false); } } } -void SavedDataStorage::save(std::shared_ptr data) -{ +void SavedDataStorage::save(std::shared_ptr data) { if (levelStorage == NULL) return; - //File file = levelStorage->getDataFile(data->id); - ConsoleSavePath file = levelStorage->getDataFile(data->id); - if (!file.getName().empty()) - { - CompoundTag *dataTag = new CompoundTag(); + // File file = levelStorage->getDataFile(data->id); + ConsoleSavePath file = levelStorage->getDataFile(data->id); + if (!file.getName().empty()) { + CompoundTag* dataTag = new CompoundTag(); data->save(dataTag); - CompoundTag *tag = new CompoundTag(); + CompoundTag* tag = new CompoundTag(); tag->putCompound(L"data", dataTag); - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); NbtIo::writeCompressed(tag, &fos); fos.close(); - delete tag; + delete tag; } } -void SavedDataStorage::loadAuxValues() -{ +void SavedDataStorage::loadAuxValues() { usedAuxIds.clear(); if (levelStorage == NULL) return; - //File file = levelStorage->getDataFile(L"idcounts"); - ConsoleSavePath file = levelStorage->getDataFile(L"idcounts"); - if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) - { - ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(levelStorage->getSaveFile(), file); + // File file = levelStorage->getDataFile(L"idcounts"); + ConsoleSavePath file = levelStorage->getDataFile(L"idcounts"); + if (!file.getName().empty() && + levelStorage->getSaveFile()->doesFileExist(file)) { + ConsoleSaveFileInputStream fis = + ConsoleSaveFileInputStream(levelStorage->getSaveFile(), file); DataInputStream dis = DataInputStream(&fis); - CompoundTag *tags = NbtIo::read(&dis); + CompoundTag* tags = NbtIo::read(&dis); dis.close(); - Tag *tag; - std::vector *allTags = tags->getAllTags(); - AUTO_VAR(itEnd, allTags->end()); - for (AUTO_VAR(it, allTags->begin()); it != itEnd; it++) - { - tag = *it; //tags->getAllTags()->at(i); + Tag* tag; + std::vector* allTags = tags->getAllTags(); + AUTO_VAR(itEnd, allTags->end()); + for (AUTO_VAR(it, allTags->begin()); it != itEnd; it++) { + tag = *it; // tags->getAllTags()->at(i); - if (dynamic_cast(tag) != NULL) - { - ShortTag *sTag = (ShortTag *) tag; + if (dynamic_cast(tag) != NULL) { + ShortTag* sTag = (ShortTag*)tag; std::wstring id = sTag->getName(); short val = sTag->data; - usedAuxIds.insert( uaiMapType::value_type( id, val ) ); + usedAuxIds.insert(uaiMapType::value_type(id, val)); } } - delete allTags; + delete allTags; } } -int SavedDataStorage::getFreeAuxValueFor(const std::wstring& id) -{ - AUTO_VAR(it, usedAuxIds.find( id )); +int SavedDataStorage::getFreeAuxValueFor(const std::wstring& id) { + AUTO_VAR(it, usedAuxIds.find(id)); short val = 0; - if ( it != usedAuxIds.end() ) - { - val = (*it).second; + if (it != usedAuxIds.end()) { + val = (*it).second; val++; } - usedAuxIds[id] = val; + usedAuxIds[id] = val; if (levelStorage == NULL) return val; - //File file = levelStorage->getDataFile(L"idcounts"); - ConsoleSavePath file = levelStorage->getDataFile(L"idcounts"); - if (!file.getName().empty()) - { - CompoundTag *tag = new CompoundTag(); + // File file = levelStorage->getDataFile(L"idcounts"); + ConsoleSavePath file = levelStorage->getDataFile(L"idcounts"); + if (!file.getName().empty()) { + CompoundTag* tag = new CompoundTag(); - // TODO 4J Stu - This was iterating over the keySet in Java, so potentially we are looking at more items? - AUTO_VAR(itEndAuxIds, usedAuxIds.end()); - for(uaiMapType::iterator it2 = usedAuxIds.begin(); it2 != itEndAuxIds; it2++) - { - short value = it2->second; - tag->putShort( (wchar_t *) it2->first.c_str(), value); + // TODO 4J Stu - This was iterating over the keySet in Java, so + // potentially we are looking at more items? + AUTO_VAR(itEndAuxIds, usedAuxIds.end()); + for (uaiMapType::iterator it2 = usedAuxIds.begin(); it2 != itEndAuxIds; + it2++) { + short value = it2->second; + tag->putShort((wchar_t*)it2->first.c_str(), value); } - ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); + ConsoleSaveFileOutputStream fos = + ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); DataOutputStream dos = DataOutputStream(&fos); NbtIo::write(tag, &dos); dos.close(); @@ -189,23 +179,20 @@ int SavedDataStorage::getFreeAuxValueFor(const std::wstring& id) } // 4J Added -int SavedDataStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale) -{ - if( levelStorage == NULL ) - { - switch(dimension) - { - case -1: - return MAP_NETHER_DEFAULT_INDEX; - case 1: - return MAP_END_DEFAULT_INDEX; - case 0: - default: - return MAP_OVERWORLD_DEFAULT_INDEX; - } - } - else - { - return levelStorage->getAuxValueForMap(xuid, dimension, centreXC, centreZC, scale); - } +int SavedDataStorage::getAuxValueForMap(PlayerUID xuid, int dimension, + int centreXC, int centreZC, int scale) { + if (levelStorage == NULL) { + switch (dimension) { + case -1: + return MAP_NETHER_DEFAULT_INDEX; + case 1: + return MAP_END_DEFAULT_INDEX; + case 0: + default: + return MAP_OVERWORLD_DEFAULT_INDEX; + } + } else { + return levelStorage->getAuxValueForMap(xuid, dimension, centreXC, + centreZC, scale); + } } diff --git a/Minecraft.World/Level/Storage/SavedDataStorage.h b/Minecraft.World/Level/Storage/SavedDataStorage.h index b35c2bdae..f214d47f2 100644 --- a/Minecraft.World/Level/Storage/SavedDataStorage.h +++ b/Minecraft.World/Level/Storage/SavedDataStorage.h @@ -1,35 +1,36 @@ #pragma once - class ConsoleSaveFile; #include "SavedData.h" -class SavedDataStorage -{ +class SavedDataStorage { private: - LevelStorage *levelStorage; + LevelStorage* levelStorage; - typedef std::unordered_map > cacheMapType; + typedef std::unordered_map > + cacheMapType; cacheMapType cache; std::vector > savedDatas; - typedef std::unordered_map uaiMapType; + typedef std::unordered_map uaiMapType; uaiMapType usedAuxIds; public: - SavedDataStorage(LevelStorage *); - std::shared_ptr get(const std::type_info& clazz, const std::wstring& id); + SavedDataStorage(LevelStorage*); + std::shared_ptr get(const std::type_info& clazz, + const std::wstring& id); void set(const std::wstring& id, std::shared_ptr data); void save(); private: - void save(std::shared_ptr data); + void save(std::shared_ptr data); void loadAuxValues(); public: - int getFreeAuxValueFor(const std::wstring& id); + int getFreeAuxValueFor(const std::wstring& id); - // 4J Added - int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int centreZC, int scale); + // 4J Added + int getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, + int centreZC, int scale); }; diff --git a/Minecraft.World/Level/Storage/SparseDataStorage.cpp b/Minecraft.World/Level/Storage/SparseDataStorage.cpp index 9ef256100..77905dc11 100644 --- a/Minecraft.World/Level/Storage/SparseDataStorage.cpp +++ b/Minecraft.World/Level/Storage/SparseDataStorage.cpp @@ -4,622 +4,628 @@ // Note: See header for an overview of this class int SparseDataStorage::deleteQueueIndex; -XLockFreeStack SparseDataStorage::deleteQueue[3]; +XLockFreeStack SparseDataStorage::deleteQueue[3]; -void SparseDataStorage::staticCtor() -{ - for( int i = 0; i < 3; i++ ) - { - deleteQueue[i].Initialize(); - } +void SparseDataStorage::staticCtor() { + for (int i = 0; i < 3; i++) { + deleteQueue[i].Initialize(); + } } -// Initialise data storage, with very limited compression - the very first plane is stored as either compressed to be "all 0", and the rest of the planes aren't compressed at all. -// The reason behind this is to keep the total allocation as a round number of 4K (small) pages, ie 16K. -// By doing this, and doing this "special" allocation as a XPhysicalAlloc rather than a malloc, we can help ensure that this full allocation gets cleaned up properly when the first -// proper compression is done on this storage. If it were just allocated with malloc, then the memory management system would have a large number of 16512 allocations to free, and -// it seems from experimentation that these basically don't make it back to the system as free pages. -// Note - the other approach here would be to allocate *no* actual storage for the data at the ctor stage. However, as chunks are created then this creates an awful lot of intermediate -// stages as each line of data is added, so it is actually much cleaner to just allocate almost fully here & then attempt to do a single compression pass over the data later on. -SparseDataStorage::SparseDataStorage() -{ - // Allocate using physical alloc. As this will (by default) return memory from the pool of 4KB pages, the address will in the range of MM_PHYSICAL_4KB_BASE upwards. We can use - // this fact to identify the allocation later, and so free it with the corresponding call to XPhysicalFree. +// Initialise data storage, with very limited compression - the very first plane +// is stored as either compressed to be "all 0", and the rest of the planes +// aren't compressed at all. The reason behind this is to keep the total +// allocation as a round number of 4K (small) pages, ie 16K. By doing this, and +// doing this "special" allocation as a XPhysicalAlloc rather than a malloc, we +// can help ensure that this full allocation gets cleaned up properly when the +// first proper compression is done on this storage. If it were just allocated +// with malloc, then the memory management system would have a large number of +// 16512 allocations to free, and it seems from experimentation that these +// basically don't make it back to the system as free pages. Note - the other +// approach here would be to allocate *no* actual storage for the data at the +// ctor stage. However, as chunks are created then this creates an awful lot of +// intermediate stages as each line of data is added, so it is actually much +// cleaner to just allocate almost fully here & then attempt to do a single +// compression pass over the data later on. +SparseDataStorage::SparseDataStorage() { + // Allocate using physical alloc. As this will (by default) return memory + // from the pool of 4KB pages, the address will in the range of + // MM_PHYSICAL_4KB_BASE upwards. We can use this fact to identify the + // allocation later, and so free it with the corresponding call to + // XPhysicalFree. #ifdef _XBOX - unsigned char *planeIndices = (unsigned char *)XPhysicalAlloc(128 * 128, MAXULONG_PTR, 4096, PAGE_READWRITE); + unsigned char* planeIndices = (unsigned char*)XPhysicalAlloc( + 128 * 128, MAXULONG_PTR, 4096, PAGE_READWRITE); #else - unsigned char *planeIndices = (unsigned char *)malloc(128 * 128); + unsigned char* planeIndices = (unsigned char*)malloc(128 * 128); #endif - unsigned char *data = planeIndices + 128; - planeIndices[0] = ALL_0_INDEX; - for( int i = 1; i < 128; i++ ) - { - planeIndices[i] = i - 1; - } - XMemSet(data, 0, 128 * 127); + unsigned char* data = planeIndices + 128; + planeIndices[0] = ALL_0_INDEX; + for (int i = 1; i < 128; i++) { + planeIndices[i] = i - 1; + } + XMemSet(data, 0, 128 * 127); - // Data and count packs together the pointer to our data and the count of planes allocated - 127 planes allocated in this case + // Data and count packs together the pointer to our data and the count of + // planes allocated - 127 planes allocated in this case - dataAndCount = 0x007F000000000000L | (( (__int64) planeIndices ) & 0x0000ffffffffffffL); + dataAndCount = + 0x007F000000000000L | (((__int64)planeIndices) & 0x0000ffffffffffffL); #ifdef DATA_COMPRESSION_STATS - count = 128; + count = 128; #endif } -SparseDataStorage::SparseDataStorage(bool isUpper) -{ - // Allocate using physical alloc. As this will (by default) return memory from the pool of 4KB pages, the address will in the range of MM_PHYSICAL_4KB_BASE upwards. We can use - // this fact to identify the allocation later, and so free it with the corresponding call to XPhysicalFree. - unsigned char *planeIndices = (unsigned char *)malloc(128); - for( int i = 0; i < 128; i++ ) - { - planeIndices[i] = ALL_0_INDEX; - } +SparseDataStorage::SparseDataStorage(bool isUpper) { + // Allocate using physical alloc. As this will (by default) return memory + // from the pool of 4KB pages, the address will in the range of + // MM_PHYSICAL_4KB_BASE upwards. We can use this fact to identify the + // allocation later, and so free it with the corresponding call to + // XPhysicalFree. + unsigned char* planeIndices = (unsigned char*)malloc(128); + for (int i = 0; i < 128; i++) { + planeIndices[i] = ALL_0_INDEX; + } - // Data and count packs together the pointer to our data and the count of planes allocated - 127 planes allocated in this case + // Data and count packs together the pointer to our data and the count of + // planes allocated - 127 planes allocated in this case - dataAndCount = 0x0000000000000000L | (( (__int64) planeIndices ) & 0x0000ffffffffffffL); + dataAndCount = + 0x0000000000000000L | (((__int64)planeIndices) & 0x0000ffffffffffffL); #ifdef DATA_COMPRESSION_STATS - count = 128; + count = 128; #endif } -SparseDataStorage::~SparseDataStorage() -{ - unsigned char *indicesAndData = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - // Determine correct means to free this data - could have been allocated either with XPhysicalAlloc or malloc - +SparseDataStorage::~SparseDataStorage() { + unsigned char* indicesAndData = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + // Determine correct means to free this data - could have been allocated + // either with XPhysicalAlloc or malloc + #ifdef _XBOX - if( (unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE ) - { - XPhysicalFree(indicesAndData); - } - else + if ((unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE) { + XPhysicalFree(indicesAndData); + } else #endif - { - free(indicesAndData); - } -// printf("Free (in dtor) 0x%x\n", indicesAndData); + { + free(indicesAndData); + } + // printf("Free (in dtor) 0x%x\n", indicesAndData); } -SparseDataStorage::SparseDataStorage(SparseDataStorage *copyFrom) -{ - // Extra details of source storage - __int64 sourceDataAndCount = copyFrom->dataAndCount; - unsigned char *sourceIndicesAndData = (unsigned char *)(sourceDataAndCount & 0x0000ffffffffffff); - int sourceCount = (sourceDataAndCount >> 48 ) & 0xffff; +SparseDataStorage::SparseDataStorage(SparseDataStorage* copyFrom) { + // Extra details of source storage + __int64 sourceDataAndCount = copyFrom->dataAndCount; + unsigned char* sourceIndicesAndData = + (unsigned char*)(sourceDataAndCount & 0x0000ffffffffffff); + int sourceCount = (sourceDataAndCount >> 48) & 0xffff; - // Allocate & copy indices ( 128 bytes ) and any allocated planes (128 * count) - unsigned char *destIndicesAndData = (unsigned char *)malloc( sourceCount * 128 + 128 ); + // Allocate & copy indices ( 128 bytes ) and any allocated planes (128 * + // count) + unsigned char* destIndicesAndData = + (unsigned char*)malloc(sourceCount * 128 + 128); - // AP - I've moved this to be before the memcpy because of a very strange bug on vita. Sometimes dataAndCount wasn't valid in time when ::get was called. - // This should never happen and this isn't a proper solution but fixes it for now. + // AP - I've moved this to be before the memcpy because of a very strange + // bug on vita. Sometimes dataAndCount wasn't valid in time when ::get was + // called. This should never happen and this isn't a proper solution but + // fixes it for now. - dataAndCount = ( sourceDataAndCount & 0xffff000000000000L ) | ( ((__int64) destIndicesAndData ) & 0x0000ffffffffffffL ); + dataAndCount = (sourceDataAndCount & 0xffff000000000000L) | + (((__int64)destIndicesAndData) & 0x0000ffffffffffffL); - - XMemCpy( destIndicesAndData, sourceIndicesAndData, sourceCount * 128 + 128 ); + XMemCpy(destIndicesAndData, sourceIndicesAndData, sourceCount * 128 + 128); #ifdef DATA_COMPRESSION_STATS - count = sourceCount; + count = sourceCount; #endif } -// Set all data values from a data array of length 16384 (128 x 16 x 16 x 0.5). Source data must have same order as original java game -void SparseDataStorage::setData(byteArray dataIn, unsigned int inOffset) -{ - // Original order is defined as: - // pos = (x << 11 | z << 7 | y); - // slot = pos >> 1; - // part = pos & 1; - // if ( part == 0 ) value = data[slot] & 0xf - // else value = (data[slot] >> 4) & 0xf +// Set all data values from a data array of length 16384 (128 x 16 x 16 x 0.5). +// Source data must have same order as original java game +void SparseDataStorage::setData(byteArray dataIn, unsigned int inOffset) { + // Original order is defined as: + // pos = (x << 11 | z << 7 | y); + // slot = pos >> 1; + // part = pos & 1; + // if ( part == 0 ) value = data[slot] & 0xf + // else value = (data[slot] >> 4) & 0xf - // Two passed through the data. First pass sets up plane indices, and counts number of planes that we actually need to allocate - int allocatedPlaneCount = 0; - unsigned char _planeIndices[128]; + // Two passed through the data. First pass sets up plane indices, and counts + // number of planes that we actually need to allocate + int allocatedPlaneCount = 0; + unsigned char _planeIndices[128]; - //unsigned char *lastDataPointer = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); + // unsigned char *lastDataPointer = (unsigned char *)(dataAndCount & + // 0x0000ffffffffffff); - for( int y = 0; y < 128; y++ ) - { - bool all0 = true; - - for( int xz = 0; xz < 256; xz++ ) // 256 in loop as 16 x 16 separate bytes need checked - { - int pos = ( xz << 7 ) | y; - int slot = pos >> 1; - int part = pos & 1; - unsigned char value = ( dataIn[slot + inOffset] >> (part * 4) ) & 15; - if( value != 0 ) all0 = false; - } - if( all0 ) - { - _planeIndices[y] = ALL_0_INDEX; - } - else - { - _planeIndices[y] = allocatedPlaneCount++; - } - } + for (int y = 0; y < 128; y++) { + bool all0 = true; - // Allocate required storage - unsigned char *planeIndices = (unsigned char *)malloc(128 * allocatedPlaneCount + 128); - unsigned char *data = planeIndices + 128; - XMemCpy(planeIndices, _planeIndices, 128); + for (int xz = 0; xz < 256; + xz++) // 256 in loop as 16 x 16 separate bytes need checked + { + int pos = (xz << 7) | y; + int slot = pos >> 1; + int part = pos & 1; + unsigned char value = (dataIn[slot + inOffset] >> (part * 4)) & 15; + if (value != 0) all0 = false; + } + if (all0) { + _planeIndices[y] = ALL_0_INDEX; + } else { + _planeIndices[y] = allocatedPlaneCount++; + } + } - // Second pass through to actually copy the data in to the storage allocated for the required planes - unsigned char *pucOut = data; - for( int y = 0; y < 128 ; y++ ) - { - // Index will be < 128 if we allocated storage for it and it has a valid index. No need to actually check the index as - // we know they were sequentially allocated above. - if( planeIndices[y] < 128 ) - { - int part = y & 1; - //int shift = 4 * part; - unsigned char *pucIn = &dataIn[ (y >> 1) + inOffset]; + // Allocate required storage + unsigned char* planeIndices = + (unsigned char*)malloc(128 * allocatedPlaneCount + 128); + unsigned char* data = planeIndices + 128; + XMemCpy(planeIndices, _planeIndices, 128); - for( int xz = 0; xz < 128; xz++ ) // 128 ( 16 x 16 x 0.5 ) in loop as packing 2 values into each destination byte - { - *pucOut = ( ( *pucIn ) >> ( part * 4 ) ) & 15; - pucIn += 64; + // Second pass through to actually copy the data in to the storage allocated + // for the required planes + unsigned char* pucOut = data; + for (int y = 0; y < 128; y++) { + // Index will be < 128 if we allocated storage for it and it has a valid + // index. No need to actually check the index as we know they were + // sequentially allocated above. + if (planeIndices[y] < 128) { + int part = y & 1; + // int shift = 4 * part; + unsigned char* pucIn = &dataIn[(y >> 1) + inOffset]; - *pucOut |= ( ( ( *pucIn ) >> ( part * 4 ) ) & 15 ) << 4; - pucIn += 64; - pucOut++; - } - } - } + for (int xz = 0; xz < 128; + xz++) // 128 ( 16 x 16 x 0.5 ) in loop as packing 2 values + // into each destination byte + { + *pucOut = ((*pucIn) >> (part * 4)) & 15; + pucIn += 64; - // Get new data and count packed info + *pucOut |= (((*pucIn) >> (part * 4)) & 15) << 4; + pucIn += 64; + pucOut++; + } + } + } - __int64 newDataAndCount = ((__int64) planeIndices) & 0x0000ffffffffffffL; + // Get new data and count packed info - newDataAndCount |= ((__int64)allocatedPlaneCount) << 48; + __int64 newDataAndCount = ((__int64)planeIndices) & 0x0000ffffffffffffL; - updateDataAndCount( newDataAndCount ); + newDataAndCount |= ((__int64)allocatedPlaneCount) << 48; + + updateDataAndCount(newDataAndCount); } -// Gets all data values into an array of length 16384. Destination data will have same order as original java game. -void SparseDataStorage::getData(byteArray retArray, unsigned int retOffset) -{ - XMemSet(retArray.data + + retOffset, 0, 16384); - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); +// Gets all data values into an array of length 16384. Destination data will +// have same order as original java game. +void SparseDataStorage::getData(byteArray retArray, unsigned int retOffset) { + XMemSet(retArray.data + +retOffset, 0, 16384); + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - // Original order is defined as: - // pos = (x << 11 | z << 7 | y); - // slot = pos >> 1; - // part = pos & 1; - // if ( part == 0 ) value = data[slot] & 0xf - // else value = (data[slot] >> 4) & 0xf + // Original order is defined as: + // pos = (x << 11 | z << 7 | y); + // slot = pos >> 1; + // part = pos & 1; + // if ( part == 0 ) value = data[slot] & 0xf + // else value = (data[slot] >> 4) & 0xf - for( int y = 0; y < 128; y++ ) - { - if( planeIndices[y] == ALL_0_INDEX ) - { - // No need to do anything in this case as retArray is initialised to zero - } - else - { - int part = y & 1; - int shift = 4 * part; - unsigned char *pucOut = &retArray.data[ (y >> 1) + + retOffset]; - unsigned char *pucIn = &data[ planeIndices[ y ] * 128 ]; - for( int xz = 0; xz < 128; xz++ ) // 128 in loop (16 x 16 x 0.5) as input data is being treated in pairs of nybbles that are packed in the same byte - { - unsigned char value = (*pucIn) & 15; - *pucOut |= ( value << shift ); - pucOut += 64; + for (int y = 0; y < 128; y++) { + if (planeIndices[y] == ALL_0_INDEX) { + // No need to do anything in this case as retArray is initialised to + // zero + } else { + int part = y & 1; + int shift = 4 * part; + unsigned char* pucOut = &retArray.data[(y >> 1) + +retOffset]; + unsigned char* pucIn = &data[planeIndices[y] * 128]; + for (int xz = 0; xz < 128; + xz++) // 128 in loop (16 x 16 x 0.5) as input data is being + // treated in pairs of nybbles that are packed in the + // same byte + { + unsigned char value = (*pucIn) & 15; + *pucOut |= (value << shift); + pucOut += 64; - value = ((*pucIn) >> 4 ) & 15; - *pucOut |= ( value << shift ); - pucOut += 64; + value = ((*pucIn) >> 4) & 15; + *pucOut |= (value << shift); + pucOut += 64; - pucIn++; - } - } - } + pucIn++; + } + } + } } // Get an individual data value -int SparseDataStorage::get(int x, int y, int z) -{ - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); - - if( planeIndices[y] == ALL_0_INDEX ) - { - return 0; - } - else - { - int planeIndex = x * 16 + z; // Index within this xz plane - int byteIndex = planeIndex / 2; // Byte index within the plane (2 tiles stored per byte) - int shift = ( planeIndex & 1 ) * 4; // Bit shift within the byte - int retval = ( data[ planeIndices[y] * 128 + byteIndex ] >> shift ) & 15; +int SparseDataStorage::get(int x, int y, int z) { + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - return retval; - } + if (planeIndices[y] == ALL_0_INDEX) { + return 0; + } else { + int planeIndex = x * 16 + z; // Index within this xz plane + int byteIndex = + planeIndex / + 2; // Byte index within the plane (2 tiles stored per byte) + int shift = (planeIndex & 1) * 4; // Bit shift within the byte + int retval = (data[planeIndices[y] * 128 + byteIndex] >> shift) & 15; + + return retval; + } } // Set an individual data value -void SparseDataStorage::set(int x, int y, int z, int val) -{ - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); +void SparseDataStorage::set(int x, int y, int z, int val) { + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - // If this plane isn't yet allocated, then we might have some extra work to do - if( planeIndices[y] >= ALL_0_INDEX ) - { - // No data allocated. Early out though if we are storing what is already represented by our special index. - if( ( val == 0 ) && ( planeIndices[y] == ALL_0_INDEX ) ) - { - return; - } + // If this plane isn't yet allocated, then we might have some extra work to + // do + if (planeIndices[y] >= ALL_0_INDEX) { + // No data allocated. Early out though if we are storing what is already + // represented by our special index. + if ((val == 0) && (planeIndices[y] == ALL_0_INDEX)) { + return; + } - // Reallocate the storage for planes to accomodate one extra - addNewPlane(y); + // Reallocate the storage for planes to accomodate one extra + addNewPlane(y); - // Get pointers again as these may have moved - getPlaneIndicesAndData(&planeIndices, &data); - } + // Get pointers again as these may have moved + getPlaneIndicesAndData(&planeIndices, &data); + } - // Either data was already allocated, or we've just done that. Now store our value into the right place. + // Either data was already allocated, or we've just done that. Now store our + // value into the right place. - int planeIndex = x * 16 + z; // Index within this xz plane - int byteIndex = planeIndex / 2; // Byte index within the plane (2 tiles stored per byte) - int shift = ( planeIndex & 1 ) * 4; // Bit shift within the byte - int mask = 0xf0 >> shift; - - int idx = planeIndices[y] * 128 + byteIndex; - data[idx] = ( data[idx] & mask ) | ( val << shift ); + int planeIndex = x * 16 + z; // Index within this xz plane + int byteIndex = planeIndex / + 2; // Byte index within the plane (2 tiles stored per byte) + int shift = (planeIndex & 1) * 4; // Bit shift within the byte + int mask = 0xf0 >> shift; + int idx = planeIndices[y] * 128 + byteIndex; + data[idx] = (data[idx] & mask) | (val << shift); } -// Sets a region of data values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer -// Note - when data was extracted from the original data layers by LevelChunk::getBlocksAndData, y0 had to have even alignment and y1 - y0 also -// needed to be even as data was packed in nyblles in this dimension, and the code didn't make any attempt to unpack it. This behaviour is copied -// here for compatibility even though our source data isn't packed this way. -// Returns size of data copied. -int SparseDataStorage::setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset, tileUpdatedCallback callback, void *param, int yparam) -{ - // Actual setting of data happens when calling set method so no need to lock here - unsigned char *pucIn = &dataIn.data[offset]; - if( callback ) - { - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - // Emulate how data was extracted from DataLayer... see comment above - int yy0 = y0 & 0xfffffffe; - int len = ( y1 - y0 ) / 2; - for( int i = 0; i < len; i++ ) - { - int y = yy0 + ( i * 2 ); +// Sets a region of data values with the data at offset position in the array +// dataIn - external ordering compatible with java DataLayer Note - when data +// was extracted from the original data layers by LevelChunk::getBlocksAndData, +// y0 had to have even alignment and y1 - y0 also needed to be even as data was +// packed in nyblles in this dimension, and the code didn't make any attempt to +// unpack it. This behaviour is copied here for compatibility even though our +// source data isn't packed this way. Returns size of data copied. +int SparseDataStorage::setDataRegion(byteArray dataIn, int x0, int y0, int z0, + int x1, int y1, int z1, int offset, + tileUpdatedCallback callback, void* param, + int yparam) { + // Actual setting of data happens when calling set method so no need to lock + // here + unsigned char* pucIn = &dataIn.data[offset]; + if (callback) { + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + // Emulate how data was extracted from DataLayer... see comment + // above + int yy0 = y0 & 0xfffffffe; + int len = (y1 - y0) / 2; + for (int i = 0; i < len; i++) { + int y = yy0 + (i * 2); - int toSet = (*pucIn) & 15; - if( get(x, y, z) != toSet ) - { - set(x, y, z, toSet ); - callback(x, y, z, param, yparam); - } - toSet = ((*pucIn) >> 4 ) & 15; - if( get(x, y + 1, z) != toSet ) - { - set(x, y + 1, z, toSet ); - callback(x, y + 1, z, param, yparam); - } - pucIn++; - } - } - } - } - else - { - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - // Emulate how data was extracted from DataLayer... see comment above - int yy0 = y0 & 0xfffffffe; - int len = ( y1 - y0 ) / 2; - for( int i = 0; i < len; i++ ) - { - int y = yy0 + ( i * 2 ); + int toSet = (*pucIn) & 15; + if (get(x, y, z) != toSet) { + set(x, y, z, toSet); + callback(x, y, z, param, yparam); + } + toSet = ((*pucIn) >> 4) & 15; + if (get(x, y + 1, z) != toSet) { + set(x, y + 1, z, toSet); + callback(x, y + 1, z, param, yparam); + } + pucIn++; + } + } + } + } else { + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + // Emulate how data was extracted from DataLayer... see comment + // above + int yy0 = y0 & 0xfffffffe; + int len = (y1 - y0) / 2; + for (int i = 0; i < len; i++) { + int y = yy0 + (i * 2); - set(x, y, z, (*pucIn) & 15 ); - set(x, y + 1, z, ((*pucIn) >> 4 ) & 15 ); - pucIn++; - } - } - } - } - ptrdiff_t count = pucIn - &dataIn.data[offset]; + set(x, y, z, (*pucIn) & 15); + set(x, y + 1, z, ((*pucIn) >> 4) & 15); + pucIn++; + } + } + } + } + ptrdiff_t count = pucIn - &dataIn.data[offset]; - return (int)count; + return (int)count; } -// Updates the data at offset position dataInOut with a region of data information - external ordering compatible with java DataLayer -// Note - when data was placed in the original data layers by LevelChunk::setBlocksAndData, y0 had to have even alignment and y1 - y0 also -// needed to be even as data was packed in nyblles in this dimension, and the code didn't make any attempt to unpack it. This behaviour is copied -// here for compatibility even though our source data isn't packed this way -// Returns size of data copied. -int SparseDataStorage::getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset) -{ - unsigned char *pucOut = &dataInOut.data[offset]; - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - // Emulate how data was extracted from DataLayer... see comment above - int yy0 = y0 & 0xfffffffe; - int len = ( y1 - y0 ) / 2; - for( int i = 0; i < len; i++ ) - { - int y = yy0 + ( i * 2 ); +// Updates the data at offset position dataInOut with a region of data +// information - external ordering compatible with java DataLayer Note - when +// data was placed in the original data layers by LevelChunk::setBlocksAndData, +// y0 had to have even alignment and y1 - y0 also needed to be even as data was +// packed in nyblles in this dimension, and the code didn't make any attempt to +// unpack it. This behaviour is copied here for compatibility even though our +// source data isn't packed this way Returns size of data copied. +int SparseDataStorage::getDataRegion(byteArray dataInOut, int x0, int y0, + int z0, int x1, int y1, int z1, + int offset) { + unsigned char* pucOut = &dataInOut.data[offset]; + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + // Emulate how data was extracted from DataLayer... see comment + // above + int yy0 = y0 & 0xfffffffe; + int len = (y1 - y0) / 2; + for (int i = 0; i < len; i++) { + int y = yy0 + (i * 2); - *pucOut = get( x, y, z); - *pucOut |= get( x, y + 1, z) << 4; - pucOut++; - } - } - } - ptrdiff_t count = pucOut - &dataInOut.data[offset]; - - return (int)count; + *pucOut = get(x, y, z); + *pucOut |= get(x, y + 1, z) << 4; + pucOut++; + } + } + } + ptrdiff_t count = pucOut - &dataInOut.data[offset]; + + return (int)count; } -void SparseDataStorage::addNewPlane(int y) -{ - bool success = false; - do - { - // Get last packed data pointer & count - __int64 lastDataAndCount = dataAndCount; +void SparseDataStorage::addNewPlane(int y) { + bool success = false; + do { + // Get last packed data pointer & count + __int64 lastDataAndCount = dataAndCount; - // Unpack count & data pointer - int lastLinesUsed = (int)(( lastDataAndCount >> 48 ) & 0xffff); - unsigned char *lastDataPointer = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); + // Unpack count & data pointer + int lastLinesUsed = (int)((lastDataAndCount >> 48) & 0xffff); + unsigned char* lastDataPointer = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); - // Find out what to prefill the newly allocated line with - unsigned char planeIndex = lastDataPointer[y]; - - if( planeIndex < ALL_0_INDEX ) return; // Something has already allocated this line - we're done - - int linesUsed = lastLinesUsed + 1; + // Find out what to prefill the newly allocated line with + unsigned char planeIndex = lastDataPointer[y]; - // Allocate new memory storage, copy over anything from old storage, and initialise remainder - unsigned char *dataPointer = (unsigned char *)malloc(linesUsed * 128 + 128); - XMemCpy( dataPointer, lastDataPointer, 128 * lastLinesUsed + 128); - XMemSet( dataPointer + ( 128 * lastLinesUsed ) + 128, 0, 128 ); - dataPointer[y] = lastLinesUsed; + if (planeIndex < ALL_0_INDEX) + return; // Something has already allocated this line - we're done - // Get new data and count packed info + int linesUsed = lastLinesUsed + 1; - __int64 newDataAndCount = ((__int64) dataPointer) & 0x0000ffffffffffffL; + // Allocate new memory storage, copy over anything from old storage, and + // initialise remainder + unsigned char* dataPointer = + (unsigned char*)malloc(linesUsed * 128 + 128); + XMemCpy(dataPointer, lastDataPointer, 128 * lastLinesUsed + 128); + XMemSet(dataPointer + (128 * lastLinesUsed) + 128, 0, 128); + dataPointer[y] = lastLinesUsed; - newDataAndCount |= ((__int64)linesUsed) << 48; + // Get new data and count packed info - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); - - if( lastDataAndCount2 == lastDataAndCount ) - { - success = true; - // Queue old data to be deleted - queueForDelete( lastDataPointer ); + __int64 newDataAndCount = ((__int64)dataPointer) & 0x0000ffffffffffffL; + + newDataAndCount |= ((__int64)linesUsed) << 48; + + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); + + if (lastDataAndCount2 == lastDataAndCount) { + success = true; + // Queue old data to be deleted + queueForDelete(lastDataPointer); // printf("Marking for delete 0x%x\n", lastDataPointer); #ifdef DATA_COMPRESSION_STATS - count = linesUsed; + count = linesUsed; #endif - } - else - { - // If we didn't succeed, queue data that we made to be deleted, and try again - queueForDelete( dataPointer ); -// printf("Marking for delete (fail) 0x%x\n", dataPointer); - } - } while( !success ); + } else { + // If we didn't succeed, queue data that we made to be deleted, and + // try again + queueForDelete(dataPointer); + // printf("Marking for delete (fail) 0x%x\n", + //dataPointer); + } + } while (!success); } -void SparseDataStorage::getPlaneIndicesAndData(unsigned char **planeIndices, unsigned char **data) -{ - unsigned char *indicesAndData = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - - *planeIndices = indicesAndData; - *data = indicesAndData + 128; +void SparseDataStorage::getPlaneIndicesAndData(unsigned char** planeIndices, + unsigned char** data) { + unsigned char* indicesAndData = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + *planeIndices = indicesAndData; + *data = indicesAndData + 128; } -void SparseDataStorage::queueForDelete(unsigned char *data) -{ - // Add this into a queue for deleting. This shouldn't be actually deleted until tick has been called twice from when - // the data went into the queue. - deleteQueue[deleteQueueIndex].Push( data ); +void SparseDataStorage::queueForDelete(unsigned char* data) { + // Add this into a queue for deleting. This shouldn't be actually deleted + // until tick has been called twice from when the data went into the queue. + deleteQueue[deleteQueueIndex].Push(data); } -void SparseDataStorage::tick() -{ - // We have 3 queues for deleting. Always delete from the next one after where we are writing to, so it should take 2 ticks - // before we ever delete something, from when the request to delete it came in - int freeIndex = ( deleteQueueIndex + 1 ) % 3; +void SparseDataStorage::tick() { + // We have 3 queues for deleting. Always delete from the next one after + // where we are writing to, so it should take 2 ticks before we ever delete + // something, from when the request to delete it came in + int freeIndex = (deleteQueueIndex + 1) % 3; -// printf("Free queue: %d, %d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); - unsigned char *toFree = NULL; - do - { - toFree = deleteQueue[freeIndex].Pop(); + // printf("Free queue: %d, + //%d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); + unsigned char* toFree = NULL; + do { + toFree = deleteQueue[freeIndex].Pop(); // if( toFree ) printf("Deleting 0x%x\n", toFree); - // Determine correct means to free this data - could have been allocated either with XPhysicalAlloc or malloc +// Determine correct means to free this data - could have been allocated either +// with XPhysicalAlloc or malloc #ifdef _XBOX - if( (unsigned int)toFree >= MM_PHYSICAL_4KB_BASE ) - { - XPhysicalFree(toFree); - } - else + if ((unsigned int)toFree >= MM_PHYSICAL_4KB_BASE) { + XPhysicalFree(toFree); + } else #endif - { - free(toFree); - } - } while( toFree ); + { + free(toFree); + } + } while (toFree); - deleteQueueIndex = ( deleteQueueIndex + 1 ) % 3; + deleteQueueIndex = (deleteQueueIndex + 1) % 3; } -// Update storage with a new values for dataAndCount, repeating as necessary if other simultaneous writes happen. -void SparseDataStorage::updateDataAndCount(__int64 newDataAndCount) -{ - // Now actually assign this data to the storage. Just repeat until successful, there isn't any useful really that we can merge the results of this - // with any other simultaneous writes that might be happening. - bool success = false; - do - { - __int64 lastDataAndCount = dataAndCount; - unsigned char *lastDataPointer = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); +// Update storage with a new values for dataAndCount, repeating as necessary if +// other simultaneous writes happen. +void SparseDataStorage::updateDataAndCount(__int64 newDataAndCount) { + // Now actually assign this data to the storage. Just repeat until + // successful, there isn't any useful really that we can merge the results + // of this with any other simultaneous writes that might be happening. + bool success = false; + do { + __int64 lastDataAndCount = dataAndCount; + unsigned char* lastDataPointer = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); - - if( lastDataAndCount2 == lastDataAndCount ) - { - success = true; - // Queue old data to be deleted -// printf("Marking for delete 0x%x (full replace)\n", lastDataPointer); - queueForDelete( lastDataPointer ); - } - } while( !success); + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); + + if (lastDataAndCount2 == lastDataAndCount) { + success = true; + // Queue old data to be deleted + // printf("Marking for delete 0x%x (full + //replace)\n", lastDataPointer); + queueForDelete(lastDataPointer); + } + } while (!success); #ifdef DATA_COMPRESSION_STATS - count = ( newDataAndCount >> 48 ) & 0xffff; + count = (newDataAndCount >> 48) & 0xffff; #endif - } -// Attempt to compress the stored data. This method makes no guarantee of success - if it fails due to something else writing to the storage whilst this is running, then it won't actually do anything. -int SparseDataStorage::compress() -{ - unsigned char _planeIndices[128]; - bool needsCompressed = false; +// Attempt to compress the stored data. This method makes no guarantee of +// success - if it fails due to something else writing to the storage whilst +// this is running, then it won't actually do anything. +int SparseDataStorage::compress() { + unsigned char _planeIndices[128]; + bool needsCompressed = false; - __int64 lastDataAndCount = dataAndCount; + __int64 lastDataAndCount = dataAndCount; - unsigned char *planeIndices = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); - unsigned char *data = planeIndices + 128; + unsigned char* planeIndices = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); + unsigned char* data = planeIndices + 128; - int planesToAlloc = 0; - for( int i = 0; i < 128; i++ ) - { - if( planeIndices[i] == ALL_0_INDEX ) - { - _planeIndices[i] = ALL_0_INDEX; - } - else - { - unsigned char *pucData = &data[ 128 * planeIndices[i] ]; - bool all0 = true; - for( int j = 0; j < 128; j++ ) // 16 x 16 x 4-bits - { - if( *pucData != 0 ) all0 = false; - pucData++; - } - if( all0 ) - { - _planeIndices[i] = ALL_0_INDEX; - needsCompressed = true; - } - else - { - _planeIndices[i] = planesToAlloc++; - } - } - } + int planesToAlloc = 0; + for (int i = 0; i < 128; i++) { + if (planeIndices[i] == ALL_0_INDEX) { + _planeIndices[i] = ALL_0_INDEX; + } else { + unsigned char* pucData = &data[128 * planeIndices[i]]; + bool all0 = true; + for (int j = 0; j < 128; j++) // 16 x 16 x 4-bits + { + if (*pucData != 0) all0 = false; + pucData++; + } + if (all0) { + _planeIndices[i] = ALL_0_INDEX; + needsCompressed = true; + } else { + _planeIndices[i] = planesToAlloc++; + } + } + } - if( needsCompressed ) - { - unsigned char *newIndicesAndData = (unsigned char *)malloc( 128 + 128 * planesToAlloc ); - unsigned char *pucData = newIndicesAndData + 128; - XMemCpy( newIndicesAndData, _planeIndices, 128 ); + if (needsCompressed) { + unsigned char* newIndicesAndData = + (unsigned char*)malloc(128 + 128 * planesToAlloc); + unsigned char* pucData = newIndicesAndData + 128; + XMemCpy(newIndicesAndData, _planeIndices, 128); - for( int i = 0; i < 128; i++ ) - { - if( newIndicesAndData[i] < ALL_0_INDEX ) - { - XMemCpy( pucData, &data[ 128 * planeIndices[i] ], 128 ); - pucData += 128; - } - } + for (int i = 0; i < 128; i++) { + if (newIndicesAndData[i] < ALL_0_INDEX) { + XMemCpy(pucData, &data[128 * planeIndices[i]], 128); + pucData += 128; + } + } - // Get new data and count packed info + // Get new data and count packed info - __int64 newDataAndCount = ((__int64) newIndicesAndData) & 0x0000ffffffffffffL; + __int64 newDataAndCount = + ((__int64)newIndicesAndData) & 0x0000ffffffffffffL; - newDataAndCount |= ((__int64)planesToAlloc) << 48; + newDataAndCount |= ((__int64)planesToAlloc) << 48; - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); - if( lastDataAndCount2 != lastDataAndCount ) - { - // Failed to write. Don't bother trying again... being very conservative here. -// printf("Marking for delete 0x%x (compress fail)\n", newIndicesAndData); - queueForDelete( newIndicesAndData ); - } - else - { - // Success - queueForDelete( planeIndices ); -// printf("Successfully compressed to %d planes, to delete 0x%x\n", planesToAlloc, planeIndices); + if (lastDataAndCount2 != lastDataAndCount) { + // Failed to write. Don't bother trying again... being very + // conservative here. + // printf("Marking for delete 0x%x (compress + //fail)\n", newIndicesAndData); + queueForDelete(newIndicesAndData); + } else { + // Success + queueForDelete(planeIndices); +// printf("Successfully compressed to %d planes, to delete +//0x%x\n", planesToAlloc, planeIndices); #ifdef DATA_COMPRESSION_STATS - count = planesToAlloc; + count = planesToAlloc; #endif - } + } - return planesToAlloc; - } - else - { - return (int)((lastDataAndCount >> 48 ) & 0xffff); - } + return planesToAlloc; + } else { + return (int)((lastDataAndCount >> 48) & 0xffff); + } } - -bool SparseDataStorage::isCompressed() -{ - - int count = ( dataAndCount >> 48 ) & 0xffff; - return (count < 127); - - +bool SparseDataStorage::isCompressed() { + int count = (dataAndCount >> 48) & 0xffff; + return (count < 127); } -void SparseDataStorage::write(DataOutputStream *dos) -{ - int count = ( dataAndCount >> 48 ) & 0xffff; - dos->writeInt(count); - unsigned char *dataPointer = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - byteArray wrapper(dataPointer, count * 128 + 128); - dos->write(wrapper); +void SparseDataStorage::write(DataOutputStream* dos) { + int count = (dataAndCount >> 48) & 0xffff; + dos->writeInt(count); + unsigned char* dataPointer = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + byteArray wrapper(dataPointer, count * 128 + 128); + dos->write(wrapper); } -void SparseDataStorage::read(DataInputStream *dis) -{ - int count = dis->readInt(); - unsigned char *dataPointer = (unsigned char *)malloc(count * 128 + 128); - byteArray wrapper(dataPointer, count * 128 + 128); - dis->readFully(wrapper); +void SparseDataStorage::read(DataInputStream* dis) { + int count = dis->readInt(); + unsigned char* dataPointer = (unsigned char*)malloc(count * 128 + 128); + byteArray wrapper(dataPointer, count * 128 + 128); + dis->readFully(wrapper); + __int64 newDataAndCount = ((__int64)dataPointer) & 0x0000ffffffffffffL; - __int64 newDataAndCount = ((__int64) dataPointer) & 0x0000ffffffffffffL; + newDataAndCount |= ((__int64)count) << 48; - newDataAndCount |= ((__int64)count) << 48; - - updateDataAndCount(newDataAndCount); + updateDataAndCount(newDataAndCount); } diff --git a/Minecraft.World/Level/Storage/SparseDataStorage.h b/Minecraft.World/Level/Storage/SparseDataStorage.h index f6806504c..ec65933f1 100644 --- a/Minecraft.World/Level/Storage/SparseDataStorage.h +++ b/Minecraft.World/Level/Storage/SparseDataStorage.h @@ -1,86 +1,128 @@ #pragma once #ifndef __linux__ #include "../../Platform/x64headers/xmcore.h" -#endif // __linux__ +#endif // __linux__ -// 4J added - Storage for data (ie the extra per tile storage). Data is normally stored as 4-bits per tile, in a DataLayer class of 16384 bytes ( 128 x 16 x 16 x 0.5 ) -// This class provides more economical storage for such data by taking into consideration that it is quite common for large parts of the data to be very compressible (ie zero). -// We are aiming here to balance performance (this data is accessed very frequently) against size. +// 4J added - Storage for data (ie the extra per tile storage). Data is normally +// stored as 4-bits per tile, in a DataLayer class of 16384 bytes ( 128 x 16 x +// 16 x 0.5 ) This class provides more economical storage for such data by +// taking into consideration that it is quite common for large parts of the data +// to be very compressible (ie zero). We are aiming here to balance performance +// (this data is accessed very frequently) against size. // Details of storage method: -// 1. Data is split into horizontal planes, of which there are 128, and each taking up 128 bytes (16 x 16 x 0.5) -// 2. Each of these layers has a permanently allocated index in this class (planeIndices). -// 3. Data for allocatedPlaneCount planes worth of data is allocated in the data array ( allocatedPlaneCount * 128 bytes ) -// 4. If a plane index for a layer is < 128, then the data for that layer is at data[ index * 128 ] +// 1. Data is split into horizontal planes, of which there are 128, and each +// taking up 128 bytes (16 x 16 x 0.5) +// 2. Each of these layers has a permanently allocated index in this class +// (planeIndices). +// 3. Data for allocatedPlaneCount planes worth of data is allocated in the data +// array ( allocatedPlaneCount * 128 bytes ) +// 4. If a plane index for a layer is < 128, then the data for that layer is at +// data[ index * 128 ] // 5. If a plane index for a layer is 128, then all values for that plane are 0 -// This class needs to be thread safe as there are times where chunk data is shared between server & main threads. Data values are queried -// very regularly so this needs to be as light-weight as possible. +// This class needs to be thread safe as there are times where chunk data is +// shared between server & main threads. Data values are queried very regularly +// so this needs to be as light-weight as possible. -// To meet these requirements, this class is now implemented using a lock-free system, implemented using a read-copy-update (RCU) type algorithm. Some details... +// To meet these requirements, this class is now implemented using a lock-free +// system, implemented using a read-copy-update (RCU) type algorithm. Some +// details... -// (1) The storage details for the class are now packed into a single __int64, which contains both a pointer to the data that is required and a count of how many planes worth -// of storage are allocated. This allows the full storage to be updated atomically using compare and exchange operations (implemented with InterlockedCompareExchangeRelease64). -// (2) The data pointer referenced in this __int64 points to an area of memory which is 128 + 128 * plane_count bytes long, where the first 128 bytes stoere the plane indices, and -// the rest of the data is variable in size to accomodate however many planes are required to be stored -// (3) The RCU bit of the algorithm means that any read operations don't need to do any checks or locks at all. When the data needs to be updated, a copy of it is made and updated, -// then an attempt is made to swap the new data in - if this succeeds then the old data pointer is deleted later at some point where we know nothing will be reading from it anymore. -// This is achieved by putting the delete request in a queue which means it won't actually get deleted until 2 game ticks after the last time its reference existed, which should give -// us a large margin of safety. If the attempt to swap the new data in fails, then the whole write operation has to be attempted again - this is the only time there is really a -// high cost for this algorithm and such write collisions should be rare. +// (1) The storage details for the class are now packed into a single __int64, +// which contains both a pointer to the data that is required and a count of how +// many planes worth +// of storage are allocated. This allows the full storage to be updated +// atomically using compare and exchange operations (implemented with +// InterlockedCompareExchangeRelease64). +// (2) The data pointer referenced in this __int64 points to an area of memory +// which is 128 + 128 * plane_count bytes long, where the first 128 bytes stoere +// the plane indices, and +// the rest of the data is variable in size to accomodate however many +// planes are required to be stored +// (3) The RCU bit of the algorithm means that any read operations don't need to +// do any checks or locks at all. When the data needs to be updated, a copy of +// it is made and updated, +// then an attempt is made to swap the new data in - if this succeeds then +// the old data pointer is deleted later at some point where we know nothing +// will be reading from it anymore. This is achieved by putting the delete +// request in a queue which means it won't actually get deleted until 2 game +// ticks after the last time its reference existed, which should give us a +// large margin of safety. If the attempt to swap the new data in fails, +// then the whole write operation has to be attempted again - this is the +// only time there is really a high cost for this algorithm and such write +// collisions should be rare. -//#define DATA_COMPRESSION_STATS +// #define DATA_COMPRESSION_STATS class TileCompressData_SPU; -class SparseDataStorage -{ - friend class TileCompressData_SPU; +class SparseDataStorage { + friend class TileCompressData_SPU; + private: -// unsigned char planeIndices[128]; - __int64 dataAndCount; // Contains packed-together data pointer (lower 48-bits), and count of lines used (upper 16-bits) + // unsigned char planeIndices[128]; + __int64 dataAndCount; // Contains packed-together data pointer (lower + // 48-bits), and count of lines used (upper 16-bits) -// unsigned char *data; -// unsigned int allocatedPlaneCount; + // unsigned char *data; + // unsigned int allocatedPlaneCount; - static const int ALL_0_INDEX = 128; + static const int ALL_0_INDEX = 128; #ifdef _XBOX - static const unsigned int MM_PHYSICAL_4KB_BASE = 0xE0000000; // Start of where 4KB page sized physical allocations are made + static const unsigned int MM_PHYSICAL_4KB_BASE = + 0xE0000000; // Start of where 4KB page sized physical allocations are + // made #endif public: SparseDataStorage(); - SparseDataStorage(bool isUpper); - SparseDataStorage(SparseDataStorage *copyFrom); // ctor with deep copy - ~SparseDataStorage(); + SparseDataStorage(bool isUpper); + SparseDataStorage(SparseDataStorage* copyFrom); // ctor with deep copy + ~SparseDataStorage(); - void setData(byteArray dataIn, unsigned int inOffset); // Set all data values from a data array of length 16384 (128 x 16 x 16 x 0.5). - void getData(byteArray retArray, unsigned int retOffset); // Gets all data values into an array of length 16384. - int get(int x, int y, int z); // Get an individual data value - void set(int x, int y, int z, int val); // Set an individual data value - typedef void (*tileUpdatedCallback)(int x, int y , int z, void *param, int yparam); - int setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset, tileUpdatedCallback callback, void *param, int yparam); // Sets a region of data values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer - int getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset); // Updates the data at offset position dataInOut with a region of data information - external ordering compatible with java DataLayer + void setData( + byteArray dataIn, + unsigned int inOffset); // Set all data values from a data array of + // length 16384 (128 x 16 x 16 x 0.5). + void getData(byteArray retArray, + unsigned int retOffset); // Gets all data values into an array + // of length 16384. + int get(int x, int y, int z); // Get an individual data value + void set(int x, int y, int z, int val); // Set an individual data value + typedef void (*tileUpdatedCallback)(int x, int y, int z, void* param, + int yparam); + int setDataRegion( + byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, + int offset, tileUpdatedCallback callback, void* param, + int yparam); // Sets a region of data values with the data at offset + // position in the array dataIn - external ordering + // compatible with java DataLayer + int getDataRegion( + byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, + int offset); // Updates the data at offset position dataInOut with a + // region of data information - external ordering + // compatible with java DataLayer - static void staticCtor(); + static void staticCtor(); - void addNewPlane(int y); - void getPlaneIndicesAndData(unsigned char **planeIndices, unsigned char **data); - void updateDataAndCount(__int64 newDataAndCount); - int compress(); + void addNewPlane(int y); + void getPlaneIndicesAndData(unsigned char** planeIndices, + unsigned char** data); + void updateDataAndCount(__int64 newDataAndCount); + int compress(); - bool isCompressed(); - void queueForDelete(unsigned char *data); + bool isCompressed(); + void queueForDelete(unsigned char* data); - static void tick(); - static int deleteQueueIndex; - static XLockFreeStack deleteQueue[3]; + static void tick(); + static int deleteQueueIndex; + static XLockFreeStack deleteQueue[3]; #ifdef DATA_COMPRESSION_STATS - int count; + int count; #endif - void write(DataOutputStream *dos); - void read(DataInputStream *dis); + void write(DataOutputStream* dos); + void read(DataInputStream* dis); }; - diff --git a/Minecraft.World/Level/Storage/SparseLightStorage.cpp b/Minecraft.World/Level/Storage/SparseLightStorage.cpp index faf245515..90edb4473 100644 --- a/Minecraft.World/Level/Storage/SparseLightStorage.cpp +++ b/Minecraft.World/Level/Storage/SparseLightStorage.cpp @@ -4,639 +4,638 @@ // Note: See header for an overview of this class int SparseLightStorage::deleteQueueIndex; -XLockFreeStack SparseLightStorage::deleteQueue[3]; +XLockFreeStack SparseLightStorage::deleteQueue[3]; -void SparseLightStorage::staticCtor() -{ - for( int i = 0; i < 3; i++ ) - { - deleteQueue[i].Initialize(); - } +void SparseLightStorage::staticCtor() { + for (int i = 0; i < 3; i++) { + deleteQueue[i].Initialize(); + } } -// Initialise lighting storage, with very limited compression - the very first plane is stored as either compressed to be "all 15" or "all 0" depending on whether this -// will store sky or not, and the rest of the planes aren't compressed at all. The reason behind this is to keep the total allocation as a round number of 4K (small) pages, ie 16K. -// By doing this, and doing this "special" allocation as a XPhysicalAlloc rather than a malloc, we can help ensure that this full allocation gets cleaned up properly when the first -// proper compression is done on this storage. If it were just allocated with malloc, then the memory management system would have a large number of 16512 allocations to free, and -// it seems from experimentation that these basically don't make it back to the system as free pages. -// Note - the other approach here would be to allocate *no* actual storage for the lights at the ctor stage. However, as chunks are created then this creates an awful lot of intermediate -// stages as each line of lighting is added, so it is actually much cleaner to just allocate almost fully here & then attempt to do a single compression pass over the data later on. -SparseLightStorage::SparseLightStorage(bool sky) -{ - // Allocate using physical alloc. As this will (by default) return memory from the pool of 4KB pages, the address will in the range of MM_PHYSICAL_4KB_BASE upwards. We can use - // this fact to identify the allocation later, and so free it with the corresponding call to XPhysicalFree. +// Initialise lighting storage, with very limited compression - the very first +// plane is stored as either compressed to be "all 15" or "all 0" depending on +// whether this will store sky or not, and the rest of the planes aren't +// compressed at all. The reason behind this is to keep the total allocation as +// a round number of 4K (small) pages, ie 16K. By doing this, and doing this +// "special" allocation as a XPhysicalAlloc rather than a malloc, we can help +// ensure that this full allocation gets cleaned up properly when the first +// proper compression is done on this storage. If it were just allocated with +// malloc, then the memory management system would have a large number of 16512 +// allocations to free, and it seems from experimentation that these basically +// don't make it back to the system as free pages. Note - the other approach +// here would be to allocate *no* actual storage for the lights at the ctor +// stage. However, as chunks are created then this creates an awful lot of +// intermediate stages as each line of lighting is added, so it is actually much +// cleaner to just allocate almost fully here & then attempt to do a single +// compression pass over the data later on. +SparseLightStorage::SparseLightStorage(bool sky) { + // Allocate using physical alloc. As this will (by default) return memory + // from the pool of 4KB pages, the address will in the range of + // MM_PHYSICAL_4KB_BASE upwards. We can use this fact to identify the + // allocation later, and so free it with the corresponding call to + // XPhysicalFree. #ifdef _XBOX - unsigned char *planeIndices = (unsigned char *)XPhysicalAlloc(128 * 128, MAXULONG_PTR, 4096, PAGE_READWRITE); + unsigned char* planeIndices = (unsigned char*)XPhysicalAlloc( + 128 * 128, MAXULONG_PTR, 4096, PAGE_READWRITE); #else - unsigned char *planeIndices = (unsigned char *)malloc(128 * 128); + unsigned char* planeIndices = (unsigned char*)malloc(128 * 128); #endif - unsigned char *data = planeIndices + 128; - planeIndices[127] = sky ? ALL_15_INDEX : ALL_0_INDEX; - for( int i = 0; i < 127; i++ ) - { - planeIndices[i] = i; - } - XMemSet(data, 0, 128 * 127); + unsigned char* data = planeIndices + 128; + planeIndices[127] = sky ? ALL_15_INDEX : ALL_0_INDEX; + for (int i = 0; i < 127; i++) { + planeIndices[i] = i; + } + XMemSet(data, 0, 128 * 127); - // Data and count packs together the pointer to our data and the count of planes allocated - 127 planes allocated in this case + // Data and count packs together the pointer to our data and the count of + // planes allocated - 127 planes allocated in this case - dataAndCount = 0x007F000000000000L | (( (__int64) planeIndices ) & 0x0000ffffffffffffL); + dataAndCount = + 0x007F000000000000L | (((__int64)planeIndices) & 0x0000ffffffffffffL); #ifdef LIGHT_COMPRESSION_STATS - count = 127; + count = 127; #endif } -SparseLightStorage::SparseLightStorage(bool sky, bool isUpper) -{ - // Allocate using physical alloc. As this will (by default) return memory from the pool of 4KB pages, the address will in the range of MM_PHYSICAL_4KB_BASE upwards. We can use - // this fact to identify the allocation later, and so free it with the corresponding call to XPhysicalFree. - unsigned char *planeIndices = (unsigned char *)malloc(128); - for( int i = 0; i < 128; i++ ) - { - planeIndices[i] = sky ? ALL_15_INDEX : ALL_0_INDEX; - } +SparseLightStorage::SparseLightStorage(bool sky, bool isUpper) { + // Allocate using physical alloc. As this will (by default) return memory + // from the pool of 4KB pages, the address will in the range of + // MM_PHYSICAL_4KB_BASE upwards. We can use this fact to identify the + // allocation later, and so free it with the corresponding call to + // XPhysicalFree. + unsigned char* planeIndices = (unsigned char*)malloc(128); + for (int i = 0; i < 128; i++) { + planeIndices[i] = sky ? ALL_15_INDEX : ALL_0_INDEX; + } - // Data and count packs together the pointer to our data and the count of planes allocated - 0 planes allocated in this case + // Data and count packs together the pointer to our data and the count of + // planes allocated - 0 planes allocated in this case - dataAndCount = 0x0000000000000000L | (( (__int64) planeIndices ) & 0x0000ffffffffffffL); + dataAndCount = + 0x0000000000000000L | (((__int64)planeIndices) & 0x0000ffffffffffffL); #ifdef LIGHT_COMPRESSION_STATS - count = 0; + count = 0; #endif } -SparseLightStorage::~SparseLightStorage() -{ - unsigned char *indicesAndData = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - // Determine correct means to free this data - could have been allocated either with XPhysicalAlloc or malloc - +SparseLightStorage::~SparseLightStorage() { + unsigned char* indicesAndData = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + // Determine correct means to free this data - could have been allocated + // either with XPhysicalAlloc or malloc + #ifdef _XBOX - if( (unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE ) - { - XPhysicalFree(indicesAndData); - } - else + if ((unsigned int)indicesAndData >= MM_PHYSICAL_4KB_BASE) { + XPhysicalFree(indicesAndData); + } else #endif - { - free(indicesAndData); - } -// printf("Free (in dtor) 0x%x\n", indicesAndData); + { + free(indicesAndData); + } + // printf("Free (in dtor) 0x%x\n", indicesAndData); } -SparseLightStorage::SparseLightStorage(SparseLightStorage *copyFrom) -{ - // Extra details of source storage - __int64 sourceDataAndCount = copyFrom->dataAndCount; - unsigned char *sourceIndicesAndData = (unsigned char *)(sourceDataAndCount & 0x0000ffffffffffff); - int sourceCount = (sourceDataAndCount >> 48 ) & 0xffff; +SparseLightStorage::SparseLightStorage(SparseLightStorage* copyFrom) { + // Extra details of source storage + __int64 sourceDataAndCount = copyFrom->dataAndCount; + unsigned char* sourceIndicesAndData = + (unsigned char*)(sourceDataAndCount & 0x0000ffffffffffff); + int sourceCount = (sourceDataAndCount >> 48) & 0xffff; - // Allocate & copy indices ( 128 bytes ) and any allocated planes (128 * count) - unsigned char *destIndicesAndData = (unsigned char *)malloc( sourceCount * 128 + 128 ); + // Allocate & copy indices ( 128 bytes ) and any allocated planes (128 * + // count) + unsigned char* destIndicesAndData = + (unsigned char*)malloc(sourceCount * 128 + 128); - // AP - I've moved this to be before the memcpy because of a very strange bug on vita. Sometimes dataAndCount wasn't valid in time when ::get was called. - // This should never happen and this isn't a proper solution but fixes it for now. + // AP - I've moved this to be before the memcpy because of a very strange + // bug on vita. Sometimes dataAndCount wasn't valid in time when ::get was + // called. This should never happen and this isn't a proper solution but + // fixes it for now. - dataAndCount = ( sourceDataAndCount & 0xffff000000000000L ) | ( ((__int64) destIndicesAndData ) & 0x0000ffffffffffffL ); + dataAndCount = (sourceDataAndCount & 0xffff000000000000L) | + (((__int64)destIndicesAndData) & 0x0000ffffffffffffL); - - XMemCpy( destIndicesAndData, sourceIndicesAndData, sourceCount * 128 + 128 ); + XMemCpy(destIndicesAndData, sourceIndicesAndData, sourceCount * 128 + 128); #ifdef LIGHT_COMPRESSION_STATS - count = sourceCount; + count = sourceCount; #endif } -// Set all lighting values from a data array of length 16384 (128 x 16 x 16 x 0.5). Source data must have same order as original java game -void SparseLightStorage::setData(byteArray dataIn, unsigned int inOffset) -{ - // Original order is defined as: - // pos = (x << 11 | z << 7 | y); - // slot = pos >> 1; - // part = pos & 1; - // if ( part == 0 ) value = data[slot] & 0xf - // else value = (data[slot] >> 4) & 0xf +// Set all lighting values from a data array of length 16384 (128 x 16 x 16 x +// 0.5). Source data must have same order as original java game +void SparseLightStorage::setData(byteArray dataIn, unsigned int inOffset) { + // Original order is defined as: + // pos = (x << 11 | z << 7 | y); + // slot = pos >> 1; + // part = pos & 1; + // if ( part == 0 ) value = data[slot] & 0xf + // else value = (data[slot] >> 4) & 0xf - // Two passed through the data. First pass sets up plane indices, and counts number of planes that we actually need to allocate - int allocatedPlaneCount = 0; - unsigned char _planeIndices[128]; + // Two passed through the data. First pass sets up plane indices, and counts + // number of planes that we actually need to allocate + int allocatedPlaneCount = 0; + unsigned char _planeIndices[128]; - for( int y = 0; y < 128; y++ ) - { - bool all0 = true; - bool all15 = true; - - for( int xz = 0; xz < 256; xz++ ) // 256 in loop as 16 x 16 separate bytes need checked - { - int pos = ( xz << 7 ) | y; - int slot = pos >> 1; - int part = pos & 1; - unsigned char value = ( dataIn[slot + inOffset] >> (part * 4) ) & 15; - if( value != 0 ) all0 = false; - if( value != 15 ) all15 = false; - } - if( all0 ) - { - _planeIndices[y] = ALL_0_INDEX; - } - else if( all15 ) - { - _planeIndices[y] = ALL_15_INDEX; - } - else - { - _planeIndices[y] = allocatedPlaneCount++; - } - } + for (int y = 0; y < 128; y++) { + bool all0 = true; + bool all15 = true; - // Allocate required storage - unsigned char *planeIndices = (unsigned char *)malloc(128 * allocatedPlaneCount + 128); - unsigned char *data = planeIndices + 128; - XMemCpy(planeIndices, _planeIndices, 128); + for (int xz = 0; xz < 256; + xz++) // 256 in loop as 16 x 16 separate bytes need checked + { + int pos = (xz << 7) | y; + int slot = pos >> 1; + int part = pos & 1; + unsigned char value = (dataIn[slot + inOffset] >> (part * 4)) & 15; + if (value != 0) all0 = false; + if (value != 15) all15 = false; + } + if (all0) { + _planeIndices[y] = ALL_0_INDEX; + } else if (all15) { + _planeIndices[y] = ALL_15_INDEX; + } else { + _planeIndices[y] = allocatedPlaneCount++; + } + } - // Second pass through to actually copy the data in to the storage allocated for the required planes - unsigned char *pucOut = data; - for( int y = 0; y < 128 ; y++ ) - { - // Index will be < 128 if we allocated storage for it and it has a valid index. No need to actually check the index as - // we know they were sequentially allocated above. - if( planeIndices[y] < 128 ) - { - int part = y & 1; - //int shift = 4 * part; - unsigned char *pucIn = &dataIn[ (y >> 1) + inOffset]; + // Allocate required storage + unsigned char* planeIndices = + (unsigned char*)malloc(128 * allocatedPlaneCount + 128); + unsigned char* data = planeIndices + 128; + XMemCpy(planeIndices, _planeIndices, 128); - for( int xz = 0; xz < 128; xz++ ) // 128 ( 16 x 16 x 0.5 ) in loop as packing 2 values into each destination byte - { - *pucOut = ( ( *pucIn ) >> ( part * 4 ) ) & 15; - pucIn += 64; + // Second pass through to actually copy the data in to the storage allocated + // for the required planes + unsigned char* pucOut = data; + for (int y = 0; y < 128; y++) { + // Index will be < 128 if we allocated storage for it and it has a valid + // index. No need to actually check the index as we know they were + // sequentially allocated above. + if (planeIndices[y] < 128) { + int part = y & 1; + // int shift = 4 * part; + unsigned char* pucIn = &dataIn[(y >> 1) + inOffset]; - *pucOut |= ( ( ( *pucIn ) >> ( part * 4 ) ) & 15 ) << 4; - pucIn += 64; - pucOut++; - } - } - } + for (int xz = 0; xz < 128; + xz++) // 128 ( 16 x 16 x 0.5 ) in loop as packing 2 values + // into each destination byte + { + *pucOut = ((*pucIn) >> (part * 4)) & 15; + pucIn += 64; - // Get new data and count packed info + *pucOut |= (((*pucIn) >> (part * 4)) & 15) << 4; + pucIn += 64; + pucOut++; + } + } + } - __int64 newDataAndCount = ((__int64) planeIndices) & 0x0000ffffffffffffL; + // Get new data and count packed info - newDataAndCount |= ((__int64)allocatedPlaneCount) << 48; + __int64 newDataAndCount = ((__int64)planeIndices) & 0x0000ffffffffffffL; - updateDataAndCount( newDataAndCount ); + newDataAndCount |= ((__int64)allocatedPlaneCount) << 48; + + updateDataAndCount(newDataAndCount); } -// Gets all lighting values into an array of length 16384. Destination data will have same order as original java game. -void SparseLightStorage::getData(byteArray retArray, unsigned int retOffset) -{ - XMemSet(retArray.data + retOffset, 0, 16384); - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); +// Gets all lighting values into an array of length 16384. Destination data will +// have same order as original java game. +void SparseLightStorage::getData(byteArray retArray, unsigned int retOffset) { + XMemSet(retArray.data + retOffset, 0, 16384); + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - // Original order is defined as: - // pos = (x << 11 | z << 7 | y); - // slot = pos >> 1; - // part = pos & 1; - // if ( part == 0 ) value = data[slot] & 0xf - // else value = (data[slot] >> 4) & 0xf + // Original order is defined as: + // pos = (x << 11 | z << 7 | y); + // slot = pos >> 1; + // part = pos & 1; + // if ( part == 0 ) value = data[slot] & 0xf + // else value = (data[slot] >> 4) & 0xf - for( int y = 0; y < 128; y++ ) - { - if( planeIndices[y] == ALL_0_INDEX ) - { - // No need to do anything in this case as retArray is initialised to zero - } - else if( planeIndices[y] == ALL_15_INDEX ) - { - int part = y & 1; - unsigned char value = 15 << ( part * 4 ); - unsigned char *pucOut = &retArray.data[ (y >> 1) + retOffset]; - for( int xz = 0; xz < 256; xz++ ) - { - *pucOut |= value; - pucOut += 64; - } - } - else - { - int part = y & 1; - int shift = 4 * part; - unsigned char *pucOut = &retArray.data[ (y >> 1) + retOffset]; - unsigned char *pucIn = &data[ planeIndices[ y ] * 128 ]; - for( int xz = 0; xz < 128; xz++ ) // 128 in loop (16 x 16 x 0.5) as input data is being treated in pairs of nybbles that are packed in the same byte - { - unsigned char value = (*pucIn) & 15; - *pucOut |= ( value << shift ); - pucOut += 64; + for (int y = 0; y < 128; y++) { + if (planeIndices[y] == ALL_0_INDEX) { + // No need to do anything in this case as retArray is initialised to + // zero + } else if (planeIndices[y] == ALL_15_INDEX) { + int part = y & 1; + unsigned char value = 15 << (part * 4); + unsigned char* pucOut = &retArray.data[(y >> 1) + retOffset]; + for (int xz = 0; xz < 256; xz++) { + *pucOut |= value; + pucOut += 64; + } + } else { + int part = y & 1; + int shift = 4 * part; + unsigned char* pucOut = &retArray.data[(y >> 1) + retOffset]; + unsigned char* pucIn = &data[planeIndices[y] * 128]; + for (int xz = 0; xz < 128; + xz++) // 128 in loop (16 x 16 x 0.5) as input data is being + // treated in pairs of nybbles that are packed in the + // same byte + { + unsigned char value = (*pucIn) & 15; + *pucOut |= (value << shift); + pucOut += 64; - value = ((*pucIn) >> 4 ) & 15; - *pucOut |= ( value << shift ); - pucOut += 64; + value = ((*pucIn) >> 4) & 15; + *pucOut |= (value << shift); + pucOut += 64; - pucIn++; - } - } - } + pucIn++; + } + } + } } // Get an individual lighting value -int SparseLightStorage::get(int x, int y, int z) -{ - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); - - if( planeIndices[y] == ALL_0_INDEX ) - { - return 0; - } - else if ( planeIndices[y] == ALL_15_INDEX ) - { - return 15; - } - else - { - int planeIndex = x * 16 + z; // Index within this xz plane - int byteIndex = planeIndex / 2; // Byte index within the plane (2 tiles stored per byte) - int shift = ( planeIndex & 1 ) * 4; // Bit shift within the byte - int retval = ( data[ planeIndices[y] * 128 + byteIndex ] >> shift ) & 15; +int SparseLightStorage::get(int x, int y, int z) { + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - return retval; - } + if (planeIndices[y] == ALL_0_INDEX) { + return 0; + } else if (planeIndices[y] == ALL_15_INDEX) { + return 15; + } else { + int planeIndex = x * 16 + z; // Index within this xz plane + int byteIndex = + planeIndex / + 2; // Byte index within the plane (2 tiles stored per byte) + int shift = (planeIndex & 1) * 4; // Bit shift within the byte + int retval = (data[planeIndices[y] * 128 + byteIndex] >> shift) & 15; + + return retval; + } } // Set an individual lighting value -void SparseLightStorage::set(int x, int y, int z, int val) -{ - unsigned char *planeIndices, *data; - getPlaneIndicesAndData(&planeIndices, &data); +void SparseLightStorage::set(int x, int y, int z, int val) { + unsigned char *planeIndices, *data; + getPlaneIndicesAndData(&planeIndices, &data); - // If this plane isn't yet allocated, then we might have some extra work to do - if( planeIndices[y] >= ALL_0_INDEX ) - { - // No data allocated. Early out though if we are storing what is already represented by our special index. - if( ( val == 0 ) && ( planeIndices[y] == ALL_0_INDEX ) ) - { - return; - } - if( ( val == 15 ) && ( planeIndices[y] == ALL_15_INDEX ) ) - { - return; - } + // If this plane isn't yet allocated, then we might have some extra work to + // do + if (planeIndices[y] >= ALL_0_INDEX) { + // No data allocated. Early out though if we are storing what is already + // represented by our special index. + if ((val == 0) && (planeIndices[y] == ALL_0_INDEX)) { + return; + } + if ((val == 15) && (planeIndices[y] == ALL_15_INDEX)) { + return; + } - // Reallocate the storage for planes to accomodate one extra - addNewPlane(y); + // Reallocate the storage for planes to accomodate one extra + addNewPlane(y); - // Get pointers again as these may have moved - getPlaneIndicesAndData(&planeIndices, &data); - } + // Get pointers again as these may have moved + getPlaneIndicesAndData(&planeIndices, &data); + } - // Either data was already allocated, or we've just done that. Now store our value into the right place. + // Either data was already allocated, or we've just done that. Now store our + // value into the right place. - int planeIndex = x * 16 + z; // Index within this xz plane - int byteIndex = planeIndex / 2; // Byte index within the plane (2 tiles stored per byte) - int shift = ( planeIndex & 1 ) * 4; // Bit shift within the byte - int mask = 0xf0 >> shift; - - int idx = planeIndices[y] * 128 + byteIndex; - data[idx] = ( data[idx] & mask ) | ( val << shift ); + int planeIndex = x * 16 + z; // Index within this xz plane + int byteIndex = planeIndex / + 2; // Byte index within the plane (2 tiles stored per byte) + int shift = (planeIndex & 1) * 4; // Bit shift within the byte + int mask = 0xf0 >> shift; + int idx = planeIndices[y] * 128 + byteIndex; + data[idx] = (data[idx] & mask) | (val << shift); } -void SparseLightStorage::setAllBright() -{ - unsigned char *planeIndices = (unsigned char *)malloc(128); - for( int i = 0; i < 128; i++ ) - { - planeIndices[i] = ALL_15_INDEX; - } - // Data and count packs together the pointer to our data and the count of planes allocated, which is currently zero +void SparseLightStorage::setAllBright() { + unsigned char* planeIndices = (unsigned char*)malloc(128); + for (int i = 0; i < 128; i++) { + planeIndices[i] = ALL_15_INDEX; + } + // Data and count packs together the pointer to our data and the count of + // planes allocated, which is currently zero - __int64 newDataAndCount = ( (__int64) planeIndices ) & 0x0000ffffffffffffL; + __int64 newDataAndCount = ((__int64)planeIndices) & 0x0000ffffffffffffL; - - updateDataAndCount( newDataAndCount ); + updateDataAndCount(newDataAndCount); } -// Sets a region of lighting values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer -// Note - when data was extracted from the original data layers by LevelChunk::getBlocksAndData, y0 had to have even alignment and y1 - y0 also -// needed to be even as data was packed in nyblles in this dimension, and the code didn't make any attempt to unpack it. This behaviour is copied -// here for compatibility even though our source data isn't packed this way. -// Returns size of data copied. -int SparseLightStorage::setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset) -{ - // Actual setting of data happens when calling set method so no need to lock here - unsigned char *pucIn = &dataIn.data[offset]; - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - // Emulate how data was extracted from DataLayer... see comment above - int yy0 = y0 & 0xfffffffe; - int len = ( y1 - y0 ) / 2; - for( int i = 0; i < len; i++ ) - { - int y = yy0 + ( i * 2 ); +// Sets a region of lighting values with the data at offset position in the +// array dataIn - external ordering compatible with java DataLayer Note - when +// data was extracted from the original data layers by +// LevelChunk::getBlocksAndData, y0 had to have even alignment and y1 - y0 also +// needed to be even as data was packed in nyblles in this dimension, and the +// code didn't make any attempt to unpack it. This behaviour is copied here for +// compatibility even though our source data isn't packed this way. Returns size +// of data copied. +int SparseLightStorage::setDataRegion(byteArray dataIn, int x0, int y0, int z0, + int x1, int y1, int z1, int offset) { + // Actual setting of data happens when calling set method so no need to lock + // here + unsigned char* pucIn = &dataIn.data[offset]; + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + // Emulate how data was extracted from DataLayer... see comment + // above + int yy0 = y0 & 0xfffffffe; + int len = (y1 - y0) / 2; + for (int i = 0; i < len; i++) { + int y = yy0 + (i * 2); - set(x, y, z, (*pucIn) & 15 ); - set(x, y + 1, z, ((*pucIn) >> 4 ) & 15 ); - pucIn++; - } - } - } - ptrdiff_t count = pucIn - &dataIn.data[offset]; + set(x, y, z, (*pucIn) & 15); + set(x, y + 1, z, ((*pucIn) >> 4) & 15); + pucIn++; + } + } + } + ptrdiff_t count = pucIn - &dataIn.data[offset]; - return (int)count; + return (int)count; } -// Updates the data at offset position dataInOut with a region of lighting information - external ordering compatible with java DataLayer -// Note - when data was placed in the original data layers by LevelChunk::setBlocksAndData, y0 had to have even alignment and y1 - y0 also -// needed to be even as data was packed in nyblles in this dimension, and the code didn't make any attempt to unpack it. This behaviour is copied -// here for compatibility even though our source data isn't packed this way -// Returns size of data copied. -int SparseLightStorage::getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset) -{ - unsigned char *pucOut = &dataInOut.data[offset]; - for( int x = x0; x < x1; x++ ) - { - for( int z = z0; z < z1; z++ ) - { - // Emulate how data was extracted from DataLayer... see comment above - int yy0 = y0 & 0xfffffffe; - int len = ( y1 - y0 ) / 2; - for( int i = 0; i < len; i++ ) - { - int y = yy0 + ( i * 2 ); +// Updates the data at offset position dataInOut with a region of lighting +// information - external ordering compatible with java DataLayer Note - when +// data was placed in the original data layers by LevelChunk::setBlocksAndData, +// y0 had to have even alignment and y1 - y0 also needed to be even as data was +// packed in nyblles in this dimension, and the code didn't make any attempt to +// unpack it. This behaviour is copied here for compatibility even though our +// source data isn't packed this way Returns size of data copied. +int SparseLightStorage::getDataRegion(byteArray dataInOut, int x0, int y0, + int z0, int x1, int y1, int z1, + int offset) { + unsigned char* pucOut = &dataInOut.data[offset]; + for (int x = x0; x < x1; x++) { + for (int z = z0; z < z1; z++) { + // Emulate how data was extracted from DataLayer... see comment + // above + int yy0 = y0 & 0xfffffffe; + int len = (y1 - y0) / 2; + for (int i = 0; i < len; i++) { + int y = yy0 + (i * 2); - *pucOut = get( x, y, z); - *pucOut |= get( x, y + 1, z) << 4; - pucOut++; - } - } - } - ptrdiff_t count = pucOut - &dataInOut.data[offset]; - - return (int)count; + *pucOut = get(x, y, z); + *pucOut |= get(x, y + 1, z) << 4; + pucOut++; + } + } + } + ptrdiff_t count = pucOut - &dataInOut.data[offset]; + + return (int)count; } -void SparseLightStorage::addNewPlane(int y) -{ - bool success = false; - do - { - // Get last packed data pointer & count - __int64 lastDataAndCount = dataAndCount; +void SparseLightStorage::addNewPlane(int y) { + bool success = false; + do { + // Get last packed data pointer & count + __int64 lastDataAndCount = dataAndCount; - // Unpack count & data pointer - int lastLinesUsed = (int)(( lastDataAndCount >> 48 ) & 0xffff); - unsigned char *lastDataPointer = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); + // Unpack count & data pointer + int lastLinesUsed = (int)((lastDataAndCount >> 48) & 0xffff); + unsigned char* lastDataPointer = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); - // Find out what to prefill the newly allocated line with - unsigned char planeIndex = lastDataPointer[y]; - int prefill = 0; - if( planeIndex < ALL_0_INDEX ) return; // Something has already allocated this line - we're done - else if( planeIndex == ALL_15_INDEX ) prefill = 255; + // Find out what to prefill the newly allocated line with + unsigned char planeIndex = lastDataPointer[y]; + int prefill = 0; + if (planeIndex < ALL_0_INDEX) + return; // Something has already allocated this line - we're done + else if (planeIndex == ALL_15_INDEX) + prefill = 255; - int linesUsed = lastLinesUsed + 1; + int linesUsed = lastLinesUsed + 1; - // Allocate new memory storage, copy over anything from old storage, and initialise remainder - unsigned char *dataPointer = (unsigned char *)malloc(linesUsed * 128 + 128); - XMemCpy( dataPointer, lastDataPointer, 128 * lastLinesUsed + 128); - XMemSet( dataPointer + ( 128 * lastLinesUsed ) + 128, prefill, 128 ); - dataPointer[y] = lastLinesUsed; + // Allocate new memory storage, copy over anything from old storage, and + // initialise remainder + unsigned char* dataPointer = + (unsigned char*)malloc(linesUsed * 128 + 128); + XMemCpy(dataPointer, lastDataPointer, 128 * lastLinesUsed + 128); + XMemSet(dataPointer + (128 * lastLinesUsed) + 128, prefill, 128); + dataPointer[y] = lastLinesUsed; - // Get new data and count packed info + // Get new data and count packed info - __int64 newDataAndCount = ((__int64) dataPointer) & 0x0000ffffffffffffL; + __int64 newDataAndCount = ((__int64)dataPointer) & 0x0000ffffffffffffL; - newDataAndCount |= ((__int64)linesUsed) << 48; + newDataAndCount |= ((__int64)linesUsed) << 48; - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); - - if( lastDataAndCount2 == lastDataAndCount ) - { - success = true; - // Queue old data to be deleted - queueForDelete( lastDataPointer ); + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); + + if (lastDataAndCount2 == lastDataAndCount) { + success = true; + // Queue old data to be deleted + queueForDelete(lastDataPointer); // printf("Marking for delete 0x%x\n", lastDataPointer); #ifdef LIGHT_COMPRESSION_STATS - count = linesUsed; + count = linesUsed; #endif - } - else - { - // If we didn't succeed, queue data that we made to be deleted, and try again - queueForDelete( dataPointer ); -// printf("Marking for delete (fail) 0x%x\n", dataPointer); - } - } while( !success ); + } else { + // If we didn't succeed, queue data that we made to be deleted, and + // try again + queueForDelete(dataPointer); + // printf("Marking for delete (fail) 0x%x\n", + //dataPointer); + } + } while (!success); } -void SparseLightStorage::getPlaneIndicesAndData(unsigned char **planeIndices, unsigned char **data) -{ - unsigned char *indicesAndData = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - - *planeIndices = indicesAndData; - *data = indicesAndData + 128; +void SparseLightStorage::getPlaneIndicesAndData(unsigned char** planeIndices, + unsigned char** data) { + unsigned char* indicesAndData = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + *planeIndices = indicesAndData; + *data = indicesAndData + 128; } -void SparseLightStorage::queueForDelete(unsigned char *data) -{ - // Add this into a queue for deleting. This shouldn't be actually deleted until tick has been called twice from when - // the data went into the queue. - deleteQueue[deleteQueueIndex].Push( data ); +void SparseLightStorage::queueForDelete(unsigned char* data) { + // Add this into a queue for deleting. This shouldn't be actually deleted + // until tick has been called twice from when the data went into the queue. + deleteQueue[deleteQueueIndex].Push(data); } -void SparseLightStorage::tick() -{ - // We have 3 queues for deleting. Always delete from the next one after where we are writing to, so it should take 2 ticks - // before we ever delete something, from when the request to delete it came in - int freeIndex = ( deleteQueueIndex + 1 ) % 3; +void SparseLightStorage::tick() { + // We have 3 queues for deleting. Always delete from the next one after + // where we are writing to, so it should take 2 ticks before we ever delete + // something, from when the request to delete it came in + int freeIndex = (deleteQueueIndex + 1) % 3; -// printf("Free queue: %d, %d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); - unsigned char *toFree = NULL; - do - { - toFree = deleteQueue[freeIndex].Pop(); + // printf("Free queue: %d, + //%d\n",deleteQueue[freeIndex].GetEntryCount(),deleteQueue[freeIndex].GetAllocated()); + unsigned char* toFree = NULL; + do { + toFree = deleteQueue[freeIndex].Pop(); // if( toFree ) printf("Deleting 0x%x\n", toFree); - // Determine correct means to free this data - could have been allocated either with XPhysicalAlloc or malloc +// Determine correct means to free this data - could have been allocated either +// with XPhysicalAlloc or malloc #ifdef _XBOX - if( (unsigned int)toFree >= MM_PHYSICAL_4KB_BASE ) - { - XPhysicalFree(toFree); - } - else + if ((unsigned int)toFree >= MM_PHYSICAL_4KB_BASE) { + XPhysicalFree(toFree); + } else #endif - { - free(toFree); - } - } while( toFree ); + { + free(toFree); + } + } while (toFree); - deleteQueueIndex = ( deleteQueueIndex + 1 ) % 3; + deleteQueueIndex = (deleteQueueIndex + 1) % 3; } -// Update storage with a new values for dataAndCount, repeating as necessary if other simultaneous writes happen. -void SparseLightStorage::updateDataAndCount(__int64 newDataAndCount) -{ - // Now actually assign this data to the storage. Just repeat until successful, there isn't any useful really that we can merge the results of this - // with any other simultaneous writes that might be happening. - bool success = false; - do - { - __int64 lastDataAndCount = dataAndCount; - unsigned char *lastDataPointer = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); +// Update storage with a new values for dataAndCount, repeating as necessary if +// other simultaneous writes happen. +void SparseLightStorage::updateDataAndCount(__int64 newDataAndCount) { + // Now actually assign this data to the storage. Just repeat until + // successful, there isn't any useful really that we can merge the results + // of this with any other simultaneous writes that might be happening. + bool success = false; + do { + __int64 lastDataAndCount = dataAndCount; + unsigned char* lastDataPointer = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); - - if( lastDataAndCount2 == lastDataAndCount ) - { - success = true; - // Queue old data to be deleted -// printf("Marking for delete 0x%x (full replace)\n", lastDataPointer); - queueForDelete( lastDataPointer ); - } - } while( !success); + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); + + if (lastDataAndCount2 == lastDataAndCount) { + success = true; + // Queue old data to be deleted + // printf("Marking for delete 0x%x (full + //replace)\n", lastDataPointer); + queueForDelete(lastDataPointer); + } + } while (!success); #ifdef LIGHT_COMPRESSION_STATS - count = ( newDataAndCount >> 48 ) & 0xffff; + count = (newDataAndCount >> 48) & 0xffff; #endif - } -// Attempt to compress the stored data. This method makes no guarantee of success - if it fails due to something else writing to the storage whilst this is running, then it won't actually do anything. -int SparseLightStorage::compress() -{ - unsigned char _planeIndices[128]; - bool needsCompressed = false; +// Attempt to compress the stored data. This method makes no guarantee of +// success - if it fails due to something else writing to the storage whilst +// this is running, then it won't actually do anything. +int SparseLightStorage::compress() { + unsigned char _planeIndices[128]; + bool needsCompressed = false; - __int64 lastDataAndCount = dataAndCount; + __int64 lastDataAndCount = dataAndCount; - unsigned char *planeIndices = (unsigned char *)(lastDataAndCount & 0x0000ffffffffffff); - unsigned char *data = planeIndices + 128; + unsigned char* planeIndices = + (unsigned char*)(lastDataAndCount & 0x0000ffffffffffff); + unsigned char* data = planeIndices + 128; - int planesToAlloc = 0; - for( int i = 0; i < 128; i++ ) - { - if( planeIndices[i] == ALL_0_INDEX ) - { - _planeIndices[i] = ALL_0_INDEX; - } - else if( planeIndices[i] == ALL_15_INDEX ) - { - _planeIndices[i] = ALL_15_INDEX; - } - else - { - unsigned char *pucData = &data[ 128 * planeIndices[i] ]; - bool all0 = true; - bool all15 = true; - for( int j = 0; j < 128; j++ ) // 16 x 16 x 4-bits - { - if( *pucData != 0 ) all0 = false; - if( *pucData != 255 ) all15 = false; - pucData++; - } - if( all0 ) - { - _planeIndices[i] = ALL_0_INDEX; - needsCompressed = true; - } - else if ( all15 ) - { - _planeIndices[i] = ALL_15_INDEX; - needsCompressed = true; - } - else - { - _planeIndices[i] = planesToAlloc++; - } - } - } + int planesToAlloc = 0; + for (int i = 0; i < 128; i++) { + if (planeIndices[i] == ALL_0_INDEX) { + _planeIndices[i] = ALL_0_INDEX; + } else if (planeIndices[i] == ALL_15_INDEX) { + _planeIndices[i] = ALL_15_INDEX; + } else { + unsigned char* pucData = &data[128 * planeIndices[i]]; + bool all0 = true; + bool all15 = true; + for (int j = 0; j < 128; j++) // 16 x 16 x 4-bits + { + if (*pucData != 0) all0 = false; + if (*pucData != 255) all15 = false; + pucData++; + } + if (all0) { + _planeIndices[i] = ALL_0_INDEX; + needsCompressed = true; + } else if (all15) { + _planeIndices[i] = ALL_15_INDEX; + needsCompressed = true; + } else { + _planeIndices[i] = planesToAlloc++; + } + } + } - if( needsCompressed ) - { - unsigned char *newIndicesAndData = (unsigned char *)malloc( 128 + 128 * planesToAlloc ); - unsigned char *pucData = newIndicesAndData + 128; - XMemCpy( newIndicesAndData, _planeIndices, 128 ); + if (needsCompressed) { + unsigned char* newIndicesAndData = + (unsigned char*)malloc(128 + 128 * planesToAlloc); + unsigned char* pucData = newIndicesAndData + 128; + XMemCpy(newIndicesAndData, _planeIndices, 128); - for( int i = 0; i < 128; i++ ) - { - if( newIndicesAndData[i] < ALL_0_INDEX ) - { - XMemCpy( pucData, &data[ 128 * planeIndices[i] ], 128 ); - pucData += 128; - } - } + for (int i = 0; i < 128; i++) { + if (newIndicesAndData[i] < ALL_0_INDEX) { + XMemCpy(pucData, &data[128 * planeIndices[i]], 128); + pucData += 128; + } + } - // Get new data and count packed info + // Get new data and count packed info - __int64 newDataAndCount = ((__int64) newIndicesAndData) & 0x0000ffffffffffffL; + __int64 newDataAndCount = + ((__int64)newIndicesAndData) & 0x0000ffffffffffffL; - newDataAndCount |= ((__int64)planesToAlloc) << 48; + newDataAndCount |= ((__int64)planesToAlloc) << 48; - // Attempt to update the data & count atomically. This command will Only succeed if the data stored at - // dataAndCount is equal to lastDataAndCount, and will return the value present just before the write took place - __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( (LONG64 *)&dataAndCount, newDataAndCount, lastDataAndCount ); + // Attempt to update the data & count atomically. This command will Only + // succeed if the data stored at dataAndCount is equal to + // lastDataAndCount, and will return the value present just before the + // write took place + __int64 lastDataAndCount2 = InterlockedCompareExchangeRelease64( + (LONG64*)&dataAndCount, newDataAndCount, lastDataAndCount); - if( lastDataAndCount2 != lastDataAndCount ) - { - // Failed to write. Don't bother trying again... being very conservative here. -// printf("Marking for delete 0x%x (compress fail)\n", newIndicesAndData); - queueForDelete( newIndicesAndData ); - } - else - { - // Success - queueForDelete( planeIndices ); -// printf("Successfully compressed to %d planes, to delete 0x%x\n", planesToAlloc, planeIndices); + if (lastDataAndCount2 != lastDataAndCount) { + // Failed to write. Don't bother trying again... being very + // conservative here. + // printf("Marking for delete 0x%x (compress + //fail)\n", newIndicesAndData); + queueForDelete(newIndicesAndData); + } else { + // Success + queueForDelete(planeIndices); +// printf("Successfully compressed to %d planes, to delete +//0x%x\n", planesToAlloc, planeIndices); #ifdef LIGHT_COMPRESSION_STATS - count = planesToAlloc; + count = planesToAlloc; #endif - } + } - return planesToAlloc; - } - else - { - return (int)((lastDataAndCount >> 48 ) & 0xffff); - } + return planesToAlloc; + } else { + return (int)((lastDataAndCount >> 48) & 0xffff); + } } - -bool SparseLightStorage::isCompressed() -{ - - int count = ( dataAndCount >> 48 ) & 0xffff; - return (count < 127); - - +bool SparseLightStorage::isCompressed() { + int count = (dataAndCount >> 48) & 0xffff; + return (count < 127); } -void SparseLightStorage::write(DataOutputStream *dos) -{ - int count = ( dataAndCount >> 48 ) & 0xffff; - dos->writeInt(count); - unsigned char *dataPointer = (unsigned char *)(dataAndCount & 0x0000ffffffffffff); - byteArray wrapper(dataPointer, count * 128 + 128); - dos->write(wrapper); +void SparseLightStorage::write(DataOutputStream* dos) { + int count = (dataAndCount >> 48) & 0xffff; + dos->writeInt(count); + unsigned char* dataPointer = + (unsigned char*)(dataAndCount & 0x0000ffffffffffff); + byteArray wrapper(dataPointer, count * 128 + 128); + dos->write(wrapper); } -void SparseLightStorage::read(DataInputStream *dis) -{ - int count = dis->readInt(); - unsigned char *dataPointer = (unsigned char *)malloc(count * 128 + 128); - byteArray wrapper(dataPointer, count * 128 + 128); - dis->readFully(wrapper); +void SparseLightStorage::read(DataInputStream* dis) { + int count = dis->readInt(); + unsigned char* dataPointer = (unsigned char*)malloc(count * 128 + 128); + byteArray wrapper(dataPointer, count * 128 + 128); + dis->readFully(wrapper); + __int64 newDataAndCount = ((__int64)dataPointer) & 0x0000ffffffffffffL; - __int64 newDataAndCount = ((__int64) dataPointer) & 0x0000ffffffffffffL; + newDataAndCount |= ((__int64)count) << 48; - newDataAndCount |= ((__int64)count) << 48; - - updateDataAndCount( newDataAndCount ); + updateDataAndCount(newDataAndCount); } diff --git a/Minecraft.World/Level/Storage/SparseLightStorage.h b/Minecraft.World/Level/Storage/SparseLightStorage.h index 355100b4f..f92ed6460 100644 --- a/Minecraft.World/Level/Storage/SparseLightStorage.h +++ b/Minecraft.World/Level/Storage/SparseLightStorage.h @@ -1,89 +1,128 @@ #pragma once #ifndef __linux__ #include "../../Platform/x64headers/xmcore.h" -#endif // __linux__ +#endif // __linux__ -// 4J added - Storage for block & sky light data. Lighting data is normally stored as 4-bits per tile, in a DataLayer class of 16384 bytes ( 128 x 16 x 16 x 0.5 ) -// This class provides more economical storage for such data by taking into consideration that it is quite common for large parts of the lighting data in a level to -// be very compressible (large amounts of 0 for block lights, 0 and 15 for sky lights). -// We are aiming here to balance performance (lighting data is accessed very frequently) against size. +// 4J added - Storage for block & sky light data. Lighting data is normally +// stored as 4-bits per tile, in a DataLayer class of 16384 bytes ( 128 x 16 x +// 16 x 0.5 ) This class provides more economical storage for such data by +// taking into consideration that it is quite common for large parts of the +// lighting data in a level to be very compressible (large amounts of 0 for +// block lights, 0 and 15 for sky lights). We are aiming here to balance +// performance (lighting data is accessed very frequently) against size. // Details of storage method: -// 1. Lighting is split into horizontal planes, of which there are 128, and each taking up 128 bytes (16 x 16 x 0.5) -// 2. Each of these layers has a permanently allocated index in this class (planeIndices). -// 3. Data for allocatedPlaneCount planes worth of data is allocated in the data array ( allocatedPlaneCount * 128 bytes ) -// 4. If a plane index for a layer is < 128, then the data for that layer is at data[ index * 128 ] +// 1. Lighting is split into horizontal planes, of which there are 128, and each +// taking up 128 bytes (16 x 16 x 0.5) +// 2. Each of these layers has a permanently allocated index in this class +// (planeIndices). +// 3. Data for allocatedPlaneCount planes worth of data is allocated in the data +// array ( allocatedPlaneCount * 128 bytes ) +// 4. If a plane index for a layer is < 128, then the data for that layer is at +// data[ index * 128 ] // 5. If a plane index for a layer is 128, then all values for that plane are 0 // 6. If a plane index for a layer is 129, then all values for that plane are 15 -// This class needs to be thread safe as there are times where chunk (and light) data are shared between server & main threads. Light values are queried -// very regularly so this needs to be as light-weight as possible. +// This class needs to be thread safe as there are times where chunk (and light) +// data are shared between server & main threads. Light values are queried very +// regularly so this needs to be as light-weight as possible. -// To meet these requirements, this class is now implemented using a lock-free system, implemented using a read-copy-update (RCU) type algorithm. Some details... +// To meet these requirements, this class is now implemented using a lock-free +// system, implemented using a read-copy-update (RCU) type algorithm. Some +// details... -// (1) The storage details for the class are now packed into a single __int64, which contains both a pointer to the data that is required and a count of how many planes worth -// of storage are allocated. This allows the full storage to be updated atomically using compare and exchange operations (implemented with InterlockedCompareExchangeRelease64). -// (2) The data pointer referenced in this __int64 points to an area of memory which is 128 + 128 * plane_count bytes long, where the first 128 bytes stoere the plane indices, and -// the rest of the data is variable in size to accomodate however many planes are required to be stored -// (3) The RCU bit of the algorithm means that any read operations don't need to do any checks or locks at all. When the data needs to be updated, a copy of it is made and updated, -// then an attempt is made to swap the new data in - if this succeeds then the old data pointer is deleted later at some point where we know nothing will be reading from it anymore. -// This is achieved by putting the delete request in a queue which means it won't actually get deleted until 2 game ticks after the last time its reference existed, which should give -// us a large margin of safety. If the attempt to swap the new data in fails, then the whole write operation has to be attempted again - this is the only time there is really a -// high cost for this algorithm and such write collisions should be rare. +// (1) The storage details for the class are now packed into a single __int64, +// which contains both a pointer to the data that is required and a count of how +// many planes worth +// of storage are allocated. This allows the full storage to be updated +// atomically using compare and exchange operations (implemented with +// InterlockedCompareExchangeRelease64). +// (2) The data pointer referenced in this __int64 points to an area of memory +// which is 128 + 128 * plane_count bytes long, where the first 128 bytes stoere +// the plane indices, and +// the rest of the data is variable in size to accomodate however many +// planes are required to be stored +// (3) The RCU bit of the algorithm means that any read operations don't need to +// do any checks or locks at all. When the data needs to be updated, a copy of +// it is made and updated, +// then an attempt is made to swap the new data in - if this succeeds then +// the old data pointer is deleted later at some point where we know nothing +// will be reading from it anymore. This is achieved by putting the delete +// request in a queue which means it won't actually get deleted until 2 game +// ticks after the last time its reference existed, which should give us a +// large margin of safety. If the attempt to swap the new data in fails, +// then the whole write operation has to be attempted again - this is the +// only time there is really a high cost for this algorithm and such write +// collisions should be rare. -//#define LIGHT_COMPRESSION_STATS +// #define LIGHT_COMPRESSION_STATS class TileCompressData_SPU; -class SparseLightStorage -{ - friend class TileCompressData_SPU; +class SparseLightStorage { + friend class TileCompressData_SPU; + private: -// unsigned char planeIndices[128]; - __int64 dataAndCount; // Contains packed-together data pointer (lower 48-bits), and count of lines used (upper 16-bits) + // unsigned char planeIndices[128]; + __int64 dataAndCount; // Contains packed-together data pointer (lower + // 48-bits), and count of lines used (upper 16-bits) -// unsigned char *data; -// unsigned int allocatedPlaneCount; + // unsigned char *data; + // unsigned int allocatedPlaneCount; - static const int ALL_0_INDEX = 128; - static const int ALL_15_INDEX = 129; + static const int ALL_0_INDEX = 128; + static const int ALL_15_INDEX = 129; #ifdef _XBOX - static const unsigned int MM_PHYSICAL_4KB_BASE = 0xE0000000; // Start of where 4KB page sized physical allocations are made + static const unsigned int MM_PHYSICAL_4KB_BASE = + 0xE0000000; // Start of where 4KB page sized physical allocations are + // made #endif public: SparseLightStorage(bool sky); - SparseLightStorage(bool sky, bool isUpper); - SparseLightStorage(SparseLightStorage *copyFrom); // ctor with deep copy - ~SparseLightStorage(); + SparseLightStorage(bool sky, bool isUpper); + SparseLightStorage(SparseLightStorage* copyFrom); // ctor with deep copy + ~SparseLightStorage(); - void setData(byteArray dataIn, unsigned int inOffset); // Set all lighting values from a data array of length 16384 (128 x 16 x 16 x 0.5). - void getData(byteArray retArray, unsigned int retOffset); // Gets all lighting values into an array of length 16384. - int get(int x, int y, int z); // Get an individual lighting value - void set(int x, int y, int z, int val); // Set an individual lighting value - void setAllBright(); // Set all lighting values to fully bright - int setDataRegion(byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, int offset); // Sets a region of lighting values with the data at offset position in the array dataIn - external ordering compatible with java DataLayer - int getDataRegion(byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, int offset); // Updates the data at offset position dataInOut with a region of lighting information - external ordering compatible with java DataLayer + void setData( + byteArray dataIn, + unsigned int inOffset); // Set all lighting values from a data array of + // length 16384 (128 x 16 x 16 x 0.5). + void getData(byteArray retArray, + unsigned int retOffset); // Gets all lighting values into an + // array of length 16384. + int get(int x, int y, int z); // Get an individual lighting value + void set(int x, int y, int z, int val); // Set an individual lighting value + void setAllBright(); // Set all lighting values to fully bright + int setDataRegion( + byteArray dataIn, int x0, int y0, int z0, int x1, int y1, int z1, + int offset); // Sets a region of lighting values with the data at + // offset position in the array dataIn - external ordering + // compatible with java DataLayer + int getDataRegion( + byteArray dataInOut, int x0, int y0, int z0, int x1, int y1, int z1, + int offset); // Updates the data at offset position dataInOut with a + // region of lighting information - external ordering + // compatible with java DataLayer - static void staticCtor(); + static void staticCtor(); - void addNewPlane(int y); - void getPlaneIndicesAndData(unsigned char **planeIndices, unsigned char **data); - void updateDataAndCount(__int64 newDataAndCount); - int compress(); + void addNewPlane(int y); + void getPlaneIndicesAndData(unsigned char** planeIndices, + unsigned char** data); + void updateDataAndCount(__int64 newDataAndCount); + int compress(); - bool isCompressed(); - void queueForDelete(unsigned char *data); - - static void tick(); - static int deleteQueueIndex; - static XLockFreeStack deleteQueue[3]; + bool isCompressed(); + void queueForDelete(unsigned char* data); + static void tick(); + static int deleteQueueIndex; + static XLockFreeStack deleteQueue[3]; #ifdef LIGHT_COMPRESSION_STATS - int count; + int count; #endif - void write(DataOutputStream *dos); - void read(DataInputStream *dis); + void write(DataOutputStream* dos); + void read(DataInputStream* dis); }; - diff --git a/Minecraft.World/Level/Storage/ZoneFile.cpp b/Minecraft.World/Level/Storage/ZoneFile.cpp index fc60cc54c..96b2734a9 100644 --- a/Minecraft.World/Level/Storage/ZoneFile.cpp +++ b/Minecraft.World/Level/Storage/ZoneFile.cpp @@ -3,116 +3,103 @@ #include "../../IO/Files/File.h" #include "ZoneFile.h" -namespace -{ - std::FILE *OpenBinaryFileForReadWrite(const File &file) - { +namespace { +std::FILE* OpenBinaryFileForReadWrite(const File& file) { #if defined(_WIN32) - std::FILE *stream = _wfopen(file.getPath().c_str(), L"r+b"); - if (stream == NULL) - { - stream = _wfopen(file.getPath().c_str(), L"w+b"); - } + std::FILE* stream = _wfopen(file.getPath().c_str(), L"r+b"); + if (stream == NULL) { + stream = _wfopen(file.getPath().c_str(), L"w+b"); + } #else - const std::string nativePath = wstringtofilename(file.getPath()); - std::FILE *stream = std::fopen(nativePath.c_str(), "r+b"); - if (stream == NULL) - { - stream = std::fopen(nativePath.c_str(), "w+b"); - } + const std::string nativePath = wstringtofilename(file.getPath()); + std::FILE* stream = std::fopen(nativePath.c_str(), "r+b"); + if (stream == NULL) { + stream = std::fopen(nativePath.c_str(), "w+b"); + } #endif - return stream; - } + return stream; } +} // namespace +const int ZoneFile::slotsLength = + ZonedChunkStorage::CHUNKS_PER_ZONE * ZonedChunkStorage::CHUNKS_PER_ZONE; -const int ZoneFile::slotsLength = ZonedChunkStorage::CHUNKS_PER_ZONE * ZonedChunkStorage::CHUNKS_PER_ZONE; +ZoneFile::ZoneFile(__int64 key, File file, File entityFile) + : slots(slotsLength) { + lastUse = 0; -ZoneFile::ZoneFile(__int64 key, File file, File entityFile) : slots(slotsLength) -{ - lastUse = 0; + this->key = key; + this->file = file; - this->key = key; - this->file = file; - - // 4J - try/catch removed -// try { + // 4J - try/catch removed + // try { this->entityFile = new NbtSlotFile(entityFile); -// } catch (Exception e) { -// System.out.println("Broken entity file: " + entityFile + " (" + e.toString() + "), replacing.."); -// entityFile.delete(); -// entityFile.createNewFile(); -// this.entityFile = new NbtSlotFile(entityFile); -// } + // } catch (Exception e) { + // System.out.println("Broken entity file: " + entityFile + " (" + + // e.toString() + "), replacing.."); entityFile.delete(); + // entityFile.createNewFile(); + // this.entityFile = new NbtSlotFile(entityFile); + // } channel = OpenBinaryFileForReadWrite(file); - // 4J - try/catch removed -// try { - readHeader(); -// } catch (Exception e) { -// e.printStackTrace(); -// throw new IOException("Broken zone file: " + file + ": " + e); -// } + // 4J - try/catch removed + // try { + readHeader(); + // } catch (Exception e) { + // e.printStackTrace(); + // throw new IOException("Broken zone file: " + file + ": " + e); + // } } -ZoneFile::~ZoneFile() -{ - delete [] slots.data; -} +ZoneFile::~ZoneFile() { delete[] slots.data; } -void ZoneFile::readHeader() -{ - ZoneIo *zoneIo = new ZoneIo(channel, 0); - ByteBuffer *bb = zoneIo->read(FILE_HEADER_SIZE); +void ZoneFile::readHeader() { + ZoneIo* zoneIo = new ZoneIo(channel, 0); + ByteBuffer* bb = zoneIo->read(FILE_HEADER_SIZE); bb->flip(); if (bb->remaining() < 5) return; int magic = bb->getInt(); -// if (magic != MAGIC_NUMBER) throw new IOException("Bad magic number: " + magic); // 4J - TODO + // if (magic != MAGIC_NUMBER) throw new IOException("Bad magic number: " + // + magic); // 4J - TODO short version = bb->getShort(); -// if (version != 0) throw new IOException("Bad version number: " + version); // 4J - TODO + // if (version != 0) throw new IOException("Bad version number: " + + // version); // 4J - TODO slotCount = bb->getShort(); bb->getShortArray(slots); bb->position(bb->position() + slotsLength * 2); } -void ZoneFile::writeHeader() -{ - ZoneIo *zoneIo = new ZoneIo(channel, 0); +void ZoneFile::writeHeader() { + ZoneIo* zoneIo = new ZoneIo(channel, 0); - ByteBuffer *bb = ByteBuffer::allocate(FILE_HEADER_SIZE); + ByteBuffer* bb = ByteBuffer::allocate(FILE_HEADER_SIZE); bb->order(ZonedChunkStorage::BYTEORDER); bb->putInt(MAGIC_NUMBER); - bb->putShort((short) 0); - bb->putShort((short) slotCount); + bb->putShort((short)0); + bb->putShort((short)slotCount); bb->putShortArray(slots); bb->position(bb->position() + slots.length * 2); bb->flip(); zoneIo->write(bb, FILE_HEADER_SIZE); } -void ZoneFile::close() -{ - if (channel != NULL) - { - std::fclose(channel); - channel = NULL; - } +void ZoneFile::close() { + if (channel != NULL) { + std::fclose(channel); + channel = NULL; + } entityFile->close(); } -ZoneIo *ZoneFile::getZoneIo(int slot) -{ - if (slots[slot] == 0) - { +ZoneIo* ZoneFile::getZoneIo(int slot) { + if (slots[slot] == 0) { slots[slot] = ++slotCount; writeHeader(); } - int byteOffs = (slots[slot] - 1) * ZonedChunkStorage::CHUNK_SIZE_BYTES + FILE_HEADER_SIZE; + int byteOffs = (slots[slot] - 1) * ZonedChunkStorage::CHUNK_SIZE_BYTES + + FILE_HEADER_SIZE; return new ZoneIo(channel, byteOffs); } -bool ZoneFile::containsSlot(int slot) -{ - return slots[slot] > 0; -} +bool ZoneFile::containsSlot(int slot) { return slots[slot] > 0; } diff --git a/Minecraft.World/Level/Storage/ZoneFile.h b/Minecraft.World/Level/Storage/ZoneFile.h index 75e402918..50b5f6abd 100644 --- a/Minecraft.World/Level/Storage/ZoneFile.h +++ b/Minecraft.World/Level/Storage/ZoneFile.h @@ -5,15 +5,14 @@ #include "../../IO/NBT/NbtSlotFile.h" #include "ZoneIO.h" -class ZoneFile -{ +class ZoneFile { public: static const int FILE_HEADER_SIZE = 1024 * 4; private: static const int MAGIC_NUMBER = 0x13737000; - static const int slotsLength; + static const int slotsLength; shortArray slots; short slotCount; @@ -22,16 +21,16 @@ public: __int64 lastUse; private: - std::FILE *channel; + std::FILE* channel; public: __int64 key; File file; - NbtSlotFile *entityFile; + NbtSlotFile* entityFile; ZoneFile(__int64 key, File file, File entityFile); - ~ZoneFile(); + ~ZoneFile(); void readHeader(); @@ -39,6 +38,6 @@ public: public: void close(); - ZoneIo *getZoneIo(int slot); + ZoneIo* getZoneIo(int slot); bool containsSlot(int slot); }; diff --git a/Minecraft.World/Level/Storage/ZoneIO.cpp b/Minecraft.World/Level/Storage/ZoneIO.cpp index 9789fae2b..f7aee7a7f 100644 --- a/Minecraft.World/Level/Storage/ZoneIO.cpp +++ b/Minecraft.World/Level/Storage/ZoneIO.cpp @@ -2,57 +2,52 @@ #include "../../IO/Streams/ByteBuffer.h" #include "ZoneIO.h" -namespace -{ - bool SeekFile(std::FILE *file, __int64 offset) - { +namespace { +bool SeekFile(std::FILE* file, __int64 offset) { #if defined(_WIN32) - return _fseeki64(file, offset, SEEK_SET) == 0; + return _fseeki64(file, offset, SEEK_SET) == 0; #else - return fseeko(file, static_cast(offset), SEEK_SET) == 0; + return fseeko(file, static_cast(offset), SEEK_SET) == 0; #endif - } +} +} // namespace + +ZoneIo::ZoneIo(std::FILE* channel, __int64 pos) { + this->channel = channel; + this->pos = pos; } -ZoneIo::ZoneIo(std::FILE *channel, __int64 pos) -{ - this->channel = channel; - this->pos = pos; -} - -void ZoneIo::write(byteArray bb, int size) -{ - ByteBuffer *buff = ByteBuffer::wrap(bb); -// if (bb.length != size) throw new IllegalArgumentException("Expected " + size + " bytes, got " + bb.length); // 4J - TODO +void ZoneIo::write(byteArray bb, int size) { + ByteBuffer* buff = ByteBuffer::wrap(bb); + // if (bb.length != size) throw new IllegalArgumentException("Expected " + // + size + " bytes, got " + bb.length); // 4J - TODO buff->order(ZonedChunkStorage::BYTEORDER); buff->position(bb.length); buff->flip(); write(buff, size); - delete buff; + delete buff; } -void ZoneIo::write(ByteBuffer *bb, int size) -{ - SeekFile(channel, pos); - std::fwrite(bb->getBuffer(), 1, bb->getSize(), channel); +void ZoneIo::write(ByteBuffer* bb, int size) { + SeekFile(channel, pos); + std::fwrite(bb->getBuffer(), 1, bb->getSize(), channel); pos += size; } -ByteBuffer *ZoneIo::read(int size) -{ +ByteBuffer* ZoneIo::read(int size) { byteArray bb = byteArray(size); - SeekFile(channel, pos); - ByteBuffer *buff = ByteBuffer::wrap(bb); - // 4J - to investigate - why is this buffer flipped before anything goes in it? + SeekFile(channel, pos); + ByteBuffer* buff = ByteBuffer::wrap(bb); + // 4J - to investigate - why is this buffer flipped before anything goes in + // it? buff->order(ZonedChunkStorage::BYTEORDER); buff->position(size); buff->flip(); - std::fread(buff->getBuffer(), 1, buff->getSize(), channel); + std::fread(buff->getBuffer(), 1, buff->getSize(), channel); pos += size; return buff; } -void ZoneIo::flush() -{ - // 4J - was channel.force(false); +void ZoneIo::flush() { + // 4J - was channel.force(false); } diff --git a/Minecraft.World/Level/Storage/ZoneIO.h b/Minecraft.World/Level/Storage/ZoneIO.h index 6bf1dbd04..73f63970f 100644 --- a/Minecraft.World/Level/Storage/ZoneIO.h +++ b/Minecraft.World/Level/Storage/ZoneIO.h @@ -5,17 +5,16 @@ class ByteBuffer; -class ZoneIo -{ +class ZoneIo { private: - std::FILE *channel; + std::FILE* channel; __int64 pos; public: - ZoneIo(std::FILE *channel, __int64 pos); + ZoneIo(std::FILE* channel, __int64 pos); void write(byteArray bb, int size); - void write(ByteBuffer *bb, int size); - ByteBuffer *read(int size); + void write(ByteBuffer* bb, int size); + ByteBuffer* read(int size); void flush(); }; diff --git a/Minecraft.World/Level/Storage/ZonedChunkStorage.cpp b/Minecraft.World/Level/Storage/ZonedChunkStorage.cpp index 6ca5e40e8..3bbe5a8c3 100644 --- a/Minecraft.World/Level/Storage/ZonedChunkStorage.cpp +++ b/Minecraft.World/Level/Storage/ZonedChunkStorage.cpp @@ -8,34 +8,37 @@ #include "ZonedChunkStorage.h" #include "ZoneFile.h" -// 4J Stu - There are changes to this class for 1.8.2, but since we never use it anyway lets not worry about it +// 4J Stu - There are changes to this class for 1.8.2, but since we never use it +// anyway lets not worry about it const int ZonedChunkStorage::BIT_TERRAIN_POPULATED = 0x0000001; - -const int ZonedChunkStorage::CHUNKS_PER_ZONE_BITS = 5; // = 32 -const int ZonedChunkStorage::CHUNKS_PER_ZONE = 1 << ZonedChunkStorage::CHUNKS_PER_ZONE_BITS; // ^2 + +const int ZonedChunkStorage::CHUNKS_PER_ZONE_BITS = 5; // = 32 +const int ZonedChunkStorage::CHUNKS_PER_ZONE = + 1 << ZonedChunkStorage::CHUNKS_PER_ZONE_BITS; // ^2 const int ZonedChunkStorage::CHUNK_WIDTH = 16; const int ZonedChunkStorage::CHUNK_HEADER_SIZE = 256; -const int ZonedChunkStorage::CHUNK_SIZE = ZonedChunkStorage::CHUNK_WIDTH * ZonedChunkStorage::CHUNK_WIDTH * Level::DEPTH; +const int ZonedChunkStorage::CHUNK_SIZE = ZonedChunkStorage::CHUNK_WIDTH * + ZonedChunkStorage::CHUNK_WIDTH * + Level::DEPTH; const int ZonedChunkStorage::CHUNK_LAYERS = 3; -const int ZonedChunkStorage::CHUNK_SIZE_BYTES = ZonedChunkStorage::CHUNK_SIZE * ZonedChunkStorage::CHUNK_LAYERS + ZonedChunkStorage::CHUNK_HEADER_SIZE; +const int ZonedChunkStorage::CHUNK_SIZE_BYTES = + ZonedChunkStorage::CHUNK_SIZE * ZonedChunkStorage::CHUNK_LAYERS + + ZonedChunkStorage::CHUNK_HEADER_SIZE; const ByteOrder ZonedChunkStorage::BYTEORDER = BIGENDIAN; -ZonedChunkStorage::ZonedChunkStorage(File dir) -{ - tickCount = 0; +ZonedChunkStorage::ZonedChunkStorage(File dir) { + tickCount = 0; - //this->dir = dir; - this->dir = File( dir, std::wstring( L"data" ) ); - if( !this->dir.exists() ) this->dir.mkdirs(); + // this->dir = dir; + this->dir = File(dir, std::wstring(L"data")); + if (!this->dir.exists()) this->dir.mkdirs(); } - -int ZonedChunkStorage::getSlot(int x, int z) -{ +int ZonedChunkStorage::getSlot(int x, int z) { int xZone = x >> CHUNKS_PER_ZONE_BITS; int zZone = z >> CHUNKS_PER_ZONE_BITS; int xOffs = x - (xZone << CHUNKS_PER_ZONE_BITS); @@ -44,60 +47,58 @@ int ZonedChunkStorage::getSlot(int x, int z) return slot; } -ZoneFile *ZonedChunkStorage::getZoneFile(int x, int z, bool create) -{ +ZoneFile* ZonedChunkStorage::getZoneFile(int x, int z, bool create) { int slot = getSlot(x, z); int xZone = x >> CHUNKS_PER_ZONE_BITS; int zZone = z >> CHUNKS_PER_ZONE_BITS; __int64 key = xZone + (zZone << 20l); - // 4J - was !zoneFiles.containsKey(key) - if (zoneFiles.find(key) == zoneFiles.end()) - { - wchar_t xRadix36[64]; - wchar_t zRadix36[64]; - _itow(x,xRadix36,36); - _itow(z,zRadix36,36); - File file = File(dir, std::wstring( L"zone_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + // 4J - was !zoneFiles.containsKey(key) + if (zoneFiles.find(key) == zoneFiles.end()) { + wchar_t xRadix36[64]; + wchar_t zRadix36[64]; + _itow(x, xRadix36, 36); + _itow(z, zRadix36, 36); + File file = File(dir, std::wstring(L"zone_") + _toString(xRadix36) + + L"_" + _toString(zRadix36) + L".dat"); - if ( !file.exists() ) - { + if (!file.exists()) { if (!create) return NULL; - HANDLE ch = CreateFile(wstringtofilename(file.getPath()), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - CloseHandle(ch); + HANDLE ch = CreateFile(wstringtofilename(file.getPath()), + GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + CloseHandle(ch); } - File entityFile = File(dir, std::wstring( L"entities_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + File entityFile = + File(dir, std::wstring(L"entities_") + _toString(xRadix36) + L"_" + + _toString(zRadix36) + L".dat"); zoneFiles[key] = new ZoneFile(key, file, entityFile); } - ZoneFile *zoneFile = zoneFiles[key]; + ZoneFile* zoneFile = zoneFiles[key]; zoneFile->lastUse = tickCount; - if (!zoneFile->containsSlot(slot)) - { + if (!zoneFile->containsSlot(slot)) { if (!create) return NULL; } return zoneFile; - } -ZoneIo *ZonedChunkStorage::getBuffer(int x, int z, bool create) -{ - ZoneFile *zoneFile = getZoneFile(x, z, create); +ZoneIo* ZonedChunkStorage::getBuffer(int x, int z, bool create) { + ZoneFile* zoneFile = getZoneFile(x, z, create); if (zoneFile == NULL) return NULL; return zoneFile->getZoneIo(getSlot(x, z)); } -LevelChunk *ZonedChunkStorage::load(Level *level, int x, int z) -{ - ZoneIo *zoneIo = getBuffer(x, z, false); +LevelChunk* ZonedChunkStorage::load(Level* level, int x, int z) { + ZoneIo* zoneIo = getBuffer(x, z, false); if (zoneIo == NULL) return NULL; - LevelChunk *lc = new LevelChunk(level, x, z); + LevelChunk* lc = new LevelChunk(level, x, z); lc->unsaved = false; - ByteBuffer *header = zoneIo->read(CHUNK_HEADER_SIZE); + ByteBuffer* header = zoneIo->read(CHUNK_HEADER_SIZE); lc->blocks = zoneIo->read(CHUNK_SIZE)->array(); lc->data = new DataLayer(zoneIo->read(CHUNK_SIZE / 2)->array()); lc->skyLight = new DataLayer(zoneIo->read(CHUNK_SIZE / 2)->array()); @@ -116,15 +117,13 @@ LevelChunk *ZonedChunkStorage::load(Level *level, int x, int z) lc->fixBlocks(); return lc; - } -void ZonedChunkStorage::save(Level *level, LevelChunk *lc) -{ +void ZonedChunkStorage::save(Level* level, LevelChunk* lc) { __int64 flags = 0; if (lc->terrainPopulated) flags |= BIT_TERRAIN_POPULATED; - ByteBuffer *header = ByteBuffer::allocate(CHUNK_HEADER_SIZE); + ByteBuffer* header = ByteBuffer::allocate(CHUNK_HEADER_SIZE); header->order(ZonedChunkStorage::BYTEORDER); header->putInt(lc->x); header->putInt(lc->z); @@ -132,7 +131,7 @@ void ZonedChunkStorage::save(Level *level, LevelChunk *lc) header->putLong(flags); header->flip(); - ZoneIo *zoneIo = getBuffer(lc->x, lc->z, true); + ZoneIo* zoneIo = getBuffer(lc->x, lc->z, true); zoneIo->write(header, CHUNK_HEADER_SIZE); zoneIo->write(lc->blocks, CHUNK_SIZE); zoneIo->write(lc->data->data, CHUNK_SIZE / 2); @@ -142,123 +141,112 @@ void ZonedChunkStorage::save(Level *level, LevelChunk *lc) zoneIo->flush(); } -void ZonedChunkStorage::tick() -{ +void ZonedChunkStorage::tick() { tickCount++; - if (tickCount % (20 * 10) == 4) - { - std::vector<__int64> toClose; + if (tickCount % (20 * 10) == 4) { + std::vector<__int64> toClose; - AUTO_VAR(itEndZF, zoneFiles.end()); - for( std::unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEndZF; it++ ) - { - ZoneFile *zoneFile = it->second; - if (tickCount - zoneFile->lastUse > 20 * 60) - { + AUTO_VAR(itEndZF, zoneFiles.end()); + for (std::unordered_map<__int64, ZoneFile*>::iterator it = + zoneFiles.begin(); + it != itEndZF; it++) { + ZoneFile* zoneFile = it->second; + if (tickCount - zoneFile->lastUse > 20 * 60) { toClose.push_back(zoneFile->key); } - } - - AUTO_VAR(itEndTC, toClose.end()); - for (AUTO_VAR(it, toClose.begin()); it != itEndTC; it++) - { - __int64 key = *it ; //toClose[i]; - // 4J - removed try/catch -// try { - char buf[256]; - sprintf(buf,"Closing zone %I64d\n",key); - app.DebugPrintf(buf); + } + + AUTO_VAR(itEndTC, toClose.end()); + for (AUTO_VAR(it, toClose.begin()); it != itEndTC; it++) { + __int64 key = *it; // toClose[i]; + // 4J - removed try/catch + // try { + char buf[256]; + sprintf(buf, "Closing zone %I64d\n", key); + app.DebugPrintf(buf); zoneFiles[key]->close(); - zoneFiles.erase(zoneFiles.find(key)); -// } catch (IOException e) { -// e.printStackTrace(); -// } - } + zoneFiles.erase(zoneFiles.find(key)); + // } catch (IOException e) { + // e.printStackTrace(); + // } + } } } - -void ZonedChunkStorage::flush() -{ - AUTO_VAR(itEnd, zoneFiles.end()); - for( std::unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEnd; it++ ) - { - ZoneFile *zoneFile = it->second; - // 4J - removed try/catch -// try { - zoneFile->close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } - } - zoneFiles.clear(); +void ZonedChunkStorage::flush() { + AUTO_VAR(itEnd, zoneFiles.end()); + for (std::unordered_map<__int64, ZoneFile*>::iterator it = + zoneFiles.begin(); + it != itEnd; it++) { + ZoneFile* zoneFile = it->second; + // 4J - removed try/catch + // try { + zoneFile->close(); + // } catch (IOException e) { + // e.printStackTrace(); + // } + } + zoneFiles.clear(); } -void ZonedChunkStorage::loadEntities(Level *level, LevelChunk *lc) -{ +void ZonedChunkStorage::loadEntities(Level* level, LevelChunk* lc) { int slot = getSlot(lc->x, lc->z); - ZoneFile *zoneFile = getZoneFile(lc->x, lc->z, true); - std::vector *tags = zoneFile->entityFile->readAll(slot); + ZoneFile* zoneFile = getZoneFile(lc->x, lc->z, true); + std::vector* tags = zoneFile->entityFile->readAll(slot); - AUTO_VAR(itEnd, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEnd; it++) - { - CompoundTag *tag = *it; //tags->at(i); + AUTO_VAR(itEnd, tags->end()); + for (AUTO_VAR(it, tags->begin()); it != itEnd; it++) { + CompoundTag* tag = *it; // tags->at(i); int type = tag->getInt(L"_TYPE"); - if (type == 0) - { + if (type == 0) { std::shared_ptr e = EntityIO::loadStatic(tag, level); if (e != NULL) lc->addEntity(e); - } - else if (type == 1) - { + } else if (type == 1) { std::shared_ptr te = TileEntity::loadStatic(tag); if (te != NULL) lc->addTileEntity(te); } } } -void ZonedChunkStorage::saveEntities(Level *level, LevelChunk *lc) -{ +void ZonedChunkStorage::saveEntities(Level* level, LevelChunk* lc) { int slot = getSlot(lc->x, lc->z); - ZoneFile *zoneFile = getZoneFile(lc->x, lc->z, true); + ZoneFile* zoneFile = getZoneFile(lc->x, lc->z, true); - std::vector tags; + std::vector tags; #ifdef _ENTITIES_RW_SECTION - EnterCriticalRWSection(&lc->m_csEntities, true); + EnterCriticalRWSection(&lc->m_csEntities, true); #else - EnterCriticalSection(&lc->m_csEntities); + EnterCriticalSection(&lc->m_csEntities); #endif - for (int i = 0; i < LevelChunk::ENTITY_BLOCKS_LENGTH; i++) - { - std::vector > *entities = lc->entityBlocks[i]; + for (int i = 0; i < LevelChunk::ENTITY_BLOCKS_LENGTH; i++) { + std::vector >* entities = lc->entityBlocks[i]; - AUTO_VAR(itEndTags, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEndTags; it++) - { - std::shared_ptr e = *it; //entities->at(j); - CompoundTag *cp = new CompoundTag(); + AUTO_VAR(itEndTags, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEndTags; it++) { + std::shared_ptr e = *it; // entities->at(j); + CompoundTag* cp = new CompoundTag(); cp->putInt(L"_TYPE", 0); e->save(cp); tags.push_back(cp); } } #ifdef _ENTITIES_RW_SECTION - LeaveCriticalRWSection(&lc->m_csEntities, true); + LeaveCriticalRWSection(&lc->m_csEntities, true); #else - LeaveCriticalSection(&lc->m_csEntities); + LeaveCriticalSection(&lc->m_csEntities); #endif - for( std::unordered_map , TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != lc->tileEntities.end(); it++) - { - std::shared_ptr te = it->second; - CompoundTag *cp = new CompoundTag(); + for (std::unordered_map, + TilePosKeyHash, TilePosKeyEq>::iterator it = + lc->tileEntities.begin(); + it != lc->tileEntities.end(); it++) { + std::shared_ptr te = it->second; + CompoundTag* cp = new CompoundTag(); cp->putInt(L"_TYPE", 1); te->save(cp); tags.push_back(cp); - } + } zoneFile->entityFile->replaceSlot(slot, &tags); } diff --git a/Minecraft.World/Level/Storage/ZonedChunkStorage.h b/Minecraft.World/Level/Storage/ZonedChunkStorage.h index 40d030b74..e2dd1f879 100644 --- a/Minecraft.World/Level/Storage/ZonedChunkStorage.h +++ b/Minecraft.World/Level/Storage/ZonedChunkStorage.h @@ -3,51 +3,50 @@ #include "ChunkStorage.h" #include "../LevelChunk.h" -// 4J Stu - There are changes to this class for 1.8.2, but since we never use it anyway lets not worry about it - - +// 4J Stu - There are changes to this class for 1.8.2, but since we never use it +// anyway lets not worry about it class ZoneFile; class ZoneIo; -class ZonedChunkStorage : public ChunkStorage -{ +class ZonedChunkStorage : public ChunkStorage { public: static const int BIT_TERRAIN_POPULATED; - - static const int CHUNKS_PER_ZONE_BITS; // = 32 - static const int CHUNKS_PER_ZONE; // ^2 - + + static const int CHUNKS_PER_ZONE_BITS; // = 32 + static const int CHUNKS_PER_ZONE; // ^2 + static const int CHUNK_WIDTH; - + static const int CHUNK_HEADER_SIZE; static const int CHUNK_SIZE; - static const int CHUNK_LAYERS ; + static const int CHUNK_LAYERS; static const int CHUNK_SIZE_BYTES; - + static const ByteOrder BYTEORDER; File dir; private: - std::unordered_map<__int64, ZoneFile *> zoneFiles; + std::unordered_map<__int64, ZoneFile*> zoneFiles; __int64 tickCount; public: - ZonedChunkStorage(File dir); + ZonedChunkStorage(File dir); + private: - int getSlot(int x, int z); - ZoneFile *getZoneFile(int x, int z, bool create); - ZoneIo *getBuffer(int x, int z, bool create); + int getSlot(int x, int z); + ZoneFile* getZoneFile(int x, int z, bool create); + ZoneIo* getBuffer(int x, int z, bool create); public: - LevelChunk *load(Level *level, int x, int z); - void save(Level *level, LevelChunk *lc); + LevelChunk* load(Level* level, int x, int z); + void save(Level* level, LevelChunk* lc); void tick(); void flush(); - void loadEntities(Level *level, LevelChunk *lc); - void saveEntities(Level *level, LevelChunk *lc); + void loadEntities(Level* level, LevelChunk* lc); + void saveEntities(Level* level, LevelChunk* lc); }; \ No newline at end of file diff --git a/Minecraft.World/Level/TickNextTickData.cpp b/Minecraft.World/Level/TickNextTickData.cpp index 292fea72e..9bbaaa7fa 100644 --- a/Minecraft.World/Level/TickNextTickData.cpp +++ b/Minecraft.World/Level/TickNextTickData.cpp @@ -4,67 +4,64 @@ __int64 TickNextTickData::C = 0; -TickNextTickData::TickNextTickData(int x, int y, int z, int tileId) -{ - m_delay = 0; - c = C++; +TickNextTickData::TickNextTickData(int x, int y, int z, int tileId) { + m_delay = 0; + c = C++; - this->x = x; - this->y = y; - this->z = z; - this->tileId = tileId; + this->x = x; + this->y = y; + this->z = z; + this->tileId = tileId; } - -bool TickNextTickData::equals(const void *o) const -{ - // TODO 4J Is this safe to cast it before we do a dynamic_cast? Will the dynamic_cast still fail? - // We cannot dynamic_cast a void* - if ( dynamic_cast( (TickNextTickData *) o ) != NULL) - { - TickNextTickData *t = (TickNextTickData *) o; - return x == t->x && y == t->y && z == t->z && tileId == t->tileId; - } - return false; +bool TickNextTickData::equals(const void* o) const { + // TODO 4J Is this safe to cast it before we do a dynamic_cast? Will the + // dynamic_cast still fail? We cannot dynamic_cast a void* + if (dynamic_cast((TickNextTickData*)o) != NULL) { + TickNextTickData* t = (TickNextTickData*)o; + return x == t->x && y == t->y && z == t->z && tileId == t->tileId; + } + return false; } -int TickNextTickData::hashCode() const -{ - // 4jcraft added cast to unsigned - return ((((unsigned) x * 1024 * 1024) + ((unsigned) z * 1024) + (unsigned) y) * 256) + tileId; +int TickNextTickData::hashCode() const { + // 4jcraft added cast to unsigned + return ((((unsigned)x * 1024 * 1024) + ((unsigned)z * 1024) + (unsigned)y) * + 256) + + tileId; } -TickNextTickData *TickNextTickData::delay(__int64 l) -{ - this->m_delay = l; - return this; +TickNextTickData* TickNextTickData::delay(__int64 l) { + this->m_delay = l; + return this; } -int TickNextTickData::compareTo(const TickNextTickData *tnd) const -{ - if (m_delay < tnd->m_delay) return -1; - if (m_delay > tnd->m_delay) return 1; - if (c < tnd->c) return -1; - if (c > tnd->c) return 1; - return 0; +int TickNextTickData::compareTo(const TickNextTickData* tnd) const { + if (m_delay < tnd->m_delay) return -1; + if (m_delay > tnd->m_delay) return 1; + if (c < tnd->c) return -1; + if (c > tnd->c) return 1; + return 0; } -//A class that takes two arguments of the same type as the container elements and returns a bool. -//The expression comp(a,b), where comp is an object of this comparison class and a and b are elements of the container, -//shall return true if a is to be placed at an earlier position than b in a strict weak ordering operation. -//This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). -//This defaults to less, which returns the same as applying the less-than operator (a, which returns the same as applying the less-than operator (a -// We don't need to do that as it is only as helper for the java sdk sorting operations +// We don't need to do that as it is only as helper for the java sdk sorting +// operations -class TickNextTickData -{ +class TickNextTickData { private: - static __int64 C; + static __int64 C; public: - int x, y, z, tileId; - __int64 m_delay; + int x, y, z, tileId; + __int64 m_delay; private: - __int64 c; + __int64 c; public: - TickNextTickData(int x, int y, int z, int tileId); + TickNextTickData(int x, int y, int z, int tileId); - bool equals(const void *o) const; - int hashCode() const; - TickNextTickData *delay(__int64 l); - int compareTo(const TickNextTickData *tnd) const; + bool equals(const void* o) const; + int hashCode() const; + TickNextTickData* delay(__int64 l); + int compareTo(const TickNextTickData* tnd) const; - static bool compare_fnct(const TickNextTickData &x, const TickNextTickData &y); - static int hash_fnct(const TickNextTickData &k); - static bool eq_test(const TickNextTickData &x, const TickNextTickData &y); + static bool compare_fnct(const TickNextTickData& x, + const TickNextTickData& y); + static int hash_fnct(const TickNextTickData& k); + static bool eq_test(const TickNextTickData& x, const TickNextTickData& y); }; -struct TickNextTickDataKeyHash -{ - int operator() (const TickNextTickData &k) const { return TickNextTickData::hash_fnct (k); } +struct TickNextTickDataKeyHash { + int operator()(const TickNextTickData& k) const { + return TickNextTickData::hash_fnct(k); + } }; -struct TickNextTickDataKeyEq -{ - bool operator() (const TickNextTickData &x, const TickNextTickData &y) const { return TickNextTickData::eq_test (x, y); } +struct TickNextTickDataKeyEq { + bool operator()(const TickNextTickData& x, + const TickNextTickData& y) const { + return TickNextTickData::eq_test(x, y); + } }; -struct TickNextTickDataKeyCompare -{ - bool operator() (const TickNextTickData &x, const TickNextTickData &y) const { return TickNextTickData::compare_fnct (x, y); } +struct TickNextTickDataKeyCompare { + bool operator()(const TickNextTickData& x, + const TickNextTickData& y) const { + return TickNextTickData::compare_fnct(x, y); + } }; \ No newline at end of file diff --git a/Minecraft.World/Level/TileEventData.cpp b/Minecraft.World/Level/TileEventData.cpp index f7911f3f0..c904e510c 100644 --- a/Minecraft.World/Level/TileEventData.cpp +++ b/Minecraft.World/Level/TileEventData.cpp @@ -2,47 +2,29 @@ #include "TileEventData.h" -TileEventData::TileEventData(int x, int y, int z, int tile, int paramA, int paramB) -{ - this->x = x; - this->y = y; - this->z = z; - this->paramA = paramA; - this->paramB = paramB; - this->tile = tile; +TileEventData::TileEventData(int x, int y, int z, int tile, int paramA, + int paramB) { + this->x = x; + this->y = y; + this->z = z; + this->paramA = paramA; + this->paramB = paramB; + this->tile = tile; } -int TileEventData::getX() -{ - return x; -} +int TileEventData::getX() { return x; } -int TileEventData::getY() -{ - return y; -} +int TileEventData::getY() { return y; } -int TileEventData::getZ() -{ - return z; -} +int TileEventData::getZ() { return z; } -int TileEventData::getParamA() -{ - return paramA; -} +int TileEventData::getParamA() { return paramA; } -int TileEventData::getParamB() -{ - return paramB; -} +int TileEventData::getParamB() { return paramB; } -int TileEventData::getTile() -{ - return tile; -} +int TileEventData::getTile() { return tile; } -bool TileEventData::equals(TileEventData &ted) -{ - return x == ted.x && y == ted.y && z == ted.z && paramA == ted.paramA && paramB == ted.paramB && tile == ted.tile; +bool TileEventData::equals(TileEventData& ted) { + return x == ted.x && y == ted.y && z == ted.z && paramA == ted.paramA && + paramB == ted.paramB && tile == ted.tile; } \ No newline at end of file diff --git a/Minecraft.World/Level/TileEventData.h b/Minecraft.World/Level/TileEventData.h index bbec478e4..602cbf00e 100644 --- a/Minecraft.World/Level/TileEventData.h +++ b/Minecraft.World/Level/TileEventData.h @@ -1,21 +1,20 @@ #pragma once -class TileEventData -{ +class TileEventData { private: - int x, y, z; - int tile; - int paramA; - int paramB; + int x, y, z; + int tile; + int paramA; + int paramB; public: - TileEventData(int x, int y, int z, int tile, int paramA, int paramB); + TileEventData(int x, int y, int z, int tile, int paramA, int paramB); - int getX(); - int getY(); - int getZ(); - int getParamA(); - int getParamB(); - int getTile(); - bool equals(TileEventData &ted); + int getX(); + int getY(); + int getZ(); + int getParamA(); + int getParamB(); + int getTile(); + bool equals(TileEventData& ted); }; \ No newline at end of file diff --git a/Minecraft.World/Level/TilePos.cpp b/Minecraft.World/Level/TilePos.cpp index efefb66bb..bb83514f3 100644 --- a/Minecraft.World/Level/TilePos.cpp +++ b/Minecraft.World/Level/TilePos.cpp @@ -3,27 +3,23 @@ #include "TilePos.h" #include "../Util/Vec3.h" -TilePos::TilePos(int x, int y, int z) -{ - this->x = x; - this->y = y; - this->z = z; +TilePos::TilePos(int x, int y, int z) { + this->x = x; + this->y = y; + this->z = z; } // 4J - brought forward from 1.2.3 -TilePos::TilePos(Vec3 *p) -{ - this->x = Mth::floor(p->x); - this->y = Mth::floor(p->y); - this->z = Mth::floor(p->z); +TilePos::TilePos(Vec3* p) { + this->x = Mth::floor(p->x); + this->y = Mth::floor(p->y); + this->z = Mth::floor(p->z); } -int TilePos::hash_fnct(const TilePos &k) -{ - return k.x * 8976890 + k.y * 981131 + k.z; +int TilePos::hash_fnct(const TilePos& k) { + return k.x * 8976890 + k.y * 981131 + k.z; } -bool TilePos::eq_test(const TilePos &x, const TilePos &y) -{ - return x.x == y.x && x.y == y.y && x.z == y.z; +bool TilePos::eq_test(const TilePos& x, const TilePos& y) { + return x.x == y.x && x.y == y.y && x.z == y.z; } \ No newline at end of file diff --git a/Minecraft.World/Level/TilePos.h b/Minecraft.World/Level/TilePos.h index df23e5f9c..e393dcfb3 100644 --- a/Minecraft.World/Level/TilePos.h +++ b/Minecraft.World/Level/TilePos.h @@ -1,26 +1,24 @@ #pragma once class Vec3; -class TilePos -{ +class TilePos { public: - int x, y, z; + int x, y, z; public: - TilePos(int x, int y, int z); - TilePos(Vec3 *p); // 4J - brought forward from 1.2.3 + TilePos(int x, int y, int z); + TilePos(Vec3* p); // 4J - brought forward from 1.2.3 - static int hash_fnct(const TilePos &k); - static bool eq_test(const TilePos &x, const TilePos &y); + static int hash_fnct(const TilePos& k); + static bool eq_test(const TilePos& x, const TilePos& y); }; -struct TilePosKeyHash -{ - int operator() (const TilePos &k) const { return TilePos::hash_fnct (k); } +struct TilePosKeyHash { + int operator()(const TilePos& k) const { return TilePos::hash_fnct(k); } }; -struct TilePosKeyEq -{ - bool operator() (const TilePos &x, const TilePos &y) const { return TilePos::eq_test (x, y); } +struct TilePosKeyEq { + bool operator()(const TilePos& x, const TilePos& y) const { + return TilePos::eq_test(x, y); + } }; - diff --git a/Minecraft.World/Level/WaterLevelChunk.cpp b/Minecraft.World/Level/WaterLevelChunk.cpp index 58ff234be..ab2661184 100644 --- a/Minecraft.World/Level/WaterLevelChunk.cpp +++ b/Minecraft.World/Level/WaterLevelChunk.cpp @@ -5,155 +5,116 @@ #include "WaterLevelChunk.h" #include "../Headers/net.minecraft.world.level.biome.h" -WaterLevelChunk::WaterLevelChunk(Level *level, byteArray blocks, int x, int z): LevelChunk(level,blocks,x,z) -{ - dontSave = true; - // Set this as fully post-processed, so we don't try and run post-processing on any edge chunks that will overlap into real chunks - terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; +WaterLevelChunk::WaterLevelChunk(Level* level, byteArray blocks, int x, int z) + : LevelChunk(level, blocks, x, z) { + dontSave = true; + // Set this as fully post-processed, so we don't try and run post-processing + // on any edge chunks that will overlap into real chunks + terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | + LevelChunk::sTerrainPostPostProcessed; } -bool WaterLevelChunk::isAt(int x, int z) -{ - return x == this->x && z == this->z; +bool WaterLevelChunk::isAt(int x, int z) { + return x == this->x && z == this->z; } -void WaterLevelChunk::recalcBlockLights() -{ +void WaterLevelChunk::recalcBlockLights() {} + +void WaterLevelChunk::recalcHeightmapOnly() {} + +void WaterLevelChunk::recalcHeightmap() {} + +void WaterLevelChunk::lightLava() {} + +bool WaterLevelChunk::setTileAndData(int x, int y, int z, int _tile, + int _data) { + return true; } -void WaterLevelChunk::recalcHeightmapOnly() -{ +bool WaterLevelChunk::setTile(int x, int y, int z, int _tile) { return true; } + +bool WaterLevelChunk::setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged) { + *maskedBitsChanged = true; + return true; } -void WaterLevelChunk::recalcHeightmap() -{ +void WaterLevelChunk::setBrightness(LightLayer::variety layer, int x, int y, + int z, int brightness) {} + +void WaterLevelChunk::addEntity(std::shared_ptr e) {} + +void WaterLevelChunk::removeEntity(std::shared_ptr e) {} + +void WaterLevelChunk::removeEntity(std::shared_ptr e, int yc) {} + +void WaterLevelChunk::skyBrightnessChanged() {} + +std::shared_ptr WaterLevelChunk::getTileEntity(int x, int y, + int z) { + return std::shared_ptr(); } -void WaterLevelChunk::lightLava() -{ -} +void WaterLevelChunk::addTileEntity(std::shared_ptr te) {} -bool WaterLevelChunk::setTileAndData(int x, int y, int z, int _tile, int _data) -{ - return true; -} +void WaterLevelChunk::setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity) {} -bool WaterLevelChunk::setTile(int x, int y, int z, int _tile) -{ - return true; -} +void WaterLevelChunk::removeTileEntity(int x, int y, int z) {} -bool WaterLevelChunk::setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged) -{ - *maskedBitsChanged = true; - return true; -} +void WaterLevelChunk::load() {} -void WaterLevelChunk::setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness) -{ -} +void WaterLevelChunk::unload(bool unloadTileEntities) // 4J - added parameter +{} -void WaterLevelChunk::addEntity(std::shared_ptr e) -{ -} +void WaterLevelChunk::markUnsaved() {} -void WaterLevelChunk::removeEntity(std::shared_ptr e) -{ -} +void WaterLevelChunk::getEntities(std::shared_ptr except, AABB bb, + std::vector >& es) {} -void WaterLevelChunk::removeEntity(std::shared_ptr e, int yc) -{ -} +void WaterLevelChunk::getEntitiesOfClass( + const std::type_info& ec, AABB bb, + std::vector >& es) {} -void WaterLevelChunk::skyBrightnessChanged() -{ -} +int WaterLevelChunk::countEntities() { return 0; } -std::shared_ptr WaterLevelChunk::getTileEntity(int x, int y, int z) -{ - return std::shared_ptr(); -} +bool WaterLevelChunk::shouldSave(bool force) { return false; } -void WaterLevelChunk::addTileEntity(std::shared_ptr te) -{ -} +void WaterLevelChunk::setBlocks(byteArray newBlocks, int sub) {} -void WaterLevelChunk::setTileEntity(int x, int y, int z, std::shared_ptr tileEntity) -{ -} - -void WaterLevelChunk::removeTileEntity(int x, int y, int z) -{ -} - -void WaterLevelChunk::load() -{ -} - -void WaterLevelChunk::unload(bool unloadTileEntities) // 4J - added parameter -{ -} - -void WaterLevelChunk::markUnsaved() -{ -} - -void WaterLevelChunk::getEntities(std::shared_ptr except, AABB bb, std::vector > &es) -{ -} - -void WaterLevelChunk::getEntitiesOfClass(const std::type_info& ec, AABB bb, std::vector > &es) -{ -} - -int WaterLevelChunk::countEntities() -{ - return 0; -} - -bool WaterLevelChunk::shouldSave(bool force) -{ - return false; -} - -void WaterLevelChunk::setBlocks(byteArray newBlocks, int sub) -{ -} - -int WaterLevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting/* = true*/) -{ +int WaterLevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, + int x1, int y1, int z1, int p, + bool includeLighting /* = true*/) { int xs = x1 - x0; int ys = y1 - y0; int zs = z1 - z0; int s = xs * ys * zs; - if( includeLighting ) - { - return s + s / 2 * 3; - } - else - { - return s + s / 2; - } + if (includeLighting) { + return s + s / 2 * 3; + } else { + return s + s / 2; + } } -bool WaterLevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p) -{ - return false; +bool WaterLevelChunk::testSetBlocksAndData(byteArray data, int x0, int y0, + int z0, int x1, int y1, int z1, + int p) { + return false; } -Random *WaterLevelChunk::getRandom(__int64 l) -{ - return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + z * z * 4392871l + z * 389711) ^ l); +Random* WaterLevelChunk::getRandom(__int64 l) { + return new Random((level->getSeed() + x * x * 4987142 + x * 5947611 + + z * z * 4392871l + z * 389711) ^ + l); } -void WaterLevelChunk::setLevelChunkBrightness(LightLayer::variety layer, int x, int y, int z, int brightness) -{ - LevelChunk::setBrightness(layer, x, y, z, brightness); +void WaterLevelChunk::setLevelChunkBrightness(LightLayer::variety layer, int x, + int y, int z, int brightness) { + LevelChunk::setBrightness(layer, x, y, z, brightness); } -Biome *WaterLevelChunk::getBiome(int x, int z, BiomeSource *biomeSource) -{ - return NULL; +Biome* WaterLevelChunk::getBiome(int x, int z, BiomeSource* biomeSource) { + return NULL; } diff --git a/Minecraft.World/Level/WaterLevelChunk.h b/Minecraft.World/Level/WaterLevelChunk.h index 23bd5eedd..c4cb39c30 100644 --- a/Minecraft.World/Level/WaterLevelChunk.h +++ b/Minecraft.World/Level/WaterLevelChunk.h @@ -4,42 +4,52 @@ class Level; -class WaterLevelChunk: public LevelChunk -{ +class WaterLevelChunk : public LevelChunk { public: - using LevelChunk::getEntities; - using LevelChunk::getEntitiesOfClass; + using LevelChunk::getEntities; + using LevelChunk::getEntitiesOfClass; - WaterLevelChunk(Level *level, byteArray blocks, int x, int z); - bool isAt(int x, int z); - void recalcBlockLights(); - void recalcHeightmapOnly(); - void recalcHeightmap(); - void lightLava(); - bool setTileAndData(int x, int y, int z, int _tile, int _data); - bool setTile(int x, int y, int z, int _tile); - bool setData(int x, int y, int z, int val, int mask, bool *maskedBitsChanged); // 4J added mask - void setBrightness(LightLayer::variety layer, int x, int y, int z, int brightness); - void setLevelChunkBrightness(LightLayer::variety layer, int x, int y, int z, int brightness); // 4J added - calls the setBrightness method of the parent class - void addEntity(std::shared_ptr e); - void removeEntity(std::shared_ptr e); - void removeEntity(std::shared_ptr e, int yc); - void skyBrightnessChanged(); - std::shared_ptr getTileEntity(int x, int y, int z); - void addTileEntity(std::shared_ptr te); - void setTileEntity(int x, int y, int z, std::shared_ptr tileEntity); - void removeTileEntity(int x, int y, int z); - void load(); - void unload(bool unloadTileEntities) ; // 4J - added parameter - void markUnsaved(); - void getEntities(std::shared_ptr except, AABB bb, std::vector > &es); - void getEntitiesOfClass(const std::type_info& ec, AABB bb, std::vector > &es); - int countEntities(); - bool shouldSave(bool force); - void setBlocks(byteArray newBlocks, int sub); - int setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, bool includeLighting = true); // 4J - added includeLighting parameter; - bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p); - Random *getRandom(__int64 l); - virtual Biome *getBiome(int x, int z, BiomeSource *biomeSource); - virtual void reSyncLighting() {}; // 4J added + WaterLevelChunk(Level* level, byteArray blocks, int x, int z); + bool isAt(int x, int z); + void recalcBlockLights(); + void recalcHeightmapOnly(); + void recalcHeightmap(); + void lightLava(); + bool setTileAndData(int x, int y, int z, int _tile, int _data); + bool setTile(int x, int y, int z, int _tile); + bool setData(int x, int y, int z, int val, int mask, + bool* maskedBitsChanged); // 4J added mask + void setBrightness(LightLayer::variety layer, int x, int y, int z, + int brightness); + void setLevelChunkBrightness( + LightLayer::variety layer, int x, int y, int z, + int brightness); // 4J added - calls the setBrightness method of the + // parent class + void addEntity(std::shared_ptr e); + void removeEntity(std::shared_ptr e); + void removeEntity(std::shared_ptr e, int yc); + void skyBrightnessChanged(); + std::shared_ptr getTileEntity(int x, int y, int z); + void addTileEntity(std::shared_ptr te); + void setTileEntity(int x, int y, int z, + std::shared_ptr tileEntity); + void removeTileEntity(int x, int y, int z); + void load(); + void unload(bool unloadTileEntities); // 4J - added parameter + void markUnsaved(); + void getEntities(std::shared_ptr except, AABB bb, + std::vector >& es); + void getEntitiesOfClass(const std::type_info& ec, AABB bb, + std::vector >& es); + int countEntities(); + bool shouldSave(bool force); + void setBlocks(byteArray newBlocks, int sub); + int setBlocksAndData( + byteArray data, int x0, int y0, int z0, int x1, int y1, int z1, int p, + bool includeLighting = true); // 4J - added includeLighting parameter; + bool testSetBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, + int y1, int z1, int p); + Random* getRandom(__int64 l); + virtual Biome* getBiome(int x, int z, BiomeSource* biomeSource); + virtual void reSyncLighting() {}; // 4J added }; diff --git a/Minecraft.World/Network/Connection.cpp b/Minecraft.World/Network/Connection.cpp index fb4a4336b..3529fadf1 100644 --- a/Minecraft.World/Network/Connection.cpp +++ b/Minecraft.World/Network/Connection.cpp @@ -17,315 +17,323 @@ int Connection::writeThreads = 0; int Connection::readSizes[256]; int Connection::writeSizes[256]; -void Connection::_init() -{ -// printf("Con:0x%x init\n",this); - InitializeCriticalSection(&writeLock); - InitializeCriticalSection(&threadCounterLock); - InitializeCriticalSection(&incoming_cs); +void Connection::_init() { + // printf("Con:0x%x init\n",this); + InitializeCriticalSection(&writeLock); + InitializeCriticalSection(&threadCounterLock); + InitializeCriticalSection(&incoming_cs); - running = true; - quitting = false; - disconnected = false; - disconnectReason = DisconnectPacket::eDisconnect_None; - noInputTicks = 0; - estimatedRemaining = 0; - fakeLag = 0; - slowWriteDelay = 50; - - tickCount = 0; + running = true; + quitting = false; + disconnected = false; + disconnectReason = DisconnectPacket::eDisconnect_None; + noInputTicks = 0; + estimatedRemaining = 0; + fakeLag = 0; + slowWriteDelay = 50; + tickCount = 0; } // 4J Jev, need to delete the critical section. -Connection::~Connection() -{ - // 4J Stu - Just to be sure, make sure the read and write threads terminate themselves before the connection object is destroyed - running = false; - if( dis ) dis->close(); // The input stream needs closed before the readThread, or the readThread - // may get stuck whilst blocking waiting on a read - readThread->WaitForCompletion(INFINITE); - writeThread->WaitForCompletion(INFINITE); - DeleteCriticalSection(&writeLock); - DeleteCriticalSection(&threadCounterLock); - DeleteCriticalSection(&incoming_cs); - delete m_hWakeReadThread; - delete m_hWakeWriteThread; +Connection::~Connection() { + // 4J Stu - Just to be sure, make sure the read and write threads terminate + // themselves before the connection object is destroyed + running = false; + if (dis) + dis->close(); // The input stream needs closed before the readThread, + // or the readThread may get stuck whilst blocking + // waiting on a read + readThread->WaitForCompletion(INFINITE); + writeThread->WaitForCompletion(INFINITE); + DeleteCriticalSection(&writeLock); + DeleteCriticalSection(&threadCounterLock); + DeleteCriticalSection(&incoming_cs); + delete m_hWakeReadThread; + delete m_hWakeWriteThread; - // These should all have been destroyed in close() but no harm in checking again - delete byteArrayDos; - byteArrayDos = NULL; - delete baos; - baos = NULL; - if( bufferedDos ) - { - bufferedDos->deleteChildStream(); - delete bufferedDos; - bufferedDos = NULL; - } - delete dis; - dis = NULL; + // These should all have been destroyed in close() but no harm in checking + // again + delete byteArrayDos; + byteArrayDos = NULL; + delete baos; + baos = NULL; + if (bufferedDos) { + bufferedDos->deleteChildStream(); + delete bufferedDos; + bufferedDos = NULL; + } + delete dis; + dis = NULL; } -Connection::Connection(Socket *socket, const std::wstring& id, PacketListener *packetListener) // throws IOException +Connection::Connection(Socket* socket, const std::wstring& id, + PacketListener* packetListener) // throws IOException { - _init(); + _init(); - this->socket = socket; + this->socket = socket; - address = socket->getRemoteSocketAddress(); + address = socket->getRemoteSocketAddress(); - this->packetListener = packetListener; + this->packetListener = packetListener; - //try { - socket->setSoTimeout(30000); - socket->setTrafficClass(IPTOS_THROUGHPUT | IPTOS_LOWDELAY); + // try { + socket->setSoTimeout(30000); + socket->setTrafficClass(IPTOS_THROUGHPUT | IPTOS_LOWDELAY); - /* 4J JEV no catch - } catch (SocketException e) { - // catching this exception because it (apparently?) causes problems - // on OSX Tiger - System.err.println(e.getMessage()); - }*/ + /* 4J JEV no catch + } catch (SocketException e) { + // catching this exception because it (apparently?) causes problems + // on OSX Tiger + System.err.println(e.getMessage()); + }*/ - dis = new DataInputStream(socket->getInputStream(packetListener->isServerPacketListener())); - - sos = socket->getOutputStream(packetListener->isServerPacketListener()); - bufferedDos = new DataOutputStream(new BufferedOutputStream(sos, SEND_BUFFER_SIZE)); - baos = new ByteArrayOutputStream( SEND_BUFFER_SIZE ); - byteArrayDos = new DataOutputStream(baos); + dis = new DataInputStream( + socket->getInputStream(packetListener->isServerPacketListener())); - m_hWakeReadThread = new C4JThread::Event; - m_hWakeWriteThread = new C4JThread::Event; + sos = socket->getOutputStream(packetListener->isServerPacketListener()); + bufferedDos = + new DataOutputStream(new BufferedOutputStream(sos, SEND_BUFFER_SIZE)); + baos = new ByteArrayOutputStream(SEND_BUFFER_SIZE); + byteArrayDos = new DataOutputStream(baos); - const char *szId = wstringtofilename(id); - char readThreadName[256]; - char writeThreadName[256]; - sprintf(readThreadName,"%s read\n",szId); - sprintf(writeThreadName,"%s write\n",szId); + m_hWakeReadThread = new C4JThread::Event; + m_hWakeWriteThread = new C4JThread::Event; - readThread = new C4JThread(runRead, (void*)this, readThreadName, READ_STACK_SIZE); - writeThread = new C4JThread(runWrite, this, writeThreadName, WRITE_STACK_SIZE); - readThread->SetProcessor(CPU_CORE_CONNECTIONS); - writeThread->SetProcessor(CPU_CORE_CONNECTIONS ); + const char* szId = wstringtofilename(id); + char readThreadName[256]; + char writeThreadName[256]; + sprintf(readThreadName, "%s read\n", szId); + sprintf(writeThreadName, "%s write\n", szId); + + readThread = + new C4JThread(runRead, (void*)this, readThreadName, READ_STACK_SIZE); + writeThread = + new C4JThread(runWrite, this, writeThreadName, WRITE_STACK_SIZE); + readThread->SetProcessor(CPU_CORE_CONNECTIONS); + writeThread->SetProcessor(CPU_CORE_CONNECTIONS); #ifdef __ORBIS__ - readThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. - writeThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + readThread->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for + // Matching 2, and that priority of that + // seems to be always at default no + // matter what we set it to. Prioritise + // this below Matching 2. + writeThread->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for + // Matching 2, and that priority of that + // seems to be always at default no + // matter what we set it to. Prioritise + // this below Matching 2. #endif - readThread->Run(); - writeThread->Run(); + readThread->Run(); + writeThread->Run(); + /* 4J JEV, java: + new Thread(std::wstring(id).append(L" read thread")) { - /* 4J JEV, java: - new Thread(std::wstring(id).append(L" read thread")) { + }; - }; + writeThread = new Thread(id + " write thread") { + public void run() { - writeThread = new Thread(id + " write thread") { - public void run() { + }; - }; - - readThread->start(); - writeThread->start(); - */ + readThread->start(); + writeThread->start(); + */ } - -void Connection::setListener(PacketListener *packetListener) -{ - this->packetListener = packetListener; +void Connection::setListener(PacketListener* packetListener) { + this->packetListener = packetListener; } -void Connection::send(std::shared_ptr packet) -{ - if (quitting) return; +void Connection::send(std::shared_ptr packet) { + if (quitting) return; - MemSect(15); - // 4J Jev, synchronized (&writeLock) - EnterCriticalSection(&writeLock); + MemSect(15); + // 4J Jev, synchronized (&writeLock) + EnterCriticalSection(&writeLock); - estimatedRemaining += packet->getEstimatedSize() + 1; - if (packet->shouldDelay) - { - // 4J We have delayed it enough by putting it in the slow queue, so don't delay when we actually send it - packet->shouldDelay = false; - outgoing_slow.push(packet); - } - else - { - outgoing.push(packet); - } + estimatedRemaining += packet->getEstimatedSize() + 1; + if (packet->shouldDelay) { + // 4J We have delayed it enough by putting it in the slow queue, so + // don't delay when we actually send it + packet->shouldDelay = false; + outgoing_slow.push(packet); + } else { + outgoing.push(packet); + } - // 4J Jev, end synchronized. - LeaveCriticalSection(&writeLock); - MemSect(0); + // 4J Jev, end synchronized. + LeaveCriticalSection(&writeLock); + MemSect(0); } - -void Connection::queueSend(std::shared_ptr packet) -{ - if (quitting) return; - estimatedRemaining += packet->getEstimatedSize() + 1; - outgoing_slow.push(packet); +void Connection::queueSend(std::shared_ptr packet) { + if (quitting) return; + estimatedRemaining += packet->getEstimatedSize() + 1; + outgoing_slow.push(packet); } -bool Connection::writeTick() -{ - bool didSomething = false; +bool Connection::writeTick() { + bool didSomething = false; - // 4J Stu - If the connection is closed and the output stream has been deleted - if(bufferedDos==NULL || byteArrayDos==NULL) - return didSomething; + // 4J Stu - If the connection is closed and the output stream has been + // deleted + if (bufferedDos == NULL || byteArrayDos == NULL) return didSomething; - // try { - if (!outgoing.empty() && (fakeLag == 0 || System::currentTimeMillis() - outgoing.front()->createTime >= fakeLag)) - { - std::shared_ptr packet; + // try { + if (!outgoing.empty() && + (fakeLag == 0 || + System::currentTimeMillis() - outgoing.front()->createTime >= + fakeLag)) { + std::shared_ptr packet; - EnterCriticalSection(&writeLock); + EnterCriticalSection(&writeLock); - packet = outgoing.front(); - outgoing.pop(); - estimatedRemaining -= packet->getEstimatedSize() + 1; + packet = outgoing.front(); + outgoing.pop(); + estimatedRemaining -= packet->getEstimatedSize() + 1; - LeaveCriticalSection(&writeLock); + LeaveCriticalSection(&writeLock); - Packet::writePacket(packet, bufferedDos); + Packet::writePacket(packet, bufferedDos); #ifdef __linux__ - bufferedDos->flush(); // Ensure buffered data reaches socket before any other writes + bufferedDos->flush(); // Ensure buffered data reaches socket before any + // other writes #endif #ifndef _CONTENT_PACKAGE - // 4J Added for debugging - if( !socket->isLocal() ) - Packet::recordOutgoingPacket(packet); + // 4J Added for debugging + if (!socket->isLocal()) Packet::recordOutgoingPacket(packet); #endif - // 4J Stu - Changed this so that rather than writing to the network stream through a buffered stream we want to: - // a) Only push whole "game" packets to QNet, rather than amalgamated chunks of data that may include many packets, and partial packets - // b) To be able to change the priority and queue of a packet if required - //sos->writeWithFlags( baos->buf, 0, baos->size(), 0 ); - //baos->reset(); + // 4J Stu - Changed this so that rather than writing to the network + // stream through a buffered stream we want to: a) Only push whole + // "game" packets to QNet, rather than amalgamated chunks of data that + // may include many packets, and partial packets b) To be able to change + // the priority and queue of a packet if required + // sos->writeWithFlags( baos->buf, 0, baos->size(), 0 ); + // baos->reset(); - writeSizes[packet->getId()] += packet->getEstimatedSize() + 1; - didSomething = true; - } + writeSizes[packet->getId()] += packet->getEstimatedSize() + 1; + didSomething = true; + } - if ((slowWriteDelay-- <= 0) && !outgoing_slow.empty() && (fakeLag == 0 || System::currentTimeMillis() - outgoing_slow.front()->createTime >= fakeLag)) - { - std::shared_ptr packet; + if ((slowWriteDelay-- <= 0) && !outgoing_slow.empty() && + (fakeLag == 0 || + System::currentTimeMillis() - outgoing_slow.front()->createTime >= + fakeLag)) { + std::shared_ptr packet; - //synchronized (writeLock) { + // synchronized (writeLock) { - EnterCriticalSection(&writeLock); + EnterCriticalSection(&writeLock); - packet = outgoing_slow.front(); - outgoing_slow.pop(); - estimatedRemaining -= packet->getEstimatedSize() + 1; + packet = outgoing_slow.front(); + outgoing_slow.pop(); + estimatedRemaining -= packet->getEstimatedSize() + 1; - LeaveCriticalSection(&writeLock); + LeaveCriticalSection(&writeLock); - // If the shouldDelay flag is still set at this point then we want to write it to QNet as a single packet with priority flags - // Otherwise just buffer the packet with other outgoing packets as the java game did + // If the shouldDelay flag is still set at this point then we want to + // write it to QNet as a single packet with priority flags Otherwise + // just buffer the packet with other outgoing packets as the java game + // did #ifdef __linux__ - // Linux fix: For local connections, always use bufferedDos to avoid byte interleaving between - // the BufferedOutputStream buffer and direct sos writes. The shouldDelay/writeWithFlags path - // writes directly to sos, which can inject bytes BEFORE unflushed bufferedDos data. - Packet::writePacket(packet, bufferedDos); - bufferedDos->flush(); // Ensure data reaches socket immediately for delayed packets + // Linux fix: For local connections, always use bufferedDos to avoid + // byte interleaving between the BufferedOutputStream buffer and direct + // sos writes. The shouldDelay/writeWithFlags path writes directly to + // sos, which can inject bytes BEFORE unflushed bufferedDos data. + Packet::writePacket(packet, bufferedDos); + bufferedDos->flush(); // Ensure data reaches socket immediately for + // delayed packets #else - if(packet->shouldDelay) - { - Packet::writePacket(packet, byteArrayDos); + if (packet->shouldDelay) { + Packet::writePacket(packet, byteArrayDos); - // 4J Stu - Changed this so that rather than writing to the network stream through a buffered stream we want to: - // a) Only push whole "game" packets to QNet, rather than amalgamated chunks of data that may include many packets, and partial packets - // b) To be able to change the priority and queue of a packet if required - int flags = QNET_SENDDATA_LOW_PRIORITY | QNET_SENDDATA_SECONDARY; - sos->writeWithFlags( baos->buf, 0, baos->size(), flags ); - baos->reset(); - } - else - { - Packet::writePacket(packet, bufferedDos); - } + // 4J Stu - Changed this so that rather than writing to the network + // stream through a buffered stream we want to: a) Only push whole + // "game" packets to QNet, rather than amalgamated chunks of data + // that may include many packets, and partial packets b) To be able + // to change the priority and queue of a packet if required + int flags = QNET_SENDDATA_LOW_PRIORITY | QNET_SENDDATA_SECONDARY; + sos->writeWithFlags(baos->buf, 0, baos->size(), flags); + baos->reset(); + } else { + Packet::writePacket(packet, bufferedDos); + } #endif #ifndef _CONTENT_PACKAGE - // 4J Added for debugging - if( !socket->isLocal() ) - Packet::recordOutgoingPacket(packet); -#endif + // 4J Added for debugging + if (!socket->isLocal()) Packet::recordOutgoingPacket(packet); +#endif - writeSizes[packet->getId()] += packet->getEstimatedSize() + 1; - slowWriteDelay = 0; - didSomething = true; - } - /* 4J JEV, removed try/catch - } catch (Exception e) { - if (!disconnected) handleException(e); - return false; - } */ + writeSizes[packet->getId()] += packet->getEstimatedSize() + 1; + slowWriteDelay = 0; + didSomething = true; + } + /* 4J JEV, removed try/catch + } catch (Exception e) { + if (!disconnected) handleException(e); + return false; + } */ - return didSomething; + return didSomething; } - -void Connection::flush() -{ - // TODO 4J Stu - How to interrupt threads? Or do we need to change the multithreaded functions a bit more - //readThread.interrupt(); - //writeThread.interrupt(); - m_hWakeReadThread->Set(); - m_hWakeWriteThread->Set(); +void Connection::flush() { + // TODO 4J Stu - How to interrupt threads? Or do we need to change the + // multithreaded functions a bit more + // readThread.interrupt(); + // writeThread.interrupt(); + m_hWakeReadThread->Set(); + m_hWakeWriteThread->Set(); } +bool Connection::readTick() { + bool didSomething = false; -bool Connection::readTick() -{ - bool didSomething = false; + // 4J Stu - If the connection has closed and the input stream has been + // deleted + if (dis == NULL) return didSomething; - // 4J Stu - If the connection has closed and the input stream has been deleted - if(dis==NULL) - return didSomething; + // try { - //try { + std::shared_ptr packet = + Packet::readPacket(dis, packetListener->isServerPacketListener()); - std::shared_ptr packet = Packet::readPacket(dis, packetListener->isServerPacketListener()); + if (packet != NULL) { + readSizes[packet->getId()] += packet->getEstimatedSize() + 1; + EnterCriticalSection(&incoming_cs); + if (!quitting) { + incoming.push(packet); + } + LeaveCriticalSection(&incoming_cs); + didSomething = true; + } else { + // printf("Con:0x%x readTick close EOS\n",this); - if (packet != NULL) - { - readSizes[packet->getId()] += packet->getEstimatedSize() + 1; - EnterCriticalSection(&incoming_cs); - if(!quitting) - { - incoming.push(packet); - } - LeaveCriticalSection(&incoming_cs); - didSomething = true; - } - else - { -// printf("Con:0x%x readTick close EOS\n",this); + // 4J Stu - Remove this line + // Fix for #10410 - UI: If the player is removed from a splitscreened + // host�s game, the next game that player joins will produce a message + // stating that the host has left. + // close(DisconnectPacket::eDisconnect_EndOfStream); + } - // 4J Stu - Remove this line - // Fix for #10410 - UI: If the player is removed from a splitscreened host�s game, the next game that player joins will produce a message stating that the host has left. - //close(DisconnectPacket::eDisconnect_EndOfStream); - } + /* 4J JEV, removed try/catch + } catch (Exception e) { + if (!disconnected) handleException(e); + return false; + } */ - - /* 4J JEV, removed try/catch - } catch (Exception e) { - if (!disconnected) handleException(e); - return false; - } */ - - return didSomething; + return didSomething; } - /* 4J JEV, removed try/catch void handleException(Exception e) { @@ -333,327 +341,317 @@ e.printStackTrace(); close("disconnect.genericReason", "Internal exception: " + e.toString()); }*/ +void Connection::close(DisconnectPacket::eDisconnectReason reason) { + fprintf(stderr, "[CONN] close called with reason=%d on connection=%p\n", + reason, (void*)this); + if (!running) return; + fprintf(stderr, "[CONN] close proceeding (was running) on connection=%p\n", + (void*)this); + disconnected = true; -void Connection::close(DisconnectPacket::eDisconnectReason reason) -{ - fprintf(stderr, "[CONN] close called with reason=%d on connection=%p\n", reason, (void*)this); - if (!running) return; - fprintf(stderr, "[CONN] close proceeding (was running) on connection=%p\n", (void*)this); - disconnected = true; + disconnectReason = reason; + disconnectReasonObjects = NULL; - disconnectReason = reason; - disconnectReasonObjects = NULL; + // int count = 0, sum = 0, i = first; + // va_list marker; + // + // va_start( marker, first ); + // while( i != -1 ) + // { + // sum += i; + // count++; + // i = va_arg( marker, int); + // } + // va_end( marker ); + // return( sum ? (sum / count) : 0 ); - // int count = 0, sum = 0, i = first; - // va_list marker; - // - // va_start( marker, first ); - // while( i != -1 ) - // { - // sum += i; - // count++; - // i = va_arg( marker, int); - // } - // va_end( marker ); - // return( sum ? (sum / count) : 0 ); + // CreateThread(NULL, 0, runClose, this, 0, NULL); + running = false; -// CreateThread(NULL, 0, runClose, this, 0, NULL); + if (dis) + dis->close(); // The input stream needs closed before the readThread, + // or the readThread may get stuck whilst blocking + // waiting on a read - running = false; + // Make sure that the read & write threads are dead before we go and kill + // the streams that they depend on + readThread->WaitForCompletion(INFINITE); + writeThread->WaitForCompletion(INFINITE); - if( dis ) dis->close(); // The input stream needs closed before the readThread, or the readThread - // may get stuck whilst blocking waiting on a read - - // Make sure that the read & write threads are dead before we go and kill the streams that they depend on - readThread->WaitForCompletion(INFINITE); - writeThread->WaitForCompletion(INFINITE); - - delete dis; - dis = NULL; - if( bufferedDos ) - { - bufferedDos->close(); - bufferedDos->deleteChildStream(); - delete bufferedDos; - bufferedDos = NULL; - } - if( byteArrayDos ) - { - byteArrayDos->close(); - delete byteArrayDos; - byteArrayDos = NULL; - } - if( socket ) - { - socket->close(packetListener->isServerPacketListener()); - socket = NULL; - } + delete dis; + dis = NULL; + if (bufferedDos) { + bufferedDos->close(); + bufferedDos->deleteChildStream(); + delete bufferedDos; + bufferedDos = NULL; + } + if (byteArrayDos) { + byteArrayDos->close(); + delete byteArrayDos; + byteArrayDos = NULL; + } + if (socket) { + socket->close(packetListener->isServerPacketListener()); + socket = NULL; + } } -void Connection::tick() -{ - if (estimatedRemaining > 1 * 1024 * 1024) - { - close(DisconnectPacket::eDisconnect_Overflow); - } - EnterCriticalSection(&incoming_cs); - bool empty = incoming.empty(); - LeaveCriticalSection(&incoming_cs); - if (empty) - { +void Connection::tick() { + if (estimatedRemaining > 1 * 1024 * 1024) { + close(DisconnectPacket::eDisconnect_Overflow); + } + EnterCriticalSection(&incoming_cs); + bool empty = incoming.empty(); + LeaveCriticalSection(&incoming_cs); + if (empty) { #if CONNECTION_ENABLE_TIMEOUT_DISCONNECT - if (noInputTicks++ == MAX_TICKS_WITHOUT_INPUT) - { - close(DisconnectPacket::eDisconnect_TimeOut); - } + if (noInputTicks++ == MAX_TICKS_WITHOUT_INPUT) { + close(DisconnectPacket::eDisconnect_TimeOut); + } #endif - } - // 4J Stu - Moved this a bit later in the function to stop the race condition of Disconnect packets not being processed when local client leaves - //else if( socket && socket->isClosing() ) - //{ - // close(DisconnectPacket::eDisconnect_Closed); - //} - else - { - noInputTicks = 0; - - } - - // 4J Added - Send a KeepAlivePacket every now and then to ensure that our read and write threads don't timeout - tickCount++; - if (tickCount % 20 == 0) - { - send( std::shared_ptr( new KeepAlivePacket() ) ); + } + // 4J Stu - Moved this a bit later in the function to stop the race + // condition of Disconnect packets not being processed when local client + // leaves + // else if( socket && socket->isClosing() ) + //{ + // close(DisconnectPacket::eDisconnect_Closed); + //} + else { + noInputTicks = 0; } - // 4J Stu - 1.8.2 changed from 100 to 1000 - int max = 1000; + // 4J Added - Send a KeepAlivePacket every now and then to ensure that our + // read and write threads don't timeout + tickCount++; + if (tickCount % 20 == 0) { + send(std::shared_ptr(new KeepAlivePacket())); + } - // 4J-PB - NEEDS CHANGED!!! - // If we can call connection.close from within a packet->handle, then we can lockup because the loop below has locked incoming_cs, and the connection.close will flag the read and write threads for the connection to close. - // they are running on other threads, and will try to lock incoming_cs - // We got this with a pre-login packet of a player who wasn't allowed to play due to parental controls, so was kicked out - // This has been changed to use a eAppAction_ExitPlayerPreLogin which will run in the main loop, so the connection will not be ticked at that point + // 4J Stu - 1.8.2 changed from 100 to 1000 + int max = 1000; + // 4J-PB - NEEDS CHANGED!!! + // If we can call connection.close from within a packet->handle, then we can + // lockup because the loop below has locked incoming_cs, and the + // connection.close will flag the read and write threads for the connection + // to close. they are running on other threads, and will try to lock + // incoming_cs We got this with a pre-login packet of a player who wasn't + // allowed to play due to parental controls, so was kicked out This has been + // changed to use a eAppAction_ExitPlayerPreLogin which will run in the main + // loop, so the connection will not be ticked at that point - EnterCriticalSection(&incoming_cs); - // 4J Stu - If disconnected, then we shouldn't process incoming packets - std::vector< std::shared_ptr > packetsToHandle; - while (!disconnected && !g_NetworkManager.IsLeavingGame() && g_NetworkManager.IsInSession() && !incoming.empty() && max-- >= 0) - { - std::shared_ptr packet = incoming.front(); - packetsToHandle.push_back(packet); - incoming.pop(); - } - LeaveCriticalSection(&incoming_cs); + EnterCriticalSection(&incoming_cs); + // 4J Stu - If disconnected, then we shouldn't process incoming packets + std::vector > packetsToHandle; + while (!disconnected && !g_NetworkManager.IsLeavingGame() && + g_NetworkManager.IsInSession() && !incoming.empty() && max-- >= 0) { + std::shared_ptr packet = incoming.front(); + packetsToHandle.push_back(packet); + incoming.pop(); + } + LeaveCriticalSection(&incoming_cs); - // MGH - moved the packet handling outside of the incoming_cs block, as it was locking up sometimes when disconnecting - for(int i=0; igetId()); - packetsToHandle[i]->handle(packetListener); - PIXEndNamedEvent(); - } - flush(); + // MGH - moved the packet handling outside of the incoming_cs block, as it + // was locking up sometimes when disconnecting + for (int i = 0; i < packetsToHandle.size(); i++) { + PIXBeginNamedEvent(0, "Handling packet %d\n", + packetsToHandle[i]->getId()); + packetsToHandle[i]->handle(packetListener); + PIXEndNamedEvent(); + } + flush(); - // 4J Stu - Moved this a bit later in the function to stop the race condition of Disconnect packets not being processed when local client leaves - if( socket && socket->isClosing() ) - { - close(DisconnectPacket::eDisconnect_Closed); - } + // 4J Stu - Moved this a bit later in the function to stop the race + // condition of Disconnect packets not being processed when local client + // leaves + if (socket && socket->isClosing()) { + close(DisconnectPacket::eDisconnect_Closed); + } - // 4J - split the following condition (used to be disconnect && iscoming.empty()) so we can wrap the access in a critical section - if (disconnected) - { - EnterCriticalSection(&incoming_cs); - bool empty = incoming.empty(); - LeaveCriticalSection(&incoming_cs); - if( empty ) - { - packetListener->onDisconnect(disconnectReason, disconnectReasonObjects); - disconnected = false; // 4J added - don't keep sending this every tick - } - } + // 4J - split the following condition (used to be disconnect && + // iscoming.empty()) so we can wrap the access in a critical section + if (disconnected) { + EnterCriticalSection(&incoming_cs); + bool empty = incoming.empty(); + LeaveCriticalSection(&incoming_cs); + if (empty) { + packetListener->onDisconnect(disconnectReason, + disconnectReasonObjects); + disconnected = + false; // 4J added - don't keep sending this every tick + } + } } -SocketAddress *Connection::getRemoteAddress() -{ - return (SocketAddress *) address; +SocketAddress* Connection::getRemoteAddress() { + return (SocketAddress*)address; } -void Connection::sendAndQuit() -{ - if (quitting) - { - return; - } -// printf("Con:0x%x send & quit\n",this); - flush(); - quitting = true; - // TODO 4J Stu - How to interrupt threads? Or do we need to change the multithreaded functions a bit more - //readThread.interrupt(); +void Connection::sendAndQuit() { + if (quitting) { + return; + } + // printf("Con:0x%x send & quit\n",this); + flush(); + quitting = true; + // TODO 4J Stu - How to interrupt threads? Or do we need to change the + // multithreaded functions a bit more + // readThread.interrupt(); #if 1 - // 4J - this used to be in a thread but not sure why, and is causing trouble for us if we kill the connection - // whilst the thread is still expecting to be able to send a packet a couple of seconds after starting it - if (running) - { - // 4J TODO writeThread.interrupt(); - close(DisconnectPacket::eDisconnect_Closed); - } + // 4J - this used to be in a thread but not sure why, and is causing trouble + // for us if we kill the connection whilst the thread is still expecting to + // be able to send a packet a couple of seconds after starting it + if (running) { + // 4J TODO writeThread.interrupt(); + close(DisconnectPacket::eDisconnect_Closed); + } #else - CreateThread(NULL, 0, runSendAndQuit, this, 0, NULL); + CreateThread(NULL, 0, runSendAndQuit, this, 0, NULL); #endif } -int Connection::countDelayedPackets() -{ - return (int)outgoing_slow.size(); -} +int Connection::countDelayedPackets() { return (int)outgoing_slow.size(); } +int Connection::runRead(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::eConnectionReadThreads); + Connection* con = (Connection*)lpParam; -int Connection::runRead(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::eConnectionReadThreads); - Connection *con = (Connection *)lpParam; - - if (con == NULL) - { + if (con == NULL) { #ifdef __PS3__ - ShutdownManager::HasFinished(ShutdownManager::eConnectionReadThreads); + ShutdownManager::HasFinished(ShutdownManager::eConnectionReadThreads); #endif - return 0; - } + return 0; + } - Compression::UseDefaultThreadStorage(); + Compression::UseDefaultThreadStorage(); - CRITICAL_SECTION *cs = &con->threadCounterLock; + CRITICAL_SECTION* cs = &con->threadCounterLock; - EnterCriticalSection(cs); - con->readThreads++; - LeaveCriticalSection(cs); + EnterCriticalSection(cs); + con->readThreads++; + LeaveCriticalSection(cs); - //try { + // try { - MemSect(19); - while (con->running && !con->quitting && ShutdownManager::ShouldRun(ShutdownManager::eConnectionReadThreads)) - { - while (con->readTick()) - ; + MemSect(19); + while ( + con->running && !con->quitting && + ShutdownManager::ShouldRun(ShutdownManager::eConnectionReadThreads)) { + while (con->readTick()); - // try { - //Sleep(100L); - // TODO - 4J Stu - 1.8.2 changes these sleeps to 2L, but not sure whether we should do that as well - con->m_hWakeReadThread->WaitForSignal(100L); - } - MemSect(0); + // try { + // Sleep(100L); + // TODO - 4J Stu - 1.8.2 changes these sleeps to 2L, but not sure + // whether we should do that as well + con->m_hWakeReadThread->WaitForSignal(100L); + } + MemSect(0); - /* 4J JEV, removed try/catch - } catch (InterruptedException e) { - } - } - } finally { - synchronized (threadCounterLock) { - readThreads--; - } - } */ + /* 4J JEV, removed try/catch + } catch (InterruptedException e) { + } + } + } finally { + synchronized (threadCounterLock) { + readThreads--; + } + } */ - ShutdownManager::HasFinished(ShutdownManager::eConnectionReadThreads); - return 0; + ShutdownManager::HasFinished(ShutdownManager::eConnectionReadThreads); + return 0; } -int Connection::runWrite(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::eConnectionWriteThreads); - Connection *con = dynamic_cast((Connection *) lpParam); +int Connection::runWrite(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::eConnectionWriteThreads); + Connection* con = dynamic_cast((Connection*)lpParam); - if (con == NULL) - { - ShutdownManager::HasFinished(ShutdownManager::eConnectionWriteThreads); - return 0; - } + if (con == NULL) { + ShutdownManager::HasFinished(ShutdownManager::eConnectionWriteThreads); + return 0; + } - Compression::UseDefaultThreadStorage(); + Compression::UseDefaultThreadStorage(); - CRITICAL_SECTION *cs = &con->threadCounterLock; + CRITICAL_SECTION* cs = &con->threadCounterLock; - EnterCriticalSection(cs); - con->writeThreads++; - LeaveCriticalSection(cs); + EnterCriticalSection(cs); + con->writeThreads++; + LeaveCriticalSection(cs); - // 4J Stu - Adding this to force us to run through the writeTick at least once after the event is fired - // Otherwise there is a race between the calling thread setting the running flag and this loop checking the condition - unsigned int waitResult = WAIT_TIMEOUT; + // 4J Stu - Adding this to force us to run through the writeTick at least + // once after the event is fired Otherwise there is a race between the + // calling thread setting the running flag and this loop checking the + // condition + unsigned int waitResult = WAIT_TIMEOUT; - while ((con->running || waitResult == 0 ) && ShutdownManager::ShouldRun(ShutdownManager::eConnectionWriteThreads)) - { - while (con->writeTick()) - ; + while ( + (con->running || waitResult == 0) && + ShutdownManager::ShouldRun(ShutdownManager::eConnectionWriteThreads)) { + while (con->writeTick()); - //Sleep(100L); - // TODO - 4J Stu - 1.8.2 changes these sleeps to 2L, but not sure whether we should do that as well - waitResult = con->m_hWakeWriteThread->WaitForSignal(100L); + // Sleep(100L); + // TODO - 4J Stu - 1.8.2 changes these sleeps to 2L, but not sure + // whether we should do that as well + waitResult = con->m_hWakeWriteThread->WaitForSignal(100L); - if (con->bufferedDos != NULL) con->bufferedDos->flush(); - //if (con->byteArrayDos != NULL) con->byteArrayDos->flush(); - } + if (con->bufferedDos != NULL) con->bufferedDos->flush(); + // if (con->byteArrayDos != NULL) con->byteArrayDos->flush(); + } + // 4J was in a finally block. + EnterCriticalSection(cs); + con->writeThreads--; + LeaveCriticalSection(cs); - // 4J was in a finally block. - EnterCriticalSection(cs); - con->writeThreads--; - LeaveCriticalSection(cs); - - ShutdownManager::HasFinished(ShutdownManager::eConnectionWriteThreads); - return 0; + ShutdownManager::HasFinished(ShutdownManager::eConnectionWriteThreads); + return 0; } -int Connection::runClose(void* lpParam) -{ - Connection *con = dynamic_cast((Connection *) lpParam); +int Connection::runClose(void* lpParam) { + Connection* con = dynamic_cast((Connection*)lpParam); - if (con == NULL) return 0; + if (con == NULL) return 0; - //try { + // try { - sleep(2000); - if (con->running) - { - // 4J TODO writeThread.interrupt(); - con->close(DisconnectPacket::eDisconnect_Closed); - } + sleep(2000); + if (con->running) { + // 4J TODO writeThread.interrupt(); + con->close(DisconnectPacket::eDisconnect_Closed); + } - /* 4J Jev, removed try/catch - } catch (Exception e) { - e.printStackTrace(); - } */ + /* 4J Jev, removed try/catch + } catch (Exception e) { + e.printStackTrace(); + } */ - return 1; + return 1; } -int Connection::runSendAndQuit(void* lpParam) -{ - Connection *con = dynamic_cast((Connection *) lpParam); -// printf("Con:0x%x runSendAndQuit\n",con); +int Connection::runSendAndQuit(void* lpParam) { + Connection* con = dynamic_cast((Connection*)lpParam); + // printf("Con:0x%x runSendAndQuit\n",con); - if (con == NULL) return 0; + if (con == NULL) return 0; - //try { + // try { - sleep(2000); - if (con->running) - { - // 4J TODO writeThread.interrupt(); - con->close(DisconnectPacket::eDisconnect_Closed); -// printf("Con:0x%x runSendAndQuit close\n",con); - } + sleep(2000); + if (con->running) { + // 4J TODO writeThread.interrupt(); + con->close(DisconnectPacket::eDisconnect_Closed); + // printf("Con:0x%x runSendAndQuit close\n",con); + } -// printf("Con:0x%x runSendAndQuit end\n",con); - /* 4J Jev, removed try/catch - } catch (Exception e) { - e.printStackTrace(); - } */ + // printf("Con:0x%x runSendAndQuit end\n",con); + /* 4J Jev, removed try/catch + } catch (Exception e) { + e.printStackTrace(); + } */ - return 0; + return 0; } diff --git a/Minecraft.World/Network/Connection.h b/Minecraft.World/Network/Connection.h index 0d321b4ae..068e7fe46 100644 --- a/Minecraft.World/Network/Connection.h +++ b/Minecraft.World/Network/Connection.h @@ -1,6 +1,5 @@ #pragma once - #include "../Platform/stdafx.h" #include #include "../Platform/System.h" @@ -17,122 +16,126 @@ class ByteArrayOutputStream; -class Connection -{ +class Connection { private: - static const int SEND_BUFFER_SIZE = 1024 * 5; + static const int SEND_BUFFER_SIZE = 1024 * 5; public: - static int readThreads, writeThreads; + static int readThreads, writeThreads; private: - static const int MAX_TICKS_WITHOUT_INPUT = 20 * 60; + static const int MAX_TICKS_WITHOUT_INPUT = 20 * 60; public: - static const int IPTOS_LOWCOST = 0x02; - static const int IPTOS_RELIABILITY = 0x04; - static const int IPTOS_THROUGHPUT = 0x08; - static const int IPTOS_LOWDELAY = 0x10; + static const int IPTOS_LOWCOST = 0x02; + static const int IPTOS_RELIABILITY = 0x04; + static const int IPTOS_THROUGHPUT = 0x08; + static const int IPTOS_LOWDELAY = 0x10; private: - Socket *socket; - const SocketAddress *address; - DataInputStream *dis; - DataOutputStream *bufferedDos; // 4J This is the same type of dos the java game has + Socket* socket; + const SocketAddress* address; + DataInputStream* dis; + DataOutputStream* + bufferedDos; // 4J This is the same type of dos the java game has - // 4J Added - DataOutputStream *byteArrayDos; // 4J This dos allows us to write individual packets to the socket - ByteArrayOutputStream *baos; - Socket::SocketOutputStream *sos; + // 4J Added + DataOutputStream* byteArrayDos; // 4J This dos allows us to write + // individual packets to the socket + ByteArrayOutputStream* baos; + Socket::SocketOutputStream* sos; - bool running; + bool running; - std::queue > incoming; // 4J - was using synchronizedList... - CRITICAL_SECTION incoming_cs; // ... now has this critical section - std::queue > outgoing; // 4J - was using synchronizedList - but don't think it is required as usage is wrapped in writeLock critical section - std::queue > outgoing_slow; // 4J - was using synchronizedList - but don't think it is required as usage is wrapped in writeLock critical section - + std::queue > + incoming; // 4J - was using synchronizedList... + CRITICAL_SECTION incoming_cs; // ... now has this critical section + std::queue > + outgoing; // 4J - was using synchronizedList - but don't think it is + // required as usage is wrapped in writeLock critical section + std::queue > + outgoing_slow; // 4J - was using synchronizedList - but don't think it + // is required as usage is wrapped in writeLock critical + // section - PacketListener *packetListener; - bool quitting; + PacketListener* packetListener; + bool quitting; + C4JThread* readThread; + C4JThread* writeThread; - C4JThread* readThread; - C4JThread* writeThread; + C4JThread::Event* m_hWakeReadThread; + C4JThread::Event* m_hWakeWriteThread; - C4JThread::Event* m_hWakeReadThread; - C4JThread::Event* m_hWakeWriteThread; + bool disconnected; + DisconnectPacket::eDisconnectReason disconnectReason; + void** disconnectReasonObjects; // 4J a pointer to an array. - bool disconnected; - DisconnectPacket::eDisconnectReason disconnectReason; - void **disconnectReasonObjects; // 4J a pointer to an array. + int noInputTicks; + int estimatedRemaining; - int noInputTicks; - int estimatedRemaining; - - int tickCount; // 4J Added + int tickCount; // 4J Added public: - static int readSizes[256]; - static int writeSizes[256]; + static int readSizes[256]; + static int writeSizes[256]; - int fakeLag; + int fakeLag; private: - void _init(); + void _init(); - // 4J Jev, these might be better of as private - CRITICAL_SECTION threadCounterLock; - CRITICAL_SECTION writeLock; + // 4J Jev, these might be better of as private + CRITICAL_SECTION threadCounterLock; + CRITICAL_SECTION writeLock; public: - // 4J Jev, need to delete the critical section. - ~Connection(); - Connection(Socket *socket, const std::wstring& id, PacketListener *packetListener); // throws IOException + // 4J Jev, need to delete the critical section. + ~Connection(); + Connection(Socket* socket, const std::wstring& id, + PacketListener* packetListener); // throws IOException - void setListener(PacketListener *packetListener); - void send(std::shared_ptr packet); + void setListener(PacketListener* packetListener); + void send(std::shared_ptr packet); public: - void queueSend(std::shared_ptr packet); + void queueSend(std::shared_ptr packet); private: - int slowWriteDelay; + int slowWriteDelay; - bool writeTick(); + bool writeTick(); public: - void flush(); + void flush(); private: - bool readTick(); + bool readTick(); private: - - /* 4J JEV, removed try/catch - void handleException(Exception e) - { - e.printStackTrace(); - close("disconnect.genericReason", "Internal exception: " + e.toString()); - }*/ + /* 4J JEV, removed try/catch + void handleException(Exception e) + { + e.printStackTrace(); + close("disconnect.genericReason", "Internal exception: " + e.toString()); + }*/ public: - void close(DisconnectPacket::eDisconnectReason reason); + void close(DisconnectPacket::eDisconnectReason reason); - void tick(); + void tick(); - SocketAddress *getRemoteAddress(); + SocketAddress* getRemoteAddress(); - void sendAndQuit(); + void sendAndQuit(); - int countDelayedPackets(); + int countDelayedPackets(); - Socket *getSocket() { return socket; } + Socket* getSocket() { return socket; } private: - static int runRead(void* lpParam); - static int runWrite(void* lpParam); - static int runClose(void* lpParam); - static int runSendAndQuit(void* lpParam); - + static int runRead(void* lpParam); + static int runWrite(void* lpParam); + static int runClose(void* lpParam); + static int runSendAndQuit(void* lpParam); }; diff --git a/Minecraft.World/Network/Packets/AddEntityPacket.cpp b/Minecraft.World/Network/Packets/AddEntityPacket.cpp index 6345bfd78..848b2cbf4 100644 --- a/Minecraft.World/Network/Packets/AddEntityPacket.cpp +++ b/Minecraft.World/Network/Packets/AddEntityPacket.cpp @@ -7,105 +7,106 @@ #include "AddEntityPacket.h" #include - -void AddEntityPacket::_init(std::shared_ptr e, int type, int data, int xp, int yp, int zp, int yRotp, int xRotp) -{ - id = e->entityId; - // 4J Stu - We should add entities at their "last sent" position so that the relative update packets - // put them in the correct place - x = xp;//(int) floor(e->x * 32); - y = yp;//(int) floor(e->y * 32); - z = zp;//(int) floor(e->z * 32); - yRot = static_cast(yRotp); - xRot = static_cast(xRotp); - this->type = type; - this->data = data; - if (data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 - { - double xd = e->xd; - double yd = e->yd; - double zd = e->zd; - double m = 3.9; - if (xd < -m) xd = -m; - if (yd < -m) yd = -m; - if (zd < -m) zd = -m; - if (xd > m) xd = m; - if (yd > m) yd = m; - if (zd > m) zd = m; - xa = (int) (xd * 8000.0); - ya = (int) (yd * 8000.0); - za = (int) (zd * 8000.0); - } +void AddEntityPacket::_init(std::shared_ptr e, int type, int data, + int xp, int yp, int zp, int yRotp, int xRotp) { + id = e->entityId; + // 4J Stu - We should add entities at their "last sent" position so that the + // relative update packets put them in the correct place + x = xp; //(int) floor(e->x * 32); + y = yp; //(int) floor(e->y * 32); + z = zp; //(int) floor(e->z * 32); + yRot = static_cast(yRotp); + xRot = static_cast(xRotp); + this->type = type; + this->data = data; + if (data > -1) // 4J - changed "no data" value to be -1, we can have a + // valid entity id of 0 + { + double xd = e->xd; + double yd = e->yd; + double zd = e->zd; + double m = 3.9; + if (xd < -m) xd = -m; + if (yd < -m) yd = -m; + if (zd < -m) zd = -m; + if (xd > m) xd = m; + if (yd > m) yd = m; + if (zd > m) zd = m; + xa = (int)(xd * 8000.0); + ya = (int)(yd * 8000.0); + za = (int)(zd * 8000.0); + } } -AddEntityPacket::AddEntityPacket() -{ +AddEntityPacket::AddEntityPacket() {} + +AddEntityPacket::AddEntityPacket(std::shared_ptr e, int type, int yRotp, + int xRotp, int xp, int yp, int zp) { + _init(e, type, -1, xp, yp, zp, yRotp, + xRotp); // 4J - changed "no data" value to be -1, we can have a valid + // entity id of 0 } -AddEntityPacket::AddEntityPacket(std::shared_ptr e, int type, int yRotp, int xRotp, int xp, int yp, int zp ) -{ - _init(e, type, -1, xp, yp, zp, yRotp, xRotp); // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 +AddEntityPacket::AddEntityPacket(std::shared_ptr e, int type, int data, + int yRotp, int xRotp, int xp, int yp, int zp) { + _init(e, type, data, xp, yp, zp, yRotp, xRotp); } -AddEntityPacket::AddEntityPacket(std::shared_ptr e, int type, int data, int yRotp, int xRotp, int xp, int yp, int zp ) +void AddEntityPacket::read(DataInputStream* dis) // throws IOException TODO 4J + // JEV add throws statement { - _init(e, type, data, xp, yp, zp, yRotp, xRotp); -} - -void AddEntityPacket::read(DataInputStream *dis) // throws IOException TODO 4J JEV add throws statement -{ - id = dis->readShort(); - type = dis->readByte(); + id = dis->readShort(); + type = dis->readByte(); #ifdef _LARGE_WORLDS - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); #else - x = dis->readShort(); - y = dis->readShort(); - z = dis->readShort(); + x = dis->readShort(); + y = dis->readShort(); + z = dis->readShort(); #endif - yRot = dis->readByte(); - xRot = dis->readByte(); - data = dis->readInt(); - if (data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 - { - xa = dis->readShort(); - ya = dis->readShort(); - za = dis->readShort(); - } + yRot = dis->readByte(); + xRot = dis->readByte(); + data = dis->readInt(); + if (data > -1) // 4J - changed "no data" value to be -1, we can have a + // valid entity id of 0 + { + xa = dis->readShort(); + ya = dis->readShort(); + za = dis->readShort(); + } } -void AddEntityPacket::write(DataOutputStream *dos) // throws IOException TODO 4J JEV add throws statement +void AddEntityPacket::write( + DataOutputStream* + dos) // throws IOException TODO 4J JEV add throws statement { - dos->writeShort(id); - dos->writeByte(static_cast(type)); + dos->writeShort(id); + dos->writeByte(static_cast(type)); #ifdef _LARGE_WORLDS - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); #else - dos->writeShort(x); - dos->writeShort(y); - dos->writeShort(z); + dos->writeShort(x); + dos->writeShort(y); + dos->writeShort(z); #endif - dos->writeByte(yRot); - dos->writeByte(xRot); - dos->writeInt(data); - if (data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 - { - dos->writeShort(xa); - dos->writeShort(ya); - dos->writeShort(za); - } + dos->writeByte(yRot); + dos->writeByte(xRot); + dos->writeInt(data); + if (data > -1) // 4J - changed "no data" value to be -1, we can have a + // valid entity id of 0 + { + dos->writeShort(xa); + dos->writeShort(ya); + dos->writeShort(za); + } } -void AddEntityPacket::handle(PacketListener *listener) -{ - listener->handleAddEntity(shared_from_this()); +void AddEntityPacket::handle(PacketListener* listener) { + listener->handleAddEntity(shared_from_this()); } -int AddEntityPacket::getEstimatedSize() -{ - return 11 + data > -1 ? 6 : 0; -} +int AddEntityPacket::getEstimatedSize() { return 11 + data > -1 ? 6 : 0; } diff --git a/Minecraft.World/Network/Packets/AddEntityPacket.h b/Minecraft.World/Network/Packets/AddEntityPacket.h index 985182ad7..abbc99c3b 100644 --- a/Minecraft.World/Network/Packets/AddEntityPacket.h +++ b/Minecraft.World/Network/Packets/AddEntityPacket.h @@ -1,58 +1,62 @@ #pragma once - #include "Packet.h" -class AddEntityPacket : public Packet, public std::enable_shared_from_this -{ +class AddEntityPacket : public Packet, + public std::enable_shared_from_this { public: - static const int BOAT = 1; - static const int ITEM = 2; + static const int BOAT = 1; + static const int ITEM = 2; static const int MINECART_RIDEABLE = 10; static const int MINECART_CHEST = 11; static const int MINECART_FURNACE = 12; static const int PRIMED_TNT = 50; - static const int ENDER_CRYSTAL = 51; + static const int ENDER_CRYSTAL = 51; static const int ARROW = 60; static const int SNOWBALL = 61; static const int EGG = 62; static const int FIREBALL = 63; - static const int SMALL_FIREBALL = 64; - static const int THROWN_ENDERPEARL = 65; + static const int SMALL_FIREBALL = 64; + static const int THROWN_ENDERPEARL = 65; static const int FALLING = 70; - static const int ITEM_FRAME = 71; - static const int EYEOFENDERSIGNAL = 72; - static const int THROWN_POTION = 73; - static const int FALLING_EGG = 74; - static const int THROWN_EXPBOTTLE = 75; + static const int ITEM_FRAME = 71; + static const int EYEOFENDERSIGNAL = 72; + static const int THROWN_POTION = 73; + static const int FALLING_EGG = 74; + static const int THROWN_EXPBOTTLE = 75; - static const int FISH_HOOK = 90; + static const int FISH_HOOK = 90; - // 4J Added TU9 - static const int DRAGON_FIRE_BALL = 200; + // 4J Added TU9 + static const int DRAGON_FIRE_BALL = 200; int id; int x, y, z; int xa, ya, za; int type; int data; - uint8_t yRot,xRot; // 4J added + uint8_t yRot, xRot; // 4J added private: - void _init(std::shared_ptr e, int type, int data, int xp, int yp, int zp, int yRotp, int xRotp ); + void _init(std::shared_ptr e, int type, int data, int xp, int yp, + int zp, int yRotp, int xRotp); public: - AddEntityPacket(); - AddEntityPacket(std::shared_ptr e, int type, int yRotp, int xRotp, int xp, int yp, int zp); - AddEntityPacket(std::shared_ptr e, int type, int data, int yRotp, int xRotp, int xp, int yp, int zp ); + AddEntityPacket(); + AddEntityPacket(std::shared_ptr e, int type, int yRotp, int xRotp, + int xp, int yp, int zp); + AddEntityPacket(std::shared_ptr e, int type, int data, int yRotp, + int xRotp, int xp, int yp, int zp); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new AddEntityPacket()); } - virtual int getId() { return 23; } + static std::shared_ptr create() { + return std::shared_ptr(new AddEntityPacket()); + } + virtual int getId() { return 23; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/AddExperienceOrbPacket.cpp b/Minecraft.World/Network/Packets/AddExperienceOrbPacket.cpp index cf4c43c45..e8394e6bb 100644 --- a/Minecraft.World/Network/Packets/AddExperienceOrbPacket.cpp +++ b/Minecraft.World/Network/Packets/AddExperienceOrbPacket.cpp @@ -4,48 +4,39 @@ #include "PacketListener.h" #include "AddExperienceOrbPacket.h" - - -AddExperienceOrbPacket::AddExperienceOrbPacket() -{ - id = 0; - x = y = z = 0; - value = 0; +AddExperienceOrbPacket::AddExperienceOrbPacket() { + id = 0; + x = y = z = 0; + value = 0; } -AddExperienceOrbPacket::AddExperienceOrbPacket(std::shared_ptr e) -{ - id = e->entityId; - x = Mth::floor(e->x * 32); - y = Mth::floor(e->y * 32); - z = Mth::floor(e->z * 32); - value = e->getValue(); +AddExperienceOrbPacket::AddExperienceOrbPacket( + std::shared_ptr e) { + id = e->entityId; + x = Mth::floor(e->x * 32); + y = Mth::floor(e->y * 32); + z = Mth::floor(e->z * 32); + value = e->getValue(); } -void AddExperienceOrbPacket::read(DataInputStream *dis) -{ - id = dis->readInt(); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); - value = dis->readShort(); +void AddExperienceOrbPacket::read(DataInputStream* dis) { + id = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); + value = dis->readShort(); } -void AddExperienceOrbPacket::write(DataOutputStream *dos) -{ - dos->writeInt(id); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); - dos->writeShort(value); +void AddExperienceOrbPacket::write(DataOutputStream* dos) { + dos->writeInt(id); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); + dos->writeShort(value); } -void AddExperienceOrbPacket::handle(PacketListener *listener) -{ - listener->handleAddExperienceOrb(shared_from_this()); +void AddExperienceOrbPacket::handle(PacketListener* listener) { + listener->handleAddExperienceOrb(shared_from_this()); } -int AddExperienceOrbPacket::getEstimatedSize() -{ - return 18; -} \ No newline at end of file +int AddExperienceOrbPacket::getEstimatedSize() { return 18; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/AddExperienceOrbPacket.h b/Minecraft.World/Network/Packets/AddExperienceOrbPacket.h index 5dad3ddb5..358703251 100644 --- a/Minecraft.World/Network/Packets/AddExperienceOrbPacket.h +++ b/Minecraft.World/Network/Packets/AddExperienceOrbPacket.h @@ -4,21 +4,24 @@ class ExperienceOrb; -class AddExperienceOrbPacket : public Packet, public std::enable_shared_from_this -{ +class AddExperienceOrbPacket + : public Packet, + public std::enable_shared_from_this { public: - int id; - int x, y, z; - int value; + int id; + int x, y, z; + int value; - AddExperienceOrbPacket(); - AddExperienceOrbPacket(std::shared_ptr e); + AddExperienceOrbPacket(); + AddExperienceOrbPacket(std::shared_ptr e); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - static std::shared_ptr create() { return std::shared_ptr(new AddExperienceOrbPacket()); } - virtual int getId() { return 26; } + static std::shared_ptr create() { + return std::shared_ptr(new AddExperienceOrbPacket()); + } + virtual int getId() { return 26; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/AddGlobalEntityPacket.cpp b/Minecraft.World/Network/Packets/AddGlobalEntityPacket.cpp index 5720d7099..41eb3c0b0 100644 --- a/Minecraft.World/Network/Packets/AddGlobalEntityPacket.cpp +++ b/Minecraft.World/Network/Packets/AddGlobalEntityPacket.cpp @@ -7,59 +7,48 @@ #include "PacketListener.h" #include "AddGlobalEntityPacket.h" - - const int AddGlobalEntityPacket::LIGHTNING = 1; -AddGlobalEntityPacket::AddGlobalEntityPacket() -{ - id = -1; - x = 0; - y = 0; - x = 0; - type = 0; +AddGlobalEntityPacket::AddGlobalEntityPacket() { + id = -1; + x = 0; + y = 0; + x = 0; + type = 0; } -AddGlobalEntityPacket::AddGlobalEntityPacket(std::shared_ptr e) -{ - id = e->entityId; +AddGlobalEntityPacket::AddGlobalEntityPacket(std::shared_ptr e) { + id = e->entityId; x = Mth::floor(e->x * 32); y = Mth::floor(e->y * 32); z = Mth::floor(e->z * 32); - if (std::dynamic_pointer_cast(e) != NULL) - { - this->type = LIGHTNING; - } - else - { - this->type = 0; - } + if (std::dynamic_pointer_cast(e) != NULL) { + this->type = LIGHTNING; + } else { + this->type = 0; + } } -void AddGlobalEntityPacket::read(DataInputStream *dis) // throws IOException +void AddGlobalEntityPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - type = static_cast(dis->readByte()); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); + id = dis->readInt(); + type = static_cast(dis->readByte()); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); } -void AddGlobalEntityPacket::write(DataOutputStream *dos) // throws IOException +void AddGlobalEntityPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeByte(static_cast(type)); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); + dos->writeInt(id); + dos->writeByte(static_cast(type)); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); } -void AddGlobalEntityPacket::handle(PacketListener *listener) -{ - listener->handleAddGlobalEntity(shared_from_this()); +void AddGlobalEntityPacket::handle(PacketListener* listener) { + listener->handleAddGlobalEntity(shared_from_this()); } -int AddGlobalEntityPacket::getEstimatedSize() -{ - return 17; -} +int AddGlobalEntityPacket::getEstimatedSize() { return 17; } diff --git a/Minecraft.World/Network/Packets/AddGlobalEntityPacket.h b/Minecraft.World/Network/Packets/AddGlobalEntityPacket.h index a457f7748..839b4190f 100644 --- a/Minecraft.World/Network/Packets/AddGlobalEntityPacket.h +++ b/Minecraft.World/Network/Packets/AddGlobalEntityPacket.h @@ -2,24 +2,27 @@ #include "Packet.h" -class AddGlobalEntityPacket : public Packet, public std::enable_shared_from_this -{ +class AddGlobalEntityPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int LIGHTNING; + static const int LIGHTNING; int id; int x, y, z; int type; - AddGlobalEntityPacket(); - AddGlobalEntityPacket(std::shared_ptr e); + AddGlobalEntityPacket(); + AddGlobalEntityPacket(std::shared_ptr e); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new AddGlobalEntityPacket()); } - virtual int getId() { return 71; } + static std::shared_ptr create() { + return std::shared_ptr(new AddGlobalEntityPacket()); + } + virtual int getId() { return 71; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/AddMobPacket.cpp b/Minecraft.World/Network/Packets/AddMobPacket.cpp index 04d9c90af..d70fafea9 100644 --- a/Minecraft.World/Network/Packets/AddMobPacket.cpp +++ b/Minecraft.World/Network/Packets/AddMobPacket.cpp @@ -5,136 +5,126 @@ #include "PacketListener.h" #include "AddMobPacket.h" - - -AddMobPacket::AddMobPacket() -{ - id = -1; - type = 0; - x = 0; - y = 0; - z = 0; - yRot = static_cast(0); - xRot = static_cast(0); - entityData = nullptr; - unpack = NULL; +AddMobPacket::AddMobPacket() { + id = -1; + type = 0; + x = 0; + y = 0; + z = 0; + yRot = static_cast(0); + xRot = static_cast(0); + entityData = nullptr; + unpack = NULL; } -AddMobPacket::~AddMobPacket() -{ - delete unpack; +AddMobPacket::~AddMobPacket() { delete unpack; } + +AddMobPacket::AddMobPacket(std::shared_ptr mob, int yRotp, int xRotp, + int xp, int yp, int zp, int yHeadRotp) { + id = mob->entityId; + + type = EntityIO::getId(mob); + // 4J Stu - We should add entities at their "last sent" position so that the + // relative update packets put them in the correct place + x = xp; // Mth::floor(mob->x * 32); + y = yp; // Mth::floor(mob->y * 32); + z = zp; // Mth::floor(mob->z * 32); + // 4J - changed - send current "previously sent" value of rotations to put + // this in sync with other clients + yRot = static_cast(yRotp); + xRot = static_cast(xRotp); + yHeadRot = static_cast(yHeadRotp); + // yRot = (uint8_t) (mob->yRot * 256 / 360); + // xRot = (uint8_t) (mob->xRot * 256 / 360); + // yHeadRot = (uint8_t) (mob->yHeadRot * 256 / 360); + + // From SetEntityMotionpacket + double m = 3.9; + double xd = mob->xd; + double yd = mob->yd; + double zd = mob->zd; + if (xd < -m) xd = -m; + if (yd < -m) yd = -m; + if (zd < -m) zd = -m; + if (xd > m) xd = m; + if (yd > m) yd = m; + if (zd > m) zd = m; + this->xd = (int)(xd * 8000.0); + this->yd = (int)(yd * 8000.0); + this->zd = (int)(zd * 8000.0); + + // printf("%d: New add mob rot %d\n",id,yRot); + + entityData = mob->getEntityData(); + unpack = NULL; } -AddMobPacket::AddMobPacket(std::shared_ptr mob, int yRotp, int xRotp, int xp, int yp, int zp, int yHeadRotp) +void AddMobPacket::read(DataInputStream* dis) // throws IOException { - id = mob->entityId; - - type = EntityIO::getId(mob); - // 4J Stu - We should add entities at their "last sent" position so that the relative update packets - // put them in the correct place - x = xp;//Mth::floor(mob->x * 32); - y = yp;//Mth::floor(mob->y * 32); - z = zp;//Mth::floor(mob->z * 32); - // 4J - changed - send current "previously sent" value of rotations to put this in sync with other clients - yRot = static_cast(yRotp); - xRot = static_cast(xRotp); - yHeadRot = static_cast(yHeadRotp); - // yRot = (uint8_t) (mob->yRot * 256 / 360); - // xRot = (uint8_t) (mob->xRot * 256 / 360); - // yHeadRot = (uint8_t) (mob->yHeadRot * 256 / 360); - - // From SetEntityMotionpacket - double m = 3.9; - double xd = mob->xd; - double yd = mob->yd; - double zd = mob->zd; - if (xd < -m) xd = -m; - if (yd < -m) yd = -m; - if (zd < -m) zd = -m; - if (xd > m) xd = m; - if (yd > m) yd = m; - if (zd > m) zd = m; - this->xd = (int) (xd * 8000.0); - this->yd = (int) (yd * 8000.0); - this->zd = (int) (zd * 8000.0); - - // printf("%d: New add mob rot %d\n",id,yRot); - - entityData = mob->getEntityData(); - unpack = NULL; -} - -void AddMobPacket::read(DataInputStream *dis) //throws IOException -{ - id = dis->readShort(); - type = static_cast(dis->readByte()) & 0xff; + id = dis->readShort(); + type = static_cast(dis->readByte()) & 0xff; #ifdef _LARGE_WORLDS - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); #else - x = dis->readShort(); - y = dis->readShort(); - z = dis->readShort(); + x = dis->readShort(); + y = dis->readShort(); + z = dis->readShort(); #endif - yRot = dis->readByte(); - xRot = dis->readByte(); - yHeadRot = dis->readByte(); - xd = dis->readShort(); - yd = dis->readShort(); - zd = dis->readShort(); - MemSect(1); - unpack = SynchedEntityData::unpack(dis); - MemSect(0); + yRot = dis->readByte(); + xRot = dis->readByte(); + yHeadRot = dis->readByte(); + xd = dis->readShort(); + yd = dis->readShort(); + zd = dis->readShort(); + MemSect(1); + unpack = SynchedEntityData::unpack(dis); + MemSect(0); } -void AddMobPacket::write(DataOutputStream *dos) //throws IOException +void AddMobPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeShort(id); - dos->writeByte(static_cast(type & 0xff)); + dos->writeShort(id); + dos->writeByte(static_cast(type & 0xff)); #ifdef _LARGE_WORLDS - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); #else - dos->writeShort(x); - dos->writeShort(y); - dos->writeShort(z); + dos->writeShort(x); + dos->writeShort(y); + dos->writeShort(z); #endif - dos->writeByte(yRot); - dos->writeByte(xRot); - dos->writeByte(yHeadRot); - dos->writeShort(xd); - dos->writeShort(yd); - dos->writeShort(zd); - entityData->packAll(dos); + dos->writeByte(yRot); + dos->writeByte(xRot); + dos->writeByte(yHeadRot); + dos->writeShort(xd); + dos->writeShort(yd); + dos->writeShort(zd); + entityData->packAll(dos); } -void AddMobPacket::handle(PacketListener *listener) -{ - listener->handleAddMob(shared_from_this()); +void AddMobPacket::handle(PacketListener* listener) { + listener->handleAddMob(shared_from_this()); } -int AddMobPacket::getEstimatedSize() -{ - int size = 11; - if( entityData != NULL ) - { - size += entityData->getSizeInBytes(); - } - else if( unpack != NULL ) - { - // 4J Stu - This is an incoming value which we aren't currently analysing - //size += unpack->get - } - return size; +int AddMobPacket::getEstimatedSize() { + int size = 11; + if (entityData != NULL) { + size += entityData->getSizeInBytes(); + } else if (unpack != NULL) { + // 4J Stu - This is an incoming value which we aren't currently + // analysing + // size += unpack->get + } + return size; } -std::vector > *AddMobPacket::getUnpackedData() -{ - if (unpack == NULL) - { - unpack = entityData->getAll(); - } - return unpack; +std::vector >* +AddMobPacket::getUnpackedData() { + if (unpack == NULL) { + unpack = entityData->getAll(); + } + return unpack; } diff --git a/Minecraft.World/Network/Packets/AddMobPacket.h b/Minecraft.World/Network/Packets/AddMobPacket.h index 70c0f71e0..2d56acf08 100644 --- a/Minecraft.World/Network/Packets/AddMobPacket.h +++ b/Minecraft.World/Network/Packets/AddMobPacket.h @@ -1,37 +1,40 @@ #pragma once - #include "Packet.h" #include "../../Entities/SyncedEntityData.h" class Mob; -class AddMobPacket : public Packet, public std::enable_shared_from_this -{ +class AddMobPacket : public Packet, + public std::enable_shared_from_this { public: - int id; - int type; - int x, y, z; - int xd, yd, zd; - uint8_t yRot, xRot, yHeadRot; + int id; + int type; + int x, y, z; + int xd, yd, zd; + uint8_t yRot, xRot, yHeadRot; private: - std::shared_ptr entityData; - std::vector > *unpack; + std::shared_ptr entityData; + std::vector >* unpack; public: - AddMobPacket(); - ~AddMobPacket(); - AddMobPacket(std::shared_ptr mob, int yRotp, int xRotp, int xp, int yp, int zp, int yHeadRotp); + AddMobPacket(); + ~AddMobPacket(); + AddMobPacket(std::shared_ptr mob, int yRotp, int xRotp, int xp, int yp, + int zp, int yHeadRotp); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - std::vector > *getUnpackedData(); + std::vector >* + getUnpackedData(); public: - static std::shared_ptr create() { return std::shared_ptr(new AddMobPacket()); } - virtual int getId() { return 24; } + static std::shared_ptr create() { + return std::shared_ptr(new AddMobPacket()); + } + virtual int getId() { return 24; } }; diff --git a/Minecraft.World/Network/Packets/AddPaintingPacket.cpp b/Minecraft.World/Network/Packets/AddPaintingPacket.cpp index 46ab56354..c85296cb3 100644 --- a/Minecraft.World/Network/Packets/AddPaintingPacket.cpp +++ b/Minecraft.World/Network/Packets/AddPaintingPacket.cpp @@ -5,54 +5,46 @@ #include "PacketListener.h" #include "AddPaintingPacket.h" - - -AddPaintingPacket::AddPaintingPacket() -{ - id = -1; - x = 0; - y = 0; - z = 0; - dir = 0; - motive = L""; +AddPaintingPacket::AddPaintingPacket() { + id = -1; + x = 0; + y = 0; + z = 0; + dir = 0; + motive = L""; } -AddPaintingPacket::AddPaintingPacket(std::shared_ptr e) -{ - id = e->entityId; - x = e->xTile; - y = e->yTile; - z = e->zTile; - dir = e->dir; - motive = e->motive->name; +AddPaintingPacket::AddPaintingPacket(std::shared_ptr e) { + id = e->entityId; + x = e->xTile; + y = e->yTile; + z = e->zTile; + dir = e->dir; + motive = e->motive->name; } -void AddPaintingPacket::read(DataInputStream *dis) //throws IOException +void AddPaintingPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - motive = readUtf(dis, Painting::Motive::MAX_MOTIVE_NAME_LENGTH); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); - dir = dis->readInt(); + id = dis->readInt(); + motive = readUtf(dis, Painting::Motive::MAX_MOTIVE_NAME_LENGTH); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); + dir = dis->readInt(); } -void AddPaintingPacket::write(DataOutputStream *dos) //throws IOException +void AddPaintingPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - writeUtf(motive, dos); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); - dos->writeInt(dir); + dos->writeInt(id); + writeUtf(motive, dos); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); + dos->writeInt(dir); } -void AddPaintingPacket::handle(PacketListener *listener) -{ - listener->handleAddPainting(shared_from_this()); +void AddPaintingPacket::handle(PacketListener* listener) { + listener->handleAddPainting(shared_from_this()); } -int AddPaintingPacket::getEstimatedSize() -{ - return 24; -} +int AddPaintingPacket::getEstimatedSize() { return 24; } diff --git a/Minecraft.World/Network/Packets/AddPaintingPacket.h b/Minecraft.World/Network/Packets/AddPaintingPacket.h index cbd35e6e7..ad55ae9ac 100644 --- a/Minecraft.World/Network/Packets/AddPaintingPacket.h +++ b/Minecraft.World/Network/Packets/AddPaintingPacket.h @@ -1,27 +1,30 @@ #pragma once - #include "Packet.h" class Painting; -class AddPaintingPacket : public Packet, public std::enable_shared_from_this -{ +class AddPaintingPacket + : public Packet, + public std::enable_shared_from_this { public: - int id; + int id; int x, y, z; int dir; std::wstring motive; public: - AddPaintingPacket(); - AddPaintingPacket(std::shared_ptr e); + AddPaintingPacket(); + AddPaintingPacket(std::shared_ptr e); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new AddPaintingPacket()); } - virtual int getId() { return 25; } + static std::shared_ptr create() { + return std::shared_ptr(new AddPaintingPacket()); + } + virtual int getId() { return 25; } }; diff --git a/Minecraft.World/Network/Packets/AddPlayerPacket.cpp b/Minecraft.World/Network/Packets/AddPlayerPacket.cpp index 57c3a5214..e19a57e7b 100644 --- a/Minecraft.World/Network/Packets/AddPlayerPacket.cpp +++ b/Minecraft.World/Network/Packets/AddPlayerPacket.cpp @@ -7,135 +7,134 @@ #include "PacketListener.h" #include "AddPlayerPacket.h" - - -AddPlayerPacket::AddPlayerPacket() -{ - id = -1; - name = L""; - x = 0; - y = 0; - z = 0; - yRot = 0; - xRot = 0; - carriedItem = 0; - xuid = INVALID_XUID; - m_playerIndex = 0; - m_skinId = 0; - m_capeId = 0; - m_uiGamePrivileges = 0; - entityData = nullptr; - unpack = NULL; +AddPlayerPacket::AddPlayerPacket() { + id = -1; + name = L""; + x = 0; + y = 0; + z = 0; + yRot = 0; + xRot = 0; + carriedItem = 0; + xuid = INVALID_XUID; + m_playerIndex = 0; + m_skinId = 0; + m_capeId = 0; + m_uiGamePrivileges = 0; + entityData = nullptr; + unpack = NULL; } -AddPlayerPacket::~AddPlayerPacket() -{ - if(unpack != NULL) delete unpack; +AddPlayerPacket::~AddPlayerPacket() { + if (unpack != NULL) delete unpack; } -AddPlayerPacket::AddPlayerPacket(std::shared_ptr player, PlayerUID xuid, PlayerUID OnlineXuid,int xp, int yp, int zp, int yRotp, int xRotp, int yHeadRotp) -{ - id = player->entityId; - name = player->name; +AddPlayerPacket::AddPlayerPacket(std::shared_ptr player, PlayerUID xuid, + PlayerUID OnlineXuid, int xp, int yp, int zp, + int yRotp, int xRotp, int yHeadRotp) { + id = player->entityId; + name = player->name; - // 4J Stu - Send "previously sent" value of position as well so that we stay in sync - x = xp;//Mth::floor(player->x * 32); - y = yp;//Mth::floor(player->y * 32); - z = zp;//Mth::floor(player->z * 32); - // 4J - changed - send current "previously sent" value of rotations to put this in sync with other clients - yRot = yRotp; - xRot = xRotp; - yHeadRot = static_cast(yHeadRotp); // 4J Added - // yRot = (std::uint8_t) (player->yRot * 256 / 360); - // xRot = (std::uint8_t) (player->xRot * 256 / 360); + // 4J Stu - Send "previously sent" value of position as well so that we stay + // in sync + x = xp; // Mth::floor(player->x * 32); + y = yp; // Mth::floor(player->y * 32); + z = zp; // Mth::floor(player->z * 32); + // 4J - changed - send current "previously sent" value of rotations to put + // this in sync with other clients + yRot = yRotp; + xRot = xRotp; + yHeadRot = static_cast(yHeadRotp); // 4J Added + // yRot = (std::uint8_t) (player->yRot * 256 / 360); + // xRot = (std::uint8_t) (player->xRot * 256 / 360); - //printf("%d: New add player (%f,%f,%f) : (%d,%d,%d) : xRot %d, yRot %d\n",id,player->x,player->y,player->z,x,y,z,xRot,yRot); + // printf("%d: New add player (%f,%f,%f) : (%d,%d,%d) : xRot %d, yRot + // %d\n",id,player->x,player->y,player->z,x,y,z,xRot,yRot); - std::shared_ptr itemInstance = player->inventory->getSelected(); - carriedItem = itemInstance == NULL ? 0 : itemInstance->id; + std::shared_ptr itemInstance = + player->inventory->getSelected(); + carriedItem = itemInstance == NULL ? 0 : itemInstance->id; - this->xuid = xuid; - this->OnlineXuid = OnlineXuid; - m_playerIndex = static_cast(player->getPlayerIndex()); - m_skinId = player->getCustomSkin(); - m_capeId = player->getCustomCape(); - m_uiGamePrivileges = player->getAllPlayerGamePrivileges(); + this->xuid = xuid; + this->OnlineXuid = OnlineXuid; + m_playerIndex = static_cast(player->getPlayerIndex()); + m_skinId = player->getCustomSkin(); + m_capeId = player->getCustomCape(); + m_uiGamePrivileges = player->getAllPlayerGamePrivileges(); - entityData = player->getEntityData(); - unpack = NULL; + entityData = player->getEntityData(); + unpack = NULL; } -void AddPlayerPacket::read(DataInputStream *dis) //throws IOException +void AddPlayerPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - name = readUtf(dis, Player::MAX_NAME_LENGTH); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); - yRot = static_cast(dis->readByte()); - xRot = static_cast(dis->readByte()); - yHeadRot = dis->readByte(); // 4J Added - carriedItem = dis->readShort(); - xuid = dis->readPlayerUID(); - OnlineXuid = dis->readPlayerUID(); - m_playerIndex = dis->readByte(); - m_skinId = static_cast(dis->readInt()); - m_capeId = static_cast(dis->readInt()); - INT privileges = dis->readInt(); - m_uiGamePrivileges = static_cast(privileges); - MemSect(1); - unpack = SynchedEntityData::unpack(dis); - MemSect(0); + id = dis->readInt(); + name = readUtf(dis, Player::MAX_NAME_LENGTH); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); + yRot = static_cast(dis->readByte()); + xRot = static_cast(dis->readByte()); + yHeadRot = dis->readByte(); // 4J Added + carriedItem = dis->readShort(); + xuid = dis->readPlayerUID(); + OnlineXuid = dis->readPlayerUID(); + m_playerIndex = dis->readByte(); + m_skinId = static_cast(dis->readInt()); + m_capeId = static_cast(dis->readInt()); + INT privileges = dis->readInt(); + m_uiGamePrivileges = static_cast(privileges); + MemSect(1); + unpack = SynchedEntityData::unpack(dis); + MemSect(0); } -void AddPlayerPacket::write(DataOutputStream *dos) //throws IOException +void AddPlayerPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - writeUtf(name, dos); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); - dos->writeByte(static_cast(yRot)); - dos->writeByte(static_cast(xRot)); - dos->writeByte(static_cast(m_playerIndex)); // 4J Added - dos->writeShort(carriedItem); - dos->writePlayerUID(xuid); - dos->writePlayerUID(OnlineXuid); - dos->writeByte(static_cast(m_playerIndex)); // 4J Added - dos->writeInt(static_cast(m_skinId)); - dos->writeInt(static_cast(m_capeId)); - dos->writeInt(m_uiGamePrivileges); - entityData->packAll(dos); - + dos->writeInt(id); + writeUtf(name, dos); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); + dos->writeByte(static_cast(yRot)); + dos->writeByte(static_cast(xRot)); + dos->writeByte(static_cast(m_playerIndex)); // 4J Added + dos->writeShort(carriedItem); + dos->writePlayerUID(xuid); + dos->writePlayerUID(OnlineXuid); + dos->writeByte(static_cast(m_playerIndex)); // 4J Added + dos->writeInt(static_cast(m_skinId)); + dos->writeInt(static_cast(m_capeId)); + dos->writeInt(m_uiGamePrivileges); + entityData->packAll(dos); } -void AddPlayerPacket::handle(PacketListener *listener) -{ - listener->handleAddPlayer(shared_from_this()); +void AddPlayerPacket::handle(PacketListener* listener) { + listener->handleAddPlayer(shared_from_this()); } -int AddPlayerPacket::getEstimatedSize() -{ - int iSize= sizeof(int) + Player::MAX_NAME_LENGTH + sizeof(int) + sizeof(int) + sizeof(int) + sizeof(std::uint8_t) + sizeof(std::uint8_t) +sizeof(short) + sizeof(PlayerUID) + sizeof(PlayerUID) + sizeof(int) + sizeof(std::uint8_t) + sizeof(unsigned int) + sizeof(std::uint8_t); +int AddPlayerPacket::getEstimatedSize() { + int iSize = sizeof(int) + Player::MAX_NAME_LENGTH + sizeof(int) + + sizeof(int) + sizeof(int) + sizeof(std::uint8_t) + + sizeof(std::uint8_t) + sizeof(short) + sizeof(PlayerUID) + + sizeof(PlayerUID) + sizeof(int) + sizeof(std::uint8_t) + + sizeof(unsigned int) + sizeof(std::uint8_t); - if( entityData != NULL ) - { - iSize += entityData->getSizeInBytes(); - } - else if( unpack != NULL ) - { - // 4J Stu - This is an incoming value which we aren't currently analysing - //iSize += unpack->get - } + if (entityData != NULL) { + iSize += entityData->getSizeInBytes(); + } else if (unpack != NULL) { + // 4J Stu - This is an incoming value which we aren't currently + // analysing + // iSize += unpack->get + } - return iSize; + return iSize; } -std::vector > *AddPlayerPacket::getUnpackedData() -{ - if (unpack == NULL) - { - unpack = entityData->getAll(); - } - return unpack; +std::vector >* +AddPlayerPacket::getUnpackedData() { + if (unpack == NULL) { + unpack = entityData->getAll(); + } + return unpack; } diff --git a/Minecraft.World/Network/Packets/AddPlayerPacket.h b/Minecraft.World/Network/Packets/AddPlayerPacket.h index 1cef92752..9a1e1324e 100644 --- a/Minecraft.World/Network/Packets/AddPlayerPacket.h +++ b/Minecraft.World/Network/Packets/AddPlayerPacket.h @@ -7,38 +7,43 @@ class Player; -class AddPlayerPacket : public Packet, public std::enable_shared_from_this -{ - +class AddPlayerPacket : public Packet, + public std::enable_shared_from_this { private: - std::shared_ptr entityData; - std::vector > *unpack; + std::shared_ptr entityData; + std::vector >* unpack; public: - int id; + int id; std::wstring name; int x, y, z; char yRot, xRot; - int carriedItem; - PlayerUID xuid; // 4J Added - PlayerUID OnlineXuid; // 4J Added - std::uint8_t m_playerIndex; // 4J Added - std::uint32_t m_skinId; // 4J Added - std::uint32_t m_capeId; // 4J Added - unsigned int m_uiGamePrivileges; // 4J Added - std::uint8_t yHeadRot; // 4J Added + int carriedItem; + PlayerUID xuid; // 4J Added + PlayerUID OnlineXuid; // 4J Added + std::uint8_t m_playerIndex; // 4J Added + std::uint32_t m_skinId; // 4J Added + std::uint32_t m_capeId; // 4J Added + unsigned int m_uiGamePrivileges; // 4J Added + std::uint8_t yHeadRot; // 4J Added - AddPlayerPacket(); - ~AddPlayerPacket(); - AddPlayerPacket(std::shared_ptr player, PlayerUID xuid, PlayerUID OnlineXuid,int xp, int yp, int zp, int yRotp, int xRotp, int yHeadRotp); + AddPlayerPacket(); + ~AddPlayerPacket(); + AddPlayerPacket(std::shared_ptr player, PlayerUID xuid, + PlayerUID OnlineXuid, int xp, int yp, int zp, int yRotp, + int xRotp, int yHeadRotp); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + + std::vector >* + getUnpackedData(); - std::vector > *getUnpackedData(); public: - static std::shared_ptr create() { return std::shared_ptr(new AddPlayerPacket()); } - virtual int getId() { return 20; } + static std::shared_ptr create() { + return std::shared_ptr(new AddPlayerPacket()); + } + virtual int getId() { return 20; } }; diff --git a/Minecraft.World/Network/Packets/AnimatePacket.cpp b/Minecraft.World/Network/Packets/AnimatePacket.cpp index a61a4f15b..363c88aa0 100644 --- a/Minecraft.World/Network/Packets/AnimatePacket.cpp +++ b/Minecraft.World/Network/Packets/AnimatePacket.cpp @@ -5,38 +5,30 @@ #include "PacketListener.h" #include "AnimatePacket.h" - - -AnimatePacket::AnimatePacket() -{ - id = -1; - action = 0; +AnimatePacket::AnimatePacket() { + id = -1; + action = 0; } -AnimatePacket::AnimatePacket(std::shared_ptr e, int action) -{ - id = e->entityId; - this->action = action; +AnimatePacket::AnimatePacket(std::shared_ptr e, int action) { + id = e->entityId; + this->action = action; } -void AnimatePacket::read(DataInputStream *dis) //throws IOException +void AnimatePacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - action = static_cast(dis->readByte()); + id = dis->readInt(); + action = static_cast(dis->readByte()); } -void AnimatePacket::write(DataOutputStream *dos) //throws IOException +void AnimatePacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeByte(static_cast(action)); + dos->writeInt(id); + dos->writeByte(static_cast(action)); } -void AnimatePacket::handle(PacketListener *listener) -{ - listener->handleAnimate(shared_from_this()); +void AnimatePacket::handle(PacketListener* listener) { + listener->handleAnimate(shared_from_this()); } -int AnimatePacket::getEstimatedSize() -{ - return 5; -} +int AnimatePacket::getEstimatedSize() { return 5; } diff --git a/Minecraft.World/Network/Packets/AnimatePacket.h b/Minecraft.World/Network/Packets/AnimatePacket.h index dba9f74e0..c0b511415 100644 --- a/Minecraft.World/Network/Packets/AnimatePacket.h +++ b/Minecraft.World/Network/Packets/AnimatePacket.h @@ -1,31 +1,32 @@ #pragma once - #include "Packet.h" -class AnimatePacket : public Packet, public std::enable_shared_from_this -{ +class AnimatePacket : public Packet, + public std::enable_shared_from_this { public: - static const int SWING = 1; - static const int HURT = 2; - static const int WAKE_UP = 3; - static const int RESPAWN = 4; - static const int EAT = 5; // 1.8.2 - static const int CRITICAL_HIT = 6; - static const int MAGIC_CRITICAL_HIT = 7; + static const int SWING = 1; + static const int HURT = 2; + static const int WAKE_UP = 3; + static const int RESPAWN = 4; + static const int EAT = 5; // 1.8.2 + static const int CRITICAL_HIT = 6; + static const int MAGIC_CRITICAL_HIT = 7; - int id; - int action; + int id; + int action; - AnimatePacket(); - AnimatePacket(std::shared_ptr e, int action); + AnimatePacket(); + AnimatePacket(std::shared_ptr e, int action); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - public: - static std::shared_ptr create() { return std::shared_ptr(new AnimatePacket()); } - virtual int getId() { return 18; } + static std::shared_ptr create() { + return std::shared_ptr(new AnimatePacket()); + } + virtual int getId() { return 18; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/AwardStatPacket.cpp b/Minecraft.World/Network/Packets/AwardStatPacket.cpp index 3ec3113a0..01fc3f2cb 100644 --- a/Minecraft.World/Network/Packets/AwardStatPacket.cpp +++ b/Minecraft.World/Network/Packets/AwardStatPacket.cpp @@ -4,92 +4,73 @@ #include "PacketListener.h" #include "AwardStatPacket.h" - - -AwardStatPacket::AwardStatPacket() -{ - this->m_paramData.data = NULL; - this->m_paramData.length = 0; +AwardStatPacket::AwardStatPacket() { + this->m_paramData.data = NULL; + this->m_paramData.length = 0; } -AwardStatPacket::AwardStatPacket(int statId, int count) -{ - this->statId = statId; +AwardStatPacket::AwardStatPacket(int statId, int count) { + this->statId = statId; - // 4jcraft, changed from (uint8_t*) new int(count); to: - // new uint8_t[sizeof(int)]; - // and memcpy of the integer into the array - // reason: operator missmatch, array is deleted with delete[] - // and typesafety - this->m_paramData.data = new uint8_t[sizeof(int)]; - memcpy(this->m_paramData.data, &count, sizeof(int)); - this->m_paramData.length = sizeof(int); + // 4jcraft, changed from (uint8_t*) new int(count); to: + // new uint8_t[sizeof(int)]; + // and memcpy of the integer into the array + // reason: operator missmatch, array is deleted with delete[] + // and typesafety + this->m_paramData.data = new uint8_t[sizeof(int)]; + memcpy(this->m_paramData.data, &count, sizeof(int)); + this->m_paramData.length = sizeof(int); } -AwardStatPacket::AwardStatPacket(int statId, byteArray paramData) -{ - this->statId = statId; - this->m_paramData = paramData; +AwardStatPacket::AwardStatPacket(int statId, byteArray paramData) { + this->statId = statId; + this->m_paramData = paramData; } -AwardStatPacket::~AwardStatPacket() -{ - if (m_paramData.data != NULL) - { - delete[] m_paramData.data; - m_paramData.data = NULL; - } +AwardStatPacket::~AwardStatPacket() { + if (m_paramData.data != NULL) { + delete[] m_paramData.data; + m_paramData.data = NULL; + } } -void AwardStatPacket::handle(PacketListener *listener) -{ - listener->handleAwardStat(shared_from_this()); - m_paramData.data = NULL; +void AwardStatPacket::handle(PacketListener* listener) { + listener->handleAwardStat(shared_from_this()); + m_paramData.data = NULL; } -void AwardStatPacket::read(DataInputStream *dis) //throws IOException +void AwardStatPacket::read(DataInputStream* dis) // throws IOException { - statId = dis->readInt(); + statId = dis->readInt(); - // Read parameter blob. - int length = dis->readInt(); - if(length > 0) - { - m_paramData = byteArray(length); - dis->readFully(m_paramData); - } + // Read parameter blob. + int length = dis->readInt(); + if (length > 0) { + m_paramData = byteArray(length); + dis->readFully(m_paramData); + } } -void AwardStatPacket::write(DataOutputStream *dos) //throws IOException +void AwardStatPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(statId); - dos->writeInt(m_paramData.length); - if(m_paramData.length > 0) dos->write(m_paramData); + dos->writeInt(statId); + dos->writeInt(m_paramData.length); + if (m_paramData.length > 0) dos->write(m_paramData); } -int AwardStatPacket::getEstimatedSize() -{ - return 6; -} +int AwardStatPacket::getEstimatedSize() { return 6; } -bool AwardStatPacket::isAync() -{ - return true; -} +bool AwardStatPacket::isAync() { return true; } // On most platforms we only store 'count' in an AwardStatPacket. -int AwardStatPacket::getCount() -{ +int AwardStatPacket::getCount() { #ifdef _DURANGO - assert(false); // Method not supported on Durango. - return 0; + assert(false); // Method not supported on Durango. + return 0; #else - return *((int*)this->m_paramData.data); + return *((int*)this->m_paramData.data); #endif } // On Durango we store 'Event' parameters here in a blob. -byteArray AwardStatPacket::getParamData() -{ - return m_paramData; -} +byteArray AwardStatPacket::getParamData() { return m_paramData; } diff --git a/Minecraft.World/Network/Packets/AwardStatPacket.h b/Minecraft.World/Network/Packets/AwardStatPacket.h index b10bda312..9ed69e256 100644 --- a/Minecraft.World/Network/Packets/AwardStatPacket.h +++ b/Minecraft.World/Network/Packets/AwardStatPacket.h @@ -1,34 +1,35 @@ #pragma once - #include "Packet.h" -class AwardStatPacket : public Packet, public std::enable_shared_from_this -{ +class AwardStatPacket : public Packet, + public std::enable_shared_from_this { public: - int statId; + int statId; - // 4J-JEV: Changed to allow for Durango events. + // 4J-JEV: Changed to allow for Durango events. protected: - byteArray m_paramData; + byteArray m_paramData; public: - AwardStatPacket(); - AwardStatPacket(int statId, int count); - AwardStatPacket(int statId, byteArray paramData); - ~AwardStatPacket(); + AwardStatPacket(); + AwardStatPacket(int statId, int count); + AwardStatPacket(int statId, byteArray paramData); + ~AwardStatPacket(); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); - virtual bool isAync(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); + virtual bool isAync(); - static std::shared_ptr create() { return std::shared_ptr(new AwardStatPacket()); } - virtual int getId() { return 200; } + static std::shared_ptr create() { + return std::shared_ptr(new AwardStatPacket()); + } + virtual int getId() { return 200; } public: - // 4J-JEV: New getters to help prevent unsafe access - int getCount(); - byteArray getParamData(); + // 4J-JEV: New getters to help prevent unsafe access + int getCount(); + byteArray getParamData(); }; diff --git a/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.cpp b/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.cpp index a209edf61..258bb410c 100644 --- a/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.cpp +++ b/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.cpp @@ -10,146 +10,136 @@ #include "../../Level/Storage/DataLayer.h" #include "../../Level/Dimensions/Dimension.h" -BlockRegionUpdatePacket::~BlockRegionUpdatePacket() -{ - delete [] buffer.data; +BlockRegionUpdatePacket::~BlockRegionUpdatePacket() { delete[] buffer.data; } + +BlockRegionUpdatePacket::BlockRegionUpdatePacket() { + shouldDelay = true; + x = 0; + y = 0; + z = 0; + xs = 0; + ys = 0; + zs = 0; + bIsFullChunk = false; } -BlockRegionUpdatePacket::BlockRegionUpdatePacket() -{ - shouldDelay = true; - x = 0; - y = 0; - z = 0; - xs = 0; - ys = 0; - zs = 0; - bIsFullChunk = false; +BlockRegionUpdatePacket::BlockRegionUpdatePacket(int x, int y, int z, int xs, + int ys, int zs, Level* level) { + shouldDelay = true; + this->x = x; + this->y = y; + this->z = z; + this->xs = xs; + this->ys = ys; + this->zs = zs; + bIsFullChunk = false; + levelIdx = + ((level->dimension->id == 0) ? 0 + : ((level->dimension->id == -1) ? 1 : 2)); + + // 4J - if we are compressing a full chunk, re-order the blocks so that they + // compress better + // TODO - we should be using compressed data directly here rather than + // decompressing first and then recompressing... + byteArray rawBuffer; + + if (xs == 16 && ys == Level::maxBuildHeight && zs == 16 && + ((x & 15) == 0) && (y == 0) && ((z & 15) == 0)) { + bIsFullChunk = true; + + LevelChunk* lc = level->getChunkAt(x, z); + rawBuffer = lc->getReorderedBlocksAndData(x & 0xF, y, z & 0xF, xs, + this->ys, zs); + } else { + MemSect(50); + rawBuffer = level->getBlocksAndData(x, y, z, xs, ys, zs, false); + MemSect(0); + } + + if (rawBuffer.length == 0) { + size = 0; + buffer = byteArray(); + } else { + // We don't know how this will compress - just make a fixed length + // buffer to initially decompress into Some small sets of blocks can end + // up compressing into something bigger than their source + unsigned char* ucTemp = new unsigned char[(256 * 16 * 16 * 5) / 2]; + unsigned int inputSize = (256 * 16 * 16 * 5) / 2; + + Compression::getCompression()->CompressLZXRLE( + ucTemp, &inputSize, rawBuffer.data, (unsigned int)rawBuffer.length); + // app.DebugPrintf("Chunk (%d,%d) compressed from %d to size %d\n", + // x>>4, z>>4, rawBuffer.length, inputSize); + unsigned char* ucTemp2 = new unsigned char[inputSize]; + memcpy(ucTemp2, ucTemp, inputSize); + delete[] ucTemp; + buffer = byteArray(ucTemp2, inputSize); + delete[] rawBuffer.data; + size = inputSize; + } } -BlockRegionUpdatePacket::BlockRegionUpdatePacket(int x, int y, int z, int xs, int ys, int zs, Level *level) +void BlockRegionUpdatePacket::read(DataInputStream* dis) // throws IOException { - - shouldDelay = true; - this->x = x; - this->y = y; - this->z = z; - this->xs = xs; - this->ys = ys; - this->zs = zs; - bIsFullChunk = false; - levelIdx = ( ( level->dimension->id == 0 ) ? 0 : ( (level->dimension->id == -1) ? 1 : 2 ) ); + bIsFullChunk = dis->readBoolean(); + x = dis->readInt(); + y = dis->readShort(); + z = dis->readInt(); + xs = dis->read() + 1; + ys = dis->read() + 1; + zs = dis->read() + 1; - // 4J - if we are compressing a full chunk, re-order the blocks so that they compress better - // TODO - we should be using compressed data directly here rather than decompressing first and then recompressing... - byteArray rawBuffer; + size = dis->readInt(); + levelIdx = (size >> 30) & 3; + size &= 0x3fffffff; - if( xs == 16 && ys == Level::maxBuildHeight && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) - { - bIsFullChunk = true; + if (size == 0) { + buffer = byteArray(); + } else { + byteArray compressedBuffer(size); + bool success = dis->readFully(compressedBuffer); - LevelChunk *lc = level->getChunkAt(x,z); - rawBuffer = lc->getReorderedBlocksAndData(x&0xF, y, z&0xF, xs, this->ys, zs); - } - else - { - MemSect(50); - rawBuffer = level->getBlocksAndData(x, y, z, xs, ys, zs, false); - MemSect(0); - } + int bufferSize = xs * ys * zs * 5 / 2; + // Add the size of the biome data if it's a full chunk + if (bIsFullChunk) bufferSize += (16 * 16); + buffer = byteArray(bufferSize); + unsigned int outputSize = buffer.length; - if(rawBuffer.length == 0) - { - size = 0; - buffer = byteArray(); - } - else - { - // We don't know how this will compress - just make a fixed length buffer to initially decompress into - // Some small sets of blocks can end up compressing into something bigger than their source - unsigned char *ucTemp = new unsigned char[(256 * 16 * 16 * 5)/2]; - unsigned int inputSize = (256 * 16 * 16 * 5)/2; - - Compression::getCompression()->CompressLZXRLE(ucTemp, &inputSize, rawBuffer.data, (unsigned int) rawBuffer.length); - //app.DebugPrintf("Chunk (%d,%d) compressed from %d to size %d\n", x>>4, z>>4, rawBuffer.length, inputSize); - unsigned char *ucTemp2 = new unsigned char[inputSize]; - memcpy(ucTemp2,ucTemp,inputSize); - delete [] ucTemp; - buffer = byteArray(ucTemp2,inputSize); - delete [] rawBuffer.data; - size = inputSize; - } + if (success) { + Compression::getCompression()->DecompressLZXRLE( + buffer.data, &outputSize, compressedBuffer.data, size); + } else { + app.DebugPrintf( + "Not decompressing packet that wasn't fully read\n"); + } + + // printf("Block (%d %d %d), (%d %d %d) coming in decomp from %d to + //%d\n",x,y,z,xs,ys,zs,size,outputSize); + + delete[] compressedBuffer.data; + assert(buffer.length == outputSize); + } } -void BlockRegionUpdatePacket::read(DataInputStream *dis) //throws IOException +void BlockRegionUpdatePacket::write( + DataOutputStream* dos) // throws IOException { - bIsFullChunk = dis->readBoolean(); - x = dis->readInt(); - y = dis->readShort(); - z = dis->readInt(); - xs = dis->read() + 1; - ys = dis->read() + 1; - zs = dis->read() + 1; + dos->writeBoolean(bIsFullChunk); + dos->writeInt(x); + dos->writeShort(y); + dos->writeInt(z); + dos->write(xs - 1); + dos->write(ys - 1); + dos->write(zs - 1); - size = dis->readInt(); - levelIdx = ( size >> 30 ) & 3; - size &= 0x3fffffff; - - if(size == 0) - { - buffer = byteArray(); - } - else - { - byteArray compressedBuffer(size); - bool success = dis->readFully(compressedBuffer); - - int bufferSize = xs * ys * zs * 5/2; - // Add the size of the biome data if it's a full chunk - if(bIsFullChunk) bufferSize += (16*16); - buffer = byteArray(bufferSize); - unsigned int outputSize = buffer.length; - - if( success ) - { - Compression::getCompression()->DecompressLZXRLE( buffer.data, &outputSize, compressedBuffer.data, size); - } - else - { - app.DebugPrintf("Not decompressing packet that wasn't fully read\n"); - } - - // printf("Block (%d %d %d), (%d %d %d) coming in decomp from %d to %d\n",x,y,z,xs,ys,zs,size,outputSize); - - - delete [] compressedBuffer.data; - assert(buffer.length == outputSize); - } + int sizeAndLevel = size; + sizeAndLevel |= (levelIdx << 30); + dos->writeInt(sizeAndLevel); + dos->write(buffer, 0, size); } -void BlockRegionUpdatePacket::write(DataOutputStream *dos) // throws IOException -{ - dos->writeBoolean(bIsFullChunk); - dos->writeInt(x); - dos->writeShort(y); - dos->writeInt(z); - dos->write(xs - 1); - dos->write(ys - 1); - dos->write(zs - 1); - - int sizeAndLevel = size; - sizeAndLevel |= ( levelIdx << 30 ); - dos->writeInt(sizeAndLevel); - dos->write(buffer, 0, size); -} - -void BlockRegionUpdatePacket::handle(PacketListener *listener) -{ - listener->handleBlockRegionUpdate(shared_from_this()); -} - -int BlockRegionUpdatePacket::getEstimatedSize() -{ - return 17 + size; +void BlockRegionUpdatePacket::handle(PacketListener* listener) { + listener->handleBlockRegionUpdate(shared_from_this()); } +int BlockRegionUpdatePacket::getEstimatedSize() { return 17 + size; } diff --git a/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.h b/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.h index 51960a038..75ab4bd12 100644 --- a/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.h +++ b/Minecraft.World/Network/Packets/BlockRegionUpdatePacket.h @@ -1,33 +1,36 @@ #pragma once - #include "Packet.h" class Level; -class BlockRegionUpdatePacket : public Packet, public std::enable_shared_from_this -{ +class BlockRegionUpdatePacket + : public Packet, + public std::enable_shared_from_this { public: int x, y, z; int xs, ys, zs; byteArray buffer; - int levelIdx; - bool bIsFullChunk; // 4J Added + int levelIdx; + bool bIsFullChunk; // 4J Added private: - int size; + int size; public: - BlockRegionUpdatePacket(); - ~BlockRegionUpdatePacket(); - BlockRegionUpdatePacket(int x, int y, int z, int xs, int ys, int zs, Level *level); + BlockRegionUpdatePacket(); + ~BlockRegionUpdatePacket(); + BlockRegionUpdatePacket(int x, int y, int z, int xs, int ys, int zs, + Level* level); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new BlockRegionUpdatePacket()); } - virtual int getId() { return 51; } + static std::shared_ptr create() { + return std::shared_ptr(new BlockRegionUpdatePacket()); + } + virtual int getId() { return 51; } }; diff --git a/Minecraft.World/Network/Packets/ChatAutoCompletePacket.h b/Minecraft.World/Network/Packets/ChatAutoCompletePacket.h index b1cd1170e..facdb4abb 100644 --- a/Minecraft.World/Network/Packets/ChatAutoCompletePacket.h +++ b/Minecraft.World/Network/Packets/ChatAutoCompletePacket.h @@ -2,8 +2,7 @@ #include "Packet.h" -class ChatAutoCompletePacket : public Packet -{ +class ChatAutoCompletePacket : public Packet { #if 0 private String message; diff --git a/Minecraft.World/Network/Packets/ChatPacket.cpp b/Minecraft.World/Network/Packets/ChatPacket.cpp index 24d127c49..a19b42857 100644 --- a/Minecraft.World/Network/Packets/ChatPacket.cpp +++ b/Minecraft.World/Network/Packets/ChatPacket.cpp @@ -6,82 +6,74 @@ #include "ChatPacket.h" // longest allowed string is "<" + name + "> " + message -const unsigned int ChatPacket::MAX_LENGTH = SharedConstants::maxChatLength + Player::MAX_NAME_LENGTH + 3; +const unsigned int ChatPacket::MAX_LENGTH = + SharedConstants::maxChatLength + Player::MAX_NAME_LENGTH + 3; -ChatPacket::ChatPacket() -{ - m_messageType = e_ChatCustom; -} +ChatPacket::ChatPacket() { m_messageType = e_ChatCustom; } -// Old chat packet constructor, adds message, custom data and additional message to arg vectors -ChatPacket::ChatPacket(const std::wstring& message, EChatPacketMessage type /*= e_ChatCustom*/, int customData /*= -1*/, const std::wstring& additionalMessage /*= L""*/) -{ - m_messageType = type; - if (customData != -1) m_intArgs.push_back(customData); - if (message != L"" || additionalMessage != L"") m_stringArgs.push_back(message); - if (additionalMessage != L"") m_stringArgs.push_back(additionalMessage); +// Old chat packet constructor, adds message, custom data and additional message +// to arg vectors +ChatPacket::ChatPacket(const std::wstring& message, + EChatPacketMessage type /*= e_ChatCustom*/, + int customData /*= -1*/, + const std::wstring& additionalMessage /*= L""*/) { + m_messageType = type; + if (customData != -1) m_intArgs.push_back(customData); + if (message != L"" || additionalMessage != L"") + m_stringArgs.push_back(message); + if (additionalMessage != L"") m_stringArgs.push_back(additionalMessage); } // Read chat packet (throws IOException) -void ChatPacket::read(DataInputStream *dis) -{ - m_messageType = (EChatPacketMessage) dis->readShort(); +void ChatPacket::read(DataInputStream* dis) { + m_messageType = (EChatPacketMessage)dis->readShort(); - short packedCounts = dis->readShort(); - int stringCount = (packedCounts >> 4) & 0xF; - int intCount = (packedCounts >> 0) & 0xF; - - for(int i = 0; i < stringCount; i++) - { - m_stringArgs.push_back(readUtf(dis, MAX_LENGTH)); - } + short packedCounts = dis->readShort(); + int stringCount = (packedCounts >> 4) & 0xF; + int intCount = (packedCounts >> 0) & 0xF; - for(int i = 0; i < intCount; i++) - { - m_intArgs.push_back(dis->readInt()); - } + for (int i = 0; i < stringCount; i++) { + m_stringArgs.push_back(readUtf(dis, MAX_LENGTH)); + } + + for (int i = 0; i < intCount; i++) { + m_intArgs.push_back(dis->readInt()); + } } // Write chat packet (throws IOException) -void ChatPacket::write(DataOutputStream *dos) -{ - dos->writeShort(m_messageType); +void ChatPacket::write(DataOutputStream* dos) { + dos->writeShort(m_messageType); - short packedCounts = 0; - packedCounts |= (m_stringArgs.size() & 0xF) << 4; - packedCounts |= (m_intArgs.size() & 0xF) << 0; + short packedCounts = 0; + packedCounts |= (m_stringArgs.size() & 0xF) << 4; + packedCounts |= (m_intArgs.size() & 0xF) << 0; - dos->writeShort(packedCounts); + dos->writeShort(packedCounts); - for(int i = 0; i < m_stringArgs.size(); i++) - { - writeUtf(m_stringArgs[i], dos); -} + for (int i = 0; i < m_stringArgs.size(); i++) { + writeUtf(m_stringArgs[i], dos); + } - for(int i = 0; i < m_intArgs.size(); i++) - { - dos->writeInt(m_intArgs[i]); - } + for (int i = 0; i < m_intArgs.size(); i++) { + dos->writeInt(m_intArgs[i]); + } } // Handle chat packet -void ChatPacket::handle(PacketListener *listener) -{ - listener->handleChat(shared_from_this()); +void ChatPacket::handle(PacketListener* listener) { + listener->handleChat(shared_from_this()); } -// Get an estimated size of the packet -int ChatPacket::getEstimatedSize() -{ - int stringsSize = 0; - for(int i = 0; i < m_stringArgs.size(); i++) - { - stringsSize += m_stringArgs[i].length(); - } +// Get an estimated size of the packet +int ChatPacket::getEstimatedSize() { + int stringsSize = 0; + for (int i = 0; i < m_stringArgs.size(); i++) { + stringsSize += m_stringArgs[i].length(); + } - return - sizeof(EChatPacketMessage) + // message type - sizeof(short) + // packed arg counts - stringsSize + // string args - (m_intArgs.size() * sizeof(int)); // int args + return sizeof(EChatPacketMessage) + // message type + sizeof(short) + // packed arg counts + stringsSize + // string args + (m_intArgs.size() * sizeof(int)); // int args } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/ChatPacket.h b/Minecraft.World/Network/Packets/ChatPacket.h index fd69a6d9a..80885bbce 100644 --- a/Minecraft.World/Network/Packets/ChatPacket.h +++ b/Minecraft.World/Network/Packets/ChatPacket.h @@ -1,98 +1,119 @@ #pragma once - #include "Packet.h" -class ChatPacket : public Packet, public std::enable_shared_from_this -{ +class ChatPacket : public Packet, + public std::enable_shared_from_this { // longest allowed string is "<" + name + "> " + message private: - static const unsigned int MAX_LENGTH; + static const unsigned int MAX_LENGTH; public: - // 4J - We want to be able to localise the messages sent. The enum also allows for the posibility that there - // may be different versions playing the game, so the enum should map to a string id which may be different on - // different versions - enum EChatPacketMessage - { - e_ChatCustom = 0, // No localised string, only the text passed in - e_ChatBedOccupied, - e_ChatBedNoSleep, - e_ChatBedNotValid, - e_ChatBedNotSafe, - e_ChatBedPlayerSleep, - e_ChatBedMeSleep, - e_ChatPlayerLeftGame, - e_ChatPlayerJoinedGame, - e_ChatPlayerKickedFromGame, - e_ChatCannotPlaceLava, + // 4J - We want to be able to localise the messages sent. The enum also + // allows for the posibility that there may be different versions playing + // the game, so the enum should map to a string id which may be different on + // different versions + enum EChatPacketMessage { + e_ChatCustom = 0, // No localised string, only the text passed in + e_ChatBedOccupied, + e_ChatBedNoSleep, + e_ChatBedNotValid, + e_ChatBedNotSafe, + e_ChatBedPlayerSleep, + e_ChatBedMeSleep, + e_ChatPlayerLeftGame, + e_ChatPlayerJoinedGame, + e_ChatPlayerKickedFromGame, + e_ChatCannotPlaceLava, - e_ChatDeathInFire, - e_ChatDeathOnFire, - e_ChatDeathLava, - e_ChatDeathInWall, - e_ChatDeathDrown, - e_ChatDeathStarve, - e_ChatDeathCactus, - e_ChatDeathFall, - e_ChatDeathOutOfWorld, - e_ChatDeathGeneric, - e_ChatDeathExplosion, - e_ChatDeathMagic, - e_ChatDeathMob, - e_ChatDeathPlayer, - e_ChatDeathArrow, - e_ChatDeathFireball, - e_ChatDeathThrown, - e_ChatDeathIndirectMagic, - e_ChatDeathDragonBreath, - e_ChatDeathWither, - e_ChatDeathAnvil, - e_ChatDeathFallingBlock, - e_ChatDeathThorns, + e_ChatDeathInFire, + e_ChatDeathOnFire, + e_ChatDeathLava, + e_ChatDeathInWall, + e_ChatDeathDrown, + e_ChatDeathStarve, + e_ChatDeathCactus, + e_ChatDeathFall, + e_ChatDeathOutOfWorld, + e_ChatDeathGeneric, + e_ChatDeathExplosion, + e_ChatDeathMagic, + e_ChatDeathMob, + e_ChatDeathPlayer, + e_ChatDeathArrow, + e_ChatDeathFireball, + e_ChatDeathThrown, + e_ChatDeathIndirectMagic, + e_ChatDeathDragonBreath, + e_ChatDeathWither, + e_ChatDeathAnvil, + e_ChatDeathFallingBlock, + e_ChatDeathThorns, - e_ChatPlayerEnteredEnd, - e_ChatPlayerLeftEnd, + e_ChatPlayerEnteredEnd, + e_ChatPlayerLeftEnd, - e_ChatPlayerMaxPigsSheepCows, // tell the players they can't use the spawn egg - e_ChatPlayerMaxChickens, // tell the players they can't use the spawn egg - e_ChatPlayerMaxSquid, // tell the players they can't use the spawn egg - e_ChatPlayerMaxMooshrooms, // tell the players they can't use the spawn egg - e_ChatPlayerMaxWolves, // tell the players they can't use the spawn egg - e_ChatPlayerMaxAnimals, // tell the players they can't use the spawn egg - e_ChatPlayerMaxEnemies, // tell the players they can't use the spawn egg - e_ChatPlayerMaxVillagers, // tell the players they can't use the spawn egg - e_ChatPlayerMaxHangingEntities, // tell the players they hit the picture/itemframe limit - e_ChatPlayerCantSpawnInPeaceful, // Tell the player they can't spawn enemies in peaceful mode - e_ChatPlayerMaxBredAnimals, // Tell the player they can't put this animal in love mode because no breeding can be done - e_ChatPlayerMaxBredPigsSheepCows, // Tell the player they can't put this animal in love mode because no breeding can be done - e_ChatPlayerMaxBredChickens, // Tell the player they can't put this animal in love mode because no breeding can be done - e_ChatPlayerMaxBredMooshrooms, // Tell the player they can't put this animal in love mode because no breeding can be done - e_ChatPlayerMaxBredWolves, // Tell the player they can't put this wolf in love mode because no breeding can be done - e_ChatPlayerCantShearMooshroom, // Tell the player they can't shear because the limits have been reached - e_ChatPlayerMaxBoats, + e_ChatPlayerMaxPigsSheepCows, // tell the players they can't use the + // spawn egg + e_ChatPlayerMaxChickens, // tell the players they can't use the spawn + // egg + e_ChatPlayerMaxSquid, // tell the players they can't use the spawn egg + e_ChatPlayerMaxMooshrooms, // tell the players they can't use the spawn + // egg + e_ChatPlayerMaxWolves, // tell the players they can't use the spawn egg + e_ChatPlayerMaxAnimals, // tell the players they can't use the spawn + // egg + e_ChatPlayerMaxEnemies, // tell the players they can't use the spawn + // egg + e_ChatPlayerMaxVillagers, // tell the players they can't use the spawn + // egg + e_ChatPlayerMaxHangingEntities, // tell the players they hit the + // picture/itemframe limit + e_ChatPlayerCantSpawnInPeaceful, // Tell the player they can't spawn + // enemies in peaceful mode + e_ChatPlayerMaxBredAnimals, // Tell the player they can't put this + // animal in love mode because no breeding + // can be done + e_ChatPlayerMaxBredPigsSheepCows, // Tell the player they can't put + // this animal in love mode because + // no breeding can be done + e_ChatPlayerMaxBredChickens, // Tell the player they can't put this + // animal in love mode because no breeding + // can be done + e_ChatPlayerMaxBredMooshrooms, // Tell the player they can't put this + // animal in love mode because no + // breeding can be done + e_ChatPlayerMaxBredWolves, // Tell the player they can't put this wolf + // in love mode because no breeding can be + // done + e_ChatPlayerCantShearMooshroom, // Tell the player they can't shear + // because the limits have been reached + e_ChatPlayerMaxBoats, - e_ChatCommandTeleportSuccess, - e_ChatCommandTeleportMe, - e_ChatCommandTeleportToMe, + e_ChatCommandTeleportSuccess, + e_ChatCommandTeleportMe, + e_ChatCommandTeleportToMe, - }; + }; public: - std::vector m_stringArgs; - std::vector m_intArgs; - EChatPacketMessage m_messageType; + std::vector m_stringArgs; + std::vector m_intArgs; + EChatPacketMessage m_messageType; - ChatPacket(); - ChatPacket(const std::wstring& message, EChatPacketMessage type = e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L""); + ChatPacket(); + ChatPacket(const std::wstring& message, + EChatPacketMessage type = e_ChatCustom, int customData = -1, + const std::wstring& additionalMessage = L""); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ChatPacket()); } - virtual int getId() { return 3; } + static std::shared_ptr create() { + return std::shared_ptr(new ChatPacket()); + } + virtual int getId() { return 3; } }; - diff --git a/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.cpp b/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.cpp index d1e6cdae2..54308acec 100644 --- a/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.cpp +++ b/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.cpp @@ -7,168 +7,154 @@ #include "ChunkTilesUpdatePacket.h" #include "../../Level/Dimensions/Dimension.h" - - -ChunkTilesUpdatePacket::~ChunkTilesUpdatePacket() -{ - delete [] blocks.data; - delete [] data.data; - delete [] positions.data; +ChunkTilesUpdatePacket::~ChunkTilesUpdatePacket() { + delete[] blocks.data; + delete[] data.data; + delete[] positions.data; } -ChunkTilesUpdatePacket::ChunkTilesUpdatePacket() -{ - shouldDelay = true; - xc = 0; - zc = 0; - count = (uint8_t)0; +ChunkTilesUpdatePacket::ChunkTilesUpdatePacket() { + shouldDelay = true; + xc = 0; + zc = 0; + count = (uint8_t)0; } -ChunkTilesUpdatePacket::ChunkTilesUpdatePacket(int xc, int zc, shortArray positions, uint8_t count, Level *level) -{ - shouldDelay = true; - this->xc = xc; - this->zc = zc; - this->count = count; - this->positions = shortArray((short int)count); +ChunkTilesUpdatePacket::ChunkTilesUpdatePacket(int xc, int zc, + shortArray positions, + uint8_t count, Level* level) { + shouldDelay = true; + this->xc = xc; + this->zc = zc; + this->count = count; + this->positions = shortArray((short int)count); - this->blocks = byteArray((unsigned int)count); - this->data = byteArray((unsigned int)count); - LevelChunk *levelChunk = level->getChunk(xc, zc); - for (int i = 0; (uint8_t)i < count; i++) - { - int x = (positions[i] >> 12) & 15; - int z = (positions[i] >> 8) & 15; - int y = (positions[i]) & 255; + this->blocks = byteArray((unsigned int)count); + this->data = byteArray((unsigned int)count); + LevelChunk* levelChunk = level->getChunk(xc, zc); + for (int i = 0; (uint8_t)i < count; i++) { + int x = (positions[i] >> 12) & 15; + int z = (positions[i] >> 8) & 15; + int y = (positions[i]) & 255; - this->positions[i] = positions[i]; - blocks[i] = (uint8_t) levelChunk->getTile(x, y, z); - data[i] = (uint8_t) levelChunk->getData(x, y, z); - } - levelIdx = ( ( level->dimension->id == 0 ) ? 0 : ( (level->dimension->id == -1) ? 1 : 2 ) ); + this->positions[i] = positions[i]; + blocks[i] = (uint8_t)levelChunk->getTile(x, y, z); + data[i] = (uint8_t)levelChunk->getData(x, y, z); + } + levelIdx = + ((level->dimension->id == 0) ? 0 + : ((level->dimension->id == -1) ? 1 : 2)); } -void ChunkTilesUpdatePacket::read(DataInputStream *dis) //throws IOException +void ChunkTilesUpdatePacket::read(DataInputStream* dis) // throws IOException { - // 4J - changed format. See comments in write method. + // 4J - changed format. See comments in write method. #ifdef _LARGE_WORLDS - xc = dis->readShort(); - zc = dis->readShort(); - // 4jcraft changed shift back and forth to a down cast - xc = (int16_t) xc; - zc = (int16_t) zc; + xc = dis->readShort(); + zc = dis->readShort(); + // 4jcraft changed shift back and forth to a down cast + xc = (int16_t)xc; + zc = (int16_t)zc; #else - xc = dis->read(); - zc = dis->read(); - xc = ( xc << 24 ) >> 24; - zc = ( zc << 24 ) >> 24; + xc = dis->read(); + zc = dis->read(); + xc = (xc << 24) >> 24; + zc = (zc << 24) >> 24; #endif - int countAndFlags = (int)dis->readByte(); - bool dataAllZero = (( countAndFlags & 0x80 ) == 0x80 ); - levelIdx = ( countAndFlags >> 5 ) & 3; - count = (uint8_t)countAndFlags & (uint8_t)0x1f; + int countAndFlags = (int)dis->readByte(); + bool dataAllZero = ((countAndFlags & 0x80) == 0x80); + levelIdx = (countAndFlags >> 5) & 3; + count = (uint8_t)countAndFlags & (uint8_t)0x1f; - positions = shortArray((short int)count); - blocks = byteArray((unsigned int)count); - data = byteArray((unsigned int)count); + positions = shortArray((short int)count); + blocks = byteArray((unsigned int)count); + data = byteArray((unsigned int)count); - int currentBlockType = -1; - for( int i = 0; (uint8_t)i < count; i++ ) - { - int xzAndFlag = dis->readShort(); - int y = (int)dis->readByte(); - positions[i] = (xzAndFlag & 0xff00) | (y & 0xff); - if( ( xzAndFlag & 0x0080 ) == 0x0080 ) - { - currentBlockType = dis->read(); - } - blocks[i] = (uint8_t)currentBlockType; - if( !dataAllZero) - { - data[i] = (uint8_t)dis->read(); - } - else - { - data[i] = (uint8_t)0; - } - } + int currentBlockType = -1; + for (int i = 0; (uint8_t)i < count; i++) { + int xzAndFlag = dis->readShort(); + int y = (int)dis->readByte(); + positions[i] = (xzAndFlag & 0xff00) | (y & 0xff); + if ((xzAndFlag & 0x0080) == 0x0080) { + currentBlockType = dis->read(); + } + blocks[i] = (uint8_t)currentBlockType; + if (!dataAllZero) { + data[i] = (uint8_t)dis->read(); + } else { + data[i] = (uint8_t)0; + } + } } -void ChunkTilesUpdatePacket::write(DataOutputStream *dos) //throws IOException +void ChunkTilesUpdatePacket::write(DataOutputStream* dos) // throws IOException { - // 4J - changed format to reduce size of these packets. + // 4J - changed format to reduce size of these packets. #ifdef _LARGE_WORLDS - dos->writeShort(xc); - dos->writeShort(zc); + dos->writeShort(xc); + dos->writeShort(zc); #else - dos->write(xc); - dos->write(zc); + dos->write(xc); + dos->write(zc); #endif - // Determine if we've got any data elements that are non-zero - a large % of these packets set all data to zero, so we don't - // bother sending all those zeros in that case. - bool dataAllZero = true; - for( int i = 0; i < (int)count; i++ ) - { - if( (bool)data[i] ) dataAllZero = false; - } - int countAndFlags = (int)count; - if( (bool)dataAllZero ) countAndFlags |= 0x80; - countAndFlags |= ( levelIdx << 5 ); - dos->write(countAndFlags); - int lastBlockType = -1; - // Each block is represented by 15 bits of position, a flag to say whether the current block type is to change, and a possible data value. - // A large % of these packets set the same block type to a several positions, so no point resending the block type when not necessary. - for( int i = 0; i < (int)count; i++ ) - { - int xzAndFlag = positions[i] &0xff00; - int y = positions[i] & 0xff; - int thisBlockType = (int)blocks[i]; - if( thisBlockType != lastBlockType ) - { - xzAndFlag |= 0x0080; // Use top bit of y as a flag, we only need 7 bits for that - dos->writeShort(xzAndFlag); - dos->write(y); - dos->write(thisBlockType); - lastBlockType = thisBlockType; - } - else - { - dos->writeShort(xzAndFlag); - dos->write(y); - } - if( !dataAllZero ) - { - dos->write((unsigned int)data[i]); - } - } + // Determine if we've got any data elements that are non-zero - a large % of + // these packets set all data to zero, so we don't bother sending all those + // zeros in that case. + bool dataAllZero = true; + for (int i = 0; i < (int)count; i++) { + if ((bool)data[i]) dataAllZero = false; + } + int countAndFlags = (int)count; + if ((bool)dataAllZero) countAndFlags |= 0x80; + countAndFlags |= (levelIdx << 5); + dos->write(countAndFlags); + int lastBlockType = -1; + // Each block is represented by 15 bits of position, a flag to say whether + // the current block type is to change, and a possible data value. A large % + // of these packets set the same block type to a several positions, so no + // point resending the block type when not necessary. + for (int i = 0; i < (int)count; i++) { + int xzAndFlag = positions[i] & 0xff00; + int y = positions[i] & 0xff; + int thisBlockType = (int)blocks[i]; + if (thisBlockType != lastBlockType) { + xzAndFlag |= 0x0080; // Use top bit of y as a flag, we only need 7 + // bits for that + dos->writeShort(xzAndFlag); + dos->write(y); + dos->write(thisBlockType); + lastBlockType = thisBlockType; + } else { + dos->writeShort(xzAndFlag); + dos->write(y); + } + if (!dataAllZero) { + dos->write((unsigned int)data[i]); + } + } } -void ChunkTilesUpdatePacket::handle(PacketListener *listener) -{ - listener->handleChunkTilesUpdate(shared_from_this()); +void ChunkTilesUpdatePacket::handle(PacketListener* listener) { + listener->handleChunkTilesUpdate(shared_from_this()); } -int ChunkTilesUpdatePacket::getEstimatedSize() -{ - bool dataAllZero = true; - int lastBlockType = -1; - int blockTypeChanges = 0; - for( int i = 0; i < (int)count; i++ ) - { - if( (bool)data[i] ) dataAllZero = false; - int thisBlockType = (int)blocks[i]; - if( thisBlockType != lastBlockType ) - { - blockTypeChanges++; - lastBlockType = thisBlockType; - } - } - int byteCount = 3 + 2 * (int)count + blockTypeChanges; - if( !dataAllZero ) - { - byteCount += (unsigned char) count; - } +int ChunkTilesUpdatePacket::getEstimatedSize() { + bool dataAllZero = true; + int lastBlockType = -1; + int blockTypeChanges = 0; + for (int i = 0; i < (int)count; i++) { + if ((bool)data[i]) dataAllZero = false; + int thisBlockType = (int)blocks[i]; + if (thisBlockType != lastBlockType) { + blockTypeChanges++; + lastBlockType = thisBlockType; + } + } + int byteCount = 3 + 2 * (int)count + blockTypeChanges; + if (!dataAllZero) { + byteCount += (unsigned char)count; + } - return byteCount; + return byteCount; } diff --git a/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.h b/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.h index 8790645a6..6ac842e1a 100644 --- a/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.h +++ b/Minecraft.World/Network/Packets/ChunkTilesUpdatePacket.h @@ -1,31 +1,33 @@ #pragma once - #include "Packet.h" class Level; -class ChunkTilesUpdatePacket : public Packet, public std::enable_shared_from_this -{ +class ChunkTilesUpdatePacket + : public Packet, + public std::enable_shared_from_this { public: - int xc, zc; + int xc, zc; shortArray positions; byteArray blocks; byteArray data; - uint8_t count; // 4J Was int but never has a value higher than 10 - int levelIdx; + uint8_t count; // 4J Was int but never has a value higher than 10 + int levelIdx; - ChunkTilesUpdatePacket(); - ~ChunkTilesUpdatePacket(); - ChunkTilesUpdatePacket(int xc, int zc, shortArray positions, uint8_t count, Level *level); + ChunkTilesUpdatePacket(); + ~ChunkTilesUpdatePacket(); + ChunkTilesUpdatePacket(int xc, int zc, shortArray positions, uint8_t count, + Level* level); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ChunkTilesUpdatePacket()); } - virtual int getId() { return 52; } + static std::shared_ptr create() { + return std::shared_ptr(new ChunkTilesUpdatePacket()); + } + virtual int getId() { return 52; } }; - diff --git a/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.cpp b/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.cpp index 025fe88ce..21ac83a91 100644 --- a/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.cpp +++ b/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.cpp @@ -5,47 +5,41 @@ #include "PacketListener.h" #include "ChunkVisibilityAreaPacket.h" - - -ChunkVisibilityAreaPacket::ChunkVisibilityAreaPacket() -{ - m_minX = 0; - m_maxX = 0; - m_minZ = 0; - m_maxZ = 0; +ChunkVisibilityAreaPacket::ChunkVisibilityAreaPacket() { + m_minX = 0; + m_maxX = 0; + m_minZ = 0; + m_maxZ = 0; } -ChunkVisibilityAreaPacket::ChunkVisibilityAreaPacket(int minX, int maxX, int minZ, int maxZ) -{ - m_minX = minX; - m_maxX = maxX; - m_minZ = minZ; - m_maxZ = maxZ; +ChunkVisibilityAreaPacket::ChunkVisibilityAreaPacket(int minX, int maxX, + int minZ, int maxZ) { + m_minX = minX; + m_maxX = maxX; + m_minZ = minZ; + m_maxZ = maxZ; } -void ChunkVisibilityAreaPacket::read(DataInputStream *dis) //throws IOException +void ChunkVisibilityAreaPacket::read( + DataInputStream* dis) // throws IOException { - m_minX = dis->readInt(); - m_maxX = dis->readInt(); - m_minZ = dis->readInt(); - m_maxZ = dis->readInt(); + m_minX = dis->readInt(); + m_maxX = dis->readInt(); + m_minZ = dis->readInt(); + m_maxZ = dis->readInt(); } -void ChunkVisibilityAreaPacket::write(DataOutputStream *dos) // throws IOException +void ChunkVisibilityAreaPacket::write( + DataOutputStream* dos) // throws IOException { - dos->writeInt(m_minX); - dos->writeInt(m_maxX); - dos->writeInt(m_minZ); - dos->writeInt(m_maxZ); + dos->writeInt(m_minX); + dos->writeInt(m_maxX); + dos->writeInt(m_minZ); + dos->writeInt(m_maxZ); } -void ChunkVisibilityAreaPacket::handle(PacketListener *listener) -{ - listener->handleChunkVisibilityArea(shared_from_this()); -} - -int ChunkVisibilityAreaPacket::getEstimatedSize() -{ - return 16; +void ChunkVisibilityAreaPacket::handle(PacketListener* listener) { + listener->handleChunkVisibilityArea(shared_from_this()); } +int ChunkVisibilityAreaPacket::getEstimatedSize() { return 16; } diff --git a/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.h b/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.h index fc8cd4c9f..099adf89f 100644 --- a/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.h +++ b/Minecraft.World/Network/Packets/ChunkVisibilityAreaPacket.h @@ -1,30 +1,33 @@ #pragma once - #include "Packet.h" class Level; -// 4J Added this packet so that when a player initially joins the game we just need to send them the area of chunks -// around them rather than one packet for each chunk -class ChunkVisibilityAreaPacket : public Packet, public std::enable_shared_from_this -{ +// 4J Added this packet so that when a player initially joins the game we just +// need to send them the area of chunks around them rather than one packet for +// each chunk +class ChunkVisibilityAreaPacket + : public Packet, + public std::enable_shared_from_this { public: int m_minX, m_maxX, m_minZ, m_maxZ; private: - //int size; + // int size; public: - ChunkVisibilityAreaPacket(); - ChunkVisibilityAreaPacket(int minX, int maxX, int minZ, int maxZ); + ChunkVisibilityAreaPacket(); + ChunkVisibilityAreaPacket(int minX, int maxX, int minZ, int maxZ); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ChunkVisibilityAreaPacket()); } - virtual int getId() { return 155; } + static std::shared_ptr create() { + return std::shared_ptr(new ChunkVisibilityAreaPacket()); + } + virtual int getId() { return 155; } }; diff --git a/Minecraft.World/Network/Packets/ChunkVisibilityPacket.cpp b/Minecraft.World/Network/Packets/ChunkVisibilityPacket.cpp index 32378bcab..18c4172da 100644 --- a/Minecraft.World/Network/Packets/ChunkVisibilityPacket.cpp +++ b/Minecraft.World/Network/Packets/ChunkVisibilityPacket.cpp @@ -4,44 +4,36 @@ #include "PacketListener.h" #include "ChunkVisibilityPacket.h" - - -ChunkVisibilityPacket::ChunkVisibilityPacket() -{ - this->shouldDelay = false; - x = 0; - z = 0; - visible = false; +ChunkVisibilityPacket::ChunkVisibilityPacket() { + this->shouldDelay = false; + x = 0; + z = 0; + visible = false; } -ChunkVisibilityPacket::ChunkVisibilityPacket(int x, int z, bool visible) -{ - this->shouldDelay = false; - this->x = x; - this->z = z; - this->visible = visible; +ChunkVisibilityPacket::ChunkVisibilityPacket(int x, int z, bool visible) { + this->shouldDelay = false; + this->x = x; + this->z = z; + this->visible = visible; } -void ChunkVisibilityPacket::read(DataInputStream *dis) //throws IOException +void ChunkVisibilityPacket::read(DataInputStream* dis) // throws IOException { - x = dis->readInt(); - z = dis->readInt(); - visible = dis->read() != 0; + x = dis->readInt(); + z = dis->readInt(); + visible = dis->read() != 0; } -void ChunkVisibilityPacket::write(DataOutputStream *dos) //throws IOException +void ChunkVisibilityPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(x); - dos->writeInt(z); - dos->write(visible ? 1 : 0); + dos->writeInt(x); + dos->writeInt(z); + dos->write(visible ? 1 : 0); } -void ChunkVisibilityPacket::handle(PacketListener *listener) -{ - listener->handleChunkVisibility(shared_from_this()); +void ChunkVisibilityPacket::handle(PacketListener* listener) { + listener->handleChunkVisibility(shared_from_this()); } -int ChunkVisibilityPacket::getEstimatedSize() -{ - return 9; -} +int ChunkVisibilityPacket::getEstimatedSize() { return 9; } diff --git a/Minecraft.World/Network/Packets/ChunkVisibilityPacket.h b/Minecraft.World/Network/Packets/ChunkVisibilityPacket.h index 3ae959506..34202ca5f 100644 --- a/Minecraft.World/Network/Packets/ChunkVisibilityPacket.h +++ b/Minecraft.World/Network/Packets/ChunkVisibilityPacket.h @@ -1,29 +1,29 @@ #pragma once - #include "Packet.h" #include "../../Platform/stdafx.h" #include #include "PacketListener.h" -class ChunkVisibilityPacket : public Packet, public std::enable_shared_from_this -{ +class ChunkVisibilityPacket + : public Packet, + public std::enable_shared_from_this { public: - int x, z; + int x, z; bool visible; - ChunkVisibilityPacket(); - ChunkVisibilityPacket(int x, int z, bool visible); + ChunkVisibilityPacket(); + ChunkVisibilityPacket(int x, int z, bool visible); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ChunkVisibilityPacket()); } - virtual int getId() { return 50; } + static std::shared_ptr create() { + return std::shared_ptr(new ChunkVisibilityPacket()); + } + virtual int getId() { return 50; } }; - - diff --git a/Minecraft.World/Network/Packets/ClientCommandPacket.cpp b/Minecraft.World/Network/Packets/ClientCommandPacket.cpp index 09fd1f334..51397673c 100644 --- a/Minecraft.World/Network/Packets/ClientCommandPacket.cpp +++ b/Minecraft.World/Network/Packets/ClientCommandPacket.cpp @@ -2,32 +2,21 @@ #include "PacketListener.h" #include "ClientCommandPacket.h" -ClientCommandPacket::ClientCommandPacket() -{ - action = 0; +ClientCommandPacket::ClientCommandPacket() { action = 0; } + +ClientCommandPacket::ClientCommandPacket(int action) { this->action = action; } + +void ClientCommandPacket::read(DataInputStream* dis) { + action = (int)dis->readByte(); } -ClientCommandPacket::ClientCommandPacket(int action) -{ - this->action = action; +void ClientCommandPacket::write(DataOutputStream* dos) { + dos->writeByte((uint8_t)action & (uint8_t)0xff); } -void ClientCommandPacket::read(DataInputStream *dis) -{ - action = (int)dis->readByte(); +void ClientCommandPacket::handle(PacketListener* listener) { + listener->handleClientCommand( + std::dynamic_pointer_cast(shared_from_this())); } -void ClientCommandPacket::write(DataOutputStream *dos) -{ - dos->writeByte((uint8_t)action & (uint8_t)0xff); -} - -void ClientCommandPacket::handle(PacketListener *listener) -{ - listener->handleClientCommand(std::dynamic_pointer_cast(shared_from_this())); -} - -int ClientCommandPacket::getEstimatedSize() -{ - return 1; -} +int ClientCommandPacket::getEstimatedSize() { return 1; } diff --git a/Minecraft.World/Network/Packets/ClientCommandPacket.h b/Minecraft.World/Network/Packets/ClientCommandPacket.h index 2a061ee8e..26cf80fd8 100644 --- a/Minecraft.World/Network/Packets/ClientCommandPacket.h +++ b/Minecraft.World/Network/Packets/ClientCommandPacket.h @@ -2,23 +2,26 @@ #include "Packet.h" -class ClientCommandPacket : public Packet, public std::enable_shared_from_this -{ +class ClientCommandPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int LOGIN_COMPLETE = 0; - static const int PERFORM_RESPAWN = 1; + static const int LOGIN_COMPLETE = 0; + static const int PERFORM_RESPAWN = 1; - int action; + int action; - ClientCommandPacket(); - ClientCommandPacket(int action); + ClientCommandPacket(); + ClientCommandPacket(int action); - void read(DataInputStream *dis); - void write(DataOutputStream *dos); - void handle(PacketListener *listener); - int getEstimatedSize(); + void read(DataInputStream* dis); + void write(DataOutputStream* dos); + void handle(PacketListener* listener); + int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ClientCommandPacket()); } - virtual int getId() { return 205; } + static std::shared_ptr create() { + return std::shared_ptr(new ClientCommandPacket()); + } + virtual int getId() { return 205; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/ClientInformationPacket.h b/Minecraft.World/Network/Packets/ClientInformationPacket.h index 38dde4609..3701384ee 100644 --- a/Minecraft.World/Network/Packets/ClientInformationPacket.h +++ b/Minecraft.World/Network/Packets/ClientInformationPacket.h @@ -2,8 +2,7 @@ #include "../../Platform/stdafx.h" -class ClientInformationPacket : public Packet -{ +class ClientInformationPacket : public Packet { #if 0 private String language; private int viewDistance; diff --git a/Minecraft.World/Network/Packets/ClientProtocolPacket.h b/Minecraft.World/Network/Packets/ClientProtocolPacket.h index 9b708d162..9b71ad440 100644 --- a/Minecraft.World/Network/Packets/ClientProtocolPacket.h +++ b/Minecraft.World/Network/Packets/ClientProtocolPacket.h @@ -2,8 +2,7 @@ #include "Packet.h" -class ClientProtocolPacket : public Packet -{ +class ClientProtocolPacket : public Packet { #if 0 private int protocolVersion; private String userName; diff --git a/Minecraft.World/Network/Packets/ComplexItemDataPacket.cpp b/Minecraft.World/Network/Packets/ComplexItemDataPacket.cpp index ebcde2925..a5b108de2 100644 --- a/Minecraft.World/Network/Packets/ComplexItemDataPacket.cpp +++ b/Minecraft.World/Network/Packets/ComplexItemDataPacket.cpp @@ -4,54 +4,47 @@ #include "PacketListener.h" #include "ComplexItemDataPacket.h" +ComplexItemDataPacket::~ComplexItemDataPacket() { delete[] data.data; } - -ComplexItemDataPacket::~ComplexItemDataPacket() -{ - delete [] data.data; +ComplexItemDataPacket::ComplexItemDataPacket() { + shouldDelay = true; + itemType = 0; } -ComplexItemDataPacket::ComplexItemDataPacket() -{ - shouldDelay = true; - itemType = 0; +ComplexItemDataPacket::ComplexItemDataPacket(short itemType, short itemId, + charArray data) { + shouldDelay = true; + this->itemType = itemType; + this->itemId = itemId; + // Take copy of array passed in as we want the packets to have full + // ownership of any data they reference + this->data = charArray(data.length); + memcpy(this->data.data, data.data, data.length); } -ComplexItemDataPacket::ComplexItemDataPacket(short itemType, short itemId, charArray data) +void ComplexItemDataPacket::read(DataInputStream* dis) // throws IOException { - shouldDelay = true; - this->itemType = itemType; - this->itemId = itemId; - // Take copy of array passed in as we want the packets to have full ownership of any data they reference - this->data = charArray(data.length); - memcpy(this->data.data, data.data, data.length); + itemType = dis->readShort(); + itemId = dis->readShort(); + + data = charArray(dis->readShort() & 0xffff); + dis->readFully(data); } -void ComplexItemDataPacket::read(DataInputStream *dis) //throws IOException +void ComplexItemDataPacket::write(DataOutputStream* dos) // throws IOException { - itemType = dis->readShort(); - itemId = dis->readShort(); + dos->writeShort(itemType); + dos->writeShort(itemId); + dos->writeShort(data.length); - data = charArray(dis->readShort() & 0xffff); - dis->readFully(data); + byteArray ba((uint8_t*)data.data, data.length); + dos->write(ba); } -void ComplexItemDataPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeShort(itemType); - dos->writeShort(itemId); - dos->writeShort(data.length); - - byteArray ba( (uint8_t*)data.data, data.length ); - dos->write(ba); +void ComplexItemDataPacket::handle(PacketListener* listener) { + listener->handleComplexItemData(shared_from_this()); } -void ComplexItemDataPacket::handle(PacketListener *listener) -{ - listener->handleComplexItemData( shared_from_this() ); -} - -int ComplexItemDataPacket::getEstimatedSize() -{ - return 2+2+2+ data.length; +int ComplexItemDataPacket::getEstimatedSize() { + return 2 + 2 + 2 + data.length; } diff --git a/Minecraft.World/Network/Packets/ComplexItemDataPacket.h b/Minecraft.World/Network/Packets/ComplexItemDataPacket.h index e502a72b0..9f51b1c2a 100644 --- a/Minecraft.World/Network/Packets/ComplexItemDataPacket.h +++ b/Minecraft.World/Network/Packets/ComplexItemDataPacket.h @@ -1,27 +1,27 @@ #pragma once - #include "Packet.h" -class ComplexItemDataPacket : public Packet, public std::enable_shared_from_this -{ +class ComplexItemDataPacket + : public Packet, + public std::enable_shared_from_this { public: - short itemType; + short itemType; short itemId; charArray data; - ComplexItemDataPacket(); - ~ComplexItemDataPacket(); - ComplexItemDataPacket(short itemType, short itemId, charArray data); + ComplexItemDataPacket(); + ~ComplexItemDataPacket(); + ComplexItemDataPacket(short itemType, short itemId, charArray data); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ComplexItemDataPacket()); } - virtual int getId() { return 131; } + static std::shared_ptr create() { + return std::shared_ptr(new ComplexItemDataPacket()); + } + virtual int getId() { return 131; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerAckPacket.cpp b/Minecraft.World/Network/Packets/ContainerAckPacket.cpp index 17e3ee017..b78211a49 100644 --- a/Minecraft.World/Network/Packets/ContainerAckPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerAckPacket.cpp @@ -4,42 +4,35 @@ #include "PacketListener.h" #include "ContainerAckPacket.h" - - -ContainerAckPacket::ContainerAckPacket() -{ - containerId = 0; - uid = 0; - accepted = 0; +ContainerAckPacket::ContainerAckPacket() { + containerId = 0; + uid = 0; + accepted = 0; } -ContainerAckPacket::ContainerAckPacket(int containerId, short uid, bool accepted) -{ - this->containerId = containerId; - this->uid = uid; - this->accepted = accepted; +ContainerAckPacket::ContainerAckPacket(int containerId, short uid, + bool accepted) { + this->containerId = containerId; + this->uid = uid; + this->accepted = accepted; } -void ContainerAckPacket::handle(PacketListener *listener) -{ - listener->handleContainerAck(shared_from_this()); +void ContainerAckPacket::handle(PacketListener* listener) { + listener->handleContainerAck(shared_from_this()); } -void ContainerAckPacket::read(DataInputStream *dis) //throws IOException +void ContainerAckPacket::read(DataInputStream* dis) // throws IOException { - containerId = (int)dis->readByte(); - uid = dis->readShort(); - accepted = (int)dis->readByte() != 0; + containerId = (int)dis->readByte(); + uid = dis->readShort(); + accepted = (int)dis->readByte() != 0; } -void ContainerAckPacket::write(DataOutputStream *dos) //throws IOException +void ContainerAckPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte((uint8_t)containerId); - dos->writeShort(uid); - dos->writeByte((uint8_t)(accepted ? 1 : 0)); + dos->writeByte((uint8_t)containerId); + dos->writeShort(uid); + dos->writeByte((uint8_t)(accepted ? 1 : 0)); } -int ContainerAckPacket::getEstimatedSize() -{ - return 4; -} +int ContainerAckPacket::getEstimatedSize() { return 4; } diff --git a/Minecraft.World/Network/Packets/ContainerAckPacket.h b/Minecraft.World/Network/Packets/ContainerAckPacket.h index 2faeffee2..92a931fa4 100644 --- a/Minecraft.World/Network/Packets/ContainerAckPacket.h +++ b/Minecraft.World/Network/Packets/ContainerAckPacket.h @@ -1,30 +1,30 @@ #pragma once - #include "Packet.h" #include "../../Platform/stdafx.h" #include #include "PacketListener.h" -class ContainerAckPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerAckPacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; + int containerId; short uid; bool accepted; - ContainerAckPacket(); - ContainerAckPacket(int containerId, short uid, bool accepted); + ContainerAckPacket(); + ContainerAckPacket(int containerId, short uid, bool accepted); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerAckPacket()); } - virtual int getId() { return 106; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerAckPacket()); + } + virtual int getId() { return 106; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerButtonClickPacket.cpp b/Minecraft.World/Network/Packets/ContainerButtonClickPacket.cpp index 93b665147..512535ded 100644 --- a/Minecraft.World/Network/Packets/ContainerButtonClickPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerButtonClickPacket.cpp @@ -5,36 +5,26 @@ #include "PacketListener.h" #include "ContainerButtonClickPacket.h" +ContainerButtonClickPacket::ContainerButtonClickPacket() {} - -ContainerButtonClickPacket::ContainerButtonClickPacket() -{ +ContainerButtonClickPacket::ContainerButtonClickPacket(int containerId, + int buttonId) { + this->containerId = containerId; + this->buttonId = buttonId; } -ContainerButtonClickPacket::ContainerButtonClickPacket(int containerId, int buttonId) -{ - this->containerId = containerId; - this->buttonId = buttonId; +void ContainerButtonClickPacket::handle(PacketListener* listener) { + listener->handleContainerButtonClick(shared_from_this()); } -void ContainerButtonClickPacket::handle(PacketListener *listener) -{ - listener->handleContainerButtonClick(shared_from_this()); +void ContainerButtonClickPacket::read(DataInputStream* dis) { + containerId = (int)dis->readByte(); + buttonId = (int)dis->readByte(); } -void ContainerButtonClickPacket::read(DataInputStream *dis) -{ - containerId = (int)dis->readByte(); - buttonId = (int)dis->readByte(); +void ContainerButtonClickPacket::write(DataOutputStream* dos) { + dos->writeByte((uint8_t)containerId); + dos->writeByte((uint8_t)buttonId); } -void ContainerButtonClickPacket::write(DataOutputStream *dos) -{ - dos->writeByte((uint8_t)containerId); - dos->writeByte((uint8_t)buttonId); -} - -int ContainerButtonClickPacket::getEstimatedSize() -{ - return 2; -} +int ContainerButtonClickPacket::getEstimatedSize() { return 2; } diff --git a/Minecraft.World/Network/Packets/ContainerButtonClickPacket.h b/Minecraft.World/Network/Packets/ContainerButtonClickPacket.h index 88bde9abf..74ac53d93 100644 --- a/Minecraft.World/Network/Packets/ContainerButtonClickPacket.h +++ b/Minecraft.World/Network/Packets/ContainerButtonClickPacket.h @@ -2,21 +2,24 @@ #include "Packet.h" -class ContainerButtonClickPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerButtonClickPacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; - int buttonId; + int containerId; + int buttonId; - ContainerButtonClickPacket(); - ContainerButtonClickPacket(int containerId, int buttonId); + ContainerButtonClickPacket(); + ContainerButtonClickPacket(int containerId, int buttonId); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerButtonClickPacket()); } - virtual int getId() { return 108; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerButtonClickPacket()); + } + virtual int getId() { return 108; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/ContainerClickPacket.cpp b/Minecraft.World/Network/Packets/ContainerClickPacket.cpp index 9a6d140af..ef55b0818 100644 --- a/Minecraft.World/Network/Packets/ContainerClickPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerClickPacket.cpp @@ -5,61 +5,55 @@ #include "PacketListener.h" #include "ContainerClickPacket.h" +ContainerClickPacket::~ContainerClickPacket() {} - -ContainerClickPacket::~ContainerClickPacket() -{ +ContainerClickPacket::ContainerClickPacket() { + containerId = 0; + slotNum = 0; + buttonNum = 0; + uid = 0; + item = nullptr; + quickKey = false; } -ContainerClickPacket::ContainerClickPacket() -{ - containerId = 0; - slotNum = 0; - buttonNum = 0; - uid = 0; - item = nullptr; - quickKey = false; +ContainerClickPacket::ContainerClickPacket(int containerId, int slotNum, + int buttonNum, bool quickKey, + std::shared_ptr item, + short uid) { + this->containerId = containerId; + this->slotNum = slotNum; + this->buttonNum = buttonNum; + this->uid = uid; + this->quickKey = quickKey; + // 4J - make a copy of the relevant bits of this item, as we want our + // packets to have full ownership of any data they reference + this->item = item ? item->copy() : nullptr; } -ContainerClickPacket::ContainerClickPacket(int containerId, int slotNum, int buttonNum, bool quickKey, std::shared_ptr item, short uid) -{ - this->containerId = containerId; - this->slotNum = slotNum; - this->buttonNum = buttonNum; - this->uid = uid; - this->quickKey = quickKey; - // 4J - make a copy of the relevant bits of this item, as we want our packets to have full ownership of any data they reference - this->item = item ? item->copy() : nullptr; +void ContainerClickPacket::handle(PacketListener* listener) { + listener->handleContainerClick(shared_from_this()); } -void ContainerClickPacket::handle(PacketListener *listener) +void ContainerClickPacket::read(DataInputStream* dis) // throws IOException { - listener->handleContainerClick(shared_from_this()); + containerId = (int)dis->readByte(); + slotNum = dis->readShort(); + buttonNum = (int)dis->readByte(); + uid = dis->readShort(); + quickKey = dis->readBoolean(); + + item = readItem(dis); } -void ContainerClickPacket::read(DataInputStream *dis) //throws IOException +void ContainerClickPacket::write(DataOutputStream* dos) // throws IOException { - containerId = (int)dis->readByte(); - slotNum = dis->readShort(); - buttonNum = (int)dis->readByte(); - uid = dis->readShort(); - quickKey = dis->readBoolean(); + dos->writeByte((uint8_t)containerId); + dos->writeShort(slotNum); + dos->writeByte((uint8_t)buttonNum); + dos->writeShort(uid); + dos->writeBoolean(quickKey); - item = readItem(dis); + writeItem(item, dos); } -void ContainerClickPacket::write(DataOutputStream *dos) // throws IOException -{ - dos->writeByte((uint8_t)containerId); - dos->writeShort(slotNum); - dos->writeByte((uint8_t)buttonNum); - dos->writeShort(uid); - dos->writeBoolean(quickKey); - - writeItem(item, dos); -} - -int ContainerClickPacket::getEstimatedSize() -{ - return 4 + 4 + 2 + 1; -} +int ContainerClickPacket::getEstimatedSize() { return 4 + 4 + 2 + 1; } diff --git a/Minecraft.World/Network/Packets/ContainerClickPacket.h b/Minecraft.World/Network/Packets/ContainerClickPacket.h index 6e96afe9c..29ac23c11 100644 --- a/Minecraft.World/Network/Packets/ContainerClickPacket.h +++ b/Minecraft.World/Network/Packets/ContainerClickPacket.h @@ -1,30 +1,32 @@ #pragma once - #include "Packet.h" -class ContainerClickPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerClickPacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; + int containerId; int slotNum; int buttonNum; short uid; std::shared_ptr item; bool quickKey; - ContainerClickPacket(); - ~ContainerClickPacket(); - ContainerClickPacket(int containerId, int slotNum, int buttonNum, bool quickKey, std::shared_ptr item, short uid); + ContainerClickPacket(); + ~ContainerClickPacket(); + ContainerClickPacket(int containerId, int slotNum, int buttonNum, + bool quickKey, std::shared_ptr item, + short uid); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerClickPacket()); } - virtual int getId() { return 102; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerClickPacket()); + } + virtual int getId() { return 102; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerClosePacket.cpp b/Minecraft.World/Network/Packets/ContainerClosePacket.cpp index 2ecafe269..bd8471950 100644 --- a/Minecraft.World/Network/Packets/ContainerClosePacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerClosePacket.cpp @@ -4,34 +4,24 @@ #include "PacketListener.h" #include "ContainerClosePacket.h" +ContainerClosePacket::ContainerClosePacket() { containerId = 0; } - -ContainerClosePacket::ContainerClosePacket() -{ - containerId = 0; +ContainerClosePacket::ContainerClosePacket(int containerId) { + this->containerId = containerId; } -ContainerClosePacket::ContainerClosePacket(int containerId) -{ - this->containerId = containerId; +void ContainerClosePacket::handle(PacketListener* listener) { + listener->handleContainerClose(shared_from_this()); } -void ContainerClosePacket::handle(PacketListener *listener) +void ContainerClosePacket::read(DataInputStream* dis) // throws IOException { - listener->handleContainerClose(shared_from_this()); + containerId = (int)dis->readByte(); } -void ContainerClosePacket::read(DataInputStream *dis) //throws IOException +void ContainerClosePacket::write(DataOutputStream* dos) // throws IOException { - containerId = (int)dis->readByte(); + dos->writeByte((uint8_t)containerId); } -void ContainerClosePacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeByte((uint8_t)containerId); -} - -int ContainerClosePacket::getEstimatedSize() -{ - return 1; -} +int ContainerClosePacket::getEstimatedSize() { return 1; } diff --git a/Minecraft.World/Network/Packets/ContainerClosePacket.h b/Minecraft.World/Network/Packets/ContainerClosePacket.h index f4b13ebe4..3e013c090 100644 --- a/Minecraft.World/Network/Packets/ContainerClosePacket.h +++ b/Minecraft.World/Network/Packets/ContainerClosePacket.h @@ -1,24 +1,24 @@ #pragma once - #include "Packet.h" -class ContainerClosePacket : public Packet, public std::enable_shared_from_this -{ +class ContainerClosePacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; + int containerId; - ContainerClosePacket(); - ContainerClosePacket(int containerId); + ContainerClosePacket(); + ContainerClosePacket(int containerId); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerClosePacket()); } - virtual int getId() { return 101; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerClosePacket()); + } + virtual int getId() { return 101; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerOpenPacket.cpp b/Minecraft.World/Network/Packets/ContainerOpenPacket.cpp index 49913ca86..1395b5b58 100644 --- a/Minecraft.World/Network/Packets/ContainerOpenPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerOpenPacket.cpp @@ -4,45 +4,39 @@ #include "PacketListener.h" #include "ContainerOpenPacket.h" -ContainerOpenPacket::ContainerOpenPacket() -{ - containerId = 0; - type = 0; - title = 0; - size = 0; +ContainerOpenPacket::ContainerOpenPacket() { + containerId = 0; + type = 0; + title = 0; + size = 0; } -ContainerOpenPacket::ContainerOpenPacket(int containerId, int type, int title, int size) -{ - this->containerId = containerId; - this->type = type; - this->title = title; - this->size = size; +ContainerOpenPacket::ContainerOpenPacket(int containerId, int type, int title, + int size) { + this->containerId = containerId; + this->type = type; + this->title = title; + this->size = size; } -void ContainerOpenPacket::handle(PacketListener *listener) -{ - listener->handleContainerOpen(shared_from_this()); +void ContainerOpenPacket::handle(PacketListener* listener) { + listener->handleContainerOpen(shared_from_this()); } - -void ContainerOpenPacket::read(DataInputStream *dis) //throws IOException +void ContainerOpenPacket::read(DataInputStream* dis) // throws IOException { - containerId = (int)(dis->readByte() & (uint8_t)0xff); - type = (int)(dis->readByte() & (uint8_t)0xff); - title = dis->readShort(); - size = (int)(dis->readByte() & (uint8_t)0xff); + containerId = (int)(dis->readByte() & (uint8_t)0xff); + type = (int)(dis->readByte() & (uint8_t)0xff); + title = dis->readShort(); + size = (int)(dis->readByte() & (uint8_t)0xff); } -void ContainerOpenPacket::write(DataOutputStream *dos) //throws IOException +void ContainerOpenPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte((uint8_t)containerId & (uint8_t)0xff); - dos->writeByte((uint8_t)type & (uint8_t)0xff); - dos->writeShort(title & 0xffff); - dos->writeByte((uint8_t)size & (uint8_t)0xff); + dos->writeByte((uint8_t)containerId & (uint8_t)0xff); + dos->writeByte((uint8_t)type & (uint8_t)0xff); + dos->writeShort(title & 0xffff); + dos->writeByte((uint8_t)size & (uint8_t)0xff); } -int ContainerOpenPacket::getEstimatedSize() -{ - return 5; -} +int ContainerOpenPacket::getEstimatedSize() { return 5; } diff --git a/Minecraft.World/Network/Packets/ContainerOpenPacket.h b/Minecraft.World/Network/Packets/ContainerOpenPacket.h index 9aa467d77..772b4f1a2 100644 --- a/Minecraft.World/Network/Packets/ContainerOpenPacket.h +++ b/Minecraft.World/Network/Packets/ContainerOpenPacket.h @@ -1,37 +1,37 @@ #pragma once - #include "Packet.h" -class ContainerOpenPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerOpenPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int CONTAINER = 0; - static const int WORKBENCH = 1; - static const int FURNACE = 2; - static const int TRAP = 3; - static const int ENCHANTMENT = 4; - static const int BREWING_STAND = 5; - static const int TRADER_NPC = 6; - static const int BEACON = 7; - static const int REPAIR_TABLE = 8; + static const int CONTAINER = 0; + static const int WORKBENCH = 1; + static const int FURNACE = 2; + static const int TRAP = 3; + static const int ENCHANTMENT = 4; + static const int BREWING_STAND = 5; + static const int TRADER_NPC = 6; + static const int BEACON = 7; + static const int REPAIR_TABLE = 8; - int containerId; - int type; - int title; // 4J Stu - Changed from string - int size; + int containerId; + int type; + int title; // 4J Stu - Changed from string + int size; - ContainerOpenPacket(); - ContainerOpenPacket(int containerId, int type, int title, int size); + ContainerOpenPacket(); + ContainerOpenPacket(int containerId, int type, int title, int size); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerOpenPacket()); } - virtual int getId() { return 100; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerOpenPacket()); + } + virtual int getId() { return 100; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerSetContentPacket.cpp b/Minecraft.World/Network/Packets/ContainerSetContentPacket.cpp index f4e9e8252..be8ed676c 100644 --- a/Minecraft.World/Network/Packets/ContainerSetContentPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerSetContentPacket.cpp @@ -5,56 +5,45 @@ #include "PacketListener.h" #include "ContainerSetContentPacket.h" +ContainerSetContentPacket::~ContainerSetContentPacket() { delete[] items.data; } +ContainerSetContentPacket::ContainerSetContentPacket() { containerId = 0; } -ContainerSetContentPacket::~ContainerSetContentPacket() -{ - delete[] items.data; +ContainerSetContentPacket::ContainerSetContentPacket( + int containerId, std::vector >* newItems) { + this->containerId = containerId; + items = ItemInstanceArray((int)newItems->size()); + for (unsigned int i = 0; i < items.length; i++) { + std::shared_ptr item = newItems->at(i); + items[i] = item == NULL ? nullptr : item->copy(); + } } -ContainerSetContentPacket::ContainerSetContentPacket() +void ContainerSetContentPacket::read( + DataInputStream* dis) // throws IOException { - containerId = 0; + containerId = (int)dis->readByte(); + int count = dis->readShort(); + items = ItemInstanceArray(count); + for (int i = 0; i < count; i++) { + items[i] = readItem(dis); + } } -ContainerSetContentPacket::ContainerSetContentPacket(int containerId, std::vector > *newItems) +void ContainerSetContentPacket::write( + DataOutputStream* dos) // throws IOException { - this->containerId = containerId; - items = ItemInstanceArray((int)newItems->size()); - for (unsigned int i = 0; i < items.length; i++) - { - std::shared_ptr item = newItems->at(i); - items[i] = item == NULL ? nullptr : item->copy(); - } + dos->writeByte((uint8_t)containerId); + dos->writeShort(items.length); + for (unsigned int i = 0; i < items.length; i++) { + writeItem(items[i], dos); + } } -void ContainerSetContentPacket::read(DataInputStream *dis) //throws IOException -{ - containerId = (int)dis->readByte(); - int count = dis->readShort(); - items = ItemInstanceArray(count); - for (int i = 0; i < count; i++) - { - items[i] = readItem(dis); - } +void ContainerSetContentPacket::handle(PacketListener* listener) { + listener->handleContainerContent(shared_from_this()); } -void ContainerSetContentPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeByte((uint8_t)containerId); - dos->writeShort(items.length); - for (unsigned int i = 0; i < items.length; i++) - { - writeItem(items[i], dos); - } -} - -void ContainerSetContentPacket::handle(PacketListener *listener) -{ - listener->handleContainerContent(shared_from_this()); -} - -int ContainerSetContentPacket::getEstimatedSize() -{ - return 3 + items.length * 5; +int ContainerSetContentPacket::getEstimatedSize() { + return 3 + items.length * 5; } diff --git a/Minecraft.World/Network/Packets/ContainerSetContentPacket.h b/Minecraft.World/Network/Packets/ContainerSetContentPacket.h index 4af928d42..4877f779b 100644 --- a/Minecraft.World/Network/Packets/ContainerSetContentPacket.h +++ b/Minecraft.World/Network/Packets/ContainerSetContentPacket.h @@ -1,26 +1,27 @@ #pragma once - #include "Packet.h" -class ContainerSetContentPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerSetContentPacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; + int containerId; ItemInstanceArray items; - ContainerSetContentPacket(); - ~ContainerSetContentPacket(); - ContainerSetContentPacket(int containerId, std::vector > *newItems); + ContainerSetContentPacket(); + ~ContainerSetContentPacket(); + ContainerSetContentPacket( + int containerId, std::vector >* newItems); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerSetContentPacket()); } - virtual int getId() { return 104; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerSetContentPacket()); + } + virtual int getId() { return 104; } }; - - diff --git a/Minecraft.World/Network/Packets/ContainerSetDataPacket.cpp b/Minecraft.World/Network/Packets/ContainerSetDataPacket.cpp index 4da70a296..a69818a49 100644 --- a/Minecraft.World/Network/Packets/ContainerSetDataPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerSetDataPacket.cpp @@ -4,42 +4,35 @@ #include "PacketListener.h" #include "ContainerSetDataPacket.h" - - -ContainerSetDataPacket::ContainerSetDataPacket() -{ - containerId = 0; - id = -1; - value = 0; +ContainerSetDataPacket::ContainerSetDataPacket() { + containerId = 0; + id = -1; + value = 0; } -ContainerSetDataPacket::ContainerSetDataPacket(int containerId, int id, int value) -{ - this->containerId = containerId; - this->id = id; - this->value = value; +ContainerSetDataPacket::ContainerSetDataPacket(int containerId, int id, + int value) { + this->containerId = containerId; + this->id = id; + this->value = value; } -void ContainerSetDataPacket::handle(PacketListener *listener) -{ - listener->handleContainerSetData(shared_from_this()); +void ContainerSetDataPacket::handle(PacketListener* listener) { + listener->handleContainerSetData(shared_from_this()); } -void ContainerSetDataPacket::read(DataInputStream *dis) //throws IOException +void ContainerSetDataPacket::read(DataInputStream* dis) // throws IOException { - containerId = (int)dis->readByte(); - id = dis->readShort(); - value = dis->readShort(); + containerId = (int)dis->readByte(); + id = dis->readShort(); + value = dis->readShort(); } -void ContainerSetDataPacket::write(DataOutputStream *dos) // throws IOException +void ContainerSetDataPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte((uint8_t)containerId); - dos->writeShort(id); - dos->writeShort(value); + dos->writeByte((uint8_t)containerId); + dos->writeShort(id); + dos->writeShort(value); } -int ContainerSetDataPacket::getEstimatedSize() -{ - return 1 + 4; -} +int ContainerSetDataPacket::getEstimatedSize() { return 1 + 4; } diff --git a/Minecraft.World/Network/Packets/ContainerSetDataPacket.h b/Minecraft.World/Network/Packets/ContainerSetDataPacket.h index 89bb437e7..c612ae9bd 100644 --- a/Minecraft.World/Network/Packets/ContainerSetDataPacket.h +++ b/Minecraft.World/Network/Packets/ContainerSetDataPacket.h @@ -1,24 +1,26 @@ #pragma once - #include "Packet.h" -class ContainerSetDataPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerSetDataPacket + : public Packet, + public std::enable_shared_from_this { public: - int containerId; + int containerId; int id; int value; - ContainerSetDataPacket(); - ContainerSetDataPacket(int containerId, int id, int value); + ContainerSetDataPacket(); + ContainerSetDataPacket(int containerId, int id, int value); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerSetDataPacket()); } - virtual int getId() { return 105; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerSetDataPacket()); + } + virtual int getId() { return 105; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/ContainerSetSlotPacket.cpp b/Minecraft.World/Network/Packets/ContainerSetSlotPacket.cpp index 15fae9311..27ca694d8 100644 --- a/Minecraft.World/Network/Packets/ContainerSetSlotPacket.cpp +++ b/Minecraft.World/Network/Packets/ContainerSetSlotPacket.cpp @@ -5,49 +5,43 @@ #include "PacketListener.h" #include "ContainerSetSlotPacket.h" - - const int ContainerSetSlotPacket::CONTAINER = 0; const int ContainerSetSlotPacket::WORKBENCH = 1; const int ContainerSetSlotPacket::FURNACE = 2; -ContainerSetSlotPacket::ContainerSetSlotPacket() -{ - containerId = 0; - slot = 0; - item = nullptr; +ContainerSetSlotPacket::ContainerSetSlotPacket() { + containerId = 0; + slot = 0; + item = nullptr; } -ContainerSetSlotPacket::ContainerSetSlotPacket(int containerId, int slot, std::shared_ptr item) -{ - this->containerId = containerId; - this->slot = slot; - this->item = item == NULL ? item : item->copy(); +ContainerSetSlotPacket::ContainerSetSlotPacket( + int containerId, int slot, std::shared_ptr item) { + this->containerId = containerId; + this->slot = slot; + this->item = item == NULL ? item : item->copy(); } -void ContainerSetSlotPacket::handle(PacketListener *listener) -{ - listener->handleContainerSetSlot(shared_from_this()); +void ContainerSetSlotPacket::handle(PacketListener* listener) { + listener->handleContainerSetSlot(shared_from_this()); } -void ContainerSetSlotPacket::read(DataInputStream *dis) //throws IOException +void ContainerSetSlotPacket::read(DataInputStream* dis) // throws IOException { - // 4J Stu - TU-1 hotfix - // Fix for #13142 - Holding down the A button on the furnace ingredient slot causes the UI to display incorrect item counts - uint8_t byteId = dis->readByte(); - containerId = *(char *)&byteId; - slot = dis->readShort(); - item = readItem(dis); + // 4J Stu - TU-1 hotfix + // Fix for #13142 - Holding down the A button on the furnace ingredient slot + // causes the UI to display incorrect item counts + uint8_t byteId = dis->readByte(); + containerId = *(char*)&byteId; + slot = dis->readShort(); + item = readItem(dis); } -void ContainerSetSlotPacket::write(DataOutputStream *dos) //throws IOException +void ContainerSetSlotPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte((uint8_t)containerId); - dos->writeShort(slot); - writeItem(item, dos); + dos->writeByte((uint8_t)containerId); + dos->writeShort(slot); + writeItem(item, dos); } -int ContainerSetSlotPacket::getEstimatedSize() -{ - return 3 + 5; -} +int ContainerSetSlotPacket::getEstimatedSize() { return 3 + 5; } diff --git a/Minecraft.World/Network/Packets/ContainerSetSlotPacket.h b/Minecraft.World/Network/Packets/ContainerSetSlotPacket.h index bfa4d2e05..b7073fdb6 100644 --- a/Minecraft.World/Network/Packets/ContainerSetSlotPacket.h +++ b/Minecraft.World/Network/Packets/ContainerSetSlotPacket.h @@ -1,12 +1,12 @@ #pragma once - #include "Packet.h" -class ContainerSetSlotPacket : public Packet, public std::enable_shared_from_this -{ +class ContainerSetSlotPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int CONTAINER; + static const int CONTAINER; static const int WORKBENCH; static const int FURNACE; @@ -14,17 +14,18 @@ public: int slot; std::shared_ptr item; - ContainerSetSlotPacket(); - ContainerSetSlotPacket(int containerId, int slot, std::shared_ptr item); + ContainerSetSlotPacket(); + ContainerSetSlotPacket(int containerId, int slot, + std::shared_ptr item); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ContainerSetSlotPacket()); } - virtual int getId() { return 103; } + static std::shared_ptr create() { + return std::shared_ptr(new ContainerSetSlotPacket()); + } + virtual int getId() { return 103; } }; - - diff --git a/Minecraft.World/Network/Packets/CraftItemPacket.cpp b/Minecraft.World/Network/Packets/CraftItemPacket.cpp index a545bfcd2..59f981a03 100644 --- a/Minecraft.World/Network/Packets/CraftItemPacket.cpp +++ b/Minecraft.World/Network/Packets/CraftItemPacket.cpp @@ -5,42 +5,32 @@ #include "PacketListener.h" #include "CraftItemPacket.h" +CraftItemPacket::~CraftItemPacket() {} - -CraftItemPacket::~CraftItemPacket() -{ +CraftItemPacket::CraftItemPacket() { + recipe = -1; + uid = 0; } -CraftItemPacket::CraftItemPacket() -{ - recipe = -1; - uid = 0; +CraftItemPacket::CraftItemPacket(int recipe, short uid) { + this->recipe = recipe; + this->uid = uid; } -CraftItemPacket::CraftItemPacket(int recipe, short uid) -{ - this->recipe = recipe; - this->uid = uid; +void CraftItemPacket::handle(PacketListener* listener) { + listener->handleCraftItem(shared_from_this()); } -void CraftItemPacket::handle(PacketListener *listener) +void CraftItemPacket::read(DataInputStream* dis) // throws IOException { - listener->handleCraftItem(shared_from_this()); + uid = dis->readShort(); + recipe = dis->readInt(); } -void CraftItemPacket::read(DataInputStream *dis) //throws IOException +void CraftItemPacket::write(DataOutputStream* dos) // throws IOException { - uid = dis->readShort(); - recipe = dis->readInt(); + dos->writeShort(uid); + dos->writeInt(recipe); } -void CraftItemPacket::write(DataOutputStream *dos) // throws IOException -{ - dos->writeShort(uid); - dos->writeInt(recipe); -} - -int CraftItemPacket::getEstimatedSize() -{ - return 2 + 4; -} +int CraftItemPacket::getEstimatedSize() { return 2 + 4; } diff --git a/Minecraft.World/Network/Packets/CraftItemPacket.h b/Minecraft.World/Network/Packets/CraftItemPacket.h index ca6fb0772..024a63fcb 100644 --- a/Minecraft.World/Network/Packets/CraftItemPacket.h +++ b/Minecraft.World/Network/Packets/CraftItemPacket.h @@ -2,26 +2,26 @@ // 4J ADDED THIS PACKET - - #include "Packet.h" -class CraftItemPacket : public Packet, public std::enable_shared_from_this -{ +class CraftItemPacket : public Packet, + public std::enable_shared_from_this { public: - int recipe; - short uid; + int recipe; + short uid; - CraftItemPacket(); - ~CraftItemPacket(); - CraftItemPacket(int recipe, short uid); + CraftItemPacket(); + ~CraftItemPacket(); + CraftItemPacket(int recipe, short uid); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new CraftItemPacket()); } - virtual int getId() { return 150; } + static std::shared_ptr create() { + return std::shared_ptr(new CraftItemPacket()); + } + virtual int getId() { return 150; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/CustomPayloadPacket.cpp b/Minecraft.World/Network/Packets/CustomPayloadPacket.cpp index ea71e3068..21e2baa65 100644 --- a/Minecraft.World/Network/Packets/CustomPayloadPacket.cpp +++ b/Minecraft.World/Network/Packets/CustomPayloadPacket.cpp @@ -10,66 +10,57 @@ const std::wstring CustomPayloadPacket::CUSTOM_BOOK_SIGN_PACKET = L"MC|BSign"; const std::wstring CustomPayloadPacket::TEXTURE_PACK_PACKET = L"MC|TPack"; const std::wstring CustomPayloadPacket::TRADER_LIST_PACKET = L"MC|TrList"; const std::wstring CustomPayloadPacket::TRADER_SELECTION_PACKET = L"MC|TrSel"; -const std::wstring CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET = L"MC|AdvCdm"; +const std::wstring CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET = + L"MC|AdvCdm"; const std::wstring CustomPayloadPacket::SET_BEACON_PACKET = L"MC|Beacon"; const std::wstring CustomPayloadPacket::SET_ITEM_NAME_PACKET = L"MC|ItemName"; -CustomPayloadPacket::CustomPayloadPacket() -{ -} +CustomPayloadPacket::CustomPayloadPacket() {} -CustomPayloadPacket::CustomPayloadPacket(const std::wstring &identifier, byteArray data) -{ - this->identifier = identifier; - this->data = data; +CustomPayloadPacket::CustomPayloadPacket(const std::wstring& identifier, + byteArray data) { + this->identifier = identifier; + this->data = data; - if (data.data != NULL) - { - length = data.length; + if (data.data != NULL) { + length = data.length; - if (length > Short::MAX_VALUE) - { - app.DebugPrintf("Payload may not be larger than 32K\n"); + if (length > Short::MAX_VALUE) { + app.DebugPrintf("Payload may not be larger than 32K\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //throw new IllegalArgumentException("Payload may not be larger than 32k"); - } - } + // throw new IllegalArgumentException("Payload may not be larger + // than 32k"); + } + } } -void CustomPayloadPacket::read(DataInputStream *dis) -{ - identifier = readUtf(dis, 20); - length = dis->readShort(); +void CustomPayloadPacket::read(DataInputStream* dis) { + identifier = readUtf(dis, 20); + length = dis->readShort(); - if (length > 0 && length < Short::MAX_VALUE) - { - if(data.data != NULL) - { - delete [] data.data; - } - data = byteArray(length); - dis->readFully(data); - } + if (length > 0 && length < Short::MAX_VALUE) { + if (data.data != NULL) { + delete[] data.data; + } + data = byteArray(length); + dis->readFully(data); + } } -void CustomPayloadPacket::write(DataOutputStream *dos) -{ - writeUtf(identifier, dos); - dos->writeShort((short) length); - if (data.data != NULL) - { - dos->write(data); - } +void CustomPayloadPacket::write(DataOutputStream* dos) { + writeUtf(identifier, dos); + dos->writeShort((short)length); + if (data.data != NULL) { + dos->write(data); + } } -void CustomPayloadPacket::handle(PacketListener *listener) -{ - listener->handleCustomPayload( shared_from_this() ); +void CustomPayloadPacket::handle(PacketListener* listener) { + listener->handleCustomPayload(shared_from_this()); } -int CustomPayloadPacket::getEstimatedSize() -{ - return 2 + identifier.length() * 2 + 2 + length; +int CustomPayloadPacket::getEstimatedSize() { + return 2 + identifier.length() * 2 + 2 + length; } diff --git a/Minecraft.World/Network/Packets/CustomPayloadPacket.h b/Minecraft.World/Network/Packets/CustomPayloadPacket.h index c545c7bff..cf4fa2946 100644 --- a/Minecraft.World/Network/Packets/CustomPayloadPacket.h +++ b/Minecraft.World/Network/Packets/CustomPayloadPacket.h @@ -1,35 +1,36 @@ #pragma once - #include "Packet.h" -class CustomPayloadPacket : public Packet, public std::enable_shared_from_this -{ +class CustomPayloadPacket + : public Packet, + public std::enable_shared_from_this { public: + // Mojang-defined custom packets + static const std::wstring CUSTOM_BOOK_PACKET; + static const std::wstring CUSTOM_BOOK_SIGN_PACKET; + static const std::wstring TEXTURE_PACK_PACKET; + static const std::wstring TRADER_LIST_PACKET; + static const std::wstring TRADER_SELECTION_PACKET; + static const std::wstring SET_ADVENTURE_COMMAND_PACKET; + static const std::wstring SET_BEACON_PACKET; + static const std::wstring SET_ITEM_NAME_PACKET; - // Mojang-defined custom packets - static const std::wstring CUSTOM_BOOK_PACKET; - static const std::wstring CUSTOM_BOOK_SIGN_PACKET; - static const std::wstring TEXTURE_PACK_PACKET; - static const std::wstring TRADER_LIST_PACKET; - static const std::wstring TRADER_SELECTION_PACKET; - static const std::wstring SET_ADVENTURE_COMMAND_PACKET; - static const std::wstring SET_BEACON_PACKET; - static const std::wstring SET_ITEM_NAME_PACKET; + std::wstring identifier; + int length; + byteArray data; - std::wstring identifier; - int length; - byteArray data; + CustomPayloadPacket(); + CustomPayloadPacket(const std::wstring& identifier, byteArray data); - CustomPayloadPacket(); - CustomPayloadPacket(const std::wstring &identifier, byteArray data); - - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new CustomPayloadPacket()); } - virtual int getId() { return 250; } + static std::shared_ptr create() { + return std::shared_ptr(new CustomPayloadPacket()); + } + virtual int getId() { return 250; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/DebugOptionsPacket.cpp b/Minecraft.World/Network/Packets/DebugOptionsPacket.cpp index f581418c0..3dcbbe295 100644 --- a/Minecraft.World/Network/Packets/DebugOptionsPacket.cpp +++ b/Minecraft.World/Network/Packets/DebugOptionsPacket.cpp @@ -5,38 +5,26 @@ #include "PacketListener.h" #include "DebugOptionsPacket.h" +DebugOptionsPacket::~DebugOptionsPacket() {} +DebugOptionsPacket::DebugOptionsPacket() { m_uiVal = 0L; } -DebugOptionsPacket::~DebugOptionsPacket() -{ +DebugOptionsPacket::DebugOptionsPacket(unsigned int uiVal) { + this->m_uiVal = uiVal; } -DebugOptionsPacket::DebugOptionsPacket() -{ - m_uiVal = 0L; +void DebugOptionsPacket::handle(PacketListener* listener) { + listener->handleDebugOptions(shared_from_this()); } -DebugOptionsPacket::DebugOptionsPacket(unsigned int uiVal) +void DebugOptionsPacket::read(DataInputStream* dis) // throws IOException { - this->m_uiVal = uiVal; + m_uiVal = (unsigned int)dis->readInt(); } -void DebugOptionsPacket::handle(PacketListener *listener) +void DebugOptionsPacket::write(DataOutputStream* dos) // throws IOException { - listener->handleDebugOptions(shared_from_this()); + dos->writeInt((int)m_uiVal); } -void DebugOptionsPacket::read(DataInputStream *dis) //throws IOException -{ - m_uiVal = (unsigned int)dis->readInt(); -} - -void DebugOptionsPacket::write(DataOutputStream *dos) // throws IOException -{ - dos->writeInt((int)m_uiVal); -} - -int DebugOptionsPacket::getEstimatedSize() -{ - return sizeof(int); -} +int DebugOptionsPacket::getEstimatedSize() { return sizeof(int); } diff --git a/Minecraft.World/Network/Packets/DebugOptionsPacket.h b/Minecraft.World/Network/Packets/DebugOptionsPacket.h index 6eda123d5..75484b30f 100644 --- a/Minecraft.World/Network/Packets/DebugOptionsPacket.h +++ b/Minecraft.World/Network/Packets/DebugOptionsPacket.h @@ -2,25 +2,26 @@ // 4J ADDED THIS PACKET - - #include "Packet.h" -class DebugOptionsPacket : public Packet, public std::enable_shared_from_this -{ +class DebugOptionsPacket + : public Packet, + public std::enable_shared_from_this { public: - unsigned int m_uiVal; + unsigned int m_uiVal; - DebugOptionsPacket(); - ~DebugOptionsPacket(); - DebugOptionsPacket(unsigned int uiVal); + DebugOptionsPacket(); + ~DebugOptionsPacket(); + DebugOptionsPacket(unsigned int uiVal); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new DebugOptionsPacket()); } - virtual int getId() { return 152; } + static std::shared_ptr create() { + return std::shared_ptr(new DebugOptionsPacket()); + } + virtual int getId() { return 152; } }; diff --git a/Minecraft.World/Network/Packets/DisconnectPacket.cpp b/Minecraft.World/Network/Packets/DisconnectPacket.cpp index 766162d47..2da1665d6 100644 --- a/Minecraft.World/Network/Packets/DisconnectPacket.cpp +++ b/Minecraft.World/Network/Packets/DisconnectPacket.cpp @@ -5,46 +5,32 @@ #include "PacketListener.h" #include "DisconnectPacket.h" +DisconnectPacket::DisconnectPacket() { reason = eDisconnect_None; } - -DisconnectPacket::DisconnectPacket() -{ - reason = eDisconnect_None; +DisconnectPacket::DisconnectPacket(eDisconnectReason reason) { + this->reason = reason; } -DisconnectPacket::DisconnectPacket(eDisconnectReason reason) +void DisconnectPacket::read(DataInputStream* dis) // throws IOException { - this->reason = reason; + reason = (eDisconnectReason)dis->readInt(); + fprintf(stderr, "[PKT] DisconnectPacket::read reason=%d\n", reason); } -void DisconnectPacket::read(DataInputStream *dis) //throws IOException +void DisconnectPacket::write(DataOutputStream* dos) // throws IOException { - reason = (eDisconnectReason)dis->readInt(); - fprintf(stderr, "[PKT] DisconnectPacket::read reason=%d\n", reason); + fprintf(stderr, "[PKT] DisconnectPacket::write reason=%d\n", reason); + dos->writeInt((int)reason); } -void DisconnectPacket::write(DataOutputStream *dos) //throws IOException -{ - fprintf(stderr, "[PKT] DisconnectPacket::write reason=%d\n", reason); - dos->writeInt((int)reason); +void DisconnectPacket::handle(PacketListener* listener) { + listener->handleDisconnect(shared_from_this()); } -void DisconnectPacket::handle(PacketListener *listener) -{ - listener->handleDisconnect(shared_from_this()); -} +int DisconnectPacket::getEstimatedSize() { return sizeof(eDisconnectReason); } -int DisconnectPacket::getEstimatedSize() -{ - return sizeof(eDisconnectReason); -} +bool DisconnectPacket::canBeInvalidated() { return true; } -bool DisconnectPacket::canBeInvalidated() -{ - return true; -} - -bool DisconnectPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; +bool DisconnectPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/DisconnectPacket.h b/Minecraft.World/Network/Packets/DisconnectPacket.h index 98f216684..dde68d95c 100644 --- a/Minecraft.World/Network/Packets/DisconnectPacket.h +++ b/Minecraft.World/Network/Packets/DisconnectPacket.h @@ -1,73 +1,71 @@ #pragma once - #include "Packet.h" -class DisconnectPacket : public Packet, public std::enable_shared_from_this -{ +class DisconnectPacket : public Packet, + public std::enable_shared_from_this { public: + enum eDisconnectReason { + eDisconnect_None = 0, + eDisconnect_Quitting, + eDisconnect_Closed, - enum eDisconnectReason - { - eDisconnect_None = 0, - eDisconnect_Quitting, - eDisconnect_Closed, + eDisconnect_LoginTooLong, + eDisconnect_IllegalStance, + eDisconnect_IllegalPosition, + eDisconnect_MovedTooQuickly, + eDisconnect_NoFlying, + eDisconnect_Kicked, - eDisconnect_LoginTooLong, - eDisconnect_IllegalStance, - eDisconnect_IllegalPosition, - eDisconnect_MovedTooQuickly, - eDisconnect_NoFlying, - eDisconnect_Kicked, + eDisconnect_TimeOut, + eDisconnect_Overflow, + eDisconnect_EndOfStream, + eDisconnect_ServerFull, + eDisconnect_OutdatedServer, + eDisconnect_OutdatedClient, + eDisconnect_UnexpectedPacket, - eDisconnect_TimeOut, - eDisconnect_Overflow, - eDisconnect_EndOfStream, - eDisconnect_ServerFull, - eDisconnect_OutdatedServer, - eDisconnect_OutdatedClient, - eDisconnect_UnexpectedPacket, + eDisconnect_ConnectionCreationFailed, + eDisconnect_NoMultiplayerPrivilegesHost, + eDisconnect_NoMultiplayerPrivilegesJoin, - eDisconnect_ConnectionCreationFailed, - eDisconnect_NoMultiplayerPrivilegesHost, - eDisconnect_NoMultiplayerPrivilegesJoin, - - eDisconnect_NoUGC_AllLocal, - eDisconnect_NoUGC_Single_Local, - eDisconnect_ContentRestricted_AllLocal, - eDisconnect_ContentRestricted_Single_Local, + eDisconnect_NoUGC_AllLocal, + eDisconnect_NoUGC_Single_Local, + eDisconnect_ContentRestricted_AllLocal, + eDisconnect_ContentRestricted_Single_Local, #ifndef __PS3__ - eDisconnect_NoUGC_Remote, + eDisconnect_NoUGC_Remote, #endif - eDisconnect_NoFriendsInGame, - eDisconnect_Banned, - eDisconnect_NotFriendsWithHost, - eDisconnect_NATMismatch, + eDisconnect_NoFriendsInGame, + eDisconnect_Banned, + eDisconnect_NotFriendsWithHost, + eDisconnect_NATMismatch, #ifdef __ORBIS__ - eDisconnect_NetworkError, + eDisconnect_NetworkError, #endif #ifdef _XBOX_ONE - eDisconnect_ExitedGame, + eDisconnect_ExitedGame, #endif - }; + }; - // 4J Stu - The reason was a string, but we need to send a non-locale specific reason - eDisconnectReason reason; + // 4J Stu - The reason was a string, but we need to send a non-locale + // specific reason + eDisconnectReason reason; - DisconnectPacket(); - DisconnectPacket(eDisconnectReason reason); + DisconnectPacket(); + DisconnectPacket(eDisconnectReason reason); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new DisconnectPacket()); } - virtual int getId() { return 255; } + static std::shared_ptr create() { + return std::shared_ptr(new DisconnectPacket()); + } + virtual int getId() { return 255; } }; - - diff --git a/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.cpp b/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.cpp index bb558ef8d..4a0255fee 100644 --- a/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.cpp +++ b/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.cpp @@ -5,52 +5,47 @@ #include "PacketListener.h" #include "EntityActionAtPositionPacket.h" - - const int EntityActionAtPositionPacket::START_SLEEP = 0; -EntityActionAtPositionPacket::EntityActionAtPositionPacket() -{ - id = -1; - x = 0; - y = 0; - z = 0; - action = 0; +EntityActionAtPositionPacket::EntityActionAtPositionPacket() { + id = -1; + x = 0; + y = 0; + z = 0; + action = 0; } -EntityActionAtPositionPacket::EntityActionAtPositionPacket(std::shared_ptr e, int action, int x, int y, int z) -{ - this->action = action; - this->x = x; - this->y = y; - this->z = z; - this->id = e->entityId; +EntityActionAtPositionPacket::EntityActionAtPositionPacket( + std::shared_ptr e, int action, int x, int y, int z) { + this->action = action; + this->x = x; + this->y = y; + this->z = z; + this->id = e->entityId; } -void EntityActionAtPositionPacket::read(DataInputStream *dis) //throws IOException +void EntityActionAtPositionPacket::read( + DataInputStream* dis) // throws IOException { - id = dis->readInt(); - action = (int)dis->readByte(); - x = dis->readInt(); - y = (int)dis->readByte(); - z = dis->readInt(); + id = dis->readInt(); + action = (int)dis->readByte(); + x = dis->readInt(); + y = (int)dis->readByte(); + z = dis->readInt(); } -void EntityActionAtPositionPacket::write(DataOutputStream *dos) //throws IOException +void EntityActionAtPositionPacket::write( + DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeByte((uint8_t)action); - dos->writeInt(x); - dos->writeByte((uint8_t)y); - dos->writeInt(z); + dos->writeInt(id); + dos->writeByte((uint8_t)action); + dos->writeInt(x); + dos->writeByte((uint8_t)y); + dos->writeInt(z); } -void EntityActionAtPositionPacket::handle(PacketListener *listener) -{ - listener->handleEntityActionAtPosition(shared_from_this()); +void EntityActionAtPositionPacket::handle(PacketListener* listener) { + listener->handleEntityActionAtPosition(shared_from_this()); } -int EntityActionAtPositionPacket::getEstimatedSize() -{ - return 14; -} +int EntityActionAtPositionPacket::getEstimatedSize() { return 14; } diff --git a/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.h b/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.h index d5edc183a..5fecd3494 100644 --- a/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.h +++ b/Minecraft.World/Network/Packets/EntityActionAtPositionPacket.h @@ -1,23 +1,26 @@ #pragma once - #include "Packet.h" -class EntityActionAtPositionPacket : public Packet, public std::enable_shared_from_this -{ +class EntityActionAtPositionPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int START_SLEEP; - int id, x, y, z, action; + static const int START_SLEEP; + int id, x, y, z, action; - EntityActionAtPositionPacket(); - EntityActionAtPositionPacket(std::shared_ptr e, int action, int x, int y, int z); + EntityActionAtPositionPacket(); + EntityActionAtPositionPacket(std::shared_ptr e, int action, int x, + int y, int z); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new EntityActionAtPositionPacket()); } - virtual int getId() { return 17; } + static std::shared_ptr create() { + return std::shared_ptr(new EntityActionAtPositionPacket()); + } + virtual int getId() { return 17; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/EntityEventPacket.cpp b/Minecraft.World/Network/Packets/EntityEventPacket.cpp index 52d8e2d20..18ac96cef 100644 --- a/Minecraft.World/Network/Packets/EntityEventPacket.cpp +++ b/Minecraft.World/Network/Packets/EntityEventPacket.cpp @@ -4,38 +4,30 @@ #include "PacketListener.h" #include "EntityEventPacket.h" - - -EntityEventPacket::EntityEventPacket() -{ - entityId = 0; - eventId = (uint8_t)0; +EntityEventPacket::EntityEventPacket() { + entityId = 0; + eventId = (uint8_t)0; } -EntityEventPacket::EntityEventPacket(int entityId, uint8_t eventId) -{ - this->entityId = entityId; - this->eventId = eventId; +EntityEventPacket::EntityEventPacket(int entityId, uint8_t eventId) { + this->entityId = entityId; + this->eventId = eventId; } -void EntityEventPacket::read(DataInputStream *dis) //throws IOException +void EntityEventPacket::read(DataInputStream* dis) // throws IOException { - entityId = dis->readInt(); - eventId = dis->readByte(); + entityId = dis->readInt(); + eventId = dis->readByte(); } -void EntityEventPacket::write(DataOutputStream *dos) //throws IOException +void EntityEventPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(entityId); - dos->writeByte(eventId); + dos->writeInt(entityId); + dos->writeByte(eventId); } -void EntityEventPacket::handle(PacketListener *listener) -{ - listener->handleEntityEvent(shared_from_this()); +void EntityEventPacket::handle(PacketListener* listener) { + listener->handleEntityEvent(shared_from_this()); } -int EntityEventPacket::getEstimatedSize() -{ - return 5; -} +int EntityEventPacket::getEstimatedSize() { return 5; } diff --git a/Minecraft.World/Network/Packets/EntityEventPacket.h b/Minecraft.World/Network/Packets/EntityEventPacket.h index a17f3be12..eff6e077f 100644 --- a/Minecraft.World/Network/Packets/EntityEventPacket.h +++ b/Minecraft.World/Network/Packets/EntityEventPacket.h @@ -1,25 +1,25 @@ #pragma once - #include "Packet.h" -class EntityEventPacket : public Packet, public std::enable_shared_from_this -{ +class EntityEventPacket + : public Packet, + public std::enable_shared_from_this { public: - int entityId; + int entityId; uint8_t eventId; - EntityEventPacket(); - EntityEventPacket(int entityId, uint8_t eventId); + EntityEventPacket(); + EntityEventPacket(int entityId, uint8_t eventId); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener) ; - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new EntityEventPacket()); } - virtual int getId() { return 38; } + static std::shared_ptr create() { + return std::shared_ptr(new EntityEventPacket()); + } + virtual int getId() { return 38; } }; - - diff --git a/Minecraft.World/Network/Packets/ExplodePacket.cpp b/Minecraft.World/Network/Packets/ExplodePacket.cpp index 99f770a7a..d636edd13 100644 --- a/Minecraft.World/Network/Packets/ExplodePacket.cpp +++ b/Minecraft.World/Network/Packets/ExplodePacket.cpp @@ -5,132 +5,114 @@ #include "PacketListener.h" #include "ExplodePacket.h" - - -ExplodePacket::ExplodePacket() -{ - x = 0; - y = 0; - z = 0; - r = 0.0f; - m_bKnockbackOnly = false; - knockbackX = 0.0f; - knockbackY = 0.0f; - knockbackZ = 0.0f; +ExplodePacket::ExplodePacket() { + x = 0; + y = 0; + z = 0; + r = 0.0f; + m_bKnockbackOnly = false; + knockbackX = 0.0f; + knockbackY = 0.0f; + knockbackZ = 0.0f; } -ExplodePacket::ExplodePacket(double x, double y, double z, float r, std::unordered_set *toBlow, Vec3 *knockback, bool knockBackOnly) -{ - this->x = x; - this->y = y; - this->z = z; - this->r = r; - m_bKnockbackOnly = knockBackOnly; +ExplodePacket::ExplodePacket( + double x, double y, double z, float r, + std::unordered_set* toBlow, + Vec3* knockback, bool knockBackOnly) { + this->x = x; + this->y = y; + this->z = z; + this->r = r; + m_bKnockbackOnly = knockBackOnly; - if(toBlow != NULL) - { - this->toBlow.assign(toBlow->begin(),toBlow->end()); - //for( AUTO_VAR(it, toBlow->begin()); it != toBlow->end(); it++ ) - //{ - // this->toBlow.push_back(*it); - //} - } + if (toBlow != NULL) { + this->toBlow.assign(toBlow->begin(), toBlow->end()); + // for( AUTO_VAR(it, toBlow->begin()); it != toBlow->end(); it++ ) + //{ + // this->toBlow.push_back(*it); + // } + } - if (knockback != NULL) - { - knockbackX = (float) knockback->x; - knockbackY = (float) knockback->y; - knockbackZ = (float) knockback->z; - } + if (knockback != NULL) { + knockbackX = (float)knockback->x; + knockbackY = (float)knockback->y; + knockbackZ = (float)knockback->z; + } } -void ExplodePacket::read(DataInputStream *dis) //throws IOException +void ExplodePacket::read(DataInputStream* dis) // throws IOException { - m_bKnockbackOnly = dis->readBoolean(); + m_bKnockbackOnly = dis->readBoolean(); - if(!m_bKnockbackOnly) - { - x = dis->readDouble(); - y = dis->readDouble(); - z = dis->readDouble(); - r = dis->readFloat(); - int count = dis->readInt(); + if (!m_bKnockbackOnly) { + x = dis->readDouble(); + y = dis->readDouble(); + z = dis->readDouble(); + r = dis->readFloat(); + int count = dis->readInt(); - int xp = (int)x; - int yp = (int)y; - int zp = (int)z; - for (int i=0; ireadByte())+xp; - int yy = ((signed char)dis->readByte())+yp; - int zz = ((signed char)dis->readByte())+zp; - toBlow.push_back( TilePos(xx, yy, zz) ); - } - } + int xp = (int)x; + int yp = (int)y; + int zp = (int)z; + for (int i = 0; i < count; i++) { + int xx = ((signed char)dis->readByte()) + xp; + int yy = ((signed char)dis->readByte()) + yp; + int zz = ((signed char)dis->readByte()) + zp; + toBlow.push_back(TilePos(xx, yy, zz)); + } + } - knockbackX = dis->readFloat(); - knockbackY = dis->readFloat(); - knockbackZ = dis->readFloat(); + knockbackX = dis->readFloat(); + knockbackY = dis->readFloat(); + knockbackZ = dis->readFloat(); } -void ExplodePacket::write(DataOutputStream *dos) //throws IOException +void ExplodePacket::write(DataOutputStream* dos) // throws IOException { - dos->writeBoolean(m_bKnockbackOnly); + dos->writeBoolean(m_bKnockbackOnly); - if(!m_bKnockbackOnly) - { - dos->writeDouble(x); - dos->writeDouble(y); - dos->writeDouble(z); - dos->writeFloat(r); - dos->writeInt((int)toBlow.size()); + if (!m_bKnockbackOnly) { + dos->writeDouble(x); + dos->writeDouble(y); + dos->writeDouble(z); + dos->writeFloat(r); + dos->writeInt((int)toBlow.size()); - int xp = (int)x; - int yp = (int)y; - int zp = (int)z; + int xp = (int)x; + int yp = (int)y; + int zp = (int)z; - //(Myset::const_iterator it = c1.begin(); - //it != c1.end(); ++it) - - for( AUTO_VAR(it, toBlow.begin()); it != toBlow.end(); it++ ) - { - TilePos tp = *it; + //(Myset::const_iterator it = c1.begin(); + // it != c1.end(); ++it) - int xx = tp.x-xp; - int yy = tp.y-yp; - int zz = tp.z-zp; - dos->writeByte((uint8_t)xx); - dos->writeByte((uint8_t)yy); - dos->writeByte((uint8_t)zz); - } - } + for (AUTO_VAR(it, toBlow.begin()); it != toBlow.end(); it++) { + TilePos tp = *it; - dos->writeFloat(knockbackX); - dos->writeFloat(knockbackY); - dos->writeFloat(knockbackZ); + int xx = tp.x - xp; + int yy = tp.y - yp; + int zz = tp.z - zp; + dos->writeByte((uint8_t)xx); + dos->writeByte((uint8_t)yy); + dos->writeByte((uint8_t)zz); + } + } + + dos->writeFloat(knockbackX); + dos->writeFloat(knockbackY); + dos->writeFloat(knockbackZ); } -void ExplodePacket::handle(PacketListener *listener) -{ - listener->handleExplosion(shared_from_this()); +void ExplodePacket::handle(PacketListener* listener) { + listener->handleExplosion(shared_from_this()); } -int ExplodePacket::getEstimatedSize() -{ - return 8*3+4+4+(int)toBlow.size()*3+12; +int ExplodePacket::getEstimatedSize() { + return 8 * 3 + 4 + 4 + (int)toBlow.size() * 3 + 12; } -float ExplodePacket::getKnockbackX() -{ - return knockbackX; -} +float ExplodePacket::getKnockbackX() { return knockbackX; } -float ExplodePacket::getKnockbackY() -{ - return knockbackY; -} +float ExplodePacket::getKnockbackY() { return knockbackY; } -float ExplodePacket::getKnockbackZ() -{ - return knockbackZ; -} +float ExplodePacket::getKnockbackZ() { return knockbackZ; } diff --git a/Minecraft.World/Network/Packets/ExplodePacket.h b/Minecraft.World/Network/Packets/ExplodePacket.h index 2f2dfa168..c6b0a5bd4 100644 --- a/Minecraft.World/Network/Packets/ExplodePacket.h +++ b/Minecraft.World/Network/Packets/ExplodePacket.h @@ -1,37 +1,42 @@ #pragma once - #include "../../Level/TilePos.h" #include "Packet.h" -class ExplodePacket : public Packet, public std::enable_shared_from_this -{ +class ExplodePacket : public Packet, + public std::enable_shared_from_this { public: - double x, y, z; + double x, y, z; float r; - std::vector toBlow; // 4J - was an unorderedset but doesn't require any features of that apart from making it match the ctor toBlow type - bool m_bKnockbackOnly; - - private: - float knockbackX; - float knockbackY; - float knockbackZ; + std::vector + toBlow; // 4J - was an unorderedset but doesn't require any features of + // that apart from making it match the ctor toBlow type + bool m_bKnockbackOnly; - public: - - ExplodePacket(); - ExplodePacket(double x, double y, double z, float r, std::unordered_set *toBlow, Vec3 *knockback, bool knockBackOnly); - - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - - float getKnockbackX(); - float getKnockbackY(); - float getKnockbackZ(); +private: + float knockbackX; + float knockbackY; + float knockbackZ; public: - static std::shared_ptr create() { return std::shared_ptr(new ExplodePacket()); } - virtual int getId() { return 60; } + ExplodePacket(); + ExplodePacket( + double x, double y, double z, float r, + std::unordered_set* toBlow, + Vec3* knockback, bool knockBackOnly); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + + float getKnockbackX(); + float getKnockbackY(); + float getKnockbackZ(); + +public: + static std::shared_ptr create() { + return std::shared_ptr(new ExplodePacket()); + } + virtual int getId() { return 60; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/GameCommandPacket.cpp b/Minecraft.World/Network/Packets/GameCommandPacket.cpp index c256d5dff..be93ef5c8 100644 --- a/Minecraft.World/Network/Packets/GameCommandPacket.cpp +++ b/Minecraft.World/Network/Packets/GameCommandPacket.cpp @@ -4,69 +4,52 @@ #include "../../Util/BasicTypeContainers.h" #include "GameCommandPacket.h" -GameCommandPacket::GameCommandPacket() -{ - length = 0; -} +GameCommandPacket::GameCommandPacket() { length = 0; } -GameCommandPacket::GameCommandPacket(EGameCommand command, byteArray data) -{ - this->command = command; - this->data = data; - length = 0; +GameCommandPacket::GameCommandPacket(EGameCommand command, byteArray data) { + this->command = command; + this->data = data; + length = 0; - if (data.data != NULL) - { - length = data.length; + if (data.data != NULL) { + length = data.length; - if (length > Short::MAX_VALUE) - { - app.DebugPrintf("Payload may not be larger than 32K\n"); + if (length > Short::MAX_VALUE) { + app.DebugPrintf("Payload may not be larger than 32K\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //throw new IllegalArgumentException("Payload may not be larger than 32k"); - } - } + // throw new IllegalArgumentException("Payload may not be larger + // than 32k"); + } + } } -GameCommandPacket::~GameCommandPacket() -{ - delete [] data.data; +GameCommandPacket::~GameCommandPacket() { delete[] data.data; } + +void GameCommandPacket::read(DataInputStream* dis) { + command = (EGameCommand)dis->readInt(); + length = dis->readShort(); + + if (length > 0 && length < Short::MAX_VALUE) { + if (data.data != NULL) { + delete[] data.data; + } + data = byteArray(length); + dis->readFully(data); + } } -void GameCommandPacket::read(DataInputStream *dis) -{ - command = (EGameCommand)dis->readInt(); - length = dis->readShort(); - - if (length > 0 && length < Short::MAX_VALUE) - { - if(data.data != NULL) - { - delete [] data.data; - } - data = byteArray(length); - dis->readFully(data); - } +void GameCommandPacket::write(DataOutputStream* dos) { + dos->writeInt(command); + dos->writeShort((short)length); + if (data.data != NULL) { + dos->write(data); + } } -void GameCommandPacket::write(DataOutputStream *dos) -{ - dos->writeInt(command); - dos->writeShort((short) length); - if (data.data != NULL) - { - dos->write(data); - } +void GameCommandPacket::handle(PacketListener* listener) { + listener->handleGameCommand(shared_from_this()); } -void GameCommandPacket::handle(PacketListener *listener) -{ - listener->handleGameCommand( shared_from_this() ); -} - -int GameCommandPacket::getEstimatedSize() -{ - return 2 + 2 + length; -} +int GameCommandPacket::getEstimatedSize() { return 2 + 2 + length; } diff --git a/Minecraft.World/Network/Packets/GameCommandPacket.h b/Minecraft.World/Network/Packets/GameCommandPacket.h index f476fb074..cb8e9d5dd 100644 --- a/Minecraft.World/Network/Packets/GameCommandPacket.h +++ b/Minecraft.World/Network/Packets/GameCommandPacket.h @@ -1,26 +1,28 @@ #pragma once - #include "../../Commands/CommandsEnum.h" #include "Packet.h" -class GameCommandPacket : public Packet, public std::enable_shared_from_this -{ +class GameCommandPacket + : public Packet, + public std::enable_shared_from_this { public: - EGameCommand command; - int length; - byteArray data; + EGameCommand command; + int length; + byteArray data; - GameCommandPacket(); - GameCommandPacket(EGameCommand command, byteArray data); - ~GameCommandPacket(); + GameCommandPacket(); + GameCommandPacket(EGameCommand command, byteArray data); + ~GameCommandPacket(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new GameCommandPacket()); } - virtual int getId() { return 167; } + static std::shared_ptr create() { + return std::shared_ptr(new GameCommandPacket()); + } + virtual int getId() { return 167; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/GameEventPacket.cpp b/Minecraft.World/Network/Packets/GameEventPacket.cpp index 5baee0c3a..0b5504141 100644 --- a/Minecraft.World/Network/Packets/GameEventPacket.cpp +++ b/Minecraft.World/Network/Packets/GameEventPacket.cpp @@ -4,12 +4,11 @@ #include "PacketListener.h" #include "GameEventPacket.h" - const int GameEventPacket::NO_RESPAWN_BED_AVAILABLE = 0; const int GameEventPacket::START_RAINING = 1; const int GameEventPacket::STOP_RAINING = 2; -const int GameEventPacket::CHANGE_GAME_MODE = 3; // 1.8.2 -const int GameEventPacket::WIN_GAME = 4; // 1.0.1 +const int GameEventPacket::CHANGE_GAME_MODE = 3; // 1.8.2 +const int GameEventPacket::WIN_GAME = 4; // 1.0.1 const int GameEventPacket::DEMO_EVENT = 5; const int GameEventPacket::DEMO_PARAM_INTRO = 0; @@ -21,38 +20,33 @@ const int GameEventPacket::DEMO_PARAM_HINT_3 = 103; const int GameEventPacket::START_SAVING = 10; const int GameEventPacket::STOP_SAVING = 11; -const int GameEventPacket::EVENT_LANGUAGE_ID[EVENT_LANGUAGE_ID_LENGTH] = { IDS_TILE_BED_NOT_VALID, -1, -1, IDS_GAME_MODE_CHANGED, -1, -1 }; +const int GameEventPacket::EVENT_LANGUAGE_ID[EVENT_LANGUAGE_ID_LENGTH] = { + IDS_TILE_BED_NOT_VALID, -1, -1, IDS_GAME_MODE_CHANGED, -1, -1}; -GameEventPacket::GameEventPacket() -{ - this->_event = 0; - this->param = 0; +GameEventPacket::GameEventPacket() { + this->_event = 0; + this->param = 0; } -GameEventPacket::GameEventPacket(int _event, int param) -{ - this->_event = _event; - this->param = param; +GameEventPacket::GameEventPacket(int _event, int param) { + this->_event = _event; + this->param = param; } -void GameEventPacket::read(DataInputStream *dis) //throws IOException +void GameEventPacket::read(DataInputStream* dis) // throws IOException { - _event = (int)dis->readByte(); - param = (int)dis->readByte(); + _event = (int)dis->readByte(); + param = (int)dis->readByte(); } -void GameEventPacket::write(DataOutputStream *dos) //throws IOException +void GameEventPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte((uint8_t)_event); - dos->writeByte((uint8_t)param); + dos->writeByte((uint8_t)_event); + dos->writeByte((uint8_t)param); } -void GameEventPacket::handle(PacketListener *listener) -{ - listener->handleGameEvent(shared_from_this()); +void GameEventPacket::handle(PacketListener* listener) { + listener->handleGameEvent(shared_from_this()); } -int GameEventPacket::getEstimatedSize() -{ - return 2; -} +int GameEventPacket::getEstimatedSize() { return 2; } diff --git a/Minecraft.World/Network/Packets/GameEventPacket.h b/Minecraft.World/Network/Packets/GameEventPacket.h index 86c59c397..28f208d47 100644 --- a/Minecraft.World/Network/Packets/GameEventPacket.h +++ b/Minecraft.World/Network/Packets/GameEventPacket.h @@ -1,45 +1,44 @@ #pragma once - #include "Packet.h" -class GameEventPacket : public Packet, public std::enable_shared_from_this -{ +class GameEventPacket : public Packet, + public std::enable_shared_from_this { +public: + static const int NO_RESPAWN_BED_AVAILABLE; + static const int START_RAINING; + static const int STOP_RAINING; + static const int CHANGE_GAME_MODE; // 1.8.2 + static const int WIN_GAME; // 1.0.01 + static const int DEMO_EVENT; // 1.3.2 + static const int SUCCESSFUL_BOW_HIT = 6; + + static const int DEMO_PARAM_INTRO; // 1.3.2 + static const int DEMO_PARAM_HINT_1; // 1.3.2 + static const int DEMO_PARAM_HINT_2; // 1.3.2 + static const int DEMO_PARAM_HINT_3; // 1.3.2 + + // 4J Added + static const int START_SAVING; + static const int STOP_SAVING; + + static const int EVENT_LANGUAGE_ID_LENGTH = 6; + static const int EVENT_LANGUAGE_ID[EVENT_LANGUAGE_ID_LENGTH]; + + int _event; + int param; + + GameEventPacket(); + GameEventPacket(int evnt, int param); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static const int NO_RESPAWN_BED_AVAILABLE; - static const int START_RAINING; - static const int STOP_RAINING; - static const int CHANGE_GAME_MODE; // 1.8.2 - static const int WIN_GAME; // 1.0.01 - static const int DEMO_EVENT; // 1.3.2 - static const int SUCCESSFUL_BOW_HIT = 6; - - static const int DEMO_PARAM_INTRO; // 1.3.2 - static const int DEMO_PARAM_HINT_1; // 1.3.2 - static const int DEMO_PARAM_HINT_2; // 1.3.2 - static const int DEMO_PARAM_HINT_3; // 1.3.2 - - // 4J Added - static const int START_SAVING; - static const int STOP_SAVING; - - static const int EVENT_LANGUAGE_ID_LENGTH = 6; - static const int EVENT_LANGUAGE_ID[EVENT_LANGUAGE_ID_LENGTH]; - - - int _event; - int param; - - GameEventPacket(); - GameEventPacket(int evnt, int param); - - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - -public: - static std::shared_ptr create() { return std::shared_ptr(new GameEventPacket()); } - virtual int getId() { return 70; } + static std::shared_ptr create() { + return std::shared_ptr(new GameEventPacket()); + } + virtual int getId() { return 70; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/GetInfoPacket.cpp b/Minecraft.World/Network/Packets/GetInfoPacket.cpp index 74db9fe1e..ddec91bb7 100644 --- a/Minecraft.World/Network/Packets/GetInfoPacket.cpp +++ b/Minecraft.World/Network/Packets/GetInfoPacket.cpp @@ -3,20 +3,12 @@ #include "PacketListener.h" #include "GetInfoPacket.h" -void GetInfoPacket::read(DataInputStream *dis) -{ +void GetInfoPacket::read(DataInputStream* dis) {} + +void GetInfoPacket::write(DataOutputStream* dos) {} + +void GetInfoPacket::handle(PacketListener* listener) { + listener->handleGetInfo(shared_from_this()); } -void GetInfoPacket::write(DataOutputStream *dos) -{ -} - -void GetInfoPacket::handle(PacketListener *listener) -{ - listener->handleGetInfo(shared_from_this()); -} - -int GetInfoPacket::getEstimatedSize() -{ - return 0; -} \ No newline at end of file +int GetInfoPacket::getEstimatedSize() { return 0; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/GetInfoPacket.h b/Minecraft.World/Network/Packets/GetInfoPacket.h index c44fa735b..fada961ea 100644 --- a/Minecraft.World/Network/Packets/GetInfoPacket.h +++ b/Minecraft.World/Network/Packets/GetInfoPacket.h @@ -2,15 +2,17 @@ #include "Packet.h" -class GetInfoPacket : public Packet, public std::enable_shared_from_this -{ +class GetInfoPacket : public Packet, + public std::enable_shared_from_this { public: - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new GetInfoPacket()); } - virtual int getId() { return 254; } + static std::shared_ptr create() { + return std::shared_ptr(new GetInfoPacket()); + } + virtual int getId() { return 254; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/InteractPacket.cpp b/Minecraft.World/Network/Packets/InteractPacket.cpp index 95b907e3a..2078127ed 100644 --- a/Minecraft.World/Network/Packets/InteractPacket.cpp +++ b/Minecraft.World/Network/Packets/InteractPacket.cpp @@ -4,45 +4,37 @@ #include "PacketListener.h" #include "InteractPacket.h" - - const int InteractPacket::INTERACT = 0; const int InteractPacket::ATTACK = 1; -InteractPacket::InteractPacket() -{ - source = 0; - target = 0; - action = 0; +InteractPacket::InteractPacket() { + source = 0; + target = 0; + action = 0; } -InteractPacket::InteractPacket(int source, int target, int action) -{ - this->source = source; - this->target = target; - this->action = action; +InteractPacket::InteractPacket(int source, int target, int action) { + this->source = source; + this->target = target; + this->action = action; } -void InteractPacket::read(DataInputStream *dis) //throws IOException +void InteractPacket::read(DataInputStream* dis) // throws IOException { - source = dis->readInt(); - target = dis->readInt(); - action = (int)dis->readByte(); + source = dis->readInt(); + target = dis->readInt(); + action = (int)dis->readByte(); } -void InteractPacket::write(DataOutputStream *dos) // throws IOException +void InteractPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(source); - dos->writeInt(target); - dos->writeByte((uint8_t)action); + dos->writeInt(source); + dos->writeInt(target); + dos->writeByte((uint8_t)action); } -void InteractPacket::handle(PacketListener *listener) -{ - listener->handleInteract(shared_from_this()); +void InteractPacket::handle(PacketListener* listener) { + listener->handleInteract(shared_from_this()); } -int InteractPacket::getEstimatedSize() -{ - return 9; -} +int InteractPacket::getEstimatedSize() { return 9; } diff --git a/Minecraft.World/Network/Packets/InteractPacket.h b/Minecraft.World/Network/Packets/InteractPacket.h index e2b67a1ff..ec94a4e28 100644 --- a/Minecraft.World/Network/Packets/InteractPacket.h +++ b/Minecraft.World/Network/Packets/InteractPacket.h @@ -1,25 +1,26 @@ #pragma once - #include "Packet.h" -class InteractPacket : public Packet, public std::enable_shared_from_this -{ +class InteractPacket : public Packet, + public std::enable_shared_from_this { public: - static const int INTERACT; + static const int INTERACT; static const int ATTACK; int source, target, action; - InteractPacket(); - InteractPacket(int source, int target, int action); + InteractPacket(); + InteractPacket(int source, int target, int action); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new InteractPacket()); } - virtual int getId() { return 7; } + static std::shared_ptr create() { + return std::shared_ptr(new InteractPacket()); + } + virtual int getId() { return 7; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/KeepAlivePacket.cpp b/Minecraft.World/Network/Packets/KeepAlivePacket.cpp index 397fbb944..e5a4329ab 100644 --- a/Minecraft.World/Network/Packets/KeepAlivePacket.cpp +++ b/Minecraft.World/Network/Packets/KeepAlivePacket.cpp @@ -4,49 +4,30 @@ #include "PacketListener.h" #include "KeepAlivePacket.h" +KeepAlivePacket::KeepAlivePacket() { id = 0; } +KeepAlivePacket::KeepAlivePacket(int id) { this->id = id; } -KeepAlivePacket::KeepAlivePacket() -{ - id = 0; +void KeepAlivePacket::handle(PacketListener* listener) { + listener->handleKeepAlive(shared_from_this()); } -KeepAlivePacket::KeepAlivePacket(int id) +void KeepAlivePacket::read(DataInputStream* dis) // throws IOException { - this->id = id; + id = dis->readInt(); } -void KeepAlivePacket::handle(PacketListener *listener) +void KeepAlivePacket::write(DataOutputStream* dos) // throws IOException { - listener->handleKeepAlive(shared_from_this()); + dos->writeInt(id); } -void KeepAlivePacket::read(DataInputStream *dis) //throws IOException -{ - id = dis->readInt(); +int KeepAlivePacket::getEstimatedSize() { return 4; } + +bool KeepAlivePacket::canBeInvalidated() { return true; } + +bool KeepAlivePacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } -void KeepAlivePacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeInt(id); -} - -int KeepAlivePacket::getEstimatedSize() -{ - return 4; -} - -bool KeepAlivePacket::canBeInvalidated() -{ - return true; -} - -bool KeepAlivePacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; -} - -bool KeepAlivePacket::isAync() -{ - return true; -} \ No newline at end of file +bool KeepAlivePacket::isAync() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/KeepAlivePacket.h b/Minecraft.World/Network/Packets/KeepAlivePacket.h index e7b74dc73..cc470b66a 100644 --- a/Minecraft.World/Network/Packets/KeepAlivePacket.h +++ b/Minecraft.World/Network/Packets/KeepAlivePacket.h @@ -1,25 +1,26 @@ #pragma once - #include "Packet.h" -class KeepAlivePacket : public Packet, public std::enable_shared_from_this -{ +class KeepAlivePacket : public Packet, + public std::enable_shared_from_this { public: - int id; + int id; - KeepAlivePacket(); - KeepAlivePacket(int id); + KeepAlivePacket(); + KeepAlivePacket(int id); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); public: - static std::shared_ptr create() { return std::shared_ptr(new KeepAlivePacket()); } - virtual int getId() { return 0; } + static std::shared_ptr create() { + return std::shared_ptr(new KeepAlivePacket()); + } + virtual int getId() { return 0; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/KickPlayerPacket.cpp b/Minecraft.World/Network/Packets/KickPlayerPacket.cpp index fde36a1b8..c1d52e149 100644 --- a/Minecraft.World/Network/Packets/KickPlayerPacket.cpp +++ b/Minecraft.World/Network/Packets/KickPlayerPacket.cpp @@ -4,34 +4,24 @@ #include "PacketListener.h" #include "KickPlayerPacket.h" +KickPlayerPacket::KickPlayerPacket() { m_networkSmallId = 0; } - -KickPlayerPacket::KickPlayerPacket() -{ - m_networkSmallId = 0; +KickPlayerPacket::KickPlayerPacket(std::uint8_t networkSmallId) { + m_networkSmallId = networkSmallId; } -KickPlayerPacket::KickPlayerPacket(std::uint8_t networkSmallId) -{ - m_networkSmallId = networkSmallId; +void KickPlayerPacket::handle(PacketListener* listener) { + listener->handleKickPlayer(shared_from_this()); } -void KickPlayerPacket::handle(PacketListener *listener) +void KickPlayerPacket::read(DataInputStream* dis) // throws IOException { - listener->handleKickPlayer(shared_from_this()); + m_networkSmallId = dis->readByte(); } -void KickPlayerPacket::read(DataInputStream *dis) //throws IOException +void KickPlayerPacket::write(DataOutputStream* dos) // throws IOException { - m_networkSmallId = dis->readByte(); + dos->writeByte((std::uint8_t)m_networkSmallId); } -void KickPlayerPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeByte((std::uint8_t)m_networkSmallId); -} - -int KickPlayerPacket::getEstimatedSize() -{ - return 1; -} +int KickPlayerPacket::getEstimatedSize() { return 1; } diff --git a/Minecraft.World/Network/Packets/KickPlayerPacket.h b/Minecraft.World/Network/Packets/KickPlayerPacket.h index 30c04b4c6..69a169565 100644 --- a/Minecraft.World/Network/Packets/KickPlayerPacket.h +++ b/Minecraft.World/Network/Packets/KickPlayerPacket.h @@ -4,20 +4,22 @@ #include "Packet.h" -class KickPlayerPacket : public Packet, public std::enable_shared_from_this -{ +class KickPlayerPacket : public Packet, + public std::enable_shared_from_this { public: - std::uint8_t m_networkSmallId; + std::uint8_t m_networkSmallId; - KickPlayerPacket(); - KickPlayerPacket(std::uint8_t networkSmallId); + KickPlayerPacket(); + KickPlayerPacket(std::uint8_t networkSmallId); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new KickPlayerPacket()); } - virtual int getId() { return 159; } + static std::shared_ptr create() { + return std::shared_ptr(new KickPlayerPacket()); + } + virtual int getId() { return 159; } }; diff --git a/Minecraft.World/Network/Packets/LevelEventPacket.cpp b/Minecraft.World/Network/Packets/LevelEventPacket.cpp index e48c94093..6ca46a95f 100644 --- a/Minecraft.World/Network/Packets/LevelEventPacket.cpp +++ b/Minecraft.World/Network/Packets/LevelEventPacket.cpp @@ -4,51 +4,42 @@ #include "PacketListener.h" #include "LevelEventPacket.h" - - -LevelEventPacket::LevelEventPacket() -{ - type = 0; - data = 0; - x = 0; - y = 0; - z = 0; +LevelEventPacket::LevelEventPacket() { + type = 0; + data = 0; + x = 0; + y = 0; + z = 0; } -LevelEventPacket::LevelEventPacket(int type, int x, int y, int z, int data) -{ - this->type = type; - this->x = x; - this->y = y; - this->z = z; - this->data = data; +LevelEventPacket::LevelEventPacket(int type, int x, int y, int z, int data) { + this->type = type; + this->x = x; + this->y = y; + this->z = z; + this->data = data; } -void LevelEventPacket::read(DataInputStream *dis) //throws IOException +void LevelEventPacket::read(DataInputStream* dis) // throws IOException { - type = dis->readInt(); - x = dis->readInt(); - y = (int)(dis->readByte() & (uint8_t)0xff); - z = dis->readInt(); - data = dis->readInt(); + type = dis->readInt(); + x = dis->readInt(); + y = (int)(dis->readByte() & (uint8_t)0xff); + z = dis->readInt(); + data = dis->readInt(); } -void LevelEventPacket::write(DataOutputStream *dos) //throws IOException +void LevelEventPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(type); - dos->writeInt(x); - dos->writeByte((uint8_t)(y & 0xff)); - dos->writeInt(z); - dos->writeInt(data); + dos->writeInt(type); + dos->writeInt(x); + dos->writeByte((uint8_t)(y & 0xff)); + dos->writeInt(z); + dos->writeInt(data); } -void LevelEventPacket::handle(PacketListener *listener) -{ - listener->handleLevelEvent(shared_from_this()); -} - -int LevelEventPacket::getEstimatedSize() -{ - return 4 * 5 + 1; +void LevelEventPacket::handle(PacketListener* listener) { + listener->handleLevelEvent(shared_from_this()); } +int LevelEventPacket::getEstimatedSize() { return 4 * 5 + 1; } diff --git a/Minecraft.World/Network/Packets/LevelEventPacket.h b/Minecraft.World/Network/Packets/LevelEventPacket.h index 3e4363498..ef9ea470c 100644 --- a/Minecraft.World/Network/Packets/LevelEventPacket.h +++ b/Minecraft.World/Network/Packets/LevelEventPacket.h @@ -1,24 +1,25 @@ #pragma once - #include "Packet.h" -class LevelEventPacket : public Packet, public std::enable_shared_from_this -{ +class LevelEventPacket : public Packet, + public std::enable_shared_from_this { public: - int type; + int type; int data; int x, y, z; - LevelEventPacket(); - LevelEventPacket(int type, int x, int y, int z, int data); + LevelEventPacket(); + LevelEventPacket(int type, int x, int y, int z, int data); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new LevelEventPacket()); } - virtual int getId() { return 61; } + static std::shared_ptr create() { + return std::shared_ptr(new LevelEventPacket()); + } + virtual int getId() { return 61; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/LevelSoundPacket.cpp b/Minecraft.World/Network/Packets/LevelSoundPacket.cpp index 3163e65b2..8bbb8fde8 100644 --- a/Minecraft.World/Network/Packets/LevelSoundPacket.cpp +++ b/Minecraft.World/Network/Packets/LevelSoundPacket.cpp @@ -7,90 +7,68 @@ const float LevelSoundPacket::PITCH_ACCURACY = Byte::MAX_VALUE / 2.0f; const float LevelSoundPacket::LOCATION_ACCURACY = 8.0f; -LevelSoundPacket::LevelSoundPacket() -{ - sound = 0; - x = 0; - y = Integer::MAX_VALUE; - z = 0; - volume = 0.0f; - pitch = 0; +LevelSoundPacket::LevelSoundPacket() { + sound = 0; + x = 0; + y = Integer::MAX_VALUE; + z = 0; + volume = 0.0f; + pitch = 0; } -LevelSoundPacket::LevelSoundPacket(int sound, double x, double y, double z, float volume, float pitch) -{ - this->sound = sound; - this->x = (int) (x * LOCATION_ACCURACY); - this->y = (int) (y * LOCATION_ACCURACY); - this->z = (int) (z * LOCATION_ACCURACY); - this->volume = volume; - // 4J-PB - Let's make the pitch a float so it doesn't get mangled and make the noteblock people unhappy - //this->pitch = (int) (pitch * PITCH_ACCURACY); - this->pitch = pitch; +LevelSoundPacket::LevelSoundPacket(int sound, double x, double y, double z, + float volume, float pitch) { + this->sound = sound; + this->x = (int)(x * LOCATION_ACCURACY); + this->y = (int)(y * LOCATION_ACCURACY); + this->z = (int)(z * LOCATION_ACCURACY); + this->volume = volume; + // 4J-PB - Let's make the pitch a float so it doesn't get mangled and make + // the noteblock people unhappy + // this->pitch = (int) (pitch * PITCH_ACCURACY); + this->pitch = pitch; -// if (this->pitch < 0) this->pitch = 0; -// if (this->pitch > 255) this->pitch = 255; + // if (this->pitch < 0) this->pitch = 0; + // if (this->pitch > 255) this->pitch = 255; } -void LevelSoundPacket::read(DataInputStream *dis) -{ - sound = dis->readInt(); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); - volume = dis->readFloat(); - //pitch = dis->readUnsignedByte(); - pitch = dis->readFloat(); +void LevelSoundPacket::read(DataInputStream* dis) { + sound = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); + volume = dis->readFloat(); + // pitch = dis->readUnsignedByte(); + pitch = dis->readFloat(); } -void LevelSoundPacket::write(DataOutputStream *dos) -{ - dos->writeInt(sound); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); - dos->writeFloat(volume); - //dos->writeByte(pitch); - dos->writeFloat(pitch); +void LevelSoundPacket::write(DataOutputStream* dos) { + dos->writeInt(sound); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); + dos->writeFloat(volume); + // dos->writeByte(pitch); + dos->writeFloat(pitch); } -int LevelSoundPacket::getSound() -{ - return sound; +int LevelSoundPacket::getSound() { return sound; } + +double LevelSoundPacket::getX() { return x / LOCATION_ACCURACY; } + +double LevelSoundPacket::getY() { return y / LOCATION_ACCURACY; } + +double LevelSoundPacket::getZ() { return z / LOCATION_ACCURACY; } + +float LevelSoundPacket::getVolume() { return volume; } + +float LevelSoundPacket::getPitch() { + // return pitch / PITCH_ACCURACY; + return pitch; } -double LevelSoundPacket::getX() -{ - return x / LOCATION_ACCURACY; +void LevelSoundPacket::handle(PacketListener* listener) { + listener->handleSoundEvent(shared_from_this()); } -double LevelSoundPacket::getY() -{ - return y / LOCATION_ACCURACY; -} - -double LevelSoundPacket::getZ() -{ - return z / LOCATION_ACCURACY; -} - -float LevelSoundPacket::getVolume() -{ - return volume; -} - -float LevelSoundPacket::getPitch() -{ - //return pitch / PITCH_ACCURACY; - return pitch; -} - -void LevelSoundPacket::handle(PacketListener *listener) -{ - listener->handleSoundEvent(shared_from_this()); -} - -int LevelSoundPacket::getEstimatedSize() -{ - return 4 * 6; -} +int LevelSoundPacket::getEstimatedSize() { return 4 * 6; } diff --git a/Minecraft.World/Network/Packets/LevelSoundPacket.h b/Minecraft.World/Network/Packets/LevelSoundPacket.h index a11a923bd..463b3b9a2 100644 --- a/Minecraft.World/Network/Packets/LevelSoundPacket.h +++ b/Minecraft.World/Network/Packets/LevelSoundPacket.h @@ -2,37 +2,40 @@ #include "Packet.h" -class LevelSoundPacket : public Packet, public std::enable_shared_from_this -{ +class LevelSoundPacket : public Packet, + public std::enable_shared_from_this { public: - static const float PITCH_ACCURACY; - static const float LOCATION_ACCURACY; + static const float PITCH_ACCURACY; + static const float LOCATION_ACCURACY; private: - int sound; - int x; - int y; - int z; - float volume; - //int pitch; - float pitch; + int sound; + int x; + int y; + int z; + float volume; + // int pitch; + float pitch; public: - LevelSoundPacket(); - LevelSoundPacket(int iSound, double x, double y, double z, float volume, float pitch); + LevelSoundPacket(); + LevelSoundPacket(int iSound, double x, double y, double z, float volume, + float pitch); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getSound(); - double getX(); - double getY(); - double getZ(); - float getVolume(); - float getPitch(); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getSound(); + double getX(); + double getY(); + double getZ(); + float getVolume(); + float getPitch(); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new LevelSoundPacket()); } - virtual int getId() { return 62; } + static std::shared_ptr create() { + return std::shared_ptr(new LevelSoundPacket()); + } + virtual int getId() { return 62; } }; diff --git a/Minecraft.World/Network/Packets/LoginPacket.cpp b/Minecraft.World/Network/Packets/LoginPacket.cpp index 9d2d3364d..be8e0918c 100644 --- a/Minecraft.World/Network/Packets/LoginPacket.cpp +++ b/Minecraft.World/Network/Packets/LoginPacket.cpp @@ -7,175 +7,176 @@ #include "LoginPacket.h" #include "../../Level/Storage/LevelType.h" +LoginPacket::LoginPacket() { + this->userName = L""; + this->clientVersion = 0; + this->seed = 0; + this->dimension = 0; + this->gameType = 0; + this->mapHeight = 0; + this->maxPlayers = 0; -LoginPacket::LoginPacket() -{ - this->userName = L""; - this->clientVersion = 0; - this->seed = 0; - this->dimension = 0; - this->gameType = 0; - this->mapHeight = 0; - this->maxPlayers = 0; + this->difficulty = 1; - this->difficulty = 1; - - this->m_offlineXuid = INVALID_XUID; - this->m_onlineXuid = INVALID_XUID; - m_friendsOnlyUGC = false; - m_ugcPlayersVersion = 0; - m_multiplayerInstanceId = 0; - m_playerIndex = 0; - m_playerSkinId = 0; - m_playerCapeId = 0; - m_isGuest = false; - m_newSeaLevel = false; - m_pLevelType = NULL; - m_uiGamePrivileges = 0; - m_xzSize = LEVEL_MAX_WIDTH; - m_hellScale = HELL_LEVEL_MAX_SCALE; + this->m_offlineXuid = INVALID_XUID; + this->m_onlineXuid = INVALID_XUID; + m_friendsOnlyUGC = false; + m_ugcPlayersVersion = 0; + m_multiplayerInstanceId = 0; + m_playerIndex = 0; + m_playerSkinId = 0; + m_playerCapeId = 0; + m_isGuest = false; + m_newSeaLevel = false; + m_pLevelType = NULL; + m_uiGamePrivileges = 0; + m_xzSize = LEVEL_MAX_WIDTH; + m_hellScale = HELL_LEVEL_MAX_SCALE; } // Client -> Server -LoginPacket::LoginPacket(const std::wstring& userName, int clientVersion, PlayerUID offlineXuid, PlayerUID onlineXuid, bool friendsOnlyUGC, std::uint32_t ugcPlayersVersion, std::uint32_t skinId, std::uint32_t capeId, bool isGuest) -{ - this->userName = userName; - this->clientVersion = clientVersion; - this->seed = 0; - this->dimension = 0; - this->gameType = 0; - this->mapHeight = 0; - this->maxPlayers = 0; +LoginPacket::LoginPacket(const std::wstring& userName, int clientVersion, + PlayerUID offlineXuid, PlayerUID onlineXuid, + bool friendsOnlyUGC, std::uint32_t ugcPlayersVersion, + std::uint32_t skinId, std::uint32_t capeId, + bool isGuest) { + this->userName = userName; + this->clientVersion = clientVersion; + this->seed = 0; + this->dimension = 0; + this->gameType = 0; + this->mapHeight = 0; + this->maxPlayers = 0; - this->difficulty = 1; + this->difficulty = 1; - this->m_offlineXuid = offlineXuid; - this->m_onlineXuid = onlineXuid; - m_friendsOnlyUGC = friendsOnlyUGC; - m_ugcPlayersVersion = ugcPlayersVersion; - m_multiplayerInstanceId = 0; - m_playerIndex = 0; - m_playerSkinId = skinId; - m_playerCapeId = capeId; - m_isGuest = isGuest; - m_newSeaLevel = false; - m_pLevelType = NULL; - m_uiGamePrivileges = 0; - m_xzSize = LEVEL_MAX_WIDTH; - m_hellScale = HELL_LEVEL_MAX_SCALE; + this->m_offlineXuid = offlineXuid; + this->m_onlineXuid = onlineXuid; + m_friendsOnlyUGC = friendsOnlyUGC; + m_ugcPlayersVersion = ugcPlayersVersion; + m_multiplayerInstanceId = 0; + m_playerIndex = 0; + m_playerSkinId = skinId; + m_playerCapeId = capeId; + m_isGuest = isGuest; + m_newSeaLevel = false; + m_pLevelType = NULL; + m_uiGamePrivileges = 0; + m_xzSize = LEVEL_MAX_WIDTH; + m_hellScale = HELL_LEVEL_MAX_SCALE; } // Server -> Client -LoginPacket::LoginPacket(const std::wstring& userName, int clientVersion, LevelType *pLevelType, __int64 seed, int gameType, char dimension, std::uint8_t mapHeight, std::uint8_t maxPlayers, char difficulty, int multiplayerInstanceId, std::uint8_t playerIndex, bool newSeaLevel, unsigned int uiGamePrivileges, int xzSize, int hellScale) -{ - this->userName = userName; - this->clientVersion = clientVersion; - this->seed = seed; - this->dimension = dimension; - this->gameType = gameType; - this->mapHeight = mapHeight; - this->maxPlayers = maxPlayers; +LoginPacket::LoginPacket(const std::wstring& userName, int clientVersion, + LevelType* pLevelType, __int64 seed, int gameType, + char dimension, std::uint8_t mapHeight, + std::uint8_t maxPlayers, char difficulty, + int multiplayerInstanceId, std::uint8_t playerIndex, + bool newSeaLevel, unsigned int uiGamePrivileges, + int xzSize, int hellScale) { + this->userName = userName; + this->clientVersion = clientVersion; + this->seed = seed; + this->dimension = dimension; + this->gameType = gameType; + this->mapHeight = mapHeight; + this->maxPlayers = maxPlayers; - this->difficulty = difficulty; + this->difficulty = difficulty; - this->m_offlineXuid = INVALID_XUID; - this->m_onlineXuid = INVALID_XUID; - m_friendsOnlyUGC = false; - m_ugcPlayersVersion = 0; - m_multiplayerInstanceId = multiplayerInstanceId; - this->m_playerIndex = playerIndex; - m_playerSkinId = 0; - m_playerCapeId = 0; - m_isGuest = false; - m_newSeaLevel = newSeaLevel; - this->m_pLevelType=pLevelType; - m_uiGamePrivileges = uiGamePrivileges; - m_xzSize = xzSize; - m_hellScale = hellScale; + this->m_offlineXuid = INVALID_XUID; + this->m_onlineXuid = INVALID_XUID; + m_friendsOnlyUGC = false; + m_ugcPlayersVersion = 0; + m_multiplayerInstanceId = multiplayerInstanceId; + this->m_playerIndex = playerIndex; + m_playerSkinId = 0; + m_playerCapeId = 0; + m_isGuest = false; + m_newSeaLevel = newSeaLevel; + this->m_pLevelType = pLevelType; + m_uiGamePrivileges = uiGamePrivileges; + m_xzSize = xzSize; + m_hellScale = hellScale; } -void LoginPacket::read(DataInputStream *dis) //throws IOException +void LoginPacket::read(DataInputStream* dis) // throws IOException { - clientVersion = dis->readInt(); - userName = readUtf(dis, Player::MAX_NAME_LENGTH); - std::wstring typeName = readUtf(dis, 16); - m_pLevelType = LevelType::getLevelType(typeName); - if (m_pLevelType == NULL) - { - m_pLevelType = LevelType::lvl_normal; - } - seed = dis->readLong(); - gameType = dis->readInt(); - dimension = (int)dis->readByte(); - mapHeight = dis->readByte(); - maxPlayers = dis->readByte(); - m_offlineXuid = dis->readPlayerUID(); - m_onlineXuid = dis->readPlayerUID(); - m_friendsOnlyUGC = dis->readBoolean(); - m_ugcPlayersVersion = static_cast(dis->readInt()); - difficulty = (int)dis->readByte(); - m_multiplayerInstanceId = dis->readInt(); - m_playerIndex = dis->readByte(); - m_playerSkinId = static_cast(dis->readInt()); - m_playerCapeId = static_cast(dis->readInt()); - m_isGuest = dis->readBoolean(); - m_newSeaLevel = dis->readBoolean(); - m_uiGamePrivileges = dis->readInt(); + clientVersion = dis->readInt(); + userName = readUtf(dis, Player::MAX_NAME_LENGTH); + std::wstring typeName = readUtf(dis, 16); + m_pLevelType = LevelType::getLevelType(typeName); + if (m_pLevelType == NULL) { + m_pLevelType = LevelType::lvl_normal; + } + seed = dis->readLong(); + gameType = dis->readInt(); + dimension = (int)dis->readByte(); + mapHeight = dis->readByte(); + maxPlayers = dis->readByte(); + m_offlineXuid = dis->readPlayerUID(); + m_onlineXuid = dis->readPlayerUID(); + m_friendsOnlyUGC = dis->readBoolean(); + m_ugcPlayersVersion = static_cast(dis->readInt()); + difficulty = (int)dis->readByte(); + m_multiplayerInstanceId = dis->readInt(); + m_playerIndex = dis->readByte(); + m_playerSkinId = static_cast(dis->readInt()); + m_playerCapeId = static_cast(dis->readInt()); + m_isGuest = dis->readBoolean(); + m_newSeaLevel = dis->readBoolean(); + m_uiGamePrivileges = dis->readInt(); #ifdef _LARGE_WORLDS - m_xzSize = dis->readShort(); - m_hellScale = dis->read(); + m_xzSize = dis->readShort(); + m_hellScale = dis->read(); #endif - app.DebugPrintf("LoginPacket::read - Difficulty = %d\n",difficulty); - + app.DebugPrintf("LoginPacket::read - Difficulty = %d\n", difficulty); } -void LoginPacket::write(DataOutputStream *dos) //throws IOException +void LoginPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(clientVersion); - writeUtf(userName, dos); - if (m_pLevelType == NULL) - { - writeUtf(L"", dos); - } - else - { - writeUtf(m_pLevelType->getGeneratorName(), dos); - } - dos->writeLong(seed); - dos->writeInt(gameType); - dos->writeByte((std::uint8_t)dimension); - dos->writeByte((std::uint8_t)mapHeight); - dos->writeByte((std::uint8_t)maxPlayers); - dos->writePlayerUID(m_offlineXuid); - dos->writePlayerUID(m_onlineXuid); - dos->writeBoolean(m_friendsOnlyUGC); - dos->writeInt(static_cast(m_ugcPlayersVersion)); - dos->writeByte((std::uint8_t)difficulty); - dos->writeInt(m_multiplayerInstanceId); - dos->writeByte((std::uint8_t)m_playerIndex); - dos->writeInt(static_cast(m_playerSkinId)); - dos->writeInt(static_cast(m_playerCapeId)); - dos->writeBoolean(m_isGuest); - dos->writeBoolean(m_newSeaLevel); - dos->writeInt(m_uiGamePrivileges); + dos->writeInt(clientVersion); + writeUtf(userName, dos); + if (m_pLevelType == NULL) { + writeUtf(L"", dos); + } else { + writeUtf(m_pLevelType->getGeneratorName(), dos); + } + dos->writeLong(seed); + dos->writeInt(gameType); + dos->writeByte((std::uint8_t)dimension); + dos->writeByte((std::uint8_t)mapHeight); + dos->writeByte((std::uint8_t)maxPlayers); + dos->writePlayerUID(m_offlineXuid); + dos->writePlayerUID(m_onlineXuid); + dos->writeBoolean(m_friendsOnlyUGC); + dos->writeInt(static_cast(m_ugcPlayersVersion)); + dos->writeByte((std::uint8_t)difficulty); + dos->writeInt(m_multiplayerInstanceId); + dos->writeByte((std::uint8_t)m_playerIndex); + dos->writeInt(static_cast(m_playerSkinId)); + dos->writeInt(static_cast(m_playerCapeId)); + dos->writeBoolean(m_isGuest); + dos->writeBoolean(m_newSeaLevel); + dos->writeInt(m_uiGamePrivileges); #ifdef _LARGE_WORLDS - dos->writeShort(m_xzSize); - dos->write(m_hellScale); + dos->writeShort(m_xzSize); + dos->write(m_hellScale); #endif } -void LoginPacket::handle(PacketListener *listener) -{ - listener->handleLogin(shared_from_this()); +void LoginPacket::handle(PacketListener* listener) { + listener->handleLogin(shared_from_this()); } -int LoginPacket::getEstimatedSize() -{ - int length=0; - if (m_pLevelType != NULL) - { - length = (int)m_pLevelType->getGeneratorName().length(); - } +int LoginPacket::getEstimatedSize() { + int length = 0; + if (m_pLevelType != NULL) { + length = (int)m_pLevelType->getGeneratorName().length(); + } - return (int)(sizeof(int) + userName.length() + 4 + 6 + sizeof(__int64) + sizeof(char) + sizeof(int) + (2*sizeof(PlayerUID)) + 1 + sizeof(char) + sizeof(std::uint8_t) + sizeof(bool) + sizeof(bool) + length + sizeof(unsigned int)); + return (int)(sizeof(int) + userName.length() + 4 + 6 + sizeof(__int64) + + sizeof(char) + sizeof(int) + (2 * sizeof(PlayerUID)) + 1 + + sizeof(char) + sizeof(std::uint8_t) + sizeof(bool) + + sizeof(bool) + length + sizeof(unsigned int)); } diff --git a/Minecraft.World/Network/Packets/LoginPacket.h b/Minecraft.World/Network/Packets/LoginPacket.h index b6f14816a..c96efc261 100644 --- a/Minecraft.World/Network/Packets/LoginPacket.h +++ b/Minecraft.World/Network/Packets/LoginPacket.h @@ -5,42 +5,54 @@ #include "Packet.h" class LevelType; -class LoginPacket : public Packet, public std::enable_shared_from_this -{ +class LoginPacket : public Packet, + public std::enable_shared_from_this { public: - int clientVersion; - std::wstring userName; - __int64 seed; - char dimension; - PlayerUID m_offlineXuid, m_onlineXuid; // 4J Added - char difficulty; // 4J Added - bool m_friendsOnlyUGC; // 4J Added - std::uint32_t m_ugcPlayersVersion; // 4J Added - int m_multiplayerInstanceId; //4J Added for sentient - std::uint8_t m_playerIndex; // 4J Added - std::uint32_t m_playerSkinId, m_playerCapeId; // 4J Added - bool m_isGuest; // 4J Added - bool m_newSeaLevel; // 4J Added - LevelType *m_pLevelType; - unsigned int m_uiGamePrivileges; - int m_xzSize; // 4J Added - int m_hellScale; // 4J Added + int clientVersion; + std::wstring userName; + __int64 seed; + char dimension; + PlayerUID m_offlineXuid, m_onlineXuid; // 4J Added + char difficulty; // 4J Added + bool m_friendsOnlyUGC; // 4J Added + std::uint32_t m_ugcPlayersVersion; // 4J Added + int m_multiplayerInstanceId; // 4J Added for sentient + std::uint8_t m_playerIndex; // 4J Added + std::uint32_t m_playerSkinId, m_playerCapeId; // 4J Added + bool m_isGuest; // 4J Added + bool m_newSeaLevel; // 4J Added + LevelType* m_pLevelType; + unsigned int m_uiGamePrivileges; + int m_xzSize; // 4J Added + int m_hellScale; // 4J Added - // 1.8.2 - int gameType; - std::uint8_t mapHeight; - std::uint8_t maxPlayers; + // 1.8.2 + int gameType; + std::uint8_t mapHeight; + std::uint8_t maxPlayers; - LoginPacket(); - LoginPacket(const std::wstring& userName, int clientVersion, LevelType *pLevelType, __int64 seed, int gameType, char dimension, std::uint8_t mapHeight, std::uint8_t maxPlayers, char difficulty, int m_multiplayerInstanceId, std::uint8_t playerIndex, bool newSeaLevel, unsigned int uiGamePrivileges, int xzSize, int hellScale); // Server -> Client - LoginPacket(const std::wstring& userName, int clientVersion, PlayerUID offlineXuid, PlayerUID onlineXuid, bool friendsOnlyUGC, std::uint32_t ugcPlayersVersion, std::uint32_t skinId, std::uint32_t capeId, bool isGuest); // Client -> Server + LoginPacket(); + LoginPacket(const std::wstring& userName, int clientVersion, + LevelType* pLevelType, __int64 seed, int gameType, + char dimension, std::uint8_t mapHeight, std::uint8_t maxPlayers, + char difficulty, int m_multiplayerInstanceId, + std::uint8_t playerIndex, bool newSeaLevel, + unsigned int uiGamePrivileges, int xzSize, + int hellScale); // Server -> Client + LoginPacket(const std::wstring& userName, int clientVersion, + PlayerUID offlineXuid, PlayerUID onlineXuid, + bool friendsOnlyUGC, std::uint32_t ugcPlayersVersion, + std::uint32_t skinId, std::uint32_t capeId, + bool isGuest); // Client -> Server - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new LoginPacket()); } - virtual int getId() { return 1; } + static std::shared_ptr create() { + return std::shared_ptr(new LoginPacket()); + } + virtual int getId() { return 1; } }; diff --git a/Minecraft.World/Network/Packets/MoveEntityPacket.cpp b/Minecraft.World/Network/Packets/MoveEntityPacket.cpp index 3fde6d6ab..30ca1b905 100644 --- a/Minecraft.World/Network/Packets/MoveEntityPacket.cpp +++ b/Minecraft.World/Network/Packets/MoveEntityPacket.cpp @@ -4,165 +4,141 @@ #include "PacketListener.h" #include "MoveEntityPacket.h" -MoveEntityPacket::MoveEntityPacket() -{ - hasRot = false; +MoveEntityPacket::MoveEntityPacket() { + hasRot = false; - id = -1; - xa = 0; - ya = 0; - za = 0; - yRot = 0; - xRot = 0; + id = -1; + xa = 0; + ya = 0; + za = 0; + yRot = 0; + xRot = 0; } -MoveEntityPacket::MoveEntityPacket(int id) -{ - this->id = id; - hasRot = false; +MoveEntityPacket::MoveEntityPacket(int id) { + this->id = id; + hasRot = false; - xa = 0; - ya = 0; - za = 0; - yRot = 0; - xRot = 0; + xa = 0; + ya = 0; + za = 0; + yRot = 0; + xRot = 0; } -void MoveEntityPacket::read(DataInputStream *dis) //throws IOException +void MoveEntityPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readShort(); + id = dis->readShort(); } -void MoveEntityPacket::write(DataOutputStream *dos) //throws IOException +void MoveEntityPacket::write(DataOutputStream* dos) // throws IOException { - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } - dos->writeShort((short)id); + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } + dos->writeShort((short)id); } -void MoveEntityPacket::handle(PacketListener *listener) -{ - listener->handleMoveEntity(shared_from_this()); +void MoveEntityPacket::handle(PacketListener* listener) { + listener->handleMoveEntity(shared_from_this()); } -int MoveEntityPacket::getEstimatedSize() -{ - return 2; +int MoveEntityPacket::getEstimatedSize() { return 2; } + +bool MoveEntityPacket::canBeInvalidated() { return true; } + +bool MoveEntityPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target != NULL && target->id == id; } -bool MoveEntityPacket::canBeInvalidated() -{ - return true; +MoveEntityPacket::PosRot::PosRot() { hasRot = true; } + +MoveEntityPacket::PosRot::PosRot(int id, char xa, char ya, char za, char yRot, + char xRot) + : MoveEntityPacket(id) { + this->xa = xa; + this->ya = ya; + this->za = za; + this->yRot = yRot; + this->xRot = xRot; + hasRot = true; } -bool MoveEntityPacket::isInvalidatedBy(std::shared_ptr packet) +void MoveEntityPacket::PosRot::read(DataInputStream* dis) // throws IOException { - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target != NULL && target->id == id; + MoveEntityPacket::read(dis); + xa = (int)dis->readByte(); + ya = (int)dis->readByte(); + za = (int)dis->readByte(); + yRot = (int)dis->readByte(); + xRot = (int)dis->readByte(); } -MoveEntityPacket::PosRot::PosRot() +void MoveEntityPacket::PosRot::write( + DataOutputStream* dos) // throws IOException { - hasRot = true; + MoveEntityPacket::write(dos); + dos->writeByte((uint8_t)xa); + dos->writeByte((uint8_t)ya); + dos->writeByte((uint8_t)za); + dos->writeByte((uint8_t)yRot); + dos->writeByte((uint8_t)xRot); } -MoveEntityPacket::PosRot::PosRot(int id, char xa, char ya, char za, char yRot, char xRot) : MoveEntityPacket( id ) -{ - this->xa = xa; - this->ya = ya; - this->za = za; - this->yRot = yRot; - this->xRot = xRot; - hasRot = true; +int MoveEntityPacket::PosRot::getEstimatedSize() { return 2 + 5; } + +MoveEntityPacket::Pos::Pos() {} + +MoveEntityPacket::Pos::Pos(int id, char xa, char ya, char za) + : MoveEntityPacket(id) { + this->xa = xa; + this->ya = ya; + this->za = za; } -void MoveEntityPacket::PosRot::read(DataInputStream *dis) //throws IOException +void MoveEntityPacket::Pos::read(DataInputStream* dis) // throws IOException { - MoveEntityPacket::read(dis); - xa = (int)dis->readByte(); - ya = (int)dis->readByte(); - za = (int)dis->readByte(); - yRot = (int)dis->readByte(); - xRot = (int)dis->readByte(); + MoveEntityPacket::read(dis); + xa = (int)dis->readByte(); + ya = (int)dis->readByte(); + za = (int)dis->readByte(); } -void MoveEntityPacket::PosRot::write(DataOutputStream *dos) //throws IOException +void MoveEntityPacket::Pos::write(DataOutputStream* dos) // throws IOException { - MoveEntityPacket::write(dos); - dos->writeByte((uint8_t)xa); - dos->writeByte((uint8_t)ya); - dos->writeByte((uint8_t)za); - dos->writeByte((uint8_t)yRot); - dos->writeByte((uint8_t)xRot); + MoveEntityPacket::write(dos); + dos->writeByte((uint8_t)xa); + dos->writeByte((uint8_t)ya); + dos->writeByte((uint8_t)za); } -int MoveEntityPacket::PosRot::getEstimatedSize() -{ - return 2+5; +int MoveEntityPacket::Pos::getEstimatedSize() { return 2 + 3; } + +MoveEntityPacket::Rot::Rot() { hasRot = true; } + +MoveEntityPacket::Rot::Rot(int id, char yRot, char xRot) + : MoveEntityPacket(id) { + this->yRot = yRot; + this->xRot = xRot; + hasRot = true; } -MoveEntityPacket::Pos::Pos() +void MoveEntityPacket::Rot::read(DataInputStream* dis) // throws IOException { + MoveEntityPacket::read(dis); + yRot = (int)dis->readByte(); + xRot = (int)dis->readByte(); } -MoveEntityPacket::Pos::Pos(int id, char xa, char ya, char za) : MoveEntityPacket(id) +void MoveEntityPacket::Rot::write(DataOutputStream* dos) // throws IOException { - this->xa = xa; - this->ya = ya; - this->za = za; + MoveEntityPacket::write(dos); + dos->writeByte((uint8_t)yRot); + dos->writeByte((uint8_t)xRot); } -void MoveEntityPacket::Pos::read(DataInputStream *dis) //throws IOException -{ - MoveEntityPacket::read(dis); - xa = (int)dis->readByte(); - ya = (int)dis->readByte(); - za = (int)dis->readByte(); -} - -void MoveEntityPacket::Pos::write(DataOutputStream *dos) //throws IOException -{ - MoveEntityPacket::write(dos); - dos->writeByte((uint8_t)xa); - dos->writeByte((uint8_t)ya); - dos->writeByte((uint8_t)za); -} - -int MoveEntityPacket::Pos::getEstimatedSize() -{ - return 2+3; -} - -MoveEntityPacket::Rot::Rot() -{ - hasRot = true; -} - -MoveEntityPacket::Rot::Rot(int id, char yRot, char xRot) : MoveEntityPacket(id) -{ - this->yRot = yRot; - this->xRot = xRot; - hasRot = true; -} - -void MoveEntityPacket::Rot::read(DataInputStream *dis) //throws IOException -{ - MoveEntityPacket::read(dis); - yRot = (int)dis->readByte(); - xRot = (int)dis->readByte(); -} - -void MoveEntityPacket::Rot::write(DataOutputStream *dos) //throws IOException -{ - MoveEntityPacket::write(dos); - dos->writeByte((uint8_t)yRot); - dos->writeByte((uint8_t)xRot); -} - -int MoveEntityPacket::Rot::getEstimatedSize() -{ - return 2+2; -} +int MoveEntityPacket::Rot::getEstimatedSize() { return 2 + 2; } diff --git a/Minecraft.World/Network/Packets/MoveEntityPacket.h b/Minecraft.World/Network/Packets/MoveEntityPacket.h index 62560809f..ea6811b3a 100644 --- a/Minecraft.World/Network/Packets/MoveEntityPacket.h +++ b/Minecraft.World/Network/Packets/MoveEntityPacket.h @@ -1,78 +1,80 @@ #pragma once - #include "Packet.h" -class MoveEntityPacket : public Packet, public std::enable_shared_from_this -{ - - // 4J JEV, static inner/sub classes +class MoveEntityPacket : public Packet, + public std::enable_shared_from_this { + // 4J JEV, static inner/sub classes public: - class PosRot; - class Pos; - class Rot; + class PosRot; + class Pos; + class Rot; - int id; - char xa, ya, za, yRot, xRot; - bool hasRot; + int id; + char xa, ya, za, yRot, xRot; + bool hasRot; - MoveEntityPacket(); - MoveEntityPacket(int id); + MoveEntityPacket(); + MoveEntityPacket(int id); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacket()); } - virtual int getId() { return 30; } + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacket()); + } + virtual int getId() { return 30; } }; -class MoveEntityPacket::PosRot : public MoveEntityPacket -{ +class MoveEntityPacket::PosRot : public MoveEntityPacket { public: - PosRot(); - PosRot(int id, char xa, char ya, char za, char yRot, char xRot); + PosRot(); + PosRot(int id, char xa, char ya, char za, char yRot, char xRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacket::PosRot()); } - virtual int getId() { return 33; } + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacket::PosRot()); + } + virtual int getId() { return 33; } }; -class MoveEntityPacket::Pos : public MoveEntityPacket -{ +class MoveEntityPacket::Pos : public MoveEntityPacket { public: - Pos(); - Pos(int id, char xa, char ya, char za); + Pos(); + Pos(int id, char xa, char ya, char za); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacket::Pos()); } - virtual int getId() { return 31; } + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacket::Pos()); + } + virtual int getId() { return 31; } }; -class MoveEntityPacket::Rot : public MoveEntityPacket -{ +class MoveEntityPacket::Rot : public MoveEntityPacket { public: - Rot(); - Rot(int id, char yRot, char xRot); + Rot(); + Rot(int id, char yRot, char xRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacket::Rot()); } - virtual int getId() { return 32; } - + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacket::Rot()); + } + virtual int getId() { return 32; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/MoveEntityPacketSmall.cpp b/Minecraft.World/Network/Packets/MoveEntityPacketSmall.cpp index 23cf4af51..085ff3152 100644 --- a/Minecraft.World/Network/Packets/MoveEntityPacketSmall.cpp +++ b/Minecraft.World/Network/Packets/MoveEntityPacketSmall.cpp @@ -4,188 +4,167 @@ #include "PacketListener.h" #include "MoveEntityPacketSmall.h" +MoveEntityPacketSmall::MoveEntityPacketSmall() { + hasRot = false; -MoveEntityPacketSmall::MoveEntityPacketSmall() -{ - hasRot = false; - - id = -1; - xa = 0; - ya = 0; - za = 0; - yRot = 0; - xRot = 0; + id = -1; + xa = 0; + ya = 0; + za = 0; + yRot = 0; + xRot = 0; } -MoveEntityPacketSmall::MoveEntityPacketSmall(int id) -{ - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } +MoveEntityPacketSmall::MoveEntityPacketSmall(int id) { + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } - this->id = id; - hasRot = false; + this->id = id; + hasRot = false; - xa = 0; - ya = 0; - za = 0; - yRot = 0; - xRot = 0; + xa = 0; + ya = 0; + za = 0; + yRot = 0; + xRot = 0; } -void MoveEntityPacketSmall::read(DataInputStream *dis) //throws IOException +void MoveEntityPacketSmall::read(DataInputStream* dis) // throws IOException { - id = dis->readShort(); + id = dis->readShort(); } -void MoveEntityPacketSmall::write(DataOutputStream *dos) //throws IOException +void MoveEntityPacketSmall::write(DataOutputStream* dos) // throws IOException { - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } - dos->writeShort((short)id); + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } + dos->writeShort((short)id); } -void MoveEntityPacketSmall::handle(PacketListener *listener) -{ - listener->handleMoveEntitySmall(shared_from_this()); +void MoveEntityPacketSmall::handle(PacketListener* listener) { + listener->handleMoveEntitySmall(shared_from_this()); } -int MoveEntityPacketSmall::getEstimatedSize() -{ - return 2; +int MoveEntityPacketSmall::getEstimatedSize() { return 2; } + +bool MoveEntityPacketSmall::canBeInvalidated() { return true; } + +bool MoveEntityPacketSmall::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target != NULL && target->id == id; } -bool MoveEntityPacketSmall::canBeInvalidated() -{ - return true; +MoveEntityPacketSmall::PosRot::PosRot() { hasRot = true; } + +MoveEntityPacketSmall::PosRot::PosRot(int id, char xa, char ya, char za, + char yRot, char xRot) + : MoveEntityPacketSmall(id) { + this->xa = xa; + this->ya = ya; + this->za = za; + this->yRot = yRot; + this->xRot = xRot; + hasRot = true; } -bool MoveEntityPacketSmall::isInvalidatedBy(std::shared_ptr packet) +void MoveEntityPacketSmall::PosRot::read( + DataInputStream* dis) // throws IOException { - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target != NULL && target->id == id; + int idAndRot = dis->readShort(); + this->id = idAndRot & 0x07ff; + this->yRot = idAndRot >> 11; + int xAndYAndZ = (int)dis->readShort(); + this->xa = xAndYAndZ >> 11; + this->ya = (xAndYAndZ << 21) >> 26; + this->za = (xAndYAndZ << 27) >> 27; } -MoveEntityPacketSmall::PosRot::PosRot() +void MoveEntityPacketSmall::PosRot::write( + DataOutputStream* dos) // throws IOException { - hasRot = true; + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } + short idAndRot = id | yRot << 11; + dos->writeShort(idAndRot); + short xAndYAndZ = (xa << 11) | ((ya & 0x3f) << 5) | (za & 0x1f); + dos->writeShort(xAndYAndZ); } -MoveEntityPacketSmall::PosRot::PosRot(int id, char xa, char ya, char za, char yRot, char xRot) : MoveEntityPacketSmall( id ) -{ - this->xa = xa; - this->ya = ya; - this->za = za; - this->yRot = yRot; - this->xRot = xRot; - hasRot = true; +int MoveEntityPacketSmall::PosRot::getEstimatedSize() { return 4; } + +MoveEntityPacketSmall::Pos::Pos() {} + +MoveEntityPacketSmall::Pos::Pos(int id, char xa, char ya, char za) + : MoveEntityPacketSmall(id) { + this->xa = xa; + this->ya = ya; + this->za = za; } -void MoveEntityPacketSmall::PosRot::read(DataInputStream *dis) //throws IOException +void MoveEntityPacketSmall::Pos::read( + DataInputStream* dis) // throws IOException { - int idAndRot = dis->readShort(); - this->id = idAndRot & 0x07ff; - this->yRot = idAndRot >> 11; - int xAndYAndZ = (int)dis->readShort(); - this->xa = xAndYAndZ >> 11; - this->ya = (xAndYAndZ << 21 ) >> 26; - this->za = (xAndYAndZ << 27 ) >> 27; + int idAndY = dis->readShort(); + this->id = idAndY & 0x07ff; + this->ya = idAndY >> 11; + int XandZ = (int)((signed char)(dis->readByte())); + xa = XandZ >> 4; + za = (XandZ << 28) >> 28; } -void MoveEntityPacketSmall::PosRot::write(DataOutputStream *dos) //throws IOException +void MoveEntityPacketSmall::Pos::write( + DataOutputStream* dos) // throws IOException { - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } - short idAndRot = id | yRot << 11; - dos->writeShort(idAndRot); - short xAndYAndZ = ( xa << 11 ) | ( ( ya & 0x3f ) << 5 ) | ( za & 0x1f ); - dos->writeShort(xAndYAndZ); + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } + short idAndY = id | ya << 11; + dos->writeShort(idAndY); + char XandZ = (xa << 4) | (za & 0x0f); + dos->writeByte((uint8_t)XandZ); } -int MoveEntityPacketSmall::PosRot::getEstimatedSize() -{ - return 4; +int MoveEntityPacketSmall::Pos::getEstimatedSize() { return 3; } + +MoveEntityPacketSmall::Rot::Rot() { hasRot = true; } + +MoveEntityPacketSmall::Rot::Rot(int id, char yRot, char xRot) + : MoveEntityPacketSmall(id) { + this->yRot = yRot; + this->xRot = xRot; + hasRot = true; } -MoveEntityPacketSmall::Pos::Pos() +void MoveEntityPacketSmall::Rot::read( + DataInputStream* dis) // throws IOException { + int idAndRot = (int)dis->readShort(); + this->id = idAndRot & 0x07ff; + this->yRot = idAndRot >> 11; } -MoveEntityPacketSmall::Pos::Pos(int id, char xa, char ya, char za) : MoveEntityPacketSmall(id) +void MoveEntityPacketSmall::Rot::write( + DataOutputStream* dos) // throws IOException { - this->xa = xa; - this->ya = ya; - this->za = za; + if ((id < 0) || (id >= 2048)) { + // We shouln't be tracking an entity that doesn't have a short type of + // id + __debugbreak(); + } + short idAndRot = id | yRot << 11; + dos->writeShort(idAndRot); } -void MoveEntityPacketSmall::Pos::read(DataInputStream *dis) //throws IOException -{ - int idAndY = dis->readShort(); - this->id = idAndY & 0x07ff; - this->ya = idAndY >> 11; - int XandZ = (int)((signed char)(dis->readByte())); - xa = XandZ >> 4; - za = ( XandZ << 28 ) >> 28; -} - -void MoveEntityPacketSmall::Pos::write(DataOutputStream *dos) //throws IOException -{ - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } - short idAndY = id | ya << 11; - dos->writeShort(idAndY); - char XandZ = ( xa << 4 ) | ( za & 0x0f ); - dos->writeByte((uint8_t)XandZ); -} - -int MoveEntityPacketSmall::Pos::getEstimatedSize() -{ - return 3; -} - -MoveEntityPacketSmall::Rot::Rot() -{ - hasRot = true; -} - -MoveEntityPacketSmall::Rot::Rot(int id, char yRot, char xRot) : MoveEntityPacketSmall(id) -{ - - this->yRot = yRot; - this->xRot = xRot; - hasRot = true; -} - -void MoveEntityPacketSmall::Rot::read(DataInputStream *dis) //throws IOException -{ - int idAndRot = (int)dis->readShort(); - this->id = idAndRot & 0x07ff; - this->yRot = idAndRot >> 11; -} - -void MoveEntityPacketSmall::Rot::write(DataOutputStream *dos) //throws IOException -{ - if( (id < 0 ) || (id >= 2048 ) ) - { - // We shouln't be tracking an entity that doesn't have a short type of id - __debugbreak(); - } - short idAndRot = id | yRot << 11; - dos->writeShort(idAndRot); -} - -int MoveEntityPacketSmall::Rot::getEstimatedSize() -{ - return 2; -} +int MoveEntityPacketSmall::Rot::getEstimatedSize() { return 2; } diff --git a/Minecraft.World/Network/Packets/MoveEntityPacketSmall.h b/Minecraft.World/Network/Packets/MoveEntityPacketSmall.h index fffdc7e56..547d5c7b2 100644 --- a/Minecraft.World/Network/Packets/MoveEntityPacketSmall.h +++ b/Minecraft.World/Network/Packets/MoveEntityPacketSmall.h @@ -1,79 +1,81 @@ #pragma once - #include "Packet.h" -class MoveEntityPacketSmall : public Packet, public std::enable_shared_from_this -{ - - // 4J JEV, static inner/sub classes +class MoveEntityPacketSmall + : public Packet, + public std::enable_shared_from_this { + // 4J JEV, static inner/sub classes public: - class PosRot; - class Pos; - class Rot; + class PosRot; + class Pos; + class Rot; - int id; + int id; char xa, ya, za, yRot, xRot; - bool hasRot; + bool hasRot; - MoveEntityPacketSmall(); - MoveEntityPacketSmall(int id); + MoveEntityPacketSmall(); + MoveEntityPacketSmall(int id); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacketSmall()); } - virtual int getId() { return 162; } + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacketSmall()); + } + virtual int getId() { return 162; } }; -class MoveEntityPacketSmall::PosRot : public MoveEntityPacketSmall -{ +class MoveEntityPacketSmall::PosRot : public MoveEntityPacketSmall { public: - PosRot(); - PosRot(int id, char xa, char ya, char za, char yRot, char xRot); + PosRot(); + PosRot(int id, char xa, char ya, char za, char yRot, char xRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacketSmall::PosRot()); } - virtual int getId() { return 165; } + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacketSmall::PosRot()); + } + virtual int getId() { return 165; } }; -class MoveEntityPacketSmall::Pos : public MoveEntityPacketSmall -{ +class MoveEntityPacketSmall::Pos : public MoveEntityPacketSmall { public: - Pos(); - Pos(int id, char xa, char ya, char za); + Pos(); + Pos(int id, char xa, char ya, char za); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacketSmall::Pos()); } - virtual int getId() { return 163; } - + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacketSmall::Pos()); + } + virtual int getId() { return 163; } }; -class MoveEntityPacketSmall::Rot : public MoveEntityPacketSmall -{ +class MoveEntityPacketSmall::Rot : public MoveEntityPacketSmall { public: - Rot(); - Rot(int id, char yRot, char xRot); + Rot(); + Rot(int id, char yRot, char xRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MoveEntityPacketSmall::Rot()); } - virtual int getId() { return 164; } - + static std::shared_ptr create() { + return std::shared_ptr(new MoveEntityPacketSmall::Rot()); + } + virtual int getId() { return 164; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/MovePlayerPacket.cpp b/Minecraft.World/Network/Packets/MovePlayerPacket.cpp index 4a007eb0e..e296dc7cf 100644 --- a/Minecraft.World/Network/Packets/MovePlayerPacket.cpp +++ b/Minecraft.World/Network/Packets/MovePlayerPacket.cpp @@ -4,185 +4,161 @@ #include "PacketListener.h" #include "MovePlayerPacket.h" -MovePlayerPacket::MovePlayerPacket() -{ - x = 0; - y = 0; - z = 0; - yView = 0; - yRot = 0; - xRot = 0; - onGround = false; - hasPos = false; - hasRot = false; - isFlying = false; +MovePlayerPacket::MovePlayerPacket() { + x = 0; + y = 0; + z = 0; + yView = 0; + yRot = 0; + xRot = 0; + onGround = false; + hasPos = false; + hasRot = false; + isFlying = false; } -MovePlayerPacket::MovePlayerPacket(bool onGround, bool isFlying) -{ - x = 0; - y = 0; - z = 0; - yView = 0; - yRot = 0; - xRot = 0; - hasPos = false; - hasRot = false; +MovePlayerPacket::MovePlayerPacket(bool onGround, bool isFlying) { + x = 0; + y = 0; + z = 0; + yView = 0; + yRot = 0; + xRot = 0; + hasPos = false; + hasRot = false; - this->onGround = onGround; - this->isFlying = isFlying; + this->onGround = onGround; + this->isFlying = isFlying; } -void MovePlayerPacket::handle(PacketListener *listener) -{ - listener->handleMovePlayer(shared_from_this()); +void MovePlayerPacket::handle(PacketListener* listener) { + listener->handleMovePlayer(shared_from_this()); } -void MovePlayerPacket::read(DataInputStream *dis) //throws IOException +void MovePlayerPacket::read(DataInputStream* dis) // throws IOException { - char value = dis->read(); - onGround = (value & 0x1) != 0; - isFlying = (value & 0x2) != 0; - //onGround = dis->read() != 0; + char value = dis->read(); + onGround = (value & 0x1) != 0; + isFlying = (value & 0x2) != 0; + // onGround = dis->read() != 0; } -void MovePlayerPacket::write(DataOutputStream *dos) //throws IOException +void MovePlayerPacket::write(DataOutputStream* dos) // throws IOException { - char value = (onGround ? 0x1 : 0) | (isFlying ? 0x2 : 0); - dos->write(value); - //dos->write(onGround ? 1 : 0); + char value = (onGround ? 0x1 : 0) | (isFlying ? 0x2 : 0); + dos->write(value); + // dos->write(onGround ? 1 : 0); } -int MovePlayerPacket::getEstimatedSize() -{ - return 1; +int MovePlayerPacket::getEstimatedSize() { return 1; } + +bool MovePlayerPacket::canBeInvalidated() { return true; } + +bool MovePlayerPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } -bool MovePlayerPacket::canBeInvalidated() -{ - return true; +MovePlayerPacket::PosRot::PosRot() { + hasRot = true; + hasPos = true; } -bool MovePlayerPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; +MovePlayerPacket::PosRot::PosRot(double x, double y, double yView, double z, + float yRot, float xRot, bool onGround, + bool isFlying) { + this->x = x; + this->y = y; + this->yView = yView; + this->z = z; + this->yRot = yRot; + this->xRot = xRot; + this->onGround = onGround; + hasRot = true; + hasPos = true; + this->isFlying = isFlying; } -MovePlayerPacket::PosRot::PosRot() +void MovePlayerPacket::PosRot::read(DataInputStream* dis) // throws IOException { - hasRot = true; - hasPos = true; + x = dis->readDouble(); + y = dis->readDouble(); + yView = dis->readDouble(); + z = dis->readDouble(); + yRot = dis->readFloat(); + xRot = dis->readFloat(); + MovePlayerPacket::read(dis); } -MovePlayerPacket::PosRot::PosRot(double x, double y, double yView, double z, float yRot, float xRot, bool onGround, bool isFlying) +void MovePlayerPacket::PosRot::write( + DataOutputStream* dos) // throws IOException { - this->x = x; - this->y = y; - this->yView = yView; - this->z = z; - this->yRot = yRot; - this->xRot = xRot; - this->onGround = onGround; - hasRot = true; - hasPos = true; - this->isFlying = isFlying; + dos->writeDouble(x); + dos->writeDouble(y); + dos->writeDouble(yView); + dos->writeDouble(z); + dos->writeFloat(yRot); + dos->writeFloat(xRot); + MovePlayerPacket::write(dos); } -void MovePlayerPacket::PosRot::read(DataInputStream *dis) //throws IOException -{ - x = dis->readDouble(); - y = dis->readDouble(); - yView = dis->readDouble(); - z = dis->readDouble(); - yRot = dis->readFloat(); - xRot = dis->readFloat(); - MovePlayerPacket::read(dis); +int MovePlayerPacket::PosRot::getEstimatedSize() { return 8 * 5 + 1; } + +MovePlayerPacket::Pos::Pos() { hasPos = true; } + +MovePlayerPacket::Pos::Pos(double x, double y, double yView, double z, + bool onGround, bool isFlying) { + this->x = x; + this->y = y; + this->yView = yView; + this->z = z; + this->onGround = onGround; + hasPos = true; + this->isFlying = isFlying; } -void MovePlayerPacket::PosRot::write(DataOutputStream *dos) //throws IOException +void MovePlayerPacket::Pos::read(DataInputStream* dis) // throws IOException { - dos->writeDouble(x); - dos->writeDouble(y); - dos->writeDouble(yView); - dos->writeDouble(z); - dos->writeFloat(yRot); - dos->writeFloat(xRot); - MovePlayerPacket::write(dos); + x = dis->readDouble(); + y = dis->readDouble(); + yView = dis->readDouble(); + z = dis->readDouble(); + MovePlayerPacket::read(dis); } -int MovePlayerPacket::PosRot::getEstimatedSize() +void MovePlayerPacket::Pos::write(DataOutputStream* dos) // throws IOException { - return 8 * 5 + 1; + dos->writeDouble(x); + dos->writeDouble(y); + dos->writeDouble(yView); + dos->writeDouble(z); + MovePlayerPacket::write(dos); } -MovePlayerPacket::Pos::Pos() -{ - hasPos = true; +int MovePlayerPacket::Pos::getEstimatedSize() { return 8 * 4 + 1; } + +MovePlayerPacket::Rot::Rot() { hasRot = true; } + +MovePlayerPacket::Rot::Rot(float yRot, float xRot, bool onGround, + bool isFlying) { + this->yRot = yRot; + this->xRot = xRot; + this->onGround = onGround; + hasRot = true; + this->isFlying = isFlying; } -MovePlayerPacket::Pos::Pos(double x, double y, double yView, double z, bool onGround, bool isFlying) +void MovePlayerPacket::Rot::read(DataInputStream* dis) // throws IOException { - this->x = x; - this->y = y; - this->yView = yView; - this->z = z; - this->onGround = onGround; - hasPos = true; - this->isFlying = isFlying; + yRot = dis->readFloat(); + xRot = dis->readFloat(); + MovePlayerPacket::read(dis); } -void MovePlayerPacket::Pos::read(DataInputStream *dis) //throws IOException +void MovePlayerPacket::Rot::write(DataOutputStream* dos) // throws IOException { - x = dis->readDouble(); - y = dis->readDouble(); - yView = dis->readDouble(); - z = dis->readDouble(); - MovePlayerPacket::read(dis); + dos->writeFloat(yRot); + dos->writeFloat(xRot); + MovePlayerPacket::write(dos); } -void MovePlayerPacket::Pos::write(DataOutputStream *dos) //throws IOException -{ - dos->writeDouble(x); - dos->writeDouble(y); - dos->writeDouble(yView); - dos->writeDouble(z); - MovePlayerPacket::write(dos); -} - -int MovePlayerPacket::Pos::getEstimatedSize() -{ - return 8 * 4 + 1; -} - -MovePlayerPacket::Rot::Rot() -{ - hasRot = true; -} - -MovePlayerPacket::Rot::Rot(float yRot, float xRot, bool onGround, bool isFlying) -{ - this->yRot = yRot; - this->xRot = xRot; - this->onGround = onGround; - hasRot = true; - this->isFlying = isFlying; -} - -void MovePlayerPacket::Rot::read(DataInputStream *dis) //throws IOException -{ - yRot = dis->readFloat(); - xRot = dis->readFloat(); - MovePlayerPacket::read(dis); -} - -void MovePlayerPacket::Rot::write(DataOutputStream *dos) //throws IOException -{ - dos->writeFloat(yRot); - dos->writeFloat(xRot); - MovePlayerPacket::write(dos); -} - -int MovePlayerPacket::Rot::getEstimatedSize() -{ - return 8 + 1; -} +int MovePlayerPacket::Rot::getEstimatedSize() { return 8 + 1; } diff --git a/Minecraft.World/Network/Packets/MovePlayerPacket.h b/Minecraft.World/Network/Packets/MovePlayerPacket.h index f0f200651..64f2c7baf 100644 --- a/Minecraft.World/Network/Packets/MovePlayerPacket.h +++ b/Minecraft.World/Network/Packets/MovePlayerPacket.h @@ -1,78 +1,83 @@ #pragma once - #include "Packet.h" -class MovePlayerPacket : public Packet, public std::enable_shared_from_this -{ +class MovePlayerPacket : public Packet, + public std::enable_shared_from_this { public: - class PosRot; - class Pos; - class Rot; + class PosRot; + class Pos; + class Rot; - double x, y, z, yView; - float yRot, xRot; - bool onGround; - bool hasPos, hasRot; - bool isFlying; // 4J Added + double x, y, z, yView; + float yRot, xRot; + bool onGround; + bool hasPos, hasRot; + bool isFlying; // 4J Added - MovePlayerPacket(); - MovePlayerPacket(bool onGround, bool isFlying); + MovePlayerPacket(); + MovePlayerPacket(bool onGround, bool isFlying); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new MovePlayerPacket()); } - virtual int getId() { return 10; } + static std::shared_ptr create() { + return std::shared_ptr(new MovePlayerPacket()); + } + virtual int getId() { return 10; } }; -class MovePlayerPacket::PosRot : public MovePlayerPacket -{ +class MovePlayerPacket::PosRot : public MovePlayerPacket { public: - PosRot(); - PosRot(double x, double y, double yView, double z, float yRot, float xRot, bool onGround, bool isFlying); + PosRot(); + PosRot(double x, double y, double yView, double z, float yRot, float xRot, + bool onGround, bool isFlying); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MovePlayerPacket::PosRot()); } - virtual int getId() { return 13; } + static std::shared_ptr create() { + return std::shared_ptr(new MovePlayerPacket::PosRot()); + } + virtual int getId() { return 13; } }; -class MovePlayerPacket::Pos : public MovePlayerPacket -{ +class MovePlayerPacket::Pos : public MovePlayerPacket { public: - Pos(); - Pos(double x, double y, double yView, double z, bool onGround, bool isFlying); + Pos(); + Pos(double x, double y, double yView, double z, bool onGround, + bool isFlying); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MovePlayerPacket::Pos()); } - virtual int getId() { return 11; } - + static std::shared_ptr create() { + return std::shared_ptr(new MovePlayerPacket::Pos()); + } + virtual int getId() { return 11; } }; -class MovePlayerPacket::Rot : public MovePlayerPacket -{ +class MovePlayerPacket::Rot : public MovePlayerPacket { public: - Rot(); - Rot(float yRot, float xRot, bool onGround, bool isFlying); + Rot(); + Rot(float yRot, float xRot, bool onGround, bool isFlying); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new MovePlayerPacket::Rot()); } - virtual int getId() { return 12; } - + static std::shared_ptr create() { + return std::shared_ptr(new MovePlayerPacket::Rot()); + } + virtual int getId() { return 12; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/Packet.cpp b/Minecraft.World/Network/Packets/Packet.cpp index 157602b3f..0043dff62 100644 --- a/Minecraft.World/Network/Packets/Packet.cpp +++ b/Minecraft.World/Network/Packets/Packet.cpp @@ -12,329 +12,411 @@ #include "../../../Minecraft.Client/UI/Gui.h" #endif -void Packet::staticCtor() -{ - //nextPrint = 0; +void Packet::staticCtor() { + // nextPrint = 0; - // 4J - Note that item IDs are now defined in virtual method for each packet type + // 4J - Note that item IDs are now defined in virtual method for each packet + // type - // 4J Stu - The values for canSendToAnyClient may not necessarily be the correct choices - map(0, true, true, true, false, typeid(KeepAlivePacket), KeepAlivePacket::create); - map(1, true, true, true, false, typeid(LoginPacket), LoginPacket::create); - map(2, true, true, true, false, typeid(PreLoginPacket), PreLoginPacket::create); - map(3, true, true, true, false, typeid(ChatPacket), ChatPacket::create); - map(4, true, false, false, true, typeid(SetTimePacket), SetTimePacket::create); - map(5, true, false, false, true, typeid(SetEquippedItemPacket), SetEquippedItemPacket::create); - map(6, true, false, true, true, typeid(SetSpawnPositionPacket), SetSpawnPositionPacket::create); - map(7, false, true, false, false, typeid(InteractPacket), InteractPacket::create); - map(8, true, false, true, true, typeid(SetHealthPacket), SetHealthPacket::create); - map(9, true, true, true, false, typeid(RespawnPacket), RespawnPacket::create); + // 4J Stu - The values for canSendToAnyClient may not necessarily be the + // correct choices + map(0, true, true, true, false, typeid(KeepAlivePacket), + KeepAlivePacket::create); + map(1, true, true, true, false, typeid(LoginPacket), LoginPacket::create); + map(2, true, true, true, false, typeid(PreLoginPacket), + PreLoginPacket::create); + map(3, true, true, true, false, typeid(ChatPacket), ChatPacket::create); + map(4, true, false, false, true, typeid(SetTimePacket), + SetTimePacket::create); + map(5, true, false, false, true, typeid(SetEquippedItemPacket), + SetEquippedItemPacket::create); + map(6, true, false, true, true, typeid(SetSpawnPositionPacket), + SetSpawnPositionPacket::create); + map(7, false, true, false, false, typeid(InteractPacket), + InteractPacket::create); + map(8, true, false, true, true, typeid(SetHealthPacket), + SetHealthPacket::create); + map(9, true, true, true, false, typeid(RespawnPacket), + RespawnPacket::create); - map(10, true, true, true, false, typeid(MovePlayerPacket), MovePlayerPacket::create); - map(11, true, true, true, true, typeid(MovePlayerPacket::Pos), MovePlayerPacket::Pos::create); - map(12, true, true, true, true, typeid(MovePlayerPacket::Rot), MovePlayerPacket::Rot::create); - map(13, true, true, true, true, typeid(MovePlayerPacket::PosRot), MovePlayerPacket::PosRot::create); + map(10, true, true, true, false, typeid(MovePlayerPacket), + MovePlayerPacket::create); + map(11, true, true, true, true, typeid(MovePlayerPacket::Pos), + MovePlayerPacket::Pos::create); + map(12, true, true, true, true, typeid(MovePlayerPacket::Rot), + MovePlayerPacket::Rot::create); + map(13, true, true, true, true, typeid(MovePlayerPacket::PosRot), + MovePlayerPacket::PosRot::create); - map(14, false, true, false, false, typeid(PlayerActionPacket), PlayerActionPacket::create); - map(15, false, true, false, false, typeid(UseItemPacket), UseItemPacket::create); - map(16, false, true, false, false, typeid(SetCarriedItemPacket), SetCarriedItemPacket::create); - // 4J-PB - we need to send to any client for the sleep in bed - //map(17, true, false, false, false, EntityActionAtPositionPacket)); - map(17, true, false, true, false, typeid(EntityActionAtPositionPacket), EntityActionAtPositionPacket::create); - // 4J-PB - we need to send to any client for the wake up from sleeping - //map(18, true, true, false, false, AnimatePacket)); - map(18, true, true, true, false, typeid(AnimatePacket), AnimatePacket::create); - map(19, false, true, false, false, typeid(PlayerCommandPacket), PlayerCommandPacket::create); + map(14, false, true, false, false, typeid(PlayerActionPacket), + PlayerActionPacket::create); + map(15, false, true, false, false, typeid(UseItemPacket), + UseItemPacket::create); + map(16, false, true, false, false, typeid(SetCarriedItemPacket), + SetCarriedItemPacket::create); + // 4J-PB - we need to send to any client for the sleep in bed + // map(17, true, false, false, false, EntityActionAtPositionPacket)); + map(17, true, false, true, false, typeid(EntityActionAtPositionPacket), + EntityActionAtPositionPacket::create); + // 4J-PB - we need to send to any client for the wake up from sleeping + // map(18, true, true, false, false, AnimatePacket)); + map(18, true, true, true, false, typeid(AnimatePacket), + AnimatePacket::create); + map(19, false, true, false, false, typeid(PlayerCommandPacket), + PlayerCommandPacket::create); - map(20, true, false, false, true, typeid(AddPlayerPacket), AddPlayerPacket::create); - map(22, true, false, true, true, typeid(TakeItemEntityPacket), TakeItemEntityPacket::create); - map(23, true, false, false, true, typeid(AddEntityPacket), AddEntityPacket::create); - map(24, true, false, false, true, typeid(AddMobPacket), AddMobPacket::create); - map(25, true, false, false, false, typeid(AddPaintingPacket), AddPaintingPacket::create); - map(26, true, false, false, false, typeid(AddExperienceOrbPacket), AddExperienceOrbPacket::create); // TODO New for 1.8.2 - Needs sendToAny? - //map(27, false, true, false, false, PlayerInputPacket)); - // 4J-PB - needs to go to any player, due to the knockback effect when a played is hit - map(28, true, false, true, true, typeid(SetEntityMotionPacket), SetEntityMotionPacket::create); - map(29, true, false, false, true, typeid(RemoveEntitiesPacket), RemoveEntitiesPacket::create); + map(20, true, false, false, true, typeid(AddPlayerPacket), + AddPlayerPacket::create); + map(22, true, false, true, true, typeid(TakeItemEntityPacket), + TakeItemEntityPacket::create); + map(23, true, false, false, true, typeid(AddEntityPacket), + AddEntityPacket::create); + map(24, true, false, false, true, typeid(AddMobPacket), + AddMobPacket::create); + map(25, true, false, false, false, typeid(AddPaintingPacket), + AddPaintingPacket::create); + map(26, true, false, false, false, typeid(AddExperienceOrbPacket), + AddExperienceOrbPacket::create); // TODO New for 1.8.2 - Needs + // sendToAny? + // map(27, false, true, false, false, PlayerInputPacket)); + // 4J-PB - needs to go to any player, due to the knockback effect when a + // played is hit + map(28, true, false, true, true, typeid(SetEntityMotionPacket), + SetEntityMotionPacket::create); + map(29, true, false, false, true, typeid(RemoveEntitiesPacket), + RemoveEntitiesPacket::create); - map(30, true, false, false, false, typeid(MoveEntityPacket), MoveEntityPacket::create); - map(31, true, false, false, true, typeid(MoveEntityPacket::Pos), MoveEntityPacket::Pos::create); - map(32, true, false, false, true, typeid(MoveEntityPacket::Rot), MoveEntityPacket::Rot::create); - map(33, true, false, false, true, typeid(MoveEntityPacket::PosRot), MoveEntityPacket::PosRot::create); - map(34, true, false, false, true, typeid(TeleportEntityPacket), TeleportEntityPacket::create); - map(35, true, false, false, false, typeid(RotateHeadPacket), RotateHeadPacket::create); + map(30, true, false, false, false, typeid(MoveEntityPacket), + MoveEntityPacket::create); + map(31, true, false, false, true, typeid(MoveEntityPacket::Pos), + MoveEntityPacket::Pos::create); + map(32, true, false, false, true, typeid(MoveEntityPacket::Rot), + MoveEntityPacket::Rot::create); + map(33, true, false, false, true, typeid(MoveEntityPacket::PosRot), + MoveEntityPacket::PosRot::create); + map(34, true, false, false, true, typeid(TeleportEntityPacket), + TeleportEntityPacket::create); + map(35, true, false, false, false, typeid(RotateHeadPacket), + RotateHeadPacket::create); - // 4J - needs to go to any player, to create sound effect when a player is hit - map(38, true, false, true, true, typeid(EntityEventPacket), EntityEventPacket::create); - map(39, true, false, true, false, typeid(SetRidingPacket), SetRidingPacket::create); - map(40, true, false, true, true, typeid(SetEntityDataPacket), SetEntityDataPacket::create); - map(41, true, false, true, false, typeid(UpdateMobEffectPacket), UpdateMobEffectPacket::create); - map(42, true, false, true, false, typeid(RemoveMobEffectPacket), RemoveMobEffectPacket::create); - map(43, true, false, true, false, typeid(SetExperiencePacket), SetExperiencePacket::create); + // 4J - needs to go to any player, to create sound effect when a player is + // hit + map(38, true, false, true, true, typeid(EntityEventPacket), + EntityEventPacket::create); + map(39, true, false, true, false, typeid(SetRidingPacket), + SetRidingPacket::create); + map(40, true, false, true, true, typeid(SetEntityDataPacket), + SetEntityDataPacket::create); + map(41, true, false, true, false, typeid(UpdateMobEffectPacket), + UpdateMobEffectPacket::create); + map(42, true, false, true, false, typeid(RemoveMobEffectPacket), + RemoveMobEffectPacket::create); + map(43, true, false, true, false, typeid(SetExperiencePacket), + SetExperiencePacket::create); - map(50, true, false, true, true, typeid(ChunkVisibilityPacket), ChunkVisibilityPacket::create); - map(51, true, false, true, true, typeid(BlockRegionUpdatePacket), BlockRegionUpdatePacket::create); // Changed to LevelChunkPacket in Java but we aren't using that - map(52, true, false, true, true, typeid(ChunkTilesUpdatePacket), ChunkTilesUpdatePacket::create); - map(53, true, false, true, true, typeid(TileUpdatePacket), TileUpdatePacket::create); - map(54, true, false, true, true, typeid(TileEventPacket), TileEventPacket::create); - map(55, true, false, false, false, typeid(TileDestructionPacket), TileDestructionPacket::create); + map(50, true, false, true, true, typeid(ChunkVisibilityPacket), + ChunkVisibilityPacket::create); + map(51, true, false, true, true, typeid(BlockRegionUpdatePacket), + BlockRegionUpdatePacket::create); // Changed to LevelChunkPacket in + // Java but we aren't using that + map(52, true, false, true, true, typeid(ChunkTilesUpdatePacket), + ChunkTilesUpdatePacket::create); + map(53, true, false, true, true, typeid(TileUpdatePacket), + TileUpdatePacket::create); + map(54, true, false, true, true, typeid(TileEventPacket), + TileEventPacket::create); + map(55, true, false, false, false, typeid(TileDestructionPacket), + TileDestructionPacket::create); - map(60, true, false, true, false, typeid(ExplodePacket), ExplodePacket::create); - map(61, true, false, true, false, typeid(LevelEventPacket), LevelEventPacket::create); - // 4J-PB - don't see the need for this, we can use 61 - map(62, true, false, true, false, typeid(LevelSoundPacket), LevelSoundPacket::create); - //map(62, true, false, true, false, typeid(LevelSoundPacket), LevelSoundPacket::create); + map(60, true, false, true, false, typeid(ExplodePacket), + ExplodePacket::create); + map(61, true, false, true, false, typeid(LevelEventPacket), + LevelEventPacket::create); + // 4J-PB - don't see the need for this, we can use 61 + map(62, true, false, true, false, typeid(LevelSoundPacket), + LevelSoundPacket::create); + // map(62, true, false, true, false, typeid(LevelSoundPacket), + // LevelSoundPacket::create); - map(70, true, false, false, false, typeid(GameEventPacket), GameEventPacket::create); - map(71, true, false, false, false, typeid(AddGlobalEntityPacket), AddGlobalEntityPacket::create); + map(70, true, false, false, false, typeid(GameEventPacket), + GameEventPacket::create); + map(71, true, false, false, false, typeid(AddGlobalEntityPacket), + AddGlobalEntityPacket::create); - map(100, true, false, true, false, typeid(ContainerOpenPacket), ContainerOpenPacket::create); - map(101, true, true, true, false, typeid(ContainerClosePacket), ContainerClosePacket::create); - map(102, false, true, false, false, typeid(ContainerClickPacket), ContainerClickPacket::create); + map(100, true, false, true, false, typeid(ContainerOpenPacket), + ContainerOpenPacket::create); + map(101, true, true, true, false, typeid(ContainerClosePacket), + ContainerClosePacket::create); + map(102, false, true, false, false, typeid(ContainerClickPacket), + ContainerClickPacket::create); #ifndef _CONTENT_PACKAGE - // 4J Stu - We have some debug code that uses this packet to send data back to the server from the client - // We may wish to add this into the real game at some point - map(103, true, true, true, false, typeid(ContainerSetSlotPacket), ContainerSetSlotPacket::create); + // 4J Stu - We have some debug code that uses this packet to send data back + // to the server from the client We may wish to add this into the real game + // at some point + map(103, true, true, true, false, typeid(ContainerSetSlotPacket), + ContainerSetSlotPacket::create); #else - map(103, true, false, true, false, typeid(ContainerSetSlotPacket), ContainerSetSlotPacket::create); + map(103, true, false, true, false, typeid(ContainerSetSlotPacket), + ContainerSetSlotPacket::create); #endif - map(104, true, false, true, false, typeid(ContainerSetContentPacket), ContainerSetContentPacket::create); - map(105, true, false, true, false, typeid(ContainerSetDataPacket), ContainerSetDataPacket::create); - map(106, true, true, true, false, typeid(ContainerAckPacket), ContainerAckPacket::create); - map(107, true, true, true, false, typeid(SetCreativeModeSlotPacket), SetCreativeModeSlotPacket::create); - map(108, false, true, false, false, typeid(ContainerButtonClickPacket), ContainerButtonClickPacket::create); + map(104, true, false, true, false, typeid(ContainerSetContentPacket), + ContainerSetContentPacket::create); + map(105, true, false, true, false, typeid(ContainerSetDataPacket), + ContainerSetDataPacket::create); + map(106, true, true, true, false, typeid(ContainerAckPacket), + ContainerAckPacket::create); + map(107, true, true, true, false, typeid(SetCreativeModeSlotPacket), + SetCreativeModeSlotPacket::create); + map(108, false, true, false, false, typeid(ContainerButtonClickPacket), + ContainerButtonClickPacket::create); - map(130, true, true, true, false, typeid(SignUpdatePacket), SignUpdatePacket::create); - map(131, true, false, true, false, typeid(ComplexItemDataPacket), ComplexItemDataPacket::create); - map(132, true, false, false, false, typeid(TileEntityDataPacket), TileEntityDataPacket::create); + map(130, true, true, true, false, typeid(SignUpdatePacket), + SignUpdatePacket::create); + map(131, true, false, true, false, typeid(ComplexItemDataPacket), + ComplexItemDataPacket::create); + map(132, true, false, false, false, typeid(TileEntityDataPacket), + TileEntityDataPacket::create); - // 4J Added - map(150, false, true, false, false, typeid(CraftItemPacket), CraftItemPacket::create); - map(151, false, true, true, false, typeid(TradeItemPacket), TradeItemPacket::create); - map(152, false, true, false, false, typeid(DebugOptionsPacket), DebugOptionsPacket::create); - map(153, true, true, false, false, typeid(ServerSettingsChangedPacket), ServerSettingsChangedPacket::create); - map(154, true, true, true, false, typeid(TexturePacket), TexturePacket::create); - map(155, true, false, true, true, typeid(ChunkVisibilityAreaPacket), ChunkVisibilityAreaPacket::create); - map(156, true, false, false, true, typeid(UpdateProgressPacket), UpdateProgressPacket::create); - map(157, true, true, true, false, typeid(TextureChangePacket), TextureChangePacket::create); - map(158, true, false, true, false, typeid(UpdateGameRuleProgressPacket), UpdateGameRuleProgressPacket::create); - map(159, false, true, false, false, typeid(KickPlayerPacket), KickPlayerPacket::create); - map(160, true, true, true, false, typeid(TextureAndGeometryPacket), TextureAndGeometryPacket::create); - map(161, true, true, true, false, typeid(TextureAndGeometryChangePacket), TextureAndGeometryChangePacket::create); + // 4J Added + map(150, false, true, false, false, typeid(CraftItemPacket), + CraftItemPacket::create); + map(151, false, true, true, false, typeid(TradeItemPacket), + TradeItemPacket::create); + map(152, false, true, false, false, typeid(DebugOptionsPacket), + DebugOptionsPacket::create); + map(153, true, true, false, false, typeid(ServerSettingsChangedPacket), + ServerSettingsChangedPacket::create); + map(154, true, true, true, false, typeid(TexturePacket), + TexturePacket::create); + map(155, true, false, true, true, typeid(ChunkVisibilityAreaPacket), + ChunkVisibilityAreaPacket::create); + map(156, true, false, false, true, typeid(UpdateProgressPacket), + UpdateProgressPacket::create); + map(157, true, true, true, false, typeid(TextureChangePacket), + TextureChangePacket::create); + map(158, true, false, true, false, typeid(UpdateGameRuleProgressPacket), + UpdateGameRuleProgressPacket::create); + map(159, false, true, false, false, typeid(KickPlayerPacket), + KickPlayerPacket::create); + map(160, true, true, true, false, typeid(TextureAndGeometryPacket), + TextureAndGeometryPacket::create); + map(161, true, true, true, false, typeid(TextureAndGeometryChangePacket), + TextureAndGeometryChangePacket::create); - map(162, true, false, false, false, typeid(MoveEntityPacketSmall), MoveEntityPacketSmall::create); - map(163, true, false, false, true, typeid(MoveEntityPacketSmall::Pos), MoveEntityPacketSmall::Pos::create); - map(164, true, false, false, true, typeid( MoveEntityPacketSmall::Rot), MoveEntityPacketSmall::Rot::create); - map(165, true, false, false, true, typeid(MoveEntityPacketSmall::PosRot), MoveEntityPacketSmall::PosRot::create); - map(166, true, true, false, false, typeid(XZPacket), XZPacket::create); - map(167, false, true, false, false, typeid(GameCommandPacket), GameCommandPacket::create); + map(162, true, false, false, false, typeid(MoveEntityPacketSmall), + MoveEntityPacketSmall::create); + map(163, true, false, false, true, typeid(MoveEntityPacketSmall::Pos), + MoveEntityPacketSmall::Pos::create); + map(164, true, false, false, true, typeid(MoveEntityPacketSmall::Rot), + MoveEntityPacketSmall::Rot::create); + map(165, true, false, false, true, typeid(MoveEntityPacketSmall::PosRot), + MoveEntityPacketSmall::PosRot::create); + map(166, true, true, false, false, typeid(XZPacket), XZPacket::create); + map(167, false, true, false, false, typeid(GameCommandPacket), + GameCommandPacket::create); - map(200, true, false, true, false, typeid(AwardStatPacket), AwardStatPacket::create); - map(201, true, true, false, false, typeid(PlayerInfoPacket), PlayerInfoPacket::create); // TODO New for 1.8.2 - Repurposed by 4J - map(202, true, true, true, false, typeid(PlayerAbilitiesPacket), PlayerAbilitiesPacket::create); - // 4J Stu - These added 1.3.2, but don't think we need them - //map(203, true, true, true, false, ChatAutoCompletePacket.class); - //map(204, false, true, true, false, ClientInformationPacket.class); - map(205, false, true, true, false, typeid(ClientCommandPacket), ClientCommandPacket::create); - map(250, true, true, true, false, typeid(CustomPayloadPacket), CustomPayloadPacket::create); - // 4J Stu - These added 1.3.2, but don't think we need them - //map(252, true, true, SharedKeyPacket.class); - //map(253, true, false, ServerAuthDataPacket.class); - map(254, false, true, false, false, typeid(GetInfoPacket), GetInfoPacket::create); // TODO New for 1.8.2 - Needs sendToAny? - map(255, true, true, true, false, typeid(DisconnectPacket), DisconnectPacket::create); + map(200, true, false, true, false, typeid(AwardStatPacket), + AwardStatPacket::create); + map(201, true, true, false, false, typeid(PlayerInfoPacket), + PlayerInfoPacket::create); // TODO New for 1.8.2 - Repurposed by 4J + map(202, true, true, true, false, typeid(PlayerAbilitiesPacket), + PlayerAbilitiesPacket::create); + // 4J Stu - These added 1.3.2, but don't think we need them + // map(203, true, true, true, false, ChatAutoCompletePacket.class); + // map(204, false, true, true, false, ClientInformationPacket.class); + map(205, false, true, true, false, typeid(ClientCommandPacket), + ClientCommandPacket::create); + map(250, true, true, true, false, typeid(CustomPayloadPacket), + CustomPayloadPacket::create); + // 4J Stu - These added 1.3.2, but don't think we need them + // map(252, true, true, SharedKeyPacket.class); + // map(253, true, false, ServerAuthDataPacket.class); + map(254, false, true, false, false, typeid(GetInfoPacket), + GetInfoPacket::create); // TODO New for 1.8.2 - Needs sendToAny? + map(255, true, true, true, false, typeid(DisconnectPacket), + DisconnectPacket::create); } -IllegalArgumentException::IllegalArgumentException(const std::wstring& information) -{ - this->information = information; +IllegalArgumentException::IllegalArgumentException( + const std::wstring& information) { + this->information = information; } -IOException::IOException(const std::wstring& information) -{ - this->information = information; +IOException::IOException(const std::wstring& information) { + this->information = information; } -RuntimeException::RuntimeException(const std::wstring& /*information*/) -{ -} +RuntimeException::RuntimeException(const std::wstring& /*information*/) {} -Packet::Packet() : createTime( System::currentTimeMillis() ) -{ - shouldDelay = false; +Packet::Packet() : createTime(System::currentTimeMillis()) { + shouldDelay = false; } std::unordered_map Packet::idToCreateMap; -std::unordered_set Packet::clientReceivedPackets = std::unordered_set(); -std::unordered_set Packet::serverReceivedPackets = std::unordered_set(); -std::unordered_set Packet::sendToAnyClientPackets = std::unordered_set(); +std::unordered_set Packet::clientReceivedPackets = + std::unordered_set(); +std::unordered_set Packet::serverReceivedPackets = + std::unordered_set(); +std::unordered_set Packet::sendToAnyClientPackets = + std::unordered_set(); // 4J Added -std::unordered_map Packet::outgoingStatistics = std::unordered_map(); -std::vector Packet::renderableStats = std::vector(); +std::unordered_map Packet::outgoingStatistics = + std::unordered_map(); +std::vector Packet::renderableStats = + std::vector(); int Packet::renderPos = 0; -// sendToAnyClient - true - send to anyone, false - Sends to one person per dimension per machine -void Packet::map(int id, bool receiveOnClient, bool receiveOnServer, bool sendToAnyClient, bool renderStats, const std::type_info& clazz, packetCreateFn createFn) -{ +// sendToAnyClient - true - send to anyone, false - Sends to one person per +// dimension per machine +void Packet::map(int id, bool receiveOnClient, bool receiveOnServer, + bool sendToAnyClient, bool renderStats, + const std::type_info& clazz, packetCreateFn createFn) { #if 0 if (idToClassMap.count(id) > 0) throw new IllegalArgumentException(std::wstring(L"Duplicate packet id:") + _toString(id)); if (classToIdMap.count(clazz) > 0) throw new IllegalArgumentException(L"Duplicate packet class:"); // TODO + clazz); #endif - idToCreateMap.insert( std::unordered_map::value_type(id, createFn) ); + idToCreateMap.insert( + std::unordered_map::value_type(id, createFn)); #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - Packet::PacketStatistics *packetStatistics = new PacketStatistics(id); - outgoingStatistics[id] = packetStatistics; + Packet::PacketStatistics* packetStatistics = new PacketStatistics(id); + outgoingStatistics[id] = packetStatistics; - if(renderStats) - { - renderableStats.push_back( packetStatistics ); - } + if (renderStats) { + renderableStats.push_back(packetStatistics); + } #endif #endif - if (receiveOnClient) - { - clientReceivedPackets.insert(id); - } - if (receiveOnServer) - { - serverReceivedPackets.insert(id); - } - if(sendToAnyClient) - { - sendToAnyClientPackets.insert(id); - } + if (receiveOnClient) { + clientReceivedPackets.insert(id); + } + if (receiveOnServer) { + serverReceivedPackets.insert(id); + } + if (sendToAnyClient) { + sendToAnyClientPackets.insert(id); + } } // 4J Added to record data for outgoing packets -void Packet::recordOutgoingPacket(std::shared_ptr packet) -{ +void Packet::recordOutgoingPacket(std::shared_ptr packet) { #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - AUTO_VAR(it, outgoingStatistics.find(packet->getId())); + AUTO_VAR(it, outgoingStatistics.find(packet->getId())); - if( it == outgoingStatistics.end() ) - { - Packet::PacketStatistics *packetStatistics = new PacketStatistics(packet->getId()); - outgoingStatistics[packet->getId()] = packetStatistics; - packetStatistics->addPacket(packet->getEstimatedSize()); - } - else - { - it->second->addPacket(packet->getEstimatedSize()); - } + if (it == outgoingStatistics.end()) { + Packet::PacketStatistics* packetStatistics = + new PacketStatistics(packet->getId()); + outgoingStatistics[packet->getId()] = packetStatistics; + packetStatistics->addPacket(packet->getEstimatedSize()); + } else { + it->second->addPacket(packet->getEstimatedSize()); + } #endif #endif } -void Packet::renderPacketStats(int id) -{ - AUTO_VAR(it, outgoingStatistics.find(id)); +void Packet::renderPacketStats(int id) { + AUTO_VAR(it, outgoingStatistics.find(id)); - if( it != outgoingStatistics.end() ) - { - it->second->renderStats(); - } + if (it != outgoingStatistics.end()) { + it->second->renderStats(); + } } -void Packet::renderAllPacketStats() -{ +void Packet::renderAllPacketStats() { #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->gui->renderStackedGraph(Packet::renderPos, 512, renderableStats.size(), &Packet::getIndexedStatValue ); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->gui->renderStackedGraph(Packet::renderPos, 512, + renderableStats.size(), + &Packet::getIndexedStatValue); - renderAllPacketStatsKey(); + renderAllPacketStatsKey(); - Packet::renderPos++; - Packet::renderPos%=511; + Packet::renderPos++; + Packet::renderPos %= 511; #endif #endif } -void Packet::renderAllPacketStatsKey() -{ -#ifndef _CONTENT_PACKAGE +void Packet::renderAllPacketStatsKey() { +#ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - Minecraft *pMinecraft = Minecraft::GetInstance(); - int total = Packet::renderableStats.size(); - for(unsigned int i = 0; i < total; ++i) - { - Packet::PacketStatistics *stat = Packet::renderableStats[i]; - float vary = (float)i/total; - int fColour = floor(vary * 0xffffff); + Minecraft* pMinecraft = Minecraft::GetInstance(); + int total = Packet::renderableStats.size(); + for (unsigned int i = 0; i < total; ++i) { + Packet::PacketStatistics* stat = Packet::renderableStats[i]; + float vary = (float)i / total; + int fColour = floor(vary * 0xffffff); - int colour = 0xff000000 + fColour; - pMinecraft->gui->drawString( pMinecraft->font, stat->getLegendString(), 900, 30 + (10 * i), colour); - } + int colour = 0xff000000 + fColour; + pMinecraft->gui->drawString(pMinecraft->font, stat->getLegendString(), + 900, 30 + (10 * i), colour); + } #endif #endif } -__int64 Packet::getIndexedStatValue(unsigned int samplePos, unsigned int renderableId) -{ - __int64 val = 0; +__int64 Packet::getIndexedStatValue(unsigned int samplePos, + unsigned int renderableId) { + __int64 val = 0; #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - val = renderableStats[renderableId]->getCountSample(samplePos); + val = renderableStats[renderableId]->getCountSample(samplePos); #endif #endif - return val; + return val; } - -std::shared_ptr Packet::getPacket(int id) -{ - // 4J - removed try/catch - // try - // { - return idToCreateMap[id](); - // } - // catch (exception e) - // { - // // TODO 4J JEV print stack trace, newInstance doesnt throw an exception in c++ yet. - // printf("Skipping packet with id %d" , id); - // return NULL; - // } +std::shared_ptr Packet::getPacket(int id) { + // 4J - removed try/catch + // try + // { + return idToCreateMap[id](); + // } + // catch (exception e) + // { + // // TODO 4J JEV print stack trace, newInstance doesnt throw an + //exception in c++ yet. + // printf("Skipping packet with id %d" , id); + // return NULL; + // } } -void Packet::writeBytes(DataOutputStream *dataoutputstream, byteArray bytes) -{ - dataoutputstream->writeShort(bytes.length); - dataoutputstream->write(bytes); +void Packet::writeBytes(DataOutputStream* dataoutputstream, byteArray bytes) { + dataoutputstream->writeShort(bytes.length); + dataoutputstream->write(bytes); } -byteArray Packet::readBytes(DataInputStream *datainputstream) -{ - int size = datainputstream->readShort(); - if (size < 0) - { - app.DebugPrintf("Key was smaller than nothing! Weird key!"); +byteArray Packet::readBytes(DataInputStream* datainputstream) { + int size = datainputstream->readShort(); + if (size < 0) { + app.DebugPrintf("Key was smaller than nothing! Weird key!"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - return byteArray(); - //throw new IOException("Key was smaller than nothing! Weird key!"); - } + return byteArray(); + // throw new IOException("Key was smaller than nothing! Weird key!"); + } - byteArray bytes(size); - datainputstream->read(bytes); + byteArray bytes(size); + datainputstream->read(bytes); - return bytes; + return bytes; } +bool Packet::canSendToAnyClient(std::shared_ptr packet) { + int packetId = packet->getId(); -bool Packet::canSendToAnyClient(std::shared_ptr packet) -{ - int packetId = packet->getId(); - - return sendToAnyClientPackets.count(packetId) != 0; + return sendToAnyClientPackets.count(packetId) != 0; } // 4J - now a pure virtual method @@ -345,99 +427,119 @@ return id; } */ -std::unordered_map Packet::statistics = std::unordered_map(); +std::unordered_map Packet::statistics = + std::unordered_map(); -//int Packet::nextPrint = 0; +// int Packet::nextPrint = 0; -std::shared_ptr Packet::readPacket(DataInputStream *dis, bool isServer) // throws IOException TODO 4J JEV, should this declare a throws? +std::shared_ptr Packet::readPacket( + DataInputStream* dis, bool isServer) // throws IOException TODO 4J JEV, + // should this declare a throws? { - // N packet ID - static int s_clientPktHistory[64]; - static int s_clientPktIdx = 0; - static int s_serverPktHistory[64]; - static int s_serverPktIdx = 0; - static bool s_clientDesyncLogged = false; - static bool s_serverDesyncLogged = false; + // N packet ID + static int s_clientPktHistory[64]; + static int s_clientPktIdx = 0; + static int s_serverPktHistory[64]; + static int s_serverPktIdx = 0; + static bool s_clientDesyncLogged = false; + static bool s_serverDesyncLogged = false; - int id = 0; - std::shared_ptr packet = nullptr; + int id = 0; + std::shared_ptr packet = nullptr; - // 4J - removed try/catch - // try - // { - id = dis->read(); - if (id == -1) return nullptr; + // 4J - removed try/catch + // try + // { + id = dis->read(); + if (id == -1) return nullptr; - if ((isServer && serverReceivedPackets.find(id) == serverReceivedPackets.end()) || (!isServer && clientReceivedPackets.find(id) == clientReceivedPackets.end())) - { - int *history = isServer ? s_serverPktHistory : s_clientPktHistory; - int idx = isServer ? s_serverPktIdx : s_clientPktIdx; - bool &logged = isServer ? s_serverDesyncLogged : s_clientDesyncLogged; - - fprintf(stderr, "[PKT] Bad packet id %d (0x%x) isServer=%d\n", id, id, isServer); - if (!logged) { - logged = true; - fprintf(stderr, "[PKT] === PACKET HISTORY (last %d, newest last) ===\n", 64); - for (int i = 0; i < 64; i++) { - int h = history[(idx + i) % 64]; - if (h != 0) fprintf(stderr, "[PKT] pkt %d (0x%x)\n", h, h); - } - fprintf(stderr, "[PKT] === END HISTORY ===\n"); - } - __debugbreak(); - //assert(false); - // Close the stream to prevent further reads on a desynced stream - dis->close(); - return nullptr; - // throw new IOException(std::wstring(L"Bad packet id ") + _toString(id)); - } + if ((isServer && + serverReceivedPackets.find(id) == serverReceivedPackets.end()) || + (!isServer && + clientReceivedPackets.find(id) == clientReceivedPackets.end())) { + int* history = isServer ? s_serverPktHistory : s_clientPktHistory; + int idx = isServer ? s_serverPktIdx : s_clientPktIdx; + bool& logged = isServer ? s_serverDesyncLogged : s_clientDesyncLogged; - // Record successfully read packet ID - if (isServer) { s_serverPktHistory[s_serverPktIdx % 64] = id; s_serverPktIdx++; } - else { s_clientPktHistory[s_clientPktIdx % 64] = id; s_clientPktIdx++; } + fprintf(stderr, "[PKT] Bad packet id %d (0x%x) isServer=%d\n", id, id, + isServer); + if (!logged) { + logged = true; + fprintf(stderr, + "[PKT] === PACKET HISTORY (last %d, newest last) ===\n", + 64); + for (int i = 0; i < 64; i++) { + int h = history[(idx + i) % 64]; + if (h != 0) fprintf(stderr, "[PKT] pkt %d (0x%x)\n", h, h); + } + fprintf(stderr, "[PKT] === END HISTORY ===\n"); + } + __debugbreak(); + // assert(false); + // Close the stream to prevent further reads on a desynced stream + dis->close(); + return nullptr; + // throw new IOException(std::wstring(L"Bad packet id ") + + // _toString(id)); + } - packet = getPacket(id); - if (packet == NULL) { fprintf(stderr, "[PKT] getPacket(%d) returned NULL\n", id); return nullptr; } - - packet->read(dis); - // } - // catch (EOFException e) - // { - // // reached end of stream - // OutputDebugString("Reached end of stream"); - // return NULL; - // } + // Record successfully read packet ID + if (isServer) { + s_serverPktHistory[s_serverPktIdx % 64] = id; + s_serverPktIdx++; + } else { + s_clientPktHistory[s_clientPktIdx % 64] = id; + s_clientPktIdx++; + } - // 4J - Don't bother tracking stats in a content package - // 4J Stu - This changes a bit in 1.0.1, but we don't really use it so stick with what we have + packet = getPacket(id); + if (packet == NULL) { + fprintf(stderr, "[PKT] getPacket(%d) returned NULL\n", id); + return nullptr; + } + + packet->read(dis); + // } + // catch (EOFException e) + // { + // // reached end of stream + // OutputDebugString("Reached end of stream"); + // return NULL; + // } + + // 4J - Don't bother tracking stats in a content package + // 4J Stu - This changes a bit in 1.0.1, but we don't really use it so stick + // with what we have #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - AUTO_VAR(it, statistics.find(id)); + AUTO_VAR(it, statistics.find(id)); - if( it == statistics.end() ) - { - Packet::PacketStatistics *packetStatistics = new PacketStatistics(id); - statistics[id] = packetStatistics; - packetStatistics->addPacket(packet->getEstimatedSize()); - } - else - { - it->second->addPacket(packet->getEstimatedSize()); - } + if (it == statistics.end()) { + Packet::PacketStatistics* packetStatistics = new PacketStatistics(id); + statistics[id] = packetStatistics; + packetStatistics->addPacket(packet->getEstimatedSize()); + } else { + it->second->addPacket(packet->getEstimatedSize()); + } #endif #endif - return packet; + return packet; } -void Packet::writePacket(std::shared_ptr packet, DataOutputStream *dos) // throws IOException TODO 4J JEV, should this declare a throws? +void Packet::writePacket( + std::shared_ptr packet, + DataOutputStream* + dos) // throws IOException TODO 4J JEV, should this declare a throws? { - //app.DebugPrintf("Writing packet %d\n", packet->getId()); - dos->write(packet->getId()); - packet->write(dos); + // app.DebugPrintf("Writing packet %d\n", packet->getId()); + dos->write(packet->getId()); + packet->write(dos); } -void Packet::writeUtf(const std::wstring& value, DataOutputStream *dos) // throws IOException TODO 4J JEV, should this declare a throws? +void Packet::writeUtf(const std::wstring& value, + DataOutputStream* dos) // throws IOException TODO 4J JEV, + // should this declare a throws? { #if 0 if (value.length() > Short::MAX_VALUE) @@ -446,180 +548,159 @@ void Packet::writeUtf(const std::wstring& value, DataOutputStream *dos) // throw } #endif - dos->writeShort((short)value.length()); - dos->writeChars(value); + dos->writeShort((short)value.length()); + dos->writeChars(value); } -std::wstring Packet::readUtf(DataInputStream *dis, int maxLength) // throws IOException TODO 4J JEV, should this declare a throws? +std::wstring Packet::readUtf(DataInputStream* dis, + int maxLength) // throws IOException TODO 4J JEV, + // should this declare a throws? { + short stringLength = dis->readShort(); + if (stringLength > maxLength) { + fprintf(stderr, + "[PKT] readUtf: string length %d > max %d (stream desync?)\n", + stringLength, maxLength); + return L""; + } + if (stringLength < 0) { + fprintf(stderr, + "[PKT] readUtf: negative string length %d (stream desync?)\n", + stringLength); + return L""; + } - short stringLength = dis->readShort(); - if (stringLength > maxLength) - { - fprintf(stderr, "[PKT] readUtf: string length %d > max %d (stream desync?)\n", stringLength, maxLength); - return L""; - } - if (stringLength < 0) - { - fprintf(stderr, "[PKT] readUtf: negative string length %d (stream desync?)\n", stringLength); - return L""; - } + std::wstring builder = L""; + for (int i = 0; i < stringLength; i++) { + wchar_t rc = dis->readChar(); + builder.push_back(rc); + } - std::wstring builder = L""; - for (int i = 0; i < stringLength; i++) - { - wchar_t rc = dis->readChar(); - builder.push_back( rc ); - } - - return builder; + return builder; } -void Packet::PacketStatistics::addPacket(int bytes) -{ - if(count == 0) - { - firstSampleTime = System::currentTimeMillis(); - } - count++; - totalSize += bytes; +void Packet::PacketStatistics::addPacket(int bytes) { + if (count == 0) { + firstSampleTime = System::currentTimeMillis(); + } + count++; + totalSize += bytes; - // 4J Added - countSamples[samplesPos & (512 - 1)]++; - sizeSamples[samplesPos & (512 - 1)] += (unsigned int) bytes; + // 4J Added + countSamples[samplesPos & (512 - 1)]++; + sizeSamples[samplesPos & (512 - 1)] += (unsigned int)bytes; } -int Packet::PacketStatistics::getCount() -{ - return count; +int Packet::PacketStatistics::getCount() { return count; } + +double Packet::PacketStatistics::getAverageSize() { + if (count == 0) { + return 0; + } + return (double)totalSize / count; } -double Packet::PacketStatistics::getAverageSize() -{ - if (count == 0) - { - return 0; - } - return (double) totalSize / count; -} - -void Packet::PacketStatistics::renderStats( ) -{ +void Packet::PacketStatistics::renderStats() { #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - samplesPos++; + samplesPos++; - countSamples[samplesPos & (512 - 1)] = 0; - sizeSamples[samplesPos & (512 - 1)] = 0; + countSamples[samplesPos & (512 - 1)] = 0; + sizeSamples[samplesPos & (512 - 1)] = 0; - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->gui->renderGraph(512, samplesPos, countSamples, 1, 10, sizeSamples, 1, 50); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->gui->renderGraph(512, samplesPos, countSamples, 1, 10, + sizeSamples, 1, 50); #endif #endif } -__int64 Packet::PacketStatistics::getCountSample(int samplePos) -{ - if(samplePos == 511) - { - samplesPos++; - countSamples[samplesPos & (512 - 1)] = 0; - sizeSamples[samplesPos & (512 - 1)] = 0; - } +__int64 Packet::PacketStatistics::getCountSample(int samplePos) { + if (samplePos == 511) { + samplesPos++; + countSamples[samplesPos & (512 - 1)] = 0; + sizeSamples[samplesPos & (512 - 1)] = 0; + } - return countSamples[samplePos] * 10; + return countSamples[samplePos] * 10; } -std::wstring Packet::PacketStatistics::getLegendString() -{ - static wchar_t string[128]; - double bps = 0.0; - if(firstSampleTime > 0) - { - float timeDiff = ((System::currentTimeMillis() - firstSampleTime)/1000); - if(timeDiff > 0) bps = totalSize / timeDiff; - } - swprintf(string, 128, L"id: %d , packets: %d , total: %d , bytes: %d, total: %d, %f Bps", id, countSamples[(samplesPos - 1) & (512 - 1)], count, sizeSamples[(samplesPos - 1) & (512 - 1)], totalSize, bps ); - return string; +std::wstring Packet::PacketStatistics::getLegendString() { + static wchar_t string[128]; + double bps = 0.0; + if (firstSampleTime > 0) { + float timeDiff = + ((System::currentTimeMillis() - firstSampleTime) / 1000); + if (timeDiff > 0) bps = totalSize / timeDiff; + } + swprintf(string, 128, + L"id: %d , packets: %d , total: %d , bytes: %d, total: %d, %f Bps", + id, countSamples[(samplesPos - 1) & (512 - 1)], count, + sizeSamples[(samplesPos - 1) & (512 - 1)], totalSize, bps); + return string; } -bool Packet::canBeInvalidated() -{ - return false; -} +bool Packet::canBeInvalidated() { return false; } -bool Packet::isInvalidatedBy(std::shared_ptr packet) -{ - return false; -} +bool Packet::isInvalidatedBy(std::shared_ptr packet) { return false; } -bool Packet::isAync() -{ - return false; -} +bool Packet::isAync() { return false; } // 4J Stu - Brought these functions forward for enchanting/game rules -std::shared_ptr Packet::readItem(DataInputStream *dis) -{ - std::shared_ptr item = nullptr; - int id = dis->readShort(); - if (id >= 0) - { - int count = dis->readByte(); - int damage = dis->readShort(); +std::shared_ptr Packet::readItem(DataInputStream* dis) { + std::shared_ptr item = nullptr; + int id = dis->readShort(); + if (id >= 0) { + int count = dis->readByte(); + int damage = dis->readShort(); - item = std::shared_ptr( new ItemInstance(id, count, damage) ); - // 4J Stu - Always read/write the tag - //if (Item.items[id].canBeDepleted() || Item.items[id].shouldOverrideMultiplayerNBT()) - { - item->tag = readNbt(dis); - } - } + item = + std::shared_ptr(new ItemInstance(id, count, damage)); + // 4J Stu - Always read/write the tag + // if (Item.items[id].canBeDepleted() || + // Item.items[id].shouldOverrideMultiplayerNBT()) + { + item->tag = readNbt(dis); + } + } - return item; + return item; } -void Packet::writeItem(std::shared_ptr item, DataOutputStream *dos) -{ - if (item == NULL) - { - dos->writeShort(-1); - } - else - { - dos->writeShort(item->id); - dos->writeByte(item->count); - dos->writeShort(item->getAuxValue()); - // 4J Stu - Always read/write the tag - //if (item.getItem().canBeDepleted() || item.getItem().shouldOverrideMultiplayerNBT()) - { - writeNbt(item->tag, dos); - } - } +void Packet::writeItem(std::shared_ptr item, + DataOutputStream* dos) { + if (item == NULL) { + dos->writeShort(-1); + } else { + dos->writeShort(item->id); + dos->writeByte(item->count); + dos->writeShort(item->getAuxValue()); + // 4J Stu - Always read/write the tag + // if (item.getItem().canBeDepleted() || + // item.getItem().shouldOverrideMultiplayerNBT()) + { + writeNbt(item->tag, dos); + } + } } -CompoundTag *Packet::readNbt(DataInputStream *dis) -{ - int size = dis->readShort(); - if (size < 0) return NULL; - byteArray buff(size); - dis->readFully(buff); - CompoundTag *result = (CompoundTag *) NbtIo::decompress(buff); - delete [] buff.data; - return result; +CompoundTag* Packet::readNbt(DataInputStream* dis) { + int size = dis->readShort(); + if (size < 0) return NULL; + byteArray buff(size); + dis->readFully(buff); + CompoundTag* result = (CompoundTag*)NbtIo::decompress(buff); + delete[] buff.data; + return result; } -void Packet::writeNbt(CompoundTag *tag, DataOutputStream *dos) -{ - if (tag == NULL) - { - dos->writeShort(-1); - } - else - { - byteArray buff = NbtIo::compress(tag); - dos->writeShort((short) buff.length); - dos->write(buff); - delete [] buff.data; - } +void Packet::writeNbt(CompoundTag* tag, DataOutputStream* dos) { + if (tag == NULL) { + dos->writeShort(-1); + } else { + byteArray buff = NbtIo::compress(tag); + dos->writeShort((short)buff.length); + dos->write(buff); + delete[] buff.data; + } } diff --git a/Minecraft.World/Network/Packets/Packet.h b/Minecraft.World/Network/Packets/Packet.h index 20a3bfb04..2efa9ff70 100644 --- a/Minecraft.World/Network/Packets/Packet.h +++ b/Minecraft.World/Network/Packets/Packet.h @@ -12,103 +12,123 @@ class Packet; typedef std::shared_ptr (*packetCreateFn)(); -class Packet -{ +class Packet { public: - class PacketStatistics - { - private: - int count; - int totalSize; + class PacketStatistics { + private: + int count; + int totalSize; - // 4J Added - __int64 countSamples[512]; - __int64 sizeSamples[512]; - int samplesPos; - __int64 firstSampleTime; + // 4J Added + __int64 countSamples[512]; + __int64 sizeSamples[512]; + int samplesPos; + __int64 firstSampleTime; + public: + const int id; - public: - const int id; + public: + PacketStatistics(int id) + : count(0), + totalSize(0), + samplesPos(0), + firstSampleTime(0), + id(id) { + countSamples[0] = 0; + sizeSamples[0] = 0; + } + void addPacket(int bytes); + int getCount(); + double getAverageSize(); - public: - PacketStatistics(int id) : count( 0 ), totalSize( 0 ), samplesPos( 0 ), firstSampleTime( 0 ), id( id ) { countSamples[0] = 0; sizeSamples[0] = 0; } - void addPacket(int bytes); - int getCount(); - double getAverageSize(); + // 4J Added + void renderStats(); + __int64 getCountSample(int samplePos); + std::wstring getLegendString(); + }; - // 4J Added - void renderStats(); - __int64 getCountSample(int samplePos); - std::wstring getLegendString(); - }; - - // 4J JEV, replaces the static blocks. - static void staticCtor(); + // 4J JEV, replaces the static blocks. + static void staticCtor(); public: - static std::unordered_map idToCreateMap; // IntHashMap in 1.8.2 ... needed? // Made public in 1.0.1 + static std::unordered_map + idToCreateMap; // IntHashMap in 1.8.2 ... needed? // Made public + // in 1.0.1 - static std::unordered_set clientReceivedPackets; - static std::unordered_set serverReceivedPackets; - static std::unordered_set sendToAnyClientPackets; + static std::unordered_set clientReceivedPackets; + static std::unordered_set serverReceivedPackets; + static std::unordered_set sendToAnyClientPackets; - // 4J Stu - Added the sendToAnyClient param so we can limit some packets to be only sent to one player on a system - // 4J Stu - Added renderStats param for use in debugging - static void map(int id, bool receiveOnClient, bool receiveOnServer, bool sendToAnyClient, bool renderStats, const std::type_info& clazz, packetCreateFn ); + // 4J Stu - Added the sendToAnyClient param so we can limit some packets to + // be only sent to one player on a system 4J Stu - Added renderStats param + // for use in debugging + static void map(int id, bool receiveOnClient, bool receiveOnServer, + bool sendToAnyClient, bool renderStats, + const std::type_info& clazz, packetCreateFn); public: - const __int64 createTime; + const __int64 createTime; - Packet(); - virtual ~Packet(){} + Packet(); + virtual ~Packet() {} - static std::shared_ptr getPacket(int id); + static std::shared_ptr getPacket(int id); - // 4J Added - static bool canSendToAnyClient(std::shared_ptr packet); + // 4J Added + static bool canSendToAnyClient(std::shared_ptr packet); - static void writeBytes(DataOutputStream *dataoutputstream, byteArray bytes); - static byteArray readBytes(DataInputStream *datainputstream); + static void writeBytes(DataOutputStream* dataoutputstream, byteArray bytes); + static byteArray readBytes(DataInputStream* datainputstream); - virtual int getId() = 0; + virtual int getId() = 0; - bool shouldDelay; + bool shouldDelay; private: - // 4J Added to track stats for packets that are going out via QNet - static std::unordered_map outgoingStatistics; // IntHashMap in 1.8.2 ... needed? - static std::vector renderableStats; - static int renderPos; -public: - static void recordOutgoingPacket(std::shared_ptr packet); - static void renderPacketStats(int id); - static void renderAllPacketStats(); - static void renderAllPacketStatsKey(); - static __int64 getIndexedStatValue(unsigned int samplePos, unsigned int renderableId); - -private : - static std::unordered_map statistics; - //static int nextPrint; + // 4J Added to track stats for packets that are going out via QNet + static std::unordered_map + outgoingStatistics; // IntHashMap in 1.8.2 ... needed? + static std::vector renderableStats; + static int renderPos; public: - static std::shared_ptr readPacket(DataInputStream *dis, bool isServer); - static void writePacket(std::shared_ptr packet, DataOutputStream *dos); - static void writeUtf(const std::wstring& value, DataOutputStream *dos); - static std::wstring readUtf(DataInputStream *dis, int maxLength); - virtual void read(DataInputStream *dis) = 0; // throws IOException = 0; TODO 4J JEV, should this declare a throws? - virtual void write(DataOutputStream *dos) = 0; // throws IOException = 0; TODO 4J JEV, should this declare a throws? - virtual void handle(PacketListener *listener) = 0; - virtual int getEstimatedSize() = 0; - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + static void recordOutgoingPacket(std::shared_ptr packet); + static void renderPacketStats(int id); + static void renderAllPacketStats(); + static void renderAllPacketStatsKey(); + static __int64 getIndexedStatValue(unsigned int samplePos, + unsigned int renderableId); - // 4J Stu - Brought these functions forward for enchanting/game rules - static std::shared_ptr readItem(DataInputStream *dis); - static void writeItem(std::shared_ptr item, DataOutputStream *dos); - static CompoundTag *readNbt(DataInputStream *dis); +private: + static std::unordered_map statistics; + // static int nextPrint; + +public: + static std::shared_ptr readPacket(DataInputStream* dis, + bool isServer); + static void writePacket(std::shared_ptr packet, + DataOutputStream* dos); + static void writeUtf(const std::wstring& value, DataOutputStream* dos); + static std::wstring readUtf(DataInputStream* dis, int maxLength); + virtual void read( + DataInputStream* dis) = 0; // throws IOException = 0; TODO 4J JEV, + // should this declare a throws? + virtual void write( + DataOutputStream* dos) = 0; // throws IOException = 0; TODO 4J JEV, + // should this declare a throws? + virtual void handle(PacketListener* listener) = 0; + virtual int getEstimatedSize() = 0; + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); + + // 4J Stu - Brought these functions forward for enchanting/game rules + static std::shared_ptr readItem(DataInputStream* dis); + static void writeItem(std::shared_ptr item, + DataOutputStream* dos); + static CompoundTag* readNbt(DataInputStream* dis); protected: - static void writeNbt(CompoundTag *tag, DataOutputStream *dos); + static void writeNbt(CompoundTag* tag, DataOutputStream* dos); }; diff --git a/Minecraft.World/Network/Packets/PacketListener.cpp b/Minecraft.World/Network/Packets/PacketListener.cpp index 299f4ed84..a6dd4edc7 100644 --- a/Minecraft.World/Network/Packets/PacketListener.cpp +++ b/Minecraft.World/Network/Packets/PacketListener.cpp @@ -2,450 +2,420 @@ #include "../../Headers/net.minecraft.network.packet.h" #include "PacketListener.h" -void PacketListener::handleBlockRegionUpdate(std::shared_ptr packet) -{ +void PacketListener::handleBlockRegionUpdate( + std::shared_ptr packet) {} + +void PacketListener::onUnhandledPacket(std::shared_ptr packet) {} + +void PacketListener::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) {} + +void PacketListener::handleDisconnect( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::onUnhandledPacket(std::shared_ptr packet) -{ +void PacketListener::handleLogin(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ +void PacketListener::handleMovePlayer( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleDisconnect(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleChunkTilesUpdate( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleLogin(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handlePlayerAction( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleMovePlayer(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTileUpdate( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleChunkTilesUpdate(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleChunkVisibility( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handlePlayerAction(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAddPlayer(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTileUpdate(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleMoveEntity( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleChunkVisibility(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleMoveEntitySmall( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAddPlayer(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTeleportEntity( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleMoveEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleUseItem(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleMoveEntitySmall(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetCarriedItem( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTeleportEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleRemoveEntity( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleUseItem(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTakeItemEntity( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetCarriedItem(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleChat(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleRemoveEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAddEntity(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTakeItemEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAnimate(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleChat(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handlePlayerCommand( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAddEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handlePreLogin(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAnimate(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAddMob(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handlePlayerCommand(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetTime(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handlePreLogin(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetSpawn( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAddMob(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetEntityMotion( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetTime(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetEntityData( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetSpawn(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleRidePacket(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetEntityMotion(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleInteract(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetEntityData(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleEntityEvent( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleRidePacket(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetHealth(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleInteract(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleRespawn(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleEntityEvent(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTexture(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetHealth(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTextureAndGeometry( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleRespawn(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleExplosion(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTexture(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerOpen( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTextureAndGeometry(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerClose( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleExplosion(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerClick( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerOpen(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerSetSlot( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerClose(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerContent( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerClick(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSignUpdate( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerSetSlot(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerSetData( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerContent(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleSetEquippedItem( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSignUpdate(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleContainerAck( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerSetData(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAddPainting( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleSetEquippedItem(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTileEvent(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleContainerAck(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAwardStat(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAddPainting(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleEntityActionAtPosition( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTileEvent(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handlePlayerInput( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleAwardStat(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleGameEvent(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleEntityActionAtPosition(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleAddGlobalEntity( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handlePlayerInput(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleComplexItemData( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleGameEvent(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); -} - -void PacketListener::handleAddGlobalEntity(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); -} - -void PacketListener::handleComplexItemData(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); -} - -void PacketListener::handleLevelEvent(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleLevelEvent( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } // 1.8.2 -void PacketListener::handleGetInfo(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleGetInfo(std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleUpdateMobEffect(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleUpdateMobEffect( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleRemoveMobEffect(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleRemoveMobEffect( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handlePlayerInfo(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handlePlayerInfo( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleKeepAlive(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleKeepAlive(std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleSetExperience(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleSetExperience( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleSetCreativeModeSlot(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleSetCreativeModeSlot( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleAddExperienceOrb(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleAddExperienceOrb( + std::shared_ptr packet) { + onUnhandledPacket(packet); } // 1.0.1 -void PacketListener::handleContainerButtonClick(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleContainerButtonClick( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleTileEntityData(std::shared_ptr tileEntityDataPacket) -{ - onUnhandledPacket(tileEntityDataPacket); +void PacketListener::handleTileEntityData( + std::shared_ptr tileEntityDataPacket) { + onUnhandledPacket(tileEntityDataPacket); } // 1.1 -void PacketListener::handleCustomPayload(std::shared_ptr customPayloadPacket) -{ - onUnhandledPacket(customPayloadPacket); +void PacketListener::handleCustomPayload( + std::shared_ptr customPayloadPacket) { + onUnhandledPacket(customPayloadPacket); } // 1.2.3 -void PacketListener::handleRotateMob(std::shared_ptr rotateMobPacket) -{ - onUnhandledPacket(rotateMobPacket); +void PacketListener::handleRotateMob( + std::shared_ptr rotateMobPacket) { + onUnhandledPacket(rotateMobPacket); } // 1.3.2 -void PacketListener::handleClientProtocolPacket(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleClientProtocolPacket( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleServerAuthData(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleServerAuthData( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -//void PacketListener::handleSharedKey(std::shared_ptr packet) +// void PacketListener::handleSharedKey(std::shared_ptr packet) //{ // onUnhandledPacket(packet); -//} +// } -void PacketListener::handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket) -{ - onUnhandledPacket(playerAbilitiesPacket); +void PacketListener::handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket) { + onUnhandledPacket(playerAbilitiesPacket); } -void PacketListener::handleChatAutoComplete(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleChatAutoComplete( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleClientInformation(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleClientInformation( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleSoundEvent(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleSoundEvent( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleTileDestruction(std::shared_ptr packet) -{ - onUnhandledPacket(packet); +void PacketListener::handleTileDestruction( + std::shared_ptr packet) { + onUnhandledPacket(packet); } -void PacketListener::handleClientCommand(std::shared_ptr packet) -{ -} +void PacketListener::handleClientCommand( + std::shared_ptr packet) {} -//void PacketListener::handleLevelChunks(std::shared_ptr packet) +// void PacketListener::handleLevelChunks(std::shared_ptr +// packet) //{ // onUnhandledPacket(packet); -//} +// } -bool PacketListener::canHandleAsyncPackets() -{ - return false; -} +bool PacketListener::canHandleAsyncPackets() { return false; } // 4J Added -void PacketListener::handleCraftItem(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleCraftItem(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTradeItem(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTradeItem(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleDebugOptions(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleDebugOptions( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleServerSettingsChanged(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleServerSettingsChanged( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleChunkVisibilityArea(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleChunkVisibilityArea( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleUpdateProgress(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleUpdateProgress( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTextureChange(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTextureChange( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleTextureAndGeometryChange(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleTextureAndGeometryChange( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleUpdateGameRuleProgressPacket(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleUpdateGameRuleProgressPacket( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleKickPlayer(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleKickPlayer( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleXZ(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleXZ(std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } -void PacketListener::handleGameCommand(std::shared_ptr packet) -{ - onUnhandledPacket( (std::shared_ptr ) packet); +void PacketListener::handleGameCommand( + std::shared_ptr packet) { + onUnhandledPacket((std::shared_ptr)packet); } diff --git a/Minecraft.World/Network/Packets/PacketListener.h b/Minecraft.World/Network/Packets/PacketListener.h index 766e96f58..ab00ce43d 100644 --- a/Minecraft.World/Network/Packets/PacketListener.h +++ b/Minecraft.World/Network/Packets/PacketListener.h @@ -1,6 +1,5 @@ #pragma once - class Packet; class AddEntityPacket; @@ -103,110 +102,155 @@ class AdditionalModelPartsPacket; class XZPacket; class GameCommandPacket; -class PacketListener -{ +class PacketListener { public: - virtual ~PacketListener(){} - virtual bool isServerPacketListener() = 0; - virtual void handleBlockRegionUpdate(std::shared_ptr packet); - virtual void onUnhandledPacket(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); - virtual void handleDisconnect(std::shared_ptr packet); - virtual void handleLogin(std::shared_ptr packet); - virtual void handleMovePlayer(std::shared_ptr packet); - virtual void handleChunkTilesUpdate(std::shared_ptr packet); - virtual void handlePlayerAction(std::shared_ptr packet); - virtual void handleTileUpdate(std::shared_ptr packet); - virtual void handleChunkVisibility(std::shared_ptr packet); - virtual void handleAddPlayer(std::shared_ptr packet); - virtual void handleMoveEntity(std::shared_ptr packet); - virtual void handleMoveEntitySmall(std::shared_ptr packet); - virtual void handleTeleportEntity(std::shared_ptr packet); - virtual void handleUseItem(std::shared_ptr packet); - virtual void handleSetCarriedItem(std::shared_ptr packet); - virtual void handleRemoveEntity(std::shared_ptr packet); - virtual void handleTakeItemEntity(std::shared_ptr packet); - virtual void handleChat(std::shared_ptr packet); - virtual void handleAddEntity(std::shared_ptr packet); - virtual void handleAnimate(std::shared_ptr packet); - virtual void handlePlayerCommand(std::shared_ptr packet); - virtual void handlePreLogin(std::shared_ptr packet); - virtual void handleAddMob(std::shared_ptr packet); - virtual void handleSetTime(std::shared_ptr packet); - virtual void handleSetSpawn(std::shared_ptr packet); - virtual void handleSetEntityMotion(std::shared_ptr packet); - virtual void handleSetEntityData(std::shared_ptr packet); - virtual void handleRidePacket(std::shared_ptr packet); - virtual void handleInteract(std::shared_ptr packet); - virtual void handleEntityEvent(std::shared_ptr packet); - virtual void handleSetHealth(std::shared_ptr packet); - virtual void handleRespawn(std::shared_ptr packet); - virtual void handleExplosion(std::shared_ptr packet); - virtual void handleContainerOpen(std::shared_ptr packet); - virtual void handleContainerClose(std::shared_ptr packet); - virtual void handleContainerClick(std::shared_ptr packet); - virtual void handleContainerSetSlot(std::shared_ptr packet); - virtual void handleContainerContent(std::shared_ptr packet); - virtual void handleSignUpdate(std::shared_ptr packet); - virtual void handleContainerSetData(std::shared_ptr packet); - virtual void handleSetEquippedItem(std::shared_ptr packet); - virtual void handleContainerAck(std::shared_ptr packet); - virtual void handleAddPainting(std::shared_ptr packet); - virtual void handleTileEvent(std::shared_ptr packet); - virtual void handleAwardStat(std::shared_ptr packet); - virtual void handleEntityActionAtPosition(std::shared_ptr packet); - virtual void handlePlayerInput(std::shared_ptr packet); - virtual void handleGameEvent(std::shared_ptr packet); - virtual void handleAddGlobalEntity(std::shared_ptr packet); - virtual void handleComplexItemData(std::shared_ptr packet); - virtual void handleLevelEvent(std::shared_ptr packet); + virtual ~PacketListener() {} + virtual bool isServerPacketListener() = 0; + virtual void handleBlockRegionUpdate( + std::shared_ptr packet); + virtual void onUnhandledPacket(std::shared_ptr packet); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); + virtual void handleDisconnect(std::shared_ptr packet); + virtual void handleLogin(std::shared_ptr packet); + virtual void handleMovePlayer(std::shared_ptr packet); + virtual void handleChunkTilesUpdate( + std::shared_ptr packet); + virtual void handlePlayerAction(std::shared_ptr packet); + virtual void handleTileUpdate(std::shared_ptr packet); + virtual void handleChunkVisibility( + std::shared_ptr packet); + virtual void handleAddPlayer(std::shared_ptr packet); + virtual void handleMoveEntity(std::shared_ptr packet); + virtual void handleMoveEntitySmall( + std::shared_ptr packet); + virtual void handleTeleportEntity( + std::shared_ptr packet); + virtual void handleUseItem(std::shared_ptr packet); + virtual void handleSetCarriedItem( + std::shared_ptr packet); + virtual void handleRemoveEntity( + std::shared_ptr packet); + virtual void handleTakeItemEntity( + std::shared_ptr packet); + virtual void handleChat(std::shared_ptr packet); + virtual void handleAddEntity(std::shared_ptr packet); + virtual void handleAnimate(std::shared_ptr packet); + virtual void handlePlayerCommand( + std::shared_ptr packet); + virtual void handlePreLogin(std::shared_ptr packet); + virtual void handleAddMob(std::shared_ptr packet); + virtual void handleSetTime(std::shared_ptr packet); + virtual void handleSetSpawn(std::shared_ptr packet); + virtual void handleSetEntityMotion( + std::shared_ptr packet); + virtual void handleSetEntityData( + std::shared_ptr packet); + virtual void handleRidePacket(std::shared_ptr packet); + virtual void handleInteract(std::shared_ptr packet); + virtual void handleEntityEvent(std::shared_ptr packet); + virtual void handleSetHealth(std::shared_ptr packet); + virtual void handleRespawn(std::shared_ptr packet); + virtual void handleExplosion(std::shared_ptr packet); + virtual void handleContainerOpen( + std::shared_ptr packet); + virtual void handleContainerClose( + std::shared_ptr packet); + virtual void handleContainerClick( + std::shared_ptr packet); + virtual void handleContainerSetSlot( + std::shared_ptr packet); + virtual void handleContainerContent( + std::shared_ptr packet); + virtual void handleSignUpdate(std::shared_ptr packet); + virtual void handleContainerSetData( + std::shared_ptr packet); + virtual void handleSetEquippedItem( + std::shared_ptr packet); + virtual void handleContainerAck(std::shared_ptr packet); + virtual void handleAddPainting(std::shared_ptr packet); + virtual void handleTileEvent(std::shared_ptr packet); + virtual void handleAwardStat(std::shared_ptr packet); + virtual void handleEntityActionAtPosition( + std::shared_ptr packet); + virtual void handlePlayerInput(std::shared_ptr packet); + virtual void handleGameEvent(std::shared_ptr packet); + virtual void handleAddGlobalEntity( + std::shared_ptr packet); + virtual void handleComplexItemData( + std::shared_ptr packet); + virtual void handleLevelEvent(std::shared_ptr packet); - // 1.8.2 - virtual void handleGetInfo(std::shared_ptr packet); - virtual void handleUpdateMobEffect(std::shared_ptr packet); - virtual void handleRemoveMobEffect(std::shared_ptr packet); - virtual void handlePlayerInfo(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); - virtual void handleSetExperience(std::shared_ptr packet); - virtual void handleSetCreativeModeSlot(std::shared_ptr packet); - virtual void handleAddExperienceOrb(std::shared_ptr packet); + // 1.8.2 + virtual void handleGetInfo(std::shared_ptr packet); + virtual void handleUpdateMobEffect( + std::shared_ptr packet); + virtual void handleRemoveMobEffect( + std::shared_ptr packet); + virtual void handlePlayerInfo(std::shared_ptr packet); + virtual void handleKeepAlive(std::shared_ptr packet); + virtual void handleSetExperience( + std::shared_ptr packet); + virtual void handleSetCreativeModeSlot( + std::shared_ptr packet); + virtual void handleAddExperienceOrb( + std::shared_ptr packet); - // 1.0.1 - virtual void handleContainerButtonClick(std::shared_ptr packet); - virtual void handleTileEntityData(std::shared_ptr tileEntityDataPacket); + // 1.0.1 + virtual void handleContainerButtonClick( + std::shared_ptr packet); + virtual void handleTileEntityData( + std::shared_ptr tileEntityDataPacket); - // 1.1s - virtual void handleCustomPayload(std::shared_ptr customPayloadPacket); + // 1.1s + virtual void handleCustomPayload( + std::shared_ptr customPayloadPacket); - // 1.2.3 - virtual void handleRotateMob(std::shared_ptr rotateMobPacket); + // 1.2.3 + virtual void handleRotateMob( + std::shared_ptr rotateMobPacket); - // 1.3.2 - virtual void handleClientProtocolPacket(std::shared_ptr packet); - virtual void handleServerAuthData(std::shared_ptr packet); - //virtual void handleSharedKey(std::shared_ptr packet); - virtual void handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket); - virtual void handleChatAutoComplete(std::shared_ptr packet); - virtual void handleClientInformation(std::shared_ptr packet); - virtual void handleSoundEvent(std::shared_ptr packet); - virtual void handleTileDestruction(std::shared_ptr packet); - virtual void handleClientCommand(std::shared_ptr packet); - //virtual void handleLevelChunks(std::shared_ptr packet); - virtual bool canHandleAsyncPackets(); + // 1.3.2 + virtual void handleClientProtocolPacket( + std::shared_ptr packet); + virtual void handleServerAuthData( + std::shared_ptr packet); + // virtual void handleSharedKey(std::shared_ptr packet); + virtual void handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket); + virtual void handleChatAutoComplete( + std::shared_ptr packet); + virtual void handleClientInformation( + std::shared_ptr packet); + virtual void handleSoundEvent(std::shared_ptr packet); + virtual void handleTileDestruction( + std::shared_ptr packet); + virtual void handleClientCommand( + std::shared_ptr packet); + // virtual void handleLevelChunks(std::shared_ptr + // packet); + virtual bool canHandleAsyncPackets(); - // 4J Added - virtual void handleCraftItem(std::shared_ptr packet); - virtual void handleTradeItem(std::shared_ptr packet); - virtual void handleDebugOptions(std::shared_ptr packet); - virtual void handleServerSettingsChanged(std::shared_ptr packet); - virtual void handleTexture(std::shared_ptr packet); - virtual void handleTextureAndGeometry(std::shared_ptr packet); - virtual void handleChunkVisibilityArea(std::shared_ptr packet); - virtual void handleUpdateProgress(std::shared_ptr packet); - virtual void handleTextureChange(std::shared_ptr packet); - virtual void handleTextureAndGeometryChange(std::shared_ptr packet); - virtual void handleUpdateGameRuleProgressPacket(std::shared_ptr packet); - virtual void handleKickPlayer(std::shared_ptr packet); - virtual void handleXZ(std::shared_ptr packet); - virtual void handleGameCommand(std::shared_ptr packet); + // 4J Added + virtual void handleCraftItem(std::shared_ptr packet); + virtual void handleTradeItem(std::shared_ptr packet); + virtual void handleDebugOptions(std::shared_ptr packet); + virtual void handleServerSettingsChanged( + std::shared_ptr packet); + virtual void handleTexture(std::shared_ptr packet); + virtual void handleTextureAndGeometry( + std::shared_ptr packet); + virtual void handleChunkVisibilityArea( + std::shared_ptr packet); + virtual void handleUpdateProgress( + std::shared_ptr packet); + virtual void handleTextureChange( + std::shared_ptr packet); + virtual void handleTextureAndGeometryChange( + std::shared_ptr packet); + virtual void handleUpdateGameRuleProgressPacket( + std::shared_ptr packet); + virtual void handleKickPlayer(std::shared_ptr packet); + virtual void handleXZ(std::shared_ptr packet); + virtual void handleGameCommand(std::shared_ptr packet); }; diff --git a/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.cpp b/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.cpp index e551d84e7..b3da7e67a 100644 --- a/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.cpp +++ b/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.cpp @@ -5,133 +5,95 @@ const float PlayerAbilitiesPacket::SPEED_ACCURACY = 255.0f; -PlayerAbilitiesPacket::PlayerAbilitiesPacket() -{ - invulnerable = false; - _isFlying = false; - _canFly = false; - instabuild = false; - flyingSpeed = 0.0f; - walkingSpeed = 0.0f; +PlayerAbilitiesPacket::PlayerAbilitiesPacket() { + invulnerable = false; + _isFlying = false; + _canFly = false; + instabuild = false; + flyingSpeed = 0.0f; + walkingSpeed = 0.0f; } -PlayerAbilitiesPacket::PlayerAbilitiesPacket(Abilities *abilities) -{ - this->setInvulnerable(abilities->invulnerable); - this->setFlying(abilities->flying); - this->setCanFly(abilities->mayfly); - this->setInstabuild(abilities->instabuild); - this->setFlyingSpeed(abilities->getFlyingSpeed()); - this->setWalkingSpeed(abilities->getWalkingSpeed()); +PlayerAbilitiesPacket::PlayerAbilitiesPacket(Abilities* abilities) { + this->setInvulnerable(abilities->invulnerable); + this->setFlying(abilities->flying); + this->setCanFly(abilities->mayfly); + this->setInstabuild(abilities->instabuild); + this->setFlyingSpeed(abilities->getFlyingSpeed()); + this->setWalkingSpeed(abilities->getWalkingSpeed()); } -void PlayerAbilitiesPacket::read(DataInputStream *dis) -{ - uint8_t bitfield = dis->readByte(); +void PlayerAbilitiesPacket::read(DataInputStream* dis) { + uint8_t bitfield = dis->readByte(); - this->setInvulnerable((bitfield & FLAG_INVULNERABLE) > 0); - this->setFlying((bitfield & FLAG_FLYING) > 0); - this->setCanFly((bitfield & FLAG_CAN_FLY) > 0); - this->setInstabuild((bitfield & FLAG_INSTABUILD) > 0); - this->setFlyingSpeed(dis->readByte() / SPEED_ACCURACY); - this->setWalkingSpeed(dis->readByte() / SPEED_ACCURACY); + this->setInvulnerable((bitfield & FLAG_INVULNERABLE) > 0); + this->setFlying((bitfield & FLAG_FLYING) > 0); + this->setCanFly((bitfield & FLAG_CAN_FLY) > 0); + this->setInstabuild((bitfield & FLAG_INSTABUILD) > 0); + this->setFlyingSpeed(dis->readByte() / SPEED_ACCURACY); + this->setWalkingSpeed(dis->readByte() / SPEED_ACCURACY); } -void PlayerAbilitiesPacket::write(DataOutputStream *dos) -{ - uint8_t bitfield = 0; +void PlayerAbilitiesPacket::write(DataOutputStream* dos) { + uint8_t bitfield = 0; - if (isInvulnerable()) bitfield |= FLAG_INVULNERABLE; - if (isFlying()) bitfield |= FLAG_FLYING; - if (canFly()) bitfield |= FLAG_CAN_FLY; - if (canInstabuild()) bitfield |= FLAG_INSTABUILD; + if (isInvulnerable()) bitfield |= FLAG_INVULNERABLE; + if (isFlying()) bitfield |= FLAG_FLYING; + if (canFly()) bitfield |= FLAG_CAN_FLY; + if (canInstabuild()) bitfield |= FLAG_INSTABUILD; - dos->writeByte(bitfield); - dos->writeByte((int) (flyingSpeed * SPEED_ACCURACY)); - dos->writeByte((int) (walkingSpeed * SPEED_ACCURACY)); + dos->writeByte(bitfield); + dos->writeByte((int)(flyingSpeed * SPEED_ACCURACY)); + dos->writeByte((int)(walkingSpeed * SPEED_ACCURACY)); } -void PlayerAbilitiesPacket::handle(PacketListener *listener) -{ - listener->handlePlayerAbilities(shared_from_this()); +void PlayerAbilitiesPacket::handle(PacketListener* listener) { + listener->handlePlayerAbilities(shared_from_this()); } -int PlayerAbilitiesPacket::getEstimatedSize() -{ - return 2; -} +int PlayerAbilitiesPacket::getEstimatedSize() { return 2; } -//std::wstring getDebugInfo() +// std::wstring getDebugInfo() //{ -// return String.format("invuln=%b, flying=%b, canfly=%b, instabuild=%b, flyspeed=%.4f, walkspped=%.4f", isInvulnerable(), isFlying(), canFly(), canInstabuild(), getFlyingSpeed(), getWalkingSpeed()); -//} +// return String.format("invuln=%b, flying=%b, canfly=%b, instabuild=%b, +//flyspeed=%.4f, walkspped=%.4f", isInvulnerable(), isFlying(), canFly(), +//canInstabuild(), getFlyingSpeed(), getWalkingSpeed()); +// } -bool PlayerAbilitiesPacket::isInvulnerable() -{ - return invulnerable; +bool PlayerAbilitiesPacket::isInvulnerable() { return invulnerable; } + +void PlayerAbilitiesPacket::setInvulnerable(bool invulnerable) { + this->invulnerable = invulnerable; } -void PlayerAbilitiesPacket::setInvulnerable(bool invulnerable) -{ - this->invulnerable = invulnerable; +bool PlayerAbilitiesPacket::isFlying() { return _isFlying; } + +void PlayerAbilitiesPacket::setFlying(bool flying) { _isFlying = flying; } + +bool PlayerAbilitiesPacket::canFly() { return _canFly; } + +void PlayerAbilitiesPacket::setCanFly(bool canFly) { this->_canFly = canFly; } + +bool PlayerAbilitiesPacket::canInstabuild() { return instabuild; } + +void PlayerAbilitiesPacket::setInstabuild(bool instabuild) { + this->instabuild = instabuild; } -bool PlayerAbilitiesPacket::isFlying() -{ - return _isFlying; +float PlayerAbilitiesPacket::getFlyingSpeed() { return flyingSpeed; } + +void PlayerAbilitiesPacket::setFlyingSpeed(float flySpeed) { + this->flyingSpeed = flySpeed; } -void PlayerAbilitiesPacket::setFlying(bool flying) -{ - _isFlying = flying; +float PlayerAbilitiesPacket::getWalkingSpeed() { return walkingSpeed; } + +void PlayerAbilitiesPacket::setWalkingSpeed(float walkingSpeed) { + this->walkingSpeed = walkingSpeed; } -bool PlayerAbilitiesPacket::canFly() -{ - return _canFly; -} +bool PlayerAbilitiesPacket::canBeInvalidated() { return true; } -void PlayerAbilitiesPacket::setCanFly(bool canFly) -{ - this->_canFly = canFly; -} - -bool PlayerAbilitiesPacket::canInstabuild() -{ - return instabuild; -} - -void PlayerAbilitiesPacket::setInstabuild(bool instabuild) -{ - this->instabuild = instabuild; -} - -float PlayerAbilitiesPacket::getFlyingSpeed() -{ - return flyingSpeed; -} - -void PlayerAbilitiesPacket::setFlyingSpeed(float flySpeed) -{ - this->flyingSpeed = flySpeed; -} - -float PlayerAbilitiesPacket::getWalkingSpeed() -{ - return walkingSpeed; -} - -void PlayerAbilitiesPacket::setWalkingSpeed(float walkingSpeed) -{ - this->walkingSpeed = walkingSpeed; -} - -bool PlayerAbilitiesPacket::canBeInvalidated() -{ - return true; -} - -bool PlayerAbilitiesPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; +bool PlayerAbilitiesPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.h b/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.h index 72efad344..7627cd916 100644 --- a/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.h +++ b/Minecraft.World/Network/Packets/PlayerAbilitiesPacket.h @@ -4,47 +4,50 @@ class Abilities; -class PlayerAbilitiesPacket : public Packet, public std::enable_shared_from_this -{ +class PlayerAbilitiesPacket + : public Packet, + public std::enable_shared_from_this { private: - static const int FLAG_INVULNERABLE = 1 << 0; - static const int FLAG_FLYING = 1 << 1; - static const int FLAG_CAN_FLY = 1 << 2; - static const int FLAG_INSTABUILD = 1 << 3; - static const float SPEED_ACCURACY; + static const int FLAG_INVULNERABLE = 1 << 0; + static const int FLAG_FLYING = 1 << 1; + static const int FLAG_CAN_FLY = 1 << 2; + static const int FLAG_INSTABUILD = 1 << 3; + static const float SPEED_ACCURACY; - bool invulnerable; - bool _isFlying; - bool _canFly; - bool instabuild; - float flyingSpeed; - float walkingSpeed; + bool invulnerable; + bool _isFlying; + bool _canFly; + bool instabuild; + float flyingSpeed; + float walkingSpeed; public: - PlayerAbilitiesPacket(); - PlayerAbilitiesPacket(Abilities *abilities); + PlayerAbilitiesPacket(); + PlayerAbilitiesPacket(Abilities* abilities); - void read(DataInputStream *dis); - void write(DataOutputStream *dos); - void handle(PacketListener *listener); - int getEstimatedSize(); - //std::wstring getDebugInfo(); - bool isInvulnerable(); - void setInvulnerable(bool invulnerable); - bool isFlying(); - void setFlying(bool flying); - bool canFly(); - void setCanFly(bool canFly); - bool canInstabuild(); - void setInstabuild(bool instabuild); - float getFlyingSpeed(); - void setFlyingSpeed(float flySpeed); - float getWalkingSpeed(); - void setWalkingSpeed(float walkingSpeed); - bool canBeInvalidated(); - bool isInvalidatedBy(std::shared_ptr packet); + void read(DataInputStream* dis); + void write(DataOutputStream* dos); + void handle(PacketListener* listener); + int getEstimatedSize(); + // std::wstring getDebugInfo(); + bool isInvulnerable(); + void setInvulnerable(bool invulnerable); + bool isFlying(); + void setFlying(bool flying); + bool canFly(); + void setCanFly(bool canFly); + bool canInstabuild(); + void setInstabuild(bool instabuild); + float getFlyingSpeed(); + void setFlyingSpeed(float flySpeed); + float getWalkingSpeed(); + void setWalkingSpeed(float walkingSpeed); + bool canBeInvalidated(); + bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new PlayerAbilitiesPacket()); } - virtual int getId() { return 202; } + static std::shared_ptr create() { + return std::shared_ptr(new PlayerAbilitiesPacket()); + } + virtual int getId() { return 202; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/PlayerActionPacket.cpp b/Minecraft.World/Network/Packets/PlayerActionPacket.cpp index d24c00924..2436ecc6e 100644 --- a/Minecraft.World/Network/Packets/PlayerActionPacket.cpp +++ b/Minecraft.World/Network/Packets/PlayerActionPacket.cpp @@ -11,48 +11,43 @@ const int PlayerActionPacket::GET_UPDATED_BLOCK = 3; const int PlayerActionPacket::DROP_ITEM = 4; const int PlayerActionPacket::RELEASE_USE_ITEM = 5; -PlayerActionPacket::PlayerActionPacket() -{ - x = 0; - y = 0; - z = 0; - face = 0; - action = 0; +PlayerActionPacket::PlayerActionPacket() { + x = 0; + y = 0; + z = 0; + face = 0; + action = 0; } -PlayerActionPacket::PlayerActionPacket(int action, int x, int y, int z, int face) -{ - this->action = action; - this->x = x; - this->y = y; - this->z = z; - this->face = face; +PlayerActionPacket::PlayerActionPacket(int action, int x, int y, int z, + int face) { + this->action = action; + this->x = x; + this->y = y; + this->z = z; + this->face = face; } -void PlayerActionPacket::read(DataInputStream *dis) //throws IOException +void PlayerActionPacket::read(DataInputStream* dis) // throws IOException { - action = dis->read(); - x = dis->readInt(); - y = dis->read(); - z = dis->readInt(); - face = dis->read(); + action = dis->read(); + x = dis->readInt(); + y = dis->read(); + z = dis->readInt(); + face = dis->read(); } -void PlayerActionPacket::write(DataOutputStream *dos) //throws IOException +void PlayerActionPacket::write(DataOutputStream* dos) // throws IOException { - dos->write(action); - dos->writeInt(x); - dos->write(y); - dos->writeInt(z); - dos->write(face); + dos->write(action); + dos->writeInt(x); + dos->write(y); + dos->writeInt(z); + dos->write(face); } -void PlayerActionPacket::handle(PacketListener *listener) -{ - listener->handlePlayerAction(shared_from_this()); +void PlayerActionPacket::handle(PacketListener* listener) { + listener->handlePlayerAction(shared_from_this()); } -int PlayerActionPacket::getEstimatedSize() -{ - return 11; -} +int PlayerActionPacket::getEstimatedSize() { return 11; } diff --git a/Minecraft.World/Network/Packets/PlayerActionPacket.h b/Minecraft.World/Network/Packets/PlayerActionPacket.h index f1624a091..d73ff9211 100644 --- a/Minecraft.World/Network/Packets/PlayerActionPacket.h +++ b/Minecraft.World/Network/Packets/PlayerActionPacket.h @@ -1,31 +1,31 @@ #pragma once - #include "Packet.h" -class PlayerActionPacket : public Packet, public std::enable_shared_from_this -{ +class PlayerActionPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int START_DESTROY_BLOCK; + static const int START_DESTROY_BLOCK; static const int ABORT_DESTROY_BLOCK; static const int STOP_DESTROY_BLOCK; static const int GET_UPDATED_BLOCK; static const int DROP_ITEM; - static const int RELEASE_USE_ITEM; + static const int RELEASE_USE_ITEM; - int x, y, z, face, action; + int x, y, z, face, action; - PlayerActionPacket(); - PlayerActionPacket(int action, int x, int y, int z, int face); + PlayerActionPacket(); + PlayerActionPacket(int action, int x, int y, int z, int face); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new PlayerActionPacket()); } - virtual int getId() { return 14; } + static std::shared_ptr create() { + return std::shared_ptr(new PlayerActionPacket()); + } + virtual int getId() { return 14; } }; - - diff --git a/Minecraft.World/Network/Packets/PlayerCommandPacket.cpp b/Minecraft.World/Network/Packets/PlayerCommandPacket.cpp index 6b1813fb5..d8129e640 100644 --- a/Minecraft.World/Network/Packets/PlayerCommandPacket.cpp +++ b/Minecraft.World/Network/Packets/PlayerCommandPacket.cpp @@ -5,47 +5,39 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "PlayerCommandPacket.h" +const int PlayerCommandPacket::START_SNEAKING = 1; +const int PlayerCommandPacket::STOP_SNEAKING = 2; +const int PlayerCommandPacket::STOP_SLEEPING = 3; +const int PlayerCommandPacket::START_SPRINTING = 4; +const int PlayerCommandPacket::STOP_SPRINTING = 5; +const int PlayerCommandPacket::START_IDLEANIM = 6; +const int PlayerCommandPacket::STOP_IDLEANIM = 7; - -const int PlayerCommandPacket::START_SNEAKING = 1; -const int PlayerCommandPacket::STOP_SNEAKING = 2; -const int PlayerCommandPacket::STOP_SLEEPING = 3; -const int PlayerCommandPacket::START_SPRINTING = 4; -const int PlayerCommandPacket::STOP_SPRINTING = 5; -const int PlayerCommandPacket::START_IDLEANIM = 6; -const int PlayerCommandPacket::STOP_IDLEANIM = 7; - - -PlayerCommandPacket::PlayerCommandPacket() -{ - id = -1; - action = 0; +PlayerCommandPacket::PlayerCommandPacket() { + id = -1; + action = 0; } -PlayerCommandPacket::PlayerCommandPacket(std::shared_ptr e, int action) -{ - id = e->entityId; - this->action = action; +PlayerCommandPacket::PlayerCommandPacket(std::shared_ptr e, + int action) { + id = e->entityId; + this->action = action; } -void PlayerCommandPacket::read(DataInputStream *dis) //throws IOException +void PlayerCommandPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - action = dis->readByte(); + id = dis->readInt(); + action = dis->readByte(); } -void PlayerCommandPacket::write(DataOutputStream *dos) //throws IOException +void PlayerCommandPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeByte(action); + dos->writeInt(id); + dos->writeByte(action); } -void PlayerCommandPacket::handle(PacketListener *listener) -{ - listener->handlePlayerCommand(shared_from_this()); +void PlayerCommandPacket::handle(PacketListener* listener) { + listener->handlePlayerCommand(shared_from_this()); } -int PlayerCommandPacket::getEstimatedSize() -{ - return 5; -} +int PlayerCommandPacket::getEstimatedSize() { return 5; } diff --git a/Minecraft.World/Network/Packets/PlayerCommandPacket.h b/Minecraft.World/Network/Packets/PlayerCommandPacket.h index 124bf4d22..08c0c1251 100644 --- a/Minecraft.World/Network/Packets/PlayerCommandPacket.h +++ b/Minecraft.World/Network/Packets/PlayerCommandPacket.h @@ -1,37 +1,40 @@ #pragma once - #include "Packet.h" -class PlayerCommandPacket : public Packet, public std::enable_shared_from_this -{ +class PlayerCommandPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int START_SNEAKING; + static const int START_SNEAKING; static const int STOP_SNEAKING; - static const int STOP_SLEEPING; - static const int START_SPRINTING; - static const int STOP_SPRINTING; - static const int START_IDLEANIM; - static const int STOP_IDLEANIM; + static const int STOP_SLEEPING; + static const int START_SPRINTING; + static const int STOP_SPRINTING; + static const int START_IDLEANIM; + static const int STOP_IDLEANIM; - // 4J Added - // 4J-PB - Making this host only setting - /* - static const int SHOW_ON_MAPS; - static const int HIDE_ON_MAPS; - */ + // 4J Added + // 4J-PB - Making this host only setting + /* + static const int SHOW_ON_MAPS; + static const int HIDE_ON_MAPS; + */ int id; int action; - PlayerCommandPacket(); - PlayerCommandPacket(std::shared_ptr e, int action); + PlayerCommandPacket(); + PlayerCommandPacket(std::shared_ptr e, int action); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new PlayerCommandPacket()); } - virtual int getId() { return 19; } + static std::shared_ptr create() { + return std::shared_ptr(new PlayerCommandPacket()); + } + virtual int getId() { return 19; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/PlayerInfoPacket.cpp b/Minecraft.World/Network/Packets/PlayerInfoPacket.cpp index 786d2734d..4dc58d535 100644 --- a/Minecraft.World/Network/Packets/PlayerInfoPacket.cpp +++ b/Minecraft.World/Network/Packets/PlayerInfoPacket.cpp @@ -4,60 +4,53 @@ #include "../../../Minecraft.Client/Network/PlayerConnection.h" #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ #include "PacketListener.h" #include "../../IO/Streams/InputOutputStream.h" #include "PlayerInfoPacket.h" - - -PlayerInfoPacket::PlayerInfoPacket() -{ - m_networkSmallId = 0; - m_playerColourIndex = -1; - m_playerPrivileges = 0; - m_entityId = -1; +PlayerInfoPacket::PlayerInfoPacket() { + m_networkSmallId = 0; + m_playerColourIndex = -1; + m_playerPrivileges = 0; + m_entityId = -1; } -PlayerInfoPacket::PlayerInfoPacket(std::uint8_t networkSmallId, short playerColourIndex, unsigned int playerPrivileges) -{ - m_networkSmallId = networkSmallId; - m_playerColourIndex = playerColourIndex; - m_playerPrivileges = playerPrivileges; - m_entityId = -1; +PlayerInfoPacket::PlayerInfoPacket(std::uint8_t networkSmallId, + short playerColourIndex, + unsigned int playerPrivileges) { + m_networkSmallId = networkSmallId; + m_playerColourIndex = playerColourIndex; + m_playerPrivileges = playerPrivileges; + m_entityId = -1; } -PlayerInfoPacket::PlayerInfoPacket(std::shared_ptr player) -{ - m_networkSmallId = 0; - if(player->connection != NULL && player->connection->getNetworkPlayer() != NULL) m_networkSmallId = player->connection->getNetworkPlayer()->GetSmallId(); - m_playerColourIndex = player->getPlayerIndex(); - m_playerPrivileges = player->getAllPlayerGamePrivileges(); - m_entityId = player->entityId; +PlayerInfoPacket::PlayerInfoPacket(std::shared_ptr player) { + m_networkSmallId = 0; + if (player->connection != NULL && + player->connection->getNetworkPlayer() != NULL) + m_networkSmallId = player->connection->getNetworkPlayer()->GetSmallId(); + m_playerColourIndex = player->getPlayerIndex(); + m_playerPrivileges = player->getAllPlayerGamePrivileges(); + m_entityId = player->entityId; } -void PlayerInfoPacket::read(DataInputStream *dis) -{ - m_networkSmallId = dis->readByte(); - m_playerColourIndex = dis->readShort(); - m_playerPrivileges = dis->readInt(); - m_entityId = dis->readInt(); +void PlayerInfoPacket::read(DataInputStream* dis) { + m_networkSmallId = dis->readByte(); + m_playerColourIndex = dis->readShort(); + m_playerPrivileges = dis->readInt(); + m_entityId = dis->readInt(); } -void PlayerInfoPacket::write(DataOutputStream *dos) -{ - dos->writeByte(m_networkSmallId); - dos->writeShort(m_playerColourIndex); - dos->writeInt(m_playerPrivileges); - dos->writeInt(m_entityId); +void PlayerInfoPacket::write(DataOutputStream* dos) { + dos->writeByte(m_networkSmallId); + dos->writeShort(m_playerColourIndex); + dos->writeInt(m_playerPrivileges); + dos->writeInt(m_entityId); } -void PlayerInfoPacket::handle(PacketListener *listener) -{ - listener->handlePlayerInfo(shared_from_this()); +void PlayerInfoPacket::handle(PacketListener* listener) { + listener->handlePlayerInfo(shared_from_this()); } -int PlayerInfoPacket::getEstimatedSize() -{ - return 2 + 2 + 4 + 4; -} +int PlayerInfoPacket::getEstimatedSize() { return 2 + 2 + 4 + 4; } diff --git a/Minecraft.World/Network/Packets/PlayerInfoPacket.h b/Minecraft.World/Network/Packets/PlayerInfoPacket.h index 0c98036df..cf556646c 100644 --- a/Minecraft.World/Network/Packets/PlayerInfoPacket.h +++ b/Minecraft.World/Network/Packets/PlayerInfoPacket.h @@ -5,29 +5,32 @@ class ServerPlayer; -class PlayerInfoPacket : public Packet, public std::enable_shared_from_this -{ - public: - // 4J Stu - I have re-purposed this packet for our uses - //std::wstring name; - //bool add; - //int latency; - std::uint8_t m_networkSmallId; - short m_playerColourIndex; - unsigned int m_playerPrivileges; - int m_entityId; +class PlayerInfoPacket : public Packet, + public std::enable_shared_from_this { +public: + // 4J Stu - I have re-purposed this packet for our uses + // std::wstring name; + // bool add; + // int latency; + std::uint8_t m_networkSmallId; + short m_playerColourIndex; + unsigned int m_playerPrivileges; + int m_entityId; - PlayerInfoPacket(); - //PlayerInfoPacket(const std::wstring &name, bool add, int latency); - PlayerInfoPacket(std::uint8_t networkSmallId, short playerColourIndex, unsigned int playerPrivileges = 0); - PlayerInfoPacket(std::shared_ptr player); + PlayerInfoPacket(); + // PlayerInfoPacket(const std::wstring &name, bool add, int latency); + PlayerInfoPacket(std::uint8_t networkSmallId, short playerColourIndex, + unsigned int playerPrivileges = 0); + PlayerInfoPacket(std::shared_ptr player); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new PlayerInfoPacket()); } - virtual int getId() { return 201; } + static std::shared_ptr create() { + return std::shared_ptr(new PlayerInfoPacket()); + } + virtual int getId() { return 201; } }; diff --git a/Minecraft.World/Network/Packets/PlayerInputPacket.cpp b/Minecraft.World/Network/Packets/PlayerInputPacket.cpp index 1827f0af5..0f5461e15 100644 --- a/Minecraft.World/Network/Packets/PlayerInputPacket.cpp +++ b/Minecraft.World/Network/Packets/PlayerInputPacket.cpp @@ -4,84 +4,60 @@ #include "PacketListener.h" #include "PlayerInputPacket.h" - - -PlayerInputPacket::PlayerInputPacket() -{ - xa = 0.0f; - ya = 0.0f; - isJumpingVar = false; - isSneakingVar = false; - xRot = 0.0f; - yRot = 0.0f; +PlayerInputPacket::PlayerInputPacket() { + xa = 0.0f; + ya = 0.0f; + isJumpingVar = false; + isSneakingVar = false; + xRot = 0.0f; + yRot = 0.0f; } -PlayerInputPacket::PlayerInputPacket(float xa, float ya, bool isJumpingVar, bool isSneakingVar, float xRot, float yRot) -{ - this->xa = xa; - this->ya = ya; - this->isJumpingVar = isJumpingVar; - this->isSneakingVar = isSneakingVar; - this->xRot = xRot; - this->yRot = yRot; +PlayerInputPacket::PlayerInputPacket(float xa, float ya, bool isJumpingVar, + bool isSneakingVar, float xRot, + float yRot) { + this->xa = xa; + this->ya = ya; + this->isJumpingVar = isJumpingVar; + this->isSneakingVar = isSneakingVar; + this->xRot = xRot; + this->yRot = yRot; } -void PlayerInputPacket::read(DataInputStream *dis) //throws IOException +void PlayerInputPacket::read(DataInputStream* dis) // throws IOException { - xa = dis->readFloat(); - ya = dis->readFloat(); - xRot = dis->readFloat(); - yRot = dis->readFloat(); - isJumpingVar = dis->readBoolean(); - isSneakingVar = dis->readBoolean(); + xa = dis->readFloat(); + ya = dis->readFloat(); + xRot = dis->readFloat(); + yRot = dis->readFloat(); + isJumpingVar = dis->readBoolean(); + isSneakingVar = dis->readBoolean(); } -void PlayerInputPacket::write(DataOutputStream *dos) //throws IOException +void PlayerInputPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeFloat(xa); - dos->writeFloat(ya); - dos->writeFloat(xRot); - dos->writeFloat(yRot); - dos->writeBoolean(isJumpingVar); - dos->writeBoolean(isSneakingVar); + dos->writeFloat(xa); + dos->writeFloat(ya); + dos->writeFloat(xRot); + dos->writeFloat(yRot); + dos->writeBoolean(isJumpingVar); + dos->writeBoolean(isSneakingVar); } -void PlayerInputPacket::handle(PacketListener *listener) -{ - listener->handlePlayerInput(shared_from_this()); +void PlayerInputPacket::handle(PacketListener* listener) { + listener->handlePlayerInput(shared_from_this()); } -int PlayerInputPacket::getEstimatedSize() -{ - return 18; -} +int PlayerInputPacket::getEstimatedSize() { return 18; } -float PlayerInputPacket::getXa() -{ - return xa; -} +float PlayerInputPacket::getXa() { return xa; } -float PlayerInputPacket::getXRot() -{ - return xRot; -} +float PlayerInputPacket::getXRot() { return xRot; } -float PlayerInputPacket::getYa() -{ - return ya; -} +float PlayerInputPacket::getYa() { return ya; } -float PlayerInputPacket::getYRot() -{ - return yRot; -} +float PlayerInputPacket::getYRot() { return yRot; } -bool PlayerInputPacket::isJumping() -{ - return isJumpingVar; -} +bool PlayerInputPacket::isJumping() { return isJumpingVar; } -bool PlayerInputPacket::isSneaking() -{ - return isSneakingVar; -} +bool PlayerInputPacket::isSneaking() { return isSneakingVar; } diff --git a/Minecraft.World/Network/Packets/PlayerInputPacket.h b/Minecraft.World/Network/Packets/PlayerInputPacket.h index 81fbd5c1f..54b14ca71 100644 --- a/Minecraft.World/Network/Packets/PlayerInputPacket.h +++ b/Minecraft.World/Network/Packets/PlayerInputPacket.h @@ -1,13 +1,12 @@ #pragma once - #include "Packet.h" -class PlayerInputPacket : public Packet, public std::enable_shared_from_this -{ - +class PlayerInputPacket + : public Packet, + public std::enable_shared_from_this { private: - float xa; + float xa; float ya; bool isJumpingVar; bool isSneakingVar; @@ -15,22 +14,25 @@ private: float yRot; public: - PlayerInputPacket(); - PlayerInputPacket(float xa, float ya, bool isJumpingVar, bool isSneakingVar, float xRot, float yRot); + PlayerInputPacket(); + PlayerInputPacket(float xa, float ya, bool isJumpingVar, bool isSneakingVar, + float xRot, float yRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - float getXa(); - float getXRot(); - float getYa(); - float getYRot(); - bool isJumping(); - bool isSneaking(); + float getXa(); + float getXRot(); + float getYa(); + float getYRot(); + bool isJumping(); + bool isSneaking(); public: - static std::shared_ptr create() { return std::shared_ptr(new PlayerInputPacket()); } - virtual int getId() { return 27; } + static std::shared_ptr create() { + return std::shared_ptr(new PlayerInputPacket()); + } + virtual int getId() { return 27; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/PreLoginPacket.cpp b/Minecraft.World/Network/Packets/PreLoginPacket.cpp index 9bb385884..55459bffd 100644 --- a/Minecraft.World/Network/Packets/PreLoginPacket.cpp +++ b/Minecraft.World/Network/Packets/PreLoginPacket.cpp @@ -6,113 +6,106 @@ #include "PreLoginPacket.h" #include "../../IO/Streams/InputOutputStream.h" -PreLoginPacket::PreLoginPacket() -{ - loginKey = L""; - m_playerXuids = NULL; - m_dwPlayerCount = 0; - m_friendsOnlyBits = 0; - m_ugcPlayersVersion = 0; - ZeroMemory(m_szUniqueSaveName,m_iSaveNameLen); - m_serverSettings = 0; - m_hostIndex = 0; - m_texturePackId = 0; - m_netcodeVersion = 0; +PreLoginPacket::PreLoginPacket() { + loginKey = L""; + m_playerXuids = NULL; + m_dwPlayerCount = 0; + m_friendsOnlyBits = 0; + m_ugcPlayersVersion = 0; + ZeroMemory(m_szUniqueSaveName, m_iSaveNameLen); + m_serverSettings = 0; + m_hostIndex = 0; + m_texturePackId = 0; + m_netcodeVersion = 0; } -PreLoginPacket::PreLoginPacket(std::wstring userName) -{ - this->loginKey = userName; - m_playerXuids = NULL; - m_dwPlayerCount = 0; - m_friendsOnlyBits = 0; - m_ugcPlayersVersion = 0; - ZeroMemory(m_szUniqueSaveName,m_iSaveNameLen); - m_serverSettings = 0; - m_hostIndex = 0; - m_texturePackId = 0; - m_netcodeVersion = 0; +PreLoginPacket::PreLoginPacket(std::wstring userName) { + this->loginKey = userName; + m_playerXuids = NULL; + m_dwPlayerCount = 0; + m_friendsOnlyBits = 0; + m_ugcPlayersVersion = 0; + ZeroMemory(m_szUniqueSaveName, m_iSaveNameLen); + m_serverSettings = 0; + m_hostIndex = 0; + m_texturePackId = 0; + m_netcodeVersion = 0; } -PreLoginPacket::PreLoginPacket(std::wstring userName, PlayerUID *playerXuids, std::uint8_t playerCount, std::uint8_t friendsOnlyBits, std::uint32_t ugcPlayersVersion, const char *pszUniqueSaveName, std::uint32_t serverSettings, std::uint8_t hostIndex, std::uint32_t texturePackId) -{ - this->loginKey = userName; - m_playerXuids = playerXuids; - m_dwPlayerCount = playerCount; - m_friendsOnlyBits = friendsOnlyBits; - m_ugcPlayersVersion = ugcPlayersVersion; - memcpy(m_szUniqueSaveName,pszUniqueSaveName,m_iSaveNameLen); - m_serverSettings = serverSettings; - m_hostIndex = hostIndex; - m_texturePackId = texturePackId; - m_netcodeVersion = 0; +PreLoginPacket::PreLoginPacket( + std::wstring userName, PlayerUID* playerXuids, std::uint8_t playerCount, + std::uint8_t friendsOnlyBits, std::uint32_t ugcPlayersVersion, + const char* pszUniqueSaveName, std::uint32_t serverSettings, + std::uint8_t hostIndex, std::uint32_t texturePackId) { + this->loginKey = userName; + m_playerXuids = playerXuids; + m_dwPlayerCount = playerCount; + m_friendsOnlyBits = friendsOnlyBits; + m_ugcPlayersVersion = ugcPlayersVersion; + memcpy(m_szUniqueSaveName, pszUniqueSaveName, m_iSaveNameLen); + m_serverSettings = serverSettings; + m_hostIndex = hostIndex; + m_texturePackId = texturePackId; + m_netcodeVersion = 0; } -PreLoginPacket::~PreLoginPacket() -{ - if( m_playerXuids != NULL ) delete [] m_playerXuids; +PreLoginPacket::~PreLoginPacket() { + if (m_playerXuids != NULL) delete[] m_playerXuids; } -void PreLoginPacket::read(DataInputStream *dis) //throws IOException +void PreLoginPacket::read(DataInputStream* dis) // throws IOException { - m_netcodeVersion = dis->readShort(); + m_netcodeVersion = dis->readShort(); - loginKey = readUtf(dis, 32); + loginKey = readUtf(dis, 32); - m_friendsOnlyBits = dis->readByte(); - m_ugcPlayersVersion = static_cast(dis->readInt()); - m_dwPlayerCount = dis->readByte(); - if( m_dwPlayerCount > 0 ) - { - m_playerXuids = new PlayerUID[m_dwPlayerCount]; - for(std::uint32_t i = 0; i < m_dwPlayerCount; ++i) - { - m_playerXuids[i] = dis->readPlayerUID(); - } - } - for(int i = 0; i < m_iSaveNameLen; ++i) - { - m_szUniqueSaveName[i] = static_cast(dis->readByte()); - } - m_serverSettings = static_cast(dis->readInt()); - m_hostIndex = dis->readByte(); - - m_texturePackId = static_cast(dis->readInt()); + m_friendsOnlyBits = dis->readByte(); + m_ugcPlayersVersion = static_cast(dis->readInt()); + m_dwPlayerCount = dis->readByte(); + if (m_dwPlayerCount > 0) { + m_playerXuids = new PlayerUID[m_dwPlayerCount]; + for (std::uint32_t i = 0; i < m_dwPlayerCount; ++i) { + m_playerXuids[i] = dis->readPlayerUID(); + } + } + for (int i = 0; i < m_iSaveNameLen; ++i) { + m_szUniqueSaveName[i] = static_cast(dis->readByte()); + } + m_serverSettings = static_cast(dis->readInt()); + m_hostIndex = dis->readByte(); - // Set the name of the map so we can check it for players banned lists - app.SetUniqueMapName((char *)m_szUniqueSaveName); + m_texturePackId = static_cast(dis->readInt()); + + // Set the name of the map so we can check it for players banned lists + app.SetUniqueMapName((char*)m_szUniqueSaveName); } -void PreLoginPacket::write(DataOutputStream *dos) //throws IOException +void PreLoginPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeShort(MINECRAFT_NET_VERSION); + dos->writeShort(MINECRAFT_NET_VERSION); - writeUtf(loginKey, dos); - - dos->writeByte(m_friendsOnlyBits); - dos->writeInt(static_cast(m_ugcPlayersVersion)); - dos->writeByte((std::uint8_t)m_dwPlayerCount); - for(std::uint32_t i = 0; i < m_dwPlayerCount; ++i) - { - dos->writePlayerUID( m_playerXuids[i] ); - } + writeUtf(loginKey, dos); - app.DebugPrintf("*** PreLoginPacket::write - %s\n",m_szUniqueSaveName); - for(int i = 0; i < m_iSaveNameLen; ++i) - { - dos->writeByte(static_cast(m_szUniqueSaveName[i])); - } - dos->writeInt(static_cast(m_serverSettings)); - dos->writeByte(m_hostIndex); - dos->writeInt(static_cast(m_texturePackId)); + dos->writeByte(m_friendsOnlyBits); + dos->writeInt(static_cast(m_ugcPlayersVersion)); + dos->writeByte((std::uint8_t)m_dwPlayerCount); + for (std::uint32_t i = 0; i < m_dwPlayerCount; ++i) { + dos->writePlayerUID(m_playerXuids[i]); + } + + app.DebugPrintf("*** PreLoginPacket::write - %s\n", m_szUniqueSaveName); + for (int i = 0; i < m_iSaveNameLen; ++i) { + dos->writeByte(static_cast(m_szUniqueSaveName[i])); + } + dos->writeInt(static_cast(m_serverSettings)); + dos->writeByte(m_hostIndex); + dos->writeInt(static_cast(m_texturePackId)); } -void PreLoginPacket::handle(PacketListener *listener) -{ - listener->handlePreLogin(shared_from_this()); +void PreLoginPacket::handle(PacketListener* listener) { + listener->handlePreLogin(shared_from_this()); } -int PreLoginPacket::getEstimatedSize() -{ - return 4 + 4 + (int)loginKey.length() + 4 +14 + 4 + 1 + 4; +int PreLoginPacket::getEstimatedSize() { + return 4 + 4 + (int)loginKey.length() + 4 + 14 + 4 + 1 + 4; } diff --git a/Minecraft.World/Network/Packets/PreLoginPacket.h b/Minecraft.World/Network/Packets/PreLoginPacket.h index 637cb34dd..8d764d0a5 100644 --- a/Minecraft.World/Network/Packets/PreLoginPacket.h +++ b/Minecraft.World/Network/Packets/PreLoginPacket.h @@ -4,37 +4,50 @@ #include "Packet.h" -class PreLoginPacket : public Packet, public std::enable_shared_from_this -{ +class PreLoginPacket : public Packet, + public std::enable_shared_from_this { // the login key is username client->server and sessionid server->client public: - static const int m_iSaveNameLen=14; - //4J Added more info to this packet so that we can check if anyone has a UGC privilege that won't let us - // join, and so that we can inform the server if we have that privilege set. Anyone with UGC turned off completely - // can't play the game online at all, so we only need to specify players with friends only set - PlayerUID *m_playerXuids; - std::uint8_t m_dwPlayerCount; - std::uint8_t m_friendsOnlyBits; - std::uint32_t m_ugcPlayersVersion; - char m_szUniqueSaveName[m_iSaveNameLen]; // added for checking if the level is in the ban list - std::uint32_t m_serverSettings; // A bitfield of server settings constructed with the MAKE_SERVER_SETTINGS macro - std::uint8_t m_hostIndex; // Rather than sending the xuid of the host again, send an index into the m_playerXuids array - std::uint32_t m_texturePackId; - std::int16_t m_netcodeVersion; + static const int m_iSaveNameLen = 14; + // 4J Added more info to this packet so that we can check if anyone has a + // UGC privilege that won't let us + // join, and so that we can inform the server if we have that privilege + // set. Anyone with UGC turned off completely can't play the game online at + // all, so we only need to specify players with friends only set + PlayerUID* m_playerXuids; + std::uint8_t m_dwPlayerCount; + std::uint8_t m_friendsOnlyBits; + std::uint32_t m_ugcPlayersVersion; + char m_szUniqueSaveName[m_iSaveNameLen]; // added for checking if the level + // is in the ban list + std::uint32_t + m_serverSettings; // A bitfield of server settings constructed with the + // MAKE_SERVER_SETTINGS macro + std::uint8_t + m_hostIndex; // Rather than sending the xuid of the host again, send an + // index into the m_playerXuids array + std::uint32_t m_texturePackId; + std::int16_t m_netcodeVersion; - std::wstring loginKey; + std::wstring loginKey; - PreLoginPacket(); - PreLoginPacket(std::wstring userName); - PreLoginPacket(std::wstring userName, PlayerUID *playerXuids, std::uint8_t playerCount, std::uint8_t friendsOnlyBits, std::uint32_t ugcPlayersVersion, const char *pszUniqueSaveName, std::uint32_t serverSettings, std::uint8_t hostIndex, std::uint32_t texturePackId); - ~PreLoginPacket(); + PreLoginPacket(); + PreLoginPacket(std::wstring userName); + PreLoginPacket(std::wstring userName, PlayerUID* playerXuids, + std::uint8_t playerCount, std::uint8_t friendsOnlyBits, + std::uint32_t ugcPlayersVersion, + const char* pszUniqueSaveName, std::uint32_t serverSettings, + std::uint8_t hostIndex, std::uint32_t texturePackId); + ~PreLoginPacket(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new PreLoginPacket()); } - virtual int getId() { return 2; } + static std::shared_ptr create() { + return std::shared_ptr(new PreLoginPacket()); + } + virtual int getId() { return 2; } }; diff --git a/Minecraft.World/Network/Packets/RemoveEntitiesPacket.cpp b/Minecraft.World/Network/Packets/RemoveEntitiesPacket.cpp index 9207ca8bf..2f0599034 100644 --- a/Minecraft.World/Network/Packets/RemoveEntitiesPacket.cpp +++ b/Minecraft.World/Network/Packets/RemoveEntitiesPacket.cpp @@ -5,52 +5,41 @@ #include "PacketListener.h" #include "RemoveEntitiesPacket.h" -RemoveEntitiesPacket::RemoveEntitiesPacket() -{ +RemoveEntitiesPacket::RemoveEntitiesPacket() {} + +RemoveEntitiesPacket::RemoveEntitiesPacket(intArray ids) { this->ids = ids; } + +RemoveEntitiesPacket::~RemoveEntitiesPacket() { + delete[] ids.data; // 4jcraft, changed to [] } -RemoveEntitiesPacket::RemoveEntitiesPacket(intArray ids) +void RemoveEntitiesPacket::read(DataInputStream* dis) // throws IOException { - this->ids = ids; + ids = intArray(dis->readByte()); + for (unsigned int i = 0; i < ids.length; ++i) { + ids[i] = dis->readInt(); + } } -RemoveEntitiesPacket::~RemoveEntitiesPacket() +void RemoveEntitiesPacket::write(DataOutputStream* dos) // throws IOException { - delete[] ids.data; //4jcraft, changed to [] + dos->writeByte(ids.length); + for (unsigned int i = 0; i < ids.length; ++i) { + dos->writeInt(ids[i]); + } } -void RemoveEntitiesPacket::read(DataInputStream *dis) //throws IOException -{ - ids = intArray(dis->readByte()); - for(unsigned int i = 0; i < ids.length; ++i) - { - ids[i] = dis->readInt(); - } +void RemoveEntitiesPacket::handle(PacketListener* listener) { + listener->handleRemoveEntity(shared_from_this()); } -void RemoveEntitiesPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeByte(ids.length); - for(unsigned int i = 0; i < ids.length; ++i) - { - dos->writeInt(ids[i]); - } -} - -void RemoveEntitiesPacket::handle(PacketListener *listener) -{ - listener->handleRemoveEntity(shared_from_this()); -} - -int RemoveEntitiesPacket::getEstimatedSize() -{ - return 1 + (ids.length * 4); -} +int RemoveEntitiesPacket::getEstimatedSize() { return 1 + (ids.length * 4); } /* - 4J: These are necesary on the PS3. - (and 4). + 4J: These are necesary on the PS3. + (and 4). */ -#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || defined __linux__) +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ || \ + defined __linux__) const int RemoveEntitiesPacket::MAX_PER_PACKET; #endif diff --git a/Minecraft.World/Network/Packets/RemoveEntitiesPacket.h b/Minecraft.World/Network/Packets/RemoveEntitiesPacket.h index b70b92249..68529e5ac 100644 --- a/Minecraft.World/Network/Packets/RemoveEntitiesPacket.h +++ b/Minecraft.World/Network/Packets/RemoveEntitiesPacket.h @@ -1,27 +1,28 @@ #pragma once - #include "../../Util/BasicTypeContainers.h" #include "Packet.h" -class RemoveEntitiesPacket : public Packet, public std::enable_shared_from_this -{ +class RemoveEntitiesPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int MAX_PER_PACKET = Byte::MAX_VALUE; + static const int MAX_PER_PACKET = Byte::MAX_VALUE; - intArray ids; + intArray ids; - RemoveEntitiesPacket(); - RemoveEntitiesPacket(intArray ids); - ~RemoveEntitiesPacket(); + RemoveEntitiesPacket(); + RemoveEntitiesPacket(intArray ids); + ~RemoveEntitiesPacket(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new RemoveEntitiesPacket()); } - virtual int getId() { return 29; } + static std::shared_ptr create() { + return std::shared_ptr(new RemoveEntitiesPacket()); + } + virtual int getId() { return 29; } }; - diff --git a/Minecraft.World/Network/Packets/RemoveMobEffectPacket.cpp b/Minecraft.World/Network/Packets/RemoveMobEffectPacket.cpp index 7a9f88db3..67604d3a2 100644 --- a/Minecraft.World/Network/Packets/RemoveMobEffectPacket.cpp +++ b/Minecraft.World/Network/Packets/RemoveMobEffectPacket.cpp @@ -4,36 +4,26 @@ #include "PacketListener.h" #include "RemoveMobEffectPacket.h" +RemoveMobEffectPacket::RemoveMobEffectPacket() {} - -RemoveMobEffectPacket::RemoveMobEffectPacket() -{ +RemoveMobEffectPacket::RemoveMobEffectPacket(int entityId, + MobEffectInstance* effect) { + this->entityId = entityId; + this->effectId = (uint8_t)(effect->getId() & 0xff); } -RemoveMobEffectPacket::RemoveMobEffectPacket(int entityId, MobEffectInstance *effect) -{ - this->entityId = entityId; - this->effectId = (uint8_t) (effect->getId() & 0xff); +void RemoveMobEffectPacket::read(DataInputStream* dis) { + entityId = dis->readInt(); + effectId = dis->readByte(); } -void RemoveMobEffectPacket::read(DataInputStream *dis) -{ - entityId = dis->readInt(); - effectId = dis->readByte(); +void RemoveMobEffectPacket::write(DataOutputStream* dos) { + dos->writeInt(entityId); + dos->writeByte(effectId); } -void RemoveMobEffectPacket::write(DataOutputStream *dos) -{ - dos->writeInt(entityId); - dos->writeByte(effectId); +void RemoveMobEffectPacket::handle(PacketListener* listener) { + listener->handleRemoveMobEffect(shared_from_this()); } -void RemoveMobEffectPacket::handle(PacketListener *listener) -{ - listener->handleRemoveMobEffect(shared_from_this()); -} - -int RemoveMobEffectPacket::getEstimatedSize() -{ - return 5; -} \ No newline at end of file +int RemoveMobEffectPacket::getEstimatedSize() { return 5; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/RemoveMobEffectPacket.h b/Minecraft.World/Network/Packets/RemoveMobEffectPacket.h index e069baa9a..13a988774 100644 --- a/Minecraft.World/Network/Packets/RemoveMobEffectPacket.h +++ b/Minecraft.World/Network/Packets/RemoveMobEffectPacket.h @@ -4,20 +4,24 @@ class MobEffectInstance; #include "Packet.h" -class RemoveMobEffectPacket : public Packet, public std::enable_shared_from_this -{ - public: - int entityId; - char effectId; - - RemoveMobEffectPacket(); - RemoveMobEffectPacket(int entityId, MobEffectInstance *effect); - - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); +class RemoveMobEffectPacket + : public Packet, + public std::enable_shared_from_this { public: - static std::shared_ptr create() { return std::shared_ptr(new RemoveMobEffectPacket()); } - virtual int getId() { return 42; } + int entityId; + char effectId; + + RemoveMobEffectPacket(); + RemoveMobEffectPacket(int entityId, MobEffectInstance* effect); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + +public: + static std::shared_ptr create() { + return std::shared_ptr(new RemoveMobEffectPacket()); + } + virtual int getId() { return 42; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/RespawnPacket.cpp b/Minecraft.World/Network/Packets/RespawnPacket.cpp index 1cb6cf34a..093be14a4 100644 --- a/Minecraft.World/Network/Packets/RespawnPacket.cpp +++ b/Minecraft.World/Network/Packets/RespawnPacket.cpp @@ -5,93 +5,85 @@ #include "RespawnPacket.h" #include "../../Level/Storage/LevelType.h" -RespawnPacket::RespawnPacket() -{ - this->dimension = 0; - this->difficulty = 1; - this->mapSeed = 0; - this->mapHeight = 0; - this->playerGameType = NULL; - this->m_newSeaLevel = false; - m_pLevelType = NULL; - m_newEntityId = 0; - m_xzSize = LEVEL_MAX_WIDTH; - m_hellScale = HELL_LEVEL_MAX_SCALE; +RespawnPacket::RespawnPacket() { + this->dimension = 0; + this->difficulty = 1; + this->mapSeed = 0; + this->mapHeight = 0; + this->playerGameType = NULL; + this->m_newSeaLevel = false; + m_pLevelType = NULL; + m_newEntityId = 0; + m_xzSize = LEVEL_MAX_WIDTH; + m_hellScale = HELL_LEVEL_MAX_SCALE; } -RespawnPacket::RespawnPacket(char dimension, __int64 mapSeed, int mapHeight, GameType *playerGameType, char difficulty, LevelType *pLevelType, bool newSeaLevel, int newEntityId, int xzSize, int hellScale) -{ - this->dimension = dimension; - this->mapSeed = mapSeed; - this->mapHeight = mapHeight; - this->playerGameType = playerGameType; - this->difficulty = difficulty; - this->m_newSeaLevel = newSeaLevel; - this->m_pLevelType=pLevelType; - this->m_newEntityId = newEntityId; - m_xzSize = xzSize; - m_hellScale = hellScale; - app.DebugPrintf("RespawnPacket - Difficulty = %d\n",difficulty); - +RespawnPacket::RespawnPacket(char dimension, __int64 mapSeed, int mapHeight, + GameType* playerGameType, char difficulty, + LevelType* pLevelType, bool newSeaLevel, + int newEntityId, int xzSize, int hellScale) { + this->dimension = dimension; + this->mapSeed = mapSeed; + this->mapHeight = mapHeight; + this->playerGameType = playerGameType; + this->difficulty = difficulty; + this->m_newSeaLevel = newSeaLevel; + this->m_pLevelType = pLevelType; + this->m_newEntityId = newEntityId; + m_xzSize = xzSize; + m_hellScale = hellScale; + app.DebugPrintf("RespawnPacket - Difficulty = %d\n", difficulty); } -void RespawnPacket::handle(PacketListener *listener) -{ - listener->handleRespawn(shared_from_this()); +void RespawnPacket::handle(PacketListener* listener) { + listener->handleRespawn(shared_from_this()); } -void RespawnPacket::read(DataInputStream *dis) //throws IOException +void RespawnPacket::read(DataInputStream* dis) // throws IOException { - dimension = dis->readByte(); - playerGameType = GameType::byId(dis->readByte()); - mapHeight = dis->readShort(); - std::wstring typeName = readUtf(dis, 16); - m_pLevelType = LevelType::getLevelType(typeName); - if (m_pLevelType == NULL) - { - m_pLevelType = LevelType::lvl_normal; - } - mapSeed = dis->readLong(); - difficulty = dis->readByte(); - m_newSeaLevel = dis->readBoolean(); - m_newEntityId = dis->readShort(); + dimension = dis->readByte(); + playerGameType = GameType::byId(dis->readByte()); + mapHeight = dis->readShort(); + std::wstring typeName = readUtf(dis, 16); + m_pLevelType = LevelType::getLevelType(typeName); + if (m_pLevelType == NULL) { + m_pLevelType = LevelType::lvl_normal; + } + mapSeed = dis->readLong(); + difficulty = dis->readByte(); + m_newSeaLevel = dis->readBoolean(); + m_newEntityId = dis->readShort(); #ifdef _LARGE_WORLDS - m_xzSize = dis->readShort(); - m_hellScale = dis->read(); + m_xzSize = dis->readShort(); + m_hellScale = dis->read(); #endif - app.DebugPrintf("RespawnPacket::read - Difficulty = %d\n",difficulty); - + app.DebugPrintf("RespawnPacket::read - Difficulty = %d\n", difficulty); } -void RespawnPacket::write(DataOutputStream *dos) //throws IOException +void RespawnPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeByte(dimension); - dos->writeByte(playerGameType->getId()); - dos->writeShort(mapHeight); - if (m_pLevelType == NULL) - { - writeUtf(L"", dos); - } - else - { - writeUtf(m_pLevelType->getGeneratorName(), dos); - } - dos->writeLong(mapSeed); - dos->writeByte(difficulty); - dos->writeBoolean(m_newSeaLevel); - dos->writeShort(m_newEntityId); + dos->writeByte(dimension); + dos->writeByte(playerGameType->getId()); + dos->writeShort(mapHeight); + if (m_pLevelType == NULL) { + writeUtf(L"", dos); + } else { + writeUtf(m_pLevelType->getGeneratorName(), dos); + } + dos->writeLong(mapSeed); + dos->writeByte(difficulty); + dos->writeBoolean(m_newSeaLevel); + dos->writeShort(m_newEntityId); #ifdef _LARGE_WORLDS - dos->writeShort(m_xzSize); - dos->write(m_hellScale); + dos->writeShort(m_xzSize); + dos->write(m_hellScale); #endif } -int RespawnPacket::getEstimatedSize() -{ - int length=0; - if (m_pLevelType != NULL) - { - length = (int)m_pLevelType->getGeneratorName().length(); - } - return 13+length; +int RespawnPacket::getEstimatedSize() { + int length = 0; + if (m_pLevelType != NULL) { + length = (int)m_pLevelType->getGeneratorName().length(); + } + return 13 + length; } diff --git a/Minecraft.World/Network/Packets/RespawnPacket.h b/Minecraft.World/Network/Packets/RespawnPacket.h index 0c00b0b9e..ae8fd2e0b 100644 --- a/Minecraft.World/Network/Packets/RespawnPacket.h +++ b/Minecraft.World/Network/Packets/RespawnPacket.h @@ -1,34 +1,38 @@ #pragma once - #include "Packet.h" class LevelType; class GameType; -class RespawnPacket : public Packet, public std::enable_shared_from_this -{ +class RespawnPacket : public Packet, + public std::enable_shared_from_this { public: - char dimension; - char difficulty; - __int64 mapSeed; + char dimension; + char difficulty; + __int64 mapSeed; int mapHeight; - GameType *playerGameType; - bool m_newSeaLevel; // 4J added - LevelType *m_pLevelType; - int m_newEntityId; - int m_xzSize; // 4J Added - int m_hellScale; // 4J Added + GameType* playerGameType; + bool m_newSeaLevel; // 4J added + LevelType* m_pLevelType; + int m_newEntityId; + int m_xzSize; // 4J Added + int m_hellScale; // 4J Added - RespawnPacket(); - RespawnPacket(char dimension, __int64 mapSeed, int mapHeight, GameType *playerGameType, char difficulty, LevelType *pLevelType, bool newSeaLevel, int newEntityId, int xzSize, int hellScale); + RespawnPacket(); + RespawnPacket(char dimension, __int64 mapSeed, int mapHeight, + GameType* playerGameType, char difficulty, + LevelType* pLevelType, bool newSeaLevel, int newEntityId, + int xzSize, int hellScale); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new RespawnPacket()); } - virtual int getId() { return 9; } + static std::shared_ptr create() { + return std::shared_ptr(new RespawnPacket()); + } + virtual int getId() { return 9; } }; diff --git a/Minecraft.World/Network/Packets/RotateHeadPacket.cpp b/Minecraft.World/Network/Packets/RotateHeadPacket.cpp index 74a5ac63b..ce9002fb1 100644 --- a/Minecraft.World/Network/Packets/RotateHeadPacket.cpp +++ b/Minecraft.World/Network/Packets/RotateHeadPacket.cpp @@ -2,50 +2,35 @@ #include "RotateHeadPacket.h" -RotateHeadPacket::RotateHeadPacket() -{ +RotateHeadPacket::RotateHeadPacket() {} + +RotateHeadPacket::RotateHeadPacket(int id, char yHeadRot) { + this->id = id; + this->yHeadRot = yHeadRot; } -RotateHeadPacket::RotateHeadPacket(int id, char yHeadRot) -{ - this->id = id; - this->yHeadRot = yHeadRot; +void RotateHeadPacket::read(DataInputStream* dis) { + id = dis->readInt(); + yHeadRot = dis->readByte(); } -void RotateHeadPacket::read(DataInputStream *dis) -{ - id = dis->readInt(); - yHeadRot = dis->readByte(); +void RotateHeadPacket::write(DataOutputStream* dos) { + dos->writeInt(id); + dos->writeByte(yHeadRot); } -void RotateHeadPacket::write(DataOutputStream *dos) -{ - dos->writeInt(id); - dos->writeByte(yHeadRot); +void RotateHeadPacket::handle(PacketListener* listener) { + listener->handleRotateMob(shared_from_this()); } -void RotateHeadPacket::handle(PacketListener *listener) -{ - listener->handleRotateMob(shared_from_this()); +int RotateHeadPacket::getEstimatedSize() { return 5; } + +bool RotateHeadPacket::canBeInvalidated() { return true; } + +bool RotateHeadPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->id == id; } -int RotateHeadPacket::getEstimatedSize() -{ - return 5; -} - -bool RotateHeadPacket::canBeInvalidated() -{ - return true; -} - -bool RotateHeadPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->id == id; -} - -bool RotateHeadPacket::isAync() -{ - return true; -} \ No newline at end of file +bool RotateHeadPacket::isAync() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/RotateHeadPacket.h b/Minecraft.World/Network/Packets/RotateHeadPacket.h index 7d3dc84bc..b1120e57c 100644 --- a/Minecraft.World/Network/Packets/RotateHeadPacket.h +++ b/Minecraft.World/Network/Packets/RotateHeadPacket.h @@ -4,24 +4,26 @@ #include "PacketListener.h" #include "Packet.h" -class RotateHeadPacket : public Packet, public std::enable_shared_from_this -{ +class RotateHeadPacket : public Packet, + public std::enable_shared_from_this { public: - int id; - char yHeadRot; + int id; + char yHeadRot; - RotateHeadPacket(); - RotateHeadPacket(int id, char yHeadRot); + RotateHeadPacket(); + RotateHeadPacket(int id, char yHeadRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); public: - static std::shared_ptr create() { return std::shared_ptr(new RotateHeadPacket()); } - virtual int getId() { return 35; } + static std::shared_ptr create() { + return std::shared_ptr(new RotateHeadPacket()); + } + virtual int getId() { return 35; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/ServerAuthDataPacket.h b/Minecraft.World/Network/Packets/ServerAuthDataPacket.h index 176daaf4e..8fbc0f733 100644 --- a/Minecraft.World/Network/Packets/ServerAuthDataPacket.h +++ b/Minecraft.World/Network/Packets/ServerAuthDataPacket.h @@ -2,8 +2,7 @@ #include "Packet.h" -class ServerAuthDataPacket : public Packet -{ +class ServerAuthDataPacket : public Packet { #if 0 private String serverId; private PublicKey publicKey; diff --git a/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.cpp b/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.cpp index 103dec57b..441117163 100644 --- a/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.cpp +++ b/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.cpp @@ -5,48 +5,42 @@ #include "PacketListener.h" #include "ServerSettingsChangedPacket.h" - - -const int ServerSettingsChangedPacket::HOST_DIFFICULTY = 0; -const int ServerSettingsChangedPacket::HOST_OPTIONS = 1; +const int ServerSettingsChangedPacket::HOST_DIFFICULTY = 0; +const int ServerSettingsChangedPacket::HOST_OPTIONS = 1; const int ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS = 2; -ServerSettingsChangedPacket::~ServerSettingsChangedPacket() -{ +ServerSettingsChangedPacket::~ServerSettingsChangedPacket() {} + +ServerSettingsChangedPacket::ServerSettingsChangedPacket() { + action = HOST_DIFFICULTY; + data = 1; } -ServerSettingsChangedPacket::ServerSettingsChangedPacket() -{ - action = HOST_DIFFICULTY; - data = 1; +ServerSettingsChangedPacket::ServerSettingsChangedPacket(char action, + unsigned int data) { + this->action = action; + this->data = data; + + // app.DebugPrintf("ServerSettingsChangedPacket - Difficulty = + // %d",difficulty); } -ServerSettingsChangedPacket::ServerSettingsChangedPacket(char action, unsigned int data) -{ - this->action = action; - this->data = data; - - //app.DebugPrintf("ServerSettingsChangedPacket - Difficulty = %d",difficulty); +void ServerSettingsChangedPacket::handle(PacketListener* listener) { + listener->handleServerSettingsChanged(shared_from_this()); } -void ServerSettingsChangedPacket::handle(PacketListener *listener) +void ServerSettingsChangedPacket::read( + DataInputStream* dis) // throws IOException { - listener->handleServerSettingsChanged(shared_from_this()); + action = dis->read(); + data = dis->readInt(); } -void ServerSettingsChangedPacket::read(DataInputStream *dis) //throws IOException +void ServerSettingsChangedPacket::write( + DataOutputStream* dos) // throws IOException { - action = dis->read(); - data = dis->readInt(); + dos->write(action); + dos->writeInt(data); } -void ServerSettingsChangedPacket::write(DataOutputStream *dos) // throws IOException -{ - dos->write(action); - dos->writeInt(data); -} - -int ServerSettingsChangedPacket::getEstimatedSize() -{ - return 2; -} +int ServerSettingsChangedPacket::getEstimatedSize() { return 2; } diff --git a/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.h b/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.h index b3246523a..ffe9a597d 100644 --- a/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.h +++ b/Minecraft.World/Network/Packets/ServerSettingsChangedPacket.h @@ -2,30 +2,31 @@ // 4J ADDED THIS PACKET - - #include "Packet.h" -class ServerSettingsChangedPacket : public Packet, public std::enable_shared_from_this -{ +class ServerSettingsChangedPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int HOST_DIFFICULTY; - static const int HOST_OPTIONS; - static const int HOST_IN_GAME_SETTINGS; + static const int HOST_DIFFICULTY; + static const int HOST_OPTIONS; + static const int HOST_IN_GAME_SETTINGS; - char action; - unsigned int data; + char action; + unsigned int data; - ServerSettingsChangedPacket(); - ~ServerSettingsChangedPacket(); - ServerSettingsChangedPacket(char action, unsigned int data); + ServerSettingsChangedPacket(); + ~ServerSettingsChangedPacket(); + ServerSettingsChangedPacket(char action, unsigned int data); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new ServerSettingsChangedPacket()); } - virtual int getId() { return 153; } + static std::shared_ptr create() { + return std::shared_ptr(new ServerSettingsChangedPacket()); + } + virtual int getId() { return 153; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetCarriedItemPacket.cpp b/Minecraft.World/Network/Packets/SetCarriedItemPacket.cpp index 3209b8aac..886cf1ae5 100644 --- a/Minecraft.World/Network/Packets/SetCarriedItemPacket.cpp +++ b/Minecraft.World/Network/Packets/SetCarriedItemPacket.cpp @@ -4,44 +4,28 @@ #include "PacketListener.h" #include "SetCarriedItemPacket.h" +SetCarriedItemPacket::SetCarriedItemPacket() { slot = 0; } +SetCarriedItemPacket::SetCarriedItemPacket(int slot) { this->slot = slot; } -SetCarriedItemPacket::SetCarriedItemPacket() +void SetCarriedItemPacket::read(DataInputStream* dis) // throws IOException { - slot = 0; + slot = dis->readShort(); } -SetCarriedItemPacket::SetCarriedItemPacket(int slot) +void SetCarriedItemPacket::write(DataOutputStream* dos) // throws IOException { - this->slot = slot; + dos->writeShort(slot); } -void SetCarriedItemPacket::read(DataInputStream *dis) //throws IOException -{ - slot = dis->readShort(); +void SetCarriedItemPacket::handle(PacketListener* listener) { + listener->handleSetCarriedItem(shared_from_this()); } -void SetCarriedItemPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeShort(slot); -} +int SetCarriedItemPacket::getEstimatedSize() { return 2; } -void SetCarriedItemPacket::handle(PacketListener *listener) -{ - listener->handleSetCarriedItem(shared_from_this()); -} +bool SetCarriedItemPacket::canBeInvalidated() { return true; } -int SetCarriedItemPacket::getEstimatedSize() -{ - return 2; -} - -bool SetCarriedItemPacket::canBeInvalidated() -{ - return true; -} - -bool SetCarriedItemPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; +bool SetCarriedItemPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetCarriedItemPacket.h b/Minecraft.World/Network/Packets/SetCarriedItemPacket.h index 26c9bbc92..132466493 100644 --- a/Minecraft.World/Network/Packets/SetCarriedItemPacket.h +++ b/Minecraft.World/Network/Packets/SetCarriedItemPacket.h @@ -1,24 +1,26 @@ #pragma once - #include "Packet.h" -class SetCarriedItemPacket : public Packet, public std::enable_shared_from_this -{ +class SetCarriedItemPacket + : public Packet, + public std::enable_shared_from_this { public: - int slot; + int slot; - SetCarriedItemPacket(); - SetCarriedItemPacket(int slot); + SetCarriedItemPacket(); + SetCarriedItemPacket(int slot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new SetCarriedItemPacket()); } - virtual int getId() { return 16; } + static std::shared_ptr create() { + return std::shared_ptr(new SetCarriedItemPacket()); + } + virtual int getId() { return 16; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.cpp b/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.cpp index 6f0a1f0e6..85e09bbcc 100644 --- a/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.cpp +++ b/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.cpp @@ -3,40 +3,31 @@ #include "PacketListener.h" #include "SetCreativeModeSlotPacket.h" - - -SetCreativeModeSlotPacket::SetCreativeModeSlotPacket() -{ - this->slotNum = 0; - this->item = nullptr; +SetCreativeModeSlotPacket::SetCreativeModeSlotPacket() { + this->slotNum = 0; + this->item = nullptr; } -SetCreativeModeSlotPacket::SetCreativeModeSlotPacket(int slotNum, std::shared_ptr item) -{ - this->slotNum = slotNum; - // 4J - take copy of item as we want our packets to have full ownership of any referenced data - this->item = item ? item->copy() : std::shared_ptr(); +SetCreativeModeSlotPacket::SetCreativeModeSlotPacket( + int slotNum, std::shared_ptr item) { + this->slotNum = slotNum; + // 4J - take copy of item as we want our packets to have full ownership of + // any referenced data + this->item = item ? item->copy() : std::shared_ptr(); } -void SetCreativeModeSlotPacket::handle(PacketListener *listener) -{ - listener->handleSetCreativeModeSlot(shared_from_this()); +void SetCreativeModeSlotPacket::handle(PacketListener* listener) { + listener->handleSetCreativeModeSlot(shared_from_this()); } -void SetCreativeModeSlotPacket::read(DataInputStream *dis) -{ - slotNum = dis->readShort(); - item = readItem(dis); +void SetCreativeModeSlotPacket::read(DataInputStream* dis) { + slotNum = dis->readShort(); + item = readItem(dis); } -void SetCreativeModeSlotPacket::write(DataOutputStream *dos) -{ - dos->writeShort(slotNum); - writeItem(item, dos); - +void SetCreativeModeSlotPacket::write(DataOutputStream* dos) { + dos->writeShort(slotNum); + writeItem(item, dos); } -int SetCreativeModeSlotPacket::getEstimatedSize() -{ - return 8; -} \ No newline at end of file +int SetCreativeModeSlotPacket::getEstimatedSize() { return 8; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.h b/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.h index 81edf128a..396e158c9 100644 --- a/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.h +++ b/Minecraft.World/Network/Packets/SetCreativeModeSlotPacket.h @@ -2,22 +2,24 @@ #include "Packet.h" -class SetCreativeModeSlotPacket : public Packet, public std::enable_shared_from_this -{ - public: - int slotNum; - std::shared_ptr item; +class SetCreativeModeSlotPacket + : public Packet, + public std::enable_shared_from_this { +public: + int slotNum; + std::shared_ptr item; - SetCreativeModeSlotPacket(); - SetCreativeModeSlotPacket(int slotNum, std::shared_ptr item); - - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + SetCreativeModeSlotPacket(); + SetCreativeModeSlotPacket(int slotNum, std::shared_ptr item); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetCreativeModeSlotPacket()); } - virtual int getId() { return 107; } + static std::shared_ptr create() { + return std::shared_ptr(new SetCreativeModeSlotPacket()); + } + virtual int getId() { return 107; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetEntityDataPacket.cpp b/Minecraft.World/Network/Packets/SetEntityDataPacket.cpp index 3ea0e1824..f96148210 100644 --- a/Minecraft.World/Network/Packets/SetEntityDataPacket.cpp +++ b/Minecraft.World/Network/Packets/SetEntityDataPacket.cpp @@ -5,60 +5,44 @@ #include "PacketListener.h" #include "SetEntityDataPacket.h" - - -SetEntityDataPacket::SetEntityDataPacket() -{ - id = -1; - packedItems = NULL; +SetEntityDataPacket::SetEntityDataPacket() { + id = -1; + packedItems = NULL; } -SetEntityDataPacket::~SetEntityDataPacket() -{ - delete packedItems; +SetEntityDataPacket::~SetEntityDataPacket() { delete packedItems; } + +SetEntityDataPacket::SetEntityDataPacket( + int id, std::shared_ptr entityData, bool notJustDirty) { + this->id = id; + if (notJustDirty) { + this->packedItems = entityData->getAll(); + } else { + this->packedItems = entityData->packDirty(); + } } -SetEntityDataPacket::SetEntityDataPacket(int id, std::shared_ptr entityData, bool notJustDirty) +void SetEntityDataPacket::read(DataInputStream* dis) // throws IOException { - this->id = id; - if(notJustDirty) - { - this->packedItems = entityData->getAll(); - } - else - { - this->packedItems = entityData->packDirty(); - } + id = dis->readInt(); + packedItems = SynchedEntityData::unpack(dis); } -void SetEntityDataPacket::read(DataInputStream *dis) //throws IOException +void SetEntityDataPacket::write(DataOutputStream* dos) // throws IOException { - id = dis->readInt(); - packedItems = SynchedEntityData::unpack(dis); + dos->writeInt(id); + SynchedEntityData::pack(packedItems, dos); } -void SetEntityDataPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeInt(id); - SynchedEntityData::pack(packedItems, dos); +void SetEntityDataPacket::handle(PacketListener* listener) { + listener->handleSetEntityData(shared_from_this()); } -void SetEntityDataPacket::handle(PacketListener *listener) -{ - listener->handleSetEntityData(shared_from_this()); -} +int SetEntityDataPacket::getEstimatedSize() { return 5; } -int SetEntityDataPacket::getEstimatedSize() -{ - return 5; -} +bool SetEntityDataPacket::isAync() { return true; } -bool SetEntityDataPacket::isAync() -{ - return true; -} - -std::vector > *SetEntityDataPacket::getUnpackedData() -{ - return packedItems; +std::vector >* +SetEntityDataPacket::getUnpackedData() { + return packedItems; } diff --git a/Minecraft.World/Network/Packets/SetEntityDataPacket.h b/Minecraft.World/Network/Packets/SetEntityDataPacket.h index 9ac726b6d..0833b9a9a 100644 --- a/Minecraft.World/Network/Packets/SetEntityDataPacket.h +++ b/Minecraft.World/Network/Packets/SetEntityDataPacket.h @@ -1,31 +1,35 @@ #pragma once - #include "Packet.h" #include "../../Entities/SyncedEntityData.h" -class SetEntityDataPacket : public Packet, public std::enable_shared_from_this -{ +class SetEntityDataPacket + : public Packet, + public std::enable_shared_from_this { public: - int id; + int id; private: - std::vector > *packedItems; + std::vector >* packedItems; public: - SetEntityDataPacket(); - ~SetEntityDataPacket(); - SetEntityDataPacket(int id, std::shared_ptr, bool notJustDirty); + SetEntityDataPacket(); + ~SetEntityDataPacket(); + SetEntityDataPacket(int id, std::shared_ptr, + bool notJustDirty); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool isAync(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool isAync(); - std::vector > *getUnpackedData(); + std::vector >* + getUnpackedData(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetEntityDataPacket()); } - virtual int getId() { return 40; } + static std::shared_ptr create() { + return std::shared_ptr(new SetEntityDataPacket()); + } + virtual int getId() { return 40; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetEntityMotionPacket.cpp b/Minecraft.World/Network/Packets/SetEntityMotionPacket.cpp index bff87c5bd..4e37d3eb1 100644 --- a/Minecraft.World/Network/Packets/SetEntityMotionPacket.cpp +++ b/Minecraft.World/Network/Packets/SetEntityMotionPacket.cpp @@ -5,109 +5,87 @@ #include "PacketListener.h" #include "SetEntityMotionPacket.h" - - -void SetEntityMotionPacket::_init(int id, double xd, double yd, double zd) -{ - this->id = id; - double m = 3.9; - if (xd < -m) xd = -m; - if (yd < -m) yd = -m; - if (zd < -m) zd = -m; - if (xd > m) xd = m; - if (yd > m) yd = m; - if (zd > m) zd = m; - xa = (int) (xd * 8000.0); - ya = (int) (yd * 8000.0); - za = (int) (zd * 8000.0); - // 4J - if we could transmit this as bytes (in 1/16 accuracy) then flag to do so - if( ( xa >= (-128 * 16 ) ) && ( ya >= (-128 * 16 ) ) && ( za >= (-128 * 16 ) ) && - ( xa < (128 * 16 ) ) && ( ya < (128 * 16 ) ) && ( za < (128 * 16 ) ) ) - { - useBytes = true; - } - else - { - useBytes = false; - } +void SetEntityMotionPacket::_init(int id, double xd, double yd, double zd) { + this->id = id; + double m = 3.9; + if (xd < -m) xd = -m; + if (yd < -m) yd = -m; + if (zd < -m) zd = -m; + if (xd > m) xd = m; + if (yd > m) yd = m; + if (zd > m) zd = m; + xa = (int)(xd * 8000.0); + ya = (int)(yd * 8000.0); + za = (int)(zd * 8000.0); + // 4J - if we could transmit this as bytes (in 1/16 accuracy) then flag to + // do so + if ((xa >= (-128 * 16)) && (ya >= (-128 * 16)) && (za >= (-128 * 16)) && + (xa < (128 * 16)) && (ya < (128 * 16)) && (za < (128 * 16))) { + useBytes = true; + } else { + useBytes = false; + } } -SetEntityMotionPacket::SetEntityMotionPacket() -{ - _init(0, 0.0f, 0.0f, 0.0f); +SetEntityMotionPacket::SetEntityMotionPacket() { _init(0, 0.0f, 0.0f, 0.0f); } + +SetEntityMotionPacket::SetEntityMotionPacket(std::shared_ptr e) { + _init(e->entityId, e->xd, e->yd, e->zd); } -SetEntityMotionPacket::SetEntityMotionPacket(std::shared_ptr e) -{ - _init(e->entityId, e->xd, e->yd, e->zd); +SetEntityMotionPacket::SetEntityMotionPacket(int id, double xd, double yd, + double zd) { + _init(id, xd, yd, zd); } -SetEntityMotionPacket::SetEntityMotionPacket(int id, double xd, double yd, double zd) +void SetEntityMotionPacket::read(DataInputStream* dis) // throws IOException { - _init(id, xd, yd, zd); + short idAndFlag = dis->readShort(); + id = idAndFlag & 0x07ff; + if (idAndFlag & 0x0800) { + xa = (int)dis->readByte(); + ya = (int)dis->readByte(); + za = (int)dis->readByte(); + xa = (xa << 24) >> 24; + ya = (ya << 24) >> 24; + za = (za << 24) >> 24; + xa *= 16; + ya *= 16; + za *= 16; + useBytes = true; + } else { + xa = dis->readShort(); + ya = dis->readShort(); + za = dis->readShort(); + useBytes = false; + } } -void SetEntityMotionPacket::read(DataInputStream *dis) //throws IOException +void SetEntityMotionPacket::write(DataOutputStream* dos) // throws IOException { - short idAndFlag = dis->readShort(); - id = idAndFlag & 0x07ff; - if( idAndFlag & 0x0800 ) - { - xa = (int)dis->readByte(); - ya = (int)dis->readByte(); - za = (int)dis->readByte(); - xa = ( xa << 24 ) >> 24; - ya = ( ya << 24 ) >> 24; - za = ( za << 24 ) >> 24; - xa *= 16; - ya *= 16; - za *= 16; - useBytes = true; - } - else - { - xa = dis->readShort(); - ya = dis->readShort(); - za = dis->readShort(); - useBytes = false; - } + if (useBytes) { + dos->writeShort(id | 0x800); + dos->writeByte(xa / 16); + dos->writeByte(ya / 16); + dos->writeByte(za / 16); + } else { + dos->writeShort(id); + dos->writeShort(xa); + dos->writeShort(ya); + dos->writeShort(za); + } } -void SetEntityMotionPacket::write(DataOutputStream *dos) //throws IOException -{ - if( useBytes ) - { - dos->writeShort(id | 0x800); - dos->writeByte(xa/16); - dos->writeByte(ya/16); - dos->writeByte(za/16); - } - else - { - dos->writeShort(id); - dos->writeShort(xa); - dos->writeShort(ya); - dos->writeShort(za); - } +void SetEntityMotionPacket::handle(PacketListener* listener) { + listener->handleSetEntityMotion(shared_from_this()); } -void SetEntityMotionPacket::handle(PacketListener *listener) -{ - listener->handleSetEntityMotion(shared_from_this()); -} +int SetEntityMotionPacket::getEstimatedSize() { return useBytes ? 5 : 8; } -int SetEntityMotionPacket::getEstimatedSize() -{ - return useBytes ? 5 : 8; -} +bool SetEntityMotionPacket::canBeInvalidated() { return true; } -bool SetEntityMotionPacket::canBeInvalidated() -{ - return true; -} - -bool SetEntityMotionPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->id == id; +bool SetEntityMotionPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->id == id; } diff --git a/Minecraft.World/Network/Packets/SetEntityMotionPacket.h b/Minecraft.World/Network/Packets/SetEntityMotionPacket.h index 537c5a4fd..bea97bb05 100644 --- a/Minecraft.World/Network/Packets/SetEntityMotionPacket.h +++ b/Minecraft.World/Network/Packets/SetEntityMotionPacket.h @@ -1,31 +1,33 @@ #pragma once - #include "Packet.h" -class SetEntityMotionPacket : public Packet, public std::enable_shared_from_this -{ +class SetEntityMotionPacket + : public Packet, + public std::enable_shared_from_this { public: - int id; + int id; int xa, ya, za; - bool useBytes; // 4J added + bool useBytes; // 4J added private: - void _init(int id, double xd, double yd, double zd); + void _init(int id, double xd, double yd, double zd); public: - SetEntityMotionPacket(); - SetEntityMotionPacket(std::shared_ptr e); - SetEntityMotionPacket(int id, double xd, double yd, double zd); + SetEntityMotionPacket(); + SetEntityMotionPacket(std::shared_ptr e); + SetEntityMotionPacket(int id, double xd, double yd, double zd); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new SetEntityMotionPacket()); } - virtual int getId() { return 28; } + static std::shared_ptr create() { + return std::shared_ptr(new SetEntityMotionPacket()); + } + virtual int getId() { return 28; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetEquippedItemPacket.cpp b/Minecraft.World/Network/Packets/SetEquippedItemPacket.cpp index af547fbf9..866ff47a7 100644 --- a/Minecraft.World/Network/Packets/SetEquippedItemPacket.cpp +++ b/Minecraft.World/Network/Packets/SetEquippedItemPacket.cpp @@ -5,65 +5,60 @@ #include "PacketListener.h" #include "SetEquippedItemPacket.h" - - -SetEquippedItemPacket::SetEquippedItemPacket() -{ - entity = 0; - slot = 0; - item = nullptr; +SetEquippedItemPacket::SetEquippedItemPacket() { + entity = 0; + slot = 0; + item = nullptr; } -SetEquippedItemPacket::SetEquippedItemPacket(int entity, int slot, std::shared_ptr item) -{ - this->entity = entity; - this->slot = slot; +SetEquippedItemPacket::SetEquippedItemPacket( + int entity, int slot, std::shared_ptr item) { + this->entity = entity; + this->slot = slot; - // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - this->item = item == NULL ? nullptr : item->copy(); + // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer + // Encountered: TU7: Content: Art: Aura of enchanted item is not displayed + // for other players in online game + this->item = item == NULL ? nullptr : item->copy(); } -void SetEquippedItemPacket::read(DataInputStream *dis) //throws IOException +void SetEquippedItemPacket::read(DataInputStream* dis) // throws IOException { - entity = dis->readInt(); - slot = dis->readShort(); + entity = dis->readInt(); + slot = dis->readShort(); - // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - item = readItem(dis); + // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer + // Encountered: TU7: Content: Art: Aura of enchanted item is not displayed + // for other players in online game + item = readItem(dis); } -void SetEquippedItemPacket::write(DataOutputStream *dos) //throws IOException +void SetEquippedItemPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(entity); - dos->writeShort(slot); + dos->writeInt(entity); + dos->writeShort(slot); - // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - writeItem(item, dos); + // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer + // Encountered: TU7: Content: Art: Aura of enchanted item is not displayed + // for other players in online game + writeItem(item, dos); } -void SetEquippedItemPacket::handle(PacketListener *listener) -{ - listener->handleSetEquippedItem(shared_from_this()); +void SetEquippedItemPacket::handle(PacketListener* listener) { + listener->handleSetEquippedItem(shared_from_this()); } -int SetEquippedItemPacket::getEstimatedSize() -{ - return 4 + 2 * 2; -} +int SetEquippedItemPacket::getEstimatedSize() { return 4 + 2 * 2; } -// 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game -std::shared_ptr SetEquippedItemPacket::getItem() -{ - return item; -} +// 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: TU7: +// Content: Art: Aura of enchanted item is not displayed for other players in +// online game +std::shared_ptr SetEquippedItemPacket::getItem() { return item; } -bool SetEquippedItemPacket::canBeInvalidated() -{ - return true; -} +bool SetEquippedItemPacket::canBeInvalidated() { return true; } -bool SetEquippedItemPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->entity == entity && target->slot == slot; +bool SetEquippedItemPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->entity == entity && target->slot == slot; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetEquippedItemPacket.h b/Minecraft.World/Network/Packets/SetEquippedItemPacket.h index 512763ed5..f366541cc 100644 --- a/Minecraft.World/Network/Packets/SetEquippedItemPacket.h +++ b/Minecraft.World/Network/Packets/SetEquippedItemPacket.h @@ -1,33 +1,40 @@ #pragma once - #include "Packet.h" -class SetEquippedItemPacket : public Packet, public std::enable_shared_from_this -{ +class SetEquippedItemPacket + : public Packet, + public std::enable_shared_from_this { public: - int entity; + int entity; int slot; private: - // 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - std::shared_ptr item; + // 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: + // TU7: Content: Art: Aura of enchanted item is not displayed for other + // players in online game + std::shared_ptr item; public: - SetEquippedItemPacket(); - SetEquippedItemPacket(int entity, int slot, std::shared_ptr item); + SetEquippedItemPacket(); + SetEquippedItemPacket(int entity, int slot, + std::shared_ptr item); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); virtual bool isInvalidatedBy(std::shared_ptr packet); - - // 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - std::shared_ptr getItem(); + + // 4J Stu - Brought forward from 1.3 to fix #64688 - Customer Encountered: + // TU7: Content: Art: Aura of enchanted item is not displayed for other + // players in online game + std::shared_ptr getItem(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetEquippedItemPacket()); } - virtual int getId() { return 5; } + static std::shared_ptr create() { + return std::shared_ptr(new SetEquippedItemPacket()); + } + virtual int getId() { return 5; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetExperiencePacket.cpp b/Minecraft.World/Network/Packets/SetExperiencePacket.cpp index 4b8e43063..01b679498 100644 --- a/Minecraft.World/Network/Packets/SetExperiencePacket.cpp +++ b/Minecraft.World/Network/Packets/SetExperiencePacket.cpp @@ -3,57 +3,42 @@ #include "PacketListener.h" #include "../../IO/Streams/InputOutputStream.h" - - -SetExperiencePacket::SetExperiencePacket() -{ - this->experienceProgress = 0; - this->totalExperience = 0; - this->experienceLevel = 0; +SetExperiencePacket::SetExperiencePacket() { + this->experienceProgress = 0; + this->totalExperience = 0; + this->experienceLevel = 0; } -SetExperiencePacket::SetExperiencePacket(float experienceProgress, int totalExperience, int experienceLevel) -{ - this->experienceProgress = experienceProgress; - this->totalExperience = totalExperience; - this->experienceLevel = experienceLevel; +SetExperiencePacket::SetExperiencePacket(float experienceProgress, + int totalExperience, + int experienceLevel) { + this->experienceProgress = experienceProgress; + this->totalExperience = totalExperience; + this->experienceLevel = experienceLevel; } -void SetExperiencePacket::read(DataInputStream *dis) -{ - experienceProgress = dis->readFloat(); - experienceLevel = dis->readShort(); - totalExperience = dis->readShort(); +void SetExperiencePacket::read(DataInputStream* dis) { + experienceProgress = dis->readFloat(); + experienceLevel = dis->readShort(); + totalExperience = dis->readShort(); } -void SetExperiencePacket::write(DataOutputStream *dos) -{ - dos->writeFloat(experienceProgress); - dos->writeShort(experienceLevel); - dos->writeShort(totalExperience); +void SetExperiencePacket::write(DataOutputStream* dos) { + dos->writeFloat(experienceProgress); + dos->writeShort(experienceLevel); + dos->writeShort(totalExperience); } -void SetExperiencePacket::handle(PacketListener *listener) -{ - listener->handleSetExperience(shared_from_this()); +void SetExperiencePacket::handle(PacketListener* listener) { + listener->handleSetExperience(shared_from_this()); } -int SetExperiencePacket::getEstimatedSize() -{ - return 8; +int SetExperiencePacket::getEstimatedSize() { return 8; } + +bool SetExperiencePacket::canBeInvalidated() { return true; } + +bool SetExperiencePacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } -bool SetExperiencePacket::canBeInvalidated() -{ - return true; -} - -bool SetExperiencePacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; -} - -bool SetExperiencePacket::isAync() -{ - return true; -} \ No newline at end of file +bool SetExperiencePacket::isAync() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetExperiencePacket.h b/Minecraft.World/Network/Packets/SetExperiencePacket.h index 86c13e842..e46898537 100644 --- a/Minecraft.World/Network/Packets/SetExperiencePacket.h +++ b/Minecraft.World/Network/Packets/SetExperiencePacket.h @@ -2,25 +2,29 @@ #include "Packet.h" -class SetExperiencePacket : public Packet, public std::enable_shared_from_this -{ +class SetExperiencePacket + : public Packet, + public std::enable_shared_from_this { public: - float experienceProgress; - int totalExperience; - int experienceLevel; + float experienceProgress; + int totalExperience; + int experienceLevel; - SetExperiencePacket(); - SetExperiencePacket(float experienceProgress, int totalExperience, int experienceLevel); + SetExperiencePacket(); + SetExperiencePacket(float experienceProgress, int totalExperience, + int experienceLevel); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetExperiencePacket()); } - virtual int getId() { return 43; } + static std::shared_ptr create() { + return std::shared_ptr(new SetExperiencePacket()); + } + virtual int getId() { return 43; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetHealthPacket.cpp b/Minecraft.World/Network/Packets/SetHealthPacket.cpp index 3d9425302..ccd8ac338 100644 --- a/Minecraft.World/Network/Packets/SetHealthPacket.cpp +++ b/Minecraft.World/Network/Packets/SetHealthPacket.cpp @@ -5,62 +5,52 @@ #include "SetHealthPacket.h" #include "../../../Minecraft.Client/Platform/Common/Telemetry/TelemetryManager.h" +SetHealthPacket::SetHealthPacket() { + this->health = 0; + this->food = 0; + this->saturation = 0; -SetHealthPacket::SetHealthPacket() -{ - this->health = 0; - this->food = 0; - this->saturation = 0; - - this->damageSource = eTelemetryChallenges_Unknown; + this->damageSource = eTelemetryChallenges_Unknown; } -SetHealthPacket::SetHealthPacket(int health, int food, float saturation, ETelemetryChallenges damageSource) -{ - this->health = health; - this->food = food; - this->saturation = saturation; - // this.exhaustion = exhaustion; // 4J - Original comment +SetHealthPacket::SetHealthPacket(int health, int food, float saturation, + ETelemetryChallenges damageSource) { + this->health = health; + this->food = food; + this->saturation = saturation; + // this.exhaustion = exhaustion; // 4J - Original comment - this->damageSource = damageSource; + this->damageSource = damageSource; } -void SetHealthPacket::read(DataInputStream *dis) //throws IOException +void SetHealthPacket::read(DataInputStream* dis) // throws IOException { - health = dis->readShort(); - food = dis->readShort(); - saturation = dis->readFloat(); - // exhaustion = dis.readFloat(); + health = dis->readShort(); + food = dis->readShort(); + saturation = dis->readFloat(); + // exhaustion = dis.readFloat(); - damageSource = (ETelemetryChallenges)dis->readByte(); + damageSource = (ETelemetryChallenges)dis->readByte(); } -void SetHealthPacket::write(DataOutputStream *dos) //throws IOException +void SetHealthPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeShort(health); - dos->writeShort(food); - dos->writeFloat(saturation); - // dos.writeFloat(exhaustion); + dos->writeShort(health); + dos->writeShort(food); + dos->writeFloat(saturation); + // dos.writeFloat(exhaustion); - dos->writeByte(damageSource); + dos->writeByte(damageSource); } -void SetHealthPacket::handle(PacketListener *listener) -{ - listener->handleSetHealth(shared_from_this()); +void SetHealthPacket::handle(PacketListener* listener) { + listener->handleSetHealth(shared_from_this()); } -int SetHealthPacket::getEstimatedSize() -{ - return 9; -} +int SetHealthPacket::getEstimatedSize() { return 9; } -bool SetHealthPacket::canBeInvalidated() -{ - return true; -} +bool SetHealthPacket::canBeInvalidated() { return true; } -bool SetHealthPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; +bool SetHealthPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } diff --git a/Minecraft.World/Network/Packets/SetHealthPacket.h b/Minecraft.World/Network/Packets/SetHealthPacket.h index 111e9e0b9..2d4deff41 100644 --- a/Minecraft.World/Network/Packets/SetHealthPacket.h +++ b/Minecraft.World/Network/Packets/SetHealthPacket.h @@ -1,30 +1,31 @@ #pragma once - #include "Packet.h" -class SetHealthPacket : public Packet, public std::enable_shared_from_this -{ +class SetHealthPacket : public Packet, + public std::enable_shared_from_this { public: - int health; - int food; - float saturation; - // public float exhaustion; // 4J - Original comment + int health; + int food; + float saturation; + // public float exhaustion; // 4J - Original comment - ETelemetryChallenges damageSource; // 4J Added + ETelemetryChallenges damageSource; // 4J Added - SetHealthPacket(); - SetHealthPacket(int health, int food, float saturation, ETelemetryChallenges damageSource); + SetHealthPacket(); + SetHealthPacket(int health, int food, float saturation, + ETelemetryChallenges damageSource); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new SetHealthPacket()); } - virtual int getId() { return 8; } + static std::shared_ptr create() { + return std::shared_ptr(new SetHealthPacket()); + } + virtual int getId() { return 8; } }; - diff --git a/Minecraft.World/Network/Packets/SetRidingPacket.cpp b/Minecraft.World/Network/Packets/SetRidingPacket.cpp index 356127b51..1db4914a5 100644 --- a/Minecraft.World/Network/Packets/SetRidingPacket.cpp +++ b/Minecraft.World/Network/Packets/SetRidingPacket.cpp @@ -5,49 +5,39 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "SetRidingPacket.h" - - -SetRidingPacket::SetRidingPacket() -{ - riderId = -1; - riddenId = -1; +SetRidingPacket::SetRidingPacket() { + riderId = -1; + riddenId = -1; } -SetRidingPacket::SetRidingPacket(std::shared_ptr rider, std::shared_ptr riding) -{ - this->riderId = rider->entityId; - this->riddenId = riding != NULL ? riding->entityId : -1; +SetRidingPacket::SetRidingPacket(std::shared_ptr rider, + std::shared_ptr riding) { + this->riderId = rider->entityId; + this->riddenId = riding != NULL ? riding->entityId : -1; } -int SetRidingPacket::getEstimatedSize() +int SetRidingPacket::getEstimatedSize() { return 8; } + +void SetRidingPacket::read(DataInputStream* dis) // throws IOException { - return 8; + riderId = dis->readInt(); + riddenId = dis->readInt(); } -void SetRidingPacket::read(DataInputStream *dis) //throws IOException +void SetRidingPacket::write(DataOutputStream* dos) // throws IOException { - riderId = dis->readInt(); - riddenId = dis->readInt(); + dos->writeInt(riderId); + dos->writeInt(riddenId); } -void SetRidingPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeInt(riderId); - dos->writeInt(riddenId); +void SetRidingPacket::handle(PacketListener* listener) { + listener->handleRidePacket(shared_from_this()); } -void SetRidingPacket::handle(PacketListener *listener) -{ - listener->handleRidePacket(shared_from_this()); -} +bool SetRidingPacket::canBeInvalidated() { return true; } -bool SetRidingPacket::canBeInvalidated() -{ - return true; -} - -bool SetRidingPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->riderId == riderId; +bool SetRidingPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->riderId == riderId; } diff --git a/Minecraft.World/Network/Packets/SetRidingPacket.h b/Minecraft.World/Network/Packets/SetRidingPacket.h index 027e38ee0..74095d260 100644 --- a/Minecraft.World/Network/Packets/SetRidingPacket.h +++ b/Minecraft.World/Network/Packets/SetRidingPacket.h @@ -1,25 +1,26 @@ #pragma once - #include "Packet.h" -class SetRidingPacket : public Packet, public std::enable_shared_from_this -{ +class SetRidingPacket : public Packet, + public std::enable_shared_from_this { public: - int riderId, riddenId; + int riderId, riddenId; - SetRidingPacket(); - SetRidingPacket(std::shared_ptr rider, std::shared_ptr riding); + SetRidingPacket(); + SetRidingPacket(std::shared_ptr rider, + std::shared_ptr riding); - virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual bool canBeInvalidated(); + virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual bool canBeInvalidated(); virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new SetRidingPacket()); } - virtual int getId() { return 39; } - + static std::shared_ptr create() { + return std::shared_ptr(new SetRidingPacket()); + } + virtual int getId() { return 39; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetSpawnPositionPacket.cpp b/Minecraft.World/Network/Packets/SetSpawnPositionPacket.cpp index 6640fb78f..591f83fdf 100644 --- a/Minecraft.World/Network/Packets/SetSpawnPositionPacket.cpp +++ b/Minecraft.World/Network/Packets/SetSpawnPositionPacket.cpp @@ -4,57 +4,42 @@ #include "PacketListener.h" #include "SetSpawnPositionPacket.h" - - -SetSpawnPositionPacket::SetSpawnPositionPacket() -{ - x = 0; - y = 0; - z = 0; +SetSpawnPositionPacket::SetSpawnPositionPacket() { + x = 0; + y = 0; + z = 0; } -SetSpawnPositionPacket::SetSpawnPositionPacket(int x, int y, int z) -{ - this->x = x; - this->y = y; - this->z = z; +SetSpawnPositionPacket::SetSpawnPositionPacket(int x, int y, int z) { + this->x = x; + this->y = y; + this->z = z; } -void SetSpawnPositionPacket::read(DataInputStream *dis) //throws IOException +void SetSpawnPositionPacket::read(DataInputStream* dis) // throws IOException { - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); } -void SetSpawnPositionPacket::write(DataOutputStream *dos) //throws IOException +void SetSpawnPositionPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); } -void SetSpawnPositionPacket::handle(PacketListener *listener) -{ - listener->handleSetSpawn(shared_from_this()); +void SetSpawnPositionPacket::handle(PacketListener* listener) { + listener->handleSetSpawn(shared_from_this()); } -int SetSpawnPositionPacket::getEstimatedSize() -{ - return 3*4; +int SetSpawnPositionPacket::getEstimatedSize() { return 3 * 4; } + +bool SetSpawnPositionPacket::canBeInvalidated() { return true; } + +bool SetSpawnPositionPacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } -bool SetSpawnPositionPacket::canBeInvalidated() -{ - return true; -} - -bool SetSpawnPositionPacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; -} - -bool SetSpawnPositionPacket::isAync() -{ - return false; -} \ No newline at end of file +bool SetSpawnPositionPacket::isAync() { return false; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetSpawnPositionPacket.h b/Minecraft.World/Network/Packets/SetSpawnPositionPacket.h index 3e995e9a4..e245dae33 100644 --- a/Minecraft.World/Network/Packets/SetSpawnPositionPacket.h +++ b/Minecraft.World/Network/Packets/SetSpawnPositionPacket.h @@ -1,25 +1,27 @@ #pragma once - #include "Packet.h" -class SetSpawnPositionPacket : public Packet, public std::enable_shared_from_this -{ +class SetSpawnPositionPacket + : public Packet, + public std::enable_shared_from_this { public: - int x, y, z; + int x, y, z; - SetSpawnPositionPacket(); - SetSpawnPositionPacket(int x, int y, int z); + SetSpawnPositionPacket(); + SetSpawnPositionPacket(int x, int y, int z); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetSpawnPositionPacket()); } - virtual int getId() { return 6; } + static std::shared_ptr create() { + return std::shared_ptr(new SetSpawnPositionPacket()); + } + virtual int getId() { return 6; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetTimePacket.cpp b/Minecraft.World/Network/Packets/SetTimePacket.cpp index cf5f87718..8661c352f 100644 --- a/Minecraft.World/Network/Packets/SetTimePacket.cpp +++ b/Minecraft.World/Network/Packets/SetTimePacket.cpp @@ -4,49 +4,30 @@ #include "PacketListener.h" #include "SetTimePacket.h" +SetTimePacket::SetTimePacket() { time = 0; } +SetTimePacket::SetTimePacket(__int64 time) { this->time = time; } -SetTimePacket::SetTimePacket() +void SetTimePacket::read(DataInputStream* dis) // throws IOException { - time = 0; + time = dis->readLong(); } -SetTimePacket::SetTimePacket(__int64 time) +void SetTimePacket::write(DataOutputStream* dos) // throws IOException { - this->time = time; + dos->writeLong(time); } -void SetTimePacket::read(DataInputStream *dis) //throws IOException -{ - time = dis->readLong(); +void SetTimePacket::handle(PacketListener* listener) { + listener->handleSetTime(shared_from_this()); } -void SetTimePacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeLong(time); +int SetTimePacket::getEstimatedSize() { return 8; } + +bool SetTimePacket::canBeInvalidated() { return true; } + +bool SetTimePacket::isInvalidatedBy(std::shared_ptr packet) { + return true; } -void SetTimePacket::handle(PacketListener *listener) -{ - listener->handleSetTime(shared_from_this()); -} - -int SetTimePacket::getEstimatedSize() -{ - return 8; -} - -bool SetTimePacket::canBeInvalidated() -{ - return true; -} - -bool SetTimePacket::isInvalidatedBy(std::shared_ptr packet) -{ - return true; -} - -bool SetTimePacket::isAync() -{ - return true; -} \ No newline at end of file +bool SetTimePacket::isAync() { return true; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SetTimePacket.h b/Minecraft.World/Network/Packets/SetTimePacket.h index ade7075e5..5e09c041a 100644 --- a/Minecraft.World/Network/Packets/SetTimePacket.h +++ b/Minecraft.World/Network/Packets/SetTimePacket.h @@ -1,25 +1,26 @@ #pragma once - #include "Packet.h" -class SetTimePacket : public Packet, public std::enable_shared_from_this -{ +class SetTimePacket : public Packet, + public std::enable_shared_from_this { public: - __int64 time; + __int64 time; - SetTimePacket(); - SetTimePacket(__int64 time); + SetTimePacket(); + SetTimePacket(__int64 time); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); - virtual bool isAync(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool isAync(); public: - static std::shared_ptr create() { return std::shared_ptr(new SetTimePacket()); } - virtual int getId() { return 4; } + static std::shared_ptr create() { + return std::shared_ptr(new SetTimePacket()); + } + virtual int getId() { return 4; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/SharedKeyPacket.h b/Minecraft.World/Network/Packets/SharedKeyPacket.h index 0abfea493..f2f7d1441 100644 --- a/Minecraft.World/Network/Packets/SharedKeyPacket.h +++ b/Minecraft.World/Network/Packets/SharedKeyPacket.h @@ -2,8 +2,7 @@ #include "Packet.h" -class SharedKeyPacket : public Packet -{ +class SharedKeyPacket : public Packet { #if 0 private byte[] keybytes = new uint8_t[]{}; private byte[] nonce = new uint8_t[]{}; diff --git a/Minecraft.World/Network/Packets/SignUpdatePacket.cpp b/Minecraft.World/Network/Packets/SignUpdatePacket.cpp index 03d8d5e51..e1addb4bc 100644 --- a/Minecraft.World/Network/Packets/SignUpdatePacket.cpp +++ b/Minecraft.World/Network/Packets/SignUpdatePacket.cpp @@ -5,67 +5,60 @@ #include "../../Headers/net.minecraft.world.level.tile.entity.h" #include "SignUpdatePacket.h" - - -SignUpdatePacket::SignUpdatePacket() -{ - shouldDelay = true; - m_bVerified=false; - m_bCensored=false; - x = 0; - y = 0; - z = 0; - +SignUpdatePacket::SignUpdatePacket() { + shouldDelay = true; + m_bVerified = false; + m_bCensored = false; + x = 0; + y = 0; + z = 0; } -SignUpdatePacket::SignUpdatePacket(int x, int y, int z, bool bVerified, bool bCensored, std::wstring lines[]) -{ - shouldDelay = true; - this->m_bVerified=bVerified; - this->m_bCensored=bCensored; - this->x = x; - this->y = y; - this->z = z; - for( int i = 0; i < MAX_SIGN_LINES; i++ ) this->lines[i] = lines[i]; +SignUpdatePacket::SignUpdatePacket(int x, int y, int z, bool bVerified, + bool bCensored, std::wstring lines[]) { + shouldDelay = true; + this->m_bVerified = bVerified; + this->m_bCensored = bCensored; + this->x = x; + this->y = y; + this->z = z; + for (int i = 0; i < MAX_SIGN_LINES; i++) this->lines[i] = lines[i]; } -void SignUpdatePacket::read(DataInputStream *dis) //throws IOException +void SignUpdatePacket::read(DataInputStream* dis) // throws IOException { - x = dis->readInt(); - y = dis->readShort(); - z = dis->readInt(); - this->m_bVerified=dis->readBoolean(); - this->m_bCensored=dis->readBoolean();; - for (int i = 0; i < MAX_SIGN_LINES; i++) - lines[i] = readUtf(dis, SignTileEntity::MAX_LINE_LENGTH); + x = dis->readInt(); + y = dis->readShort(); + z = dis->readInt(); + this->m_bVerified = dis->readBoolean(); + this->m_bCensored = dis->readBoolean(); + ; + for (int i = 0; i < MAX_SIGN_LINES; i++) + lines[i] = readUtf(dis, SignTileEntity::MAX_LINE_LENGTH); } -void SignUpdatePacket::write(DataOutputStream *dos) //throws IOException +void SignUpdatePacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(x); - dos->writeShort(y); - dos->writeInt(z); - dos->writeBoolean(m_bVerified); - dos->writeBoolean(m_bCensored); - for (int i = 0; i < MAX_SIGN_LINES; i++) - writeUtf(lines[i], dos); + dos->writeInt(x); + dos->writeShort(y); + dos->writeInt(z); + dos->writeBoolean(m_bVerified); + dos->writeBoolean(m_bCensored); + for (int i = 0; i < MAX_SIGN_LINES; i++) writeUtf(lines[i], dos); } -void SignUpdatePacket::handle(PacketListener *listener) -{ - listener->handleSignUpdate(shared_from_this()); +void SignUpdatePacket::handle(PacketListener* listener) { + listener->handleSignUpdate(shared_from_this()); } -int SignUpdatePacket::getEstimatedSize() -{ - int l = 0; - l+=sizeof(int); - l+=sizeof(short); - l+=sizeof(int); - l+=sizeof(uint8_t); - l+=sizeof(uint8_t); +int SignUpdatePacket::getEstimatedSize() { + int l = 0; + l += sizeof(int); + l += sizeof(short); + l += sizeof(int); + l += sizeof(uint8_t); + l += sizeof(uint8_t); - for (int i = 0; i < MAX_SIGN_LINES; i++) - l += (int)lines[i].length(); - return l; + for (int i = 0; i < MAX_SIGN_LINES; i++) l += (int)lines[i].length(); + return l; } diff --git a/Minecraft.World/Network/Packets/SignUpdatePacket.h b/Minecraft.World/Network/Packets/SignUpdatePacket.h index d45f59350..183ce24d9 100644 --- a/Minecraft.World/Network/Packets/SignUpdatePacket.h +++ b/Minecraft.World/Network/Packets/SignUpdatePacket.h @@ -1,26 +1,28 @@ #pragma once - #include "Packet.h" -class SignUpdatePacket : public Packet, public std::enable_shared_from_this -{ +class SignUpdatePacket : public Packet, + public std::enable_shared_from_this { public: - int x, y, z; - bool m_bVerified; - bool m_bCensored; + int x, y, z; + bool m_bVerified; + bool m_bCensored; std::wstring lines[4]; - SignUpdatePacket(); - SignUpdatePacket(int x, int y, int z, bool bVerified, bool bCensored, std::wstring lines[]); - bool GetVerified() {return m_bVerified;} - bool GetCensored() {return m_bCensored;} - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + SignUpdatePacket(); + SignUpdatePacket(int x, int y, int z, bool bVerified, bool bCensored, + std::wstring lines[]); + bool GetVerified() { return m_bVerified; } + bool GetCensored() { return m_bCensored; } + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new SignUpdatePacket()); } - virtual int getId() { return 130; } + static std::shared_ptr create() { + return std::shared_ptr(new SignUpdatePacket()); + } + virtual int getId() { return 130; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TakeItemEntityPacket.cpp b/Minecraft.World/Network/Packets/TakeItemEntityPacket.cpp index 75f02f185..837832d86 100644 --- a/Minecraft.World/Network/Packets/TakeItemEntityPacket.cpp +++ b/Minecraft.World/Network/Packets/TakeItemEntityPacket.cpp @@ -4,38 +4,30 @@ #include "PacketListener.h" #include "TakeItemEntityPacket.h" - - -TakeItemEntityPacket::TakeItemEntityPacket() -{ - itemId = -1; - playerId = -1; +TakeItemEntityPacket::TakeItemEntityPacket() { + itemId = -1; + playerId = -1; } -TakeItemEntityPacket::TakeItemEntityPacket(int itemId, int playerId) -{ - this->itemId = itemId; - this->playerId = playerId; +TakeItemEntityPacket::TakeItemEntityPacket(int itemId, int playerId) { + this->itemId = itemId; + this->playerId = playerId; } -void TakeItemEntityPacket::read(DataInputStream *dis) //throws IOException +void TakeItemEntityPacket::read(DataInputStream* dis) // throws IOException { - itemId = dis->readInt(); - playerId = dis->readInt(); + itemId = dis->readInt(); + playerId = dis->readInt(); } -void TakeItemEntityPacket::write(DataOutputStream *dos) //throws IOException +void TakeItemEntityPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(itemId); - dos->writeInt(playerId); + dos->writeInt(itemId); + dos->writeInt(playerId); } -void TakeItemEntityPacket::handle(PacketListener *listener) -{ - listener->handleTakeItemEntity(shared_from_this()); +void TakeItemEntityPacket::handle(PacketListener* listener) { + listener->handleTakeItemEntity(shared_from_this()); } -int TakeItemEntityPacket::getEstimatedSize() -{ - return 8; -} +int TakeItemEntityPacket::getEstimatedSize() { return 8; } diff --git a/Minecraft.World/Network/Packets/TakeItemEntityPacket.h b/Minecraft.World/Network/Packets/TakeItemEntityPacket.h index 524d7e627..d7792e778 100644 --- a/Minecraft.World/Network/Packets/TakeItemEntityPacket.h +++ b/Minecraft.World/Network/Packets/TakeItemEntityPacket.h @@ -1,22 +1,24 @@ #pragma once - #include "Packet.h" -class TakeItemEntityPacket : public Packet, public std::enable_shared_from_this -{ +class TakeItemEntityPacket + : public Packet, + public std::enable_shared_from_this { public: - int itemId, playerId; + int itemId, playerId; - TakeItemEntityPacket(); - TakeItemEntityPacket(int itemId, int playerId); + TakeItemEntityPacket(); + TakeItemEntityPacket(int itemId, int playerId); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TakeItemEntityPacket()); } - virtual int getId() { return 22; } + static std::shared_ptr create() { + return std::shared_ptr(new TakeItemEntityPacket()); + } + virtual int getId() { return 22; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TeleportEntityPacket.cpp b/Minecraft.World/Network/Packets/TeleportEntityPacket.cpp index fcd88af71..e2659f209 100644 --- a/Minecraft.World/Network/Packets/TeleportEntityPacket.cpp +++ b/Minecraft.World/Network/Packets/TeleportEntityPacket.cpp @@ -5,87 +5,76 @@ #include "PacketListener.h" #include "TeleportEntityPacket.h" - - -TeleportEntityPacket::TeleportEntityPacket() -{ - id = -1; - x = 0; - y = 0; - z = 0; - yRot = 0; - xRot = 0; +TeleportEntityPacket::TeleportEntityPacket() { + id = -1; + x = 0; + y = 0; + z = 0; + yRot = 0; + xRot = 0; } -TeleportEntityPacket::TeleportEntityPacket(std::shared_ptr e) -{ - id = e->entityId; - x = Mth::floor(e->x * 32); - y = Mth::floor(e->y * 32); - z = Mth::floor(e->z * 32); - yRot = (uint8_t) (e->yRot * 256 / 360); - xRot = (uint8_t) (e->xRot * 256 / 360); +TeleportEntityPacket::TeleportEntityPacket(std::shared_ptr e) { + id = e->entityId; + x = Mth::floor(e->x * 32); + y = Mth::floor(e->y * 32); + z = Mth::floor(e->z * 32); + yRot = (uint8_t)(e->yRot * 256 / 360); + xRot = (uint8_t)(e->xRot * 256 / 360); } -TeleportEntityPacket::TeleportEntityPacket(int id, int x, int y, int z, uint8_t yRot, uint8_t xRot) -{ - this->id = id; - this->x = x; - this->y = y; - this->z = z; - this->yRot = yRot; - this->xRot = xRot; +TeleportEntityPacket::TeleportEntityPacket(int id, int x, int y, int z, + uint8_t yRot, uint8_t xRot) { + this->id = id; + this->x = x; + this->y = y; + this->z = z; + this->yRot = yRot; + this->xRot = xRot; } -void TeleportEntityPacket::read(DataInputStream *dis) //throws IOException +void TeleportEntityPacket::read(DataInputStream* dis) // throws IOException { - id = dis->readShort(); + id = dis->readShort(); #ifdef _LARGE_WORLDS - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); #else - x = dis->readShort(); - y = dis->readShort(); - z = dis->readShort(); + x = dis->readShort(); + y = dis->readShort(); + z = dis->readShort(); #endif - yRot = (uint8_t) dis->read(); - xRot = (uint8_t) dis->read(); + yRot = (uint8_t)dis->read(); + xRot = (uint8_t)dis->read(); } -void TeleportEntityPacket::write(DataOutputStream *dos) //throws IOException +void TeleportEntityPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeShort(id); + dos->writeShort(id); #ifdef _LARGE_WORLDS - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); #else - dos->writeShort(x); - dos->writeShort(y); - dos->writeShort(z); + dos->writeShort(x); + dos->writeShort(y); + dos->writeShort(z); #endif - dos->write(yRot); - dos->write(xRot); + dos->write(yRot); + dos->write(xRot); } -void TeleportEntityPacket::handle(PacketListener *listener) -{ - listener->handleTeleportEntity(shared_from_this()); +void TeleportEntityPacket::handle(PacketListener* listener) { + listener->handleTeleportEntity(shared_from_this()); } -int TeleportEntityPacket::getEstimatedSize() -{ - return 2 + 2 + 2 + 2 + 1 + 1; -} +int TeleportEntityPacket::getEstimatedSize() { return 2 + 2 + 2 + 2 + 1 + 1; } -bool TeleportEntityPacket::canBeInvalidated() -{ - return true; -} +bool TeleportEntityPacket::canBeInvalidated() { return true; } -bool TeleportEntityPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->id == id; +bool TeleportEntityPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->id == id; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TeleportEntityPacket.h b/Minecraft.World/Network/Packets/TeleportEntityPacket.h index 0b85a3b99..c5e2585ce 100644 --- a/Minecraft.World/Network/Packets/TeleportEntityPacket.h +++ b/Minecraft.World/Network/Packets/TeleportEntityPacket.h @@ -1,27 +1,30 @@ #pragma once - #include "Packet.h" -class TeleportEntityPacket : public Packet, public std::enable_shared_from_this -{ +class TeleportEntityPacket + : public Packet, + public std::enable_shared_from_this { public: - int id; + int id; int x, y, z; uint8_t yRot, xRot; - TeleportEntityPacket(); - TeleportEntityPacket(std::shared_ptr e); - TeleportEntityPacket(int id, int x, int y, int z, uint8_t yRot, uint8_t xRot); + TeleportEntityPacket(); + TeleportEntityPacket(std::shared_ptr e); + TeleportEntityPacket(int id, int x, int y, int z, uint8_t yRot, + uint8_t xRot); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new TeleportEntityPacket()); } - virtual int getId() { return 34; } + static std::shared_ptr create() { + return std::shared_ptr(new TeleportEntityPacket()); + } + virtual int getId() { return 34; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.cpp b/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.cpp index aed41853e..75b66c781 100644 --- a/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.cpp +++ b/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.cpp @@ -5,49 +5,44 @@ #include "PacketListener.h" #include "TextureAndGeometryChangePacket.h" - - - -TextureAndGeometryChangePacket::TextureAndGeometryChangePacket() -{ - id = -1; - path = L""; - dwSkinID = 0; +TextureAndGeometryChangePacket::TextureAndGeometryChangePacket() { + id = -1; + path = L""; + dwSkinID = 0; } -TextureAndGeometryChangePacket::TextureAndGeometryChangePacket(std::shared_ptr e, const std::wstring &path) -{ - id = e->entityId; - this->path = path; - std::wstring skinValue = path.substr(7,path.size()); - skinValue = skinValue.substr(0,skinValue.find_first_of(L'.')); - std::wstringstream ss; - ss << std::dec << skinValue.c_str(); - ss >> dwSkinID; - dwSkinID = MAKE_SKIN_BITMASK(true, dwSkinID); - +TextureAndGeometryChangePacket::TextureAndGeometryChangePacket( + std::shared_ptr e, const std::wstring& path) { + id = e->entityId; + this->path = path; + std::wstring skinValue = path.substr(7, path.size()); + skinValue = skinValue.substr(0, skinValue.find_first_of(L'.')); + std::wstringstream ss; + ss << std::dec << skinValue.c_str(); + ss >> dwSkinID; + dwSkinID = MAKE_SKIN_BITMASK(true, dwSkinID); } -void TextureAndGeometryChangePacket::read(DataInputStream *dis) //throws IOException +void TextureAndGeometryChangePacket::read( + DataInputStream* dis) // throws IOException { - id = dis->readInt(); - dwSkinID = static_cast(dis->readInt()); - path = dis->readUTF(); + id = dis->readInt(); + dwSkinID = static_cast(dis->readInt()); + path = dis->readUTF(); } -void TextureAndGeometryChangePacket::write(DataOutputStream *dos) //throws IOException +void TextureAndGeometryChangePacket::write( + DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeInt(static_cast(dwSkinID)); - dos->writeUTF(path); + dos->writeInt(id); + dos->writeInt(static_cast(dwSkinID)); + dos->writeUTF(path); } -void TextureAndGeometryChangePacket::handle(PacketListener *listener) -{ - listener->handleTextureAndGeometryChange(shared_from_this()); +void TextureAndGeometryChangePacket::handle(PacketListener* listener) { + listener->handleTextureAndGeometryChange(shared_from_this()); } -int TextureAndGeometryChangePacket::getEstimatedSize() -{ - return 8 + (int)path.size(); +int TextureAndGeometryChangePacket::getEstimatedSize() { + return 8 + (int)path.size(); } diff --git a/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.h b/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.h index 7584b3c3e..9f2687f10 100644 --- a/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.h +++ b/Minecraft.World/Network/Packets/TextureAndGeometryChangePacket.h @@ -3,23 +3,26 @@ #include "Packet.h" -class TextureAndGeometryChangePacket : public Packet, public std::enable_shared_from_this -{ +class TextureAndGeometryChangePacket + : public Packet, + public std::enable_shared_from_this { public: - int id; - std::wstring path; - std::uint32_t dwSkinID; + std::wstring path; + std::uint32_t dwSkinID; - TextureAndGeometryChangePacket(); - TextureAndGeometryChangePacket(std::shared_ptr e, const std::wstring &path); + TextureAndGeometryChangePacket(); + TextureAndGeometryChangePacket(std::shared_ptr e, + const std::wstring& path); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TextureAndGeometryChangePacket()); } - virtual int getId() { return 161; } + static std::shared_ptr create() { + return std::shared_ptr(new TextureAndGeometryChangePacket()); + } + virtual int getId() { return 161; } }; diff --git a/Minecraft.World/Network/Packets/TextureAndGeometryPacket.cpp b/Minecraft.World/Network/Packets/TextureAndGeometryPacket.cpp index fa479a143..4d94ba74c 100644 --- a/Minecraft.World/Network/Packets/TextureAndGeometryPacket.cpp +++ b/Minecraft.World/Network/Packets/TextureAndGeometryPacket.cpp @@ -4,186 +4,171 @@ #include "PacketListener.h" #include "TextureAndGeometryPacket.h" - - -TextureAndGeometryPacket::TextureAndGeometryPacket() -{ - this->textureName = L""; - this->dwTextureBytes = 0; - this->pbData = NULL; - this->dwBoxC = 0; - this->BoxDataA = NULL; - uiAnimOverrideBitmask=0; +TextureAndGeometryPacket::TextureAndGeometryPacket() { + this->textureName = L""; + this->dwTextureBytes = 0; + this->pbData = NULL; + this->dwBoxC = 0; + this->BoxDataA = NULL; + uiAnimOverrideBitmask = 0; } -TextureAndGeometryPacket::~TextureAndGeometryPacket() -{ - // can't free these - they're used elsewhere -// if(this->BoxDataA!=NULL) -// { -// delete [] this->BoxDataA; -// } -// -// if(this->pbData!=NULL) -// { -// delete [] this->pbData; -// } +TextureAndGeometryPacket::~TextureAndGeometryPacket() { + // can't free these - they're used elsewhere + // if(this->BoxDataA!=NULL) + // { + // delete [] this->BoxDataA; + // } + // + // if(this->pbData!=NULL) + // { + // delete [] this->pbData; + // } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes) -{ - this->textureName = textureName; +TextureAndGeometryPacket::TextureAndGeometryPacket( + const std::wstring& textureName, std::uint8_t* pbData, + std::uint32_t dataBytes) { + this->textureName = textureName; - std::wstring skinValue = textureName.substr(7,textureName.size()); - skinValue = skinValue.substr(0,skinValue.find_first_of(L'.')); - std::wstringstream ss; - ss << std::dec << skinValue.c_str(); - ss >> this->dwSkinID; - this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); - this->pbData = pbData; - this->dwTextureBytes = dataBytes; - this->dwBoxC = 0; - this->BoxDataA=NULL; - this->uiAnimOverrideBitmask=0; + std::wstring skinValue = textureName.substr(7, textureName.size()); + skinValue = skinValue.substr(0, skinValue.find_first_of(L'.')); + std::wstringstream ss; + ss << std::dec << skinValue.c_str(); + ss >> this->dwSkinID; + this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); + this->pbData = pbData; + this->dwTextureBytes = dataBytes; + this->dwBoxC = 0; + this->BoxDataA = NULL; + this->uiAnimOverrideBitmask = 0; } -TextureAndGeometryPacket::TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes, DLCSkinFile *pDLCSkinFile) -{ - this->textureName = textureName; +TextureAndGeometryPacket::TextureAndGeometryPacket( + const std::wstring& textureName, std::uint8_t* pbData, + std::uint32_t dataBytes, DLCSkinFile* pDLCSkinFile) { + this->textureName = textureName; - std::wstring skinValue = textureName.substr(7,textureName.size()); - skinValue = skinValue.substr(0,skinValue.find_first_of(L'.')); - std::wstringstream ss; - ss << std::dec << skinValue.c_str(); - ss >> this->dwSkinID; - this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); + std::wstring skinValue = textureName.substr(7, textureName.size()); + skinValue = skinValue.substr(0, skinValue.find_first_of(L'.')); + std::wstringstream ss; + ss << std::dec << skinValue.c_str(); + ss >> this->dwSkinID; + this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); - this->pbData = pbData; - this->dwTextureBytes = dataBytes; - this->uiAnimOverrideBitmask = pDLCSkinFile->getAnimOverrideBitmask(); - this->dwBoxC = pDLCSkinFile->getAdditionalBoxesCount(); - if(this->dwBoxC!=0) - { - this->BoxDataA= new SKIN_BOX [this->dwBoxC]; - std::vector *pSkinBoxes=pDLCSkinFile->getAdditionalBoxes(); - int iCount=0; + this->pbData = pbData; + this->dwTextureBytes = dataBytes; + this->uiAnimOverrideBitmask = pDLCSkinFile->getAnimOverrideBitmask(); + this->dwBoxC = pDLCSkinFile->getAdditionalBoxesCount(); + if (this->dwBoxC != 0) { + this->BoxDataA = new SKIN_BOX[this->dwBoxC]; + std::vector* pSkinBoxes = pDLCSkinFile->getAdditionalBoxes(); + int iCount = 0; - for(AUTO_VAR(it, pSkinBoxes->begin());it != pSkinBoxes->end(); ++it) - { - SKIN_BOX *pSkinBox=*it; - this->BoxDataA[iCount++]=*pSkinBox; - } - } - else - { - this->BoxDataA=NULL; - } + for (AUTO_VAR(it, pSkinBoxes->begin()); it != pSkinBoxes->end(); ++it) { + SKIN_BOX* pSkinBox = *it; + this->BoxDataA[iCount++] = *pSkinBox; + } + } else { + this->BoxDataA = NULL; + } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes,std::vector *pvSkinBoxes, unsigned int uiAnimOverrideBitmask) -{ - this->textureName = textureName; +TextureAndGeometryPacket::TextureAndGeometryPacket( + const std::wstring& textureName, std::uint8_t* pbData, + std::uint32_t dataBytes, std::vector* pvSkinBoxes, + unsigned int uiAnimOverrideBitmask) { + this->textureName = textureName; - std::wstring skinValue = textureName.substr(7,textureName.size()); - skinValue = skinValue.substr(0,skinValue.find_first_of(L'.')); - std::wstringstream ss; - ss << std::dec << skinValue.c_str(); - ss >> this->dwSkinID; - this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); + std::wstring skinValue = textureName.substr(7, textureName.size()); + skinValue = skinValue.substr(0, skinValue.find_first_of(L'.')); + std::wstringstream ss; + ss << std::dec << skinValue.c_str(); + ss >> this->dwSkinID; + this->dwSkinID = MAKE_SKIN_BITMASK(true, this->dwSkinID); - this->pbData = pbData; - this->dwTextureBytes = dataBytes; - this->uiAnimOverrideBitmask = uiAnimOverrideBitmask; - if(pvSkinBoxes==NULL) - { - this->dwBoxC=0; - this->BoxDataA=NULL; - } - else - { - this->dwBoxC = (std::uint32_t)pvSkinBoxes->size(); - this->BoxDataA= new SKIN_BOX [this->dwBoxC]; - int iCount=0; - - for(AUTO_VAR(it, pvSkinBoxes->begin());it != pvSkinBoxes->end(); ++it) - { - SKIN_BOX *pSkinBox=*it; - this->BoxDataA[iCount++]=*pSkinBox; - } - } + this->pbData = pbData; + this->dwTextureBytes = dataBytes; + this->uiAnimOverrideBitmask = uiAnimOverrideBitmask; + if (pvSkinBoxes == NULL) { + this->dwBoxC = 0; + this->BoxDataA = NULL; + } else { + this->dwBoxC = (std::uint32_t)pvSkinBoxes->size(); + this->BoxDataA = new SKIN_BOX[this->dwBoxC]; + int iCount = 0; + for (AUTO_VAR(it, pvSkinBoxes->begin()); it != pvSkinBoxes->end(); + ++it) { + SKIN_BOX* pSkinBox = *it; + this->BoxDataA[iCount++] = *pSkinBox; + } + } } -void TextureAndGeometryPacket::handle(PacketListener *listener) -{ - listener->handleTextureAndGeometry(shared_from_this()); +void TextureAndGeometryPacket::handle(PacketListener* listener) { + listener->handleTextureAndGeometry(shared_from_this()); } -void TextureAndGeometryPacket::read(DataInputStream *dis) //throws IOException +void TextureAndGeometryPacket::read(DataInputStream* dis) // throws IOException { - textureName = dis->readUTF(); - dwSkinID = static_cast(dis->readInt()); - dwTextureBytes = (std::uint32_t)dis->readShort(); + textureName = dis->readUTF(); + dwSkinID = static_cast(dis->readInt()); + dwTextureBytes = (std::uint32_t)dis->readShort(); - if(dwTextureBytes>0) - { - this->pbData= new std::uint8_t [dwTextureBytes]; + if (dwTextureBytes > 0) { + this->pbData = new std::uint8_t[dwTextureBytes]; - for(std::uint32_t i=0;ipbData[i] = dis->readByte(); - } - } - uiAnimOverrideBitmask = dis->readInt(); + for (std::uint32_t i = 0; i < dwTextureBytes; i++) { + this->pbData[i] = dis->readByte(); + } + } + uiAnimOverrideBitmask = dis->readInt(); - dwBoxC = (std::uint32_t)dis->readShort(); + dwBoxC = (std::uint32_t)dis->readShort(); - if(dwBoxC>0) - { - this->BoxDataA= new SKIN_BOX [dwBoxC]; - } + if (dwBoxC > 0) { + this->BoxDataA = new SKIN_BOX[dwBoxC]; + } - for(std::uint32_t i=0;iBoxDataA[i].ePart = (eBodyPart) dis->readShort(); - this->BoxDataA[i].fX = dis->readFloat(); - this->BoxDataA[i].fY = dis->readFloat(); - this->BoxDataA[i].fZ = dis->readFloat(); - this->BoxDataA[i].fH = dis->readFloat(); - this->BoxDataA[i].fW = dis->readFloat(); - this->BoxDataA[i].fD = dis->readFloat(); - this->BoxDataA[i].fU = dis->readFloat(); - this->BoxDataA[i].fV = dis->readFloat(); - } + for (std::uint32_t i = 0; i < dwBoxC; i++) { + this->BoxDataA[i].ePart = (eBodyPart)dis->readShort(); + this->BoxDataA[i].fX = dis->readFloat(); + this->BoxDataA[i].fY = dis->readFloat(); + this->BoxDataA[i].fZ = dis->readFloat(); + this->BoxDataA[i].fH = dis->readFloat(); + this->BoxDataA[i].fW = dis->readFloat(); + this->BoxDataA[i].fD = dis->readFloat(); + this->BoxDataA[i].fU = dis->readFloat(); + this->BoxDataA[i].fV = dis->readFloat(); + } } -void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException +void TextureAndGeometryPacket::write( + DataOutputStream* dos) // throws IOException { - dos->writeUTF(textureName); - dos->writeInt(static_cast(dwSkinID)); - dos->writeShort((short)dwTextureBytes); - for(std::uint32_t i=0;iwriteByte(this->pbData[i]); - } - dos->writeInt(uiAnimOverrideBitmask); + dos->writeUTF(textureName); + dos->writeInt(static_cast(dwSkinID)); + dos->writeShort((short)dwTextureBytes); + for (std::uint32_t i = 0; i < dwTextureBytes; i++) { + dos->writeByte(this->pbData[i]); + } + dos->writeInt(uiAnimOverrideBitmask); - dos->writeShort((short)dwBoxC); - for(std::uint32_t i=0;iwriteShort((short)this->BoxDataA[i].ePart); - dos->writeFloat(this->BoxDataA[i].fX); - dos->writeFloat(this->BoxDataA[i].fY); - dos->writeFloat(this->BoxDataA[i].fZ); - dos->writeFloat(this->BoxDataA[i].fH); - dos->writeFloat(this->BoxDataA[i].fW); - dos->writeFloat(this->BoxDataA[i].fD); - dos->writeFloat(this->BoxDataA[i].fU); - dos->writeFloat(this->BoxDataA[i].fV); - } + dos->writeShort((short)dwBoxC); + for (std::uint32_t i = 0; i < dwBoxC; i++) { + dos->writeShort((short)this->BoxDataA[i].ePart); + dos->writeFloat(this->BoxDataA[i].fX); + dos->writeFloat(this->BoxDataA[i].fY); + dos->writeFloat(this->BoxDataA[i].fZ); + dos->writeFloat(this->BoxDataA[i].fH); + dos->writeFloat(this->BoxDataA[i].fW); + dos->writeFloat(this->BoxDataA[i].fD); + dos->writeFloat(this->BoxDataA[i].fU); + dos->writeFloat(this->BoxDataA[i].fV); + } } -int TextureAndGeometryPacket::getEstimatedSize() -{ - return 4096+ +sizeof(int) + sizeof(float)*8*4; +int TextureAndGeometryPacket::getEstimatedSize() { + return 4096 + +sizeof(int) + sizeof(float) * 8 * 4; } diff --git a/Minecraft.World/Network/Packets/TextureAndGeometryPacket.h b/Minecraft.World/Network/Packets/TextureAndGeometryPacket.h index c6470895d..a49b9f092 100644 --- a/Minecraft.World/Network/Packets/TextureAndGeometryPacket.h +++ b/Minecraft.World/Network/Packets/TextureAndGeometryPacket.h @@ -7,29 +7,38 @@ class DLCSkinFile; -class TextureAndGeometryPacket : public Packet, public std::enable_shared_from_this -{ +class TextureAndGeometryPacket + : public Packet, + public std::enable_shared_from_this { public: - std::wstring textureName; - std::uint32_t dwSkinID; - std::uint8_t *pbData; - std::uint32_t dwTextureBytes; - SKIN_BOX *BoxDataA; - std::uint32_t dwBoxC; - unsigned int uiAnimOverrideBitmask; + std::wstring textureName; + std::uint32_t dwSkinID; + std::uint8_t* pbData; + std::uint32_t dwTextureBytes; + SKIN_BOX* BoxDataA; + std::uint32_t dwBoxC; + unsigned int uiAnimOverrideBitmask; - TextureAndGeometryPacket(); - ~TextureAndGeometryPacket(); - TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes); - TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes, DLCSkinFile *pDLCSkinFile); - TextureAndGeometryPacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes, std::vector *pvSkinBoxes, unsigned int uiAnimOverrideBitmask); + TextureAndGeometryPacket(); + ~TextureAndGeometryPacket(); + TextureAndGeometryPacket(const std::wstring& textureName, + std::uint8_t* pbData, std::uint32_t dataBytes); + TextureAndGeometryPacket(const std::wstring& textureName, + std::uint8_t* pbData, std::uint32_t dataBytes, + DLCSkinFile* pDLCSkinFile); + TextureAndGeometryPacket(const std::wstring& textureName, + std::uint8_t* pbData, std::uint32_t dataBytes, + std::vector* pvSkinBoxes, + unsigned int uiAnimOverrideBitmask); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TextureAndGeometryPacket()); } - virtual int getId() { return 160; } + static std::shared_ptr create() { + return std::shared_ptr(new TextureAndGeometryPacket()); + } + virtual int getId() { return 160; } }; diff --git a/Minecraft.World/Network/Packets/TextureChangePacket.cpp b/Minecraft.World/Network/Packets/TextureChangePacket.cpp index 321e68eea..086758c6d 100644 --- a/Minecraft.World/Network/Packets/TextureChangePacket.cpp +++ b/Minecraft.World/Network/Packets/TextureChangePacket.cpp @@ -5,42 +5,36 @@ #include "PacketListener.h" #include "TextureChangePacket.h" - - -TextureChangePacket::TextureChangePacket() -{ - id = -1; - action = e_TextureChange_Skin; - path = L""; +TextureChangePacket::TextureChangePacket() { + id = -1; + action = e_TextureChange_Skin; + path = L""; } -TextureChangePacket::TextureChangePacket(std::shared_ptr e, ETextureChangeType action, const std::wstring &path) -{ - id = e->entityId; - this->action = action; - this->path = path; +TextureChangePacket::TextureChangePacket(std::shared_ptr e, + ETextureChangeType action, + const std::wstring& path) { + id = e->entityId; + this->action = action; + this->path = path; } -void TextureChangePacket::read(DataInputStream *dis) //throws IOException +void TextureChangePacket::read(DataInputStream* dis) // throws IOException { - id = dis->readInt(); - action = (ETextureChangeType)dis->readByte(); - path = dis->readUTF(); + id = dis->readInt(); + action = (ETextureChangeType)dis->readByte(); + path = dis->readUTF(); } -void TextureChangePacket::write(DataOutputStream *dos) //throws IOException +void TextureChangePacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(id); - dos->writeByte(action); - dos->writeUTF(path); + dos->writeInt(id); + dos->writeByte(action); + dos->writeUTF(path); } -void TextureChangePacket::handle(PacketListener *listener) -{ - listener->handleTextureChange(shared_from_this()); +void TextureChangePacket::handle(PacketListener* listener) { + listener->handleTextureChange(shared_from_this()); } -int TextureChangePacket::getEstimatedSize() -{ - return 5 + (int)path.size(); -} +int TextureChangePacket::getEstimatedSize() { return 5 + (int)path.size(); } diff --git a/Minecraft.World/Network/Packets/TextureChangePacket.h b/Minecraft.World/Network/Packets/TextureChangePacket.h index 7f281a815..b59a42a07 100644 --- a/Minecraft.World/Network/Packets/TextureChangePacket.h +++ b/Minecraft.World/Network/Packets/TextureChangePacket.h @@ -1,30 +1,32 @@ #pragma once - #include "Packet.h" -class TextureChangePacket : public Packet, public std::enable_shared_from_this -{ +class TextureChangePacket + : public Packet, + public std::enable_shared_from_this { public: - enum ETextureChangeType - { - e_TextureChange_Skin = 0, - e_TextureChange_Cape, - }; + enum ETextureChangeType { + e_TextureChange_Skin = 0, + e_TextureChange_Cape, + }; int id; ETextureChangeType action; - std::wstring path; + std::wstring path; - TextureChangePacket(); - TextureChangePacket(std::shared_ptr e, ETextureChangeType action, const std::wstring &path); + TextureChangePacket(); + TextureChangePacket(std::shared_ptr e, ETextureChangeType action, + const std::wstring& path); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TextureChangePacket()); } - virtual int getId() { return 157; } + static std::shared_ptr create() { + return std::shared_ptr(new TextureChangePacket()); + } + virtual int getId() { return 157; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TexturePacket.cpp b/Minecraft.World/Network/Packets/TexturePacket.cpp index bb179a8e5..6764f0301 100644 --- a/Minecraft.World/Network/Packets/TexturePacket.cpp +++ b/Minecraft.World/Network/Packets/TexturePacket.cpp @@ -4,63 +4,52 @@ #include "PacketListener.h" #include "TexturePacket.h" - - -TexturePacket::TexturePacket() -{ - this->textureName = L""; - this->dataBytes = 0; - this->pbData = NULL; +TexturePacket::TexturePacket() { + this->textureName = L""; + this->dataBytes = 0; + this->pbData = NULL; } -TexturePacket::~TexturePacket() -{ - // can't free this - it's used elsewhere -// if(this->pbData!=NULL) -// { -// delete [] this->pbData; -// } +TexturePacket::~TexturePacket() { + // can't free this - it's used elsewhere + // if(this->pbData!=NULL) + // { + // delete [] this->pbData; + // } } -TexturePacket::TexturePacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes) -{ - this->textureName = textureName; - this->pbData = pbData; - this->dataBytes = dataBytes; +TexturePacket::TexturePacket(const std::wstring& textureName, + std::uint8_t* pbData, std::uint32_t dataBytes) { + this->textureName = textureName; + this->pbData = pbData; + this->dataBytes = dataBytes; } -void TexturePacket::handle(PacketListener *listener) -{ - listener->handleTexture(shared_from_this()); +void TexturePacket::handle(PacketListener* listener) { + listener->handleTexture(shared_from_this()); } -void TexturePacket::read(DataInputStream *dis) //throws IOException +void TexturePacket::read(DataInputStream* dis) // throws IOException { - textureName = dis->readUTF(); - dataBytes = (std::uint32_t)dis->readShort(); + textureName = dis->readUTF(); + dataBytes = (std::uint32_t)dis->readShort(); - if(dataBytes>0) - { - this->pbData= new std::uint8_t [dataBytes]; + if (dataBytes > 0) { + this->pbData = new std::uint8_t[dataBytes]; - for(std::uint32_t i=0;ipbData[i] = dis->readByte(); - } - } + for (std::uint32_t i = 0; i < dataBytes; i++) { + this->pbData[i] = dis->readByte(); + } + } } -void TexturePacket::write(DataOutputStream *dos) //throws IOException +void TexturePacket::write(DataOutputStream* dos) // throws IOException { - dos->writeUTF(textureName); - dos->writeShort((short)dataBytes); - for(std::uint32_t i=0;iwriteByte(this->pbData[i]); - } + dos->writeUTF(textureName); + dos->writeShort((short)dataBytes); + for (std::uint32_t i = 0; i < dataBytes; i++) { + dos->writeByte(this->pbData[i]); + } } -int TexturePacket::getEstimatedSize() -{ - return 4096; -} +int TexturePacket::getEstimatedSize() { return 4096; } diff --git a/Minecraft.World/Network/Packets/TexturePacket.h b/Minecraft.World/Network/Packets/TexturePacket.h index dfa5bd70f..37919fc1a 100644 --- a/Minecraft.World/Network/Packets/TexturePacket.h +++ b/Minecraft.World/Network/Packets/TexturePacket.h @@ -3,23 +3,26 @@ #include "Packet.h" -class TexturePacket : public Packet, public std::enable_shared_from_this -{ +class TexturePacket : public Packet, + public std::enable_shared_from_this { public: - std::wstring textureName; - std::uint8_t *pbData; - std::uint32_t dataBytes; + std::wstring textureName; + std::uint8_t* pbData; + std::uint32_t dataBytes; - TexturePacket(); - ~TexturePacket(); - TexturePacket(const std::wstring &textureName, std::uint8_t *pbData, std::uint32_t dataBytes); + TexturePacket(); + ~TexturePacket(); + TexturePacket(const std::wstring& textureName, std::uint8_t* pbData, + std::uint32_t dataBytes); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TexturePacket()); } - virtual int getId() { return 154; } + static std::shared_ptr create() { + return std::shared_ptr(new TexturePacket()); + } + virtual int getId() { return 154; } }; diff --git a/Minecraft.World/Network/Packets/TileDestructionPacket.cpp b/Minecraft.World/Network/Packets/TileDestructionPacket.cpp index 48d6a9df8..859cc031b 100644 --- a/Minecraft.World/Network/Packets/TileDestructionPacket.cpp +++ b/Minecraft.World/Network/Packets/TileDestructionPacket.cpp @@ -2,84 +2,59 @@ #include "../../Headers/net.minecraft.network.packet.h" #include "TileDestructionPacket.h" -TileDestructionPacket::TileDestructionPacket() -{ - id = 0; - x = 0; - y = 0; - z = 0; - state = 0; +TileDestructionPacket::TileDestructionPacket() { + id = 0; + x = 0; + y = 0; + z = 0; + state = 0; } -TileDestructionPacket::TileDestructionPacket(int id, int x, int y, int z, int state) -{ - this->id = id; - this->x = x; - this->y = y; - this->z = z; - this->state = state; +TileDestructionPacket::TileDestructionPacket(int id, int x, int y, int z, + int state) { + this->id = id; + this->x = x; + this->y = y; + this->z = z; + this->state = state; } -void TileDestructionPacket::read(DataInputStream *dis) -{ - id = dis->readInt(); - x = dis->readInt(); - y = dis->readInt(); - z = dis->readInt(); - state = dis->read(); +void TileDestructionPacket::read(DataInputStream* dis) { + id = dis->readInt(); + x = dis->readInt(); + y = dis->readInt(); + z = dis->readInt(); + state = dis->read(); } -void TileDestructionPacket::write(DataOutputStream *dos) -{ - dos->writeInt(id); - dos->writeInt(x); - dos->writeInt(y); - dos->writeInt(z); - dos->write(state); +void TileDestructionPacket::write(DataOutputStream* dos) { + dos->writeInt(id); + dos->writeInt(x); + dos->writeInt(y); + dos->writeInt(z); + dos->write(state); } -void TileDestructionPacket::handle(PacketListener *listener) -{ - listener->handleTileDestruction(shared_from_this()); +void TileDestructionPacket::handle(PacketListener* listener) { + listener->handleTileDestruction(shared_from_this()); } -int TileDestructionPacket::getEstimatedSize() -{ - return 13; -} +int TileDestructionPacket::getEstimatedSize() { return 13; } -int TileDestructionPacket::getEntityId() -{ - return id; -} +int TileDestructionPacket::getEntityId() { return id; } -int TileDestructionPacket::getX() -{ - return x; -} +int TileDestructionPacket::getX() { return x; } -int TileDestructionPacket::getY() -{ - return y; -} +int TileDestructionPacket::getY() { return y; } -int TileDestructionPacket::getZ() -{ - return z; -} +int TileDestructionPacket::getZ() { return z; } -int TileDestructionPacket::getState() -{ - return state; -} +int TileDestructionPacket::getState() { return state; } -bool TileDestructionPacket::canBeInvalidated() -{ - return true; -} +bool TileDestructionPacket::canBeInvalidated() { return true; } -bool TileDestructionPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->id == id; +bool TileDestructionPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->id == id; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TileDestructionPacket.h b/Minecraft.World/Network/Packets/TileDestructionPacket.h index a0a8cf64f..44db0b90a 100644 --- a/Minecraft.World/Network/Packets/TileDestructionPacket.h +++ b/Minecraft.World/Network/Packets/TileDestructionPacket.h @@ -2,34 +2,37 @@ #include "Packet.h" -class TileDestructionPacket : public Packet, public std::enable_shared_from_this -{ +class TileDestructionPacket + : public Packet, + public std::enable_shared_from_this { private: - int id; - int x; - int y; - int z; - int state; + int id; + int x; + int y; + int z; + int state; public: - TileDestructionPacket(); - TileDestructionPacket(int id, int x, int y, int z, int state); + TileDestructionPacket(); + TileDestructionPacket(int id, int x, int y, int z, int state); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - int getEntityId(); - int getX(); - int getY(); - int getZ(); - int getState(); + int getEntityId(); + int getX(); + int getY(); + int getZ(); + int getState(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new TileDestructionPacket()); } - virtual int getId() { return 55; } + static std::shared_ptr create() { + return std::shared_ptr(new TileDestructionPacket()); + } + virtual int getId() { return 55; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TileEntityDataPacket.cpp b/Minecraft.World/Network/Packets/TileEntityDataPacket.cpp index 57a763ff9..b456d5d5b 100644 --- a/Minecraft.World/Network/Packets/TileEntityDataPacket.cpp +++ b/Minecraft.World/Network/Packets/TileEntityDataPacket.cpp @@ -4,62 +4,48 @@ #include "PacketListener.h" #include "TileEntityDataPacket.h" - - -void TileEntityDataPacket::_init() -{ - x = y = z = 0; - type = TYPE_MOB_SPAWNER; - tag = NULL; +void TileEntityDataPacket::_init() { + x = y = z = 0; + type = TYPE_MOB_SPAWNER; + tag = NULL; } - -TileEntityDataPacket::TileEntityDataPacket() -{ - _init(); - shouldDelay = true; +TileEntityDataPacket::TileEntityDataPacket() { + _init(); + shouldDelay = true; } -TileEntityDataPacket::TileEntityDataPacket(int x, int y, int z, int type, CompoundTag *tag) -{ - _init(); - shouldDelay = true; - this->x = x; - this->y = y; - this->z = z; - this->type = type; - this->tag = tag; +TileEntityDataPacket::TileEntityDataPacket(int x, int y, int z, int type, + CompoundTag* tag) { + _init(); + shouldDelay = true; + this->x = x; + this->y = y; + this->z = z; + this->type = type; + this->tag = tag; } -TileEntityDataPacket::~TileEntityDataPacket() -{ - delete tag; +TileEntityDataPacket::~TileEntityDataPacket() { delete tag; } + +void TileEntityDataPacket::read(DataInputStream* dis) { + x = dis->readInt(); + y = dis->readShort(); + z = dis->readInt(); + type = dis->readByte(); + tag = readNbt(dis); } -void TileEntityDataPacket::read(DataInputStream *dis) -{ - x = dis->readInt(); - y = dis->readShort(); - z = dis->readInt(); - type = dis->readByte(); - tag = readNbt(dis); +void TileEntityDataPacket::write(DataOutputStream* dos) { + dos->writeInt(x); + dos->writeShort(y); + dos->writeInt(z); + dos->writeByte((uint8_t)type); + writeNbt(tag, dos); } -void TileEntityDataPacket::write(DataOutputStream *dos) -{ - dos->writeInt(x); - dos->writeShort(y); - dos->writeInt(z); - dos->writeByte((uint8_t) type); - writeNbt(tag, dos); +void TileEntityDataPacket::handle(PacketListener* listener) { + listener->handleTileEntityData(shared_from_this()); } -void TileEntityDataPacket::handle(PacketListener *listener) -{ - listener->handleTileEntityData(shared_from_this()); -} - -int TileEntityDataPacket::getEstimatedSize() -{ - return 6 * 4 + 1; -} \ No newline at end of file +int TileEntityDataPacket::getEstimatedSize() { return 6 * 4 + 1; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TileEntityDataPacket.h b/Minecraft.World/Network/Packets/TileEntityDataPacket.h index 8af857834..04618a043 100644 --- a/Minecraft.World/Network/Packets/TileEntityDataPacket.h +++ b/Minecraft.World/Network/Packets/TileEntityDataPacket.h @@ -1,36 +1,38 @@ #pragma once - #include "Packet.h" class CompoundTag; -class TileEntityDataPacket : public Packet, public std::enable_shared_from_this -{ +class TileEntityDataPacket + : public Packet, + public std::enable_shared_from_this { public: - static const int TYPE_MOB_SPAWNER = 1; - static const int TYPE_ADV_COMMAND = 2; - static const int TYPE_BEACON = 3; - static const int TYPE_SKULL = 4; + static const int TYPE_MOB_SPAWNER = 1; + static const int TYPE_ADV_COMMAND = 2; + static const int TYPE_BEACON = 3; + static const int TYPE_SKULL = 4; - int x, y, z; - int type; - CompoundTag *tag; + int x, y, z; + int type; + CompoundTag* tag; private: - void _init(); + void _init(); public: - TileEntityDataPacket(); - ~TileEntityDataPacket(); - TileEntityDataPacket(int x, int y, int z, int type, CompoundTag *tag); + TileEntityDataPacket(); + ~TileEntityDataPacket(); + TileEntityDataPacket(int x, int y, int z, int type, CompoundTag* tag); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TileEntityDataPacket()); } - virtual int getId() { return 132; } + static std::shared_ptr create() { + return std::shared_ptr(new TileEntityDataPacket()); + } + virtual int getId() { return 132; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TileEventPacket.cpp b/Minecraft.World/Network/Packets/TileEventPacket.cpp index 8204ee171..266535abf 100644 --- a/Minecraft.World/Network/Packets/TileEventPacket.cpp +++ b/Minecraft.World/Network/Packets/TileEventPacket.cpp @@ -5,52 +5,47 @@ #include "TileEventPacket.h" #include "../../Headers/net.minecraft.world.level.tile.h" -TileEventPacket::TileEventPacket() -{ - x = 0; - y = 0; - z = 0; - b0 = 0; - b1 = 0; - tile = 0; +TileEventPacket::TileEventPacket() { + x = 0; + y = 0; + z = 0; + b0 = 0; + b1 = 0; + tile = 0; } -TileEventPacket::TileEventPacket(int x, int y, int z, int tile, int b0, int b1) -{ - this->x = x; - this->y = y; - this->z = z; - this->b0 = b0; - this->b1 = b1; - this->tile = tile; +TileEventPacket::TileEventPacket(int x, int y, int z, int tile, int b0, + int b1) { + this->x = x; + this->y = y; + this->z = z; + this->b0 = b0; + this->b1 = b1; + this->tile = tile; } -void TileEventPacket::read(DataInputStream *dis) //throws IOException +void TileEventPacket::read(DataInputStream* dis) // throws IOException { - x = dis->readInt(); - y = dis->readShort(); - z = dis->readInt(); - b0 = dis->read(); - b1 = dis->read(); - tile = dis->readShort() & Tile::TILE_NUM_MASK; + x = dis->readInt(); + y = dis->readShort(); + z = dis->readInt(); + b0 = dis->read(); + b1 = dis->read(); + tile = dis->readShort() & Tile::TILE_NUM_MASK; } -void TileEventPacket::write(DataOutputStream *dos) //throws IOException +void TileEventPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(x); - dos->writeShort(y); - dos->writeInt(z); - dos->write(b0); - dos->write(b1); - dos->writeShort(tile & Tile::TILE_NUM_MASK); + dos->writeInt(x); + dos->writeShort(y); + dos->writeInt(z); + dos->write(b0); + dos->write(b1); + dos->writeShort(tile & Tile::TILE_NUM_MASK); } -void TileEventPacket::handle(PacketListener *listener) -{ - listener->handleTileEvent(shared_from_this()); +void TileEventPacket::handle(PacketListener* listener) { + listener->handleTileEvent(shared_from_this()); } -int TileEventPacket::getEstimatedSize() -{ - return 2 * 4 + 2 + 2 + 2; -} +int TileEventPacket::getEstimatedSize() { return 2 * 4 + 2 + 2 + 2; } diff --git a/Minecraft.World/Network/Packets/TileEventPacket.h b/Minecraft.World/Network/Packets/TileEventPacket.h index 381e2d0a9..c0938bbb7 100644 --- a/Minecraft.World/Network/Packets/TileEventPacket.h +++ b/Minecraft.World/Network/Packets/TileEventPacket.h @@ -1,22 +1,23 @@ #pragma once - #include "Packet.h" -class TileEventPacket : public Packet, public std::enable_shared_from_this -{ +class TileEventPacket : public Packet, + public std::enable_shared_from_this { public: - int x, y, z, b0, b1, tile; + int x, y, z, b0, b1, tile; - TileEventPacket(); - TileEventPacket(int x, int y, int z, int tile, int b0, int b1); + TileEventPacket(); + TileEventPacket(int x, int y, int z, int tile, int b0, int b1); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TileEventPacket()); } - virtual int getId() { return 54; } + static std::shared_ptr create() { + return std::shared_ptr(new TileEventPacket()); + } + virtual int getId() { return 54; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TileUpdatePacket.cpp b/Minecraft.World/Network/Packets/TileUpdatePacket.cpp index 563461500..b60058ebc 100644 --- a/Minecraft.World/Network/Packets/TileUpdatePacket.cpp +++ b/Minecraft.World/Network/Packets/TileUpdatePacket.cpp @@ -6,87 +6,83 @@ #include "TileUpdatePacket.h" #include "../../Level/Dimensions/Dimension.h" +TileUpdatePacket::TileUpdatePacket() { shouldDelay = true; } - -TileUpdatePacket::TileUpdatePacket() -{ - shouldDelay = true; +TileUpdatePacket::TileUpdatePacket(int x, int y, int z, Level* level) { + shouldDelay = true; + this->x = x; + this->y = y; + this->z = z; + block = level->getTile(x, y, z); + data = level->getData(x, y, z); + levelIdx = + ((level->dimension->id == 0) ? 0 + : ((level->dimension->id == -1) ? 1 : 2)); } -TileUpdatePacket::TileUpdatePacket(int x, int y, int z, Level *level) -{ - shouldDelay = true; - this->x = x; - this->y = y; - this->z = z; - block = level->getTile(x, y, z); - data = level->getData(x, y, z); - levelIdx = ( ( level->dimension->id == 0 ) ? 0 : ( (level->dimension->id == -1) ? 1 : 2 ) ); -} - -void TileUpdatePacket::read(DataInputStream *dis) //throws IOException +void TileUpdatePacket::read(DataInputStream* dis) // throws IOException { #ifdef _LARGE_WORLDS - x = dis->readInt(); - y = dis->read(); - z = dis->readInt(); - - block = (int)dis->readShort() & 0xffff; + x = dis->readInt(); + y = dis->read(); + z = dis->readInt(); - std::uint8_t dataLevel = dis->readByte(); - data = dataLevel & 0xf; - levelIdx = (dataLevel>>4) & 0xf; + block = (int)dis->readShort() & 0xffff; + + std::uint8_t dataLevel = dis->readByte(); + data = dataLevel & 0xf; + levelIdx = (dataLevel >> 4) & 0xf; #else - // 4J - See comments in write for packing - int xyzdata = dis->readInt(); - x = ( xyzdata >> 22 ) & 0x3ff; - y = ( xyzdata >> 14 ) & 0xff; - z = ( xyzdata >> 4 ) & 0x3ff; - x = ( x << 22 ) >> 22; - z = ( z << 22 ) >> 22; - data = xyzdata & 0xf; - block = (int)dis->readShort() & 0xffff; - //levelIdx = ( xyzdata >> 31 ) & 1; + // 4J - See comments in write for packing + int xyzdata = dis->readInt(); + x = (xyzdata >> 22) & 0x3ff; + y = (xyzdata >> 14) & 0xff; + z = (xyzdata >> 4) & 0x3ff; + x = (x << 22) >> 22; + z = (z << 22) >> 22; + data = xyzdata & 0xf; + block = (int)dis->readShort() & 0xffff; + // levelIdx = ( xyzdata >> 31 ) & 1; - // Can't pack this as it's now 2 bits - levelIdx = (int)dis->readByte(); + // Can't pack this as it's now 2 bits + levelIdx = (int)dis->readByte(); #endif } -void TileUpdatePacket::write(DataOutputStream *dos) //throws IOException +void TileUpdatePacket::write(DataOutputStream* dos) // throws IOException { #ifdef _LARGE_WORLDS - dos->writeInt(x); - dos->write(y); - dos->writeInt(z); - dos->writeShort(block); + dos->writeInt(x); + dos->write(y); + dos->writeInt(z); + dos->writeShort(block); - std::uint8_t dataLevel = ((levelIdx & 0xf ) << 4) | (data & 0xf); - dos->writeByte(dataLevel); + std::uint8_t dataLevel = ((levelIdx & 0xf) << 4) | (data & 0xf); + dos->writeByte(dataLevel); #else - // 4J - for our fixed size map, we can pack x & z into 10 bits each (-512 -> 511), y into 8 bits (0 to 255) - // block type could really be 7 bits but leaving that as 8 for future ease of expansion. Data only needs to be 4-bits as that is how it - // is ultimately stored - int xyzdata = ( ( x & 0x3ff ) << 22 ) | ( ( y & 0xff ) << 14 ) | ( ( z & 0x3ff ) << 4 ) | ( data & 0xf); - //xyzdata |= levelIdx << 31; - dos->writeInt(xyzdata); - dos->writeShort(block); + // 4J - for our fixed size map, we can pack x & z into 10 bits each (-512 -> + // 511), y into 8 bits (0 to 255) block type could really be 7 bits but + // leaving that as 8 for future ease of expansion. Data only needs to be + // 4-bits as that is how it is ultimately stored + int xyzdata = ((x & 0x3ff) << 22) | ((y & 0xff) << 14) | + ((z & 0x3ff) << 4) | (data & 0xf); + // xyzdata |= levelIdx << 31; + dos->writeInt(xyzdata); + dos->writeShort(block); - // Can't pack this as it's now 2 bits - dos->write(levelIdx); + // Can't pack this as it's now 2 bits + dos->write(levelIdx); #endif } -void TileUpdatePacket::handle(PacketListener *listener) -{ - listener->handleTileUpdate(shared_from_this()); +void TileUpdatePacket::handle(PacketListener* listener) { + listener->handleTileUpdate(shared_from_this()); } -int TileUpdatePacket::getEstimatedSize() -{ +int TileUpdatePacket::getEstimatedSize() { #ifdef _LARGE_WORLDS - return 12; + return 12; #else - return 5; + return 5; #endif } diff --git a/Minecraft.World/Network/Packets/TileUpdatePacket.h b/Minecraft.World/Network/Packets/TileUpdatePacket.h index f4d34fc01..373fa7522 100644 --- a/Minecraft.World/Network/Packets/TileUpdatePacket.h +++ b/Minecraft.World/Network/Packets/TileUpdatePacket.h @@ -1,23 +1,25 @@ #pragma once - #include "Packet.h" -class TileUpdatePacket : public Packet, public std::enable_shared_from_this -{ +class TileUpdatePacket : public Packet, + public std::enable_shared_from_this { public: - int x, y, z; + int x, y, z; int block, data; - int levelIdx; + int levelIdx; - TileUpdatePacket(); - TileUpdatePacket(int x, int y, int z, Level *level); + TileUpdatePacket(); + TileUpdatePacket(int x, int y, int z, Level* level); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TileUpdatePacket()); } - virtual int getId() { return 53; } + static std::shared_ptr create() { + return std::shared_ptr(new TileUpdatePacket()); + } + virtual int getId() { return 53; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/TradeItemPacket.cpp b/Minecraft.World/Network/Packets/TradeItemPacket.cpp index 6faeaf3e2..06c081872 100644 --- a/Minecraft.World/Network/Packets/TradeItemPacket.cpp +++ b/Minecraft.World/Network/Packets/TradeItemPacket.cpp @@ -4,38 +4,30 @@ #include "PacketListener.h" #include "TradeItemPacket.h" - - -TradeItemPacket::TradeItemPacket() -{ - containerId = 0; - offer = 0; +TradeItemPacket::TradeItemPacket() { + containerId = 0; + offer = 0; } -TradeItemPacket::TradeItemPacket(int containerId, int offer) -{ - this->containerId = containerId; - this->offer = offer; +TradeItemPacket::TradeItemPacket(int containerId, int offer) { + this->containerId = containerId; + this->offer = offer; } -void TradeItemPacket::handle(PacketListener *listener) -{ - listener->handleTradeItem(shared_from_this()); +void TradeItemPacket::handle(PacketListener* listener) { + listener->handleTradeItem(shared_from_this()); } -void TradeItemPacket::read(DataInputStream *dis) //throws IOException +void TradeItemPacket::read(DataInputStream* dis) // throws IOException { - containerId = dis->readInt(); - offer = dis->readInt(); + containerId = dis->readInt(); + offer = dis->readInt(); } -void TradeItemPacket::write(DataOutputStream *dos) //throws IOException +void TradeItemPacket::write(DataOutputStream* dos) // throws IOException { - dos->writeInt(containerId); - dos->writeInt(offer); + dos->writeInt(containerId); + dos->writeInt(offer); } -int TradeItemPacket::getEstimatedSize() -{ - return 8; -} +int TradeItemPacket::getEstimatedSize() { return 8; } diff --git a/Minecraft.World/Network/Packets/TradeItemPacket.h b/Minecraft.World/Network/Packets/TradeItemPacket.h index 17fb09aff..671409154 100644 --- a/Minecraft.World/Network/Packets/TradeItemPacket.h +++ b/Minecraft.World/Network/Packets/TradeItemPacket.h @@ -2,31 +2,29 @@ // 4J ADDED PACKET - - #include "Packet.h" #include "../../Platform/stdafx.h" #include #include "PacketListener.h" -class TradeItemPacket : public Packet, public std::enable_shared_from_this -{ +class TradeItemPacket : public Packet, + public std::enable_shared_from_this { public: int containerId; int offer; - TradeItemPacket(); - TradeItemPacket(int containerId, int offer); + TradeItemPacket(); + TradeItemPacket(int containerId, int offer); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new TradeItemPacket()); } - virtual int getId() { return 151; } + static std::shared_ptr create() { + return std::shared_ptr(new TradeItemPacket()); + } + virtual int getId() { return 151; } }; - - diff --git a/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.cpp b/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.cpp index 2a36215a5..b6065baa2 100644 --- a/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.cpp +++ b/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.cpp @@ -3,73 +3,66 @@ #include "PacketListener.h" #include "UpdateGameRuleProgressPacket.h" - - -UpdateGameRuleProgressPacket::UpdateGameRuleProgressPacket() -{ - m_messageId = L""; - m_icon = -1; - m_auxValue = 0; - m_definitionType = ConsoleGameRules::eGameRuleType_LevelRules; - m_dataTag = 0; +UpdateGameRuleProgressPacket::UpdateGameRuleProgressPacket() { + m_messageId = L""; + m_icon = -1; + m_auxValue = 0; + m_definitionType = ConsoleGameRules::eGameRuleType_LevelRules; + m_dataTag = 0; } -UpdateGameRuleProgressPacket::UpdateGameRuleProgressPacket(ConsoleGameRules::EGameRuleType definitionType, const std::wstring &messageId, int icon, int auxValue, int dataTag, void *data, int dataLength) -{ - m_definitionType = definitionType; - m_messageId = messageId; - m_icon = icon; - m_auxValue = auxValue; - m_dataTag = dataTag; +UpdateGameRuleProgressPacket::UpdateGameRuleProgressPacket( + ConsoleGameRules::EGameRuleType definitionType, + const std::wstring& messageId, int icon, int auxValue, int dataTag, + void* data, int dataLength) { + m_definitionType = definitionType; + m_messageId = messageId; + m_icon = icon; + m_auxValue = auxValue; + m_dataTag = dataTag; - if(dataLength > 0) - { - m_data = byteArray(dataLength); - memcpy(m_data.data,data,dataLength); - } - else - { - m_data = byteArray(); - } + if (dataLength > 0) { + m_data = byteArray(dataLength); + memcpy(m_data.data, data, dataLength); + } else { + m_data = byteArray(); + } } -void UpdateGameRuleProgressPacket::read(DataInputStream *dis) //throws IOException +void UpdateGameRuleProgressPacket::read( + DataInputStream* dis) // throws IOException { - m_definitionType = (ConsoleGameRules::EGameRuleType)dis->readInt(); - m_messageId = readUtf(dis,64); - m_icon = dis->readInt(); - m_auxValue = dis->readByte(); - m_dataTag = dis->readInt(); - int dataLength = dis->readInt(); + m_definitionType = (ConsoleGameRules::EGameRuleType)dis->readInt(); + m_messageId = readUtf(dis, 64); + m_icon = dis->readInt(); + m_auxValue = dis->readByte(); + m_dataTag = dis->readInt(); + int dataLength = dis->readInt(); - if(dataLength > 0) - { - m_data = byteArray(dataLength); - dis->readFully(m_data); - } - else - { - m_data = byteArray(); - } + if (dataLength > 0) { + m_data = byteArray(dataLength); + dis->readFully(m_data); + } else { + m_data = byteArray(); + } } -void UpdateGameRuleProgressPacket::write(DataOutputStream *dos) //throws IOException +void UpdateGameRuleProgressPacket::write( + DataOutputStream* dos) // throws IOException { - dos->writeInt(m_definitionType); - writeUtf(m_messageId,dos); - dos->writeInt(m_icon); - dos->writeByte(m_auxValue); - dos->writeInt(m_dataTag); - dos->writeInt(m_data.length); - dos->write(m_data); + dos->writeInt(m_definitionType); + writeUtf(m_messageId, dos); + dos->writeInt(m_icon); + dos->writeByte(m_auxValue); + dos->writeInt(m_dataTag); + dos->writeInt(m_data.length); + dos->write(m_data); } -void UpdateGameRuleProgressPacket::handle(PacketListener *listener) -{ - listener->handleUpdateGameRuleProgressPacket(shared_from_this()); +void UpdateGameRuleProgressPacket::handle(PacketListener* listener) { + listener->handleUpdateGameRuleProgressPacket(shared_from_this()); } -int UpdateGameRuleProgressPacket::getEstimatedSize() -{ - return (int)m_messageId.length() + 4 + m_data.length; +int UpdateGameRuleProgressPacket::getEstimatedSize() { + return (int)m_messageId.length() + 4 + m_data.length; } \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.h b/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.h index 645680112..3975037d2 100644 --- a/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.h +++ b/Minecraft.World/Network/Packets/UpdateGameRuleProgressPacket.h @@ -1,26 +1,31 @@ #pragma once - #include "Packet.h" -class UpdateGameRuleProgressPacket : public Packet, public std::enable_shared_from_this -{ +class UpdateGameRuleProgressPacket + : public Packet, + public std::enable_shared_from_this { public: - ConsoleGameRules::EGameRuleType m_definitionType; - std::wstring m_messageId; - int m_icon, m_auxValue; - int m_dataTag; - byteArray m_data; + ConsoleGameRules::EGameRuleType m_definitionType; + std::wstring m_messageId; + int m_icon, m_auxValue; + int m_dataTag; + byteArray m_data; - UpdateGameRuleProgressPacket(); - UpdateGameRuleProgressPacket(ConsoleGameRules::EGameRuleType definitionType, const std::wstring &messageId, int icon, int auxValue, int dataTag, void *data, int dataLength); + UpdateGameRuleProgressPacket(); + UpdateGameRuleProgressPacket(ConsoleGameRules::EGameRuleType definitionType, + const std::wstring& messageId, int icon, + int auxValue, int dataTag, void* data, + int dataLength); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new UpdateGameRuleProgressPacket()); } - virtual int getId() { return 158; } + static std::shared_ptr create() { + return std::shared_ptr(new UpdateGameRuleProgressPacket()); + } + virtual int getId() { return 158; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/UpdateMobEffectPacket.cpp b/Minecraft.World/Network/Packets/UpdateMobEffectPacket.cpp index 443c24c56..894ddda09 100644 --- a/Minecraft.World/Network/Packets/UpdateMobEffectPacket.cpp +++ b/Minecraft.World/Network/Packets/UpdateMobEffectPacket.cpp @@ -4,57 +4,45 @@ #include "PacketListener.h" #include "UpdateMobEffectPacket.h" - - -UpdateMobEffectPacket::UpdateMobEffectPacket() -{ - this->entityId = 0; - this->effectId = 0; - this->effectAmplifier = 0; - this->effectDurationTicks = 0; +UpdateMobEffectPacket::UpdateMobEffectPacket() { + this->entityId = 0; + this->effectId = 0; + this->effectAmplifier = 0; + this->effectDurationTicks = 0; } -UpdateMobEffectPacket::UpdateMobEffectPacket(int entityId, MobEffectInstance *effect) -{ - this->entityId = entityId; - this->effectId = static_cast(effect->getId() & 0xff); - this->effectAmplifier = (char) (effect->getAmplifier() & 0xff); - this->effectDurationTicks = (short) effect->getDuration(); +UpdateMobEffectPacket::UpdateMobEffectPacket(int entityId, + MobEffectInstance* effect) { + this->entityId = entityId; + this->effectId = static_cast(effect->getId() & 0xff); + this->effectAmplifier = (char)(effect->getAmplifier() & 0xff); + this->effectDurationTicks = (short)effect->getDuration(); } -void UpdateMobEffectPacket::read(DataInputStream *dis) -{ - entityId = dis->readInt(); - effectId = dis->readByte(); - effectAmplifier = dis->readByte(); - effectDurationTicks = dis->readShort(); +void UpdateMobEffectPacket::read(DataInputStream* dis) { + entityId = dis->readInt(); + effectId = dis->readByte(); + effectAmplifier = dis->readByte(); + effectDurationTicks = dis->readShort(); } -void UpdateMobEffectPacket::write(DataOutputStream *dos) -{ - dos->writeInt(entityId); - dos->writeByte(effectId); - dos->writeByte(effectAmplifier); - dos->writeShort(effectDurationTicks); +void UpdateMobEffectPacket::write(DataOutputStream* dos) { + dos->writeInt(entityId); + dos->writeByte(effectId); + dos->writeByte(effectAmplifier); + dos->writeShort(effectDurationTicks); } -void UpdateMobEffectPacket::handle(PacketListener *listener) -{ - listener->handleUpdateMobEffect(shared_from_this()); +void UpdateMobEffectPacket::handle(PacketListener* listener) { + listener->handleUpdateMobEffect(shared_from_this()); } -int UpdateMobEffectPacket::getEstimatedSize() -{ - return 8; -} +int UpdateMobEffectPacket::getEstimatedSize() { return 8; } -bool UpdateMobEffectPacket::canBeInvalidated() -{ - return true; -} +bool UpdateMobEffectPacket::canBeInvalidated() { return true; } -bool UpdateMobEffectPacket::isInvalidatedBy(std::shared_ptr packet) -{ - std::shared_ptr target = std::dynamic_pointer_cast(packet); - return target->entityId == entityId && target->effectId == effectId; +bool UpdateMobEffectPacket::isInvalidatedBy(std::shared_ptr packet) { + std::shared_ptr target = + std::dynamic_pointer_cast(packet); + return target->entityId == entityId && target->effectId == effectId; } diff --git a/Minecraft.World/Network/Packets/UpdateMobEffectPacket.h b/Minecraft.World/Network/Packets/UpdateMobEffectPacket.h index d8d6c879e..b732ba1af 100644 --- a/Minecraft.World/Network/Packets/UpdateMobEffectPacket.h +++ b/Minecraft.World/Network/Packets/UpdateMobEffectPacket.h @@ -5,25 +5,28 @@ class MobEffectInstance; -class UpdateMobEffectPacket : public Packet, public std::enable_shared_from_this -{ +class UpdateMobEffectPacket + : public Packet, + public std::enable_shared_from_this { public: - int entityId; - std::uint8_t effectId; - char effectAmplifier; - short effectDurationTicks; + int entityId; + std::uint8_t effectId; + char effectAmplifier; + short effectDurationTicks; - UpdateMobEffectPacket(); - UpdateMobEffectPacket(int entityId, MobEffectInstance *effect); + UpdateMobEffectPacket(); + UpdateMobEffectPacket(int entityId, MobEffectInstance* effect); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - virtual bool canBeInvalidated(); - virtual bool isInvalidatedBy(std::shared_ptr packet); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); + virtual bool canBeInvalidated(); + virtual bool isInvalidatedBy(std::shared_ptr packet); public: - static std::shared_ptr create() { return std::shared_ptr(new UpdateMobEffectPacket()); } - virtual int getId() { return 41; } + static std::shared_ptr create() { + return std::shared_ptr(new UpdateMobEffectPacket()); + } + virtual int getId() { return 41; } }; diff --git a/Minecraft.World/Network/Packets/UpdateProgressPacket.cpp b/Minecraft.World/Network/Packets/UpdateProgressPacket.cpp index ec551e16d..e1253ed11 100644 --- a/Minecraft.World/Network/Packets/UpdateProgressPacket.cpp +++ b/Minecraft.World/Network/Packets/UpdateProgressPacket.cpp @@ -4,34 +4,24 @@ #include "PacketListener.h" #include "UpdateProgressPacket.h" +UpdateProgressPacket::UpdateProgressPacket() { this->m_percentage = 0; } - -UpdateProgressPacket::UpdateProgressPacket() -{ - this->m_percentage = 0; +UpdateProgressPacket::UpdateProgressPacket(int percentage) { + this->m_percentage = percentage; } -UpdateProgressPacket::UpdateProgressPacket(int percentage) +void UpdateProgressPacket::read(DataInputStream* dis) // throws IOException { - this->m_percentage = percentage; + m_percentage = dis->readByte(); } -void UpdateProgressPacket::read(DataInputStream *dis) //throws IOException +void UpdateProgressPacket::write(DataOutputStream* dos) // throws IOException { - m_percentage = dis->readByte(); + dos->writeByte(m_percentage); } -void UpdateProgressPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeByte(m_percentage); +void UpdateProgressPacket::handle(PacketListener* listener) { + listener->handleUpdateProgress(shared_from_this()); } -void UpdateProgressPacket::handle(PacketListener *listener) -{ - listener->handleUpdateProgress(shared_from_this()); -} - -int UpdateProgressPacket::getEstimatedSize() -{ - return 1; -} +int UpdateProgressPacket::getEstimatedSize() { return 1; } diff --git a/Minecraft.World/Network/Packets/UpdateProgressPacket.h b/Minecraft.World/Network/Packets/UpdateProgressPacket.h index 66e986b4f..6d82f0bad 100644 --- a/Minecraft.World/Network/Packets/UpdateProgressPacket.h +++ b/Minecraft.World/Network/Packets/UpdateProgressPacket.h @@ -1,25 +1,27 @@ #pragma once - #include "Packet.h" -// 4J Added packet to update clients on the time for the host to finish doing something +// 4J Added packet to update clients on the time for the host to finish doing +// something -class UpdateProgressPacket : public Packet, public std::enable_shared_from_this -{ +class UpdateProgressPacket + : public Packet, + public std::enable_shared_from_this { +public: + int m_percentage; + + UpdateProgressPacket(); + UpdateProgressPacket(int percentage); + + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); public: - int m_percentage; - - UpdateProgressPacket(); - UpdateProgressPacket(int percentage); - - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); - -public: - static std::shared_ptr create() { return std::shared_ptr(new UpdateProgressPacket()); } - virtual int getId() { return 156; } + static std::shared_ptr create() { + return std::shared_ptr(new UpdateProgressPacket()); + } + virtual int getId() { return 156; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Packets/UseItemPacket.cpp b/Minecraft.World/Network/Packets/UseItemPacket.cpp index 675610420..2a527fd67 100644 --- a/Minecraft.World/Network/Packets/UseItemPacket.cpp +++ b/Minecraft.World/Network/Packets/UseItemPacket.cpp @@ -7,106 +7,77 @@ const float UseItemPacket::CLICK_ACCURACY = 16.0f; -UseItemPacket::~UseItemPacket() -{ +UseItemPacket::~UseItemPacket() {} + +UseItemPacket::UseItemPacket() { + x = 0; + y = 0; + z = 0; + face = 0; + item = nullptr; + clickX = 0.0f; + clickY = 0.0f; + clickZ = 0.0f; } -UseItemPacket::UseItemPacket() -{ - x = 0; - y = 0; - z = 0; - face = 0; - item = nullptr; - clickX = 0.0f; - clickY = 0.0f; - clickZ = 0.0f; +UseItemPacket::UseItemPacket(int x, int y, int z, int face, + std::shared_ptr item, float clickX, + float clickY, float clickZ) { + this->x = x; + this->y = y; + this->z = z; + this->face = face; + // 4J - take copy of item as we want our packets to have full ownership of + // any referenced data + this->item = item ? item->copy() : std::shared_ptr(); + this->clickX = clickX; + this->clickY = clickY; + this->clickZ = clickZ; } -UseItemPacket::UseItemPacket(int x, int y, int z, int face, std::shared_ptr item, float clickX, float clickY, float clickZ) +void UseItemPacket::read(DataInputStream* dis) // throws IOException { - this->x = x; - this->y = y; - this->z = z; - this->face = face; - // 4J - take copy of item as we want our packets to have full ownership of any referenced data - this->item = item ? item->copy() : std::shared_ptr(); - this->clickX = clickX; - this->clickY = clickY; - this->clickZ = clickZ; + x = dis->readInt(); + y = dis->read(); + z = dis->readInt(); + face = dis->read(); + item = readItem(dis); + clickX = dis->read() / CLICK_ACCURACY; + clickY = dis->read() / CLICK_ACCURACY; + clickZ = dis->read() / CLICK_ACCURACY; } -void UseItemPacket::read(DataInputStream *dis) //throws IOException +void UseItemPacket::write(DataOutputStream* dos) // throws IOException { - x = dis->readInt(); - y = dis->read(); - z = dis->readInt(); - face = dis->read(); - item = readItem(dis); - clickX = dis->read() / CLICK_ACCURACY; - clickY = dis->read() / CLICK_ACCURACY; - clickZ = dis->read() / CLICK_ACCURACY; + dos->writeInt(x); + dos->write(y); + dos->writeInt(z); + dos->write(face); + + writeItem(item, dos); + dos->write((int)(clickX * CLICK_ACCURACY)); + dos->write((int)(clickY * CLICK_ACCURACY)); + dos->write((int)(clickZ * CLICK_ACCURACY)); } -void UseItemPacket::write(DataOutputStream *dos) //throws IOException -{ - dos->writeInt(x); - dos->write(y); - dos->writeInt(z); - dos->write(face); - - writeItem(item, dos); - dos->write((int) (clickX * CLICK_ACCURACY)); - dos->write((int) (clickY * CLICK_ACCURACY)); - dos->write((int)(clickZ * CLICK_ACCURACY)); +void UseItemPacket::handle(PacketListener* listener) { + listener->handleUseItem(shared_from_this()); } -void UseItemPacket::handle(PacketListener *listener) -{ - listener->handleUseItem(shared_from_this()); -} +int UseItemPacket::getEstimatedSize() { return 15; } -int UseItemPacket::getEstimatedSize() -{ - return 15; -} +int UseItemPacket::getX() { return x; } -int UseItemPacket::getX() -{ - return x; -} +int UseItemPacket::getY() { return y; } -int UseItemPacket::getY() -{ - return y; -} +int UseItemPacket::getZ() { return z; } -int UseItemPacket::getZ() -{ - return z; -} +int UseItemPacket::getFace() { return face; } -int UseItemPacket::getFace() -{ - return face; -} +std::shared_ptr UseItemPacket::getItem() { return item; } -std::shared_ptr UseItemPacket::getItem() -{ - return item; -} +float UseItemPacket::getClickX() { return clickX; } -float UseItemPacket::getClickX() -{ - return clickX; -} +float UseItemPacket::getClickY() { return clickY; } -float UseItemPacket::getClickY() -{ - return clickY; -} - -float UseItemPacket::getClickZ() -{ - return clickZ; -} +float UseItemPacket::getClickZ() { return clickZ; } diff --git a/Minecraft.World/Network/Packets/UseItemPacket.h b/Minecraft.World/Network/Packets/UseItemPacket.h index 0ac662ae4..c472bb1e2 100644 --- a/Minecraft.World/Network/Packets/UseItemPacket.h +++ b/Minecraft.World/Network/Packets/UseItemPacket.h @@ -1,36 +1,39 @@ #pragma once - #include "Packet.h" -class UseItemPacket : public Packet, public std::enable_shared_from_this -{ +class UseItemPacket : public Packet, + public std::enable_shared_from_this { private: - static const float CLICK_ACCURACY; - int x, y, z, face; - std::shared_ptr item; - float clickX, clickY, clickZ; + static const float CLICK_ACCURACY; + int x, y, z, face; + std::shared_ptr item; + float clickX, clickY, clickZ; public: - UseItemPacket(); - UseItemPacket(int x, int y, int z, int face, std::shared_ptr item, float clickX, float clickY, float clickZ); - ~UseItemPacket(); + UseItemPacket(); + UseItemPacket(int x, int y, int z, int face, + std::shared_ptr item, float clickX, + float clickY, float clickZ); + ~UseItemPacket(); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual void handle(PacketListener *listener); - virtual int getEstimatedSize(); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual void handle(PacketListener* listener); + virtual int getEstimatedSize(); - int getX(); - int getY(); - int getZ(); - int getFace(); - std::shared_ptr getItem(); - float getClickX(); - float getClickY(); - float getClickZ(); + int getX(); + int getY(); + int getZ(); + int getFace(); + std::shared_ptr getItem(); + float getClickX(); + float getClickY(); + float getClickZ(); public: - static std::shared_ptr create() { return std::shared_ptr(new UseItemPacket()); } - virtual int getId() { return 15; } + static std::shared_ptr create() { + return std::shared_ptr(new UseItemPacket()); + } + virtual int getId() { return 15; } }; diff --git a/Minecraft.World/Network/Packets/XZPacket.cpp b/Minecraft.World/Network/Packets/XZPacket.cpp index 4a14d1832..c131cbbda 100644 --- a/Minecraft.World/Network/Packets/XZPacket.cpp +++ b/Minecraft.World/Network/Packets/XZPacket.cpp @@ -5,48 +5,38 @@ #include "PacketListener.h" #include "XZPacket.h" +const int XZPacket::STRONGHOLD = 0; +XZPacket::~XZPacket() {} -const int XZPacket::STRONGHOLD = 0; - -XZPacket::~XZPacket() -{ +XZPacket::XZPacket() { + action = STRONGHOLD; + x = 0; + z = 0; } -XZPacket::XZPacket() -{ - action = STRONGHOLD; - x = 0; - z = 0; +XZPacket::XZPacket(char action, int x, int z) { + this->action = action; + this->x = x; + this->z = z; } -XZPacket::XZPacket(char action, int x, int z) -{ - this->action = action; - this->x = x; - this->z = z; +void XZPacket::handle(PacketListener* listener) { + listener->handleXZ(shared_from_this()); } -void XZPacket::handle(PacketListener *listener) +void XZPacket::read(DataInputStream* dis) // throws IOException { - listener->handleXZ(shared_from_this()); + action = dis->read(); + x = dis->readInt(); + z = dis->readInt(); } -void XZPacket::read(DataInputStream *dis) //throws IOException +void XZPacket::write(DataOutputStream* dos) // throws IOException { - action = dis->read(); - x = dis->readInt(); - z = dis->readInt(); + dos->write(action); + dos->writeInt(x); + dos->writeInt(z); } -void XZPacket::write(DataOutputStream *dos) // throws IOException -{ - dos->write(action); - dos->writeInt(x); - dos->writeInt(z); -} - -int XZPacket::getEstimatedSize() -{ - return 10; -} +int XZPacket::getEstimatedSize() { return 10; } diff --git a/Minecraft.World/Network/Packets/XZPacket.h b/Minecraft.World/Network/Packets/XZPacket.h index 4ae6e833a..33111bdf1 100644 --- a/Minecraft.World/Network/Packets/XZPacket.h +++ b/Minecraft.World/Network/Packets/XZPacket.h @@ -2,29 +2,28 @@ // 4J ADDED THIS PACKET - - #include "Packet.h" -class XZPacket : public Packet, public std::enable_shared_from_this -{ +class XZPacket : public Packet, public std::enable_shared_from_this { public: - static const int STRONGHOLD; + static const int STRONGHOLD; - char action; - int x; - int z; + char action; + int x; + int z; - XZPacket(); - ~XZPacket(); - XZPacket(char action, int x, int z); + XZPacket(); + ~XZPacket(); + XZPacket(char action, int x, int z); - virtual void handle(PacketListener *listener); - virtual void read(DataInputStream *dis); - virtual void write(DataOutputStream *dos); - virtual int getEstimatedSize(); + virtual void handle(PacketListener* listener); + virtual void read(DataInputStream* dis); + virtual void write(DataOutputStream* dos); + virtual int getEstimatedSize(); public: - static std::shared_ptr create() { return std::shared_ptr(new XZPacket()); } - virtual int getId() { return 166; } + static std::shared_ptr create() { + return std::shared_ptr(new XZPacket()); + } + virtual int getId() { return 166; } }; \ No newline at end of file diff --git a/Minecraft.World/Network/Socket.cpp b/Minecraft.World/Network/Socket.cpp index 010b29dfe..c27f852b1 100644 --- a/Minecraft.World/Network/Socket.cpp +++ b/Minecraft.World/Network/Socket.cpp @@ -7,561 +7,487 @@ #include #include "../../Minecraft.Client/Platform/PS3/PS3Extras/ShutdownManager.h" -// This current socket implementation is for the creation of a single local link. 2 sockets can be created, one for either end of this local -// link, the end (0 or 1) is passed as a parameter to the ctor. +// This current socket implementation is for the creation of a single local +// link. 2 sockets can be created, one for either end of this local link, the +// end (0 or 1) is passed as a parameter to the ctor. -CRITICAL_SECTION Socket::s_hostQueueLock[2]; +CRITICAL_SECTION Socket::s_hostQueueLock[2]; std::queue Socket::s_hostQueue[2]; -Socket::SocketOutputStreamLocal *Socket::s_hostOutStream[2]; -Socket::SocketInputStreamLocal *Socket::s_hostInStream[2]; -ServerConnection *Socket::s_serverConnection = NULL; +Socket::SocketOutputStreamLocal* Socket::s_hostOutStream[2]; +Socket::SocketInputStreamLocal* Socket::s_hostInStream[2]; +ServerConnection* Socket::s_serverConnection = NULL; -void Socket::EnsureStreamsInitialised() -{ - // Thread-safe one-time initialisation via C++11 magic-statics guarantee. - // The lambda body runs exactly once no matter how many threads call concurrently. - static bool initialized = []() -> bool { - for( int i = 0; i < 2; i++ ) - { - InitializeCriticalSection(&Socket::s_hostQueueLock[i]); - s_hostOutStream[i] = new SocketOutputStreamLocal(i); - s_hostInStream[i] = new SocketInputStreamLocal(i); - } - return true; - }(); - (void)initialized; +void Socket::EnsureStreamsInitialised() { + // Thread-safe one-time initialisation via C++11 magic-statics guarantee. + // The lambda body runs exactly once no matter how many threads call + // concurrently. + static bool initialized = []() -> bool { + for (int i = 0; i < 2; i++) { + InitializeCriticalSection(&Socket::s_hostQueueLock[i]); + s_hostOutStream[i] = new SocketOutputStreamLocal(i); + s_hostInStream[i] = new SocketInputStreamLocal(i); + } + return true; + }(); + (void)initialized; } -void Socket::Initialise(ServerConnection *serverConnection) -{ - s_serverConnection = serverConnection; +void Socket::Initialise(ServerConnection* serverConnection) { + s_serverConnection = serverConnection; - // Ensure the host-local stream objects exist (idempotent). - EnsureStreamsInitialised(); + // Ensure the host-local stream objects exist (idempotent). + EnsureStreamsInitialised(); - // Only initialise everything else once - just setting up static data, one time xrnm things, thread for ticking sockets - static bool init = false; - if( init ) - { - // Streams already exist – just reset queue state and re-open streams. - for( int i = 0; i < 2; i++ ) - { - if(TryEnterCriticalSection(&s_hostQueueLock[i])) - { - // Clear the queue - std::queue empty; - std::swap( s_hostQueue[i], empty ); - LeaveCriticalSection(&s_hostQueueLock[i]); - } - s_hostOutStream[i]->m_streamOpen = true; - s_hostInStream[i]->m_streamOpen = true; - } - return; - } - init = true; - // Streams are already guaranteed to exist via EnsureStreamsInitialised() above. - // Nothing more to do for the first call. + // Only initialise everything else once - just setting up static data, one + // time xrnm things, thread for ticking sockets + static bool init = false; + if (init) { + // Streams already exist – just reset queue state and re-open streams. + for (int i = 0; i < 2; i++) { + if (TryEnterCriticalSection(&s_hostQueueLock[i])) { + // Clear the queue + std::queue empty; + std::swap(s_hostQueue[i], empty); + LeaveCriticalSection(&s_hostQueueLock[i]); + } + s_hostOutStream[i]->m_streamOpen = true; + s_hostInStream[i]->m_streamOpen = true; + } + return; + } + init = true; + // Streams are already guaranteed to exist via EnsureStreamsInitialised() + // above. Nothing more to do for the first call. } -Socket::Socket(bool response) -{ - m_hostServerConnection = true; - m_hostLocal = true; - if( response ) - { - m_end = SOCKET_SERVER_END; - } - else - { - m_end = SOCKET_CLIENT_END; - Socket *socket = new Socket(1); - if ( s_serverConnection != NULL ) - { - s_serverConnection->NewIncomingSocket(socket); - } - else - { - app.DebugPrintf("SOCKET: Warning - attempted to notify server of new incoming socket but s_serverConnection is NULL\n"); - } - } +Socket::Socket(bool response) { + m_hostServerConnection = true; + m_hostLocal = true; + if (response) { + m_end = SOCKET_SERVER_END; + } else { + m_end = SOCKET_CLIENT_END; + Socket* socket = new Socket(1); + if (s_serverConnection != NULL) { + s_serverConnection->NewIncomingSocket(socket); + } else { + app.DebugPrintf( + "SOCKET: Warning - attempted to notify server of new incoming " + "socket but s_serverConnection is NULL\n"); + } + } - for( int i = 0; i < 2; i++ ) - { - m_endClosed[i] = false; - } - m_socketClosedEvent = NULL; - createdOk = true; - networkPlayerSmallId = g_NetworkManager.GetHostPlayer()->GetSmallId(); + for (int i = 0; i < 2; i++) { + m_endClosed[i] = false; + } + m_socketClosedEvent = NULL; + createdOk = true; + networkPlayerSmallId = g_NetworkManager.GetHostPlayer()->GetSmallId(); } -Socket::Socket(INetworkPlayer *player, bool response /* = false*/, bool hostLocal /*= false*/) -{ - m_hostServerConnection = false; - m_hostLocal = hostLocal; +Socket::Socket(INetworkPlayer* player, bool response /* = false*/, + bool hostLocal /*= false*/) { + m_hostServerConnection = false; + m_hostLocal = hostLocal; - for( int i = 0; i < 2; i++ ) - { - InitializeCriticalSection(&m_queueLockNetwork[i]); - m_inputStream[i] = NULL; - m_outputStream[i] = NULL; - m_endClosed[i] = false; - } - - if(!response || hostLocal) - { - m_inputStream[0] = new SocketInputStreamNetwork(this,0); - m_outputStream[0] = new SocketOutputStreamNetwork(this,0); - m_end = SOCKET_CLIENT_END; - } - if(response || hostLocal) - { - m_inputStream[1] = new SocketInputStreamNetwork(this,1); - m_outputStream[1] = new SocketOutputStreamNetwork(this,1); - m_end = SOCKET_SERVER_END; - } - m_socketClosedEvent = new C4JThread::Event; - //printf("New socket made %s\n", player->GetGamertag() ); - networkPlayerSmallId = player->GetSmallId(); - createdOk = true; + for (int i = 0; i < 2; i++) { + InitializeCriticalSection(&m_queueLockNetwork[i]); + m_inputStream[i] = NULL; + m_outputStream[i] = NULL; + m_endClosed[i] = false; + } + + if (!response || hostLocal) { + m_inputStream[0] = new SocketInputStreamNetwork(this, 0); + m_outputStream[0] = new SocketOutputStreamNetwork(this, 0); + m_end = SOCKET_CLIENT_END; + } + if (response || hostLocal) { + m_inputStream[1] = new SocketInputStreamNetwork(this, 1); + m_outputStream[1] = new SocketOutputStreamNetwork(this, 1); + m_end = SOCKET_SERVER_END; + } + m_socketClosedEvent = new C4JThread::Event; + // printf("New socket made %s\n", player->GetGamertag() ); + networkPlayerSmallId = player->GetSmallId(); + createdOk = true; } -SocketAddress *Socket::getRemoteSocketAddress() -{ - return NULL; +SocketAddress* Socket::getRemoteSocketAddress() { return NULL; } + +INetworkPlayer* Socket::getPlayer() { + return g_NetworkManager.GetPlayerBySmallId(networkPlayerSmallId); } -INetworkPlayer *Socket::getPlayer() -{ - return g_NetworkManager.GetPlayerBySmallId(networkPlayerSmallId); +void Socket::setPlayer(INetworkPlayer* player) { + if (player != NULL) { + networkPlayerSmallId = player->GetSmallId(); + } else { + networkPlayerSmallId = 0; + } } -void Socket::setPlayer(INetworkPlayer *player) -{ - if(player!=NULL) - { - networkPlayerSmallId = player->GetSmallId(); - } - else - { - networkPlayerSmallId = 0; - } +void Socket::pushDataToQueue(const std::uint8_t* pbData, std::size_t dataSize, + bool fromHost /*= true*/) { + int queueIdx = SOCKET_CLIENT_END; + if (!fromHost) queueIdx = SOCKET_SERVER_END; + + if (queueIdx != m_end && !m_hostLocal) { + app.DebugPrintf( + "SOCKET: Error pushing data to queue. End is %d but queue idx id " + "%d\n", + m_end, queueIdx); + return; + } + + EnterCriticalSection(&m_queueLockNetwork[queueIdx]); + for (std::size_t i = 0; i < dataSize; ++i) { + m_queueNetwork[queueIdx].push(*pbData++); + } + LeaveCriticalSection(&m_queueLockNetwork[queueIdx]); } -void Socket::pushDataToQueue(const std::uint8_t *pbData, std::size_t dataSize, bool fromHost /*= true*/) -{ - int queueIdx = SOCKET_CLIENT_END; - if(!fromHost) - queueIdx = SOCKET_SERVER_END; - - if( queueIdx != m_end && !m_hostLocal ) - { - app.DebugPrintf("SOCKET: Error pushing data to queue. End is %d but queue idx id %d\n", m_end, queueIdx); - return; - } - - EnterCriticalSection(&m_queueLockNetwork[queueIdx]); - for(std::size_t i = 0; i < dataSize; ++i) - { - m_queueNetwork[queueIdx].push(*pbData++); - } - LeaveCriticalSection(&m_queueLockNetwork[queueIdx]); +void Socket::addIncomingSocket(Socket* socket) { + if (s_serverConnection != NULL) { + s_serverConnection->NewIncomingSocket(socket); + } } -void Socket::addIncomingSocket(Socket *socket) -{ - if( s_serverConnection != NULL ) - { - s_serverConnection->NewIncomingSocket(socket); - } +InputStream* Socket::getInputStream(bool isServerConnection) { + if (!m_hostServerConnection) { + if (m_hostLocal) { + if (isServerConnection) { + return m_inputStream[SOCKET_SERVER_END]; + } else { + return m_inputStream[SOCKET_CLIENT_END]; + } + } else { + return m_inputStream[m_end]; + } + } else { + if (s_hostInStream[m_end] == NULL) { + app.DebugPrintf( + "SOCKET: Warning - s_hostInStream[%d] is NULL in " + "getInputStream(); calling EnsureStreamsInitialised()\n", + m_end); + EnsureStreamsInitialised(); + } + return s_hostInStream[m_end]; + } } -InputStream *Socket::getInputStream(bool isServerConnection) -{ - if( !m_hostServerConnection ) - { - if( m_hostLocal ) - { - if( isServerConnection ) - { - return m_inputStream[SOCKET_SERVER_END]; - } - else - { - return m_inputStream[SOCKET_CLIENT_END]; - } - } - else - { - return m_inputStream[m_end]; - } - } - else - { - if( s_hostInStream[m_end] == NULL ) - { - app.DebugPrintf("SOCKET: Warning - s_hostInStream[%d] is NULL in getInputStream(); calling EnsureStreamsInitialised()\n", m_end); - EnsureStreamsInitialised(); - } - return s_hostInStream[m_end]; - } +void Socket::setSoTimeout(int a) {} + +void Socket::setTrafficClass(int a) {} + +Socket::SocketOutputStream* Socket::getOutputStream(bool isServerConnection) { + if (!m_hostServerConnection) { + if (m_hostLocal) { + if (isServerConnection) { + return m_outputStream[SOCKET_SERVER_END]; + } else { + return m_outputStream[SOCKET_CLIENT_END]; + } + } else { + return m_outputStream[m_end]; + } + } else { + int outIdx = 1 - m_end; + if (s_hostOutStream[outIdx] == NULL) { + app.DebugPrintf( + "SOCKET: Warning - s_hostOutStream[%d] is NULL in " + "getOutputStream(); calling EnsureStreamsInitialised()\n", + outIdx); + EnsureStreamsInitialised(); + } + return s_hostOutStream[outIdx]; + } } -void Socket::setSoTimeout(int a ) -{ +bool Socket::close(bool isServerConnection) { + bool allClosed = false; + if (m_hostLocal) { + if (isServerConnection) { + m_endClosed[SOCKET_SERVER_END] = true; + if (m_endClosed[SOCKET_CLIENT_END]) { + allClosed = true; + } + } else { + m_endClosed[SOCKET_CLIENT_END] = true; + if (m_endClosed[SOCKET_SERVER_END]) { + allClosed = true; + } + } + } else { + allClosed = true; + m_endClosed[m_end] = true; + } + if (allClosed && m_socketClosedEvent != NULL) { + m_socketClosedEvent->Set(); + } + if (allClosed) createdOk = false; + return allClosed; } -void Socket::setTrafficClass( int a ) -{ -} +/////////////////////////////////// Socket for input, on local connection +/////////////////////// -Socket::SocketOutputStream *Socket::getOutputStream(bool isServerConnection) -{ - if( !m_hostServerConnection ) - { - if( m_hostLocal ) - { - if( isServerConnection ) - { - return m_outputStream[SOCKET_SERVER_END]; - } - else - { - return m_outputStream[SOCKET_CLIENT_END]; - } - } - else - { - return m_outputStream[m_end]; - } - } - else - { - int outIdx = 1 - m_end; - if( s_hostOutStream[outIdx] == NULL ) - { - app.DebugPrintf("SOCKET: Warning - s_hostOutStream[%d] is NULL in getOutputStream(); calling EnsureStreamsInitialised()\n", outIdx); - EnsureStreamsInitialised(); - } - return s_hostOutStream[outIdx]; - } -} - -bool Socket::close(bool isServerConnection) -{ - bool allClosed = false; - if( m_hostLocal ) - { - if( isServerConnection ) - { - m_endClosed[SOCKET_SERVER_END] = true; - if(m_endClosed[SOCKET_CLIENT_END]) - { - allClosed = true; - } - } - else - { - m_endClosed[SOCKET_CLIENT_END] = true; - if(m_endClosed[SOCKET_SERVER_END]) - { - allClosed = true; - } - } - } - else - { - allClosed = true; - m_endClosed[m_end] = true; - } - if( allClosed && m_socketClosedEvent != NULL ) - { - m_socketClosedEvent->Set(); - } - if(allClosed) createdOk = false; - return allClosed; -} - -/////////////////////////////////// Socket for input, on local connection //////////////////// - -Socket::SocketInputStreamLocal::SocketInputStreamLocal(int queueIdx) -{ - m_streamOpen = true; - m_queueIdx = queueIdx; +Socket::SocketInputStreamLocal::SocketInputStreamLocal(int queueIdx) { + m_streamOpen = true; + m_queueIdx = queueIdx; } // Try and get an input byte, blocking until one is available -int Socket::SocketInputStreamLocal::read() -{ - while(m_streamOpen && ShutdownManager::ShouldRun(ShutdownManager::eConnectionReadThreads)) - { - if(TryEnterCriticalSection(&s_hostQueueLock[m_queueIdx])) - { - if( s_hostQueue[m_queueIdx].size() ) - { - std::uint8_t retval = s_hostQueue[m_queueIdx].front(); - s_hostQueue[m_queueIdx].pop(); - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); - return retval; - } - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); - } - Sleep(1); - } - return -1; +int Socket::SocketInputStreamLocal::read() { + while (m_streamOpen && ShutdownManager::ShouldRun( + ShutdownManager::eConnectionReadThreads)) { + if (TryEnterCriticalSection(&s_hostQueueLock[m_queueIdx])) { + if (s_hostQueue[m_queueIdx].size()) { + std::uint8_t retval = s_hostQueue[m_queueIdx].front(); + s_hostQueue[m_queueIdx].pop(); + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); + return retval; + } + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); + } + Sleep(1); + } + return -1; } -// Try and get an input array of bytes, blocking until enough bytes are available -int Socket::SocketInputStreamLocal::read(byteArray b) -{ - return read(b, 0, b.length); +// Try and get an input array of bytes, blocking until enough bytes are +// available +int Socket::SocketInputStreamLocal::read(byteArray b) { + return read(b, 0, b.length); } -// Try and get an input range of bytes, blocking until enough bytes are available -int Socket::SocketInputStreamLocal::read(byteArray b, unsigned int offset, unsigned int length) -{ - while(m_streamOpen) - { - if(TryEnterCriticalSection(&s_hostQueueLock[m_queueIdx])) - { - if( s_hostQueue[m_queueIdx].size() >= length ) - { - for( unsigned int i = 0; i < length; i++ ) - { - b[i+offset] = s_hostQueue[m_queueIdx].front(); - s_hostQueue[m_queueIdx].pop(); - } - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); - return length; - } - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); - } - Sleep(1); - } - return -1; +// Try and get an input range of bytes, blocking until enough bytes are +// available +int Socket::SocketInputStreamLocal::read(byteArray b, unsigned int offset, + unsigned int length) { + while (m_streamOpen) { + if (TryEnterCriticalSection(&s_hostQueueLock[m_queueIdx])) { + if (s_hostQueue[m_queueIdx].size() >= length) { + for (unsigned int i = 0; i < length; i++) { + b[i + offset] = s_hostQueue[m_queueIdx].front(); + s_hostQueue[m_queueIdx].pop(); + } + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); + return length; + } + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); + } + Sleep(1); + } + return -1; } -void Socket::SocketInputStreamLocal::close() -{ - m_streamOpen = false; - EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); - std::queue().swap(s_hostQueue[m_queueIdx]); - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); +void Socket::SocketInputStreamLocal::close() { + m_streamOpen = false; + EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); + std::queue().swap(s_hostQueue[m_queueIdx]); + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); } -/////////////////////////////////// Socket for output, on local connection //////////////////// +/////////////////////////////////// Socket for output, on local connection +/////////////////////// -Socket::SocketOutputStreamLocal::SocketOutputStreamLocal(int queueIdx) -{ - m_streamOpen = true; - m_queueIdx = queueIdx; +Socket::SocketOutputStreamLocal::SocketOutputStreamLocal(int queueIdx) { + m_streamOpen = true; + m_queueIdx = queueIdx; } -void Socket::SocketOutputStreamLocal::write(unsigned int b) -{ - if( m_streamOpen != true ) - { - return; - } - EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); - s_hostQueue[m_queueIdx].push((std::uint8_t)b); - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); +void Socket::SocketOutputStreamLocal::write(unsigned int b) { + if (m_streamOpen != true) { + return; + } + EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); + s_hostQueue[m_queueIdx].push((std::uint8_t)b); + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); } -void Socket::SocketOutputStreamLocal::write(byteArray b) -{ - write(b, 0, b.length); +void Socket::SocketOutputStreamLocal::write(byteArray b) { + write(b, 0, b.length); } -void Socket::SocketOutputStreamLocal::write(byteArray b, unsigned int offset, unsigned int length) -{ - if( m_streamOpen != true ) - { - return; - } - MemSect(12); - EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); - for( unsigned int i = 0; i < length; i++ ) - { - s_hostQueue[m_queueIdx].push(b[offset+i]); - } - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); - MemSect(0); +void Socket::SocketOutputStreamLocal::write(byteArray b, unsigned int offset, + unsigned int length) { + if (m_streamOpen != true) { + return; + } + MemSect(12); + EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); + for (unsigned int i = 0; i < length; i++) { + s_hostQueue[m_queueIdx].push(b[offset + i]); + } + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); + MemSect(0); } -void Socket::SocketOutputStreamLocal::close() -{ - m_streamOpen = false; - EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); - std::queue().swap(s_hostQueue[m_queueIdx]); - LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); +void Socket::SocketOutputStreamLocal::close() { + m_streamOpen = false; + EnterCriticalSection(&s_hostQueueLock[m_queueIdx]); + std::queue().swap(s_hostQueue[m_queueIdx]); + LeaveCriticalSection(&s_hostQueueLock[m_queueIdx]); } -/////////////////////////////////// Socket for input, on network connection //////////////////// +/////////////////////////////////// Socket for input, on network connection +/////////////////////// -Socket::SocketInputStreamNetwork::SocketInputStreamNetwork(Socket *socket, int queueIdx) -{ - m_streamOpen = true; - m_queueIdx = queueIdx; - m_socket = socket; +Socket::SocketInputStreamNetwork::SocketInputStreamNetwork(Socket* socket, + int queueIdx) { + m_streamOpen = true; + m_queueIdx = queueIdx; + m_socket = socket; } // Try and get an input byte, blocking until one is available -int Socket::SocketInputStreamNetwork::read() -{ - while(m_streamOpen && ShutdownManager::ShouldRun(ShutdownManager::eConnectionReadThreads)) - { - if(TryEnterCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx])) - { - if( m_socket->m_queueNetwork[m_queueIdx].size() ) - { - std::uint8_t retval = m_socket->m_queueNetwork[m_queueIdx].front(); - m_socket->m_queueNetwork[m_queueIdx].pop(); - LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); - return retval; - } - LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); - } - Sleep(1); - } - return -1; +int Socket::SocketInputStreamNetwork::read() { + while (m_streamOpen && ShutdownManager::ShouldRun( + ShutdownManager::eConnectionReadThreads)) { + if (TryEnterCriticalSection( + &m_socket->m_queueLockNetwork[m_queueIdx])) { + if (m_socket->m_queueNetwork[m_queueIdx].size()) { + std::uint8_t retval = + m_socket->m_queueNetwork[m_queueIdx].front(); + m_socket->m_queueNetwork[m_queueIdx].pop(); + LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); + return retval; + } + LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); + } + Sleep(1); + } + return -1; } -// Try and get an input array of bytes, blocking until enough bytes are available -int Socket::SocketInputStreamNetwork::read(byteArray b) -{ - return read(b, 0, b.length); +// Try and get an input array of bytes, blocking until enough bytes are +// available +int Socket::SocketInputStreamNetwork::read(byteArray b) { + return read(b, 0, b.length); } -// Try and get an input range of bytes, blocking until enough bytes are available -int Socket::SocketInputStreamNetwork::read(byteArray b, unsigned int offset, unsigned int length) -{ - while(m_streamOpen) - { - if(TryEnterCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx])) - { - if( m_socket->m_queueNetwork[m_queueIdx].size() >= length ) - { - for( unsigned int i = 0; i < length; i++ ) - { - b[i+offset] = m_socket->m_queueNetwork[m_queueIdx].front(); - m_socket->m_queueNetwork[m_queueIdx].pop(); - } - LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); - return length; - } - LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); - } - Sleep(1); - } - return -1; +// Try and get an input range of bytes, blocking until enough bytes are +// available +int Socket::SocketInputStreamNetwork::read(byteArray b, unsigned int offset, + unsigned int length) { + while (m_streamOpen) { + if (TryEnterCriticalSection( + &m_socket->m_queueLockNetwork[m_queueIdx])) { + if (m_socket->m_queueNetwork[m_queueIdx].size() >= length) { + for (unsigned int i = 0; i < length; i++) { + b[i + offset] = + m_socket->m_queueNetwork[m_queueIdx].front(); + m_socket->m_queueNetwork[m_queueIdx].pop(); + } + LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); + return length; + } + LeaveCriticalSection(&m_socket->m_queueLockNetwork[m_queueIdx]); + } + Sleep(1); + } + return -1; } -void Socket::SocketInputStreamNetwork::close() -{ - m_streamOpen = false; +void Socket::SocketInputStreamNetwork::close() { m_streamOpen = false; } + +/////////////////////////////////// Socket for output, on network connection +/////////////////////// + +Socket::SocketOutputStreamNetwork::SocketOutputStreamNetwork(Socket* socket, + int queueIdx) { + m_queueIdx = queueIdx; + m_socket = socket; + m_streamOpen = true; } -/////////////////////////////////// Socket for output, on network connection //////////////////// - -Socket::SocketOutputStreamNetwork::SocketOutputStreamNetwork(Socket *socket, int queueIdx) -{ - m_queueIdx = queueIdx; - m_socket = socket; - m_streamOpen = true; +void Socket::SocketOutputStreamNetwork::write(unsigned int b) { + if (m_streamOpen != true) return; + byteArray barray; + std::uint8_t bb; + bb = (std::uint8_t)b; + barray.data = &bb; + barray.length = 1; + write(barray, 0, 1); } -void Socket::SocketOutputStreamNetwork::write(unsigned int b) -{ - if( m_streamOpen != true ) return; - byteArray barray; - std::uint8_t bb; - bb = (std::uint8_t)b; - barray.data = &bb; - barray.length = 1; - write(barray, 0, 1); - +void Socket::SocketOutputStreamNetwork::write(byteArray b) { + write(b, 0, b.length); } -void Socket::SocketOutputStreamNetwork::write(byteArray b) -{ - write(b, 0, b.length); +void Socket::SocketOutputStreamNetwork::write(byteArray b, unsigned int offset, + unsigned int length) { + writeWithFlags(b, offset, length, 0); } -void Socket::SocketOutputStreamNetwork::write(byteArray b, unsigned int offset, unsigned int length) -{ - writeWithFlags(b, offset, length, 0); +void Socket::SocketOutputStreamNetwork::writeWithFlags(byteArray b, + unsigned int offset, + unsigned int length, + int flags) { + if (m_streamOpen != true) return; + if (length == 0) return; + + // If this is a local connection, don't bother going through QNet as it just + // delivers it straight anyway + if (m_socket->m_hostLocal) { + // We want to write to the queue for the other end of this socket stream + int queueIdx = m_queueIdx; + if (queueIdx == SOCKET_CLIENT_END) + queueIdx = SOCKET_SERVER_END; + else + queueIdx = SOCKET_CLIENT_END; + + EnterCriticalSection(&m_socket->m_queueLockNetwork[queueIdx]); + for (unsigned int i = 0; i < length; i++) { + m_socket->m_queueNetwork[queueIdx].push(b[offset + i]); + } + LeaveCriticalSection(&m_socket->m_queueLockNetwork[queueIdx]); + } else { + XRNM_SEND_BUFFER buffer; + buffer.pbyData = &b[offset]; + buffer.dwDataSize = length; + + INetworkPlayer* hostPlayer = g_NetworkManager.GetHostPlayer(); + if (hostPlayer == NULL) { + app.DebugPrintf( + "Trying to write to network, but the hostPlayer is NULL\n"); + return; + } + INetworkPlayer* socketPlayer = m_socket->getPlayer(); + if (socketPlayer == NULL) { + app.DebugPrintf( + "Trying to write to network, but the socketPlayer is NULL\n"); + return; + } + + if (m_queueIdx == SOCKET_SERVER_END) { + // printf( "Sent %u bytes of data from \"%ls\" to \"%ls\"\n", + // buffer.dwDataSize, + // hostPlayer->GetGamertag(), + // m_socket->networkPlayer->GetGamertag()); + + hostPlayer->SendData( + socketPlayer, buffer.pbyData, buffer.dwDataSize, + QNET_SENDDATA_RELIABLE | QNET_SENDDATA_SEQUENTIAL | flags); + + // DWORD queueSize = hostPlayer->GetSendQueueSize( NULL, + // QNET_GETSENDQUEUESIZE_BYTES ); if( queueSize > 24000 ) + // { + // //printf("Queue size is: %d, forcing + // doWork()\n",queueSize); g_NetworkManager.DoWork(); + // } + } else { + // printf( "Sent %u bytes of data from \"%ls\" to \"%ls\"\n", + // buffer.dwDataSize, + // m_socket->networkPlayer->GetGamertag(), + // hostPlayer->GetGamertag()); + + socketPlayer->SendData( + hostPlayer, buffer.pbyData, buffer.dwDataSize, + QNET_SENDDATA_RELIABLE | QNET_SENDDATA_SEQUENTIAL | flags); + } + } } -void Socket::SocketOutputStreamNetwork::writeWithFlags(byteArray b, unsigned int offset, unsigned int length, int flags) -{ - if( m_streamOpen != true ) return; - if( length == 0 ) return; - - // If this is a local connection, don't bother going through QNet as it just delivers it straight anyway - if( m_socket->m_hostLocal ) - { - // We want to write to the queue for the other end of this socket stream - int queueIdx = m_queueIdx; - if(queueIdx == SOCKET_CLIENT_END) - queueIdx = SOCKET_SERVER_END; - else - queueIdx = SOCKET_CLIENT_END; - - EnterCriticalSection(&m_socket->m_queueLockNetwork[queueIdx]); - for( unsigned int i = 0; i < length; i++ ) - { - m_socket->m_queueNetwork[queueIdx].push(b[offset+i]); - } - LeaveCriticalSection(&m_socket->m_queueLockNetwork[queueIdx]); - } - else - { - XRNM_SEND_BUFFER buffer; - buffer.pbyData = &b[offset]; - buffer.dwDataSize = length; - - INetworkPlayer *hostPlayer = g_NetworkManager.GetHostPlayer(); - if(hostPlayer == NULL) - { - app.DebugPrintf("Trying to write to network, but the hostPlayer is NULL\n"); - return; - } - INetworkPlayer *socketPlayer = m_socket->getPlayer(); - if(socketPlayer == NULL) - { - app.DebugPrintf("Trying to write to network, but the socketPlayer is NULL\n"); - return; - } - - if( m_queueIdx == SOCKET_SERVER_END ) - { - //printf( "Sent %u bytes of data from \"%ls\" to \"%ls\"\n", - //buffer.dwDataSize, - //hostPlayer->GetGamertag(), - //m_socket->networkPlayer->GetGamertag()); - - hostPlayer->SendData(socketPlayer, buffer.pbyData, buffer.dwDataSize, QNET_SENDDATA_RELIABLE | QNET_SENDDATA_SEQUENTIAL | flags); - - // DWORD queueSize = hostPlayer->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ); - // if( queueSize > 24000 ) - // { - // //printf("Queue size is: %d, forcing doWork()\n",queueSize); - // g_NetworkManager.DoWork(); - // } - } - else - { - //printf( "Sent %u bytes of data from \"%ls\" to \"%ls\"\n", - //buffer.dwDataSize, - //m_socket->networkPlayer->GetGamertag(), - //hostPlayer->GetGamertag()); - - socketPlayer->SendData(hostPlayer, buffer.pbyData, buffer.dwDataSize, QNET_SENDDATA_RELIABLE | QNET_SENDDATA_SEQUENTIAL | flags); - } - } -} - -void Socket::SocketOutputStreamNetwork::close() -{ - m_streamOpen = false; -} +void Socket::SocketOutputStreamNetwork::close() { m_streamOpen = false; } diff --git a/Minecraft.World/Network/Socket.h b/Minecraft.World/Network/Socket.h index 293f9dd4a..da2830b5c 100644 --- a/Minecraft.World/Network/Socket.h +++ b/Minecraft.World/Network/Socket.h @@ -15,125 +15,145 @@ class SocketAddress; class ServerConnection; -class Socket -{ +class Socket { public: - // 4J Added so we can add a priority write function - class SocketOutputStream : public OutputStream - { - public: - // The flags are those that can be used for the QNet SendData function - virtual void writeWithFlags(byteArray b, unsigned int offset, unsigned int length, int flags) { write(b, offset, length); } - }; + // 4J Added so we can add a priority write function + class SocketOutputStream : public OutputStream { + public: + // The flags are those that can be used for the QNet SendData function + virtual void writeWithFlags(byteArray b, unsigned int offset, + unsigned int length, int flags) { + write(b, offset, length); + } + }; private: - class SocketInputStreamLocal : public InputStream - { - public: - bool m_streamOpen; - private: - int m_queueIdx; - public: - SocketInputStreamLocal(int queueIdx); + class SocketInputStreamLocal : public InputStream { + public: + bool m_streamOpen; - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual __int64 skip(__int64 n) { return n; } // 4J Stu - Not implemented - virtual void flush() {} - }; + private: + int m_queueIdx; - class SocketOutputStreamLocal : public SocketOutputStream - { - public: - bool m_streamOpen; - private: - int m_queueIdx; - public: - SocketOutputStreamLocal(int queueIdx); + public: + SocketInputStreamLocal(int queueIdx); - virtual void write(unsigned int b); - virtual void write(byteArray b); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual void flush() {} - }; + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual __int64 skip(__int64 n) { + return n; + } // 4J Stu - Not implemented + virtual void flush() {} + }; - class SocketInputStreamNetwork : public InputStream - { - bool m_streamOpen; - int m_queueIdx; - Socket *m_socket; - public: - SocketInputStreamNetwork(Socket *socket, int queueIdx); + class SocketOutputStreamLocal : public SocketOutputStream { + public: + bool m_streamOpen; - virtual int read(); - virtual int read(byteArray b); - virtual int read(byteArray b, unsigned int offset, unsigned int length); - virtual void close(); - virtual __int64 skip(__int64 n) { return n; } // 4J Stu - Not implemented - virtual void flush() {} - }; - class SocketOutputStreamNetwork : public SocketOutputStream - { - bool m_streamOpen; - int m_queueIdx; - Socket *m_socket; - public: - SocketOutputStreamNetwork(Socket *socket, int queueIdx); + private: + int m_queueIdx; - virtual void write(unsigned int b); - virtual void write(byteArray b); - virtual void write(byteArray b, unsigned int offset, unsigned int length); - virtual void writeWithFlags(byteArray b, unsigned int offset, unsigned int length, int flags); - virtual void close(); - virtual void flush() {} - }; - - bool m_hostServerConnection; // true if this is the connection between the host player and server - bool m_hostLocal; // true if this player on the same machine as the host - int m_end; // 0 for client side or 1 for host side + public: + SocketOutputStreamLocal(int queueIdx); - // For local connections between the host player and the server - static CRITICAL_SECTION s_hostQueueLock[2]; - static std::queue s_hostQueue[2]; - static SocketOutputStreamLocal *s_hostOutStream[2]; - static SocketInputStreamLocal *s_hostInStream[2]; + virtual void write(unsigned int b); + virtual void write(byteArray b); + virtual void write(byteArray b, unsigned int offset, + unsigned int length); + virtual void close(); + virtual void flush() {} + }; - // For network connections - std::queue m_queueNetwork[2]; // For input data - CRITICAL_SECTION m_queueLockNetwork[2]; // For input data - SocketInputStreamNetwork *m_inputStream[2]; - SocketOutputStreamNetwork *m_outputStream[2]; - bool m_endClosed[2]; + class SocketInputStreamNetwork : public InputStream { + bool m_streamOpen; + int m_queueIdx; + Socket* m_socket; - // Host only connection class - static ServerConnection *s_serverConnection; + public: + SocketInputStreamNetwork(Socket* socket, int queueIdx); - std::uint8_t networkPlayerSmallId; -public: - C4JThread::Event* m_socketClosedEvent; + virtual int read(); + virtual int read(byteArray b); + virtual int read(byteArray b, unsigned int offset, unsigned int length); + virtual void close(); + virtual __int64 skip(__int64 n) { + return n; + } // 4J Stu - Not implemented + virtual void flush() {} + }; + class SocketOutputStreamNetwork : public SocketOutputStream { + bool m_streamOpen; + int m_queueIdx; + Socket* m_socket; - INetworkPlayer *getPlayer(); - void setPlayer(INetworkPlayer *player); + public: + SocketOutputStreamNetwork(Socket* socket, int queueIdx); + + virtual void write(unsigned int b); + virtual void write(byteArray b); + virtual void write(byteArray b, unsigned int offset, + unsigned int length); + virtual void writeWithFlags(byteArray b, unsigned int offset, + unsigned int length, int flags); + virtual void close(); + virtual void flush() {} + }; + + bool m_hostServerConnection; // true if this is the connection between the + // host player and server + bool m_hostLocal; // true if this player on the same machine as the host + int m_end; // 0 for client side or 1 for host side + + // For local connections between the host player and the server + static CRITICAL_SECTION s_hostQueueLock[2]; + static std::queue s_hostQueue[2]; + static SocketOutputStreamLocal* s_hostOutStream[2]; + static SocketInputStreamLocal* s_hostInStream[2]; + + // For network connections + std::queue m_queueNetwork[2]; // For input data + CRITICAL_SECTION m_queueLockNetwork[2]; // For input data + SocketInputStreamNetwork* m_inputStream[2]; + SocketOutputStreamNetwork* m_outputStream[2]; + bool m_endClosed[2]; + + // Host only connection class + static ServerConnection* s_serverConnection; + + std::uint8_t networkPlayerSmallId; public: - static void EnsureStreamsInitialised(); // 4J Fix: idempotent stream creation; safe to call before Initialise(connection) - static void Initialise(ServerConnection *serverConnection); - Socket(bool response = false); // 4J - Create a local socket, for end 0 or 1 of a connection - Socket(INetworkPlayer *player, bool response = false, bool hostLocal = false); // 4J - Create a socket for an INetworkPlayer - SocketAddress *getRemoteSocketAddress(); - void pushDataToQueue(const std::uint8_t *pbData, std::size_t dataSize, bool fromHost = true); - static void addIncomingSocket(Socket *socket); - InputStream *getInputStream(bool isServerConnection); - void setSoTimeout(int a ); - void setTrafficClass( int a ); - SocketOutputStream *getOutputStream(bool isServerConnection); - bool close(bool isServerConnection); - bool createdOk; - bool isLocal() { return m_hostLocal; } + C4JThread::Event* m_socketClosedEvent; - bool isClosing() { return m_endClosed[SOCKET_CLIENT_END] || m_endClosed[SOCKET_SERVER_END]; } - std::uint8_t getSmallId() { return networkPlayerSmallId; } + INetworkPlayer* getPlayer(); + void setPlayer(INetworkPlayer* player); + +public: + static void + EnsureStreamsInitialised(); // 4J Fix: idempotent stream creation; safe to + // call before Initialise(connection) + static void Initialise(ServerConnection* serverConnection); + Socket(bool response = false); // 4J - Create a local socket, for end 0 or + // 1 of a connection + Socket( + INetworkPlayer* player, bool response = false, + bool hostLocal = false); // 4J - Create a socket for an INetworkPlayer + SocketAddress* getRemoteSocketAddress(); + void pushDataToQueue(const std::uint8_t* pbData, std::size_t dataSize, + bool fromHost = true); + static void addIncomingSocket(Socket* socket); + InputStream* getInputStream(bool isServerConnection); + void setSoTimeout(int a); + void setTrafficClass(int a); + SocketOutputStream* getOutputStream(bool isServerConnection); + bool close(bool isServerConnection); + bool createdOk; + bool isLocal() { return m_hostLocal; } + + bool isClosing() { + return m_endClosed[SOCKET_CLIENT_END] || m_endClosed[SOCKET_SERVER_END]; + } + std::uint8_t getSmallId() { return networkPlayerSmallId; } }; diff --git a/Minecraft.World/Network/SocketAddress.h b/Minecraft.World/Network/SocketAddress.h index 024e2d090..d912020eb 100644 --- a/Minecraft.World/Network/SocketAddress.h +++ b/Minecraft.World/Network/SocketAddress.h @@ -1,6 +1,3 @@ #pragma once -class SocketAddress -{ - -}; \ No newline at end of file +class SocketAddress {}; \ No newline at end of file diff --git a/Minecraft.World/Platform/Minecraft.World.cpp b/Minecraft.World/Platform/Minecraft.World.cpp index c49cd52fd..3fb2efc38 100644 --- a/Minecraft.World/Platform/Minecraft.World.cpp +++ b/Minecraft.World/Platform/Minecraft.World.cpp @@ -45,60 +45,60 @@ #include "../Stats/CommonStats.h" #endif -void MinecraftWorld_RunStaticCtors() -{ - // The ordering of these static ctors can be important. If they are within statement blocks then - // DO NOT CHANGE the ordering - 4J Stu +void MinecraftWorld_RunStaticCtors() { + // The ordering of these static ctors can be important. If they are within + // statement blocks then DO NOT CHANGE the ordering - 4J Stu - Packet::staticCtor(); + Packet::staticCtor(); - { - MaterialColor::staticCtor(); - Material::staticCtor(); - Tile::staticCtor(); - HatchetItem::staticCtor(); - PickaxeItem::staticCtor(); - ShovelItem::staticCtor(); - BlockReplacements::staticCtor(); - Biome::staticCtor(); - Item::staticCtor(); - FurnaceRecipes::staticCtor(); - Recipes::staticCtor(); + { + MaterialColor::staticCtor(); + Material::staticCtor(); + Tile::staticCtor(); + HatchetItem::staticCtor(); + PickaxeItem::staticCtor(); + ShovelItem::staticCtor(); + BlockReplacements::staticCtor(); + Biome::staticCtor(); + Item::staticCtor(); + FurnaceRecipes::staticCtor(); + Recipes::staticCtor(); #ifdef _DURANGO - GenericStats::setInstance(new DurangoStats()); + GenericStats::setInstance(new DurangoStats()); #else - GenericStats::setInstance(new CommonStats()); - Stats::staticCtor(); + GenericStats::setInstance(new CommonStats()); + Stats::staticCtor(); #endif - //Achievements::staticCtor(); // 4J Stu - This is now called from within the Stats::staticCtor() - Skeleton::staticCtor(); - PigZombie::staticCtor(); - TileEntity::staticCtor(); - EntityIO::staticCtor(); - MobCategory::staticCtor(); + // Achievements::staticCtor(); // 4J Stu - This is now called from + // within the Stats::staticCtor() + Skeleton::staticCtor(); + PigZombie::staticCtor(); + TileEntity::staticCtor(); + EntityIO::staticCtor(); + MobCategory::staticCtor(); - Item::staticInit(); - LevelChunk::staticCtor(); + Item::staticInit(); + LevelChunk::staticCtor(); - LevelType::staticCtor(); + LevelType::staticCtor(); - MineShaftPieces::staticCtor(); - StrongholdFeature::staticCtor(); - VillagePieces::Smithy::staticCtor(); - VillageFeature::staticCtor(); - RandomScatteredLargeFeature::staticCtor(); - } - EnderMan::staticCtor(); - PotionBrewing::staticCtor(); - Enchantment::staticCtor(); + MineShaftPieces::staticCtor(); + StrongholdFeature::staticCtor(); + VillagePieces::Smithy::staticCtor(); + VillageFeature::staticCtor(); + RandomScatteredLargeFeature::staticCtor(); + } + EnderMan::staticCtor(); + PotionBrewing::staticCtor(); + Enchantment::staticCtor(); - SharedConstants::staticCtor(); + SharedConstants::staticCtor(); - ServerLevel::staticCtor(); - SparseLightStorage::staticCtor(); - CompressedTileStorage::staticCtor(); - SparseDataStorage::staticCtor(); - McRegionChunkStorage::staticCtor(); - Villager::staticCtor(); - GameType::staticCtor(); + ServerLevel::staticCtor(); + SparseLightStorage::staticCtor(); + CompressedTileStorage::staticCtor(); + SparseDataStorage::staticCtor(); + McRegionChunkStorage::staticCtor(); + Villager::staticCtor(); + GameType::staticCtor(); } diff --git a/Minecraft.World/Platform/System.cpp b/Minecraft.World/Platform/System.cpp index 9c46bfdd8..789b4760e 100644 --- a/Minecraft.World/Platform/System.cpp +++ b/Minecraft.World/Platform/System.cpp @@ -7,210 +7,216 @@ #include #include #include -#endif // __linux__ +#endif // __linux__ -template void System::arraycopy(arrayWithLength src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length) -{ - assert( srcPos >=0 && srcPos <= src.length); - assert( srcPos + length <= src.length ); - assert( dstPos + length <= dst->length ); +template +void System::arraycopy(arrayWithLength src, unsigned int srcPos, + arrayWithLength* dst, unsigned int dstPos, + unsigned int length) { + assert(srcPos >= 0 && srcPos <= src.length); + assert(srcPos + length <= src.length); + assert(dstPos + length <= dst->length); - std::copy( src.data + srcPos, src.data + srcPos + length, dst->data + dstPos ); + std::copy(src.data + srcPos, src.data + srcPos + length, + dst->data + dstPos); } -ArrayCopyFunctionDefinition(Node *) -ArrayCopyFunctionDefinition(Biome *) +ArrayCopyFunctionDefinition(Node*) ArrayCopyFunctionDefinition(Biome*) -void System::arraycopy(arrayWithLength src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length) -{ - assert( srcPos >=0 && srcPos <= src.length); - assert( srcPos + length <= src.length ); - assert( dstPos + length <= dst->length ); - - memcpy( dst->data + dstPos, src.data + srcPos, length); + void System::arraycopy(arrayWithLength src, unsigned int srcPos, + arrayWithLength* dst, unsigned int dstPos, + unsigned int length) { + assert(srcPos >= 0 && srcPos <= src.length); + assert(srcPos + length <= src.length); + assert(dstPos + length <= dst->length); + + memcpy(dst->data + dstPos, src.data + srcPos, length); } -void System::arraycopy(arrayWithLength src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length) -{ - assert( srcPos >=0 && srcPos <= src.length); - assert( srcPos + length <= src.length ); - assert( dstPos + length <= dst->length ); - - memcpy( dst->data + dstPos, src.data + srcPos, length * sizeof(int) ); +void System::arraycopy(arrayWithLength src, unsigned int srcPos, + arrayWithLength* dst, unsigned int dstPos, + unsigned int length) { + assert(srcPos >= 0 && srcPos <= src.length); + assert(srcPos + length <= src.length); + assert(dstPos + length <= dst->length); + + memcpy(dst->data + dstPos, src.data + srcPos, length * sizeof(int)); } -// TODO 4J Stu - These time functions may suffer from accuracy and we might have to use a high-resolution timer -//Returns the current value of the most precise available system timer, in nanoseconds. -//This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. -//The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). -//This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how -//frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) -//will not accurately compute elapsed time due to numerical overflow. +// TODO 4J Stu - These time functions may suffer from accuracy and we might have +// to use a high-resolution timer +// Returns the current value of the most precise available system timer, in +// nanoseconds. This method can only be used to measure elapsed time and is not +// related to any other notion of system or wall-clock time. The value returned +// represents nanoseconds since some fixed but arbitrary time (perhaps in the +// future, so values may be negative). This method provides nanosecond +// precision, but not necessarily nanosecond accuracy. No guarantees are made +// about how frequently values change. Differences in successive calls that span +// greater than approximately 292 years (263 nanoseconds) will not accurately +// compute elapsed time due to numerical overflow. // -//For example, to measure how long some code takes to execute: +// For example, to measure how long some code takes to execute: // // long startTime = System.nanoTime(); // // ... the code being measured ... // long estimatedTime = System.nanoTime() - startTime; -// -//Returns: -//The current value of the system timer, in nanoseconds. -__int64 System::nanoTime() -{ +// +// Returns: +// The current value of the system timer, in nanoseconds. +__int64 System::nanoTime() { #if !defined(__linux__) - return GetTickCount() * 1000000LL; + return GetTickCount() * 1000000LL; #else - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return static_cast(ts.tv_sec) * 1000000000LL + ts.tv_nsec; -#endif // __linux__ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return static_cast(ts.tv_sec) * 1000000000LL + ts.tv_nsec; +#endif // __linux__ } -//Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, -//the granularity of the value depends on the underlying operating system and may be larger. For example, -//many operating systems measure time in units of tens of milliseconds. -//See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" -//and coordinated universal time (UTC). +// Returns the current time in milliseconds. Note that while the unit of time of +// the return value is a millisecond, the granularity of the value depends on +// the underlying operating system and may be larger. For example, many +// operating systems measure time in units of tens of milliseconds. See the +// description of the class Date for a discussion of slight discrepancies that +// may arise between "computer time" and coordinated universal time (UTC). // -//Returns: -//the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. -__int64 System::currentTimeMillis() -{ +// Returns: +// the difference, measured in milliseconds, between the current time and +// midnight, January 1, 1970 UTC. +__int64 System::currentTimeMillis() { #ifdef __PS3__ -// sys_time_get_current_time() obtains the elapsed time since Epoch (1970/01/01 00:00:00 UTC). -// The value is separated into two parts: sec stores the elapsed time in seconds, and nsec -// stores the value that is smaller than a second in nanoseconds. - sys_time_sec_t sec; - sys_time_nsec_t nsec; - sys_time_get_current_time(&sec, &nsec); - __int64 msec = (sec * 1000) + (nsec / (1000*1000)); - return msec; + // sys_time_get_current_time() obtains the elapsed time since Epoch + //(1970/01/01 00:00:00 UTC). The value is separated into two parts: sec + //stores the elapsed time in seconds, and nsec + // stores the value that is smaller than a second in nanoseconds. + sys_time_sec_t sec; + sys_time_nsec_t nsec; + sys_time_get_current_time(&sec, &nsec); + __int64 msec = (sec * 1000) + (nsec / (1000 * 1000)); + return msec; #elif defined __ORBIS__ - SceRtcTick tick; - int err = sceRtcGetCurrentTick(&tick); + SceRtcTick tick; + int err = sceRtcGetCurrentTick(&tick); - return (int64_t)(tick.tick / 1000); + return (int64_t)(tick.tick / 1000); #elif defined __PSVITA__ - // AP - TRC states we can't use the RTC for measuring elapsed game time - return sceKernelGetProcessTimeWide() / 1000; + // AP - TRC states we can't use the RTC for measuring elapsed game time + return sceKernelGetProcessTimeWide() / 1000; /* SceDateTime Time; - sceRtcGetCurrentClockLocalTime(&Time); - __int64 systTime = (((((((Time.day * 24) + Time.hour) * 60) + Time.minute) * 60) + Time.second) * 1000) + (Time.microsecond / 1000); - return systTime;*/ + sceRtcGetCurrentClockLocalTime(&Time); + __int64 systTime = (((((((Time.day * 24) + Time.hour) * 60) + + Time.minute) * 60) + Time.second) * 1000) + (Time.microsecond / 1000); return + systTime;*/ #elif defined(__linux__) - struct timeval tv; - gettimeofday(&tv, NULL); - // Convert to milliseconds since unix epoch instead of windows file time - // time is expecting calculation to be between 10-30 ms. - return (int64_t)tv.tv_sec * 1000LL + tv.tv_usec / 1000; + struct timeval tv; + gettimeofday(&tv, NULL); + // Convert to milliseconds since unix epoch instead of windows file time + // time is expecting calculation to be between 10-30 ms. + return (int64_t)tv.tv_sec * 1000LL + tv.tv_usec / 1000; #else - SYSTEMTIME UTCSysTime; - GetSystemTime( &UTCSysTime ); + SYSTEMTIME UTCSysTime; + GetSystemTime(&UTCSysTime); - //Represents as a 64-bit value the number of 100-nanosecond intervals since January 1, 1601 + // Represents as a 64-bit value the number of 100-nanosecond intervals since + // January 1, 1601 FILETIME UTCFileTime; - SystemTimeToFileTime( &UTCSysTime, &UTCFileTime ); + SystemTimeToFileTime(&UTCSysTime, &UTCFileTime); - LARGE_INTEGER li; - li.HighPart = UTCFileTime.dwHighDateTime; - li.LowPart = UTCFileTime.dwLowDateTime; + LARGE_INTEGER li; + li.HighPart = UTCFileTime.dwHighDateTime; + li.LowPart = UTCFileTime.dwLowDateTime; - return li.QuadPart/10000; -#endif // __PS3__ + return li.QuadPart / 10000; +#endif // __PS3__ } -// 4J Stu - Added this so that we can use real-world timestamps in PSVita saves. Particularly required for the save transfers to be smooth -__int64 System::currentRealTimeMillis() -{ +// 4J Stu - Added this so that we can use real-world timestamps in PSVita saves. +// Particularly required for the save transfers to be smooth +__int64 System::currentRealTimeMillis() { #ifdef __PSVITA__ - SceDateTime Time; - sceRtcGetCurrentClockLocalTime(&Time); - __int64 systTime = (((((((Time.day * 24) + Time.hour) * 60) + Time.minute) * 60) + Time.second) * 1000) + (Time.microsecond / 1000); - return systTime; + SceDateTime Time; + sceRtcGetCurrentClockLocalTime(&Time); + __int64 systTime = + (((((((Time.day * 24) + Time.hour) * 60) + Time.minute) * 60) + + Time.second) * + 1000) + + (Time.microsecond / 1000); + return systTime; #else - return currentTimeMillis(); + return currentTimeMillis(); #endif } +void System::ReverseUSHORT(unsigned short* pusVal) { + unsigned short usValue = *pusVal; + unsigned char* pchVal1 = (unsigned char*)pusVal; + unsigned char* pchVal2 = (unsigned char*)&usValue; -void System::ReverseUSHORT(unsigned short *pusVal) -{ - unsigned short usValue=*pusVal; - unsigned char *pchVal1=(unsigned char *)pusVal; - unsigned char *pchVal2=(unsigned char *)&usValue; - - pchVal1[0]=pchVal2[1]; - pchVal1[1]=pchVal2[0]; + pchVal1[0] = pchVal2[1]; + pchVal1[1] = pchVal2[0]; } -void System::ReverseSHORT(short *pusVal) -{ - short usValue=*pusVal; - unsigned char *pchVal1=(unsigned char *)pusVal; - unsigned char *pchVal2=(unsigned char *)&usValue; +void System::ReverseSHORT(short* pusVal) { + short usValue = *pusVal; + unsigned char* pchVal1 = (unsigned char*)pusVal; + unsigned char* pchVal2 = (unsigned char*)&usValue; - pchVal1[0]=pchVal2[1]; - pchVal1[1]=pchVal2[0]; + pchVal1[0] = pchVal2[1]; + pchVal1[1] = pchVal2[0]; } -void System::ReverseULONG(unsigned long *pulVal) -{ - unsigned long ulValue=*pulVal; - unsigned char *pchVal1=(unsigned char *)pulVal; - unsigned char *pchVal2=(unsigned char *)&ulValue; +void System::ReverseULONG(unsigned long* pulVal) { + unsigned long ulValue = *pulVal; + unsigned char* pchVal1 = (unsigned char*)pulVal; + unsigned char* pchVal2 = (unsigned char*)&ulValue; - pchVal1[0]=pchVal2[3]; - pchVal1[1]=pchVal2[2]; - pchVal1[2]=pchVal2[1]; - pchVal1[3]=pchVal2[0]; + pchVal1[0] = pchVal2[3]; + pchVal1[1] = pchVal2[2]; + pchVal1[2] = pchVal2[1]; + pchVal1[3] = pchVal2[0]; } -void System::ReverseULONG(unsigned int *pulVal) -{ - unsigned int ulValue=*pulVal; - unsigned char *pchVal1=(unsigned char *)pulVal; - unsigned char *pchVal2=(unsigned char *)&ulValue; +void System::ReverseULONG(unsigned int* pulVal) { + unsigned int ulValue = *pulVal; + unsigned char* pchVal1 = (unsigned char*)pulVal; + unsigned char* pchVal2 = (unsigned char*)&ulValue; - pchVal1[0]=pchVal2[3]; - pchVal1[1]=pchVal2[2]; - pchVal1[2]=pchVal2[1]; - pchVal1[3]=pchVal2[0]; + pchVal1[0] = pchVal2[3]; + pchVal1[1] = pchVal2[2]; + pchVal1[2] = pchVal2[1]; + pchVal1[3] = pchVal2[0]; } -void System::ReverseINT(int *piVal) -{ - int ulValue=*piVal; - unsigned char *pchVal1=(unsigned char *)piVal; - unsigned char *pchVal2=(unsigned char *)&ulValue; +void System::ReverseINT(int* piVal) { + int ulValue = *piVal; + unsigned char* pchVal1 = (unsigned char*)piVal; + unsigned char* pchVal2 = (unsigned char*)&ulValue; - pchVal1[0]=pchVal2[3]; - pchVal1[1]=pchVal2[2]; - pchVal1[2]=pchVal2[1]; - pchVal1[3]=pchVal2[0]; + pchVal1[0] = pchVal2[3]; + pchVal1[1] = pchVal2[2]; + pchVal1[2] = pchVal2[1]; + pchVal1[3] = pchVal2[0]; } -void System::ReverseULONGLONG(__int64 *pullVal) -{ - __int64 ullValue=*pullVal; - unsigned char *pchVal1=(unsigned char *)pullVal; - unsigned char *pchVal2=(unsigned char *)&ullValue; +void System::ReverseULONGLONG(__int64* pullVal) { + __int64 ullValue = *pullVal; + unsigned char* pchVal1 = (unsigned char*)pullVal; + unsigned char* pchVal2 = (unsigned char*)&ullValue; - pchVal1[0]=pchVal2[7]; - pchVal1[1]=pchVal2[6]; - pchVal1[2]=pchVal2[5]; - pchVal1[3]=pchVal2[4]; - pchVal1[4]=pchVal2[3]; - pchVal1[5]=pchVal2[2]; - pchVal1[6]=pchVal2[1]; - pchVal1[7]=pchVal2[0]; + pchVal1[0] = pchVal2[7]; + pchVal1[1] = pchVal2[6]; + pchVal1[2] = pchVal2[5]; + pchVal1[3] = pchVal2[4]; + pchVal1[4] = pchVal2[3]; + pchVal1[5] = pchVal2[2]; + pchVal1[6] = pchVal2[1]; + pchVal1[7] = pchVal2[0]; } -void System::ReverseWCHARA(WCHAR *pwch,int iLen) -{ - for(int i=0;i src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length); -#define ArrayCopyFunctionDefinition(x) void System::arraycopy(arrayWithLength src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length)\ -{\ - arraycopy(src,srcPos,dst,dstPos,length);\ -}\ +#define ArrayCopyFunctionDeclaration(x) \ + static void arraycopy(arrayWithLength src, unsigned int srcPos, \ + arrayWithLength* dst, unsigned int dstPos, \ + unsigned int length); +#define ArrayCopyFunctionDefinition(x) \ + void System::arraycopy(arrayWithLength src, unsigned int srcPos, \ + arrayWithLength* dst, unsigned int dstPos, \ + unsigned int length) { \ + arraycopy(src, srcPos, dst, dstPos, length); \ + } -class System -{ - template static void arraycopy(arrayWithLength src, unsigned int srcPos, arrayWithLength *dst, unsigned int dstPos, unsigned int length); +class System { + template + static void arraycopy(arrayWithLength src, unsigned int srcPos, + arrayWithLength* dst, unsigned int dstPos, + unsigned int length); public: - ArrayCopyFunctionDeclaration(uint8_t) - ArrayCopyFunctionDeclaration(Node *) - ArrayCopyFunctionDeclaration(Biome *) - ArrayCopyFunctionDeclaration(int) + ArrayCopyFunctionDeclaration(uint8_t) ArrayCopyFunctionDeclaration(Node*) + ArrayCopyFunctionDeclaration(Biome*) ArrayCopyFunctionDeclaration(int) - static __int64 nanoTime(); - static __int64 currentTimeMillis(); - static __int64 currentRealTimeMillis(); // 4J Added to get real-world time for timestamps in saves - - static void ReverseUSHORT(unsigned short *pusVal); - static void ReverseSHORT(short *psVal); - static void ReverseULONG(unsigned long *pulVal); - static void ReverseULONG(unsigned int *pulVal); - static void ReverseINT(int *piVal); - static void ReverseULONGLONG(__int64 *pullVal); - static void ReverseWCHARA(WCHAR *pwch,int iLen); + static __int64 nanoTime(); + static __int64 currentTimeMillis(); + static __int64 currentRealTimeMillis(); // 4J Added to get real-world time + // for timestamps in saves + static void ReverseUSHORT(unsigned short* pusVal); + static void ReverseSHORT(short* psVal); + static void ReverseULONG(unsigned long* pulVal); + static void ReverseULONG(unsigned int* pulVal); + static void ReverseINT(int* piVal); + static void ReverseULONGLONG(__int64* pullVal); + static void ReverseWCHARA(WCHAR* pwch, int iLen); }; -#define MAKE_FOURCC(ch0, ch1, ch2, ch3) \ - ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \ - ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 )) +#define MAKE_FOURCC(ch0, ch1, ch2, ch3) \ + ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \ + ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24)) diff --git a/Minecraft.World/Platform/stdafx.h b/Minecraft.World/Platform/stdafx.h index feae2432f..076eb9e9b 100644 --- a/Minecraft.World/Platform/stdafx.h +++ b/Minecraft.World/Platform/stdafx.h @@ -9,12 +9,12 @@ #define AUTO_VAR(_var, _val) auto _var = _val #endif -#if ( defined _XBOX || defined _WINDOWS64 || defined _DURANGO ) +#if (defined _XBOX || defined _WINDOWS64 || defined _DURANGO) typedef unsigned __int64 __uint64; #endif #ifdef _WINDOWS64 -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include #include @@ -33,7 +33,7 @@ using namespace DirectX; #include "../../Minecraft.Client/Platform/Durango/DurangoExtras/DurangoStubs.h" #endif -#if (defined __PS3__ || defined _XBOX ) +#if (defined __PS3__ || defined _XBOX) // C RunTime Header Files #include #endif @@ -70,7 +70,6 @@ typedef XUID GameSessionUID; #include #include - #include "../../Minecraft.Client/Platform/PS3/PS3Extras/Ps3Types.h" #include "../../Minecraft.Client/Platform/PS3/PS3Extras/Ps3Stubs.h" #include "../../Minecraft.Client/Platform/PS3/PS3Extras/PS3Maths.h" @@ -101,7 +100,7 @@ typedef XUID GameSessionUID; #include #include #include -#endif //__PS3__ +#endif //__PS3__ #include @@ -120,7 +119,8 @@ typedef XUID GameSessionUID; #include #include -#ifndef __PS3__ // the PS3 lib assert is rubbish, and aborts the code, we define our own in PS3Types.h +#ifndef __PS3__ // the PS3 lib assert is rubbish, and aborts the code, we + // define our own in PS3Types.h #include #endif @@ -136,7 +136,6 @@ typedef XUID GameSessionUID; #include "../IO/Streams/Compression.h" #include "../Util/PerformanceTimer.h" - #ifdef _FINAL_BUILD #define printf BREAKTHECOMPILE #define wprintf BREAKTHECOMPILE @@ -146,7 +145,6 @@ typedef XUID GameSessionUID; #define OutputDebugStringW BREAKTHECOMPILE #endif - void MemSect(int sect); #ifdef _XBOX @@ -155,7 +153,7 @@ void MemSect(int sect); #include "../Minecraft.Client/xbox/4JLibs/inc/4J_XTMS.h" #include "../Minecraft.Client/xbox/4JLibs/inc/4J_Storage.h" #include "../Minecraft.Client/xbox/4JLibs/inc/4J_Input.h" -#elif defined (__PS3__) +#elif defined(__PS3__) #include "../../Minecraft.Client/Platform/PS3/4JLibs/inc/4J_Profile.h" #include "../../Minecraft.Client/Platform/PS3/4JLibs/inc/4J_Render.h" #include "../../Minecraft.Client/Platform/PS3/4JLibs/inc/4J_Storage.h" @@ -195,7 +193,7 @@ void MemSect(int sect); #include "../../Minecraft.Client/Platform/Common/App_enums.h" #include "../../Minecraft.Client/Platform/Common/Tutorial/TutorialEnum.h" #include "../../Minecraft.Client/Platform/Common/App_structs.h" -//#endif +// #endif #ifdef _XBOX #include "../../Minecraft.Client/Platform/Common/XUI/XUI_Helper.h" @@ -218,14 +216,14 @@ void MemSect(int sect); #include "../../Minecraft.Client/Platform/Xbox/Sentient/SentientTelemetryCommon.h" #include "../../Minecraft.Client/Platform/Xbox/Sentient/MinecraftTelemetry.h" -#elif defined (__PS3__) +#elif defined(__PS3__) #include "../../Minecraft.Client/Platform/PS3/PS3_App.h" #include "../../Minecraft.Client/Platform/PS3/Sentient/SentientTelemetryCommon.h" #include "../../Minecraft.Client/Platform/PS3/Sentient/MinecraftTelemetry.h" #elif defined _DURANGO #include "../../Minecraft.Client/Platform/Durango/Durango_App.h" -//#include "../../Minecraft.Client/Platform/Durango/Sentient/SentientManager.h" +// #include "../../Minecraft.Client/Platform/Durango/Sentient/SentientManager.h" #include "../../Minecraft.Client/Platform/Durango/Sentient/SentientTelemetryCommon.h" #include "../../Minecraft.Client/Platform/Durango/Sentient/MinecraftTelemetry.h" #include "../../Minecraft.Client/Platform/Durango/Sentient/TelemetryEnum.h" @@ -240,14 +238,16 @@ void MemSect(int sect); #include "../../Minecraft.Client/Platform/PSVita/Sentient/SentientManager.h" #include "../../Minecraft.Client/Platform/PSVita/Sentient/MinecraftTelemetry.h" #elif defined(__linux__) - // Use Orbis-compatible headers on Linux (same as Minecraft.Client/Platform/stdafx.h). - // All Orbis Sentient headers have #pragma once, preventing double-inclusion - // when DLC/other Common files also pull in Minecraft.Client stdafx.h. - #include "../../Minecraft.Client/Platform/Linux/Linux_App.h" - #include "../../Minecraft.Client/Platform/Orbis/Sentient/SentientTelemetryCommon.h" - #include "../../Minecraft.Client/Platform/Orbis/Sentient/DynamicConfigurations.h" - #include "../../Minecraft.Client/Platform/Orbis/GameConfig/Minecraft.spa.h" -// #include "../../Minecraft.Client/Platform/Windows64/Sentient/MinecraftTelemetry.h" +// Use Orbis-compatible headers on Linux (same as +// Minecraft.Client/Platform/stdafx.h). All Orbis Sentient headers have #pragma +// once, preventing double-inclusion when DLC/other Common files also pull in +// Minecraft.Client stdafx.h. +#include "../../Minecraft.Client/Platform/Linux/Linux_App.h" +#include "../../Minecraft.Client/Platform/Orbis/Sentient/SentientTelemetryCommon.h" +#include "../../Minecraft.Client/Platform/Orbis/Sentient/DynamicConfigurations.h" +#include "../../Minecraft.Client/Platform/Orbis/GameConfig/Minecraft.spa.h" +// #include +// "../../Minecraft.Client/Platform/Windows64/Sentient/MinecraftTelemetry.h" #else #include "../../Minecraft.Client/Platform/Orbis/Orbis_App.h" #include "../../Minecraft.Client/Platform/Orbis/Sentient/SentientTelemetryCommon.h" diff --git a/Minecraft.World/Platform/x64headers/extraX64.h b/Minecraft.World/Platform/x64headers/extraX64.h index 51a7b5275..960170f44 100644 --- a/Minecraft.World/Platform/x64headers/extraX64.h +++ b/Minecraft.World/Platform/x64headers/extraX64.h @@ -8,7 +8,6 @@ #include "../../../Minecraft.Client/Rendering/Models/SkinBox.h" - #include #define MULTITHREAD_ENABLE @@ -25,8 +24,9 @@ const int XUSER_MAX_COUNT = 4; constexpr int MINECRAFT_NET_MAX_PLAYERS = 8; #endif -static_assert(MINECRAFT_NET_MAX_PLAYERS <= std::numeric_limits::max(), - "MINECRAFT_NET_MAX_PLAYERS must fit in the 8-bit network protocol"); +static_assert( + MINECRAFT_NET_MAX_PLAYERS <= std::numeric_limits::max(), + "MINECRAFT_NET_MAX_PLAYERS must fit in the 8-bit network protocol"); #ifdef __ORBIS__ #include @@ -37,7 +37,7 @@ static_assert(MINECRAFT_NET_MAX_PLAYERS <= std::numeric_limits::ma typedef SQRNetworkManager_Orbis::SessionID SessionID; typedef SQRNetworkManager_Orbis::PresenceSyncInfo INVITE_INFO; -#elif defined __PS3__ // defined in the profile lib +#elif defined __PS3__ // defined in the profile lib #include #include #include @@ -70,74 +70,69 @@ typedef ULONGLONG SessionID; typedef PlayerUID GameSessionUID; class INVITE_INFO; -#endif // __PS3__ +#endif // __PS3__ #ifndef _DURANGO -typedef PlayerUID *PPlayerUID; +typedef PlayerUID* PPlayerUID; #endif typedef struct _XUIOBJ* HXUIOBJ; typedef struct _XUICLASS* HXUICLASS; typedef struct _XUIBRUSH* HXUIBRUSH; typedef struct _XUIDC* HXUIDC; - - // #ifdef _DURANGO // void GetLocalTime(SYSTEMTIME *time); // #endif bool IsEqualXUID(PlayerUID a, PlayerUID b); +// Temporary implementation of lock free stack with quite a bit more locking +// than you might expect +template +class XLockFreeStack { + std::vector intStack; - -// Temporary implementation of lock free stack with quite a bit more locking than you might expect -template class XLockFreeStack -{ - std::vector intStack; public: - XLockFreeStack() { + XLockFreeStack() { #ifdef __ORBIS__ - OrbisInit(); // For PS4, we need to make sure Ult is set up for the critical sections to be able to initialise + OrbisInit(); // For PS4, we need to make sure Ult is set up for the + // critical sections to be able to initialise #endif - InitializeCriticalSectionAndSpinCount(&m_cs,5120); - } - ~XLockFreeStack() { DeleteCriticalSection( &m_cs ); } - void Initialize() {} - void Push(T *data) - { - EnterCriticalSection(&m_cs); - intStack.push_back(data); - LeaveCriticalSection(&m_cs); - } - T *Pop() - { - EnterCriticalSection(&m_cs); - if( intStack.size() ) - { - T* ret = intStack.back(); - intStack.pop_back(); - LeaveCriticalSection(&m_cs); - return ret; - } - else - { - LeaveCriticalSection(&m_cs); - return NULL; - } - } + InitializeCriticalSectionAndSpinCount(&m_cs, 5120); + } + ~XLockFreeStack() { DeleteCriticalSection(&m_cs); } + void Initialize() {} + void Push(T* data) { + EnterCriticalSection(&m_cs); + intStack.push_back(data); + LeaveCriticalSection(&m_cs); + } + T* Pop() { + EnterCriticalSection(&m_cs); + if (intStack.size()) { + T* ret = intStack.back(); + intStack.pop_back(); + LeaveCriticalSection(&m_cs); + return ret; + } else { + LeaveCriticalSection(&m_cs); + return NULL; + } + } + private: - CRITICAL_SECTION m_cs; + CRITICAL_SECTION m_cs; }; -void XMemCpy(void *a, const void *b, size_t s); -void XMemSet(void *a, int t, size_t s); -void XMemSet128(void *a, int t, size_t s); -void *XPhysicalAlloc(SIZE_T a, ULONG_PTR b, ULONG_PTR c, DWORD d); -void XPhysicalFree(void *a); +void XMemCpy(void* a, const void* b, size_t s); +void XMemSet(void* a, int t, size_t s); +void XMemSet128(void* a, int t, size_t s); +void* XPhysicalAlloc(SIZE_T a, ULONG_PTR b, ULONG_PTR c, DWORD d); +void XPhysicalFree(void* a); class DLCManager; -//class LevelGenerationOptions; +// class LevelGenerationOptions; class LevelRuleset; class ModelPart; class LevelChunk; @@ -158,81 +153,81 @@ const int XN_SYS_STORAGEDEVICESCHANGED = 3; // Codes returned for the gamepad input // -#define VK_PAD_A 0x5800 -#define VK_PAD_B 0x5801 -#define VK_PAD_X 0x5802 -#define VK_PAD_Y 0x5803 -#define VK_PAD_RSHOULDER 0x5804 -#define VK_PAD_LSHOULDER 0x5805 -#define VK_PAD_LTRIGGER 0x5806 -#define VK_PAD_RTRIGGER 0x5807 +#define VK_PAD_A 0x5800 +#define VK_PAD_B 0x5801 +#define VK_PAD_X 0x5802 +#define VK_PAD_Y 0x5803 +#define VK_PAD_RSHOULDER 0x5804 +#define VK_PAD_LSHOULDER 0x5805 +#define VK_PAD_LTRIGGER 0x5806 +#define VK_PAD_RTRIGGER 0x5807 -#define VK_PAD_DPAD_UP 0x5810 -#define VK_PAD_DPAD_DOWN 0x5811 -#define VK_PAD_DPAD_LEFT 0x5812 -#define VK_PAD_DPAD_RIGHT 0x5813 -#define VK_PAD_START 0x5814 -#define VK_PAD_BACK 0x5815 -#define VK_PAD_LTHUMB_PRESS 0x5816 -#define VK_PAD_RTHUMB_PRESS 0x5817 +#define VK_PAD_DPAD_UP 0x5810 +#define VK_PAD_DPAD_DOWN 0x5811 +#define VK_PAD_DPAD_LEFT 0x5812 +#define VK_PAD_DPAD_RIGHT 0x5813 +#define VK_PAD_START 0x5814 +#define VK_PAD_BACK 0x5815 +#define VK_PAD_LTHUMB_PRESS 0x5816 +#define VK_PAD_RTHUMB_PRESS 0x5817 -#define VK_PAD_LTHUMB_UP 0x5820 -#define VK_PAD_LTHUMB_DOWN 0x5821 -#define VK_PAD_LTHUMB_RIGHT 0x5822 -#define VK_PAD_LTHUMB_LEFT 0x5823 -#define VK_PAD_LTHUMB_UPLEFT 0x5824 -#define VK_PAD_LTHUMB_UPRIGHT 0x5825 -#define VK_PAD_LTHUMB_DOWNRIGHT 0x5826 -#define VK_PAD_LTHUMB_DOWNLEFT 0x5827 +#define VK_PAD_LTHUMB_UP 0x5820 +#define VK_PAD_LTHUMB_DOWN 0x5821 +#define VK_PAD_LTHUMB_RIGHT 0x5822 +#define VK_PAD_LTHUMB_LEFT 0x5823 +#define VK_PAD_LTHUMB_UPLEFT 0x5824 +#define VK_PAD_LTHUMB_UPRIGHT 0x5825 +#define VK_PAD_LTHUMB_DOWNRIGHT 0x5826 +#define VK_PAD_LTHUMB_DOWNLEFT 0x5827 -#define VK_PAD_RTHUMB_UP 0x5830 -#define VK_PAD_RTHUMB_DOWN 0x5831 -#define VK_PAD_RTHUMB_RIGHT 0x5832 -#define VK_PAD_RTHUMB_LEFT 0x5833 -#define VK_PAD_RTHUMB_UPLEFT 0x5834 -#define VK_PAD_RTHUMB_UPRIGHT 0x5835 -#define VK_PAD_RTHUMB_DOWNRIGHT 0x5836 -#define VK_PAD_RTHUMB_DOWNLEFT 0x5837 +#define VK_PAD_RTHUMB_UP 0x5830 +#define VK_PAD_RTHUMB_DOWN 0x5831 +#define VK_PAD_RTHUMB_RIGHT 0x5832 +#define VK_PAD_RTHUMB_LEFT 0x5833 +#define VK_PAD_RTHUMB_UPLEFT 0x5834 +#define VK_PAD_RTHUMB_UPRIGHT 0x5835 +#define VK_PAD_RTHUMB_DOWNRIGHT 0x5836 +#define VK_PAD_RTHUMB_DOWNLEFT 0x5837 const int XUSER_NAME_SIZE = 32; -class IQNetPlayer -{ +class IQNetPlayer { public: - BYTE GetSmallId(); - void SendData(IQNetPlayer *player, const void *pvData, DWORD dwDataSize, DWORD dwFlags); - bool IsSameSystem(IQNetPlayer *player); - DWORD GetSendQueueSize( IQNetPlayer *player, DWORD dwFlags ); - DWORD GetCurrentRtt(); - bool IsHost(); - bool IsGuest(); - bool IsLocal(); - PlayerUID GetXuid(); - LPCWSTR GetGamertag(); - int GetSessionIndex(); - bool IsTalking(); - bool IsMutedByLocalUser(DWORD dwUserIndex); - bool HasVoice(); - bool HasCamera(); - int GetUserIndex(); - void SetCustomDataValue(ULONG_PTR ulpCustomDataValue); - ULONG_PTR GetCustomDataValue(); + BYTE GetSmallId(); + void SendData(IQNetPlayer* player, const void* pvData, DWORD dwDataSize, + DWORD dwFlags); + bool IsSameSystem(IQNetPlayer* player); + DWORD GetSendQueueSize(IQNetPlayer* player, DWORD dwFlags); + DWORD GetCurrentRtt(); + bool IsHost(); + bool IsGuest(); + bool IsLocal(); + PlayerUID GetXuid(); + LPCWSTR GetGamertag(); + int GetSessionIndex(); + bool IsTalking(); + bool IsMutedByLocalUser(DWORD dwUserIndex); + bool HasVoice(); + bool HasCamera(); + int GetUserIndex(); + void SetCustomDataValue(ULONG_PTR ulpCustomDataValue); + ULONG_PTR GetCustomDataValue(); + private: - ULONG_PTR m_customData; + ULONG_PTR m_customData; }; const int QNET_GETSENDQUEUESIZE_SECONDARY_TYPE = 0; const int QNET_GETSENDQUEUESIZE_MESSAGES = 0; const int QNET_GETSENDQUEUESIZE_BYTES = 0; - typedef struct { BYTE bFlags; BYTE bReserved; WORD cProbesXmit; WORD cProbesRecv; WORD cbData; - BYTE *pbData; + BYTE* pbData; WORD wRttMinInMsecs; WORD wRttMedInMsecs; DWORD dwUpBitsPerSec; @@ -258,7 +253,7 @@ typedef struct { typedef struct _XSESSION_SEARCHRESULT_HEADER { DWORD dwSearchResults; - XSESSION_SEARCHRESULT *pResults; + XSESSION_SEARCHRESULT* pResults; } XSESSION_SEARCHRESULT_HEADER, *PXSESSION_SEARCHRESULT_HEADER; typedef struct _XONLINE_FRIEND { @@ -271,20 +266,14 @@ typedef struct _XONLINE_FRIEND { SessionID xnkidInvite; FILETIME gameinviteTime; DWORD cchRichPresence; -// WCHAR wszRichPresence[MAX_RICHPRESENCE_SIZE]; + // WCHAR wszRichPresence[MAX_RICHPRESENCE_SIZE]; } XONLINE_FRIEND, *PXONLINE_FRIEND; -class IQNetCallbacks -{ -}; +class IQNetCallbacks {}; -class IQNetGameSearch -{ -}; +class IQNetGameSearch {}; - -typedef enum _QNET_STATE -{ +typedef enum _QNET_STATE { QNET_STATE_IDLE, QNET_STATE_SESSION_HOSTING, QNET_STATE_SESSION_JOINING, @@ -295,46 +284,49 @@ typedef enum _QNET_STATE QNET_STATE_SESSION_ENDING, QNET_STATE_SESSION_LEAVING, QNET_STATE_SESSION_DELETING -} QNET_STATE, * PQNET_STATE; +} QNET_STATE, + *PQNET_STATE; -class IQNet -{ +class IQNet { public: - HRESULT AddLocalPlayerByUserIndex(DWORD dwUserIndex); - IQNetPlayer *GetHostPlayer(); - IQNetPlayer *GetLocalPlayerByUserIndex(DWORD dwUserIndex); - IQNetPlayer *GetPlayerByIndex(DWORD dwPlayerIndex); - IQNetPlayer *GetPlayerBySmallId(BYTE SmallId); - IQNetPlayer *GetPlayerByXuid(PlayerUID xuid); - DWORD GetPlayerCount(); - QNET_STATE GetState(); - bool IsHost(); - HRESULT JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, const INVITE_INFO *pInviteInfo); - void HostGame(); - void EndGame(); + HRESULT AddLocalPlayerByUserIndex(DWORD dwUserIndex); + IQNetPlayer* GetHostPlayer(); + IQNetPlayer* GetLocalPlayerByUserIndex(DWORD dwUserIndex); + IQNetPlayer* GetPlayerByIndex(DWORD dwPlayerIndex); + IQNetPlayer* GetPlayerBySmallId(BYTE SmallId); + IQNetPlayer* GetPlayerByXuid(PlayerUID xuid); + DWORD GetPlayerCount(); + QNET_STATE GetState(); + bool IsHost(); + HRESULT JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, + const INVITE_INFO* pInviteInfo); + void HostGame(); + void EndGame(); - static IQNetPlayer m_player[4]; + static IQNetPlayer m_player[4]; }; #ifdef _DURANGO -// 4J Stu - We don't want to be doing string conversions at runtime for timing instrumentation, so do this instead -#define PIXBeginNamedEvent(a, b, ...) PIXBeginEvent(a,L ## b, __VA_ARGS__) +// 4J Stu - We don't want to be doing string conversions at runtime for timing +// instrumentation, so do this instead +#define PIXBeginNamedEvent(a, b, ...) PIXBeginEvent(a, L##b, __VA_ARGS__) #define PIXEndNamedEvent() PIXEndEvent() -#define PIXSetMarkerDeprecated(a, b, ...) PIXSetMarker(a, L ## b, __VA_ARGS__) -#define PIXAddNamedCounter(a, b) PIXReportCounter( L ## b, a) +#define PIXSetMarkerDeprecated(a, b, ...) PIXSetMarker(a, L##b, __VA_ARGS__) +#define PIXAddNamedCounter(a, b) PIXReportCounter(L##b, a) #else -void PIXAddNamedCounter(int a, const char *b, ...); -void PIXBeginNamedEvent(int a, const char *b, ...); +void PIXAddNamedCounter(int a, const char* b, ...); +void PIXBeginNamedEvent(int a, const char* b, ...); void PIXEndNamedEvent(); -void PIXSetMarkerDeprecated(int a, const char *b, ...); +void PIXSetMarkerDeprecated(int a, const char* b, ...); #endif void XSetThreadProcessor(HANDLE a, int b); -//BOOL XCloseHandle(HANDLE a); +// BOOL XCloseHandle(HANDLE a); const int QNET_SENDDATA_LOW_PRIORITY = 0; const int QNET_SENDDATA_SECONDARY = 0; -#if defined(__PS3__) || defined(__ORBIS__) || defined(_DURANGO) || defined(__PSVITA__) +#if defined(__PS3__) || defined(__ORBIS__) || defined(_DURANGO) || \ + defined(__PSVITA__) #define INVALID_XUID PlayerUID() #else const int INVALID_XUID = 0; @@ -351,25 +343,24 @@ const int XCONTENT_MAX_DISPLAYNAME_LENGTH = 256; const int XCONTENT_MAX_FILENAME_LENGTH = 256; typedef int XCONTENTDEVICEID; -#if !defined( __PS3__) && !defined(__ORBIS__) && !defined(_DURANGO) && !defined(__PSVITA__) -typedef struct _XCONTENT_DATA -{ +#if !defined(__PS3__) && !defined(__ORBIS__) && !defined(_DURANGO) && \ + !defined(__PSVITA__) +typedef struct _XCONTENT_DATA { XCONTENTDEVICEID DeviceID; DWORD dwContentType; WCHAR szDisplayName[XCONTENT_MAX_DISPLAYNAME_LENGTH]; CHAR szFileName[XCONTENT_MAX_FILENAME_LENGTH]; } XCONTENT_DATA, *PXCONTENT_DATA; -#endif //__PS3__ +#endif //__PS3__ static const int XMARKETPLACE_CONTENT_ID_LEN = 4; #ifndef _DURANGO -typedef struct _XMARKETPLACE_CONTENTOFFER_INFO -{ +typedef struct _XMARKETPLACE_CONTENTOFFER_INFO { ULONGLONG qwOfferID; ULONGLONG qwPreviewOfferID; DWORD dwOfferNameLength; - WCHAR *wszOfferName; + WCHAR* wszOfferName; DWORD dwOfferType; BYTE contentId[XMARKETPLACE_CONTENT_ID_LEN]; BOOL fIsUnrestrictedLicense; @@ -377,19 +368,18 @@ typedef struct _XMARKETPLACE_CONTENTOFFER_INFO DWORD dwTitleID; DWORD dwContentCategory; DWORD dwTitleNameLength; - WCHAR *wszTitleName; + WCHAR* wszTitleName; BOOL fUserHasPurchased; DWORD dwPackageSize; DWORD dwInstallSize; DWORD dwSellTextLength; - WCHAR *wszSellText; + WCHAR* wszSellText; DWORD dwAssetID; DWORD dwPurchaseQuantity; DWORD dwPointsPrice; } XMARKETPLACE_CONTENTOFFER_INFO, *PXMARKETPLACE_CONTENTOFFER_INFO; -typedef enum -{ +typedef enum { XMARKETPLACE_OFFERING_TYPE_CONTENT = 0x00000002, XMARKETPLACE_OFFERING_TYPE_GAME_DEMO = 0x00000020, XMARKETPLACE_OFFERING_TYPE_GAME_TRAILER = 0x00000040, @@ -400,85 +390,61 @@ typedef enum XMARKETPLACE_OFFERING_TYPE_CONSUMABLE = 0x00010000, XMARKETPLACE_OFFERING_TYPE_AVATARITEM = 0x00100000 } XMARKETPLACE_OFFERING_TYPE; -#endif // _DURANGO +#endif // _DURANGO const int QNET_SENDDATA_RELIABLE = 0; const int QNET_SENDDATA_SEQUENTIAL = 0; -struct XRNM_SEND_BUFFER -{ - DWORD dwDataSize; - uint8_t *pbyData; +struct XRNM_SEND_BUFFER { + DWORD dwDataSize; + uint8_t* pbyData; }; const int D3DBLEND_CONSTANTALPHA = 0; const int D3DBLEND_INVCONSTANTALPHA = 0; const int D3DPT_QUADLIST = 0; - typedef struct _XUSER_SIGNIN_INFO { - PlayerUID xuid; + PlayerUID xuid; DWORD dwGuestNumber; } XUSER_SIGNIN_INFO, *PXUSER_SIGNIN_INFO; -#define XUSER_GET_SIGNIN_INFO_ONLINE_XUID_ONLY 0x00000001 -#define XUSER_GET_SIGNIN_INFO_OFFLINE_XUID_ONLY 0x00000002 +#define XUSER_GET_SIGNIN_INFO_ONLINE_XUID_ONLY 0x00000001 +#define XUSER_GET_SIGNIN_INFO_OFFLINE_XUID_ONLY 0x00000002 -DWORD XUserGetSigninInfo( - DWORD dwUserIndex, - DWORD dwFlags, - PXUSER_SIGNIN_INFO pSigninInfo -); +DWORD XUserGetSigninInfo(DWORD dwUserIndex, DWORD dwFlags, + PXUSER_SIGNIN_INFO pSigninInfo); -class CXuiStringTable -{ +class CXuiStringTable { public: - LPCWSTR Lookup(LPCWSTR szId); - LPCWSTR Lookup(UINT nIndex); - void Clear(); - HRESULT Load(LPCWSTR szId); + LPCWSTR Lookup(LPCWSTR szId); + LPCWSTR Lookup(UINT nIndex); + void Clear(); + HRESULT Load(LPCWSTR szId); }; #if !defined(__ORBIS__) && !defined(_XBOX_ONE) -typedef VOID * XMEMDECOMPRESSION_CONTEXT; -typedef VOID * XMEMCOMPRESSION_CONTEXT; +typedef VOID* XMEMDECOMPRESSION_CONTEXT; +typedef VOID* XMEMCOMPRESSION_CONTEXT; -typedef enum _XMEMCODEC_TYPE -{ +typedef enum _XMEMCODEC_TYPE { XMEMCODEC_DEFAULT = 0, XMEMCODEC_LZX = 1 } XMEMCODEC_TYPE; -HRESULT XMemDecompress( - XMEMDECOMPRESSION_CONTEXT Context, - VOID *pDestination, - SIZE_T *pDestSize, - VOID *pSource, - SIZE_T SrcSize -); +HRESULT XMemDecompress(XMEMDECOMPRESSION_CONTEXT Context, VOID* pDestination, + SIZE_T* pDestSize, VOID* pSource, SIZE_T SrcSize); +HRESULT XMemCompress(XMEMCOMPRESSION_CONTEXT Context, VOID* pDestination, + SIZE_T* pDestSize, VOID* pSource, SIZE_T SrcSize); -HRESULT XMemCompress( - XMEMCOMPRESSION_CONTEXT Context, - VOID *pDestination, - SIZE_T *pDestSize, - VOID *pSource, - SIZE_T SrcSize -); +HRESULT XMemCreateCompressionContext(XMEMCODEC_TYPE CodecType, + const VOID* pCodecParams, DWORD Flags, + XMEMCOMPRESSION_CONTEXT* pContext); -HRESULT XMemCreateCompressionContext( - XMEMCODEC_TYPE CodecType, - const VOID *pCodecParams, - DWORD Flags, - XMEMCOMPRESSION_CONTEXT *pContext -); - -HRESULT XMemCreateDecompressionContext( - XMEMCODEC_TYPE CodecType, - const VOID *pCodecParams, - DWORD Flags, - XMEMDECOMPRESSION_CONTEXT *pContext -); +HRESULT XMemCreateDecompressionContext(XMEMCODEC_TYPE CodecType, + const VOID* pCodecParams, DWORD Flags, + XMEMDECOMPRESSION_CONTEXT* pContext); typedef struct _XMEMCODEC_PARAMETERS_LZX { DWORD Flags; @@ -499,12 +465,12 @@ typedef struct { struct { DWORD cbData; LPWSTR pwszData; - }string; + } string; float fData; struct { DWORD cbData; PBYTE pbData; - }binary; + } binary; FILETIME ftData; }; } XUSER_DATA, *PXUSER_DATA; @@ -544,95 +510,93 @@ typedef struct { // #endif // matching Xbox 360 -const int XC_LANGUAGE_ENGLISH =0x01; -const int XC_LANGUAGE_JAPANESE =0x02; -const int XC_LANGUAGE_GERMAN =0x03; -const int XC_LANGUAGE_FRENCH =0x04; -const int XC_LANGUAGE_SPANISH =0x05; -const int XC_LANGUAGE_ITALIAN =0x06; -const int XC_LANGUAGE_KOREAN =0x07; -const int XC_LANGUAGE_TCHINESE =0x08; -const int XC_LANGUAGE_PORTUGUESE =0x09; -const int XC_LANGUAGE_POLISH =0x0B; -const int XC_LANGUAGE_RUSSIAN =0x0C; -const int XC_LANGUAGE_SWEDISH =0x0D; -const int XC_LANGUAGE_TURKISH =0x0E; -const int XC_LANGUAGE_BNORWEGIAN =0x0F; -const int XC_LANGUAGE_DUTCH =0x10; -const int XC_LANGUAGE_SCHINESE =0x11; +const int XC_LANGUAGE_ENGLISH = 0x01; +const int XC_LANGUAGE_JAPANESE = 0x02; +const int XC_LANGUAGE_GERMAN = 0x03; +const int XC_LANGUAGE_FRENCH = 0x04; +const int XC_LANGUAGE_SPANISH = 0x05; +const int XC_LANGUAGE_ITALIAN = 0x06; +const int XC_LANGUAGE_KOREAN = 0x07; +const int XC_LANGUAGE_TCHINESE = 0x08; +const int XC_LANGUAGE_PORTUGUESE = 0x09; +const int XC_LANGUAGE_POLISH = 0x0B; +const int XC_LANGUAGE_RUSSIAN = 0x0C; +const int XC_LANGUAGE_SWEDISH = 0x0D; +const int XC_LANGUAGE_TURKISH = 0x0E; +const int XC_LANGUAGE_BNORWEGIAN = 0x0F; +const int XC_LANGUAGE_DUTCH = 0x10; +const int XC_LANGUAGE_SCHINESE = 0x11; // for Sony -const int XC_LANGUAGE_LATINAMERICANSPANISH =0xF0; -const int XC_LANGUAGE_FINISH =0xF1; -const int XC_LANGUAGE_GREEK =0xF2; -const int XC_LANGUAGE_DANISH =0xF3; +const int XC_LANGUAGE_LATINAMERICANSPANISH = 0xF0; +const int XC_LANGUAGE_FINISH = 0xF1; +const int XC_LANGUAGE_GREEK = 0xF2; +const int XC_LANGUAGE_DANISH = 0xF3; // for Xbox One -const int XC_LANGUAGE_CZECH =0xF4; -const int XC_LANGUAGE_SLOVAK =0xF5; +const int XC_LANGUAGE_CZECH = 0xF4; +const int XC_LANGUAGE_SLOVAK = 0xF5; -const int XC_LOCALE_AUSTRALIA =1; -const int XC_LOCALE_AUSTRIA =2; -const int XC_LOCALE_BELGIUM =3; -const int XC_LOCALE_BRAZIL =4; -const int XC_LOCALE_CANADA =5; -const int XC_LOCALE_CHILE =6; -const int XC_LOCALE_CHINA =7; -const int XC_LOCALE_COLOMBIA =8; -const int XC_LOCALE_CZECH_REPUBLIC =9; -const int XC_LOCALE_DENMARK =10; -const int XC_LOCALE_FINLAND =11; -const int XC_LOCALE_FRANCE =12; -const int XC_LOCALE_GERMANY =13; -const int XC_LOCALE_GREECE =14; -const int XC_LOCALE_HONG_KONG =15; -const int XC_LOCALE_HUNGARY =16; -const int XC_LOCALE_INDIA =17; -const int XC_LOCALE_IRELAND =18; -const int XC_LOCALE_ITALY =19; -const int XC_LOCALE_JAPAN =20; -const int XC_LOCALE_KOREA =21; -const int XC_LOCALE_MEXICO =22; -const int XC_LOCALE_NETHERLANDS =23; -const int XC_LOCALE_NEW_ZEALAND =24; -const int XC_LOCALE_NORWAY =25; -const int XC_LOCALE_POLAND =26; -const int XC_LOCALE_PORTUGAL =27; -const int XC_LOCALE_SINGAPORE =28; -const int XC_LOCALE_SLOVAK_REPUBLIC =29; -const int XC_LOCALE_SOUTH_AFRICA =30; -const int XC_LOCALE_SPAIN =31; -const int XC_LOCALE_SWEDEN =32; -const int XC_LOCALE_SWITZERLAND =33; -const int XC_LOCALE_TAIWAN =34; -const int XC_LOCALE_GREAT_BRITAIN =35; -const int XC_LOCALE_UNITED_STATES =36; -const int XC_LOCALE_RUSSIAN_FEDERATION =37; -const int XC_LOCALE_WORLD_WIDE =38; -const int XC_LOCALE_TURKEY =39; -const int XC_LOCALE_ARGENTINA =40; -const int XC_LOCALE_SAUDI_ARABIA =41; -const int XC_LOCALE_ISRAEL =42; -const int XC_LOCALE_UNITED_ARAB_EMIRATES =43; +const int XC_LOCALE_AUSTRALIA = 1; +const int XC_LOCALE_AUSTRIA = 2; +const int XC_LOCALE_BELGIUM = 3; +const int XC_LOCALE_BRAZIL = 4; +const int XC_LOCALE_CANADA = 5; +const int XC_LOCALE_CHILE = 6; +const int XC_LOCALE_CHINA = 7; +const int XC_LOCALE_COLOMBIA = 8; +const int XC_LOCALE_CZECH_REPUBLIC = 9; +const int XC_LOCALE_DENMARK = 10; +const int XC_LOCALE_FINLAND = 11; +const int XC_LOCALE_FRANCE = 12; +const int XC_LOCALE_GERMANY = 13; +const int XC_LOCALE_GREECE = 14; +const int XC_LOCALE_HONG_KONG = 15; +const int XC_LOCALE_HUNGARY = 16; +const int XC_LOCALE_INDIA = 17; +const int XC_LOCALE_IRELAND = 18; +const int XC_LOCALE_ITALY = 19; +const int XC_LOCALE_JAPAN = 20; +const int XC_LOCALE_KOREA = 21; +const int XC_LOCALE_MEXICO = 22; +const int XC_LOCALE_NETHERLANDS = 23; +const int XC_LOCALE_NEW_ZEALAND = 24; +const int XC_LOCALE_NORWAY = 25; +const int XC_LOCALE_POLAND = 26; +const int XC_LOCALE_PORTUGAL = 27; +const int XC_LOCALE_SINGAPORE = 28; +const int XC_LOCALE_SLOVAK_REPUBLIC = 29; +const int XC_LOCALE_SOUTH_AFRICA = 30; +const int XC_LOCALE_SPAIN = 31; +const int XC_LOCALE_SWEDEN = 32; +const int XC_LOCALE_SWITZERLAND = 33; +const int XC_LOCALE_TAIWAN = 34; +const int XC_LOCALE_GREAT_BRITAIN = 35; +const int XC_LOCALE_UNITED_STATES = 36; +const int XC_LOCALE_RUSSIAN_FEDERATION = 37; +const int XC_LOCALE_WORLD_WIDE = 38; +const int XC_LOCALE_TURKEY = 39; +const int XC_LOCALE_ARGENTINA = 40; +const int XC_LOCALE_SAUDI_ARABIA = 41; +const int XC_LOCALE_ISRAEL = 42; +const int XC_LOCALE_UNITED_ARAB_EMIRATES = 43; // for Sony -const int XC_LOCALE_LATIN_AMERICA =240; +const int XC_LOCALE_LATIN_AMERICA = 240; - - -#if !(defined _DURANGO || defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) +#if !(defined _DURANGO || defined __PS3__ || defined __ORBIS__ || \ + defined __PSVITA__) DWORD XGetLanguage(); DWORD XGetLocale(); DWORD XEnableGuestSignin(BOOL fEnable); #endif -class D3DXVECTOR3 -{ +class D3DXVECTOR3 { public: - D3DXVECTOR3(); - D3DXVECTOR3(float,float,float); - float x,y,z,pad; - D3DXVECTOR3& operator += ( const D3DXVECTOR3& add ); + D3DXVECTOR3(); + D3DXVECTOR3(float, float, float); + float x, y, z, pad; + D3DXVECTOR3& operator+=(const D3DXVECTOR3& add); }; #define QNET_E_SESSION_FULL 0 diff --git a/Minecraft.World/Player/Abilities.cpp b/Minecraft.World/Player/Abilities.cpp index 409196472..5c3b67448 100644 --- a/Minecraft.World/Player/Abilities.cpp +++ b/Minecraft.World/Player/Abilities.cpp @@ -2,76 +2,57 @@ #include "../Headers/com.mojang.nbt.h" #include "Abilities.h" -Abilities::Abilities() -{ - invulnerable = false; - flying = false; - mayfly = false; - instabuild = false; - mayBuild = true; - flyingSpeed = 0.05f; - walkingSpeed = 0.1f; +Abilities::Abilities() { + invulnerable = false; + flying = false; + mayfly = false; + instabuild = false; + mayBuild = true; + flyingSpeed = 0.05f; + walkingSpeed = 0.1f; #ifdef _DEBUG_MENUS_ENABLED - debugflying = false; + debugflying = false; #endif } -void Abilities::addSaveData(CompoundTag *parentTag) -{ - CompoundTag *tag = new CompoundTag(); +void Abilities::addSaveData(CompoundTag* parentTag) { + CompoundTag* tag = new CompoundTag(); - tag->putBoolean(L"invulnerable", invulnerable); - tag->putBoolean(L"flying", flying); - tag->putBoolean(L"mayfly", mayfly); - tag->putBoolean(L"instabuild", instabuild); - tag->putBoolean(L"mayBuild", mayBuild); - tag->putFloat(L"flySpeed", flyingSpeed); - tag->putFloat(L"walkSpeed", walkingSpeed); - - parentTag->put(L"abilities", tag); + tag->putBoolean(L"invulnerable", invulnerable); + tag->putBoolean(L"flying", flying); + tag->putBoolean(L"mayfly", mayfly); + tag->putBoolean(L"instabuild", instabuild); + tag->putBoolean(L"mayBuild", mayBuild); + tag->putFloat(L"flySpeed", flyingSpeed); + tag->putFloat(L"walkSpeed", walkingSpeed); + parentTag->put(L"abilities", tag); } -void Abilities::loadSaveData(CompoundTag *parentTag) -{ - if (parentTag->contains(L"abilities")) - { - CompoundTag *tag = parentTag->getCompound(L"abilities"); +void Abilities::loadSaveData(CompoundTag* parentTag) { + if (parentTag->contains(L"abilities")) { + CompoundTag* tag = parentTag->getCompound(L"abilities"); - invulnerable = tag->getBoolean(L"invulnerable"); - flying = tag->getBoolean(L"flying"); - mayfly = tag->getBoolean(L"mayfly"); - instabuild = tag->getBoolean(L"instabuild"); + invulnerable = tag->getBoolean(L"invulnerable"); + flying = tag->getBoolean(L"flying"); + mayfly = tag->getBoolean(L"mayfly"); + instabuild = tag->getBoolean(L"instabuild"); - if (tag->contains(L"flySpeed")) - { - flyingSpeed = tag->getFloat(L"flySpeed"); - walkingSpeed = tag->getFloat(L"walkSpeed"); - } - if (tag->contains(L"mayBuild")) - { - mayBuild = tag->getBoolean(L"mayBuild"); - } - } + if (tag->contains(L"flySpeed")) { + flyingSpeed = tag->getFloat(L"flySpeed"); + walkingSpeed = tag->getFloat(L"walkSpeed"); + } + if (tag->contains(L"mayBuild")) { + mayBuild = tag->getBoolean(L"mayBuild"); + } + } } -float Abilities::getFlyingSpeed() -{ - return flyingSpeed; -} +float Abilities::getFlyingSpeed() { return flyingSpeed; } -void Abilities::setFlyingSpeed(float value) -{ - this->flyingSpeed = value; -} +void Abilities::setFlyingSpeed(float value) { this->flyingSpeed = value; } -float Abilities::getWalkingSpeed() -{ - return walkingSpeed; -} +float Abilities::getWalkingSpeed() { return walkingSpeed; } -void Abilities::setWalkingSpeed(float value) -{ - this->walkingSpeed = value; -} \ No newline at end of file +void Abilities::setWalkingSpeed(float value) { this->walkingSpeed = value; } \ No newline at end of file diff --git a/Minecraft.World/Player/Abilities.h b/Minecraft.World/Player/Abilities.h index f5895cdd4..85329862f 100644 --- a/Minecraft.World/Player/Abilities.h +++ b/Minecraft.World/Player/Abilities.h @@ -2,31 +2,30 @@ class CompoundTag; -class Abilities -{ +class Abilities { public: - bool invulnerable; - bool flying; - bool mayfly; - bool instabuild; - bool mayBuild; + bool invulnerable; + bool flying; + bool mayfly; + bool instabuild; + bool mayBuild; private: - float flyingSpeed; - float walkingSpeed; + float flyingSpeed; + float walkingSpeed; public: #ifdef _DEBUG_MENUS_ENABLED - bool debugflying; + bool debugflying; #endif - Abilities(); + Abilities(); - void addSaveData(CompoundTag *parentTag); - void loadSaveData(CompoundTag *parentTag); + void addSaveData(CompoundTag* parentTag); + void loadSaveData(CompoundTag* parentTag); - float getFlyingSpeed(); - void setFlyingSpeed(float value); - float getWalkingSpeed(); - void setWalkingSpeed(float value); + float getFlyingSpeed(); + void setFlyingSpeed(float value); + float getWalkingSpeed(); + void setWalkingSpeed(float value); }; \ No newline at end of file diff --git a/Minecraft.World/Player/FoodData.cpp b/Minecraft.World/Player/FoodData.cpp index ca85a3eba..17a1fa02e 100644 --- a/Minecraft.World/Player/FoodData.cpp +++ b/Minecraft.World/Player/FoodData.cpp @@ -8,152 +8,109 @@ #include "../Util/FoodConstants.h" #include "FoodData.h" -FoodData::FoodData() -{ - exhaustionLevel = 0; - tickTimer = 0; +FoodData::FoodData() { + exhaustionLevel = 0; + tickTimer = 0; - this->foodLevel = FoodConstants::MAX_FOOD; - this->lastFoodLevel = FoodConstants::MAX_FOOD; - this->saturationLevel = FoodConstants::START_SATURATION; + this->foodLevel = FoodConstants::MAX_FOOD; + this->lastFoodLevel = FoodConstants::MAX_FOOD; + this->saturationLevel = FoodConstants::START_SATURATION; } -void FoodData::eat(int food, float saturationModifier) -{ - foodLevel = std::min(food + foodLevel, FoodConstants::MAX_FOOD); - saturationLevel = std::min(saturationLevel + (float) food * saturationModifier * 2.0f, (float)foodLevel); +void FoodData::eat(int food, float saturationModifier) { + foodLevel = std::min(food + foodLevel, FoodConstants::MAX_FOOD); + saturationLevel = + std::min(saturationLevel + (float)food * saturationModifier * 2.0f, + (float)foodLevel); } -void FoodData::eat(FoodItem *item) -{ - eat(item->getNutrition(), item->getSaturationModifier()); +void FoodData::eat(FoodItem* item) { + eat(item->getNutrition(), item->getSaturationModifier()); } -void FoodData::tick(std::shared_ptr player) -{ +void FoodData::tick(std::shared_ptr player) { + int difficulty = player->level->difficulty; - int difficulty = player->level->difficulty; + lastFoodLevel = foodLevel; - lastFoodLevel = foodLevel; + if (exhaustionLevel > FoodConstants::EXHAUSTION_DROP) { + exhaustionLevel -= FoodConstants::EXHAUSTION_DROP; - if (exhaustionLevel > FoodConstants::EXHAUSTION_DROP) - { - exhaustionLevel -= FoodConstants::EXHAUSTION_DROP; - - if (saturationLevel > 0) - { - saturationLevel = std::max(saturationLevel - 1, 0.0f); - } - else if (difficulty > Difficulty::PEACEFUL) - { - foodLevel = std::max(foodLevel - 1, 0); - } - } - - // 4J Added - Allow host to disable using hunger. We don't deplete the hunger bar due to exhaustion - // but I think we should deplete it to heal - if(player->isAllowedToIgnoreExhaustion()) - { - if(foodLevel > 0 && player->isHurt()) - { - tickTimer++; - if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) - { - player->heal(1); - --foodLevel; - tickTimer = 0; - } - } - } - else if (foodLevel >= FoodConstants::HEAL_LEVEL && player->isHurt()) - { - tickTimer++; - if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) - { - player->heal(1); - tickTimer = 0; - } - } - else if (foodLevel <= FoodConstants::STARVE_LEVEL) - { - tickTimer++; - if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) - { - if (player->getHealth() > 10 || difficulty >= Difficulty::HARD || (player->getHealth() > 1 && difficulty >= Difficulty::NORMAL)) - { - player->hurt(DamageSource::starve, 1); - } - tickTimer = 0; - } - } - else - { - tickTimer = 0; - } + if (saturationLevel > 0) { + saturationLevel = std::max(saturationLevel - 1, 0.0f); + } else if (difficulty > Difficulty::PEACEFUL) { + foodLevel = std::max(foodLevel - 1, 0); + } + } + // 4J Added - Allow host to disable using hunger. We don't deplete the + // hunger bar due to exhaustion but I think we should deplete it to heal + if (player->isAllowedToIgnoreExhaustion()) { + if (foodLevel > 0 && player->isHurt()) { + tickTimer++; + if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) { + player->heal(1); + --foodLevel; + tickTimer = 0; + } + } + } else if (foodLevel >= FoodConstants::HEAL_LEVEL && player->isHurt()) { + tickTimer++; + if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) { + player->heal(1); + tickTimer = 0; + } + } else if (foodLevel <= FoodConstants::STARVE_LEVEL) { + tickTimer++; + if (tickTimer >= FoodConstants::HEALTH_TICK_COUNT) { + if (player->getHealth() > 10 || difficulty >= Difficulty::HARD || + (player->getHealth() > 1 && difficulty >= Difficulty::NORMAL)) { + player->hurt(DamageSource::starve, 1); + } + tickTimer = 0; + } + } else { + tickTimer = 0; + } } -void FoodData::readAdditionalSaveData(CompoundTag *entityTag) -{ - - if (entityTag->contains(L"foodLevel")) - { - foodLevel = entityTag->getInt(L"foodLevel"); - tickTimer = entityTag->getInt(L"foodTickTimer"); - saturationLevel = entityTag->getFloat(L"foodSaturationLevel"); - exhaustionLevel = entityTag->getFloat(L"foodExhaustionLevel"); - } +void FoodData::readAdditionalSaveData(CompoundTag* entityTag) { + if (entityTag->contains(L"foodLevel")) { + foodLevel = entityTag->getInt(L"foodLevel"); + tickTimer = entityTag->getInt(L"foodTickTimer"); + saturationLevel = entityTag->getFloat(L"foodSaturationLevel"); + exhaustionLevel = entityTag->getFloat(L"foodExhaustionLevel"); + } } -void FoodData::addAdditonalSaveData(CompoundTag *entityTag) -{ - entityTag->putInt(L"foodLevel", foodLevel); - entityTag->putInt(L"foodTickTimer", tickTimer); - entityTag->putFloat(L"foodSaturationLevel", saturationLevel); - entityTag->putFloat(L"foodExhaustionLevel", exhaustionLevel); +void FoodData::addAdditonalSaveData(CompoundTag* entityTag) { + entityTag->putInt(L"foodLevel", foodLevel); + entityTag->putInt(L"foodTickTimer", tickTimer); + entityTag->putFloat(L"foodSaturationLevel", saturationLevel); + entityTag->putFloat(L"foodExhaustionLevel", exhaustionLevel); } -int FoodData::getFoodLevel() -{ - return foodLevel; +int FoodData::getFoodLevel() { return foodLevel; } + +int FoodData::getLastFoodLevel() { return lastFoodLevel; } + +bool FoodData::needsFood() { return foodLevel < FoodConstants::MAX_FOOD; } + +void FoodData::addExhaustion(float amount) { + exhaustionLevel = + std::min(exhaustionLevel + amount, FoodConstants::MAX_SATURATION * 2); } -int FoodData::getLastFoodLevel() -{ - return lastFoodLevel; +float FoodData::getExhaustionLevel() { return exhaustionLevel; } + +float FoodData::getSaturationLevel() { return saturationLevel; } + +void FoodData::setFoodLevel(int food) { this->foodLevel = food; } + +void FoodData::setSaturation(float saturation) { + this->saturationLevel = saturation; } -bool FoodData::needsFood() -{ - return foodLevel < FoodConstants::MAX_FOOD; -} - -void FoodData::addExhaustion(float amount) -{ - exhaustionLevel = std::min(exhaustionLevel + amount, FoodConstants::MAX_SATURATION * 2); -} - -float FoodData::getExhaustionLevel() -{ - return exhaustionLevel; -} - -float FoodData::getSaturationLevel() -{ - return saturationLevel; -} - -void FoodData::setFoodLevel(int food) -{ - this->foodLevel = food; -} - -void FoodData::setSaturation(float saturation) -{ - this->saturationLevel = saturation; -} - -void FoodData::setExhaustion(float exhaustion) -{ - this->exhaustionLevel = exhaustion; +void FoodData::setExhaustion(float exhaustion) { + this->exhaustionLevel = exhaustion; } \ No newline at end of file diff --git a/Minecraft.World/Player/FoodData.h b/Minecraft.World/Player/FoodData.h index 9d847454b..c81e9267a 100644 --- a/Minecraft.World/Player/FoodData.h +++ b/Minecraft.World/Player/FoodData.h @@ -4,31 +4,30 @@ class FoodItem; class Player; class CompoundTag; -class FoodData -{ +class FoodData { private: - int foodLevel; - float saturationLevel; - float exhaustionLevel; + int foodLevel; + float saturationLevel; + float exhaustionLevel; - int tickTimer; - int lastFoodLevel; + int tickTimer; + int lastFoodLevel; public: - FoodData(); + FoodData(); - void eat(int food, float saturationModifier); - void eat(FoodItem *item); - void tick(std::shared_ptr player); - void readAdditionalSaveData(CompoundTag *entityTag); - void addAdditonalSaveData(CompoundTag *entityTag); - int getFoodLevel(); - int getLastFoodLevel(); - bool needsFood(); - void addExhaustion(float amount); - float getExhaustionLevel(); - float getSaturationLevel(); - void setFoodLevel(int food); - void setSaturation(float saturation); - void setExhaustion(float exhaustion); + void eat(int food, float saturationModifier); + void eat(FoodItem* item); + void tick(std::shared_ptr player); + void readAdditionalSaveData(CompoundTag* entityTag); + void addAdditonalSaveData(CompoundTag* entityTag); + int getFoodLevel(); + int getLastFoodLevel(); + bool needsFood(); + void addExhaustion(float amount); + float getExhaustionLevel(); + float getSaturationLevel(); + void setFoodLevel(int food); + void setSaturation(float saturation); + void setExhaustion(float exhaustion); }; \ No newline at end of file diff --git a/Minecraft.World/Player/Player.cpp b/Minecraft.World/Player/Player.cpp index 3b0c53971..a6bc411f9 100644 --- a/Minecraft.World/Player/Player.cpp +++ b/Minecraft.World/Player/Player.cpp @@ -1,10 +1,11 @@ // 4J TODO -// All the instanceof s from Java have been converted to dynamic_cast in this file -// Once all the classes are finished it may be that we do not need to use dynamic_cast -// for every test and a simple virtual function should suffice. We probably only need -// dynamic_cast to find one of the classes that an object derives from, and not to find -// the derived class itself (which should own the virtual GetType function) +// All the instanceof s from Java have been converted to dynamic_cast in this +// file Once all the classes are finished it may be that we do not need to use +// dynamic_cast for every test and a simple virtual function should suffice. We +// probably only need dynamic_cast to find one of the classes that an object +// derives from, and not to find the derived class itself (which should own the +// virtual GetType function) #include "../Platform/stdafx.h" #include "../Util/JavaMath.h" @@ -40,331 +41,284 @@ #include "../../Minecraft.Client/Rendering/Models/HumanoidModel.h" #include "../Util/SoundTypes.h" +void Player::_init() { + inventory = std::shared_ptr(new Inventory(this)); + userType = 0; + score = 0; + oBob = bob = 0.0f; + swinging = false; + swingTime = 0; -void Player::_init() -{ + // string name; + dimension = 0; + // string cloakTexture; - inventory = std::shared_ptr( new Inventory( this ) ); + xCloakO = yCloakO = zCloakO = 0.0; + xCloak = yCloak = zCloak = 0.0; - userType = 0; - score = 0; - oBob = bob = 0.0f; - swinging = false; - swingTime = 0; + m_isSleeping = false; - //string name; - dimension = 0; - //string cloakTexture; + m_uiPlayerCurrentSkin = 0; - xCloakO = yCloakO = zCloakO = 0.0; - xCloak = yCloak = zCloak = 0.0; + bedPosition = NULL; - m_isSleeping = false; + sleepCounter = 0; + deathFadeCounter = 0; - m_uiPlayerCurrentSkin=0; + bedOffsetX = bedOffsetY = bedOffsetZ = 0.0f; + stats = NULL; - bedPosition = NULL; + respawnPosition = NULL; + minecartAchievementPos = NULL; + changingDimensionDelay = 20; - sleepCounter = 0; - deathFadeCounter=0; + isInsidePortal = false; + portalTime = oPortalTime = 0.0f; - bedOffsetX = bedOffsetY = bedOffsetZ = 0.0f; - stats = NULL; + dmgSpill = 0; + fishing = nullptr; - respawnPosition = NULL; - minecartAchievementPos = NULL; + distanceWalk = distanceSwim = distanceFall = distanceClimb = + distanceMinecart = distanceBoat = distancePig = 0; + m_uiDebugOptions = 0L; - changingDimensionDelay = 20; + jumpTriggerTime = 0; + takeXpDelay = 0; + experienceLevel = totalExperience = 0; + experienceProgress = 0.0f; + useItem = nullptr; + useItemDuration = 0; - isInsidePortal = false; + defaultWalkSpeed = 0.1f; + defaultFlySpeed = 0.02f; + m_uiGamePrivileges = 0; - portalTime = oPortalTime = 0.0f; - - dmgSpill = 0; - - - fishing = nullptr; - - distanceWalk = distanceSwim = distanceFall = distanceClimb = distanceMinecart = distanceBoat = distancePig = 0; - - m_uiDebugOptions=0L; - - jumpTriggerTime = 0; - takeXpDelay = 0; - experienceLevel = totalExperience = 0; - experienceProgress = 0.0f; - - useItem = nullptr; - useItemDuration = 0; - - defaultWalkSpeed = 0.1f; - defaultFlySpeed = 0.02f; - - m_uiGamePrivileges = 0; - - m_ppAdditionalModelParts=NULL; - m_bCheckedForModelParts=false; - m_bCheckedDLCForModelParts=false; + m_ppAdditionalModelParts = NULL; + m_bCheckedForModelParts = false; + m_bCheckedDLCForModelParts = false; #if defined(__PS3__) || defined(__ORBIS__) - m_ePlayerNameValidState=ePlayerNameValid_NotSet; + m_ePlayerNameValidState = ePlayerNameValid_NotSet; #endif - enderChestInventory = std::shared_ptr(new PlayerEnderChestContainer()); + enderChestInventory = std::shared_ptr( + new PlayerEnderChestContainer()); - m_bAwardedOnARail=false; + m_bAwardedOnARail = false; } -Player::Player(Level *level) : Mob( level ) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); +Player::Player(Level* level) : Mob(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that the derived version of the function is called - health = getMaxHealth(); + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + health = getMaxHealth(); - _init(); - MemSect(11); - inventoryMenu = new InventoryMenu(inventory, !level->isClientSide, this); - MemSect(0); + _init(); + MemSect(11); + inventoryMenu = new InventoryMenu(inventory, !level->isClientSide, this); + MemSect(0); - containerMenu = inventoryMenu; + containerMenu = inventoryMenu; - heightOffset = 1.62f; - Pos *spawnPos = level->getSharedSpawnPos(); - this->moveTo(spawnPos->x + 0.5, spawnPos->y + 1, spawnPos->z + 0.5, 0, 0); - delete spawnPos; + heightOffset = 1.62f; + Pos* spawnPos = level->getSharedSpawnPos(); + this->moveTo(spawnPos->x + 0.5, spawnPos->y + 1, spawnPos->z + 0.5, 0, 0); + delete spawnPos; - modelName = L"humanoid"; - rotOffs = 180; - flameTime = 20; + modelName = L"humanoid"; + rotOffs = 180; + flameTime = 20; - textureIdx = TN_MOB_CHAR; // 4J - was L"/mob/char.png"; - m_skinIndex = eDefaultSkins_Skin0; - m_playerIndex = 0; - m_dwSkinId = 0; - m_dwCapeId = 0; + textureIdx = TN_MOB_CHAR; // 4J - was L"/mob/char.png"; + m_skinIndex = eDefaultSkins_Skin0; + m_playerIndex = 0; + m_dwSkinId = 0; + m_dwCapeId = 0; - // 4J Added - m_xuid = INVALID_XUID; - m_OnlineXuid = INVALID_XUID; - //m_bShownOnMaps = true; - setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); - m_bIsGuest = false; - m_UUID = L""; + // 4J Added + m_xuid = INVALID_XUID; + m_OnlineXuid = INVALID_XUID; + // m_bShownOnMaps = true; + setShowOnMaps( + app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false); + m_bIsGuest = false; + m_UUID = L""; } -Player::~Player() -{ - // TODO 4J - //printf("A player has been destroyed.\n"); - delete inventoryMenu; +Player::~Player() { + // TODO 4J + // printf("A player has been destroyed.\n"); + delete inventoryMenu; - // 4J Stu - Fix for #10938 - CRASH - Game hardlocks when client has an open chest and Xbox Guide while host exits without saving. - // If the container menu is not the inventory menu, then the player has a menu open. These get deleted when the xui scene - // is destroyed, so we can not delete it here - //if( containerMenu != inventoryMenu ) delete containerMenu; + // 4J Stu - Fix for #10938 - CRASH - Game hardlocks when client has an open + // chest and Xbox Guide while host exits without saving. If the container + // menu is not the inventory menu, then the player has a menu open. These + // get deleted when the xui scene is destroyed, so we can not delete it here + // if( containerMenu != inventoryMenu ) delete containerMenu; } -int Player::getMaxHealth() -{ - return MAX_HEALTH; +int Player::getMaxHealth() { return MAX_HEALTH; } + +void Player::defineSynchedData() { + this->Mob::defineSynchedData(); + + entityData->define(DATA_PLAYER_FLAGS_ID, (std::uint8_t)0); + entityData->define(DATA_PLAYER_RUNNING_ID, (std::uint8_t)0); } -void Player::defineSynchedData() -{ - this->Mob::defineSynchedData(); +std::shared_ptr Player::getUseItem() { return useItem; } - entityData->define(DATA_PLAYER_FLAGS_ID, (std::uint8_t) 0); - entityData->define(DATA_PLAYER_RUNNING_ID, (std::uint8_t) 0); +int Player::getUseItemDuration() { return useItemDuration; } + +bool Player::isUsingItem() { return useItem != NULL; } + +int Player::getTicksUsingItem() { + if (isUsingItem()) { + return useItem->getUseDuration() - useItemDuration; + } + return 0; } -std::shared_ptr Player::getUseItem() -{ - return useItem; +void Player::releaseUsingItem() { + if (useItem != NULL) { + useItem->releaseUsing( + level, std::dynamic_pointer_cast(shared_from_this()), + useItemDuration); + + // 4J Stu - Fix for various bugs where an incorrect bow was displayed + // when it broke (#70859,#93972,#93974) + if (useItem->count == 0) { + removeSelectedItem(); + } + } + stopUsingItem(); } -int Player::getUseItemDuration() -{ - return useItemDuration; +void Player::stopUsingItem() { + useItem = nullptr; + useItemDuration = 0; + if (!level->isClientSide) { + setUsingItemFlag(false); + } } -bool Player::isUsingItem() -{ - return useItem != NULL; +bool Player::isBlocking() { + return isUsingItem() && + Item::items[useItem->id]->getUseAnimation(useItem) == UseAnim_block; } -int Player::getTicksUsingItem() -{ - if (isUsingItem()) - { - return useItem->getUseDuration() - useItemDuration; - } - return 0; -} +void Player::tick() { + if (useItem != NULL) { + std::shared_ptr item = inventory->getSelected(); + // 4J Stu - Fix for #45508 - TU5: Gameplay: Eating one piece of food + // will result in a second piece being eaten as well Original code was + // item != useItem. Changed this now to use the equals function, and add + // the NULL check as well for the other possible not equals (useItem is + // not NULL if we are here) This is because the useItem and item could + // be different objects due to an inventory update from the server, but + // still be the same item (with the same id,count and auxvalue) + if (item == NULL || !item->equals(useItem)) { + stopUsingItem(); + } else { + if (useItemDuration <= 25 && useItemDuration % 4 == 0) { + spawnEatParticles(item, 5); + } + if (--useItemDuration == 0) { + if (!level->isClientSide) { + completeUsingItem(); + } + } + } + } -void Player::releaseUsingItem() -{ - if (useItem != NULL) - { - useItem->releaseUsing(level, std::dynamic_pointer_cast( shared_from_this() ), useItemDuration); + if (takeXpDelay > 0) takeXpDelay--; - // 4J Stu - Fix for various bugs where an incorrect bow was displayed when it broke (#70859,#93972,#93974) - if (useItem->count == 0) - { - removeSelectedItem(); - } - } - stopUsingItem(); -} + if (isSleeping()) { + sleepCounter++; + if (sleepCounter > SLEEP_DURATION) { + sleepCounter = SLEEP_DURATION; + } -void Player::stopUsingItem() -{ - useItem = nullptr; - useItemDuration = 0; - if (!level->isClientSide) - { - setUsingItemFlag(false); - } -} + if (!level->isClientSide) { + if (!checkBed()) { + stopSleepInBed(true, true, false); + } else if (level->isDay()) { + stopSleepInBed(false, true, true); + } + } + } else if (sleepCounter > 0) { + sleepCounter++; + if (sleepCounter >= (SLEEP_DURATION + WAKE_UP_DURATION)) { + sleepCounter = 0; + } + } -bool Player::isBlocking() -{ - return isUsingItem() && Item::items[useItem->id]->getUseAnimation(useItem) == UseAnim_block; -} + if (!isAlive()) { + deathFadeCounter++; + if (deathFadeCounter > DEATHFADE_DURATION) { + deathFadeCounter = DEATHFADE_DURATION; + } + } + this->Mob::tick(); + if (!level->isClientSide) { + if (containerMenu != NULL && + !containerMenu->stillValid( + std::dynamic_pointer_cast(shared_from_this()))) { + closeContainer(); + containerMenu = inventoryMenu; + } + } -void Player::tick() -{ - if (useItem != NULL) - { - std::shared_ptr item = inventory->getSelected(); - // 4J Stu - Fix for #45508 - TU5: Gameplay: Eating one piece of food will result in a second piece being eaten as well - // Original code was item != useItem. Changed this now to use the equals function, and add the NULL check as well for the other possible not equals (useItem is not NULL if we are here) - // This is because the useItem and item could be different objects due to an inventory update from the server, but still be the same item (with the same id,count and auxvalue) - if (item == NULL || !item->equals(useItem) ) - { - stopUsingItem(); - } - else - { - if (useItemDuration <= 25 && useItemDuration % 4 == 0) - { - spawnEatParticles(item, 5); - } - if (--useItemDuration == 0) - { - if (!level->isClientSide) - { - completeUsingItem(); - } - } - } - } + if (isOnFire() && (abilities.invulnerable || hasInvulnerablePrivilege())) { + clearFire(); + } - if (takeXpDelay > 0) takeXpDelay--; + xCloakO = xCloak; + yCloakO = yCloak; + zCloakO = zCloak; - if (isSleeping()) - { - sleepCounter++; - if (sleepCounter > SLEEP_DURATION) - { - sleepCounter = SLEEP_DURATION; - } + double xca = x - xCloak; + double yca = y - yCloak; + double zca = z - zCloak; - if (!level->isClientSide) - { - if (!checkBed()) - { - stopSleepInBed(true, true, false); - } - else if (level->isDay()) - { - stopSleepInBed(false, true, true); - } - } - } - else if (sleepCounter > 0) - { - sleepCounter++; - if (sleepCounter >= (SLEEP_DURATION + WAKE_UP_DURATION)) - { - sleepCounter = 0; - } - } + double m = 10; + if (xca > m) xCloakO = xCloak = x; + if (zca > m) zCloakO = zCloak = z; + if (yca > m) yCloakO = yCloak = y; + if (xca < -m) xCloakO = xCloak = x; + if (zca < -m) zCloakO = zCloak = z; + if (yca < -m) yCloakO = yCloak = y; - if(!isAlive()) - { - deathFadeCounter++; - if (deathFadeCounter > DEATHFADE_DURATION) - { - deathFadeCounter = DEATHFADE_DURATION; - } - } - this->Mob::tick(); + xCloak += xca * 0.25; + zCloak += zca * 0.25; + yCloak += yca * 0.25; - if (!level->isClientSide) - { - if (containerMenu != NULL && !containerMenu->stillValid( std::dynamic_pointer_cast( shared_from_this() ) )) - { - closeContainer(); - containerMenu = inventoryMenu; - } - } + if (riding == NULL) { + if (minecartAchievementPos != NULL) { + delete minecartAchievementPos; + minecartAchievementPos = NULL; + } + } - if (isOnFire() && (abilities.invulnerable || hasInvulnerablePrivilege() ) ) - { - clearFire(); - } + if (!level->isClientSide) { + foodData.tick(std::dynamic_pointer_cast(shared_from_this())); + } - xCloakO = xCloak; - yCloakO = yCloak; - zCloakO = zCloak; - - double xca = x - xCloak; - double yca = y - yCloak; - double zca = z - zCloak; - - double m = 10; - if (xca > m) xCloakO = xCloak = x; - if (zca > m) zCloakO = zCloak = z; - if (yca > m) yCloakO = yCloak = y; - if (xca < -m) xCloakO = xCloak = x; - if (zca < -m) zCloakO = zCloak = z; - if (yca < -m) yCloakO = yCloak = y; - - xCloak += xca * 0.25; - zCloak += zca * 0.25; - yCloak += yca * 0.25; - - if (riding == NULL) - { - if( minecartAchievementPos != NULL ) - { - delete minecartAchievementPos; - minecartAchievementPos = NULL; - } - } - - if (!level->isClientSide) - { - foodData.tick(std::dynamic_pointer_cast(shared_from_this())); - } - - // 4J Stu Debugging - if (!level->isClientSide) - { - static int count = 0; - if( count++ == 100 ) - { + // 4J Stu Debugging + if (!level->isClientSide) { + static int count = 0; + if (count++ == 100) { #if 0 #ifdef _WINDOWS64 // Drop some items so we have them in inventory to play with @@ -395,60 +349,70 @@ void Player::tick() this->drop( std::shared_ptr(new ItemInstance( Item::pickAxe_diamond, 1 )) ); #endif #endif - // 4J-PB - Throw items out at the start of the level - //this->drop( new ItemInstance( Item::pickAxe_diamond, 1 ) ); - //this->drop( new ItemInstance( Tile::workBench, 1 ) ); - //this->drop( new ItemInstance( Tile::treeTrunk, 8 ) ); - //this->drop( std::shared_ptr( new ItemInstance( Item::milk, 3 ) ) ); - //this->drop( std::shared_ptr( new ItemInstance( Item::sugar, 2 ) ) ); - //this->drop( new ItemInstance( Tile::stoneBrick, 8 ) ); - //this->drop( std::shared_ptr( new ItemInstance( Item::wheat, 3 ) ) ); - //this->drop( std::shared_ptr( new ItemInstance( Item::egg, 1 ) ) ); - //this->drop( new ItemInstance( Item::bow, 1 ) ); - //this->drop( new ItemInstance( Item::arrow, 10 ) ); - //this->drop( std::shared_ptr( new ItemInstance( Item::saddle, 10 ) ) ); - //this->drop( std::shared_ptr( new ItemInstance( Tile::fence, 64 ) ) ); - //this->drop( std::shared_ptr( new ItemInstance( Tile::fence, 64 ) ) ); - //this->drop( std::shared_ptr( new ItemInstance( Tile::fence, 64 ) ) ); + // 4J-PB - Throw items out at the start of the level + // this->drop( new ItemInstance( Item::pickAxe_diamond, 1 ) ); + // this->drop( new ItemInstance( Tile::workBench, 1 ) ); + // this->drop( new ItemInstance( Tile::treeTrunk, 8 ) ); + // this->drop( std::shared_ptr( new ItemInstance( + // Item::milk, 3 ) ) ); this->drop( std::shared_ptr( + // new ItemInstance( Item::sugar, 2 ) ) ); this->drop( new + // ItemInstance( Tile::stoneBrick, 8 ) ); this->drop( + // std::shared_ptr( new ItemInstance( Item::wheat, 3 ) + // ) ); this->drop( std::shared_ptr( new ItemInstance( + // Item::egg, 1 ) ) ); this->drop( new ItemInstance( Item::bow, 1 ) + // ); this->drop( new ItemInstance( Item::arrow, 10 ) ); this->drop( + // std::shared_ptr( new ItemInstance( Item::saddle, 10 + // ) ) ); this->drop( std::shared_ptr( new + // ItemInstance( Tile::fence, 64 ) ) ); this->drop( + // std::shared_ptr( new ItemInstance( Tile::fence, 64 + // ) ) ); this->drop( std::shared_ptr( new + // ItemInstance( Tile::fence, 64 ) ) ); + // std::shared_ptr mob = + // std::dynamic_pointer_cast(Pig::_class->newInstance( level + // )); mob->moveTo(x+1, y, z+1, level->random->nextFloat() * 360, + // 0); level->addEntity(mob); - //std::shared_ptr mob = std::dynamic_pointer_cast(Pig::_class->newInstance( level )); - //mob->moveTo(x+1, y, z+1, level->random->nextFloat() * 360, 0); - //level->addEntity(mob); + // 4J : WESTY : Spawn some wolves to befriend! + /* + std::shared_ptr mob1 = + std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); + mob1->moveTo(x+1, y, z+1, level->random->nextFloat() * 360, 0); + level->addEntity(mob1); - // 4J : WESTY : Spawn some wolves to befriend! - /* - std::shared_ptr mob1 = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - mob1->moveTo(x+1, y, z+1, level->random->nextFloat() * 360, 0); - level->addEntity(mob1); + std::shared_ptr mob2 = + std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); + mob2->moveTo(x+2, y, z+1, level->random->nextFloat() * 360, 0); + level->addEntity(mob2); - std::shared_ptr mob2 = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - mob2->moveTo(x+2, y, z+1, level->random->nextFloat() * 360, 0); - level->addEntity(mob2); + std::shared_ptr mob3 = + std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); + mob3->moveTo(x+1, y, z+2, level->random->nextFloat() * 360, 0); + level->addEntity(mob3); - std::shared_ptr mob3 = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - mob3->moveTo(x+1, y, z+2, level->random->nextFloat() * 360, 0); - level->addEntity(mob3); + std::shared_ptr mob4 = + std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); + mob4->moveTo(x+3, y, z+1, level->random->nextFloat() * 360, 0); + level->addEntity(mob4); - std::shared_ptr mob4 = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - mob4->moveTo(x+3, y, z+1, level->random->nextFloat() * 360, 0); - level->addEntity(mob4); + std::shared_ptr mob5 = + std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); + mob5->moveTo(x+1, y, z+3, level->random->nextFloat() * 360, 0); + level->addEntity(mob5); + */ - std::shared_ptr mob5 = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - mob5->moveTo(x+1, y, z+3, level->random->nextFloat() * 360, 0); - level->addEntity(mob5); - */ + // inventory.add(new ItemInstance(Item.potion, 1, + // PotionBrewing.THROWABLE_MASK | 0xc)); addEffect(new + // MobEffectInstance(MobEffect.blindness.id, 60)); + // increaseXp(10); - // inventory.add(new ItemInstance(Item.potion, 1, PotionBrewing.THROWABLE_MASK | 0xc)); - // addEffect(new MobEffectInstance(MobEffect.blindness.id, 60)); - // increaseXp(10); - - { - // ItemInstance itemInstance = new ItemInstance(Item.pickAxe_diamond); - // itemInstance.enchant(Enchantment.diggingBonus, 3); - // inventory.add(itemInstance); - } - } + { + // ItemInstance itemInstance = new + // ItemInstance(Item.pickAxe_diamond); + // itemInstance.enchant(Enchantment.diggingBonus, 3); + // inventory.add(itemInstance); + } + } #if 0 // 4J Stu - This makes a tunnel with a powered track just over length to get the On A Rail achievement // It needs a few items at the start to get you going (a level and some powered rails) and of course a @@ -520,2496 +484,2205 @@ void Player::tick() madeTrack = true; } #endif - } - //End 4J sTU + } + // End 4J sTU } -void Player::spawnEatParticles(std::shared_ptr useItem, int count) -{ - if (useItem->getUseAnimation() == UseAnim_drink) - { - level->playSound(shared_from_this(), eSoundType_RANDOM_DRINK, 0.5f, level->random->nextFloat() * 0.1f + 0.9f); - } - if (useItem->getUseAnimation() == UseAnim_eat) - { - for (int i = 0; i < count; i++) - { - Vec3 *d = Vec3::newTemp((random->nextFloat() - 0.5) * 0.1, Math::random() * 0.1 + 0.1, 0); +void Player::spawnEatParticles(std::shared_ptr useItem, + int count) { + if (useItem->getUseAnimation() == UseAnim_drink) { + level->playSound(shared_from_this(), eSoundType_RANDOM_DRINK, 0.5f, + level->random->nextFloat() * 0.1f + 0.9f); + } + if (useItem->getUseAnimation() == UseAnim_eat) { + for (int i = 0; i < count; i++) { + Vec3* d = Vec3::newTemp((random->nextFloat() - 0.5) * 0.1, + Math::random() * 0.1 + 0.1, 0); - d->xRot(-xRot * PI / 180); - d->yRot(-yRot * PI / 180); + d->xRot(-xRot * PI / 180); + d->yRot(-yRot * PI / 180); - Vec3 *p = Vec3::newTemp((random->nextFloat() - 0.5) * 0.3, -random->nextFloat() * 0.6 - 0.3, 0.6); - p->xRot(-xRot * PI / 180); - p->yRot(-yRot * PI / 180); - p = p->add(x, y + getHeadHeight(), z); + Vec3* p = Vec3::newTemp((random->nextFloat() - 0.5) * 0.3, + -random->nextFloat() * 0.6 - 0.3, 0.6); + p->xRot(-xRot * PI / 180); + p->yRot(-yRot * PI / 180); + p = p->add(x, y + getHeadHeight(), z); - level->addParticle(PARTICLE_ICONCRACK(useItem->getItem()->id,0), p->x, p->y, p->z, d->x, d->y + 0.05, d->z); - } + level->addParticle(PARTICLE_ICONCRACK(useItem->getItem()->id, 0), + p->x, p->y, p->z, d->x, d->y + 0.05, d->z); + } - // 4J Stu - Was L"mob.eat" which doesnt exist - level->playSound(shared_from_this(), eSoundType_RANDOM_EAT, 0.5f + 0.5f * random->nextInt(2), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - } + // 4J Stu - Was L"mob.eat" which doesnt exist + level->playSound( + shared_from_this(), eSoundType_RANDOM_EAT, + 0.5f + 0.5f * random->nextInt(2), + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + } } -void Player::completeUsingItem() -{ - if (useItem != NULL) - { - spawnEatParticles(useItem, 16); +void Player::completeUsingItem() { + if (useItem != NULL) { + spawnEatParticles(useItem, 16); - int oldCount = useItem->count; - std::shared_ptr itemInstance = useItem->useTimeDepleted(level, std::dynamic_pointer_cast(shared_from_this())); - if (itemInstance != useItem || (itemInstance != NULL && itemInstance->count != oldCount)) - { - inventory->items[inventory->selected] = itemInstance; - if (itemInstance->count == 0) - { - inventory->items[inventory->selected] = nullptr; - } - } - stopUsingItem(); - } + int oldCount = useItem->count; + std::shared_ptr itemInstance = useItem->useTimeDepleted( + level, std::dynamic_pointer_cast(shared_from_this())); + if (itemInstance != useItem || + (itemInstance != NULL && itemInstance->count != oldCount)) { + inventory->items[inventory->selected] = itemInstance; + if (itemInstance->count == 0) { + inventory->items[inventory->selected] = nullptr; + } + } + stopUsingItem(); + } } -void Player::handleEntityEvent(std::uint8_t id) -{ - if (id == EntityEvent::USE_ITEM_COMPLETE) - { - completeUsingItem(); - } - else - { - Mob::handleEntityEvent(id); - } +void Player::handleEntityEvent(std::uint8_t id) { + if (id == EntityEvent::USE_ITEM_COMPLETE) { + completeUsingItem(); + } else { + Mob::handleEntityEvent(id); + } } -bool Player::isImmobile() -{ - return getHealth() <= 0 || isSleeping(); +bool Player::isImmobile() { return getHealth() <= 0 || isSleeping(); } + +void Player::closeContainer() { containerMenu = inventoryMenu; } + +void Player::ride(std::shared_ptr e) { + if (riding != NULL && e == NULL) { + if (!level->isClientSide) findStandUpPosition(riding); + + if (riding != NULL) { + riding->rider = std::weak_ptr(); + } + riding = nullptr; + + return; + } + Mob::ride(e); } - -void Player::closeContainer() -{ - containerMenu = inventoryMenu; -} - -void Player::ride(std::shared_ptr e) -{ - if (riding != NULL && e == NULL) - { - if (!level->isClientSide) findStandUpPosition(riding); - - if (riding != NULL) - { - riding->rider = std::weak_ptr(); - } - riding = nullptr; - - return; - } - Mob::ride(e); -} - -void Player::setPlayerDefaultSkin(EDefaultSkins skin) -{ +void Player::setPlayerDefaultSkin(EDefaultSkins skin) { #ifndef _CONTENT_PACKAGE - wprintf(L"Setting default skin to %d for player %ls\n", skin, name.c_str() ); + wprintf(L"Setting default skin to %d for player %ls\n", skin, name.c_str()); #endif - m_skinIndex = skin; + m_skinIndex = skin; } -void Player::setCustomSkin(std::uint32_t skinId) -{ +void Player::setCustomSkin(std::uint32_t skinId) { #ifndef _CONTENT_PACKAGE - wprintf(L"Attempting to set skin to %08X for player %ls\n", skinId, name.c_str() ); + wprintf(L"Attempting to set skin to %08X for player %ls\n", skinId, + name.c_str()); #endif - EDefaultSkins playerSkin = eDefaultSkins_ServerSelected; + EDefaultSkins playerSkin = eDefaultSkins_ServerSelected; - // reset the idle - setIsIdle(false); + // reset the idle + setIsIdle(false); - setAnimOverrideBitmask(getSkinAnimOverrideBitmask(skinId)); - if( !GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { - // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a possible custom skin editor skin - std::uint32_t ugcSkinIndex = GET_UGC_SKIN_ID_FROM_BITMASK(skinId); - std::uint32_t defaultSkinIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(skinId); - if( ugcSkinIndex == 0 && defaultSkinIndex > 0 ) - { - playerSkin = (EDefaultSkins) defaultSkinIndex; - } - } + setAnimOverrideBitmask(getSkinAnimOverrideBitmask(skinId)); + if (!GET_IS_DLC_SKIN_FROM_BITMASK(skinId)) { + // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a + // possible custom skin editor skin + std::uint32_t ugcSkinIndex = GET_UGC_SKIN_ID_FROM_BITMASK(skinId); + std::uint32_t defaultSkinIndex = + GET_DEFAULT_SKIN_ID_FROM_BITMASK(skinId); + if (ugcSkinIndex == 0 && defaultSkinIndex > 0) { + playerSkin = (EDefaultSkins)defaultSkinIndex; + } + } - if( playerSkin == eDefaultSkins_ServerSelected) - { - playerSkin = (EDefaultSkins)(m_playerIndex + 1); - } + if (playerSkin == eDefaultSkins_ServerSelected) { + playerSkin = (EDefaultSkins)(m_playerIndex + 1); + } - // We always set a default skin, since we may be waiting for the player's custom skin to be transmitted - setPlayerDefaultSkin( playerSkin ); + // We always set a default skin, since we may be waiting for the player's + // custom skin to be transmitted + setPlayerDefaultSkin(playerSkin); - m_dwSkinId = skinId; - this->customTextureUrl = app.getSkinPathFromId(skinId); + m_dwSkinId = skinId; + this->customTextureUrl = app.getSkinPathFromId(skinId); - // set the new player additional boxes - /*std::vector *pvModelParts=app.GetAdditionalModelParts(m_dwSkinId); + // set the new player additional boxes + /*std::vector + *pvModelParts=app.GetAdditionalModelParts(m_dwSkinId); - if(pvModelParts==NULL) - { - // we don't have the data from the dlc skin yet - app.DebugPrintf("Couldn't get model parts for skin %X\n",m_dwSkinId); + if(pvModelParts==NULL) + { + // we don't have the data from the dlc skin yet + app.DebugPrintf("Couldn't get model parts for skin %X\n",m_dwSkinId); - // do we have it from the DLC pack? - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(this->customTextureUrl); + // do we have it from the DLC pack? + DLCSkinFile *pDLCSkinFile = + app.m_dlcManager.getSkinFile(this->customTextureUrl); - if(pDLCSkinFile!=NULL) - { - const int additionalBoxCount = pDLCSkinFile->getAdditionalBoxesCount(); - if(additionalBoxCount != 0) - { - app.DebugPrintf("Got model parts from DLCskin for skin %X\n",m_dwSkinId); - pvModelParts=app.SetAdditionalSkinBoxes(m_dwSkinId,pDLCSkinFile->getAdditionalBoxes()); - this->SetAdditionalModelParts(pvModelParts); - } - else - { - this->SetAdditionalModelParts(NULL); - } - app.SetAnimOverrideBitmask(pDLCSkinFile->getSkinID(),pDLCSkinFile->getAnimOverrideBitmask()); - } - else - { - this->SetAdditionalModelParts(NULL); - } - } - else - { - app.DebugPrintf("Got model parts from app.GetAdditionalModelParts for skin %X\n",m_dwSkinId); - - this->SetAdditionalModelParts(pvModelParts); - }*/ - - // reset the check for model parts - m_bCheckedForModelParts=false; - m_bCheckedDLCForModelParts=false; - this->SetAdditionalModelParts(NULL); + if(pDLCSkinFile!=NULL) + { + const int additionalBoxCount = + pDLCSkinFile->getAdditionalBoxesCount(); if(additionalBoxCount != 0) + { + app.DebugPrintf("Got model parts from DLCskin for skin %X\n",m_dwSkinId); + pvModelParts=app.SetAdditionalSkinBoxes(m_dwSkinId,pDLCSkinFile->getAdditionalBoxes()); + this->SetAdditionalModelParts(pvModelParts); + } + else + { + this->SetAdditionalModelParts(NULL); + } + app.SetAnimOverrideBitmask(pDLCSkinFile->getSkinID(),pDLCSkinFile->getAnimOverrideBitmask()); + } + else + { + this->SetAdditionalModelParts(NULL); + } + } + else + { + app.DebugPrintf("Got model parts from app.GetAdditionalModelParts for skin + %X\n",m_dwSkinId); + this->SetAdditionalModelParts(pvModelParts); + }*/ + // reset the check for model parts + m_bCheckedForModelParts = false; + m_bCheckedDLCForModelParts = false; + this->SetAdditionalModelParts(NULL); } -unsigned int Player::getSkinAnimOverrideBitmask(std::uint32_t skinId) -{ - unsigned long bitmask = 0L; - if( GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { - // Temp check for anim override - switch( GET_DLC_SKIN_ID_FROM_BITMASK(skinId) ) - { - case 0x2://SP1_ZOMBIE: - case 0x3://SP1_HEROBRINE: - case 0xc8://SP3_ZOMBIE_PIGMAN: - case 0xc9://SP3_ZOMBIE_HEROBRINE: - case 0x1f8: // SPH_4JMUMMY - case 0x220: // SPH_AOT_MUMMY - case 0x23a: // SPH_CLIMAX_ZOMBIEBUSINESSMAN - case 0x23d: // SPH_CLIMAX_EVILROBOT - case 0x247: // SPH_CLIMAX_ZOMBIE - case 0x194: // SOA_DEADLIGHT_SKINNY_ZOMBIE - case 0x195: // SOA_DEADLIGHT_FEMALE_ZOMBIE - bitmask = 1< 0) - { - this->customTextureUrl2 = Player::getCapePathFromId(capeId); - } - else - { - MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) - { - // Cape - if(pMojangData->wchCape[0] != 0) - { - this->customTextureUrl2= pMojangData->wchCape; - } - else - { - if(app.DefaultCapeExists()) - { - this->customTextureUrl2= std::wstring(L"Special_Cape.png"); - } - else - { - this->customTextureUrl2= std::wstring(L""); - } - } + if (capeId > 0) { + this->customTextureUrl2 = Player::getCapePathFromId(capeId); + } else { + MOJANG_DATA* pMojangData = app.GetMojangDataForXuid(getOnlineXuid()); + if (pMojangData) { + // Cape + if (pMojangData->wchCape[0] != 0) { + this->customTextureUrl2 = pMojangData->wchCape; + } else { + if (app.DefaultCapeExists()) { + this->customTextureUrl2 = std::wstring(L"Special_Cape.png"); + } else { + this->customTextureUrl2 = std::wstring(L""); + } + } - } - else - { - // if there is a custom default cloak, then set it here - if(app.DefaultCapeExists()) - { - this->customTextureUrl2= std::wstring(L"Special_Cape.png"); - } - else - { - this->customTextureUrl2 =std::wstring(L""); - } - } - } + } else { + // if there is a custom default cloak, then set it here + if (app.DefaultCapeExists()) { + this->customTextureUrl2 = std::wstring(L"Special_Cape.png"); + } else { + this->customTextureUrl2 = std::wstring(L""); + } + } + } } -std::uint32_t Player::getCapeIdFromPath(const std::wstring &cape) -{ - bool dlcCape = false; - std::uint32_t capeId = 0; +std::uint32_t Player::getCapeIdFromPath(const std::wstring& cape) { + bool dlcCape = false; + std::uint32_t capeId = 0; - if(cape.size() >= 14) - { - dlcCape = cape.substr(0,3).compare(L"dlc") == 0; + if (cape.size() >= 14) { + dlcCape = cape.substr(0, 3).compare(L"dlc") == 0; - std::wstring capeValue = cape.substr(7,cape.size()); - capeValue = capeValue.substr(0,capeValue.find_first_of(L'.')); + std::wstring capeValue = cape.substr(7, cape.size()); + capeValue = capeValue.substr(0, capeValue.find_first_of(L'.')); - std::wstringstream ss; - // 4J Stu - dlc skins are numbered using decimal to make it easier for artists/people to number manually - // Everything else is numbered using hex - if(dlcCape) - ss << std::dec << capeValue.c_str(); - else - ss << std::hex << capeValue.c_str(); - ss >> capeId; + std::wstringstream ss; + // 4J Stu - dlc skins are numbered using decimal to make it easier for + // artists/people to number manually Everything else is numbered using + // hex + if (dlcCape) + ss << std::dec << capeValue.c_str(); + else + ss << std::hex << capeValue.c_str(); + ss >> capeId; - capeId = MAKE_SKIN_BITMASK(dlcCape, capeId); - } - return capeId; + capeId = MAKE_SKIN_BITMASK(dlcCape, capeId); + } + return capeId; } -std::wstring Player::getCapePathFromId(std::uint32_t capeId) -{ - // 4J Stu - This function maps the encoded DWORD we store in the player profile - // to a filename that is stored as a memory texture and shared between systems in game - wchar_t chars[256]; - if( GET_IS_DLC_SKIN_FROM_BITMASK(capeId) ) - { - // 4J Stu - DLC skins are numbered using decimal rather than hex to make it easier to number manually - swprintf(chars,256,L"dlccape%08d.png",GET_DLC_SKIN_ID_FROM_BITMASK(capeId)); +std::wstring Player::getCapePathFromId(std::uint32_t capeId) { + // 4J Stu - This function maps the encoded DWORD we store in the player + // profile to a filename that is stored as a memory texture and shared + // between systems in game + wchar_t chars[256]; + if (GET_IS_DLC_SKIN_FROM_BITMASK(capeId)) { + // 4J Stu - DLC skins are numbered using decimal rather than hex to make + // it easier to number manually + swprintf(chars, 256, L"dlccape%08d.png", + GET_DLC_SKIN_ID_FROM_BITMASK(capeId)); - } - else - { - std::uint32_t ugcCapeIndex = GET_UGC_SKIN_ID_FROM_BITMASK(capeId); - std::uint32_t defaultCapeIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(capeId); - if( ugcCapeIndex == 0 ) - { - swprintf(chars,256,L"defcape%08X.png",defaultCapeIndex); - } - else - { - swprintf(chars,256,L"ugccape%08X.png",ugcCapeIndex); - } - } - return chars; + } else { + std::uint32_t ugcCapeIndex = GET_UGC_SKIN_ID_FROM_BITMASK(capeId); + std::uint32_t defaultCapeIndex = + GET_DEFAULT_SKIN_ID_FROM_BITMASK(capeId); + if (ugcCapeIndex == 0) { + swprintf(chars, 256, L"defcape%08X.png", defaultCapeIndex); + } else { + swprintf(chars, 256, L"ugccape%08X.png", ugcCapeIndex); + } + } + return chars; } -void Player::ChangePlayerSkin() -{ - - if(app.vSkinNames.size()>0) - { - - m_uiPlayerCurrentSkin++; - if(m_uiPlayerCurrentSkin>app.vSkinNames.size()) - { - m_uiPlayerCurrentSkin=0; - this->customTextureUrl=L""; - } - else - { - if(m_uiPlayerCurrentSkin>0) - { - // change this players custom texture url - this->customTextureUrl=app.vSkinNames[m_uiPlayerCurrentSkin-1]; - } - } - } +void Player::ChangePlayerSkin() { + if (app.vSkinNames.size() > 0) { + m_uiPlayerCurrentSkin++; + if (m_uiPlayerCurrentSkin > app.vSkinNames.size()) { + m_uiPlayerCurrentSkin = 0; + this->customTextureUrl = L""; + } else { + if (m_uiPlayerCurrentSkin > 0) { + // change this players custom texture url + this->customTextureUrl = + app.vSkinNames[m_uiPlayerCurrentSkin - 1]; + } + } + } } -void Player::prepareCustomTextures() -{ - MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); +void Player::prepareCustomTextures() { + MOJANG_DATA* pMojangData = app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) - { - // Skin - if(pMojangData->wchSkin[0] != 0) - { - this->customTextureUrl= pMojangData->wchSkin; - } + if (pMojangData) { + // Skin + if (pMojangData->wchSkin[0] != 0) { + this->customTextureUrl = pMojangData->wchSkin; + } - // 4J Stu - Don't update the cape here, it gets set elsewhere - // Cape - //if(pMojangData->wchCape) - //{ - // this->customTextureUrl2= pMojangData->wchCape; - //} - //else - //{ - // if(app.DefaultCapeExists()) - // { - // this->customTextureUrl2= std::wstring(L"Default_Cape.png"); - // } - // else - // { - // this->customTextureUrl2= std::wstring(L""); - // } - //} + // 4J Stu - Don't update the cape here, it gets set elsewhere + // Cape + // if(pMojangData->wchCape) + //{ + // this->customTextureUrl2= pMojangData->wchCape; + //} + // else + //{ + // if(app.DefaultCapeExists()) + // { + // this->customTextureUrl2= + //std::wstring(L"Default_Cape.png"); + // } + // else + // { + // this->customTextureUrl2= std::wstring(L""); + // } + //} - } - else - { - // 4J Stu - Don't update the cape here, it gets set elsewhere - // if there is a custom default cloak, then set it here - //if(app.DefaultCapeExists()) - //{ - // this->customTextureUrl2= std::wstring(L"Default_Cape.png"); - //} - //else - //{ - // this->customTextureUrl2 =std::wstring(L""); - //} - } + } else { + // 4J Stu - Don't update the cape here, it gets set elsewhere + // if there is a custom default cloak, then set it here + // if(app.DefaultCapeExists()) + //{ + // this->customTextureUrl2= std::wstring(L"Default_Cape.png"); + //} + // else + //{ + // this->customTextureUrl2 =std::wstring(L""); + //} + } - /*cloakTexture = std::wstring(L"http://s3.amazonaws.com/MinecraftCloaks/").append( name ).append( L".png" );*/ - //this->customTextureUrl2 = cloakTexture; + /*cloakTexture = + * std::wstring(L"http://s3.amazonaws.com/MinecraftCloaks/").append( name + * ).append( L".png" );*/ + // this->customTextureUrl2 = cloakTexture; } -void Player::rideTick() -{ - double preX = x, preY = y, preZ = z; - float preYRot = yRot, preXRot = xRot; +void Player::rideTick() { + double preX = x, preY = y, preZ = z; + float preYRot = yRot, preXRot = xRot; - this->Mob::rideTick(); - oBob = bob; - bob = 0; + this->Mob::rideTick(); + oBob = bob; + bob = 0; - checkRidingStatistiscs(x - preX, y - preY, z - preZ); + checkRidingStatistiscs(x - preX, y - preY, z - preZ); - // riding can be set to null inside 'Entity::rideTick()'. - if ( riding != NULL && (riding->GetType() & eTYPE_PIG) == eTYPE_PIG ) - { - // 4J Stu - I don't know why we would want to do this, but it means that the players head is locked in position and can't move around - //xRot = preXRot; - //yRot = preYRot; + // riding can be set to null inside 'Entity::rideTick()'. + if (riding != NULL && (riding->GetType() & eTYPE_PIG) == eTYPE_PIG) { + // 4J Stu - I don't know why we would want to do this, but it means that + // the players head is locked in position and can't move around + // xRot = preXRot; + // yRot = preYRot; - std::shared_ptr pig = std::dynamic_pointer_cast(riding); - yBodyRot = pig->yBodyRot; + std::shared_ptr pig = std::dynamic_pointer_cast(riding); + yBodyRot = pig->yBodyRot; - while (yBodyRot - yBodyRotO < -180) - yBodyRotO -= 360; - while (yBodyRot - yBodyRotO >= 180) - yBodyRotO += 360; - } + while (yBodyRot - yBodyRotO < -180) yBodyRotO -= 360; + while (yBodyRot - yBodyRotO >= 180) yBodyRotO += 360; + } } - -void Player::resetPos() -{ - heightOffset = 1.62f; - setSize(0.6f, 1.8f); - this->Mob::resetPos(); - setHealth(getMaxHealth()); - deathTime = 0; +void Player::resetPos() { + heightOffset = 1.62f; + setSize(0.6f, 1.8f); + this->Mob::resetPos(); + setHealth(getMaxHealth()); + deathTime = 0; } -int Player::getCurrentSwingDuration() -{ - if (hasEffect(MobEffect::digSpeed)) - { - return SWING_DURATION - (1 + getEffect(MobEffect::digSpeed)->getAmplifier()) * 1; - } - if (hasEffect(MobEffect::digSlowdown)) - { - return SWING_DURATION + (1 + getEffect(MobEffect::digSlowdown)->getAmplifier()) * 2; - } - return SWING_DURATION; +int Player::getCurrentSwingDuration() { + if (hasEffect(MobEffect::digSpeed)) { + return SWING_DURATION - + (1 + getEffect(MobEffect::digSpeed)->getAmplifier()) * 1; + } + if (hasEffect(MobEffect::digSlowdown)) { + return SWING_DURATION + + (1 + getEffect(MobEffect::digSlowdown)->getAmplifier()) * 2; + } + return SWING_DURATION; } -void Player::serverAiStep() -{ - int currentSwingDuration = getCurrentSwingDuration(); - if (swinging) - { - swingTime++; - if (swingTime >= currentSwingDuration) - { - swingTime = 0; - swinging = false; - } - } - else - { - swingTime = 0; - } +void Player::serverAiStep() { + int currentSwingDuration = getCurrentSwingDuration(); + if (swinging) { + swingTime++; + if (swingTime >= currentSwingDuration) { + swingTime = 0; + swinging = false; + } + } else { + swingTime = 0; + } - attackAnim = swingTime / (float) currentSwingDuration; + attackAnim = swingTime / (float)currentSwingDuration; } +void Player::aiStep() { + if (jumpTriggerTime > 0) jumpTriggerTime--; -void Player::aiStep() -{ - if (jumpTriggerTime > 0) jumpTriggerTime--; + if (level->difficulty == Difficulty::PEACEFUL && + getHealth() < getMaxHealth()) { + if (tickCount % 20 * 12 == 0) heal(1); + } + inventory->tick(); + oBob = bob; - if (level->difficulty == Difficulty::PEACEFUL && getHealth() < getMaxHealth()) - { - if (tickCount % 20 * 12 == 0) heal(1); - } - inventory->tick(); - oBob = bob; + this->Mob::aiStep(); - this->Mob::aiStep(); + this->walkingSpeed = abilities.getWalkingSpeed(); + this->flyingSpeed = defaultFlySpeed; + if (isSprinting()) { + walkingSpeed += abilities.getWalkingSpeed() * 0.3f; + flyingSpeed += defaultFlySpeed * 0.3f; + } - this->walkingSpeed = abilities.getWalkingSpeed(); - this->flyingSpeed = defaultFlySpeed; - if (isSprinting()) - { - walkingSpeed += abilities.getWalkingSpeed() * 0.3f; - flyingSpeed += defaultFlySpeed * 0.3f; - } + float tBob = (float)sqrt(xd * xd + zd * zd); - float tBob = (float) sqrt(xd * xd + zd * zd); + // 4J added - we were getting a NaN with zero xd & zd + if ((xd * xd + zd * zd) < 0.00001f) { + tBob = 0.0f; + } - // 4J added - we were getting a NaN with zero xd & zd - if(( xd * xd + zd * zd ) < 0.00001f ) - { - tBob = 0.0f; - } + float tTilt = (float)atan(-yd * 0.2f) * 15.0f; + if (tBob > 0.1f) tBob = 0.1f; + if (!onGround || getHealth() <= 0) tBob = 0; + if (onGround || getHealth() <= 0) tTilt = 0; - float tTilt = (float) atan(-yd * 0.2f) * 15.0f; - if (tBob > 0.1f) tBob = 0.1f; - if (!onGround || getHealth() <= 0) tBob = 0; - if (onGround || getHealth() <= 0) tTilt = 0; + bob += (tBob - bob) * 0.4f; - bob += (tBob - bob) * 0.4f; + tilt += (tTilt - tilt) * 0.8f; - tilt += (tTilt - tilt) * 0.8f; - - if (getHealth() > 0) - { - std::vector > *entities = level->getEntities(shared_from_this(), bb->grow(1, 0, 1)); - if (entities != NULL) - { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //entities->at(i); - if (!e->removed) - { - touch(e); - } - } - } - } + if (getHealth() > 0) { + std::vector >* entities = + level->getEntities(shared_from_this(), bb->grow(1, 0, 1)); + if (entities != NULL) { + AUTO_VAR(itEnd, entities->end()); + for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // entities->at(i); + if (!e->removed) { + touch(e); + } + } + } + } } - -void Player::touch(std::shared_ptr entity) -{ - entity->playerTouch( std::dynamic_pointer_cast( shared_from_this() ) ); +void Player::touch(std::shared_ptr entity) { + entity->playerTouch(std::dynamic_pointer_cast(shared_from_this())); } // 4J - Removed 1.0.1 -//bool Player::addResource(int resource) +// bool Player::addResource(int resource) //{ -// return inventory->add(std::shared_ptr( new ItemInstance(resource, 1, 0) ) ); +// return inventory->add(std::shared_ptr( new +//ItemInstance(resource, 1, 0) ) ); //} -int Player::getScore() -{ - return score; +int Player::getScore() { return score; } + +void Player::die(DamageSource* source) { + this->Mob::die(source); + this->setSize(0.2f, 0.2f); + setPos(x, y, z); + yd = 0.1f; + + // 4J - TODO need to use a xuid + if (app.isXuidNotch(m_xuid)) { + drop(std::shared_ptr(new ItemInstance(Item::apple, 1)), + true); + } + inventory->dropAll(); + + if (source != NULL) { + xd = -Mth::cos((hurtDir + yRot) * PI / 180) * 0.1f; + zd = -Mth::sin((hurtDir + yRot) * PI / 180) * 0.1f; + } else { + xd = zd = 0; + } + this->heightOffset = 0.1f; } -void Player::die(DamageSource *source) -{ - this->Mob::die(source); - this->setSize(0.2f, 0.2f); - setPos(x, y, z); - yd = 0.1f; - - // 4J - TODO need to use a xuid - if ( app.isXuidNotch( m_xuid ) ) - { - drop(std::shared_ptr( new ItemInstance(Item::apple, 1) ), true); - } - inventory->dropAll(); - - if (source != NULL) - { - xd = -Mth::cos((hurtDir + yRot) * PI / 180) * 0.1f; - zd = -Mth::sin((hurtDir + yRot) * PI / 180) * 0.1f; - } - else - { - xd = zd = 0; - } - this->heightOffset = 0.1f; +void Player::awardKillScore(std::shared_ptr victim, int score) { + this->score += score; } -void Player::awardKillScore(std::shared_ptr victim, int score) -{ - this->score += score; +int Player::decreaseAirSupply(int currentSupply) { + int oxygenBonus = EnchantmentHelper::getOxygenBonus(inventory); + if (oxygenBonus > 0) { + if (random->nextInt(oxygenBonus + 1) > 0) { + // the oxygen bonus prevents us from drowning + return currentSupply; + } + } + return Mob::decreaseAirSupply(currentSupply); } -int Player::decreaseAirSupply(int currentSupply) -{ - int oxygenBonus = EnchantmentHelper::getOxygenBonus(inventory); - if (oxygenBonus > 0) - { - if (random->nextInt(oxygenBonus + 1) > 0) - { - // the oxygen bonus prevents us from drowning - return currentSupply; - } - } - return Mob::decreaseAirSupply(currentSupply); +bool Player::isShootable() { return true; } + +bool Player::isCreativeModeAllowed() { return true; } + +std::shared_ptr Player::drop() { + return drop(inventory->removeItem(inventory->selected, 1), false); } -bool Player::isShootable() -{ - return true; +std::shared_ptr Player::drop(std::shared_ptr item) { + return drop(item, false); } -bool Player::isCreativeModeAllowed() -{ - return true; +std::shared_ptr Player::drop(std::shared_ptr item, + bool randomly) { + if (item == NULL) return nullptr; + + std::shared_ptr thrownItem = std::shared_ptr( + new ItemEntity(level, x, y - 0.3f + getHeadHeight(), z, item)); + thrownItem->throwTime = 20 * 2; + + thrownItem->setThrower(getName()); + + float pow = 0.1f; + if (randomly) { + float _pow = random->nextFloat() * 0.5f; + float dir = random->nextFloat() * PI * 2; + thrownItem->xd = -sin(dir) * _pow; + thrownItem->zd = cos(dir) * _pow; + thrownItem->yd = 0.2f; + + } else { + pow = 0.3f; + thrownItem->xd = -sin(yRot / 180 * PI) * cos(xRot / 180 * PI) * pow; + thrownItem->zd = cos(yRot / 180 * PI) * cos(xRot / 180 * PI) * pow; + thrownItem->yd = -sin(xRot / 180 * PI) * pow + 0.1f; + pow = 0.02f; + + float dir = random->nextFloat() * PI * 2; + pow *= random->nextFloat(); + thrownItem->xd += cos(dir) * pow; + thrownItem->yd += (random->nextFloat() - random->nextFloat()) * 0.1f; + thrownItem->zd += sin(dir) * pow; + } + + reallyDrop(thrownItem); + + return thrownItem; } -std::shared_ptr Player::drop() -{ - return drop(inventory->removeItem(inventory->selected, 1), false); +void Player::reallyDrop(std::shared_ptr thrownItem) { + level->addEntity(thrownItem); } -std::shared_ptr Player::drop(std::shared_ptr item) -{ - return drop(item, false); +float Player::getDestroySpeed(Tile* tile) { + float speed = inventory->getDestroySpeed(tile); + + int efficiency = EnchantmentHelper::getDiggingBonus(inventory); + if (efficiency > 0 && inventory->canDestroy(tile)) { + speed += (efficiency * efficiency + 1); + } + + if (hasEffect(MobEffect::digSpeed)) { + speed *= + 1.0f + (getEffect(MobEffect::digSpeed)->getAmplifier() + 1) * .2f; + } + if (hasEffect(MobEffect::digSlowdown)) { + speed *= 1.0f - + (getEffect(MobEffect::digSlowdown)->getAmplifier() + 1) * .2f; + } + + if (isUnderLiquid(Material::water) && + !EnchantmentHelper::hasWaterWorkerBonus(inventory)) + speed /= 5; + + // 4J Stu - onGround is set to true on the client when we are flying, which + // means the dig speed is out of sync with the server. Removing this speed + // change when flying so that we always dig as the same speed + // if (!onGround) speed /= 5; + + return speed; } -std::shared_ptr Player::drop(std::shared_ptr item, bool randomly) -{ - if (item == NULL) return nullptr; +bool Player::canDestroy(Tile* tile) { return inventory->canDestroy(tile); } - std::shared_ptr thrownItem = std::shared_ptr( new ItemEntity(level, x, y - 0.3f + getHeadHeight(), z, item) ); - thrownItem->throwTime = 20 * 2; +void Player::readAdditionalSaveData(CompoundTag* entityTag) { + Mob::readAdditionalSaveData(entityTag); + ListTag* inventoryList = + (ListTag*)entityTag->getList(L"Inventory"); + inventory->load(inventoryList); + dimension = entityTag->getInt(L"Dimension"); + m_isSleeping = entityTag->getBoolean(L"Sleeping"); + sleepCounter = entityTag->getShort(L"SleepTimer"); - thrownItem->setThrower(getName()); + experienceProgress = entityTag->getFloat(L"XpP"); + experienceLevel = entityTag->getInt(L"XpLevel"); + totalExperience = entityTag->getInt(L"XpTotal"); - float pow = 0.1f; - if (randomly) - { - float _pow = random->nextFloat() * 0.5f; - float dir = random->nextFloat() * PI * 2; - thrownItem->xd = -sin(dir) * _pow; - thrownItem->zd = cos(dir) * _pow; - thrownItem->yd = 0.2f; + if (m_isSleeping) { + bedPosition = new Pos(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + stopSleepInBed(true, true, false); + } - } - else - { - pow = 0.3f; - thrownItem->xd = -sin(yRot / 180 * PI) * cos(xRot / 180 * PI) * pow; - thrownItem->zd = cos(yRot / 180 * PI) * cos(xRot / 180 * PI) * pow; - thrownItem->yd = -sin(xRot / 180 * PI) * pow + 0.1f; - pow = 0.02f; + if (entityTag->contains(L"SpawnX") && entityTag->contains(L"SpawnY") && + entityTag->contains(L"SpawnZ")) { + respawnPosition = + new Pos(entityTag->getInt(L"SpawnX"), entityTag->getInt(L"SpawnY"), + entityTag->getInt(L"SpawnZ")); + } - float dir = random->nextFloat() * PI * 2; - pow *= random->nextFloat(); - thrownItem->xd += cos(dir) * pow; - thrownItem->yd += (random->nextFloat() - random->nextFloat()) * 0.1f; - thrownItem->zd += sin(dir) * pow; - } + foodData.readAdditionalSaveData(entityTag); + abilities.loadSaveData(entityTag); - reallyDrop(thrownItem); + if (entityTag->contains(L"EnderItems")) { + ListTag* enderItemsList = + (ListTag*)entityTag->getList(L"EnderItems"); + enderChestInventory->setItemsByTag(enderItemsList); + } - return thrownItem; + // 4J Added + m_uiGamePrivileges = entityTag->getInt(L"GamePrivileges"); } +void Player::addAdditonalSaveData(CompoundTag* entityTag) { + Mob::addAdditonalSaveData(entityTag); + entityTag->put(L"Inventory", inventory->save(new ListTag())); + entityTag->putInt(L"Dimension", dimension); + entityTag->putBoolean(L"Sleeping", m_isSleeping); + entityTag->putShort(L"SleepTimer", (short)sleepCounter); -void Player::reallyDrop(std::shared_ptr thrownItem) -{ - level->addEntity(thrownItem); + entityTag->putFloat(L"XpP", experienceProgress); + entityTag->putInt(L"XpLevel", experienceLevel); + entityTag->putInt(L"XpTotal", totalExperience); + + if (respawnPosition != NULL) { + entityTag->putInt(L"SpawnX", respawnPosition->x); + entityTag->putInt(L"SpawnY", respawnPosition->y); + entityTag->putInt(L"SpawnZ", respawnPosition->z); + } + + foodData.addAdditonalSaveData(entityTag); + abilities.addSaveData(entityTag); + + entityTag->put(L"EnderItems", enderChestInventory->createTag()); + + // 4J Added + entityTag->putInt(L"GamePrivileges", m_uiGamePrivileges); } - -float Player::getDestroySpeed(Tile *tile) -{ - float speed = inventory->getDestroySpeed(tile); - - int efficiency = EnchantmentHelper::getDiggingBonus(inventory); - if (efficiency > 0 && inventory->canDestroy(tile)) - { - speed += (efficiency * efficiency + 1); - } - - if (hasEffect(MobEffect::digSpeed)) - { - speed *= 1.0f + (getEffect(MobEffect::digSpeed)->getAmplifier() + 1) * .2f; - } - if (hasEffect(MobEffect::digSlowdown)) - { - speed *= 1.0f - (getEffect(MobEffect::digSlowdown)->getAmplifier() + 1) * .2f; - } - - if (isUnderLiquid(Material::water) && !EnchantmentHelper::hasWaterWorkerBonus(inventory)) speed /= 5; - - // 4J Stu - onGround is set to true on the client when we are flying, which means - // the dig speed is out of sync with the server. Removing this speed change when - // flying so that we always dig as the same speed - //if (!onGround) speed /= 5; - - return speed; +Pos* Player::getRespawnPosition(Level* level, CompoundTag* entityTag) { + if (entityTag->contains(L"SpawnX") && entityTag->contains(L"SpawnY") && + entityTag->contains(L"SpawnZ")) { + return new Pos(entityTag->getInt(L"SpawnX"), + entityTag->getInt(L"SpawnY"), + entityTag->getInt(L"SpawnZ")); + } + return level->getSharedSpawnPos(); } -bool Player::canDestroy(Tile *tile) -{ - return inventory->canDestroy(tile); +bool Player::openContainer(std::shared_ptr container) { + return true; } -void Player::readAdditionalSaveData(CompoundTag *entityTag) -{ - Mob::readAdditionalSaveData(entityTag); - ListTag *inventoryList = (ListTag *) entityTag->getList(L"Inventory"); - inventory->load(inventoryList); - dimension = entityTag->getInt(L"Dimension"); - m_isSleeping = entityTag->getBoolean(L"Sleeping"); - sleepCounter = entityTag->getShort(L"SleepTimer"); +bool Player::startEnchanting(int x, int y, int z) { return true; } - experienceProgress = entityTag->getFloat(L"XpP"); - experienceLevel = entityTag->getInt(L"XpLevel"); - totalExperience = entityTag->getInt(L"XpTotal"); +bool Player::startRepairing(int x, int y, int z) { return true; } - if (m_isSleeping) - { - bedPosition = new Pos( Mth::floor(x), Mth::floor(y), Mth::floor(z)); - stopSleepInBed(true, true, false); - } +bool Player::startCrafting(int x, int y, int z) { return true; } - if (entityTag->contains(L"SpawnX") && entityTag->contains(L"SpawnY") && entityTag->contains(L"SpawnZ")) - { - respawnPosition = new Pos(entityTag->getInt(L"SpawnX"), entityTag->getInt(L"SpawnY"), entityTag->getInt(L"SpawnZ")); - } +void Player::take(std::shared_ptr e, int orgCount) {} - foodData.readAdditionalSaveData(entityTag); - abilities.loadSaveData(entityTag); +float Player::getHeadHeight() { return 0.12f; } - if (entityTag->contains(L"EnderItems")) - { - ListTag *enderItemsList = (ListTag *) entityTag->getList(L"EnderItems"); - enderChestInventory->setItemsByTag(enderItemsList); - } +void Player::setDefaultHeadHeight() { heightOffset = 1.62f; } - // 4J Added - m_uiGamePrivileges = entityTag->getInt(L"GamePrivileges"); +bool Player::hurt(DamageSource* source, int dmg) { + if (hasInvulnerablePrivilege() || + (abilities.invulnerable && !source->isBypassInvul())) + return false; + + // 4J-JEV: Fix for PSVita: #3987 - [IN GAME] The user can take damage/die, + // when attempting to re-enter fly mode when falling from a height. + if (source == DamageSource::fall && isAllowedToFly() && abilities.flying) + return false; + + noActionTime = 0; + if (getHealth() <= 0) return false; + + if (isSleeping() && !level->isClientSide) { + stopSleepInBed(true, true, false); + } + + if (source->scalesWithDifficulty()) { + if (level->difficulty == Difficulty::PEACEFUL) dmg = 0; + if (level->difficulty == Difficulty::EASY) dmg = dmg / 2 + 1; + if (level->difficulty == Difficulty::HARD) dmg = dmg * 3 / 2; + } + + if (dmg == 0) return false; + + std::shared_ptr attacker = source->getEntity(); + if (std::dynamic_pointer_cast(attacker) != NULL) { + if ((std::dynamic_pointer_cast(attacker))->owner != NULL) { + attacker = (std::dynamic_pointer_cast(attacker))->owner; + } + } + if (std::dynamic_pointer_cast(attacker) != NULL) { + // aggreviate all pet wolves nearby + directAllTameWolvesOnTarget(std::dynamic_pointer_cast(attacker), + false); + } + + return this->Mob::hurt(source, dmg); } -void Player::addAdditonalSaveData(CompoundTag *entityTag) -{ - Mob::addAdditonalSaveData(entityTag); - entityTag->put(L"Inventory", inventory->save(new ListTag())); - entityTag->putInt(L"Dimension", dimension); - entityTag->putBoolean(L"Sleeping", m_isSleeping); - entityTag->putShort(L"SleepTimer", (short) sleepCounter); +int Player::getDamageAfterMagicAbsorb(DamageSource* damageSource, int damage) { + int remainingDamage = Mob::getDamageAfterMagicAbsorb(damageSource, damage); + if (remainingDamage <= 0) { + return 0; + } - entityTag->putFloat(L"XpP", experienceProgress); - entityTag->putInt(L"XpLevel", experienceLevel); - entityTag->putInt(L"XpTotal", totalExperience); - - if (respawnPosition != NULL) - { - entityTag->putInt(L"SpawnX", respawnPosition->x); - entityTag->putInt(L"SpawnY", respawnPosition->y); - entityTag->putInt(L"SpawnZ", respawnPosition->z); - } - - foodData.addAdditonalSaveData(entityTag); - abilities.addSaveData(entityTag); - - entityTag->put(L"EnderItems", enderChestInventory->createTag()); - - // 4J Added - entityTag->putInt(L"GamePrivileges",m_uiGamePrivileges); + int enchantmentArmor = + EnchantmentHelper::getDamageProtection(inventory, damageSource); + if (enchantmentArmor > 20) { + enchantmentArmor = 20; + } + if (enchantmentArmor > 0 && enchantmentArmor <= 20) { + int absorb = 25 - enchantmentArmor; + int v = remainingDamage * absorb + dmgSpill; + remainingDamage = v / 25; + dmgSpill = v % 25; + } + return remainingDamage; } -Pos *Player::getRespawnPosition(Level *level, CompoundTag *entityTag) -{ - if (entityTag->contains(L"SpawnX") && entityTag->contains(L"SpawnY") && entityTag->contains(L"SpawnZ")) - { - return new Pos(entityTag->getInt(L"SpawnX"), entityTag->getInt(L"SpawnY"), entityTag->getInt(L"SpawnZ")); - } - return level->getSharedSpawnPos(); +bool Player::isPlayerVersusPlayer() { return false; } + +void Player::directAllTameWolvesOnTarget(std::shared_ptr target, + bool skipSitting) { + // filter un-attackable mobs + if ((std::dynamic_pointer_cast(target) != NULL) || + (std::dynamic_pointer_cast(target) != NULL)) { + return; + } + // never target wolves that has this player as owner + if (std::dynamic_pointer_cast(target) != NULL) { + std::shared_ptr wolfTarget = + std::dynamic_pointer_cast(target); + if (wolfTarget->isTame() && + m_UUID.compare(wolfTarget->getOwnerUUID()) == 0) { + return; + } + } + if ((std::dynamic_pointer_cast(target) != NULL) && + !isPlayerVersusPlayer()) { + // pvp is off + return; + } + + // TODO: Optimize this? Most of the time players wont have pets: + std::vector >* nearbyWolves = + level->getEntitiesOfClass( + typeid(Wolf), + AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(16, 4, 16)); + AUTO_VAR(itEnd, nearbyWolves->end()); + for (AUTO_VAR(it, nearbyWolves->begin()); it != itEnd; it++) { + std::shared_ptr wolf = std::dynamic_pointer_cast(*it); + ; + if (wolf->isTame() && wolf->getAttackTarget() == NULL && + m_UUID.compare(wolf->getOwnerUUID()) == 0) { + if (!skipSitting || !wolf->isSitting()) { + wolf->setSitting(false); + wolf->setAttackTarget(target); + } + } + } + delete nearbyWolves; } -bool Player::openContainer(std::shared_ptr container) -{ - return true; -} +void Player::hurtArmor(int damage) { inventory->hurtArmor(damage); } -bool Player::startEnchanting(int x, int y, int z) -{ - return true; -} +int Player::getArmorValue() { return inventory->getArmorValue(); } -bool Player::startRepairing(int x, int y, int z) -{ - return true; -} - -bool Player::startCrafting(int x, int y, int z) -{ - return true; -} - -void Player::take(std::shared_ptr e, int orgCount) -{ -} - -float Player::getHeadHeight() -{ - return 0.12f; -} - - -void Player::setDefaultHeadHeight() -{ - heightOffset = 1.62f; -} - -bool Player::hurt(DamageSource *source, int dmg) -{ - if ( hasInvulnerablePrivilege() || (abilities.invulnerable && !source->isBypassInvul()) ) return false; - - // 4J-JEV: Fix for PSVita: #3987 - [IN GAME] The user can take damage/die, when attempting to re-enter fly mode when falling from a height. - if ( source == DamageSource::fall && isAllowedToFly() && abilities.flying ) return false; - - noActionTime = 0; - if (getHealth() <= 0) return false; - - if (isSleeping() && !level->isClientSide) - { - stopSleepInBed(true, true, false); - } - - if ( source->scalesWithDifficulty() ) - { - if (level->difficulty == Difficulty::PEACEFUL) dmg = 0; - if (level->difficulty == Difficulty::EASY) dmg = dmg / 2 + 1; - if (level->difficulty == Difficulty::HARD) dmg = dmg * 3 / 2; - } - - if (dmg == 0) return false; - - std::shared_ptr attacker = source->getEntity(); - if ( std::dynamic_pointer_cast( attacker ) != NULL ) - { - if ((std::dynamic_pointer_cast(attacker))->owner != NULL) - { - attacker = (std::dynamic_pointer_cast(attacker))->owner; - } - } - if ( std::dynamic_pointer_cast( attacker ) != NULL ) - { - // aggreviate all pet wolves nearby - directAllTameWolvesOnTarget(std::dynamic_pointer_cast(attacker), false); - } - - return this->Mob::hurt(source, dmg); -} - -int Player::getDamageAfterMagicAbsorb(DamageSource *damageSource, int damage) -{ - int remainingDamage = Mob::getDamageAfterMagicAbsorb(damageSource, damage); - if (remainingDamage <= 0) - { - return 0; - } - - int enchantmentArmor = EnchantmentHelper::getDamageProtection(inventory, damageSource); - if (enchantmentArmor > 20) - { - enchantmentArmor = 20; - } - if (enchantmentArmor > 0 && enchantmentArmor <= 20) - { - int absorb = 25 - enchantmentArmor; - int v = remainingDamage * absorb + dmgSpill; - remainingDamage = v / 25; - dmgSpill = v % 25; - } - - return remainingDamage; -} - -bool Player::isPlayerVersusPlayer() -{ - return false; -} - -void Player::directAllTameWolvesOnTarget(std::shared_ptr target, bool skipSitting) -{ - - // filter un-attackable mobs - if ((std::dynamic_pointer_cast( target ) != NULL) || (std::dynamic_pointer_cast( target) != NULL)) - { - return; - } - // never target wolves that has this player as owner - if (std::dynamic_pointer_cast(target) != NULL) - { - std::shared_ptr wolfTarget = std::dynamic_pointer_cast(target); - if (wolfTarget->isTame() && m_UUID.compare( wolfTarget->getOwnerUUID() ) == 0 ) - { - return; - } - } - if ((std::dynamic_pointer_cast( target ) != NULL) && !isPlayerVersusPlayer()) - { - // pvp is off - return; - } - - - // TODO: Optimize this? Most of the time players wont have pets: - std::vector > *nearbyWolves = level->getEntitiesOfClass(typeid(Wolf), AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(16, 4, 16)); - AUTO_VAR(itEnd, nearbyWolves->end()); - for (AUTO_VAR(it, nearbyWolves->begin()); it != itEnd; it++) - { - std::shared_ptr wolf = std::dynamic_pointer_cast(*it);; - if (wolf->isTame() && wolf->getAttackTarget() == NULL && m_UUID.compare( wolf->getOwnerUUID() ) == 0) - { - if (!skipSitting || !wolf->isSitting()) - { - wolf->setSitting(false); - wolf->setAttackTarget(target); - } - } - } - delete nearbyWolves; - -} - -void Player::hurtArmor(int damage) -{ - inventory->hurtArmor(damage); -} - -int Player::getArmorValue() -{ - return inventory->getArmorValue(); -} - -float Player::getArmorCoverPercentage() -{ +float Player::getArmorCoverPercentage() { int count = 0; - for (int i = 0; i < inventory->armor.length; i++) - { + for (int i = 0; i < inventory->armor.length; i++) { if (inventory->armor[i] != NULL) { count++; } } - return (float) count / (float) inventory->armor.length; + return (float)count / (float)inventory->armor.length; } -void Player::actuallyHurt(DamageSource *source, int dmg) -{ - if (!source->isBypassArmor() && isBlocking()) - { - dmg = (1 + dmg) >> 1; - } - dmg = getDamageAfterArmorAbsorb(source, dmg); - dmg = getDamageAfterMagicAbsorb(source, dmg); - causeFoodExhaustion(source->getFoodExhaustion()); - //this->Mob::actuallyHurt(source, dmg); - health -= dmg; +void Player::actuallyHurt(DamageSource* source, int dmg) { + if (!source->isBypassArmor() && isBlocking()) { + dmg = (1 + dmg) >> 1; + } + dmg = getDamageAfterArmorAbsorb(source, dmg); + dmg = getDamageAfterMagicAbsorb(source, dmg); + causeFoodExhaustion(source->getFoodExhaustion()); + // this->Mob::actuallyHurt(source, dmg); + health -= dmg; } - -bool Player::openFurnace(std::shared_ptr container) -{ - return true; +bool Player::openFurnace(std::shared_ptr container) { + return true; } -bool Player::openTrap(std::shared_ptr container) -{ - return true; +bool Player::openTrap(std::shared_ptr container) { + return true; } -void Player::openTextEdit(std::shared_ptr sign) -{ +void Player::openTextEdit(std::shared_ptr sign) {} + +bool Player::openBrewingStand( + std::shared_ptr brewingStand) { + return true; } -bool Player::openBrewingStand(std::shared_ptr brewingStand) -{ - return true; -} - -bool Player::openTrading(std::shared_ptr traderTarget) -{ - return true; +bool Player::openTrading(std::shared_ptr traderTarget) { + return true; } /** -* Opens an iteminstance-dependent user interface. -* -* @param itemInstance -*/ -void Player::openItemInstanceGui(std::shared_ptr itemInstance) -{ + * Opens an iteminstance-dependent user interface. + * + * @param itemInstance + */ +void Player::openItemInstanceGui(std::shared_ptr itemInstance) {} + +bool Player::interact(std::shared_ptr entity) { + if (entity->interact(std::dynamic_pointer_cast(shared_from_this()))) + return true; + std::shared_ptr item = getSelectedItem(); + if (item != NULL && std::dynamic_pointer_cast(entity) != NULL) { + // 4J - PC Comments + // Hack to prevent item stacks from decrementing if the player has + // the ability to instabuild + if (this->abilities.instabuild) item = item->copy(); + if (item->interactEnemy(std::dynamic_pointer_cast(entity))) { + // 4J - PC Comments + // Don't remove the item in hand if the player has the ability + // to + // instabuild + if (item->count <= 0 && !this->abilities.instabuild) { + removeSelectedItem(); + } + return true; + } + } + return false; } -bool Player::interact(std::shared_ptr entity) -{ - if (entity->interact( std::dynamic_pointer_cast( shared_from_this() ) )) return true; - std::shared_ptr item = getSelectedItem(); - if (item != NULL && std::dynamic_pointer_cast( entity ) != NULL) - { - // 4J - PC Comments - // Hack to prevent item stacks from decrementing if the player has - // the ability to instabuild - if(this->abilities.instabuild) item = item->copy(); - if(item->interactEnemy(std::dynamic_pointer_cast(entity))) - { - // 4J - PC Comments - // Don't remove the item in hand if the player has the ability - // to - // instabuild - if (item->count <= 0 && !this->abilities.instabuild) - { - removeSelectedItem(); - } - return true; - } - } - return false; +std::shared_ptr Player::getSelectedItem() { + return inventory->getSelected(); } -std::shared_ptr Player::getSelectedItem() -{ - return inventory->getSelected(); +void Player::removeSelectedItem() { + inventory->setItem(inventory->selected, nullptr); } -void Player::removeSelectedItem() -{ - inventory->setItem(inventory->selected, nullptr); +double Player::getRidingHeight() { return heightOffset - 0.5f; } + +void Player::swing() { + if (!swinging || swingTime >= getCurrentSwingDuration() / 2 || + swingTime < 0) { + swingTime = -1; + swinging = true; + } } -double Player::getRidingHeight() -{ - return heightOffset - 0.5f; +void Player::attack(std::shared_ptr entity) { + if (!entity->isAttackable()) { + return; + } + + int dmg = inventory->getAttackDamage(entity); + + if (hasEffect(MobEffect::damageBoost)) { + dmg += (3 << getEffect(MobEffect::damageBoost)->getAmplifier()); + } + if (hasEffect(MobEffect::weakness)) { + dmg -= (2 << getEffect(MobEffect::weakness)->getAmplifier()); + } + + int knockback = 0; + int magicBoost = 0; + std::shared_ptr mob = std::dynamic_pointer_cast(entity); + if (mob != NULL) { + magicBoost = EnchantmentHelper::getDamageBonus(inventory, mob); + knockback += EnchantmentHelper::getKnockbackBonus(inventory, mob); + } + if (isSprinting()) { + knockback += 1; + } + + if (dmg > 0 || magicBoost > 0) { + bool bCrit = fallDistance > 0 && !onGround && !onLadder() && + !isInWater() && !hasEffect(MobEffect::blindness) && + riding == NULL && mob != NULL; + if (bCrit) { + dmg += random->nextInt(dmg / 2 + 2); + } + dmg += magicBoost; + + // Ensure we put the entity on fire if we're hitting with a + // fire-enchanted weapon + bool setOnFireTemporatily = false; + int fireAspect = EnchantmentHelper::getFireAspect( + std::dynamic_pointer_cast(shared_from_this())); + if (std::dynamic_pointer_cast(entity) && fireAspect > 0 && + !entity->isOnFire()) { + setOnFireTemporatily = true; + entity->setOnFire(1); + } + + DamageSource* damageSource = DamageSource::playerAttack( + std::dynamic_pointer_cast(shared_from_this())); + bool wasHurt = entity->hurt(damageSource, dmg); + delete damageSource; + if (wasHurt) { + if (knockback > 0) { + entity->push(-Mth::sin(yRot * PI / 180) * knockback * .5f, 0.1, + Mth::cos(yRot * PI / 180) * knockback * .5f); + xd *= 0.6; + zd *= 0.6; + setSprinting(false); + } + + if (bCrit) { + crit(entity); + } + if (magicBoost > 0) { + magicCrit(entity); + } + + if (dmg >= 18) { + awardStat(GenericStats::overkill(), + GenericStats::param_overkill(dmg)); + } + setLastHurtMob(entity); + + std::shared_ptr mob = std::dynamic_pointer_cast(entity); + if (mob) { + ThornsEnchantment::doThornsAfterAttack(shared_from_this(), mob, + random); + } + } + + std::shared_ptr item = getSelectedItem(); + if (item != NULL && std::dynamic_pointer_cast(entity) != NULL) { + item->hurtEnemy( + std::dynamic_pointer_cast(entity), + std::dynamic_pointer_cast(shared_from_this())); + if (item->count <= 0) { + removeSelectedItem(); + } + } + if (std::dynamic_pointer_cast(entity) != NULL) { + if (entity->isAlive()) { + directAllTameWolvesOnTarget( + std::dynamic_pointer_cast(entity), true); + } + // 4J Stu - Brought forward wasHurt check to Fix 66140 - Bug: Fire + // Aspect bypasses "Player v Player" being Disabled + if (fireAspect > 0 && wasHurt) { + entity->setOnFire(fireAspect * 4); + } else if (setOnFireTemporatily) { + entity->clearFire(); + } + } + + causeFoodExhaustion(FoodConstants::EXHAUSTION_ATTACK); + } } -void Player::swing() -{ - if (!swinging || swingTime >= getCurrentSwingDuration() / 2 || swingTime < 0) - { - swingTime = -1; - swinging = true; - } +void Player::crit(std::shared_ptr entity) {} + +void Player::magicCrit(std::shared_ptr entity) {} + +void Player::respawn() { deathFadeCounter = 0; } + +void Player::animateRespawn(std::shared_ptr player, Level* level) { + for (int i = 0; i < 45; i++) { + float angle = i * PI * 4.0f / 25.0f; + float xo = Mth::cos(angle) * 0.7f; + float zo = Mth::sin(angle) * 0.7f; + + level->addParticle(eParticleType_netherportal, player->x + xo, + player->y - player->heightOffset + 1.62f - i * .05f, + player->z + zo, 0, 0, 0); + } } -void Player::attack(std::shared_ptr entity) -{ - if (!entity->isAttackable()) - { - return; - } +Slot* Player::getInventorySlot(int slotId) { return NULL; } - int dmg = inventory->getAttackDamage(entity); - - if (hasEffect(MobEffect::damageBoost)) - { - dmg += (3 << getEffect(MobEffect::damageBoost)->getAmplifier()); - } - if (hasEffect(MobEffect::weakness)) - { - dmg -= (2 << getEffect(MobEffect::weakness)->getAmplifier()); - } - - int knockback = 0; - int magicBoost = 0; - std::shared_ptr mob = std::dynamic_pointer_cast(entity); - if (mob != NULL) - { - magicBoost = EnchantmentHelper::getDamageBonus(inventory, mob); - knockback += EnchantmentHelper::getKnockbackBonus(inventory, mob); - } - if (isSprinting()) - { - knockback += 1; - } - - if (dmg > 0 || magicBoost > 0) - { - bool bCrit = fallDistance > 0 && !onGround && !onLadder() && !isInWater() && !hasEffect(MobEffect::blindness) && riding == NULL && mob != NULL; - if (bCrit) - { - dmg += random->nextInt(dmg / 2 + 2); - } - dmg += magicBoost; - - // Ensure we put the entity on fire if we're hitting with a - // fire-enchanted weapon - bool setOnFireTemporatily = false; - int fireAspect = EnchantmentHelper::getFireAspect(std::dynamic_pointer_cast(shared_from_this())); - if (std::dynamic_pointer_cast(entity) && fireAspect > 0 && !entity->isOnFire()) - { - setOnFireTemporatily = true; - entity->setOnFire(1); - } - - DamageSource *damageSource = DamageSource::playerAttack(std::dynamic_pointer_cast(shared_from_this())); - bool wasHurt = entity->hurt(damageSource, dmg); - delete damageSource; - if (wasHurt) - { - if (knockback > 0) - { - entity->push(-Mth::sin(yRot * PI / 180) * knockback * .5f, 0.1, Mth::cos(yRot * PI / 180) * knockback * .5f); - xd *= 0.6; - zd *= 0.6; - setSprinting(false); - } - - if (bCrit) - { - crit(entity); - } - if (magicBoost > 0) - { - magicCrit(entity); - } - - if (dmg >= 18) - { - awardStat(GenericStats::overkill(),GenericStats::param_overkill(dmg)); - } - setLastHurtMob(entity); - - std::shared_ptr mob = std::dynamic_pointer_cast(entity); - if (mob) - { - ThornsEnchantment::doThornsAfterAttack(shared_from_this(), mob, random); - } - } - - std::shared_ptr item = getSelectedItem(); - if (item != NULL && std::dynamic_pointer_cast( entity ) != NULL) - { - item->hurtEnemy(std::dynamic_pointer_cast(entity), std::dynamic_pointer_cast( shared_from_this() ) ); - if (item->count <= 0) - { - removeSelectedItem(); - } - } - if (std::dynamic_pointer_cast( entity ) != NULL) - { - if (entity->isAlive()) - { - directAllTameWolvesOnTarget(std::dynamic_pointer_cast(entity), true); - } - // 4J Stu - Brought forward wasHurt check to Fix 66140 - Bug: Fire Aspect bypasses "Player v Player" being Disabled - if (fireAspect > 0 && wasHurt) - { - entity->setOnFire(fireAspect * 4); - } - else if (setOnFireTemporatily) - { - entity->clearFire(); - } - } - - causeFoodExhaustion(FoodConstants::EXHAUSTION_ATTACK); - } +void Player::remove() { + this->Mob::remove(); + inventoryMenu->removed( + std::dynamic_pointer_cast(shared_from_this())); + if (containerMenu != NULL) { + containerMenu->removed( + std::dynamic_pointer_cast(shared_from_this())); + } } -void Player::crit(std::shared_ptr entity) -{ +bool Player::isInWall() { return !m_isSleeping && this->Mob::isInWall(); } + +bool Player::isLocalPlayer() { return false; } + +Player::BedSleepingResult Player::startSleepInBed(int x, int y, int z, + bool bTestUse) { + if (!level->isClientSide || bTestUse) { + if (isSleeping() || !isAlive()) { + return OTHER_PROBLEM; + } + + if (!level->dimension->isNaturalDimension()) { + // may not sleep in this dimension + return NOT_POSSIBLE_HERE; + } + + // 4J-PB - I'm going to move the position of these tests below + // The distance check should be before the day check, otherwise you can + // use the bed in daytime from far away and you'll get the message about + // only sleeping at night + + if (abs(this->x - x) > 3 || abs(this->y - y) > 2 || + abs(this->z - z) > 3) { + // too far away + return TOO_FAR_AWAY; + } + + if (!bTestUse) { + // 4J-PB - We still want the tooltip for Sleep + + double hRange = 8; + double vRange = 5; + std::vector >* monsters = + level->getEntitiesOfClass( + typeid(Monster), + AABB::newTemp(x - hRange, y - vRange, z - hRange, + x + hRange, y + vRange, z + hRange)); + if (!monsters->empty()) { + return NOT_SAFE; + } + delete monsters; + } + + // This causes a message to be displayed, so we do want to show the + // tooltip in test mode + if (!bTestUse && level->isDay()) { + // may not sleep during day + return NOT_POSSIBLE_NOW; + } + } + + if (bTestUse) { + // 4J-PB - we're just testing use, and we get here, then the bed can be + // used + return OK; + } + + // 4J Stu - You can use a bed from within a minecart, and this causes all + // sorts of problems. + ride(nullptr); + + setSize(0.2f, 0.2f); + heightOffset = .2f; + if (level->hasChunkAt(x, y, z)) { + int data = level->getData(x, y, z); + int direction = BedTile::getDirection(data); + float xo = .5f, zo = .5f; + + switch (direction) { + case Direction::SOUTH: + zo = .9f; + break; + case Direction::NORTH: + zo = .1f; + break; + case Direction::WEST: + xo = .1f; + break; + case Direction::EAST: + xo = .9f; + break; + } + setBedOffset(direction); + setPos(x + xo, y + 15.0f / 16.0f, z + zo); + } else { + setPos(x + .5f, y + 15.0f / 16.0f, z + .5f); + } + m_isSleeping = true; + sleepCounter = 0; + bedPosition = new Pos(x, y, z); + xd = zd = yd = 0; + + if (!level->isClientSide) { + level->updateSleepingPlayerList(); + } + + return OK; } -void Player::magicCrit(std::shared_ptr entity) -{ +void Player::setBedOffset(int bedDirection) { + // place position on pillow and feet at bottom + bedOffsetX = 0; + bedOffsetZ = 0; + + switch (bedDirection) { + case Direction::SOUTH: + bedOffsetZ = -1.8f; + break; + case Direction::NORTH: + bedOffsetZ = 1.8f; + break; + case Direction::WEST: + bedOffsetX = 1.8f; + break; + case Direction::EAST: + bedOffsetX = -1.8f; + break; + } } -void Player::respawn() -{ - deathFadeCounter=0; -} - - -void Player::animateRespawn(std::shared_ptr player, Level *level) -{ - - for (int i = 0; i < 45; i++) - { - float angle = i * PI * 4.0f / 25.0f; - float xo = Mth::cos(angle) * 0.7f; - float zo = Mth::sin(angle) * 0.7f; - - level->addParticle(eParticleType_netherportal, player->x + xo, player->y - player->heightOffset + 1.62f - i * .05f, player->z + zo, 0, 0, 0); - } - -} - -Slot *Player::getInventorySlot(int slotId) -{ - return NULL; -} - -void Player::remove() -{ - this->Mob::remove(); - inventoryMenu->removed( std::dynamic_pointer_cast( shared_from_this() ) ); - if (containerMenu != NULL) - { - containerMenu->removed( std::dynamic_pointer_cast( shared_from_this() ) ); - } -} - -bool Player::isInWall() -{ - return !m_isSleeping && this->Mob::isInWall(); -} - -bool Player::isLocalPlayer() -{ - return false; -} - -Player::BedSleepingResult Player::startSleepInBed(int x, int y, int z, bool bTestUse) -{ - if (!level->isClientSide || bTestUse) - { - if (isSleeping() || !isAlive()) - { - return OTHER_PROBLEM; - } - - if (!level->dimension->isNaturalDimension()) - { - // may not sleep in this dimension - return NOT_POSSIBLE_HERE; - } - - // 4J-PB - I'm going to move the position of these tests below - // The distance check should be before the day check, otherwise you can use the bed in daytime from far away - // and you'll get the message about only sleeping at night - - if (abs(this->x - x) > 3 || abs(this->y - y) > 2 || abs(this->z - z) > 3) - { - // too far away - return TOO_FAR_AWAY; - } - - if (!bTestUse) - { - // 4J-PB - We still want the tooltip for Sleep - - double hRange = 8; - double vRange = 5; - std::vector > *monsters = level->getEntitiesOfClass(typeid(Monster), AABB::newTemp(x - hRange, y - vRange, z - hRange, x + hRange, y + vRange, z + hRange)); - if (!monsters->empty()) - { - return NOT_SAFE; - } - delete monsters; - } - - // This causes a message to be displayed, so we do want to show the tooltip in test mode - if (!bTestUse && level->isDay()) - { - // may not sleep during day - return NOT_POSSIBLE_NOW; - } - } - - if(bTestUse) - { - // 4J-PB - we're just testing use, and we get here, then the bed can be used - return OK; - } - - // 4J Stu - You can use a bed from within a minecart, and this causes all sorts of problems. - ride(nullptr); - - setSize(0.2f, 0.2f); - heightOffset = .2f; - if (level->hasChunkAt(x, y, z)) - { - - - int data = level->getData(x, y, z); - int direction = BedTile::getDirection(data); - float xo = .5f, zo = .5f; - - switch (direction) - { - case Direction::SOUTH: - zo = .9f; - break; - case Direction::NORTH: - zo = .1f; - break; - case Direction::WEST: - xo = .1f; - break; - case Direction::EAST: - xo = .9f; - break; - } - setBedOffset(direction); - setPos(x + xo, y + 15.0f / 16.0f, z + zo); - } - else - { - setPos(x + .5f, y + 15.0f / 16.0f, z + .5f); - } - m_isSleeping = true; - sleepCounter = 0; - bedPosition = new Pos(x, y, z); - xd = zd = yd = 0; - - if (!level->isClientSide) - { - level->updateSleepingPlayerList(); - } - - return OK; -} - - -void Player::setBedOffset(int bedDirection) -{ - // place position on pillow and feet at bottom - bedOffsetX = 0; - bedOffsetZ = 0; - - switch (bedDirection) - { - case Direction::SOUTH: - bedOffsetZ = -1.8f; - break; - case Direction::NORTH: - bedOffsetZ = 1.8f; - break; - case Direction::WEST: - bedOffsetX = 1.8f; - break; - case Direction::EAST: - bedOffsetX = -1.8f; - break; - } -} - - /** -* -* @param forcefulWakeUp -* If the player has been forced to wake up. When this happens, -* the client will skip the wake-up animation. For example, when -* the player is hurt or the bed is destroyed. -* @param updateLevelList -* If the level's sleeping player list needs to be updated. This -* is usually the case. -* @param saveRespawnPoint -* TODO -*/ -void Player::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint) -{ + * + * @param forcefulWakeUp + * If the player has been forced to wake up. When this happens, + * the client will skip the wake-up animation. For example, when + * the player is hurt or the bed is destroyed. + * @param updateLevelList + * If the level's sleeping player list needs to be updated. This + * is usually the case. + * @param saveRespawnPoint + * TODO + */ +void Player::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint) { + setSize(0.6f, 1.8f); + setDefaultHeadHeight(); - setSize(0.6f, 1.8f); - setDefaultHeadHeight(); + Pos* pos = bedPosition; + Pos* standUp = bedPosition; + if (pos != NULL && level->getTile(pos->x, pos->y, pos->z) == Tile::bed_Id) { + BedTile::setOccupied(level, pos->x, pos->y, pos->z, false); - Pos *pos = bedPosition; - Pos *standUp = bedPosition; - if (pos != NULL && level->getTile(pos->x, pos->y, pos->z) == Tile::bed_Id) - { - BedTile::setOccupied(level, pos->x, pos->y, pos->z, false); + standUp = + BedTile::findStandUpPosition(level, pos->x, pos->y, pos->z, 0); + if (standUp == NULL) { + standUp = new Pos(pos->x, pos->y + 1, pos->z); + } + setPos(standUp->x + .5f, standUp->y + heightOffset + .1f, + standUp->z + .5f); + } - standUp = BedTile::findStandUpPosition(level, pos->x, pos->y, pos->z, 0); - if (standUp == NULL) - { - standUp = new Pos(pos->x, pos->y + 1, pos->z); - } - setPos(standUp->x + .5f, standUp->y + heightOffset + .1f, standUp->z + .5f); - } - - m_isSleeping = false; - if (!level->isClientSide && updateLevelList) - { - level->updateSleepingPlayerList(); - } - if (forcefulWakeUp) - { - sleepCounter = 0; - } - else - { - sleepCounter = SLEEP_DURATION; - } - if (saveRespawnPoint) - { - setRespawnPosition(bedPosition); - } + m_isSleeping = false; + if (!level->isClientSide && updateLevelList) { + level->updateSleepingPlayerList(); + } + if (forcefulWakeUp) { + sleepCounter = 0; + } else { + sleepCounter = SLEEP_DURATION; + } + if (saveRespawnPoint) { + setRespawnPosition(bedPosition); + } } - -bool Player::checkBed() -{ - return (level->getTile(bedPosition->x, bedPosition->y, bedPosition->z) == Tile::bed_Id); +bool Player::checkBed() { + return (level->getTile(bedPosition->x, bedPosition->y, bedPosition->z) == + Tile::bed_Id); } +Pos* Player::checkBedValidRespawnPosition(Level* level, Pos* pos) { + // make sure the chunks around the bed exist + ChunkSource* chunkSource = level->getChunkSource(); + chunkSource->create((pos->x - 3) >> 4, (pos->z - 3) >> 4); + chunkSource->create((pos->x + 3) >> 4, (pos->z - 3) >> 4); + chunkSource->create((pos->x - 3) >> 4, (pos->z + 3) >> 4); + chunkSource->create((pos->x + 3) >> 4, (pos->z + 3) >> 4); -Pos *Player::checkBedValidRespawnPosition(Level *level, Pos *pos) -{ - // make sure the chunks around the bed exist - ChunkSource *chunkSource = level->getChunkSource(); - chunkSource->create((pos->x - 3) >> 4, (pos->z - 3) >> 4); - chunkSource->create((pos->x + 3) >> 4, (pos->z - 3) >> 4); - chunkSource->create((pos->x - 3) >> 4, (pos->z + 3) >> 4); - chunkSource->create((pos->x + 3) >> 4, (pos->z + 3) >> 4); - - // make sure the bed is still standing - if (level->getTile(pos->x, pos->y, pos->z) != Tile::bed_Id) - { - return NULL; - } - // make sure the bed still has a stand-up position - Pos *standUp = BedTile::findStandUpPosition(level, pos->x, pos->y, pos->z, 0); - return standUp; + // make sure the bed is still standing + if (level->getTile(pos->x, pos->y, pos->z) != Tile::bed_Id) { + return NULL; + } + // make sure the bed still has a stand-up position + Pos* standUp = + BedTile::findStandUpPosition(level, pos->x, pos->y, pos->z, 0); + return standUp; } -float Player::getSleepRotation() -{ - if (bedPosition != NULL) - { - int data = level->getData(bedPosition->x, bedPosition->y, bedPosition->z); - int direction = BedTile::getDirection(data); +float Player::getSleepRotation() { + if (bedPosition != NULL) { + int data = + level->getData(bedPosition->x, bedPosition->y, bedPosition->z); + int direction = BedTile::getDirection(data); - switch (direction) - { - case Direction::SOUTH: - return 90; - case Direction::WEST: - return 0; - case Direction::NORTH: - return 270; - case Direction::EAST: - return 180; - } - } - return 0; + switch (direction) { + case Direction::SOUTH: + return 90; + case Direction::WEST: + return 0; + case Direction::NORTH: + return 270; + case Direction::EAST: + return 180; + } + } + return 0; } -bool Player::isSleeping() -{ - return m_isSleeping; +bool Player::isSleeping() { return m_isSleeping; } + +bool Player::isSleepingLongEnough() { + return m_isSleeping && sleepCounter >= SLEEP_DURATION; } -bool Player::isSleepingLongEnough() -{ - return m_isSleeping && sleepCounter >= SLEEP_DURATION; -} - -int Player::getSleepTimer() -{ - return sleepCounter; -} +int Player::getSleepTimer() { return sleepCounter; } // 4J-PB - added for death fade -int Player::getDeathFadeTimer() -{ - return deathFadeCounter; +int Player::getDeathFadeTimer() { return deathFadeCounter; } + +bool Player::getPlayerFlag(int flag) { + return (entityData->getByte(DATA_PLAYER_FLAGS_ID) & (1 << flag)) != 0; } -bool Player::getPlayerFlag(int flag) -{ - return (entityData->getByte(DATA_PLAYER_FLAGS_ID) & (1 << flag)) != 0; +void Player::setPlayerFlag(int flag, bool value) { + std::uint8_t currentValue = entityData->getByte(DATA_PLAYER_FLAGS_ID); + if (value) { + entityData->set(DATA_PLAYER_FLAGS_ID, + (std::uint8_t)(currentValue | (1 << flag))); + } else { + entityData->set(DATA_PLAYER_FLAGS_ID, + (std::uint8_t)(currentValue & ~(1 << flag))); + } } -void Player::setPlayerFlag(int flag, bool value) -{ - std::uint8_t currentValue = entityData->getByte(DATA_PLAYER_FLAGS_ID); - if (value) - { - entityData->set(DATA_PLAYER_FLAGS_ID, (std::uint8_t) (currentValue | (1 << flag))); - } - else - { - entityData->set(DATA_PLAYER_FLAGS_ID, (std::uint8_t) (currentValue & ~(1 << flag))); - } -} - - /** -* This method is currently only relevant to client-side players. It will -* try to load the messageId from the language file and display it to the -* client. -*/ -void Player::displayClientMessage(int messageId) -{ + * This method is currently only relevant to client-side players. It will + * try to load the messageId from the language file and display it to the + * client. + */ +void Player::displayClientMessage(int messageId) {} +Pos* Player::getRespawnPosition() { return respawnPosition; } + +void Player::setRespawnPosition(Pos* respawnPosition) { + if (respawnPosition != NULL) { + this->respawnPosition = new Pos(*respawnPosition); + } else { + this->respawnPosition = NULL; + } } -Pos *Player::getRespawnPosition() -{ - return respawnPosition; +void Player::awardStat(Stat* stat, byteArray paramBlob) { + if (paramBlob.data != NULL) { + delete[] paramBlob.data; + } } -void Player::setRespawnPosition(Pos *respawnPosition) -{ - if (respawnPosition != NULL) - { - this->respawnPosition = new Pos(*respawnPosition); - } - else - { - this->respawnPosition = NULL; - } +void Player::jumpFromGround() { + this->Mob::jumpFromGround(); + + // 4J Stu - This seems to have been missed from 1.7.3, but do we care? + // awardStat(Stats::jump, 1); + + if (isSprinting()) { + causeFoodExhaustion(FoodConstants::EXHAUSTION_SPRINT_JUMP); + } else { + causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); + } } -void Player::awardStat(Stat *stat, byteArray paramBlob) -{ - if (paramBlob.data != NULL) - { - delete [] paramBlob.data; - } +void Player::travel(float xa, float ya) { + double preX = x, preY = y, preZ = z; + + if (abilities.flying && riding == NULL) { + double ydo = this->yd; + float ofs = flyingSpeed; + flyingSpeed = abilities.getFlyingSpeed(); + this->Mob::travel(xa, ya); + this->yd = ydo * 0.6; + flyingSpeed = ofs; + } else { + this->Mob::travel(xa, ya); + } + + checkMovementStatistiscs(x - preX, y - preY, z - preZ); } - -void Player::jumpFromGround() -{ - this->Mob::jumpFromGround(); - - // 4J Stu - This seems to have been missed from 1.7.3, but do we care? - //awardStat(Stats::jump, 1); - - if (isSprinting()) - { - causeFoodExhaustion(FoodConstants::EXHAUSTION_SPRINT_JUMP); - } - else - { - causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); - } +void Player::checkMovementStatistiscs(double dx, double dy, double dz) { + if (riding != NULL) { + return; + } + if (isUnderLiquid(Material::water)) { + int distance = + (int)Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); + if (distance > 0) { + // awardStat(Stats::diveOneCm, distance); + causeFoodExhaustion(FoodConstants::EXHAUSTION_SWIM * distance * + .01f); + } + } else if (isInWater()) { + int horizontalDistance = + (int)Math::round(sqrt(dx * dx + dz * dz) * 100.0f); + if (horizontalDistance > 0) { + distanceSwim += horizontalDistance; + if (distanceSwim >= 100) { + int newDistance = distanceSwim - (distanceSwim % 100); + distanceSwim -= newDistance; + awardStat(GenericStats::swimOneM(), + GenericStats::param_swim(newDistance / 100)); + } + causeFoodExhaustion(FoodConstants::EXHAUSTION_SWIM * + horizontalDistance * .01f); + } + } else if (onLadder()) { + if (dy > 0) { + distanceClimb += (int)Math::round(dy * 100.0f); + if (distanceClimb >= 100) { + int newDistance = distanceClimb - (distanceClimb % 100); + distanceClimb -= newDistance; + awardStat(GenericStats::climbOneM(), + GenericStats::param_climb(newDistance / 100)); + } + } + } else if (onGround) { + int horizontalDistance = + (int)Math::round(sqrt(dx * dx + dz * dz) * 100.0f); + if (horizontalDistance > 0) { + distanceWalk += horizontalDistance; + if (distanceWalk >= 100) { + int newDistance = distanceWalk - (distanceWalk % 100); + distanceWalk -= newDistance; + awardStat(GenericStats::walkOneM(), + GenericStats::param_walk(newDistance / 100)); + } + if (isSprinting()) { + causeFoodExhaustion(FoodConstants::EXHAUSTION_SPRINT * + horizontalDistance * .01f); + } else { + causeFoodExhaustion(FoodConstants::EXHAUSTION_WALK * + horizontalDistance * .01f); + } + } + } } +void Player::checkRidingStatistiscs(double dx, double dy, double dz) { + if (riding != NULL) { + int distance = + (int)Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); + if (distance > 0) { + if (std::dynamic_pointer_cast(riding)) { + distanceMinecart += distance; + if (distanceMinecart >= 100) { + int newDistance = + distanceMinecart - (distanceMinecart % 100); + distanceMinecart -= newDistance; + awardStat(GenericStats::minecartOneM(), + GenericStats::param_minecart(newDistance / 100)); + } -void Player::travel(float xa, float ya) -{ - double preX = x, preY = y, preZ = z; - - if (abilities.flying && riding == NULL) - { - double ydo = this->yd; - float ofs = flyingSpeed; - flyingSpeed = abilities.getFlyingSpeed(); - this->Mob::travel(xa, ya); - this->yd = ydo * 0.6; - flyingSpeed = ofs; - } - else - { - this->Mob::travel(xa, ya); - } - - checkMovementStatistiscs(x - preX, y - preY, z - preZ); -} - - -void Player::checkMovementStatistiscs(double dx, double dy, double dz) -{ - - if (riding != NULL) - { - return; - } - if (isUnderLiquid(Material::water)) - { - int distance = (int) Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); - if (distance > 0) - { - //awardStat(Stats::diveOneCm, distance); - causeFoodExhaustion(FoodConstants::EXHAUSTION_SWIM * distance * .01f); - } - } - else if (isInWater()) - { - int horizontalDistance = (int) Math::round(sqrt(dx * dx + dz * dz) * 100.0f); - if (horizontalDistance > 0) - { - distanceSwim += horizontalDistance; - if( distanceSwim >= 100 ) - { - int newDistance = distanceSwim - (distanceSwim % 100); - distanceSwim -= newDistance; - awardStat( GenericStats::swimOneM(), GenericStats::param_swim(newDistance/100) ); - } - causeFoodExhaustion(FoodConstants::EXHAUSTION_SWIM * horizontalDistance * .01f); - } - } - else if (onLadder()) - { - if (dy > 0) - { - distanceClimb += (int) Math::round(dy * 100.0f); - if( distanceClimb >= 100 ) - { - int newDistance = distanceClimb - (distanceClimb % 100); - distanceClimb -= newDistance; - awardStat( GenericStats::climbOneM(), GenericStats::param_climb(newDistance/100) ); - } - } - } - else if (onGround) - { - int horizontalDistance = (int) Math::round(sqrt(dx * dx + dz * dz) * 100.0f); - if (horizontalDistance > 0) - { - distanceWalk += horizontalDistance; - if( distanceWalk >= 100 ) - { - int newDistance = distanceWalk - (distanceWalk % 100); - distanceWalk -= newDistance; - awardStat( GenericStats::walkOneM(), GenericStats::param_walk(newDistance/100) ); - } - if (isSprinting()) - { - causeFoodExhaustion(FoodConstants::EXHAUSTION_SPRINT * horizontalDistance * .01f); - } - else - { - causeFoodExhaustion(FoodConstants::EXHAUSTION_WALK * horizontalDistance * .01f); - } - } - } -} - - -void Player::checkRidingStatistiscs(double dx, double dy, double dz) -{ - if (riding != NULL) - { - int distance = (int) Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); - if (distance > 0) - { - if ( std::dynamic_pointer_cast( riding ) ) - { - distanceMinecart += distance; - if( distanceMinecart >= 100 ) - { - int newDistance = distanceMinecart - (distanceMinecart % 100); - distanceMinecart -= newDistance; - awardStat( GenericStats::minecartOneM(), GenericStats::param_minecart(newDistance/100) ); - } - - int dist = 0; - if (minecartAchievementPos == NULL) - { - minecartAchievementPos = new Pos(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - } - // 4J-PB - changed this because our world isn't big enough to go 1000m - else - { - // 4-JEV, changed slightly to add extra parameters for event on durango. - int dist = minecartAchievementPos->dist(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + int dist = 0; + if (minecartAchievementPos == NULL) { + minecartAchievementPos = + new Pos(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + } + // 4J-PB - changed this because our world isn't big enough to go + // 1000m + else { + // 4-JEV, changed slightly to add extra parameters for event + // on durango. + int dist = minecartAchievementPos->dist( + Mth::floor(x), Mth::floor(y), Mth::floor(z)); #ifdef _XBOX_ONE - // 4J-PB - send the event to cause the progress bar to increase on XB1 - if (m_bAwardedOnARail==false) - { - if(dist < 500) - { - if((dist>0) && (dist%100==0)) - { - awardStat(GenericStats::onARail(), GenericStats::param_onARail(dist)); - } - } - else - { - awardStat(GenericStats::onARail(), GenericStats::param_onARail(dist)); - m_bAwardedOnARail=true; - } - } + // 4J-PB - send the event to cause the progress bar to + // increase on XB1 + if (m_bAwardedOnARail == false) { + if (dist < 500) { + if ((dist > 0) && (dist % 100 == 0)) { + awardStat(GenericStats::onARail(), + GenericStats::param_onARail(dist)); + } + } else { + awardStat(GenericStats::onARail(), + GenericStats::param_onARail(dist)); + m_bAwardedOnARail = true; + } + } #else - if ((m_bAwardedOnARail==false) && (dist >= 500)) - { - awardStat(GenericStats::onARail(), GenericStats::param_onARail(dist)); - m_bAwardedOnARail=true; - } -#endif - } + if ((m_bAwardedOnARail == false) && (dist >= 500)) { + awardStat(GenericStats::onARail(), + GenericStats::param_onARail(dist)); + m_bAwardedOnARail = true; + } +#endif + } - } - else if (std::dynamic_pointer_cast( riding ) != NULL) - { - distanceBoat += distance; - if( distanceBoat >= 100 ) - { - int newDistance = distanceBoat - (distanceBoat % 100); - distanceBoat -= newDistance; - awardStat(GenericStats::boatOneM(), GenericStats::param_boat(newDistance/100) ); - } - } - else if (std::dynamic_pointer_cast( riding ) != NULL) - { - distancePig += distance; - if( distancePig >= 100 ) - { - int newDistance = distancePig - (distancePig % 100); - distancePig -= newDistance; - awardStat(GenericStats::pigOneM(), GenericStats::param_pig(newDistance/100) ); - } - } - } - } + } else if (std::dynamic_pointer_cast(riding) != NULL) { + distanceBoat += distance; + if (distanceBoat >= 100) { + int newDistance = distanceBoat - (distanceBoat % 100); + distanceBoat -= newDistance; + awardStat(GenericStats::boatOneM(), + GenericStats::param_boat(newDistance / 100)); + } + } else if (std::dynamic_pointer_cast(riding) != NULL) { + distancePig += distance; + if (distancePig >= 100) { + int newDistance = distancePig - (distancePig % 100); + distancePig -= newDistance; + awardStat(GenericStats::pigOneM(), + GenericStats::param_pig(newDistance / 100)); + } + } + } + } } +void Player::causeFallDamage(float distance) { + if (abilities.mayfly) return; -void Player::causeFallDamage(float distance) -{ - if (abilities.mayfly) return; - - if (distance >= 2) - { - distanceFall += (int) Math::round(distance * 100.0); - if( distanceFall >= 100 ) - { - int newDistance = distanceFall - (distanceFall % 100); - distanceFall -= newDistance; - awardStat(GenericStats::fallOneM(), GenericStats::param_fall(newDistance/100) ); - } - } - this->Mob::causeFallDamage(distance); + if (distance >= 2) { + distanceFall += (int)Math::round(distance * 100.0); + if (distanceFall >= 100) { + int newDistance = distanceFall - (distanceFall % 100); + distanceFall -= newDistance; + awardStat(GenericStats::fallOneM(), + GenericStats::param_fall(newDistance / 100)); + } + } + this->Mob::causeFallDamage(distance); } +void Player::killed(std::shared_ptr mob) { + // 4J-PB - added the lavaslime enemy - fix for #64007 - TU7: Code: + // Achievements: TCR#073: Killing Magma Cubes doesn't unlock "Monster + // Hunter" Achievement. + if (std::dynamic_pointer_cast(mob) != NULL || + mob->GetType() == eTYPE_GHAST || mob->GetType() == eTYPE_SLIME || + mob->GetType() == eTYPE_LAVASLIME || + mob->GetType() == eTYPE_ENDERDRAGON) { + awardStat(GenericStats::killEnemy(), GenericStats::param_noArgs()); -void Player::killed(std::shared_ptr mob) -{ - // 4J-PB - added the lavaslime enemy - fix for #64007 - TU7: Code: Achievements: TCR#073: Killing Magma Cubes doesn't unlock "Monster Hunter" Achievement. - if( std::dynamic_pointer_cast( mob ) != NULL || mob->GetType() == eTYPE_GHAST || mob->GetType() == eTYPE_SLIME || mob->GetType() == eTYPE_LAVASLIME || mob->GetType() == eTYPE_ENDERDRAGON) - { - awardStat(GenericStats::killEnemy(), GenericStats::param_noArgs()); - - switch( mob->GetType() ) - { - case eTYPE_CREEPER: - awardStat(GenericStats::killsCreeper(), GenericStats::param_noArgs()); - break; - case eTYPE_SKELETON: - if( mob->isRiding() && mob->riding->GetType() == eTYPE_SPIDER ) - awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else - awardStat(GenericStats::killsSkeleton(), GenericStats::param_noArgs()); - break; - case eTYPE_SPIDER: - if( mob->rider.lock() != NULL && mob->rider.lock()->GetType() == eTYPE_SKELETON ) - awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else - awardStat(GenericStats::killsSpider(), GenericStats::param_noArgs()); - break; - case eTYPE_ZOMBIE: - awardStat(GenericStats::killsZombie(), GenericStats::param_noArgs()); - break; - case eTYPE_PIGZOMBIE: - if( level->dimension->id == 0 ) - awardStat(GenericStats::killsZombiePigman(), GenericStats::param_noArgs()); - else - awardStat(GenericStats::killsNetherZombiePigman(), GenericStats::param_noArgs()); - break; - case eTYPE_GHAST: - awardStat(GenericStats::killsGhast(), GenericStats::param_noArgs()); - break; - case eTYPE_SLIME: - awardStat(GenericStats::killsSlime(), GenericStats::param_noArgs()); - break; - case eTYPE_ENDERDRAGON: - awardStat(GenericStats::killsEnderdragon(), GenericStats::param_noArgs()); - break; - default: - break; - } - } - else if( mob->GetType() == eTYPE_COW ) - { - awardStat(GenericStats::killCow(), GenericStats::param_noArgs()); - } + switch (mob->GetType()) { + case eTYPE_CREEPER: + awardStat(GenericStats::killsCreeper(), + GenericStats::param_noArgs()); + break; + case eTYPE_SKELETON: + if (mob->isRiding() && mob->riding->GetType() == eTYPE_SPIDER) + awardStat(GenericStats::killsSpiderJockey(), + GenericStats::param_noArgs()); + else + awardStat(GenericStats::killsSkeleton(), + GenericStats::param_noArgs()); + break; + case eTYPE_SPIDER: + if (mob->rider.lock() != NULL && + mob->rider.lock()->GetType() == eTYPE_SKELETON) + awardStat(GenericStats::killsSpiderJockey(), + GenericStats::param_noArgs()); + else + awardStat(GenericStats::killsSpider(), + GenericStats::param_noArgs()); + break; + case eTYPE_ZOMBIE: + awardStat(GenericStats::killsZombie(), + GenericStats::param_noArgs()); + break; + case eTYPE_PIGZOMBIE: + if (level->dimension->id == 0) + awardStat(GenericStats::killsZombiePigman(), + GenericStats::param_noArgs()); + else + awardStat(GenericStats::killsNetherZombiePigman(), + GenericStats::param_noArgs()); + break; + case eTYPE_GHAST: + awardStat(GenericStats::killsGhast(), + GenericStats::param_noArgs()); + break; + case eTYPE_SLIME: + awardStat(GenericStats::killsSlime(), + GenericStats::param_noArgs()); + break; + case eTYPE_ENDERDRAGON: + awardStat(GenericStats::killsEnderdragon(), + GenericStats::param_noArgs()); + break; + default: + break; + } + } else if (mob->GetType() == eTYPE_COW) { + awardStat(GenericStats::killCow(), GenericStats::param_noArgs()); + } } -Icon *Player::getItemInHandIcon(std::shared_ptr item, int layer) -{ - Icon *icon = Mob::getItemInHandIcon(item, layer); - if (item->id == Item::fishingRod->id && fishing != NULL) - { - icon = Item::fishingRod->getEmptyIcon(); - } - else if (item->getItem()->hasMultipleSpriteLayers()) - { - return item->getItem()->getLayerIcon(item->getAuxValue(), layer); - } - else if (useItem != NULL && item->id == Item::bow_Id) - { - int ticksHeld = (item->getUseDuration() - useItemDuration); - if (ticksHeld >= BowItem::MAX_DRAW_DURATION - 2) - { - return Item::bow->getDrawnIcon(2); - } - if (ticksHeld > (2 * BowItem::MAX_DRAW_DURATION) / 3) - { - return Item::bow->getDrawnIcon(1); - } - if (ticksHeld > 0) - { - return Item::bow->getDrawnIcon(0); - } - } - return icon; +Icon* Player::getItemInHandIcon(std::shared_ptr item, int layer) { + Icon* icon = Mob::getItemInHandIcon(item, layer); + if (item->id == Item::fishingRod->id && fishing != NULL) { + icon = Item::fishingRod->getEmptyIcon(); + } else if (item->getItem()->hasMultipleSpriteLayers()) { + return item->getItem()->getLayerIcon(item->getAuxValue(), layer); + } else if (useItem != NULL && item->id == Item::bow_Id) { + int ticksHeld = (item->getUseDuration() - useItemDuration); + if (ticksHeld >= BowItem::MAX_DRAW_DURATION - 2) { + return Item::bow->getDrawnIcon(2); + } + if (ticksHeld > (2 * BowItem::MAX_DRAW_DURATION) / 3) { + return Item::bow->getDrawnIcon(1); + } + if (ticksHeld > 0) { + return Item::bow->getDrawnIcon(0); + } + } + return icon; } -std::shared_ptr Player::getArmor(int pos) -{ - return inventory->getArmor(pos); +std::shared_ptr Player::getArmor(int pos) { + return inventory->getArmor(pos); } -void Player::handleInsidePortal() -{ - if (changingDimensionDelay > 0) - { - changingDimensionDelay = 10; - return; - } +void Player::handleInsidePortal() { + if (changingDimensionDelay > 0) { + changingDimensionDelay = 10; + return; + } - isInsidePortal = true; + isInsidePortal = true; } -void Player::increaseXp(int i) -{ - // Update xp calculations from 1.3 - score += i; - int max = INT_MAX - totalExperience; - if (i > max) - { - i = max; - } - experienceProgress += (float) i / getXpNeededForNextLevel(); - totalExperience += i; - while (experienceProgress >= 1) - { - experienceProgress = (experienceProgress - 1) * getXpNeededForNextLevel(); - levelUp(); - experienceProgress /= getXpNeededForNextLevel(); - } +void Player::increaseXp(int i) { + // Update xp calculations from 1.3 + score += i; + int max = INT_MAX - totalExperience; + if (i > max) { + i = max; + } + experienceProgress += (float)i / getXpNeededForNextLevel(); + totalExperience += i; + while (experienceProgress >= 1) { + experienceProgress = + (experienceProgress - 1) * getXpNeededForNextLevel(); + levelUp(); + experienceProgress /= getXpNeededForNextLevel(); + } } -void Player::withdrawExperienceLevels(int amount) -{ - experienceLevel -= amount; - if (experienceLevel < 0) - { - experienceLevel = 0; - } +void Player::withdrawExperienceLevels(int amount) { + experienceLevel -= amount; + if (experienceLevel < 0) { + experienceLevel = 0; + } } -int Player::getXpNeededForNextLevel() -{ - // Update xp calculations from 1.3 - if (experienceLevel >= 30) - { - return 17 + 15 * 3 + (experienceLevel - 30) * 7; - } - if (experienceLevel >= 15) - { - return 17 + (experienceLevel - 15) * 3; - } - return 17; +int Player::getXpNeededForNextLevel() { + // Update xp calculations from 1.3 + if (experienceLevel >= 30) { + return 17 + 15 * 3 + (experienceLevel - 30) * 7; + } + if (experienceLevel >= 15) { + return 17 + (experienceLevel - 15) * 3; + } + return 17; } -void Player::levelUp() -{ - experienceLevel++; -} +void Player::levelUp() { experienceLevel++; } /** -* This method adds on to the player's exhaustion, which may decrease the -* player's food level. -* -* @param amount -* Amount of exhaustion to add, between 0 and 20 (setting it to -* 20 will guarantee that at least 1, and at most 4, food points -* are deducted). See FoodConstants for cost suggestions. -*/ -void Player::causeFoodExhaustion(float amount) -{ - if( isAllowedToIgnoreExhaustion() || ( isAllowedToFly() && abilities.flying) ) return; - if (abilities.invulnerable || hasInvulnerablePrivilege() ) return; + * This method adds on to the player's exhaustion, which may decrease the + * player's food level. + * + * @param amount + * Amount of exhaustion to add, between 0 and 20 (setting it to + * 20 will guarantee that at least 1, and at most 4, food points + * are deducted). See FoodConstants for cost suggestions. + */ +void Player::causeFoodExhaustion(float amount) { + if (isAllowedToIgnoreExhaustion() || (isAllowedToFly() && abilities.flying)) + return; + if (abilities.invulnerable || hasInvulnerablePrivilege()) return; - // 4J Stu - Added 1.8.2 bug fix (TU6) - If players cannot eat, then their food bar should not decrease due to exhaustion - if(app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0 && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) != 0) return; + // 4J Stu - Added 1.8.2 bug fix (TU6) - If players cannot eat, then their + // food bar should not decrease due to exhaustion + if (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0 && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) != 0) + return; - if (!level->isClientSide) - { - foodData.addExhaustion(amount); - } + if (!level->isClientSide) { + foodData.addExhaustion(amount); + } } -FoodData *Player::getFoodData() -{ - return &foodData; +FoodData* Player::getFoodData() { return &foodData; } + +bool Player::canEat(bool magicalItem) { + return (magicalItem || foodData.needsFood()) && !abilities.invulnerable && + !hasInvulnerablePrivilege(); } -bool Player::canEat(bool magicalItem) -{ - return (magicalItem || foodData.needsFood()) && !abilities.invulnerable && !hasInvulnerablePrivilege(); +bool Player::isHurt() { + return getHealth() > 0 && getHealth() < getMaxHealth(); } -bool Player::isHurt() -{ - return getHealth() > 0 && getHealth() < getMaxHealth(); -} +void Player::startUsingItem(std::shared_ptr instance, + int duration) { + if (instance == useItem) return; + useItem = instance; + useItemDuration = duration; + if (!level->isClientSide) { + setUsingItemFlag(true); + } -void Player::startUsingItem(std::shared_ptr instance, int duration) -{ - if (instance == useItem) return; - useItem = instance; - useItemDuration = duration; - if (!level->isClientSide) - { - setUsingItemFlag(true); - } - - // 4J-JEV, hook for ItemUsed event, and ironbelly achievement. - awardStat(GenericStats::itemsUsed(instance->getItem()->id), - GenericStats::param_itemsUsed(std::dynamic_pointer_cast(shared_from_this()),instance)); + // 4J-JEV, hook for ItemUsed event, and ironbelly achievement. + awardStat( + GenericStats::itemsUsed(instance->getItem()->id), + GenericStats::param_itemsUsed( + std::dynamic_pointer_cast(shared_from_this()), instance)); #if (!defined _DURANGO) && (defined _EXTENDED_ACHIEVEMENTS) - if ( (instance->getItem()->id == Item::rotten_flesh_Id) && (getFoodData()->getFoodLevel() == 0) ) - awardStat(GenericStats::ironBelly(), GenericStats::param_ironBelly()); + if ((instance->getItem()->id == Item::rotten_flesh_Id) && + (getFoodData()->getFoodLevel() == 0)) + awardStat(GenericStats::ironBelly(), GenericStats::param_ironBelly()); #endif } -bool Player::mayBuild(int x, int y, int z) -{ - return abilities.mayBuild; +bool Player::mayBuild(int x, int y, int z) { return abilities.mayBuild; } + +int Player::getExperienceReward(std::shared_ptr killedBy) { + int reward = experienceLevel * 7; + if (reward > 100) { + return 100; + } + return reward; } -int Player::getExperienceReward(std::shared_ptr killedBy) -{ - int reward = experienceLevel * 7; - if (reward > 100) - { - return 100; - } - return reward; +bool Player::isAlwaysExperienceDropper() { + // players always drop experience + return true; } -bool Player::isAlwaysExperienceDropper() -{ - // players always drop experience - return true; +std::wstring Player::getAName() { return name; } + +void Player::changeDimension(int i) {} + +void Player::restoreFrom(std::shared_ptr oldPlayer, bool restoreAll) { + if (restoreAll) { + inventory->replaceWith(oldPlayer->inventory); + + health = oldPlayer->health; + foodData = oldPlayer->foodData; + + experienceLevel = oldPlayer->experienceLevel; + totalExperience = oldPlayer->totalExperience; + experienceProgress = oldPlayer->experienceProgress; + + score = oldPlayer->score; + + for (AUTO_VAR(it, oldPlayer->activeEffects.begin()); + it != oldPlayer->activeEffects.end(); ++it) { + MobEffectInstance* instance = it->second; + addEffectNoUpdate(instance); + } + oldPlayer->activeEffects.clear(); + } + enderChestInventory = oldPlayer->enderChestInventory; } -std::wstring Player::getAName() -{ - return name; +bool Player::makeStepSound() { return !abilities.flying; } + +void Player::onUpdateAbilities() {} + +void Player::setGameMode(GameType* mode) {} + +std::wstring Player::getName() { return name; } + +std::wstring Player::getDisplayName() { return displayName; } + +// Language getLanguage() { return Language.getInstance(); } +// String localize(String key, Object... args) { return +// getLanguage().getElement(key, args); } + +std::shared_ptr Player::getEnderChestInventory() { + return enderChestInventory; } -void Player::changeDimension(int i) -{ +std::shared_ptr Player::getCarriedItem() { + return inventory->getSelected(); } -void Player::restoreFrom(std::shared_ptr oldPlayer, bool restoreAll) -{ - if(restoreAll) - { - inventory->replaceWith(oldPlayer->inventory); - - health = oldPlayer->health; - foodData = oldPlayer->foodData; - - experienceLevel = oldPlayer->experienceLevel; - totalExperience = oldPlayer->totalExperience; - experienceProgress = oldPlayer->experienceProgress; - - score = oldPlayer->score; - - for(AUTO_VAR(it, oldPlayer->activeEffects.begin()); it != oldPlayer->activeEffects.end(); ++it) - { - MobEffectInstance *instance = it->second; - addEffectNoUpdate( instance ); - } - oldPlayer->activeEffects.clear(); - } - enderChestInventory = oldPlayer->enderChestInventory; -} - -bool Player::makeStepSound() -{ - return !abilities.flying; -} - -void Player::onUpdateAbilities() -{ -} - -void Player::setGameMode(GameType *mode) -{ -} - -std::wstring Player::getName() -{ - return name; -} - -std::wstring Player::getDisplayName() -{ - return displayName; -} - -//Language getLanguage() { return Language.getInstance(); } -//String localize(String key, Object... args) { return getLanguage().getElement(key, args); } - -std::shared_ptr Player::getEnderChestInventory() -{ - return enderChestInventory; -} - -std::shared_ptr Player::getCarriedItem() -{ - return inventory->getSelected(); -} - -bool Player::isInvisibleTo(std::shared_ptr player) -{ +bool Player::isInvisibleTo(std::shared_ptr player) { return isInvisible(); } -int Player::getTexture() -{ - switch(m_skinIndex) - { - case eDefaultSkins_Skin0: - return TN_MOB_CHAR; // 4J - was L"/mob/char.png"; - case eDefaultSkins_Skin1: - return TN_MOB_CHAR1; // 4J - was L"/mob/char1.png"; - case eDefaultSkins_Skin2: - return TN_MOB_CHAR2; // 4J - was L"/mob/char2.png"; - case eDefaultSkins_Skin3: - return TN_MOB_CHAR3; // 4J - was L"/mob/char3.png"; - case eDefaultSkins_Skin4: - return TN_MOB_CHAR4; // 4J - was L"/mob/char4.png"; - case eDefaultSkins_Skin5: - return TN_MOB_CHAR5; // 4J - was L"/mob/char5.png"; - case eDefaultSkins_Skin6: - return TN_MOB_CHAR6; // 4J - was L"/mob/char6.png"; - case eDefaultSkins_Skin7: - return TN_MOB_CHAR7; // 4J - was L"/mob/char7.png"; +int Player::getTexture() { + switch (m_skinIndex) { + case eDefaultSkins_Skin0: + return TN_MOB_CHAR; // 4J - was L"/mob/char.png"; + case eDefaultSkins_Skin1: + return TN_MOB_CHAR1; // 4J - was L"/mob/char1.png"; + case eDefaultSkins_Skin2: + return TN_MOB_CHAR2; // 4J - was L"/mob/char2.png"; + case eDefaultSkins_Skin3: + return TN_MOB_CHAR3; // 4J - was L"/mob/char3.png"; + case eDefaultSkins_Skin4: + return TN_MOB_CHAR4; // 4J - was L"/mob/char4.png"; + case eDefaultSkins_Skin5: + return TN_MOB_CHAR5; // 4J - was L"/mob/char5.png"; + case eDefaultSkins_Skin6: + return TN_MOB_CHAR6; // 4J - was L"/mob/char6.png"; + case eDefaultSkins_Skin7: + return TN_MOB_CHAR7; // 4J - was L"/mob/char7.png"; - default: - return TN_MOB_CHAR; // 4J - was L"/mob/char.png"; - } + default: + return TN_MOB_CHAR; // 4J - was L"/mob/char.png"; + } } -int Player::hash_fnct(const std::shared_ptr k) -{ - // Hashing the player's name based on platform +int Player::hash_fnct(const std::shared_ptr k) { + // Hashing the player's name based on platform #ifdef __PS3__ - return (int)boost::hash_value(k->name); + return (int)boost::hash_value(k->name); #else - return (int)std::hash()(k->name); -#endif // __PS3__ + return (int)std::hash()(k->name); +#endif // __PS3__ } -bool Player::eq_test(const std::shared_ptr x, const std::shared_ptr y) -{ - // TODO 4J Stu - Should we just be using the pointers and comparing them for equality? - return x->name.compare( y->name ) == 0; // 4J Stu - Names are completely unique? +bool Player::eq_test(const std::shared_ptr x, + const std::shared_ptr y) { + // TODO 4J Stu - Should we just be using the pointers and comparing them for + // equality? + return x->name.compare(y->name) == + 0; // 4J Stu - Names are completely unique? } - -unsigned int Player::getPlayerGamePrivilege(EPlayerGamePrivileges privilege) -{ - return Player::getPlayerGamePrivilege(m_uiGamePrivileges,privilege); +unsigned int Player::getPlayerGamePrivilege(EPlayerGamePrivileges privilege) { + return Player::getPlayerGamePrivilege(m_uiGamePrivileges, privilege); } -unsigned int Player::getPlayerGamePrivilege(unsigned int uiGamePrivileges, EPlayerGamePrivileges privilege) -{ - if( privilege == ePlayerGamePrivilege_All ) - { - return uiGamePrivileges; - } - else if (privilege < ePlayerGamePrivilege_MAX ) - { - return uiGamePrivileges&(1<id) - { - case Tile::door_wood_Id: - case Tile::button_stone_Id: - case Tile::button_wood_Id: - case Tile::lever_Id: - case Tile::fenceGate_Id: - case Tile::trapdoor_Id: - allowed = true; - break; - default: - break; - } - } + if (getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches) != 0) { + switch (tile->id) { + case Tile::door_wood_Id: + case Tile::button_stone_Id: + case Tile::button_wood_Id: + case Tile::lever_Id: + case Tile::fenceGate_Id: + case Tile::trapdoor_Id: + allowed = true; + break; + default: + break; + } + } - if(getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseContainers) != 0) - { - switch(tile->id) - { - case Tile::chest_Id: - case Tile::furnace_Id: - case Tile::furnace_lit_Id: - case Tile::dispenser_Id: - case Tile::brewingStand_Id: - case Tile::enchantTable_Id: - case Tile::workBench_Id: - case Tile::anvil_Id: - case Tile::enderChest_Id: - allowed = true; - break; - default: - break; - } - } + if (getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseContainers) != 0) { + switch (tile->id) { + case Tile::chest_Id: + case Tile::furnace_Id: + case Tile::furnace_lit_Id: + case Tile::dispenser_Id: + case Tile::brewingStand_Id: + case Tile::enchantTable_Id: + case Tile::workBench_Id: + case Tile::anvil_Id: + case Tile::enderChest_Id: + allowed = true; + break; + default: + break; + } + } - if(!allowed && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) == 0) - { - switch(tile->id) - { - case Tile::door_wood_Id: - case Tile::button_stone_Id: - case Tile::button_wood_Id: - case Tile::lever_Id: - case Tile::fenceGate_Id: - case Tile::trapdoor_Id: - case Tile::chest_Id: - case Tile::furnace_Id: - case Tile::furnace_lit_Id: - case Tile::dispenser_Id: - case Tile::brewingStand_Id: - case Tile::enchantTable_Id: - case Tile::workBench_Id: - case Tile::anvil_Id: - case Tile::enderChest_Id: - allowed = false; - break; - default: - allowed = true; - break; - } - } - } + if (!allowed && getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotBuild) == 0) { + switch (tile->id) { + case Tile::door_wood_Id: + case Tile::button_stone_Id: + case Tile::button_wood_Id: + case Tile::lever_Id: + case Tile::fenceGate_Id: + case Tile::trapdoor_Id: + case Tile::chest_Id: + case Tile::furnace_Id: + case Tile::furnace_lit_Id: + case Tile::dispenser_Id: + case Tile::brewingStand_Id: + case Tile::enchantTable_Id: + case Tile::workBench_Id: + case Tile::anvil_Id: + case Tile::enderChest_Id: + allowed = false; + break; + default: + allowed = true; + break; + } + } + } - return allowed; + return allowed; } -bool Player::isAllowedToUse(std::shared_ptr item) -{ - bool allowed = true; - if(item != NULL && app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) - { - if(getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) != 0) - { - allowed = false; - } +bool Player::isAllowedToUse(std::shared_ptr item) { + bool allowed = true; + if (item != NULL && + app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) { + if (getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) != + 0) { + allowed = false; + } - // 4J Stu - TU8 Players should always be able to eat food items, even if the build option is turned of - switch(item->id) - { - // food - case Item::mushroomStew_Id: - case Item::apple_Id: - case Item::bread_Id: - case Item::porkChop_raw_Id: - case Item::porkChop_cooked_Id: - case Item::apple_gold_Id: - case Item::fish_raw_Id: - case Item::fish_cooked_Id: - case Item::cookie_Id: - case Item::beef_cooked_Id: - case Item::beef_raw_Id: - case Item::chicken_cooked_Id: - case Item::chicken_raw_Id: - case Item::melon_Id: - case Item::rotten_flesh_Id: - // bow - case Item::bow_Id: - case Item::sword_diamond_Id: - case Item::sword_gold_Id: - case Item::sword_iron_Id: - case Item::sword_stone_Id: - case Item::sword_wood_Id: - allowed = true; - break; - default: - break; - } - } + // 4J Stu - TU8 Players should always be able to eat food items, even if + // the build option is turned of + switch (item->id) { + // food + case Item::mushroomStew_Id: + case Item::apple_Id: + case Item::bread_Id: + case Item::porkChop_raw_Id: + case Item::porkChop_cooked_Id: + case Item::apple_gold_Id: + case Item::fish_raw_Id: + case Item::fish_cooked_Id: + case Item::cookie_Id: + case Item::beef_cooked_Id: + case Item::beef_raw_Id: + case Item::chicken_cooked_Id: + case Item::chicken_raw_Id: + case Item::melon_Id: + case Item::rotten_flesh_Id: + // bow + case Item::bow_Id: + case Item::sword_diamond_Id: + case Item::sword_gold_Id: + case Item::sword_iron_Id: + case Item::sword_stone_Id: + case Item::sword_wood_Id: + allowed = true; + break; + default: + break; + } + } - return allowed; + return allowed; } -bool Player::isAllowedToInteract(std::shared_ptr target) -{ - bool allowed = true; - if(app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) - { - if (target->GetType() == eTYPE_MINECART) - { - if (getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseContainers) == 0) - { - std::shared_ptr minecart = std::dynamic_pointer_cast( target ); - if (minecart->type == Minecart::CHEST) - allowed = false; - } +bool Player::isAllowedToInteract(std::shared_ptr target) { + bool allowed = true; + if (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) { + if (target->GetType() == eTYPE_MINECART) { + if (getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseContainers) == 0) { + std::shared_ptr minecart = + std::dynamic_pointer_cast(target); + if (minecart->type == Minecart::CHEST) allowed = false; + } - } - else - { - if(getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild) != 0) - { - allowed = false; - } + } else { + if (getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotBuild) != 0) { + allowed = false; + } - if(getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine) != 0) - { - allowed = false; - } - } - } + if (getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotMine) != 0) { + allowed = false; + } + } + } - return allowed; + return allowed; } -bool Player::isAllowedToMine() -{ - bool allowed = true; - if(app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) - { - if(getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine) != 0) - { - allowed = false; - } - } - return allowed; +bool Player::isAllowedToMine() { + bool allowed = true; + if (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) { + if (getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine) != + 0) { + allowed = false; + } + } + return allowed; } -bool Player::isAllowedToAttackPlayers() -{ - bool allowed = true; - if( hasInvisiblePrivilege() || ((app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackPlayers)) ) - { - allowed = false; - } - return allowed; +bool Player::isAllowedToAttackPlayers() { + bool allowed = true; + if (hasInvisiblePrivilege() || + ((app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) && + getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackPlayers))) { + allowed = false; + } + return allowed; } -bool Player::isAllowedToAttackAnimals() -{ - bool allowed = true; - if( (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackAnimals) ) - { - allowed = false; - } - return allowed; +bool Player::isAllowedToAttackAnimals() { + bool allowed = true; + if ((app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) && + getPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackAnimals)) { + allowed = false; + } + return allowed; } -bool Player::isAllowedToHurtEntity(std::shared_ptr target) -{ - bool allowed = true; +bool Player::isAllowedToHurtEntity(std::shared_ptr target) { + bool allowed = true; - if(!isAllowedToMine()) - { - switch(target->GetType()) - { - case eTYPE_HANGING_ENTITY: - case eTYPE_PAINTING: - case eTYPE_ITEM_FRAME: + if (!isAllowedToMine()) { + switch (target->GetType()) { + case eTYPE_HANGING_ENTITY: + case eTYPE_PAINTING: + case eTYPE_ITEM_FRAME: - // 4J-JEV: Fix for #88212, - // Untrusted players shouldn't be able to damage minecarts or boats. - case eTYPE_BOAT: - case eTYPE_MINECART: + // 4J-JEV: Fix for #88212, + // Untrusted players shouldn't be able to damage minecarts or + // boats. + case eTYPE_BOAT: + case eTYPE_MINECART: - allowed = false; - break; - default: - break; - }; - } - return allowed; + allowed = false; + break; + default: + break; + }; + } + return allowed; } -bool Player::isAllowedToFly() -{ - bool allowed = false; - if(app.GetGameHostOption(eGameHostOption_HostCanFly) != 0 && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanFly) != 0) - { - allowed = true; - } - return allowed; +bool Player::isAllowedToFly() { + bool allowed = false; + if (app.GetGameHostOption(eGameHostOption_HostCanFly) != 0 && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanFly) != 0) { + allowed = true; + } + return allowed; } -bool Player::isAllowedToIgnoreExhaustion() -{ - bool allowed = false; - if( (app.GetGameHostOption(eGameHostOption_HostCanChangeHunger) != 0 && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_ClassicHunger) != 0) || - (isAllowedToFly() && abilities.flying) ) - { - allowed = true; - } - return allowed; +bool Player::isAllowedToIgnoreExhaustion() { + bool allowed = false; + if ((app.GetGameHostOption(eGameHostOption_HostCanChangeHunger) != 0 && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_ClassicHunger) != + 0) || + (isAllowedToFly() && abilities.flying)) { + allowed = true; + } + return allowed; } -bool Player::isAllowedToTeleport() -{ - bool allowed = false; - if( isModerator() && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanTeleport) != 0) - { - allowed = true; - } - return allowed; +bool Player::isAllowedToTeleport() { + bool allowed = false; + if (isModerator() && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanTeleport) != 0) { + allowed = true; + } + return allowed; } -bool Player::hasInvisiblePrivilege() -{ - bool enabled = false; - if(app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) != 0 && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invisible) != 0) - { - enabled = true; - } - return enabled; +bool Player::hasInvisiblePrivilege() { + bool enabled = false; + if (app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) != 0 && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invisible) != 0) { + enabled = true; + } + return enabled; } -bool Player::hasInvulnerablePrivilege() -{ - bool enabled = false; - if(app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) != 0 && getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invulnerable) != 0) - { - enabled = true; - } - return enabled; +bool Player::hasInvulnerablePrivilege() { + bool enabled = false; + if (app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) != 0 && + getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invulnerable) != + 0) { + enabled = true; + } + return enabled; } -bool Player::isModerator() -{ - return getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Op) != 0; +bool Player::isModerator() { + return getPlayerGamePrivilege(Player::ePlayerGamePrivilege_Op) != 0; } -void Player::enableAllPlayerPrivileges(unsigned int &uigamePrivileges, bool enable) -{ - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CannotMine, enable?0:1); - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CannotBuild, enable?0:1); - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CannotAttackPlayers, enable?0:1); - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CannotAttackAnimals, enable?0:1); - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches, enable?1:0); - Player::setPlayerGamePrivilege(uigamePrivileges, Player::ePlayerGamePrivilege_CanUseContainers, enable?1:0); +void Player::enableAllPlayerPrivileges(unsigned int& uigamePrivileges, + bool enable) { + Player::setPlayerGamePrivilege(uigamePrivileges, + Player::ePlayerGamePrivilege_CannotMine, + enable ? 0 : 1); + Player::setPlayerGamePrivilege(uigamePrivileges, + Player::ePlayerGamePrivilege_CannotBuild, + enable ? 0 : 1); + Player::setPlayerGamePrivilege( + uigamePrivileges, Player::ePlayerGamePrivilege_CannotAttackPlayers, + enable ? 0 : 1); + Player::setPlayerGamePrivilege( + uigamePrivileges, Player::ePlayerGamePrivilege_CannotAttackAnimals, + enable ? 0 : 1); + Player::setPlayerGamePrivilege( + uigamePrivileges, Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches, + enable ? 1 : 0); + Player::setPlayerGamePrivilege( + uigamePrivileges, Player::ePlayerGamePrivilege_CanUseContainers, + enable ? 1 : 0); } -void Player::enableAllPlayerPrivileges(bool enable) -{ - Player::enableAllPlayerPrivileges(m_uiGamePrivileges,enable); +void Player::enableAllPlayerPrivileges(bool enable) { + Player::enableAllPlayerPrivileges(m_uiGamePrivileges, enable); } -bool Player::canCreateParticles() -{ - return !hasInvisiblePrivilege(); +bool Player::canCreateParticles() { return !hasInvisiblePrivilege(); } + +std::vector* Player::GetAdditionalModelParts() { + if (m_ppAdditionalModelParts == NULL && !m_bCheckedForModelParts) { + bool hasCustomTexture = !customTextureUrl.empty(); + bool customTextureIsDefaultSkin = + customTextureUrl.substr(0, 3).compare(L"def") == 0; + + // see if we can find the parts + m_ppAdditionalModelParts = app.GetAdditionalModelParts(m_dwSkinId); + + // If it's a default texture (which has no parts), we have the parts, or + // we already have the texture (in which case we should have parts if + // there are any) then we are done + if (!hasCustomTexture || customTextureIsDefaultSkin || + m_ppAdditionalModelParts != NULL || + app.IsFileInMemoryTextures(customTextureUrl)) { + m_bCheckedForModelParts = true; + } + if (m_ppAdditionalModelParts == NULL && !m_bCheckedDLCForModelParts) { + m_bCheckedDLCForModelParts = true; + + // we don't have the data from the dlc skin yet + app.DebugPrintf( + "m_bCheckedForModelParts Couldn't get model parts for skin " + "%X\n", + m_dwSkinId); + + // do we have it from the DLC pack? + DLCSkinFile* pDLCSkinFile = + app.m_dlcManager.getSkinFile(this->customTextureUrl); + + if (pDLCSkinFile != NULL) { + const int additionalBoxCount = + pDLCSkinFile->getAdditionalBoxesCount(); + if (additionalBoxCount != 0) { + app.DebugPrintf( + "m_bCheckedForModelParts Got model parts from DLCskin " + "for skin %X\n", + m_dwSkinId); + m_ppAdditionalModelParts = app.SetAdditionalSkinBoxes( + m_dwSkinId, pDLCSkinFile->getAdditionalBoxes()); + } + + app.SetAnimOverrideBitmask( + pDLCSkinFile->getSkinID(), + pDLCSkinFile->getAnimOverrideBitmask()); + + m_bCheckedForModelParts = true; + } + } + + if (m_bCheckedForModelParts) + setAnimOverrideBitmask(getSkinAnimOverrideBitmask(m_dwSkinId)); + } + return m_ppAdditionalModelParts; } -std::vector *Player::GetAdditionalModelParts() -{ - if(m_ppAdditionalModelParts==NULL && !m_bCheckedForModelParts) - { - bool hasCustomTexture = !customTextureUrl.empty(); - bool customTextureIsDefaultSkin = customTextureUrl.substr(0,3).compare(L"def") == 0; - - // see if we can find the parts - m_ppAdditionalModelParts=app.GetAdditionalModelParts(m_dwSkinId); - - // If it's a default texture (which has no parts), we have the parts, or we already have the texture (in which case we should have parts if there are any) then we are done - if(!hasCustomTexture || customTextureIsDefaultSkin || m_ppAdditionalModelParts != NULL || app.IsFileInMemoryTextures(customTextureUrl)) - { - m_bCheckedForModelParts=true; - } - if(m_ppAdditionalModelParts == NULL && !m_bCheckedDLCForModelParts) - { - m_bCheckedDLCForModelParts = true; - - // we don't have the data from the dlc skin yet - app.DebugPrintf("m_bCheckedForModelParts Couldn't get model parts for skin %X\n",m_dwSkinId); - - // do we have it from the DLC pack? - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(this->customTextureUrl); - - if(pDLCSkinFile!=NULL) - { - const int additionalBoxCount = pDLCSkinFile->getAdditionalBoxesCount(); - if(additionalBoxCount != 0) - { - app.DebugPrintf("m_bCheckedForModelParts Got model parts from DLCskin for skin %X\n",m_dwSkinId); - m_ppAdditionalModelParts=app.SetAdditionalSkinBoxes(m_dwSkinId,pDLCSkinFile->getAdditionalBoxes()); - } - - app.SetAnimOverrideBitmask(pDLCSkinFile->getSkinID(),pDLCSkinFile->getAnimOverrideBitmask()); - - m_bCheckedForModelParts=true; - } - } - - if(m_bCheckedForModelParts) setAnimOverrideBitmask(getSkinAnimOverrideBitmask(m_dwSkinId)); - } - return m_ppAdditionalModelParts; -} - -void Player::SetAdditionalModelParts(std::vector *ppAdditionalModelParts) -{ - m_ppAdditionalModelParts=ppAdditionalModelParts; +void Player::SetAdditionalModelParts( + std::vector* ppAdditionalModelParts) { + m_ppAdditionalModelParts = ppAdditionalModelParts; } #if defined(__PS3__) || defined(__ORBIS__) -Player::ePlayerNameValidState Player::GetPlayerNameValidState(void) -{ - return m_ePlayerNameValidState; +Player::ePlayerNameValidState Player::GetPlayerNameValidState(void) { + return m_ePlayerNameValidState; } -void Player::SetPlayerNameValidState(bool bState) -{ - if(bState) - { - m_ePlayerNameValidState=ePlayerNameValid_True; - } - else - { - m_ePlayerNameValidState=ePlayerNameValid_False; - - } +void Player::SetPlayerNameValidState(bool bState) { + if (bState) { + m_ePlayerNameValidState = ePlayerNameValid_True; + } else { + m_ePlayerNameValidState = ePlayerNameValid_False; + } } #endif diff --git a/Minecraft.World/Player/Player.h b/Minecraft.World/Player/Player.h index 62f0a018d..06897b9df 100644 --- a/Minecraft.World/Player/Player.h +++ b/Minecraft.World/Player/Player.h @@ -29,523 +29,583 @@ class Merchant; class PlayerEnderChestContainer; class GameType; -class Player : public Mob, public CommandSender -{ +class Player : public Mob, public CommandSender { public: - static const int MAX_NAME_LENGTH = 16 + 4; - static const int MAX_HEALTH = 20; - static const int SWING_DURATION = 6; - static const int SLEEP_DURATION = 100; - static const int WAKE_UP_DURATION = 10; + static const int MAX_NAME_LENGTH = 16 + 4; + static const int MAX_HEALTH = 20; + static const int SWING_DURATION = 6; + static const int SLEEP_DURATION = 100; + static const int WAKE_UP_DURATION = 10; - static const int CHAT_VISIBILITY_FULL = 0; - static const int CHAT_VISIBILITY_SYSTEM = 1; - static const int CHAT_VISIBILITY_HIDDEN = 2; + static const int CHAT_VISIBILITY_FULL = 0; + static const int CHAT_VISIBILITY_SYSTEM = 1; + static const int CHAT_VISIBILITY_HIDDEN = 2; - // 4J-PB - added for a red death fade in the gui - static const int DEATHFADE_DURATION = 21; -private: - static const int FLY_ACHIEVEMENT_SPEED = 25; - - static const int DATA_PLAYER_FLAGS_ID = 16; - static const int DATA_PLAYER_RUNNING_ID = 17; - -public: - std::shared_ptr inventory; + // 4J-PB - added for a red death fade in the gui + static const int DEATHFADE_DURATION = 21; private: - std::shared_ptr enderChestInventory; + static const int FLY_ACHIEVEMENT_SPEED = 25; + + static const int DATA_PLAYER_FLAGS_ID = 16; + static const int DATA_PLAYER_RUNNING_ID = 17; public: - AbstractContainerMenu *inventoryMenu; - AbstractContainerMenu *containerMenu; - -protected: - FoodData foodData; - int jumpTriggerTime; - -public: - std::uint8_t userType; - int score; - float oBob, bob; - bool swinging; - int swingTime; - - std::wstring name; - int dimension; - int takeXpDelay; - - // 4J-PB - track custom skin - unsigned int m_uiPlayerCurrentSkin; - void ChangePlayerSkin(); - - // 4J-PB - not needed, since cutomtextureurl2 is the same thing std::wstring cloakTexture; - - double xCloakO, yCloakO, zCloakO; - double xCloak, yCloak, zCloak; - - // 4J-HEG - store display name, added for Xbox One - std::wstring displayName; - -protected: - // player sleeping in bed? - bool m_isSleeping; - -public: - Pos *bedPosition; + std::shared_ptr inventory; private: - int sleepCounter; // animation timer - int deathFadeCounter; // animation timer + std::shared_ptr enderChestInventory; public: - float bedOffsetX, bedOffsetY, bedOffsetZ; - Stats *stats; + AbstractContainerMenu* inventoryMenu; + AbstractContainerMenu* containerMenu; + +protected: + FoodData foodData; + int jumpTriggerTime; + +public: + std::uint8_t userType; + int score; + float oBob, bob; + bool swinging; + int swingTime; + + std::wstring name; + int dimension; + int takeXpDelay; + + // 4J-PB - track custom skin + unsigned int m_uiPlayerCurrentSkin; + void ChangePlayerSkin(); + + // 4J-PB - not needed, since cutomtextureurl2 is the same thing std::wstring + // cloakTexture; + + double xCloakO, yCloakO, zCloakO; + double xCloak, yCloak, zCloak; + + // 4J-HEG - store display name, added for Xbox One + std::wstring displayName; + +protected: + // player sleeping in bed? + bool m_isSleeping; + +public: + Pos* bedPosition; private: - Pos *respawnPosition; - Pos *minecartAchievementPos; - - //4J Gordon: These are in cms, every time they go > 1m they are entered into the stats - int distanceWalk, distanceSwim, distanceFall, distanceClimb, distanceMinecart, distanceBoat, distancePig; + int sleepCounter; // animation timer + int deathFadeCounter; // animation timer public: - int changingDimensionDelay; - -protected: - bool isInsidePortal; - -public: - float portalTime, oPortalTime; - - Abilities abilities; - - int experienceLevel, totalExperience; - float experienceProgress; - - // 4J Stu - Made protected so that we can access it from MultiPlayerLocalPlayer -protected: - std::shared_ptr useItem; - int useItemDuration; - -protected: - float defaultWalkSpeed; - float defaultFlySpeed; - -public: - - eINSTANCEOF GetType() { return eTYPE_PLAYER; } - - // 4J Added to default init - void _init(); - - Player(Level *level); - virtual ~Player(); - - virtual int getMaxHealth(); -protected: - virtual void defineSynchedData(); - -public: - std::shared_ptr getUseItem(); - int getUseItemDuration(); - bool isUsingItem(); int getTicksUsingItem(); - void releaseUsingItem(); - void stopUsingItem(); - virtual bool isBlocking(); - - virtual void tick(); - -protected: - void spawnEatParticles(std::shared_ptr useItem, int count); - virtual void completeUsingItem(); - -public: - virtual void handleEntityEvent(std::uint8_t id); - -protected: - bool isImmobile(); - virtual void closeContainer(); - -public: - virtual void ride(std::shared_ptr e); - void prepareCustomTextures(); - virtual void rideTick(); - virtual void resetPos(); + float bedOffsetX, bedOffsetY, bedOffsetZ; + Stats* stats; private: - int getCurrentSwingDuration(); + Pos* respawnPosition; + Pos* minecartAchievementPos; -protected: - virtual void serverAiStep(); + // 4J Gordon: These are in cms, every time they go > 1m they are entered + // into the stats + int distanceWalk, distanceSwim, distanceFall, distanceClimb, + distanceMinecart, distanceBoat, distancePig; public: - virtual void aiStep(); + int changingDimensionDelay; + +protected: + bool isInsidePortal; + +public: + float portalTime, oPortalTime; + + Abilities abilities; + + int experienceLevel, totalExperience; + float experienceProgress; + + // 4J Stu - Made protected so that we can access it from + // MultiPlayerLocalPlayer +protected: + std::shared_ptr useItem; + int useItemDuration; + +protected: + float defaultWalkSpeed; + float defaultFlySpeed; + +public: + eINSTANCEOF GetType() { return eTYPE_PLAYER; } + + // 4J Added to default init + void _init(); + + Player(Level* level); + virtual ~Player(); + + virtual int getMaxHealth(); + +protected: + virtual void defineSynchedData(); + +public: + std::shared_ptr getUseItem(); + int getUseItemDuration(); + bool isUsingItem(); + int getTicksUsingItem(); + void releaseUsingItem(); + void stopUsingItem(); + virtual bool isBlocking(); + + virtual void tick(); + +protected: + void spawnEatParticles(std::shared_ptr useItem, int count); + virtual void completeUsingItem(); + +public: + virtual void handleEntityEvent(std::uint8_t id); + +protected: + bool isImmobile(); + virtual void closeContainer(); + +public: + virtual void ride(std::shared_ptr e); + void prepareCustomTextures(); + virtual void rideTick(); + virtual void resetPos(); private: - virtual void touch(std::shared_ptr entity); - -public: - //bool addResource(int resource); // 4J - Removed 1.0.1 - int getScore(); - virtual void die(DamageSource *source); - void awardKillScore(std::shared_ptr victim, int score); + int getCurrentSwingDuration(); protected: - virtual int decreaseAirSupply(int currentSupply); + virtual void serverAiStep(); public: - virtual bool isShootable(); - bool isCreativeModeAllowed(); - virtual std::shared_ptr drop(); - std::shared_ptr drop(std::shared_ptr item); - std::shared_ptr drop(std::shared_ptr item, bool randomly); - -protected: - virtual void reallyDrop(std::shared_ptr thrownItem); - -public: - float getDestroySpeed(Tile *tile); - bool canDestroy(Tile *tile); - virtual void readAdditionalSaveData(CompoundTag *entityTag); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - static Pos *getRespawnPosition(Level *level, CompoundTag *entityTag); - virtual bool openContainer(std::shared_ptr container); // 4J - added bool return - virtual bool startEnchanting(int x, int y, int z); // 4J - added bool return - virtual bool startRepairing(int x, int y, int z); // 4J - added bool return - virtual bool startCrafting(int x, int y, int z); // 4J - added boo return - virtual void take(std::shared_ptr e, int orgCount); - virtual float getHeadHeight(); - - // 4J-PB - added to keep the code happy with the change to make the third person view per player - virtual int ThirdPersonView() {return 0;} - virtual void SetThirdPersonView(int val) {} - -protected: - virtual void setDefaultHeadHeight(); - -public: - std::shared_ptr fishing; - - virtual bool hurt(DamageSource *source, int dmg); - -protected: - virtual int getDamageAfterMagicAbsorb(DamageSource *damageSource, int damage); - virtual bool isPlayerVersusPlayer(); - void directAllTameWolvesOnTarget(std::shared_ptr target, bool skipSitting); - virtual void hurtArmor(int damage); - -public: - virtual int getArmorValue(); - float getArmorCoverPercentage(); - -protected: - virtual void actuallyHurt(DamageSource *source, int dmg); - -public: - using Entity::interact; - - virtual bool openFurnace(std::shared_ptr container); // 4J - added bool return - virtual bool openTrap(std::shared_ptr container); // 4J - added bool return - virtual void openTextEdit(std::shared_ptr sign); - virtual bool openBrewingStand(std::shared_ptr brewingStand); // 4J - added bool return - virtual bool openTrading(std::shared_ptr traderTarget); // 4J - added bool return - virtual void openItemInstanceGui(std::shared_ptr itemInstance); - virtual bool interact(std::shared_ptr entity); - virtual std::shared_ptr getSelectedItem(); - void removeSelectedItem(); - virtual double getRidingHeight(); - virtual void swing(); - virtual void attack(std::shared_ptr entity); - virtual void crit(std::shared_ptr entity); - virtual void magicCrit(std::shared_ptr entity); - virtual void respawn(); - -protected: - static void animateRespawn(std::shared_ptr player, Level *level); - -public: - Slot *getInventorySlot(int slotId); - virtual void remove(); - virtual bool isInWall(); - virtual bool isLocalPlayer(); - - enum BedSleepingResult - { - OK, NOT_POSSIBLE_HERE, NOT_POSSIBLE_NOW, TOO_FAR_AWAY, OTHER_PROBLEM, NOT_SAFE - }; - - virtual BedSleepingResult startSleepInBed(int x, int y, int z, bool bTestUse = false); + virtual void aiStep(); private: - void setBedOffset(int bedDirection); + virtual void touch(std::shared_ptr entity); public: - /** - * - * @param forcefulWakeUp - * If the player has been forced to wake up. When this happens, - * the client will skip the wake-up animation. For example, when - * the player is hurt or the bed is destroyed. - * @param updateLevelList - * If the level's sleeping player list needs to be updated. This - * is usually the case. - * @param saveRespawnPoint - * TODO - */ - virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); - -private: - bool checkBed(); - -public: - static Pos *checkBedValidRespawnPosition(Level *level, Pos *pos); - float getSleepRotation(); - bool isSleeping(); - bool isSleepingLongEnough(); - int getSleepTimer(); - int getDeathFadeTimer(); + // bool addResource(int resource); // 4J - Removed 1.0.1 + int getScore(); + virtual void die(DamageSource* source); + void awardKillScore(std::shared_ptr victim, int score); protected: - bool getPlayerFlag(int flag); - void setPlayerFlag(int flag, bool value); + virtual int decreaseAirSupply(int currentSupply); public: - /** - * This method is currently only relevant to client-side players. It will - * try to load the messageId from the language file and display it to the - * client. - */ - virtual void displayClientMessage(int messageId); - Pos *getRespawnPosition(); - void setRespawnPosition(Pos *respawnPosition); - virtual void awardStat(Stat *stat, byteArray param); + virtual bool isShootable(); + bool isCreativeModeAllowed(); + virtual std::shared_ptr drop(); + std::shared_ptr drop(std::shared_ptr item); + std::shared_ptr drop(std::shared_ptr item, + bool randomly); protected: - void jumpFromGround(); + virtual void reallyDrop(std::shared_ptr thrownItem); public: - void travel(float xa, float ya); - void checkMovementStatistiscs(double dx, double dy, double dz); + float getDestroySpeed(Tile* tile); + bool canDestroy(Tile* tile); + virtual void readAdditionalSaveData(CompoundTag* entityTag); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + static Pos* getRespawnPosition(Level* level, CompoundTag* entityTag); + virtual bool openContainer( + std::shared_ptr container); // 4J - added bool return + virtual bool startEnchanting(int x, int y, + int z); // 4J - added bool return + virtual bool startRepairing(int x, int y, int z); // 4J - added bool return + virtual bool startCrafting(int x, int y, int z); // 4J - added boo return + virtual void take(std::shared_ptr e, int orgCount); + virtual float getHeadHeight(); -private: - void checkRidingStatistiscs(double dx, double dy, double dz); - - bool m_bAwardedOnARail; + // 4J-PB - added to keep the code happy with the change to make the third + // person view per player + virtual int ThirdPersonView() { return 0; } + virtual void SetThirdPersonView(int val) {} protected: - virtual void causeFallDamage(float distance); + virtual void setDefaultHeadHeight(); public: - virtual void killed(std::shared_ptr mob); - virtual Icon *getItemInHandIcon(std::shared_ptr item, int layer); - virtual std::shared_ptr getArmor(int pos); - virtual void handleInsidePortal(); + std::shared_ptr fishing; - void increaseXp(int i); - virtual void withdrawExperienceLevels(int amount); - int getXpNeededForNextLevel(); - -private: - void levelUp(); - -public: - void causeFoodExhaustion(float amount); - FoodData *getFoodData(); - bool canEat(bool magicalItem); - bool isHurt(); - virtual void startUsingItem(std::shared_ptr instance, int duration); - bool mayBuild(int x, int y, int z); + virtual bool hurt(DamageSource* source, int dmg); protected: - virtual int getExperienceReward(std::shared_ptr killedBy); - virtual bool isAlwaysExperienceDropper(); + virtual int getDamageAfterMagicAbsorb(DamageSource* damageSource, + int damage); + virtual bool isPlayerVersusPlayer(); + void directAllTameWolvesOnTarget(std::shared_ptr target, + bool skipSitting); + virtual void hurtArmor(int damage); public: - virtual std::wstring getAName(); - - virtual void changeDimension(int i); - virtual void restoreFrom(std::shared_ptr oldPlayer, bool restoreAll); + virtual int getArmorValue(); + float getArmorCoverPercentage(); protected: - bool makeStepSound(); + virtual void actuallyHurt(DamageSource* source, int dmg); public: - void onUpdateAbilities(); - void setGameMode(GameType *mode); - std::wstring getName(); - std::wstring getDisplayName(); // 4J added + using Entity::interact; - //Language getLanguage() { return Language.getInstance(); } - //String localize(String key, Object... args) { return getLanguage().getElement(key, args); } - - std::shared_ptr getEnderChestInventory(); - -public: - virtual std::shared_ptr getCarriedItem(); - - virtual bool isInvisibleTo(std::shared_ptr player); - - static int hash_fnct(const std::shared_ptr k); - static bool eq_test(const std::shared_ptr x, const std::shared_ptr y); - - // 4J Stu - Added to allow callback to tutorial to stay within Minecraft.Client - // Overidden in LocalPlayer - virtual void onCrafted(std::shared_ptr item) {} - - // 4J Overriding this so that we can have some different default skins - virtual int getTexture(); // 4J changed from std::wstring to int - void setPlayerDefaultSkin(EDefaultSkins skin); - EDefaultSkins getPlayerDefaultSkin() { return m_skinIndex; } - virtual void setCustomSkin(std::uint32_t skinId); - std::uint32_t getCustomSkin() {return m_dwSkinId; } - virtual void setCustomCape(std::uint32_t capeId); - std::uint32_t getCustomCape() {return m_dwCapeId; } - - static std::uint32_t getCapeIdFromPath(const std::wstring &cape); - static std::wstring getCapePathFromId(std::uint32_t capeId); - static unsigned int getSkinAnimOverrideBitmask(std::uint32_t skinId); - - // 4J Added - void setXuid(PlayerUID xuid); - PlayerUID getXuid() { return m_xuid; } - void setOnlineXuid(PlayerUID xuid) { m_OnlineXuid = xuid; } - PlayerUID getOnlineXuid() { return m_OnlineXuid; } - void setUUID(const std::wstring &UUID) { m_UUID = UUID; } - std::wstring getUUID() { return m_UUID; } - - void setPlayerIndex(std::uint8_t index) { m_playerIndex = index; } - std::uint8_t getPlayerIndex() { return m_playerIndex; } - - void setIsGuest(bool bVal) { m_bIsGuest = bVal; } - bool isGuest() { return m_bIsGuest; } - - void setShowOnMaps(bool bVal) { m_bShownOnMaps = bVal; } - bool canShowOnMaps() { return m_bShownOnMaps && !getPlayerGamePrivilege(ePlayerGamePrivilege_Invisible); } - - virtual void sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L"") { } -private: - PlayerUID m_xuid; - PlayerUID m_OnlineXuid; + virtual bool openFurnace(std::shared_ptr + container); // 4J - added bool return + virtual bool openTrap(std::shared_ptr + container); // 4J - added bool return + virtual void openTextEdit(std::shared_ptr sign); + virtual bool openBrewingStand(std::shared_ptr + brewingStand); // 4J - added bool return + virtual bool openTrading( + std::shared_ptr traderTarget); // 4J - added bool return + virtual void openItemInstanceGui( + std::shared_ptr itemInstance); + virtual bool interact(std::shared_ptr entity); + virtual std::shared_ptr getSelectedItem(); + void removeSelectedItem(); + virtual double getRidingHeight(); + virtual void swing(); + virtual void attack(std::shared_ptr entity); + virtual void crit(std::shared_ptr entity); + virtual void magicCrit(std::shared_ptr entity); + virtual void respawn(); protected: - std::wstring m_UUID; // 4J Added + static void animateRespawn(std::shared_ptr player, Level* level); - bool m_bShownOnMaps; +public: + Slot* getInventorySlot(int slotId); + virtual void remove(); + virtual bool isInWall(); + virtual bool isLocalPlayer(); - bool m_bIsGuest; + enum BedSleepingResult { + OK, + NOT_POSSIBLE_HERE, + NOT_POSSIBLE_NOW, + TOO_FAR_AWAY, + OTHER_PROBLEM, + NOT_SAFE + }; + + virtual BedSleepingResult startSleepInBed(int x, int y, int z, + bool bTestUse = false); private: - EDefaultSkins m_skinIndex; - std::uint32_t m_dwSkinId,m_dwCapeId; - - // 4J Added - Used to show which colour the player is on the map/behind their name - std::uint8_t m_playerIndex; - - // 4J-PB - to track debug options from the server player - unsigned int m_uiDebugOptions; + void setBedOffset(int bedDirection); public: - void SetDebugOptions(unsigned int uiVal) { m_uiDebugOptions=uiVal;} - unsigned int GetDebugOptions(void) { return m_uiDebugOptions;} + /** + * + * @param forcefulWakeUp + * If the player has been forced to wake up. When this happens, + * the client will skip the wake-up animation. For example, when + * the player is hurt or the bed is destroyed. + * @param updateLevelList + * If the level's sleeping player list needs to be updated. This + * is usually the case. + * @param saveRespawnPoint + * TODO + */ + virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint); - void StopSleeping() {} - -public: - // If you add things here, you should also add a message to ClientConnection::displayPrivilegeChanges to alert players to changes - enum EPlayerGamePrivileges - { - ePlayerGamePrivilege_CannotMine = 0, // Only checked if trust system is on - ePlayerGamePrivilege_CannotBuild, // Only checked if trust system is on - ePlayerGamePrivilege_CannotAttackMobs, // Only checked if trust system is on - ePlayerGamePrivilege_CannotAttackPlayers, //Only checked if trust system is on - ePlayerGamePrivilege_Op, - ePlayerGamePrivilege_CanFly, - ePlayerGamePrivilege_ClassicHunger, - ePlayerGamePrivilege_Invisible, - ePlayerGamePrivilege_Invulnerable, - - ePlayerGamePrivilege_CreativeMode, // Used only to transfer across network, should never be used to determine if a player is in creative mode - - ePlayerGamePrivilege_CannotAttackAnimals, // Only checked if trust system is on - ePlayerGamePrivilege_CanUseDoorsAndSwitches, // Only checked if trust system is on - ePlayerGamePrivilege_CanUseContainers, // Only checked if trust system is on - - ePlayerGamePrivilege_CanToggleInvisible, - ePlayerGamePrivilege_CanToggleFly, - ePlayerGamePrivilege_CanToggleClassicHunger, - ePlayerGamePrivilege_CanTeleport, - - // Currently enum is used to bitshift into an unsigned int - ePlayerGamePrivilege_MAX = 32, - ePlayerGamePrivilege_All = 33, - ePlayerGamePrivilege_HOST, - }; private: - // 4J Added - Used to track what actions players have been allowed to perform by the host - unsigned int m_uiGamePrivileges; - - unsigned int getPlayerGamePrivilege(EPlayerGamePrivileges privilege); -public: - unsigned int getAllPlayerGamePrivileges() { return getPlayerGamePrivilege(ePlayerGamePrivilege_All); } - - static unsigned int getPlayerGamePrivilege(unsigned int uiGamePrivileges, EPlayerGamePrivileges privilege); - void setPlayerGamePrivilege(EPlayerGamePrivileges privilege, unsigned int value); - static void setPlayerGamePrivilege(unsigned int &uiGamePrivileges, EPlayerGamePrivileges privilege, unsigned int value); - - bool isAllowedToUse(Tile *tile); - bool isAllowedToUse(std::shared_ptr item); - bool isAllowedToInteract(std::shared_ptr target); - bool isAllowedToMine(); - bool isAllowedToAttackPlayers(); - bool isAllowedToAttackAnimals(); - bool isAllowedToHurtEntity(std::shared_ptr target); - bool isAllowedToFly(); - bool isAllowedToIgnoreExhaustion(); - bool isAllowedToTeleport(); - bool hasInvisiblePrivilege(); - bool hasInvulnerablePrivilege(); - bool isModerator(); - - static void enableAllPlayerPrivileges(unsigned int &uigamePrivileges, bool enable); - void enableAllPlayerPrivileges(bool enable); - - virtual bool canCreateParticles(); + bool checkBed(); public: - // 4J Stu - Added hooks for the game rules - virtual void handleCollectItem(std::shared_ptr item) {} + static Pos* checkBedValidRespawnPosition(Level* level, Pos* pos); + float getSleepRotation(); + bool isSleeping(); + bool isSleepingLongEnough(); + int getSleepTimer(); + int getDeathFadeTimer(); - std::vector *GetAdditionalModelParts(); - void SetAdditionalModelParts(std::vector *ppAdditionalModelParts); +protected: + bool getPlayerFlag(int flag); + void setPlayerFlag(int flag, bool value); + +public: + /** + * This method is currently only relevant to client-side players. It will + * try to load the messageId from the language file and display it to the + * client. + */ + virtual void displayClientMessage(int messageId); + Pos* getRespawnPosition(); + void setRespawnPosition(Pos* respawnPosition); + virtual void awardStat(Stat* stat, byteArray param); + +protected: + void jumpFromGround(); + +public: + void travel(float xa, float ya); + void checkMovementStatistiscs(double dx, double dy, double dz); + +private: + void checkRidingStatistiscs(double dx, double dy, double dz); + + bool m_bAwardedOnARail; + +protected: + virtual void causeFallDamage(float distance); + +public: + virtual void killed(std::shared_ptr mob); + virtual Icon* getItemInHandIcon(std::shared_ptr item, + int layer); + virtual std::shared_ptr getArmor(int pos); + virtual void handleInsidePortal(); + + void increaseXp(int i); + virtual void withdrawExperienceLevels(int amount); + int getXpNeededForNextLevel(); + +private: + void levelUp(); + +public: + void causeFoodExhaustion(float amount); + FoodData* getFoodData(); + bool canEat(bool magicalItem); + bool isHurt(); + virtual void startUsingItem(std::shared_ptr instance, + int duration); + bool mayBuild(int x, int y, int z); + +protected: + virtual int getExperienceReward(std::shared_ptr killedBy); + virtual bool isAlwaysExperienceDropper(); + +public: + virtual std::wstring getAName(); + + virtual void changeDimension(int i); + virtual void restoreFrom(std::shared_ptr oldPlayer, + bool restoreAll); + +protected: + bool makeStepSound(); + +public: + void onUpdateAbilities(); + void setGameMode(GameType* mode); + std::wstring getName(); + std::wstring getDisplayName(); // 4J added + + // Language getLanguage() { return Language.getInstance(); } + // String localize(String key, Object... args) { return + // getLanguage().getElement(key, args); } + + std::shared_ptr getEnderChestInventory(); + +public: + virtual std::shared_ptr getCarriedItem(); + + virtual bool isInvisibleTo(std::shared_ptr player); + + static int hash_fnct(const std::shared_ptr k); + static bool eq_test(const std::shared_ptr x, + const std::shared_ptr y); + + // 4J Stu - Added to allow callback to tutorial to stay within + // Minecraft.Client Overidden in LocalPlayer + virtual void onCrafted(std::shared_ptr item) {} + + // 4J Overriding this so that we can have some different default skins + virtual int getTexture(); // 4J changed from std::wstring to int + void setPlayerDefaultSkin(EDefaultSkins skin); + EDefaultSkins getPlayerDefaultSkin() { return m_skinIndex; } + virtual void setCustomSkin(std::uint32_t skinId); + std::uint32_t getCustomSkin() { return m_dwSkinId; } + virtual void setCustomCape(std::uint32_t capeId); + std::uint32_t getCustomCape() { return m_dwCapeId; } + + static std::uint32_t getCapeIdFromPath(const std::wstring& cape); + static std::wstring getCapePathFromId(std::uint32_t capeId); + static unsigned int getSkinAnimOverrideBitmask(std::uint32_t skinId); + + // 4J Added + void setXuid(PlayerUID xuid); + PlayerUID getXuid() { return m_xuid; } + void setOnlineXuid(PlayerUID xuid) { m_OnlineXuid = xuid; } + PlayerUID getOnlineXuid() { return m_OnlineXuid; } + void setUUID(const std::wstring& UUID) { m_UUID = UUID; } + std::wstring getUUID() { return m_UUID; } + + void setPlayerIndex(std::uint8_t index) { m_playerIndex = index; } + std::uint8_t getPlayerIndex() { return m_playerIndex; } + + void setIsGuest(bool bVal) { m_bIsGuest = bVal; } + bool isGuest() { return m_bIsGuest; } + + void setShowOnMaps(bool bVal) { m_bShownOnMaps = bVal; } + bool canShowOnMaps() { + return m_bShownOnMaps && + !getPlayerGamePrivilege(ePlayerGamePrivilege_Invisible); + } + + virtual void sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, + int customData = -1, const std::wstring& additionalMessage = L"") {} + +private: + PlayerUID m_xuid; + PlayerUID m_OnlineXuid; + +protected: + std::wstring m_UUID; // 4J Added + + bool m_bShownOnMaps; + + bool m_bIsGuest; + +private: + EDefaultSkins m_skinIndex; + std::uint32_t m_dwSkinId, m_dwCapeId; + + // 4J Added - Used to show which colour the player is on the map/behind + // their name + std::uint8_t m_playerIndex; + + // 4J-PB - to track debug options from the server player + unsigned int m_uiDebugOptions; + +public: + void SetDebugOptions(unsigned int uiVal) { m_uiDebugOptions = uiVal; } + unsigned int GetDebugOptions(void) { return m_uiDebugOptions; } + + void StopSleeping() {} + +public: + // If you add things here, you should also add a message to + // ClientConnection::displayPrivilegeChanges to alert players to changes + enum EPlayerGamePrivileges { + ePlayerGamePrivilege_CannotMine = + 0, // Only checked if trust system is on + ePlayerGamePrivilege_CannotBuild, // Only checked if trust system is on + ePlayerGamePrivilege_CannotAttackMobs, // Only checked if trust system + // is on + ePlayerGamePrivilege_CannotAttackPlayers, // Only checked if trust + // system is on + ePlayerGamePrivilege_Op, + ePlayerGamePrivilege_CanFly, + ePlayerGamePrivilege_ClassicHunger, + ePlayerGamePrivilege_Invisible, + ePlayerGamePrivilege_Invulnerable, + + ePlayerGamePrivilege_CreativeMode, // Used only to transfer across + // network, should never be used to + // determine if a player is in + // creative mode + + ePlayerGamePrivilege_CannotAttackAnimals, // Only checked if trust + // system is on + ePlayerGamePrivilege_CanUseDoorsAndSwitches, // Only checked if trust + // system is on + ePlayerGamePrivilege_CanUseContainers, // Only checked if trust system + // is on + + ePlayerGamePrivilege_CanToggleInvisible, + ePlayerGamePrivilege_CanToggleFly, + ePlayerGamePrivilege_CanToggleClassicHunger, + ePlayerGamePrivilege_CanTeleport, + + // Currently enum is used to bitshift into an unsigned int + ePlayerGamePrivilege_MAX = 32, + ePlayerGamePrivilege_All = 33, + ePlayerGamePrivilege_HOST, + }; + +private: + // 4J Added - Used to track what actions players have been allowed to + // perform by the host + unsigned int m_uiGamePrivileges; + + unsigned int getPlayerGamePrivilege(EPlayerGamePrivileges privilege); + +public: + unsigned int getAllPlayerGamePrivileges() { + return getPlayerGamePrivilege(ePlayerGamePrivilege_All); + } + + static unsigned int getPlayerGamePrivilege(unsigned int uiGamePrivileges, + EPlayerGamePrivileges privilege); + void setPlayerGamePrivilege(EPlayerGamePrivileges privilege, + unsigned int value); + static void setPlayerGamePrivilege(unsigned int& uiGamePrivileges, + EPlayerGamePrivileges privilege, + unsigned int value); + + bool isAllowedToUse(Tile* tile); + bool isAllowedToUse(std::shared_ptr item); + bool isAllowedToInteract(std::shared_ptr target); + bool isAllowedToMine(); + bool isAllowedToAttackPlayers(); + bool isAllowedToAttackAnimals(); + bool isAllowedToHurtEntity(std::shared_ptr target); + bool isAllowedToFly(); + bool isAllowedToIgnoreExhaustion(); + bool isAllowedToTeleport(); + bool hasInvisiblePrivilege(); + bool hasInvulnerablePrivilege(); + bool isModerator(); + + static void enableAllPlayerPrivileges(unsigned int& uigamePrivileges, + bool enable); + void enableAllPlayerPrivileges(bool enable); + + virtual bool canCreateParticles(); + +public: + // 4J Stu - Added hooks for the game rules + virtual void handleCollectItem(std::shared_ptr item) {} + + std::vector* GetAdditionalModelParts(); + void SetAdditionalModelParts( + std::vector* ppAdditionalModelParts); #if defined(__PS3__) || defined(__ORBIS__) - enum ePlayerNameValidState - { - ePlayerNameValid_NotSet=0, - ePlayerNameValid_True, - ePlayerNameValid_False - }; + enum ePlayerNameValidState { + ePlayerNameValid_NotSet = 0, + ePlayerNameValid_True, + ePlayerNameValid_False + }; - ePlayerNameValidState GetPlayerNameValidState(); - void SetPlayerNameValidState(bool bState); + ePlayerNameValidState GetPlayerNameValidState(); + void SetPlayerNameValidState(bool bState); #endif private: - std::vector *m_ppAdditionalModelParts; - bool m_bCheckedForModelParts; - bool m_bCheckedDLCForModelParts; + std::vector* m_ppAdditionalModelParts; + bool m_bCheckedForModelParts; + bool m_bCheckedDLCForModelParts; #if defined(__PS3__) || defined(__ORBIS__) - ePlayerNameValidState m_ePlayerNameValidState; // 4J-PB - to ensure we have the characters for this name in our font, or display a player number instead + ePlayerNameValidState + m_ePlayerNameValidState; // 4J-PB - to ensure we have the characters + // for this name in our font, or display a + // player number instead #endif }; -struct PlayerKeyHash -{ - int operator() (const std::shared_ptr k) const { return Player::hash_fnct (k); } +struct PlayerKeyHash { + int operator()(const std::shared_ptr k) const { + return Player::hash_fnct(k); + } }; -struct PlayerKeyEq -{ - bool operator() (const std::shared_ptr x, const std::shared_ptr y) const { return Player::eq_test (x, y); } +struct PlayerKeyEq { + bool operator()(const std::shared_ptr x, + const std::shared_ptr y) const { + return Player::eq_test(x, y); + } }; diff --git a/Minecraft.World/Player/PlayerEnderChestContainer.cpp b/Minecraft.World/Player/PlayerEnderChestContainer.cpp index 5ef9c09fd..4f3eabf2d 100644 --- a/Minecraft.World/Player/PlayerEnderChestContainer.cpp +++ b/Minecraft.World/Player/PlayerEnderChestContainer.cpp @@ -2,71 +2,61 @@ #include "../Headers/net.minecraft.world.level.tile.entity.h" #include "PlayerEnderChestContainer.h" -PlayerEnderChestContainer::PlayerEnderChestContainer() : SimpleContainer(IDS_TILE_ENDERCHEST, 9 * 3) -{ - activeChest = nullptr; +PlayerEnderChestContainer::PlayerEnderChestContainer() + : SimpleContainer(IDS_TILE_ENDERCHEST, 9 * 3) { + activeChest = nullptr; } -void PlayerEnderChestContainer::setActiveChest(std::shared_ptr activeChest) -{ - this->activeChest = activeChest; +void PlayerEnderChestContainer::setActiveChest( + std::shared_ptr activeChest) { + this->activeChest = activeChest; } -void PlayerEnderChestContainer::setItemsByTag(ListTag *enderItemsList) -{ - for (int i = 0; i < getContainerSize(); i++) - { - setItem(i, nullptr); - } - for (int i = 0; i < enderItemsList->size(); i++) - { - CompoundTag *tag = enderItemsList->get(i); - int slot = tag->getByte(L"Slot") & 0xff; - if (slot >= 0 && slot < getContainerSize()) setItem(slot, ItemInstance::fromTag(tag)); - } +void PlayerEnderChestContainer::setItemsByTag( + ListTag* enderItemsList) { + for (int i = 0; i < getContainerSize(); i++) { + setItem(i, nullptr); + } + for (int i = 0; i < enderItemsList->size(); i++) { + CompoundTag* tag = enderItemsList->get(i); + int slot = tag->getByte(L"Slot") & 0xff; + if (slot >= 0 && slot < getContainerSize()) + setItem(slot, ItemInstance::fromTag(tag)); + } } -ListTag *PlayerEnderChestContainer::createTag() -{ - ListTag *items = new ListTag(L"EnderItems"); - for (int i = 0; i < getContainerSize(); i++) - { - std::shared_ptr item = getItem(i); - if (item != NULL) - { - CompoundTag *tag = new CompoundTag(); - tag->putByte(L"Slot", (uint8_t) i); - item->save(tag); - items->add(tag); - } - } - return items; +ListTag* PlayerEnderChestContainer::createTag() { + ListTag* items = new ListTag(L"EnderItems"); + for (int i = 0; i < getContainerSize(); i++) { + std::shared_ptr item = getItem(i); + if (item != NULL) { + CompoundTag* tag = new CompoundTag(); + tag->putByte(L"Slot", (uint8_t)i); + item->save(tag); + items->add(tag); + } + } + return items; } -bool PlayerEnderChestContainer::stillValid(std::shared_ptr player) -{ - if (activeChest != NULL && !activeChest->stillValid(player)) - { - return false; - } - return SimpleContainer::stillValid(player); +bool PlayerEnderChestContainer::stillValid(std::shared_ptr player) { + if (activeChest != NULL && !activeChest->stillValid(player)) { + return false; + } + return SimpleContainer::stillValid(player); } -void PlayerEnderChestContainer::startOpen() -{ - if (activeChest != NULL) - { - activeChest->startOpen(); - } - SimpleContainer::startOpen(); +void PlayerEnderChestContainer::startOpen() { + if (activeChest != NULL) { + activeChest->startOpen(); + } + SimpleContainer::startOpen(); } -void PlayerEnderChestContainer::stopOpen() -{ - if (activeChest) - { - activeChest->stopOpen(); - } - SimpleContainer::stopOpen(); - activeChest = nullptr; +void PlayerEnderChestContainer::stopOpen() { + if (activeChest) { + activeChest->stopOpen(); + } + SimpleContainer::stopOpen(); + activeChest = nullptr; } diff --git a/Minecraft.World/Player/PlayerEnderChestContainer.h b/Minecraft.World/Player/PlayerEnderChestContainer.h index bd57344d1..2c156cc6f 100644 --- a/Minecraft.World/Player/PlayerEnderChestContainer.h +++ b/Minecraft.World/Player/PlayerEnderChestContainer.h @@ -4,18 +4,17 @@ class EnderChestTileEntity; -class PlayerEnderChestContainer : public SimpleContainer -{ +class PlayerEnderChestContainer : public SimpleContainer { private: - std::shared_ptr activeChest; + std::shared_ptr activeChest; public: - PlayerEnderChestContainer(); + PlayerEnderChestContainer(); - void setActiveChest(std::shared_ptr activeChest); - void setItemsByTag(ListTag *enderItemsList); - ListTag *createTag(); - bool stillValid(std::shared_ptr player); - void startOpen(); - void stopOpen(); + void setActiveChest(std::shared_ptr activeChest); + void setItemsByTag(ListTag* enderItemsList); + ListTag* createTag(); + bool stillValid(std::shared_ptr player); + void startOpen(); + void stopOpen(); }; \ No newline at end of file diff --git a/Minecraft.World/Recipes/ArmorDyeRecipe.cpp b/Minecraft.World/Recipes/ArmorDyeRecipe.cpp index 4faab0bc2..812e3faea 100644 --- a/Minecraft.World/Recipes/ArmorDyeRecipe.cpp +++ b/Minecraft.World/Recipes/ArmorDyeRecipe.cpp @@ -5,174 +5,146 @@ #include "../Headers/net.minecraft.world.item.crafting.h" #include "ArmorDyeRecipe.h" -bool ArmorDyeRecipe::matches(std::shared_ptr craftSlots, Level *level) -{ - std::shared_ptr target = nullptr; - std::vector > dyes; +bool ArmorDyeRecipe::matches(std::shared_ptr craftSlots, + Level* level) { + std::shared_ptr target = nullptr; + std::vector > dyes; - for (int slot = 0; slot < craftSlots->getContainerSize(); slot++) - { - std::shared_ptr item = craftSlots->getItem(slot); - if (item == NULL) continue; + for (int slot = 0; slot < craftSlots->getContainerSize(); slot++) { + std::shared_ptr item = craftSlots->getItem(slot); + if (item == NULL) continue; - ArmorItem *armor = dynamic_cast(item->getItem()); - if (armor) - { - if (armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH && target == NULL) - { - target = item; - } - else - { - return false; - } - } - else if (item->id == Item::dye_powder_Id) - { - dyes.push_back(item); - } - else - { - return false; - } - } + ArmorItem* armor = dynamic_cast(item->getItem()); + if (armor) { + if (armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH && + target == NULL) { + target = item; + } else { + return false; + } + } else if (item->id == Item::dye_powder_Id) { + dyes.push_back(item); + } else { + return false; + } + } - return target != NULL && !dyes.empty(); + return target != NULL && !dyes.empty(); } -std::shared_ptr ArmorDyeRecipe::assembleDyedArmor(std::shared_ptr craftSlots) -{ - std::shared_ptr target = nullptr; - int colorTotals[3]; - colorTotals[0] = 0; - colorTotals[1] = 0; - colorTotals[2] = 0; - int intensityTotal = 0; - int colourCounts = 0; - ArmorItem *armor = NULL; +std::shared_ptr ArmorDyeRecipe::assembleDyedArmor( + std::shared_ptr craftSlots) { + std::shared_ptr target = nullptr; + int colorTotals[3]; + colorTotals[0] = 0; + colorTotals[1] = 0; + colorTotals[2] = 0; + int intensityTotal = 0; + int colourCounts = 0; + ArmorItem* armor = NULL; - if(craftSlots != NULL) - { - for (int slot = 0; slot < craftSlots->getContainerSize(); slot++) - { - std::shared_ptr item = craftSlots->getItem(slot); - if (item == NULL) continue; + if (craftSlots != NULL) { + for (int slot = 0; slot < craftSlots->getContainerSize(); slot++) { + std::shared_ptr item = craftSlots->getItem(slot); + if (item == NULL) continue; - armor = dynamic_cast(item->getItem()); - if (armor) - { - if (armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH && target == NULL) - { - target = item->copy(); + armor = dynamic_cast(item->getItem()); + if (armor) { + if (armor->getMaterial() == ArmorItem::ArmorMaterial::CLOTH && + target == NULL) { + target = item->copy(); - if (armor->hasCustomColor(item)) - { - int color = armor->getColor(target); - float red = (float) ((color >> 16) & 0xFF) / 0xFF; - float green = (float) ((color >> 8) & 0xFF) / 0xFF; - float blue = (float) (color & 0xFF) / 0xFF; + if (armor->hasCustomColor(item)) { + int color = armor->getColor(target); + float red = (float)((color >> 16) & 0xFF) / 0xFF; + float green = (float)((color >> 8) & 0xFF) / 0xFF; + float blue = (float)(color & 0xFF) / 0xFF; - intensityTotal += std::max(red, std::max(green, blue)) * 0xFF; + intensityTotal += + std::max(red, std::max(green, blue)) * 0xFF; - colorTotals[0] += red * 0xFF; - colorTotals[1] += green * 0xFF; - colorTotals[2] += blue * 0xFF; - colourCounts++; - } - } - else - { - return nullptr; - } - } - else if (item->id == Item::dye_powder_Id) - { - int tileData = ClothTile::getTileDataForItemAuxValue(item->getAuxValue()); - int red = (int) (Sheep::COLOR[tileData][0] * 0xFF); - int green = (int) (Sheep::COLOR[tileData][1] * 0xFF); - int blue = (int) (Sheep::COLOR[tileData][2] * 0xFF); + colorTotals[0] += red * 0xFF; + colorTotals[1] += green * 0xFF; + colorTotals[2] += blue * 0xFF; + colourCounts++; + } + } else { + return nullptr; + } + } else if (item->id == Item::dye_powder_Id) { + int tileData = + ClothTile::getTileDataForItemAuxValue(item->getAuxValue()); + int red = (int)(Sheep::COLOR[tileData][0] * 0xFF); + int green = (int)(Sheep::COLOR[tileData][1] * 0xFF); + int blue = (int)(Sheep::COLOR[tileData][2] * 0xFF); - intensityTotal += std::max(red, std::max(green, blue)); + intensityTotal += std::max(red, std::max(green, blue)); - colorTotals[0] += red; - colorTotals[1] += green; - colorTotals[2] += blue; - colourCounts++; - } - else - { - return nullptr; - } - } - } + colorTotals[0] += red; + colorTotals[1] += green; + colorTotals[2] += blue; + colourCounts++; + } else { + return nullptr; + } + } + } - if (armor == NULL) return nullptr; + if (armor == NULL) return nullptr; - int red = (colorTotals[0] / colourCounts); - int green = (colorTotals[1] / colourCounts); - int blue = (colorTotals[2] / colourCounts); + int red = (colorTotals[0] / colourCounts); + int green = (colorTotals[1] / colourCounts); + int blue = (colorTotals[2] / colourCounts); - float averageIntensity = (float) intensityTotal / colourCounts; - float resultIntensity = (float) std::max(red, std::max(green, blue)); - // System.out.println(averageIntensity + ", " + resultIntensity); + float averageIntensity = (float)intensityTotal / colourCounts; + float resultIntensity = (float)std::max(red, std::max(green, blue)); + // System.out.println(averageIntensity + ", " + resultIntensity); - red = (int) ((float) red * averageIntensity / resultIntensity); - green = (int) ((float) green * averageIntensity / resultIntensity); - blue = (int) ((float) blue * averageIntensity / resultIntensity); + red = (int)((float)red * averageIntensity / resultIntensity); + green = (int)((float)green * averageIntensity / resultIntensity); + blue = (int)((float)blue * averageIntensity / resultIntensity); - int rgb = red; - rgb = (rgb << 8) + green; - rgb = (rgb << 8) + blue; + int rgb = red; + rgb = (rgb << 8) + green; + rgb = (rgb << 8) + blue; - armor->setColor(target, rgb); - return target; + armor->setColor(target, rgb); + return target; } -std::shared_ptr ArmorDyeRecipe::assemble(std::shared_ptr craftSlots) -{ - return ArmorDyeRecipe::assembleDyedArmor(craftSlots); +std::shared_ptr ArmorDyeRecipe::assemble( + std::shared_ptr craftSlots) { + return ArmorDyeRecipe::assembleDyedArmor(craftSlots); } -int ArmorDyeRecipe::size() -{ - return 10; -} +int ArmorDyeRecipe::size() { return 10; } -const ItemInstance *ArmorDyeRecipe::getResultItem() -{ - return NULL; -} +const ItemInstance* ArmorDyeRecipe::getResultItem() { return NULL; } -const int ArmorDyeRecipe::getGroup() -{ - return ShapedRecipy::eGroupType_Armour; -} +const int ArmorDyeRecipe::getGroup() { return ShapedRecipy::eGroupType_Armour; } // 4J-PB -bool ArmorDyeRecipe::requires(int iRecipe) -{ - return false; -} +bool ArmorDyeRecipe::requires(int iRecipe) { return false; } -void ArmorDyeRecipe::requires(INGREDIENTS_REQUIRED *pIngReq) -{ - //int iCount=0; - //bool bFound; - //int j; - INGREDIENTS_REQUIRED TempIngReq; +void ArmorDyeRecipe::requires(INGREDIENTS_REQUIRED* pIngReq) { + // int iCount=0; + // bool bFound; + // int j; + INGREDIENTS_REQUIRED TempIngReq; - // shapeless doesn't have the 3x3 shape, but we'll just use this to store the ingredients anyway - TempIngReq.iIngC=0; - TempIngReq.iType = RECIPE_TYPE_2x2; // all the dyes can be made in a 2x2 - TempIngReq.uiGridA = new unsigned int [9]; - TempIngReq.iIngIDA= new int [3*3]; - TempIngReq.iIngValA = new int [3*3]; - TempIngReq.iIngAuxValA = new int [3*3]; + // shapeless doesn't have the 3x3 shape, but we'll just use this to store + // the ingredients anyway + TempIngReq.iIngC = 0; + TempIngReq.iType = RECIPE_TYPE_2x2; // all the dyes can be made in a 2x2 + TempIngReq.uiGridA = new unsigned int[9]; + TempIngReq.iIngIDA = new int[3 * 3]; + TempIngReq.iIngValA = new int[3 * 3]; + TempIngReq.iIngAuxValA = new int[3 * 3]; - ZeroMemory(TempIngReq.iIngIDA,sizeof(int)*9); - ZeroMemory(TempIngReq.iIngValA,sizeof(int)*9); - memset(TempIngReq.iIngAuxValA,Recipes::ANY_AUX_VALUE,sizeof(int)*9); - ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); + ZeroMemory(TempIngReq.iIngIDA, sizeof(int) * 9); + ZeroMemory(TempIngReq.iIngValA, sizeof(int) * 9); + memset(TempIngReq.iIngAuxValA, Recipes::ANY_AUX_VALUE, sizeof(int) * 9); + ZeroMemory(TempIngReq.uiGridA, sizeof(unsigned int) * 9); #if 0 AUTO_VAR(citEnd, ingredients->end()); @@ -210,31 +182,32 @@ void ArmorDyeRecipe::requires(INGREDIENTS_REQUIRED *pIngReq) } #endif - pIngReq->iIngIDA = new int [TempIngReq.iIngC]; - pIngReq->iIngValA = new int [TempIngReq.iIngC]; - pIngReq->iIngAuxValA = new int [TempIngReq.iIngC]; - pIngReq->uiGridA = new unsigned int [9]; + pIngReq->iIngIDA = new int[TempIngReq.iIngC]; + pIngReq->iIngValA = new int[TempIngReq.iIngC]; + pIngReq->iIngAuxValA = new int[TempIngReq.iIngC]; + pIngReq->uiGridA = new unsigned int[9]; - pIngReq->pRecipy=this; + pIngReq->pRecipy = this; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - pIngReq->bCanMake[i]=false; - } + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + pIngReq->bCanMake[i] = false; + } - pIngReq->iIngC=TempIngReq.iIngC; - pIngReq->iType=TempIngReq.iType; + pIngReq->iIngC = TempIngReq.iIngC; + pIngReq->iType = TempIngReq.iType; - if(pIngReq->iIngC!=0) - { - memcpy(pIngReq->iIngIDA,TempIngReq.iIngIDA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngValA,TempIngReq.iIngValA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngAuxValA,TempIngReq.iIngAuxValA,sizeof(int)*TempIngReq.iIngC); - } - memcpy(pIngReq->uiGridA,TempIngReq.uiGridA,sizeof(unsigned int) *9); + if (pIngReq->iIngC != 0) { + memcpy(pIngReq->iIngIDA, TempIngReq.iIngIDA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngValA, TempIngReq.iIngValA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngAuxValA, TempIngReq.iIngAuxValA, + sizeof(int) * TempIngReq.iIngC); + } + memcpy(pIngReq->uiGridA, TempIngReq.uiGridA, sizeof(unsigned int) * 9); - delete [] TempIngReq.iIngIDA; - delete [] TempIngReq.iIngValA; - delete [] TempIngReq.iIngAuxValA; - delete [] TempIngReq.uiGridA; + delete[] TempIngReq.iIngIDA; + delete[] TempIngReq.iIngValA; + delete[] TempIngReq.iIngAuxValA; + delete[] TempIngReq.uiGridA; } diff --git a/Minecraft.World/Recipes/ArmorDyeRecipe.h b/Minecraft.World/Recipes/ArmorDyeRecipe.h index 9825be650..52fbbb591 100644 --- a/Minecraft.World/Recipes/ArmorDyeRecipe.h +++ b/Minecraft.World/Recipes/ArmorDyeRecipe.h @@ -2,22 +2,25 @@ #include "Recipy.h" -class ArmorDyeRecipe : public Recipy -{ +class ArmorDyeRecipe : public Recipy { public: - bool matches(std::shared_ptr craftSlots, Level *level); + bool matches(std::shared_ptr craftSlots, Level* level); - // 4J Stu - Made static as we use this in a different way from the Java (but needs to be a different name otherwise Orbis compiler complains - static std::shared_ptr assembleDyedArmor(std::shared_ptr craftSlots); - std::shared_ptr assemble(std::shared_ptr craftSlots); + // 4J Stu - Made static as we use this in a different way from the Java (but + // needs to be a different name otherwise Orbis compiler complains + static std::shared_ptr assembleDyedArmor( + std::shared_ptr craftSlots); + std::shared_ptr assemble( + std::shared_ptr craftSlots); - int size(); - const ItemInstance *getResultItem(); + int size(); + const ItemInstance* getResultItem(); - - virtual const int getGroup(); + virtual const int getGroup(); - // 4J-PB - virtual bool requires(int iRecipe); - virtual void requires(INGREDIENTS_REQUIRED *pIngReq); + // 4J-PB + virtual bool + requires(int iRecipe); + virtual void + requires(INGREDIENTS_REQUIRED* pIngReq); }; \ No newline at end of file diff --git a/Minecraft.World/Recipes/ArmorRecipes.cpp b/Minecraft.World/Recipes/ArmorRecipes.cpp index c26dbf47a..47850ec33 100644 --- a/Minecraft.World/Recipes/ArmorRecipes.cpp +++ b/Minecraft.World/Recipes/ArmorRecipes.cpp @@ -1,7 +1,7 @@ -//package net.minecraft.world.item.crafting; +// package net.minecraft.world.item.crafting; -//import net.minecraft.world.item.*; -//import net.minecraft.world.level.tile.Tile; +// import net.minecraft.world.item.*; +// import net.minecraft.world.level.tile.Tile; #include "../Platform/stdafx.h" #include "../Headers/net.minecraft.world.item.h" #include "../Blocks/Tile.h" @@ -10,149 +10,138 @@ #include "ArmorRecipes.h" // 4J-PB - adding "" on the end of these so we can detect it -std::wstring ArmorRecipes::shapes[][4] = -{ - {L"XXX", // - L"X X",L""},// +std::wstring ArmorRecipes::shapes[][4] = { + {L"XXX", // + L"X X", L""}, // - {L"X X", // - L"XXX",// - L"XXX",L""},// + {L"X X", // + L"XXX", // + L"XXX", L""}, // - {L"XXX", // - L"X X",// - L"X X",L""},// + {L"XXX", // + L"X X", // + L"X X", L""}, // - {L"X X",// - L"X X",L""},// + {L"X X", // + L"X X", L""}, // }; /* -ArmorRecipes::map[5] = +ArmorRecipes::map[5] = { - {Item::leather, Tile::fire, Item::ironIngot, Item::diamond, Item::goldIngot}, - {Item::helmet_cloth, Item::helmet_chain, Item::helmet_iron, Item::helmet_diamond, Item::helmet_gold}, - {Item::chestplate_cloth, Item::chestplate_chain, Item::chestplate_iron, Item::chestplate_diamond, Item::chestplate_gold}, - {Item::leggings_cloth, Item::leggings_chain, Item::leggings_iron, Item::leggings_diamond, Item::leggings_gold}, - {Item::boots_cloth, Item::boots_chain, Item::boots_iron, Item::boots_diamond, Item::boots_gold}, + {Item::leather, Tile::fire, Item::ironIngot, Item::diamond, +Item::goldIngot}, {Item::helmet_cloth, Item::helmet_chain, Item::helmet_iron, +Item::helmet_diamond, Item::helmet_gold}, {Item::chestplate_cloth, +Item::chestplate_chain, Item::chestplate_iron, Item::chestplate_diamond, +Item::chestplate_gold}, {Item::leggings_cloth, Item::leggings_chain, +Item::leggings_iron, Item::leggings_diamond, Item::leggings_gold}, + {Item::boots_cloth, Item::boots_chain, Item::boots_iron, +Item::boots_diamond, Item::boots_gold}, }; */ -void ArmorRecipes::_init() -{ - map = new std::vector [MAX_ARMOUR_RECIPES]; +void ArmorRecipes::_init() { + map = new std::vector[MAX_ARMOUR_RECIPES]; - // 4J-PB - removing the chain armour, since we show all possible recipes in the xbox game, and it's not one you can make - ADD_OBJECT(map[0],Item::leather); -// ADD_OBJECT(map[0],Tile::fire); - ADD_OBJECT(map[0],Item::ironIngot); - ADD_OBJECT(map[0],Item::diamond); - ADD_OBJECT(map[0],Item::goldIngot); + // 4J-PB - removing the chain armour, since we show all possible recipes in + // the xbox game, and it's not one you can make + ADD_OBJECT(map[0], Item::leather); + // ADD_OBJECT(map[0],Tile::fire); + ADD_OBJECT(map[0], Item::ironIngot); + ADD_OBJECT(map[0], Item::diamond); + ADD_OBJECT(map[0], Item::goldIngot); - ADD_OBJECT(map[1],Item::helmet_cloth); -// ADD_OBJECT(map[1],Item::helmet_chain); - ADD_OBJECT(map[1],Item::helmet_iron); - ADD_OBJECT(map[1],Item::helmet_diamond); - ADD_OBJECT(map[1],Item::helmet_gold); + ADD_OBJECT(map[1], Item::helmet_cloth); + // ADD_OBJECT(map[1],Item::helmet_chain); + ADD_OBJECT(map[1], Item::helmet_iron); + ADD_OBJECT(map[1], Item::helmet_diamond); + ADD_OBJECT(map[1], Item::helmet_gold); - ADD_OBJECT(map[2],Item::chestplate_cloth); -// ADD_OBJECT(map[2],Item::chestplate_chain); - ADD_OBJECT(map[2],Item::chestplate_iron); - ADD_OBJECT(map[2],Item::chestplate_diamond); - ADD_OBJECT(map[2],Item::chestplate_gold); + ADD_OBJECT(map[2], Item::chestplate_cloth); + // ADD_OBJECT(map[2],Item::chestplate_chain); + ADD_OBJECT(map[2], Item::chestplate_iron); + ADD_OBJECT(map[2], Item::chestplate_diamond); + ADD_OBJECT(map[2], Item::chestplate_gold); - ADD_OBJECT(map[3],Item::leggings_cloth); -// ADD_OBJECT(map[3],Item::leggings_chain); - ADD_OBJECT(map[3],Item::leggings_iron); - ADD_OBJECT(map[3],Item::leggings_diamond); - ADD_OBJECT(map[3],Item::leggings_gold); + ADD_OBJECT(map[3], Item::leggings_cloth); + // ADD_OBJECT(map[3],Item::leggings_chain); + ADD_OBJECT(map[3], Item::leggings_iron); + ADD_OBJECT(map[3], Item::leggings_diamond); + ADD_OBJECT(map[3], Item::leggings_gold); - ADD_OBJECT(map[4],Item::boots_cloth); -// ADD_OBJECT(map[4],Item::boots_chain); - ADD_OBJECT(map[4],Item::boots_iron); - ADD_OBJECT(map[4],Item::boots_diamond); - ADD_OBJECT(map[4],Item::boots_gold); + ADD_OBJECT(map[4], Item::boots_cloth); + // ADD_OBJECT(map[4],Item::boots_chain); + ADD_OBJECT(map[4], Item::boots_iron); + ADD_OBJECT(map[4], Item::boots_diamond); + ADD_OBJECT(map[4], Item::boots_gold); } // 4J-PB added for quick equip in the inventory -ArmorRecipes::_eArmorType ArmorRecipes::GetArmorType(int iId) -{ - switch(iId) - { - case Item::helmet_cloth_Id: - case Item::helmet_chain_Id: - case Item::helmet_iron_Id: - case Item::helmet_diamond_Id: - case Item::helmet_gold_Id: - return eArmorType_Helmet; - break; +ArmorRecipes::_eArmorType ArmorRecipes::GetArmorType(int iId) { + switch (iId) { + case Item::helmet_cloth_Id: + case Item::helmet_chain_Id: + case Item::helmet_iron_Id: + case Item::helmet_diamond_Id: + case Item::helmet_gold_Id: + return eArmorType_Helmet; + break; - case Item::chestplate_cloth_Id: - case Item::chestplate_chain_Id: - case Item::chestplate_iron_Id: - case Item::chestplate_diamond_Id: - case Item::chestplate_gold_Id: - return eArmorType_Chestplate; - break; + case Item::chestplate_cloth_Id: + case Item::chestplate_chain_Id: + case Item::chestplate_iron_Id: + case Item::chestplate_diamond_Id: + case Item::chestplate_gold_Id: + return eArmorType_Chestplate; + break; - case Item::leggings_cloth_Id: - case Item::leggings_chain_Id: - case Item::leggings_iron_Id: - case Item::leggings_diamond_Id: - case Item::leggings_gold_Id: - return eArmorType_Leggings; - break; + case Item::leggings_cloth_Id: + case Item::leggings_chain_Id: + case Item::leggings_iron_Id: + case Item::leggings_diamond_Id: + case Item::leggings_gold_Id: + return eArmorType_Leggings; + break; - case Item::boots_cloth_Id: - case Item::boots_chain_Id: - case Item::boots_iron_Id: - case Item::boots_diamond_Id: - case Item::boots_gold_Id: - return eArmorType_Boots; - break; - } + case Item::boots_cloth_Id: + case Item::boots_chain_Id: + case Item::boots_iron_Id: + case Item::boots_diamond_Id: + case Item::boots_gold_Id: + return eArmorType_Boots; + break; + } - return eArmorType_None; + return eArmorType_None; } -void ArmorRecipes::addRecipes(Recipes *r) -{ - wchar_t wchTypes[5]; - wchTypes[4]=0; +void ArmorRecipes::addRecipes(Recipes* r) { + wchar_t wchTypes[5]; + wchTypes[4] = 0; - for (unsigned int m = 0; m < map[0].size(); m++) - { - Object *pObjMaterial = map[0].at(m); + for (unsigned int m = 0; m < map[0].size(); m++) { + Object* pObjMaterial = map[0].at(m); - for (int t=0; titem; + for (int t = 0; t < MAX_ARMOUR_RECIPES - 1; t++) { + Item* target = map[t + 1].at(m)->item; - wchTypes[0]=L'w'; - wchTypes[1]=L'c'; - wchTypes[3]=L'g'; - if(pObjMaterial->GetType()==eType_TILE) - { - wchTypes[2]=L't'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + wchTypes[0] = L'w'; + wchTypes[1] = L'c'; + wchTypes[3] = L'g'; + if (pObjMaterial->GetType() == eType_TILE) { + wchTypes[2] = L't'; + r->addShapedRecipy(new ItemInstance(target), wchTypes, + shapes[t], - L'X', pObjMaterial->tile, - L'A'); - } - else - { - // must be Item - wchTypes[2]=L'i'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + L'X', pObjMaterial->tile, L'A'); + } else { + // must be Item + wchTypes[2] = L'i'; + r->addShapedRecipy(new ItemInstance(target), wchTypes, + shapes[t], - L'X', pObjMaterial->item, - L'A'); - } - } - } + L'X', pObjMaterial->item, L'A'); + } + } + } } - diff --git a/Minecraft.World/Recipes/ArmorRecipes.h b/Minecraft.World/Recipes/ArmorRecipes.h index 88a7bb5cd..3ae8db80c 100644 --- a/Minecraft.World/Recipes/ArmorRecipes.h +++ b/Minecraft.World/Recipes/ArmorRecipes.h @@ -1,34 +1,32 @@ -//package net.minecraft.world.item.crafting; +// package net.minecraft.world.item.crafting; -//import net.minecraft.world.item.*; -//import net.minecraft.world.level.tile.Tile; +// import net.minecraft.world.item.*; +// import net.minecraft.world.level.tile.Tile; #pragma once #define MAX_ARMOUR_RECIPES 5 -class ArmorRecipes -{ +class ArmorRecipes { public: - enum _eArmorType - { - eArmorType_None=0, - eArmorType_Helmet, - eArmorType_Chestplate, - eArmorType_Leggings, - eArmorType_Boots, - } - eArmorType; + enum _eArmorType { + eArmorType_None = 0, + eArmorType_Helmet, + eArmorType_Chestplate, + eArmorType_Leggings, + eArmorType_Boots, + } eArmorType; + + // 4J - added for common ctor code + void _init(); + ArmorRecipes() { _init(); } - // 4J - added for common ctor code - void _init(); - ArmorRecipes() {_init();} private: - // 4J-PB - this wasn't static in java, so might not be right - static std::wstring shapes[][4]; + // 4J-PB - this wasn't static in java, so might not be right + static std::wstring shapes[][4]; -private: - std::vector *map; +private: + std::vector* map; public: - void addRecipes(Recipes *r); - static _eArmorType GetArmorType(int iId); + void addRecipes(Recipes* r); + static _eArmorType GetArmorType(int iId); }; diff --git a/Minecraft.World/Recipes/ClothDyeRecipes.cpp b/Minecraft.World/Recipes/ClothDyeRecipes.cpp index cffb1347d..72a75bb88 100644 --- a/Minecraft.World/Recipes/ClothDyeRecipes.cpp +++ b/Minecraft.World/Recipes/ClothDyeRecipes.cpp @@ -7,101 +7,96 @@ #include "Recipes.h" #include "ClothDyeRecipes.h" -void ClothDyeRecipes::addRecipes(Recipes *r) -{ +void ClothDyeRecipes::addRecipes(Recipes* r) { // recipes for converting cloth to colored cloth using dye - for (int i = 0; i < 16; i++) - { - r->addShapelessRecipy(new ItemInstance(Tile::cloth, 1, ClothTile::getItemAuxValueForTileData(i)), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, i), new ItemInstance(Item::items[Tile::cloth_Id], 1, 0),L'D'); + for (int i = 0; i < 16; i++) { + r->addShapelessRecipy( + new ItemInstance(Tile::cloth, 1, + ClothTile::getItemAuxValueForTileData(i)), // + L"zzg", new ItemInstance(Item::dye_powder, 1, i), + new ItemInstance(Item::items[Tile::cloth_Id], 1, 0), L'D'); } // some dye recipes - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::YELLOW), - L"tg", - Tile::flower,L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::YELLOW), L"tg", + Tile::flower, L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::RED), - L"tg", - Tile::rose,L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::RED), L"tg", + Tile::rose, L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 3, DyePowderItem::WHITE), - L"ig", - Item::bone,L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 3, DyePowderItem::WHITE), L"ig", + Item::bone, L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::PINK), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::PINK), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::ORANGE), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::YELLOW),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::ORANGE), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::YELLOW), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::LIME), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::LIME), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::GRAY), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLACK), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::GRAY), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLACK), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::SILVER), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::GRAY), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::SILVER), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::GRAY), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 3, DyePowderItem::SILVER), // - L"zzzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLACK), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 3, DyePowderItem::SILVER), // + L"zzzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLACK), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::LIGHT_BLUE), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::LIGHT_BLUE), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::CYAN), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::CYAN), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::PURPLE), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::PURPLE), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 2, DyePowderItem::MAGENTA), // - L"zzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::PURPLE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::PINK),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 2, DyePowderItem::MAGENTA), // + L"zzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::PURPLE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::PINK), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 3, DyePowderItem::MAGENTA), // - L"zzzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::PINK),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 3, DyePowderItem::MAGENTA), // + L"zzzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::PINK), L'D'); - r->addShapelessRecipy(new ItemInstance(Item::dye_powder, 4, DyePowderItem::MAGENTA), // - L"zzzzg", - new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), - new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE),L'D'); + r->addShapelessRecipy( + new ItemInstance(Item::dye_powder, 4, DyePowderItem::MAGENTA), // + L"zzzzg", new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::RED), + new ItemInstance(Item::dye_powder, 1, DyePowderItem::WHITE), L'D'); - for (int i = 0; i < 16; i++) - { - r->addShapedRecipy(new ItemInstance(Tile::woolCarpet, 3, i), - L"sczg", - L"##", - L'#', new ItemInstance(Tile::cloth, 1, i), - L'D' - ); - } + for (int i = 0; i < 16; i++) { + r->addShapedRecipy(new ItemInstance(Tile::woolCarpet, 3, i), L"sczg", + L"##", L'#', new ItemInstance(Tile::cloth, 1, i), + L'D'); + } } - diff --git a/Minecraft.World/Recipes/ClothDyeRecipes.h b/Minecraft.World/Recipes/ClothDyeRecipes.h index c4283dfda..d7958367e 100644 --- a/Minecraft.World/Recipes/ClothDyeRecipes.h +++ b/Minecraft.World/Recipes/ClothDyeRecipes.h @@ -1,8 +1,6 @@ #pragma once -class ClothDyeRecipes -{ - +class ClothDyeRecipes { public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; diff --git a/Minecraft.World/Recipes/FoodRecipes.cpp b/Minecraft.World/Recipes/FoodRecipes.cpp index 97dbb2ba4..f8d50e78c 100644 --- a/Minecraft.World/Recipes/FoodRecipes.cpp +++ b/Minecraft.World/Recipes/FoodRecipes.cpp @@ -6,117 +6,99 @@ #include "Recipes.h" #include "FoodRecipes.h" -void FoodRecipies::addRecipes(Recipes *r) -{ - // 4J-JEV: Bumped up in the list to avoid a colision with the title. - r->addShapedRecipy(new ItemInstance(Item::apple_gold, 1, 0), // - L"ssscicig", - L"###", // - L"#X#", // - L"###", // - L'#', Item::goldNugget, L'X', Item::apple, - L'F'); - - // 4J-PB - Moving the mushroom stew shaped->shapeless forward from 1.9, so it will not need the crafting table - r->addShapelessRecipy(new ItemInstance(Item::mushroomStew), - L"ttig", - Tile::mushroom1, Tile::mushroom2, Item::bowl, - L'F'); +void FoodRecipies::addRecipes(Recipes* r) { + // 4J-JEV: Bumped up in the list to avoid a colision with the title. + r->addShapedRecipy(new ItemInstance(Item::apple_gold, 1, 0), // + L"ssscicig", + L"###", // + L"#X#", // + L"###", // + L'#', Item::goldNugget, L'X', Item::apple, L'F'); - /*r->addShapedRecipy(new ItemInstance(Item::mushroomStew), // - L"sssctctcig", - L"Y", // - L"X", // - L"#", // + // 4J-PB - Moving the mushroom stew shaped->shapeless forward from 1.9, so + // it will not need the crafting table + r->addShapelessRecipy(new ItemInstance(Item::mushroomStew), L"ttig", + Tile::mushroom1, Tile::mushroom2, Item::bowl, L'F'); - L'X', Tile::mushroom1, - L'Y', Tile::mushroom2, - L'#', Item::bowl, - L'F');*/ + /*r->addShapedRecipy(new ItemInstance(Item::mushroomStew), // + L"sssctctcig", + L"Y", // + L"X", // + L"#", // - // 4J-PB - removing for the xbox game - we already have it above -// r->addShapedRecipy(new ItemInstance(Item::mushroomStew), // -// L"sssctctcig", -// L"Y", // -// L"X", // -// L"#", // -// -// L'X', Tile::mushroom2, -// L'Y', Tile::mushroom1, -// L'#', Item::bowl, -// L'F'); -// - r->addShapedRecipy(new ItemInstance(Item::cookie, 8), // - L"sczcig", - L"#X#", // + L'X', Tile::mushroom1, + L'Y', Tile::mushroom2, + L'#', Item::bowl, + L'F');*/ - L'X', new ItemInstance(Item::dye_powder, 1, DyePowderItem::BROWN), - L'#', Item::wheat, - L'F'); + // 4J-PB - removing for the xbox game - we already have it above + // r->addShapedRecipy(new ItemInstance(Item::mushroomStew), // + // L"sssctctcig", + // L"Y", // + // L"X", // + // L"#", // + // + // L'X', Tile::mushroom2, + // L'Y', Tile::mushroom1, + // L'#', Item::bowl, + // L'F'); + // + r->addShapedRecipy( + new ItemInstance(Item::cookie, 8), // + L"sczcig", + L"#X#", // - r->addShapedRecipy(new ItemInstance(Tile::melon), // - L"ssscig", - L"MMM", // - L"MMM", // - L"MMM", // + L'X', new ItemInstance(Item::dye_powder, 1, DyePowderItem::BROWN), L'#', + Item::wheat, L'F'); - L'M', Item::melon, - L'F'); + r->addShapedRecipy(new ItemInstance(Tile::melon), // + L"ssscig", + L"MMM", // + L"MMM", // + L"MMM", // - r->addShapedRecipy(new ItemInstance(Item::seeds_melon), // - L"scig", - L"M", // + L'M', Item::melon, L'F'); - L'M', Item::melon, - L'F'); + r->addShapedRecipy(new ItemInstance(Item::seeds_melon), // + L"scig", + L"M", // - r->addShapedRecipy(new ItemInstance(Item::seeds_pumpkin, 4), // - L"sctg", - L"M", // + L'M', Item::melon, L'F'); - L'M', Tile::pumpkin, - L'F'); + r->addShapedRecipy(new ItemInstance(Item::seeds_pumpkin, 4), // + L"sctg", + L"M", // - r->addShapelessRecipy(new ItemInstance(Item::pumpkinPie), // - L"tiig", - Tile::pumpkin, Item::sugar, Item::egg, - L'F'); + L'M', Tile::pumpkin, L'F'); - r->addShapedRecipy(new ItemInstance(Item::apple_gold, 1, 1), // - L"sssctcig", - L"###", // - L"#X#", // - L"###", // - L'#', Tile::goldBlock, L'X', Item::apple, - L'F'); + r->addShapelessRecipy(new ItemInstance(Item::pumpkinPie), // + L"tiig", Tile::pumpkin, Item::sugar, Item::egg, L'F'); - r->addShapedRecipy(new ItemInstance(Item::carrotGolden, 1, 0), // - L"ssscicig", - L"###", // - L"#X#", // - L"###", // + r->addShapedRecipy(new ItemInstance(Item::apple_gold, 1, 1), // + L"sssctcig", + L"###", // + L"#X#", // + L"###", // + L'#', Tile::goldBlock, L'X', Item::apple, L'F'); - L'#', Item::goldNugget, L'X', Item::carrots, - L'F'); + r->addShapedRecipy(new ItemInstance(Item::carrotGolden, 1, 0), // + L"ssscicig", + L"###", // + L"#X#", // + L"###", // - r->addShapelessRecipy(new ItemInstance(Item::fermentedSpiderEye), // - L"itig", - Item::spiderEye, Tile::mushroom1, Item::sugar, - L'F'); + L'#', Item::goldNugget, L'X', Item::carrots, L'F'); - r->addShapelessRecipy(new ItemInstance(Item::speckledMelon), // - L"iig", - Item::melon, Item::goldNugget, - L'F'); + r->addShapelessRecipy(new ItemInstance(Item::fermentedSpiderEye), // + L"itig", Item::spiderEye, Tile::mushroom1, + Item::sugar, L'F'); - r->addShapelessRecipy(new ItemInstance(Item::blazePowder, 2), // - L"ig", - Item::blazeRod, - L'F'); + r->addShapelessRecipy(new ItemInstance(Item::speckledMelon), // + L"iig", Item::melon, Item::goldNugget, L'F'); - r->addShapelessRecipy(new ItemInstance(Item::magmaCream), // - L"iig", - Item::blazePowder, Item::slimeBall, - L'F'); + r->addShapelessRecipy(new ItemInstance(Item::blazePowder, 2), // + L"ig", Item::blazeRod, L'F'); + + r->addShapelessRecipy(new ItemInstance(Item::magmaCream), // + L"iig", Item::blazePowder, Item::slimeBall, L'F'); } - diff --git a/Minecraft.World/Recipes/FoodRecipes.h b/Minecraft.World/Recipes/FoodRecipes.h index 8f2c1884b..5b4fb251a 100644 --- a/Minecraft.World/Recipes/FoodRecipes.h +++ b/Minecraft.World/Recipes/FoodRecipes.h @@ -1,7 +1,6 @@ #pragma once -class FoodRecipies -{ +class FoodRecipies { public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; diff --git a/Minecraft.World/Recipes/FurnaceRecipes.cpp b/Minecraft.World/Recipes/FurnaceRecipes.cpp index fa4d2182a..17bf6121d 100644 --- a/Minecraft.World/Recipes/FurnaceRecipes.cpp +++ b/Minecraft.World/Recipes/FurnaceRecipes.cpp @@ -3,80 +3,81 @@ #include "../Blocks/Tile.h" #include "FurnaceRecipes.h" -FurnaceRecipes *FurnaceRecipes::instance = NULL; +FurnaceRecipes* FurnaceRecipes::instance = NULL; -void FurnaceRecipes::staticCtor() -{ - FurnaceRecipes::instance = new FurnaceRecipes(); +void FurnaceRecipes::staticCtor() { + FurnaceRecipes::instance = new FurnaceRecipes(); } -FurnaceRecipes *FurnaceRecipes::getInstance() -{ - return instance; +FurnaceRecipes* FurnaceRecipes::getInstance() { return instance; } + +FurnaceRecipes::FurnaceRecipes() { + addFurnaceRecipy(Tile::ironOre_Id, new ItemInstance(Item::ironIngot), .7f); + addFurnaceRecipy(Tile::goldOre_Id, new ItemInstance(Item::goldIngot), 1); + addFurnaceRecipy(Tile::diamondOre_Id, new ItemInstance(Item::diamond), 1); + addFurnaceRecipy(Tile::sand_Id, new ItemInstance(Tile::glass), .1f); + addFurnaceRecipy(Item::porkChop_raw_Id, + new ItemInstance(Item::porkChop_cooked), .35f); + addFurnaceRecipy(Item::beef_raw_Id, new ItemInstance(Item::beef_cooked), + .35f); + addFurnaceRecipy(Item::chicken_raw_Id, + new ItemInstance(Item::chicken_cooked), .35f); + addFurnaceRecipy(Item::fish_raw_Id, new ItemInstance(Item::fish_cooked), + .35f); + addFurnaceRecipy(Tile::stoneBrick_Id, new ItemInstance(Tile::rock), .1f); + addFurnaceRecipy(Item::clay_Id, new ItemInstance(Item::brick), .3f); + addFurnaceRecipy( + Tile::cactus_Id, + new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN), .2f); + addFurnaceRecipy(Tile::treeTrunk_Id, + new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL), + .15f); + addFurnaceRecipy(Tile::emeraldOre_Id, new ItemInstance(Item::emerald), 1); + addFurnaceRecipy(Item::potato_Id, new ItemInstance(Item::potatoBaked), + .35f); + // 4J - TU9 - add in smelting netherrack + addFurnaceRecipy(Tile::hellRock_Id, new ItemInstance(Item::netherbrick), + .1f); + + // special silk touch related recipes: + addFurnaceRecipy(Tile::coalOre_Id, new ItemInstance(Item::coal), .1f); + addFurnaceRecipy(Tile::redStoneOre_Id, new ItemInstance(Item::redStone), + .7f); + addFurnaceRecipy(Tile::lapisOre_Id, + new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), + .2f); + addFurnaceRecipy(Tile::netherQuartz_Id, + new ItemInstance(Item::netherQuartz), .2f); } -FurnaceRecipes::FurnaceRecipes() -{ - addFurnaceRecipy(Tile::ironOre_Id, new ItemInstance(Item::ironIngot), .7f); - addFurnaceRecipy(Tile::goldOre_Id, new ItemInstance(Item::goldIngot), 1); - addFurnaceRecipy(Tile::diamondOre_Id, new ItemInstance(Item::diamond), 1); - addFurnaceRecipy(Tile::sand_Id, new ItemInstance(Tile::glass), .1f); - addFurnaceRecipy(Item::porkChop_raw_Id, new ItemInstance(Item::porkChop_cooked), .35f); - addFurnaceRecipy(Item::beef_raw_Id, new ItemInstance(Item::beef_cooked), .35f); - addFurnaceRecipy(Item::chicken_raw_Id, new ItemInstance(Item::chicken_cooked), .35f); - addFurnaceRecipy(Item::fish_raw_Id, new ItemInstance(Item::fish_cooked), .35f); - addFurnaceRecipy(Tile::stoneBrick_Id, new ItemInstance(Tile::rock), .1f); - addFurnaceRecipy(Item::clay_Id, new ItemInstance(Item::brick), .3f); - addFurnaceRecipy(Tile::cactus_Id, new ItemInstance(Item::dye_powder, 1, DyePowderItem::GREEN), .2f); - addFurnaceRecipy(Tile::treeTrunk_Id, new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL), .15f); - addFurnaceRecipy(Tile::emeraldOre_Id, new ItemInstance(Item::emerald), 1); - addFurnaceRecipy(Item::potato_Id, new ItemInstance(Item::potatoBaked), .35f); - // 4J - TU9 - add in smelting netherrack - addFurnaceRecipy(Tile::hellRock_Id, new ItemInstance(Item::netherbrick), .1f); - - // special silk touch related recipes: - addFurnaceRecipy(Tile::coalOre_Id, new ItemInstance(Item::coal), .1f); - addFurnaceRecipy(Tile::redStoneOre_Id, new ItemInstance(Item::redStone), .7f); - addFurnaceRecipy(Tile::lapisOre_Id, new ItemInstance(Item::dye_powder, 1, DyePowderItem::BLUE), .2f); - addFurnaceRecipy(Tile::netherQuartz_Id, new ItemInstance(Item::netherQuartz), .2f); - - +void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance* result, + float value) { + // recipies->put(itemId, result); + recipies[itemId] = result; + recipeValue[result->id] = value; } -void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance *result, float value) -{ - //recipies->put(itemId, result); - recipies[itemId]=result; - recipeValue[result->id] = value; +bool FurnaceRecipes::isFurnaceItem(int itemId) { + AUTO_VAR(it, recipies.find(itemId)); + return it != recipies.end(); } -bool FurnaceRecipes::isFurnaceItem(int itemId) -{ - AUTO_VAR(it, recipies.find(itemId)); - return it != recipies.end(); +ItemInstance* FurnaceRecipes::getResult(int itemId) { + AUTO_VAR(it, recipies.find(itemId)); + if (it != recipies.end()) { + return it->second; + } + return NULL; } -ItemInstance *FurnaceRecipes::getResult(int itemId) -{ - AUTO_VAR(it, recipies.find(itemId)); - if(it != recipies.end()) - { - return it->second; - } - return NULL; +std::unordered_map* FurnaceRecipes::getRecipies() { + return &recipies; } -std::unordered_map *FurnaceRecipes::getRecipies() -{ - return &recipies; -} - -float FurnaceRecipes::getRecipeValue(int itemId) -{ - AUTO_VAR(it, recipeValue.find(itemId)); - if (it != recipeValue.end()) - { - return it->second; - } - return 0.0f; +float FurnaceRecipes::getRecipeValue(int itemId) { + AUTO_VAR(it, recipeValue.find(itemId)); + if (it != recipeValue.end()) { + return it->second; + } + return 0.0f; } \ No newline at end of file diff --git a/Minecraft.World/Recipes/FurnaceRecipes.h b/Minecraft.World/Recipes/FurnaceRecipes.h index 710c3511d..e5cff70b4 100644 --- a/Minecraft.World/Recipes/FurnaceRecipes.h +++ b/Minecraft.World/Recipes/FurnaceRecipes.h @@ -1,30 +1,28 @@ #pragma once -class FurnaceRecipes -{ +class FurnaceRecipes { +private: + static FurnaceRecipes* instance; + +public: + static void staticCtor(); private: - static FurnaceRecipes *instance; + // Map recipies = new HashMap(); + std::unordered_map recipies; + std::unordered_map recipeValue; public: - static void staticCtor(); - -private: - //Map recipies = new HashMap(); - std::unordered_map recipies; - std::unordered_map recipeValue; + static FurnaceRecipes* getInstance(); public: - static FurnaceRecipes *getInstance(); + FurnaceRecipes(); public: - FurnaceRecipes(); - -public: - void addFurnaceRecipy(int itemId, ItemInstance *result, float value); - bool isFurnaceItem(int itemId); - ItemInstance *getResult(int itemId); - std::unordered_map *getRecipies(); - float getRecipeValue(int itemId); - + void addFurnaceRecipy(int itemId, ItemInstance* result, float value); + bool isFurnaceItem(int itemId); + ItemInstance* getResult(int itemId); + std::unordered_map* getRecipies(); + float getRecipeValue(int itemId); }; diff --git a/Minecraft.World/Recipes/OreRecipes.cpp b/Minecraft.World/Recipes/OreRecipes.cpp index 974a23176..6718c487b 100644 --- a/Minecraft.World/Recipes/OreRecipes.cpp +++ b/Minecraft.World/Recipes/OreRecipes.cpp @@ -1,5 +1,5 @@ // package net.minecraft.world.item.crafting; -// +// // import net.minecraft.world.item.DyePowderItem; // import net.minecraft.world.item.Item; // import net.minecraft.world.item.ItemInstance; @@ -13,63 +13,56 @@ #include "Recipes.h" #include "OreRecipes.h" - /* - private Object[][] map = { - { - Tile.goldBlock, new ItemInstance(Item.goldIngot, 9) - }, { - Tile.ironBlock, new ItemInstance(Item.ironIngot, 9) - }, { - Tile.diamondBlock, new ItemInstance(Item.diamond, 9) - }, { - Tile.lapisBlock, new ItemInstance(Item.dye_powder, 9, DyePowderItem.BLUE) - }, - }; + private Object[][] map = { + { + Tile.goldBlock, new ItemInstance(Item.goldIngot, 9) + }, { + Tile.ironBlock, new ItemInstance(Item.ironIngot, 9) + }, { + Tile.diamondBlock, new ItemInstance(Item.diamond, 9) + }, { + Tile.lapisBlock, new + ItemInstance(Item.dye_powder, 9, DyePowderItem.BLUE) + }, + }; */ -void OreRecipies::_init() -{ - map = new std::vector [MAX_ORE_RECIPES]; +void OreRecipies::_init() { + map = new std::vector[MAX_ORE_RECIPES]; - ADD_OBJECT(map[0],Tile::goldBlock); - ADD_OBJECT(map[0],new ItemInstance(Item::goldIngot, 9)); + ADD_OBJECT(map[0], Tile::goldBlock); + ADD_OBJECT(map[0], new ItemInstance(Item::goldIngot, 9)); - ADD_OBJECT(map[1],Tile::ironBlock); - ADD_OBJECT(map[1],new ItemInstance(Item::ironIngot, 9)); + ADD_OBJECT(map[1], Tile::ironBlock); + ADD_OBJECT(map[1], new ItemInstance(Item::ironIngot, 9)); - ADD_OBJECT(map[2],Tile::diamondBlock); - ADD_OBJECT(map[2],new ItemInstance(Item::diamond, 9)); + ADD_OBJECT(map[2], Tile::diamondBlock); + ADD_OBJECT(map[2], new ItemInstance(Item::diamond, 9)); - ADD_OBJECT(map[3],Tile::emeraldBlock); - ADD_OBJECT(map[3],new ItemInstance(Item::emerald, 9)); + ADD_OBJECT(map[3], Tile::emeraldBlock); + ADD_OBJECT(map[3], new ItemInstance(Item::emerald, 9)); - ADD_OBJECT(map[4],Tile::lapisBlock); - ADD_OBJECT(map[4],new ItemInstance(Item::dye_powder, 9, DyePowderItem::BLUE)); + ADD_OBJECT(map[4], Tile::lapisBlock); + ADD_OBJECT(map[4], + new ItemInstance(Item::dye_powder, 9, DyePowderItem::BLUE)); } -void OreRecipies::addRecipes(Recipes *r) -{ +void OreRecipies::addRecipes(Recipes* r) { + for (int i = 0; i < MAX_ORE_RECIPES; i++) { + Tile* from = (Tile*)map[i].at(0)->tile; + ItemInstance* to = (ItemInstance*)map[i].at(1)->iteminstance; + r->addShapedRecipy(new ItemInstance(from), // + L"sssczg", + L"###", // + L"###", // + L"###", // - for (int i = 0; i < MAX_ORE_RECIPES; i++) - { - Tile *from = (Tile*) map[i].at(0)->tile; - ItemInstance *to = (ItemInstance*) map[i].at(1)->iteminstance; - r->addShapedRecipy(new ItemInstance(from), // - L"sssczg", - L"###", // - L"###", // - L"###", // + L'#', to, L'D'); - L'#', to, - L'D'); + r->addShapedRecipy(to, // + L"sctg", + L"#", // - r->addShapedRecipy(to, // - L"sctg", - L"#", // - - L'#', from, - L'D'); - } + L'#', from, L'D'); + } } - - diff --git a/Minecraft.World/Recipes/OreRecipes.h b/Minecraft.World/Recipes/OreRecipes.h index ef4082c5e..9e70c045a 100644 --- a/Minecraft.World/Recipes/OreRecipes.h +++ b/Minecraft.World/Recipes/OreRecipes.h @@ -2,16 +2,15 @@ #define MAX_ORE_RECIPES 5 -class OreRecipies -{ +class OreRecipies { public: - // 4J - added for common ctor code - void _init(); - OreRecipies() {_init();} + // 4J - added for common ctor code + void _init(); + OreRecipies() { _init(); } private: - std::vector *map; + std::vector* map; public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; \ No newline at end of file diff --git a/Minecraft.World/Recipes/Recipes.cpp b/Minecraft.World/Recipes/Recipes.cpp index 66eab96cd..2c053dee3 100644 --- a/Minecraft.World/Recipes/Recipes.cpp +++ b/Minecraft.World/Recipes/Recipes.cpp @@ -24,1197 +24,1080 @@ import net.minecraft.world.level.Tile::Tile;*/ #include "../Headers/net.minecraft.world.level.tile.h" #include "../Headers/net.minecraft.world.item.crafting.h" -Recipes *Recipes::instance = NULL; -ArmorRecipes *Recipes::pArmorRecipes=NULL; -ClothDyeRecipes *Recipes::pClothDyeRecipes=NULL; -FoodRecipies *Recipes::pFoodRecipies=NULL; -OreRecipies *Recipes::pOreRecipies=NULL; -StructureRecipies *Recipes::pStructureRecipies=NULL; -ToolRecipies *Recipes::pToolRecipies=NULL; -WeaponRecipies *Recipes::pWeaponRecipies=NULL; +Recipes* Recipes::instance = NULL; +ArmorRecipes* Recipes::pArmorRecipes = NULL; +ClothDyeRecipes* Recipes::pClothDyeRecipes = NULL; +FoodRecipies* Recipes::pFoodRecipies = NULL; +OreRecipies* Recipes::pOreRecipies = NULL; +StructureRecipies* Recipes::pStructureRecipies = NULL; +ToolRecipies* Recipes::pToolRecipies = NULL; +WeaponRecipies* Recipes::pWeaponRecipies = NULL; -void Recipes::staticCtor() -{ - Recipes::instance = new Recipes(); +void Recipes::staticCtor() { Recipes::instance = new Recipes(); } +void Recipes::_init() { + // 4J Jev: instance = new Recipes(); + recipies = new RecipyList(); } -void Recipes::_init() -{ - // 4J Jev: instance = new Recipes(); - recipies = new RecipyList(); +Recipes::Recipes() { + int iCount = 0; + _init(); + + pArmorRecipes = new ArmorRecipes; + pClothDyeRecipes = new ClothDyeRecipes; + pFoodRecipies = new FoodRecipies; + pOreRecipies = new OreRecipies; + pStructureRecipies = new StructureRecipies; + pToolRecipies = new ToolRecipies; + pWeaponRecipies = new WeaponRecipies; + + // 4J Stu - These just don't work with our crafting menu + // recipies->push_back(new ArmorDyeRecipe()); + + addShapedRecipy(new ItemInstance(Tile::wood, 4, 0), // + L"sczg", + L"#", // + + L'#', new ItemInstance(Tile::treeTrunk, 1, 0), L'S'); + + // TU9 - adding coloured wood + addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::BIRCH_TRUNK), // + L"sczg", + L"#", // + + L'#', + new ItemInstance(Tile::treeTrunk, 1, TreeTile::BIRCH_TRUNK), + L'S'); + + addShapedRecipy( + new ItemInstance(Tile::wood, 4, TreeTile::DARK_TRUNK), // + L"sczg", + L"#", // + + L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::DARK_TRUNK), L'S'); + + addShapedRecipy( + new ItemInstance(Tile::wood, 4, TreeTile::JUNGLE_TRUNK), // + L"sczg", + L"#", // + + L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::JUNGLE_TRUNK), + L'S'); + + addShapedRecipy(new ItemInstance(Item::stick, 4), // + L"ssctg", + L"#", // + L"#", // + + L'#', Tile::wood, L'S'); + + pToolRecipies->addRecipes(this); + pFoodRecipies->addRecipes(this); + pStructureRecipies->addRecipes(this); + + // 4J-PB - changing the order to the way we want to have things in the + // crafting menu bed + addShapedRecipy(new ItemInstance(Item::bed, 1), // + L"ssctctg", + L"###", // + L"XXX", // + L'#', Tile::cloth, L'X', Tile::wood, L'S'); + + addShapedRecipy(new ItemInstance(Tile::enchantTable, 1), // + L"sssctcicig", + L" B ", // + L"D#D", // + L"###", // + + L'#', Tile::obsidian, L'B', Item::book, L'D', Item::diamond, + L'S'); + + addShapedRecipy(new ItemInstance(Tile::anvil, 1), // + L"sssctcig", + L"III", // + L" i ", // + L"iii", // + + L'I', Tile::ironBlock, L'i', Item::ironIngot, L'S'); + + // 4J Stu - Reordered for crafting menu + addShapedRecipy(new ItemInstance(Tile::ladder, 3), // + L"ssscig", + L"# #", // + L"###", // + L"# #", // + + L'#', Item::stick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::fenceGate, 1), // + L"sscictg", + L"#W#", // + L"#W#", // + + L'#', Item::stick, L'W', Tile::wood, L'S'); + + addShapedRecipy(new ItemInstance(Tile::fence, 2), // + L"sscig", + L"###", // + L"###", // + + L'#', Item::stick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::netherFence, 6), // + L"ssctg", + L"###", // + L"###", // + + L'#', Tile::netherBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::ironFence, 16), // + L"sscig", + L"###", // + L"###", // + + L'#', Item::ironIngot, L'S'); + + addShapedRecipy( + new ItemInstance(Tile::cobbleWall, 6, WallTile::TYPE_NORMAL), // + L"ssctg", + L"###", // + L"###", // + + L'#', Tile::stoneBrick, L'S'); + + addShapedRecipy( + new ItemInstance(Tile::cobbleWall, 6, WallTile::TYPE_MOSSY), // + L"ssctg", + L"###", // + L"###", // + + L'#', Tile::mossStone, L'S'); + + addShapedRecipy(new ItemInstance(Item::door_wood, 1), // + L"sssctg", + L"##", // + L"##", // + L"##", // + + L'#', Tile::wood, L'S'); + + addShapedRecipy(new ItemInstance(Item::door_iron, 1), // + L"ssscig", + L"##", // + L"##", // + L"##", // + + L'#', Item::ironIngot, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_wood, 4), // + L"sssczg", + L"# ", // + L"## ", // + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, 0), L'S'); + + addShapedRecipy(new ItemInstance(Tile::trapdoor, 2), // + L"ssctg", + L"###", // + L"###", // + + L'#', Tile::wood, L'S'); + addShapedRecipy(new ItemInstance(Tile::stairs_stone, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::stoneBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_bricks, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::redBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_stoneBrickSmooth, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::stoneBrickSmooth, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_netherBricks, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::netherBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_sandstone, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::sandStone, L'S'); + + addShapedRecipy( + new ItemInstance(Tile::woodStairsBirch, 4), // + L"sssczg", + L"# ", // + L"## ", // + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::BIRCH_TRUNK), L'S'); + + addShapedRecipy(new ItemInstance(Tile::woodStairsDark, 4), // + L"sssczg", + L"# ", // + L"## ", // + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::DARK_TRUNK), + L'S'); + + addShapedRecipy( + new ItemInstance(Tile::woodStairsJungle, 4), // + L"sssczg", + L"# ", // + L"## ", // + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::JUNGLE_TRUNK), L'S'); + + addShapedRecipy(new ItemInstance(Tile::stairs_quartz, 4), // + L"sssctg", + L"# ", // + L"## ", // + L"###", // + + L'#', Tile::quartzBlock, L'S'); + + pArmorRecipes->addRecipes(this); + // iCount=getRecipies()->size(); + + pClothDyeRecipes->addRecipes(this); + + addShapedRecipy(new ItemInstance(Tile::snow, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::snowBall, L'S'); + + addShapedRecipy(new ItemInstance(Tile::clay, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::clay, L'S'); + + addShapedRecipy(new ItemInstance(Tile::redBrick, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::brick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::cloth, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::string, L'D'); + + addShapedRecipy(new ItemInstance(Tile::tnt, 1), // + L"ssscictg", + L"X#X", // + L"#X#", // + L"X#X", // + + L'X', Item::sulphur, // + L'#', Tile::sand, L'T'); + + addShapedRecipy( + new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::SAND_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::sandStone, L'S'); + + addShapedRecipy( + new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::STONE_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::rock, L'S'); + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, + StoneSlabTile::COBBLESTONE_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::stoneBrick, L'S'); + + addShapedRecipy( + new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::BRICK_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::redBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, + StoneSlabTile::SMOOTHBRICK_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::stoneBrickSmooth, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, + StoneSlabTile::NETHERBRICK_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::netherBrick, L'S'); + + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, + StoneSlabTile::QUARTZ_SLAB), // + L"sctg", + L"###", // + + L'#', Tile::quartzBlock, L'S'); + + addShapedRecipy(new ItemInstance(Tile::woodSlabHalf, 6, 0), // + L"sczg", + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, 0), L'S'); + // TU9 - adding wood slabs + + addShapedRecipy( + new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::BIRCH_TRUNK), // + L"sczg", + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::BIRCH_TRUNK), L'S'); + + addShapedRecipy( + new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::DARK_TRUNK), // + L"sczg", + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::DARK_TRUNK), L'S'); + + addShapedRecipy( + new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::JUNGLE_TRUNK), // + L"sczg", + L"###", // + + L'#', new ItemInstance(Tile::wood, 1, TreeTile::JUNGLE_TRUNK), L'S'); + + // iCount=getRecipies()->size(); + + addShapedRecipy(new ItemInstance(Item::cake, 1), // + L"ssscicicicig", + L"AAA", // + L"BEB", // + L"CCC", // + + L'A', Item::milk, // + L'B', Item::sugar, // + L'C', Item::wheat, L'E', Item::egg, L'F'); + + addShapedRecipy(new ItemInstance(Item::sugar, 1), // + L"scig", + L"#", // + + L'#', Item::reeds, L'F'); + + addShapedRecipy(new ItemInstance(Tile::rail, 16), // + L"ssscicig", + L"X X", // + L"X#X", // + L"X X", // + + L'X', Item::ironIngot, // + L'#', Item::stick, L'V'); + + addShapedRecipy(new ItemInstance(Tile::goldenRail, 6), // + L"ssscicicig", + L"X X", // + L"X#X", // + L"XRX", // + + L'X', Item::goldIngot, // + L'R', Item::redStone, // + L'#', Item::stick, L'V'); + + addShapedRecipy(new ItemInstance(Tile::detectorRail, 6), // + L"ssscicictg", + L"X X", // + L"X#X", // + L"XRX", // + + L'X', Item::ironIngot, // + L'R', Item::redStone, // + L'#', Tile::pressurePlate_stone, L'V'); + + addShapedRecipy(new ItemInstance(Item::minecart, 1), // + L"sscig", + L"# #", // + L"###", // + + L'#', Item::ironIngot, L'V'); + + addShapedRecipy(new ItemInstance(Item::minecart_chest, 1), // + L"ssctcig", + L"A", // + L"B", // + + L'A', Tile::chest, L'B', Item::minecart, L'V'); + + addShapedRecipy(new ItemInstance(Item::minecart_furnace, 1), // + L"ssctcig", + L"A", // + L"B", // + + L'A', Tile::furnace, L'B', Item::minecart, L'V'); + + addShapedRecipy(new ItemInstance(Item::boat, 1), // + L"ssctg", + L"# #", // + L"###", // + + L'#', Tile::wood, L'V'); + + addShapedRecipy(new ItemInstance((Item*)Item::fishingRod, 1), // + L"ssscicig", + L" #", // + L" #X", // + L"# X", // + + L'#', Item::stick, L'X', Item::string, L'T'); + + addShapedRecipy(new ItemInstance(Item::carrotOnAStick, 1), // + L"sscicig", + L"# ", // + L" X", // + + L'#', Item::fishingRod, L'X', Item::carrots, L'T') + ->keepTag(); + + addShapedRecipy(new ItemInstance(Item::flintAndSteel, 1), // + L"sscicig", + L"A ", // + L" B", // + + L'A', Item::ironIngot, L'B', Item::flint, L'T'); + + addShapedRecipy(new ItemInstance(Item::bread, 1), // + L"scig", + L"###", // + + L'#', Item::wheat, L'F'); + + // Moved bow and arrow in from weapons to avoid stacking on the group name + // display + addShapedRecipy(new ItemInstance((Item*)Item::bow, 1), // + L"ssscicig", + L" #X", // + L"# X", // + L" #X", // + + L'X', Item::string, // + L'#', Item::stick, L'T'); + + addShapedRecipy(new ItemInstance(Item::arrow, 4), // + L"ssscicicig", + L"X", // + L"#", // + L"Y", // + + L'Y', Item::feather, // + L'X', Item::flint, // + L'#', Item::stick, L'T'); + + pWeaponRecipies->addRecipes(this); + + addShapedRecipy(new ItemInstance(Item::bucket_empty, 1), // + L"sscig", + L"# #", // + L" # ", // + + L'#', Item::ironIngot, L'T'); + + addShapedRecipy(new ItemInstance(Item::bowl, 4), // + L"ssctg", + L"# #", // + L" # ", // + + L'#', Tile::wood, L'T'); + + addShapedRecipy(new ItemInstance(Item::glassBottle, 3), // + L"ssctg", + L"# #", // + L" # ", // + + L'#', Tile::glass, L'T'); + + addShapedRecipy(new ItemInstance(Item::flowerPot, 1), // + L"sscig", + L"# #", // + L" # ", // + + L'#', Item::brick, L'D'); + + // torch made of charcoal - moved to be the default due to the tutorial + // using it + addShapedRecipy(new ItemInstance(Tile::torch, 4), // + L"ssczcig", + L"X", // + L"#", // + + L'X', + new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL), // + L'#', Item::stick, L'T'); + + addShapedRecipy(new ItemInstance(Tile::torch, 4), // + L"sscicig", + L"X", // + L"#", // + L'X', Item::coal, // + L'#', Item::stick, L'T'); + + addShapedRecipy(new ItemInstance(Tile::lightGem, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::yellowDust, L'T'); + + addShapedRecipy(new ItemInstance(Tile::quartzBlock, 1), // + L"sscig", + L"##", // + L"##", // + + L'#', Item::netherQuartz, L'S'); + + addShapedRecipy(new ItemInstance(Tile::lever, 1), // + L"ssctcig", + L"X", // + L"#", // + + L'#', Tile::stoneBrick, L'X', Item::stick, L'M'); + + addShapedRecipy(new ItemInstance(Tile::tripWireSource, 2), // + L"sssctcicig", + L"I", // + L"S", // + L"#", // + + L'#', Tile::wood, L'S', Item::stick, L'I', Item::ironIngot, + L'M'); + + addShapedRecipy(new ItemInstance(Tile::notGate_on, 1), // + L"sscicig", + L"X", // + L"#", // + + L'#', Item::stick, L'X', Item::redStone, L'M'); + + addShapedRecipy(new ItemInstance(Item::diode, 1), // + L"ssctcictg", + L"#X#", // + L"III", // + + L'#', Tile::notGate_on, L'X', Item::redStone, L'I', + Tile::rock, L'M'); + + addShapedRecipy(new ItemInstance(Item::clock, 1), // + L"ssscicig", + L" # ", // + L"#X#", // + L" # ", // + L'#', Item::goldIngot, L'X', Item::redStone, L'T'); + + addShapelessRecipy(new ItemInstance(Item::eyeOfEnder, 1), // + L"iig", Item::enderPearl, Item::blazePowder, L'T'); + + addShapelessRecipy(new ItemInstance(Item::fireball, 3), // + L"iiig", Item::sulphur, Item::blazePowder, Item::coal, + L'T'); + + addShapelessRecipy(new ItemInstance(Item::fireball, 3), // + L"iizg", Item::sulphur, Item::blazePowder, + new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL), + L'T'); + + addShapedRecipy(new ItemInstance(Item::compass, 1), // + L"ssscicig", + L" # ", // + L"#X#", // + L" # ", // + + L'#', Item::ironIngot, L'X', Item::redStone, L'T'); + + // 4J-PB Added a MapItem init + addShapedRecipy(new ItemInstance(Item::map, 1), // + L"ssscicig", + L"###", // + L"#X#", // + L"###", // + + L'#', Item::paper, L'X', Item::compass, L'T'); + + addShapedRecipy(new ItemInstance(Tile::button, 1), // + L"sctg", + L"#", // + // L"#", // + L'#', Tile::rock, L'M'); + + addShapedRecipy(new ItemInstance(Tile::button_wood, 1), // + L"sctg", + L"#", // + // L"#", // + L'#', Tile::wood, L'M'); + + addShapedRecipy(new ItemInstance(Tile::pressurePlate_wood, 1), // + L"sctg", + L"##", // + L'#', Tile::wood, L'M'); + + addShapedRecipy(new ItemInstance(Tile::pressurePlate_stone, 1), // + L"sctg", + L"##", // + L'#', Tile::rock, L'M'); + + addShapedRecipy(new ItemInstance(Tile::dispenser, 1), // + L"sssctcicig", + L"###", // + L"#X#", // + L"#R#", // + L'#', Tile::stoneBrick, L'X', Item::bow, L'R', + Item::redStone, L'M'); + + addShapedRecipy(new ItemInstance(Item::cauldron, 1), // + L"ssscig", + L"# #", // + L"# #", // + L"###", // + + L'#', Item::ironIngot, L'T'); + + addShapedRecipy(new ItemInstance(Item::brewingStand, 1), // + L"ssctcig", + L" B ", // + L"###", // + + L'#', Tile::stoneBrick, L'B', Item::blazeRod, L'S'); + + addShapedRecipy(new ItemInstance(Tile::litPumpkin, 1), // + L"ssctctg", + L"A", // + L"B", // + + L'A', Tile::pumpkin, L'B', Tile::torch, L'T'); + + addShapedRecipy(new ItemInstance(Tile::recordPlayer, 1), // + L"sssctcig", + L"###", // + L"#X#", // + L"###", // + + L'#', Tile::wood, L'X', Item::diamond, 'D'); + + addShapedRecipy(new ItemInstance(Item::paper, 3), // + L"scig", + L"###", // + + L'#', Item::reeds, L'D'); + + addShapelessRecipy(new ItemInstance(Item::book, 1), L"iiiig", Item::paper, + Item::paper, Item::paper, Item::leather, L'D'); + + // addShapelessRecipy(new ItemInstance(Item.writingBook, 1), // + // Item.book, new ItemInstance(Item.dye_powder, 1, + // DyePowderItem.BLACK), Item.feather); + + addShapedRecipy(new ItemInstance(Tile::musicBlock, 1), // + L"sssctcig", + L"###", // + L"#X#", // + L"###", // + + L'#', Tile::wood, L'X', Item::redStone, L'M'); + + addShapedRecipy(new ItemInstance(Tile::bookshelf, 1), // + L"sssctcig", + L"###", // + L"XXX", // + L"###", // + + L'#', Tile::wood, L'X', Item::book, L'D'); + + addShapedRecipy(new ItemInstance(Item::painting, 1), // + L"ssscictg", + L"###", // + L"#X#", // + L"###", // + + L'#', Item::stick, L'X', Tile::cloth, L'D'); + + addShapedRecipy(new ItemInstance(Item::frame, 1), // + L"ssscicig", + L"###", // + L"#X#", // + L"###", // + + L'#', Item::stick, L'X', Item::leather, L'D'); + + pOreRecipies->addRecipes(this); + + addShapedRecipy(new ItemInstance(Item::goldIngot), // + L"ssscig", + L"###", // + L"###", // + L"###", // + + L'#', Item::goldNugget, L'D'); + + addShapedRecipy(new ItemInstance(Item::goldNugget, 9), // + L"scig", + L"#", // + L'#', Item::goldIngot, L'D'); + + // 4J-PB - moving into decorations to make the structures list smaller + addShapedRecipy(new ItemInstance(Item::sign, 3), // + L"sssctcig", + L"###", // + L"###", // + L" X ", // + + L'#', Tile::wood, L'X', Item::stick, L'D'); + + // 4J - TODO - put these new 1.7.3 items in required place within recipes + addShapedRecipy(new ItemInstance((Tile*)Tile::pistonBase, 1), // + L"sssctcicictg", + L"TTT", // + L"#X#", // + L"#R#", // + + L'#', Tile::stoneBrick, L'X', Item::ironIngot, L'R', + Item::redStone, L'T', Tile::wood, L'M'); + + addShapedRecipy(new ItemInstance((Tile*)Tile::pistonStickyBase, 1), // + L"sscictg", + L"S", // + L"P", // + + L'S', Item::slimeBall, L'P', Tile::pistonBase, L'M'); + + // Sort so the largest recipes get checked first! + /* 4J-PB - TODO + Collections.sort(recipies, new Comparator() + { + public: int compare(Recipy r0, Recipy r1) + { + + // shapeless recipes are put in the back of the list + if (r0 instanceof ShapelessRecipy && r1 instanceof + ShapedRecipy) + { + return 1; + } + if (r1 instanceof ShapelessRecipy && r0 instanceof + ShapedRecipy) + { + return -1; + } + + if (r1.size() < r0.size()) return -1; + if (r1.size() > r0.size()) return 1; + return 0; + } + }); + */ + + // 4J-PB removed System.out.println(recipies->size() + L" recipes"); + + // 4J-PB - build the array of ingredients required per recipe + buildRecipeIngredientsArray(); } -Recipes::Recipes() -{ - int iCount=0; - _init(); - - pArmorRecipes = new ArmorRecipes; - pClothDyeRecipes = new ClothDyeRecipes; - pFoodRecipies = new FoodRecipies; - pOreRecipies = new OreRecipies; - pStructureRecipies = new StructureRecipies; - pToolRecipies = new ToolRecipies; - pWeaponRecipies = new WeaponRecipies; - - // 4J Stu - These just don't work with our crafting menu - //recipies->push_back(new ArmorDyeRecipe()); - - addShapedRecipy(new ItemInstance(Tile::wood, 4, 0), // - L"sczg", - L"#", // - - L'#', new ItemInstance(Tile::treeTrunk, 1, 0), - L'S'); - - // TU9 - adding coloured wood - addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::BIRCH_TRUNK), // - L"sczg", - L"#", // - - L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::BIRCH_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::DARK_TRUNK), // - L"sczg", - L"#", // - - L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::DARK_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::JUNGLE_TRUNK), // - L"sczg", - L"#", // - - L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::JUNGLE_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Item::stick, 4), // - L"ssctg", - L"#", // - L"#", // - - L'#', Tile::wood, - L'S'); - - pToolRecipies->addRecipes(this); - pFoodRecipies->addRecipes(this); - pStructureRecipies->addRecipes(this); - - - // 4J-PB - changing the order to the way we want to have things in the crafting menu - // bed - addShapedRecipy(new ItemInstance(Item::bed, 1), // - L"ssctctg", - L"###", // - L"XXX", // - L'#', Tile::cloth, L'X', Tile::wood, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::enchantTable, 1), // - L"sssctcicig", - L" B ", // - L"D#D", // - L"###", // - - L'#', Tile::obsidian, L'B', Item::book, L'D', Item::diamond, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::anvil, 1), // - L"sssctcig", - L"III", // - L" i ", // - L"iii", // - - L'I', Tile::ironBlock, L'i', Item::ironIngot, - L'S'); - - // 4J Stu - Reordered for crafting menu - addShapedRecipy(new ItemInstance(Tile::ladder, 3), // - L"ssscig", - L"# #", // - L"###", // - L"# #", // - - L'#', Item::stick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::fenceGate, 1), // - L"sscictg", - L"#W#", // - L"#W#", // - - L'#', Item::stick, L'W', Tile::wood, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::fence, 2), // - L"sscig", - L"###", // - L"###", // - - L'#', Item::stick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::netherFence, 6), // - L"ssctg", - L"###", // - L"###", // - - L'#', Tile::netherBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::ironFence, 16), // - L"sscig", - L"###", // - L"###", // - - L'#', Item::ironIngot, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::cobbleWall, 6, WallTile::TYPE_NORMAL), // - L"ssctg", - L"###", // - L"###", // - - L'#', Tile::stoneBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::cobbleWall, 6, WallTile::TYPE_MOSSY), // - L"ssctg", - L"###", // - L"###", // - - L'#', Tile::mossStone, - L'S'); - - addShapedRecipy(new ItemInstance(Item::door_wood, 1), // - L"sssctg", - L"##", // - L"##", // - L"##", // - - L'#', Tile::wood, - L'S'); - - addShapedRecipy(new ItemInstance(Item::door_iron, 1), // - L"ssscig", - L"##", // - L"##", // - L"##", // - - L'#', Item::ironIngot, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_wood, 4), // - L"sssczg", - L"# ", // - L"## ", // - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, 0), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::trapdoor, 2), // - L"ssctg", - L"###", // - L"###", // - - L'#', Tile::wood, - L'S'); - addShapedRecipy(new ItemInstance(Tile::stairs_stone, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::stoneBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_bricks, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::redBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_stoneBrickSmooth, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::stoneBrickSmooth, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_netherBricks, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::netherBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_sandstone, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::sandStone, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::woodStairsBirch, 4), // - L"sssczg", - L"# ", // - L"## ", // - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::BIRCH_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::woodStairsDark, 4), // - L"sssczg", - L"# ", // - L"## ", // - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::DARK_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::woodStairsJungle, 4), // - L"sssczg", - L"# ", // - L"## ", // - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::JUNGLE_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stairs_quartz, 4), // - L"sssctg", - L"# ", // - L"## ", // - L"###", // - - L'#', Tile::quartzBlock, - L'S'); - - pArmorRecipes->addRecipes(this); - //iCount=getRecipies()->size(); - - pClothDyeRecipes->addRecipes(this); - - - addShapedRecipy(new ItemInstance(Tile::snow, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::snowBall, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::clay, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::clay, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::redBrick, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::brick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::cloth, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::string, - L'D'); - - addShapedRecipy(new ItemInstance(Tile::tnt, 1), // - L"ssscictg", - L"X#X", // - L"#X#", // - L"X#X", // - - L'X', Item::sulphur,// - L'#', Tile::sand, - L'T'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::SAND_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::sandStone, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::STONE_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::rock, - L'S'); - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::COBBLESTONE_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::stoneBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::BRICK_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::redBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::SMOOTHBRICK_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::stoneBrickSmooth, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::NETHERBRICK_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::netherBrick, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::QUARTZ_SLAB), // - L"sctg", - L"###", // - - L'#', Tile::quartzBlock, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::woodSlabHalf, 6, 0), // - L"sczg", - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, 0), - L'S'); - // TU9 - adding wood slabs - - addShapedRecipy(new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::BIRCH_TRUNK), // - L"sczg", - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::BIRCH_TRUNK), - L'S'); - - - addShapedRecipy(new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::DARK_TRUNK), // - L"sczg", - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::DARK_TRUNK), - L'S'); - - addShapedRecipy(new ItemInstance(Tile::woodSlabHalf, 6, TreeTile::JUNGLE_TRUNK), // - L"sczg", - L"###", // - - L'#', new ItemInstance(Tile::wood, 1, TreeTile::JUNGLE_TRUNK), - L'S'); - - - - - - //iCount=getRecipies()->size(); - - addShapedRecipy(new ItemInstance(Item::cake, 1), // - L"ssscicicicig", - L"AAA", // - L"BEB", // - L"CCC", // - - L'A', Item::milk,// - L'B', Item::sugar,// - L'C', Item::wheat, L'E', Item::egg, - L'F'); - - addShapedRecipy(new ItemInstance(Item::sugar, 1), // - L"scig", - L"#", // - - L'#', Item::reeds, - L'F'); - - addShapedRecipy(new ItemInstance(Tile::rail, 16), // - L"ssscicig", - L"X X", // - L"X#X", // - L"X X", // - - L'X', Item::ironIngot,// - L'#', Item::stick, - L'V'); - - addShapedRecipy(new ItemInstance(Tile::goldenRail, 6), // - L"ssscicicig", - L"X X", // - L"X#X", // - L"XRX", // - - L'X', Item::goldIngot,// - L'R', Item::redStone,// - L'#', Item::stick, - L'V'); - - addShapedRecipy(new ItemInstance(Tile::detectorRail, 6), // - L"ssscicictg", - L"X X", // - L"X#X", // - L"XRX", // - - L'X', Item::ironIngot,// - L'R', Item::redStone,// - L'#', Tile::pressurePlate_stone, - L'V'); - - addShapedRecipy(new ItemInstance(Item::minecart, 1), // - L"sscig", - L"# #", // - L"###", // - - L'#', Item::ironIngot, - L'V'); - - addShapedRecipy(new ItemInstance(Item::minecart_chest, 1), // - L"ssctcig", - L"A", // - L"B", // - - L'A', Tile::chest, L'B', Item::minecart, - L'V'); - - addShapedRecipy(new ItemInstance(Item::minecart_furnace, 1), // - L"ssctcig", - L"A", // - L"B", // - - L'A', Tile::furnace, L'B', Item::minecart, - L'V'); - - addShapedRecipy(new ItemInstance(Item::boat, 1), // - L"ssctg", - L"# #", // - L"###", // - - L'#', Tile::wood, - L'V'); - - addShapedRecipy(new ItemInstance((Item *)Item::fishingRod, 1), // - L"ssscicig", - L" #", // - L" #X", // - L"# X", // - - L'#', Item::stick, L'X', Item::string, - L'T'); - - addShapedRecipy(new ItemInstance(Item::carrotOnAStick, 1), // - L"sscicig", - L"# ", // - L" X", // - - L'#', Item::fishingRod, L'X', Item::carrots, - L'T')->keepTag(); - - addShapedRecipy(new ItemInstance(Item::flintAndSteel, 1), // - L"sscicig", - L"A ", // - L" B", // - - L'A', Item::ironIngot, L'B', Item::flint, - L'T'); - - addShapedRecipy(new ItemInstance(Item::bread, 1), // - L"scig", - L"###", // - - L'#', Item::wheat, - L'F'); - - // Moved bow and arrow in from weapons to avoid stacking on the group name display - addShapedRecipy(new ItemInstance((Item *)Item::bow, 1), // - L"ssscicig", - L" #X", // - L"# X", // - L" #X", // - - L'X', Item::string,// - L'#', Item::stick, - L'T'); - - addShapedRecipy(new ItemInstance(Item::arrow, 4), // - L"ssscicicig", - L"X", // - L"#", // - L"Y", // - - L'Y', Item::feather,// - L'X', Item::flint,// - L'#', Item::stick, - L'T'); - - pWeaponRecipies->addRecipes(this); - - addShapedRecipy(new ItemInstance(Item::bucket_empty, 1), // - L"sscig", - L"# #", // - L" # ", // - - L'#', Item::ironIngot, - L'T'); - - addShapedRecipy(new ItemInstance(Item::bowl, 4), // - L"ssctg", - L"# #", // - L" # ", // - - L'#', Tile::wood, - L'T'); - - addShapedRecipy(new ItemInstance(Item::glassBottle, 3), // - L"ssctg", - L"# #", // - L" # ", // - - L'#', Tile::glass, - L'T'); - - addShapedRecipy(new ItemInstance(Item::flowerPot, 1), // - L"sscig", - L"# #", // - L" # ", // - - L'#', Item::brick, - L'D'); - - // torch made of charcoal - moved to be the default due to the tutorial using it - addShapedRecipy(new ItemInstance(Tile::torch, 4), // - L"ssczcig", - L"X", // - L"#", // - - L'X', new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL),// - L'#', Item::stick, - L'T'); - - addShapedRecipy(new ItemInstance(Tile::torch, 4), // - L"sscicig", - L"X", // - L"#", // - L'X', Item::coal,// - L'#', Item::stick, - L'T'); - - addShapedRecipy(new ItemInstance(Tile::lightGem, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::yellowDust, - L'T'); - - addShapedRecipy(new ItemInstance(Tile::quartzBlock, 1), // - L"sscig", - L"##", // - L"##", // - - L'#', Item::netherQuartz, - L'S'); - - addShapedRecipy(new ItemInstance(Tile::lever, 1), // - L"ssctcig", - L"X", // - L"#", // - - L'#', Tile::stoneBrick, L'X', Item::stick, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::tripWireSource, 2), // - L"sssctcicig", - L"I", // - L"S", // - L"#", // - - L'#', Tile::wood, L'S', Item::stick, L'I', Item::ironIngot, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::notGate_on, 1), // - L"sscicig", - L"X", // - L"#", // - - L'#', Item::stick, L'X', Item::redStone, - L'M'); - - addShapedRecipy(new ItemInstance(Item::diode, 1), // - L"ssctcictg", - L"#X#", // - L"III", // - - L'#', Tile::notGate_on, L'X', Item::redStone, L'I', Tile::rock, - L'M'); - - - addShapedRecipy(new ItemInstance(Item::clock, 1), // - L"ssscicig", - L" # ", // - L"#X#", // - L" # ", // - L'#', Item::goldIngot, L'X', Item::redStone, - L'T'); - - addShapelessRecipy(new ItemInstance(Item::eyeOfEnder, 1), // - L"iig", - Item::enderPearl, Item::blazePowder, - L'T'); - - addShapelessRecipy(new ItemInstance(Item::fireball, 3), // - L"iiig", - Item::sulphur, Item::blazePowder,Item::coal, - L'T'); - - addShapelessRecipy(new ItemInstance(Item::fireball, 3), // - L"iizg", - Item::sulphur, Item::blazePowder,new ItemInstance(Item::coal, 1, CoalItem::CHAR_COAL), - L'T'); - - - addShapedRecipy(new ItemInstance(Item::compass, 1), // - L"ssscicig", - L" # ", // - L"#X#", // - L" # ", // - - L'#', Item::ironIngot, L'X', Item::redStone, - L'T'); - - // 4J-PB Added a MapItem init - addShapedRecipy(new ItemInstance(Item::map, 1), // - L"ssscicig", - L"###", // - L"#X#", // - L"###", // - - L'#', Item::paper, L'X', Item::compass, - L'T'); - - addShapedRecipy(new ItemInstance(Tile::button, 1), // - L"sctg", - L"#", // - //L"#", // - L'#', Tile::rock, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::button_wood, 1), // - L"sctg", - L"#", // - //L"#", // - L'#', Tile::wood, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::pressurePlate_wood, 1), // - L"sctg", - L"##", // - L'#', Tile::wood, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::pressurePlate_stone, 1), // - L"sctg", - L"##", // - L'#', Tile::rock, - L'M'); - - - addShapedRecipy(new ItemInstance(Tile::dispenser, 1), // - L"sssctcicig", - L"###", // - L"#X#", // - L"#R#", // - L'#', Tile::stoneBrick, L'X', Item::bow, L'R', Item::redStone, - L'M'); - - addShapedRecipy(new ItemInstance(Item::cauldron, 1), // - L"ssscig", - L"# #", // - L"# #", // - L"###", // - - L'#', Item::ironIngot, - L'T'); - - addShapedRecipy(new ItemInstance(Item::brewingStand, 1), // - L"ssctcig", - L" B ", // - L"###", // - - L'#', Tile::stoneBrick, L'B', Item::blazeRod, - L'S'); - - - addShapedRecipy(new ItemInstance(Tile::litPumpkin, 1), // - L"ssctctg", - L"A", // - L"B", // - - L'A', Tile::pumpkin, L'B', Tile::torch, - L'T'); - - - addShapedRecipy(new ItemInstance(Tile::recordPlayer, 1), // - L"sssctcig", - L"###", // - L"#X#", // - L"###", // - - L'#', Tile::wood, L'X', Item::diamond, - 'D'); - - - - addShapedRecipy(new ItemInstance(Item::paper, 3), // - L"scig", - L"###", // - - L'#', Item::reeds, - L'D'); - - addShapelessRecipy(new ItemInstance(Item::book, 1), - L"iiiig", - Item::paper, - Item::paper, - Item::paper, - Item::leather, - L'D'); - - //addShapelessRecipy(new ItemInstance(Item.writingBook, 1), // - // Item.book, new ItemInstance(Item.dye_powder, 1, DyePowderItem.BLACK), Item.feather); - - addShapedRecipy(new ItemInstance(Tile::musicBlock, 1), // - L"sssctcig", - L"###", // - L"#X#", // - L"###", // - - L'#', Tile::wood, L'X', Item::redStone, - L'M'); - - addShapedRecipy(new ItemInstance(Tile::bookshelf, 1), // - L"sssctcig", - L"###", // - L"XXX", // - L"###", // - - L'#', Tile::wood, L'X', Item::book, - L'D'); - - addShapedRecipy(new ItemInstance(Item::painting, 1), // - L"ssscictg", - L"###", // - L"#X#", // - L"###", // - - L'#', Item::stick, L'X', Tile::cloth, - L'D'); - - - addShapedRecipy(new ItemInstance(Item::frame, 1), // - L"ssscicig", - L"###", // - L"#X#", // - L"###", // - - L'#', Item::stick, L'X', Item::leather, - L'D'); - - pOreRecipies->addRecipes(this); - - addShapedRecipy(new ItemInstance(Item::goldIngot), // - L"ssscig", - L"###", // - L"###", // - L"###", // - - L'#', Item::goldNugget, - L'D'); - - addShapedRecipy(new ItemInstance(Item::goldNugget, 9), // - L"scig", - L"#", // - L'#', Item::goldIngot, - L'D'); - - // 4J-PB - moving into decorations to make the structures list smaller - addShapedRecipy(new ItemInstance(Item::sign, 3), // - L"sssctcig", - L"###", // - L"###", // - L" X ", // - - L'#', Tile::wood, L'X', Item::stick, - L'D'); - - // 4J - TODO - put these new 1.7.3 items in required place within recipes - addShapedRecipy(new ItemInstance((Tile *)Tile::pistonBase, 1), // - L"sssctcicictg", - L"TTT", // - L"#X#", // - L"#R#", // - - L'#', Tile::stoneBrick, L'X', Item::ironIngot, L'R', Item::redStone, L'T', Tile::wood, - L'M'); - - addShapedRecipy(new ItemInstance((Tile *)Tile::pistonStickyBase, 1), // - L"sscictg", - L"S", // - L"P", // - - L'S', Item::slimeBall, L'P', Tile::pistonBase, - L'M'); - - - - - // Sort so the largest recipes get checked first! - /* 4J-PB - TODO - Collections.sort(recipies, new Comparator() - { - public: int compare(Recipy r0, Recipy r1) - { - - // shapeless recipes are put in the back of the list - if (r0 instanceof ShapelessRecipy && r1 instanceof ShapedRecipy) - { - return 1; - } - if (r1 instanceof ShapelessRecipy && r0 instanceof ShapedRecipy) - { - return -1; - } - - if (r1.size() < r0.size()) return -1; - if (r1.size() > r0.size()) return 1; - return 0; - } - }); - */ - - // 4J-PB removed System.out.println(recipies->size() + L" recipes"); - - // 4J-PB - build the array of ingredients required per recipe - buildRecipeIngredientsArray(); +// 4J-PB - this function has been substantially changed due to the differences +// with a va_list of classes in C++ and Java +ShapedRecipy* Recipes::addShapedRecipy(ItemInstance* result, ...) { + std::wstring map = L""; + int p = 0; + int width = 0; + int height = 0; + int group = ShapedRecipy::eGroupType_Decoration; + va_list vl; + wchar_t* wchTypes; + wchar_t* pwchString; + std::wstring wString; + std::wstring* wStringA; + ItemInstance* pItemInstance; + Tile* pTile; + Item* pItem; + wchar_t wchFrom; + int iCount; + ItemInstance** ids = NULL; + + myMap* mappings = new std::unordered_map(); + + va_start(vl, result); + // 4J-PB - second argument is a list of the types + // s - string + // w - string array + // a - char * + // c - char + // z - ItemInstance * + // i - Item * + // t - Tile * + // g - group [wt] - which group does the item created by the recipe belong + // in. Set a default until all recipes have a group + + wchTypes = va_arg(vl, wchar_t*); + + for (int i = 0; wchTypes[i] != L'\0'; ++i) { + if (wchTypes[i + 1] == L'\0' && wchTypes[i] != L'g') { + app.DebugPrintf("Missing group type\n"); + } + + switch (wchTypes[i]) { + case L'a': + pwchString = va_arg(vl, wchar_t*); + wString = pwchString; + height++; + width = (int)wString.length(); + map += wString; + break; + case L's': + pwchString = va_arg(vl, wchar_t*); + wString = pwchString; + height++; + width = (int)wString.length(); + map += wString; + break; + case L'w': + wStringA = va_arg(vl, std::wstring*); + iCount = 0; + do { + wString = wStringA[iCount++]; + if (!wString.empty()) { + height++; + width = (int)wString.length(); + map += wString; + } + } while (!wString.empty()); + + break; + case L'c': + wchFrom = (wchar_t)va_arg(vl, int); + break; + case L'z': + pItemInstance = va_arg(vl, ItemInstance*); + mappings->insert(myMap::value_type(wchFrom, pItemInstance)); + break; + case L'i': + pItem = va_arg(vl, Item*); + pItemInstance = new ItemInstance(pItem); + mappings->insert(myMap::value_type(wchFrom, pItemInstance)); + break; + case L't': + pTile = va_arg(vl, Tile*); + pItemInstance = new ItemInstance(pTile, 1, ANY_AUX_VALUE); + mappings->insert(myMap::value_type(wchFrom, pItemInstance)); + break; + case L'g': + wchFrom = (wchar_t)va_arg(vl, int); + switch (wchFrom) { + // case L'W': + // group=ShapedRecipy::eGroupType_Weapon; + // break; + case L'T': + group = ShapedRecipy::eGroupType_Tool; + break; + case L'A': + group = ShapedRecipy::eGroupType_Armour; + break; + case L'S': + group = ShapedRecipy::eGroupType_Structure; + break; + case L'V': + group = ShapedRecipy::eGroupType_Transport; + break; + case L'M': + group = ShapedRecipy::eGroupType_Mechanism; + break; + case L'F': + group = ShapedRecipy::eGroupType_Food; + break; + case L'D': + default: + group = ShapedRecipy::eGroupType_Decoration; + break; + } + break; + } + + ids = new ItemInstance*[width * height]; + + for (int j = 0; j < width * height; j++) { + wchar_t ch = map[j]; + myMap::iterator it = mappings->find(ch); + if (it != mappings->end()) { + ids[j] = it->second; + } else { + ids[j] = NULL; + } + } + } + + va_end(vl); + + ShapedRecipy* recipe = new ShapedRecipy(width, height, ids, result, group); + recipies->push_back(recipe); + return recipe; } -// 4J-PB - this function has been substantially changed due to the differences with a va_list of classes in C++ and Java -ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) -{ - std::wstring map = L""; - int p = 0; - int width = 0; - int height = 0; - int group = ShapedRecipy::eGroupType_Decoration; - va_list vl; - wchar_t *wchTypes; - wchar_t *pwchString; - std::wstring wString; - std::wstring *wStringA; - ItemInstance *pItemInstance; - Tile *pTile; - Item *pItem; - wchar_t wchFrom; - int iCount; - ItemInstance **ids = NULL; +void Recipes::addShapelessRecipy(ItemInstance* result, ...) { + va_list vl; + wchar_t* szTypes; + std::wstring String; + ItemInstance* pItemInstance; + Tile* pTile; + Item* pItem; + Recipy::_eGroupType group = Recipy::eGroupType_Decoration; + wchar_t wchFrom; + std::vector* ingredients = new std::vector(); - myMap *mappings = new std::unordered_map(); + va_start(vl, result); + // 4J-PB - second argument is a list of the types + // z - ItemInstance * + // i - Item * + // t - Tile * + szTypes = va_arg(vl, wchar_t*); - va_start(vl,result); - // 4J-PB - second argument is a list of the types - // s - string - // w - string array - // a - char * - // c - char - // z - ItemInstance * - // i - Item * - // t - Tile * - // g - group [wt] - which group does the item created by the recipe belong in. Set a default until all recipes have a group + for (int i = 0; szTypes[i] != L'\0'; ++i) { + switch (szTypes[i]) { + case L'z': + pItemInstance = va_arg(vl, ItemInstance*); + // 4J-PB - original code copies the item instance, copy the + // pointer isnt the same... + // TODO + ingredients->push_back(pItemInstance->copy_not_shared()); + break; + case L'i': + pItem = va_arg(vl, Item*); + pItemInstance = new ItemInstance(pItem); + ingredients->push_back(pItemInstance); + break; + case L't': + pTile = va_arg(vl, Tile*); + ingredients->push_back(new ItemInstance(pTile)); + break; + case L'g': + wchFrom = (wchar_t)va_arg(vl, int); + switch (wchFrom) { + case L'T': + group = Recipy::eGroupType_Tool; + break; + case L'A': + group = Recipy::eGroupType_Armour; + break; + case L'S': + group = Recipy::eGroupType_Structure; + break; + case L'V': + group = Recipy::eGroupType_Transport; + break; + case L'M': + group = Recipy::eGroupType_Mechanism; + break; + case L'F': + group = Recipy::eGroupType_Food; + break; + case L'D': + default: + group = Recipy::eGroupType_Decoration; + break; + } + break; + } + } - wchTypes = va_arg(vl,wchar_t *); - - for(int i = 0; wchTypes[i] != L'\0'; ++i ) - { - if(wchTypes[i+1]==L'\0' && wchTypes[i]!=L'g') - { - app.DebugPrintf("Missing group type\n"); - } - - switch(wchTypes[i]) - { - case L'a': - pwchString=va_arg(vl,wchar_t *); - wString=pwchString; - height++; - width = (int)wString.length(); - map += wString; - break; - case L's': - pwchString=va_arg(vl,wchar_t *); - wString=pwchString; - height++; - width = (int)wString.length(); - map += wString; - break; - case L'w': - wStringA=va_arg(vl,std::wstring *); - iCount=0; - do - { - wString=wStringA[iCount++]; - if(!wString.empty()) - { - height++; - width = (int)wString.length(); - map += wString; - } - } - while(!wString.empty()); - - break; - case L'c': - wchFrom=(wchar_t)va_arg(vl,int); - break; - case L'z': - pItemInstance=va_arg(vl,ItemInstance *); - mappings->insert(myMap::value_type(wchFrom,pItemInstance)); - break; - case L'i': - pItem=va_arg(vl,Item *); - pItemInstance= new ItemInstance(pItem); - mappings->insert(myMap::value_type(wchFrom,pItemInstance)); - break; - case L't': - pTile=va_arg(vl,Tile *); - pItemInstance= new ItemInstance(pTile,1,ANY_AUX_VALUE); - mappings->insert(myMap::value_type(wchFrom,pItemInstance)); - break; - case L'g': - wchFrom=(wchar_t)va_arg(vl,int); - switch(wchFrom) - { -// case L'W': -// group=ShapedRecipy::eGroupType_Weapon; -// break; - case L'T': - group=ShapedRecipy::eGroupType_Tool; - break; - case L'A': - group=ShapedRecipy::eGroupType_Armour; - break; - case L'S': - group=ShapedRecipy::eGroupType_Structure; - break; - case L'V': - group=ShapedRecipy::eGroupType_Transport; - break; - case L'M': - group=ShapedRecipy::eGroupType_Mechanism; - break; - case L'F': - group=ShapedRecipy::eGroupType_Food; - break; - case L'D': - default: - group=ShapedRecipy::eGroupType_Decoration; - break; - - } - break; - - } - - - ids = new ItemInstance *[width * height]; - - for (int j = 0; j < width * height; j++) - { - wchar_t ch = map[j]; - myMap::iterator it=mappings->find(ch); - if (it != mappings->end()) - { - ids[j] =it->second; - } - else - { - ids[j] = NULL; - } - } - } - - va_end(vl); - - ShapedRecipy *recipe = new ShapedRecipy(width, height, ids, result, group); - recipies->push_back(recipe); - return recipe; + recipies->push_back(new ShapelessRecipy(result, ingredients, group)); } -void Recipes::addShapelessRecipy(ItemInstance *result,... ) -{ - va_list vl; - wchar_t *szTypes; - std::wstring String; - ItemInstance *pItemInstance; - Tile *pTile; - Item *pItem; - Recipy::_eGroupType group = Recipy::eGroupType_Decoration; - wchar_t wchFrom; - std::vector *ingredients = new std::vector(); +std::shared_ptr Recipes::getItemFor( + std::shared_ptr craftSlots, Level* level) { + int count = 0; + std::shared_ptr first = nullptr; + std::shared_ptr second = nullptr; + for (int i = 0; i < craftSlots->getContainerSize(); i++) { + std::shared_ptr item = craftSlots->getItem(i); + if (item != NULL) { + if (count == 0) first = item; + if (count == 1) second = item; + count++; + } + } - va_start(vl,result); - // 4J-PB - second argument is a list of the types - // z - ItemInstance * - // i - Item * - // t - Tile * - szTypes = va_arg(vl,wchar_t *); + if (count == 2 && first->id == second->id && first->count == 1 && + second->count == 1 && Item::items[first->id]->canBeDepleted()) { + Item* item = Item::items[first->id]; + int remaining1 = item->getMaxDamage() - first->getDamageValue(); + int remaining2 = item->getMaxDamage() - second->getDamageValue(); + int remaining = + (remaining1 + remaining2) + item->getMaxDamage() * 5 / 100; + int resultDamage = item->getMaxDamage() - remaining; + if (resultDamage < 0) resultDamage = 0; + return std::shared_ptr( + new ItemInstance(first->id, 1, resultDamage)); + } - for(int i = 0; szTypes[i] != L'\0'; ++i ) - { - switch(szTypes[i]) - { - case L'z': - pItemInstance=va_arg(vl,ItemInstance *); - // 4J-PB - original code copies the item instance, copy the pointer isnt the same... - // TODO - ingredients->push_back(pItemInstance->copy_not_shared()); - break; - case L'i': - pItem=va_arg(vl,Item *); - pItemInstance= new ItemInstance(pItem); - ingredients->push_back(pItemInstance); - break; - case L't': - pTile=va_arg(vl,Tile *); - ingredients->push_back(new ItemInstance(pTile)); - break; - case L'g': - wchFrom=(wchar_t)va_arg(vl,int); - switch(wchFrom) - { - - case L'T': - group=Recipy::eGroupType_Tool; - break; - case L'A': - group=Recipy::eGroupType_Armour; - break; - case L'S': - group=Recipy::eGroupType_Structure; - break; - case L'V': - group=Recipy::eGroupType_Transport; - break; - case L'M': - group=Recipy::eGroupType_Mechanism; - break; - case L'F': - group=Recipy::eGroupType_Food; - break; - case L'D': - default: - group=Recipy::eGroupType_Decoration; - break; - - } - break; } - } - - recipies->push_back(new ShapelessRecipy(result, ingredients, group)); + AUTO_VAR(itEnd, recipies->end()); + for (AUTO_VAR(it, recipies->begin()); it != itEnd; it++) { + Recipy* r = *it; // recipies->at(i); + if (r->matches(craftSlots, level)) return r->assemble(craftSlots); + } + return nullptr; } -std::shared_ptr Recipes::getItemFor(std::shared_ptr craftSlots, Level *level) -{ - int count = 0; - std::shared_ptr first = nullptr; - std::shared_ptr second = nullptr; - for (int i = 0; i < craftSlots->getContainerSize(); i++) - { - std::shared_ptr item = craftSlots->getItem(i); - if (item != NULL) - { - if (count == 0) first = item; - if (count == 1) second = item; - count++; - } - } - - if (count == 2 && first->id == second->id && first->count == 1 && second->count == 1 && Item::items[first->id]->canBeDepleted()) - { - Item *item = Item::items[first->id]; - int remaining1 = item->getMaxDamage() - first->getDamageValue(); - int remaining2 = item->getMaxDamage() - second->getDamageValue(); - int remaining = (remaining1 + remaining2) + item->getMaxDamage() * 5 / 100; - int resultDamage = item->getMaxDamage() - remaining; - if (resultDamage < 0) resultDamage = 0; - return std::shared_ptr( new ItemInstance(first->id, 1, resultDamage) ); - } - - AUTO_VAR(itEnd, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEnd; it++) - { - Recipy *r = *it; //recipies->at(i); - if (r->matches(craftSlots, level)) return r->assemble(craftSlots); - } - return nullptr; -} - -std::vector *Recipes::getRecipies() -{ - return recipies; -} +std::vector* Recipes::getRecipies() { return recipies; } // 4J-PB - added to deal with Xb0x 'crafting' -std::shared_ptr Recipes::getItemForRecipe(Recipy *r) -{ - return r->assemble(nullptr); +std::shared_ptr Recipes::getItemForRecipe(Recipy* r) { + return r->assemble(nullptr); } // 4J-PB - build the required ingredients for recipes -void Recipes::buildRecipeIngredientsArray(void) -{ - //RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); +void Recipes::buildRecipeIngredientsArray(void) { + // RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); - int iRecipeC=(int)recipies->size(); + int iRecipeC = (int)recipies->size(); - m_pRecipeIngredientsRequired= new Recipy::INGREDIENTS_REQUIRED [iRecipeC]; + m_pRecipeIngredientsRequired = new Recipy::INGREDIENTS_REQUIRED[iRecipeC]; - int iCount=0; - AUTO_VAR(itEndRec, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEndRec; it++) - { - Recipy *recipe = *it; - //wprintf(L"RECIPE - [%d] is %w\n",iCount,recipe->getResultItem()->getItem()->getName()); - recipe->requires(&m_pRecipeIngredientsRequired[iCount++]); - } + int iCount = 0; + AUTO_VAR(itEndRec, recipies->end()); + for (AUTO_VAR(it, recipies->begin()); it != itEndRec; it++) { + Recipy* recipe = *it; + // wprintf(L"RECIPE - [%d] is + // %w\n",iCount,recipe->getResultItem()->getItem()->getName()); + recipe->requires(&m_pRecipeIngredientsRequired[iCount++]); + } - //printf("Total recipes in buildRecipeIngredientsArray - %d",iCount); + // printf("Total recipes in buildRecipeIngredientsArray - %d",iCount); } -Recipy::INGREDIENTS_REQUIRED *Recipes::getRecipeIngredientsArray(void) -{ - return m_pRecipeIngredientsRequired; +Recipy::INGREDIENTS_REQUIRED* Recipes::getRecipeIngredientsArray(void) { + return m_pRecipeIngredientsRequired; } diff --git a/Minecraft.World/Recipes/Recipes.h b/Minecraft.World/Recipes/Recipes.h index 4a538962d..0ad7f2056 100644 --- a/Minecraft.World/Recipes/Recipes.h +++ b/Minecraft.World/Recipes/Recipes.h @@ -19,7 +19,6 @@ import net.minecraft.world.level.tile.Tile; #pragma once - class CraftingContainer; class FireTile; @@ -32,80 +31,89 @@ class ToolRecipies; class WeaponRecipies; class ShapedRecipy; -typedef std::unordered_map myMap; +typedef std::unordered_map myMap; -#define ADD_OBJECT(a,b) a.push_back(new Object(b)) +#define ADD_OBJECT(a, b) a.push_back(new Object(b)) -class Object -{ +class Object { public: - union - { - Tile *tile; - FireTile *firetile; - Item *item; - MapItem *mapitem; - ItemInstance *iteminstance; - }; + union { + Tile* tile; + FireTile* firetile; + Item* item; + MapItem* mapitem; + ItemInstance* iteminstance; + }; - Object() { eType=eTYPE_NOTSET;} - Object(Tile *t) { eType=eType_TILE;tile=t;} - Object(FireTile *t) { eType=eType_FIRETILE;firetile=t;} - Object(Item *i) { eType=eType_ITEM; item=i;} - Object(MapItem *i) { eType=eType_MAPITEM;mapitem=i;} - Object(ItemInstance *i) { eType=eType_ITEMINSTANCE;iteminstance=i;} + Object() { eType = eTYPE_NOTSET; } + Object(Tile* t) { + eType = eType_TILE; + tile = t; + } + Object(FireTile* t) { + eType = eType_FIRETILE; + firetile = t; + } + Object(Item* i) { + eType = eType_ITEM; + item = i; + } + Object(MapItem* i) { + eType = eType_MAPITEM; + mapitem = i; + } + Object(ItemInstance* i) { + eType = eType_ITEMINSTANCE; + iteminstance = i; + } - eINSTANCEOF instanceof() { return eType;} - eINSTANCEOF GetType() { return eType; }; + eINSTANCEOF instanceof() { return eType; } + eINSTANCEOF GetType() { return eType; }; private: - eINSTANCEOF eType; + eINSTANCEOF eType; }; -class Recipes -{ +class Recipes { public: - static const int ANY_AUX_VALUE = -1; - -private: - static Recipes *instance; - - std::vector *recipies; - -public: - static void staticCtor(); - -public: - static Recipes *getInstance() - { - return instance; - } - -private: - void _init(); // 4J add - Recipes(); - -public: - ShapedRecipy *addShapedRecipy(ItemInstance *, ... ); - void addShapelessRecipy(ItemInstance *result,... ); - - std::shared_ptr getItemFor(std::shared_ptr craftSlots, Level *level); - std::vector *getRecipies(); - - // 4J-PB - Added all below for new Xbox 'crafting' - std::shared_ptr getItemForRecipe(Recipy *r); - Recipy::INGREDIENTS_REQUIRED *getRecipeIngredientsArray(); + static const int ANY_AUX_VALUE = -1; private: - void buildRecipeIngredientsArray(); - Recipy::INGREDIENTS_REQUIRED *m_pRecipeIngredientsRequired; + static Recipes* instance; + std::vector* recipies; - static ToolRecipies *pToolRecipies; - static WeaponRecipies *pWeaponRecipies; - static StructureRecipies *pStructureRecipies; - static OreRecipies *pOreRecipies; - static FoodRecipies *pFoodRecipies; - static ClothDyeRecipes *pClothDyeRecipes; - static ArmorRecipes *pArmorRecipes; +public: + static void staticCtor(); + +public: + static Recipes* getInstance() { return instance; } + +private: + void _init(); // 4J add + Recipes(); + +public: + ShapedRecipy* addShapedRecipy(ItemInstance*, ...); + void addShapelessRecipy(ItemInstance* result, ...); + + std::shared_ptr getItemFor( + std::shared_ptr craftSlots, Level* level); + std::vector* getRecipies(); + + // 4J-PB - Added all below for new Xbox 'crafting' + std::shared_ptr getItemForRecipe(Recipy* r); + Recipy::INGREDIENTS_REQUIRED* getRecipeIngredientsArray(); + +private: + void buildRecipeIngredientsArray(); + Recipy::INGREDIENTS_REQUIRED* m_pRecipeIngredientsRequired; + + static ToolRecipies* pToolRecipies; + static WeaponRecipies* pWeaponRecipies; + static StructureRecipies* pStructureRecipies; + static OreRecipies* pOreRecipies; + static FoodRecipies* pFoodRecipies; + static ClothDyeRecipes* pClothDyeRecipes; + static ArmorRecipes* pArmorRecipes; }; diff --git a/Minecraft.World/Recipes/Recipy.h b/Minecraft.World/Recipes/Recipy.h index fd5865052..15b169db6 100644 --- a/Minecraft.World/Recipes/Recipy.h +++ b/Minecraft.World/Recipes/Recipy.h @@ -1,5 +1,5 @@ // package net.minecraft.world.item.crafting; -// +// // import net.minecraft.world.inventory.CraftingContainer; // import net.minecraft.world.item.ItemInstance; @@ -7,49 +7,54 @@ #include "../Containers/CraftingContainer.h" -#define RECIPE_TYPE_2x2 0 +#define RECIPE_TYPE_2x2 0 #define RECIPE_TYPE_3x3 1 -class Recipy -{ +class Recipy { public: - enum _eGroupType - { - eGroupType_First=0, - eGroupType_Structure=0, - eGroupType_Tool, - eGroupType_Food, - eGroupType_Armour, - eGroupType_Mechanism, - eGroupType_Transport, - eGroupType_Decoration, - eGroupType_Max - } - eGroupType; // to class the item produced by the recipe + enum _eGroupType { + eGroupType_First = 0, + eGroupType_Structure = 0, + eGroupType_Tool, + eGroupType_Food, + eGroupType_Armour, + eGroupType_Mechanism, + eGroupType_Transport, + eGroupType_Decoration, + eGroupType_Max + } eGroupType; // to class the item produced by the recipe - // 4J-PB - we'll classing an ingredient ID with a different aux value as a different IngID AuxVal pair - typedef struct - { - int iIngC; - int iType; // Can be a 2x2 or a 3x3. Inventory crafting can only make a 2x2. - int *iIngIDA; - int *iIngValA; - int *iIngAuxValA; - Recipy *pRecipy; - bool bCanMake[XUSER_MAX_COUNT]; - unsigned int *uiGridA; // hold the layout of the recipe (id | auxval<<24) - unsigned short usBitmaskMissingGridIngredients[XUSER_MAX_COUNT]; // each bit set means we don't have that grid ingredient - } - INGREDIENTS_REQUIRED; - ~Recipy() {} - virtual bool matches(std::shared_ptr craftSlots, Level *level) = 0; - virtual std::shared_ptr assemble(std::shared_ptr craftSlots) = 0; - virtual int size() = 0; - virtual const ItemInstance *getResultItem() = 0; - virtual const int getGroup() = 0; + // 4J-PB - we'll classing an ingredient ID with a different aux value as a + // different IngID AuxVal pair + typedef struct { + int iIngC; + int iType; // Can be a 2x2 or a 3x3. Inventory crafting can only make a + // 2x2. + int* iIngIDA; + int* iIngValA; + int* iIngAuxValA; + Recipy* pRecipy; + bool bCanMake[XUSER_MAX_COUNT]; + unsigned int* + uiGridA; // hold the layout of the recipe (id | auxval<<24) + unsigned short usBitmaskMissingGridIngredients + [XUSER_MAX_COUNT]; // each bit set means we don't have that grid + // ingredient + } INGREDIENTS_REQUIRED; + ~Recipy() {} + virtual bool matches(std::shared_ptr craftSlots, + Level* level) = 0; + virtual std::shared_ptr assemble( + std::shared_ptr craftSlots) = 0; + virtual int size() = 0; + virtual const ItemInstance* getResultItem() = 0; + virtual const int getGroup() = 0; - // 4J-PB - virtual bool requires(int iRecipe) = 0; - virtual void requires(INGREDIENTS_REQUIRED *pIngReq) = 0; + // 4J-PB + virtual bool + requires(int iRecipe) + = 0; + virtual void + requires(INGREDIENTS_REQUIRED* pIngReq) + = 0; }; - diff --git a/Minecraft.World/Recipes/ShapedRecipy.cpp b/Minecraft.World/Recipes/ShapedRecipy.cpp index b33d10153..b2a87aeec 100644 --- a/Minecraft.World/Recipes/ShapedRecipy.cpp +++ b/Minecraft.World/Recipes/ShapedRecipy.cpp @@ -1,5 +1,5 @@ // package net.minecraft.world.item.crafting; -// +// // import net.minecraft.world.inventory.CraftingContainer; // import net.minecraft.world.item.ItemInstance; @@ -11,224 +11,197 @@ #include "Recipes.h" #include "ShapedRecipy.h" -// 4J-PB - for new crafting - Adding group to define type of item that the recipe produces -ShapedRecipy::ShapedRecipy(int width, int height, ItemInstance **recipeItems, ItemInstance *result, int iGroup) - : resultId(result->id) -{ - this->width = width; - this->height = height; - this->recipeItems = recipeItems; - this->result = result; - this->group = iGroup; - _keepTag = false; +// 4J-PB - for new crafting - Adding group to define type of item that the +// recipe produces +ShapedRecipy::ShapedRecipy(int width, int height, ItemInstance** recipeItems, + ItemInstance* result, int iGroup) + : resultId(result->id) { + this->width = width; + this->height = height; + this->recipeItems = recipeItems; + this->result = result; + this->group = iGroup; + _keepTag = false; } -const int ShapedRecipy::getGroup() -{ - return group; +const int ShapedRecipy::getGroup() { return group; } + +const ItemInstance* ShapedRecipy::getResultItem() { return result; } + +bool ShapedRecipy::matches(std::shared_ptr craftSlots, + Level* level) { + for (int xOffs = 0; xOffs <= (3 - width); xOffs++) { + for (int yOffs = 0; yOffs <= (3 - height); yOffs++) { + if (matches(craftSlots, xOffs, yOffs, true)) return true; + if (matches(craftSlots, xOffs, yOffs, false)) return true; + } + } + return false; } -const ItemInstance *ShapedRecipy::getResultItem() -{ - return result; +bool ShapedRecipy::matches(std::shared_ptr craftSlots, + int xOffs, int yOffs, bool xFlip) { + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + int xs = x - xOffs; + int ys = y - yOffs; + ItemInstance* expected = NULL; + if (xs >= 0 && ys >= 0 && xs < width && ys < height) { + if (xFlip) + expected = recipeItems[(width - xs - 1) + ys * width]; + else + expected = recipeItems[xs + ys * width]; + } + std::shared_ptr item = craftSlots->getItem(x, y); + if (item == NULL && expected == NULL) { + continue; + } + if ((item == NULL && expected != NULL) || + (item != NULL && expected == NULL)) { + return false; + } + if (expected->id != item->id) { + return false; + } + if (expected->getAuxValue() != Recipes::ANY_AUX_VALUE && + expected->getAuxValue() != item->getAuxValue()) { + return false; + } + } + } + return true; } -bool ShapedRecipy::matches(std::shared_ptr craftSlots, Level *level) -{ - for (int xOffs = 0; xOffs <= (3 - width); xOffs++) - { - for (int yOffs = 0; yOffs <= (3 - height); yOffs++) - { - if (matches(craftSlots, xOffs, yOffs, true)) return true; - if (matches(craftSlots, xOffs, yOffs, false)) return true; - } - } - return false; +std::shared_ptr ShapedRecipy::assemble( + std::shared_ptr craftSlots) { + std::shared_ptr result = getResultItem()->copy(); + + if (_keepTag && craftSlots != NULL) { + for (int i = 0; i < craftSlots->getContainerSize(); i++) { + std::shared_ptr item = craftSlots->getItem(i); + + if (item != NULL && item->hasTag()) { + result->setTag((CompoundTag*)item->tag->copy()); + } + } + } + + return result; } -bool ShapedRecipy::matches(std::shared_ptr craftSlots, int xOffs, int yOffs, bool xFlip) -{ - for (int x = 0; x < 3; x++) { - for (int y = 0; y < 3; y++) { - int xs = x - xOffs; - int ys = y - yOffs; - ItemInstance *expected = NULL; - if (xs >= 0 && ys >= 0 && xs < width && ys < height) - { - if (xFlip) expected = recipeItems[(width - xs - 1) + ys * width]; - else expected = recipeItems[xs + ys * width]; - } - std::shared_ptr item = craftSlots->getItem(x, y); - if (item == NULL && expected == NULL) - { - continue; - } - if ((item == NULL && expected != NULL) || (item != NULL && expected == NULL)) - { - return false; - } - if (expected->id != item->id) - { - return false; - } - if (expected->getAuxValue() != Recipes::ANY_AUX_VALUE && expected->getAuxValue() != item->getAuxValue()) - { - return false; - } - } - } - return true; -} - -std::shared_ptr ShapedRecipy::assemble(std::shared_ptr craftSlots) -{ - std::shared_ptr result = getResultItem()->copy(); - - if (_keepTag && craftSlots != NULL) - { - for (int i = 0; i < craftSlots->getContainerSize(); i++) - { - std::shared_ptr item = craftSlots->getItem(i); - - if (item != NULL && item->hasTag()) - { - result->setTag((CompoundTag *) item->tag->copy()); - } - } - } - - return result; -} - -int ShapedRecipy::size() -{ - return width * height; -} +int ShapedRecipy::size() { return width * height; } // 4J-PB -bool ShapedRecipy::requires(int iRecipe) -{ - app.DebugPrintf("ShapedRecipy %d\n",iRecipe); - int iCount=0; - for (int x = 0; x < 3; x++) - { - for (int y = 0; y < 3; y++) - { - if (x < width && y < height) - { - ItemInstance *expected = recipeItems[x+y*width]; - if (expected!=NULL) - { - //printf("\tIngredient %d is %d\n",iCount++,expected->id); - } - } - } - } +bool ShapedRecipy::requires(int iRecipe) { + app.DebugPrintf("ShapedRecipy %d\n", iRecipe); + int iCount = 0; + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + if (x < width && y < height) { + ItemInstance* expected = recipeItems[x + y * width]; + if (expected != NULL) { + // printf("\tIngredient %d is %d\n",iCount++,expected->id); + } + } + } + } - - - return false; + return false; } -void ShapedRecipy::requires(INGREDIENTS_REQUIRED *pIngReq) -{ - //printf("ShapedRecipy %d\n",iRecipe); +void ShapedRecipy::requires(INGREDIENTS_REQUIRED* pIngReq) { + // printf("ShapedRecipy %d\n",iRecipe); - int iCount=0; - bool bFound; - int j; - INGREDIENTS_REQUIRED TempIngReq; - TempIngReq.iIngC=0; - TempIngReq.iType = ((width>2) ||(height>2))?RECIPE_TYPE_3x3:RECIPE_TYPE_2x2; // 3x3 - // 3x3 - // 4jcraft, genuinly what is this garbage code - TempIngReq.uiGridA = new unsigned int [9]; - TempIngReq.iIngIDA= new int [9]; - TempIngReq.iIngValA = new int [9]; - TempIngReq.iIngAuxValA = new int [9]; + int iCount = 0; + bool bFound; + int j; + INGREDIENTS_REQUIRED TempIngReq; + TempIngReq.iIngC = 0; + TempIngReq.iType = ((width > 2) || (height > 2)) ? RECIPE_TYPE_3x3 + : RECIPE_TYPE_2x2; // 3x3 + // 3x3 + // 4jcraft, genuinly what is this garbage code + TempIngReq.uiGridA = new unsigned int[9]; + TempIngReq.iIngIDA = new int[9]; + TempIngReq.iIngValA = new int[9]; + TempIngReq.iIngAuxValA = new int[9]; - // 4jcraft,yes, yes!! - // use winapi and inbetween use a cstd function u could have used! - ZeroMemory(TempIngReq.iIngIDA,sizeof(int)*9); - ZeroMemory(TempIngReq.iIngValA,sizeof(int)*9); - memset(TempIngReq.iIngAuxValA,Recipes::ANY_AUX_VALUE,sizeof(int)*9); - ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); + // 4jcraft,yes, yes!! + // use winapi and inbetween use a cstd function u could have used! + ZeroMemory(TempIngReq.iIngIDA, sizeof(int) * 9); + ZeroMemory(TempIngReq.iIngValA, sizeof(int) * 9); + memset(TempIngReq.iIngAuxValA, Recipes::ANY_AUX_VALUE, sizeof(int) * 9); + ZeroMemory(TempIngReq.uiGridA, sizeof(unsigned int) * 9); - for (int x = 0; x < 3; x++) - { - for (int y = 0; y < 3; y++) - { - if (x < width && y < height) - { - ItemInstance *expected = recipeItems[x+y*width]; + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + if (x < width && y < height) { + ItemInstance* expected = recipeItems[x + y * width]; - if (expected!=NULL) - { - int iAuxVal = expected->getAuxValue(); - //4jcraft, added cast to uint (shift of negativ num, undefined) - TempIngReq.uiGridA[x+y*3]=expected->id | (unsigned int) iAuxVal<<24; + if (expected != NULL) { + int iAuxVal = expected->getAuxValue(); + // 4jcraft, added cast to uint (shift of negativ num, + // undefined) + TempIngReq.uiGridA[x + y * 3] = + expected->id | (unsigned int)iAuxVal << 24; - bFound=false; - for(j=0;jid) && (iAuxVal == Recipes::ANY_AUX_VALUE || TempIngReq.iIngAuxValA[j] == iAuxVal)) - { - bFound= true; - break; - } - } - if(bFound) - { - TempIngReq.iIngValA[j]++; - } - else - { - TempIngReq.iIngIDA[TempIngReq.iIngC]=expected->id; - TempIngReq.iIngAuxValA[TempIngReq.iIngC]=iAuxVal; - TempIngReq.iIngValA[TempIngReq.iIngC++]++; - } - //printf("\tIngredient %d is %d\n",iCount++,expected->id); - } + bFound = false; + for (j = 0; j < TempIngReq.iIngC; j++) { + if ((TempIngReq.iIngIDA[j] == expected->id) && + (iAuxVal == Recipes::ANY_AUX_VALUE || + TempIngReq.iIngAuxValA[j] == iAuxVal)) { + bFound = true; + break; + } + } + if (bFound) { + TempIngReq.iIngValA[j]++; + } else { + TempIngReq.iIngIDA[TempIngReq.iIngC] = expected->id; + TempIngReq.iIngAuxValA[TempIngReq.iIngC] = iAuxVal; + TempIngReq.iIngValA[TempIngReq.iIngC++]++; + } + // printf("\tIngredient %d is %d\n",iCount++,expected->id); + } + } + } + } + pIngReq->iIngIDA = new int[TempIngReq.iIngC]; + pIngReq->iIngValA = new int[TempIngReq.iIngC]; + pIngReq->iIngAuxValA = new int[TempIngReq.iIngC]; + pIngReq->uiGridA = new unsigned int[9]; - } - } - } - pIngReq->iIngIDA= new int [TempIngReq.iIngC]; - pIngReq->iIngValA= new int [TempIngReq.iIngC]; - pIngReq->iIngAuxValA = new int [TempIngReq.iIngC]; - pIngReq->uiGridA = new unsigned int [9]; + pIngReq->iIngC = TempIngReq.iIngC; + pIngReq->iType = TempIngReq.iType; - pIngReq->iIngC=TempIngReq.iIngC; - pIngReq->iType=TempIngReq.iType; + pIngReq->pRecipy = this; - pIngReq->pRecipy=this; + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + pIngReq->bCanMake[i] = false; + } - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - pIngReq->bCanMake[i]=false; - } + for (j = 0; j < 9; j++) { + pIngReq->uiGridA[j] = TempIngReq.uiGridA[j]; + } - for(j=0;j<9;j++) - { - pIngReq->uiGridA[j]=TempIngReq.uiGridA[j]; - } + if (pIngReq->iIngC != 0) { + memcpy(pIngReq->iIngIDA, TempIngReq.iIngIDA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngValA, TempIngReq.iIngValA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngAuxValA, TempIngReq.iIngAuxValA, + sizeof(int) * TempIngReq.iIngC); + } + memcpy(pIngReq->uiGridA, TempIngReq.uiGridA, sizeof(unsigned int) * 9); - if(pIngReq->iIngC!=0) - { - memcpy(pIngReq->iIngIDA,TempIngReq.iIngIDA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngValA,TempIngReq.iIngValA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngAuxValA,TempIngReq.iIngAuxValA,sizeof(int)*TempIngReq.iIngC); - } - memcpy(pIngReq->uiGridA,TempIngReq.uiGridA,sizeof(unsigned int)*9); - - delete [] TempIngReq.iIngIDA; - delete [] TempIngReq.iIngValA; - delete [] TempIngReq.iIngAuxValA; - delete [] TempIngReq.uiGridA; + delete[] TempIngReq.iIngIDA; + delete[] TempIngReq.iIngValA; + delete[] TempIngReq.iIngAuxValA; + delete[] TempIngReq.uiGridA; } -ShapedRecipy *ShapedRecipy::keepTag() -{ - _keepTag = true; - return this; +ShapedRecipy* +ShapedRecipy::keepTag() { + _keepTag = true; + return this; } diff --git a/Minecraft.World/Recipes/ShapedRecipy.h b/Minecraft.World/Recipes/ShapedRecipy.h index 55497379c..71a1351d2 100644 --- a/Minecraft.World/Recipes/ShapedRecipy.h +++ b/Minecraft.World/Recipes/ShapedRecipy.h @@ -1,32 +1,38 @@ #pragma once -class ShapedRecipy : public Recipy -{ +class ShapedRecipy : public Recipy { private: - int width, height, group; - ItemInstance **recipeItems; - ItemInstance *result; - bool _keepTag; -public: - const int resultId; + int width, height, group; + ItemInstance** recipeItems; + ItemInstance* result; + bool _keepTag; public: - ShapedRecipy(int width, int height, ItemInstance **recipeItems, ItemInstance *result, int iGroup=Recipy::eGroupType_Decoration); + const int resultId; - virtual const ItemInstance *getResultItem(); - virtual const int getGroup(); - virtual bool matches(std::shared_ptr craftSlots, Level *level); +public: + ShapedRecipy(int width, int height, ItemInstance** recipeItems, + ItemInstance* result, + int iGroup = Recipy::eGroupType_Decoration); + + virtual const ItemInstance* getResultItem(); + virtual const int getGroup(); + virtual bool matches(std::shared_ptr craftSlots, + Level* level); private: - bool matches(std::shared_ptr craftSlots, int xOffs, int yOffs, bool xFlip); + bool matches(std::shared_ptr craftSlots, int xOffs, + int yOffs, bool xFlip); public: - virtual std::shared_ptr assemble(std::shared_ptr craftSlots); - virtual int size(); - ShapedRecipy *keepTag(); + virtual std::shared_ptr assemble( + std::shared_ptr craftSlots); + virtual int size(); + ShapedRecipy* keepTag(); - // 4J-PB - to return the items required to make a recipe - virtual bool requires(int iRecipe); - virtual void requires(INGREDIENTS_REQUIRED *pIngReq); + // 4J-PB - to return the items required to make a recipe + virtual bool + requires(int iRecipe); + virtual void + requires(INGREDIENTS_REQUIRED* pIngReq); }; - diff --git a/Minecraft.World/Recipes/ShapelessRecipy.cpp b/Minecraft.World/Recipes/ShapelessRecipy.cpp index 4c3b567a4..0d8972346 100644 --- a/Minecraft.World/Recipes/ShapelessRecipy.cpp +++ b/Minecraft.World/Recipes/ShapelessRecipy.cpp @@ -1,7 +1,7 @@ // package net.minecraft.world.item.crafting; -// +// // import java.util.*; -// +// // import net.minecraft.world.inventory.CraftingContainer; // import net.minecraft.world.item.ItemInstance; #include "../Platform/stdafx.h" @@ -12,172 +12,160 @@ #include "Recipes.h" #include "ShapelessRecipy.h" -ShapelessRecipy::ShapelessRecipy(ItemInstance *result, std::vector *ingredients, _eGroupType egroup) : - result(result), - ingredients(ingredients), - group(egroup) -{ +ShapelessRecipy::ShapelessRecipy(ItemInstance* result, + std::vector* ingredients, + _eGroupType egroup) + : result(result), ingredients(ingredients), group(egroup) {} + +const int ShapelessRecipy::getGroup() { return group; } + +const ItemInstance* ShapelessRecipy::getResultItem() { return result; } + +bool ShapelessRecipy::matches(std::shared_ptr craftSlots, + Level* level) { + std::vector tempList = *ingredients; + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + std::shared_ptr item = craftSlots->getItem(x, y); + + if (item != NULL) { + bool found = false; + + AUTO_VAR(citEnd, ingredients->end()); + for (AUTO_VAR(cit, ingredients->begin()); cit != citEnd; + ++cit) { + ItemInstance* ingredient = *cit; + if (item->id == ingredient->id && + (ingredient->getAuxValue() == Recipes::ANY_AUX_VALUE || + item->getAuxValue() == ingredient->getAuxValue())) { + found = true; + AUTO_VAR(it, find(tempList.begin(), tempList.end(), + ingredient)); + if (it != tempList.end()) tempList.erase(it); + break; + } + } + + if (!found) { + return false; + } + } + } + } + + return tempList.empty(); } -const int ShapelessRecipy::getGroup() -{ - return group; +std::shared_ptr ShapelessRecipy::assemble( + std::shared_ptr craftSlots) { + return result->copy(); } -const ItemInstance *ShapelessRecipy::getResultItem() -{ - return result; -} - -bool ShapelessRecipy::matches(std::shared_ptr craftSlots, Level *level) -{ - std::vector tempList = *ingredients; - - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 3; x++) - { - std::shared_ptr item = craftSlots->getItem(x, y); - - if (item != NULL) - { - bool found = false; - - AUTO_VAR(citEnd, ingredients->end()); - for (AUTO_VAR(cit, ingredients->begin()); cit != citEnd; ++cit) - { - ItemInstance *ingredient = *cit; - if (item->id == ingredient->id && (ingredient->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == ingredient->getAuxValue())) - { - found = true; - AUTO_VAR( it, find(tempList.begin(), tempList.end(), ingredient ) ); - if(it != tempList.end() ) tempList.erase(it); - break; - } - } - - if (!found) - { - return false; - } - } - } - } - - return tempList.empty(); -} - -std::shared_ptr ShapelessRecipy::assemble(std::shared_ptr craftSlots) -{ - return result->copy(); -} - -int ShapelessRecipy::size() -{ - return (int)ingredients->size(); -} +int ShapelessRecipy::size() { return (int)ingredients->size(); } // 4J-PB -bool ShapelessRecipy::requires(int iRecipe) -{ - std::vector *tempList = new std::vector; +bool ShapelessRecipy::requires(int iRecipe) { + std::vector* tempList = new std::vector; - *tempList=*ingredients; + *tempList = *ingredients; - //printf("ShapelessRecipy %d\n",iRecipe); + // printf("ShapelessRecipy %d\n",iRecipe); - AUTO_VAR(citEnd, ingredients->end()); - int iCount=0; - for (std::vector::iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) - { - //printf("\tIngredient %d is %d\n",iCount++,(*ingredient)->id); - //if (item->id == (*ingredient)->id && ((*ingredient)->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == (*ingredient)->getAuxValue())) - tempList->erase(ingredient); - } + AUTO_VAR(citEnd, ingredients->end()); + int iCount = 0; + for (std::vector::iterator ingredient = ingredients->begin(); + ingredient != citEnd; ingredient++) { + // printf("\tIngredient %d is %d\n",iCount++,(*ingredient)->id); + // if (item->id == (*ingredient)->id && ((*ingredient)->getAuxValue() == + // Recipes::ANY_AUX_VALUE || item->getAuxValue() == + // (*ingredient)->getAuxValue())) + tempList->erase(ingredient); + } - delete tempList; - return false; + delete tempList; + return false; } -void ShapelessRecipy::requires(INGREDIENTS_REQUIRED *pIngReq) -{ - int iCount=0; - bool bFound; - int j; - INGREDIENTS_REQUIRED TempIngReq; +void ShapelessRecipy::requires(INGREDIENTS_REQUIRED* pIngReq) { + int iCount = 0; + bool bFound; + int j; + INGREDIENTS_REQUIRED TempIngReq; - // shapeless doesn't have the 3x3 shape, but we'll just use this to store the ingredients anyway - TempIngReq.iIngC=0; - TempIngReq.iType = RECIPE_TYPE_2x2; // all the dyes can be made in a 2x2 - TempIngReq.uiGridA = new unsigned int [9]; - TempIngReq.iIngIDA= new int [3*3]; - TempIngReq.iIngValA = new int [3*3]; - TempIngReq.iIngAuxValA = new int [3*3]; + // shapeless doesn't have the 3x3 shape, but we'll just use this to store + // the ingredients anyway + TempIngReq.iIngC = 0; + TempIngReq.iType = RECIPE_TYPE_2x2; // all the dyes can be made in a 2x2 + TempIngReq.uiGridA = new unsigned int[9]; + TempIngReq.iIngIDA = new int[3 * 3]; + TempIngReq.iIngValA = new int[3 * 3]; + TempIngReq.iIngAuxValA = new int[3 * 3]; - ZeroMemory(TempIngReq.iIngIDA,sizeof(int)*9); - ZeroMemory(TempIngReq.iIngValA,sizeof(int)*9); - memset(TempIngReq.iIngAuxValA,Recipes::ANY_AUX_VALUE,sizeof(int)*9); - ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); + ZeroMemory(TempIngReq.iIngIDA, sizeof(int) * 9); + ZeroMemory(TempIngReq.iIngValA, sizeof(int) * 9); + memset(TempIngReq.iIngAuxValA, Recipes::ANY_AUX_VALUE, sizeof(int) * 9); + ZeroMemory(TempIngReq.uiGridA, sizeof(unsigned int) * 9); - AUTO_VAR(citEnd, ingredients->end()); + AUTO_VAR(citEnd, ingredients->end()); - for (std::vector::const_iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) - { - ItemInstance *expected = *ingredient; + for (std::vector::const_iterator ingredient = + ingredients->begin(); + ingredient != citEnd; ingredient++) { + ItemInstance* expected = *ingredient; - if (expected!=NULL) - { - int iAuxVal = (*ingredient)->getAuxValue(); - //4jcraft, added cast to uint, shift of negative int is undefined - TempIngReq.uiGridA[iCount++]=expected->id | (unsigned int) iAuxVal<<24; - // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them in a 2x2 crafting screen - if(iCount==2) iCount=3; - bFound=false; - for(j=0;jid) && (iAuxVal == Recipes::ANY_AUX_VALUE || TempIngReq.iIngAuxValA[j] == iAuxVal)) - { - bFound= true; - break; - } - } - if(bFound) - { - TempIngReq.iIngValA[j]++; - } - else - { - TempIngReq.iIngIDA[TempIngReq.iIngC]=expected->id; - TempIngReq.iIngAuxValA[TempIngReq.iIngC]=iAuxVal; - TempIngReq.iIngValA[TempIngReq.iIngC++]++; - } - } - } - pIngReq->iIngIDA = new int [TempIngReq.iIngC]; - pIngReq->iIngValA = new int [TempIngReq.iIngC]; - pIngReq->iIngAuxValA = new int [TempIngReq.iIngC]; - pIngReq->uiGridA = new unsigned int [9]; + if (expected != NULL) { + int iAuxVal = (*ingredient)->getAuxValue(); + // 4jcraft, added cast to uint, shift of negative int is undefined + TempIngReq.uiGridA[iCount++] = expected->id | (unsigned int)iAuxVal + << 24; + // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them + // in a 2x2 crafting screen + if (iCount == 2) iCount = 3; + bFound = false; + for (j = 0; j < TempIngReq.iIngC; j++) { + if ((TempIngReq.iIngIDA[j] == expected->id) && + (iAuxVal == Recipes::ANY_AUX_VALUE || + TempIngReq.iIngAuxValA[j] == iAuxVal)) { + bFound = true; + break; + } + } + if (bFound) { + TempIngReq.iIngValA[j]++; + } else { + TempIngReq.iIngIDA[TempIngReq.iIngC] = expected->id; + TempIngReq.iIngAuxValA[TempIngReq.iIngC] = iAuxVal; + TempIngReq.iIngValA[TempIngReq.iIngC++]++; + } + } + } + pIngReq->iIngIDA = new int[TempIngReq.iIngC]; + pIngReq->iIngValA = new int[TempIngReq.iIngC]; + pIngReq->iIngAuxValA = new int[TempIngReq.iIngC]; + pIngReq->uiGridA = new unsigned int[9]; - pIngReq->pRecipy=this; + pIngReq->pRecipy = this; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - pIngReq->bCanMake[i]=false; - } + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + pIngReq->bCanMake[i] = false; + } - pIngReq->iIngC=TempIngReq.iIngC; - pIngReq->iType=TempIngReq.iType; + pIngReq->iIngC = TempIngReq.iIngC; + pIngReq->iType = TempIngReq.iType; - if(pIngReq->iIngC!=0) - { - memcpy(pIngReq->iIngIDA,TempIngReq.iIngIDA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngValA,TempIngReq.iIngValA,sizeof(int)*TempIngReq.iIngC); - memcpy(pIngReq->iIngAuxValA,TempIngReq.iIngAuxValA,sizeof(int)*TempIngReq.iIngC); - } - memcpy(pIngReq->uiGridA,TempIngReq.uiGridA,sizeof(unsigned int) *9); + if (pIngReq->iIngC != 0) { + memcpy(pIngReq->iIngIDA, TempIngReq.iIngIDA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngValA, TempIngReq.iIngValA, + sizeof(int) * TempIngReq.iIngC); + memcpy(pIngReq->iIngAuxValA, TempIngReq.iIngAuxValA, + sizeof(int) * TempIngReq.iIngC); + } + memcpy(pIngReq->uiGridA, TempIngReq.uiGridA, sizeof(unsigned int) * 9); - delete [] TempIngReq.iIngIDA; - delete [] TempIngReq.iIngValA; - delete [] TempIngReq.iIngAuxValA; - delete [] TempIngReq.uiGridA; + delete[] TempIngReq.iIngIDA; + delete[] TempIngReq.iIngValA; + delete[] TempIngReq.iIngAuxValA; + delete[] TempIngReq.uiGridA; } diff --git a/Minecraft.World/Recipes/ShapelessRecipy.h b/Minecraft.World/Recipes/ShapelessRecipy.h index 054ae8856..910c63ad2 100644 --- a/Minecraft.World/Recipes/ShapelessRecipy.h +++ b/Minecraft.World/Recipes/ShapelessRecipy.h @@ -1,23 +1,27 @@ #pragma once -class ShapelessRecipy : public Recipy -{ +class ShapelessRecipy : public Recipy { private: - _eGroupType group; - const ItemInstance *result; - std::vector *ingredients; + _eGroupType group; + const ItemInstance* result; + std::vector* ingredients; public: - ShapelessRecipy(ItemInstance *result, std::vector *ingredients, _eGroupType egroup=Recipy::eGroupType_Decoration); + ShapelessRecipy(ItemInstance* result, + std::vector* ingredients, + _eGroupType egroup = Recipy::eGroupType_Decoration); - virtual const ItemInstance *getResultItem(); - virtual const int getGroup(); - virtual bool matches(std::shared_ptr craftSlots, Level *level); - virtual std::shared_ptr assemble(std::shared_ptr craftSlots); - virtual int size(); - - // 4J-PB - to return the items required to make a recipe - virtual bool requires(int iRecipe); - virtual void requires(INGREDIENTS_REQUIRED *pIngReq); + virtual const ItemInstance* getResultItem(); + virtual const int getGroup(); + virtual bool matches(std::shared_ptr craftSlots, + Level* level); + virtual std::shared_ptr assemble( + std::shared_ptr craftSlots); + virtual int size(); + // 4J-PB - to return the items required to make a recipe + virtual bool + requires(int iRecipe); + virtual void + requires(INGREDIENTS_REQUIRED* pIngReq); }; diff --git a/Minecraft.World/Recipes/StructureRecipes.cpp b/Minecraft.World/Recipes/StructureRecipes.cpp index 452fd8824..7b7e53140 100644 --- a/Minecraft.World/Recipes/StructureRecipes.cpp +++ b/Minecraft.World/Recipes/StructureRecipes.cpp @@ -5,124 +5,124 @@ #include "Recipes.h" #include "StructureRecipes.h" -void StructureRecipies::addRecipes(Recipes *r) -{ - r->addShapedRecipy(new ItemInstance(Tile::sandStone), // - L"ssctg", - L"##", // - L"##", // +void StructureRecipies::addRecipes(Recipes* r) { + r->addShapedRecipy(new ItemInstance(Tile::sandStone), // + L"ssctg", + L"##", // + L"##", // - L'#', Tile::sand, - L'S'); + L'#', Tile::sand, L'S'); - r->addShapedRecipy(new ItemInstance(Tile::sandStone, 4, SandStoneTile::TYPE_SMOOTHSIDE), // - L"ssczg", - L"##", // - L"##", // + r->addShapedRecipy(new ItemInstance(Tile::sandStone, 4, + SandStoneTile::TYPE_SMOOTHSIDE), // + L"ssczg", + L"##", // + L"##", // - L'#', new ItemInstance(Tile::sandStone), - L'S'); + L'#', new ItemInstance(Tile::sandStone), L'S'); - r->addShapedRecipy(new ItemInstance(Tile::sandStone, 1, SandStoneTile::TYPE_HEIROGLYPHS), // - L"ssczg", - L"#", // - L"#", // + r->addShapedRecipy( + new ItemInstance(Tile::sandStone, 1, + SandStoneTile::TYPE_HEIROGLYPHS), // + L"ssczg", + L"#", // + L"#", // - L'#', new ItemInstance(Tile::stoneSlabHalf, 1, StoneSlabTile::SAND_SLAB), - L'S'); + L'#', + new ItemInstance(Tile::stoneSlabHalf, 1, StoneSlabTile::SAND_SLAB), + L'S'); - r->addShapedRecipy(new ItemInstance(Tile::quartzBlock, 1, QuartzBlockTile::TYPE_CHISELED), // - L"ssczg", - L"#", // - L"#", // + r->addShapedRecipy( + new ItemInstance(Tile::quartzBlock, 1, + QuartzBlockTile::TYPE_CHISELED), // + L"ssczg", + L"#", // + L"#", // - L'#', new ItemInstance(Tile::stoneSlabHalf, 1, StoneSlabTile::QUARTZ_SLAB), - L'S'); + L'#', + new ItemInstance(Tile::stoneSlabHalf, 1, StoneSlabTile::QUARTZ_SLAB), + L'S'); - r->addShapedRecipy(new ItemInstance(Tile::quartzBlock, 2, QuartzBlockTile::TYPE_LINES_Y), // - L"ssczg", - L"#", // - L"#", // + r->addShapedRecipy( + new ItemInstance(Tile::quartzBlock, 2, + QuartzBlockTile::TYPE_LINES_Y), // + L"ssczg", + L"#", // + L"#", // - L'#', new ItemInstance(Tile::quartzBlock, 1, QuartzBlockTile::TYPE_DEFAULT), - L'S'); + L'#', + new ItemInstance(Tile::quartzBlock, 1, QuartzBlockTile::TYPE_DEFAULT), + L'S'); - // 4J Stu - Changed the order, as the blocks that go with sandstone cause a 3-icon scroll - // that touches the text "Structures" in the title in 720 fullscreen. - r->addShapedRecipy(new ItemInstance(Tile::workBench), // - L"ssctg", - L"##", // - L"##", // + // 4J Stu - Changed the order, as the blocks that go with sandstone cause a + // 3-icon scroll that touches the text "Structures" in the title in 720 + // fullscreen. + r->addShapedRecipy(new ItemInstance(Tile::workBench), // + L"ssctg", + L"##", // + L"##", // - L'#', Tile::wood, - L'S'); - - r->addShapedRecipy(new ItemInstance(Tile::furnace), // - L"sssctg", - L"###", // - L"# #", // - L"###", // + L'#', Tile::wood, L'S'); - L'#', Tile::stoneBrick, - L'S'); + r->addShapedRecipy(new ItemInstance(Tile::furnace), // + L"sssctg", + L"###", // + L"# #", // + L"###", // - r->addShapedRecipy(new ItemInstance((Tile*)Tile::chest), // - L"sssctg", - L"###", // - L"# #", // - L"###", // + L'#', Tile::stoneBrick, L'S'); - L'#', Tile::wood, - L'S'); + r->addShapedRecipy(new ItemInstance((Tile*)Tile::chest), // + L"sssctg", + L"###", // + L"# #", // + L"###", // - r->addShapedRecipy(new ItemInstance(Tile::enderChest), // - L"sssctcig", - L"###", // - L"#E#", // - L"###", // + L'#', Tile::wood, L'S'); - L'#', Tile::obsidian, L'E', Item::eyeOfEnder, - L'S'); + r->addShapedRecipy(new ItemInstance(Tile::enderChest), // + L"sssctcig", + L"###", // + L"#E#", // + L"###", // - r->addShapedRecipy(new ItemInstance(Tile::stoneBrickSmooth, 4), // - L"ssctg", - L"##", // - L"##", // + L'#', Tile::obsidian, L'E', Item::eyeOfEnder, L'S'); - L'#', Tile::rock, - L'S'); + r->addShapedRecipy(new ItemInstance(Tile::stoneBrickSmooth, 4), // + L"ssctg", + L"##", // + L"##", // - // 4J Stu - Move this into "Recipes" to change the order things are displayed on the crafting menu - //r->addShapedRecipy(new ItemInstance(Tile::ironFence, 16), // - // L"sscig", - // L"###", // - // L"###", // + L'#', Tile::rock, L'S'); - // L'#', Item::ironIngot, - // L'S'); + // 4J Stu - Move this into "Recipes" to change the order things are + // displayed on the crafting menu + // r->addShapedRecipy(new ItemInstance(Tile::ironFence, 16), // + // L"sscig", + // L"###", // + // L"###", // - r->addShapedRecipy(new ItemInstance(Tile::thinGlass, 16), // - L"ssctg", - L"###", // - L"###", // + // L'#', Item::ironIngot, + // L'S'); - L'#', Tile::glass, - L'D'); + r->addShapedRecipy(new ItemInstance(Tile::thinGlass, 16), // + L"ssctg", + L"###", // + L"###", // - r->addShapedRecipy(new ItemInstance(Tile::netherBrick, 1), // - L"sscig", - L"NN", // - L"NN", // + L'#', Tile::glass, L'D'); - L'N', Item::netherbrick, - L'S'); + r->addShapedRecipy(new ItemInstance(Tile::netherBrick, 1), // + L"sscig", + L"NN", // + L"NN", // - r->addShapedRecipy(new ItemInstance(Tile::redstoneLight, 1), // - L"ssscictg", - L" R ", // - L"RGR", // - L" R ", // - L'R', Item::redStone, 'G', Tile::lightGem, - L'M'); + L'N', Item::netherbrick, L'S'); + r->addShapedRecipy(new ItemInstance(Tile::redstoneLight, 1), // + L"ssscictg", + L" R ", // + L"RGR", // + L" R ", // + L'R', Item::redStone, 'G', Tile::lightGem, L'M'); } \ No newline at end of file diff --git a/Minecraft.World/Recipes/StructureRecipes.h b/Minecraft.World/Recipes/StructureRecipes.h index b972a757d..106428f3f 100644 --- a/Minecraft.World/Recipes/StructureRecipes.h +++ b/Minecraft.World/Recipes/StructureRecipes.h @@ -1,7 +1,6 @@ #pragma once -class StructureRecipies -{ +class StructureRecipies { public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; diff --git a/Minecraft.World/Recipes/ToolRecipes.cpp b/Minecraft.World/Recipes/ToolRecipes.cpp index 46e238098..90a494b67 100644 --- a/Minecraft.World/Recipes/ToolRecipes.cpp +++ b/Minecraft.World/Recipes/ToolRecipes.cpp @@ -1,7 +1,7 @@ -//package net.minecraft.world.item.crafting; +// package net.minecraft.world.item.crafting; -//import net.minecraft.world.item.*; -//import net.minecraft.world.level.tile.Tile; +// import net.minecraft.world.item.*; +// import net.minecraft.world.level.tile.Tile; #include "../Platform/stdafx.h" #include "../Headers/net.minecraft.world.item.h" #include "../Blocks/Tile.h" @@ -10,119 +10,105 @@ #include "ToolRecipes.h" // 4J-PB - adding "" on the end of these so we can detect it -std::wstring ToolRecipies::shapes[][4] = -{ - {L"XXX", // - L" # ",// - L" # "},// +std::wstring ToolRecipies::shapes[][4] = { + {L"XXX", // + L" # ", // + L" # "}, // - {L"X",// - L"#",// - L"#"},// + {L"X", // + L"#", // + L"#"}, // - {L"XX",// - L"X#",// - L" #"},// + {L"XX", // + L"X#", // + L" #"}, // - {L"XX",// - L" #",// - L" #"},// + {L"XX", // + L" #", // + L" #"}, // }; /* - Object[][] map = { - {Tile.wood, Tile.stoneBrick, Item.ironIngot, Item.diamond, Item.goldIngot}, - {Item.pickAxe_wood, Item.pickAxe_stone, Item.pickAxe_iron, Item.pickAxe_diamond, Item.pickAxe_gold}, - {Item.shovel_wood, Item.shovel_stone, Item.shovel_iron, Item.shovel_diamond, Item.shovel_gold}, - {Item.hatchet_wood, Item.hatchet_stone, Item.hatchet_iron, Item.hatchet_diamond, Item.hatchet_gold}, - {Item.hoe_wood, Item.hoe_stone, Item.hoe_iron, Item.hoe_diamond, Item.hoe_gold}, - }; - */ -//#define ADD_OBJECT(a,b) a.push_back(new Object(b)) + Object[][] map = { + {Tile.wood, Tile.stoneBrick, Item.ironIngot, + Item.diamond, Item.goldIngot}, {Item.pickAxe_wood, Item.pickAxe_stone, + Item.pickAxe_iron, Item.pickAxe_diamond, Item.pickAxe_gold}, + {Item.shovel_wood, Item.shovel_stone, Item.shovel_iron, + Item.shovel_diamond, Item.shovel_gold}, {Item.hatchet_wood, + Item.hatchet_stone, Item.hatchet_iron, Item.hatchet_diamond, + Item.hatchet_gold}, {Item.hoe_wood, Item.hoe_stone, Item.hoe_iron, + Item.hoe_diamond, Item.hoe_gold}, + }; + */ +// #define ADD_OBJECT(a,b) a.push_back(new Object(b)) -void ToolRecipies::_init() -{ - map = new std::vector [MAX_TOOL_RECIPES]; +void ToolRecipies::_init() { + map = new std::vector[MAX_TOOL_RECIPES]; - ADD_OBJECT(map[0],Tile::wood); - ADD_OBJECT(map[0],Tile::stoneBrick); - ADD_OBJECT(map[0],Item::ironIngot); - ADD_OBJECT(map[0],Item::diamond); - ADD_OBJECT(map[0],Item::goldIngot); + ADD_OBJECT(map[0], Tile::wood); + ADD_OBJECT(map[0], Tile::stoneBrick); + ADD_OBJECT(map[0], Item::ironIngot); + ADD_OBJECT(map[0], Item::diamond); + ADD_OBJECT(map[0], Item::goldIngot); - ADD_OBJECT(map[1],Item::pickAxe_wood); - ADD_OBJECT(map[1],Item::pickAxe_stone); - ADD_OBJECT(map[1],Item::pickAxe_iron); - ADD_OBJECT(map[1],Item::pickAxe_diamond); - ADD_OBJECT(map[1],Item::pickAxe_gold); + ADD_OBJECT(map[1], Item::pickAxe_wood); + ADD_OBJECT(map[1], Item::pickAxe_stone); + ADD_OBJECT(map[1], Item::pickAxe_iron); + ADD_OBJECT(map[1], Item::pickAxe_diamond); + ADD_OBJECT(map[1], Item::pickAxe_gold); - ADD_OBJECT(map[2],Item::shovel_wood); - ADD_OBJECT(map[2],Item::shovel_stone); - ADD_OBJECT(map[2],Item::shovel_iron); - ADD_OBJECT(map[2],Item::shovel_diamond); - ADD_OBJECT(map[2],Item::shovel_gold); + ADD_OBJECT(map[2], Item::shovel_wood); + ADD_OBJECT(map[2], Item::shovel_stone); + ADD_OBJECT(map[2], Item::shovel_iron); + ADD_OBJECT(map[2], Item::shovel_diamond); + ADD_OBJECT(map[2], Item::shovel_gold); - ADD_OBJECT(map[3],Item::hatchet_wood); - ADD_OBJECT(map[3],Item::hatchet_stone); - ADD_OBJECT(map[3],Item::hatchet_iron); - ADD_OBJECT(map[3],Item::hatchet_diamond); - ADD_OBJECT(map[3],Item::hatchet_gold); + ADD_OBJECT(map[3], Item::hatchet_wood); + ADD_OBJECT(map[3], Item::hatchet_stone); + ADD_OBJECT(map[3], Item::hatchet_iron); + ADD_OBJECT(map[3], Item::hatchet_diamond); + ADD_OBJECT(map[3], Item::hatchet_gold); - ADD_OBJECT(map[4],Item::hoe_wood); - ADD_OBJECT(map[4],Item::hoe_stone); - ADD_OBJECT(map[4],Item::hoe_iron); - ADD_OBJECT(map[4],Item::hoe_diamond); - ADD_OBJECT(map[4],Item::hoe_gold); + ADD_OBJECT(map[4], Item::hoe_wood); + ADD_OBJECT(map[4], Item::hoe_stone); + ADD_OBJECT(map[4], Item::hoe_iron); + ADD_OBJECT(map[4], Item::hoe_diamond); + ADD_OBJECT(map[4], Item::hoe_gold); } -void ToolRecipies::addRecipes(Recipes *r) -{ - wchar_t wchTypes[7]; - wchTypes[6]=0; +void ToolRecipies::addRecipes(Recipes* r) { + wchar_t wchTypes[7]; + wchTypes[6] = 0; - for (unsigned int m = 0; m < map[0].size(); m++) - { - Object *pObjMaterial = map[0].at(m); + for (unsigned int m = 0; m < map[0].size(); m++) { + Object* pObjMaterial = map[0].at(m); - for (int t=0; titem; + for (int t = 0; t < MAX_TOOL_RECIPES - 1; t++) { + Item* target = map[t + 1].at(m)->item; - wchTypes[0]=L'w'; - wchTypes[1]=L'c'; - wchTypes[2]=L'i'; - wchTypes[3]=L'c'; - wchTypes[5]=L'g'; - if(pObjMaterial->GetType()==eType_TILE) - { - wchTypes[4]=L't'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + wchTypes[0] = L'w'; + wchTypes[1] = L'c'; + wchTypes[2] = L'i'; + wchTypes[3] = L'c'; + wchTypes[5] = L'g'; + if (pObjMaterial->GetType() == eType_TILE) { + wchTypes[4] = L't'; + r->addShapedRecipy( + new ItemInstance(target), wchTypes, shapes[t], - L'#', Item::stick, - L'X', pObjMaterial->tile, - L'T'); - } - else - { - // must be Item - wchTypes[4]=L'i'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + L'#', Item::stick, L'X', pObjMaterial->tile, L'T'); + } else { + // must be Item + wchTypes[4] = L'i'; + r->addShapedRecipy( + new ItemInstance(target), wchTypes, shapes[t], - L'#', Item::stick, - L'X', pObjMaterial->item, - L'T'); - } - } - } - r->addShapedRecipy(new ItemInstance((Item *)Item::shears), - L"sscig", - L" #", // - L"# ", // - L'#', Item::ironIngot, - L'T' - ); + L'#', Item::stick, L'X', pObjMaterial->item, L'T'); + } + } + } + r->addShapedRecipy(new ItemInstance((Item*)Item::shears), L"sscig", + L" #", // + L"# ", // + L'#', Item::ironIngot, L'T'); } \ No newline at end of file diff --git a/Minecraft.World/Recipes/ToolRecipes.h b/Minecraft.World/Recipes/ToolRecipes.h index f04130901..a29a429e4 100644 --- a/Minecraft.World/Recipes/ToolRecipes.h +++ b/Minecraft.World/Recipes/ToolRecipes.h @@ -1,24 +1,23 @@ -//package net.minecraft.world.item.crafting; +// package net.minecraft.world.item.crafting; -//import net.minecraft.world.item.*; -//import net.minecraft.world.level.tile.Tile; +// import net.minecraft.world.item.*; +// import net.minecraft.world.level.tile.Tile; #pragma once #define MAX_TOOL_RECIPES 5 class Recipes; -class ToolRecipies -{ +class ToolRecipies { public: - // 4J - added for common ctor code - void _init(); - ToolRecipies() {_init();} + // 4J - added for common ctor code + void _init(); + ToolRecipies() { _init(); } private: - static std::wstring shapes[][4]; - std::vector *map; + static std::wstring shapes[][4]; + std::vector* map; public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; diff --git a/Minecraft.World/Recipes/WeaponRecipes.cpp b/Minecraft.World/Recipes/WeaponRecipes.cpp index 6290c4d7f..2cda4f0b5 100644 --- a/Minecraft.World/Recipes/WeaponRecipes.cpp +++ b/Minecraft.World/Recipes/WeaponRecipes.cpp @@ -7,101 +7,88 @@ #include "WeaponRecipes.h" // 4J-PB - adding "" on the end of these so we can detect it -std::wstring WeaponRecipies::shapes[][4] = -{ - {L"X", // - L"X",// - L"#",L""},// +std::wstring WeaponRecipies::shapes[][4] = { + {L"X", // + L"X", // + L"#", L""}, // }; - + /* - private Object[][] map = { - {Tile.wood, Tile.stoneBrick, Item.ironIngot, Item.diamond, Item.goldIngot}, - {Item.sword_wood, Item.sword_stone, Item.sword_iron, Item.sword_diamond, Item.sword_gold}, - }; + private Object[][] map = { + {Tile.wood, Tile.stoneBrick, Item.ironIngot, + Item.diamond, Item.goldIngot}, {Item.sword_wood, Item.sword_stone, + Item.sword_iron, Item.sword_diamond, Item.sword_gold}, + }; */ -void WeaponRecipies::_init() -{ - map = new std::vector [MAX_WEAPON_RECIPES]; +void WeaponRecipies::_init() { + map = new std::vector[MAX_WEAPON_RECIPES]; - ADD_OBJECT(map[0],Tile::wood); - ADD_OBJECT(map[0],Tile::stoneBrick); - ADD_OBJECT(map[0],Item::ironIngot); - ADD_OBJECT(map[0],Item::diamond); - ADD_OBJECT(map[0],Item::goldIngot); + ADD_OBJECT(map[0], Tile::wood); + ADD_OBJECT(map[0], Tile::stoneBrick); + ADD_OBJECT(map[0], Item::ironIngot); + ADD_OBJECT(map[0], Item::diamond); + ADD_OBJECT(map[0], Item::goldIngot); - ADD_OBJECT(map[1],Item::sword_wood); - ADD_OBJECT(map[1],Item::sword_stone); - ADD_OBJECT(map[1],Item::sword_iron); - ADD_OBJECT(map[1],Item::sword_diamond); - ADD_OBJECT(map[1],Item::sword_gold); + ADD_OBJECT(map[1], Item::sword_wood); + ADD_OBJECT(map[1], Item::sword_stone); + ADD_OBJECT(map[1], Item::sword_iron); + ADD_OBJECT(map[1], Item::sword_diamond); + ADD_OBJECT(map[1], Item::sword_gold); } -void WeaponRecipies::addRecipes(Recipes *r) -{ - wchar_t wchTypes[7]; - wchTypes[6]=0; +void WeaponRecipies::addRecipes(Recipes* r) { + wchar_t wchTypes[7]; + wchTypes[6] = 0; - for (unsigned int m = 0; m < map[0].size(); m++) - { - Object *pObjMaterial = map[0].at(m); + for (unsigned int m = 0; m < map[0].size(); m++) { + Object* pObjMaterial = map[0].at(m); - for (int t=0; titem; + for (int t = 0; t < MAX_WEAPON_RECIPES - 1; t++) { + Item* target = map[t + 1].at(m)->item; - wchTypes[0]=L'w'; - wchTypes[1]=L'c'; - wchTypes[2]=L'i'; - wchTypes[3]=L'c'; - wchTypes[5]=L'g'; - if(pObjMaterial->GetType()==eType_TILE) - { - wchTypes[4]=L't'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + wchTypes[0] = L'w'; + wchTypes[1] = L'c'; + wchTypes[2] = L'i'; + wchTypes[3] = L'c'; + wchTypes[5] = L'g'; + if (pObjMaterial->GetType() == eType_TILE) { + wchTypes[4] = L't'; + r->addShapedRecipy( + new ItemInstance(target), wchTypes, shapes[t], - L'#', Item::stick, - L'X', pObjMaterial->tile, - L'T'); - } - else - { - // must be Item - wchTypes[4]=L'i'; - r->addShapedRecipy(new ItemInstance(target), - wchTypes, - shapes[t], + L'#', Item::stick, L'X', pObjMaterial->tile, L'T'); + } else { + // must be Item + wchTypes[4] = L'i'; + r->addShapedRecipy( + new ItemInstance(target), wchTypes, shapes[t], - L'#', Item::stick, - L'X', pObjMaterial->item, - L'T'); - } - } - } + L'#', Item::stick, L'X', pObjMaterial->item, L'T'); + } + } + } - /* 4J-PB - moved out to main recipes so we can avoid them stacking on the group display name - r->addShapedRecipy(new ItemInstance(Item::bow, 1), // - L"ssscicig", - L" #X", // - L"# X", // - L" #X", // + /* 4J-PB - moved out to main recipes so we can avoid them stacking on the + group display name r->addShapedRecipy(new ItemInstance(Item::bow, 1), // + L"ssscicig", + L" #X", // + L"# X", // + L" #X", // - L'X', Item::string,// - L'#', Item::stick, - L'T'); + L'X', Item::string,// + L'#', Item::stick, + L'T'); - r->addShapedRecipy(new ItemInstance(Item::arrow, 4), // - L"ssscicicig", - L"X", // - L"#", // - L"Y", // + r->addShapedRecipy(new ItemInstance(Item::arrow, 4), // + L"ssscicicig", + L"X", // + L"#", // + L"Y", // - L'Y', Item::feather,// - L'X', Item::flint,// - L'#', Item::stick, - L'T'); - */ + L'Y', Item::feather,// + L'X', Item::flint,// + L'#', Item::stick, + L'T'); + */ } \ No newline at end of file diff --git a/Minecraft.World/Recipes/WeaponRecipes.h b/Minecraft.World/Recipes/WeaponRecipes.h index 9e4d7275e..126694e47 100644 --- a/Minecraft.World/Recipes/WeaponRecipes.h +++ b/Minecraft.World/Recipes/WeaponRecipes.h @@ -1,22 +1,21 @@ -//package net.minecraft.world.item.crafting; +// package net.minecraft.world.item.crafting; -//import net.minecraft.world.item.*; -//import net.minecraft.world.level.tile.Tile; +// import net.minecraft.world.item.*; +// import net.minecraft.world.level.tile.Tile; #pragma once #define MAX_WEAPON_RECIPES 2 -class WeaponRecipies -{ +class WeaponRecipies { public: - // 4J - added for common ctor code - void _init(); - WeaponRecipies() {_init();} + // 4J - added for common ctor code + void _init(); + WeaponRecipies() { _init(); } private: - static std::wstring shapes[][4]; - std::vector *map; - + static std::wstring shapes[][4]; + std::vector* map; + public: - void addRecipes(Recipes *r); + void addRecipes(Recipes* r); }; diff --git a/Minecraft.World/Stats/Achievement.cpp b/Minecraft.World/Stats/Achievement.cpp index 2163dbe12..c4508d69d 100644 --- a/Minecraft.World/Stats/Achievement.cpp +++ b/Minecraft.World/Stats/Achievement.cpp @@ -5,78 +5,84 @@ #include "../Util/DescFormatter.h" #include "Achievement.h" -void Achievement::_init() -{ - isGoldenVar = false; +void Achievement::_init() { + isGoldenVar = false; - if (x < Achievements::xMin) Achievements::xMin = x; - if (y < Achievements::yMin) Achievements::yMin = y; - if (x > Achievements::xMax) Achievements::xMax = x; - if (y > Achievements::yMax) Achievements::yMax = y; + if (x < Achievements::xMin) Achievements::xMin = x; + if (y < Achievements::yMin) Achievements::yMin = y; + if (x > Achievements::xMax) Achievements::xMax = x; + if (y > Achievements::yMax) Achievements::yMax = y; } -Achievement::Achievement(int id, const std::wstring& name, int x, int y, Item *icon, Achievement *requires) - : Stat( Achievements::ACHIEVEMENT_OFFSET + id, I18n::get(std::wstring(L"achievement.").append(name)) ), desc( I18n::get(std::wstring(L"achievement.").append(name).append(L".desc"))), icon( new ItemInstance(icon) ), x(x), y(y), requires(requires) -{ +Achievement::Achievement(int id, const std::wstring& name, int x, int y, + Item* icon, Achievement* requires) + : Stat(Achievements::ACHIEVEMENT_OFFSET + id, + I18n::get(std::wstring(L"achievement.").append(name))), + desc(I18n::get( + std::wstring(L"achievement.").append(name).append(L".desc"))), + icon(new ItemInstance(icon)), + x(x), + y(y), + requires(requires) {} + + Achievement::Achievement(int id, const std::wstring& name, int x, int y, + Tile* icon, Achievement* requires) + : Stat(Achievements::ACHIEVEMENT_OFFSET + id, + I18n::get(std::wstring(L"achievement.").append(name))), + desc(I18n::get( + std::wstring(L"achievement.").append(name).append(L".desc"))), + icon(new ItemInstance(icon)), + x(x), + y(y), + requires(requires) {} + + Achievement::Achievement(int id, const std::wstring& name, int x, int y, + std::shared_ptr icon, + Achievement* requires) + : Stat(Achievements::ACHIEVEMENT_OFFSET + id, + I18n::get(std::wstring(L"achievement.").append(name))), + desc(I18n::get( + std::wstring(L"achievement.").append(name).append(L".desc"))), + icon(icon), + x(x), + y(y), + requires(requires) {} + + Achievement + * Achievement::setAwardLocallyOnly() { + awardLocallyOnly = true; + return this; } -Achievement::Achievement(int id, const std::wstring& name, int x, int y, Tile *icon, Achievement *requires) - : Stat( Achievements::ACHIEVEMENT_OFFSET + id, I18n::get(std::wstring(L"achievement.").append(name)) ), desc( I18n::get(std::wstring(L"achievement.").append(name).append(L".desc"))), icon( new ItemInstance(icon) ), x(x), y(y), requires(requires) -{ +Achievement* Achievement::setGolden() { + isGoldenVar = true; + return this; } -Achievement::Achievement(int id, const std::wstring& name, int x, int y, std::shared_ptr icon, Achievement *requires) - : Stat( Achievements::ACHIEVEMENT_OFFSET + id, I18n::get(std::wstring(L"achievement.").append(name)) ), desc( I18n::get(std::wstring(L"achievement.").append(name).append(L".desc"))), icon(icon), x(x), y(y), requires(requires) -{ +Achievement* Achievement::postConstruct() { + Stat::postConstruct(); + + Achievements::achievements->push_back(this); + + return this; } -Achievement *Achievement::setAwardLocallyOnly() -{ - awardLocallyOnly = true; - return this; +bool Achievement::isAchievement() { return true; } + +std::wstring Achievement::getDescription() { + if (descFormatter != NULL) { + return descFormatter->format(desc); + } + return desc; } -Achievement *Achievement::setGolden() -{ - isGoldenVar = true; - return this; +Achievement* Achievement::setDescFormatter(DescFormatter* descFormatter) { + this->descFormatter = descFormatter; + return this; } -Achievement *Achievement::postConstruct() -{ - Stat::postConstruct(); +bool Achievement::isGolden() { return isGoldenVar; } - Achievements::achievements->push_back(this); - - return this; -} - -bool Achievement::isAchievement() -{ - return true; -} - -std::wstring Achievement::getDescription() -{ - if (descFormatter != NULL) - { - return descFormatter->format(desc); - } - return desc; -} - -Achievement *Achievement::setDescFormatter(DescFormatter *descFormatter) -{ - this->descFormatter = descFormatter; - return this; -} - -bool Achievement::isGolden() -{ - return isGoldenVar; -} - -int Achievement::getAchievementID() -{ - return id - Achievements::ACHIEVEMENT_OFFSET; +int Achievement::getAchievementID() { + return id - Achievements::ACHIEVEMENT_OFFSET; } diff --git a/Minecraft.World/Stats/Achievement.h b/Minecraft.World/Stats/Achievement.h index 5339b8431..444be24d4 100644 --- a/Minecraft.World/Stats/Achievement.h +++ b/Minecraft.World/Stats/Achievement.h @@ -1,38 +1,40 @@ #pragma once - #include "Stat.h" class DescFormatter; -class Achievement : public Stat -{ +class Achievement : public Stat { public: - const int x, y; - Achievement *requires; + const int x, y; + Achievement* + requires; -private: - const std::wstring desc; - DescFormatter *descFormatter; +private: + const std::wstring desc; + DescFormatter* descFormatter; public: - const std::shared_ptr icon; + const std::shared_ptr icon; private: bool isGoldenVar; - void _init(); + void _init(); public: - Achievement(int id, const std::wstring& name, int x, int y, Item *icon, Achievement *requires); - Achievement(int id, const std::wstring& name, int x, int y, Tile *icon, Achievement *requires); - Achievement(int id, const std::wstring& name, int x, int y, std::shared_ptr icon, Achievement *requires); + Achievement(int id, const std::wstring& name, int x, int y, Item* icon, + Achievement* requires); + Achievement(int id, const std::wstring& name, int x, int y, Tile* icon, + Achievement* requires); + Achievement(int id, const std::wstring& name, int x, int y, + std::shared_ptr icon, Achievement* requires); - Achievement *setAwardLocallyOnly(); - Achievement *setGolden(); - Achievement *postConstruct(); - bool isAchievement(); - std::wstring getDescription(); - Achievement *setDescFormatter(DescFormatter *descFormatter); - bool isGolden(); - int getAchievementID(); + Achievement* setAwardLocallyOnly(); + Achievement* setGolden(); + Achievement* postConstruct(); + bool isAchievement(); + std::wstring getDescription(); + Achievement* setDescFormatter(DescFormatter* descFormatter); + bool isGolden(); + int getAchievementID(); }; diff --git a/Minecraft.World/Stats/Achievements.cpp b/Minecraft.World/Stats/Achievements.cpp index bc09a0d50..46cdf6467 100644 --- a/Minecraft.World/Stats/Achievements.cpp +++ b/Minecraft.World/Stats/Achievements.cpp @@ -6,7 +6,6 @@ #include "Achievement.h" #include "Achievements.h" - const int Achievements::ACHIEVEMENT_OFFSET = 0x500000; // maximum position of achievements (min and max) @@ -16,170 +15,369 @@ int Achievements::yMin = std::numeric_limits::max(); int Achievements::xMax = 0; int Achievements::yMax = 0; -std::vector *Achievements::achievements = new std::vector; +std::vector* Achievements::achievements = + new std::vector; -Achievement *Achievements::openInventory = NULL; -Achievement *Achievements::mineWood = NULL; -Achievement *Achievements::buildWorkbench = NULL; -Achievement *Achievements::buildPickaxe = NULL; -Achievement *Achievements::buildFurnace = NULL; -Achievement *Achievements::acquireIron = NULL; -Achievement *Achievements::buildHoe = NULL; -Achievement *Achievements::makeBread = NULL; -Achievement *Achievements::bakeCake = NULL; -Achievement *Achievements::buildBetterPickaxe = NULL; -Achievement *Achievements::cookFish = NULL; -Achievement *Achievements::onARail = NULL; -Achievement *Achievements::buildSword = NULL; -Achievement *Achievements::killEnemy = NULL; -Achievement *Achievements::killCow = NULL; -Achievement *Achievements::flyPig = NULL; +Achievement* Achievements::openInventory = NULL; +Achievement* Achievements::mineWood = NULL; +Achievement* Achievements::buildWorkbench = NULL; +Achievement* Achievements::buildPickaxe = NULL; +Achievement* Achievements::buildFurnace = NULL; +Achievement* Achievements::acquireIron = NULL; +Achievement* Achievements::buildHoe = NULL; +Achievement* Achievements::makeBread = NULL; +Achievement* Achievements::bakeCake = NULL; +Achievement* Achievements::buildBetterPickaxe = NULL; +Achievement* Achievements::cookFish = NULL; +Achievement* Achievements::onARail = NULL; +Achievement* Achievements::buildSword = NULL; +Achievement* Achievements::killEnemy = NULL; +Achievement* Achievements::killCow = NULL; +Achievement* Achievements::flyPig = NULL; -Achievement *Achievements::snipeSkeleton = NULL; -Achievement *Achievements::diamonds = NULL; -//Achievement *Achievements::portal = NULL; -Achievement *Achievements::ghast = NULL; -Achievement *Achievements::blazeRod = NULL; -Achievement *Achievements::potion = NULL; -Achievement *Achievements::theEnd = NULL; -Achievement *Achievements::winGame = NULL; -Achievement *Achievements::enchantments = NULL; -//Achievement *Achievements::overkill = NULL; -//Achievement *Achievements::bookcase = NULL; +Achievement* Achievements::snipeSkeleton = NULL; +Achievement* Achievements::diamonds = NULL; +// Achievement *Achievements::portal = NULL; +Achievement* Achievements::ghast = NULL; +Achievement* Achievements::blazeRod = NULL; +Achievement* Achievements::potion = NULL; +Achievement* Achievements::theEnd = NULL; +Achievement* Achievements::winGame = NULL; +Achievement* Achievements::enchantments = NULL; +// Achievement *Achievements::overkill = NULL; +// Achievement *Achievements::bookcase = NULL; -// 4J : WESTY : Added new acheivements. -Achievement *Achievements::leaderOfThePack = NULL; -Achievement *Achievements::MOARTools = NULL; -Achievement *Achievements::dispenseWithThis = NULL; -Achievement *Achievements::InToTheNether = NULL; +// 4J : WESTY : Added new acheivements. +Achievement* Achievements::leaderOfThePack = NULL; +Achievement* Achievements::MOARTools = NULL; +Achievement* Achievements::dispenseWithThis = NULL; +Achievement* Achievements::InToTheNether = NULL; -// 4J : WESTY : Added other awards. -Achievement *Achievements::socialPost = NULL; -Achievement *Achievements::eatPorkChop = NULL; -Achievement *Achievements::play100Days = NULL; -Achievement *Achievements::arrowKillCreeper = NULL; -Achievement *Achievements::mine100Blocks = NULL; -Achievement *Achievements::kill10Creepers = NULL; +// 4J : WESTY : Added other awards. +Achievement* Achievements::socialPost = NULL; +Achievement* Achievements::eatPorkChop = NULL; +Achievement* Achievements::play100Days = NULL; +Achievement* Achievements::arrowKillCreeper = NULL; +Achievement* Achievements::mine100Blocks = NULL; +Achievement* Achievements::kill10Creepers = NULL; #ifdef _EXTENDED_ACHIEVEMENTS -Achievement *Achievements::overkill = NULL; // Restored old achivements. -Achievement *Achievements::bookcase = NULL; // Restored old achivements. +Achievement* Achievements::overkill = NULL; // Restored old achivements. +Achievement* Achievements::bookcase = NULL; // Restored old achivements. // 4J-JEV: New Achievements for Orbis. -Achievement *Achievements::adventuringTime = NULL; -Achievement *Achievements::repopulation = NULL; -//Achievement *Achievements::porkChop = NULL; -Achievement *Achievements::diamondsToYou = NULL; -//Achievement *Achievements::passingTheTime = NULL; -//Achievement *Achievements::archer = NULL; -Achievement *Achievements::theHaggler = NULL; -Achievement *Achievements::potPlanter = NULL; -Achievement *Achievements::itsASign = NULL; -Achievement *Achievements::ironBelly = NULL; -Achievement *Achievements::haveAShearfulDay = NULL; -Achievement *Achievements::rainbowCollection = NULL; -Achievement *Achievements::stayinFrosty = NULL; -Achievement *Achievements::chestfulOfCobblestone = NULL; -Achievement *Achievements::renewableEnergy = NULL; -Achievement *Achievements::musicToMyEars = NULL; -Achievement *Achievements::bodyGuard = NULL; -Achievement *Achievements::ironMan = NULL; -Achievement *Achievements::zombieDoctor = NULL; -Achievement *Achievements::lionTamer = NULL; +Achievement* Achievements::adventuringTime = NULL; +Achievement* Achievements::repopulation = NULL; +// Achievement *Achievements::porkChop = NULL; +Achievement* Achievements::diamondsToYou = NULL; +// Achievement *Achievements::passingTheTime = NULL; +// Achievement *Achievements::archer = NULL; +Achievement* Achievements::theHaggler = NULL; +Achievement* Achievements::potPlanter = NULL; +Achievement* Achievements::itsASign = NULL; +Achievement* Achievements::ironBelly = NULL; +Achievement* Achievements::haveAShearfulDay = NULL; +Achievement* Achievements::rainbowCollection = NULL; +Achievement* Achievements::stayinFrosty = NULL; +Achievement* Achievements::chestfulOfCobblestone = NULL; +Achievement* Achievements::renewableEnergy = NULL; +Achievement* Achievements::musicToMyEars = NULL; +Achievement* Achievements::bodyGuard = NULL; +Achievement* Achievements::ironMan = NULL; +Achievement* Achievements::zombieDoctor = NULL; +Achievement* Achievements::lionTamer = NULL; #endif -void Achievements::staticCtor() -{ - Achievements::openInventory = (new Achievement(eAward_TakingInventory, L"openInventory", 0, 0, Item::book, NULL))->setAwardLocallyOnly()->postConstruct(); - Achievements::mineWood = (new Achievement(eAward_GettingWood, L"mineWood", 2, 1, Tile::treeTrunk, (Achievement *) openInventory))->postConstruct(); - Achievements::buildWorkbench = (new Achievement(eAward_Benchmarking, L"buildWorkBench", 4, -1, Tile::workBench, (Achievement *) mineWood))->postConstruct(); - Achievements::buildPickaxe = (new Achievement(eAward_TimeToMine, L"buildPickaxe", 4, 2, Item::pickAxe_wood, (Achievement *) buildWorkbench))->postConstruct(); - Achievements::buildFurnace = (new Achievement(eAward_HotTopic, L"buildFurnace", 3, 4, Tile::furnace_lit, (Achievement *) buildPickaxe))->postConstruct(); - Achievements::acquireIron = (new Achievement(eAward_AquireHardware, L"acquireIron", 1, 4, Item::ironIngot, (Achievement *) buildFurnace))->postConstruct(); - Achievements::buildHoe = (new Achievement(eAward_TimeToFarm, L"buildHoe", 2, -3, Item::hoe_wood, (Achievement *) buildWorkbench))->postConstruct(); - Achievements::makeBread = (new Achievement(eAward_BakeBread, L"makeBread", -1, -3, Item::bread, (Achievement *) buildHoe))->postConstruct(); - Achievements::bakeCake = (new Achievement(eAward_TheLie, L"bakeCake", 0, -5, Item::cake, (Achievement *) buildHoe))->postConstruct(); - Achievements::buildBetterPickaxe = (new Achievement(eAward_GettingAnUpgrade, L"buildBetterPickaxe", 6, 2, Item::pickAxe_stone, (Achievement *) buildPickaxe))->postConstruct(); - Achievements::cookFish = (new Achievement(eAward_DeliciousFish, L"cookFish", 2, 6, Item::fish_cooked, (Achievement *) buildFurnace))->postConstruct(); - Achievements::onARail = (new Achievement(eAward_OnARail, L"onARail", 2, 3, Tile::rail, (Achievement *) acquireIron))->setGolden()->postConstruct(); - Achievements::buildSword = (new Achievement(eAward_TimeToStrike, L"buildSword", 6, -1, Item::sword_wood, (Achievement *) buildWorkbench))->postConstruct(); - Achievements::killEnemy = (new Achievement(eAward_MonsterHunter, L"killEnemy", 8, -1, Item::bone, (Achievement *) buildSword))->postConstruct(); - Achievements::killCow = (new Achievement(eAward_CowTipper, L"killCow", 7, -3, Item::leather, (Achievement *) buildSword))->postConstruct(); - Achievements::flyPig = (new Achievement(eAward_WhenPigsFly, L"flyPig", 8, -4, Item::saddle, (Achievement *) killCow))->setGolden()->postConstruct(); +void Achievements::staticCtor() { + Achievements::openInventory = + (new Achievement(eAward_TakingInventory, L"openInventory", 0, 0, + Item::book, NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::mineWood = + (new Achievement(eAward_GettingWood, L"mineWood", 2, 1, Tile::treeTrunk, + (Achievement*)openInventory)) + ->postConstruct(); + Achievements::buildWorkbench = + (new Achievement(eAward_Benchmarking, L"buildWorkBench", 4, -1, + Tile::workBench, (Achievement*)mineWood)) + ->postConstruct(); + Achievements::buildPickaxe = + (new Achievement(eAward_TimeToMine, L"buildPickaxe", 4, 2, + Item::pickAxe_wood, (Achievement*)buildWorkbench)) + ->postConstruct(); + Achievements::buildFurnace = + (new Achievement(eAward_HotTopic, L"buildFurnace", 3, 4, + Tile::furnace_lit, (Achievement*)buildPickaxe)) + ->postConstruct(); + Achievements::acquireIron = + (new Achievement(eAward_AquireHardware, L"acquireIron", 1, 4, + Item::ironIngot, (Achievement*)buildFurnace)) + ->postConstruct(); + Achievements::buildHoe = + (new Achievement(eAward_TimeToFarm, L"buildHoe", 2, -3, Item::hoe_wood, + (Achievement*)buildWorkbench)) + ->postConstruct(); + Achievements::makeBread = + (new Achievement(eAward_BakeBread, L"makeBread", -1, -3, Item::bread, + (Achievement*)buildHoe)) + ->postConstruct(); + Achievements::bakeCake = + (new Achievement(eAward_TheLie, L"bakeCake", 0, -5, Item::cake, + (Achievement*)buildHoe)) + ->postConstruct(); + Achievements::buildBetterPickaxe = + (new Achievement(eAward_GettingAnUpgrade, L"buildBetterPickaxe", 6, 2, + Item::pickAxe_stone, (Achievement*)buildPickaxe)) + ->postConstruct(); + Achievements::cookFish = + (new Achievement(eAward_DeliciousFish, L"cookFish", 2, 6, + Item::fish_cooked, (Achievement*)buildFurnace)) + ->postConstruct(); + Achievements::onARail = + (new Achievement(eAward_OnARail, L"onARail", 2, 3, Tile::rail, + (Achievement*)acquireIron)) + ->setGolden() + ->postConstruct(); + Achievements::buildSword = + (new Achievement(eAward_TimeToStrike, L"buildSword", 6, -1, + Item::sword_wood, (Achievement*)buildWorkbench)) + ->postConstruct(); + Achievements::killEnemy = + (new Achievement(eAward_MonsterHunter, L"killEnemy", 8, -1, Item::bone, + (Achievement*)buildSword)) + ->postConstruct(); + Achievements::killCow = + (new Achievement(eAward_CowTipper, L"killCow", 7, -3, Item::leather, + (Achievement*)buildSword)) + ->postConstruct(); + Achievements::flyPig = + (new Achievement(eAward_WhenPigsFly, L"flyPig", 8, -4, Item::saddle, + (Achievement*)killCow)) + ->setGolden() + ->postConstruct(); - // 4J Stu - The order of these achievemnts is very important, as they map directly to data stored in the profile data. New achievements should be added at the end. - - // 4J : WESTY : Added new achievements. Note, params "x", "y", "icon" and "requires" are ignored on xbox. - Achievements::leaderOfThePack = (new Achievement(eAward_LeaderOfThePack, L"leaderOfThePack", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); - Achievements::MOARTools = (new Achievement(eAward_MOARTools, L"MOARTools", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); - Achievements::dispenseWithThis = (new Achievement(eAward_DispenseWithThis, L"dispenseWithThis", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->postConstruct(); - Achievements::InToTheNether = (new Achievement(eAward_InToTheNether, L"InToTheNether", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->postConstruct(); + // 4J Stu - The order of these achievemnts is very important, as they map + // directly to data stored in the profile data. New achievements should be + // added at the end. - // 4J : WESTY : Added other awards. - Achievements::mine100Blocks = (new Achievement(eAward_mine100Blocks, L"mine100Blocks", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); - Achievements::kill10Creepers = (new Achievement(eAward_kill10Creepers, L"kill10Creepers", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); + // 4J : WESTY : Added new achievements. Note, params "x", "y", "icon" and + // "requires" are ignored on xbox. + Achievements::leaderOfThePack = + (new Achievement(eAward_LeaderOfThePack, L"leaderOfThePack", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::MOARTools = + (new Achievement(eAward_MOARTools, L"MOARTools", 0, 0, Tile::treeTrunk, + (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::dispenseWithThis = + (new Achievement(eAward_DispenseWithThis, L"dispenseWithThis", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->postConstruct(); + Achievements::InToTheNether = + (new Achievement(eAward_InToTheNether, L"InToTheNether", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->postConstruct(); + + // 4J : WESTY : Added other awards. + Achievements::mine100Blocks = + (new Achievement(eAward_mine100Blocks, L"mine100Blocks", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::kill10Creepers = + (new Achievement(eAward_kill10Creepers, L"kill10Creepers", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); #ifdef _EXTENDED_ACHIEVEMENTS - Achievements::eatPorkChop = (new Achievement(eAward_eatPorkChop, L"eatPorkChop", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); + Achievements::eatPorkChop = + (new Achievement(eAward_eatPorkChop, L"eatPorkChop", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); #else - Achievements::eatPorkChop = (new Achievement(eAward_eatPorkChop, L"eatPorkChop", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->postConstruct(); + Achievements::eatPorkChop = + (new Achievement(eAward_eatPorkChop, L"eatPorkChop", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->postConstruct(); #endif - Achievements::play100Days = (new Achievement(eAward_play100Days, L"play100Days", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->setAwardLocallyOnly()->postConstruct(); - Achievements::arrowKillCreeper = (new Achievement(eAward_arrowKillCreeper, L"arrowKillCreeper", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->postConstruct(); - Achievements::socialPost = (new Achievement(eAward_socialPost, L"socialPost", 0, 0, Tile::treeTrunk, (Achievement *) buildSword))->postConstruct(); + Achievements::play100Days = + (new Achievement(eAward_play100Days, L"play100Days", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::arrowKillCreeper = + (new Achievement(eAward_arrowKillCreeper, L"arrowKillCreeper", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->postConstruct(); + Achievements::socialPost = + (new Achievement(eAward_socialPost, L"socialPost", 0, 0, + Tile::treeTrunk, (Achievement*)buildSword)) + ->postConstruct(); #ifndef _XBOX -// WARNING: NO NEW ACHIEVMENTS CAN BE ADDED HERE -// These stats (achievements) are directly followed by new stats/achievements in the profile data, so cannot be changed without migrating the profile data + // WARNING: NO NEW ACHIEVMENTS CAN BE ADDED HERE + // These stats (achievements) are directly followed by new + // stats/achievements in the profile data, so cannot be changed without + // migrating the profile data - // 4J Stu - All new Java achievements removed to stop them using the profile data + // 4J Stu - All new Java achievements removed to stop them using the profile + // data - // 4J Stu - This achievment added in 1.8.2, but does not map to any Xbox achievements - Achievements::snipeSkeleton = (new Achievement(eAward_snipeSkeleton, L"snipeSkeleton", 7, 0, Item::bow, (Achievement *) killEnemy))->setGolden()->postConstruct(); + // 4J Stu - This achievment added in 1.8.2, but does not map to any Xbox + // achievements + Achievements::snipeSkeleton = + (new Achievement(eAward_snipeSkeleton, L"snipeSkeleton", 7, 0, + Item::bow, (Achievement*)killEnemy)) + ->setGolden() + ->postConstruct(); - // 4J Stu - These added in 1.0.1, but do not map to any Xbox achievements - Achievements::diamonds = (new Achievement(eAward_diamonds, L"diamonds", -1, 5, Item::diamond, (Achievement *) acquireIron) )->postConstruct(); - //Achievements::portal = (new Achievement(eAward_portal, L"portal", -1, 7, Tile::obsidian, (Achievement *)diamonds) )->postConstruct(); - Achievements::ghast = (new Achievement(eAward_ghast, L"ghast", -4, 8, Item::ghastTear, (Achievement *)ghast) )->setGolden()->postConstruct(); - Achievements::blazeRod = (new Achievement(eAward_blazeRod, L"blazeRod", 0, 9, Item::blazeRod, (Achievement *)blazeRod) )->postConstruct(); - Achievements::potion = (new Achievement(eAward_potion, L"potion", 2, 8, Item::potion, (Achievement *)potion) )->postConstruct(); - Achievements::theEnd = (new Achievement(eAward_theEnd, L"theEnd", 3, 10, Item::eyeOfEnder, (Achievement *)theEnd) )->setGolden()->postConstruct(); - Achievements::winGame = (new Achievement(eAward_winGame, L"theEnd2", 4, 13, Tile::dragonEgg, (Achievement *)winGame) )->setGolden()->postConstruct(); - Achievements::enchantments = (new Achievement(eAward_enchantments, L"enchantments", -4, 4, Tile::enchantTable, (Achievement *)enchantments) )->postConstruct(); - // Achievements::overkill = (new Achievement(eAward_overkill, L"overkill", -4, 1, Item::sword_diamond, (Achievement *)enchantments) )->setGolden()->postConstruct(); - // Achievements::bookcase = (new Achievement(eAward_bookcase, L"bookcase", -3, 6, Tile::bookshelf, (Achievement *)enchantments) )->postConstruct(); + // 4J Stu - These added in 1.0.1, but do not map to any Xbox achievements + Achievements::diamonds = + (new Achievement(eAward_diamonds, L"diamonds", -1, 5, Item::diamond, + (Achievement*)acquireIron)) + ->postConstruct(); + // Achievements::portal = (new + // Achievement(eAward_portal, L"portal", + // -1, 7, Tile::obsidian, (Achievement *)diamonds) + // )->postConstruct(); + Achievements::ghast = + (new Achievement(eAward_ghast, L"ghast", -4, 8, Item::ghastTear, + (Achievement*)ghast)) + ->setGolden() + ->postConstruct(); + Achievements::blazeRod = + (new Achievement(eAward_blazeRod, L"blazeRod", 0, 9, Item::blazeRod, + (Achievement*)blazeRod)) + ->postConstruct(); + Achievements::potion = (new Achievement(eAward_potion, L"potion", 2, 8, + Item::potion, (Achievement*)potion)) + ->postConstruct(); + Achievements::theEnd = + (new Achievement(eAward_theEnd, L"theEnd", 3, 10, Item::eyeOfEnder, + (Achievement*)theEnd)) + ->setGolden() + ->postConstruct(); + Achievements::winGame = + (new Achievement(eAward_winGame, L"theEnd2", 4, 13, Tile::dragonEgg, + (Achievement*)winGame)) + ->setGolden() + ->postConstruct(); + Achievements::enchantments = + (new Achievement(eAward_enchantments, L"enchantments", -4, 4, + Tile::enchantTable, (Achievement*)enchantments)) + ->postConstruct(); + // Achievements::overkill = (new + // Achievement(eAward_overkill, L"overkill", + // -4, 1, Item::sword_diamond, (Achievement *)enchantments) + // )->setGolden()->postConstruct(); Achievements::bookcase + // = (new Achievement(eAward_bookcase, + // L"bookcase", -3, 6, Tile::bookshelf, + // (Achievement *)enchantments) )->postConstruct(); #endif #ifdef _EXTENDED_ACHIEVEMENTS - Achievements::overkill = (new Achievement(eAward_overkill, L"overkill", -4,1, Item::sword_diamond, (Achievement *)enchantments) )->setGolden()->postConstruct(); - Achievements::bookcase = (new Achievement(eAward_bookcase, L"bookcase", -3,6, Tile::bookshelf, (Achievement *)enchantments) )->postConstruct(); + Achievements::overkill = + (new Achievement(eAward_overkill, L"overkill", -4, 1, + Item::sword_diamond, (Achievement*)enchantments)) + ->setGolden() + ->postConstruct(); + Achievements::bookcase = + (new Achievement(eAward_bookcase, L"bookcase", -3, 6, Tile::bookshelf, + (Achievement*)enchantments)) + ->postConstruct(); - Achievements::adventuringTime = (new Achievement(eAward_adventuringTime, L"adventuringTime", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::repopulation = (new Achievement(eAward_repopulation, L"repopulation", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - //Achievements::porkChoop // // // // // // - Achievements::diamondsToYou = (new Achievement(eAward_diamondsToYou, L"diamondsToYou", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - //Achievements::passingTheTime = (new Achievement(eAward_play100Days, L"passingTheTime", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - //Achievements::archer = (new Achievement(eAward_arrowKillCreeper, L"archer", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::theHaggler = (new Achievement(eAward_theHaggler, L"theHaggler", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::potPlanter = (new Achievement(eAward_potPlanter, L"potPlanter", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::itsASign = (new Achievement(eAward_itsASign, L"itsASign", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::ironBelly = (new Achievement(eAward_ironBelly, L"ironBelly", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::haveAShearfulDay = (new Achievement(eAward_haveAShearfulDay, L"haveAShearfulDay", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::rainbowCollection = (new Achievement(eAward_rainbowCollection, L"rainbowCollection", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::stayinFrosty = (new Achievement(eAward_stayinFrosty, L"stayingFrosty", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::chestfulOfCobblestone = (new Achievement(eAward_chestfulOfCobblestone, L"chestfulOfCobblestone", 0,0, Tile::bookshelf, (Achievement*) NULL) )->setAwardLocallyOnly()->postConstruct(); - Achievements::renewableEnergy = (new Achievement(eAward_renewableEnergy, L"renewableEnergy", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::musicToMyEars = (new Achievement(eAward_musicToMyEars, L"musicToMyEars", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::bodyGuard = (new Achievement(eAward_bodyGuard, L"bodyGuard", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::ironMan = (new Achievement(eAward_ironMan, L"ironMan", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::zombieDoctor = (new Achievement(eAward_zombieDoctor, L"zombieDoctor", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); - Achievements::lionTamer = (new Achievement(eAward_lionTamer, L"lionTamer", 0,0, Tile::bookshelf, (Achievement*) NULL) )->postConstruct(); + Achievements::adventuringTime = + (new Achievement(eAward_adventuringTime, L"adventuringTime", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::repopulation = + (new Achievement(eAward_repopulation, L"repopulation", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + // Achievements::porkChoop // // // + // // // // + Achievements::diamondsToYou = + (new Achievement(eAward_diamondsToYou, L"diamondsToYou", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + // Achievements::passingTheTime = (new + // Achievement(eAward_play100Days, L"passingTheTime", + // 0,0, Tile::bookshelf, (Achievement*) NULL) + // )->postConstruct(); Achievements::archer = (new + // Achievement(eAward_arrowKillCreeper, L"archer", + // 0,0, Tile::bookshelf, (Achievement*) NULL) + // )->postConstruct(); + Achievements::theHaggler = + (new Achievement(eAward_theHaggler, L"theHaggler", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::potPlanter = + (new Achievement(eAward_potPlanter, L"potPlanter", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::itsASign = + (new Achievement(eAward_itsASign, L"itsASign", 0, 0, Tile::bookshelf, + (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::ironBelly = + (new Achievement(eAward_ironBelly, L"ironBelly", 0, 0, Tile::bookshelf, + (Achievement*)NULL)) + ->postConstruct(); + Achievements::haveAShearfulDay = + (new Achievement(eAward_haveAShearfulDay, L"haveAShearfulDay", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + Achievements::rainbowCollection = + (new Achievement(eAward_rainbowCollection, L"rainbowCollection", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::stayinFrosty = + (new Achievement(eAward_stayinFrosty, L"stayingFrosty", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + Achievements::chestfulOfCobblestone = + (new Achievement(eAward_chestfulOfCobblestone, L"chestfulOfCobblestone", + 0, 0, Tile::bookshelf, (Achievement*)NULL)) + ->setAwardLocallyOnly() + ->postConstruct(); + Achievements::renewableEnergy = + (new Achievement(eAward_renewableEnergy, L"renewableEnergy", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + Achievements::musicToMyEars = + (new Achievement(eAward_musicToMyEars, L"musicToMyEars", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + Achievements::bodyGuard = + (new Achievement(eAward_bodyGuard, L"bodyGuard", 0, 0, Tile::bookshelf, + (Achievement*)NULL)) + ->postConstruct(); + Achievements::ironMan = + (new Achievement(eAward_ironMan, L"ironMan", 0, 0, Tile::bookshelf, + (Achievement*)NULL)) + ->postConstruct(); + Achievements::zombieDoctor = + (new Achievement(eAward_zombieDoctor, L"zombieDoctor", 0, 0, + Tile::bookshelf, (Achievement*)NULL)) + ->postConstruct(); + Achievements::lionTamer = + (new Achievement(eAward_lionTamer, L"lionTamer", 0, 0, Tile::bookshelf, + (Achievement*)NULL)) + ->postConstruct(); #endif - } -// Static { System.out.println(achievements.size() + " achievements"); } TODO +// Static { System.out.println(achievements.size() + " achievements"); } +// TODO - -void Achievements::init() -{ -} +void Achievements::init() {} diff --git a/Minecraft.World/Stats/Achievements.h b/Minecraft.World/Stats/Achievements.h index 772fea47c..8db1b65b4 100644 --- a/Minecraft.World/Stats/Achievements.h +++ b/Minecraft.World/Stats/Achievements.h @@ -1,92 +1,89 @@ #pragma once - - class Achievement; -class Achievements -{ - friend class Achievement; +class Achievements { + friend class Achievement; protected: - static const int ACHIEVEMENT_OFFSET; + static const int ACHIEVEMENT_OFFSET; // maximum position of achievements (min and max) public: - static const int ACHIEVEMENT_WIDTH_POSITION = 12; + static const int ACHIEVEMENT_WIDTH_POSITION = 12; static const int ACHIEVEMENT_HEIGHT_POSITION = 12; static int xMin, yMin, xMax, yMax; - static std::vector *achievements; + static std::vector* achievements; - static Achievement *openInventory; - static Achievement *mineWood; - static Achievement *buildWorkbench; - static Achievement *buildPickaxe; - static Achievement *buildFurnace; - static Achievement *acquireIron; - static Achievement *buildHoe; - static Achievement *makeBread; - static Achievement *bakeCake; - static Achievement *buildBetterPickaxe; - static Achievement *cookFish; - static Achievement *onARail; - static Achievement *buildSword; - static Achievement *killEnemy; - static Achievement *killCow; - static Achievement *flyPig; + static Achievement* openInventory; + static Achievement* mineWood; + static Achievement* buildWorkbench; + static Achievement* buildPickaxe; + static Achievement* buildFurnace; + static Achievement* acquireIron; + static Achievement* buildHoe; + static Achievement* makeBread; + static Achievement* bakeCake; + static Achievement* buildBetterPickaxe; + static Achievement* cookFish; + static Achievement* onARail; + static Achievement* buildSword; + static Achievement* killEnemy; + static Achievement* killCow; + static Achievement* flyPig; - // 4J-JEV: Present on the PS3. - static Achievement *snipeSkeleton; - static Achievement *diamonds; - //static Achievement *portal; //4J-JEV: Whats this? - static Achievement *ghast; - static Achievement *blazeRod; - static Achievement *potion; - static Achievement *theEnd; - static Achievement *winGame; - static Achievement *enchantments; + // 4J-JEV: Present on the PS3. + static Achievement* snipeSkeleton; + static Achievement* diamonds; + // static Achievement *portal; //4J-JEV: Whats this? + static Achievement* ghast; + static Achievement* blazeRod; + static Achievement* potion; + static Achievement* theEnd; + static Achievement* winGame; + static Achievement* enchantments; - // 4J : WESTY : Added new acheivements. - static Achievement *leaderOfThePack; - static Achievement *MOARTools; - static Achievement *dispenseWithThis; - static Achievement *InToTheNether; + // 4J : WESTY : Added new acheivements. + static Achievement* leaderOfThePack; + static Achievement* MOARTools; + static Achievement* dispenseWithThis; + static Achievement* InToTheNether; - // 4J : WESTY : Added other awards. - static Achievement *socialPost; - static Achievement *eatPorkChop; - static Achievement *play100Days; - static Achievement *arrowKillCreeper; - static Achievement *mine100Blocks; - static Achievement *kill10Creepers; + // 4J : WESTY : Added other awards. + static Achievement* socialPost; + static Achievement* eatPorkChop; + static Achievement* play100Days; + static Achievement* arrowKillCreeper; + static Achievement* mine100Blocks; + static Achievement* kill10Creepers; #ifdef _EXTENDED_ACHIEVEMENTS - static Achievement *overkill; // Old achievements; - static Achievement *bookcase; // Old achievements; - static Achievement *adventuringTime; - static Achievement *repopulation; - static Achievement *diamondsToYou; - static Achievement *passingTheTime; - static Achievement *archer; - static Achievement *theHaggler; - static Achievement *potPlanter; - static Achievement *itsASign; - static Achievement *ironBelly; - static Achievement *haveAShearfulDay; - static Achievement *rainbowCollection; - static Achievement *stayinFrosty; - static Achievement *chestfulOfCobblestone; - static Achievement *renewableEnergy; - static Achievement *musicToMyEars; - static Achievement *bodyGuard; - static Achievement *ironMan; - static Achievement *zombieDoctor; - static Achievement *lionTamer; + static Achievement* overkill; // Old achievements; + static Achievement* bookcase; // Old achievements; + static Achievement* adventuringTime; + static Achievement* repopulation; + static Achievement* diamondsToYou; + static Achievement* passingTheTime; + static Achievement* archer; + static Achievement* theHaggler; + static Achievement* potPlanter; + static Achievement* itsASign; + static Achievement* ironBelly; + static Achievement* haveAShearfulDay; + static Achievement* rainbowCollection; + static Achievement* stayinFrosty; + static Achievement* chestfulOfCobblestone; + static Achievement* renewableEnergy; + static Achievement* musicToMyEars; + static Achievement* bodyGuard; + static Achievement* ironMan; + static Achievement* zombieDoctor; + static Achievement* lionTamer; #endif - static void staticCtor(); + static void staticCtor(); static void init(); }; diff --git a/Minecraft.World/Stats/CommonStats.cpp b/Minecraft.World/Stats/CommonStats.cpp index aa01f33d9..22f9e7af6 100644 --- a/Minecraft.World/Stats/CommonStats.cpp +++ b/Minecraft.World/Stats/CommonStats.cpp @@ -4,36 +4,35 @@ #include "../Blocks/Tile.h" #include "CommonStats.h" -Stat *CommonStats::get_stat(int i) -{ - return Stats::get(i); -} +Stat* CommonStats::get_stat(int i) { return Stats::get(i); } -Stat* CommonStats::get_walkOneM() { return Stats::walkOneM; } +Stat* CommonStats::get_walkOneM() { return Stats::walkOneM; } -Stat* CommonStats::get_swimOneM() { return Stats::swimOneM; } +Stat* CommonStats::get_swimOneM() { return Stats::swimOneM; } -Stat* CommonStats::get_fallOneM() { return Stats::fallOneM; } +Stat* CommonStats::get_fallOneM() { return Stats::fallOneM; } -Stat* CommonStats::get_climbOneM() { return Stats::climbOneM; } +Stat* CommonStats::get_climbOneM() { return Stats::climbOneM; } -Stat* CommonStats::get_minecartOneM() { return Stats::minecartOneM; } +Stat* CommonStats::get_minecartOneM() { return Stats::minecartOneM; } -Stat* CommonStats::get_boatOneM() { return Stats::boatOneM; } +Stat* CommonStats::get_boatOneM() { return Stats::boatOneM; } -Stat* CommonStats::get_pigOneM() { return Stats::pigOneM; } +Stat* CommonStats::get_pigOneM() { return Stats::pigOneM; } -Stat* CommonStats::get_portalsCreated() { return Stats::portalsCreated; } +Stat* CommonStats::get_portalsCreated() { return Stats::portalsCreated; } Stat* CommonStats::get_cowsMilked() { return Stats::cowsMilked; } -Stat* CommonStats::get_netherLavaCollected() { return Stats::netherLavaCollected; } +Stat* CommonStats::get_netherLavaCollected() { + return Stats::netherLavaCollected; +} -Stat* CommonStats::get_killsZombie() { return Stats::killsZombie; } +Stat* CommonStats::get_killsZombie() { return Stats::killsZombie; } -Stat* CommonStats::get_killsSkeleton() { return Stats::killsSkeleton; } +Stat* CommonStats::get_killsSkeleton() { return Stats::killsSkeleton; } -Stat* CommonStats::get_killsCreeper() { return Stats::killsCreeper; } +Stat* CommonStats::get_killsCreeper() { return Stats::killsCreeper; } Stat* CommonStats::get_killsSpider() { return Stats::killsSpider; } @@ -45,254 +44,303 @@ Stat* CommonStats::get_killsSlime() { return Stats::killsSlime; } Stat* CommonStats::get_killsGhast() { return Stats::killsGhast; } -Stat* CommonStats::get_killsNetherZombiePigman() { return Stats::killsNetherZombiePigman; } - -Stat *CommonStats::get_breedEntity(eINSTANCEOF mobType) -{ - if (mobType == eTYPE_COW) return GenericStats::repopulation(); - else return NULL; +Stat* CommonStats::get_killsNetherZombiePigman() { + return Stats::killsNetherZombiePigman; } -Stat *CommonStats::get_tamedEntity(eINSTANCEOF mobType) -{ - if (mobType == eTYPE_OZELOT) return GenericStats::lionTamer(); - else if (mobType == eTYPE_WOLF) return Stats::befriendsWolf; - else return NULL; +Stat* CommonStats::get_breedEntity(eINSTANCEOF mobType) { + if (mobType == eTYPE_COW) + return GenericStats::repopulation(); + else + return NULL; } -Stat *CommonStats::get_craftedEntity(eINSTANCEOF mobType) -{ - if (mobType == eTYPE_VILLAGERGOLEM) return GenericStats::bodyGuard(); - else return NULL; +Stat* CommonStats::get_tamedEntity(eINSTANCEOF mobType) { + if (mobType == eTYPE_OZELOT) + return GenericStats::lionTamer(); + else if (mobType == eTYPE_WOLF) + return Stats::befriendsWolf; + else + return NULL; } -Stat *CommonStats::get_shearedEntity(eINSTANCEOF mobType) -{ - if (mobType == eTYPE_SHEEP) return GenericStats::haveAShearfulDay(); - else return NULL; +Stat* CommonStats::get_craftedEntity(eINSTANCEOF mobType) { + if (mobType == eTYPE_VILLAGERGOLEM) + return GenericStats::bodyGuard(); + else + return NULL; } -Stat *CommonStats::get_totalBlocksMined() { return Stats::totalBlocksMined; } +Stat* CommonStats::get_shearedEntity(eINSTANCEOF mobType) { + if (mobType == eTYPE_SHEEP) + return GenericStats::haveAShearfulDay(); + else + return NULL; +} + +Stat* CommonStats::get_totalBlocksMined() { return Stats::totalBlocksMined; } Stat* CommonStats::get_timePlayed() { return Stats::timePlayed; } -Stat* CommonStats::get_blocksPlaced(int blockId) -{ +Stat* CommonStats::get_blocksPlaced(int blockId) { #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _XBOX_ONE) - return Stats::blocksPlaced[blockId]; + return Stats::blocksPlaced[blockId]; #else - return NULL; + return NULL; #endif } -Stat *CommonStats::get_blocksMined(int blockId) { return Stats::blocksMined[blockId]; } +Stat* CommonStats::get_blocksMined(int blockId) { + return Stats::blocksMined[blockId]; +} -Stat *CommonStats::get_itemsCollected(int itemId, int itemAux) -{ - // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to - // stor itemsBought(emerald) so I don't have to make yet another massive - // StatArray for Items Bought. +Stat* CommonStats::get_itemsCollected(int itemId, int itemAux) { + // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to + // stor itemsBought(emerald) so I don't have to make yet another massive + // StatArray for Items Bought. #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _XBOX_ONE) - if (itemId == Tile::cloth_Id) return Stats::rainbowCollection[itemAux]; + if (itemId == Tile::cloth_Id) return Stats::rainbowCollection[itemAux]; #endif - if (itemId != Item::emerald_Id) return Stats::itemsCollected[itemId]; - else return NULL; + if (itemId != Item::emerald_Id) + return Stats::itemsCollected[itemId]; + else + return NULL; } -Stat *CommonStats::get_itemsCrafted(int itemId) { return Stats::itemsCrafted[itemId]; } +Stat* CommonStats::get_itemsCrafted(int itemId) { + return Stats::itemsCrafted[itemId]; +} -Stat *CommonStats::get_itemsSmelted(int itemId) { return Stats::itemsCrafted[itemId]; } +Stat* CommonStats::get_itemsSmelted(int itemId) { + return Stats::itemsCrafted[itemId]; +} -Stat *CommonStats::get_itemsUsed(int itemId) -{ +Stat* CommonStats::get_itemsUsed(int itemId) { #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _XBOX_ONE) - // 4J-JEV: I've done the same thing here, we can't place these items anyway. - if (itemId == Item::porkChop_cooked_Id) return Stats::blocksPlaced[itemId]; + // 4J-JEV: I've done the same thing here, we can't place these items anyway. + if (itemId == Item::porkChop_cooked_Id) return Stats::blocksPlaced[itemId]; #endif - return NULL; + return NULL; } -Stat *CommonStats::get_itemsBought(int itemId) -{ - // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to - // stor itemsBought(emerald) so I don't have to make yet another massive - // StatArray for Items Bought. +Stat* CommonStats::get_itemsBought(int itemId) { + // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to + // stor itemsBought(emerald) so I don't have to make yet another massive + // StatArray for Items Bought. - if (itemId == Item::emerald_Id) return Stats::itemsCollected[itemId]; - else return NULL; + if (itemId == Item::emerald_Id) + return Stats::itemsCollected[itemId]; + else + return NULL; } -Stat *CommonStats::get_killsEnderdragon() { return Stats::killsEnderdragon; } +Stat* CommonStats::get_killsEnderdragon() { return Stats::killsEnderdragon; } -Stat *CommonStats::get_completeTheEnd() { return Stats::completeTheEnd; } +Stat* CommonStats::get_completeTheEnd() { return Stats::completeTheEnd; } -Stat *CommonStats::get_enteredBiome(int biomeId) -{ +Stat* CommonStats::get_enteredBiome(int biomeId) { #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _XBOX_ONE) - return Stats::biomesVisisted[biomeId]; + return Stats::biomesVisisted[biomeId]; #else - return NULL; + return NULL; #endif } -Stat *CommonStats::get_achievement(eAward achievementId) -{ - switch (achievementId) - { - case eAward_TakingInventory: return (Stat *) Achievements::openInventory; - case eAward_GettingWood: return (Stat *) Achievements::mineWood; - case eAward_Benchmarking: return (Stat *) Achievements::buildWorkbench; - case eAward_TimeToMine: return (Stat *) Achievements::buildPickaxe; - case eAward_HotTopic: return (Stat *) Achievements::buildFurnace; - case eAward_AquireHardware: return (Stat *) Achievements::acquireIron; - case eAward_TimeToFarm: return (Stat *) Achievements::buildHoe; - case eAward_BakeBread: return (Stat *) Achievements::makeBread; - case eAward_TheLie: return (Stat *) Achievements::bakeCake; - case eAward_GettingAnUpgrade: return (Stat *) Achievements::buildBetterPickaxe; - case eAward_DeliciousFish: return (Stat *) Achievements::cookFish; - case eAward_OnARail: return (Stat *) Achievements::onARail; - case eAward_TimeToStrike: return (Stat *) Achievements::buildSword; - case eAward_MonsterHunter: return (Stat *) Achievements::killEnemy; - case eAward_CowTipper: return (Stat *) Achievements::killCow; - case eAward_WhenPigsFly: return (Stat *) Achievements::flyPig; - case eAward_LeaderOfThePack: return (Stat *) Achievements::leaderOfThePack; - case eAward_MOARTools: return (Stat *) Achievements::MOARTools; - case eAward_DispenseWithThis: return (Stat *) Achievements::dispenseWithThis; - case eAward_InToTheNether: return (Stat *) Achievements::InToTheNether; - case eAward_mine100Blocks: return (Stat *) Achievements::mine100Blocks; - case eAward_kill10Creepers: return (Stat *) Achievements::kill10Creepers; - case eAward_eatPorkChop: return (Stat *) Achievements::eatPorkChop; - case eAward_play100Days: return (Stat *) Achievements::play100Days; - case eAward_arrowKillCreeper: return (Stat *) Achievements::arrowKillCreeper; - case eAward_socialPost: return (Stat *) Achievements::socialPost; +Stat* CommonStats::get_achievement(eAward achievementId) { + switch (achievementId) { + case eAward_TakingInventory: + return (Stat*)Achievements::openInventory; + case eAward_GettingWood: + return (Stat*)Achievements::mineWood; + case eAward_Benchmarking: + return (Stat*)Achievements::buildWorkbench; + case eAward_TimeToMine: + return (Stat*)Achievements::buildPickaxe; + case eAward_HotTopic: + return (Stat*)Achievements::buildFurnace; + case eAward_AquireHardware: + return (Stat*)Achievements::acquireIron; + case eAward_TimeToFarm: + return (Stat*)Achievements::buildHoe; + case eAward_BakeBread: + return (Stat*)Achievements::makeBread; + case eAward_TheLie: + return (Stat*)Achievements::bakeCake; + case eAward_GettingAnUpgrade: + return (Stat*)Achievements::buildBetterPickaxe; + case eAward_DeliciousFish: + return (Stat*)Achievements::cookFish; + case eAward_OnARail: + return (Stat*)Achievements::onARail; + case eAward_TimeToStrike: + return (Stat*)Achievements::buildSword; + case eAward_MonsterHunter: + return (Stat*)Achievements::killEnemy; + case eAward_CowTipper: + return (Stat*)Achievements::killCow; + case eAward_WhenPigsFly: + return (Stat*)Achievements::flyPig; + case eAward_LeaderOfThePack: + return (Stat*)Achievements::leaderOfThePack; + case eAward_MOARTools: + return (Stat*)Achievements::MOARTools; + case eAward_DispenseWithThis: + return (Stat*)Achievements::dispenseWithThis; + case eAward_InToTheNether: + return (Stat*)Achievements::InToTheNether; + case eAward_mine100Blocks: + return (Stat*)Achievements::mine100Blocks; + case eAward_kill10Creepers: + return (Stat*)Achievements::kill10Creepers; + case eAward_eatPorkChop: + return (Stat*)Achievements::eatPorkChop; + case eAward_play100Days: + return (Stat*)Achievements::play100Days; + case eAward_arrowKillCreeper: + return (Stat*)Achievements::arrowKillCreeper; + case eAward_socialPost: + return (Stat*)Achievements::socialPost; #ifndef _XBOX - case eAward_snipeSkeleton: return (Stat *) Achievements::snipeSkeleton; - case eAward_diamonds: return (Stat *) Achievements::diamonds; - case eAward_portal: return (Stat *) NULL; // TODO - case eAward_ghast: return (Stat *) Achievements::ghast; - case eAward_blazeRod: return (Stat *) Achievements::blazeRod; - case eAward_potion: return (Stat *) Achievements::potion; - case eAward_theEnd: return (Stat *) Achievements::theEnd; - case eAward_winGame: return (Stat *) Achievements::winGame; - case eAward_enchantments: return (Stat *) Achievements::enchantments; + case eAward_snipeSkeleton: + return (Stat*)Achievements::snipeSkeleton; + case eAward_diamonds: + return (Stat*)Achievements::diamonds; + case eAward_portal: + return (Stat*)NULL; // TODO + case eAward_ghast: + return (Stat*)Achievements::ghast; + case eAward_blazeRod: + return (Stat*)Achievements::blazeRod; + case eAward_potion: + return (Stat*)Achievements::potion; + case eAward_theEnd: + return (Stat*)Achievements::theEnd; + case eAward_winGame: + return (Stat*)Achievements::winGame; + case eAward_enchantments: + return (Stat*)Achievements::enchantments; #endif #ifdef _EXTENDED_ACHIEVEMENTS - case eAward_overkill: return (Stat *) Achievements::overkill; // Restored old ach. - case eAward_bookcase: return (Stat *) Achievements::bookcase; // Restored old ach. + case eAward_overkill: + return (Stat*)Achievements::overkill; // Restored old ach. + case eAward_bookcase: + return (Stat*)Achievements::bookcase; // Restored old ach. - case eAward_adventuringTime: return (Stat *) Achievements::adventuringTime; - case eAward_repopulation: return (Stat *) Achievements::repopulation; - case eAward_diamondsToYou: return (Stat *) Achievements::diamondsToYou; - //case eAward_passingTheTime: return (Stat *) Achievements::passingTheTime; - //case eAward_archer: return (Stat *) Achievements::archer; - case eAward_theHaggler: return (Stat *) Achievements::theHaggler; - case eAward_potPlanter: return (Stat *) Achievements::potPlanter; - case eAward_itsASign: return (Stat *) Achievements::itsASign; - case eAward_ironBelly: return (Stat *) Achievements::ironBelly; - case eAward_haveAShearfulDay: return (Stat *) Achievements::haveAShearfulDay; - case eAward_rainbowCollection: return (Stat *) Achievements::rainbowCollection; - case eAward_stayinFrosty: return (Stat *) Achievements::stayinFrosty; - case eAward_chestfulOfCobblestone: return (Stat *) Achievements::chestfulOfCobblestone; - case eAward_renewableEnergy: return (Stat *) Achievements::renewableEnergy; - case eAward_musicToMyEars: return (Stat *) Achievements::musicToMyEars; - case eAward_bodyGuard: return (Stat *) Achievements::bodyGuard; - case eAward_ironMan: return (Stat *) Achievements::ironMan; - case eAward_zombieDoctor: return (Stat *) Achievements::zombieDoctor; - case eAward_lionTamer: return (Stat *) Achievements::lionTamer; + case eAward_adventuringTime: + return (Stat*)Achievements::adventuringTime; + case eAward_repopulation: + return (Stat*)Achievements::repopulation; + case eAward_diamondsToYou: + return (Stat*)Achievements::diamondsToYou; + // case eAward_passingTheTime: return (Stat *) + // Achievements::passingTheTime; case eAward_archer: + // return (Stat *) Achievements::archer; + case eAward_theHaggler: + return (Stat*)Achievements::theHaggler; + case eAward_potPlanter: + return (Stat*)Achievements::potPlanter; + case eAward_itsASign: + return (Stat*)Achievements::itsASign; + case eAward_ironBelly: + return (Stat*)Achievements::ironBelly; + case eAward_haveAShearfulDay: + return (Stat*)Achievements::haveAShearfulDay; + case eAward_rainbowCollection: + return (Stat*)Achievements::rainbowCollection; + case eAward_stayinFrosty: + return (Stat*)Achievements::stayinFrosty; + case eAward_chestfulOfCobblestone: + return (Stat*)Achievements::chestfulOfCobblestone; + case eAward_renewableEnergy: + return (Stat*)Achievements::renewableEnergy; + case eAward_musicToMyEars: + return (Stat*)Achievements::musicToMyEars; + case eAward_bodyGuard: + return (Stat*)Achievements::bodyGuard; + case eAward_ironMan: + return (Stat*)Achievements::ironMan; + case eAward_zombieDoctor: + return (Stat*)Achievements::zombieDoctor; + case eAward_lionTamer: + return (Stat*)Achievements::lionTamer; #endif - default: return (Stat *) NULL; - } + default: + return (Stat*)NULL; + } } -byteArray CommonStats::getParam_walkOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_walkOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_swimOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_swimOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_fallOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_fallOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_climbOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_climbOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_minecartOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_minecartOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_boatOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_boatOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_pigOneM(int distance) -{ - return makeParam(distance); +byteArray CommonStats::getParam_pigOneM(int distance) { + return makeParam(distance); } -byteArray CommonStats::getParam_blocksMined(int id, int data, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_blocksMined(int id, int data, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_itemsCollected(int id, int aux, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_itemsCollected(int id, int aux, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_itemsCrafted(int id, int aux, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_itemsCrafted(int id, int aux, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_itemsSmelted(int id, int aux, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_itemsSmelted(int id, int aux, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_itemsUsed(int id, int aux, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_itemsUsed(int id, int aux, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_itemsBought(int id, int aux, int count) -{ - return makeParam(count); +byteArray CommonStats::getParam_itemsBought(int id, int aux, int count) { + return makeParam(count); } -byteArray CommonStats::getParam_time(int timediff) -{ - return makeParam(timediff); +byteArray CommonStats::getParam_time(int timediff) { + return makeParam(timediff); } -byteArray CommonStats::getParam_noArgs() -{ - return makeParam(); +byteArray CommonStats::getParam_noArgs() { return makeParam(); } + +byteArray CommonStats::makeParam(int count) { + byteArray out(sizeof(int)); + memcpy(out.data, &count, sizeof(int)); + return out; } -byteArray CommonStats::makeParam(int count) -{ - byteArray out( sizeof(int) ); - memcpy(out.data,&count,sizeof(int)); - return out; -} - -int CommonStats::readParam(byteArray paramBlob) -{ - if (paramBlob.length == sizeof(int)) return *( (int*) paramBlob.data ); - else return 1; +int CommonStats::readParam(byteArray paramBlob) { + if (paramBlob.length == sizeof(int)) + return *((int*)paramBlob.data); + else + return 1; } \ No newline at end of file diff --git a/Minecraft.World/Stats/CommonStats.h b/Minecraft.World/Stats/CommonStats.h index 3cf079a17..931b53cd4 100644 --- a/Minecraft.World/Stats/CommonStats.h +++ b/Minecraft.World/Stats/CommonStats.h @@ -2,79 +2,78 @@ #include "GenericStats.h" -class CommonStats : public GenericStats -{ +class CommonStats : public GenericStats { protected: - using GenericStats::getParam_itemsUsed; + using GenericStats::getParam_itemsUsed; - virtual Stat *get_stat(int i); + virtual Stat* get_stat(int i); - virtual Stat* get_walkOneM(); - virtual Stat* get_swimOneM(); - virtual Stat* get_fallOneM(); - virtual Stat* get_climbOneM(); - virtual Stat* get_minecartOneM(); - virtual Stat* get_boatOneM(); - virtual Stat* get_pigOneM(); - virtual Stat* get_portalsCreated(); - virtual Stat* get_cowsMilked(); - virtual Stat* get_netherLavaCollected(); + virtual Stat* get_walkOneM(); + virtual Stat* get_swimOneM(); + virtual Stat* get_fallOneM(); + virtual Stat* get_climbOneM(); + virtual Stat* get_minecartOneM(); + virtual Stat* get_boatOneM(); + virtual Stat* get_pigOneM(); + virtual Stat* get_portalsCreated(); + virtual Stat* get_cowsMilked(); + virtual Stat* get_netherLavaCollected(); - virtual Stat* get_killsZombie(); - virtual Stat* get_killsSkeleton(); - virtual Stat* get_killsCreeper(); - virtual Stat* get_killsSpider(); - virtual Stat* get_killsSpiderJockey(); - virtual Stat* get_killsZombiePigman(); - virtual Stat* get_killsSlime(); - virtual Stat* get_killsGhast(); - virtual Stat* get_killsNetherZombiePigman(); + virtual Stat* get_killsZombie(); + virtual Stat* get_killsSkeleton(); + virtual Stat* get_killsCreeper(); + virtual Stat* get_killsSpider(); + virtual Stat* get_killsSpiderJockey(); + virtual Stat* get_killsZombiePigman(); + virtual Stat* get_killsSlime(); + virtual Stat* get_killsGhast(); + virtual Stat* get_killsNetherZombiePigman(); - virtual Stat* get_totalBlocksMined(); - virtual Stat* get_timePlayed(); + virtual Stat* get_totalBlocksMined(); + virtual Stat* get_timePlayed(); - virtual Stat* get_breedEntity(eINSTANCEOF entityId); - virtual Stat* get_tamedEntity(eINSTANCEOF entityId); - virtual Stat* get_craftedEntity(eINSTANCEOF entityId); - virtual Stat* get_shearedEntity(eINSTANCEOF entityId); + virtual Stat* get_breedEntity(eINSTANCEOF entityId); + virtual Stat* get_tamedEntity(eINSTANCEOF entityId); + virtual Stat* get_craftedEntity(eINSTANCEOF entityId); + virtual Stat* get_shearedEntity(eINSTANCEOF entityId); - virtual Stat* get_blocksPlaced(int blockId); - virtual Stat* get_blocksMined(int blockId); - virtual Stat* get_itemsCollected(int itemId, int itemAux); - virtual Stat* get_itemsCrafted(int itemId); - virtual Stat* get_itemsSmelted(int itemId); - virtual Stat* get_itemsUsed(int itemId); - virtual Stat* get_itemsBought(int itemId); + virtual Stat* get_blocksPlaced(int blockId); + virtual Stat* get_blocksMined(int blockId); + virtual Stat* get_itemsCollected(int itemId, int itemAux); + virtual Stat* get_itemsCrafted(int itemId); + virtual Stat* get_itemsSmelted(int itemId); + virtual Stat* get_itemsUsed(int itemId); + virtual Stat* get_itemsBought(int itemId); - virtual Stat* get_killsEnderdragon(); - virtual Stat* get_completeTheEnd(); + virtual Stat* get_killsEnderdragon(); + virtual Stat* get_completeTheEnd(); - virtual Stat* get_enteredBiome(int biomeId); + virtual Stat* get_enteredBiome(int biomeId); - virtual Stat* get_achievement(eAward achievementId); + virtual Stat* get_achievement(eAward achievementId); - virtual byteArray getParam_walkOneM(int distance); - virtual byteArray getParam_swimOneM(int distance); - virtual byteArray getParam_fallOneM(int distance); - virtual byteArray getParam_climbOneM(int distance); - virtual byteArray getParam_minecartOneM(int distance); - virtual byteArray getParam_boatOneM(int distance); - virtual byteArray getParam_pigOneM(int distance); + virtual byteArray getParam_walkOneM(int distance); + virtual byteArray getParam_swimOneM(int distance); + virtual byteArray getParam_fallOneM(int distance); + virtual byteArray getParam_climbOneM(int distance); + virtual byteArray getParam_minecartOneM(int distance); + virtual byteArray getParam_boatOneM(int distance); + virtual byteArray getParam_pigOneM(int distance); - virtual byteArray getParam_blocksMined(int id, int data, int count); - virtual byteArray getParam_itemsCollected(int id, int aux, int count); - virtual byteArray getParam_itemsCrafted(int id, int aux, int count); - virtual byteArray getParam_itemsSmelted(int id, int aux, int count); - virtual byteArray getParam_itemsUsed(int id, int aux, int count); - virtual byteArray getParam_itemsBought(int id, int aux, int count); + virtual byteArray getParam_blocksMined(int id, int data, int count); + virtual byteArray getParam_itemsCollected(int id, int aux, int count); + virtual byteArray getParam_itemsCrafted(int id, int aux, int count); + virtual byteArray getParam_itemsSmelted(int id, int aux, int count); + virtual byteArray getParam_itemsUsed(int id, int aux, int count); + virtual byteArray getParam_itemsBought(int id, int aux, int count); - virtual byteArray getParam_time(int timediff); + virtual byteArray getParam_time(int timediff); - virtual byteArray getParam_noArgs(); + virtual byteArray getParam_noArgs(); protected: - static byteArray makeParam(int count = 1); + static byteArray makeParam(int count = 1); public: - static int readParam(byteArray paramBlob); + static int readParam(byteArray paramBlob); }; \ No newline at end of file diff --git a/Minecraft.World/Stats/DurangoStats.cpp b/Minecraft.World/Stats/DurangoStats.cpp index 70fbd33c9..c24e1eb4a 100644 --- a/Minecraft.World/Stats/DurangoStats.cpp +++ b/Minecraft.World/Stats/DurangoStats.cpp @@ -25,1197 +25,1043 @@ #include "DurangoStats.h" - /////////////////// - // Ds Item Event // - /////////////////// +/////////////////// +// Ds Item Event // +/////////////////// -string DsItemEvent::nameMethods[] = { - "NONE", "itemPickedUp", "itemCrafted", - "itemTakenFromChest", "itemTakenFromEnderchest", - "itemBought", "itemSmithed", "blockMined", "blockPlaced", "MAX" -}; +string DsItemEvent::nameMethods[] = {"NONE", + "itemPickedUp", + "itemCrafted", + "itemTakenFromChest", + "itemTakenFromEnderchest", + "itemBought", + "itemSmithed", + "blockMined", + "blockPlaced", + "MAX"}; -DsItemEvent::DsItemEvent(int id, const std::wstring &name) : Stat(id,name) {} +DsItemEvent::DsItemEvent(int id, const std::wstring& name) : Stat(id, name) {} -bool DsItemEvent::onLeaderboard(ELeaderboardId leaderboard, eAcquisitionMethod methodId, Param *param) -{ - switch (methodId) - { - case eAcquisitionMethod_Pickedup: - switch (param->itemId) - { - case Item::egg_Id: - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - return leaderboard == eLeaderboardId_FARMING; - } - break; +bool DsItemEvent::onLeaderboard(ELeaderboardId leaderboard, + eAcquisitionMethod methodId, Param* param) { + switch (methodId) { + case eAcquisitionMethod_Pickedup: + switch (param->itemId) { + case Item::egg_Id: + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + return leaderboard == eLeaderboardId_FARMING; + } + break; - case eAcquisitionMethod_Mined: - switch (param->itemId) - { - case Tile::dirt_Id: - case Tile::stoneBrick_Id: - case Tile::sand_Id: - case Tile::rock_Id: - case Tile::gravel_Id: - case Tile::clay_Id: - case Tile::obsidian_Id: - return leaderboard == eLeaderboardId_MINING; + case eAcquisitionMethod_Mined: + switch (param->itemId) { + case Tile::dirt_Id: + case Tile::stoneBrick_Id: + case Tile::sand_Id: + case Tile::rock_Id: + case Tile::gravel_Id: + case Tile::clay_Id: + case Tile::obsidian_Id: + return leaderboard == eLeaderboardId_MINING; - case Tile::crops_Id: - case Tile::pumpkin_Id: - case Tile::reeds_Id: - return leaderboard == eLeaderboardId_FARMING; - } - break; - } + case Tile::crops_Id: + case Tile::pumpkin_Id: + case Tile::reeds_Id: + return leaderboard == eLeaderboardId_FARMING; + } + break; + } - return false; + return false; } - // 4J-JEV, for tiles/items we want to record stats together. -int DsItemEvent::mergeIds(int itemId) -{ - switch (itemId) - { - default: - return itemId; +int DsItemEvent::mergeIds(int itemId) { + switch (itemId) { + default: + return itemId; - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - return Tile::mushroom1_Id; + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + return Tile::mushroom1_Id; - case Tile::dirt_Id: - case Tile::grass_Id: - case Tile::farmland_Id: - return Tile::dirt_Id; + case Tile::dirt_Id: + case Tile::grass_Id: + case Tile::farmland_Id: + return Tile::dirt_Id; - case Tile::redstoneLight_Id: - case Tile::redstoneLight_lit_Id: - return Tile::redstoneLight_Id; + case Tile::redstoneLight_Id: + case Tile::redstoneLight_lit_Id: + return Tile::redstoneLight_Id; - case Tile::redStoneOre_Id: - case Tile::redStoneOre_lit_Id: - return Tile::redStoneOre_Id; - } + case Tile::redStoneOre_Id: + case Tile::redStoneOre_lit_Id: + return Tile::redStoneOre_Id; + } } -void DsItemEvent::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param *) paramBlob.data; +void DsItemEvent::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; - // Combine block ids. - param->itemId = mergeIds( param->itemId ); + // Combine block ids. + param->itemId = mergeIds(param->itemId); - // Send farming leaderboard updates. - if ( (param->methodId == eAcquisitionMethod_Pickedup && onLeaderboard(eLeaderboardId_FARMING, eAcquisitionMethod_Pickedup, param)) - || (param->methodId == eAcquisitionMethod_Mined && onLeaderboard(eLeaderboardId_FARMING, eAcquisitionMethod_Mined, param)) ) - { - EventWriteLeaderboardTotals( - DurangoStats::getUserId(player), //UserId - DurangoStats::getPlayerSession(), // PlayerSessionId - player->level->difficulty, // Difficulty, - eLeaderboardId_FARMING, // ScoreboardId - param->itemCount); + // Send farming leaderboard updates. + if ((param->methodId == eAcquisitionMethod_Pickedup && + onLeaderboard(eLeaderboardId_FARMING, eAcquisitionMethod_Pickedup, + param)) || + (param->methodId == eAcquisitionMethod_Mined && + onLeaderboard(eLeaderboardId_FARMING, eAcquisitionMethod_Mined, + param))) { + EventWriteLeaderboardTotals( + DurangoStats::getUserId(player), // UserId + DurangoStats::getPlayerSession(), // PlayerSessionId + player->level->difficulty, // Difficulty, + eLeaderboardId_FARMING, // ScoreboardId + param->itemCount); - app.DebugPrintf("<%ls>\tscoreboardFarming(%i:%i:%i)\n", DurangoStats::getUserId(player), - player->level->difficulty, eLeaderboardId_FARMING, param->itemCount); - } + app.DebugPrintf("<%ls>\tscoreboardFarming(%i:%i:%i)\n", + DurangoStats::getUserId(player), + player->level->difficulty, eLeaderboardId_FARMING, + param->itemCount); + } - // Send mining leaderboard updates. - if ( param->methodId == eAcquisitionMethod_Mined && onLeaderboard(eLeaderboardId_MINING, eAcquisitionMethod_Mined, param) ) - { - EventWriteLeaderboardTotals( - DurangoStats::getUserId(player), //UserId - DurangoStats::getPlayerSession(), // PlayerSessionId - player->level->difficulty, // Difficulty, - eLeaderboardId_MINING, // ScoreboardId - param->itemCount); - app.DebugPrintf("<%ls>\tscoreboardMining(%i:%i:%i)\n", DurangoStats::getUserId(player), - player->level->difficulty, eLeaderboardId_MINING, param->itemCount); - } + // Send mining leaderboard updates. + if (param->methodId == eAcquisitionMethod_Mined && + onLeaderboard(eLeaderboardId_MINING, eAcquisitionMethod_Mined, + param)) { + EventWriteLeaderboardTotals( + DurangoStats::getUserId(player), // UserId + DurangoStats::getPlayerSession(), // PlayerSessionId + player->level->difficulty, // Difficulty, + eLeaderboardId_MINING, // ScoreboardId + param->itemCount); + app.DebugPrintf("<%ls>\tscoreboardMining(%i:%i:%i)\n", + DurangoStats::getUserId(player), + player->level->difficulty, eLeaderboardId_MINING, + param->itemCount); + } - // Debug printout. - string method = nameMethods[(int)param->methodId]; - app.DebugPrintf("<%ls>\t%s(%i:%i:%i)\n", DurangoStats::getUserId(player), - method.c_str(), param->itemId, param->itemAux, param->itemCount); + // Debug printout. + string method = nameMethods[(int)param->methodId]; + app.DebugPrintf("<%ls>\t%s(%i:%i:%i)\n", + DurangoStats::getUserId(player), method.c_str(), + param->itemId, param->itemAux, param->itemCount); - // Split on acquisition method, then send relevant events. - if (param->methodId == eAcquisitionMethod_Placed) - { - EventWriteBlockPlaced( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - player->level->difficulty, - param->itemId, - param->itemAux, - param->itemCount - ); - } - else if (param->methodId == eAcquisitionMethod_Mined) - { - EventWriteBlockBroken( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - player->level->difficulty, - param->itemId, - param->itemAux, - param->itemCount - ); - } - else - { - EventWriteMcItemAcquired( - DurangoStats::getUserId(player), - 0, // TODO - DurangoStats::getPlayerSession(), - 0, - 0, - player->level->difficulty, - param->itemId, - param->methodId, - 0, 0, 0, // (x,y,z) - param->itemAux, - param->itemCount - ); - } - } + // Split on acquisition method, then send relevant events. + if (param->methodId == eAcquisitionMethod_Placed) { + EventWriteBlockPlaced(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + player->level->difficulty, param->itemId, + param->itemAux, param->itemCount); + } else if (param->methodId == eAcquisitionMethod_Mined) { + EventWriteBlockBroken(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + player->level->difficulty, param->itemId, + param->itemAux, param->itemCount); + } else { + EventWriteMcItemAcquired(DurangoStats::getUserId(player), + 0, // TODO + DurangoStats::getPlayerSession(), 0, 0, + player->level->difficulty, param->itemId, + param->methodId, 0, 0, 0, // (x,y,z) + param->itemAux, param->itemCount); + } + } } -/* 4J-JEV: note that mined events will only fire with 'Instant_Mine' on if you are carrying an appropriate - * tool for the block that you are mining. +/* 4J-JEV: note that mined events will only fire with 'Instant_Mine' on if you + * are carrying an appropriate tool for the block that you are mining. */ -byteArray DsItemEvent::createParamBlob(eAcquisitionMethod eMethod, int itemId, int itemAux, int itemCount) -{ - byteArray output; - Param param = { eMethod, itemId, itemAux, itemCount }; - output.data = (uint8_t *) new Param(param); - output.length = sizeof(Param); - return output; +byteArray DsItemEvent::createParamBlob(eAcquisitionMethod eMethod, int itemId, + int itemAux, int itemCount) { + byteArray output; + Param param = {eMethod, itemId, itemAux, itemCount}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; } +/////////////////// +// Ds Mob Killed // +/////////////////// - /////////////////// - // Ds Mob Killed // - /////////////////// +DsMobKilled::DsMobKilled(int id, const std::wstring& name) : Stat(id, name) {} -DsMobKilled::DsMobKilled(int id, const std::wstring &name) : Stat(id,name) {} +void DsMobKilled::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; -void DsMobKilled::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param *) paramBlob.data; + if (param->mobType < 0) return; - if (param->mobType < 0) return; + if (EventWriteMobKilled(DurangoStats::getUserId(player), 0, + DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId(), 0, + player->level->difficulty, + DurangoStats::getPlayerSession(), // ROUND ID + 0, param->weaponId, param->mobType, + param->isRanged ? 1 : 0, 0, 0, 0, // (x,y,z), + 0, param->distance, param->mobType) == 0) { + app.DebugPrintf( + "<%ls>\t%s(%i:%i:%i:%i)\n", DurangoStats::getUserId(player), + (param->isRanged ? "mobShotWithEntity" : "mobKilledInMelee"), + param->mobType, param->weaponId, param->distance, + param->damage); + } - if (EventWriteMobKilled(DurangoStats::getUserId(player), - 0, - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId(), - 0, - player->level->difficulty, - DurangoStats::getPlayerSession(), // ROUND ID - 0, - param->weaponId, - param->mobType, - param->isRanged?1:0, - 0, 0, 0, // (x,y,z), - 0, - param->distance, - param->mobType) - == 0) - { - app.DebugPrintf("<%ls>\t%s(%i:%i:%i:%i)\n", DurangoStats::getUserId(player), - (param->isRanged?"mobShotWithEntity":"mobKilledInMelee"), - param->mobType, param->weaponId, param->distance, param->damage); - } + switch (EntityIO::getClass(param->mobType)) { + case eTYPE_MONSTER: + if (param->mobType != SPIDER_JOCKEY_ID) break; + // Fallthrough is spider jockey + case eTYPE_ZOMBIE: + case eTYPE_SKELETON: + case eTYPE_CREEPER: + case eTYPE_SPIDER: + case eTYPE_PIGZOMBIE: + case eTYPE_SLIME: - switch(EntityIO::getClass(param->mobType)) - { - case eTYPE_MONSTER: - if(param->mobType != SPIDER_JOCKEY_ID) break; - // Fallthrough is spider jockey - case eTYPE_ZOMBIE: - case eTYPE_SKELETON: - case eTYPE_CREEPER: - case eTYPE_SPIDER: - case eTYPE_PIGZOMBIE: - case eTYPE_SLIME: - - if (EventWriteLeaderboardTotals( - DurangoStats::getUserId(player), //UserId - DurangoStats::getPlayerSession(), // PlayerSessionId - player->level->difficulty, // Difficulty, - eLeaderboardId_KILLING, // ScoreboardId - 1) // Count - == 0) - { - app.DebugPrintf("<%ls>\tscoreboardKills(%i:%i:1)\n", DurangoStats::getUserId(player), - player->level->difficulty, eLeaderboardId_KILLING); - } - } - } + if (EventWriteLeaderboardTotals( + DurangoStats::getUserId(player), // UserId + DurangoStats::getPlayerSession(), // PlayerSessionId + player->level->difficulty, // Difficulty, + eLeaderboardId_KILLING, // ScoreboardId + 1) // Count + == 0) { + app.DebugPrintf("<%ls>\tscoreboardKills(%i:%i:1)\n", + DurangoStats::getUserId(player), + player->level->difficulty, + eLeaderboardId_KILLING); + } + } + } } -byteArray DsMobKilled::createParamBlob(std::shared_ptr player, std::shared_ptr mob, DamageSource *dmgSrc) -{ - // 4J-JEV: Get the id we use for Durango Server Stats. - int mob_networking_id; - eINSTANCEOF mobEType = mob->GetType(); - if ( (mobEType == eTYPE_SPIDER) && (mob->rider.lock() != NULL) && (mob->rider.lock()->GetType() == eTYPE_SKELETON) ) - { - mob_networking_id = SPIDER_JOCKEY_ID; // Spider jockey only a concept for leaderboards. - } - else if ( (mobEType == eTYPE_SKELETON) && (mob->riding != NULL) && (mob->riding->GetType() == eTYPE_SPIDER) ) - { - mob_networking_id = SPIDER_JOCKEY_ID; // Spider jockey only a concept for leaderboards. - } - else - { - mob_networking_id = EntityIO::eTypeToIoid(mobEType); - } +byteArray DsMobKilled::createParamBlob(std::shared_ptr player, + std::shared_ptr mob, + DamageSource* dmgSrc) { + // 4J-JEV: Get the id we use for Durango Server Stats. + int mob_networking_id; + eINSTANCEOF mobEType = mob->GetType(); + if ((mobEType == eTYPE_SPIDER) && (mob->rider.lock() != NULL) && + (mob->rider.lock()->GetType() == eTYPE_SKELETON)) { + mob_networking_id = + SPIDER_JOCKEY_ID; // Spider jockey only a concept for leaderboards. + } else if ((mobEType == eTYPE_SKELETON) && (mob->riding != NULL) && + (mob->riding->GetType() == eTYPE_SPIDER)) { + mob_networking_id = + SPIDER_JOCKEY_ID; // Spider jockey only a concept for leaderboards. + } else { + mob_networking_id = EntityIO::eTypeToIoid(mobEType); + } - // Kill made with projectile, arrow/ghast/fireball/snowball. - // NB: Snowball kills would make an awesome achievement. ("Not a snowball's chance...") - if ( dmgSrc->isProjectile() ) - { - byteArray output; - Param param = { - DsMobKilled::RANGED, - mob_networking_id, - EntityIO::eTypeToIoid(dmgSrc->getDirectEntity()->GetType()), - mob->distanceTo(player->x, player->y, player->z), - 0/*not needed*/ - }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; - } - - // Kill made in melee, use itemInHand as weapon. - std::shared_ptr item = player->getCarriedItem(); - byteArray output; - Param param = { - DsMobKilled::MELEE, - mob_networking_id, - (item != NULL ? item->getItem()->id : 0), - mob->distanceTo(player->x, player->y, player->z), - 0/*not needed*/ - }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; + // Kill made with projectile, arrow/ghast/fireball/snowball. + // NB: Snowball kills would make an awesome achievement. ("Not a snowball's + // chance...") + if (dmgSrc->isProjectile()) { + byteArray output; + Param param = { + DsMobKilled::RANGED, mob_networking_id, + EntityIO::eTypeToIoid(dmgSrc->getDirectEntity()->GetType()), + mob->distanceTo(player->x, player->y, player->z), 0 /*not needed*/ + }; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; + } + + // Kill made in melee, use itemInHand as weapon. + std::shared_ptr item = player->getCarriedItem(); + byteArray output; + Param param = { + DsMobKilled::MELEE, mob_networking_id, + (item != NULL ? item->getItem()->id : 0), + mob->distanceTo(player->x, player->y, player->z), 0 /*not needed*/ + }; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; } +///////////////////// +// Ds Mob Interact // +///////////////////// - ///////////////////// - // Ds Mob Interact // - ///////////////////// +string DsMobInteract::nameInteract[] = {"unknownMobInteraction", + "mobBred", + "mobTamed", + "mobCured", + "mobCrafted", + "mobSheared"}; -string DsMobInteract::nameInteract[] = { - "unknownMobInteraction", "mobBred", "mobTamed", "mobCured", "mobCrafted", "mobSheared" +DsMobInteract::DsMobInteract(int id, const std::wstring& name) + : Stat(id, name) {} + +void DsMobInteract::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; + + if (param->mobId < 0) return; + + app.DebugPrintf("<%ls>\t%s(%i)\n", DurangoStats::getUserId(player), + nameInteract[param->interactionType].c_str(), + param->mobId); + + EventWriteMobInteract(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), param->mobId, + param->interactionType); + } +} + +byteArray DsMobInteract::createParamBlob(eInteract interactionId, + int entityId) { + byteArray output; + Param param = {interactionId, EntityIO::eTypeToIoid((eINSTANCEOF)entityId)}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; +} + +/////////////// +// Ds Travel // +/////////////// + +string DsTravel::nameMethods[eMethod_MAX] = {"Walk", "Swim", "Fall", "Climb", + "Cart", "Boat", "Pig", "Time"}; + +unsigned int DsTravel::CACHE_SIZES[eMethod_MAX] = { + 40, // WALK - Meters? + 20, // SWIM - Meters? + 0, // FALL - Meters? - Fall event naturally only sends on land, no caching + // necessary. + 10, // CLIMB - Meters? + 70, // CART - Meters? + 70, // BOAT - Meters? + 10, // PIG - Meters? + 20 * 60 * 5, // TIME - GameTicks (20*60*5 ~ 5 mins) }; -DsMobInteract::DsMobInteract(int id, const std::wstring &name) : Stat(id,name) {} - -void DsMobInteract::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param *) paramBlob.data; - - if (param->mobId < 0) return; - - app.DebugPrintf("<%ls>\t%s(%i)\n", DurangoStats::getUserId(player), - nameInteract[param->interactionType].c_str(), param->mobId); - - EventWriteMobInteract( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - param->mobId, - param->interactionType ); - } -} - -byteArray DsMobInteract::createParamBlob(eInteract interactionId, int entityId) -{ - byteArray output; - Param param = { interactionId, EntityIO::eTypeToIoid((eINSTANCEOF)entityId) }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; -} - - - /////////////// - // Ds Travel // - /////////////// - -string DsTravel::nameMethods[eMethod_MAX] = - { - "Walk", "Swim", "Fall", "Climb", "Cart", "Boat", "Pig", "Time" - }; - -unsigned int DsTravel::CACHE_SIZES[eMethod_MAX] = - { - 40, // WALK - Meters? - 20, // SWIM - Meters? - 0, // FALL - Meters? - Fall event naturally only sends on land, no caching necessary. - 10, // CLIMB - Meters? - 70, // CART - Meters? - 70, // BOAT - Meters? - 10, // PIG - Meters? - 20*60*5, // TIME - GameTicks (20*60*5 ~ 5 mins) - }; - -DsTravel::DsTravel(int id, const std::wstring &name) : Stat(id,name) -{ - ZeroMemory(¶m_cache, sizeof(unsigned int)*eMethod_MAX*MAX_LOCAL_PLAYERS); -} - -void DsTravel::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param*) paramBlob.data; - - int newDistance = cache(player->GetXboxPad(), *param); - - if ( newDistance > 0 ) write(player, param->method, newDistance); - } -} - -byteArray DsTravel::createParamBlob(eMethod method, int distance) -{ - byteArray output; - Param param = { method, distance }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; -} - -int DsTravel::cache(int iPad, Param ¶m) -{ - if ( (eMethod_walk <= param.method) && (param.method < eMethod_MAX) ) - { - param_cache[iPad][param.method] += param.distance; - - if (param_cache[iPad][param.method] > CACHE_SIZES[param.method]) - { - int out = param_cache[iPad][param.method]; - param_cache[iPad][param.method] = 0; - return out; - } - } - - return 0; -} - -void DsTravel::flush(std::shared_ptr player) -{ - int iPad = player->GetXboxPad(); - for (int i = 0; i < eMethod_MAX; i++) - { - if (param_cache[iPad][i] > 0) - { - write( player, (eMethod) i, param_cache[iPad][i] ); - param_cache[iPad][i] = 0; - } - } -} - -void DsTravel::write(std::shared_ptr player, eMethod method, int distance) -{ - if (player == nullptr) return; - - app.DebugPrintf("<%ls>\t%s(%i)\n", DurangoStats::getUserId(player), nameMethods[method].c_str(), distance); - - if (method == DsTravel::eMethod_time) - { - EventWriteIncTimePlayed( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - player->level->difficulty, - distance - ); - } - else if ( (eMethod_walk <= method) && (method < eMethod_MAX) ) - { - EventWriteIncDistanceTravelled( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - player->level->difficulty, - distance, - method - ); - - switch(method) - { - case eMethod_walk: - case eMethod_fall: - case eMethod_minecart: - case eMethod_boat: - EventWriteLeaderboardTotals( - DurangoStats::getUserId(player), //UserId - DurangoStats::getPlayerSession(), // PlayerSessionId - player->level->difficulty, // Difficulty, - eLeaderboardId_TRAVELLING, // ScoreboardId - distance); - break; - } - } -} - - ////////////////// - // Ds Item Used // - ////////////////// - -DsItemUsed::DsItemUsed(int id, const std::wstring &name) : Stat(id,name) {} - -void DsItemUsed::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param*) paramBlob.data; - app.DebugPrintf("<%ls>\titemUsed(%i,%i,%i)\n", DurangoStats::getUserId(player), - param->itemId, - param->aux, - param->count - ); - - EventWriteMcItemUsed( - DurangoStats::getUserId(player), - 0, // SectionId, - DurangoStats::getPlayerSession(), - 0, // MultiplayerCorrelationId, - 0, // Gameplay Mode, - player->level->difficulty, - param->itemId, - 0, 0, 0, // (x,y,z) - param->aux, - param->count, - param->hunger - ); - } -} - -byteArray DsItemUsed::createParamBlob(int itemId, int aux, int count, int health, int hunger) -{ - byteArray output; - Param param = { itemId, aux, count, health, hunger }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; -} - - - //////////////////// - // Ds Achievement // - //////////////////// - -DsAchievement::DsAchievement(int id, const std::wstring &name) : Stat(id,name) {} - -void DsAchievement::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(SmallParam)) - { - SmallParam *paramS = (SmallParam*) paramBlob.data; - assert( DurangoStats::binaryAchievement(paramS->award) ); - app.DebugPrintf("<%ls>\tAchievement(%i)\n", DurangoStats::getUserId(player), paramS->award); - - bool canAward = true; - if(paramS->award == eAward_stayinFrosty) - { - canAward = !player->m_bHasAwardedStayinFrosty; - player->m_bHasAwardedStayinFrosty = true; - } - - if(canAward) - { - EventWriteAchievementGet( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - paramS->award - ); - } - } - else if (paramBlob.length == sizeof(LargeParam)) - { - LargeParam *paramL = (LargeParam*) paramBlob.data; - assert( DurangoStats::enhancedAchievement(paramL->award) ); - - switch(paramL->award) - { - case eAward_musicToMyEars: - app.DebugPrintf("<%ls>\tmusicToMyEars(%i)\n", DurangoStats::getUserId(player), paramL->count); - EventWritePlayedMusicDisc( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - paramL->count - ); - break; - - case eAward_chestfulOfCobblestone: - app.DebugPrintf("<%ls>\tchestfulOfCobblestone(%i)\n", DurangoStats::getUserId(player), paramL->count); - EventWriteChestfulOfCobblestone( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - paramL->count - ); - break; - - case eAward_overkill: - app.DebugPrintf("<%ls>\toverkill(%i)\n", DurangoStats::getUserId(player), paramL->count); - EventWriteOverkill( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - paramL->count - ); - break; - - case eAward_OnARail: - app.DebugPrintf("<%ls>\nonARail(%i)\n", DurangoStats::getUserId(player), paramL->count); - EventWriteOnARail( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - paramL->count - ); - break; - } - } - else assert(false); // Unsuitable paramBlob length. -} - -byteArray DsAchievement::createSmallParamBlob(eAward award) -{ - byteArray output; - SmallParam param = { award }; - output.data = (uint8_t*) new SmallParam(param); - output.length = sizeof(SmallParam); - return output; -} - -byteArray DsAchievement::createLargeParamBlob(eAward award, int count) -{ - byteArray output; - LargeParam param = { award, count }; - output.data = (uint8_t*) new LargeParam(param); - output.length = sizeof(LargeParam); - return output; -} - - - ////////////////////////// - // Ds Changed Dimension // - ////////////////////////// - -DsChangedDimension::DsChangedDimension(int id, const std::wstring &name) : Stat(id,name) {} - -void DsChangedDimension::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param*) paramBlob.data; - app.DebugPrintf("<%ls>\tchangedDimension(%i:%i)\n", DurangoStats::getUserId(player), - param->fromDimId, param->toDimId); - - // No longer used. - } -} - -byteArray DsChangedDimension::createParamBlob(int fromDimId, int toDimId) -{ - byteArray output; - Param param = { fromDimId, toDimId }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; -} - - - ////////////////////// - // Ds Entered Biome // - ////////////////////// - -DsEnteredBiome::DsEnteredBiome(int id, const std::wstring &name) : Stat(id,name) {} - -void DsEnteredBiome::handleParamBlob(std::shared_ptr player, byteArray paramBlob) -{ - if (paramBlob.length == sizeof(Param)) - { - Param *param = (Param*) paramBlob.data; - app.DebugPrintf("<%ls>\tenteredBiome(%i)\n", DurangoStats::getUserId(player), param->biomeId); - - EventWriteEnteredNewBiome( - DurangoStats::getUserId(player), - DurangoStats::getPlayerSession(), - param->biomeId - ); - } +DsTravel::DsTravel(int id, const std::wstring& name) : Stat(id, name) { + ZeroMemory(¶m_cache, + sizeof(unsigned int) * eMethod_MAX * MAX_LOCAL_PLAYERS); +} + +void DsTravel::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; + + int newDistance = cache(player->GetXboxPad(), *param); + + if (newDistance > 0) write(player, param->method, newDistance); + } +} + +byteArray DsTravel::createParamBlob(eMethod method, int distance) { + byteArray output; + Param param = {method, distance}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; +} + +int DsTravel::cache(int iPad, Param& param) { + if ((eMethod_walk <= param.method) && (param.method < eMethod_MAX)) { + param_cache[iPad][param.method] += param.distance; + + if (param_cache[iPad][param.method] > CACHE_SIZES[param.method]) { + int out = param_cache[iPad][param.method]; + param_cache[iPad][param.method] = 0; + return out; + } + } + + return 0; +} + +void DsTravel::flush(std::shared_ptr player) { + int iPad = player->GetXboxPad(); + for (int i = 0; i < eMethod_MAX; i++) { + if (param_cache[iPad][i] > 0) { + write(player, (eMethod)i, param_cache[iPad][i]); + param_cache[iPad][i] = 0; + } + } +} + +void DsTravel::write(std::shared_ptr player, eMethod method, + int distance) { + if (player == nullptr) return; + + app.DebugPrintf("<%ls>\t%s(%i)\n", DurangoStats::getUserId(player), + nameMethods[method].c_str(), distance); + + if (method == DsTravel::eMethod_time) { + EventWriteIncTimePlayed(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + player->level->difficulty, distance); + } else if ((eMethod_walk <= method) && (method < eMethod_MAX)) { + EventWriteIncDistanceTravelled( + DurangoStats::getUserId(player), DurangoStats::getPlayerSession(), + player->level->difficulty, distance, method); + + switch (method) { + case eMethod_walk: + case eMethod_fall: + case eMethod_minecart: + case eMethod_boat: + EventWriteLeaderboardTotals( + DurangoStats::getUserId(player), // UserId + DurangoStats::getPlayerSession(), // PlayerSessionId + player->level->difficulty, // Difficulty, + eLeaderboardId_TRAVELLING, // ScoreboardId + distance); + break; + } + } +} + +////////////////// +// Ds Item Used // +////////////////// + +DsItemUsed::DsItemUsed(int id, const std::wstring& name) : Stat(id, name) {} + +void DsItemUsed::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; + app.DebugPrintf("<%ls>\titemUsed(%i,%i,%i)\n", + DurangoStats::getUserId(player), param->itemId, + param->aux, param->count); + + EventWriteMcItemUsed(DurangoStats::getUserId(player), + 0, // SectionId, + DurangoStats::getPlayerSession(), + 0, // MultiplayerCorrelationId, + 0, // Gameplay Mode, + player->level->difficulty, param->itemId, 0, 0, + 0, // (x,y,z) + param->aux, param->count, param->hunger); + } +} + +byteArray DsItemUsed::createParamBlob(int itemId, int aux, int count, + int health, int hunger) { + byteArray output; + Param param = {itemId, aux, count, health, hunger}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; +} + +//////////////////// +// Ds Achievement // +//////////////////// + +DsAchievement::DsAchievement(int id, const std::wstring& name) + : Stat(id, name) {} + +void DsAchievement::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(SmallParam)) { + SmallParam* paramS = (SmallParam*)paramBlob.data; + assert(DurangoStats::binaryAchievement(paramS->award)); + app.DebugPrintf("<%ls>\tAchievement(%i)\n", + DurangoStats::getUserId(player), paramS->award); + + bool canAward = true; + if (paramS->award == eAward_stayinFrosty) { + canAward = !player->m_bHasAwardedStayinFrosty; + player->m_bHasAwardedStayinFrosty = true; + } + + if (canAward) { + EventWriteAchievementGet(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + paramS->award); + } + } else if (paramBlob.length == sizeof(LargeParam)) { + LargeParam* paramL = (LargeParam*)paramBlob.data; + assert(DurangoStats::enhancedAchievement(paramL->award)); + + switch (paramL->award) { + case eAward_musicToMyEars: + app.DebugPrintf("<%ls>\tmusicToMyEars(%i)\n", + DurangoStats::getUserId(player), paramL->count); + EventWritePlayedMusicDisc(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + paramL->count); + break; + + case eAward_chestfulOfCobblestone: + app.DebugPrintf("<%ls>\tchestfulOfCobblestone(%i)\n", + DurangoStats::getUserId(player), paramL->count); + EventWriteChestfulOfCobblestone( + DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), paramL->count); + break; + + case eAward_overkill: + app.DebugPrintf("<%ls>\toverkill(%i)\n", + DurangoStats::getUserId(player), paramL->count); + EventWriteOverkill(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + paramL->count); + break; + + case eAward_OnARail: + app.DebugPrintf("<%ls>\nonARail(%i)\n", + DurangoStats::getUserId(player), paramL->count); + EventWriteOnARail(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + paramL->count); + break; + } + } else + assert(false); // Unsuitable paramBlob length. +} + +byteArray DsAchievement::createSmallParamBlob(eAward award) { + byteArray output; + SmallParam param = {award}; + output.data = (uint8_t*)new SmallParam(param); + output.length = sizeof(SmallParam); + return output; +} + +byteArray DsAchievement::createLargeParamBlob(eAward award, int count) { + byteArray output; + LargeParam param = {award, count}; + output.data = (uint8_t*)new LargeParam(param); + output.length = sizeof(LargeParam); + return output; +} + +////////////////////////// +// Ds Changed Dimension // +////////////////////////// + +DsChangedDimension::DsChangedDimension(int id, const std::wstring& name) + : Stat(id, name) {} + +void DsChangedDimension::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; + app.DebugPrintf("<%ls>\tchangedDimension(%i:%i)\n", + DurangoStats::getUserId(player), param->fromDimId, + param->toDimId); + + // No longer used. + } +} + +byteArray DsChangedDimension::createParamBlob(int fromDimId, int toDimId) { + byteArray output; + Param param = {fromDimId, toDimId}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; +} + +////////////////////// +// Ds Entered Biome // +////////////////////// + +DsEnteredBiome::DsEnteredBiome(int id, const std::wstring& name) + : Stat(id, name) {} + +void DsEnteredBiome::handleParamBlob(std::shared_ptr player, + byteArray paramBlob) { + if (paramBlob.length == sizeof(Param)) { + Param* param = (Param*)paramBlob.data; + app.DebugPrintf("<%ls>\tenteredBiome(%i)\n", + DurangoStats::getUserId(player), param->biomeId); + + EventWriteEnteredNewBiome(DurangoStats::getUserId(player), + DurangoStats::getPlayerSession(), + param->biomeId); + } } -byteArray DsEnteredBiome::createParamBlob(int biomeId) -{ - byteArray output; - Param param = { biomeId }; - output.data = (uint8_t*) new Param(param); - output.length = sizeof(Param); - return output; +byteArray DsEnteredBiome::createParamBlob(int biomeId) { + byteArray output; + Param param = {biomeId}; + output.data = (uint8_t*)new Param(param); + output.length = sizeof(Param); + return output; } - //////////////////////// - // DURANGO STATISTICS // - //////////////////////// +//////////////////////// +// DURANGO STATISTICS // +//////////////////////// -DurangoStats::DurangoStats() -{ - // Hopefully only using the first parameter - itemsAcquired = new DsItemEvent( itemsAcquired_Id, L"itemsAcquired" ); - itemsAcquired->postConstruct(); +DurangoStats::DurangoStats() { + // Hopefully only using the first parameter + itemsAcquired = new DsItemEvent(itemsAcquired_Id, L"itemsAcquired"); + itemsAcquired->postConstruct(); - itemUsed = new DsItemUsed( itemUsed_Id, L"itemUsed" ); - itemUsed->postConstruct(); + itemUsed = new DsItemUsed(itemUsed_Id, L"itemUsed"); + itemUsed->postConstruct(); - travel = new DsTravel( travel_Id, L"travel" ); - travel->setAwardLocallyOnly()->postConstruct(); + travel = new DsTravel(travel_Id, L"travel"); + travel->setAwardLocallyOnly()->postConstruct(); - mobKilled = new DsMobKilled( mobKilled_Id, L"mobKilled" ); - mobKilled->postConstruct(); + mobKilled = new DsMobKilled(mobKilled_Id, L"mobKilled"); + mobKilled->postConstruct(); - mobInteract = new DsMobInteract( mobInteract_Id, L"mobInteract" ); - mobInteract->postConstruct(); + mobInteract = new DsMobInteract(mobInteract_Id, L"mobInteract"); + mobInteract->postConstruct(); - changedDimension = new DsChangedDimension( changedDimension_Id, L"changedDimension" ); - changedDimension->postConstruct(); + changedDimension = + new DsChangedDimension(changedDimension_Id, L"changedDimension"); + changedDimension->postConstruct(); - enteredBiome = new DsEnteredBiome( enteredBiome_Id, L"enteredBiome" ); - enteredBiome->postConstruct(); + enteredBiome = new DsEnteredBiome(enteredBiome_Id, L"enteredBiome"); + enteredBiome->postConstruct(); - achievement = new DsAchievement( binAchievement_Id, L"achievement" ); - achievement->postConstruct(); + achievement = new DsAchievement(binAchievement_Id, L"achievement"); + achievement->postConstruct(); - achievementLocal = new DsAchievement( binAchievementLocal_Id, L"achievementLocal" ); - achievementLocal->setAwardLocallyOnly(); - achievementLocal->postConstruct(); + achievementLocal = + new DsAchievement(binAchievementLocal_Id, L"achievementLocal"); + achievementLocal->setAwardLocallyOnly(); + achievementLocal->postConstruct(); - EventRegisterXBLA_149E11AE(); + EventRegisterXBLA_149E11AE(); } -DurangoStats::~DurangoStats() -{ - EventUnregisterXBLA_149E11AE(); -} +DurangoStats::~DurangoStats() { EventUnregisterXBLA_149E11AE(); } -Stat *DurangoStats::get_stat(int i) -{ - switch (i) - { - case itemsAcquired_Id: return (Stat*) itemsAcquired; - case itemUsed_Id: return (Stat*) itemUsed; - case travel_Id: return (Stat*) travel; - case mobKilled_Id: return (Stat*) mobKilled; - case mobInteract_Id: return (Stat*) mobInteract; - case changedDimension_Id: return (Stat*) changedDimension; - case enteredBiome_Id: return (Stat*) enteredBiome; - case binAchievement_Id: return (Stat*) achievement; - case binAchievementLocal_Id: return (Stat*) achievementLocal; +Stat* DurangoStats::get_stat(int i) { + switch (i) { + case itemsAcquired_Id: + return (Stat*)itemsAcquired; + case itemUsed_Id: + return (Stat*)itemUsed; + case travel_Id: + return (Stat*)travel; + case mobKilled_Id: + return (Stat*)mobKilled; + case mobInteract_Id: + return (Stat*)mobInteract; + case changedDimension_Id: + return (Stat*)changedDimension; + case enteredBiome_Id: + return (Stat*)enteredBiome; + case binAchievement_Id: + return (Stat*)achievement; + case binAchievementLocal_Id: + return (Stat*)achievementLocal; - // Unrecognised stat id - default: assert(false); break; - } + // Unrecognised stat id + default: + assert(false); + break; + } - return NULL; + return NULL; } -Stat* DurangoStats::get_walkOneM() -{ - return travel; -} +Stat* DurangoStats::get_walkOneM() { return travel; } -Stat* DurangoStats::get_swimOneM() -{ - return travel; -} +Stat* DurangoStats::get_swimOneM() { return travel; } -Stat* DurangoStats::get_fallOneM() -{ - return travel; -} +Stat* DurangoStats::get_fallOneM() { return travel; } -Stat* DurangoStats::get_climbOneM() -{ - return travel; -} +Stat* DurangoStats::get_climbOneM() { return travel; } -Stat* DurangoStats::get_minecartOneM() -{ - return travel; -} +Stat* DurangoStats::get_minecartOneM() { return travel; } -Stat* DurangoStats::get_boatOneM() -{ - return travel; -} +Stat* DurangoStats::get_boatOneM() { return travel; } -Stat* DurangoStats::get_pigOneM() -{ - return travel; -} +Stat* DurangoStats::get_pigOneM() { return travel; } -Stat *DurangoStats::get_cowsMilked() -{ - return get_itemsCrafted(Item::milk_Id); -} +Stat* DurangoStats::get_cowsMilked() { return get_itemsCrafted(Item::milk_Id); } -Stat* DurangoStats::get_killMob() -{ - return mobKilled; -} +Stat* DurangoStats::get_killMob() { return mobKilled; } -Stat* DurangoStats::get_breedEntity(eINSTANCEOF entityId) -{ - return mobInteract; +Stat* DurangoStats::get_breedEntity(eINSTANCEOF entityId) { + return mobInteract; } -Stat* DurangoStats::get_tamedEntity(eINSTANCEOF entityId) -{ - return mobInteract; +Stat* DurangoStats::get_tamedEntity(eINSTANCEOF entityId) { + return mobInteract; } -Stat* DurangoStats::get_curedEntity(eINSTANCEOF entityId) -{ - return mobInteract; +Stat* DurangoStats::get_curedEntity(eINSTANCEOF entityId) { + return mobInteract; } -Stat* DurangoStats::get_craftedEntity(eINSTANCEOF entityId) -{ - return mobInteract; +Stat* DurangoStats::get_craftedEntity(eINSTANCEOF entityId) { + return mobInteract; } -Stat* DurangoStats::get_shearedEntity(eINSTANCEOF entityId) -{ - return mobInteract; +Stat* DurangoStats::get_shearedEntity(eINSTANCEOF entityId) { + return mobInteract; } -Stat* DurangoStats::get_timePlayed() -{ - return travel; -} +Stat* DurangoStats::get_timePlayed() { return travel; } -Stat* DurangoStats::get_blocksPlaced(int blockId) -{ - return (Stat*) itemsAcquired; +Stat* DurangoStats::get_blocksPlaced(int blockId) { + return (Stat*)itemsAcquired; } -Stat* DurangoStats::get_blocksMined(int blockId) -{ - return (Stat*) itemsAcquired; +Stat* DurangoStats::get_blocksMined(int blockId) { + return (Stat*)itemsAcquired; } -Stat* DurangoStats::get_itemsCollected(int itemId, int itemAux) -{ - return (Stat*) itemsAcquired; +Stat* DurangoStats::get_itemsCollected(int itemId, int itemAux) { + return (Stat*)itemsAcquired; } -Stat* DurangoStats::get_itemsCrafted(int itemId) -{ - switch (itemId) - { - // 4J-JEV: These items can be crafted trivially to and from their block equivalents, - // 'Acquire Hardware' also relies on 'Count_Crafted(IronIngot) == Count_Forged(IronIngot)" on the Stats server. - case Item::ironIngot_Id: - case Item::goldIngot_Id: - case Item::diamond_Id: - case Item::redStone_Id: - case Item::emerald_Id: - return NULL; +Stat* DurangoStats::get_itemsCrafted(int itemId) { + switch (itemId) { + // 4J-JEV: These items can be crafted trivially to and from their + // block equivalents, + // 'Acquire Hardware' also relies on 'Count_Crafted(IronIngot) == + //Count_Forged(IronIngot)" on the Stats server. + case Item::ironIngot_Id: + case Item::goldIngot_Id: + case Item::diamond_Id: + case Item::redStone_Id: + case Item::emerald_Id: + return NULL; - case Item::dye_powder_Id: - default: - return (Stat*) itemsAcquired; - } - + case Item::dye_powder_Id: + default: + return (Stat*)itemsAcquired; + } } -Stat* DurangoStats::get_itemsSmelted(int itemId) -{ - // 4J-JEV: Context needed for itemCrafted for iron/gold being smelted. - return (Stat*) itemsAcquired; +Stat* DurangoStats::get_itemsSmelted(int itemId) { + // 4J-JEV: Context needed for itemCrafted for iron/gold being smelted. + return (Stat*)itemsAcquired; } -Stat* DurangoStats::get_itemsUsed(int itemId) -{ - return (Stat*) itemUsed; -} +Stat* DurangoStats::get_itemsUsed(int itemId) { return (Stat*)itemUsed; } -Stat *DurangoStats::get_itemsBought(int itemId) -{ - return (Stat*) itemsAcquired; -} +Stat* DurangoStats::get_itemsBought(int itemId) { return (Stat*)itemsAcquired; } -Stat* DurangoStats::get_changedDimension(int from, int to) -{ - return (Stat*) changedDimension; +Stat* DurangoStats::get_changedDimension(int from, int to) { + return (Stat*)changedDimension; } -Stat* DurangoStats::get_enteredBiome(int biomeId) -{ - return (Stat*) enteredBiome; +Stat* DurangoStats::get_enteredBiome(int biomeId) { + return (Stat*)enteredBiome; } -Stat* DurangoStats::get_achievement(eAward achievementId) -{ - // Special case for 'binary' achievements. - if ( binaryAchievement(achievementId) - || enhancedAchievement(achievementId) ) - { - switch (achievementId) - { - case eAward_chestfulOfCobblestone: - case eAward_TakingInventory: - return achievementLocal; +Stat* DurangoStats::get_achievement(eAward achievementId) { + // Special case for 'binary' achievements. + if (binaryAchievement(achievementId) || + enhancedAchievement(achievementId)) { + switch (achievementId) { + case eAward_chestfulOfCobblestone: + case eAward_TakingInventory: + return achievementLocal; + + default: + return achievement; + } + } else if (achievementId == eAward_zombieDoctor) { + return get_curedEntity(eTYPE_ZOMBIE); + } - default: - return achievement; - } - } - else if (achievementId == eAward_zombieDoctor) - { - return get_curedEntity(eTYPE_ZOMBIE); - } - - // Other achievements awarded through more detailed generic events. - return NULL; + // Other achievements awarded through more detailed generic events. + return NULL; } -byteArray DurangoStats::getParam_walkOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_walk, distance); +byteArray DurangoStats::getParam_walkOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_walk, distance); } -byteArray DurangoStats::getParam_swimOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_swim,distance); +byteArray DurangoStats::getParam_swimOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_swim, distance); } -byteArray DurangoStats::getParam_fallOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_fall,distance); +byteArray DurangoStats::getParam_fallOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_fall, distance); } -byteArray DurangoStats::getParam_climbOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_climb,distance); +byteArray DurangoStats::getParam_climbOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_climb, distance); } -byteArray DurangoStats::getParam_minecartOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_minecart,distance); +byteArray DurangoStats::getParam_minecartOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_minecart, distance); } -byteArray DurangoStats::getParam_boatOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_boat,distance); +byteArray DurangoStats::getParam_boatOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_boat, distance); } -byteArray DurangoStats::getParam_pigOneM(int distance) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_pig,distance); +byteArray DurangoStats::getParam_pigOneM(int distance) { + return DsTravel::createParamBlob(DsTravel::eMethod_pig, distance); } -byteArray DurangoStats::getParam_cowsMilked() -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Crafted, Item::milk_Id, 0, 1); +byteArray DurangoStats::getParam_cowsMilked() { + return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Crafted, + Item::milk_Id, 0, 1); } -byteArray DurangoStats::getParam_blocksPlaced(int blockId, int data, int count) -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Placed, blockId, data, count); +byteArray DurangoStats::getParam_blocksPlaced(int blockId, int data, + int count) { + return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Placed, + blockId, data, count); } -byteArray DurangoStats::getParam_blocksMined(int blockId, int data, int count) -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Mined, blockId, data, count); +byteArray DurangoStats::getParam_blocksMined(int blockId, int data, int count) { + return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Mined, + blockId, data, count); } -byteArray DurangoStats::getParam_itemsCollected(int id, int aux, int count) -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Pickedup, id, aux, count); +byteArray DurangoStats::getParam_itemsCollected(int id, int aux, int count) { + return DsItemEvent::createParamBlob( + DsItemEvent::eAcquisitionMethod_Pickedup, id, aux, count); } -byteArray DurangoStats::getParam_itemsCrafted(int id, int aux, int count) -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Crafted, id, aux, count); +byteArray DurangoStats::getParam_itemsCrafted(int id, int aux, int count) { + return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Crafted, + id, aux, count); } -byteArray DurangoStats::getParam_itemsUsed(std::shared_ptr player, std::shared_ptr itm) -{ - return DsItemUsed::createParamBlob( - itm->getItem()->id, itm->getAuxValue(), itm->GetCount(), - player->getHealth(), player->getFoodData()->getFoodLevel() - ); +byteArray DurangoStats::getParam_itemsUsed(std::shared_ptr player, + std::shared_ptr itm) { + return DsItemUsed::createParamBlob(itm->getItem()->id, itm->getAuxValue(), + itm->GetCount(), player->getHealth(), + player->getFoodData()->getFoodLevel()); } -byteArray DurangoStats::getParam_itemsBought(int id, int aux, int count) -{ - return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Bought, id, aux, count); +byteArray DurangoStats::getParam_itemsBought(int id, int aux, int count) { + return DsItemEvent::createParamBlob(DsItemEvent::eAcquisitionMethod_Bought, + id, aux, count); } -byteArray DurangoStats::getParam_mobKill(std::shared_ptr player, std::shared_ptr mob, DamageSource *dmgSrc) -{ - return DsMobKilled::createParamBlob(player,mob,dmgSrc); +byteArray DurangoStats::getParam_mobKill(std::shared_ptr player, + std::shared_ptr mob, + DamageSource* dmgSrc) { + return DsMobKilled::createParamBlob(player, mob, dmgSrc); } -byteArray DurangoStats::getParam_breedEntity(eINSTANCEOF entityId) -{ - return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Breed, entityId); +byteArray DurangoStats::getParam_breedEntity(eINSTANCEOF entityId) { + return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Breed, + entityId); } -byteArray DurangoStats::getParam_tamedEntity(eINSTANCEOF entityId) -{ - return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Tamed, entityId); +byteArray DurangoStats::getParam_tamedEntity(eINSTANCEOF entityId) { + return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Tamed, + entityId); } -byteArray DurangoStats::getParam_curedEntity(eINSTANCEOF entityId) -{ - return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Cured, entityId); +byteArray DurangoStats::getParam_curedEntity(eINSTANCEOF entityId) { + return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Cured, + entityId); } -byteArray DurangoStats::getParam_craftedEntity(eINSTANCEOF entityId) -{ - return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Crafted, entityId); +byteArray DurangoStats::getParam_craftedEntity(eINSTANCEOF entityId) { + return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Crafted, + entityId); } -byteArray DurangoStats::getParam_shearedEntity(eINSTANCEOF entityId) -{ - return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Sheared, entityId); +byteArray DurangoStats::getParam_shearedEntity(eINSTANCEOF entityId) { + return DsMobInteract::createParamBlob(DsMobInteract::eInteract_Sheared, + entityId); } -byteArray DurangoStats::getParam_time(int timediff) -{ - return DsTravel::createParamBlob(DsTravel::eMethod_time, timediff); +byteArray DurangoStats::getParam_time(int timediff) { + return DsTravel::createParamBlob(DsTravel::eMethod_time, timediff); } -byteArray DurangoStats::getParam_changedDimension(int from, int to) -{ - return DsChangedDimension::createParamBlob(from,to); +byteArray DurangoStats::getParam_changedDimension(int from, int to) { + return DsChangedDimension::createParamBlob(from, to); } -byteArray DurangoStats::getParam_enteredBiome(int biomeId) -{ - return DsEnteredBiome::createParamBlob(biomeId); +byteArray DurangoStats::getParam_enteredBiome(int biomeId) { + return DsEnteredBiome::createParamBlob(biomeId); } -byteArray DurangoStats::getParam_achievement(eAward id) -{ - if (binaryAchievement(id)) - { - return DsAchievement::createSmallParamBlob(id); - } - else if (enhancedAchievement(id)) - { - assert(false); // Should be calling the appropriate getParam function. - } - else if (id == eAward_zombieDoctor) - { - return getParam_curedEntity(eTYPE_ZOMBIE); - } +byteArray DurangoStats::getParam_achievement(eAward id) { + if (binaryAchievement(id)) { + return DsAchievement::createSmallParamBlob(id); + } else if (enhancedAchievement(id)) { + assert(false); // Should be calling the appropriate getParam function. + } else if (id == eAward_zombieDoctor) { + return getParam_curedEntity(eTYPE_ZOMBIE); + } - // If its not a binary achievement, - // don't bother constructing the param blob. - return getParam_noArgs(); + // If its not a binary achievement, + // don't bother constructing the param blob. + return getParam_noArgs(); } -byteArray DurangoStats::getParam_onARail(int dist) -{ - return DsAchievement::createLargeParamBlob(eAward_OnARail, dist); +byteArray DurangoStats::getParam_onARail(int dist) { + return DsAchievement::createLargeParamBlob(eAward_OnARail, dist); } -byteArray DurangoStats::getParam_chestfulOfCobblestone(int count) -{ - return DsAchievement::createLargeParamBlob(eAward_chestfulOfCobblestone, count); +byteArray DurangoStats::getParam_chestfulOfCobblestone(int count) { + return DsAchievement::createLargeParamBlob(eAward_chestfulOfCobblestone, + count); } -byteArray DurangoStats::getParam_overkill(int dmg) -{ - return DsAchievement::createLargeParamBlob(eAward_overkill, dmg); +byteArray DurangoStats::getParam_overkill(int dmg) { + return DsAchievement::createLargeParamBlob(eAward_overkill, dmg); } -byteArray DurangoStats::getParam_musicToMyEars(int recordId) -{ - return DsAchievement::createLargeParamBlob(eAward_musicToMyEars, recordId); +byteArray DurangoStats::getParam_musicToMyEars(int recordId) { + return DsAchievement::createLargeParamBlob(eAward_musicToMyEars, recordId); } -bool DurangoStats::binaryAchievement(eAward achievementId) -{ - switch (achievementId) - { - case eAward_InToTheNether: - case eAward_theEnd: - case eAward_WhenPigsFly: - case eAward_diamondsToYou: - case eAward_stayinFrosty: - case eAward_renewableEnergy: - case eAward_ironMan: - case eAward_winGame: - case /*maybe*/ eAward_TakingInventory: - return true; - default: - return false; - } +bool DurangoStats::binaryAchievement(eAward achievementId) { + switch (achievementId) { + case eAward_InToTheNether: + case eAward_theEnd: + case eAward_WhenPigsFly: + case eAward_diamondsToYou: + case eAward_stayinFrosty: + case eAward_renewableEnergy: + case eAward_ironMan: + case eAward_winGame: + case /*maybe*/ eAward_TakingInventory: + return true; + default: + return false; + } } /** 4J-JEV, - Basically achievements with an inconsequential extra parameter - that I thought best not to / prefered not to / couldn't be bothered to make class handlers for. - (Motivation: it would be nice for players to see how close they were/are to achieving these things). + Basically achievements with an inconsequential extra parameter + that I thought best not to / prefered not to / couldn't be + bothered to make class handlers for. (Motivation: it would be nice for + players to see how close they were/are to achieving these things). */ -bool DurangoStats::enhancedAchievement(eAward achievementId) -{ - switch (achievementId) - { - //case eAward_TakingInventory: - case eAward_musicToMyEars: - case eAward_chestfulOfCobblestone: - case eAward_overkill: - case eAward_OnARail: - return true; - default: - return false; - } +bool DurangoStats::enhancedAchievement(eAward achievementId) { + switch (achievementId) { + // case eAward_TakingInventory: + case eAward_musicToMyEars: + case eAward_chestfulOfCobblestone: + case eAward_overkill: + case eAward_OnARail: + return true; + default: + return false; + } } - -void DurangoStats::generatePlayerSession() -{ - DurangoStats *dsInstance = (DurangoStats *) GenericStats::getInstance(); - CoCreateGuid( &dsInstance->playerSessionId ); +void DurangoStats::generatePlayerSession() { + DurangoStats* dsInstance = (DurangoStats*)GenericStats::getInstance(); + CoCreateGuid(&dsInstance->playerSessionId); } -LPCGUID DurangoStats::getPlayerSession() -{ - DurangoStats *dsInstance = (DurangoStats *) GenericStats::getInstance(); - LPCGUID lpcguid = &dsInstance->playerSessionId; - return lpcguid; +LPCGUID DurangoStats::getPlayerSession() { + DurangoStats* dsInstance = (DurangoStats*)GenericStats::getInstance(); + LPCGUID lpcguid = &dsInstance->playerSessionId; + return lpcguid; } -void DurangoStats::setMultiplayerCorrelationId(Platform::String^ mcpId) -{ - ((DurangoStats*)GenericStats::getInstance())->multiplayerCorrelationId = mcpId; +void DurangoStats::setMultiplayerCorrelationId(Platform::String ^ mcpId) { + ((DurangoStats*)GenericStats::getInstance())->multiplayerCorrelationId = + mcpId; } -LPCWSTR DurangoStats::getMultiplayerCorrelationId() -{ - return ((DurangoStats*)GenericStats::getInstance())->multiplayerCorrelationId->Data(); +LPCWSTR DurangoStats::getMultiplayerCorrelationId() { + return ((DurangoStats*)GenericStats::getInstance()) + ->multiplayerCorrelationId->Data(); } -LPCWSTR DurangoStats::getUserId(std::shared_ptr player) -{ - return getUserId(player->GetXboxPad()); +LPCWSTR DurangoStats::getUserId(std::shared_ptr player) { + return getUserId(player->GetXboxPad()); } -LPCWSTR DurangoStats::getUserId(int iPad) -{ - static std::wstring cache = L""; - PlayerUID uid = INVALID_XUID; - ProfileManager.GetXUID(iPad, &uid, true); - cache = uid.toString(); - return cache.c_str(); +LPCWSTR DurangoStats::getUserId(int iPad) { + static std::wstring cache = L""; + PlayerUID uid = INVALID_XUID; + ProfileManager.GetXUID(iPad, &uid, true); + cache = uid.toString(); + return cache.c_str(); } -void DurangoStats::playerSessionStart(PlayerUID uid, std::shared_ptr plr) -{ - if (plr != NULL && plr->level != NULL && plr->level->getLevelData() != NULL) - { - //wprintf(uid.toString().c_str()); - - //EventWritePlayerSessionStart( - app.DebugPrintf(">>>\tPlayerSessionStart(%ls,%s,%ls,%i,%i)\n", - uid.toString(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId(), - plr->level->getLevelData()->getGameType()->isSurvival(), - plr->level->difficulty - ); +void DurangoStats::playerSessionStart(PlayerUID uid, + std::shared_ptr plr) { + if (plr != NULL && plr->level != NULL && + plr->level->getLevelData() != NULL) { + // wprintf(uid.toString().c_str()); - EventWritePlayerSessionStart( - uid.toString().c_str(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId(), - plr->level->getLevelData()->getGameType()->isSurvival(), - plr->level->difficulty - ); - } + // EventWritePlayerSessionStart( + app.DebugPrintf(">>>\tPlayerSessionStart(%ls,%s,%ls,%i,%i)\n", + uid.toString(), DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId(), + plr->level->getLevelData()->getGameType()->isSurvival(), + plr->level->difficulty); + + EventWritePlayerSessionStart( + uid.toString().c_str(), DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId(), + plr->level->getLevelData()->getGameType()->isSurvival(), + plr->level->difficulty); + } } -void DurangoStats::playerSessionStart(int iPad) -{ - PlayerUID puid; std::shared_ptr plr; - ProfileManager.GetXUID(iPad, &puid, true); - plr = Minecraft::GetInstance()->localplayers[iPad]; - playerSessionStart(puid,plr); +void DurangoStats::playerSessionStart(int iPad) { + PlayerUID puid; + std::shared_ptr plr; + ProfileManager.GetXUID(iPad, &puid, true); + plr = Minecraft::GetInstance()->localplayers[iPad]; + playerSessionStart(puid, plr); } -void DurangoStats::playerSessionPause(int iPad) -{ - std::shared_ptr plr = Minecraft::GetInstance()->localplayers[iPad]; - if (plr != NULL && plr->level != NULL && plr->level->getLevelData() != NULL) - { - PlayerUID puid; - ProfileManager.GetXUID(iPad, &puid, true); +void DurangoStats::playerSessionPause(int iPad) { + std::shared_ptr plr = + Minecraft::GetInstance()->localplayers[iPad]; + if (plr != NULL && plr->level != NULL && + plr->level->getLevelData() != NULL) { + PlayerUID puid; + ProfileManager.GetXUID(iPad, &puid, true); - //EventWritePlayerSessionPause( - app.DebugPrintf(">>>\tPlayerSessionPause(%ls,%s,%ls)\n", - puid.toString().c_str(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId() - ); + // EventWritePlayerSessionPause( + app.DebugPrintf(">>>\tPlayerSessionPause(%ls,%s,%ls)\n", + puid.toString().c_str(), + DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId()); - EventWritePlayerSessionPause( - puid.toString().c_str(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId() - ); - } + EventWritePlayerSessionPause( + puid.toString().c_str(), DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId()); + } } -void DurangoStats::playerSessionResume(int iPad) -{ - std::shared_ptr plr = Minecraft::GetInstance()->localplayers[iPad]; - if (plr != NULL && plr->level != NULL && plr->level->getLevelData() != NULL) - { - PlayerUID puid; - ProfileManager.GetXUID(iPad, &puid, true); +void DurangoStats::playerSessionResume(int iPad) { + std::shared_ptr plr = + Minecraft::GetInstance()->localplayers[iPad]; + if (plr != NULL && plr->level != NULL && + plr->level->getLevelData() != NULL) { + PlayerUID puid; + ProfileManager.GetXUID(iPad, &puid, true); - //EventWritePlayerSessionResume( - app.DebugPrintf(">>>\tPlayerSessionResume(%ls,%s,%ls,%i,%i)\n", - puid.toString().c_str(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId(), - plr->level->getLevelData()->getGameType()->isSurvival(), - plr->level->difficulty - ); + // EventWritePlayerSessionResume( + app.DebugPrintf(">>>\tPlayerSessionResume(%ls,%s,%ls,%i,%i)\n", + puid.toString().c_str(), + DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId(), + plr->level->getLevelData()->getGameType()->isSurvival(), + plr->level->difficulty); - EventWritePlayerSessionResume( - puid.toString().c_str(), - DurangoStats::getPlayerSession(), - DurangoStats::getMultiplayerCorrelationId(), - plr->level->getLevelData()->getGameType()->isSurvival(), - plr->level->difficulty - ); - } + EventWritePlayerSessionResume( + puid.toString().c_str(), DurangoStats::getPlayerSession(), + DurangoStats::getMultiplayerCorrelationId(), + plr->level->getLevelData()->getGameType()->isSurvival(), + plr->level->difficulty); + } } -void DurangoStats::playerSessionEnd(int iPad) -{ - std::shared_ptr plr = Minecraft::GetInstance()->localplayers[iPad]; - if (plr != NULL) - { - DurangoStats::getInstance()->travel->flush(plr); - } +void DurangoStats::playerSessionEnd(int iPad) { + std::shared_ptr plr = + Minecraft::GetInstance()->localplayers[iPad]; + if (plr != NULL) { + DurangoStats::getInstance()->travel->flush(plr); + } } \ No newline at end of file diff --git a/Minecraft.World/Stats/DurangoStats.h b/Minecraft.World/Stats/DurangoStats.h index ee95a8c10..8b3fe861b 100644 --- a/Minecraft.World/Stats/DurangoStats.h +++ b/Minecraft.World/Stats/DurangoStats.h @@ -4,308 +4,331 @@ #include "GenericStats.h" -enum ELeaderboardId -{ - eLeaderboardId_TRAVELLING = 0, - eLeaderboardId_MINING = 1, - eLeaderboardId_FARMING = 2, - eLeaderboardId_KILLING = 3 +enum ELeaderboardId { + eLeaderboardId_TRAVELLING = 0, + eLeaderboardId_MINING = 1, + eLeaderboardId_FARMING = 2, + eLeaderboardId_KILLING = 3 }; -class DsItemEvent : public Stat -{ +class DsItemEvent : public Stat { public: - static string nameMethods[]; + static string nameMethods[]; - enum eAcquisitionMethod - { - eAcquisitionMethod_None = 0, - - eAcquisitionMethod_Pickedup, - eAcquisitionMethod_Crafted, - eAcquisitionMethod_TakenFromChest, - eAcquisitionMethod_TakenFromEnderchest, - eAcquisitionMethod_Bought, - eAcquisitionMethod_Smithed, - eAcquisitionMethod_Mined, + enum eAcquisitionMethod { + eAcquisitionMethod_None = 0, - eAcquisitionMethod_Placed, - - eAcquisitionMethod_MAX - }; + eAcquisitionMethod_Pickedup, + eAcquisitionMethod_Crafted, + eAcquisitionMethod_TakenFromChest, + eAcquisitionMethod_TakenFromEnderchest, + eAcquisitionMethod_Bought, + eAcquisitionMethod_Smithed, + eAcquisitionMethod_Mined, - typedef struct _Param - { - int methodId, itemId, itemAux, itemCount; - } Param; + eAcquisitionMethod_Placed, - DsItemEvent(int id, const std::wstring &name); + eAcquisitionMethod_MAX + }; - bool onLeaderboard(ELeaderboardId leaderboard, eAcquisitionMethod methodId, Param *param); - int mergeIds(int itemId); + typedef struct _Param { + int methodId, itemId, itemAux, itemCount; + } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray param); - static byteArray createParamBlob(eAcquisitionMethod methodId, int itemId, int itemAux, int itemCount); + DsItemEvent(int id, const std::wstring& name); + + bool onLeaderboard(ELeaderboardId leaderboard, eAcquisitionMethod methodId, + Param* param); + int mergeIds(int itemId); + + virtual void handleParamBlob(std::shared_ptr plr, + byteArray param); + static byteArray createParamBlob(eAcquisitionMethod methodId, int itemId, + int itemAux, int itemCount); }; -class DsMobKilled : public Stat -{ +class DsMobKilled : public Stat { public: - static const bool RANGED = true; - static const bool MELEE = false; + static const bool RANGED = true; + static const bool MELEE = false; - static const int SPIDER_JOCKEY_ID = 49; + static const int SPIDER_JOCKEY_ID = 49; - DsMobKilled(int id, const std::wstring &name); + DsMobKilled(int id, const std::wstring& name); - typedef struct { bool isRanged; int mobType, weaponId, distance, damage; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray param); - static byteArray createParamBlob(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc); + typedef struct { + bool isRanged; + int mobType, weaponId, distance, damage; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray param); + static byteArray createParamBlob(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc); }; -class DsMobInteract : public Stat -{ +class DsMobInteract : public Stat { protected: - static string nameInteract[]; + static string nameInteract[]; public: - enum eInteract - { - eInteract_None = 0, - eInteract_Breed, - eInteract_Tamed, - eInteract_Cured, - eInteract_Crafted, - eInteract_Sheared - }; + enum eInteract { + eInteract_None = 0, + eInteract_Breed, + eInteract_Tamed, + eInteract_Cured, + eInteract_Crafted, + eInteract_Sheared + }; - DsMobInteract(int id, const std::wstring &name); + DsMobInteract(int id, const std::wstring& name); - typedef struct { int interactionType, mobId; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray param); - static byteArray createParamBlob(eInteract interactionId, int entityId); + typedef struct { + int interactionType, mobId; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray param); + static byteArray createParamBlob(eInteract interactionId, int entityId); }; -class DsTravel : public Stat -{ +class DsTravel : public Stat { public: - static string nameMethods[]; + static string nameMethods[]; - enum eMethod { - eMethod_walk, - eMethod_swim, - eMethod_fall, - eMethod_climb, - eMethod_minecart, - eMethod_boat, - eMethod_pig, + enum eMethod { + eMethod_walk, + eMethod_swim, + eMethod_fall, + eMethod_climb, + eMethod_minecart, + eMethod_boat, + eMethod_pig, - eMethod_time, // Time is a dimension too right... + eMethod_time, // Time is a dimension too right... - eMethod_MAX - }; + eMethod_MAX + }; - static unsigned int CACHE_SIZES[eMethod_MAX]; + static unsigned int CACHE_SIZES[eMethod_MAX]; - DsTravel(int id, const std::wstring &name); + DsTravel(int id, const std::wstring& name); - typedef struct { eMethod method; int distance; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray paramBlob); - static byteArray createParamBlob(eMethod method, int distance); + typedef struct { + eMethod method; + int distance; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray paramBlob); + static byteArray createParamBlob(eMethod method, int distance); - void flush(std::shared_ptr plr); + void flush(std::shared_ptr plr); protected: - unsigned int param_cache[MAX_LOCAL_PLAYERS][eMethod_MAX]; - int cache(int iPad, Param ¶m); - void write(std::shared_ptr plr, eMethod method, int distance); + unsigned int param_cache[MAX_LOCAL_PLAYERS][eMethod_MAX]; + int cache(int iPad, Param& param); + void write(std::shared_ptr plr, eMethod method, int distance); }; -class DsItemUsed : public Stat -{ +class DsItemUsed : public Stat { public: - DsItemUsed(int id, const std::wstring &name); - typedef struct { int itemId, aux, count, health, hunger; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray paramBlob); - static byteArray createParamBlob(int itemId, int aux, int count, int health, int hunger); + DsItemUsed(int id, const std::wstring& name); + typedef struct { + int itemId, aux, count, health, hunger; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray paramBlob); + static byteArray createParamBlob(int itemId, int aux, int count, int health, + int hunger); }; -class DsAchievement : public Stat -{ +class DsAchievement : public Stat { public: - DsAchievement(int id, const std::wstring &name); - - virtual void handleParamBlob(std::shared_ptr plr, byteArray paramBlob); + DsAchievement(int id, const std::wstring& name); - typedef struct { eAward award; } SmallParam; - static byteArray createSmallParamBlob(eAward id); + virtual void handleParamBlob(std::shared_ptr plr, + byteArray paramBlob); - typedef struct { eAward award; int count; } LargeParam; - static byteArray createLargeParamBlob(eAward id, int count); + typedef struct { + eAward award; + } SmallParam; + static byteArray createSmallParamBlob(eAward id); + + typedef struct { + eAward award; + int count; + } LargeParam; + static byteArray createLargeParamBlob(eAward id, int count); }; -class DsChangedDimension : public Stat -{ +class DsChangedDimension : public Stat { public: - DsChangedDimension(int id, const std::wstring &name); - typedef struct { int fromDimId, toDimId; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray paramBlob); - static byteArray createParamBlob(int fromDimId, int toDimId); + DsChangedDimension(int id, const std::wstring& name); + typedef struct { + int fromDimId, toDimId; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray paramBlob); + static byteArray createParamBlob(int fromDimId, int toDimId); }; -class DsEnteredBiome : public Stat -{ +class DsEnteredBiome : public Stat { public: - DsEnteredBiome(int id, const std::wstring &name); - typedef struct { int biomeId; } Param; - virtual void handleParamBlob(std::shared_ptr plr, byteArray paramBlob); - static byteArray createParamBlob(int biomeId); + DsEnteredBiome(int id, const std::wstring& name); + typedef struct { + int biomeId; + } Param; + virtual void handleParamBlob(std::shared_ptr plr, + byteArray paramBlob); + static byteArray createParamBlob(int biomeId); }; -class DurangoStats : public GenericStats -{ +class DurangoStats : public GenericStats { public: - static DurangoStats *getInstance() { return (DurangoStats*) GenericStats::getInstance(); } + static DurangoStats* getInstance() { + return (DurangoStats*)GenericStats::getInstance(); + } protected: - enum { - itemsAcquired_Id = 1, - itemUsed_Id, - travel_Id, - mobKilled_Id, - mobInteract_Id, - binAchievement_Id, - binAchievementLocal_Id, - changedDimension_Id, - enteredBiome_Id, - }; + enum { + itemsAcquired_Id = 1, + itemUsed_Id, + travel_Id, + mobKilled_Id, + mobInteract_Id, + binAchievement_Id, + binAchievementLocal_Id, + changedDimension_Id, + enteredBiome_Id, + }; - DsItemEvent *itemsAcquired; - DsTravel *travel; + DsItemEvent* itemsAcquired; + DsTravel* travel; - DsMobKilled *mobKilled; - DsMobInteract *mobInteract; + DsMobKilled* mobKilled; + DsMobInteract* mobInteract; - DsAchievement *achievement; - DsAchievement *achievementLocal; + DsAchievement* achievement; + DsAchievement* achievementLocal; - DsItemUsed *itemUsed; + DsItemUsed* itemUsed; - DsChangedDimension *changedDimension; - DsEnteredBiome *enteredBiome; + DsChangedDimension* changedDimension; + DsEnteredBiome* enteredBiome; - GUID playerSessionId; - Platform::String^ multiplayerCorrelationId; + GUID playerSessionId; + Platform::String ^ multiplayerCorrelationId; public: - DurangoStats(); - ~DurangoStats(); - - virtual Stat *get_stat(int i); + DurangoStats(); + ~DurangoStats(); + virtual Stat* get_stat(int i); protected: - // Stats + // Stats - virtual Stat* get_walkOneM(); - virtual Stat* get_swimOneM(); - virtual Stat* get_fallOneM(); - virtual Stat* get_climbOneM(); - virtual Stat* get_minecartOneM(); - virtual Stat* get_boatOneM(); - virtual Stat* get_pigOneM(); + virtual Stat* get_walkOneM(); + virtual Stat* get_swimOneM(); + virtual Stat* get_fallOneM(); + virtual Stat* get_climbOneM(); + virtual Stat* get_minecartOneM(); + virtual Stat* get_boatOneM(); + virtual Stat* get_pigOneM(); - virtual Stat* get_cowsMilked(); + virtual Stat* get_cowsMilked(); - // Kills. - virtual Stat* get_killMob(); + // Kills. + virtual Stat* get_killMob(); - // Mob-Interactions. - virtual Stat* get_breedEntity(eINSTANCEOF entityId); - virtual Stat* get_tamedEntity(eINSTANCEOF entityId); - virtual Stat* get_curedEntity(eINSTANCEOF entityId); - virtual Stat* get_craftedEntity(eINSTANCEOF entityId); - virtual Stat* get_shearedEntity(eINSTANCEOF entityId); + // Mob-Interactions. + virtual Stat* get_breedEntity(eINSTANCEOF entityId); + virtual Stat* get_tamedEntity(eINSTANCEOF entityId); + virtual Stat* get_curedEntity(eINSTANCEOF entityId); + virtual Stat* get_craftedEntity(eINSTANCEOF entityId); + virtual Stat* get_shearedEntity(eINSTANCEOF entityId); - virtual Stat* get_timePlayed(); + virtual Stat* get_timePlayed(); - virtual Stat* get_blocksPlaced(int blockId); - virtual Stat* get_blocksMined(int blockId); - virtual Stat* get_itemsCollected(int itemId, int itemAux); - virtual Stat* get_itemsCrafted(int itemId); - virtual Stat* get_itemsSmelted(int itemId); - virtual Stat* get_itemsUsed(int itemId); - virtual Stat* get_itemsBought(int itemId); + virtual Stat* get_blocksPlaced(int blockId); + virtual Stat* get_blocksMined(int blockId); + virtual Stat* get_itemsCollected(int itemId, int itemAux); + virtual Stat* get_itemsCrafted(int itemId); + virtual Stat* get_itemsSmelted(int itemId); + virtual Stat* get_itemsUsed(int itemId); + virtual Stat* get_itemsBought(int itemId); - virtual Stat* get_changedDimension(int from, int to); - virtual Stat* get_enteredBiome(int biomeId); + virtual Stat* get_changedDimension(int from, int to); + virtual Stat* get_enteredBiome(int biomeId); - // Achievements + // Achievements - virtual Stat* get_achievement(eAward achievementId); + virtual Stat* get_achievement(eAward achievementId); + // Parameters - // Parameters + virtual byteArray getParam_walkOneM(int distance); + virtual byteArray getParam_swimOneM(int distance); + virtual byteArray getParam_fallOneM(int distance); + virtual byteArray getParam_climbOneM(int distance); + virtual byteArray getParam_minecartOneM(int distance); + virtual byteArray getParam_boatOneM(int distance); + virtual byteArray getParam_pigOneM(int distance); - virtual byteArray getParam_walkOneM(int distance); - virtual byteArray getParam_swimOneM(int distance); - virtual byteArray getParam_fallOneM(int distance); - virtual byteArray getParam_climbOneM(int distance); - virtual byteArray getParam_minecartOneM(int distance); - virtual byteArray getParam_boatOneM(int distance); - virtual byteArray getParam_pigOneM(int distance); + virtual byteArray getParam_cowsMilked(); - virtual byteArray getParam_cowsMilked(); + virtual byteArray getParam_blocksPlaced(int blockId, int data, int count); + virtual byteArray getParam_blocksMined(int blockId, int data, int count); + virtual byteArray getParam_itemsCollected(int id, int aux, int count); + virtual byteArray getParam_itemsCrafted(int id, int aux, int count); + virtual byteArray getParam_itemsUsed(std::shared_ptr plr, + std::shared_ptr itm); + virtual byteArray getParam_itemsBought(int id, int aux, int count); - virtual byteArray getParam_blocksPlaced(int blockId, int data, int count); - virtual byteArray getParam_blocksMined(int blockId, int data, int count); - virtual byteArray getParam_itemsCollected(int id, int aux, int count); - virtual byteArray getParam_itemsCrafted(int id, int aux, int count); - virtual byteArray getParam_itemsUsed(std::shared_ptr plr, std::shared_ptr itm); - virtual byteArray getParam_itemsBought(int id, int aux, int count); + virtual byteArray getParam_mobKill(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc); - virtual byteArray getParam_mobKill(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc); + virtual byteArray getParam_breedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_tamedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_curedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_craftedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_shearedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_breedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_tamedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_curedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_craftedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_shearedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_time(int timediff); - virtual byteArray getParam_time(int timediff); + virtual byteArray getParam_changedDimension(int from, int to); + virtual byteArray getParam_enteredBiome(int biomeId); - virtual byteArray getParam_changedDimension(int from, int to); - virtual byteArray getParam_enteredBiome(int biomeId); + virtual byteArray getParam_achievement(eAward id); - virtual byteArray getParam_achievement(eAward id); + virtual byteArray getParam_onARail(int dist); + virtual byteArray getParam_chestfulOfCobblestone(int count); + // virtual byteArray getParam_openInventory( + virtual byteArray getParam_overkill(int dmg); + virtual byteArray getParam_musicToMyEars(int recordId); - virtual byteArray getParam_onARail(int dist); - virtual byteArray getParam_chestfulOfCobblestone(int count); - // virtual byteArray getParam_openInventory( - virtual byteArray getParam_overkill(int dmg); - virtual byteArray getParam_musicToMyEars(int recordId); - - // Helpers + // Helpers public: - // Achievements that have no parameters, you have earned them or not. - static bool binaryAchievement(eAward achievementId); + // Achievements that have no parameters, you have earned them or not. + static bool binaryAchievement(eAward achievementId); - // Achievements that have parameters, but the event is specifically for this achievement. - static bool enhancedAchievement(eAward achievementId); + // Achievements that have parameters, but the event is specifically for this + // achievement. + static bool enhancedAchievement(eAward achievementId); - static void generatePlayerSession(); - static LPCGUID getPlayerSession(); + static void generatePlayerSession(); + static LPCGUID getPlayerSession(); - static void setMultiplayerCorrelationId(Platform::String^ mpcId); - static LPCWSTR getMultiplayerCorrelationId(); + static void setMultiplayerCorrelationId(Platform::String ^ mpcId); + static LPCWSTR getMultiplayerCorrelationId(); - static LPCWSTR getUserId(std::shared_ptr plr); - static LPCWSTR getUserId(int iPad); + static LPCWSTR getUserId(std::shared_ptr plr); + static LPCWSTR getUserId(int iPad); - static void playerSessionStart(PlayerUID,std::shared_ptr); - static void playerSessionStart(int iPad); - static void playerSessionPause(int iPad); - static void playerSessionResume(int iPad); - static void playerSessionEnd(int iPad); + static void playerSessionStart(PlayerUID, std::shared_ptr); + static void playerSessionStart(int iPad); + static void playerSessionPause(int iPad); + static void playerSessionResume(int iPad); + static void playerSessionEnd(int iPad); }; \ No newline at end of file diff --git a/Minecraft.World/Stats/GeneralStat.cpp b/Minecraft.World/Stats/GeneralStat.cpp index 849933677..ce1d767ac 100644 --- a/Minecraft.World/Stats/GeneralStat.cpp +++ b/Minecraft.World/Stats/GeneralStat.cpp @@ -2,16 +2,13 @@ #include "../Headers/net.minecraft.stats.h" #include "GeneralStat.h" -GeneralStat::GeneralStat(int id, const std::wstring& name, StatFormatter *formatter) : Stat(id, name, formatter) -{ -} +GeneralStat::GeneralStat(int id, const std::wstring& name, + StatFormatter* formatter) + : Stat(id, name, formatter) {} -GeneralStat::GeneralStat(int id, const std::wstring& name) : Stat(id, name) -{ -} +GeneralStat::GeneralStat(int id, const std::wstring& name) : Stat(id, name) {} -Stat *GeneralStat::postConstruct() -{ +Stat* GeneralStat::postConstruct() { Stat::postConstruct(); Stats::generalStats->push_back(this); return this; diff --git a/Minecraft.World/Stats/GeneralStat.h b/Minecraft.World/Stats/GeneralStat.h index 117ba2ec8..6f51072aa 100644 --- a/Minecraft.World/Stats/GeneralStat.h +++ b/Minecraft.World/Stats/GeneralStat.h @@ -1,12 +1,10 @@ #pragma once - #include "Stat.h" -class GeneralStat : public Stat -{ +class GeneralStat : public Stat { public: - GeneralStat(int id, const std::wstring& name, StatFormatter *formatter); - GeneralStat(int id, const std::wstring& name); - Stat *postConstruct(); + GeneralStat(int id, const std::wstring& name, StatFormatter* formatter); + GeneralStat(int id, const std::wstring& name); + Stat* postConstruct(); }; diff --git a/Minecraft.World/Stats/GenericStats.cpp b/Minecraft.World/Stats/GenericStats.cpp index 51a28daad..87396f522 100644 --- a/Minecraft.World/Stats/GenericStats.cpp +++ b/Minecraft.World/Stats/GenericStats.cpp @@ -4,1281 +4,1004 @@ #include "GenericStats.h" -GenericStats *GenericStats::instance = NULL; +GenericStats* GenericStats::instance = NULL; -Stat* GenericStats::get_walkOneM() -{ - return NULL; +Stat* GenericStats::get_walkOneM() { return NULL; } + +Stat* GenericStats::get_swimOneM() { return NULL; } + +Stat* GenericStats::get_fallOneM() { return NULL; } + +Stat* GenericStats::get_climbOneM() { return NULL; } + +Stat* GenericStats::get_minecartOneM() { return NULL; } + +Stat* GenericStats::get_boatOneM() { return NULL; } + +Stat* GenericStats::get_pigOneM() { return NULL; } + +Stat* GenericStats::get_portalsCreated() { return NULL; } + +Stat* GenericStats::get_cowsMilked() { return NULL; } + +Stat* GenericStats::get_netherLavaCollected() { return NULL; } + +Stat* GenericStats::get_killMob() { return NULL; } + +Stat* GenericStats::get_killsZombie() { return NULL; } + +Stat* GenericStats::get_killsSkeleton() { return NULL; } + +Stat* GenericStats::get_killsCreeper() { return NULL; } + +Stat* GenericStats::get_killsSpider() { return NULL; } + +Stat* GenericStats::get_killsSpiderJockey() { return NULL; } + +Stat* GenericStats::get_killsZombiePigman() { return NULL; } + +Stat* GenericStats::get_killsSlime() { return NULL; } + +Stat* GenericStats::get_killsGhast() { return NULL; } + +Stat* GenericStats::get_killsNetherZombiePigman() { return NULL; } + +Stat* GenericStats::get_breedEntity(eINSTANCEOF entityId) { return NULL; } + +Stat* GenericStats::get_tamedEntity(eINSTANCEOF entityId) { return NULL; } + +Stat* GenericStats::get_curedEntity(eINSTANCEOF entityId) { return NULL; } + +Stat* GenericStats::get_craftedEntity(eINSTANCEOF entityId) { return NULL; } + +Stat* GenericStats::get_shearedEntity(eINSTANCEOF entityId) { return NULL; } + +Stat* GenericStats::get_totalBlocksMined() { return NULL; } + +Stat* GenericStats::get_timePlayed() { return NULL; } + +Stat* GenericStats::get_blocksPlaced(int blockId) { return NULL; } + +Stat* GenericStats::get_blocksMined(int blockId) { return NULL; } + +Stat* GenericStats::get_itemsCollected(int itemId, int itemAux) { return NULL; } + +Stat* GenericStats::get_itemsCrafted(int itemId) { return NULL; } + +Stat* GenericStats::get_itemsSmelted(int itemId) { + return this->get_itemsCrafted(itemId); } -Stat* GenericStats::get_swimOneM() -{ - return NULL; +Stat* GenericStats::get_itemsUsed(int itemId) { return NULL; } + +Stat* GenericStats::get_itemsBought(int itemId) { return NULL; } + +Stat* GenericStats::get_killsEnderdragon() { return NULL; } + +Stat* GenericStats::get_completeTheEnd() { return NULL; } + +Stat* GenericStats::get_changedDimension(int from, int to) { return NULL; } + +Stat* GenericStats::get_enteredBiome(int biomeId) { return NULL; } + +Stat* GenericStats::get_achievement(eAward achievementId) { return NULL; } + +Stat* GenericStats::openInventory() { + return instance->get_achievement(eAward_TakingInventory); } -Stat* GenericStats::get_fallOneM() -{ - return NULL; +Stat* GenericStats::mineWood() { + return instance->get_achievement(eAward_GettingWood); } -Stat* GenericStats::get_climbOneM() -{ - return NULL; +Stat* GenericStats::buildWorkbench() { + return instance->get_achievement(eAward_Benchmarking); } -Stat* GenericStats::get_minecartOneM() -{ - return NULL; +Stat* GenericStats::buildPickaxe() { + return instance->get_achievement(eAward_TimeToMine); } -Stat* GenericStats::get_boatOneM() -{ - return NULL; +Stat* GenericStats::buildFurnace() { + return instance->get_achievement(eAward_HotTopic); } -Stat* GenericStats::get_pigOneM() -{ - return NULL; +Stat* GenericStats::acquireIron() { + return instance->get_achievement(eAward_AquireHardware); } -Stat* GenericStats::get_portalsCreated() -{ - return NULL; +Stat* GenericStats::buildHoe() { + return instance->get_achievement(eAward_TimeToFarm); } -Stat* GenericStats::get_cowsMilked() -{ - return NULL; +Stat* GenericStats::makeBread() { + return instance->get_achievement(eAward_BakeBread); } -Stat* GenericStats::get_netherLavaCollected() -{ - return NULL; +Stat* GenericStats::bakeCake() { + return instance->get_achievement(eAward_TheLie); } -Stat* GenericStats::get_killMob() -{ - return NULL; +Stat* GenericStats::buildBetterPickaxe() { + return instance->get_achievement(eAward_GettingAnUpgrade); } -Stat* GenericStats::get_killsZombie() -{ - return NULL; +Stat* GenericStats::cookFish() { + return instance->get_achievement(eAward_DeliciousFish); } -Stat* GenericStats::get_killsSkeleton() -{ - return NULL; +Stat* GenericStats::onARail() { + return instance->get_achievement(eAward_OnARail); } -Stat* GenericStats::get_killsCreeper() -{ - return NULL; +Stat* GenericStats::buildSword() { + return instance->get_achievement(eAward_TimeToStrike); } -Stat* GenericStats::get_killsSpider() -{ - return NULL; +Stat* GenericStats::killEnemy() { + return instance->get_achievement(eAward_MonsterHunter); } -Stat* GenericStats::get_killsSpiderJockey() -{ - return NULL; +Stat* GenericStats::killCow() { + return instance->get_achievement(eAward_CowTipper); } -Stat* GenericStats::get_killsZombiePigman() -{ - return NULL; +Stat* GenericStats::flyPig() { + return instance->get_achievement(eAward_WhenPigsFly); } -Stat* GenericStats::get_killsSlime() -{ - return NULL; -} - -Stat* GenericStats::get_killsGhast() -{ - return NULL; -} - -Stat* GenericStats::get_killsNetherZombiePigman() -{ - return NULL; -} - -Stat* GenericStats::get_breedEntity(eINSTANCEOF entityId) -{ - return NULL; -} - -Stat* GenericStats::get_tamedEntity(eINSTANCEOF entityId) -{ - return NULL; -} - -Stat* GenericStats::get_curedEntity(eINSTANCEOF entityId) -{ - return NULL; -} - -Stat* GenericStats::get_craftedEntity(eINSTANCEOF entityId) -{ - return NULL; -} - -Stat* GenericStats::get_shearedEntity(eINSTANCEOF entityId) -{ - return NULL; -} - -Stat* GenericStats::get_totalBlocksMined() -{ - return NULL; -} - -Stat* GenericStats::get_timePlayed() -{ - return NULL; -} - -Stat* GenericStats::get_blocksPlaced(int blockId) -{ - return NULL; -} - -Stat* GenericStats::get_blocksMined(int blockId) -{ - return NULL; -} - -Stat* GenericStats::get_itemsCollected(int itemId, int itemAux) -{ - return NULL; -} - -Stat* GenericStats::get_itemsCrafted(int itemId) -{ - return NULL; -} - -Stat* GenericStats::get_itemsSmelted(int itemId) -{ - return this->get_itemsCrafted(itemId); -} - -Stat* GenericStats::get_itemsUsed(int itemId) -{ - return NULL; -} - -Stat *GenericStats::get_itemsBought(int itemId) -{ - return NULL; -} - -Stat* GenericStats::get_killsEnderdragon() -{ - return NULL; -} - -Stat* GenericStats::get_completeTheEnd() -{ - return NULL; -} - -Stat* GenericStats::get_changedDimension(int from, int to) -{ - return NULL; -} - -Stat* GenericStats::get_enteredBiome(int biomeId) -{ - return NULL; -} - -Stat* GenericStats::get_achievement(eAward achievementId) -{ - return NULL; -} - -Stat* GenericStats::openInventory() -{ - return instance->get_achievement( eAward_TakingInventory ); -} - -Stat* GenericStats::mineWood() -{ - return instance->get_achievement( eAward_GettingWood ); -} - -Stat* GenericStats::buildWorkbench() -{ - return instance->get_achievement( eAward_Benchmarking ); -} - -Stat* GenericStats::buildPickaxe() -{ - return instance->get_achievement( eAward_TimeToMine); -} - -Stat* GenericStats::buildFurnace() -{ - return instance->get_achievement( eAward_HotTopic ); -} - -Stat* GenericStats::acquireIron() -{ - return instance->get_achievement( eAward_AquireHardware ); -} - -Stat* GenericStats::buildHoe() -{ - return instance->get_achievement( eAward_TimeToFarm ); -} - -Stat* GenericStats::makeBread() -{ - return instance->get_achievement( eAward_BakeBread ); -} - -Stat* GenericStats::bakeCake() -{ - return instance->get_achievement( eAward_TheLie ); -} - -Stat* GenericStats::buildBetterPickaxe() -{ - return instance->get_achievement( eAward_GettingAnUpgrade ); -} - -Stat* GenericStats::cookFish() -{ - return instance->get_achievement( eAward_DeliciousFish ); -} - -Stat* GenericStats::onARail() -{ - return instance->get_achievement( eAward_OnARail ); -} - -Stat* GenericStats::buildSword() -{ - return instance->get_achievement( eAward_TimeToStrike ); -} - -Stat* GenericStats::killEnemy() -{ - return instance->get_achievement( eAward_MonsterHunter ); -} - -Stat* GenericStats::killCow() -{ - return instance->get_achievement( eAward_CowTipper ); -} - -Stat* GenericStats::flyPig() -{ - return instance->get_achievement( eAward_WhenPigsFly ); -} - -Stat* GenericStats::snipeSkeleton() -{ +Stat* GenericStats::snipeSkeleton() { #ifndef _XBOX - return instance->get_achievement( eAward_snipeSkeleton ); + return instance->get_achievement(eAward_snipeSkeleton); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::diamonds() -{ +Stat* GenericStats::diamonds() { #ifndef _XBOX - return instance->get_achievement( eAward_diamonds ); + return instance->get_achievement(eAward_diamonds); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::ghast() -{ +Stat* GenericStats::ghast() { #ifndef _XBOX - return instance->get_achievement( eAward_ghast ); + return instance->get_achievement(eAward_ghast); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::blazeRod() -{ +Stat* GenericStats::blazeRod() { #ifndef _XBOX - return instance->get_achievement( eAward_blazeRod ); + return instance->get_achievement(eAward_blazeRod); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::potion() -{ +Stat* GenericStats::potion() { #ifndef _XBOX - return instance->get_achievement( eAward_potion ); + return instance->get_achievement(eAward_potion); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::theEnd() -{ +Stat* GenericStats::theEnd() { #ifndef _XBOX - return instance->get_achievement( eAward_theEnd ); + return instance->get_achievement(eAward_theEnd); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::winGame() -{ +Stat* GenericStats::winGame() { #ifndef _XBOX - return instance->get_achievement( eAward_winGame ); + return instance->get_achievement(eAward_winGame); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::enchantments() -{ +Stat* GenericStats::enchantments() { #ifndef _XBOX - return instance->get_achievement( eAward_enchantments ); + return instance->get_achievement(eAward_enchantments); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::overkill() -{ +Stat* GenericStats::overkill() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement( eAward_overkill ); + return instance->get_achievement(eAward_overkill); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::bookcase() -{ +Stat* GenericStats::bookcase() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement( eAward_bookcase ); + return instance->get_achievement(eAward_bookcase); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::leaderOfThePack() -{ - return instance->get_achievement( eAward_LeaderOfThePack ); +Stat* GenericStats::leaderOfThePack() { + return instance->get_achievement(eAward_LeaderOfThePack); } -Stat* GenericStats::MOARTools() -{ - return instance->get_achievement( eAward_MOARTools ); +Stat* GenericStats::MOARTools() { + return instance->get_achievement(eAward_MOARTools); } -Stat* GenericStats::dispenseWithThis() -{ - return instance->get_achievement( eAward_DispenseWithThis ); +Stat* GenericStats::dispenseWithThis() { + return instance->get_achievement(eAward_DispenseWithThis); } -Stat* GenericStats::InToTheNether() -{ - return instance->get_achievement( eAward_InToTheNether ); +Stat* GenericStats::InToTheNether() { + return instance->get_achievement(eAward_InToTheNether); } -Stat* GenericStats::socialPost() -{ - return instance->get_achievement( eAward_socialPost ); +Stat* GenericStats::socialPost() { + return instance->get_achievement(eAward_socialPost); } -Stat* GenericStats::eatPorkChop() -{ - return instance->get_achievement( eAward_eatPorkChop ); +Stat* GenericStats::eatPorkChop() { + return instance->get_achievement(eAward_eatPorkChop); } -Stat* GenericStats::play100Days() -{ - return instance->get_achievement( eAward_play100Days ); +Stat* GenericStats::play100Days() { + return instance->get_achievement(eAward_play100Days); } -Stat* GenericStats::arrowKillCreeper() -{ - return instance->get_achievement( eAward_arrowKillCreeper ); +Stat* GenericStats::arrowKillCreeper() { + return instance->get_achievement(eAward_arrowKillCreeper); } -Stat* GenericStats::mine100Blocks() -{ - return instance->get_achievement( eAward_mine100Blocks ); +Stat* GenericStats::mine100Blocks() { + return instance->get_achievement(eAward_mine100Blocks); } -Stat* GenericStats::kill10Creepers() -{ - return instance->get_achievement( eAward_kill10Creepers ); +Stat* GenericStats::kill10Creepers() { + return instance->get_achievement(eAward_kill10Creepers); } -Stat* GenericStats::adventuringTime() -{ +Stat* GenericStats::adventuringTime() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_adventuringTime); + return instance->get_achievement(eAward_adventuringTime); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::repopulation() -{ +Stat* GenericStats::repopulation() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_repopulation); + return instance->get_achievement(eAward_repopulation); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::porkChop() -{ +Stat* GenericStats::porkChop() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_eatPorkChop); + return instance->get_achievement(eAward_eatPorkChop); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::diamondsToYou() -{ +Stat* GenericStats::diamondsToYou() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_diamondsToYou); + return instance->get_achievement(eAward_diamondsToYou); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::passingTheTime() -{ +Stat* GenericStats::passingTheTime() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_play100Days); + return instance->get_achievement(eAward_play100Days); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::archer() -{ +Stat* GenericStats::archer() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_arrowKillCreeper); + return instance->get_achievement(eAward_arrowKillCreeper); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::theHaggler() -{ +Stat* GenericStats::theHaggler() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_theHaggler); + return instance->get_achievement(eAward_theHaggler); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::potPlanter() -{ +Stat* GenericStats::potPlanter() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_potPlanter); + return instance->get_achievement(eAward_potPlanter); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::itsASign() -{ +Stat* GenericStats::itsASign() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_itsASign); + return instance->get_achievement(eAward_itsASign); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::ironBelly() -{ +Stat* GenericStats::ironBelly() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_ironBelly); + return instance->get_achievement(eAward_ironBelly); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::haveAShearfulDay() -{ +Stat* GenericStats::haveAShearfulDay() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_haveAShearfulDay); + return instance->get_achievement(eAward_haveAShearfulDay); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::rainbowCollection() -{ +Stat* GenericStats::rainbowCollection() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_rainbowCollection); + return instance->get_achievement(eAward_rainbowCollection); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::stayinFrosty() -{ +Stat* GenericStats::stayinFrosty() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_stayinFrosty); + return instance->get_achievement(eAward_stayinFrosty); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::chestfulOfCobblestone() -{ +Stat* GenericStats::chestfulOfCobblestone() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_chestfulOfCobblestone); + return instance->get_achievement(eAward_chestfulOfCobblestone); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::renewableEnergy() -{ +Stat* GenericStats::renewableEnergy() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_renewableEnergy); + return instance->get_achievement(eAward_renewableEnergy); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::musicToMyEars() -{ +Stat* GenericStats::musicToMyEars() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_musicToMyEars); + return instance->get_achievement(eAward_musicToMyEars); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::bodyGuard() -{ +Stat* GenericStats::bodyGuard() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_bodyGuard); + return instance->get_achievement(eAward_bodyGuard); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::ironMan() -{ +Stat* GenericStats::ironMan() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_ironMan); + return instance->get_achievement(eAward_ironMan); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::zombieDoctor() -{ +Stat* GenericStats::zombieDoctor() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_zombieDoctor); + return instance->get_achievement(eAward_zombieDoctor); #else - return NULL; + return NULL; #endif } -Stat* GenericStats::lionTamer() -{ +Stat* GenericStats::lionTamer() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->get_achievement(eAward_lionTamer); + return instance->get_achievement(eAward_lionTamer); #else - return NULL; + return NULL; #endif } -byteArray GenericStats::getParam_walkOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_walkOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_swimOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_swimOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_fallOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_fallOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_climbOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_climbOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_minecartOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_minecartOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_boatOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_boatOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_pigOneM(int distance) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_pigOneM(int distance) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_cowsMilked() -{ - return getParam_noArgs(); +byteArray GenericStats::getParam_cowsMilked() { return getParam_noArgs(); } + +byteArray GenericStats::getParam_blocksPlaced(int id, int data, int count) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_blocksPlaced(int id, int data, int count) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_blocksMined(int id, int data, int count) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_blocksMined(int id, int data, int count) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_itemsCollected(int id, int aux, int count) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_itemsCollected(int id, int aux, int count) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_itemsCrafted(int id, int aux, int count) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_itemsCrafted(int id, int aux, int count) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_itemsSmelted(int id, int aux, int count) { + return this->getParam_itemsCrafted(id, aux, count); } -byteArray GenericStats::getParam_itemsSmelted(int id, int aux, int count) -{ - return this->getParam_itemsCrafted(id,aux,count); +byteArray GenericStats::getParam_itemsUsed(std::shared_ptr plr, + std::shared_ptr itm) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_itemsUsed(std::shared_ptr plr, std::shared_ptr itm) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_itemsBought(int id, int aux, int count) { + return getParam_noArgs(); } -byteArray GenericStats::getParam_itemsBought(int id, int aux, int count) -{ - return getParam_noArgs(); +byteArray GenericStats::getParam_mobKill(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_mobKill(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_breedEntity(eINSTANCEOF entityId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_breedEntity(eINSTANCEOF entityId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_tamedEntity(eINSTANCEOF entityId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_tamedEntity(eINSTANCEOF entityId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_curedEntity(eINSTANCEOF entityId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_curedEntity(eINSTANCEOF entityId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_craftedEntity(eINSTANCEOF entityId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_craftedEntity(eINSTANCEOF entityId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_shearedEntity(eINSTANCEOF entityId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_shearedEntity(eINSTANCEOF entityId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_time(int timediff) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_time(int timediff) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_changedDimension(int from, int to) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_changedDimension(int from, int to) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_enteredBiome(int biomeId) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_enteredBiome(int biomeId) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_achievement(eAward id) { + return getParam_noArgs(); // Really just a count on most platforms. } -byteArray GenericStats::getParam_achievement(eAward id) -{ - return getParam_noArgs(); // Really just a count on most platforms. +byteArray GenericStats::getParam_onARail(int distance) { + return getParam_achievement(eAward_OnARail); } -byteArray GenericStats::getParam_onARail(int distance) -{ - return getParam_achievement(eAward_OnARail); -} - -byteArray GenericStats::getParam_overkill(int damage) -{ +byteArray GenericStats::getParam_overkill(int damage) { #ifdef _XBOX - return getParam_noArgs(); + return getParam_noArgs(); #else - return getParam_achievement(eAward_overkill); + return getParam_achievement(eAward_overkill); #endif } -byteArray GenericStats::getParam_openInventory(int menuId) -{ - return getParam_achievement(eAward_TakingInventory); +byteArray GenericStats::getParam_openInventory(int menuId) { + return getParam_achievement(eAward_TakingInventory); } -byteArray GenericStats::getParam_chestfulOfCobblestone(int cobbleStone) -{ +byteArray GenericStats::getParam_chestfulOfCobblestone(int cobbleStone) { #ifdef _EXTENDED_ACHIEVEMENTS - return getParam_achievement(eAward_chestfulOfCobblestone); + return getParam_achievement(eAward_chestfulOfCobblestone); #else - return getParam_noArgs(); + return getParam_noArgs(); #endif } -byteArray GenericStats::getParam_musicToMyEars(int recordId) -{ +byteArray GenericStats::getParam_musicToMyEars(int recordId) { #ifdef _EXTENDED_ACHIEVEMENTS - return getParam_achievement(eAward_musicToMyEars); + return getParam_achievement(eAward_musicToMyEars); #else - return getParam_noArgs(); + return getParam_noArgs(); #endif } -byteArray GenericStats::getParam_noArgs() -{ - return byteArray(); // TODO +byteArray GenericStats::getParam_noArgs() { + return byteArray(); // TODO } -byteArray GenericStats::param_walk(int distance) -{ - return instance->getParam_walkOneM(distance); +byteArray GenericStats::param_walk(int distance) { + return instance->getParam_walkOneM(distance); } -byteArray GenericStats::param_swim(int distance) -{ - return instance->getParam_swimOneM(distance); +byteArray GenericStats::param_swim(int distance) { + return instance->getParam_swimOneM(distance); } -byteArray GenericStats::param_fall(int distance) -{ - return instance->getParam_fallOneM(distance); +byteArray GenericStats::param_fall(int distance) { + return instance->getParam_fallOneM(distance); } -byteArray GenericStats::param_climb(int distance) -{ - return instance->getParam_climbOneM(distance); +byteArray GenericStats::param_climb(int distance) { + return instance->getParam_climbOneM(distance); } -byteArray GenericStats::param_minecart(int distance) -{ - return instance->getParam_minecartOneM(distance); +byteArray GenericStats::param_minecart(int distance) { + return instance->getParam_minecartOneM(distance); } -byteArray GenericStats::param_boat(int distance) -{ - return instance->getParam_boatOneM(distance); +byteArray GenericStats::param_boat(int distance) { + return instance->getParam_boatOneM(distance); } -byteArray GenericStats::param_pig(int distance) -{ - return instance->getParam_pigOneM(distance); +byteArray GenericStats::param_pig(int distance) { + return instance->getParam_pigOneM(distance); } -byteArray GenericStats::param_cowsMilked() -{ - return instance->getParam_cowsMilked(); +byteArray GenericStats::param_cowsMilked() { + return instance->getParam_cowsMilked(); } -byteArray GenericStats::param_blocksPlaced(int id, int data, int count) -{ - return instance->getParam_blocksPlaced(id,data,count); +byteArray GenericStats::param_blocksPlaced(int id, int data, int count) { + return instance->getParam_blocksPlaced(id, data, count); } -byteArray GenericStats::param_blocksMined(int id, int data, int count) -{ - return instance->getParam_blocksMined(id,data,count); +byteArray GenericStats::param_blocksMined(int id, int data, int count) { + return instance->getParam_blocksMined(id, data, count); } -byteArray GenericStats::param_itemsCollected(int id, int aux, int count) -{ - return instance->getParam_itemsCollected(id,aux,count); +byteArray GenericStats::param_itemsCollected(int id, int aux, int count) { + return instance->getParam_itemsCollected(id, aux, count); } -byteArray GenericStats::param_itemsCrafted(int id, int aux, int count) -{ - return instance->getParam_itemsCrafted(id,aux,count); +byteArray GenericStats::param_itemsCrafted(int id, int aux, int count) { + return instance->getParam_itemsCrafted(id, aux, count); } -byteArray GenericStats::param_itemsSmelted(int id, int aux, int count) -{ - return instance->getParam_itemsSmelted(id,aux,count); +byteArray GenericStats::param_itemsSmelted(int id, int aux, int count) { + return instance->getParam_itemsSmelted(id, aux, count); } -byteArray GenericStats::param_itemsUsed(std::shared_ptr plr, std::shared_ptr itm) -{ - if ( (plr != NULL) && (itm != NULL) ) return instance->getParam_itemsUsed(plr, itm); - else return instance->getParam_noArgs(); +byteArray GenericStats::param_itemsUsed(std::shared_ptr plr, + std::shared_ptr itm) { + if ((plr != NULL) && (itm != NULL)) + return instance->getParam_itemsUsed(plr, itm); + else + return instance->getParam_noArgs(); } -byteArray GenericStats::param_itemsBought(int id, int aux, int count) -{ - return instance->getParam_itemsBought(id,aux,count); +byteArray GenericStats::param_itemsBought(int id, int aux, int count) { + return instance->getParam_itemsBought(id, aux, count); } -byteArray GenericStats::param_mobKill(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc) -{ - if ( (plr != NULL) && (mob != NULL) ) return instance->getParam_mobKill(plr, mob, dmgSrc); - else return instance->getParam_noArgs(); +byteArray GenericStats::param_mobKill(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc) { + if ((plr != NULL) && (mob != NULL)) + return instance->getParam_mobKill(plr, mob, dmgSrc); + else + return instance->getParam_noArgs(); } -byteArray GenericStats::param_breedEntity(eINSTANCEOF entityId) -{ - return instance->getParam_breedEntity(entityId); +byteArray GenericStats::param_breedEntity(eINSTANCEOF entityId) { + return instance->getParam_breedEntity(entityId); } -byteArray GenericStats::param_tamedEntity(eINSTANCEOF entityId) -{ - return instance->getParam_tamedEntity(entityId); +byteArray GenericStats::param_tamedEntity(eINSTANCEOF entityId) { + return instance->getParam_tamedEntity(entityId); } -byteArray GenericStats::param_curedEntity(eINSTANCEOF entityId) -{ - return instance->getParam_curedEntity(entityId); +byteArray GenericStats::param_curedEntity(eINSTANCEOF entityId) { + return instance->getParam_curedEntity(entityId); } -byteArray GenericStats::param_craftedEntity(eINSTANCEOF entityId) -{ - return instance->getParam_craftedEntity(entityId); +byteArray GenericStats::param_craftedEntity(eINSTANCEOF entityId) { + return instance->getParam_craftedEntity(entityId); } -byteArray GenericStats::param_shearedEntity(eINSTANCEOF entityId) -{ - return instance->getParam_shearedEntity(entityId); +byteArray GenericStats::param_shearedEntity(eINSTANCEOF entityId) { + return instance->getParam_shearedEntity(entityId); } -byteArray GenericStats::param_time(int timediff) -{ - return instance->getParam_time(timediff); +byteArray GenericStats::param_time(int timediff) { + return instance->getParam_time(timediff); } -byteArray GenericStats::param_changedDimension(int from, int to) -{ - return instance->getParam_changedDimension(from,to); +byteArray GenericStats::param_changedDimension(int from, int to) { + return instance->getParam_changedDimension(from, to); } -byteArray GenericStats::param_enteredBiome(int biomeId) -{ - return instance->getParam_enteredBiome(biomeId); +byteArray GenericStats::param_enteredBiome(int biomeId) { + return instance->getParam_enteredBiome(biomeId); } -byteArray GenericStats::param_noArgs() -{ - return instance->getParam_noArgs(); +byteArray GenericStats::param_noArgs() { return instance->getParam_noArgs(); } + +byteArray GenericStats::param_openInventory() { + return instance->getParam_achievement(eAward_TakingInventory); } -byteArray GenericStats::param_openInventory() -{ - return instance->getParam_achievement(eAward_TakingInventory); +byteArray GenericStats::param_mineWood() { + return instance->getParam_achievement(eAward_GettingWood); } -byteArray GenericStats::param_mineWood() -{ - return instance->getParam_achievement(eAward_GettingWood); +byteArray GenericStats::param_buildWorkbench() { + return instance->getParam_achievement(eAward_Benchmarking); } -byteArray GenericStats::param_buildWorkbench() -{ - return instance->getParam_achievement(eAward_Benchmarking); +byteArray GenericStats::param_buildPickaxe() { + return instance->getParam_achievement(eAward_TimeToMine); } -byteArray GenericStats::param_buildPickaxe() -{ - return instance->getParam_achievement(eAward_TimeToMine); +byteArray GenericStats::param_buildFurnace() { + return instance->getParam_achievement(eAward_HotTopic); } -byteArray GenericStats::param_buildFurnace() -{ - return instance->getParam_achievement(eAward_HotTopic); +byteArray GenericStats::param_acquireIron() { + return instance->getParam_achievement(eAward_AquireHardware); } -byteArray GenericStats::param_acquireIron() -{ - return instance->getParam_achievement(eAward_AquireHardware); +byteArray GenericStats::param_buildHoe() { + return instance->getParam_achievement(eAward_TimeToFarm); } -byteArray GenericStats::param_buildHoe() -{ - return instance->getParam_achievement(eAward_TimeToFarm); +byteArray GenericStats::param_makeBread() { + return instance->getParam_achievement(eAward_BakeBread); } -byteArray GenericStats::param_makeBread() -{ - return instance->getParam_achievement(eAward_BakeBread); +byteArray GenericStats::param_bakeCake() { + return instance->getParam_achievement(eAward_TheLie); } -byteArray GenericStats::param_bakeCake() -{ - return instance->getParam_achievement(eAward_TheLie); +byteArray GenericStats::param_buildBetterPickaxe() { + return instance->getParam_achievement(eAward_GettingAnUpgrade); } -byteArray GenericStats::param_buildBetterPickaxe() -{ - return instance->getParam_achievement(eAward_GettingAnUpgrade); +byteArray GenericStats::param_cookFish() { + return instance->getParam_achievement(eAward_DeliciousFish); } -byteArray GenericStats::param_cookFish() -{ - return instance->getParam_achievement(eAward_DeliciousFish); +byteArray GenericStats::param_onARail(int distance) { + return instance->getParam_onARail(distance); } -byteArray GenericStats::param_onARail(int distance) -{ - return instance->getParam_onARail(distance); +byteArray GenericStats::param_buildSword() { + return instance->getParam_achievement(eAward_TimeToStrike); } -byteArray GenericStats::param_buildSword() -{ - return instance->getParam_achievement(eAward_TimeToStrike); +byteArray GenericStats::param_killEnemy() { + return instance->getParam_achievement(eAward_MonsterHunter); } -byteArray GenericStats::param_killEnemy() -{ - return instance->getParam_achievement(eAward_MonsterHunter); +byteArray GenericStats::param_killCow() { + return instance->getParam_achievement(eAward_CowTipper); } -byteArray GenericStats::param_killCow() -{ - return instance->getParam_achievement(eAward_CowTipper); +byteArray GenericStats::param_flyPig() { + return instance->getParam_achievement(eAward_WhenPigsFly); } -byteArray GenericStats::param_flyPig() -{ - return instance->getParam_achievement(eAward_WhenPigsFly); -} - -byteArray GenericStats::param_snipeSkeleton() -{ +byteArray GenericStats::param_snipeSkeleton() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_snipeSkeleton); + return instance->getParam_achievement(eAward_snipeSkeleton); #endif } -byteArray GenericStats::param_diamonds() -{ +byteArray GenericStats::param_diamonds() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_diamonds); + return instance->getParam_achievement(eAward_diamonds); #endif } -byteArray GenericStats::param_ghast() -{ +byteArray GenericStats::param_ghast() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_ghast); + return instance->getParam_achievement(eAward_ghast); #endif } -byteArray GenericStats::param_blazeRod() -{ +byteArray GenericStats::param_blazeRod() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_blazeRod); + return instance->getParam_achievement(eAward_blazeRod); #endif } -byteArray GenericStats::param_potion() -{ +byteArray GenericStats::param_potion() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_potion); + return instance->getParam_achievement(eAward_potion); #endif } -byteArray GenericStats::param_theEnd() -{ +byteArray GenericStats::param_theEnd() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_theEnd); + return instance->getParam_achievement(eAward_theEnd); #endif } -byteArray GenericStats::param_winGame() -{ +byteArray GenericStats::param_winGame() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_winGame); + return instance->getParam_achievement(eAward_winGame); #endif } -byteArray GenericStats::param_enchantments() -{ +byteArray GenericStats::param_enchantments() { #ifdef _XBOX - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #else - return instance->getParam_achievement(eAward_enchantments); + return instance->getParam_achievement(eAward_enchantments); #endif } -byteArray GenericStats::param_overkill(int dmg) -{ - return instance->getParam_overkill(dmg); +byteArray GenericStats::param_overkill(int dmg) { + return instance->getParam_overkill(dmg); } -byteArray GenericStats::param_bookcase() -{ +byteArray GenericStats::param_bookcase() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_bookcase); + return instance->getParam_achievement(eAward_bookcase); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_leaderOfThePack() -{ - return instance->getParam_achievement(eAward_LeaderOfThePack); +byteArray GenericStats::param_leaderOfThePack() { + return instance->getParam_achievement(eAward_LeaderOfThePack); } -byteArray GenericStats::param_MOARTools() -{ - return instance->getParam_achievement(eAward_MOARTools); +byteArray GenericStats::param_MOARTools() { + return instance->getParam_achievement(eAward_MOARTools); } -byteArray GenericStats::param_dispenseWithThis() -{ - return instance->getParam_achievement(eAward_DispenseWithThis); +byteArray GenericStats::param_dispenseWithThis() { + return instance->getParam_achievement(eAward_DispenseWithThis); } -byteArray GenericStats::param_InToTheNether() -{ - return instance->getParam_achievement(eAward_InToTheNether); +byteArray GenericStats::param_InToTheNether() { + return instance->getParam_achievement(eAward_InToTheNether); } -byteArray GenericStats::param_socialPost() -{ - return instance->getParam_achievement(eAward_socialPost); +byteArray GenericStats::param_socialPost() { + return instance->getParam_achievement(eAward_socialPost); } -byteArray GenericStats::param_eatPorkChop() -{ - return instance->getParam_achievement(eAward_eatPorkChop); +byteArray GenericStats::param_eatPorkChop() { + return instance->getParam_achievement(eAward_eatPorkChop); } -byteArray GenericStats::param_play100Days() -{ - return instance->getParam_achievement(eAward_play100Days); +byteArray GenericStats::param_play100Days() { + return instance->getParam_achievement(eAward_play100Days); } -byteArray GenericStats::param_arrowKillCreeper() -{ - return instance->getParam_achievement(eAward_arrowKillCreeper); +byteArray GenericStats::param_arrowKillCreeper() { + return instance->getParam_achievement(eAward_arrowKillCreeper); } -byteArray GenericStats::param_mine100Blocks() -{ - return instance->getParam_achievement(eAward_mine100Blocks); +byteArray GenericStats::param_mine100Blocks() { + return instance->getParam_achievement(eAward_mine100Blocks); } -byteArray GenericStats::param_kill10Creepers() -{ - return instance->getParam_achievement(eAward_kill10Creepers); +byteArray GenericStats::param_kill10Creepers() { + return instance->getParam_achievement(eAward_kill10Creepers); } -byteArray GenericStats::param_adventuringTime() -{ +byteArray GenericStats::param_adventuringTime() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_adventuringTime); + return instance->getParam_achievement(eAward_adventuringTime); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_repopulation() -{ +byteArray GenericStats::param_repopulation() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_repopulation); + return instance->getParam_achievement(eAward_repopulation); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_porkChop() -{ +byteArray GenericStats::param_porkChop() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_eatPorkChop); + return instance->getParam_achievement(eAward_eatPorkChop); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_diamondsToYou() -{ +byteArray GenericStats::param_diamondsToYou() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_diamondsToYou); + return instance->getParam_achievement(eAward_diamondsToYou); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_passingTheTime() -{ +byteArray GenericStats::param_passingTheTime() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_play100Days); + return instance->getParam_achievement(eAward_play100Days); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_archer() -{ +byteArray GenericStats::param_archer() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_arrowKillCreeper); + return instance->getParam_achievement(eAward_arrowKillCreeper); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_theHaggler() -{ +byteArray GenericStats::param_theHaggler() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_theHaggler); + return instance->getParam_achievement(eAward_theHaggler); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_potPlanter() -{ +byteArray GenericStats::param_potPlanter() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_potPlanter); + return instance->getParam_achievement(eAward_potPlanter); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_itsASign() -{ +byteArray GenericStats::param_itsASign() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_itsASign); + return instance->getParam_achievement(eAward_itsASign); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_ironBelly() -{ +byteArray GenericStats::param_ironBelly() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_ironBelly); + return instance->getParam_achievement(eAward_ironBelly); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_haveAShearfulDay() -{ +byteArray GenericStats::param_haveAShearfulDay() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_haveAShearfulDay); + return instance->getParam_achievement(eAward_haveAShearfulDay); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_rainbowCollection() -{ +byteArray GenericStats::param_rainbowCollection() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_rainbowCollection); + return instance->getParam_achievement(eAward_rainbowCollection); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_stayinFrosty() -{ +byteArray GenericStats::param_stayinFrosty() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_stayinFrosty); + return instance->getParam_achievement(eAward_stayinFrosty); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_chestfulOfCobblestone(int cobbleStone) -{ - return instance->getParam_chestfulOfCobblestone(cobbleStone); +byteArray GenericStats::param_chestfulOfCobblestone(int cobbleStone) { + return instance->getParam_chestfulOfCobblestone(cobbleStone); } -byteArray GenericStats::param_renewableEnergy() -{ +byteArray GenericStats::param_renewableEnergy() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_renewableEnergy); + return instance->getParam_achievement(eAward_renewableEnergy); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_musicToMyEars(int recordId) -{ - return instance->getParam_musicToMyEars(recordId); +byteArray GenericStats::param_musicToMyEars(int recordId) { + return instance->getParam_musicToMyEars(recordId); } -byteArray GenericStats::param_bodyGuard() -{ +byteArray GenericStats::param_bodyGuard() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_bodyGuard); + return instance->getParam_achievement(eAward_bodyGuard); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_ironMan() -{ +byteArray GenericStats::param_ironMan() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_ironMan); + return instance->getParam_achievement(eAward_ironMan); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_zombieDoctor() -{ +byteArray GenericStats::param_zombieDoctor() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_zombieDoctor); + return instance->getParam_achievement(eAward_zombieDoctor); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } -byteArray GenericStats::param_lionTamer() -{ +byteArray GenericStats::param_lionTamer() { #ifdef _EXTENDED_ACHIEVEMENTS - return instance->getParam_achievement(eAward_lionTamer); + return instance->getParam_achievement(eAward_lionTamer); #else - return instance->getParam_noArgs(); + return instance->getParam_noArgs(); #endif } diff --git a/Minecraft.World/Stats/GenericStats.h b/Minecraft.World/Stats/GenericStats.h index 85ba86aa2..2277bf68e 100644 --- a/Minecraft.World/Stats/GenericStats.h +++ b/Minecraft.World/Stats/GenericStats.h @@ -3,346 +3,392 @@ #include "Stat.h" #include "Stats.h" -//#include "../Util/DamageSource.h" +// #include "../Util/DamageSource.h" -//#include "../../Minecraft.Client/Platform/Common/Console_Awards_enum.h" +// #include "../../Minecraft.Client/Platform/Common/Console_Awards_enum.h" /** - 4J-JEV: - Java version exposed the static instance of each stat. + 4J-JEV: + Java version exposed the static instance of each stat. - This was inconvient for me as I needed to structure the stats/achievements differently - on Durango. + This was inconvient for me as I needed to structure the + stats/achievements differently on Durango. - Using getters like this means we can use different Stats easilly on different - platforms and still have a convenient identifier to use to award them. + Using getters like this means we can use different Stats easilly + on different platforms and still have a convenient identifier to use to award + them. */ -class GenericStats -{ -private: // Static instance. - static GenericStats *instance; +class GenericStats { +private: // Static instance. + static GenericStats* instance; public: - static void setInstance(GenericStats *newInstance) { instance = newInstance; } - static GenericStats *getInstance() { return instance; } + static void setInstance(GenericStats* newInstance) { + instance = newInstance; + } + static GenericStats* getInstance() { return instance; } - // For retrieving a stat from an id. - virtual Stat *get_stat(int i) = 0; - static Stat *stat(int i) { return instance->get_stat(i); } + // For retrieving a stat from an id. + virtual Stat* get_stat(int i) = 0; + static Stat* stat(int i) { return instance->get_stat(i); } - // STATS - STATIC // + // STATS - STATIC // - static Stat* walkOneM() { return instance->get_walkOneM(); } - static Stat* swimOneM() { return instance->get_swimOneM(); } - static Stat* fallOneM() { return instance->get_fallOneM(); } - static Stat* climbOneM() { return instance->get_climbOneM(); } - static Stat* minecartOneM() { return instance->get_minecartOneM(); } - static Stat* boatOneM() { return instance->get_boatOneM(); } - static Stat* pigOneM() { return instance->get_pigOneM(); } - static Stat* portalsCreated() { return instance->get_portalsCreated(); } - static Stat* cowsMilked() { return instance->get_cowsMilked(); } - static Stat* netherLavaCollected() { return instance->get_netherLavaCollected(); } + static Stat* walkOneM() { return instance->get_walkOneM(); } + static Stat* swimOneM() { return instance->get_swimOneM(); } + static Stat* fallOneM() { return instance->get_fallOneM(); } + static Stat* climbOneM() { return instance->get_climbOneM(); } + static Stat* minecartOneM() { return instance->get_minecartOneM(); } + static Stat* boatOneM() { return instance->get_boatOneM(); } + static Stat* pigOneM() { return instance->get_pigOneM(); } + static Stat* portalsCreated() { return instance->get_portalsCreated(); } + static Stat* cowsMilked() { return instance->get_cowsMilked(); } + static Stat* netherLavaCollected() { + return instance->get_netherLavaCollected(); + } - static Stat* killMob() { return instance->get_killMob(); } + static Stat* killMob() { return instance->get_killMob(); } - static Stat* killsZombie() { return instance->get_killsZombie(); } - static Stat* killsSkeleton() { return instance->get_killsSkeleton(); } - static Stat* killsCreeper() { return instance->get_killsCreeper(); } - static Stat* killsSpider() { return instance->get_killsSpider(); } - static Stat* killsSpiderJockey() { return instance->get_killsSpiderJockey(); } - static Stat* killsZombiePigman() { return instance->get_killsZombiePigman(); } - static Stat* killsSlime() { return instance->get_killsSlime(); } - static Stat* killsGhast() { return instance->get_killsGhast(); } - static Stat* killsNetherZombiePigman() { return instance->get_killsNetherZombiePigman(); } + static Stat* killsZombie() { return instance->get_killsZombie(); } + static Stat* killsSkeleton() { return instance->get_killsSkeleton(); } + static Stat* killsCreeper() { return instance->get_killsCreeper(); } + static Stat* killsSpider() { return instance->get_killsSpider(); } + static Stat* killsSpiderJockey() { + return instance->get_killsSpiderJockey(); + } + static Stat* killsZombiePigman() { + return instance->get_killsZombiePigman(); + } + static Stat* killsSlime() { return instance->get_killsSlime(); } + static Stat* killsGhast() { return instance->get_killsGhast(); } + static Stat* killsNetherZombiePigman() { + return instance->get_killsNetherZombiePigman(); + } - static Stat* breedEntity(eINSTANCEOF entityId) { return instance->get_breedEntity(entityId); } - static Stat* tamedEntity(eINSTANCEOF entityId) { return instance->get_tamedEntity(entityId); } - static Stat* curedEntity(eINSTANCEOF entityId) { return instance->get_curedEntity(entityId); } - static Stat* craftedEntity(eINSTANCEOF entityId) { return instance->get_craftedEntity(entityId); } - static Stat* shearedEntity(eINSTANCEOF entityId) { return instance->get_shearedEntity(entityId); } + static Stat* breedEntity(eINSTANCEOF entityId) { + return instance->get_breedEntity(entityId); + } + static Stat* tamedEntity(eINSTANCEOF entityId) { + return instance->get_tamedEntity(entityId); + } + static Stat* curedEntity(eINSTANCEOF entityId) { + return instance->get_curedEntity(entityId); + } + static Stat* craftedEntity(eINSTANCEOF entityId) { + return instance->get_craftedEntity(entityId); + } + static Stat* shearedEntity(eINSTANCEOF entityId) { + return instance->get_shearedEntity(entityId); + } - static Stat* totalBlocksMined() { return instance->get_totalBlocksMined(); } - static Stat* timePlayed() { return instance->get_timePlayed(); } + static Stat* totalBlocksMined() { return instance->get_totalBlocksMined(); } + static Stat* timePlayed() { return instance->get_timePlayed(); } - static Stat* blocksPlaced(int blockId) { return instance->get_blocksPlaced(blockId); } - static Stat* blocksMined(int blockId) { return instance->get_blocksMined(blockId); } - static Stat* itemsCollected(int itemId, int itemAux) { return instance->get_itemsCollected(itemId, itemAux); } - static Stat* itemsCrafted(int itemId) { return instance->get_itemsCrafted(itemId); } - static Stat* itemsSmelted(int itemId) { return instance->get_itemsSmelted(itemId); } // 4J-JEV: Diffentiation needed, when only one type of event should be sent (eg iron smelting). - static Stat* itemsUsed(int itemId) { return instance->get_itemsUsed(itemId); } - static Stat* itemsBought(int itemId) { return instance->get_itemsBought(itemId); } + static Stat* blocksPlaced(int blockId) { + return instance->get_blocksPlaced(blockId); + } + static Stat* blocksMined(int blockId) { + return instance->get_blocksMined(blockId); + } + static Stat* itemsCollected(int itemId, int itemAux) { + return instance->get_itemsCollected(itemId, itemAux); + } + static Stat* itemsCrafted(int itemId) { + return instance->get_itemsCrafted(itemId); + } + static Stat* itemsSmelted(int itemId) { + return instance->get_itemsSmelted(itemId); + } // 4J-JEV: Diffentiation needed, when only one type of event should be + // sent (eg iron smelting). + static Stat* itemsUsed(int itemId) { + return instance->get_itemsUsed(itemId); + } + static Stat* itemsBought(int itemId) { + return instance->get_itemsBought(itemId); + } - static Stat* killsEnderdragon() { return instance->get_killsEnderdragon(); } - static Stat* completeTheEnd() { return instance->get_completeTheEnd(); } + static Stat* killsEnderdragon() { return instance->get_killsEnderdragon(); } + static Stat* completeTheEnd() { return instance->get_completeTheEnd(); } - static Stat* changedDimension(int from, int to) { return instance->get_changedDimension(from,to); } - static Stat* enteredBiome(int biomeId) { return instance->get_enteredBiome(biomeId); } + static Stat* changedDimension(int from, int to) { + return instance->get_changedDimension(from, to); + } + static Stat* enteredBiome(int biomeId) { + return instance->get_enteredBiome(biomeId); + } - // ACHIEVEMENTS - STATIC // + // ACHIEVEMENTS - STATIC // - static Stat* achievement(eAward achievementId) { return instance->get_achievement(achievementId); } + static Stat* achievement(eAward achievementId) { + return instance->get_achievement(achievementId); + } - static Stat* openInventory(); - static Stat* mineWood(); - static Stat* buildWorkbench(); - static Stat* buildPickaxe(); - static Stat* buildFurnace(); - static Stat* acquireIron(); - static Stat* buildHoe(); - static Stat* makeBread(); - static Stat* bakeCake(); - static Stat* buildBetterPickaxe(); - static Stat* cookFish(); - static Stat* onARail(); - static Stat* buildSword(); - static Stat* killEnemy(); - static Stat* killCow(); - static Stat* flyPig(); - static Stat* snipeSkeleton(); - static Stat* diamonds(); - static Stat* ghast(); - static Stat* blazeRod(); - static Stat* potion(); - static Stat* theEnd(); - static Stat* winGame(); - static Stat* enchantments(); - static Stat* overkill(); - static Stat* bookcase(); + static Stat* openInventory(); + static Stat* mineWood(); + static Stat* buildWorkbench(); + static Stat* buildPickaxe(); + static Stat* buildFurnace(); + static Stat* acquireIron(); + static Stat* buildHoe(); + static Stat* makeBread(); + static Stat* bakeCake(); + static Stat* buildBetterPickaxe(); + static Stat* cookFish(); + static Stat* onARail(); + static Stat* buildSword(); + static Stat* killEnemy(); + static Stat* killCow(); + static Stat* flyPig(); + static Stat* snipeSkeleton(); + static Stat* diamonds(); + static Stat* ghast(); + static Stat* blazeRod(); + static Stat* potion(); + static Stat* theEnd(); + static Stat* winGame(); + static Stat* enchantments(); + static Stat* overkill(); + static Stat* bookcase(); - static Stat* leaderOfThePack(); - static Stat* MOARTools(); - static Stat* dispenseWithThis(); - static Stat* InToTheNether(); + static Stat* leaderOfThePack(); + static Stat* MOARTools(); + static Stat* dispenseWithThis(); + static Stat* InToTheNether(); - static Stat* socialPost(); - static Stat* eatPorkChop(); - static Stat* play100Days(); - static Stat* arrowKillCreeper(); - static Stat* mine100Blocks(); - static Stat* kill10Creepers(); + static Stat* socialPost(); + static Stat* eatPorkChop(); + static Stat* play100Days(); + static Stat* arrowKillCreeper(); + static Stat* mine100Blocks(); + static Stat* kill10Creepers(); - static Stat* adventuringTime(); // Requires new Stat - static Stat* repopulation(); - static Stat* diamondsToYou(); // +Durango - static Stat* porkChop(); // Req Stat? - static Stat* passingTheTime(); // Req Stat - static Stat* archer(); - static Stat* theHaggler(); // Req Stat - static Stat* potPlanter(); // Req Stat - static Stat* itsASign(); // Req Stat - static Stat* ironBelly(); - static Stat* haveAShearfulDay(); - static Stat* rainbowCollection(); // Requires new Stat - static Stat* stayinFrosty(); // +Durango - static Stat* chestfulOfCobblestone(); // +Durango - static Stat* renewableEnergy(); // +Durango - static Stat* musicToMyEars(); // +Durango - static Stat* bodyGuard(); - static Stat* ironMan(); // +Durango - static Stat* zombieDoctor(); // +Durango - static Stat* lionTamer(); + static Stat* adventuringTime(); // Requires new Stat + static Stat* repopulation(); + static Stat* diamondsToYou(); // +Durango + static Stat* porkChop(); // Req Stat? + static Stat* passingTheTime(); // Req Stat + static Stat* archer(); + static Stat* theHaggler(); // Req Stat + static Stat* potPlanter(); // Req Stat + static Stat* itsASign(); // Req Stat + static Stat* ironBelly(); + static Stat* haveAShearfulDay(); + static Stat* rainbowCollection(); // Requires new Stat + static Stat* stayinFrosty(); // +Durango + static Stat* chestfulOfCobblestone(); // +Durango + static Stat* renewableEnergy(); // +Durango + static Stat* musicToMyEars(); // +Durango + static Stat* bodyGuard(); + static Stat* ironMan(); // +Durango + static Stat* zombieDoctor(); // +Durango + static Stat* lionTamer(); - // STAT PARAMS - STATIC // + // STAT PARAMS - STATIC // - static byteArray param_walk(int distance); - static byteArray param_swim(int distance); - static byteArray param_fall(int distance); - static byteArray param_climb(int distance); - static byteArray param_minecart(int distance); - static byteArray param_boat(int distance); - static byteArray param_pig(int distance); + static byteArray param_walk(int distance); + static byteArray param_swim(int distance); + static byteArray param_fall(int distance); + static byteArray param_climb(int distance); + static byteArray param_minecart(int distance); + static byteArray param_boat(int distance); + static byteArray param_pig(int distance); - static byteArray param_cowsMilked(); + static byteArray param_cowsMilked(); - static byteArray param_blocksPlaced(int id, int data, int count); - static byteArray param_blocksMined(int id, int data, int count); - static byteArray param_itemsCollected(int id, int aux, int count); - static byteArray param_itemsCrafted(int id, int aux, int count); - static byteArray param_itemsSmelted(int id, int aux, int cound); - static byteArray param_itemsUsed(std::shared_ptr plr, std::shared_ptr itm); - static byteArray param_itemsBought(int id, int aux, int count); + static byteArray param_blocksPlaced(int id, int data, int count); + static byteArray param_blocksMined(int id, int data, int count); + static byteArray param_itemsCollected(int id, int aux, int count); + static byteArray param_itemsCrafted(int id, int aux, int count); + static byteArray param_itemsSmelted(int id, int aux, int cound); + static byteArray param_itemsUsed(std::shared_ptr plr, + std::shared_ptr itm); + static byteArray param_itemsBought(int id, int aux, int count); - static byteArray param_mobKill(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc); + static byteArray param_mobKill(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc); - static byteArray param_breedEntity(eINSTANCEOF mobType); - static byteArray param_tamedEntity(eINSTANCEOF mobType); - static byteArray param_curedEntity(eINSTANCEOF mobType); - static byteArray param_craftedEntity(eINSTANCEOF mobType); - static byteArray param_shearedEntity(eINSTANCEOF mobType); + static byteArray param_breedEntity(eINSTANCEOF mobType); + static byteArray param_tamedEntity(eINSTANCEOF mobType); + static byteArray param_curedEntity(eINSTANCEOF mobType); + static byteArray param_craftedEntity(eINSTANCEOF mobType); + static byteArray param_shearedEntity(eINSTANCEOF mobType); - static byteArray param_time(int timediff); + static byteArray param_time(int timediff); - static byteArray param_changedDimension(int from, int to); - static byteArray param_enteredBiome(int biomeId); + static byteArray param_changedDimension(int from, int to); + static byteArray param_enteredBiome(int biomeId); - //static byteArray param_achievement(eAward id); + // static byteArray param_achievement(eAward id); - //static byteArray param_ach_onARail(); - //static byteArray param_overkill(int damage); //TODO - //static byteArray param_openInventory(int menuId); - //static byteArray param_chestfulOfCobblestone(); - //static byteArray param_musicToMyEars(int recordId); + // static byteArray param_ach_onARail(); + // static byteArray param_overkill(int damage); //TODO + // static byteArray param_openInventory(int menuId); + // static byteArray param_chestfulOfCobblestone(); + // static byteArray param_musicToMyEars(int recordId); - static byteArray param_noArgs(); + static byteArray param_noArgs(); - // STATIC + VIRTUAL - ACHIEVEMENT - PARAMS // + // STATIC + VIRTUAL - ACHIEVEMENT - PARAMS // - static byteArray param_openInventory(); - static byteArray param_mineWood(); - static byteArray param_buildWorkbench(); - static byteArray param_buildPickaxe(); - static byteArray param_buildFurnace(); - static byteArray param_acquireIron(); - static byteArray param_buildHoe(); - static byteArray param_makeBread(); - static byteArray param_bakeCake(); - static byteArray param_buildBetterPickaxe(); - static byteArray param_cookFish(); - static byteArray param_onARail(int distance); - static byteArray param_buildSword(); - static byteArray param_killEnemy(); - static byteArray param_killCow(); - static byteArray param_flyPig(); - static byteArray param_snipeSkeleton(); - static byteArray param_diamonds(); - static byteArray param_ghast(); - static byteArray param_blazeRod(); - static byteArray param_potion(); - static byteArray param_theEnd(); - static byteArray param_winGame(); - static byteArray param_enchantments(); - static byteArray param_overkill(int dmg); - static byteArray param_bookcase(); + static byteArray param_openInventory(); + static byteArray param_mineWood(); + static byteArray param_buildWorkbench(); + static byteArray param_buildPickaxe(); + static byteArray param_buildFurnace(); + static byteArray param_acquireIron(); + static byteArray param_buildHoe(); + static byteArray param_makeBread(); + static byteArray param_bakeCake(); + static byteArray param_buildBetterPickaxe(); + static byteArray param_cookFish(); + static byteArray param_onARail(int distance); + static byteArray param_buildSword(); + static byteArray param_killEnemy(); + static byteArray param_killCow(); + static byteArray param_flyPig(); + static byteArray param_snipeSkeleton(); + static byteArray param_diamonds(); + static byteArray param_ghast(); + static byteArray param_blazeRod(); + static byteArray param_potion(); + static byteArray param_theEnd(); + static byteArray param_winGame(); + static byteArray param_enchantments(); + static byteArray param_overkill(int dmg); + static byteArray param_bookcase(); - static byteArray param_leaderOfThePack(); - static byteArray param_MOARTools(); - static byteArray param_dispenseWithThis(); - static byteArray param_InToTheNether(); + static byteArray param_leaderOfThePack(); + static byteArray param_MOARTools(); + static byteArray param_dispenseWithThis(); + static byteArray param_InToTheNether(); - static byteArray param_socialPost(); - static byteArray param_eatPorkChop(); - static byteArray param_play100Days(); - static byteArray param_arrowKillCreeper(); - static byteArray param_mine100Blocks(); - static byteArray param_kill10Creepers(); + static byteArray param_socialPost(); + static byteArray param_eatPorkChop(); + static byteArray param_play100Days(); + static byteArray param_arrowKillCreeper(); + static byteArray param_mine100Blocks(); + static byteArray param_kill10Creepers(); - static byteArray param_adventuringTime(); - static byteArray param_repopulation(); - static byteArray param_porkChop(); - static byteArray param_diamondsToYou(); - static byteArray param_passingTheTime(); - static byteArray param_archer(); - static byteArray param_theHaggler(); - static byteArray param_potPlanter(); - static byteArray param_itsASign(); - static byteArray param_ironBelly(); - static byteArray param_haveAShearfulDay(); - static byteArray param_rainbowCollection(); - static byteArray param_stayinFrosty(); - static byteArray param_chestfulOfCobblestone(int cobbleStone); - static byteArray param_renewableEnergy(); - static byteArray param_musicToMyEars(int recordId); - static byteArray param_bodyGuard(); - static byteArray param_ironMan(); - static byteArray param_zombieDoctor(); - static byteArray param_lionTamer(); + static byteArray param_adventuringTime(); + static byteArray param_repopulation(); + static byteArray param_porkChop(); + static byteArray param_diamondsToYou(); + static byteArray param_passingTheTime(); + static byteArray param_archer(); + static byteArray param_theHaggler(); + static byteArray param_potPlanter(); + static byteArray param_itsASign(); + static byteArray param_ironBelly(); + static byteArray param_haveAShearfulDay(); + static byteArray param_rainbowCollection(); + static byteArray param_stayinFrosty(); + static byteArray param_chestfulOfCobblestone(int cobbleStone); + static byteArray param_renewableEnergy(); + static byteArray param_musicToMyEars(int recordId); + static byteArray param_bodyGuard(); + static byteArray param_ironMan(); + static byteArray param_zombieDoctor(); + static byteArray param_lionTamer(); protected: - // ACHIEVEMENTS - VIRTUAL // - - virtual Stat* get_achievement(eAward achievementId); + // ACHIEVEMENTS - VIRTUAL // + virtual Stat* get_achievement(eAward achievementId); - // STATS - VIRTUAL // + // STATS - VIRTUAL // - virtual Stat* get_walkOneM(); - virtual Stat* get_swimOneM(); - virtual Stat* get_fallOneM(); - virtual Stat* get_climbOneM(); - virtual Stat* get_minecartOneM(); - virtual Stat* get_boatOneM(); - virtual Stat* get_pigOneM(); - virtual Stat* get_portalsCreated(); - virtual Stat* get_cowsMilked(); - virtual Stat* get_netherLavaCollected(); + virtual Stat* get_walkOneM(); + virtual Stat* get_swimOneM(); + virtual Stat* get_fallOneM(); + virtual Stat* get_climbOneM(); + virtual Stat* get_minecartOneM(); + virtual Stat* get_boatOneM(); + virtual Stat* get_pigOneM(); + virtual Stat* get_portalsCreated(); + virtual Stat* get_cowsMilked(); + virtual Stat* get_netherLavaCollected(); - virtual Stat* get_killMob(); + virtual Stat* get_killMob(); - virtual Stat* get_killsZombie(); - virtual Stat* get_killsSkeleton(); - virtual Stat* get_killsCreeper(); - virtual Stat* get_killsSpider(); - virtual Stat* get_killsSpiderJockey(); - virtual Stat* get_killsZombiePigman(); - virtual Stat* get_killsSlime(); - virtual Stat* get_killsGhast(); - virtual Stat* get_killsNetherZombiePigman(); + virtual Stat* get_killsZombie(); + virtual Stat* get_killsSkeleton(); + virtual Stat* get_killsCreeper(); + virtual Stat* get_killsSpider(); + virtual Stat* get_killsSpiderJockey(); + virtual Stat* get_killsZombiePigman(); + virtual Stat* get_killsSlime(); + virtual Stat* get_killsGhast(); + virtual Stat* get_killsNetherZombiePigman(); - virtual Stat* get_breedEntity(eINSTANCEOF entityId); - virtual Stat* get_tamedEntity(eINSTANCEOF entityId); - virtual Stat* get_curedEntity(eINSTANCEOF entityId); - virtual Stat* get_craftedEntity(eINSTANCEOF entityId); - virtual Stat* get_shearedEntity(eINSTANCEOF entityId); + virtual Stat* get_breedEntity(eINSTANCEOF entityId); + virtual Stat* get_tamedEntity(eINSTANCEOF entityId); + virtual Stat* get_curedEntity(eINSTANCEOF entityId); + virtual Stat* get_craftedEntity(eINSTANCEOF entityId); + virtual Stat* get_shearedEntity(eINSTANCEOF entityId); - virtual Stat* get_totalBlocksMined(); - virtual Stat* get_timePlayed(); + virtual Stat* get_totalBlocksMined(); + virtual Stat* get_timePlayed(); - virtual Stat* get_blocksPlaced(int blockId); - virtual Stat* get_blocksMined(int blockId); - virtual Stat* get_itemsCollected(int itemId, int itemAux); - virtual Stat* get_itemsCrafted(int itemId); - virtual Stat* get_itemsSmelted(int itemId); - virtual Stat* get_itemsUsed(int itemId); - virtual Stat* get_itemsBought(int itemId); + virtual Stat* get_blocksPlaced(int blockId); + virtual Stat* get_blocksMined(int blockId); + virtual Stat* get_itemsCollected(int itemId, int itemAux); + virtual Stat* get_itemsCrafted(int itemId); + virtual Stat* get_itemsSmelted(int itemId); + virtual Stat* get_itemsUsed(int itemId); + virtual Stat* get_itemsBought(int itemId); - virtual Stat* get_killsEnderdragon(); - virtual Stat* get_completeTheEnd(); + virtual Stat* get_killsEnderdragon(); + virtual Stat* get_completeTheEnd(); - virtual Stat* get_changedDimension(int from, int to); - virtual Stat* get_enteredBiome(int biomeId); + virtual Stat* get_changedDimension(int from, int to); + virtual Stat* get_enteredBiome(int biomeId); - // STAT PARAMS - VIRTUAL // + // STAT PARAMS - VIRTUAL // - virtual byteArray getParam_walkOneM(int distance); - virtual byteArray getParam_swimOneM(int distance); - virtual byteArray getParam_fallOneM(int distance); - virtual byteArray getParam_climbOneM(int distance); - virtual byteArray getParam_minecartOneM(int distance); - virtual byteArray getParam_boatOneM(int distance); - virtual byteArray getParam_pigOneM(int distance); + virtual byteArray getParam_walkOneM(int distance); + virtual byteArray getParam_swimOneM(int distance); + virtual byteArray getParam_fallOneM(int distance); + virtual byteArray getParam_climbOneM(int distance); + virtual byteArray getParam_minecartOneM(int distance); + virtual byteArray getParam_boatOneM(int distance); + virtual byteArray getParam_pigOneM(int distance); - virtual byteArray getParam_cowsMilked(); + virtual byteArray getParam_cowsMilked(); - virtual byteArray getParam_blocksPlaced(int id, int data, int count); - virtual byteArray getParam_blocksMined(int id, int data, int count); - virtual byteArray getParam_itemsCollected(int id, int aux, int count); - virtual byteArray getParam_itemsCrafted(int id, int aux, int count); - virtual byteArray getParam_itemsSmelted(int id, int aux, int count); - virtual byteArray getParam_itemsUsed(std::shared_ptr plr, std::shared_ptr itm); - virtual byteArray getParam_itemsBought(int id, int aux, int count); + virtual byteArray getParam_blocksPlaced(int id, int data, int count); + virtual byteArray getParam_blocksMined(int id, int data, int count); + virtual byteArray getParam_itemsCollected(int id, int aux, int count); + virtual byteArray getParam_itemsCrafted(int id, int aux, int count); + virtual byteArray getParam_itemsSmelted(int id, int aux, int count); + virtual byteArray getParam_itemsUsed(std::shared_ptr plr, + std::shared_ptr itm); + virtual byteArray getParam_itemsBought(int id, int aux, int count); - virtual byteArray getParam_mobKill(std::shared_ptr plr, std::shared_ptr mob, DamageSource *dmgSrc); + virtual byteArray getParam_mobKill(std::shared_ptr plr, + std::shared_ptr mob, + DamageSource* dmgSrc); - virtual byteArray getParam_breedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_tamedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_curedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_craftedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_shearedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_breedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_tamedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_curedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_craftedEntity(eINSTANCEOF entityId); + virtual byteArray getParam_shearedEntity(eINSTANCEOF entityId); - virtual byteArray getParam_time(int timediff); + virtual byteArray getParam_time(int timediff); - virtual byteArray getParam_changedDimension(int from, int to); - virtual byteArray getParam_enteredBiome(int biomeId); + virtual byteArray getParam_changedDimension(int from, int to); + virtual byteArray getParam_enteredBiome(int biomeId); - virtual byteArray getParam_achievement(eAward id); + virtual byteArray getParam_achievement(eAward id); - virtual byteArray getParam_onARail(int distance); - virtual byteArray getParam_overkill(int damage); - virtual byteArray getParam_openInventory(int menuId); - virtual byteArray getParam_chestfulOfCobblestone(int cobbleStone); - virtual byteArray getParam_musicToMyEars(int recordId); + virtual byteArray getParam_onARail(int distance); + virtual byteArray getParam_overkill(int damage); + virtual byteArray getParam_openInventory(int menuId); + virtual byteArray getParam_chestfulOfCobblestone(int cobbleStone); + virtual byteArray getParam_musicToMyEars(int recordId); - virtual byteArray getParam_noArgs(); + virtual byteArray getParam_noArgs(); }; // Req Stats \ No newline at end of file diff --git a/Minecraft.World/Stats/ItemStat.cpp b/Minecraft.World/Stats/ItemStat.cpp index 3ef669700..c39824f9d 100644 --- a/Minecraft.World/Stats/ItemStat.cpp +++ b/Minecraft.World/Stats/ItemStat.cpp @@ -1,11 +1,7 @@ #include "../Platform/stdafx.h" #include "ItemStat.h" -ItemStat::ItemStat(int id, const std::wstring& name, int itemId) : Stat( id, name ), itemId(itemId) -{ -} +ItemStat::ItemStat(int id, const std::wstring& name, int itemId) + : Stat(id, name), itemId(itemId) {} -int ItemStat::getItemId() -{ - return itemId; -} +int ItemStat::getItemId() { return itemId; } diff --git a/Minecraft.World/Stats/ItemStat.h b/Minecraft.World/Stats/ItemStat.h index dccaf528e..317302972 100644 --- a/Minecraft.World/Stats/ItemStat.h +++ b/Minecraft.World/Stats/ItemStat.h @@ -1,14 +1,12 @@ #pragma once - #include "Stat.h" -class ItemStat : public Stat -{ +class ItemStat : public Stat { private: - const int itemId; + const int itemId; public: - ItemStat(int id, const std::wstring& name, int itemId); + ItemStat(int id, const std::wstring& name, int itemId); int getItemId(); }; diff --git a/Minecraft.World/Stats/Stat.cpp b/Minecraft.World/Stats/Stat.cpp index 67c74c457..5471c4d55 100644 --- a/Minecraft.World/Stats/Stat.cpp +++ b/Minecraft.World/Stats/Stat.cpp @@ -5,111 +5,90 @@ #include "Stats.h" #include "Stat.h" -Stat::DefaultFormat *Stat::defaultFormatter = new DefaultFormat(); -Stat::TimeFormatter *Stat::timeFormatter = new TimeFormatter(); -Stat::DistanceFormatter *Stat::distanceFormatter = new DistanceFormatter(); +Stat::DefaultFormat* Stat::defaultFormatter = new DefaultFormat(); +Stat::TimeFormatter* Stat::timeFormatter = new TimeFormatter(); +Stat::DistanceFormatter* Stat::distanceFormatter = new DistanceFormatter(); // 4J Stu - Changed this to take in a printf format string instead -DecimalFormat *Stat::decimalFormat = new DecimalFormat(L"%0(3).2f"); +DecimalFormat* Stat::decimalFormat = new DecimalFormat(L"%0(3).2f"); -void Stat::_init() -{ - awardLocallyOnly = false; -} +void Stat::_init() { awardLocallyOnly = false; } -Stat::Stat(int id, const std::wstring& name, StatFormatter *formatter) : id(id), name(name), formatter(formatter) -{ - _init(); -} - -Stat::Stat(int id, const std::wstring& name) : id(id), name(name), formatter(defaultFormatter) -{ +Stat::Stat(int id, const std::wstring& name, StatFormatter* formatter) + : id(id), name(name), formatter(formatter) { _init(); } -Stat *Stat::setAwardLocallyOnly() -{ +Stat::Stat(int id, const std::wstring& name) + : id(id), name(name), formatter(defaultFormatter) { + _init(); +} + +Stat* Stat::setAwardLocallyOnly() { awardLocallyOnly = true; return this; } -Stat *Stat::postConstruct() -{ - //if (Stats::statsById->containsKey(id)) - //{ - //throw new RuntimeException("Duplicate stat id: \"" + Stats::statsById->get(id)->name + "\" and \"" + name + "\" at id " + id); 4J - TODO +Stat* Stat::postConstruct() { + // if (Stats::statsById->containsKey(id)) + //{ + // throw new RuntimeException("Duplicate stat id: \"" + + // Stats::statsById->get(id)->name + "\" and \"" + name + "\" at id " + id); + // 4J - TODO //} Stats::all->push_back(this); - std::pair id1(id,this); + std::pair id1(id, this); #ifdef __PS3__ - Stats::statsById->emplace(id1 );// assert(0); // MGH - TODO - FIX - find out where this move function comes from + Stats::statsById->emplace(id1); // assert(0); // MGH - TODO - FIX - find + //out where this move function comes from #else - Stats::statsById->emplace(std::move(id1)); -#endif // __PS3__ + Stats::statsById->emplace(std::move(id1)); +#endif // __PS3__ return this; } -bool Stat::isAchievement() -{ - return false; +bool Stat::isAchievement() { return false; } + +std::wstring Stat::format(int value) { + return ((StatFormatter*)formatter)->format(value); } -std::wstring Stat::format(int value) -{ - return ((StatFormatter *)formatter)->format(value); -} +std::wstring Stat::toString() { return name; } -std::wstring Stat::toString() -{ - return name; -} - -std::wstring Stat::TimeFormatter::format(int value) -{ +std::wstring Stat::TimeFormatter::format(int value) { double seconds = value / 20.0; double minutes = seconds / 60.0; double hours = minutes / 60.0; double days = hours / 24.0; double years = days / 365.0; - if (years > 0.5) - { + if (years > 0.5) { return decimalFormat->format(years) + L" y"; - } - else if (days > 0.5) - { + } else if (days > 0.5) { return decimalFormat->format(days) + L" d"; - } - else if (hours > 0.5) - { + } else if (hours > 0.5) { return decimalFormat->format(hours) + L" h"; - } - else if (minutes > 0.5) - { + } else if (minutes > 0.5) { return decimalFormat->format(minutes) + L" m"; } return _toString(seconds) + L" s"; } -std::wstring Stat::DefaultFormat::format(int value) -{ - return NumberFormat::format( value ); //numberFormat->format(value); +std::wstring Stat::DefaultFormat::format(int value) { + return NumberFormat::format(value); // numberFormat->format(value); } -std::wstring Stat::DistanceFormatter::format(int cm) -{ +std::wstring Stat::DistanceFormatter::format(int cm) { double meters = cm / 100.0; double kilometers = meters / 1000.0; - if (kilometers > 0.5) - { + if (kilometers > 0.5) { return decimalFormat->format(kilometers) + L" km"; - } else if (meters > 0.5) - { + } else if (meters > 0.5) { return decimalFormat->format(meters) + L" m"; } return _toString(cm) + L" cm"; diff --git a/Minecraft.World/Stats/Stat.h b/Minecraft.World/Stats/Stat.h index 5182e6bd8..c4a7c997c 100644 --- a/Minecraft.World/Stats/Stat.h +++ b/Minecraft.World/Stats/Stat.h @@ -1,61 +1,59 @@ #pragma once - #include "StatFormatter.h" #include "GenericStats.h" class DecimalFormat; -class Stat -{ +class Stat { public: - const int id; + const int id; const std::wstring name; bool awardLocallyOnly; private: - const StatFormatter *formatter; - void _init(); + const StatFormatter* formatter; + void _init(); public: - Stat(int id, const std::wstring& name, StatFormatter *formatter); + Stat(int id, const std::wstring& name, StatFormatter* formatter); Stat(int id, const std::wstring& name); - Stat *setAwardLocallyOnly(); + Stat* setAwardLocallyOnly(); - virtual Stat *postConstruct(); + virtual Stat* postConstruct(); virtual bool isAchievement(); std::wstring format(int value); private: - //static NumberFormat *numberFormat; + // static NumberFormat *numberFormat; public: - class DefaultFormat : public StatFormatter - { - public: - std::wstring format(int value); - } static *defaultFormatter; + class DefaultFormat : public StatFormatter { + public: + std::wstring format(int value); + } static* defaultFormatter; private: - static DecimalFormat *decimalFormat; + static DecimalFormat* decimalFormat; public: + class TimeFormatter : public StatFormatter { + public: + std::wstring format(int value); + } static* timeFormatter; - class TimeFormatter : public StatFormatter - { - public: - std::wstring format(int value); - } static *timeFormatter; - - class DistanceFormatter : public StatFormatter - { - public: - std::wstring format(int cm); - } static *distanceFormatter; + class DistanceFormatter : public StatFormatter { + public: + std::wstring format(int cm); + } static* distanceFormatter; std::wstring toString(); public: - // 4J-JEV, for Durango stats - virtual void handleParamBlob(std::shared_ptr plr, byteArray param) { app.DebugPrintf("'Stat.h', Unhandled AwardStat blob.\n"); return; } + // 4J-JEV, for Durango stats + virtual void handleParamBlob(std::shared_ptr plr, + byteArray param) { + app.DebugPrintf("'Stat.h', Unhandled AwardStat blob.\n"); + return; + } }; diff --git a/Minecraft.World/Stats/StatFormatter.h b/Minecraft.World/Stats/StatFormatter.h index fcc1dd55f..b69b1c242 100644 --- a/Minecraft.World/Stats/StatFormatter.h +++ b/Minecraft.World/Stats/StatFormatter.h @@ -1,8 +1,6 @@ #pragma once - -class StatFormatter -{ +class StatFormatter { public: - virtual std::wstring format(int value) = 0; + virtual std::wstring format(int value) = 0; }; diff --git a/Minecraft.World/Stats/Stats.cpp b/Minecraft.World/Stats/Stats.cpp index 012462500..962fae493 100644 --- a/Minecraft.World/Stats/Stats.cpp +++ b/Minecraft.World/Stats/Stats.cpp @@ -13,44 +13,47 @@ const int Stats::BLOCKS_MINED_OFFSET = 0x1000000; const int Stats::ITEMS_COLLECTED_OFFSET = 0x1010000; const int Stats::ITEMS_CRAFTED_OFFSET = 0x1020000; -const int Stats::ADDITIONAL_STATS_OFFSET = 0x5010000; // Needs to be higher than Achievements::ACHIEVEMENT_OFFSET = 0x500000; +const int Stats::ADDITIONAL_STATS_OFFSET = + 0x5010000; // Needs to be higher than Achievements::ACHIEVEMENT_OFFSET = + // 0x500000; -std::unordered_map* Stats::statsById = new std::unordered_map; +std::unordered_map* Stats::statsById = + new std::unordered_map; -std::vector *Stats::all = new std::vector; -std::vector *Stats::generalStats = new std::vector; -std::vector *Stats::blocksMinedStats = new std::vector; -std::vector *Stats::itemsCollectedStats = new std::vector; -std::vector *Stats::itemsCraftedStats = new std::vector; +std::vector* Stats::all = new std::vector; +std::vector* Stats::generalStats = new std::vector; +std::vector* Stats::blocksMinedStats = new std::vector; +std::vector* Stats::itemsCollectedStats = new std::vector; +std::vector* Stats::itemsCraftedStats = new std::vector; #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _DURANGO) -std::vector *Stats::blocksPlacedStats = new std::vector; +std::vector* Stats::blocksPlacedStats = new std::vector; #endif -Stat *Stats::walkOneM = NULL; -Stat *Stats::swimOneM = NULL; -Stat *Stats::fallOneM = NULL; -Stat *Stats::climbOneM = NULL; -Stat *Stats::minecartOneM = NULL; -Stat *Stats::boatOneM = NULL; -Stat *Stats::pigOneM = NULL; -Stat *Stats::portalsCreated = NULL; -Stat *Stats::cowsMilked = NULL; -Stat *Stats::netherLavaCollected = NULL; -Stat *Stats::killsZombie = NULL; -Stat *Stats::killsSkeleton = NULL; -Stat *Stats::killsCreeper = NULL; -Stat *Stats::killsSpider = NULL; -Stat *Stats::killsSpiderJockey = NULL; -Stat *Stats::killsZombiePigman = NULL; -Stat *Stats::killsSlime = NULL; -Stat *Stats::killsGhast = NULL; -Stat *Stats::killsNetherZombiePigman = NULL; +Stat* Stats::walkOneM = NULL; +Stat* Stats::swimOneM = NULL; +Stat* Stats::fallOneM = NULL; +Stat* Stats::climbOneM = NULL; +Stat* Stats::minecartOneM = NULL; +Stat* Stats::boatOneM = NULL; +Stat* Stats::pigOneM = NULL; +Stat* Stats::portalsCreated = NULL; +Stat* Stats::cowsMilked = NULL; +Stat* Stats::netherLavaCollected = NULL; +Stat* Stats::killsZombie = NULL; +Stat* Stats::killsSkeleton = NULL; +Stat* Stats::killsCreeper = NULL; +Stat* Stats::killsSpider = NULL; +Stat* Stats::killsSpiderJockey = NULL; +Stat* Stats::killsZombiePigman = NULL; +Stat* Stats::killsSlime = NULL; +Stat* Stats::killsGhast = NULL; +Stat* Stats::killsNetherZombiePigman = NULL; // 4J : WESTY : Added for new achievements. -Stat *Stats::befriendsWolf = NULL; -Stat *Stats::totalBlocksMined = NULL; -Stat *Stats::timePlayed = NULL; +Stat* Stats::befriendsWolf = NULL; +Stat* Stats::totalBlocksMined = NULL; +Stat* Stats::timePlayed = NULL; StatArray Stats::blocksMined; StatArray Stats::itemsCollected; @@ -62,207 +65,268 @@ StatArray Stats::rainbowCollection; StatArray Stats::biomesVisisted; #endif -Stat *Stats::killsEnderdragon = NULL; // The number of times this player has dealt the killing blow to the Enderdragon -Stat *Stats::completeTheEnd = NULL; // The number of times this player has been present when the Enderdragon has died +Stat* Stats::killsEnderdragon = + NULL; // The number of times this player has dealt the killing blow to the + // Enderdragon +Stat* Stats::completeTheEnd = NULL; // The number of times this player has been + // present when the Enderdragon has died -void Stats::staticCtor() -{ - Stats::walkOneM = (new GeneralStat(2000, L"stat.walkOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::swimOneM = (new GeneralStat(2001, L"stat.swimOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::fallOneM = (new GeneralStat(2002, L"stat.fallOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::climbOneM = (new GeneralStat(2003, L"stat.climbOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::minecartOneM = (new GeneralStat(2004, L"stat.minecartOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::boatOneM = (new GeneralStat(2005, L"stat.boatOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::pigOneM = (new GeneralStat(2006, L"stat.pigOneM", (StatFormatter *) Stat::distanceFormatter))->setAwardLocallyOnly()->postConstruct(); - Stats::portalsCreated = (new GeneralStat(2007, L"stat.portalsUsed"))->postConstruct(); - Stats::cowsMilked = (new GeneralStat(2008, L"stat.cowsMilked"))->postConstruct(); - Stats::netherLavaCollected = (new GeneralStat(2009, L"stat.netherLavaCollected"))->postConstruct(); - Stats::killsZombie = (new GeneralStat(2010, L"stat.killsZombie"))->postConstruct(); - Stats::killsSkeleton = (new GeneralStat(2011, L"stat.killsSkeleton"))->postConstruct(); - Stats::killsCreeper = (new GeneralStat(2012, L"stat.killsCreeper"))->postConstruct(); - Stats::killsSpider = (new GeneralStat(2013, L"stat.killsSpider"))->postConstruct(); - Stats::killsSpiderJockey = (new GeneralStat(2014, L"stat.killsSpiderJockey"))->postConstruct(); - Stats::killsZombiePigman = (new GeneralStat(2015, L"stat.killsZombiePigman"))->postConstruct(); - Stats::killsSlime = (new GeneralStat(2016, L"stat.killsSlime"))->postConstruct(); - Stats::killsGhast = (new GeneralStat(2017, L"stat.killsGhast"))->postConstruct(); - Stats::killsNetherZombiePigman = (new GeneralStat(2018, L"stat.killsNetherZombiePigman"))->postConstruct(); +void Stats::staticCtor() { + Stats::walkOneM = (new GeneralStat(2000, L"stat.walkOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::swimOneM = (new GeneralStat(2001, L"stat.swimOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::fallOneM = (new GeneralStat(2002, L"stat.fallOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::climbOneM = + (new GeneralStat(2003, L"stat.climbOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::minecartOneM = + (new GeneralStat(2004, L"stat.minecartOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::boatOneM = (new GeneralStat(2005, L"stat.boatOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::pigOneM = (new GeneralStat(2006, L"stat.pigOneM", + (StatFormatter*)Stat::distanceFormatter)) + ->setAwardLocallyOnly() + ->postConstruct(); + Stats::portalsCreated = + (new GeneralStat(2007, L"stat.portalsUsed"))->postConstruct(); + Stats::cowsMilked = + (new GeneralStat(2008, L"stat.cowsMilked"))->postConstruct(); + Stats::netherLavaCollected = + (new GeneralStat(2009, L"stat.netherLavaCollected"))->postConstruct(); + Stats::killsZombie = + (new GeneralStat(2010, L"stat.killsZombie"))->postConstruct(); + Stats::killsSkeleton = + (new GeneralStat(2011, L"stat.killsSkeleton"))->postConstruct(); + Stats::killsCreeper = + (new GeneralStat(2012, L"stat.killsCreeper"))->postConstruct(); + Stats::killsSpider = + (new GeneralStat(2013, L"stat.killsSpider"))->postConstruct(); + Stats::killsSpiderJockey = + (new GeneralStat(2014, L"stat.killsSpiderJockey"))->postConstruct(); + Stats::killsZombiePigman = + (new GeneralStat(2015, L"stat.killsZombiePigman"))->postConstruct(); + Stats::killsSlime = + (new GeneralStat(2016, L"stat.killsSlime"))->postConstruct(); + Stats::killsGhast = + (new GeneralStat(2017, L"stat.killsGhast"))->postConstruct(); + Stats::killsNetherZombiePigman = + (new GeneralStat(2018, L"stat.killsNetherZombiePigman")) + ->postConstruct(); - // 4J : WESTY : Added for new achievements. - Stats::befriendsWolf = (new GeneralStat(2019, L"stat.befriendsWolf"))->postConstruct(); - Stats::totalBlocksMined = (new GeneralStat(2020, L"stat.totalBlocksMined"))->postConstruct(); + // 4J : WESTY : Added for new achievements. + Stats::befriendsWolf = + (new GeneralStat(2019, L"stat.befriendsWolf"))->postConstruct(); + Stats::totalBlocksMined = + (new GeneralStat(2020, L"stat.totalBlocksMined"))->postConstruct(); - // 4J-PB - don't want the time played going to the server - Stats::timePlayed = (new GeneralStat(2021, L"stat.timePlayed"))->setAwardLocallyOnly()->postConstruct(); + // 4J-PB - don't want the time played going to the server + Stats::timePlayed = (new GeneralStat(2021, L"stat.timePlayed")) + ->setAwardLocallyOnly() + ->postConstruct(); -// WARNING: NO NEW STATS CAN BE ADDED HERE -// These stats are directly followed by the achievemnts in the profile data, so cannot be changed without migrating the profile data + // WARNING: NO NEW STATS CAN BE ADDED HERE + // These stats are directly followed by the achievemnts in the profile data, + // so cannot be changed without migrating the profile data - buildBlockStats(); + buildBlockStats(); - Achievements::init(); - Achievements::staticCtor(); + Achievements::init(); + Achievements::staticCtor(); - // 4J Stu - Added this function to allow us to add news stats from TU9 onwards - buildAdditionalStats(); + // 4J Stu - Added this function to allow us to add news stats from TU9 + // onwards + buildAdditionalStats(); } -void Stats::init() -{ -} +void Stats::init() {} bool Stats::blockStatsLoaded = false; // WARNING: NO NEW STATS CAN BE ADDED HERE -// These stats are directly followed by the achievemnts in the profile data, so cannot be changed without migrating the profile data -void Stats::buildBlockStats() -{ - blocksMined = StatArray(32000); +// These stats are directly followed by the achievemnts in the profile data, so +// cannot be changed without migrating the profile data +void Stats::buildBlockStats() { + blocksMined = StatArray(32000); - ItemStat* newStat = new ItemStat(BLOCKS_MINED_OFFSET + 0, L"mineBlock.dirt", Tile::dirt->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::dirt->id] = newStat; - blocksMined[Tile::grass->id] = newStat; - blocksMined[Tile::farmland->id] = newStat; - newStat->postConstruct(); + ItemStat* newStat = new ItemStat(BLOCKS_MINED_OFFSET + 0, L"mineBlock.dirt", + Tile::dirt->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::dirt->id] = newStat; + blocksMined[Tile::grass->id] = newStat; + blocksMined[Tile::farmland->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 1, L"mineBlock.stone", Tile::stoneBrick->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::stoneBrick->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 1, L"mineBlock.stone", + Tile::stoneBrick->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::stoneBrick->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 2, L"mineBlock.sand", Tile::sand->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::sand->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 2, L"mineBlock.sand", + Tile::sand->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::sand->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 3, L"mineBlock.cobblestone", Tile::rock->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::rock->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 3, L"mineBlock.cobblestone", + Tile::rock->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::rock->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 4, L"mineBlock.gravel", Tile::gravel->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::gravel->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 4, L"mineBlock.gravel", + Tile::gravel->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::gravel->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 5, L"mineBlock.clay", Tile::clay->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::clay->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 5, L"mineBlock.clay", + Tile::clay->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::clay->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 6, L"mineBlock.obsidian", Tile::obsidian->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::obsidian->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 6, L"mineBlock.obsidian", + Tile::obsidian->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::obsidian->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 7, L"mineBlock.coal", Tile::coalOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::coalOre->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 7, L"mineBlock.coal", + Tile::coalOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::coalOre->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 8, L"mineBlock.iron", Tile::ironOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::ironOre->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 8, L"mineBlock.iron", + Tile::ironOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::ironOre->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 9, L"mineBlock.gold", Tile::goldOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::goldOre->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 9, L"mineBlock.gold", + Tile::goldOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::goldOre->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 10, L"mineBlock.diamond", Tile::diamondOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::diamondOre->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 10, L"mineBlock.diamond", + Tile::diamondOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::diamondOre->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 11, L"mineBlock.redstone", Tile::redStoneOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::redStoneOre->id] = newStat; - blocksMined[Tile::redStoneOre_lit->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 11, L"mineBlock.redstone", + Tile::redStoneOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::redStoneOre->id] = newStat; + blocksMined[Tile::redStoneOre_lit->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 12, L"mineBlock.lapisLazuli", Tile::lapisOre->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::lapisOre->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 12, L"mineBlock.lapisLazuli", + Tile::lapisOre->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::lapisOre->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 13, L"mineBlock.netherrack", Tile::hellRock->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::hellRock->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 13, L"mineBlock.netherrack", + Tile::hellRock->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::hellRock->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 14, L"mineBlock.soulSand", Tile::hellSand->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::hellSand->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 14, L"mineBlock.soulSand", + Tile::hellSand->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::hellSand->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 15, L"mineBlock.glowstone", Tile::lightGem->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::lightGem->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 15, L"mineBlock.glowstone", + Tile::lightGem->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::lightGem->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 16, L"mineBlock.wood", Tile::treeTrunk->id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::treeTrunk->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 16, L"mineBlock.wood", + Tile::treeTrunk->id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::treeTrunk->id] = newStat; + newStat->postConstruct(); -// WARNING: NO NEW STATS CAN BE ADDED HERE -// These stats are directly followed by the achievemnts in the profile data, so cannot be changed without migrating the profile data + // WARNING: NO NEW STATS CAN BE ADDED HERE + // These stats are directly followed by the achievemnts in the profile data, + // so cannot be changed without migrating the profile data - - blockStatsLoaded = true; - buildCraftableStats(); + blockStatsLoaded = true; + buildCraftableStats(); } bool Stats::itemStatsLoaded = false; -void Stats::buildItemStats() -{ - itemStatsLoaded = true; - buildCraftableStats(); +void Stats::buildItemStats() { + itemStatsLoaded = true; + buildCraftableStats(); } bool Stats::craftableStatsLoaded = false; - // WARNING: NO NEW STATS CAN BE ADDED HERE -// These stats are directly followed by the achievemnts in the profile data, so cannot be changed without migrating the profile data -void Stats::buildCraftableStats() -{ - if (!blockStatsLoaded || !itemStatsLoaded || craftableStatsLoaded) - { - // still waiting for the JVM to load stuff - //Or stats already loaded - return; - } +// These stats are directly followed by the achievemnts in the profile data, so +// cannot be changed without migrating the profile data +void Stats::buildCraftableStats() { + if (!blockStatsLoaded || !itemStatsLoaded || craftableStatsLoaded) { + // still waiting for the JVM to load stuff + // Or stats already loaded + return; + } - craftableStatsLoaded = true; + craftableStatsLoaded = true; - //Collected stats - - itemsCollected = StatArray(32000); + // Collected stats - ItemStat* newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 0, L"collectItem.egg", Item::egg->id); - itemsCollectedStats->push_back(newStat); - itemsCollected[Item::egg->id] = newStat; - newStat->postConstruct(); + itemsCollected = StatArray(32000); - // 4J Stu - The following stats were added as it was too easy to cheat the leaderboards by dropping and picking up these items - // They are now changed to mining the block which involves a tiny bit more effort - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 18, L"mineBlock.wheat", Tile::crops_Id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::crops_Id] = newStat; - newStat->postConstruct(); - - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 19, L"mineBlock.mushroom1", Tile::mushroom1_Id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::mushroom1_Id] = newStat; - newStat->postConstruct(); + ItemStat* newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 0, + L"collectItem.egg", Item::egg->id); + itemsCollectedStats->push_back(newStat); + itemsCollected[Item::egg->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(BLOCKS_MINED_OFFSET + 17, L"mineBlock.sugar", Tile::reeds_Id); - blocksMinedStats->push_back(newStat); - blocksMined[Tile::reeds_Id] = newStat; - newStat->postConstruct(); + // 4J Stu - The following stats were added as it was too easy to cheat the + // leaderboards by dropping and picking up these items They are now changed + // to mining the block which involves a tiny bit more effort + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 18, L"mineBlock.wheat", + Tile::crops_Id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::crops_Id] = newStat; + newStat->postConstruct(); + + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 19, L"mineBlock.mushroom1", + Tile::mushroom1_Id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::mushroom1_Id] = newStat; + newStat->postConstruct(); + + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 17, L"mineBlock.sugar", + Tile::reeds_Id); + blocksMinedStats->push_back(newStat); + blocksMined[Tile::reeds_Id] = newStat; + newStat->postConstruct(); #if 0 newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 1, L"collectItem.wheat", Item::wheat->id); itemsCollectedStats->push_back(newStat); @@ -281,277 +345,322 @@ void Stats::buildCraftableStats() newStat->postConstruct(); #endif - newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 4, L"collectItem.pumpkin", Tile::pumpkin->id); - itemsCollectedStats->push_back(newStat); - itemsCollected[Tile::pumpkin->id] = newStat; - itemsCollected[Tile::litPumpkin->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 4, L"collectItem.pumpkin", + Tile::pumpkin->id); + itemsCollectedStats->push_back(newStat); + itemsCollected[Tile::pumpkin->id] = newStat; + itemsCollected[Tile::litPumpkin->id] = newStat; + newStat->postConstruct(); - //Crafted stats + // Crafted stats - itemsCrafted = StatArray(32000); + itemsCrafted = StatArray(32000); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 0, L"craftItem.plank", Tile::wood->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Tile::wood->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 0, L"craftItem.plank", + Tile::wood->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Tile::wood->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 1, L"craftItem.workbench", Tile::workBench->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Tile::workBench->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 1, L"craftItem.workbench", + Tile::workBench->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Tile::workBench->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 2, L"craftItem.stick", Item::stick->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::stick->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 2, L"craftItem.stick", + Item::stick->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::stick->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 3, L"craftItem.woodenShovel", Item::shovel_wood->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::shovel_wood->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 3, L"craftItem.woodenShovel", + Item::shovel_wood->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::shovel_wood->id] = newStat; + newStat->postConstruct(); - // 4J : WESTY : Added for new achievements. - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 4, L"craftItem.woodenPickAxe", Item::pickAxe_wood->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::pickAxe_wood->id] = newStat; - newStat->postConstruct(); + // 4J : WESTY : Added for new achievements. + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 4, L"craftItem.woodenPickAxe", + Item::pickAxe_wood->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::pickAxe_wood->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 5, L"craftItem.stonePickAxe", Item::pickAxe_stone->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::pickAxe_stone->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 5, L"craftItem.stonePickAxe", + Item::pickAxe_stone->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::pickAxe_stone->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 6, L"craftItem.ironPickAxe", Item::pickAxe_iron->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::pickAxe_iron->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 6, L"craftItem.ironPickAxe", + Item::pickAxe_iron->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::pickAxe_iron->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 7, L"craftItem.diamondPickAxe", Item::pickAxe_diamond->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::pickAxe_diamond->id] = newStat; - newStat->postConstruct(); + newStat = + new ItemStat(ITEMS_CRAFTED_OFFSET + 7, L"craftItem.diamondPickAxe", + Item::pickAxe_diamond->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::pickAxe_diamond->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 8, L"craftItem.goldPickAxe", Item::pickAxe_gold->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::pickAxe_gold->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 8, L"craftItem.goldPickAxe", + Item::pickAxe_gold->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::pickAxe_gold->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 9, L"craftItem.stoneShovel", Item::shovel_stone->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::shovel_stone->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 9, L"craftItem.stoneShovel", + Item::shovel_stone->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::shovel_stone->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 10, L"craftItem.ironShovel", Item::shovel_iron->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::shovel_iron->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 10, L"craftItem.ironShovel", + Item::shovel_iron->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::shovel_iron->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 11, L"craftItem.diamondShovel", Item::shovel_diamond->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::shovel_diamond->id] = newStat; - newStat->postConstruct(); + newStat = + new ItemStat(ITEMS_CRAFTED_OFFSET + 11, L"craftItem.diamondShovel", + Item::shovel_diamond->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::shovel_diamond->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 12, L"craftItem.goldShovel", Item::shovel_gold->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::shovel_gold->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 12, L"craftItem.goldShovel", + Item::shovel_gold->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::shovel_gold->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 13, L"craftItem.woodenAxe", Item::hatchet_wood->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hatchet_wood->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 13, L"craftItem.woodenAxe", + Item::hatchet_wood->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hatchet_wood->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 14, L"craftItem.stoneAxe", Item::hatchet_stone->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hatchet_stone->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 14, L"craftItem.stoneAxe", + Item::hatchet_stone->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hatchet_stone->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 15, L"craftItem.ironAxe", Item::hatchet_iron->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hatchet_iron->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 15, L"craftItem.ironAxe", + Item::hatchet_iron->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hatchet_iron->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 16, L"craftItem.diamondAxe", Item::hatchet_diamond->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hatchet_diamond->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 16, L"craftItem.diamondAxe", + Item::hatchet_diamond->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hatchet_diamond->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 17, L"craftItem.goldAxe", Item::hatchet_gold->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hatchet_gold->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 17, L"craftItem.goldAxe", + Item::hatchet_gold->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hatchet_gold->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 18, L"craftItem.woodenHoe", Item::hoe_wood->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hoe_wood->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 18, L"craftItem.woodenHoe", + Item::hoe_wood->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hoe_wood->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 19, L"craftItem.stoneHoe", Item::hoe_stone->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hoe_stone->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 19, L"craftItem.stoneHoe", + Item::hoe_stone->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hoe_stone->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 20, L"craftItem.ironHoe", Item::hoe_iron->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hoe_iron->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 20, L"craftItem.ironHoe", + Item::hoe_iron->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hoe_iron->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 21, L"craftItem.diamondHoe", Item::hoe_diamond->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hoe_diamond->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 21, L"craftItem.diamondHoe", + Item::hoe_diamond->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hoe_diamond->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 22, L"craftItem.goldHoe", Item::hoe_gold->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::hoe_gold->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 22, L"craftItem.goldHoe", + Item::hoe_gold->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::hoe_gold->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 23, L"craftItem.glowstone", Tile::lightGem_Id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Tile::lightGem_Id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 23, L"craftItem.glowstone", + Tile::lightGem_Id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Tile::lightGem_Id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 24, L"craftItem.tnt", Tile::tnt_Id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Tile::tnt_Id] = newStat; - newStat->postConstruct(); + newStat = + new ItemStat(ITEMS_CRAFTED_OFFSET + 24, L"craftItem.tnt", Tile::tnt_Id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Tile::tnt_Id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 25, L"craftItem.bowl", Item::bowl->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::bowl->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 25, L"craftItem.bowl", + Item::bowl->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::bowl->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 26, L"craftItem.bucket", Item::bucket_empty->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::bucket_empty->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 26, L"craftItem.bucket", + Item::bucket_empty->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::bucket_empty->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 27, L"craftItem.flintAndSteel", Item::flintAndSteel->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::flintAndSteel->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 27, + L"craftItem.flintAndSteel", Item::flintAndSteel->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::flintAndSteel->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 28, L"craftItem.fishingRod", Item::fishingRod->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::fishingRod->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 28, L"craftItem.fishingRod", + Item::fishingRod->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::fishingRod->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 29, L"craftItem.clock", Item::clock->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::clock->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 29, L"craftItem.clock", + Item::clock->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::clock->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 30, L"craftItem.compass", Item::compass->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::compass->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 30, L"craftItem.compass", + Item::compass->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::compass->id] = newStat; + newStat->postConstruct(); - newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 31, L"craftItem.map", Item::map->id); - itemsCraftedStats->push_back(newStat); - itemsCrafted[Item::map->id] = newStat; - newStat->postConstruct(); + newStat = new ItemStat(ITEMS_CRAFTED_OFFSET + 31, L"craftItem.map", + Item::map->id); + itemsCraftedStats->push_back(newStat); + itemsCrafted[Item::map->id] = newStat; + newStat->postConstruct(); -// WARNING: NO NEW STATS CAN BE ADDED HERE -// These stats are directly followed by the achievemnts in the profile data, so cannot be changed without migrating the profile data + // WARNING: NO NEW STATS CAN BE ADDED HERE + // These stats are directly followed by the achievemnts in the profile data, + // so cannot be changed without migrating the profile data - //This sets up a static list of stat/leaderboard pairings, used to tell which leaderboards need an update - StatsCounter::setupStatBoards(); + // This sets up a static list of stat/leaderboard pairings, used to tell + // which leaderboards need an update + StatsCounter::setupStatBoards(); } // 4J Stu - Added this function to allow us to add news stats from TU9 onwards -void Stats::buildAdditionalStats() -{ - int offset = ADDITIONAL_STATS_OFFSET; +void Stats::buildAdditionalStats() { + int offset = ADDITIONAL_STATS_OFFSET; - // The order of these stats should not be changed, as the map directly to bits in the profile data + // The order of these stats should not be changed, as the map directly to + // bits in the profile data - // The number of times this player has dealt the killing blow to the Enderdragon - Stats::killsEnderdragon = (new GeneralStat(offset++, L"stat.killsEnderdragon"))->postConstruct(); - - // The number of times this player has been present when the Enderdragon has died - Stats::completeTheEnd = (new GeneralStat(offset++, L"stat.completeTheEnd"))->postConstruct(); + // The number of times this player has dealt the killing blow to the + // Enderdragon + Stats::killsEnderdragon = + (new GeneralStat(offset++, L"stat.killsEnderdragon"))->postConstruct(); + // The number of times this player has been present when the Enderdragon has + // died + Stats::completeTheEnd = + (new GeneralStat(offset++, L"stat.completeTheEnd"))->postConstruct(); #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _DURANGO) - { - ItemStat *itemStat = new ItemStat(offset++, L"craftItem.flowerPot", Item::flowerPot_Id); - itemsCraftedStats->push_back(itemStat); - itemsCrafted[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + { + ItemStat* itemStat = + new ItemStat(offset++, L"craftItem.flowerPot", Item::flowerPot_Id); + itemsCraftedStats->push_back(itemStat); + itemsCrafted[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - itemStat = new ItemStat(offset++, L"craftItem.sign", Item::sign_Id); - itemsCraftedStats->push_back(itemStat); - itemsCrafted[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = new ItemStat(offset++, L"craftItem.sign", Item::sign_Id); + itemsCraftedStats->push_back(itemStat); + itemsCrafted[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - itemStat = new ItemStat(offset++, L"mineBlock.emerald", Tile::emeraldOre_Id); - blocksMinedStats->push_back(itemStat); - blocksMined[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = + new ItemStat(offset++, L"mineBlock.emerald", Tile::emeraldOre_Id); + blocksMinedStats->push_back(itemStat); + blocksMined[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to - // stor itemsBought(emerald) so I don't have to make yet another massive - // StatArray for Items Bought. - itemStat = new ItemStat(offset++, L"itemsBought.emerald", Item::emerald_Id); - itemsCollectedStats->push_back(itemStat); - itemsCollected[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + // 4J-JEV: We don't need itemsCollected(emerald) so I'm using it to + // stor itemsBought(emerald) so I don't have to make yet another massive + // StatArray for Items Bought. + itemStat = + new ItemStat(offset++, L"itemsBought.emerald", Item::emerald_Id); + itemsCollectedStats->push_back(itemStat); + itemsCollected[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - // 4J-JEV: WHY ON EARTH DO THESE ARRAYS HAVE TO BE SO PAINFULLY LARGE WHEN THEY ARE GOING TO BE MOSTLY EMPTY!!! - // Either way, I'm making this one smaller because we don't need those record items (and we only need 2). - blocksPlaced = StatArray(1000); + // 4J-JEV: WHY ON EARTH DO THESE ARRAYS HAVE TO BE SO PAINFULLY + // LARGE WHEN THEY ARE GOING TO BE MOSTLY EMPTY!!! + // Either way, I'm making this one smaller because + //we don't need those record items (and we only need 2). + blocksPlaced = StatArray(1000); - itemStat = new ItemStat(offset++, L"blockPlaced.flowerPot", Tile::flowerPot_Id); - blocksPlacedStats->push_back(itemStat); - blocksPlaced[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = new ItemStat(offset++, L"blockPlaced.flowerPot", + Tile::flowerPot_Id); + blocksPlacedStats->push_back(itemStat); + blocksPlaced[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - itemStat = new ItemStat(offset++, L"blockPlaced.sign", Tile::sign_Id); - blocksPlacedStats->push_back(itemStat); - blocksPlaced[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = new ItemStat(offset++, L"blockPlaced.sign", Tile::sign_Id); + blocksPlacedStats->push_back(itemStat); + blocksPlaced[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - itemStat = new ItemStat(offset++, L"blockPlaced.wallsign", Tile::wallSign_Id); - blocksPlacedStats->push_back(itemStat); - blocksPlaced[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = + new ItemStat(offset++, L"blockPlaced.wallsign", Tile::wallSign_Id); + blocksPlacedStats->push_back(itemStat); + blocksPlaced[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - GeneralStat *generalStat = NULL; + GeneralStat* generalStat = NULL; - rainbowCollection = StatArray(16); - for (unsigned int i = 0; i < 16; i++) - { - generalStat = new GeneralStat(offset++, L"rainbowCollection." + _toString(i)); - generalStats->push_back(generalStat); - rainbowCollection[i] = generalStat; - generalStat->postConstruct(); - } + rainbowCollection = StatArray(16); + for (unsigned int i = 0; i < 16; i++) { + generalStat = new GeneralStat( + offset++, L"rainbowCollection." + _toString(i)); + generalStats->push_back(generalStat); + rainbowCollection[i] = generalStat; + generalStat->postConstruct(); + } - biomesVisisted = StatArray(23); - for (unsigned int i = 0; i < 23; i++) - { - generalStat = new GeneralStat(offset++, L"biomesVisited." + _toString(i)); - generalStats->push_back(generalStat); - biomesVisisted[i] = generalStat; - generalStat->postConstruct(); - } + biomesVisisted = StatArray(23); + for (unsigned int i = 0; i < 23; i++) { + generalStat = new GeneralStat( + offset++, L"biomesVisited." + _toString(i)); + generalStats->push_back(generalStat); + biomesVisisted[i] = generalStat; + generalStat->postConstruct(); + } - itemStat = new ItemStat(offset++, L"itemCrafted.porkchop", Item::porkChop_cooked_Id); - itemsCraftedStats->push_back(itemStat); - itemsCrafted[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); + itemStat = new ItemStat(offset++, L"itemCrafted.porkchop", + Item::porkChop_cooked_Id); + itemsCraftedStats->push_back(itemStat); + itemsCrafted[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); - itemStat = new ItemStat(offset++, L"itemEaten.porkchop", Item::porkChop_cooked_Id); - blocksPlacedStats->push_back(itemStat); - blocksPlaced[itemStat->getItemId()] = itemStat; - itemStat->postConstruct(); - } + itemStat = new ItemStat(offset++, L"itemEaten.porkchop", + Item::porkChop_cooked_Id); + blocksPlacedStats->push_back(itemStat); + blocksPlaced[itemStat->getItemId()] = itemStat; + itemStat->postConstruct(); + } #endif - } -Stat *Stats::get(int key) -{ - return statsById->at(key); -} +Stat* Stats::get(int key) { return statsById->at(key); } diff --git a/Minecraft.World/Stats/Stats.h b/Minecraft.World/Stats/Stats.h index b7d70d1c3..971f4181c 100644 --- a/Minecraft.World/Stats/Stats.h +++ b/Minecraft.World/Stats/Stats.h @@ -1,94 +1,98 @@ #pragma once - #include "Stat.h" class ItemStat; -class Stats -{ - friend class Stat; +class Stats { + friend class Stat; private: - static const int BLOCKS_MINED_OFFSET; - static const int ITEMS_COLLECTED_OFFSET; - static const int ITEMS_CRAFTED_OFFSET; - static const int ADDITIONAL_STATS_OFFSET; + static const int BLOCKS_MINED_OFFSET; + static const int ITEMS_COLLECTED_OFFSET; + static const int ITEMS_CRAFTED_OFFSET; + static const int ADDITIONAL_STATS_OFFSET; protected: - static std::unordered_map* statsById; + static std::unordered_map* statsById; public: - static std::vector *all; - static std::vector *generalStats; - static std::vector *blocksMinedStats; - static std::vector *itemsCollectedStats; - static std::vector *itemsCraftedStats; - + static std::vector* all; + static std::vector* generalStats; + static std::vector* blocksMinedStats; + static std::vector* itemsCollectedStats; + static std::vector* itemsCraftedStats; + #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _DURANGO) - static std::vector *blocksPlacedStats; + static std::vector* blocksPlacedStats; #endif - - static Stat *walkOneM; - static Stat *swimOneM; - static Stat *fallOneM; - static Stat *climbOneM; - static Stat *minecartOneM; - static Stat *boatOneM; - static Stat *pigOneM; - static Stat *portalsCreated; - static Stat *cowsMilked; - static Stat *netherLavaCollected; - static Stat *killsZombie; - static Stat *killsSkeleton; - static Stat *killsCreeper; - static Stat *killsSpider; - static Stat *killsSpiderJockey; - static Stat *killsZombiePigman; - static Stat *killsSlime; - static Stat *killsGhast; - static Stat *killsNetherZombiePigman; + static Stat* walkOneM; + static Stat* swimOneM; + static Stat* fallOneM; + static Stat* climbOneM; + static Stat* minecartOneM; + static Stat* boatOneM; + static Stat* pigOneM; + static Stat* portalsCreated; + static Stat* cowsMilked; + static Stat* netherLavaCollected; - // 4J : WESTY : Added for new achievements. - static Stat *befriendsWolf; - static Stat *totalBlocksMined; - static Stat *timePlayed; // Game time, recored as ticks, with TICKS_PER_DAY ticks per day! Stored as large stat so it doesn't max out before reaching 100 days ( 2,400,000 ticks ). + static Stat* killsZombie; + static Stat* killsSkeleton; + static Stat* killsCreeper; + static Stat* killsSpider; + static Stat* killsSpiderJockey; + static Stat* killsZombiePigman; + static Stat* killsSlime; + static Stat* killsGhast; + static Stat* killsNetherZombiePigman; - //static StatArray mobsKilled; + // 4J : WESTY : Added for new achievements. + static Stat* befriendsWolf; + static Stat* totalBlocksMined; + static Stat* + timePlayed; // Game time, recored as ticks, with TICKS_PER_DAY ticks + // per day! Stored as large stat so it doesn't max out + // before reaching 100 days ( 2,400,000 ticks ). + + // static StatArray mobsKilled; static StatArray blocksMined; static StatArray itemsCollected; static StatArray itemsCrafted; #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _DURANGO) - static StatArray blocksPlaced; + static StatArray blocksPlaced; #endif - // Added TU9 - static Stat *killsEnderdragon; // The number of times this player has dealt the killing blow to the Enderdragon - static Stat *completeTheEnd; // The number of times this player has been present when the Enderdragon has died + // Added TU9 + static Stat* killsEnderdragon; // The number of times this player has dealt + // the killing blow to the Enderdragon + static Stat* completeTheEnd; // The number of times this player has been + // present when the Enderdragon has died #if (defined _EXTENDED_ACHIEVEMENTS) && (!defined _DURANGO) - static StatArray biomesVisisted; - static StatArray rainbowCollection; + static StatArray biomesVisisted; + static StatArray rainbowCollection; #endif - static void staticCtor(); + static void staticCtor(); - static void init(); + static void init(); private: - static bool blockStatsLoaded; - static bool itemStatsLoaded; - static bool craftableStatsLoaded; + static bool blockStatsLoaded; + static bool itemStatsLoaded; + static bool craftableStatsLoaded; public: - static void buildBlockStats(); - static void buildItemStats(); + static void buildBlockStats(); + static void buildItemStats(); static void buildCraftableStats(); - // 4J Stu - Added this function to allow us to add news stats from TU9 onwards - static void buildAdditionalStats(); + // 4J Stu - Added this function to allow us to add news stats from TU9 + // onwards + static void buildAdditionalStats(); - static Stat *get(int key); + static Stat* get(int key); }; diff --git a/Minecraft.World/Util/AABB.cpp b/Minecraft.World/Util/AABB.cpp index 2d40fcaee..97e0df198 100644 --- a/Minecraft.World/Util/AABB.cpp +++ b/Minecraft.World/Util/AABB.cpp @@ -1,76 +1,62 @@ -//package net.minecraft.world.phys; +// package net.minecraft.world.phys; -//import java->util.ArrayList; -//import java->util.List; +// import java->util.ArrayList; +// import java->util.List; #include "../Platform/stdafx.h" #include "AABB.h" #include "HitResult.h" unsigned int AABB::tlsIdx = 0; -AABB::ThreadStorage *AABB::tlsDefault = NULL; +AABB::ThreadStorage* AABB::tlsDefault = NULL; -AABB::ThreadStorage::ThreadStorage() -{ - pool = new AABB[POOL_SIZE]; //4jcraft, needs to be deleted with delete[] - poolPointer = 0; +AABB::ThreadStorage::ThreadStorage() { + pool = new AABB[POOL_SIZE]; // 4jcraft, needs to be deleted with delete[] + poolPointer = 0; } - -AABB::ThreadStorage::~ThreadStorage() -{ - delete[] pool; //4jcraft, changed to [] +AABB::ThreadStorage::~ThreadStorage() { + delete[] pool; // 4jcraft, changed to [] } -void AABB::CreateNewThreadStorage() -{ - ThreadStorage *tls = new ThreadStorage(); - if(tlsDefault == NULL ) - { - tlsIdx = TlsAlloc(); - tlsDefault = tls; - } +void AABB::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + if (tlsDefault == NULL) { + tlsIdx = TlsAlloc(); + tlsDefault = tls; + } - TlsSetValue(tlsIdx, tls); + TlsSetValue(tlsIdx, tls); } -void AABB::UseDefaultThreadStorage() -{ - TlsSetValue(tlsIdx, tlsDefault); +void AABB::UseDefaultThreadStorage() { TlsSetValue(tlsIdx, tlsDefault); } + +void AABB::ReleaseThreadStorage() { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); + if (tls == tlsDefault) return; + + delete tls; } -void AABB::ReleaseThreadStorage() -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); - if( tls == tlsDefault ) return; - - delete tls; +AABB* AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, + double z1) { + return new AABB(x0, y0, z0, x1, y1, z1); } -AABB *AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return new AABB(x0, y0, z0, x1, y1, z1); -} +void AABB::clearPool() {} -void AABB::clearPool() -{ -} +void AABB::resetPool() {} -void AABB::resetPool() -{ -} - -AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, double z1) -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); - AABB *thisAABB = &tls->pool[tls->poolPointer]; - thisAABB->set(x0, y0, z0, x1, y1, z1); - tls->poolPointer = ( tls->poolPointer + 1 ) % ThreadStorage::POOL_SIZE; +AABB* AABB::newTemp(double x0, double y0, double z0, double x1, double y1, + double z1) { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); + AABB* thisAABB = &tls->pool[tls->poolPointer]; + thisAABB->set(x0, y0, z0, x1, y1, z1); + tls->poolPointer = (tls->poolPointer + 1) % ThreadStorage::POOL_SIZE; return thisAABB; } -AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) -{ +AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) { this->x0 = x0; this->y0 = y0; this->z0 = z0; @@ -79,9 +65,8 @@ AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) this->z1 = z1; } - -AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1) -{ +AABB* AABB::set(double x0, double y0, double z0, double x1, double y1, + double z1) { this->x0 = x0; this->y0 = y0; this->z0 = z0; @@ -91,8 +76,7 @@ AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1 return this; } -AABB *AABB::expand(double xa, double ya, double za) -{ +AABB* AABB::expand(double xa, double ya, double za) { double _x0 = x0; double _y0 = y0; double _z0 = z0; @@ -112,8 +96,7 @@ AABB *AABB::expand(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::grow(double xa, double ya, double za) -{ +AABB* AABB::grow(double xa, double ya, double za) { double _x0 = x0 - xa; double _y0 = y0 - ya; double _z0 = z0 - za; @@ -124,23 +107,19 @@ AABB *AABB::grow(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::cloneMove(double xa, double ya, double za) -{ +AABB* AABB::cloneMove(double xa, double ya, double za) { return AABB::newTemp(x0 + xa, y0 + ya, z0 + za, x1 + xa, y1 + ya, z1 + za); } -double AABB::clipXCollide(AABB *c, double xa) -{ +double AABB::clipXCollide(AABB* c, double xa) { if (c->y1 <= y0 || c->y0 >= y1) return xa; if (c->z1 <= z0 || c->z0 >= z1) return xa; - if (xa > 0 && c->x1 <= x0) - { + if (xa > 0 && c->x1 <= x0) { double max = x0 - c->x1; if (max < xa) xa = max; } - if (xa < 0 && c->x0 >= x1) - { + if (xa < 0 && c->x0 >= x1) { double max = x1 - c->x0; if (max > xa) xa = max; } @@ -148,18 +127,15 @@ double AABB::clipXCollide(AABB *c, double xa) return xa; } -double AABB::clipYCollide(AABB *c, double ya) -{ +double AABB::clipYCollide(AABB* c, double ya) { if (c->x1 <= x0 || c->x0 >= x1) return ya; if (c->z1 <= z0 || c->z0 >= z1) return ya; - if (ya > 0 && c->y1 <= y0) - { + if (ya > 0 && c->y1 <= y0) { double max = y0 - c->y1; if (max < ya) ya = max; } - if (ya < 0 && c->y0 >= y1) - { + if (ya < 0 && c->y0 >= y1) { double max = y1 - c->y0; if (max > ya) ya = max; } @@ -167,18 +143,15 @@ double AABB::clipYCollide(AABB *c, double ya) return ya; } -double AABB::clipZCollide(AABB *c, double za) -{ +double AABB::clipZCollide(AABB* c, double za) { if (c->x1 <= x0 || c->x0 >= x1) return za; if (c->y1 <= y0 || c->y0 >= y1) return za; - if (za > 0 && c->z1 <= z0) - { + if (za > 0 && c->z1 <= z0) { double max = z0 - c->z1; if (max < za) za = max; } - if (za < 0 && c->z0 >= z1) - { + if (za < 0 && c->z0 >= z1) { double max = z1 - c->z0; if (max > za) za = max; } @@ -186,24 +159,21 @@ double AABB::clipZCollide(AABB *c, double za) return za; } -bool AABB::intersects(AABB *c) -{ +bool AABB::intersects(AABB* c) { if (c->x1 <= x0 || c->x0 >= x1) return false; if (c->y1 <= y0 || c->y0 >= y1) return false; if (c->z1 <= z0 || c->z0 >= z1) return false; return true; } -bool AABB::intersectsInner(AABB *c) -{ +bool AABB::intersectsInner(AABB* c) { if (c->x1 < x0 || c->x0 > x1) return false; if (c->y1 < y0 || c->y0 > y1) return false; if (c->z1 < z0 || c->z0 > z1) return false; return true; } -AABB *AABB::move(double xa, double ya, double za) -{ +AABB* AABB::move(double xa, double ya, double za) { x0 += xa; y0 += ya; z0 += za; @@ -213,16 +183,15 @@ AABB *AABB::move(double xa, double ya, double za) return this; } -bool AABB::intersects(double x02, double y02, double z02, double x12, double y12, double z12) -{ +bool AABB::intersects(double x02, double y02, double z02, double x12, + double y12, double z12) { if (x12 <= x0 || x02 >= x1) return false; if (y12 <= y0 || y02 >= y1) return false; if (z12 <= z0 || z02 >= z1) return false; return true; } -bool AABB::contains(Vec3 *p) -{ +bool AABB::contains(Vec3* p) { if (p->x <= x0 || p->x >= x1) return false; if (p->y <= y0 || p->y >= y1) return false; if (p->z <= z0 || p->z >= z1) return false; @@ -230,24 +199,21 @@ bool AABB::contains(Vec3 *p) } // 4J Added -bool AABB::containsIncludingLowerBound(Vec3 *p) -{ +bool AABB::containsIncludingLowerBound(Vec3* p) { if (p->x < x0 || p->x >= x1) return false; if (p->y < y0 || p->y >= y1) return false; if (p->z < z0 || p->z >= z1) return false; return true; } -double AABB::getSize() -{ +double AABB::getSize() { double xs = x1 - x0; double ys = y1 - y0; double zs = z1 - z0; return (xs + ys + zs) / 3.0f; } -AABB *AABB::shrink(double xa, double ya, double za) -{ +AABB* AABB::shrink(double xa, double ya, double za) { double _x0 = x0 + xa; double _y0 = y0 + ya; double _z0 = z0 + za; @@ -258,21 +224,17 @@ AABB *AABB::shrink(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::copy() -{ - return AABB::newTemp(x0, y0, z0, x1, y1, z1); -} +AABB* AABB::copy() { return AABB::newTemp(x0, y0, z0, x1, y1, z1); } -HitResult *AABB::clip(Vec3 *a, Vec3 *b) -{ - Vec3 *xh0 = a->clipX(b, x0); - Vec3 *xh1 = a->clipX(b, x1); +HitResult* AABB::clip(Vec3* a, Vec3* b) { + Vec3* xh0 = a->clipX(b, x0); + Vec3* xh1 = a->clipX(b, x1); - Vec3 *yh0 = a->clipY(b, y0); - Vec3 *yh1 = a->clipY(b, y1); + Vec3* yh0 = a->clipY(b, y0); + Vec3* yh1 = a->clipY(b, y1); - Vec3 *zh0 = a->clipZ(b, z0); - Vec3 *zh1 = a->clipZ(b, z1); + Vec3* zh0 = a->clipZ(b, z0); + Vec3* zh1 = a->clipZ(b, z1); if (!containsX(xh0)) xh0 = NULL; if (!containsX(xh1)) xh1 = NULL; @@ -281,14 +243,26 @@ HitResult *AABB::clip(Vec3 *a, Vec3 *b) if (!containsZ(zh0)) zh0 = NULL; if (!containsZ(zh1)) zh1 = NULL; - Vec3 *closest = NULL; + Vec3* closest = NULL; - if (xh0 != NULL && (closest == NULL || a->distanceToSqr(xh0) < a->distanceToSqr(closest))) closest = xh0; - if (xh1 != NULL && (closest == NULL || a->distanceToSqr(xh1) < a->distanceToSqr(closest))) closest = xh1; - if (yh0 != NULL && (closest == NULL || a->distanceToSqr(yh0) < a->distanceToSqr(closest))) closest = yh0; - if (yh1 != NULL && (closest == NULL || a->distanceToSqr(yh1) < a->distanceToSqr(closest))) closest = yh1; - if (zh0 != NULL && (closest == NULL || a->distanceToSqr(zh0) < a->distanceToSqr(closest))) closest = zh0; - if (zh1 != NULL && (closest == NULL || a->distanceToSqr(zh1) < a->distanceToSqr(closest))) closest = zh1; + if (xh0 != NULL && + (closest == NULL || a->distanceToSqr(xh0) < a->distanceToSqr(closest))) + closest = xh0; + if (xh1 != NULL && + (closest == NULL || a->distanceToSqr(xh1) < a->distanceToSqr(closest))) + closest = xh1; + if (yh0 != NULL && + (closest == NULL || a->distanceToSqr(yh0) < a->distanceToSqr(closest))) + closest = yh0; + if (yh1 != NULL && + (closest == NULL || a->distanceToSqr(yh1) < a->distanceToSqr(closest))) + closest = yh1; + if (zh0 != NULL && + (closest == NULL || a->distanceToSqr(zh0) < a->distanceToSqr(closest))) + closest = zh0; + if (zh1 != NULL && + (closest == NULL || a->distanceToSqr(zh1) < a->distanceToSqr(closest))) + closest = zh1; if (closest == NULL) return NULL; @@ -304,28 +278,22 @@ HitResult *AABB::clip(Vec3 *a, Vec3 *b) return new HitResult(0, 0, 0, face, closest); } - -bool AABB::containsX(Vec3 *v) -{ +bool AABB::containsX(Vec3* v) { if (v == NULL) return false; return v->y >= y0 && v->y <= y1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsY(Vec3 *v) -{ +bool AABB::containsY(Vec3* v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsZ(Vec3 *v) -{ +bool AABB::containsZ(Vec3* v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->y >= y0 && v->y <= y1; } - -void AABB::set(AABB *b) -{ +void AABB::set(AABB* b) { this->x0 = b->x0; this->y0 = b->y0; this->z0 = b->z0; @@ -334,9 +302,8 @@ void AABB::set(AABB *b) this->z1 = b->z1; } -std::wstring AABB::toString() -{ - return L"box[" + _toString(x0) + L", " + _toString(y0) + L", " + _toString(z0) + L" -> " + - _toString(x1) + L", " + _toString(y1) + L", " + _toString(z1) + L"]"; +std::wstring AABB::toString() { + return L"box[" + _toString(x0) + L", " + _toString(y0) + + L", " + _toString(z0) + L" -> " + _toString(x1) + + L", " + _toString(y1) + L", " + _toString(z1) + L"]"; } - diff --git a/Minecraft.World/Util/AABB.h b/Minecraft.World/Util/AABB.h index 28f55d1f8..109ee3674 100644 --- a/Minecraft.World/Util/AABB.h +++ b/Minecraft.World/Util/AABB.h @@ -5,61 +5,65 @@ class HitResult; +class AABB { + // 4J added so we can have separate pools for different threads + class ThreadStorage { + public: + static const int POOL_SIZE = 1024; + AABB* pool; + unsigned int poolPointer; + ThreadStorage(); + ~ThreadStorage(); + }; + static unsigned int tlsIdx; + static ThreadStorage* tlsDefault; -class AABB -{ - // 4J added so we can have separate pools for different threads - class ThreadStorage - { - public: - static const int POOL_SIZE = 1024; - AABB *pool; - unsigned int poolPointer; - ThreadStorage(); - ~ThreadStorage(); - }; - static unsigned int tlsIdx; - static ThreadStorage *tlsDefault; public: - // Each new thread that needs to use Vec3 pools will need to call one of the following 2 functions, to either create its own - // local storage, or share the default storage already allocated by the main thread - static void CreateNewThreadStorage(); - static void UseDefaultThreadStorage(); - static void ReleaseThreadStorage(); + // Each new thread that needs to use Vec3 pools will need to call one of the + // following 2 functions, to either create its own local storage, or share + // the default storage already allocated by the main thread + static void CreateNewThreadStorage(); + static void UseDefaultThreadStorage(); + static void ReleaseThreadStorage(); - static AABB *newPermanent(double x0, double y0, double z0, double x1, double y1, double z1); - static void clearPool(); - static void resetPool(); - static AABB *newTemp(double x0, double y0, double z0, double x1, double y1, double z1); + static AABB* newPermanent(double x0, double y0, double z0, double x1, + double y1, double z1); + static void clearPool(); + static void resetPool(); + static AABB* newTemp(double x0, double y0, double z0, double x1, double y1, + double z1); - double x0, y0, z0; - double x1, y1, z1; + double x0, y0, z0; + double x1, y1, z1; private: - AABB(double x0, double y0, double z0, double x1, double y1, double z1); - AABB() {} + AABB(double x0, double y0, double z0, double x1, double y1, double z1); + AABB() {} + public: - AABB *set(double x0, double y0, double z0, double x1, double y1, double z1); - AABB *expand(double xa, double ya, double za); - AABB *grow(double xa, double ya, double za); + AABB* set(double x0, double y0, double z0, double x1, double y1, double z1); + AABB* expand(double xa, double ya, double za); + AABB* grow(double xa, double ya, double za); + public: - AABB *cloneMove(double xa, double ya, double za); - double clipXCollide(AABB *c, double xa); - double clipYCollide(AABB *c, double ya); - double clipZCollide(AABB *c, double za); - bool intersects(AABB *c); - bool intersectsInner(AABB *c); - AABB *move(double xa, double ya, double za); - bool intersects(double x02, double y02, double z02, double x12, double y12, double z12); - bool contains(Vec3 *p); - bool containsIncludingLowerBound(Vec3 *p); // 4J Added - double getSize(); - AABB *shrink(double xa, double ya, double za); - AABB *copy(); - HitResult *clip(Vec3 *a, Vec3 *b); - bool containsX(Vec3 *v); - bool containsY(Vec3 *v); - bool containsZ(Vec3 *v); - void set(AABB *b); - std::wstring toString(); + AABB* cloneMove(double xa, double ya, double za); + double clipXCollide(AABB* c, double xa); + double clipYCollide(AABB* c, double ya); + double clipZCollide(AABB* c, double za); + bool intersects(AABB* c); + bool intersectsInner(AABB* c); + AABB* move(double xa, double ya, double za); + bool intersects(double x02, double y02, double z02, double x12, double y12, + double z12); + bool contains(Vec3* p); + bool containsIncludingLowerBound(Vec3* p); // 4J Added + double getSize(); + AABB* shrink(double xa, double ya, double za); + AABB* copy(); + HitResult* clip(Vec3* a, Vec3* b); + bool containsX(Vec3* v); + bool containsY(Vec3* v); + bool containsZ(Vec3* v); + void set(AABB* b); + std::wstring toString(); }; diff --git a/Minecraft.World/Util/ArrayWithLength.h b/Minecraft.World/Util/ArrayWithLength.h index f2e268766..e381d08a7 100644 --- a/Minecraft.World/Util/ArrayWithLength.h +++ b/Minecraft.World/Util/ArrayWithLength.h @@ -2,64 +2,80 @@ #include -//Note - this is meant to be a really simple wrapper round a pointer just to be able to add a length value to arrays. -// As such, it shouldn't delete its data in a destructor as shallow copies will be made of this and we don't want to -// free the data just because one of those has gone out of scope -template class arrayWithLength -{ +// Note - this is meant to be a really simple wrapper round a pointer just to be +// able to add a length value to arrays. +// As such, it shouldn't delete its data in a destructor as shallow copies will +// be made of this and we don't want to free the data just because one of those +// has gone out of scope +template +class arrayWithLength { public: - T *data; - unsigned int length; - arrayWithLength() { data = NULL; length = 0; } - arrayWithLength(unsigned int elements, bool bClearArray=true) { assert(elements!=0); data = new T[elements]; if(bClearArray){ memset( (void*)data,0,sizeof(T)*elements); } this->length = elements; } + T* data; + unsigned int length; + arrayWithLength() { + data = NULL; + length = 0; + } + arrayWithLength(unsigned int elements, bool bClearArray = true) { + assert(elements != 0); + data = new T[elements]; + if (bClearArray) { + memset((void*)data, 0, sizeof(T) * elements); + } + this->length = elements; + } - // 4J Stu Added this ctor so I static init arrays in the Item derivation tree - arrayWithLength( T data[], unsigned int elements) { this->data = data; this->length = elements; } + // 4J Stu Added this ctor so I static init arrays in the Item derivation + // tree + arrayWithLength(T data[], unsigned int elements) { + this->data = data; + this->length = elements; + } - //~arrayWithLength() { delete[] data; } + //~arrayWithLength() { delete[] data; } - void resize( unsigned int elements ) - { - assert( elements > length ); - T *temp = new T[elements]; - memset( (void*)temp,0,sizeof(T)*elements); + void resize(unsigned int elements) { + assert(elements > length); + T* temp = new T[elements]; + memset((void*)temp, 0, sizeof(T) * elements); - if( data != NULL ) - { - std::copy( data, data+length, temp ); + if (data != NULL) { + std::copy(data, data + length, temp); - delete[] data; - } - data = temp; - length = elements; - } + delete[] data; + } + data = temp; + length = elements; + } - T& operator[](unsigned int i) { return data[i]; } - T operator[](unsigned int i) const { return data[i]; } + T& operator[](unsigned int i) { return data[i]; } + T operator[](unsigned int i) const { return data[i]; } }; // TODO 4J Stu - This looks right, but is it? -template class array2DWithLength -{ - typedef arrayWithLength< T >* _parrayWithLength; +template +class array2DWithLength { + typedef arrayWithLength* _parrayWithLength; + public: - _parrayWithLength *data; - unsigned int length; - array2DWithLength() { data = NULL; length = 0; } - array2DWithLength(unsigned int dimA, unsigned int dimB) - { - data = new _parrayWithLength[dimA]; - this->length = dimA; + _parrayWithLength* data; + unsigned int length; + array2DWithLength() { + data = NULL; + length = 0; + } + array2DWithLength(unsigned int dimA, unsigned int dimB) { + data = new _parrayWithLength[dimA]; + this->length = dimA; - for( unsigned int i = 0; i < length; i++ ) - data[i] = new arrayWithLength(dimB); - } + for (unsigned int i = 0; i < length; i++) + data[i] = new arrayWithLength(dimB); + } - _parrayWithLength& operator[](unsigned int i) { return data[i]; } - _parrayWithLength operator[](unsigned int i) const { return data[i]; } + _parrayWithLength& operator[](unsigned int i) { return data[i]; } + _parrayWithLength operator[](unsigned int i) const { return data[i]; } }; - class Biome; class LevelChunk; class Node; @@ -69,7 +85,7 @@ class Stat; class MobCategory; class File; class Vertex; -class _Polygon; // Renaming as have conflict with Windows Polygon fn +class _Polygon; // Renaming as have conflict with Windows Polygon fn class ServerLevel; class MultiPlayerLevel; class Level; @@ -77,7 +93,7 @@ class LevelRenderer; class WeighedRandomItem; class WeighedTreasure; class Layer; -//class Cube; +// class Cube; class ModelPart; class Enchantment; class ClipChunk; @@ -88,27 +104,27 @@ typedef arrayWithLength charArray; typedef arrayWithLength shortArray; typedef arrayWithLength intArray; typedef arrayWithLength floatArray; -typedef arrayWithLength BiomeArray; -typedef arrayWithLength LevelChunkArray; -typedef array2DWithLength LevelChunk2DArray; -typedef arrayWithLength NodeArray; -typedef arrayWithLength ItemArray; -typedef arrayWithLength TileArray; -typedef arrayWithLength StatArray; -typedef arrayWithLength MobCategoryArray; -typedef arrayWithLength FileArray; -typedef arrayWithLength VertexArray; -typedef arrayWithLength<_Polygon *> PolygonArray; -typedef arrayWithLength ServerLevelArray; -typedef arrayWithLength MultiPlayerLevelArray; -typedef arrayWithLength LevelArray; -typedef arrayWithLength LevelRendererArray; -typedef arrayWithLength WeighedRandomItemArray; -typedef arrayWithLength WeighedTreasureArray; -typedef arrayWithLength< std::shared_ptr > LayerArray; -//typedef arrayWithLength CubeArray; -typedef arrayWithLength ModelPartArray; -typedef arrayWithLength EnchantmentArray; +typedef arrayWithLength BiomeArray; +typedef arrayWithLength LevelChunkArray; +typedef array2DWithLength LevelChunk2DArray; +typedef arrayWithLength NodeArray; +typedef arrayWithLength ItemArray; +typedef arrayWithLength TileArray; +typedef arrayWithLength StatArray; +typedef arrayWithLength MobCategoryArray; +typedef arrayWithLength FileArray; +typedef arrayWithLength VertexArray; +typedef arrayWithLength<_Polygon*> PolygonArray; +typedef arrayWithLength ServerLevelArray; +typedef arrayWithLength MultiPlayerLevelArray; +typedef arrayWithLength LevelArray; +typedef arrayWithLength LevelRendererArray; +typedef arrayWithLength WeighedRandomItemArray; +typedef arrayWithLength WeighedTreasureArray; +typedef arrayWithLength > LayerArray; +// typedef arrayWithLength CubeArray; +typedef arrayWithLength ModelPartArray; +typedef arrayWithLength EnchantmentArray; typedef arrayWithLength ClipChunkArray; #include "../Items/ItemInstance.h" diff --git a/Minecraft.World/Util/Arrays.h b/Minecraft.World/Util/Arrays.h index 4cf2f8060..89e3fcfd5 100644 --- a/Minecraft.World/Util/Arrays.h +++ b/Minecraft.World/Util/Arrays.h @@ -1,23 +1,42 @@ #pragma once - #include "ArrayWithLength.h" -class Arrays -{ +class Arrays { public: - static void fill(doubleArray arr, unsigned int from, unsigned int to, double value) - { assert(from >=0); assert( from <= to ); assert( to <= arr.length ); std::fill( arr.data+from, arr.data+to, value ); } + static void fill(doubleArray arr, unsigned int from, unsigned int to, + double value) { + assert(from >= 0); + assert(from <= to); + assert(to <= arr.length); + std::fill(arr.data + from, arr.data + to, value); + } - static void fill(floatArray arr, unsigned int from, unsigned int to, float value) - { assert(from >=0); assert( from <= to ); assert( to <= arr.length ); std::fill( arr.data+from, arr.data+to, value ); } + static void fill(floatArray arr, unsigned int from, unsigned int to, + float value) { + assert(from >= 0); + assert(from <= to); + assert(to <= arr.length); + std::fill(arr.data + from, arr.data + to, value); + } - static void fill(BiomeArray arr, unsigned int from, unsigned int to, Biome *value) - { assert(from >=0); assert( from <= to ); assert( to <= arr.length ); std::fill( arr.data+from, arr.data+to, value ); } + static void fill(BiomeArray arr, unsigned int from, unsigned int to, + Biome* value) { + assert(from >= 0); + assert(from <= to); + assert(to <= arr.length); + std::fill(arr.data + from, arr.data + to, value); + } - static void fill(byteArray arr, unsigned int from, unsigned int to, uint8_t value) - { assert(from >=0); assert( from <= to ); assert( to <= arr.length ); std::fill( arr.data+from, arr.data+to, value ); } + static void fill(byteArray arr, unsigned int from, unsigned int to, + uint8_t value) { + assert(from >= 0); + assert(from <= to); + assert(to <= arr.length); + std::fill(arr.data + from, arr.data + to, value); + } - static void fill(byteArray arr, uint8_t value) - { std::fill( arr.data, arr.data+arr.length, value ); } + static void fill(byteArray arr, uint8_t value) { + std::fill(arr.data, arr.data + arr.length, value); + } }; diff --git a/Minecraft.World/Util/BasicTypeContainers.cpp b/Minecraft.World/Util/BasicTypeContainers.cpp index d3f3fe8b7..9078477ac 100644 --- a/Minecraft.World/Util/BasicTypeContainers.cpp +++ b/Minecraft.World/Util/BasicTypeContainers.cpp @@ -2,19 +2,18 @@ #include "BasicTypeContainers.h" #include - /* 4J Jev TODO, - this is different to Float::MAX_VALUE, javas floats - seem to actually allow values of infinity which c++ does not. + this is different to Float::MAX_VALUE, javas floats + seem to actually allow values of infinity which c++ does not. */ -//A constant holding the positive infinity of type float. It is equal to the value returned by Float.intBitsToFloat(0x7f800000). +// A constant holding the positive infinity of type float. It is equal to the +// value returned by Float.intBitsToFloat(0x7f800000). const float Float::POSITIVE_INFINITY = 0x7f800000; const float Float::MAX_VALUE = FLT_MAX; const double Double::MAX_VALUE = DBL_MAX; -int Integer::parseInt(std::wstring &str, int radix /* = 10*/) -{ - return wcstol( str.c_str(), NULL, radix ); +int Integer::parseInt(std::wstring& str, int radix /* = 10*/) { + return wcstol(str.c_str(), NULL, radix); } \ No newline at end of file diff --git a/Minecraft.World/Util/BasicTypeContainers.h b/Minecraft.World/Util/BasicTypeContainers.h index aa24e0bc1..0cf134ad5 100644 --- a/Minecraft.World/Util/BasicTypeContainers.h +++ b/Minecraft.World/Util/BasicTypeContainers.h @@ -3,76 +3,54 @@ #include #include - -class Byte -{ +class Byte { public: - static const char MAX_VALUE = CHAR_MAX; - static const char MIN_VALUE = CHAR_MIN; + static const char MAX_VALUE = CHAR_MAX; + static const char MIN_VALUE = CHAR_MIN; }; -class Short -{ +class Short { public: - static const short MAX_VALUE = SHRT_MAX; - static const short MIN_VALUE = SHRT_MIN; + static const short MAX_VALUE = SHRT_MAX; + static const short MIN_VALUE = SHRT_MIN; }; -class Integer -{ +class Integer { public: - static const int MAX_VALUE = INT_MAX; - static int parseInt(std::wstring &str, int radix = 10); + static const int MAX_VALUE = INT_MAX; + static int parseInt(std::wstring& str, int radix = 10); }; -class Float -{ +class Float { public: - static const float MAX_VALUE; - static int floatToIntBits( float value ) - { - return *(int *)&value; - } - static int floatToRawIntBits( float value ) - { - return *(int *)&value; - } + static const float MAX_VALUE; + static int floatToIntBits(float value) { return *(int*)&value; } + static int floatToRawIntBits(float value) { return *(int*)&value; } - static float intBitsToFloat( int bits ) - { - return *(float *)&bits; - } + static float intBitsToFloat(int bits) { return *(float*)&bits; } - static const float POSITIVE_INFINITY; + static const float POSITIVE_INFINITY; }; -class Double -{ +class Double { public: - static const double MAX_VALUE; + static const double MAX_VALUE; - static bool isNaN( double a ) { + static bool isNaN(double a) { #ifdef __PS3__ - return isnan(a); + return isnan(a); #else - return ( a != a ); + return (a != a); #endif - } - static bool isInfinite( double a ) { return false; /*4J TODO*/ } + } + static bool isInfinite(double a) { return false; /*4J TODO*/ } - static double longBitsToDouble( __int64 bits ) - { - return *(double *)&bits; - } + static double longBitsToDouble(__int64 bits) { return *(double*)&bits; } - static __int64 doubleToLongBits( double d ) - { - return *(__int64 *)&d; - } + static __int64 doubleToLongBits(double d) { return *(__int64*)&d; } }; -// 4J Stu - The String class should only be used if we need to use the BaseClass::class type -// As such I have renamed it so that we don't confuse it with places where we should use std::string -class _String -{ -}; +// 4J Stu - The String class should only be used if we need to use the +// BaseClass::class type As such I have renamed it so that we don't confuse it +// with places where we should use std::string +class _String {}; diff --git a/Minecraft.World/Util/BinaryHeap.cpp b/Minecraft.World/Util/BinaryHeap.cpp index 67e0cd4fd..ac1ab1413 100644 --- a/Minecraft.World/Util/BinaryHeap.cpp +++ b/Minecraft.World/Util/BinaryHeap.cpp @@ -5,34 +5,26 @@ #include "BinaryHeap.h" // 4J Jev, add common ctor code. -void BinaryHeap::_init() -{ - heap = NodeArray(1024); - sizeVar = 0; +void BinaryHeap::_init() { + heap = NodeArray(1024); + sizeVar = 0; } -BinaryHeap::BinaryHeap() -{ - _init(); -} +BinaryHeap::BinaryHeap() { _init(); } -BinaryHeap::~BinaryHeap() -{ - delete[] heap.data; -} +BinaryHeap::~BinaryHeap() { delete[] heap.data; } -Node *BinaryHeap::insert(Node *node) -{ - /* if (node->heapIdx >=0) throw new IllegalStateException("OW KNOWS!"); 4J Jev, removed try/catch */ +Node* BinaryHeap::insert(Node* node) { + /* if (node->heapIdx >=0) throw new IllegalStateException("OW KNOWS!"); 4J + * Jev, removed try/catch */ // Expand if necessary. - if (sizeVar == heap.length) - { + if (sizeVar == heap.length) { NodeArray newHeap = NodeArray(sizeVar << 1); System::arraycopy(heap, 0, &newHeap, 0, sizeVar); - delete[] heap.data; + delete[] heap.data; heap = newHeap; } @@ -44,39 +36,27 @@ Node *BinaryHeap::insert(Node *node) return node; } -void BinaryHeap::clear() -{ - sizeVar = 0; -} +void BinaryHeap::clear() { sizeVar = 0; } -Node *BinaryHeap::peek() -{ - return heap[0]; -} +Node* BinaryHeap::peek() { return heap[0]; } -Node *BinaryHeap::pop() -{ - Node *popped = heap[0]; +Node* BinaryHeap::pop() { + Node* popped = heap[0]; heap[0] = heap[--sizeVar]; heap[sizeVar] = NULL; if (sizeVar > 0) downHeap(0); - popped->heapIdx=-1; + popped->heapIdx = -1; return popped; } -void BinaryHeap::remove(Node *node) -{ +void BinaryHeap::remove(Node* node) { // This is what node.heapIdx is for. heap[node->heapIdx] = heap[--sizeVar]; heap[sizeVar] = NULL; - if (sizeVar > node->heapIdx) - { - if (heap[node->heapIdx]->f < node->f) - { + if (sizeVar > node->heapIdx) { + if (heap[node->heapIdx]->f < node->f) { upHeap(node->heapIdx); - } - else - { + } else { downHeap(node->heapIdx); } } @@ -84,97 +64,77 @@ void BinaryHeap::remove(Node *node) node->heapIdx = -1; } -void BinaryHeap::changeCost(Node *node, float newCost) -{ +void BinaryHeap::changeCost(Node* node, float newCost) { float oldCost = node->f; node->f = newCost; - if (newCost < oldCost) - { + if (newCost < oldCost) { upHeap(node->heapIdx); - } - else - { + } else { downHeap(node->heapIdx); } } -int BinaryHeap::size() -{ - return sizeVar; -} +int BinaryHeap::size() { return sizeVar; } -void BinaryHeap::upHeap(int idx) -{ - Node *node = heap[idx]; +void BinaryHeap::upHeap(int idx) { + Node* node = heap[idx]; float cost = node->f; - while (idx > 0) - { + while (idx > 0) { int parentIdx = (idx - 1) >> 1; - Node *parent = heap[parentIdx]; - if (cost < parent->f) - { + Node* parent = heap[parentIdx]; + if (cost < parent->f) { heap[idx] = parent; parent->heapIdx = idx; idx = parentIdx; - } - else break; + } else + break; } heap[idx] = node; node->heapIdx = idx; } -void BinaryHeap::downHeap(int idx) -{ - Node *node = heap[idx]; +void BinaryHeap::downHeap(int idx) { + Node* node = heap[idx]; float cost = node->f; - while (true) - { + while (true) { int leftIdx = 1 + (idx << 1); int rightIdx = leftIdx + 1; if (leftIdx >= sizeVar) break; // We definitely have a left child. - Node *leftNode = heap[leftIdx]; + Node* leftNode = heap[leftIdx]; float leftCost = leftNode->f; // We may have a right child. - Node *rightNode; + Node* rightNode; float rightCost; - if (rightIdx >= sizeVar) - { + if (rightIdx >= sizeVar) { // Only need to compare with left. rightNode = NULL; rightCost = Float::POSITIVE_INFINITY; - } - else - { + } else { rightNode = heap[rightIdx]; rightCost = rightNode->f; } // Find the smallest of the three costs: the corresponding node // should be the parent. - if (leftCost < rightCost) - { - if (leftCost < cost) - { + if (leftCost < rightCost) { + if (leftCost < cost) { heap[idx] = leftNode; leftNode->heapIdx = idx; idx = leftIdx; - } - else break; - } - else - { - if (rightCost < cost) - { + } else + break; + } else { + if (rightCost < cost) { heap[idx] = rightNode; rightNode->heapIdx = idx; idx = rightIdx; - } - else break; + } else + break; } } @@ -182,7 +142,4 @@ void BinaryHeap::downHeap(int idx) node->heapIdx = idx; } -bool BinaryHeap::isEmpty() -{ - return sizeVar==0; -} \ No newline at end of file +bool BinaryHeap::isEmpty() { return sizeVar == 0; } \ No newline at end of file diff --git a/Minecraft.World/Util/BinaryHeap.h b/Minecraft.World/Util/BinaryHeap.h index bb0ed219a..793800d15 100644 --- a/Minecraft.World/Util/BinaryHeap.h +++ b/Minecraft.World/Util/BinaryHeap.h @@ -1,34 +1,32 @@ #pragma once - #include "../Platform/stdafx.h" #include "../AI/Navigation/Node.h" #include "../Platform/System.h" #include "BasicTypeContainers.h" -class BinaryHeap -{ +class BinaryHeap { private: - NodeArray heap; + NodeArray heap; int sizeVar; - // 4J Jev, add common ctor code. - void _init(); + // 4J Jev, add common ctor code. + void _init(); public: - BinaryHeap(); - ~BinaryHeap(); + BinaryHeap(); + ~BinaryHeap(); - Node *insert(Node *node); - void clear(); - Node *peek(); - Node *pop(); - void remove(Node *node); - void changeCost(Node *node, float newCost); + Node* insert(Node* node); + void clear(); + Node* peek(); + Node* pop(); + void remove(Node* node); + void changeCost(Node* node, float newCost); int size(); private: - void upHeap(int idx); + void upHeap(int idx); void downHeap(int idx); public: diff --git a/Minecraft.World/Util/BoundingBox.cpp b/Minecraft.World/Util/BoundingBox.cpp index e6ce72ef9..9492487a9 100644 --- a/Minecraft.World/Util/BoundingBox.cpp +++ b/Minecraft.World/Util/BoundingBox.cpp @@ -3,45 +3,58 @@ #include "Direction.h" #include "JavaMath.h" -BoundingBox::BoundingBox() -{ - // 4J added initialisers - x0 = 0; - y0 = 0; - z0 = 0; - x1 = 0; - y1 = 0; - z1 = 0; +BoundingBox::BoundingBox() { + // 4J added initialisers + x0 = 0; + y0 = 0; + z0 = 0; + x1 = 0; + y1 = 0; + z1 = 0; } -BoundingBox *BoundingBox::getUnknownBox() -{ - return new BoundingBox(INT_MAX, INT_MAX, INT_MAX, INT_MIN, INT_MIN, INT_MIN ); +BoundingBox* BoundingBox::getUnknownBox() { + return new BoundingBox(INT_MAX, INT_MAX, INT_MAX, INT_MIN, INT_MIN, + INT_MIN); } -BoundingBox *BoundingBox::orientBox(int footX, int footY, int footZ, int offX, int offY, int offZ, int width, int height, int depth, int orientation) -{ - switch (orientation) - { - default: - return new BoundingBox(footX + offX, footY + offY, footZ + offZ, footX + width - 1 + offX, footY + height - 1 + offY, footZ + depth - 1 + offZ); - case Direction::NORTH: - // foot is at x0, y0, z1 - return new BoundingBox(footX + offX, footY + offY, footZ - depth + 1 + offZ, footX + width - 1 + offX, footY + height - 1 + offY, footZ + offZ); - case Direction::SOUTH: - // foot is at x0, y0, z0 - return new BoundingBox(footX + offX, footY + offY, footZ + offZ, footX + width - 1 + offX, footY + height - 1 + offY, footZ + depth - 1 + offZ); - case Direction::WEST: - // foot is at x1, y0, z0, but width and depth are flipped - return new BoundingBox(footX - depth + 1 + offZ, footY + offY, footZ + offX, footX + offZ, footY + height - 1 + offY, footZ + width - 1 + offX); - case Direction::EAST: - // foot is at x0, y0, z0, but width and depth are flipped - return new BoundingBox(footX + offZ, footY + offY, footZ + offX, footX + depth - 1 + offZ, footY + height - 1 + offY, footZ + width - 1 + offX); +BoundingBox* BoundingBox::orientBox(int footX, int footY, int footZ, int offX, + int offY, int offZ, int width, int height, + int depth, int orientation) { + switch (orientation) { + default: + return new BoundingBox(footX + offX, footY + offY, footZ + offZ, + footX + width - 1 + offX, + footY + height - 1 + offY, + footZ + depth - 1 + offZ); + case Direction::NORTH: + // foot is at x0, y0, z1 + return new BoundingBox(footX + offX, footY + offY, + footZ - depth + 1 + offZ, + footX + width - 1 + offX, + footY + height - 1 + offY, footZ + offZ); + case Direction::SOUTH: + // foot is at x0, y0, z0 + return new BoundingBox(footX + offX, footY + offY, footZ + offZ, + footX + width - 1 + offX, + footY + height - 1 + offY, + footZ + depth - 1 + offZ); + case Direction::WEST: + // foot is at x1, y0, z0, but width and depth are flipped + return new BoundingBox(footX - depth + 1 + offZ, footY + offY, + footZ + offX, footX + offZ, + footY + height - 1 + offY, + footZ + width - 1 + offX); + case Direction::EAST: + // foot is at x0, y0, z0, but width and depth are flipped + return new BoundingBox(footX + offZ, footY + offY, footZ + offX, + footX + depth - 1 + offZ, + footY + height - 1 + offY, + footZ + width - 1 + offX); } } -BoundingBox::BoundingBox(BoundingBox *other) -{ +BoundingBox::BoundingBox(BoundingBox* other) { this->x0 = other->x0; this->y0 = other->y0; this->z0 = other->z0; @@ -50,8 +63,7 @@ BoundingBox::BoundingBox(BoundingBox *other) this->z1 = other->z1; } -BoundingBox::BoundingBox(int x0, int y0, int z0, int x1, int y1, int z1) -{ +BoundingBox::BoundingBox(int x0, int y0, int z0, int x1, int y1, int z1) { this->x0 = x0; this->y0 = y0; this->z0 = z0; @@ -60,36 +72,34 @@ BoundingBox::BoundingBox(int x0, int y0, int z0, int x1, int y1, int z1) this->z1 = z1; } -BoundingBox::BoundingBox(int x0, int z0, int x1, int z1) -{ +BoundingBox::BoundingBox(int x0, int z0, int x1, int z1) { this->x0 = x0; this->z0 = z0; this->x1 = x1; this->z1 = z1; - // the bounding box for this constructor is limited to world size, - // excluding bedrock level - this->y0 = 1; - this->y1 = 512; + // the bounding box for this constructor is limited to world size, + // excluding bedrock level + this->y0 = 1; + this->y1 = 512; } -bool BoundingBox::intersects(BoundingBox *other) -{ - return !(this->x1 < other->x0 || this->x0 > other->x1 || this->z1 < other->z0 || this->z0 > other->z1 || this->y1 < other->y0 || this->y0 > other->y1); +bool BoundingBox::intersects(BoundingBox* other) { + return !(this->x1 < other->x0 || this->x0 > other->x1 || + this->z1 < other->z0 || this->z0 > other->z1 || + this->y1 < other->y0 || this->y0 > other->y1); } -bool BoundingBox::intersects(int x0, int y0, int z0, int x1, int y1, int z1) -{ - return !(this->x1 < x0 || this->x0 > x1 || this->z1 < z0 || this->z0 > z1 || this->y1 < y0 || this->y0 > y1); +bool BoundingBox::intersects(int x0, int y0, int z0, int x1, int y1, int z1) { + return !(this->x1 < x0 || this->x0 > x1 || this->z1 < z0 || this->z0 > z1 || + this->y1 < y0 || this->y0 > y1); } -bool BoundingBox::intersects(int x0, int z0, int x1, int z1) -{ - return !(this->x1 < x0 || this->x0 > x1 || this->z1 < z0 || this->z0 > z1); +bool BoundingBox::intersects(int x0, int z0, int x1, int z1) { + return !(this->x1 < x0 || this->x0 > x1 || this->z1 < z0 || this->z0 > z1); } -void BoundingBox::expand(BoundingBox *other) -{ +void BoundingBox::expand(BoundingBox* other) { this->x0 = Math::_min(this->x0, other->x0); this->y0 = Math::_min(this->y0, other->y0); this->z0 = Math::_min(this->z0, other->z0); @@ -98,13 +108,11 @@ void BoundingBox::expand(BoundingBox *other) this->z1 = Math::_max(this->z1, other->z1); } -BoundingBox *BoundingBox::getIntersection(BoundingBox *other) -{ - if (!intersects(other)) - { +BoundingBox* BoundingBox::getIntersection(BoundingBox* other) { + if (!intersects(other)) { return NULL; } - BoundingBox *result = new BoundingBox(); + BoundingBox* result = new BoundingBox(); result->x0 = Math::_max(this->x0, other->x0); result->y0 = Math::_max(this->y0, other->y0); result->z0 = Math::_max(this->z0, other->z0); @@ -115,8 +123,7 @@ BoundingBox *BoundingBox::getIntersection(BoundingBox *other) return result; } -void BoundingBox::move(int dx, int dy, int dz) -{ +void BoundingBox::move(int dx, int dy, int dz) { x0 += dx; y0 += dy; z0 += dz; @@ -125,42 +132,24 @@ void BoundingBox::move(int dx, int dy, int dz) z1 += dz; } -bool BoundingBox::isInside(int x, int y, int z) -{ - return (x >= x0 && x <= x1 && z >= z0 && z <= z1 && y >= y0 && y <= y1); +bool BoundingBox::isInside(int x, int y, int z) { + return (x >= x0 && x <= x1 && z >= z0 && z <= z1 && y >= y0 && y <= y1); } -int BoundingBox::getXSpan() -{ - return x1 - x0 + 1; -} +int BoundingBox::getXSpan() { return x1 - x0 + 1; } -int BoundingBox::getYSpan() -{ - return y1 - y0 + 1; -} +int BoundingBox::getYSpan() { return y1 - y0 + 1; } -int BoundingBox::getZSpan() -{ - return z1 - z0 + 1; -} +int BoundingBox::getZSpan() { return z1 - z0 + 1; } -int BoundingBox::getXCenter() -{ - return x0 + (x1 - x0 + 1) / 2; -} +int BoundingBox::getXCenter() { return x0 + (x1 - x0 + 1) / 2; } -int BoundingBox::getYCenter() -{ - return y0 + (y1 - y0 + 1) / 2; -} +int BoundingBox::getYCenter() { return y0 + (y1 - y0 + 1) / 2; } -int BoundingBox::getZCenter() -{ - return z0 + (z1 - z0 + 1) / 2; -} +int BoundingBox::getZCenter() { return z0 + (z1 - z0 + 1) / 2; } -std::wstring BoundingBox::toString() -{ - return L"(" + _toString(x0) + L", " + _toString(y0) + L", " + _toString(z0) + L"; " + _toString(x1) + L", " + _toString(y1) + L", " + _toString(z1) + L")"; +std::wstring BoundingBox::toString() { + return L"(" + _toString(x0) + L", " + _toString(y0) + L", " + + _toString(z0) + L"; " + _toString(x1) + L", " + + _toString(y1) + L", " + _toString(z1) + L")"; } \ No newline at end of file diff --git a/Minecraft.World/Util/BoundingBox.h b/Minecraft.World/Util/BoundingBox.h index 7f3480dec..ccd8afad1 100644 --- a/Minecraft.World/Util/BoundingBox.h +++ b/Minecraft.World/Util/BoundingBox.h @@ -1,31 +1,32 @@ #pragma once -class BoundingBox -{ +class BoundingBox { public: - int x0, y0, z0, x1, y1, z1; + int x0, y0, z0, x1, y1, z1; - BoundingBox(); - static BoundingBox *getUnknownBox(); - static BoundingBox *orientBox(int footX, int footY, int footZ, int offX, int offY, int offZ, int width, int height, int depth, int orientation); - BoundingBox(BoundingBox *other); - BoundingBox(int x0, int y0, int z0, int x1, int y1, int z1); - BoundingBox(int x0, int z0, int x1, int z1); - bool intersects(BoundingBox *other); - bool intersects(int x0, int y0, int z0, int x1, int y1, int z1); + BoundingBox(); + static BoundingBox* getUnknownBox(); + static BoundingBox* orientBox(int footX, int footY, int footZ, int offX, + int offY, int offZ, int width, int height, + int depth, int orientation); + BoundingBox(BoundingBox* other); + BoundingBox(int x0, int y0, int z0, int x1, int y1, int z1); + BoundingBox(int x0, int z0, int x1, int z1); + bool intersects(BoundingBox* other); + bool intersects(int x0, int y0, int z0, int x1, int y1, int z1); - bool intersects(int x0, int z0, int x1, int z1); - void expand(BoundingBox *other); - BoundingBox *getIntersection(BoundingBox *other); - void move(int dx, int dy, int dz); - bool isInside(int x, int y, int z); + bool intersects(int x0, int z0, int x1, int z1); + void expand(BoundingBox* other); + BoundingBox* getIntersection(BoundingBox* other); + void move(int dx, int dy, int dz); + bool isInside(int x, int y, int z); - int getXSpan(); - int getYSpan(); - int getZSpan(); - int getXCenter(); - int getYCenter(); - int getZCenter(); + int getXSpan(); + int getYSpan(); + int getZSpan(); + int getXCenter(); + int getYCenter(); + int getZCenter(); - std::wstring toString(); + std::wstring toString(); }; \ No newline at end of file diff --git a/Minecraft.World/Util/C4JThread.cpp b/Minecraft.World/Util/C4JThread.cpp index b60c27e2b..dbf88da0d 100644 --- a/Minecraft.World/Util/C4JThread.cpp +++ b/Minecraft.World/Util/C4JThread.cpp @@ -1,12 +1,13 @@ #include "../Platform/stdafx.h" - #include "C4JThread.h" #ifdef __PSVITA__ #include "../../Minecraft.Client/Platform/PSVita/PSVitaExtras/ShutdownManager.h" #include "../../Minecraft.Client/Platform/PSVita/PSVitaExtras/PSVitaTLSStorage.h" -// AP - this comes from the low level user_malloc.c file used to overide the default memory functions. These must be called when a thread is started/stopped +// AP - this comes from the low level user_malloc.c file used to overide the +// default memory functions. These must be called when a thread is +// started/stopped extern "C" { extern void user_registerthread(); extern void user_removethread(); @@ -20,1081 +21,1043 @@ std::vector C4JThread::ms_threadList; CRITICAL_SECTION C4JThread::ms_threadListCS; #ifdef _XBOX_ONE - // 4J Stu - On XboxOne the main thread is not the one that does all the static init, so we have to set this up later -C4JThread *C4JThread::m_mainThread = NULL; +// 4J Stu - On XboxOne the main thread is not the one that does all the static +// init, so we have to set this up later +C4JThread* C4JThread::m_mainThread = NULL; -void C4JThread::StaticInit() -{ - m_mainThread = new C4JThread("Main thread"); -} +void C4JThread::StaticInit() { m_mainThread = new C4JThread("Main thread"); } #else -C4JThread C4JThread::m_mainThread("Main thread"); +C4JThread C4JThread::m_mainThread("Main thread"); #endif #ifdef __ORBIS__ __thread SceKernelCpumask C4JThread::m_oldAffinityMask; #endif - #if __PSVITA__ static SceInt32 g_DefaultCPU; static SceInt32 g_DefaultPriority; #endif -C4JThread::C4JThread( C4JThreadStartFunc* startFunc, void* param, const char* threadName, int stackSize/* = 0*/ ) -{ - m_startFunc = startFunc; - m_threadParam = param; - m_stackSize = stackSize; +C4JThread::C4JThread(C4JThreadStartFunc* startFunc, void* param, + const char* threadName, int stackSize /* = 0*/) { + m_startFunc = startFunc; + m_threadParam = param; + m_stackSize = stackSize; - // to match XBox, if the stack size is zero, use the default 64k - if(m_stackSize == 0) - m_stackSize = 65536 * 2; - // make sure it's at least 16K - if(m_stackSize < 16384) - m_stackSize = 16384; + // to match XBox, if the stack size is zero, use the default 64k + if (m_stackSize == 0) m_stackSize = 65536 * 2; + // make sure it's at least 16K + if (m_stackSize < 16384) m_stackSize = 16384; #ifdef __PS3__ - sprintf(m_threadName, "(4J) %s", threadName ); + sprintf(m_threadName, "(4J) %s", threadName); #else - sprintf_s(m_threadName,64, "(4J) %s", threadName ); + sprintf_s(m_threadName, 64, "(4J) %s", threadName); #endif - m_isRunning = false; - m_hasStarted = false; + m_isRunning = false; + m_hasStarted = false; - m_exitCode = STILL_ACTIVE; + m_exitCode = STILL_ACTIVE; #ifdef __PS3__ - m_completionFlag = new Event(Event::e_modeManualClear); - m_threadID = 0; - m_lastSleepTime = 0; - m_priority = 1002; // main thread has priority 1001 + m_completionFlag = new Event(Event::e_modeManualClear); + m_threadID = 0; + m_lastSleepTime = 0; + m_priority = 1002; // main thread has priority 1001 #elif defined __ORBIS__ - m_completionFlag = new Event(Event::e_modeManualClear); - m_threadID = 0; - m_lastSleepTime = 0; - scePthreadAttrInit(&m_threadAttr); - int err = scePthreadAttrSetaffinity(&m_threadAttr, 63); // set the thread affinity to all cores to start with - assert(err == SCE_OK); - m_oldAffinityMask = 0; - m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; + m_completionFlag = new Event(Event::e_modeManualClear); + m_threadID = 0; + m_lastSleepTime = 0; + scePthreadAttrInit(&m_threadAttr); + int err = scePthreadAttrSetaffinity( + &m_threadAttr, + 63); // set the thread affinity to all cores to start with + assert(err == SCE_OK); + m_oldAffinityMask = 0; + m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; #elif defined __PSVITA__ - m_completionFlag = new Event(Event::e_modeManualClear); - m_threadID = 0; - m_lastSleepTime = 0; - m_priority = g_DefaultPriority; - //m_CPUMask = SCE_KERNEL_CPU_MASK_USER_ALL; + m_completionFlag = new Event(Event::e_modeManualClear); + m_threadID = 0; + m_lastSleepTime = 0; + m_priority = g_DefaultPriority; + // m_CPUMask = SCE_KERNEL_CPU_MASK_USER_ALL; - // AP - I had trouble getting the cpu to change once the thread was created so I've hard coded them here - // The main work division is... - // 0 - Main - // 1 - Chunk/Tile Update - // 2 - Server/Audio - // These three can sometimes consume ALL the CPU time so they are set to below average priority so as not to block other critical threads - int CPU = SCE_KERNEL_CPU_MASK_USER_ALL; - if( !strcmp(threadName, "Chunk update") ) - { - CPU = SCE_KERNEL_CPU_MASK_USER_2; - m_priority = g_DefaultPriority + 1; - } - if( !strcmp(threadName, "Server" ) ) - { - CPU = SCE_KERNEL_CPU_MASK_USER_1; - m_priority = g_DefaultPriority + 1; - } - // make sure Tile Update doesn't go on cpu 0 because it will hold up the main thread. And it can't go on cpu 1 because Chunk Update crashes. - if( !strcmp(threadName, "Tile update") ) - { - CPU = SCE_KERNEL_CPU_MASK_USER_1; - } + // AP - I had trouble getting the cpu to change once the thread was created + // so I've hard coded them here The main work division is... 0 - Main 1 - + // Chunk/Tile Update 2 - Server/Audio These three can sometimes consume ALL + // the CPU time so they are set to below average priority so as not to block + // other critical threads + int CPU = SCE_KERNEL_CPU_MASK_USER_ALL; + if (!strcmp(threadName, "Chunk update")) { + CPU = SCE_KERNEL_CPU_MASK_USER_2; + m_priority = g_DefaultPriority + 1; + } + if (!strcmp(threadName, "Server")) { + CPU = SCE_KERNEL_CPU_MASK_USER_1; + m_priority = g_DefaultPriority + 1; + } + // make sure Tile Update doesn't go on cpu 0 because it will hold up the + // main thread. And it can't go on cpu 1 because Chunk Update crashes. + if (!strcmp(threadName, "Tile update")) { + CPU = SCE_KERNEL_CPU_MASK_USER_1; + } - m_threadID = sceKernelCreateThread(m_threadName, entryPoint, g_DefaultPriority, m_stackSize, 0, CPU, NULL); - app.DebugPrintf("***************************** start thread %s **************************\n", m_threadName); + m_threadID = sceKernelCreateThread( + m_threadName, entryPoint, g_DefaultPriority, m_stackSize, 0, CPU, NULL); + app.DebugPrintf( + "***************************** start thread %s " + "**************************\n", + m_threadName); #else - m_threadID = 0; - m_threadHandle = 0; - m_threadHandle = CreateThread(NULL, m_stackSize, entryPoint, this, CREATE_SUSPENDED, &m_threadID); + m_threadID = 0; + m_threadHandle = 0; + m_threadHandle = CreateThread(NULL, m_stackSize, entryPoint, this, + CREATE_SUSPENDED, &m_threadID); #endif - EnterCriticalSection(&ms_threadListCS); - ms_threadList.push_back(this); - LeaveCriticalSection(&ms_threadListCS); + EnterCriticalSection(&ms_threadListCS); + ms_threadList.push_back(this); + LeaveCriticalSection(&ms_threadListCS); } // only used for the main thread -C4JThread::C4JThread( const char* mainThreadName) -{ +C4JThread::C4JThread(const char* mainThreadName) { #ifdef __PSVITA__ - user_registerthread(); + user_registerthread(); #endif - m_startFunc = NULL; - m_threadParam = NULL; - m_stackSize = 0; + m_startFunc = NULL; + m_threadParam = NULL; + m_stackSize = 0; #ifdef __PS3__ - sprintf(m_threadName, "(4J) %s", mainThreadName); + sprintf(m_threadName, "(4J) %s", mainThreadName); #else - sprintf_s(m_threadName, 64, "(4J) %s", mainThreadName); + sprintf_s(m_threadName, 64, "(4J) %s", mainThreadName); #endif - m_isRunning = true; - m_hasStarted = true; - m_lastSleepTime = System::currentTimeMillis(); - - // should be the first thread to be created, so init the static critical section for the threadlist here - InitializeCriticalSection(&ms_threadListCS); + m_isRunning = true; + m_hasStarted = true; + m_lastSleepTime = System::currentTimeMillis(); + // should be the first thread to be created, so init the static critical + // section for the threadlist here + InitializeCriticalSection(&ms_threadListCS); #ifdef __PS3__ - m_completionFlag = new Event(Event::e_modeManualClear); - sys_ppu_thread_get_id(&m_threadID); + m_completionFlag = new Event(Event::e_modeManualClear); + sys_ppu_thread_get_id(&m_threadID); #elif defined __ORBIS__ - m_completionFlag = new Event(Event::e_modeManualClear); - m_threadID = scePthreadSelf(); - m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; + m_completionFlag = new Event(Event::e_modeManualClear); + m_threadID = scePthreadSelf(); + m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; #elif defined __PSVITA__ - m_completionFlag = new Event(Event::e_modeManualClear); - g_DefaultPriority = sceKernelGetThreadCurrentPriority(); - m_threadID = sceKernelGetThreadId(); - int err = sceKernelChangeThreadCpuAffinityMask(m_threadID, SCE_KERNEL_CPU_MASK_USER_0); -// sceKernelChangeThreadPriority(m_threadID, g_DefaultPriority + 1); - g_DefaultCPU = SCE_KERNEL_CPU_MASK_USER_ALL;//sceKernelGetThreadCpuAffinityMask(m_threadID); + m_completionFlag = new Event(Event::e_modeManualClear); + g_DefaultPriority = sceKernelGetThreadCurrentPriority(); + m_threadID = sceKernelGetThreadId(); + int err = sceKernelChangeThreadCpuAffinityMask(m_threadID, + SCE_KERNEL_CPU_MASK_USER_0); + // sceKernelChangeThreadPriority(m_threadID, g_DefaultPriority + 1); + g_DefaultCPU = + SCE_KERNEL_CPU_MASK_USER_ALL; // sceKernelGetThreadCpuAffinityMask(m_threadID); #else - m_threadID = GetCurrentThreadId(); - m_threadHandle = GetCurrentThread(); + m_threadID = GetCurrentThreadId(); + m_threadHandle = GetCurrentThread(); #endif #ifdef _XBOX_ONE - SetThreadName(-1, m_threadName); + SetThreadName(-1, m_threadName); #endif - EnterCriticalSection(&ms_threadListCS); - ms_threadList.push_back(this); - LeaveCriticalSection(&ms_threadListCS); + EnterCriticalSection(&ms_threadListCS); + ms_threadList.push_back(this); + LeaveCriticalSection(&ms_threadListCS); } -C4JThread::~C4JThread() -{ +C4JThread::~C4JThread() { #if defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - delete m_completionFlag; + delete m_completionFlag; #endif #if defined __ORBIS__ - scePthreadJoin(m_threadID, NULL); + scePthreadJoin(m_threadID, NULL); #endif - EnterCriticalSection(&ms_threadListCS); + EnterCriticalSection(&ms_threadListCS); - for( AUTO_VAR(it,ms_threadList.begin()); it != ms_threadList.end(); it++ ) - { - if( (*it) == this ) - { - ms_threadList.erase(it); - LeaveCriticalSection(&ms_threadListCS); - return; - } - } + for (AUTO_VAR(it, ms_threadList.begin()); it != ms_threadList.end(); it++) { + if ((*it) == this) { + ms_threadList.erase(it); + LeaveCriticalSection(&ms_threadListCS); + return; + } + } - LeaveCriticalSection(&ms_threadListCS); + LeaveCriticalSection(&ms_threadListCS); } #ifdef __PS3__ -void C4JThread::entryPoint(uint64_t param) -{ - C4JThread* pThread = (C4JThread*)param; - pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); - pThread->m_completionFlag->Set(); - pThread->m_isRunning = false; - sys_ppu_thread_exit(0); +void C4JThread::entryPoint(uint64_t param) { + C4JThread* pThread = (C4JThread*)param; + pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); + pThread->m_completionFlag->Set(); + pThread->m_isRunning = false; + sys_ppu_thread_exit(0); } #elif defined __ORBIS__ -void * C4JThread::entryPoint(void *param) -{ - C4JThread* pThread = (C4JThread*)param; - pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); - pThread->m_completionFlag->Set(); - pThread->m_isRunning = false; - scePthreadExit(NULL); +void* C4JThread::entryPoint(void* param) { + C4JThread* pThread = (C4JThread*)param; + pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); + pThread->m_completionFlag->Set(); + pThread->m_isRunning = false; + scePthreadExit(NULL); } #elif defined __PSVITA__ struct StrArg { - C4JThread* Thread; + C4JThread* Thread; }; -SceInt32 C4JThread::entryPoint(SceSize argSize, void *pArgBlock) -{ - StrArg *strArg = (StrArg*)pArgBlock; - C4JThread* pThread = strArg->Thread; - user_registerthread(); - pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); - app.DebugPrintf("***************************** thread exit %s **************************\n", pThread->m_threadName); - pThread->m_completionFlag->Set(); - pThread->m_isRunning = false; +SceInt32 C4JThread::entryPoint(SceSize argSize, void* pArgBlock) { + StrArg* strArg = (StrArg*)pArgBlock; + C4JThread* pThread = strArg->Thread; + user_registerthread(); + pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); + app.DebugPrintf( + "***************************** thread exit %s " + "**************************\n", + pThread->m_threadName); + pThread->m_completionFlag->Set(); + pThread->m_isRunning = false; - // AP - make sure we clean up this thread's storage and memory - PSVitaTLSStorage::RemoveThread(pThread->m_threadID); - user_removethread(); + // AP - make sure we clean up this thread's storage and memory + PSVitaTLSStorage::RemoveThread(pThread->m_threadID); + user_removethread(); - sceKernelExitDeleteThread(NULL); + sceKernelExitDeleteThread(NULL); - return pThread->m_exitCode; + return pThread->m_exitCode; } #else -DWORD WINAPI C4JThread::entryPoint(LPVOID lpParam) -{ - C4JThread* pThread = (C4JThread*)lpParam; - SetThreadName(-1, pThread->m_threadName); - pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); - pThread->m_isRunning = false; - return pThread->m_exitCode; +DWORD WINAPI C4JThread::entryPoint(LPVOID lpParam) { + C4JThread* pThread = (C4JThread*)lpParam; + SetThreadName(-1, pThread->m_threadName); + pThread->m_exitCode = (*pThread->m_startFunc)(pThread->m_threadParam); + pThread->m_isRunning = false; + return pThread->m_exitCode; } #endif - - - -void C4JThread::Run() -{ +void C4JThread::Run() { #ifdef __PS3__ - // prio specifies the priority value of the PPU thread within the range from 0 to 3071 where 0 is the highest. - // One of the following values is set to flags: - // 0 - non-joinable non-interrupt thread - // SYS_PPU_THREAD_CREATE_JOINABLE - Create a joinable thread - // SYS_PPU_THREAD_CREATE_INTERRUPT - Create an interrupt thread - uint64_t flags = 0; - int err = sys_ppu_thread_create(&m_threadID, entryPoint, (uint64_t)this, m_priority, m_stackSize, flags, m_threadName); + // prio specifies the priority value of the PPU thread within the + //range from 0 to 3071 where 0 is the highest. + // One of the following values is set to flags: + // 0 - non-joinable non-interrupt thread + // SYS_PPU_THREAD_CREATE_JOINABLE - Create a joinable thread + // SYS_PPU_THREAD_CREATE_INTERRUPT - Create an interrupt thread + uint64_t flags = 0; + int err = + sys_ppu_thread_create(&m_threadID, entryPoint, (uint64_t)this, + m_priority, m_stackSize, flags, m_threadName); #elif defined __ORBIS__ - scePthreadAttrSetstacksize(&m_threadAttr, m_stackSize); - scePthreadAttrSetguardsize(&m_threadAttr, 1024); - int ret = scePthreadCreate(&m_threadID, &m_threadAttr, entryPoint, this, m_threadName); - assert( ret == SCE_OK ); - scePthreadSetprio(m_threadID,m_priority); - scePthreadAttrDestroy(&m_threadAttr); + scePthreadAttrSetstacksize(&m_threadAttr, m_stackSize); + scePthreadAttrSetguardsize(&m_threadAttr, 1024); + int ret = scePthreadCreate(&m_threadID, &m_threadAttr, entryPoint, this, + m_threadName); + assert(ret == SCE_OK); + scePthreadSetprio(m_threadID, m_priority); + scePthreadAttrDestroy(&m_threadAttr); #elif defined __PSVITA__ - StrArg strArg = {this}; -// m_threadID = sceKernelCreateThread(m_threadName, entryPoint, m_priority, m_stackSize, 0, m_CPUMask, NULL); - sceKernelStartThread( m_threadID, sizeof(strArg), &strArg); + StrArg strArg = {this}; + // m_threadID = sceKernelCreateThread(m_threadName, entryPoint, m_priority, + //m_stackSize, 0, m_CPUMask, NULL); + sceKernelStartThread(m_threadID, sizeof(strArg), &strArg); #else - ResumeThread(m_threadHandle); + ResumeThread(m_threadHandle); #endif - m_lastSleepTime = System::currentTimeMillis(); - m_isRunning = true; - m_hasStarted = true; + m_lastSleepTime = System::currentTimeMillis(); + m_isRunning = true; + m_hasStarted = true; } -void C4JThread::SetProcessor( int proc ) -{ +void C4JThread::SetProcessor(int proc) { #ifdef __PS3__ - // does nothing since we only have the 1 processor + // does nothing since we only have the 1 processor #elif defined __ORBIS__ - scePthreadAttrSetaffinity(&m_threadAttr, 1 << proc); + scePthreadAttrSetaffinity(&m_threadAttr, 1 << proc); #elif defined __PSVITA__ - int Proc = proc >> 1; // convert from 360's 3 cores * 2 hardware threads to Vita's 3 cores - int Mask = SCE_KERNEL_CPU_MASK_USER_0 << Proc; - //m_CPUMask = Mask; -// int err = sceKernelChangeThreadCpuAffinityMask(m_threadID, Mask); - int Newmask = sceKernelGetThreadCpuAffinityMask(m_threadID); - app.DebugPrintf("***************************** set thread proc %s %d %d %d **************************\n", m_threadName, proc, Mask, Newmask); + int Proc = + proc >> + 1; // convert from 360's 3 cores * 2 hardware threads to Vita's 3 cores + int Mask = SCE_KERNEL_CPU_MASK_USER_0 << Proc; + // m_CPUMask = Mask; + // int err = sceKernelChangeThreadCpuAffinityMask(m_threadID, Mask); + int Newmask = sceKernelGetThreadCpuAffinityMask(m_threadID); + app.DebugPrintf( + "***************************** set thread proc %s %d %d %d " + "**************************\n", + m_threadName, proc, Mask, Newmask); #elif defined _DURANGO - SetThreadAffinityMask(m_threadHandle, 1 << proc ); + SetThreadAffinityMask(m_threadHandle, 1 << proc); #else - XSetThreadProcessor( m_threadHandle, proc); + XSetThreadProcessor(m_threadHandle, proc); #endif } -void C4JThread::SetPriority( int priority ) -{ +void C4JThread::SetPriority(int priority) { #ifdef __PS3__ - switch(priority) - { - case THREAD_PRIORITY_LOWEST: m_priority = 1003; break; - case THREAD_PRIORITY_BELOW_NORMAL: m_priority = 1002; break; - case THREAD_PRIORITY_NORMAL: m_priority = 1001; break; // same as main thread - case THREAD_PRIORITY_ABOVE_NORMAL: m_priority = 1000; break; - case THREAD_PRIORITY_HIGHEST: m_priority = 999; break; - } - if(m_threadID != 0) - sys_ppu_thread_set_priority(m_threadID, m_priority); - //int erro = sys_ppu_thread_set_priority(m_threadID, priority); + switch (priority) { + case THREAD_PRIORITY_LOWEST: + m_priority = 1003; + break; + case THREAD_PRIORITY_BELOW_NORMAL: + m_priority = 1002; + break; + case THREAD_PRIORITY_NORMAL: + m_priority = 1001; + break; // same as main thread + case THREAD_PRIORITY_ABOVE_NORMAL: + m_priority = 1000; + break; + case THREAD_PRIORITY_HIGHEST: + m_priority = 999; + break; + } + if (m_threadID != 0) sys_ppu_thread_set_priority(m_threadID, m_priority); + // int erro = sys_ppu_thread_set_priority(m_threadID, priority); #elif defined __ORBIS__ - switch(priority) - { - case THREAD_PRIORITY_LOWEST: m_priority = SCE_KERNEL_PRIO_FIFO_LOWEST; break; - case THREAD_PRIORITY_BELOW_NORMAL: m_priority = SCE_KERNEL_PRIO_FIFO_LOWEST + ((SCE_KERNEL_PRIO_FIFO_DEFAULT-SCE_KERNEL_PRIO_FIFO_LOWEST)/2); break; - case THREAD_PRIORITY_NORMAL: m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; break; // same as main thread - case THREAD_PRIORITY_ABOVE_NORMAL: m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT + ((SCE_KERNEL_PRIO_FIFO_HIGHEST-SCE_KERNEL_PRIO_FIFO_DEFAULT)/2); break; - case THREAD_PRIORITY_HIGHEST: m_priority = SCE_KERNEL_PRIO_FIFO_HIGHEST; break; - } + switch (priority) { + case THREAD_PRIORITY_LOWEST: + m_priority = SCE_KERNEL_PRIO_FIFO_LOWEST; + break; + case THREAD_PRIORITY_BELOW_NORMAL: + m_priority = + SCE_KERNEL_PRIO_FIFO_LOWEST + + ((SCE_KERNEL_PRIO_FIFO_DEFAULT - SCE_KERNEL_PRIO_FIFO_LOWEST) / + 2); + break; + case THREAD_PRIORITY_NORMAL: + m_priority = SCE_KERNEL_PRIO_FIFO_DEFAULT; + break; // same as main thread + case THREAD_PRIORITY_ABOVE_NORMAL: + m_priority = + SCE_KERNEL_PRIO_FIFO_DEFAULT + + ((SCE_KERNEL_PRIO_FIFO_HIGHEST - SCE_KERNEL_PRIO_FIFO_DEFAULT) / + 2); + break; + case THREAD_PRIORITY_HIGHEST: + m_priority = SCE_KERNEL_PRIO_FIFO_HIGHEST; + break; + } - if( m_threadID != 0 ) - { - scePthreadSetprio(m_threadID,m_priority); - } + if (m_threadID != 0) { + scePthreadSetprio(m_threadID, m_priority); + } #elif defined __PSVITA__ - int Mid = g_DefaultPriority;//(SCE_KERNEL_LOWEST_PRIORITY_USER + SCE_KERNEL_HIGHEST_PRIORITY_USER) / 2; - switch(priority) - { - case THREAD_PRIORITY_LOWEST: - m_priority = SCE_KERNEL_LOWEST_PRIORITY_USER; - break; - case THREAD_PRIORITY_BELOW_NORMAL: - m_priority = Mid + 1; - break; - case THREAD_PRIORITY_NORMAL: - m_priority = Mid; - break; // same as main thread - case THREAD_PRIORITY_ABOVE_NORMAL: - m_priority = Mid - 1; - break; - case THREAD_PRIORITY_HIGHEST: - m_priority = SCE_KERNEL_HIGHEST_PRIORITY_USER; - break; - } + int Mid = g_DefaultPriority; //(SCE_KERNEL_LOWEST_PRIORITY_USER + + //SCE_KERNEL_HIGHEST_PRIORITY_USER) / 2; + switch (priority) { + case THREAD_PRIORITY_LOWEST: + m_priority = SCE_KERNEL_LOWEST_PRIORITY_USER; + break; + case THREAD_PRIORITY_BELOW_NORMAL: + m_priority = Mid + 1; + break; + case THREAD_PRIORITY_NORMAL: + m_priority = Mid; + break; // same as main thread + case THREAD_PRIORITY_ABOVE_NORMAL: + m_priority = Mid - 1; + break; + case THREAD_PRIORITY_HIGHEST: + m_priority = SCE_KERNEL_HIGHEST_PRIORITY_USER; + break; + } -// sceKernelChangeThreadPriority(m_threadID, m_priority); - app.DebugPrintf("***************************** set thread prio %s %d %d **************************\n", m_threadName, priority, m_priority); + // sceKernelChangeThreadPriority(m_threadID, m_priority); + app.DebugPrintf( + "***************************** set thread prio %s %d %d " + "**************************\n", + m_threadName, priority, m_priority); #else - SetThreadPriority(m_threadHandle, priority); -#endif // __PS3__ + SetThreadPriority(m_threadHandle, priority); +#endif // __PS3__ } -DWORD C4JThread::WaitForCompletion( int timeoutMs ) -{ +DWORD C4JThread::WaitForCompletion(int timeoutMs) { #ifdef __PS3__ - if(timeoutMs == INFINITE) - timeoutMs = SYS_NO_TIMEOUT ; - return m_completionFlag->WaitForSignal(timeoutMs); + if (timeoutMs == INFINITE) timeoutMs = SYS_NO_TIMEOUT; + return m_completionFlag->WaitForSignal(timeoutMs); #elif defined __ORBIS__ - return m_completionFlag->WaitForSignal( timeoutMs ); + return m_completionFlag->WaitForSignal(timeoutMs); #elif defined __PSVITA__ - return m_completionFlag->WaitForSignal( timeoutMs ); + return m_completionFlag->WaitForSignal(timeoutMs); /* SceUInt32 Timeout = timeoutMs * 1000; - SceInt32 err = sceKernelWaitThreadEnd(m_threadID, &m_exitCode, &Timeout); - if( err == 0 ) - { - return m_exitCode; - } - else - { - if( err == SCE_KERNEL_ERROR_WAIT_TIMEOUT ) - { - return WAIT_TIMEOUT; - } - else - { - // AP - not sure what to do here - return 0; - } - }*/ + SceInt32 err = sceKernelWaitThreadEnd(m_threadID, &m_exitCode, + &Timeout); if( err == 0 ) + { + return m_exitCode; + } + else + { + if( err == SCE_KERNEL_ERROR_WAIT_TIMEOUT ) + { + return WAIT_TIMEOUT; + } + else + { + // AP - not sure what to do here + return 0; + } + }*/ // return m_exitCode; #else - return WaitForSingleObject(m_threadHandle, timeoutMs); -#endif // __PS3__ + return WaitForSingleObject(m_threadHandle, timeoutMs); +#endif // __PS3__ } -int C4JThread::GetExitCode() -{ -#if defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - return m_exitCode; +int C4JThread::GetExitCode() { +#if defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ + return m_exitCode; #else - DWORD exitcode = 0; - GetExitCodeThread(m_threadHandle, &exitcode); + DWORD exitcode = 0; + GetExitCodeThread(m_threadHandle, &exitcode); - return *((int *)&exitcode); + return *((int*)&exitcode); #endif } -void C4JThread::Sleep( int millisecs ) -{ +void C4JThread::Sleep(int millisecs) { #ifdef __PS3__ - if(millisecs == 0) - { - // https://ps3.scedev.net/forums/thread/116470/ - // "sys_timer_usleep(0) does not yield the CPU." - sys_ppu_thread_yield(); - } - else - sys_timer_usleep(millisecs * 1000); + if (millisecs == 0) { + // https://ps3.scedev.net/forums/thread/116470/ + // "sys_timer_usleep(0) does not yield the CPU." + sys_ppu_thread_yield(); + } else + sys_timer_usleep(millisecs * 1000); #elif defined __ORBIS__ - sceKernelUsleep(((SceKernelUseconds)millisecs) * 1000); + sceKernelUsleep(((SceKernelUseconds)millisecs) * 1000); #elif defined __PSVITA__ - // 4J Stu - 0 is an error, so add a tiny sleep when we just want to yield - sceKernelDelayThread(millisecs * 1000 + 1); + // 4J Stu - 0 is an error, so add a tiny sleep when we just want to yield + sceKernelDelayThread(millisecs * 1000 + 1); #else - ::Sleep(millisecs); -#endif // __PS3__ + ::Sleep(millisecs); +#endif // __PS3__ } -C4JThread* C4JThread::getCurrentThread() -{ +C4JThread* C4JThread::getCurrentThread() { #ifdef __PS3__ - sys_ppu_thread_t currThreadID; - sys_ppu_thread_get_id(&currThreadID); + sys_ppu_thread_t currThreadID; + sys_ppu_thread_get_id(&currThreadID); #elif defined __ORBIS__ - ScePthread currThreadID = scePthreadSelf(); + ScePthread currThreadID = scePthreadSelf(); #elif defined __PSVITA__ - SceUID currThreadID = sceKernelGetThreadId(); + SceUID currThreadID = sceKernelGetThreadId(); #else - DWORD currThreadID = GetCurrentThreadId(); -#endif //__PS3__ - EnterCriticalSection(&ms_threadListCS); + DWORD currThreadID = GetCurrentThreadId(); +#endif //__PS3__ + EnterCriticalSection(&ms_threadListCS); - for(int i=0;im_threadID) - { - LeaveCriticalSection(&ms_threadListCS); - return ms_threadList[i]; - } - } + for (int i = 0; i < ms_threadList.size(); i++) { + if (currThreadID == ms_threadList[i]->m_threadID) { + LeaveCriticalSection(&ms_threadListCS); + return ms_threadList[i]; + } + } - LeaveCriticalSection(&ms_threadListCS); + LeaveCriticalSection(&ms_threadListCS); - return NULL; + return NULL; } -bool C4JThread::isMainThread() -{ +bool C4JThread::isMainThread() { #ifdef _XBOX_ONE - return getCurrentThread() == m_mainThread; + return getCurrentThread() == m_mainThread; #else - return getCurrentThread() == &m_mainThread; + return getCurrentThread() == &m_mainThread; #endif } -C4JThread::Event::Event(EMode mode/* = e_modeAutoClear*/) -{ - m_mode = mode; +C4JThread::Event::Event(EMode mode /* = e_modeAutoClear*/) { + m_mode = mode; #ifdef __PS3__ - sys_event_flag_attribute_t attr; - // default values taken from sys_event_flag_attribute_initialize - attr.attr_protocol = SYS_SYNC_PRIORITY; - attr.attr_pshared = SYS_SYNC_NOT_PROCESS_SHARED; - attr.key = 0; - attr.flags = 0; - attr.type = SYS_SYNC_WAITER_SINGLE; - attr.name[0] = '\0'; - sys_event_flag_attribute_initialize(attr); - - int err = sys_event_flag_create(&m_event, &attr, 0); + sys_event_flag_attribute_t attr; + // default values taken from sys_event_flag_attribute_initialize + attr.attr_protocol = SYS_SYNC_PRIORITY; + attr.attr_pshared = SYS_SYNC_NOT_PROCESS_SHARED; + attr.key = 0; + attr.flags = 0; + attr.type = SYS_SYNC_WAITER_SINGLE; + attr.name[0] = '\0'; + sys_event_flag_attribute_initialize(attr); + + int err = sys_event_flag_create(&m_event, &attr, 0); #elif defined __ORBIS__ - char name[1] = {0}; - sceKernelCreateEventFlag( &m_event, name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); + char name[1] = {0}; + sceKernelCreateEventFlag( + &m_event, name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, + 0, NULL); #elif defined __PSVITA__ - char name[1] = {0}; - m_event = sceKernelCreateEventFlag( name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); + char name[1] = {0}; + m_event = sceKernelCreateEventFlag( + name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); #else - m_event = CreateEvent( NULL, (m_mode == e_modeManualClear), FALSE, NULL ); -#endif //__PS3__ + m_event = CreateEvent(NULL, (m_mode == e_modeManualClear), FALSE, NULL); +#endif //__PS3__ } - -C4JThread::Event::~Event() -{ +C4JThread::Event::~Event() { #ifdef __PS3__ - sys_event_flag_destroy(m_event); + sys_event_flag_destroy(m_event); #elif defined __ORBIS__ - sceKernelDeleteEventFlag(m_event); + sceKernelDeleteEventFlag(m_event); #elif defined __PSVITA__ - sceKernelDeleteEventFlag(m_event); + sceKernelDeleteEventFlag(m_event); #else - CloseHandle( m_event ); -#endif // __PS3__ + CloseHandle(m_event); +#endif // __PS3__ } - -void C4JThread::Event::Set() -{ +void C4JThread::Event::Set() { #ifdef __PS3__ - int err =sys_event_flag_set(m_event, 1); + int err = sys_event_flag_set(m_event, 1); #elif defined __ORBIS__ - sceKernelSetEventFlag(m_event, 1); + sceKernelSetEventFlag(m_event, 1); #elif defined __PSVITA__ - sceKernelSetEventFlag(m_event, 1); + sceKernelSetEventFlag(m_event, 1); #else - SetEvent(m_event); -#endif //__PS3__ + SetEvent(m_event); +#endif //__PS3__ } -void C4JThread::Event::Clear() -{ +void C4JThread::Event::Clear() { #ifdef __PS3__ - int err =sys_event_flag_clear(m_event, ~(1)); + int err = sys_event_flag_clear(m_event, ~(1)); #elif defined __ORBIS__ - sceKernelClearEventFlag(m_event, ~(1)); + sceKernelClearEventFlag(m_event, ~(1)); #elif defined __PSVITA__ - sceKernelClearEventFlag(m_event, ~1); + sceKernelClearEventFlag(m_event, ~1); #else - ResetEvent(m_event); -#endif //__PS3__ + ResetEvent(m_event); +#endif //__PS3__ } -DWORD C4JThread::Event::WaitForSignal( int timeoutMs ) -{ +DWORD C4JThread::Event::WaitForSignal(int timeoutMs) { #ifdef __PS3__ - if(timeoutMs == INFINITE) - timeoutMs = SYS_NO_TIMEOUT ; - int timoutMicrosecs = timeoutMs * 1000; - uint32_t mode = SYS_EVENT_FLAG_WAIT_AND; - if(m_mode == e_modeAutoClear) - mode |= SYS_EVENT_FLAG_WAIT_CLEAR; - int err = sys_event_flag_wait(m_event, 1, mode, 0, timoutMicrosecs); + if (timeoutMs == INFINITE) timeoutMs = SYS_NO_TIMEOUT; + int timoutMicrosecs = timeoutMs * 1000; + uint32_t mode = SYS_EVENT_FLAG_WAIT_AND; + if (m_mode == e_modeAutoClear) mode |= SYS_EVENT_FLAG_WAIT_CLEAR; + int err = sys_event_flag_wait(m_event, 1, mode, 0, timoutMicrosecs); - switch(err) - { - case CELL_OK: return WAIT_OBJECT_0; - case ETIMEDOUT: return WAIT_TIMEOUT; - case ECANCELED: return WAIT_ABANDONED; - default: return WAIT_FAILED; - } + switch (err) { + case CELL_OK: + return WAIT_OBJECT_0; + case ETIMEDOUT: + return WAIT_TIMEOUT; + case ECANCELED: + return WAIT_ABANDONED; + default: + return WAIT_FAILED; + } #elif defined __ORBIS__ - SceKernelUseconds timeoutMicrosecs; - SceKernelUseconds *pTimeoutMicrosecs; - if( timeoutMs == INFINITE ) - { - pTimeoutMicrosecs = NULL; - } - else - { - timeoutMicrosecs = ((SceKernelUseconds)timeoutMs) * 1000; - pTimeoutMicrosecs = &timeoutMicrosecs; - } - uint32_t waitMode = SCE_KERNEL_EVF_WAITMODE_AND; - if(m_mode == e_modeAutoClear) - { - waitMode |= SCE_KERNEL_EVF_WAITMODE_CLEAR_PAT; - } - int err = sceKernelWaitEventFlag(m_event, 1, waitMode, NULL, pTimeoutMicrosecs); - switch(err) - { - case SCE_OK: return WAIT_OBJECT_0; - case SCE_KERNEL_ERROR_ETIMEDOUT: return WAIT_TIMEOUT; - case SCE_KERNEL_ERROR_ECANCELED: return WAIT_ABANDONED; - default: return WAIT_FAILED; - } + SceKernelUseconds timeoutMicrosecs; + SceKernelUseconds* pTimeoutMicrosecs; + if (timeoutMs == INFINITE) { + pTimeoutMicrosecs = NULL; + } else { + timeoutMicrosecs = ((SceKernelUseconds)timeoutMs) * 1000; + pTimeoutMicrosecs = &timeoutMicrosecs; + } + uint32_t waitMode = SCE_KERNEL_EVF_WAITMODE_AND; + if (m_mode == e_modeAutoClear) { + waitMode |= SCE_KERNEL_EVF_WAITMODE_CLEAR_PAT; + } + int err = + sceKernelWaitEventFlag(m_event, 1, waitMode, NULL, pTimeoutMicrosecs); + switch (err) { + case SCE_OK: + return WAIT_OBJECT_0; + case SCE_KERNEL_ERROR_ETIMEDOUT: + return WAIT_TIMEOUT; + case SCE_KERNEL_ERROR_ECANCELED: + return WAIT_ABANDONED; + default: + return WAIT_FAILED; + } #elif defined __PSVITA__ - SceUInt32 timeoutMicrosecs; - SceUInt32 *pTimeoutMicrosecs; - if( timeoutMs == INFINITE ) - { - pTimeoutMicrosecs = NULL; - } - else - { - timeoutMicrosecs = ((SceInt32)timeoutMs) * 1000; - pTimeoutMicrosecs = &timeoutMicrosecs; - } - uint32_t waitMode = SCE_KERNEL_EVF_WAITMODE_AND; - if(m_mode == e_modeAutoClear) - { - waitMode |= SCE_KERNEL_EVF_WAITMODE_CLEAR_ALL; - } - int err = sceKernelWaitEventFlag(m_event, 1, waitMode, NULL, pTimeoutMicrosecs); - switch(err) - { - case SCE_OK: return WAIT_OBJECT_0; - case SCE_KERNEL_ERROR_WAIT_TIMEOUT: return WAIT_TIMEOUT; - case SCE_KERNEL_ERROR_WAIT_CANCEL: return WAIT_ABANDONED; - default: return WAIT_FAILED; - } + SceUInt32 timeoutMicrosecs; + SceUInt32* pTimeoutMicrosecs; + if (timeoutMs == INFINITE) { + pTimeoutMicrosecs = NULL; + } else { + timeoutMicrosecs = ((SceInt32)timeoutMs) * 1000; + pTimeoutMicrosecs = &timeoutMicrosecs; + } + uint32_t waitMode = SCE_KERNEL_EVF_WAITMODE_AND; + if (m_mode == e_modeAutoClear) { + waitMode |= SCE_KERNEL_EVF_WAITMODE_CLEAR_ALL; + } + int err = + sceKernelWaitEventFlag(m_event, 1, waitMode, NULL, pTimeoutMicrosecs); + switch (err) { + case SCE_OK: + return WAIT_OBJECT_0; + case SCE_KERNEL_ERROR_WAIT_TIMEOUT: + return WAIT_TIMEOUT; + case SCE_KERNEL_ERROR_WAIT_CANCEL: + return WAIT_ABANDONED; + default: + return WAIT_FAILED; + } #else - return WaitForSingleObject(m_event, timeoutMs); -#endif // __PS3__ + return WaitForSingleObject(m_event, timeoutMs); +#endif // __PS3__ } -C4JThread::EventArray::EventArray( int size, EMode mode/* = e_modeAutoClear*/) -{ - assert(size<32); - m_size = size; - m_mode = mode; +C4JThread::EventArray::EventArray(int size, EMode mode /* = e_modeAutoClear*/) { + assert(size < 32); + m_size = size; + m_mode = mode; #ifdef __PS3__ - sys_event_flag_attribute_t attr; - // default values taken from sys_event_flag_attribute_initialize - attr.attr_protocol = SYS_SYNC_PRIORITY; - attr.attr_pshared = SYS_SYNC_NOT_PROCESS_SHARED; - attr.key = 0; - attr.flags = 0; - attr.type = SYS_SYNC_WAITER_SINGLE; - attr.name[0] = '\0'; - sys_event_flag_attribute_initialize(attr); - int err = sys_event_flag_create(&m_events, &attr, 0); - assert(err == CELL_OK); + sys_event_flag_attribute_t attr; + // default values taken from sys_event_flag_attribute_initialize + attr.attr_protocol = SYS_SYNC_PRIORITY; + attr.attr_pshared = SYS_SYNC_NOT_PROCESS_SHARED; + attr.key = 0; + attr.flags = 0; + attr.type = SYS_SYNC_WAITER_SINGLE; + attr.name[0] = '\0'; + sys_event_flag_attribute_initialize(attr); + int err = sys_event_flag_create(&m_events, &attr, 0); + assert(err == CELL_OK); #elif defined __ORBIS__ - char name[1] = {0}; - sceKernelCreateEventFlag( &m_events, name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); + char name[1] = {0}; + sceKernelCreateEventFlag( + &m_events, name, + SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); #elif defined __PSVITA__ - char name[1] = {0}; - m_events = sceKernelCreateEventFlag( name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); + char name[1] = {0}; + m_events = sceKernelCreateEventFlag( + name, SCE_KERNEL_EVF_ATTR_TH_FIFO | SCE_KERNEL_EVF_ATTR_MULTI, 0, NULL); #else - m_events = new HANDLE[size]; - for(int i=0;i= 0) - m_thread->SetProcessor(m_processor); - if(m_priority != THREAD_PRIORITY_HIGHEST+1) - m_thread->SetPriority(m_priority); - m_thread->Run(); +void C4JThread::EventQueue::init() { + m_startEvent = new C4JThread::EventArray(1); + m_finishedEvent = new C4JThread::Event(); + InitializeCriticalSection(&m_critSect); + m_thread = new C4JThread(threadFunc, this, m_threadName); + if (m_processor >= 0) m_thread->SetProcessor(m_processor); + if (m_priority != THREAD_PRIORITY_HIGHEST + 1) + m_thread->SetPriority(m_priority); + m_thread->Run(); } -void C4JThread::EventQueue::sendEvent( Level* pLevel ) -{ - if(m_thread == NULL) - init(); - EnterCriticalSection(&m_critSect); - m_queue.push(pLevel); - m_startEvent->Set(0); - m_finishedEvent->Clear(); - LeaveCriticalSection(&m_critSect); +void C4JThread::EventQueue::sendEvent(Level* pLevel) { + if (m_thread == NULL) init(); + EnterCriticalSection(&m_critSect); + m_queue.push(pLevel); + m_startEvent->Set(0); + m_finishedEvent->Clear(); + LeaveCriticalSection(&m_critSect); } -void C4JThread::EventQueue::waitForFinish() -{ - if(m_thread == NULL) - init(); - EnterCriticalSection(&m_critSect); - if(m_queue.empty()) - { - LeaveCriticalSection((&m_critSect)); - return; - } - LeaveCriticalSection((&m_critSect)); - m_finishedEvent->WaitForSignal(INFINITE); +void C4JThread::EventQueue::waitForFinish() { + if (m_thread == NULL) init(); + EnterCriticalSection(&m_critSect); + if (m_queue.empty()) { + LeaveCriticalSection((&m_critSect)); + return; + } + LeaveCriticalSection((&m_critSect)); + m_finishedEvent->WaitForSignal(INFINITE); } -int C4JThread::EventQueue::threadFunc( void* lpParam ) -{ - EventQueue* p = (EventQueue*)lpParam; - p->threadPoll(); - return 0; +int C4JThread::EventQueue::threadFunc(void* lpParam) { + EventQueue* p = (EventQueue*)lpParam; + p->threadPoll(); + return 0; } -void C4JThread::EventQueue::threadPoll() -{ - ShutdownManager::HasStarted(ShutdownManager::eEventQueueThreads, m_startEvent); +void C4JThread::EventQueue::threadPoll() { + ShutdownManager::HasStarted(ShutdownManager::eEventQueueThreads, + m_startEvent); - if(m_threadInitFunc) - m_threadInitFunc(); + if (m_threadInitFunc) m_threadInitFunc(); - while(ShutdownManager::ShouldRun(ShutdownManager::eEventQueueThreads)) - { + while (ShutdownManager::ShouldRun(ShutdownManager::eEventQueueThreads)) { + DWORD err = m_startEvent->WaitForAny(INFINITE); + if (err == WAIT_OBJECT_0) { + bool bListEmpty = true; + do { + EnterCriticalSection(&m_critSect); + void* updateParam = m_queue.front(); + LeaveCriticalSection(&m_critSect); - DWORD err = m_startEvent->WaitForAny(INFINITE); - if(err == WAIT_OBJECT_0) - { - bool bListEmpty = true; - do - { - EnterCriticalSection(&m_critSect); - void* updateParam = m_queue.front(); - LeaveCriticalSection(&m_critSect); + m_updateFunc(updateParam); - m_updateFunc(updateParam); + EnterCriticalSection(&m_critSect); + m_queue.pop(); + bListEmpty = m_queue.empty(); + if (bListEmpty) { + m_finishedEvent->Set(); + } + LeaveCriticalSection(&m_critSect); - EnterCriticalSection(&m_critSect); - m_queue.pop(); - bListEmpty = m_queue.empty(); - if(bListEmpty) - { - m_finishedEvent->Set(); - } - LeaveCriticalSection(&m_critSect); + } while (!bListEmpty); + } + }; - } while(!bListEmpty); - } - }; - - ShutdownManager::HasFinished(ShutdownManager::eEventQueueThreads); + ShutdownManager::HasFinished(ShutdownManager::eEventQueueThreads); } - #ifdef __ORBIS__ -void C4JThread::PushAffinityAllCores() -{ - assert(m_oldAffinityMask == 0); - int err; - ScePthread currThreadID = scePthreadSelf(); - err = scePthreadGetaffinity(currThreadID, &m_oldAffinityMask); - assert(err == SCE_OK); - err = scePthreadSetaffinity(currThreadID, 63); - assert(err == SCE_OK); - - +void C4JThread::PushAffinityAllCores() { + assert(m_oldAffinityMask == 0); + int err; + ScePthread currThreadID = scePthreadSelf(); + err = scePthreadGetaffinity(currThreadID, &m_oldAffinityMask); + assert(err == SCE_OK); + err = scePthreadSetaffinity(currThreadID, 63); + assert(err == SCE_OK); } -void C4JThread::PopAffinity() -{ - int err; - ScePthread currThreadID = scePthreadSelf(); - err = scePthreadSetaffinity(currThreadID, m_oldAffinityMask); - m_oldAffinityMask = 0; - assert(err == SCE_OK); +void C4JThread::PopAffinity() { + int err; + ScePthread currThreadID = scePthreadSelf(); + err = scePthreadSetaffinity(currThreadID, m_oldAffinityMask); + m_oldAffinityMask = 0; + assert(err == SCE_OK); } -#endif // __ORBIS__ \ No newline at end of file +#endif // __ORBIS__ \ No newline at end of file diff --git a/Minecraft.World/Util/C4JThread.h b/Minecraft.World/Util/C4JThread.h index 9a303c7b5..1b4abf6bd 100644 --- a/Minecraft.World/Util/C4JThread.h +++ b/Minecraft.World/Util/C4JThread.h @@ -1,7 +1,7 @@ #pragma once #include -typedef int (C4JThreadStartFunc)(void* lpThreadParameter); +typedef int(C4JThreadStartFunc)(void* lpThreadParameter); class Level; @@ -27,7 +27,7 @@ class Level; #define CPU_CORE_CHUNK_REBUILD_C 5 #define CPU_CORE_SAVE_THREAD_C 5 -#define CPU_CORE_LEADERBOARDS 5 // Orbis only +#define CPU_CORE_LEADERBOARDS 5 // Orbis only #else @@ -50,176 +50,169 @@ class Level; #define CPU_CORE_CHUNK_REBUILD_C 5 #define CPU_CORE_SAVE_THREAD_C 5 -#define CPU_CORE_LEADERBOARDS 5 // Sony only +#define CPU_CORE_LEADERBOARDS 5 // Sony only #endif -class C4JThread -{ +class C4JThread { public: + class Event { + public: + enum EMode { e_modeAutoClear, e_modeManualClear }; + Event(EMode mode = e_modeAutoClear); + ~Event(); + void Set(); + void Clear(); + DWORD WaitForSignal(int timeoutMs); - class Event - { - public: - enum EMode - { - e_modeAutoClear, - e_modeManualClear - }; - Event(EMode mode = e_modeAutoClear); - ~Event(); - void Set(); - void Clear(); - DWORD WaitForSignal(int timeoutMs); - - private: - EMode m_mode; - #ifdef __PS3__ - sys_event_flag_t m_event; - #elif defined __ORBIS__ - SceKernelEventFlag m_event; - #elif defined __PSVITA__ - SceUID m_event; - #else - HANDLE m_event; - #endif // __PS3__ - }; - - class EventArray - { - public: - enum EMode - { - e_modeAutoClear, - e_modeManualClear - }; - - EventArray(int size, EMode mode = e_modeAutoClear); - - void Set(int index); - void Clear(int index); - void SetAll(); - void ClearAll(); - DWORD WaitForAll(int timeoutMs); - DWORD WaitForAny(int timeoutMs); - DWORD WaitForSingle(int index, int timeoutMs); + private: + EMode m_mode; #ifdef __PS3__ - void Cancel(); + sys_event_flag_t m_event; +#elif defined __ORBIS__ + SceKernelEventFlag m_event; +#elif defined __PSVITA__ + SceUID m_event; +#else + HANDLE m_event; +#endif // __PS3__ + }; + + class EventArray { + public: + enum EMode { e_modeAutoClear, e_modeManualClear }; + + EventArray(int size, EMode mode = e_modeAutoClear); + + void Set(int index); + void Clear(int index); + void SetAll(); + void ClearAll(); + DWORD WaitForAll(int timeoutMs); + DWORD WaitForAny(int timeoutMs); + DWORD WaitForSingle(int index, int timeoutMs); +#ifdef __PS3__ + void Cancel(); #endif - private: - int m_size; - EMode m_mode; + private: + int m_size; + EMode m_mode; #ifdef __PS3__ - sys_event_flag_t m_events; + sys_event_flag_t m_events; #elif defined __ORBIS__ - SceKernelEventFlag m_events; + SceKernelEventFlag m_events; #elif defined __PSVITA__ - SceUID m_events; + SceUID m_events; #else - HANDLE* m_events; -#endif // __PS3__ - }; + HANDLE* m_events; +#endif // __PS3__ + }; + class EventQueue { + typedef void(UpdateFunc)(void* lpParameter); + typedef void(ThreadInitFunc)(); + C4JThread* m_thread; + std::queue m_queue; + C4JThread::EventArray* m_startEvent; + C4JThread::Event* m_finishedEvent; + CRITICAL_SECTION m_critSect; + UpdateFunc* m_updateFunc; + ThreadInitFunc* m_threadInitFunc; + char m_threadName[64]; + int m_processor; + int m_priority; + void init(); + static int threadFunc(void* lpParam); + void threadPoll(); - class EventQueue - { - typedef void (UpdateFunc)(void* lpParameter); - typedef void (ThreadInitFunc)(); + public: + EventQueue(UpdateFunc* updateFunc, ThreadInitFunc threadInitFunc, + const char* szThreadName); + void setProcessor(int proc) { + m_processor = proc; + if (m_thread) m_thread->SetProcessor(proc); + } + void setPriority(int priority) { + m_priority = priority; + if (m_thread) m_thread->SetPriority(priority); + } + void sendEvent(Level* pLevel); + void waitForFinish(); + }; - C4JThread* m_thread; - std::queue m_queue; - C4JThread::EventArray* m_startEvent; - C4JThread::Event* m_finishedEvent; - CRITICAL_SECTION m_critSect; - UpdateFunc* m_updateFunc; - ThreadInitFunc* m_threadInitFunc; - char m_threadName[64]; - int m_processor; - int m_priority; - void init(); - static int threadFunc(void* lpParam); - void threadPoll(); + C4JThread(C4JThreadStartFunc* startFunc, void* param, + const char* threadName, int stackSize = 0); + C4JThread(const char* mainThreadName); // only used for the main thread + ~C4JThread(); - public: - EventQueue(UpdateFunc* updateFunc, ThreadInitFunc threadInitFunc, const char* szThreadName); - void setProcessor(int proc) { m_processor = proc; if(m_thread) m_thread->SetProcessor(proc); } - void setPriority(int priority) { m_priority = priority; if(m_thread) m_thread->SetPriority(priority); } - void sendEvent(Level* pLevel); - void waitForFinish(); - }; - - - - C4JThread(C4JThreadStartFunc* startFunc, void* param, const char* threadName, int stackSize = 0); - C4JThread( const char* mainThreadName ); // only used for the main thread - ~C4JThread(); - - void Run(); - bool isRunning() { return m_isRunning; } - bool hasStarted() { return m_hasStarted; } - void SetProcessor(int proc); - void SetPriority(int priority); - DWORD WaitForCompletion(int timeoutMs); - int GetExitCode(); - char* getName() { return m_threadName; } - static void Sleep(int millisecs); - static C4JThread* getCurrentThread(); - static bool isMainThread(); - static char* getCurrentThreadName() { return getCurrentThread()->getName(); } + void Run(); + bool isRunning() { return m_isRunning; } + bool hasStarted() { return m_hasStarted; } + void SetProcessor(int proc); + void SetPriority(int priority); + DWORD WaitForCompletion(int timeoutMs); + int GetExitCode(); + char* getName() { return m_threadName; } + static void Sleep(int millisecs); + static C4JThread* getCurrentThread(); + static bool isMainThread(); + static char* getCurrentThreadName() { + return getCurrentThread()->getName(); + } #ifdef __ORBIS__ - static void PushAffinityAllCores(); // PS4 only - static void PopAffinity(); - static __thread SceKernelCpumask m_oldAffinityMask; -#endif // __ORBIS__ + static void PushAffinityAllCores(); // PS4 only + static void PopAffinity(); + static __thread SceKernelCpumask m_oldAffinityMask; +#endif // __ORBIS__ #ifdef _XBOX_ONE - static void StaticInit(); + static void StaticInit(); #endif private: - void* m_threadParam; - C4JThreadStartFunc* m_startFunc; - int m_stackSize; - char m_threadName[64]; - bool m_isRunning; - bool m_hasStarted; - int m_exitCode; - __int64 m_lastSleepTime; - static std::vector ms_threadList; - static CRITICAL_SECTION ms_threadListCS; + void* m_threadParam; + C4JThreadStartFunc* m_startFunc; + int m_stackSize; + char m_threadName[64]; + bool m_isRunning; + bool m_hasStarted; + int m_exitCode; + __int64 m_lastSleepTime; + static std::vector ms_threadList; + static CRITICAL_SECTION ms_threadListCS; #ifdef _XBOX_ONE - // 4J Stu - On XboxOne the main thread is not the one that does all the static init, so we have to set this up later - static C4JThread *m_mainThread; + // 4J Stu - On XboxOne the main thread is not the one that does all the + // static init, so we have to set this up later + static C4JThread* m_mainThread; #else - static C4JThread m_mainThread; + static C4JThread m_mainThread; #endif #ifdef __PS3__ - sys_ppu_thread_t m_threadID; - Event *m_completionFlag; - int m_priority; - static void entryPoint(uint64_t); + sys_ppu_thread_t m_threadID; + Event* m_completionFlag; + int m_priority; + static void entryPoint(uint64_t); #elif defined __ORBIS__ - ScePthreadAttr m_threadAttr; - ScePthread m_threadID; - Event *m_completionFlag; - int m_priority; - static void *entryPoint(void *); + ScePthreadAttr m_threadAttr; + ScePthread m_threadID; + Event* m_completionFlag; + int m_priority; + static void* entryPoint(void*); #elif defined __PSVITA__ - SceUID m_threadID; - Event *m_completionFlag; - int m_priority; - static SceInt32 entryPoint(SceSize argSize, void *pArgBlock); + SceUID m_threadID; + Event* m_completionFlag; + int m_priority; + static SceInt32 entryPoint(SceSize argSize, void* pArgBlock); #else - DWORD m_threadID; - HANDLE m_threadHandle; - Event *m_completionFlag; - static DWORD WINAPI entryPoint(LPVOID lpParam); + DWORD m_threadID; + HANDLE m_threadHandle; + Event* m_completionFlag; + static DWORD WINAPI entryPoint(LPVOID lpParam); #endif }; -void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName ); - +void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName); diff --git a/Minecraft.World/Util/Class.cpp b/Minecraft.World/Util/Class.cpp index 250dd8fd7..48c13b3a1 100644 --- a/Minecraft.World/Util/Class.cpp +++ b/Minecraft.World/Util/Class.cpp @@ -1,5 +1,5 @@ #include "../Platform/stdafx.h" #include "Class.h" -// 4J Stu - To ensure that other classes can get the _class object of it's superclass, we also need -// the BaseObject to have that member +// 4J Stu - To ensure that other classes can get the _class object of it's +// superclass, we also need the BaseObject to have that member diff --git a/Minecraft.World/Util/Class.h b/Minecraft.World/Util/Class.h index 9d07027ad..697d0f21f 100644 --- a/Minecraft.World/Util/Class.h +++ b/Minecraft.World/Util/Class.h @@ -2,161 +2,172 @@ class InputStream; -// This file aims to provide functionality to mimic the subset of java's Class class that we require. Classes that require this -// functionality derive from BaseObject, and each contain a unique nested class definition Class. There are #defines here to -// simplify declaring classes with this added functionality. +// This file aims to provide functionality to mimic the subset of java's Class +// class that we require. Classes that require this functionality derive from +// BaseObject, and each contain a unique nested class definition Class. There +// are #defines here to simplify declaring classes with this added +// functionality. +// 4J Stu - This Enum can be used as a more lightweight version of the above, +// without having do dynamic casts 4J-PB - for replacement of instanceof +enum eINSTANCEOF { + eTYPE_NOTSET = 0, -// 4J Stu - This Enum can be used as a more lightweight version of the above, without having do dynamic casts -// 4J-PB - for replacement of instanceof -enum eINSTANCEOF -{ - eTYPE_NOTSET=0, + // 4J-RR arranging these pathfinder types in a bitfield fashion so that a + // single and can determine whether they are derived from the 3 subclasses + // of pathfinders (water animals, animals, and monsters) that the mob + // spawner uses + eTYPE_WATERANIMAL = 0x100, + eTYPE_SQUID = 0x101, - // 4J-RR arranging these pathfinder types in a bitfield fashion so that a single and can determine whether they are derived from - // the 3 subclasses of pathfinders (water animals, animals, and monsters) that the mob spawner uses - eTYPE_WATERANIMAL = 0x100, - eTYPE_SQUID = 0x101, + eTYPE_ANIMAL = 0x200, - eTYPE_ANIMAL = 0x200, + // 4J Stu - These have the ANIMAL, AGABLE_MOB and ANIMALS_SPAWN_LIMIT_CHECK + // bits set + eTYPE_COW = 0x82201, + eTYPE_SHEEP = 0x82202, + eTYPE_PIG = 0x82203, + eTYPE_SNOWMAN = 0x82204, + eTYPE_OZELOT = 0x82205, - // 4J Stu - These have the ANIMAL, AGABLE_MOB and ANIMALS_SPAWN_LIMIT_CHECK bits set - eTYPE_COW = 0x82201, - eTYPE_SHEEP = 0x82202, - eTYPE_PIG = 0x82203, - eTYPE_SNOWMAN = 0x82204, - eTYPE_OZELOT = 0x82205, + // 4J Stu - When adding new categories, please also update + // ConsoleSchematicFile::generateSchematicFile so these can be saved out to + // schematics 4J Stu- These have the ANIMAL and AGABLE_MOB bits set, but NOT + // ANIMALS_SPAWN_LIMIT_CHECK + eTYPE_CHICKEN = 0x2206, + eTYPE_WOLF = 0x2207, + eTYPE_MUSHROOMCOW = 0x2208, - // 4J Stu - When adding new categories, please also update ConsoleSchematicFile::generateSchematicFile so these can be saved out to schematics - // 4J Stu- These have the ANIMAL and AGABLE_MOB bits set, but NOT ANIMALS_SPAWN_LIMIT_CHECK - eTYPE_CHICKEN = 0x2206, - eTYPE_WOLF = 0x2207, - eTYPE_MUSHROOMCOW = 0x2208, + // 4J Stu - If you add new hostile mobs here you should also update the + // string lookup function at CConsoleMinecraftApp::getEntityName + eTYPE_MONSTER = 0x400, + eTYPE_ENEMY = 0x800, + eTYPE_CREEPER = 0xC01, + eTYPE_GIANT = 0xC02, + eTYPE_SKELETON = 0xC03, + eTYPE_SPIDER = 0xC04, + eTYPE_ZOMBIE = 0xC05, + eTYPE_PIGZOMBIE = 0xC06, + eTYPE_ENDERMAN = 0xC07, + eTYPE_SILVERFISH = 0xC08, + eTYPE_CAVESPIDER = 0xC09, + eTYPE_BLAZE = 0xC0A, - // 4J Stu - If you add new hostile mobs here you should also update the string lookup function at CConsoleMinecraftApp::getEntityName - eTYPE_MONSTER = 0x400, - eTYPE_ENEMY = 0x800, - eTYPE_CREEPER = 0xC01, - eTYPE_GIANT = 0xC02, - eTYPE_SKELETON = 0xC03, - eTYPE_SPIDER = 0xC04, - eTYPE_ZOMBIE = 0xC05, - eTYPE_PIGZOMBIE = 0xC06, - eTYPE_ENDERMAN = 0xC07, - eTYPE_SILVERFISH = 0xC08, - eTYPE_CAVESPIDER = 0xC09, - eTYPE_BLAZE = 0xC0A, + eTYPE_GHAST = + 0xC0B, // Now considering as a monster even though class inheritance + // doesn't work like this - but otherwise breaks mob spawning + eTYPE_SLIME = + 0xC0C, // Now considering as a monster even though class inheritance + // doesn't work like this - but otherwise breaks mob spawning + eTYPE_LAVASLIME = 0xC0D, - eTYPE_GHAST = 0xC0B, // Now considering as a monster even though class inheritance doesn't work like this - but otherwise breaks mob spawning - eTYPE_SLIME = 0xC0C, // Now considering as a monster even though class inheritance doesn't work like this - but otherwise breaks mob spawning - eTYPE_LAVASLIME = 0xC0D, + eTYPE_VILLAGERGOLEM = 0x1000, - eTYPE_VILLAGERGOLEM = 0x1000, + eTYPE_AGABLE_MOB = 0x2000, - eTYPE_AGABLE_MOB = 0x2000, + eTYPE_PLAYER = 0x8000, + eTYPE_SERVERPLAYER = 0x8001, - eTYPE_PLAYER = 0x8000, - eTYPE_SERVERPLAYER= 0x8001, + // Include AGABLE_MOB + eTYPE_VILLAGER = 0x12000, - // Include AGABLE_MOB - eTYPE_VILLAGER = 0x12000, + eTYPE_PROJECTILE = 0x40000, + eTYPE_ARROW = 0x40001, + eTYPE_FIREBALL = 0x40002, + eTYPE_FISHINGHOOK = 0x40003, + eTYPE_SNOWBALL = 0x40004, + eTYPE_THROWNEGG = 0x40005, + eTYPE_EYEOFENDERSIGNAL = 0x40006, + eTYPE_SMALL_FIREBALL = 0x40007, + eTYPE_THROWNENDERPEARL = 0x40008, + eTYPE_THROWNPOTION = 0x40009, + eTYPE_THROWNEXPBOTTLE = 0x4000A, - eTYPE_PROJECTILE = 0x40000, - eTYPE_ARROW = 0x40001, - eTYPE_FIREBALL = 0x40002, - eTYPE_FISHINGHOOK = 0x40003, - eTYPE_SNOWBALL = 0x40004, - eTYPE_THROWNEGG = 0x40005, - eTYPE_EYEOFENDERSIGNAL = 0x40006, - eTYPE_SMALL_FIREBALL = 0x40007, - eTYPE_THROWNENDERPEARL = 0x40008, - eTYPE_THROWNPOTION = 0x40009, - eTYPE_THROWNEXPBOTTLE = 0x4000A, + eTYPE_ANIMALS_SPAWN_LIMIT_CHECK = 0x80000, - eTYPE_ANIMALS_SPAWN_LIMIT_CHECK = 0x80000, + // Never used, exists to ensure all later entities don't match the bitmasks + // above + eTYPE_OTHERS = 0x100000, - // Never used, exists to ensure all later entities don't match the bitmasks above - eTYPE_OTHERS = 0x100000, + eTYPE_NETHER_SPHERE, + eTYPE_ENDER_CRYSTAL, + eTYPE_ENDERDRAGON, + eTYPE_BOSS_MOB_PART, - eTYPE_NETHER_SPHERE, - eTYPE_ENDER_CRYSTAL, - eTYPE_ENDERDRAGON, - eTYPE_BOSS_MOB_PART, + eTYPE_ENTITY, - eTYPE_ENTITY, + eTYPE_MOB, - eTYPE_MOB, + eTYPE_LIGHTNINGBOLT, - eTYPE_LIGHTNINGBOLT, + eTYPE_PAINTING, + eTYPE_ITEMENTITY, + eTYPE_FALLINGTILE, + eTYPE_BOAT, + eTYPE_MINECART, + eTYPE_PRIMEDTNT, - eTYPE_PAINTING, - eTYPE_ITEMENTITY, - eTYPE_FALLINGTILE, - eTYPE_BOAT, - eTYPE_MINECART, - eTYPE_PRIMEDTNT, + eTYPE_TILEENTITY, + eTYPE_CHESTTILEENTITY, + eTYPE_DISPENSERTILEENTITY, + eTYPE_MOBSPAWNERTILEENTITY, + eTYPE_FURNACETILEENTITY, + eTYPE_SIGNTILEENTITY, + eTYPE_MUSICTILEENTITY, + eTYPE_RECORDPLAYERTILE, + eTYPE_PISTONPIECEENTITY, + eTYPE_BREWINGSTANDTILEENTITY, + eTYPE_ENCHANTMENTTABLEENTITY, + eTYPE_THEENDPORTALTILEENTITY, + eTYPE_SKULLTILEENTITY, + eTYPE_ENDERCHESTTILEENTITY, - eTYPE_TILEENTITY, - eTYPE_CHESTTILEENTITY, - eTYPE_DISPENSERTILEENTITY, - eTYPE_MOBSPAWNERTILEENTITY, - eTYPE_FURNACETILEENTITY, - eTYPE_SIGNTILEENTITY, - eTYPE_MUSICTILEENTITY, - eTYPE_RECORDPLAYERTILE, - eTYPE_PISTONPIECEENTITY, - eTYPE_BREWINGSTANDTILEENTITY, - eTYPE_ENCHANTMENTTABLEENTITY, - eTYPE_THEENDPORTALTILEENTITY, - eTYPE_SKULLTILEENTITY, - eTYPE_ENDERCHESTTILEENTITY, + eType_NODE, - eType_NODE, + eType_ITEM, + eType_ITEMINSTANCE, + eType_MAPITEM, + eType_TILE, + eType_FIRETILE, - eType_ITEM, - eType_ITEMINSTANCE, - eType_MAPITEM, - eType_TILE, - eType_FIRETILE, + eType_BREAKINGITEMPARTICLE, + eType_BUBBLEPARTICLE, + eType_EXPLODEPARTICLE, + eType_FLAMEPARTICLE, + eType_FOOTSTEPPARTICLE, + eType_HEARTPARTICLE, + eType_LAVAPARTICLE, + eType_NOTEPARTICLE, + eType_NETHERPORTALPARTICLE, + eType_REDDUSTPARTICLE, + eType_SMOKEPARTICLE, + eType_SNOWSHOVELPARTICLE, + eType_SPLASHPARTICLE, + eType_TAKEANIMATIONPARTICLE, + eType_TERRAINPARTICLE, + eType_WATERDROPPARTICLE, - eType_BREAKINGITEMPARTICLE, - eType_BUBBLEPARTICLE, - eType_EXPLODEPARTICLE, - eType_FLAMEPARTICLE, - eType_FOOTSTEPPARTICLE, - eType_HEARTPARTICLE, - eType_LAVAPARTICLE, - eType_NOTEPARTICLE, - eType_NETHERPORTALPARTICLE, - eType_REDDUSTPARTICLE, - eType_SMOKEPARTICLE, - eType_SNOWSHOVELPARTICLE, - eType_SPLASHPARTICLE, - eType_TAKEANIMATIONPARTICLE, - eType_TERRAINPARTICLE, - eType_WATERDROPPARTICLE, + // 1.8.2 + eTYPE_DELAYEDRELEASE, + eTYPE_EXPERIENCEORB, + eType_CRITPARTICLE, + eType_CRITPARTICLE2, + eType_HUGEEXPLOSIONPARTICLE, + eType_HUGEEXPLOSIONSEEDPARTICLE, + eType_PLAYERCLOUDPARTICLEPARTICLE, + eType_SUSPENDEDPARTICLE, + eType_SUSPENDEDTOWNPARTICLE, - // 1.8.2 - eTYPE_DELAYEDRELEASE, - eTYPE_EXPERIENCEORB, - eType_CRITPARTICLE, - eType_CRITPARTICLE2, - eType_HUGEEXPLOSIONPARTICLE, - eType_HUGEEXPLOSIONSEEDPARTICLE, - eType_PLAYERCLOUDPARTICLEPARTICLE, - eType_SUSPENDEDPARTICLE, - eType_SUSPENDEDTOWNPARTICLE, + // 1.0.1 + eTYPE_DRIPPARTICLE, + eTYPE_ENCHANTMENTTABLEPARTICLE, + eTYPE_SPELLPARTICLE, - //1.0.1 - eTYPE_DRIPPARTICLE, - eTYPE_ENCHANTMENTTABLEPARTICLE, - eTYPE_SPELLPARTICLE, + // TU9 + eTYPE_HANGING_ENTITY, + eTYPE_ITEM_FRAME, + eTYPE_DRAGONBREATHPARTICLE, + eTYPE_DRAGON_FIREBALL, - //TU9 - eTYPE_HANGING_ENTITY, - eTYPE_ITEM_FRAME, - eTYPE_DRAGONBREATHPARTICLE, - eTYPE_DRAGON_FIREBALL, - - eType_ENDERPARTICLE, + eType_ENDERPARTICLE, }; diff --git a/Minecraft.World/Util/Color.cpp b/Minecraft.World/Util/Color.cpp index ed5e41773..8843b01ca 100644 --- a/Minecraft.World/Util/Color.cpp +++ b/Minecraft.World/Util/Color.cpp @@ -2,96 +2,85 @@ #include "Color.h" -//Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0). -//Alpha is defaulted to 1.0. The actual color used in rendering depends on finding the best match given the color space -//available for a particular output device. -//Parameters: -//r - the red component -//g - the green component -//b - the blue component -//Throws: -//IllegalArgumentException - if r, g or b are outside of the range 0.0 to 1.0, inclusive -Color::Color( float r, float g, float b) -{ - assert( r >= 0.0f && r <= 1.0f ); - assert( g >= 0.0f && g <= 1.0f ); - assert( b >= 0.0f && b <= 1.0f ); +// Creates an opaque sRGB color with the specified red, green, and blue values +// in the range (0.0 - 1.0). Alpha is defaulted to 1.0. The actual color used in +// rendering depends on finding the best match given the color space available +// for a particular output device. Parameters: r - the red component g - the +// green component b - the blue component Throws: IllegalArgumentException - if +// r, g or b are outside of the range 0.0 to 1.0, inclusive +Color::Color(float r, float g, float b) { + assert(r >= 0.0f && r <= 1.0f); + assert(g >= 0.0f && g <= 1.0f); + assert(b >= 0.0f && b <= 1.0f); - //argb - colour = ( (0xFF<<24) | ( (int)(r*255)<<16 ) | ( (int)(g*255)<<8 ) | ( (int)(b*255) ) ); + // argb + colour = ((0xFF << 24) | ((int)(r * 255) << 16) | ((int)(g * 255) << 8) | + ((int)(b * 255))); } -Color::Color( int r, int g, int b) -{ - colour = ( (0xFF<<24) | ( (r&0xff)<<16 ) | ( (g&0xff)<<8 ) | ( (b&0xff) ) ); +Color::Color(int r, int g, int b) { + colour = + ((0xFF << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b & 0xff))); } - -//Creates a Color object based on the specified values for the HSB color model. -//The s and b components should be floating-point values between zero and one (numbers in the range 0.0-1.0). -//The h component can be any floating-point number. The floor of this number is subtracted from it to create a fraction between 0 and 1. -//This fractional number is then multiplied by 360 to produce the hue angle in the HSB color model. +// Creates a Color object based on the specified values for the HSB color model. +// The s and b components should be floating-point values between zero and one +// (numbers in the range 0.0-1.0). The h component can be any floating-point +// number. The floor of this number is subtracted from it to create a fraction +// between 0 and 1. This fractional number is then multiplied by 360 to produce +// the hue angle in the HSB color model. // -//Parameters: -//h - the hue component -//s - the saturation of the color -//b - the brightness of the color -//Returns: -//a Color object with the specified hue, saturation, and brightness. -Color Color::getHSBColor(float hue, float saturation, float brightness) -{ - int r = 0, g = 0, b = 0; - if (saturation == 0) - { - r = g = b = (int) (brightness * 255.0f + 0.5f); - } - else - { - float h = (hue - (float)floor(hue)) * 6.0f; - float f = h - (float)floor(h); - float p = brightness * (1.0f - saturation); - float q = brightness * (1.0f - saturation * f); - float t = brightness * (1.0f - (saturation * (1.0f - f))); - switch ((int) h) - { - case 0: - r = (int) (brightness * 255.0f + 0.5f); - g = (int) (t * 255.0f + 0.5f); - b = (int) (p * 255.0f + 0.5f); - break; - case 1: - r = (int) (q * 255.0f + 0.5f); - g = (int) (brightness * 255.0f + 0.5f); - b = (int) (p * 255.0f + 0.5f); - break; - case 2: - r = (int) (p * 255.0f + 0.5f); - g = (int) (brightness * 255.0f + 0.5f); - b = (int) (t * 255.0f + 0.5f); - break; - case 3: - r = (int) (p * 255.0f + 0.5f); - g = (int) (q * 255.0f + 0.5f); - b = (int) (brightness * 255.0f + 0.5f); - break; - case 4: - r = (int) (t * 255.0f + 0.5f); - g = (int) (p * 255.0f + 0.5f); - b = (int) (brightness * 255.0f + 0.5f); - break; - case 5: - r = (int) (brightness * 255.0f + 0.5f); - g = (int) (p * 255.0f + 0.5f); - b = (int) (q * 255.0f + 0.5f); - break; - } - } +// Parameters: +// h - the hue component +// s - the saturation of the color +// b - the brightness of the color +// Returns: +// a Color object with the specified hue, saturation, and brightness. +Color Color::getHSBColor(float hue, float saturation, float brightness) { + int r = 0, g = 0, b = 0; + if (saturation == 0) { + r = g = b = (int)(brightness * 255.0f + 0.5f); + } else { + float h = (hue - (float)floor(hue)) * 6.0f; + float f = h - (float)floor(h); + float p = brightness * (1.0f - saturation); + float q = brightness * (1.0f - saturation * f); + float t = brightness * (1.0f - (saturation * (1.0f - f))); + switch ((int)h) { + case 0: + r = (int)(brightness * 255.0f + 0.5f); + g = (int)(t * 255.0f + 0.5f); + b = (int)(p * 255.0f + 0.5f); + break; + case 1: + r = (int)(q * 255.0f + 0.5f); + g = (int)(brightness * 255.0f + 0.5f); + b = (int)(p * 255.0f + 0.5f); + break; + case 2: + r = (int)(p * 255.0f + 0.5f); + g = (int)(brightness * 255.0f + 0.5f); + b = (int)(t * 255.0f + 0.5f); + break; + case 3: + r = (int)(p * 255.0f + 0.5f); + g = (int)(q * 255.0f + 0.5f); + b = (int)(brightness * 255.0f + 0.5f); + break; + case 4: + r = (int)(t * 255.0f + 0.5f); + g = (int)(p * 255.0f + 0.5f); + b = (int)(brightness * 255.0f + 0.5f); + break; + case 5: + r = (int)(brightness * 255.0f + 0.5f); + g = (int)(p * 255.0f + 0.5f); + b = (int)(q * 255.0f + 0.5f); + break; + } + } - - return Color( r, g, b ); + return Color(r, g, b); } -int Color::getRGB() -{ - return colour; -} \ No newline at end of file +int Color::getRGB() { return colour; } \ No newline at end of file diff --git a/Minecraft.World/Util/Color.h b/Minecraft.World/Util/Color.h index a9d31ecab..ba6631071 100644 --- a/Minecraft.World/Util/Color.h +++ b/Minecraft.World/Util/Color.h @@ -1,15 +1,15 @@ #pragma once -class Color -{ +class Color { private: - int colour; + int colour; public: - //Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0). - Color( float r, float g, float b); - Color( int r, int g, int b); + // Creates an opaque sRGB color with the specified red, green, and blue + // values in the range (0.0 - 1.0). + Color(float r, float g, float b); + Color(int r, int g, int b); - static Color getHSBColor(float h, float s, float b); - int getRGB(); + static Color getHSBColor(float h, float s, float b); + int getRGB(); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Coord.h b/Minecraft.World/Util/Coord.h index 9fb8ad720..e1add5020 100644 --- a/Minecraft.World/Util/Coord.h +++ b/Minecraft.World/Util/Coord.h @@ -1,12 +1,9 @@ #pragma once -class Coord -{ +class Coord { public: - const int x, y, z; + const int x, y, z; public: - Coord(int x, int y, int z) : x( x ), y( y ), z( z ) - { - }; + Coord(int x, int y, int z) : x(x), y(y), z(z) {}; }; \ No newline at end of file diff --git a/Minecraft.World/Util/DamageSource.cpp b/Minecraft.World/Util/DamageSource.cpp index 6fe561234..e48124729 100644 --- a/Minecraft.World/Util/DamageSource.cpp +++ b/Minecraft.World/Util/DamageSource.cpp @@ -6,175 +6,173 @@ #include "../Headers/net.minecraft.world.food.h" #include "../Headers/net.minecraft.network.packet.h" -DamageSource *DamageSource::inFire = (new DamageSource(ChatPacket::e_ChatDeathInFire))->setIsFire(); -DamageSource *DamageSource::onFire = (new DamageSource(ChatPacket::e_ChatDeathOnFire))->bypassArmor()->setIsFire(); -DamageSource *DamageSource::lava = (new DamageSource(ChatPacket::e_ChatDeathLava))->setIsFire(); -DamageSource *DamageSource::inWall = (new DamageSource(ChatPacket::e_ChatDeathInWall))->bypassArmor(); -DamageSource *DamageSource::drown = (new DamageSource(ChatPacket::e_ChatDeathDrown))->bypassArmor(); -DamageSource *DamageSource::starve = (new DamageSource(ChatPacket::e_ChatDeathStarve))->bypassArmor(); -DamageSource *DamageSource::cactus = new DamageSource(ChatPacket::e_ChatDeathCactus); -DamageSource *DamageSource::fall = (new DamageSource(ChatPacket::e_ChatDeathFall))->bypassArmor(); -DamageSource *DamageSource::outOfWorld = (new DamageSource(ChatPacket::e_ChatDeathOutOfWorld))->bypassArmor()->bypassInvul(); -DamageSource *DamageSource::genericSource = (new DamageSource(ChatPacket::e_ChatDeathGeneric))->bypassArmor(); -DamageSource *DamageSource::explosion = (new DamageSource(ChatPacket::e_ChatDeathExplosion))->setScalesWithDifficulty(); -DamageSource *DamageSource::controlledExplosion = (new DamageSource(ChatPacket::e_ChatDeathExplosion)); -DamageSource *DamageSource::magic = (new DamageSource(ChatPacket::e_ChatDeathMagic))->bypassArmor()->setMagic(); -DamageSource *DamageSource::dragonbreath = (new DamageSource(ChatPacket::e_ChatDeathDragonBreath))->bypassArmor(); -DamageSource *DamageSource::wither = (new DamageSource(ChatPacket::e_ChatDeathWither))->bypassArmor(); -DamageSource *DamageSource::anvil = (new DamageSource(ChatPacket::e_ChatDeathAnvil)); -DamageSource *DamageSource::fallingBlock = (new DamageSource(ChatPacket::e_ChatDeathFallingBlock)); +DamageSource* DamageSource::inFire = + (new DamageSource(ChatPacket::e_ChatDeathInFire))->setIsFire(); +DamageSource* DamageSource::onFire = + (new DamageSource(ChatPacket::e_ChatDeathOnFire)) + ->bypassArmor() + ->setIsFire(); +DamageSource* DamageSource::lava = + (new DamageSource(ChatPacket::e_ChatDeathLava))->setIsFire(); +DamageSource* DamageSource::inWall = + (new DamageSource(ChatPacket::e_ChatDeathInWall))->bypassArmor(); +DamageSource* DamageSource::drown = + (new DamageSource(ChatPacket::e_ChatDeathDrown))->bypassArmor(); +DamageSource* DamageSource::starve = + (new DamageSource(ChatPacket::e_ChatDeathStarve))->bypassArmor(); +DamageSource* DamageSource::cactus = + new DamageSource(ChatPacket::e_ChatDeathCactus); +DamageSource* DamageSource::fall = + (new DamageSource(ChatPacket::e_ChatDeathFall))->bypassArmor(); +DamageSource* DamageSource::outOfWorld = + (new DamageSource(ChatPacket::e_ChatDeathOutOfWorld)) + ->bypassArmor() + ->bypassInvul(); +DamageSource* DamageSource::genericSource = + (new DamageSource(ChatPacket::e_ChatDeathGeneric))->bypassArmor(); +DamageSource* DamageSource::explosion = + (new DamageSource(ChatPacket::e_ChatDeathExplosion)) + ->setScalesWithDifficulty(); +DamageSource* DamageSource::controlledExplosion = + (new DamageSource(ChatPacket::e_ChatDeathExplosion)); +DamageSource* DamageSource::magic = + (new DamageSource(ChatPacket::e_ChatDeathMagic))->bypassArmor()->setMagic(); +DamageSource* DamageSource::dragonbreath = + (new DamageSource(ChatPacket::e_ChatDeathDragonBreath))->bypassArmor(); +DamageSource* DamageSource::wither = + (new DamageSource(ChatPacket::e_ChatDeathWither))->bypassArmor(); +DamageSource* DamageSource::anvil = + (new DamageSource(ChatPacket::e_ChatDeathAnvil)); +DamageSource* DamageSource::fallingBlock = + (new DamageSource(ChatPacket::e_ChatDeathFallingBlock)); -DamageSource *DamageSource::mobAttack(std::shared_ptr mob) -{ - return new EntityDamageSource(ChatPacket::e_ChatDeathMob, mob); +DamageSource* DamageSource::mobAttack(std::shared_ptr mob) { + return new EntityDamageSource(ChatPacket::e_ChatDeathMob, mob); } -DamageSource *DamageSource::playerAttack(std::shared_ptr player) -{ - return new EntityDamageSource(ChatPacket::e_ChatDeathPlayer, player); +DamageSource* DamageSource::playerAttack(std::shared_ptr player) { + return new EntityDamageSource(ChatPacket::e_ChatDeathPlayer, player); } -DamageSource *DamageSource::arrow(std::shared_ptr arrow, std::shared_ptr owner) -{ - return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathArrow, arrow, owner))->setProjectile(); +DamageSource* DamageSource::arrow(std::shared_ptr arrow, + std::shared_ptr owner) { + return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathArrow, arrow, + owner)) + ->setProjectile(); } -DamageSource *DamageSource::fireball(std::shared_ptr fireball, std::shared_ptr owner) -{ - if (owner == NULL) - { - return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathOnFire, fireball, fireball))->setIsFire()->setProjectile(); - } - return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathFireball, fireball, owner))->setIsFire()->setProjectile(); +DamageSource* DamageSource::fireball(std::shared_ptr fireball, + std::shared_ptr owner) { + if (owner == NULL) { + return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathOnFire, + fireball, fireball)) + ->setIsFire() + ->setProjectile(); + } + return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathFireball, + fireball, owner)) + ->setIsFire() + ->setProjectile(); } -DamageSource *DamageSource::thrown(std::shared_ptr entity, std::shared_ptr owner) -{ - return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathThrown, entity, owner))->setProjectile(); +DamageSource* DamageSource::thrown(std::shared_ptr entity, + std::shared_ptr owner) { + return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathThrown, + entity, owner)) + ->setProjectile(); } -DamageSource *DamageSource::indirectMagic(std::shared_ptr entity, std::shared_ptr owner) -{ - return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathIndirectMagic, entity, owner) )->bypassArmor()->setMagic();; +DamageSource* DamageSource::indirectMagic(std::shared_ptr entity, + std::shared_ptr owner) { + return (new IndirectEntityDamageSource(ChatPacket::e_ChatDeathIndirectMagic, + entity, owner)) + ->bypassArmor() + ->setMagic(); + ; } -DamageSource *DamageSource::thorns(std::shared_ptr source) -{ - return (new EntityDamageSource(ChatPacket::e_ChatDeathThorns, source))->setMagic(); +DamageSource* DamageSource::thorns(std::shared_ptr source) { + return (new EntityDamageSource(ChatPacket::e_ChatDeathThorns, source)) + ->setMagic(); } -bool DamageSource::isProjectile() -{ - return _isProjectile; +bool DamageSource::isProjectile() { return _isProjectile; } + +DamageSource* DamageSource::setProjectile() { + this->_isProjectile = true; + return this; } -DamageSource *DamageSource::setProjectile() -{ - this->_isProjectile = true; - return this; +bool DamageSource::isBypassArmor() { return _bypassArmor; } + +float DamageSource::getFoodExhaustion() { return exhaustion; } + +bool DamageSource::isBypassInvul() { return _bypassInvul; } + +// DamageSource::DamageSource(const std::wstring &msgId) +DamageSource::DamageSource(ChatPacket::EChatPacketMessage msgId) { + // 4J added initialisors + _bypassArmor = false; + _bypassInvul = false; + // food exhastion caused by being damaged by this source + exhaustion = FoodConstants::EXHAUSTION_ATTACK; + isFireSource = false; + _isProjectile = false; + _isMagic = false; + + // this->msgId = msgId; + m_msgId = msgId; } -bool DamageSource::isBypassArmor() -{ - return _bypassArmor; +std::shared_ptr DamageSource::getDirectEntity() { return getEntity(); } + +std::shared_ptr DamageSource::getEntity() { + return std::shared_ptr(); } -float DamageSource::getFoodExhaustion() -{ - return exhaustion; +DamageSource* DamageSource::bypassArmor() { + _bypassArmor = true; + // these kinds of damages don't cause the player to grow more hungry + exhaustion = 0; + return this; } -bool DamageSource::isBypassInvul() -{ - return _bypassInvul; +DamageSource* DamageSource::bypassInvul() { + _bypassInvul = true; + return this; } - -//DamageSource::DamageSource(const std::wstring &msgId) -DamageSource::DamageSource(ChatPacket::EChatPacketMessage msgId) -{ - // 4J added initialisors - _bypassArmor = false; - _bypassInvul = false; - // food exhastion caused by being damaged by this source - exhaustion = FoodConstants::EXHAUSTION_ATTACK; - isFireSource = false; - _isProjectile = false; - _isMagic = false; - - //this->msgId = msgId; - m_msgId = msgId; +DamageSource* DamageSource::setIsFire() { + isFireSource = true; + return this; } -std::shared_ptr DamageSource::getDirectEntity() -{ - return getEntity(); +DamageSource* DamageSource::setScalesWithDifficulty() { + _scalesWithDifficulty = true; + return this; } -std::shared_ptr DamageSource::getEntity() -{ - return std::shared_ptr(); +bool DamageSource::scalesWithDifficulty() { return _scalesWithDifficulty; } + +bool DamageSource::isMagic() { return _isMagic; } + +DamageSource* DamageSource::setMagic() { + _isMagic = true; + return this; } -DamageSource *DamageSource::bypassArmor() -{ - _bypassArmor = true; - // these kinds of damages don't cause the player to grow more hungry - exhaustion = 0; - return this; -} - -DamageSource *DamageSource::bypassInvul() -{ - _bypassInvul = true; - return this; -} - -DamageSource *DamageSource::setIsFire() -{ - isFireSource = true; - return this; -} - -DamageSource *DamageSource::setScalesWithDifficulty() -{ - _scalesWithDifficulty = true; - return this; -} - -bool DamageSource::scalesWithDifficulty() -{ - return _scalesWithDifficulty; -} - -bool DamageSource::isMagic() -{ - return _isMagic; -} - -DamageSource *DamageSource::setMagic() -{ - _isMagic = true; - return this; -} - -//std::wstring DamageSource::getLocalizedDeathMessage(std::shared_ptr player) +// std::wstring DamageSource::getLocalizedDeathMessage(std::shared_ptr +// player) //{ // return L"death." + msgId + player->name; // //return I18n.get(L"death." + msgId, player.name); -//} +// } -std::shared_ptr DamageSource::getDeathMessagePacket(std::shared_ptr player) -{ - return std::shared_ptr( new ChatPacket(player->name, m_msgId ) ); +std::shared_ptr DamageSource::getDeathMessagePacket( + std::shared_ptr player) { + return std::shared_ptr(new ChatPacket(player->name, m_msgId)); } -bool DamageSource::isFire() -{ - return isFireSource; -} +bool DamageSource::isFire() { return isFireSource; } -ChatPacket::EChatPacketMessage DamageSource::getMsgId() -{ - return m_msgId; -} \ No newline at end of file +ChatPacket::EChatPacketMessage DamageSource::getMsgId() { return m_msgId; } \ No newline at end of file diff --git a/Minecraft.World/Util/DamageSource.h b/Minecraft.World/Util/DamageSource.h index cefa4a9e9..7fe7d0dc0 100644 --- a/Minecraft.World/Util/DamageSource.h +++ b/Minecraft.World/Util/DamageSource.h @@ -1,6 +1,5 @@ #pragma once - class Mob; class Entity; class Arrow; @@ -9,82 +8,88 @@ class Player; #include "../Network/Packets/ChatPacket.h" -class DamageSource -{ +class DamageSource { public: - static DamageSource *inFire; - static DamageSource *onFire; - static DamageSource *lava; - static DamageSource *inWall; - static DamageSource *drown; - static DamageSource *starve; - static DamageSource *cactus; - static DamageSource *fall; - static DamageSource *outOfWorld; - static DamageSource *genericSource; - static DamageSource *explosion; - static DamageSource *controlledExplosion; - static DamageSource *magic; - static DamageSource *dragonbreath; - static DamageSource *wither; - static DamageSource *anvil; - static DamageSource *fallingBlock; + static DamageSource* inFire; + static DamageSource* onFire; + static DamageSource* lava; + static DamageSource* inWall; + static DamageSource* drown; + static DamageSource* starve; + static DamageSource* cactus; + static DamageSource* fall; + static DamageSource* outOfWorld; + static DamageSource* genericSource; + static DamageSource* explosion; + static DamageSource* controlledExplosion; + static DamageSource* magic; + static DamageSource* dragonbreath; + static DamageSource* wither; + static DamageSource* anvil; + static DamageSource* fallingBlock; - static DamageSource *mobAttack(std::shared_ptr mob); - static DamageSource *playerAttack(std::shared_ptr player); - static DamageSource *arrow(std::shared_ptr arrow, std::shared_ptr owner); - static DamageSource *fireball(std::shared_ptr fireball, std::shared_ptr owner); - static DamageSource *thrown(std::shared_ptr entity, std::shared_ptr owner); - static DamageSource *indirectMagic(std::shared_ptr entity, std::shared_ptr owner); - static DamageSource *thorns(std::shared_ptr source); + static DamageSource* mobAttack(std::shared_ptr mob); + static DamageSource* playerAttack(std::shared_ptr player); + static DamageSource* arrow(std::shared_ptr arrow, + std::shared_ptr owner); + static DamageSource* fireball(std::shared_ptr fireball, + std::shared_ptr owner); + static DamageSource* thrown(std::shared_ptr entity, + std::shared_ptr owner); + static DamageSource* indirectMagic(std::shared_ptr entity, + std::shared_ptr owner); + static DamageSource* thorns(std::shared_ptr source); private: - bool _bypassArmor; - bool _bypassInvul; - // food exhastion caused by being damaged by this source - float exhaustion; - bool isFireSource; - bool _isProjectile; - bool _scalesWithDifficulty; - bool _isMagic; + bool _bypassArmor; + bool _bypassInvul; + // food exhastion caused by being damaged by this source + float exhaustion; + bool isFireSource; + bool _isProjectile; + bool _scalesWithDifficulty; + bool _isMagic; public: - bool isProjectile(); - DamageSource *setProjectile(); + bool isProjectile(); + DamageSource* setProjectile(); - bool isBypassArmor(); - float getFoodExhaustion(); - bool isBypassInvul(); + bool isBypassArmor(); + float getFoodExhaustion(); + bool isBypassInvul(); - //std::wstring msgId; - ChatPacket::EChatPacketMessage m_msgId; // 4J Made int so we can localise + // std::wstring msgId; + ChatPacket::EChatPacketMessage m_msgId; // 4J Made int so we can localise protected: - //DamageSource(const std::wstring &msgId); - DamageSource(ChatPacket::EChatPacketMessage msgId); + // DamageSource(const std::wstring &msgId); + DamageSource(ChatPacket::EChatPacketMessage msgId); public: - virtual ~DamageSource() {} + virtual ~DamageSource() {} - virtual std::shared_ptr getDirectEntity(); - virtual std::shared_ptr getEntity(); + virtual std::shared_ptr getDirectEntity(); + virtual std::shared_ptr getEntity(); protected: - DamageSource *bypassArmor(); - DamageSource *bypassInvul(); - DamageSource *setIsFire(); - DamageSource *setScalesWithDifficulty(); + DamageSource* bypassArmor(); + DamageSource* bypassInvul(); + DamageSource* setIsFire(); + DamageSource* setScalesWithDifficulty(); public: - virtual bool scalesWithDifficulty(); + virtual bool scalesWithDifficulty(); - bool isMagic(); - DamageSource *setMagic(); + bool isMagic(); + DamageSource* setMagic(); - // 4J Stu - Made return a packet - //virtual std::wstring getLocalizedDeathMessage(std::shared_ptr player); - virtual std::shared_ptr getDeathMessagePacket(std::shared_ptr player); + // 4J Stu - Made return a packet + // virtual std::wstring getLocalizedDeathMessage(std::shared_ptr + // player); + virtual std::shared_ptr getDeathMessagePacket( + std::shared_ptr player); - bool isFire(); - ChatPacket::EChatPacketMessage getMsgId(); // 4J Stu - Used to return String + bool isFire(); + ChatPacket::EChatPacketMessage + getMsgId(); // 4J Stu - Used to return String }; \ No newline at end of file diff --git a/Minecraft.World/Util/Definitions.h b/Minecraft.World/Util/Definitions.h index 8399c5813..b0dec3cfe 100644 --- a/Minecraft.World/Util/Definitions.h +++ b/Minecraft.World/Util/Definitions.h @@ -1,40 +1,37 @@ #pragma once - class AABB; class Recipy; class Object; typedef std::vector AABBList; -typedef std::vector RecipyList; -typedef std::vector ObjectList; +typedef std::vector RecipyList; +typedef std::vector ObjectList; #define MAX_PATH_SIZE 256 #define PI (3.141592654f) #define HALF_PI (1.570796327f) -enum ByteOrder -{ - BIGENDIAN, - LITTLEENDIAN, +enum ByteOrder { + BIGENDIAN, + LITTLEENDIAN, #if defined(__PS3__) || defined(_XBOX) - LOCALSYTEM_ENDIAN = BIGENDIAN, + LOCALSYTEM_ENDIAN = BIGENDIAN, #else - LOCALSYTEM_ENDIAN = LITTLEENDIAN, + LOCALSYTEM_ENDIAN = LITTLEENDIAN, #endif }; -enum EDefaultSkins -{ - eDefaultSkins_ServerSelected, - eDefaultSkins_Skin0, - eDefaultSkins_Skin1, - eDefaultSkins_Skin2, - eDefaultSkins_Skin3, - eDefaultSkins_Skin4, - eDefaultSkins_Skin5, - eDefaultSkins_Skin6, - eDefaultSkins_Skin7, +enum EDefaultSkins { + eDefaultSkins_ServerSelected, + eDefaultSkins_Skin0, + eDefaultSkins_Skin1, + eDefaultSkins_Skin2, + eDefaultSkins_Skin3, + eDefaultSkins_Skin4, + eDefaultSkins_Skin5, + eDefaultSkins_Skin6, + eDefaultSkins_Skin7, - eDefaultSkins_Count, + eDefaultSkins_Count, }; \ No newline at end of file diff --git a/Minecraft.World/Util/DelayedRelease.cpp b/Minecraft.World/Util/DelayedRelease.cpp index acf2c8512..4b8fafd63 100644 --- a/Minecraft.World/Util/DelayedRelease.cpp +++ b/Minecraft.World/Util/DelayedRelease.cpp @@ -2,45 +2,27 @@ #include "../Headers/net.minecraft.world.level.h" #include "DelayedRelease.h" - - -DelayedRelease::DelayedRelease(Level *level, std::shared_ptr toRelease, int delay) : Entity(level) -{ - moveTo(toRelease->x, toRelease->y, toRelease->z, 0, 0); - this->toRelease = toRelease; - this->delay = delay; +DelayedRelease::DelayedRelease(Level* level, std::shared_ptr toRelease, + int delay) + : Entity(level) { + moveTo(toRelease->x, toRelease->y, toRelease->z, 0, 0); + this->toRelease = toRelease; + this->delay = delay; } +bool DelayedRelease::makeStepSound() { return false; } -bool DelayedRelease::makeStepSound() -{ - return false; +void DelayedRelease::tick() { + if (delay-- <= 0) { + level->addEntity(toRelease); + remove(); + } } +bool DelayedRelease::hurt(DamageSource* source, int damage) { return false; } -void DelayedRelease::tick() -{ - if (delay-- <= 0) - { - level->addEntity(toRelease); - remove(); - } -} +void DelayedRelease::defineSynchedData() {} -bool DelayedRelease::hurt(DamageSource *source, int damage) -{ - return false; -} +void DelayedRelease::readAdditionalSaveData(CompoundTag* tag) {} - -void DelayedRelease::defineSynchedData() -{ -} - -void DelayedRelease::readAdditionalSaveData(CompoundTag *tag) -{ -} - -void DelayedRelease::addAdditonalSaveData(CompoundTag *tag) -{ -} \ No newline at end of file +void DelayedRelease::addAdditonalSaveData(CompoundTag* tag) {} \ No newline at end of file diff --git a/Minecraft.World/Util/DelayedRelease.h b/Minecraft.World/Util/DelayedRelease.h index b3579fa57..42c63af8d 100644 --- a/Minecraft.World/Util/DelayedRelease.h +++ b/Minecraft.World/Util/DelayedRelease.h @@ -4,27 +4,26 @@ class DamageSource; -class DelayedRelease : public Entity -{ +class DelayedRelease : public Entity { public: - virtual eINSTANCEOF GetType() { return eTYPE_DELAYEDRELEASE; } + virtual eINSTANCEOF GetType() { return eTYPE_DELAYEDRELEASE; } private: - std::shared_ptr toRelease; - int delay; + std::shared_ptr toRelease; + int delay; public: - DelayedRelease(Level *level, std::shared_ptr toRelease, int delay); + DelayedRelease(Level* level, std::shared_ptr toRelease, int delay); protected: - virtual bool makeStepSound(); + virtual bool makeStepSound(); public: - virtual void tick(); - virtual bool hurt(DamageSource *source, int damage); + virtual void tick(); + virtual bool hurt(DamageSource* source, int damage); protected: - virtual void defineSynchedData(); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void addAdditonalSaveData(CompoundTag *tag); + virtual void defineSynchedData(); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void addAdditonalSaveData(CompoundTag* tag); }; \ No newline at end of file diff --git a/Minecraft.World/Util/DescFormatter.h b/Minecraft.World/Util/DescFormatter.h index a5b04eeb8..a28900d5b 100644 --- a/Minecraft.World/Util/DescFormatter.h +++ b/Minecraft.World/Util/DescFormatter.h @@ -1,8 +1,6 @@ #pragma once - -class DescFormatter -{ +class DescFormatter { public: - virtual std::wstring format(const std::wstring& i18nValue); + virtual std::wstring format(const std::wstring& i18nValue); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Difficulty.h b/Minecraft.World/Util/Difficulty.h index d238ef15e..7ef5bb940 100644 --- a/Minecraft.World/Util/Difficulty.h +++ b/Minecraft.World/Util/Difficulty.h @@ -1,7 +1,6 @@ #pragma once -class Difficulty -{ +class Difficulty { public: static const int PEACEFUL = 0; static const int EASY = 1; diff --git a/Minecraft.World/Util/Direction.cpp b/Minecraft.World/Util/Direction.cpp index 3c6156c56..0ba3669fe 100644 --- a/Minecraft.World/Util/Direction.cpp +++ b/Minecraft.World/Util/Direction.cpp @@ -2,61 +2,39 @@ #include "Direction.h" #include "Facing.h" -const int Direction::STEP_X[] = -{ - 0, -1, 0, 1 -}; +const int Direction::STEP_X[] = {0, -1, 0, 1}; -const int Direction::STEP_Z[] = -{ - 1, 0, -1, 0 -}; +const int Direction::STEP_Z[] = {1, 0, -1, 0}; // for [direction] it gives [tile-face] -int Direction::DIRECTION_FACING[4] = -{ - Facing::SOUTH, Facing::WEST, Facing::NORTH, Facing::EAST -}; +int Direction::DIRECTION_FACING[4] = {Facing::SOUTH, Facing::WEST, + Facing::NORTH, Facing::EAST}; // for [facing] it gives [direction] -int Direction::FACING_DIRECTION[] = -{ - UNDEFINED, UNDEFINED, NORTH, SOUTH, WEST, EAST -}; +int Direction::FACING_DIRECTION[] = {UNDEFINED, UNDEFINED, NORTH, + SOUTH, WEST, EAST}; -int Direction::DIRECTION_OPPOSITE[4] = -{ - Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST -}; +int Direction::DIRECTION_OPPOSITE[4] = {Direction::NORTH, Direction::EAST, + Direction::SOUTH, Direction::WEST}; // for [direction] it gives [90 degrees clockwise direction] -int Direction::DIRECTION_CLOCKWISE[] = -{ - Direction::WEST, Direction::NORTH, Direction::EAST, Direction::SOUTH -}; +int Direction::DIRECTION_CLOCKWISE[] = {Direction::WEST, Direction::NORTH, + Direction::EAST, Direction::SOUTH}; // for [direction] it gives [90 degrees counter clockwise direction] -int Direction::DIRECTION_COUNTER_CLOCKWISE[] = -{ - Direction::EAST, Direction::SOUTH, Direction::WEST, Direction::NORTH -}; +int Direction::DIRECTION_COUNTER_CLOCKWISE[] = { + Direction::EAST, Direction::SOUTH, Direction::WEST, Direction::NORTH}; -int Direction::RELATIVE_DIRECTION_FACING[4][6] = -{ +int Direction::RELATIVE_DIRECTION_FACING[4][6] = { // south - { - Facing::UP, Facing::DOWN, Facing::SOUTH, Facing::NORTH, Facing::EAST, Facing::WEST - }, + {Facing::UP, Facing::DOWN, Facing::SOUTH, Facing::NORTH, Facing::EAST, + Facing::WEST}, // west - { - Facing::UP, Facing::DOWN, Facing::EAST, Facing::WEST, Facing::NORTH, Facing::SOUTH - }, + {Facing::UP, Facing::DOWN, Facing::EAST, Facing::WEST, Facing::NORTH, + Facing::SOUTH}, // north - { - Facing::UP, Facing::DOWN, Facing::NORTH, Facing::SOUTH, Facing::WEST, Facing::EAST - }, + {Facing::UP, Facing::DOWN, Facing::NORTH, Facing::SOUTH, Facing::WEST, + Facing::EAST}, // east - { - Facing::UP, Facing::DOWN, Facing::WEST, Facing::EAST, Facing::SOUTH, Facing::NORTH - } -}; + {Facing::UP, Facing::DOWN, Facing::WEST, Facing::EAST, Facing::SOUTH, + Facing::NORTH}}; diff --git a/Minecraft.World/Util/Direction.h b/Minecraft.World/Util/Direction.h index aadd2bbb4..c1182f1dd 100644 --- a/Minecraft.World/Util/Direction.h +++ b/Minecraft.World/Util/Direction.h @@ -1,31 +1,30 @@ #pragma once -class Direction -{ +class Direction { public: - static const int UNDEFINED = -1; + static const int UNDEFINED = -1; static const int SOUTH = 0; static const int WEST = 1; static const int NORTH = 2; static const int EAST = 3; - static const int STEP_X[]; - static const int STEP_Z[]; + static const int STEP_X[]; + static const int STEP_Z[]; // for [direction] it gives [tile-face] static int DIRECTION_FACING[]; // for [facing] it gives [direction] - static int FACING_DIRECTION[]; + static int FACING_DIRECTION[]; // for [direction] it gives [opposite direction] static int DIRECTION_OPPOSITE[]; // for [direction] it gives [90 degrees clockwise direction] - static int DIRECTION_CLOCKWISE[]; + static int DIRECTION_CLOCKWISE[]; // for [direction] it gives [90 degrees counter-clockwise direction] - static int DIRECTION_COUNTER_CLOCKWISE[]; + static int DIRECTION_COUNTER_CLOCKWISE[]; // for [direction][world-facing] it gives [tile-facing] static int RELATIVE_DIRECTION_FACING[4][6]; diff --git a/Minecraft.World/Util/Distort.cpp b/Minecraft.World/Util/Distort.cpp index b8e7ff7a9..31917e09f 100644 --- a/Minecraft.World/Util/Distort.cpp +++ b/Minecraft.World/Util/Distort.cpp @@ -1,13 +1,11 @@ #include "../Platform/stdafx.h" #include "Distort.h" -Distort::Distort(Synth *source, Synth *distort) -{ +Distort::Distort(Synth* source, Synth* distort) { this->source = source; this->distort = distort; } -double Distort::getValue(double x, double y) -{ +double Distort::getValue(double x, double y) { return source->getValue(x + distort->getValue(x, y), y); } diff --git a/Minecraft.World/Util/Distort.h b/Minecraft.World/Util/Distort.h index 941dae760..3dfaac7cc 100644 --- a/Minecraft.World/Util/Distort.h +++ b/Minecraft.World/Util/Distort.h @@ -1,14 +1,13 @@ #pragma once #include "../WorldGen/Noise/Synth.h" -class Distort: public Synth -{ +class Distort : public Synth { private: - Synth *source; - Synth *distort; + Synth* source; + Synth* distort; public: - Distort(Synth *source, Synth *distort); + Distort(Synth* source, Synth* distort); virtual double getValue(double x, double y); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Emboss.cpp b/Minecraft.World/Util/Emboss.cpp index 182a28e80..ddd31f8a2 100644 --- a/Minecraft.World/Util/Emboss.cpp +++ b/Minecraft.World/Util/Emboss.cpp @@ -1,12 +1,8 @@ #include "../Platform/stdafx.h" #include "Emboss.h" -Emboss::Emboss(Synth *synth) -{ - this->synth = synth; -} +Emboss::Emboss(Synth* synth) { this->synth = synth; } -double Emboss::getValue(double x, double y) -{ +double Emboss::getValue(double x, double y) { return synth->getValue(x, y) - synth->getValue(x + 1, y + 1); } \ No newline at end of file diff --git a/Minecraft.World/Util/Emboss.h b/Minecraft.World/Util/Emboss.h index 19f989d68..a62e244f4 100644 --- a/Minecraft.World/Util/Emboss.h +++ b/Minecraft.World/Util/Emboss.h @@ -1,13 +1,12 @@ #pragma once #include "../WorldGen/Noise/Synth.h" -class Emboss: public Synth -{ +class Emboss : public Synth { private: - Synth *synth; + Synth* synth; public: - Emboss(Synth *synth); + Emboss(Synth* synth); virtual double getValue(double x, double y); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Exceptions.h b/Minecraft.World/Util/Exceptions.h index 49ff86fde..d8d4ccbfd 100644 --- a/Minecraft.World/Util/Exceptions.h +++ b/Minecraft.World/Util/Exceptions.h @@ -1,29 +1,22 @@ #pragma once +class EOFException : public std::exception {}; -class EOFException : public std::exception -{ +class IllegalArgumentException : public std::exception { +public: + std::wstring information; + IllegalArgumentException(const std::wstring& information); }; -class IllegalArgumentException : public std::exception -{ +class IOException : public std::exception { public: - std::wstring information; + std::wstring information; - IllegalArgumentException(const std::wstring& information); + IOException(const std::wstring& information); }; -class IOException : public std::exception -{ +class RuntimeException : public std::exception { public: - std::wstring information; - - IOException(const std::wstring& information); -}; - -class RuntimeException : public std::exception -{ -public: - RuntimeException(const std::wstring& information); + RuntimeException(const std::wstring& information); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Facing.cpp b/Minecraft.World/Util/Facing.cpp index 77271a622..b2fcf5aa3 100644 --- a/Minecraft.World/Util/Facing.cpp +++ b/Minecraft.World/Util/Facing.cpp @@ -1,22 +1,10 @@ #include "../Platform/stdafx.h" #include "Facing.h" -const int Facing::OPPOSITE_FACING[6] = -{ - UP, DOWN, SOUTH, NORTH, EAST, WEST -}; +const int Facing::OPPOSITE_FACING[6] = {UP, DOWN, SOUTH, NORTH, EAST, WEST}; -const int Facing::STEP_X[6] = -{ - 0, 0, 0, 0, -1, 1 -}; +const int Facing::STEP_X[6] = {0, 0, 0, 0, -1, 1}; -const int Facing::STEP_Y[6] = -{ - -1, 1, 0, 0, 0, 0 -}; +const int Facing::STEP_Y[6] = {-1, 1, 0, 0, 0, 0}; -const int Facing::STEP_Z[6] = -{ - 0, 0, -1, 1, 0, 0 -}; +const int Facing::STEP_Z[6] = {0, 0, -1, 1, 0, 0}; diff --git a/Minecraft.World/Util/Facing.h b/Minecraft.World/Util/Facing.h index 1c4cfdf3b..62dcc49b1 100644 --- a/Minecraft.World/Util/Facing.h +++ b/Minecraft.World/Util/Facing.h @@ -1,7 +1,6 @@ #pragma once -class Facing -{ +class Facing { public: static const int DOWN = 0; static const int UP = 1; @@ -10,8 +9,8 @@ public: static const int WEST = 4; static const int EAST = 5; - static const int OPPOSITE_FACING[6]; - static const int STEP_X[6]; - static const int STEP_Y[6]; - static const int STEP_Z[6]; + static const int OPPOSITE_FACING[6]; + static const int STEP_X[6]; + static const int STEP_Y[6]; + static const int STEP_Z[6]; }; \ No newline at end of file diff --git a/Minecraft.World/Util/FlippedIcon.cpp b/Minecraft.World/Util/FlippedIcon.cpp index e0b916511..3064189f8 100644 --- a/Minecraft.World/Util/FlippedIcon.cpp +++ b/Minecraft.World/Util/FlippedIcon.cpp @@ -2,87 +2,55 @@ #include "FlippedIcon.h" #include "SharedConstants.h" -FlippedIcon::FlippedIcon(Icon *base, bool horizontal, bool vertical) : base(base), horizontal(horizontal), vertical(vertical) -{ +FlippedIcon::FlippedIcon(Icon* base, bool horizontal, bool vertical) + : base(base), horizontal(horizontal), vertical(vertical) {} + +int FlippedIcon::getX() const { return base->getX(); } + +int FlippedIcon::getY() const { return base->getY(); } + +int FlippedIcon::getWidth() const { return base->getWidth(); } + +int FlippedIcon::getHeight() const { return base->getHeight(); } + +float FlippedIcon::getU0(bool adjust /*=false*/) const { + if (horizontal) return base->getU1(adjust); + return base->getU0(adjust); } -int FlippedIcon::getX() const -{ - return base->getX(); +float FlippedIcon::getU1(bool adjust /*=false*/) const { + if (horizontal) return base->getU0(adjust); + return base->getU1(adjust); } -int FlippedIcon::getY() const -{ - return base->getY(); +float FlippedIcon::getU(double offset, bool adjust /*=false*/) const { + float diff = getU1(adjust) - getU0(adjust); + return getU0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -int FlippedIcon::getWidth() const -{ - return base->getWidth(); +float FlippedIcon::getV0(bool adjust /*=false*/) const { + if (vertical) return base->getV0(adjust); + return base->getV0(adjust); } -int FlippedIcon::getHeight() const -{ - return base->getHeight(); +float FlippedIcon::getV1(bool adjust /*=false*/) const { + if (vertical) return base->getV0(adjust); + return base->getV1(adjust); } -float FlippedIcon::getU0(bool adjust/*=false*/) const -{ - if (horizontal) return base->getU1(adjust); - return base->getU0(adjust); +float FlippedIcon::getV(double offset, bool adjust /*=false*/) const { + float diff = getV1(adjust) - getV0(adjust); + return getV0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -float FlippedIcon::getU1(bool adjust/*=false*/) const -{ - if (horizontal) return base->getU0(adjust); - return base->getU1(adjust); -} +std::wstring FlippedIcon::getName() const { return base->getName(); } -float FlippedIcon::getU(double offset, bool adjust/*=false*/) const -{ - float diff = getU1(adjust) - getU0(adjust); - return getU0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); -} +int FlippedIcon::getSourceWidth() const { return base->getSourceWidth(); } -float FlippedIcon::getV0(bool adjust/*=false*/) const -{ - if (vertical) return base->getV0(adjust); - return base->getV0(adjust); -} +int FlippedIcon::getSourceHeight() const { return base->getSourceHeight(); } -float FlippedIcon::getV1(bool adjust/*=false*/) const -{ - if (vertical) return base->getV0(adjust); - return base->getV1(adjust); -} +int FlippedIcon::getFlags() const { return base->getFlags(); } -float FlippedIcon::getV(double offset, bool adjust/*=false*/) const -{ - float diff = getV1(adjust) - getV0(adjust); - return getV0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); -} - -std::wstring FlippedIcon::getName() const -{ - return base->getName(); -} - -int FlippedIcon::getSourceWidth() const -{ - return base->getSourceWidth(); -} - -int FlippedIcon::getSourceHeight() const -{ - return base->getSourceHeight(); -} - -int FlippedIcon::getFlags() const -{ - return base->getFlags(); -} - -void FlippedIcon::setFlags(int flags) -{ - base->setFlags(flags); -} +void FlippedIcon::setFlags(int flags) { base->setFlags(flags); } diff --git a/Minecraft.World/Util/FlippedIcon.h b/Minecraft.World/Util/FlippedIcon.h index 37f083d46..711949ff3 100644 --- a/Minecraft.World/Util/FlippedIcon.h +++ b/Minecraft.World/Util/FlippedIcon.h @@ -1,31 +1,29 @@ #pragma once - #include "Icon.h" -class FlippedIcon : public Icon -{ +class FlippedIcon : public Icon { private: - Icon *base; - const bool horizontal; - const bool vertical; + Icon* base; + const bool horizontal; + const bool vertical; public: - FlippedIcon(Icon *base, bool horizontal, bool vertical); + FlippedIcon(Icon* base, bool horizontal, bool vertical); - int getX() const; - int getY() const; - int getWidth() const; - int getHeight() const; - float getU0(bool adjust = false) const; - float getU1(bool adjust = false) const; - float getU(double offset, bool adjust = false) const; - float getV0(bool adjust = false) const; - float getV1(bool adjust = false) const; - float getV(double offset, bool adjust = false) const; - std::wstring getName() const; - int getSourceWidth() const; - int getSourceHeight() const; - int getFlags() const; // 4J added - void setFlags(int flags); // 4J added + int getX() const; + int getY() const; + int getWidth() const; + int getHeight() const; + float getU0(bool adjust = false) const; + float getU1(bool adjust = false) const; + float getU(double offset, bool adjust = false) const; + float getV0(bool adjust = false) const; + float getV1(bool adjust = false) const; + float getV(double offset, bool adjust = false) const; + std::wstring getName() const; + int getSourceWidth() const; + int getSourceHeight() const; + int getFlags() const; // 4J added + void setFlags(int flags); // 4J added }; \ No newline at end of file diff --git a/Minecraft.World/Util/FoliageColor.cpp b/Minecraft.World/Util/FoliageColor.cpp index 3ecc88fe0..a6d328dc4 100644 --- a/Minecraft.World/Util/FoliageColor.cpp +++ b/Minecraft.World/Util/FoliageColor.cpp @@ -3,16 +3,16 @@ #include "FoliageColor.h" // 4J Stu - Don't use this any more -//intArray FoliageColor::pixels; +// intArray FoliageColor::pixels; // -//void FoliageColor::init(intArray pixels) +// void FoliageColor::init(intArray pixels) //{ // int *oldData = FoliageColor::pixels.data; // FoliageColor::pixels = pixels; // delete[] oldData; //} // -//int FoliageColor::get(double temp, double rain) +// int FoliageColor::get(double temp, double rain) //{ // rain *= temp; // int x = (int) ((1 - temp) * 255); @@ -21,20 +21,20 @@ // return returnVal; //} -int FoliageColor::getEvergreenColor() -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Foliage_Evergreen); - //return 0x619961; +int FoliageColor::getEvergreenColor() { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Foliage_Evergreen); + // return 0x619961; } -int FoliageColor::getBirchColor() -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Foliage_Birch); - //return 0x80a755; +int FoliageColor::getBirchColor() { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Foliage_Birch); + // return 0x80a755; } -int FoliageColor::getDefaultColor() -{ - return Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Foliage_Default); - //return 0x48b518; +int FoliageColor::getDefaultColor() { + return Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Foliage_Default); + // return 0x48b518; } \ No newline at end of file diff --git a/Minecraft.World/Util/FoliageColor.h b/Minecraft.World/Util/FoliageColor.h index 140a06731..ed08c310a 100644 --- a/Minecraft.World/Util/FoliageColor.h +++ b/Minecraft.World/Util/FoliageColor.h @@ -1,17 +1,16 @@ #pragma once -class FoliageColor -{ - // 4J Stu - We don't want to use this any more -//private: -// static intArray pixels; -// -//public: -// static void init(intArray pixels); -// static int get(double temp, double rain); +class FoliageColor { + // 4J Stu - We don't want to use this any more + // private: + // static intArray pixels; + // + // public: + // static void init(intArray pixels); + // static int get(double temp, double rain); public: - static int getEvergreenColor(); - static int getBirchColor(); - static int getDefaultColor(); + static int getEvergreenColor(); + static int getBirchColor(); + static int getDefaultColor(); }; \ No newline at end of file diff --git a/Minecraft.World/Util/FoodConstants.cpp b/Minecraft.World/Util/FoodConstants.cpp index d4cae3f66..633c7ff75 100644 --- a/Minecraft.World/Util/FoodConstants.cpp +++ b/Minecraft.World/Util/FoodConstants.cpp @@ -3,9 +3,11 @@ #include "FoodConstants.h" const int FoodConstants::MAX_FOOD = 20; -const float FoodConstants::MAX_SATURATION = (float) FoodConstants::MAX_FOOD; -const float FoodConstants::START_SATURATION = (float) FoodConstants::MAX_SATURATION / 4.0f; -const float FoodConstants::SATURATION_FLOOR = FoodConstants::MAX_SATURATION / 8.0f; +const float FoodConstants::MAX_SATURATION = (float)FoodConstants::MAX_FOOD; +const float FoodConstants::START_SATURATION = + (float)FoodConstants::MAX_SATURATION / 4.0f; +const float FoodConstants::SATURATION_FLOOR = + FoodConstants::MAX_SATURATION / 8.0f; // this value modifies how quickly food is dropped const float FoodConstants::EXHAUSTION_DROP = 4.0f; @@ -26,10 +28,12 @@ const float FoodConstants::FOOD_SATURATION_SUPERNATURAL = 1.2f; // some exhaustion guidelines const float FoodConstants::EXHAUSTION_JUMP = .2f; -const float FoodConstants::EXHAUSTION_SPRINT_JUMP = FoodConstants::EXHAUSTION_JUMP * 4; +const float FoodConstants::EXHAUSTION_SPRINT_JUMP = + FoodConstants::EXHAUSTION_JUMP * 4; const float FoodConstants::EXHAUSTION_MINE = .025f; const float FoodConstants::EXHAUSTION_ATTACK = .3f; const float FoodConstants::EXHAUSTION_DAMAGE = .1f; const float FoodConstants::EXHAUSTION_WALK = .010f; -const float FoodConstants::EXHAUSTION_SPRINT = FoodConstants::EXHAUSTION_WALK * 10; +const float FoodConstants::EXHAUSTION_SPRINT = + FoodConstants::EXHAUSTION_WALK * 10; const float FoodConstants::EXHAUSTION_SWIM = .015f; \ No newline at end of file diff --git a/Minecraft.World/Util/FoodConstants.h b/Minecraft.World/Util/FoodConstants.h index 6f80b0413..7fc8bb8e6 100644 --- a/Minecraft.World/Util/FoodConstants.h +++ b/Minecraft.World/Util/FoodConstants.h @@ -1,7 +1,6 @@ #pragma once -class FoodConstants -{ +class FoodConstants { public: static const int MAX_FOOD; static const float MAX_SATURATION; diff --git a/Minecraft.World/Util/GrassColor.cpp b/Minecraft.World/Util/GrassColor.cpp index 40ca3e2c6..77f75a350 100644 --- a/Minecraft.World/Util/GrassColor.cpp +++ b/Minecraft.World/Util/GrassColor.cpp @@ -2,20 +2,20 @@ #include "GrassColor.h" // 4J Stu - Don't want to do this any more -//intArray GrassColor::pixels; +// intArray GrassColor::pixels; // -//void GrassColor::init(intArray pixels) +// void GrassColor::init(intArray pixels) //{ // int *oldData = GrassColor::pixels.data; // GrassColor::pixels = pixels; // delete [] oldData; //} // -//int GrassColor::get(double temp, double rain) +// int GrassColor::get(double temp, double rain) //{ // rain *= temp; // int x = (int) ((1 - temp) * 255); // int y = (int) ((1 - rain) * 255); -// int returnVal = pixels[y << 8 | x]; +// int returnVal = pixels[y << 8 | x]; // return returnVal; //} \ No newline at end of file diff --git a/Minecraft.World/Util/GrassColor.h b/Minecraft.World/Util/GrassColor.h index 3aa092837..54d7d24d4 100644 --- a/Minecraft.World/Util/GrassColor.h +++ b/Minecraft.World/Util/GrassColor.h @@ -1,12 +1,11 @@ #pragma once -class GrassColor -{ - // 4J Stu - We don't use this any more -//private: -// static intArray pixels; -//public: -// -// static void init(intArray pixels); -// static int get(double temp, double rain); +class GrassColor { + // 4J Stu - We don't use this any more + // private: + // static intArray pixels; + // public: + // + // static void init(intArray pixels); + // static int get(double temp, double rain); }; \ No newline at end of file diff --git a/Minecraft.World/Util/HashExtension.h b/Minecraft.World/Util/HashExtension.h index 8f76fe6b6..49fd13277 100644 --- a/Minecraft.World/Util/HashExtension.h +++ b/Minecraft.World/Util/HashExtension.h @@ -1,20 +1,16 @@ #pragma once #ifdef _XBOX // -namespace std -{ - namespace tr1 - { +namespace std { +namespace tr1 { - template - class hash< std::shared_ptr > - { - public: - size_t operator()(const std::shared_ptr& key) const - { - return (size_t)key.get(); - } - }; - } -} +template +class hash > { +public: + size_t operator()(const std::shared_ptr& key) const { + return (size_t)key.get(); + } +}; +} // namespace tr1 +} // namespace std #endif \ No newline at end of file diff --git a/Minecraft.World/Util/Hasher.cpp b/Minecraft.World/Util/Hasher.cpp index bd1d12191..78a3f8483 100644 --- a/Minecraft.World/Util/Hasher.cpp +++ b/Minecraft.World/Util/Hasher.cpp @@ -6,50 +6,45 @@ #include #include #include -#endif // _WIN32 +#endif // _WIN32 #include "Hasher.h" #include -Hasher::Hasher(std::wstring &salt) -{ - this->salt = salt; -} +Hasher::Hasher(std::wstring& salt) { this->salt = salt; } -std::wstring Hasher::getHash(std::wstring &name) -{ +std::wstring Hasher::getHash(std::wstring& name) { #if defined(_WIN32) - // 4J Stu - Removed try/catch - //try { - std::wstring s = std::wstring( salt ).append( name ); - //MessageDigest m; - //m = MessageDigest.getInstance("MD5"); - //m.update(s.getBytes(), 0, s.length()); - //return new BigInteger(1, m.digest()).toString(16); + // 4J Stu - Removed try/catch + // try { + std::wstring s = std::wstring(salt).append(name); + // MessageDigest m; + // m = MessageDigest.getInstance("MD5"); + // m.update(s.getBytes(), 0, s.length()); + // return new BigInteger(1, m.digest()).toString(16); - // TODO 4J Stu - Will this hash us with the same distribution as the MD5? - return _toString( hash_value( s ) ); - //} - //catch (NoSuchAlgorithmException e) - //{ - // throw new RuntimeException(e); - //} + // TODO 4J Stu - Will this hash us with the same distribution as the MD5? + return _toString(hash_value(s)); + //} + // catch (NoSuchAlgorithmException e) + //{ + // throw new RuntimeException(e); + //} #else - // adapted from a SSL example - std::wstring combined = salt + name; - std::string combined_str(combined.begin(), combined.end()); - unsigned char result[EVP_MAX_MD_SIZE]; - EVP_MD_CTX* md5_ctx = EVP_MD_CTX_new(); - EVP_DigestInit_ex(md5_ctx, EVP_md5(), NULL); - EVP_DigestUpdate(md5_ctx, combined_str.c_str(), combined_str.size()); - unsigned int result_len; - EVP_DigestFinal_ex(md5_ctx, result, &result_len); - EVP_MD_CTX_free(md5_ctx); - std::stringstream ss; - for (unsigned int i = 0; i < result_len; i++) - { - ss << std::setw(2) << std::setfill('0') << std::hex << (int)result[i]; - } - std::string hash_str = ss.str(); - return std::wstring(hash_str.begin(), hash_str.end()); + // adapted from a SSL example + std::wstring combined = salt + name; + std::string combined_str(combined.begin(), combined.end()); + unsigned char result[EVP_MAX_MD_SIZE]; + EVP_MD_CTX* md5_ctx = EVP_MD_CTX_new(); + EVP_DigestInit_ex(md5_ctx, EVP_md5(), NULL); + EVP_DigestUpdate(md5_ctx, combined_str.c_str(), combined_str.size()); + unsigned int result_len; + EVP_DigestFinal_ex(md5_ctx, result, &result_len); + EVP_MD_CTX_free(md5_ctx); + std::stringstream ss; + for (unsigned int i = 0; i < result_len; i++) { + ss << std::setw(2) << std::setfill('0') << std::hex << (int)result[i]; + } + std::string hash_str = ss.str(); + return std::wstring(hash_str.begin(), hash_str.end()); #endif } diff --git a/Minecraft.World/Util/Hasher.h b/Minecraft.World/Util/Hasher.h index 7621f85c2..c0ac09627 100644 --- a/Minecraft.World/Util/Hasher.h +++ b/Minecraft.World/Util/Hasher.h @@ -1,12 +1,10 @@ #pragma once - -class Hasher -{ +class Hasher { private: - std::wstring salt; + std::wstring salt; public: - Hasher(std::wstring &salt); - std::wstring getHash(std::wstring &name); + Hasher(std::wstring& salt); + std::wstring getHash(std::wstring& name); }; \ No newline at end of file diff --git a/Minecraft.World/Util/HitResult.cpp b/Minecraft.World/Util/HitResult.cpp index 6f1a078a8..0b868d1ad 100644 --- a/Minecraft.World/Util/HitResult.cpp +++ b/Minecraft.World/Util/HitResult.cpp @@ -3,31 +3,28 @@ #include "../Headers/net.minecraft.world.entity.h" #include "HitResult.h" -HitResult::HitResult(int x, int y, int z, int f, Vec3 *pos) -{ - this->type = TILE; - this->x = x; - this->y = y; - this->z = z; - this->f = f; - this->pos = Vec3::newTemp(pos->x, pos->y, pos->z); +HitResult::HitResult(int x, int y, int z, int f, Vec3* pos) { + this->type = TILE; + this->x = x; + this->y = y; + this->z = z; + this->f = f; + this->pos = Vec3::newTemp(pos->x, pos->y, pos->z); - this->entity = nullptr; + this->entity = nullptr; } -HitResult::HitResult(std::shared_ptr entity) -{ - this->type = ENTITY; - this->entity = entity; - pos = Vec3::newTemp(entity->x, entity->y, entity->z); +HitResult::HitResult(std::shared_ptr entity) { + this->type = ENTITY; + this->entity = entity; + pos = Vec3::newTemp(entity->x, entity->y, entity->z); - x = y = z = f = 0; + x = y = z = f = 0; } -double HitResult::distanceTo(std::shared_ptr e) -{ - double xd = pos->x - e->x; - double yd = pos->y - e->y; - double zd = pos->z - e->z; - return xd * xd + yd * yd + zd * zd; +double HitResult::distanceTo(std::shared_ptr e) { + double xd = pos->x - e->x; + double yd = pos->y - e->y; + double zd = pos->z - e->z; + return xd * xd + yd * yd + zd * zd; } \ No newline at end of file diff --git a/Minecraft.World/Util/HitResult.h b/Minecraft.World/Util/HitResult.h index 7721a0ff9..ee4121d52 100644 --- a/Minecraft.World/Util/HitResult.h +++ b/Minecraft.World/Util/HitResult.h @@ -1,22 +1,18 @@ #pragma once #include "Vec3.h" -class HitResult -{ +class HitResult { public: - enum Type - { - TILE, ENTITY - }; + enum Type { TILE, ENTITY }; - Type type; - int x, y, z, f; - Vec3 *pos; - std::shared_ptr entity; + Type type; + int x, y, z, f; + Vec3* pos; + std::shared_ptr entity; - HitResult(int x, int y, int z, int f, Vec3 *pos); + HitResult(int x, int y, int z, int f, Vec3* pos); - HitResult(std::shared_ptr entity); + HitResult(std::shared_ptr entity); - double distanceTo(std::shared_ptr e); + double distanceTo(std::shared_ptr e); }; \ No newline at end of file diff --git a/Minecraft.World/Util/I18n.cpp b/Minecraft.World/Util/I18n.cpp index 1d45ab5fb..4203e44b5 100644 --- a/Minecraft.World/Util/I18n.cpp +++ b/Minecraft.World/Util/I18n.cpp @@ -2,20 +2,20 @@ #include "Language.h" #include "I18n.h" -Language *I18n::lang = Language::getInstance(); +Language* I18n::lang = Language::getInstance(); // 4jcraft const & into va_start is ub -std::wstring I18n::get(std::wstring id, ...) -{ -#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last parameter passed to va_start - we shouldn't need this method anyway - return L""; +std::wstring I18n::get(std::wstring id, ...) { +#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last + // parameter passed to va_start - we shouldn't need this + // method anyway + return L""; #else - va_list va; - va_start(va, id); + va_list va; + va_start(va, id); return I18n::get(id, va); #endif } -std::wstring I18n::get(const std::wstring& id, va_list args) -{ - return lang->getElement(id, args); +std::wstring I18n::get(const std::wstring& id, va_list args) { + return lang->getElement(id, args); } diff --git a/Minecraft.World/Util/I18n.h b/Minecraft.World/Util/I18n.h index 02fc0bc80..2393606fa 100644 --- a/Minecraft.World/Util/I18n.h +++ b/Minecraft.World/Util/I18n.h @@ -1,15 +1,13 @@ #pragma once - #include "../Platform/stdafx.h" #include "Language.h" -class I18n -{ +class I18n { private: - static Language *lang; + static Language* lang; public: static std::wstring get(std::wstring id, ...); - static std::wstring get(const std::wstring& id, va_list args); + static std::wstring get(const std::wstring& id, va_list args); }; diff --git a/Minecraft.World/Util/Icon.h b/Minecraft.World/Util/Icon.h index c77fba2c9..3937e974e 100644 --- a/Minecraft.World/Util/Icon.h +++ b/Minecraft.World/Util/Icon.h @@ -1,36 +1,33 @@ #pragma once - - -class Icon -{ +class Icon { public: - static const int TYPE_TERRAIN = 0; - static const int TYPE_ITEM = 1; + static const int TYPE_TERRAIN = 0; + static const int TYPE_ITEM = 1; - static const int IS_GRASS_SIDE = 1; - static const int IS_GRASS_TOP = 2; + static const int IS_GRASS_SIDE = 1; + static const int IS_GRASS_TOP = 2; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita so we mark which icons require it - static const int IS_ALPHA_CUT_OUT = 4; + // AP - alpha cut out is expensive on vita so we mark which icons require it + static const int IS_ALPHA_CUT_OUT = 4; #endif - virtual ~Icon() {} // added by 4jcraft, needed for abstract class + virtual ~Icon() {} // added by 4jcraft, needed for abstract class - virtual int getX() const = 0; - virtual int getY() const = 0; - virtual int getWidth() const = 0; - virtual int getHeight() const = 0; - virtual float getU0(bool adjust = false) const = 0; - virtual float getU1(bool adjust = false) const = 0; - virtual float getU(double offset, bool adjust = false) const = 0; - virtual float getV0(bool adjust = false) const = 0; - virtual float getV1(bool adjust = false) const = 0; - virtual float getV(double offset, bool adjust = false) const = 0; - virtual std::wstring getName() const = 0; - virtual int getSourceWidth() const = 0; - virtual int getSourceHeight() const = 0; - virtual int getFlags() const = 0; // 4J added - virtual void setFlags(int flags) = 0; // 4J added + virtual int getX() const = 0; + virtual int getY() const = 0; + virtual int getWidth() const = 0; + virtual int getHeight() const = 0; + virtual float getU0(bool adjust = false) const = 0; + virtual float getU1(bool adjust = false) const = 0; + virtual float getU(double offset, bool adjust = false) const = 0; + virtual float getV0(bool adjust = false) const = 0; + virtual float getV1(bool adjust = false) const = 0; + virtual float getV(double offset, bool adjust = false) const = 0; + virtual std::wstring getName() const = 0; + virtual int getSourceWidth() const = 0; + virtual int getSourceHeight() const = 0; + virtual int getFlags() const = 0; // 4J added + virtual void setFlags(int flags) = 0; // 4J added }; diff --git a/Minecraft.World/Util/IconRegister.h b/Minecraft.World/Util/IconRegister.h index b7a5bbf3f..333e4d60b 100644 --- a/Minecraft.World/Util/IconRegister.h +++ b/Minecraft.World/Util/IconRegister.h @@ -1,12 +1,10 @@ #pragma once - class Icon; -class IconRegister -{ +class IconRegister { public: - // 4J Stu - register is a reserved keyword in C++ - virtual Icon *registerIcon(const std::wstring &name) = 0; - virtual int getIconType() = 0; + // 4J Stu - register is a reserved keyword in C++ + virtual Icon* registerIcon(const std::wstring& name) = 0; + virtual int getIconType() = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Util/IntCache.cpp b/Minecraft.World/Util/IntCache.cpp index 241c541f9..439dccecc 100644 --- a/Minecraft.World/Util/IntCache.cpp +++ b/Minecraft.World/Util/IntCache.cpp @@ -3,162 +3,138 @@ unsigned int IntCache::tlsIdx = TlsAlloc(); -void IntCache::CreateNewThreadStorage() -{ - ThreadStorage *tls = new ThreadStorage(); - TlsSetValue(tlsIdx, (void *)tls); - tls->maxSize = TINY_CUTOFF; +void IntCache::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + TlsSetValue(tlsIdx, (void*)tls); + tls->maxSize = TINY_CUTOFF; } -IntCache::ThreadStorage::~ThreadStorage() -{ - for(unsigned int i = 0; i < tcache.size(); i++ ) - { - delete [] tcache[i].data; - } - for(unsigned int i = 0; i < tallocated.size(); i++ ) - { - delete [] tallocated[i].data; - } - for(unsigned int i = 0; i < cache.size(); i++ ) - { - delete [] cache[i].data; - } - for(unsigned int i = 0; i < allocated.size(); i++ ) - { - delete [] allocated[i].data; - } - for( int i = 0; i < toosmall.size(); i++ ) - { - delete [] toosmall[i].data; - } +IntCache::ThreadStorage::~ThreadStorage() { + for (unsigned int i = 0; i < tcache.size(); i++) { + delete[] tcache[i].data; + } + for (unsigned int i = 0; i < tallocated.size(); i++) { + delete[] tallocated[i].data; + } + for (unsigned int i = 0; i < cache.size(); i++) { + delete[] cache[i].data; + } + for (unsigned int i = 0; i < allocated.size(); i++) { + delete[] allocated[i].data; + } + for (int i = 0; i < toosmall.size(); i++) { + delete[] toosmall[i].data; + } } -void IntCache::ReleaseThreadStorage() -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); +void IntCache::ReleaseThreadStorage() { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); - - delete tls; + delete tls; } -intArray IntCache::allocate(int size) -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); +intArray IntCache::allocate(int size) { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); - if (size <= TINY_CUTOFF) - { - if (tls->tcache.empty()) - { - intArray result = intArray(TINY_CUTOFF, true); - tls->tallocated.push_back(result); - return result; - } - else - { - intArray result = tls->tcache.back(); - tls->tcache.pop_back(); - tls->tallocated.push_back(result); - return result; - } - } + if (size <= TINY_CUTOFF) { + if (tls->tcache.empty()) { + intArray result = intArray(TINY_CUTOFF, true); + tls->tallocated.push_back(result); + return result; + } else { + intArray result = tls->tcache.back(); + tls->tcache.pop_back(); + tls->tallocated.push_back(result); + return result; + } + } - if (size > tls->maxSize) - { -// app.DebugPrintf("IntCache: New max size: %d\n" , size); - tls->maxSize = size; + if (size > tls->maxSize) { + // app.DebugPrintf("IntCache: New max size: %d\n" , size); + tls->maxSize = size; - // 4J - added - all the vectors in cache & allocated are smaller than maxSize so should be discarded. However, we - // can't delete them until the next releaseAll so copy into another vector until then - tls->toosmall.insert(tls->toosmall.end(),tls->cache.begin(),tls->cache.end()); - tls->toosmall.insert(tls->toosmall.end(),tls->allocated.begin(),tls->allocated.end()); + // 4J - added - all the vectors in cache & allocated are smaller than + // maxSize so should be discarded. However, we can't delete them until + // the next releaseAll so copy into another vector until then + tls->toosmall.insert(tls->toosmall.end(), tls->cache.begin(), + tls->cache.end()); + tls->toosmall.insert(tls->toosmall.end(), tls->allocated.begin(), + tls->allocated.end()); - tls->cache.clear(); - tls->allocated.clear(); + tls->cache.clear(); + tls->allocated.clear(); - intArray result = intArray(tls->maxSize, true); - tls->allocated.push_back(result); - return result; - } - else - { - if (tls->cache.empty()) - { - intArray result = intArray(tls->maxSize, true); - tls->allocated.push_back(result); - return result; - } - else - { - intArray result = tls->cache.back(); - tls->cache.pop_back(); - tls->allocated.push_back(result); - return result; - } - } + intArray result = intArray(tls->maxSize, true); + tls->allocated.push_back(result); + return result; + } else { + if (tls->cache.empty()) { + intArray result = intArray(tls->maxSize, true); + tls->allocated.push_back(result); + return result; + } else { + intArray result = tls->cache.back(); + tls->cache.pop_back(); + tls->allocated.push_back(result); + return result; + } + } } -void IntCache::releaseAll() -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); +void IntCache::releaseAll() { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); - // 4J - added - we can now remove the vectors that were deemed as too small (see comment in IntCache::allocate) - for( int i = 0; i < tls->toosmall.size(); i++ ) - { - delete [] tls->toosmall[i].data; - } - tls->toosmall.clear(); + // 4J - added - we can now remove the vectors that were deemed as too small + // (see comment in IntCache::allocate) + for (int i = 0; i < tls->toosmall.size(); i++) { + delete[] tls->toosmall[i].data; + } + tls->toosmall.clear(); - if (!tls->cache.empty()) - { - delete [] tls->cache.back().data; - tls->cache.pop_back(); - } - if (!tls->tcache.empty()) - { - delete [] tls->tcache.back().data; - tls->tcache.pop_back(); - } + if (!tls->cache.empty()) { + delete[] tls->cache.back().data; + tls->cache.pop_back(); + } + if (!tls->tcache.empty()) { + delete[] tls->tcache.back().data; + tls->tcache.pop_back(); + } - tls->cache.insert(tls->cache.end(),tls->allocated.begin(),tls->allocated.end()); - tls->tcache.insert(tls->tcache.end(),tls->tallocated.begin(),tls->tallocated.end()); + tls->cache.insert(tls->cache.end(), tls->allocated.begin(), + tls->allocated.end()); + tls->tcache.insert(tls->tcache.end(), tls->tallocated.begin(), + tls->tallocated.end()); - tls->allocated.clear(); - tls->tallocated.clear(); + tls->allocated.clear(); + tls->tallocated.clear(); } // 4J added so that we can fully reset between levels -void IntCache::Reset() -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); - tls->maxSize = TINY_CUTOFF; - for( int i = 0; i < tls->allocated.size(); i++ ) - { - delete [] tls->allocated[i].data; - } - tls->allocated.clear(); +void IntCache::Reset() { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); + tls->maxSize = TINY_CUTOFF; + for (int i = 0; i < tls->allocated.size(); i++) { + delete[] tls->allocated[i].data; + } + tls->allocated.clear(); - for( int i = 0; i < tls->cache.size(); i++ ) - { - delete [] tls->cache[i].data; - } - tls->cache.clear(); + for (int i = 0; i < tls->cache.size(); i++) { + delete[] tls->cache[i].data; + } + tls->cache.clear(); - for( int i = 0; i < tls->tallocated.size(); i++ ) - { - delete [] tls->tallocated[i].data; - } - tls->tallocated.clear(); + for (int i = 0; i < tls->tallocated.size(); i++) { + delete[] tls->tallocated[i].data; + } + tls->tallocated.clear(); - for( int i = 0; i < tls->tcache.size(); i++ ) - { - delete [] tls->tcache[i].data; - } - tls->tcache.clear(); + for (int i = 0; i < tls->tcache.size(); i++) { + delete[] tls->tcache[i].data; + } + tls->tcache.clear(); - for( int i = 0; i < tls->toosmall.size(); i++ ) - { - delete [] tls->toosmall[i].data; - } - tls->toosmall.clear(); + for (int i = 0; i < tls->toosmall.size(); i++) { + delete[] tls->toosmall[i].data; + } + tls->toosmall.clear(); } diff --git a/Minecraft.World/Util/IntCache.h b/Minecraft.World/Util/IntCache.h index c83b1eba8..4654d4f3c 100644 --- a/Minecraft.World/Util/IntCache.h +++ b/Minecraft.World/Util/IntCache.h @@ -2,33 +2,29 @@ #include "ArrayWithLength.h" - -class IntCache -{ +class IntCache { private: + class ThreadStorage { + public: + int maxSize; - class ThreadStorage - { - public: - int maxSize; + std::vector tcache; + std::vector tallocated; - std::vector tcache; - std::vector tallocated; - - std::vector cache; - std::vector allocated; - std::vector toosmall; // 4J added - ~ThreadStorage(); - }; - static unsigned int tlsIdx; + std::vector cache; + std::vector allocated; + std::vector toosmall; // 4J added + ~ThreadStorage(); + }; + static unsigned int tlsIdx; - static const int TINY_CUTOFF = 256; + static const int TINY_CUTOFF = 256; public: - static intArray allocate(int size); - static void releaseAll(); + static intArray allocate(int size); + static void releaseAll(); - static void CreateNewThreadStorage(); - static void ReleaseThreadStorage(); - static void Reset(); // 4J added + static void CreateNewThreadStorage(); + static void ReleaseThreadStorage(); + static void Reset(); // 4J added }; diff --git a/Minecraft.World/Util/JavaIntHash.h b/Minecraft.World/Util/JavaIntHash.h index ca79c038f..138b7202a 100644 --- a/Minecraft.World/Util/JavaIntHash.h +++ b/Minecraft.World/Util/JavaIntHash.h @@ -1,77 +1,68 @@ #pragma once -// Java doesn't have a default hash value for ints, however, the hashmap itself does some "supplemental" hashing, so -// our ints actually get hashed by code as implemented below. std templates *do* have a standard hash for ints, but it -// would appear to be a bit expensive so matching the java one for now anyway. This code implements the supplemental -// hashing that happens in java so we can match what their maps are doing with ints. +// Java doesn't have a default hash value for ints, however, the hashmap itself +// does some "supplemental" hashing, so our ints actually get hashed by code as +// implemented below. std templates *do* have a standard hash for ints, but it +// would appear to be a bit expensive so matching the java one for now anyway. +// This code implements the supplemental hashing that happens in java so we can +// match what their maps are doing with ints. -struct IntKeyHash -{ - int operator() (const int &k) const - { - // 4jcraft added h to be unsigned, to not cast it later - unsigned int h = k; +struct IntKeyHash { + int operator()(const int& k) const { + // 4jcraft added h to be unsigned, to not cast it later + unsigned int h = k; h += ~(h << 9); - h ^= (h >> 14); - h += (h << 4); - h ^= (h >> 10); - return h; - } + h ^= (h >> 14); + h += (h << 4); + h ^= (h >> 10); + return h; + } }; -struct IntKeyEq -{ - bool operator() (const int &x, const int &y) const { return x==y; } +struct IntKeyEq { + bool operator()(const int& x, const int& y) const { return x == y; } }; - -// This hash functor is taken from the IntHashMap java class used by the game, so that we can use a standard std hashmap with this hash rather -// than implement the class itself -struct IntKeyHash2 -{ - int operator() (const int &k) const - { - unsigned int h = (unsigned int)k; +// This hash functor is taken from the IntHashMap java class used by the game, +// so that we can use a standard std hashmap with this hash rather than +// implement the class itself +struct IntKeyHash2 { + int operator()(const int& k) const { + unsigned int h = (unsigned int)k; h ^= (h >> 20) ^ (h >> 12); return (int)(h ^ (h >> 7) ^ (h >> 4)); - } + } }; - -// This hash functor is taken from the LongHashMap java class used by the game, so that we can use a standard std hashmap with this hash rather -// than implement the class itself -struct LongKeyHash -{ - int hash(const int &k) const - { - unsigned int h = (unsigned int)k; +// This hash functor is taken from the LongHashMap java class used by the game, +// so that we can use a standard std hashmap with this hash rather than +// implement the class itself +struct LongKeyHash { + int hash(const int& k) const { + unsigned int h = (unsigned int)k; h ^= (h >> 20) ^ (h >> 12); return (int)(h ^ (h >> 7) ^ (h >> 4)); - } + } - int operator() (const __int64 &k) const - { - return hash((int) ( k ^ (((__uint64)k) >> 32 ))); - } + int operator()(const __int64& k) const { + return hash((int)(k ^ (((__uint64)k) >> 32))); + } }; -struct LongKeyEq -{ - bool operator() (const __int64 &x, const __int64 &y) const { return x==y; } +struct LongKeyEq { + bool operator()(const __int64& x, const __int64& y) const { return x == y; } }; -struct eINSTANCEOFKeyHash -{ - int operator() (const eINSTANCEOF &k) const - { - unsigned int h = (unsigned int)k; +struct eINSTANCEOFKeyHash { + int operator()(const eINSTANCEOF& k) const { + unsigned int h = (unsigned int)k; h ^= (h >> 20) ^ (h >> 12); return (int)(h ^ (h >> 7) ^ (h >> 4)); - } + } }; -struct eINSTANCEOFKeyEq -{ - bool operator() (const eINSTANCEOF &x, const eINSTANCEOF &y) const { return x==y; } +struct eINSTANCEOFKeyEq { + bool operator()(const eINSTANCEOF& x, const eINSTANCEOF& y) const { + return x == y; + } }; - diff --git a/Minecraft.World/Util/JavaMath.cpp b/Minecraft.World/Util/JavaMath.cpp index 21389bb2b..b6a8b8fe1 100644 --- a/Minecraft.World/Util/JavaMath.cpp +++ b/Minecraft.World/Util/JavaMath.cpp @@ -4,86 +4,71 @@ Random Math::rand = Random(); -//Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. -//Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. -//When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression +// Returns a double value with a positive sign, greater than or equal to 0.0 and +// less than 1.0. Returned values are chosen pseudorandomly with (approximately) +// uniform distribution from that range. When this method is first called, it +// creates a single new pseudorandom-number generator, exactly as if by the +// expression // -//new java.util.Random -//This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else. -//This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to -//generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator. +// new java.util.Random +// This new pseudorandom-number generator is used thereafter for all calls to +// this method and is used nowhere else. This method is properly synchronized to +// allow correct use by more than one thread. However, if many threads need to +// generate pseudorandom numbers at a great rate, it may reduce contention for +// each thread to have its own pseudorandom-number generator. // -//Returns: -//a pseudorandom double greater than or equal to 0.0 and less than 1.0. -double Math::random() -{ - return Math::rand.nextDouble(); -} +// Returns: +// a pseudorandom double greater than or equal to 0.0 and less than 1.0. +double Math::random() { return Math::rand.nextDouble(); } -//Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, -//and casting the result to type long. In other words, the result is equal to the value of the expression: +// Returns the closest long to the argument. The result is rounded to an integer +// by adding 1/2, taking the floor of the result, and casting the result to type +// long. In other words, the result is equal to the value of the expression: //(long)Math.floor(a + 0.5d) -//Special cases: +// Special cases: // -//If the argument is NaN, the result is 0. -//If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the -//value of Long.MIN_VALUE. -//If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the -//value of Long.MAX_VALUE. -//Parameters: -//a - a floating-point value to be rounded to a long. -//Returns: -//the value of the argument rounded to the nearest long value. -__int64 Math::round( double d ) -{ - // 4jcraft fixes the fact that if double is a huge - // number than the cast of d to int64_t overflows +// If the argument is NaN, the result is 0. +// If the argument is negative infinity or any value less than or equal to the +// value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE. +// If the argument is positive infinity or any value greater than or equal to +// the value of Long.MAX_VALUE, the result is equal to the value of +// Long.MAX_VALUE. Parameters: a - a floating-point value to be rounded to a +// long. Returns: the value of the argument rounded to the nearest long value. +__int64 Math::round(double d) { + // 4jcraft fixes the fact that if double is a huge + // number than the cast of d to int64_t overflows - d = floor( d + 0.5 ); + d = floor(d + 0.5); - // if smaller or bigger than representable int64 than return the max - if(d >= (double)INT64_MAX) { - return INT64_MAX; + // if smaller or bigger than representable int64 than return the max + if (d >= (double)INT64_MAX) { + return INT64_MAX; - } else if (d <= (double)INT64_MIN) { - return INT64_MIN; - } + } else if (d <= (double)INT64_MIN) { + return INT64_MIN; + } - return (int64_t) d; + return (int64_t)d; } -int Math::_max(int a, int b) -{ - return a > b ? a : b; +int Math::_max(int a, int b) { return a > b ? a : b; } + +int Math::_min(int a, int b) { return a < b ? a : b; } + +float Math::_max(float a, float b) { return a > b ? a : b; } + +float Math::_min(float a, float b) { return a < b ? a : b; } + +float Math::wrapDegrees(float input) { + while (input >= 360.0f) input -= 360.0f; + if (input >= 180.0f) input -= 360.0f; + if (input < -180.0f) input += 360.0f; + return input; } -int Math::_min(int a, int b) -{ - return a < b ? a : b; -} - -float Math::_max(float a, float b) -{ - return a > b ? a : b; -} - -float Math::_min(float a, float b) -{ - return a < b ? a : b; -} - -float Math::wrapDegrees(float input) -{ - while(input>=360.0f)input-=360.0f; - if (input >= 180.0f) input -= 360.0f; - if (input < -180.0f) input += 360.0f; - return input; -} - -double Math::wrapDegrees(double input) -{ - while(input>=360.0)input-=360.0; - if (input >= 180.0) input -= 360.0; - if (input < -180.0) input += 360.0; - return input; +double Math::wrapDegrees(double input) { + while (input >= 360.0) input -= 360.0; + if (input >= 180.0) input -= 360.0; + if (input < -180.0) input += 360.0; + return input; } diff --git a/Minecraft.World/Util/JavaMath.h b/Minecraft.World/Util/JavaMath.h index fcd095c8b..aac3fb477 100644 --- a/Minecraft.World/Util/JavaMath.h +++ b/Minecraft.World/Util/JavaMath.h @@ -1,19 +1,18 @@ #pragma once #include "Random.h" -class Math -{ +class Math { private: - static Random rand; + static Random rand; public: - static double random(); - static __int64 round( double d ); - static int _max(int a, int b); - static float _max(float a, float b); - static int _min(int a, int b); - static float _min(float a, float b); + static double random(); + static __int64 round(double d); + static int _max(int a, int b); + static float _max(float a, float b); + static int _min(int a, int b); + static float _min(float a, float b); - static float wrapDegrees(float input); - static double wrapDegrees(double input); + static float wrapDegrees(float input); + static double wrapDegrees(double input); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Language.cpp b/Minecraft.World/Util/Language.cpp index 9ffbf4c2f..43039ba34 100644 --- a/Minecraft.World/Util/Language.cpp +++ b/Minecraft.World/Util/Language.cpp @@ -3,52 +3,47 @@ // 4J - TODO - properly implement -Language *Language::singleton = nullptr; +Language* Language::singleton = nullptr; -Language::Language() -{ -} +Language::Language() {} -Language *Language::getInstance() -{ - // 4jcraft, fixes static init fiassco in I18n.cpp - if(singleton == nullptr) { - singleton = new Language(); - } +Language* Language::getInstance() { + // 4jcraft, fixes static init fiassco in I18n.cpp + if (singleton == nullptr) { + singleton = new Language(); + } - return singleton; + return singleton; } /* 4J Jev, creates 2 identical functions. std::wstring Language::getElement(const std::wstring& elementId) { - return elementId; + return elementId; } */ // 4jcraft changed, again const reference into va_start, std forbids -std::wstring Language::getElement(std::wstring elementId, ...) -{ -#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last parameter passed to va_start - we shouldn't need this method anyway - return L""; +std::wstring Language::getElement(std::wstring elementId, ...) { +#ifdef __PSVITA__ // 4J - vita doesn't like having a reference type as the last + // parameter passed to va_start - we shouldn't need this + // method anyway + return L""; #else - va_list args; - va_start(args, elementId); - return getElement(elementId, args); + va_list args; + va_start(args, elementId); + return getElement(elementId, args); #endif } -std::wstring Language::getElement(const std::wstring& elementId, va_list args) -{ - // 4J TODO - return elementId; +std::wstring Language::getElement(const std::wstring& elementId, va_list args) { + // 4J TODO + return elementId; } -std::wstring Language::getElementName(const std::wstring& elementId) -{ - return elementId; +std::wstring Language::getElementName(const std::wstring& elementId) { + return elementId; } -std::wstring Language::getElementDescription(const std::wstring& elementId) -{ - return elementId; +std::wstring Language::getElementDescription(const std::wstring& elementId) { + return elementId; } diff --git a/Minecraft.World/Util/Language.h b/Minecraft.World/Util/Language.h index b04ede3d1..30f3814fa 100644 --- a/Minecraft.World/Util/Language.h +++ b/Minecraft.World/Util/Language.h @@ -1,14 +1,14 @@ #pragma once -class Language -{ +class Language { private: - static Language *singleton; + static Language* singleton; + public: - Language(); - static Language *getInstance(); + Language(); + static Language* getInstance(); std::wstring getElement(std::wstring elementId, ...); - std::wstring getElement(const std::wstring& elementId, va_list args); + std::wstring getElement(const std::wstring& elementId, va_list args); std::wstring getElementName(const std::wstring& elementId); std::wstring getElementDescription(const std::wstring& elementId); }; diff --git a/Minecraft.World/Util/LightLayer.h b/Minecraft.World/Util/LightLayer.h index bceab76b6..ddd457894 100644 --- a/Minecraft.World/Util/LightLayer.h +++ b/Minecraft.World/Util/LightLayer.h @@ -1,14 +1,13 @@ #pragma once -// 4J Stu Richard has added the class like this to the stubs, although the original Java code -// had an enum with a "surrounding" data member, which is set to the value we are setting the enum to +// 4J Stu Richard has added the class like this to the stubs, although the +// original Java code had an enum with a "surrounding" data member, which is set +// to the value we are setting the enum to -class LightLayer -{ +class LightLayer { public: - enum variety - { - Sky = 15, - Block = 0, - }; + enum variety { + Sky = 15, + Block = 0, + }; }; \ No newline at end of file diff --git a/Minecraft.World/Util/Mth.cpp b/Minecraft.World/Util/Mth.cpp index 752986135..a4c27aff5 100644 --- a/Minecraft.World/Util/Mth.cpp +++ b/Minecraft.World/Util/Mth.cpp @@ -8,179 +8,139 @@ const float Mth::RAD_TO_GRAD = PI / 180.0f; const float Mth::DEGRAD = PI / 180.0f; const float Mth::RADDEG = 180.0f / PI; -float *Mth::_sin = NULL; +float* Mth::_sin = NULL; // 4jcraft for clarity constexpr size_t SIN_TAB_CNT = 65536; -const float Mth::sinScale = 65536.0f / (float) (PI * 2); +const float Mth::sinScale = 65536.0f / (float)(PI * 2); // 4J - added - was in static constructor -void Mth::init() -{ +void Mth::init() { _sin = new float[SIN_TAB_CNT]; - for (int i = 0; i < SIN_TAB_CNT; i++) - { - _sin[i] = (float) ::sin(i * PI * 2 / (float) SIN_TAB_CNT); + for (int i = 0; i < SIN_TAB_CNT; i++) { + _sin[i] = (float)::sin(i * PI * 2 / (float)SIN_TAB_CNT); } } -float Mth::sin(float i) -{ - - if(_sin == NULL) init(); // 4J - added +float Mth::sin(float i) { + if (_sin == NULL) init(); // 4J - added - // 4jcraft changed, what ever this was, it was not safe - // fmodf returns between -65536 and 65536 (casted) - // last end is there to shift it into 0 to 65535 - - return _sin[(int32_t) fmodf(i * sinScale, (float) SIN_TAB_CNT) & (SIN_TAB_CNT - 1)]; + // 4jcraft changed, what ever this was, it was not safe + // fmodf returns between -65536 and 65536 (casted) + // last end is there to shift it into 0 to 65535 + + return _sin[(int32_t)fmodf(i * sinScale, (float)SIN_TAB_CNT) & + (SIN_TAB_CNT - 1)]; } -float Mth::cos(float i) -{ - if(_sin == NULL) init(); // 4J - added - // 4jcraft same thing as ::sin but shift by SIN_TAB_CNT / 4 - // which is aquivalent to shift by pi / 2 - // and again the same modulo logic to cramp and map it onto the computed table - - return _sin[(int32_t) fmodf(i * sinScale + ((float) SIN_TAB_CNT / 4), (float) SIN_TAB_CNT) & (SIN_TAB_CNT - 1)]; +float Mth::cos(float i) { + if (_sin == NULL) init(); // 4J - added + // 4jcraft same thing as ::sin but shift by SIN_TAB_CNT / 4 + // which is aquivalent to shift by pi / 2 + // and again the same modulo logic to cramp and map it onto the computed + // table + + return _sin[(int32_t)fmodf(i * sinScale + ((float)SIN_TAB_CNT / 4), + (float)SIN_TAB_CNT) & + (SIN_TAB_CNT - 1)]; } +float Mth::sqrt(float x) { return (float)::sqrt(x); } -float Mth::sqrt(float x) -{ - return (float) ::sqrt(x); -} +float Mth::sqrt(double x) { return (float)::sqrt(x); } -float Mth::sqrt(double x) -{ - return (float) ::sqrt(x); -} - -int Mth::floor(float v) -{ - int i = (int) v; +int Mth::floor(float v) { + int i = (int)v; return v < i ? i - 1 : i; } -__int64 Mth::lfloor(double v) -{ - __int64 i = (__int64) v; +__int64 Mth::lfloor(double v) { + __int64 i = (__int64)v; return v < i ? i - 1 : i; } -int Mth::fastFloor(double x) -{ - return (int) (x + BIG_ENOUGH_FLOAT) - BIG_ENOUGH_INT; +int Mth::fastFloor(double x) { + return (int)(x + BIG_ENOUGH_FLOAT) - BIG_ENOUGH_INT; } -int Mth::floor(double v) -{ - int i = (int) v; +int Mth::floor(double v) { + int i = (int)v; return v < i ? i - 1 : i; } -int Mth::absFloor(double v) -{ - return (int) (v >= 0 ? v : -v + 1); -} +int Mth::absFloor(double v) { return (int)(v >= 0 ? v : -v + 1); } -float Mth::abs(float v) -{ - return v >= 0 ? v : -v; -} +float Mth::abs(float v) { return v >= 0 ? v : -v; } -int Mth::abs(int v) -{ - return v >= 0 ? v : -v; -} +int Mth::abs(int v) { return v >= 0 ? v : -v; } -int Mth::ceil(float v) -{ - int i = (int) v; +int Mth::ceil(float v) { + int i = (int)v; return v > i ? i + 1 : i; } -int Mth::clamp(int value, int min, int max) -{ - if (value < min) - { +int Mth::clamp(int value, int min, int max) { + if (value < min) { return min; } - if (value > max) - { + if (value > max) { return max; } return value; } -float Mth::clamp(float value, float min, float max) -{ - if (value < min) - { - return min; - } - if (value > max) - { - return max; - } - return value; +float Mth::clamp(float value, float min, float max) { + if (value < min) { + return min; + } + if (value > max) { + return max; + } + return value; } -double Mth::asbMax(double a, double b) -{ +double Mth::asbMax(double a, double b) { if (a < 0) a = -a; if (b < 0) b = -b; return a > b ? a : b; } -int Mth::intFloorDiv(int a, int b) -{ +int Mth::intFloorDiv(int a, int b) { if (a < 0) return -((-a - 1) / b) - 1; return a / b; } - -int Mth::nextInt(Random *random, int minInclusive, int maxInclusive) -{ - if (minInclusive >= maxInclusive) - { +int Mth::nextInt(Random* random, int minInclusive, int maxInclusive) { + if (minInclusive >= maxInclusive) { return minInclusive; } return random->nextInt(maxInclusive - minInclusive + 1) + minInclusive; } -float Mth::wrapDegrees(float input) -{ - //input %= 360; - while (input >= 180) - { - input -= 360; - } - while (input < -180) - { - input += 360; - } - return input; +float Mth::wrapDegrees(float input) { + // input %= 360; + while (input >= 180) { + input -= 360; + } + while (input < -180) { + input += 360; + } + return input; } -double Mth::wrapDegrees(double input) -{ - //input %= 360; - while (input >= 180) - { - input -= 360; - } - while (input < -180) - { - input += 360; - } - return input; +double Mth::wrapDegrees(double input) { + // input %= 360; + while (input >= 180) { + input -= 360; + } + while (input < -180) { + input += 360; + } + return input; } // 4J Added -bool Mth::almostEquals( double double1, double double2, double precision) -{ - return (std::abs(double1 - double2) <= precision); +bool Mth::almostEquals(double double1, double double2, double precision) { + return (std::abs(double1 - double2) <= precision); } diff --git a/Minecraft.World/Util/Mth.h b/Minecraft.World/Util/Mth.h index 17119fb1d..e3c8a9145 100644 --- a/Minecraft.World/Util/Mth.h +++ b/Minecraft.World/Util/Mth.h @@ -1,42 +1,45 @@ #pragma once class Random; -class Mth -{ +class Mth { private: - static const int BIG_ENOUGH_INT; + static const int BIG_ENOUGH_INT; static const float BIG_ENOUGH_FLOAT; public: static const float RAD_TO_GRAD; + public: - static const float DEGRAD; - static const float RADDEG; + static const float DEGRAD; + static const float RADDEG; + private: - static float *_sin; + static float* _sin; + private: - static const float sinScale; -public : - static void init(); // 4J added - static float sin(float i); + static const float sinScale; + +public: + static void init(); // 4J added + static float sin(float i); static float cos(float i); static float sqrt(float x); static float sqrt(double x); static int floor(float v); - static __int64 lfloor(double v); + static __int64 lfloor(double v); static int fastFloor(double x); static int floor(double v); static int absFloor(double v); static float abs(float v); - static int abs(int v); + static int abs(int v); static int ceil(float v); - static int clamp(int value, int min, int max) ; - static float clamp(float value, float min, float max); + static int clamp(int value, int min, int max); + static float clamp(float value, float min, float max); static double asbMax(double a, double b); static int intFloorDiv(int a, int b); - static int nextInt(Random *random, int minInclusive, int maxInclusive); - static float wrapDegrees(float input); - static double wrapDegrees(double input); + static int nextInt(Random* random, int minInclusive, int maxInclusive); + static float wrapDegrees(float input); + static double wrapDegrees(double input); - // 4J Added - static bool almostEquals( double double1, double double2, double precision); + // 4J Added + static bool almostEquals(double double1, double double2, double precision); }; \ No newline at end of file diff --git a/Minecraft.World/Util/NumberFormatters.h b/Minecraft.World/Util/NumberFormatters.h index 08b3dda55..29a1bba51 100644 --- a/Minecraft.World/Util/NumberFormatters.h +++ b/Minecraft.World/Util/NumberFormatters.h @@ -1,35 +1,32 @@ #pragma once - -// 4J Stu - The java formated numbers based on a local passed in, but I am just going for a constant format here -class NumberFormat -{ +// 4J Stu - The java formated numbers based on a local passed in, but I am just +// going for a constant format here +class NumberFormat { public: - static std::wstring format(int value) - { - // TODO 4J Stu - Change the length of the formatted number - wchar_t output[256]; - swprintf( output, 256, L"%d", value); - std::wstring result = std::wstring( output ); - return result; - } + static std::wstring format(int value) { + // TODO 4J Stu - Change the length of the formatted number + wchar_t output[256]; + swprintf(output, 256, L"%d", value); + std::wstring result = std::wstring(output); + return result; + } }; - -class DecimalFormat -{ +class DecimalFormat { private: - const std::wstring formatString; -public: - std::wstring format(double value) - { - // TODO 4J Stu - Change the length of the formatted number - wchar_t output[256]; - swprintf( output, 256, formatString.c_str(), value); - std::wstring result = std::wstring( output ); - return result; - } + const std::wstring formatString; - // 4J Stu - The java code took a string format, we take a printf format string - DecimalFormat(std::wstring x) : formatString( x ) {}; +public: + std::wstring format(double value) { + // TODO 4J Stu - Change the length of the formatted number + wchar_t output[256]; + swprintf(output, 256, formatString.c_str(), value); + std::wstring result = std::wstring(output); + return result; + } + + // 4J Stu - The java code took a string format, we take a printf format + // string + DecimalFormat(std::wstring x) : formatString(x) {}; }; \ No newline at end of file diff --git a/Minecraft.World/Util/ParticleTypes.h b/Minecraft.World/Util/ParticleTypes.h index d822008e9..eebf07048 100644 --- a/Minecraft.World/Util/ParticleTypes.h +++ b/Minecraft.World/Util/ParticleTypes.h @@ -1,56 +1,67 @@ #pragma once // 4J-PB added to avoid string compares on adding particles -enum ePARTICLE_TYPE -{ - eParticleType_bubble, - eParticleType_smoke, - eParticleType_note, - eParticleType_netherportal, // 4J - This particle should only be used by the Nether portal. Everything else should use eParticleType_end - eParticleType_endportal, // 4J - Seperated this from torches and fires - eParticleType_explode, - eParticleType_flame, - eParticleType_lava, - eParticleType_footstep, - eParticleType_splash, - eParticleType_largesmoke, - eParticleType_reddust, - eParticleType_snowballpoof, - eParticleType_snowshovel, - eParticleType_slime, - eParticleType_heart, - eParticleType_suspended, - eParticleType_depthsuspend, - eParticleType_crit, - eParticleType_hugeexplosion, - eParticleType_largeexplode, - eParticleType_townaura, - eParticleType_spell, - eParticleType_mobSpell, - eParticleType_instantSpell, - eParticleType_magicCrit, - eParticleType_dripWater, - eParticleType_dripLava, - eParticleType_enchantmenttable, - eParticleType_dragonbreath, - eParticleType_ender, // 4J Added - These are things that used the "portal" particle but are actually end related entities - eParticleType_angryVillager, - eParticleType_happyVillager, +enum ePARTICLE_TYPE { + eParticleType_bubble, + eParticleType_smoke, + eParticleType_note, + eParticleType_netherportal, // 4J - This particle should only be used by + // the Nether portal. Everything else should + // use eParticleType_end + eParticleType_endportal, // 4J - Seperated this from torches and fires + eParticleType_explode, + eParticleType_flame, + eParticleType_lava, + eParticleType_footstep, + eParticleType_splash, + eParticleType_largesmoke, + eParticleType_reddust, + eParticleType_snowballpoof, + eParticleType_snowshovel, + eParticleType_slime, + eParticleType_heart, + eParticleType_suspended, + eParticleType_depthsuspend, + eParticleType_crit, + eParticleType_hugeexplosion, + eParticleType_largeexplode, + eParticleType_townaura, + eParticleType_spell, + eParticleType_mobSpell, + eParticleType_instantSpell, + eParticleType_magicCrit, + eParticleType_dripWater, + eParticleType_dripLava, + eParticleType_enchantmenttable, + eParticleType_dragonbreath, + eParticleType_ender, // 4J Added - These are things that used the "portal" + // particle but are actually end related entities + eParticleType_angryVillager, + eParticleType_happyVillager, - // 4J-JEV: In the java, the particle name was used to sneak parameters in for the Terrain and IconCrack particle constructors. - - eParticleType_iconcrack_base = 0x100000, // There's range of iconcrack particle types based on item id and data. - eParticleType_iconcrack_last = 0x1FFFFF, - eParticleType_tilecrack_base = 0x200000, // There's a range of tilecrack particle types based on tile id and data. - eParticleType_tilecrack_last = 0x2FFFFF, - // 0x0000FF, <- these bits are for storing the data value. - // 0x0FFF00, <- these bits are for encoding tile/item id. - // 0x300000, <- these bits show if its an icon/tile or not. + // 4J-JEV: In the java, the particle name was used to sneak parameters in + // for the Terrain and IconCrack particle constructors. + + eParticleType_iconcrack_base = + 0x100000, // There's range of iconcrack particle types based on item + // id and data. + eParticleType_iconcrack_last = 0x1FFFFF, + eParticleType_tilecrack_base = + 0x200000, // There's a range of tilecrack particle types based on tile + // id and data. + eParticleType_tilecrack_last = 0x2FFFFF, + // 0x0000FF, <- these bits are for storing the data value. + // 0x0FFF00, <- these bits are for encoding tile/item id. + // 0x300000, <- these bits show if its an icon/tile or not. }; -#define PARTICLE_TILECRACK(id,data) ( (ePARTICLE_TYPE) ( ((int) eParticleType_tilecrack_base) | ((0x0FFF & id) << 8) | (0x0FF & data)) ) -#define PARTICLE_ICONCRACK(id,data) ( (ePARTICLE_TYPE) ( ((int) eParticleType_iconcrack_base) | ((0x0FFF & id) << 8) | (0x0FF & data)) ) +#define PARTICLE_TILECRACK(id, data) \ + ((ePARTICLE_TYPE)(((int)eParticleType_tilecrack_base) | \ + ((0x0FFF & id) << 8) | (0x0FF & data))) +#define PARTICLE_ICONCRACK(id, data) \ + ((ePARTICLE_TYPE)(((int)eParticleType_iconcrack_base) | \ + ((0x0FFF & id) << 8) | (0x0FF & data))) -#define PARTICLE_CRACK_ID(ePType) ((0x0FFF00 & (int)ePType) >> 8) +#define PARTICLE_CRACK_ID(ePType) ((0x0FFF00 & (int)ePType) >> 8) #define PARTICLE_CRACK_DATA(ePType) (0x0FF & (int)ePType) \ No newline at end of file diff --git a/Minecraft.World/Util/PerformanceTimer.cpp b/Minecraft.World/Util/PerformanceTimer.cpp index 42b00a2a7..4b6c02c95 100644 --- a/Minecraft.World/Util/PerformanceTimer.cpp +++ b/Minecraft.World/Util/PerformanceTimer.cpp @@ -1,19 +1,16 @@ #include "../Platform/stdafx.h" #include "PerformanceTimer.h" -PerformanceTimer::PerformanceTimer() -{ - Reset(); +PerformanceTimer::PerformanceTimer() { Reset(); } + +void PerformanceTimer::Reset() { + m_startTime = std::chrono::steady_clock::now(); } -void PerformanceTimer::Reset() -{ - m_startTime = std::chrono::steady_clock::now(); -} +void PerformanceTimer::PrintElapsedTime(const std::wstring& description) { + const std::chrono::duration elapsedTime = + std::chrono::steady_clock::now() - m_startTime; -void PerformanceTimer::PrintElapsedTime(const std::wstring &description) -{ - const std::chrono::duration elapsedTime = std::chrono::steady_clock::now() - m_startTime; - - app.DebugPrintf("TIMER: %ls: Elapsed time %f\n", description.c_str(), elapsedTime.count()); + app.DebugPrintf("TIMER: %ls: Elapsed time %f\n", description.c_str(), + elapsedTime.count()); } diff --git a/Minecraft.World/Util/PerformanceTimer.h b/Minecraft.World/Util/PerformanceTimer.h index 7fca90507..e0c1b443d 100644 --- a/Minecraft.World/Util/PerformanceTimer.h +++ b/Minecraft.World/Util/PerformanceTimer.h @@ -12,13 +12,12 @@ #endif #include -class PerformanceTimer -{ +class PerformanceTimer { private: - std::chrono::steady_clock::time_point m_startTime; + std::chrono::steady_clock::time_point m_startTime; public: - PerformanceTimer(); - void Reset(); - void PrintElapsedTime(const std::wstring &description); + PerformanceTimer(); + void Reset(); + void PrintElapsedTime(const std::wstring& description); }; diff --git a/Minecraft.World/Util/PortableFileIO.h b/Minecraft.World/Util/PortableFileIO.h index aed99aa31..037bcdb4a 100644 --- a/Minecraft.World/Util/PortableFileIO.h +++ b/Minecraft.World/Util/PortableFileIO.h @@ -6,157 +6,141 @@ #include "StringHelpers.h" -namespace PortableFileIO -{ - enum class BinaryReadStatus - { - ok, - not_found, - too_large, - read_error, - }; +namespace PortableFileIO { +enum class BinaryReadStatus { + ok, + not_found, + too_large, + read_error, +}; - struct BinaryReadResult - { - BinaryReadStatus status; - std::size_t bytesRead; - std::size_t fileSize; - }; +struct BinaryReadResult { + BinaryReadStatus status; + std::size_t bytesRead; + std::size_t fileSize; +}; - inline std::FILE *OpenBinaryFileForRead(const std::wstring &path) - { +inline std::FILE* OpenBinaryFileForRead(const std::wstring& path) { #if defined(_WIN32) - return _wfopen(path.c_str(), L"rb"); + return _wfopen(path.c_str(), L"rb"); #else - const std::string nativePath = wstringtofilename(path); - return std::fopen(nativePath.c_str(), "rb"); + const std::string nativePath = wstringtofilename(path); + return std::fopen(nativePath.c_str(), "rb"); #endif - } - - inline bool Seek(std::FILE *file, std::size_t offset, int origin) - { -#if defined(_WIN32) - return _fseeki64(file, static_cast<__int64>(offset), origin) == 0; -#else - return fseeko(file, static_cast(offset), origin) == 0; -#endif - } - - inline __int64 Tell(std::FILE *file) - { -#if defined(_WIN32) - return _ftelli64(file); -#else - return static_cast<__int64>(ftello(file)); -#endif - } - - inline BinaryReadResult ReadBinaryFile(const std::wstring &path, void *buffer, std::size_t capacity) - { - std::FILE *stream = OpenBinaryFileForRead(path); - if (stream == NULL) - { - return { BinaryReadStatus::not_found, 0, 0 }; - } - - if (!Seek(stream, 0, SEEK_END)) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, 0 }; - } - - const __int64 endPosition = Tell(stream); - if (endPosition < 0) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, 0 }; - } - - const std::size_t fileSize = static_cast(endPosition); - if (fileSize > capacity) - { - std::fclose(stream); - return { BinaryReadStatus::too_large, 0, fileSize }; - } - - if (!Seek(stream, 0, SEEK_SET)) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, fileSize }; - } - - const std::size_t bytesRead = std::fread(buffer, 1, fileSize, stream); - const bool failed = std::ferror(stream) != 0; - std::fclose(stream); - if (failed || bytesRead != fileSize) - { - return { BinaryReadStatus::read_error, bytesRead, fileSize }; - } - - return { BinaryReadStatus::ok, bytesRead, fileSize }; - } - - inline BinaryReadResult ReadBinaryFileSegment(const std::wstring &path, std::size_t offset, void *buffer, std::size_t bytesToRead) - { - std::FILE *stream = OpenBinaryFileForRead(path); - if (stream == NULL) - { - return { BinaryReadStatus::not_found, 0, 0 }; - } - - if (!Seek(stream, 0, SEEK_END)) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, 0 }; - } - - const __int64 endPosition = Tell(stream); - if (endPosition < 0) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, 0 }; - } - - const std::size_t fileSize = static_cast(endPosition); - if ((offset > fileSize) || (bytesToRead > (fileSize - offset))) - { - std::fclose(stream); - return { BinaryReadStatus::too_large, 0, fileSize }; - } - - if (!Seek(stream, offset, SEEK_SET)) - { - std::fclose(stream); - return { BinaryReadStatus::read_error, 0, fileSize }; - } - - const std::size_t bytesRead = std::fread(buffer, 1, bytesToRead, stream); - const bool failed = std::ferror(stream) != 0; - std::fclose(stream); - if (failed || bytesRead != bytesToRead) - { - return { BinaryReadStatus::read_error, bytesRead, fileSize }; - } - - return { BinaryReadStatus::ok, bytesRead, fileSize }; - } - - inline bool WriteBinaryFile(const std::wstring &path, const void *buffer, std::size_t bytesToWrite) - { -#if defined(_WIN32) - std::FILE *stream = _wfopen(path.c_str(), L"wb"); -#else - const std::string nativePath = wstringtofilename(path); - std::FILE *stream = std::fopen(nativePath.c_str(), "wb"); -#endif - if (stream == NULL) - { - return false; - } - - const std::size_t bytesWritten = std::fwrite(buffer, 1, bytesToWrite, stream); - const bool failed = std::ferror(stream) != 0 || bytesWritten != bytesToWrite; - const bool closeFailed = std::fclose(stream) != 0; - return !failed && !closeFailed; - } } + +inline bool Seek(std::FILE* file, std::size_t offset, int origin) { +#if defined(_WIN32) + return _fseeki64(file, static_cast<__int64>(offset), origin) == 0; +#else + return fseeko(file, static_cast(offset), origin) == 0; +#endif +} + +inline __int64 Tell(std::FILE* file) { +#if defined(_WIN32) + return _ftelli64(file); +#else + return static_cast<__int64>(ftello(file)); +#endif +} + +inline BinaryReadResult ReadBinaryFile(const std::wstring& path, void* buffer, + std::size_t capacity) { + std::FILE* stream = OpenBinaryFileForRead(path); + if (stream == NULL) { + return {BinaryReadStatus::not_found, 0, 0}; + } + + if (!Seek(stream, 0, SEEK_END)) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, 0}; + } + + const __int64 endPosition = Tell(stream); + if (endPosition < 0) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, 0}; + } + + const std::size_t fileSize = static_cast(endPosition); + if (fileSize > capacity) { + std::fclose(stream); + return {BinaryReadStatus::too_large, 0, fileSize}; + } + + if (!Seek(stream, 0, SEEK_SET)) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, fileSize}; + } + + const std::size_t bytesRead = std::fread(buffer, 1, fileSize, stream); + const bool failed = std::ferror(stream) != 0; + std::fclose(stream); + if (failed || bytesRead != fileSize) { + return {BinaryReadStatus::read_error, bytesRead, fileSize}; + } + + return {BinaryReadStatus::ok, bytesRead, fileSize}; +} + +inline BinaryReadResult ReadBinaryFileSegment(const std::wstring& path, + std::size_t offset, void* buffer, + std::size_t bytesToRead) { + std::FILE* stream = OpenBinaryFileForRead(path); + if (stream == NULL) { + return {BinaryReadStatus::not_found, 0, 0}; + } + + if (!Seek(stream, 0, SEEK_END)) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, 0}; + } + + const __int64 endPosition = Tell(stream); + if (endPosition < 0) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, 0}; + } + + const std::size_t fileSize = static_cast(endPosition); + if ((offset > fileSize) || (bytesToRead > (fileSize - offset))) { + std::fclose(stream); + return {BinaryReadStatus::too_large, 0, fileSize}; + } + + if (!Seek(stream, offset, SEEK_SET)) { + std::fclose(stream); + return {BinaryReadStatus::read_error, 0, fileSize}; + } + + const std::size_t bytesRead = std::fread(buffer, 1, bytesToRead, stream); + const bool failed = std::ferror(stream) != 0; + std::fclose(stream); + if (failed || bytesRead != bytesToRead) { + return {BinaryReadStatus::read_error, bytesRead, fileSize}; + } + + return {BinaryReadStatus::ok, bytesRead, fileSize}; +} + +inline bool WriteBinaryFile(const std::wstring& path, const void* buffer, + std::size_t bytesToWrite) { +#if defined(_WIN32) + std::FILE* stream = _wfopen(path.c_str(), L"wb"); +#else + const std::string nativePath = wstringtofilename(path); + std::FILE* stream = std::fopen(nativePath.c_str(), "wb"); +#endif + if (stream == NULL) { + return false; + } + + const std::size_t bytesWritten = + std::fwrite(buffer, 1, bytesToWrite, stream); + const bool failed = + std::ferror(stream) != 0 || bytesWritten != bytesToWrite; + const bool closeFailed = std::fclose(stream) != 0; + return !failed && !closeFailed; +} +} // namespace PortableFileIO diff --git a/Minecraft.World/Util/Pos.cpp b/Minecraft.World/Util/Pos.cpp index 50048632a..931bf3e41 100644 --- a/Minecraft.World/Util/Pos.cpp +++ b/Minecraft.World/Util/Pos.cpp @@ -2,247 +2,142 @@ #include "Pos.h" +Pos::Pos() { x = y = z = 0; } - -Pos::Pos() -{ - x = y = z = 0; +Pos::Pos(int x, int y, int z) { + this->x = x; + this->y = y; + this->z = z; } -Pos::Pos(int x, int y, int z) -{ - this->x = x; - this->y = y; - this->z = z; -} - -Pos::Pos(Pos *position) -{ - this->x = position->x; - this->y = position->y; - this->z = position->z; +Pos::Pos(Pos* position) { + this->x = position->x; + this->y = position->y; + this->z = position->z; } //@Override -//public boolean equals(Object other) -bool Pos::equals(void *other) -{ - // TODO 4J Stu I cannot do a dynamic_cast from a void pointer - // If I cast it to a Pos then do a dynamic_cast will it still return NULL if it wasn't originally a Pos? - if (!( dynamic_cast( (Pos *)other ) != NULL )) - { - return false; - } +// public boolean equals(Object other) +bool Pos::equals(void* other) { + // TODO 4J Stu I cannot do a dynamic_cast from a void pointer + // If I cast it to a Pos then do a dynamic_cast will it still return NULL if + // it wasn't originally a Pos? + if (!(dynamic_cast((Pos*)other) != NULL)) { + return false; + } - Pos *p = (Pos *) other; - return x == p->x && y == p->y && z == p->z; + Pos* p = (Pos*)other; + return x == p->x && y == p->y && z == p->z; } //@Override -int Pos::hashCode() -{ - return x + (z << 8) + (y << 16); +int Pos::hashCode() { return x + (z << 8) + (y << 16); } + +int Pos::compareTo(Pos* pos) { + if (y == pos->y) { + if (z == pos->z) { + return x - pos->x; + } + return z - pos->z; + } + return y - pos->y; } -int Pos::compareTo(Pos *pos) -{ - if (y == pos->y) - { - if (z == pos->z) - { - return x - pos->x; - } - return z - pos->z; - } - return y - pos->y; +Pos* Pos::offset(int x, int y, int z) { + return new Pos(this->x + x, this->y + y, this->z + z); } -Pos *Pos::offset(int x, int y, int z) -{ - return new Pos(this->x + x, this->y + y, this->z + z); +void Pos::set(int x, int y, int z) { + this->x = x; + this->y = y; + this->z = z; } -void Pos::set(int x, int y, int z) -{ - this->x = x; - this->y = y; - this->z = z; +void Pos::set(Pos* pos) { + this->x = pos->x; + this->y = pos->y; + this->z = pos->z; } -void Pos::set(Pos *pos) -{ - this->x = pos->x; - this->y = pos->y; - this->z = pos->z; +Pos* Pos::above() { return new Pos(x, y + 1, z); } + +Pos* Pos::above(int steps) { return new Pos(x, y + steps, z); } + +Pos* Pos::below() { return new Pos(x, y - 1, z); } + +Pos* Pos::below(int steps) { return new Pos(x, y - steps, z); } + +Pos* Pos::north() { return new Pos(x, y, z - 1); } + +Pos* Pos::north(int steps) { return new Pos(x, y, z - steps); } + +Pos* Pos::south() { return new Pos(x, y, z + 1); } + +Pos* Pos::south(int steps) { return new Pos(x, y, z + steps); } + +Pos* Pos::west() { return new Pos(x - 1, y, z); } + +Pos* Pos::west(int steps) { return new Pos(x - 1, y, z); } + +Pos* Pos::east() { return new Pos(x + 1, y, z); } + +Pos* Pos::east(int steps) { return new Pos(x + steps, y, z); } + +void Pos::move(int x, int y, int z) { + this->x += x; + this->y += y; + this->z += z; } -Pos *Pos::above() -{ - return new Pos(x, y + 1, z); +void Pos::move(Pos pos) { + this->x += pos.x; + this->y += pos.y; + this->z += pos.z; } -Pos *Pos::above(int steps) -{ - return new Pos(x, y + steps, z); +void Pos::moveX(int steps) { this->x += steps; } + +void Pos::moveY(int steps) { this->y += steps; } + +void Pos::moveZ(int steps) { this->z += steps; } + +void Pos::moveUp(int steps) { this->y += steps; } + +void Pos::moveUp() { this->y++; } + +void Pos::moveDown(int steps) { this->y -= steps; } + +void Pos::moveDown() { this->y--; } + +void Pos::moveEast(int steps) { this->x += steps; } + +void Pos::moveEast() { this->x++; } + +void Pos::moveWest(int steps) { this->x -= steps; } + +void Pos::moveWest() { this->x--; } + +void Pos::moveNorth(int steps) { this->z -= steps; } + +void Pos::moveNorth() { this->z--; } + +void Pos::moveSouth(int steps) { this->z += steps; } + +void Pos::moveSouth() { this->z++; } + +double Pos::dist(int x, int y, int z) { + int dx = this->x - x; + int dy = this->y - y; + int dz = this->z - z; + + return sqrt((double)dx * dx + dy * dy + dz * dz); } -Pos *Pos::below() -{ - return new Pos(x, y - 1, z); -} +double Pos::dist(Pos* pos) { return dist(pos->x, pos->y, pos->z); } -Pos *Pos::below(int steps) -{ - return new Pos(x, y - steps, z); -} - -Pos *Pos::north() -{ - return new Pos(x, y, z - 1); -} - -Pos *Pos::north(int steps) -{ - return new Pos(x, y, z - steps); -} - -Pos *Pos::south() -{ - return new Pos(x, y, z + 1); -} - -Pos *Pos::south(int steps) -{ - return new Pos(x, y, z + steps); -} - -Pos *Pos::west() -{ - return new Pos(x - 1, y, z); -} - -Pos *Pos::west(int steps) -{ - return new Pos(x - 1, y, z); -} - -Pos *Pos::east() -{ - return new Pos(x + 1, y, z); -} - -Pos *Pos::east(int steps) -{ - return new Pos(x + steps, y, z); -} - -void Pos::move(int x, int y, int z) -{ - this->x += x; - this->y += y; - this->z += z; -} - -void Pos::move(Pos pos) -{ - this->x += pos.x; - this->y += pos.y; - this->z += pos.z; -} - -void Pos::moveX(int steps) -{ - this->x += steps; -} - -void Pos::moveY(int steps) -{ - this->y += steps; -} - -void Pos::moveZ(int steps) -{ - this->z += steps; -} - -void Pos::moveUp(int steps) -{ - this->y += steps; -} - -void Pos::moveUp() -{ - this->y++; -} - -void Pos::moveDown(int steps) -{ - this->y -= steps; -} - -void Pos::moveDown() -{ - this->y--; -} - -void Pos::moveEast(int steps) -{ - this->x += steps; -} - -void Pos::moveEast() -{ - this->x++; -} - -void Pos::moveWest(int steps) -{ - this->x -= steps; -} - -void Pos::moveWest() -{ - this->x--; -} - -void Pos::moveNorth(int steps) -{ - this->z -= steps; -} - -void Pos::moveNorth() -{ - this->z--; -} - -void Pos::moveSouth(int steps) -{ - this->z += steps; -} - -void Pos::moveSouth() -{ - this->z++; -} - -double Pos::dist(int x, int y, int z) -{ - int dx = this->x - x; - int dy = this->y - y; - int dz = this->z - z; - - return sqrt( (double) dx * dx + dy * dy + dz * dz); -} - -double Pos::dist(Pos *pos) -{ - return dist(pos->x, pos->y, pos->z); -} - -float Pos::distSqr(int x, int y, int z) -{ - int dx = this->x - x; - int dy = this->y - y; - int dz = this->z - z; - return dx * dx + dy * dy + dz * dz; +float Pos::distSqr(int x, int y, int z) { + int dx = this->x - x; + int dy = this->y - y; + int dz = this->z - z; + return dx * dx + dy * dy + dz * dz; } \ No newline at end of file diff --git a/Minecraft.World/Util/Pos.h b/Minecraft.World/Util/Pos.h index a07c7fe38..d7287aea1 100644 --- a/Minecraft.World/Util/Pos.h +++ b/Minecraft.World/Util/Pos.h @@ -1,97 +1,96 @@ #pragma once // Pos implements Comparable -// We don't REALLY need it as it's main use it to make things easy +// We don't REALLY need it as it's main use it to make things easy // to handle in the java array/list classes, but adding to help // maintain as much original code as possible -//class Pos //implements Comparable -class Pos -{ +// class Pos //implements Comparable +class Pos { public: - int x; - int y; - int z; + int x; + int y; + int z; - Pos(); + Pos(); - Pos(int x, int y, int z); + Pos(int x, int y, int z); - Pos(Pos *position); + Pos(Pos* position); - //@Override - //public boolean equals(Object other) - bool equals(void *other); + //@Override + // public boolean equals(Object other) + bool equals(void* other); - int hashCode(); + int hashCode(); - int compareTo(Pos *pos); + int compareTo(Pos* pos); - Pos *offset(int x, int y, int z); + Pos* offset(int x, int y, int z); - void set(int x, int y, int z); + void set(int x, int y, int z); - void set(Pos *pos); + void set(Pos* pos); - Pos *above(); + Pos* above(); - Pos *above(int steps); + Pos* above(int steps); - Pos *below(); + Pos* below(); - Pos *below(int steps); + Pos* below(int steps); - Pos *north(); + Pos* north(); - Pos *north(int steps); + Pos* north(int steps); - Pos *south(); + Pos* south(); - Pos *south(int steps); + Pos* south(int steps); - Pos *west(); + Pos* west(); - Pos *west(int steps); + Pos* west(int steps); - Pos *east(); + Pos* east(); - Pos *east(int steps); + Pos* east(int steps); - void move(int x, int y, int z); + void move(int x, int y, int z); - void move(Pos pos); + void move(Pos pos); - void moveX(int steps); + void moveX(int steps); - void moveY(int steps); + void moveY(int steps); - void moveZ(int steps); + void moveZ(int steps); - void moveUp(int steps); + void moveUp(int steps); - void moveUp(); + void moveUp(); - void moveDown(int steps); + void moveDown(int steps); - void moveDown(); + void moveDown(); - void moveEast(int steps); + void moveEast(int steps); - void moveEast(); + void moveEast(); - void moveWest(int steps); + void moveWest(int steps); - void moveWest(); + void moveWest(); - void moveNorth(int steps); + void moveNorth(int steps); - void moveNorth(); + void moveNorth(); - void moveSouth(int steps); + void moveSouth(int steps); - void moveSouth(); + void moveSouth(); - double dist(int x, int y, int z); + double dist(int x, int y, int z); - double dist(Pos *pos); - float distSqr(int x, int y, int z); + double dist(Pos* pos); + float distSqr(int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/Util/ProgressListener.h b/Minecraft.World/Util/ProgressListener.h index d258f1342..36a677ef2 100644 --- a/Minecraft.World/Util/ProgressListener.h +++ b/Minecraft.World/Util/ProgressListener.h @@ -1,15 +1,13 @@ #pragma once - -class ProgressListener -{ +class ProgressListener { public: - // 4J Stu - Changed all messages here to be string Id's - virtual void progressStagePercentage(int p) = 0; - virtual void progressStart(int stringId) = 0; - virtual void progressStartNoAbort(int stringId) = 0; - virtual void progressStage(int stringId) = 0; + // 4J Stu - Changed all messages here to be string Id's + virtual void progressStagePercentage(int p) = 0; + virtual void progressStart(int stringId) = 0; + virtual void progressStartNoAbort(int stringId) = 0; + virtual void progressStage(int stringId) = 0; - // 4J-PB - added to display bytes retrieved of a save transfer - virtual void progressStage(std::wstring &wstrText) = 0; + // 4J-PB - added to display bytes retrieved of a save transfer + virtual void progressStage(std::wstring& wstrText) = 0; }; \ No newline at end of file diff --git a/Minecraft.World/Util/Random.cpp b/Minecraft.World/Util/Random.cpp index 20c92c588..cd15b4a89 100644 --- a/Minecraft.World/Util/Random.cpp +++ b/Minecraft.World/Util/Random.cpp @@ -1,14 +1,14 @@ -#include "../Platform/stdafx.h" +#include "../Platform/stdafx.h" #include "Random.h" #include -#include // for int64_t +#include // for int64_t #include "../Platform/System.h" -Random::Random() -{ - // 4J - jave now uses the system nanosecond counter added to a "seedUniquifier" to get an initial seed. Our nanosecond timer is actually only millisecond accuate, so - // use QueryPerformanceCounter here instead - __int64 seed; +Random::Random() { + // 4J - jave now uses the system nanosecond counter added to a + // "seedUniquifier" to get an initial seed. Our nanosecond timer is actually + // only millisecond accuate, so use QueryPerformanceCounter here instead + __int64 seed; struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -17,102 +17,75 @@ Random::Random() seed += 8682522807148012LL; - setSeed(seed); + setSeed(seed); } -Random::Random(__int64 seed) -{ - setSeed(seed); -} +Random::Random(__int64 seed) { setSeed(seed); } -void Random::setSeed(__int64 s) -{ +void Random::setSeed(__int64 s) { this->seed = (s ^ 0x5DEECE66DLL) & ((1LL << 48) - 1); haveNextNextGaussian = false; } -int Random::next(int bits) -{ - // 4jcraft, cast to uint64_t for modulo arithmethic - // overflow of int undefined, and its guaranteed here. - seed = ((uint64_t) seed * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1); +int Random::next(int bits) { + // 4jcraft, cast to uint64_t for modulo arithmethic + // overflow of int undefined, and its guaranteed here. + seed = ((uint64_t)seed * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1); return (int)(seed >> (48 - bits)); } -void Random::nextBytes(uint8_t *bytes, unsigned int count) -{ - for(unsigned int i = 0; i < count; i++ ) - { - bytes[i] = (uint8_t)next(8); - } +void Random::nextBytes(uint8_t* bytes, unsigned int count) { + for (unsigned int i = 0; i < count; i++) { + bytes[i] = (uint8_t)next(8); + } } -double Random::nextDouble() -{ - - return (((__int64)next(26) << 27) + next(27)) - / (double)(1LL << 53); +double Random::nextDouble() { + return (((__int64)next(26) << 27) + next(27)) / (double)(1LL << 53); } -double Random::nextGaussian() -{ - if (haveNextNextGaussian) - { +double Random::nextGaussian() { + if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; - } - else - { + } else { double v1, v2, s; - do - { - v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 - v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 + do { + v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 + v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); - double multiplier = sqrt(-2 * log(s)/s); + double multiplier = sqrt(-2 * log(s) / s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } } -int Random::nextInt() -{ - return next(32); -} - -int Random::nextInt(int n) -{ - assert (n>0); +int Random::nextInt() { return next(32); } +int Random::nextInt(int n) { + assert(n > 0); if ((n & -n) == n) // i.e., n is a power of 2 - // 4jcraft added casts to unsigned (and uint64_t) - return (int)(((uint64_t)next(31) * n) >> 31); // 4J Stu - Made __int64 instead of long + // 4jcraft added casts to unsigned (and uint64_t) + return (int)(((uint64_t)next(31) * n) >> + 31); // 4J Stu - Made __int64 instead of long int bits, val; - do - { + do { bits = next(31); val = bits % n; - // 4jcraft added a cast to prevent overflow - } while((int64_t) bits - val + (n-1) < 0); + // 4jcraft added a cast to prevent overflow + } while ((int64_t)bits - val + (n - 1) < 0); return val; } -float Random::nextFloat() -{ - return next(24) / ((float)(1 << 24)); +float Random::nextFloat() { return next(24) / ((float)(1 << 24)); } + +__int64 Random::nextLong() { + // 4jcraft added casts to unsigned + return (int64_t)((uint64_t)next(32) << 32) + next(32); } -__int64 Random::nextLong() -{ - // 4jcraft added casts to unsigned - return (int64_t)((uint64_t) next(32) << 32) + next(32); -} - -bool Random::nextBoolean() -{ - return next(1) != 0; -} +bool Random::nextBoolean() { return next(1) != 0; } diff --git a/Minecraft.World/Util/Random.h b/Minecraft.World/Util/Random.h index ae36d48f3..0efb1838d 100644 --- a/Minecraft.World/Util/Random.h +++ b/Minecraft.World/Util/Random.h @@ -1,23 +1,24 @@ #pragma once -class Random -{ +class Random { private: - __int64 seed; - bool haveNextNextGaussian; - double nextNextGaussian; + __int64 seed; + bool haveNextNextGaussian; + double nextNextGaussian; + protected: - int next(int bits); + int next(int bits); + public: - Random(); - Random(__int64 seed); - void setSeed(__int64 s); - void nextBytes(uint8_t *bytes, unsigned int count); - double nextDouble(); - double nextGaussian(); - int nextInt(); - int nextInt(int to); - float nextFloat(); - __int64 nextLong(); - bool nextBoolean(); + Random(); + Random(__int64 seed); + void setSeed(__int64 s); + void nextBytes(uint8_t* bytes, unsigned int count); + double nextDouble(); + double nextGaussian(); + int nextInt(); + int nextInt(int to); + float nextFloat(); + __int64 nextLong(); + bool nextBoolean(); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Rarity.cpp b/Minecraft.World/Util/Rarity.cpp index 41fcb2a2b..73368c2a7 100644 --- a/Minecraft.World/Util/Rarity.cpp +++ b/Minecraft.World/Util/Rarity.cpp @@ -2,11 +2,10 @@ #include "Rarity.h" -const Rarity *Rarity::common = new Rarity(eHTMLColor_f, L"Common"); -const Rarity *Rarity::uncommon = new Rarity(eHTMLColor_e, L"Uncommon"); -const Rarity *Rarity::rare = new Rarity(eHTMLColor_b, L"Rare"); -const Rarity *Rarity::epic = new Rarity(eHTMLColor_d, L"Epic"); +const Rarity* Rarity::common = new Rarity(eHTMLColor_f, L"Common"); +const Rarity* Rarity::uncommon = new Rarity(eHTMLColor_e, L"Uncommon"); +const Rarity* Rarity::rare = new Rarity(eHTMLColor_b, L"Rare"); +const Rarity* Rarity::epic = new Rarity(eHTMLColor_d, L"Epic"); -Rarity::Rarity(eMinecraftColour color, const std::wstring &name) : color(color), name(name) -{ -} \ No newline at end of file +Rarity::Rarity(eMinecraftColour color, const std::wstring& name) + : color(color), name(name) {} \ No newline at end of file diff --git a/Minecraft.World/Util/Rarity.h b/Minecraft.World/Util/Rarity.h index d53c1b4ff..3fc6158ea 100644 --- a/Minecraft.World/Util/Rarity.h +++ b/Minecraft.World/Util/Rarity.h @@ -1,15 +1,14 @@ #pragma once -class Rarity -{ +class Rarity { public: - static const Rarity *common; - static const Rarity *uncommon; - static const Rarity *rare; - static const Rarity *epic; + static const Rarity* common; + static const Rarity* uncommon; + static const Rarity* rare; + static const Rarity* epic; - const eMinecraftColour color; - const std::wstring name; + const eMinecraftColour color; + const std::wstring name; - Rarity(eMinecraftColour color, const std::wstring &name); + Rarity(eMinecraftColour color, const std::wstring& name); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Reference.h b/Minecraft.World/Util/Reference.h index 2d33f17e4..3bd01f63e 100644 --- a/Minecraft.World/Util/Reference.h +++ b/Minecraft.World/Util/Reference.h @@ -1,10 +1,11 @@ #pragma once -template class Reference -{ +template +class Reference { private: - T *obj; + T* obj; + public: - T *get() { return obj; } - Reference(T *i) { obj = i; } + T* get() { return obj; } + Reference(T* i) { obj = i; } }; \ No newline at end of file diff --git a/Minecraft.World/Util/Rotate.cpp b/Minecraft.World/Util/Rotate.cpp index f92b37e19..2b4d10bce 100644 --- a/Minecraft.World/Util/Rotate.cpp +++ b/Minecraft.World/Util/Rotate.cpp @@ -1,15 +1,13 @@ #include "../Platform/stdafx.h" #include "Rotate.h" -Rotate::Rotate(Synth *synth, float angle) -{ +Rotate::Rotate(Synth* synth, float angle) { this->synth = synth; _sin = sin(angle); _cos = cos(angle); } -double Rotate::getValue(double x, double y) -{ - return synth->getValue(x * _cos + y * _sin, y * _cos - x * _sin); +double Rotate::getValue(double x, double y) { + return synth->getValue(x * _cos + y * _sin, y * _cos - x * _sin); } \ No newline at end of file diff --git a/Minecraft.World/Util/Rotate.h b/Minecraft.World/Util/Rotate.h index 4d2b8b248..02a7806e5 100644 --- a/Minecraft.World/Util/Rotate.h +++ b/Minecraft.World/Util/Rotate.h @@ -1,15 +1,14 @@ #pragma once #include "../WorldGen/Noise/Synth.h" -class Rotate : public Synth -{ +class Rotate : public Synth { private: - Synth *synth; - double _sin; - double _cos; + Synth* synth; + double _sin; + double _cos; public: - Rotate(Synth *synth, float angle); + Rotate(Synth* synth, float angle); virtual double getValue(double x, double y); }; \ No newline at end of file diff --git a/Minecraft.World/Util/Scale.cpp b/Minecraft.World/Util/Scale.cpp index f3efd317f..45c55054d 100644 --- a/Minecraft.World/Util/Scale.cpp +++ b/Minecraft.World/Util/Scale.cpp @@ -1,14 +1,12 @@ #include "../Platform/stdafx.h" #include "Scale.h" -Scale::Scale(Synth *synth, double xScale, double yScale) -{ +Scale::Scale(Synth* synth, double xScale, double yScale) { this->synth = synth; this->xScale = 1.0 / xScale; this->yScale = 1.0 / yScale; } -double Scale::getValue(double x, double y) -{ - return synth->getValue(x * xScale, y * yScale); +double Scale::getValue(double x, double y) { + return synth->getValue(x * xScale, y * yScale); } diff --git a/Minecraft.World/Util/Scale.h b/Minecraft.World/Util/Scale.h index 7f176b07f..dce37b00e 100644 --- a/Minecraft.World/Util/Scale.h +++ b/Minecraft.World/Util/Scale.h @@ -1,15 +1,14 @@ #pragma once #include "../WorldGen/Noise/Synth.h" -class Scale : public Synth -{ +class Scale : public Synth { private: - Synth *synth; - double xScale; - double yScale; + Synth* synth; + double xScale; + double yScale; public: - Scale(Synth *synth, double xScale, double yScale); + Scale(Synth* synth, double xScale, double yScale); virtual double getValue(double x, double y); }; \ No newline at end of file diff --git a/Minecraft.World/Util/SharedConstants.cpp b/Minecraft.World/Util/SharedConstants.cpp index a110d6239..497160a5f 100644 --- a/Minecraft.World/Util/SharedConstants.cpp +++ b/Minecraft.World/Util/SharedConstants.cpp @@ -6,13 +6,19 @@ const std::wstring SharedConstants::VERSION_STRING = L"1.2.3"; const bool SharedConstants::TEXTURE_LIGHTING = true; -std::wstring SharedConstants::readAcceptableChars() -{ - // 4J-PB - I've added ã in (for Portuguese in bed string) and added the character at the same place in the default.png font - std::wstring result = L" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»ã"; -#if 0 // 4J - do we actually really need to get this from a file? - //try { - //BufferedReader br = new BufferedReader(new InputStreamReader(SharedConstants.class.getResourceAsStream("/font.txt"), "UTF-8")); +std::wstring SharedConstants::readAcceptableChars() { + // 4J-PB - I've added ã in (for Portuguese in bed string) and added the + // character at the same place in the default.png font + std::wstring result = + L" !\"#$%&'()*+,-./" + L"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'" + L"abcdefghijklmnopqrstuvwxyz{|}~" + L" ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»ã"; +#if 0 // 4J - do we actually really need to get this from a file? + // try { + // BufferedReader br = new BufferedReader(new + // InputStreamReader(SharedConstants.class.getResourceAsStream("/font.txt"), + // "UTF-8")); BufferedReader *br = new BufferedReader(new InputStreamReader( new FileInputStream( new File( std::wstring(L"/font.txt") ) ) ) ); std::wstring line; while ( !(line = br->readLine()).empty()) @@ -27,25 +33,25 @@ std::wstring SharedConstants::readAcceptableChars() // TODO 4J Stu - Exception handling? //} #endif - return result; + return result; } -bool SharedConstants::isAllowedChatCharacter(char ch) -{ - //return ch != '§' && (acceptableLetters.indexOf(ch) >= 0 || (int) ch > 32); - // 4J Unused - return true; +bool SharedConstants::isAllowedChatCharacter(char ch) { + // return ch != '§' && (acceptableLetters.indexOf(ch) >= 0 || (int) ch > + // 32); + // 4J Unused + return true; } -std::wstring SharedConstants::acceptableLetters = SharedConstants::readAcceptableChars(); +std::wstring SharedConstants::acceptableLetters = + SharedConstants::readAcceptableChars(); -void SharedConstants::staticCtor() -{ - acceptableLetters = readAcceptableChars(); +void SharedConstants::staticCtor() { + acceptableLetters = readAcceptableChars(); } -const wchar_t SharedConstants::ILLEGAL_FILE_CHARACTERS[ILLEGAL_FILE_CHARACTERS_LENGTH] = -{ - // 4J-PB - corrected - L'/', L'\n', L'\r', L'\t', L'\0', L'\f', L'`', L'?', L'*', L'\\', L'<', L'>', L'|', L'\"', L':' -}; \ No newline at end of file +const wchar_t + SharedConstants::ILLEGAL_FILE_CHARACTERS[ILLEGAL_FILE_CHARACTERS_LENGTH] = { + // 4J-PB - corrected + L'/', L'\n', L'\r', L'\t', L'\0', L'\f', L'`', L'?', + L'*', L'\\', L'<', L'>', L'|', L'\"', L':'}; \ No newline at end of file diff --git a/Minecraft.World/Util/SharedConstants.h b/Minecraft.World/Util/SharedConstants.h index e9b8a254d..9c364c19c 100644 --- a/Minecraft.World/Util/SharedConstants.h +++ b/Minecraft.World/Util/SharedConstants.h @@ -2,30 +2,31 @@ #include "Class.h" -class SharedConstants -{ - public: - static void staticCtor(); - static const std::wstring VERSION_STRING; - static const int NETWORK_PROTOCOL_VERSION = 39; - - // NOT texture resolution. How many sub-blocks each block face is made up of. - // 4J Added for texture packs - static const int WORLD_RESOLUTION = 16; +class SharedConstants { +public: + static void staticCtor(); + static const std::wstring VERSION_STRING; + static const int NETWORK_PROTOCOL_VERSION = 39; - static bool isAllowedChatCharacter(char ch); - // why private?????????? - static std::wstring readAcceptableChars(); + // NOT texture resolution. How many sub-blocks each block face is made up + // of. 4J Added for texture packs + static const int WORLD_RESOLUTION = 16; - public: - static const int maxChatLength = 100; - static std::wstring acceptableLetters; + static bool isAllowedChatCharacter(char ch); + // why private?????????? + static std::wstring readAcceptableChars(); - static const int ILLEGAL_FILE_CHARACTERS_LENGTH = 15; - static const wchar_t ILLEGAL_FILE_CHARACTERS[ILLEGAL_FILE_CHARACTERS_LENGTH]; +public: + static const int maxChatLength = 100; + static std::wstring acceptableLetters; - static const bool TEXTURE_LIGHTING; // 4J - change brought forward from 1.8.2 - static const int TICKS_PER_SECOND = 20; + static const int ILLEGAL_FILE_CHARACTERS_LENGTH = 15; + static const wchar_t + ILLEGAL_FILE_CHARACTERS[ILLEGAL_FILE_CHARACTERS_LENGTH]; - static const int FULLBRIGHT_LIGHTVALUE = 15 << 20 | 15 << 4; + static const bool + TEXTURE_LIGHTING; // 4J - change brought forward from 1.8.2 + static const int TICKS_PER_SECOND = 20; + + static const int FULLBRIGHT_LIGHTVALUE = 15 << 20 | 15 << 4; }; \ No newline at end of file diff --git a/Minecraft.World/Util/SmoothFloat.cpp b/Minecraft.World/Util/SmoothFloat.cpp index 4d3ed55c5..dd61b8b3b 100644 --- a/Minecraft.World/Util/SmoothFloat.cpp +++ b/Minecraft.World/Util/SmoothFloat.cpp @@ -1,21 +1,20 @@ #include "../Platform/stdafx.h" #include "SmoothFloat.h" -SmoothFloat::SmoothFloat() -{ - targetValue = 0.0f; - remainingValue = 0.0f; - lastAmount = 0.0f; +SmoothFloat::SmoothFloat() { + targetValue = 0.0f; + remainingValue = 0.0f; + lastAmount = 0.0f; } -float SmoothFloat::getNewDeltaValue(float deltaValue, float accelerationAmount) -{ +float SmoothFloat::getNewDeltaValue(float deltaValue, + float accelerationAmount) { targetValue += deltaValue; deltaValue = (targetValue - remainingValue) * accelerationAmount; lastAmount = lastAmount + (deltaValue - lastAmount) * 0.5f; - if ((deltaValue > 0 && deltaValue > lastAmount) || (deltaValue < 0 && deltaValue < lastAmount)) - { + if ((deltaValue > 0 && deltaValue > lastAmount) || + (deltaValue < 0 && deltaValue < lastAmount)) { deltaValue = lastAmount; } remainingValue += deltaValue; @@ -23,7 +22,4 @@ float SmoothFloat::getNewDeltaValue(float deltaValue, float accelerationAmount) return deltaValue; } -float SmoothFloat::getTargetValue() -{ - return targetValue; -} \ No newline at end of file +float SmoothFloat::getTargetValue() { return targetValue; } \ No newline at end of file diff --git a/Minecraft.World/Util/SmoothFloat.h b/Minecraft.World/Util/SmoothFloat.h index 5b25302a3..4af35e0f4 100644 --- a/Minecraft.World/Util/SmoothFloat.h +++ b/Minecraft.World/Util/SmoothFloat.h @@ -1,13 +1,13 @@ #pragma once -class SmoothFloat -{ +class SmoothFloat { private: - float targetValue; + float targetValue; float remainingValue; float lastAmount; + public: - SmoothFloat(); // 4J added - float getNewDeltaValue(float deltaValue, float accelerationAmount); + SmoothFloat(); // 4J added + float getNewDeltaValue(float deltaValue, float accelerationAmount); float getTargetValue(); }; \ No newline at end of file diff --git a/Minecraft.World/Util/SoundTypes.h b/Minecraft.World/Util/SoundTypes.h index acbe91674..8d95728b4 100644 --- a/Minecraft.World/Util/SoundTypes.h +++ b/Minecraft.World/Util/SoundTypes.h @@ -1,180 +1,178 @@ #pragma once // 4J-PB - if you change this, you need to update SoundEngine::wchSoundNames[] -enum eSOUND_TYPE -{ - eSoundType_MOB_CHICKEN_AMBIENT, - eSoundType_MOB_CHICKEN_HURT, - eSoundType_MOB_CHICKENPLOP, - eSoundType_MOB_COW_AMBIENT, - eSoundType_MOB_COW_HURT, - eSoundType_MOB_PIG_AMBIENT, - eSoundType_MOB_PIG_DEATH, - eSoundType_MOB_SHEEP_AMBIENT, - eSoundType_MOB_WOLF_GROWL, - eSoundType_MOB_WOLF_WHINE, - eSoundType_MOB_WOLF_PANTING, - eSoundType_MOB_WOLF_BARK, - eSoundType_MOB_WOLF_HURT, - eSoundType_MOB_WOLF_DEATH, - eSoundType_MOB_WOLF_SHAKE, - eSoundType_MOB_BLAZE_BREATHE, - eSoundType_MOB_BLAZE_HURT, - eSoundType_MOB_BLAZE_DEATH, - eSoundType_MOB_GHAST_MOAN, - eSoundType_MOB_GHAST_SCREAM, - eSoundType_MOB_GHAST_DEATH, - eSoundType_MOB_GHAST_FIREBALL, - eSoundType_MOB_GHAST_CHARGE, - eSoundType_MOB_ENDERMEN_IDLE, - eSoundType_MOB_ENDERMEN_HIT, - eSoundType_MOB_ENDERMEN_DEATH, - eSoundType_MOB_ENDERMEN_PORTAL, - eSoundType_MOB_ZOMBIEPIG_AMBIENT, - eSoundType_MOB_ZOMBIEPIG_HURT, - eSoundType_MOB_ZOMBIEPIG_DEATH, - eSoundType_MOB_ZOMBIEPIG_ZPIGANGRY, - eSoundType_MOB_SILVERFISH_AMBIENT, - eSoundType_MOB_SILVERFISH_HURT, - eSoundType_MOB_SILVERFISH_DEATH, - eSoundType_MOB_SILVERFISH_STEP, - eSoundType_MOB_SKELETON_AMBIENT, - eSoundType_MOB_SKELETON_HURT, - eSoundType_MOB_SPIDER_AMBIENT, - eSoundType_MOB_SPIDER_DEATH, - eSoundType_MOB_SLIME, - eSoundType_MOB_SLIME_ATTACK, - eSoundType_MOB_CREEPER_HURT, - eSoundType_MOB_CREEPER_DEATH, - eSoundType_MOB_ZOMBIE_AMBIENT, - eSoundType_MOB_ZOMBIE_HURT, - eSoundType_MOB_ZOMBIE_DEATH, - eSoundType_MOB_ZOMBIE_WOOD, - eSoundType_MOB_ZOMBIE_WOOD_BREAK, - eSoundType_MOB_ZOMBIE_METAL, - eSoundType_MOB_MAGMACUBE_BIG, - eSoundType_MOB_MAGMACUBE_SMALL, - eSoundType_MOB_CAT_PURR, - eSoundType_MOB_CAT_PURREOW, - eSoundType_MOB_CAT_MEOW, - eSoundType_MOB_CAT_HITT, -// eSoundType_MOB_IRONGOLEM_THROW, -// eSoundType_MOB_IRONGOLEM_HIT, -// eSoundType_MOB_IRONGOLEM_DEATH, -// eSoundType_MOB_IRONGOLEM_WALK, - eSoundType_RANDOM_BOW, - eSoundType_RANDOM_BOW_HIT, - eSoundType_RANDOM_EXPLODE, - eSoundType_RANDOM_FIZZ, - eSoundType_RANDOM_POP, - eSoundType_RANDOM_FUSE, - eSoundType_RANDOM_DRINK, - eSoundType_RANDOM_EAT, - eSoundType_RANDOM_BURP, - eSoundType_RANDOM_SPLASH, - eSoundType_RANDOM_CLICK, - eSoundType_RANDOM_GLASS, - eSoundType_RANDOM_ORB, - eSoundType_RANDOM_BREAK, - eSoundType_RANDOM_CHEST_OPEN, - eSoundType_RANDOM_CHEST_CLOSE, - eSoundType_RANDOM_DOOR_OPEN, - eSoundType_RANDOM_DOOR_CLOSE, - eSoundType_AMBIENT_WEATHER_RAIN, - eSoundType_AMBIENT_WEATHER_THUNDER, - eSoundType_AMBIENT_CAVE_CAVE, +enum eSOUND_TYPE { + eSoundType_MOB_CHICKEN_AMBIENT, + eSoundType_MOB_CHICKEN_HURT, + eSoundType_MOB_CHICKENPLOP, + eSoundType_MOB_COW_AMBIENT, + eSoundType_MOB_COW_HURT, + eSoundType_MOB_PIG_AMBIENT, + eSoundType_MOB_PIG_DEATH, + eSoundType_MOB_SHEEP_AMBIENT, + eSoundType_MOB_WOLF_GROWL, + eSoundType_MOB_WOLF_WHINE, + eSoundType_MOB_WOLF_PANTING, + eSoundType_MOB_WOLF_BARK, + eSoundType_MOB_WOLF_HURT, + eSoundType_MOB_WOLF_DEATH, + eSoundType_MOB_WOLF_SHAKE, + eSoundType_MOB_BLAZE_BREATHE, + eSoundType_MOB_BLAZE_HURT, + eSoundType_MOB_BLAZE_DEATH, + eSoundType_MOB_GHAST_MOAN, + eSoundType_MOB_GHAST_SCREAM, + eSoundType_MOB_GHAST_DEATH, + eSoundType_MOB_GHAST_FIREBALL, + eSoundType_MOB_GHAST_CHARGE, + eSoundType_MOB_ENDERMEN_IDLE, + eSoundType_MOB_ENDERMEN_HIT, + eSoundType_MOB_ENDERMEN_DEATH, + eSoundType_MOB_ENDERMEN_PORTAL, + eSoundType_MOB_ZOMBIEPIG_AMBIENT, + eSoundType_MOB_ZOMBIEPIG_HURT, + eSoundType_MOB_ZOMBIEPIG_DEATH, + eSoundType_MOB_ZOMBIEPIG_ZPIGANGRY, + eSoundType_MOB_SILVERFISH_AMBIENT, + eSoundType_MOB_SILVERFISH_HURT, + eSoundType_MOB_SILVERFISH_DEATH, + eSoundType_MOB_SILVERFISH_STEP, + eSoundType_MOB_SKELETON_AMBIENT, + eSoundType_MOB_SKELETON_HURT, + eSoundType_MOB_SPIDER_AMBIENT, + eSoundType_MOB_SPIDER_DEATH, + eSoundType_MOB_SLIME, + eSoundType_MOB_SLIME_ATTACK, + eSoundType_MOB_CREEPER_HURT, + eSoundType_MOB_CREEPER_DEATH, + eSoundType_MOB_ZOMBIE_AMBIENT, + eSoundType_MOB_ZOMBIE_HURT, + eSoundType_MOB_ZOMBIE_DEATH, + eSoundType_MOB_ZOMBIE_WOOD, + eSoundType_MOB_ZOMBIE_WOOD_BREAK, + eSoundType_MOB_ZOMBIE_METAL, + eSoundType_MOB_MAGMACUBE_BIG, + eSoundType_MOB_MAGMACUBE_SMALL, + eSoundType_MOB_CAT_PURR, + eSoundType_MOB_CAT_PURREOW, + eSoundType_MOB_CAT_MEOW, + eSoundType_MOB_CAT_HITT, + // eSoundType_MOB_IRONGOLEM_THROW, + // eSoundType_MOB_IRONGOLEM_HIT, + // eSoundType_MOB_IRONGOLEM_DEATH, + // eSoundType_MOB_IRONGOLEM_WALK, + eSoundType_RANDOM_BOW, + eSoundType_RANDOM_BOW_HIT, + eSoundType_RANDOM_EXPLODE, + eSoundType_RANDOM_FIZZ, + eSoundType_RANDOM_POP, + eSoundType_RANDOM_FUSE, + eSoundType_RANDOM_DRINK, + eSoundType_RANDOM_EAT, + eSoundType_RANDOM_BURP, + eSoundType_RANDOM_SPLASH, + eSoundType_RANDOM_CLICK, + eSoundType_RANDOM_GLASS, + eSoundType_RANDOM_ORB, + eSoundType_RANDOM_BREAK, + eSoundType_RANDOM_CHEST_OPEN, + eSoundType_RANDOM_CHEST_CLOSE, + eSoundType_RANDOM_DOOR_OPEN, + eSoundType_RANDOM_DOOR_CLOSE, + eSoundType_AMBIENT_WEATHER_RAIN, + eSoundType_AMBIENT_WEATHER_THUNDER, + eSoundType_AMBIENT_CAVE_CAVE, #ifdef _XBOX - eSoundType_AMBIENT_CAVE_CAVE2, //- fixed version of eSoundType_CAVE_CAVE, without the two 192k sounds + eSoundType_AMBIENT_CAVE_CAVE2, //- fixed version of eSoundType_CAVE_CAVE, + //without the two 192k sounds #endif - eSoundType_PORTAL_PORTAL, - // 4J-PB - adding some that were still text in the code - eSoundType_PORTAL_TRIGGER, - eSoundType_PORTAL_TRAVEL, + eSoundType_PORTAL_PORTAL, + // 4J-PB - adding some that were still text in the code + eSoundType_PORTAL_TRIGGER, + eSoundType_PORTAL_TRAVEL, - eSoundType_FIRE_IGNITE, - eSoundType_FIRE_FIRE, - eSoundType_DAMAGE_HURT, - eSoundType_DAMAGE_FALL_SMALL, - eSoundType_DAMAGE_FALL_BIG, - eSoundType_NOTE_HARP, - eSoundType_NOTE_BD, - eSoundType_NOTE_SNARE, - eSoundType_NOTE_HAT, - eSoundType_NOTE_BASSATTACK, - eSoundType_TILE_PISTON_IN, - eSoundType_TILE_PISTON_OUT, - eSoundType_LIQUID_WATER, - eSoundType_LIQUID_LAVA_POP, - eSoundType_LIQUID_LAVA, - eSoundType_STEP_STONE, - eSoundType_STEP_WOOD, - eSoundType_STEP_GRAVEL, - eSoundType_STEP_GRASS, - eSoundType_STEP_METAL, - eSoundType_STEP_CLOTH, - eSoundType_STEP_SAND, - // soundbank 2 - eSoundType_MOB_ENDERDRAGON_END, - eSoundType_MOB_ENDERDRAGON_GROWL, - eSoundType_MOB_ENDERDRAGON_HIT, - eSoundType_MOB_ENDERDRAGON_MOVE, - eSoundType_MOB_IRONGOLEM_THROW, - eSoundType_MOB_IRONGOLEM_HIT, - eSoundType_MOB_IRONGOLEM_DEATH, - eSoundType_MOB_IRONGOLEM_WALK, + eSoundType_FIRE_IGNITE, + eSoundType_FIRE_FIRE, + eSoundType_DAMAGE_HURT, + eSoundType_DAMAGE_FALL_SMALL, + eSoundType_DAMAGE_FALL_BIG, + eSoundType_NOTE_HARP, + eSoundType_NOTE_BD, + eSoundType_NOTE_SNARE, + eSoundType_NOTE_HAT, + eSoundType_NOTE_BASSATTACK, + eSoundType_TILE_PISTON_IN, + eSoundType_TILE_PISTON_OUT, + eSoundType_LIQUID_WATER, + eSoundType_LIQUID_LAVA_POP, + eSoundType_LIQUID_LAVA, + eSoundType_STEP_STONE, + eSoundType_STEP_WOOD, + eSoundType_STEP_GRAVEL, + eSoundType_STEP_GRASS, + eSoundType_STEP_METAL, + eSoundType_STEP_CLOTH, + eSoundType_STEP_SAND, + // soundbank 2 + eSoundType_MOB_ENDERDRAGON_END, + eSoundType_MOB_ENDERDRAGON_GROWL, + eSoundType_MOB_ENDERDRAGON_HIT, + eSoundType_MOB_ENDERDRAGON_MOVE, + eSoundType_MOB_IRONGOLEM_THROW, + eSoundType_MOB_IRONGOLEM_HIT, + eSoundType_MOB_IRONGOLEM_DEATH, + eSoundType_MOB_IRONGOLEM_WALK, - // TU14 - eSoundType_DAMAGE_THORNS, - eSoundType_RANDOM_ANVIL_BREAK, - eSoundType_RANDOM_ANVIL_LAND, - eSoundType_RANDOM_ANVIL_USE, - eSoundType_MOB_VILLAGER_HAGGLE, - eSoundType_MOB_VILLAGER_IDLE, - eSoundType_MOB_VILLAGER_HIT, - eSoundType_MOB_VILLAGER_DEATH, - eSoundType_MOB_VILLAGER_YES, - eSoundType_MOB_VILLAGER_NO, - eSoundType_MOB_ZOMBIE_INFECT, - eSoundType_MOB_ZOMBIE_UNFECT, - eSoundType_MOB_ZOMBIE_REMEDY, - eSoundType_STEP_SNOW, - eSoundType_STEP_LADDER, - eSoundType_DIG_CLOTH, - eSoundType_DIG_GRASS, - eSoundType_DIG_GRAVEL, - eSoundType_DIG_SAND, - eSoundType_DIG_SNOW, - eSoundType_DIG_STONE, - eSoundType_DIG_WOOD, + // TU14 + eSoundType_DAMAGE_THORNS, + eSoundType_RANDOM_ANVIL_BREAK, + eSoundType_RANDOM_ANVIL_LAND, + eSoundType_RANDOM_ANVIL_USE, + eSoundType_MOB_VILLAGER_HAGGLE, + eSoundType_MOB_VILLAGER_IDLE, + eSoundType_MOB_VILLAGER_HIT, + eSoundType_MOB_VILLAGER_DEATH, + eSoundType_MOB_VILLAGER_YES, + eSoundType_MOB_VILLAGER_NO, + eSoundType_MOB_ZOMBIE_INFECT, + eSoundType_MOB_ZOMBIE_UNFECT, + eSoundType_MOB_ZOMBIE_REMEDY, + eSoundType_STEP_SNOW, + eSoundType_STEP_LADDER, + eSoundType_DIG_CLOTH, + eSoundType_DIG_GRASS, + eSoundType_DIG_GRAVEL, + eSoundType_DIG_SAND, + eSoundType_DIG_SNOW, + eSoundType_DIG_STONE, + eSoundType_DIG_WOOD, - eSoundType_MAX + eSoundType_MAX }; // 4J-PB - if you change this, you need to update SoundEngine::wchUISoundNames[] -enum ESoundEffect -{ - eSFX_Back, - eSFX_Craft, - eSFX_CraftFail, - eSFX_Focus, - eSFX_Press, - eSFX_Scroll, - eSFX_MAX +enum ESoundEffect { + eSFX_Back, + eSFX_Craft, + eSFX_CraftFail, + eSFX_Focus, + eSFX_Press, + eSFX_Scroll, + eSFX_MAX }; -enum eMATERIALSOUND_TYPE -{ - eMaterialSoundType_STONE, - eMaterialSoundType_WOOD, - eMaterialSoundType_GRAVEL, - eMaterialSoundType_GRASS, - eMaterialSoundType_METAL, - eMaterialSoundType_GLASS, - eMaterialSoundType_CLOTH, - eMaterialSoundType_SAND, - eMaterialSoundType_SNOW, - eMaterialSoundType_LADDER, - eMaterialSoundType_ANVIL, +enum eMATERIALSOUND_TYPE { + eMaterialSoundType_STONE, + eMaterialSoundType_WOOD, + eMaterialSoundType_GRAVEL, + eMaterialSoundType_GRASS, + eMaterialSoundType_METAL, + eMaterialSoundType_GLASS, + eMaterialSoundType_CLOTH, + eMaterialSoundType_SAND, + eMaterialSoundType_SNOW, + eMaterialSoundType_LADDER, + eMaterialSoundType_ANVIL, }; /* @@ -208,97 +206,97 @@ L"mob.ghast.moan", L"mob.ghast.scream", L"mob.ghast.death", L"mob.ghast.fireball", - L"mob.ghast.charge", + L"mob.ghast.charge", - L"mob.endermen.idle", - L"mob.endermen.hit", - L"mob.endermen.death", - L"mob.endermen.portal", + L"mob.endermen.idle", + L"mob.endermen.hit", + L"mob.endermen.death", + L"mob.endermen.portal", - L"mob.zombiepig.zpig", - L"mob.zombiepig.zpighurt", - L"mob.zombiepig.zpigdeath", - L"mob.zombiepig.zpigangry", + L"mob.zombiepig.zpig", + L"mob.zombiepig.zpighurt", + L"mob.zombiepig.zpigdeath", + L"mob.zombiepig.zpigangry", - L"mob.silverfish.say", - L"mob.silverfish.hit", - L"mob.silverfish.kill", - L"mob.silverfish.step", + L"mob.silverfish.say", + L"mob.silverfish.hit", + L"mob.silverfish.kill", + L"mob.silverfish.step", - L"mob.skeleton", - L"mob.skeleton.hurt", + L"mob.skeleton", + L"mob.skeleton.hurt", - L"mob.spider", - L"mob.spiderdeath", + L"mob.spider", + L"mob.spiderdeath", - L"mob.slime", - L"mob.slimeattack", + L"mob.slime", + L"mob.slimeattack", - L"mob.creeper", - L"mob.creeperdeath", + L"mob.creeper", + L"mob.creeperdeath", - L"mob.zombie", - L"mob.zombiehurt", - L"mob.zombiedeath", - L"mob.zombie.wood", - L"mob.zombie.woodbreak", - L"mob.zombie.metal", + L"mob.zombie", + L"mob.zombiehurt", + L"mob.zombiedeath", + L"mob.zombie.wood", + L"mob.zombie.woodbreak", + L"mob.zombie.metal", - L"mob.magmacube.big", - L"mob.magmacube.small", + L"mob.magmacube.big", + L"mob.magmacube.small", - L"random.bow", - L"random.bowhit", - L"random.explode", - L"random.fizz", - L"random.pop", - L"random.fuse", - L"random.drink", - L"random.eat", - L"random.burp", - L"random.splash", - L"random.click", - L"random.glass", - L"random.orb", - L"random.break", - L"random.chestopen", - L"random.chestclosed", - L"random.door_open", - L"random.door_close", + L"random.bow", + L"random.bowhit", + L"random.explode", + L"random.fizz", + L"random.pop", + L"random.fuse", + L"random.drink", + L"random.eat", + L"random.burp", + L"random.splash", + L"random.click", + L"random.glass", + L"random.orb", + L"random.break", + L"random.chestopen", + L"random.chestclosed", + L"random.door_open", + L"random.door_close", - L"ambient.weather.rain", - L"ambient.weather.thunder", + L"ambient.weather.rain", + L"ambient.weather.thunder", - L"ambient.cave.cave", + L"ambient.cave.cave", - L"portal.portal", + L"portal.portal", - L"fire.ignite", - L"fire.fire", + L"fire.ignite", + L"fire.fire", - L"damage.hurtflesh", - L"damage.fallsmall", - L"damage.fallbig", + L"damage.hurtflesh", + L"damage.fallsmall", + L"damage.fallbig", - L"note.harp", - L"note.bd", - L"note.snare", - L"note.hat", - L"note.bassattack", + L"note.harp", + L"note.bd", + L"note.snare", + L"note.hat", + L"note.bassattack", - L"tile.piston.in", - L"tile.piston.out", + L"tile.piston.in", + L"tile.piston.out", - L"liquid.water", - L"liquid.lavapop", - L"liquid.lava", + L"liquid.water", + L"liquid.lavapop", + L"liquid.lava", - L"step.stone", - L"step.wood", - L"step.gravel", - L"step.grass", - L"step.metal", - L"step.cloth", - L"step.sand", + L"step.stone", + L"step.wood", + L"step.gravel", + L"step.grass", + L"step.metal", + L"step.cloth", + L"step.sand", };*/ \ No newline at end of file diff --git a/Minecraft.World/Util/StringHelpers.cpp b/Minecraft.World/Util/StringHelpers.cpp index 12bfbfeda..c253f8236 100644 --- a/Minecraft.World/Util/StringHelpers.cpp +++ b/Minecraft.World/Util/StringHelpers.cpp @@ -1,133 +1,125 @@ #include "../Platform/stdafx.h" -std::wstring toLower(const std::wstring& a) -{ - std::wstring out = std::wstring(a); - std::transform(out.begin(), out.end(), out.begin(), ::tolower); - return out; +std::wstring toLower(const std::wstring& a) { + std::wstring out = std::wstring(a); + std::transform(out.begin(), out.end(), out.begin(), ::tolower); + return out; } -std::wstring trimString(const std::wstring& a) -{ - std::wstring b; - int start = (int)a.find_first_not_of(L" \t\n\r"); - int end = (int)a.find_last_not_of(L" \t\n\r"); - if( start == std::wstring::npos ) start = 0; - if( end == std::wstring::npos ) end = (int)a.size()-1; - b = a.substr(start,(end-start)+1); - return b; +std::wstring trimString(const std::wstring& a) { + std::wstring b; + int start = (int)a.find_first_not_of(L" \t\n\r"); + int end = (int)a.find_last_not_of(L" \t\n\r"); + if (start == std::wstring::npos) start = 0; + if (end == std::wstring::npos) end = (int)a.size() - 1; + b = a.substr(start, (end - start) + 1); + return b; } -std::wstring replaceAll(const std::wstring& in, const std::wstring& replace, const std::wstring& with) -{ - std::wstring out = in; - size_t pos = 0; - while( ( pos = out.find(replace, pos) ) != std::wstring::npos ) - { - out.replace( pos, replace.length(), with ); - pos++; - } - return out; +std::wstring replaceAll(const std::wstring& in, const std::wstring& replace, + const std::wstring& with) { + std::wstring out = in; + size_t pos = 0; + while ((pos = out.find(replace, pos)) != std::wstring::npos) { + out.replace(pos, replace.length(), with); + pos++; + } + return out; } -bool equalsIgnoreCase(const std::wstring& a, const std::wstring& b) -{ - bool out; - std::wstring c = toLower(a); - std::wstring d = toLower(b); - out = c.compare(d) == 0; - return out; +bool equalsIgnoreCase(const std::wstring& a, const std::wstring& b) { + bool out; + std::wstring c = toLower(a); + std::wstring d = toLower(b); + out = c.compare(d) == 0; + return out; } -std::wstring convStringToWstring(const std::string& converting) -{ - std::wstring converted(converting.length(), L' '); - copy(converting.begin(), converting.end(), converted.begin()); - return converted; +std::wstring convStringToWstring(const std::string& converting) { + std::wstring converted(converting.length(), L' '); + copy(converting.begin(), converting.end(), converted.begin()); + return converted; } -// Convert for filename std::wstrings to a straight character pointer for Xbox APIs. The returned string is only valid until -// this function is called again, and it isn't thread-safe etc. as I'm just storing the returned name in a local static -// to save having to clear it up everywhere this is used. -const char *wstringtofilename(const std::wstring& name) -{ - static char buf[256]; - assert(name.length()<256); - for(unsigned int i = 0; i < name.length(); i++ ) - { - wchar_t c = name[i]; +// Convert for filename std::wstrings to a straight character pointer for Xbox +// APIs. The returned string is only valid until this function is called again, +// and it isn't thread-safe etc. as I'm just storing the returned name in a +// local static to save having to clear it up everywhere this is used. +const char* wstringtofilename(const std::wstring& name) { + static char buf[256]; + assert(name.length() < 256); + for (unsigned int i = 0; i < name.length(); i++) { + wchar_t c = name[i]; #if defined __PS3__ || defined __ORBIS__ || defined __linux__ - if(c=='\\') c='/'; + if (c == '\\') c = '/'; #else - if(c=='/') c='\\'; + if (c == '/') c = '\\'; #endif - assert(c<128); // Will we have to do any conversion of non-ASCII characters in filenames? - buf[i] = (char)c; - } - buf[name.length()] = 0; - return buf; + assert(c < 128); // Will we have to do any conversion of non-ASCII + // characters in filenames? + buf[i] = (char)c; + } + buf[name.length()] = 0; + return buf; } -std::wstring filenametowstring(const char *name) -{ - return convStringToWstring(name); +std::wstring filenametowstring(const char* name) { + return convStringToWstring(name); } -std::vector &stringSplit(const std::wstring &s, wchar_t delim, std::vector &elems) -{ +std::vector& stringSplit(const std::wstring& s, wchar_t delim, + std::vector& elems) { std::wstringstream ss(s); std::wstring item; - while(std::getline(ss, item, delim)) - { + while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } - -std::vector stringSplit(const std::wstring &s, wchar_t delim) -{ +std::vector stringSplit(const std::wstring& s, wchar_t delim) { std::vector elems; return stringSplit(s, delim, elems); } -bool BothAreSpaces(wchar_t lhs, wchar_t rhs) { return (lhs == rhs) && (lhs == L' '); } - -void stripWhitespaceForHtml(std::wstring &string, bool bRemoveNewline) -{ - // Strip newline chars - if(bRemoveNewline) - { - string.erase(std::remove(string.begin(), string.end(), '\n'), string.end()); - string.erase(std::remove(string.begin(), string.end(), '\r'), string.end()); - } - - string.erase(std::remove(string.begin(), string.end(), '\t'), string.end()); - - // Strip duplicate spaces - string.erase(std::unique(string.begin(), string.end(), BothAreSpaces), string.end()); - - string = trimString(string); +bool BothAreSpaces(wchar_t lhs, wchar_t rhs) { + return (lhs == rhs) && (lhs == L' '); } -std::wstring escapeXML(const std::wstring &in) -{ - std::wstring out = in; - out = replaceAll(out, L"&", L"&"); - //out = replaceAll(out, L"\"", L"""); - //out = replaceAll(out, L"'", L"'"); - out = replaceAll(out, L"<", L"<"); - out = replaceAll(out, L">", L">"); - return out; +void stripWhitespaceForHtml(std::wstring& string, bool bRemoveNewline) { + // Strip newline chars + if (bRemoveNewline) { + string.erase(std::remove(string.begin(), string.end(), '\n'), + string.end()); + string.erase(std::remove(string.begin(), string.end(), '\r'), + string.end()); + } + + string.erase(std::remove(string.begin(), string.end(), '\t'), string.end()); + + // Strip duplicate spaces + string.erase(std::unique(string.begin(), string.end(), BothAreSpaces), + string.end()); + + string = trimString(string); } -std::wstring parseXMLSpecials(const std::wstring &in) -{ - std::wstring out = in; - out = replaceAll(out, L"&", L"&"); - //out = replaceAll(out, L"\"", L"""); - //out = replaceAll(out, L"'", L"'"); - out = replaceAll(out, L"<", L"<"); - out = replaceAll(out, L">", L">"); - return out; +std::wstring escapeXML(const std::wstring& in) { + std::wstring out = in; + out = replaceAll(out, L"&", L"&"); + // out = replaceAll(out, L"\"", L"""); + // out = replaceAll(out, L"'", L"'"); + out = replaceAll(out, L"<", L"<"); + out = replaceAll(out, L">", L">"); + return out; +} + +std::wstring parseXMLSpecials(const std::wstring& in) { + std::wstring out = in; + out = replaceAll(out, L"&", L"&"); + // out = replaceAll(out, L"\"", L"""); + // out = replaceAll(out, L"'", L"'"); + out = replaceAll(out, L"<", L"<"); + out = replaceAll(out, L">", L">"); + return out; } \ No newline at end of file diff --git a/Minecraft.World/Util/StringHelpers.h b/Minecraft.World/Util/StringHelpers.h index 73092ef69..ae606d505 100644 --- a/Minecraft.World/Util/StringHelpers.h +++ b/Minecraft.World/Util/StringHelpers.h @@ -1,40 +1,42 @@ #pragma once -//using namespace stdtd; +// using namespace stdtd; std::wstring toLower(const std::wstring& a); std::wstring trimString(const std::wstring& a); -std::wstring replaceAll(const std::wstring& in, const std::wstring& replace, const std::wstring& with); +std::wstring replaceAll(const std::wstring& in, const std::wstring& replace, + const std::wstring& with); bool equalsIgnoreCase(const std::wstring& a, const std::wstring& b); -// 4J-PB - for use in the ::toString -template std::wstring _toString(T t) -{ - std::wostringstream oss; - oss << std::dec << t; - return oss.str(); +// 4J-PB - for use in the ::toString +template +std::wstring _toString(T t) { + std::wostringstream oss; + oss << std::dec << t; + return oss.str(); } -template T _fromString(const std::wstring& s) -{ - std::wistringstream stream (s); +template +T _fromString(const std::wstring& s) { + std::wistringstream stream(s); T t; stream >> t; return t; } -template T _fromHEXString(const std::wstring& s) -{ - std::wistringstream stream (s); +template +T _fromHEXString(const std::wstring& s) { + std::wistringstream stream(s); T t; stream >> std::hex >> t; return t; } std::wstring convStringToWstring(const std::string& converting); -const char *wstringtofilename(const std::wstring& name); -std::wstring filenametowstring(const char *name); +const char* wstringtofilename(const std::wstring& name); +std::wstring filenametowstring(const char* name); -std::vector &stringSplit(const std::wstring &s, wchar_t delim, std::vector &elems); -std::vector stringSplit(const std::wstring &s, wchar_t delim); +std::vector& stringSplit(const std::wstring& s, wchar_t delim, + std::vector& elems); +std::vector stringSplit(const std::wstring& s, wchar_t delim); -void stripWhitespaceForHtml(std::wstring &string, bool bRemoveNewline=true); -std::wstring escapeXML(const std::wstring &in); -std::wstring parseXMLSpecials(const std::wstring &in); +void stripWhitespaceForHtml(std::wstring& string, bool bRemoveNewline = true); +std::wstring escapeXML(const std::wstring& in); +std::wstring parseXMLSpecials(const std::wstring& in); diff --git a/Minecraft.World/Util/ThreadName.cpp b/Minecraft.World/Util/ThreadName.cpp index 9cd372c96..81bfb71bd 100644 --- a/Minecraft.World/Util/ThreadName.cpp +++ b/Minecraft.World/Util/ThreadName.cpp @@ -3,39 +3,36 @@ // From Xbox documentation typedef struct tagTHREADNAME_INFO { - DWORD dwType; // Must be 0x1000 - LPCSTR szName; // Pointer to name (in user address space) - DWORD dwThreadID; // Thread ID (-1 for caller thread) - DWORD dwFlags; // Reserved for future use; must be zero + DWORD dwType; // Must be 0x1000 + LPCSTR szName; // Pointer to name (in user address space) + DWORD dwThreadID; // Thread ID (-1 for caller thread) + DWORD dwFlags; // Reserved for future use; must be zero } THREADNAME_INFO; -void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName ) -{ +void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) { #ifndef __PS3__ THREADNAME_INFO info; - + info.dwType = 0x1000; info.szName = szThreadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; - -#if ( defined _WINDOWS64 | defined _DURANGO ) - __try - { - RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (ULONG_PTR *)&info ); - } - __except( GetExceptionCode()==0x406D1388 ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER ) - { - } + +#if (defined _WINDOWS64 | defined _DURANGO) + __try { + RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), + (ULONG_PTR*)&info); + } __except (GetExceptionCode() == 0x406D1388 ? EXCEPTION_CONTINUE_EXECUTION + : EXCEPTION_EXECUTE_HANDLER) { + } #endif #ifdef _XBOX - __try - { - RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD *)&info ); - } - __except( GetExceptionCode()==0x406D1388 ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER ) - { + __try { + RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), + (DWORD*)&info); + } __except (GetExceptionCode() == 0x406D1388 ? EXCEPTION_CONTINUE_EXECUTION + : EXCEPTION_EXECUTE_HANDLER) { } #endif -#endif // __PS3__ +#endif // __PS3__ } diff --git a/Minecraft.World/Util/ThreadName.h b/Minecraft.World/Util/ThreadName.h index e7afe594d..562c69ad1 100644 --- a/Minecraft.World/Util/ThreadName.h +++ b/Minecraft.World/Util/ThreadName.h @@ -1,3 +1,3 @@ #pragma once -void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName ); \ No newline at end of file +void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName); \ No newline at end of file diff --git a/Minecraft.World/Util/UseAnim.h b/Minecraft.World/Util/UseAnim.h index cb0452638..a93b8aa3e 100644 --- a/Minecraft.World/Util/UseAnim.h +++ b/Minecraft.World/Util/UseAnim.h @@ -1,10 +1,9 @@ #pragma once -enum UseAnim -{ - UseAnim_none, - UseAnim_eat, - UseAnim_drink, - UseAnim_block, - UseAnim_bow +enum UseAnim { + UseAnim_none, + UseAnim_eat, + UseAnim_drink, + UseAnim_block, + UseAnim_bow }; diff --git a/Minecraft.World/Util/Vec3.cpp b/Minecraft.World/Util/Vec3.cpp index 24132d839..bc9f5266c 100644 --- a/Minecraft.World/Util/Vec3.cpp +++ b/Minecraft.World/Util/Vec3.cpp @@ -3,67 +3,50 @@ #include "AABB.h" unsigned int Vec3::tlsIdx = 0; -Vec3::ThreadStorage *Vec3::tlsDefault = NULL; +Vec3::ThreadStorage* Vec3::tlsDefault = NULL; -Vec3::ThreadStorage::ThreadStorage() -{ - pool = new Vec3[POOL_SIZE]; - poolPointer = 0; +Vec3::ThreadStorage::ThreadStorage() { + pool = new Vec3[POOL_SIZE]; + poolPointer = 0; } -Vec3::ThreadStorage::~ThreadStorage() -{ - delete [] pool; +Vec3::ThreadStorage::~ThreadStorage() { delete[] pool; } + +void Vec3::CreateNewThreadStorage() { + ThreadStorage* tls = new ThreadStorage(); + if (tlsDefault == NULL) { + tlsIdx = TlsAlloc(); + tlsDefault = tls; + } + TlsSetValue(tlsIdx, tls); } -void Vec3::CreateNewThreadStorage() -{ - ThreadStorage *tls = new ThreadStorage(); - if(tlsDefault == NULL ) - { - tlsIdx = TlsAlloc(); - tlsDefault = tls; - } - TlsSetValue(tlsIdx, tls); +void Vec3::UseDefaultThreadStorage() { TlsSetValue(tlsIdx, tlsDefault); } + +void Vec3::ReleaseThreadStorage() { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); + if (tls == tlsDefault) return; + + delete tls; } -void Vec3::UseDefaultThreadStorage() -{ - TlsSetValue(tlsIdx, tlsDefault); -} - -void Vec3::ReleaseThreadStorage() -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); - if( tls == tlsDefault ) return; - - delete tls; -} - -Vec3 *Vec3::newPermanent(double x, double y, double z) -{ - return new Vec3(x,y,z); +Vec3* Vec3::newPermanent(double x, double y, double z) { + return new Vec3(x, y, z); }; -void Vec3::clearPool() -{ -} +void Vec3::clearPool() {} -void Vec3::resetPool() -{ -} +void Vec3::resetPool() {} -Vec3 *Vec3::newTemp(double x, double y, double z) -{ - ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); - Vec3 *thisVec = &tls->pool[tls->poolPointer]; - thisVec->set(x, y, z); - tls->poolPointer = ( tls->poolPointer + 1 ) % ThreadStorage::POOL_SIZE; +Vec3* Vec3::newTemp(double x, double y, double z) { + ThreadStorage* tls = (ThreadStorage*)TlsGetValue(tlsIdx); + Vec3* thisVec = &tls->pool[tls->poolPointer]; + thisVec->set(x, y, z); + tls->poolPointer = (tls->poolPointer + 1) % ThreadStorage::POOL_SIZE; return thisVec; } -Vec3::Vec3(double x, double y, double z) -{ +Vec3::Vec3(double x, double y, double z) { if (x == -0.0) x = 0.0; if (y == -0.0) y = 0.0; if (z == -0.0) z = 0.0; @@ -72,17 +55,14 @@ Vec3::Vec3(double x, double y, double z) this->z = z; } -Vec3 *Vec3::set(double x, double y, double z) -{ +Vec3* Vec3::set(double x, double y, double z) { this->x = x; this->y = y; this->z = z; return this; } - -Vec3 *Vec3::interpolateTo(Vec3 *t, double p) -{ +Vec3* Vec3::interpolateTo(Vec3* t, double p) { double xt = x + (t->x - x) * p; double yt = y + (t->y - y) * p; double zt = z + (t->z - z) * p; @@ -90,69 +70,53 @@ Vec3 *Vec3::interpolateTo(Vec3 *t, double p) return Vec3::newTemp(xt, yt, zt); } -Vec3 *Vec3::vectorTo(Vec3 *p) -{ - return Vec3::newTemp(p->x - x, p->y - y, p->z - z); +Vec3* Vec3::vectorTo(Vec3* p) { + return Vec3::newTemp(p->x - x, p->y - y, p->z - z); } -Vec3 *Vec3::normalize() -{ - double dist = (double) (sqrt(x * x + y * y + z * z)); +Vec3* Vec3::normalize() { + double dist = (double)(sqrt(x * x + y * y + z * z)); if (dist < 0.0001) return Vec3::newTemp(0, 0, 0); return Vec3::newTemp(x / dist, y / dist, z / dist); } -double Vec3::dot(Vec3 *p) -{ - return x * p->x + y * p->y + z * p->z; +double Vec3::dot(Vec3* p) { return x * p->x + y * p->y + z * p->z; } + +Vec3* Vec3::cross(Vec3* p) { + return Vec3::newTemp(y * p->z - z * p->y, z * p->x - x * p->z, + x * p->y - y * p->x); } -Vec3 *Vec3::cross(Vec3 *p) -{ - return Vec3::newTemp(y * p->z - z * p->y, z * p->x - x * p->z, x * p->y - y * p->x); +Vec3* Vec3::add(double x, double y, double z) { + return Vec3::newTemp(this->x + x, this->y + y, this->z + z); } -Vec3 *Vec3::add(double x, double y, double z) -{ - return Vec3::newTemp(this->x + x, this->y + y, this->z + z); -} - -double Vec3::distanceTo(Vec3 *p) -{ +double Vec3::distanceTo(Vec3* p) { double xd = p->x - x; double yd = p->y - y; double zd = p->z - z; - return (double) sqrt(xd * xd + yd * yd + zd * zd); + return (double)sqrt(xd * xd + yd * yd + zd * zd); } -double Vec3::distanceToSqr(Vec3 *p) -{ +double Vec3::distanceToSqr(Vec3* p) { double xd = p->x - x; double yd = p->y - y; double zd = p->z - z; return xd * xd + yd * yd + zd * zd; } -double Vec3::distanceToSqr(double x2, double y2, double z2) -{ +double Vec3::distanceToSqr(double x2, double y2, double z2) { double xd = x2 - x; double yd = y2 - y; double zd = z2 - z; return xd * xd + yd * yd + zd * zd; } -Vec3 *Vec3::scale(double l) -{ - return Vec3::newTemp(x * l, y * l, z * l); -} +Vec3* Vec3::scale(double l) { return Vec3::newTemp(x * l, y * l, z * l); } -double Vec3::length() -{ - return sqrt(x * x + y * y + z * z); -} +double Vec3::length() { return sqrt(x * x + y * y + z * z); } -Vec3 *Vec3::clipX(Vec3 *b, double xt) -{ +Vec3* Vec3::clipX(Vec3* b, double xt) { double xd = b->x - x; double yd = b->y - y; double zd = b->z - z; @@ -164,8 +128,7 @@ Vec3 *Vec3::clipX(Vec3 *b, double xt) return Vec3::newTemp(x + xd * d, y + yd * d, z + zd * d); } -Vec3 *Vec3::clipY(Vec3 *b, double yt) -{ +Vec3* Vec3::clipY(Vec3* b, double yt) { double xd = b->x - x; double yd = b->y - y; double zd = b->z - z; @@ -177,8 +140,7 @@ Vec3 *Vec3::clipY(Vec3 *b, double yt) return Vec3::newTemp(x + xd * d, y + yd * d, z + zd * d); } -Vec3 *Vec3::clipZ(Vec3 *b, double zt) -{ +Vec3* Vec3::clipZ(Vec3* b, double zt) { double xd = b->x - x; double yd = b->y - y; double zd = b->z - z; @@ -190,21 +152,20 @@ Vec3 *Vec3::clipZ(Vec3 *b, double zt) return Vec3::newTemp(x + xd * d, y + yd * d, z + zd * d); } -std::wstring Vec3::toString() -{ - static wchar_t buf[128]; - swprintf(buf, 128, L"(%f,%f,%f)",x,y,z); - return std::wstring(buf); +std::wstring Vec3::toString() { + static wchar_t buf[128]; + swprintf(buf, 128, L"(%f,%f,%f)", x, y, z); + return std::wstring(buf); } -Vec3 *Vec3::lerp(Vec3 *v, double a) -{ - return Vec3::newTemp(x + (v->x - x) * a, y + (v->y - y) * a, z + (v->z - z) * a); +Vec3* Vec3::lerp(Vec3* v, double a) { + return Vec3::newTemp(x + (v->x - x) * a, y + (v->y - y) * a, + z + (v->z - z) * a); } -void Vec3::xRot(float degs) -{ - double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless wasting precision here +void Vec3::xRot(float degs) { + double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless + // wasting precision here double _sin = sin(degs); double xx = x; @@ -216,9 +177,9 @@ void Vec3::xRot(float degs) this->z = zz; } -void Vec3::yRot(float degs) -{ - double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless wasting precision here +void Vec3::yRot(float degs) { + double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless + // wasting precision here double _sin = sin(degs); double xx = x * _cos + z * _sin; @@ -230,9 +191,9 @@ void Vec3::yRot(float degs) this->z = zz; } -void Vec3::zRot(float degs) -{ - double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless wasting precision here +void Vec3::zRot(float degs) { + double _cos = cos(degs); // 4J - cos/sin were floats but seems pointless + // wasting precision here double _sin = sin(degs); double xx = x * _cos + y * _sin; @@ -246,20 +207,25 @@ void Vec3::zRot(float degs) // Returns 0 if this point is within the box // Otherwise returns the distance to the box -double Vec3::distanceTo(AABB *box) -{ - if(box->contains(this)) return 0; +double Vec3::distanceTo(AABB* box) { + if (box->contains(this)) return 0; - double xd = 0, yd = 0, zd = 0; + double xd = 0, yd = 0, zd = 0; - if(x < box->x0) xd = box->x0 - x; - else if( x > box->x1) xd = x - box->x1; + if (x < box->x0) + xd = box->x0 - x; + else if (x > box->x1) + xd = x - box->x1; - if(y < box->y0) yd = box->y0 - y; - else if( y > box->y1) yd = y - box->y1; + if (y < box->y0) + yd = box->y0 - y; + else if (y > box->y1) + yd = y - box->y1; - if(z < box->z0) zd = box->z0 - z; - else if( z > box->z1) zd = z - box->z1; + if (z < box->z0) + zd = box->z0 - z; + else if (z > box->z1) + zd = z - box->z1; - return sqrt(xd * xd + yd * yd + zd * zd); + return sqrt(xd * xd + yd * yd + zd * zd); } diff --git a/Minecraft.World/Util/Vec3.h b/Minecraft.World/Util/Vec3.h index 826bf9a0a..7a81f818d 100644 --- a/Minecraft.World/Util/Vec3.h +++ b/Minecraft.World/Util/Vec3.h @@ -1,59 +1,60 @@ #pragma once - class AABB; -class Vec3 -{ - // 4J added so we can have separate pools for different threads - class ThreadStorage - { - public: - static const int POOL_SIZE = 1024; - Vec3 *pool; - unsigned int poolPointer; - ThreadStorage(); - ~ThreadStorage(); - }; - static unsigned int tlsIdx; - static ThreadStorage *tlsDefault; -public: - // Each new thread that needs to use Vec3 pools will need to call one of the following 2 functions, to either create its own - // local storage, or share the default storage already allocated by the main thread - static void CreateNewThreadStorage(); - static void UseDefaultThreadStorage(); - static void ReleaseThreadStorage(); +class Vec3 { + // 4J added so we can have separate pools for different threads + class ThreadStorage { + public: + static const int POOL_SIZE = 1024; + Vec3* pool; + unsigned int poolPointer; + ThreadStorage(); + ~ThreadStorage(); + }; + static unsigned int tlsIdx; + static ThreadStorage* tlsDefault; - static Vec3 *newPermanent(double x, double y, double z); +public: + // Each new thread that needs to use Vec3 pools will need to call one of the + // following 2 functions, to either create its own local storage, or share + // the default storage already allocated by the main thread + static void CreateNewThreadStorage(); + static void UseDefaultThreadStorage(); + static void ReleaseThreadStorage(); + + static Vec3* newPermanent(double x, double y, double z); static void clearPool(); static void resetPool(); - static Vec3 *newTemp(double x, double y, double z); + static Vec3* newTemp(double x, double y, double z); double x, y, z; + private: - Vec3() {} + Vec3() {} Vec3(double x, double y, double z); - Vec3 *set(double x, double y, double z); + Vec3* set(double x, double y, double z); + public: - Vec3 *interpolateTo(Vec3 *t, double p); - Vec3 *vectorTo(Vec3 *p); - Vec3 *normalize(); - double dot(Vec3 *p); - Vec3 *cross(Vec3 *p); - Vec3 *add(double x, double y, double z); - double distanceTo(Vec3 *p); - double distanceToSqr(Vec3 *p); + Vec3* interpolateTo(Vec3* t, double p); + Vec3* vectorTo(Vec3* p); + Vec3* normalize(); + double dot(Vec3* p); + Vec3* cross(Vec3* p); + Vec3* add(double x, double y, double z); + double distanceTo(Vec3* p); + double distanceToSqr(Vec3* p); double distanceToSqr(double x2, double y2, double z2); - Vec3 *scale(double l); + Vec3* scale(double l); double length(); - Vec3 *clipX(Vec3 *b, double xt); - Vec3 *clipY(Vec3 *b, double yt); - Vec3 *clipZ(Vec3 *b, double zt); + Vec3* clipX(Vec3* b, double xt); + Vec3* clipY(Vec3* b, double yt); + Vec3* clipZ(Vec3* b, double zt); std::wstring toString(); - Vec3 *lerp(Vec3 *v, double a); + Vec3* lerp(Vec3* v, double a); void xRot(float degs); void yRot(float degs); void zRot(float degs); - // 4J Added - double distanceTo(AABB *box); + // 4J Added + double distanceTo(AABB* box); }; diff --git a/Minecraft.World/Util/WaterColor.cpp b/Minecraft.World/Util/WaterColor.cpp index b632b93a8..8399afd08 100644 --- a/Minecraft.World/Util/WaterColor.cpp +++ b/Minecraft.World/Util/WaterColor.cpp @@ -3,16 +3,16 @@ #include "WaterColor.h" // 4J Stu - Not using this any more -//intArray WaterColor::pixels; +// intArray WaterColor::pixels; // -//void WaterColor::init(intArray pixels) +// void WaterColor::init(intArray pixels) //{ // int *oldData = WaterColor::pixels.data; // WaterColor::pixels = pixels; // delete [] oldData; //} // -//int WaterColor::get(double temp, double rain) +// int WaterColor::get(double temp, double rain) //{ // rain *= temp; // int x = (int) ((1 - temp) * 255); diff --git a/Minecraft.World/Util/WaterColor.h b/Minecraft.World/Util/WaterColor.h index c4473091e..34e7755e3 100644 --- a/Minecraft.World/Util/WaterColor.h +++ b/Minecraft.World/Util/WaterColor.h @@ -1,14 +1,13 @@ #pragma once -class WaterColor -{ - // 4J Stu - Not using this (and it wasn't ever used anyway...) -//private: -// static intArray pixels; -// -//public: -// static void init(intArray pixels); -// -//public: -// static int get(double temp, double rain); +class WaterColor { + // 4J Stu - Not using this (and it wasn't ever used anyway...) + // private: + // static intArray pixels; + // + // public: + // static void init(intArray pixels); + // + // public: + // static int get(double temp, double rain); }; diff --git a/Minecraft.World/Util/WeighedRandom.cpp b/Minecraft.World/Util/WeighedRandom.cpp index 9c661b23f..47f61897d 100644 --- a/Minecraft.World/Util/WeighedRandom.cpp +++ b/Minecraft.World/Util/WeighedRandom.cpp @@ -1,72 +1,62 @@ #include "../Platform/stdafx.h" #include "WeighedRandom.h" -int WeighedRandom::getTotalWeight(std::vector *items) -{ +int WeighedRandom::getTotalWeight(std::vector* items) { int totalWeight = 0; - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) - { - totalWeight += (*it)->randomWeight; - } + for (AUTO_VAR(it, items->begin()); it != items->end(); it++) { + totalWeight += (*it)->randomWeight; + } return totalWeight; } -WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, std::vector *items, int totalWeight) -{ - if (totalWeight <= 0) - { +WeighedRandomItem* WeighedRandom::getRandomItem( + Random* random, std::vector* items, int totalWeight) { + if (totalWeight <= 0) { __debugbreak(); } - int selection = random->nextInt(totalWeight); + int selection = random->nextInt(totalWeight); - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) - { - selection -= (*it)->randomWeight; - if (selection < 0) - { + for (AUTO_VAR(it, items->begin()); it != items->end(); it++) { + selection -= (*it)->randomWeight; + if (selection < 0) { return *it; } - } + } return NULL; } -WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, std::vector *items) -{ - return getRandomItem(random, items, getTotalWeight(items)); +WeighedRandomItem* WeighedRandom::getRandomItem( + Random* random, std::vector* items) { + return getRandomItem(random, items, getTotalWeight(items)); } -int WeighedRandom::getTotalWeight(WeighedRandomItemArray items) -{ +int WeighedRandom::getTotalWeight(WeighedRandomItemArray items) { int totalWeight = 0; - for( unsigned int i = 0; i < items.length; i++ ) - { + for (unsigned int i = 0; i < items.length; i++) { totalWeight += items[i]->randomWeight; } return totalWeight; } -WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, WeighedRandomItemArray items, int totalWeight) -{ - if (totalWeight <= 0) - { +WeighedRandomItem* WeighedRandom::getRandomItem(Random* random, + WeighedRandomItemArray items, + int totalWeight) { + if (totalWeight <= 0) { __debugbreak(); } int selection = random->nextInt(totalWeight); - for( unsigned int i = 0; i < items.length; i++ ) - { - selection -= items[i]->randomWeight; - if (selection < 0) - { + for (unsigned int i = 0; i < items.length; i++) { + selection -= items[i]->randomWeight; + if (selection < 0) { return items[i]; } - } + } return NULL; } - -WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, WeighedRandomItemArray items) -{ - return getRandomItem(random, items, getTotalWeight(items)); +WeighedRandomItem* WeighedRandom::getRandomItem(Random* random, + WeighedRandomItemArray items) { + return getRandomItem(random, items, getTotalWeight(items)); } \ No newline at end of file diff --git a/Minecraft.World/Util/WeighedRandom.h b/Minecraft.World/Util/WeighedRandom.h index 7aa5d2db8..af1a0e54f 100644 --- a/Minecraft.World/Util/WeighedRandom.h +++ b/Minecraft.World/Util/WeighedRandom.h @@ -1,28 +1,30 @@ #pragma once -// 4J - this WeighedRandomItem class was a nested static class within WeighedRandom, but we need to be able to refer to it externally +// 4J - this WeighedRandomItem class was a nested static class within +// WeighedRandom, but we need to be able to refer to it externally + +class WeighedRandomItem { + friend class WeighedRandom; -class WeighedRandomItem -{ - friend class WeighedRandom; protected: - int randomWeight; + int randomWeight; public: - WeighedRandomItem(int randomWeight) - { - this->randomWeight = randomWeight; - } + WeighedRandomItem(int randomWeight) { this->randomWeight = randomWeight; } }; -class WeighedRandom -{ +class WeighedRandom { public: - // 4J - vectors here were Collection - static int getTotalWeight(std::vector *items); - static WeighedRandomItem *getRandomItem(Random *random, std::vector *items, int totalWeight); - static WeighedRandomItem *getRandomItem(Random *random, std::vector *items); - static int getTotalWeight(WeighedRandomItemArray items); - static WeighedRandomItem *getRandomItem(Random *random, WeighedRandomItemArray items, int totalWeight); - static WeighedRandomItem *getRandomItem(Random *random, WeighedRandomItemArray items); - + // 4J - vectors here were Collection + static int getTotalWeight(std::vector* items); + static WeighedRandomItem* getRandomItem( + Random* random, std::vector* items, + int totalWeight); + static WeighedRandomItem* getRandomItem( + Random* random, std::vector* items); + static int getTotalWeight(WeighedRandomItemArray items); + static WeighedRandomItem* getRandomItem(Random* random, + WeighedRandomItemArray items, + int totalWeight); + static WeighedRandomItem* getRandomItem(Random* random, + WeighedRandomItemArray items); }; diff --git a/Minecraft.World/Util/WeighedTreasure.cpp b/Minecraft.World/Util/WeighedTreasure.cpp index f4a1056fe..1011567f5 100644 --- a/Minecraft.World/Util/WeighedTreasure.cpp +++ b/Minecraft.World/Util/WeighedTreasure.cpp @@ -4,83 +4,85 @@ #include "WeighedRandom.h" #include "WeighedTreasure.h" -WeighedTreasure::WeighedTreasure(int itemId, int auxValue, int minCount, int maxCount, int weight) : WeighedRandomItem(weight) -{ - this->item = std::shared_ptr( new ItemInstance(itemId, 1, auxValue) ); - this->minCount = minCount; - this->maxCount = maxCount; +WeighedTreasure::WeighedTreasure(int itemId, int auxValue, int minCount, + int maxCount, int weight) + : WeighedRandomItem(weight) { + this->item = + std::shared_ptr(new ItemInstance(itemId, 1, auxValue)); + this->minCount = minCount; + this->maxCount = maxCount; } -WeighedTreasure::WeighedTreasure(std::shared_ptr item, int minCount, int maxCount, int weight) : WeighedRandomItem(weight) -{ - this->item = item; - this->minCount = minCount; - this->maxCount = maxCount; +WeighedTreasure::WeighedTreasure(std::shared_ptr item, + int minCount, int maxCount, int weight) + : WeighedRandomItem(weight) { + this->item = item; + this->minCount = minCount; + this->maxCount = maxCount; } -void WeighedTreasure::addChestItems(Random *random, WeighedTreasureArray items, std::shared_ptr dest, int numRolls) -{ - for (int r = 0; r < numRolls; r++) - { - WeighedTreasure *treasure = (WeighedTreasure *) WeighedRandom::getRandomItem(random, *((WeighedRandomItemArray *)&items)); +void WeighedTreasure::addChestItems(Random* random, WeighedTreasureArray items, + std::shared_ptr dest, + int numRolls) { + for (int r = 0; r < numRolls; r++) { + WeighedTreasure* treasure = + (WeighedTreasure*)WeighedRandom::getRandomItem( + random, *((WeighedRandomItemArray*)&items)); - int count = treasure->minCount + random->nextInt(treasure->maxCount - treasure->minCount + 1); - if (treasure->item->getMaxStackSize() >= count) - { - std::shared_ptr copy = treasure->item->copy(); - copy->count = count; - dest->setItem(random->nextInt(dest->getContainerSize()), copy); - } - else - { - // use multiple slots - for (int c = 0; c < count; c++) - { - std::shared_ptr copy = treasure->item->copy(); - copy->count = 1; - dest->setItem(random->nextInt(dest->getContainerSize()), copy); - } - } - } + int count = + treasure->minCount + + random->nextInt(treasure->maxCount - treasure->minCount + 1); + if (treasure->item->getMaxStackSize() >= count) { + std::shared_ptr copy = treasure->item->copy(); + copy->count = count; + dest->setItem(random->nextInt(dest->getContainerSize()), copy); + } else { + // use multiple slots + for (int c = 0; c < count; c++) { + std::shared_ptr copy = treasure->item->copy(); + copy->count = 1; + dest->setItem(random->nextInt(dest->getContainerSize()), copy); + } + } + } } -void WeighedTreasure::addDispenserItems(Random *random, WeighedTreasureArray items, std::shared_ptr dest, int numRolls) -{ - for (int r = 0; r < numRolls; r++) - { - WeighedTreasure *treasure = (WeighedTreasure *) WeighedRandom::getRandomItem(random, *((WeighedRandomItemArray *)&items)); +void WeighedTreasure::addDispenserItems( + Random* random, WeighedTreasureArray items, + std::shared_ptr dest, int numRolls) { + for (int r = 0; r < numRolls; r++) { + WeighedTreasure* treasure = + (WeighedTreasure*)WeighedRandom::getRandomItem( + random, *((WeighedRandomItemArray*)&items)); - int count = treasure->minCount + random->nextInt(treasure->maxCount - treasure->minCount + 1); - if (treasure->item->getMaxStackSize() >= count) - { - std::shared_ptr copy = treasure->item->copy(); - copy->count = count; - dest->setItem(random->nextInt(dest->getContainerSize()), copy); - } - else - { - // use multiple slots - for (int c = 0; c < count; c++) - { - std::shared_ptr copy = treasure->item->copy(); - copy->count = 1; - dest->setItem(random->nextInt(dest->getContainerSize()), copy); - } - } - } + int count = + treasure->minCount + + random->nextInt(treasure->maxCount - treasure->minCount + 1); + if (treasure->item->getMaxStackSize() >= count) { + std::shared_ptr copy = treasure->item->copy(); + copy->count = count; + dest->setItem(random->nextInt(dest->getContainerSize()), copy); + } else { + // use multiple slots + for (int c = 0; c < count; c++) { + std::shared_ptr copy = treasure->item->copy(); + copy->count = 1; + dest->setItem(random->nextInt(dest->getContainerSize()), copy); + } + } + } } -WeighedTreasureArray WeighedTreasure::addToTreasure(WeighedTreasureArray items, WeighedTreasure *extra) -{ - WeighedTreasureArray result(items.length + 1); - int i = 0; +WeighedTreasureArray WeighedTreasure::addToTreasure(WeighedTreasureArray items, + WeighedTreasure* extra) { + WeighedTreasureArray result(items.length + 1); + int i = 0; - for (int j = 0; j < items.length; j++) - { - result[i++] = items[j]; - } + for (int j = 0; j < items.length; j++) { + result[i++] = items[j]; + } - result[i++] = extra; + result[i++] = extra; - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/Util/WeighedTreasure.h b/Minecraft.World/Util/WeighedTreasure.h index 7b0ecd4c2..2205fd65d 100644 --- a/Minecraft.World/Util/WeighedTreasure.h +++ b/Minecraft.World/Util/WeighedTreasure.h @@ -2,18 +2,24 @@ #include "WeighedRandom.h" -class WeighedTreasure : public WeighedRandomItem -{ +class WeighedTreasure : public WeighedRandomItem { private: - std::shared_ptr item; - int minCount; - int maxCount; + std::shared_ptr item; + int minCount; + int maxCount; public: - WeighedTreasure(int itemId, int auxValue, int minCount, int maxCount, int weight); - WeighedTreasure(std::shared_ptr item, int minCount, int maxCount, int weight); + WeighedTreasure(int itemId, int auxValue, int minCount, int maxCount, + int weight); + WeighedTreasure(std::shared_ptr item, int minCount, + int maxCount, int weight); - static void addChestItems(Random *random, WeighedTreasureArray items, std::shared_ptr dest, int numRolls); - static void addDispenserItems(Random *random, WeighedTreasureArray items, std::shared_ptr dest, int numRolls); - static WeighedTreasureArray addToTreasure(WeighedTreasureArray items, WeighedTreasure *extra); + static void addChestItems(Random* random, WeighedTreasureArray items, + std::shared_ptr dest, + int numRolls); + static void addDispenserItems(Random* random, WeighedTreasureArray items, + std::shared_ptr dest, + int numRolls); + static WeighedTreasureArray addToTreasure(WeighedTreasureArray items, + WeighedTreasure* extra); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/BeachBiome.cpp b/Minecraft.World/WorldGen/Biomes/BeachBiome.cpp index b0563e18b..dc245389a 100644 --- a/Minecraft.World/WorldGen/Biomes/BeachBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/BeachBiome.cpp @@ -3,16 +3,15 @@ #include "BiomeDecorator.h" #include "BeachBiome.h" -BeachBiome::BeachBiome(int id) : Biome(id) -{ - // remove default mob spawn settings - friendlies.clear(); - friendlies_chicken.clear(); // 4J added - this->topMaterial = (uint8_t) Tile::sand_Id; - this->material = (uint8_t) Tile::sand_Id; +BeachBiome::BeachBiome(int id) : Biome(id) { + // remove default mob spawn settings + friendlies.clear(); + friendlies_chicken.clear(); // 4J added + this->topMaterial = (uint8_t)Tile::sand_Id; + this->material = (uint8_t)Tile::sand_Id; - decorator->treeCount = -999; - decorator->deadBushCount = 0; - decorator->reedsCount = 0; - decorator->cactusCount = 0; + decorator->treeCount = -999; + decorator->deadBushCount = 0; + decorator->reedsCount = 0; + decorator->cactusCount = 0; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/BeachBiome.h b/Minecraft.World/WorldGen/Biomes/BeachBiome.h index d01f63e3e..c41078124 100644 --- a/Minecraft.World/WorldGen/Biomes/BeachBiome.h +++ b/Minecraft.World/WorldGen/Biomes/BeachBiome.h @@ -2,8 +2,7 @@ #include "Biome.h" -class BeachBiome : public Biome -{ +class BeachBiome : public Biome { public: - BeachBiome(int id); + BeachBiome(int id); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/Biome.cpp b/Minecraft.World/WorldGen/Biomes/Biome.cpp index abd52f0b6..dbb53de36 100644 --- a/Minecraft.World/WorldGen/Biomes/Biome.cpp +++ b/Minecraft.World/WorldGen/Biomes/Biome.cpp @@ -10,299 +10,479 @@ #include "Biome.h" #include "../../Headers/net.minecraft.world.level.biome.h" -//public static final Biome[] biomes = new Biome[256]; -Biome *Biome::biomes[256]; +// public static final Biome[] biomes = new Biome[256]; +Biome* Biome::biomes[256]; -Biome *Biome::ocean = NULL; -Biome *Biome::plains = NULL; -Biome *Biome::desert = NULL; +Biome* Biome::ocean = NULL; +Biome* Biome::plains = NULL; +Biome* Biome::desert = NULL; -Biome *Biome::extremeHills = NULL; -Biome *Biome::forest = NULL; -Biome *Biome::taiga = NULL; +Biome* Biome::extremeHills = NULL; +Biome* Biome::forest = NULL; +Biome* Biome::taiga = NULL; -Biome *Biome::swampland = NULL; -Biome *Biome::river = NULL; +Biome* Biome::swampland = NULL; +Biome* Biome::river = NULL; -Biome *Biome::hell = NULL; -Biome *Biome::sky = NULL; +Biome* Biome::hell = NULL; +Biome* Biome::sky = NULL; -Biome *Biome::frozenOcean = NULL; -Biome *Biome::frozenRiver = NULL; -Biome *Biome::iceFlats = NULL; -Biome *Biome::iceMountains = NULL; -Biome *Biome::mushroomIsland = NULL; -Biome *Biome::mushroomIslandShore = NULL; -Biome *Biome::beaches = NULL; -Biome *Biome::desertHills = NULL; -Biome *Biome::forestHills = NULL; -Biome *Biome::taigaHills = NULL; -Biome *Biome::smallerExtremeHills = NULL; +Biome* Biome::frozenOcean = NULL; +Biome* Biome::frozenRiver = NULL; +Biome* Biome::iceFlats = NULL; +Biome* Biome::iceMountains = NULL; +Biome* Biome::mushroomIsland = NULL; +Biome* Biome::mushroomIslandShore = NULL; +Biome* Biome::beaches = NULL; +Biome* Biome::desertHills = NULL; +Biome* Biome::forestHills = NULL; +Biome* Biome::taigaHills = NULL; +Biome* Biome::smallerExtremeHills = NULL; -Biome *Biome::jungle = NULL; -Biome *Biome::jungleHills = NULL; +Biome* Biome::jungle = NULL; +Biome* Biome::jungleHills = NULL; +void Biome::staticCtor() { + // public static final Biome[] biomes = new Biome[256]; -void Biome::staticCtor() -{ - //public static final Biome[] biomes = new Biome[256]; + Biome::ocean = + (new OceanBiome(0)) + ->setColor(0x000070) + ->setName(L"Ocean") + ->setDepthAndScale(-1, 0.4f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Ocean, eMinecraftColour_Foliage_Ocean, + eMinecraftColour_Water_Ocean, eMinecraftColour_Sky_Ocean); + Biome::plains = + (new PlainsBiome(1)) + ->setColor(0x8db360) + ->setName(L"Plains") + ->setTemperatureAndDownfall(0.8f, 0.4f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Plains, eMinecraftColour_Foliage_Plains, + eMinecraftColour_Water_Plains, eMinecraftColour_Sky_Plains); + Biome::desert = + (new DesertBiome(2)) + ->setColor(0xFA9418) + ->setName(L"Desert") + ->setNoRain() + ->setTemperatureAndDownfall(2, 0) + ->setDepthAndScale(0.1f, 0.2f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Desert, eMinecraftColour_Foliage_Desert, + eMinecraftColour_Water_Desert, eMinecraftColour_Sky_Desert); - Biome::ocean = (new OceanBiome(0))->setColor(0x000070)->setName(L"Ocean")->setDepthAndScale(-1, 0.4f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Ocean, eMinecraftColour_Foliage_Ocean, eMinecraftColour_Water_Ocean,eMinecraftColour_Sky_Ocean); - Biome::plains = (new PlainsBiome(1))->setColor(0x8db360)->setName(L"Plains")->setTemperatureAndDownfall(0.8f, 0.4f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Plains, eMinecraftColour_Foliage_Plains, eMinecraftColour_Water_Plains,eMinecraftColour_Sky_Plains); - Biome::desert = (new DesertBiome(2))->setColor(0xFA9418)->setName(L"Desert")->setNoRain()->setTemperatureAndDownfall(2, 0)->setDepthAndScale(0.1f, 0.2f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Desert, eMinecraftColour_Foliage_Desert, eMinecraftColour_Water_Desert,eMinecraftColour_Sky_Desert); + Biome::extremeHills = + (new ExtremeHillsBiome(3)) + ->setColor(0x606060) + ->setName(L"Extreme Hills") + ->setDepthAndScale(0.3f, 1.5f) + ->setTemperatureAndDownfall(0.2f, 0.3f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_ExtremeHills, + eMinecraftColour_Foliage_ExtremeHills, + eMinecraftColour_Water_ExtremeHills, + eMinecraftColour_Sky_ExtremeHills); + Biome::forest = + (new ForestBiome(4)) + ->setColor(0x056621) + ->setName(L"Forest") + ->setLeafColor(0x4EBA31) + ->setTemperatureAndDownfall(0.7f, 0.8f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Forest, eMinecraftColour_Foliage_Forest, + eMinecraftColour_Water_Forest, eMinecraftColour_Sky_Forest); + // 4J - brought forward Taiga temperature change from 0.3f to 0.05f, + // from 1.2.3 + Biome::taiga = + (new TaigaBiome(5)) + ->setColor(0x0b6659) + ->setName(L"Taiga") + ->setLeafColor(0x4EBA31) + ->setSnowCovered() + ->setTemperatureAndDownfall(0.05f, 0.8f) + ->setDepthAndScale(0.1f, 0.4f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Taiga, eMinecraftColour_Foliage_Taiga, + eMinecraftColour_Water_Taiga, eMinecraftColour_Sky_Taiga); - Biome::extremeHills = (new ExtremeHillsBiome(3))->setColor(0x606060)->setName(L"Extreme Hills")->setDepthAndScale(0.3f, 1.5f)->setTemperatureAndDownfall(0.2f, 0.3f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_ExtremeHills, eMinecraftColour_Foliage_ExtremeHills, eMinecraftColour_Water_ExtremeHills,eMinecraftColour_Sky_ExtremeHills); - Biome::forest = (new ForestBiome(4))->setColor(0x056621)->setName(L"Forest")->setLeafColor(0x4EBA31)->setTemperatureAndDownfall(0.7f, 0.8f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Forest, eMinecraftColour_Foliage_Forest, eMinecraftColour_Water_Forest,eMinecraftColour_Sky_Forest); - // 4J - brought forward Taiga temperature change from 0.3f to 0.05f, from 1.2.3 - Biome::taiga = (new TaigaBiome(5))->setColor(0x0b6659)->setName(L"Taiga")->setLeafColor(0x4EBA31)->setSnowCovered()->setTemperatureAndDownfall(0.05f, 0.8f)->setDepthAndScale(0.1f, 0.4f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Taiga, eMinecraftColour_Foliage_Taiga, eMinecraftColour_Water_Taiga,eMinecraftColour_Sky_Taiga); + Biome::swampland = + (new SwampBiome(6)) + ->setColor(0x07F9B2) + ->setName(L"Swampland") + ->setLeafColor(0x8BAF48) + ->setDepthAndScale(-0.2f, 0.1f) + ->setTemperatureAndDownfall(0.8f, 0.9f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Swampland, + eMinecraftColour_Foliage_Swampland, + eMinecraftColour_Water_Swampland, + eMinecraftColour_Sky_Swampland); + Biome::river = + (new RiverBiome(7)) + ->setColor(0x0000ff) + ->setName(L"River") + ->setDepthAndScale(-0.5f, 0) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_River, eMinecraftColour_Foliage_River, + eMinecraftColour_Water_River, eMinecraftColour_Sky_River); - Biome::swampland = (new SwampBiome(6))->setColor(0x07F9B2)->setName(L"Swampland")->setLeafColor(0x8BAF48)->setDepthAndScale(-0.2f, 0.1f)->setTemperatureAndDownfall(0.8f, 0.9f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Swampland, eMinecraftColour_Foliage_Swampland, eMinecraftColour_Water_Swampland,eMinecraftColour_Sky_Swampland); - Biome::river = (new RiverBiome(7))->setColor(0x0000ff)->setName(L"River")->setDepthAndScale(-0.5f, 0)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_River, eMinecraftColour_Foliage_River, eMinecraftColour_Water_River,eMinecraftColour_Sky_River); + Biome::hell = + (new HellBiome(8)) + ->setColor(0xff0000) + ->setName(L"Hell") + ->setNoRain() + ->setTemperatureAndDownfall(2, 0) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Hell, eMinecraftColour_Foliage_Hell, + eMinecraftColour_Water_Hell, eMinecraftColour_Sky_Hell); + Biome::sky = (new TheEndBiome(9)) + ->setColor(0x8080ff) + ->setName(L"Sky") + ->setNoRain() + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Sky, + eMinecraftColour_Foliage_Sky, + eMinecraftColour_Water_Sky, + eMinecraftColour_Sky_Sky); - Biome::hell = (new HellBiome(8))->setColor(0xff0000)->setName(L"Hell")->setNoRain()->setTemperatureAndDownfall(2, 0)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Hell, eMinecraftColour_Foliage_Hell, eMinecraftColour_Water_Hell,eMinecraftColour_Sky_Hell); - Biome::sky = (new TheEndBiome(9))->setColor(0x8080ff)->setName(L"Sky")->setNoRain()->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Sky, eMinecraftColour_Foliage_Sky, eMinecraftColour_Water_Sky,eMinecraftColour_Sky_Sky); - - Biome::frozenOcean = (new OceanBiome(10))->setColor(0x9090a0)->setName(L"FrozenOcean")->setSnowCovered()->setDepthAndScale(-1, 0.5f)->setTemperatureAndDownfall(0, 0.5f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_FrozenOcean, eMinecraftColour_Foliage_FrozenOcean, eMinecraftColour_Water_FrozenOcean,eMinecraftColour_Sky_FrozenOcean); - Biome::frozenRiver = (new RiverBiome(11))->setColor(0xa0a0ff)->setName(L"FrozenRiver")->setSnowCovered()->setDepthAndScale(-0.5f, 0)->setTemperatureAndDownfall(0, 0.5f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_FrozenRiver, eMinecraftColour_Foliage_FrozenRiver, eMinecraftColour_Water_FrozenRiver,eMinecraftColour_Sky_FrozenRiver); - Biome::iceFlats = (new IceBiome(12))->setColor(0xffffff)->setName(L"Ice Plains")->setSnowCovered()->setTemperatureAndDownfall(0, 0.5f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_IcePlains, eMinecraftColour_Foliage_IcePlains, eMinecraftColour_Water_IcePlains,eMinecraftColour_Sky_IcePlains); - Biome::iceMountains = (new IceBiome(13))->setColor(0xa0a0a0)->setName(L"Ice Mountains")->setSnowCovered()->setDepthAndScale(0.3f, 1.3f)->setTemperatureAndDownfall(0, 0.5f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_IceMountains, eMinecraftColour_Foliage_IceMountains, eMinecraftColour_Water_IceMountains,eMinecraftColour_Sky_IceMountains); - - Biome::mushroomIsland = (new MushroomIslandBiome(14))->setColor(0xff00ff)->setName(L"MushroomIsland")->setTemperatureAndDownfall(0.9f, 1.0f)->setDepthAndScale(0.2f, 1.0f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_MushroomIsland, eMinecraftColour_Foliage_MushroomIsland, eMinecraftColour_Water_MushroomIsland,eMinecraftColour_Sky_MushroomIsland); - Biome::mushroomIslandShore = (new MushroomIslandBiome(15))->setColor(0xa000ff)->setName(L"MushroomIslandShore")->setTemperatureAndDownfall(0.9f, 1.0f)->setDepthAndScale(-1, 0.1f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_MushroomIslandShore, eMinecraftColour_Foliage_MushroomIslandShore, eMinecraftColour_Water_MushroomIslandShore,eMinecraftColour_Sky_MushroomIslandShore); + Biome::frozenOcean = + (new OceanBiome(10)) + ->setColor(0x9090a0) + ->setName(L"FrozenOcean") + ->setSnowCovered() + ->setDepthAndScale(-1, 0.5f) + ->setTemperatureAndDownfall(0, 0.5f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_FrozenOcean, + eMinecraftColour_Foliage_FrozenOcean, + eMinecraftColour_Water_FrozenOcean, + eMinecraftColour_Sky_FrozenOcean); + Biome::frozenRiver = + (new RiverBiome(11)) + ->setColor(0xa0a0ff) + ->setName(L"FrozenRiver") + ->setSnowCovered() + ->setDepthAndScale(-0.5f, 0) + ->setTemperatureAndDownfall(0, 0.5f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_FrozenRiver, + eMinecraftColour_Foliage_FrozenRiver, + eMinecraftColour_Water_FrozenRiver, + eMinecraftColour_Sky_FrozenRiver); + Biome::iceFlats = + (new IceBiome(12)) + ->setColor(0xffffff) + ->setName(L"Ice Plains") + ->setSnowCovered() + ->setTemperatureAndDownfall(0, 0.5f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_IcePlains, + eMinecraftColour_Foliage_IcePlains, + eMinecraftColour_Water_IcePlains, + eMinecraftColour_Sky_IcePlains); + Biome::iceMountains = + (new IceBiome(13)) + ->setColor(0xa0a0a0) + ->setName(L"Ice Mountains") + ->setSnowCovered() + ->setDepthAndScale(0.3f, 1.3f) + ->setTemperatureAndDownfall(0, 0.5f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_IceMountains, + eMinecraftColour_Foliage_IceMountains, + eMinecraftColour_Water_IceMountains, + eMinecraftColour_Sky_IceMountains); - Biome::beaches = (new BeachBiome(16))->setColor(0xfade55)->setName(L"Beach")->setTemperatureAndDownfall(0.8f, 0.4f)->setDepthAndScale(0.0f, 0.1f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Beach, eMinecraftColour_Foliage_Beach, eMinecraftColour_Water_Beach,eMinecraftColour_Sky_Beach); - Biome::desertHills = (new DesertBiome(17))->setColor(0xd25f12)->setName(L"DesertHills")->setNoRain()->setTemperatureAndDownfall(2, 0)->setDepthAndScale(0.3f, 0.8f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_DesertHills, eMinecraftColour_Foliage_DesertHills, eMinecraftColour_Water_DesertHills,eMinecraftColour_Sky_DesertHills); - Biome::forestHills = (new ForestBiome(18))->setColor(0x22551c)->setName(L"ForestHills")->setLeafColor(0x4EBA31)->setTemperatureAndDownfall(0.7f, 0.8f)->setDepthAndScale(0.3f, 0.7f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_ForestHills, eMinecraftColour_Foliage_ForestHills, eMinecraftColour_Water_ForestHills,eMinecraftColour_Sky_ForestHills); - Biome::taigaHills = (new TaigaBiome(19))->setColor(0x163933)->setName(L"TaigaHills")->setSnowCovered()->setLeafColor(0x4EBA31)->setTemperatureAndDownfall(0.05f, 0.8f)->setDepthAndScale(0.3f, 0.8f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_TaigaHills, eMinecraftColour_Foliage_TaigaHills, eMinecraftColour_Water_TaigaHills,eMinecraftColour_Sky_TaigaHills); - Biome::smallerExtremeHills = (new ExtremeHillsBiome(20))->setColor(0x72789a)->setName(L"Extreme Hills Edge")->setDepthAndScale(0.2f, 0.8f)->setTemperatureAndDownfall(0.2f, 0.3f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_ExtremeHillsEdge, eMinecraftColour_Foliage_ExtremeHillsEdge, eMinecraftColour_Water_ExtremeHillsEdge,eMinecraftColour_Sky_ExtremeHillsEdge); + Biome::mushroomIsland = (new MushroomIslandBiome(14)) + ->setColor(0xff00ff) + ->setName(L"MushroomIsland") + ->setTemperatureAndDownfall(0.9f, 1.0f) + ->setDepthAndScale(0.2f, 1.0f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_MushroomIsland, + eMinecraftColour_Foliage_MushroomIsland, + eMinecraftColour_Water_MushroomIsland, + eMinecraftColour_Sky_MushroomIsland); + Biome::mushroomIslandShore = + (new MushroomIslandBiome(15)) + ->setColor(0xa000ff) + ->setName(L"MushroomIslandShore") + ->setTemperatureAndDownfall(0.9f, 1.0f) + ->setDepthAndScale(-1, 0.1f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_MushroomIslandShore, + eMinecraftColour_Foliage_MushroomIslandShore, + eMinecraftColour_Water_MushroomIslandShore, + eMinecraftColour_Sky_MushroomIslandShore); - Biome::jungle = (new JungleBiome(21))->setColor(0x537b09)->setName(L"Jungle")->setLeafColor(0x537b09)->setTemperatureAndDownfall(1.2f, 0.9f)->setDepthAndScale(0.2f, 0.4f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_Jungle, eMinecraftColour_Foliage_Jungle, eMinecraftColour_Water_Jungle,eMinecraftColour_Sky_Jungle); - Biome::jungleHills = (new JungleBiome(22))->setColor(0x2c4205)->setName(L"JungleHills")->setLeafColor(0x537b09)->setTemperatureAndDownfall(1.2f, 0.9f)->setDepthAndScale(1.8f, 0.5f)->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_JungleHills, eMinecraftColour_Foliage_JungleHills, eMinecraftColour_Water_JungleHills,eMinecraftColour_Sky_JungleHills); -} - -Biome::Biome(int id) : id(id) -{ - // 4J Stu Default inits - color = 0; -// snowCovered = false; // 4J - this isn't set by the java game any more so removing to save confusion + Biome::beaches = + (new BeachBiome(16)) + ->setColor(0xfade55) + ->setName(L"Beach") + ->setTemperatureAndDownfall(0.8f, 0.4f) + ->setDepthAndScale(0.0f, 0.1f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Beach, eMinecraftColour_Foliage_Beach, + eMinecraftColour_Water_Beach, eMinecraftColour_Sky_Beach); + Biome::desertHills = + (new DesertBiome(17)) + ->setColor(0xd25f12) + ->setName(L"DesertHills") + ->setNoRain() + ->setTemperatureAndDownfall(2, 0) + ->setDepthAndScale(0.3f, 0.8f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_DesertHills, + eMinecraftColour_Foliage_DesertHills, + eMinecraftColour_Water_DesertHills, + eMinecraftColour_Sky_DesertHills); + Biome::forestHills = + (new ForestBiome(18)) + ->setColor(0x22551c) + ->setName(L"ForestHills") + ->setLeafColor(0x4EBA31) + ->setTemperatureAndDownfall(0.7f, 0.8f) + ->setDepthAndScale(0.3f, 0.7f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_ForestHills, + eMinecraftColour_Foliage_ForestHills, + eMinecraftColour_Water_ForestHills, + eMinecraftColour_Sky_ForestHills); + Biome::taigaHills = + (new TaigaBiome(19)) + ->setColor(0x163933) + ->setName(L"TaigaHills") + ->setSnowCovered() + ->setLeafColor(0x4EBA31) + ->setTemperatureAndDownfall(0.05f, 0.8f) + ->setDepthAndScale(0.3f, 0.8f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_TaigaHills, + eMinecraftColour_Foliage_TaigaHills, + eMinecraftColour_Water_TaigaHills, + eMinecraftColour_Sky_TaigaHills); + Biome::smallerExtremeHills = + (new ExtremeHillsBiome(20)) + ->setColor(0x72789a) + ->setName(L"Extreme Hills Edge") + ->setDepthAndScale(0.2f, 0.8f) + ->setTemperatureAndDownfall(0.2f, 0.3f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_ExtremeHillsEdge, + eMinecraftColour_Foliage_ExtremeHillsEdge, + eMinecraftColour_Water_ExtremeHillsEdge, + eMinecraftColour_Sky_ExtremeHillsEdge); - topMaterial = (uint8_t) Tile::grass_Id; - material = (uint8_t) Tile::dirt_Id; - leafColor = 0x4EE031; - _hasRain = true; - depth = 0.1f; - scale = 0.3f; - temperature = 0.5f; - downfall = 0.5f; - //waterColor = 0xffffff; // 4J Stu - Not used - decorator = NULL; - - m_grassColor = eMinecraftColour_NOT_SET; - m_foliageColor = eMinecraftColour_NOT_SET; - m_waterColor = eMinecraftColour_NOT_SET; - - /* 4J - removing these so that we can consistently return newly created trees via getTreeFeature, and let the calling function be resposible for deleting the returned tree - normalTree = new TreeFeature(); - fancyTree = new BasicTree(); - birchTree = new BirchFeature(); - swampTree = new SwampTreeFeature(); - */ - - biomes[id] = this; - decorator = createDecorator(); - - friendlies.push_back(new MobSpawnerData(eTYPE_SHEEP, 12, 4, 4)); - friendlies.push_back(new MobSpawnerData(eTYPE_PIG, 10, 4, 4)); - friendlies_chicken.push_back(new MobSpawnerData(eTYPE_CHICKEN, 10, 4, 4)); // 4J - moved chickens to their own category - friendlies.push_back(new MobSpawnerData(eTYPE_COW, 8, 4, 4)); - - enemies.push_back(new MobSpawnerData(eTYPE_SPIDER, 10, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_ZOMBIE, 10, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_SKELETON, 10, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_CREEPER, 10, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_SLIME, 10, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_ENDERMAN, 1, 1, 4)); - - // wolves are added to forests and taigas - - waterFriendlies.push_back(new MobSpawnerData(eTYPE_SQUID, 10, 4, 4)); + Biome::jungle = + (new JungleBiome(21)) + ->setColor(0x537b09) + ->setName(L"Jungle") + ->setLeafColor(0x537b09) + ->setTemperatureAndDownfall(1.2f, 0.9f) + ->setDepthAndScale(0.2f, 0.4f) + ->setLeafFoliageWaterSkyColor( + eMinecraftColour_Grass_Jungle, eMinecraftColour_Foliage_Jungle, + eMinecraftColour_Water_Jungle, eMinecraftColour_Sky_Jungle); + Biome::jungleHills = + (new JungleBiome(22)) + ->setColor(0x2c4205) + ->setName(L"JungleHills") + ->setLeafColor(0x537b09) + ->setTemperatureAndDownfall(1.2f, 0.9f) + ->setDepthAndScale(1.8f, 0.5f) + ->setLeafFoliageWaterSkyColor(eMinecraftColour_Grass_JungleHills, + eMinecraftColour_Foliage_JungleHills, + eMinecraftColour_Water_JungleHills, + eMinecraftColour_Sky_JungleHills); } -Biome::~Biome() -{ - if(decorator != NULL) delete decorator; +Biome::Biome(int id) : id(id) { + // 4J Stu Default inits + color = 0; + // snowCovered = false; // 4J - this isn't set by the java game any more + // so removing to save confusion + + topMaterial = (uint8_t)Tile::grass_Id; + material = (uint8_t)Tile::dirt_Id; + leafColor = 0x4EE031; + _hasRain = true; + depth = 0.1f; + scale = 0.3f; + temperature = 0.5f; + downfall = 0.5f; + // waterColor = 0xffffff; // 4J Stu - Not used + decorator = NULL; + + m_grassColor = eMinecraftColour_NOT_SET; + m_foliageColor = eMinecraftColour_NOT_SET; + m_waterColor = eMinecraftColour_NOT_SET; + + /* 4J - removing these so that we can consistently return newly created +trees via getTreeFeature, and let the calling function be resposible for +deleting the returned tree normalTree = new TreeFeature(); fancyTree = new +BasicTree(); birchTree = new BirchFeature(); swampTree = new SwampTreeFeature(); + */ + + biomes[id] = this; + decorator = createDecorator(); + + friendlies.push_back(new MobSpawnerData(eTYPE_SHEEP, 12, 4, 4)); + friendlies.push_back(new MobSpawnerData(eTYPE_PIG, 10, 4, 4)); + friendlies_chicken.push_back(new MobSpawnerData( + eTYPE_CHICKEN, 10, 4, 4)); // 4J - moved chickens to their own category + friendlies.push_back(new MobSpawnerData(eTYPE_COW, 8, 4, 4)); + + enemies.push_back(new MobSpawnerData(eTYPE_SPIDER, 10, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_ZOMBIE, 10, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_SKELETON, 10, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_CREEPER, 10, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_SLIME, 10, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_ENDERMAN, 1, 1, 4)); + + // wolves are added to forests and taigas + + waterFriendlies.push_back(new MobSpawnerData(eTYPE_SQUID, 10, 4, 4)); } -BiomeDecorator *Biome::createDecorator() -{ - return new BiomeDecorator(this); +Biome::~Biome() { + if (decorator != NULL) delete decorator; } +BiomeDecorator* Biome::createDecorator() { return new BiomeDecorator(this); } + // 4J Added -Biome *Biome::setLeafFoliageWaterSkyColor(eMinecraftColour grassColor, eMinecraftColour foliageColor, eMinecraftColour waterColour, eMinecraftColour skyColour) -{ - m_grassColor = grassColor; - m_foliageColor = foliageColor; - m_waterColor = waterColour; - m_skyColor = skyColour; - return this; +Biome* Biome::setLeafFoliageWaterSkyColor(eMinecraftColour grassColor, + eMinecraftColour foliageColor, + eMinecraftColour waterColour, + eMinecraftColour skyColour) { + m_grassColor = grassColor; + m_foliageColor = foliageColor; + m_waterColor = waterColour; + m_skyColor = skyColour; + return this; } -Biome *Biome::setTemperatureAndDownfall(float temp, float downfall) -{ - this->temperature = temp; - this->downfall = downfall; - return this; +Biome* Biome::setTemperatureAndDownfall(float temp, float downfall) { + this->temperature = temp; + this->downfall = downfall; + return this; } -Biome *Biome::setDepthAndScale(float depth, float scale) -{ - this->depth = depth; - this->scale = scale; - return this; +Biome* Biome::setDepthAndScale(float depth, float scale) { + this->depth = depth; + this->scale = scale; + return this; } -Biome *Biome::setNoRain() -{ +Biome* Biome::setNoRain() { _hasRain = false; return this; } -Feature *Biome::getTreeFeature(Random *random) -{ - if (random->nextInt(10) == 0) - { - return new BasicTree(false); // 4J used to return member fancyTree, now returning newly created object so that caller can be consistently resposible for cleanup +Feature* Biome::getTreeFeature(Random* random) { + if (random->nextInt(10) == 0) { + return new BasicTree( + false); // 4J used to return member fancyTree, now returning newly + // created object so that caller can be consistently + // resposible for cleanup } - return new TreeFeature(false); // 4J used to return member normalTree, now returning newly created object so that caller can be consistently resposible for cleanup + return new TreeFeature( + false); // 4J used to return member normalTree, now returning newly + // created object so that caller can be consistently resposible + // for cleanup } -Feature *Biome::getGrassFeature(Random *random) -{ - return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::TALL_GRASS); +Feature* Biome::getGrassFeature(Random* random) { + return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::TALL_GRASS); } -Biome *Biome::setSnowCovered() -{ +Biome* Biome::setSnowCovered() { this->snowCovered = true; return this; } -Biome *Biome::setName(const std::wstring &name) -{ +Biome* Biome::setName(const std::wstring& name) { this->m_name = name; return this; } -Biome *Biome::setLeafColor(int leafColor) -{ +Biome* Biome::setLeafColor(int leafColor) { this->leafColor = leafColor; return this; } -Biome *Biome::setColor(int color) -{ +Biome* Biome::setColor(int color) { this->color = color; return this; } -int Biome::getSkyColor(float temp) -{ - //temp /= 3.0f; - //if (temp < -1) temp = -1; - //if (temp > 1) temp = 1; - //return Color::getHSBColor(224 / 360.0f - temp * 0.05f, 0.50f + temp * 0.1f, 1.0f).getRGB(); - - // 4J Stu - Load colour from texture pack - return Minecraft::GetInstance()->getColourTable()->getColor( m_skyColor ); +int Biome::getSkyColor(float temp) { + // temp /= 3.0f; + // if (temp < -1) temp = -1; + // if (temp > 1) temp = 1; + // return Color::getHSBColor(224 / 360.0f - temp * 0.05f, 0.50f + temp * + // 0.1f, 1.0f).getRGB(); + + // 4J Stu - Load colour from texture pack + return Minecraft::GetInstance()->getColourTable()->getColor(m_skyColor); } -std::vector *Biome::getMobs(MobCategory *category) -{ +std::vector* Biome::getMobs(MobCategory* category) { if (category == MobCategory::monster) return &enemies; if (category == MobCategory::creature) return &friendlies; if (category == MobCategory::waterCreature) return &waterFriendlies; - if (category == MobCategory::creature_chicken) return &friendlies_chicken; - if (category == MobCategory::creature_wolf) return &friendlies_wolf; - if (category == MobCategory::creature_mushroomcow) return &friendlies_mushroomcow; + if (category == MobCategory::creature_chicken) return &friendlies_chicken; + if (category == MobCategory::creature_wolf) return &friendlies_wolf; + if (category == MobCategory::creature_mushroomcow) + return &friendlies_mushroomcow; return NULL; } -bool Biome::hasSnow() -{ - // 4J - snowCovered flag removed as it wasn't being set by the game anymore - snow is now temperature dependent to match code in rain rendering, shouldFreeze functions etc. - if( !_hasRain ) return false; +bool Biome::hasSnow() { + // 4J - snowCovered flag removed as it wasn't being set by the game anymore + // - snow is now temperature dependent to match code in rain rendering, + // shouldFreeze functions etc. + if (!_hasRain) return false; - if( getTemperature() >= 0.15f ) return false; + if (getTemperature() >= 0.15f) return false; return true; } -bool Biome::hasRain() -{ - // 4J - snowCovered flag removed as it wasn't being set by the game anymore, replaced by call to hasSnow() - if( hasSnow() ) return false; -// if (snowCovered) return false; +bool Biome::hasRain() { + // 4J - snowCovered flag removed as it wasn't being set by the game anymore, + // replaced by call to hasSnow() + if (hasSnow()) return false; + // if (snowCovered) return false; return _hasRain; } -bool Biome::isHumid() -{ - return downfall > .85f; -} +bool Biome::isHumid() { return downfall > .85f; } -float Biome::getCreatureProbability() -{ - return 0.1f; -} +float Biome::getCreatureProbability() { return 0.1f; } - int Biome::getDownfallInt() - { - return (int) (downfall * 65536); -} +int Biome::getDownfallInt() { return (int)(downfall * 65536); } -int Biome::getTemperatureInt() -{ - return (int) (temperature * 65536); -} +int Biome::getTemperatureInt() { return (int)(temperature * 65536); } // 4J - brought forward from 1.2.3 -float Biome::getDownfall() -{ - return downfall; -} +float Biome::getDownfall() { return downfall; } // 4J - brought forward from 1.2.3 -float Biome::getTemperature() -{ - return temperature; +float Biome::getTemperature() { return temperature; } + +void Biome::decorate(Level* level, Random* random, int xo, int zo) { + decorator->decorate(level, random, xo, zo); } -void Biome::decorate(Level *level, Random *random, int xo, int zo) -{ - decorator->decorate(level, random, xo, zo); +int Biome::getGrassColor() { + // double temp = Mth::clamp(getTemperature(), 0.0f, 1.0f); + // double rain = Mth::clamp(getDownfall(), 0.0f, 1.0f); + + // return GrassColor::get(temp, rain); + return Minecraft::GetInstance()->getColourTable()->getColor(m_grassColor); } -int Biome::getGrassColor() -{ - //double temp = Mth::clamp(getTemperature(), 0.0f, 1.0f); - //double rain = Mth::clamp(getDownfall(), 0.0f, 1.0f); +int Biome::getFolageColor() { + // double temp = Mth::clamp(getTemperature(), 0.0f, 1.0f); + // double rain = Mth::clamp(getDownfall(), 0.0f, 1.0f); - //return GrassColor::get(temp, rain); - return Minecraft::GetInstance()->getColourTable()->getColor( m_grassColor ); -} - -int Biome::getFolageColor() -{ - //double temp = Mth::clamp(getTemperature(), 0.0f, 1.0f); - //double rain = Mth::clamp(getDownfall(), 0.0f, 1.0f); - - //return FoliageColor::get(temp, rain); - return Minecraft::GetInstance()->getColourTable()->getColor( m_foliageColor ); + // return FoliageColor::get(temp, rain); + return Minecraft::GetInstance()->getColourTable()->getColor(m_foliageColor); } // 4J Added -int Biome::getWaterColor() -{ - return Minecraft::GetInstance()->getColourTable()->getColor( m_waterColor ); +int Biome::getWaterColor() { + return Minecraft::GetInstance()->getColourTable()->getColor(m_waterColor); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/Biome.h b/Minecraft.World/WorldGen/Biomes/Biome.h index a02c2bb4a..1fc9a8c72 100644 --- a/Minecraft.World/WorldGen/Biomes/Biome.h +++ b/Minecraft.World/WorldGen/Biomes/Biome.h @@ -1,6 +1,5 @@ #pragma once - #include "../../Level/Storage/LevelSource.h" #include "../../Entities/Mob.h" #include "../../Util/WeighedRandom.h" @@ -14,43 +13,43 @@ class BirchFeature; class SwampTreeFeature; class ChunkRebuildData; -class Biome -{ - friend class ChunkRebuildData; -public: - // 4J JEV, replaces the static blocks. - static void staticCtor(); - - static Biome *biomes[256]; - - static Biome *ocean; - static Biome *plains; - static Biome *desert; - static Biome *extremeHills; - static Biome *forest; - static Biome *taiga; - static Biome *swampland; - static Biome *river; - static Biome *hell; - static Biome *sky; - static Biome *frozenOcean; - static Biome *frozenRiver; - static Biome *iceFlats; - static Biome *iceMountains; - static Biome *mushroomIsland; - static Biome *mushroomIslandShore ; - static Biome *beaches; - static Biome *desertHills; - static Biome *forestHills; - static Biome *taigaHills; - static Biome *smallerExtremeHills; - static Biome *jungle; - static Biome *jungleHills; - - static const int BIOME_COUNT = 23; // 4J Stu added +class Biome { + friend class ChunkRebuildData; public: - std::wstring m_name; + // 4J JEV, replaces the static blocks. + static void staticCtor(); + + static Biome* biomes[256]; + + static Biome* ocean; + static Biome* plains; + static Biome* desert; + static Biome* extremeHills; + static Biome* forest; + static Biome* taiga; + static Biome* swampland; + static Biome* river; + static Biome* hell; + static Biome* sky; + static Biome* frozenOcean; + static Biome* frozenRiver; + static Biome* iceFlats; + static Biome* iceMountains; + static Biome* mushroomIsland; + static Biome* mushroomIslandShore; + static Biome* beaches; + static Biome* desertHills; + static Biome* forestHills; + static Biome* taigaHills; + static Biome* smallerExtremeHills; + static Biome* jungle; + static Biome* jungleHills; + + static const int BIOME_COUNT = 23; // 4J Stu added + +public: + std::wstring m_name; int color; uint8_t topMaterial; uint8_t material; @@ -59,94 +58,96 @@ public: float scale; float temperature; float downfall; - //int waterColor; // 4J Stu removed + // int waterColor; // 4J Stu removed - BiomeDecorator *decorator; + BiomeDecorator* decorator; - const int id; + const int id; - class MobSpawnerData : public WeighedRandomItem - { - public: - eINSTANCEOF mobClass; - int minCount; - int maxCount; + class MobSpawnerData : public WeighedRandomItem { + public: + eINSTANCEOF mobClass; + int minCount; + int maxCount; - MobSpawnerData(eINSTANCEOF mobClass, int probabilityWeight, int minCount, int maxCount) : WeighedRandomItem(probabilityWeight) - { - this->mobClass = mobClass; - this->minCount = minCount; - this->maxCount = maxCount; + MobSpawnerData(eINSTANCEOF mobClass, int probabilityWeight, + int minCount, int maxCount) + : WeighedRandomItem(probabilityWeight) { + this->mobClass = mobClass; + this->minCount = minCount; + this->maxCount = maxCount; } }; protected: - std::vector enemies; - std::vector friendlies; - std::vector waterFriendlies; - std::vector friendlies_chicken; - std::vector friendlies_wolf; - std::vector friendlies_mushroomcow; - - Biome(int id); - ~Biome(); - - BiomeDecorator *createDecorator(); + std::vector enemies; + std::vector friendlies; + std::vector waterFriendlies; + std::vector friendlies_chicken; + std::vector friendlies_wolf; + std::vector friendlies_mushroomcow; + + Biome(int id); + ~Biome(); + + BiomeDecorator* createDecorator(); private: - Biome *setTemperatureAndDownfall(float temp, float downfall); - Biome *setDepthAndScale(float depth, float scale); + Biome* setTemperatureAndDownfall(float temp, float downfall); + Biome* setDepthAndScale(float depth, float scale); - bool snowCovered; + bool snowCovered; bool _hasRain; - // 4J Added - eMinecraftColour m_grassColor; - eMinecraftColour m_foliageColor; - eMinecraftColour m_waterColor; - eMinecraftColour m_skyColor; + // 4J Added + eMinecraftColour m_grassColor; + eMinecraftColour m_foliageColor; + eMinecraftColour m_waterColor; + eMinecraftColour m_skyColor; - Biome *setNoRain(); + Biome* setNoRain(); protected: - /* removing these so that we can consistently return newly created trees via getTreeFeature, and let the calling function be resposible for deleting the returned tree - TreeFeature *normalTree; - BasicTree *fancyTree; - BirchFeature *birchTree; - SwampTreeFeature *swampTree; - */ + /* removing these so that we can consistently return newly created trees via +getTreeFeature, and let the calling function be resposible for deleting the +returned tree TreeFeature *normalTree; BasicTree *fancyTree; BirchFeature +*birchTree; SwampTreeFeature *swampTree; + */ public: - virtual Feature *getTreeFeature(Random *random); - virtual Feature *getGrassFeature(Random *random); + virtual Feature* getTreeFeature(Random* random); + virtual Feature* getGrassFeature(Random* random); protected: - Biome *setSnowCovered(); - Biome *setName(const std::wstring &name); - Biome *setLeafColor(int leafColor); - Biome *setColor(int color); + Biome* setSnowCovered(); + Biome* setName(const std::wstring& name); + Biome* setLeafColor(int leafColor); + Biome* setColor(int color); - // 4J Added - Biome *setLeafFoliageWaterSkyColor(eMinecraftColour grassColor, eMinecraftColour foliageColor, eMinecraftColour waterColour, eMinecraftColour skyColour); + // 4J Added + Biome* setLeafFoliageWaterSkyColor(eMinecraftColour grassColor, + eMinecraftColour foliageColor, + eMinecraftColour waterColour, + eMinecraftColour skyColour); public: virtual int getSkyColor(float temp); - std::vector *getMobs(MobCategory *category); + std::vector* getMobs(MobCategory* category); virtual bool hasSnow(); virtual bool hasRain(); - virtual bool isHumid(); + virtual bool isHumid(); virtual float getCreatureProbability(); virtual int getDownfallInt(); virtual int getTemperatureInt(); - virtual float getDownfall(); // 4J - brought forward from 1.2.3 - virtual float getTemperature(); // 4J - brought forward from 1.2.3 + virtual float getDownfall(); // 4J - brought forward from 1.2.3 + virtual float getTemperature(); // 4J - brought forward from 1.2.3 - virtual void decorate(Level *level, Random *random, int xo, int zo); + virtual void decorate(Level* level, Random* random, int xo, int zo); virtual int getGrassColor(); virtual int getFolageColor(); - virtual int getWaterColor(); // 4J Added + virtual int getWaterColor(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/BiomeCache.cpp b/Minecraft.World/WorldGen/Biomes/BiomeCache.cpp index 0e6f91eb0..35f9639c0 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeCache.cpp +++ b/Minecraft.World/WorldGen/Biomes/BiomeCache.cpp @@ -5,162 +5,146 @@ #include "BiomeCache.h" #include "../../Platform/System.h" -BiomeCache::Block::Block(int x, int z, BiomeCache *parent) -{ -// temps = floatArray(ZONE_SIZE * ZONE_SIZE, false); // MGH - added "no clear" flag to arrayWithLength -// downfall = floatArray(ZONE_SIZE * ZONE_SIZE, false); -// biomes = BiomeArray(ZONE_SIZE * ZONE_SIZE, false); - biomeIndices = byteArray(ZONE_SIZE * ZONE_SIZE, false); - - lastUse = 0; - this->x = x; - this->z = z; -// parent->source->getTemperatureBlock(temps, x << ZONE_SIZE_BITS, z << ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE); -// parent->source->getDownfallBlock(downfall, x << ZONE_SIZE_BITS, z << ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE); -// parent->source->getBiomeBlock(biomes, x << ZONE_SIZE_BITS, z << ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE, false); - // 4jcraft added cast to unsigned - parent->source->getBiomeIndexBlock(biomeIndices, (unsigned) x << ZONE_SIZE_BITS, (unsigned) z << ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE, false); +BiomeCache::Block::Block(int x, int z, BiomeCache* parent) { + // temps = floatArray(ZONE_SIZE * ZONE_SIZE, false); // MGH - + // added "no clear" flag to arrayWithLength downfall = floatArray(ZONE_SIZE + // * ZONE_SIZE, false); biomes = BiomeArray(ZONE_SIZE * ZONE_SIZE, false); + biomeIndices = byteArray(ZONE_SIZE * ZONE_SIZE, false); + lastUse = 0; + this->x = x; + this->z = z; + // parent->source->getTemperatureBlock(temps, x << ZONE_SIZE_BITS, z << + // ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE); + // parent->source->getDownfallBlock(downfall, x << ZONE_SIZE_BITS, z << + // ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE); + // parent->source->getBiomeBlock(biomes, x << ZONE_SIZE_BITS, z << + // ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE, false); 4jcraft added cast to + // unsigned + parent->source->getBiomeIndexBlock( + biomeIndices, (unsigned)x << ZONE_SIZE_BITS, + (unsigned)z << ZONE_SIZE_BITS, ZONE_SIZE, ZONE_SIZE, false); } -BiomeCache::Block::~Block() -{ -// delete [] temps.data; -// delete [] downfall.data; -// delete [] biomes.data; - delete [] biomeIndices.data; +BiomeCache::Block::~Block() { + // delete [] temps.data; + // delete [] downfall.data; + // delete [] biomes.data; + delete[] biomeIndices.data; } -Biome *BiomeCache::Block::getBiome(int x, int z) -{ -// return biomes[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; +Biome* BiomeCache::Block::getBiome(int x, int z) { + // return biomes[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << + //ZONE_SIZE_BITS)]; - int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; - return Biome::biomes[biomeIndex]; + int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | + ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; + return Biome::biomes[biomeIndex]; } -float BiomeCache::Block::getTemperature(int x, int z) -{ -// return temps[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; - - int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; - return Biome::biomes[biomeIndex]->getTemperature(); +float BiomeCache::Block::getTemperature(int x, int z) { + // return temps[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << + //ZONE_SIZE_BITS)]; + int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | + ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; + return Biome::biomes[biomeIndex]->getTemperature(); } -float BiomeCache::Block::getDownfall(int x, int z) -{ -// return downfall[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; - - int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; - return Biome::biomes[biomeIndex]->getDownfall(); +float BiomeCache::Block::getDownfall(int x, int z) { + // return downfall[(x & ZONE_SIZE_MASK) | ((z & ZONE_SIZE_MASK) << + // ZONE_SIZE_BITS)]; + int biomeIndex = biomeIndices[(x & ZONE_SIZE_MASK) | + ((z & ZONE_SIZE_MASK) << ZONE_SIZE_BITS)]; + return Biome::biomes[biomeIndex]->getDownfall(); } -BiomeCache::BiomeCache(BiomeSource *source) -{ - // 4J Initialisors - lastUpdateTime = 0; +BiomeCache::BiomeCache(BiomeSource* source) { + // 4J Initialisors + lastUpdateTime = 0; - this->source = source; - - InitializeCriticalSection(&m_CS); + this->source = source; + InitializeCriticalSection(&m_CS); } -BiomeCache::~BiomeCache() -{ - // 4J Stu - Delete source? - // delete source; +BiomeCache::~BiomeCache() { + // 4J Stu - Delete source? + // delete source; - for(AUTO_VAR(it, all.begin()); it != all.end(); ++it) - { - delete (*it); - } - DeleteCriticalSection(&m_CS); + for (AUTO_VAR(it, all.begin()); it != all.end(); ++it) { + delete (*it); + } + DeleteCriticalSection(&m_CS); } - -BiomeCache::Block *BiomeCache::getBlockAt(int x, int z) -{ - EnterCriticalSection(&m_CS); - x >>= ZONE_SIZE_BITS; - z >>= ZONE_SIZE_BITS; - __int64 slot = (((__int64) x) & 0xffffffffl) | ((((__int64) z) & 0xffffffffl) << 32l); - AUTO_VAR(it, cached.find(slot)); - Block *block = NULL; - if (it == cached.end()) - { - MemSect(48); - block = new Block(x, z, this); - cached[slot] = block; - all.push_back(block); - MemSect(0); - } - else - { - block = it->second; - } - block->lastUse = app.getAppTime(); - LeaveCriticalSection(&m_CS); - return block; +BiomeCache::Block* BiomeCache::getBlockAt(int x, int z) { + EnterCriticalSection(&m_CS); + x >>= ZONE_SIZE_BITS; + z >>= ZONE_SIZE_BITS; + __int64 slot = + (((__int64)x) & 0xffffffffl) | ((((__int64)z) & 0xffffffffl) << 32l); + AUTO_VAR(it, cached.find(slot)); + Block* block = NULL; + if (it == cached.end()) { + MemSect(48); + block = new Block(x, z, this); + cached[slot] = block; + all.push_back(block); + MemSect(0); + } else { + block = it->second; + } + block->lastUse = app.getAppTime(); + LeaveCriticalSection(&m_CS); + return block; } - -Biome *BiomeCache::getBiome(int x, int z) -{ - return getBlockAt(x, z)->getBiome(x, z); +Biome* BiomeCache::getBiome(int x, int z) { + return getBlockAt(x, z)->getBiome(x, z); } -float BiomeCache::getTemperature(int x, int z) -{ - return getBlockAt(x, z)->getTemperature(x, z); +float BiomeCache::getTemperature(int x, int z) { + return getBlockAt(x, z)->getTemperature(x, z); } -float BiomeCache::getDownfall(int x, int z) -{ - return getBlockAt(x, z)->getDownfall(x, z); +float BiomeCache::getDownfall(int x, int z) { + return getBlockAt(x, z)->getDownfall(x, z); } -void BiomeCache::update() -{ - EnterCriticalSection(&m_CS); - __int64 now = app.getAppTime(); - __int64 utime = now - lastUpdateTime; - if (utime > DECAY_TIME / 4 || utime < 0) - { - lastUpdateTime = now; +void BiomeCache::update() { + EnterCriticalSection(&m_CS); + __int64 now = app.getAppTime(); + __int64 utime = now - lastUpdateTime; + if (utime > DECAY_TIME / 4 || utime < 0) { + lastUpdateTime = now; - for (AUTO_VAR(it, all.begin()); it != all.end();) - { - Block *block = *it; - __int64 time = now - block->lastUse; - if (time > DECAY_TIME || time < 0) - { - it = all.erase(it); - __int64 slot = (((__int64) block->x) & 0xffffffffl) | ((((__int64) block->z) & 0xffffffffl) << 32l); - cached.erase(slot); - delete block; - } - else - { - ++it; - } - } - } - LeaveCriticalSection(&m_CS); + for (AUTO_VAR(it, all.begin()); it != all.end();) { + Block* block = *it; + __int64 time = now - block->lastUse; + if (time > DECAY_TIME || time < 0) { + it = all.erase(it); + __int64 slot = (((__int64)block->x) & 0xffffffffl) | + ((((__int64)block->z) & 0xffffffffl) << 32l); + cached.erase(slot); + delete block; + } else { + ++it; + } + } + } + LeaveCriticalSection(&m_CS); } -BiomeArray BiomeCache::getBiomeBlockAt(int x, int z) -{ - byteArray indices = getBlockAt(x, z)->biomeIndices; - BiomeArray biomes(indices.length); - for(int i=0;ibiomeIndices; + BiomeArray biomes(indices.length); + for (int i = 0; i < indices.length; i++) + biomes[i] = Biome::biomes[indices[i]]; + return biomes; } -byteArray BiomeCache::getBiomeIndexBlockAt(int x, int z) -{ - return getBlockAt(x, z)->biomeIndices; +byteArray BiomeCache::getBiomeIndexBlockAt(int x, int z) { + return getBlockAt(x, z)->biomeIndices; } diff --git a/Minecraft.World/WorldGen/Biomes/BiomeCache.h b/Minecraft.World/WorldGen/Biomes/BiomeCache.h index 1b4555530..5e64db0e8 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeCache.h +++ b/Minecraft.World/WorldGen/Biomes/BiomeCache.h @@ -1,52 +1,52 @@ #pragma once #include "../../Util/JavaIntHash.h" -class BiomeCache -{ +class BiomeCache { private: - static const int DECAY_TIME = 1000 * 30; - static const int ZONE_SIZE_BITS = 4; - static const int ZONE_SIZE = 1 << ZONE_SIZE_BITS; - static const int ZONE_SIZE_MASK = ZONE_SIZE - 1; + static const int DECAY_TIME = 1000 * 30; + static const int ZONE_SIZE_BITS = 4; + static const int ZONE_SIZE = 1 << ZONE_SIZE_BITS; + static const int ZONE_SIZE_MASK = ZONE_SIZE - 1; - const BiomeSource *source; - __int64 lastUpdateTime; + const BiomeSource* source; + __int64 lastUpdateTime; public: - class Block - { - public: - // MGH - changed this to just cache biome indices, as we have direct access to the data if we know the index. -// floatArray temps; -// floatArray downfall; -// BiomeArray biomes; - byteArray biomeIndices; - int x, z; - __int64 lastUse; + class Block { + public: + // MGH - changed this to just cache biome indices, as we have direct + // access to the data if we know the index. + // floatArray temps; + // floatArray downfall; + // BiomeArray biomes; + byteArray biomeIndices; + int x, z; + __int64 lastUse; - Block(int x, int z, BiomeCache *parent); - ~Block(); - Biome *getBiome(int x, int z); - float getTemperature(int x, int z); - float getDownfall(int x, int z); - }; + Block(int x, int z, BiomeCache* parent); + ~Block(); + Biome* getBiome(int x, int z); + float getTemperature(int x, int z); + float getDownfall(int x, int z); + }; private: - std::unordered_map<__int64,Block *,LongKeyHash,LongKeyEq> cached; // 4J - was LongHashMap - std::vector all; // was ArrayList + std::unordered_map<__int64, Block*, LongKeyHash, LongKeyEq> + cached; // 4J - was LongHashMap + std::vector all; // was ArrayList public: - BiomeCache(BiomeSource *source); - ~BiomeCache(); + BiomeCache(BiomeSource* source); + ~BiomeCache(); - Block *getBlockAt(int x, int z); - Biome *getBiome(int x, int z); - float getTemperature(int x, int z); - float getDownfall(int x, int z); - void update(); - BiomeArray getBiomeBlockAt(int x, int z); - byteArray getBiomeIndexBlockAt(int x, int z); + Block* getBlockAt(int x, int z); + Biome* getBiome(int x, int z); + float getTemperature(int x, int z); + float getDownfall(int x, int z); + void update(); + BiomeArray getBiomeBlockAt(int x, int z); + byteArray getBiomeIndexBlockAt(int x, int z); private: - CRITICAL_SECTION m_CS; + CRITICAL_SECTION m_CS; }; diff --git a/Minecraft.World/WorldGen/Biomes/BiomeDecorator.cpp b/Minecraft.World/WorldGen/Biomes/BiomeDecorator.cpp index 544f79ad6..ca5f25ed1 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeDecorator.cpp +++ b/Minecraft.World/WorldGen/Biomes/BiomeDecorator.cpp @@ -4,325 +4,296 @@ #include "../../Headers/net.minecraft.world.level.levelgen.feature.h" #include "../../Headers/net.minecraft.world.level.biome.h" -BiomeDecorator::BiomeDecorator(Biome *biome) -{ - _init(); +BiomeDecorator::BiomeDecorator(Biome* biome) { + _init(); - // 4J inits - level = NULL; - random = NULL; - xo = 0; - zo = 0; + // 4J inits + level = NULL; + random = NULL; + xo = 0; + zo = 0; - this->biome = biome; + this->biome = biome; } -void BiomeDecorator::decorate(Level *level, Random *random, int xo, int zo) -{ - if (this->level != NULL) - { - app.DebugPrintf("BiomeDecorator::decorate - Already decorating!!\n"); +void BiomeDecorator::decorate(Level* level, Random* random, int xo, int zo) { + if (this->level != NULL) { + app.DebugPrintf("BiomeDecorator::decorate - Already decorating!!\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); - //throw new RuntimeException("Already decorating!!"); + __debugbreak(); + // throw new RuntimeException("Already decorating!!"); #endif - } - this->level = level; - this->random = random; - this->xo = xo; - this->zo = zo; + } + this->level = level; + this->random = random; + this->xo = xo; + this->zo = zo; - decorate(); + decorate(); - this->level = NULL; - this->random = NULL; + this->level = NULL; + this->random = NULL; } +void BiomeDecorator::_init() { + clayFeature = new ClayFeature(4); + sandFeature = new SandFeature(7, Tile::sand_Id); + gravelFeature = new SandFeature(6, Tile::gravel_Id); + dirtOreFeature = new OreFeature(Tile::dirt_Id, 32); + gravelOreFeature = new OreFeature(Tile::gravel_Id, 32); + coalOreFeature = new OreFeature(Tile::coalOre_Id, 16); + ironOreFeature = new OreFeature(Tile::ironOre_Id, 8); + goldOreFeature = new OreFeature(Tile::goldOre_Id, 8); + redStoneOreFeature = new OreFeature(Tile::redStoneOre_Id, 7); + diamondOreFeature = new OreFeature(Tile::diamondOre_Id, 7); + lapisOreFeature = new OreFeature(Tile::lapisOre_Id, 6); + yellowFlowerFeature = new FlowerFeature(Tile::flower_Id); + roseFlowerFeature = new FlowerFeature(Tile::rose_Id); + brownMushroomFeature = new FlowerFeature(Tile::mushroom1_Id); + redMushroomFeature = new FlowerFeature(Tile::mushroom2_Id); + hugeMushroomFeature = new HugeMushroomFeature(); + reedsFeature = new ReedsFeature(); + cactusFeature = new CactusFeature(); + waterlilyFeature = new WaterlilyFeature(); - -void BiomeDecorator::_init() -{ - clayFeature = new ClayFeature(4); - sandFeature = new SandFeature(7, Tile::sand_Id); - gravelFeature = new SandFeature(6, Tile::gravel_Id); - dirtOreFeature = new OreFeature(Tile::dirt_Id, 32); - gravelOreFeature = new OreFeature(Tile::gravel_Id, 32); - coalOreFeature = new OreFeature(Tile::coalOre_Id, 16); - ironOreFeature = new OreFeature(Tile::ironOre_Id, 8); - goldOreFeature = new OreFeature(Tile::goldOre_Id, 8); - redStoneOreFeature = new OreFeature(Tile::redStoneOre_Id, 7); - diamondOreFeature = new OreFeature(Tile::diamondOre_Id, 7); - lapisOreFeature = new OreFeature(Tile::lapisOre_Id, 6); - yellowFlowerFeature = new FlowerFeature(Tile::flower_Id); - roseFlowerFeature = new FlowerFeature(Tile::rose_Id); - brownMushroomFeature = new FlowerFeature(Tile::mushroom1_Id); - redMushroomFeature = new FlowerFeature(Tile::mushroom2_Id); - hugeMushroomFeature = new HugeMushroomFeature(); - reedsFeature = new ReedsFeature(); - cactusFeature = new CactusFeature(); - waterlilyFeature = new WaterlilyFeature(); - - waterlilyCount = 0; - treeCount = 0; - flowerCount = 2; - grassCount = 1; - deadBushCount = 0; - mushroomCount = 0; - reedsCount = 0; - cactusCount = 0; - gravelCount = 1; - sandCount = 3; - clayCount = 1; - hugeMushrooms = 0; - liquids = true; + waterlilyCount = 0; + treeCount = 0; + flowerCount = 2; + grassCount = 1; + deadBushCount = 0; + mushroomCount = 0; + reedsCount = 0; + cactusCount = 0; + gravelCount = 1; + sandCount = 3; + clayCount = 1; + hugeMushrooms = 0; + liquids = true; } +void BiomeDecorator::decorate() { + PIXBeginNamedEvent(0, "Decorate ores"); + decorateOres(); + PIXEndNamedEvent(); -void BiomeDecorator::decorate() -{ - PIXBeginNamedEvent(0,"Decorate ores"); - decorateOres(); - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Decorate sand/clay/gravel"); - for (int i = 0; i < sandCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - sandFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); - } - - for (int i = 0; i < clayCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - clayFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); - } - - for (int i = 0; i < gravelCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - sandFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); - } - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0, "Decorate forests"); - int forests = treeCount; - if (random->nextInt(10) == 0) forests += 1; - - for (int i = 0; i < forests; i++) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - Feature *tree = biome->getTreeFeature(random); - tree->init(1, 1, 1); - tree->place(level, random, x, level->getHeightmap(x, z), z); - delete tree; - } - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Decorate mushrooms/flowers/grass"); - for (int i = 0; i < hugeMushrooms; i++) - { + PIXBeginNamedEvent(0, "Decorate sand/clay/gravel"); + for (int i = 0; i < sandCount; i++) { int x = xo + random->nextInt(16) + 8; int z = zo + random->nextInt(16) + 8; - hugeMushroomFeature->place(level, random, x, level->getHeightmap(x, z), z); + sandFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); } - for (int i = 0; i < flowerCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - yellowFlowerFeature->place(level, random, x, y, z); + for (int i = 0; i < clayCount; i++) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + clayFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); + } - if (random->nextInt(4) == 0) - { - x = xo + random->nextInt(16) + 8; - y = random->nextInt(Level::genDepth); - z = zo + random->nextInt(16) + 8; - roseFlowerFeature->place(level, random, x, y, z); - } - } + for (int i = 0; i < gravelCount; i++) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + sandFeature->place(level, random, x, level->getTopSolidBlock(x, z), z); + } + PIXEndNamedEvent(); - for (int i = 0; i < grassCount; i++) - { - //int grassType = TallGrass::TALL_GRASS; + PIXBeginNamedEvent(0, "Decorate forests"); + int forests = treeCount; + if (random->nextInt(10) == 0) forests += 1; - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - MemSect(50); - Feature *grassFeature = biome->getGrassFeature(random); - MemSect(0); - grassFeature->place(level, random, x, y, z); - delete grassFeature; - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Decorate bush/waterlily/mushroom/reeds/pumpkins/cactuses"); + for (int i = 0; i < forests; i++) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + Feature* tree = biome->getTreeFeature(random); + tree->init(1, 1, 1); + tree->place(level, random, x, level->getHeightmap(x, z), z); + delete tree; + } + PIXEndNamedEvent(); - // 4J Stu - For some reason this was created each time round in the loop - // I assume there is a case where deadBushCount could be 0 - DeadBushFeature *deadBushFeature = NULL; - if(deadBushCount > 0) deadBushFeature = new DeadBushFeature(Tile::deadBush_Id); - for (int i = 0; i < deadBushCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - //new DeadBushFeature(Tile::deadBush_Id)->place(level, random, x, y, z); - deadBushFeature->place(level, random, x, y, z); - } - if(deadBushFeature != NULL)delete deadBushFeature; + PIXBeginNamedEvent(0, "Decorate mushrooms/flowers/grass"); + for (int i = 0; i < hugeMushrooms; i++) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + hugeMushroomFeature->place(level, random, x, level->getHeightmap(x, z), + z); + } - for (int i = 0; i < waterlilyCount; i++) - { + for (int i = 0; i < flowerCount; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + yellowFlowerFeature->place(level, random, x, y, z); + + if (random->nextInt(4) == 0) { + x = xo + random->nextInt(16) + 8; + y = random->nextInt(Level::genDepth); + z = zo + random->nextInt(16) + 8; + roseFlowerFeature->place(level, random, x, y, z); + } + } + + for (int i = 0; i < grassCount; i++) { + // int grassType = TallGrass::TALL_GRASS; + + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + MemSect(50); + Feature* grassFeature = biome->getGrassFeature(random); + MemSect(0); + grassFeature->place(level, random, x, y, z); + delete grassFeature; + } + PIXEndNamedEvent(); + PIXBeginNamedEvent( + 0, "Decorate bush/waterlily/mushroom/reeds/pumpkins/cactuses"); + + // 4J Stu - For some reason this was created each time round in the loop + // I assume there is a case where deadBushCount could be 0 + DeadBushFeature* deadBushFeature = NULL; + if (deadBushCount > 0) + deadBushFeature = new DeadBushFeature(Tile::deadBush_Id); + for (int i = 0; i < deadBushCount; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + // new DeadBushFeature(Tile::deadBush_Id)->place(level, random, x, y, + // z); + deadBushFeature->place(level, random, x, y, z); + } + if (deadBushFeature != NULL) delete deadBushFeature; + + for (int i = 0; i < waterlilyCount; i++) { int x = xo + random->nextInt(16) + 8; int z = zo + random->nextInt(16) + 8; int y = random->nextInt(Level::genDepth); - while (y > 0 && level->getTile(x, y - 1, z) == 0) - y--; + while (y > 0 && level->getTile(x, y - 1, z) == 0) y--; waterlilyFeature->place(level, random, x, y, z); } - for (int i = 0; i < mushroomCount; i++) - { - if (random->nextInt(4) == 0) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - int y = level->getHeightmap(x, z); - brownMushroomFeature->place(level, random, x, y, z); - } + for (int i = 0; i < mushroomCount; i++) { + if (random->nextInt(4) == 0) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + int y = level->getHeightmap(x, z); + brownMushroomFeature->place(level, random, x, y, z); + } - if (random->nextInt(8) == 0) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - redMushroomFeature->place(level, random, x, y, z); - } - } + if (random->nextInt(8) == 0) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + redMushroomFeature->place(level, random, x, y, z); + } + } - if (random->nextInt(4) == 0) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - brownMushroomFeature->place(level, random, x, y, z); - } + if (random->nextInt(4) == 0) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + brownMushroomFeature->place(level, random, x, y, z); + } - if (random->nextInt(8) == 0) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - redMushroomFeature->place(level, random, x, y, z); - } + if (random->nextInt(8) == 0) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + redMushroomFeature->place(level, random, x, y, z); + } - for (int i = 0; i < reedsCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - reedsFeature->place(level, random, x, y, z); - } + for (int i = 0; i < reedsCount; i++) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + reedsFeature->place(level, random, x, y, z); + } - for (int i = 0; i < 10; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - reedsFeature->place(level, random, x, y, z); - } + for (int i = 0; i < 10; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + reedsFeature->place(level, random, x, y, z); + } - if (random->nextInt(32) == 0) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - PumpkinFeature *pumpkinFeature = new PumpkinFeature(); - pumpkinFeature->place(level, random, x, y, z); - delete pumpkinFeature; - } + if (random->nextInt(32) == 0) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + PumpkinFeature* pumpkinFeature = new PumpkinFeature(); + pumpkinFeature->place(level, random, x, y, z); + delete pumpkinFeature; + } - for (int i = 0; i < cactusCount; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(Level::genDepth); - int z = zo + random->nextInt(16) + 8; - cactusFeature->place(level, random, x, y, z); - } + for (int i = 0; i < cactusCount; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(Level::genDepth); + int z = zo + random->nextInt(16) + 8; + cactusFeature->place(level, random, x, y, z); + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Decorate liquids"); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Decorate liquids"); + if (liquids) { + // 4J Stu - For some reason this was created each time round in the loop + SpringFeature* waterSpringFeature = new SpringFeature(Tile::water_Id); + for (int i = 0; i < 50; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt(random->nextInt(Level::genDepth - 8) + 8); + int z = zo + random->nextInt(16) + 8; + waterSpringFeature->place(level, random, x, y, z); + } + delete waterSpringFeature; - if( liquids ) - { - // 4J Stu - For some reason this was created each time round in the loop - SpringFeature *waterSpringFeature = new SpringFeature(Tile::water_Id); - for (int i = 0; i < 50; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(random->nextInt(Level::genDepth - 8) + 8); - int z = zo + random->nextInt(16) + 8; - waterSpringFeature->place(level, random, x, y, z); - } - delete waterSpringFeature; - - // 4J Stu - For some reason this was created each time round in the loop - SpringFeature *lavaSpringFeature = new SpringFeature(Tile::lava_Id); - for (int i = 0; i < 20; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = random->nextInt(random->nextInt(random->nextInt(Level::genDepth - 16) + 8) + 8); - int z = zo + random->nextInt(16) + 8; - lavaSpringFeature->place(level, random, x, y, z); - } - delete lavaSpringFeature; - } - PIXEndNamedEvent(); + // 4J Stu - For some reason this was created each time round in the loop + SpringFeature* lavaSpringFeature = new SpringFeature(Tile::lava_Id); + for (int i = 0; i < 20; i++) { + int x = xo + random->nextInt(16) + 8; + int y = random->nextInt( + random->nextInt(random->nextInt(Level::genDepth - 16) + 8) + 8); + int z = zo + random->nextInt(16) + 8; + lavaSpringFeature->place(level, random, x, y, z); + } + delete lavaSpringFeature; + } + PIXEndNamedEvent(); } -void BiomeDecorator::decorate(int count, Feature *feature) -{ - decorateDepthSpan(count, feature, 0, Level::genDepth); +void BiomeDecorator::decorate(int count, Feature* feature) { + decorateDepthSpan(count, feature, 0, Level::genDepth); } -void BiomeDecorator::decorateDepthSpan(int count, Feature *feature, int y0, int y1) -{ - for (int i = 0; i < count; i++) - { - int x = xo + random->nextInt(16); - int y = random->nextInt(y1 - y0) + y0; - int z = zo + random->nextInt(16); - feature->place(level, random, x, y, z); - } +void BiomeDecorator::decorateDepthSpan(int count, Feature* feature, int y0, + int y1) { + for (int i = 0; i < count; i++) { + int x = xo + random->nextInt(16); + int y = random->nextInt(y1 - y0) + y0; + int z = zo + random->nextInt(16); + feature->place(level, random, x, y, z); + } } -void BiomeDecorator::decorateDepthAverage(int count, Feature *feature, int yMid, int ySpan) -{ - for (int i = 0; i < count; i++) - { - int x = xo + random->nextInt(16); - int y = random->nextInt(ySpan) + random->nextInt(ySpan) + (yMid - ySpan); - int z = zo + random->nextInt(16); - feature->place(level, random, x, y, z); - } +void BiomeDecorator::decorateDepthAverage(int count, Feature* feature, int yMid, + int ySpan) { + for (int i = 0; i < count; i++) { + int x = xo + random->nextInt(16); + int y = + random->nextInt(ySpan) + random->nextInt(ySpan) + (yMid - ySpan); + int z = zo + random->nextInt(16); + feature->place(level, random, x, y, z); + } } -void BiomeDecorator::decorateOres() -{ - level->setInstaTick(true); // 4J - optimisation - decorateDepthSpan(20, dirtOreFeature, 0, Level::genDepth); - decorateDepthSpan(10, gravelOreFeature, 0, Level::genDepth); - decorateDepthSpan(20, coalOreFeature, 0, Level::genDepth); - decorateDepthSpan(20, ironOreFeature, 0, Level::genDepth / 2); - decorateDepthSpan(2, goldOreFeature, 0, Level::genDepth / 4); - decorateDepthSpan(8, redStoneOreFeature, 0, Level::genDepth / 8); - decorateDepthSpan(1, diamondOreFeature, 0, Level::genDepth / 8); - decorateDepthAverage(1, lapisOreFeature, Level::genDepth / 8, Level::genDepth / 8); - level->setInstaTick(false); +void BiomeDecorator::decorateOres() { + level->setInstaTick(true); // 4J - optimisation + decorateDepthSpan(20, dirtOreFeature, 0, Level::genDepth); + decorateDepthSpan(10, gravelOreFeature, 0, Level::genDepth); + decorateDepthSpan(20, coalOreFeature, 0, Level::genDepth); + decorateDepthSpan(20, ironOreFeature, 0, Level::genDepth / 2); + decorateDepthSpan(2, goldOreFeature, 0, Level::genDepth / 4); + decorateDepthSpan(8, redStoneOreFeature, 0, Level::genDepth / 8); + decorateDepthSpan(1, diamondOreFeature, 0, Level::genDepth / 8); + decorateDepthAverage(1, lapisOreFeature, Level::genDepth / 8, + Level::genDepth / 8); + level->setInstaTick(false); } diff --git a/Minecraft.World/WorldGen/Biomes/BiomeDecorator.h b/Minecraft.World/WorldGen/Biomes/BiomeDecorator.h index 480def9dd..5f67adba4 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeDecorator.h +++ b/Minecraft.World/WorldGen/Biomes/BiomeDecorator.h @@ -5,73 +5,71 @@ class Random; class Biome; class Feature; -class BiomeDecorator -{ - friend class DesertBiome; - friend class ForestBiome; - friend class PlainsBiome; - friend class SwampBiome; - friend class TaigaBiome; - friend class MushroomIslandBiome; - friend class BeachBiome; - friend class JungleBiome; +class BiomeDecorator { + friend class DesertBiome; + friend class ForestBiome; + friend class PlainsBiome; + friend class SwampBiome; + friend class TaigaBiome; + friend class MushroomIslandBiome; + friend class BeachBiome; + friend class JungleBiome; + protected: - Level *level; - Random *random; - int xo; - int zo; - Biome *biome; + Level* level; + Random* random; + int xo; + int zo; + Biome* biome; public: - BiomeDecorator(Biome *biome); - virtual ~BiomeDecorator(){} + BiomeDecorator(Biome* biome); + virtual ~BiomeDecorator() {} - - void decorate(Level *level, Random *random, int xo, int zo); + void decorate(Level* level, Random* random, int xo, int zo); protected: - Feature *clayFeature; - Feature *sandFeature; - Feature *gravelFeature; - Feature *dirtOreFeature; - Feature *gravelOreFeature; - Feature *coalOreFeature; - Feature *ironOreFeature; - Feature *goldOreFeature; - Feature *redStoneOreFeature; - Feature *diamondOreFeature; - Feature *lapisOreFeature; - Feature *yellowFlowerFeature; - Feature *roseFlowerFeature; - Feature *brownMushroomFeature; - Feature *redMushroomFeature; - Feature *hugeMushroomFeature; - Feature *reedsFeature; - Feature *cactusFeature; - Feature *waterlilyFeature; + Feature* clayFeature; + Feature* sandFeature; + Feature* gravelFeature; + Feature* dirtOreFeature; + Feature* gravelOreFeature; + Feature* coalOreFeature; + Feature* ironOreFeature; + Feature* goldOreFeature; + Feature* redStoneOreFeature; + Feature* diamondOreFeature; + Feature* lapisOreFeature; + Feature* yellowFlowerFeature; + Feature* roseFlowerFeature; + Feature* brownMushroomFeature; + Feature* redMushroomFeature; + Feature* hugeMushroomFeature; + Feature* reedsFeature; + Feature* cactusFeature; + Feature* waterlilyFeature; - int waterlilyCount; - int treeCount; - int flowerCount; - int grassCount; - int deadBushCount; - int mushroomCount; - int reedsCount; - int cactusCount; - int gravelCount; - int sandCount; - int clayCount; - int hugeMushrooms; - bool liquids; + int waterlilyCount; + int treeCount; + int flowerCount; + int grassCount; + int deadBushCount; + int mushroomCount; + int reedsCount; + int cactusCount; + int gravelCount; + int sandCount; + int clayCount; + int hugeMushrooms; + bool liquids; - void _init(); + void _init(); protected: - virtual void decorate(); + virtual void decorate(); - - void decorate(int count, Feature *feature); - void decorateDepthSpan(int count, Feature *feature, int y0, int y1); - void decorateDepthAverage(int count, Feature *feature, int yMid, int ySpan); - void decorateOres(); + void decorate(int count, Feature* feature); + void decorateDepthSpan(int count, Feature* feature, int y0, int y1); + void decorateDepthAverage(int count, Feature* feature, int yMid, int ySpan); + void decorateOres(); }; diff --git a/Minecraft.World/WorldGen/Biomes/BiomeSource.cpp b/Minecraft.World/WorldGen/Biomes/BiomeSource.cpp index 3a77b436d..d06846971 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeSource.cpp +++ b/Minecraft.World/WorldGen/Biomes/BiomeSource.cpp @@ -8,631 +8,586 @@ #include "../../../Minecraft.Client/Minecraft.h" #include "../../../Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h" -// 4J - removal of separate temperature & downfall layers brought forward from 1.2.3 -void BiomeSource::_init() -{ +// 4J - removal of separate temperature & downfall layers brought forward +// from 1.2.3 +void BiomeSource::_init() { layer = nullptr; - zoomedLayer = nullptr; - - cache = new BiomeCache(this); + zoomedLayer = nullptr; - playerSpawnBiomes.push_back(Biome::forest); - playerSpawnBiomes.push_back(Biome::taiga); - // 4J-PB - Moving forward plains as a spawnable biome (mainly for the Superflat world) - playerSpawnBiomes.push_back(Biome::plains); - playerSpawnBiomes.push_back(Biome::taigaHills); - playerSpawnBiomes.push_back(Biome::forestHills); - playerSpawnBiomes.push_back(Biome::jungle); - playerSpawnBiomes.push_back(Biome::jungleHills); + cache = new BiomeCache(this); + + playerSpawnBiomes.push_back(Biome::forest); + playerSpawnBiomes.push_back(Biome::taiga); + // 4J-PB - Moving forward plains as a spawnable biome (mainly for the + // Superflat world) + playerSpawnBiomes.push_back(Biome::plains); + playerSpawnBiomes.push_back(Biome::taigaHills); + playerSpawnBiomes.push_back(Biome::forestHills); + playerSpawnBiomes.push_back(Biome::jungle); + playerSpawnBiomes.push_back(Biome::jungleHills); } -void BiomeSource::_init(__int64 seed, LevelType *generator) -{ - _init(); - - LayerArray layers = Layer::getDefaultLayers(seed, generator); - layer = layers[0]; - zoomedLayer = layers[1]; - - delete [] layers.data; -} - -BiomeSource::BiomeSource() -{ +void BiomeSource::_init(__int64 seed, LevelType* generator) { _init(); + + LayerArray layers = Layer::getDefaultLayers(seed, generator); + layer = layers[0]; + zoomedLayer = layers[1]; + + delete[] layers.data; } +BiomeSource::BiomeSource() { _init(); } + // 4J added -BiomeSource::BiomeSource(__int64 seed, LevelType *generator) -{ - _init(seed, generator); +BiomeSource::BiomeSource(__int64 seed, LevelType* generator) { + _init(seed, generator); } -// 4J - removal of separate temperature & downfall layers brought forward from 1.2.3 -BiomeSource::BiomeSource(Level *level) -{ - _init(level->getSeed(), level->getLevelData()->getGenerator()); +// 4J - removal of separate temperature & downfall layers brought forward +// from 1.2.3 +BiomeSource::BiomeSource(Level* level) { + _init(level->getSeed(), level->getLevelData()->getGenerator()); } -BiomeSource::~BiomeSource() -{ - delete cache; +BiomeSource::~BiomeSource() { delete cache; } + +Biome* BiomeSource::getBiome(ChunkPos* cp) { + return getBiome(cp->x << 4, cp->z << 4); } -Biome *BiomeSource::getBiome(ChunkPos *cp) -{ - return getBiome(cp->x << 4, cp->z << 4); +Biome* BiomeSource::getBiome(int x, int z) { return cache->getBiome(x, z); } + +float BiomeSource::getDownfall(int x, int z) const { + return cache->getDownfall(x, z); } -Biome *BiomeSource::getBiome(int x, int z) -{ - return cache->getBiome(x, z); +// 4J - note that caller is responsible for deleting returned array. +// temperatures array is for output only. +floatArray BiomeSource::getDownfallBlock(int x, int z, int w, int h) const { + floatArray downfalls; + getDownfallBlock(downfalls, x, z, w, h); + return downfalls; } -float BiomeSource::getDownfall(int x, int z) const -{ - return cache->getDownfall(x, z); +// 4J - note that caller is responsible for deleting returned array. +// temperatures array is for output only. 4J - removal of separate temperature & +// downfall layers brought forward from 1.2.3 +void BiomeSource::getDownfallBlock(floatArray& downfalls, int x, int z, int w, + int h) const { + IntCache::releaseAll(); + // if (downfalls == NULL || downfalls->length < w * h) + if (downfalls.data == NULL || downfalls.length < w * h) { + if (downfalls.data != NULL) delete[] downfalls.data; + downfalls = floatArray(w * h); + } + + intArray result = zoomedLayer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + float d = (float)Biome::biomes[result[i]]->getDownfallInt() / 65536.0f; + if (d > 1) d = 1; + downfalls[i] = d; + } } -// 4J - note that caller is responsible for deleting returned array. temperatures array is for output only. -floatArray BiomeSource::getDownfallBlock(int x, int z, int w, int h) const -{ - floatArray downfalls; - getDownfallBlock(downfalls, x, z, w, h); - return downfalls; -} - -// 4J - note that caller is responsible for deleting returned array. temperatures array is for output only. -// 4J - removal of separate temperature & downfall layers brought forward from 1.2.3 -void BiomeSource::getDownfallBlock(floatArray &downfalls, int x, int z, int w, int h) const -{ - IntCache::releaseAll(); - //if (downfalls == NULL || downfalls->length < w * h) - if (downfalls.data == NULL || downfalls.length < w * h) - { - if(downfalls.data != NULL) delete [] downfalls.data; - downfalls = floatArray(w * h); - } - - intArray result = zoomedLayer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - float d = (float) Biome::biomes[result[i]]->getDownfallInt() / 65536.0f; - if (d > 1) d = 1; - downfalls[i] = d; - } -} - -BiomeCache::Block *BiomeSource::getBlockAt(int x, int y) -{ +BiomeCache::Block* BiomeSource::getBlockAt(int x, int y) { return cache->getBlockAt(x, y); } -float BiomeSource::getTemperature(int x, int y, int z) const -{ - return scaleTemp(cache->getTemperature(x, z), y); +float BiomeSource::getTemperature(int x, int y, int z) const { + return scaleTemp(cache->getTemperature(x, z), y); } // 4J - brought forward from 1.2.3 -float BiomeSource::scaleTemp(float temp, int y ) const -{ - return temp; +float BiomeSource::scaleTemp(float temp, int y) const { return temp; } + +floatArray BiomeSource::getTemperatureBlock(int x, int z, int w, int h) const { + floatArray temperatures; + getTemperatureBlock(temperatures, x, z, w, h); + return temperatures; } -floatArray BiomeSource::getTemperatureBlock(int x, int z, int w, int h) const -{ - floatArray temperatures; - getTemperatureBlock(temperatures, x, z, w, h); - return temperatures; +// 4J - note that caller is responsible for deleting returned array. +// temperatures array is for output only. 4J - removal of separate temperature & +// downfall layers brought forward from 1.2.3 +void BiomeSource::getTemperatureBlock(floatArray& temperatures, int x, int z, + int w, int h) const { + IntCache::releaseAll(); + // if (temperatures == null || temperatures.length < w * h) { + if (temperatures.data == NULL || temperatures.length < w * h) { + if (temperatures.data != NULL) delete[] temperatures.data; + temperatures = floatArray(w * h); + } + + intArray result = zoomedLayer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + float t = + (float)Biome::biomes[result[i]]->getTemperatureInt() / 65536.0f; + if (t > 1) t = 1; + temperatures[i] = t; + } } -// 4J - note that caller is responsible for deleting returned array. temperatures array is for output only. -// 4J - removal of separate temperature & downfall layers brought forward from 1.2.3 -void BiomeSource::getTemperatureBlock(floatArray& temperatures, int x, int z, int w, int h) const -{ - IntCache::releaseAll(); - //if (temperatures == null || temperatures.length < w * h) { - if (temperatures.data == NULL || temperatures.length < w * h) - { - if( temperatures.data != NULL ) delete [] temperatures.data; - temperatures = floatArray(w * h); - } - - intArray result = zoomedLayer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - float t = (float) Biome::biomes[result[i]]->getTemperatureInt() / 65536.0f; - if (t > 1) t = 1; - temperatures[i] = t; - } -} - -BiomeArray BiomeSource::getRawBiomeBlock(int x, int z, int w, int h) const -{ - BiomeArray biomes; - getRawBiomeBlock(biomes, x, z, w, h); - return biomes; +BiomeArray BiomeSource::getRawBiomeBlock(int x, int z, int w, int h) const { + BiomeArray biomes; + getRawBiomeBlock(biomes, x, z, w, h); + return biomes; } // 4J added -void BiomeSource::getRawBiomeIndices(intArray &biomes, int x, int z, int w, int h) const -{ - IntCache::releaseAll(); +void BiomeSource::getRawBiomeIndices(intArray& biomes, int x, int z, int w, + int h) const { + IntCache::releaseAll(); - intArray result = layer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - biomes[i] = result[i]; - } + intArray result = layer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + biomes[i] = result[i]; + } } -void BiomeSource::getRawBiomeBlock(BiomeArray &biomes, int x, int z, int w, int h) const -{ - IntCache::releaseAll(); - //if (biomes == null || biomes.length < w * h) - if (biomes.data == NULL || biomes.length < w * h) - { - if(biomes.data != NULL) delete [] biomes.data; - biomes = BiomeArray(w * h); - } +void BiomeSource::getRawBiomeBlock(BiomeArray& biomes, int x, int z, int w, + int h) const { + IntCache::releaseAll(); + // if (biomes == null || biomes.length < w * h) + if (biomes.data == NULL || biomes.length < w * h) { + if (biomes.data != NULL) delete[] biomes.data; + biomes = BiomeArray(w * h); + } - intArray result = layer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - biomes[i] = Biome::biomes[result[i]]; + intArray result = layer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + biomes[i] = Biome::biomes[result[i]]; #ifndef _CONTENT_PACKAGE - if(biomes[i] == NULL) - { - app.DebugPrintf("Tried to assign null biome %d\n", result[i]); - __debugbreak(); - } + if (biomes[i] == NULL) { + app.DebugPrintf("Tried to assign null biome %d\n", result[i]); + __debugbreak(); + } #endif - } + } } - - -BiomeArray BiomeSource::getBiomeBlock(int x, int z, int w, int h) const -{ - if (w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) - { - return cache->getBiomeBlockAt(x, z); - } - BiomeArray biomes; - getBiomeBlock(biomes, x, z, w, h, true); - return biomes; +BiomeArray BiomeSource::getBiomeBlock(int x, int z, int w, int h) const { + if (w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) { + return cache->getBiomeBlockAt(x, z); + } + BiomeArray biomes; + getBiomeBlock(biomes, x, z, w, h, true); + return biomes; } // 4J - caller is responsible for deleting biomes array -void BiomeSource::getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, bool useCache) const -{ - IntCache::releaseAll(); - //if (biomes == null || biomes.length < w * h) - if (biomes.data == NULL || biomes.length < w * h) - { - if(biomes.data != NULL) delete [] biomes.data; - biomes = BiomeArray(w * h); - } +void BiomeSource::getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, + bool useCache) const { + IntCache::releaseAll(); + // if (biomes == null || biomes.length < w * h) + if (biomes.data == NULL || biomes.length < w * h) { + if (biomes.data != NULL) delete[] biomes.data; + biomes = BiomeArray(w * h); + } - if (useCache && w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) - { - BiomeArray tmp = cache->getBiomeBlockAt(x, z); - System::arraycopy(tmp, 0, &biomes, 0, w * h); - delete[] tmp.data; // MGH - added, the caching creates this array from the indices now. //4jcraft made it array delete - //return biomes; - } + if (useCache && w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) { + BiomeArray tmp = cache->getBiomeBlockAt(x, z); + System::arraycopy(tmp, 0, &biomes, 0, w * h); + delete[] tmp.data; // MGH - added, the caching creates this array from + // the indices now. //4jcraft made it array delete + // return biomes; + } - intArray result = zoomedLayer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - biomes[i] = Biome::biomes[result[i]]; - } + intArray result = zoomedLayer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + biomes[i] = Biome::biomes[result[i]]; + } } - - - -byteArray BiomeSource::getBiomeIndexBlock(int x, int z, int w, int h) const -{ - if (w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) - { - return cache->getBiomeIndexBlockAt(x, z); - } - byteArray biomeIndices; - getBiomeIndexBlock(biomeIndices, x, z, w, h, true); - return biomeIndices; +byteArray BiomeSource::getBiomeIndexBlock(int x, int z, int w, int h) const { + if (w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) { + return cache->getBiomeIndexBlockAt(x, z); + } + byteArray biomeIndices; + getBiomeIndexBlock(biomeIndices, x, z, w, h, true); + return biomeIndices; } // 4J - caller is responsible for deleting biomes array -void BiomeSource::getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, int w, int h, bool useCache) const -{ - IntCache::releaseAll(); - //if (biomes == null || biomes.length < w * h) - if (biomeIndices.data == NULL || biomeIndices.length < w * h) - { - if(biomeIndices.data != NULL) delete [] biomeIndices.data; - biomeIndices = byteArray(w * h); - } +void BiomeSource::getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, + int w, int h, bool useCache) const { + IntCache::releaseAll(); + // if (biomes == null || biomes.length < w * h) + if (biomeIndices.data == NULL || biomeIndices.length < w * h) { + if (biomeIndices.data != NULL) delete[] biomeIndices.data; + biomeIndices = byteArray(w * h); + } - if (useCache && w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) - { - byteArray tmp = cache->getBiomeIndexBlockAt(x, z); - System::arraycopy(tmp, 0, &biomeIndices, 0, w * h); - //return biomes; - } + if (useCache && w == 16 && h == 16 && (x & 0xf) == 0 && (z & 0xf) == 0) { + byteArray tmp = cache->getBiomeIndexBlockAt(x, z); + System::arraycopy(tmp, 0, &biomeIndices, 0, w * h); + // return biomes; + } - intArray result = zoomedLayer->getArea(x, z, w, h); - for (int i = 0; i < w * h; i++) - { - biomeIndices[i] = (uint8_t)result[i]; - } + intArray result = zoomedLayer->getArea(x, z, w, h); + for (int i = 0; i < w * h; i++) { + biomeIndices[i] = (uint8_t)result[i]; + } } /** -* Checks if an area around a block contains only the specified biomes. -* Useful for placing elements like towns. -* -* This is a bit of a rough check, to make it as fast as possible. To ensure -* NO other biomes, add a margin of at least four blocks to the radius -*/ -bool BiomeSource::containsOnly(int x, int z, int r, std::vector allowed) -{ - int x0 = ((x - r) >> 2); - int z0 = ((z - r) >> 2); - int x1 = ((x + r) >> 2); - int z1 = ((z + r) >> 2); + * Checks if an area around a block contains only the specified biomes. + * Useful for placing elements like towns. + * + * This is a bit of a rough check, to make it as fast as possible. To ensure + * NO other biomes, add a margin of at least four blocks to the radius + */ +bool BiomeSource::containsOnly(int x, int z, int r, + std::vector allowed) { + int x0 = ((x - r) >> 2); + int z0 = ((z - r) >> 2); + int x1 = ((x + r) >> 2); + int z1 = ((z + r) >> 2); - int w = x1 - x0 + 1; - int h = z1 - z0 + 1; + int w = x1 - x0 + 1; + int h = z1 - z0 + 1; - intArray biomes = layer->getArea(x0, z0, w, h); - for (int i = 0; i < w * h; i++) - { - Biome *b = Biome::biomes[biomes[i]]; - if (find(allowed.begin(), allowed.end(), b) == allowed.end()) return false; - } + intArray biomes = layer->getArea(x0, z0, w, h); + for (int i = 0; i < w * h; i++) { + Biome* b = Biome::biomes[biomes[i]]; + if (find(allowed.begin(), allowed.end(), b) == allowed.end()) + return false; + } - return true; + return true; } /** -* Checks if an area around a block contains only the specified biome. -* Useful for placing elements like towns. -* -* This is a bit of a rough check, to make it as fast as possible. To ensure -* NO other biomes, add a margin of at least four blocks to the radius -*/ -bool BiomeSource::containsOnly(int x, int z, int r, Biome *allowed) -{ - int x0 = ((x - r) >> 2); - int z0 = ((z - r) >> 2); - int x1 = ((x + r) >> 2); - int z1 = ((z + r) >> 2); - - int w = x1 - x0; - int h = z1 - z0; - int biomesCount = w*h; - intArray biomes = layer->getArea(x0, z0, w, h); - for (unsigned int i = 0; i < biomesCount; i++) - { - Biome *b = Biome::biomes[biomes[i]]; - if (allowed != b) return false; - } + * Checks if an area around a block contains only the specified biome. + * Useful for placing elements like towns. + * + * This is a bit of a rough check, to make it as fast as possible. To ensure + * NO other biomes, add a margin of at least four blocks to the radius + */ +bool BiomeSource::containsOnly(int x, int z, int r, Biome* allowed) { + int x0 = ((x - r) >> 2); + int z0 = ((z - r) >> 2); + int x1 = ((x + r) >> 2); + int z1 = ((z + r) >> 2); - return true; + int w = x1 - x0; + int h = z1 - z0; + int biomesCount = w * h; + intArray biomes = layer->getArea(x0, z0, w, h); + for (unsigned int i = 0; i < biomesCount; i++) { + Biome* b = Biome::biomes[biomes[i]]; + if (allowed != b) return false; + } + + return true; } /** -* Finds the specified biome within the radius. This will return a random -* position if several are found. This test is fairly rough. -* -* Returns null if the biome wasn't found -*/ -TilePos *BiomeSource::findBiome(int x, int z, int r, Biome *toFind, Random *random) -{ - int x0 = ((x - r) >> 2); - int z0 = ((z - r) >> 2); - int x1 = ((x + r) >> 2); - int z1 = ((z + r) >> 2); + * Finds the specified biome within the radius. This will return a random + * position if several are found. This test is fairly rough. + * + * Returns null if the biome wasn't found + */ +TilePos* BiomeSource::findBiome(int x, int z, int r, Biome* toFind, + Random* random) { + int x0 = ((x - r) >> 2); + int z0 = ((z - r) >> 2); + int x1 = ((x + r) >> 2); + int z1 = ((z + r) >> 2); - int w = x1 - x0 + 1; - int h = z1 - z0 + 1; - intArray biomes = layer->getArea(x0, z0, w, h); - TilePos *res = NULL; - int found = 0; - int biomesCount = w*h; - for (unsigned int i = 0; i < biomesCount; i++) - { - int xx = x0 + i % w; - int zz = z0 + i / w; - Biome *b = Biome::biomes[biomes[i]]; - if (b == toFind) - { - if (res == NULL || random->nextInt(found + 1) == 0) - { - res = new TilePos(xx, 0, zz); - found++; - } - } - } + int w = x1 - x0 + 1; + int h = z1 - z0 + 1; + intArray biomes = layer->getArea(x0, z0, w, h); + TilePos* res = NULL; + int found = 0; + int biomesCount = w * h; + for (unsigned int i = 0; i < biomesCount; i++) { + int xx = x0 + i % w; + int zz = z0 + i / w; + Biome* b = Biome::biomes[biomes[i]]; + if (b == toFind) { + if (res == NULL || random->nextInt(found + 1) == 0) { + res = new TilePos(xx, 0, zz); + found++; + } + } + } - return res; + return res; } /** -* Finds one of the specified biomes within the radius. This will return a -* random position if several are found. This test is fairly rough. -* -* Returns null if the biome wasn't found -*/ -TilePos *BiomeSource::findBiome(int x, int z, int r, std::vector allowed, Random *random) -{ - int x0 = ((x - r) >> 2); - int z0 = ((z - r) >> 2); - int x1 = ((x + r) >> 2); - int z1 = ((z + r) >> 2); + * Finds one of the specified biomes within the radius. This will return a + * random position if several are found. This test is fairly rough. + * + * Returns null if the biome wasn't found + */ +TilePos* BiomeSource::findBiome(int x, int z, int r, + std::vector allowed, Random* random) { + int x0 = ((x - r) >> 2); + int z0 = ((z - r) >> 2); + int x1 = ((x + r) >> 2); + int z1 = ((z + r) >> 2); - int w = x1 - x0 + 1; - int h = z1 - z0 + 1; - MemSect(50); - intArray biomes = layer->getArea(x0, z0, w, h); - TilePos *res = NULL; - int found = 0; - int biomesCount = w*h; - for (unsigned int i = 0; i < biomesCount; i++) - { - int xx = (x0 + i % w) << 2; - int zz = (z0 + i / w) << 2; - Biome *b = Biome::biomes[biomes[i]]; - if (find(allowed.begin(), allowed.end(), b) != allowed.end()) - { - if (res == NULL || random->nextInt(found + 1) == 0) - { - delete res; - res = new TilePos(xx, 0, zz); - found++; - } - } - } - MemSect(0); + int w = x1 - x0 + 1; + int h = z1 - z0 + 1; + MemSect(50); + intArray biomes = layer->getArea(x0, z0, w, h); + TilePos* res = NULL; + int found = 0; + int biomesCount = w * h; + for (unsigned int i = 0; i < biomesCount; i++) { + int xx = (x0 + i % w) << 2; + int zz = (z0 + i / w) << 2; + Biome* b = Biome::biomes[biomes[i]]; + if (find(allowed.begin(), allowed.end(), b) != allowed.end()) { + if (res == NULL || random->nextInt(found + 1) == 0) { + delete res; + res = new TilePos(xx, 0, zz); + found++; + } + } + } + MemSect(0); - return res; + return res; } -void BiomeSource::update() -{ - cache->update(); -} +void BiomeSource::update() { cache->update(); } -//#define DEBUG_SEEDS 50 +// #define DEBUG_SEEDS 50 // 4J added - find a seed for this biomesource that matches certain criteria #ifdef __PSVITA__ -__int64 BiomeSource::findSeed(LevelType *generator, bool* pServerRunning) // MGH - added pRunning, so we can early out of this on Vita as it can take up to 60 secs +__int64 BiomeSource::findSeed( + LevelType* generator, + bool* pServerRunning) // MGH - added pRunning, so we can early out of this + // on Vita as it can take up to 60 secs #else -__int64 BiomeSource::findSeed(LevelType *generator) +__int64 BiomeSource::findSeed(LevelType* generator) #endif { - __int64 bestSeed = 0; + __int64 bestSeed = 0; - ProgressRenderer *mcprogress = Minecraft::GetInstance()->progressRenderer; - mcprogress->progressStage(IDS_PROGRESS_NEW_WORLD_SEED); + ProgressRenderer* mcprogress = Minecraft::GetInstance()->progressRenderer; + mcprogress->progressStage(IDS_PROGRESS_NEW_WORLD_SEED); #ifndef _CONTENT_PACKAGE - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<nextLong(); - BiomeSource *biomeSource = new BiomeSource(seed,generator); + // Just keeping trying to generate seeds until we find one that + // matches our criteria + do { + __int64 seed = pr->nextLong(); + BiomeSource* biomeSource = new BiomeSource(seed, generator); - biomeSource->getRawBiomeIndices(indices, biomeOffset, biomeOffset, biomeWidth, biomeWidth); - getFracs(indices, toCompare); + biomeSource->getRawBiomeIndices( + indices, biomeOffset, biomeOffset, biomeWidth, biomeWidth); + getFracs(indices, toCompare); - matchFound = getIsMatch( toCompare ); + matchFound = getIsMatch(toCompare); - if( matchFound ) bestSeed = seed; + if (matchFound) bestSeed = seed; - delete biomeSource; - tryCount++; + delete biomeSource; + tryCount++; - mcprogress->progressStagePercentage( tryCount % 100 ); + mcprogress->progressStagePercentage(tryCount % 100); #ifdef __PSVITA__ - } while (!matchFound && *pServerRunning); + } while (!matchFound && *pServerRunning); #else - } while (!matchFound); + } while (!matchFound); #endif - // Clean up - delete pr; - delete indices.data; + // Clean up + delete pr; + delete indices.data; #ifdef DEBUG_SEEDS - app.DebugPrintf("%d: %d tries taken, seed used is %lld\n", k, tryCount, bestSeed); + app.DebugPrintf("%d: %d tries taken, seed used is %lld\n", k, + tryCount, bestSeed); - BiomeSource *biomeSource = new BiomeSource(bestSeed); - BiomeArray biomes = biomeSource->getBiomeBlock(-27 * 16, -27 * 16, 54 * 16, 54 * 16); + BiomeSource* biomeSource = new BiomeSource(bestSeed); + BiomeArray biomes = biomeSource->getBiomeBlock(-27 * 16, -27 * 16, + 54 * 16, 54 * 16); - unsigned int *pixels = new unsigned int[54 * 16 * 54 * 16]; - for(int i = 0; i < 54 * 16 * 54 * 16; i++ ) - { - int id = biomes[i]->id; + unsigned int* pixels = new unsigned int[54 * 16 * 54 * 16]; + for (int i = 0; i < 54 * 16 * 54 * 16; i++) { + int id = biomes[i]->id; - // Create following colours: - // 0 ocean 0000 black - // 1 plains 0001 pastel cyan - // 2 desert 0010 green - // 3 extreme hills 0011 yellow - // 4 forest 0100 blue - // 5 taiga 0101 magenta - // 6 swamps 0110 cyan - // 7 river 0111 white - // 8 hell 1000 grey - // 9 end biome 1001 white - // 10 frozen ocean 1010 pastel green - // 11 frozen river 1011 pastel yellow - // 12 ice flats 1100 pastel blue - // 13 ice mountains 1101 pastel magenta - // 14 mushroom island 1110 red - // 15 mushroom shore 1111 pastel red + // Create following colours: + // 0 ocean 0000 black + // 1 plains 0001 pastel cyan + // 2 desert 0010 green + // 3 extreme hills 0011 yellow + // 4 forest 0100 blue + // 5 taiga 0101 magenta + // 6 swamps 0110 cyan + // 7 river 0111 white + // 8 hell 1000 grey + // 9 end biome 1001 white + // 10 frozen ocean 1010 pastel green + // 11 frozen river 1011 pastel yellow + // 12 ice flats 1100 pastel blue + // 13 ice mountains 1101 pastel magenta + // 14 mushroom island 1110 red + // 15 mushroom shore 1111 pastel red - if( id == 1 ) id = 14; - else if ( id == 14 ) id = 1; - else if( id == 9 ) id = 15; - else if( id == 15 ) id = 9; - pixels[i] = 0xff000000; - if( id & 1 ) pixels[i] |= 0x00ff0000; - if( id & 2 ) pixels[i] |= 0x0000ff00; - if( id & 4 ) pixels[i] |= 0x000000ff; - if( id & 8 ) pixels[i] |= 0x00808080; - } - D3DXIMAGE_INFO srcInfo; - srcInfo.Format = D3DFMT_LIN_A8R8G8B8; - srcInfo.ImageFileFormat = D3DXIFF_BMP; - srcInfo.Width = 54 * 16; - srcInfo.Height = 54 * 16; + if (id == 1) + id = 14; + else if (id == 14) + id = 1; + else if (id == 9) + id = 15; + else if (id == 15) + id = 9; + pixels[i] = 0xff000000; + if (id & 1) pixels[i] |= 0x00ff0000; + if (id & 2) pixels[i] |= 0x0000ff00; + if (id & 4) pixels[i] |= 0x000000ff; + if (id & 8) pixels[i] |= 0x00808080; + } + D3DXIMAGE_INFO srcInfo; + srcInfo.Format = D3DFMT_LIN_A8R8G8B8; + srcInfo.ImageFileFormat = D3DXIFF_BMP; + srcInfo.Width = 54 * 16; + srcInfo.Height = 54 * 16; - char buf[256]; - sprintf(buf,"GAME:\\BiomeTest%d.bmp",k); - RenderManager.SaveTextureData(buf, &srcInfo, (int *)pixels); + char buf[256]; + sprintf(buf, "GAME:\\BiomeTest%d.bmp", k); + RenderManager.SaveTextureData(buf, &srcInfo, (int*)pixels); - delete [] pixels; - delete biomes.data; - delete biomeSource; + delete[] pixels; + delete biomes.data; + delete biomeSource; #endif - } - } + } + } - return bestSeed; + return bestSeed; } // 4J added - get the fractional amounts of each biome type in the given indices -void BiomeSource::getFracs(intArray indices, float *fracs) -{ - for( int i = 0; i < Biome::BIOME_COUNT; i++ ) - { - fracs[i] = 0.0f; - } +void BiomeSource::getFracs(intArray indices, float* fracs) { + for (int i = 0; i < Biome::BIOME_COUNT; i++) { + fracs[i] = 0.0f; + } - for( int i = 0; i < indices.length; i++ ) - { - fracs[indices[i]] += 1.0f; - } + for (int i = 0; i < indices.length; i++) { + fracs[indices[i]] += 1.0f; + } - for( int i = 0; i < Biome::BIOME_COUNT; i++ ) - { - fracs[i] /= (float)(indices.length); - } + for (int i = 0; i < Biome::BIOME_COUNT; i++) { + fracs[i] /= (float)(indices.length); + } } +// 4J added - determine if this particular set of fractional amounts of biome +// types matches are requirements +bool BiomeSource::getIsMatch(float* frac) { + // A true for a particular biome type here marks it as one that *has* to be + // present + static const bool critical[Biome::BIOME_COUNT] = { + true, // ocean + true, // plains + true, // desert + false, // extreme hills + true, // forest + true, // taiga + true, // swamps + false, // river + false, // hell + false, // end biome + false, // frozen ocean + false, // frozen river + false, // ice flats + false, // ice mountains + true, // mushroom island / shore + false, // mushroom shore (combined with above) + false, // beach + false, // desert hills (combined with desert) + false, // forest hills (combined with forest) + false, // taiga hills (combined with taga) + false, // small extreme hills + true, // jungle + false, // jungle hills (combined with jungle) + }; + // Don't want more than 15% ocean + if (frac[0] > 0.15f) { + return false; + } -// 4J added - determine if this particular set of fractional amounts of biome types matches are requirements -bool BiomeSource::getIsMatch(float *frac) -{ - // A true for a particular biome type here marks it as one that *has* to be present - static const bool critical[Biome::BIOME_COUNT] = { - true, // ocean - true, // plains - true, // desert - false, // extreme hills - true, // forest - true, // taiga - true, // swamps - false, // river - false, // hell - false, // end biome - false, // frozen ocean - false, // frozen river - false, // ice flats - false, // ice mountains - true, // mushroom island / shore - false, // mushroom shore (combined with above) - false, // beach - false, // desert hills (combined with desert) - false, // forest hills (combined with forest) - false, // taiga hills (combined with taga) - false, // small extreme hills - true, // jungle - false, // jungle hills (combined with jungle) - }; + // Consider mushroom shore & islands as the same by finding max + frac[14] = ((frac[15] > frac[14]) ? frac[15] : frac[14]); + // Merge desert and desert hills + frac[2] = ((frac[17] > frac[2]) ? frac[17] : frac[2]); - // Don't want more than 15% ocean - if( frac[0] > 0.15f ) - { - return false; - } + // Merge forest and forest hills + frac[4] = ((frac[18] > frac[4]) ? frac[18] : frac[4]); - // Consider mushroom shore & islands as the same by finding max - frac[14] = ( ( frac[15] > frac[14] ) ? frac[15] : frac[14] ); + // Merge taiga and taiga hills + frac[5] = ((frac[19] > frac[5]) ? frac[19] : frac[5]); - // Merge desert and desert hills - frac[2] = ( ( frac[17] > frac[2] ) ? frac[17] : frac[2] ); + // Merge jungle and jungle hills + frac[21] = ((frac[22] > frac[21]) ? frac[22] : frac[21]); - // Merge forest and forest hills - frac[4] = ( ( frac[18] > frac[4] ) ? frac[18] : frac[4] ); + // Loop through all biome types, and: + // (1) count them + // (2) give up if one of the critical ones is missing - // Merge taiga and taiga hills - frac[5] = ( ( frac[19] > frac[5] ) ? frac[19] : frac[5] ); + int typeCount = 0; + for (int i = 0; i < Biome::BIOME_COUNT; i++) { + // We want to skip some where we have merged with another type + if (i == 15 || i == 17 || i == 18 || i == 19 || i == 22) continue; - // Merge jungle and jungle hills - frac[21] = ( ( frac[22] > frac[21] ) ? frac[22] : frac[21] ); + // Consider 0.1% as being "present" - this equates an area of about 3 + // chunks + if (frac[i] > 0.001f) { + typeCount++; + } else { + // If a critical biome is missing, just give up + if (critical[i]) { + return false; + } + } + } - // Loop through all biome types, and: - // (1) count them - // (2) give up if one of the critical ones is missing - - int typeCount = 0; - for( int i = 0; i < Biome::BIOME_COUNT; i++ ) - { - // We want to skip some where we have merged with another type - if(i == 15 || i == 17 || i == 18 || i == 19 || i == 22) continue; - - // Consider 0.1% as being "present" - this equates an area of about 3 chunks - if( frac[i] > 0.001f ) - { - typeCount++; - } - else - { - // If a critical biome is missing, just give up - if( critical[i] ) - { - return false; - } - } - } - - // Consider as suitable if we've got all the critical ones, and in total 9 or more - currently there's 8 critical so this just forces at least 1 more others - return ( typeCount >= 9 ); + // Consider as suitable if we've got all the critical ones, and in total 9 + // or more - currently there's 8 critical so this just forces at least 1 + // more others + return (typeCount >= 9); } diff --git a/Minecraft.World/WorldGen/Biomes/BiomeSource.h b/Minecraft.World/WorldGen/Biomes/BiomeSource.h index a85908934..e6a7107ea 100644 --- a/Minecraft.World/WorldGen/Biomes/BiomeSource.h +++ b/Minecraft.World/WorldGen/Biomes/BiomeSource.h @@ -10,97 +10,111 @@ class Layer; class TilePos; class LevelType; -class BiomeSource -{ +class BiomeSource { private: - std::shared_ptr layer; - std::shared_ptr zoomedLayer; + std::shared_ptr layer; + std::shared_ptr zoomedLayer; + public: - static const int CACHE_DIAMETER = 256; + static const int CACHE_DIAMETER = 256; private: - BiomeCache *cache; + BiomeCache* cache; - std::vector playerSpawnBiomes; + std::vector playerSpawnBiomes; protected: - void _init(); - void _init(__int64 seed, LevelType *generator); + void _init(); + void _init(__int64 seed, LevelType* generator); BiomeSource(); public: - BiomeSource(__int64 seed, LevelType *generator); - BiomeSource(Level *level); + BiomeSource(__int64 seed, LevelType* generator); + BiomeSource(Level* level); + private: - static bool getIsMatch(float *frac); // 4J added - static void getFracs(intArray indices, float *fracs); // 4J added + static bool getIsMatch(float* frac); // 4J added + static void getFracs(intArray indices, float* fracs); // 4J added public: #ifdef __PSVITA__ - static __int64 findSeed(LevelType *generator, bool* pServerRunning); // MGH - added pRunning, so we can early out of this on Vita as it can take up to 60 secs // 4J added + static __int64 findSeed( + LevelType* generator, + bool* pServerRunning); // MGH - added pRunning, so we can early out of + // this on Vita as it can take up to 60 secs + // // 4J added #else - static __int64 findSeed(LevelType *generator); // 4J added + static __int64 findSeed(LevelType* generator); // 4J added #endif - virtual ~BiomeSource(); + virtual ~BiomeSource(); public: - std::vector getPlayerSpawnBiomes() { return playerSpawnBiomes; } - virtual Biome *getBiome(ChunkPos *cp); - virtual Biome *getBiome(int x, int z); + std::vector getPlayerSpawnBiomes() { return playerSpawnBiomes; } + virtual Biome* getBiome(ChunkPos* cp); + virtual Biome* getBiome(int x, int z); - // 4J - changed the interface for these methods, mainly for thread safety - virtual float getDownfall(int x, int z) const; + // 4J - changed the interface for these methods, mainly for thread safety + virtual float getDownfall(int x, int z) const; virtual floatArray getDownfallBlock(int x, int z, int w, int h) const; - virtual void getDownfallBlock(floatArray &downfalls, int x, int z, int w, int h) const; + virtual void getDownfallBlock(floatArray& downfalls, int x, int z, int w, + int h) const; - // 4J - changed the interface for these methods, mainly for thread safety - virtual BiomeCache::Block *getBlockAt(int x, int y); - virtual float getTemperature(int x, int y, int z) const; - float scaleTemp(float temp, int y ) const; // 4J - brought forward from 1.2.3 - virtual floatArray getTemperatureBlock(int x, int z, int w, int h) const; - virtual void getTemperatureBlock(floatArray& temperatures, int x, int z, int w, int h) const; + // 4J - changed the interface for these methods, mainly for thread safety + virtual BiomeCache::Block* getBlockAt(int x, int y); + virtual float getTemperature(int x, int y, int z) const; + float scaleTemp(float temp, + int y) const; // 4J - brought forward from 1.2.3 + virtual floatArray getTemperatureBlock(int x, int z, int w, int h) const; + virtual void getTemperatureBlock(floatArray& temperatures, int x, int z, + int w, int h) const; - virtual BiomeArray getRawBiomeBlock(int x, int z, int w, int h) const; - virtual void getRawBiomeBlock(BiomeArray &biomes, int x, int z, int w, int h) const; - virtual void getRawBiomeIndices(intArray &biomes, int x, int z, int w, int h) const; // 4J added - virtual BiomeArray getBiomeBlock(int x, int z, int w, int h) const; - virtual void getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, bool useCache) const; + virtual BiomeArray getRawBiomeBlock(int x, int z, int w, int h) const; + virtual void getRawBiomeBlock(BiomeArray& biomes, int x, int z, int w, + int h) const; + virtual void getRawBiomeIndices(intArray& biomes, int x, int z, int w, + int h) const; // 4J added + virtual BiomeArray getBiomeBlock(int x, int z, int w, int h) const; + virtual void getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, + bool useCache) const; - virtual byteArray getBiomeIndexBlock(int x, int z, int w, int h) const; - virtual void getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, int w, int h, bool useCache) const; + virtual byteArray getBiomeIndexBlock(int x, int z, int w, int h) const; + virtual void getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, + int w, int h, bool useCache) const; - /** - * Checks if an area around a block contains only the specified biomes. - * Useful for placing elements like towns. - * - * This is a bit of a rough check, to make it as fast as possible. To ensure - * NO other biomes, add a margin of at least four blocks to the radius - */ - virtual bool containsOnly(int x, int z, int r, std::vector allowed); + /** + * Checks if an area around a block contains only the specified biomes. + * Useful for placing elements like towns. + * + * This is a bit of a rough check, to make it as fast as possible. To ensure + * NO other biomes, add a margin of at least four blocks to the radius + */ + virtual bool containsOnly(int x, int z, int r, std::vector allowed); - /** - * Checks if an area around a block contains only the specified biome. - * Useful for placing elements like towns. - * - * This is a bit of a rough check, to make it as fast as possible. To ensure - * NO other biomes, add a margin of at least four blocks to the radius - */ - virtual bool containsOnly(int x, int z, int r, Biome *allowed); + /** + * Checks if an area around a block contains only the specified biome. + * Useful for placing elements like towns. + * + * This is a bit of a rough check, to make it as fast as possible. To ensure + * NO other biomes, add a margin of at least four blocks to the radius + */ + virtual bool containsOnly(int x, int z, int r, Biome* allowed); - /** - * Finds the specified biome within the radius. This will return a random - * position if several are found. This test is fairly rough. - * - * Returns null if the biome wasn't found - */ - virtual TilePos *findBiome(int x, int z, int r, Biome *toFind, Random *random); + /** + * Finds the specified biome within the radius. This will return a random + * position if several are found. This test is fairly rough. + * + * Returns null if the biome wasn't found + */ + virtual TilePos* findBiome(int x, int z, int r, Biome* toFind, + Random* random); - /** - * Finds one of the specified biomes within the radius. This will return a - * random position if several are found. This test is fairly rough. - * - * Returns null if the biome wasn't found - */ - virtual TilePos *findBiome(int x, int z, int r, std::vector allowed, Random *random); + /** + * Finds one of the specified biomes within the radius. This will return a + * random position if several are found. This test is fairly rough. + * + * Returns null if the biome wasn't found + */ + virtual TilePos* findBiome(int x, int z, int r, std::vector allowed, + Random* random); - void update(); + void update(); }; diff --git a/Minecraft.World/WorldGen/Biomes/DesertBiome.cpp b/Minecraft.World/WorldGen/Biomes/DesertBiome.cpp index 198d44406..ebf590dc4 100644 --- a/Minecraft.World/WorldGen/Biomes/DesertBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/DesertBiome.cpp @@ -4,30 +4,27 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Headers/net.minecraft.world.level.biome.h" -DesertBiome::DesertBiome(int id) : Biome(id) -{ - // remove default mob spawn settings - friendlies.clear(); - friendlies_chicken.clear(); // 4J added - friendlies_wolf.clear(); // 4J added - this->topMaterial = static_cast(Tile::sand_Id); - this->material = static_cast(Tile::sand_Id); +DesertBiome::DesertBiome(int id) : Biome(id) { + // remove default mob spawn settings + friendlies.clear(); + friendlies_chicken.clear(); // 4J added + friendlies_wolf.clear(); // 4J added + this->topMaterial = static_cast(Tile::sand_Id); + this->material = static_cast(Tile::sand_Id); - decorator->treeCount = -999; - decorator->deadBushCount = 2; - decorator->reedsCount = 50; - decorator->cactusCount = 10; + decorator->treeCount = -999; + decorator->deadBushCount = 2; + decorator->reedsCount = 50; + decorator->cactusCount = 10; } -void DesertBiome::decorate(Level *level, Random *random, int xo, int zo) -{ - Biome::decorate(level, random, xo, zo); +void DesertBiome::decorate(Level* level, Random* random, int xo, int zo) { + Biome::decorate(level, random, xo, zo); - if (random->nextInt(1000) == 0) - { - int x = xo + random->nextInt(16) + 8; - int z = zo + random->nextInt(16) + 8; - Feature *well = new DesertWellFeature(); - well->place(level, random, x, level->getHeightmap(x, z) + 1, z); - } + if (random->nextInt(1000) == 0) { + int x = xo + random->nextInt(16) + 8; + int z = zo + random->nextInt(16) + 8; + Feature* well = new DesertWellFeature(); + well->place(level, random, x, level->getHeightmap(x, z) + 1, z); + } } diff --git a/Minecraft.World/WorldGen/Biomes/DesertBiome.h b/Minecraft.World/WorldGen/Biomes/DesertBiome.h index d8fc5fb82..2fd0680e7 100644 --- a/Minecraft.World/WorldGen/Biomes/DesertBiome.h +++ b/Minecraft.World/WorldGen/Biomes/DesertBiome.h @@ -2,9 +2,8 @@ #include "Biome.h" -class DesertBiome : public Biome -{ +class DesertBiome : public Biome { public: - DesertBiome(int id); - virtual void decorate(Level *level, Random *random, int xo, int zo); + DesertBiome(int id); + virtual void decorate(Level* level, Random* random, int xo, int zo); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.cpp b/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.cpp index 368fafc00..73bd164bc 100644 --- a/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.cpp @@ -3,28 +3,21 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "ExtremeHillsBiome.h" -ExtremeHillsBiome::ExtremeHillsBiome(int id) : Biome(id) -{ - friendlies.clear(); -} - -void ExtremeHillsBiome::decorate(Level *level, Random *random, int xo, int zo) { - Biome::decorate(level, random, xo, zo); - - if (GENERATE_EMERALD_ORE) - { - int emeraldCount = 3 + random->nextInt(6); - for (int d = 0; d < emeraldCount; d++) - { - int x = xo + random->nextInt(16); - int y = random->nextInt((Level::genDepth / 4) - 4) + 4; - int z = zo + random->nextInt(16); - int tile = level->getTile(x, y, z); - if (tile == Tile::rock_Id) - { - level->setTileNoUpdate(x, y, z, Tile::emeraldOre_Id); - } - } - } - +ExtremeHillsBiome::ExtremeHillsBiome(int id) : Biome(id) { friendlies.clear(); } + +void ExtremeHillsBiome::decorate(Level* level, Random* random, int xo, int zo) { + Biome::decorate(level, random, xo, zo); + + if (GENERATE_EMERALD_ORE) { + int emeraldCount = 3 + random->nextInt(6); + for (int d = 0; d < emeraldCount; d++) { + int x = xo + random->nextInt(16); + int y = random->nextInt((Level::genDepth / 4) - 4) + 4; + int z = zo + random->nextInt(16); + int tile = level->getTile(x, y, z); + if (tile == Tile::rock_Id) { + level->setTileNoUpdate(x, y, z, Tile::emeraldOre_Id); + } + } + } } diff --git a/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.h b/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.h index faafa66e0..29bae0098 100644 --- a/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.h +++ b/Minecraft.World/WorldGen/Biomes/ExtremeHillsBiome.h @@ -2,15 +2,15 @@ #include "Biome.h" -class ExtremeHillsBiome : public Biome -{ - friend class Biome; +class ExtremeHillsBiome : public Biome { + friend class Biome; + private: - static const bool GENERATE_EMERALD_ORE = true; + static const bool GENERATE_EMERALD_ORE = true; protected: - ExtremeHillsBiome(int id); + ExtremeHillsBiome(int id); public: - void decorate(Level *level, Random *random, int xo, int zo); + void decorate(Level* level, Random* random, int xo, int zo); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.cpp b/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.cpp index ab620df42..f4db3ed11 100644 --- a/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.cpp +++ b/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.cpp @@ -2,152 +2,142 @@ #include "../../Util/Arrays.h" #include "FixedBiomeSource.h" -FixedBiomeSource::FixedBiomeSource(Biome *fixed, float temperature, float downfall) -{ - this->biome = fixed; - this->temperature = temperature; - this->downfall = downfall; +FixedBiomeSource::FixedBiomeSource(Biome* fixed, float temperature, + float downfall) { + this->biome = fixed; + this->temperature = temperature; + this->downfall = downfall; } -Biome *FixedBiomeSource::getBiome(ChunkPos *cp) -{ - return biome; +Biome* FixedBiomeSource::getBiome(ChunkPos* cp) { return biome; } + +Biome* FixedBiomeSource::getBiome(int x, int z) { return biome; } + +float FixedBiomeSource::getTemperature(int x, int z) { return temperature; } + +void FixedBiomeSource::getTemperatureBlock(floatArray& temperatures, int x, + int z, int w, int h) const { + if (temperatures.data == NULL || temperatures.length < w * h) { + if (temperatures.data != NULL) delete[] temperatures.data; + temperatures = floatArray(w * h); + } + + Arrays::fill(temperatures, 0, w * h, temperature); } -Biome *FixedBiomeSource::getBiome(int x, int z) -{ - return biome; +floatArray FixedBiomeSource::getTemperatureBlock(int x, int z, int w, + int h) const { + floatArray temps(w * h); + getTemperatureBlock(temps, x, z, w, h); + return temps; } -float FixedBiomeSource::getTemperature(int x, int z) -{ - return temperature; -} - -void FixedBiomeSource::getTemperatureBlock(floatArray& temperatures, int x, int z, int w, int h) const -{ - if (temperatures.data == NULL || temperatures.length < w * h) - { - if(temperatures.data != NULL) delete [] temperatures.data; - temperatures = floatArray(w * h); - } - - Arrays::fill(temperatures, 0, w * h, temperature); -} - -floatArray FixedBiomeSource::getTemperatureBlock(int x, int z, int w, int h) const -{ - floatArray temps(w*h); - getTemperatureBlock(temps, x, z, w, h); - return temps; -} - -// 4J - note that caller is responsible for deleting returned array. temperatures array is for output only. -void FixedBiomeSource::getTemperatureBlock(doubleArray& temperatures, int x, int z, int w, int h) const -{ +// 4J - note that caller is responsible for deleting returned array. +// temperatures array is for output only. +void FixedBiomeSource::getTemperatureBlock(doubleArray& temperatures, int x, + int z, int w, int h) const { temperatures = doubleArray(w * h); Arrays::fill(temperatures, 0, w * h, (double)temperature); } -void FixedBiomeSource::getDownfallBlock(floatArray &downfalls, int x, int z, int w, int h) const -{ - if (downfalls.data == NULL || downfalls.length < w * h) - { - if(downfalls.data != NULL) delete [] downfalls.data; - downfalls = floatArray(w * h); - } - Arrays::fill(downfalls, 0, w * h, downfall); +void FixedBiomeSource::getDownfallBlock(floatArray& downfalls, int x, int z, + int w, int h) const { + if (downfalls.data == NULL || downfalls.length < w * h) { + if (downfalls.data != NULL) delete[] downfalls.data; + downfalls = floatArray(w * h); + } + Arrays::fill(downfalls, 0, w * h, downfall); } -floatArray FixedBiomeSource::getDownfallBlock(int x, int z, int w, int h) const -{ - floatArray downfalls(w*h); - getDownfallBlock(downfalls, x, z, w, h); - return downfalls; +floatArray FixedBiomeSource::getDownfallBlock(int x, int z, int w, + int h) const { + floatArray downfalls(w * h); + getDownfallBlock(downfalls, x, z, w, h); + return downfalls; } -float FixedBiomeSource::getDownfall(int x, int z) const -{ - return downfall; +float FixedBiomeSource::getDownfall(int x, int z) const { return downfall; } + +void FixedBiomeSource::getDownfallBlock(doubleArray downfalls, int x, int z, + int w, int h) { + if (downfalls.data == NULL || downfalls.length < w * h) { + if (downfalls.data != NULL) delete[] downfalls.data; + downfalls = doubleArray(w * h); + } + Arrays::fill(downfalls, 0, w * h, (double)downfall); } -void FixedBiomeSource::getDownfallBlock(doubleArray downfalls, int x, int z, int w, int h) -{ - if (downfalls.data == NULL || downfalls.length < w * h) - { - if(downfalls.data != NULL) delete [] downfalls.data; - downfalls = doubleArray(w * h); - } - Arrays::fill(downfalls, 0, w * h, (double) downfall); +// 4J - caller is responsible for deleting biomes array, plus any optional +// arrays output if pointers are passed in (_temperatures, _downfalls) +void FixedBiomeSource::getBiomeBlock(BiomeArray& biomes, int x, int z, int w, + int h, bool useCache) const { + MemSect(36); + biomes = BiomeArray(w * h); + MemSect(0); + + Arrays::fill(biomes, 0, w * h, biome); } -// 4J - caller is responsible for deleting biomes array, plus any optional arrays output if pointers are passed in (_temperatures, _downfalls) -void FixedBiomeSource::getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, bool useCache) const -{ - MemSect(36); - biomes = BiomeArray(w * h); - MemSect(0); - - Arrays::fill(biomes, 0, w * h, biome); -} - -// 4J - caller is responsible for deleting biomes array, plus any optional arrays output if pointers are passed in (_temperatures, _downfalls) -void FixedBiomeSource::getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, int w, int h, bool useCache) const -{ - MemSect(36); - biomeIndices = byteArray(w * h); - MemSect(0); - int biomeIndex = biome->id; - Arrays::fill(biomeIndices, 0, w * h, biomeIndex); +// 4J - caller is responsible for deleting biomes array, plus any optional +// arrays output if pointers are passed in (_temperatures, _downfalls) +void FixedBiomeSource::getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, + int w, int h, bool useCache) const { + MemSect(36); + biomeIndices = byteArray(w * h); + MemSect(0); + int biomeIndex = biome->id; + Arrays::fill(biomeIndices, 0, w * h, biomeIndex); } // 4J-PB added in from beyond 1.8.2 -// 4J - caller is responsible for deleting biomes array, plus any optional arrays output if pointers are passed in (_temperatures, _downfalls) -void FixedBiomeSource::getRawBiomeBlock(BiomeArray& biomes,int x, int z, int w, int h) const -{ - MemSect(36); - biomes = BiomeArray(w * h); - MemSect(0); +// 4J - caller is responsible for deleting biomes array, plus any optional +// arrays output if pointers are passed in (_temperatures, _downfalls) +void FixedBiomeSource::getRawBiomeBlock(BiomeArray& biomes, int x, int z, int w, + int h) const { + MemSect(36); + biomes = BiomeArray(w * h); + MemSect(0); - Arrays::fill(biomes, 0, w * h, biome); + Arrays::fill(biomes, 0, w * h, biome); } // 4J-PB added in from beyond 1.8.2 -// 4J - caller is responsible for deleting biomes array, plus any optional arrays output if pointers are passed in (_temperatures, _downfalls) -BiomeArray FixedBiomeSource::getRawBiomeBlock( int x, int z, int w, int h) const -{ - BiomeArray biomes; - getRawBiomeBlock(biomes, x, z, w, h); - return biomes; +// 4J - caller is responsible for deleting biomes array, plus any optional +// arrays output if pointers are passed in (_temperatures, _downfalls) +BiomeArray FixedBiomeSource::getRawBiomeBlock(int x, int z, int w, + int h) const { + BiomeArray biomes; + getRawBiomeBlock(biomes, x, z, w, h); + return biomes; } -TilePos *FixedBiomeSource::findBiome(int x, int z, int r, Biome *toFind, Random *random) -{ - if (toFind == biome) - { - return new TilePos(x - r + random->nextInt(r * 2 + 1), 0, z - r + random->nextInt(r * 2 + 1)); - } +TilePos* FixedBiomeSource::findBiome(int x, int z, int r, Biome* toFind, + Random* random) { + if (toFind == biome) { + return new TilePos(x - r + random->nextInt(r * 2 + 1), 0, + z - r + random->nextInt(r * 2 + 1)); + } - return NULL; + return NULL; } -TilePos *FixedBiomeSource::findBiome(int x, int z, int r, std::vector allowed, Random *random) -{ - if (find(allowed.begin(), allowed.end(), biome) != allowed.end()) - { - return new TilePos(x - r + random->nextInt(r * 2 + 1), 0, z - r + random->nextInt(r * 2 + 1)); - } +TilePos* FixedBiomeSource::findBiome(int x, int z, int r, + std::vector allowed, + Random* random) { + if (find(allowed.begin(), allowed.end(), biome) != allowed.end()) { + return new TilePos(x - r + random->nextInt(r * 2 + 1), 0, + z - r + random->nextInt(r * 2 + 1)); + } - return NULL; + return NULL; } -bool FixedBiomeSource::containsOnly(int x, int z, int r, Biome *allowed) -{ - return allowed == biome; +bool FixedBiomeSource::containsOnly(int x, int z, int r, Biome* allowed) { + return allowed == biome; } -bool FixedBiomeSource::containsOnly(int x, int z, int r, std::vector allowed) -{ - return find(allowed.begin(), allowed.end(), biome) != allowed.end(); +bool FixedBiomeSource::containsOnly(int x, int z, int r, + std::vector allowed) { + return find(allowed.begin(), allowed.end(), biome) != allowed.end(); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.h b/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.h index f9e175c31..4148e3b2e 100644 --- a/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.h +++ b/Minecraft.World/WorldGen/Biomes/FixedBiomeSource.h @@ -1,37 +1,45 @@ #pragma once #include "BiomeSource.h" -class FixedBiomeSource : public BiomeSource -{ +class FixedBiomeSource : public BiomeSource { private: - Biome *biome; + Biome* biome; float temperature, downfall; public: - using BiomeSource::getTemperature; + using BiomeSource::getTemperature; - FixedBiomeSource(Biome *fixed, float temperature, float downfall); + FixedBiomeSource(Biome* fixed, float temperature, float downfall); - virtual Biome *getBiome(ChunkPos *cp); - virtual Biome *getBiome(int x, int z); + virtual Biome* getBiome(ChunkPos* cp); + virtual Biome* getBiome(int x, int z); virtual float getTemperature(int x, int z); - virtual void getTemperatureBlock(floatArray& temperatures, int x, int z, int w, int h) const; - virtual floatArray getTemperatureBlock(int x, int z, int w, int h) const; - virtual void getTemperatureBlock(doubleArray& temperatures, int x, int z, int w, int h) const; - virtual void getDownfallBlock(floatArray &downfalls, int x, int z, int w, int h) const; - virtual floatArray getDownfallBlock(int x, int z, int w, int h) const; - virtual float getDownfall(int x, int z) const; - virtual void getDownfallBlock(doubleArray downfalls, int x, int z, int w, int h); - virtual void getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, bool useCache) const; - virtual void getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, int w, int h, bool useCache) const; + virtual void getTemperatureBlock(floatArray& temperatures, int x, int z, + int w, int h) const; + virtual floatArray getTemperatureBlock(int x, int z, int w, int h) const; + virtual void getTemperatureBlock(doubleArray& temperatures, int x, int z, + int w, int h) const; + virtual void getDownfallBlock(floatArray& downfalls, int x, int z, int w, + int h) const; + virtual floatArray getDownfallBlock(int x, int z, int w, int h) const; + virtual float getDownfall(int x, int z) const; + virtual void getDownfallBlock(doubleArray downfalls, int x, int z, int w, + int h); + virtual void getBiomeBlock(BiomeArray& biomes, int x, int z, int w, int h, + bool useCache) const; + virtual void getBiomeIndexBlock(byteArray& biomeIndices, int x, int z, + int w, int h, bool useCache) const; - // 4J-PB added in from beyond 1.8.2 - virtual BiomeArray getRawBiomeBlock(int x, int z, int w, int h) const; - virtual void getRawBiomeBlock(BiomeArray &biomes, int x, int z, int w, int h) const; + // 4J-PB added in from beyond 1.8.2 + virtual BiomeArray getRawBiomeBlock(int x, int z, int w, int h) const; + virtual void getRawBiomeBlock(BiomeArray& biomes, int x, int z, int w, + int h) const; - //////////////////////////////////// - virtual TilePos *findBiome(int x, int z, int r, Biome *toFind, Random *random); - virtual TilePos *findBiome(int x, int z, int r, std::vector allowed, Random *random); - virtual bool containsOnly(int x, int z, int r, Biome *allowed); - virtual bool containsOnly(int x, int z, int r, std::vector allowed); + //////////////////////////////////// + virtual TilePos* findBiome(int x, int z, int r, Biome* toFind, + Random* random); + virtual TilePos* findBiome(int x, int z, int r, std::vector allowed, + Random* random); + virtual bool containsOnly(int x, int z, int r, Biome* allowed); + virtual bool containsOnly(int x, int z, int r, std::vector allowed); }; diff --git a/Minecraft.World/WorldGen/Biomes/ForestBiome.cpp b/Minecraft.World/WorldGen/Biomes/ForestBiome.cpp index 0390604f6..b7c1b994c 100644 --- a/Minecraft.World/WorldGen/Biomes/ForestBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/ForestBiome.cpp @@ -5,22 +5,28 @@ #include "../../Headers/net.minecraft.world.entity.h" #include "ForestBiome.h" -ForestBiome::ForestBiome(int id) : Biome(id) -{ - friendlies_wolf.push_back(new MobSpawnerData(eTYPE_WOLF, 5, 4, 4)); // 4J - moved to their own category - decorator->treeCount = 10; - decorator->grassCount = 2; +ForestBiome::ForestBiome(int id) : Biome(id) { + friendlies_wolf.push_back(new MobSpawnerData( + eTYPE_WOLF, 5, 4, 4)); // 4J - moved to their own category + decorator->treeCount = 10; + decorator->grassCount = 2; } -Feature *ForestBiome::getTreeFeature(Random *random) -{ - if (random->nextInt(5) == 0) - { - return new BirchFeature(false); // 4J used to return member birchTree, now returning newly created object so that caller can be consistently resposible for cleanup +Feature* ForestBiome::getTreeFeature(Random* random) { + if (random->nextInt(5) == 0) { + return new BirchFeature( + false); // 4J used to return member birchTree, now returning newly + // created object so that caller can be consistently + // resposible for cleanup } - if (random->nextInt(10) == 0) - { - return new BasicTree(false); // 4J used to return member fancyTree, now returning newly created object so that caller can be consistently resposible for cleanup + if (random->nextInt(10) == 0) { + return new BasicTree( + false); // 4J used to return member fancyTree, now returning newly + // created object so that caller can be consistently + // resposible for cleanup } - return new TreeFeature(false); // 4J used to return member normalTree, now returning newly created object so that caller can be consistently resposible for cleanup + return new TreeFeature( + false); // 4J used to return member normalTree, now returning newly + // created object so that caller can be consistently resposible + // for cleanup } diff --git a/Minecraft.World/WorldGen/Biomes/ForestBiome.h b/Minecraft.World/WorldGen/Biomes/ForestBiome.h index e8045bd43..310f456b2 100644 --- a/Minecraft.World/WorldGen/Biomes/ForestBiome.h +++ b/Minecraft.World/WorldGen/Biomes/ForestBiome.h @@ -1,10 +1,9 @@ #pragma once #include "Biome.h" -class ForestBiome : public Biome -{ +class ForestBiome : public Biome { public: ForestBiome(int id); - virtual Feature *getTreeFeature(Random *random); + virtual Feature* getTreeFeature(Random* random); }; diff --git a/Minecraft.World/WorldGen/Biomes/HellBiome.cpp b/Minecraft.World/WorldGen/Biomes/HellBiome.cpp index 517c092b8..c508d89b8 100644 --- a/Minecraft.World/WorldGen/Biomes/HellBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/HellBiome.cpp @@ -2,15 +2,14 @@ #include "../../Headers/net.minecraft.world.entity.monster.h" #include "HellBiome.h" -HellBiome::HellBiome(int id) : Biome(id) -{ +HellBiome::HellBiome(int id) : Biome(id) { enemies.clear(); friendlies.clear(); - friendlies_chicken.clear(); // 4J added - friendlies_wolf.clear(); // 4J added + friendlies_chicken.clear(); // 4J added + friendlies_wolf.clear(); // 4J added waterFriendlies.clear(); enemies.push_back(new MobSpawnerData(eTYPE_GHAST, 50, 4, 4)); enemies.push_back(new MobSpawnerData(eTYPE_PIGZOMBIE, 100, 4, 4)); - enemies.push_back(new MobSpawnerData(eTYPE_LAVASLIME, 1, 4, 4)); + enemies.push_back(new MobSpawnerData(eTYPE_LAVASLIME, 1, 4, 4)); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/HellBiome.h b/Minecraft.World/WorldGen/Biomes/HellBiome.h index ed51de836..b26964f84 100644 --- a/Minecraft.World/WorldGen/Biomes/HellBiome.h +++ b/Minecraft.World/WorldGen/Biomes/HellBiome.h @@ -1,8 +1,7 @@ #pragma once #include "Biome.h" -class HellBiome : public Biome -{ +class HellBiome : public Biome { public: HellBiome(int id); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/IceBiome.cpp b/Minecraft.World/WorldGen/Biomes/IceBiome.cpp index 429de82dc..c37c49f8d 100644 --- a/Minecraft.World/WorldGen/Biomes/IceBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/IceBiome.cpp @@ -1,6 +1,4 @@ #include "../../Platform/stdafx.h" #include "IceBiome.h" -IceBiome::IceBiome(int id) : Biome(id) -{ -}; \ No newline at end of file +IceBiome::IceBiome(int id) : Biome(id) {}; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/IceBiome.h b/Minecraft.World/WorldGen/Biomes/IceBiome.h index 306ba14f3..4fab90038 100644 --- a/Minecraft.World/WorldGen/Biomes/IceBiome.h +++ b/Minecraft.World/WorldGen/Biomes/IceBiome.h @@ -1,8 +1,7 @@ #pragma once #include "Biome.h" -class IceBiome : public Biome -{ +class IceBiome : public Biome { public: IceBiome(int id); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/JungleBiome.cpp b/Minecraft.World/WorldGen/Biomes/JungleBiome.cpp index 01b1081a2..ef3aaba69 100644 --- a/Minecraft.World/WorldGen/Biomes/JungleBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/JungleBiome.cpp @@ -6,58 +6,55 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "JungleBiome.h" -JungleBiome::JungleBiome(int id) : Biome(id) -{ - decorator->treeCount = 50; - decorator->grassCount = 25; - decorator->flowerCount = 4; +JungleBiome::JungleBiome(int id) : Biome(id) { + decorator->treeCount = 50; + decorator->grassCount = 25; + decorator->flowerCount = 4; - enemies.push_back(new MobSpawnerData(eTYPE_OZELOT, 2, 1, 1)); + enemies.push_back(new MobSpawnerData(eTYPE_OZELOT, 2, 1, 1)); - // make chicken a lot more common in the jungle - friendlies.push_back(new MobSpawnerData(eTYPE_CHICKEN, 10, 4, 4)); + // make chicken a lot more common in the jungle + friendlies.push_back(new MobSpawnerData(eTYPE_CHICKEN, 10, 4, 4)); } - -Feature *JungleBiome::getTreeFeature(Random *random) -{ - if (random->nextInt(10) == 0) - { - return new BasicTree(false); // 4J used to return member fancyTree, now returning newly created object so that caller can be consistently resposible for cleanup - } - if (random->nextInt(2) == 0) - { - return new GroundBushFeature(TreeTile::JUNGLE_TRUNK, LeafTile::NORMAL_LEAF); - } - if (random->nextInt(3) == 0) - { - return new MegaTreeFeature(false, 10 + random->nextInt(20), TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF); - } - return new TreeFeature(false, 4 + random->nextInt(7), TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF, true); +Feature* JungleBiome::getTreeFeature(Random* random) { + if (random->nextInt(10) == 0) { + return new BasicTree( + false); // 4J used to return member fancyTree, now returning newly + // created object so that caller can be consistently + // resposible for cleanup + } + if (random->nextInt(2) == 0) { + return new GroundBushFeature(TreeTile::JUNGLE_TRUNK, + LeafTile::NORMAL_LEAF); + } + if (random->nextInt(3) == 0) { + return new MegaTreeFeature(false, 10 + random->nextInt(20), + TreeTile::JUNGLE_TRUNK, + LeafTile::JUNGLE_LEAF); + } + return new TreeFeature(false, 4 + random->nextInt(7), + TreeTile::JUNGLE_TRUNK, LeafTile::JUNGLE_LEAF, true); } -Feature *JungleBiome::getGrassFeature(Random *random) -{ - if (random->nextInt(4) == 0) - { - return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::FERN); - } - return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::TALL_GRASS); +Feature* JungleBiome::getGrassFeature(Random* random) { + if (random->nextInt(4) == 0) { + return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::FERN); + } + return new TallGrassFeature(Tile::tallgrass_Id, TallGrass::TALL_GRASS); } -void JungleBiome::decorate(Level *level, Random *random, int xo, int zo) -{ - Biome::decorate(level, random, xo, zo); +void JungleBiome::decorate(Level* level, Random* random, int xo, int zo) { + Biome::decorate(level, random, xo, zo); - PIXBeginNamedEvent(0, "Adding vines"); - VinesFeature *vines = new VinesFeature(); + PIXBeginNamedEvent(0, "Adding vines"); + VinesFeature* vines = new VinesFeature(); - for (int i = 0; i < 50; i++) - { - int x = xo + random->nextInt(16) + 8; - int y = Level::genDepth / 2; - int z = zo + random->nextInt(16) + 8; - vines->place(level, random, x, y, z); - } - PIXEndNamedEvent(); + for (int i = 0; i < 50; i++) { + int x = xo + random->nextInt(16) + 8; + int y = Level::genDepth / 2; + int z = zo + random->nextInt(16) + 8; + vines->place(level, random, x, y, z); + } + PIXEndNamedEvent(); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/JungleBiome.h b/Minecraft.World/WorldGen/Biomes/JungleBiome.h index 115afb5d8..4b094df90 100644 --- a/Minecraft.World/WorldGen/Biomes/JungleBiome.h +++ b/Minecraft.World/WorldGen/Biomes/JungleBiome.h @@ -2,13 +2,11 @@ #include "Biome.h" -class JungleBiome : public Biome -{ +class JungleBiome : public Biome { public: - JungleBiome(int id); + JungleBiome(int id); - - Feature *getTreeFeature(Random *random); - Feature *getGrassFeature(Random *random); - void decorate(Level *level, Random *random, int xo, int zo); + Feature* getTreeFeature(Random* random); + Feature* getGrassFeature(Random* random); + void decorate(Level* level, Random* random, int xo, int zo); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.cpp b/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.cpp index 2a1317c2a..027e28bce 100644 --- a/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.cpp @@ -4,8 +4,7 @@ #include "../../Headers/net.minecraft.world.entity.animal.h" #include "../../Headers/net.minecraft.world.level.tile.h" -MushroomIslandBiome::MushroomIslandBiome(int id) : Biome(id) -{ +MushroomIslandBiome::MushroomIslandBiome(int id) : Biome(id) { decorator->treeCount = -100; decorator->flowerCount = -100; decorator->grassCount = -100; @@ -13,13 +12,14 @@ MushroomIslandBiome::MushroomIslandBiome(int id) : Biome(id) decorator->mushroomCount = 1; decorator->hugeMushrooms = 1; - topMaterial = (uint8_t) Tile::mycel_Id; + topMaterial = (uint8_t)Tile::mycel_Id; enemies.clear(); friendlies.clear(); - friendlies_chicken.clear(); // 4J added - friendlies_wolf.clear(); // 4J added + friendlies_chicken.clear(); // 4J added + friendlies_wolf.clear(); // 4J added waterFriendlies.clear(); - friendlies_mushroomcow.push_back(new MobSpawnerData(eTYPE_MUSHROOMCOW, 8, 4, 8)); // 4J moved to own category + friendlies_mushroomcow.push_back(new MobSpawnerData( + eTYPE_MUSHROOMCOW, 8, 4, 8)); // 4J moved to own category } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.h b/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.h index 41cb463cb..23c0d8e2f 100644 --- a/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.h +++ b/Minecraft.World/WorldGen/Biomes/MushroomIslandBiome.h @@ -1,8 +1,7 @@ #pragma once #include "Biome.h" -class MushroomIslandBiome : public Biome -{ +class MushroomIslandBiome : public Biome { public: MushroomIslandBiome(int id); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/OceanBiome.h b/Minecraft.World/WorldGen/Biomes/OceanBiome.h index a7faaf393..1fb3af25f 100644 --- a/Minecraft.World/WorldGen/Biomes/OceanBiome.h +++ b/Minecraft.World/WorldGen/Biomes/OceanBiome.h @@ -2,13 +2,13 @@ #include "Biome.h" -class OceanBiome : public Biome -{ +class OceanBiome : public Biome { public: - OceanBiome(int id) : Biome(id) - { - friendlies.clear(); - friendlies_chicken.clear(); // 4J added since chicken now separated from main friendlies - friendlies_wolf.clear(); // 4J added since wolf now separated from main friendlies - } + OceanBiome(int id) : Biome(id) { + friendlies.clear(); + friendlies_chicken.clear(); // 4J added since chicken now separated + // from main friendlies + friendlies_wolf + .clear(); // 4J added since wolf now separated from main friendlies + } }; diff --git a/Minecraft.World/WorldGen/Biomes/PlainsBiome.cpp b/Minecraft.World/WorldGen/Biomes/PlainsBiome.cpp index cd1a51452..feac79930 100644 --- a/Minecraft.World/WorldGen/Biomes/PlainsBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/PlainsBiome.cpp @@ -1,9 +1,8 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.biome.h" -PlainsBiome::PlainsBiome(int id) : Biome(id) -{ - decorator->treeCount = -999; - decorator->flowerCount = 4; - decorator->grassCount = 10; +PlainsBiome::PlainsBiome(int id) : Biome(id) { + decorator->treeCount = -999; + decorator->flowerCount = 4; + decorator->grassCount = 10; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/PlainsBiome.h b/Minecraft.World/WorldGen/Biomes/PlainsBiome.h index b49fd0322..90388a885 100644 --- a/Minecraft.World/WorldGen/Biomes/PlainsBiome.h +++ b/Minecraft.World/WorldGen/Biomes/PlainsBiome.h @@ -2,9 +2,9 @@ #include "Biome.h" -class PlainsBiome : public Biome -{ - friend class Biome; +class PlainsBiome : public Biome { + friend class Biome; + protected: - PlainsBiome(int id); + PlainsBiome(int id); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/RainforestBiome.cpp b/Minecraft.World/WorldGen/Biomes/RainforestBiome.cpp index eb956cdd0..dfbb9eb4a 100644 --- a/Minecraft.World/WorldGen/Biomes/RainforestBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/RainforestBiome.cpp @@ -2,14 +2,10 @@ #include "RainforestBiome.h" #include "../../Headers/net.minecraft.world.level.levelgen.feature.h" -RainforestBiome::RainforestBiome(int id) : Biome(id) -{ -} +RainforestBiome::RainforestBiome(int id) : Biome(id) {} -Feature *RainforestBiome::getTreeFeature(Random *random) -{ - if (random->nextInt(3) == 0) - { +Feature* RainforestBiome::getTreeFeature(Random* random) { + if (random->nextInt(3) == 0) { return new BasicTree(false); } return new TreeFeature(false); diff --git a/Minecraft.World/WorldGen/Biomes/RainforestBiome.h b/Minecraft.World/WorldGen/Biomes/RainforestBiome.h index 791ffcdaa..d59c01957 100644 --- a/Minecraft.World/WorldGen/Biomes/RainforestBiome.h +++ b/Minecraft.World/WorldGen/Biomes/RainforestBiome.h @@ -1,9 +1,8 @@ #pragma once #include "Biome.h" -class RainforestBiome : public Biome -{ +class RainforestBiome : public Biome { public: - RainforestBiome(int id); - virtual Feature *getTreeFeature(Random *random); + RainforestBiome(int id); + virtual Feature* getTreeFeature(Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/RiverBiome.h b/Minecraft.World/WorldGen/Biomes/RiverBiome.h index 45a6839ed..92a57b4c2 100644 --- a/Minecraft.World/WorldGen/Biomes/RiverBiome.h +++ b/Minecraft.World/WorldGen/Biomes/RiverBiome.h @@ -2,13 +2,13 @@ #include "Biome.h" -class RiverBiome : public Biome -{ +class RiverBiome : public Biome { public: - RiverBiome(int id) : Biome(id) - { - friendlies.clear(); - friendlies_chicken.clear(); // 4J added since chicken now separated from main friendlies - friendlies_wolf.clear(); // 4J added since wolf now separated from main friendlies - } + RiverBiome(int id) : Biome(id) { + friendlies.clear(); + friendlies_chicken.clear(); // 4J added since chicken now separated + // from main friendlies + friendlies_wolf + .clear(); // 4J added since wolf now separated from main friendlies + } }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/SwampBiome.cpp b/Minecraft.World/WorldGen/Biomes/SwampBiome.cpp index e7ce389db..7325f654f 100644 --- a/Minecraft.World/WorldGen/Biomes/SwampBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/SwampBiome.cpp @@ -3,27 +3,27 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../Features/SwampTreeFeature.h" -SwampBiome::SwampBiome(int id) : Biome(id) -{ - decorator->treeCount = 2; - decorator->flowerCount = -999; - decorator->deadBushCount = 1; - decorator->mushroomCount = 8; - decorator->reedsCount = 10; - decorator->clayCount = 1; - decorator->waterlilyCount = 4; - - // waterColor = 0xe0ffae; +SwampBiome::SwampBiome(int id) : Biome(id) { + decorator->treeCount = 2; + decorator->flowerCount = -999; + decorator->deadBushCount = 1; + decorator->mushroomCount = 8; + decorator->reedsCount = 10; + decorator->clayCount = 1; + decorator->waterlilyCount = 4; + + // waterColor = 0xe0ffae; } - -Feature *SwampBiome::getTreeFeature(Random *random) -{ - return new SwampTreeFeature(); // 4J used to return member swampTree, now returning newly created object so that caller can be consistently resposible for cleanup +Feature* SwampBiome::getTreeFeature(Random* random) { + return new SwampTreeFeature(); // 4J used to return member swampTree, now + // returning newly created object so that + // caller can be consistently resposible for + // cleanup } // 4J Stu - Not using these any more -//int SwampBiome::getGrassColor() +// int SwampBiome::getGrassColor() //{ // double temp = getTemperature(); // double rain = getDownfall(); @@ -31,7 +31,7 @@ Feature *SwampBiome::getTreeFeature(Random *random) // return ((GrassColor::get(temp, rain) & 0xfefefe) + 0x4e0e4e) / 2; //} // -//int SwampBiome::getFolageColor() +// int SwampBiome::getFolageColor() //{ // double temp = getTemperature(); // double rain = getDownfall(); diff --git a/Minecraft.World/WorldGen/Biomes/SwampBiome.h b/Minecraft.World/WorldGen/Biomes/SwampBiome.h index 2bcdb8ac1..2546a0944 100644 --- a/Minecraft.World/WorldGen/Biomes/SwampBiome.h +++ b/Minecraft.World/WorldGen/Biomes/SwampBiome.h @@ -2,17 +2,16 @@ #include "Biome.h" class LevelSource; -class SwampBiome : public Biome -{ - // 4J Stu - No idea why this is protected in Java -//protected: +class SwampBiome : public Biome { + // 4J Stu - No idea why this is protected in Java + // protected: public: - SwampBiome(int id); + SwampBiome(int id); public: - virtual Feature *getTreeFeature(Random *random); + virtual Feature* getTreeFeature(Random* random); - // 4J Stu - Not using these any more - //virtual int getGrassColor(); - //virtual int getFolageColor(); + // 4J Stu - Not using these any more + // virtual int getGrassColor(); + // virtual int getFolageColor(); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/TaigaBiome.cpp b/Minecraft.World/WorldGen/Biomes/TaigaBiome.cpp index 44d4c2dae..e25d5e7d1 100644 --- a/Minecraft.World/WorldGen/Biomes/TaigaBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/TaigaBiome.cpp @@ -4,19 +4,17 @@ #include "../../Headers/net.minecraft.world.level.levelgen.feature.h" #include "../../Headers/net.minecraft.world.level.biome.h" -TaigaBiome::TaigaBiome(int id) : Biome(id) -{ - friendlies_wolf.push_back(new MobSpawnerData(eTYPE_WOLF, 8, 4, 4)); // 4J - moved to their own category +TaigaBiome::TaigaBiome(int id) : Biome(id) { + friendlies_wolf.push_back(new MobSpawnerData( + eTYPE_WOLF, 8, 4, 4)); // 4J - moved to their own category decorator->treeCount = 10; decorator->grassCount = 1; } -Feature *TaigaBiome::getTreeFeature(Random *random) -{ - if (random->nextInt(3) == 0) - { - return new PineFeature(); - } - return new SpruceFeature(false); +Feature* TaigaBiome::getTreeFeature(Random* random) { + if (random->nextInt(3) == 0) { + return new PineFeature(); + } + return new SpruceFeature(false); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/TaigaBiome.h b/Minecraft.World/WorldGen/Biomes/TaigaBiome.h index 8250fab13..62c707036 100644 --- a/Minecraft.World/WorldGen/Biomes/TaigaBiome.h +++ b/Minecraft.World/WorldGen/Biomes/TaigaBiome.h @@ -1,10 +1,9 @@ #pragma once #include "Biome.h" -class TaigaBiome : public Biome -{ +class TaigaBiome : public Biome { public: - TaigaBiome(int id); + TaigaBiome(int id); - virtual Feature *getTreeFeature(Random *random); + virtual Feature* getTreeFeature(Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/TheEndBiome.cpp b/Minecraft.World/WorldGen/Biomes/TheEndBiome.cpp index b984dc8b7..b67d7a0b1 100644 --- a/Minecraft.World/WorldGen/Biomes/TheEndBiome.cpp +++ b/Minecraft.World/WorldGen/Biomes/TheEndBiome.cpp @@ -4,23 +4,22 @@ #include "../../Headers/net.minecraft.world.entity.monster.h" #include "../../Headers/net.minecraft.world.level.tile.h" -TheEndBiome::TheEndBiome(int id) : Biome(id) -{ +TheEndBiome::TheEndBiome(int id) : Biome(id) { enemies.clear(); friendlies.clear(); - friendlies_chicken.clear(); // 4J added - friendlies_wolf.clear(); // 4J added + friendlies_chicken.clear(); // 4J added + friendlies_wolf.clear(); // 4J added waterFriendlies.clear(); enemies.push_back(new MobSpawnerData(eTYPE_ENDERMAN, 10, 4, 4)); - topMaterial = (uint8_t) Tile::dirt_Id; - this->material = (uint8_t) Tile::dirt_Id; + topMaterial = (uint8_t)Tile::dirt_Id; + this->material = (uint8_t)Tile::dirt_Id; decorator = new TheEndBiomeDecorator(this); } // 4J Stu - Don't need override -//int TheEndBiome::getSkyColor(float temp) +// int TheEndBiome::getSkyColor(float temp) //{ // return 0x000000; //} \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Biomes/TheEndBiome.h b/Minecraft.World/WorldGen/Biomes/TheEndBiome.h index b3698511d..52d5a1bf0 100644 --- a/Minecraft.World/WorldGen/Biomes/TheEndBiome.h +++ b/Minecraft.World/WorldGen/Biomes/TheEndBiome.h @@ -1,11 +1,10 @@ #pragma once #include "Biome.h" -class TheEndBiome : public Biome -{ +class TheEndBiome : public Biome { public: TheEndBiome(int id); - // 4J Stu - Don't need override - //virtual int getSkyColor(float temp); + // 4J Stu - Don't need override + // virtual int getSkyColor(float temp); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/BasicTreeFeature.cpp b/Minecraft.World/WorldGen/Features/BasicTreeFeature.cpp index f8921d120..7d949b606 100644 --- a/Minecraft.World/WorldGen/Features/BasicTreeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/BasicTreeFeature.cpp @@ -3,25 +3,22 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "BasicTreeFeature.h" -uint8_t BasicTree::axisConversionArray[] = { 2, 0, 0, 1, 2, 1 }; +uint8_t BasicTree::axisConversionArray[] = {2, 0, 0, 1, 2, 1}; -BasicTree::~BasicTree() -{ - delete rnd; +BasicTree::~BasicTree() { + delete rnd; - for( int i = 0; i < foliageCoordsLength; i++ ) - { - delete [] foliageCoords[i]; - } - delete [] foliageCoords; + for (int i = 0; i < foliageCoordsLength; i++) { + delete[] foliageCoords[i]; + } + delete[] foliageCoords; } -BasicTree::BasicTree(bool doUpdate) : Feature(doUpdate) -{ - rnd = new Random(); +BasicTree::BasicTree(bool doUpdate) : Feature(doUpdate) { + rnd = new Random(); origin[0] = 0; - origin[1] = 0; - origin[2] = 0; + origin[1] = 0; + origin[2] = 0; // Field to hold the tree height. height = 0; // Other important tree information. @@ -34,26 +31,25 @@ BasicTree::BasicTree(bool doUpdate) : Feature(doUpdate) trunkWidth = 1; heightVariance = 12; foliageHeight = 4; - foliageCoords = NULL; - foliageCoordsLength = 0; + foliageCoords = NULL; + foliageCoordsLength = 0; } -void BasicTree::prepare() -{ +void BasicTree::prepare() { // Initialize the instance variables. // Populate the list of foliage cluster locations. // Designed to be overridden in child classes to change basic // tree properties (trunk width, branch angle, foliage density, etc..). - trunkHeight = (int) (height * trunkHeightScale); + trunkHeight = (int)(height * trunkHeightScale); if (trunkHeight >= height) trunkHeight = height - 1; - int clustersPerY = (int) (1.382 + pow(foliageDensity * height / 13.0, 2)); + int clustersPerY = (int)(1.382 + pow(foliageDensity * height / 13.0, 2)); if (clustersPerY < 1) clustersPerY = 1; - // The foliage coordinates are a list of [x,y,z,y of branch base] values for each cluster - int **tempFoliageCoords = new int *[clustersPerY * height]; - for( int i = 0; i < clustersPerY * height; i++ ) - { - tempFoliageCoords[i] = new int[4]; - } + // The foliage coordinates are a list of [x,y,z,y of branch base] values for + // each cluster + int** tempFoliageCoords = new int*[clustersPerY * height]; + for (int i = 0; i < clustersPerY * height; i++) { + tempFoliageCoords[i] = new int[4]; + } int y = origin[1] + height - foliageHeight; int clusterCount = 1; int trunkTop = origin[1] + trunkHeight; @@ -65,13 +61,11 @@ void BasicTree::prepare() tempFoliageCoords[0][3] = trunkTop; y--; - while (relativeY >= 0) - { + while (relativeY >= 0) { int num = 0; float shapefac = treeShape(relativeY); - if (shapefac < 0) - { + if (shapefac < 0) { y--; relativeY--; continue; @@ -79,32 +73,30 @@ void BasicTree::prepare() // The originOffset is to put the value in the middle of the block. double originOffset = 0.5; - while (num < clustersPerY) - { - double radius = widthScale * (shapefac * (rnd->nextFloat() + 0.328)); + while (num < clustersPerY) { + double radius = + widthScale * (shapefac * (rnd->nextFloat() + 0.328)); double angle = rnd->nextFloat() * 2.0 * 3.14159; int x = Mth::floor(radius * sin(angle) + origin[0] + originOffset); int z = Mth::floor(radius * cos(angle) + origin[2] + originOffset); - int checkStart[] = { x, y, z }; - int checkEnd[] = { x, y + foliageHeight, z }; + int checkStart[] = {x, y, z}; + int checkEnd[] = {x, y + foliageHeight, z}; // check the center column of the cluster for obstructions. if (checkLine(checkStart, checkEnd) == -1) { // If the cluster can be created, check the branch path // for obstructions. - int checkBranchBase[] = { origin[0], origin[1], origin[2] }; - double distance = sqrt(pow(abs(origin[0] - checkStart[0]), 2.0) + pow(abs(origin[2] - checkStart[2]), 2.0)); + int checkBranchBase[] = {origin[0], origin[1], origin[2]}; + double distance = + sqrt(pow(abs(origin[0] - checkStart[0]), 2.0) + + pow(abs(origin[2] - checkStart[2]), 2.0)); double branchHeight = distance * branchSlope; - if ((checkStart[1] - branchHeight) > trunkTop) - { + if ((checkStart[1] - branchHeight) > trunkTop) { checkBranchBase[1] = trunkTop; - } - else - { - checkBranchBase[1] = (int) (checkStart[1] - branchHeight); + } else { + checkBranchBase[1] = (int)(checkStart[1] - branchHeight); } // Now check the branch path - if (checkLine(checkBranchBase, checkStart) == -1) - { + if (checkLine(checkBranchBase, checkStart) == -1) { // If the branch path is clear, add the position to the list // of foliage positions tempFoliageCoords[clusterCount][0] = x; @@ -119,24 +111,25 @@ void BasicTree::prepare() y--; relativeY--; } - // 4J Stu - Rather than copying the array, we are storing the number of valid elements in the array - foliageCoordsLength = clusterCount; - foliageCoords = tempFoliageCoords; - // Delete the rest of the array whilst we still know how big it was - for( int i = clusterCount; i < clustersPerY * height; i++ ) - { - delete [] tempFoliageCoords[i]; - tempFoliageCoords[i] = NULL; - } - // 4J - original code for above is the following, it isn't obvious to me why it is doing a copy of the array, so let's not for now -// foliageCoords = new int[clusterCount][4]; -// System.arraycopy(tempFoliageCoords, 0, foliageCoords, 0, clusterCount); - + // 4J Stu - Rather than copying the array, we are storing the number of + // valid elements in the array + foliageCoordsLength = clusterCount; + foliageCoords = tempFoliageCoords; + // Delete the rest of the array whilst we still know how big it was + for (int i = clusterCount; i < clustersPerY * height; i++) { + delete[] tempFoliageCoords[i]; + tempFoliageCoords[i] = NULL; + } + // 4J - original code for above is the following, it isn't obvious to me why + // it is doing a copy of the array, so let's not for now + // foliageCoords = new int[clusterCount][4]; + // System.arraycopy(tempFoliageCoords, 0, foliageCoords, 0, + // clusterCount); } -void BasicTree::crossection(int x, int y, int z, float radius, uint8_t direction, int material) -{ - PIXBeginNamedEvent(0, "BasicTree crossection"); +void BasicTree::crossection(int x, int y, int z, float radius, + uint8_t direction, int material) { + PIXBeginNamedEvent(0, "BasicTree crossection"); // Create a circular cross section. // // Used to nearly everything in the foliage, branches, and trunk. @@ -145,116 +138,115 @@ void BasicTree::crossection(int x, int y, int z, float radius, uint8_t direction // Passed values: // x,y,z is the center location of the cross section // radius is the radius of the section from the center - // direction is the direction the cross section is pointed, 0 for x, 1 for y, 2 for z - // material is the index number for the material to use - int rad = (int) (radius + 0.618); + // direction is the direction the cross section is pointed, 0 for x, 1 for + // y, 2 for z material is the index number for the material to use + int rad = (int)(radius + 0.618); uint8_t secidx1 = axisConversionArray[direction]; uint8_t secidx2 = axisConversionArray[direction + 3]; - int center[] = { x, y, z }; - int position[] = { 0, 0, 0 }; + int center[] = {x, y, z}; + int position[] = {0, 0, 0}; int offset1 = -rad; int offset2 = -rad; int thismat; position[direction] = center[direction]; - while (offset1 <= rad) - { + while (offset1 <= rad) { position[secidx1] = center[secidx1] + offset1; offset2 = -rad; - while (offset2 <= rad) - { - double thisdistance = pow(abs(offset1) + 0.5, 2) + pow(abs(offset2) + 0.5, 2); - if (thisdistance > radius * radius) - { + while (offset2 <= rad) { + double thisdistance = + pow(abs(offset1) + 0.5, 2) + pow(abs(offset2) + 0.5, 2); + if (thisdistance > radius * radius) { offset2++; continue; } position[secidx2] = center[secidx2] + offset2; - PIXBeginNamedEvent(0,"BasicTree getting tile"); + PIXBeginNamedEvent(0, "BasicTree getting tile"); thismat = thisLevel->getTile(position[0], position[1], position[2]); - PIXEndNamedEvent(); - if (!((thismat == 0) || (thismat == Tile::leaves_Id))) - { + PIXEndNamedEvent(); + if (!((thismat == 0) || (thismat == Tile::leaves_Id))) { // If the material of the checked block is anything other than // air or foliage, skip this tile. offset2++; continue; } - PIXBeginNamedEvent(0,"BasicTree placing block"); - placeBlock(thisLevel, position[0], position[1], position[2], material, 0); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "BasicTree placing block"); + placeBlock(thisLevel, position[0], position[1], position[2], + material, 0); + PIXEndNamedEvent(); offset2++; } offset1++; } - PIXEndNamedEvent(); + PIXEndNamedEvent(); } -float BasicTree::treeShape(int y) -{ +float BasicTree::treeShape(int y) { // Take the y position relative to the base of the tree. // Return the distance the foliage should be from the trunk axis. // Return a negative number if foliage should not be created at this height. // This method is intended for overriding in child classes, allowing // different shaped trees. - // This method should return a consistent value for each y (don't randomize). - if (y < (((float) height) * 0.3)) return (float) -1.618; - float radius = ((float) height) / ((float) 2.0); - float adjacent = (((float) height) / ((float) 2.0)) - y; + // This method should return a consistent value for each y (don't + // randomize). + if (y < (((float)height) * 0.3)) return (float)-1.618; + float radius = ((float)height) / ((float)2.0); + float adjacent = (((float)height) / ((float)2.0)) - y; float distance; - if (adjacent == 0) distance = radius; - else if (abs(adjacent) >= radius) distance = (float) 0.0; - else distance = (float) sqrt(pow(abs(radius), 2) - pow(abs(adjacent), 2)); + if (adjacent == 0) + distance = radius; + else if (abs(adjacent) >= radius) + distance = (float)0.0; + else + distance = (float)sqrt(pow(abs(radius), 2) - pow(abs(adjacent), 2)); // Alter this factor to change the overall width of the tree. - distance *= (float) 0.5; + distance *= (float)0.5; return distance; } -float BasicTree::foliageShape(int y) -{ +float BasicTree::foliageShape(int y) { // Take the y position relative to the base of the foliage cluster. // Return the radius of the cluster at this y // Return a negative number if no foliage should be created at this level // this method is intended for overriding in child classes, allowing // foliage of different sizes and shapes. - if ((y < 0) || (y >= foliageHeight)) return (float) -1; - else if ((y == 0) || (y == (foliageHeight - 1))) return (float) 2; - else return (float) 3; + if ((y < 0) || (y >= foliageHeight)) + return (float)-1; + else if ((y == 0) || (y == (foliageHeight - 1))) + return (float)2; + else + return (float)3; } -void BasicTree::foliageCluster(int x, int y, int z) -{ - PIXBeginNamedEvent(0,"BasicTree foliageCluster"); +void BasicTree::foliageCluster(int x, int y, int z) { + PIXBeginNamedEvent(0, "BasicTree foliageCluster"); // Generate a cluster of foliage, with the base at x, y, z. // The shape of the cluster is derived from foliageShape // crossection is called to make each level. int topy = y + foliageHeight; int cury = topy - 1; float radius; - // 4J Stu - Generate foliage from the top down so that we don't keep recalculating heightmaps - while (cury >= y) - { + // 4J Stu - Generate foliage from the top down so that we don't keep + // recalculating heightmaps + while (cury >= y) { radius = foliageShape(cury - y); - crossection(x, cury, z, radius, (uint8_t) 1, Tile::leaves_Id); + crossection(x, cury, z, radius, (uint8_t)1, Tile::leaves_Id); cury--; } - PIXEndNamedEvent(); + PIXEndNamedEvent(); } -void BasicTree::limb(int *start, int *end, int material) -{ +void BasicTree::limb(int* start, int* end, int material) { // Create a limb from the start position to the end position. // Used for creating the branches and trunk. // Populate delta, the difference between start and end for all three axies. // Set primidx to the index with the largest overall distance traveled. - int delta[] = { 0, 0, 0 }; + int delta[] = {0, 0, 0}; uint8_t idx = 0; uint8_t primidx = 0; - while (idx < 3) - { + while (idx < 3) { delta[idx] = end[idx] - start[idx]; - if (abs(delta[idx]) > abs(delta[primidx])) - { + if (abs(delta[idx]) > abs(delta[primidx])) { primidx = idx; } idx++; @@ -267,51 +259,49 @@ void BasicTree::limb(int *start, int *end, int material) // primsign is digit 1 or -1 depending on whether the limb is headed // along the positive or negative primidx axis. char primsign; - if (delta[primidx] > 0) primsign = 1; - else primsign = -1; + if (delta[primidx] > 0) + primsign = 1; + else + primsign = -1; // Initilize the per-step movement for the non-primary axies. - double secfac1 = ((double) delta[secidx1]) / ((double) delta[primidx]); - double secfac2 = ((double) delta[secidx2]) / ((double) delta[primidx]); + double secfac1 = ((double)delta[secidx1]) / ((double)delta[primidx]); + double secfac2 = ((double)delta[secidx2]) / ((double)delta[primidx]); // Initialize the coordinates. - int coordinate[] = { 0, 0, 0 }; + int coordinate[] = {0, 0, 0}; // Loop through each crossection along the primary axis, from start to end int primoffset = 0; int endoffset = delta[primidx] + primsign; - while (primoffset != endoffset) - { + while (primoffset != endoffset) { coordinate[primidx] = Mth::floor(start[primidx] + primoffset + 0.5); - coordinate[secidx1] = Mth::floor(start[secidx1] + (primoffset * secfac1) + 0.5); - coordinate[secidx2] = Mth::floor(start[secidx2] + (primoffset * secfac2) + 0.5); + coordinate[secidx1] = + Mth::floor(start[secidx1] + (primoffset * secfac1) + 0.5); + coordinate[secidx2] = + Mth::floor(start[secidx2] + (primoffset * secfac2) + 0.5); - int dir = TreeTile::FACING_Y; - int xdiff = abs(coordinate[0] - start[0]); - int zdiff = abs(coordinate[2] - start[2]); - int maxdiff = std::max(xdiff, zdiff); + int dir = TreeTile::FACING_Y; + int xdiff = abs(coordinate[0] - start[0]); + int zdiff = abs(coordinate[2] - start[2]); + int maxdiff = std::max(xdiff, zdiff); - if (maxdiff > 0) - { - if (xdiff == maxdiff) - { - dir = TreeTile::FACING_X; - } - else if (zdiff == maxdiff) - { - dir = TreeTile::FACING_Z; - } - } - placeBlock(thisLevel, coordinate[0], coordinate[1], coordinate[2], material, dir); + if (maxdiff > 0) { + if (xdiff == maxdiff) { + dir = TreeTile::FACING_X; + } else if (zdiff == maxdiff) { + dir = TreeTile::FACING_Z; + } + } + placeBlock(thisLevel, coordinate[0], coordinate[1], coordinate[2], + material, dir); primoffset += primsign; } } -void BasicTree::makeFoliage() -{ +void BasicTree::makeFoliage() { // Create the tree foliage. // Call foliageCluster at the correct locations int idx = 0; int finish = foliageCoordsLength; - while (idx < finish) - { + while (idx < finish) { int x = foliageCoords[idx][0]; int y = foliageCoords[idx][1]; int z = foliageCoords[idx][2]; @@ -320,8 +310,7 @@ void BasicTree::makeFoliage() } } -bool BasicTree::trimBranches(int localY) -{ +bool BasicTree::trimBranches(int localY) { // For larger trees, randomly "prune" the branches so there // aren't too many. // Return true if the branch should be created. @@ -329,22 +318,22 @@ bool BasicTree::trimBranches(int localY) // decent amounts of branches on very large trees. // Can also be used to disable branches on some tree types, or // make branches more sparse. - if (localY < (height * 0.2)) return false; - else return true; + if (localY < (height * 0.2)) + return false; + else + return true; } -void BasicTree::makeTrunk() -{ +void BasicTree::makeTrunk() { // Create the trunk of the tree. int x = origin[0]; int startY = origin[1]; int topY = origin[1] + trunkHeight; int z = origin[2]; - int startCoord[] = { x, startY, z }; - int endCoord[] = { x, topY, z }; + int startCoord[] = {x, startY, z}; + int endCoord[] = {x, topY, z}; limb(startCoord, endCoord, Tile::treeTrunk_Id); - if (trunkWidth == 2) - { + if (trunkWidth == 2) { startCoord[0] += 1; endCoord[0] += 1; limb(startCoord, endCoord, Tile::treeTrunk_Id); @@ -357,45 +346,38 @@ void BasicTree::makeTrunk() } } -void BasicTree::makeBranches() -{ +void BasicTree::makeBranches() { // Create the tree branches. // Call trimBranches for each branch to see if you should create it. // Call taperedLimb to the correct locations int idx = 0; int finish = foliageCoordsLength; - int baseCoord[] = { origin[0], origin[1], origin[2] }; - while (idx < finish) - { - int *coordValues = foliageCoords[idx]; - int endCoord[] = { coordValues[0], coordValues[1], coordValues[2] }; + int baseCoord[] = {origin[0], origin[1], origin[2]}; + while (idx < finish) { + int* coordValues = foliageCoords[idx]; + int endCoord[] = {coordValues[0], coordValues[1], coordValues[2]}; baseCoord[1] = coordValues[3]; int localY = baseCoord[1] - origin[1]; - if (trimBranches(localY)) - { + if (trimBranches(localY)) { limb(baseCoord, endCoord, Tile::treeTrunk_Id); } idx++; } } -int BasicTree::checkLine(int *start, int *end) -{ - // Check from coordinates start to end (both inclusive) for blocks other than air and foliage - // If a block other than air and foliage is found, return the number of steps taken. - // If no block other than air and foliage is found, return -1. - // Examples: - // If the third block searched is stone, return 2 - // If the first block searched is lava, return 0 +int BasicTree::checkLine(int* start, int* end) { + // Check from coordinates start to end (both inclusive) for blocks other + // than air and foliage If a block other than air and foliage is found, + // return the number of steps taken. If no block other than air and foliage + // is found, return -1. Examples: If the third block searched is stone, + // return 2 If the first block searched is lava, return 0 - int delta[] = { 0, 0, 0 }; + int delta[] = {0, 0, 0}; uint8_t idx = 0; uint8_t primidx = 0; - while (idx < 3) - { + while (idx < 3) { delta[idx] = end[idx] - start[idx]; - if (abs(delta[idx]) > abs(delta[primidx])) - { + if (abs(delta[idx]) > abs(delta[primidx])) { primidx = idx; } idx++; @@ -407,26 +389,31 @@ int BasicTree::checkLine(int *start, int *end) uint8_t secidx2 = axisConversionArray[primidx + 3]; // primsign is digit 1 or -1 depending on whether the limb is headed // along the positive or negative primidx axis. - char primsign; // 4J Stu - Was byte, but we use in a sum below and byte=unsigned char so we were setting endoffset incorrectly - if (delta[primidx] > 0) primsign = 1; - else primsign = -1; + char primsign; // 4J Stu - Was byte, but we use in a sum below and + // byte=unsigned char so we were setting endoffset + // incorrectly + if (delta[primidx] > 0) + primsign = 1; + else + primsign = -1; // Initilize the per-step movement for the non-primary axies. - double secfac1 = ((double) delta[secidx1]) / ((double) delta[primidx]); - double secfac2 = ((double) delta[secidx2]) / ((double) delta[primidx]); + double secfac1 = ((double)delta[secidx1]) / ((double)delta[primidx]); + double secfac2 = ((double)delta[secidx2]) / ((double)delta[primidx]); // Initialize the coordinates. - int coordinate[] = { 0, 0, 0 }; + int coordinate[] = {0, 0, 0}; // Loop through each crossection along the primary axis, from start to end int primoffset = 0; int endoffset = delta[primidx] + primsign; int thismat; - while (primoffset != endoffset) - { + while (primoffset != endoffset) { coordinate[primidx] = start[primidx] + primoffset; - coordinate[secidx1] = Mth::floor(start[secidx1] + (primoffset * secfac1)); - coordinate[secidx2] = Mth::floor(start[secidx2] + (primoffset * secfac2)); - thismat = thisLevel->getTile(coordinate[0], coordinate[1], coordinate[2]); - if (!((thismat == 0) || (thismat == Tile::leaves_Id))) - { + coordinate[secidx1] = + Mth::floor(start[secidx1] + (primoffset * secfac1)); + coordinate[secidx2] = + Mth::floor(start[secidx2] + (primoffset * secfac2)); + thismat = + thisLevel->getTile(coordinate[0], coordinate[1], coordinate[2]); + if (!((thismat == 0) || (thismat == Tile::leaves_Id))) { // If the material of the checked block is anything other than // air or foliage, stop looking. break; @@ -434,19 +421,16 @@ int BasicTree::checkLine(int *start, int *end) primoffset += primsign; } // If you reached the end without finding anything, return -1. - if (primoffset == endoffset) - { + if (primoffset == endoffset) { return -1; } // Otherwise, return the number of steps you took. - else - { + else { return abs(primoffset); } } -bool BasicTree::checkLocation() -{ +bool BasicTree::checkLocation() { // Return true if the tree can be placed here. // Return false if the tree can not be placed here. @@ -456,71 +440,71 @@ bool BasicTree::checkLocation() // If the checked height is shorter than height, but taller // than 4, set the tree to the maximum height allowed. // If the space is too short, return false. - int startPosition[] = { origin[0], origin[1], origin[2] }; - int endPosition[] = { origin[0], origin[1] + height - 1, origin[2] }; + int startPosition[] = {origin[0], origin[1], origin[2]}; + int endPosition[] = {origin[0], origin[1] + height - 1, origin[2]}; - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(startPosition[0], startPosition[1], startPosition[2], endPosition[0], endPosition[1], endPosition[2]); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + startPosition[0], startPosition[1], startPosition[2], + endPosition[0], endPosition[1], endPosition[2]); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } // Check the location it is resting on int baseMaterial = thisLevel->getTile(origin[0], origin[1] - 1, origin[2]); - if (!((baseMaterial == 2) || (baseMaterial == 3))) - { + if (!((baseMaterial == 2) || (baseMaterial == 3))) { return false; } int allowedHeight = checkLine(startPosition, endPosition); // If the set height is good, go with that - if (allowedHeight == -1) - { + if (allowedHeight == -1) { return true; } // If the space is too short, tell the build to abort - else if (allowedHeight < 6) - { + else if (allowedHeight < 6) { return false; } // If the space is shorter than the set height, but not too short // shorten the height, and tell the build to continue - else - { + else { height = allowedHeight; - //System.out.println("Shortened the tree"); + // System.out.println("Shortened the tree"); return true; } } -void BasicTree::init(double heightInit, double widthInit, double foliageDensityInit) -{ +void BasicTree::init(double heightInit, double widthInit, + double foliageDensityInit) { // all of the parameters should be from 0.0 to 1.0 - // heightInit scales the maximum overall height of the tree (still randomizes height within the possible range) - // widthInit scales the maximum overall width of the tree (keep this above 0.3 or so) - // foliageDensityInit scales how many foliage clusters are created. + // heightInit scales the maximum overall height of the tree (still + // randomizes height within the possible range) widthInit scales the maximum + // overall width of the tree (keep this above 0.3 or so) foliageDensityInit + // scales how many foliage clusters are created. // // Note, you can call "place" without calling "init". // This is the same as calling init(1.0,1.0,1.0) and then calling place. - heightVariance = (int) (heightInit * 12); + heightVariance = (int)(heightInit * 12); if (heightInit > 0.5) foliageHeight = 5; widthScale = widthInit; foliageDensity = foliageDensityInit; } -bool BasicTree::place(Level *level, Random *random, int x, int y, int z) -{ +bool BasicTree::place(Level* level, Random* random, int x, int y, int z) { // Note to Markus. // currently the following fields are set randomly. If you like, make them // parameters passed into "place". // - // height: so the map generator can intelligently set the height of the tree, - // and make forests with large trees in the middle and smaller ones on the edges. + // height: so the map generator can intelligently set the height of the + // tree, and make forests with large trees in the middle and smaller ones on + // the edges. // Initialize the instance fields for the level and the seed. thisLevel = level; @@ -531,35 +515,33 @@ bool BasicTree::place(Level *level, Random *random, int x, int y, int z) origin[1] = y; origin[2] = z; // Sets the height. Take out this line if height is passed as a parameter - if (height == 0) - { + if (height == 0) { height = 5 + rnd->nextInt(heightVariance); } - if (!(checkLocation())) - { - //System.out.println("Tree location failed"); + if (!(checkLocation())) { + // System.out.println("Tree location failed"); return false; } - PIXBeginNamedEvent(0, "Placing BasicTree"); - //System.out.println("The height is"); - //System.out.println(height); - //System.out.println("Trunk Height check done"); - PIXBeginNamedEvent(0, "Preparing tree"); + PIXBeginNamedEvent(0, "Placing BasicTree"); + // System.out.println("The height is"); + // System.out.println(height); + // System.out.println("Trunk Height check done"); + PIXBeginNamedEvent(0, "Preparing tree"); prepare(); - PIXEndNamedEvent(); - //System.out.println("Prepare done"); - PIXBeginNamedEvent(0, "Making foliage"); + PIXEndNamedEvent(); + // System.out.println("Prepare done"); + PIXBeginNamedEvent(0, "Making foliage"); makeFoliage(); - PIXEndNamedEvent(); - //System.out.println("Foliage done"); - PIXBeginNamedEvent(0, "Making trunk"); + PIXEndNamedEvent(); + // System.out.println("Foliage done"); + PIXBeginNamedEvent(0, "Making trunk"); makeTrunk(); - PIXEndNamedEvent(); - //System.out.println("Trunk done"); - PIXBeginNamedEvent(0, "Making branches"); + PIXEndNamedEvent(); + // System.out.println("Trunk done"); + PIXBeginNamedEvent(0, "Making branches"); makeBranches(); - PIXEndNamedEvent(); - //System.out.println("Branches done"); - PIXEndNamedEvent(); + PIXEndNamedEvent(); + // System.out.println("Branches done"); + PIXEndNamedEvent(); return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/BasicTreeFeature.h b/Minecraft.World/WorldGen/Features/BasicTreeFeature.h index 7bc085270..f69426bd2 100644 --- a/Minecraft.World/WorldGen/Features/BasicTreeFeature.h +++ b/Minecraft.World/WorldGen/Features/BasicTreeFeature.h @@ -3,8 +3,7 @@ class Level; -class BasicTree : public Feature -{ +class BasicTree : public Feature { private: // The axisConversionArray, when given a primary index, allows easy // access to the indices of the other two axies. Access the data at the @@ -26,10 +25,10 @@ private: static uint8_t axisConversionArray[]; // Set up the pseudorandom number generator - Random *rnd; + Random* rnd; // Make fields to hold the level data and the random seed - Level *thisLevel; + Level* thisLevel; // Field to hold the tree origin, x y and z. int origin[3]; @@ -45,26 +44,29 @@ private: int trunkWidth; int heightVariance; int foliageHeight; - // The foliage coordinates are a list of [x,y,z,y of branch base] values for each cluster - int **foliageCoords; - int foliageCoordsLength; - void prepare(); - void crossection(int x, int y, int z, float radius, uint8_t direction, int material); - float treeShape(int y); - float foliageShape(int y); - void foliageCluster(int x, int y, int z); - void limb(int *start, int *end, int material); - void makeFoliage(); - bool trimBranches(int localY); - void makeTrunk(); - void makeBranches(); - int checkLine(int *start, int *end); - bool checkLocation(); + // The foliage coordinates are a list of [x,y,z,y of branch base] values for + // each cluster + int** foliageCoords; + int foliageCoordsLength; + void prepare(); + void crossection(int x, int y, int z, float radius, uint8_t direction, + int material); + float treeShape(int y); + float foliageShape(int y); + void foliageCluster(int x, int y, int z); + void limb(int* start, int* end, int material); + void makeFoliage(); + bool trimBranches(int localY); + void makeTrunk(); + void makeBranches(); + int checkLine(int* start, int* end); + bool checkLocation(); public: - BasicTree(bool doUpdate); - virtual ~BasicTree(); + BasicTree(bool doUpdate); + virtual ~BasicTree(); - virtual void init(double heightInit, double widthInit, double foliageDensityInit); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual void init(double heightInit, double widthInit, + double foliageDensityInit); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/BirchFeature.cpp b/Minecraft.World/WorldGen/Features/BirchFeature.cpp index bff988ef2..2d2f34ce1 100644 --- a/Minecraft.World/WorldGen/Features/BirchFeature.cpp +++ b/Minecraft.World/WorldGen/Features/BirchFeature.cpp @@ -3,33 +3,24 @@ #include "BirchFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -BirchFeature::BirchFeature(bool doUpdate) : Feature(doUpdate) -{ -} +BirchFeature::BirchFeature(bool doUpdate) : Feature(doUpdate) {} -bool BirchFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool BirchFeature::place(Level* level, Random* random, int x, int y, int z) { int treeHeight = random->nextInt(3) + 5; bool free = true; if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) return false; - for (int yy = y; yy <= y + 1 + treeHeight; yy++) - { + for (int yy = y; yy <= y + 1 + treeHeight; yy++) { int r = 1; if (yy == y) r = 0; if (yy >= y + 1 + treeHeight - 2) r = 2; - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::maxBuildHeight) - { + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::maxBuildHeight) { int tt = level->getTile(xx, yy, zz); if (tt != 0 && tt != Tile::leaves_Id) free = false; - } - else - { + } else { free = false; } } @@ -39,43 +30,49 @@ bool BirchFeature::place(Level *level, Random *random, int x, int y, int z) if (!free) return false; int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::maxBuildHeight - treeHeight - 1) return false; + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::maxBuildHeight - treeHeight - 1) + return false; - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - int radius = 3; - bool intersects = levelGenOptions->checkIntersects(x - radius, y - 1, z - radius, x + radius, y + treeHeight, z + radius); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + int radius = 3; + bool intersects = levelGenOptions->checkIntersects( + x - radius, y - 1, z - radius, x + radius, y + treeHeight, + z + radius); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } level->setTileNoUpdate(x, y - 1, z, Tile::dirt_Id); - for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) - { + for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) { int yo = yy - (y + treeHeight); int offs = 1 - yo / 2; - for (int xx = x - offs; xx <= x + offs; xx++) - { + for (int xx = x - offs; xx <= x + offs; xx++) { int xo = xx - (x); - for (int zz = z - offs; zz <= z + offs; zz++) - { + for (int zz = z - offs; zz <= z + offs; zz++) { int zo = zz - (z); - if (abs(xo) == offs && abs(zo) == offs && (random->nextInt(2) == 0 || yo == 0)) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id, LeafTile::BIRCH_LEAF); + if (abs(xo) == offs && abs(zo) == offs && + (random->nextInt(2) == 0 || yo == 0)) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id, + LeafTile::BIRCH_LEAF); } } } - for (int hh = 0; hh < treeHeight; hh++) - { + for (int hh = 0; hh < treeHeight; hh++) { int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, TreeTile::BIRCH_TRUNK); + if (t == 0 || t == Tile::leaves_Id) + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, + TreeTile::BIRCH_TRUNK); } return true; - } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/BirchFeature.h b/Minecraft.World/WorldGen/Features/BirchFeature.h index 6fabd1226..2c3d6887b 100644 --- a/Minecraft.World/WorldGen/Features/BirchFeature.h +++ b/Minecraft.World/WorldGen/Features/BirchFeature.h @@ -3,9 +3,8 @@ class Level; -class BirchFeature : public Feature -{ +class BirchFeature : public Feature { public: - BirchFeature(bool doUpdate); - virtual bool place(Level *level, Random *random, int x, int y, int z); + BirchFeature(bool doUpdate); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/BonusChestFeature.cpp b/Minecraft.World/WorldGen/Features/BonusChestFeature.cpp index fdc991f30..5a698dfc9 100644 --- a/Minecraft.World/WorldGen/Features/BonusChestFeature.cpp +++ b/Minecraft.World/WorldGen/Features/BonusChestFeature.cpp @@ -6,78 +6,84 @@ #include "../../Util/WeighedTreasure.h" #include "../Structures/StructurePiece.h" -BonusChestFeature::BonusChestFeature(WeighedTreasureArray treasureList, int numRolls) : treasureList(treasureList), numRolls(numRolls) -{ -} +BonusChestFeature::BonusChestFeature(WeighedTreasureArray treasureList, + int numRolls) + : treasureList(treasureList), numRolls(numRolls) {} // 4J - original virtual method -bool BonusChestFeature::place(Level *level, Random *random, int x, int y, int z) -{ - return place(level, random, x, y, z, false ); +bool BonusChestFeature::place(Level* level, Random* random, int x, int y, + int z) { + return place(level, random, x, y, z, false); } -// 4J - added force parameter - trying to keep this as similar as possible to the original algorithm, but would also like it to definitely place a -// chest as it doesn't necessarily find somewhere in the original java. This method is called multple times for different x,y,z round the -// spawn point and force signifies that this is the last time this will be called. In this case, just place the chest exactly where the input -// parameters requested we place it (we know this will be one tile above the top solid block of a randomn column), and then do our best to place -// any surrounding torches where appropriate. +// 4J - added force parameter - trying to keep this as similar as possible to +// the original algorithm, but would also like it to definitely place a chest as +// it doesn't necessarily find somewhere in the original java. This method is +// called multple times for different x,y,z round the spawn point and force +// signifies that this is the last time this will be called. In this case, just +// place the chest exactly where the input parameters requested we place it (we +// know this will be one tile above the top solid block of a randomn column), +// and then do our best to place any surrounding torches where appropriate. -bool BonusChestFeature::place(Level *level, Random *random, int x, int y, int z, bool force) -{ - if( !force ) - { - int t = 0; - while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && y > 1) - y--; +bool BonusChestFeature::place(Level* level, Random* random, int x, int y, int z, + bool force) { + if (!force) { + int t = 0; + while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && + y > 1) + y--; - if (y < 1) - { - return false; - } - y++; - } + if (y < 1) { + return false; + } + y++; + } - for (int i = 0; i < 4; i++) - { - int x2, y2, z2; + for (int i = 0; i < 4; i++) { + int x2, y2, z2; - if( force ) - { - x2 = x; - y2 = y - 1; // 4J - the position passed in is actually two above the top solid block, as the calling function adds 1 to getTopSolidBlock, and that actually returns the block above anyway. - // this would explain why there is a while loop above here (not used in force mode) to move the y back down again, shouldn't really be needed if 1 wasn't added to the getTopSolidBlock return value. - z2 = z; - } - else - { - x2 = x + random->nextInt(4) - random->nextInt(4); - y2 = y + random->nextInt(3) - random->nextInt(3); - z2 = z + random->nextInt(4) - random->nextInt(4); - } + if (force) { + x2 = x; + y2 = + y - 1; // 4J - the position passed in is actually two above the + // top solid block, as the calling function adds 1 to + // getTopSolidBlock, and that actually returns the block + // above anyway. this would explain why there is a while + // loop above here (not used in force mode) to move the + // y back down again, shouldn't really be needed if 1 + // wasn't added to the getTopSolidBlock return value. + z2 = z; + } else { + x2 = x + random->nextInt(4) - random->nextInt(4); + y2 = y + random->nextInt(3) - random->nextInt(3); + z2 = z + random->nextInt(4) - random->nextInt(4); + } - if (force || ( level->isEmptyTile(x2, y2, z2) && level->isTopSolidBlocking(x2, y2 - 1, z2))) - { + if (force || (level->isEmptyTile(x2, y2, z2) && + level->isTopSolidBlocking(x2, y2 - 1, z2))) { level->setTile(x2, y2, z2, Tile::chest_Id); - std::shared_ptr chest = std::dynamic_pointer_cast(level->getTileEntity(x2, y2, z2)); - if (chest != NULL) - { - WeighedTreasure::addChestItems(random, treasureList, chest, numRolls); - chest->isBonusChest = true; // 4J added + std::shared_ptr chest = + std::dynamic_pointer_cast( + level->getTileEntity(x2, y2, z2)); + if (chest != NULL) { + WeighedTreasure::addChestItems(random, treasureList, chest, + numRolls); + chest->isBonusChest = true; // 4J added } - if (level->isEmptyTile(x2 - 1, y2, z2) && level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) - { + if (level->isEmptyTile(x2 - 1, y2, z2) && + level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) { level->setTile(x2 - 1, y2, z2, Tile::torch_Id); } - if (level->isEmptyTile(x2 + 1, y2, z2) && level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) - { + if (level->isEmptyTile(x2 + 1, y2, z2) && + level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) { level->setTile(x2 + 1, y2, z2, Tile::torch_Id); } - if (level->isEmptyTile(x2, y2, z2 - 1) && level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) - { + if (level->isEmptyTile(x2, y2, z2 - 1) && + level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) { level->setTile(x2, y2, z2 - 1, Tile::torch_Id); } - if (level->isEmptyTile(x2, y2, z2 + 1) && level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) - { + if (level->isEmptyTile(x2, y2, z2 + 1) && + level->isTopSolidBlocking(x2 - 1, y2 - 1, z2)) { level->setTile(x2, y2, z2 + 1, Tile::torch_Id); } return true; diff --git a/Minecraft.World/WorldGen/Features/BonusChestFeature.h b/Minecraft.World/WorldGen/Features/BonusChestFeature.h index cd4aca3ed..0b8f67bd1 100644 --- a/Minecraft.World/WorldGen/Features/BonusChestFeature.h +++ b/Minecraft.World/WorldGen/Features/BonusChestFeature.h @@ -4,16 +4,15 @@ class Random; class Level; -class BonusChestFeature : public Feature -{ - +class BonusChestFeature : public Feature { private: - const WeighedTreasureArray treasureList; + const WeighedTreasureArray treasureList; const int numRolls; public: - BonusChestFeature(WeighedTreasureArray treasureList, int numRolls); + BonusChestFeature(WeighedTreasureArray treasureList, int numRolls); - virtual bool place(Level *level, Random *random, int x, int y, int z); - bool place(Level *level, Random *random, int x, int y, int z, bool force); // 4J added this method with extra force parameter + virtual bool place(Level* level, Random* random, int x, int y, int z); + bool place(Level* level, Random* random, int x, int y, int z, + bool force); // 4J added this method with extra force parameter }; diff --git a/Minecraft.World/WorldGen/Features/CactusFeature.cpp b/Minecraft.World/WorldGen/Features/CactusFeature.cpp index 57f7f7d2a..609f1061b 100644 --- a/Minecraft.World/WorldGen/Features/CactusFeature.cpp +++ b/Minecraft.World/WorldGen/Features/CactusFeature.cpp @@ -3,20 +3,16 @@ #include "CactusFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -bool CactusFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool CactusFeature::place(Level* level, Random* random, int x, int y, int z) { for (int i = 0; i < 10; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2)) - { + if (level->isEmptyTile(x2, y2, z2)) { int h = 1 + random->nextInt(random->nextInt(3) + 1); - for (int yy = 0; yy < h; yy++) - { - if (Tile::cactus->canSurvive(level, x2, y2+yy, z2)) - { - level->setTileNoUpdate(x2, y2+yy, z2, Tile::cactus_Id); + for (int yy = 0; yy < h; yy++) { + if (Tile::cactus->canSurvive(level, x2, y2 + yy, z2)) { + level->setTileNoUpdate(x2, y2 + yy, z2, Tile::cactus_Id); } } } @@ -24,4 +20,3 @@ bool CactusFeature::place(Level *level, Random *random, int x, int y, int z) return true; } - diff --git a/Minecraft.World/WorldGen/Features/CactusFeature.h b/Minecraft.World/WorldGen/Features/CactusFeature.h index 6040289b3..3cda54664 100644 --- a/Minecraft.World/WorldGen/Features/CactusFeature.h +++ b/Minecraft.World/WorldGen/Features/CactusFeature.h @@ -1,9 +1,7 @@ #pragma once #include "Feature.h" - -class CactusFeature : public Feature -{ +class CactusFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/CanyonFeature.cpp b/Minecraft.World/WorldGen/Features/CanyonFeature.cpp index 6cbf47d58..9fa41f785 100644 --- a/Minecraft.World/WorldGen/Features/CanyonFeature.cpp +++ b/Minecraft.World/WorldGen/Features/CanyonFeature.cpp @@ -4,11 +4,13 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Headers/net.minecraft.world.level.biome.h" -void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale) -{ - MemSect(49); - Random *random = new Random(seed); - MemSect(0); +void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, + byteArray blocks, double xCave, double yCave, + double zCave, float thickness, float yRot, + float xRot, int step, int dist, double yScale) { + MemSect(49); + Random* random = new Random(seed); + MemSect(0); double xMid = xOffs * 16 + 8; double zMid = zOffs * 16 + 8; @@ -17,36 +19,31 @@ void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray bloc // int dist = CAVE_RADIUS * 16 - 16; // if (step>0) dist = step*2; - if (dist <= 0) - { + if (dist <= 0) { int max = radius * 16 - 16; dist = max - random->nextInt(max / 4); } bool singleStep = false; - if (step == -1) - { + if (step == -1) { step = dist / 2; singleStep = true; } - float f = 1; - for (int i = 0; i < Level::genDepth; i++) - { - if (i == 0 || random->nextInt(3) == 0) - { - f = 1 + (random->nextFloat() * random->nextFloat()) * 1.0f; - } - rs[i] = f * f; - } + float f = 1; + for (int i = 0; i < Level::genDepth; i++) { + if (i == 0 || random->nextInt(3) == 0) { + f = 1 + (random->nextFloat() * random->nextFloat()) * 1.0f; + } + rs[i] = f * f; + } - for (; step < dist; step++) - { + for (; step < dist; step++) { double rad = 1.5 + (Mth::sin(step * PI / dist) * thickness) * 1; double yRad = rad * yScale; - rad *= (random->nextFloat() * 0.25 + 0.75); - yRad *= (random->nextFloat() * 0.25 + 0.75); + rad *= (random->nextFloat() * 0.25 + 0.75); + yRad *= (random->nextFloat() * 0.25 + 0.75); float xc = Mth::cos(xRot); float xs = Mth::sin(xRot); @@ -54,15 +51,17 @@ void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray bloc yCave += xs; zCave += Mth::sin(yRot) * xc; - xRot *= 0.7f; + xRot *= 0.7f; xRot += xRota * 0.05f; yRot += yRota * 0.05f; xRota *= 0.80f; yRota *= 0.50f; - xRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 2; - yRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 4; + xRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 2; + yRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 4; if (!singleStep && random->nextInt(4) == 0) continue; @@ -71,14 +70,15 @@ void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray bloc double zd = zCave - zMid; double remaining = dist - step; double rr = (thickness + 2) + 16; - if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) - { - delete random; + if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) { + delete random; return; } } - if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) continue; + if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || + xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) + continue; int x0 = Mth::floor(xCave - rad) - xOffs * 16 - 1; int x1 = Mth::floor(xCave + rad) - xOffs * 16 + 1; @@ -99,20 +99,17 @@ void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray bloc if (z1 > 16) z1 = 16; bool detectedWater = false; - for (int xx = x0; !detectedWater && xx < x1; xx++) - { - for (int zz = z0; !detectedWater && zz < z1; zz++) - { - for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) - { + for (int xx = x0; !detectedWater && xx < x1; xx++) { + for (int zz = z0; !detectedWater && zz < z1; zz++) { + for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) { int p = (xx * 16 + zz) * Level::genDepth + yy; if (yy < 0 || yy >= Level::genDepth) continue; - if (blocks[p] == Tile::water_Id || blocks[p] == Tile::calmWater_Id) - { + if (blocks[p] == Tile::water_Id || + blocks[p] == Tile::calmWater_Id) { detectedWater = true; } - if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && zz != z1 - 1) - { + if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && + zz != z1 - 1) { yy = y0; } } @@ -120,66 +117,65 @@ void CanyonFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray bloc } if (detectedWater) continue; - for (int xx = x0; xx < x1; xx++) - { + for (int xx = x0; xx < x1; xx++) { double xd = ((xx + xOffs * 16 + 0.5) - xCave) / rad; - for (int zz = z0; zz < z1; zz++) - { + for (int zz = z0; zz < z1; zz++) { double zd = ((zz + zOffs * 16 + 0.5) - zCave) / rad; int p = (xx * 16 + zz) * Level::genDepth + y1; bool hasGrass = false; - if (xd * xd + zd * zd < 1) - { - for (int yy = y1 - 1; yy >= y0; yy--) - { - double yd = (yy + 0.5 - yCave) / yRad; - if ((xd * xd + zd * zd) * rs[yy] + (yd * yd / 6) < 1) - { - int block = blocks[p]; - if (block == Tile::grass_Id) hasGrass = true; - if (block == Tile::rock_Id || block == Tile::dirt_Id || block == Tile::grass_Id) - { - if (yy < 10) - { - blocks[p] = (uint8_t) Tile::lava_Id; - } - else - { - blocks[p] = (uint8_t) 0; - if (hasGrass && blocks[p - 1] == Tile::dirt_Id) blocks[p - 1] = (uint8_t) level->getBiome(xx + xOffs * 16, zz + zOffs * 16)->topMaterial; - } - } - } - p--; - } - } + if (xd * xd + zd * zd < 1) { + for (int yy = y1 - 1; yy >= y0; yy--) { + double yd = (yy + 0.5 - yCave) / yRad; + if ((xd * xd + zd * zd) * rs[yy] + (yd * yd / 6) < 1) { + int block = blocks[p]; + if (block == Tile::grass_Id) hasGrass = true; + if (block == Tile::rock_Id || + block == Tile::dirt_Id || + block == Tile::grass_Id) { + if (yy < 10) { + blocks[p] = (uint8_t)Tile::lava_Id; + } else { + blocks[p] = (uint8_t)0; + if (hasGrass && + blocks[p - 1] == Tile::dirt_Id) + blocks[p - 1] = + (uint8_t)level + ->getBiome(xx + xOffs * 16, + zz + zOffs * 16) + ->topMaterial; + } + } + } + p--; + } + } } } if (singleStep) break; } - delete random; + delete random; } -void CanyonFeature::addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) -{ +void CanyonFeature::addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks) { if (random->nextInt(50) != 0) return; double xCave = x * 16 + random->nextInt(16); double yCave = random->nextInt(random->nextInt(40) + 8) + 20; double zCave = z * 16 + random->nextInt(16); - int tunnels = 1; + int tunnels = 1; - for (int i = 0; i < tunnels; i++) - { - float yRot = random->nextFloat() * PI * 2; - float xRot = ((random->nextFloat() - 0.5f) * 2) / 8; - float thickness = (random->nextFloat() * 2 + random->nextFloat()) * 2; + for (int i = 0; i < tunnels; i++) { + float yRot = random->nextFloat() * PI * 2; + float xRot = ((random->nextFloat() - 0.5f) * 2) / 8; + float thickness = (random->nextFloat() * 2 + random->nextFloat()) * 2; - addTunnel(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave, thickness, yRot, xRot, 0, 0, 3.0); - - // 4J Add to feature list - app.AddTerrainFeaturePosition(eTerrainFeature_Ravine,(int)(xCave/16.0),(int)(yCave/16.0)); - } + addTunnel(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave, + thickness, yRot, xRot, 0, 0, 3.0); + // 4J Add to feature list + app.AddTerrainFeaturePosition(eTerrainFeature_Ravine, + (int)(xCave / 16.0), (int)(yCave / 16.0)); + } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/CanyonFeature.h b/Minecraft.World/WorldGen/Features/CanyonFeature.h index cf3f7a61c..9f3b137b7 100644 --- a/Minecraft.World/WorldGen/Features/CanyonFeature.h +++ b/Minecraft.World/WorldGen/Features/CanyonFeature.h @@ -3,12 +3,14 @@ class Level; -class CanyonFeature : public LargeFeature -{ +class CanyonFeature : public LargeFeature { private: - float rs[1024]; + float rs[1024]; protected: - void addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale); - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks); + void addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, + double xCave, double yCave, double zCave, float thickness, + float yRot, float xRot, int step, int dist, double yScale); + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks); }; diff --git a/Minecraft.World/WorldGen/Features/CaveFeature.cpp b/Minecraft.World/WorldGen/Features/CaveFeature.cpp index 3f495cc1a..53e77a335 100644 --- a/Minecraft.World/WorldGen/Features/CaveFeature.cpp +++ b/Minecraft.World/WorldGen/Features/CaveFeature.cpp @@ -3,9 +3,7 @@ #include "../../Headers/net.minecraft.world.level.h" #include "../../Headers/net.minecraft.world.level.tile.h" - - bool CaveFeature::place(Level *level, Random *random, int x, int y, int z) - { +bool CaveFeature::place(Level* level, Random* random, int x, int y, int z) { float dir = random->nextFloat() * PI; double rd = 8; @@ -22,10 +20,9 @@ __int64 seed = random->nextLong(); random->setSeed(seed); - std::vector toRemove; + std::vector toRemove; - for (int d = 0; d <= 16; d++) - { + for (int d = 0; d <= 16; d++) { double xx = x0 + (x1 - x0) * d / 16; double yy = y0 + (y1 - y0) * d / 16; double zz = z0 + (z1 - z0) * d / 16; @@ -34,58 +31,63 @@ double r = (Mth::sin(d / 16.0f * PI) * radius + 1) * ss + 1; double hr = (Mth::sin(d / 16.0f * PI) * radius + 1) * ss + 1; - // 4J Stu Added to stop cave features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects((xx - r / 2), (yy - hr / 2), (zz - r / 2), (xx + r / 2), (yy + hr / 2), (zz + r / 2)); - if(intersects) - { - //app.DebugPrintf("Skipping cave feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop cave features generating areas previously place + // by game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + (xx - r / 2), (yy - hr / 2), (zz - r / 2), (xx + r / 2), + (yy + hr / 2), (zz + r / 2)); + if (intersects) { + // app.DebugPrintf("Skipping cave feature generation as it + // overlaps a game rule structure\n"); + return false; + } + } - for (int x2 = (int) (xx - r / 2); x2 <= (int) (xx + r / 2); x2++) - for (int y2 = (int) (yy - hr / 2); y2 <= (int) (yy + hr / 2); y2++) - for (int z2 = (int) (zz - r / 2); z2 <= (int) (zz + r / 2); z2++) - { + for (int x2 = (int)(xx - r / 2); x2 <= (int)(xx + r / 2); x2++) + for (int y2 = (int)(yy - hr / 2); y2 <= (int)(yy + hr / 2); y2++) + for (int z2 = (int)(zz - r / 2); z2 <= (int)(zz + r / 2); + z2++) { double xd = ((x2 + 0.5) - xx) / (r / 2); double yd = ((y2 + 0.5) - yy) / (hr / 2); double zd = ((z2 + 0.5) - zz) / (r / 2); - if (xd * xd + yd * yd + zd * zd < random->nextDouble() * fuss + (1 - fuss)) - { - if (!level->isEmptyTile(x2, y2, z2)) - { + if (xd * xd + yd * yd + zd * zd < + random->nextDouble() * fuss + (1 - fuss)) { + if (!level->isEmptyTile(x2, y2, z2)) { for (int x3 = (x2 - 2); x3 <= (x2 + 1); x3++) for (int y3 = (y2 - 1); y3 <= (y2 + 1); y3++) - for (int z3 = (z2 - 1); z3 <= (z2 + 1); z3++) - { - if (x3 <= x || z3 <= z || x3 >= x + 16 - 1 || z3 >= z + 16 - 1) return false; - if (level->getMaterial(x3, y3, z3)->isLiquid()) return false; + for (int z3 = (z2 - 1); z3 <= (z2 + 1); + z3++) { + if (x3 <= x || z3 <= z || + x3 >= x + 16 - 1 || + z3 >= z + 16 - 1) + return false; + if (level->getMaterial(x3, y3, z3) + ->isLiquid()) + return false; } toRemove.push_back(new TilePos(x2, y2, z2)); } } } } - - AUTO_VAR(itEnd, toRemove.end()); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) - { - TilePos *p = *it; //toRemove[i]; + + AUTO_VAR(itEnd, toRemove.end()); + for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) { + TilePos* p = *it; // toRemove[i]; level->setTileNoUpdate(p->x, p->y, p->z, 0); } - - itEnd = toRemove.end(); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) - { - TilePos *p = *it; //toRemove[i]; - if (level->getTile(p->x, p->y - 1, p->z) == Tile::dirt_Id && level->getDaytimeRawBrightness(p->x, p->y, p->z) > 8) - { + + itEnd = toRemove.end(); + for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) { + TilePos* p = *it; // toRemove[i]; + if (level->getTile(p->x, p->y - 1, p->z) == Tile::dirt_Id && + level->getDaytimeRawBrightness(p->x, p->y, p->z) > 8) { level->setTileNoUpdate(p->x, p->y - 1, p->z, Tile::grass_Id); } - delete p; + delete p; } return true; diff --git a/Minecraft.World/WorldGen/Features/CaveFeature.h b/Minecraft.World/WorldGen/Features/CaveFeature.h index 1fa2fc1d3..f00c62352 100644 --- a/Minecraft.World/WorldGen/Features/CaveFeature.h +++ b/Minecraft.World/WorldGen/Features/CaveFeature.h @@ -4,7 +4,6 @@ class Level; -class CaveFeature : public Feature -{ - virtual bool place(Level *level, Random *random, int x, int y, int z); +class CaveFeature : public Feature { + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/ClayFeature.cpp b/Minecraft.World/WorldGen/Features/ClayFeature.cpp index 4b137d228..29db4ed4e 100644 --- a/Minecraft.World/WorldGen/Features/ClayFeature.cpp +++ b/Minecraft.World/WorldGen/Features/ClayFeature.cpp @@ -4,30 +4,24 @@ #include "ClayFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -ClayFeature::ClayFeature(int radius) -{ - this->tile = Tile::clay_Id; - this->radius = radius; +ClayFeature::ClayFeature(int radius) { + this->tile = Tile::clay_Id; + this->radius = radius; } -bool ClayFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool ClayFeature::place(Level* level, Random* random, int x, int y, int z) { if (level->getMaterial(x, y, z) != Material::water) return false; int r = random->nextInt(radius - 2) + 2; int yr = 1; - for (int xx = x - r; xx <= x + r; xx++) - { - for (int zz = z - r; zz <= z + r; zz++) - { + for (int xx = x - r; xx <= x + r; xx++) { + for (int zz = z - r; zz <= z + r; zz++) { int xd = xx - x; int zd = zz - z; if (xd * xd + zd * zd > r * r) continue; - for (int yy = y - yr; yy <= y + yr; yy++) - { + for (int yy = y - yr; yy <= y + yr; yy++) { int t = level->getTile(xx, yy, zz); - if (t == Tile::dirt_Id || t == Tile::clay_Id) - { + if (t == Tile::dirt_Id || t == Tile::clay_Id) { level->setTileNoUpdate(xx, yy, zz, tile); } } diff --git a/Minecraft.World/WorldGen/Features/ClayFeature.h b/Minecraft.World/WorldGen/Features/ClayFeature.h index 985502a68..973657c8d 100644 --- a/Minecraft.World/WorldGen/Features/ClayFeature.h +++ b/Minecraft.World/WorldGen/Features/ClayFeature.h @@ -4,14 +4,13 @@ class Level; -class ClayFeature : public Feature -{ +class ClayFeature : public Feature { private: - int tile; - int radius; + int tile; + int radius; public: - ClayFeature (int radius); + ClayFeature(int radius); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DeadBushFeature.cpp b/Minecraft.World/WorldGen/Features/DeadBushFeature.cpp index 113d23f04..c3bf084ec 100644 --- a/Minecraft.World/WorldGen/Features/DeadBushFeature.cpp +++ b/Minecraft.World/WorldGen/Features/DeadBushFeature.cpp @@ -3,31 +3,24 @@ #include "DeadBushFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -DeadBushFeature::DeadBushFeature(int tile) -{ - this->tile = tile; -} +DeadBushFeature::DeadBushFeature(int tile) { this->tile = tile; } -bool DeadBushFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool DeadBushFeature::place(Level* level, Random* random, int x, int y, int z) { int t = 0; - while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && y > 0) + while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && + y > 0) y--; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2) ) - { - if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) - { + if (level->isEmptyTile(x2, y2, z2)) { + if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) { level->setTileNoUpdate(x2, y2, z2, tile); } } } return true; - } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DeadBushFeature.h b/Minecraft.World/WorldGen/Features/DeadBushFeature.h index 6b0a338f1..2654845d2 100644 --- a/Minecraft.World/WorldGen/Features/DeadBushFeature.h +++ b/Minecraft.World/WorldGen/Features/DeadBushFeature.h @@ -3,13 +3,12 @@ class Level; -class DeadBushFeature : public Feature -{ +class DeadBushFeature : public Feature { private: - int tile; + int tile; public: - DeadBushFeature (int tile); + DeadBushFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DesertWellFeature.cpp b/Minecraft.World/WorldGen/Features/DesertWellFeature.cpp index 559d2e449..0633d8017 100644 --- a/Minecraft.World/WorldGen/Features/DesertWellFeature.cpp +++ b/Minecraft.World/WorldGen/Features/DesertWellFeature.cpp @@ -3,88 +3,81 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "DesertWellFeature.h" -bool DesertWellFeature::place(Level *level, Random *random, int x, int y, int z) -{ - while (level->isEmptyTile(x, y, z) && y > 2) - y--; +bool DesertWellFeature::place(Level* level, Random* random, int x, int y, + int z) { + while (level->isEmptyTile(x, y, z) && y > 2) y--; - int tile = level->getTile(x, y, z); - if (tile != Tile::sand_Id) - { - return false; - } + int tile = level->getTile(x, y, z); + if (tile != Tile::sand_Id) { + return false; + } - // the surrounding 5x5 area may not be lower than y-1 - for (int ox = -2; ox <= 2; ox++) - { - for (int oz = -2; oz <= 2; oz++) - { - if (level->isEmptyTile(x + ox, y - 1, z + oz) && level->isEmptyTile(x + ox, y - 2, z + oz)) - { - return false; - } - } - } + // the surrounding 5x5 area may not be lower than y-1 + for (int ox = -2; ox <= 2; ox++) { + for (int oz = -2; oz <= 2; oz++) { + if (level->isEmptyTile(x + ox, y - 1, z + oz) && + level->isEmptyTile(x + ox, y - 2, z + oz)) { + return false; + } + } + } - // place floor - for (int oy = -1; oy <= 0; oy++) - { - for (int ox = -2; ox <= 2; ox++) - { - for (int oz = -2; oz <= 2; oz++) - { - level->setTileNoUpdate(x + ox, y + oy, z + oz, Tile::sandStone_Id); - } - } - } + // place floor + for (int oy = -1; oy <= 0; oy++) { + for (int ox = -2; ox <= 2; ox++) { + for (int oz = -2; oz <= 2; oz++) { + level->setTileNoUpdate(x + ox, y + oy, z + oz, + Tile::sandStone_Id); + } + } + } - // place water cross - level->setTileNoUpdate(x, y, z, Tile::water_Id); - level->setTileNoUpdate(x - 1, y, z, Tile::water_Id); - level->setTileNoUpdate(x + 1, y, z, Tile::water_Id); - level->setTileNoUpdate(x, y, z - 1, Tile::water_Id); - level->setTileNoUpdate(x, y, z + 1, Tile::water_Id); + // place water cross + level->setTileNoUpdate(x, y, z, Tile::water_Id); + level->setTileNoUpdate(x - 1, y, z, Tile::water_Id); + level->setTileNoUpdate(x + 1, y, z, Tile::water_Id); + level->setTileNoUpdate(x, y, z - 1, Tile::water_Id); + level->setTileNoUpdate(x, y, z + 1, Tile::water_Id); - // place "fence" - for (int ox = -2; ox <= 2; ox++) - { - for (int oz = -2; oz <= 2; oz++) - { - if (ox == -2 || ox == 2 || oz == -2 || oz == 2) - { - level->setTileNoUpdate(x + ox, y + 1, z + oz, Tile::sandStone_Id); - } - } - } - level->setTileAndDataNoUpdate(x + 2, y + 1, z, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB); - level->setTileAndDataNoUpdate(x - 2, y + 1, z, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB); - level->setTileAndDataNoUpdate(x, y + 1, z + 2, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB); - level->setTileAndDataNoUpdate(x, y + 1, z - 2, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB); + // place "fence" + for (int ox = -2; ox <= 2; ox++) { + for (int oz = -2; oz <= 2; oz++) { + if (ox == -2 || ox == 2 || oz == -2 || oz == 2) { + level->setTileNoUpdate(x + ox, y + 1, z + oz, + Tile::sandStone_Id); + } + } + } + level->setTileAndDataNoUpdate(x + 2, y + 1, z, Tile::stoneSlabHalf_Id, + StoneSlabTile::SAND_SLAB); + level->setTileAndDataNoUpdate(x - 2, y + 1, z, Tile::stoneSlabHalf_Id, + StoneSlabTile::SAND_SLAB); + level->setTileAndDataNoUpdate(x, y + 1, z + 2, Tile::stoneSlabHalf_Id, + StoneSlabTile::SAND_SLAB); + level->setTileAndDataNoUpdate(x, y + 1, z - 2, Tile::stoneSlabHalf_Id, + StoneSlabTile::SAND_SLAB); - // place roof - for (int ox = -1; ox <= 1; ox++) - { - for (int oz = -1; oz <= 1; oz++) - { - if (ox == 0 && oz == 0) - { - level->setTileNoUpdate(x + ox, y + 4, z + oz, Tile::sandStone_Id); - } - else - { - level->setTileAndDataNoUpdate(x + ox, y + 4, z + oz, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB); - } - } - } + // place roof + for (int ox = -1; ox <= 1; ox++) { + for (int oz = -1; oz <= 1; oz++) { + if (ox == 0 && oz == 0) { + level->setTileNoUpdate(x + ox, y + 4, z + oz, + Tile::sandStone_Id); + } else { + level->setTileAndDataNoUpdate(x + ox, y + 4, z + oz, + Tile::stoneSlabHalf_Id, + StoneSlabTile::SAND_SLAB); + } + } + } - // place pillars - for (int oy = 1; oy <= 3; oy++) - { - level->setTileNoUpdate(x - 1, y + oy, z - 1, Tile::sandStone_Id); - level->setTileNoUpdate(x - 1, y + oy, z + 1, Tile::sandStone_Id); - level->setTileNoUpdate(x + 1, y + oy, z - 1, Tile::sandStone_Id); - level->setTileNoUpdate(x + 1, y + oy, z + 1, Tile::sandStone_Id); - } + // place pillars + for (int oy = 1; oy <= 3; oy++) { + level->setTileNoUpdate(x - 1, y + oy, z - 1, Tile::sandStone_Id); + level->setTileNoUpdate(x - 1, y + oy, z + 1, Tile::sandStone_Id); + level->setTileNoUpdate(x + 1, y + oy, z - 1, Tile::sandStone_Id); + level->setTileNoUpdate(x + 1, y + oy, z + 1, Tile::sandStone_Id); + } - return true; + return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DesertWellFeature.h b/Minecraft.World/WorldGen/Features/DesertWellFeature.h index 380a35e36..7ce93742d 100644 --- a/Minecraft.World/WorldGen/Features/DesertWellFeature.h +++ b/Minecraft.World/WorldGen/Features/DesertWellFeature.h @@ -2,8 +2,7 @@ #include "Feature.h" -class DesertWellFeature : public Feature -{ +class DesertWellFeature : public Feature { public: - bool place(Level *level, Random *random, int x, int y, int z); + bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DungeonFeature.cpp b/Minecraft.World/WorldGen/Features/DungeonFeature.cpp index fa24aeff8..472db063c 100644 --- a/Minecraft.World/WorldGen/Features/DungeonFeature.cpp +++ b/Minecraft.World/WorldGen/Features/DungeonFeature.cpp @@ -3,39 +3,38 @@ #include "DungeonFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -void DungeonFeature::addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom) -{ - addTunnel(xOffs, zOffs, blocks, xRoom, yRoom, zRoom, 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); +void DungeonFeature::addRoom(int xOffs, int zOffs, byteArray blocks, + double xRoom, double yRoom, double zRoom) { + addTunnel(xOffs, zOffs, blocks, xRoom, yRoom, zRoom, + 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); } -void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale) -{ +void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, + double xCave, double yCave, double zCave, + float thickness, float yRot, float xRot, + int step, int dist, double yScale) { double xMid = xOffs * 16 + 8; double zMid = zOffs * 16 + 8; float yRota = 0; float xRota = 0; - Random *random = new Random(this->random->nextLong()); + Random* random = new Random(this->random->nextLong()); - if (dist <= 0) - { + if (dist <= 0) { int max = radius * 16 - 16; dist = max - random->nextInt(max / 4); } bool singleStep = false; - if (step == -1) - { + if (step == -1) { step = dist / 2; singleStep = true; } - int splitPoint = random->nextInt(dist / 2) + dist / 4; bool steep = random->nextInt(6) == 0; - for (; step < dist; step++) - { + for (; step < dist; step++) { double rad = 1.5 + (Mth::sin(step * PI / dist) * thickness) * 1; double yRad = rad * yScale; @@ -45,12 +44,9 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC yCave += xs; zCave += Mth::sin(yRot) * xc; - if (steep) - { + if (steep) { xRot *= 0.92f; - } - else - { + } else { xRot *= 0.7f; } xRot += xRota * 0.1f; @@ -58,14 +54,18 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC xRota *= 0.90f; yRota *= 0.75f; - xRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 2; - yRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 4; + xRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 2; + yRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 4; - - if (!singleStep && step == splitPoint && thickness > 1) - { - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, random->nextFloat() * 0.5f + 0.5f, yRot - PI / 2, xRot / 3, step, dist, 1.0); - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, random->nextFloat() * 0.5f + 0.5f, yRot + PI / 2, xRot / 3, step, dist, 1.0); + if (!singleStep && step == splitPoint && thickness > 1) { + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, + random->nextFloat() * 0.5f + 0.5f, yRot - PI / 2, + xRot / 3, step, dist, 1.0); + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, + random->nextFloat() * 0.5f + 0.5f, yRot + PI / 2, + xRot / 3, step, dist, 1.0); return; } if (!singleStep && random->nextInt(4) == 0) continue; @@ -75,13 +75,14 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC double zd = zCave - zMid; double remaining = dist - step; double rr = (thickness + 2) + 16; - if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) - { + if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) { return; } } - if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) continue; + if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || + xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) + continue; int x0 = Mth::floor(xCave - rad) - xOffs * 16 - 1; int x1 = Mth::floor(xCave + rad) - xOffs * 16 + 1; @@ -102,20 +103,17 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC if (z1 > 16) z1 = 16; bool detectedWater = false; - for (int xx = x0; !detectedWater && xx < x1; xx++) - { - for (int zz = z0; !detectedWater && zz < z1; zz++) - { - for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) - { + for (int xx = x0; !detectedWater && xx < x1; xx++) { + for (int zz = z0; !detectedWater && zz < z1; zz++) { + for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) { int p = (xx * 16 + zz) * Level::genDepth + yy; - if (yy < 0 || yy >= Level::genDepth) continue; - if (blocks[p] == Tile::water_Id || blocks[p] == Tile::calmWater_Id) - { + if (yy < 0 || yy >= Level::genDepth) continue; + if (blocks[p] == Tile::water_Id || + blocks[p] == Tile::calmWater_Id) { detectedWater = true; } - if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && zz != z1 - 1) - { + if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && + zz != z1 - 1) { yy = y0; } } @@ -123,31 +121,25 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC } if (detectedWater) continue; - for (int xx = x0; xx < x1; xx++) - { + for (int xx = x0; xx < x1; xx++) { double xd = ((xx + xOffs * 16 + 0.5) - xCave) / rad; - for (int zz = z0; zz < z1; zz++) - { + for (int zz = z0; zz < z1; zz++) { double zd = ((zz + zOffs * 16 + 0.5) - zCave) / rad; int p = (xx * 16 + zz) * Level::genDepth + y1; bool hasGrass = false; - for (int yy = y1 - 1; yy >= y0; yy--) - { + for (int yy = y1 - 1; yy >= y0; yy--) { double yd = (yy + 0.5 - yCave) / yRad; - if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) - { + if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) { int block = blocks[p]; if (block == Tile::grass_Id) hasGrass = true; - if (block == Tile::rock_Id || block == Tile::dirt_Id || block == Tile::grass_Id) - { - if (yy < 10) - { - blocks[p] = (uint8_t) Tile::lava_Id; - } - else - { - blocks[p] = (uint8_t) 0; - if (hasGrass && blocks[p - 1] == Tile::dirt_Id) blocks[p - 1] = (uint8_t) Tile::grass_Id; + if (block == Tile::rock_Id || block == Tile::dirt_Id || + block == Tile::grass_Id) { + if (yy < 10) { + blocks[p] = (uint8_t)Tile::lava_Id; + } else { + blocks[p] = (uint8_t)0; + if (hasGrass && blocks[p - 1] == Tile::dirt_Id) + blocks[p - 1] = (uint8_t)Tile::grass_Id; } } } @@ -157,35 +149,32 @@ void DungeonFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xC } if (singleStep) break; } - } -void DungeonFeature::addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) -{ +void DungeonFeature::addFeature(Level* level, int x, int z, int xOffs, + int zOffs, byteArray blocks) { int caves = random->nextInt(random->nextInt(random->nextInt(40) + 1) + 1); if (random->nextInt(15) != 0) caves = 0; - for (int cave = 0; cave < caves; cave++) - { + for (int cave = 0; cave < caves; cave++) { double xCave = x * 16 + random->nextInt(16); - double yCave = random->nextInt(random->nextInt(Level::genDepth - 8) + 8); + double yCave = + random->nextInt(random->nextInt(Level::genDepth - 8) + 8); double zCave = z * 16 + random->nextInt(16); int tunnels = 1; - if (random->nextInt(4) == 0) - { + if (random->nextInt(4) == 0) { addRoom(xOffs, zOffs, blocks, xCave, yCave, zCave); tunnels += random->nextInt(4); } - for (int i = 0; i < tunnels; i++) - { - + for (int i = 0; i < tunnels; i++) { float yRot = random->nextFloat() * PI * 2; float xRot = ((random->nextFloat() - 0.5f) * 2) / 8; float thickness = random->nextFloat() * 2 + random->nextFloat(); - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, thickness, yRot, xRot, 0, 0, 1.0); + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, thickness, + yRot, xRot, 0, 0, 1.0); } } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/DungeonFeature.h b/Minecraft.World/WorldGen/Features/DungeonFeature.h index 488ca59ce..598c60d89 100644 --- a/Minecraft.World/WorldGen/Features/DungeonFeature.h +++ b/Minecraft.World/WorldGen/Features/DungeonFeature.h @@ -3,10 +3,13 @@ class Level; -class DungeonFeature : public LargeFeature -{ - void addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom); - void addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale); +class DungeonFeature : public LargeFeature { + void addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, + double yRoom, double zRoom); + void addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, + double yCave, double zCave, float thickness, float yRot, + float xRot, int step, int dist, double yScale); - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks); + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks); }; diff --git a/Minecraft.World/WorldGen/Features/EndPodiumFeature.cpp b/Minecraft.World/WorldGen/Features/EndPodiumFeature.cpp index 4732f8f00..6215aa4a8 100644 --- a/Minecraft.World/WorldGen/Features/EndPodiumFeature.cpp +++ b/Minecraft.World/WorldGen/Features/EndPodiumFeature.cpp @@ -4,83 +4,66 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "EndPodiumFeature.h" -EndPodiumFeature::EndPodiumFeature(int tile) -{ - this->tile = tile; - //m_iIndex=0; +EndPodiumFeature::EndPodiumFeature(int tile) { + this->tile = tile; + // m_iIndex=0; } -bool EndPodiumFeature::place(Level *level, Random *random, int x, int y, int z) -{ - // spawn Exit portal - int r = 4; +bool EndPodiumFeature::place(Level* level, Random* random, int x, int y, + int z) { + // spawn Exit portal + int r = 4; - for (int yy = y - 1; yy <= y + 32; yy++) - { - for (int xx = x - r; xx <= x + r; xx++) - { - for (int zz = z - r; zz <= z + r; zz++) - { - double xd = xx - x; - double zd = zz - z; - double d = sqrt(xd * xd + zd * zd); - if (d <= r - 0.5) - { - if (yy < y) - { - if (d > r - 1 - 0.5) - { - } - else - { - //level->setTile(xx, yy, zz, Tile::unbreakable_Id); - placeBlock(level, xx, yy, zz, Tile::unbreakable_Id, 0); - } - } - else if (yy > y) - { - //level->setTile(xx, yy, zz, 0); - placeBlock(level, xx, yy, zz, 0, 0); - } - else - { - if (d > r - 1 - 0.5) - { - //level->setTile(xx, yy, zz, Tile::unbreakable_Id); - placeBlock(level, xx, yy, zz, Tile::unbreakable_Id, 0); - } - } - } - } - } - } + for (int yy = y - 1; yy <= y + 32; yy++) { + for (int xx = x - r; xx <= x + r; xx++) { + for (int zz = z - r; zz <= z + r; zz++) { + double xd = xx - x; + double zd = zz - z; + double d = sqrt(xd * xd + zd * zd); + if (d <= r - 0.5) { + if (yy < y) { + if (d > r - 1 - 0.5) { + } else { + // level->setTile(xx, yy, zz, Tile::unbreakable_Id); + placeBlock(level, xx, yy, zz, Tile::unbreakable_Id, + 0); + } + } else if (yy > y) { + // level->setTile(xx, yy, zz, 0); + placeBlock(level, xx, yy, zz, 0, 0); + } else { + if (d > r - 1 - 0.5) { + // level->setTile(xx, yy, zz, Tile::unbreakable_Id); + placeBlock(level, xx, yy, zz, Tile::unbreakable_Id, + 0); + } + } + } + } + } + } - placeBlock(level,x, y + 0, z, Tile::unbreakable_Id, 0); - placeBlock(level,x, y + 1, z, Tile::unbreakable_Id, 0); - placeBlock(level,x, y + 2, z, Tile::unbreakable_Id, 0); - placeBlock(level,x - 1, y + 2, z, Tile::torch_Id, 0); - placeBlock(level,x + 1, y + 2, z, Tile::torch_Id, 0); - placeBlock(level,x, y + 2, z - 1, Tile::torch_Id, 0); - placeBlock(level,x, y + 2, z + 1, Tile::torch_Id, 0); - placeBlock(level,x, y + 3, z, Tile::unbreakable_Id, 0); - //placeBlock(level,x, y + 4, z, Tile::dragonEgg_Id, 0); + placeBlock(level, x, y + 0, z, Tile::unbreakable_Id, 0); + placeBlock(level, x, y + 1, z, Tile::unbreakable_Id, 0); + placeBlock(level, x, y + 2, z, Tile::unbreakable_Id, 0); + placeBlock(level, x - 1, y + 2, z, Tile::torch_Id, 0); + placeBlock(level, x + 1, y + 2, z, Tile::torch_Id, 0); + placeBlock(level, x, y + 2, z - 1, Tile::torch_Id, 0); + placeBlock(level, x, y + 2, z + 1, Tile::torch_Id, 0); + placeBlock(level, x, y + 3, z, Tile::unbreakable_Id, 0); + // placeBlock(level,x, y + 4, z, Tile::dragonEgg_Id, 0); - // 4J-PB - The podium can be floating with nothing under it, so put some whiteStone under it if this is the case - for (int yy = y - 5; yy < y - 1; yy++) - { - for (int xx = x - (r - 1); xx <= x + (r - 1); xx++) - { - for (int zz = z - (r - 1); zz <= z + (r - 1); zz++) - { - if(level->isEmptyTile(xx,yy,zz)) - { - placeBlock(level, xx, yy, zz, Tile::whiteStone_Id, 0); - } - } - } - } - + // 4J-PB - The podium can be floating with nothing under it, so put some + // whiteStone under it if this is the case + for (int yy = y - 5; yy < y - 1; yy++) { + for (int xx = x - (r - 1); xx <= x + (r - 1); xx++) { + for (int zz = z - (r - 1); zz <= z + (r - 1); zz++) { + if (level->isEmptyTile(xx, yy, zz)) { + placeBlock(level, xx, yy, zz, Tile::whiteStone_Id, 0); + } + } + } + } return true; } - diff --git a/Minecraft.World/WorldGen/Features/EndPodiumFeature.h b/Minecraft.World/WorldGen/Features/EndPodiumFeature.h index fd231d328..7ab2f8422 100644 --- a/Minecraft.World/WorldGen/Features/EndPodiumFeature.h +++ b/Minecraft.World/WorldGen/Features/EndPodiumFeature.h @@ -1,14 +1,12 @@ #pragma once #include "Feature.h" -class EndPodiumFeature : public Feature -{ +class EndPodiumFeature : public Feature { private: - int tile; - //int m_iIndex; + int tile; + // int m_iIndex; public: - EndPodiumFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); - + EndPodiumFeature(int tile); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/Feature.cpp b/Minecraft.World/WorldGen/Features/Feature.cpp index b12149b5e..93f535ecf 100644 --- a/Minecraft.World/WorldGen/Features/Feature.cpp +++ b/Minecraft.World/WorldGen/Features/Feature.cpp @@ -2,30 +2,19 @@ #include "../../Headers/net.minecraft.world.level.h" #include "Feature.h" +Feature::Feature() { this->doUpdate = false; } -Feature::Feature() -{ - this->doUpdate = false; +Feature::Feature(bool doUpdate) { this->doUpdate = doUpdate; } + +void Feature::placeBlock(Level* level, int x, int y, int z, int tile) { + placeBlock(level, x, y, z, tile, 0); } -Feature::Feature(bool doUpdate) -{ - this->doUpdate = doUpdate; -} - -void Feature::placeBlock(Level *level, int x, int y, int z, int tile) -{ - placeBlock(level, x, y, z, tile, 0); -} - -void Feature::placeBlock(Level *level, int x, int y, int z, int tile, int data) -{ - if (doUpdate) - { - level->setTileAndData(x, y, z, tile, data); - } - else - { - level->setTileAndDataNoUpdate(x, y, z, tile, data); - } +void Feature::placeBlock(Level* level, int x, int y, int z, int tile, + int data) { + if (doUpdate) { + level->setTileAndData(x, y, z, tile, data); + } else { + level->setTileAndDataNoUpdate(x, y, z, tile, data); + } } diff --git a/Minecraft.World/WorldGen/Features/Feature.h b/Minecraft.World/WorldGen/Features/Feature.h index 9b89c0a66..f554df50a 100644 --- a/Minecraft.World/WorldGen/Features/Feature.h +++ b/Minecraft.World/WorldGen/Features/Feature.h @@ -2,19 +2,24 @@ class Level; -class Feature -{ +class Feature { private: - bool doUpdate; -public: - Feature(); - Feature(bool doUpdate); - virtual ~Feature() {}; + bool doUpdate; + +public: + Feature(); + Feature(bool doUpdate); + virtual ~Feature() {}; + + virtual bool place(Level* level, Random* random, int x, int y, int z) = 0; + virtual bool placeWithIndex(Level* level, Random* random, int x, int y, + int z, int iIndex, int iRadius) { + return false; + } + virtual void init(double V1, double V2, double V3) {}; - virtual bool place(Level *level, Random *random, int x, int y, int z) = 0; - virtual bool placeWithIndex(Level *level, Random *random, int x, int y, int z,int iIndex, int iRadius) { return false;} - virtual void init(double V1, double V2, double V3) {}; protected: - virtual void placeBlock(Level *level, int x, int y, int z, int tile); - virtual void placeBlock(Level *level, int x, int y, int z, int tile, int data); + virtual void placeBlock(Level* level, int x, int y, int z, int tile); + virtual void placeBlock(Level* level, int x, int y, int z, int tile, + int data); }; diff --git a/Minecraft.World/WorldGen/Features/FlowerFeature.cpp b/Minecraft.World/WorldGen/Features/FlowerFeature.cpp index 589cbcebf..1cbe6d457 100644 --- a/Minecraft.World/WorldGen/Features/FlowerFeature.cpp +++ b/Minecraft.World/WorldGen/Features/FlowerFeature.cpp @@ -3,34 +3,29 @@ #include "FlowerFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -FlowerFeature::FlowerFeature(int tile) -{ - this->tile = tile; -} +FlowerFeature::FlowerFeature(int tile) { this->tile = tile; } -bool FlowerFeature::place(Level *level, Random *random, int x, int y, int z) -{ - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - 8, y - 4, z - 8, x + 8, y + 4, z + 8); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } +bool FlowerFeature::place(Level* level, Random* random, int x, int y, int z) { + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects(x - 8, y - 4, z - 8, + x + 8, y + 4, z + 8); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } - for (int i = 0; i < 64; i++) - { + for (int i = 0; i < 64; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2)) - { - if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) - { + if (level->isEmptyTile(x2, y2, z2)) { + if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) { level->setTileNoUpdate(x2, y2, z2, tile); } } diff --git a/Minecraft.World/WorldGen/Features/FlowerFeature.h b/Minecraft.World/WorldGen/Features/FlowerFeature.h index 47a0c3bc5..efa792bc5 100644 --- a/Minecraft.World/WorldGen/Features/FlowerFeature.h +++ b/Minecraft.World/WorldGen/Features/FlowerFeature.h @@ -3,12 +3,11 @@ class Level; -class FlowerFeature : public Feature -{ +class FlowerFeature : public Feature { private: - int tile; + int tile; public: - FlowerFeature (int tile); - bool place(Level *level, Random *random, int x, int y, int z); + FlowerFeature(int tile); + bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/GroundBushFeature.cpp b/Minecraft.World/WorldGen/Features/GroundBushFeature.cpp index 12a45f315..f9668e191 100644 --- a/Minecraft.World/WorldGen/Features/GroundBushFeature.cpp +++ b/Minecraft.World/WorldGen/Features/GroundBushFeature.cpp @@ -3,41 +3,41 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "GroundBushFeature.h" -GroundBushFeature::GroundBushFeature(int trunkType, int leafType) -{ - this->trunkTileType = trunkType; - this->leafTileType = leafType; +GroundBushFeature::GroundBushFeature(int trunkType, int leafType) { + this->trunkTileType = trunkType; + this->leafTileType = leafType; } -bool GroundBushFeature::place(Level *level, Random *random, int x, int y, int z) -{ - PIXBeginNamedEvent(0,"Placing GroundBushFeature"); - int t = 0; - while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && y > 0) - y--; +bool GroundBushFeature::place(Level* level, Random* random, int x, int y, + int z) { + PIXBeginNamedEvent(0, "Placing GroundBushFeature"); + int t = 0; + while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && + y > 0) + y--; - int tile = level->getTile(x, y, z); - if (tile == Tile::dirt_Id || tile == Tile::grass_Id) - { - y++; - placeBlock(level, x, y, z, Tile::treeTrunk_Id, trunkTileType); + int tile = level->getTile(x, y, z); + if (tile == Tile::dirt_Id || tile == Tile::grass_Id) { + y++; + placeBlock(level, x, y, z, Tile::treeTrunk_Id, trunkTileType); - for (int yy = y; yy <= y + 2; yy++) - { - int yo = yy - y; - int offs = 2 - yo; - for (int xx = x - offs; xx <= x + offs; xx++) - { - int xo = xx - (x); - for (int zz = z - offs; zz <= z + offs; zz++) - { - int zo = zz - (z); - if (abs(xo) == offs && abs(zo) == offs && random->nextInt(2) == 0) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id, leafTileType); - } - } - } - } - PIXEndNamedEvent(); - return true; + for (int yy = y; yy <= y + 2; yy++) { + int yo = yy - y; + int offs = 2 - yo; + for (int xx = x - offs; xx <= x + offs; xx++) { + int xo = xx - (x); + for (int zz = z - offs; zz <= z + offs; zz++) { + int zo = zz - (z); + if (abs(xo) == offs && abs(zo) == offs && + random->nextInt(2) == 0) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id, + leafTileType); + } + } + } + } + PIXEndNamedEvent(); + return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/GroundBushFeature.h b/Minecraft.World/WorldGen/Features/GroundBushFeature.h index cf7f16bb2..b87e34291 100644 --- a/Minecraft.World/WorldGen/Features/GroundBushFeature.h +++ b/Minecraft.World/WorldGen/Features/GroundBushFeature.h @@ -2,14 +2,13 @@ #include "Feature.h" -class GroundBushFeature : public Feature -{ +class GroundBushFeature : public Feature { private: - int leafTileType; - int trunkTileType; + int leafTileType; + int trunkTileType; public: - GroundBushFeature(int trunkType, int leafType); + GroundBushFeature(int trunkType, int leafType); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HellFireFeature.cpp b/Minecraft.World/WorldGen/Features/HellFireFeature.cpp index 69ded099f..11c9e1e17 100644 --- a/Minecraft.World/WorldGen/Features/HellFireFeature.cpp +++ b/Minecraft.World/WorldGen/Features/HellFireFeature.cpp @@ -3,10 +3,8 @@ #include "HellFireFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -bool HellFireFeature::place(Level *level, Random *random, int x, int y, int z) -{ - for (int i = 0; i < 64; i++) - { +bool HellFireFeature::place(Level* level, Random* random, int x, int y, int z) { + for (int i = 0; i < 64; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); diff --git a/Minecraft.World/WorldGen/Features/HellFireFeature.h b/Minecraft.World/WorldGen/Features/HellFireFeature.h index 9373e25b9..c6ce6c854 100644 --- a/Minecraft.World/WorldGen/Features/HellFireFeature.h +++ b/Minecraft.World/WorldGen/Features/HellFireFeature.h @@ -3,8 +3,7 @@ class Level; -class HellFireFeature : public Feature -{ +class HellFireFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HellPortalFeature.cpp b/Minecraft.World/WorldGen/Features/HellPortalFeature.cpp index 9e397b1f1..8b9b69747 100644 --- a/Minecraft.World/WorldGen/Features/HellPortalFeature.cpp +++ b/Minecraft.World/WorldGen/Features/HellPortalFeature.cpp @@ -3,22 +3,20 @@ #include "HellPortalFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -bool HellPortalFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool HellPortalFeature::place(Level* level, Random* random, int x, int y, + int z) { if (!level->isEmptyTile(x, y, z)) return false; if (level->getTile(x, y + 1, z) != Tile::hellRock_Id) return false; level->setTile(x, y, z, Tile::lightGem_Id); - for (int i = 0; i < 1500; i++) - { + for (int i = 0; i < 1500; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y - random->nextInt(12); int z2 = z + random->nextInt(8) - random->nextInt(8); if (level->getTile(x2, y2, z2) != 0) continue; int count = 0; - for (int t = 0; t < 6; t++) - { + for (int t = 0; t < 6; t++) { int tile = 0; if (t == 0) tile = level->getTile(x2 - 1, y2, z2); if (t == 1) tile = level->getTile(x2 + 1, y2, z2); diff --git a/Minecraft.World/WorldGen/Features/HellPortalFeature.h b/Minecraft.World/WorldGen/Features/HellPortalFeature.h index d4699ee3e..3da0207cc 100644 --- a/Minecraft.World/WorldGen/Features/HellPortalFeature.h +++ b/Minecraft.World/WorldGen/Features/HellPortalFeature.h @@ -1,8 +1,7 @@ #pragma once #include "Feature.h" -class HellPortalFeature : public Feature -{ +class HellPortalFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HellSpringFeature.cpp b/Minecraft.World/WorldGen/Features/HellSpringFeature.cpp index 4070b5124..87c452bae 100644 --- a/Minecraft.World/WorldGen/Features/HellSpringFeature.cpp +++ b/Minecraft.World/WorldGen/Features/HellSpringFeature.cpp @@ -3,34 +3,32 @@ #include "HellSpringFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -HellSpringFeature::HellSpringFeature(int tile) -{ - this->tile = tile; -} +HellSpringFeature::HellSpringFeature(int tile) { this->tile = tile; } -bool HellSpringFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool HellSpringFeature::place(Level* level, Random* random, int x, int y, + int z) { if (level->getTile(x, y + 1, z) != Tile::hellRock_Id) return false; if (level->getTile(x, y - 1, z) != Tile::hellRock_Id) return false; - if (level->getTile(x, y, z) != 0 && level->getTile(x, y, z) != Tile::hellRock_Id) return false; + if (level->getTile(x, y, z) != 0 && + level->getTile(x, y, z) != Tile::hellRock_Id) + return false; int rockCount = 0; if (level->getTile(x - 1, y, z) == Tile::hellRock_Id) rockCount++; if (level->getTile(x + 1, y, z) == Tile::hellRock_Id) rockCount++; if (level->getTile(x, y, z - 1) == Tile::hellRock_Id) rockCount++; if (level->getTile(x, y, z + 1) == Tile::hellRock_Id) rockCount++; - if (level->getTile(x, y - 1, z) == Tile::hellRock_Id) rockCount++; + if (level->getTile(x, y - 1, z) == Tile::hellRock_Id) rockCount++; int holeCount = 0; if (level->isEmptyTile(x - 1, y, z)) holeCount++; if (level->isEmptyTile(x + 1, y, z)) holeCount++; if (level->isEmptyTile(x, y, z - 1)) holeCount++; if (level->isEmptyTile(x, y, z + 1)) holeCount++; - if (level->isEmptyTile(x, y - 1, z)) holeCount++; + if (level->isEmptyTile(x, y - 1, z)) holeCount++; - if (rockCount == 4 && holeCount == 1) - { + if (rockCount == 4 && holeCount == 1) { level->setTile(x, y, z, tile); level->setInstaTick(true); Tile::tiles[tile]->tick(level, x, y, z, random); @@ -38,5 +36,4 @@ bool HellSpringFeature::place(Level *level, Random *random, int x, int y, int z) } return true; - } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HellSpringFeature.h b/Minecraft.World/WorldGen/Features/HellSpringFeature.h index a8ffbc000..d97d5bf22 100644 --- a/Minecraft.World/WorldGen/Features/HellSpringFeature.h +++ b/Minecraft.World/WorldGen/Features/HellSpringFeature.h @@ -1,14 +1,12 @@ #pragma once #include "Feature.h" - -class HellSpringFeature : public Feature -{ +class HellSpringFeature : public Feature { private: - int tile; + int tile; public: - HellSpringFeature(int tile); + HellSpringFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HouseFeature.cpp b/Minecraft.World/WorldGen/Features/HouseFeature.cpp index dc72d33d8..eba1785f5 100644 --- a/Minecraft.World/WorldGen/Features/HouseFeature.cpp +++ b/Minecraft.World/WorldGen/Features/HouseFeature.cpp @@ -5,28 +5,27 @@ #include "../../Headers/net.minecraft.world.entity.monster.h" #include "../../Headers/net.minecraft.world.item.h" -bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool HouseFeature::place(Level* level, Random* random, int x, int y, int z) { while (y > 0 && !level->getMaterial(x, y - 1, z)->blocksMotion()) { y--; } - int w = random->nextInt(7) + 7; - int h = 4 + random->nextInt(3) / 2; - int d = random->nextInt(7) + 7; + int w = random->nextInt(7) + 7; + int h = 4 + random->nextInt(3) / 2; + int d = random->nextInt(7) + 7; int x0 = x - w / 2; int y0 = y; int z0 = z - d / 2; int doorSide = random->nextInt(4); - if (doorSide < 2) d += 2; - else w += 2; + if (doorSide < 2) + d += 2; + else + w += 2; - for (int xx = x0; xx < x0 + w; xx++) - { - for (int zz = z0; zz < z0 + d; zz++) - { - Material *m = level->getMaterial(xx, y - 1, zz); + for (int xx = x0; xx < x0 + w; xx++) { + for (int zz = z0; zz < z0 + d; zz++) { + Material* m = level->getMaterial(xx, y - 1, zz); if (!m->blocksMotion() || m == Material::ice) return false; bool ok = false; @@ -35,34 +34,24 @@ bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) if (doorSide == 2 && zz < z0 + 2) ok = true; if (doorSide == 3 && zz > z0 + d - 1 - 2) ok = true; int t = level->getTile(xx, y, zz); - if (ok) - { + if (ok) { if (t != 0) return false; + } else { + if (t == Tile::stoneBrick_Id || t == Tile::mossStone_Id) + return false; } - else - { - if (t == Tile::stoneBrick_Id || t == Tile::mossStone_Id) return false; - } - } } - if (doorSide == 0) - { + if (doorSide == 0) { x0++; w--; - } - else if (doorSide == 1) - { + } else if (doorSide == 1) { w--; - } - else if (doorSide == 2) - { + } else if (doorSide == 2) { z0++; d--; - } - else if (doorSide == 3) - { + } else if (doorSide == 3) { d--; } @@ -70,51 +59,42 @@ bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) int xx1 = x0 + w - 1; int zz0 = z0; int zz1 = z0 + d - 1; - if (doorSide >= 2) - { - xx0++; - xx1--; + if (doorSide >= 2) { + xx0++; + xx1--; + } else { + zz0++; + zz1--; } - else - { - zz0++; - zz1--; - } - for (int xx = x0; xx < x0 + w; xx++) - { - for (int zz = z0; zz < z0 + d; zz++) - { + for (int xx = x0; xx < x0 + w; xx++) { + for (int zz = z0; zz < z0 + d; zz++) { int ho = h; int d1 = zz - z0; int d2 = (z0 + d - 1) - zz; - if (doorSide < 2) - { + if (doorSide < 2) { d1 = xx - x0; d2 = (x0 + w - 1) - xx; } if (d2 < d1) d1 = d2; h += d1; - for (int yy = y0 - 1; yy < y0 + h; yy++) - { + for (int yy = y0 - 1; yy < y0 + h; yy++) { int material = -1; - if (yy == y0 + h - 1) - { + if (yy == y0 + h - 1) { material = Tile::wood_Id; - } - else if (xx >= xx0 && xx <= xx1 && zz >= zz0 && zz <= zz1) - { + } else if (xx >= xx0 && xx <= xx1 && zz >= zz0 && zz <= zz1) { material = 0; - if (yy == y0 - 1 || yy == y0 + h - 1 || xx == xx0 || zz == zz0 || xx == xx1 || zz == zz1) - { - if (yy <= y0 + random->nextInt(3)) material = Tile::mossStone_Id; - else material = Tile::stoneBrick_Id; + if (yy == y0 - 1 || yy == y0 + h - 1 || xx == xx0 || + zz == zz0 || xx == xx1 || zz == zz1) { + if (yy <= y0 + random->nextInt(3)) + material = Tile::mossStone_Id; + else + material = Tile::stoneBrick_Id; } } - if (material >= 0) - { + if (material >= 0) { level->setTileNoUpdate(xx, yy, zz, material); } } @@ -140,8 +120,7 @@ bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) DoorItem::place(level, xx, y0, zz, dir, Tile::door_wood); } - for (int i = 0; i < (w * 2 + d * 2) * 3; i++) - { + for (int i = 0; i < (w * 2 + d * 2) * 3; i++) { int xx = x0 + random->nextInt(w - 4) + 2; int zz = z0 + random->nextInt(d - 4) + 2; int side = random->nextInt(4); @@ -151,11 +130,14 @@ bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) if (side == 2) zz = zz0; if (side == 3) zz = zz1; - if (level->isSolidBlockingTile(xx, y0 + 1, zz)) - { + if (level->isSolidBlockingTile(xx, y0 + 1, zz)) { int count = 0; - if (level->isSolidBlockingTile(xx - 1, y0 + 1, zz) && level->isSolidBlockingTile(xx + 1, y0 + 1, zz)) count++; - if (level->isSolidBlockingTile(xx, y0 + 1, zz - 1) && level->isSolidBlockingTile(xx, y0 + 1, zz + 1)) count++; + if (level->isSolidBlockingTile(xx - 1, y0 + 1, zz) && + level->isSolidBlockingTile(xx + 1, y0 + 1, zz)) + count++; + if (level->isSolidBlockingTile(xx, y0 + 1, zz - 1) && + level->isSolidBlockingTile(xx, y0 + 1, zz + 1)) + count++; if (count == 1) { level->setTileNoUpdate(xx, y0 + 1, zz, Tile::glass_Id); } @@ -164,30 +146,27 @@ bool HouseFeature::place(Level *level, Random *random, int x, int y, int z) int ww = xx1 - xx0; int dd = zz1 - zz0; - for (int i = 0; i < (ww * 2 + dd * 2); i++) - { + for (int i = 0; i < (ww * 2 + dd * 2); i++) { int xx = xx0 + random->nextInt(ww - 1) + 1; int zz = zz0 + random->nextInt(dd - 1) + 1; int yy = y0; - if (level->getTile(xx, yy + 2, zz) == 0) - { + if (level->getTile(xx, yy + 2, zz) == 0) { int count = 0; if (level->isSolidBlockingTile(xx - 1, yy + 2, zz)) count++; if (level->isSolidBlockingTile(xx + 1, yy + 2, zz)) count++; if (level->isSolidBlockingTile(xx, yy + 2, zz - 1)) count++; if (level->isSolidBlockingTile(xx, yy + 2, zz + 1)) count++; - if (count == 1) - { + if (count == 1) { level->setTileNoUpdate(xx, y0 + 2, zz, Tile::torch_Id); } } } - std::shared_ptr(pz) = std::shared_ptr(new PigZombie(level)); + std::shared_ptr(pz) = + std::shared_ptr(new PigZombie(level)); pz->moveTo(x0 + w / 2.0 + 0.5, y0 + 0.5, z0 + d / 2.0 + 0.5, 0, 0); level->addEntity(pz); return true; - } diff --git a/Minecraft.World/WorldGen/Features/HouseFeature.h b/Minecraft.World/WorldGen/Features/HouseFeature.h index 893699451..1c9f9f36c 100644 --- a/Minecraft.World/WorldGen/Features/HouseFeature.h +++ b/Minecraft.World/WorldGen/Features/HouseFeature.h @@ -2,8 +2,7 @@ #include "Feature.h" #include "../../Blocks/Material.h" -class HouseFeature : public Feature -{ +class HouseFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/HugeMushroomFeature.cpp b/Minecraft.World/WorldGen/Features/HugeMushroomFeature.cpp index a92f0f266..e6944a6ad 100644 --- a/Minecraft.World/WorldGen/Features/HugeMushroomFeature.cpp +++ b/Minecraft.World/WorldGen/Features/HugeMushroomFeature.cpp @@ -3,44 +3,35 @@ #include "../../Headers/net.minecraft.world.level.h" #include "../../Headers/net.minecraft.world.level.tile.h" -HugeMushroomFeature::HugeMushroomFeature(int forcedType) : Feature(true) -{ - this->forcedType = forcedType; +HugeMushroomFeature::HugeMushroomFeature(int forcedType) : Feature(true) { + this->forcedType = forcedType; } -HugeMushroomFeature::HugeMushroomFeature() : Feature(false) -{ - this->forcedType = -1; +HugeMushroomFeature::HugeMushroomFeature() : Feature(false) { + this->forcedType = -1; } -bool HugeMushroomFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool HugeMushroomFeature::place(Level* level, Random* random, int x, int y, + int z) { int type = random->nextInt(2); if (forcedType >= 0) type = forcedType; - + int treeHeight = random->nextInt(3) + 4; bool free = true; - if (y < 1 || y + treeHeight + 1 >= Level::maxBuildHeight) return false; + if (y < 1 || y + treeHeight + 1 >= Level::maxBuildHeight) return false; - for (int yy = y; yy <= y + 1 + treeHeight; yy++) - { + for (int yy = y; yy <= y + 1 + treeHeight; yy++) { int r = 3; - if (yy <= (y + 3) ) r = 0; - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::maxBuildHeight) - { + if (yy <= (y + 3)) r = 0; + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::maxBuildHeight) { int tt = level->getTile(xx, yy, zz); - if (tt != 0 && tt != Tile::leaves_Id) - { - free = false; - } - } - else - { + if (tt != 0 && tt != Tile::leaves_Id) { + free = false; + } + } else { free = false; } } @@ -48,39 +39,37 @@ bool HugeMushroomFeature::place(Level *level, Random *random, int x, int y, int } int belowTile = level->getTile(x, y - 1, z); - if (belowTile != Tile::dirt_Id && belowTile != Tile::grass_Id && belowTile != Tile::mycel_Id) - { + if (belowTile != Tile::dirt_Id && belowTile != Tile::grass_Id && + belowTile != Tile::mycel_Id) { return false; } if (!free) return false; - //if (!Tile::mushroom1->mayPlace(level, x, y, z)) return false; + // if (!Tile::mushroom1->mayPlace(level, x, y, z)) return false; - //placeBlock(level, x, y - 1, z, Tile::dirt_Id, 0); + // placeBlock(level, x, y - 1, z, Tile::dirt_Id, 0); int low = y + treeHeight; if (type == 1) { low = y + treeHeight - 3; } - for (int yy = low; yy <= y + treeHeight; yy++) - { + for (int yy = low; yy <= y + treeHeight; yy++) { int offs = 1; if (yy < y + treeHeight) offs += 1; if (type == 0) offs = 3; - for (int xx = x - offs; xx <= x + offs; xx++) - { - for (int zz = z - offs; zz <= z + offs; zz++) - { + for (int xx = x - offs; xx <= x + offs; xx++) { + for (int zz = z - offs; zz <= z + offs; zz++) { int data = 5; if (xx == x - offs) data--; if (xx == x + offs) data++; if (zz == z - offs) data -= 3; if (zz == z + offs) data += 3; - if (type == 0 || yy < y + treeHeight) - { - if ((xx == x - offs || xx == x + offs) && (zz == z - offs || zz == z + offs)) continue; + if (type == 0 || yy < y + treeHeight) { + if ((xx == x - offs || xx == x + offs) && + (zz == z - offs || zz == z + offs)) + continue; if (xx == x - (offs - 1) && zz == z - offs) data = 1; if (xx == x - offs && zz == z - (offs - 1)) data = 1; @@ -95,17 +84,18 @@ bool HugeMushroomFeature::place(Level *level, Random *random, int x, int y, int } if (data == 5 && yy < y + treeHeight) data = 0; - if (data != 0 || y >= y + treeHeight - 1) - { - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::hugeMushroom1_Id + type, data); + if (data != 0 || y >= y + treeHeight - 1) { + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, + Tile::hugeMushroom1_Id + type, data); } } } } - for (int hh = 0; hh < treeHeight; hh++) - { + for (int hh = 0; hh < treeHeight; hh++) { int t = level->getTile(x, y + hh, z); - if (!Tile::solid[t]) placeBlock(level, x, y + hh, z, Tile::hugeMushroom1_Id + type, 10); + if (!Tile::solid[t]) + placeBlock(level, x, y + hh, z, Tile::hugeMushroom1_Id + type, 10); } return true; } diff --git a/Minecraft.World/WorldGen/Features/HugeMushroomFeature.h b/Minecraft.World/WorldGen/Features/HugeMushroomFeature.h index 6523c5fb3..dd2a4f7d9 100644 --- a/Minecraft.World/WorldGen/Features/HugeMushroomFeature.h +++ b/Minecraft.World/WorldGen/Features/HugeMushroomFeature.h @@ -1,13 +1,12 @@ #pragma once #include "Feature.h" -class HugeMushroomFeature : public Feature -{ +class HugeMushroomFeature : public Feature { private: - int forcedType; + int forcedType; public: - HugeMushroomFeature(int forcedType); - HugeMushroomFeature(); - virtual bool place(Level *level, Random *random, int x, int y, int z); + HugeMushroomFeature(int forcedType); + HugeMushroomFeature(); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/LakeFeature.cpp b/Minecraft.World/WorldGen/Features/LakeFeature.cpp index ad07da9d4..513047a5d 100644 --- a/Minecraft.World/WorldGen/Features/LakeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/LakeFeature.cpp @@ -4,51 +4,45 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Headers/net.minecraft.world.level.biome.h" -LakeFeature::LakeFeature(int tile) -{ - this->tile = tile; -} +LakeFeature::LakeFeature(int tile) { this->tile = tile; } -bool LakeFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool LakeFeature::place(Level* level, Random* random, int x, int y, int z) { x -= 8; z -= 8; while (y > 5 && level->isEmptyTile(x, y, z)) { y--; } - if (y <= 4) - { - return false; - } + if (y <= 4) { + return false; + } y -= 4; - bool grid[16*16*8] = {0}; + bool grid[16 * 16 * 8] = {0}; - LevelGenerationOptions *levelGenOptions = NULL; - if( app.getLevelGenerationOptions() != NULL ) - { - levelGenOptions = app.getLevelGenerationOptions(); + LevelGenerationOptions* levelGenOptions = NULL; + if (app.getLevelGenerationOptions() != NULL) { + levelGenOptions = app.getLevelGenerationOptions(); - int minX = x; - int minY = y; - int minZ = z; - - int maxX = x + 16; - int maxY = y + 8; - int maxZ = z + 16; + int minX = x; + int minY = y; + int minZ = z; - bool intersects = levelGenOptions->checkIntersects(minX, minY, minZ, maxX, maxY, maxZ); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + int maxX = x + 16; + int maxY = y + 8; + int maxZ = z + 16; + + bool intersects = levelGenOptions->checkIntersects(minX, minY, minZ, + maxX, maxY, maxZ); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } int spots = random->nextInt(4) + 4; - for (int i = 0; i < spots; i++) - { + for (int i = 0; i < spots; i++) { double xr = random->nextDouble() * 6 + 3; double yr = random->nextDouble() * 4 + 2; double zr = random->nextDouble() * 6 + 3; @@ -57,12 +51,9 @@ bool LakeFeature::place(Level *level, Random *random, int x, int y, int z) double yp = random->nextDouble() * (8 - yr - 4) + 2 + yr / 2; double zp = random->nextDouble() * (16 - zr - 2) + 1 + zr / 2; - for (int xx = 1; xx < 15; xx++) - { - for (int zz = 1; zz < 15; zz++) - { - for (int yy = 1; yy < 7; yy++) - { + for (int xx = 1; xx < 15; xx++) { + for (int zz = 1; zz < 15; zz++) { + for (int yy = 1; yy < 7; yy++) { double xd = ((xx - xp) / (xr / 2)); double yd = ((yy - yp) / (yr / 2)); double zd = ((zz - zp) / (zr / 2)); @@ -73,85 +64,86 @@ bool LakeFeature::place(Level *level, Random *random, int x, int y, int z) } } - for (int xx = 0; xx < 16; xx++) - { - for (int zz = 0; zz < 16; zz++) - { - for (int yy = 0; yy < 8; yy++) - { - bool check = !grid[((xx) * 16 + (zz)) * 8 + (yy)] && ( - (xx < 15 && grid[((xx + 1) * 16 + (zz)) * 8 + (yy)]) - || (xx > 0 && grid[((xx - 1) * 16 + (zz)) * 8 + (yy)]) - || (zz < 15 && grid[((xx) * 16 + (zz + 1)) * 8 + (yy)]) - || (zz > 0 && grid[((xx) * 16 + (zz - 1)) * 8 + (yy)]) - || (yy < 7 && grid[((xx) * 16 + (zz)) * 8 + (yy + 1)]) - || (yy > 0 && grid[((xx) * 16 + (zz)) * 8 + (yy - 1)])); + for (int xx = 0; xx < 16; xx++) { + for (int zz = 0; zz < 16; zz++) { + for (int yy = 0; yy < 8; yy++) { + bool check = + !grid[((xx) * 16 + (zz)) * 8 + (yy)] && + ((xx < 15 && grid[((xx + 1) * 16 + (zz)) * 8 + (yy)]) || + (xx > 0 && grid[((xx - 1) * 16 + (zz)) * 8 + (yy)]) || + (zz < 15 && grid[((xx) * 16 + (zz + 1)) * 8 + (yy)]) || + (zz > 0 && grid[((xx) * 16 + (zz - 1)) * 8 + (yy)]) || + (yy < 7 && grid[((xx) * 16 + (zz)) * 8 + (yy + 1)]) || + (yy > 0 && grid[((xx) * 16 + (zz)) * 8 + (yy - 1)])); - if (check) - { - Material *m = level->getMaterial(x + xx, y + yy, z + zz); + if (check) { + Material* m = level->getMaterial(x + xx, y + yy, z + zz); if (yy >= 4 && m->isLiquid()) return false; - if (yy < 4 && (!m->isSolid() && level->getTile(x + xx, y + yy, z + zz) != tile)) return false; - + if (yy < 4 && + (!m->isSolid() && + level->getTile(x + xx, y + yy, z + zz) != tile)) + return false; } } } } - for (int xx = 0; xx < 16; xx++) - { - for (int zz = 0; zz < 16; zz++) - { - for (int yy = 0; yy < 8; yy++) - { - if (grid[((xx) * 16 + (zz)) * 8 + (yy)]) - { - level->setTileNoUpdate(x + xx, y + yy, z + zz, yy >= 4 ? 0 : tile); + for (int xx = 0; xx < 16; xx++) { + for (int zz = 0; zz < 16; zz++) { + for (int yy = 0; yy < 8; yy++) { + if (grid[((xx) * 16 + (zz)) * 8 + (yy)]) { + level->setTileNoUpdate(x + xx, y + yy, z + zz, + yy >= 4 ? 0 : tile); } } } } - for (int xx = 0; xx < 16; xx++) - { - for (int zz = 0; zz < 16; zz++) - { - for (int yy = 4; yy < 8; yy++) - { - if (grid[((xx) * 16 + (zz)) * 8 + (yy)]) - { - if (level->getTile(x + xx, y + yy - 1, z + zz) == Tile::dirt_Id && level->getBrightness(LightLayer::Sky, x + xx, y + yy, z + zz) > 0) - { - Biome *b = level->getBiome(x + xx, z + zz); - if (b->topMaterial == Tile::mycel_Id) level->setTileNoUpdate(x + xx, y + yy - 1, z + zz, Tile::mycel_Id); - else level->setTileNoUpdate(x + xx, y + yy - 1, z + zz, Tile::grass_Id); + for (int xx = 0; xx < 16; xx++) { + for (int zz = 0; zz < 16; zz++) { + for (int yy = 4; yy < 8; yy++) { + if (grid[((xx) * 16 + (zz)) * 8 + (yy)]) { + if (level->getTile(x + xx, y + yy - 1, z + zz) == + Tile::dirt_Id && + level->getBrightness(LightLayer::Sky, x + xx, y + yy, + z + zz) > 0) { + Biome* b = level->getBiome(x + xx, z + zz); + if (b->topMaterial == Tile::mycel_Id) + level->setTileNoUpdate(x + xx, y + yy - 1, z + zz, + Tile::mycel_Id); + else + level->setTileNoUpdate(x + xx, y + yy - 1, z + zz, + Tile::grass_Id); } } } } } - if (Tile::tiles[tile]->material == Material::lava) - { - for (int xx = 0; xx < 16; xx++) - { - for (int zz = 0; zz < 16; zz++) - { - for (int yy = 0; yy < 8; yy++) - { - bool check = !grid[((xx) * 16 + (zz)) * 8 + (yy)] && ( - (xx < 15 && grid[(((xx + 1) * 16 + (zz)) * 8 + (yy))]) - || (xx > 0 && grid[(((xx - 1) * 16 + (zz)) * 8 + (yy))]) - || (zz < 15 && grid[(((xx) * 16 + (zz + 1)) * 8 + (yy))]) - || (zz > 0 && grid[(((xx) * 16 + (zz - 1)) * 8 + (yy))]) - || (yy < 7 && grid[(((xx) * 16 + (zz)) * 8 + (yy + 1))]) - || (yy > 0 && grid[(((xx) * 16 + (zz)) * 8 + (yy - 1))])); + if (Tile::tiles[tile]->material == Material::lava) { + for (int xx = 0; xx < 16; xx++) { + for (int zz = 0; zz < 16; zz++) { + for (int yy = 0; yy < 8; yy++) { + bool check = + !grid[((xx) * 16 + (zz)) * 8 + (yy)] && + ((xx < 15 && + grid[(((xx + 1) * 16 + (zz)) * 8 + (yy))]) || + (xx > 0 && + grid[(((xx - 1) * 16 + (zz)) * 8 + (yy))]) || + (zz < 15 && + grid[(((xx) * 16 + (zz + 1)) * 8 + (yy))]) || + (zz > 0 && + grid[(((xx) * 16 + (zz - 1)) * 8 + (yy))]) || + (yy < 7 && + grid[(((xx) * 16 + (zz)) * 8 + (yy + 1))]) || + (yy > 0 && grid[(((xx) * 16 + (zz)) * 8 + (yy - 1))])); - if (check) - { - if ((yy<4 || random->nextInt(2)!=0) && level->getMaterial(x + xx, y + yy, z + zz)->isSolid()) - { - level->setTileNoUpdate(x + xx, y + yy, z + zz, Tile::rock_Id); + if (check) { + if ((yy < 4 || random->nextInt(2) != 0) && + level->getMaterial(x + xx, y + yy, z + zz) + ->isSolid()) { + level->setTileNoUpdate(x + xx, y + yy, z + zz, + Tile::rock_Id); } } } @@ -159,15 +151,14 @@ bool LakeFeature::place(Level *level, Random *random, int x, int y, int z) } } - // 4J - brought forward from 1.8.2 - if (Tile::tiles[tile]->material == Material::water) - { - for (int xx = 0; xx < 16; xx++) - { - for (int zz = 0; zz < 16; zz++) - { + // 4J - brought forward from 1.8.2 + if (Tile::tiles[tile]->material == Material::water) { + for (int xx = 0; xx < 16; xx++) { + for (int zz = 0; zz < 16; zz++) { int yy = 4; - if (level->shouldFreezeIgnoreNeighbors(x + xx, y + yy, z + zz)) level->setTileNoUpdate(x + xx, y + yy, z + zz, Tile::ice_Id); + if (level->shouldFreezeIgnoreNeighbors(x + xx, y + yy, z + zz)) + level->setTileNoUpdate(x + xx, y + yy, z + zz, + Tile::ice_Id); } } } diff --git a/Minecraft.World/WorldGen/Features/LakeFeature.h b/Minecraft.World/WorldGen/Features/LakeFeature.h index 4aad2ca53..197eea9e2 100644 --- a/Minecraft.World/WorldGen/Features/LakeFeature.h +++ b/Minecraft.World/WorldGen/Features/LakeFeature.h @@ -2,13 +2,12 @@ #include "Feature.h" #include "../../Blocks/Material.h" -class LakeFeature : public Feature -{ +class LakeFeature : public Feature { private: - int tile; + int tile; public: - LakeFeature (int tile); + LakeFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/LargeCaveFeature.cpp b/Minecraft.World/WorldGen/Features/LargeCaveFeature.cpp index 6d5f91f3a..30a1c1fb7 100644 --- a/Minecraft.World/WorldGen/Features/LargeCaveFeature.cpp +++ b/Minecraft.World/WorldGen/Features/LargeCaveFeature.cpp @@ -4,13 +4,18 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "LargeCaveFeature.h" -void LargeCaveFeature::addRoom(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom) -{ - addTunnel(seed, xOffs, zOffs, blocks, xRoom, yRoom, zRoom, 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); +void LargeCaveFeature::addRoom(__int64 seed, int xOffs, int zOffs, + byteArray blocks, double xRoom, double yRoom, + double zRoom) { + addTunnel(seed, xOffs, zOffs, blocks, xRoom, yRoom, zRoom, + 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); } -void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale) -{ +void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, + byteArray blocks, double xCave, double yCave, + double zCave, float thickness, float yRot, + float xRot, int step, int dist, + double yScale) { double xMid = xOffs * 16 + 8; double zMid = zOffs * 16 + 8; @@ -18,25 +23,21 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b float xRota = 0; Random random = Random(seed); - if (dist <= 0) - { + if (dist <= 0) { int max = radius * 16 - 16; dist = max - random.nextInt(max / 4); } bool singleStep = false; - if (step == -1) - { + if (step == -1) { step = dist / 2; singleStep = true; } - int splitPoint = random.nextInt(dist / 2) + dist / 4; bool steep = random.nextInt(6) == 0; - for (; step < dist; step++) - { + for (; step < dist; step++) { double rad = 1.5 + (Mth::sin(step * PI / dist) * thickness) * 1; double yRad = rad * yScale; @@ -46,12 +47,9 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b yCave += xs; zCave += Mth::sin(yRot) * xc; - if (steep) - { + if (steep) { xRot *= 0.92f; - } - else - { + } else { xRot *= 0.7f; } xRot += xRota * 0.1f; @@ -59,14 +57,18 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b xRota *= 0.90f; yRota *= 0.75f; - xRota += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2; - yRota += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4; + xRota += + (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2; + yRota += + (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4; - - if (!singleStep && step == splitPoint && thickness > 1 && dist > 0) - { - addTunnel(random.nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave, random.nextFloat() * 0.5f + 0.5f, yRot - PI / 2, xRot / 3, step, dist, 1.0); - addTunnel(random.nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave, random.nextFloat() * 0.5f + 0.5f, yRot + PI / 2, xRot / 3, step, dist, 1.0); + if (!singleStep && step == splitPoint && thickness > 1 && dist > 0) { + addTunnel(random.nextLong(), xOffs, zOffs, blocks, xCave, yCave, + zCave, random.nextFloat() * 0.5f + 0.5f, yRot - PI / 2, + xRot / 3, step, dist, 1.0); + addTunnel(random.nextLong(), xOffs, zOffs, blocks, xCave, yCave, + zCave, random.nextFloat() * 0.5f + 0.5f, yRot + PI / 2, + xRot / 3, step, dist, 1.0); return; } if (!singleStep && random.nextInt(4) == 0) continue; @@ -75,13 +77,14 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b double zd = zCave - zMid; double remaining = dist - step; double rr = (thickness + 2) + 16; - if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) - { + if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) { return; } } - if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) continue; + if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || + xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) + continue; int x0 = Mth::floor(xCave - rad) - xOffs * 16 - 1; int x1 = Mth::floor(xCave + rad) - xOffs * 16 + 1; @@ -102,20 +105,17 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b if (z1 > 16) z1 = 16; bool detectedWater = false; - for (int xx = x0; !detectedWater && xx < x1; xx++) - { - for (int zz = z0; !detectedWater && zz < z1; zz++) - { - for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) - { + for (int xx = x0; !detectedWater && xx < x1; xx++) { + for (int zz = z0; !detectedWater && zz < z1; zz++) { + for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) { int p = (xx * 16 + zz) * Level::genDepth + yy; if (yy < 0 || yy >= Level::genDepth) continue; - if (blocks[p] == Tile::water_Id || blocks[p] == Tile::calmWater_Id) - { + if (blocks[p] == Tile::water_Id || + blocks[p] == Tile::calmWater_Id) { detectedWater = true; } - if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && zz != z1 - 1) - { + if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && + zz != z1 - 1) { yy = y0; } } @@ -123,33 +123,32 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b } if (detectedWater) continue; - for (int xx = x0; xx < x1; xx++) - { + for (int xx = x0; xx < x1; xx++) { double xd = ((xx + xOffs * 16 + 0.5) - xCave) / rad; - for (int zz = z0; zz < z1; zz++) - { + for (int zz = z0; zz < z1; zz++) { double zd = ((zz + zOffs * 16 + 0.5) - zCave) / rad; int p = (xx * 16 + zz) * Level::genDepth + y1; bool hasGrass = false; - if (xd * xd + zd * zd < 1) - { - for (int yy = y1 - 1; yy >= y0; yy--) - { + if (xd * xd + zd * zd < 1) { + for (int yy = y1 - 1; yy >= y0; yy--) { double yd = (yy + 0.5 - yCave) / yRad; - if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) - { + if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) { int block = blocks[p]; if (block == Tile::grass_Id) hasGrass = true; - if (block == Tile::rock_Id || block == Tile::dirt_Id || block == Tile::grass_Id) - { - if (yy < 10) - { - blocks[p] = (uint8_t) Tile::lava_Id; - } - else - { - blocks[p] = (uint8_t) 0; - if (hasGrass && blocks[p - 1] == Tile::dirt_Id) blocks[p - 1] = (uint8_t) level->getBiome(xx + xOffs * 16, zz + zOffs * 16)->topMaterial; + if (block == Tile::rock_Id || + block == Tile::dirt_Id || + block == Tile::grass_Id) { + if (yy < 10) { + blocks[p] = (uint8_t)Tile::lava_Id; + } else { + blocks[p] = (uint8_t)0; + if (hasGrass && + blocks[p - 1] == Tile::dirt_Id) + blocks[p - 1] = + (uint8_t)level + ->getBiome(xx + xOffs * 16, + zz + zOffs * 16) + ->topMaterial; } } } @@ -160,37 +159,35 @@ void LargeCaveFeature::addTunnel(__int64 seed, int xOffs, int zOffs, byteArray b } if (singleStep) break; } - } -void LargeCaveFeature::addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) -{ - int caves = random->nextInt(random->nextInt(random->nextInt(40) + 1) + 1); +void LargeCaveFeature::addFeature(Level* level, int x, int z, int xOffs, + int zOffs, byteArray blocks) { + int caves = random->nextInt(random->nextInt(random->nextInt(40) + 1) + 1); if (random->nextInt(15) != 0) caves = 0; - for (int cave = 0; cave < caves; cave++) - { + for (int cave = 0; cave < caves; cave++) { double xCave = x * 16 + random->nextInt(16); - double yCave = random->nextInt(random->nextInt(Level::genDepth - 8) + 8); + double yCave = + random->nextInt(random->nextInt(Level::genDepth - 8) + 8); double zCave = z * 16 + random->nextInt(16); int tunnels = 1; - if (random->nextInt(4) == 0) - { - addRoom(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave); + if (random->nextInt(4) == 0) { + addRoom(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, + zCave); tunnels += random->nextInt(4); } - for (int i = 0; i < tunnels; i++) - { - + for (int i = 0; i < tunnels; i++) { float yRot = random->nextFloat() * PI * 2; float xRot = ((random->nextFloat() - 0.5f) * 2) / 8; float thickness = random->nextFloat() * 2 + random->nextFloat(); - if (random->nextInt(10) == 0) thickness *= random->nextFloat() * random->nextFloat() * 3 + 1; + if (random->nextInt(10) == 0) + thickness *= random->nextFloat() * random->nextFloat() * 3 + 1; - addTunnel(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, zCave, thickness, yRot, xRot, 0, 0, 1.0); + addTunnel(random->nextLong(), xOffs, zOffs, blocks, xCave, yCave, + zCave, thickness, yRot, xRot, 0, 0, 1.0); } } - } diff --git a/Minecraft.World/WorldGen/Features/LargeCaveFeature.h b/Minecraft.World/WorldGen/Features/LargeCaveFeature.h index 5188aca72..7e60aaf1e 100644 --- a/Minecraft.World/WorldGen/Features/LargeCaveFeature.h +++ b/Minecraft.World/WorldGen/Features/LargeCaveFeature.h @@ -2,10 +2,13 @@ #include "LargeFeature.h" -class LargeCaveFeature : public LargeFeature -{ +class LargeCaveFeature : public LargeFeature { protected: - void addRoom(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom); - void addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale); - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks); + void addRoom(__int64 seed, int xOffs, int zOffs, byteArray blocks, + double xRoom, double yRoom, double zRoom); + void addTunnel(__int64 seed, int xOffs, int zOffs, byteArray blocks, + double xCave, double yCave, double zCave, float thickness, + float yRot, float xRot, int step, int dist, double yScale); + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks); }; diff --git a/Minecraft.World/WorldGen/Features/LargeFeature.cpp b/Minecraft.World/WorldGen/Features/LargeFeature.cpp index caf3d040e..10e3b57be 100644 --- a/Minecraft.World/WorldGen/Features/LargeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/LargeFeature.cpp @@ -4,32 +4,26 @@ const std::wstring LargeFeature::STRONGHOLD = L"StrongHold"; -LargeFeature::LargeFeature() -{ - radius = 8; - random = new Random(); +LargeFeature::LargeFeature() { + radius = 8; + random = new Random(); } -LargeFeature::~LargeFeature() -{ - delete random; -} +LargeFeature::~LargeFeature() { delete random; } -void LargeFeature::apply(ChunkSource *ChunkSource, Level *level, int xOffs, int zOffs, byteArray blocks) -{ +void LargeFeature::apply(ChunkSource* ChunkSource, Level* level, int xOffs, + int zOffs, byteArray blocks) { int r = radius; - this->level = level; + this->level = level; random->setSeed(level->getSeed()); __int64 xScale = random->nextLong(); __int64 zScale = random->nextLong(); - for (int x = xOffs - r; x <= xOffs + r; x++) - { - for (int z = zOffs - r; z <= zOffs + r; z++) - { - int64_t xx = (uint64_t) x * xScale; - int64_t zz = (uint64_t) z * zScale; + for (int x = xOffs - r; x <= xOffs + r; x++) { + for (int z = zOffs - r; z <= zOffs + r; z++) { + int64_t xx = (uint64_t)x * xScale; + int64_t zz = (uint64_t)z * zScale; random->setSeed(xx ^ zz ^ level->getSeed()); addFeature(level, x, z, xOffs, zOffs, blocks); } diff --git a/Minecraft.World/WorldGen/Features/LargeFeature.h b/Minecraft.World/WorldGen/Features/LargeFeature.h index b35fc566b..075c28f88 100644 --- a/Minecraft.World/WorldGen/Features/LargeFeature.h +++ b/Minecraft.World/WorldGen/Features/LargeFeature.h @@ -3,21 +3,23 @@ class Level; -class LargeFeature -{ +class LargeFeature { public: - static const std::wstring STRONGHOLD; + static const std::wstring STRONGHOLD; + protected: int radius; - Random *random; - Level *level; + Random* random; + Level* level; public: - LargeFeature(); - virtual ~LargeFeature(); + LargeFeature(); + virtual ~LargeFeature(); - virtual void apply(ChunkSource *ChunkSource, Level *level, int xOffs, int zOffs, byteArray blocks); + virtual void apply(ChunkSource* ChunkSource, Level* level, int xOffs, + int zOffs, byteArray blocks); protected: - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) {} + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks) {} }; diff --git a/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.cpp b/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.cpp index 9f042141b..8778e6ca2 100644 --- a/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.cpp +++ b/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.cpp @@ -3,39 +3,38 @@ #include "LargeHellCaveFeature.h" #include "../../Headers/net.minecraft.world.level.tile.h" -void LargeHellCaveFeature::addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom) -{ - addTunnel(xOffs, zOffs, blocks, xRoom, yRoom, zRoom, 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); +void LargeHellCaveFeature::addRoom(int xOffs, int zOffs, byteArray blocks, + double xRoom, double yRoom, double zRoom) { + addTunnel(xOffs, zOffs, blocks, xRoom, yRoom, zRoom, + 1 + random->nextFloat() * 6, 0, 0, -1, -1, 0.5); } -void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale) -{ +void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, + double xCave, double yCave, double zCave, + float thickness, float yRot, float xRot, + int step, int dist, double yScale) { double xMid = xOffs * 16 + 8; double zMid = zOffs * 16 + 8; float yRota = 0; float xRota = 0; - Random *random = new Random(this->random->nextLong()); + Random* random = new Random(this->random->nextLong()); - if (dist <= 0) - { + if (dist <= 0) { int max = radius * 16 - 16; dist = max - random->nextInt(max / 4); } bool singleStep = false; - if (step == -1) - { + if (step == -1) { step = dist / 2; singleStep = true; } - int splitPoint = random->nextInt(dist / 2) + dist / 4; bool steep = random->nextInt(6) == 0; - for (; step < dist; step++) - { + for (; step < dist; step++) { double rad = 1.5 + (Mth::sin(step * PI / dist) * thickness) * 1; double yRad = rad * yScale; @@ -45,12 +44,9 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou yCave += xs; zCave += Mth::sin(yRot) * xc; - if (steep) - { + if (steep) { xRot *= 0.92f; - } - else - { + } else { xRot *= 0.7f; } xRot += xRota * 0.1f; @@ -58,15 +54,19 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou xRota *= 0.90f; yRota *= 0.75f; - xRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 2; - yRota += (random->nextFloat() - random->nextFloat()) * random->nextFloat() * 4; + xRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 2; + yRota += (random->nextFloat() - random->nextFloat()) * + random->nextFloat() * 4; - - if (!singleStep && step == splitPoint && thickness > 1) - { - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, random->nextFloat() * 0.5f + 0.5f, yRot - PI / 2, xRot / 3, step, dist, 1.0); - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, random->nextFloat() * 0.5f + 0.5f, yRot + PI / 2, xRot / 3, step, dist, 1.0); - delete random; + if (!singleStep && step == splitPoint && thickness > 1) { + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, + random->nextFloat() * 0.5f + 0.5f, yRot - PI / 2, + xRot / 3, step, dist, 1.0); + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, + random->nextFloat() * 0.5f + 0.5f, yRot + PI / 2, + xRot / 3, step, dist, 1.0); + delete random; return; } if (!singleStep && random->nextInt(4) == 0) continue; @@ -76,14 +76,15 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou double zd = zCave - zMid; double remaining = dist - step; double rr = (thickness + 2) + 16; - if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) - { - delete random; + if (xd * xd + zd * zd - (remaining * remaining) > rr * rr) { + delete random; return; } } - if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) continue; + if (xCave < xMid - 16 - rad * 2 || zCave < zMid - 16 - rad * 2 || + xCave > xMid + 16 + rad * 2 || zCave > zMid + 16 + rad * 2) + continue; int x0 = Mth::floor(xCave - rad) - xOffs * 16 - 1; int x1 = Mth::floor(xCave + rad) - xOffs * 16 + 1; @@ -104,20 +105,17 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou if (z1 > 16) z1 = 16; bool detectedWater = false; - for (int xx = x0; !detectedWater && xx < x1; xx++) - { - for (int zz = z0; !detectedWater && zz < z1; zz++) - { - for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) - { + for (int xx = x0; !detectedWater && xx < x1; xx++) { + for (int zz = z0; !detectedWater && zz < z1; zz++) { + for (int yy = y1 + 1; !detectedWater && yy >= y0 - 1; yy--) { int p = (xx * 16 + zz) * Level::genDepth + yy; if (yy < 0 || yy >= Level::genDepth) continue; - if (blocks[p] == Tile::lava_Id || blocks[p] == Tile::calmLava_Id) - { + if (blocks[p] == Tile::lava_Id || + blocks[p] == Tile::calmLava_Id) { detectedWater = true; } - if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && zz != z1 - 1) - { + if (yy != y0 - 1 && xx != x0 && xx != x1 - 1 && zz != z0 && + zz != z1 - 1) { yy = y0; } } @@ -125,22 +123,18 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou } if (detectedWater) continue; - for (int xx = x0; xx < x1; xx++) - { + for (int xx = x0; xx < x1; xx++) { double xd = ((xx + xOffs * 16 + 0.5) - xCave) / rad; - for (int zz = z0; zz < z1; zz++) - { + for (int zz = z0; zz < z1; zz++) { double zd = ((zz + zOffs * 16 + 0.5) - zCave) / rad; int p = (xx * 16 + zz) * Level::genDepth + y1; - for (int yy = y1 - 1; yy >= y0; yy--) - { + for (int yy = y1 - 1; yy >= y0; yy--) { double yd = (yy + 0.5 - yCave) / yRad; - if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) - { + if (yd > -0.7 && xd * xd + yd * yd + zd * zd < 1) { int block = blocks[p]; - if (block == Tile::hellRock_Id || block == Tile::dirt_Id || block == Tile::grass_Id) - { - blocks[p] = (uint8_t) 0; + if (block == Tile::hellRock_Id || + block == Tile::dirt_Id || block == Tile::grass_Id) { + blocks[p] = (uint8_t)0; } } p--; @@ -149,17 +143,15 @@ void LargeHellCaveFeature::addTunnel(int xOffs, int zOffs, byteArray blocks, dou } if (singleStep) break; } - delete random; + delete random; } - -void LargeHellCaveFeature::addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) -{ +void LargeHellCaveFeature::addFeature(Level* level, int x, int z, int xOffs, + int zOffs, byteArray blocks) { int caves = random->nextInt(random->nextInt(random->nextInt(10) + 1) + 1); if (random->nextInt(5) != 0) caves = 0; - for (int cave = 0; cave < caves; cave++) - { + for (int cave = 0; cave < caves; cave++) { double xCave = x * 16 + random->nextInt(16); double yCave = random->nextInt(Level::genDepth); double zCave = z * 16 + random->nextInt(16); @@ -171,14 +163,12 @@ void LargeHellCaveFeature::addFeature(Level *level, int x, int z, int xOffs, int } for (int i = 0; i < tunnels; i++) { - float yRot = random->nextFloat() * PI * 2; float xRot = ((random->nextFloat() - 0.5f) * 2) / 8; float thickness = random->nextFloat() * 2 + random->nextFloat(); - addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, thickness*2, yRot, xRot, 0, 0, 0.5); + addTunnel(xOffs, zOffs, blocks, xCave, yCave, zCave, thickness * 2, + yRot, xRot, 0, 0, 0.5); } } } - - diff --git a/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.h b/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.h index 53d336928..b8b59f62c 100644 --- a/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.h +++ b/Minecraft.World/WorldGen/Features/LargeHellCaveFeature.h @@ -2,10 +2,13 @@ #include "LargeFeature.h" -class LargeHellCaveFeature : public LargeFeature -{ +class LargeHellCaveFeature : public LargeFeature { protected: - void addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, double yRoom, double zRoom); - void addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, double yCave, double zCave, float thickness, float yRot, float xRot, int step, int dist, double yScale); - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks); + void addRoom(int xOffs, int zOffs, byteArray blocks, double xRoom, + double yRoom, double zRoom); + void addTunnel(int xOffs, int zOffs, byteArray blocks, double xCave, + double yCave, double zCave, float thickness, float yRot, + float xRot, int step, int dist, double yScale); + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks); }; diff --git a/Minecraft.World/WorldGen/Features/LightGemFeature.cpp b/Minecraft.World/WorldGen/Features/LightGemFeature.cpp index 42ea51be7..bf8b31871 100644 --- a/Minecraft.World/WorldGen/Features/LightGemFeature.cpp +++ b/Minecraft.World/WorldGen/Features/LightGemFeature.cpp @@ -3,22 +3,19 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "LightGemFeature.h" -bool LightGemFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool LightGemFeature::place(Level* level, Random* random, int x, int y, int z) { if (!level->isEmptyTile(x, y, z)) return false; if (level->getTile(x, y + 1, z) != Tile::hellRock_Id) return false; level->setTile(x, y, z, Tile::lightGem_Id); - for (int i = 0; i < 1500; i++) - { + for (int i = 0; i < 1500; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y - random->nextInt(12); int z2 = z + random->nextInt(8) - random->nextInt(8); if (level->getTile(x2, y2, z2) != 0) continue; int count = 0; - for (int t = 0; t < 6; t++) - { + for (int t = 0; t < 6; t++) { int tile = 0; if (t == 0) tile = level->getTile(x2 - 1, y2, z2); if (t == 1) tile = level->getTile(x2 + 1, y2, z2); diff --git a/Minecraft.World/WorldGen/Features/LightGemFeature.h b/Minecraft.World/WorldGen/Features/LightGemFeature.h index 1eaf5c08a..5ac06dab2 100644 --- a/Minecraft.World/WorldGen/Features/LightGemFeature.h +++ b/Minecraft.World/WorldGen/Features/LightGemFeature.h @@ -1,8 +1,7 @@ #pragma once #include "Feature.h" -class LightGemFeature : public Feature -{ +class LightGemFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MegaTreeFeature.cpp b/Minecraft.World/WorldGen/Features/MegaTreeFeature.cpp index 6c5f2e431..f4270db73 100644 --- a/Minecraft.World/WorldGen/Features/MegaTreeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/MegaTreeFeature.cpp @@ -3,199 +3,200 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "MegaTreeFeature.h" -MegaTreeFeature::MegaTreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType) : Feature(doUpdate), baseHeight(baseHeight), trunkType(trunkType), leafType(leafType) -{ +MegaTreeFeature::MegaTreeFeature(bool doUpdate, int baseHeight, int trunkType, + int leafType) + : Feature(doUpdate), + baseHeight(baseHeight), + trunkType(trunkType), + leafType(leafType) {} + +bool MegaTreeFeature::place(Level* level, Random* random, int x, int y, int z) { + int treeHeight = random->nextInt(3) + baseHeight; + + bool free = true; + if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) return false; + + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + PIXBeginNamedEvent(0, "MegaTreeFeature Checking intersects"); + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - 2, y - 1, z - 2, x + 2, y + treeHeight, z + 2); + PIXEndNamedEvent(); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } + + for (int yy = y; yy <= y + 1 + treeHeight; yy++) { + int r = 2; + if (yy == y) r = 1; + if (yy >= y + 1 + treeHeight - 2) r = 2; + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::maxBuildHeight) { + int tt = level->getTile(xx, yy, zz); + if (tt != 0 && tt != Tile::leaves_Id && + tt != Tile::grass_Id && tt != Tile::dirt_Id && + tt != Tile::treeTrunk_Id && tt != Tile::sapling_Id) + free = false; + } else { + free = false; + } + } + } + } + + if (!free) return false; + + int belowTile = level->getTile(x, y - 1, z); + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::maxBuildHeight - treeHeight - 1) + return false; + + level->setTileNoUpdate(x, y - 1, z, Tile::dirt_Id); + level->setTileNoUpdate(x + 1, y - 1, z, Tile::dirt_Id); + level->setTileNoUpdate(x, y - 1, z + 1, Tile::dirt_Id); + level->setTileNoUpdate(x + 1, y - 1, z + 1, Tile::dirt_Id); + + PIXBeginNamedEvent(0, "MegaTree placing leaves, %d, %d, %d", x, z, + y + treeHeight); + placeLeaves(level, x, z, y + treeHeight, 2, random); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "MegaTree placing branches"); + int branchHeight = y + treeHeight - 2 - random->nextInt(4); + while (branchHeight > y + treeHeight / 2) { + float angle = random->nextFloat() * PI * 2.0f; + int bx = x + (int)(0.5f + Mth::cos(angle) * 4.0f); + int bz = z + (int)(0.5f + Mth::sin(angle) * 4.0f); + placeLeaves(level, bx, bz, branchHeight, 0, random); + + for (int b = 0; b < 5; b++) { + bx = x + (int)(1.5f + Mth::cos(angle) * b); + bz = z + (int)(1.5f + Mth::sin(angle) * b); + placeBlock(level, bx, branchHeight - 3 + b / 2, bz, + Tile::treeTrunk_Id, trunkType); + } + + branchHeight -= 2 + random->nextInt(4); + } + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "MegaTree placing vines"); + for (int hh = 0; hh < treeHeight; hh++) { + int t = level->getTile(x, y + hh, z); + if (t == 0 || t == Tile::leaves_Id) { + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, trunkType); + if (hh > 0) { + if (random->nextInt(3) > 0 && + level->isEmptyTile(x - 1, y + hh, z)) { + placeBlock(level, x - 1, y + hh, z, Tile::vine_Id, + VineTile::VINE_EAST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x, y + hh, z - 1)) { + placeBlock(level, x, y + hh, z - 1, Tile::vine_Id, + VineTile::VINE_SOUTH); + } + } + } + if (hh < (treeHeight - 1)) { + t = level->getTile(x + 1, y + hh, z); + if (t == 0 || t == Tile::leaves_Id) { + placeBlock(level, x + 1, y + hh, z, Tile::treeTrunk_Id, + trunkType); + if (hh > 0) { + if (random->nextInt(3) > 0 && + level->isEmptyTile(x + 2, y + hh, z)) { + placeBlock(level, x + 2, y + hh, z, Tile::vine_Id, + VineTile::VINE_WEST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x + 1, y + hh, z - 1)) { + placeBlock(level, x + 1, y + hh, z - 1, Tile::vine_Id, + VineTile::VINE_SOUTH); + } + } + } + t = level->getTile(x + 1, y + hh, z + 1); + if (t == 0 || t == Tile::leaves_Id) { + placeBlock(level, x + 1, y + hh, z + 1, Tile::treeTrunk_Id, + trunkType); + if (hh > 0) { + if (random->nextInt(3) > 0 && + level->isEmptyTile(x + 2, y + hh, z + 1)) { + placeBlock(level, x + 2, y + hh, z + 1, Tile::vine_Id, + VineTile::VINE_WEST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x + 1, y + hh, z + 2)) { + placeBlock(level, x + 1, y + hh, z + 2, Tile::vine_Id, + VineTile::VINE_NORTH); + } + } + } + t = level->getTile(x, y + hh, z + 1); + if (t == 0 || t == Tile::leaves_Id) { + placeBlock(level, x, y + hh, z + 1, Tile::treeTrunk_Id, + trunkType); + if (hh > 0) { + if (random->nextInt(3) > 0 && + level->isEmptyTile(x - 1, y + hh, z + 1)) { + placeBlock(level, x - 1, y + hh, z + 1, Tile::vine_Id, + VineTile::VINE_EAST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x, y + hh, z + 2)) { + placeBlock(level, x, y + hh, z + 2, Tile::vine_Id, + VineTile::VINE_NORTH); + } + } + } + } + } + PIXEndNamedEvent(); + + return true; } -bool MegaTreeFeature::place(Level *level, Random *random, int x, int y, int z) -{ - int treeHeight = random->nextInt(3) + baseHeight; - - bool free = true; - if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) return false; - - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - PIXBeginNamedEvent(0, "MegaTreeFeature Checking intersects"); - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - 2, y - 1, z - 2, x + 2, y + treeHeight, z + 2); - PIXEndNamedEvent(); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } - - for (int yy = y; yy <= y + 1 + treeHeight; yy++) - { - int r = 2; - if (yy == y) r = 1; - if (yy >= y + 1 + treeHeight - 2) r = 2; - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::maxBuildHeight) - { - int tt = level->getTile(xx, yy, zz); - if (tt != 0 && tt != Tile::leaves_Id && tt != Tile::grass_Id && tt != Tile::dirt_Id && tt != Tile::treeTrunk_Id && tt != Tile::sapling_Id) free = false; - } - else - { - free = false; - } - } - } - } - - if (!free) return false; - - int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::maxBuildHeight - treeHeight - 1) return false; - - level->setTileNoUpdate(x, y - 1, z, Tile::dirt_Id); - level->setTileNoUpdate(x + 1, y - 1, z, Tile::dirt_Id); - level->setTileNoUpdate(x, y - 1, z + 1, Tile::dirt_Id); - level->setTileNoUpdate(x + 1, y - 1, z + 1, Tile::dirt_Id); - - PIXBeginNamedEvent(0,"MegaTree placing leaves, %d, %d, %d", x, z, y+treeHeight); - placeLeaves(level, x, z, y + treeHeight, 2, random); - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"MegaTree placing branches"); - int branchHeight = y + treeHeight - 2 - random->nextInt(4); - while (branchHeight > y + treeHeight / 2) - { - float angle = random->nextFloat() * PI * 2.0f; - int bx = x + (int) (0.5f + Mth::cos(angle) * 4.0f); - int bz = z + (int) (0.5f + Mth::sin(angle) * 4.0f); - placeLeaves(level, bx, bz, branchHeight, 0, random); - - for (int b = 0; b < 5; b++) - { - bx = x + (int) (1.5f + Mth::cos(angle) * b); - bz = z + (int) (1.5f + Mth::sin(angle) * b); - placeBlock(level, bx, branchHeight - 3 + b / 2, bz, Tile::treeTrunk_Id, trunkType); - } - - branchHeight -= 2 + random->nextInt(4); - } - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0, "MegaTree placing vines"); - for (int hh = 0; hh < treeHeight; hh++) - { - int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) - { - placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, trunkType); - if (hh > 0) - { - if (random->nextInt(3) > 0 && level->isEmptyTile(x - 1, y + hh, z)) - { - placeBlock(level, x - 1, y + hh, z, Tile::vine_Id, VineTile::VINE_EAST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x, y + hh, z - 1)) - { - placeBlock(level, x, y + hh, z - 1, Tile::vine_Id, VineTile::VINE_SOUTH); - } - } - } - if (hh < (treeHeight - 1)) - { - t = level->getTile(x + 1, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) - { - placeBlock(level, x + 1, y + hh, z, Tile::treeTrunk_Id, trunkType); - if (hh > 0) - { - if (random->nextInt(3) > 0 && level->isEmptyTile(x + 2, y + hh, z)) - { - placeBlock(level, x + 2, y + hh, z, Tile::vine_Id, VineTile::VINE_WEST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x + 1, y + hh, z - 1)) - { - placeBlock(level, x + 1, y + hh, z - 1, Tile::vine_Id, VineTile::VINE_SOUTH); - } - } - } - t = level->getTile(x + 1, y + hh, z + 1); - if (t == 0 || t == Tile::leaves_Id) - { - placeBlock(level, x + 1, y + hh, z + 1, Tile::treeTrunk_Id, trunkType); - if (hh > 0) - { - if (random->nextInt(3) > 0 && level->isEmptyTile(x + 2, y + hh, z + 1)) - { - placeBlock(level, x + 2, y + hh, z + 1, Tile::vine_Id, VineTile::VINE_WEST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x + 1, y + hh, z + 2)) - { - placeBlock(level, x + 1, y + hh, z + 2, Tile::vine_Id, VineTile::VINE_NORTH); - } - } - } - t = level->getTile(x, y + hh, z + 1); - if (t == 0 || t == Tile::leaves_Id) - { - placeBlock(level, x, y + hh, z + 1, Tile::treeTrunk_Id, trunkType); - if (hh > 0) - { - if (random->nextInt(3) > 0 && level->isEmptyTile(x - 1, y + hh, z + 1)) - { - placeBlock(level, x - 1, y + hh, z + 1, Tile::vine_Id, VineTile::VINE_EAST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x, y + hh, z + 2)) - { - placeBlock(level, x, y + hh, z + 2, Tile::vine_Id, VineTile::VINE_NORTH); - } - } - } - } - } - PIXEndNamedEvent(); - - return true; -} - -void MegaTreeFeature::placeLeaves(Level *level, int x, int z, int topPosition, int baseRadius, Random *random) -{ - int grassHeight = 2; - // 4J Stu - Generate from top down so that we don't have to keep adjusting the heightmaps - for (int yy = topPosition; yy >= topPosition - grassHeight; yy--) - { - int yo = yy - (topPosition); - int radius = baseRadius + 1 - yo; - for (int xx = x - radius; xx <= x + radius + 1; xx++) - { - int xo = xx - (x); - for (int zz = z - radius; zz <= z + radius + 1; zz++) - { - int zo = zz - (z); - if ((xo < 0 && zo < 0) && (xo * xo + zo * zo) > (radius * radius)) - { - continue; - } - if ((xo > 0 || zo > 0) && (xo * xo + zo * zo) > ((radius + 1) * (radius + 1))) - { - continue; - } - if (random->nextInt(4) == 0 && (xo * xo + zo * zo) > ((radius - 1) * (radius - 1))) - { - continue; - } - PIXBeginNamedEvent(0,"Getting tile"); - int t = level->getTile(xx, yy, zz); - PIXEndNamedEvent(); - if (!Tile::solid[t]) - { - PIXBeginNamedEvent(0,"Placing block"); - placeBlock(level, xx, yy, zz, Tile::leaves_Id, leafType); - PIXEndNamedEvent(); - } - } - } - } +void MegaTreeFeature::placeLeaves(Level* level, int x, int z, int topPosition, + int baseRadius, Random* random) { + int grassHeight = 2; + // 4J Stu - Generate from top down so that we don't have to keep adjusting + // the heightmaps + for (int yy = topPosition; yy >= topPosition - grassHeight; yy--) { + int yo = yy - (topPosition); + int radius = baseRadius + 1 - yo; + for (int xx = x - radius; xx <= x + radius + 1; xx++) { + int xo = xx - (x); + for (int zz = z - radius; zz <= z + radius + 1; zz++) { + int zo = zz - (z); + if ((xo < 0 && zo < 0) && + (xo * xo + zo * zo) > (radius * radius)) { + continue; + } + if ((xo > 0 || zo > 0) && + (xo * xo + zo * zo) > ((radius + 1) * (radius + 1))) { + continue; + } + if (random->nextInt(4) == 0 && + (xo * xo + zo * zo) > ((radius - 1) * (radius - 1))) { + continue; + } + PIXBeginNamedEvent(0, "Getting tile"); + int t = level->getTile(xx, yy, zz); + PIXEndNamedEvent(); + if (!Tile::solid[t]) { + PIXBeginNamedEvent(0, "Placing block"); + placeBlock(level, xx, yy, zz, Tile::leaves_Id, leafType); + PIXEndNamedEvent(); + } + } + } + } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MegaTreeFeature.h b/Minecraft.World/WorldGen/Features/MegaTreeFeature.h index 9d02a4cdf..c64e26eb0 100644 --- a/Minecraft.World/WorldGen/Features/MegaTreeFeature.h +++ b/Minecraft.World/WorldGen/Features/MegaTreeFeature.h @@ -2,18 +2,18 @@ #include "Feature.h" -class MegaTreeFeature : public Feature -{ +class MegaTreeFeature : public Feature { private: - const int baseHeight; - const int trunkType; - const int leafType; + const int baseHeight; + const int trunkType; + const int leafType; public: - MegaTreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType); + MegaTreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType); - bool place(Level *level, Random *random, int x, int y, int z); + bool place(Level* level, Random* random, int x, int y, int z); private: - void placeLeaves(Level *level, int x, int z, int topPosition, int baseRadius, Random *random); + void placeLeaves(Level* level, int x, int z, int topPosition, + int baseRadius, Random* random); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MineShaftFeature.cpp b/Minecraft.World/WorldGen/Features/MineShaftFeature.cpp index 4b719366c..1dfd838ff 100644 --- a/Minecraft.World/WorldGen/Features/MineShaftFeature.cpp +++ b/Minecraft.World/WorldGen/Features/MineShaftFeature.cpp @@ -2,22 +2,21 @@ #include "../../Headers/net.minecraft.world.level.levelgen.structure.h" #include "../../Util/JavaMath.h" -bool MineShaftFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) -{ - bool forcePlacement = false; - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - if( levelGenOptions != NULL ) - { - forcePlacement = levelGenOptions->isFeatureChunk(x,z,eFeature_Mineshaft); - } +bool MineShaftFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { + bool forcePlacement = false; + LevelGenerationOptions* levelGenOptions = app.getLevelGenerationOptions(); + if (levelGenOptions != NULL) { + forcePlacement = + levelGenOptions->isFeatureChunk(x, z, eFeature_Mineshaft); + } - return forcePlacement || (random->nextInt(100) == 0 && random->nextInt(80) < std::max(abs(x), abs(z))); + return forcePlacement || (random->nextInt(100) == 0 && + random->nextInt(80) < std::max(abs(x), abs(z))); } -StructureStart *MineShaftFeature::createStructureStart(int x, int z) -{ - // 4J added - app.AddTerrainFeaturePosition(eTerrainFeature_Mineshaft,x,z); +StructureStart* MineShaftFeature::createStructureStart(int x, int z) { + // 4J added + app.AddTerrainFeaturePosition(eTerrainFeature_Mineshaft, x, z); - return new MineShaftStart(level, random, x, z); + return new MineShaftStart(level, random, x, z); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MineShaftFeature.h b/Minecraft.World/WorldGen/Features/MineShaftFeature.h index 698010ec4..b42fed562 100644 --- a/Minecraft.World/WorldGen/Features/MineShaftFeature.h +++ b/Minecraft.World/WorldGen/Features/MineShaftFeature.h @@ -2,9 +2,8 @@ #include "StructureFeature.h" -class MineShaftFeature : public StructureFeature -{ +class MineShaftFeature : public StructureFeature { protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat=false); - virtual StructureStart *createStructureStart(int x, int z); + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat = false); + virtual StructureStart* createStructureStart(int x, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MonsterRoomFeature.cpp b/Minecraft.World/WorldGen/Features/MonsterRoomFeature.cpp index 323bf4507..8369c3093 100644 --- a/Minecraft.World/WorldGen/Features/MonsterRoomFeature.cpp +++ b/Minecraft.World/WorldGen/Features/MonsterRoomFeature.cpp @@ -6,135 +6,141 @@ #include "../../Headers/net.minecraft.world.item.h" #include "MonsterRoomFeature.h" -bool MonsterRoomFeature::place(Level *level, Random *random, int x, int y, int z) -{ - int hr = 3; - int xr = random->nextInt(2) + 2; - int zr = random->nextInt(2) + 2; +bool MonsterRoomFeature::place(Level* level, Random* random, int x, int y, + int z) { + int hr = 3; + int xr = random->nextInt(2) + 2; + int zr = random->nextInt(2) + 2; - int holeCount = 0; - for (int xx = x - xr - 1; xx <= x + xr + 1; xx++) - { - for (int yy = y - 1; yy <= y + hr + 1; yy++) - { - for (int zz = z - zr - 1; zz <= z + zr + 1; zz++) - { - Material *m = level->getMaterial(xx, yy, zz); - if (yy == y - 1 && !m->isSolid()) return false; - if (yy == y + hr + 1 && !m->isSolid()) return false; + int holeCount = 0; + for (int xx = x - xr - 1; xx <= x + xr + 1; xx++) { + for (int yy = y - 1; yy <= y + hr + 1; yy++) { + for (int zz = z - zr - 1; zz <= z + zr + 1; zz++) { + Material* m = level->getMaterial(xx, yy, zz); + if (yy == y - 1 && !m->isSolid()) return false; + if (yy == y + hr + 1 && !m->isSolid()) return false; - if (xx == x - xr - 1 || xx == x + xr + 1 || zz == z - zr - 1 || zz == z + zr + 1) - { - if (yy == y && level->isEmptyTile(xx, yy, zz) && level->isEmptyTile(xx, yy + 1, zz)) - { - holeCount++; - } - } + if (xx == x - xr - 1 || xx == x + xr + 1 || zz == z - zr - 1 || + zz == z + zr + 1) { + if (yy == y && level->isEmptyTile(xx, yy, zz) && + level->isEmptyTile(xx, yy + 1, zz)) { + holeCount++; + } + } + } + } + } - } - } - } + if (holeCount < 1 || holeCount > 5) return false; - if (holeCount < 1 || holeCount > 5) return false; + for (int xx = x - xr - 1; xx <= x + xr + 1; xx++) { + for (int yy = y + hr; yy >= y - 1; yy--) { + for (int zz = z - zr - 1; zz <= z + zr + 1; zz++) { + if (xx == x - xr - 1 || yy == y - 1 || zz == z - zr - 1 || + xx == x + xr + 1 || yy == y + hr + 1 || zz == z + zr + 1) { + if (yy >= 0 && + !level->getMaterial(xx, yy - 1, zz)->isSolid()) { + level->setTile(xx, yy, zz, 0); + } else if (level->getMaterial(xx, yy, zz)->isSolid()) { + if (yy == y - 1 && random->nextInt(4) != 0) { + level->setTile(xx, yy, zz, Tile::mossStone_Id); + } else { + level->setTile(xx, yy, zz, Tile::stoneBrick_Id); + } + } + } else { + level->setTile(xx, yy, zz, 0); + } + } + } + } - for (int xx = x - xr - 1; xx <= x + xr + 1; xx++) - { - for (int yy = y + hr; yy >= y - 1; yy--) - { - for (int zz = z - zr - 1; zz <= z + zr + 1; zz++) - { + for (int cc = 0; cc < 2; cc++) { + for (int i = 0; i < 3; i++) { + int xc = x + random->nextInt(xr * 2 + 1) - xr; + int yc = y; + int zc = z + random->nextInt(zr * 2 + 1) - zr; + if (!level->isEmptyTile(xc, yc, zc)) continue; - if (xx == x - xr - 1 || yy == y - 1 || zz == z - zr - 1 || xx == x + xr + 1 || yy == y + hr + 1 || zz == z + zr + 1) - { - if (yy >= 0 && !level->getMaterial(xx, yy - 1, zz)->isSolid()) - { - level->setTile(xx, yy, zz, 0); - } else if (level->getMaterial(xx, yy, zz)->isSolid()) - { - if (yy == y - 1 && random->nextInt(4) != 0) - { - level->setTile(xx, yy, zz, Tile::mossStone_Id); - } else { - level->setTile(xx, yy, zz, Tile::stoneBrick_Id); - } - } - } else - { - level->setTile(xx, yy, zz, 0); - } - } - } - } + int count = 0; + if (level->getMaterial(xc - 1, yc, zc)->isSolid()) count++; + if (level->getMaterial(xc + 1, yc, zc)->isSolid()) count++; + if (level->getMaterial(xc, yc, zc - 1)->isSolid()) count++; + if (level->getMaterial(xc, yc, zc + 1)->isSolid()) count++; - for (int cc = 0; cc < 2; cc++) - { - for (int i = 0; i < 3; i++) - { - int xc = x + random->nextInt(xr * 2 + 1) - xr; - int yc = y; - int zc = z + random->nextInt(zr * 2 + 1) - zr; - if (!level->isEmptyTile(xc, yc, zc)) continue; + if (count != 1) continue; - int count = 0; - if (level->getMaterial(xc - 1, yc, zc)->isSolid()) count++; - if (level->getMaterial(xc + 1, yc, zc)->isSolid()) count++; - if (level->getMaterial(xc, yc, zc - 1)->isSolid()) count++; - if (level->getMaterial(xc, yc, zc + 1)->isSolid()) count++; + level->setTile(xc, yc, zc, Tile::chest_Id); + std::shared_ptr chest = + std::dynamic_pointer_cast( + level->getTileEntity(xc, yc, zc)); + if (chest != NULL) { + for (int j = 0; j < 8; j++) { + std::shared_ptr item = randomItem(random); + if (item != NULL) + chest->setItem( + random->nextInt(chest->getContainerSize()), item); + } + } - if (count != 1) continue; + break; + } + } - level->setTile(xc, yc, zc, Tile::chest_Id); - std::shared_ptr chest = std::dynamic_pointer_cast( level->getTileEntity(xc, yc, zc) ); - if (chest != NULL ) - { - for (int j = 0; j < 8; j++) - { - std::shared_ptr item = randomItem(random); - if (item != NULL) chest->setItem(random->nextInt(chest->getContainerSize()), item); - } - } - - break; - } - } - - - level->setTile(x, y, z, Tile::mobSpawner_Id); - std::shared_ptr entity = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if( entity != NULL ) - { - entity->setEntityId(randomEntityId(random)); - } - - return true; + level->setTile(x, y, z, Tile::mobSpawner_Id); + std::shared_ptr entity = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (entity != NULL) { + entity->setEntityId(randomEntityId(random)); + } + return true; } -std::shared_ptr MonsterRoomFeature::randomItem(Random *random) -{ - int type = random->nextInt(12); - if (type == 0) return std::shared_ptr( new ItemInstance(Item::saddle) ); - if (type == 1) return std::shared_ptr( new ItemInstance(Item::ironIngot, random->nextInt(4) + 1) ); - if (type == 2) return std::shared_ptr( new ItemInstance(Item::bread) ); - if (type == 3) return std::shared_ptr( new ItemInstance(Item::wheat, random->nextInt(4) + 1) ); - if (type == 4) return std::shared_ptr( new ItemInstance(Item::sulphur, random->nextInt(4) + 1) ); - if (type == 5) return std::shared_ptr( new ItemInstance(Item::string, random->nextInt(4) + 1) ); - if (type == 6) return std::shared_ptr( new ItemInstance(Item::bucket_empty) ); - if (type == 7 && random->nextInt(100) == 0) return std::shared_ptr( new ItemInstance(Item::apple_gold) ); - if (type == 8 && random->nextInt(2) == 0) return std::shared_ptr( new ItemInstance(Item::redStone, random->nextInt(4) + 1) ); - if (type == 9 && random->nextInt(10) == 0) return std::shared_ptr( new ItemInstance( Item::items[Item::record_01->id + random->nextInt(2)]) ); - if (type == 10) return std::shared_ptr( new ItemInstance(Item::dye_powder, 1, DyePowderItem::BROWN) ); - if (type == 11) return Item::enchantedBook->createForRandomLoot(random); +std::shared_ptr MonsterRoomFeature::randomItem(Random* random) { + int type = random->nextInt(12); + if (type == 0) + return std::shared_ptr(new ItemInstance(Item::saddle)); + if (type == 1) + return std::shared_ptr( + new ItemInstance(Item::ironIngot, random->nextInt(4) + 1)); + if (type == 2) + return std::shared_ptr(new ItemInstance(Item::bread)); + if (type == 3) + return std::shared_ptr( + new ItemInstance(Item::wheat, random->nextInt(4) + 1)); + if (type == 4) + return std::shared_ptr( + new ItemInstance(Item::sulphur, random->nextInt(4) + 1)); + if (type == 5) + return std::shared_ptr( + new ItemInstance(Item::string, random->nextInt(4) + 1)); + if (type == 6) + return std::shared_ptr( + new ItemInstance(Item::bucket_empty)); + if (type == 7 && random->nextInt(100) == 0) + return std::shared_ptr( + new ItemInstance(Item::apple_gold)); + if (type == 8 && random->nextInt(2) == 0) + return std::shared_ptr( + new ItemInstance(Item::redStone, random->nextInt(4) + 1)); + if (type == 9 && random->nextInt(10) == 0) + return std::shared_ptr(new ItemInstance( + Item::items[Item::record_01->id + random->nextInt(2)])); + if (type == 10) + return std::shared_ptr( + new ItemInstance(Item::dye_powder, 1, DyePowderItem::BROWN)); + if (type == 11) return Item::enchantedBook->createForRandomLoot(random); - return std::shared_ptr(); + return std::shared_ptr(); } -std::wstring MonsterRoomFeature::randomEntityId(Random *random) -{ - int id = random->nextInt(4); - if (id == 0) return std::wstring(L"Skeleton"); - if (id == 1) return std::wstring(L"Zombie"); - if (id == 2) return std::wstring(L"Zombie"); - if (id == 3) return std::wstring(L"Spider"); - return std::wstring(L""); +std::wstring MonsterRoomFeature::randomEntityId(Random* random) { + int id = random->nextInt(4); + if (id == 0) return std::wstring(L"Skeleton"); + if (id == 1) return std::wstring(L"Zombie"); + if (id == 2) return std::wstring(L"Zombie"); + if (id == 3) return std::wstring(L"Spider"); + return std::wstring(L""); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/MonsterRoomFeature.h b/Minecraft.World/WorldGen/Features/MonsterRoomFeature.h index d2b90de5b..16fd3c232 100644 --- a/Minecraft.World/WorldGen/Features/MonsterRoomFeature.h +++ b/Minecraft.World/WorldGen/Features/MonsterRoomFeature.h @@ -2,15 +2,14 @@ #include "Feature.h" #include "../../Blocks/Material.h" -class MonsterRoomFeature : public Feature -{ +class MonsterRoomFeature : public Feature { private: - //int tile; + // int tile; public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); private: - std::shared_ptr randomItem(Random *random); - std::wstring randomEntityId(Random *random); + std::shared_ptr randomItem(Random* random); + std::wstring randomEntityId(Random* random); }; diff --git a/Minecraft.World/WorldGen/Features/NetherBridgeFeature.cpp b/Minecraft.World/WorldGen/Features/NetherBridgeFeature.cpp index 2fd594a9f..23f66ccec 100644 --- a/Minecraft.World/WorldGen/Features/NetherBridgeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/NetherBridgeFeature.cpp @@ -7,110 +7,104 @@ #include "../../Headers/net.minecraft.world.level.h" #include "../../Headers/net.minecraft.world.level.dimension.h" - -NetherBridgeFeature::NetherBridgeFeature() : StructureFeature() -{ +NetherBridgeFeature::NetherBridgeFeature() : StructureFeature() { bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_BLAZE, 10, 2, 3)); - bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_PIGZOMBIE, 10, 4, 4)); - bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); - isSpotSelected=false; - netherFortressPos = NULL; - + bridgeEnemies.push_back( + new Biome::MobSpawnerData(eTYPE_PIGZOMBIE, 10, 4, 4)); + bridgeEnemies.push_back( + new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); + isSpotSelected = false; + netherFortressPos = NULL; } -NetherBridgeFeature::~NetherBridgeFeature() -{ - if( netherFortressPos != NULL ) delete netherFortressPos; +NetherBridgeFeature::~NetherBridgeFeature() { + if (netherFortressPos != NULL) delete netherFortressPos; } -std::vector *NetherBridgeFeature::getBridgeEnemies() -{ - return &bridgeEnemies; +std::vector* NetherBridgeFeature::getBridgeEnemies() { + return &bridgeEnemies; } -bool NetherBridgeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) -{ - // 4J Stu - New implementation to force a nether fortress - if (!isSpotSelected) - { - // Set the random - random->setSeed(level->getSeed()); - random->nextInt(); +bool NetherBridgeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { + // 4J Stu - New implementation to force a nether fortress + if (!isSpotSelected) { + // Set the random + random->setSeed(level->getSeed()); + random->nextInt(); - // Due to our nether size we want to accept chunks in the range [(-3,-3),(3,3)] (7x7). This is 49 possible chunks that should give - // the fortress enough room to grow within our limited nether - int chunk = random->nextInt(49); + // Due to our nether size we want to accept chunks in the range + // [(-3,-3),(3,3)] (7x7). This is 49 possible chunks that should give + // the fortress enough room to grow within our limited nether + int chunk = random->nextInt(49); - int xCoord = chunk % 7; - int zCoord = chunk / 7; + int xCoord = chunk % 7; + int zCoord = chunk / 7; - netherFortressPos = new ChunkPos(xCoord, zCoord); + netherFortressPos = new ChunkPos(xCoord, zCoord); - isSpotSelected = true; - } - - bool forcePlacement = false; - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - if( levelGenOptions != NULL ) - { - forcePlacement = levelGenOptions->isFeatureChunk(x,z,eFeature_NetherBridge); - } + isSpotSelected = true; + } + + bool forcePlacement = false; + LevelGenerationOptions* levelGenOptions = app.getLevelGenerationOptions(); + if (levelGenOptions != NULL) { + forcePlacement = + levelGenOptions->isFeatureChunk(x, z, eFeature_NetherBridge); + } + + if (forcePlacement || + (x == netherFortressPos->x && z == netherFortressPos->z)) + return true; - if(forcePlacement || (x == netherFortressPos->x && z == netherFortressPos->z) ) return true; - #ifdef _LARGE_WORLDS - int xzSize = level->dimension->getXZSize(); - if(xzSize > 30) - { - // For large worlds, lets allow the PC version of the spawning to place nether fortresses (plus the one we forced above) - int cx = x >> 4; - int cz = z >> 4; + int xzSize = level->dimension->getXZSize(); + if (xzSize > 30) { + // For large worlds, lets allow the PC version of the spawning to place + // nether fortresses (plus the one we forced above) + int cx = x >> 4; + int cz = z >> 4; - random->setSeed(cx ^ (cz << 4) ^ level->getSeed()); - random->nextInt(); + random->setSeed(cx ^ (cz << 4) ^ level->getSeed()); + random->nextInt(); - if (random->nextInt(3) != 0) - { - return false; - } - if (x != ((cx << 4) + 4 + random->nextInt(8))) - { - return false; - } - if (z != ((cz << 4) + 4 + random->nextInt(8))) - { - return false; - } - return true; - } + if (random->nextInt(3) != 0) { + return false; + } + if (x != ((cx << 4) + 4 + random->nextInt(8))) { + return false; + } + if (z != ((cz << 4) + 4 + random->nextInt(8))) { + return false; + } + return true; + } #endif - return false; + return false; } -StructureStart *NetherBridgeFeature::createStructureStart(int x, int z) -{ - return new NetherBridgeStart(level, random, x, z); +StructureStart* NetherBridgeFeature::createStructureStart(int x, int z) { + return new NetherBridgeStart(level, random, x, z); } -void NetherBridgeFeature::clearCachedBuildings() -{ - cachedStructures.clear(); -} +void NetherBridgeFeature::clearCachedBuildings() { cachedStructures.clear(); } -NetherBridgeFeature::NetherBridgeStart::NetherBridgeStart(Level *level, Random *random, int chunkX, int chunkZ) : StructureStart() -{ - NetherBridgePieces::StartPiece *start = new NetherBridgePieces::StartPiece(random, (chunkX << 4) + 2, (chunkZ << 4) + 2, level); +NetherBridgeFeature::NetherBridgeStart::NetherBridgeStart(Level* level, + Random* random, + int chunkX, + int chunkZ) + : StructureStart() { + NetherBridgePieces::StartPiece* start = new NetherBridgePieces::StartPiece( + random, (chunkX << 4) + 2, (chunkZ << 4) + 2, level); pieces.push_back(start); start->addChildren(start, &pieces, random); - std::vector *pendingChildren = &start->pendingChildren; - while (!pendingChildren->empty()) - { + std::vector* pendingChildren = &start->pendingChildren; + while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; - pendingChildren->erase(it); + AUTO_VAR(it, pendingChildren->begin() + pos); + StructurePiece* structurePiece = *it; + pendingChildren->erase(it); structurePiece->addChildren(start, &pieces, random); } diff --git a/Minecraft.World/WorldGen/Features/NetherBridgeFeature.h b/Minecraft.World/WorldGen/Features/NetherBridgeFeature.h index 03f6bd432..62f43c480 100644 --- a/Minecraft.World/WorldGen/Features/NetherBridgeFeature.h +++ b/Minecraft.World/WorldGen/Features/NetherBridgeFeature.h @@ -4,27 +4,27 @@ #include "../Biomes/Biome.h" class Random; -class NetherBridgeFeature : public StructureFeature -{ - +class NetherBridgeFeature : public StructureFeature { private: - std::vector bridgeEnemies; - bool isSpotSelected; - ChunkPos *netherFortressPos; + std::vector bridgeEnemies; + bool isSpotSelected; + ChunkPos* netherFortressPos; public: - NetherBridgeFeature(); - ~NetherBridgeFeature(); - std::vector *getBridgeEnemies(); + NetherBridgeFeature(); + ~NetherBridgeFeature(); + std::vector* getBridgeEnemies(); + protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat); - virtual StructureStart *createStructureStart(int x, int z); + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat); + virtual StructureStart* createStructureStart(int x, int z); + public: - void clearCachedBuildings(); + void clearCachedBuildings(); + private: - class NetherBridgeStart : public StructureStart - { - public: - NetherBridgeStart(Level *level, Random *random, int chunkX, int chunkZ); + class NetherBridgeStart : public StructureStart { + public: + NetherBridgeStart(Level* level, Random* random, int chunkX, int chunkZ); }; }; diff --git a/Minecraft.World/WorldGen/Features/NetherSphereFeature.cpp b/Minecraft.World/WorldGen/Features/NetherSphereFeature.cpp index e5373bd36..3d855b923 100644 --- a/Minecraft.World/WorldGen/Features/NetherSphereFeature.cpp +++ b/Minecraft.World/WorldGen/Features/NetherSphereFeature.cpp @@ -1,26 +1,16 @@ #include "../../Platform/stdafx.h" #include "NetherSphereFeature.h" +NetherSphere::NetherSphere(Level* level) : Entity(level) { + // 4J Stu - This function call had to be moved here from the Entity ctor to + // ensure that the derived version of the function is called + this->defineSynchedData(); - -NetherSphere::NetherSphere(Level *level) : Entity(level) -{ - // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that - // the derived version of the function is called - this->defineSynchedData(); - - setSize(4, 4); + setSize(4, 4); } +void NetherSphere::defineSynchedData() {} -void NetherSphere::defineSynchedData() -{ -} +void NetherSphere::readAdditionalSaveData(CompoundTag* tag) {} -void NetherSphere::readAdditionalSaveData(CompoundTag *tag) -{ -} - -void NetherSphere::addAdditonalSaveData(CompoundTag *tag) -{ -} \ No newline at end of file +void NetherSphere::addAdditonalSaveData(CompoundTag* tag) {} \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/NetherSphereFeature.h b/Minecraft.World/WorldGen/Features/NetherSphereFeature.h index a3087e09f..c1b16a16b 100644 --- a/Minecraft.World/WorldGen/Features/NetherSphereFeature.h +++ b/Minecraft.World/WorldGen/Features/NetherSphereFeature.h @@ -2,15 +2,15 @@ #include "../../Entities/Entity.h" -class NetherSphere : public Entity -{ +class NetherSphere : public Entity { public: - eINSTANCEOF GetType() { return eTYPE_NETHER_SPHERE; }; + eINSTANCEOF GetType() { return eTYPE_NETHER_SPHERE; }; + public: - NetherSphere(Level *level); + NetherSphere(Level* level); protected: - virtual void defineSynchedData(); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void addAdditonalSaveData(CompoundTag *tag); + virtual void defineSynchedData(); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void addAdditonalSaveData(CompoundTag* tag); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/OreFeature.cpp b/Minecraft.World/WorldGen/Features/OreFeature.cpp index 9dce1cfb9..2d5a08f64 100644 --- a/Minecraft.World/WorldGen/Features/OreFeature.cpp +++ b/Minecraft.World/WorldGen/Features/OreFeature.cpp @@ -3,26 +3,22 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "OreFeature.h" -void OreFeature::_init(int tile, int count, int targetTile) -{ - this->tile = tile; - this->count = count; - this->targetTile = targetTile; +void OreFeature::_init(int tile, int count, int targetTile) { + this->tile = tile; + this->count = count; + this->targetTile = targetTile; } -OreFeature::OreFeature(int tile, int count) -{ - _init(tile, count, Tile::rock_Id); +OreFeature::OreFeature(int tile, int count) { + _init(tile, count, Tile::rock_Id); } -OreFeature::OreFeature(int tile, int count, int targetTile) -{ - _init(tile, count, targetTile); +OreFeature::OreFeature(int tile, int count, int targetTile) { + _init(tile, count, targetTile); } -bool OreFeature::place(Level *level, Random *random, int x, int y, int z) -{ - PIXBeginNamedEvent(0,"Place Ore Feature"); +bool OreFeature::place(Level* level, Random* random, int x, int y, int z) { + PIXBeginNamedEvent(0, "Place Ore Feature"); float dir = random->nextFloat() * PI; double x0 = x + 8 + Mth::sin(dir) * count / 8; @@ -33,30 +29,30 @@ bool OreFeature::place(Level *level, Random *random, int x, int y, int z) double y0 = y + random->nextInt(3) - 2; double y1 = y + random->nextInt(3) - 2; - bool collisionsExpected = false; - - LevelGenerationOptions *levelGenOptions = NULL; - if( app.getLevelGenerationOptions() != NULL ) - { - levelGenOptions = app.getLevelGenerationOptions(); + bool collisionsExpected = false; - // 4J Stu - Optimise schematic intersection checks by first checking the max possible bounding box of this place call - int minX = x0 - 1; - int minY = y0 - 1; - int minZ = z0 - 1; - - double maxss = count / 16; - double maxr = (Mth::sin(PI) + 1) * maxss + 1; - double maxhr = (Mth::sin(PI) + 1) * maxss + 1; - int maxX = Mth::floor(x1 + maxr / 2); - int maxY = Mth::floor(y1 + maxhr / 2); - int maxZ = Mth::floor(z1 + maxr / 2); + LevelGenerationOptions* levelGenOptions = NULL; + if (app.getLevelGenerationOptions() != NULL) { + levelGenOptions = app.getLevelGenerationOptions(); - collisionsExpected = levelGenOptions->checkIntersects(minX, minY, minZ, maxX, maxY, maxZ); - } + // 4J Stu - Optimise schematic intersection checks by first checking the + // max possible bounding box of this place call + int minX = x0 - 1; + int minY = y0 - 1; + int minZ = z0 - 1; - for (int d = 0; d <= count; d++) - { + double maxss = count / 16; + double maxr = (Mth::sin(PI) + 1) * maxss + 1; + double maxhr = (Mth::sin(PI) + 1) * maxss + 1; + int maxX = Mth::floor(x1 + maxr / 2); + int maxY = Mth::floor(y1 + maxhr / 2); + int maxZ = Mth::floor(z1 + maxr / 2); + + collisionsExpected = levelGenOptions->checkIntersects(minX, minY, minZ, + maxX, maxY, maxZ); + } + + for (int d = 0; d <= count; d++) { double xx = x0 + (x1 - x0) * d / count; double yy = y0 + (y1 - y0) * d / count; double zz = z0 + (z1 - z0) * d / count; @@ -68,52 +64,54 @@ bool OreFeature::place(Level *level, Random *random, int x, int y, int z) int xt0 = Mth::floor(xx - r / 2); int yt0 = Mth::floor(yy - hr / 2); int zt0 = Mth::floor(zz - r / 2); - + int xt1 = Mth::floor(xx + r / 2); int yt1 = Mth::floor(yy + hr / 2); int zt1 = Mth::floor(zz + r / 2); - // 4J Stu Added to stop ore features generating areas previously place by game rule generation - if(collisionsExpected && levelGenOptions != NULL) - { - bool intersects = levelGenOptions->checkIntersects(xt0, yt0, zt0, xt1, yt1, zt1); - if(intersects) - { - //app.DebugPrintf("Skipping ore feature generation as it overlaps a game rule structure\n"); - continue; - } - } + // 4J Stu Added to stop ore features generating areas previously place + // by game rule generation + if (collisionsExpected && levelGenOptions != NULL) { + bool intersects = + levelGenOptions->checkIntersects(xt0, yt0, zt0, xt1, yt1, zt1); + if (intersects) { + // app.DebugPrintf("Skipping ore feature generation as it + // overlaps a game rule structure\n"); + continue; + } + } - // A large % of ore placement is entirely into the air. Attempt to identify some of these early, by check the corners - // of the area we are placing in to see if we are going to (very probably) be entirely above the height stored in the heightmap + // A large % of ore placement is entirely into the air. Attempt to + // identify some of these early, by check the corners of the area we are + // placing in to see if we are going to (very probably) be entirely + // above the height stored in the heightmap - bool earlyReject = true; - if ( level->getHeightmap(xt0, zt0) >= yt0 ) earlyReject = false; - else if( level->getHeightmap(xt1, zt0) >= yt0 ) earlyReject = false; - else if( level->getHeightmap(xt0, zt1) >= yt0 ) earlyReject = false; - else if( level->getHeightmap(xt1, zt1) >= yt0 ) earlyReject = false; + bool earlyReject = true; + if (level->getHeightmap(xt0, zt0) >= yt0) + earlyReject = false; + else if (level->getHeightmap(xt1, zt0) >= yt0) + earlyReject = false; + else if (level->getHeightmap(xt0, zt1) >= yt0) + earlyReject = false; + else if (level->getHeightmap(xt1, zt1) >= yt0) + earlyReject = false; - if( earlyReject ) continue; + if (earlyReject) continue; - for (int x2 = xt0; x2 <= xt1; x2++) - { + for (int x2 = xt0; x2 <= xt1; x2++) { double xd = ((x2 + 0.5) - xx) / (r / 2); - if (xd * xd < 1) - { - for (int y2 = yt0; y2 <= yt1; y2++) - { + if (xd * xd < 1) { + for (int y2 = yt0; y2 <= yt1; y2++) { double yd = ((y2 + 0.5) - yy) / (hr / 2); - if (xd * xd + yd * yd < 1) - { - for (int z2 = zt0; z2 <= zt1; z2++) - { + if (xd * xd + yd * yd < 1) { + for (int z2 = zt0; z2 <= zt1; z2++) { double zd = ((z2 + 0.5) - zz) / (r / 2); - if (xd * xd + yd * yd + zd * zd < 1) - { - if (level->getTile(x2, y2, z2) == targetTile) - { - level->setTileNoUpdateNoLightCheck(x2, y2, z2, tile); // 4J changed from setTileNoUpdate - } + if (xd * xd + yd * yd + zd * zd < 1) { + if (level->getTile(x2, y2, z2) == targetTile) { + level->setTileNoUpdateNoLightCheck( + x2, y2, z2, tile); // 4J changed from + // setTileNoUpdate + } } } } @@ -122,6 +120,6 @@ bool OreFeature::place(Level *level, Random *random, int x, int y, int z) } } - PIXEndNamedEvent(); + PIXEndNamedEvent(); return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/OreFeature.h b/Minecraft.World/WorldGen/Features/OreFeature.h index 4103f9621..cfa859f50 100644 --- a/Minecraft.World/WorldGen/Features/OreFeature.h +++ b/Minecraft.World/WorldGen/Features/OreFeature.h @@ -3,17 +3,17 @@ class Level; -class OreFeature : public Feature -{ +class OreFeature : public Feature { private: - int tile; - int count; - int targetTile; + int tile; + int count; + int targetTile; + + void _init(int tile, int count, int targetTile); - void _init(int tile, int count, int targetTile); public: - OreFeature (int tile, int count); - OreFeature(int tile, int count, int targetTile); + OreFeature(int tile, int count); + OreFeature(int tile, int count, int targetTile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/PineFeature.cpp b/Minecraft.World/WorldGen/Features/PineFeature.cpp index 0b6297dd3..db74d9ac9 100644 --- a/Minecraft.World/WorldGen/Features/PineFeature.cpp +++ b/Minecraft.World/WorldGen/Features/PineFeature.cpp @@ -3,8 +3,7 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "PineFeature.h" -bool PineFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool PineFeature::place(Level* level, Random* random, int x, int y, int z) { // pines can be quite tall int treeHeight = random->nextInt(5) + 7; int trunkHeight = treeHeight - random->nextInt(2) - 3; @@ -13,47 +12,39 @@ bool PineFeature::place(Level *level, Random *random, int x, int y, int z) bool free = true; // may not be outside of y boundaries - if (y < 1 || y + treeHeight + 1 > Level::genDepth) - { + if (y < 1 || y + treeHeight + 1 > Level::genDepth) { return false; } - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - topRadius, y - 1, z - topRadius, x + topRadius, y + treeHeight, z + topRadius); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - topRadius, y - 1, z - topRadius, x + topRadius, y + treeHeight, + z + topRadius); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } // make sure there is enough space - for (int yy = y; yy <= y + 1 + treeHeight && free; yy++) - { - + for (int yy = y; yy <= y + 1 + treeHeight && free; yy++) { int r = 1; - if ((yy - y) < trunkHeight) - { + if ((yy - y) < trunkHeight) { r = 0; - } - else - { + } else { r = topRadius; } - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::genDepth) - { + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::genDepth) { int tt = level->getTile(xx, yy, zz); if (tt != 0 && tt != Tile::leaves_Id) free = false; - } - else - { + } else { free = false; } } @@ -64,38 +55,39 @@ bool PineFeature::place(Level *level, Random *random, int x, int y, int z) // must stand on ground int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::genDepth - treeHeight - 1) return false; + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::genDepth - treeHeight - 1) + return false; placeBlock(level, x, y - 1, z, Tile::dirt_Id); // place leaf top int currentRadius = 0; - for (int yy = y + treeHeight; yy >= y + trunkHeight; yy--) - { - for (int xx = x - currentRadius; xx <= x + currentRadius; xx++) - { + for (int yy = y + treeHeight; yy >= y + trunkHeight; yy--) { + for (int xx = x - currentRadius; xx <= x + currentRadius; xx++) { int xo = xx - (x); - for (int zz = z - currentRadius; zz <= z + currentRadius; zz++) - { + for (int zz = z - currentRadius; zz <= z + currentRadius; zz++) { int zo = zz - (z); - if (abs(xo) == currentRadius && abs(zo) == currentRadius && currentRadius > 0) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id, LeafTile::EVERGREEN_LEAF); + if (abs(xo) == currentRadius && abs(zo) == currentRadius && + currentRadius > 0) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id, + LeafTile::EVERGREEN_LEAF); } } - if (currentRadius >= 1 && yy == (y + trunkHeight + 1)) - { + if (currentRadius >= 1 && yy == (y + trunkHeight + 1)) { currentRadius -= 1; - } - else if (currentRadius < topRadius) - { + } else if (currentRadius < topRadius) { currentRadius += 1; } } - for (int hh = 0; hh < treeHeight - 1; hh++) - { + for (int hh = 0; hh < treeHeight - 1; hh++) { int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, TreeTile::DARK_TRUNK); + if (t == 0 || t == Tile::leaves_Id) + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, + TreeTile::DARK_TRUNK); } return true; diff --git a/Minecraft.World/WorldGen/Features/PineFeature.h b/Minecraft.World/WorldGen/Features/PineFeature.h index 62ded1e49..b68bb50bf 100644 --- a/Minecraft.World/WorldGen/Features/PineFeature.h +++ b/Minecraft.World/WorldGen/Features/PineFeature.h @@ -1,8 +1,7 @@ #pragma once #include "Feature.h" -class PineFeature : public Feature -{ +class PineFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/PumpkinFeature.cpp b/Minecraft.World/WorldGen/Features/PumpkinFeature.cpp index b2fa76ed7..7278bfe4b 100644 --- a/Minecraft.World/WorldGen/Features/PumpkinFeature.cpp +++ b/Minecraft.World/WorldGen/Features/PumpkinFeature.cpp @@ -3,18 +3,16 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "PumpkinFeature.h" -bool PumpkinFeature::place(Level *level, Random *random, int x, int y, int z) -{ - for (int i = 0; i < 64; i++) - { +bool PumpkinFeature::place(Level* level, Random* random, int x, int y, int z) { + for (int i = 0; i < 64; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2) && level->getTile(x2, y2 - 1, z2) == Tile::grass_Id) - { - if (Tile::pumpkin->mayPlace(level, x2, y2, z2)) - { - level->setTileAndDataNoUpdate(x2, y2, z2, Tile::pumpkin_Id, random->nextInt(4)); + if (level->isEmptyTile(x2, y2, z2) && + level->getTile(x2, y2 - 1, z2) == Tile::grass_Id) { + if (Tile::pumpkin->mayPlace(level, x2, y2, z2)) { + level->setTileAndDataNoUpdate(x2, y2, z2, Tile::pumpkin_Id, + random->nextInt(4)); } } } diff --git a/Minecraft.World/WorldGen/Features/PumpkinFeature.h b/Minecraft.World/WorldGen/Features/PumpkinFeature.h index f4fc0be8d..8868653ce 100644 --- a/Minecraft.World/WorldGen/Features/PumpkinFeature.h +++ b/Minecraft.World/WorldGen/Features/PumpkinFeature.h @@ -1,9 +1,7 @@ #pragma once #include "Feature.h" - -class PumpkinFeature : public Feature -{ +class PumpkinFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.cpp b/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.cpp index b5b633f0b..d89001d88 100644 --- a/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.cpp @@ -4,81 +4,81 @@ #include "../Structures/ScatteredFeaturePieces.h" #include "RandomScatteredLargeFeature.h" -std::vector RandomScatteredLargeFeature::allowedBiomes; +std::vector RandomScatteredLargeFeature::allowedBiomes; -void RandomScatteredLargeFeature::staticCtor() -{ - allowedBiomes.push_back( Biome::desert ); - allowedBiomes.push_back( Biome::desertHills ); - allowedBiomes.push_back( Biome::jungle ); +void RandomScatteredLargeFeature::staticCtor() { + allowedBiomes.push_back(Biome::desert); + allowedBiomes.push_back(Biome::desertHills); + allowedBiomes.push_back(Biome::jungle); } -RandomScatteredLargeFeature::RandomScatteredLargeFeature() -{ +RandomScatteredLargeFeature::RandomScatteredLargeFeature() {} + +bool RandomScatteredLargeFeature::isFeatureChunk(int x, int z, + bool bIsSuperflat) { + int featureSpacing = 32; + int minFeatureSeparation = 8; + + int xx = x; + int zz = z; + if (x < 0) x -= featureSpacing - 1; + if (z < 0) z -= featureSpacing - 1; + + int xCenterFeatureChunk = x / featureSpacing; + int zCenterFeatureChunk = z / featureSpacing; + Random* r = + level->getRandomFor(xCenterFeatureChunk, zCenterFeatureChunk, 14357617); + xCenterFeatureChunk *= featureSpacing; + zCenterFeatureChunk *= featureSpacing; + xCenterFeatureChunk += r->nextInt(featureSpacing - minFeatureSeparation); + zCenterFeatureChunk += r->nextInt(featureSpacing - minFeatureSeparation); + x = xx; + z = zz; + + bool forcePlacement = false; + LevelGenerationOptions* levelGenOptions = app.getLevelGenerationOptions(); + if (levelGenOptions != NULL) { + forcePlacement = + levelGenOptions->isFeatureChunk(x, z, eFeature_Temples); + } + + if (forcePlacement || + (x == xCenterFeatureChunk && z == zCenterFeatureChunk)) { + bool biomeOk = level->getBiomeSource()->containsOnly( + x * 16 + 8, z * 16 + 8, 0, allowedBiomes); + if (biomeOk) { + // System.out.println("feature at " + (x * 16) + " " + // + (z * 16)); + return true; + } + } + + return false; } -bool RandomScatteredLargeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) -{ - int featureSpacing = 32; - int minFeatureSeparation = 8; - - int xx = x; - int zz = z; - if (x < 0) x -= featureSpacing - 1; - if (z < 0) z -= featureSpacing - 1; - - int xCenterFeatureChunk = x / featureSpacing; - int zCenterFeatureChunk = z / featureSpacing; - Random *r = level->getRandomFor(xCenterFeatureChunk, zCenterFeatureChunk, 14357617); - xCenterFeatureChunk *= featureSpacing; - zCenterFeatureChunk *= featureSpacing; - xCenterFeatureChunk += r->nextInt(featureSpacing - minFeatureSeparation); - zCenterFeatureChunk += r->nextInt(featureSpacing - minFeatureSeparation); - x = xx; - z = zz; - - bool forcePlacement = false; - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - if( levelGenOptions != NULL ) - { - forcePlacement = levelGenOptions->isFeatureChunk(x,z,eFeature_Temples); - } - - if (forcePlacement || (x == xCenterFeatureChunk && z == zCenterFeatureChunk)) - { - bool biomeOk = level->getBiomeSource()->containsOnly(x * 16 + 8, z * 16 + 8, 0, allowedBiomes); - if (biomeOk) - { - // System.out.println("feature at " + (x * 16) + " " + (z * 16)); - return true; - } - } - - return false; - +StructureStart* RandomScatteredLargeFeature::createStructureStart(int x, + int z) { + // System.out.println("feature at " + (x * 16) + " " + (z * 16)); + return new ScatteredFeatureStart(level, random, x, z); } -StructureStart *RandomScatteredLargeFeature::createStructureStart(int x, int z) -{ - // System.out.println("feature at " + (x * 16) + " " + (z * 16)); - return new ScatteredFeatureStart(level, random, x, z); -} +RandomScatteredLargeFeature::ScatteredFeatureStart::ScatteredFeatureStart( + Level* level, Random* random, int chunkX, int chunkZ) { + if (level->getBiome(chunkX * 16 + 8, chunkZ * 16 + 8) == Biome::jungle) { + ScatteredFeaturePieces::JunglePyramidPiece* startRoom = + new ScatteredFeaturePieces::JunglePyramidPiece(random, chunkX * 16, + chunkZ * 16); + pieces.push_back(startRoom); + // System.out.println("jungle feature at " + (chunkX * + // 16) + " " + (chunkZ * 16)); + } else { + ScatteredFeaturePieces::DesertPyramidPiece* startRoom = + new ScatteredFeaturePieces::DesertPyramidPiece(random, chunkX * 16, + chunkZ * 16); + pieces.push_back(startRoom); + // System.out.println("desert feature at " + (chunkX * + // 16) + " " + (chunkZ * 16)); + } - -RandomScatteredLargeFeature::ScatteredFeatureStart::ScatteredFeatureStart(Level *level, Random *random, int chunkX, int chunkZ) -{ - if (level->getBiome(chunkX * 16 + 8, chunkZ * 16 + 8) == Biome::jungle) - { - ScatteredFeaturePieces::JunglePyramidPiece *startRoom = new ScatteredFeaturePieces::JunglePyramidPiece(random, chunkX * 16, chunkZ * 16); - pieces.push_back(startRoom); - // System.out.println("jungle feature at " + (chunkX * 16) + " " + (chunkZ * 16)); - } - else - { - ScatteredFeaturePieces::DesertPyramidPiece *startRoom = new ScatteredFeaturePieces::DesertPyramidPiece(random, chunkX * 16, chunkZ * 16); - pieces.push_back(startRoom); - // System.out.println("desert feature at " + (chunkX * 16) + " " + (chunkZ * 16)); - } - - calculateBoundingBox(); + calculateBoundingBox(); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.h b/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.h index 020522630..122f13c7e 100644 --- a/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.h +++ b/Minecraft.World/WorldGen/Features/RandomScatteredLargeFeature.h @@ -3,20 +3,19 @@ #include "StructureFeature.h" #include "../Structures/StructureStart.h" -class RandomScatteredLargeFeature : public StructureFeature -{ +class RandomScatteredLargeFeature : public StructureFeature { public: - static void staticCtor(); - static std::vector allowedBiomes; - RandomScatteredLargeFeature(); + static void staticCtor(); + static std::vector allowedBiomes; + RandomScatteredLargeFeature(); protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat=false); - StructureStart *createStructureStart(int x, int z); + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat = false); + StructureStart* createStructureStart(int x, int z); - class ScatteredFeatureStart : public StructureStart - { - public: - ScatteredFeatureStart(Level *level, Random *random, int chunkX, int chunkZ); - }; + class ScatteredFeatureStart : public StructureStart { + public: + ScatteredFeatureStart(Level* level, Random* random, int chunkX, + int chunkZ); + }; }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/ReedsFeature.cpp b/Minecraft.World/WorldGen/Features/ReedsFeature.cpp index b935ad41a..9f0e472f6 100644 --- a/Minecraft.World/WorldGen/Features/ReedsFeature.cpp +++ b/Minecraft.World/WorldGen/Features/ReedsFeature.cpp @@ -3,38 +3,33 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "ReedsFeature.h" -bool ReedsFeature::place(Level *level, Random *random, int x, int y, int z) -{ - for (int i = 0; i < 20; i++) - { +bool ReedsFeature::place(Level* level, Random* random, int x, int y, int z) { + for (int i = 0; i < 20; i++) { int x2 = x + random->nextInt(4) - random->nextInt(4); int y2 = y; int z2 = z + random->nextInt(4) - random->nextInt(4); - // 4J Stu Added to stop reed features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x2, y2, z2, x2, y2, z2); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - continue; - } - } - if (level->isEmptyTile(x2, y2, z2)) - { - if (level->getMaterial(x2-1, y2-1, z2) == Material::water || - level->getMaterial(x2+1, y2-1, z2) == Material::water || - level->getMaterial(x2, y2-1, z2-1) == Material::water || - level->getMaterial(x2, y2-1, z2+1) == Material::water) - { - + // 4J Stu Added to stop reed features generating areas previously place + // by game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = + levelGenOptions->checkIntersects(x2, y2, z2, x2, y2, z2); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it + // overlaps a game rule structure\n"); + continue; + } + } + if (level->isEmptyTile(x2, y2, z2)) { + if (level->getMaterial(x2 - 1, y2 - 1, z2) == Material::water || + level->getMaterial(x2 + 1, y2 - 1, z2) == Material::water || + level->getMaterial(x2, y2 - 1, z2 - 1) == Material::water || + level->getMaterial(x2, y2 - 1, z2 + 1) == Material::water) { int h = 2 + random->nextInt(random->nextInt(3) + 1); - for (int yy = 0; yy < h; yy++) - { - if ( Tile::reeds->canSurvive(level, x2, y2 + yy, z2) ) - { + for (int yy = 0; yy < h; yy++) { + if (Tile::reeds->canSurvive(level, x2, y2 + yy, z2)) { level->setTileNoUpdate(x2, y2 + yy, z2, Tile::reeds_Id); } } diff --git a/Minecraft.World/WorldGen/Features/ReedsFeature.h b/Minecraft.World/WorldGen/Features/ReedsFeature.h index 82cb37ab9..d49aafa35 100644 --- a/Minecraft.World/WorldGen/Features/ReedsFeature.h +++ b/Minecraft.World/WorldGen/Features/ReedsFeature.h @@ -2,8 +2,7 @@ #include "Feature.h" #include "../../Blocks/Material.h" -class ReedsFeature : public Feature -{ +class ReedsFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/SandFeature.cpp b/Minecraft.World/WorldGen/Features/SandFeature.cpp index 1463c78ea..8cd0e46aa 100644 --- a/Minecraft.World/WorldGen/Features/SandFeature.cpp +++ b/Minecraft.World/WorldGen/Features/SandFeature.cpp @@ -3,56 +3,53 @@ #include "../../Headers/net.minecraft.world.level.h" #include "../../Headers/net.minecraft.world.level.tile.h" -SandFeature::SandFeature(int radius, int tile) -{ +SandFeature::SandFeature(int radius, int tile) { this->tile = tile; this->radius = radius; } -bool SandFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool SandFeature::place(Level* level, Random* random, int x, int y, int z) { if (level->getMaterial(x, y, z) != Material::water) return false; - // 4J - optimisation. Without this, we can end up creating a huge number of HeavyTiles to be ticked - // a few frames away. I think instatick ought to be fine here - we're only turning rock into gravel, - // so should instantly know if we've made a rock with nothing underneath and that should fall. - level->setInstaTick(true); + // 4J - optimisation. Without this, we can end up creating a huge number of + // HeavyTiles to be ticked a few frames away. I think instatick ought to be + // fine here - we're only turning rock into gravel, so should instantly know + // if we've made a rock with nothing underneath and that should fall. + level->setInstaTick(true); - int r = random->nextInt(radius-2)+2; + int r = random->nextInt(radius - 2) + 2; int yr = 2; - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - r, y - yr, z - r, x + r, y + yr, z + r); - if(intersects) - { - level->setInstaTick(false); - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - r, y - yr, z - r, x + r, y + yr, z + r); + if (intersects) { + level->setInstaTick(false); + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } - for (int xx = x - r; xx <= x + r; xx++) - { - for (int zz = z - r; zz <= z + r; zz++) - { + for (int xx = x - r; xx <= x + r; xx++) { + for (int zz = z - r; zz <= z + r; zz++) { int xd = xx - x; int zd = zz - z; if (xd * xd + zd * zd > r * r) continue; - for (int yy = y - yr; yy <= y + yr; yy++) - { + for (int yy = y - yr; yy <= y + yr; yy++) { int t = level->getTile(xx, yy, zz); - if (t == Tile::dirt_Id || t == Tile::grass_Id) - { + if (t == Tile::dirt_Id || t == Tile::grass_Id) { level->setTileNoUpdate(xx, yy, zz, tile); } } } } - level->setInstaTick(false); + level->setInstaTick(false); return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/SandFeature.h b/Minecraft.World/WorldGen/Features/SandFeature.h index 582e40d12..bbfcd71d2 100644 --- a/Minecraft.World/WorldGen/Features/SandFeature.h +++ b/Minecraft.World/WorldGen/Features/SandFeature.h @@ -2,13 +2,12 @@ #include "Feature.h" class Random; -class SandFeature : public Feature -{ +class SandFeature : public Feature { private: - int tile; + int tile; int radius; public: - SandFeature(int radius, int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + SandFeature(int radius, int tile); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/SpikeFeature.cpp b/Minecraft.World/WorldGen/Features/SpikeFeature.cpp index 758cccd7b..2a4a93e84 100644 --- a/Minecraft.World/WorldGen/Features/SpikeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/SpikeFeature.cpp @@ -4,176 +4,150 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "SpikeFeature.h" -SpikeFeature::SpikeFeature(int tile) -{ - this->tile = tile; - //m_iIndex=0; +SpikeFeature::SpikeFeature(int tile) { + this->tile = tile; + // m_iIndex=0; } -bool SpikeFeature::place(Level *level, Random *random, int x, int y, int z) -{ - if (!(level->isEmptyTile(x, y, z) && level->getTile(x, y - 1, z) == tile)) - { +bool SpikeFeature::place(Level* level, Random* random, int x, int y, int z) { + if (!(level->isEmptyTile(x, y, z) && level->getTile(x, y - 1, z) == tile)) { return false; } int hh = random->nextInt(32) + 6; int r = random->nextInt(4) + 1; for (int xx = x - r; xx <= x + r; xx++) - for (int zz = z - r; zz <= z + r; zz++) - { + for (int zz = z - r; zz <= z + r; zz++) { int xd = xx - x; int zd = zz - z; - if (xd * xd + zd * zd <= r * r + 1) - { - if (level->getTile(xx, y - 1, zz) != tile) - { - return false; - } + if (xd * xd + zd * zd <= r * r + 1) { + if (level->getTile(xx, y - 1, zz) != tile) { + return false; + } } } - for (int yy = y; yy < y + hh; yy++) - { - if (yy < Level::genDepth) - { + for (int yy = y; yy < y + hh; yy++) { + if (yy < Level::genDepth) { for (int xx = x - r; xx <= x + r; xx++) - for (int zz = z - r; zz <= z + r; zz++) - { + for (int zz = z - r; zz <= z + r; zz++) { int xd = xx - x; int zd = zz - z; - if (xd * xd + zd * zd <= r * r + 1) - { + if (xd * xd + zd * zd <= r * r + 1) { level->setTile(xx, yy, zz, Tile::obsidian_Id); } } - } else break; + } else + break; } - std::shared_ptr enderCrystal = std::shared_ptr(new EnderCrystal(level)); - enderCrystal->moveTo(x + 0.5f, y + hh, z + 0.5f, random->nextFloat() * 360, 0); + std::shared_ptr enderCrystal = + std::shared_ptr(new EnderCrystal(level)); + enderCrystal->moveTo(x + 0.5f, y + hh, z + 0.5f, random->nextFloat() * 360, + 0); level->addEntity(enderCrystal); level->setTile(x, y + hh, z, Tile::unbreakable_Id); return true; } -bool SpikeFeature::placeWithIndex(Level *level, Random *random, int x, int y, int z,int iIndex, int iRadius) -{ - app.DebugPrintf("Spike - %d,%d,%d - index %d\n",x,y,z,iIndex); +bool SpikeFeature::placeWithIndex(Level* level, Random* random, int x, int y, + int z, int iIndex, int iRadius) { + app.DebugPrintf("Spike - %d,%d,%d - index %d\n", x, y, z, iIndex); - int hh = 12 + (iIndex*3); + int hh = 12 + (iIndex * 3); - // fill any tiles below the spike + // fill any tiles below the spike - for (int xx = x - iRadius; xx <= x + iRadius; xx++) - { - for (int zz = z - iRadius; zz <= z + iRadius; zz++) - { + for (int xx = x - iRadius; xx <= x + iRadius; xx++) { + for (int zz = z - iRadius; zz <= z + iRadius; zz++) { int xd = xx - x; int zd = zz - z; - if (xd * xd + zd * zd <= iRadius * iRadius + 1) - { - int iTileBelow=1; + if (xd * xd + zd * zd <= iRadius * iRadius + 1) { + int iTileBelow = 1; - while((y-iTileBelow>-10) && level->getTile(xx, y - iTileBelow, zz) != tile) - { - if(level->isEmptyTile(xx, y - iTileBelow, zz)) - { - // empty tile - level->setTileNoUpdate(xx, y - iTileBelow, zz, Tile::obsidian_Id); - } - else - { - level->setTile(xx, y - iTileBelow, zz, Tile::obsidian_Id); - } - iTileBelow++; - } + while ((y - iTileBelow > -10) && + level->getTile(xx, y - iTileBelow, zz) != tile) { + if (level->isEmptyTile(xx, y - iTileBelow, zz)) { + // empty tile + level->setTileNoUpdate(xx, y - iTileBelow, zz, + Tile::obsidian_Id); + } else { + level->setTile(xx, y - iTileBelow, zz, + Tile::obsidian_Id); + } + iTileBelow++; + } } } - } - - for (int yy = y; yy < y + hh; yy++) - { - if (yy < Level::genDepth) - { - for (int xx = x - iRadius; xx <= x + iRadius; xx++) - { - for (int zz = z - iRadius; zz <= z + iRadius; zz++) - { - int xd = xx - x; - int zd = zz - z; - int iVal = xd * xd + zd * zd; - if ( iVal <= iRadius * iRadius + 1) - { - //level->setTile(xx, yy, zz, Tile::obsidian_Id); - placeBlock(level, xx, yy, zz, Tile::obsidian_Id, 0); - } - } - } - } - else - { - app.DebugPrintf("Breaking out of spike feature\n"); - break; - } } - // cap the last spikes with a fence to stop lucky arrows hitting the crystal + for (int yy = y; yy < y + hh; yy++) { + if (yy < Level::genDepth) { + for (int xx = x - iRadius; xx <= x + iRadius; xx++) { + for (int zz = z - iRadius; zz <= z + iRadius; zz++) { + int xd = xx - x; + int zd = zz - z; + int iVal = xd * xd + zd * zd; + if (iVal <= iRadius * iRadius + 1) { + // level->setTile(xx, yy, zz, Tile::obsidian_Id); + placeBlock(level, xx, yy, zz, Tile::obsidian_Id, 0); + } + } + } + } else { + app.DebugPrintf("Breaking out of spike feature\n"); + break; + } + } - if(iIndex>5) - { - for (int yy = y; yy < y + hh; yy++) - { - if (yy < Level::genDepth) - { - for (int xx = x - 2; xx <= x + 2; xx++) - { - for (int zz = z - 2; zz <= z + 2; zz++) - { - int xd = xx - x; - int zd = zz - z; - int iVal = xd * xd + zd * zd; - if ( iVal >= 2 * 2) - { - if(yy==(y + hh - 1)) - { - placeBlock(level, xx, y + hh, zz, Tile::ironFence_Id, 0); - placeBlock(level, xx, y + hh +1, zz, Tile::ironFence_Id, 0); - placeBlock(level, xx, y + hh +2, zz, Tile::ironFence_Id, 0); - } - } - } - } - } - else - { - app.DebugPrintf("Breaking out of spike feature\n"); - break; - } - } + // cap the last spikes with a fence to stop lucky arrows hitting the crystal - // and cap off the top - int yy = y + hh + 3; - - if (yy < Level::genDepth) - { - for (int xx = x - 2; xx <= x + 2; xx++) - { - for (int zz = z - 2; zz <= z + 2; zz++) - { - placeBlock(level, xx, yy, zz, Tile::ironFence_Id, 0); - } - } - } - } + if (iIndex > 5) { + for (int yy = y; yy < y + hh; yy++) { + if (yy < Level::genDepth) { + for (int xx = x - 2; xx <= x + 2; xx++) { + for (int zz = z - 2; zz <= z + 2; zz++) { + int xd = xx - x; + int zd = zz - z; + int iVal = xd * xd + zd * zd; + if (iVal >= 2 * 2) { + if (yy == (y + hh - 1)) { + placeBlock(level, xx, y + hh, zz, + Tile::ironFence_Id, 0); + placeBlock(level, xx, y + hh + 1, zz, + Tile::ironFence_Id, 0); + placeBlock(level, xx, y + hh + 2, zz, + Tile::ironFence_Id, 0); + } + } + } + } + } else { + app.DebugPrintf("Breaking out of spike feature\n"); + break; + } + } - std::shared_ptr enderCrystal = std::shared_ptr(new EnderCrystal(level)); - enderCrystal->moveTo(x + 0.5f, y + hh, z + 0.5f, random->nextFloat() * 360, 0); + // and cap off the top + int yy = y + hh + 3; + + if (yy < Level::genDepth) { + for (int xx = x - 2; xx <= x + 2; xx++) { + for (int zz = z - 2; zz <= z + 2; zz++) { + placeBlock(level, xx, yy, zz, Tile::ironFence_Id, 0); + } + } + } + } + + std::shared_ptr enderCrystal = + std::shared_ptr(new EnderCrystal(level)); + enderCrystal->moveTo(x + 0.5f, y + hh, z + 0.5f, random->nextFloat() * 360, + 0); level->addEntity(enderCrystal); - placeBlock(level, x, y + hh, z, Tile::unbreakable_Id, 0); - //level->setTile(x, y + hh, z, Tile::unbreakable_Id); + placeBlock(level, x, y + hh, z, Tile::unbreakable_Id, 0); + // level->setTile(x, y + hh, z, Tile::unbreakable_Id); return true; } - diff --git a/Minecraft.World/WorldGen/Features/SpikeFeature.h b/Minecraft.World/WorldGen/Features/SpikeFeature.h index 9612b9fa0..3d5741a3c 100644 --- a/Minecraft.World/WorldGen/Features/SpikeFeature.h +++ b/Minecraft.World/WorldGen/Features/SpikeFeature.h @@ -1,14 +1,14 @@ #pragma once #include "Feature.h" -class SpikeFeature : public Feature -{ +class SpikeFeature : public Feature { private: - int tile; - //int m_iIndex; + int tile; + // int m_iIndex; public: - SpikeFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); - virtual bool placeWithIndex(Level *level, Random *random, int x, int y, int z,int iIndex, int iRadius); + SpikeFeature(int tile); + virtual bool place(Level* level, Random* random, int x, int y, int z); + virtual bool placeWithIndex(Level* level, Random* random, int x, int y, + int z, int iIndex, int iRadius); }; diff --git a/Minecraft.World/WorldGen/Features/SpringFeature.cpp b/Minecraft.World/WorldGen/Features/SpringFeature.cpp index bddbdbe61..ca3a08890 100644 --- a/Minecraft.World/WorldGen/Features/SpringFeature.cpp +++ b/Minecraft.World/WorldGen/Features/SpringFeature.cpp @@ -3,29 +3,28 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "SpringFeature.h" -SpringFeature::SpringFeature(int tile) -{ - this->tile = tile; -} +SpringFeature::SpringFeature(int tile) { this->tile = tile; } -bool SpringFeature::place(Level *level, Random *random, int x, int y, int z) -{ - // 4J Stu Added to stop spring features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x, y, z, x, y, z); - if(intersects) - { - //app.DebugPrintf("Skipping spring feature generation as it overlaps a game rule structure\n"); - return false; - } - } +bool SpringFeature::place(Level* level, Random* random, int x, int y, int z) { + // 4J Stu Added to stop spring features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects(x, y, z, x, y, z); + if (intersects) { + // app.DebugPrintf("Skipping spring feature generation as it + // overlaps a game rule structure\n"); + return false; + } + } if (level->getTile(x, y + 1, z) != Tile::rock_Id) return false; if (level->getTile(x, y - 1, z) != Tile::rock_Id) return false; - if (level->getTile(x, y, z) != 0 && level->getTile(x, y, z) != Tile::rock_Id) return false; + if (level->getTile(x, y, z) != 0 && + level->getTile(x, y, z) != Tile::rock_Id) + return false; int rockCount = 0; if (level->getTile(x - 1, y, z) == Tile::rock_Id) rockCount++; @@ -39,8 +38,7 @@ bool SpringFeature::place(Level *level, Random *random, int x, int y, int z) if (level->isEmptyTile(x, y, z - 1)) holeCount++; if (level->isEmptyTile(x, y, z + 1)) holeCount++; - if (rockCount == 3 && holeCount == 1) - { + if (rockCount == 3 && holeCount == 1) { level->setTile(x, y, z, tile); level->setInstaTick(true); Tile::tiles[tile]->tick(level, x, y, z, random); diff --git a/Minecraft.World/WorldGen/Features/SpringFeature.h b/Minecraft.World/WorldGen/Features/SpringFeature.h index bb904eff6..40f06debd 100644 --- a/Minecraft.World/WorldGen/Features/SpringFeature.h +++ b/Minecraft.World/WorldGen/Features/SpringFeature.h @@ -1,14 +1,12 @@ #pragma once #include "Feature.h" - -class SpringFeature : public Feature -{ +class SpringFeature : public Feature { private: - int tile; + int tile; public: - SpringFeature(int tile); + SpringFeature(int tile); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/SpruceFeature.cpp b/Minecraft.World/WorldGen/Features/SpruceFeature.cpp index 1c7ae0e75..730c69ed2 100644 --- a/Minecraft.World/WorldGen/Features/SpruceFeature.cpp +++ b/Minecraft.World/WorldGen/Features/SpruceFeature.cpp @@ -3,12 +3,9 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "SpruceFeature.h" -SpruceFeature::SpruceFeature(bool doUpdate) : Feature(doUpdate) -{ -} +SpruceFeature::SpruceFeature(bool doUpdate) : Feature(doUpdate) {} -bool SpruceFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool SpruceFeature::place(Level* level, Random* random, int x, int y, int z) { // pines can be quite tall int treeHeight = random->nextInt(4) + 6; int trunkHeight = 1 + random->nextInt(2); @@ -17,46 +14,39 @@ bool SpruceFeature::place(Level *level, Random *random, int x, int y, int z) bool free = true; // may not be outside of y boundaries - if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) - { + if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) { return false; } - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - leafRadius, y - 1, z - leafRadius, x + leafRadius, y + treeHeight, z + leafRadius); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - leafRadius, y - 1, z - leafRadius, x + leafRadius, + y + treeHeight, z + leafRadius); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } // make sure there is enough space - for (int yy = y; yy <= y + 1 + treeHeight && free; yy++) - { + for (int yy = y; yy <= y + 1 + treeHeight && free; yy++) { int r = 1; - if ((yy - y) < trunkHeight) - { + if ((yy - y) < trunkHeight) { r = 0; - } - else - { + } else { r = leafRadius; } - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::maxBuildHeight) - { + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::maxBuildHeight) { int tt = level->getTile(xx, yy, zz); if (tt != 0 && tt != Tile::leaves_Id) free = false; - } - else - { + } else { free = false; } } @@ -67,7 +57,9 @@ bool SpruceFeature::place(Level *level, Random *random, int x, int y, int z) // must stand on ground int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::maxBuildHeight - treeHeight - 1) return false; + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::maxBuildHeight - treeHeight - 1) + return false; placeBlock(level, x, y - 1, z, Tile::dirt_Id); @@ -75,42 +67,39 @@ bool SpruceFeature::place(Level *level, Random *random, int x, int y, int z) int currentRadius = random->nextInt(2); int maxRadius = 1; int minRadius = 0; - for (int heightPos = 0; heightPos <= topHeight; heightPos++) - { - + for (int heightPos = 0; heightPos <= topHeight; heightPos++) { const int yy = y + treeHeight - heightPos; - for (int xx = x - currentRadius; xx <= x + currentRadius; xx++) - { + for (int xx = x - currentRadius; xx <= x + currentRadius; xx++) { int xo = xx - (x); - for (int zz = z - currentRadius; zz <= z + currentRadius; zz++) - { + for (int zz = z - currentRadius; zz <= z + currentRadius; zz++) { int zo = zz - (z); - if (abs(xo) == currentRadius && abs(zo) == currentRadius && currentRadius > 0) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id, LeafTile::EVERGREEN_LEAF); + if (abs(xo) == currentRadius && abs(zo) == currentRadius && + currentRadius > 0) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id, + LeafTile::EVERGREEN_LEAF); } } - if (currentRadius >= maxRadius) - { + if (currentRadius >= maxRadius) { currentRadius = minRadius; minRadius = 1; maxRadius += 1; - if (maxRadius > leafRadius) - { + if (maxRadius > leafRadius) { maxRadius = leafRadius; } - } - else - { + } else { currentRadius = currentRadius + 1; } } int topOffset = random->nextInt(3); - for (int hh = 0; hh < treeHeight - topOffset; hh++) - { + for (int hh = 0; hh < treeHeight - topOffset; hh++) { int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, TreeTile::DARK_TRUNK); + if (t == 0 || t == Tile::leaves_Id) + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, + TreeTile::DARK_TRUNK); } return true; } diff --git a/Minecraft.World/WorldGen/Features/SpruceFeature.h b/Minecraft.World/WorldGen/Features/SpruceFeature.h index 79918cc76..cc7cf8a51 100644 --- a/Minecraft.World/WorldGen/Features/SpruceFeature.h +++ b/Minecraft.World/WorldGen/Features/SpruceFeature.h @@ -1,9 +1,8 @@ #pragma once #include "Feature.h" -class SpruceFeature : public Feature -{ +class SpruceFeature : public Feature { public: - SpruceFeature(bool doUpdate); - virtual bool place(Level *level, Random *random, int x, int y, int z); + SpruceFeature(bool doUpdate); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Features/StrongholdFeature.cpp b/Minecraft.World/WorldGen/Features/StrongholdFeature.cpp index 1c6a69d51..b9e49b387 100644 --- a/Minecraft.World/WorldGen/Features/StrongholdFeature.cpp +++ b/Minecraft.World/WorldGen/Features/StrongholdFeature.cpp @@ -7,190 +7,189 @@ #include "../../IO/Files/FileHeader.h" #include "../../Util/JavaMath.h" -std::vector StrongholdFeature::allowedBiomes; +std::vector StrongholdFeature::allowedBiomes; -void StrongholdFeature::staticCtor() -{ - allowedBiomes.push_back(Biome::desert); - allowedBiomes.push_back(Biome::forest); - allowedBiomes.push_back(Biome::extremeHills); - allowedBiomes.push_back(Biome::swampland); - allowedBiomes.push_back(Biome::taiga); - allowedBiomes.push_back(Biome::iceFlats); - allowedBiomes.push_back(Biome::iceMountains); - allowedBiomes.push_back(Biome::desertHills); - allowedBiomes.push_back(Biome::forestHills); - allowedBiomes.push_back(Biome::smallerExtremeHills); - allowedBiomes.push_back(Biome::taigaHills); - allowedBiomes.push_back(Biome::jungle); - allowedBiomes.push_back(Biome::jungleHills); +void StrongholdFeature::staticCtor() { + allowedBiomes.push_back(Biome::desert); + allowedBiomes.push_back(Biome::forest); + allowedBiomes.push_back(Biome::extremeHills); + allowedBiomes.push_back(Biome::swampland); + allowedBiomes.push_back(Biome::taiga); + allowedBiomes.push_back(Biome::iceFlats); + allowedBiomes.push_back(Biome::iceMountains); + allowedBiomes.push_back(Biome::desertHills); + allowedBiomes.push_back(Biome::forestHills); + allowedBiomes.push_back(Biome::smallerExtremeHills); + allowedBiomes.push_back(Biome::taigaHills); + allowedBiomes.push_back(Biome::jungle); + allowedBiomes.push_back(Biome::jungleHills); }; - -StrongholdFeature::StrongholdFeature() : StructureFeature() -{ - // 4J added initialisers - for (int i = 0; i < strongholdPos_length; i++) - { - strongholdPos[i] = NULL; - } - isSpotSelected = false; +StrongholdFeature::StrongholdFeature() : StructureFeature() { + // 4J added initialisers + for (int i = 0; i < strongholdPos_length; i++) { + strongholdPos[i] = NULL; + } + isSpotSelected = false; } -StrongholdFeature::~StrongholdFeature() -{ - for (int i = 0; i < strongholdPos_length; i++) - { - delete strongholdPos[i]; - } +StrongholdFeature::~StrongholdFeature() { + for (int i = 0; i < strongholdPos_length; i++) { + delete strongholdPos[i]; + } } -bool StrongholdFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) -{ - if (!isSpotSelected) - { - Random random; +bool StrongholdFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { + if (!isSpotSelected) { + Random random; random.setSeed(level->getSeed()); - double angle = random.nextDouble() * PI * 2.0; + double angle = random.nextDouble() * PI * 2.0; - // 4J Stu - Changed so that we keep trying more until we have found somewhere in the world to place a stronghold - bool hasFoundValidPos = false; - int findAttempts = 0; - do - { - for (int i = 0; i < strongholdPos_length; i++) - { - double dist = 0.0; + // 4J Stu - Changed so that we keep trying more until we have found + // somewhere in the world to place a stronghold + bool hasFoundValidPos = false; + int findAttempts = 0; + do { + for (int i = 0; i < strongholdPos_length; i++) { + double dist = 0.0; #ifdef _LARGE_WORLDS - if(level->dimension->getXZSize() < (2.25f * 32.0f) ) - { - // Xbox360/PS3 distances - dist = (1.25 + random.nextDouble()) * (3 + random.nextInt(4)); - } - else - { - // Original Java - dist = (1.25 + random.nextDouble()) * 32.0; - } + if (level->dimension->getXZSize() < (2.25f * 32.0f)) { + // Xbox360/PS3 distances + dist = + (1.25 + random.nextDouble()) * (3 + random.nextInt(4)); + } else { + // Original Java + dist = (1.25 + random.nextDouble()) * 32.0; + } #else - // 4J Stu - Design change: Original spawns at *32 chunks rather than *10 chunks from (0,0) but that is outside our world - // double dist = (1.25 + random->nextDouble()) * 32.0; - // The max of the first part is 2.25, and we have 27 chunks in each direction - // Therefore 27/2.25 = 12, which should be the max of the second part - // The constant part and random part can be tuned to move the strongholds further from the spawn - // 4J Stu - The original (pre-TU9) calculation for selecting a start point could put the stronghold very close to the edge - // of the world, causing some parts to fail to generate. If the save is a newer save then we bring that generation in - if(level->getOriginalSaveVersion() >= SAVE_FILE_VERSION_MOVED_STRONGHOLD) - { - // Post TU9 - // The stronghold cannot extend more than 7 chunks in any direction from the start position - // Therefore as long as the the start x/z are less than 20 it will be fully contained - dist = (1.25 + random.nextDouble()) * (3 + random.nextInt(4)); - } - else - { - // Pre TU9 - dist = (1.25 + random.nextDouble()) * (5.0 + random.nextInt(7)); - } + // 4J Stu - Design change: Original spawns at *32 chunks rather + // than *10 chunks from (0,0) but that is outside our world + // double dist = (1.25 + random->nextDouble()) * 32.0; + // The max of the first part is 2.25, and we have 27 chunks in + // each direction Therefore 27/2.25 = 12, which should be the + // max of the second part The constant part and random part can + // be tuned to move the strongholds further from the spawn 4J + // Stu - The original (pre-TU9) calculation for selecting a + // start point could put the stronghold very close to the edge + // of the world, causing some parts to fail to generate. If the + // save is a newer save then we bring that generation in + if (level->getOriginalSaveVersion() >= + SAVE_FILE_VERSION_MOVED_STRONGHOLD) { + // Post TU9 + // The stronghold cannot extend more than 7 chunks in any + // direction from the start position Therefore as long as + // the the start x/z are less than 20 it will be fully + // contained + dist = + (1.25 + random.nextDouble()) * (3 + random.nextInt(4)); + } else { + // Pre TU9 + dist = (1.25 + random.nextDouble()) * + (5.0 + random.nextInt(7)); + } #endif - int selectedX = (int) (Math::round(cos(angle) * dist)); - int selectedZ = (int) (Math::round(sin(angle) * dist)); + int selectedX = (int)(Math::round(cos(angle) * dist)); + int selectedZ = (int)(Math::round(sin(angle) * dist)); - TilePos *position = level->getBiomeSource()->findBiome(((unsigned int) selectedX << 4) + 8, ((unsigned int) selectedZ << 4) + 8, 7 << 4, allowedBiomes, &random); - if (position != NULL) - { - selectedX = position->x >> 4; - selectedZ = position->z >> 4; + TilePos* position = level->getBiomeSource()->findBiome( + ((unsigned int)selectedX << 4) + 8, + ((unsigned int)selectedZ << 4) + 8, 7 << 4, allowedBiomes, + &random); + if (position != NULL) { + selectedX = position->x >> 4; + selectedZ = position->z >> 4; #ifndef _CONTENT_PACKAGE - if(position->x > 2560 || position->x < -2560 || position->z > 2560 || position->z < -2560) - { - __debugbreak(); - } + if (position->x > 2560 || position->x < -2560 || + position->z > 2560 || position->z < -2560) { + __debugbreak(); + } #endif - app.DebugPrintf("Placed stronghold in valid biome at (%d, %d), (%d, %d)\n", selectedX, selectedZ, position->x, position->z); - // 4J added - app.AddTerrainFeaturePosition(eTerrainFeature_Stronghold,selectedX,selectedZ); + app.DebugPrintf( + "Placed stronghold in valid biome at (%d, %d), (%d, " + "%d)\n", + selectedX, selectedZ, position->x, position->z); + // 4J added + app.AddTerrainFeaturePosition(eTerrainFeature_Stronghold, + selectedX, selectedZ); - // 4J Added - hasFoundValidPos = true; - delete position; - } - else - { - app.DebugPrintf("Placed stronghold in INVALID biome at (%d, %d)\n", selectedX, selectedZ); - } + // 4J Added + hasFoundValidPos = true; + delete position; + } else { + app.DebugPrintf( + "Placed stronghold in INVALID biome at (%d, %d)\n", + selectedX, selectedZ); + } - delete strongholdPos[i]; - strongholdPos[i] = new ChunkPos(selectedX, selectedZ); + delete strongholdPos[i]; + strongholdPos[i] = new ChunkPos(selectedX, selectedZ); - angle += PI * 2.0 / (double) strongholdPos_length; - } + angle += PI * 2.0 / (double)strongholdPos_length; + } - // 4J Stu - We want to make sure that we have at least one stronghold in this world - ++findAttempts; + // 4J Stu - We want to make sure that we have at least one + // stronghold in this world + ++findAttempts; - // 4J Stu - Randomise the angles for retries as well + // 4J Stu - Randomise the angles for retries as well #ifdef _LARGE_WORLDS - angle = random.nextDouble() * PI * 2.0; + angle = random.nextDouble() * PI * 2.0; #endif - } - while(!hasFoundValidPos && findAttempts < MAX_STRONGHOLD_ATTEMPTS); + } while (!hasFoundValidPos && findAttempts < MAX_STRONGHOLD_ATTEMPTS); - if(!hasFoundValidPos) - { - // Even if it's not a valid position we are still creating the last one we tried, so store it in the save so Eye of Ender works - // Fix for #81933 - GAMEPLAY: The Eye of Ender occasionally does not appear when used to try and locate the End Portal. - app.AddTerrainFeaturePosition(eTerrainFeature_Stronghold,strongholdPos[0]->x,strongholdPos[0]->z); - } + if (!hasFoundValidPos) { + // Even if it's not a valid position we are still creating the last + // one we tried, so store it in the save so Eye of Ender works Fix + // for #81933 - GAMEPLAY: The Eye of Ender occasionally does not + // appear when used to try and locate the End Portal. + app.AddTerrainFeaturePosition(eTerrainFeature_Stronghold, + strongholdPos[0]->x, + strongholdPos[0]->z); + } - isSpotSelected = true; + isSpotSelected = true; } - - for (int i = 0; i < strongholdPos_length; i++) - { - bool forcePlacement = false; - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - if( levelGenOptions != NULL ) - { - forcePlacement = levelGenOptions->isFeatureChunk(x,z,eFeature_Stronghold); - } - ChunkPos *pos = strongholdPos[i]; - if (forcePlacement || (pos && x == pos->x && z == pos->z) ) - { + for (int i = 0; i < strongholdPos_length; i++) { + bool forcePlacement = false; + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + if (levelGenOptions != NULL) { + forcePlacement = + levelGenOptions->isFeatureChunk(x, z, eFeature_Stronghold); + } + + ChunkPos* pos = strongholdPos[i]; + if (forcePlacement || (pos && x == pos->x && z == pos->z)) { return true; } - } + } return false; } -std::vector *StrongholdFeature::getGuesstimatedFeaturePositions() -{ - std::vector *positions = new std::vector(); - for( int i = 0; i < strongholdPos_length; i++ ) - { - ChunkPos *chunkPos = strongholdPos[i]; - if (chunkPos != NULL) - { - positions->push_back(chunkPos->getMiddleBlockPosition(64)); +std::vector* StrongholdFeature::getGuesstimatedFeaturePositions() { + std::vector* positions = new std::vector(); + for (int i = 0; i < strongholdPos_length; i++) { + ChunkPos* chunkPos = strongholdPos[i]; + if (chunkPos != NULL) { + positions->push_back(chunkPos->getMiddleBlockPosition(64)); } } return positions; } -StructureStart *StrongholdFeature::createStructureStart(int x, int z) -{ +StructureStart* StrongholdFeature::createStructureStart(int x, int z) { + StrongholdStart* start = new StrongholdStart(level, random, x, z); - StrongholdStart *start = new StrongholdStart(level, random, x, z); - - // 4J - front() was get(0) - while (start->getPieces()->empty() || ((StrongholdPieces::StartPiece *) start->getPieces()->front())->portalRoomPiece == NULL) - { - delete start; + // 4J - front() was get(0) + while (start->getPieces()->empty() || + ((StrongholdPieces::StartPiece*)start->getPieces()->front()) + ->portalRoomPiece == NULL) { + delete start; // regenerate stronghold without changing seed start = new StrongholdStart(level, random, x, z); } @@ -198,24 +197,26 @@ StructureStart *StrongholdFeature::createStructureStart(int x, int z) return start; // System.out.println("Creating stronghold at (" + x + ", " + z + ")"); - // return new StrongholdStart(level, random, x, z); + // return new StrongholdStart(level, random, x, z); } -StrongholdFeature::StrongholdStart::StrongholdStart(Level *level, Random *random, int chunkX, int chunkZ) : StructureStart() -{ +StrongholdFeature::StrongholdStart::StrongholdStart(Level* level, + Random* random, int chunkX, + int chunkZ) + : StructureStart() { StrongholdPieces::resetPieces(); - StrongholdPieces::StartPiece *startRoom = new StrongholdPieces::StartPiece(0, random, (chunkX << 4) + 2, (chunkZ << 4) + 2, level); + StrongholdPieces::StartPiece* startRoom = new StrongholdPieces::StartPiece( + 0, random, (chunkX << 4) + 2, (chunkZ << 4) + 2, level); pieces.push_back(startRoom); startRoom->addChildren(startRoom, &pieces, random); - std::vector *pendingChildren = &startRoom->pendingChildren; - while (!pendingChildren->empty()) - { + std::vector* pendingChildren = &startRoom->pendingChildren; + while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; - pendingChildren->erase(it); + AUTO_VAR(it, pendingChildren->begin() + pos); + StructurePiece* structurePiece = *it; + pendingChildren->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } diff --git a/Minecraft.World/WorldGen/Features/StrongholdFeature.h b/Minecraft.World/WorldGen/Features/StrongholdFeature.h index 5eb13e6ff..de889c93e 100644 --- a/Minecraft.World/WorldGen/Features/StrongholdFeature.h +++ b/Minecraft.World/WorldGen/Features/StrongholdFeature.h @@ -5,7 +5,6 @@ class Biome; #include "../Structures/StructureStart.h" - #include "../../Level/ChunkPos.h" // 4J Stu Added @@ -16,30 +15,31 @@ class Biome; #define MAX_STRONGHOLD_ATTEMPTS 10 #endif -class StrongholdFeature : public StructureFeature -{ +class StrongholdFeature : public StructureFeature { public: - static void staticCtor(); + static void staticCtor(); + private: - static std::vector allowedBiomes; + static std::vector allowedBiomes; bool isSpotSelected; - static const int strongholdPos_length = 1;// Java game has 3, but xbox game only has 1 because of the world size; // 4J added - ChunkPos *strongholdPos[strongholdPos_length]; + static const int strongholdPos_length = + 1; // Java game has 3, but xbox game only has 1 because of the world + // size; // 4J added + ChunkPos* strongholdPos[strongholdPos_length]; public: - StrongholdFeature(); - ~StrongholdFeature(); + StrongholdFeature(); + ~StrongholdFeature(); protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat=false); - std::vector *getGuesstimatedFeaturePositions(); - virtual StructureStart *createStructureStart(int x, int z); + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat = false); + std::vector* getGuesstimatedFeaturePositions(); + virtual StructureStart* createStructureStart(int x, int z); private: - class StrongholdStart : public StructureStart - { - public: - StrongholdStart(Level *level, Random *random, int chunkX, int chunkZ); + class StrongholdStart : public StructureStart { + public: + StrongholdStart(Level* level, Random* random, int chunkX, int chunkZ); }; }; diff --git a/Minecraft.World/WorldGen/Features/StructureFeature.cpp b/Minecraft.World/WorldGen/Features/StructureFeature.cpp index dfb98b0c6..cf6d0b704 100644 --- a/Minecraft.World/WorldGen/Features/StructureFeature.cpp +++ b/Minecraft.World/WorldGen/Features/StructureFeature.cpp @@ -7,56 +7,60 @@ #include "../../Headers/net.minecraft.world.level.h" #include "../../Level/LevelData.h" -StructureFeature::~StructureFeature() -{ - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) - { - delete it->second; - } +StructureFeature::~StructureFeature() { + for (AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); + it++) { + delete it->second; + } } -void StructureFeature::addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks) -{ +void StructureFeature::addFeature(Level* level, int x, int z, int xOffs, + int zOffs, byteArray blocks) { // this method is called for each chunk within 8 chunk's distance from // the chunk being generated, but not all chunks are the sources of // structures - if (cachedStructures.find(ChunkPos::hashCode(x, z)) != cachedStructures.end()) - { + if (cachedStructures.find(ChunkPos::hashCode(x, z)) != + cachedStructures.end()) { return; } // clear random key random->nextInt(); - // 4J-PB - want to know if it's a superflat land, so we don't generate so many villages - we've changed the distance required between villages on the xbox - if (isFeatureChunk(x, z,level->getLevelData()->getGenerator() == LevelType::lvl_flat)) - { - StructureStart *start = createStructureStart(x, z); + // 4J-PB - want to know if it's a superflat land, so we don't generate so + // many villages - we've changed the distance required between villages on + // the xbox + if (isFeatureChunk( + x, z, + level->getLevelData()->getGenerator() == LevelType::lvl_flat)) { + StructureStart* start = createStructureStart(x, z); cachedStructures[ChunkPos::hashCode(x, z)] = start; } } -bool StructureFeature::postProcess(Level *level, Random *random, int chunkX, int chunkZ) -{ - // 4J Stu - The x and z used to be offset by (+8) here, but that means we can miss out half structures on the edge of the world - // Normal feature generation offsets generation by half a chunk to ensure that it can generate the entire feature in chunks already created - // Structure features don't need this, as the PlaceBlock function only places blocks inside the BoundingBox specified, and parts - // of a struture piece can be added in more than one post-process call - int cx = ((unsigned) chunkX << 4); // + 8; - int cz = ((unsigned)chunkZ << 4); // + 8; +bool StructureFeature::postProcess(Level* level, Random* random, int chunkX, + int chunkZ) { + // 4J Stu - The x and z used to be offset by (+8) here, but that means we + // can miss out half structures on the edge of the world Normal feature + // generation offsets generation by half a chunk to ensure that it can + // generate the entire feature in chunks already created Structure features + // don't need this, as the PlaceBlock function only places blocks inside the + // BoundingBox specified, and parts of a struture piece can be added in more + // than one post-process call + int cx = ((unsigned)chunkX << 4); // + 8; + int cz = ((unsigned)chunkZ << 4); // + 8; bool intersection = false; - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) - { - StructureStart *structureStart = it->second; + for (AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); + it++) { + StructureStart* structureStart = it->second; - if (structureStart->isValid()) - { - if (structureStart->getBoundingBox()->intersects(cx, cz, cx + 15, cz + 15)) - { - BoundingBox *bb = new BoundingBox(cx, cz, cx + 15, cz + 15); + if (structureStart->isValid()) { + if (structureStart->getBoundingBox()->intersects(cx, cz, cx + 15, + cz + 15)) { + BoundingBox* bb = new BoundingBox(cx, cz, cx + 15, cz + 15); structureStart->postProcess(level, random, bb); - delete bb; + delete bb; intersection = true; } } @@ -65,21 +69,18 @@ bool StructureFeature::postProcess(Level *level, Random *random, int chunkX, int return intersection; } -bool StructureFeature::isIntersection(int cellX, int cellZ) -{ - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) - { - StructureStart *structureStart = it->second; - if (structureStart->isValid()) - { - if (structureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) - { - AUTO_VAR(it2, structureStart->getPieces()->begin()); - while( it2 != structureStart->getPieces()->end() ) - { - StructurePiece *next = *it2++; - if (next->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) - { +bool StructureFeature::isIntersection(int cellX, int cellZ) { + for (AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); + it++) { + StructureStart* structureStart = it->second; + if (structureStart->isValid()) { + if (structureStart->getBoundingBox()->intersects(cellX, cellZ, + cellX, cellZ)) { + AUTO_VAR(it2, structureStart->getPieces()->begin()); + while (it2 != structureStart->getPieces()->end()) { + StructurePiece* next = *it2++; + if (next->getBoundingBox()->intersects(cellX, cellZ, cellX, + cellZ)) { return true; } } @@ -92,117 +93,109 @@ bool StructureFeature::isIntersection(int cellX, int cellZ) /////////////////////////////////////////// // 4J-PB - Below functions added from 1.2.3 /////////////////////////////////////////// -bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) -{ - //for (StructureStart structureStart : cachedStructures.values()) - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) - { - StructureStart *pStructureStart = it->second; +bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) { + // for (StructureStart structureStart : cachedStructures.values()) + for (AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); + ++it) { + StructureStart* pStructureStart = it->second; - if (pStructureStart->isValid()) - { - if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) - { - /* - Iterator it = structureStart.getPieces().iterator(); - while (it.hasNext()) { - StructurePiece next = it.next(); - if (next.getBoundingBox().isInside(cellX, cellY, cellZ)) { - return true; - } - */ - std::list *pieces=pStructureStart->getPieces(); + if (pStructureStart->isValid()) { + if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, + cellX, cellZ)) { + /* + Iterator it = + structureStart.getPieces().iterator(); while (it.hasNext()) { + StructurePiece next = it.next(); + if (next.getBoundingBox().isInside(cellX, cellY, cellZ)) { + return true; + } + */ + std::list* pieces = + pStructureStart->getPieces(); - for ( AUTO_VAR(it2, pieces->begin()); it2 != pieces->end(); it2++ ) - { - StructurePiece* piece = *it2; - if ( piece->getBoundingBox()->isInside(cellX, cellY, cellZ) ) - { - return true; - } - } - } - } - } - return false; + for (AUTO_VAR(it2, pieces->begin()); it2 != pieces->end(); + it2++) { + StructurePiece* piece = *it2; + if (piece->getBoundingBox()->isInside(cellX, cellY, + cellZ)) { + return true; + } + } + } + } + } + return false; } -TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ) -{ +TilePos* StructureFeature::getNearestGeneratedFeature(Level* level, int cellX, + int cellY, int cellZ) { + // this is a hack that will "force" the feature to generate positions + // even if the player hasn't generated new chunks yet + this->level = level; - // this is a hack that will "force" the feature to generate positions - // even if the player hasn't generated new chunks yet - this->level = level; + random->setSeed(level->getSeed()); + __int64 xScale = random->nextLong(); + __int64 zScale = random->nextLong(); + __int64 xx = (cellX >> 4) * xScale; + __int64 zz = (cellZ >> 4) * zScale; + random->setSeed(xx ^ zz ^ level->getSeed()); - random->setSeed(level->getSeed()); - __int64 xScale = random->nextLong(); - __int64 zScale = random->nextLong(); - __int64 xx = (cellX >> 4) * xScale; - __int64 zz = (cellZ >> 4) * zScale; - random->setSeed(xx ^ zz ^ level->getSeed()); + addFeature(level, cellX >> 4, cellZ >> 4, 0, 0, byteArray()); - addFeature(level, cellX >> 4, cellZ >> 4, 0, 0, byteArray()); + double minDistance = DBL_MAX; + TilePos* selected = NULL; - double minDistance = DBL_MAX; - TilePos *selected = NULL; + for (AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); + ++it) { + StructureStart* pStructureStart = it->second; - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) - { - StructureStart *pStructureStart = it->second; + if (pStructureStart->isValid()) { + // StructurePiece *pStructurePiece = + // pStructureStart->getPieces().get(0); + StructurePiece* pStructurePiece = + *pStructureStart->getPieces()->begin(); + TilePos* locatorPosition = pStructurePiece->getLocatorPosition(); - if (pStructureStart->isValid()) - { + int dx = locatorPosition->x - cellX; + int dy = locatorPosition->y - cellY; + int dz = locatorPosition->z - cellZ; + double dist = dx + dx * dy * dy + dz * dz; - //StructurePiece *pStructurePiece = pStructureStart->getPieces().get(0); - StructurePiece* pStructurePiece = * pStructureStart->getPieces()->begin(); - TilePos *locatorPosition = pStructurePiece->getLocatorPosition(); + if (dist < minDistance) { + minDistance = dist; + selected = locatorPosition; + } + } + } + if (selected != NULL) { + return selected; + } else { + std::vector* guesstimatedFeaturePositions = + getGuesstimatedFeaturePositions(); + if (guesstimatedFeaturePositions != NULL) { + TilePos* pSelectedPos = new TilePos(0, 0, 0); - int dx = locatorPosition->x - cellX; - int dy = locatorPosition->y - cellY; - int dz = locatorPosition->z - cellZ; - double dist = dx + dx * dy * dy + dz * dz; + for (AUTO_VAR(it, guesstimatedFeaturePositions->begin()); + it != guesstimatedFeaturePositions->end(); ++it) { + int dx = (*it).x - cellX; + int dy = (*it).y - cellY; + int dz = (*it).z - cellZ; + double dist = dx + dx * dy * dy + dz * dz; - if (dist < minDistance) - { - minDistance = dist; - selected = locatorPosition; - } - } - } - if (selected != NULL) - { - return selected; - } - else - { - std::vector *guesstimatedFeaturePositions = getGuesstimatedFeaturePositions(); - if (guesstimatedFeaturePositions != NULL) - { - TilePos *pSelectedPos = new TilePos(0,0,0); - - for(AUTO_VAR(it, guesstimatedFeaturePositions->begin()); it != guesstimatedFeaturePositions->end(); ++it) - { - int dx = (*it).x - cellX; - int dy = (*it).y - cellY; - int dz = (*it).z - cellZ; - double dist = dx + dx * dy * dy + dz * dz; - - if (dist < minDistance) - { - minDistance = dist; - pSelectedPos->x = (*it).x; - pSelectedPos->y = (*it).y; - pSelectedPos->z = (*it).z; - } - } - delete guesstimatedFeaturePositions; - return pSelectedPos; - } - } - return NULL; + if (dist < minDistance) { + minDistance = dist; + pSelectedPos->x = (*it).x; + pSelectedPos->y = (*it).y; + pSelectedPos->z = (*it).z; + } + } + delete guesstimatedFeaturePositions; + return pSelectedPos; + } + } + return NULL; } -std::vector *StructureFeature::getGuesstimatedFeaturePositions() -{ - return NULL; +std::vector* StructureFeature::getGuesstimatedFeaturePositions() { + return NULL; } diff --git a/Minecraft.World/WorldGen/Features/StructureFeature.h b/Minecraft.World/WorldGen/Features/StructureFeature.h index 6668fef44..c6fcca9a1 100644 --- a/Minecraft.World/WorldGen/Features/StructureFeature.h +++ b/Minecraft.World/WorldGen/Features/StructureFeature.h @@ -2,39 +2,40 @@ #include "LargeFeature.h" class StructureStart; -class StructureFeature : public LargeFeature -{ +class StructureFeature : public LargeFeature { public: - // 4J added - Maps to values in the game rules xml - enum EFeatureTypes - { - eFeature_Mineshaft, - eFeature_NetherBridge, - eFeature_Temples, - eFeature_Stronghold, - eFeature_Village, - }; + // 4J added - Maps to values in the game rules xml + enum EFeatureTypes { + eFeature_Mineshaft, + eFeature_NetherBridge, + eFeature_Temples, + eFeature_Stronghold, + eFeature_Village, + }; protected: - std::unordered_map<__int64, StructureStart *> cachedStructures; + std::unordered_map<__int64, StructureStart*> cachedStructures; public: - ~StructureFeature(); + ~StructureFeature(); - virtual void addFeature(Level *level, int x, int z, int xOffs, int zOffs, byteArray blocks); + virtual void addFeature(Level* level, int x, int z, int xOffs, int zOffs, + byteArray blocks); - bool postProcess(Level *level, Random *random, int chunkX, int chunkZ); + bool postProcess(Level* level, Random* random, int chunkX, int chunkZ); bool isIntersection(int cellX, int cellZ); - bool isInsideFeature(int cellX, int cellY, int cellZ); - TilePos *getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ); + bool isInsideFeature(int cellX, int cellY, int cellZ); + TilePos* getNearestGeneratedFeature(Level* level, int cellX, int cellY, + int cellZ); + protected: - std::vector *getGuesstimatedFeaturePositions(); + std::vector* getGuesstimatedFeaturePositions(); /** * Returns true if the given chunk coordinates should hold a structure * source. - * + * * @param x * chunk x * @param z @@ -42,17 +43,17 @@ protected: * @return */ protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat=false) = 0; + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat = false) = 0; /** * Creates a new instance of a structure source at the given chunk * coordinates. - * + * * @param x * chunk x * @param z * chunk z * @return */ - virtual StructureStart *createStructureStart(int x, int z) = 0; + virtual StructureStart* createStructureStart(int x, int z) = 0; }; diff --git a/Minecraft.World/WorldGen/Features/SwampTreeFeature.cpp b/Minecraft.World/WorldGen/Features/SwampTreeFeature.cpp index 5dfb63a01..ac3007d9f 100644 --- a/Minecraft.World/WorldGen/Features/SwampTreeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/SwampTreeFeature.cpp @@ -4,128 +4,115 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Util/JavaMath.h" -bool SwampTreeFeature::place(Level *level, Random *random, int x, int y, int z) -{ - int treeHeight = random->nextInt(4) + 5; - while (level->getMaterial(x, y - 1, z) == Material::water) - y--; +bool SwampTreeFeature::place(Level* level, Random* random, int x, int y, + int z) { + int treeHeight = random->nextInt(4) + 5; + while (level->getMaterial(x, y - 1, z) == Material::water) y--; - bool free = true; - if (y < 1 || y + treeHeight + 1 > Level::genDepth) return false; + bool free = true; + if (y < 1 || y + treeHeight + 1 > Level::genDepth) return false; - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - 3, y - 1, z - 3, x + 3, y + treeHeight, z + 3); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - 3, y - 1, z - 3, x + 3, y + treeHeight, z + 3); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } - for (int yy = y; yy <= y + 1 + treeHeight; yy++) - { - int r = 1; - if (yy == y) r = 0; - if (yy >= y + 1 + treeHeight - 2) r = 3; - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::genDepth) - { - int tt = level->getTile(xx, yy, zz); - if (tt != 0 && tt != Tile::leaves_Id) - { - if (tt == Tile::calmWater_Id || tt == Tile::water_Id) - { - if (yy > y) free = false; - } - else - { - free = false; - } - } - } - else - { - free = false; - } - } - } - } + for (int yy = y; yy <= y + 1 + treeHeight; yy++) { + int r = 1; + if (yy == y) r = 0; + if (yy >= y + 1 + treeHeight - 2) r = 3; + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::genDepth) { + int tt = level->getTile(xx, yy, zz); + if (tt != 0 && tt != Tile::leaves_Id) { + if (tt == Tile::calmWater_Id || tt == Tile::water_Id) { + if (yy > y) free = false; + } else { + free = false; + } + } + } else { + free = false; + } + } + } + } - if (!free) return false; + if (!free) return false; - int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::genDepth - treeHeight - 1) return false; + int belowTile = level->getTile(x, y - 1, z); + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::genDepth - treeHeight - 1) + return false; - placeBlock(level, x, y - 1, z, Tile::dirt_Id); + placeBlock(level, x, y - 1, z, Tile::dirt_Id); - for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) - { - int yo = yy - (y + treeHeight); - int offs = 2 - yo / 2; - for (int xx = x - offs; xx <= x + offs; xx++) - { - int xo = xx - (x); - for (int zz = z - offs; zz <= z + offs; zz++) - { - int zo = zz - (z); - if (abs(xo) == offs && abs(zo) == offs && (random->nextInt(2) == 0 || yo == 0)) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id); - } - } - } + for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) { + int yo = yy - (y + treeHeight); + int offs = 2 - yo / 2; + for (int xx = x - offs; xx <= x + offs; xx++) { + int xo = xx - (x); + for (int zz = z - offs; zz <= z + offs; zz++) { + int zo = zz - (z); + if (abs(xo) == offs && abs(zo) == offs && + (random->nextInt(2) == 0 || yo == 0)) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id); + } + } + } - for (int hh = 0; hh < treeHeight; hh++) - { - int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id || t == Tile::water_Id || t == Tile::calmWater_Id) placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id); - } - - for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) - { - int yo = yy - (y + treeHeight); - int offs = 2 - yo / 2; - for (int xx = x - offs; xx <= x + offs; xx++) - { - for (int zz = z - offs; zz <= z + offs; zz++) - { - if (level->getTile(xx, yy, zz) == Tile::leaves_Id) - { - if (random->nextInt(4) == 0 && level->getTile(xx - 1, yy, zz) == 0) - { - addVine(level, xx - 1, yy, zz, VineTile::VINE_EAST); - } - if (random->nextInt(4) == 0 && level->getTile(xx + 1, yy, zz) == 0) - { - addVine(level, xx + 1, yy, zz, VineTile::VINE_WEST); - } - if (random->nextInt(4) == 0 && level->getTile(xx, yy, zz - 1) == 0) - { - addVine(level, xx, yy, zz - 1, VineTile::VINE_SOUTH); - } - if (random->nextInt(4) == 0 && level->getTile(xx, yy, zz + 1) == 0) - { - addVine(level, xx, yy, zz + 1, VineTile::VINE_NORTH); - } - } - } - } - } - return true; + for (int hh = 0; hh < treeHeight; hh++) { + int t = level->getTile(x, y + hh, z); + if (t == 0 || t == Tile::leaves_Id || t == Tile::water_Id || + t == Tile::calmWater_Id) + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id); + } + for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) { + int yo = yy - (y + treeHeight); + int offs = 2 - yo / 2; + for (int xx = x - offs; xx <= x + offs; xx++) { + for (int zz = z - offs; zz <= z + offs; zz++) { + if (level->getTile(xx, yy, zz) == Tile::leaves_Id) { + if (random->nextInt(4) == 0 && + level->getTile(xx - 1, yy, zz) == 0) { + addVine(level, xx - 1, yy, zz, VineTile::VINE_EAST); + } + if (random->nextInt(4) == 0 && + level->getTile(xx + 1, yy, zz) == 0) { + addVine(level, xx + 1, yy, zz, VineTile::VINE_WEST); + } + if (random->nextInt(4) == 0 && + level->getTile(xx, yy, zz - 1) == 0) { + addVine(level, xx, yy, zz - 1, VineTile::VINE_SOUTH); + } + if (random->nextInt(4) == 0 && + level->getTile(xx, yy, zz + 1) == 0) { + addVine(level, xx, yy, zz + 1, VineTile::VINE_NORTH); + } + } + } + } + } + return true; } -void SwampTreeFeature::addVine(Level *level, int xx, int yy, int zz, int dir) -{ +void SwampTreeFeature::addVine(Level* level, int xx, int yy, int zz, int dir) { placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); int maxDir = 4; - while (level->getTile(xx, --yy, zz) == 0 && maxDir > 0) - { + while (level->getTile(xx, --yy, zz) == 0 && maxDir > 0) { placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); maxDir--; } diff --git a/Minecraft.World/WorldGen/Features/SwampTreeFeature.h b/Minecraft.World/WorldGen/Features/SwampTreeFeature.h index e1c40b8f4..b5fdcd1fc 100644 --- a/Minecraft.World/WorldGen/Features/SwampTreeFeature.h +++ b/Minecraft.World/WorldGen/Features/SwampTreeFeature.h @@ -2,10 +2,10 @@ #include "Feature.h" class Random; -class SwampTreeFeature : public Feature -{ +class SwampTreeFeature : public Feature { public: - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); + private: - void addVine(Level *level, int xx, int yy, int zz, int dir); + void addVine(Level* level, int xx, int yy, int zz, int dir); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/TallGrassFeature.cpp b/Minecraft.World/WorldGen/Features/TallGrassFeature.cpp index e42d68274..53888823a 100644 --- a/Minecraft.World/WorldGen/Features/TallGrassFeature.cpp +++ b/Minecraft.World/WorldGen/Features/TallGrassFeature.cpp @@ -3,27 +3,24 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "TallGrassFeature.h" -TallGrassFeature::TallGrassFeature(int tile, int type) -{ - this->tile = tile; - this->type = type; +TallGrassFeature::TallGrassFeature(int tile, int type) { + this->tile = tile; + this->type = type; } -bool TallGrassFeature::place(Level *level, Random *random, int x, int y, int z) -{ +bool TallGrassFeature::place(Level* level, Random* random, int x, int y, + int z) { int t = 0; - while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && y > 0) + while (((t = level->getTile(x, y, z)) == 0 || t == Tile::leaves_Id) && + y > 0) y--; - for (int i = 0; i < 128; i++) - { + for (int i = 0; i < 128; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2)) - { - if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) - { + if (level->isEmptyTile(x2, y2, z2)) { + if (Tile::tiles[tile]->canSurvive(level, x2, y2, z2)) { level->setTileAndDataNoUpdate(x2, y2, z2, tile, type); } } diff --git a/Minecraft.World/WorldGen/Features/TallGrassFeature.h b/Minecraft.World/WorldGen/Features/TallGrassFeature.h index f72df5426..9a99f5458 100644 --- a/Minecraft.World/WorldGen/Features/TallGrassFeature.h +++ b/Minecraft.World/WorldGen/Features/TallGrassFeature.h @@ -1,14 +1,13 @@ #pragma once #include "Feature.h" -class TallGrassFeature : public Feature -{ +class TallGrassFeature : public Feature { private: - int tile; - int type; + int tile; + int type; public: - TallGrassFeature (int tile, int type); + TallGrassFeature(int tile, int type); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/TownFeature.h b/Minecraft.World/WorldGen/Features/TownFeature.h index 446daaea0..af554cefc 100644 --- a/Minecraft.World/WorldGen/Features/TownFeature.h +++ b/Minecraft.World/WorldGen/Features/TownFeature.h @@ -1,5 +1,3 @@ #pragma once -class TownFeature : public LargeFeature -{ -}; \ No newline at end of file +class TownFeature : public LargeFeature {}; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/TreeFeature.cpp b/Minecraft.World/WorldGen/Features/TreeFeature.cpp index a6565d57e..4b5f02bac 100644 --- a/Minecraft.World/WorldGen/Features/TreeFeature.cpp +++ b/Minecraft.World/WorldGen/Features/TreeFeature.cpp @@ -3,177 +3,182 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "TreeFeature.h" -TreeFeature::TreeFeature(bool doUpdate) : Feature(doUpdate), baseHeight(4), trunkType(0), leafType(0), addJungleFeatures(false) -{ +TreeFeature::TreeFeature(bool doUpdate) + : Feature(doUpdate), + baseHeight(4), + trunkType(0), + leafType(0), + addJungleFeatures(false) {} + +TreeFeature::TreeFeature(bool doUpdate, int baseHeight, int trunkType, + int leafType, bool addJungleFeatures) + : Feature(doUpdate), + baseHeight(baseHeight), + trunkType(trunkType), + leafType(leafType), + addJungleFeatures(addJungleFeatures) {} + +bool TreeFeature::place(Level* level, Random* random, int x, int y, int z) { + int treeHeight = random->nextInt(3) + baseHeight; + + bool free = true; + if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) return false; + + // 4J Stu Added to stop tree features generating areas previously place by + // game rule generation + if (app.getLevelGenerationOptions() != NULL) { + PIXBeginNamedEvent(0, "TreeFeature checking intersects"); + LevelGenerationOptions* levelGenOptions = + app.getLevelGenerationOptions(); + bool intersects = levelGenOptions->checkIntersects( + x - 2, y - 1, z - 2, x + 2, y + treeHeight, z + 2); + PIXEndNamedEvent(); + if (intersects) { + // app.DebugPrintf("Skipping reeds feature generation as it overlaps + // a game rule structure\n"); + return false; + } + } + + for (int yy = y; yy <= y + 1 + treeHeight; yy++) { + int r = 1; + if (yy == y) r = 0; + if (yy >= y + 1 + treeHeight - 2) r = 2; + for (int xx = x - r; xx <= x + r && free; xx++) { + for (int zz = z - r; zz <= z + r && free; zz++) { + if (yy >= 0 && yy < Level::maxBuildHeight) { + int tt = level->getTile(xx, yy, zz); + if (tt != 0 && tt != Tile::leaves_Id && + tt != Tile::grass_Id && tt != Tile::dirt_Id && + tt != Tile::treeTrunk_Id) + free = false; + } else { + free = false; + } + } + } + } + + if (!free) return false; + + int belowTile = level->getTile(x, y - 1, z); + if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || + y >= Level::maxBuildHeight - treeHeight - 1) + return false; + + placeBlock(level, x, y - 1, z, Tile::dirt_Id, 0); + + PIXBeginNamedEvent(0, "Placing TreeFeature leaves"); + int grassHeight = 3; + int extraWidth = 0; + // 4J Stu - Generate leaves from the top down to stop having to recalc + // heightmaps + for (int yy = y + treeHeight; yy >= y - grassHeight + treeHeight; yy--) { + int yo = yy - (y + treeHeight); + int offs = extraWidth + 1 - yo / 2; + for (int xx = x - offs; xx <= x + offs; xx++) { + int xo = xx - (x); + for (int zz = z - offs; zz <= z + offs; zz++) { + int zo = zz - (z); + if (abs(xo) == offs && abs(zo) == offs && + (random->nextInt(2) == 0 || yo == 0)) + continue; + if (!Tile::solid[level->getTile(xx, yy, zz)]) + placeBlock(level, xx, yy, zz, Tile::leaves_Id, leafType); + } + } + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Placing TreeFeature trunks"); + for (int hh = 0; hh < treeHeight; hh++) { + int t = level->getTile(x, y + hh, z); + if (t == 0 || t == Tile::leaves_Id) { + placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, trunkType); + if (addJungleFeatures && hh > 0) { + if (random->nextInt(3) > 0 && + level->isEmptyTile(x - 1, y + hh, z)) { + placeBlock(level, x - 1, y + hh, z, Tile::vine_Id, + VineTile::VINE_EAST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x + 1, y + hh, z)) { + placeBlock(level, x + 1, y + hh, z, Tile::vine_Id, + VineTile::VINE_WEST); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x, y + hh, z - 1)) { + placeBlock(level, x, y + hh, z - 1, Tile::vine_Id, + VineTile::VINE_SOUTH); + } + if (random->nextInt(3) > 0 && + level->isEmptyTile(x, y + hh, z + 1)) { + placeBlock(level, x, y + hh, z + 1, Tile::vine_Id, + VineTile::VINE_NORTH); + } + } + } + } + PIXEndNamedEvent(); + if (addJungleFeatures) { + PIXBeginNamedEvent(0, "TreeFeature adding vines"); + for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) { + int yo = yy - (y + treeHeight); + int offs = 2 - yo / 2; + for (int xx = x - offs; xx <= x + offs; xx++) { + for (int zz = z - offs; zz <= z + offs; zz++) { + if (level->getTile(xx, yy, zz) == Tile::leaves_Id) { + if (random->nextInt(4) == 0 && + level->getTile(xx - 1, yy, zz) == 0) { + addVine(level, xx - 1, yy, zz, VineTile::VINE_EAST); + } + if (random->nextInt(4) == 0 && + level->getTile(xx + 1, yy, zz) == 0) { + addVine(level, xx + 1, yy, zz, VineTile::VINE_WEST); + } + if (random->nextInt(4) == 0 && + level->getTile(xx, yy, zz - 1) == 0) { + addVine(level, xx, yy, zz - 1, + VineTile::VINE_SOUTH); + } + if (random->nextInt(4) == 0 && + level->getTile(xx, yy, zz + 1) == 0) { + addVine(level, xx, yy, zz + 1, + VineTile::VINE_NORTH); + } + } + } + } + } + PIXEndNamedEvent(); + // also chance for cocoa plants around stem + if (random->nextInt(5) == 0 && treeHeight > 5) { + PIXBeginNamedEvent(0, "TreeFeature adding cocoa"); + for (int rows = 0; rows < 2; rows++) { + for (int dir = 0; dir < 4; dir++) { + if (random->nextInt(4 - rows) == 0) { + int age = random->nextInt(3); + placeBlock(level, + x + Direction::STEP_X + [Direction::DIRECTION_OPPOSITE[dir]], + y + treeHeight - 5 + rows, + z + Direction::STEP_Z + [Direction::DIRECTION_OPPOSITE[dir]], + Tile::cocoa_Id, (age << 2) | dir); + } + } + } + PIXEndNamedEvent(); + } + } + + return true; } -TreeFeature::TreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType, bool addJungleFeatures) : Feature(doUpdate), baseHeight(baseHeight), trunkType(trunkType), leafType(leafType), addJungleFeatures(addJungleFeatures) -{ -} - -bool TreeFeature::place(Level *level, Random *random, int x, int y, int z) -{ - int treeHeight = random->nextInt(3) + baseHeight; - - bool free = true; - if (y < 1 || y + treeHeight + 1 > Level::maxBuildHeight) return false; - - // 4J Stu Added to stop tree features generating areas previously place by game rule generation - if(app.getLevelGenerationOptions() != NULL) - { - PIXBeginNamedEvent(0,"TreeFeature checking intersects"); - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - bool intersects = levelGenOptions->checkIntersects(x - 2, y - 1, z - 2, x + 2, y + treeHeight, z + 2); - PIXEndNamedEvent(); - if(intersects) - { - //app.DebugPrintf("Skipping reeds feature generation as it overlaps a game rule structure\n"); - return false; - } - } - - for (int yy = y; yy <= y + 1 + treeHeight; yy++) - { - int r = 1; - if (yy == y) r = 0; - if (yy >= y + 1 + treeHeight - 2) r = 2; - for (int xx = x - r; xx <= x + r && free; xx++) - { - for (int zz = z - r; zz <= z + r && free; zz++) - { - if (yy >= 0 && yy < Level::maxBuildHeight) - { - int tt = level->getTile(xx, yy, zz); - if (tt != 0 && tt != Tile::leaves_Id && tt != Tile::grass_Id && tt != Tile::dirt_Id && tt != Tile::treeTrunk_Id) free = false; - } - else - { - free = false; - } - } - } - } - - if (!free) return false; - - int belowTile = level->getTile(x, y - 1, z); - if ((belowTile != Tile::grass_Id && belowTile != Tile::dirt_Id) || y >= Level::maxBuildHeight - treeHeight - 1) return false; - - placeBlock(level, x, y - 1, z, Tile::dirt_Id, 0); - - PIXBeginNamedEvent(0,"Placing TreeFeature leaves"); - int grassHeight = 3; - int extraWidth = 0; - // 4J Stu - Generate leaves from the top down to stop having to recalc heightmaps - for (int yy = y + treeHeight; yy >= y - grassHeight + treeHeight; yy--) - { - int yo = yy - (y + treeHeight); - int offs = extraWidth + 1 - yo / 2; - for (int xx = x - offs; xx <= x + offs; xx++) - { - int xo = xx - (x); - for (int zz = z - offs; zz <= z + offs; zz++) - { - int zo = zz - (z); - if (abs(xo) == offs && abs(zo) == offs && (random->nextInt(2) == 0 || yo == 0)) continue; - if (!Tile::solid[level->getTile(xx, yy, zz)]) placeBlock(level, xx, yy, zz, Tile::leaves_Id, leafType); - } - } - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Placing TreeFeature trunks"); - for (int hh = 0; hh < treeHeight; hh++) - { - int t = level->getTile(x, y + hh, z); - if (t == 0 || t == Tile::leaves_Id) - { - placeBlock(level, x, y + hh, z, Tile::treeTrunk_Id, trunkType); - if (addJungleFeatures && hh > 0) - { - if (random->nextInt(3) > 0 && level->isEmptyTile(x - 1, y + hh, z)) - { - placeBlock(level, x - 1, y + hh, z, Tile::vine_Id, VineTile::VINE_EAST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x + 1, y + hh, z)) - { - placeBlock(level, x + 1, y + hh, z, Tile::vine_Id, VineTile::VINE_WEST); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x, y + hh, z - 1)) - { - placeBlock(level, x, y + hh, z - 1, Tile::vine_Id, VineTile::VINE_SOUTH); - } - if (random->nextInt(3) > 0 && level->isEmptyTile(x, y + hh, z + 1)) - { - placeBlock(level, x, y + hh, z + 1, Tile::vine_Id, VineTile::VINE_NORTH); - } - } - } - } - PIXEndNamedEvent(); - if (addJungleFeatures) - { - PIXBeginNamedEvent(0,"TreeFeature adding vines"); - for (int yy = y - 3 + treeHeight; yy <= y + treeHeight; yy++) - { - int yo = yy - (y + treeHeight); - int offs = 2 - yo / 2; - for (int xx = x - offs; xx <= x + offs; xx++) - { - for (int zz = z - offs; zz <= z + offs; zz++) - { - if (level->getTile(xx, yy, zz) == Tile::leaves_Id) - { - if (random->nextInt(4) == 0 && level->getTile(xx - 1, yy, zz) == 0) - { - addVine(level, xx - 1, yy, zz, VineTile::VINE_EAST); - } - if (random->nextInt(4) == 0 && level->getTile(xx + 1, yy, zz) == 0) - { - addVine(level, xx + 1, yy, zz, VineTile::VINE_WEST); - } - if (random->nextInt(4) == 0 && level->getTile(xx, yy, zz - 1) == 0) - { - addVine(level, xx, yy, zz - 1, VineTile::VINE_SOUTH); - } - if (random->nextInt(4) == 0 && level->getTile(xx, yy, zz + 1) == 0) - { - addVine(level, xx, yy, zz + 1, VineTile::VINE_NORTH); - } - } - } - } - } - PIXEndNamedEvent(); - // also chance for cocoa plants around stem - if (random->nextInt(5) == 0 && treeHeight > 5) - { - PIXBeginNamedEvent(0,"TreeFeature adding cocoa"); - for (int rows = 0; rows < 2; rows++) - { - for (int dir = 0; dir < 4; dir++) - { - if (random->nextInt(4 - rows) == 0) - { - int age = random->nextInt(3); - placeBlock(level, x + Direction::STEP_X[Direction::DIRECTION_OPPOSITE[dir]], y + treeHeight - 5 + rows, z + Direction::STEP_Z[Direction::DIRECTION_OPPOSITE[dir]], - Tile::cocoa_Id, (age << 2) | dir); - } - } - } - PIXEndNamedEvent(); - } - } - - return true; -} - -void TreeFeature::addVine(Level *level, int xx, int yy, int zz, int dir) -{ - placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); - int maxDir = 4; - while (level->getTile(xx, --yy, zz) == 0 && maxDir > 0) - { - placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); - maxDir--; - } +void TreeFeature::addVine(Level* level, int xx, int yy, int zz, int dir) { + placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); + int maxDir = 4; + while (level->getTile(xx, --yy, zz) == 0 && maxDir > 0) { + placeBlock(level, xx, yy, zz, Tile::vine_Id, dir); + maxDir--; + } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/TreeFeature.h b/Minecraft.World/WorldGen/Features/TreeFeature.h index c58f72d9e..e3c3d8838 100644 --- a/Minecraft.World/WorldGen/Features/TreeFeature.h +++ b/Minecraft.World/WorldGen/Features/TreeFeature.h @@ -1,20 +1,20 @@ #pragma once #include "Feature.h" -class TreeFeature : public Feature -{ +class TreeFeature : public Feature { private: - const int baseHeight; - const int trunkType; - const int leafType; - const bool addJungleFeatures; + const int baseHeight; + const int trunkType; + const int leafType; + const bool addJungleFeatures; public: - TreeFeature(bool doUpdate); - TreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType, bool addJungleFeatures); + TreeFeature(bool doUpdate); + TreeFeature(bool doUpdate, int baseHeight, int trunkType, int leafType, + bool addJungleFeatures); - virtual bool place(Level *level, Random *random, int x, int y, int z); + virtual bool place(Level* level, Random* random, int x, int y, int z); private: - void addVine(Level *level, int xx, int yy, int zz, int dir); + void addVine(Level* level, int xx, int yy, int zz, int dir); }; diff --git a/Minecraft.World/WorldGen/Features/VillageFeature.cpp b/Minecraft.World/WorldGen/Features/VillageFeature.cpp index ab3755071..95d62a5f7 100644 --- a/Minecraft.World/WorldGen/Features/VillageFeature.cpp +++ b/Minecraft.World/WorldGen/Features/VillageFeature.cpp @@ -5,39 +5,31 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.dimension.h" -std::vector VillageFeature::allowedBiomes; +std::vector VillageFeature::allowedBiomes; -void VillageFeature::staticCtor() -{ - allowedBiomes.push_back( Biome::plains ); - allowedBiomes.push_back( Biome::desert ); +void VillageFeature::staticCtor() { + allowedBiomes.push_back(Biome::plains); + allowedBiomes.push_back(Biome::desert); } - -VillageFeature::VillageFeature(int villageSizeModifier, int iXZSize) : StructureFeature(), villageSizeModifier(villageSizeModifier) -{ - m_iXZSize=iXZSize; +VillageFeature::VillageFeature(int villageSizeModifier, int iXZSize) + : StructureFeature(), villageSizeModifier(villageSizeModifier) { + m_iXZSize = iXZSize; } -bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) -{ +bool VillageFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { int townSpacing; #ifdef _LARGE_WORLDS - if(level->dimension->getXZSize() > 128) - { - townSpacing = 32; - } - else + if (level->dimension->getXZSize() > 128) { + townSpacing = 32; + } else #endif - if(bIsSuperflat) - { - townSpacing= 32; - } - else - { - townSpacing= 16;// 4J change 32; - } + if (bIsSuperflat) { + townSpacing = 32; + } else { + townSpacing = 16; // 4J change 32; + } int minTownSeparation = 8; @@ -48,7 +40,8 @@ bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) int xCenterTownChunk = x / townSpacing; int zCenterTownChunk = z / townSpacing; - Random *r = level->getRandomFor(xCenterTownChunk, zCenterTownChunk, 10387312); + Random* r = + level->getRandomFor(xCenterTownChunk, zCenterTownChunk, 10387312); xCenterTownChunk *= townSpacing; zCenterTownChunk *= townSpacing; xCenterTownChunk += r->nextInt(townSpacing - minTownSeparation); @@ -56,19 +49,19 @@ bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) x = xx; z = zz; - bool forcePlacement = false; - LevelGenerationOptions *levelGenOptions = app.getLevelGenerationOptions(); - if( levelGenOptions != NULL ) - { - forcePlacement = levelGenOptions->isFeatureChunk(x,z,eFeature_Village); - } + bool forcePlacement = false; + LevelGenerationOptions* levelGenOptions = app.getLevelGenerationOptions(); + if (levelGenOptions != NULL) { + forcePlacement = + levelGenOptions->isFeatureChunk(x, z, eFeature_Village); + } - if (forcePlacement || (x == xCenterTownChunk && z == zCenterTownChunk) ) - { - bool biomeOk = level->getBiomeSource()->containsOnly(x * 16 + 8, z * 16 + 8, 0, allowedBiomes); - if (biomeOk) - { - //app.DebugPrintf("Biome ok for Village at %d, %d\n",(x * 16 + 8),(z * 16 + 8)); + if (forcePlacement || (x == xCenterTownChunk && z == zCenterTownChunk)) { + bool biomeOk = level->getBiomeSource()->containsOnly( + x * 16 + 8, z * 16 + 8, 0, allowedBiomes); + if (biomeOk) { + // app.DebugPrintf("Biome ok for Village at %d, %d\n",(x * 16 + + // 8),(z * 16 + 8)); return true; } } @@ -76,46 +69,46 @@ bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) return false; } -StructureStart *VillageFeature::createStructureStart(int x, int z) -{ - // 4J added - app.AddTerrainFeaturePosition(eTerrainFeature_Village,x,z); +StructureStart* VillageFeature::createStructureStart(int x, int z) { + // 4J added + app.AddTerrainFeaturePosition(eTerrainFeature_Village, x, z); - return new VillageStart(level, random, x, z, villageSizeModifier, m_iXZSize); + return new VillageStart(level, random, x, z, villageSizeModifier, + m_iXZSize); } -VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chunkX, int chunkZ, int villageSizeModifier, int iXZSize) -{ - valid = false; // 4J added initialiser - m_iXZSize=iXZSize; +VillageFeature::VillageStart::VillageStart(Level* level, Random* random, + int chunkX, int chunkZ, + int villageSizeModifier, + int iXZSize) { + valid = false; // 4J added initialiser + m_iXZSize = iXZSize; - std::list *pieceSet = VillagePieces::createPieceSet(random, villageSizeModifier); + std::list* pieceSet = + VillagePieces::createPieceSet(random, villageSizeModifier); // 4jcraft added casts to u - VillagePieces::StartPiece *startRoom = new VillagePieces::StartPiece(level->getBiomeSource(), 0, random, ((unsigned) chunkX << 4) + 2, ((unsigned) chunkZ << 4) + 2, pieceSet, villageSizeModifier, level); - pieces.push_back(startRoom); + VillagePieces::StartPiece* startRoom = new VillagePieces::StartPiece( + level->getBiomeSource(), 0, random, ((unsigned)chunkX << 4) + 2, + ((unsigned)chunkZ << 4) + 2, pieceSet, villageSizeModifier, level); + pieces.push_back(startRoom); startRoom->addChildren(startRoom, &pieces, random); - std::vector *pendingRoads = &startRoom->pendingRoads; - std::vector *pendingHouses = &startRoom->pendingHouses; - while (!pendingRoads->empty() || !pendingHouses->empty()) - { - + std::vector* pendingRoads = &startRoom->pendingRoads; + std::vector* pendingHouses = &startRoom->pendingHouses; + while (!pendingRoads->empty() || !pendingHouses->empty()) { // prioritize roads - if (pendingRoads->empty()) - { + if (pendingRoads->empty()) { int pos = random->nextInt((int)pendingHouses->size()); - AUTO_VAR(it, pendingHouses->begin() + pos); - StructurePiece *structurePiece = *it; - pendingHouses->erase(it); + AUTO_VAR(it, pendingHouses->begin() + pos); + StructurePiece* structurePiece = *it; + pendingHouses->erase(it); structurePiece->addChildren(startRoom, &pieces, random); - } - else - { + } else { int pos = random->nextInt((int)pendingRoads->size()); - AUTO_VAR(it, pendingRoads->begin() + pos); - StructurePiece *structurePiece = *it; - pendingRoads->erase(it); + AUTO_VAR(it, pendingRoads->begin() + pos); + StructurePiece* structurePiece = *it; + pendingRoads->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } } @@ -123,23 +116,23 @@ VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chu calculateBoundingBox(); int count = 0; - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) - { - StructurePiece *piece = *it; - if (dynamic_cast(piece) == NULL) - { + for (AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++) { + StructurePiece* piece = *it; + if (dynamic_cast(piece) == NULL) { count++; } - } - valid = count > 2; + } + valid = count > 2; } -bool VillageFeature::VillageStart::isValid() -{ - // 4J-PB - Adding a bounds check to ensure a village isn't over the edge of our world - we end up with half houses in that case - if((boundingBox->x0<(-m_iXZSize/2)) || (boundingBox->x1>(m_iXZSize/2)) || (boundingBox->z0<(-m_iXZSize/2)) || (boundingBox->z1>(m_iXZSize/2))) - { - valid=false; - } - return valid; +bool VillageFeature::VillageStart::isValid() { + // 4J-PB - Adding a bounds check to ensure a village isn't over the edge of + // our world - we end up with half houses in that case + if ((boundingBox->x0 < (-m_iXZSize / 2)) || + (boundingBox->x1 > (m_iXZSize / 2)) || + (boundingBox->z0 < (-m_iXZSize / 2)) || + (boundingBox->z1 > (m_iXZSize / 2))) { + valid = false; + } + return valid; } diff --git a/Minecraft.World/WorldGen/Features/VillageFeature.h b/Minecraft.World/WorldGen/Features/VillageFeature.h index 036304823..eede4c592 100644 --- a/Minecraft.World/WorldGen/Features/VillageFeature.h +++ b/Minecraft.World/WorldGen/Features/VillageFeature.h @@ -3,29 +3,30 @@ #include "../Structures/StructureStart.h" class Biome; -class VillageFeature : public StructureFeature -{ +class VillageFeature : public StructureFeature { private: - const int villageSizeModifier; + const int villageSizeModifier; + public: - static void staticCtor(); - static std::vector allowedBiomes; + static void staticCtor(); + static std::vector allowedBiomes; VillageFeature(int villageSizeModifier, int iXZSize); protected: - virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat=false); - virtual StructureStart *createStructureStart(int x, int z); + virtual bool isFeatureChunk(int x, int z, bool bIsSuperflat = false); + virtual StructureStart* createStructureStart(int x, int z); private: - class VillageStart : public StructureStart - { - private: - bool valid; - int m_iXZSize; - public: - VillageStart(Level *level, Random *random, int chunkX, int chunkZ, int villageSizeModifier,int iXZSize); + class VillageStart : public StructureStart { + private: + bool valid; + int m_iXZSize; + + public: + VillageStart(Level* level, Random* random, int chunkX, int chunkZ, + int villageSizeModifier, int iXZSize); bool isValid(); }; - int m_iXZSize; + int m_iXZSize; }; diff --git a/Minecraft.World/WorldGen/Features/VinesFeature.cpp b/Minecraft.World/WorldGen/Features/VinesFeature.cpp index d66c7d6e9..e6243cd02 100644 --- a/Minecraft.World/WorldGen/Features/VinesFeature.cpp +++ b/Minecraft.World/WorldGen/Features/VinesFeature.cpp @@ -4,36 +4,29 @@ #include "../../Headers/net.minecraft.h" #include "VinesFeature.h" +VinesFeature::VinesFeature() {} -VinesFeature::VinesFeature() -{ -} +bool VinesFeature::place(Level* level, Random* random, int x, int y, int z) { + int ox = x; + int oz = z; -bool VinesFeature::place(Level *level, Random *random, int x, int y, int z) -{ - int ox = x; - int oz = z; + while (y < 128) { + if (level->isEmptyTile(x, y, z)) { + for (int face = Facing::NORTH; face <= Facing::EAST; face++) { + if (Tile::vine->mayPlace(level, x, y, z, face)) { + level->setTileAndDataNoUpdate( + x, y, z, Tile::vine_Id, + 1 << Direction::FACING_DIRECTION + [Facing::OPPOSITE_FACING[face]]); + break; + } + } + } else { + x = ox + random->nextInt(4) - random->nextInt(4); + z = oz + random->nextInt(4) - random->nextInt(4); + } + y++; + } - while (y < 128) - { - if (level->isEmptyTile(x, y, z)) - { - for (int face = Facing::NORTH; face <= Facing::EAST; face++) - { - if (Tile::vine->mayPlace(level, x, y, z, face)) - { - level->setTileAndDataNoUpdate(x, y, z, Tile::vine_Id, 1 << Direction::FACING_DIRECTION[Facing::OPPOSITE_FACING[face]]); - break; - } - } - } - else - { - x = ox + random->nextInt(4) - random->nextInt(4); - z = oz + random->nextInt(4) - random->nextInt(4); - } - y++; - } - - return true; + return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/VinesFeature.h b/Minecraft.World/WorldGen/Features/VinesFeature.h index 8dea3df7d..99b8e473d 100644 --- a/Minecraft.World/WorldGen/Features/VinesFeature.h +++ b/Minecraft.World/WorldGen/Features/VinesFeature.h @@ -2,11 +2,9 @@ #include "Feature.h" -class VinesFeature : public Feature -{ - +class VinesFeature : public Feature { public: - VinesFeature(); + VinesFeature(); - bool place(Level *level, Random *random, int x, int y, int z); + bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Features/WaterlilyFeature.cpp b/Minecraft.World/WorldGen/Features/WaterlilyFeature.cpp index 6a6b9bc93..2f2abb8b8 100644 --- a/Minecraft.World/WorldGen/Features/WaterlilyFeature.cpp +++ b/Minecraft.World/WorldGen/Features/WaterlilyFeature.cpp @@ -3,17 +3,14 @@ #include "../../Headers/net.minecraft.world.level.tile.h" #include "../../Headers/net.minecraft.world.level.h" -bool WaterlilyFeature::place(Level *level, Random *random, int x, int y, int z) -{ - for (int i = 0; i < 10; i++) - { +bool WaterlilyFeature::place(Level* level, Random* random, int x, int y, + int z) { + for (int i = 0; i < 10; i++) { int x2 = x + random->nextInt(8) - random->nextInt(8); int y2 = y + random->nextInt(4) - random->nextInt(4); int z2 = z + random->nextInt(8) - random->nextInt(8); - if (level->isEmptyTile(x2, y2, z2)) - { - if (Tile::waterLily->mayPlace(level, x2, y2, z2)) - { + if (level->isEmptyTile(x2, y2, z2)) { + if (Tile::waterLily->mayPlace(level, x2, y2, z2)) { level->setTileNoUpdate(x2, y2, z2, Tile::waterLily_Id); } } diff --git a/Minecraft.World/WorldGen/Features/WaterlilyFeature.h b/Minecraft.World/WorldGen/Features/WaterlilyFeature.h index ddf2330f8..de2a2eaff 100644 --- a/Minecraft.World/WorldGen/Features/WaterlilyFeature.h +++ b/Minecraft.World/WorldGen/Features/WaterlilyFeature.h @@ -1,7 +1,6 @@ #pragma once #include "Feature.h" -class WaterlilyFeature : public Feature -{ - virtual bool place(Level *level, Random *random, int x, int y, int z); +class WaterlilyFeature : public Feature { + virtual bool place(Level* level, Random* random, int x, int y, int z); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/AddIslandLayer.cpp b/Minecraft.World/WorldGen/Layers/AddIslandLayer.cpp index 870bfb20f..a2c5e59a0 100644 --- a/Minecraft.World/WorldGen/Layers/AddIslandLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/AddIslandLayer.cpp @@ -2,63 +2,55 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Headers/net.minecraft.world.level.biome.h" -AddIslandLayer::AddIslandLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +AddIslandLayer::AddIslandLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray AddIslandLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo - 1; - int py = yo - 1; - int pw = w + 2; - int ph = h + 2; - intArray p = parent->getArea(px, py, pw, ph); +intArray AddIslandLayer::getArea(int xo, int yo, int w, int h) { + int px = xo - 1; + int py = yo - 1; + int pw = w + 2; + int ph = h + 2; + intArray p = parent->getArea(px, py, pw, ph); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - int n1 = p[(x + 0) + (y + 0) * pw]; - int n2 = p[(x + 2) + (y + 0) * pw]; - int n3 = p[(x + 0) + (y + 2) * pw]; - int n4 = p[(x + 2) + (y + 2) * pw]; - int c = p[(x + 1) + (y + 1) * pw]; - initRandom(x + xo, y + yo); - if (c == 0 && (n1 != 0 || n2 != 0 || n3 != 0 || n4 != 0)) - { - int odds = 1; - int swap = 1; - if (n1 != 0 && nextRandom(odds++) == 0) swap = n1; - if (n2 != 0 && nextRandom(odds++) == 0) swap = n2; - if (n3 != 0 && nextRandom(odds++) == 0) swap = n3; - if (n4 != 0 && nextRandom(odds++) == 0) swap = n4; - if (nextRandom(3) == 0) - { - result[x + y * w] = swap; - } - else - { - if (swap == Biome::iceFlats->id) result[x + y * w] = Biome::frozenOcean->id; - else result[x + y * w] = 0; - } - } - else if (c > 0 && (n1 == 0 || n2 == 0 || n3 == 0 || n4 == 0)) - { - if (nextRandom(5) == 0) - { - if (c == Biome::iceFlats->id) result[x + y * w] = Biome::frozenOcean->id; - else result[x + y * w] = 0; - } - else result[x + y * w] = c; - } - else - { - result[x + y * w] = c; - } - } - } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int n1 = p[(x + 0) + (y + 0) * pw]; + int n2 = p[(x + 2) + (y + 0) * pw]; + int n3 = p[(x + 0) + (y + 2) * pw]; + int n4 = p[(x + 2) + (y + 2) * pw]; + int c = p[(x + 1) + (y + 1) * pw]; + initRandom(x + xo, y + yo); + if (c == 0 && (n1 != 0 || n2 != 0 || n3 != 0 || n4 != 0)) { + int odds = 1; + int swap = 1; + if (n1 != 0 && nextRandom(odds++) == 0) swap = n1; + if (n2 != 0 && nextRandom(odds++) == 0) swap = n2; + if (n3 != 0 && nextRandom(odds++) == 0) swap = n3; + if (n4 != 0 && nextRandom(odds++) == 0) swap = n4; + if (nextRandom(3) == 0) { + result[x + y * w] = swap; + } else { + if (swap == Biome::iceFlats->id) + result[x + y * w] = Biome::frozenOcean->id; + else + result[x + y * w] = 0; + } + } else if (c > 0 && (n1 == 0 || n2 == 0 || n3 == 0 || n4 == 0)) { + if (nextRandom(5) == 0) { + if (c == Biome::iceFlats->id) + result[x + y * w] = Biome::frozenOcean->id; + else + result[x + y * w] = 0; + } else + result[x + y * w] = c; + } else { + result[x + y * w] = c; + } + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/AddIslandLayer.h b/Minecraft.World/WorldGen/Layers/AddIslandLayer.h index 3ad55f3aa..584d6bcd0 100644 --- a/Minecraft.World/WorldGen/Layers/AddIslandLayer.h +++ b/Minecraft.World/WorldGen/Layers/AddIslandLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class AddIslandLayer : public Layer -{ +class AddIslandLayer : public Layer { public: - AddIslandLayer(__int64 seedMixup, std::shared_ptrparent); + AddIslandLayer(__int64 seedMixup, std::shared_ptr parent); - intArray getArea(int xo, int yo, int w, int h); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.cpp b/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.cpp index 5d56f9295..2e4fd90a9 100644 --- a/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.cpp @@ -2,14 +2,13 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Headers/net.minecraft.world.level.biome.h" - -AddMushroomIslandLayer::AddMushroomIslandLayer(__int64 seedMixup, std::shared_ptr parent) : Layer(seedMixup) -{ - this->parent = parent; +AddMushroomIslandLayer::AddMushroomIslandLayer(__int64 seedMixup, + std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray AddMushroomIslandLayer::getArea(int xo, int yo, int w, int h) -{ +intArray AddMushroomIslandLayer::getArea(int xo, int yo, int w, int h) { int px = xo - 1; int py = yo - 1; int pw = w + 2; @@ -17,22 +16,18 @@ intArray AddMushroomIslandLayer::getArea(int xo, int yo, int w, int h) intArray p = parent->getArea(px, py, pw, ph); intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { int n1 = p[(x + 0) + (y + 0) * pw]; int n2 = p[(x + 2) + (y + 0) * pw]; int n3 = p[(x + 0) + (y + 2) * pw]; int n4 = p[(x + 2) + (y + 2) * pw]; int c = p[(x + 1) + (y + 1) * pw]; initRandom(x + xo, y + yo); - if (c == 0 && (n1 == 0 && n2 == 0 && n3 == 0 && n4 == 0) && nextRandom(100) == 0) - { + if (c == 0 && (n1 == 0 && n2 == 0 && n3 == 0 && n4 == 0) && + nextRandom(100) == 0) { result[x + y * w] = Biome::mushroomIsland->id; - } - else - { + } else { result[x + y * w] = c; } } diff --git a/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.h b/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.h index eecad4103..0e25b61f9 100644 --- a/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.h +++ b/Minecraft.World/WorldGen/Layers/AddMushroomIslandLayer.h @@ -1,8 +1,7 @@ #pragma once #include "Layer.h" -class AddMushroomIslandLayer : public Layer -{ +class AddMushroomIslandLayer : public Layer { public: AddMushroomIslandLayer(__int64 seedMixup, std::shared_ptr parent); virtual intArray getArea(int xo, int yo, int w, int h); diff --git a/Minecraft.World/WorldGen/Layers/AddSnowLayer.cpp b/Minecraft.World/WorldGen/Layers/AddSnowLayer.cpp index 54931c560..d10baed45 100644 --- a/Minecraft.World/WorldGen/Layers/AddSnowLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/AddSnowLayer.cpp @@ -2,13 +2,12 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Headers/net.minecraft.world.level.biome.h" -AddSnowLayer::AddSnowLayer(__int64 seedMixup, std::shared_ptr parent) : Layer(seedMixup) -{ - this->parent = parent; +AddSnowLayer::AddSnowLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray AddSnowLayer::getArea(int xo, int yo, int w, int h) -{ +intArray AddSnowLayer::getArea(int xo, int yo, int w, int h) { int px = xo - 1; int py = yo - 1; int pw = w + 2; @@ -16,21 +15,18 @@ intArray AddSnowLayer::getArea(int xo, int yo, int w, int h) intArray p = parent->getArea(px, py, pw, ph); intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { int c = p[(x + 1) + (y + 1) * pw]; initRandom(x + xo, y + yo); - if (c == 0) - { + if (c == 0) { result[x + y * w] = 0; - } - else - { + } else { int r = nextRandom(5); - if (r == 0) r = Biome::iceFlats->id; - else r = 1; + if (r == 0) + r = Biome::iceFlats->id; + else + r = 1; result[x + y * w] = r; } } diff --git a/Minecraft.World/WorldGen/Layers/AddSnowLayer.h b/Minecraft.World/WorldGen/Layers/AddSnowLayer.h index 45101266b..c5d56f90b 100644 --- a/Minecraft.World/WorldGen/Layers/AddSnowLayer.h +++ b/Minecraft.World/WorldGen/Layers/AddSnowLayer.h @@ -1,8 +1,7 @@ #pragma once #include "Layer.h" -class AddSnowLayer : public Layer -{ +class AddSnowLayer : public Layer { public: AddSnowLayer(__int64 seedMixup, std::shared_ptr parent); virtual intArray getArea(int xo, int yo, int w, int h); diff --git a/Minecraft.World/WorldGen/Layers/BiomeInitLayer.cpp b/Minecraft.World/WorldGen/Layers/BiomeInitLayer.cpp index 666bd8b02..c8377b5ef 100644 --- a/Minecraft.World/WorldGen/Layers/BiomeInitLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/BiomeInitLayer.cpp @@ -4,76 +4,58 @@ #include "../../Headers/net.minecraft.world.level.h" #include "BiomeInitLayer.h" -BiomeInitLayer::BiomeInitLayer(__int64 seed, std::shared_ptrparent, LevelType *levelType) : Layer(seed) -{ - this->parent = parent; +BiomeInitLayer::BiomeInitLayer(__int64 seed, std::shared_ptr parent, + LevelType* levelType) + : Layer(seed) { + this->parent = parent; - - if(levelType == LevelType::lvl_normal_1_1) - { - startBiomes = BiomeArray(6); - startBiomes[0] = Biome::desert; - startBiomes[1] = Biome::forest; - startBiomes[2] = Biome::extremeHills; - startBiomes[3] = Biome::swampland; - startBiomes[4] = Biome::plains; - startBiomes[5] = Biome::taiga; - } - else - { - startBiomes = BiomeArray(7); - startBiomes[0] = Biome::desert; - startBiomes[1] = Biome::forest; - startBiomes[2] = Biome::extremeHills; - startBiomes[3] = Biome::swampland; - startBiomes[4] = Biome::plains; - startBiomes[5] = Biome::taiga; - startBiomes[6] = Biome::jungle; - } + if (levelType == LevelType::lvl_normal_1_1) { + startBiomes = BiomeArray(6); + startBiomes[0] = Biome::desert; + startBiomes[1] = Biome::forest; + startBiomes[2] = Biome::extremeHills; + startBiomes[3] = Biome::swampland; + startBiomes[4] = Biome::plains; + startBiomes[5] = Biome::taiga; + } else { + startBiomes = BiomeArray(7); + startBiomes[0] = Biome::desert; + startBiomes[1] = Biome::forest; + startBiomes[2] = Biome::extremeHills; + startBiomes[3] = Biome::swampland; + startBiomes[4] = Biome::plains; + startBiomes[5] = Biome::taiga; + startBiomes[6] = Biome::jungle; + } } -BiomeInitLayer::~BiomeInitLayer() -{ - delete [] startBiomes.data; -} +BiomeInitLayer::~BiomeInitLayer() { delete[] startBiomes.data; } -intArray BiomeInitLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); +intArray BiomeInitLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - initRandom(x + xo, y + yo); + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + initRandom(x + xo, y + yo); int old = b[x + y * w]; - if (old == 0) - { + if (old == 0) { result[x + y * w] = 0; - } - else if (old == Biome::mushroomIsland->id) - { + } else if (old == Biome::mushroomIsland->id) { result[x + y * w] = old; + } else if (old == 1) { + result[x + y * w] = + startBiomes[nextRandom(startBiomes.length)]->id; + } else { + int isTaiga = startBiomes[nextRandom(startBiomes.length)]->id; + if (isTaiga == Biome::taiga->id) { + result[x + y * w] = isTaiga; + } else { + result[x + y * w] = Biome::iceFlats->id; + } } - else if (old == 1) - { - result[x + y * w] = startBiomes[nextRandom(startBiomes.length)]->id; - } - else - { - int isTaiga = startBiomes[nextRandom(startBiomes.length)]->id; - if (isTaiga == Biome::taiga->id) - { - result[x + y * w] = isTaiga; - } - else - { - result[x + y * w] = Biome::iceFlats->id; - } - } - } - } + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/BiomeInitLayer.h b/Minecraft.World/WorldGen/Layers/BiomeInitLayer.h index f85d1e949..c5ae6285e 100644 --- a/Minecraft.World/WorldGen/Layers/BiomeInitLayer.h +++ b/Minecraft.World/WorldGen/Layers/BiomeInitLayer.h @@ -4,13 +4,13 @@ class LevelType; -class BiomeInitLayer : public Layer -{ +class BiomeInitLayer : public Layer { private: - BiomeArray startBiomes; + BiomeArray startBiomes; public: - BiomeInitLayer(__int64 seed, std::shared_ptr parent, LevelType *levelType); - virtual ~BiomeInitLayer(); + BiomeInitLayer(__int64 seed, std::shared_ptr parent, + LevelType* levelType); + virtual ~BiomeInitLayer(); intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.cpp b/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.cpp index 9f6c90585..3cf640b2d 100644 --- a/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.cpp @@ -5,56 +5,49 @@ #include "../../Headers/net.minecraft.world.level.h" #include "BiomeOverrideLayer.h" - -BiomeOverrideLayer::BiomeOverrideLayer(int seedMixup) : Layer(seedMixup) -{ - m_biomeOverride = byteArray( width * height ); +BiomeOverrideLayer::BiomeOverrideLayer(int seedMixup) : Layer(seedMixup) { + m_biomeOverride = byteArray(width * height); #ifdef _WINDOWS64 - const std::wstring path = L"GameRules\\biomemap.bin"; + const std::wstring path = L"GameRules\\biomemap.bin"; #else - const std::wstring path = L"GAME:\\GameRules\\biomemap.bin"; + const std::wstring path = L"GAME:\\GameRules\\biomemap.bin"; #endif - const PortableFileIO::BinaryReadResult readResult = PortableFileIO::ReadBinaryFile(path, m_biomeOverride.data, m_biomeOverride.length); - if(readResult.status == PortableFileIO::BinaryReadStatus::not_found) - { - app.DebugPrintf("Biome override not found, using plains as default\n"); - memset(m_biomeOverride.data,Biome::plains->id,m_biomeOverride.length); - } - else if(readResult.status == PortableFileIO::BinaryReadStatus::too_large) - { - app.DebugPrintf("Biomemap binary is too large!!\n"); - __debugbreak(); - } - else if(readResult.status != PortableFileIO::BinaryReadStatus::ok) - { - app.FatalLoadError(); - } + const PortableFileIO::BinaryReadResult readResult = + PortableFileIO::ReadBinaryFile(path, m_biomeOverride.data, + m_biomeOverride.length); + if (readResult.status == PortableFileIO::BinaryReadStatus::not_found) { + app.DebugPrintf("Biome override not found, using plains as default\n"); + memset(m_biomeOverride.data, Biome::plains->id, m_biomeOverride.length); + } else if (readResult.status == + PortableFileIO::BinaryReadStatus::too_large) { + app.DebugPrintf("Biomemap binary is too large!!\n"); + __debugbreak(); + } else if (readResult.status != PortableFileIO::BinaryReadStatus::ok) { + app.FatalLoadError(); + } } -intArray BiomeOverrideLayer::getArea(int xo, int yo, int w, int h) -{ - intArray result = IntCache::allocate(w * h); +intArray BiomeOverrideLayer::getArea(int xo, int yo, int w, int h) { + intArray result = IntCache::allocate(w * h); - int xOrigin = xo + width/2; - int yOrigin = yo + height/2; - if(xOrigin < 0 ) xOrigin = 0; - if(xOrigin >= width) xOrigin = width - 1; - if(yOrigin < 0 ) yOrigin = 0; - if(yOrigin >= height) yOrigin = height - 1; - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - int curX = xOrigin + x; - int curY = yOrigin + y; - if(curX >= width) curX = width - 1; - if(curY >= height) curY = height - 1; - int index = curX + curY * width; + int xOrigin = xo + width / 2; + int yOrigin = yo + height / 2; + if (xOrigin < 0) xOrigin = 0; + if (xOrigin >= width) xOrigin = width - 1; + if (yOrigin < 0) yOrigin = 0; + if (yOrigin >= height) yOrigin = height - 1; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int curX = xOrigin + x; + int curY = yOrigin + y; + if (curX >= width) curX = width - 1; + if (curY >= height) curY = height - 1; + int index = curX + curY * width; - unsigned char headerValue = m_biomeOverride[index]; - result[x + y * w] = headerValue; - } - } - return result; + unsigned char headerValue = m_biomeOverride[index]; + result[x + y * w] = headerValue; + } + } + return result; } diff --git a/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.h b/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.h index cfa689eff..373d0ec59 100644 --- a/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.h +++ b/Minecraft.World/WorldGen/Layers/BiomeOverrideLayer.h @@ -4,15 +4,14 @@ class LevelType; -class BiomeOverrideLayer : public Layer -{ +class BiomeOverrideLayer : public Layer { private: - static const unsigned int width = 216; - static const unsigned int height = 216; + static const unsigned int width = 216; + static const unsigned int height = 216; - byteArray m_biomeOverride; + byteArray m_biomeOverride; public: - BiomeOverrideLayer(int seedMixup); - intArray getArea(int xo, int yo, int w, int h); + BiomeOverrideLayer(int seedMixup); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/DownfallLayer.cpp b/Minecraft.World/WorldGen/Layers/DownfallLayer.cpp index 2019981d7..d83cb0ed8 100644 --- a/Minecraft.World/WorldGen/Layers/DownfallLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/DownfallLayer.cpp @@ -2,20 +2,17 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -DownfallLayer::DownfallLayer(std::shared_ptrparent) : Layer(0) -{ - this->parent = parent; +DownfallLayer::DownfallLayer(std::shared_ptr parent) : Layer(0) { + this->parent = parent; } -intArray DownfallLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); +intArray DownfallLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int i = 0; i < w * h; i++) - { - result[i] = Biome::biomes[b[i]]->getDownfallInt(); - } + intArray result = IntCache::allocate(w * h); + for (int i = 0; i < w * h; i++) { + result[i] = Biome::biomes[b[i]]->getDownfallInt(); + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/DownfallLayer.h b/Minecraft.World/WorldGen/Layers/DownfallLayer.h index ed191b175..17aa1f2a8 100644 --- a/Minecraft.World/WorldGen/Layers/DownfallLayer.h +++ b/Minecraft.World/WorldGen/Layers/DownfallLayer.h @@ -2,9 +2,8 @@ #include "Layer.h" -class DownfallLayer : public Layer -{ +class DownfallLayer : public Layer { public: - DownfallLayer(std::shared_ptrparent); - intArray getArea(int xo, int yo, int w, int h); + DownfallLayer(std::shared_ptr parent); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.cpp b/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.cpp index f10429bec..88b45ea10 100644 --- a/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.cpp @@ -2,23 +2,23 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -DownfallMixerLayer::DownfallMixerLayer(std::shared_ptrdownfall, std::shared_ptrparent, int layer) : Layer(0) -{ - this->parent = parent; - this->downfall = downfall; - this->layer = layer; +DownfallMixerLayer::DownfallMixerLayer(std::shared_ptr downfall, + std::shared_ptr parent, int layer) + : Layer(0) { + this->parent = parent; + this->downfall = downfall; + this->layer = layer; } -intArray DownfallMixerLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); - intArray d = downfall->getArea(xo, yo, w, h); +intArray DownfallMixerLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); + intArray d = downfall->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int i = 0; i < w * h; i++) - { - result[i] = d[i] + (Biome::biomes[b[i]]->getDownfallInt() - d[i]) / (layer + 1); - } + intArray result = IntCache::allocate(w * h); + for (int i = 0; i < w * h; i++) { + result[i] = + d[i] + (Biome::biomes[b[i]]->getDownfallInt() - d[i]) / (layer + 1); + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.h b/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.h index c0149dce3..04a7db0c4 100644 --- a/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.h +++ b/Minecraft.World/WorldGen/Layers/DownfallMixerLayer.h @@ -2,13 +2,13 @@ #include "Layer.h" -class DownfallMixerLayer : public Layer -{ +class DownfallMixerLayer : public Layer { private: - std::shared_ptr downfall; - int layer; + std::shared_ptr downfall; + int layer; public: - DownfallMixerLayer(std::shared_ptr downfall, std::shared_ptr parent, int layer); - intArray getArea(int xo, int yo, int w, int h); + DownfallMixerLayer(std::shared_ptr downfall, + std::shared_ptr parent, int layer); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/FlatLayer.cpp b/Minecraft.World/WorldGen/Layers/FlatLayer.cpp index badedcc92..6cc234087 100644 --- a/Minecraft.World/WorldGen/Layers/FlatLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/FlatLayer.cpp @@ -1,20 +1,14 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -FlatLayer::FlatLayer(int val) : Layer(0) -{ - this->val = val; -} +FlatLayer::FlatLayer(int val) : Layer(0) { this->val = val; } -intArray FlatLayer::getArea(int xo, int yo, int w, int h) -{ - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - result[x + y * w] = val; - } - } - return result; +intArray FlatLayer::getArea(int xo, int yo, int w, int h) { + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + result[x + y * w] = val; + } + } + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/FlatLayer.h b/Minecraft.World/WorldGen/Layers/FlatLayer.h index a4592fb05..1941052d0 100644 --- a/Minecraft.World/WorldGen/Layers/FlatLayer.h +++ b/Minecraft.World/WorldGen/Layers/FlatLayer.h @@ -2,12 +2,11 @@ #include "Layer.h" -class FlatLayer : public Layer -{ +class FlatLayer : public Layer { private: - int val; + int val; public: - FlatLayer(int val); - intArray getArea(int xo, int yo, int w, int h); + FlatLayer(int val); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.cpp b/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.cpp index 70fb06100..2580fb77a 100644 --- a/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.cpp @@ -2,72 +2,67 @@ #include "../../Platform/System.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -FuzzyZoomLayer::FuzzyZoomLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +FuzzyZoomLayer::FuzzyZoomLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray FuzzyZoomLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo >> 1; - int py = yo >> 1; - int pw = (w >> 1) + 3; - int ph = (h >> 1) + 3; - intArray p = parent->getArea(px, py, pw, ph); +intArray FuzzyZoomLayer::getArea(int xo, int yo, int w, int h) { + int px = xo >> 1; + int py = yo >> 1; + int pw = (w >> 1) + 3; + int ph = (h >> 1) + 3; + intArray p = parent->getArea(px, py, pw, ph); - // 4jcraft added casts to unsigned to prevent shift of neg value - intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); - int ww = ((unsigned int) pw << 1); - for (int y = 0; y < ph - 1; y++) - { - int ry = (unsigned int) y << 1; - int pp = ry * ww; - int ul = p[(0 + 0) + (y + 0) * pw]; - int dl = p[(0 + 0) + (y + 1) * pw]; - for (int x = 0; x < pw - 1; x++) - { - initRandom((unsigned int) (x + px) << 1, (unsigned int) (y + py) << 1); - int ur = p[(x + 1) + (y + 0) * pw]; - int dr = p[(x + 1) + (y + 1) * pw]; + // 4jcraft added casts to unsigned to prevent shift of neg value + intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); + int ww = ((unsigned int)pw << 1); + for (int y = 0; y < ph - 1; y++) { + int ry = (unsigned int)y << 1; + int pp = ry * ww; + int ul = p[(0 + 0) + (y + 0) * pw]; + int dl = p[(0 + 0) + (y + 1) * pw]; + for (int x = 0; x < pw - 1; x++) { + initRandom((unsigned int)(x + px) << 1, (unsigned int)(y + py) + << 1); + int ur = p[(x + 1) + (y + 0) * pw]; + int dr = p[(x + 1) + (y + 1) * pw]; - tmp[pp] = ul; - tmp[pp++ + ww] = random(ul, dl); - tmp[pp] = random(ul, ur); - tmp[pp++ + ww] = random(ul, ur, dl, dr); + tmp[pp] = ul; + tmp[pp++ + ww] = random(ul, dl); + tmp[pp] = random(ul, ur); + tmp[pp++ + ww] = random(ul, ur, dl, dr); - ul = ur; - dl = dr; - } - } - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - System::arraycopy(tmp, (y + (yo & 1)) * ((unsigned int) pw << 1) + (xo & 1), &result, y * w, w); - } + ul = ur; + dl = dr; + } + } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + System::arraycopy(tmp, + (y + (yo & 1)) * ((unsigned int)pw << 1) + (xo & 1), + &result, y * w, w); + } - return result; + return result; } -int FuzzyZoomLayer::random(int a, int b) -{ - return nextRandom(2) == 0 ? a : b; +int FuzzyZoomLayer::random(int a, int b) { return nextRandom(2) == 0 ? a : b; } + +int FuzzyZoomLayer::random(int a, int b, int c, int d) { + int s = nextRandom(4); + if (s == 0) return a; + if (s == 1) return b; + if (s == 2) return c; + return d; } -int FuzzyZoomLayer::random(int a, int b, int c, int d) -{ - int s = nextRandom(4); - if (s == 0) return a; - if (s == 1) return b; - if (s == 2) return c; - return d; -} - -std::shared_ptrFuzzyZoomLayer::zoom(__int64 seed, std::shared_ptrsup, int count) -{ - std::shared_ptr result = sup; - for (int i = 0; i < count; i++) - { - result = std::shared_ptr(new FuzzyZoomLayer(seed + i, result)); - } - return result; +std::shared_ptr FuzzyZoomLayer::zoom(__int64 seed, + std::shared_ptr sup, + int count) { + std::shared_ptr result = sup; + for (int i = 0; i < count; i++) { + result = std::shared_ptr(new FuzzyZoomLayer(seed + i, result)); + } + return result; } diff --git a/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.h b/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.h index 06d03be40..0e657897b 100644 --- a/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.h +++ b/Minecraft.World/WorldGen/Layers/FuzzyZoomLayer.h @@ -2,16 +2,16 @@ #include "Layer.h" -class FuzzyZoomLayer : public Layer -{ +class FuzzyZoomLayer : public Layer { public: - FuzzyZoomLayer(__int64 seedMixup, std::shared_ptrparent); + FuzzyZoomLayer(__int64 seedMixup, std::shared_ptr parent); intArray getArea(int xo, int yo, int w, int h); protected: - int random(int a, int b); + int random(int a, int b); int random(int a, int b, int c, int d); public: - static std::shared_ptrzoom(__int64 seed, std::shared_ptrsup, int count); + static std::shared_ptr zoom(__int64 seed, std::shared_ptr sup, + int count); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.cpp b/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.cpp index 4275dec99..9093fa8ca 100644 --- a/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.cpp @@ -2,14 +2,13 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Headers/net.minecraft.world.level.biome.h" - -GrowMushroomIslandLayer::GrowMushroomIslandLayer(__int64 seedMixup, std::shared_ptr parent) : Layer(seedMixup) -{ - this->parent = parent; +GrowMushroomIslandLayer::GrowMushroomIslandLayer(__int64 seedMixup, + std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray GrowMushroomIslandLayer::getArea(int xo, int yo, int w, int h) -{ +intArray GrowMushroomIslandLayer::getArea(int xo, int yo, int w, int h) { int px = xo - 1; int py = yo - 1; int pw = w + 2; @@ -17,25 +16,23 @@ intArray GrowMushroomIslandLayer::getArea(int xo, int yo, int w, int h) intArray p = parent->getArea(px, py, pw, ph); intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { int n1 = p[(x + 0) + (y + 0) * pw]; int n2 = p[(x + 2) + (y + 0) * pw]; int n3 = p[(x + 0) + (y + 2) * pw]; int n4 = p[(x + 2) + (y + 2) * pw]; - + int c = p[(x + 1) + (y + 1) * pw]; - if( ( n1 == Biome::mushroomIsland->id ) || ( n2 == Biome::mushroomIsland->id ) || ( n3 == Biome::mushroomIsland->id ) || ( n4 == Biome::mushroomIsland->id ) ) - { - result[x + y * w] = Biome::mushroomIsland->id; - } - else - { - result[x + y * w] = c; - } + if ((n1 == Biome::mushroomIsland->id) || + (n2 == Biome::mushroomIsland->id) || + (n3 == Biome::mushroomIsland->id) || + (n4 == Biome::mushroomIsland->id)) { + result[x + y * w] = Biome::mushroomIsland->id; + } else { + result[x + y * w] = c; + } } } return result; diff --git a/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.h b/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.h index 874e28947..63150175e 100644 --- a/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.h +++ b/Minecraft.World/WorldGen/Layers/GrowMushroomIslandLayer.h @@ -1,8 +1,7 @@ #pragma once #include "Layer.h" -class GrowMushroomIslandLayer : public Layer -{ +class GrowMushroomIslandLayer : public Layer { public: GrowMushroomIslandLayer(__int64 seedMixup, std::shared_ptr parent); virtual intArray getArea(int xo, int yo, int w, int h); diff --git a/Minecraft.World/WorldGen/Layers/IslandLayer.cpp b/Minecraft.World/WorldGen/Layers/IslandLayer.cpp index 5f5e41395..b24c11ab8 100644 --- a/Minecraft.World/WorldGen/Layers/IslandLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/IslandLayer.cpp @@ -1,25 +1,19 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -IslandLayer::IslandLayer(__int64 seedMixup) : Layer(seedMixup) -{ -} +IslandLayer::IslandLayer(__int64 seedMixup) : Layer(seedMixup) {} -intArray IslandLayer::getArea(int xo, int yo, int w, int h) -{ - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - initRandom(xo + x, yo + y); - result[x + y * w] = (nextRandom(10) == 0) ? 1 : 0; - } - } - // if (0, 0) is located here, place an island - if (xo > -w && xo <= 0 && yo > -h && yo <= 0) - { - result[-xo + -yo * w] = 1; - } - return result; +intArray IslandLayer::getArea(int xo, int yo, int w, int h) { + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + initRandom(xo + x, yo + y); + result[x + y * w] = (nextRandom(10) == 0) ? 1 : 0; + } + } + // if (0, 0) is located here, place an island + if (xo > -w && xo <= 0 && yo > -h && yo <= 0) { + result[-xo + -yo * w] = 1; + } + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/IslandLayer.h b/Minecraft.World/WorldGen/Layers/IslandLayer.h index 09e90eb30..461ab0ffa 100644 --- a/Minecraft.World/WorldGen/Layers/IslandLayer.h +++ b/Minecraft.World/WorldGen/Layers/IslandLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class IslandLayer : public Layer -{ +class IslandLayer : public Layer { public: - IslandLayer(__int64 seedMixup); + IslandLayer(__int64 seedMixup); - intArray getArea(int xo, int yo, int w, int h); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/Layer.cpp b/Minecraft.World/WorldGen/Layers/Layer.cpp index 454ec8d5f..25f4203ea 100644 --- a/Minecraft.World/WorldGen/Layers/Layer.cpp +++ b/Minecraft.World/WorldGen/Layers/Layer.cpp @@ -16,188 +16,198 @@ libdivide::divider fast_d7(7); libdivide::divider fast_d10(10); #endif -LayerArray Layer::getDefaultLayers(__int64 seed, LevelType *levelType) -{ - // 4J - Some changes moved here from 1.2.3. Temperature & downfall layers are no longer created & returned, and a debug layer is isn't. - // For reference with regard to future merging, things NOT brought forward from the 1.2.3 version are new layer types that we - // don't have yet (shores, swamprivers, region hills etc.) - std::shared_ptrislandLayer = std::shared_ptr(new IslandLayer(1)); - islandLayer = std::shared_ptr(new FuzzyZoomLayer(2000, islandLayer)); - islandLayer = std::shared_ptr(new AddIslandLayer(1, islandLayer)); - islandLayer = std::shared_ptr(new ZoomLayer(2001, islandLayer)); - islandLayer = std::shared_ptr(new AddIslandLayer(2, islandLayer)); - islandLayer = std::shared_ptr(new AddSnowLayer(2, islandLayer)); - islandLayer = std::shared_ptr(new ZoomLayer(2002, islandLayer)); - islandLayer = std::shared_ptr(new AddIslandLayer(3, islandLayer)); - islandLayer = std::shared_ptr(new ZoomLayer(2003, islandLayer)); - islandLayer = std::shared_ptr(new AddIslandLayer(4, islandLayer)); -// islandLayer = std::shared_ptr(new AddMushroomIslandLayer(5, islandLayer)); // 4J - old position of mushroom island layer +LayerArray Layer::getDefaultLayers(__int64 seed, LevelType* levelType) { + // 4J - Some changes moved here from 1.2.3. Temperature & downfall layers + // are no longer created & returned, and a debug layer is isn't. For + // reference with regard to future merging, things NOT brought forward from + // the 1.2.3 version are new layer types that we don't have yet (shores, + // swamprivers, region hills etc.) + std::shared_ptr islandLayer = + std::shared_ptr(new IslandLayer(1)); + islandLayer = std::shared_ptr(new FuzzyZoomLayer(2000, islandLayer)); + islandLayer = std::shared_ptr(new AddIslandLayer(1, islandLayer)); + islandLayer = std::shared_ptr(new ZoomLayer(2001, islandLayer)); + islandLayer = std::shared_ptr(new AddIslandLayer(2, islandLayer)); + islandLayer = std::shared_ptr(new AddSnowLayer(2, islandLayer)); + islandLayer = std::shared_ptr(new ZoomLayer(2002, islandLayer)); + islandLayer = std::shared_ptr(new AddIslandLayer(3, islandLayer)); + islandLayer = std::shared_ptr(new ZoomLayer(2003, islandLayer)); + islandLayer = std::shared_ptr(new AddIslandLayer(4, islandLayer)); + // islandLayer = std::shared_ptr(new AddMushroomIslandLayer(5, + //islandLayer)); // 4J - old position of mushroom island layer - int zoomLevel = 4; - if (levelType == LevelType::lvl_largeBiomes) - { - zoomLevel = 6; - } + int zoomLevel = 4; + if (levelType == LevelType::lvl_largeBiomes) { + zoomLevel = 6; + } - std::shared_ptr riverLayer = islandLayer; - riverLayer = ZoomLayer::zoom(1000, riverLayer, 0); - riverLayer = std::shared_ptr(new RiverInitLayer(100, riverLayer)); - riverLayer = ZoomLayer::zoom(1000, riverLayer, zoomLevel + 2); - riverLayer = std::shared_ptr(new RiverLayer(1, riverLayer)); - riverLayer = std::shared_ptr(new SmoothLayer(1000, riverLayer)); + std::shared_ptr riverLayer = islandLayer; + riverLayer = ZoomLayer::zoom(1000, riverLayer, 0); + riverLayer = std::shared_ptr(new RiverInitLayer(100, riverLayer)); + riverLayer = ZoomLayer::zoom(1000, riverLayer, zoomLevel + 2); + riverLayer = std::shared_ptr(new RiverLayer(1, riverLayer)); + riverLayer = std::shared_ptr(new SmoothLayer(1000, riverLayer)); - std::shared_ptr biomeLayer = islandLayer; - biomeLayer = ZoomLayer::zoom(1000, biomeLayer, 0); - biomeLayer = std::shared_ptr(new BiomeInitLayer(200, biomeLayer, levelType)); + std::shared_ptr biomeLayer = islandLayer; + biomeLayer = ZoomLayer::zoom(1000, biomeLayer, 0); + biomeLayer = + std::shared_ptr(new BiomeInitLayer(200, biomeLayer, levelType)); - biomeLayer = ZoomLayer::zoom(1000, biomeLayer, 2); - biomeLayer = std::shared_ptr(new RegionHillsLayer(1000, biomeLayer)); + biomeLayer = ZoomLayer::zoom(1000, biomeLayer, 2); + biomeLayer = std::shared_ptr(new RegionHillsLayer(1000, biomeLayer)); - for (int i = 0; i < zoomLevel; i++) - { - biomeLayer = std::shared_ptr(new ZoomLayer(1000 + i, biomeLayer)); + for (int i = 0; i < zoomLevel; i++) { + biomeLayer = + std::shared_ptr(new ZoomLayer(1000 + i, biomeLayer)); - if (i == 0) biomeLayer = std::shared_ptr(new AddIslandLayer(3, biomeLayer)); - - if (i == 0) - { - // 4J - moved mushroom islands to here. This skips 3 zooms that the old location of the add was, making them about 1/8 of the original size. Adding - // them at this scale actually lets us place them near enough other land, if we add them at the same scale as java then they have to be too far out to see for - // the scale of our maps - biomeLayer = std::shared_ptr(new AddMushroomIslandLayer(5, biomeLayer)); - } + if (i == 0) + biomeLayer = + std::shared_ptr(new AddIslandLayer(3, biomeLayer)); - if (i == 1 ) - { - // 4J - now expand mushroom islands up again. This does a simple region grow to add a new mushroom island element when any of the neighbours are also mushroom islands. - // This helps make the islands into nice compact shapes of the type that are actually likely to be able to make an island out of the sea in a small space. Also - // helps the shore layer from doing too much damage in shrinking the islands we are making - biomeLayer = std::shared_ptr(new GrowMushroomIslandLayer(5, biomeLayer)); - // Note - this reduces the size of mushroom islands by turning their edges into shores. We are doing this at i == 1 rather than i == 0 as the original does - biomeLayer = std::shared_ptr(new ShoreLayer(1000, biomeLayer)); + if (i == 0) { + // 4J - moved mushroom islands to here. This skips 3 zooms that the + // old location of the add was, making them about 1/8 of the + // original size. Adding them at this scale actually lets us place + // them near enough other land, if we add them at the same scale as + // java then they have to be too far out to see for the scale of our + // maps + biomeLayer = std::shared_ptr( + new AddMushroomIslandLayer(5, biomeLayer)); + } - biomeLayer = std::shared_ptr(new SwampRiversLayer(1000, biomeLayer)); - } - } + if (i == 1) { + // 4J - now expand mushroom islands up again. This does a simple + // region grow to add a new mushroom island element when any of the + // neighbours are also mushroom islands. This helps make the islands + // into nice compact shapes of the type that are actually likely to + // be able to make an island out of the sea in a small space. Also + // helps the shore layer from doing too much damage in shrinking the + // islands we are making + biomeLayer = std::shared_ptr( + new GrowMushroomIslandLayer(5, biomeLayer)); + // Note - this reduces the size of mushroom islands by turning their + // edges into shores. We are doing this at i == 1 rather than i == 0 + // as the original does + biomeLayer = + std::shared_ptr(new ShoreLayer(1000, biomeLayer)); - biomeLayer = std::shared_ptr(new SmoothLayer(1000, biomeLayer)); + biomeLayer = + std::shared_ptr(new SwampRiversLayer(1000, biomeLayer)); + } + } - biomeLayer = std::shared_ptr(new RiverMixerLayer(100, biomeLayer, riverLayer)); + biomeLayer = std::shared_ptr(new SmoothLayer(1000, biomeLayer)); + + biomeLayer = std::shared_ptr( + new RiverMixerLayer(100, biomeLayer, riverLayer)); #ifndef _CONTENT_PACKAGE #ifdef _BIOME_OVERRIDE - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<(new BiomeOverrideLayer(1)); - } + if (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_EnableHeightWaterBiomeOverride)) { + biomeLayer = + std::shared_ptr(new BiomeOverrideLayer(1)); + } #endif #endif - std::shared_ptr debugLayer = biomeLayer; + std::shared_ptr debugLayer = biomeLayer; - std::shared_ptrzoomedLayer = std::shared_ptr(new VoronoiZoom(10, biomeLayer)); + std::shared_ptr zoomedLayer = + std::shared_ptr(new VoronoiZoom(10, biomeLayer)); - biomeLayer->init(seed); - zoomedLayer->init(seed); + biomeLayer->init(seed); + zoomedLayer->init(seed); - LayerArray result(3); - result[0] = biomeLayer; - result[1] = zoomedLayer; - result[2] = debugLayer; - return result; + LayerArray result(3); + result[0] = biomeLayer; + result[1] = zoomedLayer; + result[2] = debugLayer; + return result; } -Layer::Layer(__int64 seedMixup) -{ - parent = nullptr; +Layer::Layer(__int64 seedMixup) { + parent = nullptr; - // 4jcraft added casts to prevent signed int overflow - this->seedMixup = seedMixup; - this->seedMixup *= (uint64_t) this->seedMixup * 6364136223846793005l + 1442695040888963407l; - this->seedMixup = (uint64_t) this->seedMixup + seedMixup; - this->seedMixup *= (uint64_t) this->seedMixup * 6364136223846793005l + 1442695040888963407l; - this->seedMixup = (uint64_t) this->seedMixup + seedMixup; - this->seedMixup *= (uint64_t) this->seedMixup * 6364136223846793005l + 1442695040888963407l; - this->seedMixup = (uint64_t) this->seedMixup + seedMixup; + // 4jcraft added casts to prevent signed int overflow + this->seedMixup = seedMixup; + this->seedMixup *= + (uint64_t)this->seedMixup * 6364136223846793005l + 1442695040888963407l; + this->seedMixup = (uint64_t)this->seedMixup + seedMixup; + this->seedMixup *= + (uint64_t)this->seedMixup * 6364136223846793005l + 1442695040888963407l; + this->seedMixup = (uint64_t)this->seedMixup + seedMixup; + this->seedMixup *= + (uint64_t)this->seedMixup * 6364136223846793005l + 1442695040888963407l; + this->seedMixup = (uint64_t)this->seedMixup + seedMixup; } -void Layer::init(__int64 seed) -{ - this->seed = seed; - if (parent != NULL) parent->init(seed); - // 4jcraft added casts to prevent signed int overflow - this->seed *= (uint64_t) this->seed * 6364136223846793005l + 1442695040888963407l; - this->seed = (uint64_t) this->seed + seedMixup; - this->seed *= (uint64_t) this->seed * 6364136223846793005l + 1442695040888963407l; - this->seed = (uint64_t) this->seed + seedMixup; - this->seed *= (uint64_t) this->seed * 6364136223846793005l + 1442695040888963407l; - this->seed = (uint64_t) this->seed + seedMixup; +void Layer::init(__int64 seed) { + this->seed = seed; + if (parent != NULL) parent->init(seed); + // 4jcraft added casts to prevent signed int overflow + this->seed *= + (uint64_t)this->seed * 6364136223846793005l + 1442695040888963407l; + this->seed = (uint64_t)this->seed + seedMixup; + this->seed *= + (uint64_t)this->seed * 6364136223846793005l + 1442695040888963407l; + this->seed = (uint64_t)this->seed + seedMixup; + this->seed *= + (uint64_t)this->seed * 6364136223846793005l + 1442695040888963407l; + this->seed = (uint64_t)this->seed + seedMixup; } -void Layer::initRandom(__int64 x, __int64 y) -{ - rval = seed; - // 4jcraft added casts to prevent signed int overflow - rval *= (uint64_t) rval * 6364136223846793005l + 1442695040888963407l; - rval += (uint64_t) x; - rval *= (uint64_t) rval * 6364136223846793005l + 1442695040888963407l; - rval += (uint64_t) y; - rval *= (uint64_t) rval * 6364136223846793005l + 1442695040888963407l; - rval += (uint64_t) x; - rval *= (uint64_t) rval * 6364136223846793005l + 1442695040888963407l; - rval += (uint64_t) y; +void Layer::initRandom(__int64 x, __int64 y) { + rval = seed; + // 4jcraft added casts to prevent signed int overflow + rval *= (uint64_t)rval * 6364136223846793005l + 1442695040888963407l; + rval += (uint64_t)x; + rval *= (uint64_t)rval * 6364136223846793005l + 1442695040888963407l; + rval += (uint64_t)y; + rval *= (uint64_t)rval * 6364136223846793005l + 1442695040888963407l; + rval += (uint64_t)x; + rval *= (uint64_t)rval * 6364136223846793005l + 1442695040888963407l; + rval += (uint64_t)y; } -int Layer::nextRandom(int max) -{ +int Layer::nextRandom(int max) { #ifdef __PSVITA__ - // AP - 64bit mods are very slow on Vita. Replaced with a divide/mult for general case and a fast divide library for specific numbers - // todo - this can sometimes yield a different number to the original. There's a strange bug sometimes with Vita where if the line - // "result = (int) ((rval >> 24) % max);" is done twice in a row 'result' will not be the same. Need to speak to Sony about that - // Also need to compare level against a different platform using the same seed - int result; - long long temp = rval; - temp >>= 24; - if( max == 2 ) - { - result = temp-(temp/fast_d2)*2; - } - else if( max == 3 ) - { - result = temp-(temp/fast_d3)*3; - } - else if( max == 4 ) - { - result = temp-(temp/fast_d4)*4; - } - else if( max == 5 ) - { - result = temp-(temp/fast_d5)*5; - } - else if( max == 6 ) - { - result = temp-(temp/fast_d6)*6; - } - else if( max == 7 ) - { - result = temp-(temp/fast_d7)*7; - } - else if( max == 10 ) - { - result = temp-(temp/fast_d10)*10; - } - else - { - result = temp-(temp/max)*max; - } + // AP - 64bit mods are very slow on Vita. Replaced with a divide/mult for + // general case and a fast divide library for specific numbers todo - this + // can sometimes yield a different number to the original. There's a strange + // bug sometimes with Vita where if the line "result = (int) ((rval >> 24) % + // max);" is done twice in a row 'result' will not be the same. Need to + // speak to Sony about that Also need to compare level against a different + // platform using the same seed + int result; + long long temp = rval; + temp >>= 24; + if (max == 2) { + result = temp - (temp / fast_d2) * 2; + } else if (max == 3) { + result = temp - (temp / fast_d3) * 3; + } else if (max == 4) { + result = temp - (temp / fast_d4) * 4; + } else if (max == 5) { + result = temp - (temp / fast_d5) * 5; + } else if (max == 6) { + result = temp - (temp / fast_d6) * 6; + } else if (max == 7) { + result = temp - (temp / fast_d7) * 7; + } else if (max == 10) { + result = temp - (temp / fast_d10) * 10; + } else { + result = temp - (temp / max) * max; + } #else - int result = (int) ((rval >> 24) % max); + int result = (int)((rval >> 24) % max); #endif - if (result < 0) result += max; - // 4jcraft added cast to unsigned - rval *= (uint64_t) rval * 6364136223846793005l + 1442695040888963407l; - rval += (uint64_t) seed; - return result; + if (result < 0) result += max; + // 4jcraft added cast to unsigned + rval *= (uint64_t)rval * 6364136223846793005l + 1442695040888963407l; + rval += (uint64_t)seed; + return result; } diff --git a/Minecraft.World/WorldGen/Layers/Layer.h b/Minecraft.World/WorldGen/Layers/Layer.h index ec1598b4f..58090e3f8 100644 --- a/Minecraft.World/WorldGen/Layers/Layer.h +++ b/Minecraft.World/WorldGen/Layers/Layer.h @@ -8,30 +8,29 @@ class LevelType; #define _BIOME_OVERRIDE #endif -class Layer -{ +class Layer { private: - __int64 seed; + __int64 seed; protected: - std::shared_ptrparent; + std::shared_ptr parent; private: - __int64 rval; - __int64 seedMixup; + __int64 rval; + __int64 seedMixup; public: - static LayerArray getDefaultLayers(__int64 seed, LevelType *levelType); + static LayerArray getDefaultLayers(__int64 seed, LevelType* levelType); - Layer(__int64 seedMixup); - virtual ~Layer(){} + Layer(__int64 seedMixup); + virtual ~Layer() {} - virtual void init(__int64 seed); - virtual void initRandom(__int64 x, __int64 y); + virtual void init(__int64 seed); + virtual void initRandom(__int64 x, __int64 y); protected: - int nextRandom(int max); + int nextRandom(int max); public: - virtual intArray getArea(int xo, int yo, int w, int h) = 0; + virtual intArray getArea(int xo, int yo, int w, int h) = 0; }; diff --git a/Minecraft.World/WorldGen/Layers/RegionHillsLayer.cpp b/Minecraft.World/WorldGen/Layers/RegionHillsLayer.cpp index b085a58fd..cecccc7b3 100644 --- a/Minecraft.World/WorldGen/Layers/RegionHillsLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/RegionHillsLayer.cpp @@ -3,76 +3,52 @@ #include "../../Util/IntCache.h" #include "RegionHillsLayer.h" -RegionHillsLayer::RegionHillsLayer(__int64 seed, std::shared_ptr parent) : Layer(seed) -{ - this->parent = parent; +RegionHillsLayer::RegionHillsLayer(__int64 seed, std::shared_ptr parent) + : Layer(seed) { + this->parent = parent; } -intArray RegionHillsLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo - 1, yo - 1, w + 2, h + 2); +intArray RegionHillsLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo - 1, yo - 1, w + 2, h + 2); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - initRandom(x + xo, y + yo); - int old = b[(x + 1) + (y + 1) * (w + 2)]; - if (nextRandom(3) == 0) - { - int next = old; - if (old == Biome::desert->id) - { - next = Biome::desertHills->id; - } - else if (old == Biome::forest->id) - { - next = Biome::forestHills->id; - } - else if (old == Biome::taiga->id) - { - next = Biome::taigaHills->id; - } - else if (old == Biome::plains->id) - { - next = Biome::forest->id; - } - else if (old == Biome::iceFlats->id) - { - next = Biome::iceMountains->id; - } - else if (old == Biome::jungle->id) - { - next = Biome::jungleHills->id; + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + initRandom(x + xo, y + yo); + int old = b[(x + 1) + (y + 1) * (w + 2)]; + if (nextRandom(3) == 0) { + int next = old; + if (old == Biome::desert->id) { + next = Biome::desertHills->id; + } else if (old == Biome::forest->id) { + next = Biome::forestHills->id; + } else if (old == Biome::taiga->id) { + next = Biome::taigaHills->id; + } else if (old == Biome::plains->id) { + next = Biome::forest->id; + } else if (old == Biome::iceFlats->id) { + next = Biome::iceMountains->id; + } else if (old == Biome::jungle->id) { + next = Biome::jungleHills->id; + } + if (next == old) { + result[x + y * w] = old; + } else { + int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; + int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; + int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; + int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; + if (_n == old && _e == old && _w == old && _s == old) { + result[x + y * w] = next; + } else { + result[x + y * w] = old; + } + } + } else { + result[x + y * w] = old; + } + } + } - } - if (next == old) - { - result[x + y * w] = old; - } - else - { - int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; - int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; - int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; - int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; - if (_n == old && _e == old && _w == old && _s == old) - { - result[x + y * w] = next; - } - else - { - result[x + y * w] = old; - } - } - } - else - { - result[x + y * w] = old; - } - } - } - - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RegionHillsLayer.h b/Minecraft.World/WorldGen/Layers/RegionHillsLayer.h index 1492857fb..7e26bc6c5 100644 --- a/Minecraft.World/WorldGen/Layers/RegionHillsLayer.h +++ b/Minecraft.World/WorldGen/Layers/RegionHillsLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class RegionHillsLayer : public Layer -{ +class RegionHillsLayer : public Layer { public: - RegionHillsLayer(__int64 seed, std::shared_ptr parent); + RegionHillsLayer(__int64 seed, std::shared_ptr parent); - intArray getArea(int xo, int yo, int w, int h); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverInitLayer.cpp b/Minecraft.World/WorldGen/Layers/RiverInitLayer.cpp index d633ea50f..cf674435b 100644 --- a/Minecraft.World/WorldGen/Layers/RiverInitLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/RiverInitLayer.cpp @@ -1,24 +1,21 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -RiverInitLayer::RiverInitLayer(__int64 seed, std::shared_ptrparent) : Layer(seed) -{ - this->parent = parent; +RiverInitLayer::RiverInitLayer(__int64 seed, std::shared_ptr parent) + : Layer(seed) { + this->parent = parent; } -intArray RiverInitLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); +intArray RiverInitLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - initRandom(x + xo, y + yo); - result[x + y * w] = b[x + y * w] > 0 ? nextRandom(2) + 2 : 0; - } - } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + initRandom(x + xo, y + yo); + result[x + y * w] = b[x + y * w] > 0 ? nextRandom(2) + 2 : 0; + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverInitLayer.h b/Minecraft.World/WorldGen/Layers/RiverInitLayer.h index ef543d7c5..bb2f027e1 100644 --- a/Minecraft.World/WorldGen/Layers/RiverInitLayer.h +++ b/Minecraft.World/WorldGen/Layers/RiverInitLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class RiverInitLayer : public Layer -{ +class RiverInitLayer : public Layer { public: - RiverInitLayer(__int64 seed, std::shared_ptrparent); + RiverInitLayer(__int64 seed, std::shared_ptr parent); - intArray getArea(int xo, int yo, int w, int h); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverLayer.cpp b/Minecraft.World/WorldGen/Layers/RiverLayer.cpp index a428fded0..2ae4d195a 100644 --- a/Minecraft.World/WorldGen/Layers/RiverLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/RiverLayer.cpp @@ -2,39 +2,34 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -RiverLayer::RiverLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +RiverLayer::RiverLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray RiverLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo - 1; - int py = yo - 1; - int pw = w + 2; - int ph = h + 2; - intArray p = parent->getArea(px, py, pw, ph); +intArray RiverLayer::getArea(int xo, int yo, int w, int h) { + int px = xo - 1; + int py = yo - 1; + int pw = w + 2; + int ph = h + 2; + intArray p = parent->getArea(px, py, pw, ph); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - int l = p[(x + 0) + (y + 1) * pw]; - int r = p[(x + 2) + (y + 1) * pw]; - int u = p[(x + 1) + (y + 0) * pw]; - int d = p[(x + 1) + (y + 2) * pw]; - int c = p[(x + 1) + (y + 1) * pw]; - if (c == 0 || (l == 0 || r == 0 || u == 0 || d == 0) || c != l || c != u || c != r || c != d) - { - result[x + y * w] = Biome::river->id; - } - else - { - result[x + y * w] = -1; - } - } - } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int l = p[(x + 0) + (y + 1) * pw]; + int r = p[(x + 2) + (y + 1) * pw]; + int u = p[(x + 1) + (y + 0) * pw]; + int d = p[(x + 1) + (y + 2) * pw]; + int c = p[(x + 1) + (y + 1) * pw]; + if (c == 0 || (l == 0 || r == 0 || u == 0 || d == 0) || c != l || + c != u || c != r || c != d) { + result[x + y * w] = Biome::river->id; + } else { + result[x + y * w] = -1; + } + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverLayer.h b/Minecraft.World/WorldGen/Layers/RiverLayer.h index 839f05555..078b26e65 100644 --- a/Minecraft.World/WorldGen/Layers/RiverLayer.h +++ b/Minecraft.World/WorldGen/Layers/RiverLayer.h @@ -2,9 +2,8 @@ #include "Layer.h" -class RiverLayer : public Layer -{ +class RiverLayer : public Layer { public: - RiverLayer(__int64 seedMixup, std::shared_ptrparent); - intArray getArea(int xo, int yo, int w, int h); + RiverLayer(__int64 seedMixup, std::shared_ptr parent); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverMixerLayer.cpp b/Minecraft.World/WorldGen/Layers/RiverMixerLayer.cpp index 99778cb2c..fa448ab04 100644 --- a/Minecraft.World/WorldGen/Layers/RiverMixerLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/RiverMixerLayer.cpp @@ -2,46 +2,47 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -RiverMixerLayer::RiverMixerLayer(__int64 seed, std::shared_ptrbiomes, std::shared_ptrrivers) : Layer(seed) -{ - this->biomes = biomes; - this->rivers = rivers; +RiverMixerLayer::RiverMixerLayer(__int64 seed, std::shared_ptr biomes, + std::shared_ptr rivers) + : Layer(seed) { + this->biomes = biomes; + this->rivers = rivers; } -void RiverMixerLayer::init(__int64 seed) -{ - biomes->init(seed); - rivers->init(seed); - Layer::init(seed); +void RiverMixerLayer::init(__int64 seed) { + biomes->init(seed); + rivers->init(seed); + Layer::init(seed); } -intArray RiverMixerLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = biomes->getArea(xo, yo, w, h); - intArray r = rivers->getArea(xo, yo, w, h); +intArray RiverMixerLayer::getArea(int xo, int yo, int w, int h) { + intArray b = biomes->getArea(xo, yo, w, h); + intArray r = rivers->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int i = 0; i < w * h; i++) - { - if (b[i] == Biome::ocean->id) - { - result[i] = b[i]; + intArray result = IntCache::allocate(w * h); + for (int i = 0; i < w * h; i++) { + if (b[i] == Biome::ocean->id) { + result[i] = b[i]; - } - else - { - if (r[i] >= 0) - { - if (b[i] == Biome::iceFlats->id) result[i] = Biome::frozenRiver->id; - else if (b[i] == Biome::mushroomIsland->id || b[i] == Biome::mushroomIslandShore->id) result[i] = Biome::mushroomIsland->id; // 4J - don't make mushroom island shores as we don't have any island left once we do this as our islands are small (this used to change to mushroomIslandShore) - else result[i] = r[i]; - } - else - { - result[i] = b[i]; - } - } - } + } else { + if (r[i] >= 0) { + if (b[i] == Biome::iceFlats->id) + result[i] = Biome::frozenRiver->id; + else if (b[i] == Biome::mushroomIsland->id || + b[i] == Biome::mushroomIslandShore->id) + result[i] = + Biome::mushroomIsland + ->id; // 4J - don't make mushroom island shores as + // we don't have any island left once we do + // this as our islands are small (this used + // to change to mushroomIslandShore) + else + result[i] = r[i]; + } else { + result[i] = b[i]; + } + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/RiverMixerLayer.h b/Minecraft.World/WorldGen/Layers/RiverMixerLayer.h index 338f83b0b..a9b39b81d 100644 --- a/Minecraft.World/WorldGen/Layers/RiverMixerLayer.h +++ b/Minecraft.World/WorldGen/Layers/RiverMixerLayer.h @@ -2,15 +2,15 @@ #include "Layer.h" -class RiverMixerLayer : public Layer -{ +class RiverMixerLayer : public Layer { private: - std::shared_ptrbiomes; - std::shared_ptrrivers; + std::shared_ptr biomes; + std::shared_ptr rivers; public: - RiverMixerLayer(__int64 seed, std::shared_ptrbiomes, std::shared_ptrrivers); + RiverMixerLayer(__int64 seed, std::shared_ptr biomes, + std::shared_ptr rivers); - virtual void init(__int64 seed); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual void init(__int64 seed); + virtual intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/ShoreLayer.cpp b/Minecraft.World/WorldGen/Layers/ShoreLayer.cpp index 03701b8be..133ee3ab3 100644 --- a/Minecraft.World/WorldGen/Layers/ShoreLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/ShoreLayer.cpp @@ -2,69 +2,57 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Headers/net.minecraft.world.level.biome.h" -ShoreLayer::ShoreLayer(__int64 seed, std::shared_ptr parent) : Layer(seed) -{ - this->parent = parent; +ShoreLayer::ShoreLayer(__int64 seed, std::shared_ptr parent) + : Layer(seed) { + this->parent = parent; } -intArray ShoreLayer::getArea(int xo, int yo, int w, int h) -{ +intArray ShoreLayer::getArea(int xo, int yo, int w, int h) { intArray b = parent->getArea(xo - 1, yo - 1, w + 2, h + 2); intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { initRandom(x + xo, y + yo); int old = b[(x + 1) + (y + 1) * (w + 2)]; - if (old == Biome::mushroomIsland->id) - { + if (old == Biome::mushroomIsland->id) { int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; - if (_n == Biome::ocean->id || _e == Biome::ocean->id || _w == Biome::ocean->id || _s == Biome::ocean->id) - { + if (_n == Biome::ocean->id || _e == Biome::ocean->id || + _w == Biome::ocean->id || _s == Biome::ocean->id) { result[x + y * w] = Biome::mushroomIslandShore->id; - } - else - { + } else { result[x + y * w] = old; } - } - else if (old != Biome::ocean->id && old != Biome::river->id && old != Biome::swampland->id && old != Biome::extremeHills->id) - { - int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; - int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; - int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; - int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; - if (_n == Biome::ocean->id || _e == Biome::ocean->id || _w == Biome::ocean->id || _s == Biome::ocean->id) - { - result[x + y * w] = Biome::beaches->id; - } - else - { - result[x + y * w] = old; - } - } - else if (old == Biome::extremeHills->id) - { - int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; - int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; - int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; - int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; - if (_n != Biome::extremeHills->id || _e != Biome::extremeHills->id || _w != Biome::extremeHills->id || _s != Biome::extremeHills->id) - { - result[x + y * w] = Biome::smallerExtremeHills->id; - } - else - { - result[x + y * w] = old; - } - } - else - { + } else if (old != Biome::ocean->id && old != Biome::river->id && + old != Biome::swampland->id && + old != Biome::extremeHills->id) { + int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; + int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; + int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; + int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; + if (_n == Biome::ocean->id || _e == Biome::ocean->id || + _w == Biome::ocean->id || _s == Biome::ocean->id) { + result[x + y * w] = Biome::beaches->id; + } else { + result[x + y * w] = old; + } + } else if (old == Biome::extremeHills->id) { + int _n = b[(x + 1) + (y + 1 - 1) * (w + 2)]; + int _e = b[(x + 1 + 1) + (y + 1) * (w + 2)]; + int _w = b[(x + 1 - 1) + (y + 1) * (w + 2)]; + int _s = b[(x + 1) + (y + 1 + 1) * (w + 2)]; + if (_n != Biome::extremeHills->id || + _e != Biome::extremeHills->id || + _w != Biome::extremeHills->id || + _s != Biome::extremeHills->id) { + result[x + y * w] = Biome::smallerExtremeHills->id; + } else { + result[x + y * w] = old; + } + } else { result[x + y * w] = old; } } diff --git a/Minecraft.World/WorldGen/Layers/ShoreLayer.h b/Minecraft.World/WorldGen/Layers/ShoreLayer.h index 3728d66f2..6f50c8657 100644 --- a/Minecraft.World/WorldGen/Layers/ShoreLayer.h +++ b/Minecraft.World/WorldGen/Layers/ShoreLayer.h @@ -1,8 +1,7 @@ #pragma once #include "Layer.h" -class ShoreLayer : public Layer -{ +class ShoreLayer : public Layer { public: ShoreLayer(__int64 seed, std::shared_ptr parent); virtual intArray getArea(int xo, int yo, int w, int h); diff --git a/Minecraft.World/WorldGen/Layers/SmoothLayer.cpp b/Minecraft.World/WorldGen/Layers/SmoothLayer.cpp index ebf3cb25c..78f8c4910 100644 --- a/Minecraft.World/WorldGen/Layers/SmoothLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/SmoothLayer.cpp @@ -1,45 +1,40 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -SmoothLayer::SmoothLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +SmoothLayer::SmoothLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray SmoothLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo - 1; - int py = yo - 1; - int pw = w + 2; - int ph = h + 2; - intArray p = parent->getArea(px, py, pw, ph); +intArray SmoothLayer::getArea(int xo, int yo, int w, int h) { + int px = xo - 1; + int py = yo - 1; + int pw = w + 2; + int ph = h + 2; + intArray p = parent->getArea(px, py, pw, ph); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - int l = p[(x + 0) + (y + 1) * pw]; - int r = p[(x + 2) + (y + 1) * pw]; - int u = p[(x + 1) + (y + 0) * pw]; - int d = p[(x + 1) + (y + 2) * pw]; - int c = p[(x + 1) + (y + 1) * pw]; - if (l == r && u == d) - { - initRandom((x + xo), (y + yo)); - if (nextRandom(2) == 0) c = l; - else c = u; + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int l = p[(x + 0) + (y + 1) * pw]; + int r = p[(x + 2) + (y + 1) * pw]; + int u = p[(x + 1) + (y + 0) * pw]; + int d = p[(x + 1) + (y + 2) * pw]; + int c = p[(x + 1) + (y + 1) * pw]; + if (l == r && u == d) { + initRandom((x + xo), (y + yo)); + if (nextRandom(2) == 0) + c = l; + else + c = u; - } - else - { - if (l == r) c = l; - if (u == d) c = u; - } - result[x + y * w] = c; + } else { + if (l == r) c = l; + if (u == d) c = u; + } + result[x + y * w] = c; + } + } - } - } - - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/SmoothLayer.h b/Minecraft.World/WorldGen/Layers/SmoothLayer.h index 3eee6e170..117164996 100644 --- a/Minecraft.World/WorldGen/Layers/SmoothLayer.h +++ b/Minecraft.World/WorldGen/Layers/SmoothLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class SmoothLayer : public Layer -{ +class SmoothLayer : public Layer { public: - SmoothLayer(__int64 seedMixup, std::shared_ptrparent); + SmoothLayer(__int64 seedMixup, std::shared_ptr parent); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.cpp b/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.cpp index b8e06f7d0..614fe915e 100644 --- a/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.cpp @@ -2,60 +2,58 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Platform/System.h" -SmoothZoomLayer::SmoothZoomLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +SmoothZoomLayer::SmoothZoomLayer(__int64 seedMixup, + std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray SmoothZoomLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo >> 1; - int py = yo >> 1; - int pw = (w >> 1) + 3; - int ph = (h >> 1) + 3; - intArray p = parent->getArea(px, py, pw, ph); +intArray SmoothZoomLayer::getArea(int xo, int yo, int w, int h) { + int px = xo >> 1; + int py = yo >> 1; + int pw = (w >> 1) + 3; + int ph = (h >> 1) + 3; + intArray p = parent->getArea(px, py, pw, ph); - intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); - int ww = (pw << 1); - for (int y = 0; y < ph - 1; y++) - { - int ry = y << 1; - int pp = ry * ww; - int ul = p[(0 + 0) + (y + 0) * pw]; - int dl = p[(0 + 0) + (y + 1) * pw]; - for (int x = 0; x < pw - 1; x++) - { - initRandom((x + px) << 1, (y + py) << 1); + intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); + int ww = (pw << 1); + for (int y = 0; y < ph - 1; y++) { + int ry = y << 1; + int pp = ry * ww; + int ul = p[(0 + 0) + (y + 0) * pw]; + int dl = p[(0 + 0) + (y + 1) * pw]; + for (int x = 0; x < pw - 1; x++) { + initRandom((x + px) << 1, (y + py) << 1); - int ur = p[(x + 1) + (y + 0) * pw]; - int dr = p[(x + 1) + (y + 1) * pw]; + int ur = p[(x + 1) + (y + 0) * pw]; + int dr = p[(x + 1) + (y + 1) * pw]; - tmp[pp] = ul; - tmp[pp++ + ww] = ul + (dl - ul) * (nextRandom(256)) / 256; - tmp[pp] = ul + (ur - ul) * (nextRandom(256)) / 256; + tmp[pp] = ul; + tmp[pp++ + ww] = ul + (dl - ul) * (nextRandom(256)) / 256; + tmp[pp] = ul + (ur - ul) * (nextRandom(256)) / 256; - int a = ul + (ur - ul) * (nextRandom(256)) / 256; - int b = dl + (dr - dl) * (nextRandom(256)) / 256; - tmp[pp++ + ww] = a + (b - a) * (nextRandom(256)) / 256; + int a = ul + (ur - ul) * (nextRandom(256)) / 256; + int b = dl + (dr - dl) * (nextRandom(256)) / 256; + tmp[pp++ + ww] = a + (b - a) * (nextRandom(256)) / 256; - ul = ur; - dl = dr; - } - } - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - System::arraycopy(tmp, (y + (yo & 1)) * (pw << 1) + (xo & 1), &result, y * w, w); - } - return result; + ul = ur; + dl = dr; + } + } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + System::arraycopy(tmp, (y + (yo & 1)) * (pw << 1) + (xo & 1), &result, + y * w, w); + } + return result; } -std::shared_ptrSmoothZoomLayer::zoom(__int64 seed, std::shared_ptrsup, int count) -{ - std::shared_ptrresult = sup; - for (int i = 0; i < count; i++) - { - result = std::shared_ptr(new SmoothZoomLayer(seed + i, result)); - } - return result; +std::shared_ptr SmoothZoomLayer::zoom(__int64 seed, + std::shared_ptr sup, + int count) { + std::shared_ptr result = sup; + for (int i = 0; i < count; i++) { + result = std::shared_ptr(new SmoothZoomLayer(seed + i, result)); + } + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.h b/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.h index 9aae06f1e..2bd8343fc 100644 --- a/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.h +++ b/Minecraft.World/WorldGen/Layers/SmoothZoomLayer.h @@ -2,11 +2,11 @@ #include "Layer.h" -class SmoothZoomLayer : public Layer -{ +class SmoothZoomLayer : public Layer { public: - SmoothZoomLayer(__int64 seedMixup, std::shared_ptrparent); + SmoothZoomLayer(__int64 seedMixup, std::shared_ptr parent); - virtual intArray getArea(int xo, int yo, int w, int h); - static std::shared_ptrzoom(__int64 seed, std::shared_ptrsup, int count); + virtual intArray getArea(int xo, int yo, int w, int h); + static std::shared_ptr zoom(__int64 seed, std::shared_ptr sup, + int count); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/SwampRiversLayer.cpp b/Minecraft.World/WorldGen/Layers/SwampRiversLayer.cpp index 1c21429f3..77a4b0411 100644 --- a/Minecraft.World/WorldGen/Layers/SwampRiversLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/SwampRiversLayer.cpp @@ -3,32 +3,28 @@ #include "../../Util/IntCache.h" #include "SwampRiversLayer.h" -SwampRiversLayer::SwampRiversLayer(__int64 seed, std::shared_ptr parent) : Layer(seed) -{ - this->parent = parent; +SwampRiversLayer::SwampRiversLayer(__int64 seed, std::shared_ptr parent) + : Layer(seed) { + this->parent = parent; } -intArray SwampRiversLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo - 1, yo - 1, w + 2, h + 2); +intArray SwampRiversLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo - 1, yo - 1, w + 2, h + 2); - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - for (int x = 0; x < w; x++) - { - initRandom(x + xo, y + yo); - int old = b[(x + 1) + (y + 1) * (w + 2)]; - if ((old == Biome::swampland->id && nextRandom(6) == 0) || ((old == Biome::jungle->id || old == Biome::jungleHills->id) && nextRandom(8) == 0)) - { - result[x + y * w] = Biome::river->id; - } - else - { - result[x + y * w] = old; - } - } - } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + initRandom(x + xo, y + yo); + int old = b[(x + 1) + (y + 1) * (w + 2)]; + if ((old == Biome::swampland->id && nextRandom(6) == 0) || + ((old == Biome::jungle->id || old == Biome::jungleHills->id) && + nextRandom(8) == 0)) { + result[x + y * w] = Biome::river->id; + } else { + result[x + y * w] = old; + } + } + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/SwampRiversLayer.h b/Minecraft.World/WorldGen/Layers/SwampRiversLayer.h index 37ba49f46..cd20ccd10 100644 --- a/Minecraft.World/WorldGen/Layers/SwampRiversLayer.h +++ b/Minecraft.World/WorldGen/Layers/SwampRiversLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class SwampRiversLayer : public Layer -{ +class SwampRiversLayer : public Layer { public: - SwampRiversLayer(__int64 seed, std::shared_ptr parent); + SwampRiversLayer(__int64 seed, std::shared_ptr parent); - intArray getArea(int xo, int yo, int w, int h); + intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/TemperatureLayer.cpp b/Minecraft.World/WorldGen/Layers/TemperatureLayer.cpp index 6abab19f4..3cb51d756 100644 --- a/Minecraft.World/WorldGen/Layers/TemperatureLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/TemperatureLayer.cpp @@ -2,19 +2,16 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -TemperatureLayer::TemperatureLayer(std::shared_ptr parent) : Layer(0) -{ - this->parent = parent; +TemperatureLayer::TemperatureLayer(std::shared_ptr parent) : Layer(0) { + this->parent = parent; } -intArray TemperatureLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); +intArray TemperatureLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int i = 0; i < w * h; i++) - { - result[i] = Biome::biomes[b[i]]->getTemperatureInt(); - } - return result; + intArray result = IntCache::allocate(w * h); + for (int i = 0; i < w * h; i++) { + result[i] = Biome::biomes[b[i]]->getTemperatureInt(); + } + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/TemperatureLayer.h b/Minecraft.World/WorldGen/Layers/TemperatureLayer.h index 0da464021..efe037167 100644 --- a/Minecraft.World/WorldGen/Layers/TemperatureLayer.h +++ b/Minecraft.World/WorldGen/Layers/TemperatureLayer.h @@ -2,10 +2,9 @@ #include "Layer.h" -class TemperatureLayer : public Layer -{ +class TemperatureLayer : public Layer { public: - TemperatureLayer(std::shared_ptr parent); + TemperatureLayer(std::shared_ptr parent); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.cpp b/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.cpp index f89619529..d86159608 100644 --- a/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.cpp @@ -2,22 +2,24 @@ #include "../../Headers/net.minecraft.world.level.biome.h" #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" -TemperatureMixerLayer::TemperatureMixerLayer(std::shared_ptrtemp, std::shared_ptrparent, int layer) : Layer(0) -{ - this->parent = parent; - this->temp = temp; - this->layer = layer; +TemperatureMixerLayer::TemperatureMixerLayer(std::shared_ptr temp, + std::shared_ptr parent, + int layer) + : Layer(0) { + this->parent = parent; + this->temp = temp; + this->layer = layer; } -intArray TemperatureMixerLayer::getArea(int xo, int yo, int w, int h) -{ - intArray b = parent->getArea(xo, yo, w, h); - intArray t = temp->getArea(xo, yo, w, h); +intArray TemperatureMixerLayer::getArea(int xo, int yo, int w, int h) { + intArray b = parent->getArea(xo, yo, w, h); + intArray t = temp->getArea(xo, yo, w, h); - intArray result = IntCache::allocate(w * h); - for (int i = 0; i < w * h; i++) { - result[i] = t[i] + (Biome::biomes[b[i]]->getTemperatureInt() - t[i]) / (layer * 2 + 1); - } + intArray result = IntCache::allocate(w * h); + for (int i = 0; i < w * h; i++) { + result[i] = t[i] + (Biome::biomes[b[i]]->getTemperatureInt() - t[i]) / + (layer * 2 + 1); + } - return result; + return result; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.h b/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.h index 0e7abf937..d1a4b4c5e 100644 --- a/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.h +++ b/Minecraft.World/WorldGen/Layers/TemperatureMixerLayer.h @@ -2,14 +2,14 @@ #include "Layer.h" -class TemperatureMixerLayer : public Layer -{ +class TemperatureMixerLayer : public Layer { private: - std::shared_ptrtemp; - int layer; + std::shared_ptr temp; + int layer; public: - TemperatureMixerLayer(std::shared_ptrtemp, std::shared_ptrparent, int layer); + TemperatureMixerLayer(std::shared_ptr temp, + std::shared_ptr parent, int layer); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual intArray getArea(int xo, int yo, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/VoronoiZoom.cpp b/Minecraft.World/WorldGen/Layers/VoronoiZoom.cpp index 85154ecd4..da16ab43d 100644 --- a/Minecraft.World/WorldGen/Layers/VoronoiZoom.cpp +++ b/Minecraft.World/WorldGen/Layers/VoronoiZoom.cpp @@ -2,122 +2,112 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Platform/System.h" -VoronoiZoom::VoronoiZoom(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +VoronoiZoom::VoronoiZoom(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray VoronoiZoom::getArea(int xo, int yo, int w, int h) -{ - xo -= 2; - yo -= 2; - int bits = 2; - int ss = 1 << bits; - int px = xo >> bits; - int py = yo >> bits; - int pw = (w >> bits) + 3; - int ph = (h >> bits) + 3; - intArray p = parent->getArea(px, py, pw, ph); +intArray VoronoiZoom::getArea(int xo, int yo, int w, int h) { + xo -= 2; + yo -= 2; + int bits = 2; + int ss = 1 << bits; + int px = xo >> bits; + int py = yo >> bits; + int pw = (w >> bits) + 3; + int ph = (h >> bits) + 3; + intArray p = parent->getArea(px, py, pw, ph); - // 4jcraft added all those casts to unsigned - int ww = (unsigned) pw << bits; - int hh = (unsigned) ph << bits; - intArray tmp = IntCache::allocate(ww * hh); - for (int y = 0; y < ph - 1; y++) - { - int ul = p[(0 + 0) + (y + 0) * pw]; - int dl = p[(0 + 0) + (y + 1) * pw]; - for (int x = 0; x < pw - 1; x++) - { - double s = ss * 0.9; - initRandom((unsigned) (x + px) << bits, (unsigned) (y + py) << bits); - double x0 = (nextRandom(1024) / 1024.0 - 0.5) * s; - double y0 = (nextRandom(1024) / 1024.0 - 0.5) * s; - initRandom((unsigned) (x + px + 1) << bits, (unsigned) (y + py) << bits); - double x1 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; - double y1 = (nextRandom(1024) / 1024.0 - 0.5) * s; - initRandom((unsigned) (x + px) << bits, (unsigned) (y + py + 1) << bits); - double x2 = (nextRandom(1024) / 1024.0 - 0.5) * s; - double y2 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; - initRandom((unsigned) (x + px + 1) << bits, (unsigned) (y + py + 1) << bits); - double x3 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; - double y3 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; + // 4jcraft added all those casts to unsigned + int ww = (unsigned)pw << bits; + int hh = (unsigned)ph << bits; + intArray tmp = IntCache::allocate(ww * hh); + for (int y = 0; y < ph - 1; y++) { + int ul = p[(0 + 0) + (y + 0) * pw]; + int dl = p[(0 + 0) + (y + 1) * pw]; + for (int x = 0; x < pw - 1; x++) { + double s = ss * 0.9; + initRandom((unsigned)(x + px) << bits, (unsigned)(y + py) << bits); + double x0 = (nextRandom(1024) / 1024.0 - 0.5) * s; + double y0 = (nextRandom(1024) / 1024.0 - 0.5) * s; + initRandom((unsigned)(x + px + 1) << bits, (unsigned)(y + py) + << bits); + double x1 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; + double y1 = (nextRandom(1024) / 1024.0 - 0.5) * s; + initRandom((unsigned)(x + px) << bits, (unsigned)(y + py + 1) + << bits); + double x2 = (nextRandom(1024) / 1024.0 - 0.5) * s; + double y2 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; + initRandom((unsigned)(x + px + 1) << bits, (unsigned)(y + py + 1) + << bits); + double x3 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; + double y3 = (nextRandom(1024) / 1024.0 - 0.5) * s + ss; - int ur = p[(x + 1) + (y + 0) * pw]; - int dr = p[(x + 1) + (y + 1) * pw]; + int ur = p[(x + 1) + (y + 0) * pw]; + int dr = p[(x + 1) + (y + 1) * pw]; - for (int yy = 0; yy < ss; yy++) - { - int pp = ((unsigned) (y << bits) + yy) * ww + ((unsigned) (x << bits)); - for (int xx = 0; xx < ss; xx++) - { - double d0 = ((yy - y0) * (yy - y0) + (xx - x0) * (xx - x0)); - double d1 = ((yy - y1) * (yy - y1) + (xx - x1) * (xx - x1)); - double d2 = ((yy - y2) * (yy - y2) + (xx - x2) * (xx - x2)); - double d3 = ((yy - y3) * (yy - y3) + (xx - x3) * (xx - x3)); + for (int yy = 0; yy < ss; yy++) { + int pp = + ((unsigned)(y << bits) + yy) * ww + ((unsigned)(x << bits)); + for (int xx = 0; xx < ss; xx++) { + double d0 = ((yy - y0) * (yy - y0) + (xx - x0) * (xx - x0)); + double d1 = ((yy - y1) * (yy - y1) + (xx - x1) * (xx - x1)); + double d2 = ((yy - y2) * (yy - y2) + (xx - x2) * (xx - x2)); + double d3 = ((yy - y3) * (yy - y3) + (xx - x3) * (xx - x3)); - if (d0 < d1 && d0 < d2 && d0 < d3) - { - tmp[pp++] = ul; - } - else if (d1 < d0 && d1 < d2 && d1 < d3) - { - tmp[pp++] = ur; - } - else if (d2 < d0 && d2 < d1 && d2 < d3) - { - tmp[pp++] = dl; - } - else - { - tmp[pp++] = dr; - } - } - } + if (d0 < d1 && d0 < d2 && d0 < d3) { + tmp[pp++] = ul; + } else if (d1 < d0 && d1 < d2 && d1 < d3) { + tmp[pp++] = ur; + } else if (d2 < d0 && d2 < d1 && d2 < d3) { + tmp[pp++] = dl; + } else { + tmp[pp++] = dr; + } + } + } - ul = ur; - dl = dr; - } - } - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - System::arraycopy(tmp, (y + (yo & (ss - 1))) * ((unsigned) pw << bits) + (xo & (ss - 1)), &result, y * w, w); - } - return result; + ul = ur; + dl = dr; + } + } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + System::arraycopy( + tmp, + (y + (yo & (ss - 1))) * ((unsigned)pw << bits) + (xo & (ss - 1)), + &result, y * w, w); + } + return result; } -int VoronoiZoom::random(int a, int b) -{ - return nextRandom(2) == 0 ? a : b; -} - -int VoronoiZoom::random(int a, int b, int c, int d) -{ - if (b == c && c == d) return b; - if (a == b && a == c) return a; - if (a == b && a == d) return a; - if (a == c && a == d) return a; - - if (a == b && c != d) return a; - if (a == c && b != d) return a; - if (a == d && b != c) return a; - - if (b == a && c != d) return b; - if (b == c && a != d) return b; - if (b == d && a != c) return b; - - if (c == a && b != d) return c; - if (c == b && a != d) return c; - if (c == d && a != b) return c; - - if (d == a && b != c) return c; - if (d == b && a != c) return c; - if (d == c && a != b) return c; - - int s = nextRandom(4); - if (s == 0) return a; - if (s == 1) return b; - if (s == 2) return c; - return d; +int VoronoiZoom::random(int a, int b) { return nextRandom(2) == 0 ? a : b; } + +int VoronoiZoom::random(int a, int b, int c, int d) { + if (b == c && c == d) return b; + if (a == b && a == c) return a; + if (a == b && a == d) return a; + if (a == c && a == d) return a; + + if (a == b && c != d) return a; + if (a == c && b != d) return a; + if (a == d && b != c) return a; + + if (b == a && c != d) return b; + if (b == c && a != d) return b; + if (b == d && a != c) return b; + + if (c == a && b != d) return c; + if (c == b && a != d) return c; + if (c == d && a != b) return c; + + if (d == a && b != c) return c; + if (d == b && a != c) return c; + if (d == c && a != b) return c; + + int s = nextRandom(4); + if (s == 0) return a; + if (s == 1) return b; + if (s == 2) return c; + return d; } diff --git a/Minecraft.World/WorldGen/Layers/VoronoiZoom.h b/Minecraft.World/WorldGen/Layers/VoronoiZoom.h index 25087ad38..40faeabca 100644 --- a/Minecraft.World/WorldGen/Layers/VoronoiZoom.h +++ b/Minecraft.World/WorldGen/Layers/VoronoiZoom.h @@ -2,14 +2,13 @@ #include "Layer.h" -class VoronoiZoom : public Layer -{ +class VoronoiZoom : public Layer { public: - VoronoiZoom(__int64 seedMixup, std::shared_ptrparent); + VoronoiZoom(__int64 seedMixup, std::shared_ptr parent); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual intArray getArea(int xo, int yo, int w, int h); protected: - int random(int a, int b); - int random(int a, int b, int c, int d); + int random(int a, int b); + int random(int a, int b, int c, int d); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Layers/ZoomLayer.cpp b/Minecraft.World/WorldGen/Layers/ZoomLayer.cpp index 3f7cbf5f9..d5ebda59c 100644 --- a/Minecraft.World/WorldGen/Layers/ZoomLayer.cpp +++ b/Minecraft.World/WorldGen/Layers/ZoomLayer.cpp @@ -2,92 +2,86 @@ #include "../../Headers/net.minecraft.world.level.newbiome.layer.h" #include "../../Platform/System.h" -ZoomLayer::ZoomLayer(__int64 seedMixup, std::shared_ptrparent) : Layer(seedMixup) -{ - this->parent = parent; +ZoomLayer::ZoomLayer(__int64 seedMixup, std::shared_ptr parent) + : Layer(seedMixup) { + this->parent = parent; } -intArray ZoomLayer::getArea(int xo, int yo, int w, int h) -{ - int px = xo >> 1; - int py = yo >> 1; - int pw = (w >> 1) + 3; - int ph = (h >> 1) + 3; - intArray p = parent->getArea(px, py, pw, ph); +intArray ZoomLayer::getArea(int xo, int yo, int w, int h) { + int px = xo >> 1; + int py = yo >> 1; + int pw = (w >> 1) + 3; + int ph = (h >> 1) + 3; + intArray p = parent->getArea(px, py, pw, ph); - intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); - // 4jcraft added casts to unsigned - int ww = ((unsigned int) pw << 1); - for (int y = 0; y < ph - 1; y++) - { - int ry = (unsigned int) y << 1; - int pp = ry * ww; - int ul = p[(0 + 0) + (y + 0) * pw]; - int dl = p[(0 + 0) + (y + 1) * pw]; - for (int x = 0; x < pw - 1; x++) - { - initRandom((unsigned int) (x + px) << 1, (unsigned int) (y + py) << 1); - int ur = p[(x + 1) + (y + 0) * pw]; - int dr = p[(x + 1) + (y + 1) * pw]; + intArray tmp = IntCache::allocate((pw * 2) * (ph * 2)); + // 4jcraft added casts to unsigned + int ww = ((unsigned int)pw << 1); + for (int y = 0; y < ph - 1; y++) { + int ry = (unsigned int)y << 1; + int pp = ry * ww; + int ul = p[(0 + 0) + (y + 0) * pw]; + int dl = p[(0 + 0) + (y + 1) * pw]; + for (int x = 0; x < pw - 1; x++) { + initRandom((unsigned int)(x + px) << 1, (unsigned int)(y + py) + << 1); + int ur = p[(x + 1) + (y + 0) * pw]; + int dr = p[(x + 1) + (y + 1) * pw]; - tmp[pp] = ul; - tmp[pp++ + ww] = random(ul, dl); - tmp[pp] = random(ul, ur); - tmp[pp++ + ww] = random(ul, ur, dl, dr); + tmp[pp] = ul; + tmp[pp++ + ww] = random(ul, dl); + tmp[pp] = random(ul, ur); + tmp[pp++ + ww] = random(ul, ur, dl, dr); - ul = ur; - dl = dr; - } - } - intArray result = IntCache::allocate(w * h); - for (int y = 0; y < h; y++) - { - System::arraycopy(tmp, (y + (yo & 1)) * (unsigned int) (pw << 1) + (xo & 1), &result, y * w, w); - } - return result; + ul = ur; + dl = dr; + } + } + intArray result = IntCache::allocate(w * h); + for (int y = 0; y < h; y++) { + System::arraycopy(tmp, + (y + (yo & 1)) * (unsigned int)(pw << 1) + (xo & 1), + &result, y * w, w); + } + return result; } -int ZoomLayer::random(int a, int b) -{ - return nextRandom(2) == 0 ? a : b; +int ZoomLayer::random(int a, int b) { return nextRandom(2) == 0 ? a : b; } + +int ZoomLayer::random(int a, int b, int c, int d) { + if (b == c && c == d) return b; + if (a == b && a == c) return a; + if (a == b && a == d) return a; + if (a == c && a == d) return a; + + if (a == b && c != d) return a; + if (a == c && b != d) return a; + if (a == d && b != c) return a; + + if (b == a && c != d) return b; + if (b == c && a != d) return b; + if (b == d && a != c) return b; + + if (c == a && b != d) return c; + if (c == b && a != d) return c; + if (c == d && a != b) return c; + + if (d == a && b != c) return c; + if (d == b && a != c) return c; + if (d == c && a != b) return c; + + int s = nextRandom(4); + if (s == 0) return a; + if (s == 1) return b; + if (s == 2) return c; + return d; } -int ZoomLayer::random(int a, int b, int c, int d) -{ - if (b == c && c == d) return b; - if (a == b && a == c) return a; - if (a == b && a == d) return a; - if (a == c && a == d) return a; - - if (a == b && c != d) return a; - if (a == c && b != d) return a; - if (a == d && b != c) return a; - - if (b == a && c != d) return b; - if (b == c && a != d) return b; - if (b == d && a != c) return b; - - if (c == a && b != d) return c; - if (c == b && a != d) return c; - if (c == d && a != b) return c; - - if (d == a && b != c) return c; - if (d == b && a != c) return c; - if (d == c && a != b) return c; - - int s = nextRandom(4); - if (s == 0) return a; - if (s == 1) return b; - if (s == 2) return c; - return d; -} - -std::shared_ptrZoomLayer::zoom(__int64 seed, std::shared_ptr sup, int count) -{ - std::shared_ptrresult = sup; - for (int i = 0; i < count; i++) - { - result = std::shared_ptr(new ZoomLayer(seed + i, result)); - } - return result; +std::shared_ptr ZoomLayer::zoom(__int64 seed, std::shared_ptr sup, + int count) { + std::shared_ptr result = sup; + for (int i = 0; i < count; i++) { + result = std::shared_ptr(new ZoomLayer(seed + i, result)); + } + return result; } diff --git a/Minecraft.World/WorldGen/Layers/ZoomLayer.h b/Minecraft.World/WorldGen/Layers/ZoomLayer.h index 345e6fb66..a4309102c 100644 --- a/Minecraft.World/WorldGen/Layers/ZoomLayer.h +++ b/Minecraft.World/WorldGen/Layers/ZoomLayer.h @@ -2,17 +2,17 @@ #include "Layer.h" -class ZoomLayer : public Layer -{ +class ZoomLayer : public Layer { public: - ZoomLayer(__int64 seedMixup, std::shared_ptr parent); + ZoomLayer(__int64 seedMixup, std::shared_ptr parent); - virtual intArray getArea(int xo, int yo, int w, int h); + virtual intArray getArea(int xo, int yo, int w, int h); protected: - int random(int a, int b); - int random(int a, int b, int c, int d); + int random(int a, int b); + int random(int a, int b, int c, int d); public: - static std::shared_ptr zoom(__int64 seed, std::shared_ptrsup, int count); + static std::shared_ptr zoom(__int64 seed, std::shared_ptr sup, + int count); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Noise/FastNoise.cpp b/Minecraft.World/WorldGen/Noise/FastNoise.cpp index d4aa83a33..6c1483345 100644 --- a/Minecraft.World/WorldGen/Noise/FastNoise.cpp +++ b/Minecraft.World/WorldGen/Noise/FastNoise.cpp @@ -1,76 +1,65 @@ #include "../../Platform/stdafx.h" #include "FastNoise.h" -FastNoise::FastNoise(int levels) -{ - Random random; - init(&random, levels); +FastNoise::FastNoise(int levels) { + Random random; + init(&random, levels); } -FastNoise::FastNoise(Random *random, int levels) -{ - init(random,levels); -} +FastNoise::FastNoise(Random* random, int levels) { init(random, levels); } -void FastNoise::init(Random *random, int levels) -{ +void FastNoise::init(Random* random, int levels) { this->levels = levels; - noiseMaps = new uint8_t *[levels]; - for (int i = 0; i < levels; i++) - { - noiseMaps[i] = new uint8_t[0x100000]; - random->nextBytes(noiseMaps[i],0x100000); + noiseMaps = new uint8_t*[levels]; + for (int i = 0; i < levels; i++) { + noiseMaps[i] = new uint8_t[0x100000]; + random->nextBytes(noiseMaps[i], 0x100000); } } -FastNoise::~FastNoise() -{ - for( int i = 0; i < levels; i++ ) - { - delete [] noiseMaps[i]; - } - delete [] noiseMaps; +FastNoise::~FastNoise() { + for (int i = 0; i < levels; i++) { + delete[] noiseMaps[i]; + } + delete[] noiseMaps; } -doubleArray FastNoise::getRegion(doubleArray buffer, double x, double y, double z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale) -{ - if (buffer.data == NULL) buffer = doubleArray(xSize * ySize * zSize); - else for (unsigned int i = 0; i < buffer.length; i++) - buffer[i] = 0; - +doubleArray FastNoise::getRegion(doubleArray buffer, double x, double y, + double z, int xSize, int ySize, int zSize, + double xScale, double yScale, double zScale) { + if (buffer.data == NULL) + buffer = doubleArray(xSize * ySize * zSize); + else + for (unsigned int i = 0; i < buffer.length; i++) buffer[i] = 0; double pow = 1; int AA = 487211441; int BB = 21771; - for (int i = 0; i < levels; i++) - { - uint8_t *map = noiseMaps[i]; + for (int i = 0; i < levels; i++) { + uint8_t* map = noiseMaps[i]; int pp = 0; - for (int zp = 0; zp < zSize; zp++) - { + for (int zp = 0; zp < zSize; zp++) { double zz = (z + zp) * zScale; - int Z = (int) zz; + int Z = (int)zz; if (zz < Z) Z -= 1; - int zl = (int) ((zz - Z) * 65536); + int zl = (int)((zz - Z) * 65536); - for (int yp = 0; yp < ySize; yp++) - { + for (int yp = 0; yp < ySize; yp++) { double yy = (y + yp) * yScale; - int Y = (int) yy; + int Y = (int)yy; if (yy < Y) Y -= 1; - int yl = (int) ((yy - Y) * 65536); + int yl = (int)((yy - Y) * 65536); - for (int xp = 0; xp < xSize; xp++) - { + for (int xp = 0; xp < xSize; xp++) { double xx = (x + xp) * xScale; - int X = (int) xx; + int X = (int)xx; if (xx < X) X -= 1; - int xl = (int) ((xx - X) * 65536); - + int xl = (int)((xx - X) * 65536); + int X0 = (X + 0) * AA; int X1 = (X + 1) * AA; - + int Y0 = (Y + 0); int Y1 = (Y + 1); int Z0 = (Z + 0); @@ -100,14 +89,14 @@ doubleArray FastNoise::getRegion(doubleArray buffer, double x, double y, double int res = abcd + (((efgh - abcd) * zl) >> 16); - buffer[pp++] += res*pow; + buffer[pp++] += res * pow; } } } pow /= 2; - xScale*=2; - yScale*=2; - zScale*=2; + xScale *= 2; + yScale *= 2; + zScale *= 2; } return buffer; diff --git a/Minecraft.World/WorldGen/Noise/FastNoise.h b/Minecraft.World/WorldGen/Noise/FastNoise.h index e3bd991b3..c1ebbec3f 100644 --- a/Minecraft.World/WorldGen/Noise/FastNoise.h +++ b/Minecraft.World/WorldGen/Noise/FastNoise.h @@ -1,17 +1,18 @@ #pragma once -class FastNoise -{ +class FastNoise { private: - uint8_t **noiseMaps; + uint8_t** noiseMaps; int levels; public: FastNoise(int levels); - FastNoise(Random *random, int levels); + FastNoise(Random* random, int levels); - void init(Random *random, int levels); - ~FastNoise(); + void init(Random* random, int levels); + ~FastNoise(); - doubleArray getRegion(doubleArray buffer, double x, double y, double z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale); + doubleArray getRegion(doubleArray buffer, double x, double y, double z, + int xSize, int ySize, int zSize, double xScale, + double yScale, double zScale); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Noise/ImprovedNoise.cpp b/Minecraft.World/WorldGen/Noise/ImprovedNoise.cpp index 5ac61b4eb..ffc16f4fa 100644 --- a/Minecraft.World/WorldGen/Noise/ImprovedNoise.cpp +++ b/Minecraft.World/WorldGen/Noise/ImprovedNoise.cpp @@ -1,31 +1,24 @@ #include "../../Platform/stdafx.h" #include "ImprovedNoise.h" -ImprovedNoise::ImprovedNoise() -{ - Random random; - init(&random); +ImprovedNoise::ImprovedNoise() { + Random random; + init(&random); } -ImprovedNoise::ImprovedNoise(Random *random) -{ - init(random); -} +ImprovedNoise::ImprovedNoise(Random* random) { init(random); } -void ImprovedNoise::init(Random *random) -{ - p = new int[512]; +void ImprovedNoise::init(Random* random) { + p = new int[512]; xo = random->nextDouble() * 256; yo = random->nextDouble() * 256; zo = random->nextDouble() * 256; - for (int i = 0; i < 256; i++) - { + for (int i = 0; i < 256; i++) { p[i] = i; } - for (int i = 0; i < 256; i++) - { + for (int i = 0; i < 256; i++) { int j = random->nextInt(256 - i) + i; int tmp = p[i]; p[i] = p[j]; @@ -35,117 +28,113 @@ void ImprovedNoise::init(Random *random) } } -ImprovedNoise::~ImprovedNoise() -{ - delete [] p; -} +ImprovedNoise::~ImprovedNoise() { delete[] p; } -double ImprovedNoise::noise(double _x, double _y, double _z) -{ - double x = _x + xo; - double y = _y + yo; - double z = _z + zo; +double ImprovedNoise::noise(double _x, double _y, double _z) { + double x = _x + xo; + double y = _y + yo; + double z = _z + zo; - int xf = (int) x; - int yf = (int) y; - int zf = (int) z; + int xf = (int)x; + int yf = (int)y; + int zf = (int)z; - if (x < xf) xf--; - if (y < yf) yf--; - if (z < zf) zf--; + if (x < xf) xf--; + if (y < yf) yf--; + if (z < zf) zf--; - int X = xf & 255, // FIND UNIT CUBE THAT - Y = yf & 255, // CONTAINS POINT. + int X = xf & 255, // FIND UNIT CUBE THAT + Y = yf & 255, // CONTAINS POINT. Z = zf & 255; - x -= xf; // FIND RELATIVE X,Y,Z - y -= yf; // OF POINT IN CUBE. - z -= zf; + x -= xf; // FIND RELATIVE X,Y,Z + y -= yf; // OF POINT IN CUBE. + z -= zf; - double u = x * x * x * (x * (x * 6 - 15) + 10), // COMPUTE FADE CURVES - v = y * y * y * (y * (y * 6 - 15) + 10), // FOR EACH OF X,Y,Z. + double u = x * x * x * (x * (x * 6 - 15) + 10), // COMPUTE FADE CURVES + v = y * y * y * (y * (y * 6 - 15) + 10), // FOR EACH OF X,Y,Z. w = z * z * z * (z * (z * 6 - 15) + 10); - int A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, // HASH COORDINATES OF - B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z; // THE 8 CUBE CORNERS, - - return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), // AND ADD - grad(p[BA], x - 1, y, z)), // BLENDED - lerp(u, grad(p[AB], x, y - 1, z), // RESULTS - grad(p[BB], x - 1, y - 1, z))),// FROM 8 - lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), // CORNERS - grad(p[BA + 1], x - 1, y, z - 1)), // OF CUBE - lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))); + int A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, // HASH COORDINATES OF + B = p[X + 1] + Y, BA = p[B] + Z, + BB = p[B + 1] + Z; // THE 8 CUBE CORNERS, + return lerp(w, + lerp(v, + lerp(u, grad(p[AA], x, y, z), // AND ADD + grad(p[BA], x - 1, y, z)), // BLENDED + lerp(u, grad(p[AB], x, y - 1, z), // RESULTS + grad(p[BB], x - 1, y - 1, z))), // FROM 8 + lerp(v, + lerp(u, grad(p[AA + 1], x, y, z - 1), // CORNERS + grad(p[BA + 1], x - 1, y, z - 1)), // OF CUBE + lerp(u, grad(p[AB + 1], x, y - 1, z - 1), + grad(p[BB + 1], x - 1, y - 1, z - 1)))); } -double ImprovedNoise::lerp(double t, double a, double b) -{ - return a + t * (b - a); +double ImprovedNoise::lerp(double t, double a, double b) { + return a + t * (b - a); } -double ImprovedNoise::grad2(int hash, double x, double z) -{ - int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE - - double u = (1-((h&8)>>3))*x, // INTO 12 GRADIENT DIRECTIONS. - v = h < 4 ? 0 : h == 12 || h == 14 ? x : z; - +double ImprovedNoise::grad2(int hash, double x, double z) { + int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE + + double u = (1 - ((h & 8) >> 3)) * x, // INTO 12 GRADIENT DIRECTIONS. + v = h < 4 ? 0 + : h == 12 || h == 14 ? x + : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } -double ImprovedNoise::grad(int hash, double x, double y, double z) -{ - int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE - - double u = h < 8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. - v = h < 4 ? y : h == 12 || h == 14 ? x : z; - +double ImprovedNoise::grad(int hash, double x, double y, double z) { + int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE + + double u = h < 8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. + v = h < 4 ? y + : h == 12 || h == 14 ? x + : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } -double ImprovedNoise::getValue(double x, double y) -{ - return noise(x, y, 0); +double ImprovedNoise::getValue(double x, double y) { return noise(x, y, 0); } + +double ImprovedNoise::getValue(double x, double y, double z) { + return noise(x, y, z); } -double ImprovedNoise::getValue(double x, double y, double z) -{ - return noise(x, y, z); -} - -void ImprovedNoise::add(doubleArray buffer, double _x, double _y, double _z, int xSize, int ySize, int zSize, double xs, double ys, double zs, double pow) -{ - if (ySize==1) - { +void ImprovedNoise::add(doubleArray buffer, double _x, double _y, double _z, + int xSize, int ySize, int zSize, double xs, double ys, + double zs, double pow) { + if (ySize == 1) { int A = 0, AA = 0, B = 0, BA = 0; double vv0 = 0, vv2 = 0; int pp = 0; double scale = 1.0 / pow; - for (int xx = 0; xx < xSize; xx++) - { - double x = _x + (xx) * xs + xo; - int xf = (int) x; + for (int xx = 0; xx < xSize; xx++) { + double x = _x + (xx)*xs + xo; + int xf = (int)x; if (x < xf) xf--; int X = xf & 255; x -= xf; double u = x * x * x * (x * (x * 6 - 15) + 10); - for (int zz = 0; zz < zSize; zz++) - { - double z = _z + (zz) * zs + zo; - int zf = (int) z; + for (int zz = 0; zz < zSize; zz++) { + double z = _z + (zz)*zs + zo; + int zf = (int)z; if (z < zf) zf--; int Z = zf & 255; z -= zf; double w = z * z * z * (z * (z * 6 - 15) + 10); - + A = p[X] + 0; AA = p[A] + Z; B = p[X + 1] + 0; BA = p[B] + Z; vv0 = lerp(u, grad2(p[AA], x, z), grad(p[BA], x - 1, 0, z)); - vv2 = lerp(u, grad(p[AA + 1], x, 0, z - 1), grad(p[BA + 1], x - 1, 0, z - 1)); + vv2 = lerp(u, grad(p[AA + 1], x, 0, z - 1), + grad(p[BA + 1], x - 1, 0, z - 1)); double val = lerp(w, vv0, vv2); @@ -160,37 +149,31 @@ void ImprovedNoise::add(doubleArray buffer, double _x, double _y, double _z, int int A = 0, AA = 0, AB = 0, B = 0, BA = 0, BB = 0; double vv0 = 0, vv1 = 0, vv2 = 0, vv3 = 0; - for (int xx = 0; xx < xSize; xx++) - { - double x = _x + (xx) * xs + xo; - int xf = (int) x; + for (int xx = 0; xx < xSize; xx++) { + double x = _x + (xx)*xs + xo; + int xf = (int)x; if (x < xf) xf--; int X = xf & 255; x -= xf; double u = x * x * x * (x * (x * 6 - 15) + 10); - - for (int zz = 0; zz < zSize; zz++) - { - double z = _z + (zz) * zs + zo; - int zf = (int) z; + for (int zz = 0; zz < zSize; zz++) { + double z = _z + (zz)*zs + zo; + int zf = (int)z; if (z < zf) zf--; int Z = zf & 255; z -= zf; double w = z * z * z * (z * (z * 6 - 15) + 10); - - for (int yy = 0; yy < ySize; yy++) - { - double y = _y + (yy) * ys + yo; - int yf = (int) y; + for (int yy = 0; yy < ySize; yy++) { + double y = _y + (yy)*ys + yo; + int yf = (int)y; if (y < yf) yf--; int Y = yf & 255; y -= yf; double v = y * y * y * (y * (y * 6 - 15) + 10); - if (yy == 0 || Y != yOld) - { + if (yy == 0 || Y != yOld) { yOld = Y; A = p[X] + Y; AA = p[A] + Z; @@ -198,13 +181,16 @@ void ImprovedNoise::add(doubleArray buffer, double _x, double _y, double _z, int B = p[X + 1] + Y; BA = p[B] + Z; BB = p[B + 1] + Z; - vv0 = lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)); - vv1 = lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z)); - vv2 = lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)); - vv3 = lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)); + vv0 = + lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)); + vv1 = lerp(u, grad(p[AB], x, y - 1, z), + grad(p[BB], x - 1, y - 1, z)); + vv2 = lerp(u, grad(p[AA + 1], x, y, z - 1), + grad(p[BA + 1], x - 1, y, z - 1)); + vv3 = lerp(u, grad(p[AB + 1], x, y - 1, z - 1), + grad(p[BB + 1], x - 1, y - 1, z - 1)); } - double v0 = lerp(v, vv0, vv1); double v1 = lerp(v, vv2, vv3); double val = lerp(w, v0, v1); @@ -212,5 +198,5 @@ void ImprovedNoise::add(doubleArray buffer, double _x, double _y, double _z, int buffer[pp++] += val * scale; } } - } + } } diff --git a/Minecraft.World/WorldGen/Noise/ImprovedNoise.h b/Minecraft.World/WorldGen/Noise/ImprovedNoise.h index b35bb3fd6..6573fbb47 100644 --- a/Minecraft.World/WorldGen/Noise/ImprovedNoise.h +++ b/Minecraft.World/WorldGen/Noise/ImprovedNoise.h @@ -1,21 +1,21 @@ #pragma once #include "Synth.h" -class ImprovedNoise : public Synth -{ - friend class PerlinNoise_SPU; +class ImprovedNoise : public Synth { + friend class PerlinNoise_SPU; + private: - int *p; + int* p; public: double scale; double xo, yo, zo; ImprovedNoise(); - ImprovedNoise(Random *random); - void init(Random *random); + ImprovedNoise(Random* random); + void init(Random* random); - ~ImprovedNoise(); + ~ImprovedNoise(); double noise(double _x, double _y, double _z); @@ -25,5 +25,6 @@ public: virtual double getValue(double x, double y); double getValue(double x, double y, double z); - void add(doubleArray buffer, double _x, double _y, double _z, int xSize, int ySize, int zSize, double xs, double ys, double zs, double pow); + void add(doubleArray buffer, double _x, double _y, double _z, int xSize, + int ySize, int zSize, double xs, double ys, double zs, double pow); }; diff --git a/Minecraft.World/WorldGen/Noise/PerlinNoise.cpp b/Minecraft.World/WorldGen/Noise/PerlinNoise.cpp index e09e83b1f..50cc8f97c 100644 --- a/Minecraft.World/WorldGen/Noise/PerlinNoise.cpp +++ b/Minecraft.World/WorldGen/Noise/PerlinNoise.cpp @@ -2,45 +2,35 @@ #include "PerlinNoise.h" #include "../../Util/Mth.h" -PerlinNoise::PerlinNoise(int levels) -{ - Random random; - init(&random, levels); +PerlinNoise::PerlinNoise(int levels) { + Random random; + init(&random, levels); } -PerlinNoise::PerlinNoise(Random *random, int levels) -{ - init(random, levels); -} +PerlinNoise::PerlinNoise(Random* random, int levels) { init(random, levels); } -void PerlinNoise::init(Random *random, int levels) -{ - MemSect(2); +void PerlinNoise::init(Random* random, int levels) { + MemSect(2); this->levels = levels; - noiseLevels = new ImprovedNoise *[levels]; - for (int i = 0; i < levels; i++) - { + noiseLevels = new ImprovedNoise*[levels]; + for (int i = 0; i < levels; i++) { noiseLevels[i] = new ImprovedNoise(random); } - MemSect(0); + MemSect(0); } -PerlinNoise::~PerlinNoise() -{ - for( int i = 0; i < levels; i++ ) - { - delete noiseLevels[i]; - } - delete [] noiseLevels; +PerlinNoise::~PerlinNoise() { + for (int i = 0; i < levels; i++) { + delete noiseLevels[i]; + } + delete[] noiseLevels; } -double PerlinNoise::getValue(double x, double y) -{ +double PerlinNoise::getValue(double x, double y) { double value = 0; double pow = 1; - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { value += noiseLevels[i]->getValue(x * pow, y * pow) / pow; pow /= 2; } @@ -48,13 +38,11 @@ double PerlinNoise::getValue(double x, double y) return value; } -double PerlinNoise::getValue(double x, double y, double z) -{ +double PerlinNoise::getValue(double x, double y, double z) { double value = 0; double pow = 1; - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { value += noiseLevels[i]->getValue(x * pow, y * pow, z * pow) / pow; pow /= 2; } @@ -62,18 +50,20 @@ double PerlinNoise::getValue(double x, double y, double z) return value; } -doubleArray PerlinNoise::getRegion(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale) -{ - if (buffer.data == NULL) buffer = doubleArray(xSize * ySize * zSize); - else for (unsigned int i = 0; i < buffer.length; i++) - buffer[i] = 0; - +doubleArray PerlinNoise::getRegion(doubleArray buffer, int x, int y, int z, + int xSize, int ySize, int zSize, + double xScale, double yScale, + double zScale) { + if (buffer.data == NULL) + buffer = doubleArray(xSize * ySize * zSize); + else + for (unsigned int i = 0; i < buffer.length; i++) buffer[i] = 0; double pow = 1; - for (int i = 0; i < levels; i++) - { - // value += noiseLevels[i].getValue(x * pow, y * pow, z * pow) / pow; + for (int i = 0; i < levels; i++) { + // value += noiseLevels[i].getValue(x * pow, y * pow, z * + // pow) / pow; double xx = x * pow * xScale; double yy = y * pow * yScale; double zz = z * pow * zScale; @@ -85,14 +75,16 @@ doubleArray PerlinNoise::getRegion(doubleArray buffer, int x, int y, int z, int zb %= 16777216; xx += xb; zz += zb; - noiseLevels[i]->add(buffer, xx, yy, zz, xSize, ySize, zSize, xScale * pow, yScale * pow, zScale * pow, pow); + noiseLevels[i]->add(buffer, xx, yy, zz, xSize, ySize, zSize, + xScale * pow, yScale * pow, zScale * pow, pow); pow /= 2; } return buffer; } -doubleArray PerlinNoise::getRegion(doubleArray sr, int x, int z, int xSize, int zSize, double xScale, double zScale, double pow) -{ - return getRegion(sr, x, 10, z, xSize, 1, zSize, xScale, 1, zScale); +doubleArray PerlinNoise::getRegion(doubleArray sr, int x, int z, int xSize, + int zSize, double xScale, double zScale, + double pow) { + return getRegion(sr, x, 10, z, xSize, 1, zSize, xScale, 1, zScale); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Noise/PerlinNoise.h b/Minecraft.World/WorldGen/Noise/PerlinNoise.h index 25b676272..2429f52d0 100644 --- a/Minecraft.World/WorldGen/Noise/PerlinNoise.h +++ b/Minecraft.World/WorldGen/Noise/PerlinNoise.h @@ -2,23 +2,25 @@ #include "Synth.h" #include "ImprovedNoise.h" +class PerlinNoise : public Synth { + friend class PerlinNoise_SPU; -class PerlinNoise: public Synth -{ - friend class PerlinNoise_SPU; private: - ImprovedNoise **noiseLevels; + ImprovedNoise** noiseLevels; int levels; public: PerlinNoise(int levels); - PerlinNoise(Random *random, int levels); + PerlinNoise(Random* random, int levels); - void init(Random *random, int levels); - ~PerlinNoise(); + void init(Random* random, int levels); + ~PerlinNoise(); virtual double getValue(double x, double y); double getValue(double x, double y, double z); - doubleArray getRegion(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale); - doubleArray getRegion(doubleArray sr, int x, int z, int xSize, int zSize, double xScale, double zScale, double pow); + doubleArray getRegion(doubleArray buffer, int x, int y, int z, int xSize, + int ySize, int zSize, double xScale, double yScale, + double zScale); + doubleArray getRegion(doubleArray sr, int x, int z, int xSize, int zSize, + double xScale, double zScale, double pow); }; diff --git a/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.cpp b/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.cpp index 080b184f7..c19fac8e6 100644 --- a/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.cpp +++ b/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.cpp @@ -1,46 +1,38 @@ #include "../../Platform/stdafx.h" #include "PerlinSimplexNoise.h" -PerlinSimplexNoise::PerlinSimplexNoise(int levels) -{ - Random random; - init(&random,levels); +PerlinSimplexNoise::PerlinSimplexNoise(int levels) { + Random random; + init(&random, levels); } -PerlinSimplexNoise::PerlinSimplexNoise(Random *random, int levels) -{ - init(random,levels); - delete random; +PerlinSimplexNoise::PerlinSimplexNoise(Random* random, int levels) { + init(random, levels); + delete random; } -void PerlinSimplexNoise::init(Random *random, int levels) -{ - MemSect(3); +void PerlinSimplexNoise::init(Random* random, int levels) { + MemSect(3); this->levels = levels; - noiseLevels = new SimplexNoise *[levels]; - for (int i = 0; i < levels; i++) - { + noiseLevels = new SimplexNoise*[levels]; + for (int i = 0; i < levels; i++) { noiseLevels[i] = new SimplexNoise(random); } - MemSect(0); + MemSect(0); } -PerlinSimplexNoise::~PerlinSimplexNoise() -{ - for(int i = 0; i < levels; i++ ) - { - delete noiseLevels[i]; - } - delete[] noiseLevels; +PerlinSimplexNoise::~PerlinSimplexNoise() { + for (int i = 0; i < levels; i++) { + delete noiseLevels[i]; + } + delete[] noiseLevels; } -double PerlinSimplexNoise::getValue(double x, double y) -{ +double PerlinSimplexNoise::getValue(double x, double y) { double value = 0; double pow = 1; - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { value += noiseLevels[i]->getValue(x * pow, y * pow) / pow; pow /= 2; } @@ -48,13 +40,11 @@ double PerlinSimplexNoise::getValue(double x, double y) return value; } -double PerlinSimplexNoise::getValue(double x, double y, double z) -{ +double PerlinSimplexNoise::getValue(double x, double y, double z) { double value = 0; double pow = 1; - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { value += noiseLevels[i]->getValue(x * pow, y * pow, z * pow) / pow; pow /= 2; } @@ -62,30 +52,32 @@ double PerlinSimplexNoise::getValue(double x, double y, double z) return value; } -doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, double y, int xSize, int ySize, double xScale, double yScale, double sizeScale) -{ - return getRegion(buffer, x, y, xSize, ySize, xScale, yScale, sizeScale, 0.5); +doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, + double y, int xSize, int ySize, + double xScale, double yScale, + double sizeScale) { + return getRegion(buffer, x, y, xSize, ySize, xScale, yScale, sizeScale, + 0.5); } -doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, double y, int xSize, int ySize, double xScale, double yScale, double sizeScale, double powScale) -{ - xScale/=1.5; - yScale/=1.5; - - if (buffer.data == NULL || (int) buffer.length < xSize * ySize) - { - if( buffer.data ) delete [] buffer.data; - buffer = doubleArray(xSize * ySize); - } - else for (unsigned int i = 0; i < buffer.length; i++) - buffer[i] = 0; +doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, + double y, int xSize, int ySize, + double xScale, double yScale, + double sizeScale, double powScale) { + xScale /= 1.5; + yScale /= 1.5; + if (buffer.data == NULL || (int)buffer.length < xSize * ySize) { + if (buffer.data) delete[] buffer.data; + buffer = doubleArray(xSize * ySize); + } else + for (unsigned int i = 0; i < buffer.length; i++) buffer[i] = 0; double pow = 1; double scale = 1; - for (int i = 0; i < levels; i++) - { - noiseLevels[i]->add(buffer, x, y, xSize, ySize, xScale * scale, yScale * scale, 0.55/pow); + for (int i = 0; i < levels; i++) { + noiseLevels[i]->add(buffer, x, y, xSize, ySize, xScale * scale, + yScale * scale, 0.55 / pow); scale *= sizeScale; pow *= powScale; } @@ -93,21 +85,25 @@ doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, double y return buffer; } -doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, double y, double z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale) -{ - xScale/=1.5; - yScale/=1.5; - - if (buffer.data == NULL) buffer = doubleArray(xSize * ySize * zSize); - else for (unsigned int i = 0; i < buffer.length; i++) - buffer[i] = 0; +doubleArray PerlinSimplexNoise::getRegion(doubleArray buffer, double x, + double y, double z, int xSize, + int ySize, int zSize, double xScale, + double yScale, double zScale) { + xScale /= 1.5; + yScale /= 1.5; + if (buffer.data == NULL) + buffer = doubleArray(xSize * ySize * zSize); + else + for (unsigned int i = 0; i < buffer.length; i++) buffer[i] = 0; double pow = 1; for (int i = 0; i < levels; i++) { - // value += noiseLevels[i].getValue(x * pow, y * pow, z * pow) / pow; - noiseLevels[i]->add(buffer, x, y, z, xSize, ySize, zSize, xScale * pow, yScale * pow, zScale * pow, 0.55/pow); + // value += noiseLevels[i].getValue(x * pow, y * pow, z * + // pow) / pow; + noiseLevels[i]->add(buffer, x, y, z, xSize, ySize, zSize, xScale * pow, + yScale * pow, zScale * pow, 0.55 / pow); pow *= 0.5; } diff --git a/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.h b/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.h index 396259885..7331299c9 100644 --- a/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.h +++ b/Minecraft.World/WorldGen/Noise/PerlinSimplexNoise.h @@ -2,22 +2,27 @@ #include "Synth.h" #include "SimplexNoise.h" -class PerlinSimplexNoise : public Synth -{ +class PerlinSimplexNoise : public Synth { private: - SimplexNoise **noiseLevels; + SimplexNoise** noiseLevels; int levels; public: PerlinSimplexNoise(int levels); - PerlinSimplexNoise(Random *random, int levels); - void init(Random *random, int levels); - ~PerlinSimplexNoise(); + PerlinSimplexNoise(Random* random, int levels); + void init(Random* random, int levels); + ~PerlinSimplexNoise(); virtual double getValue(double x, double y); double getValue(double x, double y, double z); - doubleArray getRegion(doubleArray buffer, double x, double y, int xSize, int ySize, double xScale, double yScale, double sizeScale); - doubleArray getRegion(doubleArray buffer, double x, double y, int xSize, int ySize, double xScale, double yScale, double sizeScale, double powScale); - doubleArray getRegion(doubleArray buffer, double x, double y, double z, int xSize, int ySize, int zSize, double xScale, double yScale, double zScale); + doubleArray getRegion(doubleArray buffer, double x, double y, int xSize, + int ySize, double xScale, double yScale, + double sizeScale); + doubleArray getRegion(doubleArray buffer, double x, double y, int xSize, + int ySize, double xScale, double yScale, + double sizeScale, double powScale); + doubleArray getRegion(doubleArray buffer, double x, double y, double z, + int xSize, int ySize, int zSize, double xScale, + double yScale, double zScale); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Noise/SimplexNoise.cpp b/Minecraft.World/WorldGen/Noise/SimplexNoise.cpp index c37253bdc..e505d3622 100644 --- a/Minecraft.World/WorldGen/Noise/SimplexNoise.cpp +++ b/Minecraft.World/WorldGen/Noise/SimplexNoise.cpp @@ -1,38 +1,33 @@ #include "../../Platform/stdafx.h" #include "SimplexNoise.h" -int SimplexNoise::grad3[12][3] = { { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, { -1, 0, -1 }, { 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, -1, -1 } }; +int SimplexNoise::grad3[12][3] = { + {1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, + {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; double SimplexNoise::F2 = 0.5 * (sqrt(3.0) - 1.0); double SimplexNoise::G2 = (3.0 - sqrt(3.0)) / 6.0; double SimplexNoise::F3 = 1.0 / 3.0; double SimplexNoise::G3 = 1.0 / 6.0; -SimplexNoise::SimplexNoise() -{ - Random random; - init(&random); +SimplexNoise::SimplexNoise() { + Random random; + init(&random); } -SimplexNoise::SimplexNoise(Random *random) -{ - init(random); -} +SimplexNoise::SimplexNoise(Random* random) { init(random); } -void SimplexNoise::init(Random *random) -{ - p = new int[512]; +void SimplexNoise::init(Random* random) { + p = new int[512]; xo = random->nextDouble() * 256; yo = random->nextDouble() * 256; zo = random->nextDouble() * 256; - for (int i = 0; i < 256; i++) - { + for (int i = 0; i < 256; i++) { p[i] = i; } - for (int i = 0; i < 256; i++) - { + for (int i = 0; i < 256; i++) { int j = random->nextInt(256 - i) + i; int tmp = p[i]; p[i] = p[j]; @@ -42,55 +37,49 @@ void SimplexNoise::init(Random *random) } } -SimplexNoise::~SimplexNoise() -{ - delete [] p; +SimplexNoise::~SimplexNoise() { delete[] p; } + +int SimplexNoise::fastfloor(double x) { return x > 0 ? (int)x : (int)x - 1; } + +double SimplexNoise::dot(int* g, double x, double y) { + return g[0] * x + g[1] * y; } -int SimplexNoise::fastfloor(double x) -{ - return x > 0 ? (int) x : (int) x - 1; +double SimplexNoise::dot(int* g, double x, double y, double z) { + return g[0] * x + g[1] * y + g[2] * z; } -double SimplexNoise::dot(int *g, double x, double y) -{ - return g[0] * x + g[1] * y; -} - -double SimplexNoise::dot(int *g, double x, double y, double z) -{ - return g[0] * x + g[1] * y + g[2] * z; -} - -double SimplexNoise::getValue(double xin, double yin) -{ - double n0, n1, n2; // Noise contributions from the three corners +double SimplexNoise::getValue(double xin, double yin) { + double n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in - double s = (xin + yin) * F2; // Hairy factor for 2D + double s = (xin + yin) * F2; // Hairy factor for 2D int i = fastfloor(xin + s); int j = fastfloor(yin + s); double t = (i + j) * G2; - double X0 = i - t; // Unskew the cell origin back to (x,y) space + double X0 = i - t; // Unskew the cell origin back to (x,y) space double Y0 = j - t; - double x0 = xin - X0; // The x,y distances from the cell origin + double x0 = xin - X0; // The x,y distances from the cell origin double y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. - int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords + int i1, + j1; // Offsets for second (middle) corner of simplex in (i,j) coords if (x0 > y0) { i1 = 1; j1 = 0; - } // lower triangle, XY order: (0,0)->(1,0)->(1,1) + } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; - } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 - double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + double x1 = + x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords double y1 = y0 - j1 + G2; - double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords + double x2 = x0 - 1.0 + + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords double y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; @@ -100,19 +89,23 @@ double SimplexNoise::getValue(double xin, double yin) int gi2 = p[ii + 1 + p[jj + 1]] % 12; // Calculate the contribution from the three corners double t0 = 0.5 - x0 * x0 - y0 * y0; - if (t0 < 0) n0 = 0.0; + if (t0 < 0) + n0 = 0.0; else { t0 *= t0; - n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + n0 = t0 * t0 * + dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient } double t1 = 0.5 - x1 * x1 - y1 * y1; - if (t1 < 0) n1 = 0.0; + if (t1 < 0) + n1 = 0.0; else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1); } double t2 = 0.5 - x2 * x2 - y2 * y2; - if (t2 < 0) n2 = 0.0; + if (t2 < 0) + n2 = 0.0; else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2); @@ -122,8 +115,7 @@ double SimplexNoise::getValue(double xin, double yin) return 70.0 * (n0 + n1 + n2); } -double SimplexNoise::getValue(double xin, double yin, double zin) -{ +double SimplexNoise::getValue(double xin, double yin, double zin) { double n0, n1, n2, n3; double s = (xin + yin + zin) * F3; int i = fastfloor(xin + s); @@ -139,78 +131,71 @@ double SimplexNoise::getValue(double xin, double yin, double zin) double z0 = zin - Z0; int i1, j1, k1; int i2, j2, k2; - if (x0 >= y0) - { - if (y0 >= z0) - { + if (x0 >= y0) { + if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; - } // X Y Z order - else if (x0 >= z0) - { + } // X Y Z order + else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; - } // X Z Y order - else - { + } // X Z Y order + else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; - } // Z X Y order - } - else - { // x0 y0) - { + int i1, j1; // Offsets for second (middle) corner of simplex in + // (i,j) coords + if (x0 > y0) { i1 = 1; j1 = 0; - } // lower triangle, XY order: (0,0)->(1,0)->(1,1) - else - { + } // lower triangle, XY order: (0,0)->(1,0)->(1,1) + else { i1 = 0; j1 = 1; - } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 - double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + double x1 = + x0 - i1 + + G2; // Offsets for middle corner in (x,y) unskewed coords double y1 = y0 - j1 + G2; - double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords + double x2 = + x0 - 1.0 + + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords double y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; @@ -302,46 +288,45 @@ void SimplexNoise::add(doubleArray buffer, double _x, double _y, int xSize, int int gi2 = p[ii + 1 + p[jj + 1]] % 12; // Calculate the contribution from the three corners double t0 = 0.5 - x0 * x0 - y0 * y0; - if (t0 < 0) n0 = 0.0; - else - { + if (t0 < 0) + n0 = 0.0; + else { t0 *= t0; - n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + n0 = t0 * t0 * + dot(grad3[gi0], x0, + y0); // (x,y) of grad3 used for 2D gradient } double t1 = 0.5 - x1 * x1 - y1 * y1; - if (t1 < 0) n1 = 0.0; - else - { + if (t1 < 0) + n1 = 0.0; + else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1); } double t2 = 0.5 - x2 * x2 - y2 * y2; - if (t2 < 0) n2 = 0.0; - else - { + if (t2 < 0) + n2 = 0.0; + else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. - buffer[pp++] += (70.0 * (n0 + n1 + n2))*pow; + buffer[pp++] += (70.0 * (n0 + n1 + n2)) * pow; } } - } -void SimplexNoise::add(doubleArray buffer, double _x, double _y, double _z, int xSize, int ySize, int zSize, double xs, double ys, double zs, double pow) -{ +void SimplexNoise::add(doubleArray buffer, double _x, double _y, double _z, + int xSize, int ySize, int zSize, double xs, double ys, + double zs, double pow) { int pp = 0; - for (int xx = 0; xx < xSize; xx++) - { + for (int xx = 0; xx < xSize; xx++) { double xin = (_x + xx) * xs + xo; - for (int zz = 0; zz < zSize; zz++) - { + for (int zz = 0; zz < zSize; zz++) { double zin = (_z + zz) * zs + zo; - for (int yy = 0; yy < ySize; yy++) - { + for (int yy = 0; yy < ySize; yy++) { double yin = (_y + yy) * ys + yo; - + double n0, n1, n2, n3; double s = (xin + yin + zin) * F3; int i = fastfloor(xin + s); @@ -356,81 +341,78 @@ void SimplexNoise::add(doubleArray buffer, double _x, double _y, double _z, int double z0 = zin - Z0; int i1, j1, k1; int i2, j2, k2; - if (x0 >= y0) - { - if (y0 >= z0) - { + if (x0 >= y0) { + if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; - } // X Y Z order - else if (x0 >= z0) - { + } // X Y Z order + else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; - } // X Z Y order - else - { + } // X Z Y order + else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; - } // Z X Y order - } - else - { // x0getLevelData()->getXZSize(); - - this->level = level; - this->generateStructures = generateStructures; - this->random = new Random(seed); - this->pprandom = new Random(seed); // 4J - added, so that we can have a separate random for doing post-processing in parallel with creation - - villageFeature = new VillageFeature(0,m_XZSize); +FlatLevelSource::FlatLevelSource(Level* level, __int64 seed, + bool generateStructures) { + m_XZSize = level->getLevelData()->getXZSize(); + this->level = level; + this->generateStructures = generateStructures; + this->random = new Random(seed); + this->pprandom = new Random( + seed); // 4J - added, so that we can have a separate random for doing + // post-processing in parallel with creation + villageFeature = new VillageFeature(0, m_XZSize); } -FlatLevelSource::~FlatLevelSource() -{ - delete random; - delete pprandom; - delete villageFeature; +FlatLevelSource::~FlatLevelSource() { + delete random; + delete pprandom; + delete villageFeature; } -void FlatLevelSource::prepareHeights(byteArray blocks) -{ - int height = blocks.length / (16 * 16); +void FlatLevelSource::prepareHeights(byteArray blocks) { + int height = blocks.length / (16 * 16); - for (int xc = 0; xc < 16; xc++) - { - for (int zc = 0; zc < 16; zc++) - { - for (int yc = 0; yc < height; yc++) - { - int block = 0; - if (yc == 0) - { - block = Tile::unbreakable_Id; - } - else if (yc <= 2) - { - block = Tile::dirt_Id; - } - else if (yc == 3) - { - block = Tile::grass_Id; - } - blocks[xc << 11 | zc << 7 | yc] = (uint8_t) block; - } - } - } + for (int xc = 0; xc < 16; xc++) { + for (int zc = 0; zc < 16; zc++) { + for (int yc = 0; yc < height; yc++) { + int block = 0; + if (yc == 0) { + block = Tile::unbreakable_Id; + } else if (yc <= 2) { + block = Tile::dirt_Id; + } else if (yc == 3) { + block = Tile::grass_Id; + } + blocks[xc << 11 | zc << 7 | yc] = (uint8_t)block; + } + } + } } -LevelChunk *FlatLevelSource::create(int x, int z) -{ - return getChunk(x, z); +LevelChunk* FlatLevelSource::create(int x, int z) { return getChunk(x, z); } + +LevelChunk* FlatLevelSource::getChunk(int xOffs, int zOffs) { + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + int chunksSize = Level::genDepth * 16 * 16; + uint8_t* tileData = (uint8_t*)XPhysicalAlloc(chunksSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); + XMemSet128(tileData, 0, chunksSize); + byteArray blocks = byteArray(tileData, chunksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); + prepareHeights(blocks); + + // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + //// 4J - moved below + // double[] temperatures = level.getBiomeSource().temperatures; + + if (generateStructures) { + villageFeature->apply(this, level, xOffs, zOffs, blocks); + } + + // 4J - this now creates compressed block data from the blocks array passed + // in, so moved it until after the blocks are actually finalised. We also + // now need to free the passed in blocks as the LevelChunk doesn't use the + // passed in allocation anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + XPhysicalFree(tileData); + + levelChunk->recalcHeightmap(); + + return levelChunk; } -LevelChunk *FlatLevelSource::getChunk(int xOffs, int zOffs) -{ - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - int chunksSize = Level::genDepth * 16 * 16; - uint8_t *tileData = (uint8_t *)XPhysicalAlloc(chunksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,chunksSize); - byteArray blocks = byteArray(tileData,chunksSize); -// byteArray blocks = byteArray(16 * level->depth * 16); - prepareHeights(blocks); +bool FlatLevelSource::hasChunk(int x, int y) { return true; } -// LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); // 4J - moved below - // double[] temperatures = level.getBiomeSource().temperatures; +void FlatLevelSource::postProcess(ChunkSource* parent, int xt, int zt) { + // 4J - changed from random to pprandom so we can run in parallel with + // getChunk etc. + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); + if (generateStructures) { + villageFeature->postProcess(level, pprandom, xt, zt); + } - if (generateStructures) - { - villageFeature->apply(this, level, xOffs, zOffs, blocks); - } - - // 4J - this now creates compressed block data from the blocks array passed in, so moved it until after the blocks are actually finalised. We also - // now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - XPhysicalFree(tileData); - - levelChunk->recalcHeightmap(); - - return levelChunk; + app.processSchematics(parent->getChunk(xt, zt)); } - -bool FlatLevelSource::hasChunk(int x, int y) -{ - return true; +bool FlatLevelSource::save(bool force, ProgressListener* progressListener) { + return true; } -void FlatLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ - // 4J - changed from random to pprandom so we can run in parallel with getChunk etc. - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); +bool FlatLevelSource::tick() { return false; } - if (generateStructures) - { - villageFeature->postProcess(level, pprandom, xt, zt); - } - - app.processSchematics(parent->getChunk(xt,zt)); +bool FlatLevelSource::shouldSave() { return true; } + +std::wstring FlatLevelSource::gatherStats() { return L"FlatLevelSource"; } + +std::vector* FlatLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { + return NULL; + } + return biome->getMobs(mobCategory); } -bool FlatLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; -} - -bool FlatLevelSource::tick() -{ - return false; -} - -bool FlatLevelSource::shouldSave() -{ - return true; -} - -std::wstring FlatLevelSource::gatherStats() -{ - return L"FlatLevelSource"; -} - -std::vector *FlatLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { - return NULL; - } - return biome->getMobs(mobCategory); -} - -TilePos *FlatLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - return NULL; +TilePos* FlatLevelSource::findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z) { + return NULL; } diff --git a/Minecraft.World/WorldGen/Sources/FlatLevelSource.h b/Minecraft.World/WorldGen/Sources/FlatLevelSource.h index 430eb722b..5d188a067 100644 --- a/Minecraft.World/WorldGen/Sources/FlatLevelSource.h +++ b/Minecraft.World/WorldGen/Sources/FlatLevelSource.h @@ -1,6 +1,5 @@ #pragma once - #include "../../Level/ChunkSource.h" class ProgressListener; @@ -10,35 +9,38 @@ class VillageFeature; class MineShaftFeature; class PerlinNoise; -class FlatLevelSource : public ChunkSource -{ +class FlatLevelSource : public ChunkSource { public: - static const int CHUNK_HEIGHT = 8; - static const int CHUNK_WIDTH = 4; + static const int CHUNK_HEIGHT = 8; + static const int CHUNK_WIDTH = 4; private: - Level *level; - Random *random; - Random *pprandom; + Level* level; + Random* random; + Random* pprandom; - boolean generateStructures; - VillageFeature *villageFeature;// = new VillageFeature(1); + boolean generateStructures; + VillageFeature* villageFeature; // = new VillageFeature(1); -public: - FlatLevelSource(Level *level, __int64 seed, bool generateStructures); - ~FlatLevelSource(); +public: + FlatLevelSource(Level* level, __int64 seed, bool generateStructures); + ~FlatLevelSource(); -private: void prepareHeights(byteArray blocks); +private: + void prepareHeights(byteArray blocks); -public: - virtual LevelChunk *create(int x, int z); - virtual LevelChunk *getChunk(int xOffs, int zOffs); - virtual bool hasChunk(int x, int y); - virtual void postProcess(ChunkSource *parent, int xt, int zt); - virtual bool save(bool force, ProgressListener *progressListener); - virtual bool tick(); - virtual bool shouldSave(); - virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); +public: + virtual LevelChunk* create(int x, int z); + virtual LevelChunk* getChunk(int xOffs, int zOffs); + virtual bool hasChunk(int x, int y); + virtual void postProcess(ChunkSource* parent, int xt, int zt); + virtual bool save(bool force, ProgressListener* progressListener); + virtual bool tick(); + virtual bool shouldSave(); + virtual std::wstring gatherStats(); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.cpp b/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.cpp index 287db0ad4..3f542ef63 100644 --- a/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.cpp +++ b/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.cpp @@ -4,169 +4,152 @@ #include "../../Headers/net.minecraft.world.level.storage.h" #include "HellFlatLevelSource.h" -HellFlatLevelSource::HellFlatLevelSource(Level *level, __int64 seed) -{ - int xzSize = level->getLevelData()->getXZSize(); - int hellScale = level->getLevelData()->getHellScale(); - m_XZSize = ceil((float)xzSize / hellScale); +HellFlatLevelSource::HellFlatLevelSource(Level* level, __int64 seed) { + int xzSize = level->getLevelData()->getXZSize(); + int hellScale = level->getLevelData()->getHellScale(); + m_XZSize = ceil((float)xzSize / hellScale); this->level = level; random = new Random(seed); - pprandom = new Random(seed); + pprandom = new Random(seed); } -HellFlatLevelSource::~HellFlatLevelSource() -{ - delete random; - delete pprandom; +HellFlatLevelSource::~HellFlatLevelSource() { + delete random; + delete pprandom; } -void HellFlatLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) -{ - int height = blocks.length / (16 * 16); +void HellFlatLevelSource::prepareHeights(int xOffs, int zOffs, + byteArray blocks) { + int height = blocks.length / (16 * 16); - for (int xc = 0; xc < 16; xc++) - { - for (int zc = 0; zc < 16; zc++) - { - for (int yc = 0; yc < height; yc++) - { - int block = 0; - if ( (yc <= 6) || ( yc >= 121 ) ) - { - block = Tile::hellRock_Id; - } - - blocks[xc << 11 | zc << 7 | yc] = (uint8_t) block; - } - } - } -} - -void HellFlatLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks) -{ - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { - for (int y = Level::genDepthMinusOne; y >= 0; y--) - { - int offs = (z * 16 + x) * Level::genDepth + y; - - // 4J Build walls around the level - bool blockSet = false; - if(xOffs <= -(m_XZSize/2)) - { - if( z - random->nextInt( 4 ) <= 0 || xOffs < -(m_XZSize/2) ) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(zOffs <= -(m_XZSize/2)) - { - if( x - random->nextInt( 4 ) <= 0 || zOffs < -(m_XZSize/2)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(xOffs >= (m_XZSize/2)-1) - { - if( z + random->nextInt(4) >= 15 || xOffs > (m_XZSize/2)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(zOffs >= (m_XZSize/2)-1) - { - if( x + random->nextInt(4) >= 15 || zOffs > (m_XZSize/2) ) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if( blockSet ) continue; - // End 4J Extra to build walls around the level - - if (y >= Level::genDepthMinusOne - random->nextInt(5)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; + for (int xc = 0; xc < 16; xc++) { + for (int zc = 0; zc < 16; zc++) { + for (int yc = 0; yc < height; yc++) { + int block = 0; + if ((yc <= 6) || (yc >= 121)) { + block = Tile::hellRock_Id; } - else if (y <= 0 + random->nextInt(5)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; -} + + blocks[xc << 11 | zc << 7 | yc] = (uint8_t)block; } } } } -LevelChunk *HellFlatLevelSource::create(int x, int z) -{ - return getChunk(x,z); +void HellFlatLevelSource::buildSurfaces(int xOffs, int zOffs, + byteArray blocks) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = Level::genDepthMinusOne; y >= 0; y--) { + int offs = (z * 16 + x) * Level::genDepth + y; + + // 4J Build walls around the level + bool blockSet = false; + if (xOffs <= -(m_XZSize / 2)) { + if (z - random->nextInt(4) <= 0 || + xOffs < -(m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (zOffs <= -(m_XZSize / 2)) { + if (x - random->nextInt(4) <= 0 || + zOffs < -(m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (xOffs >= (m_XZSize / 2) - 1) { + if (z + random->nextInt(4) >= 15 || + xOffs > (m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (zOffs >= (m_XZSize / 2) - 1) { + if (x + random->nextInt(4) >= 15 || + zOffs > (m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (blockSet) continue; + // End 4J Extra to build walls around the level + + if (y >= Level::genDepthMinusOne - random->nextInt(5)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + } else if (y <= 0 + random->nextInt(5)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + } + } + } + } } -LevelChunk *HellFlatLevelSource::getChunk(int xOffs, int zOffs) -{ +LevelChunk* HellFlatLevelSource::create(int x, int z) { return getChunk(x, z); } + +LevelChunk* HellFlatLevelSource::getChunk(int xOffs, int zOffs) { random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - int chunksSize = Level::genDepth * 16 * 16; - uint8_t *tileData = (uint8_t *)XPhysicalAlloc(chunksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,chunksSize); - byteArray blocks = byteArray(tileData,chunksSize); -// byteArray blocks = byteArray(16 * level->depth * 16); + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + int chunksSize = Level::genDepth * 16 * 16; + uint8_t* tileData = (uint8_t*)XPhysicalAlloc(chunksSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); + XMemSet128(tileData, 0, chunksSize); + byteArray blocks = byteArray(tileData, chunksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); prepareHeights(xOffs, zOffs, blocks); buildSurfaces(xOffs, zOffs, blocks); -// caveFeature->apply(this, level, xOffs, zOffs, blocks); + // caveFeature->apply(this, level, xOffs, zOffs, blocks); // townFeature.apply(this, level, xOffs, zOffs, blocks); // addCaves(xOffs, zOffs, blocks); // addTowns(xOffs, zOffs, blocks); - // 4J - this now creates compressed block data from the blocks array passed in, so needs to be after data is finalised. - // Also now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - XPhysicalFree(tileData); + // 4J - this now creates compressed block data from the blocks array passed + // in, so needs to be after data is finalised. Also now need to free the + // passed in blocks as the LevelChunk doesn't use the passed in allocation + // anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + XPhysicalFree(tileData); return levelChunk; } -// 4J - removed & moved into its own method from getChunk, so we can call recalcHeightmap after the chunk is added into the cache. Without -// doing this, then loads of the lightgaps() calls will fail to add any lights, because adding a light checks if the cache has this chunk in. -// lightgaps also does light 1 block into the neighbouring chunks, and maybe that is somehow enough to get lighting to propagate round the world, -// but this just doesn't seem right - this isn't a new fault in the 360 version, have checked that java does the same. -void HellFlatLevelSource::lightChunk(LevelChunk *lc) -{ - lc->recalcHeightmap(); -} +// 4J - removed & moved into its own method from getChunk, so we can call +// recalcHeightmap after the chunk is added into the cache. Without doing this, +// then loads of the lightgaps() calls will fail to add any lights, because +// adding a light checks if the cache has this chunk in. lightgaps also does +// light 1 block into the neighbouring chunks, and maybe that is somehow enough +// to get lighting to propagate round the world, but this just doesn't seem +// right - this isn't a new fault in the 360 version, have checked that java +// does the same. +void HellFlatLevelSource::lightChunk(LevelChunk* lc) { lc->recalcHeightmap(); } -bool HellFlatLevelSource::hasChunk(int x, int y) -{ - return true; -} +bool HellFlatLevelSource::hasChunk(int x, int y) { return true; } -void HellFlatLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ +void HellFlatLevelSource::postProcess(ChunkSource* parent, int xt, int zt) { HeavyTile::instaFall = true; int xo = xt * 16; int zo = zt * 16; - // 4J - added. The original java didn't do any setting of the random seed here. We'll be running our postProcess in parallel with getChunk etc. so - // we need to use a separate random - have used the same initialisation code as used in RandomLevelSource::postProcess to make sure this random value - // is consistent for each world generation. Also changed all uses of random here to pprandom. - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); + // 4J - added. The original java didn't do any setting of the random seed + // here. We'll be running our postProcess in parallel with getChunk etc. so + // we need to use a separate random - have used the same initialisation code + // as used in RandomLevelSource::postProcess to make sure this random value + // is consistent for each world generation. Also changed all uses of random + // here to pprandom. + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + pprandom->setSeed(((xt * xScale) + (zt * zScale)) ^ level->getSeed()); int count = pprandom->nextInt(pprandom->nextInt(10) + 1) + 1; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth - 8) + 4; int z = zo + pprandom->nextInt(16) + 8; @@ -174,8 +157,7 @@ void HellFlatLevelSource::postProcess(ChunkSource *parent, int xt, int zt) } count = pprandom->nextInt(pprandom->nextInt(10) + 1); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth - 8) + 4; int z = zo + pprandom->nextInt(16) + 8; @@ -184,41 +166,31 @@ void HellFlatLevelSource::postProcess(ChunkSource *parent, int xt, int zt) HeavyTile::instaFall = false; - app.processSchematics(parent->getChunk(xt,zt)); - + app.processSchematics(parent->getChunk(xt, zt)); } -bool HellFlatLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; +bool HellFlatLevelSource::save(bool force, ProgressListener* progressListener) { + return true; } -bool HellFlatLevelSource::tick() -{ - return false; +bool HellFlatLevelSource::tick() { return false; } + +bool HellFlatLevelSource::shouldSave() { return true; } + +std::wstring HellFlatLevelSource::gatherStats() { + return L"HellFlatLevelSource"; } -bool HellFlatLevelSource::shouldSave() -{ - return true; +std::vector* HellFlatLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { + return NULL; + } + return biome->getMobs(mobCategory); } -std::wstring HellFlatLevelSource::gatherStats() -{ - return L"HellFlatLevelSource"; -} - -std::vector *HellFlatLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { - return NULL; - } - return biome->getMobs(mobCategory); -} - -TilePos *HellFlatLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - return NULL; +TilePos* HellFlatLevelSource::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } diff --git a/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.h b/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.h index 6ff27e654..e89ce28b1 100644 --- a/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.h +++ b/Minecraft.World/WorldGen/Sources/HellFlatLevelSource.h @@ -12,22 +12,21 @@ class ProgressListener; -class HellFlatLevelSource : public ChunkSource -{ +class HellFlatLevelSource : public ChunkSource { public: - static const int CHUNK_HEIGHT = 8; + static const int CHUNK_HEIGHT = 8; static const int CHUNK_WIDTH = 4; private: - Random *random; - Random *pprandom; + Random* random; + Random* pprandom; private: - Level *level; + Level* level; public: - HellFlatLevelSource(Level *level, __int64 seed); - ~HellFlatLevelSource(); + HellFlatLevelSource(Level* level, __int64 seed); + ~HellFlatLevelSource(); private: void prepareHeights(int xOffs, int zOffs, byteArray blocks); @@ -35,17 +34,20 @@ private: public: void buildSurfaces(int xOffs, int zOffs, byteArray blocks); - LevelChunk *create(int x, int z); - LevelChunk *getChunk(int xOffs, int zOffs); - virtual void lightChunk(LevelChunk *lc); // 4J added + LevelChunk* create(int x, int z); + LevelChunk* getChunk(int xOffs, int zOffs); + virtual void lightChunk(LevelChunk* lc); // 4J added public: - virtual bool hasChunk(int x, int y); - void postProcess(ChunkSource *parent, int xt, int zt); - bool save(bool force, ProgressListener *progressListener); + virtual bool hasChunk(int x, int y); + void postProcess(ChunkSource* parent, int xt, int zt); + bool save(bool force, ProgressListener* progressListener); bool tick(); bool shouldSave(); std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.cpp b/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.cpp index 8b3864211..4b7a40e85 100644 --- a/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.cpp +++ b/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.cpp @@ -7,19 +7,20 @@ #include "../Biomes/BiomeSource.h" #include "HellRandomLevelSource.h" -HellRandomLevelSource::HellRandomLevelSource(Level *level, __int64 seed) -{ - int xzSize = level->getLevelData()->getXZSize(); - int hellScale = level->getLevelData()->getHellScale(); - m_XZSize = ceil((float)xzSize / hellScale); +HellRandomLevelSource::HellRandomLevelSource(Level* level, __int64 seed) { + int xzSize = level->getLevelData()->getXZSize(); + int hellScale = level->getLevelData()->getHellScale(); + m_XZSize = ceil((float)xzSize / hellScale); - netherBridgeFeature = new NetherBridgeFeature(); - caveFeature = new LargeHellCaveFeature(); + netherBridgeFeature = new NetherBridgeFeature(); + caveFeature = new LargeHellCaveFeature(); this->level = level; random = new Random(seed); - pprandom = new Random(seed); // 4J - added, so that we can have a separate random for doing post-processing in parallel with creation + pprandom = new Random( + seed); // 4J - added, so that we can have a separate random for doing + // post-processing in parallel with creation lperlinNoise1 = new PerlinNoise(random, 16); lperlinNoise2 = new PerlinNoise(random, 16); perlinNoise1 = new PerlinNoise(random, 8); @@ -30,13 +31,12 @@ HellRandomLevelSource::HellRandomLevelSource(Level *level, __int64 seed) depthNoise = new PerlinNoise(random, 16); } -HellRandomLevelSource::~HellRandomLevelSource() -{ - delete netherBridgeFeature; - delete caveFeature; +HellRandomLevelSource::~HellRandomLevelSource() { + delete netherBridgeFeature; + delete caveFeature; delete random; - delete pprandom; // 4J added + delete pprandom; // 4J added delete lperlinNoise1; delete lperlinNoise2; delete perlinNoise1; @@ -47,64 +47,78 @@ HellRandomLevelSource::~HellRandomLevelSource() delete depthNoise; } -void HellRandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks) -{ +void HellRandomLevelSource::prepareHeights(int xOffs, int zOffs, + byteArray blocks) { int xChunks = 16 / CHUNK_WIDTH; int waterHeight = 32; int xSize = xChunks + 1; int ySize = Level::genDepth / CHUNK_HEIGHT + 1; int zSize = xChunks + 1; - doubleArray buffer; // 4J - used to be declared with class level scope but tidying up for thread safety reasons - buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, ySize, zSize); + doubleArray buffer; // 4J - used to be declared with class level scope but + // tidying up for thread safety reasons + buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, + ySize, zSize); - for (int xc = 0; xc < xChunks; xc++) - { - for (int zc = 0; zc < xChunks; zc++) - { - for (int yc = 0; yc < Level::genDepth / CHUNK_HEIGHT; yc++) - { - double yStep = 1 / (double) CHUNK_HEIGHT; - double s0 = buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s1 = buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s2 = buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s3 = buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; + for (int xc = 0; xc < xChunks; xc++) { + for (int zc = 0; zc < xChunks; zc++) { + for (int yc = 0; yc < Level::genDepth / CHUNK_HEIGHT; yc++) { + double yStep = 1 / (double)CHUNK_HEIGHT; + double s0 = + buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s1 = + buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; + double s2 = + buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s3 = + buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s0a = (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - s0) * yStep; - double s1a = (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - s1) * yStep; - double s2a = (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - s2) * yStep; - double s3a = (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - s3) * yStep; + double s0a = + (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s0) * + yStep; + double s1a = + (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s1) * + yStep; + double s2a = + (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s2) * + yStep; + double s3a = + (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s3) * + yStep; - for (int y = 0; y < CHUNK_HEIGHT; y++) - { - double xStep = 1 / (double) CHUNK_WIDTH; + for (int y = 0; y < CHUNK_HEIGHT; y++) { + double xStep = 1 / (double)CHUNK_WIDTH; double _s0 = s0; double _s1 = s1; double _s0a = (s2 - s0) * xStep; double _s1a = (s3 - s1) * xStep; - for (int x = 0; x < CHUNK_WIDTH; x++) - { - int offs = (x + xc * CHUNK_WIDTH) << Level::genDepthBitsPlusFour | (0 + zc * CHUNK_WIDTH) << Level::genDepthBits | (yc * CHUNK_HEIGHT + y); + for (int x = 0; x < CHUNK_WIDTH; x++) { + int offs = (x + xc * CHUNK_WIDTH) + << Level::genDepthBitsPlusFour | + (0 + zc * CHUNK_WIDTH) + << Level::genDepthBits | + (yc * CHUNK_HEIGHT + y); int step = 1 << Level::genDepthBits; - double zStep = 1 / (double) CHUNK_WIDTH; + double zStep = 1 / (double)CHUNK_WIDTH; double val = _s0; double vala = (_s1 - _s0) * zStep; - for (int z = 0; z < CHUNK_WIDTH; z++) - { + for (int z = 0; z < CHUNK_WIDTH; z++) { int tileId = 0; - if (yc * CHUNK_HEIGHT + y < waterHeight) - { + if (yc * CHUNK_HEIGHT + y < waterHeight) { tileId = Tile::calmLava_Id; } - if (val > 0) - { + if (val > 0) { tileId = Tile::hellRock_Id; } - blocks[offs] = (uint8_t) tileId; + blocks[offs] = (uint8_t)tileId; offs += step; val += vala; } @@ -120,135 +134,140 @@ void HellRandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray block } } } - delete [] buffer.data; + delete[] buffer.data; } -void HellRandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks) -{ +void HellRandomLevelSource::buildSurfaces(int xOffs, int zOffs, + byteArray blocks) { int waterHeight = Level::genDepth - 64; double s = 1 / 32.0; - doubleArray sandBuffer(16*16); // 4J - used to be declared with class level scope but moved here for thread safety - doubleArray gravelBuffer(16*16); - doubleArray depthBuffer(16*16); + doubleArray sandBuffer(16 * + 16); // 4J - used to be declared with class level + // scope but moved here for thread safety + doubleArray gravelBuffer(16 * 16); + doubleArray depthBuffer(16 * 16); - sandBuffer = perlinNoise2->getRegion(sandBuffer, xOffs * 16, zOffs * 16, 0, 16, 16, 1, s, s, 1); - gravelBuffer = perlinNoise2->getRegion(gravelBuffer, xOffs * 16, 109, zOffs * 16, 16, 1, 16, s, 1, s); - depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, 0, 16, 16, 1, s * 2, s * 2, s * 2); + sandBuffer = perlinNoise2->getRegion(sandBuffer, xOffs * 16, zOffs * 16, 0, + 16, 16, 1, s, s, 1); + gravelBuffer = perlinNoise2->getRegion(gravelBuffer, xOffs * 16, 109, + zOffs * 16, 16, 1, 16, s, 1, s); + depthBuffer = perlinNoise3->getRegion(depthBuffer, xOffs * 16, zOffs * 16, + 0, 16, 16, 1, s * 2, s * 2, s * 2); - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { - bool sand = (sandBuffer[x + z * 16] + random->nextDouble() * 0.2) > 0; - bool gravel = (gravelBuffer[x + z * 16] + random->nextDouble() * 0.2) > 0; - int runDepth = (int) (depthBuffer[x + z * 16] / 3 + 3 + random->nextDouble() * 0.25); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + bool sand = + (sandBuffer[x + z * 16] + random->nextDouble() * 0.2) > 0; + bool gravel = + (gravelBuffer[x + z * 16] + random->nextDouble() * 0.2) > 0; + int runDepth = (int)(depthBuffer[x + z * 16] / 3 + 3 + + random->nextDouble() * 0.25); int run = -1; - uint8_t top = (uint8_t) Tile::hellRock_Id; - uint8_t material = (uint8_t) Tile::hellRock_Id; + uint8_t top = (uint8_t)Tile::hellRock_Id; + uint8_t material = (uint8_t)Tile::hellRock_Id; - for (int y = Level::genDepthMinusOne; y >= 0; y--) - { + for (int y = Level::genDepthMinusOne; y >= 0; y--) { int offs = (z * 16 + x) * Level::genDepth + y; - // 4J Build walls around the level - bool blockSet = false; - if(xOffs <= -(m_XZSize/2)) - { - if( z - random->nextInt( 4 ) <= 0 || xOffs < -(m_XZSize/2) ) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(zOffs <= -(m_XZSize/2)) - { - if( x - random->nextInt( 4 ) <= 0 || zOffs < -(m_XZSize/2)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(xOffs >= (m_XZSize/2)-1) - { - if( z + random->nextInt(4) >= 15 || xOffs > (m_XZSize/2)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if(zOffs >= (m_XZSize/2)-1) - { - if( x + random->nextInt(4) >= 15 || zOffs > (m_XZSize/2) ) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; - blockSet = true; - } - } - if( blockSet ) continue; - // End 4J Extra to build walls around the level - - if (y >= Level::genDepthMinusOne - random->nextInt(5) || y <= 0 + random->nextInt(5)) - { - blocks[offs] = (uint8_t) Tile::unbreakable_Id; + // 4J Build walls around the level + bool blockSet = false; + if (xOffs <= -(m_XZSize / 2)) { + if (z - random->nextInt(4) <= 0 || + xOffs < -(m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } } - else - { + if (zOffs <= -(m_XZSize / 2)) { + if (x - random->nextInt(4) <= 0 || + zOffs < -(m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (xOffs >= (m_XZSize / 2) - 1) { + if (z + random->nextInt(4) >= 15 || + xOffs > (m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (zOffs >= (m_XZSize / 2) - 1) { + if (x + random->nextInt(4) >= 15 || + zOffs > (m_XZSize / 2)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + blockSet = true; + } + } + if (blockSet) continue; + // End 4J Extra to build walls around the level + + if (y >= Level::genDepthMinusOne - random->nextInt(5) || + y <= 0 + random->nextInt(5)) { + blocks[offs] = (uint8_t)Tile::unbreakable_Id; + } else { int old = blocks[offs]; - if (old == 0) - { + if (old == 0) { run = -1; - } - else if (old == Tile::hellRock_Id) - { - if (run == -1) - { - if (runDepth <= 0) - { + } else if (old == Tile::hellRock_Id) { + if (run == -1) { + if (runDepth <= 0) { top = 0; - material = (uint8_t) Tile::hellRock_Id; - } - else if (y >= waterHeight - 4 && y <= waterHeight + 1) - { - top = (uint8_t) Tile::hellRock_Id; - material = (uint8_t) Tile::hellRock_Id; - if (gravel) top = (uint8_t) Tile::gravel_Id; - if (gravel) material = (uint8_t) Tile::hellRock_Id; - if (sand) - { - // 4J Stu - Make some nether wart spawn outside of the nether fortresses - if(random->nextInt(16) == 0) - { - top = (uint8_t) Tile::netherStalk_Id; - - // Place the nether wart on top of the soul sand - y += 1; - int genDepthMinusOne = Level::genDepthMinusOne; // Take into local int for PS4 as min takes a reference to the const int there and then needs the value to exist for the linker - y = std::min(y, genDepthMinusOne); - runDepth += 1; - offs = (z * 16 + x) * Level::genDepth + y; - } - else - { - top = (uint8_t) Tile::hellSand_Id; - } - } - if (sand) material = (uint8_t) Tile::hellSand_Id; + material = (uint8_t)Tile::hellRock_Id; + } else if (y >= waterHeight - 4 && + y <= waterHeight + 1) { + top = (uint8_t)Tile::hellRock_Id; + material = (uint8_t)Tile::hellRock_Id; + if (gravel) top = (uint8_t)Tile::gravel_Id; + if (gravel) + material = (uint8_t)Tile::hellRock_Id; + if (sand) { + // 4J Stu - Make some nether wart spawn + // outside of the nether fortresses + if (random->nextInt(16) == 0) { + top = (uint8_t)Tile::netherStalk_Id; + + // Place the nether wart on top of the + // soul sand + y += 1; + int genDepthMinusOne = Level:: + genDepthMinusOne; // Take into + // local int for + // PS4 as min + // takes a + // reference to + // the const int + // there and then + // needs the + // value to exist + // for the linker + y = std::min(y, genDepthMinusOne); + runDepth += 1; + offs = + (z * 16 + x) * Level::genDepth + y; + } else { + top = (uint8_t)Tile::hellSand_Id; + } + } + if (sand) material = (uint8_t)Tile::hellSand_Id; } - if (y < waterHeight && top == 0) top = (uint8_t) Tile::calmLava_Id; + if (y < waterHeight && top == 0) + top = (uint8_t)Tile::calmLava_Id; run = runDepth; - // 4J Stu - If sand, then allow adding nether wart at heights below the water level - if (y >= waterHeight - 1 || sand) blocks[offs] = top; - else blocks[offs] = material; - } - else if (run > 0) - { + // 4J Stu - If sand, then allow adding nether wart + // at heights below the water level + if (y >= waterHeight - 1 || sand) + blocks[offs] = top; + else + blocks[offs] = material; + } else if (run > 0) { run--; blocks[offs] = material; } @@ -257,79 +276,85 @@ void HellRandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks } } } - delete [] sandBuffer.data; - delete [] gravelBuffer.data; - delete [] depthBuffer.data; + delete[] sandBuffer.data; + delete[] gravelBuffer.data; + delete[] depthBuffer.data; } -LevelChunk *HellRandomLevelSource::create(int x, int z) -{ - return getChunk(x,z); +LevelChunk* HellRandomLevelSource::create(int x, int z) { + return getChunk(x, z); } -LevelChunk *HellRandomLevelSource::getChunk(int xOffs, int zOffs) -{ +LevelChunk* HellRandomLevelSource::getChunk(int xOffs, int zOffs) { random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - int blocksSize = Level::genDepth * 16 * 16; - uint8_t *tileData = (uint8_t *)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,blocksSize); - byteArray blocks = byteArray(tileData,blocksSize); -// byteArray blocks = byteArray(16 * level->depth * 16); + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + int blocksSize = Level::genDepth * 16 * 16; + uint8_t* tileData = (uint8_t*)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); + XMemSet128(tileData, 0, blocksSize); + byteArray blocks = byteArray(tileData, blocksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); prepareHeights(xOffs, zOffs, blocks); buildSurfaces(xOffs, zOffs, blocks); caveFeature->apply(this, level, xOffs, zOffs, blocks); - netherBridgeFeature->apply(this, level, xOffs, zOffs, blocks); + netherBridgeFeature->apply(this, level, xOffs, zOffs, blocks); - // 4J - this now creates compressed block data from the blocks array passed in, so needs to be after data is finalised. - // Also now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - levelChunk->setCheckAllLight(); - XPhysicalFree(tileData); + // 4J - this now creates compressed block data from the blocks array passed + // in, so needs to be after data is finalised. Also now need to free the + // passed in blocks as the LevelChunk doesn't use the passed in allocation + // anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + levelChunk->setCheckAllLight(); + XPhysicalFree(tileData); return levelChunk; } -// 4J - removed & moved into its own method from getChunk, so we can call recalcHeightmap after the chunk is added into the cache. Without -// doing this, then loads of the lightgaps() calls will fail to add any lights, because adding a light checks if the cache has this chunk in. -// lightgaps also does light 1 block into the neighbouring chunks, and maybe that is somehow enough to get lighting to propagate round the world, -// but this just doesn't seem right - this isn't a new fault in the 360 version, have checked that java does the same. -void HellRandomLevelSource::lightChunk(LevelChunk *lc) -{ - lc->recalcHeightmap(); +// 4J - removed & moved into its own method from getChunk, so we can call +// recalcHeightmap after the chunk is added into the cache. Without doing this, +// then loads of the lightgaps() calls will fail to add any lights, because +// adding a light checks if the cache has this chunk in. lightgaps also does +// light 1 block into the neighbouring chunks, and maybe that is somehow enough +// to get lighting to propagate round the world, but this just doesn't seem +// right - this isn't a new fault in the 360 version, have checked that java +// does the same. +void HellRandomLevelSource::lightChunk(LevelChunk* lc) { + lc->recalcHeightmap(); } -doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize) -{ - if (buffer.data == NULL) - { +doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, + int z, int xSize, int ySize, + int zSize) { + if (buffer.data == NULL) { buffer = doubleArray(xSize * ySize * zSize); } double s = 1 * 684.412; double hs = 1 * 684.412 * 3; - doubleArray pnr, ar, br, sr, dr, fi, fis; // 4J - used to be declared with class level scope but moved here for thread safety + doubleArray pnr, ar, br, sr, dr, fi, + fis; // 4J - used to be declared with class level scope but moved here + // for thread safety sr = scaleNoise->getRegion(sr, x, y, z, xSize, 1, zSize, 1.0, 0, 1.0); dr = depthNoise->getRegion(dr, x, y, z, xSize, 1, zSize, 100.0, 0, 100.0); - pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, hs / 60.0, s / 80.0); + pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, + hs / 60.0, s / 80.0); ar = lperlinNoise1->getRegion(ar, x, y, z, xSize, ySize, zSize, s, hs, s); br = lperlinNoise2->getRegion(br, x, y, z, xSize, ySize, zSize, s, hs, s); int p = 0; int pp = 0; doubleArray yoffs = doubleArray(ySize); - for (int yy = 0; yy < ySize; yy++) - { - yoffs[yy] = cos(yy * PI * 6 / (double) ySize) * 2; + for (int yy = 0; yy < ySize; yy++) { + yoffs[yy] = cos(yy * PI * 6 / (double)ySize) * 2; double dd = yy; - if (yy > ySize / 2) - { + if (yy > ySize / 2) { dd = (ySize - 1) - yy; } if (dd < 4) { @@ -338,10 +363,8 @@ doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, } } - for (int xx = 0; xx < xSize; xx++) - { - for (int zz = 0; zz < zSize; zz++) - { + for (int xx = 0; xx < xSize; xx++) { + for (int zz = 0; zz < zSize; zz++) { double scale = ((sr[pp] + 256.0) / 512); if (scale > 1) scale = 1; @@ -351,16 +374,13 @@ doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, if (depth < 0) depth = -depth; depth = depth * 3.0 - 3.0; - if (depth < 0) - { + if (depth < 0) { depth = depth / 2; if (depth < -1) depth = -1; depth = depth / 1.4; depth /= 2; scale = 0; - } - else - { + } else { if (depth > 1) depth = 1; depth = depth / 6; } @@ -368,8 +388,7 @@ doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, depth = depth * ySize / 16; pp++; - for (int yy = 0; yy < ySize; yy++) - { + for (int yy = 0; yy < ySize; yy++) { double val = 0; double yOffs = yoffs[yy]; @@ -378,19 +397,20 @@ doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, double cc = br[p] / 512; double v = (pnr[p] / 10 + 1) / 2; - if (v < 0) val = bb; - else if (v > 1) val = cc; - else val = bb + (cc - bb) * v; + if (v < 0) + val = bb; + else if (v > 1) + val = cc; + else + val = bb + (cc - bb) * v; val -= yOffs; - if (yy > ySize - 4) - { + if (yy > ySize - 4) { double slide = (yy - (ySize - 4)) / (4 - 1.0f); val = val * (1 - slide) + -10 * slide; } - if (yy < floating) - { + if (yy < floating) { double slide = (floating - yy) / (4); if (slide < 0) slide = 0; if (slide > 1) slide = 1; @@ -403,42 +423,42 @@ doubleArray HellRandomLevelSource::getHeights(doubleArray buffer, int x, int y, } } - delete [] pnr.data; - delete [] ar.data; - delete [] br.data; - delete [] sr.data; - delete [] dr.data; - delete [] fi.data; - delete [] fis.data; - delete [] yoffs.data; + delete[] pnr.data; + delete[] ar.data; + delete[] br.data; + delete[] sr.data; + delete[] dr.data; + delete[] fi.data; + delete[] fis.data; + delete[] yoffs.data; return buffer; } -bool HellRandomLevelSource::hasChunk(int x, int y) -{ - return true; -} +bool HellRandomLevelSource::hasChunk(int x, int y) { return true; } -void HellRandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ +void HellRandomLevelSource::postProcess(ChunkSource* parent, int xt, int zt) { HeavyTile::instaFall = true; int xo = xt * 16; int zo = zt * 16; - // 4J - added. The original java didn't do any setting of the random seed here. We'll be running our postProcess in parallel with getChunk etc. so - // we need to use a separate random - have used the same initialisation code as used in RandomLevelSource::postProcess to make sure this random value - // is consistent for each world generation. Also changed all uses of random here to pprandom. - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - // 4jcraft added casts to a higher int and unsigned - pprandom->setSeed((((uint64_t)xt * (uint64_t)xScale) + ((uint64_t)zt * (uint64_t)zScale)) ^ level->getSeed()); + // 4J - added. The original java didn't do any setting of the random seed + // here. We'll be running our postProcess in parallel with getChunk etc. so + // we need to use a separate random - have used the same initialisation code + // as used in RandomLevelSource::postProcess to make sure this random value + // is consistent for each world generation. Also changed all uses of random + // here to pprandom. + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + // 4jcraft added casts to a higher int and unsigned + pprandom->setSeed((((uint64_t)xt * (uint64_t)xScale) + + ((uint64_t)zt * (uint64_t)zScale)) ^ + level->getSeed()); - netherBridgeFeature->postProcess(level, pprandom, xt, zt); + netherBridgeFeature->postProcess(level, pprandom, xt, zt); - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth - 8) + 4; int z = zo + pprandom->nextInt(16) + 8; @@ -447,8 +467,7 @@ void HellRandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) int count = pprandom->nextInt(pprandom->nextInt(10) + 1) + 1; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth - 8) + 4; int z = zo + pprandom->nextInt(16) + 8; @@ -456,90 +475,76 @@ void HellRandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) } count = pprandom->nextInt(pprandom->nextInt(10) + 1); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth - 8) + 4; int z = zo + pprandom->nextInt(16) + 8; LightGemFeature().place(level, pprandom, x, y, z); } - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth); int z = zo + pprandom->nextInt(16) + 8; HellPortalFeature().place(level, pprandom, x, y, z); } - if (pprandom->nextInt(1) == 0) - { + if (pprandom->nextInt(1) == 0) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth); int z = zo + pprandom->nextInt(16) + 8; FlowerFeature(Tile::mushroom1_Id).place(level, pprandom, x, y, z); } - if (pprandom->nextInt(1) == 0) - { + if (pprandom->nextInt(1) == 0) { int x = xo + pprandom->nextInt(16) + 8; int y = pprandom->nextInt(Level::genDepth); int z = zo + pprandom->nextInt(16) + 8; FlowerFeature(Tile::mushroom2_Id).place(level, pprandom, x, y, z); } - OreFeature quartzFeature(Tile::netherQuartz_Id, 13, Tile::hellRock_Id); - for (int i = 0; i < 16; i++) - { - int x = xo + pprandom->nextInt(16); - int y = pprandom->nextInt(Level::genDepth - 20) + 10; - int z = zo + pprandom->nextInt(16); - quartzFeature.place(level, pprandom, x, y, z); - } + OreFeature quartzFeature(Tile::netherQuartz_Id, 13, Tile::hellRock_Id); + for (int i = 0; i < 16; i++) { + int x = xo + pprandom->nextInt(16); + int y = pprandom->nextInt(Level::genDepth - 20) + 10; + int z = zo + pprandom->nextInt(16); + quartzFeature.place(level, pprandom, x, y, z); + } HeavyTile::instaFall = false; - - app.processSchematics(parent->getChunk(xt,zt)); + app.processSchematics(parent->getChunk(xt, zt)); } -bool HellRandomLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; +bool HellRandomLevelSource::save(bool force, + ProgressListener* progressListener) { + return true; } -bool HellRandomLevelSource::tick() -{ - return false; +bool HellRandomLevelSource::tick() { return false; } + +bool HellRandomLevelSource::shouldSave() { return true; } + +std::wstring HellRandomLevelSource::gatherStats() { + return L"HellRandomLevelSource"; } -bool HellRandomLevelSource::shouldSave() -{ - return true; -} - -std::wstring HellRandomLevelSource::gatherStats() -{ - return L"HellRandomLevelSource"; -} - -std::vector *HellRandomLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ +std::vector* HellRandomLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { // check if the coordinates is within a netherbridge - if (mobCategory == MobCategory::monster && netherBridgeFeature->isInsideFeature(x, y, z)) - { + if (mobCategory == MobCategory::monster && + netherBridgeFeature->isInsideFeature(x, y, z)) { return netherBridgeFeature->getBridgeEnemies(); } - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { return NULL; } return biome->getMobs(mobCategory); } -TilePos *HellRandomLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - return NULL; +TilePos* HellRandomLevelSource::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } diff --git a/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.h b/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.h index 6a6180565..0b35b91fb 100644 --- a/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.h +++ b/Minecraft.World/WorldGen/Sources/HellRandomLevelSource.h @@ -13,34 +13,33 @@ class ProgressListener; -class HellRandomLevelSource : public ChunkSource -{ +class HellRandomLevelSource : public ChunkSource { public: - static const int CHUNK_HEIGHT = 8; + static const int CHUNK_HEIGHT = 8; static const int CHUNK_WIDTH = 4; private: - Random *random; - Random *pprandom; // 4J added + Random* random; + Random* pprandom; // 4J added - PerlinNoise *lperlinNoise1; - PerlinNoise *lperlinNoise2; - PerlinNoise *perlinNoise1; - PerlinNoise *perlinNoise2; - PerlinNoise *perlinNoise3; + PerlinNoise* lperlinNoise1; + PerlinNoise* lperlinNoise2; + PerlinNoise* perlinNoise1; + PerlinNoise* perlinNoise2; + PerlinNoise* perlinNoise3; public: - PerlinNoise *scaleNoise; - PerlinNoise *depthNoise; + PerlinNoise* scaleNoise; + PerlinNoise* depthNoise; private: - Level *level; + Level* level; public: - HellRandomLevelSource(Level *level, __int64 seed); - ~HellRandomLevelSource(); + HellRandomLevelSource(Level* level, __int64 seed); + ~HellRandomLevelSource(); - NetherBridgeFeature *netherBridgeFeature; + NetherBridgeFeature* netherBridgeFeature; private: void prepareHeights(int xOffs, int zOffs, byteArray blocks); @@ -49,24 +48,28 @@ public: void buildSurfaces(int xOffs, int zOffs, byteArray blocks); private: - LargeFeature *caveFeature; + LargeFeature* caveFeature; public: - LevelChunk *create(int x, int z); - LevelChunk *getChunk(int xOffs, int zOffs); - virtual void lightChunk(LevelChunk *lc); // 4J added + LevelChunk* create(int x, int z); + LevelChunk* getChunk(int xOffs, int zOffs); + virtual void lightChunk(LevelChunk* lc); // 4J added private: - doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize); + doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, + int ySize, int zSize); public: - bool hasChunk(int x, int y); - void postProcess(ChunkSource *parent, int xt, int zt); - bool save(bool force, ProgressListener *progressListener); + bool hasChunk(int x, int y); + void postProcess(ChunkSource* parent, int xt, int zt); + bool save(bool force, ProgressListener* progressListener); bool tick(); bool shouldSave(); std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.cpp b/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.cpp index 5e095e4e7..ea7cfb160 100644 --- a/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.cpp +++ b/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.cpp @@ -9,14 +9,14 @@ #include "../../Headers/net.minecraft.world.level.storage.h" #include "TheEndLevelRandomLevelSource.h" -TheEndLevelRandomLevelSource::TheEndLevelRandomLevelSource(Level *level, __int64 seed) -{ - m_XZSize = END_LEVEL_MIN_WIDTH; +TheEndLevelRandomLevelSource::TheEndLevelRandomLevelSource(Level* level, + __int64 seed) { + m_XZSize = END_LEVEL_MIN_WIDTH; this->level = level; random = new Random(seed); - pprandom = new Random(seed); // 4J added + pprandom = new Random(seed); // 4J added lperlinNoise1 = new PerlinNoise(random, 16); lperlinNoise2 = new PerlinNoise(random, 16); perlinNoise1 = new PerlinNoise(random, 8); @@ -25,72 +25,87 @@ TheEndLevelRandomLevelSource::TheEndLevelRandomLevelSource(Level *level, __int64 depthNoise = new PerlinNoise(random, 16); } -TheEndLevelRandomLevelSource::~TheEndLevelRandomLevelSource() -{ - delete random; - delete pprandom; - delete lperlinNoise1; - delete lperlinNoise2; - delete perlinNoise1; - delete scaleNoise; - delete depthNoise; +TheEndLevelRandomLevelSource::~TheEndLevelRandomLevelSource() { + delete random; + delete pprandom; + delete lperlinNoise1; + delete lperlinNoise2; + delete perlinNoise1; + delete scaleNoise; + delete depthNoise; } -void TheEndLevelRandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes) -{ - doubleArray buffer; // 4J - used to be declared with class level scope but tidying up for thread safety reasons +void TheEndLevelRandomLevelSource::prepareHeights(int xOffs, int zOffs, + byteArray blocks, + BiomeArray biomes) { + doubleArray buffer; // 4J - used to be declared with class level scope but + // tidying up for thread safety reasons int xChunks = 16 / CHUNK_WIDTH; int xSize = xChunks + 1; int ySize = Level::genDepth / CHUNK_HEIGHT + 1; int zSize = xChunks + 1; - buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, ySize, zSize); + buffer = getHeights(buffer, xOffs * xChunks, 0, zOffs * xChunks, xSize, + ySize, zSize); - for (int xc = 0; xc < xChunks; xc++) - { - for (int zc = 0; zc < xChunks; zc++) - { - for (int yc = 0; yc < Level::genDepth / CHUNK_HEIGHT; yc++) - { - double yStep = 1 / (double) CHUNK_HEIGHT; - double s0 = buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s1 = buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s2 = buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; - double s3 = buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; + for (int xc = 0; xc < xChunks; xc++) { + for (int zc = 0; zc < xChunks; zc++) { + for (int yc = 0; yc < Level::genDepth / CHUNK_HEIGHT; yc++) { + double yStep = 1 / (double)CHUNK_HEIGHT; + double s0 = + buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s1 = + buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 0)]; + double s2 = + buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 0)]; + double s3 = + buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 0)]; - double s0a = (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - s0) * yStep; - double s1a = (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - s1) * yStep; - double s2a = (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - s2) * yStep; - double s3a = (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - s3) * yStep; + double s0a = + (buffer[((xc + 0) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s0) * + yStep; + double s1a = + (buffer[((xc + 0) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s1) * + yStep; + double s2a = + (buffer[((xc + 1) * zSize + (zc + 0)) * ySize + (yc + 1)] - + s2) * + yStep; + double s3a = + (buffer[((xc + 1) * zSize + (zc + 1)) * ySize + (yc + 1)] - + s3) * + yStep; - for (int y = 0; y < CHUNK_HEIGHT; y++) - { - double xStep = 1 / (double) CHUNK_WIDTH; + for (int y = 0; y < CHUNK_HEIGHT; y++) { + double xStep = 1 / (double)CHUNK_WIDTH; double _s0 = s0; double _s1 = s1; double _s0a = (s2 - s0) * xStep; double _s1a = (s3 - s1) * xStep; - for (int x = 0; x < CHUNK_WIDTH; x++) - { - int offs = (x + xc * CHUNK_WIDTH) << Level::genDepthBitsPlusFour | (0 + zc * CHUNK_WIDTH) << Level::genDepthBits | (yc * CHUNK_HEIGHT + y); + for (int x = 0; x < CHUNK_WIDTH; x++) { + int offs = (x + xc * CHUNK_WIDTH) + << Level::genDepthBitsPlusFour | + (0 + zc * CHUNK_WIDTH) + << Level::genDepthBits | + (yc * CHUNK_HEIGHT + y); int step = 1 << Level::genDepthBits; - double zStep = 1 / (double) CHUNK_WIDTH; + double zStep = 1 / (double)CHUNK_WIDTH; double val = _s0; double vala = (_s1 - _s0) * zStep; - for (int z = 0; z < CHUNK_WIDTH; z++) - { + for (int z = 0; z < CHUNK_WIDTH; z++) { int tileId = 0; - if (val > 0) - { + if (val > 0) { tileId = Tile::whiteStone_Id; } else { } - blocks[offs] = (uint8_t) tileId; + blocks[offs] = (uint8_t)tileId; offs += step; val += vala; } @@ -106,48 +121,40 @@ void TheEndLevelRandomLevelSource::prepareHeights(int xOffs, int zOffs, byteArra } } } - delete [] buffer.data; - + delete[] buffer.data; } -void TheEndLevelRandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes) -{ - for (int x = 0; x < 16; x++) - { - for (int z = 0; z < 16; z++) - { +void TheEndLevelRandomLevelSource::buildSurfaces(int xOffs, int zOffs, + byteArray blocks, + BiomeArray biomes) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { int runDepth = 1; int run = -1; - uint8_t top = (uint8_t) Tile::whiteStone_Id; - uint8_t material = (uint8_t) Tile::whiteStone_Id; + uint8_t top = (uint8_t)Tile::whiteStone_Id; + uint8_t material = (uint8_t)Tile::whiteStone_Id; - for (int y = Level::genDepthMinusOne; y >= 0; y--) - { + for (int y = Level::genDepthMinusOne; y >= 0; y--) { int offs = (z * 16 + x) * Level::genDepth + y; int old = blocks[offs]; - if (old == 0) - { + if (old == 0) { run = -1; - } - else if (old == Tile::rock_Id) - { - if (run == -1) - { - if (runDepth <= 0) - { + } else if (old == Tile::rock_Id) { + if (run == -1) { + if (runDepth <= 0) { top = 0; - material = (uint8_t) Tile::whiteStone_Id; + material = (uint8_t)Tile::whiteStone_Id; } run = runDepth; - if (y >= 0) blocks[offs] = top; - else blocks[offs] = material; - } - else if (run > 0) - { + if (y >= 0) + blocks[offs] = top; + else + blocks[offs] = material; + } else if (run > 0) { run--; blocks[offs] = material; } @@ -157,75 +164,79 @@ void TheEndLevelRandomLevelSource::buildSurfaces(int xOffs, int zOffs, byteArray } } -LevelChunk *TheEndLevelRandomLevelSource::create(int x, int z) -{ - return getChunk(x, z); +LevelChunk* TheEndLevelRandomLevelSource::create(int x, int z) { + return getChunk(x, z); } -LevelChunk *TheEndLevelRandomLevelSource::getChunk(int xOffs, int zOffs) -{ +LevelChunk* TheEndLevelRandomLevelSource::getChunk(int xOffs, int zOffs) { random->setSeed(xOffs * 341873128712l + zOffs * 132897987541l); - BiomeArray biomes; - // 4J - now allocating this with a physical alloc & bypassing general memory management so that it will get cleanly freed - unsigned int blocksSize = Level::genDepth * 16 * 16; - uint8_t *tileData = (uint8_t *)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, PAGE_READWRITE); - XMemSet128(tileData,0,blocksSize); - byteArray blocks = byteArray(tileData,blocksSize); -// byteArray blocks = byteArray(16 * level->depth * 16); + BiomeArray biomes; + // 4J - now allocating this with a physical alloc & bypassing general memory + // management so that it will get cleanly freed + unsigned int blocksSize = Level::genDepth * 16 * 16; + uint8_t* tileData = (uint8_t*)XPhysicalAlloc(blocksSize, MAXULONG_PTR, 4096, + PAGE_READWRITE); + XMemSet128(tileData, 0, blocksSize); + byteArray blocks = byteArray(tileData, blocksSize); + // byteArray blocks = byteArray(16 * level->depth * 16); -// LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); // 4J moved below - level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, 16, true); + // LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + // // 4J moved below + level->getBiomeSource()->getBiomeBlock(biomes, xOffs * 16, zOffs * 16, 16, + 16, true); prepareHeights(xOffs, zOffs, blocks, biomes); buildSurfaces(xOffs, zOffs, blocks, biomes); - // 4J - this now creates compressed block data from the blocks array passed in, so moved it until after the blocks are actually finalised. We also - // now need to free the passed in blocks as the LevelChunk doesn't use the passed in allocation anymore. - LevelChunk *levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); - XPhysicalFree(tileData); + // 4J - this now creates compressed block data from the blocks array passed + // in, so moved it until after the blocks are actually finalised. We also + // now need to free the passed in blocks as the LevelChunk doesn't use the + // passed in allocation anymore. + LevelChunk* levelChunk = new LevelChunk(level, blocks, xOffs, zOffs); + XPhysicalFree(tileData); levelChunk->recalcHeightmap(); - //delete blocks.data; // Don't delete the blocks as the array data is actually owned by the chunk now - //4jcraft changed to [] - delete[] biomes.data; + // delete blocks.data; // Don't delete the blocks as the array data is + // actually owned by the chunk now 4jcraft changed to [] + delete[] biomes.data; return levelChunk; } -doubleArray TheEndLevelRandomLevelSource::getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize) -{ - if (buffer.data == NULL) - { +doubleArray TheEndLevelRandomLevelSource::getHeights(doubleArray buffer, int x, + int y, int z, int xSize, + int ySize, int zSize) { + if (buffer.data == NULL) { buffer = doubleArray(xSize * ySize * zSize); } double s = 1 * 684.412; double hs = 1 * 684.412; - doubleArray pnr, ar, br, sr, dr, fi, fis; // 4J - used to be declared with class level scope but moved here for thread safety + doubleArray pnr, ar, br, sr, dr, fi, + fis; // 4J - used to be declared with class level scope but moved here + // for thread safety sr = scaleNoise->getRegion(sr, x, z, xSize, zSize, 1.121, 1.121, 0.5); dr = depthNoise->getRegion(dr, x, z, xSize, zSize, 200.0, 200.0, 0.5); s *= 2; - pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, hs / 160.0, s / 80.0); + pnr = perlinNoise1->getRegion(pnr, x, y, z, xSize, ySize, zSize, s / 80.0, + hs / 160.0, s / 80.0); ar = lperlinNoise1->getRegion(ar, x, y, z, xSize, ySize, zSize, s, hs, s); br = lperlinNoise2->getRegion(br, x, y, z, xSize, ySize, zSize, s, hs, s); int p = 0; int pp = 0; - for (int xx = 0; xx < xSize; xx++) - { - for (int zz = 0; zz < zSize; zz++) - { + for (int xx = 0; xx < xSize; xx++) { + for (int zz = 0; zz < zSize; zz++) { double scale = ((sr[pp] + 256.0) / 512); if (scale > 1) scale = 1; - double depth = (dr[pp] / 8000.0); if (depth < 0) depth = -depth * 0.3; depth = depth * 3.0 - 2.0; @@ -247,9 +258,7 @@ doubleArray TheEndLevelRandomLevelSource::getHeights(doubleArray buffer, int x, double yCenter = ySize / 2.0; - - for (int yy = 0; yy < ySize; yy++) - { + for (int yy = 0; yy < ySize; yy++) { double val = 0; double yOffs = (yy - (yCenter)) * 8 / scale; @@ -259,100 +268,105 @@ doubleArray TheEndLevelRandomLevelSource::getHeights(doubleArray buffer, int x, double cc = br[p] / 512; double v = (pnr[p] / 10 + 1) / 2; - if (v < 0) val = bb; - else if (v > 1) val = cc; - else val = bb + (cc - bb) * v; + if (v < 0) + val = bb; + else if (v > 1) + val = cc; + else + val = bb + (cc - bb) * v; val -= 8; val += doffs; int r = 2; - if (yy > ySize / 2 - r) - { + if (yy > ySize / 2 - r) { double slide = (yy - (ySize / 2 - r)) / (64.0f); if (slide < 0) slide = 0; if (slide > 1) slide = 1; val = val * (1 - slide) + -3000 * slide; } r = 8; - if (yy < r) - { + if (yy < r) { double slide = (r - yy) / (r - 1.0f); val = val * (1 - slide) + -30 * slide; } - buffer[p] = val; p++; } } } - delete [] pnr.data; - delete [] ar.data; - delete [] br.data; - delete [] sr.data; - delete [] dr.data; - delete [] fi.data; - delete [] fis.data; + delete[] pnr.data; + delete[] ar.data; + delete[] br.data; + delete[] sr.data; + delete[] dr.data; + delete[] fi.data; + delete[] fis.data; return buffer; - } -bool TheEndLevelRandomLevelSource::hasChunk(int x, int y) -{ - return true; -} +bool TheEndLevelRandomLevelSource::hasChunk(int x, int y) { return true; } -void TheEndLevelRandomLevelSource::calcWaterDepths(ChunkSource *parent, int xt, int zt) -{ +void TheEndLevelRandomLevelSource::calcWaterDepths(ChunkSource* parent, int xt, + int zt) { int xo = xt * 16; int zo = zt * 16; - for (int x = 0; x < 16; x++) - { + for (int x = 0; x < 16; x++) { int y = level->getSeaLevel(); - for (int z = 0; z < 16; z++) - { + for (int z = 0; z < 16; z++) { int xp = xo + x + 7; int zp = zo + z + 7; int h = level->getHeightmap(xp, zp); - if (h <= 0) - { - if (level->getHeightmap(xp - 1, zp) > 0 || level->getHeightmap(xp + 1, zp) > 0 || level->getHeightmap(xp, zp - 1) > 0 || level->getHeightmap(xp, zp + 1) > 0) - { + if (h <= 0) { + if (level->getHeightmap(xp - 1, zp) > 0 || + level->getHeightmap(xp + 1, zp) > 0 || + level->getHeightmap(xp, zp - 1) > 0 || + level->getHeightmap(xp, zp + 1) > 0) { bool hadWater = false; - if (hadWater || (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && level->getData(xp - 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && level->getData(xp + 1, y, zp) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && level->getData(xp, y, zp - 1) < 7)) hadWater = true; - if (hadWater || (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && level->getData(xp, y, zp + 1) < 7)) hadWater = true; - if (hadWater) - { - for (int x2 = -5; x2 <= 5; x2++) - { - for (int z2 = -5; z2 <= 5; z2++) - { - int d = (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); + if (hadWater || + (level->getTile(xp - 1, y, zp) == Tile::calmWater_Id && + level->getData(xp - 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp + 1, y, zp) == Tile::calmWater_Id && + level->getData(xp + 1, y, zp) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp - 1) == Tile::calmWater_Id && + level->getData(xp, y, zp - 1) < 7)) + hadWater = true; + if (hadWater || + (level->getTile(xp, y, zp + 1) == Tile::calmWater_Id && + level->getData(xp, y, zp + 1) < 7)) + hadWater = true; + if (hadWater) { + for (int x2 = -5; x2 <= 5; x2++) { + for (int z2 = -5; z2 <= 5; z2++) { + int d = + (x2 > 0 ? x2 : -x2) + (z2 > 0 ? z2 : -z2); - if (d <= 5) - { + if (d <= 5) { d = 6 - d; - if (level->getTile(xp + x2, y, zp + z2) == Tile::calmWater_Id) - { - int od = level->getData(xp + x2, y, zp + z2); - if (od < 7 && od < d) - { - level->setData(xp + x2, y, zp + z2, d); + if (level->getTile(xp + x2, y, zp + z2) == + Tile::calmWater_Id) { + int od = + level->getData(xp + x2, y, zp + z2); + if (od < 7 && od < d) { + level->setData(xp + x2, y, zp + z2, + d); } } } } } - if (hadWater) - { - level->setTileAndDataNoUpdate(xp, y, zp, Tile::calmWater_Id, 7); - for (int y2 = 0; y2 < y; y2++) - { - level->setTileAndDataNoUpdate(xp, y2, zp, Tile::calmWater_Id, 8); + if (hadWater) { + level->setTileAndDataNoUpdate( + xp, y, zp, Tile::calmWater_Id, 7); + for (int y2 = 0; y2 < y; y2++) { + level->setTileAndDataNoUpdate( + xp, y2, zp, Tile::calmWater_Id, 8); } } } @@ -360,64 +374,61 @@ void TheEndLevelRandomLevelSource::calcWaterDepths(ChunkSource *parent, int xt, } } } - } -void TheEndLevelRandomLevelSource::postProcess(ChunkSource *parent, int xt, int zt) -{ +void TheEndLevelRandomLevelSource::postProcess(ChunkSource* parent, int xt, + int zt) { HeavyTile::instaFall = true; int xo = xt * 16; int zo = zt * 16; - // 4J - added. The original java didn't do any setting of the random seed here, and passes the level random to the biome decorator. - // We'll be running our postProcess in parallel with getChunk etc. so we need to use a separate random - have used the same initialisation code as - // used in RandomLevelSource::postProcess to make sure this random value is consistent for each world generation. - pprandom->setSeed(level->getSeed()); - __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; - __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; - // 4jcraft added cast to higher int and unsigned - pprandom->setSeed((((uint64_t)xt * xScale) + ((uint64_t)zt * zScale)) ^ level->getSeed()); + // 4J - added. The original java didn't do any setting of the random seed + // here, and passes the level random to the biome decorator. We'll be + // running our postProcess in parallel with getChunk etc. so we need to use + // a separate random - have used the same initialisation code as used in + // RandomLevelSource::postProcess to make sure this random value is + // consistent for each world generation. + pprandom->setSeed(level->getSeed()); + __int64 xScale = pprandom->nextLong() / 2 * 2 + 1; + __int64 zScale = pprandom->nextLong() / 2 * 2 + 1; + // 4jcraft added cast to higher int and unsigned + pprandom->setSeed((((uint64_t)xt * xScale) + ((uint64_t)zt * zScale)) ^ + level->getSeed()); - Biome *biome = level->getBiome(xo + 16, zo + 16); - biome->decorate(level, pprandom, xo, zo); // 4J - passing pprandom rather than level->random here to make this consistent with our parallel world generation + Biome* biome = level->getBiome(xo + 16, zo + 16); + biome->decorate( + level, pprandom, xo, + zo); // 4J - passing pprandom rather than level->random here to make + // this consistent with our parallel world generation HeavyTile::instaFall = false; - - app.processSchematics(parent->getChunk(xt,zt)); + + app.processSchematics(parent->getChunk(xt, zt)); } -bool TheEndLevelRandomLevelSource::save(bool force, ProgressListener *progressListener) -{ - return true; +bool TheEndLevelRandomLevelSource::save(bool force, + ProgressListener* progressListener) { + return true; } -bool TheEndLevelRandomLevelSource::tick() -{ - return false; +bool TheEndLevelRandomLevelSource::tick() { return false; } + +bool TheEndLevelRandomLevelSource::shouldSave() { return true; } + +std::wstring TheEndLevelRandomLevelSource::gatherStats() { + return L"RandomLevelSource"; } -bool TheEndLevelRandomLevelSource::shouldSave() -{ - return true; -} - -std::wstring TheEndLevelRandomLevelSource::gatherStats() -{ - return L"RandomLevelSource"; -} - -std::vector *TheEndLevelRandomLevelSource::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - Biome *biome = level->getBiome(x, z); - if (biome == NULL) - { +std::vector* TheEndLevelRandomLevelSource::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + Biome* biome = level->getBiome(x, z); + if (biome == NULL) { return NULL; } return biome->getMobs(mobCategory); } -TilePos *TheEndLevelRandomLevelSource::findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z) -{ - return NULL; +TilePos* TheEndLevelRandomLevelSource::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } - diff --git a/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.h b/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.h index 27e28cb78..4f05e5e51 100644 --- a/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.h +++ b/Minecraft.World/WorldGen/Sources/TheEndLevelRandomLevelSource.h @@ -3,58 +3,66 @@ #include "../../Level/ChunkSource.h" class PerlinNoise; -class TheEndLevelRandomLevelSource : public ChunkSource -{ +class TheEndLevelRandomLevelSource : public ChunkSource { public: static const double SNOW_CUTOFF; static const double SNOW_SCALE; static const bool FLOATING_ISLANDS; - + static const int CHUNK_HEIGHT = 4; static const int CHUNK_WIDTH = 8; -private: - Random *random; - Random *pprandom; private: - PerlinNoise *lperlinNoise1; - PerlinNoise *lperlinNoise2; - PerlinNoise *perlinNoise1; -public: - PerlinNoise *scaleNoise; - PerlinNoise *depthNoise; - PerlinNoise *forestNoise; - + Random* random; + Random* pprandom; private: - Level *level; + PerlinNoise* lperlinNoise1; + PerlinNoise* lperlinNoise2; + PerlinNoise* perlinNoise1; public: - TheEndLevelRandomLevelSource(Level *level, __int64 seed); - ~TheEndLevelRandomLevelSource(); - - void prepareHeights(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes); - void buildSurfaces(int xOffs, int zOffs, byteArray blocks, BiomeArray biomes); - -public: - virtual LevelChunk *create(int x, int z); - virtual LevelChunk *getChunk(int xOffs, int zOffs); + PerlinNoise* scaleNoise; + PerlinNoise* depthNoise; + PerlinNoise* forestNoise; private: - doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, int ySize, int zSize); + Level* level; public: - virtual bool hasChunk(int x, int y); -private: - void calcWaterDepths(ChunkSource *parent, int xt, int zt); + TheEndLevelRandomLevelSource(Level* level, __int64 seed); + ~TheEndLevelRandomLevelSource(); + + void prepareHeights(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes); + void buildSurfaces(int xOffs, int zOffs, byteArray blocks, + BiomeArray biomes); + public: - virtual void postProcess(ChunkSource *parent, int xt, int zt); - virtual bool save(bool force, ProgressListener *progressListener); + virtual LevelChunk* create(int x, int z); + virtual LevelChunk* getChunk(int xOffs, int zOffs); + +private: + doubleArray getHeights(doubleArray buffer, int x, int y, int z, int xSize, + int ySize, int zSize); + +public: + virtual bool hasChunk(int x, int y); + +private: + void calcWaterDepths(ChunkSource* parent, int xt, int zt); + +public: + virtual void postProcess(ChunkSource* parent, int xt, int zt); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); public: - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring& featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); }; diff --git a/Minecraft.World/WorldGen/Structures/MineShaftPieces.cpp b/Minecraft.World/WorldGen/Structures/MineShaftPieces.cpp index 5129db022..8ec0bf937 100644 --- a/Minecraft.World/WorldGen/Structures/MineShaftPieces.cpp +++ b/Minecraft.World/WorldGen/Structures/MineShaftPieces.cpp @@ -8,690 +8,807 @@ #include "../../Util/WeighedTreasure.h" #include "MineShaftPieces.h" -WeighedTreasureArray MineShaftPieces::smallTreasureItems;; +WeighedTreasureArray MineShaftPieces::smallTreasureItems; +; -void MineShaftPieces::staticCtor() -{ - smallTreasureItems = WeighedTreasureArray(11); - smallTreasureItems[0] = new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10); - smallTreasureItems[1] = new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5); - smallTreasureItems[2] = new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5); - smallTreasureItems[3] = new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BLUE, 4, 9, 5); - smallTreasureItems[4] = new WeighedTreasure(Item::diamond_Id, 0, 1, 2, 3); - smallTreasureItems[5] = new WeighedTreasure(Item::coal_Id, CoalItem::STONE_COAL, 3, 8, 10); - smallTreasureItems[6] = new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15); - smallTreasureItems[7] = new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 1); - smallTreasureItems[8] = new WeighedTreasure(Tile::rail_Id, 0, 4, 8, 1); - smallTreasureItems[9] = new WeighedTreasure(Item::seeds_melon_Id, 0, 2, 4, 10); - // 4J-PB - Adding from 1.2.3 - smallTreasureItems[10] = new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 2, 4, 10); +void MineShaftPieces::staticCtor() { + smallTreasureItems = WeighedTreasureArray(11); + smallTreasureItems[0] = + new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10); + smallTreasureItems[1] = new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5); + smallTreasureItems[2] = new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5); + smallTreasureItems[3] = + new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BLUE, 4, 9, 5); + smallTreasureItems[4] = new WeighedTreasure(Item::diamond_Id, 0, 1, 2, 3); + smallTreasureItems[5] = + new WeighedTreasure(Item::coal_Id, CoalItem::STONE_COAL, 3, 8, 10); + smallTreasureItems[6] = new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15); + smallTreasureItems[7] = + new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 1); + smallTreasureItems[8] = new WeighedTreasure(Tile::rail_Id, 0, 4, 8, 1); + smallTreasureItems[9] = + new WeighedTreasure(Item::seeds_melon_Id, 0, 2, 4, 10); + // 4J-PB - Adding from 1.2.3 + smallTreasureItems[10] = + new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 2, 4, 10); } -StructurePiece *MineShaftPieces::createRandomShaftPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - int randomSelection = random->nextInt(100); - if (randomSelection >= 80) - { - BoundingBox *crossingBox = MineShaftCrossing::findCrossing(pieces, random, footX, footY, footZ, direction); - if (crossingBox != NULL) - { - return new MineShaftCrossing(genDepth, random, crossingBox, direction); - } - } - else if (randomSelection >= 70) - { - BoundingBox *stairsBox = MineShaftStairs::findStairs(pieces, random, footX, footY, footZ, direction); - if (stairsBox != NULL) - { - return new MineShaftPieces::MineShaftStairs(genDepth, random, stairsBox, direction); - } - } - else - { - BoundingBox *corridorBox = MineShaftCorridor::findCorridorSize(pieces, random, footX, footY, footZ, direction); - if (corridorBox != NULL) - { - return new MineShaftCorridor(genDepth, random, corridorBox, direction); - } - } +StructurePiece* MineShaftPieces::createRandomShaftPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + int randomSelection = random->nextInt(100); + if (randomSelection >= 80) { + BoundingBox* crossingBox = MineShaftCrossing::findCrossing( + pieces, random, footX, footY, footZ, direction); + if (crossingBox != NULL) { + return new MineShaftCrossing(genDepth, random, crossingBox, + direction); + } + } else if (randomSelection >= 70) { + BoundingBox* stairsBox = MineShaftStairs::findStairs( + pieces, random, footX, footY, footZ, direction); + if (stairsBox != NULL) { + return new MineShaftPieces::MineShaftStairs(genDepth, random, + stairsBox, direction); + } + } else { + BoundingBox* corridorBox = MineShaftCorridor::findCorridorSize( + pieces, random, footX, footY, footZ, direction); + if (corridorBox != NULL) { + return new MineShaftCorridor(genDepth, random, corridorBox, + direction); + } + } - return NULL; + return NULL; } -StructurePiece *MineShaftPieces::generateAndAddPiece(StructurePiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - if (depth > MAX_DEPTH) - { - return NULL; - } - if (abs(footX - startPiece->getBoundingBox()->x0) > 5 * 16 || abs(footZ - startPiece->getBoundingBox()->z0) > 5 * 16) - { - return NULL; - } +StructurePiece* MineShaftPieces::generateAndAddPiece( + StructurePiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, int depth) { + if (depth > MAX_DEPTH) { + return NULL; + } + if (abs(footX - startPiece->getBoundingBox()->x0) > 5 * 16 || + abs(footZ - startPiece->getBoundingBox()->z0) > 5 * 16) { + return NULL; + } - StructurePiece *newPiece = createRandomShaftPiece(pieces, random, footX, footY, footZ, direction, depth + 1); - if (newPiece != NULL) - { - MemSect(50); - pieces->push_back(newPiece); - MemSect(0); - newPiece->addChildren(startPiece, pieces, random); - } - return newPiece; + StructurePiece* newPiece = createRandomShaftPiece( + pieces, random, footX, footY, footZ, direction, depth + 1); + if (newPiece != NULL) { + MemSect(50); + pieces->push_back(newPiece); + MemSect(0); + newPiece->addChildren(startPiece, pieces, random); + } + return newPiece; } - -MineShaftPieces::MineShaftRoom::MineShaftRoom(int genDepth, Random *random, int west, int north) : StructurePiece(genDepth) -{ - boundingBox = new BoundingBox(west, 50, north, west + 7 + random->nextInt(6), 54 + random->nextInt(6), north + 7 + random->nextInt(6)); +MineShaftPieces::MineShaftRoom::MineShaftRoom(int genDepth, Random* random, + int west, int north) + : StructurePiece(genDepth) { + boundingBox = new BoundingBox( + west, 50, north, west + 7 + random->nextInt(6), 54 + random->nextInt(6), + north + 7 + random->nextInt(6)); } -MineShaftPieces::MineShaftRoom::~MineShaftRoom() -{ - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) - { - delete (*it); - } +MineShaftPieces::MineShaftRoom::~MineShaftRoom() { + for (AUTO_VAR(it, childEntranceBoxes.begin()); + it != childEntranceBoxes.end(); ++it) { + delete (*it); + } } -void MineShaftPieces::MineShaftRoom::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ +void MineShaftPieces::MineShaftRoom::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + int depth = getGenDepth(); - int depth = getGenDepth(); + int pos; - int pos; + int heightSpace = boundingBox->getYSpan() - DEFAULT_SHAFT_HEIGHT - 1; + if (heightSpace <= 0) { + heightSpace = 1; + } - int heightSpace = boundingBox->getYSpan() - DEFAULT_SHAFT_HEIGHT - 1; - if (heightSpace <= 0) - { - heightSpace = 1; - } - - // northern exits - pos = 0; - while (pos < boundingBox->getXSpan()) - { - pos += random->nextInt(boundingBox->getXSpan()); - if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getXSpan()) - { - break; - } - StructurePiece *child = generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + pos, boundingBox->y0 + random->nextInt(heightSpace) + 1, boundingBox->z0 - 1, Direction::NORTH, depth); - if (child != NULL) - { - BoundingBox *childBox = child->getBoundingBox(); - childEntranceBoxes.push_back(new BoundingBox(childBox->x0, childBox->y0, boundingBox->z0, childBox->x1, childBox->y1, boundingBox->z0 + 1)); - } - pos += DEFAULT_SHAFT_WIDTH + 1; - } - // southern exits - pos = 0; - while (pos < boundingBox->getXSpan()) - { - pos += random->nextInt(boundingBox->getXSpan()); - if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getXSpan()) - { - break; - } - StructurePiece *child = generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + pos, boundingBox->y0 + random->nextInt(heightSpace) + 1, boundingBox->z1 + 1, Direction::SOUTH, depth); - if (child != NULL) - { - BoundingBox *childBox = child->getBoundingBox(); - childEntranceBoxes.push_back(new BoundingBox(childBox->x0, childBox->y0, boundingBox->z1 - 1, childBox->x1, childBox->y1, boundingBox->z1)); - } - pos += DEFAULT_SHAFT_WIDTH + 1; - } - // western exits - pos = 0; - while (pos < boundingBox->getZSpan()) - { - pos += random->nextInt(boundingBox->getZSpan()); - if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getZSpan()) - { - break; - } - StructurePiece *child = generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + random->nextInt(heightSpace) + 1, boundingBox->z0 + pos, Direction::WEST, depth); - if (child != NULL) - { - BoundingBox *childBox = child->getBoundingBox(); - childEntranceBoxes.push_back(new BoundingBox(boundingBox->x0, childBox->y0, childBox->z0, boundingBox->x0 + 1, childBox->y1, childBox->z1)); - } - pos += DEFAULT_SHAFT_WIDTH + 1; - } - // eastern exits - pos = 0; - while (pos < boundingBox->getZSpan()) - { - pos += random->nextInt(boundingBox->getZSpan()); - if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getZSpan()) - { - break; - } - StructurePiece *child = generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + random->nextInt(heightSpace) + 1, boundingBox->z0 + pos, Direction::EAST, depth); - if (child != NULL) - { - BoundingBox *childBox = child->getBoundingBox(); - childEntranceBoxes.push_back(new BoundingBox(boundingBox->x1 - 1, childBox->y0, childBox->z0, boundingBox->x1, childBox->y1, childBox->z1)); - } - pos += DEFAULT_SHAFT_WIDTH + 1; - } + // northern exits + pos = 0; + while (pos < boundingBox->getXSpan()) { + pos += random->nextInt(boundingBox->getXSpan()); + if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getXSpan()) { + break; + } + StructurePiece* child = generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + pos, + boundingBox->y0 + random->nextInt(heightSpace) + 1, + boundingBox->z0 - 1, Direction::NORTH, depth); + if (child != NULL) { + BoundingBox* childBox = child->getBoundingBox(); + childEntranceBoxes.push_back(new BoundingBox( + childBox->x0, childBox->y0, boundingBox->z0, childBox->x1, + childBox->y1, boundingBox->z0 + 1)); + } + pos += DEFAULT_SHAFT_WIDTH + 1; + } + // southern exits + pos = 0; + while (pos < boundingBox->getXSpan()) { + pos += random->nextInt(boundingBox->getXSpan()); + if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getXSpan()) { + break; + } + StructurePiece* child = generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + pos, + boundingBox->y0 + random->nextInt(heightSpace) + 1, + boundingBox->z1 + 1, Direction::SOUTH, depth); + if (child != NULL) { + BoundingBox* childBox = child->getBoundingBox(); + childEntranceBoxes.push_back( + new BoundingBox(childBox->x0, childBox->y0, boundingBox->z1 - 1, + childBox->x1, childBox->y1, boundingBox->z1)); + } + pos += DEFAULT_SHAFT_WIDTH + 1; + } + // western exits + pos = 0; + while (pos < boundingBox->getZSpan()) { + pos += random->nextInt(boundingBox->getZSpan()); + if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getZSpan()) { + break; + } + StructurePiece* child = generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + random->nextInt(heightSpace) + 1, + boundingBox->z0 + pos, Direction::WEST, depth); + if (child != NULL) { + BoundingBox* childBox = child->getBoundingBox(); + childEntranceBoxes.push_back(new BoundingBox( + boundingBox->x0, childBox->y0, childBox->z0, + boundingBox->x0 + 1, childBox->y1, childBox->z1)); + } + pos += DEFAULT_SHAFT_WIDTH + 1; + } + // eastern exits + pos = 0; + while (pos < boundingBox->getZSpan()) { + pos += random->nextInt(boundingBox->getZSpan()); + if ((pos + DEFAULT_SHAFT_WIDTH) > boundingBox->getZSpan()) { + break; + } + StructurePiece* child = generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + random->nextInt(heightSpace) + 1, + boundingBox->z0 + pos, Direction::EAST, depth); + if (child != NULL) { + BoundingBox* childBox = child->getBoundingBox(); + childEntranceBoxes.push_back( + new BoundingBox(boundingBox->x1 - 1, childBox->y0, childBox->z0, + boundingBox->x1, childBox->y1, childBox->z1)); + } + pos += DEFAULT_SHAFT_WIDTH + 1; + } } -bool MineShaftPieces::MineShaftRoom::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { - return false; - } +bool MineShaftPieces::MineShaftRoom::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { + return false; + } - // floor - generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, boundingBox->z0, boundingBox->x1, boundingBox->y0, boundingBox->z1, Tile::dirt_Id, 0, true); + // floor + generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, + boundingBox->z0, boundingBox->x1, boundingBox->y0, + boundingBox->z1, Tile::dirt_Id, 0, true); - // room air - generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0 + 1, boundingBox->z0, boundingBox->x1, std::min(boundingBox->y0 + 3, boundingBox->y1), boundingBox->z1, 0, 0, false); - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) - { - BoundingBox *entranceBox = *it; - generateBox(level, chunkBB, entranceBox->x0, entranceBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), entranceBox->z0, entranceBox->x1, entranceBox->y1, entranceBox->z1, 0, 0, false); - } - generateUpperHalfSphere(level, chunkBB, boundingBox->x0, boundingBox->y0 + 4, boundingBox->z0, boundingBox->x1, boundingBox->y1, boundingBox->z1, 0, false); + // room air + generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0 + 1, + boundingBox->z0, boundingBox->x1, + std::min(boundingBox->y0 + 3, boundingBox->y1), boundingBox->z1, + 0, 0, false); + for (AUTO_VAR(it, childEntranceBoxes.begin()); + it != childEntranceBoxes.end(); ++it) { + BoundingBox* entranceBox = *it; + generateBox(level, chunkBB, entranceBox->x0, + entranceBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), + entranceBox->z0, entranceBox->x1, entranceBox->y1, + entranceBox->z1, 0, 0, false); + } + generateUpperHalfSphere( + level, chunkBB, boundingBox->x0, boundingBox->y0 + 4, boundingBox->z0, + boundingBox->x1, boundingBox->y1, boundingBox->z1, 0, false); - return true; + return true; } +MineShaftPieces::MineShaftCorridor::MineShaftCorridor(int genDepth, + Random* random, + BoundingBox* corridorBox, + int direction) + : StructurePiece(genDepth) { + orientation = direction; + boundingBox = corridorBox; + hasRails = random->nextInt(3) == 0; + hasPlacedSpider = false; + spiderCorridor = !hasRails && random->nextInt(23) == 0; + // debug + // spiderCorridor = !hasRails ;//&& random->nextInt(23) == 0; -MineShaftPieces::MineShaftCorridor::MineShaftCorridor(int genDepth, Random *random, BoundingBox *corridorBox, int direction) - : StructurePiece(genDepth) -{ - orientation = direction; - boundingBox = corridorBox; - hasRails = random->nextInt(3) == 0; - hasPlacedSpider=false; - spiderCorridor = !hasRails && random->nextInt(23) == 0; - //debug - //spiderCorridor = !hasRails ;//&& random->nextInt(23) == 0; - - if (orientation == Direction::NORTH || orientation == Direction::SOUTH) - { - numSections = corridorBox->getZSpan() / DEFAULT_SHAFT_LENGTH; - } - else - { - numSections = corridorBox->getXSpan() / DEFAULT_SHAFT_LENGTH; - } + if (orientation == Direction::NORTH || orientation == Direction::SOUTH) { + numSections = corridorBox->getZSpan() / DEFAULT_SHAFT_LENGTH; + } else { + numSections = corridorBox->getXSpan() / DEFAULT_SHAFT_LENGTH; + } } -BoundingBox *MineShaftPieces::MineShaftCorridor::findCorridorSize(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ +BoundingBox* MineShaftPieces::MineShaftCorridor::findCorridorSize( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction) { + BoundingBox* box = new BoundingBox( + footX, footY, footZ, footX, footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); - BoundingBox *box = new BoundingBox(footX, footY, footZ, footX, footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); + int corridorLength = random->nextInt(3) + 2; + while (corridorLength > 0) { + int blockLength = corridorLength * DEFAULT_SHAFT_LENGTH; - int corridorLength = random->nextInt(3) + 2; - while (corridorLength > 0) - { - int blockLength = corridorLength * DEFAULT_SHAFT_LENGTH; + switch (direction) { + case Direction::NORTH: + box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); + box->z0 = footZ - (blockLength - 1); + break; + case Direction::SOUTH: + box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); + box->z1 = footZ + (blockLength - 1); + break; + case Direction::WEST: + box->x0 = footX - (blockLength - 1); + box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); + break; + case Direction::EAST: + box->x1 = footX + (blockLength - 1); + box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); + break; + } - switch (direction) - { - case Direction::NORTH: - box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); - box->z0 = footZ - (blockLength - 1); - break; - case Direction::SOUTH: - box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); - box->z1 = footZ + (blockLength - 1); - break; - case Direction::WEST: - box->x0 = footX - (blockLength - 1); - box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); - break; - case Direction::EAST: - box->x1 = footX + (blockLength - 1); - box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); - break; - } + if (StructurePiece::findCollisionPiece(pieces, box) != NULL) { + corridorLength--; + } else { + break; + } + } - if (StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - corridorLength--; - } - else - { - break; - } - } - - if (corridorLength > 0) - { - return box; - } - delete box; - // unable to place corridor here - return NULL; + if (corridorLength > 0) { + return box; + } + delete box; + // unable to place corridor here + return NULL; } -void MineShaftPieces::MineShaftCorridor::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - int depth = getGenDepth(); - int endSelection = random->nextInt(4); - switch (orientation) - { - case Direction::NORTH: - if (endSelection <= 1) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0 - 1, orientation, depth); - } - else if (endSelection == 2) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0, Direction::WEST, depth); - } - else - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0, Direction::EAST, depth); - } - break; - case Direction::SOUTH: - if (endSelection <= 1) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z1 + 1, orientation, depth); - } - else if (endSelection == 2) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z1 - DEFAULT_SHAFT_WIDTH, Direction::WEST, depth); - } - else - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z1 - DEFAULT_SHAFT_WIDTH, Direction::EAST, depth); - } - break; - case Direction::WEST: - if (endSelection <= 1) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0, orientation, depth); - } - else if (endSelection == 2) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0 - 1, Direction::NORTH, depth); - } - else - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z1 + 1, Direction::SOUTH, depth); - } - break; - case Direction::EAST: - if (endSelection <= 1) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0, orientation, depth); - } - else if (endSelection == 2) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 - DEFAULT_SHAFT_WIDTH, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z0 - 1, Direction::NORTH, depth); - } - else - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 - DEFAULT_SHAFT_WIDTH, boundingBox->y0 - 1 + random->nextInt(3), boundingBox->z1 + 1, Direction::SOUTH, depth); - } - break; - } +void MineShaftPieces::MineShaftCorridor::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + int depth = getGenDepth(); + int endSelection = random->nextInt(4); + switch (orientation) { + case Direction::NORTH: + if (endSelection <= 1) { + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0 - 1, orientation, depth); + } else if (endSelection == 2) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x0 - 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0, Direction::WEST, depth); + } else { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 + 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0, Direction::EAST, depth); + } + break; + case Direction::SOUTH: + if (endSelection <= 1) { + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z1 + 1, orientation, depth); + } else if (endSelection == 2) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x0 - 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z1 - DEFAULT_SHAFT_WIDTH, + Direction::WEST, depth); + } else { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 + 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z1 - DEFAULT_SHAFT_WIDTH, + Direction::EAST, depth); + } + break; + case Direction::WEST: + if (endSelection <= 1) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x0 - 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0, orientation, depth); + } else if (endSelection == 2) { + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0 - 1, Direction::NORTH, + depth); + } else { + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z1 + 1, Direction::SOUTH, + depth); + } + break; + case Direction::EAST: + if (endSelection <= 1) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 + 1, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0, orientation, depth); + } else if (endSelection == 2) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 - DEFAULT_SHAFT_WIDTH, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z0 - 1, Direction::NORTH, + depth); + } else { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 - DEFAULT_SHAFT_WIDTH, + boundingBox->y0 - 1 + random->nextInt(3), + boundingBox->z1 + 1, Direction::SOUTH, + depth); + } + break; + } - // generate cross sections using higher depth - if (depth < MAX_DEPTH) - { - if (orientation == Direction::NORTH || orientation == Direction::SOUTH) - { - for (int z = boundingBox->z0 + 3; (z + DEFAULT_SHAFT_WIDTH) <= boundingBox->z1; z += DEFAULT_SHAFT_LENGTH) - { - int selection = random->nextInt(5); - if (selection == 0) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, z, Direction::WEST, depth + 1); - } - else if (selection == 1) - { - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, z, Direction::EAST, depth + 1); - } - } - } - else - { - for (int x = boundingBox->x0 + 3; (x + DEFAULT_SHAFT_WIDTH) <= boundingBox->x1; x += DEFAULT_SHAFT_LENGTH) - { - int selection = random->nextInt(5); - if (selection == 0) - { - generateAndAddPiece(startPiece, pieces, random, x, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, depth + 1); - } - else if (selection == 1) - { - generateAndAddPiece(startPiece, pieces, random, x, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, depth + 1); - } - } - } - } + // generate cross sections using higher depth + if (depth < MAX_DEPTH) { + if (orientation == Direction::NORTH || + orientation == Direction::SOUTH) { + for (int z = boundingBox->z0 + 3; + (z + DEFAULT_SHAFT_WIDTH) <= boundingBox->z1; + z += DEFAULT_SHAFT_LENGTH) { + int selection = random->nextInt(5); + if (selection == 0) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x0 - 1, boundingBox->y0, z, + Direction::WEST, depth + 1); + } else if (selection == 1) { + generateAndAddPiece(startPiece, pieces, random, + boundingBox->x1 + 1, boundingBox->y0, z, + Direction::EAST, depth + 1); + } + } + } else { + for (int x = boundingBox->x0 + 3; + (x + DEFAULT_SHAFT_WIDTH) <= boundingBox->x1; + x += DEFAULT_SHAFT_LENGTH) { + int selection = random->nextInt(5); + if (selection == 0) { + generateAndAddPiece(startPiece, pieces, random, x, + boundingBox->y0, boundingBox->z0 - 1, + Direction::NORTH, depth + 1); + } else if (selection == 1) { + generateAndAddPiece(startPiece, pieces, random, x, + boundingBox->y0, boundingBox->z1 + 1, + Direction::SOUTH, depth + 1); + } + } + } + } } -bool MineShaftPieces::MineShaftCorridor::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { - return false; - } +bool MineShaftPieces::MineShaftCorridor::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { + return false; + } - const int x0 = 0; - const int x1 = DEFAULT_SHAFT_WIDTH - 1; - const int y0 = 0; - const int y1 = DEFAULT_SHAFT_HEIGHT - 1; - const int length = (numSections * DEFAULT_SHAFT_LENGTH) - 1; + const int x0 = 0; + const int x1 = DEFAULT_SHAFT_WIDTH - 1; + const int y0 = 0; + const int y1 = DEFAULT_SHAFT_HEIGHT - 1; + const int length = (numSections * DEFAULT_SHAFT_LENGTH) - 1; - // corridor air - generateBox(level, chunkBB, x0, 0, y0, x1, y1 - 1, length, 0, 0, false); - generateMaybeBox(level, chunkBB, random, .8f, x0, y1, y0, x1, y1, length, 0, 0, false); + // corridor air + generateBox(level, chunkBB, x0, 0, y0, x1, y1 - 1, length, 0, 0, false); + generateMaybeBox(level, chunkBB, random, .8f, x0, y1, y0, x1, y1, length, 0, + 0, false); - if (spiderCorridor) - { - generateMaybeBox(level, chunkBB, random, .6f, x0, 0, y0, x1, y1 - 1, length, Tile::web_Id, 0, false); - } + if (spiderCorridor) { + generateMaybeBox(level, chunkBB, random, .6f, x0, 0, y0, x1, y1 - 1, + length, Tile::web_Id, 0, false); + } - // place a support in every section - for (int section = 0; section < numSections; section++) - { + // place a support in every section + for (int section = 0; section < numSections; section++) { + int z = 2 + section * DEFAULT_SHAFT_LENGTH; - int z = 2 + section * DEFAULT_SHAFT_LENGTH; + // 4J-PB - Bringing forward the changes in 1.2.3 + generateBox(level, chunkBB, x0, y0, z, x0, y1 - 1, z, Tile::fence_Id, 0, + false); + generateBox(level, chunkBB, x1, y0, z, x1, y1 - 1, z, Tile::fence_Id, 0, + false); + if (random->nextInt(4) == 0) { + generateBox(level, chunkBB, x0, y1, z, x0, y1, z, Tile::wood_Id, 0, + false); + generateBox(level, chunkBB, x1, y1, z, x1, y1, z, Tile::wood_Id, 0, + false); + } else { + generateBox(level, chunkBB, x0, y1, z, x1, y1, z, Tile::wood_Id, 0, + false); + } + maybeGenerateBlock(level, chunkBB, random, .1f, x0, y1, z - 1, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .1f, x1, y1, z - 1, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .1f, x0, y1, z + 1, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .1f, x1, y1, z + 1, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x0, y1, z - 2, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x1, y1, z - 2, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x0, y1, z + 2, + Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x1, y1, z + 2, + Tile::web_Id, 0); - // 4J-PB - Bringing forward the changes in 1.2.3 - generateBox(level, chunkBB, x0, y0, z, x0, y1 - 1, z, Tile::fence_Id, 0, false); - generateBox(level, chunkBB, x1, y0, z, x1, y1 - 1, z, Tile::fence_Id, 0, false); - if (random->nextInt(4) == 0) - { - generateBox(level, chunkBB, x0, y1, z, x0, y1, z, Tile::wood_Id, 0, false); - generateBox(level, chunkBB, x1, y1, z, x1, y1, z, Tile::wood_Id, 0, false); - } - else - { - generateBox(level, chunkBB, x0, y1, z, x1, y1, z, Tile::wood_Id, 0, false); - } - maybeGenerateBlock(level, chunkBB, random, .1f, x0, y1, z - 1, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .1f, x1, y1, z - 1, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .1f, x0, y1, z + 1, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .1f, x1, y1, z + 1, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x0, y1, z - 2, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x1, y1, z - 2, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x0, y1, z + 2, Tile::web_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x1, y1, z + 2, Tile::web_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x0 + 1, y1, z - 1, + Tile::torch_Id, 0); + maybeGenerateBlock(level, chunkBB, random, .05f, x0 + 1, y1, z + 1, + Tile::torch_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x0 + 1, y1, z - 1, Tile::torch_Id, 0); - maybeGenerateBlock(level, chunkBB, random, .05f, x0 + 1, y1, z + 1, Tile::torch_Id, 0); + if (random->nextInt(100) == 0) { + createChest( + level, chunkBB, random, x1, y0, z - 1, + WeighedTreasure::addToTreasure( + smallTreasureItems, + Item::enchantedBook->createForRandomTreasure(random)), + 3 + random->nextInt(4)); + } + if (random->nextInt(100) == 0) { + createChest( + level, chunkBB, random, x0, y0, z + 1, + WeighedTreasure::addToTreasure( + smallTreasureItems, + Item::enchantedBook->createForRandomTreasure(random)), + 3 + random->nextInt(4)); + } - if (random->nextInt(100) == 0) - { - createChest(level, chunkBB, random, x1, y0, z - 1, WeighedTreasure::addToTreasure(smallTreasureItems, Item::enchantedBook->createForRandomTreasure(random)), 3 + random->nextInt(4)); - } - if (random->nextInt(100) == 0) - { - createChest(level, chunkBB, random, x0, y0, z + 1, WeighedTreasure::addToTreasure(smallTreasureItems, Item::enchantedBook->createForRandomTreasure(random)), 3 + random->nextInt(4)); - } + if (spiderCorridor && !hasPlacedSpider) { + int y = getWorldY(y0), newZ = z - 1 + random->nextInt(3); + int x = getWorldX(x0 + 1, newZ); + newZ = getWorldZ(x0 + 1, newZ); + if (chunkBB->isInside(x, y, newZ)) { + hasPlacedSpider = true; + level->setTile(x, y, newZ, Tile::mobSpawner_Id); + std::shared_ptr entity = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, newZ)); + if (entity != NULL) entity->setEntityId(L"CaveSpider"); + } + } + } - if (spiderCorridor && !hasPlacedSpider) - { - int y = getWorldY(y0), newZ = z - 1 + random->nextInt(3); - int x = getWorldX(x0 + 1, newZ); - newZ = getWorldZ(x0 + 1, newZ); - if (chunkBB->isInside(x, y, newZ)) - { - hasPlacedSpider = true; - level->setTile(x, y, newZ, Tile::mobSpawner_Id); - std::shared_ptr entity = std::dynamic_pointer_cast( level->getTileEntity(x, y, newZ) ); - if (entity != NULL) entity->setEntityId(L"CaveSpider"); - } - } - } + // prevent air floating + for (int x = x0; x <= x1; x++) { + for (int z = 0; z <= length; z++) { + int block = getBlock(level, x, -1, z, chunkBB); + if (block == 0) { + placeBlock(level, Tile::wood_Id, 0, x, -1, z, chunkBB); + } + } + } - // prevent air floating - for (int x = x0; x <= x1; x++) - { - for (int z = 0; z <= length; z++) - { - int block = getBlock(level, x, -1, z, chunkBB); - if (block == 0) - { - placeBlock(level, Tile::wood_Id, 0, x, -1, z, chunkBB); - } - } - } + if (hasRails) { + for (int z = 0; z <= length; z++) { + int floor = getBlock(level, x0 + 1, y0 - 1, z, chunkBB); + if (floor > 0 && Tile::solid[floor]) { + maybeGenerateBlock( + level, chunkBB, random, .7f, x0 + 1, y0, z, Tile::rail_Id, + getOrientationData(Tile::rail_Id, RailTile::DIR_FLAT_Z)); + } + } + } - if (hasRails) - { - for (int z = 0; z <= length; z++) - { - int floor = getBlock(level, x0 + 1, y0 - 1, z, chunkBB); - if (floor > 0 && Tile::solid[floor]) - { - maybeGenerateBlock(level, chunkBB, random, .7f, x0 + 1, y0, z, Tile::rail_Id, getOrientationData(Tile::rail_Id, RailTile::DIR_FLAT_Z)); - } - } - } - - return true; + return true; } -MineShaftPieces::MineShaftCrossing::MineShaftCrossing(int genDepth, Random *random, BoundingBox *crossingBox, int direction) - : StructurePiece(genDepth), direction(direction), isTwoFloored( crossingBox->getYSpan() > DEFAULT_SHAFT_HEIGHT ) -{ - boundingBox = crossingBox; +MineShaftPieces::MineShaftCrossing::MineShaftCrossing(int genDepth, + Random* random, + BoundingBox* crossingBox, + int direction) + : StructurePiece(genDepth), + direction(direction), + isTwoFloored(crossingBox->getYSpan() > DEFAULT_SHAFT_HEIGHT) { + boundingBox = crossingBox; } -BoundingBox *MineShaftPieces::MineShaftCrossing::findCrossing(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ +BoundingBox* MineShaftPieces::MineShaftCrossing::findCrossing( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction) { + BoundingBox* box = new BoundingBox( + footX, footY, footZ, footX, footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); - BoundingBox *box = new BoundingBox(footX, footY, footZ, footX, footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); + if (random->nextInt(4) == 0) { + box->y1 += DEFAULT_SHAFT_HEIGHT + 1; // two-floored + } - if (random->nextInt(4) == 0) - { - box->y1 += DEFAULT_SHAFT_HEIGHT + 1; // two-floored - } + switch (direction) { + case Direction::NORTH: + box->x0 = footX - 1; + box->x1 = footX + DEFAULT_SHAFT_WIDTH; + box->z0 = footZ - (DEFAULT_SHAFT_WIDTH + 1); + break; + case Direction::SOUTH: + box->x0 = footX - 1; + box->x1 = footX + DEFAULT_SHAFT_WIDTH; + box->z1 = footZ + (DEFAULT_SHAFT_WIDTH + 1); + break; + case Direction::WEST: + box->x0 = footX - (DEFAULT_SHAFT_WIDTH + 1); + box->z0 = footZ - 1; + box->z1 = footZ + DEFAULT_SHAFT_WIDTH; + break; + case Direction::EAST: + box->x1 = footX + (DEFAULT_SHAFT_WIDTH + 1); + box->z0 = footZ - 1; + box->z1 = footZ + DEFAULT_SHAFT_WIDTH; + break; + } - switch (direction) - { - case Direction::NORTH: - box->x0 = footX - 1; - box->x1 = footX + DEFAULT_SHAFT_WIDTH; - box->z0 = footZ - (DEFAULT_SHAFT_WIDTH + 1); - break; - case Direction::SOUTH: - box->x0 = footX - 1; - box->x1 = footX + DEFAULT_SHAFT_WIDTH; - box->z1 = footZ + (DEFAULT_SHAFT_WIDTH + 1); - break; - case Direction::WEST: - box->x0 = footX - (DEFAULT_SHAFT_WIDTH + 1); - box->z0 = footZ - 1; - box->z1 = footZ + DEFAULT_SHAFT_WIDTH; - break; - case Direction::EAST: - box->x1 = footX + (DEFAULT_SHAFT_WIDTH + 1); - box->z0 = footZ - 1; - box->z1 = footZ + DEFAULT_SHAFT_WIDTH; - break; - } + if (StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - if (StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return box; + return box; } -void MineShaftPieces::MineShaftCrossing::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ +void MineShaftPieces::MineShaftCrossing::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + int depth = getGenDepth(); + // crossings are coming from a direction and will generate children + // in the + // remaining three directions + switch (direction) { + case Direction::NORTH: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z0 - 1, + Direction::NORTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::WEST, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::EAST, depth); + break; + case Direction::SOUTH: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z1 + 1, + Direction::SOUTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::WEST, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::EAST, depth); + break; + case Direction::WEST: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z0 - 1, + Direction::NORTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z1 + 1, + Direction::SOUTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::WEST, depth); + break; + case Direction::EAST: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z0 - 1, + Direction::NORTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0, boundingBox->z1 + 1, + Direction::SOUTH, depth); + generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0, boundingBox->z0 + 1, + Direction::EAST, depth); + break; + } - int depth = getGenDepth(); - // crossings are coming from a direction and will generate children - // in the - // remaining three directions - switch (direction) - { - case Direction::NORTH: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z0 + 1, Direction::WEST, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0 + 1, Direction::EAST, depth); - break; - case Direction::SOUTH: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z0 + 1, Direction::WEST, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0 + 1, Direction::EAST, depth); - break; - case Direction::WEST: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z0 + 1, Direction::WEST, depth); - break; - case Direction::EAST: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, depth); - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0 + 1, Direction::EAST, depth); - break; - } - - if (isTwoFloored) - { - if (random->nextBoolean()) generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, boundingBox->z0 - 1, Direction::NORTH, depth); - if (random->nextBoolean()) generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, boundingBox->z0 + 1, Direction::WEST, depth); - if (random->nextBoolean()) generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, boundingBox->z0 + 1, Direction::EAST, depth); - if (random->nextBoolean()) generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, boundingBox->z1 + 1, Direction::SOUTH, depth); - } + if (isTwoFloored) { + if (random->nextBoolean()) + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, + boundingBox->z0 - 1, Direction::NORTH, depth); + if (random->nextBoolean()) + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, + boundingBox->z0 + 1, Direction::WEST, depth); + if (random->nextBoolean()) + generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, + boundingBox->z0 + 1, Direction::EAST, depth); + if (random->nextBoolean()) + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT + 1, + boundingBox->z1 + 1, Direction::SOUTH, depth); + } } -bool MineShaftPieces::MineShaftCrossing::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { - return false; - } +bool MineShaftPieces::MineShaftCrossing::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { + return false; + } - // corridor air - if (isTwoFloored) - { - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0, boundingBox->x1 - 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT - 1, boundingBox->z1, 0, 0, false); - generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, boundingBox->z0 + 1, boundingBox->x1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT - 1, boundingBox->z1 - 1, 0, 0, false); - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), boundingBox->z0, boundingBox->x1 - 1, boundingBox->y1, boundingBox->z1, 0, 0, false); - generateBox(level, chunkBB, boundingBox->x0, boundingBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), boundingBox->z0 + 1, boundingBox->x1, boundingBox->y1, boundingBox->z1 - 1, 0, 0, false); - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT, boundingBox->z0 + 1, boundingBox->x1 - 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT, boundingBox->z1 - 1, 0, 0, false); - } - else - { - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0, boundingBox->x1 - 1, boundingBox->y1, boundingBox->z1, 0, 0, false); - generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, boundingBox->z0 + 1, boundingBox->x1, boundingBox->y1, boundingBox->z1 - 1, 0, 0, false); - } + // corridor air + if (isTwoFloored) { + generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, + boundingBox->z0, boundingBox->x1 - 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT - 1, boundingBox->z1, + 0, 0, false); + generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, + boundingBox->z0 + 1, boundingBox->x1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT - 1, + boundingBox->z1 - 1, 0, 0, false); + generateBox(level, chunkBB, boundingBox->x0 + 1, + boundingBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), + boundingBox->z0, boundingBox->x1 - 1, boundingBox->y1, + boundingBox->z1, 0, 0, false); + generateBox(level, chunkBB, boundingBox->x0, + boundingBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), + boundingBox->z0 + 1, boundingBox->x1, boundingBox->y1, + boundingBox->z1 - 1, 0, 0, false); + generateBox(level, chunkBB, boundingBox->x0 + 1, + boundingBox->y0 + DEFAULT_SHAFT_HEIGHT, boundingBox->z0 + 1, + boundingBox->x1 - 1, boundingBox->y0 + DEFAULT_SHAFT_HEIGHT, + boundingBox->z1 - 1, 0, 0, false); + } else { + generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, + boundingBox->z0, boundingBox->x1 - 1, boundingBox->y1, + boundingBox->z1, 0, 0, false); + generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0, + boundingBox->z0 + 1, boundingBox->x1, boundingBox->y1, + boundingBox->z1 - 1, 0, 0, false); + } - // support pillars - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z0 + 1, boundingBox->x0 + 1, boundingBox->y1, boundingBox->z0 + 1, Tile::wood_Id, 0, false); - generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, boundingBox->z1 - 1, boundingBox->x0 + 1, boundingBox->y1, boundingBox->z1 - 1, Tile::wood_Id, 0, false); - generateBox(level, chunkBB, boundingBox->x1 - 1, boundingBox->y0, boundingBox->z0 + 1, boundingBox->x1 - 1, boundingBox->y1, boundingBox->z0 + 1, Tile::wood_Id, 0, false); - generateBox(level, chunkBB, boundingBox->x1 - 1, boundingBox->y0, boundingBox->z1 - 1, boundingBox->x1 - 1, boundingBox->y1, boundingBox->z1 - 1, Tile::wood_Id, 0, false); + // support pillars + generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, + boundingBox->z0 + 1, boundingBox->x0 + 1, boundingBox->y1, + boundingBox->z0 + 1, Tile::wood_Id, 0, false); + generateBox(level, chunkBB, boundingBox->x0 + 1, boundingBox->y0, + boundingBox->z1 - 1, boundingBox->x0 + 1, boundingBox->y1, + boundingBox->z1 - 1, Tile::wood_Id, 0, false); + generateBox(level, chunkBB, boundingBox->x1 - 1, boundingBox->y0, + boundingBox->z0 + 1, boundingBox->x1 - 1, boundingBox->y1, + boundingBox->z0 + 1, Tile::wood_Id, 0, false); + generateBox(level, chunkBB, boundingBox->x1 - 1, boundingBox->y0, + boundingBox->z1 - 1, boundingBox->x1 - 1, boundingBox->y1, + boundingBox->z1 - 1, Tile::wood_Id, 0, false); - // prevent air floating - // note: use world coordinates because the corridor hasn't defined - // orientation - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) - { - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) - { - int block = getBlock(level, x, boundingBox->y0 - 1, z, chunkBB); - if (block == 0) - { - placeBlock(level, Tile::wood_Id, 0, x, boundingBox->y0 - 1, z, chunkBB); - } - } - } + // prevent air floating + // note: use world coordinates because the corridor hasn't defined + // orientation + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { + int block = getBlock(level, x, boundingBox->y0 - 1, z, chunkBB); + if (block == 0) { + placeBlock(level, Tile::wood_Id, 0, x, boundingBox->y0 - 1, z, + chunkBB); + } + } + } - return true; + return true; } - -MineShaftPieces::MineShaftStairs::MineShaftStairs(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StructurePiece(genDepth) -{ - this->orientation = direction; - boundingBox = stairsBox; +MineShaftPieces::MineShaftStairs::MineShaftStairs(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : StructurePiece(genDepth) { + this->orientation = direction; + boundingBox = stairsBox; } -BoundingBox *MineShaftPieces::MineShaftStairs::findStairs(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ - // stairs are two steps in, 5x5 steps down, two steps out +BoundingBox* MineShaftPieces::MineShaftStairs::findStairs( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction) { + // stairs are two steps in, 5x5 steps down, two steps out - BoundingBox *box = new BoundingBox(footX, footY - 5, footZ, footX, footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); + BoundingBox* box = + new BoundingBox(footX, footY - 5, footZ, footX, + footY + (DEFAULT_SHAFT_HEIGHT - 1), footZ); - switch (direction) - { - case Direction::NORTH: - box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); - box->z0 = footZ - 8; - break; - case Direction::SOUTH: - box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); - box->z1 = footZ + 8; - break; - case Direction::WEST: - box->x0 = footX - 8; - box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); - break; - case Direction::EAST: - box->x1 = footX + 8; - box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); - break; - } + switch (direction) { + case Direction::NORTH: + box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); + box->z0 = footZ - 8; + break; + case Direction::SOUTH: + box->x1 = footX + (DEFAULT_SHAFT_WIDTH - 1); + box->z1 = footZ + 8; + break; + case Direction::WEST: + box->x0 = footX - 8; + box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); + break; + case Direction::EAST: + box->x1 = footX + 8; + box->z1 = footZ + (DEFAULT_SHAFT_WIDTH - 1); + break; + } - if (StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return box; + return box; } -void MineShaftPieces::MineShaftStairs::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - int depth = getGenDepth(); - // crossings are coming from a direction and will generate children - // in the - // remaining three directions - switch (orientation) - { - case Direction::NORTH: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, depth); - break; - case Direction::SOUTH: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, depth); - break; - case Direction::WEST: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z0, Direction::WEST, depth); - break; - case Direction::EAST: - generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0, Direction::EAST, depth); - break; - } - +void MineShaftPieces::MineShaftStairs::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + int depth = getGenDepth(); + // crossings are coming from a direction and will generate children + // in the + // remaining three directions + switch (orientation) { + case Direction::NORTH: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0, boundingBox->z0 - 1, + Direction::NORTH, depth); + break; + case Direction::SOUTH: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0, + boundingBox->y0, boundingBox->z1 + 1, + Direction::SOUTH, depth); + break; + case Direction::WEST: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0, boundingBox->z0, + Direction::WEST, depth); + break; + case Direction::EAST: + generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0, boundingBox->z0, + Direction::EAST, depth); + break; + } } -bool MineShaftPieces::MineShaftStairs::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ +bool MineShaftPieces::MineShaftStairs::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { + return false; + } - if (edgesLiquid(level, chunkBB)) - { - return false; - } + // upper floor + generateBox(level, chunkBB, 0, 5, 0, (DEFAULT_SHAFT_WIDTH - 1), + 5 + (DEFAULT_SHAFT_HEIGHT - 1), 1, 0, 0, false); + // lower floor + generateBox(level, chunkBB, 0, 0, 7, (DEFAULT_SHAFT_WIDTH - 1), + (DEFAULT_SHAFT_HEIGHT - 1), 8, 0, 0, false); + // stairs + for (int i = 0; i < 5; i++) { + generateBox(level, chunkBB, 0, 5 - i - ((i < 4) ? 1 : 0), 2 + i, + (DEFAULT_SHAFT_WIDTH - 1), + 5 + (DEFAULT_SHAFT_HEIGHT - 1) - i, 2 + i, 0, 0, false); + } - // upper floor - generateBox(level, chunkBB, 0, 5, 0, (DEFAULT_SHAFT_WIDTH - 1), 5 + (DEFAULT_SHAFT_HEIGHT - 1), 1, 0, 0, false); - // lower floor - generateBox(level, chunkBB, 0, 0, 7, (DEFAULT_SHAFT_WIDTH - 1), (DEFAULT_SHAFT_HEIGHT - 1), 8, 0, 0, false); - // stairs - for (int i = 0; i < 5; i++) - { - generateBox(level, chunkBB, 0, 5 - i - ((i < 4) ? 1 : 0), 2 + i, (DEFAULT_SHAFT_WIDTH - 1), 5 + (DEFAULT_SHAFT_HEIGHT - 1) - i, 2 + i, 0, 0, false); - } - - return true; + return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/MineShaftPieces.h b/Minecraft.World/WorldGen/Structures/MineShaftPieces.h index 87978b4a1..75322f48d 100644 --- a/Minecraft.World/WorldGen/Structures/MineShaftPieces.h +++ b/Minecraft.World/WorldGen/Structures/MineShaftPieces.h @@ -2,95 +2,115 @@ #include "StructurePiece.h" -class MineShaftPieces -{ +class MineShaftPieces { private: - static const int DEFAULT_SHAFT_WIDTH = 3; - static const int DEFAULT_SHAFT_HEIGHT = 3; - static const int DEFAULT_SHAFT_LENGTH = 5; + static const int DEFAULT_SHAFT_WIDTH = 3; + static const int DEFAULT_SHAFT_HEIGHT = 3; + static const int DEFAULT_SHAFT_LENGTH = 5; - static const int MAX_DEPTH = 8; // 1.2.3 change + static const int MAX_DEPTH = 8; // 1.2.3 change - static StructurePiece *createRandomShaftPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - static StructurePiece *generateAndAddPiece(StructurePiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); + static StructurePiece* createRandomShaftPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + static StructurePiece* generateAndAddPiece( + StructurePiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); - /** - * - * - */ + /** + * + * + */ public: - class MineShaftRoom : public StructurePiece - { - private: - std::list childEntranceBoxes; + class MineShaftRoom : public StructurePiece { + private: + std::list childEntranceBoxes; - public: - MineShaftRoom(int genDepth, Random *random, int west, int north); - ~MineShaftRoom(); + public: + MineShaftRoom(int genDepth, Random* random, int west, int north); + ~MineShaftRoom(); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; - /** - * - * - */ - class MineShaftCorridor : public StructurePiece - { - private: - bool hasRails; // was final - bool spiderCorridor; // was final - bool hasPlacedSpider; - int numSections; + /** + * + * + */ + class MineShaftCorridor : public StructurePiece { + private: + bool hasRails; // was final + bool spiderCorridor; // was final + bool hasPlacedSpider; + int numSections; - public: - MineShaftCorridor(int genDepth, Random *random, BoundingBox *corridorBox, int direction); + public: + MineShaftCorridor(int genDepth, Random* random, + BoundingBox* corridorBox, int direction); - static BoundingBox *findCorridorSize(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; + static BoundingBox* findCorridorSize(std::list* pieces, + Random* random, int footX, + int footY, int footZ, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; - /** - * - * - */ - class MineShaftCrossing : public StructurePiece - { - private: - const int direction; - const bool isTwoFloored; + /** + * + * + */ + class MineShaftCrossing : public StructurePiece { + private: + const int direction; + const bool isTwoFloored; - public: - MineShaftCrossing(int genDepth, Random *random, BoundingBox *crossingBox, int direction); + public: + MineShaftCrossing(int genDepth, Random* random, + BoundingBox* crossingBox, int direction); - static BoundingBox *findCrossing(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; + static BoundingBox* findCrossing(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; - /** - * - * - */ - class MineShaftStairs : public StructurePiece - { - public: - MineShaftStairs(int genDepth, Random *random, BoundingBox *stairsBox, int direction); + /** + * + * + */ + class MineShaftStairs : public StructurePiece { + public: + MineShaftStairs(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); - static BoundingBox *findStairs(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + static BoundingBox* findStairs(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; - }; - - /* @formatter:off */ + /* @formatter:off */ private: - static WeighedTreasureArray smallTreasureItems; - /* @formatter:on */ + static WeighedTreasureArray smallTreasureItems; + /* @formatter:on */ public: - static void staticCtor(); - + static void staticCtor(); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/MineShaftStart.cpp b/Minecraft.World/WorldGen/Structures/MineShaftStart.cpp index 8e905916d..ecee80167 100644 --- a/Minecraft.World/WorldGen/Structures/MineShaftStart.cpp +++ b/Minecraft.World/WorldGen/Structures/MineShaftStart.cpp @@ -1,13 +1,16 @@ #include "../../Platform/stdafx.h" #include "../../Headers/net.minecraft.world.level.levelgen.structure.h" -MineShaftStart::MineShaftStart(Level *level, Random *random, int chunkX, int chunkZ) -{ - // 4jcraft added to unsigned - MineShaftPieces::MineShaftRoom *mineShaftRoom = new MineShaftPieces::MineShaftRoom(0, random, ((unsigned) chunkX << 4) + 2, ((unsigned) chunkZ << 4) + 2); - pieces.push_back(mineShaftRoom); - mineShaftRoom->addChildren(mineShaftRoom, &pieces, random); +MineShaftStart::MineShaftStart(Level* level, Random* random, int chunkX, + int chunkZ) { + // 4jcraft added to unsigned + MineShaftPieces::MineShaftRoom* mineShaftRoom = + new MineShaftPieces::MineShaftRoom(0, random, + ((unsigned)chunkX << 4) + 2, + ((unsigned)chunkZ << 4) + 2); + pieces.push_back(mineShaftRoom); + mineShaftRoom->addChildren(mineShaftRoom, &pieces, random); - calculateBoundingBox(); - moveBelowSeaLevel(level, random, 10); + calculateBoundingBox(); + moveBelowSeaLevel(level, random, 10); } diff --git a/Minecraft.World/WorldGen/Structures/MineShaftStart.h b/Minecraft.World/WorldGen/Structures/MineShaftStart.h index b46e3d675..76f9e60fd 100644 --- a/Minecraft.World/WorldGen/Structures/MineShaftStart.h +++ b/Minecraft.World/WorldGen/Structures/MineShaftStart.h @@ -2,8 +2,7 @@ #include "StructureStart.h" -class MineShaftStart : public StructureStart -{ +class MineShaftStart : public StructureStart { public: - MineShaftStart(Level *level, Random *random, int chunkX, int chunkZ); + MineShaftStart(Level* level, Random* random, int chunkX, int chunkZ); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/NetherBridgePieces.cpp b/Minecraft.World/WorldGen/Structures/NetherBridgePieces.cpp index 620a5643b..03fc90367 100644 --- a/Minecraft.World/WorldGen/Structures/NetherBridgePieces.cpp +++ b/Minecraft.World/WorldGen/Structures/NetherBridgePieces.cpp @@ -7,1447 +7,1747 @@ #include "NetherBridgePieces.h" #include "../../Util/Direction.h" -NetherBridgePieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount, bool allowInRow) : weight(weight) -{ - this->placeCount = 0; - this->pieceClass = pieceClass; - this->maxPlaceCount = maxPlaceCount; - this->allowInRow = allowInRow; +NetherBridgePieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, + int maxPlaceCount, bool allowInRow) + : weight(weight) { + this->placeCount = 0; + this->pieceClass = pieceClass; + this->maxPlaceCount = maxPlaceCount; + this->allowInRow = allowInRow; } -NetherBridgePieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount) : weight(weight) -{ - this->placeCount = 0; - this->pieceClass = pieceClass; - this->maxPlaceCount = maxPlaceCount; - this->allowInRow = false; +NetherBridgePieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, + int maxPlaceCount) + : weight(weight) { + this->placeCount = 0; + this->pieceClass = pieceClass; + this->maxPlaceCount = maxPlaceCount; + this->allowInRow = false; } -bool NetherBridgePieces::PieceWeight::doPlace(int depth) -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool NetherBridgePieces::PieceWeight::doPlace(int depth) { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -bool NetherBridgePieces::PieceWeight::isValid() -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool NetherBridgePieces::PieceWeight::isValid() { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -NetherBridgePieces::PieceWeight *NetherBridgePieces::bridgePieceWeights[NetherBridgePieces::BRIDGE_PIECEWEIGHTS_COUNT] = -{ - new PieceWeight(EPieceClass_BridgeStraight, 30, 0, true), - new PieceWeight(EPieceClass_BridgeCrossing, 10, 4), - new PieceWeight(EPieceClass_MonsterThrone, 15, 2), // 4J Stu - Increased weight to ensure that we have these (was 5), required for Blazes and therefore required for brewing - new PieceWeight(EPieceClass_CastleEntrance, 15, 1), // 4J Stu - Increased weight to ensure that we have these (was 5), required for CastleStalkRoom, and therefore required for brewing - new PieceWeight(EPieceClass_RoomCrossing, 10, 4), - new PieceWeight(EPieceClass_StairsRoom, 10, 3), +NetherBridgePieces::PieceWeight* NetherBridgePieces::bridgePieceWeights + [NetherBridgePieces::BRIDGE_PIECEWEIGHTS_COUNT] = { + new PieceWeight(EPieceClass_BridgeStraight, 30, 0, true), + new PieceWeight(EPieceClass_BridgeCrossing, 10, 4), + new PieceWeight( + EPieceClass_MonsterThrone, 15, + 2), // 4J Stu - Increased weight to ensure that we have these (was + // 5), required for Blazes and therefore required for brewing + new PieceWeight(EPieceClass_CastleEntrance, 15, + 1), // 4J Stu - Increased weight to ensure that we have + // these (was 5), required for CastleStalkRoom, and + // therefore required for brewing + new PieceWeight(EPieceClass_RoomCrossing, 10, 4), + new PieceWeight(EPieceClass_StairsRoom, 10, 3), }; -NetherBridgePieces::PieceWeight *NetherBridgePieces::castlePieceWeights[NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = -{ - new PieceWeight(EPieceClass_CastleStalkRoom, 30, 2), // 4J Stu - Increased weight to ensure that we have these (was 5), required for Nether Wart, and therefore required for brewing - new PieceWeight(EPieceClass_CastleSmallCorridorPiece, 25, 0, true), - new PieceWeight(EPieceClass_CastleSmallCorridorCrossingPiece, 15, 5), - new PieceWeight(EPieceClass_CastleSmallCorridorRightTurnPiece, 5, 10), - new PieceWeight(EPieceClass_CastleSmallCorridorLeftTurnPiece, 5, 10), - new PieceWeight(EPieceClass_CastleCorridorStairsPiece, 10, 3, true), - new PieceWeight(EPieceClass_CastleCorridorTBalconyPiece, 7, 2), +NetherBridgePieces::PieceWeight* NetherBridgePieces::castlePieceWeights + [NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = { + new PieceWeight(EPieceClass_CastleStalkRoom, 30, + 2), // 4J Stu - Increased weight to ensure that we have + // these (was 5), required for Nether Wart, and + // therefore required for brewing + new PieceWeight(EPieceClass_CastleSmallCorridorPiece, 25, 0, true), + new PieceWeight(EPieceClass_CastleSmallCorridorCrossingPiece, 15, 5), + new PieceWeight(EPieceClass_CastleSmallCorridorRightTurnPiece, 5, 10), + new PieceWeight(EPieceClass_CastleSmallCorridorLeftTurnPiece, 5, 10), + new PieceWeight(EPieceClass_CastleCorridorStairsPiece, 10, 3, true), + new PieceWeight(EPieceClass_CastleCorridorTBalconyPiece, 7, 2), }; -NetherBridgePieces::NetherBridgePiece *NetherBridgePieces::findAndCreateBridgePieceFactory(NetherBridgePieces::PieceWeight *piece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - EPieceClass pieceClass = piece->pieceClass; - NetherBridgePiece *structurePiece = NULL; - - if (pieceClass == EPieceClass_BridgeStraight) - { - structurePiece = BridgeStraight::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_BridgeCrossing) - { - structurePiece = BridgeCrossing::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_RoomCrossing) - { - structurePiece = RoomCrossing::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_StairsRoom) - { - structurePiece = StairsRoom::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_MonsterThrone) - { - structurePiece = MonsterThrone::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleEntrance) - { - structurePiece = CastleEntrance::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleSmallCorridorPiece) - { - structurePiece = CastleSmallCorridorPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleSmallCorridorRightTurnPiece) - { - structurePiece = CastleSmallCorridorRightTurnPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleSmallCorridorLeftTurnPiece) - { - structurePiece = CastleSmallCorridorLeftTurnPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleCorridorStairsPiece) - { - structurePiece = CastleCorridorStairsPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleCorridorTBalconyPiece) - { - structurePiece = CastleCorridorTBalconyPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleSmallCorridorCrossingPiece) - { - structurePiece = CastleSmallCorridorCrossingPiece::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_CastleStalkRoom) - { - structurePiece = CastleStalkRoom::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - return structurePiece; -} - -NetherBridgePieces::NetherBridgePiece::NetherBridgePiece(int genDepth) : StructurePiece(genDepth) -{ -} - -int NetherBridgePieces::NetherBridgePiece::updatePieceWeight(std::list *currentPieces) -{ - bool hasAnyPieces = false; - int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) - { - PieceWeight *piece = *it; - - if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) - { - hasAnyPieces = true; - } - totalWeight += piece->weight; - } - return (hasAnyPieces ? totalWeight : -1); -} - -NetherBridgePieces::NetherBridgePiece *NetherBridgePieces::NetherBridgePiece::generatePiece(StartPiece *startPiece, std::list *currentPieces, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - int totalWeight = updatePieceWeight(currentPieces); - boolean doStuff = totalWeight > 0 && depth <= MAX_DEPTH; - - int numAttempts = 0; - while (numAttempts < 5 && doStuff) - { - numAttempts++; - - int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) - { - PieceWeight *piece = *it; - weightSelection -= piece->weight; - if (weightSelection < 0) - { - if (!piece->doPlace(depth) || (piece == startPiece->previousPiece && !piece->allowInRow)) - { - break; - } - - NetherBridgePiece *structurePiece = findAndCreateBridgePieceFactory(piece, pieces, random, footX, footY, footZ, direction, depth); - if (structurePiece != NULL) - { - piece->placeCount++; - startPiece->previousPiece = piece; - - if (!piece->isValid()) - { - currentPieces->remove(piece); - } - return structurePiece; - } - } - } - } - { - return BridgeEndFiller::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - -} - -StructurePiece *NetherBridgePieces::NetherBridgePiece::generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth, bool isCastle) -{ - if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) - { - return BridgeEndFiller::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - std::list *availablePieces = &startPiece->availableBridgePieces; - if (isCastle) - { - availablePieces = &startPiece->availableCastlePieces; - } - StructurePiece *newPiece = generatePiece(startPiece, availablePieces, pieces, random, footX, footY, footZ, direction, depth + 1); - if (newPiece != NULL) - { - pieces->push_back(newPiece); - startPiece->pendingChildren.push_back(newPiece); - } - return newPiece; -} - -StructurePiece *NetherBridgePieces::NetherBridgePiece::generateChildForward(StartPiece *startPiece, std::list *pieces, Random *random, int xOff, int yOff, bool isCastle) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + xOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, orientation, getGenDepth(), isCastle); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + xOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, orientation, getGenDepth(), isCastle); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, getGenDepth(), isCastle); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, getGenDepth(), isCastle); - } - return NULL; -} - -StructurePiece *NetherBridgePieces::NetherBridgePiece::generateChildLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff, bool isCastle) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth(), isCastle); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth(), isCastle); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth(), isCastle); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth(), isCastle); - } - return NULL; -} - -StructurePiece *NetherBridgePieces::NetherBridgePiece::generateChildRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff, bool isCastle) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth(), isCastle); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth(), isCastle); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth(), isCastle); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth(), isCastle); - } - return NULL; -} - -bool NetherBridgePieces::NetherBridgePiece::isOkBox(BoundingBox *box, StartPiece *startPiece) -{ - bool bIsOk = false; - - if(box != NULL) - { - if( box->y0 > LOWEST_Y_POSITION ) bIsOk = true; - int xzSize = (startPiece->m_level->getLevelData()->getXZSize() / startPiece->m_level->getLevelData()->getHellScale()); //HellRandomLevelSource::XZSIZE; - int blockMin = -( (xzSize << 4) / 2) + 1; - int blockMax = ( (xzSize << 4) / 2 ) - 1; - - if(box->x0 <= blockMin) bIsOk = false; - if(box->z0 <= blockMin) bIsOk = false; - if(box->x1 >= blockMax) bIsOk = false; - if(box->z1 >= blockMax) bIsOk = false; - } - - return bIsOk; -} - -void NetherBridgePieces::NetherBridgePiece::generateLightPost(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z, int xOff, int zOff) -{ - int worldX = getWorldX(x, z); - int worldY = getWorldY(y); - int worldZ = getWorldZ(x, z); - - if (!chunkBB->isInside(worldX, worldY, worldZ)) - { - return; - } - - if (level->isEmptyTile(worldX, worldY, worldZ) && level->isEmptyTile(worldX, worldY + 1, worldZ) && level->isEmptyTile(worldX, worldY + 2, worldZ) - && level->isEmptyTile(worldX, worldY + 3, worldZ)) - { - level->setTileAndDataNoUpdate(worldX, worldY, worldZ, Tile::netherFence_Id, 0); - level->setTileAndDataNoUpdate(worldX, worldY + 1, worldZ, Tile::netherFence_Id, 0); - level->setTileAndDataNoUpdate(worldX, worldY + 2, worldZ, Tile::netherFence_Id, 0); - level->setTileAndDataNoUpdate(worldX, worldY + 3, worldZ, Tile::netherFence_Id, 0); - placeBlock(level, Tile::netherFence_Id, 0, x + xOff, y + 3, z + zOff, chunkBB); - placeBlock(level, Tile::lightGem_Id, 0, x + xOff, y + 2, z + zOff, chunkBB); - } -} - -void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingRight(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z) -{ - generateLightPost(level, random, chunkBB, x, y, z, 1, 0); -} - -void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingLeft(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z) -{ - generateLightPost(level, random, chunkBB, x, y, z, -1, 0); -} - -void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingUp(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z) -{ - generateLightPost(level, random, chunkBB, x, y, z, 0, 1); -} - -void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingDown(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z) -{ - generateLightPost(level, random, chunkBB, x, y, z, 0, -1); -} - - -NetherBridgePieces::BridgeStraight::BridgeStraight(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::BridgeStraight::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 1, 3, false); -} - -NetherBridgePieces::BridgeStraight *NetherBridgePieces::BridgeStraight::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new BridgeStraight(genDepth, random, box, direction); -} - -bool NetherBridgePieces::BridgeStraight::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 3, 0, width - 1, 4, depth - 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 1, 5, 0, 3, 7, depth - 1, 0, 0, false); - - // hand rails - generateBox(level, chunkBB, 0, 5, 0, 0, 5, depth - 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 5, 0, 4, 5, depth - 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - generateBox(level, chunkBB, 0, 2, 0, 4, 2, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 13, 4, 2, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 0, 0, 4, 1, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 0, 15, 4, 1, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 2; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 18 - z, chunkBB); - } - } - - generateBox(level, chunkBB, 0, 1, 1, 0, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 3, 4, 0, 4, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 3, 14, 0, 4, 14, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 1, 17, 0, 4, 17, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 1, 1, 4, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 3, 4, 4, 4, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 3, 14, 4, 4, 14, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 1, 17, 4, 4, 17, Tile::netherFence_Id, Tile::netherFence_Id, false); - - return true; -} - -NetherBridgePieces::BridgeEndFiller::BridgeEndFiller(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; - selfSeed = random->nextInt(); -} - -NetherBridgePieces::BridgeEndFiller *NetherBridgePieces::BridgeEndFiller::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new BridgeEndFiller(genDepth, random, box, direction); -} - -bool NetherBridgePieces::BridgeEndFiller::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - Random *selfRandom = new Random(selfSeed); - - // floor - for (int x = 0; x <= 4; x++) - { - for (int y = 3; y <= 4; y++) - { - int z = selfRandom->nextInt(8); - generateBox(level, chunkBB, x, y, 0, x, y, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - } - - // hand rails - { - int z = selfRandom->nextInt(8); - generateBox(level, chunkBB, 0, 5, 0, 0, 5, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - { - int z = selfRandom->nextInt(8); - generateBox(level, chunkBB, 4, 5, 0, 4, 5, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - - // supports - for (int x = 0; x <= 4; x++) - { - int z = selfRandom->nextInt(5); - generateBox(level, chunkBB, x, 2, 0, x, 2, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - for (int x = 0; x <= 4; x++) - { - for (int y = 0; y <= 1; y++) - { - int z = selfRandom->nextInt(3); - generateBox(level, chunkBB, x, y, 0, x, y, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - } - - delete selfRandom; - - return true; -} - -NetherBridgePieces::BridgeCrossing::BridgeCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -NetherBridgePieces::BridgeCrossing::BridgeCrossing(Random *random, int west, int north) : NetherBridgePiece(0) -{ - orientation = random->nextInt(4); - - switch (orientation) - { - case Direction::NORTH: - case Direction::SOUTH: - boundingBox = new BoundingBox(west, 64, north, west + width - 1, 64 + height - 1, north + depth - 1); - break; - default: - boundingBox = new BoundingBox(west, 64, north, west + depth - 1, 64 + height - 1, north + width - 1); - break; - } -} - -void NetherBridgePieces::BridgeCrossing::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 8, 3, false); - generateChildLeft((StartPiece *) startPiece, pieces, random, 3, 8, false); - generateChildRight((StartPiece *) startPiece, pieces, random, 3, 8, false); -} - -NetherBridgePieces::BridgeCrossing *NetherBridgePieces::BridgeCrossing::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -8, -3, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new BridgeCrossing(genDepth, random, box, direction); -} - -bool NetherBridgePieces::BridgeCrossing::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 7, 3, 0, 11, 4, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 3, 7, 18, 4, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 8, 5, 0, 10, 7, 18, 0, 0, false); - generateBox(level, chunkBB, 0, 5, 8, 18, 7, 10, 0, 0, false); - // hand rails - generateBox(level, chunkBB, 7, 5, 0, 7, 5, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 7, 5, 11, 7, 5, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 0, 11, 5, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 11, 11, 5, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 5, 7, 7, 5, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 7, 18, 5, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 5, 11, 7, 5, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 11, 18, 5, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - generateBox(level, chunkBB, 7, 2, 0, 11, 2, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 7, 2, 13, 11, 2, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 7, 0, 0, 11, 1, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 7, 0, 15, 11, 1, 18, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - for (int x = 7; x <= 11; x++) - { - for (int z = 0; z <= 2; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 18 - z, chunkBB); - } - } - - generateBox(level, chunkBB, 0, 2, 7, 5, 2, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 13, 2, 7, 18, 2, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 0, 7, 3, 1, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 15, 0, 7, 18, 1, 11, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - for (int x = 0; x <= 2; x++) - { - for (int z = 7; z <= 11; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, 18 - x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::StartPiece::StartPiece(Random *random, int west, int north, Level *level) : BridgeCrossing(random, west, north) -{ - isLibraryAdded = false; - previousPiece = NULL; - m_level = level; - - for( int i = 0; i < BRIDGE_PIECEWEIGHTS_COUNT; i++ ) - { - PieceWeight *piece = bridgePieceWeights[i]; - piece->placeCount = 0; - availableBridgePieces.push_back(piece); - } - - for( int i = 0; i < CASTLE_PIECEWEIGHTS_COUNT; i++ ) - { - PieceWeight *piece = castlePieceWeights[i]; - - piece->placeCount = 0; - availableCastlePieces.push_back(piece); - } -} - - -NetherBridgePieces::RoomCrossing::RoomCrossing(int genDepth, Random *random, BoundingBox *box, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = box; -} - -void NetherBridgePieces::RoomCrossing::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 2, 0, false); - generateChildLeft((StartPiece *) startPiece, pieces, random, 0, 2, false); - generateChildRight((StartPiece *) startPiece, pieces, random, 0, 2, false); -} - -NetherBridgePieces::RoomCrossing *NetherBridgePieces::RoomCrossing::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new RoomCrossing(genDepth, random, box, direction); -} - -bool NetherBridgePieces::RoomCrossing::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, width - 1, 1, depth - 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 6, 7, 6, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 2, 0, 1, 6, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 6, 1, 6, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 2, 0, 6, 6, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 2, 6, 6, 6, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 0, 0, 6, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 5, 0, 6, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 2, 0, 6, 6, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 2, 5, 6, 6, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // entries - generateBox(level, chunkBB, 2, 6, 0, 4, 6, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 0, 4, 5, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 2, 6, 6, 4, 6, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 6, 4, 5, 6, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 6, 2, 0, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 5, 2, 0, 5, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 6, 6, 2, 6, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 5, 2, 6, 5, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - - for (int x = 0; x <= 6; x++) - { - for (int z = 0; z <= 6; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - -NetherBridgePieces::StairsRoom::StairsRoom(int genDepth, Random *random, BoundingBox *box, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = box; -} - -void NetherBridgePieces::StairsRoom::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildRight((StartPiece *) startPiece, pieces, random, 6, 2, false); -} - -NetherBridgePieces::StairsRoom *NetherBridgePieces::StairsRoom::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new StairsRoom(genDepth, random, box, direction); -} - -bool NetherBridgePieces::StairsRoom::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, width - 1, 1, depth - 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 6, 10, 6, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 2, 0, 1, 8, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 2, 0, 6, 8, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 1, 0, 8, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 2, 1, 6, 8, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 2, 6, 5, 8, 6, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // wall decorations - generateBox(level, chunkBB, 0, 3, 2, 0, 5, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 6, 3, 2, 6, 5, 2, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 6, 3, 4, 6, 5, 4, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // stair - placeBlock(level, Tile::netherBrick_Id, 0, 5, 2, 5, chunkBB); - generateBox(level, chunkBB, 4, 2, 5, 4, 3, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 3, 2, 5, 3, 4, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 2, 5, 2, 5, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 2, 5, 1, 6, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // top floor - generateBox(level, chunkBB, 1, 7, 1, 5, 7, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 8, 2, 6, 8, 4, 0, 0, false); - - // entries - generateBox(level, chunkBB, 2, 6, 0, 4, 8, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 0, 4, 5, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - - for (int x = 0; x <= 6; x++) - { - for (int z = 0; z <= 6; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; - -} - - -NetherBridgePieces::MonsterThrone::MonsterThrone(int genDepth, Random *random, BoundingBox *box, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = box; - hasPlacedMobSpawner = false; -} - -NetherBridgePieces::MonsterThrone *NetherBridgePieces::MonsterThrone::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new MonsterThrone(genDepth, random, box, direction); -} - -bool NetherBridgePieces::MonsterThrone::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - generateBox(level, chunkBB, 0, 2, 0, 6, 7, 7, 0, 0, false); - - // floors - generateBox(level, chunkBB, 1, 0, 0, 5, 1, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 2, 1, 5, 2, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 3, 2, 5, 3, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 4, 3, 5, 4, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // rails - generateBox(level, chunkBB, 1, 2, 0, 1, 4, 2, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 2, 0, 5, 4, 2, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 5, 2, 1, 5, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 5, 2, 5, 5, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 5, 3, 0, 5, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 5, 3, 6, 5, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 5, 8, 5, 5, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - placeBlock(level, Tile::netherFence_Id, 0, 1, 6, 3, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 5, 6, 3, chunkBB); - generateBox(level, chunkBB, 0, 6, 3, 0, 6, 8, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 6, 6, 3, 6, 6, 8, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 1, 6, 8, 5, 7, 8, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 2, 8, 8, 4, 8, 8, Tile::netherFence_Id, Tile::netherFence_Id, false); - - - if (!hasPlacedMobSpawner) - { - int y = getWorldY(5), x = getWorldX(3, 5), z = getWorldZ(3, 5); - if (chunkBB->isInside(x, y, z)) - { - hasPlacedMobSpawner = true; - level->setTile(x, y, z, Tile::mobSpawner_Id); - std::shared_ptr entity = std::dynamic_pointer_cast( level->getTileEntity(x, y, z) ); - if (entity != NULL) entity->setEntityId(L"Blaze"); - } - } - - for (int x = 0; x <= 6; x++) - { - for (int z = 0; z <= 6; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::CastleEntrance::CastleEntrance(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleEntrance::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 5, 3, true); -} - -NetherBridgePieces::CastleEntrance *NetherBridgePieces::CastleEntrance::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleEntrance(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleEntrance::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 3, 0, 12, 4, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 5, 0, 12, 13, 12, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 5, 0, 1, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 0, 12, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 11, 4, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 8, 5, 11, 10, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 9, 11, 7, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 0, 4, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 8, 5, 0, 10, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 9, 0, 7, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // roof - generateBox(level, chunkBB, 2, 11, 2, 10, 12, 10, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // entrance decoration - generateBox(level, chunkBB, 5, 8, 0, 7, 8, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // wall decorations - for (int i = 1; i <= 11; i += 2) - { - generateBox(level, chunkBB, i, 10, 0, i, 11, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, i, 10, 12, i, 11, 12, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 10, i, 0, 11, i, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 12, 10, i, 12, 11, i, Tile::netherFence_Id, Tile::netherFence_Id, false); - placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 0, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 12, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, 0, 13, i, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, 12, 13, i, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 12, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, i + 1, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 12, 13, i + 1, chunkBB); - } - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 12, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 12, 13, 0, chunkBB); - - // inside decorations - for (int z = 3; z <= 9; z += 2) - { - generateBox(level, chunkBB, 1, 7, z, 1, 8, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 11, 7, z, 11, 8, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - } - - // supports - generateBox(level, chunkBB, 4, 2, 0, 8, 2, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 4, 12, 2, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - generateBox(level, chunkBB, 4, 0, 0, 8, 1, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 0, 9, 8, 1, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 0, 4, 3, 1, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 9, 0, 4, 12, 1, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - for (int x = 4; x <= 8; x++) - { - for (int z = 0; z <= 2; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 12 - z, chunkBB); - } - } - for (int x = 0; x <= 2; x++) - { - for (int z = 4; z <= 8; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, 12 - x, -1, z, chunkBB); - } - } - - // lava well - generateBox(level, chunkBB, 5, 5, 5, 7, 5, 7, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 1, 6, 6, 4, 6, 0, 0, false); - placeBlock(level, Tile::netherBrick_Id, 0, 6, 0, 6, chunkBB); - placeBlock(level, Tile::lava_Id, 0, 6, 5, 6, chunkBB); - // tick lava well - int x = getWorldX(6, 6); - int y = getWorldY(5); - int z = getWorldZ(6, 6); - if (chunkBB->isInside(x, y, z)) - { - level->setInstaTick(true); - Tile::tiles[Tile::lava_Id]->tick(level, x, y, z, random); - level->setInstaTick(false); - } - - - return true; -} - - -NetherBridgePieces::CastleStalkRoom::CastleStalkRoom(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleStalkRoom::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 5, 3, true); - generateChildForward((StartPiece *) startPiece, pieces, random, 5, 11, true); -} - -NetherBridgePieces::CastleStalkRoom *NetherBridgePieces::CastleStalkRoom::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleStalkRoom(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleStalkRoom::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 3, 0, 12, 4, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 5, 0, 12, 13, 12, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 5, 0, 1, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 11, 5, 0, 12, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 11, 4, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 8, 5, 11, 10, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 9, 11, 7, 12, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 0, 4, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 8, 5, 0, 10, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 5, 9, 0, 7, 12, 1, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // roof - generateBox(level, chunkBB, 2, 11, 2, 10, 12, 10, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // wall decorations - for (int i = 1; i <= 11; i += 2) - { - generateBox(level, chunkBB, i, 10, 0, i, 11, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, i, 10, 12, i, 11, 12, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 10, i, 0, 11, i, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 12, 10, i, 12, 11, i, Tile::netherFence_Id, Tile::netherFence_Id, false); - placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 0, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 12, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, 0, 13, i, chunkBB); - placeBlock(level, Tile::netherBrick_Id, 0, 12, 13, i, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 12, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, i + 1, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 12, 13, i + 1, chunkBB); - } - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 12, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); - placeBlock(level, Tile::netherFence_Id, 0, 12, 13, 0, chunkBB); - - // inside decorations - for (int z = 3; z <= 9; z += 2) - { - generateBox(level, chunkBB, 1, 7, z, 1, 8, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 11, 7, z, 11, 8, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - } - - // inside stair - int stairOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 3); - for (int i = 0; i <= 6; i++) - { - int z = i + 4; - for (int x = 5; x <= 7; x++) - { - placeBlock(level, Tile::stairs_netherBricks_Id, stairOrientation, x, 5 + i, z, chunkBB); - } - if (z >= 5 && z <= 8) - { - generateBox(level, chunkBB, 5, 5, z, 7, i + 4, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - else if (z >= 9 && z <= 10) - { - generateBox(level, chunkBB, 5, 8, z, 7, i + 4, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - } - if (i >= 1) - { - generateBox(level, chunkBB, 5, 6 + i, z, 7, 9 + i, z, 0, 0, false); - } - } - for (int x = 5; x <= 7; x++) - { - placeBlock(level, Tile::stairs_netherBricks_Id, stairOrientation, x, 12, 11, chunkBB); - } - generateBox(level, chunkBB, 5, 6, 7, 5, 7, 7, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 7, 6, 7, 7, 7, 7, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 5, 13, 12, 7, 13, 12, 0, 0, false); - - // farmland catwalks - generateBox(level, chunkBB, 2, 5, 2, 3, 5, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 9, 3, 5, 10, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 2, 5, 4, 2, 5, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 9, 5, 2, 10, 5, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 9, 5, 9, 10, 5, 10, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 10, 5, 4, 10, 5, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - int eastOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 0); - int westOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 1); - placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 2, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 3, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 9, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 10, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 2, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 3, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 9, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 10, chunkBB); - - // farmlands - generateBox(level, chunkBB, 3, 4, 4, 4, 4, 8, Tile::hellSand_Id, Tile::hellSand_Id, false); - generateBox(level, chunkBB, 8, 4, 4, 9, 4, 8, Tile::hellSand_Id, Tile::hellSand_Id, false); - generateBox(level, chunkBB, 3, 5, 4, 4, 5, 8, Tile::netherStalk_Id, Tile::netherStalk_Id, false); - generateBox(level, chunkBB, 8, 5, 4, 9, 5, 8, Tile::netherStalk_Id, Tile::netherStalk_Id, false); - - // supports - generateBox(level, chunkBB, 4, 2, 0, 8, 2, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 4, 12, 2, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - generateBox(level, chunkBB, 4, 0, 0, 8, 1, 3, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 0, 9, 8, 1, 12, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 0, 4, 3, 1, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 9, 0, 4, 12, 1, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - for (int x = 4; x <= 8; x++) - { - for (int z = 0; z <= 2; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 12 - z, chunkBB); - } - } - for (int x = 0; x <= 2; x++) - { - for (int z = 4; z <= 8; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - fillColumnDown(level, Tile::netherBrick_Id, 0, 12 - x, -1, z, chunkBB); - } - } - - return true; - -} - - -NetherBridgePieces::CastleSmallCorridorPiece::CastleSmallCorridorPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - - -void NetherBridgePieces::CastleSmallCorridorPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 1, 0, true); -} - -NetherBridgePieces::CastleSmallCorridorPiece *NetherBridgePieces::CastleSmallCorridorPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleSmallCorridorPiece(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleSmallCorridorPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 2, 0, 0, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 2, 0, 4, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 3, 1, 0, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 3, 3, 0, 4, 3, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 3, 1, 4, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 3, 3, 4, 4, 3, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // roof - generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 4; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::CastleSmallCorridorCrossingPiece::CastleSmallCorridorCrossingPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleSmallCorridorCrossingPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 1, 0, true); - generateChildLeft((StartPiece *) startPiece, pieces, random, 0, 1, true); - generateChildRight((StartPiece *) startPiece, pieces, random, 0, 1, true); -} - -NetherBridgePieces::CastleSmallCorridorCrossingPiece *NetherBridgePieces::CastleSmallCorridorCrossingPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleSmallCorridorCrossingPiece(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleSmallCorridorCrossingPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 2, 0, 0, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 2, 0, 4, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 4, 0, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 2, 4, 4, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // roof - generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 4; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::CastleSmallCorridorRightTurnPiece::CastleSmallCorridorRightTurnPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleSmallCorridorRightTurnPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildRight((StartPiece *) startPiece, pieces, random, 0, 1, true); -} - -NetherBridgePieces::CastleSmallCorridorRightTurnPiece *NetherBridgePieces::CastleSmallCorridorRightTurnPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleSmallCorridorRightTurnPiece(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleSmallCorridorRightTurnPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); - - // walls - generateBox(level, chunkBB, 0, 2, 0, 0, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 0, 3, 1, 0, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 3, 3, 0, 4, 3, Tile::netherFence_Id, Tile::netherFence_Id, false); - - generateBox(level, chunkBB, 4, 2, 0, 4, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - generateBox(level, chunkBB, 1, 2, 4, 4, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 3, 4, 1, 4, 4, Tile::netherFence_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 3, 3, 4, 3, 4, 4, Tile::netherFence_Id, Tile::netherBrick_Id, false); - - // roof - generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 4; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::CastleSmallCorridorLeftTurnPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildLeft((StartPiece *) startPiece, pieces, random, 0, 1, true); -} - -NetherBridgePieces::CastleSmallCorridorLeftTurnPiece *NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleSmallCorridorLeftTurnPiece(genDepth, random, box, direction); +NetherBridgePieces::NetherBridgePiece* +NetherBridgePieces::findAndCreateBridgePieceFactory( + NetherBridgePieces::PieceWeight* piece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, int depth) { + EPieceClass pieceClass = piece->pieceClass; + NetherBridgePiece* structurePiece = NULL; + + if (pieceClass == EPieceClass_BridgeStraight) { + structurePiece = BridgeStraight::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_BridgeCrossing) { + structurePiece = BridgeCrossing::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_RoomCrossing) { + structurePiece = RoomCrossing::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_StairsRoom) { + structurePiece = StairsRoom::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_MonsterThrone) { + structurePiece = MonsterThrone::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleEntrance) { + structurePiece = CastleEntrance::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleSmallCorridorPiece) { + structurePiece = CastleSmallCorridorPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleSmallCorridorRightTurnPiece) { + structurePiece = CastleSmallCorridorRightTurnPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleSmallCorridorLeftTurnPiece) { + structurePiece = CastleSmallCorridorLeftTurnPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleCorridorStairsPiece) { + structurePiece = CastleCorridorStairsPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleCorridorTBalconyPiece) { + structurePiece = CastleCorridorTBalconyPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleSmallCorridorCrossingPiece) { + structurePiece = CastleSmallCorridorCrossingPiece::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_CastleStalkRoom) { + structurePiece = CastleStalkRoom::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } + return structurePiece; +} + +NetherBridgePieces::NetherBridgePiece::NetherBridgePiece(int genDepth) + : StructurePiece(genDepth) {} + +int NetherBridgePieces::NetherBridgePiece::updatePieceWeight( + std::list* currentPieces) { + bool hasAnyPieces = false; + int totalWeight = 0; + for (AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); + it++) { + PieceWeight* piece = *it; + + if (piece->maxPlaceCount > 0 && + piece->placeCount < piece->maxPlaceCount) { + hasAnyPieces = true; + } + totalWeight += piece->weight; + } + return (hasAnyPieces ? totalWeight : -1); +} + +NetherBridgePieces::NetherBridgePiece* +NetherBridgePieces::NetherBridgePiece::generatePiece( + StartPiece* startPiece, + std::list* currentPieces, + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int depth) { + int totalWeight = updatePieceWeight(currentPieces); + boolean doStuff = totalWeight > 0 && depth <= MAX_DEPTH; + + int numAttempts = 0; + while (numAttempts < 5 && doStuff) { + numAttempts++; + + int weightSelection = random->nextInt(totalWeight); + for (AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); + it++) { + PieceWeight* piece = *it; + weightSelection -= piece->weight; + if (weightSelection < 0) { + if (!piece->doPlace(depth) || + (piece == startPiece->previousPiece && + !piece->allowInRow)) { + break; + } + + NetherBridgePiece* structurePiece = + findAndCreateBridgePieceFactory(piece, pieces, random, + footX, footY, footZ, + direction, depth); + if (structurePiece != NULL) { + piece->placeCount++; + startPiece->previousPiece = piece; + + if (!piece->isValid()) { + currentPieces->remove(piece); + } + return structurePiece; + } + } + } + } + { + return BridgeEndFiller::createPiece(pieces, random, footX, footY, footZ, + direction, depth); + } +} + +StructurePiece* NetherBridgePieces::NetherBridgePiece::generateAndAddPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth, bool isCastle) { + if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || + abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) { + return BridgeEndFiller::createPiece(pieces, random, footX, footY, footZ, + direction, depth); + } + std::list* availablePieces = + &startPiece->availableBridgePieces; + if (isCastle) { + availablePieces = &startPiece->availableCastlePieces; + } + StructurePiece* newPiece = + generatePiece(startPiece, availablePieces, pieces, random, footX, footY, + footZ, direction, depth + 1); + if (newPiece != NULL) { + pieces->push_back(newPiece); + startPiece->pendingChildren.push_back(newPiece); + } + return newPiece; +} + +StructurePiece* NetherBridgePieces::NetherBridgePiece::generateChildForward( + StartPiece* startPiece, std::list* pieces, Random* random, + int xOff, int yOff, bool isCastle) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + xOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, orientation, + getGenDepth(), isCastle); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + xOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, orientation, + getGenDepth(), isCastle); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, + getGenDepth(), isCastle); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, + getGenDepth(), isCastle); + } + return NULL; +} + +StructurePiece* NetherBridgePieces::NetherBridgePiece::generateChildLeft( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff, bool isCastle) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth(), isCastle); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth(), isCastle); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth(), isCastle); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth(), isCastle); + } + return NULL; +} + +StructurePiece* NetherBridgePieces::NetherBridgePiece::generateChildRight( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff, bool isCastle) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth(), isCastle); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth(), isCastle); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth(), isCastle); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth(), isCastle); + } + return NULL; +} + +bool NetherBridgePieces::NetherBridgePiece::isOkBox(BoundingBox* box, + StartPiece* startPiece) { + bool bIsOk = false; + + if (box != NULL) { + if (box->y0 > LOWEST_Y_POSITION) bIsOk = true; + int xzSize = (startPiece->m_level->getLevelData()->getXZSize() / + startPiece->m_level->getLevelData() + ->getHellScale()); // HellRandomLevelSource::XZSIZE; + int blockMin = -((xzSize << 4) / 2) + 1; + int blockMax = ((xzSize << 4) / 2) - 1; + + if (box->x0 <= blockMin) bIsOk = false; + if (box->z0 <= blockMin) bIsOk = false; + if (box->x1 >= blockMax) bIsOk = false; + if (box->z1 >= blockMax) bIsOk = false; + } + + return bIsOk; +} + +void NetherBridgePieces::NetherBridgePiece::generateLightPost( + Level* level, Random* random, BoundingBox* chunkBB, int x, int y, int z, + int xOff, int zOff) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); + + if (!chunkBB->isInside(worldX, worldY, worldZ)) { + return; + } + + if (level->isEmptyTile(worldX, worldY, worldZ) && + level->isEmptyTile(worldX, worldY + 1, worldZ) && + level->isEmptyTile(worldX, worldY + 2, worldZ) && + level->isEmptyTile(worldX, worldY + 3, worldZ)) { + level->setTileAndDataNoUpdate(worldX, worldY, worldZ, + Tile::netherFence_Id, 0); + level->setTileAndDataNoUpdate(worldX, worldY + 1, worldZ, + Tile::netherFence_Id, 0); + level->setTileAndDataNoUpdate(worldX, worldY + 2, worldZ, + Tile::netherFence_Id, 0); + level->setTileAndDataNoUpdate(worldX, worldY + 3, worldZ, + Tile::netherFence_Id, 0); + placeBlock(level, Tile::netherFence_Id, 0, x + xOff, y + 3, z + zOff, + chunkBB); + placeBlock(level, Tile::lightGem_Id, 0, x + xOff, y + 2, z + zOff, + chunkBB); + } +} + +void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingRight( + Level* level, Random* random, BoundingBox* chunkBB, int x, int y, int z) { + generateLightPost(level, random, chunkBB, x, y, z, 1, 0); +} + +void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingLeft( + Level* level, Random* random, BoundingBox* chunkBB, int x, int y, int z) { + generateLightPost(level, random, chunkBB, x, y, z, -1, 0); +} + +void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingUp( + Level* level, Random* random, BoundingBox* chunkBB, int x, int y, int z) { + generateLightPost(level, random, chunkBB, x, y, z, 0, 1); +} + +void NetherBridgePieces::NetherBridgePiece::generateLightPostFacingDown( + Level* level, Random* random, BoundingBox* chunkBB, int x, int y, int z) { + generateLightPost(level, random, chunkBB, x, y, z, 0, -1); +} + +NetherBridgePieces::BridgeStraight::BridgeStraight(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::BridgeStraight::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 1, 3, false); +} + +NetherBridgePieces::BridgeStraight* +NetherBridgePieces::BridgeStraight::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new BridgeStraight(genDepth, random, box, direction); +} + +bool NetherBridgePieces::BridgeStraight::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 3, 0, width - 1, 4, depth - 1, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 1, 5, 0, 3, 7, depth - 1, 0, 0, false); + + // hand rails + generateBox(level, chunkBB, 0, 5, 0, 0, 5, depth - 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 5, 0, 4, 5, depth - 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + generateBox(level, chunkBB, 0, 2, 0, 4, 2, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 13, 4, 2, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 0, 0, 4, 1, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 0, 15, 4, 1, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 2; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 18 - z, + chunkBB); + } + } + + generateBox(level, chunkBB, 0, 1, 1, 0, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 3, 4, 0, 4, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 3, 14, 0, 4, 14, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 1, 17, 0, 4, 17, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 1, 1, 4, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 3, 4, 4, 4, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 3, 14, 4, 4, 14, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 1, 17, 4, 4, 17, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + return true; +} + +NetherBridgePieces::BridgeEndFiller::BridgeEndFiller(int genDepth, + Random* random, + BoundingBox* stairsBox, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; + selfSeed = random->nextInt(); +} + +NetherBridgePieces::BridgeEndFiller* +NetherBridgePieces::BridgeEndFiller::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new BridgeEndFiller(genDepth, random, box, direction); +} + +bool NetherBridgePieces::BridgeEndFiller::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + Random* selfRandom = new Random(selfSeed); + + // floor + for (int x = 0; x <= 4; x++) { + for (int y = 3; y <= 4; y++) { + int z = selfRandom->nextInt(8); + generateBox(level, chunkBB, x, y, 0, x, y, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + } + } + + // hand rails + { + int z = selfRandom->nextInt(8); + generateBox(level, chunkBB, 0, 5, 0, 0, 5, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + } + { + int z = selfRandom->nextInt(8); + generateBox(level, chunkBB, 4, 5, 0, 4, 5, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + } + + // supports + for (int x = 0; x <= 4; x++) { + int z = selfRandom->nextInt(5); + generateBox(level, chunkBB, x, 2, 0, x, 2, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + } + for (int x = 0; x <= 4; x++) { + for (int y = 0; y <= 1; y++) { + int z = selfRandom->nextInt(3); + generateBox(level, chunkBB, x, y, 0, x, y, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + } + } + + delete selfRandom; + + return true; +} + +NetherBridgePieces::BridgeCrossing::BridgeCrossing(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +NetherBridgePieces::BridgeCrossing::BridgeCrossing(Random* random, int west, + int north) + : NetherBridgePiece(0) { + orientation = random->nextInt(4); + + switch (orientation) { + case Direction::NORTH: + case Direction::SOUTH: + boundingBox = new BoundingBox(west, 64, north, west + width - 1, + 64 + height - 1, north + depth - 1); + break; + default: + boundingBox = new BoundingBox(west, 64, north, west + depth - 1, + 64 + height - 1, north + width - 1); + break; + } +} + +void NetherBridgePieces::BridgeCrossing::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 8, 3, false); + generateChildLeft((StartPiece*)startPiece, pieces, random, 3, 8, false); + generateChildRight((StartPiece*)startPiece, pieces, random, 3, 8, false); +} + +NetherBridgePieces::BridgeCrossing* +NetherBridgePieces::BridgeCrossing::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -8, -3, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new BridgeCrossing(genDepth, random, box, direction); +} + +bool NetherBridgePieces::BridgeCrossing::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 7, 3, 0, 11, 4, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 3, 7, 18, 4, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 8, 5, 0, 10, 7, 18, 0, 0, false); + generateBox(level, chunkBB, 0, 5, 8, 18, 7, 10, 0, 0, false); + // hand rails + generateBox(level, chunkBB, 7, 5, 0, 7, 5, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 7, 5, 11, 7, 5, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 0, 11, 5, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 11, 11, 5, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 5, 7, 7, 5, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 7, 18, 5, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 5, 11, 7, 5, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 11, 18, 5, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + generateBox(level, chunkBB, 7, 2, 0, 11, 2, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 7, 2, 13, 11, 2, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 7, 0, 0, 11, 1, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 7, 0, 15, 11, 1, 18, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + for (int x = 7; x <= 11; x++) { + for (int z = 0; z <= 2; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 18 - z, + chunkBB); + } + } + + generateBox(level, chunkBB, 0, 2, 7, 5, 2, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 13, 2, 7, 18, 2, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 0, 7, 3, 1, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 15, 0, 7, 18, 1, 11, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + for (int x = 0; x <= 2; x++) { + for (int z = 7; z <= 11; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, 18 - x, -1, z, + chunkBB); + } + } + + return true; +} + +NetherBridgePieces::StartPiece::StartPiece(Random* random, int west, int north, + Level* level) + : BridgeCrossing(random, west, north) { + isLibraryAdded = false; + previousPiece = NULL; + m_level = level; + + for (int i = 0; i < BRIDGE_PIECEWEIGHTS_COUNT; i++) { + PieceWeight* piece = bridgePieceWeights[i]; + piece->placeCount = 0; + availableBridgePieces.push_back(piece); + } + + for (int i = 0; i < CASTLE_PIECEWEIGHTS_COUNT; i++) { + PieceWeight* piece = castlePieceWeights[i]; + + piece->placeCount = 0; + availableCastlePieces.push_back(piece); + } +} + +NetherBridgePieces::RoomCrossing::RoomCrossing(int genDepth, Random* random, + BoundingBox* box, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = box; +} + +void NetherBridgePieces::RoomCrossing::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 2, 0, false); + generateChildLeft((StartPiece*)startPiece, pieces, random, 0, 2, false); + generateChildRight((StartPiece*)startPiece, pieces, random, 0, 2, false); +} + +NetherBridgePieces::RoomCrossing* NetherBridgePieces::RoomCrossing::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new RoomCrossing(genDepth, random, box, direction); +} + +bool NetherBridgePieces::RoomCrossing::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, width - 1, 1, depth - 1, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 6, 7, 6, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 2, 0, 1, 6, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 6, 1, 6, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 2, 0, 6, 6, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 2, 6, 6, 6, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 0, 0, 6, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 5, 0, 6, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 2, 0, 6, 6, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 2, 5, 6, 6, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // entries + generateBox(level, chunkBB, 2, 6, 0, 4, 6, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 0, 4, 5, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 2, 6, 6, 4, 6, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 6, 4, 5, 6, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 6, 2, 0, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 5, 2, 0, 5, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 6, 6, 2, 6, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 5, 2, 6, 5, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + for (int x = 0; x <= 6; x++) { + for (int z = 0; z <= 6; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::StairsRoom::StairsRoom(int genDepth, Random* random, + BoundingBox* box, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = box; +} + +void NetherBridgePieces::StairsRoom::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildRight((StartPiece*)startPiece, pieces, random, 6, 2, false); +} + +NetherBridgePieces::StairsRoom* NetherBridgePieces::StairsRoom::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new StairsRoom(genDepth, random, box, direction); +} + +bool NetherBridgePieces::StairsRoom::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, width - 1, 1, depth - 1, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 6, 10, 6, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 2, 0, 1, 8, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 2, 0, 6, 8, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 1, 0, 8, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 2, 1, 6, 8, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 2, 6, 5, 8, 6, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // wall decorations + generateBox(level, chunkBB, 0, 3, 2, 0, 5, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 6, 3, 2, 6, 5, 2, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 6, 3, 4, 6, 5, 4, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // stair + placeBlock(level, Tile::netherBrick_Id, 0, 5, 2, 5, chunkBB); + generateBox(level, chunkBB, 4, 2, 5, 4, 3, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 3, 2, 5, 3, 4, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 2, 5, 2, 5, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 2, 5, 1, 6, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // top floor + generateBox(level, chunkBB, 1, 7, 1, 5, 7, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 8, 2, 6, 8, 4, 0, 0, false); + + // entries + generateBox(level, chunkBB, 2, 6, 0, 4, 8, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 0, 4, 5, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + for (int x = 0; x <= 6; x++) { + for (int z = 0; z <= 6; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::MonsterThrone::MonsterThrone(int genDepth, Random* random, + BoundingBox* box, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = box; + hasPlacedMobSpawner = false; +} + +NetherBridgePieces::MonsterThrone* +NetherBridgePieces::MonsterThrone::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new MonsterThrone(genDepth, random, box, direction); +} + +bool NetherBridgePieces::MonsterThrone::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + generateBox(level, chunkBB, 0, 2, 0, 6, 7, 7, 0, 0, false); + + // floors + generateBox(level, chunkBB, 1, 0, 0, 5, 1, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 2, 1, 5, 2, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 3, 2, 5, 3, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 4, 3, 5, 4, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // rails + generateBox(level, chunkBB, 1, 2, 0, 1, 4, 2, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 2, 0, 5, 4, 2, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 5, 2, 1, 5, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 5, 2, 5, 5, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 5, 3, 0, 5, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 5, 3, 6, 5, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 5, 8, 5, 5, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + placeBlock(level, Tile::netherFence_Id, 0, 1, 6, 3, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 5, 6, 3, chunkBB); + generateBox(level, chunkBB, 0, 6, 3, 0, 6, 8, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 6, 6, 3, 6, 6, 8, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 1, 6, 8, 5, 7, 8, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 2, 8, 8, 4, 8, 8, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + if (!hasPlacedMobSpawner) { + int y = getWorldY(5), x = getWorldX(3, 5), z = getWorldZ(3, 5); + if (chunkBB->isInside(x, y, z)) { + hasPlacedMobSpawner = true; + level->setTile(x, y, z, Tile::mobSpawner_Id); + std::shared_ptr entity = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (entity != NULL) entity->setEntityId(L"Blaze"); + } + } + + for (int x = 0; x <= 6; x++) { + for (int z = 0; z <= 6; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleEntrance::CastleEntrance(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleEntrance::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 5, 3, true); +} + +NetherBridgePieces::CastleEntrance* +NetherBridgePieces::CastleEntrance::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleEntrance(genDepth, random, box, direction); +} + +bool NetherBridgePieces::CastleEntrance::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 3, 0, 12, 4, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 5, 0, 12, 13, 12, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 5, 0, 1, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 0, 12, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 11, 4, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 8, 5, 11, 10, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 9, 11, 7, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 0, 4, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 8, 5, 0, 10, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 9, 0, 7, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // roof + generateBox(level, chunkBB, 2, 11, 2, 10, 12, 10, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // entrance decoration + generateBox(level, chunkBB, 5, 8, 0, 7, 8, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // wall decorations + for (int i = 1; i <= 11; i += 2) { + generateBox(level, chunkBB, i, 10, 0, i, 11, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, i, 10, 12, i, 11, 12, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 10, i, 0, 11, i, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 12, 10, i, 12, 11, i, Tile::netherFence_Id, + Tile::netherFence_Id, false); + placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 0, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 12, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, 0, 13, i, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, 12, 13, i, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 12, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, i + 1, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 12, 13, i + 1, chunkBB); + } + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 12, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 12, 13, 0, chunkBB); + + // inside decorations + for (int z = 3; z <= 9; z += 2) { + generateBox(level, chunkBB, 1, 7, z, 1, 8, z, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 11, 7, z, 11, 8, z, Tile::netherFence_Id, + Tile::netherFence_Id, false); + } + + // supports + generateBox(level, chunkBB, 4, 2, 0, 8, 2, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 4, 12, 2, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + generateBox(level, chunkBB, 4, 0, 0, 8, 1, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 0, 9, 8, 1, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 0, 4, 3, 1, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 9, 0, 4, 12, 1, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + for (int x = 4; x <= 8; x++) { + for (int z = 0; z <= 2; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 12 - z, + chunkBB); + } + } + for (int x = 0; x <= 2; x++) { + for (int z = 4; z <= 8; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, 12 - x, -1, z, + chunkBB); + } + } + + // lava well + generateBox(level, chunkBB, 5, 5, 5, 7, 5, 7, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 1, 6, 6, 4, 6, 0, 0, false); + placeBlock(level, Tile::netherBrick_Id, 0, 6, 0, 6, chunkBB); + placeBlock(level, Tile::lava_Id, 0, 6, 5, 6, chunkBB); + // tick lava well + int x = getWorldX(6, 6); + int y = getWorldY(5); + int z = getWorldZ(6, 6); + if (chunkBB->isInside(x, y, z)) { + level->setInstaTick(true); + Tile::tiles[Tile::lava_Id]->tick(level, x, y, z, random); + level->setInstaTick(false); + } + + return true; +} + +NetherBridgePieces::CastleStalkRoom::CastleStalkRoom(int genDepth, + Random* random, + BoundingBox* stairsBox, + int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleStalkRoom::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 5, 3, true); + generateChildForward((StartPiece*)startPiece, pieces, random, 5, 11, true); +} + +NetherBridgePieces::CastleStalkRoom* +NetherBridgePieces::CastleStalkRoom::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleStalkRoom(genDepth, random, box, direction); +} + +bool NetherBridgePieces::CastleStalkRoom::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 3, 0, 12, 4, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 5, 0, 12, 13, 12, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 5, 0, 1, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 11, 5, 0, 12, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 11, 4, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 8, 5, 11, 10, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 9, 11, 7, 12, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 0, 4, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 8, 5, 0, 10, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 5, 9, 0, 7, 12, 1, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // roof + generateBox(level, chunkBB, 2, 11, 2, 10, 12, 10, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // wall decorations + for (int i = 1; i <= 11; i += 2) { + generateBox(level, chunkBB, i, 10, 0, i, 11, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, i, 10, 12, i, 11, 12, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 10, i, 0, 11, i, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 12, 10, i, 12, 11, i, Tile::netherFence_Id, + Tile::netherFence_Id, false); + placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 0, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, i, 13, 12, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, 0, 13, i, chunkBB); + placeBlock(level, Tile::netherBrick_Id, 0, 12, 13, i, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, i + 1, 13, 12, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, i + 1, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 12, 13, i + 1, chunkBB); + } + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 12, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 0, 13, 0, chunkBB); + placeBlock(level, Tile::netherFence_Id, 0, 12, 13, 0, chunkBB); + + // inside decorations + for (int z = 3; z <= 9; z += 2) { + generateBox(level, chunkBB, 1, 7, z, 1, 8, z, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 11, 7, z, 11, 8, z, Tile::netherFence_Id, + Tile::netherFence_Id, false); + } + + // inside stair + int stairOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 3); + for (int i = 0; i <= 6; i++) { + int z = i + 4; + for (int x = 5; x <= 7; x++) { + placeBlock(level, Tile::stairs_netherBricks_Id, stairOrientation, x, + 5 + i, z, chunkBB); + } + if (z >= 5 && z <= 8) { + generateBox(level, chunkBB, 5, 5, z, 7, i + 4, z, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + } else if (z >= 9 && z <= 10) { + generateBox(level, chunkBB, 5, 8, z, 7, i + 4, z, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + } + if (i >= 1) { + generateBox(level, chunkBB, 5, 6 + i, z, 7, 9 + i, z, 0, 0, false); + } + } + for (int x = 5; x <= 7; x++) { + placeBlock(level, Tile::stairs_netherBricks_Id, stairOrientation, x, 12, + 11, chunkBB); + } + generateBox(level, chunkBB, 5, 6, 7, 5, 7, 7, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 7, 6, 7, 7, 7, 7, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 5, 13, 12, 7, 13, 12, 0, 0, false); + + // farmland catwalks + generateBox(level, chunkBB, 2, 5, 2, 3, 5, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 9, 3, 5, 10, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 2, 5, 4, 2, 5, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 9, 5, 2, 10, 5, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 9, 5, 9, 10, 5, 10, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 10, 5, 4, 10, 5, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + int eastOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 0); + int westOrientation = getOrientationData(Tile::stairs_netherBricks_Id, 1); + placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 2, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 3, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 9, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, westOrientation, 4, 5, 10, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 2, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 3, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 9, + chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, eastOrientation, 8, 5, 10, + chunkBB); + + // farmlands + generateBox(level, chunkBB, 3, 4, 4, 4, 4, 8, Tile::hellSand_Id, + Tile::hellSand_Id, false); + generateBox(level, chunkBB, 8, 4, 4, 9, 4, 8, Tile::hellSand_Id, + Tile::hellSand_Id, false); + generateBox(level, chunkBB, 3, 5, 4, 4, 5, 8, Tile::netherStalk_Id, + Tile::netherStalk_Id, false); + generateBox(level, chunkBB, 8, 5, 4, 9, 5, 8, Tile::netherStalk_Id, + Tile::netherStalk_Id, false); + + // supports + generateBox(level, chunkBB, 4, 2, 0, 8, 2, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 4, 12, 2, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + generateBox(level, chunkBB, 4, 0, 0, 8, 1, 3, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 0, 9, 8, 1, 12, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 0, 4, 3, 1, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 9, 0, 4, 12, 1, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + for (int x = 4; x <= 8; x++) { + for (int z = 0; z <= 2; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, 12 - z, + chunkBB); + } + } + for (int x = 0; x <= 2; x++) { + for (int z = 4; z <= 8; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + fillColumnDown(level, Tile::netherBrick_Id, 0, 12 - x, -1, z, + chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleSmallCorridorPiece::CastleSmallCorridorPiece( + int genDepth, Random* random, BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleSmallCorridorPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 1, 0, true); +} + +NetherBridgePieces::CastleSmallCorridorPiece* +NetherBridgePieces::CastleSmallCorridorPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleSmallCorridorPiece(genDepth, random, box, direction); +} + +bool NetherBridgePieces::CastleSmallCorridorPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 2, 0, 0, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 2, 0, 4, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 3, 1, 0, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 3, 3, 0, 4, 3, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 3, 1, 4, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 3, 3, 4, 4, 3, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // roof + generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 4; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleSmallCorridorCrossingPiece:: + CastleSmallCorridorCrossingPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleSmallCorridorCrossingPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 1, 0, true); + generateChildLeft((StartPiece*)startPiece, pieces, random, 0, 1, true); + generateChildRight((StartPiece*)startPiece, pieces, random, 0, 1, true); +} + +NetherBridgePieces::CastleSmallCorridorCrossingPiece* +NetherBridgePieces::CastleSmallCorridorCrossingPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleSmallCorridorCrossingPiece(genDepth, random, box, + direction); +} + +bool NetherBridgePieces::CastleSmallCorridorCrossingPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 2, 0, 0, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 2, 0, 4, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 4, 0, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 2, 4, 4, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // roof + generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 4; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleSmallCorridorRightTurnPiece:: + CastleSmallCorridorRightTurnPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleSmallCorridorRightTurnPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildRight((StartPiece*)startPiece, pieces, random, 0, 1, true); +} + +NetherBridgePieces::CastleSmallCorridorRightTurnPiece* +NetherBridgePieces::CastleSmallCorridorRightTurnPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleSmallCorridorRightTurnPiece(genDepth, random, box, + direction); +} + +bool NetherBridgePieces::CastleSmallCorridorRightTurnPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); + + // walls + generateBox(level, chunkBB, 0, 2, 0, 0, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 0, 3, 1, 0, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 3, 3, 0, 4, 3, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + generateBox(level, chunkBB, 4, 2, 0, 4, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + generateBox(level, chunkBB, 1, 2, 4, 4, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 3, 4, 1, 4, 4, Tile::netherFence_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 3, 3, 4, 3, 4, 4, Tile::netherFence_Id, + Tile::netherBrick_Id, false); + + // roof + generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 4; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleSmallCorridorLeftTurnPiece:: + CastleSmallCorridorLeftTurnPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildLeft((StartPiece*)startPiece, pieces, random, 0, 1, true); +} + +NetherBridgePieces::CastleSmallCorridorLeftTurnPiece* +NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleSmallCorridorLeftTurnPiece(genDepth, random, box, + direction); +} + +bool NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); + + // walls + generateBox(level, chunkBB, 4, 2, 0, 4, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, 3, 1, 4, 4, 1, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, 3, 3, 4, 4, 3, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + generateBox(level, chunkBB, 0, 2, 0, 0, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + generateBox(level, chunkBB, 0, 2, 4, 3, 5, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 3, 4, 1, 4, 4, Tile::netherFence_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 3, 3, 4, 3, 4, 4, Tile::netherFence_Id, + Tile::netherBrick_Id, false); + + // roof + generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // supports + for (int x = 0; x <= 4; x++) { + for (int z = 0; z <= 4; z++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleCorridorStairsPiece::CastleCorridorStairsPiece( + int genDepth, Random* random, BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleCorridorStairsPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateChildForward((StartPiece*)startPiece, pieces, random, 1, 0, true); +} + +NetherBridgePieces::CastleCorridorStairsPiece* +NetherBridgePieces::CastleCorridorStairsPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -7, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleCorridorStairsPiece(genDepth, random, box, direction); +} + +bool NetherBridgePieces::CastleCorridorStairsPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // generate stairs + int stairsData = getOrientationData(Tile::stairs_netherBricks_Id, 2); + for (int step = 0; step <= 9; step++) { + int floor = std::max(1, 7 - step); + int roof = std::min(std::max(floor + 5, 14 - step), 13); + int z = step; + + // floor + generateBox(level, chunkBB, 0, 0, z, 4, floor, z, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 1, floor + 1, z, 3, roof - 1, z, 0, 0, + false); + if (step <= 6) { + placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 1, + floor + 1, z, chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 2, + floor + 1, z, chunkBB); + placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 3, + floor + 1, z, chunkBB); + } + // roof + generateBox(level, chunkBB, 0, roof, z, 4, roof, z, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + // walls + generateBox(level, chunkBB, 0, floor + 1, z, 0, roof - 1, z, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 4, floor + 1, z, 4, roof - 1, z, + Tile::netherBrick_Id, Tile::netherBrick_Id, false); + if ((step & 1) == 0) { + generateBox(level, chunkBB, 0, floor + 2, z, 0, floor + 3, z, + Tile::netherFence_Id, Tile::netherFence_Id, false); + generateBox(level, chunkBB, 4, floor + 2, z, 4, floor + 3, z, + Tile::netherFence_Id, Tile::netherFence_Id, false); + } + + // supports + for (int x = 0; x <= 4; x++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; +} + +NetherBridgePieces::CastleCorridorTBalconyPiece::CastleCorridorTBalconyPiece( + int genDepth, Random* random, BoundingBox* stairsBox, int direction) + : NetherBridgePiece(genDepth) { + orientation = direction; + boundingBox = stairsBox; +} + +void NetherBridgePieces::CastleCorridorTBalconyPiece::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + int zOff = 1; + // compensate for weird negative-facing behaviour + if (orientation == Direction::WEST || orientation == Direction::NORTH) { + zOff = 5; + } + + generateChildLeft((StartPiece*)startPiece, pieces, random, 0, zOff, + random->nextInt(8) > 0); + generateChildRight((StartPiece*)startPiece, pieces, random, 0, zOff, + random->nextInt(8) > 0); +} + +NetherBridgePieces::CastleCorridorTBalconyPiece* +NetherBridgePieces::CastleCorridorTBalconyPiece::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -3, 0, 0, + width, height, depth, direction); + + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((NetherBridgePieces::StartPiece*)pieces->front()); + + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } + + return new CastleCorridorTBalconyPiece(genDepth, random, box, direction); +} + +bool NetherBridgePieces::CastleCorridorTBalconyPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // floor + generateBox(level, chunkBB, 0, 0, 0, 8, 1, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + // room air + generateBox(level, chunkBB, 0, 2, 0, 8, 5, 8, 0, 0, false); + // corridor roof + generateBox(level, chunkBB, 0, 6, 0, 8, 6, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + + // inside walls + generateBox(level, chunkBB, 0, 2, 0, 2, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 2, 0, 8, 5, 0, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 3, 0, 1, 4, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 7, 3, 0, 7, 4, 0, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // balcony floor + generateBox(level, chunkBB, 0, 2, 4, 8, 2, 8, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 1, 4, 2, 2, 4, 0, 0, false); + generateBox(level, chunkBB, 6, 1, 4, 7, 2, 4, 0, 0, false); + + // hand rails + generateBox(level, chunkBB, 0, 3, 8, 8, 3, 8, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 0, 3, 6, 0, 3, 7, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 8, 3, 6, 8, 3, 7, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // balcony walls + generateBox(level, chunkBB, 0, 3, 4, 0, 5, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 8, 3, 4, 8, 5, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 3, 5, 2, 5, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 6, 3, 5, 7, 5, 5, Tile::netherBrick_Id, + Tile::netherBrick_Id, false); + generateBox(level, chunkBB, 1, 4, 5, 1, 5, 5, Tile::netherFence_Id, + Tile::netherFence_Id, false); + generateBox(level, chunkBB, 7, 4, 5, 7, 5, 5, Tile::netherFence_Id, + Tile::netherFence_Id, false); + + // supports + for (int z = 0; z <= 5; z++) { + for (int x = 0; x <= 8; x++) { + fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); + } + } + + return true; } - -bool NetherBridgePieces::CastleSmallCorridorLeftTurnPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, 4, 1, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 4, 5, 4, 0, 0, false); - - // walls - generateBox(level, chunkBB, 4, 2, 0, 4, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, 3, 1, 4, 4, 1, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, 3, 3, 4, 4, 3, Tile::netherFence_Id, Tile::netherFence_Id, false); - - generateBox(level, chunkBB, 0, 2, 0, 0, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - generateBox(level, chunkBB, 0, 2, 4, 3, 5, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 3, 4, 1, 4, 4, Tile::netherFence_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 3, 3, 4, 3, 4, 4, Tile::netherFence_Id, Tile::netherBrick_Id, false); - - // roof - generateBox(level, chunkBB, 0, 6, 0, 4, 6, 4, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // supports - for (int x = 0; x <= 4; x++) - { - for (int z = 0; z <= 4; z++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - -NetherBridgePieces::CastleCorridorStairsPiece::CastleCorridorStairsPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleCorridorStairsPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateChildForward((StartPiece *) startPiece, pieces, random, 1, 0, true); -} - -NetherBridgePieces::CastleCorridorStairsPiece *NetherBridgePieces::CastleCorridorStairsPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -7, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleCorridorStairsPiece(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleCorridorStairsPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // generate stairs - int stairsData = getOrientationData(Tile::stairs_netherBricks_Id, 2); - for (int step = 0; step <= 9; step++) - { - int floor = std::max(1, 7 - step); - int roof = std::min(std::max(floor + 5, 14 - step), 13); - int z = step; - - // floor - generateBox(level, chunkBB, 0, 0, z, 4, floor, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 1, floor + 1, z, 3, roof - 1, z, 0, 0, false); - if (step <= 6) - { - placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 1, floor + 1, z, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 2, floor + 1, z, chunkBB); - placeBlock(level, Tile::stairs_netherBricks_Id, stairsData, 3, floor + 1, z, chunkBB); - } - // roof - generateBox(level, chunkBB, 0, roof, z, 4, roof, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // walls - generateBox(level, chunkBB, 0, floor + 1, z, 0, roof - 1, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 4, floor + 1, z, 4, roof - 1, z, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - if ((step & 1) == 0) - { - generateBox(level, chunkBB, 0, floor + 2, z, 0, floor + 3, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 4, floor + 2, z, 4, floor + 3, z, Tile::netherFence_Id, Tile::netherFence_Id, false); - } - - // supports - for (int x = 0; x <= 4; x++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - - return true; -} - - -NetherBridgePieces::CastleCorridorTBalconyPiece::CastleCorridorTBalconyPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : NetherBridgePiece(genDepth) -{ - orientation = direction; - boundingBox = stairsBox; -} - -void NetherBridgePieces::CastleCorridorTBalconyPiece::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - int zOff = 1; - // compensate for weird negative-facing behaviour - if (orientation == Direction::WEST || orientation == Direction::NORTH) - { - zOff = 5; - } - - generateChildLeft((StartPiece *) startPiece, pieces, random, 0, zOff, random->nextInt(8) > 0); - generateChildRight((StartPiece *) startPiece, pieces, random, 0, zOff, random->nextInt(8) > 0); -} - -NetherBridgePieces::CastleCorridorTBalconyPiece *NetherBridgePieces::CastleCorridorTBalconyPiece::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -3, 0, 0, width, height, depth, direction); - - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); - - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new CastleCorridorTBalconyPiece(genDepth, random, box, direction); -} - -bool NetherBridgePieces::CastleCorridorTBalconyPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // floor - generateBox(level, chunkBB, 0, 0, 0, 8, 1, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - // room air - generateBox(level, chunkBB, 0, 2, 0, 8, 5, 8, 0, 0, false); - // corridor roof - generateBox(level, chunkBB, 0, 6, 0, 8, 6, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - - // inside walls - generateBox(level, chunkBB, 0, 2, 0, 2, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 2, 0, 8, 5, 0, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 3, 0, 1, 4, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 7, 3, 0, 7, 4, 0, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // balcony floor - generateBox(level, chunkBB, 0, 2, 4, 8, 2, 8, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 1, 4, 2, 2, 4, 0, 0, false); - generateBox(level, chunkBB, 6, 1, 4, 7, 2, 4, 0, 0, false); - - // hand rails - generateBox(level, chunkBB, 0, 3, 8, 8, 3, 8, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 0, 3, 6, 0, 3, 7, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 8, 3, 6, 8, 3, 7, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // balcony walls - generateBox(level, chunkBB, 0, 3, 4, 0, 5, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 8, 3, 4, 8, 5, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 3, 5, 2, 5, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 6, 3, 5, 7, 5, 5, Tile::netherBrick_Id, Tile::netherBrick_Id, false); - generateBox(level, chunkBB, 1, 4, 5, 1, 5, 5, Tile::netherFence_Id, Tile::netherFence_Id, false); - generateBox(level, chunkBB, 7, 4, 5, 7, 5, 5, Tile::netherFence_Id, Tile::netherFence_Id, false); - - // supports - for (int z = 0; z <= 5; z++) - { - for (int x = 0; x <= 8; x++) - { - fillColumnDown(level, Tile::netherBrick_Id, 0, x, -1, z, chunkBB); - } - } - - return true; -} - - diff --git a/Minecraft.World/WorldGen/Structures/NetherBridgePieces.h b/Minecraft.World/WorldGen/Structures/NetherBridgePieces.h index a31c97c24..ac2ba4590 100644 --- a/Minecraft.World/WorldGen/Structures/NetherBridgePieces.h +++ b/Minecraft.World/WorldGen/Structures/NetherBridgePieces.h @@ -1,343 +1,449 @@ #pragma once #include "StructurePiece.h" -class NetherBridgePieces -{ +class NetherBridgePieces { private: - static const int MAX_DEPTH = 30; + static const int MAX_DEPTH = 30; // the dungeon starts at 64 and traverses downwards to this point static const int LOWEST_Y_POSITION = 10; - // 4J - added to replace use of Class within this class - enum EPieceClass - { - EPieceClass_BridgeStraight, - EPieceClass_BridgeEndFiller, - EPieceClass_BridgeCrossing, - EPieceClass_RoomCrossing, - EPieceClass_StairsRoom, - EPieceClass_MonsterThrone, - EPieceClass_CastleEntrance, - EPieceClass_CastleStalkRoom, - EPieceClass_CastleSmallCorridorPiece, - EPieceClass_CastleSmallCorridorCrossingPiece, - EPieceClass_CastleSmallCorridorRightTurnPiece, - EPieceClass_CastleSmallCorridorLeftTurnPiece, - EPieceClass_CastleCorridorStairsPiece, - EPieceClass_CastleCorridorTBalconyPiece - }; + // 4J - added to replace use of Class within + // this class + enum EPieceClass { + EPieceClass_BridgeStraight, + EPieceClass_BridgeEndFiller, + EPieceClass_BridgeCrossing, + EPieceClass_RoomCrossing, + EPieceClass_StairsRoom, + EPieceClass_MonsterThrone, + EPieceClass_CastleEntrance, + EPieceClass_CastleStalkRoom, + EPieceClass_CastleSmallCorridorPiece, + EPieceClass_CastleSmallCorridorCrossingPiece, + EPieceClass_CastleSmallCorridorRightTurnPiece, + EPieceClass_CastleSmallCorridorLeftTurnPiece, + EPieceClass_CastleCorridorStairsPiece, + EPieceClass_CastleCorridorTBalconyPiece + }; - class PieceWeight - { - public: + class PieceWeight { + public: EPieceClass pieceClass; const int weight; int placeCount; int maxPlaceCount; bool allowInRow; - PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount, bool allowInRow); + PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount, + bool allowInRow); PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount); bool doPlace(int depth); bool isValid(); }; - static const int BRIDGE_PIECEWEIGHTS_COUNT = 6; - static const int CASTLE_PIECEWEIGHTS_COUNT = 7; - static NetherBridgePieces::PieceWeight *bridgePieceWeights[BRIDGE_PIECEWEIGHTS_COUNT]; - static NetherBridgePieces::PieceWeight *castlePieceWeights[CASTLE_PIECEWEIGHTS_COUNT]; + static const int BRIDGE_PIECEWEIGHTS_COUNT = 6; + static const int CASTLE_PIECEWEIGHTS_COUNT = 7; + static NetherBridgePieces::PieceWeight* + bridgePieceWeights[BRIDGE_PIECEWEIGHTS_COUNT]; + static NetherBridgePieces::PieceWeight* + castlePieceWeights[CASTLE_PIECEWEIGHTS_COUNT]; private: - class NetherBridgePiece; - static NetherBridgePiece *findAndCreateBridgePieceFactory(NetherBridgePieces::PieceWeight *piece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); + class NetherBridgePiece; + static NetherBridgePiece* findAndCreateBridgePieceFactory( + NetherBridgePieces::PieceWeight* piece, + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int depth); /** - * + * * */ public: - class StartPiece; + class StartPiece; + private: + class NetherBridgePiece : public StructurePiece { + protected: + NetherBridgePiece(int genDepth); - class NetherBridgePiece : public StructurePiece - { - protected: - NetherBridgePiece(int genDepth); - private: - int updatePieceWeight(std::list *currentPieces); + private: + int updatePieceWeight(std::list* currentPieces); - NetherBridgePiece *generatePiece(StartPiece *startPiece, std::list *currentPieces, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - StructurePiece *generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth, bool isCastle); - protected: - StructurePiece *generateChildForward(StartPiece *startPiece, std::list *pieces, Random *random, int xOff, int yOff, bool isCastle); - StructurePiece *generateChildLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff, bool isCastle); - StructurePiece *generateChildRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff, bool isCastle); - - static bool isOkBox(BoundingBox *box, StartPiece *startRoom); // 4J added startRoom param - void generateLightPost(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z, int xOff, int zOff); - - void generateLightPostFacingRight(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z); - void generateLightPostFacingLeft(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z); - void generateLightPostFacingUp(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z); - void generateLightPostFacingDown(Level *level, Random *random, BoundingBox *chunkBB, int x, int y, int z); + NetherBridgePiece* generatePiece( + StartPiece* startPiece, + std::list* currentPieces, + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int depth); + StructurePiece* generateAndAddPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, + int footY, int footZ, int direction, + int depth, bool isCastle); + + protected: + StructurePiece* generateChildForward(StartPiece* startPiece, + std::list* pieces, + Random* random, int xOff, int yOff, + bool isCastle); + StructurePiece* generateChildLeft(StartPiece* startPiece, + std::list* pieces, + Random* random, int yOff, int zOff, + bool isCastle); + StructurePiece* generateChildRight(StartPiece* startPiece, + std::list* pieces, + Random* random, int yOff, int zOff, + bool isCastle); + + static bool isOkBox(BoundingBox* box, + StartPiece* startRoom); // 4J added startRoom param + void generateLightPost(Level* level, Random* random, + BoundingBox* chunkBB, int x, int y, int z, + int xOff, int zOff); + + void generateLightPostFacingRight(Level* level, Random* random, + BoundingBox* chunkBB, int x, int y, + int z); + void generateLightPostFacingLeft(Level* level, Random* random, + BoundingBox* chunkBB, int x, int y, + int z); + void generateLightPostFacingUp(Level* level, Random* random, + BoundingBox* chunkBB, int x, int y, + int z); + void generateLightPostFacingDown(Level* level, Random* random, + BoundingBox* chunkBB, int x, int y, + int z); }; /** - * + * * */ - class BridgeStraight : public NetherBridgePiece - { - private: - static const int width = 5; + class BridgeStraight : public NetherBridgePiece { + private: + static const int width = 5; static const int height = 10; static const int depth = 19; - public: - BridgeStraight(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static BridgeStraight *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + BridgeStraight(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static BridgeStraight* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; - class BridgeEndFiller : public NetherBridgePiece - { - private: - static const int width = 5; + class BridgeEndFiller : public NetherBridgePiece { + private: + static const int width = 5; static const int height = 10; static const int depth = 8; int selfSeed; - public: - BridgeEndFiller(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static BridgeEndFiller *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + BridgeEndFiller(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + static BridgeEndFiller* createPiece(std::list* pieces, + Random* random, int footX, + int footY, int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; - class BridgeCrossing : public NetherBridgePiece - { - private: - static const int width = 19; + class BridgeCrossing : public NetherBridgePiece { + private: + static const int width = 19; static const int height = 10; static const int depth = 19; - public: - BridgeCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - protected: - BridgeCrossing(Random *random, int west, int north); - public: - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static BridgeCrossing *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + BridgeCrossing(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + + protected: + BridgeCrossing(Random* random, int west, int north); + + public: + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static BridgeCrossing* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; public: - class StartPiece : public BridgeCrossing - { + class StartPiece : public BridgeCrossing { + public: + bool isLibraryAdded; + PieceWeight* previousPiece; + Level* m_level; - public: - bool isLibraryAdded; - PieceWeight *previousPiece; - Level *m_level; - - std::list availableBridgePieces; - std::list availableCastlePieces; + std::list availableBridgePieces; + std::list availableCastlePieces; // this queue is used so that the addChildren calls are // called in a random order - std::vector pendingChildren; - - StartPiece(Random *random, int west, int north, Level *level); // 4J Added level param + std::vector pendingChildren; + StartPiece(Random* random, int west, int north, + Level* level); // 4J Added level param }; private: - class RoomCrossing : public NetherBridgePiece - { - private: - static const int width = 7; + class RoomCrossing : public NetherBridgePiece { + private: + static const int width = 7; static const int height = 9; static const int depth = 7; - public: - RoomCrossing(int genDepth, Random *random, BoundingBox *box, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static RoomCrossing *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + RoomCrossing(int genDepth, Random* random, BoundingBox* box, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static RoomCrossing* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; - class StairsRoom : public NetherBridgePiece - { - private: - static const int width = 7; + class StairsRoom : public NetherBridgePiece { + private: + static const int width = 7; static const int height = 11; static const int depth = 7; - public: - StairsRoom(int genDepth, Random *random, BoundingBox *box, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static StairsRoom *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + StairsRoom(int genDepth, Random* random, BoundingBox* box, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static StairsRoom* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; - class MonsterThrone : public NetherBridgePiece - { - private: - static const int width = 7; + class MonsterThrone : public NetherBridgePiece { + private: + static const int width = 7; static const int height = 8; static const int depth = 9; bool hasPlacedMobSpawner; - public: - MonsterThrone(int genDepth, Random *random, BoundingBox *box, int direction); - static MonsterThrone *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + MonsterThrone(int genDepth, Random* random, BoundingBox* box, + int direction); + static MonsterThrone* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleEntrance : public NetherBridgePiece - { - private: - static const int width = 13; - static const int height = 14; - static const int depth = 13; - public: - CastleEntrance(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleEntrance *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; - - /** - * - * - */ - class CastleStalkRoom : public NetherBridgePiece - { - private: + class CastleEntrance : public NetherBridgePiece { + private: static const int width = 13; static const int height = 14; static const int depth = 13; - public: - CastleStalkRoom(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleStalkRoom *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + CastleEntrance(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleEntrance* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleSmallCorridorPiece : public NetherBridgePiece - { - private: + class CastleStalkRoom : public NetherBridgePiece { + private: + static const int width = 13; + static const int height = 14; + static const int depth = 13; + + public: + CastleStalkRoom(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleStalkRoom* createPiece(std::list* pieces, + Random* random, int footX, + int footY, int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; + + /** + * + * + */ + class CastleSmallCorridorPiece : public NetherBridgePiece { + private: static const int width = 5; static const int height = 7; static const int depth = 5; - public: - CastleSmallCorridorPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleSmallCorridorPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + CastleSmallCorridorPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleSmallCorridorPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleSmallCorridorCrossingPiece : public NetherBridgePiece - { - private: + class CastleSmallCorridorCrossingPiece : public NetherBridgePiece { + private: static const int width = 5; static const int height = 7; static const int depth = 5; - public: - CastleSmallCorridorCrossingPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleSmallCorridorCrossingPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + CastleSmallCorridorCrossingPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleSmallCorridorCrossingPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleSmallCorridorRightTurnPiece : public NetherBridgePiece - { - private: - static const int width = 5; - static const int height = 7; - static const int depth = 5; - - public: - CastleSmallCorridorRightTurnPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleSmallCorridorRightTurnPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + class CastleSmallCorridorRightTurnPiece : public NetherBridgePiece { + private: + static const int width = 5; + static const int height = 7; + static const int depth = 5; + public: + CastleSmallCorridorRightTurnPiece(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleSmallCorridorRightTurnPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleSmallCorridorLeftTurnPiece : public NetherBridgePiece - { - private: - static const int width = 5; - static const int height = 7; - static const int depth = 5; + class CastleSmallCorridorLeftTurnPiece : public NetherBridgePiece { + private: + static const int width = 5; + static const int height = 7; + static const int depth = 5; - public: - CastleSmallCorridorLeftTurnPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleSmallCorridorLeftTurnPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + CastleSmallCorridorLeftTurnPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleSmallCorridorLeftTurnPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleCorridorStairsPiece : public NetherBridgePiece - { - private: - static const int width = 5; - static const int height = 14; - static const int depth = 10; - - public: - CastleCorridorStairsPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleCorridorStairsPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + class CastleCorridorStairsPiece : public NetherBridgePiece { + private: + static const int width = 5; + static const int height = 14; + static const int depth = 10; + public: + CastleCorridorStairsPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleCorridorStairsPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class CastleCorridorTBalconyPiece : public NetherBridgePiece - { - private: + class CastleCorridorTBalconyPiece : public NetherBridgePiece { + private: static const int width = 9; static const int height = 7; static const int depth = 9; - public: - CastleCorridorTBalconyPiece(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static CastleCorridorTBalconyPiece *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + CastleCorridorTBalconyPiece(int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static CastleCorridorTBalconyPiece* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; }; diff --git a/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.cpp b/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.cpp index 54d3f607f..1bf46204d 100644 --- a/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.cpp +++ b/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.cpp @@ -7,531 +7,705 @@ #include "../../Util/WeighedTreasure.h" #include "ScatteredFeaturePieces.h" -ScatteredFeaturePieces::ScatteredFeaturePiece::ScatteredFeaturePiece(Random *random, int west, int floor, int north, int width, int height, int depth) : StructurePiece(0) -{ - heightPosition = -1; - this->width = width; - this->height = height; - this->depth = depth; +ScatteredFeaturePieces::ScatteredFeaturePiece::ScatteredFeaturePiece( + Random* random, int west, int floor, int north, int width, int height, + int depth) + : StructurePiece(0) { + heightPosition = -1; + this->width = width; + this->height = height; + this->depth = depth; - orientation = random->nextInt(4); + orientation = random->nextInt(4); - switch (orientation) - { - case Direction::NORTH: - case Direction::SOUTH: - boundingBox = new BoundingBox(west, floor, north, west + width - 1, floor + height - 1, north + depth - 1); - break; - default: - boundingBox = new BoundingBox(west, floor, north, west + depth - 1, floor + height - 1, north + width - 1); - break; - } + switch (orientation) { + case Direction::NORTH: + case Direction::SOUTH: + boundingBox = + new BoundingBox(west, floor, north, west + width - 1, + floor + height - 1, north + depth - 1); + break; + default: + boundingBox = + new BoundingBox(west, floor, north, west + depth - 1, + floor + height - 1, north + width - 1); + break; + } } -bool ScatteredFeaturePieces::ScatteredFeaturePiece::updateAverageGroundHeight(Level *level, BoundingBox *chunkBB, int offset) -{ - if (heightPosition >= 0) - { - return true; - } +bool ScatteredFeaturePieces::ScatteredFeaturePiece::updateAverageGroundHeight( + Level* level, BoundingBox* chunkBB, int offset) { + if (heightPosition >= 0) { + return true; + } - int total = 0; - int count = 0; - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) - { - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) - { - if (chunkBB->isInside(x, 64, z)) - { - total += std::max(level->getTopSolidBlock(x, z), level->dimension->getSpawnYPosition()); - count++; - } - } - } + int total = 0; + int count = 0; + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { + if (chunkBB->isInside(x, 64, z)) { + total += std::max(level->getTopSolidBlock(x, z), + level->dimension->getSpawnYPosition()); + count++; + } + } + } - if (count == 0) - { - return false; - } - heightPosition = total / count; - boundingBox->move(0, heightPosition - boundingBox->y0 + offset, 0); - return true; + if (count == 0) { + return false; + } + heightPosition = total / count; + boundingBox->move(0, heightPosition - boundingBox->y0 + offset, 0); + return true; } -WeighedTreasure *ScatteredFeaturePieces::DesertPyramidPiece::treasureItems[ScatteredFeaturePieces::DesertPyramidPiece::TREASURE_ITEMS_COUNT] = -{ - new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), - new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), - new WeighedTreasure(Item::goldIngot_Id, 0, 2, 7, 15), - new WeighedTreasure(Item::emerald_Id, 0, 1, 3, 2), - new WeighedTreasure(Item::bone_Id, 0, 4, 6, 20), - new WeighedTreasure(Item::rotten_flesh_Id, 0, 3, 7, 16), +WeighedTreasure* ScatteredFeaturePieces::DesertPyramidPiece::treasureItems + [ScatteredFeaturePieces::DesertPyramidPiece::TREASURE_ITEMS_COUNT] = { + new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), + new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), + new WeighedTreasure(Item::goldIngot_Id, 0, 2, 7, 15), + new WeighedTreasure(Item::emerald_Id, 0, 1, 3, 2), + new WeighedTreasure(Item::bone_Id, 0, 4, 6, 20), + new WeighedTreasure(Item::rotten_flesh_Id, 0, 3, 7, 16), }; -ScatteredFeaturePieces::DesertPyramidPiece::DesertPyramidPiece(Random *random, int west, int north) : ScatteredFeaturePiece(random, west, 64, north, 21, 15, 21) -{ - hasPlacedChest[0] = false; - hasPlacedChest[1] = false; - hasPlacedChest[2] = false; - hasPlacedChest[3] = false; +ScatteredFeaturePieces::DesertPyramidPiece::DesertPyramidPiece(Random* random, + int west, + int north) + : ScatteredFeaturePiece(random, west, 64, north, 21, 15, 21) { + hasPlacedChest[0] = false; + hasPlacedChest[1] = false; + hasPlacedChest[2] = false; + hasPlacedChest[3] = false; } -bool ScatteredFeaturePieces::DesertPyramidPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // pyramid - generateBox(level, chunkBB, 0, -4, 0, width - 1, 0, depth - 1, Tile::sandStone_Id, Tile::sandStone_Id, false); - for (int pos = 1; pos <= 9; pos++) - { - generateBox(level, chunkBB, pos, pos, pos, width - 1 - pos, pos, depth - 1 - pos, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, pos + 1, pos, pos + 1, width - 2 - pos, pos, depth - 2 - pos, 0, 0, false); - } - for (int x = 0; x < width; x++) - { - for (int z = 0; z < depth; z++) - { - fillColumnDown(level, Tile::sandStone_Id, 0, x, -5, z, chunkBB); - } - } +bool ScatteredFeaturePieces::DesertPyramidPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + // pyramid + generateBox(level, chunkBB, 0, -4, 0, width - 1, 0, depth - 1, + Tile::sandStone_Id, Tile::sandStone_Id, false); + for (int pos = 1; pos <= 9; pos++) { + generateBox(level, chunkBB, pos, pos, pos, width - 1 - pos, pos, + depth - 1 - pos, Tile::sandStone_Id, Tile::sandStone_Id, + false); + generateBox(level, chunkBB, pos + 1, pos, pos + 1, width - 2 - pos, pos, + depth - 2 - pos, 0, 0, false); + } + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + fillColumnDown(level, Tile::sandStone_Id, 0, x, -5, z, chunkBB); + } + } - int stairsNorth = getOrientationData(Tile::stairs_sandstone_Id, 3); - int stairsSouth = getOrientationData(Tile::stairs_sandstone_Id, 2); - int stairsEast = getOrientationData(Tile::stairs_sandstone_Id, 0); - int stairsWest = getOrientationData(Tile::stairs_sandstone_Id, 1); - int baseDecoColor = ~DyePowderItem::ORANGE & 0xf; - int blue = ~DyePowderItem::BLUE & 0xf; + int stairsNorth = getOrientationData(Tile::stairs_sandstone_Id, 3); + int stairsSouth = getOrientationData(Tile::stairs_sandstone_Id, 2); + int stairsEast = getOrientationData(Tile::stairs_sandstone_Id, 0); + int stairsWest = getOrientationData(Tile::stairs_sandstone_Id, 1); + int baseDecoColor = ~DyePowderItem::ORANGE & 0xf; + int blue = ~DyePowderItem::BLUE & 0xf; - // towers - generateBox(level, chunkBB, 0, 0, 0, 4, 9, 4, Tile::sandStone_Id, 0, false); - generateBox(level, chunkBB, 1, 10, 1, 3, 10, 3, Tile::sandStone_Id, Tile::sandStone_Id, false); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 10, 0, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsSouth, 2, 10, 4, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, 0, 10, 2, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, 4, 10, 2, chunkBB); - generateBox(level, chunkBB, width - 5, 0, 0, width - 1, 9, 4, Tile::sandStone_Id, 0, false); - generateBox(level, chunkBB, width - 4, 10, 1, width - 2, 10, 3, Tile::sandStone_Id, Tile::sandStone_Id, false); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 10, 0, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsSouth, width - 3, 10, 4, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, width - 5, 10, 2, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, width - 1, 10, 2, chunkBB); + // towers + generateBox(level, chunkBB, 0, 0, 0, 4, 9, 4, Tile::sandStone_Id, 0, false); + generateBox(level, chunkBB, 1, 10, 1, 3, 10, 3, Tile::sandStone_Id, + Tile::sandStone_Id, false); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 10, 0, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsSouth, 2, 10, 4, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, 0, 10, 2, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, 4, 10, 2, chunkBB); + generateBox(level, chunkBB, width - 5, 0, 0, width - 1, 9, 4, + Tile::sandStone_Id, 0, false); + generateBox(level, chunkBB, width - 4, 10, 1, width - 2, 10, 3, + Tile::sandStone_Id, Tile::sandStone_Id, false); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 10, 0, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsSouth, width - 3, 10, 4, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, width - 5, 10, 2, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, width - 1, 10, 2, + chunkBB); - // entrance - generateBox(level, chunkBB, 8, 0, 0, 12, 4, 4, Tile::sandStone_Id, 0, false); - generateBox(level, chunkBB, 9, 1, 0, 11, 3, 4, 0, 0, false); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 1, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 2, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 3, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, 3, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 3, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 2, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 1, 1, chunkBB); + // entrance + generateBox(level, chunkBB, 8, 0, 0, 12, 4, 4, Tile::sandStone_Id, 0, + false); + generateBox(level, chunkBB, 9, 1, 0, 11, 3, 4, 0, 0, false); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 1, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 2, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 9, 3, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, 3, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 3, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 2, + 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 11, 1, + 1, chunkBB); - // tower pathways - generateBox(level, chunkBB, 4, 1, 1, 8, 3, 3, Tile::sandStone_Id, 0, false); - generateBox(level, chunkBB, 4, 1, 2, 8, 2, 2, 0, 0, false); - generateBox(level, chunkBB, 12, 1, 1, 16, 3, 3, Tile::sandStone_Id, 0, false); - generateBox(level, chunkBB, 12, 1, 2, 16, 2, 2, 0, 0, false); + // tower pathways + generateBox(level, chunkBB, 4, 1, 1, 8, 3, 3, Tile::sandStone_Id, 0, false); + generateBox(level, chunkBB, 4, 1, 2, 8, 2, 2, 0, 0, false); + generateBox(level, chunkBB, 12, 1, 1, 16, 3, 3, Tile::sandStone_Id, 0, + false); + generateBox(level, chunkBB, 12, 1, 2, 16, 2, 2, 0, 0, false); - // hall floor and pillars - generateBox(level, chunkBB, 5, 4, 5, width - 6, 4, depth - 6, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, 9, 4, 9, 11, 4, 11, 0, 0, false); - generateBox(level, chunkBB, 8, 1, 8, 8, 3, 8, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, 12, 1, 8, 12, 3, 8, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, 8, 1, 12, 8, 3, 12, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, 12, 1, 12, 12, 3, 12, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); + // hall floor and pillars + generateBox(level, chunkBB, 5, 4, 5, width - 6, 4, depth - 6, + Tile::sandStone_Id, Tile::sandStone_Id, false); + generateBox(level, chunkBB, 9, 4, 9, 11, 4, 11, 0, 0, false); + generateBox(level, chunkBB, 8, 1, 8, 8, 3, 8, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, 12, 1, 8, 12, 3, 8, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, 8, 1, 12, 8, 3, 12, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, 12, 1, 12, 12, 3, 12, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); - // catwalks - generateBox(level, chunkBB, 1, 1, 5, 4, 4, 11, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, width - 5, 1, 5, width - 2, 4, 11, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, 6, 7, 9, 6, 7, 11, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, width - 7, 7, 9, width - 7, 7, 11, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, 5, 5, 9, 5, 7, 11, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, width - 6, 5, 9, width - 6, 7, 11, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - placeBlock(level, 0, 0, 5, 5, 10, chunkBB); - placeBlock(level, 0, 0, 5, 6, 10, chunkBB); - placeBlock(level, 0, 0, 6, 6, 10, chunkBB); - placeBlock(level, 0, 0, width - 6, 5, 10, chunkBB); - placeBlock(level, 0, 0, width - 6, 6, 10, chunkBB); - placeBlock(level, 0, 0, width - 7, 6, 10, chunkBB); + // catwalks + generateBox(level, chunkBB, 1, 1, 5, 4, 4, 11, Tile::sandStone_Id, + Tile::sandStone_Id, false); + generateBox(level, chunkBB, width - 5, 1, 5, width - 2, 4, 11, + Tile::sandStone_Id, Tile::sandStone_Id, false); + generateBox(level, chunkBB, 6, 7, 9, 6, 7, 11, Tile::sandStone_Id, + Tile::sandStone_Id, false); + generateBox(level, chunkBB, width - 7, 7, 9, width - 7, 7, 11, + Tile::sandStone_Id, Tile::sandStone_Id, false); + generateBox(level, chunkBB, 5, 5, 9, 5, 7, 11, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, width - 6, 5, 9, width - 6, 7, 11, + Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); + placeBlock(level, 0, 0, 5, 5, 10, chunkBB); + placeBlock(level, 0, 0, 5, 6, 10, chunkBB); + placeBlock(level, 0, 0, 6, 6, 10, chunkBB); + placeBlock(level, 0, 0, width - 6, 5, 10, chunkBB); + placeBlock(level, 0, 0, width - 6, 6, 10, chunkBB); + placeBlock(level, 0, 0, width - 7, 6, 10, chunkBB); - // tower stairs - generateBox(level, chunkBB, 2, 4, 4, 2, 6, 4, 0, 0, false); - generateBox(level, chunkBB, width - 3, 4, 4, width - 3, 6, 4, 0, 0, false); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 4, 5, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 3, 4, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 4, 5, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 3, 4, chunkBB); - generateBox(level, chunkBB, 1, 1, 3, 2, 2, 3, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, width - 3, 1, 3, width - 2, 2, 3, Tile::sandStone_Id, Tile::sandStone_Id, false); - placeBlock(level, Tile::stairs_sandstone_Id, 0, 1, 1, 2, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, 0, width - 2, 1, 2, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB, 1, 2, 2, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB, width - 2, 2, 2, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, 2, 1, 2, chunkBB); - placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, width - 3, 1, 2, chunkBB); + // tower stairs + generateBox(level, chunkBB, 2, 4, 4, 2, 6, 4, 0, 0, false); + generateBox(level, chunkBB, width - 3, 4, 4, width - 3, 6, 4, 0, 0, false); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 4, 5, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, 2, 3, 4, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 4, 5, + chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsNorth, width - 3, 3, 4, + chunkBB); + generateBox(level, chunkBB, 1, 1, 3, 2, 2, 3, Tile::sandStone_Id, + Tile::sandStone_Id, false); + generateBox(level, chunkBB, width - 3, 1, 3, width - 2, 2, 3, + Tile::sandStone_Id, Tile::sandStone_Id, false); + placeBlock(level, Tile::stairs_sandstone_Id, 0, 1, 1, 2, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, 0, width - 2, 1, 2, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB, 1, 2, 2, + chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SAND_SLAB, + width - 2, 2, 2, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsWest, 2, 1, 2, chunkBB); + placeBlock(level, Tile::stairs_sandstone_Id, stairsEast, width - 3, 1, 2, + chunkBB); - // indoor decoration - generateBox(level, chunkBB, 4, 3, 5, 4, 3, 18, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, width - 5, 3, 5, width - 5, 3, 17, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, 3, 1, 5, 4, 2, 16, 0, 0, false); - generateBox(level, chunkBB, width - 6, 1, 5, width - 5, 2, 16, 0, 0, false); - for (int z = 5; z <= 17; z += 2) - { - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 4, 1, z, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 4, 2, z, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, width - 5, 1, z, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, width - 5, 2, z, chunkBB); - } - placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 7, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 8, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 0, 9, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 0, 9, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 8, 0, 10, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 12, 0, 10, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 7, 0, 10, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 13, 0, 10, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 0, 11, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 0, 11, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 12, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 13, chunkBB); - placeBlock(level, Tile::cloth_Id, blue, 10, 0, 10, chunkBB); + // indoor decoration + generateBox(level, chunkBB, 4, 3, 5, 4, 3, 18, Tile::sandStone_Id, + Tile::sandStone_Id, false); + generateBox(level, chunkBB, width - 5, 3, 5, width - 5, 3, 17, + Tile::sandStone_Id, Tile::sandStone_Id, false); + generateBox(level, chunkBB, 3, 1, 5, 4, 2, 16, 0, 0, false); + generateBox(level, chunkBB, width - 6, 1, 5, width - 5, 2, 16, 0, 0, false); + for (int z = 5; z <= 17; z += 2) { + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 4, + 1, z, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + 4, 2, z, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + width - 5, 1, z, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + width - 5, 2, z, chunkBB); + } + placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 7, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 8, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 0, 9, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 0, 9, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 8, 0, 10, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 12, 0, 10, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 7, 0, 10, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 13, 0, 10, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 0, 11, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 0, 11, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 12, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 10, 0, 13, chunkBB); + placeBlock(level, Tile::cloth_Id, blue, 10, 0, 10, chunkBB); - // outdoor decoration - for (int x = 0; x <= width - 1; x += width - 1) - { - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 2, 1, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 2, 2, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 2, 3, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 3, 1, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 3, 2, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 3, 3, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 4, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, x, 4, 2, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 4, 3, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 5, 1, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 5, 2, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 5, 3, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 6, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, x, 6, 2, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 6, 3, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 1, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 2, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 3, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 8, 1, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 8, 2, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 8, 3, chunkBB); - } - for (int x = 2; x <= width - 3; x += width - 3 - 2) - { - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x - 1, 2, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 2, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x + 1, 2, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x - 1, 3, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 3, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x + 1, 3, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 4, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, x, 4, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 4, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x - 1, 5, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 5, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x + 1, 5, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 6, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, x, 6, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 6, 00, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 7, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 7, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x - 1, 8, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, 8, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x + 1, 8, 0, chunkBB); - } - generateBox(level, chunkBB, 8, 4, 0, 12, 6, 0, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - placeBlock(level, 0, 0, 8, 6, 0, chunkBB); - placeBlock(level, 0, 0, 12, 6, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 5, 0, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, 5, 0, chunkBB); - placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 5, 0, chunkBB); + // outdoor decoration + for (int x = 0; x <= width - 1; x += width - 1) { + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 2, 1, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 2, 2, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 2, 3, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 3, 1, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 3, 2, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 3, 3, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 4, 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + x, 4, 2, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 4, 3, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 5, 1, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 5, 2, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 5, 3, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 6, 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + x, 6, 2, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 6, 3, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 1, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 2, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 3, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 8, 1, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 8, 2, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 8, 3, chunkBB); + } + for (int x = 2; x <= width - 3; x += width - 3 - 2) { + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x - 1, 2, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 2, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x + 1, 2, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x - 1, 3, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 3, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x + 1, 3, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 4, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + x, 4, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 4, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x - 1, 5, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 5, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x + 1, 5, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 6, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, + x, 6, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 6, 00, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x - 1, 7, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x, 7, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, x + 1, 7, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x - 1, 8, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, x, + 8, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, + x + 1, 8, 0, chunkBB); + } + generateBox(level, chunkBB, 8, 4, 0, 12, 6, 0, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + placeBlock(level, 0, 0, 8, 6, 0, chunkBB); + placeBlock(level, 0, 0, 12, 6, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 9, 5, 0, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, + 5, 0, chunkBB); + placeBlock(level, Tile::cloth_Id, baseDecoColor, 11, 5, 0, chunkBB); - // tombs - generateBox(level, chunkBB, 8, -14, 8, 12, -11, 12, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, 8, -10, 8, 12, -10, 12, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, false); - generateBox(level, chunkBB, 8, -9, 8, 12, -9, 12, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, false); - generateBox(level, chunkBB, 8, -8, 8, 12, -1, 12, Tile::sandStone_Id, Tile::sandStone_Id, false); - generateBox(level, chunkBB, 9, -11, 9, 11, -1, 11, 0, 0, false); - placeBlock(level, Tile::pressurePlate_stone_Id, 0, 10, -11, 10, chunkBB); - generateBox(level, chunkBB, 9, -13, 9, 11, -13, 11, Tile::tnt_Id, 0, false); - placeBlock(level, 0, 0, 8, -11, 10, chunkBB); - placeBlock(level, 0, 0, 8, -10, 10, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 7, -10, 10, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 7, -11, 10, chunkBB); - placeBlock(level, 0, 0, 12, -11, 10, chunkBB); - placeBlock(level, 0, 0, 12, -10, 10, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 13, -10, 10, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 13, -11, 10, chunkBB); - placeBlock(level, 0, 0, 10, -11, 8, chunkBB); - placeBlock(level, 0, 0, 10, -10, 8, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, -10, 7, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, -11, 7, chunkBB); - placeBlock(level, 0, 0, 10, -11, 12, chunkBB); - placeBlock(level, 0, 0, 10, -10, 12, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, -10, 13, chunkBB); - placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, -11, 13, chunkBB); + // tombs + generateBox(level, chunkBB, 8, -14, 8, 12, -11, 12, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, 8, -10, 8, 12, -10, 12, Tile::sandStone_Id, + SandStoneTile::TYPE_HEIROGLYPHS, Tile::sandStone_Id, + SandStoneTile::TYPE_HEIROGLYPHS, false); + generateBox(level, chunkBB, 8, -9, 8, 12, -9, 12, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, Tile::sandStone_Id, + SandStoneTile::TYPE_SMOOTHSIDE, false); + generateBox(level, chunkBB, 8, -8, 8, 12, -1, 12, Tile::sandStone_Id, + Tile::sandStone_Id, false); + generateBox(level, chunkBB, 9, -11, 9, 11, -1, 11, 0, 0, false); + placeBlock(level, Tile::pressurePlate_stone_Id, 0, 10, -11, 10, chunkBB); + generateBox(level, chunkBB, 9, -13, 9, 11, -13, 11, Tile::tnt_Id, 0, false); + placeBlock(level, 0, 0, 8, -11, 10, chunkBB); + placeBlock(level, 0, 0, 8, -10, 10, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 7, + -10, 10, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 7, + -11, 10, chunkBB); + placeBlock(level, 0, 0, 12, -11, 10, chunkBB); + placeBlock(level, 0, 0, 12, -10, 10, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 13, + -10, 10, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 13, + -11, 10, chunkBB); + placeBlock(level, 0, 0, 10, -11, 8, chunkBB); + placeBlock(level, 0, 0, 10, -10, 8, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, + -10, 7, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, + -11, 7, chunkBB); + placeBlock(level, 0, 0, 10, -11, 12, chunkBB); + placeBlock(level, 0, 0, 10, -10, 12, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_HEIROGLYPHS, 10, + -10, 13, chunkBB); + placeBlock(level, Tile::sandStone_Id, SandStoneTile::TYPE_SMOOTHSIDE, 10, + -11, 13, chunkBB); - // chests! - for (int i = 0; i < 4; i++) - { - if (!hasPlacedChest[i]) - { - int xo = Direction::STEP_X[i] * 2; - int zo = Direction::STEP_Z[i] * 2; - hasPlacedChest[i] = createChest(level, chunkBB, random, 10 + xo, -11, 10 + zo, WeighedTreasure::addToTreasure(WeighedTreasureArray(treasureItems,TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random)), 2 + random->nextInt(5)); - } - } + // chests! + for (int i = 0; i < 4; i++) { + if (!hasPlacedChest[i]) { + int xo = Direction::STEP_X[i] * 2; + int zo = Direction::STEP_Z[i] * 2; + hasPlacedChest[i] = createChest( + level, chunkBB, random, 10 + xo, -11, 10 + zo, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(treasureItems, TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random)), + 2 + random->nextInt(5)); + } + } - return true; + return true; } - -WeighedTreasure *ScatteredFeaturePieces::JunglePyramidPiece::treasureItems[ScatteredFeaturePieces::JunglePyramidPiece::TREASURE_ITEMS_COUNT] = -{ - new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), - new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), - new WeighedTreasure(Item::goldIngot_Id, 0, 2, 7, 15), - new WeighedTreasure(Item::emerald_Id, 0, 1, 3, 2), - new WeighedTreasure(Item::bone_Id, 0, 4, 6, 20), - new WeighedTreasure(Item::rotten_flesh_Id, 0, 3, 7, 16), + +WeighedTreasure* ScatteredFeaturePieces::JunglePyramidPiece::treasureItems + [ScatteredFeaturePieces::JunglePyramidPiece::TREASURE_ITEMS_COUNT] = { + new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), + new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), + new WeighedTreasure(Item::goldIngot_Id, 0, 2, 7, 15), + new WeighedTreasure(Item::emerald_Id, 0, 1, 3, 2), + new WeighedTreasure(Item::bone_Id, 0, 4, 6, 20), + new WeighedTreasure(Item::rotten_flesh_Id, 0, 3, 7, 16), }; - -WeighedTreasure *ScatteredFeaturePieces::JunglePyramidPiece::dispenserItems[ScatteredFeaturePieces::JunglePyramidPiece::DISPENSER_ITEMS_COUNT] = -{ - new WeighedTreasure(Item::arrow_Id, 0, 2, 7, 30), - // new WeighedTreasure(Item.fireball.id, 0, 1, 1, 10), +WeighedTreasure* ScatteredFeaturePieces::JunglePyramidPiece::dispenserItems + [ScatteredFeaturePieces::JunglePyramidPiece::DISPENSER_ITEMS_COUNT] = { + new WeighedTreasure(Item::arrow_Id, 0, 2, 7, 30), + // new WeighedTreasure(Item.fireball.id, 0, 1, 1, 10), }; -ScatteredFeaturePieces::JunglePyramidPiece::JunglePyramidPiece(Random *random, int west, int north) : ScatteredFeaturePiece(random, west, 64, north, 12, 10, 15) -{ - placedMainChest = false; - placedHiddenChest = false; - placedTrap1 = false; - placedTrap2 = false; +ScatteredFeaturePieces::JunglePyramidPiece::JunglePyramidPiece(Random* random, + int west, + int north) + : ScatteredFeaturePiece(random, west, 64, north, 12, 10, 15) { + placedMainChest = false; + placedHiddenChest = false; + placedTrap1 = false; + placedTrap2 = false; } -bool ScatteredFeaturePieces::JunglePyramidPiece::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (!updateAverageGroundHeight(level, chunkBB, 0)) - { - return false; - } +bool ScatteredFeaturePieces::JunglePyramidPiece::postProcess( + Level* level, Random* random, BoundingBox* chunkBB) { + if (!updateAverageGroundHeight(level, chunkBB, 0)) { + return false; + } - int stairsNorth = getOrientationData(Tile::stairs_stone_Id, 3); - int stairsSouth = getOrientationData(Tile::stairs_stone_Id, 2); - int stairsEast = getOrientationData(Tile::stairs_stone_Id, 0); - int stairsWest = getOrientationData(Tile::stairs_stone_Id, 1); + int stairsNorth = getOrientationData(Tile::stairs_stone_Id, 3); + int stairsSouth = getOrientationData(Tile::stairs_stone_Id, 2); + int stairsEast = getOrientationData(Tile::stairs_stone_Id, 0); + int stairsWest = getOrientationData(Tile::stairs_stone_Id, 1); - // floor - generateBox(level, chunkBB, 0, -4, 0, width - 1, 0, depth - 1, false, random, &stoneSelector); + // floor + generateBox(level, chunkBB, 0, -4, 0, width - 1, 0, depth - 1, false, + random, &stoneSelector); - // first floor walls - generateBox(level, chunkBB, 2, 1, 2, 9, 2, 2, false, random, &stoneSelector); - generateBox(level, chunkBB, 2, 1, 12, 9, 2, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 2, 1, 3, 2, 2, 11, false, random, &stoneSelector); - generateBox(level, chunkBB, 9, 1, 3, 9, 2, 11, false, random, &stoneSelector); + // first floor walls + generateBox(level, chunkBB, 2, 1, 2, 9, 2, 2, false, random, + &stoneSelector); + generateBox(level, chunkBB, 2, 1, 12, 9, 2, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 2, 1, 3, 2, 2, 11, false, random, + &stoneSelector); + generateBox(level, chunkBB, 9, 1, 3, 9, 2, 11, false, random, + &stoneSelector); - // second floor walls - generateBox(level, chunkBB, 1, 3, 1, 10, 6, 1, false, random, &stoneSelector); - generateBox(level, chunkBB, 1, 3, 13, 10, 6, 13, false, random, &stoneSelector); - generateBox(level, chunkBB, 1, 3, 2, 1, 6, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 10, 3, 2, 10, 6, 12, false, random, &stoneSelector); + // second floor walls + generateBox(level, chunkBB, 1, 3, 1, 10, 6, 1, false, random, + &stoneSelector); + generateBox(level, chunkBB, 1, 3, 13, 10, 6, 13, false, random, + &stoneSelector); + generateBox(level, chunkBB, 1, 3, 2, 1, 6, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 10, 3, 2, 10, 6, 12, false, random, + &stoneSelector); - // roof levels - generateBox(level, chunkBB, 2, 3, 2, 9, 3, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 2, 6, 2, 9, 6, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 3, 7, 3, 8, 7, 11, false, random, &stoneSelector); - generateBox(level, chunkBB, 4, 8, 4, 7, 8, 10, false, random, &stoneSelector); + // roof levels + generateBox(level, chunkBB, 2, 3, 2, 9, 3, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 2, 6, 2, 9, 6, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 3, 7, 3, 8, 7, 11, false, random, + &stoneSelector); + generateBox(level, chunkBB, 4, 8, 4, 7, 8, 10, false, random, + &stoneSelector); - // clear interior - generateAirBox(level, chunkBB, 3, 1, 3, 8, 2, 11); - generateAirBox(level, chunkBB, 4, 3, 6, 7, 3, 9); - generateAirBox(level, chunkBB, 2, 4, 2, 9, 5, 12); - generateAirBox(level, chunkBB, 4, 6, 5, 7, 6, 9); - generateAirBox(level, chunkBB, 5, 7, 6, 6, 7, 8); + // clear interior + generateAirBox(level, chunkBB, 3, 1, 3, 8, 2, 11); + generateAirBox(level, chunkBB, 4, 3, 6, 7, 3, 9); + generateAirBox(level, chunkBB, 2, 4, 2, 9, 5, 12); + generateAirBox(level, chunkBB, 4, 6, 5, 7, 6, 9); + generateAirBox(level, chunkBB, 5, 7, 6, 6, 7, 8); - // doors and windows - generateAirBox(level, chunkBB, 5, 1, 2, 6, 2, 2); - generateAirBox(level, chunkBB, 5, 2, 12, 6, 2, 12); - generateAirBox(level, chunkBB, 5, 5, 1, 6, 5, 1); - generateAirBox(level, chunkBB, 5, 5, 13, 6, 5, 13); - placeBlock(level, 0, 0, 1, 5, 5, chunkBB); - placeBlock(level, 0, 0, 10, 5, 5, chunkBB); - placeBlock(level, 0, 0, 1, 5, 9, chunkBB); - placeBlock(level, 0, 0, 10, 5, 9, chunkBB); + // doors and windows + generateAirBox(level, chunkBB, 5, 1, 2, 6, 2, 2); + generateAirBox(level, chunkBB, 5, 2, 12, 6, 2, 12); + generateAirBox(level, chunkBB, 5, 5, 1, 6, 5, 1); + generateAirBox(level, chunkBB, 5, 5, 13, 6, 5, 13); + placeBlock(level, 0, 0, 1, 5, 5, chunkBB); + placeBlock(level, 0, 0, 10, 5, 5, chunkBB); + placeBlock(level, 0, 0, 1, 5, 9, chunkBB); + placeBlock(level, 0, 0, 10, 5, 9, chunkBB); - // outside decoration - for (int z = 0; z <= 14; z += 14) - { - generateBox(level, chunkBB, 2, 4, z, 2, 5, z, false, random, &stoneSelector); - generateBox(level, chunkBB, 4, 4, z, 4, 5, z, false, random, &stoneSelector); - generateBox(level, chunkBB, 7, 4, z, 7, 5, z, false, random, &stoneSelector); - generateBox(level, chunkBB, 9, 4, z, 9, 5, z, false, random, &stoneSelector); - } - generateBox(level, chunkBB, 5, 6, 0, 6, 6, 0, false, random, &stoneSelector); - for (int x = 0; x <= 11; x += 11) - { - for (int z = 2; z <= 12; z += 2) - { - generateBox(level, chunkBB, x, 4, z, x, 5, z, false, random, &stoneSelector); - } - generateBox(level, chunkBB, x, 6, 5, x, 6, 5, false, random, &stoneSelector); - generateBox(level, chunkBB, x, 6, 9, x, 6, 9, false, random, &stoneSelector); - } - generateBox(level, chunkBB, 2, 7, 2, 2, 9, 2, false, random, &stoneSelector); - generateBox(level, chunkBB, 9, 7, 2, 9, 9, 2, false, random, &stoneSelector); - generateBox(level, chunkBB, 2, 7, 12, 2, 9, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 9, 7, 12, 9, 9, 12, false, random, &stoneSelector); - generateBox(level, chunkBB, 4, 9, 4, 4, 9, 4, false, random, &stoneSelector); - generateBox(level, chunkBB, 7, 9, 4, 7, 9, 4, false, random, &stoneSelector); - generateBox(level, chunkBB, 4, 9, 10, 4, 9, 10, false, random, &stoneSelector); - generateBox(level, chunkBB, 7, 9, 10, 7, 9, 10, false, random, &stoneSelector); - generateBox(level, chunkBB, 5, 9, 7, 6, 9, 7, false, random, &stoneSelector); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 5, 9, 6, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 6, 9, 6, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 5, 9, 8, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 6, 9, 8, chunkBB); + // outside decoration + for (int z = 0; z <= 14; z += 14) { + generateBox(level, chunkBB, 2, 4, z, 2, 5, z, false, random, + &stoneSelector); + generateBox(level, chunkBB, 4, 4, z, 4, 5, z, false, random, + &stoneSelector); + generateBox(level, chunkBB, 7, 4, z, 7, 5, z, false, random, + &stoneSelector); + generateBox(level, chunkBB, 9, 4, z, 9, 5, z, false, random, + &stoneSelector); + } + generateBox(level, chunkBB, 5, 6, 0, 6, 6, 0, false, random, + &stoneSelector); + for (int x = 0; x <= 11; x += 11) { + for (int z = 2; z <= 12; z += 2) { + generateBox(level, chunkBB, x, 4, z, x, 5, z, false, random, + &stoneSelector); + } + generateBox(level, chunkBB, x, 6, 5, x, 6, 5, false, random, + &stoneSelector); + generateBox(level, chunkBB, x, 6, 9, x, 6, 9, false, random, + &stoneSelector); + } + generateBox(level, chunkBB, 2, 7, 2, 2, 9, 2, false, random, + &stoneSelector); + generateBox(level, chunkBB, 9, 7, 2, 9, 9, 2, false, random, + &stoneSelector); + generateBox(level, chunkBB, 2, 7, 12, 2, 9, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 9, 7, 12, 9, 9, 12, false, random, + &stoneSelector); + generateBox(level, chunkBB, 4, 9, 4, 4, 9, 4, false, random, + &stoneSelector); + generateBox(level, chunkBB, 7, 9, 4, 7, 9, 4, false, random, + &stoneSelector); + generateBox(level, chunkBB, 4, 9, 10, 4, 9, 10, false, random, + &stoneSelector); + generateBox(level, chunkBB, 7, 9, 10, 7, 9, 10, false, random, + &stoneSelector); + generateBox(level, chunkBB, 5, 9, 7, 6, 9, 7, false, random, + &stoneSelector); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 5, 9, 6, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 6, 9, 6, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 5, 9, 8, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 6, 9, 8, chunkBB); - // front stairs - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 0, 0, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 5, 0, 0, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 6, 0, 0, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 0, 0, chunkBB); + // front stairs + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 0, 0, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 5, 0, 0, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 6, 0, 0, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 0, 0, chunkBB); - // indoor stairs up - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 1, 8, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 2, 9, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 3, 10, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 1, 8, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 2, 9, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 3, 10, chunkBB); - generateBox(level, chunkBB, 4, 1, 9, 4, 1, 9, false, random, &stoneSelector); - generateBox(level, chunkBB, 7, 1, 9, 7, 1, 9, false, random, &stoneSelector); - generateBox(level, chunkBB, 4, 1, 10, 7, 2, 10, false, random, &stoneSelector); + // indoor stairs up + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 1, 8, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 2, 9, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 4, 3, 10, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 1, 8, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 2, 9, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsNorth, 7, 3, 10, chunkBB); + generateBox(level, chunkBB, 4, 1, 9, 4, 1, 9, false, random, + &stoneSelector); + generateBox(level, chunkBB, 7, 1, 9, 7, 1, 9, false, random, + &stoneSelector); + generateBox(level, chunkBB, 4, 1, 10, 7, 2, 10, false, random, + &stoneSelector); - // indoor hand rail - generateBox(level, chunkBB, 5, 4, 5, 6, 4, 5, false, random, &stoneSelector); - placeBlock(level, Tile::stairs_stone_Id, stairsEast, 4, 4, 5, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsWest, 7, 4, 5, chunkBB); + // indoor hand rail + generateBox(level, chunkBB, 5, 4, 5, 6, 4, 5, false, random, + &stoneSelector); + placeBlock(level, Tile::stairs_stone_Id, stairsEast, 4, 4, 5, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsWest, 7, 4, 5, chunkBB); - // indoor stairs down - for (int i = 0; i < 4; i++) - { - placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 5, 0 - i, 6 + i, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 6, 0 - i, 6 + i, chunkBB); - generateAirBox(level, chunkBB, 5, 0 - i, 7 + i, 6, 0 - i, 9 + i); - } + // indoor stairs down + for (int i = 0; i < 4; i++) { + placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 5, 0 - i, 6 + i, + chunkBB); + placeBlock(level, Tile::stairs_stone_Id, stairsSouth, 6, 0 - i, 6 + i, + chunkBB); + generateAirBox(level, chunkBB, 5, 0 - i, 7 + i, 6, 0 - i, 9 + i); + } - // underground corridors - generateAirBox(level, chunkBB, 1, -3, 12, 10, -1, 13); - generateAirBox(level, chunkBB, 1, -3, 1, 3, -1, 13); - generateAirBox(level, chunkBB, 1, -3, 1, 9, -1, 5); - for (int z = 1; z <= 13; z += 2) - { - generateBox(level, chunkBB, 1, -3, z, 1, -2, z, false, random, &stoneSelector); - } - for (int z = 2; z <= 12; z += 2) - { - generateBox(level, chunkBB, 1, -1, z, 3, -1, z, false, random, &stoneSelector); - } - generateBox(level, chunkBB, 2, -2, 1, 5, -2, 1, false, random, &stoneSelector); - generateBox(level, chunkBB, 7, -2, 1, 9, -2, 1, false, random, &stoneSelector); - generateBox(level, chunkBB, 6, -3, 1, 6, -3, 1, false, random, &stoneSelector); - generateBox(level, chunkBB, 6, -1, 1, 6, -1, 1, false, random, &stoneSelector); + // underground corridors + generateAirBox(level, chunkBB, 1, -3, 12, 10, -1, 13); + generateAirBox(level, chunkBB, 1, -3, 1, 3, -1, 13); + generateAirBox(level, chunkBB, 1, -3, 1, 9, -1, 5); + for (int z = 1; z <= 13; z += 2) { + generateBox(level, chunkBB, 1, -3, z, 1, -2, z, false, random, + &stoneSelector); + } + for (int z = 2; z <= 12; z += 2) { + generateBox(level, chunkBB, 1, -1, z, 3, -1, z, false, random, + &stoneSelector); + } + generateBox(level, chunkBB, 2, -2, 1, 5, -2, 1, false, random, + &stoneSelector); + generateBox(level, chunkBB, 7, -2, 1, 9, -2, 1, false, random, + &stoneSelector); + generateBox(level, chunkBB, 6, -3, 1, 6, -3, 1, false, random, + &stoneSelector); + generateBox(level, chunkBB, 6, -1, 1, 6, -1, 1, false, random, + &stoneSelector); - // trip wire trap 1 - placeBlock(level, Tile::tripWireSource_Id, getOrientationData(Tile::tripWireSource_Id, Direction::EAST) | TripWireSourceTile::MASK_ATTACHED, 1, -3, 8, chunkBB); - placeBlock(level, Tile::tripWireSource_Id, getOrientationData(Tile::tripWireSource_Id, Direction::WEST) | TripWireSourceTile::MASK_ATTACHED, 4, -3, 8, chunkBB); - placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 2, -3, 8, chunkBB); - placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 3, -3, 8, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 7, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 6, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 5, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 4, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 3, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 2, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 1, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 4, -3, 1, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 3, -3, 1, chunkBB); - if (!placedTrap1) - { - placedTrap1 = createDispenser(level, chunkBB, random, 3, -2, 1, Facing::NORTH, WeighedTreasureArray(dispenserItems,DISPENSER_ITEMS_COUNT), 2); - } - placeBlock(level, Tile::vine_Id, 0xf, 3, -2, 2, chunkBB); + // trip wire trap 1 + placeBlock(level, Tile::tripWireSource_Id, + getOrientationData(Tile::tripWireSource_Id, Direction::EAST) | + TripWireSourceTile::MASK_ATTACHED, + 1, -3, 8, chunkBB); + placeBlock(level, Tile::tripWireSource_Id, + getOrientationData(Tile::tripWireSource_Id, Direction::WEST) | + TripWireSourceTile::MASK_ATTACHED, + 4, -3, 8, chunkBB); + placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 2, -3, 8, + chunkBB); + placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 3, -3, 8, + chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 7, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 6, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 5, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 4, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 3, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 2, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 5, -3, 1, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 4, -3, 1, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 3, -3, 1, chunkBB); + if (!placedTrap1) { + placedTrap1 = createDispenser( + level, chunkBB, random, 3, -2, 1, Facing::NORTH, + WeighedTreasureArray(dispenserItems, DISPENSER_ITEMS_COUNT), 2); + } + placeBlock(level, Tile::vine_Id, 0xf, 3, -2, 2, chunkBB); - // trip wire trap 2 - placeBlock(level, Tile::tripWireSource_Id, getOrientationData(Tile::tripWireSource_Id, Direction::NORTH) | TripWireSourceTile::MASK_ATTACHED, 7, -3, 1, chunkBB); - placeBlock(level, Tile::tripWireSource_Id, getOrientationData(Tile::tripWireSource_Id, Direction::SOUTH) | TripWireSourceTile::MASK_ATTACHED, 7, -3, 5, chunkBB); - placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 2, chunkBB); - placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 3, chunkBB); - placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 4, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 8, -3, 6, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 9, -3, 6, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 9, -3, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 9, -3, 4, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 9, -2, 4, chunkBB); - if (!placedTrap2) - { - placedTrap2 = createDispenser(level, chunkBB, random, 9, -2, 3, Facing::WEST, WeighedTreasureArray(dispenserItems,DISPENSER_ITEMS_COUNT), 2); - } - placeBlock(level, Tile::vine_Id, 0xf, 8, -1, 3, chunkBB); - placeBlock(level, Tile::vine_Id, 0xf, 8, -2, 3, chunkBB); - if (!placedMainChest) - { - placedMainChest = createChest(level, chunkBB, random, 8, -3, 3, WeighedTreasure::addToTreasure(WeighedTreasureArray(treasureItems,TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random)), 2 + random->nextInt(5)); - } - placeBlock(level, Tile::mossStone_Id, 0, 9, -3, 2, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 8, -3, 1, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 4, -3, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 5, -2, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 5, -1, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 6, -3, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 7, -2, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 7, -1, 5, chunkBB); - placeBlock(level, Tile::mossStone_Id, 0, 8, -3, 5, chunkBB); - generateBox(level, chunkBB, 9, -1, 1, 9, -1, 5, false, random, &stoneSelector); + // trip wire trap 2 + placeBlock(level, Tile::tripWireSource_Id, + getOrientationData(Tile::tripWireSource_Id, Direction::NORTH) | + TripWireSourceTile::MASK_ATTACHED, + 7, -3, 1, chunkBB); + placeBlock(level, Tile::tripWireSource_Id, + getOrientationData(Tile::tripWireSource_Id, Direction::SOUTH) | + TripWireSourceTile::MASK_ATTACHED, + 7, -3, 5, chunkBB); + placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 2, + chunkBB); + placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 3, + chunkBB); + placeBlock(level, Tile::tripWire_Id, TripWireTile::MASK_ATTACHED, 7, -3, 4, + chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 8, -3, 6, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 9, -3, 6, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 9, -3, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 9, -3, 4, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 9, -2, 4, chunkBB); + if (!placedTrap2) { + placedTrap2 = createDispenser( + level, chunkBB, random, 9, -2, 3, Facing::WEST, + WeighedTreasureArray(dispenserItems, DISPENSER_ITEMS_COUNT), 2); + } + placeBlock(level, Tile::vine_Id, 0xf, 8, -1, 3, chunkBB); + placeBlock(level, Tile::vine_Id, 0xf, 8, -2, 3, chunkBB); + if (!placedMainChest) { + placedMainChest = createChest( + level, chunkBB, random, 8, -3, 3, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(treasureItems, TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random)), + 2 + random->nextInt(5)); + } + placeBlock(level, Tile::mossStone_Id, 0, 9, -3, 2, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 8, -3, 1, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 4, -3, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 5, -2, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 5, -1, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 6, -3, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 7, -2, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 7, -1, 5, chunkBB); + placeBlock(level, Tile::mossStone_Id, 0, 8, -3, 5, chunkBB); + generateBox(level, chunkBB, 9, -1, 1, 9, -1, 5, false, random, + &stoneSelector); - // hidden room - generateAirBox(level, chunkBB, 8, -3, 8, 10, -1, 10); - placeBlock(level, Tile::stoneBrickSmooth_Id, SmoothStoneBrickTile::TYPE_DETAIL, 8, -2, 11, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, SmoothStoneBrickTile::TYPE_DETAIL, 9, -2, 11, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, SmoothStoneBrickTile::TYPE_DETAIL, 10, -2, 11, chunkBB); - placeBlock(level, Tile::lever_Id, LeverTile::getLeverFacing(getOrientationData(Tile::lever_Id, Facing::NORTH)), 8, -2, 12, chunkBB); - placeBlock(level, Tile::lever_Id, LeverTile::getLeverFacing(getOrientationData(Tile::lever_Id, Facing::NORTH)), 9, -2, 12, chunkBB); - placeBlock(level, Tile::lever_Id, LeverTile::getLeverFacing(getOrientationData(Tile::lever_Id, Facing::NORTH)), 10, -2, 12, chunkBB); - generateBox(level, chunkBB, 8, -3, 8, 8, -3, 10, false, random, &stoneSelector); - generateBox(level, chunkBB, 10, -3, 8, 10, -3, 10, false, random, &stoneSelector); - placeBlock(level, Tile::mossStone_Id, 0, 10, -2, 9, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 8, -2, 9, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 8, -2, 10, chunkBB); - placeBlock(level, Tile::redStoneDust_Id, 0, 10, -1, 9, chunkBB); - placeBlock(level, Tile::pistonStickyBase_Id, Facing::UP, 9, -2, 8, chunkBB); - placeBlock(level, Tile::pistonStickyBase_Id, getOrientationData(Tile::pistonStickyBase_Id, Facing::WEST), 10, -2, 8, chunkBB); - placeBlock(level, Tile::pistonStickyBase_Id, getOrientationData(Tile::pistonStickyBase_Id, Facing::WEST), 10, -1, 8, chunkBB); - placeBlock(level, Tile::diode_off_Id, getOrientationData(Tile::diode_off_Id, Direction::NORTH), 10, -2, 10, chunkBB); - if (!placedHiddenChest) - { - placedHiddenChest = createChest(level, chunkBB, random, 9, -3, 10, WeighedTreasure::addToTreasure(WeighedTreasureArray(treasureItems,TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random)), 2 + random->nextInt(5)); - } + // hidden room + generateAirBox(level, chunkBB, 8, -3, 8, 10, -1, 10); + placeBlock(level, Tile::stoneBrickSmooth_Id, + SmoothStoneBrickTile::TYPE_DETAIL, 8, -2, 11, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, + SmoothStoneBrickTile::TYPE_DETAIL, 9, -2, 11, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, + SmoothStoneBrickTile::TYPE_DETAIL, 10, -2, 11, chunkBB); + placeBlock(level, Tile::lever_Id, + LeverTile::getLeverFacing( + getOrientationData(Tile::lever_Id, Facing::NORTH)), + 8, -2, 12, chunkBB); + placeBlock(level, Tile::lever_Id, + LeverTile::getLeverFacing( + getOrientationData(Tile::lever_Id, Facing::NORTH)), + 9, -2, 12, chunkBB); + placeBlock(level, Tile::lever_Id, + LeverTile::getLeverFacing( + getOrientationData(Tile::lever_Id, Facing::NORTH)), + 10, -2, 12, chunkBB); + generateBox(level, chunkBB, 8, -3, 8, 8, -3, 10, false, random, + &stoneSelector); + generateBox(level, chunkBB, 10, -3, 8, 10, -3, 10, false, random, + &stoneSelector); + placeBlock(level, Tile::mossStone_Id, 0, 10, -2, 9, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 8, -2, 9, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 8, -2, 10, chunkBB); + placeBlock(level, Tile::redStoneDust_Id, 0, 10, -1, 9, chunkBB); + placeBlock(level, Tile::pistonStickyBase_Id, Facing::UP, 9, -2, 8, chunkBB); + placeBlock(level, Tile::pistonStickyBase_Id, + getOrientationData(Tile::pistonStickyBase_Id, Facing::WEST), 10, + -2, 8, chunkBB); + placeBlock(level, Tile::pistonStickyBase_Id, + getOrientationData(Tile::pistonStickyBase_Id, Facing::WEST), 10, + -1, 8, chunkBB); + placeBlock(level, Tile::diode_off_Id, + getOrientationData(Tile::diode_off_Id, Direction::NORTH), 10, -2, + 10, chunkBB); + if (!placedHiddenChest) { + placedHiddenChest = createChest( + level, chunkBB, random, 9, -3, 10, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(treasureItems, TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random)), + 2 + random->nextInt(5)); + } - return true; + return true; } -void ScatteredFeaturePieces::JunglePyramidPiece::MossStoneSelector::next(Random *random, int worldX, int worldY, int worldZ, bool isEdge) -{ - if (random->nextFloat() < .4f) - { - nextId = Tile::stoneBrick_Id; - } - else - { - nextId = Tile::mossStone_Id; - } +void ScatteredFeaturePieces::JunglePyramidPiece::MossStoneSelector::next( + Random* random, int worldX, int worldY, int worldZ, bool isEdge) { + if (random->nextFloat() < .4f) { + nextId = Tile::stoneBrick_Id; + } else { + nextId = Tile::mossStone_Id; + } } -ScatteredFeaturePieces::JunglePyramidPiece::MossStoneSelector ScatteredFeaturePieces::JunglePyramidPiece::stoneSelector; \ No newline at end of file +ScatteredFeaturePieces::JunglePyramidPiece::MossStoneSelector + ScatteredFeaturePieces::JunglePyramidPiece::stoneSelector; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.h b/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.h index 08ab92ba4..802c92374 100644 --- a/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.h +++ b/Minecraft.World/WorldGen/Structures/ScatteredFeaturePieces.h @@ -2,66 +2,64 @@ #include "StructurePiece.h" -class ScatteredFeaturePieces -{ +class ScatteredFeaturePieces { private: - class ScatteredFeaturePiece : public StructurePiece - { - protected: - int width; - int height; - int depth; + class ScatteredFeaturePiece : public StructurePiece { + protected: + int width; + int height; + int depth; - int heightPosition; + int heightPosition; - ScatteredFeaturePiece(Random *random, int west, int floor, int north, int width, int height, int depth); + ScatteredFeaturePiece(Random* random, int west, int floor, int north, + int width, int height, int depth); - bool updateAverageGroundHeight(Level *level, BoundingBox *chunkBB, int offset); - }; + bool updateAverageGroundHeight(Level* level, BoundingBox* chunkBB, + int offset); + }; public: - class DesertPyramidPiece : public ScatteredFeaturePiece - { - public: - static const int TREASURE_ITEMS_COUNT = 6; - private: - bool hasPlacedChest[4]; - static WeighedTreasure *treasureItems[TREASURE_ITEMS_COUNT]; + class DesertPyramidPiece : public ScatteredFeaturePiece { + public: + static const int TREASURE_ITEMS_COUNT = 6; - public: - DesertPyramidPiece(Random *random, int west, int north); + private: + bool hasPlacedChest[4]; + static WeighedTreasure* treasureItems[TREASURE_ITEMS_COUNT]; - bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + DesertPyramidPiece(Random* random, int west, int north); - }; + bool postProcess(Level* level, Random* random, BoundingBox* chunkBB); + }; - class JunglePyramidPiece : public ScatteredFeaturePiece - { - public: - static const int TREASURE_ITEMS_COUNT = 6; - static const int DISPENSER_ITEMS_COUNT = 1; - private: - bool placedMainChest; - bool placedHiddenChest; - bool placedTrap1; - bool placedTrap2; + class JunglePyramidPiece : public ScatteredFeaturePiece { + public: + static const int TREASURE_ITEMS_COUNT = 6; + static const int DISPENSER_ITEMS_COUNT = 1; - static WeighedTreasure *treasureItems[TREASURE_ITEMS_COUNT]; - static WeighedTreasure *dispenserItems[DISPENSER_ITEMS_COUNT]; + private: + bool placedMainChest; + bool placedHiddenChest; + bool placedTrap1; + bool placedTrap2; - public: - JunglePyramidPiece(Random *random, int west, int north); + static WeighedTreasure* treasureItems[TREASURE_ITEMS_COUNT]; + static WeighedTreasure* dispenserItems[DISPENSER_ITEMS_COUNT]; - bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + JunglePyramidPiece(Random* random, int west, int north); - private: - class MossStoneSelector : public BlockSelector - { - public: - void next(Random *random, int worldX, int worldY, int worldZ, bool isEdge); - }; + bool postProcess(Level* level, Random* random, BoundingBox* chunkBB); - static MossStoneSelector stoneSelector; + private: + class MossStoneSelector : public BlockSelector { + public: + void next(Random* random, int worldX, int worldY, int worldZ, + bool isEdge); + }; - }; + static MossStoneSelector stoneSelector; + }; }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/StrongholdPieces.cpp b/Minecraft.World/WorldGen/Structures/StrongholdPieces.cpp index f70e70e79..876743744 100644 --- a/Minecraft.World/WorldGen/Structures/StrongholdPieces.cpp +++ b/Minecraft.World/WorldGen/Structures/StrongholdPieces.cpp @@ -11,59 +11,57 @@ #include "../../Util/Facing.h" int StrongholdPieces::totalWeight = 0; -std::list StrongholdPieces::currentPieces; +std::list StrongholdPieces::currentPieces; StrongholdPieces::EPieceClass StrongholdPieces::imposedPiece; const bool StrongholdPieces::CHECK_AIR = true; -StrongholdPieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount) : weight(weight) -{ - this->placeCount = 0; // 4J added initialiser - this->pieceClass = pieceClass; - this->maxPlaceCount = maxPlaceCount; +StrongholdPieces::PieceWeight::PieceWeight(EPieceClass pieceClass, int weight, + int maxPlaceCount) + : weight(weight) { + this->placeCount = 0; // 4J added initialiser + this->pieceClass = pieceClass; + this->maxPlaceCount = maxPlaceCount; } -bool StrongholdPieces::PieceWeight::doPlace(int depth) -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool StrongholdPieces::PieceWeight::doPlace(int depth) { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -bool StrongholdPieces::PieceWeight::isValid() -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool StrongholdPieces::PieceWeight::isValid() { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -void StrongholdPieces::resetPieces() -{ - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - delete (*it); - } - currentPieces.clear(); +void StrongholdPieces::resetPieces() { + for (AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++) { + delete (*it); + } + currentPieces.clear(); - currentPieces.push_back( new PieceWeight(EPieceClass_Straight, 40, 0) ); - currentPieces.push_back( new PieceWeight(EPieceClass_PrisonHall, 5, 5) ); - currentPieces.push_back( new PieceWeight(EPieceClass_LeftTurn, 20, 0) ); - currentPieces.push_back( new PieceWeight(EPieceClass_RightTurn, 20, 0) ); - currentPieces.push_back( new PieceWeight(EPieceClass_RoomCrossing, 10, 6) ); - currentPieces.push_back( new PieceWeight(EPieceClass_StraightStairsDown, 5, 5) ); - currentPieces.push_back( new PieceWeight(EPieceClass_StairsDown, 5, 5) ); - currentPieces.push_back( new PieceWeight(EPieceClass_FiveCrossing, 5, 4) ); - currentPieces.push_back( new PieceWeight(EPieceClass_ChestCorridor, 5, 4) ); - currentPieces.push_back( new PieceWeight_Library(EPieceClass_Library, 10, 2) ); - currentPieces.push_back( new PieceWeight_PortalRoom(EPieceClass_PortalRoom, 20, 1) ); + currentPieces.push_back(new PieceWeight(EPieceClass_Straight, 40, 0)); + currentPieces.push_back(new PieceWeight(EPieceClass_PrisonHall, 5, 5)); + currentPieces.push_back(new PieceWeight(EPieceClass_LeftTurn, 20, 0)); + currentPieces.push_back(new PieceWeight(EPieceClass_RightTurn, 20, 0)); + currentPieces.push_back(new PieceWeight(EPieceClass_RoomCrossing, 10, 6)); + currentPieces.push_back( + new PieceWeight(EPieceClass_StraightStairsDown, 5, 5)); + currentPieces.push_back(new PieceWeight(EPieceClass_StairsDown, 5, 5)); + currentPieces.push_back(new PieceWeight(EPieceClass_FiveCrossing, 5, 4)); + currentPieces.push_back(new PieceWeight(EPieceClass_ChestCorridor, 5, 4)); + currentPieces.push_back( + new PieceWeight_Library(EPieceClass_Library, 10, 2)); + currentPieces.push_back( + new PieceWeight_PortalRoom(EPieceClass_PortalRoom, 20, 1)); - imposedPiece = EPieceClass_NULL; + imposedPiece = EPieceClass_NULL; } -bool StrongholdPieces::updatePieceWeight() -{ +bool StrongholdPieces::updatePieceWeight() { bool hasAnyPieces = false; totalWeight = 0; - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; - if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) - { + for (AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++) { + PieceWeight* piece = *it; + if (piece->maxPlaceCount > 0 && + piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; } totalWeight += piece->weight; @@ -71,102 +69,90 @@ bool StrongholdPieces::updatePieceWeight() return hasAnyPieces; } -StrongholdPieces::StrongholdPiece *StrongholdPieces::findAndCreatePieceFactory(EPieceClass pieceClass, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - StrongholdPiece *strongholdPiece = NULL; +StrongholdPieces::StrongholdPiece* StrongholdPieces::findAndCreatePieceFactory( + EPieceClass pieceClass, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + StrongholdPiece* strongholdPiece = NULL; - if (pieceClass == EPieceClass_Straight) - { - strongholdPiece = Straight::createPiece(pieces, random, footX, footY, footZ, direction, depth); + if (pieceClass == EPieceClass_Straight) { + strongholdPiece = Straight::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_PrisonHall) { + strongholdPiece = PrisonHall::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_LeftTurn) { + strongholdPiece = LeftTurn::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_RightTurn) { + strongholdPiece = RightTurn::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_RoomCrossing) { + strongholdPiece = RoomCrossing::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_StraightStairsDown) { + strongholdPiece = StraightStairsDown::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_StairsDown) { + strongholdPiece = StairsDown::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_FiveCrossing) { + strongholdPiece = FiveCrossing::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_ChestCorridor) { + strongholdPiece = ChestCorridor::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == EPieceClass_Library) { + strongholdPiece = Library::createPiece(pieces, random, footX, footY, + footZ, direction, depth); + } else if (pieceClass == EPieceClass_PortalRoom) { + strongholdPiece = PortalRoom::createPiece(pieces, random, footX, footY, + footZ, direction, depth); } - else if (pieceClass == EPieceClass_PrisonHall) - { - strongholdPiece = PrisonHall::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_LeftTurn) - { - strongholdPiece = LeftTurn::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_RightTurn) - { - strongholdPiece = RightTurn::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_RoomCrossing) - { - strongholdPiece = RoomCrossing::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_StraightStairsDown) - { - strongholdPiece = StraightStairsDown::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_StairsDown) - { - strongholdPiece = StairsDown::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_FiveCrossing) - { - strongholdPiece = FiveCrossing::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_ChestCorridor) - { - strongholdPiece = ChestCorridor::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_Library) - { - strongholdPiece = Library::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == EPieceClass_PortalRoom) - { - strongholdPiece = PortalRoom::createPiece(pieces, random, footX, footY, footZ, direction, depth); - } - return strongholdPiece; } -StrongholdPieces::StrongholdPiece *StrongholdPieces::generatePieceFromSmallDoor(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - if (!updatePieceWeight()) - { +StrongholdPieces::StrongholdPiece* StrongholdPieces::generatePieceFromSmallDoor( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + if (!updatePieceWeight()) { return NULL; } - if (imposedPiece != EPieceClass_NULL) - { - StrongholdPiece *strongholdPiece = findAndCreatePieceFactory(imposedPiece, pieces, random, footX, footY, footZ, direction, depth); + if (imposedPiece != EPieceClass_NULL) { + StrongholdPiece* strongholdPiece = + findAndCreatePieceFactory(imposedPiece, pieces, random, footX, + footY, footZ, direction, depth); imposedPiece = EPieceClass_NULL; - if (strongholdPiece != NULL) - { + if (strongholdPiece != NULL) { return strongholdPiece; } } int numAttempts = 0; - while (numAttempts < 5) - { + while (numAttempts < 5) { numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; + for (AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); + it++) { + PieceWeight* piece = *it; weightSelection -= piece->weight; - if (weightSelection < 0) - { - if (!piece->doPlace(depth) || piece == startPiece->previousPiece) - { + if (weightSelection < 0) { + if (!piece->doPlace(depth) || + piece == startPiece->previousPiece) { break; } - StrongholdPiece *strongholdPiece = findAndCreatePieceFactory(piece->pieceClass, pieces, random, footX, footY, footZ, direction, depth); - if (strongholdPiece != NULL) - { + StrongholdPiece* strongholdPiece = findAndCreatePieceFactory( + piece->pieceClass, pieces, random, footX, footY, footZ, + direction, depth); + if (strongholdPiece != NULL) { piece->placeCount++; startPiece->previousPiece = piece; - if (!piece->isValid()) - { + if (!piece->isValid()) { currentPieces.remove(piece); } return strongholdPiece; @@ -175,265 +161,334 @@ StrongholdPieces::StrongholdPiece *StrongholdPieces::generatePieceFromSmallDoor( } } { - BoundingBox *box = FillerCorridor::findPieceBox(pieces, random, footX, footY, footZ, direction); - if (box != NULL && box->y0 > 1) - { + BoundingBox* box = FillerCorridor::findPieceBox( + pieces, random, footX, footY, footZ, direction); + if (box != NULL && box->y0 > 1) { return new FillerCorridor(depth, random, box, direction); } - if(box != NULL) delete box; + if (box != NULL) delete box; } return NULL; } -StructurePiece *StrongholdPieces::generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - if (depth > MAX_DEPTH) - { +StructurePiece* StrongholdPieces::generateAndAddPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + if (depth > MAX_DEPTH) { return NULL; } - if (abs(footX - startPiece->getBoundingBox()->x0) > 3 * 16 || abs(footZ - startPiece->getBoundingBox()->z0) > 3 * 16) - { - // Force attempt at spawning a portal room - if(startPiece->m_level->getOriginalSaveVersion() >= SAVE_FILE_VERSION_MOVED_STRONGHOLD && !startPiece->m_level->getLevelData()->getHasStrongholdEndPortal()) - { - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; + if (abs(footX - startPiece->getBoundingBox()->x0) > 3 * 16 || + abs(footZ - startPiece->getBoundingBox()->z0) > 3 * 16) { + // Force attempt at spawning a portal room + if (startPiece->m_level->getOriginalSaveVersion() >= + SAVE_FILE_VERSION_MOVED_STRONGHOLD && + !startPiece->m_level->getLevelData()->getHasStrongholdEndPortal()) { + for (AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); + it++) { + PieceWeight* piece = *it; - if(piece->pieceClass != EPieceClass_PortalRoom) continue; + if (piece->pieceClass != EPieceClass_PortalRoom) continue; #ifndef _CONTENT_PACKAGE - printf("Portal room forcing attempt\n"); + printf("Portal room forcing attempt\n"); #endif - StrongholdPiece *strongholdPiece = PortalRoom::createPiece(pieces, random, footX, footY, footZ, direction, depth); - if (strongholdPiece != NULL) - { - piece->placeCount++; - startPiece->previousPiece = piece; + StrongholdPiece* strongholdPiece = PortalRoom::createPiece( + pieces, random, footX, footY, footZ, direction, depth); + if (strongholdPiece != NULL) { + piece->placeCount++; + startPiece->previousPiece = piece; - if (!piece->isValid()) - { - currentPieces.remove(piece); - } + if (!piece->isValid()) { + currentPieces.remove(piece); + } #ifndef _CONTENT_PACKAGE - printf("Success\n"); + printf("Success\n"); #endif - return strongholdPiece; - } - } - } + return strongholdPiece; + } + } + } return NULL; } - StructurePiece *newPiece = generatePieceFromSmallDoor(startPiece, pieces, random, footX, footY, footZ, direction, depth + 1); - if (newPiece != NULL) - { - pieces->push_back(newPiece); + StructurePiece* newPiece = generatePieceFromSmallDoor( + startPiece, pieces, random, footX, footY, footZ, direction, depth + 1); + if (newPiece != NULL) { + pieces->push_back(newPiece); startPiece->pendingChildren.push_back(newPiece); -// newPiece.addChildren(startPiece, pieces, random, depth + 1); + // newPiece.addChildren(startPiece, pieces, random, depth + + // 1); } return newPiece; } -StrongholdPieces::StrongholdPiece::StrongholdPiece(int genDepth) : StructurePiece(genDepth) -{ -} +StrongholdPieces::StrongholdPiece::StrongholdPiece(int genDepth) + : StructurePiece(genDepth) {} -void StrongholdPieces::StrongholdPiece::generateSmallDoor(Level *level, Random *random, BoundingBox *chunkBB, StrongholdPieces::StrongholdPiece::SmallDoorType doorType, int footX, int footY, int footZ) -{ - switch (doorType) - { +void StrongholdPieces::StrongholdPiece::generateSmallDoor( + Level* level, Random* random, BoundingBox* chunkBB, + StrongholdPieces::StrongholdPiece::SmallDoorType doorType, int footX, + int footY, int footZ) { + switch (doorType) { default: case OPENING: - generateBox(level, chunkBB, footX, footY, footZ, footX + SMALL_DOOR_WIDTH - 1, footY + SMALL_DOOR_HEIGHT - 1, footZ, 0, 0, false); + generateBox(level, chunkBB, footX, footY, footZ, + footX + SMALL_DOOR_WIDTH - 1, + footY + SMALL_DOOR_HEIGHT - 1, footZ, 0, 0, false); break; case WOOD_DOOR: - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 1, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY, footZ, chunkBB); - placeBlock(level, Tile::door_wood_Id, 0, footX + 1, footY, footZ, chunkBB); - placeBlock(level, Tile::door_wood_Id, DoorTile::UPPER_BIT, footX + 1, footY + 1, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY, footZ, + chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 1, + footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 2, + footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 1, + footY + 2, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, + footY + 2, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, + footY + 1, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY, + footZ, chunkBB); + placeBlock(level, Tile::door_wood_Id, 0, footX + 1, footY, footZ, + chunkBB); + placeBlock(level, Tile::door_wood_Id, DoorTile::UPPER_BIT, + footX + 1, footY + 1, footZ, chunkBB); break; case GRATES: placeBlock(level, 0, 0, footX + 1, footY, footZ, chunkBB); placeBlock(level, 0, 0, footX + 1, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX, footY, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX + 1, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY, footZ, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX, footY, footZ, + chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX, footY + 1, footZ, + chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX, footY + 2, footZ, + chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX + 1, footY + 2, + footZ, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY + 2, + footZ, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY + 1, + footZ, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, footX + 2, footY, footZ, + chunkBB); break; case IRON_DOOR: - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 1, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY + 2, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY, footZ, chunkBB); - placeBlock(level, Tile::door_iron_Id, 0, footX + 1, footY, footZ, chunkBB); - placeBlock(level, Tile::door_iron_Id, DoorTile::UPPER_BIT, footX + 1, footY + 1, footZ, chunkBB); - placeBlock(level, Tile::button_stone_Id, getOrientationData(Tile::button_stone_Id, 4), footX + 2, footY + 1, footZ + 1, chunkBB); - placeBlock(level, Tile::button_stone_Id, getOrientationData(Tile::button_stone_Id, 3), footX + 2, footY + 1, footZ - 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY, footZ, + chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 1, + footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX, footY + 2, + footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 1, + footY + 2, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, + footY + 2, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, + footY + 1, footZ, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, footX + 2, footY, + footZ, chunkBB); + placeBlock(level, Tile::door_iron_Id, 0, footX + 1, footY, footZ, + chunkBB); + placeBlock(level, Tile::door_iron_Id, DoorTile::UPPER_BIT, + footX + 1, footY + 1, footZ, chunkBB); + placeBlock(level, Tile::button_stone_Id, + getOrientationData(Tile::button_stone_Id, 4), footX + 2, + footY + 1, footZ + 1, chunkBB); + placeBlock(level, Tile::button_stone_Id, + getOrientationData(Tile::button_stone_Id, 3), footX + 2, + footY + 1, footZ - 1, chunkBB); break; - } - + } } -StrongholdPieces::StrongholdPiece::SmallDoorType StrongholdPieces::StrongholdPiece::randomSmallDoor(Random *random) -{ +StrongholdPieces::StrongholdPiece::SmallDoorType +StrongholdPieces::StrongholdPiece::randomSmallDoor(Random* random) { int selection = random->nextInt(5); - switch (selection) - { - default: - case 0: - case 1: - return OPENING; - case 2: - return WOOD_DOOR; - case 3: - return GRATES; - case 4: - return IRON_DOOR; + switch (selection) { + default: + case 0: + case 1: + return OPENING; + case 2: + return WOOD_DOOR; + case 3: + return GRATES; + case 4: + return IRON_DOOR; } } -StructurePiece *StrongholdPieces::StrongholdPiece::generateSmallDoorChildForward(StartPiece *startPiece, std::list *pieces, Random *random, int xOff, int yOff) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + xOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, orientation, getGenDepth()); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + xOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, orientation, getGenDepth()); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, getGenDepth()); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, getGenDepth()); +StructurePiece* +StrongholdPieces::StrongholdPiece::generateSmallDoorChildForward( + StartPiece* startPiece, std::list* pieces, Random* random, + int xOff, int yOff) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + xOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, orientation, + getGenDepth()); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + xOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, orientation, + getGenDepth()); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, + getGenDepth()); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + xOff, orientation, + getGenDepth()); } return NULL; } -StructurePiece *StrongholdPieces::StrongholdPiece::generateSmallDoorChildLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth()); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth()); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); +StructurePiece* StrongholdPieces::StrongholdPiece::generateSmallDoorChildLeft( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth()); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth()); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); } return NULL; } -StructurePiece *StrongholdPieces::StrongholdPiece::generateSmallDoorChildRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth()); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth()); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); +StructurePiece* StrongholdPieces::StrongholdPiece::generateSmallDoorChildRight( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth()); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth()); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); } return NULL; } - -bool StrongholdPieces::StrongholdPiece::isOkBox(BoundingBox *box, StartPiece *startRoom) -{ - //return box != NULL && box->y0 > LOWEST_Y_POSITION; - - bool bIsOk = false; - - if(box != NULL) - { - if( box->y0 > LOWEST_Y_POSITION ) bIsOk = true; - if( startRoom != NULL && startRoom->m_level->getOriginalSaveVersion() >= SAVE_FILE_VERSION_MOVED_STRONGHOLD ) - { - int xzSize = startRoom->m_level->getLevelData()->getXZSize(); - int blockMin = -( (xzSize << 4) / 2) + 1; - int blockMax = ( (xzSize << 4) / 2 ) - 1; +bool StrongholdPieces::StrongholdPiece::isOkBox(BoundingBox* box, + StartPiece* startRoom) { + // return box != NULL && box->y0 > LOWEST_Y_POSITION; - if(box->x0 <= blockMin) bIsOk = false; - if(box->z0 <= blockMin) bIsOk = false; - if(box->x1 >= blockMax) bIsOk = false; - if(box->z1 >= blockMax) bIsOk = false; - } - } + bool bIsOk = false; - return bIsOk; + if (box != NULL) { + if (box->y0 > LOWEST_Y_POSITION) bIsOk = true; + + if (startRoom != NULL && startRoom->m_level->getOriginalSaveVersion() >= + SAVE_FILE_VERSION_MOVED_STRONGHOLD) { + int xzSize = startRoom->m_level->getLevelData()->getXZSize(); + int blockMin = -((xzSize << 4) / 2) + 1; + int blockMax = ((xzSize << 4) / 2) - 1; + + if (box->x0 <= blockMin) bIsOk = false; + if (box->z0 <= blockMin) bIsOk = false; + if (box->x1 >= blockMax) bIsOk = false; + if (box->z1 >= blockMax) bIsOk = false; + } + } + + return bIsOk; } -StrongholdPieces::FillerCorridor::FillerCorridor(int genDepth, Random *random, BoundingBox *corridorBox, int direction) : StrongholdPiece(genDepth), - steps((direction == Direction::NORTH || direction == Direction::SOUTH) ? corridorBox->getZSpan() : corridorBox->getXSpan()) -{ +StrongholdPieces::FillerCorridor::FillerCorridor(int genDepth, Random* random, + BoundingBox* corridorBox, + int direction) + : StrongholdPiece(genDepth), + steps((direction == Direction::NORTH || direction == Direction::SOUTH) + ? corridorBox->getZSpan() + : corridorBox->getXSpan()) { orientation = direction; boundingBox = corridorBox; } -BoundingBox *StrongholdPieces::FillerCorridor::findPieceBox(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ +BoundingBox* StrongholdPieces::FillerCorridor::findPieceBox( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction) { const int maxLength = 3; - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, 5, maxLength + 1, direction); + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, + 5, maxLength + 1, direction); - StructurePiece *collisionPiece = StructurePiece::findCollisionPiece(pieces, box); - - if (collisionPiece == NULL) - { - delete box; + StructurePiece* collisionPiece = + StructurePiece::findCollisionPiece(pieces, box); + + if (collisionPiece == NULL) { + delete box; // the filler must collide with something in order to be // generated return NULL; } - if (collisionPiece->getBoundingBox()->y0 == box->y0) - { - delete box; + if (collisionPiece->getBoundingBox()->y0 == box->y0) { + delete box; // attempt to make a smaller piece until it fits - for (int depth = maxLength; depth >= 1; depth--) - { - box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, 5, depth - 1, direction); - if (!collisionPiece->getBoundingBox()->intersects(box)) - { - delete box; + for (int depth = maxLength; depth >= 1; depth--) { + box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, 5, + depth - 1, direction); + if (!collisionPiece->getBoundingBox()->intersects(box)) { + delete box; // the corridor has shrunk enough to fit, but make it // one step too big to build an entrance into the other // block - return BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, 5, depth, direction); + return BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, 5, + 5, depth, direction); } - delete box; + delete box; } } return NULL; } -bool StrongholdPieces::FillerCorridor::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::FillerCorridor::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // filler corridor - for (int i = 0; i < steps; i++) - { + for (int i = 0; i < steps; i++) { // row 0 placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 0, 0, i, chunkBB); placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 0, i, chunkBB); @@ -441,8 +496,7 @@ bool StrongholdPieces::FillerCorridor::postProcess(Level *level, Random *random, placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 0, i, chunkBB); placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 4, 0, i, chunkBB); // row 1-3 - for (int y = 1; y <= 3; y++) - { + for (int y = 1; y <= 3; y++) { placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 0, y, i, chunkBB); placeBlock(level, 0, 0, 1, y, i, chunkBB); placeBlock(level, 0, 0, 2, y, i, chunkBB); @@ -460,151 +514,178 @@ bool StrongholdPieces::FillerCorridor::postProcess(Level *level, Random *random, return true; } -StrongholdPieces::StairsDown::StairsDown(int genDepth, Random *random, int west, int north) : StrongholdPiece(genDepth), isSource(true), entryDoor(OPENING) -{ +StrongholdPieces::StairsDown::StairsDown(int genDepth, Random* random, int west, + int north) + : StrongholdPiece(genDepth), isSource(true), entryDoor(OPENING) { orientation = random->nextInt(4); - switch (orientation) - { - case Direction::NORTH: - case Direction::SOUTH: - boundingBox = new BoundingBox(west, 64, north, west + width - 1, 64 + height - 1, north + depth - 1); - break; - default: - boundingBox = new BoundingBox(west, 64, north, west + depth - 1, 64 + height - 1, north + width - 1); - break; + switch (orientation) { + case Direction::NORTH: + case Direction::SOUTH: + boundingBox = new BoundingBox(west, 64, north, west + width - 1, + 64 + height - 1, north + depth - 1); + break; + default: + boundingBox = new BoundingBox(west, 64, north, west + depth - 1, + 64 + height - 1, north + width - 1); + break; } } -StrongholdPieces::StairsDown::StairsDown(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), isSource(false), entryDoor(randomSmallDoor(random)) -{ +StrongholdPieces::StairsDown::StairsDown(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : StrongholdPiece(genDepth), + isSource(false), + entryDoor(randomSmallDoor(random)) { orientation = direction; boundingBox = stairsBox; } -void StrongholdPieces::StairsDown::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - if( isSource ) - { - imposedPiece = EPieceClass_FiveCrossing; - } - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 1, 1); +void StrongholdPieces::StairsDown::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + if (isSource) { + imposedPiece = EPieceClass_FiveCrossing; + } + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 1, + 1); } -StrongholdPieces::StairsDown *StrongholdPieces::StairsDown::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); +StrongholdPieces::StairsDown* StrongholdPieces::StairsDown::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = + BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, + height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new StairsDown(genDepth, random, box, direction); } -bool StrongholdPieces::StairsDown::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { - return false; - } +bool StrongholdPieces::StairsDown::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { + return false; + } - // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); - // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); - // exit door - generateSmallDoor(level, random, chunkBB, OPENING, 1, 1, depth - 1); + // bounding walls + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); + // entry door + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); + // exit door + generateSmallDoor(level, random, chunkBB, OPENING, 1, 1, depth - 1); - // stair steps - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 6, 1, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 5, 1, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 6, 1, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 5, 2, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 4, 3, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 5, 3, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 4, 3, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 3, 3, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 3, 4, 3, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 3, 2, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 2, 1, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 3, 3, 1, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 2, 1, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 1, 1, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 2, 1, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 1, 2, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 1, 3, chunkBB); + // stair steps + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 6, 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 5, 1, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 6, + 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 5, 2, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 4, 3, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 5, + 3, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 4, 3, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 3, 3, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 3, 4, + 3, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 3, 2, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 2, 1, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 3, 3, + 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, 2, 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 1, 1, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 2, + 1, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, 1, 2, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::STONE_SLAB, 1, 1, + 3, chunkBB); - return true; + return true; } -StrongholdPieces::StartPiece::StartPiece(int genDepth, Random *random, int west, int north, Level *level) : StairsDown(0, random, west, north) -{ - // 4J added initialisers - isLibraryAdded = false; - previousPiece = NULL; - portalRoomPiece = NULL; +StrongholdPieces::StartPiece::StartPiece(int genDepth, Random* random, int west, + int north, Level* level) + : StairsDown(0, random, west, north) { + // 4J added initialisers + isLibraryAdded = false; + previousPiece = NULL; + portalRoomPiece = NULL; - m_level = level; + m_level = level; } -TilePos *StrongholdPieces::StartPiece::getLocatorPosition() -{ - if( portalRoomPiece != NULL ) - { - return portalRoomPiece->getLocatorPosition(); - } - return StairsDown::getLocatorPosition(); +TilePos* StrongholdPieces::StartPiece::getLocatorPosition() { + if (portalRoomPiece != NULL) { + return portalRoomPiece->getLocatorPosition(); + } + return StairsDown::getLocatorPosition(); } -StrongholdPieces::Straight::Straight(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), - entryDoor(randomSmallDoor(random)), - leftChild(random->nextInt(2) == 0), - rightChild(random->nextInt(2) == 0) -{ +StrongholdPieces::Straight::Straight(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : StrongholdPiece(genDepth), + entryDoor(randomSmallDoor(random)), + leftChild(random->nextInt(2) == 0), + rightChild(random->nextInt(2) == 0) { orientation = direction; boundingBox = stairsBox; } -void StrongholdPieces::Straight::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 1, 1); - if (leftChild) generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, 1, 2); - if (rightChild) generateSmallDoorChildRight((StartPiece *) startPiece, pieces, random, 1, 2); +void StrongholdPieces::Straight::addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random) { + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 1, + 1); + if (leftChild) + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, 1, + 2); + if (rightChild) + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, 1, + 2); } -StrongholdPieces::Straight *StrongholdPieces::Straight::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); +StrongholdPieces::Straight* StrongholdPieces::Straight::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new Straight(genDepth, random, box, direction); } -bool StrongholdPieces::Straight::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::Straight::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); // exit door generateSmallDoor(level, random, chunkBB, OPENING, 1, 1, depth - 1); @@ -613,309 +694,346 @@ bool StrongholdPieces::Straight::postProcess(Level *level, Random *random, Bound maybeGenerateBlock(level, chunkBB, random, .1f, 1, 2, 5, Tile::torch_Id, 0); maybeGenerateBlock(level, chunkBB, random, .1f, 3, 2, 5, Tile::torch_Id, 0); - if (leftChild) - { + if (leftChild) { generateBox(level, chunkBB, 0, 1, 2, 0, 3, 4, 0, 0, false); } - if (rightChild) - { + if (rightChild) { generateBox(level, chunkBB, 4, 1, 2, 4, 3, 4, 0, 0, false); } return true; } -WeighedTreasure *StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = -{ - new WeighedTreasure(Item::enderPearl_Id, 0, 1, 1, 10), - new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), - new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), - new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), - new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5), - new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15), - new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15), - new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::sword_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::chestplate_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::helmet_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::leggings_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::boots_iron_Id, 0, 1, 1, 5), - new WeighedTreasure(Item::apple_gold_Id, 0, 1, 1, 1) -}; +WeighedTreasure* + StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = { + new WeighedTreasure(Item::enderPearl_Id, 0, 1, 1, 10), + new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), + new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), + new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), + new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5), + new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15), + new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15), + new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::sword_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::chestplate_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::helmet_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::leggings_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::boots_iron_Id, 0, 1, 1, 5), + new WeighedTreasure(Item::apple_gold_Id, 0, 1, 1, 1)}; -StrongholdPieces::ChestCorridor::ChestCorridor(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) -{ - orientation = direction; - boundingBox = stairsBox; +StrongholdPieces::ChestCorridor::ChestCorridor(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) { + orientation = direction; + boundingBox = stairsBox; } -void StrongholdPieces::ChestCorridor::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 1, 1); +void StrongholdPieces::ChestCorridor::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 1, + 1); } -StrongholdPieces::ChestCorridor *StrongholdPieces::ChestCorridor::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); +StrongholdPieces::ChestCorridor* StrongholdPieces::ChestCorridor::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new ChestCorridor(genDepth, random, box, direction); } -bool StrongholdPieces::ChestCorridor::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::ChestCorridor::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); // exit door generateSmallDoor(level, random, chunkBB, OPENING, 1, 1, depth - 1); // chest placement - generateBox(level, chunkBB, 3, 1, 2, 3, 1, 4, Tile::stoneBrickSmooth_Id, Tile::stoneBrickSmooth_Id, false); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, 3, 1, 1, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, 3, 1, 5, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, 3, 2, 2, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, 3, 2, 4, chunkBB); - for (int z = 2; z <= 4; z++) - { - placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, 2, 1, z, chunkBB); + generateBox(level, chunkBB, 3, 1, 2, 3, 1, 4, Tile::stoneBrickSmooth_Id, + Tile::stoneBrickSmooth_Id, false); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, + 3, 1, 1, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, + 3, 1, 5, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, + 3, 2, 2, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, StoneSlabTile::SMOOTHBRICK_SLAB, + 3, 2, 4, chunkBB); + for (int z = 2; z <= 4; z++) { + placeBlock(level, Tile::stoneSlabHalf_Id, + StoneSlabTile::SMOOTHBRICK_SLAB, 2, 1, z, chunkBB); } - if (!hasPlacedChest) - { + if (!hasPlacedChest) { int y = getWorldY(2); int x = getWorldX(3, 3), z = getWorldZ(3, 3); - if (chunkBB->isInside(x, y, z)) - { + if (chunkBB->isInside(x, y, z)) { hasPlacedChest = true; - createChest(level, chunkBB, random, 3, 2, 3, WeighedTreasure::addToTreasure(WeighedTreasureArray(treasureItems,TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random)), 2 + random->nextInt(2)); + createChest( + level, chunkBB, random, 3, 2, 3, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(treasureItems, TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random)), + 2 + random->nextInt(2)); } } - return true; + return true; } -StrongholdPieces::StraightStairsDown::StraightStairsDown(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) -{ +StrongholdPieces::StraightStairsDown::StraightStairsDown(int genDepth, + Random* random, + BoundingBox* stairsBox, + int direction) + : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) { orientation = direction; boundingBox = stairsBox; } -void StrongholdPieces::StraightStairsDown::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 1, 1); +void StrongholdPieces::StraightStairsDown::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 1, + 1); } -StrongholdPieces::StraightStairsDown *StrongholdPieces::StraightStairsDown::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); +StrongholdPieces::StraightStairsDown* +StrongholdPieces::StraightStairsDown::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = + BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, + height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new StraightStairsDown(genDepth, random, box, direction); } -bool StrongholdPieces::StraightStairsDown::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::StraightStairsDown::postProcess(Level* level, + Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); // exit door generateSmallDoor(level, random, chunkBB, OPENING, 1, 1, depth - 1); // stairs int orientationData = getOrientationData(Tile::stairs_stone_Id, 2); - for (int i = 0; i < 6; i++) - { - placeBlock(level, Tile::stairs_stone_Id, orientationData, 1, height - 5 - i, 1 + i, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, orientationData, 2, height - 5 - i, 1 + i, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, orientationData, 3, height - 5 - i, 1 + i, chunkBB); - if (i < 5) - { - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, height - 6 - i, 1 + i, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, height - 6 - i, 1 + i, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, height - 6 - i, 1 + i, chunkBB); + for (int i = 0; i < 6; i++) { + placeBlock(level, Tile::stairs_stone_Id, orientationData, 1, + height - 5 - i, 1 + i, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, orientationData, 2, + height - 5 - i, 1 + i, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, orientationData, 3, + height - 5 - i, 1 + i, chunkBB); + if (i < 5) { + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 1, height - 6 - i, + 1 + i, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 2, height - 6 - i, + 1 + i, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, height - 6 - i, + 1 + i, chunkBB); } } return true; } -StrongholdPieces::LeftTurn::LeftTurn(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) -{ +StrongholdPieces::LeftTurn::LeftTurn(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) { orientation = direction; boundingBox = stairsBox; } -void StrongholdPieces::LeftTurn::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - if (orientation == Direction::NORTH || orientation == Direction::EAST) - { - generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, 1, 1); - } - else - { - generateSmallDoorChildRight((StartPiece *) startPiece, pieces, random, 1, 1); - } +void StrongholdPieces::LeftTurn::addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random) { + if (orientation == Direction::NORTH || orientation == Direction::EAST) { + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, 1, + 1); + } else { + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, 1, + 1); + } } -StrongholdPieces::LeftTurn *StrongholdPieces::LeftTurn::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); +StrongholdPieces::LeftTurn* StrongholdPieces::LeftTurn::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new LeftTurn(genDepth, random, box, direction); } -bool StrongholdPieces::LeftTurn::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::LeftTurn::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); // exit opening - if (orientation == Direction::NORTH || orientation == Direction::EAST) - { + if (orientation == Direction::NORTH || orientation == Direction::EAST) { generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, 0, 0, false); - } - else - { + } else { generateBox(level, chunkBB, 4, 1, 1, 4, 3, 3, 0, 0, false); } return true; } -StrongholdPieces::RightTurn::RightTurn(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : LeftTurn(genDepth, random, stairsBox, direction) -{ -} +StrongholdPieces::RightTurn::RightTurn(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : LeftTurn(genDepth, random, stairsBox, direction) {} -void StrongholdPieces::RightTurn::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - if (orientation == Direction::NORTH || orientation == Direction::EAST) - { - generateSmallDoorChildRight((StartPiece *) startPiece, pieces, random, 1, 1); - } - else - { - generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, 1, 1); +void StrongholdPieces::RightTurn::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + if (orientation == Direction::NORTH || orientation == Direction::EAST) { + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, 1, + 1); + } else { + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, 1, + 1); } } -bool StrongholdPieces::RightTurn::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::RightTurn::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door - generateSmallDoor(level, random, chunkBB, entryDoor, 1, height - SMALL_DOOR_HEIGHT - 1, 0); + generateSmallDoor(level, random, chunkBB, entryDoor, 1, + height - SMALL_DOOR_HEIGHT - 1, 0); // exit opening - if (orientation == Direction::NORTH || orientation == Direction::EAST) - { + if (orientation == Direction::NORTH || orientation == Direction::EAST) { generateBox(level, chunkBB, 4, 1, 1, 4, 3, 3, 0, 0, false); - } - else - { + } else { generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, 0, 0, false); } return true; } - -StrongholdPieces::RoomCrossing::RoomCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)), type(random->nextInt(5)) -{ +StrongholdPieces::RoomCrossing::RoomCrossing(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : StrongholdPiece(genDepth), + entryDoor(randomSmallDoor(random)), + type(random->nextInt(5)) { orientation = direction; - boundingBox = stairsBox; + boundingBox = stairsBox; } -void StrongholdPieces::RoomCrossing::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateSmallDoorChildForward((StartPiece*) startPiece, pieces, random, 4, 1); - generateSmallDoorChildLeft((StartPiece*) startPiece, pieces, random, 1, 4); - generateSmallDoorChildRight((StartPiece*) startPiece, pieces, random, 1, 4); +void StrongholdPieces::RoomCrossing::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 4, + 1); + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, 1, 4); + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, 1, 4); } -StrongholdPieces::RoomCrossing *StrongholdPieces::RoomCrossing::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); +StrongholdPieces::RoomCrossing* StrongholdPieces::RoomCrossing::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new RoomCrossing(genDepth, random, box, direction); } -WeighedTreasure *StrongholdPieces::RoomCrossing::smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT] = -{ - new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), - new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), - new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5), - new WeighedTreasure(Item::coal_Id, CoalItem::STONE_COAL, 3, 8, 10), - new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15), - new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15), - new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 1), +WeighedTreasure* StrongholdPieces::RoomCrossing::smallTreasureItems + [SMALL_TREASURE_ITEMS_COUNT] = { + new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), + new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), + new WeighedTreasure(Item::redStone_Id, 0, 4, 9, 5), + new WeighedTreasure(Item::coal_Id, CoalItem::STONE_COAL, 3, 8, 10), + new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15), + new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15), + new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 1), }; -bool StrongholdPieces::RoomCrossing::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::RoomCrossing::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door generateSmallDoor(level, random, chunkBB, entryDoor, 4, 1, 0); // exit openings @@ -923,186 +1041,213 @@ bool StrongholdPieces::RoomCrossing::postProcess(Level *level, Random *random, B generateBox(level, chunkBB, 0, 1, 4, 0, 3, 6, 0, 0, false); generateBox(level, chunkBB, width - 1, 1, 4, width - 1, 3, 6, 0, 0, false); - switch (type) - { - default: - break; - case 0: - // middle torch pillar - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 1, 5, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 2, 5, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 3, 5, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 4, 3, 5, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 6, 3, 5, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 5, 3, 4, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 5, 3, 6, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 4, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 5, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 6, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 4, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 5, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 6, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 5, 1, 4, chunkBB); - placeBlock(level, Tile::stoneSlabHalf_Id, 0, 5, 1, 6, chunkBB); - break; - case 1: - { - for (int i = 0; i < 5; i++) - { - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 1, 3 + i, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 7, 1, 3 + i, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3 + i, 1, 3, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3 + i, 1, 7, chunkBB); - } - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 1, 5, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 2, 5, chunkBB); - placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 3, 5, chunkBB); - placeBlock(level, Tile::water_Id, 0, 5, 4, 5, chunkBB); - } - break; - case 2: - { - for (int z = 1; z <= 9; z++) - { - placeBlock(level, Tile::stoneBrick_Id, 0, 1, 3, z, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 9, 3, z, chunkBB); - } - for (int x = 1; x <= 9; x++) - { - placeBlock(level, Tile::stoneBrick_Id, 0, x, 3, 1, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, x, 3, 9, chunkBB); - } - placeBlock(level, Tile::stoneBrick_Id, 0, 5, 1, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 5, 1, 6, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 5, 3, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 5, 3, 6, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 5, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, 1, 5, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 5, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, 3, 5, chunkBB); - for (int y = 1; y <= 3; y++) - { - placeBlock(level, Tile::stoneBrick_Id, 0, 4, y, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, y, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, y, 6, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, y, 6, chunkBB); - } - placeBlock(level, Tile::torch_Id, 0, 5, 3, 5, chunkBB); - for (int z = 2; z <= 8; z++) - { - placeBlock(level, Tile::wood_Id, 0, 2, 3, z, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 3, 3, z, chunkBB); - if (z <= 3 || z >= 7) - { - placeBlock(level, Tile::wood_Id, 0, 4, 3, z, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 5, 3, z, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 6, 3, z, chunkBB); - } - placeBlock(level, Tile::wood_Id, 0, 7, 3, z, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 3, z, chunkBB); - } - placeBlock(level, Tile::ladder_Id, getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 1, 3, chunkBB); - placeBlock(level, Tile::ladder_Id, getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 2, 3, chunkBB); - placeBlock(level, Tile::ladder_Id, getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 3, 3, chunkBB); + switch (type) { + default: + break; + case 0: + // middle torch pillar + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 1, 5, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 2, 5, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 3, 5, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 4, 3, 5, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 6, 3, 5, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 5, 3, 4, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 5, 3, 6, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 4, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 5, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 4, 1, 6, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 4, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 5, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 6, 1, 6, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 5, 1, 4, chunkBB); + placeBlock(level, Tile::stoneSlabHalf_Id, 0, 5, 1, 6, chunkBB); + break; + case 1: { + for (int i = 0; i < 5; i++) { + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3, 1, 3 + i, + chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 7, 1, 3 + i, + chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3 + i, 1, 3, + chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 3 + i, 1, 7, + chunkBB); + } + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 1, 5, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 2, 5, chunkBB); + placeBlock(level, Tile::stoneBrickSmooth_Id, 0, 5, 3, 5, chunkBB); + placeBlock(level, Tile::water_Id, 0, 5, 4, 5, chunkBB); + } break; + case 2: { + for (int z = 1; z <= 9; z++) { + placeBlock(level, Tile::stoneBrick_Id, 0, 1, 3, z, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 9, 3, z, chunkBB); + } + for (int x = 1; x <= 9; x++) { + placeBlock(level, Tile::stoneBrick_Id, 0, x, 3, 1, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, x, 3, 9, chunkBB); + } + placeBlock(level, Tile::stoneBrick_Id, 0, 5, 1, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 5, 1, 6, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 5, 3, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 5, 3, 6, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 5, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, 1, 5, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 5, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, 3, 5, chunkBB); + for (int y = 1; y <= 3; y++) { + placeBlock(level, Tile::stoneBrick_Id, 0, 4, y, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, y, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, y, 6, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, y, 6, chunkBB); + } + placeBlock(level, Tile::torch_Id, 0, 5, 3, 5, chunkBB); + for (int z = 2; z <= 8; z++) { + placeBlock(level, Tile::wood_Id, 0, 2, 3, z, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 3, 3, z, chunkBB); + if (z <= 3 || z >= 7) { + placeBlock(level, Tile::wood_Id, 0, 4, 3, z, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 5, 3, z, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 6, 3, z, chunkBB); + } + placeBlock(level, Tile::wood_Id, 0, 7, 3, z, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 3, z, chunkBB); + } + placeBlock(level, Tile::ladder_Id, + getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 1, + 3, chunkBB); + placeBlock(level, Tile::ladder_Id, + getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 2, + 3, chunkBB); + placeBlock(level, Tile::ladder_Id, + getOrientationData(Tile::ladder_Id, Facing::WEST), 9, 3, + 3, chunkBB); - createChest(level, chunkBB, random, 3, 4, 8, WeighedTreasure::addToTreasure(WeighedTreasureArray(smallTreasureItems,SMALL_TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random)), 1 + random->nextInt(4)); - // System.out.println("Created chest at " + getWorldX(3, 8) + - // "," + getWorldY(4) + "," + getWorldZ(3, 8)); + createChest( + level, chunkBB, random, 3, 4, 8, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(smallTreasureItems, + SMALL_TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random)), + 1 + random->nextInt(4)); + // System.out.println("Created chest at " + getWorldX(3, 8) + + // "," + getWorldY(4) + "," + getWorldZ(3, 8)); - } - break; + } break; } return true; } -StrongholdPieces::PrisonHall::PrisonHall(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) -{ +StrongholdPieces::PrisonHall::PrisonHall(int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) { orientation = direction; boundingBox = stairsBox; } -void StrongholdPieces::PrisonHall::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 1, 1); +void StrongholdPieces::PrisonHall::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 1, + 1); } -StrongholdPieces::PrisonHall *StrongholdPieces::PrisonHall::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); +StrongholdPieces::PrisonHall* StrongholdPieces::PrisonHall::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new PrisonHall(genDepth, random, box, direction); } -bool StrongholdPieces::PrisonHall::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::PrisonHall::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door generateSmallDoor(level, random, chunkBB, entryDoor, 1, 1, 0); // exit openings generateBox(level, chunkBB, 1, 1, depth - 1, 3, 3, depth - 1, 0, 0, false); // door pillars - generateBox(level, chunkBB, 4, 1, 1, 4, 3, 1, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 1, 3, 4, 3, 3, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 1, 7, 4, 3, 7, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 1, 9, 4, 3, 9, false, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 1, 4, 3, 1, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 3, 4, 3, 3, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 7, 4, 3, 7, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 9, 4, 3, 9, false, random, + (BlockSelector*)smoothStoneSelector); // grates - generateBox(level, chunkBB, 4, 1, 4, 4, 3, 6, Tile::ironFence_Id, Tile::ironFence_Id, false); - generateBox(level, chunkBB, 5, 1, 5, 7, 3, 5, Tile::ironFence_Id, Tile::ironFence_Id, false); + generateBox(level, chunkBB, 4, 1, 4, 4, 3, 6, Tile::ironFence_Id, + Tile::ironFence_Id, false); + generateBox(level, chunkBB, 5, 1, 5, 7, 3, 5, Tile::ironFence_Id, + Tile::ironFence_Id, false); // doors placeBlock(level, Tile::ironFence_Id, 0, 4, 3, 2, chunkBB); placeBlock(level, Tile::ironFence_Id, 0, 4, 3, 8, chunkBB); - placeBlock(level, Tile::door_iron_Id, getOrientationData(Tile::door_iron_Id, 3), 4, 1, 2, chunkBB); - placeBlock(level, Tile::door_iron_Id, getOrientationData(Tile::door_iron_Id, 3) + DoorTile::UPPER_BIT, 4, 2, 2, chunkBB); - placeBlock(level, Tile::door_iron_Id, getOrientationData(Tile::door_iron_Id, 3), 4, 1, 8, chunkBB); - placeBlock(level, Tile::door_iron_Id, getOrientationData(Tile::door_iron_Id, 3) + DoorTile::UPPER_BIT, 4, 2, 8, chunkBB); + placeBlock(level, Tile::door_iron_Id, + getOrientationData(Tile::door_iron_Id, 3), 4, 1, 2, chunkBB); + placeBlock(level, Tile::door_iron_Id, + getOrientationData(Tile::door_iron_Id, 3) + DoorTile::UPPER_BIT, + 4, 2, 2, chunkBB); + placeBlock(level, Tile::door_iron_Id, + getOrientationData(Tile::door_iron_Id, 3), 4, 1, 8, chunkBB); + placeBlock(level, Tile::door_iron_Id, + getOrientationData(Tile::door_iron_Id, 3) + DoorTile::UPPER_BIT, + 4, 2, 8, chunkBB); return true; - } -StrongholdPieces::Library::Library(int genDepth, Random *random, BoundingBox *roomBox, int direction) : StrongholdPiece(genDepth), - entryDoor(randomSmallDoor(random)), - isTall(roomBox->getYSpan() > height) -{ +StrongholdPieces::Library::Library(int genDepth, Random* random, + BoundingBox* roomBox, int direction) + : StrongholdPiece(genDepth), + entryDoor(randomSmallDoor(random)), + isTall(roomBox->getYSpan() > height) { orientation = direction; boundingBox = roomBox; } -StrongholdPieces::Library *StrongholdPieces::Library::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ +StrongholdPieces::Library* StrongholdPieces::Library::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { // attempt to make a tall library first - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, tallHeight, depth, direction); + BoundingBox* box = BoundingBox::orientBox( + footX, footY, footZ, -4, -1, 0, width, tallHeight, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; // make a short library - box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); + box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, + height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } } @@ -1110,34 +1255,35 @@ StrongholdPieces::Library *StrongholdPieces::Library::createPiece(std::listcreateForRandomTreasure(random, 1, 5, 2)), 1 + random->nextInt(4)); - if (isTall) - { + createChest( + level, chunkBB, random, 3, 3, 5, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(libraryTreasureItems, + LIBRARY_TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random, 1, 5, 2)), + 1 + random->nextInt(4)); + if (isTall) { placeBlock(level, 0, 0, width - 2, tallHeight - 2, 1, chunkBB); - createChest(level, chunkBB, random, width - 2, tallHeight - 3, 1, WeighedTreasure::addToTreasure(WeighedTreasureArray(libraryTreasureItems,LIBRARY_TREASURE_ITEMS_COUNT), Item::enchantedBook->createForRandomTreasure(random, 1, 5, 2)), 1 + random->nextInt(4)); + createChest( + level, chunkBB, random, width - 2, tallHeight - 3, 1, + WeighedTreasure::addToTreasure( + WeighedTreasureArray(libraryTreasureItems, + LIBRARY_TREASURE_ITEMS_COUNT), + Item::enchantedBook->createForRandomTreasure(random, 1, 5, 2)), + 1 + random->nextInt(4)); } return true; - } -StrongholdPieces::FiveCrossing::FiveCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction) : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) -{ +StrongholdPieces::FiveCrossing::FiveCrossing(int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : StrongholdPiece(genDepth), entryDoor(randomSmallDoor(random)) { orientation = direction; boundingBox = stairsBox; @@ -1257,49 +1439,61 @@ StrongholdPieces::FiveCrossing::FiveCrossing(int genDepth, Random *random, Bound rightHigh = random->nextInt(3) > 0; } -void StrongholdPieces::FiveCrossing::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ +void StrongholdPieces::FiveCrossing::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { int zOffA = 3; int zOffB = 5; // compensate for weird negative-facing behaviour - if (orientation == Direction::WEST || orientation == Direction::NORTH) - { + if (orientation == Direction::WEST || orientation == Direction::NORTH) { zOffA = depth - 3 - zOffA; zOffB = depth - 3 - zOffB; - } - - generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 5, 1); - if (leftLow) generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, zOffA, 1); - if (leftHigh) generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, zOffB, 7); - if (rightLow) generateSmallDoorChildRight((StartPiece *) startPiece, pieces, random, zOffA, 1); - if (rightHigh) generateSmallDoorChildRight((StartPiece *) startPiece, pieces, random, zOffB, 7); + } + + generateSmallDoorChildForward((StartPiece*)startPiece, pieces, random, 5, + 1); + if (leftLow) + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, + zOffA, 1); + if (leftHigh) + generateSmallDoorChildLeft((StartPiece*)startPiece, pieces, random, + zOffB, 7); + if (rightLow) + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, + zOffA, 1); + if (rightHigh) + generateSmallDoorChildRight((StartPiece*)startPiece, pieces, random, + zOffB, 7); } -StrongholdPieces::FiveCrossing *StrongholdPieces::FiveCrossing::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -3, 0, width, height, depth, direction); +StrongholdPieces::FiveCrossing* StrongholdPieces::FiveCrossing::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -4, -3, 0, + width, height, depth, direction); - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new FiveCrossing(genDepth, random, box, direction); } -bool StrongholdPieces::FiveCrossing::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (edgesLiquid(level, chunkBB)) - { +bool StrongholdPieces::FiveCrossing::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (edgesLiquid(level, chunkBB)) { return false; } // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, CHECK_AIR, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + CHECK_AIR, random, (BlockSelector*)smoothStoneSelector); // entry door generateSmallDoor(level, random, chunkBB, entryDoor, 4, 3, 0); @@ -1311,207 +1505,283 @@ bool StrongholdPieces::FiveCrossing::postProcess(Level *level, Random *random, B generateBox(level, chunkBB, 5, 1, 10, 7, 3, 10, 0, 0, false); // main floor - generateBox(level, chunkBB, 1, 2, 1, 8, 2, 6, false, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 1, 2, 1, 8, 2, 6, false, random, + (BlockSelector*)smoothStoneSelector); // side walls - generateBox(level, chunkBB, 4, 1, 5, 4, 4, 9, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 8, 1, 5, 8, 4, 9, false, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 5, 4, 4, 9, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 8, 1, 5, 8, 4, 9, false, random, + (BlockSelector*)smoothStoneSelector); // upper floor - generateBox(level, chunkBB, 1, 4, 7, 3, 4, 9, false, random, (BlockSelector *)smoothStoneSelector); + generateBox(level, chunkBB, 1, 4, 7, 3, 4, 9, false, random, + (BlockSelector*)smoothStoneSelector); // left stairs - generateBox(level, chunkBB, 1, 3, 5, 3, 3, 6, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 1, 3, 4, 3, 3, 4, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); - generateBox(level, chunkBB, 1, 4, 6, 3, 4, 6, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 1, 3, 5, 3, 3, 6, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 1, 3, 4, 3, 3, 4, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 1, 4, 6, 3, 4, 6, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); // lower stairs - generateBox(level, chunkBB, 5, 1, 7, 7, 1, 8, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 5, 1, 9, 7, 1, 9, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); - generateBox(level, chunkBB, 5, 2, 7, 7, 2, 7, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 5, 1, 7, 7, 1, 8, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 5, 1, 9, 7, 1, 9, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 5, 2, 7, 7, 2, 7, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); // bridge - generateBox(level, chunkBB, 4, 5, 7, 4, 5, 9, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); - generateBox(level, chunkBB, 8, 5, 7, 8, 5, 9, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); - generateBox(level, chunkBB, 5, 5, 7, 7, 5, 9, Tile::stoneSlab_Id, Tile::stoneSlab_Id, false); + generateBox(level, chunkBB, 4, 5, 7, 4, 5, 9, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 8, 5, 7, 8, 5, 9, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 5, 5, 7, 7, 5, 9, Tile::stoneSlab_Id, + Tile::stoneSlab_Id, false); placeBlock(level, Tile::torch_Id, 0, 6, 5, 6, chunkBB); return true; - } -StrongholdPieces::PortalRoom::PortalRoom(int genDepth, Random *random, BoundingBox *box, int direction) : StrongholdPiece(genDepth) -{ - hasPlacedMobSpawner = false; +StrongholdPieces::PortalRoom::PortalRoom(int genDepth, Random* random, + BoundingBox* box, int direction) + : StrongholdPiece(genDepth) { + hasPlacedMobSpawner = false; orientation = direction; boundingBox = box; } -void StrongholdPieces::PortalRoom::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - if (startPiece != NULL) - { - ((StartPiece *) startPiece)->portalRoomPiece = this; +void StrongholdPieces::PortalRoom::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + if (startPiece != NULL) { + ((StartPiece*)startPiece)->portalRoomPiece = this; } } -StrongholdPieces::PortalRoom *StrongholdPieces::PortalRoom::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); +StrongholdPieces::PortalRoom* StrongholdPieces::PortalRoom::createPiece( + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, + width, height, depth, direction); - // 4J Added so that we can check that Portals stay within the bounds of the world (which they ALWAYS should anyway) - StartPiece *startPiece = NULL; - if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); + // 4J Added so that we can check that Portals stay within the bounds of the + // world (which they ALWAYS should anyway) + StartPiece* startPiece = NULL; + if (pieces != NULL) + startPiece = ((StrongholdPieces::StartPiece*)pieces->front()); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; return NULL; } return new PortalRoom(genDepth, random, box, direction); } -bool StrongholdPieces::PortalRoom::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - // bounding walls - generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, false, random, (BlockSelector *)smoothStoneSelector); - // entry door - generateSmallDoor(level, random, chunkBB, GRATES, 4, 1, 0); +bool StrongholdPieces::PortalRoom::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + // bounding walls + generateBox(level, chunkBB, 0, 0, 0, width - 1, height - 1, depth - 1, + false, random, (BlockSelector*)smoothStoneSelector); + // entry door + generateSmallDoor(level, random, chunkBB, GRATES, 4, 1, 0); - // inner roof row - int y = height - 2; - generateBox(level, chunkBB, 1, y, 1, 1, y, depth - 2, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, width - 2, y, 1, width - 2, y, depth - 2, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 2, y, 1, width - 3, y, 2, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 2, y, depth - 2, width - 3, y, depth - 2, false, random, (BlockSelector *)smoothStoneSelector); + // inner roof row + int y = height - 2; + generateBox(level, chunkBB, 1, y, 1, 1, y, depth - 2, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, width - 2, y, 1, width - 2, y, depth - 2, false, + random, (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 2, y, 1, width - 3, y, 2, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 2, y, depth - 2, width - 3, y, depth - 2, false, + random, (BlockSelector*)smoothStoneSelector); - // entrance lava pools - generateBox(level, chunkBB, 1, 1, 1, 2, 1, 4, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, width - 3, 1, 1, width - 2, 1, 4, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 1, 1, 1, 1, 1, 3, Tile::lava_Id, Tile::lava_Id, false); - generateBox(level, chunkBB, width - 2, 1, 1, width - 2, 1, 3, Tile::lava_Id, Tile::lava_Id, false); + // entrance lava pools + generateBox(level, chunkBB, 1, 1, 1, 2, 1, 4, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, width - 3, 1, 1, width - 2, 1, 4, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 1, 1, 1, 1, 1, 3, Tile::lava_Id, Tile::lava_Id, + false); + generateBox(level, chunkBB, width - 2, 1, 1, width - 2, 1, 3, Tile::lava_Id, + Tile::lava_Id, false); - // portal lava pool - generateBox(level, chunkBB, 3, 1, 8, 7, 1, 12, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 1, 9, 6, 1, 11, Tile::lava_Id, Tile::lava_Id, false); + // portal lava pool + generateBox(level, chunkBB, 3, 1, 8, 7, 1, 12, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 1, 9, 6, 1, 11, Tile::lava_Id, Tile::lava_Id, + false); - // wall decorations - for (int z = 3; z < depth - 2; z += 2) - { - generateBox(level, chunkBB, 0, 3, z, 0, 4, z, Tile::ironFence_Id, Tile::ironFence_Id, false); - generateBox(level, chunkBB, width - 1, 3, z, width - 1, 4, z, Tile::ironFence_Id, Tile::ironFence_Id, false); - } - for (int x = 2; x < width - 2; x += 2) - { - generateBox(level, chunkBB, x, 3, depth - 1, x, 4, depth - 1, Tile::ironFence_Id, Tile::ironFence_Id, false); - } + // wall decorations + for (int z = 3; z < depth - 2; z += 2) { + generateBox(level, chunkBB, 0, 3, z, 0, 4, z, Tile::ironFence_Id, + Tile::ironFence_Id, false); + generateBox(level, chunkBB, width - 1, 3, z, width - 1, 4, z, + Tile::ironFence_Id, Tile::ironFence_Id, false); + } + for (int x = 2; x < width - 2; x += 2) { + generateBox(level, chunkBB, x, 3, depth - 1, x, 4, depth - 1, + Tile::ironFence_Id, Tile::ironFence_Id, false); + } - // stair - int orientationData = getOrientationData(Tile::stairs_stoneBrickSmooth_Id, 3); - generateBox(level, chunkBB, 4, 1, 5, 6, 1, 7, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 2, 6, 6, 2, 7, false, random, (BlockSelector *)smoothStoneSelector); - generateBox(level, chunkBB, 4, 3, 7, 6, 3, 7, false, random, (BlockSelector *)smoothStoneSelector); - for (int x = 4; x <= 6; x++) - { - placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, 2, 5, chunkBB); - placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, 3, 6, chunkBB); - } + // stair + int orientationData = + getOrientationData(Tile::stairs_stoneBrickSmooth_Id, 3); + generateBox(level, chunkBB, 4, 1, 5, 6, 1, 7, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 2, 6, 6, 2, 7, false, random, + (BlockSelector*)smoothStoneSelector); + generateBox(level, chunkBB, 4, 3, 7, 6, 3, 7, false, random, + (BlockSelector*)smoothStoneSelector); + for (int x = 4; x <= 6; x++) { + placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, + 1, 4, chunkBB); + placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, + 2, 5, chunkBB); + placeBlock(level, Tile::stairs_stoneBrickSmooth_Id, orientationData, x, + 3, 6, chunkBB); + } - int north = Direction::NORTH; - int south = Direction::SOUTH; - int east = Direction::EAST; - int west = Direction::WEST; + int north = Direction::NORTH; + int south = Direction::SOUTH; + int east = Direction::EAST; + int west = Direction::WEST; - switch (orientation) - { - case Direction::SOUTH: - north = Direction::SOUTH; - south = Direction::NORTH; - break; - case Direction::EAST: - north = Direction::EAST; - south = Direction::WEST; - east = Direction::SOUTH; - west = Direction::NORTH; - break; - case Direction::WEST: - north = Direction::WEST; - south = Direction::EAST; - east = Direction::SOUTH; - west = Direction::NORTH; - break; - } + switch (orientation) { + case Direction::SOUTH: + north = Direction::SOUTH; + south = Direction::NORTH; + break; + case Direction::EAST: + north = Direction::EAST; + south = Direction::WEST; + east = Direction::SOUTH; + west = Direction::NORTH; + break; + case Direction::WEST: + north = Direction::WEST; + south = Direction::EAST; + east = Direction::SOUTH; + west = Direction::NORTH; + break; + } - // 4J-PB - Removed for Christmas update since we don't have The End - - // 4J-PB - not going to remove it, so that maps generated will have it in, but it can't be activated - placeBlock(level, Tile::endPortalFrameTile_Id, north + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 4, 3, 8, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, north + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 5, 3, 8, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, north + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 6, 3, 8, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, south + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 4, 3, 12, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, south + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 5, 3, 12, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, south + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 6, 3, 12, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, east + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 3, 3, 9, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, east + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 3, 3, 10, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, east + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 3, 3, 11, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, west + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 7, 3, 9, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, west + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 7, 3, 10, chunkBB); - placeBlock(level, Tile::endPortalFrameTile_Id, west + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), 7, 3, 11, chunkBB); - + // 4J-PB - Removed for Christmas update since we don't have The End - if (!hasPlacedMobSpawner) - { - y = getWorldY(3); - int x = getWorldX(5, 6), z = getWorldZ(5, 6); - if (chunkBB->isInside(x, y, z)) - { - // 4J Stu - The mob spawner location is close enough for the map icon display, and this ensures that we only need to set the position once - app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal,x,z); - level->getLevelData()->setXStrongholdEndPortal(x); - level->getLevelData()->setZStrongholdEndPortal(z); - level->getLevelData()->setHasStrongholdEndPortal(); + // 4J-PB - not going to remove it, so that maps generated will have it in, + // but it can't be activated + placeBlock( + level, Tile::endPortalFrameTile_Id, + north + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 4, 3, 8, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + north + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 5, 3, 8, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + north + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 6, 3, 8, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + south + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 4, 3, 12, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + south + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 5, 3, 12, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + south + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 6, 3, 12, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + east + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 3, 3, 9, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + east + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 3, 3, 10, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + east + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 3, 3, 11, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + west + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 7, 3, 9, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + west + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 7, 3, 10, chunkBB); + placeBlock( + level, Tile::endPortalFrameTile_Id, + west + + ((random->nextFloat() > 0.9f) ? TheEndPortalFrameTile::EYE_BIT : 0), + 7, 3, 11, chunkBB); - hasPlacedMobSpawner = true; - level->setTile(x, y, z, Tile::mobSpawner_Id); - std::shared_ptr entity = std::dynamic_pointer_cast(level->getTileEntity(x, y, z)); - if (entity != NULL) entity->setEntityId(L"Silverfish"); - } - } + if (!hasPlacedMobSpawner) { + y = getWorldY(3); + int x = getWorldX(5, 6), z = getWorldZ(5, 6); + if (chunkBB->isInside(x, y, z)) { + // 4J Stu - The mob spawner location is close enough for the map + // icon display, and this ensures that we only need to set the + // position once + app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal, + x, z); + level->getLevelData()->setXStrongholdEndPortal(x); + level->getLevelData()->setZStrongholdEndPortal(z); + level->getLevelData()->setHasStrongholdEndPortal(); - return true; + hasPlacedMobSpawner = true; + level->setTile(x, y, z, Tile::mobSpawner_Id); + std::shared_ptr entity = + std::dynamic_pointer_cast( + level->getTileEntity(x, y, z)); + if (entity != NULL) entity->setEntityId(L"Silverfish"); + } + } + return true; } -void StrongholdPieces::SmoothStoneSelector::next(Random *random, int worldX, int worldY, int worldZ, bool isEdge) -{ - if (isEdge) - { +void StrongholdPieces::SmoothStoneSelector::next(Random* random, int worldX, + int worldY, int worldZ, + bool isEdge) { + if (isEdge) { nextId = Tile::stoneBrickSmooth_Id; float selection = random->nextFloat(); - if (selection < 0.2f) - { + if (selection < 0.2f) { nextData = SmoothStoneBrickTile::TYPE_CRACKED; - } - else if (selection < 0.5f) - { + } else if (selection < 0.5f) { nextData = SmoothStoneBrickTile::TYPE_MOSSY; - } - else if (selection < 0.55f) - { + } else if (selection < 0.55f) { nextId = Tile::monsterStoneEgg_Id; nextData = StoneMonsterTile::HOST_STONEBRICK; - } - else - { + } else { nextData = 0; } - } - else - { + } else { nextId = 0; nextData = 0; } } -const StrongholdPieces::SmoothStoneSelector *StrongholdPieces::smoothStoneSelector = new SmoothStoneSelector(); +const StrongholdPieces::SmoothStoneSelector* + StrongholdPieces::smoothStoneSelector = new SmoothStoneSelector(); diff --git a/Minecraft.World/WorldGen/Structures/StrongholdPieces.h b/Minecraft.World/WorldGen/Structures/StrongholdPieces.h index d9779d6a8..93f32faa7 100644 --- a/Minecraft.World/WorldGen/Structures/StrongholdPieces.h +++ b/Minecraft.World/WorldGen/Structures/StrongholdPieces.h @@ -1,396 +1,472 @@ #pragma once #include "StructurePiece.h" -class StrongholdPieces -{ - +class StrongholdPieces { private: - static const int SMALL_DOOR_WIDTH = 3; + static const int SMALL_DOOR_WIDTH = 3; static const int SMALL_DOOR_HEIGHT = 3; static const int MAX_DEPTH = 50; // the dungeon starts at 64 and traverses downwards to this point static const int LOWEST_Y_POSITION = 10; - static const bool CHECK_AIR; + static const bool CHECK_AIR; - // 4J - added to replace use of Class within this class - enum EPieceClass - { - EPieceClass_NULL, - EPieceClass_Straight, - EPieceClass_PrisonHall, - EPieceClass_LeftTurn, - EPieceClass_RightTurn, - EPieceClass_RoomCrossing, - EPieceClass_StraightStairsDown, - EPieceClass_StairsDown, - EPieceClass_FiveCrossing, - EPieceClass_ChestCorridor, - EPieceClass_Library, - EPieceClass_PortalRoom - }; - - class PieceWeight - { - public: - EPieceClass pieceClass; // 4J - was Class - const int weight; - int placeCount; - int maxPlaceCount; - - PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount); - virtual ~PieceWeight(){} - virtual bool doPlace(int depth); - bool isValid(); + // 4J - added to replace use of Class within this + // class + enum EPieceClass { + EPieceClass_NULL, + EPieceClass_Straight, + EPieceClass_PrisonHall, + EPieceClass_LeftTurn, + EPieceClass_RightTurn, + EPieceClass_RoomCrossing, + EPieceClass_StraightStairsDown, + EPieceClass_StairsDown, + EPieceClass_FiveCrossing, + EPieceClass_ChestCorridor, + EPieceClass_Library, + EPieceClass_PortalRoom }; - // 4J - added, java uses a local specialisation of these classes when instancing to achieve the same thing - class PieceWeight_Library : public PieceWeight - { - public: - PieceWeight_Library(EPieceClass pieceClass, int weight, int maxPlaceCount) : PieceWeight(pieceClass, weight, maxPlaceCount) {} - virtual bool doPlace(int depth) { return PieceWeight::doPlace(depth) && depth > 4; } - }; + class PieceWeight { + public: + EPieceClass pieceClass; // 4J - was Class + const int weight; + int placeCount; + int maxPlaceCount; - class PieceWeight_PortalRoom : public PieceWeight - { - public: - PieceWeight_PortalRoom(EPieceClass pieceClass, int weight, int maxPlaceCount) : PieceWeight(pieceClass, weight, maxPlaceCount) {} - virtual bool doPlace(int depth) { return PieceWeight::doPlace(depth) && depth > 5; } - }; + PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount); + virtual ~PieceWeight() {} + virtual bool doPlace(int depth); + bool isValid(); + }; - static std::list currentPieces; - static EPieceClass imposedPiece; + // 4J - added, java uses a local specialisation of these classes when + // instancing to achieve the same thing + class PieceWeight_Library : public PieceWeight { + public: + PieceWeight_Library(EPieceClass pieceClass, int weight, + int maxPlaceCount) + : PieceWeight(pieceClass, weight, maxPlaceCount) {} + virtual bool doPlace(int depth) { + return PieceWeight::doPlace(depth) && depth > 4; + } + }; + + class PieceWeight_PortalRoom : public PieceWeight { + public: + PieceWeight_PortalRoom(EPieceClass pieceClass, int weight, + int maxPlaceCount) + : PieceWeight(pieceClass, weight, maxPlaceCount) {} + virtual bool doPlace(int depth) { + return PieceWeight::doPlace(depth) && depth > 5; + } + }; + + static std::list currentPieces; + static EPieceClass imposedPiece; static int totalWeight; public: - static void resetPieces(); - class StartPiece; -private: - class StrongholdPiece; - static bool updatePieceWeight(); - static StrongholdPiece *findAndCreatePieceFactory(EPieceClass pieceClass, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - static StrongholdPiece *generatePieceFromSmallDoor(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - static StructurePiece *generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); + static void resetPieces(); + class StartPiece; +private: + class StrongholdPiece; + static bool updatePieceWeight(); + static StrongholdPiece* findAndCreatePieceFactory( + EPieceClass pieceClass, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); + static StrongholdPiece* generatePieceFromSmallDoor( + StartPiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); + static StructurePiece* generateAndAddPiece( + StartPiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); /** - * + * * */ private: - class StrongholdPiece : public StructurePiece - { + class StrongholdPiece : public StructurePiece { + protected: + StrongholdPiece(int genDepth); - protected: - StrongholdPiece(int genDepth); - - enum SmallDoorType - { - OPENING, WOOD_DOOR, GRATES, IRON_DOOR, + enum SmallDoorType { + OPENING, + WOOD_DOOR, + GRATES, + IRON_DOOR, }; - void generateSmallDoor(Level *level, Random *random, BoundingBox *chunkBB, SmallDoorType doorType, int footX, int footY, int footZ); - SmallDoorType randomSmallDoor(Random *random); - StructurePiece *generateSmallDoorChildForward(StartPiece *startPiece, std::list *pieces, Random *random, int xOff, int yOff); - StructurePiece *generateSmallDoorChildLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff); - StructurePiece *generateSmallDoorChildRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff); - - static bool isOkBox(BoundingBox *box, StartPiece *startRoom); // 4J added startRoom param + void generateSmallDoor(Level* level, Random* random, + BoundingBox* chunkBB, SmallDoorType doorType, + int footX, int footY, int footZ); + SmallDoorType randomSmallDoor(Random* random); + StructurePiece* generateSmallDoorChildForward( + StartPiece* startPiece, std::list* pieces, + Random* random, int xOff, int yOff); + StructurePiece* generateSmallDoorChildLeft( + StartPiece* startPiece, std::list* pieces, + Random* random, int yOff, int zOff); + StructurePiece* generateSmallDoorChildRight( + StartPiece* startPiece, std::list* pieces, + Random* random, int yOff, int zOff); + + static bool isOkBox(BoundingBox* box, + StartPiece* startRoom); // 4J added startRoom param }; /** * Corridor pieces that connects unconnected ends. - * - */ -public: - class FillerCorridor : public StrongholdPiece - { - private: - const int steps; - - public: - FillerCorridor(int genDepth, Random *random, BoundingBox *corridorBox, int direction); - - static BoundingBox *findPieceBox(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; - - /** - * * */ public: - class StairsDown : public StrongholdPiece - { - private: - static const int width = 5; - static const int height = 11; - static const int depth = 5; - - const bool isSource; - const SmallDoorType entryDoor; + class FillerCorridor : public StrongholdPiece { + private: + const int steps; - public: - StairsDown(int genDepth, Random *random, int west, int north); - StairsDown(int genDepth, Random *random, BoundingBox *stairsBox, int direction); + public: + FillerCorridor(int genDepth, Random* random, BoundingBox* corridorBox, + int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static StairsDown *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + static BoundingBox* findPieceBox(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; + + /** + * + * + */ +public: + class StairsDown : public StrongholdPiece { + private: + static const int width = 5; + static const int height = 11; + static const int depth = 5; + + const bool isSource; + const SmallDoorType entryDoor; + + public: + StairsDown(int genDepth, Random* random, int west, int north); + StairsDown(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static StairsDown* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; public: - class PortalRoom; + class PortalRoom; - class StartPiece : public StairsDown - { - public: - bool isLibraryAdded; - PieceWeight *previousPiece; - PortalRoom *portalRoomPiece; - Level *m_level; // 4J added + class StartPiece : public StairsDown { + public: + bool isLibraryAdded; + PieceWeight* previousPiece; + PortalRoom* portalRoomPiece; + Level* m_level; // 4J added // this queue is used so that the addChildren calls are // called in a random order - std::vector pendingChildren; + std::vector pendingChildren; - StartPiece(int genDepth, Random *random, int west, int north, Level *level); // 4J Added level param - virtual TilePos *getLocatorPosition(); + StartPiece(int genDepth, Random* random, int west, int north, + Level* level); // 4J Added level param + virtual TilePos* getLocatorPosition(); }; /** - * + * * */ public: - class Straight : public StrongholdPiece - { - private: - static const int width = 5; - static const int height = 5; - static const int depth = 7; + class Straight : public StrongholdPiece { + private: + static const int width = 5; + static const int height = 5; + static const int depth = 7; - const SmallDoorType entryDoor; - const bool leftChild; - const bool rightChild; - - public: - Straight(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static Straight *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + const SmallDoorType entryDoor; + const bool leftChild; + const bool rightChild; + public: + Straight(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static Straight* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; - /** - * + /** + * * */ - class ChestCorridor : public StrongholdPiece - { - private: - static const int width = 5; + class ChestCorridor : public StrongholdPiece { + private: + static const int width = 5; static const int height = 5; static const int depth = 7; - static const int TREASURE_ITEMS_COUNT = 14; - static WeighedTreasure *treasureItems[TREASURE_ITEMS_COUNT]; + static const int TREASURE_ITEMS_COUNT = 14; + static WeighedTreasure* treasureItems[TREASURE_ITEMS_COUNT]; const SmallDoorType entryDoor; boolean hasPlacedChest; - public: - ChestCorridor(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static ChestCorridor *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + ChestCorridor(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static ChestCorridor* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class StraightStairsDown : public StrongholdPiece - { - private: - static const int width = 5; - static const int height = 11; - static const int depth = 8; + class StraightStairsDown : public StrongholdPiece { + private: + static const int width = 5; + static const int height = 11; + static const int depth = 8; - const SmallDoorType entryDoor; + const SmallDoorType entryDoor; - public: - StraightStairsDown(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static StraightStairsDown *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + StraightStairsDown(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static StraightStairsDown* createPiece( + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class LeftTurn : public StrongholdPiece - { + class LeftTurn : public StrongholdPiece { + protected: + static const int width = 5; + static const int height = 5; + static const int depth = 5; - protected: - static const int width = 5; - static const int height = 5; - static const int depth = 5; + const SmallDoorType entryDoor; - const SmallDoorType entryDoor; - - public: - LeftTurn(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static LeftTurn *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + LeftTurn(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static LeftTurn* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class RightTurn : public LeftTurn - { - public: - RightTurn(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; + class RightTurn : public LeftTurn { + public: + RightTurn(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; /** - * + * * */ public: - class RoomCrossing : public StrongholdPiece - { - private: - static const int SMALL_TREASURE_ITEMS_COUNT = 7; // 4J added - static WeighedTreasure *smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT]; + class RoomCrossing : public StrongholdPiece { + private: + static const int SMALL_TREASURE_ITEMS_COUNT = 7; // 4J added + static WeighedTreasure* smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT]; - protected: - static const int width = 11; - static const int height = 7; - static const int depth = 11; + protected: + static const int width = 11; + static const int height = 7; + static const int depth = 11; - protected: - const SmallDoorType entryDoor; + protected: + const SmallDoorType entryDoor; const int type; - public: - RoomCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static RoomCrossing *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + + public: + RoomCrossing(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static RoomCrossing* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class PrisonHall : public StrongholdPiece - { - protected: - static const int width = 9; - static const int height = 5; - static const int depth = 11; + class PrisonHall : public StrongholdPiece { + protected: + static const int width = 9; + static const int height = 5; + static const int depth = 11; const SmallDoorType entryDoor; - public: - PrisonHall(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static PrisonHall *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + PrisonHall(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static PrisonHall* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class Library : public StrongholdPiece - { - private: - static const int LIBRARY_TREASURE_ITEMS_COUNT = 4; // 4J added - static WeighedTreasure *libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT]; + class Library : public StrongholdPiece { + private: + static const int LIBRARY_TREASURE_ITEMS_COUNT = 4; // 4J added + static WeighedTreasure* + libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT]; - protected: - static const int width = 14; - static const int height = 6; - static const int tallHeight = 11; - static const int depth = 15; + protected: + static const int width = 14; + static const int height = 6; + static const int tallHeight = 11; + static const int depth = 15; const SmallDoorType entryDoor; - private: - const bool isTall; - public: - Library(int genDepth, Random *random, BoundingBox *roomBox, int direction); - static Library *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + private: + const bool isTall; + public: + Library(int genDepth, Random* random, BoundingBox* roomBox, + int direction); + static Library* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class FiveCrossing : public StrongholdPiece - { - protected: - static const int width = 10; + class FiveCrossing : public StrongholdPiece { + protected: + static const int width = 10; static const int height = 9; static const int depth = 11; const SmallDoorType entryDoor; - private: - bool leftLow, leftHigh, rightLow, rightHigh; + private: + bool leftLow, leftHigh, rightLow, rightHigh; - public: - FiveCrossing(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static FiveCrossing *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + FiveCrossing(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static FiveCrossing* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ - class PortalRoom : public StrongholdPiece - { - protected: - static const int width = 11; + class PortalRoom : public StrongholdPiece { + protected: + static const int width = 11; static const int height = 8; static const int depth = 16; - private: - bool hasPlacedMobSpawner; + private: + bool hasPlacedMobSpawner; - public: - PortalRoom(int genDepth, Random *random, BoundingBox *stairsBox, int direction); - void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static PortalRoom *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + PortalRoom(int genDepth, Random* random, BoundingBox* stairsBox, + int direction); + void addChildren(StructurePiece* startPiece, + std::list* pieces, Random* random); + static PortalRoom* createPiece(std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + bool postProcess(Level* level, Random* random, BoundingBox* chunkBB); }; private: - - class SmoothStoneSelector : public StructurePiece::BlockSelector - { - public: - virtual void next(Random *random, int worldX, int worldY, int worldZ, bool isEdge); + class SmoothStoneSelector : public StructurePiece::BlockSelector { + public: + virtual void next(Random* random, int worldX, int worldY, int worldZ, + bool isEdge); }; - static const SmoothStoneSelector *smoothStoneSelector; + static const SmoothStoneSelector* smoothStoneSelector; }; diff --git a/Minecraft.World/WorldGen/Structures/StructurePiece.cpp b/Minecraft.World/WorldGen/Structures/StructurePiece.cpp index eb1b4e7c6..b1de56e2b 100644 --- a/Minecraft.World/WorldGen/Structures/StructurePiece.cpp +++ b/Minecraft.World/WorldGen/Structures/StructurePiece.cpp @@ -13,810 +13,662 @@ #include "../../Items/DoorItem.h" /** -* -* A structure piece is a construction or room, located somewhere in the world -* with a given orientatino (out of Direction.java). Structure pieces have a -* bounding box that says where the piece is located and its bounds, and the -* orientation is used to translate local coordinates into world coordinates. -*

-* The default orientation is Direction.UNDEFINED, in which case no translation -* will occur. If the orientation is Direction::NORTH, coordinate (0, 0, 0) will -* be at (boundingBox.x0, boundingBox.y0, boundingBox.z1). In other words, (1, -* 1, 1) will be translated to (boundingBox.x0 + 1, boundingBox.y0 + 1, -* boundingBox.z1 - 1). -*

-* When using Direction::SOUTH, the x coordinate will be the same, and the z -* coordinate will be flipped. In other words, the bounding box is NOT rotated! -* It is only flipped along the z axis. Also note that the bounding box is in -* world coordinates, so the local drawing must never reach outside of this. -*

-* When using east and west coordinates, the local z coordinate will be swapped -* with the local x coordinate. For example, (0, 0, 0) is (boundingBox.z1, -* boundingBox.y0, boundingBox.z0), and (1, 1, 1) becomes (boundingBox.x1 - 1, -* boundingBox.y0 + 1, boundingBox.z0 + 1) when using Direction::WEST. -*

-* When-ever a structure piece is placing blocks, it is VERY IMPORTANT to always -* make sure that all getTile and setTile calls are within the chunk's bounding -* box. Failing to check this will cause the level generator to create new -* chunks, leading to infinite loops and other errors. -*/ + * + * A structure piece is a construction or room, located somewhere in the world + * with a given orientatino (out of Direction.java). Structure pieces have a + * bounding box that says where the piece is located and its bounds, and the + * orientation is used to translate local coordinates into world coordinates. + *

+ * The default orientation is Direction.UNDEFINED, in which case no translation + * will occur. If the orientation is Direction::NORTH, coordinate (0, 0, 0) will + * be at (boundingBox.x0, boundingBox.y0, boundingBox.z1). In other words, (1, + * 1, 1) will be translated to (boundingBox.x0 + 1, boundingBox.y0 + 1, + * boundingBox.z1 - 1). + *

+ * When using Direction::SOUTH, the x coordinate will be the same, and the z + * coordinate will be flipped. In other words, the bounding box is NOT rotated! + * It is only flipped along the z axis. Also note that the bounding box is in + * world coordinates, so the local drawing must never reach outside of this. + *

+ * When using east and west coordinates, the local z coordinate will be swapped + * with the local x coordinate. For example, (0, 0, 0) is (boundingBox.z1, + * boundingBox.y0, boundingBox.z0), and (1, 1, 1) becomes (boundingBox.x1 - 1, + * boundingBox.y0 + 1, boundingBox.z0 + 1) when using Direction::WEST. + *

+ * When-ever a structure piece is placing blocks, it is VERY IMPORTANT to always + * make sure that all getTile and setTile calls are within the chunk's bounding + * box. Failing to check this will cause the level generator to create new + * chunks, leading to infinite loops and other errors. + */ -StructurePiece::StructurePiece( int genDepth ) -{ - boundingBox = NULL; - this->genDepth = genDepth; - orientation = Direction::UNDEFINED; +StructurePiece::StructurePiece(int genDepth) { + boundingBox = NULL; + this->genDepth = genDepth; + orientation = Direction::UNDEFINED; } -StructurePiece::~StructurePiece() -{ - if(boundingBox != NULL) delete boundingBox; +StructurePiece::~StructurePiece() { + if (boundingBox != NULL) delete boundingBox; } -void StructurePiece::addChildren( StructurePiece* startPiece, std::list< StructurePiece* > *pieces, Random* random ) -{ +void StructurePiece::addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random) {} + +BoundingBox* StructurePiece::getBoundingBox() { return boundingBox; } + +int StructurePiece::getGenDepth() { return genDepth; } + +bool StructurePiece::isInChunk(ChunkPos* pos) { + int cx = (pos->x << 4); + int cz = (pos->z << 4); + + return boundingBox->intersects(cx, cz, cx + 15, cz + 15); } -BoundingBox* StructurePiece::getBoundingBox() -{ - return boundingBox; -} - -int StructurePiece::getGenDepth() -{ - return genDepth; -} - -bool StructurePiece::isInChunk( ChunkPos* pos ) -{ - int cx = ( pos->x << 4 ); - int cz = ( pos->z << 4 ); - - return boundingBox->intersects( cx, cz, cx + 15, cz + 15 ); -} - -StructurePiece* StructurePiece::findCollisionPiece( std::list< StructurePiece* > *pieces, BoundingBox* box ) -{ - for ( AUTO_VAR(it, pieces->begin()); it != pieces->end(); it++ ) - { - StructurePiece* piece = *it; - if ( piece->getBoundingBox() != NULL && piece->getBoundingBox()->intersects( box ) ) - { - return piece; - } - } - return NULL; +StructurePiece* StructurePiece::findCollisionPiece( + std::list* pieces, BoundingBox* box) { + for (AUTO_VAR(it, pieces->begin()); it != pieces->end(); it++) { + StructurePiece* piece = *it; + if (piece->getBoundingBox() != NULL && + piece->getBoundingBox()->intersects(box)) { + return piece; + } + } + return NULL; } // 4J-PB - Added from 1.2.3 -TilePos *StructurePiece::getLocatorPosition() -{ - return new TilePos(boundingBox->getXCenter(), boundingBox->getYCenter(), boundingBox->getZCenter()); +TilePos* StructurePiece::getLocatorPosition() { + return new TilePos(boundingBox->getXCenter(), boundingBox->getYCenter(), + boundingBox->getZCenter()); } -bool StructurePiece::edgesLiquid( Level* level, BoundingBox* chunkBB ) -{ - int x0 = Math::_max( boundingBox->x0 - 1, chunkBB->x0 ); - int y0 = Math::_max( boundingBox->y0 - 1, chunkBB->y0 ); - int z0 = Math::_max( boundingBox->z0 - 1, chunkBB->z0 ); - int x1 = Math::_min( boundingBox->x1 + 1, chunkBB->x1 ); - int y1 = Math::_min( boundingBox->y1 + 1, chunkBB->y1 ); - int z1 = Math::_min( boundingBox->z1 + 1, chunkBB->z1 ); - - // roof and floor - for ( int x = x0; x <= x1; x++ ) - { - for ( int z = z0; z <= z1; z++ ) - { - int tile = level->getTile( x, y0, z ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - tile = level->getTile( x, y1, z ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - } - } - // north and south - for ( int x = x0; x <= x1; x++ ) - { - for ( int y = y0; y <= y1; y++ ) - { - int tile = level->getTile( x, y, z0 ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - tile = level->getTile( x, y, z1 ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - } - } - // east and west - for ( int z = z0; z <= z1; z++ ) - { - for ( int y = y0; y <= y1; y++ ) - { - int tile = level->getTile( x0, y, z ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - tile = level->getTile( x1, y, z ); - if ( tile > 0 && Tile::tiles[tile]->material->isLiquid() ) - { - return true; - } - } - } - return false; +bool StructurePiece::edgesLiquid(Level* level, BoundingBox* chunkBB) { + int x0 = Math::_max(boundingBox->x0 - 1, chunkBB->x0); + int y0 = Math::_max(boundingBox->y0 - 1, chunkBB->y0); + int z0 = Math::_max(boundingBox->z0 - 1, chunkBB->z0); + int x1 = Math::_min(boundingBox->x1 + 1, chunkBB->x1); + int y1 = Math::_min(boundingBox->y1 + 1, chunkBB->y1); + int z1 = Math::_min(boundingBox->z1 + 1, chunkBB->z1); + // roof and floor + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + int tile = level->getTile(x, y0, z); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + tile = level->getTile(x, y1, z); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + } + } + // north and south + for (int x = x0; x <= x1; x++) { + for (int y = y0; y <= y1; y++) { + int tile = level->getTile(x, y, z0); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + tile = level->getTile(x, y, z1); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + } + } + // east and west + for (int z = z0; z <= z1; z++) { + for (int y = y0; y <= y1; y++) { + int tile = level->getTile(x0, y, z); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + tile = level->getTile(x1, y, z); + if (tile > 0 && Tile::tiles[tile]->material->isLiquid()) { + return true; + } + } + } + return false; } -int StructurePiece::getWorldX( int x, int z ) -{ - switch ( orientation ) - { - case Direction::NORTH: - case Direction::SOUTH: - return boundingBox->x0 + x; - case Direction::WEST: - return boundingBox->x1 - z; - case Direction::EAST: - return boundingBox->x0 + z; - default: - return x; - } +int StructurePiece::getWorldX(int x, int z) { + switch (orientation) { + case Direction::NORTH: + case Direction::SOUTH: + return boundingBox->x0 + x; + case Direction::WEST: + return boundingBox->x1 - z; + case Direction::EAST: + return boundingBox->x0 + z; + default: + return x; + } } -int StructurePiece::getWorldY( int y ) -{ - if ( orientation == Direction::UNDEFINED ) - { - return y; - } - return y + boundingBox->y0; +int StructurePiece::getWorldY(int y) { + if (orientation == Direction::UNDEFINED) { + return y; + } + return y + boundingBox->y0; } -int StructurePiece::getWorldZ( int x, int z ) -{ - switch ( orientation ) - { - case Direction::NORTH: - return boundingBox->z1 - z; - case Direction::SOUTH: - return boundingBox->z0 + z; - case Direction::WEST: - case Direction::EAST: - return boundingBox->z0 + x; - default: - return z; - } +int StructurePiece::getWorldZ(int x, int z) { + switch (orientation) { + case Direction::NORTH: + return boundingBox->z1 - z; + case Direction::SOUTH: + return boundingBox->z0 + z; + case Direction::WEST: + case Direction::EAST: + return boundingBox->z0 + x; + default: + return z; + } } -int StructurePiece::getOrientationData( int tile, int data ) -{ - if ( tile == Tile::rail->id ) - { - if ( orientation == Direction::WEST || orientation == Direction::EAST ) - { - if ( data == RailTile::DIR_FLAT_X ) - { - return RailTile::DIR_FLAT_Z; - } - else - { - return RailTile::DIR_FLAT_X; - } - } - } - else if ( tile == Tile::door_wood_Id || tile == Tile::door_iron_Id ) - { - if ( orientation == Direction::SOUTH ) - { - if ( data == 0 ) - { - return 2; - } - if ( data == 2 ) - { - return 0; - } - } - else if ( orientation == Direction::WEST ) - { - // 0 = 1 - // 1 = 2 - // 2 = 3 - // 3 = 0 - return ( data + 1 ) & 3; - } - else if ( orientation == Direction::EAST ) - { - // 0 = 3 - // 1 = 0 - // 2 = 1 - // 3 = 2 - return ( data + 3 ) & 3; - } - } - else if ( tile == Tile::stairs_stone_Id || tile == Tile::stairs_wood_Id || tile == Tile::stairs_netherBricks_Id || tile == Tile::stairs_stoneBrickSmooth_Id || tile == Tile::stairs_sandstone_Id) - { - if ( orientation == Direction::SOUTH ) - { - if ( data == 2 ) - { - return 3; - } - if ( data == 3 ) - { - return 2; - } - } - else if ( orientation == Direction::WEST ) - { - if ( data == 0 ) - { - return 2; - } - if ( data == 1 ) - { - return 3; - } - if ( data == 2 ) - { - return 0; - } - if ( data == 3 ) - { - return 1; - } - } - else if ( orientation == Direction::EAST ) - { - if ( data == 0 ) - { - return 2; - } - if ( data == 1 ) - { - return 3; - } - if ( data == 2 ) - { - return 1; - } - if ( data == 3 ) - { - return 0; - } - } - } - else if ( tile == Tile::ladder->id ) - { - if ( orientation == Direction::SOUTH ) - { - if ( data == Facing::NORTH ) - { - return Facing::SOUTH; - } - if ( data == Facing::SOUTH ) - { - return Facing::NORTH; - } - } - else if ( orientation == Direction::WEST ) - { - if ( data == Facing::NORTH ) - { - return Facing::WEST; - } - if ( data == Facing::SOUTH ) - { - return Facing::EAST; - } - if ( data == Facing::WEST ) - { - return Facing::NORTH; - } - if ( data == Facing::EAST ) - { - return Facing::SOUTH; - } - } - else if ( orientation == Direction::EAST ) - { - if ( data == Facing::NORTH ) - { - return Facing::EAST; - } - if ( data == Facing::SOUTH ) - { - return Facing::WEST; - } - if ( data == Facing::WEST ) - { - return Facing::NORTH; - } - if ( data == Facing::EAST ) - { - return Facing::SOUTH; - } - } - - } - else if ( tile == Tile::button->id ) - { - if ( orientation == Direction::SOUTH ) - { - if ( data == 3 ) - { - return 4; - } - if ( data == 4 ) - { - return 3; - } - } - else if ( orientation == Direction::WEST ) - { - if ( data == 3 ) - { - return 1; - } - if ( data == 4 ) - { - return 2; - } - if ( data == 2 ) - { - return 3; - } - if ( data == 1 ) - { - return 4; - } - } - else if ( orientation == Direction::EAST ) - { - if ( data == 3 ) - { - return 2; - } - if ( data == 4 ) - { - return 1; - } - if ( data == 2 ) - { - return 3; - } - if ( data == 1 ) - { - return 4; - } - } - } - else if (tile == Tile::tripWireSource_Id || (Tile::tiles[tile] != NULL && dynamic_cast(Tile::tiles[tile]))) - { - if (orientation == Direction::SOUTH) - { - if (data == Direction::SOUTH || data == Direction::NORTH) - { - return Direction::DIRECTION_OPPOSITE[data]; - } - } - else if (orientation == Direction::WEST) - { - if (data == Direction::NORTH) - { - return Direction::WEST; - } - if (data == Direction::SOUTH) - { - return Direction::EAST; - } - if (data == Direction::WEST) - { - return Direction::NORTH; - } - if (data == Direction::EAST) - { - return Direction::SOUTH; - } - } - else if (orientation == Direction::EAST) - { - if (data == Direction::NORTH) - { - return Direction::EAST; - } - if (data == Direction::SOUTH) - { - return Direction::WEST; - } - if (data == Direction::WEST) - { - return Direction::NORTH; - } - if (data == Direction::EAST) - { - return Direction::SOUTH; - } - } - } - else if (tile == Tile::pistonBase_Id || tile == Tile::pistonStickyBase_Id || tile == Tile::lever_Id || tile == Tile::dispenser_Id) - { - if (orientation == Direction::SOUTH) - { - if (data == Facing::NORTH || data == Facing::SOUTH) - { - return Facing::OPPOSITE_FACING[data]; - } - } - else if (orientation == Direction::WEST) - { - if (data == Facing::NORTH) - { - return Facing::WEST; - } - if (data == Facing::SOUTH) - { - return Facing::EAST; - } - if (data == Facing::WEST) - { - return Facing::NORTH; - } - if (data == Facing::EAST) - { - return Facing::SOUTH; - } - } else if (orientation == Direction::EAST) - { - if (data == Facing::NORTH) - { - return Facing::EAST; - } - if (data == Facing::SOUTH) - { - return Facing::WEST; - } - if (data == Facing::WEST) - { - return Facing::NORTH; - } - if (data == Facing::EAST) - { - return Facing::SOUTH; - } - } - } - return data; +int StructurePiece::getOrientationData(int tile, int data) { + if (tile == Tile::rail->id) { + if (orientation == Direction::WEST || orientation == Direction::EAST) { + if (data == RailTile::DIR_FLAT_X) { + return RailTile::DIR_FLAT_Z; + } else { + return RailTile::DIR_FLAT_X; + } + } + } else if (tile == Tile::door_wood_Id || tile == Tile::door_iron_Id) { + if (orientation == Direction::SOUTH) { + if (data == 0) { + return 2; + } + if (data == 2) { + return 0; + } + } else if (orientation == Direction::WEST) { + // 0 = 1 + // 1 = 2 + // 2 = 3 + // 3 = 0 + return (data + 1) & 3; + } else if (orientation == Direction::EAST) { + // 0 = 3 + // 1 = 0 + // 2 = 1 + // 3 = 2 + return (data + 3) & 3; + } + } else if (tile == Tile::stairs_stone_Id || tile == Tile::stairs_wood_Id || + tile == Tile::stairs_netherBricks_Id || + tile == Tile::stairs_stoneBrickSmooth_Id || + tile == Tile::stairs_sandstone_Id) { + if (orientation == Direction::SOUTH) { + if (data == 2) { + return 3; + } + if (data == 3) { + return 2; + } + } else if (orientation == Direction::WEST) { + if (data == 0) { + return 2; + } + if (data == 1) { + return 3; + } + if (data == 2) { + return 0; + } + if (data == 3) { + return 1; + } + } else if (orientation == Direction::EAST) { + if (data == 0) { + return 2; + } + if (data == 1) { + return 3; + } + if (data == 2) { + return 1; + } + if (data == 3) { + return 0; + } + } + } else if (tile == Tile::ladder->id) { + if (orientation == Direction::SOUTH) { + if (data == Facing::NORTH) { + return Facing::SOUTH; + } + if (data == Facing::SOUTH) { + return Facing::NORTH; + } + } else if (orientation == Direction::WEST) { + if (data == Facing::NORTH) { + return Facing::WEST; + } + if (data == Facing::SOUTH) { + return Facing::EAST; + } + if (data == Facing::WEST) { + return Facing::NORTH; + } + if (data == Facing::EAST) { + return Facing::SOUTH; + } + } else if (orientation == Direction::EAST) { + if (data == Facing::NORTH) { + return Facing::EAST; + } + if (data == Facing::SOUTH) { + return Facing::WEST; + } + if (data == Facing::WEST) { + return Facing::NORTH; + } + if (data == Facing::EAST) { + return Facing::SOUTH; + } + } + } else if (tile == Tile::button->id) { + if (orientation == Direction::SOUTH) { + if (data == 3) { + return 4; + } + if (data == 4) { + return 3; + } + } else if (orientation == Direction::WEST) { + if (data == 3) { + return 1; + } + if (data == 4) { + return 2; + } + if (data == 2) { + return 3; + } + if (data == 1) { + return 4; + } + } else if (orientation == Direction::EAST) { + if (data == 3) { + return 2; + } + if (data == 4) { + return 1; + } + if (data == 2) { + return 3; + } + if (data == 1) { + return 4; + } + } + } else if (tile == Tile::tripWireSource_Id || + (Tile::tiles[tile] != NULL && + dynamic_cast(Tile::tiles[tile]))) { + if (orientation == Direction::SOUTH) { + if (data == Direction::SOUTH || data == Direction::NORTH) { + return Direction::DIRECTION_OPPOSITE[data]; + } + } else if (orientation == Direction::WEST) { + if (data == Direction::NORTH) { + return Direction::WEST; + } + if (data == Direction::SOUTH) { + return Direction::EAST; + } + if (data == Direction::WEST) { + return Direction::NORTH; + } + if (data == Direction::EAST) { + return Direction::SOUTH; + } + } else if (orientation == Direction::EAST) { + if (data == Direction::NORTH) { + return Direction::EAST; + } + if (data == Direction::SOUTH) { + return Direction::WEST; + } + if (data == Direction::WEST) { + return Direction::NORTH; + } + if (data == Direction::EAST) { + return Direction::SOUTH; + } + } + } else if (tile == Tile::pistonBase_Id || + tile == Tile::pistonStickyBase_Id || tile == Tile::lever_Id || + tile == Tile::dispenser_Id) { + if (orientation == Direction::SOUTH) { + if (data == Facing::NORTH || data == Facing::SOUTH) { + return Facing::OPPOSITE_FACING[data]; + } + } else if (orientation == Direction::WEST) { + if (data == Facing::NORTH) { + return Facing::WEST; + } + if (data == Facing::SOUTH) { + return Facing::EAST; + } + if (data == Facing::WEST) { + return Facing::NORTH; + } + if (data == Facing::EAST) { + return Facing::SOUTH; + } + } else if (orientation == Direction::EAST) { + if (data == Facing::NORTH) { + return Facing::EAST; + } + if (data == Facing::SOUTH) { + return Facing::WEST; + } + if (data == Facing::WEST) { + return Facing::NORTH; + } + if (data == Facing::EAST) { + return Facing::SOUTH; + } + } + } + return data; } -void StructurePiece::placeBlock( Level* level, int block, int data, int x, int y, int z, BoundingBox* chunkBB ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( y ); - int worldZ = getWorldZ( x, z ); +void StructurePiece::placeBlock(Level* level, int block, int data, int x, int y, + int z, BoundingBox* chunkBB) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); - if ( !chunkBB->isInside( worldX, worldY, worldZ ) ) - { - return; - } + if (!chunkBB->isInside(worldX, worldY, worldZ)) { + return; + } - // 4J Stu - We shouldn't be removing bedrock when generating things (eg in SuperFlat) - if(worldY == 0) return; + // 4J Stu - We shouldn't be removing bedrock when generating things (eg in + // SuperFlat) + if (worldY == 0) return; - level->setTileAndDataNoUpdate( worldX, worldY, worldZ, block, data ); + level->setTileAndDataNoUpdate(worldX, worldY, worldZ, block, data); } - /** -* The purpose of this method is to wrap the getTile call on Level, in order -* to prevent the level from generating chunks that shouldn't be loaded yet. -* Returns 0 if the call is out of bounds. -* -* @param level -* @param x -* @param y -* @param z -* @param chunkPosition -* @return -*/ -int StructurePiece::getBlock( Level* level, int x, int y, int z, BoundingBox* chunkBB ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( y ); - int worldZ = getWorldZ( x, z ); + * The purpose of this method is to wrap the getTile call on Level, in order + * to prevent the level from generating chunks that shouldn't be loaded yet. + * Returns 0 if the call is out of bounds. + * + * @param level + * @param x + * @param y + * @param z + * @param chunkPosition + * @return + */ +int StructurePiece::getBlock(Level* level, int x, int y, int z, + BoundingBox* chunkBB) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); - if ( !chunkBB->isInside( worldX, worldY, worldZ ) ) - { - return 0; - } + if (!chunkBB->isInside(worldX, worldY, worldZ)) { + return 0; + } - return level->getTile( worldX, worldY, worldZ ); + return level->getTile(worldX, worldY, worldZ); } -void StructurePiece::generateAirBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1) -{ - for (int y = y0; y <= y1; y++) - { - for (int x = x0; x <= x1; x++) - { - for (int z = z0; z <= z1; z++) - { - placeBlock(level, 0, 0, x, y, z, chunkBB); - } - } - } +void StructurePiece::generateAirBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1) { + for (int y = y0; y <= y1; y++) { + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + placeBlock(level, 0, 0, x, y, z, chunkBB); + } + } + } } -void StructurePiece::generateBox( Level* level, BoundingBox* chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, - int edgeTile, int fillTile, bool skipAir ) -{ - for ( int y = y0; y <= y1; y++ ) - { - for ( int x = x0; x <= x1; x++ ) - { - for ( int z = z0; z <= z1; z++ ) - { - - if ( skipAir && getBlock( level, x, y, z, chunkBB ) == 0 ) - { - continue; - } - if ( y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1 ) - { - placeBlock( level, edgeTile, 0, x, y, z, chunkBB ); - } - else - { - placeBlock( level, fillTile, 0, x, y, z, chunkBB ); - } - - } - } - } +void StructurePiece::generateBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1, + int edgeTile, int fillTile, bool skipAir) { + for (int y = y0; y <= y1; y++) { + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) { + continue; + } + if (y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || + z == z1) { + placeBlock(level, edgeTile, 0, x, y, z, chunkBB); + } else { + placeBlock(level, fillTile, 0, x, y, z, chunkBB); + } + } + } + } } -void StructurePiece::generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int edgeData, int fillTile, int fillData, bool skipAir) -{ - for (int y = y0; y <= y1; y++) - { - for (int x = x0; x <= x1; x++) - { - for (int z = z0; z <= z1; z++) - { - - if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) - { - continue; - } - if (y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1) - { - placeBlock(level, edgeTile, edgeData, x, y, z, chunkBB); - } - else - { - placeBlock(level, fillTile, fillData, x, y, z, chunkBB); - } - - } - } - } +void StructurePiece::generateBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1, + int edgeTile, int edgeData, int fillTile, + int fillData, bool skipAir) { + for (int y = y0; y <= y1; y++) { + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) { + continue; + } + if (y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || + z == z1) { + placeBlock(level, edgeTile, edgeData, x, y, z, chunkBB); + } else { + placeBlock(level, fillTile, fillData, x, y, z, chunkBB); + } + } + } + } } -void StructurePiece::generateBox( Level* level, BoundingBox* chunkBB, BoundingBox* boxBB, int edgeTile, int fillTile, - bool skipAir ) -{ - generateBox( level, chunkBB, boxBB->x0, boxBB->y0, boxBB->z0, boxBB->x1, boxBB->y1, boxBB->z1, edgeTile, fillTile, - skipAir ); +void StructurePiece::generateBox(Level* level, BoundingBox* chunkBB, + BoundingBox* boxBB, int edgeTile, int fillTile, + bool skipAir) { + generateBox(level, chunkBB, boxBB->x0, boxBB->y0, boxBB->z0, boxBB->x1, + boxBB->y1, boxBB->z1, edgeTile, fillTile, skipAir); } -void StructurePiece::generateBox( Level* level, BoundingBox* chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, - bool skipAir, Random* random, StructurePiece::BlockSelector* selector ) -{ - for ( int y = y0; y <= y1; y++ ) - { - for ( int x = x0; x <= x1; x++ ) - { - for ( int z = z0; z <= z1; z++ ) - { - - if ( skipAir && getBlock( level, x, y, z, chunkBB ) == 0 ) - { - continue; - } - selector->next( random, x, y, z, y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1 ); - placeBlock( level, selector->getNextId(), selector->getNextData(), x, y, z, chunkBB ); - - } - } - } +void StructurePiece::generateBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1, + bool skipAir, Random* random, + StructurePiece::BlockSelector* selector) { + for (int y = y0; y <= y1; y++) { + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) { + continue; + } + selector->next(random, x, y, z, + y == y0 || y == y1 || x == x0 || x == x1 || + z == z0 || z == z1); + placeBlock(level, selector->getNextId(), + selector->getNextData(), x, y, z, chunkBB); + } + } + } } -void StructurePiece::generateBox( Level* level, BoundingBox* chunkBB, BoundingBox* boxBB, bool skipAir, Random* random, - StructurePiece::BlockSelector* selector ) -{ - generateBox( level, chunkBB, boxBB->x0, boxBB->y0, boxBB->z0, boxBB->x1, boxBB->y1, boxBB->z1, skipAir, random, - selector ); +void StructurePiece::generateBox(Level* level, BoundingBox* chunkBB, + BoundingBox* boxBB, bool skipAir, + Random* random, + StructurePiece::BlockSelector* selector) { + generateBox(level, chunkBB, boxBB->x0, boxBB->y0, boxBB->z0, boxBB->x1, + boxBB->y1, boxBB->z1, skipAir, random, selector); } -void StructurePiece::generateMaybeBox( Level* level, BoundingBox* chunkBB, Random *random, float probability, int x0, - int y0, int z0, int x1, int y1, int z1, int edgeTile, int fillTile, - bool skipAir ) -{ - for ( int y = y0; y <= y1; y++ ) - { - for ( int x = x0; x <= x1; x++ ) - { - for ( int z = z0; z <= z1; z++ ) - { - - if ( random->nextFloat() > probability ) - { - continue; - } - if ( skipAir && getBlock( level, x, y, z, chunkBB ) == 0 ) - { - continue; - } - if ( y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || z == z1 ) - { - placeBlock( level, edgeTile, 0, x, y, z, chunkBB ); - } - else - { - placeBlock( level, fillTile, 0, x, y, z, chunkBB ); - } - - } - } - } +void StructurePiece::generateMaybeBox(Level* level, BoundingBox* chunkBB, + Random* random, float probability, int x0, + int y0, int z0, int x1, int y1, int z1, + int edgeTile, int fillTile, + bool skipAir) { + for (int y = y0; y <= y1; y++) { + for (int x = x0; x <= x1; x++) { + for (int z = z0; z <= z1; z++) { + if (random->nextFloat() > probability) { + continue; + } + if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) { + continue; + } + if (y == y0 || y == y1 || x == x0 || x == x1 || z == z0 || + z == z1) { + placeBlock(level, edgeTile, 0, x, y, z, chunkBB); + } else { + placeBlock(level, fillTile, 0, x, y, z, chunkBB); + } + } + } + } } -void StructurePiece::maybeGenerateBlock( Level* level, BoundingBox* chunkBB, Random *random, float probability, int x, - int y, int z, int tile, int data ) -{ - if ( random->nextFloat() < probability ) - { - placeBlock( level, tile, data, x, y, z, chunkBB ); - } +void StructurePiece::maybeGenerateBlock(Level* level, BoundingBox* chunkBB, + Random* random, float probability, + int x, int y, int z, int tile, + int data) { + if (random->nextFloat() < probability) { + placeBlock(level, tile, data, x, y, z, chunkBB); + } } -void StructurePiece::generateUpperHalfSphere( Level* level, BoundingBox* chunkBB, int x0, int y0, int z0, int x1, - int y1, int z1, int fillTile, bool skipAir ) -{ - float diagX = (float)( x1 - x0 + 1 ); - float diagY = (float)( y1 - y0 + 1 ); - float diagZ = (float)( z1 - z0 + 1 ); - float cx = x0 + diagX / 2; - float cz = z0 + diagZ / 2; +void StructurePiece::generateUpperHalfSphere(Level* level, BoundingBox* chunkBB, + int x0, int y0, int z0, int x1, + int y1, int z1, int fillTile, + bool skipAir) { + float diagX = (float)(x1 - x0 + 1); + float diagY = (float)(y1 - y0 + 1); + float diagZ = (float)(z1 - z0 + 1); + float cx = x0 + diagX / 2; + float cz = z0 + diagZ / 2; - for ( int y = y0; y <= y1; y++ ) - { - float normalizedYDistance = ( float )( y - y0 ) / diagY; + for (int y = y0; y <= y1; y++) { + float normalizedYDistance = (float)(y - y0) / diagY; - for ( int x = x0; x <= x1; x++ ) - { - float normalizedXDistance = ( float )( x - cx ) / ( diagX * 0.5f ); + for (int x = x0; x <= x1; x++) { + float normalizedXDistance = (float)(x - cx) / (diagX * 0.5f); - for ( int z = z0; z <= z1; z++ ) - { - float normalizedZDistance = ( float )( z - cz ) / ( diagZ * 0.5f ); + for (int z = z0; z <= z1; z++) { + float normalizedZDistance = (float)(z - cz) / (diagZ * 0.5f); - if ( skipAir && getBlock( level, x, y, z, chunkBB ) == 0 ) - { - continue; - } + if (skipAir && getBlock(level, x, y, z, chunkBB) == 0) { + continue; + } - float dist = ( normalizedXDistance * normalizedXDistance ) + ( normalizedYDistance * - normalizedYDistance ) + ( normalizedZDistance * normalizedZDistance ); - - if ( dist <= 1.05f ) - { - placeBlock( level, fillTile, 0, x, y, z, chunkBB ); - } - - } - } - } + float dist = (normalizedXDistance * normalizedXDistance) + + (normalizedYDistance * normalizedYDistance) + + (normalizedZDistance * normalizedZDistance); + if (dist <= 1.05f) { + placeBlock(level, fillTile, 0, x, y, z, chunkBB); + } + } + } + } } -void StructurePiece::generateAirColumnUp( Level* level, int x, int startY, int z, BoundingBox* chunkBB ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( startY ); - int worldZ = getWorldZ( x, z ); +void StructurePiece::generateAirColumnUp(Level* level, int x, int startY, int z, + BoundingBox* chunkBB) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(startY); + int worldZ = getWorldZ(x, z); - if ( !chunkBB->isInside( worldX, worldY, worldZ ) ) - { - return; - } + if (!chunkBB->isInside(worldX, worldY, worldZ)) { + return; + } - while ( !level->isEmptyTile( worldX, worldY, worldZ ) && worldY < Level::maxBuildHeight - 1 ) - { - level->setTileAndDataNoUpdate( worldX, worldY, worldZ, 0, 0 ); - worldY++; - } + while (!level->isEmptyTile(worldX, worldY, worldZ) && + worldY < Level::maxBuildHeight - 1) { + level->setTileAndDataNoUpdate(worldX, worldY, worldZ, 0, 0); + worldY++; + } } -void StructurePiece::fillColumnDown( Level* level, int tile, int tileData, int x, int startY, int z, - BoundingBox* chunkBB ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( startY ); - int worldZ = getWorldZ( x, z ); +void StructurePiece::fillColumnDown(Level* level, int tile, int tileData, int x, + int startY, int z, BoundingBox* chunkBB) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(startY); + int worldZ = getWorldZ(x, z); - if ( !chunkBB->isInside( worldX, worldY, worldZ ) ) - { - return; - } + if (!chunkBB->isInside(worldX, worldY, worldZ)) { + return; + } - while ( ( level->isEmptyTile( worldX, worldY, worldZ ) || level->getMaterial( worldX, worldY, worldZ )->isLiquid() ) && worldY > 1 ) - { - level->setTileAndDataNoUpdate( worldX, worldY, worldZ, tile, tileData ); - worldY--; - } + while ((level->isEmptyTile(worldX, worldY, worldZ) || + level->getMaterial(worldX, worldY, worldZ)->isLiquid()) && + worldY > 1) { + level->setTileAndDataNoUpdate(worldX, worldY, worldZ, tile, tileData); + worldY--; + } } -bool StructurePiece::createChest( Level* level, BoundingBox* chunkBB, Random* random, int x, int y, int z, - WeighedTreasureArray treasure, int numRolls ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( y ); - int worldZ = getWorldZ( x, z ); +bool StructurePiece::createChest(Level* level, BoundingBox* chunkBB, + Random* random, int x, int y, int z, + WeighedTreasureArray treasure, int numRolls) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); - if ( chunkBB->isInside( worldX, worldY, worldZ ) ) - { - if ( level->getTile( worldX, worldY, worldZ ) != Tile::chest->id ) - { - level->setTile( worldX, worldY, worldZ, Tile::chest->id ); - std::shared_ptr chest = std::dynamic_pointer_cast(level->getTileEntity( worldX, worldY, worldZ )); - if ( chest != NULL ) WeighedTreasure::addChestItems( random, treasure, chest, numRolls ); - return true; - } - } - return false; + if (chunkBB->isInside(worldX, worldY, worldZ)) { + if (level->getTile(worldX, worldY, worldZ) != Tile::chest->id) { + level->setTile(worldX, worldY, worldZ, Tile::chest->id); + std::shared_ptr chest = + std::dynamic_pointer_cast( + level->getTileEntity(worldX, worldY, worldZ)); + if (chest != NULL) + WeighedTreasure::addChestItems(random, treasure, chest, + numRolls); + return true; + } + } + return false; } -bool StructurePiece::createDispenser(Level *level, BoundingBox *chunkBB, Random *random, int x, int y, int z, int facing, WeighedTreasureArray items, int numRolls) -{ - int worldX = getWorldX(x, z); - int worldY = getWorldY(y); - int worldZ = getWorldZ(x, z); +bool StructurePiece::createDispenser(Level* level, BoundingBox* chunkBB, + Random* random, int x, int y, int z, + int facing, WeighedTreasureArray items, + int numRolls) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); - if (chunkBB->isInside(worldX, worldY, worldZ)) - { - if (level->getTile(worldX, worldY, worldZ) != Tile::dispenser_Id) - { - level->setTileAndData(worldX, worldY, worldZ, Tile::dispenser_Id, getOrientationData(Tile::dispenser_Id, facing)); - std::shared_ptr dispenser = std::dynamic_pointer_cast(level->getTileEntity(worldX, worldY, worldZ)); - if (dispenser != NULL) WeighedTreasure::addDispenserItems(random, items, dispenser, numRolls); - return true; - } - } - return false; + if (chunkBB->isInside(worldX, worldY, worldZ)) { + if (level->getTile(worldX, worldY, worldZ) != Tile::dispenser_Id) { + level->setTileAndData( + worldX, worldY, worldZ, Tile::dispenser_Id, + getOrientationData(Tile::dispenser_Id, facing)); + std::shared_ptr dispenser = + std::dynamic_pointer_cast( + level->getTileEntity(worldX, worldY, worldZ)); + if (dispenser != NULL) + WeighedTreasure::addDispenserItems(random, items, dispenser, + numRolls); + return true; + } + } + return false; } -void StructurePiece::createDoor( Level* level, BoundingBox* chunkBB, Random* random, int x, int y, int z, - int orientation ) -{ - int worldX = getWorldX( x, z ); - int worldY = getWorldY( y ); - int worldZ = getWorldZ( x, z ); +void StructurePiece::createDoor(Level* level, BoundingBox* chunkBB, + Random* random, int x, int y, int z, + int orientation) { + int worldX = getWorldX(x, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x, z); - if ( chunkBB->isInside( worldX, worldY, worldZ ) ) - { - DoorItem::place( level, worldX, worldY, worldZ, orientation, Tile::door_wood ); - } + if (chunkBB->isInside(worldX, worldY, worldZ)) { + DoorItem::place(level, worldX, worldY, worldZ, orientation, + Tile::door_wood); + } } diff --git a/Minecraft.World/WorldGen/Structures/StructurePiece.h b/Minecraft.World/WorldGen/Structures/StructurePiece.h index 94b49cc81..780035b52 100644 --- a/Minecraft.World/WorldGen/Structures/StructurePiece.h +++ b/Minecraft.World/WorldGen/Structures/StructurePiece.h @@ -10,7 +10,7 @@ class ChestTileEntity; class TilePos; /** - * + * * A structure piece is a construction or room, located somewhere in the world * with a given orientatino (out of Direction.java). Structure pieces have a * bounding box that says where the piece is located and its bounds, and the @@ -37,59 +37,67 @@ class TilePos; * box. Failing to check this will cause the level generator to create new * chunks, leading to infinite loops and other errors. */ -class StructurePiece -{ +class StructurePiece { public: - class BlockSelector - { - - protected: - int nextId; + class BlockSelector { + protected: + int nextId; int nextData; - public: - virtual void next(Random *random, int worldX, int worldY, int worldZ, bool isEdge) {} + public: + virtual void next(Random* random, int worldX, int worldY, int worldZ, + bool isEdge) {} - virtual int getNextId() { return nextId; } - virtual int getNextData() { return nextData; } + virtual int getNextId() { return nextId; } + virtual int getNextData() { return nextData; } }; -public: // 4J is protected in java, but accessed from VillagePieces, not sure how - BoundingBox *boundingBox; +public + : // 4J is protected in java, but accessed from VillagePieces, not sure how + BoundingBox* boundingBox; + protected: - int orientation; - int genDepth; + int orientation; + int genDepth; StructurePiece(int genDepth); + public: - virtual ~StructurePiece(); + virtual ~StructurePiece(); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB) = 0; + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB) = 0; - virtual BoundingBox *getBoundingBox(); + virtual BoundingBox* getBoundingBox(); int getGenDepth(); public: - bool isInChunk(ChunkPos *pos); - static StructurePiece *findCollisionPiece(std::list *pieces, BoundingBox *box); - virtual TilePos *getLocatorPosition(); + bool isInChunk(ChunkPos* pos); + static StructurePiece* findCollisionPiece( + std::list* pieces, BoundingBox* box); + virtual TilePos* getLocatorPosition(); + protected: - bool edgesLiquid(Level *level, BoundingBox *chunkBB); + bool edgesLiquid(Level* level, BoundingBox* chunkBB); + public: - // 4J Stu - Made these public to use in game rules - int getWorldX(int x, int z); - int getWorldY(int y); - int getWorldZ(int x, int z); - int getOrientationData(int tile, int data); - virtual void placeBlock(Level *level, int block, int data, int x, int y, int z, BoundingBox *chunkBB); + // 4J Stu - Made these public to use in game rules + int getWorldX(int x, int z); + int getWorldY(int y); + int getWorldZ(int x, int z); + int getOrientationData(int tile, int data); + virtual void placeBlock(Level* level, int block, int data, int x, int y, + int z, BoundingBox* chunkBB); /** * The purpose of this method is to wrap the getTile call on Level, in order * to prevent the level from generating chunks that shouldn't be loaded yet. * Returns 0 if the call is out of bounds. - * + * * @param level * @param x * @param y @@ -97,21 +105,49 @@ public: * @param chunkPosition * @return */ - virtual int getBlock(Level *level, int x, int y, int z, BoundingBox *chunkBB); - virtual void generateAirBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1); - virtual void generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int fillTile, bool skipAir); - virtual void generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int edgeData, int fillTile, int fillData, bool skipAir); - virtual void generateBox(Level *level, BoundingBox *chunkBB, BoundingBox *boxBB, int edgeTile, int fillTile, bool skipAir); - virtual void generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, bool skipAir, Random *random, BlockSelector *selector); - virtual void generateBox(Level *level, BoundingBox *chunkBB, BoundingBox *boxBB, bool skipAir, Random *random, BlockSelector *selector); - virtual void generateMaybeBox(Level *level, BoundingBox *chunkBB, Random *random, float probability, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int fillTile, bool skipAir); - virtual void maybeGenerateBlock(Level *level, BoundingBox *chunkBB, Random *random, float probability, int x, int y, int z, int tile, int data); - virtual void generateUpperHalfSphere(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int fillTile, bool skipAir); - virtual void generateAirColumnUp(Level *level, int x, int startY, int z, BoundingBox *chunkBB); - virtual void fillColumnDown(Level *level, int tile, int tileData, int x, int startY, int z, BoundingBox *chunkBB); - virtual bool createChest(Level *level, BoundingBox *chunkBB, Random *random, int x, int y, int z, WeighedTreasureArray treasure, int numRolls); - virtual bool createDispenser(Level *level, BoundingBox *chunkBB, Random *random, int x, int y, int z, int facing, WeighedTreasureArray items, int numRolls); + virtual int getBlock(Level* level, int x, int y, int z, + BoundingBox* chunkBB); + virtual void generateAirBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1); + virtual void generateBox(Level* level, BoundingBox* chunkBB, int x0, int y0, + int z0, int x1, int y1, int z1, int edgeTile, + int fillTile, bool skipAir); + virtual void generateBox(Level* level, BoundingBox* chunkBB, int x0, int y0, + int z0, int x1, int y1, int z1, int edgeTile, + int edgeData, int fillTile, int fillData, + bool skipAir); + virtual void generateBox(Level* level, BoundingBox* chunkBB, + BoundingBox* boxBB, int edgeTile, int fillTile, + bool skipAir); + virtual void generateBox(Level* level, BoundingBox* chunkBB, int x0, int y0, + int z0, int x1, int y1, int z1, bool skipAir, + Random* random, BlockSelector* selector); + virtual void generateBox(Level* level, BoundingBox* chunkBB, + BoundingBox* boxBB, bool skipAir, Random* random, + BlockSelector* selector); + virtual void generateMaybeBox(Level* level, BoundingBox* chunkBB, + Random* random, float probability, int x0, + int y0, int z0, int x1, int y1, int z1, + int edgeTile, int fillTile, bool skipAir); + virtual void maybeGenerateBlock(Level* level, BoundingBox* chunkBB, + Random* random, float probability, int x, + int y, int z, int tile, int data); + virtual void generateUpperHalfSphere(Level* level, BoundingBox* chunkBB, + int x0, int y0, int z0, int x1, int y1, + int z1, int fillTile, bool skipAir); + virtual void generateAirColumnUp(Level* level, int x, int startY, int z, + BoundingBox* chunkBB); + virtual void fillColumnDown(Level* level, int tile, int tileData, int x, + int startY, int z, BoundingBox* chunkBB); + virtual bool createChest(Level* level, BoundingBox* chunkBB, Random* random, + int x, int y, int z, WeighedTreasureArray treasure, + int numRolls); + virtual bool createDispenser(Level* level, BoundingBox* chunkBB, + Random* random, int x, int y, int z, + int facing, WeighedTreasureArray items, + int numRolls); protected: - void createDoor(Level *level, BoundingBox *chunkBB, Random *random, int x, int y, int z, int orientation); + void createDoor(Level* level, BoundingBox* chunkBB, Random* random, int x, + int y, int z, int orientation); }; diff --git a/Minecraft.World/WorldGen/Structures/StructureStart.cpp b/Minecraft.World/WorldGen/Structures/StructureStart.cpp index 25002c5d1..07845cc58 100644 --- a/Minecraft.World/WorldGen/Structures/StructureStart.cpp +++ b/Minecraft.World/WorldGen/Structures/StructureStart.cpp @@ -4,108 +4,85 @@ #include "StructurePiece.h" #include "../../Util/BoundingBox.h" - -StructureStart::StructureStart() -{ - boundingBox = NULL; // 4J added initialiser +StructureStart::StructureStart() { + boundingBox = NULL; // 4J added initialiser } -StructureStart::~StructureStart() -{ - for(AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) - { - delete (*it); - } - delete boundingBox; +StructureStart::~StructureStart() { + for (AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++) { + delete (*it); + } + delete boundingBox; } -BoundingBox *StructureStart::getBoundingBox() -{ - return boundingBox; -} +BoundingBox* StructureStart::getBoundingBox() { return boundingBox; } -std::list *StructureStart::getPieces() -{ - return &pieces; -} +std::list* StructureStart::getPieces() { return &pieces; } -void StructureStart::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - AUTO_VAR(it, pieces.begin()); +void StructureStart::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + AUTO_VAR(it, pieces.begin()); - while( it != pieces.end() ) - { - if( (*it)->getBoundingBox()->intersects(chunkBB) && !(*it)->postProcess(level, random, chunkBB)) - { + while (it != pieces.end()) { + if ((*it)->getBoundingBox()->intersects(chunkBB) && + !(*it)->postProcess(level, random, chunkBB)) { // this piece can't be placed, so remove it to avoid future // attempts - it = pieces.erase(it); - } - else - { - it++; - } - } + it = pieces.erase(it); + } else { + it++; + } + } } -void StructureStart::calculateBoundingBox() -{ +void StructureStart::calculateBoundingBox() { boundingBox = BoundingBox::getUnknownBox(); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) - { - StructurePiece *piece = *it; - boundingBox->expand(piece->getBoundingBox()); - } + for (AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++) { + StructurePiece* piece = *it; + boundingBox->expand(piece->getBoundingBox()); + } } -void StructureStart::moveBelowSeaLevel(Level *level, Random *random, int offset) -{ - const int MAX_Y = level->seaLevel - offset; +void StructureStart::moveBelowSeaLevel(Level* level, Random* random, + int offset) { + const int MAX_Y = level->seaLevel - offset; // set lowest possible position (at bedrock) int y1Pos = boundingBox->getYSpan() + 1; // move up randomly within the available span - if (y1Pos < MAX_Y) - { + if (y1Pos < MAX_Y) { y1Pos += random->nextInt(MAX_Y - y1Pos); } // move all bounding boxes int dy = y1Pos - boundingBox->y1; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) - { - StructurePiece *piece = *it; + for (AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++) { + StructurePiece* piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } -void StructureStart::moveInsideHeights(Level *level, Random *random, int lowestAllowed, int highestAllowed) -{ - int heightSpan = highestAllowed - lowestAllowed + 1 - boundingBox->getYSpan(); +void StructureStart::moveInsideHeights(Level* level, Random* random, + int lowestAllowed, int highestAllowed) { + int heightSpan = + highestAllowed - lowestAllowed + 1 - boundingBox->getYSpan(); int y0Pos = 1; - if (heightSpan > 1) - { + if (heightSpan > 1) { y0Pos = lowestAllowed + random->nextInt(heightSpan); - } - else - { + } else { y0Pos = lowestAllowed; } // move all bounding boxes int dy = y0Pos - boundingBox->y0; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) - { - StructurePiece *piece = *it; + for (AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++) { + StructurePiece* piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } -bool StructureStart::isValid() -{ - return true; -} \ No newline at end of file +bool StructureStart::isValid() { return true; } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/StructureStart.h b/Minecraft.World/WorldGen/Structures/StructureStart.h index 3f7c35bc3..f9afa5aba 100644 --- a/Minecraft.World/WorldGen/Structures/StructureStart.h +++ b/Minecraft.World/WorldGen/Structures/StructureStart.h @@ -2,24 +2,25 @@ class StructurePiece; class BoundingBox; -class StructureStart -{ - +class StructureStart { protected: - std::list pieces; - BoundingBox *boundingBox; + std::list pieces; + BoundingBox* boundingBox; StructureStart(); -public: - ~StructureStart(); - BoundingBox *getBoundingBox(); - std::list *getPieces(); - void postProcess(Level *level, Random *random, BoundingBox *chunkBB); -protected: - void calculateBoundingBox(); - void moveBelowSeaLevel(Level *level, Random *random, int offset); - void moveInsideHeights(Level *level, Random *random, int lowestAllowed, int highestAllowed); -public: - bool isValid(); +public: + ~StructureStart(); + BoundingBox* getBoundingBox(); + std::list* getPieces(); + void postProcess(Level* level, Random* random, BoundingBox* chunkBB); + +protected: + void calculateBoundingBox(); + void moveBelowSeaLevel(Level* level, Random* random, int offset); + void moveInsideHeights(Level* level, Random* random, int lowestAllowed, + int highestAllowed); + +public: + bool isValid(); }; diff --git a/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.cpp b/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.cpp index e1b0e07b3..376985870 100644 --- a/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.cpp +++ b/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.cpp @@ -5,7 +5,6 @@ #include "../../Headers/net.minecraft.world.level.levelgen.feature.h" #include "../../Headers/net.minecraft.world.entity.boss.enderdragon.h" - // Spike centre positions, calculated using // for(int i=0;i<8;i++) // { @@ -13,59 +12,58 @@ // int z=40* Mth::sin(2*(-PI+(PI/8)*i)); // } +TheEndBiomeDecorator::SPIKE TheEndBiomeDecorator::SpikeValA[8] = { + // The chunk that the spike is in has to be the smallest x and z that any + // part of it is in a chunk(x,z) will only be post-processed when the chunks + // (x+1,z), (x,z+1) and (x+1,z+1) are also loaded -TheEndBiomeDecorator::SPIKE TheEndBiomeDecorator::SpikeValA[8]= -{ - // The chunk that the spike is in has to be the smallest x and z that any part of it is in - // a chunk(x,z) will only be post-processed when the chunks (x+1,z), (x,z+1) and (x+1,z+1) are also loaded - - // first two values are the smallest x and z of the chunk that the feature is in - so the centre point minus the radius - { 32, -16, 40, 0, 2 },// smallest block - 38,-2 - { 16, 16, 28, 28, 2 },// smallest block - 26,26 - { -16, 32, 0, 40, 2 },// smallest block - -2,38 - { -32, 16, -28, 28, 3 },// smallest block - -31,26 - { -48, -16, -40, 0, 3 },// smallest block - -43,-3 - { -32, -32, -28, -28, 3 },// smallest block - -31,-31 - { -16, -48, 0, -40, 4 },// smallest block - -4,-44 - { 16, -32, 28, -28, 4 },// smallest block - 24,-32 + // first two values are the smallest x and z of the chunk that the feature + // is in - so the centre point minus the radius + {32, -16, 40, 0, 2}, // smallest block - 38,-2 + {16, 16, 28, 28, 2}, // smallest block - 26,26 + {-16, 32, 0, 40, 2}, // smallest block - -2,38 + {-32, 16, -28, 28, 3}, // smallest block - -31,26 + {-48, -16, -40, 0, 3}, // smallest block - -43,-3 + {-32, -32, -28, -28, 3}, // smallest block - -31,-31 + {-16, -48, 0, -40, 4}, // smallest block - -4,-44 + {16, -32, 28, -28, 4}, // smallest block - 24,-32 }; - -TheEndBiomeDecorator::TheEndBiomeDecorator(Biome *biome) : BiomeDecorator(biome) -{ - spikeFeature = new SpikeFeature(Tile::whiteStone_Id); - endPodiumFeature = new EndPodiumFeature(Tile::whiteStone_Id); +TheEndBiomeDecorator::TheEndBiomeDecorator(Biome* biome) + : BiomeDecorator(biome) { + spikeFeature = new SpikeFeature(Tile::whiteStone_Id); + endPodiumFeature = new EndPodiumFeature(Tile::whiteStone_Id); } -void TheEndBiomeDecorator::decorate() -{ - decorateOres(); +void TheEndBiomeDecorator::decorate() { + decorateOres(); - // this will only set the y to the top y of the chunks already processed... - int y = level->getTopSolidBlock(xo+8, zo+8); - if(y>level->GetHighestY()) level->SetHighestY(y); + // this will only set the y to the top y of the chunks already processed... + int y = level->getTopSolidBlock(xo + 8, zo + 8); + if (y > level->GetHighestY()) level->SetHighestY(y); - // 4J-PB - editing to place 8 spikes in a circle, with increasing height + // 4J-PB - editing to place 8 spikes in a circle, with increasing height - // are we within the chunk with a spike? - for(int i=0;i<8;i++) - { - if((xo == SpikeValA[i].iChunkX) && (zo == SpikeValA[i].iChunkZ)) - { - // in the right chunk - spikeFeature->placeWithIndex(level, random, SpikeValA[i].x, level->GetHighestY(), SpikeValA[i].z,i,SpikeValA[i].radius); - } - } - if (xo == 0 && zo == 0) - { - std::shared_ptr enderDragon = std::shared_ptr(new EnderDragon(level)); + // are we within the chunk with a spike? + for (int i = 0; i < 8; i++) { + if ((xo == SpikeValA[i].iChunkX) && (zo == SpikeValA[i].iChunkZ)) { + // in the right chunk + spikeFeature->placeWithIndex(level, random, SpikeValA[i].x, + level->GetHighestY(), SpikeValA[i].z, + i, SpikeValA[i].radius); + } + } + if (xo == 0 && zo == 0) { + std::shared_ptr enderDragon = + std::shared_ptr(new EnderDragon(level)); enderDragon->moveTo(0, 128, 0, random->nextFloat() * 360, 0); level->addEntity(enderDragon); - } + } - // end podium radius is 4, position is 0,0, so chunk needs to be the -16,-16 one since this guarantees that all chunks required for the podium are loaded - if (xo == -16 && zo == -16) - { - endPodiumFeature->place(level, random, 0, Level::genDepth / 2, 0); + // end podium radius is 4, position is 0,0, so chunk needs to be the -16,-16 + // one since this guarantees that all chunks required for the podium are + // loaded + if (xo == -16 && zo == -16) { + endPodiumFeature->place(level, random, 0, Level::genDepth / 2, 0); } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.h b/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.h index a447b0a58..c184af238 100644 --- a/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.h +++ b/Minecraft.World/WorldGen/Structures/TheEndBiomeDecorator.h @@ -1,25 +1,22 @@ #pragma once #include "../Biomes/BiomeDecorator.h" -class TheEndBiomeDecorator : public BiomeDecorator -{ +class TheEndBiomeDecorator : public BiomeDecorator { public: - typedef struct - { - int iChunkX; - int iChunkZ; - int x; - int z; - int radius; - } - SPIKE; - - TheEndBiomeDecorator(Biome *biome); + typedef struct { + int iChunkX; + int iChunkZ; + int x; + int z; + int radius; + } SPIKE; + + TheEndBiomeDecorator(Biome* biome); + protected: - Feature *spikeFeature; - Feature *endPodiumFeature; - virtual void decorate(); + Feature* spikeFeature; + Feature* endPodiumFeature; + virtual void decorate(); - - static SPIKE SpikeValA[8]; + static SPIKE SpikeValA[8]; }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/Village.cpp b/Minecraft.World/WorldGen/Structures/Village.cpp index a81a7e656..737a7b498 100644 --- a/Minecraft.World/WorldGen/Structures/Village.cpp +++ b/Minecraft.World/WorldGen/Structures/Village.cpp @@ -8,505 +8,449 @@ #include "../../Util/BasicTypeContainers.h" #include "Village.h" -Village::Aggressor::Aggressor(std::shared_ptr mob, int timeStamp) -{ - this->mob = mob; - this->timeStamp = timeStamp; +Village::Aggressor::Aggressor(std::shared_ptr mob, int timeStamp) { + this->mob = mob; + this->timeStamp = timeStamp; } -Village::Village() -{ - accCenter = new Pos(0, 0, 0); - center = new Pos(0, 0, 0); - radius = 0; - stableSince = 0; - _tick = 0; - populationSize = 0; - golemCount = 0; - noBreedTimer = 0; +Village::Village() { + accCenter = new Pos(0, 0, 0); + center = new Pos(0, 0, 0); + radius = 0; + stableSince = 0; + _tick = 0; + populationSize = 0; + golemCount = 0; + noBreedTimer = 0; - level = NULL; + level = NULL; } -Village::Village(Level *level) -{ - accCenter = new Pos(0, 0, 0); - center = new Pos(0, 0, 0); - radius = 0; - stableSince = 0; - _tick = 0; - populationSize = 0; - golemCount = 0; - noBreedTimer = 0; +Village::Village(Level* level) { + accCenter = new Pos(0, 0, 0); + center = new Pos(0, 0, 0); + radius = 0; + stableSince = 0; + _tick = 0; + populationSize = 0; + golemCount = 0; + noBreedTimer = 0; - this->level = level; + this->level = level; } -Village::~Village() -{ - delete accCenter; - delete center; - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) - { - delete *it; - } +Village::~Village() { + delete accCenter; + delete center; + for (AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) { + delete *it; + } } -void Village::setLevel(Level *level) -{ - this->level = level; +void Village::setLevel(Level* level) { this->level = level; } + +void Village::tick(int tick) { + this->_tick = tick; + updateDoors(); + updateAggressors(); + if (tick % 20 == 0) countPopulation(); + if (tick % 30 == 0) countGolem(); + + int idealGolemCount = populationSize / 10; + if (golemCount < idealGolemCount && doorInfos.size() > 20 && + level->random->nextInt(7000) == 0) { + Vec3* spawnPos = + findRandomSpawnPos(center->x, center->y, center->z, 2, 4, 2); + if (spawnPos != NULL) { + std::shared_ptr vg = + std::shared_ptr(new VillagerGolem(level)); + vg->setPos(spawnPos->x, spawnPos->y, spawnPos->z); + level->addEntity(vg); + ++golemCount; + } + } + + // 4J - All commented out in java + // for (DoorInfo di : doorInfos) { + // level.addParticle("heart", di.getIndoorX() + 0.5, + // di.getIndoorY() + .5f, di.getIndoorZ() + 0.5, 0, 1, 0); + // } + // + // for (int i = 0; i < 8; ++i) + // for (int j = 0; j < 8; ++j) + // level.addParticle("heart", center.x + 0.5 + i, center.y + + // .5f, center.z + 0.5 + j, 0, 1, 0); + // for (float i = 0; i < Math.PI * 2; i += 0.1) { + // int x = center.x + (int) (Math.cos(i) * radius); + // int z = center.z + (int) (Math.sin(i) * radius); + // level.addParticle("heart", x, center.y + .5f, z, 0, 1, 0); + // } } -void Village::tick(int tick) -{ - this->_tick = tick; - updateDoors(); - updateAggressors(); - if (tick % 20 == 0) countPopulation(); - if (tick % 30 == 0) countGolem(); - - int idealGolemCount = populationSize / 10; - if (golemCount < idealGolemCount && doorInfos.size() > 20 && level->random->nextInt(7000) == 0) - { - Vec3 *spawnPos = findRandomSpawnPos(center->x, center->y, center->z, 2, 4, 2); - if (spawnPos != NULL) - { - std::shared_ptr vg = std::shared_ptr( new VillagerGolem(level) ); - vg->setPos(spawnPos->x, spawnPos->y, spawnPos->z); - level->addEntity(vg); - ++golemCount; - } - } - - // 4J - All commented out in java - // for (DoorInfo di : doorInfos) { - // level.addParticle("heart", di.getIndoorX() + 0.5, di.getIndoorY() + .5f, di.getIndoorZ() + 0.5, 0, 1, 0); - // } - // - // for (int i = 0; i < 8; ++i) - // for (int j = 0; j < 8; ++j) - // level.addParticle("heart", center.x + 0.5 + i, center.y + .5f, center.z + 0.5 + j, 0, 1, 0); - // for (float i = 0; i < Math.PI * 2; i += 0.1) { - // int x = center.x + (int) (Math.cos(i) * radius); - // int z = center.z + (int) (Math.sin(i) * radius); - // level.addParticle("heart", x, center.y + .5f, z, 0, 1, 0); - // } +Vec3* Village::findRandomSpawnPos(int x, int y, int z, int sx, int sy, int sz) { + for (int i = 0; i < 10; ++i) { + int xx = x + level->random->nextInt(16) - 8; + int yy = y + level->random->nextInt(6) - 3; + int zz = z + level->random->nextInt(16) - 8; + if (!isInside(xx, yy, zz)) continue; + if (canSpawnAt(xx, yy, zz, sx, sy, sz)) + return Vec3::newTemp(xx, yy, zz); + } + return NULL; } -Vec3 *Village::findRandomSpawnPos(int x, int y, int z, int sx, int sy, int sz) -{ - for (int i = 0; i < 10; ++i) - { - int xx = x + level->random->nextInt(16) - 8; - int yy = y + level->random->nextInt(6) - 3; - int zz = z + level->random->nextInt(16) - 8; - if (!isInside(xx, yy, zz)) continue; - if (canSpawnAt(xx, yy, zz, sx, sy, sz)) return Vec3::newTemp(xx, yy, zz); - } - return NULL; +bool Village::canSpawnAt(int x, int y, int z, int sx, int sy, int sz) { + if (!level->isTopSolidBlocking(x, y - 1, z)) return false; + + int startX = x - sx / 2; + int startZ = z - sz / 2; + for (int xx = startX; xx < startX + sx; xx++) + for (int yy = y; yy < y + sy; yy++) + for (int zz = startZ; zz < startZ + sz; zz++) + if (level->isSolidBlockingTile(xx, yy, zz)) return false; + + return true; } -bool Village::canSpawnAt(int x, int y, int z, int sx, int sy, int sz) -{ - if (!level->isTopSolidBlocking(x, y - 1, z)) return false; - - int startX = x - sx / 2; - int startZ = z - sz / 2; - for (int xx = startX; xx < startX + sx; xx++) - for (int yy = y; yy < y + sy; yy++) - for (int zz = startZ; zz < startZ + sz; zz++) - if (level->isSolidBlockingTile(xx, yy, zz)) return false; - - return true; +void Village::countGolem() { + // Fix - let bots report themselves? + std::vector >* golems = level->getEntitiesOfClass( + typeid(VillagerGolem), + AABB::newTemp(center->x - radius, center->y - 4, center->z - radius, + center->x + radius, center->y + 4, center->z + radius)); + golemCount = golems->size(); + delete golems; } -void Village::countGolem() -{ - // Fix - let bots report themselves? - std::vector > *golems = level->getEntitiesOfClass(typeid(VillagerGolem), AABB::newTemp(center->x - radius, center->y - 4, center->z - radius, center->x + radius, center->y + 4, center->z + radius)); - golemCount = golems->size(); - delete golems; +void Village::countPopulation() { + std::vector >* villagers = + level->getEntitiesOfClass( + typeid(Villager), + AABB::newTemp(center->x - radius, center->y - 4, center->z - radius, + center->x + radius, center->y + 4, + center->z + radius)); + populationSize = villagers->size(); + delete villagers; + + if (populationSize == 0) { + // forget standing + playerStanding.clear(); + } } -void Village::countPopulation() -{ - std::vector > *villagers = level->getEntitiesOfClass(typeid(Villager), AABB::newTemp(center->x - radius, center->y - 4, center->z - radius, center->x + radius, center->y + 4, center->z + radius)); - populationSize = villagers->size(); - delete villagers; +Pos* Village::getCenter() { return center; } - if (populationSize == 0) - { - // forget standing - playerStanding.clear(); - } +int Village::getRadius() { return radius; } + +int Village::getDoorCount() { return doorInfos.size(); } + +int Village::getStableAge() { return _tick - stableSince; } + +int Village::getPopulationSize() { return populationSize; } + +bool Village::isInside(int xx, int yy, int zz) { + return center->distSqr(xx, yy, zz) < radius * radius; } -Pos *Village::getCenter() -{ - return center; +std::vector >* Village::getDoorInfos() { + return &doorInfos; } -int Village::getRadius() -{ - return radius; +std::shared_ptr Village::getClosestDoorInfo(int x, int y, int z) { + std::shared_ptr closest = nullptr; + int closestDistSqr = Integer::MAX_VALUE; + // for (DoorInfo dm : doorInfos) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) { + std::shared_ptr dm = *it; + int distSqr = dm->distanceToSqr(x, y, z); + if (distSqr < closestDistSqr) { + closest = dm; + closestDistSqr = distSqr; + } + } + return closest; } -int Village::getDoorCount() -{ - return doorInfos.size(); +std::shared_ptr Village::getBestDoorInfo(int x, int y, int z) { + std::shared_ptr closest = nullptr; + int closestDist = Integer::MAX_VALUE; + // for (DoorInfo dm : doorInfos) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) { + std::shared_ptr dm = *it; + + int distSqr = dm->distanceToSqr(x, y, z); + if (distSqr > 16 * 16) + distSqr *= 1000; + else + distSqr = dm->getBookingsCount(); + + if (distSqr < closestDist) { + closest = dm; + closestDist = distSqr; + } + } + return closest; } -int Village::getStableAge() -{ - return _tick - stableSince; +bool Village::hasDoorInfo(int x, int y, int z) { + return getDoorInfo(x, y, z) != NULL; } -int Village::getPopulationSize() -{ - return populationSize; +std::shared_ptr Village::getDoorInfo(int x, int y, int z) { + if (center->distSqr(x, y, z) > radius * radius) return nullptr; + // for (DoorInfo di : doorInfos) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) { + std::shared_ptr di = *it; + if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; + } + return nullptr; } -bool Village::isInside(int xx, int yy, int zz) -{ - return center->distSqr(xx, yy, zz) < radius * radius; +void Village::addDoorInfo(std::shared_ptr di) { + doorInfos.push_back(di); + accCenter->x += di->x; + accCenter->y += di->y; + accCenter->z += di->z; + calcInfo(); + stableSince = di->timeStamp; } -std::vector > *Village::getDoorInfos() -{ - return &doorInfos; +bool Village::canRemove() { return doorInfos.empty(); } + +void Village::addAggressor(std::shared_ptr mob) { + // for (Aggressor a : aggressors) + for (AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) { + Aggressor* a = *it; + if (a->mob == mob) { + a->timeStamp = _tick; + return; + } + } + aggressors.push_back(new Aggressor(mob, _tick)); } -std::shared_ptr Village::getClosestDoorInfo(int x, int y, int z) -{ - std::shared_ptr closest = nullptr; - int closestDistSqr = Integer::MAX_VALUE; - //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) - { - std::shared_ptr dm = *it; - int distSqr = dm->distanceToSqr(x, y, z); - if (distSqr < closestDistSqr) - { - closest = dm; - closestDistSqr = distSqr; - } - } - return closest; +std::shared_ptr Village::getClosestAggressor(std::shared_ptr from) { + double closestSqr = Double::MAX_VALUE; + Aggressor* closest = NULL; + // for (int i = 0; i < aggressors.size(); ++i) + for (AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) { + Aggressor* a = *it; // aggressors.get(i); + double distSqr = a->mob->distanceToSqr(from); + if (distSqr > closestSqr) continue; + closest = a; + closestSqr = distSqr; + } + return closest != NULL ? closest->mob : nullptr; } -std::shared_ptrVillage::getBestDoorInfo(int x, int y, int z) +std::shared_ptr Village::getClosestBadStandingPlayer( + std::shared_ptr + from) // 4J Stu - Should be LivingEntity when we add that { - std::shared_ptr closest = nullptr; - int closestDist = Integer::MAX_VALUE; - //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) - { - std::shared_ptrdm = *it; + double closestSqr = Double::MAX_VALUE; + std::shared_ptr closest = nullptr; - int distSqr = dm->distanceToSqr(x, y, z); - if (distSqr > 16 * 16) distSqr *= 1000; - else distSqr = dm->getBookingsCount(); + // for (String player : playerStanding.keySet()) + for (AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); + ++it) { + std::wstring player = it->first; + if (isVeryBadStanding(player)) { + std::shared_ptr mob = level->getPlayerByName(player); + if (mob != NULL) { + double distSqr = mob->distanceToSqr(from); + if (distSqr > closestSqr) continue; + closest = mob; + closestSqr = distSqr; + } + } + } - if (distSqr < closestDist) - { - closest = dm; - closestDist = distSqr; - } - } - return closest; + return closest; } -bool Village::hasDoorInfo(int x, int y, int z) -{ - return getDoorInfo(x, y, z) != NULL; +void Village::updateAggressors() { + // for (Iterator it = aggressors.iterator(); it.hasNext();) + for (AUTO_VAR(it, aggressors.begin()); it != aggressors.end();) { + Aggressor* a = *it; // it.next(); + if (!a->mob->isAlive() || abs(_tick - a->timeStamp) > 300) { + delete *it; + it = aggressors.erase(it); + // it.remove(); + } else { + ++it; + } + } } -std::shared_ptrVillage::getDoorInfo(int x, int y, int z) -{ - if (center->distSqr(x, y, z) > radius * radius) return nullptr; - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) - { - std::shared_ptr di = *it; - if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; - } - return nullptr; +void Village::updateDoors() { + bool removed = false; + bool resetBookings = level->random->nextInt(50) == 0; + // for (Iterator it = doorInfos.iterator(); it.hasNext();) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end();) { + std::shared_ptr dm = *it; // it.next(); + if (resetBookings) dm->resetBookingCount(); + if (!isDoor(dm->x, dm->y, dm->z) || abs(_tick - dm->timeStamp) > 1200) { + accCenter->x -= dm->x; + accCenter->y -= dm->y; + accCenter->z -= dm->z; + removed = true; + dm->removed = true; + + it = doorInfos.erase(it); + // it.remove(); + } else { + ++it; + } + } + + if (removed) calcInfo(); } -void Village::addDoorInfo(std::shared_ptr di) -{ - doorInfos.push_back(di); - accCenter->x += di->x; - accCenter->y += di->y; - accCenter->z += di->z; - calcInfo(); - stableSince = di->timeStamp; +bool Village::isDoor(int x, int y, int z) { + int tileId = level->getTile(x, y, z); + if (tileId <= 0) return false; + return tileId == Tile::door_wood_Id; } -bool Village::canRemove() -{ - return doorInfos.empty(); +void Village::calcInfo() { + int s = doorInfos.size(); + if (s == 0) { + center->set(0, 0, 0); + radius = 0; + return; + } + center->set(accCenter->x / s, accCenter->y / s, accCenter->z / s); + int maxRadiusSqr = 0; + // for (DoorInfo dm : doorInfos) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) { + std::shared_ptr dm = *it; + maxRadiusSqr = std::max( + dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); + } + int doorDist = + Villages::MaxDoorDist; // Take into local int for PS4 as max takes a + // reference to the const int there and then + // needs the value to exist for the linker + radius = std::max(doorDist, (int)sqrt((float)maxRadiusSqr) + 1); } -void Village::addAggressor(std::shared_ptr mob) -{ - //for (Aggressor a : aggressors) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) - { - Aggressor *a = *it; - if (a->mob == mob) - { - a->timeStamp = _tick; - return; - } - } - aggressors.push_back(new Aggressor(mob, _tick)); +int Village::getStanding(const std::wstring& playerName) { + AUTO_VAR(it, playerStanding.find(playerName)); + if (it != playerStanding.end()) { + return it->second; + } + return 0; } -std::shared_ptr Village::getClosestAggressor(std::shared_ptr from) -{ - double closestSqr = Double::MAX_VALUE; - Aggressor *closest = NULL; - //for (int i = 0; i < aggressors.size(); ++i) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) - { - Aggressor *a = *it; //aggressors.get(i); - double distSqr = a->mob->distanceToSqr(from); - if (distSqr > closestSqr) continue; - closest = a; - closestSqr = distSqr; - } - return closest != NULL ? closest->mob : nullptr; +int Village::modifyStanding(const std::wstring& playerName, int delta) { + int current = getStanding(playerName); + int newValue = Mth::clamp(current + delta, -30, 10); + playerStanding.insert(std::pair(playerName, newValue)); + return newValue; } -std::shared_ptr Village::getClosestBadStandingPlayer(std::shared_ptr from) // 4J Stu - Should be LivingEntity when we add that -{ - double closestSqr = Double::MAX_VALUE; - std::shared_ptr closest = nullptr; - - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it,playerStanding.begin()); it != playerStanding.end(); ++it) - { - std::wstring player = it->first; - if (isVeryBadStanding(player)) - { - std::shared_ptr mob = level->getPlayerByName(player); - if (mob != NULL) - { - double distSqr = mob->distanceToSqr(from); - if (distSqr > closestSqr) continue; - closest = mob; - closestSqr = distSqr; - } - } - } - - return closest; +bool Village::isGoodStanding(const std::wstring& playerName) { + return getStanding(playerName) >= 0; } -void Village::updateAggressors() -{ - //for (Iterator it = aggressors.iterator(); it.hasNext();) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end();) - { - Aggressor *a = *it; //it.next(); - if (!a->mob->isAlive() || abs(_tick - a->timeStamp) > 300) - { - delete *it; - it = aggressors.erase(it); - //it.remove(); - } - else - { - ++it; - } - } +bool Village::isBadStanding(const std::wstring& playerName) { + return getStanding(playerName) <= -5; } -void Village::updateDoors() -{ - bool removed = false; - bool resetBookings = level->random->nextInt(50) == 0; - //for (Iterator it = doorInfos.iterator(); it.hasNext();) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end();) - { - std::shared_ptr dm = *it; //it.next(); - if (resetBookings) dm->resetBookingCount(); - if (!isDoor(dm->x, dm->y, dm->z) || abs(_tick - dm->timeStamp) > 1200) - { - accCenter->x -= dm->x; - accCenter->y -= dm->y; - accCenter->z -= dm->z; - removed = true; - dm->removed = true; - - it = doorInfos.erase(it); - //it.remove(); - } - else - { - ++it; - } - } - - if (removed) calcInfo(); +bool Village::isVeryBadStanding(const std::wstring playerName) { + return getStanding(playerName) <= -15; } -bool Village::isDoor(int x, int y, int z) -{ - int tileId = level->getTile(x, y, z); - if (tileId <= 0) return false; - return tileId == Tile::door_wood_Id; +void Village::readAdditionalSaveData(CompoundTag* tag) { + populationSize = tag->getInt(L"PopSize"); + radius = tag->getInt(L"Radius"); + golemCount = tag->getInt(L"Golems"); + stableSince = tag->getInt(L"Stable"); + _tick = tag->getInt(L"Tick"); + noBreedTimer = tag->getInt(L"MTick"); + center->x = tag->getInt(L"CX"); + center->y = tag->getInt(L"CY"); + center->z = tag->getInt(L"CZ"); + accCenter->x = tag->getInt(L"ACX"); + accCenter->y = tag->getInt(L"ACY"); + accCenter->z = tag->getInt(L"ACZ"); + + ListTag* doorTags = + (ListTag*)tag->getList(L"Doors"); + for (int i = 0; i < doorTags->size(); i++) { + CompoundTag* dTag = doorTags->get(i); + + std::shared_ptr door = std::shared_ptr(new DoorInfo( + dTag->getInt(L"X"), dTag->getInt(L"Y"), dTag->getInt(L"Z"), + dTag->getInt(L"IDX"), dTag->getInt(L"IDZ"), dTag->getInt(L"TS"))); + doorInfos.push_back(door); + } + + ListTag* playerTags = + (ListTag*)tag->getList(L"Players"); + for (int i = 0; i < playerTags->size(); i++) { + CompoundTag* pTag = playerTags->get(i); + playerStanding.insert(std::pair( + pTag->getString(L"Name"), pTag->getInt(L"S"))); + } } -void Village::calcInfo() -{ - int s = doorInfos.size(); - if (s == 0) - { - center->set(0, 0, 0); - radius = 0; - return; - } - center->set(accCenter->x / s, accCenter->y / s, accCenter->z / s); - int maxRadiusSqr = 0; - //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) - { - std::shared_ptr dm = *it; - maxRadiusSqr = std::max(dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); - } - int doorDist= Villages::MaxDoorDist; // Take into local int for PS4 as max takes a reference to the const int there and then needs the value to exist for the linker - radius = std::max(doorDist, (int) sqrt((float)maxRadiusSqr) + 1); +void Village::addAdditonalSaveData(CompoundTag* tag) { + tag->putInt(L"PopSize", populationSize); + tag->putInt(L"Radius", radius); + tag->putInt(L"Golems", golemCount); + tag->putInt(L"Stable", stableSince); + tag->putInt(L"Tick", _tick); + tag->putInt(L"MTick", noBreedTimer); + tag->putInt(L"CX", center->x); + tag->putInt(L"CY", center->y); + tag->putInt(L"CZ", center->z); + tag->putInt(L"ACX", accCenter->x); + tag->putInt(L"ACY", accCenter->y); + tag->putInt(L"ACZ", accCenter->z); + + ListTag* doorTags = new ListTag(L"Doors"); + // for (DoorInfo dm : doorInfos) + for (AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) { + std::shared_ptr dm = *it; + CompoundTag* doorTag = new CompoundTag(L"Door"); + doorTag->putInt(L"X", dm->x); + doorTag->putInt(L"Y", dm->y); + doorTag->putInt(L"Z", dm->z); + doorTag->putInt(L"IDX", dm->insideDx); + doorTag->putInt(L"IDZ", dm->insideDz); + doorTag->putInt(L"TS", dm->timeStamp); + doorTags->add(doorTag); + } + tag->put(L"Doors", doorTags); + + ListTag* playerTags = new ListTag(L"Players"); + // for (String player : playerStanding.keySet()) + for (AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); + ++it) { + std::wstring player = it->first; + CompoundTag* playerTag = new CompoundTag(player); + playerTag->putString(L"Name", player); + playerTag->putInt(L"S", it->second); + playerTags->add(playerTag); + } + tag->put(L"Players", playerTags); } -int Village::getStanding(const std::wstring &playerName) -{ - AUTO_VAR(it,playerStanding.find(playerName)); - if (it != playerStanding.end()) - { - return it->second; - } - return 0; +void Village::resetNoBreedTimer() { noBreedTimer = _tick; } + +bool Village::isBreedTimerOk() { + // prevent new villagers if a villager was killed by a mob within 3 + // minutes + return noBreedTimer == 0 || + (_tick - noBreedTimer) >= + (SharedConstants::TICKS_PER_SECOND * 60 * 3); } -int Village::modifyStanding(const std::wstring &playerName, int delta) -{ - int current = getStanding(playerName); - int newValue = Mth::clamp(current + delta, -30, 10); - playerStanding.insert(std::pair(playerName, newValue)); - return newValue; -} - -bool Village::isGoodStanding(const std::wstring &playerName) -{ - return getStanding(playerName) >= 0; -} - -bool Village::isBadStanding(const std::wstring &playerName) -{ - return getStanding(playerName) <= -5; -} - -bool Village::isVeryBadStanding(const std::wstring playerName) -{ - return getStanding(playerName) <= -15; -} - -void Village::readAdditionalSaveData(CompoundTag *tag) -{ - populationSize = tag->getInt(L"PopSize"); - radius = tag->getInt(L"Radius"); - golemCount = tag->getInt(L"Golems"); - stableSince = tag->getInt(L"Stable"); - _tick = tag->getInt(L"Tick"); - noBreedTimer = tag->getInt(L"MTick"); - center->x = tag->getInt(L"CX"); - center->y = tag->getInt(L"CY"); - center->z = tag->getInt(L"CZ"); - accCenter->x = tag->getInt(L"ACX"); - accCenter->y = tag->getInt(L"ACY"); - accCenter->z = tag->getInt(L"ACZ"); - - ListTag *doorTags = (ListTag *) tag->getList(L"Doors"); - for (int i = 0; i < doorTags->size(); i++) - { - CompoundTag *dTag = doorTags->get(i); - - std::shared_ptr door = std::shared_ptr(new DoorInfo(dTag->getInt(L"X"), dTag->getInt(L"Y"), dTag->getInt(L"Z"), dTag->getInt(L"IDX"), dTag->getInt(L"IDZ"), dTag->getInt(L"TS"))); - doorInfos.push_back(door); - } - - ListTag *playerTags = (ListTag *) tag->getList(L"Players"); - for (int i = 0; i < playerTags->size(); i++) - { - CompoundTag *pTag = playerTags->get(i); - playerStanding.insert(std::pair(pTag->getString(L"Name"), pTag->getInt(L"S"))); - } -} - -void Village::addAdditonalSaveData(CompoundTag *tag) -{ - tag->putInt(L"PopSize", populationSize); - tag->putInt(L"Radius", radius); - tag->putInt(L"Golems", golemCount); - tag->putInt(L"Stable", stableSince); - tag->putInt(L"Tick", _tick); - tag->putInt(L"MTick", noBreedTimer); - tag->putInt(L"CX", center->x); - tag->putInt(L"CY", center->y); - tag->putInt(L"CZ", center->z); - tag->putInt(L"ACX", accCenter->x); - tag->putInt(L"ACY", accCenter->y); - tag->putInt(L"ACZ", accCenter->z); - - ListTag *doorTags = new ListTag(L"Doors"); - //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it,doorInfos.begin()); it != doorInfos.end(); ++it) - { - std::shared_ptr dm = *it; - CompoundTag *doorTag = new CompoundTag(L"Door"); - doorTag->putInt(L"X", dm->x); - doorTag->putInt(L"Y", dm->y); - doorTag->putInt(L"Z", dm->z); - doorTag->putInt(L"IDX", dm->insideDx); - doorTag->putInt(L"IDZ", dm->insideDz); - doorTag->putInt(L"TS", dm->timeStamp); - doorTags->add(doorTag); - } - tag->put(L"Doors", doorTags); - - ListTag *playerTags = new ListTag(L"Players"); - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) - { - std::wstring player = it->first; - CompoundTag *playerTag = new CompoundTag(player); - playerTag->putString(L"Name", player); - playerTag->putInt(L"S", it->second); - playerTags->add(playerTag); - } - tag->put(L"Players", playerTags); - -} - -void Village::resetNoBreedTimer() -{ - noBreedTimer = _tick; -} - -bool Village::isBreedTimerOk() -{ - // prevent new villagers if a villager was killed by a mob within 3 - // minutes - return noBreedTimer == 0 || (_tick - noBreedTimer) >= (SharedConstants::TICKS_PER_SECOND * 60 * 3); -} - -void Village::rewardAllPlayers(int amount) -{ - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) - { - modifyStanding(it->first, amount); - } +void Village::rewardAllPlayers(int amount) { + // for (String player : playerStanding.keySet()) + for (AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); + ++it) { + modifyStanding(it->first, amount); + } } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/Village.h b/Minecraft.World/WorldGen/Structures/Village.h index 664d6d404..697afaed4 100644 --- a/Minecraft.World/WorldGen/Structures/Village.h +++ b/Minecraft.World/WorldGen/Structures/Village.h @@ -1,81 +1,81 @@ #pragma once -class Village -{ +class Village { private: - Level *level; - std::vector > doorInfos; + Level* level; + std::vector > doorInfos; - Pos *accCenter; - Pos *center; - int radius; - int stableSince; - int _tick; - int populationSize; - int noBreedTimer; + Pos* accCenter; + Pos* center; + int radius; + int stableSince; + int _tick; + int populationSize; + int noBreedTimer; - std::unordered_map playerStanding; + std::unordered_map playerStanding; - class Aggressor - { - public: - std::shared_ptr mob; - int timeStamp; + class Aggressor { + public: + std::shared_ptr mob; + int timeStamp; - Aggressor(std::shared_ptr mob, int timeStamp); - }; + Aggressor(std::shared_ptr mob, int timeStamp); + }; - std::vector aggressors; - int golemCount; + std::vector aggressors; + int golemCount; public: - Village(); - Village(Level *level); - ~Village(); + Village(); + Village(Level* level); + ~Village(); - void setLevel(Level *level); + void setLevel(Level* level); - void tick(int tick); + void tick(int tick); private: - Vec3 *findRandomSpawnPos(int x, int y, int z, int sx, int sy, int sz); - bool canSpawnAt(int x, int y, int z, int sx, int sy, int sz); - void countGolem(); - void countPopulation(); + Vec3* findRandomSpawnPos(int x, int y, int z, int sx, int sy, int sz); + bool canSpawnAt(int x, int y, int z, int sx, int sy, int sz); + void countGolem(); + void countPopulation(); public: - Pos *getCenter(); - int getRadius(); - int getDoorCount(); - int getStableAge(); - int getPopulationSize(); - bool isInside(int xx, int yy, int zz); - std::vector > *getDoorInfos(); - std::shared_ptr getClosestDoorInfo(int x, int y, int z); - std::shared_ptr getBestDoorInfo(int x, int y, int z); - bool hasDoorInfo(int x, int y, int z); - std::shared_ptr getDoorInfo(int x, int y, int z); - void addDoorInfo(std::shared_ptr di); - bool canRemove(); - void addAggressor(std::shared_ptr mob); - std::shared_ptr getClosestAggressor(std::shared_ptr from); - std::shared_ptr getClosestBadStandingPlayer(std::shared_ptr from); // 4J Stu - Should be LivingEntity when we add that + Pos* getCenter(); + int getRadius(); + int getDoorCount(); + int getStableAge(); + int getPopulationSize(); + bool isInside(int xx, int yy, int zz); + std::vector >* getDoorInfos(); + std::shared_ptr getClosestDoorInfo(int x, int y, int z); + std::shared_ptr getBestDoorInfo(int x, int y, int z); + bool hasDoorInfo(int x, int y, int z); + std::shared_ptr getDoorInfo(int x, int y, int z); + void addDoorInfo(std::shared_ptr di); + bool canRemove(); + void addAggressor(std::shared_ptr mob); + std::shared_ptr getClosestAggressor(std::shared_ptr from); + std::shared_ptr getClosestBadStandingPlayer( + std::shared_ptr + from); // 4J Stu - Should be LivingEntity when we add that private: - void updateAggressors(); - void updateDoors(); - bool isDoor(int x, int y, int z); - void calcInfo(); + void updateAggressors(); + void updateDoors(); + bool isDoor(int x, int y, int z); + void calcInfo(); public: - int getStanding(const std::wstring &playerName); - int modifyStanding(const std::wstring &playerName, int delta); - bool isGoodStanding(const std::wstring &playerName); - bool isBadStanding(const std::wstring &playerName); - bool isVeryBadStanding(const std::wstring playerName); - void readAdditionalSaveData(CompoundTag *tag); - void addAdditonalSaveData(CompoundTag *tag); - void resetNoBreedTimer(); - bool isBreedTimerOk(); - void rewardAllPlayers(int amount); + int getStanding(const std::wstring& playerName); + int modifyStanding(const std::wstring& playerName, int delta); + bool isGoodStanding(const std::wstring& playerName); + bool isBadStanding(const std::wstring& playerName); + bool isVeryBadStanding(const std::wstring playerName); + void readAdditionalSaveData(CompoundTag* tag); + void addAdditonalSaveData(CompoundTag* tag); + void resetNoBreedTimer(); + bool isBreedTimerOk(); + void rewardAllPlayers(int amount); }; \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/VillagePieces.cpp b/Minecraft.World/WorldGen/Structures/VillagePieces.cpp index ae8bf9295..b6bbdf711 100644 --- a/Minecraft.World/WorldGen/Structures/VillagePieces.cpp +++ b/Minecraft.World/WorldGen/Structures/VillagePieces.cpp @@ -16,1832 +16,1996 @@ WeighedTreasureArray VillagePieces::Smithy::treasureItems; -VillagePieces::PieceWeight::PieceWeight(VillagePieces::EPieceClass pieceClass, int weight, int maxPlaceCount) : weight(weight) -{ - this->placeCount = 0; // 4J added initialiser - this->pieceClass = pieceClass; - this->maxPlaceCount = maxPlaceCount; +VillagePieces::PieceWeight::PieceWeight(VillagePieces::EPieceClass pieceClass, + int weight, int maxPlaceCount) + : weight(weight) { + this->placeCount = 0; // 4J added initialiser + this->pieceClass = pieceClass; + this->maxPlaceCount = maxPlaceCount; } -bool VillagePieces::PieceWeight::doPlace(int depth) -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool VillagePieces::PieceWeight::doPlace(int depth) { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -bool VillagePieces::PieceWeight::isValid() -{ - return maxPlaceCount == 0 || placeCount < maxPlaceCount; +bool VillagePieces::PieceWeight::isValid() { + return maxPlaceCount == 0 || placeCount < maxPlaceCount; } -std::list *VillagePieces::createPieceSet(Random *random, int villageSize) -{ - std::list *newPieces = new std::list; +std::list* VillagePieces::createPieceSet( + Random* random, int villageSize) { + std::list* newPieces = new std::list; - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_SimpleHouse, 4, Mth::nextInt(random, 2 + villageSize, 4 + villageSize * 2))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_SmallTemple, 20, Mth::nextInt(random, 0 + villageSize, 1 + villageSize))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_BookHouse, 20, Mth::nextInt(random, 0 + villageSize, 2 + villageSize))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_SmallHut, 3, Mth::nextInt(random, 2 + villageSize, 5 + villageSize * 3))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_PigHouse, 15, Mth::nextInt(random, 0 + villageSize, 2 + villageSize))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_DoubleFarmland, 3, Mth::nextInt(random, 1 + villageSize, 4 + villageSize))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_Farmland, 3, Mth::nextInt(random, 2 + villageSize, 4 + villageSize * 2))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_Smithy, 15, Mth::nextInt(random, 0, 1 + villageSize))); - newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_TwoRoomHouse, 8, Mth::nextInt(random, 0 + villageSize, 3 + villageSize * 2))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_SimpleHouse, 4, + Mth::nextInt(random, 2 + villageSize, 4 + villageSize * 2))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_SmallTemple, 20, + Mth::nextInt(random, 0 + villageSize, 1 + villageSize))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_BookHouse, 20, + Mth::nextInt(random, 0 + villageSize, 2 + villageSize))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_SmallHut, 3, + Mth::nextInt(random, 2 + villageSize, 5 + villageSize * 3))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_PigHouse, 15, + Mth::nextInt(random, 0 + villageSize, 2 + villageSize))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_DoubleFarmland, 3, + Mth::nextInt(random, 1 + villageSize, 4 + villageSize))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_Farmland, 3, + Mth::nextInt(random, 2 + villageSize, 4 + villageSize * 2))); + newPieces->push_back( + new PieceWeight(VillagePieces::EPieceClass_Smithy, 15, + Mth::nextInt(random, 0, 1 + villageSize))); + newPieces->push_back(new PieceWeight( + VillagePieces::EPieceClass_TwoRoomHouse, 8, + Mth::nextInt(random, 0 + villageSize, 3 + villageSize * 2))); - // silly way of filtering "infinite" buildings - AUTO_VAR(it, newPieces->begin()); - while( it != newPieces->end() ) - { - if( (*it)->maxPlaceCount == 0 ) - { - delete (*it); - it = newPieces->erase(it); - } - else - { - it++; - } - } + // silly way of filtering "infinite" buildings + AUTO_VAR(it, newPieces->begin()); + while (it != newPieces->end()) { + if ((*it)->maxPlaceCount == 0) { + delete (*it); + it = newPieces->erase(it); + } else { + it++; + } + } - return newPieces; + return newPieces; } -int VillagePieces::updatePieceWeight(std::list *currentPieces) -{ - bool hasAnyPieces = false; - int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) - { - PieceWeight *piece = *it; - if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) - { - hasAnyPieces = true; - } - totalWeight += piece->weight; - } - return (hasAnyPieces ? totalWeight : -1); +int VillagePieces::updatePieceWeight(std::list* currentPieces) { + bool hasAnyPieces = false; + int totalWeight = 0; + for (AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); + it++) { + PieceWeight* piece = *it; + if (piece->maxPlaceCount > 0 && + piece->placeCount < piece->maxPlaceCount) { + hasAnyPieces = true; + } + totalWeight += piece->weight; + } + return (hasAnyPieces ? totalWeight : -1); } -VillagePieces::VillagePiece *VillagePieces::findAndCreatePieceFactory(StartPiece *startPiece, VillagePieces::PieceWeight *piece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - VillagePieces::EPieceClass pieceClass = piece->pieceClass; - VillagePiece *villagePiece = NULL; +VillagePieces::VillagePiece* VillagePieces::findAndCreatePieceFactory( + StartPiece* startPiece, VillagePieces::PieceWeight* piece, + std::list* pieces, Random* random, int footX, int footY, + int footZ, int direction, int depth) { + VillagePieces::EPieceClass pieceClass = piece->pieceClass; + VillagePiece* villagePiece = NULL; - if (pieceClass == VillagePieces::EPieceClass_SimpleHouse) - { - villagePiece = SimpleHouse::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_SmallTemple) - { - villagePiece = SmallTemple::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_BookHouse) - { - villagePiece = BookHouse::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_SmallHut) - { - villagePiece = SmallHut::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_PigHouse) - { - villagePiece = PigHouse::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_DoubleFarmland) - { - villagePiece = DoubleFarmland::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_Farmland) - { - villagePiece = Farmland::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_Smithy) - { - villagePiece = Smithy::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } - else if (pieceClass == VillagePieces::EPieceClass_TwoRoomHouse) - { - villagePiece = TwoRoomHouse::createPiece(startPiece, pieces, random, footX, footY, footZ, direction, depth); - } + if (pieceClass == VillagePieces::EPieceClass_SimpleHouse) { + villagePiece = SimpleHouse::createPiece( + startPiece, pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_SmallTemple) { + villagePiece = SmallTemple::createPiece( + startPiece, pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_BookHouse) { + villagePiece = BookHouse::createPiece(startPiece, pieces, random, footX, + footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_SmallHut) { + villagePiece = SmallHut::createPiece(startPiece, pieces, random, footX, + footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_PigHouse) { + villagePiece = PigHouse::createPiece(startPiece, pieces, random, footX, + footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_DoubleFarmland) { + villagePiece = DoubleFarmland::createPiece( + startPiece, pieces, random, footX, footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_Farmland) { + villagePiece = Farmland::createPiece(startPiece, pieces, random, footX, + footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_Smithy) { + villagePiece = Smithy::createPiece(startPiece, pieces, random, footX, + footY, footZ, direction, depth); + } else if (pieceClass == VillagePieces::EPieceClass_TwoRoomHouse) { + villagePiece = TwoRoomHouse::createPiece( + startPiece, pieces, random, footX, footY, footZ, direction, depth); + } - return villagePiece; + return villagePiece; } -VillagePieces::VillagePiece *VillagePieces::generatePieceFromSmallDoor(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - int totalWeight = updatePieceWeight(startPiece->pieceSet); - if (totalWeight <= 0) - { - return NULL; - } +VillagePieces::VillagePiece* VillagePieces::generatePieceFromSmallDoor( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + int totalWeight = updatePieceWeight(startPiece->pieceSet); + if (totalWeight <= 0) { + return NULL; + } - int numAttempts = 0; - while (numAttempts < 5) - { - numAttempts++; + int numAttempts = 0; + while (numAttempts < 5) { + numAttempts++; - int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, startPiece->pieceSet->begin()); it != startPiece->pieceSet->end(); it++ ) - { - PieceWeight *piece = *it; - weightSelection -= piece->weight; - if (weightSelection < 0) - { + int weightSelection = random->nextInt(totalWeight); + for (AUTO_VAR(it, startPiece->pieceSet->begin()); + it != startPiece->pieceSet->end(); it++) { + PieceWeight* piece = *it; + weightSelection -= piece->weight; + if (weightSelection < 0) { + if (!piece->doPlace(depth) || + (piece == startPiece->previousPiece && + startPiece->pieceSet->size() > 1)) { + break; + } - if (!piece->doPlace(depth) || (piece == startPiece->previousPiece && startPiece->pieceSet->size() > 1)) - { - break; - } + VillagePiece* villagePiece = findAndCreatePieceFactory( + startPiece, piece, pieces, random, footX, footY, footZ, + direction, depth); + if (villagePiece != NULL) { + piece->placeCount++; + startPiece->previousPiece = piece; - VillagePiece *villagePiece = findAndCreatePieceFactory(startPiece, piece, pieces, random, footX, footY, footZ, direction, depth); - if (villagePiece != NULL) - { - piece->placeCount++; - startPiece->previousPiece = piece; + if (!piece->isValid()) { + startPiece->pieceSet->remove(piece); + } + return villagePiece; + } + } + } + } - if (!piece->isValid()) - { - startPiece->pieceSet->remove(piece); - } - return villagePiece; - } - } - } - } + // attempt to place a light post instead + { + BoundingBox* box = LightPost::findPieceBox( + startPiece, pieces, random, footX, footY, footZ, direction); + if (box != NULL) { + return new LightPost(startPiece, depth, random, box, direction); + } + delete box; + } - // attempt to place a light post instead - { - BoundingBox *box = LightPost::findPieceBox(startPiece, pieces, random, footX, footY, footZ, direction); - if (box != NULL) - { - return new LightPost(startPiece, depth, random, box, direction); - } - delete box; - } - - return NULL; + return NULL; } -StructurePiece *VillagePieces::generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - if (depth > MAX_DEPTH) - { - return NULL; - } - if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) - { - return NULL; - } +StructurePiece* VillagePieces::generateAndAddPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + if (depth > MAX_DEPTH) { + return NULL; + } + if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || + abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) { + return NULL; + } - StructurePiece *newPiece = generatePieceFromSmallDoor(startPiece, pieces, random, footX, footY, footZ, direction, depth + 1); - if (newPiece != NULL) - { - int x = (newPiece->boundingBox->x0 + newPiece->boundingBox->x1) / 2; - int z = (newPiece->boundingBox->z0 + newPiece->boundingBox->z1) / 2; - int xs = newPiece->boundingBox->x1 - newPiece->boundingBox->x0; - int zs = newPiece->boundingBox->z1 - newPiece->boundingBox->z0; - int r = xs > zs ? xs : zs; - if (startPiece->getBiomeSource()->containsOnly(x, z, r / 2 + 4, VillageFeature::allowedBiomes)) - { - pieces->push_back(newPiece); - startPiece->pendingHouses.push_back(newPiece); - return newPiece; - } - delete newPiece; - } - return NULL; + StructurePiece* newPiece = generatePieceFromSmallDoor( + startPiece, pieces, random, footX, footY, footZ, direction, depth + 1); + if (newPiece != NULL) { + int x = (newPiece->boundingBox->x0 + newPiece->boundingBox->x1) / 2; + int z = (newPiece->boundingBox->z0 + newPiece->boundingBox->z1) / 2; + int xs = newPiece->boundingBox->x1 - newPiece->boundingBox->x0; + int zs = newPiece->boundingBox->z1 - newPiece->boundingBox->z0; + int r = xs > zs ? xs : zs; + if (startPiece->getBiomeSource()->containsOnly( + x, z, r / 2 + 4, VillageFeature::allowedBiomes)) { + pieces->push_back(newPiece); + startPiece->pendingHouses.push_back(newPiece); + return newPiece; + } + delete newPiece; + } + return NULL; } -StructurePiece *VillagePieces::generateAndAddRoadPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth) -{ - if (depth > BASE_ROAD_DEPTH + startPiece->villageSize) - { - return NULL; - } - if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) - { - return NULL; - } +StructurePiece* VillagePieces::generateAndAddRoadPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int depth) { + if (depth > BASE_ROAD_DEPTH + startPiece->villageSize) { + return NULL; + } + if (abs(footX - startPiece->getBoundingBox()->x0) > 7 * 16 || + abs(footZ - startPiece->getBoundingBox()->z0) > 7 * 16) { + return NULL; + } - BoundingBox *box = StraightRoad::findPieceBox(startPiece, pieces, random, footX, footY, footZ, direction); - if (box != NULL && box->y0 > LOWEST_Y_POSITION) - { - StructurePiece *newPiece = new StraightRoad(startPiece, depth, random, box, direction); - int x = (newPiece->boundingBox->x0 + newPiece->boundingBox->x1) / 2; - int z = (newPiece->boundingBox->z0 + newPiece->boundingBox->z1) / 2; - int xs = newPiece->boundingBox->x1 - newPiece->boundingBox->x0; - int zs = newPiece->boundingBox->z1 - newPiece->boundingBox->z0; - int r = xs > zs ? xs : zs; - if (startPiece->getBiomeSource()->containsOnly(x, z, r / 2 + 4, VillageFeature::allowedBiomes)) - { - pieces->push_back(newPiece); - startPiece->pendingRoads.push_back(newPiece); - return newPiece; - } - // 4J Stu - The dtor for newPiece will destroy box - delete newPiece; - } - else if(box != NULL) - { - delete box; - } + BoundingBox* box = StraightRoad::findPieceBox( + startPiece, pieces, random, footX, footY, footZ, direction); + if (box != NULL && box->y0 > LOWEST_Y_POSITION) { + StructurePiece* newPiece = + new StraightRoad(startPiece, depth, random, box, direction); + int x = (newPiece->boundingBox->x0 + newPiece->boundingBox->x1) / 2; + int z = (newPiece->boundingBox->z0 + newPiece->boundingBox->z1) / 2; + int xs = newPiece->boundingBox->x1 - newPiece->boundingBox->x0; + int zs = newPiece->boundingBox->z1 - newPiece->boundingBox->z0; + int r = xs > zs ? xs : zs; + if (startPiece->getBiomeSource()->containsOnly( + x, z, r / 2 + 4, VillageFeature::allowedBiomes)) { + pieces->push_back(newPiece); + startPiece->pendingRoads.push_back(newPiece); + return newPiece; + } + // 4J Stu - The dtor for newPiece will destroy box + delete newPiece; + } else if (box != NULL) { + delete box; + } - return NULL; + return NULL; } -VillagePieces::VillagePiece::VillagePiece(StartPiece *startPiece, int genDepth) : StructurePiece(genDepth) -{ - spawnedVillagerCount = 0; - this->startPiece = startPiece; +VillagePieces::VillagePiece::VillagePiece(StartPiece* startPiece, int genDepth) + : StructurePiece(genDepth) { + spawnedVillagerCount = 0; + this->startPiece = startPiece; } -StructurePiece *VillagePieces::VillagePiece::generateHouseNorthernLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth()); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, getGenDepth()); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - } - return NULL; +StructurePiece* VillagePieces::VillagePiece::generateHouseNorthernLeft( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth()); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 - 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::WEST, + getGenDepth()); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + } + return NULL; } -StructurePiece *VillagePieces::VillagePiece::generateHouseNorthernRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff) -{ - switch (orientation) - { - case Direction::NORTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth()); - case Direction::SOUTH: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, getGenDepth()); - case Direction::WEST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - case Direction::EAST: - return generateAndAddPiece(startPiece, pieces, random, boundingBox->x0 + zOff, boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - } - return NULL; +StructurePiece* VillagePieces::VillagePiece::generateHouseNorthernRight( + StartPiece* startPiece, std::list* pieces, Random* random, + int yOff, int zOff) { + switch (orientation) { + case Direction::NORTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth()); + case Direction::SOUTH: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x1 + 1, + boundingBox->y0 + yOff, boundingBox->z0 + zOff, Direction::EAST, + getGenDepth()); + case Direction::WEST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); + case Direction::EAST: + return generateAndAddPiece( + startPiece, pieces, random, boundingBox->x0 + zOff, + boundingBox->y0 + yOff, boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); + } + return NULL; } -int VillagePieces::VillagePiece::getAverageGroundHeight(Level *level, BoundingBox *chunkBB) -{ - int total = 0; - int count = 0; - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) - { - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) - { - if (chunkBB->isInside(x, 64, z)) - { - total += Math::_max(level->getTopSolidBlock(x, z), level->dimension->getSpawnYPosition()); - count++; - } - } - } +int VillagePieces::VillagePiece::getAverageGroundHeight(Level* level, + BoundingBox* chunkBB) { + int total = 0; + int count = 0; + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { + if (chunkBB->isInside(x, 64, z)) { + total += Math::_max(level->getTopSolidBlock(x, z), + level->dimension->getSpawnYPosition()); + count++; + } + } + } - if (count == 0) - { - return -1; - } - return total / count; + if (count == 0) { + return -1; + } + return total / count; } -bool VillagePieces::VillagePiece::isOkBox(BoundingBox *box, StartPiece *startRoom) -{ - bool bIsOk = false; +bool VillagePieces::VillagePiece::isOkBox(BoundingBox* box, + StartPiece* startRoom) { + bool bIsOk = false; - if(box != NULL) - { - if( box->y0 > LOWEST_Y_POSITION ) bIsOk = true; + if (box != NULL) { + if (box->y0 > LOWEST_Y_POSITION) bIsOk = true; - int xzSize = startRoom->m_level->getLevelData()->getXZSize(); - int blockMin = -( (xzSize << 4) / 2) + 1; - int blockMax = ( (xzSize << 4) / 2 ) - 1; + int xzSize = startRoom->m_level->getLevelData()->getXZSize(); + int blockMin = -((xzSize << 4) / 2) + 1; + int blockMax = ((xzSize << 4) / 2) - 1; - if(box->x0 <= blockMin) bIsOk = false; - if(box->z0 <= blockMin) bIsOk = false; - if(box->x1 >= blockMax) bIsOk = false; - if(box->z1 >= blockMax) bIsOk = false; - } + if (box->x0 <= blockMin) bIsOk = false; + if (box->z0 <= blockMin) bIsOk = false; + if (box->x1 >= blockMax) bIsOk = false; + if (box->z1 >= blockMax) bIsOk = false; + } - return bIsOk; + return bIsOk; } -void VillagePieces::VillagePiece::spawnVillagers(Level *level, BoundingBox *chunkBB, int x, int y, int z, int count) -{ - if (spawnedVillagerCount >= count) - { - return; - } +void VillagePieces::VillagePiece::spawnVillagers(Level* level, + BoundingBox* chunkBB, int x, + int y, int z, int count) { + if (spawnedVillagerCount >= count) { + return; + } - for (int i = spawnedVillagerCount; i < count; i++) - { - int worldX = getWorldX(x + i, z); - int worldY = getWorldY(y); - int worldZ = getWorldZ(x + i, z); + for (int i = spawnedVillagerCount; i < count; i++) { + int worldX = getWorldX(x + i, z); + int worldY = getWorldY(y); + int worldZ = getWorldZ(x + i, z); - if (chunkBB->isInside(worldX, worldY, worldZ)) - { - spawnedVillagerCount++; + if (chunkBB->isInside(worldX, worldY, worldZ)) { + spawnedVillagerCount++; - std::shared_ptr villager = std::shared_ptr(new Villager(level, getVillagerProfession(i))); - villager->moveTo(worldX + 0.5, worldY, worldZ + 0.5, 0, 0); - level->addEntity(villager); - } - else - { - // try again later - break; - } - } + std::shared_ptr villager = std::shared_ptr( + new Villager(level, getVillagerProfession(i))); + villager->moveTo(worldX + 0.5, worldY, worldZ + 0.5, 0, 0); + level->addEntity(villager); + } else { + // try again later + break; + } + } } -int VillagePieces::VillagePiece::getVillagerProfession(int villagerNumber) -{ - return Villager::PROFESSION_FARMER; +int VillagePieces::VillagePiece::getVillagerProfession(int villagerNumber) { + return Villager::PROFESSION_FARMER; } -int VillagePieces::VillagePiece::biomeBlock(int tile, int data) -{ - if (startPiece->isDesertVillage) - { - if (tile == Tile::treeTrunk_Id) - { - return Tile::sandStone_Id; - } - else if (tile == Tile::stoneBrick_Id) - { - return Tile::sandStone_Id; - } - else if (tile == Tile::wood_Id) - { - return Tile::sandStone_Id; - } - else if (tile == Tile::stairs_wood_Id) - { - return Tile::stairs_sandstone_Id; - } - else if (tile == Tile::stairs_stone_Id) - { - return Tile::stairs_sandstone_Id; - } - else if (tile == Tile::gravel_Id) - { - return Tile::sandStone_Id; - } - } - return tile; +int VillagePieces::VillagePiece::biomeBlock(int tile, int data) { + if (startPiece->isDesertVillage) { + if (tile == Tile::treeTrunk_Id) { + return Tile::sandStone_Id; + } else if (tile == Tile::stoneBrick_Id) { + return Tile::sandStone_Id; + } else if (tile == Tile::wood_Id) { + return Tile::sandStone_Id; + } else if (tile == Tile::stairs_wood_Id) { + return Tile::stairs_sandstone_Id; + } else if (tile == Tile::stairs_stone_Id) { + return Tile::stairs_sandstone_Id; + } else if (tile == Tile::gravel_Id) { + return Tile::sandStone_Id; + } + } + return tile; } -int VillagePieces::VillagePiece::biomeData(int tile, int data) -{ - if (startPiece->isDesertVillage) - { - if (tile == Tile::treeTrunk_Id) - { - return 0; - } - else if (tile == Tile::stoneBrick_Id) - { - return SandStoneTile::TYPE_DEFAULT; - } - else if (tile == Tile::wood_Id) - { - return SandStoneTile::TYPE_SMOOTHSIDE; - } - } - return data; +int VillagePieces::VillagePiece::biomeData(int tile, int data) { + if (startPiece->isDesertVillage) { + if (tile == Tile::treeTrunk_Id) { + return 0; + } else if (tile == Tile::stoneBrick_Id) { + return SandStoneTile::TYPE_DEFAULT; + } else if (tile == Tile::wood_Id) { + return SandStoneTile::TYPE_SMOOTHSIDE; + } + } + return data; } -void VillagePieces::VillagePiece::placeBlock(Level *level, int block, int data, int x, int y, int z, BoundingBox *chunkBB) -{ - int bblock = biomeBlock(block, data); - int bdata = biomeData(block, data); - StructurePiece::placeBlock(level, bblock, bdata, x, y, z, chunkBB); +void VillagePieces::VillagePiece::placeBlock(Level* level, int block, int data, + int x, int y, int z, + BoundingBox* chunkBB) { + int bblock = biomeBlock(block, data); + int bdata = biomeData(block, data); + StructurePiece::placeBlock(level, bblock, bdata, x, y, z, chunkBB); } -void VillagePieces::VillagePiece::generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int fillTile, bool skipAir) -{ - int bEdge = biomeBlock(edgeTile, 0); - int bEdgeData = biomeData(edgeTile, 0); - int bFill = biomeBlock(fillTile, 0); - int bFillData = biomeData(fillTile, 0); - StructurePiece::generateBox(level, chunkBB, x0, y0, z0, x1, y1, z1, bEdge, bEdgeData, bFill, bFillData, skipAir); +void VillagePieces::VillagePiece::generateBox(Level* level, + BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, + int z1, int edgeTile, + int fillTile, bool skipAir) { + int bEdge = biomeBlock(edgeTile, 0); + int bEdgeData = biomeData(edgeTile, 0); + int bFill = biomeBlock(fillTile, 0); + int bFillData = biomeData(fillTile, 0); + StructurePiece::generateBox(level, chunkBB, x0, y0, z0, x1, y1, z1, bEdge, + bEdgeData, bFill, bFillData, skipAir); } -void VillagePieces::VillagePiece::fillColumnDown(Level *level, int block, int data, int x, int startY, int z, BoundingBox *chunkBB) -{ - int bblock = biomeBlock(block, data); - int bdata = biomeData(block, data); - StructurePiece::fillColumnDown(level, bblock, bdata, x, startY, z, chunkBB); +void VillagePieces::VillagePiece::fillColumnDown(Level* level, int block, + int data, int x, int startY, + int z, BoundingBox* chunkBB) { + int bblock = biomeBlock(block, data); + int bdata = biomeData(block, data); + StructurePiece::fillColumnDown(level, bblock, bdata, x, startY, z, chunkBB); } -VillagePieces::Well::Well(StartPiece *startPiece, int genDepth, Random *random, int west, int north) : VillagePiece(startPiece, genDepth), isSource(true) -{ - heightPosition = -1; // 4J added initialiser - orientation = random->nextInt(4); +VillagePieces::Well::Well(StartPiece* startPiece, int genDepth, Random* random, + int west, int north) + : VillagePiece(startPiece, genDepth), isSource(true) { + heightPosition = -1; // 4J added initialiser + orientation = random->nextInt(4); - switch (orientation) - { - case Direction::NORTH: - case Direction::SOUTH: - boundingBox = new BoundingBox(west, 64, north, west + width - 1, 64 + height - 1, north + depth - 1); - break; - default: - boundingBox = new BoundingBox(west, 64, north, west + depth - 1, 64 + height - 1, north + width - 1); - break; - } + switch (orientation) { + case Direction::NORTH: + case Direction::SOUTH: + boundingBox = new BoundingBox(west, 64, north, west + width - 1, + 64 + height - 1, north + depth - 1); + break; + default: + boundingBox = new BoundingBox(west, 64, north, west + depth - 1, + 64 + height - 1, north + width - 1); + break; + } } -VillagePieces::Well::Well(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth), isSource(false) -{ - heightPosition = -1; // 4J added initialiser +VillagePieces::Well::Well(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction) + : VillagePiece(startPiece, genDepth), isSource(false) { + heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; + orientation = direction; + boundingBox = stairsBox; } -void VillagePieces::Well::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y1 - 4, boundingBox->z0 + 1, Direction::WEST, getGenDepth()); - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y1 - 4, boundingBox->z0 + 1, Direction::EAST, getGenDepth()); - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y1 - 4, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0 + 1, boundingBox->y1 - 4, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); +void VillagePieces::Well::addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random) { + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0 - 1, boundingBox->y1 - 4, + boundingBox->z0 + 1, Direction::WEST, + getGenDepth()); + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x1 + 1, boundingBox->y1 - 4, + boundingBox->z0 + 1, Direction::EAST, + getGenDepth()); + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0 + 1, boundingBox->y1 - 4, + boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0 + 1, boundingBox->y1 - 4, + boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); } -//VillagePieces::Well *VillagePieces::Well::createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) +// VillagePieces::Well +// *VillagePieces::Well::createPiece(std::list *pieces, Random +// *random, int footX, int footY, int footZ, int direction, int genDepth) //{ -// BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); +// BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - +// height, 0, width, height, depth, direction); // -// if (!isOkBox(box) || StructurePiece::findCollisionPiece(pieces, box) != NULL) +// if (!isOkBox(box) || StructurePiece::findCollisionPiece(pieces, box) != +// NULL) // { // delete box; -// return NULL; -// } +// return NULL; +// } // -// return new Well(genDepth, random, box, direction); -//} +// return new Well(genDepth, random, box, direction); +// } -bool VillagePieces::Well::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + 3, 0); - } +bool VillagePieces::Well::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + 3, 0); + } - generateBox(level, chunkBB, 1, 0, 1, 4, height - 3, 4, Tile::stoneBrick_Id, Tile::water_Id, false); - placeBlock(level, 0, 0, 2, height - 3, 2, chunkBB); - placeBlock(level, 0, 0, 3, height - 3, 2, chunkBB); - placeBlock(level, 0, 0, 2, height - 3, 3, chunkBB); - placeBlock(level, 0, 0, 3, height - 3, 3, chunkBB); + generateBox(level, chunkBB, 1, 0, 1, 4, height - 3, 4, Tile::stoneBrick_Id, + Tile::water_Id, false); + placeBlock(level, 0, 0, 2, height - 3, 2, chunkBB); + placeBlock(level, 0, 0, 3, height - 3, 2, chunkBB); + placeBlock(level, 0, 0, 2, height - 3, 3, chunkBB); + placeBlock(level, 0, 0, 3, height - 3, 3, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, height - 2, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, height - 1, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, height - 2, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, height - 1, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, height - 2, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, height - 1, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, height - 2, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, height - 1, 4, chunkBB); - generateBox(level, chunkBB, 1, height, 1, 4, height, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + placeBlock(level, Tile::fence_Id, 0, 1, height - 2, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, height - 1, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, height - 2, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, height - 1, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, height - 2, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, height - 1, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, height - 2, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, height - 1, 4, chunkBB); + generateBox(level, chunkBB, 1, height, 1, 4, height, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - for (int z = 0; z <= 5; z++) - { - for (int x = 0; x <= 5; x++) - { - // only do the frame - if (x != 0 && x != 5 && z != 0 && z != 5) - { - continue; - } - placeBlock(level, Tile::gravel_Id, 0, x, height - 4, z, chunkBB); - generateAirColumnUp(level, x, height - 3, z, chunkBB); - } - } - - return true; + for (int z = 0; z <= 5; z++) { + for (int x = 0; x <= 5; x++) { + // only do the frame + if (x != 0 && x != 5 && z != 0 && z != 5) { + continue; + } + placeBlock(level, Tile::gravel_Id, 0, x, height - 4, z, chunkBB); + generateAirColumnUp(level, x, height - 3, z, chunkBB); + } + } + return true; } -VillagePieces::StartPiece::StartPiece(BiomeSource *biomeSource, int genDepth, Random *random, int west, int north, std::list *pieceSet, int villageSize, Level *level) : Well(NULL, 0, random, west, north) -{ - isLibraryAdded = false; // 4J - added initialiser - previousPiece = NULL; // 4J - added initialiser - this->biomeSource = biomeSource; - this->pieceSet = pieceSet; - this->villageSize = villageSize; - m_level = level; +VillagePieces::StartPiece::StartPiece(BiomeSource* biomeSource, int genDepth, + Random* random, int west, int north, + std::list* pieceSet, + int villageSize, Level* level) + : Well(NULL, 0, random, west, north) { + isLibraryAdded = false; // 4J - added initialiser + previousPiece = NULL; // 4J - added initialiser + this->biomeSource = biomeSource; + this->pieceSet = pieceSet; + this->villageSize = villageSize; + m_level = level; - Biome *biome = biomeSource->getBiome(west, north); - this->isDesertVillage = biome == Biome::desert || biome == Biome::desertHills; - this->startPiece = this; + Biome* biome = biomeSource->getBiome(west, north); + this->isDesertVillage = + biome == Biome::desert || biome == Biome::desertHills; + this->startPiece = this; } -VillagePieces::StartPiece::~StartPiece() -{ - for(AUTO_VAR(it, pieceSet->begin()); it != pieceSet->end(); it++ ) - { - delete (*it); - } - delete pieceSet; +VillagePieces::StartPiece::~StartPiece() { + for (AUTO_VAR(it, pieceSet->begin()); it != pieceSet->end(); it++) { + delete (*it); + } + delete pieceSet; } -BiomeSource *VillagePieces::StartPiece::getBiomeSource() -{ - return biomeSource; +BiomeSource* VillagePieces::StartPiece::getBiomeSource() { return biomeSource; } + +VillagePieces::StraightRoad::StraightRoad(StartPiece* startPiece, int genDepth, + Random* random, + BoundingBox* stairsBox, int direction) + : VillageRoadPiece(startPiece, genDepth) { + orientation = direction; + boundingBox = stairsBox; + length = Math::_max(stairsBox->getXSpan(), stairsBox->getZSpan()); } -VillagePieces::StraightRoad::StraightRoad(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillageRoadPiece(startPiece, genDepth) -{ - orientation = direction; - boundingBox = stairsBox; - length = Math::_max(stairsBox->getXSpan(), stairsBox->getZSpan()); +void VillagePieces::StraightRoad::addChildren( + StructurePiece* startPiece, std::list* pieces, + Random* random) { + bool hasHouses = false; + + // place left houses + int depth = random->nextInt(5); + while (depth < length - 8) { + StructurePiece* piece = generateHouseNorthernLeft( + (StartPiece*)startPiece, pieces, random, 0, depth); + if (piece != NULL) { + depth += Math::_max(piece->boundingBox->getXSpan(), + piece->boundingBox->getZSpan()); + hasHouses = true; + } + depth += 2 + random->nextInt(5); + } + + // place right houses + depth = random->nextInt(5); + while (depth < length - 8) { + StructurePiece* piece = generateHouseNorthernRight( + (StartPiece*)startPiece, pieces, random, 0, depth); + if (piece != NULL) { + depth += Math::_max(piece->boundingBox->getXSpan(), + piece->boundingBox->getZSpan()); + hasHouses = true; + } + depth += 2 + random->nextInt(5); + } + + if (hasHouses && random->nextInt(3) > 0) { + switch (orientation) { + case Direction::NORTH: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0 - 1, boundingBox->y0, + boundingBox->z0, Direction::WEST, + getGenDepth()); + break; + case Direction::SOUTH: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0 - 1, boundingBox->y0, + boundingBox->z1 - 2, Direction::WEST, + getGenDepth()); + break; + case Direction::EAST: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x1 - 2, boundingBox->y0, + boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + break; + case Direction::WEST: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0, boundingBox->y0, + boundingBox->z0 - 1, Direction::NORTH, + getGenDepth()); + break; + } + } + if (hasHouses && random->nextInt(3) > 0) { + switch (orientation) { + case Direction::NORTH: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x1 + 1, boundingBox->y0, + boundingBox->z0, Direction::EAST, + getGenDepth()); + break; + case Direction::SOUTH: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x1 + 1, boundingBox->y0, + boundingBox->z1 - 2, Direction::EAST, + getGenDepth()); + break; + case Direction::EAST: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x1 - 2, boundingBox->y0, + boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); + break; + case Direction::WEST: + generateAndAddRoadPiece((StartPiece*)startPiece, pieces, random, + boundingBox->x0, boundingBox->y0, + boundingBox->z1 + 1, Direction::SOUTH, + getGenDepth()); + break; + } + } } -void VillagePieces::StraightRoad::addChildren(StructurePiece *startPiece, std::list *pieces, Random *random) -{ - bool hasHouses = false; +BoundingBox* VillagePieces::StraightRoad::findPieceBox( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction) { + int length = 7 * (Mth::nextInt(random, 3, 5)); - // place left houses - int depth = random->nextInt(5); - while (depth < length - 8) - { - StructurePiece *piece = generateHouseNorthernLeft((StartPiece *) startPiece, pieces, random, 0, depth); - if (piece != NULL) - { - depth += Math::_max(piece->boundingBox->getXSpan(), piece->boundingBox->getZSpan()); - hasHouses = true; - } - depth += 2 + random->nextInt(5); - } + while (length >= 7) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, 3, length, direction); - // place right houses - depth = random->nextInt(5); - while (depth < length - 8) - { - StructurePiece *piece = generateHouseNorthernRight((StartPiece *) startPiece, pieces, random, 0, depth); - if (piece != NULL) - { - depth += Math::_max(piece->boundingBox->getXSpan(), piece->boundingBox->getZSpan()); - hasHouses = true; - } - depth += 2 + random->nextInt(5); - } + if (isOkBox(box, startPiece) && + StructurePiece::findCollisionPiece(pieces, box) == NULL) { + return box; + } + delete box; + length -= 7; + } - if (hasHouses && random->nextInt(3) > 0) - { - switch (orientation) - { - case Direction::NORTH: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z0, Direction::WEST, getGenDepth()); - break; - case Direction::SOUTH: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0 - 1, boundingBox->y0, boundingBox->z1 - 2, Direction::WEST, getGenDepth()); - break; - case Direction::EAST: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 - 2, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - break; - case Direction::WEST: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z0 - 1, Direction::NORTH, getGenDepth()); - break; - } - } - if (hasHouses && random->nextInt(3) > 0) - { - switch (orientation) - { - case Direction::NORTH: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0, Direction::EAST, getGenDepth()); - break; - case Direction::SOUTH: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z1 - 2, Direction::EAST, getGenDepth()); - break; - case Direction::EAST: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 - 2, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - break; - case Direction::WEST: - generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - break; - } - } + return NULL; } -BoundingBox *VillagePieces::StraightRoad::findPieceBox(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ - int length = 7 * (Mth::nextInt(random, 3, 5)); +bool VillagePieces::StraightRoad::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + int tile = biomeBlock(Tile::gravel_Id, 0); + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { + if (chunkBB->isInside(x, 64, z)) { + int y = level->getTopSolidBlock(x, z) - 1; + level->setTileNoUpdate(x, y, z, tile); + } + } + } - while (length >= 7) - { - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, 3, length, direction); - - if (isOkBox(box, startPiece) && StructurePiece::findCollisionPiece(pieces, box) == NULL) - { - return box; - } - delete box; - length -= 7; - } - - return NULL; -} - -bool VillagePieces::StraightRoad::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - int tile = biomeBlock(Tile::gravel_Id, 0); - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) - { - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) - { - if (chunkBB->isInside(x, 64, z)) - { - int y = level->getTopSolidBlock(x, z) - 1; - level->setTileNoUpdate(x, y, z,tile); - } - } - } - - return true; + return true; } /* int heightPosition; const bool hasTerrace;*/ -VillagePieces::SimpleHouse::SimpleHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth), hasTerrace(random->nextBoolean()) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::SimpleHouse::SimpleHouse(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth), hasTerrace(random->nextBoolean()) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::SimpleHouse *VillagePieces::SimpleHouse::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::SimpleHouse* VillagePieces::SimpleHouse::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new SimpleHouse(startPiece, genDepth, random, box, direction); + return new SimpleHouse(startPiece, genDepth, random, box, direction); } -bool VillagePieces::SimpleHouse::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::SimpleHouse::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // floor - generateBox(level, chunkBB, 0, 0, 0, 4, 0, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // roof - generateBox(level, chunkBB, 0, 4, 0, 4, 4, 4, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 1, 4, 1, 3, 4, 3, Tile::wood_Id, Tile::wood_Id, false); + // floor + generateBox(level, chunkBB, 0, 0, 0, 4, 0, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // roof + generateBox(level, chunkBB, 0, 4, 0, 4, 4, 4, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 1, 4, 1, 3, 4, 3, Tile::wood_Id, Tile::wood_Id, + false); - // window walls - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 1, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 2, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 3, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 2, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 1, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 2, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 3, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 2, 4, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 4, chunkBB); - generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 4, 1, 1, 4, 3, 3, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 1, 4, 3, 3, 4, Tile::wood_Id, Tile::wood_Id, false); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 2, chunkBB); + // window walls + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 1, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 2, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 3, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 2, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 1, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 2, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 3, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 1, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 2, 4, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 3, 4, chunkBB); + generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 4, 1, 1, 4, 3, 3, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 1, 4, 3, 3, 4, Tile::wood_Id, Tile::wood_Id, + false); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 2, chunkBB); - // door wall - placeBlock(level, Tile::wood_Id, 0, 1, 1, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 1, 2, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 1, 3, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 2, 3, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 3, 3, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 3, 2, 0, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 3, 1, 0, chunkBB); - if (getBlock(level, 2, 0, -1, chunkBB) == 0 && getBlock(level, 2, -1, -1, chunkBB) != 0) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, chunkBB); - } + // door wall + placeBlock(level, Tile::wood_Id, 0, 1, 1, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 1, 2, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 1, 3, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 2, 3, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 3, 3, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 3, 2, 0, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 3, 1, 0, chunkBB); + if (getBlock(level, 2, 0, -1, chunkBB) == 0 && + getBlock(level, 2, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, + chunkBB); + } - // fill room with air - generateBox(level, chunkBB, 1, 1, 1, 3, 3, 3, 0, 0, false); + // fill room with air + generateBox(level, chunkBB, 1, 1, 1, 3, 3, 3, 0, 0, false); - // roof fence - if (hasTerrace) { - placeBlock(level, Tile::fence_Id, 0, 0, 5, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, 5, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 2, 5, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 3, 5, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 5, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 0, 5, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, 5, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 2, 5, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 3, 5, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 5, 4, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 5, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 5, 2, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 5, 3, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 0, 5, 1, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 0, 5, 2, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 0, 5, 3, chunkBB); - } + // roof fence + if (hasTerrace) { + placeBlock(level, Tile::fence_Id, 0, 0, 5, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, 5, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 2, 5, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 3, 5, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 5, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 0, 5, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, 5, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 2, 5, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 3, 5, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 5, 4, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 5, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 5, 2, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 5, 3, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 0, 5, 1, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 0, 5, 2, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 0, 5, 3, chunkBB); + } - // ladder - if (hasTerrace) - { - int orientationData = getOrientationData(Tile::ladder_Id, 3); - placeBlock(level, Tile::ladder_Id, orientationData, 3, 1, 3, chunkBB); - placeBlock(level, Tile::ladder_Id, orientationData, 3, 2, 3, chunkBB); - placeBlock(level, Tile::ladder_Id, orientationData, 3, 3, 3, chunkBB); - placeBlock(level, Tile::ladder_Id, orientationData, 3, 4, 3, chunkBB); - } + // ladder + if (hasTerrace) { + int orientationData = getOrientationData(Tile::ladder_Id, 3); + placeBlock(level, Tile::ladder_Id, orientationData, 3, 1, 3, chunkBB); + placeBlock(level, Tile::ladder_Id, orientationData, 3, 2, 3, chunkBB); + placeBlock(level, Tile::ladder_Id, orientationData, 3, 3, 3, chunkBB); + placeBlock(level, Tile::ladder_Id, orientationData, 3, 4, 3, chunkBB); + } - // torch - placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); + // torch + placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 1, 1, 2, 1); - - return true; + spawnVillagers(level, chunkBB, 1, 1, 2, 1); + return true; } -VillagePieces::SmallTemple::SmallTemple(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::SmallTemple::SmallTemple(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::SmallTemple *VillagePieces::SmallTemple::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::SmallTemple* VillagePieces::SmallTemple::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new SmallTemple(startPiece, genDepth, random, box, direction); + return new SmallTemple(startPiece, genDepth, random, box, direction); } -bool VillagePieces::SmallTemple::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::SmallTemple::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 1, 1, 1, 3, 3, 7, 0, 0, false); - generateBox(level, chunkBB, 1, 5, 1, 3, 9, 3, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 1, 1, 1, 3, 3, 7, 0, 0, false); + generateBox(level, chunkBB, 1, 5, 1, 3, 9, 3, 0, 0, false); - // floor - generateBox(level, chunkBB, 1, 0, 0, 3, 0, 8, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // floor + generateBox(level, chunkBB, 1, 0, 0, 3, 0, 8, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // front wall - generateBox(level, chunkBB, 1, 1, 0, 3, 10, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // left tall wall - generateBox(level, chunkBB, 0, 1, 1, 0, 10, 3, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // right tall wall - generateBox(level, chunkBB, 4, 1, 1, 4, 10, 3, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // left low wall - generateBox(level, chunkBB, 0, 0, 4, 0, 4, 7, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // right low wall - generateBox(level, chunkBB, 4, 0, 4, 4, 4, 7, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // far low wall - generateBox(level, chunkBB, 1, 1, 8, 3, 4, 8, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // far upper wall - generateBox(level, chunkBB, 1, 5, 4, 3, 10, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // front wall + generateBox(level, chunkBB, 1, 1, 0, 3, 10, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // left tall wall + generateBox(level, chunkBB, 0, 1, 1, 0, 10, 3, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // right tall wall + generateBox(level, chunkBB, 4, 1, 1, 4, 10, 3, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // left low wall + generateBox(level, chunkBB, 0, 0, 4, 0, 4, 7, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // right low wall + generateBox(level, chunkBB, 4, 0, 4, 4, 4, 7, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // far low wall + generateBox(level, chunkBB, 1, 1, 8, 3, 4, 8, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // far upper wall + generateBox(level, chunkBB, 1, 5, 4, 3, 10, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // low roof - generateBox(level, chunkBB, 1, 5, 5, 3, 5, 7, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // high roof - generateBox(level, chunkBB, 0, 9, 0, 4, 9, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // middle floor / roof - generateBox(level, chunkBB, 0, 4, 0, 4, 4, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - placeBlock(level, Tile::stoneBrick_Id, 0, 0, 11, 2, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 4, 11, 2, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 2, 11, 0, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 2, 11, 4, chunkBB); + // low roof + generateBox(level, chunkBB, 1, 5, 5, 3, 5, 7, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // high roof + generateBox(level, chunkBB, 0, 9, 0, 4, 9, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // middle floor / roof + generateBox(level, chunkBB, 0, 4, 0, 4, 4, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + placeBlock(level, Tile::stoneBrick_Id, 0, 0, 11, 2, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 4, 11, 2, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 2, 11, 0, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 2, 11, 4, chunkBB); - // altar pieces - placeBlock(level, Tile::stoneBrick_Id, 0, 1, 1, 6, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 1, 1, 7, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 2, 1, 7, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 3, 1, 6, chunkBB); - placeBlock(level, Tile::stoneBrick_Id, 0, 3, 1, 7, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 1, 1, 5, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 2, 1, 6, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 3, 1, 5, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 1), 1, 2, 7, chunkBB); - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 0), 3, 2, 7, chunkBB); + // altar pieces + placeBlock(level, Tile::stoneBrick_Id, 0, 1, 1, 6, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 1, 1, 7, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 2, 1, 7, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 3, 1, 6, chunkBB); + placeBlock(level, Tile::stoneBrick_Id, 0, 3, 1, 7, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 1, 1, 5, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 2, 1, 6, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 3, 1, 5, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 1), 1, 2, 7, chunkBB); + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 0), 3, 2, 7, chunkBB); - // windows - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 6, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 7, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 6, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 7, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 6, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 7, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 6, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 7, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 6, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 6, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 3, 8, chunkBB); + // windows + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 6, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 7, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 6, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 7, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 6, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 7, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 6, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 7, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 6, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 6, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 3, 8, chunkBB); - // torches - placeBlock(level, Tile::torch_Id, 0, 2, 4, 7, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 1, 4, 6, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 3, 4, 6, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 2, 4, 5, chunkBB); + // torches + placeBlock(level, Tile::torch_Id, 0, 2, 4, 7, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 1, 4, 6, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 3, 4, 6, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 2, 4, 5, chunkBB); - // ladder - int orientationData = getOrientationData(Tile::ladder_Id, 4); - for (int y = 1; y <= 9; y++) - { - placeBlock(level, Tile::ladder_Id, orientationData, 3, y, 3, chunkBB); - } + // ladder + int orientationData = getOrientationData(Tile::ladder_Id, 4); + for (int y = 1; y <= 9; y++) { + placeBlock(level, Tile::ladder_Id, orientationData, 3, y, 3, chunkBB); + } - // entrance - placeBlock(level, 0, 0, 2, 1, 0, chunkBB); - placeBlock(level, 0, 0, 2, 2, 0, chunkBB); - createDoor(level, chunkBB, random, 2, 1, 0, getOrientationData(Tile::door_wood_Id, 1)); - if (getBlock(level, 2, 0, -1, chunkBB) == 0 && getBlock(level, 2, -1, -1, chunkBB) != 0) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, chunkBB); - } + // entrance + placeBlock(level, 0, 0, 2, 1, 0, chunkBB); + placeBlock(level, 0, 0, 2, 2, 0, chunkBB); + createDoor(level, chunkBB, random, 2, 1, 0, + getOrientationData(Tile::door_wood_Id, 1)); + if (getBlock(level, 2, 0, -1, chunkBB) == 0 && + getBlock(level, 2, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, + chunkBB); + } + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } - - spawnVillagers(level, chunkBB, 2, 1, 2, 1); - - return true; + spawnVillagers(level, chunkBB, 2, 1, 2, 1); + return true; } -int VillagePieces::SmallTemple::getVillagerProfession(int villagerNumber) -{ - return Villager::PROFESSION_PRIEST; +int VillagePieces::SmallTemple::getVillagerProfession(int villagerNumber) { + return Villager::PROFESSION_PRIEST; } - -VillagePieces::BookHouse::BookHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::BookHouse::BookHouse(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::BookHouse *VillagePieces::BookHouse::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::BookHouse* VillagePieces::BookHouse::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new BookHouse(startPiece, genDepth, random, box, direction); + return new BookHouse(startPiece, genDepth, random, box, direction); } -bool VillagePieces::BookHouse::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::BookHouse::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 1, 1, 1, 7, 5, 4, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 1, 1, 1, 7, 5, 4, 0, 0, false); - // floor - generateBox(level, chunkBB, 0, 0, 0, 8, 0, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - // roof - generateBox(level, chunkBB, 0, 5, 0, 8, 5, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 0, 6, 1, 8, 6, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 0, 7, 2, 8, 7, 3, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); - int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); - for (int d = -1; d <= 2; d++) { - for (int w = 0; w <= 8; w++) { - placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 6 + d, d, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 6 + d, 5 - d, chunkBB); - } - } + // floor + generateBox(level, chunkBB, 0, 0, 0, 8, 0, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + // roof + generateBox(level, chunkBB, 0, 5, 0, 8, 5, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 0, 6, 1, 8, 6, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 0, 7, 2, 8, 7, 3, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); + int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); + for (int d = -1; d <= 2; d++) { + for (int w = 0; w <= 8; w++) { + placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 6 + d, d, + chunkBB); + placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 6 + d, + 5 - d, chunkBB); + } + } - // rock supports - generateBox(level, chunkBB, 0, 1, 0, 0, 1, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 1, 5, 8, 1, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 8, 1, 0, 8, 1, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 2, 1, 0, 7, 1, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 0, 0, 4, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 0, 2, 5, 0, 4, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 8, 2, 5, 8, 4, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 8, 2, 0, 8, 4, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // rock supports + generateBox(level, chunkBB, 0, 1, 0, 0, 1, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 1, 5, 8, 1, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 8, 1, 0, 8, 1, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 2, 1, 0, 7, 1, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 0, 0, 4, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 0, 2, 5, 0, 4, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 8, 2, 5, 8, 4, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 8, 2, 0, 8, 4, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // wooden walls - generateBox(level, chunkBB, 0, 2, 1, 0, 4, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 2, 5, 7, 4, 5, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 8, 2, 1, 8, 4, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 2, 0, 7, 4, 0, Tile::wood_Id, Tile::wood_Id, false); + // wooden walls + generateBox(level, chunkBB, 0, 2, 1, 0, 4, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 2, 5, 7, 4, 5, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 8, 2, 1, 8, 4, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 2, 0, 7, 4, 0, Tile::wood_Id, Tile::wood_Id, + false); - // windows - placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 3, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 6, 3, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 3, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 3, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 5, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 5, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 5, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 5, chunkBB); + // windows + placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 3, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 3, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 6, 3, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 3, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 3, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 3, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 5, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 5, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 5, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 5, chunkBB); - // roof inside and bookshelf - generateBox(level, chunkBB, 1, 4, 1, 7, 4, 1, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 4, 4, 7, 4, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 3, 4, 7, 3, 4, Tile::bookshelf_Id, Tile::bookshelf_Id, false); + // roof inside and bookshelf + generateBox(level, chunkBB, 1, 4, 1, 7, 4, 1, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 4, 4, 7, 4, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 3, 4, 7, 3, 4, Tile::bookshelf_Id, + Tile::bookshelf_Id, false); - // couch - placeBlock(level, Tile::wood_Id, 0, 7, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, getOrientationData(Tile::stairs_wood_Id, 0), 7, 1, 3, chunkBB); - int orientationData = getOrientationData(Tile::stairs_wood_Id, 3); - placeBlock(level, Tile::stairs_wood_Id, orientationData, 6, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, orientationData, 5, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, orientationData, 4, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, orientationData, 3, 1, 4, chunkBB); + // couch + placeBlock(level, Tile::wood_Id, 0, 7, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, + getOrientationData(Tile::stairs_wood_Id, 0), 7, 1, 3, chunkBB); + int orientationData = getOrientationData(Tile::stairs_wood_Id, 3); + placeBlock(level, Tile::stairs_wood_Id, orientationData, 6, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, orientationData, 5, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, orientationData, 4, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, orientationData, 3, 1, 4, chunkBB); - // tables - placeBlock(level, Tile::fence_Id, 0, 6, 1, 3, chunkBB); - placeBlock(level, Tile::pressurePlate_wood_Id, 0, 6, 2, 3, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 4, 1, 3, chunkBB); - placeBlock(level, Tile::pressurePlate_wood_Id, 0, 4, 2, 3, chunkBB); - placeBlock(level, Tile::workBench_Id, 0, 7, 1, 1, chunkBB); + // tables + placeBlock(level, Tile::fence_Id, 0, 6, 1, 3, chunkBB); + placeBlock(level, Tile::pressurePlate_wood_Id, 0, 6, 2, 3, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 4, 1, 3, chunkBB); + placeBlock(level, Tile::pressurePlate_wood_Id, 0, 4, 2, 3, chunkBB); + placeBlock(level, Tile::workBench_Id, 0, 7, 1, 1, chunkBB); - // entrance - placeBlock(level, 0, 0, 1, 1, 0, chunkBB); - placeBlock(level, 0, 0, 1, 2, 0, chunkBB); - createDoor(level, chunkBB, random, 1, 1, 0, getOrientationData(Tile::door_wood_Id, 1)); - if (getBlock(level, 1, 0, -1, chunkBB) == 0 && getBlock(level, 1, -1, -1, chunkBB) != 0) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 1, 0, -1, chunkBB); - } + // entrance + placeBlock(level, 0, 0, 1, 1, 0, chunkBB); + placeBlock(level, 0, 0, 1, 2, 0, chunkBB); + createDoor(level, chunkBB, random, 1, 1, 0, + getOrientationData(Tile::door_wood_Id, 1)); + if (getBlock(level, 1, 0, -1, chunkBB) == 0 && + getBlock(level, 1, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 1, 0, -1, + chunkBB); + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 2, 1, 2, 1); - - return true; + spawnVillagers(level, chunkBB, 2, 1, 2, 1); + return true; } -int VillagePieces::BookHouse::getVillagerProfession(int villagerNumber) -{ - return Villager::PROFESSION_LIBRARIAN; +int VillagePieces::BookHouse::getVillagerProfession(int villagerNumber) { + return Villager::PROFESSION_LIBRARIAN; } -VillagePieces::SmallHut::SmallHut(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth), lowCeiling(random->nextBoolean()), tablePlacement(random->nextInt(3)) -{ - heightPosition = -1; // 4J added initialiser +VillagePieces::SmallHut::SmallHut(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth), + lowCeiling(random->nextBoolean()), + tablePlacement(random->nextInt(3)) { + heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::SmallHut *VillagePieces::SmallHut::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::SmallHut* VillagePieces::SmallHut::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new SmallHut(startPiece, genDepth, random, box, direction); + return new SmallHut(startPiece, genDepth, random, box, direction); } -bool VillagePieces::SmallHut::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::SmallHut::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 1, 1, 1, 3, 5, 4, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 1, 1, 1, 3, 5, 4, 0, 0, false); - // floor - generateBox(level, chunkBB, 0, 0, 0, 3, 0, 4, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 0, 1, 2, 0, 3, Tile::dirt_Id, Tile::dirt_Id, false); - // roof - if (lowCeiling) { - generateBox(level, chunkBB, 1, 4, 1, 2, 4, 3, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - } else { - generateBox(level, chunkBB, 1, 5, 1, 2, 5, 3, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - } - placeBlock(level, Tile::treeTrunk_Id, 0, 1, 4, 0, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 2, 4, 0, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 1, 4, 4, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 2, 4, 4, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 1, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 2, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 3, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 1, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 2, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 3, chunkBB); + // floor + generateBox(level, chunkBB, 0, 0, 0, 3, 0, 4, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 0, 1, 2, 0, 3, Tile::dirt_Id, Tile::dirt_Id, + false); + // roof + if (lowCeiling) { + generateBox(level, chunkBB, 1, 4, 1, 2, 4, 3, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + } else { + generateBox(level, chunkBB, 1, 5, 1, 2, 5, 3, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + } + placeBlock(level, Tile::treeTrunk_Id, 0, 1, 4, 0, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 2, 4, 0, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 1, 4, 4, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 2, 4, 4, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 1, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 2, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 4, 3, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 1, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 2, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 3, 4, 3, chunkBB); - // corners - generateBox(level, chunkBB, 0, 1, 0, 0, 3, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 3, 1, 0, 3, 3, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 0, 1, 4, 0, 3, 4, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 3, 1, 4, 3, 3, 4, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); + // corners + generateBox(level, chunkBB, 0, 1, 0, 0, 3, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 3, 1, 0, 3, 3, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 0, 1, 4, 0, 3, 4, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 3, 1, 4, 3, 3, 4, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); - // wooden walls - generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 3, 1, 1, 3, 3, 3, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 1, 0, 2, 3, 0, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 1, 4, 2, 3, 4, Tile::wood_Id, Tile::wood_Id, false); + // wooden walls + generateBox(level, chunkBB, 0, 1, 1, 0, 3, 3, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 3, 1, 1, 3, 3, 3, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 1, 0, 2, 3, 0, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 1, 4, 2, 3, 4, Tile::wood_Id, Tile::wood_Id, + false); - // windows - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 2, chunkBB); + // windows + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 2, chunkBB); - // table - if (tablePlacement > 0) { - placeBlock(level, Tile::fence_Id, 0, tablePlacement, 1, 3, chunkBB); - placeBlock(level, Tile::pressurePlate_wood_Id, 0, tablePlacement, 2, 3, chunkBB); - } + // table + if (tablePlacement > 0) { + placeBlock(level, Tile::fence_Id, 0, tablePlacement, 1, 3, chunkBB); + placeBlock(level, Tile::pressurePlate_wood_Id, 0, tablePlacement, 2, 3, + chunkBB); + } - // entrance - placeBlock(level, 0, 0, 1, 1, 0, chunkBB); - placeBlock(level, 0, 0, 1, 2, 0, chunkBB); - createDoor(level, chunkBB, random, 1, 1, 0, getOrientationData(Tile::door_wood_Id, 1)); - if (getBlock(level, 1, 0, -1, chunkBB) == 0 && getBlock(level, 1, -1, -1, chunkBB) != 0) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 1, 0, -1, chunkBB); - } + // entrance + placeBlock(level, 0, 0, 1, 1, 0, chunkBB); + placeBlock(level, 0, 0, 1, 2, 0, chunkBB); + createDoor(level, chunkBB, random, 1, 1, 0, + getOrientationData(Tile::door_wood_Id, 1)); + if (getBlock(level, 1, 0, -1, chunkBB) == 0 && + getBlock(level, 1, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 1, 0, -1, + chunkBB); + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 1, 1, 2, 1); - - return true; + spawnVillagers(level, chunkBB, 1, 1, 2, 1); + return true; } -VillagePieces::PigHouse::PigHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::PigHouse::PigHouse(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::PigHouse *VillagePieces::PigHouse::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ +VillagePieces::PigHouse* VillagePieces::PigHouse::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } - - return new PigHouse(startPiece, genDepth, random, box, direction); + return new PigHouse(startPiece, genDepth, random, box, direction); } -bool VillagePieces::PigHouse::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::PigHouse::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 1, 1, 1, 7, 4, 4, 0, 0, false); - generateBox(level, chunkBB, 2, 1, 6, 8, 4, 10, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 1, 1, 1, 7, 4, 4, 0, 0, false); + generateBox(level, chunkBB, 2, 1, 6, 8, 4, 10, 0, 0, false); - // pig floor - generateBox(level, chunkBB, 2, 0, 6, 8, 0, 10, Tile::dirt_Id, Tile::dirt_Id, false); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, 0, 6, chunkBB); - // pig fence - generateBox(level, chunkBB, 2, 1, 6, 2, 1, 10, Tile::fence_Id, Tile::fence_Id, false); - generateBox(level, chunkBB, 8, 1, 6, 8, 1, 10, Tile::fence_Id, Tile::fence_Id, false); - generateBox(level, chunkBB, 3, 1, 10, 7, 1, 10, Tile::fence_Id, Tile::fence_Id, false); + // pig floor + generateBox(level, chunkBB, 2, 0, 6, 8, 0, 10, Tile::dirt_Id, Tile::dirt_Id, + false); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, 0, 6, chunkBB); + // pig fence + generateBox(level, chunkBB, 2, 1, 6, 2, 1, 10, Tile::fence_Id, + Tile::fence_Id, false); + generateBox(level, chunkBB, 8, 1, 6, 8, 1, 10, Tile::fence_Id, + Tile::fence_Id, false); + generateBox(level, chunkBB, 3, 1, 10, 7, 1, 10, Tile::fence_Id, + Tile::fence_Id, false); - // floor - generateBox(level, chunkBB, 1, 0, 1, 7, 0, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 0, 0, 0, 3, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 8, 0, 0, 8, 3, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 0, 0, 7, 1, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 0, 5, 7, 1, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // floor + generateBox(level, chunkBB, 1, 0, 1, 7, 0, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 0, 0, 0, 3, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 8, 0, 0, 8, 3, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 0, 0, 7, 1, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 0, 5, 7, 1, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // roof - generateBox(level, chunkBB, 1, 2, 0, 7, 3, 0, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 2, 5, 7, 3, 5, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 4, 1, 8, 4, 1, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 4, 4, 8, 4, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 5, 2, 8, 5, 3, Tile::wood_Id, Tile::wood_Id, false); - placeBlock(level, Tile::wood_Id, 0, 0, 4, 2, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 0, 4, 3, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 4, 2, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 4, 3, chunkBB); + // roof + generateBox(level, chunkBB, 1, 2, 0, 7, 3, 0, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 2, 5, 7, 3, 5, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 4, 1, 8, 4, 1, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 4, 4, 8, 4, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 5, 2, 8, 5, 3, Tile::wood_Id, Tile::wood_Id, + false); + placeBlock(level, Tile::wood_Id, 0, 0, 4, 2, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 0, 4, 3, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 4, 2, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 4, 3, chunkBB); - int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); - int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); - for (int d = -1; d <= 2; d++) - { - for (int w = 0; w <= 8; w++) - { - placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 4 + d, d, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 4 + d, 5 - d, chunkBB); - } - } + int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); + int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); + for (int d = -1; d <= 2; d++) { + for (int w = 0; w <= 8; w++) { + placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 4 + d, d, + chunkBB); + placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 4 + d, + 5 - d, chunkBB); + } + } - // windows etc - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 1, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 4, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 1, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 5, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 5, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 5, chunkBB); + // windows etc + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 1, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 4, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 1, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 5, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 3, 2, 5, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 6, 2, 5, chunkBB); - // table - placeBlock(level, Tile::fence_Id, 0, 2, 1, 3, chunkBB); - placeBlock(level, Tile::pressurePlate_wood_Id, 0, 2, 2, 3, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 1, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, getOrientationData(Tile::stairs_wood_Id, 3), 2, 1, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, getOrientationData(Tile::stairs_wood_Id, 1), 1, 1, 3, chunkBB); + // table + placeBlock(level, Tile::fence_Id, 0, 2, 1, 3, chunkBB); + placeBlock(level, Tile::pressurePlate_wood_Id, 0, 2, 2, 3, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 1, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, + getOrientationData(Tile::stairs_wood_Id, 3), 2, 1, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, + getOrientationData(Tile::stairs_wood_Id, 1), 1, 1, 3, chunkBB); - // butcher table - generateBox(level, chunkBB, 5, 0, 1, 7, 0, 3, Tile::stoneSlab_Id, Tile::stoneSlab_Id, false); - placeBlock(level, Tile::stoneSlab_Id, 0, 6, 1, 1, chunkBB); - placeBlock(level, Tile::stoneSlab_Id, 0, 6, 1, 2, chunkBB); + // butcher table + generateBox(level, chunkBB, 5, 0, 1, 7, 0, 3, Tile::stoneSlab_Id, + Tile::stoneSlab_Id, false); + placeBlock(level, Tile::stoneSlab_Id, 0, 6, 1, 1, chunkBB); + placeBlock(level, Tile::stoneSlab_Id, 0, 6, 1, 2, chunkBB); - // entrance - placeBlock(level, 0, 0, 2, 1, 0, chunkBB); - placeBlock(level, 0, 0, 2, 2, 0, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); - createDoor(level, chunkBB, random, 2, 1, 0, getOrientationData(Tile::door_wood_Id, 1)); - if (getBlock(level, 2, 0, -1, chunkBB) == 0 && getBlock(level, 2, -1, -1, chunkBB) != 0) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, chunkBB); - } + // entrance + placeBlock(level, 0, 0, 2, 1, 0, chunkBB); + placeBlock(level, 0, 0, 2, 2, 0, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); + createDoor(level, chunkBB, random, 2, 1, 0, + getOrientationData(Tile::door_wood_Id, 1)); + if (getBlock(level, 2, 0, -1, chunkBB) == 0 && + getBlock(level, 2, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, + chunkBB); + } - // pig entrance - placeBlock(level, 0, 0, 6, 1, 5, chunkBB); - placeBlock(level, 0, 0, 6, 2, 5, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 6, 3, 4, chunkBB); - createDoor(level, chunkBB, random, 6, 1, 5, getOrientationData(Tile::door_wood_Id, 1)); + // pig entrance + placeBlock(level, 0, 0, 6, 1, 5, chunkBB); + placeBlock(level, 0, 0, 6, 2, 5, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 6, 3, 4, chunkBB); + createDoor(level, chunkBB, random, 6, 1, 5, + getOrientationData(Tile::door_wood_Id, 1)); - for (int z = 0; z < 5; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < 5; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 4, 1, 2, 2); - - return true; + spawnVillagers(level, chunkBB, 4, 1, 2, 2); + return true; } -int VillagePieces::PigHouse::getVillagerProfession(int villagerNumber) -{ - if (villagerNumber == 0) - { - return Villager::PROFESSION_BUTCHER; - } - return Villager::PROFESSION_FARMER; +int VillagePieces::PigHouse::getVillagerProfession(int villagerNumber) { + if (villagerNumber == 0) { + return Villager::PROFESSION_BUTCHER; + } + return Villager::PROFESSION_FARMER; } -VillagePieces::TwoRoomHouse::TwoRoomHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser +VillagePieces::TwoRoomHouse::TwoRoomHouse(StartPiece* startPiece, int genDepth, + Random* random, + BoundingBox* stairsBox, int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::TwoRoomHouse *VillagePieces::TwoRoomHouse::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::TwoRoomHouse* VillagePieces::TwoRoomHouse::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new TwoRoomHouse(startPiece, genDepth, random, box, direction); + return new TwoRoomHouse(startPiece, genDepth, random, box, direction); } -bool VillagePieces::TwoRoomHouse::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::TwoRoomHouse::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 1, 1, 1, 7, 4, 4, 0, 0, false); - generateBox(level, chunkBB, 2, 1, 6, 8, 4, 10, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 1, 1, 1, 7, 4, 4, 0, 0, false); + generateBox(level, chunkBB, 2, 1, 6, 8, 4, 10, 0, 0, false); - // floor - generateBox(level, chunkBB, 2, 0, 5, 8, 0, 10, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 0, 1, 7, 0, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 0, 0, 0, 3, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 8, 0, 0, 8, 3, 10, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 0, 0, 7, 2, 0, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 1, 0, 5, 2, 1, 5, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 2, 0, 6, 2, 3, 10, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 3, 0, 10, 7, 3, 10, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // floor + generateBox(level, chunkBB, 2, 0, 5, 8, 0, 10, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 0, 1, 7, 0, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 0, 0, 0, 3, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 8, 0, 0, 8, 3, 10, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 0, 0, 7, 2, 0, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 1, 0, 5, 2, 1, 5, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 2, 0, 6, 2, 3, 10, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 3, 0, 10, 7, 3, 10, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // room 1 roof - generateBox(level, chunkBB, 1, 2, 0, 7, 3, 0, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 2, 5, 2, 3, 5, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 4, 1, 8, 4, 1, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 4, 4, 3, 4, 4, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 5, 2, 8, 5, 3, Tile::wood_Id, Tile::wood_Id, false); - placeBlock(level, Tile::wood_Id, 0, 0, 4, 2, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 0, 4, 3, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 4, 2, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 4, 3, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 4, 4, chunkBB); + // room 1 roof + generateBox(level, chunkBB, 1, 2, 0, 7, 3, 0, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 2, 5, 2, 3, 5, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 4, 1, 8, 4, 1, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 4, 4, 3, 4, 4, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 5, 2, 8, 5, 3, Tile::wood_Id, Tile::wood_Id, + false); + placeBlock(level, Tile::wood_Id, 0, 0, 4, 2, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 0, 4, 3, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 4, 2, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 4, 3, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 4, 4, chunkBB); - int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); - int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); - for (int d = -1; d <= 2; d++) - { - for (int w = 0; w <= 8; w++) - { - placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 4 + d, d, chunkBB); - if ((d > -1 || w <= 1) && (d > 0 || w <= 3) && (d > 1 || w <= 4 || w >= 6)) { - placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 4 + d, 5 - d, chunkBB); - } - } - } + int southStairs = getOrientationData(Tile::stairs_wood_Id, 3); + int northStairs = getOrientationData(Tile::stairs_wood_Id, 2); + for (int d = -1; d <= 2; d++) { + for (int w = 0; w <= 8; w++) { + placeBlock(level, Tile::stairs_wood_Id, southStairs, w, 4 + d, d, + chunkBB); + if ((d > -1 || w <= 1) && (d > 0 || w <= 3) && + (d > 1 || w <= 4 || w >= 6)) { + placeBlock(level, Tile::stairs_wood_Id, northStairs, w, 4 + d, + 5 - d, chunkBB); + } + } + } - // room 2 roof - generateBox(level, chunkBB, 3, 4, 5, 3, 4, 10, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 7, 4, 2, 7, 4, 10, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 4, 5, 4, 4, 5, 10, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 6, 5, 4, 6, 5, 10, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 5, 6, 3, 5, 6, 10, Tile::wood_Id, Tile::wood_Id, false); - int westStairs = getOrientationData(Tile::stairs_wood_Id, 0); - for (int w = 4; w >= 1; w--) - { - placeBlock(level, Tile::wood_Id, 0, w, 2 + w, 7 - w, chunkBB); - for (int d = 8 - w; d <= 10; d++) - { - placeBlock(level, Tile::stairs_wood_Id, westStairs, w, 2 + w, d, chunkBB); - } - } - int eastStairs = getOrientationData(Tile::stairs_wood_Id, 1); - placeBlock(level, Tile::wood_Id, 0, 6, 6, 3, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 7, 5, 4, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, eastStairs, 6, 6, 4, chunkBB); - for (int w = 6; w <= 8; w++) - { - for (int d = 5; d <= 10; d++) - { - placeBlock(level, Tile::stairs_wood_Id, eastStairs, w, 12 - w, d, chunkBB); - } - } + // room 2 roof + generateBox(level, chunkBB, 3, 4, 5, 3, 4, 10, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 7, 4, 2, 7, 4, 10, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 4, 5, 4, 4, 5, 10, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 6, 5, 4, 6, 5, 10, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 5, 6, 3, 5, 6, 10, Tile::wood_Id, Tile::wood_Id, + false); + int westStairs = getOrientationData(Tile::stairs_wood_Id, 0); + for (int w = 4; w >= 1; w--) { + placeBlock(level, Tile::wood_Id, 0, w, 2 + w, 7 - w, chunkBB); + for (int d = 8 - w; d <= 10; d++) { + placeBlock(level, Tile::stairs_wood_Id, westStairs, w, 2 + w, d, + chunkBB); + } + } + int eastStairs = getOrientationData(Tile::stairs_wood_Id, 1); + placeBlock(level, Tile::wood_Id, 0, 6, 6, 3, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 7, 5, 4, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, eastStairs, 6, 6, 4, chunkBB); + for (int w = 6; w <= 8; w++) { + for (int d = 5; d <= 10; d++) { + placeBlock(level, Tile::stairs_wood_Id, eastStairs, w, 12 - w, d, + chunkBB); + } + } - // windows etc - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 1, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); + // windows etc + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 1, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 0, 2, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 3, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 4, 2, 0, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 6, 2, 0, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 4, 2, 0, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 2, 0, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 6, 2, 0, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 1, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 4, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 8, 2, 5, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 6, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 7, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 8, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 9, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 2, 2, 6, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 7, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 8, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 2, 2, 9, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 1, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 3, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 4, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 8, 2, 5, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 6, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 7, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 8, 2, 8, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 8, 2, 9, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 2, 2, 6, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 7, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 8, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 2, 2, 9, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 4, 4, 10, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 5, 4, 10, chunkBB); - placeBlock(level, Tile::treeTrunk_Id, 0, 6, 4, 10, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 5, 5, 10, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 4, 4, 10, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 5, 4, 10, chunkBB); + placeBlock(level, Tile::treeTrunk_Id, 0, 6, 4, 10, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 5, 5, 10, chunkBB); - // entrance - placeBlock(level, 0, 0, 2, 1, 0, chunkBB); - placeBlock(level, 0, 0, 2, 2, 0, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); - createDoor(level, chunkBB, random, 2, 1, 0, getOrientationData(Tile::door_wood_Id, 1)); - generateBox(level, chunkBB, 1, 0, -1, 3, 2, -1, 0, 0, false); - if (getBlock(level, 2, 0, -1, chunkBB) == 0 && getBlock(level, 2, -1, -1, chunkBB) != 0) { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, chunkBB); - } + // entrance + placeBlock(level, 0, 0, 2, 1, 0, chunkBB); + placeBlock(level, 0, 0, 2, 2, 0, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 2, 3, 1, chunkBB); + createDoor(level, chunkBB, random, 2, 1, 0, + getOrientationData(Tile::door_wood_Id, 1)); + generateBox(level, chunkBB, 1, 0, -1, 3, 2, -1, 0, 0, false); + if (getBlock(level, 2, 0, -1, chunkBB) == 0 && + getBlock(level, 2, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), 2, 0, -1, + chunkBB); + } - for (int z = 0; z < 5; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } - for (int z = 5; z < depth - 1; z++) - { - for (int x = 2; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < 5; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } + for (int z = 5; z < depth - 1; z++) { + for (int x = 2; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 4, 1, 2, 2); - - return true; + spawnVillagers(level, chunkBB, 4, 1, 2, 2); + return true; } -void VillagePieces::Smithy::staticCtor() -{ - treasureItems = WeighedTreasureArray(13); - treasureItems[0] = new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3); - treasureItems[1] = new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10); - treasureItems[2] = new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5); - treasureItems[3] = new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15); - treasureItems[4] = new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15); - treasureItems[5] = new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 5); - treasureItems[6] = new WeighedTreasure(Item::sword_iron_Id, 0, 1, 1, 5); - treasureItems[7] = new WeighedTreasure(Item::chestplate_iron_Id, 0, 1, 1, 5); - treasureItems[8] = new WeighedTreasure(Item::helmet_iron_Id, 0, 1, 1, 5); - treasureItems[9] = new WeighedTreasure(Item::leggings_iron_Id, 0, 1, 1, 5); - treasureItems[10] = new WeighedTreasure(Item::boots_iron_Id, 0, 1, 1, 5); - treasureItems[11] = new WeighedTreasure(Tile::obsidian_Id, 0, 3, 7, 5); - treasureItems[12] = new WeighedTreasure(Tile::sapling_Id, 0, 3, 7, 5); +void VillagePieces::Smithy::staticCtor() { + treasureItems = WeighedTreasureArray(13); + treasureItems[0] = new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3); + treasureItems[1] = new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10); + treasureItems[2] = new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5); + treasureItems[3] = new WeighedTreasure(Item::bread_Id, 0, 1, 3, 15); + treasureItems[4] = new WeighedTreasure(Item::apple_Id, 0, 1, 3, 15); + treasureItems[5] = new WeighedTreasure(Item::pickAxe_iron_Id, 0, 1, 1, 5); + treasureItems[6] = new WeighedTreasure(Item::sword_iron_Id, 0, 1, 1, 5); + treasureItems[7] = + new WeighedTreasure(Item::chestplate_iron_Id, 0, 1, 1, 5); + treasureItems[8] = new WeighedTreasure(Item::helmet_iron_Id, 0, 1, 1, 5); + treasureItems[9] = new WeighedTreasure(Item::leggings_iron_Id, 0, 1, 1, 5); + treasureItems[10] = new WeighedTreasure(Item::boots_iron_Id, 0, 1, 1, 5); + treasureItems[11] = new WeighedTreasure(Tile::obsidian_Id, 0, 3, 7, 5); + treasureItems[12] = new WeighedTreasure(Tile::sapling_Id, 0, 3, 7, 5); } -VillagePieces::Smithy::Smithy(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - hasPlacedChest = false; +VillagePieces::Smithy::Smithy(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + hasPlacedChest = false; - orientation = direction; - boundingBox = stairsBox; + orientation = direction; + boundingBox = stairsBox; } -VillagePieces::Smithy *VillagePieces::Smithy::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::Smithy* VillagePieces::Smithy::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new Smithy(startPiece, genDepth, random, box, direction); + return new Smithy(startPiece, genDepth, random, box, direction); } -bool VillagePieces::Smithy::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::Smithy::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 0, 1, 0, 9, 4, 6, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 0, 1, 0, 9, 4, 6, 0, 0, false); - // floor - generateBox(level, chunkBB, 0, 0, 0, 9, 0, 6, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); + // floor + generateBox(level, chunkBB, 0, 0, 0, 9, 0, 6, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); - // roof - generateBox(level, chunkBB, 0, 4, 0, 9, 4, 6, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - generateBox(level, chunkBB, 0, 5, 0, 9, 5, 6, Tile::stoneSlabHalf_Id, Tile::stoneSlabHalf_Id, false); - generateBox(level, chunkBB, 1, 5, 1, 8, 5, 5, 0, 0, false); + // roof + generateBox(level, chunkBB, 0, 4, 0, 9, 4, 6, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + generateBox(level, chunkBB, 0, 5, 0, 9, 5, 6, Tile::stoneSlabHalf_Id, + Tile::stoneSlabHalf_Id, false); + generateBox(level, chunkBB, 1, 5, 1, 8, 5, 5, 0, 0, false); - // room walls - generateBox(level, chunkBB, 1, 1, 0, 2, 3, 0, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 1, 0, 0, 4, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 3, 1, 0, 3, 4, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 0, 1, 6, 0, 4, 6, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - placeBlock(level, Tile::wood_Id, 0, 3, 3, 1, chunkBB); - generateBox(level, chunkBB, 3, 1, 2, 3, 3, 2, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 4, 1, 3, 5, 3, 3, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 0, 1, 1, 0, 3, 5, Tile::wood_Id, Tile::wood_Id, false); - generateBox(level, chunkBB, 1, 1, 6, 5, 3, 6, Tile::wood_Id, Tile::wood_Id, false); + // room walls + generateBox(level, chunkBB, 1, 1, 0, 2, 3, 0, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 1, 0, 0, 4, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 3, 1, 0, 3, 4, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 0, 1, 6, 0, 4, 6, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + placeBlock(level, Tile::wood_Id, 0, 3, 3, 1, chunkBB); + generateBox(level, chunkBB, 3, 1, 2, 3, 3, 2, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 4, 1, 3, 5, 3, 3, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 0, 1, 1, 0, 3, 5, Tile::wood_Id, Tile::wood_Id, + false); + generateBox(level, chunkBB, 1, 1, 6, 5, 3, 6, Tile::wood_Id, Tile::wood_Id, + false); - // pillars - generateBox(level, chunkBB, 5, 1, 0, 5, 3, 0, Tile::fence_Id, Tile::fence_Id, false); - generateBox(level, chunkBB, 9, 1, 0, 9, 3, 0, Tile::fence_Id, Tile::fence_Id, false); + // pillars + generateBox(level, chunkBB, 5, 1, 0, 5, 3, 0, Tile::fence_Id, + Tile::fence_Id, false); + generateBox(level, chunkBB, 9, 1, 0, 9, 3, 0, Tile::fence_Id, + Tile::fence_Id, false); - // furnace - generateBox(level, chunkBB, 6, 1, 4, 9, 4, 6, Tile::stoneBrick_Id, Tile::stoneBrick_Id, false); - placeBlock(level, Tile::lava_Id, 0, 7, 1, 5, chunkBB); - placeBlock(level, Tile::lava_Id, 0, 8, 1, 5, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, 9, 2, 5, chunkBB); - placeBlock(level, Tile::ironFence_Id, 0, 9, 2, 4, chunkBB); - generateBox(level, chunkBB, 7, 2, 4, 8, 2, 5, 0, 0, false); - placeBlock(level, Tile::stoneBrick_Id, 0, 6, 1, 3, chunkBB); - placeBlock(level, Tile::furnace_Id, 0, 6, 2, 3, chunkBB); - placeBlock(level, Tile::furnace_Id, 0, 6, 3, 3, chunkBB); - placeBlock(level, Tile::stoneSlab_Id, 0, 8, 1, 1, chunkBB); + // furnace + generateBox(level, chunkBB, 6, 1, 4, 9, 4, 6, Tile::stoneBrick_Id, + Tile::stoneBrick_Id, false); + placeBlock(level, Tile::lava_Id, 0, 7, 1, 5, chunkBB); + placeBlock(level, Tile::lava_Id, 0, 8, 1, 5, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, 9, 2, 5, chunkBB); + placeBlock(level, Tile::ironFence_Id, 0, 9, 2, 4, chunkBB); + generateBox(level, chunkBB, 7, 2, 4, 8, 2, 5, 0, 0, false); + placeBlock(level, Tile::stoneBrick_Id, 0, 6, 1, 3, chunkBB); + placeBlock(level, Tile::furnace_Id, 0, 6, 2, 3, chunkBB); + placeBlock(level, Tile::furnace_Id, 0, 6, 3, 3, chunkBB); + placeBlock(level, Tile::stoneSlab_Id, 0, 8, 1, 1, chunkBB); - // windows etc - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 4, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 6, chunkBB); - placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 6, chunkBB); + // windows etc + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 2, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 0, 2, 4, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 2, 2, 6, chunkBB); + placeBlock(level, Tile::thinGlass_Id, 0, 4, 2, 6, chunkBB); - // table - placeBlock(level, Tile::fence_Id, 0, 2, 1, 4, chunkBB); - placeBlock(level, Tile::pressurePlate_wood_Id, 0, 2, 2, 4, chunkBB); - placeBlock(level, Tile::wood_Id, 0, 1, 1, 5, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, getOrientationData(Tile::stairs_wood_Id, 3), 2, 1, 5, chunkBB); - placeBlock(level, Tile::stairs_wood_Id, getOrientationData(Tile::stairs_wood_Id, 1), 1, 1, 4, chunkBB); + // table + placeBlock(level, Tile::fence_Id, 0, 2, 1, 4, chunkBB); + placeBlock(level, Tile::pressurePlate_wood_Id, 0, 2, 2, 4, chunkBB); + placeBlock(level, Tile::wood_Id, 0, 1, 1, 5, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, + getOrientationData(Tile::stairs_wood_Id, 3), 2, 1, 5, chunkBB); + placeBlock(level, Tile::stairs_wood_Id, + getOrientationData(Tile::stairs_wood_Id, 1), 1, 1, 4, chunkBB); - if (!hasPlacedChest) - { - int y = getWorldY(1); - int x = getWorldX(5, 5), z = getWorldZ(5, 5); - if (chunkBB->isInside(x, y, z)) - { - hasPlacedChest = true; - createChest(level, chunkBB, random, 5, 1, 5, treasureItems, 3 + random->nextInt(6)); - } - } + if (!hasPlacedChest) { + int y = getWorldY(1); + int x = getWorldX(5, 5), z = getWorldZ(5, 5); + if (chunkBB->isInside(x, y, z)) { + hasPlacedChest = true; + createChest(level, chunkBB, random, 5, 1, 5, treasureItems, + 3 + random->nextInt(6)); + } + } - // entrance - for (int x = 6; x <= 8; x++) - { - if (getBlock(level, x, 0, -1, chunkBB) == 0 && getBlock(level, x, -1, -1, chunkBB) != 0 ) - { - placeBlock(level, Tile::stairs_stone_Id, getOrientationData(Tile::stairs_stone_Id, 3), x, 0, -1, chunkBB); - } - } + // entrance + for (int x = 6; x <= 8; x++) { + if (getBlock(level, x, 0, -1, chunkBB) == 0 && + getBlock(level, x, -1, -1, chunkBB) != 0) { + placeBlock(level, Tile::stairs_stone_Id, + getOrientationData(Tile::stairs_stone_Id, 3), x, 0, -1, + chunkBB); + } + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); - } - } + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::stoneBrick_Id, 0, x, -1, z, chunkBB); + } + } - spawnVillagers(level, chunkBB, 7, 1, 1, 1); - - return true; + spawnVillagers(level, chunkBB, 7, 1, 1, 1); + return true; } -int VillagePieces::Smithy::getVillagerProfession(int villagerNumber) -{ - return Villager::PROFESSION_SMITH; +int VillagePieces::Smithy::getVillagerProfession(int villagerNumber) { + return Villager::PROFESSION_SMITH; } -VillagePieces::Farmland::Farmland(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::Farmland::Farmland(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; - cropsA = selectCrops(random); - cropsB = selectCrops(random); + cropsA = selectCrops(random); + cropsB = selectCrops(random); } -int VillagePieces::Farmland::selectCrops(Random *random) -{ - switch (random->nextInt(5)) - { - default: - return Tile::crops_Id; - case 0: - return Tile::carrots_Id; - case 1: - return Tile::potatoes_Id; - } +int VillagePieces::Farmland::selectCrops(Random* random) { + switch (random->nextInt(5)) { + default: + return Tile::crops_Id; + case 0: + return Tile::carrots_Id; + case 1: + return Tile::potatoes_Id; + } } -VillagePieces::Farmland *VillagePieces::Farmland::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::Farmland* VillagePieces::Farmland::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new Farmland(startPiece, genDepth, random, box, direction); + return new Farmland(startPiece, genDepth, random, box, direction); } -bool VillagePieces::Farmland::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::Farmland::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 0, 1, 0, 6, 4, 8, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 0, 1, 0, 6, 4, 8, 0, 0, false); - // farmlands - generateBox(level, chunkBB, 1, 0, 1, 2, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - generateBox(level, chunkBB, 4, 0, 1, 5, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - // walkpaths - generateBox(level, chunkBB, 0, 0, 0, 0, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 6, 0, 0, 6, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 1, 0, 0, 5, 0, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 1, 0, 8, 5, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - // water - generateBox(level, chunkBB, 3, 0, 1, 3, 0, 7, Tile::water_Id, Tile::water_Id, false); - // crops - for (int d = 1; d <= 7; d++) - { - placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 1, 1, d, chunkBB); - placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 2, 1, d, chunkBB); - placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 4, 1, d, chunkBB); - placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 5, 1, d, chunkBB); - } + // farmlands + generateBox(level, chunkBB, 1, 0, 1, 2, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + generateBox(level, chunkBB, 4, 0, 1, 5, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + // walkpaths + generateBox(level, chunkBB, 0, 0, 0, 0, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 6, 0, 0, 6, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 1, 0, 0, 5, 0, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 1, 0, 8, 5, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + // water + generateBox(level, chunkBB, 3, 0, 1, 3, 0, 7, Tile::water_Id, + Tile::water_Id, false); + // crops + for (int d = 1; d <= 7; d++) { + placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 1, 1, d, chunkBB); + placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 2, 1, d, chunkBB); + placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 4, 1, d, chunkBB); + placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 5, 1, d, chunkBB); + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::dirt_Id, 0, x, -1, z, chunkBB); - } - } - - return true; + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::dirt_Id, 0, x, -1, z, chunkBB); + } + } + return true; } -VillagePieces::DoubleFarmland::DoubleFarmland(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J added initialiser - orientation = direction; - boundingBox = stairsBox; +VillagePieces::DoubleFarmland::DoubleFarmland(StartPiece* startPiece, + int genDepth, Random* random, + BoundingBox* stairsBox, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J added initialiser + orientation = direction; + boundingBox = stairsBox; - cropsA = selectCrops(random); - cropsB = selectCrops(random); - cropsC = selectCrops(random); - cropsD = selectCrops(random); + cropsA = selectCrops(random); + cropsB = selectCrops(random); + cropsC = selectCrops(random); + cropsD = selectCrops(random); } -int VillagePieces::DoubleFarmland::selectCrops(Random *random) -{ - switch (random->nextInt(5)) - { - default: - return Tile::crops_Id; - case 0: - return Tile::carrots_Id; - case 1: - return Tile::potatoes_Id; - } +int VillagePieces::DoubleFarmland::selectCrops(Random* random) { + switch (random->nextInt(5)) { + default: + return Tile::crops_Id; + case 0: + return Tile::carrots_Id; + case 1: + return Tile::potatoes_Id; + } } -VillagePieces::DoubleFarmland *VillagePieces::DoubleFarmland::createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +VillagePieces::DoubleFarmland* VillagePieces::DoubleFarmland::createPiece( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction, int genDepth) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return new DoubleFarmland(startPiece, genDepth, random, box, direction); + return new DoubleFarmland(startPiece, genDepth, random, box, direction); } -bool VillagePieces::DoubleFarmland::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::DoubleFarmland::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill inside with air - generateBox(level, chunkBB, 0, 1, 0, 12, 4, 8, 0, 0, false); + // fill inside with air + generateBox(level, chunkBB, 0, 1, 0, 12, 4, 8, 0, 0, false); - // farmlands - generateBox(level, chunkBB, 1, 0, 1, 2, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - generateBox(level, chunkBB, 4, 0, 1, 5, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - generateBox(level, chunkBB, 7, 0, 1, 8, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - generateBox(level, chunkBB, 10, 0, 1, 11, 0, 7, Tile::farmland_Id, Tile::farmland_Id, false); - // walkpaths - generateBox(level, chunkBB, 0, 0, 0, 0, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 6, 0, 0, 6, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 12, 0, 0, 12, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 1, 0, 0, 11, 0, 0, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - generateBox(level, chunkBB, 1, 0, 8, 11, 0, 8, Tile::treeTrunk_Id, Tile::treeTrunk_Id, false); - // water - generateBox(level, chunkBB, 3, 0, 1, 3, 0, 7, Tile::water_Id, Tile::water_Id, false); - generateBox(level, chunkBB, 9, 0, 1, 9, 0, 7, Tile::water_Id, Tile::water_Id, false); - // crops - for (int d = 1; d <= 7; d++) - { - placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 1, 1, d, chunkBB); - placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 2, 1, d, chunkBB); - placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 4, 1, d, chunkBB); - placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 5, 1, d, chunkBB); - placeBlock(level, cropsC, Mth::nextInt(random, 2, 7), 7, 1, d, chunkBB); - placeBlock(level, cropsC, Mth::nextInt(random, 2, 7), 8, 1, d, chunkBB); - placeBlock(level, cropsD, Mth::nextInt(random, 2, 7), 10, 1, d, chunkBB); - placeBlock(level, cropsD, Mth::nextInt(random, 2, 7), 11, 1, d, chunkBB); - } + // farmlands + generateBox(level, chunkBB, 1, 0, 1, 2, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + generateBox(level, chunkBB, 4, 0, 1, 5, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + generateBox(level, chunkBB, 7, 0, 1, 8, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + generateBox(level, chunkBB, 10, 0, 1, 11, 0, 7, Tile::farmland_Id, + Tile::farmland_Id, false); + // walkpaths + generateBox(level, chunkBB, 0, 0, 0, 0, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 6, 0, 0, 6, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 12, 0, 0, 12, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 1, 0, 0, 11, 0, 0, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + generateBox(level, chunkBB, 1, 0, 8, 11, 0, 8, Tile::treeTrunk_Id, + Tile::treeTrunk_Id, false); + // water + generateBox(level, chunkBB, 3, 0, 1, 3, 0, 7, Tile::water_Id, + Tile::water_Id, false); + generateBox(level, chunkBB, 9, 0, 1, 9, 0, 7, Tile::water_Id, + Tile::water_Id, false); + // crops + for (int d = 1; d <= 7; d++) { + placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 1, 1, d, chunkBB); + placeBlock(level, cropsA, Mth::nextInt(random, 2, 7), 2, 1, d, chunkBB); + placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 4, 1, d, chunkBB); + placeBlock(level, cropsB, Mth::nextInt(random, 2, 7), 5, 1, d, chunkBB); + placeBlock(level, cropsC, Mth::nextInt(random, 2, 7), 7, 1, d, chunkBB); + placeBlock(level, cropsC, Mth::nextInt(random, 2, 7), 8, 1, d, chunkBB); + placeBlock(level, cropsD, Mth::nextInt(random, 2, 7), 10, 1, d, + chunkBB); + placeBlock(level, cropsD, Mth::nextInt(random, 2, 7), 11, 1, d, + chunkBB); + } - for (int z = 0; z < depth; z++) - { - for (int x = 0; x < width; x++) - { - generateAirColumnUp(level, x, height, z, chunkBB); - fillColumnDown(level, Tile::dirt_Id, 0, x, -1, z, chunkBB); - } - } - - - return true; + for (int z = 0; z < depth; z++) { + for (int x = 0; x < width; x++) { + generateAirColumnUp(level, x, height, z, chunkBB); + fillColumnDown(level, Tile::dirt_Id, 0, x, -1, z, chunkBB); + } + } + return true; } -VillagePieces::LightPost::LightPost(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *box, int direction) : VillagePiece(startPiece, genDepth) -{ - heightPosition = -1; // 4J - added initialiser - orientation = direction; - boundingBox = box; +VillagePieces::LightPost::LightPost(StartPiece* startPiece, int genDepth, + Random* random, BoundingBox* box, + int direction) + : VillagePiece(startPiece, genDepth) { + heightPosition = -1; // 4J - added initialiser + orientation = direction; + boundingBox = box; } -BoundingBox *VillagePieces::LightPost::findPieceBox(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction) -{ - BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, width, height, depth, direction); +BoundingBox* VillagePieces::LightPost::findPieceBox( + StartPiece* startPiece, std::list* pieces, Random* random, + int footX, int footY, int footZ, int direction) { + BoundingBox* box = BoundingBox::orientBox(footX, footY, footZ, 0, 0, 0, + width, height, depth, direction); - if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) - { - delete box; - return NULL; - } + if (!isOkBox(box, startPiece) || + StructurePiece::findCollisionPiece(pieces, box) != NULL) { + delete box; + return NULL; + } - return box; + return box; } -bool VillagePieces::LightPost::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ - if (heightPosition < 0) - { - heightPosition = getAverageGroundHeight(level, chunkBB); - if (heightPosition < 0) - { - return true; - } - boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); - } +bool VillagePieces::LightPost::postProcess(Level* level, Random* random, + BoundingBox* chunkBB) { + if (heightPosition < 0) { + heightPosition = getAverageGroundHeight(level, chunkBB); + if (heightPosition < 0) { + return true; + } + boundingBox->move(0, heightPosition - boundingBox->y1 + height - 1, 0); + } - // fill with air - generateBox(level, chunkBB, 0, 0, 0, 2, 3, 1, 0, 0, false); + // fill with air + generateBox(level, chunkBB, 0, 0, 0, 2, 3, 1, 0, 0, false); - // pillar - placeBlock(level, Tile::fence_Id, 0, 1, 0, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, 1, 0, chunkBB); - placeBlock(level, Tile::fence_Id, 0, 1, 2, 0, chunkBB); + // pillar + placeBlock(level, Tile::fence_Id, 0, 1, 0, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, 1, 0, chunkBB); + placeBlock(level, Tile::fence_Id, 0, 1, 2, 0, chunkBB); - // head - placeBlock(level, Tile::cloth_Id, DyePowderItem::WHITE, 1, 3, 0, chunkBB); + // head + placeBlock(level, Tile::cloth_Id, DyePowderItem::WHITE, 1, 3, 0, chunkBB); - // torches - placeBlock(level, Tile::torch_Id, 0, 0, 3, 0, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 1, 3, 1, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 2, 3, 0, chunkBB); - placeBlock(level, Tile::torch_Id, 0, 1, 3, -1, chunkBB); + // torches + placeBlock(level, Tile::torch_Id, 0, 0, 3, 0, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 1, 3, 1, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 2, 3, 0, chunkBB); + placeBlock(level, Tile::torch_Id, 0, 1, 3, -1, chunkBB); - return true; + return true; } diff --git a/Minecraft.World/WorldGen/Structures/VillagePieces.h b/Minecraft.World/WorldGen/Structures/VillagePieces.h index f0c95b429..c7e972c5c 100644 --- a/Minecraft.World/WorldGen/Structures/VillagePieces.h +++ b/Minecraft.World/WorldGen/Structures/VillagePieces.h @@ -3,351 +3,427 @@ class BiomeSource; -class VillagePieces -{ - +class VillagePieces { private: - static const int MAX_DEPTH = 50; + static const int MAX_DEPTH = 50; static const int BASE_ROAD_DEPTH = 3; // the dungeon starts at 64 and traverses downwards to this point static const int LOWEST_Y_POSITION = 10; public: - static const int SIZE_SMALL = 0; - static const int SIZE_BIG = 1; - static const int SIZE_BIGGEST = 2; + static const int SIZE_SMALL = 0; + static const int SIZE_BIG = 1; + static const int SIZE_BIGGEST = 2; - // 4J - added to replace use of Class within this class - enum EPieceClass - { - EPieceClass_SimpleHouse, - EPieceClass_SmallTemple, - EPieceClass_BookHouse, - EPieceClass_SmallHut, - EPieceClass_PigHouse, - EPieceClass_DoubleFarmland, - EPieceClass_Farmland, - EPieceClass_Smithy, - EPieceClass_TwoRoomHouse - }; + // 4J - added to replace use of Class within this + // class + enum EPieceClass { + EPieceClass_SimpleHouse, + EPieceClass_SmallTemple, + EPieceClass_BookHouse, + EPieceClass_SmallHut, + EPieceClass_PigHouse, + EPieceClass_DoubleFarmland, + EPieceClass_Farmland, + EPieceClass_Smithy, + EPieceClass_TwoRoomHouse + }; class PieceWeight { - public: - EPieceClass pieceClass; // 4J - EPieceClass was Class + public: + EPieceClass + pieceClass; // 4J - EPieceClass was Class const int weight; int placeCount; int maxPlaceCount; - PieceWeight(EPieceClass pieceClass, int weight, int maxPlaceCount); // 4J - EPieceClass was Class + PieceWeight(EPieceClass pieceClass, int weight, + int maxPlaceCount); // 4J - EPieceClass was Class bool doPlace(int depth); bool isValid(); }; - static std::list *createPieceSet(Random *random, int villageSize); // 4J - was ArrayList + static std::list* createPieceSet( + Random* random, int villageSize); // 4J - was ArrayList + + class StartPiece; - class StartPiece; private: - class VillagePiece; - static int updatePieceWeight(std::list *currentPieces); // 4J = was array list - static VillagePiece *findAndCreatePieceFactory(StartPiece *startPiece, PieceWeight *piece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - static VillagePiece *generatePieceFromSmallDoor(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - static StructurePiece *generateAndAddPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - static StructurePiece *generateAndAddRoadPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int depth); - + class VillagePiece; + static int updatePieceWeight( + std::list* currentPieces); // 4J = was array list + static VillagePiece* findAndCreatePieceFactory( + StartPiece* startPiece, PieceWeight* piece, + std::list* pieces, Random* random, int footX, + int footY, int footZ, int direction, int depth); + static VillagePiece* generatePieceFromSmallDoor( + StartPiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); + static StructurePiece* generateAndAddPiece( + StartPiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); + static StructurePiece* generateAndAddRoadPiece( + StartPiece* startPiece, std::list* pieces, + Random* random, int footX, int footY, int footZ, int direction, + int depth); /** - * + * * */ private: - class VillagePiece : public StructurePiece - { - private: - int spawnedVillagerCount; - protected: - StartPiece *startPiece; + class VillagePiece : public StructurePiece { + private: + int spawnedVillagerCount; - VillagePiece(StartPiece *startPiece, int genDepth); - StructurePiece *generateHouseNorthernLeft(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff); - StructurePiece *generateHouseNorthernRight(StartPiece *startPiece, std::list *pieces, Random *random, int yOff, int zOff); - int getAverageGroundHeight(Level *level, BoundingBox *chunkBB); - static bool isOkBox(BoundingBox *box, StartPiece *startRoom); // 4J added startRoom param - void spawnVillagers(Level *level, BoundingBox *chunkBB, int x, int y, int z, int count); - virtual int getVillagerProfession(int villagerNumber); - virtual int biomeBlock(int tile, int data); - virtual int biomeData(int tile, int data); - virtual void placeBlock(Level *level, int block, int data, int x, int y, int z, BoundingBox *chunkBB); - virtual void generateBox(Level *level, BoundingBox *chunkBB, int x0, int y0, int z0, int x1, int y1, int z1, int edgeTile, int fillTile, bool skipAir); - virtual void fillColumnDown(Level *level, int block, int data, int x, int startY, int z, BoundingBox *chunkBB); + protected: + StartPiece* startPiece; + + VillagePiece(StartPiece* startPiece, int genDepth); + StructurePiece* generateHouseNorthernLeft( + StartPiece* startPiece, std::list* pieces, + Random* random, int yOff, int zOff); + StructurePiece* generateHouseNorthernRight( + StartPiece* startPiece, std::list* pieces, + Random* random, int yOff, int zOff); + int getAverageGroundHeight(Level* level, BoundingBox* chunkBB); + static bool isOkBox(BoundingBox* box, + StartPiece* startRoom); // 4J added startRoom param + void spawnVillagers(Level* level, BoundingBox* chunkBB, int x, int y, + int z, int count); + virtual int getVillagerProfession(int villagerNumber); + virtual int biomeBlock(int tile, int data); + virtual int biomeData(int tile, int data); + virtual void placeBlock(Level* level, int block, int data, int x, int y, + int z, BoundingBox* chunkBB); + virtual void generateBox(Level* level, BoundingBox* chunkBB, int x0, + int y0, int z0, int x1, int y1, int z1, + int edgeTile, int fillTile, bool skipAir); + virtual void fillColumnDown(Level* level, int block, int data, int x, + int startY, int z, BoundingBox* chunkBB); }; /** - * + * * */ public: - class Well : public VillagePiece - { - private: - static const int width = 6; - static const int height = 15; - static const int depth = 6; - - const bool isSource; - int heightPosition; + class Well : public VillagePiece { + private: + static const int width = 6; + static const int height = 15; + static const int depth = 6; - public: - Well(StartPiece *startPiece, int genDepth, Random *random, int west, int north); + const bool isSource; + int heightPosition; - Well(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - //static Well *createPiece(std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + Well(StartPiece* startPiece, int genDepth, Random* random, int west, + int north); + + Well(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + // static Well *createPiece(std::list *pieces, Random + // *random, int footX, int footY, int footZ, int direction, int + // genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; public: - class StartPiece : public Well - { - public: - BiomeSource *biomeSource; - bool isDesertVillage; + class StartPiece : public Well { + public: + BiomeSource* biomeSource; + bool isDesertVillage; - int villageSize; - bool isLibraryAdded; - PieceWeight *previousPiece; - std::list *pieceSet; // 4J - was ArrayList - Level *m_level; + int villageSize; + bool isLibraryAdded; + PieceWeight* previousPiece; + std::list* pieceSet; // 4J - was ArrayList + Level* m_level; // these queues are used so that the addChildren calls are // called in a random order - std::vector pendingHouses; // 4J - was ArrayList - std::vector pendingRoads; // 4J - was ArrayList - - StartPiece(BiomeSource *biomeSource, int genDepth, Random *random, int west, int north, std::list *pieceSet, int villageSize, Level *level); // 4J Added level param - virtual ~StartPiece(); - - BiomeSource *getBiomeSource(); + std::vector pendingHouses; // 4J - was ArrayList + std::vector pendingRoads; // 4J - was ArrayList + StartPiece(BiomeSource* biomeSource, int genDepth, Random* random, + int west, int north, std::list* pieceSet, + int villageSize, Level* level); // 4J Added level param + virtual ~StartPiece(); + + BiomeSource* getBiomeSource(); }; public: - class VillageRoadPiece : public VillagePiece - { - protected : - VillageRoadPiece(StartPiece *startPiece, int genDepth) : VillagePiece(startPiece, genDepth) {} + class VillageRoadPiece : public VillagePiece { + protected: + VillageRoadPiece(StartPiece* startPiece, int genDepth) + : VillagePiece(startPiece, genDepth) {} }; /** - * + * * */ public: - class StraightRoad : public VillageRoadPiece - { + class StraightRoad : public VillageRoadPiece { + private: + static const int width = 3; + int length; - private: - static const int width = 3; - int length; - public: - StraightRoad(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - virtual void addChildren(StructurePiece *startPiece, std::list *pieces, Random *random); - static BoundingBox *findPieceBox(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + StraightRoad(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + virtual void addChildren(StructurePiece* startPiece, + std::list* pieces, + Random* random); + static BoundingBox* findPieceBox(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; /** - * + * * */ public: - class SimpleHouse : public VillagePiece - { - private: - static const int width = 5; - static const int height = 6; - static const int depth = 5; + class SimpleHouse : public VillagePiece { + private: + static const int width = 5; + static const int height = 6; + static const int depth = 5; - private: - int heightPosition; - const bool hasTerrace; + private: + int heightPosition; + const bool hasTerrace; - public: - SimpleHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - public: - static SimpleHouse *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; + public: + SimpleHouse(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); -public: - class SmallTemple : public VillagePiece - { - private: - static const int width = 5; - static const int height = 12; - static const int depth = 9; - - int heightPosition; - - public: - SmallTemple(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - - static SmallTemple *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - virtual int getVillagerProfession(int villagerNumber); - }; - -public: - class BookHouse : public VillagePiece - { - private: - static const int width = 9; - static const int height = 9; - static const int depth = 6; - - int heightPosition; - - public: - BookHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - - static BookHouse *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - virtual int getVillagerProfession(int villagerNumber); - }; - - public: - class SmallHut : public VillagePiece - { - - private: - static const int width = 4; - static const int height = 6; - static const int depth = 5; - - int heightPosition; - const bool lowCeiling; - const int tablePlacement; - - public: - SmallHut(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static SmallHut *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + static SimpleHouse* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; public: - class PigHouse : public VillagePiece - { - - private: - static const int width = 9; - static const int height = 7; - static const int depth = 11; - - int heightPosition; - - public: - PigHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static PigHouse *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - virtual int getVillagerProfession(int villagerNumber); - }; - -public: - class TwoRoomHouse : public VillagePiece - { - private: - static const int width = 9; - static const int height = 7; - static const int depth = 12; - - int heightPosition; - - public: - TwoRoomHouse(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static TwoRoomHouse *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - }; - -public: - class Smithy : public VillagePiece - { - - private: - static const int width = 10; - static const int height = 6; - static const int depth = 7; + class SmallTemple : public VillagePiece { + private: + static const int width = 5; + static const int height = 12; + static const int depth = 9; int heightPosition; - bool hasPlacedChest; - static WeighedTreasureArray treasureItems; + public: + SmallTemple(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); - public: - static void staticCtor(); - - Smithy(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static Smithy *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); - virtual int getVillagerProfession(int villagerNumber); + static SmallTemple* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + virtual int getVillagerProfession(int villagerNumber); }; public: - class Farmland : public VillagePiece - { + class BookHouse : public VillagePiece { + private: + static const int width = 9; + static const int height = 9; + static const int depth = 6; - private: - static const int width = 7; - static const int height = 4; - static const int depth = 9; - - int heightPosition; + int heightPosition; - int cropsA; - int cropsB; + public: + BookHouse(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); - int selectCrops(Random *random); - - public: - Farmland(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static Farmland *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + static BookHouse* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + virtual int getVillagerProfession(int villagerNumber); }; public: - class DoubleFarmland : public VillagePiece - { - private: - static const int width = 13; - static const int height = 4; - static const int depth = 9; - - int heightPosition; + class SmallHut : public VillagePiece { + private: + static const int width = 4; + static const int height = 6; + static const int depth = 5; - int cropsA; - int cropsB; - int cropsC; - int cropsD; + int heightPosition; + const bool lowCeiling; + const int tablePlacement; - int selectCrops(Random *random); - - public: - DoubleFarmland(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *stairsBox, int direction); - static DoubleFarmland *createPiece(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction, int genDepth); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + SmallHut(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static SmallHut* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; public: - class LightPost : public VillagePiece - { - private: - static const int width = 3; + class PigHouse : public VillagePiece { + private: + static const int width = 9; + static const int height = 7; + static const int depth = 11; + + int heightPosition; + + public: + PigHouse(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static PigHouse* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + virtual int getVillagerProfession(int villagerNumber); + }; + +public: + class TwoRoomHouse : public VillagePiece { + private: + static const int width = 9; + static const int height = 7; + static const int depth = 12; + + int heightPosition; + + public: + TwoRoomHouse(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static TwoRoomHouse* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; + +public: + class Smithy : public VillagePiece { + private: + static const int width = 10; + static const int height = 6; + static const int depth = 7; + + int heightPosition; + bool hasPlacedChest; + + static WeighedTreasureArray treasureItems; + + public: + static void staticCtor(); + + Smithy(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static Smithy* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + virtual int getVillagerProfession(int villagerNumber); + }; + +public: + class Farmland : public VillagePiece { + private: + static const int width = 7; + static const int height = 4; + static const int depth = 9; + + int heightPosition; + + int cropsA; + int cropsB; + + int selectCrops(Random* random); + + public: + Farmland(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static Farmland* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; + +public: + class DoubleFarmland : public VillagePiece { + private: + static const int width = 13; + static const int height = 4; + static const int depth = 9; + + int heightPosition; + + int cropsA; + int cropsB; + int cropsC; + int cropsD; + + int selectCrops(Random* random); + + public: + DoubleFarmland(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* stairsBox, int direction); + static DoubleFarmland* createPiece(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction, + int genDepth); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); + }; + +public: + class LightPost : public VillagePiece { + private: + static const int width = 3; static const int height = 4; static const int depth = 2; int heightPosition; - public: - LightPost(StartPiece *startPiece, int genDepth, Random *random, BoundingBox *box, int direction); - static BoundingBox *findPieceBox(StartPiece *startPiece, std::list *pieces, Random *random, int footX, int footY, int footZ, int direction); - virtual bool postProcess(Level *level, Random *random, BoundingBox *chunkBB); + public: + LightPost(StartPiece* startPiece, int genDepth, Random* random, + BoundingBox* box, int direction); + static BoundingBox* findPieceBox(StartPiece* startPiece, + std::list* pieces, + Random* random, int footX, int footY, + int footZ, int direction); + virtual bool postProcess(Level* level, Random* random, + BoundingBox* chunkBB); }; }; diff --git a/Minecraft.World/WorldGen/Structures/Villages.cpp b/Minecraft.World/WorldGen/Structures/Villages.cpp index c9a3639f5..34bb25098 100644 --- a/Minecraft.World/WorldGen/Structures/Villages.cpp +++ b/Minecraft.World/WorldGen/Structures/Villages.cpp @@ -8,246 +8,217 @@ const std::wstring Villages::VILLAGE_FILE_ID = L"villages"; -Villages::Villages(const std::wstring &id) : SavedData(id) -{ - _tick = 0; - level = NULL; +Villages::Villages(const std::wstring& id) : SavedData(id) { + _tick = 0; + level = NULL; } -Villages::Villages(Level *level) : SavedData(VILLAGE_FILE_ID) -{ - _tick = 0; - this->level = level; +Villages::Villages(Level* level) : SavedData(VILLAGE_FILE_ID) { + _tick = 0; + this->level = level; } -Villages::~Villages() -{ - for(AUTO_VAR(it,queries.begin()); it != queries.end(); ++it) delete *it; +Villages::~Villages() { + for (AUTO_VAR(it, queries.begin()); it != queries.end(); ++it) delete *it; } -void Villages::setLevel(Level *level) -{ - this->level = level; +void Villages::setLevel(Level* level) { + this->level = level; - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) - { - std::shared_ptr village = *it; - village->setLevel(level); - } + // for (Village village : villages) + for (AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) { + std::shared_ptr village = *it; + village->setLevel(level); + } } -void Villages::queryUpdateAround(int x, int y, int z) -{ - if (queries.size() > 64) return; - if (!hasQuery(x, y, z)) queries.push_back(new Pos(x, y, z)); +void Villages::queryUpdateAround(int x, int y, int z) { + if (queries.size() > 64) return; + if (!hasQuery(x, y, z)) queries.push_back(new Pos(x, y, z)); } -void Villages::tick() -{ - ++_tick; - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) - { - std::shared_ptr village = *it; - village->tick(_tick); - } - removeVillages(); - processNextQuery(); - cluster(); +void Villages::tick() { + ++_tick; + // for (Village village : villages) + for (AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) { + std::shared_ptr village = *it; + village->tick(_tick); + } + removeVillages(); + processNextQuery(); + cluster(); - if ((_tick % 400) == 0) - { - setDirty(); - } + if ((_tick % 400) == 0) { + setDirty(); + } } -void Villages::removeVillages() -{ - //for (Iterator it = villages.iterator(); it.hasNext();) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ) - { - std::shared_ptr village = *it; //it.next(); - if (village->canRemove()) - { - it = villages.erase(it); - //it.remove(); - setDirty(); - } - else - { - ++it; - } - } +void Villages::removeVillages() { + // for (Iterator it = villages.iterator(); it.hasNext();) + for (AUTO_VAR(it, villages.begin()); it != villages.end();) { + std::shared_ptr village = *it; // it.next(); + if (village->canRemove()) { + it = villages.erase(it); + // it.remove(); + setDirty(); + } else { + ++it; + } + } } -std::vector > *Villages::getVillages() -{ - return &villages; +std::vector >* Villages::getVillages() { + return &villages; } -std::shared_ptr Villages::getClosestVillage(int x, int y, int z, int maxDist) -{ - std::shared_ptr closest = nullptr; - float closestDistSqr = Float::MAX_VALUE; - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) - { - std::shared_ptr village = *it; - float distSqr = village->getCenter()->distSqr(x, y, z); - if (distSqr >= closestDistSqr) continue; +std::shared_ptr Villages::getClosestVillage(int x, int y, int z, + int maxDist) { + std::shared_ptr closest = nullptr; + float closestDistSqr = Float::MAX_VALUE; + // for (Village village : villages) + for (AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) { + std::shared_ptr village = *it; + float distSqr = village->getCenter()->distSqr(x, y, z); + if (distSqr >= closestDistSqr) continue; - float requiredDist = maxDist + village->getRadius(); - if (distSqr > requiredDist * requiredDist) continue; + float requiredDist = maxDist + village->getRadius(); + if (distSqr > requiredDist * requiredDist) continue; - closest = village; - closestDistSqr = distSqr; - } - return closest; + closest = village; + closestDistSqr = distSqr; + } + return closest; } -void Villages::processNextQuery() -{ - if (queries.empty()) return; - Pos *q = queries.front(); - queries.pop_front(); - addDoorInfos(q); - delete q; +void Villages::processNextQuery() { + if (queries.empty()) return; + Pos* q = queries.front(); + queries.pop_front(); + addDoorInfos(q); + delete q; } -void Villages::cluster() -{ - // note doesn't merge or split existing villages - //for (int i = 0; i < unclustered.size(); ++i) - for(AUTO_VAR(it, unclustered.begin()); it != unclustered.end(); ++it) - { - std::shared_ptr di = *it; //unclustered.get(i); +void Villages::cluster() { + // note doesn't merge or split existing villages + // for (int i = 0; i < unclustered.size(); ++i) + for (AUTO_VAR(it, unclustered.begin()); it != unclustered.end(); ++it) { + std::shared_ptr di = *it; // unclustered.get(i); - bool found = false; - //for (Village village : villages) - for(AUTO_VAR(itV, villages.begin()); itV != villages.end(); ++itV) - { - std::shared_ptr village = *itV; - int dist = (int) village->getCenter()->distSqr(di->x, di->y, di->z); - int radius = MaxDoorDist + village->getRadius(); - if (dist > radius * radius) continue; - village->addDoorInfo(di); - found = true; - break; - } - if (found) continue; + bool found = false; + // for (Village village : villages) + for (AUTO_VAR(itV, villages.begin()); itV != villages.end(); ++itV) { + std::shared_ptr village = *itV; + int dist = (int)village->getCenter()->distSqr(di->x, di->y, di->z); + int radius = MaxDoorDist + village->getRadius(); + if (dist > radius * radius) continue; + village->addDoorInfo(di); + found = true; + break; + } + if (found) continue; - // create new Village - std::shared_ptr village = std::shared_ptr(new Village(level)); - village->addDoorInfo(di); - villages.push_back(village); - setDirty(); - } - unclustered.clear(); + // create new Village + std::shared_ptr village = + std::shared_ptr(new Village(level)); + village->addDoorInfo(di); + villages.push_back(village); + setDirty(); + } + unclustered.clear(); } -void Villages::addDoorInfos(Pos *pos) -{ - int scanX = 16, scanY = 4, scanZ = 16; - for (int xx = pos->x - scanX; xx < pos->x + scanX; xx++) - { - for (int yy = pos->y - scanY; yy < pos->y + scanY; yy++) - { - for (int zz = pos->z - scanZ; zz < pos->z + scanZ; zz++) - { - if (isDoor(xx, yy, zz)) - { - std::shared_ptr currentDoor = getDoorInfo(xx, yy, zz); - if (currentDoor == NULL) createDoorInfo(xx, yy, zz); - else currentDoor->timeStamp = _tick; - } - } - } - } +void Villages::addDoorInfos(Pos* pos) { + int scanX = 16, scanY = 4, scanZ = 16; + for (int xx = pos->x - scanX; xx < pos->x + scanX; xx++) { + for (int yy = pos->y - scanY; yy < pos->y + scanY; yy++) { + for (int zz = pos->z - scanZ; zz < pos->z + scanZ; zz++) { + if (isDoor(xx, yy, zz)) { + std::shared_ptr currentDoor = + getDoorInfo(xx, yy, zz); + if (currentDoor == NULL) + createDoorInfo(xx, yy, zz); + else + currentDoor->timeStamp = _tick; + } + } + } + } } -std::shared_ptr Villages::getDoorInfo(int x, int y, int z) -{ - //for (DoorInfo di : unclustered) - for(AUTO_VAR(it,unclustered.begin()); it != unclustered.end(); ++it) - { - std::shared_ptr di = *it; - if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; - } - //for (Village v : villages) - for(AUTO_VAR(it,villages.begin()); it != villages.end(); ++it) - { - std::shared_ptr v = *it; - std::shared_ptr di = v->getDoorInfo(x, y, z); - if (di != NULL) return di; - } - return nullptr; +std::shared_ptr Villages::getDoorInfo(int x, int y, int z) { + // for (DoorInfo di : unclustered) + for (AUTO_VAR(it, unclustered.begin()); it != unclustered.end(); ++it) { + std::shared_ptr di = *it; + if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; + } + // for (Village v : villages) + for (AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) { + std::shared_ptr v = *it; + std::shared_ptr di = v->getDoorInfo(x, y, z); + if (di != NULL) return di; + } + return nullptr; } -void Villages::createDoorInfo(int x, int y, int z) -{ - int dir = ((DoorTile *) Tile::door_wood)->getDir(level, x, y, z); - if (dir == 0 || dir == 2) - { - int canSeeX = 0; - for (int i = -5; i < 0; ++i) - if (level->canSeeSky(x + i, y, z)) canSeeX--; - for (int i = 1; i <= 5; ++i) - if (level->canSeeSky(x + i, y, z)) canSeeX++; - if (canSeeX != 0) unclustered.push_back(std::shared_ptr(new DoorInfo(x, y, z, canSeeX > 0 ? -2 : 2, 0, _tick))); - } - else - { - int canSeeZ = 0; - for (int i = -5; i < 0; ++i) - if (level->canSeeSky(x, y, z + i)) canSeeZ--; - for (int i = 1; i <= 5; ++i) - if (level->canSeeSky(x, y, z + i)) canSeeZ++; - if (canSeeZ != 0) unclustered.push_back(std::shared_ptr(new DoorInfo(x, y, z, 0, canSeeZ > 0 ? -2 : 2, _tick))); - } +void Villages::createDoorInfo(int x, int y, int z) { + int dir = ((DoorTile*)Tile::door_wood)->getDir(level, x, y, z); + if (dir == 0 || dir == 2) { + int canSeeX = 0; + for (int i = -5; i < 0; ++i) + if (level->canSeeSky(x + i, y, z)) canSeeX--; + for (int i = 1; i <= 5; ++i) + if (level->canSeeSky(x + i, y, z)) canSeeX++; + if (canSeeX != 0) + unclustered.push_back(std::shared_ptr( + new DoorInfo(x, y, z, canSeeX > 0 ? -2 : 2, 0, _tick))); + } else { + int canSeeZ = 0; + for (int i = -5; i < 0; ++i) + if (level->canSeeSky(x, y, z + i)) canSeeZ--; + for (int i = 1; i <= 5; ++i) + if (level->canSeeSky(x, y, z + i)) canSeeZ++; + if (canSeeZ != 0) + unclustered.push_back(std::shared_ptr( + new DoorInfo(x, y, z, 0, canSeeZ > 0 ? -2 : 2, _tick))); + } } -bool Villages::hasQuery(int x, int y, int z) -{ - //for (Pos pos : queries) - for(AUTO_VAR(it, queries.begin()); it != queries.end(); ++it) - { - Pos *pos = *it; - if (pos->x == x && pos->y == y && pos->z == z) return true; - } - return false; +bool Villages::hasQuery(int x, int y, int z) { + // for (Pos pos : queries) + for (AUTO_VAR(it, queries.begin()); it != queries.end(); ++it) { + Pos* pos = *it; + if (pos->x == x && pos->y == y && pos->z == z) return true; + } + return false; } -bool Villages::isDoor(int x, int y, int z) -{ - int tileId = level->getTile(x, y, z); - return tileId == Tile::door_wood_Id; +bool Villages::isDoor(int x, int y, int z) { + int tileId = level->getTile(x, y, z); + return tileId == Tile::door_wood_Id; } -void Villages::load(CompoundTag *tag) -{ - _tick = tag->getInt(L"Tick"); - ListTag *villageTags = (ListTag *) tag->getList(L"Villages"); - for (int i = 0; i < villageTags->size(); i++) - { - CompoundTag *compoundTag = villageTags->get(i); - std::shared_ptr village = std::shared_ptr(new Village()); - village->readAdditionalSaveData(compoundTag); - villages.push_back(village); - } +void Villages::load(CompoundTag* tag) { + _tick = tag->getInt(L"Tick"); + ListTag* villageTags = + (ListTag*)tag->getList(L"Villages"); + for (int i = 0; i < villageTags->size(); i++) { + CompoundTag* compoundTag = villageTags->get(i); + std::shared_ptr village = + std::shared_ptr(new Village()); + village->readAdditionalSaveData(compoundTag); + villages.push_back(village); + } } -void Villages::save(CompoundTag *tag) -{ - tag->putInt(L"Tick", _tick); - ListTag *villageTags = new ListTag(L"Villages"); - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) - { - std::shared_ptr village = *it; - CompoundTag *villageTag = new CompoundTag(L"Village"); - village->addAdditonalSaveData(villageTag); - villageTags->add(villageTag); - } - tag->put(L"Villages", villageTags); +void Villages::save(CompoundTag* tag) { + tag->putInt(L"Tick", _tick); + ListTag* villageTags = new ListTag(L"Villages"); + // for (Village village : villages) + for (AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) { + std::shared_ptr village = *it; + CompoundTag* villageTag = new CompoundTag(L"Village"); + village->addAdditonalSaveData(villageTag); + villageTags->add(villageTag); + } + tag->put(L"Villages", villageTags); } \ No newline at end of file diff --git a/Minecraft.World/WorldGen/Structures/Villages.h b/Minecraft.World/WorldGen/Structures/Villages.h index d0057d0a7..9ab55837f 100644 --- a/Minecraft.World/WorldGen/Structures/Villages.h +++ b/Minecraft.World/WorldGen/Structures/Villages.h @@ -2,46 +2,46 @@ #include "../../Level/Storage/SavedData.h" -class Villages : public SavedData -{ +class Villages : public SavedData { public: - static const std::wstring VILLAGE_FILE_ID; + static const std::wstring VILLAGE_FILE_ID; - static const int MaxDoorDist = 32; + static const int MaxDoorDist = 32; private: - Level *level; - std::deque queries; - std::vector > unclustered; - std::vector > villages; - int _tick; + Level* level; + std::deque queries; + std::vector > unclustered; + std::vector > villages; + int _tick; public: - Villages(const std::wstring &id); - Villages(Level *level); - ~Villages(); + Villages(const std::wstring& id); + Villages(Level* level); + ~Villages(); - void setLevel(Level *level); - void queryUpdateAround(int x, int y, int z); - void tick(); + void setLevel(Level* level); + void queryUpdateAround(int x, int y, int z); + void tick(); private: - void removeVillages(); + void removeVillages(); public: - std::vector > *getVillages(); - std::shared_ptr getClosestVillage(int x, int y, int z, int maxDist); + std::vector >* getVillages(); + std::shared_ptr getClosestVillage(int x, int y, int z, + int maxDist); private: - void processNextQuery(); - void cluster(); - void addDoorInfos(Pos *pos); - std::shared_ptrgetDoorInfo(int x, int y, int z); - void createDoorInfo(int x, int y, int z); - bool hasQuery(int x, int y, int z); - bool isDoor(int x, int y, int z); + void processNextQuery(); + void cluster(); + void addDoorInfos(Pos* pos); + std::shared_ptr getDoorInfo(int x, int y, int z); + void createDoorInfo(int x, int y, int z); + bool hasQuery(int x, int y, int z); + bool isDoor(int x, int y, int z); public: - void load(CompoundTag *tag); - void save(CompoundTag *tag); + void load(CompoundTag* tag); + void save(CompoundTag* tag); }; \ No newline at end of file From e8424f2000222490850d2a5227b6b6b0c0a5d6ce Mon Sep 17 00:00:00 2001 From: Tropical <42101043+tropicaaal@users.noreply.github.com> Date: Fri, 13 Mar 2026 17:10:10 -0500 Subject: [PATCH 2/5] chore: format `Minecraft.Client` --- Minecraft.Client/ClientConstants.cpp | 4 +- Minecraft.Client/ClientConstants.h | 23 +- Minecraft.Client/Commands/TeleportCommand.cpp | 156 +- Minecraft.Client/Commands/TeleportCommand.h | 11 +- Minecraft.Client/GameState/CreativeMode.cpp | 152 +- Minecraft.Client/GameState/CreativeMode.h | 41 +- Minecraft.Client/GameState/DemoMode.cpp | 141 +- Minecraft.Client/GameState/DemoMode.h | 31 +- Minecraft.Client/GameState/DemoUser.cpp | 4 +- Minecraft.Client/GameState/DemoUser.h | 5 +- Minecraft.Client/GameState/GameMode.cpp | 177 +- Minecraft.Client/GameState/GameMode.h | 73 +- Minecraft.Client/GameState/Options.cpp | 687 +- Minecraft.Client/GameState/Options.h | 147 +- Minecraft.Client/GameState/Settings.cpp | 74 +- Minecraft.Client/GameState/Settings.h | 19 +- Minecraft.Client/GameState/StatsCounter.cpp | 2966 ++-- Minecraft.Client/GameState/StatsCounter.h | 148 +- Minecraft.Client/GameState/StatsSyncer.h | 44 +- Minecraft.Client/GameState/SurvivalMode.cpp | 187 +- Minecraft.Client/GameState/SurvivalMode.h | 24 +- Minecraft.Client/Input/ConsoleInput.cpp | 8 +- Minecraft.Client/Input/ConsoleInput.h | 10 +- Minecraft.Client/Input/ConsoleInputSource.h | 7 +- Minecraft.Client/Input/Input.cpp | 161 +- Minecraft.Client/Input/Input.h | 14 +- Minecraft.Client/Input/KeyMapping.cpp | 7 +- Minecraft.Client/Input/KeyMapping.h | 9 +- Minecraft.Client/Level/DemoLevel.cpp | 27 +- Minecraft.Client/Level/DemoLevel.h | 15 +- Minecraft.Client/Level/DerivedServerLevel.cpp | 39 +- Minecraft.Client/Level/DerivedServerLevel.h | 12 +- Minecraft.Client/Level/MultiPlayerLevel.cpp | 1402 +- Minecraft.Client/Level/MultiPlayerLevel.h | 112 +- Minecraft.Client/Level/ServerLevel.cpp | 2256 ++- Minecraft.Client/Level/ServerLevel.h | 238 +- .../Level/ServerLevelListener.cpp | 182 +- Minecraft.Client/Level/ServerLevelListener.h | 40 +- Minecraft.Client/Linux/LinuxGL.h | 32 +- Minecraft.Client/Minecraft.cpp | 7698 ++++----- Minecraft.Client/Minecraft.h | 486 +- Minecraft.Client/MinecraftServer.cpp | 2526 +-- Minecraft.Client/MinecraftServer.h | 347 +- Minecraft.Client/Network/ClientConnection.cpp | 5495 +++---- Minecraft.Client/Network/ClientConnection.h | 210 +- .../Network/MultiPlayerChunkCache.cpp | 470 +- .../Network/MultiPlayerChunkCache.h | 57 +- .../Network/PendingConnection.cpp | 293 +- Minecraft.Client/Network/PendingConnection.h | 36 +- Minecraft.Client/Network/PlayerChunkMap.cpp | 1040 +- Minecraft.Client/Network/PlayerChunkMap.h | 129 +- Minecraft.Client/Network/PlayerConnection.cpp | 2964 ++-- Minecraft.Client/Network/PlayerConnection.h | 166 +- Minecraft.Client/Network/PlayerInfo.h | 17 +- Minecraft.Client/Network/PlayerList.cpp | 2162 +-- Minecraft.Client/Network/PlayerList.h | 156 +- Minecraft.Client/Network/ServerChunkCache.cpp | 1554 +- Minecraft.Client/Network/ServerChunkCache.h | 121 +- .../Network/ServerCommandDispatcher.cpp | 121 +- .../Network/ServerCommandDispatcher.h | 11 +- Minecraft.Client/Network/ServerConnection.cpp | 299 +- Minecraft.Client/Network/ServerConnection.h | 61 +- Minecraft.Client/Network/ServerInterface.h | 52 +- .../Platform/Linux/Iggy/gdraw/gdraw_glfw.c | 227 +- .../Platform/Linux/Iggy/gdraw/gdraw_glfw.h | 50 +- .../Leaderboards/LinuxLeaderboardManager.cpp | 4 +- .../Leaderboards/LinuxLeaderboardManager.h | 57 +- Minecraft.Client/Platform/Linux/LinuxGL.cpp | 184 +- Minecraft.Client/Platform/Linux/Linux_App.cpp | 123 +- Minecraft.Client/Platform/Linux/Linux_App.h | 44 +- .../Platform/Linux/Linux_Minecraft.cpp | 1408 +- .../Platform/Linux/Linux_ShutdownManager.cpp | 7 +- .../Platform/Linux/Linux_UIController.cpp | 138 +- .../Platform/Linux/Linux_UIController.h | 27 +- .../Platform/Linux/Social/SocialManager.h | 34 +- .../Stubs/DirectXMath/DirectXCollision.h | 702 +- .../Linux/Stubs/DirectXMath/DirectXColors.h | 776 +- .../Linux/Stubs/DirectXMath/DirectXMath.h | 4262 ++--- .../Stubs/DirectXMath/DirectXPackedVector.h | 2062 +-- .../Platform/Linux/Stubs/DirectXMath/sal.h | 4334 ++++-- .../Platform/Linux/Stubs/LinuxStubs.h | 2 +- .../Platform/Linux/Stubs/d3d11_stubs.h | 74 +- .../Platform/Linux/Stubs/iggy_stubs.h | 341 +- .../Platform/Linux/Stubs/winapi_stubs.h | 707 +- .../Platform/Linux/Stubs/xbox_stubs.h | 183 +- .../Platform/Linux/linux_game_stubs.cpp | 11 +- Minecraft.Client/Player/EntityTracker.cpp | 332 +- Minecraft.Client/Player/EntityTracker.h | 30 +- Minecraft.Client/Player/LocalPlayer.cpp | 2406 ++- Minecraft.Client/Player/LocalPlayer.h | 244 +- .../Player/MultiPlayerGameMode.cpp | 649 +- Minecraft.Client/Player/MultiPlayerGameMode.h | 93 +- .../Player/MultiPlayerLocalPlayer.cpp | 512 +- .../Player/MultiPlayerLocalPlayer.h | 94 +- Minecraft.Client/Player/RemotePlayer.cpp | 136 +- Minecraft.Client/Player/RemotePlayer.h | 33 +- Minecraft.Client/Player/ServerPlayer.cpp | 2433 +-- Minecraft.Client/Player/ServerPlayer.h | 212 +- .../Player/ServerPlayerGameMode.cpp | 556 +- .../Player/ServerPlayerGameMode.h | 48 +- Minecraft.Client/Player/TrackedEntity.cpp | 1700 +- Minecraft.Client/Player/TrackedEntity.h | 56 +- Minecraft.Client/Player/User.cpp | 8 +- Minecraft.Client/Player/User.h | 16 +- Minecraft.Client/Rendering/Camera.cpp | 116 +- Minecraft.Client/Rendering/Camera.h | 25 +- Minecraft.Client/Rendering/Chunk.cpp | 1770 +-- Minecraft.Client/Rendering/Chunk.h | 91 +- Minecraft.Client/Rendering/Cube.cpp | 149 +- Minecraft.Client/Rendering/Cube.h | 26 +- .../Rendering/Culling/AllowAllCuller.cpp | 25 +- .../Rendering/Culling/AllowAllCuller.h | 13 +- Minecraft.Client/Rendering/Culling/Culler.h | 13 +- .../Rendering/Culling/DirtyChunkSorter.cpp | 12 +- .../Rendering/Culling/DirtyChunkSorter.h | 12 +- .../Rendering/Culling/DistanceChunkSorter.cpp | 12 +- .../Rendering/Culling/DistanceChunkSorter.h | 7 +- .../Rendering/Culling/ViewportCuller.cpp | 186 +- .../Rendering/Culling/ViewportCuller.h | 38 +- .../EntityRenderers/ArrowRenderer.cpp | 95 +- .../Rendering/EntityRenderers/ArrowRenderer.h | 6 +- .../EntityRenderers/BlazeRenderer.cpp | 29 +- .../Rendering/EntityRenderers/BlazeRenderer.h | 10 +- .../EntityRenderers/BoatRenderer.cpp | 34 +- .../Rendering/EntityRenderers/BoatRenderer.h | 10 +- .../EntityRenderers/ChestRenderer.cpp | 156 +- .../Rendering/EntityRenderers/ChestRenderer.h | 15 +- .../EntityRenderers/ChickenRenderer.cpp | 27 +- .../EntityRenderers/ChickenRenderer.h | 11 +- .../Rendering/EntityRenderers/CowRenderer.cpp | 11 +- .../Rendering/EntityRenderers/CowRenderer.h | 8 +- .../EntityRenderers/CreeperRenderer.cpp | 53 +- .../EntityRenderers/CreeperRenderer.h | 13 +- .../EntityRenderers/DefaultRenderer.cpp | 9 +- .../EntityRenderers/DefaultRenderer.h | 6 +- .../EntityRenderers/EnchantTableRenderer.cpp | 75 +- .../EntityRenderers/EnchantTableRenderer.h | 18 +- .../EntityRenderers/EnderChestRenderer.cpp | 77 +- .../EntityRenderers/EnderChestRenderer.h | 9 +- .../EntityRenderers/EnderCrystalRenderer.cpp | 47 +- .../EntityRenderers/EnderCrystalRenderer.h | 12 +- .../EntityRenderers/EnderDragonRenderer.cpp | 442 +- .../EntityRenderers/EnderDragonRenderer.h | 25 +- .../EntityRenderers/EnderManRenderer.cpp | 152 +- .../EntityRenderers/EnderManRenderer.h | 16 +- .../EntityRenderDispatcher.cpp | 284 +- .../EntityRenderers/EntityRenderDispatcher.h | 55 +- .../EntityRenderers/EntityRenderer.cpp | 471 +- .../EntityRenderers/EntityRenderer.h | 76 +- .../EntityRenderers/EntityTileRenderer.cpp | 29 +- .../EntityRenderers/EntityTileRenderer.h | 23 +- .../EntityRenderers/ExperienceOrbRenderer.cpp | 134 +- .../EntityRenderers/ExperienceOrbRenderer.h | 14 +- .../EntityRenderers/FallingTileRenderer.cpp | 90 +- .../EntityRenderers/FallingTileRenderer.h | 11 +- .../EntityRenderers/FireballRenderer.cpp | 98 +- .../EntityRenderers/FireballRenderer.h | 15 +- .../EntityRenderers/FishingHookRenderer.cpp | 100 +- .../EntityRenderers/FishingHookRenderer.h | 8 +- .../EntityRenderers/GhastRenderer.cpp | 25 +- .../Rendering/EntityRenderers/GhastRenderer.h | 7 +- .../EntityRenderers/GiantMobRenderer.cpp | 13 +- .../EntityRenderers/GiantMobRenderer.h | 9 +- .../EntityRenderers/HumanoidMobRenderer.cpp | 175 +- .../EntityRenderers/HumanoidMobRenderer.h | 26 +- .../EntityRenderers/ItemFrameRenderer.cpp | 272 +- .../EntityRenderers/ItemFrameRenderer.h | 16 +- .../EntityRenderers/ItemInHandRenderer.cpp | 905 +- .../EntityRenderers/ItemInHandRenderer.h | 31 +- .../EntityRenderers/ItemRenderer.cpp | 1153 +- .../Rendering/EntityRenderers/ItemRenderer.h | 84 +- .../EntityRenderers/ItemSpriteRenderer.cpp | 83 +- .../EntityRenderers/ItemSpriteRenderer.h | 17 +- .../EntityRenderers/LavaSlimeRenderer.cpp | 54 +- .../EntityRenderers/LavaSlimeRenderer.h | 12 +- .../EntityRenderers/LightningBoltRenderer.cpp | 50 +- .../EntityRenderers/LightningBoltRenderer.h | 6 +- .../EntityRenderers/MinecartRenderer.cpp | 98 +- .../EntityRenderers/MinecartRenderer.h | 10 +- .../Rendering/EntityRenderers/MobRenderer.cpp | 749 +- .../Rendering/EntityRenderers/MobRenderer.h | 52 +- .../EntityRenderers/MobSpawnerRenderer.cpp | 22 +- .../EntityRenderers/MobSpawnerRenderer.h | 12 +- .../EntityRenderers/MushroomCowRenderer.cpp | 79 +- .../EntityRenderers/MushroomCowRenderer.h | 10 +- .../EntityRenderers/OcelotRenderer.cpp | 32 +- .../EntityRenderers/OcelotRenderer.h | 10 +- .../EntityRenderers/PaintingRenderer.cpp | 117 +- .../EntityRenderers/PaintingRenderer.h | 13 +- .../Rendering/EntityRenderers/PigRenderer.cpp | 28 +- .../Rendering/EntityRenderers/PigRenderer.h | 11 +- .../EntityRenderers/PistonPieceRenderer.cpp | 79 +- .../EntityRenderers/PistonPieceRenderer.h | 13 +- .../EntityRenderers/PlayerRenderer.cpp | 716 +- .../EntityRenderers/PlayerRenderer.h | 53 +- .../EntityRenderers/ProgressRenderer.cpp | 152 +- .../EntityRenderers/ProgressRenderer.h | 43 +- .../EntityRenderers/SheepRenderer.cpp | 45 +- .../Rendering/EntityRenderers/SheepRenderer.h | 10 +- .../EntityRenderers/SignRenderer.cpp | 130 +- .../Rendering/EntityRenderers/SignRenderer.h | 12 +- .../EntityRenderers/SilverfishRenderer.cpp | 24 +- .../EntityRenderers/SilverfishRenderer.h | 14 +- .../EntityRenderers/SkullTileRenderer.cpp | 174 +- .../EntityRenderers/SkullTileRenderer.h | 23 +- .../EntityRenderers/SlimeRenderer.cpp | 38 +- .../Rendering/EntityRenderers/SlimeRenderer.h | 11 +- .../EntityRenderers/SnowManRenderer.cpp | 50 +- .../EntityRenderers/SnowManRenderer.h | 9 +- .../EntityRenderers/SpiderRenderer.cpp | 74 +- .../EntityRenderers/SpiderRenderer.h | 10 +- .../EntityRenderers/SquidRenderer.cpp | 33 +- .../Rendering/EntityRenderers/SquidRenderer.h | 11 +- .../EntityRenderers/TheEndPortalRenderer.cpp | 200 +- .../EntityRenderers/TheEndPortalRenderer.h | 13 +- .../TileEntityRenderDispatcher.cpp | 159 +- .../TileEntityRenderDispatcher.h | 43 +- .../EntityRenderers/TileEntityRenderer.cpp | 31 +- .../EntityRenderers/TileEntityRenderer.h | 28 +- .../EntityRenderers/TileRenderer.cpp | 12875 ++++++++-------- .../Rendering/EntityRenderers/TileRenderer.h | 393 +- .../Rendering/EntityRenderers/TntRenderer.cpp | 39 +- .../Rendering/EntityRenderers/TntRenderer.h | 10 +- .../EntityRenderers/VillagerGolemRenderer.cpp | 100 +- .../EntityRenderers/VillagerGolemRenderer.h | 17 +- .../EntityRenderers/VillagerRenderer.cpp | 53 +- .../EntityRenderers/VillagerRenderer.h | 19 +- .../EntityRenderers/WolfRenderer.cpp | 57 +- .../Rendering/EntityRenderers/WolfRenderer.h | 8 +- .../EntityRenderers/ZombieRenderer.cpp | 123 +- .../EntityRenderers/ZombieRenderer.h | 33 +- Minecraft.Client/Rendering/Frustum.cpp | 104 +- Minecraft.Client/Rendering/Frustum.h | 25 +- Minecraft.Client/Rendering/FrustumCuller.cpp | 27 +- Minecraft.Client/Rendering/FrustumCuller.h | 20 +- Minecraft.Client/Rendering/FrustumData.cpp | 173 +- Minecraft.Client/Rendering/FrustumData.h | 37 +- Minecraft.Client/Rendering/GameRenderer.cpp | 3207 ++-- Minecraft.Client/Rendering/GameRenderer.h | 193 +- Minecraft.Client/Rendering/LevelRenderer.cpp | 6155 ++++---- Minecraft.Client/Rendering/LevelRenderer.h | 460 +- Minecraft.Client/Rendering/Lighting.cpp | 33 +- Minecraft.Client/Rendering/Lighting.h | 14 +- Minecraft.Client/Rendering/Minimap.cpp | 331 +- Minecraft.Client/Rendering/Minimap.h | 30 +- .../Rendering/Models/BlazeModel.cpp | 73 +- .../Rendering/Models/BlazeModel.h | 20 +- .../Rendering/Models/BoatModel.cpp | 84 +- Minecraft.Client/Rendering/Models/BoatModel.h | 9 +- .../Rendering/Models/BookModel.cpp | 103 +- Minecraft.Client/Rendering/Models/BookModel.h | 21 +- .../Rendering/Models/ChestModel.cpp | 62 +- .../Rendering/Models/ChestModel.h | 15 +- .../Rendering/Models/ChickenModel.cpp | 133 +- .../Rendering/Models/ChickenModel.h | 14 +- .../Rendering/Models/CowModel.cpp | 22 +- Minecraft.Client/Rendering/Models/CowModel.h | 9 +- .../Rendering/Models/CreeperModel.cpp | 58 +- .../Rendering/Models/CreeperModel.h | 15 +- .../Rendering/Models/DragonModel.cpp | 424 +- .../Rendering/Models/DragonModel.h | 44 +- .../Rendering/Models/EnderCrystalModel.cpp | 68 +- .../Rendering/Models/EnderCrystalModel.h | 17 +- .../Rendering/Models/EnderManModel.cpp | 184 +- .../Rendering/Models/EnderManModel.h | 13 +- .../Rendering/Models/GhastModel.cpp | 45 +- .../Rendering/Models/GhastModel.h | 17 +- .../Rendering/Models/HumanoidModel.cpp | 769 +- .../Rendering/Models/HumanoidModel.h | 102 +- .../Rendering/Models/LargeChestModel.cpp | 42 +- .../Rendering/Models/LargeChestModel.h | 5 +- .../Rendering/Models/LavaSlimeModel.cpp | 65 +- .../Rendering/Models/LavaSlimeModel.h | 20 +- .../Rendering/Models/MinecartModel.cpp | 34 +- .../Rendering/Models/MinecartModel.h | 11 +- Minecraft.Client/Rendering/Models/Model.cpp | 28 +- Minecraft.Client/Rendering/Models/Model.h | 45 +- .../Rendering/Models/ModelPart.cpp | 477 +- Minecraft.Client/Rendering/Models/ModelPart.h | 78 +- .../Rendering/Models/OcelotModel.cpp | 374 +- .../Rendering/Models/OcelotModel.h | 62 +- .../Rendering/Models/PigModel.cpp | 19 +- Minecraft.Client/Rendering/Models/PigModel.h | 8 +- .../Rendering/Models/QuadrupedModel.cpp | 172 +- .../Rendering/Models/QuadrupedModel.h | 17 +- .../Rendering/Models/SheepFurModel.cpp | 53 +- .../Rendering/Models/SheepFurModel.h | 17 +- .../Rendering/Models/SheepModel.cpp | 43 +- .../Rendering/Models/SheepModel.h | 17 +- .../Rendering/Models/SignModel.cpp | 19 +- Minecraft.Client/Rendering/Models/SignModel.h | 11 +- .../Rendering/Models/SilverfishModel.cpp | 157 +- .../Rendering/Models/SilverfishModel.h | 29 +- .../Rendering/Models/SkeletonHeadModel.cpp | 58 +- .../Rendering/Models/SkeletonHeadModel.h | 17 +- .../Rendering/Models/SkeletonModel.cpp | 42 +- .../Rendering/Models/SkeletonModel.h | 13 +- Minecraft.Client/Rendering/Models/SkinBox.h | 27 +- .../Rendering/Models/SlimeModel.cpp | 51 +- .../Rendering/Models/SlimeModel.h | 11 +- .../Rendering/Models/SnowManModel.cpp | 80 +- .../Rendering/Models/SnowManModel.h | 16 +- .../Rendering/Models/SpiderModel.cpp | 150 +- .../Rendering/Models/SpiderModel.h | 14 +- .../Rendering/Models/SquidModel.cpp | 46 +- .../Rendering/Models/SquidModel.h | 17 +- .../Rendering/Models/VillagerGolemModel.cpp | 132 +- .../Rendering/Models/VillagerGolemModel.h | 34 +- .../Rendering/Models/VillagerModel.cpp | 110 +- .../Rendering/Models/VillagerModel.h | 15 +- .../Rendering/Models/VillagerZombieModel.cpp | 86 +- .../Rendering/Models/VillagerZombieModel.h | 14 +- .../Rendering/Models/WolfModel.cpp | 134 +- Minecraft.Client/Rendering/Models/WolfModel.h | 32 +- .../Rendering/Models/ZombieModel.cpp | 44 +- .../Rendering/Models/ZombieModel.h | 13 +- .../Rendering/OffsettedRenderList.cpp | 51 +- .../Rendering/OffsettedRenderList.h | 11 +- .../Particles/BreakingItemParticle.cpp | 78 +- .../Particles/BreakingItemParticle.h | 19 +- .../Rendering/Particles/BubbleParticle.cpp | 36 +- .../Rendering/Particles/BubbleParticle.h | 10 +- .../Rendering/Particles/CritParticle.cpp | 87 +- .../Rendering/Particles/CritParticle.h | 30 +- .../Rendering/Particles/CritParticle2.cpp | 142 +- .../Rendering/Particles/CritParticle2.h | 28 +- .../Particles/DragonBreathParticle.cpp | 99 +- .../Particles/DragonBreathParticle.h | 24 +- .../Rendering/Particles/DripParticle.cpp | 209 +- .../Rendering/Particles/DripParticle.h | 20 +- .../Particles/EnchantmentTableParticle.cpp | 101 +- .../Particles/EnchantmentTableParticle.h | 18 +- .../Rendering/Particles/EnderParticle.cpp | 100 +- .../Rendering/Particles/EnderParticle.h | 23 +- .../Rendering/Particles/ExplodeParticle.cpp | 69 +- .../Rendering/Particles/ExplodeParticle.h | 13 +- .../Rendering/Particles/FlameParticle.cpp | 57 +- .../Rendering/Particles/FlameParticle.h | 18 +- .../Rendering/Particles/FootstepParticle.cpp | 53 +- .../Rendering/Particles/FootstepParticle.h | 16 +- .../Rendering/Particles/GuiParticle.cpp | 26 +- .../Rendering/Particles/GuiParticle.h | 12 +- .../Rendering/Particles/GuiParticles.cpp | 28 +- .../Rendering/Particles/GuiParticles.h | 12 +- .../Rendering/Particles/HeartParticle.cpp | 32 +- .../Rendering/Particles/HeartParticle.h | 18 +- .../Particles/HugeExplosionParticle.cpp | 119 +- .../Particles/HugeExplosionParticle.h | 25 +- .../Particles/HugeExplosionSeedParticle.cpp | 56 +- .../Particles/HugeExplosionSeedParticle.h | 19 +- .../Rendering/Particles/LavaParticle.cpp | 33 +- .../Rendering/Particles/LavaParticle.h | 16 +- .../Particles/NetherPortalParticle.cpp | 109 +- .../Particles/NetherPortalParticle.h | 22 +- .../Rendering/Particles/NoteParticle.cpp | 73 +- .../Rendering/Particles/NoteParticle.h | 18 +- .../Rendering/Particles/Particle.cpp | 261 +- .../Rendering/Particles/Particle.h | 60 +- .../Rendering/Particles/ParticleEngine.cpp | 220 +- .../Rendering/Particles/ParticleEngine.h | 30 +- .../Particles/PlayerCloudParticle.cpp | 96 +- .../Rendering/Particles/PlayerCloudParticle.h | 15 +- .../Rendering/Particles/RedDustParticle.cpp | 50 +- .../Rendering/Particles/RedDustParticle.h | 18 +- .../Rendering/Particles/SmokeParticle.cpp | 54 +- .../Rendering/Particles/SmokeParticle.h | 19 +- .../Particles/SnowShovelParticle.cpp | 37 +- .../Rendering/Particles/SnowShovelParticle.h | 18 +- .../Rendering/Particles/SpellParticle.cpp | 82 +- .../Rendering/Particles/SpellParticle.h | 17 +- .../Rendering/Particles/SplashParticle.cpp | 8 +- .../Rendering/Particles/SplashParticle.h | 8 +- .../Rendering/Particles/SuspendedParticle.cpp | 50 +- .../Rendering/Particles/SuspendedParticle.h | 10 +- .../Particles/SuspendedTownParticle.cpp | 49 +- .../Particles/SuspendedTownParticle.h | 10 +- .../Particles/TakeAnimationParticle.cpp | 68 +- .../Particles/TakeAnimationParticle.h | 14 +- .../Rendering/Particles/TerrainParticle.cpp | 93 +- .../Rendering/Particles/TerrainParticle.h | 20 +- .../Rendering/Particles/WaterDropParticle.cpp | 32 +- .../Rendering/Particles/WaterDropParticle.h | 7 +- Minecraft.Client/Rendering/Polygon.cpp | 58 +- Minecraft.Client/Rendering/Polygon.h | 19 +- Minecraft.Client/Rendering/Tesselator.cpp | 1538 +- Minecraft.Client/Rendering/Tesselator.h | 215 +- Minecraft.Client/Rendering/TexOffs.cpp | 7 +- Minecraft.Client/Rendering/TexOffs.h | 7 +- Minecraft.Client/Rendering/Vertex.cpp | 16 +- Minecraft.Client/Rendering/Vertex.h | 16 +- Minecraft.Client/Rendering/glWrapper.cpp | 523 +- Minecraft.Client/Textures/BufferedImage.cpp | 602 +- Minecraft.Client/Textures/BufferedImage.h | 48 +- Minecraft.Client/Textures/ClockTexture.cpp | 166 +- Minecraft.Client/Textures/ClockTexture.h | 27 +- Minecraft.Client/Textures/CompassTexture.cpp | 205 +- Minecraft.Client/Textures/CompassTexture.h | 32 +- Minecraft.Client/Textures/HttpTexture.cpp | 8 +- Minecraft.Client/Textures/HttpTexture.h | 5 +- .../Textures/HttpTextureProcessor.h | 5 +- Minecraft.Client/Textures/MemTexture.cpp | 39 +- Minecraft.Client/Textures/MemTexture.h | 12 +- .../Textures/MemTextureProcessor.h | 7 +- .../Textures/MobSkinMemTextureProcessor.cpp | 38 +- .../Textures/MobSkinMemTextureProcessor.h | 12 +- .../Textures/MobSkinTextureProcessor.cpp | 35 +- .../Textures/MobSkinTextureProcessor.h | 12 +- .../Textures/Packs/AbstractTexturePack.cpp | 521 +- .../Textures/Packs/AbstractTexturePack.h | 123 +- .../Textures/Packs/DLCTexturePack.cpp | 945 +- .../Textures/Packs/DLCTexturePack.h | 101 +- .../Textures/Packs/DefaultTexturePack.cpp | 179 +- .../Textures/Packs/DefaultTexturePack.h | 38 +- .../Textures/Packs/FileTexturePack.cpp | 33 +- .../Textures/Packs/FileTexturePack.h | 25 +- .../Textures/Packs/FolderTexturePack.cpp | 121 +- .../Textures/Packs/FolderTexturePack.h | 27 +- .../Textures/Packs/TexturePack.cpp | 81 +- Minecraft.Client/Textures/Packs/TexturePack.h | 83 +- .../Textures/Packs/TexturePackRepository.cpp | 453 +- .../Textures/Packs/TexturePackRepository.h | 101 +- .../Stitching/PreStitchedTextureMap.cpp | 2906 +++- .../Stitching/PreStitchedTextureMap.h | 57 +- .../Textures/Stitching/StitchSlot.cpp | 270 +- .../Textures/Stitching/StitchSlot.h | 32 +- .../Textures/Stitching/StitchedTexture.cpp | 524 +- .../Textures/Stitching/StitchedTexture.h | 124 +- .../Textures/Stitching/Stitcher.cpp | 389 +- .../Textures/Stitching/Stitcher.h | 82 +- .../Textures/Stitching/TextureMap.cpp | 352 +- .../Textures/Stitching/TextureMap.h | 54 +- Minecraft.Client/Textures/Texture.cpp | 1221 +- Minecraft.Client/Textures/Texture.h | 142 +- Minecraft.Client/Textures/TextureHolder.cpp | 106 +- Minecraft.Client/Textures/TextureHolder.h | 42 +- Minecraft.Client/Textures/TextureManager.cpp | 326 +- Minecraft.Client/Textures/TextureManager.h | 48 +- Minecraft.Client/Textures/Textures.cpp | 1850 ++- Minecraft.Client/Textures/Textures.h | 482 +- Minecraft.Client/UI/Button.cpp | 65 +- Minecraft.Client/UI/Button.h | 24 +- Minecraft.Client/UI/EditBox.cpp | 111 +- Minecraft.Client/UI/EditBox.h | 13 +- Minecraft.Client/UI/Font.cpp | 799 +- Minecraft.Client/UI/Font.h | 111 +- Minecraft.Client/UI/Gui.cpp | 2198 +-- Minecraft.Client/UI/Gui.h | 83 +- Minecraft.Client/UI/GuiComponent.cpp | 124 +- Minecraft.Client/UI/GuiComponent.h | 18 +- Minecraft.Client/UI/GuiMessage.cpp | 7 +- Minecraft.Client/UI/GuiMessage.h | 10 +- Minecraft.Client/UI/Rect2i.cpp | 87 +- Minecraft.Client/UI/Rect2i.h | 33 +- Minecraft.Client/UI/Screen.cpp | 207 +- Minecraft.Client/UI/Screen.h | 58 +- Minecraft.Client/UI/ScreenSizeCalculator.cpp | 48 +- Minecraft.Client/UI/ScreenSizeCalculator.h | 11 +- .../UI/Screens/AbstractContainerScreen.cpp | 111 +- .../UI/Screens/AbstractContainerScreen.h | 36 +- .../UI/Screens/AchievementPopup.cpp | 30 +- .../UI/Screens/AchievementPopup.h | 20 +- .../UI/Screens/AchievementScreen.cpp | 114 +- .../UI/Screens/AchievementScreen.h | 35 +- Minecraft.Client/UI/Screens/ChatScreen.cpp | 73 +- Minecraft.Client/UI/Screens/ChatScreen.h | 25 +- Minecraft.Client/UI/Screens/ConfirmScreen.cpp | 42 +- Minecraft.Client/UI/Screens/ConfirmScreen.h | 19 +- Minecraft.Client/UI/Screens/ConnectScreen.cpp | 105 +- Minecraft.Client/UI/Screens/ConnectScreen.h | 22 +- .../UI/Screens/ContainerScreen.cpp | 28 +- Minecraft.Client/UI/Screens/ContainerScreen.h | 16 +- .../UI/Screens/ControlsScreen.cpp | 65 +- Minecraft.Client/UI/Screens/ControlsScreen.h | 29 +- .../UI/Screens/CraftingScreen.cpp | 17 +- Minecraft.Client/UI/Screens/CraftingScreen.h | 13 +- .../UI/Screens/CreateWorldScreen.cpp | 154 +- .../UI/Screens/CreateWorldScreen.h | 25 +- Minecraft.Client/UI/Screens/DeathScreen.cpp | 56 +- Minecraft.Client/UI/Screens/DeathScreen.h | 13 +- .../UI/Screens/DisconnectedScreen.cpp | 40 +- .../UI/Screens/DisconnectedScreen.h | 27 +- Minecraft.Client/UI/Screens/ErrorScreen.cpp | 19 +- Minecraft.Client/UI/Screens/ErrorScreen.h | 11 +- Minecraft.Client/UI/Screens/FurnaceScreen.cpp | 19 +- Minecraft.Client/UI/Screens/FurnaceScreen.h | 13 +- .../UI/Screens/InBedChatScreen.cpp | 65 +- Minecraft.Client/UI/Screens/InBedChatScreen.h | 20 +- .../UI/Screens/InventoryScreen.cpp | 44 +- Minecraft.Client/UI/Screens/InventoryScreen.h | 19 +- .../UI/Screens/JoinMultiplayerScreen.cpp | 110 +- .../UI/Screens/JoinMultiplayerScreen.h | 21 +- .../UI/Screens/NameEntryScreen.cpp | 57 +- Minecraft.Client/UI/Screens/NameEntryScreen.h | 26 +- Minecraft.Client/UI/Screens/OptionsScreen.cpp | 72 +- Minecraft.Client/UI/Screens/OptionsScreen.h | 23 +- Minecraft.Client/UI/Screens/PauseScreen.cpp | 83 +- Minecraft.Client/UI/Screens/PauseScreen.h | 21 +- .../UI/Screens/ReceivingLevelScreen.cpp | 41 +- .../UI/Screens/ReceivingLevelScreen.h | 27 +- .../UI/Screens/RenameWorldScreen.cpp | 56 +- .../UI/Screens/RenameWorldScreen.h | 18 +- .../UI/Screens/SelectWorldScreen.cpp | 300 +- .../UI/Screens/SelectWorldScreen.h | 67 +- Minecraft.Client/UI/Screens/StatsScreen.cpp | 784 +- Minecraft.Client/UI/Screens/StatsScreen.h | 127 +- .../UI/Screens/TextEditScreen.cpp | 80 +- Minecraft.Client/UI/Screens/TextEditScreen.h | 23 +- Minecraft.Client/UI/Screens/TitleScreen.cpp | 151 +- Minecraft.Client/UI/Screens/TitleScreen.h | 22 +- Minecraft.Client/UI/Screens/TrapScreen.cpp | 15 +- Minecraft.Client/UI/Screens/TrapScreen.h | 9 +- .../UI/Screens/VideoSettingsScreen.cpp | 73 +- .../UI/Screens/VideoSettingsScreen.h | 20 +- Minecraft.Client/UI/ScrolledSelectionList.cpp | 93 +- Minecraft.Client/UI/ScrolledSelectionList.h | 46 +- Minecraft.Client/UI/SimpleIcon.cpp | 13 +- Minecraft.Client/UI/SimpleIcon.h | 10 +- Minecraft.Client/UI/SlideButton.cpp | 41 +- Minecraft.Client/UI/SlideButton.h | 19 +- Minecraft.Client/UI/SmallButton.cpp | 25 +- Minecraft.Client/UI/SmallButton.h | 15 +- Minecraft.Client/Utils/ArchiveFile.cpp | 216 +- Minecraft.Client/Utils/ArchiveFile.h | 42 +- Minecraft.Client/Utils/MemoryTracker.cpp | 81 +- Minecraft.Client/Utils/MemoryTracker.h | 23 +- Minecraft.Client/Utils/StringTable.cpp | 232 +- Minecraft.Client/Utils/StringTable.h | 104 +- Minecraft.Client/Utils/Timer.cpp | 77 +- Minecraft.Client/Utils/Timer.h | 12 +- Minecraft.Client/Utils/WstringLookup.cpp | 70 +- Minecraft.Client/Utils/WstringLookup.h | 21 +- 531 files changed, 67709 insertions(+), 62690 deletions(-) diff --git a/Minecraft.Client/ClientConstants.cpp b/Minecraft.Client/ClientConstants.cpp index 55a7ab0ad..9ac5d55bf 100644 --- a/Minecraft.Client/ClientConstants.cpp +++ b/Minecraft.Client/ClientConstants.cpp @@ -1,4 +1,6 @@ #include "Platform/stdafx.h" #include "ClientConstants.h" -const std::wstring ClientConstants::VERSION_STRING = std::wstring(L"Minecraft Xbox ") + VER_FILEVERSION_STR_W;//+ SharedConstants::VERSION_STRING; \ No newline at end of file +const std::wstring ClientConstants::VERSION_STRING = + std::wstring(L"Minecraft Xbox ") + + VER_FILEVERSION_STR_W; //+ SharedConstants::VERSION_STRING; \ No newline at end of file diff --git a/Minecraft.Client/ClientConstants.h b/Minecraft.Client/ClientConstants.h index 8533f59f4..1abca946c 100644 --- a/Minecraft.Client/ClientConstants.h +++ b/Minecraft.Client/ClientConstants.h @@ -1,19 +1,16 @@ #pragma once +class ClientConstants { + // This file holds global constants used by the client. + // The file should be replaced at compile-time with the + // proper settings for the given compilation. For example, + // release builds should replace this file with no-cheat + // settings. -class ClientConstants -{ - - // This file holds global constants used by the client. - // The file should be replaced at compile-time with the - // proper settings for the given compilation. For example, - // release builds should replace this file with no-cheat - // settings. - - // INTERNAL DEVELOPMENT SETTINGS + // INTERNAL DEVELOPMENT SETTINGS public: - static const std::wstring VERSION_STRING; + static const std::wstring VERSION_STRING; - static const bool DEADMAU5_CAMERA_CHEATS = false; - static const bool IS_DEMO_VERSION = false; + static const bool DEADMAU5_CAMERA_CHEATS = false; + static const bool IS_DEMO_VERSION = false; }; \ No newline at end of file diff --git a/Minecraft.Client/Commands/TeleportCommand.cpp b/Minecraft.Client/Commands/TeleportCommand.cpp index 5b997d16e..8919ec833 100644 --- a/Minecraft.Client/Commands/TeleportCommand.cpp +++ b/Minecraft.Client/Commands/TeleportCommand.cpp @@ -9,82 +9,90 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h" #include "TeleportCommand.h" -EGameCommand TeleportCommand::getId() -{ - return eGameCommand_Teleport; +EGameCommand TeleportCommand::getId() { return eGameCommand_Teleport; } + +void TeleportCommand::execute(std::shared_ptr source, + byteArray commandData) { + ByteArrayInputStream bais(commandData); + DataInputStream dis(&bais); + + PlayerUID subjectID = dis.readPlayerUID(); + PlayerUID destinationID = dis.readPlayerUID(); + + bais.reset(); + + PlayerList* players = MinecraftServer::getInstance()->getPlayerList(); + + std::shared_ptr subject = players->getPlayer(subjectID); + std::shared_ptr destination = + players->getPlayer(destinationID); + + if (subject != NULL && destination != NULL && + subject->level->dimension->id == destination->level->dimension->id && + subject->isAlive()) { + subject->ride(nullptr); + subject->connection->teleport(destination->x, destination->y, + destination->z, destination->yRot, + destination->xRot); + // logAdminAction(source, "commands.tp.success", subject->getAName(), + // destination->getAName()); + logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess, + subject->getName(), eTYPE_SERVERPLAYER, + destination->getName()); + + if (subject == source) { + destination->sendMessage(subject->getName(), + ChatPacket::e_ChatCommandTeleportToMe); + } else { + subject->sendMessage(destination->getName(), + ChatPacket::e_ChatCommandTeleportMe); + } + } + + // if (args.length >= 1) { + // MinecraftServer server = MinecraftServer.getInstance(); + // ServerPlayer victim; + + // if (args.length == 2 || args.length == 4) { + // victim = server.getPlayers().getPlayer(args[0]); + // if (victim == null) throw new PlayerNotFoundException(); + // } else { + // victim = (ServerPlayer) convertSourceToPlayer(source); + // } + + // if (args.length == 3 || args.length == 4) { + // if (victim.level != null) { + // int pos = args.length - 3; + // int maxPos = Level.MAX_LEVEL_SIZE; + // int x = convertArgToInt(source, args[pos++], -maxPos, + //maxPos); int y = convertArgToInt(source, args[pos++], + //Level.minBuildHeight, Level.maxBuildHeight); int z = + //convertArgToInt(source, args[pos++], -maxPos, maxPos); + + // victim.teleportTo(x + 0.5f, y, z + 0.5f); + // logAdminAction(source, "commands.tp.coordinates", + //victim.getAName(), x, y, z); + // } + // } else if (args.length == 1 || args.length == 2) { + // ServerPlayer destination = + //server.getPlayers().getPlayer(args[args.length - 1]); if (destination == + //null) throw new PlayerNotFoundException(); + + // victim.connection.teleport(destination.x, destination.y, + //destination.z, destination.yRot, destination.xRot); logAdminAction(source, + //"commands.tp.success", victim.getAName(), destination.getAName()); + // } + //} } -void TeleportCommand::execute(std::shared_ptr source, byteArray commandData) -{ - ByteArrayInputStream bais(commandData); - DataInputStream dis(&bais); +std::shared_ptr TeleportCommand::preparePacket( + PlayerUID subject, PlayerUID destination) { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); - PlayerUID subjectID = dis.readPlayerUID(); - PlayerUID destinationID = dis.readPlayerUID(); - - bais.reset(); + dos.writePlayerUID(subject); + dos.writePlayerUID(destination); - PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - - std::shared_ptr subject = players->getPlayer(subjectID); - std::shared_ptr destination = players->getPlayer(destinationID); - - if(subject != NULL && destination != NULL && subject->level->dimension->id == destination->level->dimension->id && subject->isAlive() ) - { - subject->ride(nullptr); - subject->connection->teleport(destination->x, destination->y, destination->z, destination->yRot, destination->xRot); - //logAdminAction(source, "commands.tp.success", subject->getAName(), destination->getAName()); - logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess, subject->getName(), eTYPE_SERVERPLAYER, destination->getName()); - - if(subject == source) - { - destination->sendMessage(subject->getName(), ChatPacket::e_ChatCommandTeleportToMe); - } - else - { - subject->sendMessage(destination->getName(), ChatPacket::e_ChatCommandTeleportMe); - } - } - - //if (args.length >= 1) { - // MinecraftServer server = MinecraftServer.getInstance(); - // ServerPlayer victim; - - // if (args.length == 2 || args.length == 4) { - // victim = server.getPlayers().getPlayer(args[0]); - // if (victim == null) throw new PlayerNotFoundException(); - // } else { - // victim = (ServerPlayer) convertSourceToPlayer(source); - // } - - // if (args.length == 3 || args.length == 4) { - // if (victim.level != null) { - // int pos = args.length - 3; - // int maxPos = Level.MAX_LEVEL_SIZE; - // int x = convertArgToInt(source, args[pos++], -maxPos, maxPos); - // int y = convertArgToInt(source, args[pos++], Level.minBuildHeight, Level.maxBuildHeight); - // int z = convertArgToInt(source, args[pos++], -maxPos, maxPos); - - // victim.teleportTo(x + 0.5f, y, z + 0.5f); - // logAdminAction(source, "commands.tp.coordinates", victim.getAName(), x, y, z); - // } - // } else if (args.length == 1 || args.length == 2) { - // ServerPlayer destination = server.getPlayers().getPlayer(args[args.length - 1]); - // if (destination == null) throw new PlayerNotFoundException(); - - // victim.connection.teleport(destination.x, destination.y, destination.z, destination.yRot, destination.xRot); - // logAdminAction(source, "commands.tp.success", victim.getAName(), destination.getAName()); - // } - //} -} - -std::shared_ptr TeleportCommand::preparePacket(PlayerUID subject, PlayerUID destination) -{ - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - - dos.writePlayerUID(subject); - dos.writePlayerUID(destination); - - return std::shared_ptr( new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray() )); + return std::shared_ptr( + new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray())); } \ No newline at end of file diff --git a/Minecraft.Client/Commands/TeleportCommand.h b/Minecraft.Client/Commands/TeleportCommand.h index f17e728df..f42016ab1 100644 --- a/Minecraft.Client/Commands/TeleportCommand.h +++ b/Minecraft.Client/Commands/TeleportCommand.h @@ -2,11 +2,12 @@ #include "../../Minecraft.World/Commands/Command.h" -class TeleportCommand : public Command -{ +class TeleportCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); - static std::shared_ptr preparePacket(PlayerUID subject, PlayerUID destination); + static std::shared_ptr preparePacket( + PlayerUID subject, PlayerUID destination); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/CreativeMode.cpp b/Minecraft.Client/GameState/CreativeMode.cpp index aab4b6e8d..86cb9ecc5 100644 --- a/Minecraft.Client/GameState/CreativeMode.cpp +++ b/Minecraft.Client/GameState/CreativeMode.cpp @@ -10,121 +10,91 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -CreativeMode::CreativeMode(Minecraft *minecraft) : GameMode(minecraft) -{ - destroyDelay = 0; - instaBuild = true; +CreativeMode::CreativeMode(Minecraft* minecraft) : GameMode(minecraft) { + destroyDelay = 0; + instaBuild = true; } -void CreativeMode::init() -{ - // initPlayer(); +void CreativeMode::init() { + // initPlayer(); } -void CreativeMode::enableCreativeForPlayer(std::shared_ptr player) -{ - // please check ServerPlayerGameMode.java if you change these - player->abilities.mayfly = true; - player->abilities.instabuild = true; - player->abilities.invulnerable = true; +void CreativeMode::enableCreativeForPlayer(std::shared_ptr player) { + // please check ServerPlayerGameMode.java if you change these + player->abilities.mayfly = true; + player->abilities.instabuild = true; + player->abilities.invulnerable = true; } -void CreativeMode::disableCreativeForPlayer(std::shared_ptr player) -{ - player->abilities.mayfly = false; - player->abilities.flying = false; - player->abilities.instabuild = false; - player->abilities.invulnerable = false; +void CreativeMode::disableCreativeForPlayer(std::shared_ptr player) { + player->abilities.mayfly = false; + player->abilities.flying = false; + player->abilities.instabuild = false; + player->abilities.invulnerable = false; } -void CreativeMode::adjustPlayer(std::shared_ptr player) -{ - enableCreativeForPlayer(player); +void CreativeMode::adjustPlayer(std::shared_ptr player) { + enableCreativeForPlayer(player); - for (int i = 0; i < 9; i++) - { - if (player->inventory->items[i] == NULL) - { - player->inventory->items[i] = std::shared_ptr( new ItemInstance(User::allowedTiles[i]) ); - } - else - { - // 4J-PB - this line is commented out in 1.0.1 - //player->inventory->items[i]->count = 1; + for (int i = 0; i < 9; i++) { + if (player->inventory->items[i] == NULL) { + player->inventory->items[i] = std::shared_ptr( + new ItemInstance(User::allowedTiles[i])); + } else { + // 4J-PB - this line is commented out in 1.0.1 + // player->inventory->items[i]->count = 1; } } } -void CreativeMode::creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face) -{ - if(!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) - { - gameMode->destroyBlock(x, y, z, face); - } +void CreativeMode::creativeDestroyBlock(Minecraft* minecraft, + GameMode* gameMode, int x, int y, int z, + int face) { + if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) { + gameMode->destroyBlock(x, y, z, face); + } } -bool CreativeMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) -{ - int t = level->getTile(x, y, z); - if (t > 0) - { - if (Tile::tiles[t]->use(level, x, y, z, player)) return true; - } - if (item == NULL) return false; - int aux = item->getAuxValue(); - int count = item->count; - bool success = item->useOn(player, level, x, y, z, face); - item->setAuxValue(aux); - item->count = count; - return success; +bool CreativeMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly, + bool* pbUsedItem) { + int t = level->getTile(x, y, z); + if (t > 0) { + if (Tile::tiles[t]->use(level, x, y, z, player)) return true; + } + if (item == NULL) return false; + int aux = item->getAuxValue(); + int count = item->count; + bool success = item->useOn(player, level, x, y, z, face); + item->setAuxValue(aux); + item->count = count; + return success; } -void CreativeMode::startDestroyBlock(int x, int y, int z, int face) -{ - creativeDestroyBlock(minecraft, this, x, y, z, face); - destroyDelay = 5; +void CreativeMode::startDestroyBlock(int x, int y, int z, int face) { + creativeDestroyBlock(minecraft, this, x, y, z, face); + destroyDelay = 5; } -void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) -{ - destroyDelay--; - if (destroyDelay <= 0) - { - destroyDelay = 5; - creativeDestroyBlock(minecraft, this, x, y, z, face); - } +void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) { + destroyDelay--; + if (destroyDelay <= 0) { + destroyDelay = 5; + creativeDestroyBlock(minecraft, this, x, y, z, face); + } } -void CreativeMode::stopDestroyBlock() -{ -} +void CreativeMode::stopDestroyBlock() {} -bool CreativeMode::canHurtPlayer() -{ - return false; -} +bool CreativeMode::canHurtPlayer() { return false; } -void CreativeMode::initLevel(Level *level) -{ - GameMode::initLevel(level); -} +void CreativeMode::initLevel(Level* level) { GameMode::initLevel(level); } -float CreativeMode::getPickRange() -{ - return 5.0f; -} +float CreativeMode::getPickRange() { return 5.0f; } -bool CreativeMode::hasMissTime() -{ - return false; -} +bool CreativeMode::hasMissTime() { return false; } -bool CreativeMode::hasInfiniteItems() -{ - return true; -} +bool CreativeMode::hasInfiniteItems() { return true; } -bool CreativeMode::hasFarPickRange() -{ - return true; -} \ No newline at end of file +bool CreativeMode::hasFarPickRange() { return true; } \ No newline at end of file diff --git a/Minecraft.Client/GameState/CreativeMode.h b/Minecraft.Client/GameState/CreativeMode.h index 9732cfd0f..f98fd38e3 100644 --- a/Minecraft.Client/GameState/CreativeMode.h +++ b/Minecraft.Client/GameState/CreativeMode.h @@ -1,26 +1,29 @@ #pragma once #include "GameMode.h" -class CreativeMode : public GameMode -{ +class CreativeMode : public GameMode { private: - int destroyDelay; + int destroyDelay; public: - CreativeMode(Minecraft *minecraft); - virtual void init(); - static void enableCreativeForPlayer(std::shared_ptr player); - static void disableCreativeForPlayer(std::shared_ptr player); - virtual void adjustPlayer(std::shared_ptr player); - static void creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL); - virtual void startDestroyBlock(int x, int y, int z, int face); - virtual void continueDestroyBlock(int x, int y, int z, int face); - virtual void stopDestroyBlock(); - virtual bool canHurtPlayer(); - virtual void initLevel(Level *level); - virtual float getPickRange(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); + CreativeMode(Minecraft* minecraft); + virtual void init(); + static void enableCreativeForPlayer(std::shared_ptr player); + static void disableCreativeForPlayer(std::shared_ptr player); + virtual void adjustPlayer(std::shared_ptr player); + static void creativeDestroyBlock(Minecraft* minecraft, GameMode* gameMode, + int x, int y, int z, int face); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL); + virtual void startDestroyBlock(int x, int y, int z, int face); + virtual void continueDestroyBlock(int x, int y, int z, int face); + virtual void stopDestroyBlock(); + virtual bool canHurtPlayer(); + virtual void initLevel(Level* level); + virtual float getPickRange(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/DemoMode.cpp b/Minecraft.Client/GameState/DemoMode.cpp index 9ecb5cf05..7b9a01bc0 100644 --- a/Minecraft.Client/GameState/DemoMode.cpp +++ b/Minecraft.Client/GameState/DemoMode.cpp @@ -2,111 +2,107 @@ #include "DemoMode.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" -DemoMode::DemoMode(Minecraft *minecraft) : SurvivalMode(minecraft) -{ - demoHasEnded = false; +DemoMode::DemoMode(Minecraft* minecraft) : SurvivalMode(minecraft) { + demoHasEnded = false; demoEndedReminder = 0; } -void DemoMode::tick() -{ +void DemoMode::tick() { SurvivalMode::tick(); -/* 4J - TODO - seems unlikely we need this demo mode anyway - __int64 time = minecraft->level->getTime(); - __int64 day = (time / Level::TICKS_PER_DAY) + 1; + /* 4J - TODO - seems unlikely we need this demo mode anyway + __int64 time = minecraft->level->getTime(); + __int64 day = (time / Level::TICKS_PER_DAY) + 1; - demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS)); - if (demoHasEnded) - { - demoEndedReminder++; - } + demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS)); + if (demoHasEnded) + { + demoEndedReminder++; + } - if ((time % Level::TICKS_PER_DAY) == 500) - { - if (day <= (DEMO_DAYS + 1)) - { - minecraft->gui->displayClientMessage(L"demo.day." + _toString<__int64>(day)); + if ((time % Level::TICKS_PER_DAY) == 500) + { + if (day <= (DEMO_DAYS + 1)) + { + minecraft->gui->displayClientMessage(L"demo.day." + + _toString<__int64>(day)); + } } - } - else if (day == 1) - { - Options *options = minecraft->options; - std::wstring message; + else if (day == 1) + { + Options *options = minecraft->options; + std::wstring message; - if (time == 100) { - minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed()); - message = language.getElement("demo.help.movement"); - message = String.format(message, Keyboard.getKeyName(options.keyUp.key), Keyboard.getKeyName(options.keyLeft.key), Keyboard.getKeyName(options.keyDown.key), - Keyboard.getKeyName(options.keyRight.key)); - } else if (time == 175) { - message = language.getElement("demo.help.jump"); - message = String.format(message, Keyboard.getKeyName(options.keyJump.key)); - } else if (time == 250) { - message = language.getElement("demo.help.inventory"); - message = String.format(message, Keyboard.getKeyName(options.keyBuild.key)); + if (time == 100) { + minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed()); + message = language.getElement("demo.help.movement"); + message = String.format(message, + Keyboard.getKeyName(options.keyUp.key), + Keyboard.getKeyName(options.keyLeft.key), + Keyboard.getKeyName(options.keyDown.key), + Keyboard.getKeyName(options.keyRight.key)); + } else if (time == 175) { + message = language.getElement("demo.help.jump"); + message = String.format(message, + Keyboard.getKeyName(options.keyJump.key)); } else if (time == 250) { + message = language.getElement("demo.help.inventory"); + message = String.format(message, + Keyboard.getKeyName(options.keyBuild.key)); + } + if (message != null) { + minecraft.gui.addMessage(message); + } + } else if (day == DEMO_DAYS) { + if ((time % Level.TICKS_PER_DAY) == 22000) { + minecraft.gui.displayClientMessage("demo.day.warning"); + } } - if (message != null) { - minecraft.gui.addMessage(message); - } - } else if (day == DEMO_DAYS) { - if ((time % Level.TICKS_PER_DAY) == 22000) { - minecraft.gui.displayClientMessage("demo.day.warning"); - } - } -*/ + */ } -void DemoMode::outputDemoReminder() -{ -/* 4J - TODO - if (demoEndedReminder > 100) { - minecraft.gui.displayClientMessage("demo.reminder"); - demoEndedReminder = 0; - } - */ +void DemoMode::outputDemoReminder() { + /* 4J - TODO + if (demoEndedReminder > 100) { + minecraft.gui.displayClientMessage("demo.reminder"); + demoEndedReminder = 0; + } + */ } -void DemoMode::startDestroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +void DemoMode::startDestroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { outputDemoReminder(); return; } SurvivalMode::startDestroyBlock(x, y, z, face); } -void DemoMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +void DemoMode::continueDestroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { return; } SurvivalMode::continueDestroyBlock(x, y, z, face); } -bool DemoMode::destroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +bool DemoMode::destroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { return false; } return SurvivalMode::destroyBlock(x, y, z, face); } -bool DemoMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item) -{ - if (demoHasEnded) - { +bool DemoMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item) { + if (demoHasEnded) { outputDemoReminder(); return false; } return SurvivalMode::useItem(player, level, item); } -bool DemoMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face) -{ +bool DemoMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face) { if (demoHasEnded) { outputDemoReminder(); return false; @@ -114,10 +110,9 @@ bool DemoMode::useItemOn(std::shared_ptr player, Level *level, std::shar return SurvivalMode::useItemOn(player, level, item, x, y, z, face); } -void DemoMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ - if (demoHasEnded) - { +void DemoMode::attack(std::shared_ptr player, + std::shared_ptr entity) { + if (demoHasEnded) { outputDemoReminder(); return; } diff --git a/Minecraft.Client/GameState/DemoMode.h b/Minecraft.Client/GameState/DemoMode.h index 9b5f19401..3b6eee7b5 100644 --- a/Minecraft.Client/GameState/DemoMode.h +++ b/Minecraft.Client/GameState/DemoMode.h @@ -1,27 +1,32 @@ #pragma once #include "SurvivalMode.h" -class DemoMode : public SurvivalMode -{ +class DemoMode : public SurvivalMode { private: - static const int DEMO_DAYS = 5; + static const int DEMO_DAYS = 5; bool demoHasEnded; int demoEndedReminder; public: - DemoMode(Minecraft *minecraft); + DemoMode(Minecraft* minecraft); virtual void tick(); -private: - void outputDemoReminder(); -public: - using GameMode::useItem; - using SurvivalMode::useItemOn; - virtual void startDestroyBlock(int x, int y, int z, int face); +private: + void outputDemoReminder(); + +public: + using GameMode::useItem; + using SurvivalMode::useItemOn; + + virtual void startDestroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); }; diff --git a/Minecraft.Client/GameState/DemoUser.cpp b/Minecraft.Client/GameState/DemoUser.cpp index d44b29110..b38394972 100644 --- a/Minecraft.Client/GameState/DemoUser.cpp +++ b/Minecraft.Client/GameState/DemoUser.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "DemoUser.h" -DemoUser::DemoUser() : User(L"DemoUser", L"n/a") -{ -} \ No newline at end of file +DemoUser::DemoUser() : User(L"DemoUser", L"n/a") {} \ No newline at end of file diff --git a/Minecraft.Client/GameState/DemoUser.h b/Minecraft.Client/GameState/DemoUser.h index b987a7e3e..6a3818904 100644 --- a/Minecraft.Client/GameState/DemoUser.h +++ b/Minecraft.Client/GameState/DemoUser.h @@ -1,8 +1,7 @@ #pragma once #include "../Player/User.h" -class DemoUser : public User -{ +class DemoUser : public User { public: - DemoUser(); + DemoUser(); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/GameMode.cpp b/Minecraft.Client/GameState/GameMode.cpp index 1ef38ca7a..eddaa7612 100644 --- a/Minecraft.Client/GameState/GameMode.cpp +++ b/Minecraft.Client/GameState/GameMode.cpp @@ -11,60 +11,55 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" -GameMode::GameMode(Minecraft *minecraft) -{ - instaBuild = false; // 4J - added - this->minecraft = minecraft; +GameMode::GameMode(Minecraft* minecraft) { + instaBuild = false; // 4J - added + this->minecraft = minecraft; } -void GameMode::initLevel(Level *level) -{ -} +void GameMode::initLevel(Level* level) {} -bool GameMode::destroyBlock(int x, int y, int z, int face) -{ - Level *level = minecraft->level; - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; - if (oldTile == NULL) return false; +bool GameMode::destroyBlock(int x, int y, int z, int face) { + Level* level = minecraft->level; + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; + if (oldTile == NULL) return false; - // 4J - Let the rendering side of thing know we are about to destroy the tile, so we can synchronise collision with async render data upates. - minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x, y, z); - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + // 4J - Let the rendering side of thing know we are about to destroy the + // tile, so we can synchronise collision with async render data upates. + minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x, + y, z); + level->levelEvent( + LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); int data = level->getData(x, y, z); - // 4J - before we remove the tile, recalc the heightmap - setTile depends on this being valid to be able to do - // a quick update of skylighting when the block is removed, and there are cases with falling tiles where this can get out of sync - level->getChunkAt(x,z)->recalcHeightmapOnly(); + // 4J - before we remove the tile, recalc the heightmap - setTile depends on + // this being valid to be able to do a quick update of skylighting when the + // block is removed, and there are cases with falling tiles where this can + // get out of sync + level->getChunkAt(x, z)->recalcHeightmapOnly(); bool changed = level->setTile(x, y, z, 0); - if (oldTile != NULL && changed) - { + if (oldTile != NULL && changed) { oldTile->destroy(level, x, y, z, data); } return changed; } -void GameMode::render(float a) -{ +void GameMode::render(float a) {} + +bool GameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, bool bTestUseOnly) { + return false; } -bool GameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - return false; -} +void GameMode::initPlayer(std::shared_ptr player) {} -void GameMode::initPlayer(std::shared_ptr player) -{ -} +void GameMode::tick() {} -void GameMode::tick() -{ -} +void GameMode::adjustPlayer(std::shared_ptr player) {} -void GameMode::adjustPlayer(std::shared_ptr player) -{ -} - -//bool GameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly) +// bool GameMode::useItemOn(std::shared_ptr player, Level *level, +// std::shared_ptr item, int x, int y, int z, int face, bool +// bTestUseOnOnly) //{ // // 4J-PB - Adding a test only version to allow tooltips to be displayed // int t = level->getTile(x, y, z); @@ -74,9 +69,10 @@ void GameMode::adjustPlayer(std::shared_ptr player) // { // switch(t) // { -// case Tile::recordPlayer_Id: +// case Tile::recordPlayer_Id: // case Tile::bed_Id: // special case for a bed -// if (Tile::tiles[t]->TestUse(level, x, y, z, player )) +// if (Tile::tiles[t]->TestUse(level, x, y, z, +//player )) // { // return true; // } @@ -91,94 +87,73 @@ void GameMode::adjustPlayer(std::shared_ptr player) // break; // } // } -// else +// else // { -// if (Tile::tiles[t]->use(level, x, y, z, player )) return true; +// if (Tile::tiles[t]->use(level, x, y, z, player )) return +//true; // } // } -// -// if (item == NULL) return false; -// return item->useOn(player, level, x, y, z, face, bTestUseOnOnly); -//} +// +// if (item == NULL) return false; +// return item->useOn(player, level, x, y, z, face, bTestUseOnOnly); +// } - -std::shared_ptr GameMode::createPlayer(Level *level) -{ - return std::shared_ptr( new LocalPlayer(minecraft, level, minecraft->user, level->dimension->id) ); +std::shared_ptr GameMode::createPlayer(Level* level) { + return std::shared_ptr(new LocalPlayer( + minecraft, level, minecraft->user, level->dimension->id)); } -bool GameMode::interact(std::shared_ptr player, std::shared_ptr entity) -{ - return player->interact(entity); +bool GameMode::interact(std::shared_ptr player, + std::shared_ptr entity) { + return player->interact(entity); } -void GameMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ - player->attack(entity); +void GameMode::attack(std::shared_ptr player, + std::shared_ptr entity) { + player->attack(entity); } -std::shared_ptr GameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player) -{ - return nullptr; +std::shared_ptr GameMode::handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player) { + return nullptr; } -void GameMode::handleCloseInventory(int containerId, std::shared_ptr player) -{ +void GameMode::handleCloseInventory(int containerId, + std::shared_ptr player) { player->containerMenu->removed(player); - delete player->containerMenu; + delete player->containerMenu; player->containerMenu = player->inventoryMenu; } -void GameMode::handleInventoryButtonClick(int containerId, int buttonId) -{ +void GameMode::handleInventoryButtonClick(int containerId, int buttonId) {} +bool GameMode::isCutScene() { return false; } + +void GameMode::releaseUsingItem(std::shared_ptr player) { + player->releaseUsingItem(); } -bool GameMode::isCutScene() -{ - return false; -} +bool GameMode::hasExperience() { return false; } -void GameMode::releaseUsingItem(std::shared_ptr player) -{ - player->releaseUsingItem(); -} +bool GameMode::hasMissTime() { return true; } -bool GameMode::hasExperience() -{ - return false; -} +bool GameMode::hasInfiniteItems() { return false; } -bool GameMode::hasMissTime() -{ - return true; -} +bool GameMode::hasFarPickRange() { return false; } -bool GameMode::hasInfiniteItems() -{ - return false; -} +void GameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, + int i) {} -bool GameMode::hasFarPickRange() -{ - return false; -} +void GameMode::handleCreativeModeItemDrop( + std::shared_ptr clicked) {} -void GameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, int i) -{ -} - -void GameMode::handleCreativeModeItemDrop(std::shared_ptr clicked) -{ -} - -bool GameMode::handleCraftItem(int recipe, std::shared_ptr player) -{ - return true; +bool GameMode::handleCraftItem(int recipe, std::shared_ptr player) { + return true; } // 4J-PB -void GameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr player) -{ - player->SetDebugOptions(uiVal); +void GameMode::handleDebugOptions(unsigned int uiVal, + std::shared_ptr player) { + player->SetDebugOptions(uiVal); } diff --git a/Minecraft.Client/GameState/GameMode.h b/Minecraft.Client/GameState/GameMode.h index 71559708a..e1c14b467 100644 --- a/Minecraft.Client/GameState/GameMode.h +++ b/Minecraft.Client/GameState/GameMode.h @@ -8,17 +8,17 @@ class Entity; class Tutorial; -class GameMode -{ +class GameMode { protected: - Minecraft *minecraft; + Minecraft* minecraft; + public: - bool instaBuild; + bool instaBuild; - GameMode(Minecraft *minecraft); - virtual ~GameMode() {} + GameMode(Minecraft* minecraft); + virtual ~GameMode() {} - virtual void initLevel(Level *level) ; + virtual void initLevel(Level* level); virtual void startDestroyBlock(int x, int y, int z, int face) = 0; virtual bool destroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face) = 0; @@ -29,31 +29,44 @@ public: virtual void tick(); virtual bool canHurtPlayer() = 0; virtual void adjustPlayer(std::shared_ptr player); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL) = 0; + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly = false); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL) = 0; - virtual std::shared_ptr createPlayer(Level *level); - virtual bool interact(std::shared_ptr player, std::shared_ptr entity); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); - virtual std::shared_ptr handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player); - virtual void handleCloseInventory(int containerId, std::shared_ptr player); - virtual void handleInventoryButtonClick(int containerId, int buttonId); + virtual std::shared_ptr createPlayer(Level* level); + virtual bool interact(std::shared_ptr player, + std::shared_ptr entity); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); + virtual std::shared_ptr handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player); + virtual void handleCloseInventory(int containerId, + std::shared_ptr player); + virtual void handleInventoryButtonClick(int containerId, int buttonId); - virtual bool isCutScene(); - virtual void releaseUsingItem(std::shared_ptr player); - virtual bool hasExperience(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); - virtual void handleCreativeModeItemAdd(std::shared_ptr clicked, int i); - virtual void handleCreativeModeItemDrop(std::shared_ptr clicked); + virtual bool isCutScene(); + virtual void releaseUsingItem(std::shared_ptr player); + virtual bool hasExperience(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); + virtual void handleCreativeModeItemAdd( + std::shared_ptr clicked, int i); + virtual void handleCreativeModeItemDrop( + std::shared_ptr clicked); - // 4J Stu - Added so we can send packets for this in the network game - virtual bool handleCraftItem(int recipe, std::shared_ptr player); - virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr player); + // 4J Stu - Added so we can send packets for this in the network game + virtual bool handleCraftItem(int recipe, std::shared_ptr player); + virtual void handleDebugOptions(unsigned int uiVal, + std::shared_ptr player); - // 4J Stu - Added for tutorial checks - virtual bool isInputAllowed(int mapping) { return true; } - virtual bool isTutorial() { return false; } - virtual Tutorial *getTutorial() { return NULL; } + // 4J Stu - Added for tutorial checks + virtual bool isInputAllowed(int mapping) { return true; } + virtual bool isTutorial() { return false; } + virtual Tutorial* getTutorial() { return NULL; } }; diff --git a/Minecraft.Client/GameState/Options.cpp b/Minecraft.Client/GameState/Options.cpp index 06b08d5bd..556942464 100644 --- a/Minecraft.Client/GameState/Options.cpp +++ b/Minecraft.Client/GameState/Options.cpp @@ -14,100 +14,90 @@ #include "../../Minecraft.World/IO/Streams/DataOutputStream.h" #include "../../Minecraft.World/Util/StringHelpers.h" -// 4J - the Option sub-class used to be an java enumerated type, trying to emulate that functionality here -const Options::Option Options::Option::options[17] = -{ - Options::Option(L"options.music", true, false), - Options::Option(L"options.sound", true, false), - Options::Option(L"options.invertMouse", false, true), - Options::Option(L"options.sensitivity", true, false), - Options::Option(L"options.renderDistance", false, false), - Options::Option(L"options.viewBobbing", false, true), - Options::Option(L"options.anaglyph", false, true), - Options::Option(L"options.advancedOpengl", false, true), - Options::Option(L"options.framerateLimit", false, false), - Options::Option(L"options.difficulty", false, false), - Options::Option(L"options.graphics", false, false), - Options::Option(L"options.ao", false, true), - Options::Option(L"options.guiScale", false, false), - Options::Option(L"options.fov", true, false), - Options::Option(L"options.gamma", true, false), - Options::Option(L"options.renderClouds",false, true), - Options::Option(L"options.particles", false, false), +// 4J - the Option sub-class used to be an java enumerated type, trying to +// emulate that functionality here +const Options::Option Options::Option::options[17] = { + Options::Option(L"options.music", true, false), + Options::Option(L"options.sound", true, false), + Options::Option(L"options.invertMouse", false, true), + Options::Option(L"options.sensitivity", true, false), + Options::Option(L"options.renderDistance", false, false), + Options::Option(L"options.viewBobbing", false, true), + Options::Option(L"options.anaglyph", false, true), + Options::Option(L"options.advancedOpengl", false, true), + Options::Option(L"options.framerateLimit", false, false), + Options::Option(L"options.difficulty", false, false), + Options::Option(L"options.graphics", false, false), + Options::Option(L"options.ao", false, true), + Options::Option(L"options.guiScale", false, false), + Options::Option(L"options.fov", true, false), + Options::Option(L"options.gamma", true, false), + Options::Option(L"options.renderClouds", false, true), + Options::Option(L"options.particles", false, false), }; -const Options::Option *Options::Option::MUSIC = &Options::Option::options[0]; -const Options::Option *Options::Option::SOUND = &Options::Option::options[1]; -const Options::Option *Options::Option::INVERT_MOUSE = &Options::Option::options[2]; -const Options::Option *Options::Option::SENSITIVITY = &Options::Option::options[3]; -const Options::Option *Options::Option::RENDER_DISTANCE = &Options::Option::options[4]; -const Options::Option *Options::Option::VIEW_BOBBING = &Options::Option::options[5]; -const Options::Option *Options::Option::ANAGLYPH = &Options::Option::options[6]; -const Options::Option *Options::Option::ADVANCED_OPENGL = &Options::Option::options[7]; -const Options::Option *Options::Option::FRAMERATE_LIMIT = &Options::Option::options[8]; -const Options::Option *Options::Option::DIFFICULTY = &Options::Option::options[9]; -const Options::Option *Options::Option::GRAPHICS = &Options::Option::options[10]; -const Options::Option *Options::Option::AMBIENT_OCCLUSION = &Options::Option::options[11]; -const Options::Option *Options::Option::GUI_SCALE = &Options::Option::options[12]; -const Options::Option *Options::Option::FOV = &Options::Option::options[13]; -const Options::Option *Options::Option::GAMMA = &Options::Option::options[14]; -const Options::Option *Options::Option::RENDER_CLOUDS = &Options::Option::options[15]; -const Options::Option *Options::Option::PARTICLES = &Options::Option::options[16]; +const Options::Option* Options::Option::MUSIC = &Options::Option::options[0]; +const Options::Option* Options::Option::SOUND = &Options::Option::options[1]; +const Options::Option* Options::Option::INVERT_MOUSE = + &Options::Option::options[2]; +const Options::Option* Options::Option::SENSITIVITY = + &Options::Option::options[3]; +const Options::Option* Options::Option::RENDER_DISTANCE = + &Options::Option::options[4]; +const Options::Option* Options::Option::VIEW_BOBBING = + &Options::Option::options[5]; +const Options::Option* Options::Option::ANAGLYPH = &Options::Option::options[6]; +const Options::Option* Options::Option::ADVANCED_OPENGL = + &Options::Option::options[7]; +const Options::Option* Options::Option::FRAMERATE_LIMIT = + &Options::Option::options[8]; +const Options::Option* Options::Option::DIFFICULTY = + &Options::Option::options[9]; +const Options::Option* Options::Option::GRAPHICS = + &Options::Option::options[10]; +const Options::Option* Options::Option::AMBIENT_OCCLUSION = + &Options::Option::options[11]; +const Options::Option* Options::Option::GUI_SCALE = + &Options::Option::options[12]; +const Options::Option* Options::Option::FOV = &Options::Option::options[13]; +const Options::Option* Options::Option::GAMMA = &Options::Option::options[14]; +const Options::Option* Options::Option::RENDER_CLOUDS = + &Options::Option::options[15]; +const Options::Option* Options::Option::PARTICLES = + &Options::Option::options[16]; +const Options::Option* Options::Option::getItem(int id) { return &options[id]; } -const Options::Option *Options::Option::getItem(int id) -{ - return &options[id]; -} +Options::Option::Option(const std::wstring& captionId, bool hasProgress, + bool isBoolean) + : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) {} -Options::Option::Option(const std::wstring& captionId, bool hasProgress, bool isBoolean) : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) -{ -} +bool Options::Option::isProgress() const { return _isProgress; } -bool Options::Option::isProgress() const -{ - return _isProgress; -} +bool Options::Option::isBoolean() const { return _isBoolean; } -bool Options::Option::isBoolean() const -{ - return _isBoolean; -} +int Options::Option::getId() const { return (int)(this - options); } -int Options::Option::getId() const -{ - return (int)(this-options); -} +std::wstring Options::Option::getCaptionId() const { return captionId; } -std::wstring Options::Option::getCaptionId() const -{ - return captionId; -} +const std::wstring Options::RENDER_DISTANCE_NAMES[] = { + L"options.renderDistance.far", L"options.renderDistance.normal", + L"options.renderDistance.short", L"options.renderDistance.tiny"}; +const std::wstring Options::DIFFICULTY_NAMES[] = { + L"options.difficulty.peaceful", L"options.difficulty.easy", + L"options.difficulty.normal", L"options.difficulty.hard"}; +const std::wstring Options::GUI_SCALE[] = { + L"options.guiScale.auto", L"options.guiScale.small", + L"options.guiScale.normal", L"options.guiScale.large"}; +const std::wstring Options::FRAMERATE_LIMITS[] = { + L"performance.max", L"performance.balanced", L"performance.powersaver"}; -const std::wstring Options::RENDER_DISTANCE_NAMES[] = -{ - L"options.renderDistance.far", L"options.renderDistance.normal", L"options.renderDistance.short", L"options.renderDistance.tiny" -}; -const std::wstring Options::DIFFICULTY_NAMES[] = -{ - L"options.difficulty.peaceful", L"options.difficulty.easy", L"options.difficulty.normal", L"options.difficulty.hard" -}; -const std::wstring Options::GUI_SCALE[] = -{ - L"options.guiScale.auto", L"options.guiScale.small", L"options.guiScale.normal", L"options.guiScale.large" -}; -const std::wstring Options::FRAMERATE_LIMITS[] = -{ - L"performance.max", L"performance.balanced", L"performance.powersaver" -}; - -const std::wstring Options::PARTICLES[] = { - L"options.particles.all", L"options.particles.decreased", L"options.particles.minimal" -}; +const std::wstring Options::PARTICLES[] = {L"options.particles.all", + L"options.particles.decreased", + L"options.particles.minimal"}; // 4J added -void Options::init() -{ +void Options::init() { music = 1; sound = 1; sensitivity = 0.5f; @@ -116,16 +106,16 @@ void Options::init() bobView = true; anaglyph3d = false; advancedOpengl = false; - - //4JCRAFT V-Sync / VSync - #ifdef ENABLE_VSYNC + +// 4JCRAFT V-Sync / VSync +#ifdef ENABLE_VSYNC framerateLimit = 2; - #else +#else framerateLimit = 3; - #endif +#endif fancyGraphics = true; ambientOcclusion = true; - renderClouds = true; + renderClouds = true; skin = L"Default"; keyUp = new KeyMapping(L"key.forward", Keyboard::KEY_W); @@ -137,395 +127,348 @@ void Options::init() keyDrop = new KeyMapping(L"key.drop", Keyboard::KEY_Q); keyChat = new KeyMapping(L"key.chat", Keyboard::KEY_T); keySneak = new KeyMapping(L"key.sneak", Keyboard::KEY_LSHIFT); - keyAttack = new KeyMapping(L"key.attack", -100 + 0); + keyAttack = new KeyMapping(L"key.attack", -100 + 0); keyUse = new KeyMapping(L"key.use", -100 + 1); keyPlayerList = new KeyMapping(L"key.playerlist", Keyboard::KEY_TAB); keyPickItem = new KeyMapping(L"key.pickItem", -100 + 2); keyToggleFog = new KeyMapping(L"key.fog", Keyboard::KEY_F); - keyMappings[0] = keyAttack; - keyMappings[1] = keyUse; + keyMappings[0] = keyAttack; + keyMappings[1] = keyUse; keyMappings[2] = keyUp; - keyMappings[3] = keyLeft; - keyMappings[4] = keyDown; - keyMappings[5] = keyRight; - keyMappings[6] = keyJump; - keyMappings[7] = keySneak; - keyMappings[8] = keyDrop; - keyMappings[9] = keyBuild; - keyMappings[10] = keyChat; - keyMappings[11] = keyPlayerList; - keyMappings[12] = keyPickItem; - keyMappings[13] = keyToggleFog; + keyMappings[3] = keyLeft; + keyMappings[4] = keyDown; + keyMappings[5] = keyRight; + keyMappings[6] = keyJump; + keyMappings[7] = keySneak; + keyMappings[8] = keyDrop; + keyMappings[9] = keyBuild; + keyMappings[10] = keyChat; + keyMappings[11] = keyPlayerList; + keyMappings[12] = keyPickItem; + keyMappings[13] = keyToggleFog; - minecraft = NULL; - //optionsFile = NULL; + minecraft = NULL; + // optionsFile = NULL; - difficulty = 2; - hideGui = false; - thirdPersonView = false; - renderDebug = false; - lastMpIp = L""; + difficulty = 2; + hideGui = false; + thirdPersonView = false; + renderDebug = false; + lastMpIp = L""; - isFlying = false; - smoothCamera = false; - fixedCamera = false; - flySpeed = 1; - cameraSpeed = 1; - guiScale = 0; - particles = 0; - fov = 0; - gamma = 0; + isFlying = false; + smoothCamera = false; + fixedCamera = false; + flySpeed = 1; + cameraSpeed = 1; + guiScale = 0; + particles = 0; + fov = 0; + gamma = 0; } -Options::Options(Minecraft *minecraft, File workingDirectory) -{ - init(); - this->minecraft = minecraft; - optionsFile = File(workingDirectory, L"options.txt"); +Options::Options(Minecraft* minecraft, File workingDirectory) { + init(); + this->minecraft = minecraft; + optionsFile = File(workingDirectory, L"options.txt"); } -Options::Options() -{ - init(); -} +Options::Options() { init(); } -std::wstring Options::getKeyDescription(int i) -{ - Language *language = Language::getInstance(); +std::wstring Options::getKeyDescription(int i) { + Language* language = Language::getInstance(); return language->getElement(keyMappings[i]->name); } -std::wstring Options::getKeyMessage(int i) -{ - int key = keyMappings[i]->key; - if (key < 0) { - return I18n::get(L"key.mouseButton", key + 101); - } else { - return Keyboard::getKeyName(keyMappings[i]->key); - } +std::wstring Options::getKeyMessage(int i) { + int key = keyMappings[i]->key; + if (key < 0) { + return I18n::get(L"key.mouseButton", key + 101); + } else { + return Keyboard::getKeyName(keyMappings[i]->key); + } } -void Options::setKey(int i, int key) -{ +void Options::setKey(int i, int key) { keyMappings[i]->key = key; save(); } -void Options::set(const Options::Option *item, float fVal) -{ - if (item == Option::MUSIC) - { +void Options::set(const Options::Option* item, float fVal) { + if (item == Option::MUSIC) { music = fVal; #ifdef _XBOX - minecraft->soundEngine->updateMusicVolume(fVal*2.0f); + minecraft->soundEngine->updateMusicVolume(fVal * 2.0f); #else - minecraft->soundEngine->updateMusicVolume(fVal); + minecraft->soundEngine->updateMusicVolume(fVal); #endif } - if (item == Option::SOUND) - { + if (item == Option::SOUND) { sound = fVal; #ifdef _XBOX - minecraft->soundEngine->updateSoundEffectVolume(fVal*2.0f); + minecraft->soundEngine->updateSoundEffectVolume(fVal * 2.0f); #else - minecraft->soundEngine->updateSoundEffectVolume(fVal); + minecraft->soundEngine->updateSoundEffectVolume(fVal); #endif } - if (item == Option::SENSITIVITY) - { + if (item == Option::SENSITIVITY) { sensitivity = fVal; } - if (item == Option::FOV) - { - fov = fVal; - } - if (item == Option::GAMMA) - { - gamma = fVal; - } + if (item == Option::FOV) { + fov = fVal; + } + if (item == Option::GAMMA) { + gamma = fVal; + } } -void Options::toggle(const Options::Option *option, int dir) -{ +void Options::toggle(const Options::Option* option, int dir) { if (option == Option::INVERT_MOUSE) invertYMouse = !invertYMouse; - if (option == Option::RENDER_DISTANCE) viewDistance = (viewDistance + dir) & 3; + if (option == Option::RENDER_DISTANCE) + viewDistance = (viewDistance + dir) & 3; if (option == Option::GUI_SCALE) guiScale = (guiScale + dir) & 3; - if (option == Option::PARTICLES) particles = (particles + dir) % 3; + if (option == Option::PARTICLES) particles = (particles + dir) % 3; - // 4J-PB - changing - //if (option == Option::VIEW_BOBBING) bobView = !bobView; - if (option == Option::VIEW_BOBBING) ((dir==0)?bobView=false: bobView=true); - if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds; - if (option == Option::ADVANCED_OPENGL) - { + // 4J-PB - changing + // if (option == Option::VIEW_BOBBING) bobView = !bobView; + if (option == Option::VIEW_BOBBING) + ((dir == 0) ? bobView = false : bobView = true); + if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds; + if (option == Option::ADVANCED_OPENGL) { advancedOpengl = !advancedOpengl; minecraft->levelRenderer->allChanged(); } - if (option == Option::ANAGLYPH) - { + if (option == Option::ANAGLYPH) { anaglyph3d = !anaglyph3d; minecraft->textures->reloadAll(); } - if (option == Option::FRAMERATE_LIMIT) framerateLimit = (framerateLimit + dir + 3) % 3; + if (option == Option::FRAMERATE_LIMIT) + framerateLimit = (framerateLimit + dir + 3) % 3; - // 4J-PB - Change for Xbox - //if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3; - if (option == Option::DIFFICULTY) difficulty = (dir) & 3; + // 4J-PB - Change for Xbox + // if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3; + if (option == Option::DIFFICULTY) difficulty = (dir) & 3; - app.DebugPrintf("Option::DIFFICULTY = %d",difficulty); + app.DebugPrintf("Option::DIFFICULTY = %d", difficulty); - if (option == Option::GRAPHICS) - { + if (option == Option::GRAPHICS) { fancyGraphics = !fancyGraphics; minecraft->levelRenderer->allChanged(); } - if (option == Option::AMBIENT_OCCLUSION) - { + if (option == Option::AMBIENT_OCCLUSION) { ambientOcclusion = !ambientOcclusion; minecraft->levelRenderer->allChanged(); } - // 4J-PB - don't do the file save on the xbox + // 4J-PB - don't do the file save on the xbox // save(); - } -float Options::getProgressValue(const Options::Option *item) -{ - if (item == Option::FOV) return fov; - if (item == Option::GAMMA) return gamma; +float Options::getProgressValue(const Options::Option* item) { + if (item == Option::FOV) return fov; + if (item == Option::GAMMA) return gamma; if (item == Option::MUSIC) return music; if (item == Option::SOUND) return sound; if (item == Option::SENSITIVITY) return sensitivity; return 0; } -bool Options::getBooleanValue(const Options::Option *item) -{ - // 4J - was a switch statement which we can't do with our Option:: pointer types - if( item == Option::INVERT_MOUSE) return invertYMouse; - if( item == Option::VIEW_BOBBING) return bobView; - if( item == Option::ANAGLYPH) return anaglyph3d; - if( item == Option::ADVANCED_OPENGL) return advancedOpengl; - if( item == Option::AMBIENT_OCCLUSION) return ambientOcclusion; - if( item == Option::RENDER_CLOUDS) return renderClouds; - return false; +bool Options::getBooleanValue(const Options::Option* item) { + // 4J - was a switch statement which we can't do with our Option:: pointer + // types + if (item == Option::INVERT_MOUSE) return invertYMouse; + if (item == Option::VIEW_BOBBING) return bobView; + if (item == Option::ANAGLYPH) return anaglyph3d; + if (item == Option::ADVANCED_OPENGL) return advancedOpengl; + if (item == Option::AMBIENT_OCCLUSION) return ambientOcclusion; + if (item == Option::RENDER_CLOUDS) return renderClouds; + return false; } -std::wstring Options::getMessage(const Options::Option *item) -{ - // 4J TODO, should these std::wstrings append rather than add? +std::wstring Options::getMessage(const Options::Option* item) { + // 4J TODO, should these std::wstrings append rather than add? - Language *language = Language::getInstance(); + Language* language = Language::getInstance(); std::wstring caption = language->getElement(item->getCaptionId()) + L": "; - if (item->isProgress()) - { + if (item->isProgress()) { float progressValue = getProgressValue(item); - if (item == Option::SENSITIVITY) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.sensitivity.min"); + if (item == Option::SENSITIVITY) { + if (progressValue == 0) { + return caption + + language->getElement(L"options.sensitivity.min"); } - if (progressValue == 1) - { - return caption + language->getElement(L"options.sensitivity.max"); + if (progressValue == 1) { + return caption + + language->getElement(L"options.sensitivity.max"); } - return caption + _toString((int) (progressValue * 200)) + L"%"; - } else if (item == Option::FOV) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.fov.min"); - } - if (progressValue == 1) - { - return caption + language->getElement(L"options.fov.max"); - } - return caption + _toString((int) (70 + progressValue * 40)); - } else if (item == Option::GAMMA) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.gamma.min"); - } - if (progressValue == 1) - { - return caption + language->getElement(L"options.gamma.max"); - } - return caption + L"+" + _toString((int) (progressValue * 100)) + L"%"; - } - else - { - if (progressValue == 0) - { + return caption + _toString((int)(progressValue * 200)) + L"%"; + } else if (item == Option::FOV) { + if (progressValue == 0) { + return caption + language->getElement(L"options.fov.min"); + } + if (progressValue == 1) { + return caption + language->getElement(L"options.fov.max"); + } + return caption + _toString((int)(70 + progressValue * 40)); + } else if (item == Option::GAMMA) { + if (progressValue == 0) { + return caption + language->getElement(L"options.gamma.min"); + } + if (progressValue == 1) { + return caption + language->getElement(L"options.gamma.max"); + } + return caption + L"+" + _toString((int)(progressValue * 100)) + + L"%"; + } else { + if (progressValue == 0) { return caption + language->getElement(L"options.off"); } - return caption + _toString((int) (progressValue * 100)) + L"%"; + return caption + _toString((int)(progressValue * 100)) + L"%"; } - } else if (item->isBoolean()) - { - + } else if (item->isBoolean()) { bool booleanValue = getBooleanValue(item); - if (booleanValue) - { + if (booleanValue) { return caption + language->getElement(L"options.on"); } return caption + language->getElement(L"options.off"); - } - else if (item == Option::RENDER_DISTANCE) - { - return caption + language->getElement(RENDER_DISTANCE_NAMES[viewDistance]); - } - else if (item == Option::DIFFICULTY) - { + } else if (item == Option::RENDER_DISTANCE) { + return caption + + language->getElement(RENDER_DISTANCE_NAMES[viewDistance]); + } else if (item == Option::DIFFICULTY) { return caption + language->getElement(DIFFICULTY_NAMES[difficulty]); - } - else if (item == Option::GUI_SCALE) - { + } else if (item == Option::GUI_SCALE) { return caption + language->getElement(GUI_SCALE[guiScale]); - } - else if (item == Option::PARTICLES) - { - return caption + language->getElement(PARTICLES[particles]); - } - else if (item == Option::FRAMERATE_LIMIT) - { + } else if (item == Option::PARTICLES) { + return caption + language->getElement(PARTICLES[particles]); + } else if (item == Option::FRAMERATE_LIMIT) { return caption + I18n::get(FRAMERATE_LIMITS[framerateLimit]); - } - else if (item == Option::GRAPHICS) - { - if (fancyGraphics) - { + } else if (item == Option::GRAPHICS) { + if (fancyGraphics) { return caption + language->getElement(L"options.graphics.fancy"); } return caption + language->getElement(L"options.graphics.fast"); } return caption; - } -void Options::load() -{ - // 4J - removed try/catch -// try { - if (!optionsFile.exists()) return; - // 4J - was new BufferedReader(new FileReader(optionsFile)); - BufferedReader *br = new BufferedReader(new InputStreamReader( new FileInputStream( optionsFile ) ) ); - - std::wstring line = L""; - while ((line = br->readLine()) != L"") // 4J - was check against NULL - do we need to distinguish between empty lines and a fail here? - { - // 4J - removed try/catch -// try { - std::wstring cmds[2]; - int splitpos = (int)line.find(L":"); - if( splitpos == std::wstring::npos ) - { - cmds[0] = line; - cmds[1] = L""; - } - else - { - cmds[0] = line.substr(0,splitpos); - cmds[1] = line.substr(splitpos,line.length()-splitpos); - } +void Options::load() { + // 4J - removed try/catch + // try { + if (!optionsFile.exists()) return; + // 4J - was new BufferedReader(new FileReader(optionsFile)); + BufferedReader* br = new BufferedReader( + new InputStreamReader(new FileInputStream(optionsFile))); - if (cmds[0] == L"music") music = readFloat(cmds[1]); - if (cmds[0] == L"sound") sound = readFloat(cmds[1]); - if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]); - if (cmds[0] == L"fov") fov = readFloat(cmds[1]); - if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]); - if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1]==L"true"; - if (cmds[0] == L"viewDistance") viewDistance = _fromString(cmds[1]); - if (cmds[0] == L"guiScale") guiScale =_fromString(cmds[1]); - if (cmds[0] == L"particles") particles = _fromString(cmds[1]); - if (cmds[0] == L"bobView") bobView = cmds[1]==L"true"; - if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1]==L"true"; - if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1]==L"true"; - if (cmds[0] == L"fpsLimit") framerateLimit = _fromString(cmds[1]); - if (cmds[0] == L"difficulty") difficulty = _fromString(cmds[1]); - if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1]==L"true"; - if (cmds[0] == L"ao") ambientOcclusion = cmds[1]==L"true"; - if (cmds[0] == L"clouds") renderClouds = cmds[1]==L"true"; - if (cmds[0] == L"skin") skin = cmds[1]; - if (cmds[0] == L"lastServer") lastMpIp = cmds[1]; - - for (int i = 0; i < keyMappings_length; i++) - { - if (cmds[0] == (L"key_" + keyMappings[i]->name)) - { - keyMappings[i]->key = _fromString(cmds[1]); - } - } -// } catch (Exception e) { -// System.out.println("Skipping bad option: " + line); -// } + std::wstring line = L""; + while ((line = br->readLine()) != + L"") // 4J - was check against NULL - do we need to distinguish + // between empty lines and a fail here? + { + // 4J - removed try/catch + // try { + std::wstring cmds[2]; + int splitpos = (int)line.find(L":"); + if (splitpos == std::wstring::npos) { + cmds[0] = line; + cmds[1] = L""; + } else { + cmds[0] = line.substr(0, splitpos); + cmds[1] = line.substr(splitpos, line.length() - splitpos); } - //KeyMapping.resetMapping(); // 4J Not implemented - br->close(); -// } catch (Exception e) { -// System.out.println("Failed to load options"); -// e.printStackTrace(); -// } + if (cmds[0] == L"music") music = readFloat(cmds[1]); + if (cmds[0] == L"sound") sound = readFloat(cmds[1]); + if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]); + if (cmds[0] == L"fov") fov = readFloat(cmds[1]); + if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]); + if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1] == L"true"; + if (cmds[0] == L"viewDistance") + viewDistance = _fromString(cmds[1]); + if (cmds[0] == L"guiScale") guiScale = _fromString(cmds[1]); + if (cmds[0] == L"particles") particles = _fromString(cmds[1]); + if (cmds[0] == L"bobView") bobView = cmds[1] == L"true"; + if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1] == L"true"; + if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1] == L"true"; + if (cmds[0] == L"fpsLimit") framerateLimit = _fromString(cmds[1]); + if (cmds[0] == L"difficulty") difficulty = _fromString(cmds[1]); + if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1] == L"true"; + if (cmds[0] == L"ao") ambientOcclusion = cmds[1] == L"true"; + if (cmds[0] == L"clouds") renderClouds = cmds[1] == L"true"; + if (cmds[0] == L"skin") skin = cmds[1]; + if (cmds[0] == L"lastServer") lastMpIp = cmds[1]; + + for (int i = 0; i < keyMappings_length; i++) { + if (cmds[0] == (L"key_" + keyMappings[i]->name)) { + keyMappings[i]->key = _fromString(cmds[1]); + } + } + // } catch (Exception e) { + // System.out.println("Skipping bad option: " + line); + // } + } + // KeyMapping.resetMapping(); // 4J Not implemented + br->close(); + // } catch (Exception e) { + // System.out.println("Failed to load options"); + // e.printStackTrace(); + // } } -float Options::readFloat(std::wstring string) -{ +float Options::readFloat(std::wstring string) { if (string == L"true") return 1; if (string == L"false") return 0; return _fromString(string); } -void Options::save() -{ - // 4J - try/catch removed -// try { +void Options::save() { + // 4J - try/catch removed + // try { - // 4J - original used a PrintWriter & FileWriter, but seems a bit much implementing these just to do this - FileOutputStream fos = FileOutputStream(optionsFile); - DataOutputStream dos = DataOutputStream(&fos); -// PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); + // 4J - original used a PrintWriter & FileWriter, but seems a bit much + // implementing these just to do this + FileOutputStream fos = FileOutputStream(optionsFile); + DataOutputStream dos = DataOutputStream(&fos); + // PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); - dos.writeChars(L"music:" + _toString(music) + L"\n"); - dos.writeChars(L"sound:" + _toString(sound) + L"\n"); - dos.writeChars(L"invertYMouse:" + std::wstring(invertYMouse ? L"true" : L"false") + L"\n"); - dos.writeChars(L"mouseSensitivity:" + _toString(sensitivity)); - dos.writeChars(L"fov:" + _toString(fov)); - dos.writeChars(L"gamma:" + _toString(gamma)); - dos.writeChars(L"viewDistance:" + _toString(viewDistance)); - dos.writeChars(L"guiScale:" + _toString(guiScale)); - dos.writeChars(L"particles:" + _toString(particles)); - dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false")); - dos.writeChars(L"anaglyph3d:" + std::wstring(anaglyph3d ? L"true" : L"false")); - dos.writeChars(L"advancedOpengl:" + std::wstring(advancedOpengl ? L"true" : L"false")); - dos.writeChars(L"fpsLimit:" + _toString(framerateLimit)); - dos.writeChars(L"difficulty:" + _toString(difficulty)); - dos.writeChars(L"fancyGraphics:" + std::wstring(fancyGraphics ? L"true" : L"false")); - dos.writeChars(L"ao:" + std::wstring(ambientOcclusion ? L"true" : L"false")); - dos.writeChars(L"clouds:" + _toString(renderClouds)); - dos.writeChars(L"skin:" + skin); - dos.writeChars(L"lastServer:" + lastMpIp); + dos.writeChars(L"music:" + _toString(music) + L"\n"); + dos.writeChars(L"sound:" + _toString(sound) + L"\n"); + dos.writeChars(L"invertYMouse:" + + std::wstring(invertYMouse ? L"true" : L"false") + L"\n"); + dos.writeChars(L"mouseSensitivity:" + _toString(sensitivity)); + dos.writeChars(L"fov:" + _toString(fov)); + dos.writeChars(L"gamma:" + _toString(gamma)); + dos.writeChars(L"viewDistance:" + _toString(viewDistance)); + dos.writeChars(L"guiScale:" + _toString(guiScale)); + dos.writeChars(L"particles:" + _toString(particles)); + dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false")); + dos.writeChars(L"anaglyph3d:" + + std::wstring(anaglyph3d ? L"true" : L"false")); + dos.writeChars(L"advancedOpengl:" + + std::wstring(advancedOpengl ? L"true" : L"false")); + dos.writeChars(L"fpsLimit:" + _toString(framerateLimit)); + dos.writeChars(L"difficulty:" + _toString(difficulty)); + dos.writeChars(L"fancyGraphics:" + + std::wstring(fancyGraphics ? L"true" : L"false")); + dos.writeChars(L"ao:" + + std::wstring(ambientOcclusion ? L"true" : L"false")); + dos.writeChars(L"clouds:" + _toString(renderClouds)); + dos.writeChars(L"skin:" + skin); + dos.writeChars(L"lastServer:" + lastMpIp); - for (int i = 0; i < keyMappings_length; i++) - { - dos.writeChars(L"key_" + keyMappings[i]->name + L":" + _toString(keyMappings[i]->key)); - } - - dos.close(); -// } catch (Exception e) { -// System.out.println("Failed to save options"); -// e.printStackTrace(); -// } + for (int i = 0; i < keyMappings_length; i++) { + dos.writeChars(L"key_" + keyMappings[i]->name + L":" + + _toString(keyMappings[i]->key)); + } + dos.close(); + // } catch (Exception e) { + // System.out.println("Failed to save options"); + // e.printStackTrace(); + // } } -bool Options::isCloudsOn() -{ - return viewDistance < 2 && renderClouds; -} +bool Options::isCloudsOn() { return viewDistance < 2 && renderClouds; } diff --git a/Minecraft.Client/GameState/Options.h b/Minecraft.Client/GameState/Options.h index b9d2d4928..b727da4a0 100644 --- a/Minecraft.Client/GameState/Options.h +++ b/Minecraft.Client/GameState/Options.h @@ -4,60 +4,58 @@ class Minecraft; class KeyMapping; #include "../../Minecraft.World/IO/Files/File.h" -class Options -{ +class Options { public: - static const int AO_OFF = 0; - static const int AO_MIN = 1; - static const int AO_MAX = 2; + static const int AO_OFF = 0; + static const int AO_MIN = 1; + static const int AO_MAX = 2; - // 4J - this used to be an enum - class Option - { - public: - static const Option options[17]; - static const Option *MUSIC; - static const Option *SOUND; - static const Option *INVERT_MOUSE; - static const Option *SENSITIVITY; - static const Option *RENDER_DISTANCE; - static const Option *VIEW_BOBBING; - static const Option *ANAGLYPH; - static const Option *ADVANCED_OPENGL; - static const Option *FRAMERATE_LIMIT; - static const Option *DIFFICULTY; - static const Option *GRAPHICS; - static const Option *AMBIENT_OCCLUSION; - static const Option *GUI_SCALE; - static const Option *FOV; - static const Option *GAMMA; - static const Option *RENDER_CLOUDS; - static const Option *PARTICLES; + // 4J - this used to be an enum + class Option { + public: + static const Option options[17]; + static const Option* MUSIC; + static const Option* SOUND; + static const Option* INVERT_MOUSE; + static const Option* SENSITIVITY; + static const Option* RENDER_DISTANCE; + static const Option* VIEW_BOBBING; + static const Option* ANAGLYPH; + static const Option* ADVANCED_OPENGL; + static const Option* FRAMERATE_LIMIT; + static const Option* DIFFICULTY; + static const Option* GRAPHICS; + static const Option* AMBIENT_OCCLUSION; + static const Option* GUI_SCALE; + static const Option* FOV; + static const Option* GAMMA; + static const Option* RENDER_CLOUDS; + static const Option* PARTICLES; - private: - const bool _isProgress; + private: + const bool _isProgress; const bool _isBoolean; const std::wstring captionId; - public: - static const Option *getItem(int id); + public: + static const Option* getItem(int id); Option(const std::wstring& captionId, bool hasProgress, bool isBoolean); - bool isProgress() const; - bool isBoolean() const; - int getId() const; - std::wstring getCaptionId() const; + bool isProgress() const; + bool isBoolean() const; + int getId() const; + std::wstring getCaptionId() const; }; private: - static const std::wstring RENDER_DISTANCE_NAMES[]; + static const std::wstring RENDER_DISTANCE_NAMES[]; static const std::wstring DIFFICULTY_NAMES[]; static const std::wstring GUI_SCALE[]; static const std::wstring FRAMERATE_LIMITS[]; - static const std::wstring PARTICLES[]; + static const std::wstring PARTICLES[]; public: - float music; + float music; float sound; float sensitivity; bool invertYMouse; @@ -68,34 +66,35 @@ public: int framerateLimit; bool fancyGraphics; bool ambientOcclusion; - bool renderClouds; + bool renderClouds; std::wstring skin; - KeyMapping *keyUp; - KeyMapping *keyLeft; - KeyMapping *keyDown; - KeyMapping *keyRight; - KeyMapping *keyJump; - KeyMapping *keyBuild; - KeyMapping *keyDrop; - KeyMapping *keyChat; - KeyMapping *keySneak; - KeyMapping *keyAttack; - KeyMapping *keyUse; - KeyMapping *keyPlayerList; - KeyMapping *keyPickItem; - KeyMapping *keyToggleFog; + KeyMapping* keyUp; + KeyMapping* keyLeft; + KeyMapping* keyDown; + KeyMapping* keyRight; + KeyMapping* keyJump; + KeyMapping* keyBuild; + KeyMapping* keyDrop; + KeyMapping* keyChat; + KeyMapping* keySneak; + KeyMapping* keyAttack; + KeyMapping* keyUse; + KeyMapping* keyPlayerList; + KeyMapping* keyPickItem; + KeyMapping* keyToggleFog; - static const int keyMappings_length = 14; - KeyMapping *keyMappings[keyMappings_length]; + static const int keyMappings_length = 14; + KeyMapping* keyMappings[keyMappings_length]; protected: - Minecraft *minecraft; + Minecraft* minecraft; + private: - File optionsFile; + File optionsFile; public: - int difficulty; + int difficulty; bool hideGui; bool thirdPersonView; bool renderDebug; @@ -107,26 +106,28 @@ public: float flySpeed; float cameraSpeed; int guiScale; - int particles; // 0 is all, 1 is decreased and 2 is minimal - float fov; - float gamma; + int particles; // 0 is all, 1 is decreased and 2 is minimal + float fov; + float gamma; - void init(); // 4J added - Options(Minecraft *minecraft, File workingDirectory); + void init(); // 4J added + Options(Minecraft* minecraft, File workingDirectory); Options(); std::wstring getKeyDescription(int i); std::wstring getKeyMessage(int i); void setKey(int i, int key); - void set(const Options::Option *item, float value); - void toggle(const Options::Option *option, int dir); - float getProgressValue(const Options::Option *item); - bool getBooleanValue(const Options::Option *item); - std::wstring getMessage(const Options::Option *item); + void set(const Options::Option* item, float value); + void toggle(const Options::Option* option, int dir); + float getProgressValue(const Options::Option* item); + bool getBooleanValue(const Options::Option* item); + std::wstring getMessage(const Options::Option* item); void load(); -private: - float readFloat(std::wstring string); -public: - void save(); - bool isCloudsOn(); +private: + float readFloat(std::wstring string); + +public: + void save(); + + bool isCloudsOn(); }; diff --git a/Minecraft.Client/GameState/Settings.cpp b/Minecraft.Client/GameState/Settings.cpp index 7f035e18c..658cebd32 100644 --- a/Minecraft.Client/GameState/Settings.cpp +++ b/Minecraft.Client/GameState/Settings.cpp @@ -3,53 +3,41 @@ #include "../../Minecraft.World/Util/StringHelpers.h" // 4J - TODO - serialise/deserialise from file -Settings::Settings(File *file) -{ +Settings::Settings(File* file) {} + +void Settings::generateNewProperties() {} + +void Settings::saveProperties() {} + +std::wstring Settings::getString(const std::wstring& key, + const std::wstring& defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = defaultValue; + saveProperties(); + } + return properties[key]; } -void Settings::generateNewProperties() -{ +int Settings::getInt(const std::wstring& key, int defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = _toString(defaultValue); + saveProperties(); + } + return _fromString(properties[key]); } -void Settings::saveProperties() -{ +bool Settings::getBoolean(const std::wstring& key, bool defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = _toString(defaultValue); + saveProperties(); + } + MemSect(35); + bool retval = _fromString(properties[key]); + MemSect(0); + return retval; } -std::wstring Settings::getString(const std::wstring& key, const std::wstring& defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = defaultValue; - saveProperties(); - } - return properties[key]; -} - -int Settings::getInt(const std::wstring& key, int defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = _toString(defaultValue); - saveProperties(); - } - return _fromString(properties[key]); -} - -bool Settings::getBoolean(const std::wstring& key, bool defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = _toString(defaultValue); - saveProperties(); - } - MemSect(35); - bool retval = _fromString(properties[key]); - MemSect(0); - return retval; -} - -void Settings::setBooleanAndSave(const std::wstring& key, bool value) -{ - properties[key] = _toString(value); - saveProperties(); +void Settings::setBooleanAndSave(const std::wstring& key, bool value) { + properties[key] = _toString(value); + saveProperties(); } \ No newline at end of file diff --git a/Minecraft.Client/GameState/Settings.h b/Minecraft.Client/GameState/Settings.h index 8ead97244..cacdd6857 100644 --- a/Minecraft.Client/GameState/Settings.h +++ b/Minecraft.Client/GameState/Settings.h @@ -1,20 +1,21 @@ #pragma once class File; - -class Settings -{ -// public static Logger logger = Logger.getLogger("Minecraft"); -// private Properties properties = new Properties(); +class Settings { + // public static Logger logger = Logger.getLogger("Minecraft"); + // private Properties properties = new Properties(); private: - std::unordered_map properties; // 4J - TODO was Properties type, will need to implement something we can serialise/deserialise too - //File *file; + std::unordered_map + properties; // 4J - TODO was Properties type, will need to implement + // something we can serialise/deserialise too + // File *file; public: - Settings(File *file); + Settings(File* file); void generateNewProperties(); void saveProperties(); - std::wstring getString(const std::wstring& key, const std::wstring& defaultValue); + std::wstring getString(const std::wstring& key, + const std::wstring& defaultValue); int getInt(const std::wstring& key, int defaultValue); bool getBoolean(const std::wstring& key, bool defaultValue); void setBooleanAndSave(const std::wstring& key, bool value); diff --git a/Minecraft.Client/GameState/StatsCounter.cpp b/Minecraft.Client/GameState/StatsCounter.cpp index b63e909f7..a03bd236c 100644 --- a/Minecraft.Client/GameState/StatsCounter.cpp +++ b/Minecraft.Client/GameState/StatsCounter.cpp @@ -12,1341 +12,1915 @@ #include "../Platform/Common/Leaderboards/LeaderboardManager.h" #include -Stat** StatsCounter::LARGE_STATS[] = { - &Stats::walkOneM, - &Stats::swimOneM, - &Stats::fallOneM, - &Stats::climbOneM, - &Stats::minecartOneM, - &Stats::boatOneM, - &Stats::pigOneM, - &Stats::timePlayed -}; +Stat** StatsCounter::LARGE_STATS[] = {&Stats::walkOneM, &Stats::swimOneM, + &Stats::fallOneM, &Stats::climbOneM, + &Stats::minecartOneM, &Stats::boatOneM, + &Stats::pigOneM, &Stats::timePlayed}; std::unordered_map StatsCounter::statBoards; -StatsCounter::StatsCounter() -{ - requiresSave = false; - saveCounter = 0; - modifiedBoards = 0; - flushCounter = 0; +StatsCounter::StatsCounter() { + requiresSave = false; + saveCounter = 0; + modifiedBoards = 0; + flushCounter = 0; } -void StatsCounter::award(Stat* stat, unsigned int difficulty, unsigned int count) -{ +void StatsCounter::award(Stat* stat, unsigned int difficulty, + unsigned int count) { #ifndef _DURANGO - if( stat->isAchievement() ) - difficulty = 0; + if (stat->isAchievement()) difficulty = 0; - StatsMap::iterator val = stats.find(stat); - if( val == stats.end() ) - { - StatContainer newVal; - newVal.stats[difficulty] = count; - stats.insert( std::make_pair(stat, newVal) ); - } - else - { - val->second.stats[difficulty] += count; + StatsMap::iterator val = stats.find(stat); + if (val == stats.end()) { + StatContainer newVal; + newVal.stats[difficulty] = count; + stats.insert(std::make_pair(stat, newVal)); + } else { + val->second.stats[difficulty] += count; - if (stat != GenericStats::timePlayed()) - app.DebugPrintf(""); + if (stat != GenericStats::timePlayed()) app.DebugPrintf(""); - //If value has wrapped, cap it to UINT_MAX - if( val->second.stats[difficulty] < (val->second.stats[difficulty]-count) ) - val->second.stats[difficulty] = UINT_MAX; + // If value has wrapped, cap it to UINT_MAX + if (val->second.stats[difficulty] < + (val->second.stats[difficulty] - count)) + val->second.stats[difficulty] = UINT_MAX; - //If value is larger than USHRT_MAX and is not designated as large, cap it to USHRT_MAX - if( val->second.stats[difficulty] > USHRT_MAX && !isLargeStat(stat) ) - val->second.stats[difficulty] = USHRT_MAX; - } + // If value is larger than USHRT_MAX and is not designated as large, cap + // it to USHRT_MAX + if (val->second.stats[difficulty] > USHRT_MAX && !isLargeStat(stat)) + val->second.stats[difficulty] = USHRT_MAX; + } - requiresSave = true; + requiresSave = true; - //If this stat is on a leaderboard, mark that leaderboard as needing updated - std::unordered_map::iterator leaderboardEntry = statBoards.find(stat); - if( leaderboardEntry != statBoards.end() ) - { - app.DebugPrintf("[StatsCounter] award(): %X\n", leaderboardEntry->second << difficulty); - modifiedBoards |= (leaderboardEntry->second << difficulty); - if( flushCounter == 0 ) - flushCounter = FLUSH_DELAY; - } + // If this stat is on a leaderboard, mark that leaderboard as needing + // updated + std::unordered_map::iterator leaderboardEntry = + statBoards.find(stat); + if (leaderboardEntry != statBoards.end()) { + app.DebugPrintf("[StatsCounter] award(): %X\n", + leaderboardEntry->second << difficulty); + modifiedBoards |= (leaderboardEntry->second << difficulty); + if (flushCounter == 0) flushCounter = FLUSH_DELAY; + } #endif } -bool StatsCounter::hasTaken(Achievement *ach) -{ - return stats.find(ach) != stats.end(); +bool StatsCounter::hasTaken(Achievement* ach) { + return stats.find(ach) != stats.end(); } -bool StatsCounter::canTake(Achievement *ach) -{ - //4J Gordon: Remove achievement dependencies, always able to take - return true; +bool StatsCounter::canTake(Achievement* ach) { + // 4J Gordon: Remove achievement dependencies, always able to take + return true; } -unsigned int StatsCounter::getValue(Stat *stat, unsigned int difficulty) -{ - StatsMap::iterator val = stats.find(stat); - if( val != stats.end() ) - return val->second.stats[difficulty]; - return 0; +unsigned int StatsCounter::getValue(Stat* stat, unsigned int difficulty) { + StatsMap::iterator val = stats.find(stat); + if (val != stats.end()) return val->second.stats[difficulty]; + return 0; } -unsigned int StatsCounter::getTotalValue(Stat *stat) -{ - StatsMap::iterator val = stats.find(stat); - if( val != stats.end() ) - return val->second.stats[0] + val->second.stats[1] + val->second.stats[2] + val->second.stats[3]; - return 0; +unsigned int StatsCounter::getTotalValue(Stat* stat) { + StatsMap::iterator val = stats.find(stat); + if (val != stats.end()) + return val->second.stats[0] + val->second.stats[1] + + val->second.stats[2] + val->second.stats[3]; + return 0; } -void StatsCounter::tick(int player) -{ - if( saveCounter > 0 ) - --saveCounter; +void StatsCounter::tick(int player) { + if (saveCounter > 0) --saveCounter; - if( requiresSave && saveCounter == 0 ) - save(player); + if (requiresSave && saveCounter == 0) save(player); - // 4J-JEV, we don't want to write leaderboards in the middle of a game. - // EDIT: Yes we do, people were not ending their games properly and not updating scores. -// #ifndef __PS3__ - if( flushCounter > 0 ) - { - --flushCounter; - if( flushCounter == 0 ) - flushLeaderboards(); - } -// #endif + // 4J-JEV, we don't want to write leaderboards in the middle of a game. + // EDIT: Yes we do, people were not ending their games properly and not + // updating scores. + // #ifndef __PS3__ + if (flushCounter > 0) { + --flushCounter; + if (flushCounter == 0) flushLeaderboards(); + } + // #endif } -void StatsCounter::clear() -{ - // clear out the stats when someone signs out - stats.clear(); +void StatsCounter::clear() { + // clear out the stats when someone signs out + stats.clear(); } -void StatsCounter::parse(void* data) -{ +void StatsCounter::parse(void* data) { #ifndef _DURANGO - // 4J-PB - If this is the trial game, let's just make sure all the stats are empty - // 4J-PB - removing - someone can have the full game, and then remove it and go back to the trial -// if(!ProfileManager.IsFullVersion()) -// { -// stats.clear(); -// return; -// } - //Check that we don't already have any stats - assert( stats.size() == 0 ); + // 4J-PB - If this is the trial game, let's just make sure all the stats are + // empty 4J-PB - removing - someone can have the full game, and then remove + // it and go back to the trial + // if(!ProfileManager.IsFullVersion()) + // { + // stats.clear(); + // return; + // } + // Check that we don't already have any stats + assert(stats.size() == 0); - //Pointer to current position in stat array - std::uint8_t* pbData = reinterpret_cast(data); - pbData += sizeof(GAME_SETTINGS); - std::uint8_t* statData = pbData; + // Pointer to current position in stat array + std::uint8_t* pbData = reinterpret_cast(data); + pbData += sizeof(GAME_SETTINGS); + std::uint8_t* statData = pbData; - //Value being read - StatContainer newVal; + // Value being read + StatContainer newVal; - //For each stat - std::vector::iterator end = Stats::all->end(); - for( std::vector::iterator iter = Stats::all->begin() ; iter != end ; ++iter ) - { - if( !(*iter)->isAchievement() ) - { - if( !isLargeStat(*iter) ) - { - std::uint16_t difficultyStats[eDifficulty_Max] = {}; - std::memcpy(difficultyStats, statData, sizeof(difficultyStats)); - if( difficultyStats[0] != 0 || difficultyStats[1] != 0 || difficultyStats[2] != 0 || difficultyStats[3] != 0 ) - { - newVal.stats[0] = difficultyStats[0]; - newVal.stats[1] = difficultyStats[1]; - newVal.stats[2] = difficultyStats[2]; - newVal.stats[3] = difficultyStats[3]; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(difficultyStats); - } - else - { - std::uint32_t largeStatData[eDifficulty_Max] = {}; - std::memcpy(largeStatData, statData, sizeof(largeStatData)); - if( largeStatData[0] != 0 || largeStatData[1] != 0 || largeStatData[2] != 0 || largeStatData[3] != 0 ) - { - newVal.stats[0] = largeStatData[0]; - newVal.stats[1] = largeStatData[1]; - newVal.stats[2] = largeStatData[2]; - newVal.stats[3] = largeStatData[3]; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(largeStatData); - } - } - else - { - std::uint16_t achievementValue = 0; - std::memcpy(&achievementValue, statData, sizeof(achievementValue)); - if( achievementValue != 0 ) - { - newVal.stats[0] = achievementValue; - newVal.stats[1] = 0; - newVal.stats[2] = 0; - newVal.stats[3] = 0; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(achievementValue); - } - } + // For each stat + std::vector::iterator end = Stats::all->end(); + for (std::vector::iterator iter = Stats::all->begin(); iter != end; + ++iter) { + if (!(*iter)->isAchievement()) { + if (!isLargeStat(*iter)) { + std::uint16_t difficultyStats[eDifficulty_Max] = {}; + std::memcpy(difficultyStats, statData, sizeof(difficultyStats)); + if (difficultyStats[0] != 0 || difficultyStats[1] != 0 || + difficultyStats[2] != 0 || difficultyStats[3] != 0) { + newVal.stats[0] = difficultyStats[0]; + newVal.stats[1] = difficultyStats[1]; + newVal.stats[2] = difficultyStats[2]; + newVal.stats[3] = difficultyStats[3]; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(difficultyStats); + } else { + std::uint32_t largeStatData[eDifficulty_Max] = {}; + std::memcpy(largeStatData, statData, sizeof(largeStatData)); + if (largeStatData[0] != 0 || largeStatData[1] != 0 || + largeStatData[2] != 0 || largeStatData[3] != 0) { + newVal.stats[0] = largeStatData[0]; + newVal.stats[1] = largeStatData[1]; + newVal.stats[2] = largeStatData[2]; + newVal.stats[3] = largeStatData[3]; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(largeStatData); + } + } else { + std::uint16_t achievementValue = 0; + std::memcpy(&achievementValue, statData, sizeof(achievementValue)); + if (achievementValue != 0) { + newVal.stats[0] = achievementValue; + newVal.stats[1] = 0; + newVal.stats[2] = 0; + newVal.stats[3] = 0; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(achievementValue); + } + } - dumpStatsToTTY(); + dumpStatsToTTY(); #endif } -void StatsCounter::save(int player, bool force) -{ +void StatsCounter::save(int player, bool force) { #ifndef _DURANGO - // 4J-PB - If this is the trial game, don't save any stats - if(!ProfileManager.IsFullVersion()) - { - return; - } + // 4J-PB - If this is the trial game, don't save any stats + if (!ProfileManager.IsFullVersion()) { + return; + } - //Check we're going to have enough room to store all possible stats - unsigned int uiTotalStatsSize = (Stats::all->size() * 4 * sizeof(unsigned short)) - (Achievements::achievements->size() * 3 * sizeof(unsigned short)) + (LARGE_STATS_COUNT*4*(sizeof(unsigned int)-sizeof(unsigned short))); - assert( uiTotalStatsSize <= (CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES-sizeof(GAME_SETTINGS)) ); + // Check we're going to have enough room to store all possible stats + unsigned int uiTotalStatsSize = + (Stats::all->size() * 4 * sizeof(unsigned short)) - + (Achievements::achievements->size() * 3 * sizeof(unsigned short)) + + (LARGE_STATS_COUNT * 4 * + (sizeof(unsigned int) - sizeof(unsigned short))); + assert(uiTotalStatsSize <= + (CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES - + sizeof(GAME_SETTINGS))); - //Retrieve the data pointer from the profile -#if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__ ) - std::uint8_t* pbData = reinterpret_cast(StorageManager.GetGameDefinedProfileData(player)); + // Retrieve the data pointer from the profile +#if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || \ + defined __PSVITA__) + std::uint8_t* pbData = reinterpret_cast( + StorageManager.GetGameDefinedProfileData(player)); #else - std::uint8_t* pbData = reinterpret_cast(ProfileManager.GetGameDefinedProfileData(player)); + std::uint8_t* pbData = reinterpret_cast( + ProfileManager.GetGameDefinedProfileData(player)); #endif - pbData += sizeof(GAME_SETTINGS); - - //Pointer to current position in stat array - std::uint8_t* statData = pbData; + pbData += sizeof(GAME_SETTINGS); - //Reset all the data to 0 (we're going to replace it with the map data) - memset(statData, 0, CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES-sizeof(GAME_SETTINGS)); + // Pointer to current position in stat array + std::uint8_t* statData = pbData; - //For each stat - StatsMap::iterator val; - std::vector::iterator end = Stats::all->end(); - for( std::vector::iterator iter = Stats::all->begin() ; iter != end ; ++iter ) - { - //If the stat is in the map write out it's value - val = stats.find(*iter); - if( !(*iter)->isAchievement() ) - { - if( !isLargeStat(*iter) ) - { - std::uint16_t difficultyStats[eDifficulty_Max] = {}; - if( val != stats.end() ) - { - difficultyStats[0] = static_cast(val->second.stats[0]); - difficultyStats[1] = static_cast(val->second.stats[1]); - difficultyStats[2] = static_cast(val->second.stats[2]); - difficultyStats[3] = static_cast(val->second.stats[3]); - } - std::memcpy(statData, difficultyStats, sizeof(difficultyStats)); - statData += sizeof(difficultyStats); - } - else - { - std::uint32_t largeStatData[eDifficulty_Max] = {}; - if( val != stats.end() ) - { - largeStatData[0] = val->second.stats[0]; - largeStatData[1] = val->second.stats[1]; - largeStatData[2] = val->second.stats[2]; - largeStatData[3] = val->second.stats[3]; - } - std::memcpy(statData, largeStatData, sizeof(largeStatData)); - statData += sizeof(largeStatData); - } - } - else - { - std::uint16_t achievementValue = 0; - if( val != stats.end() ) - { - achievementValue = static_cast(val->second.stats[0]); - } - std::memcpy(statData, &achievementValue, sizeof(achievementValue)); - statData += sizeof(achievementValue); - } - } + // Reset all the data to 0 (we're going to replace it with the map data) + memset(statData, 0, + CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES - + sizeof(GAME_SETTINGS)); -#if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__ ) - StorageManager.WriteToProfile(player, true, force); + // For each stat + StatsMap::iterator val; + std::vector::iterator end = Stats::all->end(); + for (std::vector::iterator iter = Stats::all->begin(); iter != end; + ++iter) { + // If the stat is in the map write out it's value + val = stats.find(*iter); + if (!(*iter)->isAchievement()) { + if (!isLargeStat(*iter)) { + std::uint16_t difficultyStats[eDifficulty_Max] = {}; + if (val != stats.end()) { + difficultyStats[0] = + static_cast(val->second.stats[0]); + difficultyStats[1] = + static_cast(val->second.stats[1]); + difficultyStats[2] = + static_cast(val->second.stats[2]); + difficultyStats[3] = + static_cast(val->second.stats[3]); + } + std::memcpy(statData, difficultyStats, sizeof(difficultyStats)); + statData += sizeof(difficultyStats); + } else { + std::uint32_t largeStatData[eDifficulty_Max] = {}; + if (val != stats.end()) { + largeStatData[0] = val->second.stats[0]; + largeStatData[1] = val->second.stats[1]; + largeStatData[2] = val->second.stats[2]; + largeStatData[3] = val->second.stats[3]; + } + std::memcpy(statData, largeStatData, sizeof(largeStatData)); + statData += sizeof(largeStatData); + } + } else { + std::uint16_t achievementValue = 0; + if (val != stats.end()) { + achievementValue = + static_cast(val->second.stats[0]); + } + std::memcpy(statData, &achievementValue, sizeof(achievementValue)); + statData += sizeof(achievementValue); + } + } + +#if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || \ + defined __PSVITA__) + StorageManager.WriteToProfile(player, true, force); #else - ProfileManager.WriteToProfile(player, true, force); + ProfileManager.WriteToProfile(player, true, force); #endif - saveCounter = SAVE_DELAY; + saveCounter = SAVE_DELAY; #endif } #ifdef _XBOX -void StatsCounter::setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, unsigned int value) -{ - app.DebugPrintf("Setting property id: %d to value %d\n", id, value); - prop->dwPropertyId = id; - prop->value.type = XUSER_DATA_TYPE_INT32; - prop->value.nData = (int)(value&0x7FFFFFFF); // Just making sure we clamp the unsigned int to the max val for a signed int +void StatsCounter::setLeaderboardProperty(XUSER_PROPERTY* prop, + std::uint32_t id, + unsigned int value) { + app.DebugPrintf("Setting property id: %d to value %d\n", id, value); + prop->dwPropertyId = id; + prop->value.type = XUSER_DATA_TYPE_INT32; + prop->value.nData = + (int)(value & 0x7FFFFFFF); // Just making sure we clamp the unsigned + // int to the max val for a signed int } -void StatsCounter::setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value) -{ - prop->dwPropertyId = PROPERTY_RATING; - prop->value.type = XUSER_DATA_TYPE_INT64; - prop->value.i64Data = value; +void StatsCounter::setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value) { + prop->dwPropertyId = PROPERTY_RATING; + prop->value.type = XUSER_DATA_TYPE_INT64; + prop->value.i64Data = value; } #endif -void StatsCounter::flushLeaderboards() -{ +void StatsCounter::flushLeaderboards() { #ifndef _DURANGO - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->FlushStats(); - } - else - { - app.DebugPrintf("Failed to open a session in order to write to leaderboard\n"); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->FlushStats(); + } else { + app.DebugPrintf( + "Failed to open a session in order to write to leaderboard\n"); - // 4J-JEV: If user was not signed in it would hit this. - //assert(false);// && "Failed to open a session in order to write to leaderboard"); - } + // 4J-JEV: If user was not signed in it would hit this. + // assert(false);// && "Failed to open a session in order to write to + // leaderboard"); + } - modifiedBoards = 0; + modifiedBoards = 0; #endif } -void StatsCounter::saveLeaderboards() -{ +void StatsCounter::saveLeaderboards() { #ifndef _DURANGO - // 4J-PB - If this is the trial game, no writing leaderboards - if(!ProfileManager.IsFullVersion()) - { - return; - } + // 4J-PB - If this is the trial game, no writing leaderboards + if (!ProfileManager.IsFullVersion()) { + return; + } - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->CloseSession(); - } - else - { - app.DebugPrintf("Failed to open a session in order to write to leaderboard\n"); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->CloseSession(); + } else { + app.DebugPrintf( + "Failed to open a session in order to write to leaderboard\n"); - // 4J-JEV: If user was not signed in it would hit this. - //assert(false);// && "Failed to open a session in order to write to leaderboard"); - } + // 4J-JEV: If user was not signed in it would hit this. + // assert(false);// && "Failed to open a session in order to write to + // leaderboard"); + } - modifiedBoards = 0; + modifiedBoards = 0; #endif } -void StatsCounter::writeStats() -{ +void StatsCounter::writeStats() { #ifndef _DURANGO - // 4J-PB - If this is the trial game, no writing - if(!ProfileManager.IsFullVersion()) - { - return; - } - //unsigned int locale = XGetLocale(); - - int viewCount = 0; - int iPad = ProfileManager.GetLockedProfile(); - -#if defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) - LeaderboardManager::RegisterScore *scores = new LeaderboardManager::RegisterScore[24]; - - if( modifiedBoards & LEADERBOARD_KILLS_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Easy); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Easy); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_KILLS_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Normal); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Normal); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_KILLS_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Hard); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Hard); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD) ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD\n"); - - //viewCount++; - } - - if( viewCount > 0 ) - { - if( !LeaderboardManager::Instance()->WriteStats(viewCount, scores) ) - { - app.DebugPrintf("Failed to write to leaderboard\n"); - assert(false);// && "Failed to write to leaderboard"); - //printf("Failed to write to leaderboard"); - } - else - { - app.DebugPrintf("Successfully wrote %d leadeboard views\n", viewCount); - } - } + // 4J-PB - If this is the trial game, no writing + if (!ProfileManager.IsFullVersion()) { + return; + } + // unsigned int locale = XGetLocale(); + + int viewCount = 0; + int iPad = ProfileManager.GetLockedProfile(); + +#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) + LeaderboardManager::RegisterScore* scores = + new LeaderboardManager::RegisterScore[24]; + + if (modifiedBoards & LEADERBOARD_KILLS_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Easy); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Easy); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_KILLS_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Normal); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Normal); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_KILLS_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Hard); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Hard); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_gravel = getValue( + Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_obsidian = getValue( + Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_obsidian = + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_obsidian = getValue( + Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_obsidian = + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = getValue( + Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_mushroom = getValue( + Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_mushroom = + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_mushroom = getValue( + Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_mushroom = + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & + (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | + LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD)) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | " + "LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | " + "LEADERBOARD_TRAVELLING_HARD\n"); + + // viewCount++; + } + + if (viewCount > 0) { + if (!LeaderboardManager::Instance()->WriteStats(viewCount, scores)) { + app.DebugPrintf("Failed to write to leaderboard\n"); + assert(false); // && "Failed to write to leaderboard"); + // printf("Failed to write to leaderboard"); + } else { + app.DebugPrintf("Successfully wrote %d leadeboard views\n", + viewCount); + } + } #elif defined _XBOX - - LONGLONG rating; - XSESSION_VIEW_PROPERTIES views[24]; + LONGLONG rating; - XUSER_PROPERTY killsEasyProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY killsNormalProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY killsHardProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY miningBlocksPeacefulProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksEasyProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksNormalProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksHardProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY farmingPeacefulProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingEasyProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingNormalProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingHardProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY travellingPeacefulProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingEasyProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingNormalProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingHardProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingProperties[1]; // arcade leaderboard + XSESSION_VIEW_PROPERTIES views[24]; - if( modifiedBoards & LEADERBOARD_KILLS_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsEasyProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Easy) + - getValue(Stats::killsSkeleton, eDifficulty_Easy) + - getValue(Stats::killsCreeper, eDifficulty_Easy) + - getValue(Stats::killsSpider, eDifficulty_Easy) + - getValue(Stats::killsSpiderJockey, eDifficulty_Easy) + - getValue(Stats::killsZombiePigman, eDifficulty_Easy) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) + - getValue(Stats::killsSlime, eDifficulty_Easy); - - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Easy) ); - // 4J-PB - this could overflow - //setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Easy) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) ); - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Easy) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + XUSER_PROPERTY killsEasyProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY + killsNormalProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY killsHardProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingEasyProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingNormalProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingHardProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY + travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY + travellingHardProperties[LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY travellingProperties[1]; // arcade leaderboard - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Easy) ); - setLeaderboardRating( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_KILLS_EASY) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsEasyProperties; - viewCount++; - } + rating = getValue(Stats::killsZombie, eDifficulty_Easy) + + getValue(Stats::killsSkeleton, eDifficulty_Easy) + + getValue(Stats::killsCreeper, eDifficulty_Easy) + + getValue(Stats::killsSpider, eDifficulty_Easy) + + getValue(Stats::killsSpiderJockey, eDifficulty_Easy) + + getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsSlime, eDifficulty_Easy); - if( modifiedBoards & LEADERBOARD_KILLS_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsNormalProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Normal) + - getValue(Stats::killsSkeleton, eDifficulty_Normal) + - getValue(Stats::killsCreeper, eDifficulty_Normal) + - getValue(Stats::killsSpider, eDifficulty_Normal) + - getValue(Stats::killsSpiderJockey, eDifficulty_Normal) + - getValue(Stats::killsZombiePigman, eDifficulty_Normal) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) + - getValue(Stats::killsSlime, eDifficulty_Normal); - - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Normal) ); - // 4J-PB - this could overflow - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Normal) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); - //setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Normal) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Easy)); + // 4J-PB - this could overflow + // setLeaderboardProperty( + // &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) ); + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); + setLeaderboardProperty( + &killsEasyProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Normal) ); - setLeaderboardRating( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Easy)); + setLeaderboardRating( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_KILLS_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsHardProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Hard) + - getValue(Stats::killsSkeleton, eDifficulty_Hard) + - getValue(Stats::killsCreeper, eDifficulty_Hard) + - getValue(Stats::killsSpider, eDifficulty_Hard) + - getValue(Stats::killsSpiderJockey, eDifficulty_Hard) + - getValue(Stats::killsZombiePigman, eDifficulty_Hard) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) + - getValue(Stats::killsSlime, eDifficulty_Hard); - - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Hard) ); - // 4J-PB - this could overflow - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Hard) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); - //setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Hard) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + if (modifiedBoards & LEADERBOARD_KILLS_NORMAL) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsNormalProperties; - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Hard) ); - setLeaderboardRating( &killsHardProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + rating = getValue(Stats::killsZombie, eDifficulty_Normal) + + getValue(Stats::killsSkeleton, eDifficulty_Normal) + + getValue(Stats::killsCreeper, eDifficulty_Normal) + + getValue(Stats::killsSpider, eDifficulty_Normal) + + getValue(Stats::killsSpiderJockey, eDifficulty_Normal) + + getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsSlime, eDifficulty_Normal); - viewCount++; - } + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Normal)); + // 4J-PB - this could overflow + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); + // setLeaderboardProperty( + // &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) ); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksPeacefulProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); - - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful) ); - setLeaderboardRating( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Normal)); + setLeaderboardRating( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksEasyProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy) ); - setLeaderboardRating( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_KILLS_HARD) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsHardProperties; - viewCount++; - } + rating = getValue(Stats::killsZombie, eDifficulty_Hard) + + getValue(Stats::killsSkeleton, eDifficulty_Hard) + + getValue(Stats::killsCreeper, eDifficulty_Hard) + + getValue(Stats::killsSpider, eDifficulty_Hard) + + getValue(Stats::killsSpiderJockey, eDifficulty_Hard) + + getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsSlime, eDifficulty_Hard); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksNormalProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); - - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Cobblestone ], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal) ); - setLeaderboardRating( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Hard)); + // 4J-PB - this could overflow + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); + // setLeaderboardProperty( + // &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) ); + setLeaderboardProperty( + &killsHardProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - viewCount++; - } + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Hard)); + setLeaderboardRating( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksHardProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard) ); - setLeaderboardRating( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksPeacefulProperties; - if( modifiedBoards & LEADERBOARD_FARMING_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingPeacefulProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) + - getValue(Stats::cowsMilked, eDifficulty_Peaceful) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); - - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful) ); - setLeaderboardRating( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::gravel->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Peaceful); - viewCount++; - } + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Peaceful)); + setLeaderboardRating(&miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - if( modifiedBoards & LEADERBOARD_FARMING_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingEasyProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) + - getValue(Stats::cowsMilked, eDifficulty_Easy) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); + viewCount++; + } - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy) ); - setLeaderboardRating( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksEasyProperties; - viewCount++; - } + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - if( modifiedBoards & LEADERBOARD_FARMING_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingNormalProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) + - getValue(Stats::cowsMilked, eDifficulty_Normal) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy)); + setLeaderboardRating(&miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Sugarcane], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal) ); - setLeaderboardRating( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksNormalProperties; - if( modifiedBoards & LEADERBOARD_FARMING_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingHardProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) + - getValue(Stats::cowsMilked, eDifficulty_Hard) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Normal); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard) ); - setLeaderboardRating( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Normal)); + setLeaderboardRating(&miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingPeacefulProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Peaceful) + - getValue(Stats::fallOneM, eDifficulty_Peaceful) + - getValue(Stats::minecartOneM, eDifficulty_Peaceful) + - getValue(Stats::boatOneM, eDifficulty_Peaceful); + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksHardProperties; - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Peaceful) ); - setLeaderboardRating( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - viewCount++; - } + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard)); + setLeaderboardRating(&miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - if( modifiedBoards & LEADERBOARD_TRAVELLING_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingEasyProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Easy) + - getValue(Stats::fallOneM, eDifficulty_Easy) + - getValue(Stats::minecartOneM, eDifficulty_Easy) + - getValue(Stats::boatOneM, eDifficulty_Easy); + viewCount++; + } - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Easy) ); - setLeaderboardRating( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_FARMING_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingPeacefulProperties; - viewCount++; - } + rating = + getValue(Stats::itemsCollected[Item::egg->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) + + getValue(Stats::cowsMilked, eDifficulty_Peaceful) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Peaceful); - if( modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingNormalProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Normal) + - getValue(Stats::fallOneM, eDifficulty_Normal) + - getValue(Stats::minecartOneM, eDifficulty_Normal) + - getValue(Stats::boatOneM, eDifficulty_Normal); + setLeaderboardProperty(&farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Peaceful)); + setLeaderboardRating(&farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Normal) ); - setLeaderboardRating( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_FARMING_EASY) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingEasyProperties; - if( modifiedBoards & LEADERBOARD_TRAVELLING_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingHardProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Hard) + - getValue(Stats::fallOneM, eDifficulty_Hard) + - getValue(Stats::minecartOneM, eDifficulty_Hard) + - getValue(Stats::boatOneM, eDifficulty_Hard); + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) + + getValue(Stats::cowsMilked, eDifficulty_Easy) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Easy); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Hard) ); - setLeaderboardRating( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Easy)); + setLeaderboardRating(&farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD) ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_TOTAL; - views[viewCount].dwNumProperties = 1; - views[viewCount].pProperties = travellingProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Peaceful) + getValue(Stats::fallOneM, eDifficulty_Peaceful) + getValue(Stats::boatOneM, eDifficulty_Peaceful) + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + - getValue(Stats::walkOneM, eDifficulty_Easy) + getValue(Stats::fallOneM, eDifficulty_Easy) + getValue(Stats::boatOneM, eDifficulty_Easy) + getValue(Stats::minecartOneM, eDifficulty_Easy) + - getValue(Stats::walkOneM, eDifficulty_Normal) + getValue(Stats::fallOneM, eDifficulty_Normal) + getValue(Stats::boatOneM, eDifficulty_Normal) + getValue(Stats::minecartOneM, eDifficulty_Normal) + - getValue(Stats::walkOneM, eDifficulty_Hard) + getValue(Stats::fallOneM, eDifficulty_Hard) + getValue(Stats::boatOneM, eDifficulty_Hard) + getValue(Stats::minecartOneM, eDifficulty_Hard); + if (modifiedBoards & LEADERBOARD_FARMING_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingNormalProperties; - setLeaderboardRating( &travellingProperties[0], rating ); + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) + + getValue(Stats::cowsMilked, eDifficulty_Normal) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Normal); - viewCount++; - } + setLeaderboardProperty( + &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal)); + setLeaderboardProperty(&farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Normal)); + setLeaderboardRating(&farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - if( viewCount > 0 ) - { - if( !LeaderboardManager::Instance()->WriteStats(viewCount, views) ) - { - assert(false && "Failed to write to leaderboard"); - //printf("Failed to write to leaderboard"); - } - else - { - app.DebugPrintf("Successfully wrote %d leadeboard views\n", viewCount); - } - } -#endif // Xbox -#endif // ndef _DURANGO + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_HARD) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingHardProperties; + + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) + + getValue(Stats::cowsMilked, eDifficulty_Hard) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Hard); + + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Hard)); + setLeaderboardRating(&farmingHardProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingPeacefulProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Peaceful) + + getValue(Stats::fallOneM, eDifficulty_Peaceful) + + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + + getValue(Stats::boatOneM, eDifficulty_Peaceful); + + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, + getValue(Stats::walkOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, + getValue(Stats::fallOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, + getValue(Stats::boatOneM, eDifficulty_Peaceful)); + setLeaderboardRating( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_EASY) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingEasyProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Easy) + + getValue(Stats::fallOneM, eDifficulty_Easy) + + getValue(Stats::minecartOneM, eDifficulty_Easy) + + getValue(Stats::boatOneM, eDifficulty_Easy); + + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Easy)); + setLeaderboardRating( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingNormalProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Normal) + + getValue(Stats::fallOneM, eDifficulty_Normal) + + getValue(Stats::minecartOneM, eDifficulty_Normal) + + getValue(Stats::boatOneM, eDifficulty_Normal); + + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, + getValue(Stats::walkOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, + getValue(Stats::fallOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, + getValue(Stats::boatOneM, eDifficulty_Normal)); + setLeaderboardRating( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_HARD) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingHardProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Hard) + + getValue(Stats::fallOneM, eDifficulty_Hard) + + getValue(Stats::minecartOneM, eDifficulty_Hard) + + getValue(Stats::boatOneM, eDifficulty_Hard); + + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Hard)); + setLeaderboardRating( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & + (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | + LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD)) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | " + "LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | " + "LEADERBOARD_TRAVELLING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_TOTAL; + views[viewCount].dwNumProperties = 1; + views[viewCount].pProperties = travellingProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Peaceful) + + getValue(Stats::fallOneM, eDifficulty_Peaceful) + + getValue(Stats::boatOneM, eDifficulty_Peaceful) + + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + + getValue(Stats::walkOneM, eDifficulty_Easy) + + getValue(Stats::fallOneM, eDifficulty_Easy) + + getValue(Stats::boatOneM, eDifficulty_Easy) + + getValue(Stats::minecartOneM, eDifficulty_Easy) + + getValue(Stats::walkOneM, eDifficulty_Normal) + + getValue(Stats::fallOneM, eDifficulty_Normal) + + getValue(Stats::boatOneM, eDifficulty_Normal) + + getValue(Stats::minecartOneM, eDifficulty_Normal) + + getValue(Stats::walkOneM, eDifficulty_Hard) + + getValue(Stats::fallOneM, eDifficulty_Hard) + + getValue(Stats::boatOneM, eDifficulty_Hard) + + getValue(Stats::minecartOneM, eDifficulty_Hard); + + setLeaderboardRating(&travellingProperties[0], rating); + + viewCount++; + } + + if (viewCount > 0) { + if (!LeaderboardManager::Instance()->WriteStats(viewCount, views)) { + assert(false && "Failed to write to leaderboard"); + // printf("Failed to write to leaderboard"); + } else { + app.DebugPrintf("Successfully wrote %d leadeboard views\n", + viewCount); + } + } +#endif // Xbox +#endif // ndef _DURANGO } -void StatsCounter::setupStatBoards() -{ +void StatsCounter::setupStatBoards() { #ifndef _DURANGO - statBoards.insert( std::make_pair(Stats::killsZombie, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSkeleton, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsCreeper, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSpider, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSpiderJockey, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsZombiePigman, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsNetherZombiePigman, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSlime, LEADERBOARD_KILLS_PEACEFUL) ); + statBoards.insert( + std::make_pair(Stats::killsZombie, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSkeleton, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsCreeper, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSpider, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSpiderJockey, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsZombiePigman, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::killsNetherZombiePigman, + LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSlime, LEADERBOARD_KILLS_PEACEFUL)); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::dirt->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::stoneBrick->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::sand->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::rock->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::gravel->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::clay->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::obsidian->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - - statBoards.insert( std::make_pair(Stats::itemsCollected[Item::egg->id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::crops_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::mushroom1_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::reeds_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::cowsMilked, LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::itemsCollected[Tile::pumpkin->id], LEADERBOARD_FARMING_PEACEFUL) ); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::dirt->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::stoneBrick->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::sand->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::rock->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::gravel->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::clay->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::obsidian->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); - statBoards.insert( std::make_pair(Stats::walkOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::fallOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::minecartOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::boatOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); + statBoards.insert(std::make_pair(Stats::itemsCollected[Item::egg->id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::crops_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::mushroom1_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::reeds_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::cowsMilked, LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::itemsCollected[Tile::pumpkin->id], + LEADERBOARD_FARMING_PEACEFUL)); + + statBoards.insert( + std::make_pair(Stats::walkOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::fallOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::minecartOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::boatOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); #endif } -bool StatsCounter::isLargeStat(Stat* stat) -{ +bool StatsCounter::isLargeStat(Stat* stat) { #ifndef _DURANGO - Stat*** end = &LARGE_STATS[LARGE_STATS_COUNT]; - for( Stat*** iter = LARGE_STATS ; iter != end ; ++iter ) - if( (*(*iter))->id == stat->id ) - return true; + Stat*** end = &LARGE_STATS[LARGE_STATS_COUNT]; + for (Stat*** iter = LARGE_STATS; iter != end; ++iter) + if ((*(*iter))->id == stat->id) return true; #endif - return false; + return false; } -void StatsCounter::dumpStatsToTTY() -{ - std::vector::iterator statsEnd = Stats::all->end(); - for( std::vector::iterator statsIter = Stats::all->begin() ; statsIter!=statsEnd ; ++statsIter ) - { - app.DebugPrintf("%ls\t\t%u\t%u\t%u\t%u\n", - (*statsIter)->name.c_str(), - getValue(*statsIter, 0), - getValue(*statsIter, 1), - getValue(*statsIter, 2), - getValue(*statsIter, 3) - ); - } +void StatsCounter::dumpStatsToTTY() { + std::vector::iterator statsEnd = Stats::all->end(); + for (std::vector::iterator statsIter = Stats::all->begin(); + statsIter != statsEnd; ++statsIter) { + app.DebugPrintf("%ls\t\t%u\t%u\t%u\t%u\n", (*statsIter)->name.c_str(), + getValue(*statsIter, 0), getValue(*statsIter, 1), + getValue(*statsIter, 2), getValue(*statsIter, 3)); + } } #ifdef _DEBUG -//To clear leaderboards set DEBUG_ENABLE_CLEAR_LEADERBOARDS to 1 and set DEBUG_CLEAR_LEADERBOARDS to be the bitmask of what you want to clear -//Leaderboards are updated on game exit so enter and exit a level to trigger the clear +// To clear leaderboards set DEBUG_ENABLE_CLEAR_LEADERBOARDS to 1 and set +// DEBUG_CLEAR_LEADERBOARDS to be the bitmask of what you want to clear +// Leaderboards are updated on game exit so enter and exit a level to trigger +// the clear -//#define DEBUG_CLEAR_LEADERBOARDS (LEADERBOARD_KILLS_EASY | LEADERBOARD_KILLS_NORMAL | LEADERBOARD_KILLS_HARD) -#define DEBUG_CLEAR_LEADERBOARDS (0xFFFFFFFF) +// #define DEBUG_CLEAR_LEADERBOARDS (LEADERBOARD_KILLS_EASY +// | LEADERBOARD_KILLS_NORMAL | LEADERBOARD_KILLS_HARD) +#define DEBUG_CLEAR_LEADERBOARDS (0xFFFFFFFF) #define DEBUG_ENABLE_CLEAR_LEADERBOARDS -void StatsCounter::WipeLeaderboards() -{ - +void StatsCounter::WipeLeaderboards() { #if defined DEBUG_ENABLE_CLEAR_LEADERBOARDS && defined _XBOX - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, NULL); - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->CloseSession(); - } -#endif + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, NULL); + // if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, NULL); + // if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, NULL); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->CloseSession(); + } +#endif } #endif diff --git a/Minecraft.Client/GameState/StatsCounter.h b/Minecraft.Client/GameState/StatsCounter.h index 55298ae01..b02a09ad2 100644 --- a/Minecraft.Client/GameState/StatsCounter.h +++ b/Minecraft.Client/GameState/StatsCounter.h @@ -5,100 +5,96 @@ class Achievement; class StatsSyncher; class User; - -class StatsCounter -{ +class StatsCounter { private: + enum eDifficulty { + eDifficulty_Peaceful = 0, + eDifficulty_Easy, + eDifficulty_Normal, + eDifficulty_Hard, + eDifficulty_Max + }; - enum eDifficulty - { - eDifficulty_Peaceful=0, - eDifficulty_Easy, - eDifficulty_Normal, - eDifficulty_Hard, - eDifficulty_Max - }; + struct StatContainer { + unsigned int stats[eDifficulty_Max]; - struct StatContainer - { - unsigned int stats[eDifficulty_Max]; + StatContainer() { + stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] = + stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0; + } + }; - StatContainer() - { - stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] = stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0; - } - }; - - typedef std::unordered_map StatsMap; + typedef std::unordered_map StatsMap; - //static const int STAT_DATA_OFFSET = 32; - static const int LARGE_STATS_COUNT = 8; - static Stat** LARGE_STATS[LARGE_STATS_COUNT]; - static const int SAVE_DELAY = 30*60; - static const int FLUSH_DELAY = 30*60*5; + // static const int STAT_DATA_OFFSET = 32; + static const int LARGE_STATS_COUNT = 8; + static Stat** LARGE_STATS[LARGE_STATS_COUNT]; + static const int SAVE_DELAY = 30 * 60; + static const int FLUSH_DELAY = 30 * 60 * 5; - typedef enum { - LEADERBOARD_KILLS_PEACEFUL = 0x00000001, - LEADERBOARD_KILLS_EASY = 0x00000002, - LEADERBOARD_KILLS_NORMAL = 0x00000004, - LEADERBOARD_KILLS_HARD = 0x00000008, - LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010, - LEADERBOARD_MININGBLOCKS_EASY = 0x00000020, - LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040, - LEADERBOARD_MININGBLOCKS_HARD = 0x00000080, - LEADERBOARD_MININGORE_PEACEFUL = 0x00000100, - LEADERBOARD_MININGORE_EASY = 0x00000200, - LEADERBOARD_MININGORE_NORMAL = 0x00000400, - LEADERBOARD_MININGORE_HARD = 0x00000800, - LEADERBOARD_FARMING_PEACEFUL = 0x00001000, - LEADERBOARD_FARMING_EASY = 0x00002000, - LEADERBOARD_FARMING_NORMAL = 0x00004000, - LEADERBOARD_FARMING_HARD = 0x00008000, - LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000, - LEADERBOARD_TRAVELLING_EASY = 0x00020000, - LEADERBOARD_TRAVELLING_NORMAL = 0x00040000, - LEADERBOARD_TRAVELLING_HARD = 0x00080000, - LEADERBOARD_NETHER_PEACEFUL = 0x00100000, - LEADERBOARD_NETHER_EASY = 0x00200000, - LEADERBOARD_NETHER_NORMAL = 0x00400000, - LEADERBOARD_NETHER_HARD = 0x00800000, - LEADERBOARD_TRAVELLING_TOTAL = 0x01000000 - } LEADERBOARD_FLAG; + typedef enum { + LEADERBOARD_KILLS_PEACEFUL = 0x00000001, + LEADERBOARD_KILLS_EASY = 0x00000002, + LEADERBOARD_KILLS_NORMAL = 0x00000004, + LEADERBOARD_KILLS_HARD = 0x00000008, + LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010, + LEADERBOARD_MININGBLOCKS_EASY = 0x00000020, + LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040, + LEADERBOARD_MININGBLOCKS_HARD = 0x00000080, + LEADERBOARD_MININGORE_PEACEFUL = 0x00000100, + LEADERBOARD_MININGORE_EASY = 0x00000200, + LEADERBOARD_MININGORE_NORMAL = 0x00000400, + LEADERBOARD_MININGORE_HARD = 0x00000800, + LEADERBOARD_FARMING_PEACEFUL = 0x00001000, + LEADERBOARD_FARMING_EASY = 0x00002000, + LEADERBOARD_FARMING_NORMAL = 0x00004000, + LEADERBOARD_FARMING_HARD = 0x00008000, + LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000, + LEADERBOARD_TRAVELLING_EASY = 0x00020000, + LEADERBOARD_TRAVELLING_NORMAL = 0x00040000, + LEADERBOARD_TRAVELLING_HARD = 0x00080000, + LEADERBOARD_NETHER_PEACEFUL = 0x00100000, + LEADERBOARD_NETHER_EASY = 0x00200000, + LEADERBOARD_NETHER_NORMAL = 0x00400000, + LEADERBOARD_NETHER_HARD = 0x00800000, + LEADERBOARD_TRAVELLING_TOTAL = 0x01000000 + } LEADERBOARD_FLAG; - StatsMap stats; + StatsMap stats; bool requiresSave; - int saveCounter; + int saveCounter; - int modifiedBoards; - static std::unordered_map statBoards; - int flushCounter; + int modifiedBoards; + static std::unordered_map statBoards; + int flushCounter; public: - StatsCounter(); - void award(Stat *stat, unsigned int difficulty, unsigned int count); - bool hasTaken(Achievement *ach); - bool canTake(Achievement *ach); - unsigned int getValue(Stat *stat, unsigned int difficulty); - unsigned int getTotalValue(Stat *stat); + StatsCounter(); + void award(Stat* stat, unsigned int difficulty, unsigned int count); + bool hasTaken(Achievement* ach); + bool canTake(Achievement* ach); + unsigned int getValue(Stat* stat, unsigned int difficulty); + unsigned int getTotalValue(Stat* stat); void tick(int player); - void parse(void* data); - void clear(); - void save(int player, bool force=false); - void flushLeaderboards(); - void saveLeaderboards(); - static void setupStatBoards(); + void parse(void* data); + void clear(); + void save(int player, bool force = false); + void flushLeaderboards(); + void saveLeaderboards(); + static void setupStatBoards(); #ifdef _DEBUG - void WipeLeaderboards(); + void WipeLeaderboards(); #endif private: - bool isLargeStat(Stat* stat); - void dumpStatsToTTY(); + bool isLargeStat(Stat* stat); + void dumpStatsToTTY(); #ifdef _XBOX - static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, unsigned int value); - static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value); + static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, + unsigned int value); + static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value); #endif - void writeStats(); + void writeStats(); }; diff --git a/Minecraft.Client/GameState/StatsSyncer.h b/Minecraft.Client/GameState/StatsSyncer.h index 0742acc3d..61d59aaf1 100644 --- a/Minecraft.Client/GameState/StatsSyncer.h +++ b/Minecraft.Client/GameState/StatsSyncer.h @@ -5,42 +5,46 @@ class User; class File; class Stat; - -class StatsSyncher -{ +class StatsSyncher { private: - static const int SAVE_INTERVAL = 20 * 5; + static const int SAVE_INTERVAL = 20 * 5; static const int SEND_INTERVAL = 20 * 60; volatile bool busy; - volatile std::unordered_map *serverStats; - volatile std::unordered_map *failedSentStats; + volatile std::unordered_map* serverStats; + volatile std::unordered_map* failedSentStats; - StatsCounter *statsCounter; + StatsCounter* statsCounter; File *unsentFile, *lastServerFile; File *unsentFileTmp, *lastServerFileTmp; File *unsentFileOld, *lastServerFileOld; - User *user; + User* user; int noSaveIn, noSendIn; public: - StatsSyncher(User *user, StatsCounter *statsCounter, File *dir); + StatsSyncher(User* user, StatsCounter* statsCounter, File* dir); + private: - void attemptRename(File *dir, const std::wstring& name, File *to); - std::unordered_map *loadStatsFromDisk(File *file, File *tmp, File *old); - std::unordered_map *loadStatsFromDisk(File *file); - void doSend(std::unordered_map *stats); - void doSave(std::unordered_map *stats, File *file, File *tmp, File *old); + void attemptRename(File* dir, const std::wstring& name, File* to); + std::unordered_map* loadStatsFromDisk(File* file, File* tmp, + File* old); + std::unordered_map* loadStatsFromDisk(File* file); + void doSend(std::unordered_map* stats); + void doSave(std::unordered_map* stats, File* file, File* tmp, + File* old); + protected: - std::unordered_map *doGetStats(); + std::unordered_map* doGetStats(); + public: - void getStatsFromServer(); - void saveUnsent(std::unordered_map *stats); - void sendUnsent(std::unordered_map *stats, std::unordered_map *fullStats); - void forceSendUnsent(std::unordered_map *stats); - void forceSaveUnsent(std::unordered_map *stats); + void getStatsFromServer(); + void saveUnsent(std::unordered_map* stats); + void sendUnsent(std::unordered_map* stats, + std::unordered_map* fullStats); + void forceSendUnsent(std::unordered_map* stats); + void forceSaveUnsent(std::unordered_map* stats); bool maySave(); bool maySend(); void tick(); diff --git a/Minecraft.Client/GameState/SurvivalMode.cpp b/Minecraft.Client/GameState/SurvivalMode.cpp index 7fdf0dd27..ddf96d737 100644 --- a/Minecraft.Client/GameState/SurvivalMode.cpp +++ b/Minecraft.Client/GameState/SurvivalMode.cpp @@ -11,10 +11,9 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../ClientConstants.h" -SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft) -{ - // 4J - added initialisers - xDestroyBlock = -1; +SurvivalMode::SurvivalMode(Minecraft* minecraft) : GameMode(minecraft) { + // 4J - added initialisers + xDestroyBlock = -1; yDestroyBlock = -1; zDestroyBlock = -1; destroyProgress = 0; @@ -22,122 +21,103 @@ SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft) destroyTicks = 0; destroyDelay = 0; - if (ClientConstants::IS_DEMO_VERSION) - { - if( dynamic_cast(this) == NULL ) - { - assert(false); -// throw new IllegalStateException("Invalid game mode"); // 4J - removed + if (ClientConstants::IS_DEMO_VERSION) { + if (dynamic_cast(this) == NULL) { + assert(false); + // throw new IllegalStateException("Invalid game mode"); + // // 4J - removed } } } -// 4J Stu - Added this ctor so we can exit the tutorial and replace it with a standard -// survival mode -SurvivalMode::SurvivalMode(SurvivalMode *copy) : GameMode( copy->minecraft ) -{ - xDestroyBlock = copy->xDestroyBlock; - yDestroyBlock = copy->yDestroyBlock; - zDestroyBlock = copy->zDestroyBlock; - destroyProgress = copy->destroyProgress; - oDestroyProgress = copy->oDestroyProgress; - destroyTicks = copy->destroyTicks; +// 4J Stu - Added this ctor so we can exit the tutorial and replace it with a +// standard survival mode +SurvivalMode::SurvivalMode(SurvivalMode* copy) : GameMode(copy->minecraft) { + xDestroyBlock = copy->xDestroyBlock; + yDestroyBlock = copy->yDestroyBlock; + zDestroyBlock = copy->zDestroyBlock; + destroyProgress = copy->destroyProgress; + oDestroyProgress = copy->oDestroyProgress; + destroyTicks = copy->destroyTicks; destroyDelay = copy->destroyDelay; } -void SurvivalMode::initPlayer(std::shared_ptr player) -{ - player->yRot = -180; +void SurvivalMode::initPlayer(std::shared_ptr player) { + player->yRot = -180; } -void SurvivalMode::init() -{ -} +void SurvivalMode::init() {} -bool SurvivalMode::canHurtPlayer() -{ - return true; -} +bool SurvivalMode::canHurtPlayer() { return true; } -bool SurvivalMode::destroyBlock(int x, int y, int z, int face) -{ +bool SurvivalMode::destroyBlock(int x, int y, int z, int face) { int t = minecraft->level->getTile(x, y, z); int data = minecraft->level->getData(x, y, z); bool changed = GameMode::destroyBlock(x, y, z, face); std::shared_ptr item = minecraft->player->getSelectedItem(); bool couldDestroy = minecraft->player->canDestroy(Tile::tiles[t]); - if (item != NULL) - { + if (item != NULL) { item->mineBlock(minecraft->level, t, x, y, z, minecraft->player); - if (item->count == 0) - { + if (item->count == 0) { minecraft->player->removeSelectedItem(); } } - if (changed && couldDestroy) - { - Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, z, data); - } + if (changed && couldDestroy) { + Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, + z, data); + } return changed; - } -void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) -{ - if (!minecraft->player->mayBuild(x, y, z)) return; +void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->mayBuild(x, y, z)) return; minecraft->level->extinguishFire(minecraft->player, x, y, z, face); int t = minecraft->level->getTile(x, y, z); - if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); - if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) - { + if (t > 0 && destroyProgress == 0) + Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); + if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) { destroyBlock(x, y, z, face); } } -void SurvivalMode::stopDestroyBlock() -{ +void SurvivalMode::stopDestroyBlock() { destroyProgress = 0; destroyDelay = 0; } -void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if (destroyDelay > 0) - { +void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) { + if (destroyDelay > 0) { destroyDelay--; return; } - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { int t = minecraft->level->getTile(x, y, z); - if (!minecraft->player->mayBuild(x, y, z)) return; + if (!minecraft->player->mayBuild(x, y, z)) return; if (t == 0) return; - Tile *tile = Tile::tiles[t]; + Tile* tile = Tile::tiles[t]; destroyProgress += tile->getDestroyProgress(minecraft->player); - if (destroyTicks % 4 == 0) - { - if (tile != NULL) - { - minecraft->soundEngine->play(tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); + if (destroyTicks % 4 == 0) { + if (tile != NULL) { + minecraft->soundEngine->play( + tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, + z + 0.5f, (tile->soundType->getVolume() + 1) / 8, + tile->soundType->getPitch() * 0.5f); } } destroyTicks++; - if (destroyProgress >= 1) - { + if (destroyProgress >= 1) { destroyBlock(x, y, z, face); destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; destroyDelay = 5; } - } - else - { + } else { destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; @@ -145,64 +125,49 @@ void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) yDestroyBlock = y; zDestroyBlock = z; } - } -void SurvivalMode::render(float a) -{ - if (destroyProgress <= 0) - { +void SurvivalMode::render(float a) { + if (destroyProgress <= 0) { minecraft->gui->progress = 0; minecraft->levelRenderer->destroyProgress = 0; - } - else - { + } else { float dp = oDestroyProgress + (destroyProgress - oDestroyProgress) * a; minecraft->gui->progress = dp; minecraft->levelRenderer->destroyProgress = dp; } } -float SurvivalMode::getPickRange() -{ - return 4.0f; +float SurvivalMode::getPickRange() { return 4.0f; } + +void SurvivalMode::initLevel(Level* level) { GameMode::initLevel(level); } + +std::shared_ptr SurvivalMode::createPlayer(Level* level) { + std::shared_ptr player = GameMode::createPlayer(level); + // player.inventory.add(new ItemInstance(Item.pickAxe_diamond)); + // player.inventory.add(new ItemInstance(Item.hatchet_diamond)); + // player.inventory.add(new ItemInstance(Tile.torch, 64)); + // player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4)); + // player.inventory.add(new ItemInstance(Item.bow, 1)); + // player.inventory.add(new ItemInstance(Item.arrow, 64)); + return player; } -void SurvivalMode::initLevel(Level *level) -{ - GameMode::initLevel(level); -} - -std::shared_ptr SurvivalMode::createPlayer(Level *level) -{ - std::shared_ptr player = GameMode::createPlayer(level); - // player.inventory.add(new ItemInstance(Item.pickAxe_diamond)); - // player.inventory.add(new ItemInstance(Item.hatchet_diamond)); - // player.inventory.add(new ItemInstance(Tile.torch, 64)); - // player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4)); - // player.inventory.add(new ItemInstance(Item.bow, 1)); - // player.inventory.add(new ItemInstance(Item.arrow, 64)); - return player; -} - -void SurvivalMode::tick() -{ +void SurvivalMode::tick() { oDestroyProgress = destroyProgress; - //minecraft->soundEngine->playMusicTick(); + // minecraft->soundEngine->playMusicTick(); } -bool SurvivalMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) -{ - int t = level->getTile(x, y, z); - if (t > 0) - { - if (Tile::tiles[t]->use(level, x, y, z, player)) return true; - } - if (item == NULL) return false; - return item->useOn(player, level, x, y, z, face); +bool SurvivalMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly, + bool* pbUsedItem) { + int t = level->getTile(x, y, z); + if (t > 0) { + if (Tile::tiles[t]->use(level, x, y, z, player)) return true; + } + if (item == NULL) return false; + return item->useOn(player, level, x, y, z, face); } -bool SurvivalMode::hasExperience() -{ - return true; -} \ No newline at end of file +bool SurvivalMode::hasExperience() { return true; } \ No newline at end of file diff --git a/Minecraft.Client/GameState/SurvivalMode.h b/Minecraft.Client/GameState/SurvivalMode.h index 643e50d15..406cdcc1e 100644 --- a/Minecraft.Client/GameState/SurvivalMode.h +++ b/Minecraft.Client/GameState/SurvivalMode.h @@ -1,32 +1,34 @@ #pragma once #include "GameMode.h" -class SurvivalMode : public GameMode -{ +class SurvivalMode : public GameMode { private: - int xDestroyBlock; + int xDestroyBlock; int yDestroyBlock; int zDestroyBlock; float destroyProgress; float oDestroyProgress; - int destroyTicks; // 4J was float but doesn't seem to need to be + int destroyTicks; // 4J was float but doesn't seem to need to be int destroyDelay; public: - SurvivalMode(Minecraft *minecraft); - SurvivalMode(SurvivalMode *copy); + SurvivalMode(Minecraft* minecraft); + SurvivalMode(SurvivalMode* copy); virtual void initPlayer(std::shared_ptr player); virtual void init(); - virtual bool canHurtPlayer(); + virtual bool canHurtPlayer(); virtual bool destroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face); virtual void stopDestroyBlock(); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual void render(float a); virtual float getPickRange(); - virtual void initLevel(Level *level); - virtual std::shared_ptr createPlayer(Level *level); + virtual void initLevel(Level* level); + virtual std::shared_ptr createPlayer(Level* level); virtual void tick(); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); - virtual bool hasExperience(); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL); + virtual bool hasExperience(); }; \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInput.cpp b/Minecraft.Client/Input/ConsoleInput.cpp index 98f047d18..66aebd432 100644 --- a/Minecraft.Client/Input/ConsoleInput.cpp +++ b/Minecraft.Client/Input/ConsoleInput.cpp @@ -1,8 +1,8 @@ #include "../Platform/stdafx.h" #include "ConsoleInput.h" -ConsoleInput::ConsoleInput(const std::wstring& msg, ConsoleInputSource *source) -{ - this->msg = msg; - this->source = source; +ConsoleInput::ConsoleInput(const std::wstring& msg, + ConsoleInputSource* source) { + this->msg = msg; + this->source = source; } \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInput.h b/Minecraft.Client/Input/ConsoleInput.h index db228631a..4b0d36fbe 100644 --- a/Minecraft.Client/Input/ConsoleInput.h +++ b/Minecraft.Client/Input/ConsoleInput.h @@ -1,12 +1,10 @@ #pragma once #include "ConsoleInputSource.h" - -class ConsoleInput -{ +class ConsoleInput { public: - std::wstring msg; - ConsoleInputSource *source; + std::wstring msg; + ConsoleInputSource* source; - ConsoleInput(const std::wstring& msg, ConsoleInputSource *source); + ConsoleInput(const std::wstring& msg, ConsoleInputSource* source); }; \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInputSource.h b/Minecraft.Client/Input/ConsoleInputSource.h index 391d12916..82b66214a 100644 --- a/Minecraft.Client/Input/ConsoleInputSource.h +++ b/Minecraft.Client/Input/ConsoleInputSource.h @@ -1,10 +1,9 @@ #pragma once -class ConsoleInputSource -{ +class ConsoleInputSource { public: - virtual ~ConsoleInputSource(){} - virtual void info(const std::wstring& string) = 0; + virtual ~ConsoleInputSource() {} + virtual void info(const std::wstring& string) = 0; virtual void warn(const std::wstring& string) = 0; virtual std::wstring getConsoleName() = 0; }; diff --git a/Minecraft.Client/Input/Input.cpp b/Minecraft.Client/Input/Input.cpp index 439a0e536..69b5e9f09 100644 --- a/Minecraft.Client/Input/Input.cpp +++ b/Minecraft.Client/Input/Input.cpp @@ -8,108 +8,123 @@ #include "../Player/LocalPlayer.h" #include "../GameState/Options.h" -Input::Input() -{ - xa = 0; - ya = 0; - wasJumping = false; - jumping = false; - sneaking = false; - sprintKey = false; +Input::Input() { + xa = 0; + ya = 0; + wasJumping = false; + jumping = false; + sneaking = false; + sprintKey = false; - lReset = false; + lReset = false; rReset = false; } -void Input::tick(LocalPlayer *player) -{ - // 4J Stu - Assume that we only need one input class, even though the java has subclasses for keyboard/controller - // This function is based on the ControllerInput class in the Java, and will probably need changed - //OutputDebugString("INPUT: Beginning input tick\n"); +void Input::tick(LocalPlayer* player) { + // 4J Stu - Assume that we only need one input class, even though the java + // has subclasses for keyboard/controller This function is based on the + // ControllerInput class in the Java, and will probably need changed + // OutputDebugString("INPUT: Beginning input tick\n"); - Minecraft *pMinecraft=Minecraft::GetInstance(); - int iPad=player->GetXboxPad(); + Minecraft* pMinecraft = Minecraft::GetInstance(); + int iPad = player->GetXboxPad(); - // 4J-PB minecraft movement seems to be the wrong way round, so invert x! - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_RIGHT) ) - xa = -InputManager.GetJoypadStick_LX(iPad); - else - xa = 0.0f; - - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_FORWARD) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_BACKWARD) ) - ya = InputManager.GetJoypadStick_LY(iPad); - else - ya = 0.0f; + // 4J-PB minecraft movement seems to be the wrong way round, so invert x! + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LEFT) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_RIGHT)) + xa = -InputManager.GetJoypadStick_LX(iPad); + else + xa = 0.0f; + + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_FORWARD) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_BACKWARD)) + ya = InputManager.GetJoypadStick_LY(iPad); + else + ya = 0.0f; #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) - { - xa = ya = 0.0f; - player->abilities.flying = true; - } + if (app.GetFreezePlayers()) { + xa = ya = 0.0f; + player->abilities.flying = true; + } #endif - - if (!lReset) - { - if (xa*xa+ya*ya==0.0f) - { + + if (!lReset) { + if (xa * xa + ya * ya == 0.0f) { lReset = true; } xa = ya = 0.0f; } - // 4J - in flying mode, don't actually toggle sneaking - if(!player->abilities.flying) - { - if((player->ullButtonsPressed&(1LL<localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SNEAK_TOGGLE)) - { - sneaking=!sneaking; - } - } + // 4J - in flying mode, don't actually toggle sneaking + if (!player->abilities.flying) { + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_SNEAK_TOGGLE)) && + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_SNEAK_TOGGLE)) { + sneaking = !sneaking; + } + } - if(sneaking) - { - xa*=0.3f; - ya*=0.3f; - } + if (sneaking) { + xa *= 0.3f; + ya *= 0.3f; + } float turnSpeed = 50.0f; - float tx = 0.0f; - float ty = 0.0f; - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_RIGHT) ) - tx = InputManager.GetJoypadStick_RX(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_UP) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_DOWN) ) - ty = InputManager.GetJoypadStick_RY(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look - + float tx = 0.0f; + float ty = 0.0f; + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_LEFT) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_RIGHT)) + tx = InputManager.GetJoypadStick_RX(iPad) * + (((float)app.GetGameSettings(iPad, + eGameSetting_Sensitivity_InGame)) / + 100.0f); // apply sensitivity to look + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_UP) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_DOWN)) + ty = InputManager.GetJoypadStick_RY(iPad) * + (((float)app.GetGameSettings(iPad, + eGameSetting_Sensitivity_InGame)) / + 100.0f); // apply sensitivity to look + #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) tx = ty = 0.0f; + if (app.GetFreezePlayers()) tx = ty = 0.0f; #endif - // 4J: WESTY : Invert look Y if required. - if ( app.GetGameSettings(iPad,eGameSetting_ControlInvertLook) ) - { - ty = -ty; - } + // 4J: WESTY : Invert look Y if required. + if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook)) { + ty = -ty; + } - if (!rReset) - { - if (tx*tx+ty*ty==0.0f) - { + if (!rReset) { + if (tx * tx + ty * ty == 0.0f) { rReset = true; } tx = ty = 0.0f; } - player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed); - - //jumping = controller.isButtonPressed(0); + player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed); - sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SPRINT); - jumping = InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP); + // jumping = controller.isButtonPressed(0); + + sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_SPRINT); + jumping = + InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && + pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP); #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) jumping = false; + if (app.GetFreezePlayers()) jumping = false; #endif - //OutputDebugString("INPUT: End input tick\n"); + // OutputDebugString("INPUT: End input tick\n"); } \ No newline at end of file diff --git a/Minecraft.Client/Input/Input.h b/Minecraft.Client/Input/Input.h index d30df79a2..fc2dc03dc 100644 --- a/Minecraft.Client/Input/Input.h +++ b/Minecraft.Client/Input/Input.h @@ -1,24 +1,22 @@ #pragma once class Player; -class Input -{ +class Input { public: - float xa; + float xa; float ya; bool wasJumping; bool jumping; bool sneaking; bool sprintKey; - - Input(); // 4J - added - virtual ~Input(){} - virtual void tick(LocalPlayer *player); + Input(); // 4J - added + virtual ~Input() {} + + virtual void tick(LocalPlayer* player); private: - bool lReset; bool rReset; }; diff --git a/Minecraft.Client/Input/KeyMapping.cpp b/Minecraft.Client/Input/KeyMapping.cpp index b993aabec..c439bde54 100644 --- a/Minecraft.Client/Input/KeyMapping.cpp +++ b/Minecraft.Client/Input/KeyMapping.cpp @@ -1,8 +1,7 @@ #include "../Platform/stdafx.h" #include "KeyMapping.h" -KeyMapping::KeyMapping(const std::wstring& name, int key) -{ - this->name = name; - this->key = key; +KeyMapping::KeyMapping(const std::wstring& name, int key) { + this->name = name; + this->key = key; } \ No newline at end of file diff --git a/Minecraft.Client/Input/KeyMapping.h b/Minecraft.Client/Input/KeyMapping.h index 85ac8d211..6f06e6c1a 100644 --- a/Minecraft.Client/Input/KeyMapping.h +++ b/Minecraft.Client/Input/KeyMapping.h @@ -1,10 +1,9 @@ #pragma once // 4J Stu - Not updated to 1.8.2 as we don't use this -class KeyMapping -{ +class KeyMapping { public: - std::wstring name; - int key; - KeyMapping(const std::wstring& name, int key); + std::wstring name; + int key; + KeyMapping(const std::wstring& name, int key); }; \ No newline at end of file diff --git a/Minecraft.Client/Level/DemoLevel.cpp b/Minecraft.Client/Level/DemoLevel.cpp index f7d633e96..6549de08d 100644 --- a/Minecraft.Client/Level/DemoLevel.cpp +++ b/Minecraft.Client/Level/DemoLevel.cpp @@ -2,24 +2,17 @@ #include "DemoLevel.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.storage.h" -LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS = LevelSettings( - DemoLevel::DEMO_LEVEL_SEED, - GameType::SURVIVAL, - false, - false, - false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH, - 1.0 -); +LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS = + LevelSettings(DemoLevel::DEMO_LEVEL_SEED, GameType::SURVIVAL, false, false, + false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH, 1.0); -DemoLevel::DemoLevel(std::shared_ptr levelStorage, const std::wstring& levelName) : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) -{ -} +DemoLevel::DemoLevel(std::shared_ptr levelStorage, + const std::wstring& levelName) + : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) {} -DemoLevel::DemoLevel(Level *level, Dimension *dimension): Level(level, dimension) -{ -} +DemoLevel::DemoLevel(Level* level, Dimension* dimension) + : Level(level, dimension) {} -void DemoLevel::setInitialSpawn() -{ - levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z); +void DemoLevel::setInitialSpawn() { + levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z); } \ No newline at end of file diff --git a/Minecraft.Client/Level/DemoLevel.h b/Minecraft.Client/Level/DemoLevel.h index d8639dee7..4bfa37984 100644 --- a/Minecraft.Client/Level/DemoLevel.h +++ b/Minecraft.Client/Level/DemoLevel.h @@ -1,17 +1,20 @@ #pragma once #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" -class DemoLevel : public Level -{ +class DemoLevel : public Level { private: - static const __int64 DEMO_LEVEL_SEED = 0; // 4J - TODO - was "Don't Look Back".hashCode(); + static const __int64 DEMO_LEVEL_SEED = + 0; // 4J - TODO - was "Don't Look Back".hashCode(); static const int DEMO_SPAWN_X = 796; static const int DEMO_SPAWN_Y = 72; static const int DEMO_SPAWN_Z = -731; static LevelSettings DEMO_LEVEL_SETTINGS; + public: - DemoLevel(std::shared_ptr levelStorage, const std::wstring& levelName); - DemoLevel(Level *level, Dimension *dimension); + DemoLevel(std::shared_ptr levelStorage, + const std::wstring& levelName); + DemoLevel(Level* level, Dimension* dimension); + protected: - virtual void setInitialSpawn(); + virtual void setInitialSpawn(); }; diff --git a/Minecraft.Client/Level/DerivedServerLevel.cpp b/Minecraft.Client/Level/DerivedServerLevel.cpp index 199db90fc..0038111b3 100644 --- a/Minecraft.Client/Level/DerivedServerLevel.cpp +++ b/Minecraft.Client/Level/DerivedServerLevel.cpp @@ -3,27 +3,28 @@ #include "../../Minecraft.World/Level/Storage/SavedDataStorage.h" #include "../../Minecraft.World/Level/DerivedLevelData.h" -DerivedServerLevel::DerivedServerLevel(MinecraftServer *server, std::shared_ptr levelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped) - : ServerLevel(server, levelStorage, levelName, dimension, levelSettings) -{ - // 4J-PB - we're going to override the savedDataStorage, so we need to delete the current one - if(this->savedDataStorage) - { - delete this->savedDataStorage; - this->savedDataStorage=NULL; - } - this->savedDataStorage = wrapped->savedDataStorage; - levelData = new DerivedLevelData(wrapped->getLevelData()); +DerivedServerLevel::DerivedServerLevel( + MinecraftServer* server, std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, LevelSettings* levelSettings, + ServerLevel* wrapped) + : ServerLevel(server, levelStorage, levelName, dimension, levelSettings) { + // 4J-PB - we're going to override the savedDataStorage, so we need to + // delete the current one + if (this->savedDataStorage) { + delete this->savedDataStorage; + this->savedDataStorage = NULL; + } + this->savedDataStorage = wrapped->savedDataStorage; + levelData = new DerivedLevelData(wrapped->getLevelData()); } -DerivedServerLevel::~DerivedServerLevel() -{ - // we didn't allocate savedDataStorage here, so we don't want the level destructor to delete it - this->savedDataStorage=NULL; +DerivedServerLevel::~DerivedServerLevel() { + // we didn't allocate savedDataStorage here, so we don't want the level + // destructor to delete it + this->savedDataStorage = NULL; } -void DerivedServerLevel::saveLevelData() -{ - // Do nothing? - // Do nothing! +void DerivedServerLevel::saveLevelData() { + // Do nothing? + // Do nothing! } \ No newline at end of file diff --git a/Minecraft.Client/Level/DerivedServerLevel.h b/Minecraft.Client/Level/DerivedServerLevel.h index 2c9048563..72e63880d 100644 --- a/Minecraft.Client/Level/DerivedServerLevel.h +++ b/Minecraft.Client/Level/DerivedServerLevel.h @@ -1,12 +1,14 @@ #pragma once #include "ServerLevel.h" -class DerivedServerLevel : public ServerLevel -{ +class DerivedServerLevel : public ServerLevel { public: - DerivedServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped); - ~DerivedServerLevel(); + DerivedServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings, ServerLevel* wrapped); + ~DerivedServerLevel(); protected: - void saveLevelData(); + void saveLevelData(); }; \ No newline at end of file diff --git a/Minecraft.Client/Level/MultiPlayerLevel.cpp b/Minecraft.Client/Level/MultiPlayerLevel.cpp index dc901fef7..4f0055489 100644 --- a/Minecraft.Client/Level/MultiPlayerLevel.cpp +++ b/Minecraft.Client/Level/MultiPlayerLevel.cpp @@ -13,8 +13,8 @@ #include "../../Minecraft.World/Blocks/Tile.h" #include "../../Minecraft.World/Blocks/TileEntities/TileEntity.h" -MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, int data) -{ +MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, + int data) { this->x = x; this->y = y; this->z = z; @@ -23,406 +23,407 @@ MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, int data) this->data = data; } -MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty) - : Level(std::shared_ptr(new MockedLevelStorage()), L"MpServer", Dimension::getNew(dimension), levelSettings, false) -{ - minecraft = Minecraft::GetInstance(); +MultiPlayerLevel::MultiPlayerLevel(ClientConnection* connection, + LevelSettings* levelSettings, int dimension, + int difficulty) + : Level(std::shared_ptr(new MockedLevelStorage()), + L"MpServer", Dimension::getNew(dimension), levelSettings, false) { + minecraft = Minecraft::GetInstance(); - // 4J - this this used to be called in parent ctor via a virtual fn - chunkSource = createChunkSource(); - // 4J - optimisation - keep direct reference of underlying cache here - chunkSourceCache = chunkSource->getCache(); - chunkSourceXZSize = chunkSource->m_XZSize; + // 4J - this this used to be called in parent ctor via a virtual fn + chunkSource = createChunkSource(); + // 4J - optimisation - keep direct reference of underlying cache here + chunkSourceCache = chunkSource->getCache(); + chunkSourceXZSize = chunkSource->m_XZSize; - // This also used to be called in parent ctor, but can't be called until chunkSource is created. Call now if required. - if (!levelData->isInitialized()) - { - initializeLevel(levelSettings); - levelData->setInitialized(true); - } - - if(connection !=NULL) - { - this->connections.push_back( connection ); - } - this->difficulty = difficulty; - // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing towards the original spawn point, once the player has entered the Nether. - // 4J Stu - We should never be setting a specific spawn position for a multiplayer, this should only be set by receiving a packet from the server - // (which happens when a player logs in) - //setSpawnPos(new Pos(8, 64, 8)); - // The base ctor already has made some storage, so need to delete that - if( this->savedDataStorage ) delete savedDataStorage; - if(connection !=NULL) - { - this->savedDataStorage = connection->savedDataStorage; - } - unshareCheckX = 0; - unshareCheckZ = 0; - compressCheckX = 0; - compressCheckZ = 0; - - // 4J Added, as there are some times when we don't want to add tile updates to the updatesToReset vector - m_bEnableResetChanges = true; -} - -MultiPlayerLevel::~MultiPlayerLevel() -{ - // Don't let the base class delete this, it comes from the connection for multiplayerlevels, and we'll delete there - this->savedDataStorage = NULL; -} - -void MultiPlayerLevel::unshareChunkAt(int x, int z) -{ - if( g_NetworkManager.IsHost() ) - { - Level::getChunkAt(x,z)->stopSharingTilesAndData(); - } -} - -void MultiPlayerLevel::shareChunkAt(int x, int z) -{ - if( g_NetworkManager.IsHost() ) - { - Level::getChunkAt(x,z)->startSharingTilesAndData(); - } -} - - -void MultiPlayerLevel::tick() -{ - PIXBeginNamedEvent(0,"Sky color changing"); - setTime(getTime() + 1); - /* 4J - change brought forward from 1.8.2 - int newDark = this->getSkyDarken(1); - if (newDark != skyDarken) - { - skyDarken = newDark; - for (unsigned int i = 0; i < listeners.size(); i++) - { - listeners[i]->skyColorChanged(); - } - }*/ - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Entity re-entry"); - EnterCriticalSection(&m_entitiesCS); - for (int i = 0; i < 10 && !reEntries.empty(); i++) - { - std::shared_ptr e = *(reEntries.begin()); - - if (find(entities.begin(), entities.end(), e) == entities.end() ) addEntity(e); + // This also used to be called in parent ctor, but can't be called until + // chunkSource is created. Call now if required. + if (!levelData->isInitialized()) { + initializeLevel(levelSettings); + levelData->setInitialized(true); } - LeaveCriticalSection(&m_entitiesCS); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Connection ticking"); - // 4J HEG - Copy the connections vector to prevent crash when moving to Nether - std::vector connectionsTemp = connections; - for(AUTO_VAR(connection, connectionsTemp.begin()); connection < connectionsTemp.end(); ++connection ) - { - (*connection)->tick(); - } - PIXEndNamedEvent(); + if (connection != NULL) { + this->connections.push_back(connection); + } + this->difficulty = difficulty; + // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing + // towards the original spawn point, once the player has entered the Nether. + // 4J Stu - We should never be setting a specific spawn position for a + // multiplayer, this should only be set by receiving a packet from the + // server (which happens when a player logs in) + // setSpawnPos(new Pos(8, 64, 8)); + // The base ctor already has made some storage, so need to delete that + if (this->savedDataStorage) delete savedDataStorage; + if (connection != NULL) { + this->savedDataStorage = connection->savedDataStorage; + } + unshareCheckX = 0; + unshareCheckZ = 0; + compressCheckX = 0; + compressCheckZ = 0; - PIXBeginNamedEvent(0,"Updating resets"); - unsigned int lastIndexToRemove = 0; - bool eraseElements = false; - for (unsigned int i = 0; i < updatesToReset.size(); i++) - { + // 4J Added, as there are some times when we don't want to add tile updates + // to the updatesToReset vector + m_bEnableResetChanges = true; +} + +MultiPlayerLevel::~MultiPlayerLevel() { + // Don't let the base class delete this, it comes from the connection for + // multiplayerlevels, and we'll delete there + this->savedDataStorage = NULL; +} + +void MultiPlayerLevel::unshareChunkAt(int x, int z) { + if (g_NetworkManager.IsHost()) { + Level::getChunkAt(x, z)->stopSharingTilesAndData(); + } +} + +void MultiPlayerLevel::shareChunkAt(int x, int z) { + if (g_NetworkManager.IsHost()) { + Level::getChunkAt(x, z)->startSharingTilesAndData(); + } +} + +void MultiPlayerLevel::tick() { + PIXBeginNamedEvent(0, "Sky color changing"); + setTime(getTime() + 1); + /* 4J - change brought forward from 1.8.2 +int newDark = this->getSkyDarken(1); +if (newDark != skyDarken) + { + skyDarken = newDark; + for (unsigned int i = 0; i < listeners.size(); i++) + { + listeners[i]->skyColorChanged(); + } +}*/ + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Entity re-entry"); + EnterCriticalSection(&m_entitiesCS); + for (int i = 0; i < 10 && !reEntries.empty(); i++) { + std::shared_ptr e = *(reEntries.begin()); + + if (find(entities.begin(), entities.end(), e) == entities.end()) + addEntity(e); + } + LeaveCriticalSection(&m_entitiesCS); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Connection ticking"); + // 4J HEG - Copy the connections vector to prevent crash when moving to + // Nether + std::vector connectionsTemp = connections; + for (AUTO_VAR(connection, connectionsTemp.begin()); + connection < connectionsTemp.end(); ++connection) { + (*connection)->tick(); + } + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Updating resets"); + unsigned int lastIndexToRemove = 0; + bool eraseElements = false; + for (unsigned int i = 0; i < updatesToReset.size(); i++) { ResetInfo& r = updatesToReset[i]; - if (--r.ticks == 0) - { + if (--r.ticks == 0) { Level::setTileAndDataNoUpdate(r.x, r.y, r.z, r.tile, r.data); Level::sendTileUpdated(r.x, r.y, r.z); - - //updatesToReset.erase(updatesToReset.begin()+i); - eraseElements = true; - lastIndexToRemove = 0; - i--; + // updatesToReset.erase(updatesToReset.begin()+i); + eraseElements = true; + lastIndexToRemove = 0; + + i--; } } - // 4J Stu - As elements in the updatesToReset vector are inserted with a fixed initial lifetime, the elements at the front should always be the oldest - // Therefore we can always remove from the first element - if(eraseElements) - { - updatesToReset.erase(updatesToReset.begin(), updatesToReset.begin()+lastIndexToRemove); - } - PIXEndNamedEvent(); + // 4J Stu - As elements in the updatesToReset vector are inserted with a + // fixed initial lifetime, the elements at the front should always be the + // oldest Therefore we can always remove from the first element + if (eraseElements) { + updatesToReset.erase(updatesToReset.begin(), + updatesToReset.begin() + lastIndexToRemove); + } + PIXEndNamedEvent(); - chunkCache->tick(); - tickTiles(); + chunkCache->tick(); + tickTiles(); - // 4J - added this section. Each tick we'll check a different block, and force it to share data if it has been - // more than 2 minutes since we last wanted to unshare it. This shouldn't really ever happen, and is added - // here as a safe guard against accumulated memory leaks should a lot of chunks become unshared over time. - - int ls = dimension->getXZSize(); - if( g_NetworkManager.IsHost() ) - { - if( Level::reallyHasChunk(unshareCheckX - ( ls / 2), unshareCheckZ - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(unshareCheckX - ( ls / 2), unshareCheckZ - ( ls / 2 )); - if( g_NetworkManager.IsHost() ) - { - lc->startSharingTilesAndData(1000 * 60 * 2); - } - } + // 4J - added this section. Each tick we'll check a different block, and + // force it to share data if it has been more than 2 minutes since we last + // wanted to unshare it. This shouldn't really ever happen, and is added + // here as a safe guard against accumulated memory leaks should a lot of + // chunks become unshared over time. - unshareCheckX++; - if( unshareCheckX >= ls ) - { - unshareCheckX = 0; - unshareCheckZ++; - if( unshareCheckZ >= ls ) - { - unshareCheckZ = 0; - } - } - } + int ls = dimension->getXZSize(); + if (g_NetworkManager.IsHost()) { + if (Level::reallyHasChunk(unshareCheckX - (ls / 2), + unshareCheckZ - (ls / 2))) { + LevelChunk* lc = Level::getChunk(unshareCheckX - (ls / 2), + unshareCheckZ - (ls / 2)); + if (g_NetworkManager.IsHost()) { + lc->startSharingTilesAndData(1000 * 60 * 2); + } + } - // 4J added - also similar thing tosee if we can compress the lighting in any of these chunks. This is slightly different - // as it does try to make sure that at least one chunk has something done to it. + unshareCheckX++; + if (unshareCheckX >= ls) { + unshareCheckX = 0; + unshareCheckZ++; + if (unshareCheckZ >= ls) { + unshareCheckZ = 0; + } + } + } - // At most loop round at least one row the chunks, so we should be able to at least find a non-empty chunk to do something with in 2.7 seconds of ticks, and process the whole thing in about 2.4 minutes. - for( int i = 0; i < ls; i++ ) - { - compressCheckX++; - if( compressCheckX >= ls ) - { - compressCheckX = 0; - compressCheckZ++; - if( compressCheckZ >= ls ) - { - compressCheckZ = 0; - } - } + // 4J added - also similar thing tosee if we can compress the lighting in + // any of these chunks. This is slightly different as it does try to make + // sure that at least one chunk has something done to it. - if( Level::reallyHasChunk(compressCheckX - ( ls / 2), compressCheckZ - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(compressCheckX - ( ls / 2), compressCheckZ - ( ls / 2 )); - lc->compressLighting(); - lc->compressBlocks(); - lc->compressData(); - break; - } - } + // At most loop round at least one row the chunks, so we should be able to + // at least find a non-empty chunk to do something with in 2.7 seconds of + // ticks, and process the whole thing in about 2.4 minutes. + for (int i = 0; i < ls; i++) { + compressCheckX++; + if (compressCheckX >= ls) { + compressCheckX = 0; + compressCheckZ++; + if (compressCheckZ >= ls) { + compressCheckZ = 0; + } + } + + if (Level::reallyHasChunk(compressCheckX - (ls / 2), + compressCheckZ - (ls / 2))) { + LevelChunk* lc = Level::getChunk(compressCheckX - (ls / 2), + compressCheckZ - (ls / 2)); + lc->compressLighting(); + lc->compressBlocks(); + lc->compressData(); + break; + } + } #ifdef LIGHT_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int totalBLu = 0; - unsigned int totalBLl = 0; - unsigned int totalSLu = 0; - unsigned int totalSLl = 0; - unsigned int totalChunks = 0; + if ((updateTick % 60) == 0) { + unsigned int totalBLu = 0; + unsigned int totalBLl = 0; + unsigned int totalSLu = 0; + unsigned int totalSLl = 0; + unsigned int totalChunks = 0; - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - totalBLu += lc->getBlockLightPlanesUpper(); - totalBLl += lc->getBlockLightPlanesLower(); - totalSLu += lc->getSkyLightPlanesUpper(); - totalSLl += lc->getSkyLightPlanesLower(); - } - } - if( totalChunks ) - { - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + totalBLu += lc->getBlockLightPlanesUpper(); + totalBLl += lc->getBlockLightPlanesLower(); + totalSLu += lc->getSkyLightPlanesUpper(); + totalSLl += lc->getSkyLightPlanesLower(); + } + } + if (totalChunks) { + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - unsigned int totalBL = totalBLu + totalBLl; - unsigned int totalSL = totalSLu + totalSLl; - printf("%d: %d chunks, %d BL (%d + %d), %d SL (%d + %d ) (out of %d) - total %d %% (%dMB mem free)\n", - dimension->id, totalChunks, totalBL, totalBLu, totalBLl, totalSL, totalSLu, totalSLl, totalChunks * 256, ( 100 * (totalBL + totalSL) ) / ( totalChunks * 256 * 2),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + unsigned int totalBL = totalBLu + totalBLl; + unsigned int totalSL = totalSLu + totalSLl; + printf( + "%d: %d chunks, %d BL (%d + %d), %d SL (%d + %d ) (out of %d) " + "- total %d %% (%dMB mem free)\n", + dimension->id, totalChunks, totalBL, totalBLu, totalBLl, + totalSL, totalSLu, totalSLl, totalChunks * 256, + (100 * (totalBL + totalSL)) / (totalChunks * 256 * 2), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif #ifdef DATA_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int totalData = 0; - unsigned int totalChunks = 0; + if ((updateTick % 60) == 0) { + unsigned int totalData = 0; + unsigned int totalChunks = 0; - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - totalData += lc->getDataPlanes(); - } - } - if( totalChunks ) - { - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + totalData += lc->getDataPlanes(); + } + } + if (totalChunks) { + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - printf("%d: %d chunks, %d data (out of %d) - total %d %% (%dMB mem free)\n", - dimension->id, totalChunks, totalData, totalChunks * 128, ( 100 * totalData)/ ( totalChunks * 128),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + printf( + "%d: %d chunks, %d data (out of %d) - total %d %% (%dMB mem " + "free)\n", + dimension->id, totalChunks, totalData, totalChunks * 128, + (100 * totalData) / (totalChunks * 128), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif #ifdef BLOCK_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int total = 0; - unsigned int totalChunks = 0; - unsigned int total0 = 0, total1 = 0, total2 = 0, total4 = 0, total8 = 0; + if ((updateTick % 60) == 0) { + unsigned int total = 0; + unsigned int totalChunks = 0; + unsigned int total0 = 0, total1 = 0, total2 = 0, total4 = 0, total8 = 0; - printf("*****************************************************************************************************************************************\n"); - printf("TODO: Report upper chunk data as well\n"); - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - int i0, i1, i2, i4, i8; - int thisSize = lc->getBlocksAllocatedSize(&i0, &i1, &i2, &i4, &i8); - total0 += i0; - total1 += i1; - total2 += i2; - total4 += i4; - total8 += i8; - printf("%d ",thisSize); - thisSize = ( thisSize + 0xfff ) & 0xfffff000; // round to 4096k blocks for actual memory consumption - total += thisSize; - } - } - printf("\n*****************************************************************************************************************************************\n"); - if( totalChunks ) - { - printf("%d (0) %d (1) %d (2) %d (4) %d (8)\n",total0/totalChunks,total1/totalChunks,total2/totalChunks,total4/totalChunks,total8/totalChunks); - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + printf( + "******************************************************************" + "******************************************************************" + "*****\n"); + printf("TODO: Report upper chunk data as well\n"); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + int i0, i1, i2, i4, i8; + int thisSize = + lc->getBlocksAllocatedSize(&i0, &i1, &i2, &i4, &i8); + total0 += i0; + total1 += i1; + total2 += i2; + total4 += i4; + total8 += i8; + printf("%d ", thisSize); + thisSize = (thisSize + 0xfff) & + 0xfffff000; // round to 4096k blocks for actual + // memory consumption + total += thisSize; + } + } + printf( + "\n****************************************************************" + "******************************************************************" + "*******\n"); + if (totalChunks) { + printf("%d (0) %d (1) %d (2) %d (4) %d (8)\n", total0 / totalChunks, + total1 / totalChunks, total2 / totalChunks, + total4 / totalChunks, total8 / totalChunks); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - printf("%d: %d chunks, %d KB (out of %dKB) : %d %% (%dMB mem free)\n", - dimension->id, totalChunks, total/1024, totalChunks * 32, ( ( total / 1024 ) * 100 ) / ( totalChunks * 32),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + printf( + "%d: %d chunks, %d KB (out of %dKB) : %d %% (%dMB mem free)\n", + dimension->id, totalChunks, total / 1024, totalChunks * 32, + ((total / 1024) * 100) / (totalChunks * 32), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif // super.tick(); - } -void MultiPlayerLevel::clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - for (unsigned int i = 0; i < updatesToReset.size(); i++) - { +void MultiPlayerLevel::clearResetRegion(int x0, int y0, int z0, int x1, int y1, + int z1) { + for (unsigned int i = 0; i < updatesToReset.size(); i++) { ResetInfo& r = updatesToReset[i]; - if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && r.z <= z1) - { - updatesToReset.erase(updatesToReset.begin()+i); - i--; + if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && + r.z <= z1) { + updatesToReset.erase(updatesToReset.begin() + i); + i--; } } } -ChunkSource *MultiPlayerLevel::createChunkSource() -{ +ChunkSource* MultiPlayerLevel::createChunkSource() { chunkCache = new MultiPlayerChunkCache(this); return chunkCache; } -void MultiPlayerLevel::validateSpawn() -{ - // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing towards the original spawn point, once the player has entered the Nether. - // 4J Stu - We should never be setting a specific spawn position for a multiplayer, this should only be set by receiving a packet from the server - // (which happens when a player logs in) - //setSpawnPos(new Pos(8, 64, 8)); +void MultiPlayerLevel::validateSpawn() { + // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing + // towards the original spawn point, once the player has entered the Nether. + // 4J Stu - We should never be setting a specific spawn position for a + // multiplayer, this should only be set by receiving a packet from the + // server (which happens when a player logs in) + // setSpawnPos(new Pos(8, 64, 8)); } -void MultiPlayerLevel::tickTiles() -{ - chunksToPoll.clear(); // 4J - added or else we don't reset this set at all in a multiplayer level... think current java now resets in buildAndPrepareChunksToPoll rather than the calling functions +void MultiPlayerLevel::tickTiles() { + chunksToPoll.clear(); // 4J - added or else we don't reset this set at all + // in a multiplayer level... think current java now + // resets in buildAndPrepareChunksToPoll rather than + // the calling functions - PIXBeginNamedEvent(0,"Ticking tiles (multiplayer)"); - PIXBeginNamedEvent(0,"buildAndPrepareChunksToPoll"); - Level::tickTiles(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Ticking tiles (multiplayer)"); + PIXBeginNamedEvent(0, "buildAndPrepareChunksToPoll"); + Level::tickTiles(); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Ticking client side tiles"); + PIXBeginNamedEvent(0, "Ticking client side tiles"); #ifdef __PSVITA__ - // AP - see CustomSet.h for and explanation - for( int i = 0;i < chunksToPoll.end();i += 1 ) - { - ChunkPos cp = chunksToPoll.get(i); + // AP - see CustomSet.h for and explanation + for (int i = 0; i < chunksToPoll.end(); i += 1) { + ChunkPos cp = chunksToPoll.get(i); #else - AUTO_VAR(itEndCtp, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) - { - ChunkPos cp = *it; + AUTO_VAR(itEndCtp, chunksToPoll.end()); + for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) { + ChunkPos cp = *it; #endif - int xo = cp.x * 16; - int zo = cp.z * 16; + int xo = cp.x * 16; + int zo = cp.z * 16; - LevelChunk *lc = this->getChunk(cp.x, cp.z); + LevelChunk* lc = this->getChunk(cp.x, cp.z); - tickClientSideTiles(xo, zo, lc); - } - PIXEndNamedEvent(); - PIXEndNamedEvent(); -} - -void MultiPlayerLevel::setChunkVisible(int x, int z, bool visible) -{ - if (visible) - { - chunkCache->create(x, z); - } - else - { - chunkCache->drop(x, z); - } - if (!visible) - { - this->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, Level::maxBuildHeight, z * 16 + 15); + tickClientSideTiles(xo, zo, lc); } - + PIXEndNamedEvent(); + PIXEndNamedEvent(); } -bool MultiPlayerLevel::addEntity(std::shared_ptr e) -{ +void MultiPlayerLevel::setChunkVisible(int x, int z, bool visible) { + if (visible) { + chunkCache->create(x, z); + } else { + chunkCache->drop(x, z); + } + if (!visible) { + this->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, + Level::maxBuildHeight, z * 16 + 15); + } +} + +bool MultiPlayerLevel::addEntity(std::shared_ptr e) { bool ok = Level::addEntity(e); forced.insert(e); - if (!ok) - { + if (!ok) { reEntries.insert(e); } return ok; } -void MultiPlayerLevel::removeEntity(std::shared_ptr e) -{ - // 4J Stu - Add this remove from the reEntries collection to stop us continually removing and re-adding things, - // in particular the MultiPlayerLocalPlayer when they die - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) - { +void MultiPlayerLevel::removeEntity(std::shared_ptr e) { + // 4J Stu - Add this remove from the reEntries collection to stop us + // continually removing and re-adding things, in particular the + // MultiPlayerLocalPlayer when they die + AUTO_VAR(it, reEntries.find(e)); + if (it != reEntries.end()) { reEntries.erase(it); } @@ -430,486 +431,457 @@ void MultiPlayerLevel::removeEntity(std::shared_ptr e) forced.erase(e); } -void MultiPlayerLevel::entityAdded(std::shared_ptr e) -{ +void MultiPlayerLevel::entityAdded(std::shared_ptr e) { Level::entityAdded(e); - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) - { + AUTO_VAR(it, reEntries.find(e)); + if (it != reEntries.end()) { reEntries.erase(it); } } -void MultiPlayerLevel::entityRemoved(std::shared_ptr e) -{ +void MultiPlayerLevel::entityRemoved(std::shared_ptr e) { Level::entityRemoved(e); - AUTO_VAR(it, forced.find(e)); - if (it!=forced.end()) - { + AUTO_VAR(it, forced.find(e)); + if (it != forced.end()) { reEntries.insert(e); } } -void MultiPlayerLevel::putEntity(int id, std::shared_ptr e) -{ +void MultiPlayerLevel::putEntity(int id, std::shared_ptr e) { std::shared_ptr old = getEntity(id); - if (old != NULL) - { + if (old != NULL) { removeEntity(old); } forced.insert(e); e->entityId = id; - if (!addEntity(e)) - { + if (!addEntity(e)) { this->reEntries.insert(e); } entitiesById[id] = e; } -std::shared_ptr MultiPlayerLevel::getEntity(int id) -{ - AUTO_VAR(it, entitiesById.find(id)); - if( it == entitiesById.end() ) return nullptr; - return it->second; +std::shared_ptr MultiPlayerLevel::getEntity(int id) { + AUTO_VAR(it, entitiesById.find(id)); + if (it == entitiesById.end()) return nullptr; + return it->second; } -std::shared_ptr MultiPlayerLevel::removeEntity(int id) -{ - std::shared_ptr e; - AUTO_VAR(it, entitiesById.find(id)); - if( it != entitiesById.end() ) - { - e = it->second; - entitiesById.erase(it); - forced.erase(e); - removeEntity(e); - } - else - { - } +std::shared_ptr MultiPlayerLevel::removeEntity(int id) { + std::shared_ptr e; + AUTO_VAR(it, entitiesById.find(id)); + if (it != entitiesById.end()) { + e = it->second; + entitiesById.erase(it); + forced.erase(e); + removeEntity(e); + } else { + } return e; } // 4J Added to remove the entities from the forced list -// This gets called when a chunk is unloaded, but we only do half an unload to remove entities slightly differently -void MultiPlayerLevel::removeEntities(std::vector > *list) -{ - for(AUTO_VAR(it, list->begin()); it < list->end(); ++it) - { - std::shared_ptr e = *it; +// This gets called when a chunk is unloaded, but we only do half an unload to +// remove entities slightly differently +void MultiPlayerLevel::removeEntities( + std::vector >* list) { + for (AUTO_VAR(it, list->begin()); it < list->end(); ++it) { + std::shared_ptr e = *it; - AUTO_VAR(reIt, reEntries.find(e)); - if (reIt!=reEntries.end()) - { - reEntries.erase(reIt); - } + AUTO_VAR(reIt, reEntries.find(e)); + if (reIt != reEntries.end()) { + reEntries.erase(reIt); + } - forced.erase(e); - } - Level::removeEntities(list); + forced.erase(e); + } + Level::removeEntities(list); } -bool MultiPlayerLevel::setDataNoUpdate(int x, int y, int z, int data) -{ +bool MultiPlayerLevel::setDataNoUpdate(int x, int y, int z, int data) { int t = getTile(x, y, z); int d = getData(x, y, z); - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setDataNoUpdate(x, y, z, data)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setDataNoUpdate(x, y, z, data)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) -{ - // First check if this isn't going to do anything, because if it isn't then the next stage (of unsharing data) is really quite - // expensive so far better to early out here +bool MultiPlayerLevel::setTileAndDataNoUpdate(int x, int y, int z, int tile, + int data) { + // First check if this isn't going to do anything, because if it isn't then + // the next stage (of unsharing data) is really quite expensive so far + // better to early out here int t = getTile(x, y, z); int d = getData(x, y, z); - if( ( t == tile ) && ( d == data ) ) - { - // If we early-out, its important that we still do a checkLight here (which would otherwise have happened as part of Level::setTileAndDataNoUpdate) - // This is because since we are potentially sharing tile/data but not lighting data, it is possible that the server might tell a client - // of a lighting update that doesn't need actioned on the client just because the chunk's data was being shared with the server when it was set. However, - // the lighting data will potentially now be out of sync on the client. - checkLight(x,y,z); - return false; - } - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + if ((t == tile) && (d == data)) { + // If we early-out, its important that we still do a checkLight here + // (which would otherwise have happened as part of + // Level::setTileAndDataNoUpdate) This is because since we are + // potentially sharing tile/data but not lighting data, it is possible + // that the server might tell a client of a lighting update that doesn't + // need actioned on the client just because the chunk's data was being + // shared with the server when it was set. However, the lighting data + // will potentially now be out of sync on the client. + checkLight(x, y, z); + return false; + } + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setTileAndDataNoUpdate(x, y, z, tile, data)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setTileAndDataNoUpdate(x, y, z, tile, data)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::setTileNoUpdate(int x, int y, int z, int tile) -{ +bool MultiPlayerLevel::setTileNoUpdate(int x, int y, int z, int tile) { int t = getTile(x, y, z); int d = getData(x, y, z); - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setTileNoUpdate(x, y, z, tile)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setTileNoUpdate(x, y, z, tile)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::doSetTileAndData(int x, int y, int z, int tile, int data) -{ +bool MultiPlayerLevel::doSetTileAndData(int x, int y, int z, int tile, + int data) { clearResetRegion(x, y, z, x, y, z); - // 4J - Don't bother setting this to dirty if it isn't going to visually change - we get a lot of - // water changing from static to dynamic for instance. Note that this is only called from a client connection, - // and so the thing being notified of any update through tileUpdated is the renderer - int prevTile = getTile(x, y, z); - bool visuallyImportant = (!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || - ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ); - // If we're the host, need to tell the renderer for updates even if they don't change things as the host - // might have been sharing data and so set it already, but the renderer won't know to update - if( (Level::setTileAndData(x, y, z, tile, data) || g_NetworkManager.IsHost() ) ) - { - if( g_NetworkManager.IsHost() && visuallyImportant ) - { - // 4J Stu - This got removed from the tileUpdated function in TU14. Adding it back here as we need it - // to handle the cases where the chunk data is shared so the normal paths never call this - sendTileUpdated(x,y,z); + // 4J - Don't bother setting this to dirty if it isn't going to visually + // change - we get a lot of water changing from static to dynamic for + // instance. Note that this is only called from a client connection, and so + // the thing being notified of any update through tileUpdated is the + // renderer + int prevTile = getTile(x, y, z); + bool visuallyImportant = + (!(((prevTile == Tile::water_Id) && (tile == Tile::calmWater_Id)) || + ((prevTile == Tile::calmWater_Id) && (tile == Tile::water_Id)) || + ((prevTile == Tile::lava_Id) && (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && (tile == Tile::lava_Id)))); + // If we're the host, need to tell the renderer for updates even if they + // don't change things as the host might have been sharing data and so set + // it already, but the renderer won't know to update + if ((Level::setTileAndData(x, y, z, tile, data) || + g_NetworkManager.IsHost())) { + if (g_NetworkManager.IsHost() && visuallyImportant) { + // 4J Stu - This got removed from the tileUpdated function in TU14. + // Adding it back here as we need it to handle the cases where the + // chunk data is shared so the normal paths never call this + sendTileUpdated(x, y, z); - tileUpdated(x, y, z, tile); - } + tileUpdated(x, y, z, tile); + } return true; } - return false; + return false; } -void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) -{ - if( sendDisconnect ) - { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); - } - } - else - { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->close(); - } - } +void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) { + if (sendDisconnect) { + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->sendAndDisconnect(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + } + } else { + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->close(); + } + } } -void MultiPlayerLevel::tickWeather() -{ +void MultiPlayerLevel::tickWeather() { if (dimension->hasCeiling) return; - if (lightningTime > 0) - { + if (lightningTime > 0) { lightningTime--; } oRainLevel = rainLevel; - if (levelData->isRaining()) - { + if (levelData->isRaining()) { rainLevel += 0.01; - } - else - { + } else { rainLevel -= 0.01; } if (rainLevel < 0) rainLevel = 0; if (rainLevel > 1) rainLevel = 1; oThunderLevel = thunderLevel; - if (levelData->isThundering()) - { + if (levelData->isThundering()) { thunderLevel += 0.01; - } - else - { + } else { thunderLevel -= 0.01; } if (thunderLevel < 0) thunderLevel = 0; if (thunderLevel > 1) thunderLevel = 1; - } -void MultiPlayerLevel::animateTick(int xt, int yt, int zt) -{ - // Get 8x8x8 chunk (ie not like the renderer or game chunks... maybe we need another word here...) that the player is in - // We then want to add a 3x3 region of chunks into a set that we'll be ticking over. Set is stored as unsigned ints which encode - // this chunk position - int cx = xt >> 3; - int cy = yt >> 3; - int cz = zt >> 3; +void MultiPlayerLevel::animateTick(int xt, int yt, int zt) { + // Get 8x8x8 chunk (ie not like the renderer or game chunks... maybe we need + // another word here...) that the player is in We then want to add a 3x3 + // region of chunks into a set that we'll be ticking over. Set is stored as + // unsigned ints which encode this chunk position + int cx = xt >> 3; + int cy = yt >> 3; + int cz = zt >> 3; - for( int xx = -1; xx <= 1; xx++ ) - for( int yy = -1; yy <= 1; yy++ ) - for( int zz = -1; zz <= 1; zz++ ) - { - if( ( cy + yy ) < 0 ) continue; - if( ( cy + yy ) > 15 ) continue; - // Note - LEVEL_MAX_WIDTH is in game (16) tile chunks, and so our level goes from -LEVEL_MAX_WIDTH to LEVEL_MAX_WIDTH of our half-sized chunks - if( ( cx + xx ) >= LEVEL_MAX_WIDTH ) continue; - if( ( cx + xx ) < -LEVEL_MAX_WIDTH ) continue; - if( ( cz + zz ) >= LEVEL_MAX_WIDTH ) continue; - if( ( cz + zz ) < -LEVEL_MAX_WIDTH ) continue; - chunksToAnimate.insert( ( ( ( cx + xx ) & 0xff ) << 16 ) | ( ( ( cy + yy ) & 0xff ) << 8 ) | ( ( ( cz + zz ) & 0xff ) ) ); - } -} - -// 4J - the game used to tick 1000 tiles in a random region +/- 16 units round the player. We've got a 3x3 region of 8x8x8 chunks round each -// player. So the original game was ticking 1000 things in a 32x32x32 region ie had about a 1 in 32 chance of updating any one tile per tick. -// We're not dealing with quite such a big region round each player (24x24x24) but potentially we've got 4 players. Ultimately, we could end -// up ticking anywhere between 432 and 1728 tiles depending on how many players we've got, which seems like a good tradeoff from the original. -void MultiPlayerLevel::animateTickDoWork() -{ - const int ticksPerChunk = 16; // This ought to give us roughly the same 1000/32768 chance of a tile being animated as the original - - // Horrible hack to communicate with the level renderer, which is just attached as a listener to this level. This let's the particle - // rendering know to use this level (rather than try to work it out from the current player), and to not bother distance clipping particles - // which would again be based on the current player. - Minecraft::GetInstance()->animateTickLevel = this; - - MemSect(31); - Random *animateRandom = new Random(); - MemSect(0); - - for( int i = 0; i < ticksPerChunk; i++ ) - { - for( AUTO_VAR(it, chunksToAnimate.begin()); it != chunksToAnimate.end(); it++ ) - { - int packed = *it; - // 4jcraft changed the extraction logic to be safe - // constantly shifting a signed integer - int cx = (int8_t)(packed >> 16) * 8; - int cy = (int8_t)(packed >> 8) * 8; - int cz = (int8_t)packed * 8; - - int x = cx + random->nextInt(8); - int y = cy + random->nextInt(8); - int z = cz + random->nextInt(8); - int t = getTile(x, y, z); - if (random->nextInt(8) > y && t == 0 && dimension->hasBedrockFog()) // 4J - test for bedrock fog brought forward from 1.2.3 - { - addParticle(eParticleType_depthsuspend, x + random->nextFloat(), y + random->nextFloat(), z + random->nextFloat(), 0, 0, 0); + for (int xx = -1; xx <= 1; xx++) + for (int yy = -1; yy <= 1; yy++) + for (int zz = -1; zz <= 1; zz++) { + if ((cy + yy) < 0) continue; + if ((cy + yy) > 15) continue; + // Note - LEVEL_MAX_WIDTH is in game (16) tile chunks, and so + // our level goes from -LEVEL_MAX_WIDTH to LEVEL_MAX_WIDTH of + // our half-sized chunks + if ((cx + xx) >= LEVEL_MAX_WIDTH) continue; + if ((cx + xx) < -LEVEL_MAX_WIDTH) continue; + if ((cz + zz) >= LEVEL_MAX_WIDTH) continue; + if ((cz + zz) < -LEVEL_MAX_WIDTH) continue; + chunksToAnimate.insert((((cx + xx) & 0xff) << 16) | + (((cy + yy) & 0xff) << 8) | + (((cz + zz) & 0xff))); } - else if (t > 0) - { - Tile::tiles[t]->animateTick(this, x, y, z, animateRandom); - } - } - } - - Minecraft::GetInstance()->animateTickLevel = NULL; - delete animateRandom; - - chunksToAnimate.clear(); - } -void MultiPlayerLevel::playSound(std::shared_ptr entity, int iSound, float volume, float pitch) -{ - playLocalSound(entity->x, entity->y - entity->heightOffset, entity->z, iSound, volume, pitch); -} +// 4J - the game used to tick 1000 tiles in a random region +/- 16 units round +// the player. We've got a 3x3 region of 8x8x8 chunks round each player. So the +// original game was ticking 1000 things in a 32x32x32 region ie had about a 1 +// in 32 chance of updating any one tile per tick. We're not dealing with quite +// such a big region round each player (24x24x24) but potentially we've got 4 +// players. Ultimately, we could end up ticking anywhere between 432 and 1728 +// tiles depending on how many players we've got, which seems like a good +// tradeoff from the original. +void MultiPlayerLevel::animateTickDoWork() { + const int ticksPerChunk = + 16; // This ought to give us roughly the same 1000/32768 chance of a + // tile being animated as the original -void MultiPlayerLevel::playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) -{ - //float dd = 16; - if (volume > 1) fClipSoundDist *= volume; + // Horrible hack to communicate with the level renderer, which is just + // attached as a listener to this level. This let's the particle rendering + // know to use this level (rather than try to work it out from the current + // player), and to not bother distance clipping particles which would again + // be based on the current player. + Minecraft::GetInstance()->animateTickLevel = this; - // 4J - find min distance to any players rather than just the current one - float minDistSq = FLT_MAX; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - float distSq = minecraft->localplayers[i]->distanceToSqr(x, y, z ); - if( distSq < minDistSq ) - { - minDistSq = distSq; - } - } - } + MemSect(31); + Random* animateRandom = new Random(); + MemSect(0); - if (minDistSq < fClipSoundDist * fClipSoundDist) - { - minecraft->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, pitch); - } -} + for (int i = 0; i < ticksPerChunk; i++) { + for (AUTO_VAR(it, chunksToAnimate.begin()); it != chunksToAnimate.end(); + it++) { + int packed = *it; + // 4jcraft changed the extraction logic to be safe + // constantly shifting a signed integer + int cx = (int8_t)(packed >> 16) * 8; + int cy = (int8_t)(packed >> 8) * 8; + int cz = (int8_t)packed * 8; -void MultiPlayerLevel::removeAllPendingEntityRemovals() -{ - //entities.removeAll(entitiesToRemove); - - EnterCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { - bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) - { - if( (*it) == (*it2) ) - { - found = true; - break; - } - } - if( found ) - { - it = entities.erase(it); - } - else - { - it++; - } - } - LeaveCriticalSection(&m_entitiesCS); - - AUTO_VAR(endIt, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) - { - std::shared_ptr e = *it; - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - } - - // 4J Stu - Is there a reason do this in a separate loop? Thats what the Java does... - endIt = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) - { - entityRemoved(*it); - } - entitiesToRemove.clear(); - - //for (int i = 0; i < entities.size(); i++) - EnterCriticalSection(&m_entitiesCS); - std::vector >::iterator it = entities.begin(); - while( it != entities.end() ) - { - std::shared_ptr e = *it;//entities.at(i); - - if (e->riding != NULL) - { - if (e->riding->removed || e->riding->rider.lock() != e) - { - e->riding->rider = std::weak_ptr(); - e->riding = nullptr; - } - else - { - ++it; - continue; - } - } - - if (e->removed) - { - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - //entities.remove(i--); - - it = entities.erase( it ); - entityRemoved(e); - } - else - { - it++; - } - } - LeaveCriticalSection(&m_entitiesCS); -} - -void MultiPlayerLevel::removeClientConnection(ClientConnection *c, bool sendDisconnect) -{ - if( sendDisconnect ) - { - c->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); - } - - AUTO_VAR(it, find( connections.begin(), connections.end(), c )); - if( it != connections.end() ) - { - connections.erase( it ); - } -} - -void MultiPlayerLevel::tickAllConnections() -{ - PIXBeginNamedEvent(0,"Connection ticking"); - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->tick(); - } - PIXEndNamedEvent(); -} - -void MultiPlayerLevel::dataReceivedForChunk(int x, int z) -{ - chunkCache->dataReceived(x, z); -} - -// 4J added - removes all tile entities in the given region from both level & levelchunks -void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - EnterCriticalSection(&m_tileEntityListCS); - - for (unsigned int i = 0; i < tileEntityList.size();) - { - bool removed = false; - std::shared_ptr te = tileEntityList[i]; - if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) - { - LevelChunk *lc = getChunk(te->x >> 4, te->z >> 4); - if (lc != NULL) - { - // Only remove tile entities where this is no longer a tile entity - int tileId = lc->getTile(te->x & 15, te->y, te->z & 15 ); - if( Tile::tiles[tileId] == NULL || !Tile::tiles[tileId]->isEntityTile()) - { - tileEntityList[i] = tileEntityList.back(); - tileEntityList.pop_back(); - - // 4J Stu - Chests can create new tile entities when being removed, so disable this - m_bDisableAddNewTileEntities = true; - lc->removeTileEntity(te->x & 15, te->y, te->z & 15); - m_bDisableAddNewTileEntities = false; - removed = true; - } - } + int x = cx + random->nextInt(8); + int y = cy + random->nextInt(8); + int z = cz + random->nextInt(8); + int t = getTile(x, y, z); + if (random->nextInt(8) > y && t == 0 && + dimension->hasBedrockFog()) // 4J - test for bedrock fog + // brought forward from 1.2.3 + { + addParticle(eParticleType_depthsuspend, x + random->nextFloat(), + y + random->nextFloat(), z + random->nextFloat(), 0, + 0, 0); + } else if (t > 0) { + Tile::tiles[t]->animateTick(this, x, y, z, animateRandom); + } } - if( !removed ) i++; } - LeaveCriticalSection(&m_tileEntityListCS); + Minecraft::GetInstance()->animateTickLevel = NULL; + delete animateRandom; + + chunksToAnimate.clear(); } +void MultiPlayerLevel::playSound(std::shared_ptr entity, int iSound, + float volume, float pitch) { + playLocalSound(entity->x, entity->y - entity->heightOffset, entity->z, + iSound, volume, pitch); +} + +void MultiPlayerLevel::playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist) { + // float dd = 16; + if (volume > 1) fClipSoundDist *= volume; + + // 4J - find min distance to any players rather than just the current one + float minDistSq = FLT_MAX; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + float distSq = minecraft->localplayers[i]->distanceToSqr(x, y, z); + if (distSq < minDistSq) { + minDistSq = distSq; + } + } + } + + if (minDistSq < fClipSoundDist * fClipSoundDist) { + minecraft->soundEngine->play(iSound, (float)x, (float)y, (float)z, + volume, pitch); + } +} + +void MultiPlayerLevel::removeAllPendingEntityRemovals() { + // entities.removeAll(entitiesToRemove); + + EnterCriticalSection(&m_entitiesCS); + for (AUTO_VAR(it, entities.begin()); it != entities.end();) { + bool found = false; + for (AUTO_VAR(it2, entitiesToRemove.begin()); + it2 != entitiesToRemove.end(); it2++) { + if ((*it) == (*it2)) { + found = true; + break; + } + } + if (found) { + it = entities.erase(it); + } else { + it++; + } + } + LeaveCriticalSection(&m_entitiesCS); + + AUTO_VAR(endIt, entitiesToRemove.end()); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) { + std::shared_ptr e = *it; + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + } + + // 4J Stu - Is there a reason do this in a separate loop? Thats what the + // Java does... + endIt = entitiesToRemove.end(); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) { + entityRemoved(*it); + } + entitiesToRemove.clear(); + + // for (int i = 0; i < entities.size(); i++) + EnterCriticalSection(&m_entitiesCS); + std::vector >::iterator it = entities.begin(); + while (it != entities.end()) { + std::shared_ptr e = *it; // entities.at(i); + + if (e->riding != NULL) { + if (e->riding->removed || e->riding->rider.lock() != e) { + e->riding->rider = std::weak_ptr(); + e->riding = nullptr; + } else { + ++it; + continue; + } + } + + if (e->removed) { + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + // entities.remove(i--); + + it = entities.erase(it); + entityRemoved(e); + } else { + it++; + } + } + LeaveCriticalSection(&m_entitiesCS); +} + +void MultiPlayerLevel::removeClientConnection(ClientConnection* c, + bool sendDisconnect) { + if (sendDisconnect) { + c->sendAndDisconnect(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + } + + AUTO_VAR(it, find(connections.begin(), connections.end(), c)); + if (it != connections.end()) { + connections.erase(it); + } +} + +void MultiPlayerLevel::tickAllConnections() { + PIXBeginNamedEvent(0, "Connection ticking"); + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->tick(); + } + PIXEndNamedEvent(); +} + +void MultiPlayerLevel::dataReceivedForChunk(int x, int z) { + chunkCache->dataReceived(x, z); +} + +// 4J added - removes all tile entities in the given region from both level & +// levelchunks +void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, + int x1, int y1, + int z1) { + EnterCriticalSection(&m_tileEntityListCS); + + for (unsigned int i = 0; i < tileEntityList.size();) { + bool removed = false; + std::shared_ptr te = tileEntityList[i]; + if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && + te->y < y1 && te->z < z1) { + LevelChunk* lc = getChunk(te->x >> 4, te->z >> 4); + if (lc != NULL) { + // Only remove tile entities where this is no longer a tile + // entity + int tileId = lc->getTile(te->x & 15, te->y, te->z & 15); + if (Tile::tiles[tileId] == NULL || + !Tile::tiles[tileId]->isEntityTile()) { + tileEntityList[i] = tileEntityList.back(); + tileEntityList.pop_back(); + + // 4J Stu - Chests can create new tile entities when being + // removed, so disable this + m_bDisableAddNewTileEntities = true; + lc->removeTileEntity(te->x & 15, te->y, te->z & 15); + m_bDisableAddNewTileEntities = false; + removed = true; + } + } + } + if (!removed) i++; + } + + LeaveCriticalSection(&m_tileEntityListCS); +} diff --git a/Minecraft.Client/Level/MultiPlayerLevel.h b/Minecraft.Client/Level/MultiPlayerLevel.h index ac6ed0812..0a02089d6 100644 --- a/Minecraft.Client/Level/MultiPlayerLevel.h +++ b/Minecraft.Client/Level/MultiPlayerLevel.h @@ -8,95 +8,111 @@ class ClientConnection; class MultiPlayerChunkCache; - - -class MultiPlayerLevel : public Level -{ +class MultiPlayerLevel : public Level { private: - static const int TICKS_BEFORE_RESET = 20 * 4; + static const int TICKS_BEFORE_RESET = 20 * 4; - class ResetInfo - { - public: + class ResetInfo { + public: int x, y, z, ticks, tile, data; ResetInfo(int x, int y, int z, int tile, int data); }; - std::vector updatesToReset; // 4J - was linked list but vector seems more appropriate - bool m_bEnableResetChanges; // 4J Added + std::vector updatesToReset; // 4J - was linked list but vector + // seems more appropriate + bool m_bEnableResetChanges; // 4J Added public: - void unshareChunkAt(int x, int z); // 4J - added - void shareChunkAt(int x, int z); // 4J - added + void unshareChunkAt(int x, int z); // 4J - added + void shareChunkAt(int x, int z); // 4J - added - void enableResetChanges(bool enable) { m_bEnableResetChanges = enable; } // 4J Added + void enableResetChanges(bool enable) { + m_bEnableResetChanges = enable; + } // 4J Added private: - int unshareCheckX; // 4J - added - int unshareCheckZ; // 4J - added - int compressCheckX; // 4J - added - int compressCheckZ; // 4J - added - std::vector connections; // 4J Stu - Made this a vector as we can have more than one local connection - MultiPlayerChunkCache *chunkCache; - Minecraft *minecraft; + int unshareCheckX; // 4J - added + int unshareCheckZ; // 4J - added + int compressCheckX; // 4J - added + int compressCheckZ; // 4J - added + std::vector + connections; // 4J Stu - Made this a vector as we can have more than + // one local connection + MultiPlayerChunkCache* chunkCache; + Minecraft* minecraft; public: - MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty); - virtual ~MultiPlayerLevel(); - virtual void tick() ; + MultiPlayerLevel(ClientConnection* connection, LevelSettings* levelSettings, + int dimension, int difficulty); + virtual ~MultiPlayerLevel(); + virtual void tick(); + + void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1); - void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1); protected: - ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor + ChunkSource* + createChunkSource(); // 4J - was virtual, but was called from parent ctor public: - virtual void validateSpawn(); + virtual void validateSpawn(); + protected: - virtual void tickTiles(); + virtual void tickTiles(); + public: void setChunkVisible(int x, int z, bool visible); private: - std::unordered_map, IntKeyHash2, IntKeyEq> entitiesById; // 4J - was IntHashMap + std::unordered_map, IntKeyHash2, IntKeyEq> + entitiesById; // 4J - was IntHashMap std::unordered_set > forced; std::unordered_set > reEntries; public: - virtual bool addEntity(std::shared_ptr e); + virtual bool addEntity(std::shared_ptr e); virtual void removeEntity(std::shared_ptr e); + protected: - virtual void entityAdded(std::shared_ptr e); + virtual void entityAdded(std::shared_ptr e); virtual void entityRemoved(std::shared_ptr e); + public: - void putEntity(int id, std::shared_ptr e); + void putEntity(int id, std::shared_ptr e); std::shared_ptr getEntity(int id); std::shared_ptr removeEntity(int id); - virtual void removeEntities(std::vector > *list); // 4J Added override + virtual void removeEntities( + std::vector >* list); // 4J Added override virtual bool setDataNoUpdate(int x, int y, int z, int data); - virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data); + virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, + int data); virtual bool setTileNoUpdate(int x, int y, int z, int tile); bool doSetTileAndData(int x, int y, int z, int tile, int data); virtual void disconnect(bool sendDisconnect = true); - void animateTick(int xt, int yt, int zt); + void animateTick(int xt, int yt, int zt); + protected: - virtual void tickWeather(); - - static const int ANIMATE_TICK_MAX_PARTICLES = 500; + virtual void tickWeather(); + + static const int ANIMATE_TICK_MAX_PARTICLES = 500; public: - void animateTickDoWork(); // 4J added - std::unordered_set chunksToAnimate; // 4J added + void animateTickDoWork(); // 4J added + std::unordered_set chunksToAnimate; // 4J added public: - void removeAllPendingEntityRemovals(); + void removeAllPendingEntityRemovals(); - virtual void playSound(std::shared_ptr entity, int iSound, float volume, float pitch); + virtual void playSound(std::shared_ptr entity, int iSound, + float volume, float pitch); - virtual void playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist=16.0f); + virtual void playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist = 16.0f); - // 4J Stu - Added so we can have multiple local connections - void addClientConnection(ClientConnection *c) { connections.push_back( c ); } - void removeClientConnection(ClientConnection *c, bool sendDisconnect); + // 4J Stu - Added so we can have multiple local connections + void addClientConnection(ClientConnection* c) { connections.push_back(c); } + void removeClientConnection(ClientConnection* c, bool sendDisconnect); - void tickAllConnections(); + void tickAllConnections(); - void dataReceivedForChunk(int x, int z); // 4J added - void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); // 4J added + void dataReceivedForChunk(int x, int z); // 4J added + void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, + int y1, int z1); // 4J added }; diff --git a/Minecraft.Client/Level/ServerLevel.cpp b/Minecraft.Client/Level/ServerLevel.cpp index 9657a3511..422c30a9f 100644 --- a/Minecraft.Client/Level/ServerLevel.cpp +++ b/Minecraft.Client/Level/ServerLevel.cpp @@ -41,1427 +41,1401 @@ C4JThread* ServerLevel::m_updateThread = NULL; C4JThread::EventArray* ServerLevel::m_updateTrigger; CRITICAL_SECTION ServerLevel::m_updateCS[3]; -Level *ServerLevel::m_level[3]; -int ServerLevel::m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; -int ServerLevel::m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; -int ServerLevel::m_updateChunkCount[3]; -int ServerLevel::m_updateTileX[3][MAX_UPDATES]; -int ServerLevel::m_updateTileY[3][MAX_UPDATES]; -int ServerLevel::m_updateTileZ[3][MAX_UPDATES]; -int ServerLevel::m_updateTileCount[3]; -int ServerLevel::m_randValue[3]; +Level* ServerLevel::m_level[3]; +int ServerLevel::m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; +int ServerLevel::m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; +int ServerLevel::m_updateChunkCount[3]; +int ServerLevel::m_updateTileX[3][MAX_UPDATES]; +int ServerLevel::m_updateTileY[3][MAX_UPDATES]; +int ServerLevel::m_updateTileZ[3][MAX_UPDATES]; +int ServerLevel::m_updateTileCount[3]; +int ServerLevel::m_randValue[3]; -void ServerLevel::staticCtor() -{ - m_updateTrigger = new C4JThread::EventArray(3); - InitializeCriticalSection(&m_updateCS[0]); - InitializeCriticalSection(&m_updateCS[1]); - InitializeCriticalSection(&m_updateCS[2]); +void ServerLevel::staticCtor() { + m_updateTrigger = new C4JThread::EventArray(3); + InitializeCriticalSection(&m_updateCS[0]); + InitializeCriticalSection(&m_updateCS[1]); + InitializeCriticalSection(&m_updateCS[2]); - m_updateThread = new C4JThread(runUpdate, NULL, "Tile update"); - m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE); + m_updateThread = new C4JThread(runUpdate, NULL, "Tile update"); + m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE); #ifdef __ORBIS__ - m_updateThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + m_updateThread->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for + // Matching 2, and that priority of that + // seems to be always at default no + // matter what we set it to. Prioritise + // this below Matching 2. #endif - m_updateThread->Run(); + m_updateThread->Run(); - RANDOM_BONUS_ITEMS = WeighedTreasureArray(20); + RANDOM_BONUS_ITEMS = WeighedTreasureArray(20); - RANDOM_BONUS_ITEMS[0] = new WeighedTreasure(Item::stick_Id, 0, 1, 3, 10); + RANDOM_BONUS_ITEMS[0] = new WeighedTreasure(Item::stick_Id, 0, 1, 3, 10); RANDOM_BONUS_ITEMS[1] = new WeighedTreasure(Tile::wood_Id, 0, 1, 3, 10); - RANDOM_BONUS_ITEMS[2] = new WeighedTreasure(Tile::treeTrunk_Id, 0, 1, 3, 10); - RANDOM_BONUS_ITEMS[3] = new WeighedTreasure(Item::hatchet_stone_Id, 0, 1, 1, 3); - RANDOM_BONUS_ITEMS[4] = new WeighedTreasure(Item::hatchet_wood_Id, 0, 1, 1, 5); - RANDOM_BONUS_ITEMS[5] = new WeighedTreasure(Item::pickAxe_stone_Id, 0, 1, 1, 3); - RANDOM_BONUS_ITEMS[6] = new WeighedTreasure(Item::pickAxe_wood_Id, 0, 1, 1, 5); + RANDOM_BONUS_ITEMS[2] = + new WeighedTreasure(Tile::treeTrunk_Id, 0, 1, 3, 10); + RANDOM_BONUS_ITEMS[3] = + new WeighedTreasure(Item::hatchet_stone_Id, 0, 1, 1, 3); + RANDOM_BONUS_ITEMS[4] = + new WeighedTreasure(Item::hatchet_wood_Id, 0, 1, 1, 5); + RANDOM_BONUS_ITEMS[5] = + new WeighedTreasure(Item::pickAxe_stone_Id, 0, 1, 1, 3); + RANDOM_BONUS_ITEMS[6] = + new WeighedTreasure(Item::pickAxe_wood_Id, 0, 1, 1, 5); RANDOM_BONUS_ITEMS[7] = new WeighedTreasure(Item::apple_Id, 0, 2, 3, 5); RANDOM_BONUS_ITEMS[8] = new WeighedTreasure(Item::bread_Id, 0, 2, 3, 3); - // 4J-PB - new items - RANDOM_BONUS_ITEMS[9] = new WeighedTreasure(Tile::sapling_Id, 0, 4, 4, 2); - RANDOM_BONUS_ITEMS[10] = new WeighedTreasure(Tile::sapling_Id, 1, 4, 4, 2); - RANDOM_BONUS_ITEMS[11] = new WeighedTreasure(Tile::sapling_Id, 2, 4, 4, 2); - RANDOM_BONUS_ITEMS[12] = new WeighedTreasure(Tile::sapling_Id, 3, 4, 4, 4); - RANDOM_BONUS_ITEMS[13] = new WeighedTreasure(Item::seeds_melon_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[14] = new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[15] = new WeighedTreasure(Tile::cactus_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[16] = new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BROWN, 1, 2, 2); - RANDOM_BONUS_ITEMS[17] = new WeighedTreasure(Item::potato_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[18] = new WeighedTreasure(Item::carrots_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[19] = new WeighedTreasure(Tile::mushroom1_Id, 0, 1, 2, 2); - + // 4J-PB - new items + RANDOM_BONUS_ITEMS[9] = new WeighedTreasure(Tile::sapling_Id, 0, 4, 4, 2); + RANDOM_BONUS_ITEMS[10] = new WeighedTreasure(Tile::sapling_Id, 1, 4, 4, 2); + RANDOM_BONUS_ITEMS[11] = new WeighedTreasure(Tile::sapling_Id, 2, 4, 4, 2); + RANDOM_BONUS_ITEMS[12] = new WeighedTreasure(Tile::sapling_Id, 3, 4, 4, 4); + RANDOM_BONUS_ITEMS[13] = + new WeighedTreasure(Item::seeds_melon_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[14] = + new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[15] = new WeighedTreasure(Tile::cactus_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[16] = + new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BROWN, 1, 2, 2); + RANDOM_BONUS_ITEMS[17] = new WeighedTreasure(Item::potato_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[18] = new WeighedTreasure(Item::carrots_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[19] = + new WeighedTreasure(Tile::mushroom1_Id, 0, 1, 2, 2); }; -ServerLevel::ServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings) : Level(levelStorage, levelName, levelSettings, Dimension::getNew(dimension), false) -{ - InitializeCriticalSection(&m_limiterCS); - InitializeCriticalSection(&m_tickNextTickCS); - InitializeCriticalSection(&m_csQueueSendTileUpdates); - m_fallingTileCount = 0; - m_primedTntCount = 0; +ServerLevel::ServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings) + : Level(levelStorage, levelName, levelSettings, + Dimension::getNew(dimension), false) { + InitializeCriticalSection(&m_limiterCS); + InitializeCriticalSection(&m_tickNextTickCS); + InitializeCriticalSection(&m_csQueueSendTileUpdates); + m_fallingTileCount = 0; + m_primedTntCount = 0; - // 4J - this this used to be called in parent ctor via a virtual fn - chunkSource = createChunkSource(); - // 4J - optimisation - keep direct reference of underlying cache here - chunkSourceCache = chunkSource->getCache(); - chunkSourceXZSize = chunkSource->m_XZSize; + // 4J - this this used to be called in parent ctor via a virtual fn + chunkSource = createChunkSource(); + // 4J - optimisation - keep direct reference of underlying cache here + chunkSourceCache = chunkSource->getCache(); + chunkSourceXZSize = chunkSource->m_XZSize; - // 4J - The listener used to be added in MinecraftServer::loadLevel but we need it to be set up before we do the next couple of things, or else chunks get loaded before we have the entity tracker set up to listen to them - this->server = server; - server->setLevel(dimension, this); // The listener needs the server to have the level set up... this will be set up anyway on return of this ctor but setting up early here - addListener(new ServerLevelListener(server, this)); + // 4J - The listener used to be added in MinecraftServer::loadLevel but we + // need it to be set up before we do the next couple of things, or else + // chunks get loaded before we have the entity tracker set up to listen to + // them + this->server = server; + server->setLevel(dimension, + this); // The listener needs the server to have the level + // set up... this will be set up anyway on return + // of this ctor but setting up early here + addListener(new ServerLevelListener(server, this)); - this->tracker = new EntityTracker(this); - this->chunkMap = new PlayerChunkMap(this, dimension, server->getPlayers()->getViewDistance()); + this->tracker = new EntityTracker(this); + this->chunkMap = new PlayerChunkMap( + this, dimension, server->getPlayers()->getViewDistance()); - // This also used to be called in parent ctor, but can't be called until chunkSource is created. Call now if required. - if (!levelData->isInitialized()) - { - initializeLevel(levelSettings); - levelData->setInitialized(true); - } - else if ( (dimension==0) && levelData->getSpawnBonusChest() ) // 4J-JEV, still would like bonus chests to respawn. - { - // 4J - added isFindingSpawn as we want any chunks we are looking in here for suitable locations for the bonus chest to actually create those chunks rather than just get emptychunks if they aren't loaded - isFindingSpawn = true; - generateBonusItemsNearSpawn(); - isFindingSpawn = false; - } + // This also used to be called in parent ctor, but can't be called until + // chunkSource is created. Call now if required. + if (!levelData->isInitialized()) { + initializeLevel(levelSettings); + levelData->setInitialized(true); + } else if ((dimension == 0) && + levelData->getSpawnBonusChest()) // 4J-JEV, still would like + // bonus chests to respawn. + { + // 4J - added isFindingSpawn as we want any chunks we are looking in + // here for suitable locations for the bonus chest to actually create + // those chunks rather than just get emptychunks if they aren't loaded + isFindingSpawn = true; + generateBonusItemsNearSpawn(); + isFindingSpawn = false; + } - // 4J - added initialisers - // 4J Stu - Allowing spawn edit for our game, and consider a better solution for the possible griefing - canEditSpawn = true; //false; - noSave = false; - allPlayersSleeping = false; - m_bAtLeastOnePlayerSleeping = false; - emptyTime = 0; - activeTileEventsList = 0; + // 4J - added initialisers + // 4J Stu - Allowing spawn edit for our game, and consider a better solution + // for the possible griefing + canEditSpawn = true; // false; + noSave = false; + allPlayersSleeping = false; + m_bAtLeastOnePlayerSleeping = false; + emptyTime = 0; + activeTileEventsList = 0; #ifdef _LARGE_WORLDS - saveInterval = 3; + saveInterval = 3; #else - saveInterval = 20 * 2; + saveInterval = 20 * 2; #endif } -ServerLevel::~ServerLevel() -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) - { - Pos *p = *it; - delete p; - } - m_queuedSendTileUpdates.clear(); +ServerLevel::~ServerLevel() { + EnterCriticalSection(&m_csQueueSendTileUpdates); + for (AUTO_VAR(it, m_queuedSendTileUpdates.begin()); + it != m_queuedSendTileUpdates.end(); ++it) { + Pos* p = *it; + delete p; + } + m_queuedSendTileUpdates.clear(); - delete this->tracker; // MGH - added, we were losing about 500K going in and out the menus - delete this->chunkMap; + delete this->tracker; // MGH - added, we were losing about 500K going in + // and out the menus + delete this->chunkMap; - LeaveCriticalSection(&m_csQueueSendTileUpdates); - DeleteCriticalSection(&m_csQueueSendTileUpdates); - DeleteCriticalSection(&m_limiterCS); - DeleteCriticalSection(&m_tickNextTickCS); + LeaveCriticalSection(&m_csQueueSendTileUpdates); + DeleteCriticalSection(&m_csQueueSendTileUpdates); + DeleteCriticalSection(&m_limiterCS); + DeleteCriticalSection(&m_tickNextTickCS); - // Make sure that the update thread isn't actually doing any updating - EnterCriticalSection(&m_updateCS[0]); - LeaveCriticalSection(&m_updateCS[0]); - EnterCriticalSection(&m_updateCS[1]); - LeaveCriticalSection(&m_updateCS[1]); - EnterCriticalSection(&m_updateCS[2]); - LeaveCriticalSection(&m_updateCS[2]); - m_updateTrigger->ClearAll(); + // Make sure that the update thread isn't actually doing any updating + EnterCriticalSection(&m_updateCS[0]); + LeaveCriticalSection(&m_updateCS[0]); + EnterCriticalSection(&m_updateCS[1]); + LeaveCriticalSection(&m_updateCS[1]); + EnterCriticalSection(&m_updateCS[2]); + LeaveCriticalSection(&m_updateCS[2]); + m_updateTrigger->ClearAll(); } - -void ServerLevel::tick() -{ - Level::tick(); - if (getLevelData()->isHardcore() && difficulty < 3) - { +void ServerLevel::tick() { + Level::tick(); + if (getLevelData()->isHardcore() && difficulty < 3) { difficulty = 3; } - dimension->biomeSource->update(); + dimension->biomeSource->update(); - if (allPlayersAreSleeping()) - { - bool somebodyWokeUp = false; - if (spawnEnemies && difficulty >= Difficulty::EASY) - { - } + if (allPlayersAreSleeping()) { + bool somebodyWokeUp = false; + if (spawnEnemies && difficulty >= Difficulty::EASY) { + } - if (!somebodyWokeUp) - { - // skip time until new day - __int64 newTime = levelData->getTime() + TICKS_PER_DAY; + if (!somebodyWokeUp) { + // skip time until new day + __int64 newTime = levelData->getTime() + TICKS_PER_DAY; - // 4J : WESTY : Changed so that time update goes through stats tracking update code. - //levelData->setTime(newTime - (newTime % TICKS_PER_DAY)); - setTime(newTime - (newTime % TICKS_PER_DAY)); + // 4J : WESTY : Changed so that time update goes through stats + // tracking update code. + // levelData->setTime(newTime - (newTime % TICKS_PER_DAY)); + setTime(newTime - (newTime % TICKS_PER_DAY)); - awakenAllPlayers(); - } - } + awakenAllPlayers(); + } + } - PIXBeginNamedEvent(0,"Mob spawner tick"); - // for Minecraft 1.8, spawn friendlies really rarely - 4J - altered from once every 400 ticks to 40 ticks as we depend on this a more than the original since we don't have chunk post-process spawning - MobSpawner::tick(this, spawnEnemies, spawnFriendlies && (levelData->getTime() % 40) == 0); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Chunk source tick"); - chunkSource->tick(); - PIXEndNamedEvent(); - int newDark = this->getOldSkyDarken(1); - if (newDark != skyDarken) - { - skyDarken = newDark; - if (!SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->skyColorChanged(); - } - } - } - - PIXBeginNamedEvent(0,"runTileEvents"); - // run after entity updates - runTileEvents(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Mob spawner tick"); + // for Minecraft 1.8, spawn friendlies really rarely - 4J - altered + // from once every 400 ticks to 40 ticks as we depend on this a more than + // the original since we don't have chunk post-process spawning + MobSpawner::tick(this, spawnEnemies, + spawnFriendlies && (levelData->getTime() % 40) == 0); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Chunk source tick"); + chunkSource->tick(); + PIXEndNamedEvent(); + int newDark = this->getOldSkyDarken(1); + if (newDark != skyDarken) { + skyDarken = newDark; + if (!SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward + // from 1.8.2 + { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->skyColorChanged(); + } + } + } - //4J - temporarily disabling saves as they are causing gameplay to generally stutter quite a lot + PIXBeginNamedEvent(0, "runTileEvents"); + // run after entity updates + runTileEvents(); + PIXEndNamedEvent(); - __int64 time = levelData->getTime() + 1; -// 4J Stu - Putting this back in, but I have reduced the number of chunks that save when not forced + // 4J - temporarily disabling saves as they are causing gameplay to + // generally stutter quite a lot + + __int64 time = levelData->getTime() + 1; +// 4J Stu - Putting this back in, but I have reduced the number of chunks that +// save when not forced #ifdef _LARGE_WORLDS - if (time % (saveInterval) == (dimension->id + 1)) + if (time % (saveInterval) == (dimension->id + 1)) #else - if (time % (saveInterval) == (dimension->id * dimension->id * (saveInterval/2))) + if (time % (saveInterval) == + (dimension->id * dimension->id * (saveInterval / 2))) #endif - { - //app.DebugPrintf("Incremental save\n"); - PIXBeginNamedEvent(0,"Incremental save"); - save(false, NULL); - PIXEndNamedEvent(); - } + { + // app.DebugPrintf("Incremental save\n"); + PIXBeginNamedEvent(0, "Incremental save"); + save(false, NULL); + PIXEndNamedEvent(); + } - // 4J : WESTY : Changed so that time update goes through stats tracking update code. - //levelData->setTime(time); - setTime(time); + // 4J : WESTY : Changed so that time update goes through stats tracking + // update code. + // levelData->setTime(time); + setTime(time); - PIXBeginNamedEvent(0,"Tick pending ticks"); - // if (tickCount % 5 == 0) { - tickPendingTicks(false); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick pending ticks"); + // if (tickCount % 5 == 0) { + tickPendingTicks(false); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Tick tiles"); - MemSect(18); - tickTiles(); - MemSect(0); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick tiles"); + MemSect(18); + tickTiles(); + MemSect(0); + PIXEndNamedEvent(); - chunkMap->tick(); + chunkMap->tick(); - PIXBeginNamedEvent(0,"Tick villages"); - //MemSect(18); - villages->tick(); - villageSiege->tick(); - //MemSect(0); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick villages"); + // MemSect(18); + villages->tick(); + villageSiege->tick(); + // MemSect(0); + PIXEndNamedEvent(); - // repeat after tile ticks - runTileEvents(); + // repeat after tile ticks + runTileEvents(); - // 4J Added - runQueuedSendTileUpdates(); + // 4J Added + runQueuedSendTileUpdates(); } -Biome::MobSpawnerData *ServerLevel::getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z) -{ - std::vector *mobList = getChunkSource()->getMobsAt(mobCategory, x, y, z); - if (mobList == NULL || mobList->empty()) return NULL; +Biome::MobSpawnerData* ServerLevel::getRandomMobSpawnAt( + MobCategory* mobCategory, int x, int y, int z) { + std::vector* mobList = + getChunkSource()->getMobsAt(mobCategory, x, y, z); + if (mobList == NULL || mobList->empty()) return NULL; - return (Biome::MobSpawnerData *) WeighedRandom::getRandomItem(random, (std::vector *)mobList); + return (Biome::MobSpawnerData*)WeighedRandom::getRandomItem( + random, (std::vector*)mobList); } -void ServerLevel::updateSleepingPlayerList() -{ - allPlayersSleeping = !players.empty(); - m_bAtLeastOnePlayerSleeping = false; +void ServerLevel::updateSleepingPlayerList() { + allPlayersSleeping = !players.empty(); + m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++) - { - if (!(*it)->isSleeping()) - { - allPlayersSleeping = false; - //break; - } - else - { - m_bAtLeastOnePlayerSleeping = true; - } - if(m_bAtLeastOnePlayerSleeping && !allPlayersSleeping) break; - } + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = players.begin(); + it != itEnd; it++) { + if (!(*it)->isSleeping()) { + allPlayersSleeping = false; + // break; + } else { + m_bAtLeastOnePlayerSleeping = true; + } + if (m_bAtLeastOnePlayerSleeping && !allPlayersSleeping) break; + } } -void ServerLevel::awakenAllPlayers() -{ - allPlayersSleeping = false; - m_bAtLeastOnePlayerSleeping = false; +void ServerLevel::awakenAllPlayers() { + allPlayersSleeping = false; + m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++) - { - if ((*it)->isSleeping()) - { - (*it)->stopSleepInBed(false, false, true); - } - } + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = players.begin(); + it != itEnd; it++) { + if ((*it)->isSleeping()) { + (*it)->stopSleepInBed(false, false, true); + } + } - stopWeather(); + stopWeather(); } -void ServerLevel::stopWeather() -{ - levelData->setRainTime(0); - levelData->setRaining(false); - levelData->setThunderTime(0); - levelData->setThundering(false); +void ServerLevel::stopWeather() { + levelData->setRainTime(0); + levelData->setRaining(false); + levelData->setThunderTime(0); + levelData->setThundering(false); } -bool ServerLevel::allPlayersAreSleeping() -{ - if (allPlayersSleeping && !isClientSide) - { - // all players are sleeping, but have they slept long enough? - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++ ) - { - // System.out.println(player->entityId + ": " + player->getSleepTimer()); - if (! (*it)->isSleepingLongEnough()) - { - return false; - } - } - // yep - return true; - } - return false; +bool ServerLevel::allPlayersAreSleeping() { + if (allPlayersSleeping && !isClientSide) { + // all players are sleeping, but have they slept long enough? + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = + players.begin(); + it != itEnd; it++) { + // System.out.println(player->entityId + ": " + + // player->getSleepTimer()); + if (!(*it)->isSleepingLongEnough()) { + return false; + } + } + // yep + return true; + } + return false; } -void ServerLevel::validateSpawn() -{ - if (levelData->getYSpawn() <= 0) - { - levelData->setYSpawn(genDepth / 2); - } - int xSpawn = levelData->getXSpawn(); - int zSpawn = levelData->getZSpawn(); - int tries = 0; - while (getTopTile(xSpawn, zSpawn) == 0) - { - xSpawn += random->nextInt(8) - random->nextInt(8); - zSpawn += random->nextInt(8) - random->nextInt(8); - if (++tries == 10000) break; - } - levelData->setXSpawn(xSpawn); - levelData->setZSpawn(zSpawn); +void ServerLevel::validateSpawn() { + if (levelData->getYSpawn() <= 0) { + levelData->setYSpawn(genDepth / 2); + } + int xSpawn = levelData->getXSpawn(); + int zSpawn = levelData->getZSpawn(); + int tries = 0; + while (getTopTile(xSpawn, zSpawn) == 0) { + xSpawn += random->nextInt(8) - random->nextInt(8); + zSpawn += random->nextInt(8) - random->nextInt(8); + if (++tries == 10000) break; + } + levelData->setXSpawn(xSpawn); + levelData->setZSpawn(zSpawn); } -// 4J - Changes made here to move a section of code (which randomly determines which tiles in the current chunks to tick, and is very cache unfriendly by nature) -// This code now has a thread of its own so it can wait all it wants on the cache without holding the main game thread up. This slightly changes how things are -// processed, as we now tick the tiles that were determined in the previous tick. Have also limited the amount of tiles to be ticked to 256 (it never seemed to creep -// up much beyond this in normal play anyway, and we need some finite limit). -void ServerLevel::tickTiles() -{ - // Index into the arrays used by the update thread - int iLev = 0; - if( dimension->id == -1 ) - { - iLev = 1; - } - else if( dimension->id == 1 ) - { - iLev = 2; - } - chunksToPoll.clear(); +// 4J - Changes made here to move a section of code (which randomly determines +// which tiles in the current chunks to tick, and is very cache unfriendly by +// nature) This code now has a thread of its own so it can wait all it wants on +// the cache without holding the main game thread up. This slightly changes how +// things are processed, as we now tick the tiles that were determined in the +// previous tick. Have also limited the amount of tiles to be ticked to 256 (it +// never seemed to creep up much beyond this in normal play anyway, and we need +// some finite limit). +void ServerLevel::tickTiles() { + // Index into the arrays used by the update thread + int iLev = 0; + if (dimension->id == -1) { + iLev = 1; + } else if (dimension->id == 1) { + iLev = 2; + } + chunksToPoll.clear(); - unsigned int tickCount = 0; + unsigned int tickCount = 0; - EnterCriticalSection(&m_updateCS[iLev]); - // This section processes the tiles that need to be ticked, which we worked out in the previous tick (or haven't yet, if this is the first frame) - /*int grassTicks = 0; - int lavaTicks = 0; - int otherTicks = 0;*/ - for( int i = 0; i < m_updateTileCount[iLev]; i++ ) - { - int x = m_updateTileX[iLev][i]; - int y = m_updateTileY[iLev][i]; - int z = m_updateTileZ[iLev][i]; - if( hasChunkAt(x,y,z) ) - { - int id = getTile(x,y,z); - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking()) - { - /*if(id == 2) ++grassTicks; - else if(id == 11) ++lavaTicks; - else ++otherTicks;*/ - Tile::tiles[id]->tick(this, x, y, z, random); - } - } - } - //printf("Total ticks - Grass: %d, Lava: %d, Other: %d, Total: %d\n", grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks + otherTicks); - m_updateTileCount[iLev] = 0; - m_updateChunkCount[iLev] = 0; - LeaveCriticalSection(&m_updateCS[iLev]); + EnterCriticalSection(&m_updateCS[iLev]); + // This section processes the tiles that need to be ticked, which we worked + // out in the previous tick (or haven't yet, if this is the first frame) + /*int grassTicks = 0; + int lavaTicks = 0; + int otherTicks = 0;*/ + for (int i = 0; i < m_updateTileCount[iLev]; i++) { + int x = m_updateTileX[iLev][i]; + int y = m_updateTileY[iLev][i]; + int z = m_updateTileZ[iLev][i]; + if (hasChunkAt(x, y, z)) { + int id = getTile(x, y, z); + if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking()) { + /*if(id == 2) ++grassTicks; + else if(id == 11) ++lavaTicks; + else ++otherTicks;*/ + Tile::tiles[id]->tick(this, x, y, z, random); + } + } + } + // printf("Total ticks - Grass: %d, Lava: %d, Other: %d, Total: %d\n", + // grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks + otherTicks); + m_updateTileCount[iLev] = 0; + m_updateChunkCount[iLev] = 0; + LeaveCriticalSection(&m_updateCS[iLev]); - Level::tickTiles(); + Level::tickTiles(); - // AP moved this outside of the loop - int prob = 100000; - if(app.GetGameSettingsDebugMask()&(1L<hasChunk(cp.x, cp.z) ) continue; + // 4J added - don't let this actually load/create any chunks, we'll let + // the normal updateDirtyChunks etc. processes do that, so it can happen + // on another thread + if (!this->hasChunk(cp.x, cp.z)) continue; - // 4J Stu - When adding a 5th player to the game, the number of chunksToPoll is greater than the size of - // the m_updateChunkX & m_updateChunkZ arrays (19*19*4 at time of writing). It doesn't seem like there should - // ever be that many chunks needing polled, so this needs looked at in more detail. For now I have enlarged - // the size of the array to 19*19*8 but this seems way to big for our needs. + // 4J Stu - When adding a 5th player to the game, the number of + // chunksToPoll is greater than the size of the m_updateChunkX & + // m_updateChunkZ arrays (19*19*4 at time of writing). It doesn't seem + // like there should ever be that many chunks needing polled, so this + // needs looked at in more detail. For now I have enlarged the size of + // the array to 19*19*8 but this seems way to big for our needs. - // The cause of this is largely because the chunksToPoll vector does not enforce unique elements - // The java version used a HashSet which would, although if our world size gets a lot larger - // then we may have no overlaps of players surrounding chunks - //assert(false); + // The cause of this is largely because the chunksToPoll vector does not + // enforce unique elements The java version used a HashSet which would, + // although if our world size gets a lot larger then we may have no + // overlaps of players surrounding chunks + // assert(false); - // If you hit this assert, then a memory overwrite will occur when you continue - assert(m_updateChunkCount[iLev] < LEVEL_CHUNKS_TO_UPDATE_MAX); + // If you hit this assert, then a memory overwrite will occur when you + // continue + assert(m_updateChunkCount[iLev] < LEVEL_CHUNKS_TO_UPDATE_MAX); - m_updateChunkX[iLev][m_updateChunkCount[iLev]] = cp.x; - m_updateChunkZ[iLev][m_updateChunkCount[iLev]++] = cp.z; + m_updateChunkX[iLev][m_updateChunkCount[iLev]] = cp.x; + m_updateChunkZ[iLev][m_updateChunkCount[iLev]++] = cp.z; - LevelChunk *lc = this->getChunk(cp.x, cp.z); - tickClientSideTiles(xo, zo, lc); + LevelChunk* lc = this->getChunk(cp.x, cp.z); + tickClientSideTiles(xo, zo, lc); - if (random->nextInt(prob) == 0 && isRaining() && isThundering()) - { - randValue = randValue * 3 + addend; - int val = (randValue >> 2); - int x = xo + (val & 15); - int z = zo + ((val >> 8) & 15); - int y = getTopRainBlock(x, z); + if (random->nextInt(prob) == 0 && isRaining() && isThundering()) { + randValue = randValue * 3 + addend; + int val = (randValue >> 2); + int x = xo + (val & 15); + int z = zo + ((val >> 8) & 15); + int y = getTopRainBlock(x, z); - if (isRainingAt(x, y, z)) - { - addGlobalEntity( std::shared_ptr( new LightningBolt(this, x, y, z) ) ); - lightningTime = 2; - } - } + if (isRainingAt(x, y, z)) { + addGlobalEntity(std::shared_ptr( + new LightningBolt(this, x, y, z))); + lightningTime = 2; + } + } - // 4J - changes here brought forrward from 1.2.3 - if (random->nextInt(16) == 0) - { - //4jcraft added cast to unsigned + // 4J - changes here brought forrward from 1.2.3 + if (random->nextInt(16) == 0) { + // 4jcraft added cast to unsigned randValue = (unsigned)randValue * 3 + (unsigned)addend; int val = (randValue >> 2); int x = (val & 15); int z = ((val >> 8) & 15); int yy = this->getTopRainBlock(x + xo, z + zo); - if (shouldFreeze(x + xo, yy - 1, z + zo)) - { + if (shouldFreeze(x + xo, yy - 1, z + zo)) { setTile(x + xo, yy - 1, z + zo, Tile::ice_Id); } - if (isRaining() && shouldSnow(x + xo, yy, z + zo)) - { + if (isRaining() && shouldSnow(x + xo, yy, z + zo)) { setTile(x + xo, yy, z + zo, Tile::topSnow_Id); - } - if (isRaining()) - { - Biome *b = getBiome(x + xo, z + zo); - if (b->hasRain()) - { - int tile = getTile(x + xo, yy - 1, z + zo); - if (tile != 0) - { - Tile::tiles[tile]->handleRain(this, x + xo, yy - 1, z + zo); - } - } - } - } + } + if (isRaining()) { + Biome* b = getBiome(x + xo, z + zo); + if (b->hasRain()) { + int tile = getTile(x + xo, yy - 1, z + zo); + if (tile != 0) { + Tile::tiles[tile]->handleRain(this, x + xo, yy - 1, + z + zo); + } + } + } + } - // 4J - lighting change brought forward from 1.8.2 - checkLight(xo + random->nextInt(16), random->nextInt(128), zo + random->nextInt(16)); - } + // 4J - lighting change brought forward from 1.8.2 + checkLight(xo + random->nextInt(16), random->nextInt(128), + zo + random->nextInt(16)); + } - m_level[iLev] = this; - m_randValue[iLev] = randValue; - // We've set up everything that the udpate thread needs, so kick it off - m_updateTrigger->Set(iLev); + m_level[iLev] = this; + m_randValue[iLev] = randValue; + // We've set up everything that the udpate thread needs, so kick it off + m_updateTrigger->Set(iLev); } -void ServerLevel::addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) -{ - MemSect(27); - TickNextTickData td = TickNextTickData(x, y, z, tileId); - int r = 8; - if (getInstaTick()) - { - if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, td.z + r)) - { - int id = getTile(td.x, td.y, td.z); - if (id == td.tileId && id > 0) - { - Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); - } - } - MemSect(0); - return; - } +void ServerLevel::addToTickNextTick(int x, int y, int z, int tileId, + int tickDelay) { + MemSect(27); + TickNextTickData td = TickNextTickData(x, y, z, tileId); + int r = 8; + if (getInstaTick()) { + if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, + td.z + r)) { + int id = getTile(td.x, td.y, td.z); + if (id == td.tileId && id > 0) { + Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); + } + } + MemSect(0); + return; + } - if (hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) - { - if (tileId > 0) - { - td.delay(tickDelay + levelData->getTime()); - } - EnterCriticalSection(&m_tickNextTickCS); - if ( tickNextTickSet.find(td) == tickNextTickSet.end() ) - { - tickNextTickSet.insert(td); - tickNextTickList.insert(td); - } - LeaveCriticalSection(&m_tickNextTickCS); - } - MemSect(0); + if (hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) { + if (tileId > 0) { + td.delay(tickDelay + levelData->getTime()); + } + EnterCriticalSection(&m_tickNextTickCS); + if (tickNextTickSet.find(td) == tickNextTickSet.end()) { + tickNextTickSet.insert(td); + tickNextTickList.insert(td); + } + LeaveCriticalSection(&m_tickNextTickCS); + } + MemSect(0); } -void ServerLevel::forceAddTileTick(int x, int y, int z, int tileId, int tickDelay) -{ +void ServerLevel::forceAddTileTick(int x, int y, int z, int tileId, + int tickDelay) { TickNextTickData td = TickNextTickData(x, y, z, tileId); - if (tileId > 0) - { + if (tileId > 0) { td.delay(tickDelay + levelData->getTime()); } - EnterCriticalSection(&m_tickNextTickCS); - if ( tickNextTickSet.find(td) == tickNextTickSet.end() ) - { + EnterCriticalSection(&m_tickNextTickCS); + if (tickNextTickSet.find(td) == tickNextTickSet.end()) { tickNextTickSet.insert(td); tickNextTickList.insert(td); } - LeaveCriticalSection(&m_tickNextTickCS); + LeaveCriticalSection(&m_tickNextTickCS); } -void ServerLevel::tickEntities() -{ - if (players.empty()) - { - if (emptyTime++ >= EMPTY_TIME_NO_TICK) - { - return; - } - } - else - { - emptyTime = 0; - } +void ServerLevel::tickEntities() { + if (players.empty()) { + if (emptyTime++ >= EMPTY_TIME_NO_TICK) { + return; + } + } else { + emptyTime = 0; + } - Level::tickEntities(); + Level::tickEntities(); } -bool ServerLevel::tickPendingTicks(bool force) -{ - EnterCriticalSection(&m_tickNextTickCS); - int count = (int)tickNextTickList.size(); - int count2 = (int)tickNextTickSet.size(); - if (count != tickNextTickSet.size()) - { - // TODO 4J Stu - Add new exception types - //throw new IllegalStateException("TickNextTick list out of synch"); - } - if (count > MAX_TICK_TILES_PER_TICK) count = MAX_TICK_TILES_PER_TICK; - - AUTO_VAR(itTickList, tickNextTickList.begin()); - for (int i = 0; i < count; i++) - { - TickNextTickData td = *(itTickList); - if (!force && td.m_delay > levelData->getTime()) - { - break; - } +bool ServerLevel::tickPendingTicks(bool force) { + EnterCriticalSection(&m_tickNextTickCS); + int count = (int)tickNextTickList.size(); + int count2 = (int)tickNextTickSet.size(); + if (count != tickNextTickSet.size()) { + // TODO 4J Stu - Add new exception types + // throw new IllegalStateException("TickNextTick list out of synch"); + } + if (count > MAX_TICK_TILES_PER_TICK) count = MAX_TICK_TILES_PER_TICK; - itTickList = tickNextTickList.erase(itTickList); - tickNextTickSet.erase(td); - int r = 8; - if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, td.z + r)) - { - int id = getTile(td.x, td.y, td.z); - if (id == td.tileId && id > 0) - { - Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); - } - } - } + AUTO_VAR(itTickList, tickNextTickList.begin()); + for (int i = 0; i < count; i++) { + TickNextTickData td = *(itTickList); + if (!force && td.m_delay > levelData->getTime()) { + break; + } - int count3 = (int)tickNextTickList.size(); - int count4 = (int)tickNextTickSet.size(); + itTickList = tickNextTickList.erase(itTickList); + tickNextTickSet.erase(td); + int r = 8; + if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, + td.z + r)) { + int id = getTile(td.x, td.y, td.z); + if (id == td.tileId && id > 0) { + Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); + } + } + } - bool retval = tickNextTickList.size() != 0; - LeaveCriticalSection(&m_tickNextTickCS); + int count3 = (int)tickNextTickList.size(); + int count4 = (int)tickNextTickSet.size(); - return retval; + bool retval = tickNextTickList.size() != 0; + LeaveCriticalSection(&m_tickNextTickCS); + + return retval; } -std::vector *ServerLevel::fetchTicksInChunk(LevelChunk *chunk, bool remove) -{ - EnterCriticalSection(&m_tickNextTickCS); - std::vector *results = new std::vector; +std::vector* ServerLevel::fetchTicksInChunk(LevelChunk* chunk, + bool remove) { + EnterCriticalSection(&m_tickNextTickCS); + std::vector* results = new std::vector; - ChunkPos *pos = chunk->getPos(); + ChunkPos* pos = chunk->getPos(); // 4jcraft added cast to unsigned - int west = (unsigned) pos->x << 4; + int west = (unsigned)pos->x << 4; int east = west + 16; - int north =(unsigned) pos->z << 4; + int north = (unsigned)pos->z << 4; int south = north + 16; - delete pos; + delete pos; - for( AUTO_VAR(it, tickNextTickSet.begin()); it != tickNextTickSet.end(); ) - { - TickNextTickData td = *it; + for (AUTO_VAR(it, tickNextTickSet.begin()); it != tickNextTickSet.end();) { + TickNextTickData td = *it; - if (td.x >= west && td.x < east && td.z >= north && td.z < south) - { - if (remove) - { + if (td.x >= west && td.x < east && td.z >= north && td.z < south) { + if (remove) { tickNextTickList.erase(td); it = tickNextTickSet.erase(it); + } else { + it++; } - else - { - it++; - } - results->push_back(td); + results->push_back(td); + } else { + it++; } - else - { - it++; - } - } + } - LeaveCriticalSection(&m_tickNextTickCS); - return results; + LeaveCriticalSection(&m_tickNextTickCS); + return results; } -void ServerLevel::tick(std::shared_ptr e, bool actual) -{ - if (!server->isAnimals() && ((e->GetType() & eTYPE_ANIMAL) || (e->GetType() & eTYPE_WATERANIMAL))) - { +void ServerLevel::tick(std::shared_ptr e, bool actual) { + if (!server->isAnimals() && + ((e->GetType() & eTYPE_ANIMAL) || (e->GetType() & eTYPE_WATERANIMAL))) { e->remove(); } - if (!server->isNpcsEnabled() && (std::dynamic_pointer_cast(e) != NULL)) - { - e->remove(); - } - if (e->rider.lock() == NULL || (std::dynamic_pointer_cast(e->rider.lock())==NULL) ) // 4J - was !(e->rider instanceof Player) - { + if (!server->isNpcsEnabled() && + (std::dynamic_pointer_cast(e) != NULL)) { + e->remove(); + } + if (e->rider.lock() == NULL || + (std::dynamic_pointer_cast(e->rider.lock()) == + NULL)) // 4J - was !(e->rider instanceof Player) + { Level::tick(e, actual); } } -void ServerLevel::forceTick(std::shared_ptr e, bool actual) -{ - Level::tick(e, actual); +void ServerLevel::forceTick(std::shared_ptr e, bool actual) { + Level::tick(e, actual); } -ChunkSource *ServerLevel::createChunkSource() -{ - ChunkStorage *storage = levelStorage->createChunkStorage(dimension); - cache = new ServerChunkCache(this, storage, dimension->createRandomLevelSource()); +ChunkSource* ServerLevel::createChunkSource() { + ChunkStorage* storage = levelStorage->createChunkStorage(dimension); + cache = new ServerChunkCache(this, storage, + dimension->createRandomLevelSource()); return cache; } -std::vector > *ServerLevel::getTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - std::vector > *result = new std::vector >; - for (unsigned int i = 0; i < tileEntityList.size(); i++) - { +std::vector >* ServerLevel::getTileEntitiesInRegion( + int x0, int y0, int z0, int x1, int y1, int z1) { + std::vector >* result = + new std::vector >; + for (unsigned int i = 0; i < tileEntityList.size(); i++) { std::shared_ptr te = tileEntityList[i]; - if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) - { + if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && + te->y < y1 && te->z < z1) { result->push_back(te); } } return result; } -bool ServerLevel::mayInteract(std::shared_ptr player, int xt, int yt, int zt, int content) -{ - // 4J-PB - This will look like a bug to players, and we really should have a message to explain why we're not allowing lava to be placed at or near a spawn point - // We'll need to do this in a future update +bool ServerLevel::mayInteract(std::shared_ptr player, int xt, int yt, + int zt, int content) { + // 4J-PB - This will look like a bug to players, and we really should have a + // message to explain why we're not allowing lava to be placed at or near a + // spawn point We'll need to do this in a future update - // 4J-PB - Let's allow water near the spawn point, but not lava - if(content!=Tile::lava_Id) - { - // allow this to be used - return true; - } - else if(dimension->id == 0) // 4J Stu - Only limit this in the overworld - { - int xd = (int) Mth::abs((float)(xt - levelData->getXSpawn())); - int zd = (int) Mth::abs((float)(zt - levelData->getZSpawn())); - if (xd > zd) zd = xd; - return (zd > 16 || server->getPlayers()->isOp(player->name)); - } - return true; + // 4J-PB - Let's allow water near the spawn point, but not lava + if (content != Tile::lava_Id) { + // allow this to be used + return true; + } else if (dimension->id == 0) // 4J Stu - Only limit this in the overworld + { + int xd = (int)Mth::abs((float)(xt - levelData->getXSpawn())); + int zd = (int)Mth::abs((float)(zt - levelData->getZSpawn())); + if (xd > zd) zd = xd; + return (zd > 16 || server->getPlayers()->isOp(player->name)); + } + return true; } -void ServerLevel::initializeLevel(LevelSettings *settings) -{ - setInitialSpawn(settings); +void ServerLevel::initializeLevel(LevelSettings* settings) { + setInitialSpawn(settings); - Level::initializeLevel(settings); + Level::initializeLevel(settings); } /** -* Sets the initial spawn, created this method so we could do a special -* location for the demo version. -*/ -void ServerLevel::setInitialSpawn(LevelSettings *levelSettings) -{ - if (!dimension->mayRespawn()) - { - levelData->setSpawn(0, dimension->getSpawnYPosition(), 0); - return; - } + * Sets the initial spawn, created this method so we could do a special + * location for the demo version. + */ +void ServerLevel::setInitialSpawn(LevelSettings* levelSettings) { + if (!dimension->mayRespawn()) { + levelData->setSpawn(0, dimension->getSpawnYPosition(), 0); + return; + } - isFindingSpawn = true; + isFindingSpawn = true; - BiomeSource *biomeSource = dimension->biomeSource; - std::vector playerSpawnBiomes = biomeSource->getPlayerSpawnBiomes(); - Random random(getSeed()); + BiomeSource* biomeSource = dimension->biomeSource; + std::vector playerSpawnBiomes = biomeSource->getPlayerSpawnBiomes(); + Random random(getSeed()); - TilePos *findBiome = biomeSource->findBiome(0, 0, 16 * 16, playerSpawnBiomes, &random); + TilePos* findBiome = + biomeSource->findBiome(0, 0, 16 * 16, playerSpawnBiomes, &random); - int xSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; - int ySpawn = dimension->getSpawnYPosition(); - int zSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; - int minXZ = - (dimension->getXZSize() * 16 ) / 2; - int maxXZ = (dimension->getXZSize() * 16 ) / 2 - 1; + int xSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; + int ySpawn = dimension->getSpawnYPosition(); + int zSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; + int minXZ = -(dimension->getXZSize() * 16) / 2; + int maxXZ = (dimension->getXZSize() * 16) / 2 - 1; - if (findBiome != NULL) - { - xSpawn = findBiome->x; - zSpawn = findBiome->z; - delete findBiome; - } - else - { - app.DebugPrintf("Level::setInitialSpawn - Unable to find spawn biome\n"); - } + if (findBiome != NULL) { + xSpawn = findBiome->x; + zSpawn = findBiome->z; + delete findBiome; + } else { + app.DebugPrintf( + "Level::setInitialSpawn - Unable to find spawn biome\n"); + } - int tries = 0; + int tries = 0; - while (!dimension->isValidSpawn(xSpawn, zSpawn)) - { - // 4J-PB changed to stay within our level limits - xSpawn += random.nextInt(64) - random.nextInt(64); - if(xSpawn>maxXZ) xSpawn=0; - if(xSpawnmaxXZ) zSpawn=0; - if(zSpawnisValidSpawn(xSpawn, zSpawn)) { + // 4J-PB changed to stay within our level limits + xSpawn += random.nextInt(64) - random.nextInt(64); + if (xSpawn > maxXZ) xSpawn = 0; + if (xSpawn < minXZ) xSpawn = 0; + zSpawn += random.nextInt(64) - random.nextInt(64); + if (zSpawn > maxXZ) zSpawn = 0; + if (zSpawn < minXZ) zSpawn = 0; - levelData->setSpawn(xSpawn, ySpawn, zSpawn); - if (levelSettings->hasStartingBonusItems()) - { - generateBonusItemsNearSpawn(); - } - isFindingSpawn = false; + if (++tries == 1000) break; + } + + levelData->setSpawn(xSpawn, ySpawn, zSpawn); + if (levelSettings->hasStartingBonusItems()) { + generateBonusItemsNearSpawn(); + } + isFindingSpawn = false; } // 4J - brought forward from 1.3.2 -void ServerLevel::generateBonusItemsNearSpawn() -{ +void ServerLevel::generateBonusItemsNearSpawn() { // once we've found the initial spawn, try to find a location for the -// starting bonus chest - // 4J - added - scan the spawn area first to see if there's already a chest near here + // starting bonus chest + // 4J - added - scan the spawn area first to see if there's already a chest + // near here - static const int r = 20; - int xs = levelData->getXSpawn(); - int zs = levelData->getZSpawn(); - for( int xx = -r; xx <= r; xx++ ) - for( int zz = -r; zz <= r; zz++ ) - { - int x = xx + xs; - int z = zz + zs; - int y = getTopSolidBlock( x, z ) - 1; - - if( getTile( x, y, z ) == Tile::chest_Id ) - { - std::shared_ptr chest = std::dynamic_pointer_cast(getTileEntity(x, y, z)); - if (chest != NULL) - { - if( chest->isBonusChest ) - { - return; - } - } - } - } + static const int r = 20; + int xs = levelData->getXSpawn(); + int zs = levelData->getZSpawn(); + for (int xx = -r; xx <= r; xx++) + for (int zz = -r; zz <= r; zz++) { + int x = xx + xs; + int z = zz + zs; + int y = getTopSolidBlock(x, z) - 1; - BonusChestFeature *feature = new BonusChestFeature(RANDOM_BONUS_ITEMS, 16); - for (int attempt = 0; attempt < 16; attempt++) - { - int x = levelData->getXSpawn() + random->nextInt(6) - random->nextInt(6); - int z = levelData->getZSpawn() + random->nextInt(6) - random->nextInt(6); + if (getTile(x, y, z) == Tile::chest_Id) { + std::shared_ptr chest = + std::dynamic_pointer_cast( + getTileEntity(x, y, z)); + if (chest != NULL) { + if (chest->isBonusChest) { + return; + } + } + } + } + + BonusChestFeature* feature = new BonusChestFeature(RANDOM_BONUS_ITEMS, 16); + for (int attempt = 0; attempt < 16; attempt++) { + int x = + levelData->getXSpawn() + random->nextInt(6) - random->nextInt(6); + int z = + levelData->getZSpawn() + random->nextInt(6) - random->nextInt(6); int y = getTopSolidBlock(x, z) + 1; - if (feature->place(this, random, x, y, z, (attempt == 15) )) - { + if (feature->place(this, random, x, y, z, (attempt == 15))) { break; } } - delete feature; + delete feature; } -Pos *ServerLevel::getDimensionSpecificSpawn() -{ - return dimension->getSpawnPos(); +Pos* ServerLevel::getDimensionSpecificSpawn() { + return dimension->getSpawnPos(); } // 4j Added for XboxOne PLM -void ServerLevel::Suspend() -{ - if(StorageManager.GetSaveDisabled()) return; - saveLevelData(); - chunkSource->saveAllEntities(); +void ServerLevel::Suspend() { + if (StorageManager.GetSaveDisabled()) return; + saveLevelData(); + chunkSource->saveAllEntities(); } -void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAutosave) -{ - if (!chunkSource->shouldSave()) return; +void ServerLevel::save(bool force, ProgressListener* progressListener, + bool bAutosave) { + if (!chunkSource->shouldSave()) return; - // 4J-PB - check that saves are enabled - if(StorageManager.GetSaveDisabled()) return; + // 4J-PB - check that saves are enabled + if (StorageManager.GetSaveDisabled()) return; + if (progressListener != NULL) { + if (bAutosave) { + progressListener->progressStartNoAbort( + IDS_PROGRESS_AUTOSAVING_LEVEL); + } else { + progressListener->progressStartNoAbort(IDS_PROGRESS_SAVING_LEVEL); + } + } + PIXBeginNamedEvent(0, "Saving level data"); + saveLevelData(); + PIXEndNamedEvent(); - if (progressListener != NULL) - { - if(bAutosave) - { - progressListener->progressStartNoAbort(IDS_PROGRESS_AUTOSAVING_LEVEL); - } - else - { - progressListener->progressStartNoAbort(IDS_PROGRESS_SAVING_LEVEL); - } - - } - PIXBeginNamedEvent(0,"Saving level data"); - saveLevelData(); - PIXEndNamedEvent(); - - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); + if (progressListener != NULL) + progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Our autosave is a minimal save. All the chunks are saves by the constant save process - if(bAutosave) - { - chunkSource->saveAllEntities(); - } - else + // Our autosave is a minimal save. All the chunks are saves by the constant + // save process + if (bAutosave) { + chunkSource->saveAllEntities(); + } else #endif - { - chunkSource->save(force, progressListener); + { + chunkSource->save(force, progressListener); #ifdef _LARGE_WORLDS - // 4J Stu - Only do this if there are players in the level - if(chunkMap->players.size() > 0) - { - // 4J Stu - This will come in a later change anyway - // clean cache - std::vector *loadedChunkList = cache->getLoadedChunkList(); - for (AUTO_VAR(it, loadedChunkList->begin()); it != loadedChunkList->end(); ++it) - { - LevelChunk *lc = *it; - if (!chunkMap->hasChunk(lc->x, lc->z) ) - { - cache->drop(lc->x, lc->z); - } - } - } + // 4J Stu - Only do this if there are players in the level + if (chunkMap->players.size() > 0) { + // 4J Stu - This will come in a later change anyway + // clean cache + std::vector* loadedChunkList = + cache->getLoadedChunkList(); + for (AUTO_VAR(it, loadedChunkList->begin()); + it != loadedChunkList->end(); ++it) { + LevelChunk* lc = *it; + if (!chunkMap->hasChunk(lc->x, lc->z)) { + cache->drop(lc->x, lc->z); + } + } + } #endif - } + } - //if( force && !isClientSide ) - //{ - // if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); - // levelStorage->flushSaveFile(); - //} + // if( force && !isClientSide ) + //{ + // if (progressListener != NULL) + //progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + // levelStorage->flushSaveFile(); + // } } // 4J Added -void ServerLevel::saveToDisc(ProgressListener *progressListener, bool autosave) -{ - // 4J-PB - check that saves are enabled - if(StorageManager.GetSaveDisabled()) return; +void ServerLevel::saveToDisc(ProgressListener* progressListener, + bool autosave) { + // 4J-PB - check that saves are enabled + if (StorageManager.GetSaveDisabled()) return; - // Check if we are using a trial version of a texture pack (which will be the case for going into the mash-up pack world with a trial version) - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + // Check if we are using a trial version of a texture pack (which will be + // the case for going into the mash-up pack world with a trial version) + if (!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + DLCTexturePack* pDLCTexPack = (DLCTexturePack*)tPack; - DLCPack * pDLCPack=pDLCTexPack->getDLCInfoParentPack(); + DLCPack* pDLCPack = pDLCTexPack->getDLCInfoParentPack(); - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - return; - } - } + if (!pDLCPack->hasPurchasedFile(DLCManager::e_DLCType_Texture, L"")) { + return; + } + } - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); - levelStorage->flushSaveFile(autosave); + if (progressListener != NULL) + progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + levelStorage->flushSaveFile(autosave); } -void ServerLevel::saveLevelData() -{ - checkSession(); +void ServerLevel::saveLevelData() { + checkSession(); - levelStorage->saveLevelData(levelData, &players); - savedDataStorage->save(); + levelStorage->saveLevelData(levelData, &players); + savedDataStorage->save(); } -void ServerLevel::entityAdded(std::shared_ptr e) -{ +void ServerLevel::entityAdded(std::shared_ptr e) { Level::entityAdded(e); entitiesById[e->entityId] = e; - std::vector > *es = e->getSubEntities(); - if (es != NULL) - { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) - { - entitiesById.insert( intEntityMap::value_type( (*it)->entityId, (*it) )); - } - } - entityAddedExtra(e); // 4J added + std::vector >* es = e->getSubEntities(); + if (es != NULL) { + // for (int i = 0; i < es.length; i++) + for (AUTO_VAR(it, es->begin()); it != es->end(); ++it) { + entitiesById.insert( + intEntityMap::value_type((*it)->entityId, (*it))); + } + } + entityAddedExtra(e); // 4J added } -void ServerLevel::entityRemoved(std::shared_ptr e) -{ +void ServerLevel::entityRemoved(std::shared_ptr e) { Level::entityRemoved(e); - entitiesById.erase(e->entityId); - std::vector > *es = e->getSubEntities(); - if (es != NULL) - { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) - { - entitiesById.erase((*it)->entityId); - } - } - entityRemovedExtra(e); // 4J added + entitiesById.erase(e->entityId); + std::vector >* es = e->getSubEntities(); + if (es != NULL) { + // for (int i = 0; i < es.length; i++) + for (AUTO_VAR(it, es->begin()); it != es->end(); ++it) { + entitiesById.erase((*it)->entityId); + } + } + entityRemovedExtra(e); // 4J added } -std::shared_ptr ServerLevel::getEntity(int id) -{ - return entitiesById[id]; +std::shared_ptr ServerLevel::getEntity(int id) { + return entitiesById[id]; } -bool ServerLevel::addGlobalEntity(std::shared_ptr e) -{ - if (Level::addGlobalEntity(e)) - { - server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, std::shared_ptr( new AddGlobalEntityPacket(e) ) ); +bool ServerLevel::addGlobalEntity(std::shared_ptr e) { + if (Level::addGlobalEntity(e)) { + server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, + std::shared_ptr( + new AddGlobalEntityPacket(e))); return true; } return false; } -void ServerLevel::broadcastEntityEvent(std::shared_ptr e, uint8_t event) -{ - std::shared_ptr p = std::shared_ptr( new EntityEventPacket(e->entityId, event) ); +void ServerLevel::broadcastEntityEvent(std::shared_ptr e, + uint8_t event) { + std::shared_ptr p = std::shared_ptr( + new EntityEventPacket(e->entityId, event)); server->getLevel(dimension->id)->getTracker()->broadcastAndSend(e, p); } -std::shared_ptr ServerLevel::explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks) -{ +std::shared_ptr ServerLevel::explode(std::shared_ptr source, + double x, double y, double z, + float r, bool fire, + bool destroyBlocks) { // instead of calling super, we run the same explosion code here except // we don't generate any particles - std::shared_ptr explosion = std::shared_ptr( new Explosion(this, source, x, y, z, r) ); + std::shared_ptr explosion = + std::shared_ptr(new Explosion(this, source, x, y, z, r)); explosion->fire = fire; - explosion->destroyBlocks = destroyBlocks; + explosion->destroyBlocks = destroyBlocks; explosion->explode(); explosion->finalizeExplosion(false); - if (!destroyBlocks) - { - explosion->toBlow.clear(); - } + if (!destroyBlocks) { + explosion->toBlow.clear(); + } - std::vector > sentTo; - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - if (player->dimension != dimension->id) continue; + std::vector > sentTo; + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + if (player->dimension != dimension->id) continue; - bool knockbackOnly = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - continue; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - knockbackOnly = true; - } - } - } - } + bool knockbackOnly = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + continue; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + knockbackOnly = true; + } + } + } + } - if (player->distanceToSqr(x, y, z) < 64 * 64) - { - Vec3 *knockbackVec = explosion->getHitPlayerKnockback(player); - //app.DebugPrintf("Sending %s with knockback (%f,%f,%f)\n", knockbackOnly?"knockbackOnly":"allExplosion",knockbackVec->x,knockbackVec->y,knockbackVec->z); - // If the player is not the primary on the system, then we only want to send info for the knockback - player->connection->send( std::shared_ptr( new ExplodePacket(x, y, z, r, &explosion->toBlow, knockbackVec, knockbackOnly))); - sentTo.push_back( player ); + if (player->distanceToSqr(x, y, z) < 64 * 64) { + Vec3* knockbackVec = explosion->getHitPlayerKnockback(player); + // app.DebugPrintf("Sending %s with knockback (%f,%f,%f)\n", + // knockbackOnly?"knockbackOnly":"allExplosion",knockbackVec->x,knockbackVec->y,knockbackVec->z); + // If the player is not the primary on the system, then we only + // want to send info for the knockback + player->connection->send(std::shared_ptr( + new ExplodePacket(x, y, z, r, &explosion->toBlow, knockbackVec, + knockbackOnly))); + sentTo.push_back(player); } } return explosion; } -void ServerLevel::tileEvent(int x, int y, int z, int tile, int b0, int b1) -{ - // super.tileEvent(x, y, z, b0, b1); - // server.getPlayers().broadcast(x, y, z, 64, dimension.id, new TileEventPacket(x, y, z, b0, b1)); - TileEventData newEvent(x, y, z, tile, b0, b1); - //for (TileEventData te : tileEvents[activeTileEventsList]) - for(AUTO_VAR(it, tileEvents[activeTileEventsList].begin()); it != tileEvents[activeTileEventsList].end(); ++it) - { - if ((*it).equals(newEvent)) - { - return; - } - } - tileEvents[activeTileEventsList].push_back(newEvent); +void ServerLevel::tileEvent(int x, int y, int z, int tile, int b0, int b1) { + // super.tileEvent(x, y, z, b0, b1); + // server.getPlayers().broadcast(x, y, z, 64, dimension.id, new + // TileEventPacket(x, y, z, b0, b1)); + TileEventData newEvent(x, y, z, tile, b0, b1); + // for (TileEventData te : tileEvents[activeTileEventsList]) + for (AUTO_VAR(it, tileEvents[activeTileEventsList].begin()); + it != tileEvents[activeTileEventsList].end(); ++it) { + if ((*it).equals(newEvent)) { + return; + } + } + tileEvents[activeTileEventsList].push_back(newEvent); } -void ServerLevel::runTileEvents() -{ - // use two lists until both are empty, intended to avoid concurrent - // modifications - while (!tileEvents[activeTileEventsList].empty()) - { - int runList = activeTileEventsList; - activeTileEventsList ^= 1; +void ServerLevel::runTileEvents() { + // use two lists until both are empty, intended to avoid concurrent + // modifications + while (!tileEvents[activeTileEventsList].empty()) { + int runList = activeTileEventsList; + activeTileEventsList ^= 1; - //for (TileEventData te : tileEvents[runList]) - for(AUTO_VAR(it, tileEvents[runList].begin()); it != tileEvents[runList].end(); ++it) - { - if (doTileEvent(&(*it))) - { - TileEventData te = *it; - server->getPlayers()->broadcast(te.getX(), te.getY(), te.getZ(), 64, dimension->id, std::shared_ptr( new TileEventPacket(te.getX(), te.getY(), te.getZ(), te.getTile(), te.getParamA(), te.getParamB()))); - } - } - tileEvents[runList].clear(); - } + // for (TileEventData te : tileEvents[runList]) + for (AUTO_VAR(it, tileEvents[runList].begin()); + it != tileEvents[runList].end(); ++it) { + if (doTileEvent(&(*it))) { + TileEventData te = *it; + server->getPlayers()->broadcast( + te.getX(), te.getY(), te.getZ(), 64, dimension->id, + std::shared_ptr(new TileEventPacket( + te.getX(), te.getY(), te.getZ(), te.getTile(), + te.getParamA(), te.getParamB()))); + } + } + tileEvents[runList].clear(); + } } -bool ServerLevel::doTileEvent(TileEventData *te) -{ - int t = getTile(te->getX(), te->getY(), te->getZ()); - if (t == te->getTile()) { - Tile::tiles[t]->triggerEvent(this, te->getX(), te->getY(), te->getZ(), te->getParamA(), te->getParamB()); - return true; - } - return false; +bool ServerLevel::doTileEvent(TileEventData* te) { + int t = getTile(te->getX(), te->getY(), te->getZ()); + if (t == te->getTile()) { + Tile::tiles[t]->triggerEvent(this, te->getX(), te->getY(), te->getZ(), + te->getParamA(), te->getParamB()); + return true; + } + return false; } -void ServerLevel::closeLevelStorage() -{ - levelStorage->closeAll(); -} +void ServerLevel::closeLevelStorage() { levelStorage->closeAll(); } -void ServerLevel::tickWeather() -{ +void ServerLevel::tickWeather() { bool wasRaining = isRaining(); Level::tickWeather(); - if (wasRaining != isRaining()) - { - if (wasRaining) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + if (wasRaining != isRaining()) { + if (wasRaining) { + server->getPlayers()->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_RAINING, 0))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_RAINING, 0))); } } - } -MinecraftServer *ServerLevel::getServer() -{ - return server; +MinecraftServer* ServerLevel::getServer() { return server; } + +EntityTracker* ServerLevel::getTracker() { return tracker; } + +void ServerLevel::setTimeAndAdjustTileTicks(__int64 newTime) { + __int64 delta = newTime - levelData->getTime(); + // 4J - can't directly adjust m_delay in a set as it has a const interator, + // since changing values in here might change the ordering of the elements + // in the set. Instead move to a vector, do the adjustment, put back in the + // set. + std::vector temp; + for (AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); + ++it) { + temp.push_back(*it); + temp.back().m_delay += delta; + } + tickNextTickList.clear(); + for (unsigned int i = 0; i < temp.size(); i++) { + tickNextTickList.insert(temp[i]); + } + setTime(newTime); } -EntityTracker *ServerLevel::getTracker() -{ - return tracker; +PlayerChunkMap* ServerLevel::getChunkMap() { return chunkMap; } + +// 4J Stu - Sometimes we want to update tiles on the server from the main thread +// (eg SignTileEntity when string verify returns) +void ServerLevel::queueSendTileUpdate(int x, int y, int z) { + EnterCriticalSection(&m_csQueueSendTileUpdates); + m_queuedSendTileUpdates.push_back(new Pos(x, y, z)); + LeaveCriticalSection(&m_csQueueSendTileUpdates); } -void ServerLevel::setTimeAndAdjustTileTicks(__int64 newTime) -{ - __int64 delta = newTime - levelData->getTime(); - // 4J - can't directly adjust m_delay in a set as it has a const interator, since changing values in here might change the ordering of the elements in the set. - // Instead move to a vector, do the adjustment, put back in the set. - std::vector temp; - for(AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); ++it) - { - temp.push_back(*it); - temp.back().m_delay += delta; - } - tickNextTickList.clear(); - for(unsigned int i = 0; i < temp.size(); i++ ) - { - tickNextTickList.insert(temp[i]); - } - setTime(newTime); +void ServerLevel::runQueuedSendTileUpdates() { + EnterCriticalSection(&m_csQueueSendTileUpdates); + for (AUTO_VAR(it, m_queuedSendTileUpdates.begin()); + it != m_queuedSendTileUpdates.end(); ++it) { + Pos* p = *it; + sendTileUpdated(p->x, p->y, p->z); + delete p; + } + m_queuedSendTileUpdates.clear(); + LeaveCriticalSection(&m_csQueueSendTileUpdates); } -PlayerChunkMap *ServerLevel::getChunkMap() -{ - return chunkMap; -} +// 4J - added special versions of addEntity and extra processing on entity +// removed and added so we can limit the number of itementities created +bool ServerLevel::addEntity(std::shared_ptr e) { + // If its an item entity, and we've got to our capacity, delete the oldest + if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding item entity count + //%d\n",m_itemEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_itemEntities.size() >= MAX_ITEM_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_itemEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an hanging entity, and we've got to our capacity, delete the + // oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding item entity count + //%d\n",m_itemEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_hangingEntities.size() >= MAX_HANGING_ENTITIES) { + // printf("Adding - doing remove\n"); -// 4J Stu - Sometimes we want to update tiles on the server from the main thread (eg SignTileEntity when string verify returns) -void ServerLevel::queueSendTileUpdate(int x, int y, int z) -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - m_queuedSendTileUpdates.push_back( new Pos(x,y,z) ); - LeaveCriticalSection(&m_csQueueSendTileUpdates); -} + // 4J-PB - refuse to add the entity, since we'll be removing one + // already there, and it may be an item frame with something in it. + LeaveCriticalSection(&m_limiterCS); + return FALSE; -void ServerLevel::runQueuedSendTileUpdates() -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) - { - Pos *p = *it; - sendTileUpdated(p->x, p->y, p->z); - delete p; - } - m_queuedSendTileUpdates.clear(); - LeaveCriticalSection(&m_csQueueSendTileUpdates); -} - -// 4J - added special versions of addEntity and extra processing on entity removed and added so we can limit the number of itementities created -bool ServerLevel::addEntity(std::shared_ptr e) -{ - // If its an item entity, and we've got to our capacity, delete the oldest - if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding item entity count %d\n",m_itemEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_itemEntities.size() >= MAX_ITEM_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_itemEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an hanging entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { - // printf("Adding item entity count %d\n",m_itemEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_hangingEntities.size() >= MAX_HANGING_ENTITIES ) - { - // printf("Adding - doing remove\n"); - - // 4J-PB - refuse to add the entity, since we'll be removing one already there, and it may be an item frame with something in it. - LeaveCriticalSection(&m_limiterCS); - return FALSE; - - //removeEntityImmediately(m_hangingEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an arrow entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding arrow entity count %d\n",m_arrowEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_arrowEntities.size() >= MAX_ARROW_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_arrowEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an experience orb entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding arrow entity count %d\n",m_arrowEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_experienceOrbEntities.size() >= MAX_EXPERIENCEORB_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_experienceOrbEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - return Level::addEntity(e); + // removeEntityImmediately(m_hangingEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an arrow entity, and we've got to our capacity, delete the oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding arrow entity count + //%d\n",m_arrowEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_arrowEntities.size() >= MAX_ARROW_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_arrowEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an experience orb entity, and we've got to our capacity, delete + // the oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding arrow entity count + //%d\n",m_arrowEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_experienceOrbEntities.size() >= MAX_EXPERIENCEORB_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_experienceOrbEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + return Level::addEntity(e); } // Maintain a cound of primed tnt & falling tiles in this level -void ServerLevel::entityAddedExtra(std::shared_ptr e) -{ - if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_itemEntities.push_back(e); -// printf("entity added: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_hangingEntities.push_back(e); - // printf("entity added: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_arrowEntities.push_back(e); -// printf("entity added: arrow entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_experienceOrbEntities.push_back(e); -// printf("entity added: experience orb entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_primedTntCount++; - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_fallingTileCount++; - LeaveCriticalSection(&m_limiterCS); - } +void ServerLevel::entityAddedExtra(std::shared_ptr e) { + if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_itemEntities.push_back(e); + // printf("entity added: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_hangingEntities.push_back(e); + // printf("entity added: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_arrowEntities.push_back(e); + // printf("entity added: arrow entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_experienceOrbEntities.push_back(e); + // printf("entity added: experience orb entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_primedTntCount++; + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_fallingTileCount++; + LeaveCriticalSection(&m_limiterCS); + } } -// Maintain a cound of primed tnt & falling tiles in this level, and remove any item entities from our list -void ServerLevel::entityRemovedExtra(std::shared_ptr e) -{ - if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_itemEntities.begin(),m_itemEntities.end(),e)); - if( it != m_itemEntities.end() ) - { -// printf("Item to remove found\n"); - m_itemEntities.erase(it); - } -// printf("entity removed: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - // printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_hangingEntities.begin(),m_hangingEntities.end(),e)); - if( it != m_hangingEntities.end() ) - { - // printf("Item to remove found\n"); - m_hangingEntities.erase(it); - } - // printf("entity removed: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: arrow entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_arrowEntities.begin(),m_arrowEntities.end(),e)); - if( it != m_arrowEntities.end() ) - { -// printf("Item to remove found\n"); - m_arrowEntities.erase(it); - } -// printf("entity removed: arrow entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: experience orb entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_experienceOrbEntities.begin(),m_experienceOrbEntities.end(),e)); - if( it != m_experienceOrbEntities.end() ) - { -// printf("Item to remove found\n"); - m_experienceOrbEntities.erase(it); - } -// printf("entity removed: experience orb entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_primedTntCount--; - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_fallingTileCount--; - LeaveCriticalSection(&m_limiterCS); - } +// Maintain a cound of primed tnt & falling tiles in this level, and remove any +// item entities from our list +void ServerLevel::entityRemovedExtra(std::shared_ptr e) { + if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: item entity count + //%d\n",m_itemEntities.size()); + AUTO_VAR(it, find(m_itemEntities.begin(), m_itemEntities.end(), e)); + if (it != m_itemEntities.end()) { + // printf("Item to remove found\n"); + m_itemEntities.erase(it); + } + // printf("entity removed: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: item entity count + //%d\n",m_itemEntities.size()); + AUTO_VAR(it, + find(m_hangingEntities.begin(), m_hangingEntities.end(), e)); + if (it != m_hangingEntities.end()) { + // printf("Item to remove found\n"); + m_hangingEntities.erase(it); + } + // printf("entity removed: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: arrow entity count + //%d\n",m_arrowEntities.size()); + AUTO_VAR(it, find(m_arrowEntities.begin(), m_arrowEntities.end(), e)); + if (it != m_arrowEntities.end()) { + // printf("Item to remove found\n"); + m_arrowEntities.erase(it); + } + // printf("entity removed: arrow entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: experience orb entity count + //%d\n",m_arrowEntities.size()); + AUTO_VAR(it, find(m_experienceOrbEntities.begin(), + m_experienceOrbEntities.end(), e)); + if (it != m_experienceOrbEntities.end()) { + // printf("Item to remove found\n"); + m_experienceOrbEntities.erase(it); + } + // printf("entity removed: experience orb entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_primedTntCount--; + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_fallingTileCount--; + LeaveCriticalSection(&m_limiterCS); + } } -bool ServerLevel::newPrimedTntAllowed() -{ - EnterCriticalSection(&m_limiterCS); - bool retval = m_primedTntCount < MAX_PRIMED_TNT; - LeaveCriticalSection(&m_limiterCS); - return retval; +bool ServerLevel::newPrimedTntAllowed() { + EnterCriticalSection(&m_limiterCS); + bool retval = m_primedTntCount < MAX_PRIMED_TNT; + LeaveCriticalSection(&m_limiterCS); + return retval; } -bool ServerLevel::newFallingTileAllowed() -{ - EnterCriticalSection(&m_limiterCS); - bool retval = m_fallingTileCount < MAX_FALLING_TILE; - LeaveCriticalSection(&m_limiterCS); - return retval; +bool ServerLevel::newFallingTileAllowed() { + EnterCriticalSection(&m_limiterCS); + bool retval = m_fallingTileCount < MAX_FALLING_TILE; + LeaveCriticalSection(&m_limiterCS); + return retval; } -int ServerLevel::runUpdate(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::eRunUpdateThread,m_updateTrigger); - while(ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) - { - m_updateTrigger->WaitForAll(INFINITE); +int ServerLevel::runUpdate(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::eRunUpdateThread, + m_updateTrigger); + while (ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) { + m_updateTrigger->WaitForAll(INFINITE); - if(!ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) break; + if (!ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) + break; - PIXBeginNamedEvent(0,"Updating tiles to be ticked"); - // 4J Stu - Grass and Lava ticks currently take up the majority of all tile updates, so I am limiting them - int grassTicks = 0; - int lavaTicks = 0; - for( unsigned int iLev = 0; iLev < 3; ++iLev ) - { - EnterCriticalSection(&m_updateCS[iLev]); - for( int i = 0; i < m_updateChunkCount[iLev]; i++ ) - { - // 4J - some of these tile ticks will check things in neighbouring tiles, causing chunks to load/create that aren't yet in memory. - // Try and avoid this by limiting the min/max x & z values that we will try and inspect in this chunk according to what surround chunks are loaded - int cx = m_updateChunkX[iLev][i]; - int cz = m_updateChunkZ[iLev][i]; - int minx = 0; - int maxx = 15; - int minz = 0; - int maxz = 15; - if( !m_level[iLev]->hasChunk(cx, cz) ) continue; + PIXBeginNamedEvent(0, "Updating tiles to be ticked"); + // 4J Stu - Grass and Lava ticks currently take up the majority of all + // tile updates, so I am limiting them + int grassTicks = 0; + int lavaTicks = 0; + for (unsigned int iLev = 0; iLev < 3; ++iLev) { + EnterCriticalSection(&m_updateCS[iLev]); + for (int i = 0; i < m_updateChunkCount[iLev]; i++) { + // 4J - some of these tile ticks will check things in + // neighbouring tiles, causing chunks to load/create that aren't + // yet in memory. Try and avoid this by limiting the min/max x & + // z values that we will try and inspect in this chunk according + // to what surround chunks are loaded + int cx = m_updateChunkX[iLev][i]; + int cz = m_updateChunkZ[iLev][i]; + int minx = 0; + int maxx = 15; + int minz = 0; + int maxz = 15; + if (!m_level[iLev]->hasChunk(cx, cz)) continue; - if( !m_level[iLev]->hasChunk(cx + 1, cz + 0) ) { maxx = 11; } - if( !m_level[iLev]->hasChunk(cx + 0, cz + 1) ) { maxz = 11; } - if( !m_level[iLev]->hasChunk(cx - 1, cz + 0) ) { minx = 4; } - if( !m_level[iLev]->hasChunk(cx + 0, cz - 1) ) { minz = 4; } - if( !m_level[iLev]->hasChunk(cx + 1, cz + 1) ) { maxx = 11; maxz = 11; } - if( !m_level[iLev]->hasChunk(cx + 1, cz - 1) ) { maxx = 11; minz = 4; } - if( !m_level[iLev]->hasChunk(cx - 1, cz - 1) ) { minx = 4; minz = 4; } - if( !m_level[iLev]->hasChunk(cx - 1, cz + 1) ) { minx = 4; maxz = 11; } + if (!m_level[iLev]->hasChunk(cx + 1, cz + 0)) { + maxx = 11; + } + if (!m_level[iLev]->hasChunk(cx + 0, cz + 1)) { + maxz = 11; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz + 0)) { + minx = 4; + } + if (!m_level[iLev]->hasChunk(cx + 0, cz - 1)) { + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx + 1, cz + 1)) { + maxx = 11; + maxz = 11; + } + if (!m_level[iLev]->hasChunk(cx + 1, cz - 1)) { + maxx = 11; + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz - 1)) { + minx = 4; + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz + 1)) { + minx = 4; + maxz = 11; + } - LevelChunk *lc = m_level[iLev]->getChunk(cx, cz); + LevelChunk* lc = m_level[iLev]->getChunk(cx, cz); - for (int j = 0; j < 80; j++) - { - // 4jcraft added cast to unsigned - m_randValue[iLev] = (unsigned) m_randValue[iLev] * 3 + (unsigned) m_level[iLev]->addend; - int val = (m_randValue[iLev] >> 2); - int x = (val & 15); - if( ( x < minx ) || ( x > maxx ) ) continue; - int z = ((val >> 8) & 15); - if( ( z < minz ) || ( z > maxz ) ) continue; - int y = ((val >> 16) & (Level::maxBuildHeight - 1)); + for (int j = 0; j < 80; j++) { + // 4jcraft added cast to unsigned + m_randValue[iLev] = (unsigned)m_randValue[iLev] * 3 + + (unsigned)m_level[iLev]->addend; + int val = (m_randValue[iLev] >> 2); + int x = (val & 15); + if ((x < minx) || (x > maxx)) continue; + int z = ((val >> 8) & 15); + if ((z < minz) || (z > maxz)) continue; + int y = ((val >> 16) & (Level::maxBuildHeight - 1)); - // This array access is a cache miss pretty much every time - int id = lc->getTile(x,y,z); - if( m_updateTileCount[iLev] >= MAX_UPDATES ) break; + // This array access is a cache miss pretty much every time + int id = lc->getTile(x, y, z); + if (m_updateTileCount[iLev] >= MAX_UPDATES) break; - // 4J Stu - Grass and Lava ticks currently take up the majority of all tile updates, so I am limiting them - if( (id == Tile::grass_Id && grassTicks >= MAX_GRASS_TICKS) || (id == Tile::calmLava_Id && lavaTicks >= MAX_LAVA_TICKS) ) continue; + // 4J Stu - Grass and Lava ticks currently take up the + // majority of all tile updates, so I am limiting them + if ((id == Tile::grass_Id && + grassTicks >= MAX_GRASS_TICKS) || + (id == Tile::calmLava_Id && + lavaTicks >= MAX_LAVA_TICKS)) + continue; - // 4J Stu - Added shouldTileTick as some tiles won't even do anything if they are set to tick and use up one of our updates - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking() && Tile::tiles[id]->shouldTileTick(m_level[iLev],x + (cx * 16), y, z + (cz * 16) ) ) - { - if(id == Tile::grass_Id) ++grassTicks; - else if(id == Tile::calmLava_Id) ++lavaTicks; - m_updateTileX[iLev][m_updateTileCount[iLev]] = x + (cx * 16); - m_updateTileY[iLev][m_updateTileCount[iLev]] = y; - m_updateTileZ[iLev][m_updateTileCount[iLev]] = z + (cz * 16); + // 4J Stu - Added shouldTileTick as some tiles won't even do + // anything if they are set to tick and use up one of our + // updates + if (Tile::tiles[id] != NULL && + Tile::tiles[id]->isTicking() && + Tile::tiles[id]->shouldTileTick( + m_level[iLev], x + (cx * 16), y, z + (cz * 16))) { + if (id == Tile::grass_Id) + ++grassTicks; + else if (id == Tile::calmLava_Id) + ++lavaTicks; + m_updateTileX[iLev][m_updateTileCount[iLev]] = + x + (cx * 16); + m_updateTileY[iLev][m_updateTileCount[iLev]] = y; + m_updateTileZ[iLev][m_updateTileCount[iLev]] = + z + (cz * 16); - m_updateTileCount[iLev]++; - } - } - } - LeaveCriticalSection(&m_updateCS[iLev]); - } - PIXEndNamedEvent(); + m_updateTileCount[iLev]++; + } + } + } + LeaveCriticalSection(&m_updateCS[iLev]); + } + PIXEndNamedEvent(); #ifdef __PS3__ - Sleep(10); -#endif //__PS3__ - } + Sleep(10); +#endif //__PS3__ + } - ShutdownManager::HasFinished(ShutdownManager::eRunUpdateThread); + ShutdownManager::HasFinished(ShutdownManager::eRunUpdateThread); - return 0; + return 0; } -void ServerLevel::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound) -{ - if( chunkMap ) - { - chunkMap->flagEntitiesToBeRemoved(flags, removedFound); - } +void ServerLevel::flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound) { + if (chunkMap) { + chunkMap->flagEntitiesToBeRemoved(flags, removedFound); + } } diff --git a/Minecraft.Client/Level/ServerLevel.h b/Minecraft.Client/Level/ServerLevel.h index 3605eb195..56b0a9884 100644 --- a/Minecraft.Client/Level/ServerLevel.h +++ b/Minecraft.Client/Level/ServerLevel.h @@ -7,165 +7,193 @@ class Node; class EntityTracker; class PlayerChunkMap; - -class ServerLevel : public Level -{ +class ServerLevel : public Level { private: - static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3; + static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3; - MinecraftServer *server; - EntityTracker *tracker; - PlayerChunkMap *chunkMap; + MinecraftServer* server; + EntityTracker* tracker; + PlayerChunkMap* chunkMap; - CRITICAL_SECTION m_tickNextTickCS; // 4J added - std::set tickNextTickList; // 4J Was TreeSet - std::unordered_set tickNextTickSet; // 4J Was HashSet + CRITICAL_SECTION m_tickNextTickCS; // 4J added + std::set + tickNextTickList; // 4J Was TreeSet + std::unordered_set + tickNextTickSet; // 4J Was HashSet - std::vector m_queuedSendTileUpdates; // 4J added - CRITICAL_SECTION m_csQueueSendTileUpdates; + std::vector m_queuedSendTileUpdates; // 4J added + CRITICAL_SECTION m_csQueueSendTileUpdates; protected: - int saveInterval; + int saveInterval; public: - ServerChunkCache *cache; + ServerChunkCache* cache; bool canEditSpawn; bool noSave; -private: - bool allPlayersSleeping; - int emptyTime; - bool m_bAtLeastOnePlayerSleeping; // 4J Added - static WeighedTreasureArray RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2 - - std::vector tileEvents[2]; - int activeTileEventsList; -public: - static void staticCtor(); - ServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings); - ~ServerLevel(); - void tick(); - Biome::MobSpawnerData *getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z); - void updateSleepingPlayerList(); -protected: - void awakenAllPlayers(); private: - void stopWeather(); + bool allPlayersSleeping; + int emptyTime; + bool m_bAtLeastOnePlayerSleeping; // 4J Added + static WeighedTreasureArray + RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2 + + std::vector tileEvents[2]; + int activeTileEventsList; public: - bool allPlayersAreSleeping(); - void validateSpawn(); + static void staticCtor(); + ServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings); + ~ServerLevel(); + void tick(); + Biome::MobSpawnerData* getRandomMobSpawnAt(MobCategory* mobCategory, int x, + int y, int z); + void updateSleepingPlayerList(); protected: - void tickTiles(); + void awakenAllPlayers(); + +private: + void stopWeather(); public: - void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); - void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); - void tickEntities(); - bool tickPendingTicks(bool force); - std::vector *fetchTicksInChunk(LevelChunk *chunk, bool remove); + bool allPlayersAreSleeping(); + void validateSpawn(); + +protected: + void tickTiles(); + +public: + void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); + void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); + void tickEntities(); + bool tickPendingTicks(bool force); + std::vector* fetchTicksInChunk(LevelChunk* chunk, + bool remove); virtual void tick(std::shared_ptr e, bool actual); void forceTick(std::shared_ptr e, bool actual); - bool AllPlayersAreSleeping() { return allPlayersSleeping;} // 4J added for a message to other players - bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping;} + bool AllPlayersAreSleeping() { + return allPlayersSleeping; + } // 4J added for a message to other players + bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping; } + protected: - ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor + ChunkSource* + createChunkSource(); // 4J - was virtual, but was called from parent ctor public: - std::vector > *getTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); - virtual bool mayInteract(std::shared_ptr player, int xt, int yt, int zt, int id); + std::vector >* getTileEntitiesInRegion( + int x0, int y0, int z0, int x1, int y1, int z1); + virtual bool mayInteract(std::shared_ptr player, int xt, int yt, + int zt, int id); + protected: - virtual void initializeLevel(LevelSettings *settings); - virtual void setInitialSpawn(LevelSettings *settings); - void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2 + virtual void initializeLevel(LevelSettings* settings); + virtual void setInitialSpawn(LevelSettings* settings); + void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2 public: - Pos *getDimensionSpecificSpawn(); + Pos* getDimensionSpecificSpawn(); - void Suspend(); // 4j Added for XboxOne PLM + void Suspend(); // 4j Added for XboxOne PLM - void save(bool force, ProgressListener *progressListener, bool bAutosave=false); - void saveToDisc(ProgressListener *progressListener, bool autosave); // 4J Added + void save(bool force, ProgressListener* progressListener, + bool bAutosave = false); + void saveToDisc(ProgressListener* progressListener, + bool autosave); // 4J Added private: - void saveLevelData(); + void saveLevelData(); - typedef std::unordered_map , IntKeyHash2, IntKeyEq> intEntityMap; - intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing function as this uses + typedef std::unordered_map, IntKeyHash2, + IntKeyEq> + intEntityMap; + intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing + // function as this uses protected: - virtual void entityAdded(std::shared_ptr e); + virtual void entityAdded(std::shared_ptr e); virtual void entityRemoved(std::shared_ptr e); + public: - std::shared_ptr getEntity(int id); + std::shared_ptr getEntity(int id); virtual bool addGlobalEntity(std::shared_ptr e); void broadcastEntityEvent(std::shared_ptr e, uint8_t event); - virtual std::shared_ptr explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks); + virtual std::shared_ptr explode(std::shared_ptr source, + double x, double y, double z, + float r, bool fire, + bool destroyBlocks); virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1); private: - void runTileEvents(); - bool doTileEvent(TileEventData *te); + void runTileEvents(); + bool doTileEvent(TileEventData* te); public: void closeLevelStorage(); + protected: - virtual void tickWeather(); + virtual void tickWeather(); public: - MinecraftServer *getServer(); - EntityTracker *getTracker(); - void setTimeAndAdjustTileTicks(__int64 newTime); - PlayerChunkMap *getChunkMap(); + MinecraftServer* getServer(); + EntityTracker* getTracker(); + void setTimeAndAdjustTileTicks(__int64 newTime); + PlayerChunkMap* getChunkMap(); - void queueSendTileUpdate(int x, int y, int z); // 4J Added + void queueSendTileUpdate(int x, int y, int z); // 4J Added private: - void runQueuedSendTileUpdates();// 4J Added + void runQueuedSendTileUpdates(); // 4J Added - // 4J - added for implementation of finite limit to number of item entities, tnt and falling block entities + // 4J - added for implementation of finite limit to number of item entities, + // tnt and falling block entities public: + static const int MAX_HANGING_ENTITIES = 400; + static const int MAX_ITEM_ENTITIES = 200; + static const int MAX_ARROW_ENTITIES = 200; + static const int MAX_EXPERIENCEORB_ENTITIES = 50; + static const int MAX_PRIMED_TNT = 20; + static const int MAX_FALLING_TILE = 20; - static const int MAX_HANGING_ENTITIES = 400; - static const int MAX_ITEM_ENTITIES = 200; - static const int MAX_ARROW_ENTITIES = 200; - static const int MAX_EXPERIENCEORB_ENTITIES = 50; - static const int MAX_PRIMED_TNT = 20; - static const int MAX_FALLING_TILE = 20; + int m_primedTntCount; + int m_fallingTileCount; + CRITICAL_SECTION m_limiterCS; + std::list > m_itemEntities; + std::list > m_hangingEntities; + std::list > m_arrowEntities; + std::list > m_experienceOrbEntities; - int m_primedTntCount; - int m_fallingTileCount; - CRITICAL_SECTION m_limiterCS; - std::list< std::shared_ptr > m_itemEntities; - std::list< std::shared_ptr > m_hangingEntities; - std::list< std::shared_ptr > m_arrowEntities; - std::list< std::shared_ptr > m_experienceOrbEntities; + virtual bool addEntity(std::shared_ptr e); + void entityAddedExtra(std::shared_ptr e); + void entityRemovedExtra(std::shared_ptr e); - virtual bool addEntity(std::shared_ptr e); - void entityAddedExtra(std::shared_ptr e); - void entityRemovedExtra(std::shared_ptr e); - - virtual bool newPrimedTntAllowed(); - virtual bool newFallingTileAllowed(); + virtual bool newPrimedTntAllowed(); + virtual bool newFallingTileAllowed(); - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added - // 4J added - static const int MAX_UPDATES = 256; + // 4J added + static const int MAX_UPDATES = 256; - // Each of these need to be duplicated for each level in the current game. As we currently only have 2 (over/nether), making this constant - static Level *m_level[3]; - static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; - static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; - static int m_updateChunkCount[3]; - static int m_updateTileX[3][MAX_UPDATES]; - static int m_updateTileY[3][MAX_UPDATES]; - static int m_updateTileZ[3][MAX_UPDATES]; - static int m_updateTileCount[3]; - static int m_randValue[3]; + // Each of these need to be duplicated for each level in the current game. + // As we currently only have 2 (over/nether), making this constant + static Level* m_level[3]; + static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; + static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; + static int m_updateChunkCount[3]; + static int m_updateTileX[3][MAX_UPDATES]; + static int m_updateTileY[3][MAX_UPDATES]; + static int m_updateTileZ[3][MAX_UPDATES]; + static int m_updateTileCount[3]; + static int m_randValue[3]; - static C4JThread::EventArray* m_updateTrigger; - static CRITICAL_SECTION m_updateCS[3]; - - static C4JThread* m_updateThread; - static int runUpdate(void* lpParam); + static C4JThread::EventArray* m_updateTrigger; + static CRITICAL_SECTION m_updateCS[3]; + static C4JThread* m_updateThread; + static int runUpdate(void* lpParam); }; diff --git a/Minecraft.Client/Level/ServerLevelListener.cpp b/Minecraft.Client/Level/ServerLevelListener.cpp index 6705a16fe..0440f6dbc 100644 --- a/Minecraft.Client/Level/ServerLevelListener.cpp +++ b/Minecraft.Client/Level/ServerLevelListener.cpp @@ -11,116 +11,120 @@ #include "../../Minecraft.World/Headers/net.minecraft.network.packet.h" #include "../../Minecraft.World/Level/LevelData.h" - -ServerLevelListener::ServerLevelListener(MinecraftServer *server, ServerLevel *level) -{ - this->server = server; - this->level = level; +ServerLevelListener::ServerLevelListener(MinecraftServer* server, + ServerLevel* level) { + this->server = server; + this->level = level; } -// 4J removed - +// 4J removed - /* -void ServerLevelListener::addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) +void ServerLevelListener::addParticle(const std::wstring& name, double x, double +y, double z, double xa, double ya, double za) { } */ -void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za) -{ +void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y, + double z, double xa, double ya, + double za) {} + +void ServerLevelListener::allChanged() {} + +void ServerLevelListener::entityAdded(std::shared_ptr entity) { + MemSect(10); + level->getTracker()->addEntity(entity); + MemSect(0); } -void ServerLevelListener::allChanged() -{ -} - -void ServerLevelListener::entityAdded(std::shared_ptr entity) -{ - MemSect(10); - level->getTracker()->addEntity(entity); - MemSect(0); -} - -void ServerLevelListener::entityRemoved(std::shared_ptr entity) -{ - level->getTracker()->removeEntity(entity); +void ServerLevelListener::entityRemoved(std::shared_ptr entity) { + level->getTracker()->removeEntity(entity); } // 4J added -void ServerLevelListener::playerRemoved(std::shared_ptr entity) -{ - std::shared_ptr player = std::dynamic_pointer_cast(entity); - player->getLevel()->getTracker()->removePlayer(entity); +void ServerLevelListener::playerRemoved(std::shared_ptr entity) { + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + player->getLevel()->getTracker()->removePlayer(entity); } -void ServerLevelListener::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) -{ - if(iSound < 0) - { - app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); - } - else - { - // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. - // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - server->getPlayers()->broadcast(x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); - } +void ServerLevelListener::playSound(int iSound, double x, double y, double z, + float volume, float pitch, + float fClipSoundDist) { + if (iSound < 0) { + app.DebugPrintf( + "ServerLevelListener received request for sound less than 0, so " + "ignoring\n"); + } else { + // 4J-PB - I don't want to broadcast player sounds to my local machine, + // since we're already playing these in the LevelRenderer::playSound. + // The PC version does seem to do this and the result is I can stop + // walking , and then I'll hear my footstep sound with a delay + server->getPlayers()->broadcast( + x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, + std::shared_ptr( + new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + } } -void ServerLevelListener::playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) -{ - if(iSound < 0) - { - app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); - } - else - { - // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. - // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - std::shared_ptr player= std::dynamic_pointer_cast(entity); - server->getPlayers()->broadcast(player,x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); - } +void ServerLevelListener::playSound(std::shared_ptr entity, int iSound, + double x, double y, double z, float volume, + float pitch, float fClipSoundDist) { + if (iSound < 0) { + app.DebugPrintf( + "ServerLevelListener received request for sound less than 0, so " + "ignoring\n"); + } else { + // 4J-PB - I don't want to broadcast player sounds to my local machine, + // since we're already playing these in the LevelRenderer::playSound. + // The PC version does seem to do this and the result is I can stop + // walking , and then I'll hear my footstep sound with a delay + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + server->getPlayers()->broadcast( + player, x, y, z, volume > 1 ? 16 * volume : 16, + level->dimension->id, + std::shared_ptr( + new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + } } -void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) -{ +void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1, + int z1, Level* level) {} + +void ServerLevelListener::skyColorChanged() {} + +void ServerLevelListener::tileChanged(int x, int y, int z) { + level->getChunkMap()->tileChanged(x, y, z); } -void ServerLevelListener::skyColorChanged() -{ +void ServerLevelListener::tileLightChanged(int x, int y, int z) {} + +void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x, + int y, int z) {} + +void ServerLevelListener::levelEvent(std::shared_ptr source, int type, + int x, int y, int z, int data) { + server->getPlayers()->broadcast( + source, x, y, z, 64, level->dimension->id, + std::shared_ptr( + new LevelEventPacket(type, x, y, z, data))); } -void ServerLevelListener::tileChanged(int x, int y, int z) -{ - level->getChunkMap()->tileChanged(x, y, z); -} +void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, + int progress) { + // for (ServerPlayer p : server->getPlayers()->players) + for (AUTO_VAR(it, server->getPlayers()->players.begin()); + it != server->getPlayers()->players.end(); ++it) { + std::shared_ptr p = *it; + if (p == NULL || p->level != level || p->entityId == id) continue; + double xd = (double)x - p->x; + double yd = (double)y - p->y; + double zd = (double)z - p->z; -void ServerLevelListener::tileLightChanged(int x, int y, int z) -{ -} - -void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x, int y, int z) -{ -} - -void ServerLevelListener::levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) -{ - server->getPlayers()->broadcast(source, x, y, z, 64, level->dimension->id, std::shared_ptr( new LevelEventPacket(type, x, y, z, data) ) ); -} - -void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, int progress) -{ - //for (ServerPlayer p : server->getPlayers()->players) - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) - { - std::shared_ptr p = *it; - if (p == NULL || p->level != level || p->entityId == id) continue; - double xd = (double) x - p->x; - double yd = (double) y - p->y; - double zd = (double) z - p->z; - - if (xd * xd + yd * yd + zd * zd < 32 * 32) - { - p->connection->send(std::shared_ptr(new TileDestructionPacket(id, x, y, z, progress))); - } - } + if (xd * xd + yd * yd + zd * zd < 32 * 32) { + p->connection->send(std::shared_ptr( + new TileDestructionPacket(id, x, y, z, progress))); + } + } } \ No newline at end of file diff --git a/Minecraft.Client/Level/ServerLevelListener.h b/Minecraft.Client/Level/ServerLevelListener.h index d5ba2cbc2..6212df1b1 100644 --- a/Minecraft.Client/Level/ServerLevelListener.h +++ b/Minecraft.Client/Level/ServerLevelListener.h @@ -7,27 +7,37 @@ class MinecraftServer; class ServerLevel; // 4J - renamed class to ServerLevelListener to avoid clash with LevelListener -class ServerLevelListener : public LevelListener -{ +class ServerLevelListener : public LevelListener { private: - MinecraftServer *server; - ServerLevel *level; + MinecraftServer* server; + ServerLevel* level; public: - ServerLevelListener(MinecraftServer *server, ServerLevel *level); - // 4J removed - virtual void addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za); - virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za); // 4J added + ServerLevelListener(MinecraftServer* server, ServerLevel* level); + // 4J removed - virtual void addParticle(const std::wstring& name, double x, + // double y, double z, double xa, double ya, double za); + virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, + double xa, double ya, double za); // 4J added virtual void allChanged(); virtual void entityAdded(std::shared_ptr entity); virtual void entityRemoved(std::shared_ptr entity); - virtual void playerRemoved(std::shared_ptr entity); // 4J added - for when a player is removed from the level's player array, not just the entity storage - virtual void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); - virtual void playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); - virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param + virtual void playerRemoved( + std::shared_ptr + entity); // 4J added - for when a player is removed from the + // level's player array, not just the entity storage + virtual void playSound(int iSound, double x, double y, double z, + float volume, float pitch, float fClipSoundDist); + virtual void playSound(std::shared_ptr entity, int iSound, double x, + double y, double z, float volume, float pitch, + float fClipSoundDist); + virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param virtual void skyColorChanged(); virtual void tileChanged(int x, int y, int z); - virtual void tileLightChanged(int x, int y, int z); - virtual void playStreamingMusic(const std::wstring& name, int x, int y, int z); - virtual void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data); - virtual void destroyTileProgress(int id, int x, int y, int z, int progress); + virtual void tileLightChanged(int x, int y, int z); + virtual void playStreamingMusic(const std::wstring& name, int x, int y, + int z); + virtual void levelEvent(std::shared_ptr source, int type, int x, + int y, int z, int data); + virtual void destroyTileProgress(int id, int x, int y, int z, int progress); }; diff --git a/Minecraft.Client/Linux/LinuxGL.h b/Minecraft.Client/Linux/LinuxGL.h index ccdf4553f..2d8ab33fb 100644 --- a/Minecraft.Client/Linux/LinuxGL.h +++ b/Minecraft.Client/Linux/LinuxGL.h @@ -9,31 +9,31 @@ class FloatBuffer; class IntBuffer; class ByteBuffer; -void glGenTextures(IntBuffer *); +void glGenTextures(IntBuffer*); int glGenTextures(); -void glDeleteTextures(IntBuffer *); -void glLight(int, int, FloatBuffer *); -void glLightModel(int, FloatBuffer *); -void glGetFloat(int a, FloatBuffer *b); +void glDeleteTextures(IntBuffer*); +void glLight(int, int, FloatBuffer*); +void glLightModel(int, FloatBuffer*); +void glGetFloat(int a, FloatBuffer* b); void glTexCoordPointer(int, int, int, int); -void glTexCoordPointer(int, int, FloatBuffer *); +void glTexCoordPointer(int, int, FloatBuffer*); void glNormalPointer(int, int, int); -void glNormalPointer(int, ByteBuffer *); -void glColorPointer(int, bool, int, ByteBuffer *); +void glNormalPointer(int, ByteBuffer*); +void glColorPointer(int, bool, int, ByteBuffer*); void glColorPointer(int, int, int, int); void glVertexPointer(int, int, int, int); -void glVertexPointer(int, int, FloatBuffer *); +void glVertexPointer(int, int, FloatBuffer*); void glNewList(int, int); void glEndList(int vertexCount = 0); -void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer *); -void glCallLists(IntBuffer *); -void glGenQueriesARB(IntBuffer *); +void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer*); +void glCallLists(IntBuffer*); +void glGenQueriesARB(IntBuffer*); void glBeginQueryARB(int, int); void glEndQueryARB(int); -void glGetQueryObjectuARB(int, int, IntBuffer *); -void glFog(int, FloatBuffer *); -void glTexGen(int, int, FloatBuffer *); -void glReadPixels(int, int, int, int, int, int, ByteBuffer *); +void glGetQueryObjectuARB(int, int, IntBuffer*); +void glFog(int, FloatBuffer*); +void glTexGen(int, int, FloatBuffer*); +void glReadPixels(int, int, int, int, int, int, ByteBuffer*); void glTexGeni(int, int, int); void glMultiTexCoord2f(int, float, float); void glClientActiveTexture(int); diff --git a/Minecraft.Client/Minecraft.cpp b/Minecraft.Client/Minecraft.cpp index d91d0cb4b..96aaafbbd 100644 --- a/Minecraft.Client/Minecraft.cpp +++ b/Minecraft.Client/Minecraft.cpp @@ -73,15 +73,17 @@ #include "Platform/Orbis/Network/PsPlusUpsellWrapper_Orbis.h" #endif -// 4J Turning this on will change the graph at the bottom of the debug overlay to show the number of packets of each type added per fram -//#define DEBUG_RENDER_SHOWS_PACKETS 1 -//#define SPLITSCREEN_TEST +// 4J Turning this on will change the graph at the bottom of the debug overlay +// to show the number of packets of each type added per fram +// #define DEBUG_RENDER_SHOWS_PACKETS 1 +// #define SPLITSCREEN_TEST -// If not disabled, this creates an event queue on a seperate thread so that the Level::tick calls can be offloaded -// from the main thread, and have longer to run, since it's called at 20Hz instead of 60 +// If not disabled, this creates an event queue on a seperate thread so that the +// Level::tick calls can be offloaded from the main thread, and have longer to +// run, since it's called at 20Hz instead of 60 #define DISABLE_LEVELTICK_THREAD -Minecraft *Minecraft::m_instance = NULL; +Minecraft* Minecraft::m_instance = NULL; __int64 Minecraft::frameTimes[512]; __int64 Minecraft::tickTimes[512]; int Minecraft::frameTimePos = 0; @@ -90,161 +92,154 @@ File Minecraft::workDir = File(L""); #ifdef __PSVITA__ -TOUCHSCREENRECT QuickSelectRect[3]= -{ - { 560, 890, 1360, 980 }, - { 450, 840, 1449, 960 }, - { 320, 840, 1600, 970 }, +TOUCHSCREENRECT QuickSelectRect[3] = { + {560, 890, 1360, 980}, + {450, 840, 1449, 960}, + {320, 840, 1600, 970}, }; -int QuickSelectBoxWidth[3]= -{ - 89, - 111, - 142 -}; +int QuickSelectBoxWidth[3] = {89, 111, 142}; #endif -Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen) -{ - // 4J - added this block of initialisers - gameMode = NULL; - hasCrashed = false; - timer = new Timer(SharedConstants::TICKS_PER_SECOND); - oldLevel = NULL; //4J Stu added - level = NULL; - levels = MultiPlayerLevelArray(3); // 4J Added - levelRenderer = NULL; - player = nullptr; - cameraTargetPlayer = nullptr; - particleEngine = NULL; - user = NULL; - parent = NULL; - pause = false; - textures = NULL; - font = NULL; - screen = NULL; - localPlayerIdx = 0; - rightClickDelay = 0; +Minecraft::Minecraft(Component* mouseComponent, Canvas* parent, + MinecraftApplet* minecraftApplet, int width, int height, + bool fullscreen) { + // 4J - added this block of initialisers + gameMode = NULL; + hasCrashed = false; + timer = new Timer(SharedConstants::TICKS_PER_SECOND); + oldLevel = NULL; // 4J Stu added + level = NULL; + levels = MultiPlayerLevelArray(3); // 4J Added + levelRenderer = NULL; + player = nullptr; + cameraTargetPlayer = nullptr; + particleEngine = NULL; + user = NULL; + parent = NULL; + pause = false; + textures = NULL; + font = NULL; + screen = NULL; + localPlayerIdx = 0; + rightClickDelay = 0; - // 4J Stu Added - InitializeCriticalSection( &ProgressRenderer::s_progress ); - InitializeCriticalSection(&m_setLevelCS); - //m_hPlayerRespawned = CreateEvent(NULL, FALSE, FALSE, NULL); + // 4J Stu Added + InitializeCriticalSection(&ProgressRenderer::s_progress); + InitializeCriticalSection(&m_setLevelCS); + // m_hPlayerRespawned = CreateEvent(NULL, FALSE, FALSE, NULL); - progressRenderer = NULL; - gameRenderer = NULL; - bgLoader = NULL; + progressRenderer = NULL; + gameRenderer = NULL; + bgLoader = NULL; - ticks = 0; - // 4J-PB - moved into the local player - //missTime = 0; - //lastClickTick = 0; - //isRaining = false; - // 4J-PB - end + ticks = 0; + // 4J-PB - moved into the local player + // missTime = 0; + // lastClickTick = 0; + // isRaining = false; + // 4J-PB - end - orgWidth = orgHeight = 0; - achievementPopup = new AchievementPopup(this); - gui = NULL; - noRender = false; - humanoidModel = new HumanoidModel(0); - hitResult = 0; - options = NULL; - soundEngine = new SoundEngine(); - mouseHandler = NULL; - skins = NULL; - workingDirectory = File(L""); - levelSource = NULL; - stats[0] = NULL; - stats[1] = NULL; - stats[2] = NULL; - stats[3] = NULL; - connectToPort = 0; - workDir = File(L""); - // 4J removed - //wasDown = false; - lastTimer = -1; + orgWidth = orgHeight = 0; + achievementPopup = new AchievementPopup(this); + gui = NULL; + noRender = false; + humanoidModel = new HumanoidModel(0); + hitResult = 0; + options = NULL; + soundEngine = new SoundEngine(); + mouseHandler = NULL; + skins = NULL; + workingDirectory = File(L""); + levelSource = NULL; + stats[0] = NULL; + stats[1] = NULL; + stats[2] = NULL; + stats[3] = NULL; + connectToPort = 0; + workDir = File(L""); + // 4J removed + // wasDown = false; + lastTimer = -1; - // 4J removed - //lastTickTime = System::currentTimeMillis(); - recheckPlayerIn = 0; - running = true; - unoccupiedQuadrant = -1; + // 4J removed + // lastTickTime = System::currentTimeMillis(); + recheckPlayerIn = 0; + running = true; + unoccupiedQuadrant = -1; - Stats::init(); + Stats::init(); - orgHeight = height; - this->fullscreen = fullscreen; - this->minecraftApplet = NULL; + orgHeight = height; + this->fullscreen = fullscreen; + this->minecraftApplet = NULL; - this->parent = parent; - // 4J - Our actual physical frame buffer is always 1280x720 ie in a 16:9 ratio. If we want to do a 4:3 mode, we are telling the original minecraft code - // that the width is 3/4 what it actually is, to correctly present a 4:3 image. Have added width_phys and height_phys for any code we add that requires - // to know the real physical dimensions of the frame buffer. - if( RenderManager.IsWidescreen() ) - { - this->width = width; - } - else - { - this->width = (width * 3 ) / 4; - } - this->height = height; - this->width_phys = width; - this->height_phys = height; + this->parent = parent; + // 4J - Our actual physical frame buffer is always 1280x720 ie in a 16:9 + // ratio. If we want to do a 4:3 mode, we are telling the original minecraft + // code that the width is 3/4 what it actually is, to correctly present a + // 4:3 image. Have added width_phys and height_phys for any code we add that + // requires to know the real physical dimensions of the frame buffer. + if (RenderManager.IsWidescreen()) { + this->width = width; + } else { + this->width = (width * 3) / 4; + } + this->height = height; + this->width_phys = width; + this->height_phys = height; - this->fullscreen = fullscreen; + this->fullscreen = fullscreen; - appletMode = false; + appletMode = false; - Minecraft::m_instance = this; - TextureManager::createInstance(); + Minecraft::m_instance = this; + TextureManager::createInstance(); - for(int i=0;isoundEngine->init(NULL); + this->soundEngine->init(NULL); #endif #ifndef DISABLE_LEVELTICK_THREAD - levelTickEventQueue = new C4JThread::EventQueue(levelTickUpdateFunc, levelTickThreadInitFunc, "LevelTick_EventQueuePoll"); - levelTickEventQueue->setProcessor(3); - levelTickEventQueue->setPriority(THREAD_PRIORITY_NORMAL); -#endif // DISABLE_LEVELTICK_THREAD + levelTickEventQueue = + new C4JThread::EventQueue(levelTickUpdateFunc, levelTickThreadInitFunc, + "LevelTick_EventQueuePoll"); + levelTickEventQueue->setProcessor(3); + levelTickEventQueue->setPriority(THREAD_PRIORITY_NORMAL); +#endif // DISABLE_LEVELTICK_THREAD } -void Minecraft::clearConnectionFailed() -{ - for(int i=0;iaddDebugPacks(); - textures = new Textures(skins, options); - //renderLoadingScreen(); + workingDirectory = getWorkingDirectory(); + levelSource = + new McRegionLevelStorageSource(File(workingDirectory, L"saves")); + // levelSource = new MemoryLevelStorageSource(); + options = new Options(this, workingDirectory); + skins = new TexturePackRepository(workingDirectory, this); + skins->addDebugPacks(); + textures = new Textures(skins, options); + // renderLoadingScreen(); - font = new Font(options, L"font/Default.png", textures, false, TN_DEFAULT_FONT, 23, 20, 8, 8, SFontData::Codepoints); - altFont = new Font(options, L"font/alternate.png", textures, false, TN_ALT_FONT, 16, 16, 8, 8); + font = new Font(options, L"font/Default.png", textures, false, + TN_DEFAULT_FONT, 23, 20, 8, 8, SFontData::Codepoints); + altFont = new Font(options, L"font/alternate.png", textures, false, + TN_ALT_FONT, 16, 16, 8, 8); - //if (options.languageCode != null) { - // Language.getInstance().loadLanguage(options.languageCode); - // // font.setEnforceUnicodeSheet("true".equalsIgnoreCase(I18n.get("language.enforceUnicode"))); - // font.setEnforceUnicodeSheet(Language.getInstance().isSelectedLanguageIsUnicode()); - // font.setBidirectional(Language.isBidirectional(options.languageCode)); - //} + // if (options.languageCode != null) { + // Language.getInstance().loadLanguage(options.languageCode); + // // + //font.setEnforceUnicodeSheet("true".equalsIgnoreCase(I18n.get("language.enforceUnicode"))); + // font.setEnforceUnicodeSheet(Language.getInstance().isSelectedLanguageIsUnicode()); + // font.setBidirectional(Language.isBidirectional(options.languageCode)); + // } - // 4J Stu - Not using these any more - //WaterColor::init(textures->loadTexturePixels(L"misc/watercolor.png")); - //GrassColor::init(textures->loadTexturePixels(L"misc/grasscolor.png")); - //FoliageColor::init(textures->loadTexturePixels(L"misc/foliagecolor.png")); + // 4J Stu - Not using these any more + // WaterColor::init(textures->loadTexturePixels(L"misc/watercolor.png")); + // GrassColor::init(textures->loadTexturePixels(L"misc/grasscolor.png")); + // FoliageColor::init(textures->loadTexturePixels(L"misc/foliagecolor.png")); - gameRenderer = new GameRenderer(this); - EntityRenderDispatcher::instance->itemInHandRenderer = new ItemInHandRenderer(this,false); + gameRenderer = new GameRenderer(this); + EntityRenderDispatcher::instance->itemInHandRenderer = + new ItemInHandRenderer(this, false); - for( int i=0 ; i<4 ; ++i ) - stats[i] = new StatsCounter(); + for (int i = 0; i < 4; ++i) stats[i] = new StatsCounter(); - /* 4J - TODO, 4J-JEV: Unnecessary. - Achievements::openInventory->setDescFormatter(NULL); - Achievements.openInventory.setDescFormatter(new DescFormatter(){ - public String format(String i18nValue) { - return String.format(i18nValue, Keyboard.getKeyName(options.keyBuild.key)); - } - }); - */ + /* 4J - TODO, 4J-JEV: Unnecessary. + Achievements::openInventory->setDescFormatter(NULL); + Achievements.openInventory.setDescFormatter(new DescFormatter(){ + public String format(String i18nValue) { + return String.format(i18nValue, Keyboard.getKeyName(options.keyBuild.key)); + } + }); + */ - // 4J-PB - We'll do this in a xui intro - //renderLoadingScreen(); + // 4J-PB - We'll do this in a xui intro + // renderLoadingScreen(); - //Keyboard::create(); - Mouse::create(); -#if 0 // 4J - removed + // Keyboard::create(); + Mouse::create(); +#if 0 // 4J - removed mouseHandler = new MouseHandler(parent); try { Controllers.create(); @@ -364,295 +363,281 @@ void Minecraft::init() } #endif - MemSect(31); - checkGlError(L"Pre startup"); - MemSect(0); + MemSect(31); + checkGlError(L"Pre startup"); + MemSect(0); - // width = Display.getDisplayMode().getWidth(); - // height = Display.getDisplayMode().getHeight(); + // width = Display.getDisplayMode().getWidth(); + // height = Display.getDisplayMode().getHeight(); - glEnable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); - glClearDepth(1.0); - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.1f); - glCullFace(GL_BACK); + glEnable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); + glClearDepth(1.0); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.1f); + glCullFace(GL_BACK); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - MemSect(31); - checkGlError(L"Startup"); - MemSect(0); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + MemSect(31); + checkGlError(L"Startup"); + MemSect(0); - // openGLCapabilities = new OpenGLCapabilities(); // 4J - removed + // openGLCapabilities = new OpenGLCapabilities(); // 4J - removed - levelRenderer = new LevelRenderer(this, textures); - textures->stitch(); + levelRenderer = new LevelRenderer(this, textures); + textures->stitch(); - glViewport(0, 0, width, height); + glViewport(0, 0, width, height); - particleEngine = new ParticleEngine(level, textures); - // try { // 4J - removed try/catch - bgLoader = new BackgroundDownloader(workingDirectory, this); - bgLoader->start(); - // } catch (Exception e) { - // } + particleEngine = new ParticleEngine(level, textures); + // try { // 4J - removed try/catch + bgLoader = new BackgroundDownloader(workingDirectory, this); + bgLoader->start(); + // } catch (Exception e) { + // } - MemSect(31); - checkGlError(L"Post startup"); - MemSect(0); - gui = new Gui(this); + MemSect(31); + checkGlError(L"Post startup"); + MemSect(0); + gui = new Gui(this); - if (connectToIp != L"") // 4J - was NULL comparison - { - // setScreen(new ConnectScreen(this, connectToIp, connectToPort)); // 4J TODO - put back in - } - else - { - setScreen(new TitleScreen()); - } - progressRenderer = new ProgressRenderer(this); + if (connectToIp != L"") // 4J - was NULL comparison + { + // setScreen(new ConnectScreen(this, connectToIp, + // connectToPort)); // 4J TODO - put back in + } else { + setScreen(new TitleScreen()); + } + progressRenderer = new ProgressRenderer(this); - RenderManager.CBuffLockStaticCreations(); + RenderManager.CBuffLockStaticCreations(); } -void Minecraft::renderLoadingScreen() -{ - // 4J Unused - // testing stuff on vita just now +void Minecraft::renderLoadingScreen() { + // 4J Unused + // testing stuff on vita just now #ifdef __PSVITA__ - ScreenSizeCalculator ssc(options, width, height); + ScreenSizeCalculator ssc(options, width, height); - // xxx - RenderManager.StartFrame(); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); - glViewport(0, 0, width, height); - glClearColor(0, 0, 0, 0); + // xxx + RenderManager.StartFrame(); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); + glViewport(0, 0, width, height); + glClearColor(0, 0, 0, 0); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - glDisable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); - glDisable(GL_FOG); - // xxx - glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_MOB_PIG)); - t->begin(); - t->color(0xffffff); - t->vertexUV((float)(0), (float)( height), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(width), (float)( height), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(width), (float)( 0), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(0), (float)( 0), (float)( 0), (float)( 0), (float)( 0)); - t->end(); + glDisable(GL_LIGHTING); + glEnable(GL_TEXTURE_2D); + glDisable(GL_FOG); + // xxx + glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_MOB_PIG)); + t->begin(); + t->color(0xffffff); + t->vertexUV((float)(0), (float)(height), (float)(0), (float)(0), + (float)(0)); + t->vertexUV((float)(width), (float)(height), (float)(0), (float)(0), + (float)(0)); + t->vertexUV((float)(width), (float)(0), (float)(0), (float)(0), (float)(0)); + t->vertexUV((float)(0), (float)(0), (float)(0), (float)(0), (float)(0)); + t->end(); - int lw = 256; - int lh = 256; - glColor4f(1, 1, 1, 1); - t->color(0xffffff); - blit((ssc.getWidth() - lw) / 2, (ssc.getHeight() - lh) / 2, 0, 0, lw, lh); - glDisable(GL_LIGHTING); - glDisable(GL_FOG); + int lw = 256; + int lh = 256; + glColor4f(1, 1, 1, 1); + t->color(0xffffff); + blit((ssc.getWidth() - lw) / 2, (ssc.getHeight() - lh) / 2, 0, 0, lw, lh); + glDisable(GL_LIGHTING); + glDisable(GL_FOG); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.1f); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.1f); - Display::swapBuffers(); - // xxx - RenderManager.Present(); + Display::swapBuffers(); + // xxx + RenderManager.Present(); #endif } -void Minecraft::blit(int x, int y, int sx, int sy, int w, int h) -{ - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertexUV((float)(x + 0), (float)( y + h), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + h), (float)( 0), (float)( (sx + w) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + 0), (float)( 0), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); - t->vertexUV((float)(x + 0), (float)( y + 0), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); - t->end(); +void Minecraft::blit(int x, int y, int sx, int sy, int w, int h) { + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(0), + (float)((sx + 0) * us), (float)((sy + h) * vs)); + t->vertexUV((float)(x + w), (float)(y + h), (float)(0), + (float)((sx + w) * us), (float)((sy + h) * vs)); + t->vertexUV((float)(x + w), (float)(y + 0), (float)(0), + (float)((sx + w) * us), (float)((sy + 0) * vs)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(0), + (float)((sx + 0) * us), (float)((sy + 0) * vs)); + t->end(); } -File Minecraft::getWorkingDirectory() -{ - if (workDir.getPath().empty()) workDir = getWorkingDirectory(L"4jcraft"); - return workDir; +File Minecraft::getWorkingDirectory() { + if (workDir.getPath().empty()) workDir = getWorkingDirectory(L"4jcraft"); + return workDir; } -File Minecraft::getWorkingDirectory(const std::wstring& applicationName) -{ - // 4J - original version - // 4jcraft: ported to C++ - std::wstring userHome = convStringToWstring(getenv("HOME")); - File *workingDirectory; +File Minecraft::getWorkingDirectory(const std::wstring& applicationName) { + // 4J - original version + // 4jcraft: ported to C++ + std::wstring userHome = convStringToWstring(getenv("HOME")); + File* workingDirectory; #if defined(__linux__) - workingDirectory = new File(userHome, L'.' + applicationName + L'/'); + workingDirectory = new File(userHome, L'.' + applicationName + L'/'); #elif defined(_WINDOWS64) - std::string applicationData = getenv("APPDATA"); - if (!applicationData.empty()) - { - workingDirectory = new File(convStringToWstring(applicationData), L'.' + applicationName + L'/'); - } - else - { - workingDirectory = new File(userHome, L'.' + applicationName + L'/'); - } -//#elif defined(_MACOS) -// workingDirectory = new File(userHome, "Library/Application Support/" + applicationName); + std::string applicationData = getenv("APPDATA"); + if (!applicationData.empty()) { + workingDirectory = new File(convStringToWstring(applicationData), + L'.' + applicationName + L'/'); + } else { + workingDirectory = new File(userHome, L'.' + applicationName + L'/'); + } +// #elif defined(_MACOS) +// workingDirectory = new File(userHome, "Library/Application +//Support/" + applicationName); #else - workingDirectory = new File(userHome, applicationName + L'/'); + workingDirectory = new File(userHome, applicationName + L'/'); #endif - if (!workingDirectory->exists()){ - if (!workingDirectory->mkdirs()) { - app.DebugPrintf("The working directory could not be created"); - assert(0); - //throw new RuntimeException(L"The working directory could not be created: " + workingDirectory); - } - } - return *workingDirectory; + if (!workingDirectory->exists()) { + if (!workingDirectory->mkdirs()) { + app.DebugPrintf("The working directory could not be created"); + assert(0); + // throw new RuntimeException(L"The working directory could not be + // created: " + workingDirectory); + } + } + return *workingDirectory; } -LevelStorageSource *Minecraft::getLevelSource() -{ - return levelSource; +LevelStorageSource* Minecraft::getLevelSource() { return levelSource; } + +void Minecraft::setScreen(Screen* screen) { + if (dynamic_cast(this->screen) != NULL) return; + + if (this->screen != NULL) { + this->screen->removed(); + } + + // 4J Gordon: Do not force a stats save here + /*if (dynamic_cast(screen)!=NULL) + { + stats->forceSend(); + } + stats->forceSave();*/ + + if (screen == NULL && level == NULL) { + screen = new TitleScreen(); + } else if (player != NULL && !ui.GetMenuDisplayed(player->GetXboxPad()) && + player->getHealth() <= 0) { + // screen = new DeathScreen(); + + // 4J Stu - If we exit from the death screen then we are saved as being + // dead. In the Java game when you load the game you are still dead, but + // this is silly so only show the dead screen if we have died during + // gameplay + if (ticks == 0) { + player->respawn(); + } else { + ui.NavigateToScene(player->GetXboxPad(), eUIScene_DeathMenu, NULL); + } + } + + if (dynamic_cast(screen) != NULL) { + options->renderDebug = false; + gui->clearMessages(); + } + + this->screen = screen; + if (screen != NULL) { + // releaseMouse(); // 4J - removed + ScreenSizeCalculator ssc(options, width, height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + screen->init(this, screenWidth, screenHeight); + noRender = false; + } else { + // grabMouse(); // 4J - removed + } + + // 4J-PB - if a screen has been set, go into menu mode + // it's possible that player doesn't exist here yet + /*if(screen!=NULL) + { + if(player && player->GetXboxPad()!=-1) + { + InputManager.SetMenuDisplayed(player->GetXboxPad(),true); + } + else + { + // set all + //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,true); + } + } + else + { + if(player && player->GetXboxPad()!=-1) + { + InputManager.SetMenuDisplayed(player->GetXboxPad(),false); + } + else + { + //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,false); + } + }*/ } -void Minecraft::setScreen(Screen *screen) -{ - if( dynamic_cast(this->screen) != NULL ) return; - - if (this->screen != NULL) - { - this->screen->removed(); - } - - //4J Gordon: Do not force a stats save here - /*if (dynamic_cast(screen)!=NULL) - { - stats->forceSend(); - } - stats->forceSave();*/ - - if (screen == NULL && level == NULL) - { - screen = new TitleScreen(); - } - else if (player != NULL && !ui.GetMenuDisplayed(player->GetXboxPad()) && player->getHealth() <= 0) - { - //screen = new DeathScreen(); - - // 4J Stu - If we exit from the death screen then we are saved as being dead. In the Java - // game when you load the game you are still dead, but this is silly so only show the dead - // screen if we have died during gameplay - if(ticks==0) - { - player->respawn(); - } - else - { - ui.NavigateToScene(player->GetXboxPad(),eUIScene_DeathMenu,NULL); - } - } - - if (dynamic_cast(screen)!=NULL) - { - options->renderDebug = false; - gui->clearMessages(); - } - - this->screen = screen; - if (screen != NULL) - { - // releaseMouse(); // 4J - removed - ScreenSizeCalculator ssc(options, width, height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - screen->init(this, screenWidth, screenHeight); - noRender = false; - } - else - { - // grabMouse(); // 4J - removed - } - - // 4J-PB - if a screen has been set, go into menu mode - // it's possible that player doesn't exist here yet - /*if(screen!=NULL) - { - if(player && player->GetXboxPad()!=-1) - { - InputManager.SetMenuDisplayed(player->GetXboxPad(),true); - } - else - { - // set all - //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,true); - } - } - else - { - if(player && player->GetXboxPad()!=-1) - { - InputManager.SetMenuDisplayed(player->GetXboxPad(),false); - } - else - { - //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,false); - } - }*/ +void Minecraft::checkGlError(const std::wstring& string) { + // 4J - TODO } -void Minecraft::checkGlError(const std::wstring& string) -{ - // 4J - TODO +void Minecraft::destroy() { + // 4J Gordon: Do not force a stats save here + /*stats->forceSend(); + stats->forceSave();*/ + + // 4J - all try/catch/finally things in here removed + // try { + if (this->bgLoader != NULL) { + bgLoader->halt(); + } + // } catch (Exception e) { + // } + + // try { + setLevel(NULL); + // } catch (Throwable e) { + // } + + // try { + MemoryTracker::release(); + // } catch (Throwable e) { + // } + + soundEngine->destroy(); + Mouse::destroy(); + Keyboard::destroy(); + //} finally { + Display::destroy(); + // if (!hasCrashed) System.exit(0); //4J - removed + //} + // System.gc(); // 4J - removed } -void Minecraft::destroy() -{ - //4J Gordon: Do not force a stats save here - /*stats->forceSend(); - stats->forceSave();*/ - - // 4J - all try/catch/finally things in here removed - // try { - if (this->bgLoader != NULL) - { - bgLoader->halt(); - } - // } catch (Exception e) { - // } - - // try { - setLevel(NULL); - // } catch (Throwable e) { - // } - - // try { - MemoryTracker::release(); - // } catch (Throwable e) { - // } - - soundEngine->destroy(); - Mouse::destroy(); - Keyboard::destroy(); - //} finally { - Display::destroy(); - // if (!hasCrashed) System.exit(0); //4J - removed - //} - //System.gc(); // 4J - removed -} - -// 4J-PB - splitting this function into 3 parts, so we can call the middle part from our xbox game loop +// 4J-PB - splitting this function into 3 parts, so we can call the middle part +// from our xbox game loop #if 0 void Minecraft::run() @@ -810,1364 +795,1520 @@ void Minecraft::run() } #endif -void Minecraft::run() -{ - running = true; - // try { // 4J - removed try/catch - init(); - // } catch (Exception e) { - // e.printStackTrace(); - // crash(new CrashReport("Failed to start game", e)); - // return; - // } - // try { // 4J - removed try/catch - } - -// 4J added - Selects which local player is currently active for processing by the existing minecraft code -bool Minecraft::setLocalPlayerIdx(int idx) -{ - localPlayerIdx = idx; - // If the player is not null, but the game mode is then this is just a temp player - // whose only real purpose is to hold the viewport position - if( localplayers[idx] == NULL || localgameModes[idx] == NULL ) return false; - - gameMode = localgameModes[idx]; - player = localplayers[idx]; - cameraTargetPlayer = localplayers[idx]; - gameRenderer->itemInHandRenderer = localitemInHandRenderers[idx]; - level = getLevel( localplayers[idx]->dimension ); - particleEngine->setLevel( level ); - - return true; +void Minecraft::run() { + running = true; + // try { // 4J - removed try/catch + init(); + // } catch (Exception e) { + // e.printStackTrace(); + // crash(new CrashReport("Failed to start game", e)); + // return; + // } + // try { // 4J - removed try/catch } -int Minecraft::getLocalPlayerIdx() -{ - return localPlayerIdx; +// 4J added - Selects which local player is currently active for processing by +// the existing minecraft code +bool Minecraft::setLocalPlayerIdx(int idx) { + localPlayerIdx = idx; + // If the player is not null, but the game mode is then this is just a temp + // player whose only real purpose is to hold the viewport position + if (localplayers[idx] == NULL || localgameModes[idx] == NULL) return false; + + gameMode = localgameModes[idx]; + player = localplayers[idx]; + cameraTargetPlayer = localplayers[idx]; + gameRenderer->itemInHandRenderer = localitemInHandRenderers[idx]; + level = getLevel(localplayers[idx]->dimension); + particleEngine->setLevel(level); + + return true; } -void Minecraft::updatePlayerViewportAssignments() -{ - unoccupiedQuadrant = -1; - // Find out how many viewports we'll be needing - int viewportsRequired = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) viewportsRequired++; - } - if( viewportsRequired == 3 ) viewportsRequired = 4; +int Minecraft::getLocalPlayerIdx() { return localPlayerIdx; } - // Allocate away... - if( viewportsRequired == 1 ) - { - // Single viewport - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - } - } - else if( viewportsRequired == 2 ) - { - // Split screen - TODO - option for vertical/horizontal split - int found = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { - // Primary player settings decide what the mode is - if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_SplitScreenVertical)) - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_SPLIT_LEFT + found; - } - else - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_SPLIT_TOP + found; - } - found++; - } - } - } - else if( viewportsRequired >= 3 ) - { - // Quadrants - this is slightly more complicated. We don't want to move viewports around if we are going from 3 to 4, or 4 to 3 players, - // so persist any allocations for quadrants that already exist. - bool quadrantsAllocated[4] = {false,false,false,false}; +void Minecraft::updatePlayerViewportAssignments() { + unoccupiedQuadrant = -1; + // Find out how many viewports we'll be needing + int viewportsRequired = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) viewportsRequired++; + } + if (viewportsRequired == 3) viewportsRequired = 4; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { + // Allocate away... + if (viewportsRequired == 1) { + // Single viewport + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; + } + } else if (viewportsRequired == 2) { + // Split screen - TODO - option for vertical/horizontal split + int found = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + // Primary player settings decide what the mode is + if (app.GetGameSettings(ProfileManager.GetPrimaryPad(), + eGameSetting_SplitScreenVertical)) { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT + found; + } else { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_SPLIT_TOP + found; + } + found++; + } + } + } else if (viewportsRequired >= 3) { + // Quadrants - this is slightly more complicated. We don't want to move + // viewports around if we are going from 3 to 4, or 4 to 3 players, so + // persist any allocations for quadrants that already exist. + bool quadrantsAllocated[4] = {false, false, false, false}; - // 4J Stu - If the game hasn't started, ignore current allocations (as the players won't have seen them) - // This fixes an issue with the primary player being the 4th controller quadrant, but ending up in the 3rd viewport. - if(app.GetGameStarted()) - { - if( ( localplayers[i]->m_iScreenSection >= C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT ) && - ( localplayers[i]->m_iScreenSection <= C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT ) ) - { - quadrantsAllocated[localplayers[i]->m_iScreenSection - C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT] = true; - } - } - else - { - // Reset the viewport so that it can be assigned in the next loop - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - } - } - } + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + // 4J Stu - If the game hasn't started, ignore current + // allocations (as the players won't have seen them) This fixes + // an issue with the primary player being the 4th controller + // quadrant, but ending up in the 3rd viewport. + if (app.GetGameStarted()) { + if ((localplayers[i]->m_iScreenSection >= + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT) && + (localplayers[i]->m_iScreenSection <= + C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT)) { + quadrantsAllocated + [localplayers[i]->m_iScreenSection - + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT] = true; + } + } else { + // Reset the viewport so that it can be assigned in the next + // loop + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; + } + } + } - // Found which quadrants are currently in use, now allocate out any spares that are required - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { - if( ( localplayers[i]->m_iScreenSection < C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT ) || - ( localplayers[i]->m_iScreenSection > C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT ) ) - { - for( int j = 0; j < 4; j++ ) - { - if( !quadrantsAllocated[j] ) - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + j; - quadrantsAllocated[j] = true; - break; - } - } - } - } - } - // If there's an unoccupied quadrant, record which one so we can clear it to black when rendering - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( quadrantsAllocated[i] == false ) - { - unoccupiedQuadrant = i; - } - } - } + // Found which quadrants are currently in use, now allocate out any + // spares that are required + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + if ((localplayers[i]->m_iScreenSection < + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT) || + (localplayers[i]->m_iScreenSection > + C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT)) { + for (int j = 0; j < 4; j++) { + if (!quadrantsAllocated[j]) { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + j; + quadrantsAllocated[j] = true; + break; + } + } + } + } + } + // If there's an unoccupied quadrant, record which one so we can clear + // it to black when rendering + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (quadrantsAllocated[i] == false) { + unoccupiedQuadrant = i; + } + } + } - // 4J Stu - If the game is not running we do not want to do this yet, and should wait until the task - // that caused the app to not be running is finished - if(app.GetGameStarted())ui.UpdatePlayerBasePositions(); + // 4J Stu - If the game is not running we do not want to do this yet, and + // should wait until the task that caused the app to not be running is + // finished + if (app.GetGameStarted()) ui.UpdatePlayerBasePositions(); } -// Add a temporary player so that the viewports get re-arranged, and add the player to the game session -bool Minecraft::addLocalPlayer(int idx) -{ - //int iLocalPlayerC=app.GetLocalPlayerCount(); - if( m_pendingLocalConnections[idx] != NULL ) - { - // 4J Stu - Should we ever be in a state where this happens? - assert(false); - m_pendingLocalConnections[idx]->close(); - } - m_connectionFailed[idx] = false; - m_pendingLocalConnections[idx] = NULL; +// Add a temporary player so that the viewports get re-arranged, and add the +// player to the game session +bool Minecraft::addLocalPlayer(int idx) { + // int iLocalPlayerC=app.GetLocalPlayerCount(); + if (m_pendingLocalConnections[idx] != NULL) { + // 4J Stu - Should we ever be in a state where this happens? + assert(false); + m_pendingLocalConnections[idx]->close(); + } + m_connectionFailed[idx] = false; + m_pendingLocalConnections[idx] = NULL; - bool success=g_NetworkManager.AddLocalPlayerByUserIndex(idx); + bool success = g_NetworkManager.AddLocalPlayerByUserIndex(idx); - if(success) - { - app.DebugPrintf("Adding temp local player on pad %d\n", idx); - localplayers[idx] = std::shared_ptr( new MultiplayerLocalPlayer(this, level, user, NULL ) ); - localgameModes[idx] = NULL; + if (success) { + app.DebugPrintf("Adding temp local player on pad %d\n", idx); + localplayers[idx] = std::shared_ptr( + new MultiplayerLocalPlayer(this, level, user, NULL)); + localgameModes[idx] = NULL; - updatePlayerViewportAssignments(); + updatePlayerViewportAssignments(); #ifdef _XBOX - // tell the xui scenes a splitscreen player joined - XUIMessage xuiMsg; - CustomMessage_Splitscreenplayer_Struct myMsgData; - CustomMessage_Splitscreenplayer( &xuiMsg, &myMsgData, true); + // tell the xui scenes a splitscreen player joined + XUIMessage xuiMsg; + CustomMessage_Splitscreenplayer_Struct myMsgData; + CustomMessage_Splitscreenplayer(&xuiMsg, &myMsgData, true); - // send the message - for(int i=0;iiPad = idx; - param->stringId = IDS_PROGRESS_CONNECTING; - param->showTooltips = true; - param->setFailTimer = true; - param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; + ConnectionProgressParams* param = new ConnectionProgressParams(); + param->iPad = idx; + param->stringId = IDS_PROGRESS_CONNECTING; + param->showTooltips = true; + param->setFailTimer = true; + param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; - // Joining as second player so always the small progress - ui.NavigateToScene(idx, eUIScene_ConnectingProgress, param); + // Joining as second player so always the small progress + ui.NavigateToScene(idx, eUIScene_ConnectingProgress, param); - } - else - { - app.DebugPrintf("g_NetworkManager.AddLocalPlayerByUserIndex failed\n"); + } else { + app.DebugPrintf("g_NetworkManager.AddLocalPlayerByUserIndex failed\n"); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(idx); + ProfileManager.RemoveGamepadFromGame(idx); #endif - } + } - return success; + return success; } -void Minecraft::addPendingLocalConnection(int idx, ClientConnection *connection) -{ - m_pendingLocalConnections[idx] = connection; +void Minecraft::addPendingLocalConnection(int idx, + ClientConnection* connection) { + m_pendingLocalConnections[idx] = connection; } -std::shared_ptr Minecraft::createExtraLocalPlayer(int idx, const std::wstring& name, int iPad, int iDimension, ClientConnection *clientConnection /*= NULL*/,MultiPlayerLevel *levelpassedin) -{ - if( clientConnection == NULL) return nullptr; +std::shared_ptr Minecraft::createExtraLocalPlayer( + int idx, const std::wstring& name, int iPad, int iDimension, + ClientConnection* clientConnection /*= NULL*/, + MultiPlayerLevel* levelpassedin) { + if (clientConnection == NULL) return nullptr; - if( clientConnection == m_pendingLocalConnections[idx] ) - { - int tempScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - if( localplayers[idx] != NULL && localgameModes[idx] == NULL ) - { - // A temp player displaying a connecting screen - tempScreenSection = localplayers[idx]->m_iScreenSection; - } - std::wstring prevname = user->name; - user->name = name; + if (clientConnection == m_pendingLocalConnections[idx]) { + int tempScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; + if (localplayers[idx] != NULL && localgameModes[idx] == NULL) { + // A temp player displaying a connecting screen + tempScreenSection = localplayers[idx]->m_iScreenSection; + } + std::wstring prevname = user->name; + user->name = name; - // Don't need this any more - m_pendingLocalConnections[idx] = NULL; + // Don't need this any more + m_pendingLocalConnections[idx] = NULL; - // Add the connection to the level which will now take responsibility for ticking it - // 4J-PB - can't use the dimension from localplayers[idx], since there may be no localplayers at this point - //MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)getLevel( localplayers[idx]->dimension ); + // Add the connection to the level which will now take responsibility + // for ticking it 4J-PB - can't use the dimension from + // localplayers[idx], since there may be no localplayers at this point + // MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)getLevel( + // localplayers[idx]->dimension ); - MultiPlayerLevel *mpLevel; + MultiPlayerLevel* mpLevel; - if(levelpassedin) - { - level=levelpassedin; - mpLevel=levelpassedin; - } - else - { - level=getLevel( iDimension ); - mpLevel = getLevel( iDimension ); - mpLevel->addClientConnection( clientConnection ); - } + if (levelpassedin) { + level = levelpassedin; + mpLevel = levelpassedin; + } else { + level = getLevel(iDimension); + mpLevel = getLevel(iDimension); + mpLevel->addClientConnection(clientConnection); + } - if( app.GetTutorialMode() ) - { - localgameModes[idx] = new FullTutorialMode(idx, this, clientConnection); - } - // check if we're in the trial version - else if(ProfileManager.IsFullVersion()==false) - { - localgameModes[idx] = new TrialMode(idx, this, clientConnection); - } - else - { - localgameModes[idx] = new ConsoleGameMode(idx, this, clientConnection); - } + if (app.GetTutorialMode()) { + localgameModes[idx] = + new FullTutorialMode(idx, this, clientConnection); + } + // check if we're in the trial version + else if (ProfileManager.IsFullVersion() == false) { + localgameModes[idx] = new TrialMode(idx, this, clientConnection); + } else { + localgameModes[idx] = + new ConsoleGameMode(idx, this, clientConnection); + } - // 4J-PB - can't do this here because they use a render context, but this is running from a thread. - // Moved the creation of these into the main thread, before level launch - //localitemInHandRenderers[idx] = new ItemInHandRenderer(this); - localplayers[idx] = localgameModes[idx]->createPlayer(level); + // 4J-PB - can't do this here because they use a render context, but + // this is running from a thread. Moved the creation of these into the + // main thread, before level launch + // localitemInHandRenderers[idx] = new ItemInHandRenderer(this); + localplayers[idx] = localgameModes[idx]->createPlayer(level); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(idx,&playerXUIDOffline,false); - ProfileManager.GetXUID(idx,&playerXUIDOnline,true); - localplayers[idx]->setXuid(playerXUIDOffline); - localplayers[idx]->setOnlineXuid(playerXUIDOnline); - localplayers[idx]->setIsGuest(ProfileManager.IsGuest(idx)); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(idx, &playerXUIDOffline, false); + ProfileManager.GetXUID(idx, &playerXUIDOnline, true); + localplayers[idx]->setXuid(playerXUIDOffline); + localplayers[idx]->setOnlineXuid(playerXUIDOnline); + localplayers[idx]->setIsGuest(ProfileManager.IsGuest(idx)); - localplayers[idx]->displayName = ProfileManager.GetDisplayName(idx); + localplayers[idx]->displayName = ProfileManager.GetDisplayName(idx); - localplayers[idx]->m_iScreenSection = tempScreenSection; + localplayers[idx]->m_iScreenSection = tempScreenSection; - if( levelpassedin == NULL) level->addEntity(localplayers[idx]); // Don't add if we're passing the level in, we only do this from the client connection & we'll be handling adding it ourselves + if (levelpassedin == NULL) + level->addEntity( + localplayers[idx]); // Don't add if we're passing the level in, + // we only do this from the client + // connection & we'll be handling adding it + // ourselves - localplayers[idx]->SetXboxPad(iPad); + localplayers[idx]->SetXboxPad(iPad); - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; - localplayers[idx]->input = new Input(); + if (localplayers[idx]->input != NULL) delete localplayers[idx]->input; + localplayers[idx]->input = new Input(); - localplayers[idx]->resetPos(); + localplayers[idx]->resetPos(); - levelRenderer->setLevel(idx, level); - localplayers[idx]->level = level; + levelRenderer->setLevel(idx, level); + localplayers[idx]->level = level; - user->name = prevname; + user->name = prevname; - updatePlayerViewportAssignments(); + updatePlayerViewportAssignments(); - // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players are spawned at incorrect places after re-joining previously saved and loaded "Mass Effect World". - // Move this check to ClientConnection::handleMovePlayer -// // 4J-PB - can't call this when this function is called from the qnet thread (GetGameStarted will be false) -// if(app.GetGameStarted()) -// { -// ui.CloseUIScenes(idx); -// } - } + // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players + // are spawned at incorrect places after re-joining previously saved and + // loaded "Mass Effect World". Move this check to + // ClientConnection::handleMovePlayer + // // 4J-PB - can't call this when this function is called + //from the qnet thread (GetGameStarted will be false) + // if(app.GetGameStarted()) + // { + // ui.CloseUIScenes(idx); + // } + } - return localplayers[idx]; + return localplayers[idx]; } // on a respawn of the local player, just store them -void Minecraft::storeExtraLocalPlayer(int idx) -{ - localplayers[idx] = player; +void Minecraft::storeExtraLocalPlayer(int idx) { + localplayers[idx] = player; - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; - localplayers[idx]->input = new Input(); + if (localplayers[idx]->input != NULL) delete localplayers[idx]->input; + localplayers[idx]->input = new Input(); - if(ProfileManager.IsSignedIn(idx)) - { - localplayers[idx]->name = convStringToWstring( ProfileManager.GetGamertag(idx) ); - } + if (ProfileManager.IsSignedIn(idx)) { + localplayers[idx]->name = + convStringToWstring(ProfileManager.GetGamertag(idx)); + } } -void Minecraft::removeLocalPlayerIdx(int idx) -{ - bool updateXui = true; - if(localgameModes[idx] != NULL) - { - if( getLevel( localplayers[idx]->dimension )->isClientSide ) - { - std::shared_ptr mplp = localplayers[idx]; - ( (MultiPlayerLevel *)getLevel( localplayers[idx]->dimension ) )->removeClientConnection(mplp->connection, true); - delete mplp->connection; - mplp->connection = NULL; - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); - } - getLevel( localplayers[idx]->dimension )->removeEntity(localplayers[idx]); +void Minecraft::removeLocalPlayerIdx(int idx) { + bool updateXui = true; + if (localgameModes[idx] != NULL) { + if (getLevel(localplayers[idx]->dimension)->isClientSide) { + std::shared_ptr mplp = localplayers[idx]; + ((MultiPlayerLevel*)getLevel(localplayers[idx]->dimension)) + ->removeClientConnection(mplp->connection, true); + delete mplp->connection; + mplp->connection = NULL; + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + } + getLevel(localplayers[idx]->dimension)->removeEntity(localplayers[idx]); #ifdef _XBOX - // 4J Stu - Fix for #12368 - Crash: Game crashes when saving then exiting and selecting to save - app.TutorialSceneNavigateBack(idx); + // 4J Stu - Fix for #12368 - Crash: Game crashes when saving then + // exiting and selecting to save + app.TutorialSceneNavigateBack(idx); #endif - // 4J Stu - Fix for #13257 - CRASH: Gameplay: Title crashed after exiting the tutorial - // It doesn't matter if they were in the tutorial already - playerLeftTutorial( idx ); + // 4J Stu - Fix for #13257 - CRASH: Gameplay: Title crashed after + // exiting the tutorial It doesn't matter if they were in the tutorial + // already + playerLeftTutorial(idx); - delete localgameModes[idx]; - localgameModes[idx] = NULL; - } - else if( m_pendingLocalConnections[idx] != NULL ) - { - m_pendingLocalConnections[idx]->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) );; - delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); - } - else - { - // Not sure how this works on qnet, but for other platforms, calling RemoveLocalPlayerByUserIndex won't do anything if there isn't a local user to remove - // Now just updating the UI directly in this case + delete localgameModes[idx]; + localgameModes[idx] = NULL; + } else if (m_pendingLocalConnections[idx] != NULL) { + m_pendingLocalConnections[idx]->sendAndDisconnect( + std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + ; + delete m_pendingLocalConnections[idx]; + m_pendingLocalConnections[idx] = NULL; + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + } else { + // Not sure how this works on qnet, but for other platforms, calling + // RemoveLocalPlayerByUserIndex won't do anything if there isn't a local + // user to remove Now just updating the UI directly in this case #ifdef _XBOX - // 4J Stu - A signout early in the game creation before this player has connected to the game server - updateXui = false; + // 4J Stu - A signout early in the game creation before this player has + // connected to the game server + updateXui = false; #endif - // 4J Stu - Adding this back in for exactly the reason my comment above suggests it was added in the first place + // 4J Stu - Adding this back in for exactly the reason my comment above + // suggests it was added in the first place #ifdef _XBOX_ONE - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); #endif - } - localplayers[idx] = nullptr; + } + localplayers[idx] = nullptr; - if( idx == ProfileManager.GetPrimaryPad() ) - { - // We should never try to remove the Primary player in this way - assert(false); - /* - // If we are removing the primary player then there can't be a valid gamemode left anymore, this - // pointer will be referring to the one we've just deleted - gameMode = NULL; - // Remove references to player - player = NULL; - cameraTargetPlayer = NULL; - EntityRenderDispatcher::instance->cameraEntity = NULL; - TileEntityRenderDispatcher::instance->cameraEntity = NULL; - */ - } - else if( updateXui ) - { - gameRenderer->DisableUpdateThread(); - levelRenderer->setLevel(idx, NULL); - gameRenderer->EnableUpdateThread(); - ui.CloseUIScenes(idx,true); - updatePlayerViewportAssignments(); - } + if (idx == ProfileManager.GetPrimaryPad()) { + // We should never try to remove the Primary player in this way + assert(false); + /* + // If we are removing the primary player then there can't be a valid + gamemode left anymore, this + // pointer will be referring to the one we've just deleted + gameMode = NULL; + // Remove references to player + player = NULL; + cameraTargetPlayer = NULL; + EntityRenderDispatcher::instance->cameraEntity = NULL; + TileEntityRenderDispatcher::instance->cameraEntity = NULL; + */ + } else if (updateXui) { + gameRenderer->DisableUpdateThread(); + levelRenderer->setLevel(idx, NULL); + gameRenderer->EnableUpdateThread(); + ui.CloseUIScenes(idx, true); + updatePlayerViewportAssignments(); + } - // We only create these once ever so don't delete it here - //delete localitemInHandRenderers[idx]; + // We only create these once ever so don't delete it here + // delete localitemInHandRenderers[idx]; } -void Minecraft::createPrimaryLocalPlayer(int iPad) -{ - localgameModes[iPad] = gameMode; - localplayers[iPad] = player; - //gameRenderer->itemInHandRenderer = localitemInHandRenderers[iPad]; - // Give them the gamertag if they're signed in - if(ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) - { - user->name = convStringToWstring( ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad()) ); - } +void Minecraft::createPrimaryLocalPlayer(int iPad) { + localgameModes[iPad] = gameMode; + localplayers[iPad] = player; + // gameRenderer->itemInHandRenderer = localitemInHandRenderers[iPad]; + // Give them the gamertag if they're signed in + if (ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) { + user->name = convStringToWstring( + ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); + } } -void Minecraft::run_middle() -{ - static __int64 lastTime = 0; - static bool bFirstTimeIntoGame = true; - static bool bAutosaveTimerSet=false; - static unsigned int uiAutosaveTimer=0; - static int iFirstTimeCountdown=60; - if( lastTime == 0 ) lastTime = System::nanoTime(); - static int frames = 0; +void Minecraft::run_middle() { + static __int64 lastTime = 0; + static bool bFirstTimeIntoGame = true; + static bool bAutosaveTimerSet = false; + static unsigned int uiAutosaveTimer = 0; + static int iFirstTimeCountdown = 60; + if (lastTime == 0) lastTime = System::nanoTime(); + static int frames = 0; - EnterCriticalSection(&m_setLevelCS); + EnterCriticalSection(&m_setLevelCS); - if(running) - { - if (reloadTextures) - { - reloadTextures = false; - textures->reloadAll(); - } + if (running) { + if (reloadTextures) { + reloadTextures = false; + textures->reloadAll(); + } - //while (running) - { - // try { // 4J - removed try/catch - // if (minecraftApplet != null && !minecraftApplet.isActive()) break; // 4J - removed - AABB::resetPool(); - Vec3::resetPool(); + // while (running) + { + // try { // 4J - removed try/catch + // if (minecraftApplet != null && + // !minecraftApplet.isActive()) break; // 4J - removed + AABB::resetPool(); + Vec3::resetPool(); - // if (parent == NULL && Display.isCloseRequested()) { // 4J - removed - // stop(); - // } + // if (parent == NULL && Display.isCloseRequested()) { + // // 4J - removed + // stop(); + // } - // 4J-PB - AUTOSAVE TIMER - only in the full game and if the player is the host - if(level!=NULL && ProfileManager.IsFullVersion() && g_NetworkManager.IsHost()) - { - /*if(!bAutosaveTimerSet) - { - // set the timer - bAutosaveTimerSet=true; + // 4J-PB - AUTOSAVE TIMER - only in the full game and if the player + // is the host + if (level != NULL && ProfileManager.IsFullVersion() && + g_NetworkManager.IsHost()) { + /*if(!bAutosaveTimerSet) + { + // set the timer + bAutosaveTimerSet=true; - app.SetAutosaveTimerTime(); - } - else*/ - { - // if the pause menu is up for the primary player, don't autosave - // If saving isn't disabled, and the main player has a app action running , or has any crafting or containers open, don't autosave - if(!StorageManager.GetSaveDisabled() && (app.GetXuiAction(ProfileManager.GetPrimaryPad())==eAppAction_Idle) ) - { - if(!ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) && !ui.IsIgnoreAutosaveMenuDisplayed(ProfileManager.GetPrimaryPad())) - { - // check if the autotimer countdown has reached zero - unsigned char ucAutosaveVal=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Autosave); - bool bTrialTexturepack=false; - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + app.SetAutosaveTimerTime(); + } + else*/ + { + // if the pause menu is up for the primary player, don't + // autosave If saving isn't disabled, and the main player + // has a app action running , or has any crafting or + // containers open, don't autosave + if (!StorageManager.GetSaveDisabled() && + (app.GetXuiAction(ProfileManager.GetPrimaryPad()) == + eAppAction_Idle)) { + if (!ui.IsPauseMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + !ui.IsIgnoreAutosaveMenuDisplayed( + ProfileManager.GetPrimaryPad())) { + // check if the autotimer countdown has reached zero + unsigned char ucAutosaveVal = app.GetGameSettings( + ProfileManager.GetPrimaryPad(), + eGameSetting_Autosave); + bool bTrialTexturepack = false; + if (!Minecraft::GetInstance() + ->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance() + ->skins->getSelected(); + DLCTexturePack* pDLCTexPack = + (DLCTexturePack*)tPack; - DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack(); + DLCPack* pDLCPack = + pDLCTexPack->getDLCInfoParentPack(); - if( pDLCPack ) - { - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - bTrialTexturepack=true; - } - } - } + if (pDLCPack) { + if (!pDLCPack->hasPurchasedFile( + DLCManager::e_DLCType_Texture, + L"")) { + bTrialTexturepack = true; + } + } + } - // If the autosave value is not zero, and the player isn't using a trial texture pack, then check whether we need to save this tick - if((ucAutosaveVal!=0) && !bTrialTexturepack) - { - if(app.AutosaveDue()) - { - // disable the autosave countdown - ui.ShowAutosaveCountdownTimer(false); + // If the autosave value is not zero, and the player + // isn't using a trial texture pack, then check + // whether we need to save this tick + if ((ucAutosaveVal != 0) && !bTrialTexturepack) { + if (app.AutosaveDue()) { + // disable the autosave countdown + ui.ShowAutosaveCountdownTimer(false); - // Need to save now - app.DebugPrintf("+++++++++++\n"); - app.DebugPrintf("+++Autosave\n"); - app.DebugPrintf("+++++++++++\n"); - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_AutosaveSaveGame); - //app.SetAutosaveTimerTime(); + // Need to save now + app.DebugPrintf("+++++++++++\n"); + app.DebugPrintf("+++Autosave\n"); + app.DebugPrintf("+++++++++++\n"); + app.SetAction( + ProfileManager.GetPrimaryPad(), + eAppAction_AutosaveSaveGame); + // app.SetAutosaveTimerTime(); #ifndef _CONTENT_PACKAGE - { - // print the time - SYSTEMTIME UTCSysTime; - GetSystemTime( &UTCSysTime ); - //char szTime[15]; + { + // print the time + SYSTEMTIME UTCSysTime; + GetSystemTime(&UTCSysTime); + // char szTime[15]; - app.DebugPrintf("%02d:%02d:%02d\n",UTCSysTime.wHour,UTCSysTime.wMinute,UTCSysTime.wSecond); - } + app.DebugPrintf("%02d:%02d:%02d\n", + UTCSysTime.wHour, + UTCSysTime.wMinute, + UTCSysTime.wSecond); + } #endif - } - else - { - unsigned int uiTimeToAutosave=app.SecondsToAutosave(); + } else { + unsigned int uiTimeToAutosave = + app.SecondsToAutosave(); - if(uiTimeToAutosave<6) - { - ui.ShowAutosaveCountdownTimer(true); - ui.UpdateAutosaveCountdownTimer(uiTimeToAutosave); - } - } - } - } - else - { - // disable the autosave countdown - ui.ShowAutosaveCountdownTimer(false); - } - } - } - } + if (uiTimeToAutosave < 6) { + ui.ShowAutosaveCountdownTimer(true); + ui.UpdateAutosaveCountdownTimer( + uiTimeToAutosave); + } + } + } + } else { + // disable the autosave countdown + ui.ShowAutosaveCountdownTimer(false); + } + } + } + } - // 4J-PB - Once we're in the level, check if the players have the level in their banned list and ask if they want to play it - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] && (app.GetBanListCheck(i)==false) && !Minecraft::GetInstance()->isTutorial() && ProfileManager.IsSignedInLive(i) && !ProfileManager.IsGuest(i) ) - { - // If there is a sys ui displayed, we can't display the message box here, so ignore until we can - if(!ProfileManager.IsSystemUIDisplayed()) - { - app.SetBanListCheck(i,true); - // 4J-PB - check if the level is in the banned level list - // get the unique save name and xuid from whoever is the host + // 4J-PB - Once we're in the level, check if the players have the + // level in their banned list and ask if they want to play it + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] && (app.GetBanListCheck(i) == false) && + !Minecraft::GetInstance()->isTutorial() && + ProfileManager.IsSignedInLive(i) && + !ProfileManager.IsGuest(i)) { + // If there is a sys ui displayed, we can't display the + // message box here, so ignore until we can + if (!ProfileManager.IsSystemUIDisplayed()) { + app.SetBanListCheck(i, true); + // 4J-PB - check if the level is in the banned level + // list get the unique save name and xuid from whoever + // is the host #if defined _XBOX || defined _XBOX_ONE - INetworkPlayer *pHostPlayer = g_NetworkManager.GetHostPlayer(); + INetworkPlayer* pHostPlayer = + g_NetworkManager.GetHostPlayer(); #ifdef _XBOX - PlayerUID xuid=((NetworkPlayerXbox *)pHostPlayer)->GetUID(); + PlayerUID xuid = + ((NetworkPlayerXbox*)pHostPlayer)->GetUID(); #else - PlayerUID xuid=pHostPlayer->GetUID(); + PlayerUID xuid = pHostPlayer->GetUID(); #endif - if(app.IsInBannedLevelList(i,xuid,app.GetUniqueMapName())) - { - // put up a message box asking if the player would like to unban this level - app.DebugPrintf("This level is banned\n"); - // set the app action to bring up the message box to give them the option to remove from the ban list or exit the level - app.SetAction(i,eAppAction_LevelInBanLevelList,(void *)TRUE); - } + if (app.IsInBannedLevelList(i, xuid, + app.GetUniqueMapName())) { + // put up a message box asking if the player would + // like to unban this level + app.DebugPrintf("This level is banned\n"); + // set the app action to bring up the message box to + // give them the option to remove from the ban list + // or exit the level + app.SetAction(i, eAppAction_LevelInBanLevelList, + (void*)TRUE); + } #endif - } - } - } + } + } + } - if(!ProfileManager.IsSystemUIDisplayed() && app.DLCInstallProcessCompleted() && !app.DLCInstallPending() && app.m_dlcManager.NeedsCorruptCheck() ) - { - app.m_dlcManager.checkForCorruptDLCAndAlert(); - } + if (!ProfileManager.IsSystemUIDisplayed() && + app.DLCInstallProcessCompleted() && !app.DLCInstallPending() && + app.m_dlcManager.NeedsCorruptCheck()) { + app.m_dlcManager.checkForCorruptDLCAndAlert(); + } - // When we go into the first loaded level, check if the console has active joypads that are not in the game, and bring up the quadrant display to remind them to press start (if the session has space) - if(level!=NULL && bFirstTimeIntoGame && g_NetworkManager.SessionHasSpace()) - { - // have a short delay before the display - if(iFirstTimeCountdown==0) - { - bFirstTimeIntoGame=false; + // When we go into the first loaded level, check if the console has + // active joypads that are not in the game, and bring up the + // quadrant display to remind them to press start (if the session + // has space) + if (level != NULL && bFirstTimeIntoGame && + g_NetworkManager.SessionHasSpace()) { + // have a short delay before the display + if (iFirstTimeCountdown == 0) { + bFirstTimeIntoGame = false; - if(app.IsLocalMultiplayerAvailable()) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if((localplayers[i] == NULL) && InputManager.IsPadConnected(i)) - { - if(!ui.PressStartPlaying(i)) - { - ui.ShowPressStart(i); - } - } - } - } - } - else iFirstTimeCountdown--; - } - // 4J-PB - store any button toggles for the players, since the minecraft::tick may not be called if we're running fast, and a button press and release will be missed + if (app.IsLocalMultiplayerAvailable()) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if ((localplayers[i] == NULL) && + InputManager.IsPadConnected(i)) { + if (!ui.PressStartPlaying(i)) { + ui.ShowPressStart(i); + } + } + } + } + } else + iFirstTimeCountdown--; + } + // 4J-PB - store any button toggles for the players, since the + // minecraft::tick may not be called if we're running fast, and a + // button press and release will be missed - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { #ifdef __ORBIS__ - if ( m_pPsPlusUpsell != NULL && m_pPsPlusUpsell->hasResponse() && m_pPsPlusUpsell->m_userIndex == i ) - { - delete m_pPsPlusUpsell; - m_pPsPlusUpsell = NULL; - - if ( ProfileManager.HasPlayStationPlus(i) ) - { - app.DebugPrintf(" Player_%i is now authorised for PsPlus.\n", i); - if (!ui.PressStartPlaying(i)) ui.ShowPressStart(i); - } - else - { - unsigned int uiIDA[1] = { IDS_OK }; - ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA, 1, i, NULL, NULL, app.GetStringTable() ); - } - } - else -#endif - if(localplayers[i]) - { - // 4J-PB - add these to check for coming out of idle - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_JUMP)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<hasResponse() && + m_pPsPlusUpsell->m_userIndex == i) { + delete m_pPsPlusUpsell; + m_pPsPlusUpsell = NULL; - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_INVENTORY)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL< Player_%i is now authorised for " + "PsPlus.\n", + i); + if (!ui.PressStartPlaying(i)) ui.ShowPressStart(i); + } else { + unsigned int uiIDA[1] = {IDS_OK}; + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA, + 1, i, NULL, NULL, app.GetStringTable()); + } + } else +#endif + if (localplayers[i]) { + // 4J-PB - add these to check for coming out of idle + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_JUMP)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_JUMP; + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_USE; + + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_INVENTORY)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_INVENTORY; + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_ACTION; + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_CRAFTING)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_CRAFTING; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_PAUSEMENU)) { + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_PAUSEMENU; + app.DebugPrintf( + "PAUSE PRESSED - ipad = %d, Storing press\n", i); + } #ifdef _DURANGO - if(InputManager.ButtonPressed(i, ACTION_MENU_GTC_PAUSE)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed |= + 1LL << ACTION_MENU_GTC_PAUSE; #endif - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_DROP)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_DROP; - // 4J-PB - If we're flying, the sneak needs to be held on to go down - if(localplayers[i]->abilities.flying) - { - if(InputManager.ButtonDown(i, MINECRAFT_ACTION_SNEAK_TOGGLE)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<abilities.flying) { + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_SNEAK_TOGGLE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SNEAK_TOGGLE; + } else { + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_SNEAK_TOGGLE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SNEAK_TOGGLE; + } + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_RENDER_THIRD_PERSON)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_RENDER_THIRD_PERSON; + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_GAME_INFO)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_GAME_INFO; #ifndef _FINAL_BUILD - if( app.DebugSettingsOn() && app.GetUseDPadForDebug() ) - { - localplayers[i]->ullDpad_last = 0; - localplayers[i]->ullDpad_this = 0; - localplayers[i]->ullDpad_filtered = 0; - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_DPAD_RIGHT)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullDpad_last = 0; + localplayers[i]->ullDpad_this = 0; + localplayers[i]->ullDpad_filtered = 0; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_RIGHT)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_CHANGE_SKIN; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_UP)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_FLY_TOGGLE; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_DOWN)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_RENDER_DEBUG; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_LEFT)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SPAWN_CREEPER; + } else #endif - { - // Movement on DPAD is stored ulimately into ullDpad_filtered - this ignores any diagonals pressed, instead reporting the last single direction - otherwise - // we get loads of accidental diagonal movements + { + // Movement on DPAD is stored ulimately into + // ullDpad_filtered - this ignores any diagonals + // pressed, instead reporting the last single direction + // - otherwise we get loads of accidental diagonal + // movements - localplayers[i]->ullDpad_this = 0; - int dirCount = 0; + localplayers[i]->ullDpad_this = 0; + int dirCount = 0; #ifndef __PSVITA__ - if(InputManager.ButtonDown(i, MINECRAFT_ACTION_DPAD_LEFT)) { localplayers[i]->ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_LEFT; + dirCount++; + } + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_DPAD_RIGHT)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_RIGHT; + dirCount++; + } + if (InputManager.ButtonDown(i, + MINECRAFT_ACTION_DPAD_UP)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_UP; + dirCount++; + } + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_DPAD_DOWN)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_DOWN; + dirCount++; + } #endif - if( dirCount <= 1 ) - { - localplayers[i]->ullDpad_last = localplayers[i]->ullDpad_this; - localplayers[i]->ullDpad_filtered = localplayers[i]->ullDpad_this; - } - else - { - localplayers[i]->ullDpad_filtered = localplayers[i]->ullDpad_last; - } - } + if (dirCount <= 1) { + localplayers[i]->ullDpad_last = + localplayers[i]->ullDpad_this; + localplayers[i]->ullDpad_filtered = + localplayers[i]->ullDpad_this; + } else { + localplayers[i]->ullDpad_filtered = + localplayers[i]->ullDpad_last; + } + } - // for the opacity timer - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_LEFT_SCROLL) || InputManager.ButtonPressed(i, MINECRAFT_ACTION_RIGHT_SCROLL)) - //InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE) || InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) - { - app.SetOpacityTimer(i); - } - } - else - { - // 4J Stu - This doesn't make any sense with the way we handle XboxOne users + // for the opacity timer + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_LEFT_SCROLL) || + InputManager.ButtonPressed( + i, MINECRAFT_ACTION_RIGHT_SCROLL)) + // InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE) || + // InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) + { + app.SetOpacityTimer(i); + } + } else { + // 4J Stu - This doesn't make any sense with the way we + // handle XboxOne users #ifndef _DURANGO - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - bool tryJoin = !pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef() && InputManager.ButtonPressed(i); + // did we just get input from a player who doesn't exist? + // They'll be wanting to join the game then + bool tryJoin = !pause && + !ui.IsIgnorePlayerJoinMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + g_NetworkManager.SessionHasSpace() && + RenderManager.IsHiDef() && + InputManager.ButtonPressed(i); #ifdef __ORBIS__ - // Check for remote play - tryJoin = tryJoin && InputManager.IsLocalMultiplayerAvailable(); + // Check for remote play + tryJoin = + tryJoin && InputManager.IsLocalMultiplayerAvailable(); - // 4J Stu - Check that content restriction information has been received - if( !g_NetworkManager.IsLocalGame() ) - { - tryJoin = tryJoin && ProfileManager.GetChatAndContentRestrictions(i,true,NULL,NULL,NULL); - } + // 4J Stu - Check that content restriction information has + // been received + if (!g_NetworkManager.IsLocalGame()) { + tryJoin = tryJoin && + ProfileManager.GetChatAndContentRestrictions( + i, true, NULL, NULL, NULL); + } #endif - if(tryJoin) - { - if(!ui.PressStartPlaying(i)) - { + if (tryJoin) { + if (!ui.PressStartPlaying(i)) { #ifdef __ORBIS__ - // Don't let player start joining until their PS Plus check has finished - if (g_NetworkManager.IsLocalGame() || !ProfileManager.RequestingPlaystationPlus(i)) + // Don't let player start joining until their PS + // Plus check has finished + if (g_NetworkManager.IsLocalGame() || + !ProfileManager.RequestingPlaystationPlus(i)) #endif - { - ui.ShowPressStart(i); - } - } - else - { - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then + { + ui.ShowPressStart(i); + } + } else { + // did we just get input from a player who doesn't + // exist? They'll be wanting to join the game then #ifdef __ORBIS__ - if(InputManager.ButtonPressed(i, ACTION_MENU_A)) + if (InputManager.ButtonPressed(i, ACTION_MENU_A)) #else - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_PAUSEMENU)) + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_PAUSEMENU)) #endif - { - // Let them join + { + // Let them join - // are they signed in? - if(ProfileManager.IsSignedIn(i)) - { - // if this is a local game, then the player just needs to be signed in - if( g_NetworkManager.IsLocalGame() || (ProfileManager.IsSignedInLive(i) && ProfileManager.AllowedToPlayMultiplayer(i) ) ) - { + // are they signed in? + if (ProfileManager.IsSignedIn(i)) { + // if this is a local game, then the player + // just needs to be signed in + if (g_NetworkManager.IsLocalGame() || + (ProfileManager.IsSignedInLive(i) && + ProfileManager + .AllowedToPlayMultiplayer(i))) { #ifdef __ORBIS__ - bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,NULL,&contentRestricted,NULL); // TODO! + bool contentRestricted = false; + ProfileManager + .GetChatAndContentRestrictions( + i, false, NULL, + &contentRestricted, + NULL); // TODO! - if (!g_NetworkManager.IsLocalGame() && contentRestricted) - { - ui.RequestContentRestrictedMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_CONTENT_RESTRICTION, i); - } - else if(!g_NetworkManager.IsLocalGame() && !ProfileManager.HasPlayStationPlus(i)) - { - m_pPsPlusUpsell = new PsPlusUpsellWrapper(i); - m_pPsPlusUpsell->displayUpsell(); - } - else + if (!g_NetworkManager.IsLocalGame() && + contentRestricted) { + ui.RequestContentRestrictedMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_CONTENT_RESTRICTION, i); + } else if (!g_NetworkManager + .IsLocalGame() && + !ProfileManager + .HasPlayStationPlus( + i)) { + m_pPsPlusUpsell = + new PsPlusUpsellWrapper(i); + m_pPsPlusUpsell->displayUpsell(); + } else #endif - if( level->isClientSide ) - { - bool success=addLocalPlayer(i); + if (level->isClientSide) { + bool success = addLocalPlayer(i); - if(!success) - { - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - else - { + if (!success) { + app.DebugPrintf( + "Bringing up the sign in " + "ui\n"); + ProfileManager.RequestSignInUI( + false, + g_NetworkManager + .IsLocalGame(), + true, false, true, + &Minecraft:: + InGame_SignInReturned, + this, i); + } else { #ifdef __ORBIS__ - if(g_NetworkManager.IsLocalGame() == false) - { - bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,NULL,NULL); - if(chatRestricted) - { - ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, i ); - } - } + if (g_NetworkManager + .IsLocalGame() == + false) { + bool chatRestricted = false; + ProfileManager + .GetChatAndContentRestrictions( + i, false, + &chatRestricted, + NULL, NULL); + if (chatRestricted) { + ProfileManager + .DisplaySystemMessage( + SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, + i); + } + } #endif - } - } - else - { - // create the localplayer - std::shared_ptr player = localplayers[i]; - if( player == NULL) - { - player = createExtraLocalPlayer(i, (convStringToWstring( ProfileManager.GetGamertag(i) )).c_str(), i, level->dimension->id); - } - } - } - else - { - if( ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()) && !ProfileManager.AllowedToPlayMultiplayer(i) ) - { - ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, this,i); - // 4J Stu - Don't allow converting to guests as we don't allow any guest sign-in while in the game - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - //ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, this,i); + } + } else { + // create the localplayer + std::shared_ptr player = + localplayers[i]; + if (player == NULL) { + player = createExtraLocalPlayer( + i, + (convStringToWstring( + ProfileManager + .GetGamertag(i))) + .c_str(), + i, level->dimension->id); + } + } + } else { + if (ProfileManager.IsSignedInLive( + ProfileManager + .GetPrimaryPad()) && + !ProfileManager + .AllowedToPlayMultiplayer(i)) { + ProfileManager + .RequestConvertOfflineToGuestUI( + &Minecraft:: + InGame_SignInReturned, + this, i); + // 4J Stu - Don't allow converting + // to guests as we don't allow any + // guest sign-in while in the game + // Fix for #66516 - TCR #124: MPS + // Guest Support ; #001: BAS Game + // Stability: TU8: The game crashes + // when second Guest signs-in on + // console which takes part in Xbox + // LIVE multiplayer session. + // ProfileManager.RequestConvertOfflineToGuestUI( + // &Minecraft::InGame_SignInReturned, + // this,i); #ifndef _XBOX - ui.HidePressStart(); + ui.HidePressStart(); #endif #ifdef __ORBIS__ - int npAvailability = ProfileManager.getNPAvailability(i); + int npAvailability = + ProfileManager + .getNPAvailability(i); - // Check if PSN is unavailable because of age restriction - if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) - { - unsigned int uiIDA[1]; - uiIDA[0] = IDS_OK; - ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, i, NULL, NULL, app.GetStringTable()); - } - else if (ProfileManager.IsSignedIn(i) && !ProfileManager.IsSignedInLive(i)) - { - // You're not signed in to PSN! - unsigned int uiIDA[2]; - uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; - uiIDA[1] = IDS_CANCEL; - ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, i,&Minecraft::MustSignInReturnedPSN, this, app.GetStringTable(), NULL, 0, false); - } - else + // Check if PSN is unavailable + // because of age restriction + if (npAvailability == + SCE_NP_ERROR_AGE_RESTRICTION) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox( + IDS_ONLINE_SERVICE_TITLE, + IDS_CONTENT_RESTRICTION, + uiIDA, 1, i, NULL, NULL, + app.GetStringTable()); + } else if (ProfileManager + .IsSignedIn(i) && + !ProfileManager + .IsSignedInLive( + i)) { + // You're not signed in to PSN! + unsigned int uiIDA[2]; + uiIDA[0] = + IDS_PRO_NOTONLINE_ACCEPT; + uiIDA[1] = IDS_CANCEL; + ui.RequestMessageBox( + IDS_PRO_NOTONLINE_TITLE, + IDS_PRO_NOTONLINE_TEXT, + uiIDA, 2, i, + &Minecraft:: + MustSignInReturnedPSN, + this, app.GetStringTable(), + NULL, 0, false); + } else #endif - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA, 1, i, NULL, NULL, app.GetStringTable()); - } - } - //else - { - // player not signed in to live - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - } - } - else - { - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - } - } - } -#endif // _DURANGO - } - } + { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, i, NULL, NULL, + app.GetStringTable()); + } + } + // else + { + // player not signed in to live + // bring up the sign in dialog + app.DebugPrintf( + "Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, + g_NetworkManager.IsLocalGame(), + true, false, true, + &Minecraft:: + InGame_SignInReturned, + this, i); + } + } + } else { + // bring up the sign in dialog + app.DebugPrintf( + "Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, g_NetworkManager.IsLocalGame(), + true, false, true, + &Minecraft::InGame_SignInReturned, this, + i); + } + } + } + } +#endif // _DURANGO + } + } #ifdef _DURANGO - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - if(!pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef() ) - { - int firstEmptyUser = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if(localplayers[i] == NULL) - { - firstEmptyUser = i; - break; - } - } + // did we just get input from a player who doesn't exist? They'll be + // wanting to join the game then + if (!pause && + !ui.IsIgnorePlayerJoinMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef()) { + int firstEmptyUser = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] == NULL) { + firstEmptyUser = i; + break; + } + } - // For durango, check for unmapped controllers - for(unsigned int iPad = XUSER_MAX_COUNT; iPad < (XUSER_MAX_COUNT + InputManager.MAX_GAMEPADS); ++iPad) - { - if(InputManager.IsPadLocked(iPad) || !InputManager.IsPadConnected(iPad) ) continue; - if(!InputManager.ButtonPressed(iPad)) continue; + // For durango, check for unmapped controllers + for (unsigned int iPad = XUSER_MAX_COUNT; + iPad < (XUSER_MAX_COUNT + InputManager.MAX_GAMEPADS); + ++iPad) { + if (InputManager.IsPadLocked(iPad) || + !InputManager.IsPadConnected(iPad)) + continue; + if (!InputManager.ButtonPressed(iPad)) continue; - if(!ui.PressStartPlaying(firstEmptyUser)) - { - ui.ShowPressStart(firstEmptyUser); - } - else - { - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - if(InputManager.ButtonPressed(iPad, MINECRAFT_ACTION_PAUSEMENU)) - { - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,iPad); + if (!ui.PressStartPlaying(firstEmptyUser)) { + ui.ShowPressStart(firstEmptyUser); + } else { + // did we just get input from a player who doesn't + // exist? They'll be wanting to join the game then + if (InputManager.ButtonPressed( + iPad, MINECRAFT_ACTION_PAUSEMENU)) { + // bring up the sign in dialog + app.DebugPrintf("Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, g_NetworkManager.IsLocalGame(), true, + false, true, &Minecraft::InGame_SignInReturned, + this, iPad); - // 4J Stu - If we are joining a pad here, then we don't want to try and join any others - break; - } - } - } - } + // 4J Stu - If we are joining a pad here, then we + // don't want to try and join any others + break; + } + } + } + } #endif - if (pause && level != NULL) - { - float lastA = timer->a; - timer->advanceTime(); - timer->a = lastA; - } - else - { - timer->advanceTime(); - } + if (pause && level != NULL) { + float lastA = timer->a; + timer->advanceTime(); + timer->a = lastA; + } else { + timer->advanceTime(); + } - __int64 beforeTickTime = System::nanoTime(); - for (int i = 0; i < timer->ticks; i++) - { - bool bLastTimerTick = ( i == ( timer->ticks - 1 ) ); - // 4J-PB - the tick here can run more than once, and this is a problem for our input, which would see the a key press twice with the same time - let's tick the inputmanager again - if(i!=0) - { - InputManager.Tick(); - app.HandleButtonPresses(); - } + __int64 beforeTickTime = System::nanoTime(); + for (int i = 0; i < timer->ticks; i++) { + bool bLastTimerTick = (i == (timer->ticks - 1)); + // 4J-PB - the tick here can run more than once, and this is a + // problem for our input, which would see the a key press twice + // with the same time - let's tick the inputmanager again + if (i != 0) { + InputManager.Tick(); + app.HandleButtonPresses(); + } - ticks++; - // try { // 4J - try/catch removed - bool bFirst = true; - for( int idx = 0; idx < XUSER_MAX_COUNT; idx++ ) - { - // 4J - If we are waiting for this connection to do something, then tick it here. - // This replaces many of the original Java scenes which would tick the connection while showing that scene - if( m_pendingLocalConnections[idx] != NULL ) - { - m_pendingLocalConnections[idx]->tick(); - } + ticks++; + // try { // 4J - try/catch removed + bool bFirst = true; + for (int idx = 0; idx < XUSER_MAX_COUNT; idx++) { + // 4J - If we are waiting for this connection to do + // something, then tick it here. This replaces many of the + // original Java scenes which would tick the connection + // while showing that scene + if (m_pendingLocalConnections[idx] != NULL) { + m_pendingLocalConnections[idx]->tick(); + } - // reset the player inactive tick - if(localplayers[idx]!=NULL) - { - // any input received? - if((localplayers[idx]->ullButtonsPressed!=0) || InputManager.GetJoypadStick_LX(idx,false)!=0.0f || - InputManager.GetJoypadStick_LY(idx,false)!=0.0f || InputManager.GetJoypadStick_RX(idx,false)!=0.0f || - InputManager.GetJoypadStick_RY(idx,false)!=0.0f ) - { - localplayers[idx]->ResetInactiveTicks(); - } - else - { - localplayers[idx]->IncrementInactiveTicks(); - } + // reset the player inactive tick + if (localplayers[idx] != NULL) { + // any input received? + if ((localplayers[idx]->ullButtonsPressed != 0) || + InputManager.GetJoypadStick_LX(idx, false) != + 0.0f || + InputManager.GetJoypadStick_LY(idx, false) != + 0.0f || + InputManager.GetJoypadStick_RX(idx, false) != + 0.0f || + InputManager.GetJoypadStick_RY(idx, false) != + 0.0f) { + localplayers[idx]->ResetInactiveTicks(); + } else { + localplayers[idx]->IncrementInactiveTicks(); + } - if(localplayers[idx]->GetInactiveTicks()>200) - { - if(!localplayers[idx]->isIdle() && localplayers[idx]->onGround) - { - localplayers[idx]->setIsIdle(true); - } - } - else - { - if(localplayers[idx]->isIdle()) - { - localplayers[idx]->setIsIdle(false); - } - } - } + if (localplayers[idx]->GetInactiveTicks() > 200) { + if (!localplayers[idx]->isIdle() && + localplayers[idx]->onGround) { + localplayers[idx]->setIsIdle(true); + } + } else { + if (localplayers[idx]->isIdle()) { + localplayers[idx]->setIsIdle(false); + } + } + } - if( setLocalPlayerIdx(idx) ) - { - tick(bFirst, bLastTimerTick); - bFirst = false; - // clear the stored button downs since the tick for this player will now have actioned them - player->ullButtonsPressed=0LL; - } - } + if (setLocalPlayerIdx(idx)) { + tick(bFirst, bLastTimerTick); + bFirst = false; + // clear the stored button downs since the tick for this + // player will now have actioned them + player->ullButtonsPressed = 0LL; + } + } - ui.HandleGameTick(); + ui.HandleGameTick(); - setLocalPlayerIdx(ProfileManager.GetPrimaryPad()); + setLocalPlayerIdx(ProfileManager.GetPrimaryPad()); - // 4J - added - now do the equivalent of level::animateTick, but taking into account the positions of all our players + // 4J - added - now do the equivalent of level::animateTick, but + // taking into account the positions of all our players - for( int l = 0; l < levels.length; l++ ) - { - if( levels[l] ) - { - levels[l]->animateTickDoWork(); - } - } + for (int l = 0; l < levels.length; l++) { + if (levels[l]) { + levels[l]->animateTickDoWork(); + } + } - // } catch (LevelConflictException e) { - // this.level = null; - // setLevel(null); - // setScreen(new LevelConflictScreen()); - // } -// SparseLightStorage::tick(); // 4J added -// CompressedTileStorage::tick(); // 4J added -// SparseDataStorage::tick(); // 4J added - } - __int64 tickDuraction = System::nanoTime() - beforeTickTime; - MemSect(31); - checkGlError(L"Pre render"); - MemSect(0); + // } catch (LevelConflictException e) { + // this.level = null; + // setLevel(null); + // setScreen(new LevelConflictScreen()); + // } + // SparseLightStorage::tick(); + // // 4J added CompressedTileStorage::tick(); // 4J added + // SparseDataStorage::tick(); + // // 4J added + } + __int64 tickDuraction = System::nanoTime() - beforeTickTime; + MemSect(31); + checkGlError(L"Pre render"); + MemSect(0); - TileRenderer::fancy = options->fancyGraphics; + TileRenderer::fancy = options->fancyGraphics; - // if (pause) timer.a = 1; + // if (pause) timer.a = 1; - PIXBeginNamedEvent(0,"Sound engine update"); - soundEngine->tick((std::shared_ptr *)localplayers, timer->a); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sound engine update"); + soundEngine->tick((std::shared_ptr*)localplayers, timer->a); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Light update"); + PIXBeginNamedEvent(0, "Light update"); - if (level != NULL) level->updateLights(); - glEnable(GL_TEXTURE_2D); + if (level != NULL) level->updateLights(); + glEnable(GL_TEXTURE_2D); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) Display.update(); // 4J - removed + // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) + // Display.update(); // 4J - removed - // 4J-PB - changing this to be per player - //if (player != NULL && player->isInWall()) options->thirdPersonView = false; - if (player != NULL && player->isInWall()) player->SetThirdPersonView(0); + // 4J-PB - changing this to be per player + // if (player != NULL && player->isInWall()) + // options->thirdPersonView = false; + if (player != NULL && player->isInWall()) + player->SetThirdPersonView(0); - if (!noRender) - { - bool bFirst = true; - int iPrimaryPad=ProfileManager.GetPrimaryPad(); - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( setLocalPlayerIdx(i) ) - { - PIXBeginNamedEvent(0,"Game render player idx %d",i); - RenderManager.StateSetViewport((C4JRender::eViewportType)player->m_iScreenSection); - gameRenderer->render(timer->a, bFirst); - bFirst = false; - PIXEndNamedEvent(); + if (!noRender) { + bool bFirst = true; + int iPrimaryPad = ProfileManager.GetPrimaryPad(); + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (setLocalPlayerIdx(i)) { + PIXBeginNamedEvent(0, "Game render player idx %d", i); + RenderManager.StateSetViewport( + (C4JRender::eViewportType)player->m_iScreenSection); + gameRenderer->render(timer->a, bFirst); + bFirst = false; + PIXEndNamedEvent(); - if(i==iPrimaryPad) - { + if (i == iPrimaryPad) { #ifdef __ORBIS__ - // PS4 does much of the screen-capturing for every frame, to simplify the synchronisation when we actually want a capture. This call tells it the point in the frame to do it. - RenderManager.InternalScreenCapture(); + // PS4 does much of the screen-capturing for every + // frame, to simplify the synchronisation when we + // actually want a capture. This call tells it the + // point in the frame to do it. + RenderManager.InternalScreenCapture(); #endif - // check to see if we need to capture a screenshot for the save game thumbnail - switch(app.GetXuiAction(i)) - { - case eAppAction_ExitWorldCapturedThumbnail: - case eAppAction_SaveGameCapturedThumbnail: - case eAppAction_AutosaveSaveGameCapturedThumbnail: - // capture the save thumbnail - app.CaptureSaveThumbnail(); - break; - default: - break; - } - } - } - } + // check to see if we need to capture a screenshot + // for the save game thumbnail + switch (app.GetXuiAction(i)) { + case eAppAction_ExitWorldCapturedThumbnail: + case eAppAction_SaveGameCapturedThumbnail: + case eAppAction_AutosaveSaveGameCapturedThumbnail: + // capture the save thumbnail + app.CaptureSaveThumbnail(); + break; + default: + break; + } + } + } + } #ifdef __linux__ - // On Linux, Iggy Flash UI is not available. If no players were rendered - // (menu / title-screen state), call GameRenderer directly so mc->screen draws. - if (bFirst) - { - localPlayerIdx = 0; - RenderManager.StateSetViewport(C4JRender::VIEWPORT_TYPE_FULLSCREEN); - gameRenderer->render(timer->a, true); - } + // On Linux, Iggy Flash UI is not available. If no players were + // rendered (menu / title-screen state), call GameRenderer + // directly so mc->screen draws. + if (bFirst) { + localPlayerIdx = 0; + RenderManager.StateSetViewport( + C4JRender::VIEWPORT_TYPE_FULLSCREEN); + gameRenderer->render(timer->a, true); + } #endif - // If there's an unoccupied quadrant, then clear that to black - if( unoccupiedQuadrant > -1 ) - { - // render a logo - RenderManager.StateSetViewport((C4JRender::eViewportType)(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant)); - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT); + // If there's an unoccupied quadrant, then clear that to black + if (unoccupiedQuadrant > -1) { + // render a logo + RenderManager.StateSetViewport(( + C4JRender:: + eViewportType)(C4JRender:: + VIEWPORT_TYPE_QUADRANT_TOP_LEFT + + unoccupiedQuadrant)); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); - ui.SetEmptyQuadrantLogo(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant); - } - setLocalPlayerIdx(iPrimaryPad); - RenderManager.StateSetViewport(C4JRender::VIEWPORT_TYPE_FULLSCREEN); + ui.SetEmptyQuadrantLogo( + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + + unoccupiedQuadrant); + } + setLocalPlayerIdx(iPrimaryPad); + RenderManager.StateSetViewport( + C4JRender::VIEWPORT_TYPE_FULLSCREEN); #ifdef _XBOX - // Do we need to capture a screenshot for a social post? - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if(app.GetXuiAction(i)==eAppAction_SocialPostScreenshot) - { - app.CaptureScreenshot(i); - } - } + // Do we need to capture a screenshot for a social post? + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (app.GetXuiAction(i) == + eAppAction_SocialPostScreenshot) { + app.CaptureScreenshot(i); + } + } #endif - } - glFlush(); - - /* 4J - removed - if (!Display::isActive()) - { - if (fullscreen) - { - this->toggleFullScreen(); - } - Sleep(10); - } - */ - if (options->renderDebug) - { - + } + glFlush(); + /* 4J - removed + if (!Display::isActive()) + { + if (fullscreen) + { + this->toggleFullScreen(); + } + Sleep(10); + } + */ + if (options->renderDebug) { #if DEBUG_RENDER_SHOWS_PACKETS - // To show data for only one packet type - //Packet::renderPacketStats(31); + // To show data for only one packet type + // Packet::renderPacketStats(31); - // To show data for all packet types selected as being renderable in the Packet:static_ctor call to Packet::map - Packet::renderAllPacketStats(); + // To show data for all packet types selected as being + // renderable in the Packet:static_ctor call to Packet::map + Packet::renderAllPacketStats(); #else - // To show the size of the QNet queue in bytes and messages - g_NetworkManager.renderQueueMeter(); + // To show the size of the QNet queue in bytes and messages + g_NetworkManager.renderQueueMeter(); #endif - } - else - { - lastTimer = System::nanoTime(); - } + } else { + lastTimer = System::nanoTime(); + } - achievementPopup->render(); + achievementPopup->render(); - PIXBeginNamedEvent(0,"Sleeping"); - Sleep(0); // 4J - was Thread.yield() - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sleeping"); + Sleep(0); // 4J - was Thread.yield() + PIXEndNamedEvent(); - // if (Keyboard::isKeyDown(Keyboard::KEY_F7)) Display.update(); // 4J - removed condition - PIXBeginNamedEvent(0,"Display update"); - Display::update(); - PIXEndNamedEvent(); + // if (Keyboard::isKeyDown(Keyboard::KEY_F7)) + // Display.update(); // 4J - removed condition + PIXBeginNamedEvent(0, "Display update"); + Display::update(); + PIXEndNamedEvent(); - // checkScreenshot(); // 4J - removed + // checkScreenshot(); // 4J - removed - /* 4J - removed - if (parent != NULL && !fullscreen) - { - if (parent.getWidth() != width || parent.getHeight() != height) - { - width = parent.getWidth(); - height = parent.getHeight(); - if (width <= 0) width = 1; - if (height <= 0) height = 1; + /* 4J - removed + if (parent != NULL && !fullscreen) + { + if (parent.getWidth() != width || parent.getHeight() != height) + { + width = parent.getWidth(); + height = parent.getHeight(); + if (width <= 0) width = 1; + if (height <= 0) height = 1; - resize(width, height); - } - } - */ - MemSect(31); - checkGlError(L"Post render"); - MemSect(0); - frames++; - //pause = !isClientSide() && screen != NULL && screen->isPauseScreen(); - //pause = g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()); - pause = app.IsAppPaused(); + resize(width, height); + } + } + */ + MemSect(31); + checkGlError(L"Post render"); + MemSect(0); + frames++; + // pause = !isClientSide() && screen != NULL && + // screen->isPauseScreen(); pause = g_NetworkManager.IsLocalGame() + // && g_NetworkManager.GetPlayerCount() == 1 && + // app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()); + pause = app.IsAppPaused(); #ifndef _CONTENT_PACKAGE - while (System::nanoTime() >= lastTime + 1000000000) - { - MemSect(31); - fpsString = _toString(frames) + L" fps, " + _toString(Chunk::updates) + L" chunk updates"; - MemSect(0); - Chunk::updates = 0; - lastTime += 1000000000; - frames = 0; - } + while (System::nanoTime() >= lastTime + 1000000000) { + MemSect(31); + fpsString = _toString(frames) + L" fps, " + + _toString(Chunk::updates) + L" chunk updates"; + MemSect(0); + Chunk::updates = 0; + lastTime += 1000000000; + frames = 0; + } #endif - /* - } catch (LevelConflictException e) { - this.level = null; - setLevel(null); - setScreen(new LevelConflictScreen()); - } catch (OutOfMemoryError e) { - emergencySave(); - setScreen(new OutOfMemoryScreen()); - System.gc(); - } - */ - } - /* - } catch (StopGameException e) { - } catch (Throwable e) { - emergencySave(); - e.printStackTrace(); - crash(new CrashReport("Unexpected error", e)); - } finally { - destroy(); - } - */ - } - LeaveCriticalSection(&m_setLevelCS); + /* + } catch (LevelConflictException e) { + this.level = null; + setLevel(null); + setScreen(new LevelConflictScreen()); + } catch (OutOfMemoryError e) { + emergencySave(); + setScreen(new OutOfMemoryScreen()); + System.gc(); + } + */ + } + /* + } catch (StopGameException e) { + } catch (Throwable e) { + emergencySave(); + e.printStackTrace(); + crash(new CrashReport("Unexpected error", e)); + } finally { + destroy(); + } + */ + } + LeaveCriticalSection(&m_setLevelCS); } -void Minecraft::run_end() -{ - destroy(); +void Minecraft::run_end() { destroy(); } + +void Minecraft::emergencySave() { + // 4J - lots of try/catches removed here, and garbage collector things + levelRenderer->clear(); + AABB::clearPool(); + Vec3::clearPool(); + setLevel(NULL); } -void Minecraft::emergencySave() -{ - // 4J - lots of try/catches removed here, and garbage collector things - levelRenderer->clear(); - AABB::clearPool(); - Vec3::clearPool(); - setLevel(NULL); +void Minecraft::renderFpsMeter(__int64 tickTime) { + int nsPer60Fps = 1000000000l / 60; + if (lastTimer == -1) { + lastTimer = System::nanoTime(); + } + __int64 now = System::nanoTime(); + Minecraft::tickTimes[(Minecraft::frameTimePos) & + (Minecraft::frameTimes_length - 1)] = tickTime; + Minecraft::frameTimes[(Minecraft::frameTimePos++) & + (Minecraft::frameTimes_length - 1)] = now - lastTimer; + lastTimer = now; + + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glEnable(GL_COLOR_MATERIAL); + glLoadIdentity(); + glOrtho(0, (float)width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); + + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); + t->begin(GL_QUADS); + int hh1 = (int)(nsPer60Fps / 200000); + t->color(0x20000000); + t->vertex((float)(0), (float)(height - hh1), (float)(0)); + t->vertex((float)(0), (float)(height), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1), + (float)(0)); + + t->color(0x20200000); + t->vertex((float)(0), (float)(height - hh1 * 2), (float)(0)); + t->vertex((float)(0), (float)(height - hh1), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1 * 2), + (float)(0)); + + t->end(); + __int64 totalTime = 0; + for (int i = 0; i < Minecraft::frameTimes_length; i++) { + totalTime += Minecraft::frameTimes[i]; + } + int hh = (int)(totalTime / 200000 / Minecraft::frameTimes_length); + t->begin(GL_QUADS); + t->color(0x20400000); + t->vertex((float)(0), (float)(height - hh), (float)(0)); + t->vertex((float)(0), (float)(height), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh), + (float)(0)); + t->end(); + t->begin(GL_LINES); + for (int i = 0; i < Minecraft::frameTimes_length; i++) { + int col = ((i - Minecraft::frameTimePos) & + (Minecraft::frameTimes_length - 1)) * + 255 / Minecraft::frameTimes_length; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; + if (Minecraft::frameTimes[i] > nsPer60Fps) { + t->color(0xff000000 + cc * 65536); + } else { + t->color(0xff000000 + cc * 256); + } + + __int64 time = Minecraft::frameTimes[i] / 200000; + __int64 time2 = Minecraft::tickTimes[i] / 200000; + + t->vertex((float)(i + 0.5f), (float)(height - time + 0.5f), (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height + 0.5f), (float)(0)); + + // if (Minecraft.frameTimes[i]>nsPer60Fps) { + t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); + // } else { + // t.color(0xff808080 + cc/2 * 256); + // } + t->vertex((float)(i + 0.5f), (float)(height - time + 0.5f), (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height - (time - time2) + 0.5f), + (float)(0)); + } + t->end(); + + glEnable(GL_TEXTURE_2D); } -void Minecraft::renderFpsMeter(__int64 tickTime) -{ - int nsPer60Fps = 1000000000l / 60; - if (lastTimer == -1) - { - lastTimer = System::nanoTime(); - } - __int64 now = System::nanoTime(); - Minecraft::tickTimes[(Minecraft::frameTimePos) & (Minecraft::frameTimes_length - 1)] = tickTime; - Minecraft::frameTimes[(Minecraft::frameTimePos++) & (Minecraft::frameTimes_length - 1)] = now - lastTimer; - lastTimer = now; - - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glEnable(GL_COLOR_MATERIAL); - glLoadIdentity(); - glOrtho(0, (float)width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); - - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); - t->begin(GL_QUADS); - int hh1 = (int) (nsPer60Fps / 200000); - t->color(0x20000000); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); - - t->color(0x20200000); - t->vertex((float)(0), (float)( height - hh1 * 2), (float)( 0)); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1 * 2), (float)( 0)); - - t->end(); - __int64 totalTime = 0; - for (int i = 0; i < Minecraft::frameTimes_length; i++) - { - totalTime += Minecraft::frameTimes[i]; - } - int hh = (int) (totalTime / 200000 / Minecraft::frameTimes_length); - t->begin(GL_QUADS); - t->color(0x20400000); - t->vertex((float)(0), (float)( height - hh), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh), (float)( 0)); - t->end(); - t->begin(GL_LINES); - for (int i = 0; i < Minecraft::frameTimes_length; i++) - { - int col = ((i - Minecraft::frameTimePos) & (Minecraft::frameTimes_length - 1)) * 255 / Minecraft::frameTimes_length; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; - if (Minecraft::frameTimes[i] > nsPer60Fps) - { - t->color(0xff000000 + cc * 65536); - } - else - { - t->color(0xff000000 + cc * 256); - } - - __int64 time = Minecraft::frameTimes[i] / 200000; - __int64 time2 = Minecraft::tickTimes[i] / 200000; - - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height + 0.5f), (float)( 0)); - - // if (Minecraft.frameTimes[i]>nsPer60Fps) { - t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); - // } else { - // t.color(0xff808080 + cc/2 * 256); - // } - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - (time - time2) + 0.5f), (float)( 0)); - } - t->end(); - - glEnable(GL_TEXTURE_2D); +void Minecraft::stop() { + running = false; + // keepPolling = false; } -void Minecraft::stop() -{ - running = false; - // keepPolling = false; +void Minecraft::pauseGame() { + if (screen != NULL) return; + + // setScreen(new PauseScreen()); // 4J - TODO put back in } -void Minecraft::pauseGame() -{ - if (screen != NULL) return; +void Minecraft::resize(int width, int height) { + if (width <= 0) width = 1; + if (height <= 0) height = 1; + this->width = width; + this->height = height; - // setScreen(new PauseScreen()); // 4J - TODO put back in + if (screen != NULL) { + ScreenSizeCalculator ssc(options, width, height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + // screen->init(this, screenWidth, screenHeight); // 4J - + // TODO - put back in + } } -void Minecraft::resize(int width, int height) -{ - if (width <= 0) width = 1; - if (height <= 0) height = 1; - this->width = width; - this->height = height; - - if (screen != NULL) - { - ScreenSizeCalculator ssc(options, width, height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - // screen->init(this, screenWidth, screenHeight); // 4J - TODO - put back in - } +void Minecraft::verify() { + /* 4J - TODO + new Thread() { + public void run() { + try { + HttpURLConnection huc = (HttpURLConnection) new + URL("https://login.minecraft.net/session?name=" + user.name + "&session=" + + user.sessionId).openConnection(); huc.connect(); if (huc.getResponseCode() + == 400) { warezTime = System.currentTimeMillis(); + } + huc.disconnect(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + */ } -void Minecraft::verify() -{ - /* 4J - TODO - new Thread() { - public void run() { - try { - HttpURLConnection huc = (HttpURLConnection) new URL("https://login.minecraft.net/session?name=" + user.name + "&session=" + user.sessionId).openConnection(); - huc.connect(); - if (huc.getResponseCode() == 400) { - warezTime = System.currentTimeMillis(); - } - huc.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - */ +void Minecraft::levelTickUpdateFunc(void* pParam) { + Level* pLevel = (Level*)pParam; + pLevel->tick(); } - - - -void Minecraft::levelTickUpdateFunc(void* pParam) -{ - Level* pLevel = (Level*)pParam; - pLevel->tick(); +void Minecraft::levelTickThreadInitFunc() { + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::UseDefaultThreadStorage(); } -void Minecraft::levelTickThreadInitFunc() -{ - AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Compression::UseDefaultThreadStorage(); -} +// 4J - added bFirst parameter, which is true for the first active viewport in +// splitscreen 4J - added bUpdateTextures, which is true if the actual renderer +// textures are to be updated - this will be true for the last time this tick +// runs with bFirst true +void Minecraft::tick(bool bFirst, bool bUpdateTextures) { + int iPad = player->GetXboxPad(); + // OutputDebugString("Minecraft::tick\n"); + // 4J-PB - only tick this player's stats + stats[iPad]->tick(iPad); -// 4J - added bFirst parameter, which is true for the first active viewport in splitscreen -// 4J - added bUpdateTextures, which is true if the actual renderer textures are to be updated - this will be true for the last time this tick runs with bFirst true -void Minecraft::tick(bool bFirst, bool bUpdateTextures) -{ - int iPad=player->GetXboxPad(); - //OutputDebugString("Minecraft::tick\n"); + // Tick the opacity timer (to display the interface at default opacity for a + // certain time if the user has been navigating it) + app.TickOpacityTimer(iPad); - //4J-PB - only tick this player's stats - stats[iPad]->tick(iPad); + // 4J added + if (bFirst) levelRenderer->destroyedTileManager->tick(); - // Tick the opacity timer (to display the interface at default opacity for a certain time if the user has been navigating it) - app.TickOpacityTimer(iPad); - - // 4J added - if( bFirst ) levelRenderer->destroyedTileManager->tick(); - - gui->tick(); - gameRenderer->pick(1); + gui->tick(); + gameRenderer->pick(1); #if 0 // 4J - removed - we don't use ChunkCache anymore if (player != NULL) @@ -2185,1300 +2326,1365 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #endif - // soundEngine.playMusicTick(); - - if (!pause && level != NULL) gameMode->tick(); - MemSect(31); - glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_TERRAIN));//L"/terrain.png")); - MemSect(0); - if( bFirst ) - { - PIXBeginNamedEvent(0,"Texture tick"); - if (!pause) textures->tick(bUpdateTextures); - PIXEndNamedEvent(); - } - - /* - * if (serverConnection != null && !(screen instanceof ErrorScreen)) { - * if (!serverConnection.isConnected()) { - * progressRenderer.progressStart("Connecting.."); - * progressRenderer.progressStagePercentage(0); } else { - * serverConnection.tick(); serverConnection.sendPosition(player); } } - */ - if (screen == NULL && player != NULL ) - { - if (player->getHealth() <= 0 && !ui.GetMenuDisplayed(iPad) ) - { - setScreen(NULL); - } - else if (player->isSleeping() && level != NULL && level->isClientSide) - { - // setScreen(new InBedChatScreen()); // 4J - TODO put back in - } - } - else if (screen != NULL && (dynamic_cast(screen)!=NULL) && !player->isSleeping()) - { - setScreen(NULL); - } - - if (screen != NULL) - { - player->missTime = 10000; - player->lastClickTick[0] = ticks + 10000; - player->lastClickTick[1] = ticks + 10000; - } - - if (screen != NULL) - { - screen->updateEvents(); - if (screen != NULL) - { - screen->particles->tick(); - screen->tick(); - } - } - - if (screen == NULL && !ui.GetMenuDisplayed(iPad) ) - { - // 4J-PB - add some tooltips if required - int iA=-1, iB=-1, iX, iY=IDS_CONTROLS_INVENTORY, iLT=-1, iRT=-1, iLB=-1, iRB=-1; - - if(player->abilities.instabuild) - { - iX=IDS_TOOLTIPS_CREATIVE; - } - else - { - iX=IDS_CONTROLS_CRAFTING; - } - // control scheme remapping can move the Action button, so we need to check this - int *piAction; - int *piJump; - int *piUse; - - unsigned int uiAction = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_ACTION ); - unsigned int uiJump = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_JUMP ); - unsigned int uiUse = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_USE ); - - // Also need to handle PS3 having swapped triggers/bumpers - switch(uiAction) - { - case _360_JOY_BUTTON_RT: - piAction=&iRT; - break; - case _360_JOY_BUTTON_LT: - piAction=&iLT; - break; - case _360_JOY_BUTTON_LB: - piAction=&iLB; - break; - case _360_JOY_BUTTON_RB: - piAction=&iRB; - break; - case _360_JOY_BUTTON_A: - default: - piAction=&iA; - break; - } - - switch(uiJump) - { - case _360_JOY_BUTTON_LT: - piJump=&iLT; - break; - case _360_JOY_BUTTON_RT: - piJump=&iRT; - break; - case _360_JOY_BUTTON_LB: - piJump=&iLB; - break; - case _360_JOY_BUTTON_RB: - piJump=&iRB; - break; - case _360_JOY_BUTTON_A: - default: - piJump=&iA; - break; - } - - switch(uiUse) - { - case _360_JOY_BUTTON_LB: - piUse=&iLB; - break; - case _360_JOY_BUTTON_RB: - piUse=&iRB; - break; - case _360_JOY_BUTTON_LT: - piUse=&iLT; - break; - case _360_JOY_BUTTON_RT: - default: - piUse=&iRT; - break; - } - - if (player->isUnderLiquid(Material::water)) - { - *piJump=IDS_TOOLTIPS_SWIMUP; - } - else - { - *piJump=-1; - } - - *piUse=-1; - *piAction=-1; - - // 4J-PB another special case for when the player is sleeping in a bed - if (player->isSleeping() && (level != NULL) && level->isClientSide) - { - *piUse=IDS_TOOLTIPS_WAKEUP; - } - else - { - // no hit result, but we may have something in our hand that we can do something with - std::shared_ptr itemInstance = player->inventory->getSelected(); - - // 4J-JEV: Moved all this here to avoid having it in 3 different places. - if (itemInstance) - { - // 4J-PB - very special case for boat and empty bucket and glass bottle and more - bool bUseItem = gameMode->useItem(player, level, itemInstance, true); - - switch (itemInstance->getItem()->id) - { - // food - case Item::potatoBaked_Id: - case Item::potato_Id: - case Item::pumpkinPie_Id: - case Item::potatoPoisonous_Id: - case Item::carrotGolden_Id: - case Item::carrots_Id: - case Item::mushroomStew_Id: - case Item::apple_Id: - case Item::bread_Id: - case Item::porkChop_raw_Id: - case Item::porkChop_cooked_Id: - case Item::apple_gold_Id: - case Item::fish_raw_Id: - case Item::fish_cooked_Id: - case Item::cookie_Id: - case Item::beef_cooked_Id: - case Item::beef_raw_Id: - case Item::chicken_cooked_Id: - case Item::chicken_raw_Id: - case Item::melon_Id: - case Item::rotten_flesh_Id: - case Item::spiderEye_Id: - // Check that we are actually hungry so will eat this item - { - FoodItem *food = (FoodItem *)itemInstance->getItem(); - if (food != NULL && food->canEat(player)) - { - *piUse=IDS_TOOLTIPS_EAT; - } - } - break; - - case Item::milk_Id: - *piUse=IDS_TOOLTIPS_DRINK; - break; - - case Item::fishingRod_Id: // use - *piUse=IDS_TOOLTIPS_USE; - break; - - case Item::egg_Id: // throw - case Item::snowBall_Id: - *piUse=IDS_TOOLTIPS_THROW; - break; - - case Item::bow_Id: // draw or release - if ( player->abilities.instabuild || player->inventory->hasResource(Item::arrow_Id) ) - { - if (player->isUsingItem()) *piUse=IDS_TOOLTIPS_RELEASE_BOW; - else *piUse=IDS_TOOLTIPS_DRAW_BOW; - } - break; - - case Item::sword_wood_Id: - case Item::sword_stone_Id: - case Item::sword_iron_Id: - case Item::sword_diamond_Id: - case Item::sword_gold_Id: - *piUse=IDS_TOOLTIPS_BLOCK; - break; - - case Item::bucket_empty_Id: - case Item::glassBottle_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_COLLECT; - break; - - case Item::boat_Id: - case Tile::waterLily_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_PLACE; - break; - - case Item::potion_Id: - if (bUseItem) - { - if (MACRO_POTION_IS_SPLASH(itemInstance->getAuxValue())) *piUse=IDS_TOOLTIPS_THROW; - else *piUse=IDS_TOOLTIPS_DRINK; - } - break; - - case Item::enderPearl_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_THROW; - break; - - case Item::eyeOfEnder_Id: - // This will only work if there is a stronghold in this dimension - if ( bUseItem && (level->dimension->id==0) && level->getLevelData()->getHasStronghold() ) - { - *piUse=IDS_TOOLTIPS_THROW; - } - break; - - case Item::expBottle_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_THROW; - break; - } - } - - if (hitResult!=NULL) - { - switch(hitResult->type) - { - case HitResult::TILE: - { - int x,y,z; - x=hitResult->x; - y=hitResult->y; - z=hitResult->z; - int face = hitResult->f; - - int iTileID=level->getTile(x,y ,z ); - int iData = level->getData(x, y, z); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints - gameMode->getTutorial()->onLookAt(iTileID,iData); - } - - // 4J-PB - Call the useItemOn with the TestOnly flag set - bool bUseItemOn=gameMode->useItemOn(player, level, itemInstance, x, y, z, face, hitResult->pos, true); - - /* 4J-Jev: - * Moved this here so we have item tooltips to fallback on - * for noteblocks, enderportals and flowerpots in case of non-standard items. - * (ie. ignite behaviour) - */ - if (bUseItemOn && itemInstance!=NULL) - { - switch (itemInstance->getItem()->id) - { - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::tallgrass_Id: - case Tile::cactus_Id: - case Tile::sapling_Id: - case Tile::reeds_Id: - case Tile::flower_Id: - case Tile::rose_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - // Things to USE - case Item::hoe_wood_Id: - case Item::hoe_stone_Id: - case Item::hoe_iron_Id: - case Item::hoe_diamond_Id: - case Item::hoe_gold_Id: - *piUse=IDS_TOOLTIPS_TILL; - break; - - case Item::seeds_wheat_Id: - case Item::netherStalkSeeds_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - case Item::bucket_empty_Id: - switch(iTileID) - { - // can collect lava or water in the empty bucket - case Tile::water_Id: - case Tile::calmWater_Id: - case Tile::lava_Id: - case Tile::calmLava_Id: - *piUse=IDS_TOOLTIPS_COLLECT; - break; - } - break; - - case Item::bucket_lava_Id: - case Item::bucket_water_Id: - *piUse=IDS_TOOLTIPS_EMPTY; - break; - - case Item::dye_powder_Id: - // bonemeal grows various plants - if (itemInstance->getAuxValue() == DyePowderItem::WHITE) - { - switch(iTileID) - { - case Tile::sapling_Id: - case Tile::crops_Id: - case Tile::grass_Id: - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::melonStem_Id: - case Tile::pumpkinStem_Id: - case Tile::carrots_Id: - case Tile::potatoes_Id: - *piUse=IDS_TOOLTIPS_GROW; - break; - } - } - break; - - case Item::painting_Id: - *piUse=IDS_TOOLTIPS_HANG; - break; - - case Item::flintAndSteel_Id: - case Item::fireball_Id: - *piUse=IDS_TOOLTIPS_IGNITE; - break; - - default: - *piUse=IDS_TOOLTIPS_PLACE; - break; - } - } - - switch(iTileID) - { - case Tile::anvil_Id: - case Tile::enchantTable_Id: - case Tile::brewingStand_Id: - case Tile::workBench_Id: - case Tile::furnace_Id: - case Tile::furnace_lit_Id: - case Tile::door_wood_Id: - case Tile::dispenser_Id: - case Tile::lever_Id: - case Tile::button_stone_Id: - case Tile::button_wood_Id: - case Tile::trapdoor_Id: - case Tile::fenceGate_Id: - *piAction=IDS_TOOLTIPS_MINE; - *piUse=IDS_TOOLTIPS_USE; - break; - - case Tile::goldenRail_Id: - case Tile::detectorRail_Id: - case Tile::rail_Id: - if (bUseItemOn) *piUse=IDS_TOOLTIPS_PLACE; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::chest_Id: - case Tile::enderChest_Id: - *piUse=IDS_TOOLTIPS_OPEN; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::bed_Id: - if (bUseItemOn) *piUse=IDS_TOOLTIPS_SLEEP; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::musicBlock_Id: - // if in creative mode, we will mine - if (player->abilities.instabuild) *piAction=IDS_TOOLTIPS_MINE; - else *piAction=IDS_TOOLTIPS_PLAY; - *piUse=IDS_TOOLTIPS_CHANGEPITCH; - break; - - case Tile::sign_Id: - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::cauldron_Id: - // special case for a cauldron of water and an empty bottle - if (itemInstance) - { - int iID=itemInstance->getItem()->id; - int currentData = level->getData(x, y, z); - if ((iID==Item::glassBottle_Id) && (currentData > 0)) - { - *piUse=IDS_TOOLTIPS_COLLECT; - } - } - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::cake_Id: - if (player->abilities.instabuild) // if in creative mode, we will mine - { - *piAction=IDS_TOOLTIPS_MINE; - } - else - { - if (player->getFoodData()->needsFood() ) // 4J-JEV: Changed from healthto hunger. - { - *piAction=IDS_TOOLTIPS_EAT; - *piUse=IDS_TOOLTIPS_EAT; - } - else - { - *piAction=IDS_TOOLTIPS_MINE; - } - } - break; - - case Tile::recordPlayer_Id: - if (!bUseItemOn && itemInstance!=NULL) - { - int iID=itemInstance->getItem()->id; - if ( (iID>=Item::record_01_Id) && (iID<=Item::record_12_Id) ) - { - *piUse=IDS_TOOLTIPS_PLAY; - } - *piAction=IDS_TOOLTIPS_MINE; - } - else - { - if (Tile::recordPlayer->TestUse(level, x, y, z, player)) // means we can eject - { - *piUse=IDS_TOOLTIPS_EJECT; - } - *piAction=IDS_TOOLTIPS_MINE; - } - break; - - case Tile::flowerPot_Id: - if ( !bUseItemOn && (itemInstance != NULL) && (iData == 0) ) - { - int iID = itemInstance->getItem()->id; - if (iID<256) // is it a tile? - { - switch(iID) - { - case Tile::flower_Id: - case Tile::rose_Id: - case Tile::sapling_Id: - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::cactus_Id: - case Tile::deadBush_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - case Tile::tallgrass_Id: - if (itemInstance->getAuxValue() != TallGrass::TALL_GRASS) *piUse=IDS_TOOLTIPS_PLANT; - break; - } - } - } - *piAction=IDS_TOOLTIPS_MINE; - break; - - default: - *piAction=IDS_TOOLTIPS_MINE; - break; - } - } - break; - - case HitResult::ENTITY: - eINSTANCEOF entityType = hitResult->entity->GetType(); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints - gameMode->getTutorial()->onLookAtEntity(entityType); - } - - switch(entityType) - { - case eTYPE_CHICKEN: - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - break; - - case eTYPE_COW: - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - // It's an item - switch(iID) - { - // Things to USE - case Item::bucket_empty_Id: - *piUse=IDS_TOOLTIPS_MILK; - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - break; - case eTYPE_MUSHROOMCOW: - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - // It's an item - switch(iID) - { - // Things to USE - case Item::bowl_Id: - case Item::bucket_empty_Id: // You can milk a mooshroom with either a bowl (mushroom soup) or a bucket (milk)! - *piUse=IDS_TOOLTIPS_MILK; - break; - case Item::shears_Id: - { - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - if(!animal->isBaby()) *piUse=IDS_TOOLTIPS_SHEAR; - } - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - else - { - // 4J-PB - Fix for #13081 - No tooltip is displayed for hitting a cow when you have nothing in your hand - // nothing in your hand - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - } - break; - - case eTYPE_BOAT: - *piAction=IDS_TOOLTIPS_MINE; - - // are we in the boat already? - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - *piUse=IDS_TOOLTIPS_SAIL; - } - break; - case eTYPE_MINECART: - *piAction=IDS_TOOLTIPS_MINE; - // are we in the minecart already? - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - switch(std::dynamic_pointer_cast(hitResult->entity)->type) - { - case Minecart::RIDEABLE: - *piUse=IDS_TOOLTIPS_RIDE; - break; - case Minecart::CHEST: - *piUse=IDS_TOOLTIPS_OPEN; - break; - case Minecart::FURNACE: - // if you have coal, it'll go - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - if(iID==Item::coal->id) - { - *piUse=IDS_TOOLTIPS_USE; - } - else - { - *piUse=IDS_TOOLTIPS_HIT; - } - } - break; - } - } - - break; - case eTYPE_SHEEP: - // can dye a sheep - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - case Item::dye_powder_Id: - { - std::shared_ptr sheep = std::dynamic_pointer_cast(hitResult->entity); - // convert to tile-based color value (0 is white instead of black) - int newColor = ClothTile::getTileDataForItemAuxValue(heldItem->getAuxValue()); - - // can only use a dye on sheep that haven't been sheared - if(!(sheep->isSheared() && sheep->getColor() != newColor)) - { - *piUse=IDS_TOOLTIPS_DYE; - } - } - break; - case Item::shears_Id: - { - std::shared_ptr sheep = std::dynamic_pointer_cast(hitResult->entity); - - // can only shear a sheep that hasn't been sheared - if(!sheep->isSheared() ) - { - *piUse=IDS_TOOLTIPS_SHEAR; - } - } - - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - - break; - case eTYPE_PIG: - // can ride a pig - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - // does the pig have a saddle? - if(std::dynamic_pointer_cast(hitResult->entity)->hasSaddle()) - { - *piUse=IDS_TOOLTIPS_RIDE; - } - else if (!std::dynamic_pointer_cast(hitResult->entity)->isBaby()) - { - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - case Item::saddle_Id: - *piUse=IDS_TOOLTIPS_SADDLE; - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - } - } - - break; - case eTYPE_WOLF: - // can be tamed, fed, and made to sit/stand, or enter love mode - { - int iID=-1; - std::shared_ptr heldItem=nullptr; - std::shared_ptr wolf = std::dynamic_pointer_cast(hitResult->entity); - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - iID=heldItem->getItem()->id; - } - - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - switch(iID) - { - case Item::bone_Id: - if (!wolf->isAngry() && !wolf->isTame()) - { - *piUse=IDS_TOOLTIPS_TAME; - } - else if (equalsIgnoreCase(player->getUUID(), wolf->getOwnerUUID())) - { - if(wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - - break; - case Item::enderPearl_Id: - // Use is throw, so don't change the tips for the wolf - break; - case Item::dye_powder_Id: - if (wolf->isTame()) - { - if (ClothTile::getTileDataForItemAuxValue(heldItem->getAuxValue()) != wolf->getCollarColor()) - { - *piUse=IDS_TOOLTIPS_DYECOLLAR; - } - else if (wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - break; - default: - if(wolf->isTame()) - { - if(wolf->isFood(heldItem)) - { - if(wolf->GetSynchedHealth() < wolf->getMaxHealth()) - { - *piUse=IDS_TOOLTIPS_HEAL; - } - else - { - if(!wolf->isBaby() && !wolf->isInLove() && (wolf->getAge() == 0)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - // break out here - break; - } - - if (equalsIgnoreCase(player->getUUID(), wolf->getOwnerUUID())) - { - if(wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - } - break; - } - } - break; - case eTYPE_OZELOT: - { - int iID=-1; - std::shared_ptr heldItem=nullptr; - std::shared_ptr ocelot = std::dynamic_pointer_cast(hitResult->entity); - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - iID=heldItem->getItem()->id; - } - - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - if(ocelot->isTame()) - { - // 4J-PB - if you have a raw fish in your hand, you will feed the ocelot rather than have it sit/follow - if(ocelot->isFood(heldItem)) - { - if(!ocelot->isBaby()) - { - if(!ocelot->isInLove()) - { - if(ocelot->getAge() == 0) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - else - { - *piUse=IDS_TOOLTIPS_FEED; - } - } - - } - else if (equalsIgnoreCase(player->getUUID(), ocelot->getOwnerUUID())) - { - if(ocelot->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - } - else if(iID!=-1) - { - switch(iID) - { - default: - { - if(ocelot->isFood(heldItem)) *piUse=IDS_TOOLTIPS_TAME; - } - break; - } - } - } - - break; - - case eTYPE_PLAYER: - { - // Fix for #58576 - TU6: Content: Gameplay: Hit button prompt is available when attacking a host who has "Invisible" option turned on - std::shared_ptr TargetPlayer = std::dynamic_pointer_cast(hitResult->entity); - - if(!TargetPlayer->hasInvisiblePrivilege()) // This means they are invisible, not just that they have the privilege - { - if( app.GetGameHostOption(eGameHostOption_PvP) && player->isAllowedToAttackPlayers()) - { - *piAction=IDS_TOOLTIPS_HIT; - } - } - } - break; - case eTYPE_ITEM_FRAME: - { - std::shared_ptr itemFrame = std::dynamic_pointer_cast(hitResult->entity); - - // is the frame occupied? - if(itemFrame->getItem()!=NULL) - { - // rotate the item - *piUse=IDS_TOOLTIPS_ROTATE; - } - else - { - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - *piUse=IDS_TOOLTIPS_PLACE; - } - } - - *piAction=IDS_TOOLTIPS_HIT; - } - break; - case eTYPE_VILLAGER: - { - std::shared_ptr villager = std::dynamic_pointer_cast(hitResult->entity); - if (!villager->isBaby()) - { - *piUse=IDS_TOOLTIPS_TRADE; - } - *piAction=IDS_TOOLTIPS_HIT; - } - break; - case eTYPE_ZOMBIE: - { - std::shared_ptr zomb = std::dynamic_pointer_cast(hitResult->entity); - std::shared_ptr heldItem=nullptr; - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - } - - if ( zomb->isVillager() && zomb->isWeakened() //zomb->hasEffect(MobEffect::weakness) - not present on client. - && heldItem != NULL && heldItem->getItem()->id == Item::apple_gold_Id ) - { - *piUse=IDS_TOOLTIPS_CURE; - } - *piAction=IDS_TOOLTIPS_HIT; - } - break; - default: - *piAction=IDS_TOOLTIPS_HIT; - break; - } - break; - } - } - } - - ui.SetTooltips( iPad, iA,iB,iX,iY,iLT,iRT,iLB,iRB); - - int wheel = 0; - unsigned int leftTicks = InputManager.GetValue(iPad, MINECRAFT_ACTION_LEFT_SCROLL, true); - unsigned int rightTicks = InputManager.GetValue(iPad, MINECRAFT_ACTION_RIGHT_SCROLL, true); - if (leftTicks > 0 && gameMode->isInputAllowed(MINECRAFT_ACTION_LEFT_SCROLL)) { - wheel = (int)leftTicks; // positive = left - } else if (rightTicks > 0 && gameMode->isInputAllowed(MINECRAFT_ACTION_RIGHT_SCROLL)) { - wheel = -(int)rightTicks; // negative = right - } - if (wheel != 0) - { - player->inventory->swapPaint(wheel); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we are using so that we can give hints - gameMode->getTutorial()->onSelectedItemChanged(player->inventory->getSelected()); - } - - // Update presence - player->updateRichPresence(); - - if (options->isFlying) - { - if (wheel > 0) wheel = 1; - if (wheel < 0) wheel = -1; - - options->flySpeed += wheel * .25f; - } - } - if( gameMode->isInputAllowed(MINECRAFT_ACTION_ACTION) ) - { - if((player->ullButtonsPressed&(1LL<handleMouseClick(0); - player->lastClickTick[0] = ticks; - } - - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) && ticks - player->lastClickTick[0] >= timer->ticksPerSecond / 4) - { - //printf("MINECRAFT_ACTION_ACTION ButtonDown"); - player->handleMouseClick(0); - player->lastClickTick[0] = ticks; - } - - if(InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) ) - { - player->handleMouseDown(0, true ); - } - else - { - player->handleMouseDown(0, false ); - } - } - - // 4J Stu - This is how we used to handle the USE action. It has now been replaced with the block below which is more like the way the Java game does it, - // however we may find that the way we had it previously is more fun to play. - /* - if ((InputManager.GetValue(iPad, MINECRAFT_ACTION_USE,true)>0) && gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) - { - handleMouseClick(1); - lastClickTick = ticks; - } - */ - if( player->isUsingItem() ) - { - if(!InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) gameMode->releaseUsingItem(player); - } - else if( gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) - { - if( player->abilities.instabuild ) - { - // 4J - attempt to handle click in special creative mode fashion if possible (used for placing blocks at regular intervals) - bool didClick = player->creativeModeHandleMouseClick(1, InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) ); - // If this handler has put us in lastClick_oldRepeat mode then it is because we aren't placing blocks - behave largely as the code used to - if( player->lastClickState == LocalPlayer::lastClick_oldRepeat ) - { - // If we've already handled the click in creativeModeHandleMouseClick then just record the time of this click - if( didClick ) - { - player->lastClickTick[1] = ticks; - } - else - { - // Otherwise just the original game code for handling autorepeat - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) && ticks - player->lastClickTick[1] >= timer->ticksPerSecond / 4) - { - player->handleMouseClick(1); - player->lastClickTick[1] = ticks; - } - } - } - } - else - { - // Consider as a click if we've had a period of not pressing the button, or we've reached auto-repeat time since the last time - // Auto-repeat is only considered if we aren't riding or sprinting, to avoid photo sensitivity issues when placing fire whilst doing fast things - // Also disable repeat when the player is sleeping to stop the waking up right after using the bed - bool firstClick = ( player->lastClickTick[1] == 0 ); - bool autoRepeat = ticks - player->lastClickTick[1] >= timer->ticksPerSecond / 4; - if ( player->isRiding() || player->isSprinting() || player->isSleeping() ) autoRepeat = false; - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) ) - { - // If the player has just exited a bed, then delay the time before a repeat key is allowed without releasing - if(player->isSleeping() ) player->lastClickTick[1] = ticks + (timer->ticksPerSecond * 2); - if( firstClick || autoRepeat ) - { - bool wasSleeping = player->isSleeping(); - - player->handleMouseClick(1); - - // If the player has just exited a bed, then delay the time before a repeat key is allowed without releasing - if(wasSleeping) player->lastClickTick[1] = ticks + (timer->ticksPerSecond * 2); - else player->lastClickTick[1] = ticks; - } - } - else - { - player->lastClickTick[1] = 0; - } - } - } - - if(app.DebugSettingsOn()) - { - if (player->ullButtonsPressed & ( 1LL << MINECRAFT_ACTION_CHANGE_SKIN) ) - { - player->ChangePlayerSkin(); - } - } - - if (player->missTime > 0) player->missTime--; + // soundEngine.playMusicTick(); + + if (!pause && level != NULL) gameMode->tick(); + MemSect(31); + glBindTexture(GL_TEXTURE_2D, + textures->loadTexture(TN_TERRAIN)); // L"/terrain.png")); + MemSect(0); + if (bFirst) { + PIXBeginNamedEvent(0, "Texture tick"); + if (!pause) textures->tick(bUpdateTextures); + PIXEndNamedEvent(); + } + + /* + * if (serverConnection != null && !(screen instanceof ErrorScreen)) { + * if (!serverConnection.isConnected()) { + * progressRenderer.progressStart("Connecting.."); + * progressRenderer.progressStagePercentage(0); } else { + * serverConnection.tick(); serverConnection.sendPosition(player); } } + */ + if (screen == NULL && player != NULL) { + if (player->getHealth() <= 0 && !ui.GetMenuDisplayed(iPad)) { + setScreen(NULL); + } else if (player->isSleeping() && level != NULL && + level->isClientSide) { + // setScreen(new InBedChatScreen()); // 4J - + // TODO put back in + } + } else if (screen != NULL && + (dynamic_cast(screen) != NULL) && + !player->isSleeping()) { + setScreen(NULL); + } + + if (screen != NULL) { + player->missTime = 10000; + player->lastClickTick[0] = ticks + 10000; + player->lastClickTick[1] = ticks + 10000; + } + + if (screen != NULL) { + screen->updateEvents(); + if (screen != NULL) { + screen->particles->tick(); + screen->tick(); + } + } + + if (screen == NULL && !ui.GetMenuDisplayed(iPad)) { + // 4J-PB - add some tooltips if required + int iA = -1, iB = -1, iX, iY = IDS_CONTROLS_INVENTORY, iLT = -1, + iRT = -1, iLB = -1, iRB = -1; + + if (player->abilities.instabuild) { + iX = IDS_TOOLTIPS_CREATIVE; + } else { + iX = IDS_CONTROLS_CRAFTING; + } + // control scheme remapping can move the Action button, so we need to + // check this + int* piAction; + int* piJump; + int* piUse; + + unsigned int uiAction = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_ACTION); + unsigned int uiJump = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_JUMP); + unsigned int uiUse = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_USE); + + // Also need to handle PS3 having swapped triggers/bumpers + switch (uiAction) { + case _360_JOY_BUTTON_RT: + piAction = &iRT; + break; + case _360_JOY_BUTTON_LT: + piAction = &iLT; + break; + case _360_JOY_BUTTON_LB: + piAction = &iLB; + break; + case _360_JOY_BUTTON_RB: + piAction = &iRB; + break; + case _360_JOY_BUTTON_A: + default: + piAction = &iA; + break; + } + + switch (uiJump) { + case _360_JOY_BUTTON_LT: + piJump = &iLT; + break; + case _360_JOY_BUTTON_RT: + piJump = &iRT; + break; + case _360_JOY_BUTTON_LB: + piJump = &iLB; + break; + case _360_JOY_BUTTON_RB: + piJump = &iRB; + break; + case _360_JOY_BUTTON_A: + default: + piJump = &iA; + break; + } + + switch (uiUse) { + case _360_JOY_BUTTON_LB: + piUse = &iLB; + break; + case _360_JOY_BUTTON_RB: + piUse = &iRB; + break; + case _360_JOY_BUTTON_LT: + piUse = &iLT; + break; + case _360_JOY_BUTTON_RT: + default: + piUse = &iRT; + break; + } + + if (player->isUnderLiquid(Material::water)) { + *piJump = IDS_TOOLTIPS_SWIMUP; + } else { + *piJump = -1; + } + + *piUse = -1; + *piAction = -1; + + // 4J-PB another special case for when the player is sleeping in a bed + if (player->isSleeping() && (level != NULL) && level->isClientSide) { + *piUse = IDS_TOOLTIPS_WAKEUP; + } else { + // no hit result, but we may have something in our hand that we can + // do something with + std::shared_ptr itemInstance = + player->inventory->getSelected(); + + // 4J-JEV: Moved all this here to avoid having it in 3 different + // places. + if (itemInstance) { + // 4J-PB - very special case for boat and empty bucket and glass + // bottle and more + bool bUseItem = + gameMode->useItem(player, level, itemInstance, true); + + switch (itemInstance->getItem()->id) { + // food + case Item::potatoBaked_Id: + case Item::potato_Id: + case Item::pumpkinPie_Id: + case Item::potatoPoisonous_Id: + case Item::carrotGolden_Id: + case Item::carrots_Id: + case Item::mushroomStew_Id: + case Item::apple_Id: + case Item::bread_Id: + case Item::porkChop_raw_Id: + case Item::porkChop_cooked_Id: + case Item::apple_gold_Id: + case Item::fish_raw_Id: + case Item::fish_cooked_Id: + case Item::cookie_Id: + case Item::beef_cooked_Id: + case Item::beef_raw_Id: + case Item::chicken_cooked_Id: + case Item::chicken_raw_Id: + case Item::melon_Id: + case Item::rotten_flesh_Id: + case Item::spiderEye_Id: + // Check that we are actually hungry so will eat this + // item + { + FoodItem* food = (FoodItem*)itemInstance->getItem(); + if (food != NULL && food->canEat(player)) { + *piUse = IDS_TOOLTIPS_EAT; + } + } + break; + + case Item::milk_Id: + *piUse = IDS_TOOLTIPS_DRINK; + break; + + case Item::fishingRod_Id: // use + *piUse = IDS_TOOLTIPS_USE; + break; + + case Item::egg_Id: // throw + case Item::snowBall_Id: + *piUse = IDS_TOOLTIPS_THROW; + break; + + case Item::bow_Id: // draw or release + if (player->abilities.instabuild || + player->inventory->hasResource(Item::arrow_Id)) { + if (player->isUsingItem()) + *piUse = IDS_TOOLTIPS_RELEASE_BOW; + else + *piUse = IDS_TOOLTIPS_DRAW_BOW; + } + break; + + case Item::sword_wood_Id: + case Item::sword_stone_Id: + case Item::sword_iron_Id: + case Item::sword_diamond_Id: + case Item::sword_gold_Id: + *piUse = IDS_TOOLTIPS_BLOCK; + break; + + case Item::bucket_empty_Id: + case Item::glassBottle_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_COLLECT; + break; + + case Item::boat_Id: + case Tile::waterLily_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_PLACE; + break; + + case Item::potion_Id: + if (bUseItem) { + if (MACRO_POTION_IS_SPLASH( + itemInstance->getAuxValue())) + *piUse = IDS_TOOLTIPS_THROW; + else + *piUse = IDS_TOOLTIPS_DRINK; + } + break; + + case Item::enderPearl_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_THROW; + break; + + case Item::eyeOfEnder_Id: + // This will only work if there is a stronghold in this + // dimension + if (bUseItem && (level->dimension->id == 0) && + level->getLevelData()->getHasStronghold()) { + *piUse = IDS_TOOLTIPS_THROW; + } + break; + + case Item::expBottle_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_THROW; + break; + } + } + + if (hitResult != NULL) { + switch (hitResult->type) { + case HitResult::TILE: { + int x, y, z; + x = hitResult->x; + y = hitResult->y; + z = hitResult->z; + int face = hitResult->f; + + int iTileID = level->getTile(x, y, z); + int iData = level->getData(x, y, z); + + if (gameMode != NULL && + gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to + // record what items we look at so that we can give + // hints + gameMode->getTutorial()->onLookAt(iTileID, iData); + } + + // 4J-PB - Call the useItemOn with the TestOnly flag set + bool bUseItemOn = gameMode->useItemOn( + player, level, itemInstance, x, y, z, face, + hitResult->pos, true); + + /* 4J-Jev: + * Moved this here so we have item tooltips to + * fallback on for noteblocks, enderportals and + * flowerpots in case of non-standard items. (ie. ignite + * behaviour) + */ + if (bUseItemOn && itemInstance != NULL) { + switch (itemInstance->getItem()->id) { + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::tallgrass_Id: + case Tile::cactus_Id: + case Tile::sapling_Id: + case Tile::reeds_Id: + case Tile::flower_Id: + case Tile::rose_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + // Things to USE + case Item::hoe_wood_Id: + case Item::hoe_stone_Id: + case Item::hoe_iron_Id: + case Item::hoe_diamond_Id: + case Item::hoe_gold_Id: + *piUse = IDS_TOOLTIPS_TILL; + break; + + case Item::seeds_wheat_Id: + case Item::netherStalkSeeds_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + case Item::bucket_empty_Id: + switch (iTileID) { + // can collect lava or water in the + // empty bucket + case Tile::water_Id: + case Tile::calmWater_Id: + case Tile::lava_Id: + case Tile::calmLava_Id: + *piUse = IDS_TOOLTIPS_COLLECT; + break; + } + break; + + case Item::bucket_lava_Id: + case Item::bucket_water_Id: + *piUse = IDS_TOOLTIPS_EMPTY; + break; + + case Item::dye_powder_Id: + // bonemeal grows various plants + if (itemInstance->getAuxValue() == + DyePowderItem::WHITE) { + switch (iTileID) { + case Tile::sapling_Id: + case Tile::crops_Id: + case Tile::grass_Id: + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::melonStem_Id: + case Tile::pumpkinStem_Id: + case Tile::carrots_Id: + case Tile::potatoes_Id: + *piUse = IDS_TOOLTIPS_GROW; + break; + } + } + break; + + case Item::painting_Id: + *piUse = IDS_TOOLTIPS_HANG; + break; + + case Item::flintAndSteel_Id: + case Item::fireball_Id: + *piUse = IDS_TOOLTIPS_IGNITE; + break; + + default: + *piUse = IDS_TOOLTIPS_PLACE; + break; + } + } + + switch (iTileID) { + case Tile::anvil_Id: + case Tile::enchantTable_Id: + case Tile::brewingStand_Id: + case Tile::workBench_Id: + case Tile::furnace_Id: + case Tile::furnace_lit_Id: + case Tile::door_wood_Id: + case Tile::dispenser_Id: + case Tile::lever_Id: + case Tile::button_stone_Id: + case Tile::button_wood_Id: + case Tile::trapdoor_Id: + case Tile::fenceGate_Id: + *piAction = IDS_TOOLTIPS_MINE; + *piUse = IDS_TOOLTIPS_USE; + break; + + case Tile::goldenRail_Id: + case Tile::detectorRail_Id: + case Tile::rail_Id: + if (bUseItemOn) *piUse = IDS_TOOLTIPS_PLACE; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::chest_Id: + case Tile::enderChest_Id: + *piUse = IDS_TOOLTIPS_OPEN; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::bed_Id: + if (bUseItemOn) *piUse = IDS_TOOLTIPS_SLEEP; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::musicBlock_Id: + // if in creative mode, we will mine + if (player->abilities.instabuild) + *piAction = IDS_TOOLTIPS_MINE; + else + *piAction = IDS_TOOLTIPS_PLAY; + *piUse = IDS_TOOLTIPS_CHANGEPITCH; + break; + + case Tile::sign_Id: + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::cauldron_Id: + // special case for a cauldron of water and an + // empty bottle + if (itemInstance) { + int iID = itemInstance->getItem()->id; + int currentData = level->getData(x, y, z); + if ((iID == Item::glassBottle_Id) && + (currentData > 0)) { + *piUse = IDS_TOOLTIPS_COLLECT; + } + } + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::cake_Id: + if (player->abilities + .instabuild) // if in creative mode, we + // will mine + { + *piAction = IDS_TOOLTIPS_MINE; + } else { + if (player->getFoodData() + ->needsFood()) // 4J-JEV: Changed + // from healthto + // hunger. + { + *piAction = IDS_TOOLTIPS_EAT; + *piUse = IDS_TOOLTIPS_EAT; + } else { + *piAction = IDS_TOOLTIPS_MINE; + } + } + break; + + case Tile::recordPlayer_Id: + if (!bUseItemOn && itemInstance != NULL) { + int iID = itemInstance->getItem()->id; + if ((iID >= Item::record_01_Id) && + (iID <= Item::record_12_Id)) { + *piUse = IDS_TOOLTIPS_PLAY; + } + *piAction = IDS_TOOLTIPS_MINE; + } else { + if (Tile::recordPlayer->TestUse( + level, x, y, z, + player)) // means we can eject + { + *piUse = IDS_TOOLTIPS_EJECT; + } + *piAction = IDS_TOOLTIPS_MINE; + } + break; + + case Tile::flowerPot_Id: + if (!bUseItemOn && (itemInstance != NULL) && + (iData == 0)) { + int iID = itemInstance->getItem()->id; + if (iID < 256) // is it a tile? + { + switch (iID) { + case Tile::flower_Id: + case Tile::rose_Id: + case Tile::sapling_Id: + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::cactus_Id: + case Tile::deadBush_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + case Tile::tallgrass_Id: + if (itemInstance + ->getAuxValue() != + TallGrass::TALL_GRASS) + *piUse = IDS_TOOLTIPS_PLANT; + break; + } + } + } + *piAction = IDS_TOOLTIPS_MINE; + break; + + default: + *piAction = IDS_TOOLTIPS_MINE; + break; + } + } break; + + case HitResult::ENTITY: + eINSTANCEOF entityType = hitResult->entity->GetType(); + + if (gameMode != NULL && + gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to + // record what items we look at so that we can give + // hints + gameMode->getTutorial()->onLookAtEntity(entityType); + } + + switch (entityType) { + case eTYPE_CHICKEN: + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + break; + + case eTYPE_COW: + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + // It's an item + switch (iID) { + // Things to USE + case Item::bucket_empty_Id: + *piUse = IDS_TOOLTIPS_MILK; + break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + break; + case eTYPE_MUSHROOMCOW: + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + // It's an item + switch (iID) { + // Things to USE + case Item::bowl_Id: + case Item:: + bucket_empty_Id: // You can milk a + // mooshroom with + // either a bowl + // (mushroom soup) + // or a bucket + // (milk)! + *piUse = IDS_TOOLTIPS_MILK; + break; + case Item::shears_Id: { + if (player + ->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + if (!animal->isBaby()) + *piUse = IDS_TOOLTIPS_SHEAR; + } break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } else { + // 4J-PB - Fix for #13081 - No tooltip is + // displayed for hitting a cow when you have + // nothing in your hand nothing in your hand + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + } + break; + + case eTYPE_BOAT: + *piAction = IDS_TOOLTIPS_MINE; + + // are we in the boat already? + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + *piUse = IDS_TOOLTIPS_SAIL; + } + break; + case eTYPE_MINECART: + *piAction = IDS_TOOLTIPS_MINE; + // are we in the minecart already? + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + switch (std::dynamic_pointer_cast( + hitResult->entity) + ->type) { + case Minecart::RIDEABLE: + *piUse = IDS_TOOLTIPS_RIDE; + break; + case Minecart::CHEST: + *piUse = IDS_TOOLTIPS_OPEN; + break; + case Minecart::FURNACE: + // if you have coal, it'll go + // is there an object in hand? + if (player->inventory + ->IsHeldItem()) { + std::shared_ptr + heldItem = + player->inventory + ->getSelected(); + int iID = + heldItem->getItem()->id; + + if (iID == Item::coal->id) { + *piUse = IDS_TOOLTIPS_USE; + } else { + *piUse = IDS_TOOLTIPS_HIT; + } + } + break; + } + } + + break; + case eTYPE_SHEEP: + // can dye a sheep + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + case Item::dye_powder_Id: { + std::shared_ptr sheep = + std::dynamic_pointer_cast< + Sheep>(hitResult->entity); + // convert to tile-based color value + // (0 is white instead of black) + int newColor = ClothTile:: + getTileDataForItemAuxValue( + heldItem->getAuxValue()); + + // can only use a dye on sheep that + // haven't been sheared + if (!(sheep->isSheared() && + sheep->getColor() != + newColor)) { + *piUse = IDS_TOOLTIPS_DYE; + } + } break; + case Item::shears_Id: { + std::shared_ptr sheep = + std::dynamic_pointer_cast< + Sheep>(hitResult->entity); + + // can only shear a sheep that + // hasn't been sheared + if (!sheep->isSheared()) { + *piUse = IDS_TOOLTIPS_SHEAR; + } + } + + break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + + break; + case eTYPE_PIG: + // can ride a pig + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + // does the pig have a saddle? + if (std::dynamic_pointer_cast( + hitResult->entity) + ->hasSaddle()) { + *piUse = IDS_TOOLTIPS_RIDE; + } else if (!std::dynamic_pointer_cast( + hitResult->entity) + ->isBaby()) { + if (player->inventory->IsHeldItem()) { + std::shared_ptr + heldItem = player->inventory + ->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + case Item::saddle_Id: + *piUse = + IDS_TOOLTIPS_SADDLE; + break; + default: { + std::shared_ptr + animal = std:: + dynamic_pointer_cast< + Animal>( + hitResult + ->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == + 0) && + animal->isFood( + heldItem)) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + } + } + + break; + case eTYPE_WOLF: + // can be tamed, fed, and made to sit/stand, or + // enter love mode + { + int iID = -1; + std::shared_ptr heldItem = + nullptr; + std::shared_ptr wolf = + std::dynamic_pointer_cast( + hitResult->entity); + + if (player->inventory->IsHeldItem()) { + heldItem = + player->inventory->getSelected(); + iID = heldItem->getItem()->id; + } + + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + switch (iID) { + case Item::bone_Id: + if (!wolf->isAngry() && + !wolf->isTame()) { + *piUse = IDS_TOOLTIPS_TAME; + } else if ( + equalsIgnoreCase( + player->getUUID(), + wolf->getOwnerUUID())) { + if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + + break; + case Item::enderPearl_Id: + // Use is throw, so don't change the + // tips for the wolf + break; + case Item::dye_powder_Id: + if (wolf->isTame()) { + if (ClothTile:: + getTileDataForItemAuxValue( + heldItem + ->getAuxValue()) != + wolf->getCollarColor()) { + *piUse = + IDS_TOOLTIPS_DYECOLLAR; + } else if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + break; + default: + if (wolf->isTame()) { + if (wolf->isFood(heldItem)) { + if (wolf->GetSynchedHealth() < + wolf->getMaxHealth()) { + *piUse = + IDS_TOOLTIPS_HEAL; + } else { + if (!wolf->isBaby() && + !wolf->isInLove() && + (wolf->getAge() == + 0)) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } + // break out here + break; + } + + if (equalsIgnoreCase( + player->getUUID(), + wolf->getOwnerUUID())) { + if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = + IDS_TOOLTIPS_SIT; + } + } + } + break; + } + } + break; + case eTYPE_OZELOT: { + int iID = -1; + std::shared_ptr heldItem = + nullptr; + std::shared_ptr ocelot = + std::dynamic_pointer_cast( + hitResult->entity); + + if (player->inventory->IsHeldItem()) { + heldItem = player->inventory->getSelected(); + iID = heldItem->getItem()->id; + } + + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + if (ocelot->isTame()) { + // 4J-PB - if you have a raw fish in your + // hand, you will feed the ocelot rather + // than have it sit/follow + if (ocelot->isFood(heldItem)) { + if (!ocelot->isBaby()) { + if (!ocelot->isInLove()) { + if (ocelot->getAge() == 0) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } else { + *piUse = IDS_TOOLTIPS_FEED; + } + } + + } else if (equalsIgnoreCase( + player->getUUID(), + ocelot->getOwnerUUID())) { + if (ocelot->isSitting()) { + *piUse = IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + } else if (iID != -1) { + switch (iID) { + default: { + if (ocelot->isFood(heldItem)) + *piUse = IDS_TOOLTIPS_TAME; + } break; + } + } + } + + break; + + case eTYPE_PLAYER: { + // Fix for #58576 - TU6: Content: Gameplay: Hit + // button prompt is available when attacking a + // host who has "Invisible" option turned on + std::shared_ptr TargetPlayer = + std::dynamic_pointer_cast( + hitResult->entity); + + if (!TargetPlayer + ->hasInvisiblePrivilege()) // This + // means + // they are + // invisible, + // not just + // that + // they + // have the + // privilege + { + if (app.GetGameHostOption( + eGameHostOption_PvP) && + player->isAllowedToAttackPlayers()) { + *piAction = IDS_TOOLTIPS_HIT; + } + } + } break; + case eTYPE_ITEM_FRAME: { + std::shared_ptr itemFrame = + std::dynamic_pointer_cast( + hitResult->entity); + + // is the frame occupied? + if (itemFrame->getItem() != NULL) { + // rotate the item + *piUse = IDS_TOOLTIPS_ROTATE; + } else { + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + *piUse = IDS_TOOLTIPS_PLACE; + } + } + + *piAction = IDS_TOOLTIPS_HIT; + } break; + case eTYPE_VILLAGER: { + std::shared_ptr villager = + std::dynamic_pointer_cast( + hitResult->entity); + if (!villager->isBaby()) { + *piUse = IDS_TOOLTIPS_TRADE; + } + *piAction = IDS_TOOLTIPS_HIT; + } break; + case eTYPE_ZOMBIE: { + std::shared_ptr zomb = + std::dynamic_pointer_cast( + hitResult->entity); + std::shared_ptr heldItem = + nullptr; + + if (player->inventory->IsHeldItem()) { + heldItem = player->inventory->getSelected(); + } + + if (zomb->isVillager() && + zomb->isWeakened() // zomb->hasEffect(MobEffect::weakness) + // - not present on + // client. + && heldItem != NULL && + heldItem->getItem()->id == + Item::apple_gold_Id) { + *piUse = IDS_TOOLTIPS_CURE; + } + *piAction = IDS_TOOLTIPS_HIT; + } break; + default: + *piAction = IDS_TOOLTIPS_HIT; + break; + } + break; + } + } + } + + ui.SetTooltips(iPad, iA, iB, iX, iY, iLT, iRT, iLB, iRB); + + int wheel = 0; + unsigned int leftTicks = + InputManager.GetValue(iPad, MINECRAFT_ACTION_LEFT_SCROLL, true); + unsigned int rightTicks = + InputManager.GetValue(iPad, MINECRAFT_ACTION_RIGHT_SCROLL, true); + if (leftTicks > 0 && + gameMode->isInputAllowed(MINECRAFT_ACTION_LEFT_SCROLL)) { + wheel = (int)leftTicks; // positive = left + } else if (rightTicks > 0 && + gameMode->isInputAllowed(MINECRAFT_ACTION_RIGHT_SCROLL)) { + wheel = -(int)rightTicks; // negative = right + } + if (wheel != 0) { + player->inventory->swapPaint(wheel); + + if (gameMode != NULL && gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to record what + // items we are using so that we can give hints + gameMode->getTutorial()->onSelectedItemChanged( + player->inventory->getSelected()); + } + + // Update presence + player->updateRichPresence(); + + if (options->isFlying) { + if (wheel > 0) wheel = 1; + if (wheel < 0) wheel = -1; + + options->flySpeed += wheel * .25f; + } + } + if (gameMode->isInputAllowed(MINECRAFT_ACTION_ACTION)) { + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_ACTION))) + // if(InputManager.ButtonPressed(iPad, MINECRAFT_ACTION_ACTION) ) + { + // printf("MINECRAFT_ACTION_ACTION ButtonPressed"); + player->handleMouseClick(0); + player->lastClickTick[0] = ticks; + } + + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) && + ticks - player->lastClickTick[0] >= timer->ticksPerSecond / 4) { + // printf("MINECRAFT_ACTION_ACTION ButtonDown"); + player->handleMouseClick(0); + player->lastClickTick[0] = ticks; + } + + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION)) { + player->handleMouseDown(0, true); + } else { + player->handleMouseDown(0, false); + } + } + + // 4J Stu - This is how we used to handle the USE action. It has now + // been replaced with the block below which is more like the way the + // Java game does it, however we may find that the way we had it + // previously is more fun to play. + /* + if ((InputManager.GetValue(iPad, MINECRAFT_ACTION_USE,true)>0) && + gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) + { + handleMouseClick(1); + lastClickTick = ticks; + } + */ + if (player->isUsingItem()) { + if (!InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) + gameMode->releaseUsingItem(player); + } else if (gameMode->isInputAllowed(MINECRAFT_ACTION_USE)) { + if (player->abilities.instabuild) { + // 4J - attempt to handle click in special creative mode fashion + // if possible (used for placing blocks at regular intervals) + bool didClick = player->creativeModeHandleMouseClick( + 1, InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)); + // If this handler has put us in lastClick_oldRepeat mode then + // it is because we aren't placing blocks - behave largely as + // the code used to + if (player->lastClickState == + LocalPlayer::lastClick_oldRepeat) { + // If we've already handled the click in + // creativeModeHandleMouseClick then just record the time of + // this click + if (didClick) { + player->lastClickTick[1] = ticks; + } else { + // Otherwise just the original game code for handling + // autorepeat + if (InputManager.ButtonDown(iPad, + MINECRAFT_ACTION_USE) && + ticks - player->lastClickTick[1] >= + timer->ticksPerSecond / 4) { + player->handleMouseClick(1); + player->lastClickTick[1] = ticks; + } + } + } + } else { + // Consider as a click if we've had a period of not pressing the + // button, or we've reached auto-repeat time since the last time + // Auto-repeat is only considered if we aren't riding or + // sprinting, to avoid photo sensitivity issues when placing + // fire whilst doing fast things Also disable repeat when the + // player is sleeping to stop the waking up right after using + // the bed + bool firstClick = (player->lastClickTick[1] == 0); + bool autoRepeat = ticks - player->lastClickTick[1] >= + timer->ticksPerSecond / 4; + if (player->isRiding() || player->isSprinting() || + player->isSleeping()) + autoRepeat = false; + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) { + // If the player has just exited a bed, then delay the time + // before a repeat key is allowed without releasing + if (player->isSleeping()) + player->lastClickTick[1] = + ticks + (timer->ticksPerSecond * 2); + if (firstClick || autoRepeat) { + bool wasSleeping = player->isSleeping(); + + player->handleMouseClick(1); + + // If the player has just exited a bed, then delay the + // time before a repeat key is allowed without releasing + if (wasSleeping) + player->lastClickTick[1] = + ticks + (timer->ticksPerSecond * 2); + else + player->lastClickTick[1] = ticks; + } + } else { + player->lastClickTick[1] = 0; + } + } + } + + if (app.DebugSettingsOn()) { + if (player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_CHANGE_SKIN)) { + player->ChangePlayerSkin(); + } + } + + if (player->missTime > 0) player->missTime--; #ifdef _DEBUG_MENUS_ENABLED - if(app.DebugSettingsOn()) - { + if (app.DebugSettingsOn()) { #ifndef __PSVITA__ - // 4J-PB - debugoverlay for primary player only - if(iPad==ProfileManager.GetPrimaryPad()) - { - if((player->ullButtonsPressed&(1LL<ullButtonsPressed & + (1LL << MINECRAFT_ACTION_RENDER_DEBUG))) { #ifndef _CONTENT_PACKAGE - options->renderDebug = !options->renderDebug; + options->renderDebug = !options->renderDebug; #ifdef _XBOX - app.EnableDebugOverlay(options->renderDebug,iPad); + app.EnableDebugOverlay(options->renderDebug, iPad); #else - // 4J Stu - The xbox uses a completely different way of navigating to this scene - ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, eUILayer_Debug); + // 4J Stu - The xbox uses a completely different way of + // navigating to this scene + ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, + eUILayer_Debug); #endif #endif - } + } - if((player->ullButtonsPressed&(1LL< mob = std::dynamic_pointer_cast(Creeper::_class->newInstance( level )); - //std::shared_ptr mob = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - std::shared_ptr mob = std::dynamic_pointer_cast(std::shared_ptr(new Spider( level ))); - mob->moveTo(player->x+1, player->y, player->z+1, level->random->nextFloat() * 360, 0); - level->addEntity(mob); - } - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_SPAWN_CREEPER)) && + app.GetMobsDontAttackEnabled()) { + // std::shared_ptr mob = + // std::dynamic_pointer_cast(Creeper::_class->newInstance( + // level )); std::shared_ptr mob = + // std::dynamic_pointer_cast(Wolf::_class->newInstance( + // level )); + std::shared_ptr mob = std::dynamic_pointer_cast( + std::shared_ptr(new Spider(level))); + mob->moveTo(player->x + 1, player->y, player->z + 1, + level->random->nextFloat() * 360, 0); + level->addEntity(mob); + } + } - if( (player->ullButtonsPressed&(1LL<abilities.debugflying = !player->abilities.debugflying; - player->abilities.flying = !player->abilities.flying; - } -#endif // PSVITA - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_FLY_TOGGLE))) { + player->abilities.debugflying = !player->abilities.debugflying; + player->abilities.flying = !player->abilities.flying; + } +#endif // PSVITA + } #endif - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_RENDER_THIRD_PERSON)) - { - // 4J-PB - changing this to be per player - player->SetThirdPersonView((player->ThirdPersonView()+1)%3); - //options->thirdPersonView = !options->thirdPersonView; - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_RENDER_THIRD_PERSON)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_RENDER_THIRD_PERSON)) { + // 4J-PB - changing this to be per player + player->SetThirdPersonView((player->ThirdPersonView() + 1) % 3); + // options->thirdPersonView = !options->thirdPersonView; + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_GAME_INFO)) - { - ui.NavigateToScene(iPad,eUIScene_InGameInfoMenu); - ui.PlayUISFX(eSFX_Press); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_GAME_INFO)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_GAME_INFO)) { + ui.NavigateToScene(iPad, eUIScene_InGameInfoMenu); + ui.PlayUISFX(eSFX_Press); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_INVENTORY)) - { - std::shared_ptr player = std::dynamic_pointer_cast( Minecraft::GetInstance()->player ); - ui.PlayUISFX(eSFX_Press); - app.LoadInventoryMenu(iPad,player); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_INVENTORY)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_INVENTORY)) { + std::shared_ptr player = + std::dynamic_pointer_cast( + Minecraft::GetInstance()->player); + ui.PlayUISFX(eSFX_Press); + app.LoadInventoryMenu(iPad, player); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_CRAFTING)) - { - std::shared_ptr player = std::dynamic_pointer_cast( Minecraft::GetInstance()->player ); + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_CRAFTING)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_CRAFTING)) { + std::shared_ptr player = + std::dynamic_pointer_cast( + Minecraft::GetInstance()->player); - // 4J-PB - reordered the if statement so creative mode doesn't bring up the crafting table - // Fix for #39014 - TU5: Creative Mode: Pressing X to access the creative menu while looking at a crafting table causes the crafting menu to display - if(gameMode->hasInfiniteItems()) - { - // Creative mode + // 4J-PB - reordered the if statement so creative mode doesn't bring + // up the crafting table Fix for #39014 - TU5: Creative Mode: + // Pressing X to access the creative menu while looking at a + // crafting table causes the crafting menu to display + if (gameMode->hasInfiniteItems()) { + // Creative mode - ui.PlayUISFX(eSFX_Press); - app.LoadCreativeMenu(iPad,player); - } - // 4J-PB - Microsoft request that we use the 3x3 crafting if someone presses X while at the workbench - else if ((hitResult!=NULL) && (hitResult->type == HitResult::TILE) && (level->getTile(hitResult->x, hitResult->y, hitResult->z) == Tile::workBench_Id)) - { - //ui.PlayUISFX(eSFX_Press); - //app.LoadXuiCrafting3x3Menu(iPad,player,hitResult->x, hitResult->y, hitResult->z); - bool usedItem = false; - gameMode->useItemOn(player, level, nullptr, hitResult->x, hitResult->y, hitResult->z, 0, hitResult->pos, false, &usedItem); - } - else - { - ui.PlayUISFX(eSFX_Press); - app.LoadCrafting2x2Menu(iPad,player); - } - } + ui.PlayUISFX(eSFX_Press); + app.LoadCreativeMenu(iPad, player); + } + // 4J-PB - Microsoft request that we use the 3x3 crafting if someone + // presses X while at the workbench + else if ((hitResult != NULL) && + (hitResult->type == HitResult::TILE) && + (level->getTile(hitResult->x, hitResult->y, + hitResult->z) == Tile::workBench_Id)) { + // ui.PlayUISFX(eSFX_Press); + // app.LoadXuiCrafting3x3Menu(iPad,player,hitResult->x, + // hitResult->y, hitResult->z); + bool usedItem = false; + gameMode->useItemOn(player, level, nullptr, hitResult->x, + hitResult->y, hitResult->z, 0, + hitResult->pos, false, &usedItem); + } else { + ui.PlayUISFX(eSFX_Press); + app.LoadCrafting2x2Menu(iPad, player); + } + } - if ( (player->ullButtonsPressed&(1LL<ullButtonsPressed&(1LL<ullButtonsPressed & (1LL << MINECRAFT_ACTION_PAUSEMENU)) +#ifdef _DURANGO + || (player->ullButtonsPressed & (1LL << ACTION_MENU_GTC_PAUSE)) #endif - ) - { - app.DebugPrintf("PAUSE PRESS PROCESSING - ipad = %d, NavigateToScene\n",player->GetXboxPad()); - ui.PlayUISFX(eSFX_Press); - ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); - } + ) { + app.DebugPrintf( + "PAUSE PRESS PROCESSING - ipad = %d, NavigateToScene\n", + player->GetXboxPad()); + ui.PlayUISFX(eSFX_Press); + ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_DROP)) - { - player->drop(); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_DROP)) { + player->drop(); + } + + __uint64 ullButtonsPressed = player->ullButtonsPressed; + + bool selected = false; - __uint64 ullButtonsPressed=player->ullButtonsPressed; - - bool selected = false; - #ifdef __PSVITA__ - // 4J-PB - use the touchscreen for quickselect - SceTouchData* pTouchData = InputManager.GetTouchPadData(iPad,false); + // 4J-PB - use the touchscreen for quickselect + SceTouchData* pTouchData = InputManager.GetTouchPadData(iPad, false); - if(pTouchData->reportNum==1) - { - int iHudSize=app.GetGameSettings(iPad,eGameSetting_UISize); - if((pTouchData->report[0].x>QuickSelectRect[iHudSize].left)&&(pTouchData->report[0].xreport[0].y>QuickSelectRect[iHudSize].top)&&(pTouchData->report[0].yinventory->selected=(pTouchData->report[0].x-QuickSelectRect[iHudSize].left)/QuickSelectBoxWidth[iHudSize]; - selected = true; - app.DebugPrintf("Touch %d\n",player->inventory->selected); - } - } + if (pTouchData->reportNum == 1) { + int iHudSize = app.GetGameSettings(iPad, eGameSetting_UISize); + if ((pTouchData->report[0].x > QuickSelectRect[iHudSize].left) && + (pTouchData->report[0].x < QuickSelectRect[iHudSize].right) && + (pTouchData->report[0].y > QuickSelectRect[iHudSize].top) && + (pTouchData->report[0].y < QuickSelectRect[iHudSize].bottom)) { + player->inventory->selected = + (pTouchData->report[0].x - QuickSelectRect[iHudSize].left) / + QuickSelectBoxWidth[iHudSize]; + selected = true; + app.DebugPrintf("Touch %d\n", player->inventory->selected); + } + } #endif - { - int hotbarSlot = InputManager.GetHotbarSlotPressed(iPad); - if (hotbarSlot >= 0 && hotbarSlot <= 9) - { - player->inventory->selected = hotbarSlot; - selected = true; - } - } - if( selected || wheel != 0 || (player->ullButtonsPressed&(1LL< selectedItem = player->getSelectedItem(); - // Dropping items happens over network, so if we only have one then assume that we dropped it and should hide the item - int iCount=0; - - if(selectedItem != NULL) iCount=selectedItem->GetCount(); - if(selectedItem != NULL && !( (player->ullButtonsPressed&(1LL<GetCount() == 1)) - { - itemName = selectedItem->getHoverName(); - } - if( !(player->ullButtonsPressed&(1LL<GetCount() <= 1) ) ui.SetSelectedItem( iPad, itemName ); - } - } - else - { - // 4J-PB - if (InputManager.GetValue(iPad, ACTION_MENU_CANCEL) > 0 && gameMode->isInputAllowed(ACTION_MENU_CANCEL)) - { - setScreen(NULL); - } - } + { + int hotbarSlot = InputManager.GetHotbarSlotPressed(iPad); + if (hotbarSlot >= 0 && hotbarSlot <= 9) { + player->inventory->selected = hotbarSlot; + selected = true; + } + } + if (selected || wheel != 0 || + (player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP))) { + std::wstring itemName = L""; + std::shared_ptr selectedItem = + player->getSelectedItem(); + // Dropping items happens over network, so if we only have one then + // assume that we dropped it and should hide the item + int iCount = 0; - // monitor for keyboard input - // #ifndef _CONTENT_PACKAGE - // if(!(ui.GetMenuDisplayed(iPad))) - // { - // WCHAR wchInput; - // if(InputManager.InputDetected(iPad,&wchInput)) - // { - // printf("Input Detected!\n"); - // - // // see if we can react to this - // if(app.GetXuiAction(iPad)==eAppAction_Idle) - // { - // app.SetAction(iPad,eAppAction_DebugText,(LPVOID)wchInput); - // } - // } - // } - // #endif + if (selectedItem != NULL) iCount = selectedItem->GetCount(); + if (selectedItem != NULL && !((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_DROP)) && + selectedItem->GetCount() == 1)) { + itemName = selectedItem->getHoverName(); + } + if (!(player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP)) || + (selectedItem != NULL && selectedItem->GetCount() <= 1)) + ui.SetSelectedItem(iPad, itemName); + } + } else { + // 4J-PB + if (InputManager.GetValue(iPad, ACTION_MENU_CANCEL) > 0 && + gameMode->isInputAllowed(ACTION_MENU_CANCEL)) { + setScreen(NULL); + } + } + + // monitor for keyboard input + // #ifndef _CONTENT_PACKAGE + // if(!(ui.GetMenuDisplayed(iPad))) + // { + // WCHAR wchInput; + // if(InputManager.InputDetected(iPad,&wchInput)) + // { + // printf("Input Detected!\n"); + // + // // see if we can react to this + // if(app.GetXuiAction(iPad)==eAppAction_Idle) + // { + // app.SetAction(iPad,eAppAction_DebugText,(LPVOID)wchInput); + // } + // } + // } + // #endif #if 0 // 4J - TODO - some replacement for input handling... @@ -3632,388 +3838,397 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #endif - if (level != NULL) - { - if (player != NULL) - { - recheckPlayerIn++; - if (recheckPlayerIn == 30) - { - recheckPlayerIn = 0; - level->ensureAdded(player); - } - } - // 4J Changed - We are setting the difficulty the same as the server so that leaderboard updates work correctly - //level->difficulty = options->difficulty; - //if (level->isClientSide) level->difficulty = Difficulty::HARD; - if( !level->isClientSide ) - { - //app.DebugPrintf("Minecraft::tick - Difficulty = %d",options->difficulty); - level->difficulty = options->difficulty; - } + if (level != NULL) { + if (player != NULL) { + recheckPlayerIn++; + if (recheckPlayerIn == 30) { + recheckPlayerIn = 0; + level->ensureAdded(player); + } + } + // 4J Changed - We are setting the difficulty the same as the server so + // that leaderboard updates work correctly + // level->difficulty = options->difficulty; + // if (level->isClientSide) level->difficulty = Difficulty::HARD; + if (!level->isClientSide) { + // app.DebugPrintf("Minecraft::tick - Difficulty = + // %d",options->difficulty); + level->difficulty = options->difficulty; + } - PIXBeginNamedEvent(0,"Game renderer tick"); - if (!pause) gameRenderer->tick( bFirst); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Game renderer tick"); + if (!pause) gameRenderer->tick(bFirst); + PIXEndNamedEvent(); - // 4J - we want to tick each level once only per frame, and do it when a player that is actually in that level happens to be active. - // This is important as things that get called in the level tick (eg the levellistener) eventually end up working out what the current - // level is by determing it from the current player. Use flags here to make sure each level is only ticked the once. - static unsigned int levelsTickedFlags; - if( bFirst ) - { - levelsTickedFlags = 0; + // 4J - we want to tick each level once only per frame, and do it when a + // player that is actually in that level happens to be active. This is + // important as things that get called in the level tick (eg the + // levellistener) eventually end up working out what the current level + // is by determing it from the current player. Use flags here to make + // sure each level is only ticked the once. + static unsigned int levelsTickedFlags; + if (bFirst) { + levelsTickedFlags = 0; #ifndef DISABLE_LEVELTICK_THREAD - PIXBeginNamedEvent(0,"levelTickEventQueue waitForFinish"); - levelTickEventQueue->waitForFinish(); - PIXEndNamedEvent(); -#endif // DISABLE_LEVELTICK_THREAD - SparseLightStorage::tick(); // 4J added - CompressedTileStorage::tick(); // 4J added - SparseDataStorage::tick(); // 4J added - } + PIXBeginNamedEvent(0, "levelTickEventQueue waitForFinish"); + levelTickEventQueue->waitForFinish(); + PIXEndNamedEvent(); +#endif // DISABLE_LEVELTICK_THREAD + SparseLightStorage::tick(); // 4J added + CompressedTileStorage::tick(); // 4J added + SparseDataStorage::tick(); // 4J added + } - for(unsigned int i = 0; i < levels.length; ++i) - { - if( player->level != levels[i] ) continue; // Don't tick if the current player isn't in this level + for (unsigned int i = 0; i < levels.length; ++i) { + if (player->level != levels[i]) + continue; // Don't tick if the current player isn't in this + // level - // 4J - this doesn't fully tick the animateTick here, but does register this player's position. The actual - // work is now done in Level::animateTickDoWork() so we can take into account multiple players in the one level. - if (!pause && levels[i] != NULL) levels[i]->animateTick(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + // 4J - this doesn't fully tick the animateTick here, but does + // register this player's position. The actual work is now done in + // Level::animateTickDoWork() so we can take into account multiple + // players in the one level. + if (!pause && levels[i] != NULL) + levels[i]->animateTick(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z)); - if( levelsTickedFlags & ( 1 << i ) ) continue; // Don't tick further if we've already ticked this level this frame - levelsTickedFlags |= (1 << i); + if (levelsTickedFlags & (1 << i)) + continue; // Don't tick further if we've already ticked this + // level this frame + levelsTickedFlags |= (1 << i); - PIXBeginNamedEvent(0,"Level renderer tick"); - if (!pause) levelRenderer->tick(); - PIXEndNamedEvent(); - // if (!pause && player!=null) { - // if (player != null && !level.entities.contains(player)) { - // level.addEntity(player); - // } - // } - if( levels[i] != NULL ) - { - if (!pause) - { - if (levels[i]->lightningBoltTime > 0) levels[i]->lightningBoltTime--; - PIXBeginNamedEvent(0,"Level entity tick"); - levels[i]->tickEntities(); - PIXEndNamedEvent(); - } + PIXBeginNamedEvent(0, "Level renderer tick"); + if (!pause) levelRenderer->tick(); + PIXEndNamedEvent(); + // if (!pause && player!=null) { + // if (player != null && !level.entities.contains(player)) { + // level.addEntity(player); + // } + // } + if (levels[i] != NULL) { + if (!pause) { + if (levels[i]->lightningBoltTime > 0) + levels[i]->lightningBoltTime--; + PIXBeginNamedEvent(0, "Level entity tick"); + levels[i]->tickEntities(); + PIXEndNamedEvent(); + } - // optimisation to set the culling off early, in parallel with other stuff + // optimisation to set the culling off early, in parallel with + // other stuff #if defined __PS3__ && !defined DISABLE_SPU_CODE - // kick off the culling for all valid players in this level - int currPlayerIdx = getLocalPlayerIdx(); - for( int idx = 0; idx < XUSER_MAX_COUNT; idx++ ) - { - if(localplayers[idx]!=NULL) - { - if( localplayers[idx]->level == levels[i] ) - { - setLocalPlayerIdx(idx); - gameRenderer->setupCamera(timer->a, i); - Camera::prepare(localplayers[idx], localplayers[idx]->ThirdPersonView() == 2); - std::shared_ptr cameraEntity = cameraTargetPlayer; - double xOff = cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * timer->a; - double yOff = cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * timer->a; - double zOff = cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * timer->a; - FrustumCuller frustObj; - Culler *frustum = &frustObj; - MemSect(0); - frustum->prepare(xOff, yOff, zOff); - levelRenderer->cull_SPU(idx, frustum, 0); - } - } - } - setLocalPlayerIdx(currPlayerIdx); -#endif // __PS3__ + // kick off the culling for all valid players in this level + int currPlayerIdx = getLocalPlayerIdx(); + for (int idx = 0; idx < XUSER_MAX_COUNT; idx++) { + if (localplayers[idx] != NULL) { + if (localplayers[idx]->level == levels[i]) { + setLocalPlayerIdx(idx); + gameRenderer->setupCamera(timer->a, i); + Camera::prepare( + localplayers[idx], + localplayers[idx]->ThirdPersonView() == 2); + std::shared_ptr cameraEntity = + cameraTargetPlayer; + double xOff = + cameraEntity->xOld + + (cameraEntity->x - cameraEntity->xOld) * + timer->a; + double yOff = + cameraEntity->yOld + + (cameraEntity->y - cameraEntity->yOld) * + timer->a; + double zOff = + cameraEntity->zOld + + (cameraEntity->z - cameraEntity->zOld) * + timer->a; + FrustumCuller frustObj; + Culler* frustum = &frustObj; + MemSect(0); + frustum->prepare(xOff, yOff, zOff); + levelRenderer->cull_SPU(idx, frustum, 0); + } + } + } + setLocalPlayerIdx(currPlayerIdx); +#endif // __PS3__ - // 4J Stu - We are always online, but still could be paused - if (!pause) // || isClientSide()) - { - //app.DebugPrintf("Minecraft::tick spawn settings - Difficulty = %d",options->difficulty); - levels[i]->setSpawnSettings(level->difficulty > 0, true); - PIXBeginNamedEvent(0,"Level tick"); + // 4J Stu - We are always online, but still could be paused + if (!pause) // || isClientSide()) + { + // app.DebugPrintf("Minecraft::tick spawn settings - + // Difficulty = %d",options->difficulty); + levels[i]->setSpawnSettings(level->difficulty > 0, true); + PIXBeginNamedEvent(0, "Level tick"); #ifdef DISABLE_LEVELTICK_THREAD - levels[i]->tick(); + levels[i]->tick(); #else - levelTickEventQueue->sendEvent(levels[i]); -#endif // DISABLE_LEVELTICK_THREAD - PIXEndNamedEvent(); - } - } - } + levelTickEventQueue->sendEvent(levels[i]); +#endif // DISABLE_LEVELTICK_THREAD + PIXEndNamedEvent(); + } + } + } - if( bFirst ) - { - PIXBeginNamedEvent(0,"Particle tick"); - if (!pause) particleEngine->tick(); - PIXEndNamedEvent(); - } + if (bFirst) { + PIXBeginNamedEvent(0, "Particle tick"); + if (!pause) particleEngine->tick(); + PIXEndNamedEvent(); + } - // 4J Stu - Keep ticking the connections if paused so that they don't time out - if( pause ) tickAllConnections(); - // player->tick(); - } + // 4J Stu - Keep ticking the connections if paused so that they don't + // time out + if (pause) tickAllConnections(); + // player->tick(); + } #ifdef __PS3__ -// while(!g_tickLevelQueue.empty()) -// { -// Level* pLevel = g_tickLevelQueue.front(); -// g_tickLevelQueue.pop(); -// pLevel->tick(); -// }; + // while(!g_tickLevelQueue.empty()) + // { + // Level* pLevel = g_tickLevelQueue.front(); + // g_tickLevelQueue.pop(); + // pLevel->tick(); + // }; #endif - // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD7) || - // Keyboard.isKeyDown(Keyboard.KEY_Q)) rota++; - // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9) || - // Keyboard.isKeyDown(Keyboard.KEY_E)) rota--; - // 4J removed - //lastTickTime = System::currentTimeMillis(); + // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD7) || + // Keyboard.isKeyDown(Keyboard.KEY_Q)) rota++; + // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9) || + // Keyboard.isKeyDown(Keyboard.KEY_E)) rota--; + // 4J removed + // lastTickTime = System::currentTimeMillis(); } -void Minecraft::reloadSound() -{ - // System.out.println("FORCING RELOAD!"); // 4J - removed - soundEngine = new SoundEngine(); - soundEngine->init(options); - bgLoader->forceReload(); +void Minecraft::reloadSound() { + // System.out.println("FORCING RELOAD!"); // 4J - removed + soundEngine = new SoundEngine(); + soundEngine->init(options); + bgLoader->forceReload(); } -bool Minecraft::isClientSide() -{ - return level != NULL && level->isClientSide; +bool Minecraft::isClientSide() { return level != NULL && level->isClientSide; } + +void Minecraft::selectLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + const std::wstring& levelName, + LevelSettings* levelSettings) {} + +bool Minecraft::saveSlot(int slot, const std::wstring& name) { return false; } + +bool Minecraft::loadSlot(const std::wstring& userName, int slot) { + return false; } -void Minecraft::selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, const std::wstring& levelName, LevelSettings *levelSettings) -{ - } - -bool Minecraft::saveSlot(int slot, const std::wstring& name) -{ - return false; +void Minecraft::releaseLevel(int message) { + // this->level = NULL; + setLevel(NULL, message); } -bool Minecraft::loadSlot(const std::wstring& userName, int slot) -{ - return false; -} +// 4J Stu - This code was within setLevel, but I moved it out so that I can call +// it at a better time when exiting from an online game +void Minecraft::forceStatsSave(int idx) { + // 4J Gordon: Force a stats save + stats[idx]->save(idx, true); -void Minecraft::releaseLevel(int message) -{ - //this->level = NULL; - setLevel(NULL, message); -} - -// 4J Stu - This code was within setLevel, but I moved it out so that I can call it at a better -// time when exiting from an online game -void Minecraft::forceStatsSave(int idx) -{ - //4J Gordon: Force a stats save - stats[idx]->save(idx, true); - - //4J Gordon: If the player is signed in, save the leaderboards - if( ProfileManager.IsSignedInLive(idx) ) - { - int tempLockedProfile = ProfileManager.GetLockedProfile(); - ProfileManager.SetLockedProfile(idx); - stats[idx]->saveLeaderboards(); - ProfileManager.SetLockedProfile(tempLockedProfile); - } + // 4J Gordon: If the player is signed in, save the leaderboards + if (ProfileManager.IsSignedInLive(idx)) { + int tempLockedProfile = ProfileManager.GetLockedProfile(); + ProfileManager.SetLockedProfile(idx); + stats[idx]->saveLeaderboards(); + ProfileManager.SetLockedProfile(tempLockedProfile); + } } // 4J Added -MultiPlayerLevel *Minecraft::getLevel(int dimension) -{ - if (dimension == -1) return levels[1]; - else if(dimension == 1) return levels[2]; - else return levels[0]; +MultiPlayerLevel* Minecraft::getLevel(int dimension) { + if (dimension == -1) + return levels[1]; + else if (dimension == 1) + return levels[2]; + else + return levels[0]; } // 4J Stu - Removed as redundant with default values in params. -//void Minecraft::setLevel(Level *level, bool doForceStatsSave /*= true*/) +// void Minecraft::setLevel(Level *level, bool doForceStatsSave /*= true*/) //{ // setLevel(level, -1, NULL, doForceStatsSave); //} // Also causing ambiguous call for some reason -// as it is matching std::shared_ptr from the func below with bool from this one -//void Minecraft::setLevel(Level *level, const std::wstring& message, bool doForceStatsSave /*= true*/) +// as it is matching std::shared_ptr from the func below with bool from +// this one +// void Minecraft::setLevel(Level *level, const std::wstring& message, bool +// doForceStatsSave /*= true*/) //{ // setLevel(level, message, NULL, doForceStatsSave); //} -void Minecraft::forceaddLevel(MultiPlayerLevel *level) -{ - int dimId = level->dimension->id; - if (dimId == -1) levels[1] = level; - else if(dimId == 1) levels[2] = level; - else levels[0] = level; +void Minecraft::forceaddLevel(MultiPlayerLevel* level) { + int dimId = level->dimension->id; + if (dimId == -1) + levels[1] = level; + else if (dimId == 1) + levels[2] = level; + else + levels[0] = level; } -void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, std::shared_ptr forceInsertPlayer /*=NULL*/, bool doForceStatsSave /*=true*/, bool bPrimaryPlayerSignedOut /*=false*/) -{ - EnterCriticalSection(&m_setLevelCS); - bool playerAdded = false; - this->cameraTargetPlayer = nullptr; +void Minecraft::setLevel(MultiPlayerLevel* level, int message /*=-1*/, + std::shared_ptr forceInsertPlayer /*=NULL*/, + bool doForceStatsSave /*=true*/, + bool bPrimaryPlayerSignedOut /*=false*/) { + EnterCriticalSection(&m_setLevelCS); + bool playerAdded = false; + this->cameraTargetPlayer = nullptr; - if(progressRenderer != NULL) - { - this->progressRenderer->progressStart(message); - this->progressRenderer->progressStage(-1); - } + if (progressRenderer != NULL) { + this->progressRenderer->progressStart(message); + this->progressRenderer->progressStage(-1); + } - // 4J-PB - since we now play music in the menu, just let it keep playing - //soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); + // 4J-PB - since we now play music in the menu, just let it keep playing + // soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); - // 4J - stop update thread from processing this level, which blocks until it is safe to move on - will be re-enabled if we set the level to be non-NULL - gameRenderer->DisableUpdateThread(); + // 4J - stop update thread from processing this level, which blocks until it + // is safe to move on - will be re-enabled if we set the level to be + // non-NULL + gameRenderer->DisableUpdateThread(); - for(unsigned int i = 0; i < levels.length; ++i) - { - // 4J We only need to save out in multiplayer is we are setting the level to NULL - // If we ever go back to making single player only then this will not work properly! - if (levels[i] != NULL && level == NULL) - { - // 4J Stu - This is really only relevant for single player (ie not what we do at the moment) - if((doForceStatsSave==true) && player!=NULL) - forceStatsSave(player->GetXboxPad() ); + for (unsigned int i = 0; i < levels.length; ++i) { + // 4J We only need to save out in multiplayer is we are setting the + // level to NULL If we ever go back to making single player only then + // this will not work properly! + if (levels[i] != NULL && level == NULL) { + // 4J Stu - This is really only relevant for single player (ie not + // what we do at the moment) + if ((doForceStatsSave == true) && player != NULL) + forceStatsSave(player->GetXboxPad()); - // 4J Stu - Added these for the case when we exit a level so we are setting the level to NULL - // The level renderer needs to have it's stored level set to NULL so that it doesn't break next time we set one - if (levelRenderer != NULL) - { - for(unsigned int p = 0; p < XUSER_MAX_COUNT; ++p) - { - levelRenderer->setLevel(p, NULL); - } - } - if (particleEngine != NULL) particleEngine->setLevel(NULL); - } - } - // 4J If we are setting the level to NULL then we are exiting, so delete the levels - if( level == NULL ) - { - if(levels[0]!=NULL) - { - delete levels[0]; - levels[0] = NULL; + // 4J Stu - Added these for the case when we exit a level so we are + // setting the level to NULL The level renderer needs to have it's + // stored level set to NULL so that it doesn't break next time we + // set one + if (levelRenderer != NULL) { + for (unsigned int p = 0; p < XUSER_MAX_COUNT; ++p) { + levelRenderer->setLevel(p, NULL); + } + } + if (particleEngine != NULL) particleEngine->setLevel(NULL); + } + } + // 4J If we are setting the level to NULL then we are exiting, so delete the + // levels + if (level == NULL) { + if (levels[0] != NULL) { + delete levels[0]; + levels[0] = NULL; - // Both level share the same savedDataStorage - if(levels[1]!=NULL) levels[1]->savedDataStorage = NULL; - } - if(levels[1]!=NULL) - { - delete levels[1]; - levels[1] = NULL; - } - if(levels[2]!=NULL) - { - delete levels[2]; - levels[2] = NULL; - } + // Both level share the same savedDataStorage + if (levels[1] != NULL) levels[1]->savedDataStorage = NULL; + } + if (levels[1] != NULL) { + delete levels[1]; + levels[1] = NULL; + } + if (levels[2] != NULL) { + delete levels[2]; + levels[2] = NULL; + } - // Delete all the player objects - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - std::shared_ptr mplp = localplayers[idx]; - if(mplp != NULL && mplp->connection != NULL ) - { - delete mplp->connection; - mplp->connection = NULL; - } + // Delete all the player objects + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + std::shared_ptr mplp = localplayers[idx]; + if (mplp != NULL && mplp->connection != NULL) { + delete mplp->connection; + mplp->connection = NULL; + } - if( localgameModes[idx] != NULL ) - { - delete localgameModes[idx]; - localgameModes[idx] = NULL; - } + if (localgameModes[idx] != NULL) { + delete localgameModes[idx]; + localgameModes[idx] = NULL; + } - if( m_pendingLocalConnections[idx] != NULL ) - { - delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; - } + if (m_pendingLocalConnections[idx] != NULL) { + delete m_pendingLocalConnections[idx]; + m_pendingLocalConnections[idx] = NULL; + } - localplayers[idx] = nullptr; - } - // If we are removing the primary player then there can't be a valid gamemode left anymore, this - // pointer will be referring to the one we've just deleted - gameMode = NULL; - // Remove references to player - player = nullptr; - cameraTargetPlayer = nullptr; - EntityRenderDispatcher::instance->cameraEntity = nullptr; - TileEntityRenderDispatcher::instance->cameraEntity = nullptr; - } - this->level = level; + localplayers[idx] = nullptr; + } + // If we are removing the primary player then there can't be a valid + // gamemode left anymore, this pointer will be referring to the one + // we've just deleted + gameMode = NULL; + // Remove references to player + player = nullptr; + cameraTargetPlayer = nullptr; + EntityRenderDispatcher::instance->cameraEntity = nullptr; + TileEntityRenderDispatcher::instance->cameraEntity = nullptr; + } + this->level = level; - if (level != NULL) - { - int dimId = level->dimension->id; - if (dimId == -1) levels[1] = level; - else if(dimId == 1) levels[2] = level; - else levels[0] = level; + if (level != NULL) { + int dimId = level->dimension->id; + if (dimId == -1) + levels[1] = level; + else if (dimId == 1) + levels[2] = level; + else + levels[0] = level; - // If no player has been set, then this is the first level to be set this game, so set up - // a primary player & initialise some other things - if (player == NULL) - { - int iPrimaryPlayer = ProfileManager.GetPrimaryPad(); + // If no player has been set, then this is the first level to be set + // this game, so set up a primary player & initialise some other things + if (player == NULL) { + int iPrimaryPlayer = ProfileManager.GetPrimaryPad(); - player = gameMode->createPlayer(level); + player = gameMode->createPlayer(level); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(iPrimaryPlayer,&playerXUIDOffline,false); - ProfileManager.GetXUID(iPrimaryPlayer,&playerXUIDOnline,true); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(iPrimaryPlayer, &playerXUIDOffline, false); + ProfileManager.GetXUID(iPrimaryPlayer, &playerXUIDOnline, true); #ifdef __PSVITA__ - if(CGameNetworkManager::usingAdhocMode() && playerXUIDOnline.getOnlineID()[0] == 0) - { - // player doesn't have an online UID, set it from the player name - playerXUIDOnline.setForAdhoc(); - } + if (CGameNetworkManager::usingAdhocMode() && + playerXUIDOnline.getOnlineID()[0] == 0) { + // player doesn't have an online UID, set it from the player + // name + playerXUIDOnline.setForAdhoc(); + } #endif - player->setXuid(playerXUIDOffline); - player->setOnlineXuid(playerXUIDOnline); + player->setXuid(playerXUIDOffline); + player->setOnlineXuid(playerXUIDOnline); - player->displayName = ProfileManager.GetDisplayName(iPrimaryPlayer); + player->displayName = ProfileManager.GetDisplayName(iPrimaryPlayer); + player->resetPos(); + gameMode->initPlayer(player); + player->SetXboxPad(iPrimaryPlayer); - player->resetPos(); - gameMode->initPlayer(player); - - player->SetXboxPad(iPrimaryPlayer); + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + m_pendingLocalConnections[i] = NULL; + if (i != iPrimaryPlayer) localgameModes[i] = NULL; + } + } - for(int i=0;iresetPos(); + // gameMode.initPlayer(player); + if (level != NULL) { + level->addEntity(player); + playerAdded = true; + } + } - if (player != NULL) - { - player->resetPos(); - // gameMode.initPlayer(player); - if (level != NULL) - { - level->addEntity(player); - playerAdded = true; - } - } + if (player->input != NULL) delete player->input; + player->input = new Input(); - if(player->input != NULL) delete player->input; - player->input = new Input(); - - if (levelRenderer != NULL) levelRenderer->setLevel(player->GetXboxPad(), level); - if (particleEngine != NULL) particleEngine->setLevel(level); + if (levelRenderer != NULL) + levelRenderer->setLevel(player->GetXboxPad(), level); + if (particleEngine != NULL) particleEngine->setLevel(level); #if 0 // 4J - removed - we don't use ChunkCache anymore @@ -4029,60 +4244,55 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, std::shar spcc->centerOn(xt, zt); } #endif - gameMode->adjustPlayer(player); + gameMode->adjustPlayer(player); - for(int i=0;icameraTargetPlayer = player; + this->cameraTargetPlayer = player; - // 4J - allow update thread to start processing the level now both it & the player should be ok - gameRenderer->EnableUpdateThread(); - } - else - { - levelSource->clearAll(); - player = nullptr; + // 4J - allow update thread to start processing the level now both it & + // the player should be ok + gameRenderer->EnableUpdateThread(); + } else { + levelSource->clearAll(); + player = nullptr; - // Clear all players if the new level is NULL - for(int i=0;iclose(); - m_pendingLocalConnections[i] = NULL; - localplayers[i] = nullptr; - localgameModes[i] = NULL; - } - } + // Clear all players if the new level is NULL + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (m_pendingLocalConnections[i] != NULL) + m_pendingLocalConnections[i]->close(); + m_pendingLocalConnections[i] = NULL; + localplayers[i] = nullptr; + localgameModes[i] = NULL; + } + } - // System.gc(); // 4J - removed - // 4J removed - //this->lastTickTime = 0; - LeaveCriticalSection(&m_setLevelCS); + // System.gc(); // 4J - removed + // 4J removed + // this->lastTickTime = 0; + LeaveCriticalSection(&m_setLevelCS); } -void Minecraft::prepareLevel(int title) -{ - if(progressRenderer != NULL) - { - this->progressRenderer->progressStart(title); - this->progressRenderer->progressStage(IDS_PROGRESS_BUILDING_TERRAIN); - } - int r = 128; - if (gameMode->isCutScene()) r = 64; - int pp = 0; - int max = r * 2 / 16 + 1; - max = max * max; - ChunkSource *cs = level->getChunkSource(); +void Minecraft::prepareLevel(int title) { + if (progressRenderer != NULL) { + this->progressRenderer->progressStart(title); + this->progressRenderer->progressStage(IDS_PROGRESS_BUILDING_TERRAIN); + } + int r = 128; + if (gameMode->isCutScene()) r = 64; + int pp = 0; + int max = r * 2 / 16 + 1; + max = max * max; + ChunkSource* cs = level->getChunkSource(); - Pos *spawnPos = level->getSharedSpawnPos(); - if (player != NULL) - { - spawnPos->x = (int) player->x; - spawnPos->z = (int) player->z; - } + Pos* spawnPos = level->getSharedSpawnPos(); + if (player != NULL) { + spawnPos->x = (int)player->x; + spawnPos->z = (int)player->z; + } #if 0 // 4J - removed - we don't use ChunkCache anymore @@ -4094,437 +4304,419 @@ void Minecraft::prepareLevel(int title) } #endif - for (int x = -r; x <= r; x += 16) - { - for (int z = -r; z <= r; z += 16) - { - if(progressRenderer != NULL) this->progressRenderer->progressStagePercentage((pp++) * 100 / max); - level->getTile(spawnPos->x + x, 64, spawnPos->z + z); - if (!gameMode->isCutScene()) { - while (level->updateLights()) - ; - } - } - } - delete spawnPos; - if (!gameMode->isCutScene()) - { - if(progressRenderer != NULL) this->progressRenderer->progressStage(IDS_PROGRESS_SIMULATING_WORLD); - max = 2000; -} + for (int x = -r; x <= r; x += 16) { + for (int z = -r; z <= r; z += 16) { + if (progressRenderer != NULL) + this->progressRenderer->progressStagePercentage((pp++) * 100 / + max); + level->getTile(spawnPos->x + x, 64, spawnPos->z + z); + if (!gameMode->isCutScene()) { + while (level->updateLights()); + } + } + } + delete spawnPos; + if (!gameMode->isCutScene()) { + if (progressRenderer != NULL) + this->progressRenderer->progressStage( + IDS_PROGRESS_SIMULATING_WORLD); + max = 2000; + } } -void Minecraft::fileDownloaded(const std::wstring& name, File *file) -{ - int p = (int)name.find(L"/"); - std::wstring category = name.substr(0, p); - std::wstring name2 = name.substr(p + 1); - toLower(category); - if (category==L"sound") - { - soundEngine->add(name, file); - } - else if (category==L"newsound") - { - soundEngine->add(name, file); - } - else if (category==L"streaming") - { - soundEngine->addStreaming(name, file); - } - else if (category==L"music") - { - soundEngine->addMusic(name, file); - } - else if (category==L"newmusic") - { - soundEngine->addMusic(name, file); - } +void Minecraft::fileDownloaded(const std::wstring& name, File* file) { + int p = (int)name.find(L"/"); + std::wstring category = name.substr(0, p); + std::wstring name2 = name.substr(p + 1); + toLower(category); + if (category == L"sound") { + soundEngine->add(name, file); + } else if (category == L"newsound") { + soundEngine->add(name, file); + } else if (category == L"streaming") { + soundEngine->addStreaming(name, file); + } else if (category == L"music") { + soundEngine->addMusic(name, file); + } else if (category == L"newmusic") { + soundEngine->addMusic(name, file); + } } -std::wstring Minecraft::gatherStats1() -{ - //return levelRenderer->gatherStats1(); - return L"Time to autosave: " + _toString( app.SecondsToAutosave() ) + L"s"; +std::wstring Minecraft::gatherStats1() { + // return levelRenderer->gatherStats1(); + return L"Time to autosave: " + + _toString(app.SecondsToAutosave()) + L"s"; } -std::wstring Minecraft::gatherStats2() -{ - return g_NetworkManager.GatherStats(); - //return levelRenderer->gatherStats2(); +std::wstring Minecraft::gatherStats2() { + return g_NetworkManager.GatherStats(); + // return levelRenderer->gatherStats2(); } -std::wstring Minecraft::gatherStats3() -{ - return g_NetworkManager.GatherRTTStats(); - //return L"P: " + particleEngine->countParticles() + L". T: " + level->gatherStats(); +std::wstring Minecraft::gatherStats3() { + return g_NetworkManager.GatherRTTStats(); + // return L"P: " + particleEngine->countParticles() + L". T: " + + // level->gatherStats(); } -std::wstring Minecraft::gatherStats4() -{ - return level->gatherChunkSourceStats(); +std::wstring Minecraft::gatherStats4() { + return level->gatherChunkSourceStats(); } -void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) -{ - gameRenderer->DisableUpdateThread(); // 4J - don't do updating whilst we are adjusting the player & localplayer array - std::shared_ptr localPlayer = localplayers[iPad]; +void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) { + gameRenderer + ->DisableUpdateThread(); // 4J - don't do updating whilst we are + // adjusting the player & localplayer array + std::shared_ptr localPlayer = localplayers[iPad]; - level->validateSpawn(); - level->removeAllPendingEntityRemovals(); + level->validateSpawn(); + level->removeAllPendingEntityRemovals(); - if (localPlayer != NULL) - { + if (localPlayer != NULL) { + level->removeEntity(localPlayer); + } - level->removeEntity(localPlayer); - } + std::shared_ptr oldPlayer = localPlayer; + cameraTargetPlayer = nullptr; - std::shared_ptr oldPlayer = localPlayer; - cameraTargetPlayer = nullptr; + // 4J-PB - copy and set the players xbox pad + int iTempPad = localPlayer->GetXboxPad(); + int iTempScreenSection = localPlayer->m_iScreenSection; + EDefaultSkins skin = localPlayer->getPlayerDefaultSkin(); + player = localgameModes[iPad]->createPlayer(level); - // 4J-PB - copy and set the players xbox pad - int iTempPad=localPlayer->GetXboxPad(); - int iTempScreenSection = localPlayer->m_iScreenSection; - EDefaultSkins skin = localPlayer->getPlayerDefaultSkin(); - player = localgameModes[iPad]->createPlayer(level); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(iTempPad, &playerXUIDOffline, false); + ProfileManager.GetXUID(iTempPad, &playerXUIDOnline, true); + player->setXuid(playerXUIDOffline); + player->setOnlineXuid(playerXUIDOnline); + player->setIsGuest(ProfileManager.IsGuest(iTempPad)); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(iTempPad,&playerXUIDOffline,false); - ProfileManager.GetXUID(iTempPad,&playerXUIDOnline,true); - player->setXuid(playerXUIDOffline); - player->setOnlineXuid(playerXUIDOnline); - player->setIsGuest( ProfileManager.IsGuest(iTempPad) ); + player->displayName = ProfileManager.GetDisplayName(iPad); - player->displayName = ProfileManager.GetDisplayName(iPad); + player->SetXboxPad(iTempPad); - player->SetXboxPad(iTempPad); + player->m_iScreenSection = iTempScreenSection; + player->setPlayerIndex(localPlayer->getPlayerIndex()); + player->setCustomSkin(localPlayer->getCustomSkin()); + player->setPlayerDefaultSkin(skin); + player->setCustomCape(localPlayer->getCustomCape()); + player->m_sessionTimeStart = localPlayer->m_sessionTimeStart; + player->m_dimensionTimeStart = localPlayer->m_dimensionTimeStart; + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + localPlayer->getAllPlayerGamePrivileges()); - player->m_iScreenSection = iTempScreenSection; - player->setPlayerIndex( localPlayer->getPlayerIndex() ); - player->setCustomSkin(localPlayer->getCustomSkin()); - player->setPlayerDefaultSkin( skin ); - player->setCustomCape(localPlayer->getCustomCape()); - player->m_sessionTimeStart = localPlayer->m_sessionTimeStart; - player->m_dimensionTimeStart = localPlayer->m_dimensionTimeStart; - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, localPlayer->getAllPlayerGamePrivileges()); + player->SetThirdPersonView(oldPlayer->ThirdPersonView()); - player->SetThirdPersonView(oldPlayer->ThirdPersonView()); + // Fix for #63021 - TU7: Content: UI: Travelling from/to the Nether results + // in switching currently held item to another. Fix for #81759 - TU9: + // Content: Gameplay: Entering The End Exit Portal replaces the Player's + // currently held item with the first one from the Quickbar + if (localPlayer->getHealth() > 0 && localPlayer->y > -64) { + player->inventory->selected = localPlayer->inventory->selected; + } - // Fix for #63021 - TU7: Content: UI: Travelling from/to the Nether results in switching currently held item to another. - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - if( localPlayer->getHealth() > 0 && localPlayer->y > -64) - { - player->inventory->selected = localPlayer->inventory->selected; - } + // Set the animation override if the skin has one + std::uint32_t dwSkinID = app.getSkinIdFromPath(player->customTextureUrl); + if (GET_IS_DLC_SKIN_FROM_BITMASK(dwSkinID)) { + player->setAnimOverrideBitmask( + player->getSkinAnimOverrideBitmask(dwSkinID)); + } - // Set the animation override if the skin has one - std::uint32_t dwSkinID = app.getSkinIdFromPath(player->customTextureUrl); - if(GET_IS_DLC_SKIN_FROM_BITMASK(dwSkinID)) - { - player->setAnimOverrideBitmask(player->getSkinAnimOverrideBitmask(dwSkinID)); - } + player->dimension = dimension; + cameraTargetPlayer = player; - player->dimension = dimension; - cameraTargetPlayer = player; + // 4J-PB - are we the primary player or a local player? + if (iPad == ProfileManager.GetPrimaryPad()) { + createPrimaryLocalPlayer(iPad); - // 4J-PB - are we the primary player or a local player? - if(iPad==ProfileManager.GetPrimaryPad()) - { - createPrimaryLocalPlayer(iPad); + // update the debugoptions + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + app.GetGameSettingsDebugMask(-1, true)); + } else { + storeExtraLocalPlayer(iPad); + } - // update the debugoptions - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),app.GetGameSettingsDebugMask(-1,true)); - } - else - { - storeExtraLocalPlayer(iPad); - } + player->setShowOnMaps( + app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false); - player->setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); + player->resetPos(); + level->addEntity(player); + gameMode->initPlayer(player); - player->resetPos(); - level->addEntity(player); - gameMode->initPlayer(player); + if (player->input != NULL) delete player->input; + player->input = new Input(); + player->entityId = newEntityId; + player->animateRespawn(); + gameMode->adjustPlayer(player); - if(player->input != NULL) delete player->input; - player->input = new Input(); - player->entityId = newEntityId; - player->animateRespawn(); - gameMode->adjustPlayer(player); + // 4J - added isClientSide check here + if (!level->isClientSide) { + prepareLevel(IDS_PROGRESS_RESPAWNING); + } - // 4J - added isClientSide check here - if (!level->isClientSide) - { - prepareLevel(IDS_PROGRESS_RESPAWNING); - } + // 4J Added for multiplayer. At this point we know everything is ready to + // run again + // SetEvent(m_hPlayerRespawned); + player->SetPlayerRespawned(true); - // 4J Added for multiplayer. At this point we know everything is ready to run again - //SetEvent(m_hPlayerRespawned); - player->SetPlayerRespawned(true); + if (dynamic_cast(screen) != NULL) setScreen(NULL); - if (dynamic_cast(screen) != NULL) setScreen(NULL); - - gameRenderer->EnableUpdateThread(); + gameRenderer->EnableUpdateThread(); } -void Minecraft::start(const std::wstring& name, const std::wstring& sid) -{ - startAndConnectTo(name, sid, L""); +void Minecraft::start(const std::wstring& name, const std::wstring& sid) { + startAndConnectTo(name, sid, L""); } -void Minecraft::startAndConnectTo(const std::wstring& name, const std::wstring& sid, const std::wstring& url) -{ - bool fullScreen = false; - std::wstring userName = name; +void Minecraft::startAndConnectTo(const std::wstring& name, + const std::wstring& sid, + const std::wstring& url) { + bool fullScreen = false; + std::wstring userName = name; - /* 4J - removed window handling things here - final Frame frame = new Frame("Minecraft"); - Canvas canvas = new Canvas(); - frame.setLayout(new BorderLayout()); + /* 4J - removed window handling things here + final Frame frame = new Frame("Minecraft"); + Canvas canvas = new Canvas(); + frame.setLayout(new BorderLayout()); - frame.add(canvas, BorderLayout.CENTER); + frame.add(canvas, BorderLayout.CENTER); - // OverlayLayout oll = new OverlayLayout(frame); - // oll.addLayoutComponent(canvas, BorderLayout.CENTER); - // oll.addLayoutComponent(new JLabel("TEST"), BorderLayout.EAST); + // OverlayLayout oll = new OverlayLayout(frame); + // oll.addLayoutComponent(canvas, BorderLayout.CENTER); + // oll.addLayoutComponent(new JLabel("TEST"), BorderLayout.EAST); - canvas.setPreferredSize(new Dimension(854, 480)); - frame.pack(); - frame.setLocationRelativeTo(null); - */ + canvas.setPreferredSize(new Dimension(854, 480)); + frame.pack(); + frame.setLocationRelativeTo(null); + */ - Minecraft *minecraft; - // 4J - was new Minecraft(frame, canvas, NULL, 854, 480, fullScreen); + Minecraft* minecraft; + // 4J - was new Minecraft(frame, canvas, NULL, 854, 480, fullScreen); - minecraft = new Minecraft(NULL, NULL, NULL, 1280, 720, fullScreen); + minecraft = new Minecraft(NULL, NULL, NULL, 1280, 720, fullScreen); - /* - 4J - removed - { - @Override - public void onCrash(CrashReport crashReport) { - frame.removeAll(); - frame.add(new CrashInfoPanel(crashReport), BorderLayout.CENTER); - frame.validate(); - } - }; */ + /* - 4J - removed + { + @Override + public void onCrash(CrashReport crashReport) { + frame.removeAll(); + frame.add(new CrashInfoPanel(crashReport), BorderLayout.CENTER); + frame.validate(); + } + }; */ - /* 4J - removed - final Thread thread = new Thread(minecraft, "Minecraft main thread"); - thread.setPriority(Thread.MAX_PRIORITY); - */ - minecraft->serverDomain = L"www.minecraft.net"; + /* 4J - removed + final Thread thread = new Thread(minecraft, "Minecraft main thread"); + thread.setPriority(Thread.MAX_PRIORITY); + */ + minecraft->serverDomain = L"www.minecraft.net"; - // 4J Stu - We never want the player to be DemoUser, we always want them to have their gamertag displayed - //if (ProfileManager.IsFullVersion()) - { - if (userName != L"" && sid != L"") // 4J - username & side were compared with NULL rather than empty strings - { - minecraft->user = new User(userName, sid); - } - else - { - minecraft->user = new User(L"Player" + _toString(System::currentTimeMillis() % 1000), L""); - } - } - //else - //{ - // minecraft->user = new DemoUser(); - //} + // 4J Stu - We never want the player to be DemoUser, we always want them to + // have their gamertag displayed + // if (ProfileManager.IsFullVersion()) + { + if (userName != L"" && + sid != L"") // 4J - username & side were compared with NULL rather + // than empty strings + { + minecraft->user = new User(userName, sid); + } else { + minecraft->user = new User( + L"Player" + _toString(System::currentTimeMillis() % 1000), + L""); + } + } + // else + //{ + // minecraft->user = new DemoUser(); + // } - /* 4J - TODO - if (url != NULL) - { - String[] tokens = url.split(":"); - minecraft.connectTo(tokens[0], Integer.parseInt(tokens[1])); - } - */ + /* 4J - TODO + if (url != NULL) + { + String[] tokens = url.split(":"); + minecraft.connectTo(tokens[0], Integer.parseInt(tokens[1])); + } + */ - /* 4J - removed - frame.setVisible(true); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent arg0) { - minecraft.stop(); - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.exit(0); - } - }); - */ - // 4J - TODO - consider whether we need to actually create a thread here - minecraft->run(); + /* 4J - removed + frame.setVisible(true); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent arg0) { + minecraft.stop(); + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.exit(0); + } + }); + */ + // 4J - TODO - consider whether we need to actually create a thread here + minecraft->run(); } -ClientConnection *Minecraft::getConnection(int iPad) -{ - return localplayers[iPad]->connection; +ClientConnection* Minecraft::getConnection(int iPad) { + return localplayers[iPad]->connection; } // 4J-PB - so we can access this from within our xbox game loop -Minecraft *Minecraft::GetInstance() -{ - return m_instance; -} +Minecraft* Minecraft::GetInstance() { return m_instance; } bool useLomp = false; int g_iMainThreadId; -void Minecraft::main() -{ - std::wstring name; - std::wstring sessionId; +void Minecraft::main() { + std::wstring name; + std::wstring sessionId; - //g_iMainThreadId = GetCurrentThreadId(); + // g_iMainThreadId = GetCurrentThreadId(); - useLomp = true; + useLomp = true; - MinecraftWorld_RunStaticCtors(); - EntityRenderDispatcher::staticCtor(); - TileEntityRenderDispatcher::staticCtor(); - User::staticCtor(); - Tutorial::staticCtor(); - ColourTable::staticCtor(); - app.loadDefaultGameRules(); + MinecraftWorld_RunStaticCtors(); + EntityRenderDispatcher::staticCtor(); + TileEntityRenderDispatcher::staticCtor(); + User::staticCtor(); + Tutorial::staticCtor(); + ColourTable::staticCtor(); + app.loadDefaultGameRules(); #ifdef _LARGE_WORLDS - LevelRenderer::staticCtor(); + LevelRenderer::staticCtor(); #endif - // 4J Stu - This block generates XML for the game rules schema - //for(unsigned int i = 0; i < Item::items.length; ++i) - //{ - // if(Item::items[i] != NULL) - // { - // wprintf(L"%ls\n", i, app.GetString( Item::items[i]->getDescriptionId() )); - // } - //} + // 4J Stu - This block generates XML for the game rules schema + // for(unsigned int i = 0; i < Item::items.length; ++i) + //{ + // if(Item::items[i] != NULL) + // { + // wprintf(L"%ls\n", + //i, app.GetString( Item::items[i]->getDescriptionId() )); + // } + //} - //wprintf(L"\n\n\n\n\n"); - // - //for(unsigned int i = 0; i < 256; ++i) - //{ - // if(Tile::tiles[i] != NULL) - // { - // wprintf(L"%ls\n", i, app.GetString( Tile::tiles[i]->getDescriptionId() )); - // } - //} - //__debugbreak(); + // wprintf(L"\n\n\n\n\n"); + // + // for(unsigned int i = 0; i < 256; ++i) + //{ + // if(Tile::tiles[i] != NULL) + // { + // wprintf(L"%ls\n", + //i, app.GetString( Tile::tiles[i]->getDescriptionId() )); + // } + // } + //__debugbreak(); - // 4J-PB - Can't call this for the first 5 seconds of a game - MS rule - //if (ProfileManager.IsFullVersion()) - { - name = L"Player" + _toString<__int64>(System::currentTimeMillis() % 1000); - sessionId = L"-"; - /* 4J - TODO - get a session ID from somewhere? - if (args.length > 0) name = args[0]; - sessionId = "-"; - if (args.length > 1) sessionId = args[1]; - */ - } + // 4J-PB - Can't call this for the first 5 seconds of a game - MS rule + // if (ProfileManager.IsFullVersion()) + { + name = + L"Player" + _toString<__int64>(System::currentTimeMillis() % 1000); + sessionId = L"-"; + /* 4J - TODO - get a session ID from somewhere? + if (args.length > 0) name = args[0]; + sessionId = "-"; + if (args.length > 1) sessionId = args[1]; + */ + } - // Common for all platforms - IUIScene_CreativeMenu::staticCtor(); + // Common for all platforms + IUIScene_CreativeMenu::staticCtor(); - // On PS4, we call Minecraft::Start from another thread, as this has been timed taking ~2.5 seconds and we need to do some basic - // rendering stuff so that we don't break the TRCs on SubmitDone calls + // On PS4, we call Minecraft::Start from another thread, as this has been + // timed taking ~2.5 seconds and we need to do some basic rendering stuff so + // that we don't break the TRCs on SubmitDone calls #ifndef __ORBIS__ - Minecraft::start(name, sessionId); + Minecraft::start(name, sessionId); #endif } -bool Minecraft::renderNames() -{ - if (m_instance == NULL || !m_instance->options->hideGui) - { - return true; - } - return false; +bool Minecraft::renderNames() { + if (m_instance == NULL || !m_instance->options->hideGui) { + return true; + } + return false; } -bool Minecraft::useFancyGraphics() -{ - return (m_instance != NULL && m_instance->options->fancyGraphics); +bool Minecraft::useFancyGraphics() { + return (m_instance != NULL && m_instance->options->fancyGraphics); } -bool Minecraft::useAmbientOcclusion() -{ - return (m_instance != NULL && m_instance->options->ambientOcclusion); +bool Minecraft::useAmbientOcclusion() { + return (m_instance != NULL && m_instance->options->ambientOcclusion); } -bool Minecraft::renderDebug() -{ - return (m_instance != NULL && m_instance->options->renderDebug); +bool Minecraft::renderDebug() { + return (m_instance != NULL && m_instance->options->renderDebug); } -bool Minecraft::handleClientSideCommand(const std::wstring& chatMessage) -{ - /* 4J - TODO - if (chatMessage.startsWith("/")) { - if (DEADMAU5_CAMERA_CHEATS) { - if (chatMessage.startsWith("/follow")) { - String[] tokens = chatMessage.split(" "); - if (tokens.length >= 2) { - String playerName = tokens[1]; +bool Minecraft::handleClientSideCommand(const std::wstring& chatMessage) { + /* 4J - TODO + if (chatMessage.startsWith("/")) { + if (DEADMAU5_CAMERA_CHEATS) { + if (chatMessage.startsWith("/follow")) { + String[] tokens = chatMessage.split(" "); + if (tokens.length >= 2) { + String playerName = tokens[1]; - boolean found = false; - for (Player player : level.players) { - if (playerName.equalsIgnoreCase(player.name)) { - cameraTargetPlayer = player; - found = true; - break; - } - } + boolean found = false; + for (Player player : level.players) { + if (playerName.equalsIgnoreCase(player.name)) { + cameraTargetPlayer = player; + found = true; + break; + } + } - if (!found) { - try { - int entityId = Integer.parseInt(playerName); - for (Entity e : level.entities) { - if (e.entityId == entityId && e instanceof Mob) { - cameraTargetPlayer = (Mob) e; - found = true; - break; - } - } - } catch (NumberFormatException e) { - } - } - } + if (!found) { + try { + int entityId = Integer.parseInt(playerName); + for (Entity e : level.entities) { + if (e.entityId == entityId && e instanceof Mob) { + cameraTargetPlayer = (Mob) e; + found = true; + break; + } + } + } catch (NumberFormatException e) { + } + } + } - return true; - } - } - } - */ - return false; + return true; + } + } + } + */ + return false; } -int Minecraft::maxSupportedTextureSize() -{ - // 4J Force value - return 1024; +int Minecraft::maxSupportedTextureSize() { + // 4J Force value + return 1024; - //for (int texSize = 16384; texSize > 0; texSize >>= 1) { - // GL11.glTexImage2D(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_RGBA, texSize, texSize, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); - // final int width = GL11.glGetTexLevelParameteri(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); - // if (width != 0) { - // return texSize; - // } - //} - //return -1; + // for (int texSize = 16384; texSize > 0; texSize >>= 1) { + // GL11.glTexImage2D(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_RGBA, texSize, + //texSize, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); final + //int width = GL11.glGetTexLevelParameteri(GL11.GL_PROXY_TEXTURE_2D, 0, + //GL11.GL_TEXTURE_WIDTH); if (width != 0) { return texSize; + // } + // } + // return -1; } -void Minecraft::delayTextureReload() -{ - reloadTextures = true; -} +void Minecraft::delayTextureReload() { reloadTextures = true; } -__int64 Minecraft::currentTimeMillis() -{ - return System::currentTimeMillis();//(Sys.getTime() * 1000) / Sys.getTimerResolution(); +__int64 Minecraft::currentTimeMillis() { + return System::currentTimeMillis(); //(Sys.getTime() * 1000) / + //Sys.getTimerResolution(); } /*void Minecraft::handleMouseDown(int button, bool down) @@ -4533,7 +4725,8 @@ if (gameMode->instaBuild) return; if (!down) missTime = 0; if (button == 0 && missTime > 0) return; -if (down && hitResult != NULL && hitResult->type == HitResult::TILE && button == 0) +if (down && hitResult != NULL && hitResult->type == HitResult::TILE && button == +0) { int x = hitResult->x; int y = hitResult->y; @@ -4552,8 +4745,8 @@ void Minecraft::handleMouseClick(int button) if (button == 0 && missTime > 0) return; if (button == 0) { -app.DebugPrintf("handleMouseClick - Player %d is swinging\n",player->GetXboxPad()); -player->swing(); +app.DebugPrintf("handleMouseClick - Player %d is +swinging\n",player->GetXboxPad()); player->swing(); } bool mayUse = true; @@ -4563,25 +4756,30 @@ bool mayUse = true; // * (gameMode.useItem(player, item)) { // * gameRenderer.itemInHandRenderer.itemUsed(); return; } } } -// 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button +// 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer +game - we need to wake up, and we don't have the inbedchatscreen with a button if(button==1 && (player->isSleeping() && level != NULL && level->isClientSide)) { -std::shared_ptr mplp = std::dynamic_pointer_cast( player ); +std::shared_ptr mplp = +std::dynamic_pointer_cast( player ); if(mplp) mplp->StopSleeping(); // 4J - TODO //if (minecraft.player instanceof MultiplayerLocalPlayer) //{ -// ClientConnection connection = ((MultiplayerLocalPlayer) minecraft.player).connection; -// connection.send(new PlayerCommandPacket(minecraft.player, PlayerCommandPacket.STOP_SLEEPING)); +// ClientConnection connection = ((MultiplayerLocalPlayer) +minecraft.player).connection; +// connection.send(new PlayerCommandPacket(minecraft.player, +PlayerCommandPacket.STOP_SLEEPING)); //} } if (hitResult == NULL) { -if (button == 0 && !(dynamic_cast(gameMode) != NULL)) missTime = 10; +if (button == 0 && !(dynamic_cast(gameMode) != NULL)) missTime = +10; } else if (hitResult->type == HitResult::ENTITY) { @@ -4655,247 +4853,249 @@ gameRenderer->itemInHandRenderer->itemUsed(); */ // 4J-PB -Screen * Minecraft::getScreen() -{ - return screen; +Screen* Minecraft::getScreen() { return screen; } + +bool Minecraft::isTutorial() { + return m_inFullTutorialBits > 0; + + /*if( gameMode != NULL && gameMode->isTutorial() ) + { + return true; + } + else + { + return false; + }*/ } -bool Minecraft::isTutorial() -{ - return m_inFullTutorialBits > 0; - - /*if( gameMode != NULL && gameMode->isTutorial() ) - { - return true; - } - else - { - return false; - }*/ +void Minecraft::playerStartedTutorial(int iPad) { + // If the app doesn't think we are in a tutorial mode then just ignore this + // add + if (app.GetTutorialMode()) + m_inFullTutorialBits = m_inFullTutorialBits | (1 << iPad); } -void Minecraft::playerStartedTutorial(int iPad) -{ - // If the app doesn't think we are in a tutorial mode then just ignore this add - if( app.GetTutorialMode() ) m_inFullTutorialBits = m_inFullTutorialBits | ( 1 << iPad ); -} +void Minecraft::playerLeftTutorial(int iPad) { + // 4J Stu - Fix for bug that was flooding Sentient with LevelStart events + // If the tutorial bits are already 0 then don't need to update anything + if (m_inFullTutorialBits == 0) { + app.SetTutorialMode(false); + return; + } -void Minecraft::playerLeftTutorial(int iPad) -{ - // 4J Stu - Fix for bug that was flooding Sentient with LevelStart events - // If the tutorial bits are already 0 then don't need to update anything - if(m_inFullTutorialBits == 0) - { - app.SetTutorialMode( false ); - return; - } + m_inFullTutorialBits = m_inFullTutorialBits & ~(1 << iPad); + if (m_inFullTutorialBits == 0) { + app.SetTutorialMode(false); - m_inFullTutorialBits = m_inFullTutorialBits & ~( 1 << iPad ); - if(m_inFullTutorialBits == 0) - { - app.SetTutorialMode( false ); - - // 4J Stu -This telemetry event means something different on XboxOne, so we don't call it for simple state changes like this + // 4J Stu -This telemetry event means something different on XboxOne, so + // we don't call it for simple state changes like this #ifndef _XBOX_ONE - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(localplayers[idx] != NULL) - { - TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); - } - } + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (localplayers[idx] != NULL) { + TelemetryManager->RecordLevelStart( + idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, level->difficulty, + app.GetLocalPlayerCount(), + g_NetworkManager.GetOnlinePlayerCount()); + } + } #endif - } + } } #ifdef _DURANGO -void Minecraft::inGameSignInCheckAllPrivilegesCallback(void *lpParam, bool hasPrivileges, int iPad) -{ - Minecraft* pClass = (Minecraft*)lpParam; +void Minecraft::inGameSignInCheckAllPrivilegesCallback(void* lpParam, + bool hasPrivileges, + int iPad) { + Minecraft* pClass = (Minecraft*)lpParam; - if(!hasPrivileges) - { - ProfileManager.RemoveGamepadFromGame(iPad); - } - else - { - if( !g_NetworkManager.SessionHasSpace() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_OK; - ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); - ProfileManager.RemoveGamepadFromGame(iPad); - } - else if( ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad) ) - { - // create the local player for the iPad - std::shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) - { - if( pClass->level->isClientSide ) - { - pClass->addLocalPlayer(iPad); - } - else - { - // create the local player for the iPad - std::shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) - { - player = pClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pClass->level->dimension->id); - } - } - } - } - } + if (!hasPrivileges) { + ProfileManager.RemoveGamepadFromGame(iPad); + } else { + if (!g_NetworkManager.SessionHasSpace()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, + IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); + ProfileManager.RemoveGamepadFromGame(iPad); + } else if (ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad)) { + // create the local player for the iPad + std::shared_ptr player = pClass->localplayers[iPad]; + if (player == NULL) { + if (pClass->level->isClientSide) { + pClass->addLocalPlayer(iPad); + } else { + // create the local player for the iPad + std::shared_ptr player = pClass->localplayers[iPad]; + if (player == NULL) { + player = pClass->createExtraLocalPlayer( + iPad, + (convStringToWstring( + ProfileManager.GetGamertag(iPad))) + .c_str(), + iPad, pClass->level->dimension->id); + } + } + } + } + } } #endif -int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) -{ - Minecraft* pMinecraftClass = (Minecraft*)pParam; +int Minecraft::InGame_SignInReturned(void* pParam, bool bContinue, int iPad) { + Minecraft* pMinecraftClass = (Minecraft*)pParam; - if(g_NetworkManager.IsInSession()) - { - // 4J Stu - There seems to be a bug in the signin ui call that enables guest sign in. We never allow this within game, so make sure that it's disabled - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - app.DebugPrintf("Disabling Guest Signin\n"); - XEnableGuestSignin(FALSE); - } + if (g_NetworkManager.IsInSession()) { + // 4J Stu - There seems to be a bug in the signin ui call that enables + // guest sign in. We never allow this within game, so make sure that + // it's disabled Fix for #66516 - TCR #124: MPS Guest Support ; #001: + // BAS Game Stability: TU8: The game crashes when second Guest signs-in + // on console which takes part in Xbox LIVE multiplayer session. + app.DebugPrintf("Disabling Guest Signin\n"); + XEnableGuestSignin(FALSE); + } - // If sign in succeded, we're in game and this player isn't already playing, continue - if(bContinue==true && g_NetworkManager.IsInSession() && pMinecraftClass->localplayers[iPad] == NULL) - { - // It's possible that the player has not signed in - they can back out or choose no for the converttoguest - if(ProfileManager.IsSignedIn(iPad)) - { + // If sign in succeded, we're in game and this player isn't already playing, + // continue + if (bContinue == true && g_NetworkManager.IsInSession() && + pMinecraftClass->localplayers[iPad] == NULL) { + // It's possible that the player has not signed in - they can back out + // or choose no for the converttoguest + if (ProfileManager.IsSignedIn(iPad)) { #ifdef _DURANGO - if(!g_NetworkManager.IsLocalGame() && ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad)) - { - ProfileManager.CheckMultiplayerPrivileges(iPad, true, &inGameSignInCheckAllPrivilegesCallback, pMinecraftClass); - } - else + if (!g_NetworkManager.IsLocalGame() && + ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad)) { + ProfileManager.CheckMultiplayerPrivileges( + iPad, true, &inGameSignInCheckAllPrivilegesCallback, + pMinecraftClass); + } else #endif - if( !g_NetworkManager.SessionHasSpace() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_OK; - ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); + if (!g_NetworkManager.SessionHasSpace()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, + IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(iPad); + ProfileManager.RemoveGamepadFromGame(iPad); #endif - } - // if this is a local game then profiles just need to be signed in - else if( g_NetworkManager.IsLocalGame() || (ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad)) ) - { + } + // if this is a local game then profiles just need to be signed in + else if (g_NetworkManager.IsLocalGame() || + (ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad))) { #ifdef __ORBIS__ - bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(iPad,false,NULL,&contentRestricted,NULL); // TODO! + bool contentRestricted = false; + ProfileManager.GetChatAndContentRestrictions( + iPad, false, NULL, &contentRestricted, NULL); // TODO! - if (!g_NetworkManager.IsLocalGame() && contentRestricted) - { - ui.RequestContentRestrictedMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_CONTENT_RESTRICTION, iPad); - } - else if(!g_NetworkManager.IsLocalGame() && !ProfileManager.HasPlayStationPlus(iPad)) - { - pMinecraftClass->m_pPsPlusUpsell = new PsPlusUpsellWrapper(iPad); - pMinecraftClass->m_pPsPlusUpsell->displayUpsell(); - } - else + if (!g_NetworkManager.IsLocalGame() && contentRestricted) { + ui.RequestContentRestrictedMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_CONTENT_RESTRICTION, iPad); + } else if (!g_NetworkManager.IsLocalGame() && + !ProfileManager.HasPlayStationPlus(iPad)) { + pMinecraftClass->m_pPsPlusUpsell = + new PsPlusUpsellWrapper(iPad); + pMinecraftClass->m_pPsPlusUpsell->displayUpsell(); + } else #endif - if( pMinecraftClass->level->isClientSide ) - { - pMinecraftClass->addLocalPlayer(iPad); - } - else - { - // create the local player for the iPad - std::shared_ptr player = pMinecraftClass->localplayers[iPad]; - if( player == NULL) - { - player = pMinecraftClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pMinecraftClass->level->dimension->id); - } - } - } - else if( ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()) && !ProfileManager.AllowedToPlayMultiplayer(iPad) ) - { - // 4J Stu - Don't allow converting to guests as we don't allow any guest sign-in while in the game - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - //ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, pMinecraftClass,iPad); - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,iPad,NULL,NULL, app.GetStringTable()); + if (pMinecraftClass->level->isClientSide) { + pMinecraftClass->addLocalPlayer(iPad); + } else { + // create the local player for the iPad + std::shared_ptr player = + pMinecraftClass->localplayers[iPad]; + if (player == NULL) { + player = pMinecraftClass->createExtraLocalPlayer( + iPad, + (convStringToWstring( + ProfileManager.GetGamertag(iPad))) + .c_str(), + iPad, pMinecraftClass->level->dimension->id); + } + } + } else if (ProfileManager.IsSignedInLive( + ProfileManager.GetPrimaryPad()) && + !ProfileManager.AllowedToPlayMultiplayer(iPad)) { + // 4J Stu - Don't allow converting to guests as we don't allow + // any guest sign-in while in the game Fix for #66516 - TCR + // #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The + // game crashes when second Guest signs-in on console which + // takes part in Xbox LIVE multiplayer session. + // ProfileManager.RequestConvertOfflineToGuestUI( + // &Minecraft::InGame_SignInReturned, pMinecraftClass,iPad); + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, iPad, NULL, NULL, + app.GetStringTable()); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(iPad); + ProfileManager.RemoveGamepadFromGame(iPad); #endif - } - } - } - return 0; + } + } + } + return 0; } -void Minecraft::tickAllConnections() -{ - int oldIdx = getLocalPlayerIdx(); - for(unsigned int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - std::shared_ptr mplp = localplayers[i]; - if( mplp && mplp->connection) - { - setLocalPlayerIdx(i); - mplp->connection->tick(); - } - } - setLocalPlayerIdx(oldIdx); +void Minecraft::tickAllConnections() { + int oldIdx = getLocalPlayerIdx(); + for (unsigned int i = 0; i < XUSER_MAX_COUNT; i++) { + std::shared_ptr mplp = localplayers[i]; + if (mplp && mplp->connection) { + setLocalPlayerIdx(i); + mplp->connection->tick(); + } + } + setLocalPlayerIdx(oldIdx); } -bool Minecraft::addPendingClientTextureRequest(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.push_back(textureName); - return true; - } - return false; +bool Minecraft::addPendingClientTextureRequest( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it == m_pendingTextureRequests.end()) { + m_pendingTextureRequests.push_back(textureName); + return true; + } + return false; } -void Minecraft::handleClientTextureReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } +void Minecraft::handleClientTextureReceived(const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } } -unsigned int Minecraft::getCurrentTexturePackId() -{ - return skins->getSelected()->getId(); +unsigned int Minecraft::getCurrentTexturePackId() { + return skins->getSelected()->getId(); } -ColourTable *Minecraft::getColourTable() -{ - TexturePack *selected = skins->getSelected(); +ColourTable* Minecraft::getColourTable() { + TexturePack* selected = skins->getSelected(); - ColourTable *colours = selected->getColourTable(); + ColourTable* colours = selected->getColourTable(); - if(colours == NULL) - { - colours = skins->getDefault()->getColourTable(); - } + if (colours == NULL) { + colours = skins->getDefault()->getColourTable(); + } - return colours; + return colours; } #if defined __ORBIS__ -int Minecraft::MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessageResult result) -{ - Minecraft* pMinecraft = (Minecraft *)pParam; +int Minecraft::MustSignInReturnedPSN(void* pParam, int iPad, + C4JStorage::EMessageResult result) { + Minecraft* pMinecraft = (Minecraft*)pParam; - if(result == C4JStorage::EMessage_ResultAccept) - { - SQRNetworkManager_Orbis::AttemptPSNSignIn(&Minecraft::InGame_SignInReturned, pMinecraft, false, iPad); + if (result == C4JStorage::EMessage_ResultAccept) { + SQRNetworkManager_Orbis::AttemptPSNSignIn( + &Minecraft::InGame_SignInReturned, pMinecraft, false, iPad); } return 0; diff --git a/Minecraft.Client/Minecraft.h b/Minecraft.Client/Minecraft.h index 1e54067e3..8493675f7 100644 --- a/Minecraft.Client/Minecraft.h +++ b/Minecraft.Client/Minecraft.h @@ -46,299 +46,349 @@ class PsPlusUpsellWrapper; #undef linux #endif - - -class Minecraft -{ +class Minecraft { public: - static const std::wstring VERSION_STRING; - Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen); - void init(); + static const std::wstring VERSION_STRING; + Minecraft(Component* mouseComponent, Canvas* parent, + MinecraftApplet* minecraftApplet, int width, int height, + bool fullscreen); + void init(); - // 4J - removed - // void crash(CrashReport crash); - // public abstract void onCrash(CrashReport crash); + // 4J - removed + // void crash(CrashReport crash); + // public abstract void onCrash(CrashReport crash); private: - static Minecraft *m_instance; + static Minecraft* m_instance; public: - MultiPlayerGameMode *gameMode; + MultiPlayerGameMode* gameMode; private: - bool fullscreen; - bool hasCrashed; + bool fullscreen; + bool hasCrashed; - C4JThread::EventQueue* levelTickEventQueue; - - static void levelTickUpdateFunc(void* pParam); - static void levelTickThreadInitFunc(); + C4JThread::EventQueue* levelTickEventQueue; + + static void levelTickUpdateFunc(void* pParam); + static void levelTickThreadInitFunc(); public: - int width, height; - int width_phys, height_phys; // 4J - added - // private OpenGLCapabilities openGLCapabilities; + int width, height; + int width_phys, height_phys; // 4J - added + // private OpenGLCapabilities openGLCapabilities; private: - Timer *timer; - bool reloadTextures; + Timer* timer; + bool reloadTextures; + public: - Level *oldLevel; // 4J Stu added to keep a handle on an old level so we can delete it - //HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it is done (for async in multiplayer) + Level* oldLevel; // 4J Stu added to keep a handle on an old level so we can + // delete it + // HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it + // is done (for async in multiplayer) public: + MultiPlayerLevel* level; + LevelRenderer* levelRenderer; + std::shared_ptr player; - MultiPlayerLevel *level; - LevelRenderer *levelRenderer; - std::shared_ptr player; + MultiPlayerLevelArray levels; - MultiPlayerLevelArray levels; + std::shared_ptr localplayers[XUSER_MAX_COUNT]; + MultiPlayerGameMode* localgameModes[XUSER_MAX_COUNT]; + int localPlayerIdx; + ItemInHandRenderer* localitemInHandRenderers[XUSER_MAX_COUNT]; + // 4J-PB - so we can have debugoptions in the server + unsigned int uiDebugOptionsA[XUSER_MAX_COUNT]; - std::shared_ptr localplayers[XUSER_MAX_COUNT]; - MultiPlayerGameMode *localgameModes[XUSER_MAX_COUNT]; - int localPlayerIdx; - ItemInHandRenderer *localitemInHandRenderers[XUSER_MAX_COUNT]; - // 4J-PB - so we can have debugoptions in the server - unsigned int uiDebugOptionsA[XUSER_MAX_COUNT]; + // 4J Stu - Added these so that we can show a Xui scene while connecting + bool m_connectionFailed[XUSER_MAX_COUNT]; + DisconnectPacket::eDisconnectReason + m_connectionFailedReason[XUSER_MAX_COUNT]; + ClientConnection* m_pendingLocalConnections[XUSER_MAX_COUNT]; - // 4J Stu - Added these so that we can show a Xui scene while connecting - bool m_connectionFailed[XUSER_MAX_COUNT]; - DisconnectPacket::eDisconnectReason m_connectionFailedReason[XUSER_MAX_COUNT]; - ClientConnection *m_pendingLocalConnections[XUSER_MAX_COUNT]; + bool addLocalPlayer( + int idx); // Re-arrange the screen and start the connection + void addPendingLocalConnection(int idx, ClientConnection* connection); + void connectionDisconnected(int idx, + DisconnectPacket::eDisconnectReason reason) { + m_connectionFailed[idx] = true; + m_connectionFailedReason[idx] = reason; + } - bool addLocalPlayer(int idx); // Re-arrange the screen and start the connection - void addPendingLocalConnection(int idx, ClientConnection *connection); - void connectionDisconnected(int idx, DisconnectPacket::eDisconnectReason reason) { m_connectionFailed[idx] = true; m_connectionFailedReason[idx] = reason; } + std::shared_ptr createExtraLocalPlayer( + int idx, const std::wstring& name, int pad, int iDimension, + ClientConnection* clientConnection = NULL, + MultiPlayerLevel* levelpassedin = NULL); + void createPrimaryLocalPlayer(int iPad); + bool setLocalPlayerIdx(int idx); + int getLocalPlayerIdx(); + void removeLocalPlayerIdx(int idx); + void storeExtraLocalPlayer(int idx); + void updatePlayerViewportAssignments(); + int unoccupiedQuadrant; // 4J - added - std::shared_ptr createExtraLocalPlayer(int idx, const std::wstring& name, int pad, int iDimension, ClientConnection *clientConnection = NULL,MultiPlayerLevel *levelpassedin=NULL); - void createPrimaryLocalPlayer(int iPad); - bool setLocalPlayerIdx(int idx); - int getLocalPlayerIdx(); - void removeLocalPlayerIdx(int idx); - void storeExtraLocalPlayer(int idx); - void updatePlayerViewportAssignments(); - int unoccupiedQuadrant; // 4J - added + std::shared_ptr cameraTargetPlayer; + ParticleEngine* particleEngine; + User* user; + std::wstring serverDomain; + Canvas* parent; + bool appletMode; - std::shared_ptr cameraTargetPlayer; - ParticleEngine *particleEngine; - User *user; - std::wstring serverDomain; - Canvas *parent; - bool appletMode; + // 4J - per player ? + volatile bool pause; - // 4J - per player ? - volatile bool pause; + Textures* textures; + Font *font, *altFont; + Screen* screen; + ProgressRenderer* progressRenderer; + GameRenderer* gameRenderer; - Textures *textures; - Font *font, *altFont; - Screen *screen; - ProgressRenderer *progressRenderer; - GameRenderer *gameRenderer; private: - BackgroundDownloader *bgLoader; + BackgroundDownloader* bgLoader; - int ticks; - // 4J-PB - moved to per player + int ticks; + // 4J-PB - moved to per player - //int missTime; + // int missTime; + + int orgWidth, orgHeight; - int orgWidth, orgHeight; public: - AchievementPopup *achievementPopup; -public: - Gui *gui; - // 4J - move to the per player structure? - bool noRender; + AchievementPopup* achievementPopup; + +public: + Gui* gui; + // 4J - move to the per player structure? + bool noRender; + + HumanoidModel* humanoidModel; + HitResult* hitResult; + Options* options; - HumanoidModel *humanoidModel; - HitResult *hitResult; - Options *options; protected: - MinecraftApplet *minecraftApplet; -public: - SoundEngine *soundEngine; - MouseHandler *mouseHandler; -public: - TexturePackRepository *skins; - File workingDirectory; -private: - LevelStorageSource *levelSource; -public: - static const int frameTimes_length = 512; - static __int64 frameTimes[frameTimes_length]; - static const int tickTimes_length = 512; - static __int64 tickTimes[tickTimes_length]; - static int frameTimePos; - static __int64 warezTime; -private: - int rightClickDelay; -public: - // 4J- this should really be in localplayer - StatsCounter* stats[4]; - -private: - std::wstring connectToIp; - int connectToPort; + MinecraftApplet* minecraftApplet; public: - void clearConnectionFailed(); - void connectTo(const std::wstring& server, int port); - -private: - void renderLoadingScreen(); + SoundEngine* soundEngine; + MouseHandler* mouseHandler; public: - void blit(int x, int y, int sx, int sy, int w, int h); + TexturePackRepository* skins; + File workingDirectory; private: - static File workDir; + LevelStorageSource* levelSource; public: - static File getWorkingDirectory(); - static File getWorkingDirectory(const std::wstring& applicationName); -public: - LevelStorageSource *getLevelSource(); - void setScreen(Screen *screen); + static const int frameTimes_length = 512; + static __int64 frameTimes[frameTimes_length]; + static const int tickTimes_length = 512; + static __int64 tickTimes[tickTimes_length]; + static int frameTimePos; + static __int64 warezTime; + private: - void checkGlError(const std::wstring& string); + int rightClickDelay; + +public: + // 4J- this should really be in localplayer + StatsCounter* stats[4]; + +private: + std::wstring connectToIp; + int connectToPort; + +public: + void clearConnectionFailed(); + void connectTo(const std::wstring& server, int port); + +private: + void renderLoadingScreen(); + +public: + void blit(int x, int y, int sx, int sy, int w, int h); + +private: + static File workDir; + +public: + static File getWorkingDirectory(); + static File getWorkingDirectory(const std::wstring& applicationName); + +public: + LevelStorageSource* getLevelSource(); + void setScreen(Screen* screen); + +private: + void checkGlError(const std::wstring& string); #ifdef __ORBIS__ - PsPlusUpsellWrapper *m_pPsPlusUpsell; + PsPlusUpsellWrapper* m_pPsPlusUpsell; #endif public: - void destroy(); - volatile bool running; - std::wstring fpsString; - void run(); - // 4J-PB - split the run into 3 parts so we can run it from our xbox game loop - static Minecraft *GetInstance(); - void run_middle(); - void run_end(); + void destroy(); + volatile bool running; + std::wstring fpsString; + void run(); + // 4J-PB - split the run into 3 parts so we can run it from our xbox game + // loop + static Minecraft* GetInstance(); + void run_middle(); + void run_end(); - void emergencySave(); + void emergencySave(); - // 4J - removed - //bool wasDown ; + // 4J - removed + // bool wasDown ; private: - // void checkScreenshot(); // 4J - removed - // String grabHugeScreenshot(File workDir2, int width, int height, int ssWidth, int ssHeight); // 4J - removed + // void checkScreenshot(); // 4J - removed + // String grabHugeScreenshot(File workDir2, int width, int height, int + // ssWidth, int ssHeight); // 4J - removed - // 4J - per player thing? - __int64 lastTimer; + // 4J - per player thing? + __int64 lastTimer; - void renderFpsMeter(__int64 tickTime); -public: - void stop(); - // 4J removed - // bool mouseGrabbed; - // void grabMouse(); - // void releaseMouse(); - // 4J-PB - moved these into localplayer - //void handleMouseDown(int button, bool down); - //void handleMouseClick(int button); - - void pauseGame(); - // void toggleFullScreen(); // 4J - removed -private: - void resize(int width, int height); + void renderFpsMeter(__int64 tickTime); public: - // 4J - Moved to per player - //bool isRaining ; - - // 4J - Moved to per player - //__int64 lastTickTime; + void stop(); + // 4J removed + // bool mouseGrabbed; + // void grabMouse(); + // void releaseMouse(); + // 4J-PB - moved these into localplayer + // void handleMouseDown(int button, bool down); + // void handleMouseClick(int button); + void pauseGame(); + // void toggleFullScreen(); // 4J - removed private: - // 4J- per player? - int recheckPlayerIn; - void verify(); + void resize(int width, int height); public: - // 4J - added bFirst parameter, which is true for the first active viewport in splitscreen - // 4J - added bUpdateTextures, which is true if the actual renderer textures are to be updated - this will be true for the last time this tick runs with bFirst true - void tick(bool bFirst, bool bUpdateTextures); + // 4J - Moved to per player + // bool isRaining ; + + // 4J - Moved to per player + //__int64 lastTickTime; + private: - void reloadSound(); + // 4J- per player? + int recheckPlayerIn; + void verify(); + public: - bool isClientSide(); - void selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, const std::wstring& levelName, LevelSettings *levelSettings); - //void toggleDimension(int targetDimension); - bool saveSlot(int slot, const std::wstring& name); - bool loadSlot(const std::wstring& userName, int slot); - void releaseLevel(int message); - // 4J Stu - Added the doForceStatsSave param - //void setLevel(Level *level, bool doForceStatsSave = true); - //void setLevel(Level *level, const std::wstring& message, bool doForceStatsSave = true); - void setLevel(MultiPlayerLevel *level, int message = -1, std::shared_ptr forceInsertPlayer = nullptr, bool doForceStatsSave = true,bool bPrimaryPlayerSignedOut=false); - // 4J-PB - added to force in the 'other' level when the main player creates the level at game load time - void forceaddLevel(MultiPlayerLevel *level); - void prepareLevel(int title); // 4J - changed to public - void fileDownloaded(const std::wstring& name, File *file); - // OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed + // 4J - added bFirst parameter, which is true for the first active viewport + // in splitscreen 4J - added bUpdateTextures, which is true if the actual + // renderer textures are to be updated - this will be true for the last time + // this tick runs with bFirst true + void tick(bool bFirst, bool bUpdateTextures); - std::wstring gatherStats1(); - std::wstring gatherStats2(); - std::wstring gatherStats3(); - std::wstring gatherStats4(); +private: + void reloadSound(); - void respawnPlayer(int iPad,int dimension,int newEntityId); - static void start(const std::wstring& name, const std::wstring& sid); - static void startAndConnectTo(const std::wstring& name, const std::wstring& sid, const std::wstring& url); - ClientConnection *getConnection(int iPad); // 4J Stu added iPad param - static void main(); - static bool renderNames(); - static bool useFancyGraphics(); - static bool useAmbientOcclusion(); - static bool renderDebug(); - bool handleClientSideCommand(const std::wstring& chatMessage); +public: + bool isClientSide(); + void selectLevel(ConsoleSaveFile* saveFile, const std::wstring& levelId, + const std::wstring& levelName, + LevelSettings* levelSettings); + // void toggleDimension(int targetDimension); + bool saveSlot(int slot, const std::wstring& name); + bool loadSlot(const std::wstring& userName, int slot); + void releaseLevel(int message); + // 4J Stu - Added the doForceStatsSave param + // void setLevel(Level *level, bool doForceStatsSave = true); + // void setLevel(Level *level, const std::wstring& message, bool + // doForceStatsSave = true); + void setLevel(MultiPlayerLevel* level, int message = -1, + std::shared_ptr forceInsertPlayer = nullptr, + bool doForceStatsSave = true, + bool bPrimaryPlayerSignedOut = false); + // 4J-PB - added to force in the 'other' level when the main player creates + // the level at game load time + void forceaddLevel(MultiPlayerLevel* level); + void prepareLevel(int title); // 4J - changed to public + void fileDownloaded(const std::wstring& name, File* file); + // OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed - static int maxSupportedTextureSize(); - void delayTextureReload(); - static __int64 currentTimeMillis(); + std::wstring gatherStats1(); + std::wstring gatherStats2(); + std::wstring gatherStats3(); + std::wstring gatherStats4(); + + void respawnPlayer(int iPad, int dimension, int newEntityId); + static void start(const std::wstring& name, const std::wstring& sid); + static void startAndConnectTo(const std::wstring& name, + const std::wstring& sid, + const std::wstring& url); + ClientConnection* getConnection(int iPad); // 4J Stu added iPad param + static void main(); + static bool renderNames(); + static bool useFancyGraphics(); + static bool useAmbientOcclusion(); + static bool renderDebug(); + bool handleClientSideCommand(const std::wstring& chatMessage); + + static int maxSupportedTextureSize(); + void delayTextureReload(); + static __int64 currentTimeMillis(); #ifdef _DURANGO - static void inGameSignInCheckAllPrivilegesCallback(void *lpParam, bool hasPrivileges, int iPad); + static void inGameSignInCheckAllPrivilegesCallback(void* lpParam, + bool hasPrivileges, + int iPad); #endif - static int InGame_SignInReturned(void *pParam,bool bContinue, int iPad); - // 4J-PB - Screen * getScreen(); + static int InGame_SignInReturned(void* pParam, bool bContinue, int iPad); + // 4J-PB + Screen* getScreen(); - // 4J Stu - void forceStatsSave(int idx); + // 4J Stu + void forceStatsSave(int idx); + + CRITICAL_SECTION m_setLevelCS; - CRITICAL_SECTION m_setLevelCS; private: - // A bit field that store whether a particular quadrant is in the full tutorial or not - std::uint8_t m_inFullTutorialBits; + // A bit field that store whether a particular quadrant is in the full + // tutorial or not + std::uint8_t m_inFullTutorialBits; + public: - bool isTutorial(); - void playerStartedTutorial(int iPad); - void playerLeftTutorial(int iPad); + bool isTutorial(); + void playerStartedTutorial(int iPad); + void playerLeftTutorial(int iPad); - // 4J Added - MultiPlayerLevel *getLevel(int dimension); + // 4J Added + MultiPlayerLevel* getLevel(int dimension); - void tickAllConnections(); + void tickAllConnections(); - Level *animateTickLevel; // 4J added + Level* animateTickLevel; // 4J added - // 4J - When a client requests a texture, it should add it to here while we are waiting for it - std::vector m_pendingTextureRequests; - std::vector m_pendingGeometryRequests; // additional skin box geometry + // 4J - When a client requests a texture, it should add it to here while we + // are waiting for it + std::vector m_pendingTextureRequests; + std::vector + m_pendingGeometryRequests; // additional skin box geometry - // 4J Added - bool addPendingClientTextureRequest(const std::wstring &textureName); - void handleClientTextureReceived(const std::wstring &textureName); - void clearPendingClientTextureRequests() { m_pendingTextureRequests.clear(); } - bool addPendingClientGeometryRequest(const std::wstring &textureName); - void handleClientGeometryReceived(const std::wstring &textureName); - void clearPendingClientGeometryRequests() { m_pendingGeometryRequests.clear(); } + // 4J Added + bool addPendingClientTextureRequest(const std::wstring& textureName); + void handleClientTextureReceived(const std::wstring& textureName); + void clearPendingClientTextureRequests() { + m_pendingTextureRequests.clear(); + } + bool addPendingClientGeometryRequest(const std::wstring& textureName); + void handleClientGeometryReceived(const std::wstring& textureName); + void clearPendingClientGeometryRequests() { + m_pendingGeometryRequests.clear(); + } - unsigned int getCurrentTexturePackId(); - ColourTable *getColourTable(); + unsigned int getCurrentTexturePackId(); + ColourTable* getColourTable(); #if defined __ORBIS__ - static int MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessageResult result); + static int MustSignInReturnedPSN(void* pParam, int iPad, + C4JStorage::EMessageResult result); #endif }; diff --git a/Minecraft.Client/MinecraftServer.cpp b/Minecraft.Client/MinecraftServer.cpp index 71910a18a..cf6bf483b 100644 --- a/Minecraft.Client/MinecraftServer.cpp +++ b/Minecraft.Client/MinecraftServer.cpp @@ -1,5 +1,5 @@ #include "Platform/stdafx.h" -//#include "Minecraft.h" +// #include "Minecraft.h" #include @@ -51,57 +51,54 @@ #define DEBUG_SERVER_DONT_SPAWN_MOBS 0 -//4J Added -MinecraftServer *MinecraftServer::server = NULL; +// 4J Added +MinecraftServer* MinecraftServer::server = NULL; bool MinecraftServer::setTimeAtEndOfTick = false; __int64 MinecraftServer::setTime = 0; bool MinecraftServer::setTimeOfDayAtEndOfTick = false; __int64 MinecraftServer::setTimeOfDay = 0; -bool MinecraftServer::m_bPrimaryPlayerSignedOut=false; -bool MinecraftServer::s_bServerHalted=false; -bool MinecraftServer::s_bSaveOnExitAnswered=false; +bool MinecraftServer::m_bPrimaryPlayerSignedOut = false; +bool MinecraftServer::s_bServerHalted = false; +bool MinecraftServer::s_bSaveOnExitAnswered = false; int MinecraftServer::s_slowQueuePlayerIndex = 0; int MinecraftServer::s_slowQueueLastTime = 0; bool MinecraftServer::s_slowQueuePacketSent = false; std::unordered_map MinecraftServer::ironTimers; -MinecraftServer::MinecraftServer() -{ - // 4J - added initialisers - connection = NULL; +MinecraftServer::MinecraftServer() { + // 4J - added initialisers + connection = NULL; settings = NULL; players = NULL; - commands = NULL; + commands = NULL; running = true; - m_bLoaded = false; - stopped = false; + m_bLoaded = false; + stopped = false; tickCount = 0; - std::wstring progressStatus; + std::wstring progressStatus; progress = 0; - motd = L""; + motd = L""; - m_isServerPaused = false; - m_serverPausedEvent = new C4JThread::Event; + m_isServerPaused = false; + m_serverPausedEvent = new C4JThread::Event; - m_saveOnExit = false; - m_suspending = false; + m_saveOnExit = false; + m_suspending = false; - m_ugcPlayersVersion = 0; - m_texturePackId = 0; - maxBuildHeight = Level::maxBuildHeight; - m_postUpdateThread = NULL; + m_ugcPlayersVersion = 0; + m_texturePackId = 0; + maxBuildHeight = Level::maxBuildHeight; + m_postUpdateThread = NULL; - commandDispatcher = new ServerCommandDispatcher(); + commandDispatcher = new ServerCommandDispatcher(); } -MinecraftServer::~MinecraftServer() -{ -} +MinecraftServer::~MinecraftServer() {} -bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, std::uint32_t initSettings, bool findSeed) -{ - // 4J - removed +bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData* initData, + std::uint32_t initSettings, bool findSeed) { + // 4J - removed #if 0 commands = new ConsoleCommands(this); @@ -132,116 +129,141 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, st logger.info("Loading properties"); #endif - settings = new Settings(new File(L"server.properties")); + settings = new Settings(new File(L"server.properties")); - app.DebugPrintf("\n*** SERVER SETTINGS ***\n"); - app.DebugPrintf("ServerSettings: host-friends-only is %s\n",(app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: game-type is %s\n",(app.GetGameHostOption(eGameHostOption_GameType)==0)?"Survival Mode":"Creative Mode"); - app.DebugPrintf("ServerSettings: pvp is %s\n",(app.GetGameHostOption(eGameHostOption_PvP)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: fire spreads is %s\n",(app.GetGameHostOption(eGameHostOption_FireSpreads)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: tnt explodes is %s\n",(app.GetGameHostOption(eGameHostOption_TNT)>0)?"on":"off"); - app.DebugPrintf("\n"); + app.DebugPrintf("\n*** SERVER SETTINGS ***\n"); + app.DebugPrintf( + "ServerSettings: host-friends-only is %s\n", + (app.GetGameHostOption(eGameHostOption_FriendsOfFriends) > 0) ? "on" + : "off"); + app.DebugPrintf("ServerSettings: game-type is %s\n", + (app.GetGameHostOption(eGameHostOption_GameType) == 0) + ? "Survival Mode" + : "Creative Mode"); + app.DebugPrintf( + "ServerSettings: pvp is %s\n", + (app.GetGameHostOption(eGameHostOption_PvP) > 0) ? "on" : "off"); + app.DebugPrintf("ServerSettings: fire spreads is %s\n", + (app.GetGameHostOption(eGameHostOption_FireSpreads) > 0) + ? "on" + : "off"); + app.DebugPrintf( + "ServerSettings: tnt explodes is %s\n", + (app.GetGameHostOption(eGameHostOption_TNT) > 0) ? "on" : "off"); + app.DebugPrintf("\n"); - // TODO 4J Stu - Init a load of settings based on data passed as params - //settings->setBooleanAndSave( L"host-friends-only", (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0) ); + // TODO 4J Stu - Init a load of settings based on data passed as params + // settings->setBooleanAndSave( L"host-friends-only", + // (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0) ); - // 4J - Unused - //localIp = settings->getString(L"server-ip", L""); - //onlineMode = settings->getBoolean(L"online-mode", true); - //motd = settings->getString(L"motd", L"A Minecraft Server"); - //motd.replace('§', '$'); + // 4J - Unused + // localIp = settings->getString(L"server-ip", L""); + // onlineMode = settings->getBoolean(L"online-mode", true); + // motd = settings->getString(L"motd", L"A Minecraft Server"); + // motd.replace('§', '$'); - setAnimals(settings->getBoolean(L"spawn-animals", true)); - setNpcsEnabled(settings->getBoolean(L"spawn-npcs", true)); - setPvpAllowed(app.GetGameHostOption( eGameHostOption_PvP )>0?true:false); // settings->getBoolean(L"pvp", true); + setAnimals(settings->getBoolean(L"spawn-animals", true)); + setNpcsEnabled(settings->getBoolean(L"spawn-npcs", true)); + setPvpAllowed(app.GetGameHostOption(eGameHostOption_PvP) > 0 + ? true + : false); // settings->getBoolean(L"pvp", true); - // 4J Stu - We should never have hacked clients flying when they shouldn't be like the PC version, so enable flying always - // Fix for #46612 - TU5: Code: Multiplayer: A client can be banned for flying when accidentaly being blown by dynamite - setFlightAllowed(true); //settings->getBoolean(L"allow-flight", false); + // 4J Stu - We should never have hacked clients flying when they shouldn't + // be like the PC version, so enable flying always Fix for #46612 - TU5: + // Code: Multiplayer: A client can be banned for flying when accidentaly + // being blown by dynamite + setFlightAllowed(true); // settings->getBoolean(L"allow-flight", false); - // 4J Stu - Enabling flight to stop it kicking us when we use it + // 4J Stu - Enabling flight to stop it kicking us when we use it #ifdef _DEBUG_MENUS_ENABLED - setFlightAllowed(true); + setFlightAllowed(true); #endif #if 1 - connection = new ServerConnection(this); - Socket::Initialise(connection); // 4J - added + connection = new ServerConnection(this); + Socket::Initialise(connection); // 4J - added #else - // 4J - removed - InetAddress localAddress = null; - if (localIp.length() > 0) localAddress = InetAddress.getByName(localIp); - port = settings.getInt("server-port", DEFAULT_MINECRAFT_PORT); + // 4J - removed + InetAddress localAddress = null; + if (localIp.length() > 0) localAddress = InetAddress.getByName(localIp); + port = settings.getInt("server-port", DEFAULT_MINECRAFT_PORT); - logger.info("Starting Minecraft server on " + (localIp.length() == 0 ? "*" : localIp) + ":" + port); - try { - connection = new ServerConnection(this, localAddress, port); - } catch (IOException e) { - logger.warning("**** FAILED TO BIND TO PORT!"); - logger.log(Level.WARNING, "The exception was: " + e.toString()); - logger.warning("Perhaps a server is already running on that port?"); - return false; - } + logger.info("Starting Minecraft server on " + + (localIp.length() == 0 ? "*" : localIp) + ":" + port); + try { + connection = new ServerConnection(this, localAddress, port); + } catch (IOException e) { + logger.warning("**** FAILED TO BIND TO PORT!"); + logger.log(Level.WARNING, "The exception was: " + e.toString()); + logger.warning("Perhaps a server is already running on that port?"); + return false; + } - if (!onlineMode) { - logger.warning("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); - logger.warning("The server will make no attempt to authenticate usernames. Beware."); - logger.warning("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose."); - logger.warning("To change this, set \"online-mode\" to \"true\" in the server.settings file."); - } + if (!onlineMode) { + logger.warning("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); + logger.warning( + "The server will make no attempt to authenticate usernames. " + "Beware."); + logger.warning( + "While this makes the game possible to play without internet " + "access, it also opens up the ability for hackers to connect with " + "any username they choose."); + logger.warning( + "To change this, set \"online-mode\" to \"true\" in the " + "server.settings file."); + } #endif - setPlayers(new PlayerList(this)); + setPlayers(new PlayerList(this)); - // 4J-JEV: Need to wait for levelGenerationOptions to load. - while ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->hasLoadedData() ) - Sleep(1); + // 4J-JEV: Need to wait for levelGenerationOptions to load. + while (app.getLevelGenerationOptions() != NULL && + !app.getLevelGenerationOptions()->hasLoadedData()) + Sleep(1); - if ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->ready() ) - { - // TODO: Stop loading, add error message. - } + if (app.getLevelGenerationOptions() != NULL && + !app.getLevelGenerationOptions()->ready()) { + // TODO: Stop loading, add error message. + } - __int64 levelNanoTime = System::nanoTime(); + __int64 levelNanoTime = System::nanoTime(); - std::wstring levelName = settings->getString(L"level-name", L"world"); - std::wstring levelTypeString; + std::wstring levelName = settings->getString(L"level-name", L"world"); + std::wstring levelTypeString; - bool gameRuleUseFlatWorld = false; - if(app.getLevelGenerationOptions() != NULL) - { - gameRuleUseFlatWorld = app.getLevelGenerationOptions()->getuseFlatWorld(); - } - if(gameRuleUseFlatWorld || app.GetGameHostOption(eGameHostOption_LevelType)>0) - { - levelTypeString = settings->getString(L"level-type", L"flat"); - } - else - { - levelTypeString = settings->getString(L"level-type",L"default"); - } + bool gameRuleUseFlatWorld = false; + if (app.getLevelGenerationOptions() != NULL) { + gameRuleUseFlatWorld = + app.getLevelGenerationOptions()->getuseFlatWorld(); + } + if (gameRuleUseFlatWorld || + app.GetGameHostOption(eGameHostOption_LevelType) > 0) { + levelTypeString = settings->getString(L"level-type", L"flat"); + } else { + levelTypeString = settings->getString(L"level-type", L"default"); + } - LevelType *pLevelType = LevelType::getLevelType(levelTypeString); - if (pLevelType == NULL) - { - pLevelType = LevelType::lvl_normal; - } + LevelType* pLevelType = LevelType::getLevelType(levelTypeString); + if (pLevelType == NULL) { + pLevelType = LevelType::lvl_normal; + } - ProgressRenderer *mcprogress = Minecraft::GetInstance()->progressRenderer; - mcprogress->progressStart(IDS_PROGRESS_INITIALISING_SERVER); + ProgressRenderer* mcprogress = Minecraft::GetInstance()->progressRenderer; + mcprogress->progressStart(IDS_PROGRESS_INITIALISING_SERVER); - if( findSeed ) - { + if (findSeed) { #ifdef __PSVITA__ - seed = BiomeSource::findSeed(pLevelType, &running); + seed = BiomeSource::findSeed(pLevelType, &running); #else - seed = BiomeSource::findSeed(pLevelType); + seed = BiomeSource::findSeed(pLevelType); #endif - } + } - setMaxBuildHeight(settings->getInt(L"max-build-height", Level::maxBuildHeight)); - setMaxBuildHeight(((getMaxBuildHeight() + 8) / 16) * 16); - setMaxBuildHeight(Mth::clamp(getMaxBuildHeight(), 64, Level::maxBuildHeight)); - //settings->setProperty(L"max-build-height", maxBuildHeight); + setMaxBuildHeight( + settings->getInt(L"max-build-height", Level::maxBuildHeight)); + setMaxBuildHeight(((getMaxBuildHeight() + 8) / 16) * 16); + setMaxBuildHeight( + Mth::clamp(getMaxBuildHeight(), 64, Level::maxBuildHeight)); + // settings->setProperty(L"max-build-height", maxBuildHeight); #if 0 std::wstring levelSeedString = settings->getString(L"level-seed", L""); @@ -254,317 +276,342 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, st } } #endif -// logger.info("Preparing level \"" + levelName + "\""); - m_bLoaded = loadLevel(new McRegionLevelStorageSource(File(L".")), levelName, seed, pLevelType, initData); -// logger.info("Done (" + (System.nanoTime() - levelNanoTime) + "ns)! For help, type \"help\" or \"?\""); - app.DebugPrintf("[SRV] loadLevel returned %d\n", m_bLoaded); + // logger.info("Preparing level \"" + levelName + "\""); + m_bLoaded = loadLevel(new McRegionLevelStorageSource(File(L".")), levelName, + seed, pLevelType, initData); + // logger.info("Done (" + (System.nanoTime() - levelNanoTime) + "ns)! + // For help, type \"help\" or \"?\""); + app.DebugPrintf("[SRV] loadLevel returned %d\n", m_bLoaded); - // 4J delete passed in save data now - this is only required for the tutorial which is loaded by passing data directly in rather than using the storage manager - if( initData->saveData ) - { - delete[] reinterpret_cast(initData->saveData->data); - initData->saveData->data = 0; - initData->saveData->fileSize = 0; - } - - app.DebugPrintf("[SRV] Signaling ServerReady\n"); - g_NetworkManager.ServerReady(); // 4J added - app.DebugPrintf("[SRV] ServerReady signaled, returning m_bLoaded=%d\n", m_bLoaded); - return m_bLoaded; + // 4J delete passed in save data now - this is only required for the + // tutorial which is loaded by passing data directly in rather than using + // the storage manager + if (initData->saveData) { + delete[] reinterpret_cast(initData->saveData->data); + initData->saveData->data = 0; + initData->saveData->fileSize = 0; + } + app.DebugPrintf("[SRV] Signaling ServerReady\n"); + g_NetworkManager.ServerReady(); // 4J added + app.DebugPrintf("[SRV] ServerReady signaled, returning m_bLoaded=%d\n", + m_bLoaded); + return m_bLoaded; } -// 4J - added - extra thread to post processing on separate thread during level creation -int MinecraftServer::runPostUpdate(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::ePostProcessThread); +// 4J - added - extra thread to post processing on separate thread during level +// creation +int MinecraftServer::runPostUpdate(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::ePostProcessThread); - MinecraftServer *server = (MinecraftServer *)lpParam; - Entity::useSmallIds(); // This thread can end up spawning entities as resources - IntCache::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); - Compression::UseDefaultThreadStorage(); - Level::enableLightingCache(); - Tile::CreateNewThreadStorage(); + MinecraftServer* server = (MinecraftServer*)lpParam; + Entity::useSmallIds(); // This thread can end up spawning entities as + // resources + IntCache::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + Compression::UseDefaultThreadStorage(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); - // Update lights for both levels until we are signalled to terminate - do - { - EnterCriticalSection(&server->m_postProcessCS); - if( server->m_postProcessRequests.size() ) - { - MinecraftServer::postProcessRequest request = server->m_postProcessRequests.back(); - server->m_postProcessRequests.pop_back(); - LeaveCriticalSection(&server->m_postProcessCS); - static int count = 0; - PIXBeginNamedEvent(0,"Post processing %d ", (count++)%8); - request.chunkSource->postProcess(request.chunkSource, request.x, request.z ); - PIXEndNamedEvent(); - } - else - { - LeaveCriticalSection(&server->m_postProcessCS); - } - Sleep(1); - } while (!server->m_postUpdateTerminate && ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)); -//#ifndef __PS3__ - // One final pass through updates to make sure we're done - EnterCriticalSection(&server->m_postProcessCS); - int maxRequests = server->m_postProcessRequests.size(); - while(server->m_postProcessRequests.size() && ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread) ) - { - MinecraftServer::postProcessRequest request = server->m_postProcessRequests.back(); - server->m_postProcessRequests.pop_back(); - LeaveCriticalSection(&server->m_postProcessCS); - request.chunkSource->postProcess(request.chunkSource, request.x, request.z ); + // Update lights for both levels until we are signalled to terminate + do { + EnterCriticalSection(&server->m_postProcessCS); + if (server->m_postProcessRequests.size()) { + MinecraftServer::postProcessRequest request = + server->m_postProcessRequests.back(); + server->m_postProcessRequests.pop_back(); + LeaveCriticalSection(&server->m_postProcessCS); + static int count = 0; + PIXBeginNamedEvent(0, "Post processing %d ", (count++) % 8); + request.chunkSource->postProcess(request.chunkSource, request.x, + request.z); + PIXEndNamedEvent(); + } else { + LeaveCriticalSection(&server->m_postProcessCS); + } + Sleep(1); + } while (!server->m_postUpdateTerminate && + ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)); + // #ifndef __PS3__ + // One final pass through updates to make sure we're done + EnterCriticalSection(&server->m_postProcessCS); + int maxRequests = server->m_postProcessRequests.size(); + while (server->m_postProcessRequests.size() && + ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)) { + MinecraftServer::postProcessRequest request = + server->m_postProcessRequests.back(); + server->m_postProcessRequests.pop_back(); + LeaveCriticalSection(&server->m_postProcessCS); + request.chunkSource->postProcess(request.chunkSource, request.x, + request.z); #ifdef __PS3__ #ifndef _CONTENT_PACKAGE - if((server->m_postProcessRequests.size() % 10) == 0) - printf("processing request %00d\n", server->m_postProcessRequests.size()); + if ((server->m_postProcessRequests.size() % 10) == 0) + printf("processing request %00d\n", + server->m_postProcessRequests.size()); #endif - Sleep(1); + Sleep(1); #endif - EnterCriticalSection(&server->m_postProcessCS); - } - LeaveCriticalSection(&server->m_postProcessCS); -//#endif //__PS3__ - Tile::ReleaseThreadStorage(); - IntCache::ReleaseThreadStorage(); - AABB::ReleaseThreadStorage(); - Vec3::ReleaseThreadStorage(); - Level::destroyLightingCache(); + EnterCriticalSection(&server->m_postProcessCS); + } + LeaveCriticalSection(&server->m_postProcessCS); + // #endif //__PS3__ + Tile::ReleaseThreadStorage(); + IntCache::ReleaseThreadStorage(); + AABB::ReleaseThreadStorage(); + Vec3::ReleaseThreadStorage(); + Level::destroyLightingCache(); - ShutdownManager::HasFinished(ShutdownManager::ePostProcessThread); + ShutdownManager::HasFinished(ShutdownManager::ePostProcessThread); - return 0; + return 0; } -void MinecraftServer::addPostProcessRequest(ChunkSource *chunkSource, int x, int z) -{ - EnterCriticalSection(&m_postProcessCS); - m_postProcessRequests.push_back(MinecraftServer::postProcessRequest(x,z,chunkSource)); - LeaveCriticalSection(&m_postProcessCS); +void MinecraftServer::addPostProcessRequest(ChunkSource* chunkSource, int x, + int z) { + EnterCriticalSection(&m_postProcessCS); + m_postProcessRequests.push_back( + MinecraftServer::postProcessRequest(x, z, chunkSource)); + LeaveCriticalSection(&m_postProcessCS); } -void MinecraftServer::postProcessTerminate(ProgressRenderer *mcprogress) -{ - std::uint32_t status = 0; +void MinecraftServer::postProcessTerminate(ProgressRenderer* mcprogress) { + std::uint32_t status = 0; - EnterCriticalSection(&server->m_postProcessCS); - size_t postProcessItemCount = server->m_postProcessRequests.size(); - LeaveCriticalSection(&server->m_postProcessCS); + EnterCriticalSection(&server->m_postProcessCS); + size_t postProcessItemCount = server->m_postProcessRequests.size(); + LeaveCriticalSection(&server->m_postProcessCS); - do - { - status = m_postUpdateThread->WaitForCompletion(50); - if( status == WAIT_TIMEOUT ) - { - EnterCriticalSection(&server->m_postProcessCS); - size_t postProcessItemRemaining = server->m_postProcessRequests.size(); - LeaveCriticalSection(&server->m_postProcessCS); + do { + status = m_postUpdateThread->WaitForCompletion(50); + if (status == WAIT_TIMEOUT) { + EnterCriticalSection(&server->m_postProcessCS); + size_t postProcessItemRemaining = + server->m_postProcessRequests.size(); + LeaveCriticalSection(&server->m_postProcessCS); - if( postProcessItemCount ) - { - mcprogress->progressStagePercentage((postProcessItemCount - postProcessItemRemaining) * 100 / postProcessItemCount); - } - CompressedTileStorage::tick(); - SparseLightStorage::tick(); - SparseDataStorage::tick(); - } - } while ( status == WAIT_TIMEOUT ); - delete m_postUpdateThread; - m_postUpdateThread = NULL; - DeleteCriticalSection(&m_postProcessCS); + if (postProcessItemCount) { + mcprogress->progressStagePercentage( + (postProcessItemCount - postProcessItemRemaining) * 100 / + postProcessItemCount); + } + CompressedTileStorage::tick(); + SparseLightStorage::tick(); + SparseDataStorage::tick(); + } + } while (status == WAIT_TIMEOUT); + delete m_postUpdateThread; + m_postUpdateThread = NULL; + DeleteCriticalSection(&m_postProcessCS); } -bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::wstring& name, __int64 levelSeed, LevelType *pLevelType, NetworkGameInitData *initData) -{ -// 4J - TODO - do with new save stuff -// if (storageSource->requiresConversion(name)) -// { -// assert(false); -// } - ProgressRenderer *mcprogress = Minecraft::GetInstance()->progressRenderer; +bool MinecraftServer::loadLevel(LevelStorageSource* storageSource, + const std::wstring& name, __int64 levelSeed, + LevelType* pLevelType, + NetworkGameInitData* initData) { + // 4J - TODO - do with new save stuff + // if (storageSource->requiresConversion(name)) + // { + // assert(false); + // } + ProgressRenderer* mcprogress = Minecraft::GetInstance()->progressRenderer; - // 4J TODO - free levels here if there are already some? + // 4J TODO - free levels here if there are already some? levels = ServerLevelArray(3); - int gameTypeId = settings->getInt(L"gamemode", app.GetGameHostOption(eGameHostOption_GameType));//LevelSettings::GAMETYPE_SURVIVAL); - GameType *gameType = LevelSettings::validateGameType(gameTypeId); - app.DebugPrintf("Default game type: %d\n" , gameTypeId); + int gameTypeId = settings->getInt( + L"gamemode", + app.GetGameHostOption( + eGameHostOption_GameType)); // LevelSettings::GAMETYPE_SURVIVAL); + GameType* gameType = LevelSettings::validateGameType(gameTypeId); + app.DebugPrintf("Default game type: %d\n", gameTypeId); - LevelSettings *levelSettings = new LevelSettings(levelSeed, gameType, app.GetGameHostOption(eGameHostOption_Structures)>0?true:false, isHardcore(), true, pLevelType, initData->xzSize, initData->hellScale); - if( app.GetGameHostOption(eGameHostOption_BonusChest ) ) levelSettings->enableStartingBonusItems(); + LevelSettings* levelSettings = new LevelSettings( + levelSeed, gameType, + app.GetGameHostOption(eGameHostOption_Structures) > 0 ? true : false, + isHardcore(), true, pLevelType, initData->xzSize, initData->hellScale); + if (app.GetGameHostOption(eGameHostOption_BonusChest)) + levelSettings->enableStartingBonusItems(); - // 4J - temp - load existing level - std::shared_ptr storage = nullptr; - bool levelChunksNeedConverted = false; - if( initData->saveData != NULL ) - { - // We are loading a file from disk with the data passed in + // 4J - temp - load existing level + std::shared_ptr storage = nullptr; + bool levelChunksNeedConverted = false; + if (initData->saveData != NULL) { + // We are loading a file from disk with the data passed in -#ifdef SPLIT_SAVES - ConsoleSaveFileOriginal oldFormatSave( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); - ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( &oldFormatSave ); - - //ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); -#else - ConsoleSaveFile* pSave = new ConsoleSaveFileOriginal( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); -#endif - if(pSave->isSaveEndianDifferent()) - levelChunksNeedConverted = true; - pSave->ConvertToLocalPlatform(); // check if we need to convert this file from PS3->PS4 - - storage = std::shared_ptr(new McRegionLevelStorage(pSave, File(L"."), name, true)); - } - else - { - // We are loading a save from the storage manager #ifdef SPLIT_SAVES - bool bLevelGenBaseSave = false; - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if( levelGen != NULL && levelGen->requiresBaseSave()) - { - unsigned int fileSize = 0; - std::uint8_t *pvSaveData = levelGen->getBaseSaveData(fileSize); - if(pvSaveData && fileSize != 0) bLevelGenBaseSave = true; - } - ConsoleSaveFileSplit *newFormatSave = NULL; - if(bLevelGenBaseSave) - { - ConsoleSaveFileOriginal oldFormatSave( L"" ); - newFormatSave = new ConsoleSaveFileSplit( &oldFormatSave ); - } - else - { - newFormatSave = new ConsoleSaveFileSplit( L"" ); - } + ConsoleSaveFileOriginal oldFormatSave( + initData->saveData->saveName, initData->saveData->data, + initData->saveData->fileSize, false, initData->savePlatform); + ConsoleSaveFile* pSave = new ConsoleSaveFileSplit(&oldFormatSave); - storage = std::shared_ptr(new McRegionLevelStorage(newFormatSave, File(L"."), name, true)); + // ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( + // initData->saveData->saveName, initData->saveData->data, + // initData->saveData->fileSize, false, initData->savePlatform ); #else - storage = std::shared_ptr(new McRegionLevelStorage(new ConsoleSaveFileOriginal( L"" ), File(L"."), name, true)); + ConsoleSaveFile* pSave = new ConsoleSaveFileOriginal( + initData->saveData->saveName, initData->saveData->data, + initData->saveData->fileSize, false, initData->savePlatform); #endif - } + if (pSave->isSaveEndianDifferent()) levelChunksNeedConverted = true; + pSave->ConvertToLocalPlatform(); // check if we need to convert this + // file from PS3->PS4 -// McRegionLevelStorage *storage = new McRegionLevelStorage(new ConsoleSaveFile( L"" ), L"", L"", 0); // original -// McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), name, true); // TODO - for (unsigned int i = 0; i < levels.length; i++) - { - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) - { - return false; - } + storage = std::shared_ptr( + new McRegionLevelStorage(pSave, File(L"."), name, true)); + } else { + // We are loading a save from the storage manager +#ifdef SPLIT_SAVES + bool bLevelGenBaseSave = false; + LevelGenerationOptions* levelGen = app.getLevelGenerationOptions(); + if (levelGen != NULL && levelGen->requiresBaseSave()) { + unsigned int fileSize = 0; + std::uint8_t* pvSaveData = levelGen->getBaseSaveData(fileSize); + if (pvSaveData && fileSize != 0) bLevelGenBaseSave = true; + } + ConsoleSaveFileSplit* newFormatSave = NULL; + if (bLevelGenBaseSave) { + ConsoleSaveFileOriginal oldFormatSave(L""); + newFormatSave = new ConsoleSaveFileSplit(&oldFormatSave); + } else { + newFormatSave = new ConsoleSaveFileSplit(L""); + } -// String levelName = name; -// if (i == 1) levelName += "_nether"; - int dimension = 0; - if (i == 1) dimension = -1; - if (i == 2) dimension = 1; - if (i == 0) - { - levels[i] = new ServerLevel(this, storage, name, dimension, levelSettings); - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *mapOptions = app.getLevelGenerationOptions(); - Pos *spawnPos = mapOptions->getSpawnPos(); - if( spawnPos != NULL ) - { - levels[i]->setSpawnPos( spawnPos ); - } + storage = std::shared_ptr( + new McRegionLevelStorage(newFormatSave, File(L"."), name, true)); +#else + storage = + std::shared_ptr(new McRegionLevelStorage( + new ConsoleSaveFileOriginal(L""), File(L"."), name, true)); +#endif + } - levels[i]->getLevelData()->setHasBeenInCreative(mapOptions->isFromDLC()); - } - } - else levels[i] = new DerivedServerLevel(this, storage, name, dimension, levelSettings, levels[0]); -// levels[i]->addListener(new ServerLevelListener(this, levels[i])); // 4J - have moved this to the ServerLevel ctor so that it is set up in time for the first chunk to load, which might actually happen there + // McRegionLevelStorage *storage = new McRegionLevelStorage(new + //ConsoleSaveFile( L"" ), L"", L"", 0); // original + // McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), + // name, true); // TODO + for (unsigned int i = 0; i < levels.length; i++) { + if (s_bServerHalted || !g_NetworkManager.IsInSession()) { + return false; + } - // 4J Stu - We set the levels difficulty based on the minecraft options - //levels[i]->difficulty = settings->getBoolean(L"spawn-monsters", true) ? Difficulty::EASY : Difficulty::PEACEFUL; - Minecraft *pMinecraft = Minecraft::GetInstance(); -// m_lastSentDifficulty = pMinecraft->options->difficulty; - levels[i]->difficulty = app.GetGameHostOption(eGameHostOption_Difficulty); //pMinecraft->options->difficulty; - app.DebugPrintf("MinecraftServer::loadLevel - Difficulty = %d\n",levels[i]->difficulty); + // String levelName = name; + // if (i == 1) levelName += "_nether"; + int dimension = 0; + if (i == 1) dimension = -1; + if (i == 2) dimension = 1; + if (i == 0) { + levels[i] = + new ServerLevel(this, storage, name, dimension, levelSettings); + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* mapOptions = + app.getLevelGenerationOptions(); + Pos* spawnPos = mapOptions->getSpawnPos(); + if (spawnPos != NULL) { + levels[i]->setSpawnPos(spawnPos); + } + + levels[i]->getLevelData()->setHasBeenInCreative( + mapOptions->isFromDLC()); + } + } else + levels[i] = new DerivedServerLevel(this, storage, name, dimension, + levelSettings, levels[0]); + // levels[i]->addListener(new ServerLevelListener(this, + // levels[i])); // 4J - have moved this to the + // ServerLevel ctor so that it is set up in time for the first + // chunk to load, which might actually happen there + + // 4J Stu - We set the levels difficulty based on the minecraft options + // levels[i]->difficulty = settings->getBoolean(L"spawn-monsters", true) + // ? Difficulty::EASY : Difficulty::PEACEFUL; + Minecraft* pMinecraft = Minecraft::GetInstance(); + // m_lastSentDifficulty = pMinecraft->options->difficulty; + levels[i]->difficulty = app.GetGameHostOption( + eGameHostOption_Difficulty); // pMinecraft->options->difficulty; + app.DebugPrintf("MinecraftServer::loadLevel - Difficulty = %d\n", + levels[i]->difficulty); #if DEBUG_SERVER_DONT_SPAWN_MOBS levels[i]->setSpawnSettings(false, false); #else - levels[i]->setSpawnSettings(settings->getBoolean(L"spawn-monsters", true), animals); + levels[i]->setSpawnSettings( + settings->getBoolean(L"spawn-monsters", true), animals); #endif - levels[i]->getLevelData()->setGameType(gameType); + levels[i]->getLevelData()->setGameType(gameType); players->setLevel(levels); } - if( levels[0]->isNew ) - { - mcprogress->progressStage(IDS_PROGRESS_GENERATING_SPAWN_AREA); - } - else - { - mcprogress->progressStage(IDS_PROGRESS_LOADING_SPAWN_AREA); - } - app.SetGameHostOption( eGameHostOption_HasBeenInCreative, gameType == GameType::CREATIVE || levels[0]->getHasBeenInCreative() ); - app.SetGameHostOption( eGameHostOption_Structures, levels[0]->isGenerateMapFeatures() ); + if (levels[0]->isNew) { + mcprogress->progressStage(IDS_PROGRESS_GENERATING_SPAWN_AREA); + } else { + mcprogress->progressStage(IDS_PROGRESS_LOADING_SPAWN_AREA); + } + app.SetGameHostOption( + eGameHostOption_HasBeenInCreative, + gameType == GameType::CREATIVE || levels[0]->getHasBeenInCreative()); + app.SetGameHostOption(eGameHostOption_Structures, + levels[0]->isGenerateMapFeatures()); - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - // 4J - Make a new thread to do post processing - InitializeCriticalSection(&m_postProcessCS); + // 4J - Make a new thread to do post processing + InitializeCriticalSection(&m_postProcessCS); - app.DebugPrintf("[SRV] Starting post-processing thread\n"); + app.DebugPrintf("[SRV] Starting post-processing thread\n"); - m_postUpdateThread = new C4JThread(runPostUpdate, this, "Post processing", 256*1024); + m_postUpdateThread = + new C4JThread(runPostUpdate, this, "Post processing", 256 * 1024); - m_postUpdateTerminate = false; - m_postUpdateThread->SetProcessor(CPU_CORE_POST_PROCESSING); - m_postUpdateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); - m_postUpdateThread->Run(); - app.DebugPrintf("[SRV] Post-processing thread started\n"); + m_postUpdateTerminate = false; + m_postUpdateThread->SetProcessor(CPU_CORE_POST_PROCESSING); + m_postUpdateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); + m_postUpdateThread->Run(); + app.DebugPrintf("[SRV] Post-processing thread started\n"); - __int64 startTime = System::currentTimeMillis(); + __int64 startTime = System::currentTimeMillis(); - // 4J Stu - Added this to temporarily make starting games on vita faster + // 4J Stu - Added this to temporarily make starting games on vita faster #ifdef __PSVITA__ - int r = 48; + int r = 48; #else - int r = 196; + int r = 196; #endif - // 4J JEV: load gameRules. - ConsoleSavePath filepath(GAME_RULE_SAVENAME); - ConsoleSaveFile *csf = getLevel(0)->getLevelStorage()->getSaveFile(); - if( csf->doesFileExist(filepath) ) - { - unsigned int numberOfBytesRead; - byteArray ba_gameRules; + // 4J JEV: load gameRules. + ConsoleSavePath filepath(GAME_RULE_SAVENAME); + ConsoleSaveFile* csf = getLevel(0)->getLevelStorage()->getSaveFile(); + if (csf->doesFileExist(filepath)) { + unsigned int numberOfBytesRead; + byteArray ba_gameRules; - FileEntry *fe = csf->createFile(filepath); + FileEntry* fe = csf->createFile(filepath); - ba_gameRules.length = fe->getFileSize(); - ba_gameRules.data = new std::uint8_t[ ba_gameRules.length ]; + ba_gameRules.length = fe->getFileSize(); + ba_gameRules.data = new std::uint8_t[ba_gameRules.length]; - csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); - csf->readFile(fe, ba_gameRules.data, ba_gameRules.length, &numberOfBytesRead); - assert(numberOfBytesRead == ba_gameRules.length); + csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); + csf->readFile(fe, ba_gameRules.data, ba_gameRules.length, + &numberOfBytesRead); + assert(numberOfBytesRead == ba_gameRules.length); - app.m_gameRules.loadGameRules(ba_gameRules.data, ba_gameRules.length); - csf->closeHandle(fe); - } + app.m_gameRules.loadGameRules(ba_gameRules.data, ba_gameRules.length); + csf->closeHandle(fe); + } __int64 lastTime = System::currentTimeMillis(); - // 4J Stu - This loop is changed in 1.0.1 to only process the first level (ie the overworld), but I think we still want to do them all - int i = 0; - for (int i = 0; i < levels.length ; i++) - { -// logger.info("Preparing start region for level " + i); - if (i == 0 || settings->getBoolean(L"allow-nether", true)) - { - ServerLevel *level = levels[i]; - if(levelChunksNeedConverted) - { -// storage->getSaveFile()->convertLevelChunks(level) - } + // 4J Stu - This loop is changed in 1.0.1 to only process the first level + // (ie the overworld), but I think we still want to do them all + int i = 0; + for (int i = 0; i < levels.length; i++) { + // logger.info("Preparing start region for level " + i); + if (i == 0 || settings->getBoolean(L"allow-nether", true)) { + ServerLevel* level = levels[i]; + if (levelChunksNeedConverted) { + // storage->getSaveFile()->convertLevelChunks(level) + } #if 0 __int64 lastStorageTickTime = System::currentTimeMillis(); @@ -590,53 +637,63 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::ws } } #else - __int64 lastStorageTickTime = System::currentTimeMillis(); - Pos *spawnPos = level->getSharedSpawnPos(); - app.DebugPrintf("[SRV] dim=%d spawn=(%d,%d) r=%d\n", i, spawnPos->x, spawnPos->z, r); + __int64 lastStorageTickTime = System::currentTimeMillis(); + Pos* spawnPos = level->getSharedSpawnPos(); + app.DebugPrintf("[SRV] dim=%d spawn=(%d,%d) r=%d\n", i, spawnPos->x, + spawnPos->z, r); - int twoRPlusOne = r*2 + 1; - int total = twoRPlusOne * twoRPlusOne; - int chunksDone = 0; - for (int x = -r; x <= r && running; x += 16) - { - for (int z = -r; z <= r && running; z += 16) - { - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) - { - delete spawnPos; - m_postUpdateTerminate = true; - postProcessTerminate(mcprogress); - return false; - } -// printf(">>>%d %d %d\n",i,x,z); -// __int64 now = System::currentTimeMillis(); -// if (now < lastTime) lastTime = now; -// if (now > lastTime + 1000) - { - int pos = (x + r) * twoRPlusOne + (z + 1); -// setProgress(L"Preparing spawn area", (pos) * 100 / total); - mcprogress->progressStagePercentage((pos+r) * 100 / total); -// lastTime = now; + int twoRPlusOne = r * 2 + 1; + int total = twoRPlusOne * twoRPlusOne; + int chunksDone = 0; + for (int x = -r; x <= r && running; x += 16) { + for (int z = -r; z <= r && running; z += 16) { + if (s_bServerHalted || !g_NetworkManager.IsInSession()) { + delete spawnPos; + m_postUpdateTerminate = true; + postProcessTerminate(mcprogress); + return false; + } + // printf(">>>%d %d + //%d\n",i,x,z); + // __int64 now = + // System::currentTimeMillis(); if (now < + // lastTime) lastTime = now; if (now > + // lastTime + 1000) + { + int pos = (x + r) * twoRPlusOne + (z + 1); + // setProgress(L"Preparing spawn + // area", (pos) * 100 / total); + mcprogress->progressStagePercentage((pos + r) * 100 / + total); + // lastTime = now; + } + static int count = 0; + PIXBeginNamedEvent(0, "Creating %d ", (count++) % 8); + level->cache->create((spawnPos->x + x) >> 4, + (spawnPos->z + z) >> 4, + true); // 4J - added parameter to + // disable postprocessing here + PIXEndNamedEvent(); + chunksDone++; + if (chunksDone % 50 == 0) + app.DebugPrintf("[SRV] dim=%d chunk %d/%d\n", i, + chunksDone, total); + // while (level->updateLights() && + // running) + // ; + if (System::currentTimeMillis() - lastStorageTickTime > + 50) { + CompressedTileStorage::tick(); + SparseLightStorage::tick(); + SparseDataStorage::tick(); + lastStorageTickTime = System::currentTimeMillis(); } - static int count = 0; - PIXBeginNamedEvent(0,"Creating %d ", (count++)%8); - level->cache->create((spawnPos->x + x) >> 4, (spawnPos->z + z) >> 4, true); // 4J - added parameter to disable postprocessing here - PIXEndNamedEvent(); - chunksDone++; - if(chunksDone % 50 == 0) app.DebugPrintf("[SRV] dim=%d chunk %d/%d\n", i, chunksDone, total); -// while (level->updateLights() && running) -// ; - if( System::currentTimeMillis() - lastStorageTickTime > 50 ) - { - CompressedTileStorage::tick(); - SparseLightStorage::tick(); - SparseDataStorage::tick(); - lastStorageTickTime = System::currentTimeMillis(); - } } } - // 4J - removed this as now doing the recheckGaps call when each chunk is post-processed, so can happen on things outside of the spawn area too + // 4J - removed this as now doing the recheckGaps call when each + // chunk is post-processed, so can happen on things outside of the + // spawn area too #if 0 // 4J - added this code to propagate lighting properly in the spawn area before we go sharing it with the local client or across the network for (int x = -r; x <= r && running; x += 16) @@ -650,754 +707,778 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::ws } #endif - delete spawnPos; + delete spawnPos; #endif } } -// printf("Main thread complete at %dms\n",System::currentTimeMillis() - startTime); + // printf("Main thread complete at %dms\n",System::currentTimeMillis() - + //startTime); - app.DebugPrintf("[SRV] All chunk loops done, waiting for postProcess\n"); - // Wait for post processing, then lighting threads, to end (post-processing may make more lighting changes) - m_postUpdateTerminate = true; + app.DebugPrintf("[SRV] All chunk loops done, waiting for postProcess\n"); + // Wait for post processing, then lighting threads, to end (post-processing + // may make more lighting changes) + m_postUpdateTerminate = true; - postProcessTerminate(mcprogress); - app.DebugPrintf("[SRV] postProcessTerminate done\n"); + postProcessTerminate(mcprogress); + app.DebugPrintf("[SRV] postProcessTerminate done\n"); + // stronghold position? + if (levels[0]->dimension->id == 0) { + app.DebugPrintf("===================================\n"); - // stronghold position? - if(levels[0]->dimension->id==0) - { + if (!levels[0]->getLevelData()->getHasStronghold()) { + int x, z; + if (app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold, &x, + &z)) { + levels[0]->getLevelData()->setXStronghold(x); + levels[0]->getLevelData()->setZStronghold(z); + levels[0]->getLevelData()->setHasStronghold(); - app.DebugPrintf("===================================\n"); + app.DebugPrintf( + "=== FOUND stronghold in terrain features list\n"); - if(!levels[0]->getLevelData()->getHasStronghold()) - { - int x,z; - if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) - { - levels[0]->getLevelData()->setXStronghold(x); - levels[0]->getLevelData()->setZStronghold(z); - levels[0]->getLevelData()->setHasStronghold(); + } else { + // can't find the stronghold position in the terrain feature + // list. Do we have to run a post-process? + app.DebugPrintf( + "=== Can't find stronghold in terrain features list\n"); + } + } else { + app.DebugPrintf("=== Leveldata has stronghold position\n"); + } + app.DebugPrintf("===================================\n"); + } - app.DebugPrintf("=== FOUND stronghold in terrain features list\n"); + // printf("Post processing complete at %dms\n",System::currentTimeMillis() + //- startTime); - } - else - { - // can't find the stronghold position in the terrain feature list. Do we have to run a post-process? - app.DebugPrintf("=== Can't find stronghold in terrain features list\n"); - } - } - else - { - app.DebugPrintf("=== Leveldata has stronghold position\n"); - } - app.DebugPrintf("===================================\n"); - } + // printf("Lighting complete at %dms\n",System::currentTimeMillis() - + //startTime); -// printf("Post processing complete at %dms\n",System::currentTimeMillis() - startTime); + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; -// printf("Lighting complete at %dms\n",System::currentTimeMillis() - startTime); + if (levels[1]->isNew) { + levels[1]->save(true, mcprogress); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; - - if( levels[1]->isNew ) - { - levels[1]->save(true, mcprogress); - } + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (levels[2]->isNew) { + levels[2]->save(true, mcprogress); + } - if( levels[2]->isNew ) - { - levels[2]->save(true, mcprogress); - } + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + // 4J - added - immediately save newly created level, like single player + // game 4J Stu - We also want to immediately save the tutorial + if (levels[0]->isNew) saveGameRules(); - // 4J - added - immediately save newly created level, like single player game - // 4J Stu - We also want to immediately save the tutorial - if ( levels[0]->isNew ) - saveGameRules(); - - if( levels[0]->isNew ) - { - app.DebugPrintf("[SRV] Saving level 0...\n"); - levels[0]->save(true, mcprogress); - app.DebugPrintf("[SRV] Level 0 saved\n"); - } + if (levels[0]->isNew) { + app.DebugPrintf("[SRV] Saving level 0...\n"); + levels[0]->save(true, mcprogress); + app.DebugPrintf("[SRV] Level 0 saved\n"); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( levels[0]->isNew || levels[1]->isNew || levels[2]->isNew ) - { - app.DebugPrintf("[SRV] Saving to disc...\n"); - levels[0]->saveToDisc(mcprogress, false); - app.DebugPrintf("[SRV] saveToDisc done\n"); - } + if (levels[0]->isNew || levels[1]->isNew || levels[2]->isNew) { + app.DebugPrintf("[SRV] Saving to disc...\n"); + levels[0]->saveToDisc(mcprogress, false); + app.DebugPrintf("[SRV] saveToDisc done\n"); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; -/* -* int r = 24; for (int x = -r; x <= r; x++) { -* setProgress("Preparing spawn area", (x + r) * 100 / (r + r + 1)); for (int z -* = -r; z <= r; z++) { if (!running) return; level.cache.create((level.xSpawn -* >> 4) + x, (level.zSpawn >> 4) + z); while (running && level.updateLights()) -* ; } } -*/ + /* + * int r = 24; for (int x = -r; x <= r; x++) { + * setProgress("Preparing spawn area", (x + r) * 100 / (r + r + 1)); for + * (int z = -r; z <= r; z++) { if (!running) return; + * level.cache.create((level.xSpawn + * >> 4) + x, (level.zSpawn >> 4) + z); while (running && + * level.updateLights()) ; } } + */ endProgress(); - return true; + return true; } -void MinecraftServer::setProgress(const std::wstring& status, int progress) -{ +void MinecraftServer::setProgress(const std::wstring& status, int progress) { progressStatus = status; this->progress = progress; -// logger.info(status + ": " + progress + "%"); + // logger.info(status + ": " + progress + "%"); } -void MinecraftServer::endProgress() -{ +void MinecraftServer::endProgress() { progressStatus = L""; this->progress = 0; } -void MinecraftServer::saveAllChunks() -{ -// logger.info("Saving chunks"); - for (unsigned int i = 0; i < levels.length; i++) - { - // 4J Stu - Due to the way save mounting is handled on XboxOne, we can actually save after the player has signed out. +void MinecraftServer::saveAllChunks() { + // logger.info("Saving chunks"); + for (unsigned int i = 0; i < levels.length; i++) { + // 4J Stu - Due to the way save mounting is handled on XboxOne, we can + // actually save after the player has signed out. #ifndef _XBOX_ONE - if( m_bPrimaryPlayerSignedOut ) break; + if (m_bPrimaryPlayerSignedOut) break; #endif - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - i]; - if( level ) // 4J - added check as level can be NULL if we end up in stopServer really early on due to network failure - { - level->save(true, Minecraft::GetInstance()->progressRenderer); + // 4J Stu - Save the levels in reverse order so we don't overwrite the + // level.dat with the data from the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a bed will place + // player at nighttime when restarting. + ServerLevel* level = levels[levels.length - 1 - i]; + if (level) // 4J - added check as level can be NULL if we end up in + // stopServer really early on due to network failure + { + level->save(true, Minecraft::GetInstance()->progressRenderer); - // Only close the level storage when we have saved the last level, otherwise we need to recreate the region files - // when saving the next levels - if( i == (levels.length - 1)) - { - level->closeLevelStorage(); - } - } + // Only close the level storage when we have saved the last level, + // otherwise we need to recreate the region files when saving the + // next levels + if (i == (levels.length - 1)) { + level->closeLevelStorage(); + } + } } } // 4J-JEV: Added -void MinecraftServer::saveGameRules() -{ +void MinecraftServer::saveGameRules() { #ifndef _CONTENT_PACKAGE - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getLevelStorage()->getSaveFile(); - FileEntry *fe = csf->createFile(ConsoleSavePath(GAME_RULE_SAVENAME)); - csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); - unsigned int length; - csf->writeFile(fe, ba.data, ba.length, &length ); + if (ba.data != NULL) { + ConsoleSaveFile* csf = + getLevel(0)->getLevelStorage()->getSaveFile(); + FileEntry* fe = + csf->createFile(ConsoleSavePath(GAME_RULE_SAVENAME)); + csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); + unsigned int length; + csf->writeFile(fe, ba.data, ba.length, &length); - delete [] ba.data; + delete[] ba.data; - csf->closeHandle(fe); - } - } + csf->closeHandle(fe); + } + } } -void MinecraftServer::Suspend() -{ - PIXBeginNamedEvent(0,"Suspending server"); - m_suspending = true; - // Get the frequency of the timer - LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; - float fElapsedTime = 0.0f; - QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; - // Save the start time - QueryPerformanceCounter( &qwTime ); - if(m_bLoaded && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) - { - if (players != NULL) - { - players->saveAll(NULL); - } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - level->Suspend(); - } - if( !s_bServerHalted ) - { - saveGameRules(); - levels[0]->saveToDisc(NULL, true); - } - } - QueryPerformanceCounter( &qwNewTime ); +void MinecraftServer::Suspend() { + PIXBeginNamedEvent(0, "Suspending server"); + m_suspending = true; + // Get the frequency of the timer + LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; + float fElapsedTime = 0.0f; + QueryPerformanceFrequency(&qwTicksPerSec); + float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + // Save the start time + QueryPerformanceCounter(&qwTime); + if (m_bLoaded && ProfileManager.IsFullVersion() && + (!StorageManager.GetSaveDisabled())) { + if (players != NULL) { + players->saveAll(NULL); + } + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we don't overwrite + // the level.dat with the data from the nethers leveldata. Fix for + // #7418 - Functional: Gameplay: Saving after sleeping in a bed will + // place player at nighttime when restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + level->Suspend(); + } + if (!s_bServerHalted) { + saveGameRules(); + levels[0]->saveToDisc(NULL, true); + } + } + QueryPerformanceCounter(&qwNewTime); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - // 4J-JEV: Flush stats and call PlayerSessionExit. - for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) - { - if (ProfileManager.IsSignedIn(iPad)) - { - TelemetryManager->RecordPlayerSessionExit(iPad, DisconnectPacket::eDisconnect_Quitting); - } - } + // 4J-JEV: Flush stats and call PlayerSessionExit. + for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) { + if (ProfileManager.IsSignedIn(iPad)) { + TelemetryManager->RecordPlayerSessionExit( + iPad, DisconnectPacket::eDisconnect_Quitting); + } + } - m_suspending = false; - app.DebugPrintf("Suspend server: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + m_suspending = false; + app.DebugPrintf("Suspend server: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); } -bool MinecraftServer::IsSuspending() -{ - return m_suspending; -} +bool MinecraftServer::IsSuspending() { return m_suspending; } -void MinecraftServer::stopServer() -{ - - // 4J-PB - need to halt the rendering of the data, since we're about to remove it +void MinecraftServer::stopServer() { + // 4J-PB - need to halt the rendering of the data, since we're about to + // remove it #ifdef __PS3__ - if( ShutdownManager::ShouldRun(ShutdownManager::eServerThread ) ) // This thread will take itself out if we are shutting down + if (ShutdownManager::ShouldRun( + ShutdownManager::eServerThread)) // This thread will take itself + // out if we are shutting down #endif - { - Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); - } + { + Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); + } - connection->stop(); + connection->stop(); - app.DebugPrintf("Stopping server\n"); -// logger.info("Stopping server"); - // 4J-PB - If the primary player has signed out, then don't attempt to save anything - - // also need to check for a profile switch here - primary player signs out, and another player signs in before dismissing the dash + app.DebugPrintf("Stopping server\n"); + // logger.info("Stopping server"); + // 4J-PB - If the primary player has signed out, then don't attempt to save + // anything + + // also need to check for a profile switch here - primary player signs out, + // and another player signs in before dismissing the dash #ifdef _DURANGO - // On Durango check if the primary user is signed in OR mid-sign-out - if(ProfileManager.GetUser(0, true) != nullptr) + // On Durango check if the primary user is signed in OR mid-sign-out + if (ProfileManager.GetUser(0, true) != nullptr) #else - if((m_bPrimaryPlayerSignedOut==false) && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) + if ((m_bPrimaryPlayerSignedOut == false) && + ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) #endif - { + { #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Always save on exit! Except if saves are disabled. - if(!saveOnExitAnswered()) m_saveOnExit = true; + // Always save on exit! Except if saves are disabled. + if (!saveOnExitAnswered()) m_saveOnExit = true; #endif - // if trial version or saving is disabled, then don't save anything - if(m_saveOnExit && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) - { - if (players != NULL) - { - players->saveAll(Minecraft::GetInstance()->progressRenderer, true); - } - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - //for (unsigned int i = levels.length - 1; i >= 0; i--) - //{ - // ServerLevel *level = levels[i]; - // if (level != NULL) - // { - saveAllChunks(); - // } - //} + // if trial version or saving is disabled, then don't save anything + if (m_saveOnExit && ProfileManager.IsFullVersion() && + (!StorageManager.GetSaveDisabled())) { + if (players != NULL) { + players->saveAll(Minecraft::GetInstance()->progressRenderer, + true); + } + // 4J Stu - Save the levels in reverse order so we don't overwrite + // the level.dat with the data from the nethers leveldata. Fix for + // #7418 - Functional: Gameplay: Saving after sleeping in a bed will + // place player at nighttime when restarting. + // for (unsigned int i = levels.length - 1; i >= 0; i--) + //{ + // ServerLevel *level = levels[i]; + // if (level != NULL) + // { + saveAllChunks(); + // } + //} - saveGameRules(); - app.m_gameRules.unloadCurrentGameRules(); - if( levels[0] != NULL ) // This can be null if stopServer happens very quickly due to network error - { - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, false); - } - } - } - // reset the primary player signout flag - m_bPrimaryPlayerSignedOut=false; - s_bServerHalted = false; + saveGameRules(); + app.m_gameRules.unloadCurrentGameRules(); + if (levels[0] != NULL) // This can be null if stopServer happens + // very quickly due to network error + { + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, false); + } + } + } + // reset the primary player signout flag + m_bPrimaryPlayerSignedOut = false; + s_bServerHalted = false; - // On Durango/Orbis, we need to wait for all the asynchronous saving processes to complete before destroying the levels, as that will ultimately delete - // the directory level storage & therefore the ConsoleSaveSplit instance, which needs to be around until all the sub files have completed saving. + // On Durango/Orbis, we need to wait for all the asynchronous saving + // processes to complete before destroying the levels, as that will + // ultimately delete the directory level storage & therefore the + // ConsoleSaveSplit instance, which needs to be around until all the sub + // files have completed saving. #if defined(_DURANGO) || defined(__ORBIS__) || defined(__PSVITA__) - while(StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) - { - Sleep(10); - } + while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) { + Sleep(10); + } #endif - // 4J-PB remove the server levels - unsigned int iServerLevelC=levels.length; - for (unsigned int i = 0; i < iServerLevelC; i++) - { - if(levels[i]!=NULL) - { - delete levels[i]; - levels[i] = NULL; - } - } + // 4J-PB remove the server levels + unsigned int iServerLevelC = levels.length; + for (unsigned int i = 0; i < iServerLevelC; i++) { + if (levels[i] != NULL) { + delete levels[i]; + levels[i] = NULL; + } + } #if defined(__PS3__) || defined(__ORBIS__) - // Clear the update flags as it's possible they could be out of sync, causing a crash when starting a new world after the first new level ticks - // Fix for PS3 #1538 - [IN GAME] If the user 'Exit without saving' from inside the Nether or The End, the title can hang when loading back into the save. + // Clear the update flags as it's possible they could be out of sync, + // causing a crash when starting a new world after the first new level ticks + // Fix for PS3 #1538 - [IN GAME] If the user 'Exit without saving' from + // inside the Nether or The End, the title can hang when loading back into + // the save. #endif - delete connection; - connection = NULL; - delete players; - players = NULL; - delete settings; - settings = NULL; + delete connection; + connection = NULL; + delete players; + players = NULL; + delete settings; + settings = NULL; - g_NetworkManager.ServerStopped(); + g_NetworkManager.ServerStopped(); } -void MinecraftServer::halt() -{ - running = false; +void MinecraftServer::halt() { running = false; } + +void MinecraftServer::setMaxBuildHeight(int maxBuildHeight) { + this->maxBuildHeight = maxBuildHeight; } -void MinecraftServer::setMaxBuildHeight(int maxBuildHeight) -{ - this->maxBuildHeight = maxBuildHeight; +int MinecraftServer::getMaxBuildHeight() { return maxBuildHeight; } + +PlayerList* MinecraftServer::getPlayers() { return players; } + +void MinecraftServer::setPlayers(PlayerList* players) { + this->players = players; } -int MinecraftServer::getMaxBuildHeight() -{ - return maxBuildHeight; +ServerConnection* MinecraftServer::getConnection() { return connection; } + +bool MinecraftServer::isAnimals() { return animals; } + +void MinecraftServer::setAnimals(bool animals) { this->animals = animals; } + +bool MinecraftServer::isNpcsEnabled() { return npcs; } + +void MinecraftServer::setNpcsEnabled(bool npcs) { this->npcs = npcs; } + +bool MinecraftServer::isPvpAllowed() { return pvp; } + +void MinecraftServer::setPvpAllowed(bool pvp) { this->pvp = pvp; } + +bool MinecraftServer::isFlightAllowed() { return allowFlight; } + +void MinecraftServer::setFlightAllowed(bool allowFlight) { + this->allowFlight = allowFlight; } -PlayerList *MinecraftServer::getPlayers() -{ - return players; +bool MinecraftServer::isNetherEnabled() { + return true; // settings.getBoolean("allow-nether", true); } -void MinecraftServer::setPlayers(PlayerList *players) -{ - this->players = players; -} +bool MinecraftServer::isHardcore() { return false; } -ServerConnection *MinecraftServer::getConnection() -{ - return connection; -} - -bool MinecraftServer::isAnimals() -{ - return animals; -} - -void MinecraftServer::setAnimals(bool animals) -{ - this->animals = animals; -} - -bool MinecraftServer::isNpcsEnabled() -{ - return npcs; -} - -void MinecraftServer::setNpcsEnabled(bool npcs) -{ - this->npcs = npcs; -} - -bool MinecraftServer::isPvpAllowed() -{ - return pvp; -} - -void MinecraftServer::setPvpAllowed(bool pvp) -{ - this->pvp = pvp; -} - -bool MinecraftServer::isFlightAllowed() -{ - return allowFlight; -} - -void MinecraftServer::setFlightAllowed(bool allowFlight) -{ - this->allowFlight = allowFlight; -} - -bool MinecraftServer::isNetherEnabled() -{ - return true; //settings.getBoolean("allow-nether", true); -} - -bool MinecraftServer::isHardcore() -{ - return false; -} - -CommandDispatcher *MinecraftServer::getCommandDispatcher() -{ - return commandDispatcher; +CommandDispatcher* MinecraftServer::getCommandDispatcher() { + return commandDispatcher; } extern int c0a, c0b, c1a, c1b, c1c, c2a, c2b; -void MinecraftServer::run(__int64 seed, void *lpParameter) -{ - NetworkGameInitData *initData = NULL; - std::uint32_t initSettings = 0; - bool findSeed = false; - if(lpParameter != NULL) - { - initData = (NetworkGameInitData *)lpParameter; - initSettings = app.GetGameHostOption(eGameHostOption_All); - findSeed = initData->findSeed; - m_texturePackId = initData->texturePackId; - } -// try { // 4J - removed try/catch/finally - if (initServer(seed, initData, initSettings,findSeed)) - { - ServerLevel *levelNormalDimension = levels[0]; - // 4J-PB - Set the Stronghold position in the leveldata if there isn't one in there - Minecraft *pMinecraft = Minecraft::GetInstance(); - LevelData *pLevelData=levelNormalDimension->getLevelData(); +void MinecraftServer::run(__int64 seed, void* lpParameter) { + NetworkGameInitData* initData = NULL; + std::uint32_t initSettings = 0; + bool findSeed = false; + if (lpParameter != NULL) { + initData = (NetworkGameInitData*)lpParameter; + initSettings = app.GetGameHostOption(eGameHostOption_All); + findSeed = initData->findSeed; + m_texturePackId = initData->texturePackId; + } + // try { // 4J - removed try/catch/finally + if (initServer(seed, initData, initSettings, findSeed)) { + ServerLevel* levelNormalDimension = levels[0]; + // 4J-PB - Set the Stronghold position in the leveldata if there isn't + // one in there + Minecraft* pMinecraft = Minecraft::GetInstance(); + LevelData* pLevelData = levelNormalDimension->getLevelData(); - if(pLevelData && pLevelData->getHasStronghold()==false) - { - int x,z; - if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) - { - pLevelData->setXStronghold(x); - pLevelData->setZStronghold(z); - pLevelData->setHasStronghold(); - } - } + if (pLevelData && pLevelData->getHasStronghold() == false) { + int x, z; + if (app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold, &x, + &z)) { + pLevelData->setXStronghold(x); + pLevelData->setZStronghold(z); + pLevelData->setHasStronghold(); + } + } __int64 lastTime = System::currentTimeMillis(); __int64 unprocessedTime = 0; - while (running && !s_bServerHalted) - { + while (running && !s_bServerHalted) { __int64 now = System::currentTimeMillis(); - // 4J Stu - When we pause the server, we don't want to count that as time passed - // 4J Stu - TU-1 hotifx - Remove this line. We want to make sure that we tick connections at the proper rate when paused - //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - //if(m_isServerPaused) lastTime = now; + // 4J Stu - When we pause the server, we don't want to count that as + // time passed 4J Stu - TU-1 hotifx - Remove this line. We want to + // make sure that we tick connections at the proper rate when paused + // Fix for #13191 - The host of a game can get a message informing + // them that the connection to the server has been lost + // if(m_isServerPaused) lastTime = now; __int64 passedTime = now - lastTime; - if (passedTime > MS_PER_TICK * 40) - { -// logger.warning("Can't keep up! Did the system time change, or is the server overloaded?"); + if (passedTime > MS_PER_TICK * 40) { + // logger.warning("Can't keep up! Did the system + // time change, or is the server overloaded?"); passedTime = MS_PER_TICK * 40; } - if (passedTime < 0) - { -// logger.warning("Time ran backwards! Did the system time change?"); + if (passedTime < 0) { + // logger.warning("Time ran backwards! Did the + // system time change?"); passedTime = 0; } unprocessedTime += passedTime; lastTime = now; - // 4J Added ability to pause the server - if( !m_isServerPaused ) - { - bool didTick = false; - if (levels[0]->allPlayersAreSleeping()) - { - tick(); - unprocessedTime = 0; - } - else - { -// int tickcount = 0; -// __int64 beforeall = System::currentTimeMillis(); - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; -// __int64 before = System::currentTimeMillis(); - tick(); -// __int64 after = System::currentTimeMillis(); -// PIXReportCounter(L"Server time",(float)(after-before)); + // 4J Added ability to pause the server + if (!m_isServerPaused) { + bool didTick = false; + if (levels[0]->allPlayersAreSleeping()) { + tick(); + unprocessedTime = 0; + } else { + // int tickcount = 0; + // __int64 beforeall = + //System::currentTimeMillis(); + while (unprocessedTime > MS_PER_TICK) { + unprocessedTime -= MS_PER_TICK; + // __int64 + //before = System::currentTimeMillis(); + tick(); + // __int64 + //after = System::currentTimeMillis(); + // PIXReportCounter(L"Server + //time",(float)(after-before)); - // 4J Ensure that the slow queue owner keeps cycling if it's not been used in a while - int time = GetTickCount(); - if( ( s_slowQueuePacketSent ) || ( (time - s_slowQueueLastTime) > ( 2 * MINECRAFT_SERVER_SLOW_QUEUE_DELAY ) ) ) - { -// app.DebugPrintf("Considering cycling: (%d) %d - %d -> %d > %d\n",s_slowQueuePacketSent, time, s_slowQueueLastTime, (time - s_slowQueueLastTime), (2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); - MinecraftServer::cycleSlowQueueIndex(); - s_slowQueuePacketSent = false; - s_slowQueueLastTime = time; - } -// else -// { -// app.DebugPrintf("Not considering cycling: %d - %d -> %d > %d\n",time, s_slowQueueLastTime, (time - s_slowQueueLastTime), (2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); -// } - } -// __int64 afterall = System::currentTimeMillis(); -// PIXReportCounter(L"Server time all",(float)(afterall-beforeall)); -// PIXReportCounter(L"Server ticks",(float)tickcount); - } - } - else - { - // 4J Stu - TU1-hotfix - //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - // The connections should tick at the same frequency even when paused - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; - // Keep ticking the connections to stop them timing out - connection->tick(); - } - } - if(MinecraftServer::setTimeAtEndOfTick) - { - MinecraftServer::setTimeAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { -// if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether - { - ServerLevel *level = levels[i]; - level->setTime( MinecraftServer::setTime ); - level->setOverrideTimeOfDay( -1 ); - } - } - } - if(MinecraftServer::setTimeOfDayAtEndOfTick) - { - MinecraftServer::setTimeOfDayAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { - if (i == 0 || settings->getBoolean(L"allow-nether", true)) - { - ServerLevel *level = levels[i]; - //level->setTime( MinecraftServer::setTime ); - level->setOverrideTimeOfDay( MinecraftServer::setTimeOfDay ); - } - } - } + // 4J Ensure that the slow queue owner keeps cycling if + // it's not been used in a while + int time = GetTickCount(); + if ((s_slowQueuePacketSent) || + ((time - s_slowQueueLastTime) > + (2 * MINECRAFT_SERVER_SLOW_QUEUE_DELAY))) { + // app.DebugPrintf("Considering + //cycling: (%d) %d - %d -> %d > + //%d\n",s_slowQueuePacketSent, time, + //s_slowQueueLastTime, (time - s_slowQueueLastTime), + //(2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); + MinecraftServer::cycleSlowQueueIndex(); + s_slowQueuePacketSent = false; + s_slowQueueLastTime = time; + } + // else + // { + // app.DebugPrintf("Not + //considering cycling: %d - %d -> %d > %d\n",time, + //s_slowQueueLastTime, (time - s_slowQueueLastTime), + //(2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); + // } + } + // __int64 afterall = + //System::currentTimeMillis(); PIXReportCounter(L"Server + //time all",(float)(afterall-beforeall)); + // PIXReportCounter(L"Server + //ticks",(float)tickcount); + } + } else { + // 4J Stu - TU1-hotfix + // Fix for #13191 - The host of a game can get a message + // informing them that the connection to the server has been + // lost + // The connections should tick at the same frequency even when + // paused + while (unprocessedTime > MS_PER_TICK) { + unprocessedTime -= MS_PER_TICK; + // Keep ticking the connections to stop them timing out + connection->tick(); + } + } + if (MinecraftServer::setTimeAtEndOfTick) { + MinecraftServer::setTimeAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) { + // if (i == 0 || + //settings->getBoolean(L"allow-nether", true)) + //// 4J removed - we always have nether + { + ServerLevel* level = levels[i]; + level->setTime(MinecraftServer::setTime); + level->setOverrideTimeOfDay(-1); + } + } + } + if (MinecraftServer::setTimeOfDayAtEndOfTick) { + MinecraftServer::setTimeOfDayAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) { + if (i == 0 || settings->getBoolean(L"allow-nether", true)) { + ServerLevel* level = levels[i]; + // level->setTime( MinecraftServer::setTime ); + level->setOverrideTimeOfDay( + MinecraftServer::setTimeOfDay); + } + } + } - // Process delayed actions - eXuiServerAction eAction; - void *param; - for(int i=0;isaveAll(NULL); - } + if (players != NULL) { + players->saveAll(NULL); + } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - PIXBeginNamedEvent(0, "Saving level %d",levels.length - 1 - j); - level->save(false, NULL, true); - PIXEndNamedEvent(); - } - if( !s_bServerHalted ) - { - PIXBeginNamedEvent(0,"Saving game rules"); - saveGameRules(); - PIXEndNamedEvent(); + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we + // don't overwrite the level.dat with the data from + // the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a + // bed will place player at nighttime when + // restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + PIXBeginNamedEvent(0, "Saving level %d", + levels.length - 1 - j); + level->save(false, NULL, true); + PIXEndNamedEvent(); + } + if (!s_bServerHalted) { + PIXBeginNamedEvent(0, "Saving game rules"); + saveGameRules(); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Save to disc"); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, true); - PIXEndNamedEvent(); - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Save to disc"); + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, + true); + PIXEndNamedEvent(); + } + PIXEndNamedEvent(); - QueryPerformanceCounter( &qwNewTime ); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Autosave: Elapsed time %f\n", fElapsedTime); - } - break; + QueryPerformanceCounter(&qwNewTime); + qwDeltaTime.QuadPart = + qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = + fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + app.DebugPrintf("Autosave: Elapsed time %f\n", + fElapsedTime); + } break; #endif - case eXuiServerAction_SaveGame: - app.EnterSaveNotificationSection(); - if (players != NULL) - { - players->saveAll(Minecraft::GetInstance()->progressRenderer); - } - - players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(20) ) ); + case eXuiServerAction_SaveGame: + app.EnterSaveNotificationSection(); + if (players != NULL) { + players->saveAll( + Minecraft::GetInstance()->progressRenderer); + } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - level->save(true, Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - - players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(33 + (j*33) ) ) ); - } - if( !s_bServerHalted ) - { - saveGameRules(); + players->broadcastAll( + std::shared_ptr( + new UpdateProgressPacket(20))); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - } - app.LeaveSaveNotificationSection(); - break; - case eXuiServerAction_DropItem: - // Find the player, and drop the id at their feet - { - std::shared_ptr player = players->players.at(0); - size_t id = (size_t) param; - player->drop( std::shared_ptr( new ItemInstance(id, 1, 0 ) ) ); - } - break; - case eXuiServerAction_SpawnMob: - { - std::shared_ptr player = players->players.at(0); - eINSTANCEOF factory = (eINSTANCEOF)((size_t)param); - std::shared_ptr mob = std::dynamic_pointer_cast(EntityIO::newByEnumType(factory,player->level )); - mob->moveTo(player->x+1, player->y, player->z+1, player->level->random->nextFloat() * 360, 0); - mob->setDespawnProtected(); // 4J added, default to being protected against despawning (has to be done after initial position is set) - player->level->addEntity(mob); - } - break; - case eXuiServerAction_PauseServer: - m_isServerPaused = ( (size_t) param == TRUE ); - if( m_isServerPaused ) - { - m_serverPausedEvent->Set(); - } - break; - case eXuiServerAction_ToggleRain: - { - bool isRaining = levels[0]->getLevelData()->isRaining(); - levels[0]->getLevelData()->setRaining(!isRaining); - levels[0]->getLevelData()->setRainTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); - } - break; - case eXuiServerAction_ToggleThunder: - { - bool isThundering = levels[0]->getLevelData()->isThundering(); - levels[0]->getLevelData()->setThundering(!isThundering); - levels[0]->getLevelData()->setThunderTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); - } - break; - case eXuiServerAction_ServerSettingChanged_Gamertags: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_OPTIONS, app.GetGameHostOption(eGameHostOption_Gamertags)) ) ); - break; - case eXuiServerAction_ServerSettingChanged_BedrockFog: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, app.GetGameHostOption(eGameHostOption_All)) ) ); - break; + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we + // don't overwrite the level.dat with the data from + // the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a + // bed will place player at nighttime when + // restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + level->save( + true, + Minecraft::GetInstance()->progressRenderer, + (eAction == eXuiServerAction_AutoSaveGame)); - case eXuiServerAction_ServerSettingChanged_Difficulty: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_DIFFICULTY, Minecraft::GetInstance()->options->difficulty) ) ); - break; - case eXuiServerAction_ExportSchematic: + players->broadcastAll( + std::shared_ptr( + new UpdateProgressPacket(33 + (j * 33)))); + } + if (!s_bServerHalted) { + saveGameRules(); + + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, + (eAction == eXuiServerAction_AutoSaveGame)); + } + app.LeaveSaveNotificationSection(); + break; + case eXuiServerAction_DropItem: + // Find the player, and drop the id at their feet + { + std::shared_ptr player = + players->players.at(0); + size_t id = (size_t)param; + player->drop(std::shared_ptr( + new ItemInstance(id, 1, 0))); + } + break; + case eXuiServerAction_SpawnMob: { + std::shared_ptr player = + players->players.at(0); + eINSTANCEOF factory = (eINSTANCEOF)((size_t)param); + std::shared_ptr mob = + std::dynamic_pointer_cast( + EntityIO::newByEnumType(factory, + player->level)); + mob->moveTo(player->x + 1, player->y, player->z + 1, + player->level->random->nextFloat() * 360, + 0); + mob->setDespawnProtected(); // 4J added, default to + // being protected against + // despawning (has to be + // done after initial + // position is set) + player->level->addEntity(mob); + } break; + case eXuiServerAction_PauseServer: + m_isServerPaused = ((size_t)param == TRUE); + if (m_isServerPaused) { + m_serverPausedEvent->Set(); + } + break; + case eXuiServerAction_ToggleRain: { + bool isRaining = levels[0]->getLevelData()->isRaining(); + levels[0]->getLevelData()->setRaining(!isRaining); + levels[0]->getLevelData()->setRainTime( + levels[0]->random->nextInt(Level::TICKS_PER_DAY * + 7) + + Level::TICKS_PER_DAY / 2); + } break; + case eXuiServerAction_ToggleThunder: { + bool isThundering = + levels[0]->getLevelData()->isThundering(); + levels[0]->getLevelData()->setThundering(!isThundering); + levels[0]->getLevelData()->setThunderTime( + levels[0]->random->nextInt(Level::TICKS_PER_DAY * + 7) + + Level::TICKS_PER_DAY / 2); + } break; + case eXuiServerAction_ServerSettingChanged_Gamertags: + players->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_OPTIONS, + app.GetGameHostOption( + eGameHostOption_Gamertags)))); + break; + case eXuiServerAction_ServerSettingChanged_BedrockFog: + players->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket:: + HOST_IN_GAME_SETTINGS, + app.GetGameHostOption( + eGameHostOption_All)))); + break; + + case eXuiServerAction_ServerSettingChanged_Difficulty: + players->broadcastAll(std::shared_ptr< + ServerSettingsChangedPacket>( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_DIFFICULTY, + Minecraft::GetInstance() + ->options->difficulty))); + break; + case eXuiServerAction_ExportSchematic: #ifndef _CONTENT_PACKAGE - app.EnterSaveNotificationSection(); - - //players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(20) ) ); + app.EnterSaveNotificationSection(); - if( !s_bServerHalted ) - { - ConsoleSchematicFile::XboxSchematicInitParam *initData = (ConsoleSchematicFile::XboxSchematicInitParam *)param; + // players->broadcastAll( + // std::shared_ptr( new + // UpdateProgressPacket(20) ) ); + + if (!s_bServerHalted) { + ConsoleSchematicFile::XboxSchematicInitParam* + initData = (ConsoleSchematicFile:: + XboxSchematicInitParam*)param; #ifdef _XBOX - File targetFileDir(File::pathRoot + File::pathSeparator + L"Schematics"); + File targetFileDir(File::pathRoot + + File::pathSeparator + + L"Schematics"); #else - File targetFileDir(L"Schematics"); + File targetFileDir(L"Schematics"); #endif - if(!targetFileDir.exists()) targetFileDir.mkdir(); + if (!targetFileDir.exists()) targetFileDir.mkdir(); - wchar_t filename[128]; - swprintf(filename,128,L"%ls%dx%dx%d.sch",initData->name,(initData->endX - initData->startX + 1), (initData->endY - initData->startY + 1), (initData->endZ - initData->startZ + 1)); + wchar_t filename[128]; + swprintf(filename, 128, L"%ls%dx%dx%d.sch", + initData->name, + (initData->endX - initData->startX + 1), + (initData->endY - initData->startY + 1), + (initData->endZ - initData->startZ + 1)); - File dataFile = File( targetFileDir, std::wstring(filename) ); - if(dataFile.exists()) dataFile._delete(); - FileOutputStream fos = FileOutputStream(dataFile); - DataOutputStream dos = DataOutputStream(&fos); - ConsoleSchematicFile::generateSchematicFile(&dos, levels[0], initData->startX, initData->startY, initData->startZ, initData->endX, initData->endY, initData->endZ, initData->bSaveMobs, initData->compressionType); - dos.close(); + File dataFile = + File(targetFileDir, std::wstring(filename)); + if (dataFile.exists()) dataFile._delete(); + FileOutputStream fos = FileOutputStream(dataFile); + DataOutputStream dos = DataOutputStream(&fos); + ConsoleSchematicFile::generateSchematicFile( + &dos, levels[0], initData->startX, + initData->startY, initData->startZ, + initData->endX, initData->endY, initData->endZ, + initData->bSaveMobs, initData->compressionType); + dos.close(); - delete initData; - } - app.LeaveSaveNotificationSection(); + delete initData; + } + app.LeaveSaveNotificationSection(); #endif - break; - case eXuiServerAction_SetCameraLocation: + break; + case eXuiServerAction_SetCameraLocation: #ifndef _CONTENT_PACKAGE - { - DebugSetCameraPosition *pos = (DebugSetCameraPosition *)param; + { + DebugSetCameraPosition* pos = + (DebugSetCameraPosition*)param; - app.DebugPrintf( "DEBUG: Player=%i\n", pos->player ); - app.DebugPrintf( "DEBUG: Teleporting to pos=(%f.2, %f.2, %f.2), looking at=(%f.2,%f.2)\n", - pos->m_camX, pos->m_camY, pos->m_camZ, - pos->m_yRot, pos->m_elev - ); + app.DebugPrintf("DEBUG: Player=%i\n", pos->player); + app.DebugPrintf( + "DEBUG: Teleporting to pos=(%f.2, %f.2, %f.2), " + "looking at=(%f.2,%f.2)\n", + pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, + pos->m_elev); - std::shared_ptr player = players->players.at(pos->player); - player->debug_setPosition( pos->m_camX, pos->m_camY, pos->m_camZ, - pos->m_yRot, pos->m_elev ); + std::shared_ptr player = + players->players.at(pos->player); + player->debug_setPosition(pos->m_camX, pos->m_camY, + pos->m_camZ, pos->m_yRot, + pos->m_elev); - // Doesn't work - //player->setYHeadRot(pos->m_yRot); - //player->absMoveTo(pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, pos->m_elev); - } + // Doesn't work + // player->setYHeadRot(pos->m_yRot); + // player->absMoveTo(pos->m_camX, pos->m_camY, + // pos->m_camZ, pos->m_yRot, pos->m_elev); + } #endif - break; - default: - break; - } - - app.SetXuiServerAction(i,eXuiServerAction_Idle); - } + break; + default: + break; + } - Sleep(1); + app.SetXuiServerAction(i, eXuiServerAction_Idle); + } + + Sleep(1); } } - //else - //{ - // while (running) - // { + // else + //{ + // while (running) + // { // handleConsoleInputs(); - // Sleep(10); + // Sleep(10); // } //} #if 0 @@ -1424,279 +1505,284 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) } #endif - // 4J Stu - Stop the server when the loops complete, as the finally would do - stopServer(); - stopped = true; + // 4J Stu - Stop the server when the loops complete, as the finally would do + stopServer(); + stopped = true; } -void MinecraftServer::broadcastStartSavingPacket() -{ - players->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::START_SAVING, 0) ) );; +void MinecraftServer::broadcastStartSavingPacket() { + players->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_SAVING, 0))); + ; } -void MinecraftServer::broadcastStopSavingPacket() -{ - if( !s_bServerHalted ) - { - players->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_SAVING, 0) ) );; - } +void MinecraftServer::broadcastStopSavingPacket() { + if (!s_bServerHalted) { + players->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_SAVING, 0))); + ; + } } -void MinecraftServer::tick() -{ +void MinecraftServer::tick() { std::vector toRemove; - for (AUTO_VAR(it, ironTimers.begin()); it != ironTimers.end(); it++ ) - { + for (AUTO_VAR(it, ironTimers.begin()); it != ironTimers.end(); it++) { int t = it->second; - if (t > 0) - { + if (t > 0) { ironTimers[it->first] = t - 1; - } - else - { + } else { toRemove.push_back(it->first); } } - for (unsigned int i = 0; i < toRemove.size(); i++) - { + for (unsigned int i = 0; i < toRemove.size(); i++) { ironTimers.erase(toRemove[i]); } AABB::resetPool(); Vec3::resetPool(); - + tickCount++; - // 4J We need to update client difficulty levels based on the servers - Minecraft *pMinecraft = Minecraft::GetInstance(); - // 4J-PB - sending this on the host changing the difficulty in the menus -/* if(m_lastSentDifficulty != pMinecraft->options->difficulty) - { - m_lastSentDifficulty = pMinecraft->options->difficulty; - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_DIFFICULTY, pMinecraft->options->difficulty) ) ); - }*/ + // 4J We need to update client difficulty levels based on the servers + Minecraft* pMinecraft = Minecraft::GetInstance(); + // 4J-PB - sending this on the host changing the difficulty in the menus + /* if(m_lastSentDifficulty != pMinecraft->options->difficulty) + { + m_lastSentDifficulty = pMinecraft->options->difficulty; + players->broadcastAll( + std::shared_ptr( new + ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_DIFFICULTY, + pMinecraft->options->difficulty) ) ); + }*/ - for (unsigned int i = 0; i < levels.length; i++) - { -// if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether - { - ServerLevel *level = levels[i]; + for (unsigned int i = 0; i < levels.length; i++) { + // if (i == 0 || settings->getBoolean(L"allow-nether", true)) + // // 4J removed - we always have nether + { + ServerLevel* level = levels[i]; - // 4J Stu - We set the levels difficulty based on the minecraft options - level->difficulty = app.GetGameHostOption(eGameHostOption_Difficulty); //pMinecraft->options->difficulty; + // 4J Stu - We set the levels difficulty based on the minecraft + // options + level->difficulty = app.GetGameHostOption( + eGameHostOption_Difficulty); // pMinecraft->options->difficulty; #if DEBUG_SERVER_DONT_SPAWN_MOBS - level->setSpawnSettings(false, false); + level->setSpawnSettings(false, false); #else - level->setSpawnSettings(level->difficulty > 0 && !Minecraft::GetInstance()->isTutorial(), animals); + level->setSpawnSettings(level->difficulty > 0 && + !Minecraft::GetInstance()->isTutorial(), + animals); #endif - if (tickCount % 20 == 0) - { - players->broadcastAll( std::shared_ptr( new SetTimePacket(level->getTime() ) ), level->dimension->id); + if (tickCount % 20 == 0) { + players->broadcastAll(std::shared_ptr( + new SetTimePacket(level->getTime())), + level->dimension->id); } -// #ifndef __PS3__ - static __int64 stc = 0; - __int64 st0 = System::currentTimeMillis(); - PIXBeginNamedEvent(0,"Level tick %d",i); - ((Level *)level)->tick(); - __int64 st1 = System::currentTimeMillis(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Update lights %d",i); - // 4J - used to be in a while loop, but we don't want the server locking up for a big chunk of time (could end up trying to process 1,000,000 lights...) - // Instead call this once, which will try and process up to 2000 lights per tick -// printf("lights: %d\n",level->getLightsToUpdate()); - while(level->updateLights() ) - ; - __int64 st2 = System::currentTimeMillis(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Entity tick %d",i); - // 4J added to stop ticking entities in levels when players are not in those levels. - // Note: now changed so that we also tick if there are entities to be removed, as this also happens as a result of calling tickEntities. If we don't do this, then the - // entities get removed at the first point that there is a player count in the level - this has been causing a problem when going from normal dimension -> nether -> normal, - // as the player is getting flagged as to be removed (from the normal dimension) when going to the nether, but Actually gets removed only when it returns - if( ( players->getPlayerCount(level) > 0) || ( level->hasEntitiesToRemove() ) ) - { + // #ifndef __PS3__ + static __int64 stc = 0; + __int64 st0 = System::currentTimeMillis(); + PIXBeginNamedEvent(0, "Level tick %d", i); + ((Level*)level)->tick(); + __int64 st1 = System::currentTimeMillis(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Update lights %d", i); + // 4J - used to be in a while loop, but we don't want the server + // locking up for a big chunk of time (could end up trying to + // process 1,000,000 lights...) Instead call this once, which will + // try and process up to 2000 lights per tick + // printf("lights: + //%d\n",level->getLightsToUpdate()); + while (level->updateLights()); + __int64 st2 = System::currentTimeMillis(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Entity tick %d", i); + // 4J added to stop ticking entities in levels when players are not + // in those levels. Note: now changed so that we also tick if there + // are entities to be removed, as this also happens as a result of + // calling tickEntities. If we don't do this, then the entities get + // removed at the first point that there is a player count in the + // level - this has been causing a problem when going from normal + // dimension -> nether -> normal, as the player is getting flagged + // as to be removed (from the normal dimension) when going to the + // nether, but Actually gets removed only when it returns + if ((players->getPlayerCount(level) > 0) || + (level->hasEntitiesToRemove())) { #ifdef __PSVITA__ - // AP - the PlayerList->viewDistance initially starts out at 3 to make starting a level speedy - // the problem with this is that spawned monsters are always generated on the edge of the known map - // which means they wont process (unless they are surrounded by 2 visible chunks). This means - // they wont checkDespawn so they are NEVER removed which results in monsters not spawning. - // This bit of hack will modify the view distance once the level is up and running. - int newViewDistance = 5; - level->getServer()->getPlayers()->setViewDistance(newViewDistance); - level->getTracker()->updateMaxRange(); - level->getChunkMap()->setRadius(level->getServer()->getPlayers()->getViewDistance()); + // AP - the PlayerList->viewDistance initially starts out at 3 + // to make starting a level speedy the problem with this is that + // spawned monsters are always generated on the edge of the + // known map which means they wont process (unless they are + // surrounded by 2 visible chunks). This means they wont + // checkDespawn so they are NEVER removed which results in + // monsters not spawning. This bit of hack will modify the view + // distance once the level is up and running. + int newViewDistance = 5; + level->getServer()->getPlayers()->setViewDistance( + newViewDistance); + level->getTracker()->updateMaxRange(); + level->getChunkMap()->setRadius( + level->getServer()->getPlayers()->getViewDistance()); #endif - level->tickEntities(); - } - PIXEndNamedEvent(); + level->tickEntities(); + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Entity tracker tick"); - level->getTracker()->tick(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Entity tracker tick"); + level->getTracker()->tick(); + PIXEndNamedEvent(); - __int64 st3 = System::currentTimeMillis(); -// printf(">>>>>>>>>>>>>>>>>>>>>> Tick %d %d %d : %d\n", st1 - st0, st2 - st1, st3 - st2, st0 - stc ); - stc = st0; -// #endif// __PS3__ + __int64 st3 = System::currentTimeMillis(); + // printf(">>>>>>>>>>>>>>>>>>>>>> Tick %d %d %d : + //%d\n", st1 - st0, st2 - st1, st3 - st2, st0 - stc ); + stc = st0; + // #endif// __PS3__ } } - Entity::tickExtraWandering(); // 4J added + Entity::tickExtraWandering(); // 4J added - PIXBeginNamedEvent(0,"Connection tick"); + PIXBeginNamedEvent(0, "Connection tick"); connection->tick(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Players tick"); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Players tick"); players->tick(); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // 4J - removed + // 4J - removed #if 0 for (int i = 0; i < tickables.size(); i++) { tickables.get(i)-tick(); } #endif -// try { // 4J - removed try/catch - handleConsoleInputs(); -// } catch (Exception e) { -// logger.log(Level.WARNING, "Unexpected exception while parsing console command", e); -// } + // try { // 4J - removed try/catch + handleConsoleInputs(); + // } catch (Exception e) { + // logger.log(Level.WARNING, "Unexpected exception while parsing + // console command", e); + // } } -void MinecraftServer::handleConsoleInput(const std::wstring& msg, ConsoleInputSource *source) -{ - consoleInput.push_back(new ConsoleInput(msg, source)); +void MinecraftServer::handleConsoleInput(const std::wstring& msg, + ConsoleInputSource* source) { + consoleInput.push_back(new ConsoleInput(msg, source)); } -void MinecraftServer::handleConsoleInputs() -{ - while (consoleInput.size() > 0) - { - AUTO_VAR(it, consoleInput.begin()); - ConsoleInput *input = *it; - consoleInput.erase(it); -// commands->handleCommand(input); // 4J - removed - TODO - do we want equivalent of console commands? +void MinecraftServer::handleConsoleInputs() { + while (consoleInput.size() > 0) { + AUTO_VAR(it, consoleInput.begin()); + ConsoleInput* input = *it; + consoleInput.erase(it); + // commands->handleCommand(input); // 4J - removed + // - TODO - do we want equivalent of console commands? } } -void MinecraftServer::main(__int64 seed, void *lpParameter) -{ +void MinecraftServer::main(__int64 seed, void* lpParameter) { #if __PS3__ - ShutdownManager::HasStarted(ShutdownManager::eServerThread ); + ShutdownManager::HasStarted(ShutdownManager::eServerThread); #endif - server = new MinecraftServer(); - server->run(seed, lpParameter); - delete server; - server = NULL; - ShutdownManager::HasFinished(ShutdownManager::eServerThread ); + server = new MinecraftServer(); + server->run(seed, lpParameter); + delete server; + server = NULL; + ShutdownManager::HasFinished(ShutdownManager::eServerThread); } -void MinecraftServer::HaltServer(bool bPrimaryPlayerSignedOut) -{ - s_bServerHalted = true; - if( server != NULL ) - { - m_bPrimaryPlayerSignedOut=bPrimaryPlayerSignedOut; - server->halt(); - } +void MinecraftServer::HaltServer(bool bPrimaryPlayerSignedOut) { + s_bServerHalted = true; + if (server != NULL) { + m_bPrimaryPlayerSignedOut = bPrimaryPlayerSignedOut; + server->halt(); + } } -File *MinecraftServer::getFile(const std::wstring& name) -{ - return new File(name); +File* MinecraftServer::getFile(const std::wstring& name) { + return new File(name); } -void MinecraftServer::info(const std::wstring& string) -{ -} +void MinecraftServer::info(const std::wstring& string) {} -void MinecraftServer::warn(const std::wstring& string) -{ -} +void MinecraftServer::warn(const std::wstring& string) {} -std::wstring MinecraftServer::getConsoleName() -{ - return L"CONSOLE"; -} +std::wstring MinecraftServer::getConsoleName() { return L"CONSOLE"; } -ServerLevel *MinecraftServer::getLevel(int dimension) -{ - if (dimension == -1) return levels[1]; - else if (dimension == 1) return levels[2]; - else return levels[0]; +ServerLevel* MinecraftServer::getLevel(int dimension) { + if (dimension == -1) + return levels[1]; + else if (dimension == 1) + return levels[2]; + else + return levels[0]; } // 4J added -void MinecraftServer::setLevel(int dimension, ServerLevel *level) -{ - if (dimension == -1) levels[1] = level; - else if (dimension == 1) levels[2] = level; - else levels[0] = level; +void MinecraftServer::setLevel(int dimension, ServerLevel* level) { + if (dimension == -1) + levels[1] = level; + else if (dimension == 1) + levels[2] = level; + else + levels[0] = level; } // 4J Added -bool MinecraftServer::canSendOnSlowQueue(INetworkPlayer *player) -{ - if( player == NULL ) return false; +bool MinecraftServer::canSendOnSlowQueue(INetworkPlayer* player) { + if (player == NULL) return false; - int time = GetTickCount(); - if( player->GetSessionIndex() == s_slowQueuePlayerIndex && (time - s_slowQueueLastTime) > MINECRAFT_SERVER_SLOW_QUEUE_DELAY ) - { -// app.DebugPrintf("Slow queue OK for player #%d\n", player->GetSessionIndex()); - return true; - } + int time = GetTickCount(); + if (player->GetSessionIndex() == s_slowQueuePlayerIndex && + (time - s_slowQueueLastTime) > MINECRAFT_SERVER_SLOW_QUEUE_DELAY) { + // app.DebugPrintf("Slow queue OK for player #%d\n", + //player->GetSessionIndex()); + return true; + } - return false; + return false; } -void MinecraftServer::cycleSlowQueueIndex() -{ - if( !g_NetworkManager.IsInSession() ) return; +void MinecraftServer::cycleSlowQueueIndex() { + if (!g_NetworkManager.IsInSession()) return; - int startingIndex = s_slowQueuePlayerIndex; - INetworkPlayer *currentPlayer = NULL; - int currentPlayerCount = 0; - do - { - currentPlayerCount = g_NetworkManager.GetPlayerCount(); - if( startingIndex >= currentPlayerCount ) startingIndex = 0; - ++s_slowQueuePlayerIndex; + int startingIndex = s_slowQueuePlayerIndex; + INetworkPlayer* currentPlayer = NULL; + int currentPlayerCount = 0; + do { + currentPlayerCount = g_NetworkManager.GetPlayerCount(); + if (startingIndex >= currentPlayerCount) startingIndex = 0; + ++s_slowQueuePlayerIndex; - if( currentPlayerCount > 0 ) - { - s_slowQueuePlayerIndex %= currentPlayerCount; - // Fix for #9530 - NETWORKING: Attempting to fill a multiplayer game beyond capacity results in a softlock for the last players to join. - // The QNet session might be ending while we do this, so do a few more checks that the player is real - currentPlayer = g_NetworkManager.GetPlayerByIndex( s_slowQueuePlayerIndex ); - } - else - { - s_slowQueuePlayerIndex = 0; - } - } while ( g_NetworkManager.IsInSession() && - currentPlayerCount > 0 && - s_slowQueuePlayerIndex != startingIndex && - currentPlayer != NULL && - currentPlayer->IsLocal() - ); -// app.DebugPrintf("Cycled slow queue index to %d\n", s_slowQueuePlayerIndex); + if (currentPlayerCount > 0) { + s_slowQueuePlayerIndex %= currentPlayerCount; + // Fix for #9530 - NETWORKING: Attempting to fill a multiplayer game + // beyond capacity results in a softlock for the last players to + // join. The QNet session might be ending while we do this, so do a + // few more checks that the player is real + currentPlayer = + g_NetworkManager.GetPlayerByIndex(s_slowQueuePlayerIndex); + } else { + s_slowQueuePlayerIndex = 0; + } + } while (g_NetworkManager.IsInSession() && currentPlayerCount > 0 && + s_slowQueuePlayerIndex != startingIndex && currentPlayer != NULL && + currentPlayer->IsLocal()); + // app.DebugPrintf("Cycled slow queue index to %d\n", + //s_slowQueuePlayerIndex); } -// 4J added - sets up a vector of flags to indicate which entities (with small Ids) have been removed from the level, but are still haven't constructed a network packet -// to tell a remote client about it. These small Ids shouldn't be re-used. Most of the time this method shouldn't actually do anything, in which case it will return false -// and nothing is set up. -bool MinecraftServer::flagEntitiesToBeRemoved(unsigned int *flags) -{ - bool removedFound = false; - for( unsigned int i = 0; i < levels.length; i++ ) - { - ServerLevel *level = levels[i]; - if( level ) - { - level->flagEntitiesToBeRemoved( flags, &removedFound ); - } - } - return removedFound; +// 4J added - sets up a vector of flags to indicate which entities (with small +// Ids) have been removed from the level, but are still haven't constructed a +// network packet to tell a remote client about it. These small Ids shouldn't be +// re-used. Most of the time this method shouldn't actually do anything, in +// which case it will return false and nothing is set up. +bool MinecraftServer::flagEntitiesToBeRemoved(unsigned int* flags) { + bool removedFound = false; + for (unsigned int i = 0; i < levels.length; i++) { + ServerLevel* level = levels[i]; + if (level) { + level->flagEntitiesToBeRemoved(flags, &removedFound); + } + } + return removedFound; } diff --git a/Minecraft.Client/MinecraftServer.h b/Minecraft.Client/MinecraftServer.h index 4e9fd5895..597b3bab7 100644 --- a/Minecraft.Client/MinecraftServer.h +++ b/Minecraft.Client/MinecraftServer.h @@ -22,226 +22,265 @@ class CommandDispatcher; #define MINECRAFT_SERVER_SLOW_QUEUE_DELAY 250 -typedef struct _LoadSaveDataThreadParam -{ - void *data; - __int64 fileSize; - const std::wstring saveName; - _LoadSaveDataThreadParam(void *data, __int64 filesize, const std::wstring &saveName) : data( data ), fileSize( filesize ), saveName( saveName ) {} +typedef struct _LoadSaveDataThreadParam { + void* data; + __int64 fileSize; + const std::wstring saveName; + _LoadSaveDataThreadParam(void* data, __int64 filesize, + const std::wstring& saveName) + : data(data), fileSize(filesize), saveName(saveName) {} } LoadSaveDataThreadParam; -typedef struct _NetworkGameInitData -{ - __int64 seed; - LoadSaveDataThreadParam *saveData; - std::uint32_t settings; - LevelGenerationOptions *levelGen; - std::uint32_t texturePackId; - bool findSeed; - unsigned int xzSize; - unsigned char hellScale; - ESavePlatform savePlatform; +typedef struct _NetworkGameInitData { + __int64 seed; + LoadSaveDataThreadParam* saveData; + std::uint32_t settings; + LevelGenerationOptions* levelGen; + std::uint32_t texturePackId; + bool findSeed; + unsigned int xzSize; + unsigned char hellScale; + ESavePlatform savePlatform; - _NetworkGameInitData() - { - seed = 0; - saveData = NULL; - settings = 0; - levelGen = NULL; - texturePackId = 0; - findSeed = false; - xzSize = LEVEL_LEGACY_WIDTH; - hellScale = HELL_LEVEL_LEGACY_SCALE; - savePlatform = SAVE_FILE_PLATFORM_LOCAL; - } + _NetworkGameInitData() { + seed = 0; + saveData = NULL; + settings = 0; + levelGen = NULL; + texturePackId = 0; + findSeed = false; + xzSize = LEVEL_LEGACY_WIDTH; + hellScale = HELL_LEVEL_LEGACY_SCALE; + savePlatform = SAVE_FILE_PLATFORM_LOCAL; + } } NetworkGameInitData; - - -// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but I don't think we will use any of the functions that defines so not implementing here -class MinecraftServer : public ConsoleInputSource -{ +// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but +// I don't think we will use any of the functions that defines so not +// implementing here +class MinecraftServer : public ConsoleInputSource { public: - static const std::wstring VERSION; - static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5; + static const std::wstring VERSION; + static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5; -// static Logger logger = Logger.getLogger("Minecraft"); + // static Logger logger = Logger.getLogger("Minecraft"); static std::unordered_map ironTimers; private: - static const int DEFAULT_MINECRAFT_PORT = 25565; - static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND; + static const int DEFAULT_MINECRAFT_PORT = 25565; + static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND; - // 4J Stu - Added 1.0.1, Not needed - //std::wstring localIp; - //int port; + // 4J Stu - Added 1.0.1, Not needed + // std::wstring localIp; + // int port; public: - ServerConnection *connection; - Settings *settings; + ServerConnection* connection; + Settings* settings; ServerLevelArray levels; private: - PlayerList *players; + PlayerList* players; - // 4J Stu - Added 1.0.1, Not needed - //long[] tickTimes = new long[TICK_STATS_SPAN]; - //long[][] levelTickTimes; + // 4J Stu - Added 1.0.1, Not needed + // long[] tickTimes = new long[TICK_STATS_SPAN]; + // long[][] levelTickTimes; private: - ConsoleCommands *commands; + ConsoleCommands* commands; bool running; - bool m_bLoaded; + bool m_bLoaded; + public: - bool stopped; + bool stopped; int tickCount; public: - std::wstring progressStatus; + std::wstring progressStatus; int progress; + private: -// std::vector tickables = new ArrayList(); // 4J - removed - CommandDispatcher *commandDispatcher; - std::vector consoleInput; // 4J - was synchronizedList - TODO - investigate + // std::vector tickables = new ArrayList(); // 4J - + //removed + CommandDispatcher* commandDispatcher; + std::vector + consoleInput; // 4J - was synchronizedList - TODO - investigate public: bool onlineMode; bool animals; - bool npcs; + bool npcs; bool pvp; bool allowFlight; - std::wstring motd; - int maxBuildHeight; + std::wstring motd; + int maxBuildHeight; private: - // 4J Added - //int m_lastSentDifficulty; + // 4J Added + // int m_lastSentDifficulty; public: - // 4J Stu - This value should be incremented every time the list of players with friends-only UGC settings changes - // It is sent with PreLoginPacket and compared when it comes back in the LoginPacket - std::uint32_t m_ugcPlayersVersion; + // 4J Stu - This value should be incremented every time the list of players + // with friends-only UGC settings changes It is sent with PreLoginPacket and + // compared when it comes back in the LoginPacket + std::uint32_t m_ugcPlayersVersion; - // This value is used to store the texture pack id for the currently loaded world - std::uint32_t m_texturePackId; + // This value is used to store the texture pack id for the currently loaded + // world + std::uint32_t m_texturePackId; public: - MinecraftServer(); - ~MinecraftServer(); + MinecraftServer(); + ~MinecraftServer(); + private: - // 4J Added - LoadSaveDataThreadParam - bool initServer(__int64 seed, NetworkGameInitData *initData, std::uint32_t initSettings, bool findSeed); - void postProcessTerminate(ProgressRenderer *mcprogress); - bool loadLevel(LevelStorageSource *storageSource, const std::wstring& name, __int64 levelSeed, LevelType *pLevelType, NetworkGameInitData *initData); + // 4J Added - LoadSaveDataThreadParam + bool initServer(__int64 seed, NetworkGameInitData* initData, + std::uint32_t initSettings, bool findSeed); + void postProcessTerminate(ProgressRenderer* mcprogress); + bool loadLevel(LevelStorageSource* storageSource, const std::wstring& name, + __int64 levelSeed, LevelType* pLevelType, + NetworkGameInitData* initData); void setProgress(const std::wstring& status, int progress); void endProgress(); void saveAllChunks(); - void saveGameRules(); + void saveGameRules(); void stopServer(); public: - void setMaxBuildHeight(int maxBuildHeight); - int getMaxBuildHeight(); - PlayerList *getPlayers(); - void setPlayers(PlayerList *players); - ServerConnection *getConnection(); - bool isAnimals(); - void setAnimals(bool animals); - bool isNpcsEnabled(); - void setNpcsEnabled(bool npcs); - bool isPvpAllowed(); - void setPvpAllowed(bool pvp); - bool isFlightAllowed(); - void setFlightAllowed(bool allowFlight); - bool isNetherEnabled(); - bool isHardcore(); - CommandDispatcher *getCommandDispatcher(); + void setMaxBuildHeight(int maxBuildHeight); + int getMaxBuildHeight(); + PlayerList* getPlayers(); + void setPlayers(PlayerList* players); + ServerConnection* getConnection(); + bool isAnimals(); + void setAnimals(bool animals); + bool isNpcsEnabled(); + void setNpcsEnabled(bool npcs); + bool isPvpAllowed(); + void setPvpAllowed(bool pvp); + bool isFlightAllowed(); + void setFlightAllowed(bool allowFlight); + bool isNetherEnabled(); + bool isHardcore(); + CommandDispatcher* getCommandDispatcher(); public: - void halt(); - void run(__int64 seed, void *lpParameter); + void halt(); + void run(__int64 seed, void* lpParameter); - void broadcastStartSavingPacket(); - void broadcastStopSavingPacket(); + void broadcastStartSavingPacket(); + void broadcastStopSavingPacket(); private: - void tick(); -public: - void handleConsoleInput(const std::wstring& msg, ConsoleInputSource *source); - void handleConsoleInputs(); -// void addTickable(Tickable tickable); // 4J removed - static void main(__int64 seed, void *lpParameter); - static void HaltServer(bool bPrimaryPlayerSignedOut=false); + void tick(); - File *getFile(const std::wstring& name); +public: + void handleConsoleInput(const std::wstring& msg, + ConsoleInputSource* source); + void handleConsoleInputs(); + // void addTickable(Tickable tickable); // 4J removed + static void main(__int64 seed, void* lpParameter); + static void HaltServer(bool bPrimaryPlayerSignedOut = false); + + File* getFile(const std::wstring& name); void info(const std::wstring& string); void warn(const std::wstring& string); std::wstring getConsoleName(); - ServerLevel *getLevel(int dimension); - void setLevel(int dimension, ServerLevel *level); // 4J added - static MinecraftServer *getInstance() { return server; } // 4J added - static bool serverHalted() { return s_bServerHalted; } - static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; } - static void resetFlags() { s_bServerHalted = false; s_bSaveOnExitAnswered = false; } + ServerLevel* getLevel(int dimension); + void setLevel(int dimension, ServerLevel* level); // 4J added + static MinecraftServer* getInstance() { return server; } // 4J added + static bool serverHalted() { return s_bServerHalted; } + static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; } + static void resetFlags() { + s_bServerHalted = false; + s_bSaveOnExitAnswered = false; + } - bool flagEntitiesToBeRemoved(unsigned int *flags); // 4J added + bool flagEntitiesToBeRemoved(unsigned int* flags); // 4J added private: - //4J Added - static MinecraftServer *server; + // 4J Added + static MinecraftServer* server; - static bool setTimeOfDayAtEndOfTick; - static __int64 setTimeOfDay; - static bool setTimeAtEndOfTick; - static __int64 setTime; + static bool setTimeOfDayAtEndOfTick; + static __int64 setTimeOfDay; + static bool setTimeAtEndOfTick; + static __int64 setTime; - static bool m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to save the game - another player may have signed in in their place, so ProfileManager.IsSignedIn isn't enough - static bool s_bServerHalted; // 4J Stu Added so that we can halt the server even before it's been created properly - static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this question once when we exit + static bool + m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to + // save the game - another player may have + // signed in in their place, so + // ProfileManager.IsSignedIn isn't enough + static bool s_bServerHalted; // 4J Stu Added so that we can halt the server + // even before it's been created properly + static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this + // question once when we exit - // 4J - added so that we can have a separate thread for post processing chunks on level creation - static int runPostUpdate(void* lpParam); - C4JThread* m_postUpdateThread; - bool m_postUpdateTerminate; - class postProcessRequest - { - public: - int x, z; - ChunkSource *chunkSource; - postProcessRequest(int x, int z, ChunkSource *chunkSource) : x(x), z(z), chunkSource(chunkSource) {} - }; - std::vector m_postProcessRequests; - CRITICAL_SECTION m_postProcessCS; -public: - void addPostProcessRequest(ChunkSource *chunkSource, int x, int z); + // 4J - added so that we can have a separate thread for post processing + // chunks on level creation + static int runPostUpdate(void* lpParam); + C4JThread* m_postUpdateThread; + bool m_postUpdateTerminate; + class postProcessRequest { + public: + int x, z; + ChunkSource* chunkSource; + postProcessRequest(int x, int z, ChunkSource* chunkSource) + : x(x), z(z), chunkSource(chunkSource) {} + }; + std::vector m_postProcessRequests; + CRITICAL_SECTION m_postProcessCS; public: - static PlayerList *getPlayerList() { if( server != NULL ) return server->players; else return NULL; } - static void SetTimeOfDay(__int64 time) { setTimeOfDayAtEndOfTick = true; setTimeOfDay = time; } - static void SetTime(__int64 time) { setTimeAtEndOfTick = true; setTime = time; } - - C4JThread::Event* m_serverPausedEvent; -private: - // 4J Added - bool m_isServerPaused; + void addPostProcessRequest(ChunkSource* chunkSource, int x, int z); - // 4J Added - A static that stores the QNet index of the player that is next allowed to send a packet in the slow queue - static int s_slowQueuePlayerIndex; - static int s_slowQueueLastTime; public: - static bool s_slowQueuePacketSent; + static PlayerList* getPlayerList() { + if (server != NULL) + return server->players; + else + return NULL; + } + static void SetTimeOfDay(__int64 time) { + setTimeOfDayAtEndOfTick = true; + setTimeOfDay = time; + } + static void SetTime(__int64 time) { + setTimeAtEndOfTick = true; + setTime = time; + } - bool IsServerPaused() { return m_isServerPaused; } + C4JThread::Event* m_serverPausedEvent; private: - // 4J Added - bool m_saveOnExit; - bool m_suspending; + // 4J Added + bool m_isServerPaused; + + // 4J Added - A static that stores the QNet index of the player that is next + // allowed to send a packet in the slow queue + static int s_slowQueuePlayerIndex; + static int s_slowQueueLastTime; public: - //static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; } - static bool canSendOnSlowQueue(INetworkPlayer *player); - static void cycleSlowQueueIndex(); + static bool s_slowQueuePacketSent; - void setSaveOnExit(bool save) { m_saveOnExit = save; s_bSaveOnExitAnswered = true; } - void Suspend(); - bool IsSuspending(); + bool IsServerPaused() { return m_isServerPaused; } - // 4J Stu - A load of functions were all added in 1.0.1 in the ServerInterface, but I don't think we need any of them +private: + // 4J Added + bool m_saveOnExit; + bool m_suspending; + +public: + // static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; } + static bool canSendOnSlowQueue(INetworkPlayer* player); + static void cycleSlowQueueIndex(); + + void setSaveOnExit(bool save) { + m_saveOnExit = save; + s_bSaveOnExitAnswered = true; + } + void Suspend(); + bool IsSuspending(); + + // 4J Stu - A load of functions were all added in 1.0.1 in the + // ServerInterface, but I don't think we need any of them }; diff --git a/Minecraft.Client/Network/ClientConnection.cpp b/Minecraft.Client/Network/ClientConnection.cpp index d062fed55..deaad03f9 100644 --- a/Minecraft.Client/Network/ClientConnection.cpp +++ b/Minecraft.Client/Network/ClientConnection.cpp @@ -57,10 +57,10 @@ #include "../../Minecraft.World/Stats/GenericStats.h" #endif -ClientConnection::ClientConnection(Minecraft *minecraft, const std::wstring& ip, int port) -{ - // 4J Stu - No longer used as we use the socket version below. - assert(FALSE); +ClientConnection::ClientConnection(Minecraft* minecraft, const std::wstring& ip, + int port) { + // 4J Stu - No longer used as we use the socket version below. + assert(FALSE); #if 0 // 4J - added initiliasers random = new Random(); @@ -92,600 +92,630 @@ ClientConnection::ClientConnection(Minecraft *minecraft, const std::wstring& ip, #endif } -ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex /*= -1*/) -{ - // 4J - added initiliasers - random = new Random(); - done = false; +ClientConnection::ClientConnection(Minecraft* minecraft, Socket* socket, + int iUserIndex /*= -1*/) { + // 4J - added initiliasers + random = new Random(); + done = false; level = NULL; started = false; - savedDataStorage = new SavedDataStorage(NULL); - maxPlayers = 20; + savedDataStorage = new SavedDataStorage(NULL); + maxPlayers = 20; this->minecraft = minecraft; - if( iUserIndex < 0 ) - { - m_userIndex = ProfileManager.GetPrimaryPad(); - } - else - { - m_userIndex = iUserIndex; - } + if (iUserIndex < 0) { + m_userIndex = ProfileManager.GetPrimaryPad(); + } else { + m_userIndex = iUserIndex; + } - if( socket == NULL ) - { - socket = new Socket(); // 4J - Local connection - } + if (socket == NULL) { + socket = new Socket(); // 4J - Local connection + } - createdOk = socket->createdOk; - if( createdOk ) - { - connection = new Connection(socket, L"Client", this); - } - else - { - connection = NULL; - // TODO 4J Stu - This will cause issues since the session player owns the socket - //delete socket; - } + createdOk = socket->createdOk; + if (createdOk) { + connection = new Connection(socket, L"Client", this); + } else { + connection = NULL; + // TODO 4J Stu - This will cause issues since the session player owns + // the socket + // delete socket; + } } -ClientConnection::~ClientConnection() -{ - delete connection; - delete random; - delete savedDataStorage; +ClientConnection::~ClientConnection() { + delete connection; + delete random; + delete savedDataStorage; } -void ClientConnection::tick() -{ +void ClientConnection::tick() { if (!done) connection->tick(); connection->flush(); } -INetworkPlayer *ClientConnection::getNetworkPlayer() -{ - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; +INetworkPlayer* ClientConnection::getNetworkPlayer() { + if (connection != NULL && connection->getSocket() != NULL) + return connection->getSocket()->getPlayer(); + else + return NULL; } -void ClientConnection::handleLogin(std::shared_ptr packet) -{ +void ClientConnection::handleLogin(std::shared_ptr packet) { if (done) return; - PlayerUID OnlineXuid; - ProfileManager.GetXUID(m_userIndex,&OnlineXuid,true); // online xuid - MOJANG_DATA *pMojangData = NULL; - - if(!g_NetworkManager.IsLocalGame()) - { - pMojangData=app.GetMojangDataForXuid(OnlineXuid); - } + PlayerUID OnlineXuid; + ProfileManager.GetXUID(m_userIndex, &OnlineXuid, true); // online xuid + MOJANG_DATA* pMojangData = NULL; - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCLoginReceived * 100)/ (eCCConnected)); - } + if (!g_NetworkManager.IsLocalGame()) { + pMojangData = app.GetMojangDataForXuid(OnlineXuid); + } - // 4J-PB - load the local player skin (from the global title user storage area) if there is one - // the primary player on the host machine won't have a qnet player from the socket - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - int iUserID=-1; + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCLoginReceived * 100) / (eCCConnected)); + } - if( m_userIndex == ProfileManager.GetPrimaryPad() ) - { - iUserID=m_userIndex; + // 4J-PB - load the local player skin (from the global title user storage + // area) if there is one the primary player on the host machine won't have a + // qnet player from the socket + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + int iUserID = -1; - TelemetryManager->SetMultiplayerInstanceId(packet->m_multiplayerInstanceId); - } - else - { - if(!networkPlayer->IsGuest() && networkPlayer->IsLocal()) - { - // find the pad number of this local player - for(int i=0;iSetMultiplayerInstanceId( + packet->m_multiplayerInstanceId); + } else { + if (!networkPlayer->IsGuest() && networkPlayer->IsLocal()) { + // find the pad number of this local player + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + INetworkPlayer* networkLocalPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(i); + if (networkLocalPlayer == networkPlayer) { + iUserID = i; + } + } + } + } - // if there's a special skin or cloak for this player, add it in - if(pMojangData) - { - // a skin? - if(pMojangData->wchSkin[0]!=0L) - { - std::wstring wstr=pMojangData->wchSkin; - // check the file is not already in - bRes=app.IsFileInMemoryTextures(wstr); - if(!bRes) - { + if (iUserID != -1) { + std::uint8_t* pBuffer = NULL; + unsigned int dwSize = 0; + bool bRes; + + // if there's a special skin or cloak for this player, add it in + if (pMojangData) { + // a skin? + if (pMojangData->wchSkin[0] != 0L) { + std::wstring wstr = pMojangData->wchSkin; + // check the file is not already in + bRes = app.IsFileInMemoryTextures(wstr); + if (!bRes) { #ifdef _XBOX - C4JStorage::ETMSStatus eTMSStatus; - eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchSkin,&pBuffer, &dwSize); + C4JStorage::ETMSStatus eTMSStatus; + eTMSStatus = StorageManager.ReadTMSFile( + iUserID, C4JStorage::eGlobalStorage_Title, + C4JStorage::eTMS_FileType_Graphic, pMojangData->wchSkin, + &pBuffer, &dwSize); - bRes=(eTMSStatus==C4JStorage::ETMSStatus_Idle); + bRes = (eTMSStatus == C4JStorage::ETMSStatus_Idle); #endif - } + } - if(bRes) - { - app.AddMemoryTextureFile(wstr,pBuffer,dwSize); - } - } + if (bRes) { + app.AddMemoryTextureFile(wstr, pBuffer, dwSize); + } + } - // a cloak? - if(pMojangData->wchCape[0]!=0L) - { - std::wstring wstr=pMojangData->wchCape; - // check the file is not already in - bRes=app.IsFileInMemoryTextures(wstr); - if(!bRes) - { + // a cloak? + if (pMojangData->wchCape[0] != 0L) { + std::wstring wstr = pMojangData->wchCape; + // check the file is not already in + bRes = app.IsFileInMemoryTextures(wstr); + if (!bRes) { #ifdef _XBOX - C4JStorage::ETMSStatus eTMSStatus; - eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchCape,&pBuffer, &dwSize); - bRes=(eTMSStatus==C4JStorage::ETMSStatus_Idle); + C4JStorage::ETMSStatus eTMSStatus; + eTMSStatus = StorageManager.ReadTMSFile( + iUserID, C4JStorage::eGlobalStorage_Title, + C4JStorage::eTMS_FileType_Graphic, pMojangData->wchCape, + &pBuffer, &dwSize); + bRes = (eTMSStatus == C4JStorage::ETMSStatus_Idle); #endif - } + } - if(bRes) - { - app.AddMemoryTextureFile(wstr,pBuffer,dwSize); - } - } - } + if (bRes) { + app.AddMemoryTextureFile(wstr, pBuffer, dwSize); + } + } + } - // If we're online, read the banned game list - app.ReadBannedList(iUserID); - // mark the level as not checked against banned levels - it'll be checked once the level starts - app.SetBanListCheck(iUserID,false); - } + // If we're online, read the banned game list + app.ReadBannedList(iUserID); + // mark the level as not checked against banned levels - it'll be + // checked once the level starts + app.SetBanListCheck(iUserID, false); + } - if( m_userIndex == ProfileManager.GetPrimaryPad() ) - { - if( app.GetTutorialMode() ) - { - minecraft->gameMode = new FullTutorialMode(ProfileManager.GetPrimaryPad(), minecraft, this); - } - // check if we're in the trial version - else if(ProfileManager.IsFullVersion()==false) - { - minecraft->gameMode = new TrialMode(ProfileManager.GetPrimaryPad(), minecraft, this); - } - else - { - MemSect(13); - minecraft->gameMode = new ConsoleGameMode(ProfileManager.GetPrimaryPad(), minecraft, this); - MemSect(0); - } + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + if (app.GetTutorialMode()) { + minecraft->gameMode = new FullTutorialMode( + ProfileManager.GetPrimaryPad(), minecraft, this); + } + // check if we're in the trial version + else if (ProfileManager.IsFullVersion() == false) { + minecraft->gameMode = + new TrialMode(ProfileManager.GetPrimaryPad(), minecraft, this); + } else { + MemSect(13); + minecraft->gameMode = new ConsoleGameMode( + ProfileManager.GetPrimaryPad(), minecraft, this); + MemSect(0); + } + Level* dimensionLevel = minecraft->getLevel(packet->dimension); + if (dimensionLevel == NULL) { + level = new MultiPlayerLevel( + this, + new LevelSettings( + packet->seed, GameType::byId(packet->gameType), false, + false, packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - Level *dimensionLevel = minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) - { - level = new MultiPlayerLevel(this, new LevelSettings(packet->seed, GameType::byId(packet->gameType), false, false, packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + // 4J Stu - We want to share the SavedDataStorage between levels + int otherDimensionId = packet->dimension == 0 ? -1 : 0; + Level* activeLevel = minecraft->getLevel(otherDimensionId); + if (activeLevel != NULL) { + // Don't need to delete it here as it belongs to a client + // connection while will delete it when it's done + // if( level->savedDataStorage != NULL ) delete + // level->savedDataStorage; + level->savedDataStorage = activeLevel->savedDataStorage; + } - // 4J Stu - We want to share the SavedDataStorage between levels - int otherDimensionId = packet->dimension == 0 ? -1 : 0; - Level *activeLevel = minecraft->getLevel(otherDimensionId); - if( activeLevel != NULL ) - { - // Don't need to delete it here as it belongs to a client connection while will delete it when it's done - //if( level->savedDataStorage != NULL ) delete level->savedDataStorage; - level->savedDataStorage = activeLevel->savedDataStorage; - } + app.DebugPrintf("ClientConnection - DIFFICULTY --- %d\n", + packet->difficulty); + level->difficulty = packet->difficulty; // 4J Added + level->isClientSide = true; + minecraft->setLevel(level); + } - app.DebugPrintf("ClientConnection - DIFFICULTY --- %d\n",packet->difficulty); - level->difficulty = packet->difficulty; // 4J Added - level->isClientSide = true; - minecraft->setLevel(level); - } + minecraft->player->setPlayerIndex(packet->m_playerIndex); + minecraft->player->setCustomSkin(app.GetPlayerSkinId(m_userIndex)); + minecraft->player->setCustomCape(app.GetPlayerCapeId(m_userIndex)); - minecraft->player->setPlayerIndex( packet->m_playerIndex ); - minecraft->player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); - minecraft->player->setCustomCape( app.GetPlayerCapeId(m_userIndex) ); + minecraft->createPrimaryLocalPlayer(ProfileManager.GetPrimaryPad()); + minecraft->player->dimension = packet->dimension; + // minecraft->setScreen(new ReceivingLevelScreen(this)); + minecraft->player->entityId = packet->clientVersion; - minecraft->createPrimaryLocalPlayer(ProfileManager.GetPrimaryPad()); + std::uint8_t networkSmallId = getSocket()->getSmallId(); + app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, + packet->m_uiGamePrivileges); + minecraft->player->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); - minecraft->player->dimension = packet->dimension; - //minecraft->setScreen(new ReceivingLevelScreen(this)); - minecraft->player->entityId = packet->clientVersion; + // Assume all privileges are on, so that the first message we see only + // indicates things that have been turned off + unsigned int startingPrivileges = 0; + Player::enableAllPlayerPrivileges(startingPrivileges, true); - std::uint8_t networkSmallId = getSocket()->getSmallId(); - app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, packet->m_uiGamePrivileges); - minecraft->player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); + if (networkPlayer->IsHost()) { + Player::setPlayerGamePrivilege( + startingPrivileges, Player::ePlayerGamePrivilege_HOST, 1); + } - // Assume all privileges are on, so that the first message we see only indicates things that have been turned off - unsigned int startingPrivileges = 0; - Player::enableAllPlayerPrivileges(startingPrivileges,true); + displayPrivilegeChanges(minecraft->player, startingPrivileges); - if(networkPlayer->IsHost()) - { - Player::setPlayerGamePrivilege(startingPrivileges, Player::ePlayerGamePrivilege_HOST,1); - } + // update the debugoptions + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + app.GetGameSettingsDebugMask(-1, true)); + } else { + // 4J-PB - this isn't the level we want + // level = (MultiPlayerLevel *)minecraft->level; + level = (MultiPlayerLevel*)minecraft->getLevel(packet->dimension); + std::shared_ptr player; - displayPrivilegeChanges(minecraft->player,startingPrivileges); + if (level == NULL) { + int otherDimensionId = packet->dimension == 0 ? -1 : 0; + MultiPlayerLevel* activeLevel = + minecraft->getLevel(otherDimensionId); - // update the debugoptions - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),app.GetGameSettingsDebugMask(-1,true)); - } - else - { - // 4J-PB - this isn't the level we want - //level = (MultiPlayerLevel *)minecraft->level; - level = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); - std::shared_ptr player; + if (activeLevel == NULL) { + otherDimensionId = packet->dimension == 0 + ? 1 + : (packet->dimension == -1 ? 1 : -1); + activeLevel = minecraft->getLevel(otherDimensionId); + } - if(level==NULL) - { - int otherDimensionId = packet->dimension == 0 ? -1 : 0; - MultiPlayerLevel *activeLevel = minecraft->getLevel(otherDimensionId); + MultiPlayerLevel* dimensionLevel = new MultiPlayerLevel( + this, + new LevelSettings( + packet->seed, GameType::byId(packet->gameType), false, + false, packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - if(activeLevel == NULL) - { - otherDimensionId = packet->dimension == 0 ? 1 : (packet->dimension == -1 ? 1 : -1); - activeLevel = minecraft->getLevel(otherDimensionId); - } + dimensionLevel->savedDataStorage = activeLevel->savedDataStorage; - MultiPlayerLevel *dimensionLevel = new MultiPlayerLevel(this, new LevelSettings(packet->seed, GameType::byId(packet->gameType), false, false, packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + dimensionLevel->difficulty = packet->difficulty; // 4J Added + dimensionLevel->isClientSide = true; + level = dimensionLevel; + // 4J Stu - At time of writing ProfileManager.GetGamertag() does not + // always return the correct name, if sign-ins are turned off while + // the player signed in. Using the qnetPlayer instead. need to have + // a level before create extra local player + MultiPlayerLevel* levelpassedin = (MultiPlayerLevel*)level; + player = minecraft->createExtraLocalPlayer( + m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, + packet->dimension, this, levelpassedin); - dimensionLevel->savedDataStorage = activeLevel->savedDataStorage; + // need to have a player before the setlevel + std::shared_ptr lastPlayer = + minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + minecraft->setLevel(level); + minecraft->player = lastPlayer; + } else { + player = minecraft->createExtraLocalPlayer( + m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, + packet->dimension, this); + } - dimensionLevel->difficulty = packet->difficulty; // 4J Added - dimensionLevel->isClientSide = true; - level = dimensionLevel; - // 4J Stu - At time of writing ProfileManager.GetGamertag() does not always return the correct name, - // if sign-ins are turned off while the player signed in. Using the qnetPlayer instead. - // need to have a level before create extra local player - MultiPlayerLevel *levelpassedin=(MultiPlayerLevel *)level; - player = minecraft->createExtraLocalPlayer(m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, packet->dimension, this,levelpassedin); + // level->addClientConnection( this ); + player->dimension = packet->dimension; + player->entityId = packet->clientVersion; - // need to have a player before the setlevel - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - minecraft->setLevel(level); - minecraft->player = lastPlayer; - } - else - { - player = minecraft->createExtraLocalPlayer(m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, packet->dimension, this); - } + player->setPlayerIndex(packet->m_playerIndex); + player->setCustomSkin(app.GetPlayerSkinId(m_userIndex)); + player->setCustomCape(app.GetPlayerCapeId(m_userIndex)); + std::uint8_t networkSmallId = getSocket()->getSmallId(); + app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, + packet->m_uiGamePrivileges); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_uiGamePrivileges); - //level->addClientConnection( this ); - player->dimension = packet->dimension; - player->entityId = packet->clientVersion; + // Assume all privileges are on, so that the first message we see only + // indicates things that have been turned off + unsigned int startingPrivileges = 0; + Player::enableAllPlayerPrivileges(startingPrivileges, true); - player->setPlayerIndex( packet->m_playerIndex ); - player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); - player->setCustomCape( app.GetPlayerCapeId(m_userIndex) ); - + displayPrivilegeChanges(minecraft->localplayers[m_userIndex], + startingPrivileges); + } - std::uint8_t networkSmallId = getSocket()->getSmallId(); - app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, packet->m_uiGamePrivileges); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); + maxPlayers = packet->maxPlayers; - // Assume all privileges are on, so that the first message we see only indicates things that have been turned off - unsigned int startingPrivileges = 0; - Player::enableAllPlayerPrivileges(startingPrivileges,true); + // need to have a player before the setLocalCreativeMode + std::shared_ptr lastPlayer = minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + ((MultiPlayerGameMode*)minecraft->localgameModes[m_userIndex]) + ->setLocalMode(GameType::byId(packet->gameType)); + minecraft->player = lastPlayer; - displayPrivilegeChanges(minecraft->localplayers[m_userIndex],startingPrivileges); - } - - maxPlayers = packet->maxPlayers; - - // need to have a player before the setLocalCreativeMode - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - ((MultiPlayerGameMode *)minecraft->localgameModes[m_userIndex])->setLocalMode(GameType::byId(packet->gameType)); - minecraft->player = lastPlayer; - - // make sure the UI offsets for this player are set correctly - if(iUserID!=-1) - { - ui.UpdateSelectedItemPos(iUserID); - } - - TelemetryManager->RecordLevelStart(m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); + // make sure the UI offsets for this player are set correctly + if (iUserID != -1) { + ui.UpdateSelectedItemPos(iUserID); + } + + TelemetryManager->RecordLevelStart( + m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, + app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } -void ClientConnection::handleAddEntity(std::shared_ptr packet) -{ +void ClientConnection::handleAddEntity( + std::shared_ptr packet) { double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; std::shared_ptr e; - boolean setRot = true; + boolean setRot = true; - // 4J-PB - replacing this massive if nest with switch - switch(packet->type) - { - case AddEntityPacket::MINECART_RIDEABLE: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) ); - break; - case AddEntityPacket::MINECART_CHEST: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); - break; + // 4J-PB - replacing this massive if nest with switch + switch (packet->type) { + case AddEntityPacket::MINECART_RIDEABLE: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::RIDEABLE)); + break; + case AddEntityPacket::MINECART_CHEST: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::CHEST)); + break; - case AddEntityPacket::MINECART_FURNACE: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) ); - break; + case AddEntityPacket::MINECART_FURNACE: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::FURNACE)); + break; - case AddEntityPacket::FISH_HOOK: - { - // 4J Stu - Brought forward from 1.4 to be able to drop XP from fishing - std::shared_ptr owner = getEntity(packet->data); + case AddEntityPacket::FISH_HOOK: { + // 4J Stu - Brought forward from 1.4 to be able to drop XP from + // fishing + std::shared_ptr owner = getEntity(packet->data); - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - - owner = minecraft->localplayers[i]; - break; - } - } - } - } - std::shared_ptr player = std::dynamic_pointer_cast(owner); - if (player != NULL) - { - std::shared_ptr hook = std::shared_ptr( new FishingHook(level, x, y, z, player) ); - e = hook; - // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' - player->fishing = hook; - } - packet->data = 0; - } - break; - case AddEntityPacket::ARROW: - e = std::shared_ptr( new Arrow(level, x, y, z) ); - break; - case AddEntityPacket::SNOWBALL: - e = std::shared_ptr( new Snowball(level, x, y, z) ); - break; - case AddEntityPacket::ITEM_FRAME: - { - int ix=(int) x; - int iy=(int) y; - int iz = (int) z; - app.DebugPrintf("ClientConnection ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } - e = std::shared_ptr(new ItemFrame(level, (int) x, (int) y, (int) z, packet->data)); - packet->data = 0; - setRot = false; - break; - case AddEntityPacket::THROWN_ENDERPEARL: - e = std::shared_ptr( new ThrownEnderpearl(level, x, y, z) ); - break; - case AddEntityPacket::EYEOFENDERSIGNAL: - e = std::shared_ptr( new EyeOfEnderSignal(level, x, y, z) ); - break; - case AddEntityPacket::FIREBALL: - e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::SMALL_FIREBALL: - e = std::shared_ptr( new SmallFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::DRAGON_FIRE_BALL: - e = std::shared_ptr( new DragonFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::EGG: - e = std::shared_ptr( new ThrownEgg(level, x, y, z) ); - break; - case AddEntityPacket::THROWN_POTION: - e = std::shared_ptr( new ThrownPotion(level, x, y, z, packet->data) ); - packet->data = 0; - break; - case AddEntityPacket::THROWN_EXPBOTTLE: - e = std::shared_ptr( new ThrownExpBottle(level, x, y, z) ); - packet->data = 0; - break; - case AddEntityPacket::BOAT: - e = std::shared_ptr( new Boat(level, x, y, z) ); - break; - case AddEntityPacket::PRIMED_TNT: - e = std::shared_ptr( new PrimedTnt(level, x, y, z) ); - break; - case AddEntityPacket::ENDER_CRYSTAL: - e = std::shared_ptr( new EnderCrystal(level, x, y, z) ); - break; - case AddEntityPacket::ITEM: - e = std::shared_ptr( new ItemEntity(level, x, y, z) ); - break; - case AddEntityPacket::FALLING: - e = std::shared_ptr( new FallingTile(level, x, y, z, packet->data & 0xFFFF, packet->data >> 16) ); - packet->data = 0; - break; - - - - } - /* if (packet->type == AddEntityPacket::MINECART_RIDEABLE) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) ); - if (packet->type == AddEntityPacket::MINECART_CHEST) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); - if (packet->type == AddEntityPacket::MINECART_FURNACE) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) ); - if (packet->type == AddEntityPacket::FISH_HOOK) - { - // 4J Stu - Brought forward from 1.4 to be able to drop XP from fishing - std::shared_ptr owner = getEntity(packet->data); - - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - - owner = minecraft->localplayers[i]; - break; - } - } - } - } - std::shared_ptr player = std::dynamic_pointer_cast(owner); - if (player != NULL) - { - std::shared_ptr hook = std::shared_ptr( new FishingHook(level, x, y, z, player) ); - e = hook; - // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' - player->fishing = hook; - } - packet->data = 0; - } - - if (packet->type == AddEntityPacket::ARROW) e = std::shared_ptr( new Arrow(level, x, y, z) ); - if (packet->type == AddEntityPacket::SNOWBALL) e = std::shared_ptr( new Snowball(level, x, y, z) ); - if (packet->type == AddEntityPacket::THROWN_ENDERPEARL) e = std::shared_ptr( new ThrownEnderpearl(level, x, y, z) ); - if (packet->type == AddEntityPacket::EYEOFENDERSIGNAL) e = std::shared_ptr( new EyeOfEnderSignal(level, x, y, z) ); - if (packet->type == AddEntityPacket::FIREBALL) - { - e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; + // 4J - check all local players to find match + if (owner == NULL) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == + packet->data) { + owner = minecraft->localplayers[i]; + break; + } + } + } + } + std::shared_ptr player = + std::dynamic_pointer_cast(owner); + if (player != NULL) { + std::shared_ptr hook = + std::shared_ptr( + new FishingHook(level, x, y, z, player)); + e = hook; + // 4J Stu - Move the player->fishing out of the ctor as we + // cannot reference 'this' + player->fishing = hook; + } + packet->data = 0; + } break; + case AddEntityPacket::ARROW: + e = std::shared_ptr(new Arrow(level, x, y, z)); + break; + case AddEntityPacket::SNOWBALL: + e = std::shared_ptr(new Snowball(level, x, y, z)); + break; + case AddEntityPacket::ITEM_FRAME: { + int ix = (int)x; + int iy = (int)y; + int iz = (int)z; + app.DebugPrintf("ClientConnection ITEM_FRAME xyz %d,%d,%d\n", ix, + iy, iz); + } + e = std::shared_ptr( + new ItemFrame(level, (int)x, (int)y, (int)z, packet->data)); + packet->data = 0; + setRot = false; + break; + case AddEntityPacket::THROWN_ENDERPEARL: + e = std::shared_ptr(new ThrownEnderpearl(level, x, y, z)); + break; + case AddEntityPacket::EYEOFENDERSIGNAL: + e = std::shared_ptr(new EyeOfEnderSignal(level, x, y, z)); + break; + case AddEntityPacket::FIREBALL: + e = std::shared_ptr( + new Fireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::SMALL_FIREBALL: + e = std::shared_ptr( + new SmallFireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::DRAGON_FIRE_BALL: + e = std::shared_ptr( + new DragonFireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::EGG: + e = std::shared_ptr(new ThrownEgg(level, x, y, z)); + break; + case AddEntityPacket::THROWN_POTION: + e = std::shared_ptr( + new ThrownPotion(level, x, y, z, packet->data)); + packet->data = 0; + break; + case AddEntityPacket::THROWN_EXPBOTTLE: + e = std::shared_ptr(new ThrownExpBottle(level, x, y, z)); + packet->data = 0; + break; + case AddEntityPacket::BOAT: + e = std::shared_ptr(new Boat(level, x, y, z)); + break; + case AddEntityPacket::PRIMED_TNT: + e = std::shared_ptr(new PrimedTnt(level, x, y, z)); + break; + case AddEntityPacket::ENDER_CRYSTAL: + e = std::shared_ptr(new EnderCrystal(level, x, y, z)); + break; + case AddEntityPacket::ITEM: + e = std::shared_ptr(new ItemEntity(level, x, y, z)); + break; + case AddEntityPacket::FALLING: + e = std::shared_ptr(new FallingTile( + level, x, y, z, packet->data & 0xFFFF, packet->data >> 16)); + packet->data = 0; + break; } - if (packet->type == AddEntityPacket::SMALL_FIREBALL) - { - e = std::shared_ptr( new SmallFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::EGG) e = std::shared_ptr( new ThrownEgg(level, x, y, z) ); - if (packet->type == AddEntityPacket::THROWN_POTION) - { - e = std::shared_ptr( new ThrownPotion(level, x, y, z, packet->data) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::THROWN_EXPBOTTLE) - { - e = std::shared_ptr( new ThrownExpBottle(level, x, y, z) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::BOAT) e = std::shared_ptr( new Boat(level, x, y, z) ); - if (packet->type == AddEntityPacket::PRIMED_TNT) e = std::shared_ptr( new PrimedTnt(level, x, y, z) ); - if (packet->type == AddEntityPacket::ENDER_CRYSTAL) e = std::shared_ptr( new EnderCrystal(level, x, y, z) ); - if (packet->type == AddEntityPacket::FALLING_SAND) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::sand->id) ); - if (packet->type == AddEntityPacket::FALLING_GRAVEL) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::gravel->id) ); - if (packet->type == AddEntityPacket::FALLING_EGG) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::dragonEgg_Id) ); + /* if (packet->type == AddEntityPacket::MINECART_RIDEABLE) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) + ); if (packet->type == AddEntityPacket::MINECART_CHEST) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); + if (packet->type == AddEntityPacket::MINECART_FURNACE) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) + ); if (packet->type == AddEntityPacket::FISH_HOOK) + { + // 4J Stu - Brought forward from 1.4 to be able to drop XP + from fishing std::shared_ptr owner = getEntity(packet->data); - */ + // 4J - check all local players to find match + if( owner == NULL ) + { + for( int i = 0; i < XUSER_MAX_COUNT; i++ ) + { + if( minecraft->localplayers[i] ) + { + if( + minecraft->localplayers[i]->entityId == packet->data ) + { - if (e != NULL) - { + owner = + minecraft->localplayers[i]; break; + } + } + } + } + std::shared_ptr player = + std::dynamic_pointer_cast(owner); if (player != NULL) + { + std::shared_ptr hook = + std::shared_ptr( new FishingHook(level, x, y, z, player) ); + e = hook; + // 4J Stu - Move the player->fishing out of the ctor + as we cannot reference 'this' player->fishing = hook; + } + packet->data = 0; + } + + if (packet->type == AddEntityPacket::ARROW) e = std::shared_ptr( + new Arrow(level, x, y, z) ); if (packet->type == + AddEntityPacket::SNOWBALL) e = std::shared_ptr( new + Snowball(level, x, y, z) ); if (packet->type == + AddEntityPacket::THROWN_ENDERPEARL) e = std::shared_ptr( new + ThrownEnderpearl(level, x, y, z) ); if (packet->type == + AddEntityPacket::EYEOFENDERSIGNAL) e = std::shared_ptr( new + EyeOfEnderSignal(level, x, y, z) ); if (packet->type == + AddEntityPacket::FIREBALL) + { + e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa + / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::SMALL_FIREBALL) + { + e = std::shared_ptr( new SmallFireball(level, x, y, + z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); + packet->data = 0; + } + if (packet->type == AddEntityPacket::EGG) e = std::shared_ptr( + new ThrownEgg(level, x, y, z) ); if (packet->type == + AddEntityPacket::THROWN_POTION) + { + e = std::shared_ptr( new ThrownPotion(level, x, y, z, + packet->data) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::THROWN_EXPBOTTLE) + { + e = std::shared_ptr( new ThrownExpBottle(level, x, y, + z) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::BOAT) e = std::shared_ptr( + new Boat(level, x, y, z) ); if (packet->type == + AddEntityPacket::PRIMED_TNT) e = std::shared_ptr( new + PrimedTnt(level, x, y, z) ); if (packet->type == + AddEntityPacket::ENDER_CRYSTAL) e = std::shared_ptr( new + EnderCrystal(level, x, y, z) ); if (packet->type == + AddEntityPacket::FALLING_SAND) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::sand->id) ); if (packet->type == + AddEntityPacket::FALLING_GRAVEL) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::gravel->id) ); if (packet->type == + AddEntityPacket::FALLING_EGG) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::dragonEgg_Id) ); + + */ + + if (e != NULL) { e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; - float yRot = packet->yRot * 360 / 256.0f; - float xRot = packet->xRot * 360 / 256.0f; - e->yRotp = packet->yRot; - e->xRotp = packet->xRot; + float yRot = packet->yRot * 360 / 256.0f; + float xRot = packet->xRot * 360 / 256.0f; + e->yRotp = packet->yRot; + e->xRotp = packet->xRot; - if (setRot) - { - e->yRot = 0.0f; - e->xRot = 0.0f; - } + if (setRot) { + e->yRot = 0.0f; + e->xRot = 0.0f; + } - std::vector > *subEntities = e->getSubEntities(); - if (subEntities != NULL) - { - int offs = packet->id - e->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - (*it)->entityId += offs; - //subEntities[i].entityId += offs; - //System.out.println(subEntities[i].entityId); - } - } + std::vector >* subEntities = + e->getSubEntities(); + if (subEntities != NULL) { + int offs = packet->id - e->entityId; + // for (int i = 0; i < subEntities.length; i++) + for (AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); + ++it) { + (*it)->entityId += offs; + // subEntities[i].entityId += offs; + // System.out.println(subEntities[i].entityId); + } + } - // Note - not doing this move for frame, as the ctor for these objects does some adjustments on the position based on direction to move the object out slightly from what it is attached to, and this just overwrites it - if( packet->type != AddEntityPacket::ITEM_FRAME ) - { - e->absMoveTo(x,y,z,yRot,xRot); - } + // Note - not doing this move for frame, as the ctor for these objects + // does some adjustments on the position based on direction to move the + // object out slightly from what it is attached to, and this just + // overwrites it + if (packet->type != AddEntityPacket::ITEM_FRAME) { + e->absMoveTo(x, y, z, yRot, xRot); + } e->entityId = packet->id; level->putEntity(packet->id, e); - if (packet->data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 - { - - if (packet->type == AddEntityPacket::ARROW) - { + if (packet->data > -1) // 4J - changed "no data" value to be -1, we can + // have a valid entity id of 0 + { + if (packet->type == AddEntityPacket::ARROW) { std::shared_ptr owner = getEntity(packet->data); - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - owner = minecraft->localplayers[i]; - break; - } - } - } - } + // 4J - check all local players to find match + if (owner == NULL) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == + packet->data) { + owner = minecraft->localplayers[i]; + break; + } + } + } + } - if (std::dynamic_pointer_cast(owner) != NULL) - { - std::dynamic_pointer_cast(e)->owner = std::dynamic_pointer_cast(owner); + if (std::dynamic_pointer_cast(owner) != NULL) { + std::dynamic_pointer_cast(e)->owner = + std::dynamic_pointer_cast(owner); } } - e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); + e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, + packet->za / 8000.0); } - } - + } } -void ClientConnection::handleAddExperienceOrb(std::shared_ptr packet) -{ - std::shared_ptr e = std::shared_ptr( new ExperienceOrb(level, packet->x / 32.0, packet->y / 32.0, packet->z / 32.0, packet->value) ); - e->xp = packet->x; - e->yp = packet->y; - e->zp = packet->z; - e->yRot = 0; - e->xRot = 0; - e->entityId = packet->id; - level->putEntity(packet->id, e); +void ClientConnection::handleAddExperienceOrb( + std::shared_ptr packet) { + std::shared_ptr e = std::shared_ptr( + new ExperienceOrb(level, packet->x / 32.0, packet->y / 32.0, + packet->z / 32.0, packet->value)); + e->xp = packet->x; + e->yp = packet->y; + e->zp = packet->z; + e->yRot = 0; + e->xRot = 0; + e->entityId = packet->id; + level->putEntity(packet->id, e); } -void ClientConnection::handleAddGlobalEntity(std::shared_ptr packet) -{ +void ClientConnection::handleAddGlobalEntity( + std::shared_ptr packet) { double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; - std::shared_ptr e;// = nullptr; - if (packet->type == AddGlobalEntityPacket::LIGHTNING) e = std::shared_ptr( new LightningBolt(level, x, y, z) ); - if (e != NULL) - { + std::shared_ptr e; // = nullptr; + if (packet->type == AddGlobalEntityPacket::LIGHTNING) + e = std::shared_ptr(new LightningBolt(level, x, y, z)); + if (e != NULL) { e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; @@ -696,131 +726,149 @@ void ClientConnection::handleAddGlobalEntity(std::shared_ptr packet) -{ - std::shared_ptr painting = std::shared_ptr( new Painting(level, packet->x, packet->y, packet->z, packet->dir, packet->motive) ); +void ClientConnection::handleAddPainting( + std::shared_ptr packet) { + std::shared_ptr painting = std::shared_ptr(new Painting( + level, packet->x, packet->y, packet->z, packet->dir, packet->motive)); level->putEntity(packet->id, painting); } -void ClientConnection::handleSetEntityMotion(std::shared_ptr packet) -{ +void ClientConnection::handleSetEntityMotion( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); + e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, + packet->za / 8000.0); } -void ClientConnection::handleSetEntityData(std::shared_ptr packet) -{ +void ClientConnection::handleSetEntityData( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); - if (e != NULL && packet->getUnpackedData() != NULL) - { + if (e != NULL && packet->getUnpackedData() != NULL) { e->getEntityData()->assignValues(packet->getUnpackedData()); } } -void ClientConnection::handleAddPlayer(std::shared_ptr packet) -{ - // Some remote players could actually be local players that are already added - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - // need to use the XUID here - PlayerUID playerXUIDOnline = INVALID_XUID, playerXUIDOffline = INVALID_XUID; - ProfileManager.GetXUID(idx,&playerXUIDOnline,true); - ProfileManager.GetXUID(idx,&playerXUIDOffline,false); - if( (playerXUIDOnline != INVALID_XUID && ProfileManager.AreXUIDSEqual(playerXUIDOnline,packet->xuid) ) || - (playerXUIDOffline != INVALID_XUID && ProfileManager.AreXUIDSEqual(playerXUIDOffline,packet->xuid) ) ) - { - app.DebugPrintf("AddPlayerPacket received with XUID of local player\n"); - return; - } - } +void ClientConnection::handleAddPlayer( + std::shared_ptr packet) { + // Some remote players could actually be local players that are already + // added + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + // need to use the XUID here + PlayerUID playerXUIDOnline = INVALID_XUID, + playerXUIDOffline = INVALID_XUID; + ProfileManager.GetXUID(idx, &playerXUIDOnline, true); + ProfileManager.GetXUID(idx, &playerXUIDOffline, false); + if ((playerXUIDOnline != INVALID_XUID && + ProfileManager.AreXUIDSEqual(playerXUIDOnline, packet->xuid)) || + (playerXUIDOffline != INVALID_XUID && + ProfileManager.AreXUIDSEqual(playerXUIDOffline, packet->xuid))) { + app.DebugPrintf( + "AddPlayerPacket received with XUID of local player\n"); + return; + } + } double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; float yRot = packet->yRot * 360 / 256.0f; float xRot = packet->xRot * 360 / 256.0f; - std::shared_ptr player = std::shared_ptr( new RemotePlayer(minecraft->level, packet->name) ); + std::shared_ptr player = std::shared_ptr( + new RemotePlayer(minecraft->level, packet->name)); player->xo = player->xOld = player->xp = packet->x; player->yo = player->yOld = player->yp = packet->y; player->zo = player->zOld = player->zp = packet->z; - player->xRotp = packet->xRot; - player->yRotp = packet->yRot; - player->yHeadRot = packet->yHeadRot * 360 / 256.0f; - player->setXuid(packet->xuid); + player->xRotp = packet->xRot; + player->yRotp = packet->yRot; + player->yHeadRot = packet->yHeadRot * 360 / 256.0f; + player->setXuid(packet->xuid); #ifdef _DURANGO - // On Durango request player display name from network manager - INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerByXuid(player->getXuid()); - if (networkPlayer != NULL) player->displayName = networkPlayer->GetDisplayName(); + // On Durango request player display name from network manager + INetworkPlayer* networkPlayer = + g_NetworkManager.GetPlayerByXuid(player->getXuid()); + if (networkPlayer != NULL) + player->displayName = networkPlayer->GetDisplayName(); #else - // On all other platforms display name is just gamertag so don't check with the network manager - player->displayName = player->name; + // On all other platforms display name is just gamertag so don't check with + // the network manager + player->displayName = player->name; #endif - // printf("\t\t\t\t%d: Add player\n",packet->id,packet->yRot); + // printf("\t\t\t\t%d: Add player\n",packet->id,packet->yRot); int item = packet->carriedItem; - if (item == 0) - { - player->inventory->items[player->inventory->selected] = std::shared_ptr(); // NULL; - } - else - { - player->inventory->items[player->inventory->selected] = std::shared_ptr( new ItemInstance(item, 1, 0) ); + if (item == 0) { + player->inventory->items[player->inventory->selected] = + std::shared_ptr(); // NULL; + } else { + player->inventory->items[player->inventory->selected] = + std::shared_ptr(new ItemInstance(item, 1, 0)); } player->absMoveTo(x, y, z, yRot, xRot); - player->setPlayerIndex( packet->m_playerIndex ); - player->setCustomSkin( packet->m_skinId ); - player->setCustomCape( packet->m_capeId ); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); - - if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) - { - if( minecraft->addPendingClientTextureRequest(player->customTextureUrl) ) - { - app.DebugPrintf("Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + player->setPlayerIndex(packet->m_playerIndex); + player->setCustomSkin(packet->m_skinId); + player->setCustomCape(packet->m_capeId); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_uiGamePrivileges); - send(std::shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); - } - } - else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); - } + if (!player->customTextureUrl.empty() && + player->customTextureUrl.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl)) { + if (minecraft->addPendingClientTextureRequest( + player->customTextureUrl)) { + app.DebugPrintf( + "Client sending TextureAndGeometryPacket to get custom skin " + "%ls for player %ls\n", + player->customTextureUrl.c_str(), player->name.c_str()); - app.DebugPrintf("Custom skin for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl.c_str()); - - if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - if( minecraft->addPendingClientTextureRequest(player->customTextureUrl2) ) - { - app.DebugPrintf("Client sending texture packet to get custom cape %ls for player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); - send(std::shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); - } - } - else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); - } + send(std::shared_ptr( + new TextureAndGeometryPacket(player->customTextureUrl, NULL, + 0))); + } + } else if (!player->customTextureUrl.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl, NULL, 0); + } - app.DebugPrintf("Custom cape for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl2.c_str()); + app.DebugPrintf("Custom skin for player %ls is %ls\n", player->name.c_str(), + player->customTextureUrl.c_str()); + + if (!player->customTextureUrl2.empty() && + player->customTextureUrl2.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl2)) { + if (minecraft->addPendingClientTextureRequest( + player->customTextureUrl2)) { + app.DebugPrintf( + "Client sending texture packet to get custom cape %ls for " + "player %ls\n", + player->customTextureUrl2.c_str(), player->name.c_str()); + send(std::shared_ptr( + new TexturePacket(player->customTextureUrl2, NULL, 0))); + } + } else if (!player->customTextureUrl2.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl2)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl2, NULL, 0); + } + + app.DebugPrintf("Custom cape for player %ls is %ls\n", player->name.c_str(), + player->customTextureUrl2.c_str()); level->putEntity(packet->id, player); - std::vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) - { - player->getEntityData()->assignValues(unpackedData); - } - + std::vector >* unpackedData = + packet->getUnpackedData(); + if (unpackedData != NULL) { + player->getEntityData()->assignValues(unpackedData); + } } -void ClientConnection::handleTeleportEntity(std::shared_ptr packet) -{ +void ClientConnection::handleTeleportEntity( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp = packet->x; @@ -829,79 +877,82 @@ void ClientConnection::handleTeleportEntity(std::shared_ptrxp / 32.0; double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - make sure xRot stays within -90 -> 90 range - int ixRot = packet->xRot; - if( ixRot >= 128 ) ixRot -= 256; + // 4J - make sure xRot stays within -90 -> 90 range + int ixRot = packet->xRot; + if (ixRot >= 128) ixRot -= 256; float yRot = packet->yRot * 360 / 256.0f; float xRot = ixRot * 360 / 256.0f; - e->yRotp = packet->yRot; - e->xRotp = ixRot; + e->yRotp = packet->yRot; + e->xRotp = ixRot; -// printf("\t\t\t\t%d: Teleport to %d (lerp to %f)\n",packet->id,packet->yRot,yRot); + // printf("\t\t\t\t%d: Teleport to %d (lerp to + //%f)\n",packet->id,packet->yRot,yRot); e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleMoveEntity(std::shared_ptr packet) -{ +void ClientConnection::handleMoveEntity( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; double x = e->xp / 32.0; - // 4J - The original code did not add the 1/64.0f like the teleport above did, which caused minecarts to fall through the ground + // 4J - The original code did not add the 1/64.0f like the teleport above + // did, which caused minecarts to fall through the ground double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - have changed rotation to be relative here too - e->yRotp += packet->yRot; - e->xRotp += packet->xRot; - float yRot = ( e->yRotp * 360 ) / 256.0f; - float xRot = ( e->xRotp * 360 ) / 256.0f; -// float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; -// float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; + // 4J - have changed rotation to be relative here too + e->yRotp += packet->yRot; + e->xRotp += packet->xRot; + float yRot = (e->yRotp * 360) / 256.0f; + float xRot = (e->xRotp * 360) / 256.0f; + // float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; + // float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleRotateMob(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); - if (e == NULL) return; - float yHeadRot = packet->yHeadRot * 360 / 256.f; - e->setYHeadRot(yHeadRot); +void ClientConnection::handleRotateMob( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + float yHeadRot = packet->yHeadRot * 360 / 256.f; + e->setYHeadRot(yHeadRot); } -void ClientConnection::handleMoveEntitySmall(std::shared_ptr packet) -{ +void ClientConnection::handleMoveEntitySmall( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; double x = e->xp / 32.0; - // 4J - The original code did not add the 1/64.0f like the teleport above did, which caused minecarts to fall through the ground + // 4J - The original code did not add the 1/64.0f like the teleport above + // did, which caused minecarts to fall through the ground double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - have changed rotation to be relative here too - e->yRotp += packet->yRot; - e->xRotp += packet->xRot; - float yRot = ( e->yRotp * 360 ) / 256.0f; - float xRot = ( e->xRotp * 360 ) / 256.0f; -// float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; -// float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; + // 4J - have changed rotation to be relative here too + e->yRotp += packet->yRot; + e->xRotp += packet->xRot; + float yRot = (e->yRotp * 360) / 256.0f; + float xRot = (e->xRotp * 360) / 256.0f; + // float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; + // float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleRemoveEntity(std::shared_ptr packet) -{ - for (int i = 0; i < packet->ids.length; i++) - { - level->removeEntity(packet->ids[i]); - } +void ClientConnection::handleRemoveEntity( + std::shared_ptr packet) { + for (int i = 0; i < packet->ids.length; i++) { + level->removeEntity(packet->ids[i]); + } } -void ClientConnection::handleMovePlayer(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; //minecraft->player; +void ClientConnection::handleMovePlayer( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; // minecraft->player; double x = player->x; double y = player->y; @@ -909,14 +960,12 @@ void ClientConnection::handleMovePlayer(std::shared_ptr packet float yRot = player->yRot; float xRot = player->xRot; - if (packet->hasPos) - { + if (packet->hasPos) { x = packet->x; y = packet->y; z = packet->z; } - if (packet->hasRot) - { + if (packet->hasRot) { yRot = packet->yRot; xRot = packet->xRot; } @@ -929,2097 +978,2200 @@ void ClientConnection::handleMovePlayer(std::shared_ptr packet packet->z = player->z; packet->yView = player->y; connection->send(packet); - if (!started) - { - - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCConnected * 100)/ (eCCConnected)); - } + if (!started) { + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCConnected * 100) / (eCCConnected)); + } player->xo = player->x; player->yo = player->y; player->zo = player->z; - // 4J - added setting xOld/yOld/zOld here too, as otherwise at the start of the game we interpolate the player position from the origin to wherever its first position really is - player->xOld = player->x; - player->yOld = player->y; - player->zOld = player->z; + // 4J - added setting xOld/yOld/zOld here too, as otherwise at the start + // of the game we interpolate the player position from the origin to + // wherever its first position really is + player->xOld = player->x; + player->yOld = player->y; + player->zOld = player->z; started = true; minecraft->setScreen(NULL); - - // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players are spawned at incorrect places after re-joining previously saved and loaded "Mass Effect World". - // Move this check from Minecraft::createExtraLocalPlayer - // 4J-PB - can't call this when this function is called from the qnet thread (GetGameStarted will be false) - if(app.GetGameStarted()) - { - ui.CloseUIScenes(m_userIndex); - } - } + // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players + // are spawned at incorrect places after re-joining previously saved and + // loaded "Mass Effect World". Move this check from + // Minecraft::createExtraLocalPlayer 4J-PB - can't call this when this + // function is called from the qnet thread (GetGameStarted will be + // false) + if (app.GetGameStarted()) { + ui.CloseUIScenes(m_userIndex); + } + } } // 4J Added -void ClientConnection::handleChunkVisibilityArea(std::shared_ptr packet) -{ - for(int z = packet->m_minZ; z <= packet->m_maxZ; ++z) - for(int x = packet->m_minX; x <= packet->m_maxX; ++x) - level->setChunkVisible(x, z, true); +void ClientConnection::handleChunkVisibilityArea( + std::shared_ptr packet) { + for (int z = packet->m_minZ; z <= packet->m_maxZ; ++z) + for (int x = packet->m_minX; x <= packet->m_maxX; ++x) + level->setChunkVisible(x, z, true); } -void ClientConnection::handleChunkVisibility(std::shared_ptr packet) -{ - level->setChunkVisible(packet->x, packet->z, packet->visible); +void ClientConnection::handleChunkVisibility( + std::shared_ptr packet) { + level->setChunkVisible(packet->x, packet->z, packet->visible); } -void ClientConnection::handleChunkTilesUpdate(std::shared_ptr packet) -{ - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle chunk tiles update"); - LevelChunk *lc = dimensionLevel->getChunk(packet->xc, packet->zc); - int xo = packet->xc * 16; - int zo = packet->zc * 16; - // 4J Stu - Unshare before we make any changes incase the server is already another step ahead of us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - // This is quite expensive to do, so only consider unsharing if this tile setting is going to actually - // change something - bool forcedUnshare = false; - for (int i = 0; i < packet->count; i++) - { - int pos = packet->positions[i]; - int tile = packet->blocks[i] & 0xff; - int data = packet->data[i]; +void ClientConnection::handleChunkTilesUpdate( + std::shared_ptr packet) { + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle chunk tiles update"); + LevelChunk* lc = dimensionLevel->getChunk(packet->xc, packet->zc); + int xo = packet->xc * 16; + int zo = packet->zc * 16; + // 4J Stu - Unshare before we make any changes incase the server is + // already another step ahead of us Fix for #7904 - Gameplay: Players + // can dupe torches by throwing them repeatedly into water. This is + // quite expensive to do, so only consider unsharing if this tile + // setting is going to actually change something + bool forcedUnshare = false; + for (int i = 0; i < packet->count; i++) { + int pos = packet->positions[i]; + int tile = packet->blocks[i] & 0xff; + int data = packet->data[i]; + int x = (pos >> 12) & 15; + int z = (pos >> 8) & 15; + int y = ((pos) & 255); - int x = (pos >> 12) & 15; - int z = (pos >> 8) & 15; - int y = ((pos) & 255); + // If this is going to actually change a tile, we'll need to unshare + int prevTile = lc->getTile(x, y, z); + if ((tile != prevTile && !forcedUnshare)) { + PIXBeginNamedEvent(0, "Chunk data unsharing\n"); + dimensionLevel->unshareChunkAt(xo, zo); + PIXEndNamedEvent(); + forcedUnshare = true; + } - // If this is going to actually change a tile, we'll need to unshare - int prevTile = lc->getTile(x, y, z); - if( ( tile != prevTile && !forcedUnshare ) ) - { - PIXBeginNamedEvent(0,"Chunk data unsharing\n"); - dimensionLevel->unshareChunkAt(xo,zo); - PIXEndNamedEvent(); - forcedUnshare = true; - } + // 4J - Changes now that lighting is done at the client side of + // things... Note - the java version now calls the doSetTileAndData + // method from the level here rather than the levelchunk, which + // ultimately ends up calling checkLight for the altered tile. For + // us this doesn't always work as when sharing tile data between a + // local server & client, the tile might not be considered to be + // being changed on the client as the server already has changed the + // shared data, and so the checkLight doesn't happen. Hence doing an + // explicit checkLight here instead. + lc->setTileAndData(x, y, z, tile, data); + dimensionLevel->checkLight(x + xo, y, z + zo); - // 4J - Changes now that lighting is done at the client side of things... - // Note - the java version now calls the doSetTileAndData method from the level here rather than the levelchunk, which ultimately ends up - // calling checkLight for the altered tile. For us this doesn't always work as when sharing tile data between a local server & client, the - // tile might not be considered to be being changed on the client as the server already has changed the shared data, and so the checkLight - // doesn't happen. Hence doing an explicit checkLight here instead. - lc->setTileAndData(x, y, z, tile, data); - dimensionLevel->checkLight(x + xo, y, z + zo); + dimensionLevel->clearResetRegion(x + xo, y, z + zo, x + xo, y, + z + zo); - dimensionLevel->clearResetRegion(x + xo, y, z + zo, x + xo, y, z + zo); + // Don't bother setting this to dirty if it isn't going to visually + // change - we get a lot of water changing from static to dynamic + // for instance + if (!(((prevTile == Tile::water_Id) && + (tile == Tile::calmWater_Id)) || + ((prevTile == Tile::calmWater_Id) && + (tile == Tile::water_Id)) || + ((prevTile == Tile::lava_Id) && + (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && + (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && + (tile == Tile::lava_Id)))) { + dimensionLevel->setTilesDirty(x + xo, y, z + zo, x + xo, y, + z + zo); + } - // Don't bother setting this to dirty if it isn't going to visually change - we get a lot of - // water changing from static to dynamic for instance - if(!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || - ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ) - { - dimensionLevel->setTilesDirty(x + xo, y, z + zo, x + xo, y, z + zo); - } + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing + // this we end up with stray tile entities kicking round, which + // leads to a bug where chests can't be properly placed again in a + // location after (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + xo + x, y, zo + z, xo + x + 1, y + 1, zo + z + 1); + } + PIXBeginNamedEvent(0, "Chunk data sharing\n"); + dimensionLevel->shareChunkAt(xo, + zo); // 4J - added - only shares if chunks + // are same on server & client + PIXEndNamedEvent(); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(xo + x, y, zo + z, xo + x+1, y+1, zo + z+1); - } - PIXBeginNamedEvent(0,"Chunk data sharing\n"); - dimensionLevel->shareChunkAt(xo,zo); // 4J - added - only shares if chunks are same on server & client - PIXEndNamedEvent(); - - PIXEndNamedEvent(); - } + PIXEndNamedEvent(); + } } -void ClientConnection::handleBlockRegionUpdate(std::shared_ptr packet) -{ - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle block region update"); +void ClientConnection::handleBlockRegionUpdate( + std::shared_ptr packet) { + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle block region update"); - int y1 = packet->y + packet->ys; - if(packet->bIsFullChunk) - { - y1 = Level::maxBuildHeight; - if(packet->buffer.length > 0) LevelChunk::reorderBlocksAndDataToXZY(packet->y, packet->xs, packet->ys, packet->zs, &packet->buffer); - } - dimensionLevel->clearResetRegion(packet->x, packet->y, packet->z, packet->x + packet->xs - 1, y1 - 1, packet->z + packet->zs - 1); + int y1 = packet->y + packet->ys; + if (packet->bIsFullChunk) { + y1 = Level::maxBuildHeight; + if (packet->buffer.length > 0) + LevelChunk::reorderBlocksAndDataToXZY(packet->y, packet->xs, + packet->ys, packet->zs, + &packet->buffer); + } + dimensionLevel->clearResetRegion(packet->x, packet->y, packet->z, + packet->x + packet->xs - 1, y1 - 1, + packet->z + packet->zs - 1); - // Only full chunks send lighting information now - added flag to end of this call - dimensionLevel->setBlocksAndData(packet->x, packet->y, packet->z, packet->xs, packet->ys, packet->zs, packet->buffer, packet->bIsFullChunk); + // Only full chunks send lighting information now - added flag to end of + // this call + dimensionLevel->setBlocksAndData(packet->x, packet->y, packet->z, + packet->xs, packet->ys, packet->zs, + packet->buffer, packet->bIsFullChunk); -// OutputDebugString("END BRU\n"); + // OutputDebugString("END BRU\n"); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(packet->x, packet->y, packet->z, packet->x + packet->xs, y1, packet->z + packet->zs ); + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing this + // we end up with stray tile entities kicking round, which leads to a + // bug where chests can't be properly placed again in a location after + // (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + packet->x, packet->y, packet->z, packet->x + packet->xs, y1, + packet->z + packet->zs); - // If this is a full packet for a chunk, make sure that the cache now considers that it has data for this chunk - this is used to determine whether to bother - // rendering mobs or not, so we don't have them in crazy positions before the data is there - if( packet->bIsFullChunk ) - { - dimensionLevel->dataReceivedForChunk( packet->x >> 4, packet->z >> 4 ); - } - PIXEndNamedEvent(); - } + // If this is a full packet for a chunk, make sure that the cache now + // considers that it has data for this chunk - this is used to determine + // whether to bother rendering mobs or not, so we don't have them in + // crazy positions before the data is there + if (packet->bIsFullChunk) { + dimensionLevel->dataReceivedForChunk(packet->x >> 4, + packet->z >> 4); + } + PIXEndNamedEvent(); + } } -void ClientConnection::handleTileUpdate(std::shared_ptr packet) -{ - // 4J added - using a block of 255 to signify that this is a packet for destroying a tile, where we need to inform the level renderer that we are about to do so. - // This is used in creative mode as the point where a tile is first destroyed at the client end of things. Packets formed like this are potentially sent from - // ServerPlayerGameMode::destroyBlock - bool destroyTilePacket = false; - if( packet->block == 255 ) - { - packet->block = 0; - destroyTilePacket = true; - } - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle tile update"); +void ClientConnection::handleTileUpdate( + std::shared_ptr packet) { + // 4J added - using a block of 255 to signify that this is a packet for + // destroying a tile, where we need to inform the level renderer that we are + // about to do so. This is used in creative mode as the point where a tile + // is first destroyed at the client end of things. Packets formed like this + // are potentially sent from ServerPlayerGameMode::destroyBlock + bool destroyTilePacket = false; + if (packet->block == 255) { + packet->block = 0; + destroyTilePacket = true; + } + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle tile update"); - if( g_NetworkManager.IsHost() ) - { - // 4J Stu - Unshare before we make any changes incase the server is already another step ahead of us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - // This is quite expensive to do, so only consider unsharing if this tile setting is going to actually - // change something - int prevTile = dimensionLevel->getTile(packet->x, packet->y, packet->z); - int prevData = dimensionLevel->getData(packet->x, packet->y, packet->z); - if( packet->block != prevTile || packet->data != prevData ) - { - PIXBeginNamedEvent(0,"Chunk data unsharing\n"); - dimensionLevel->unshareChunkAt(packet->x,packet->z); - PIXEndNamedEvent(); - } - } + if (g_NetworkManager.IsHost()) { + // 4J Stu - Unshare before we make any changes incase the server is + // already another step ahead of us Fix for #7904 - Gameplay: + // Players can dupe torches by throwing them repeatedly into water. + // This is quite expensive to do, so only consider unsharing if this + // tile setting is going to actually change something + int prevTile = + dimensionLevel->getTile(packet->x, packet->y, packet->z); + int prevData = + dimensionLevel->getData(packet->x, packet->y, packet->z); + if (packet->block != prevTile || packet->data != prevData) { + PIXBeginNamedEvent(0, "Chunk data unsharing\n"); + dimensionLevel->unshareChunkAt(packet->x, packet->z); + PIXEndNamedEvent(); + } + } - // 4J - In creative mode, we don't update the tile locally then get it confirmed by the server - the first point that we know we are about to destroy a tile is here. Let - // the rendering side of thing know so we can synchronise collision with async render data upates. - if( destroyTilePacket ) - { - minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(dimensionLevel, packet->x, packet->y, packet->z); - } + // 4J - In creative mode, we don't update the tile locally then get it + // confirmed by the server - the first point that we know we are about + // to destroy a tile is here. Let the rendering side of thing know so we + // can synchronise collision with async render data upates. + if (destroyTilePacket) { + minecraft->levelRenderer->destroyedTileManager->destroyingTileAt( + dimensionLevel, packet->x, packet->y, packet->z); + } - PIXBeginNamedEvent(0,"Setting data\n"); - bool tileWasSet = dimensionLevel->doSetTileAndData(packet->x, packet->y, packet->z, packet->block, packet->data); + PIXBeginNamedEvent(0, "Setting data\n"); + bool tileWasSet = dimensionLevel->doSetTileAndData( + packet->x, packet->y, packet->z, packet->block, packet->data); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(packet->x, packet->y, packet->z, packet->x+1, packet->y+1, packet->z+1 ); + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing this + // we end up with stray tile entities kicking round, which leads to a + // bug where chests can't be properly placed again in a location after + // (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + packet->x, packet->y, packet->z, packet->x + 1, packet->y + 1, + packet->z + 1); - PIXBeginNamedEvent(0,"Sharing data\n"); - dimensionLevel->shareChunkAt(packet->x,packet->z); // 4J - added - only shares if chunks are same on server & client - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sharing data\n"); + dimensionLevel->shareChunkAt( + packet->x, packet->z); // 4J - added - only shares if chunks are + // same on server & client + PIXEndNamedEvent(); - PIXEndNamedEvent(); - } + PIXEndNamedEvent(); + } } -void ClientConnection::handleDisconnect(std::shared_ptr packet) -{ +void ClientConnection::handleDisconnect( + std::shared_ptr packet) { #ifdef __linux__ - // Linux fix: On local host connections, ignore DisconnectPacket. The singleplayer internal - // server should never disconnect itself. If we see this, it's likely stream desync reading - // garbage data as a DisconnectPacket. - if (connection && connection->getSocket() && connection->getSocket()->isLocal()) { - fprintf(stderr, "[CONN] Ignoring DisconnectPacket on local connection (reason=%d)\n", packet->reason); - return; - } + // Linux fix: On local host connections, ignore DisconnectPacket. The + // singleplayer internal server should never disconnect itself. If we see + // this, it's likely stream desync reading garbage data as a + // DisconnectPacket. + if (connection && connection->getSocket() && + connection->getSocket()->isLocal()) { + fprintf(stderr, + "[CONN] Ignoring DisconnectPacket on local connection " + "(reason=%d)\n", + packet->reason); + return; + } #endif - connection->close(DisconnectPacket::eDisconnect_Kicked); + connection->close(DisconnectPacket::eDisconnect_Kicked); done = true; - - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->connectionDisconnected( m_userIndex , packet->reason ); - app.SetDisconnectReason( packet->reason ); - app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); - //minecraft->setLevel(NULL); - //minecraft->setScreen(new DisconnectedScreen(L"disconnect.disconnected", L"disconnect.genericReason", &packet->reason)); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->connectionDisconnected(m_userIndex, packet->reason); + app.SetDisconnectReason(packet->reason); + app.SetAction(m_userIndex, eAppAction_ExitWorld, (void*)TRUE); + // minecraft->setLevel(NULL); + // minecraft->setScreen(new DisconnectedScreen(L"disconnect.disconnected", + // L"disconnect.genericReason", &packet->reason)); } -void ClientConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ +void ClientConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { if (done) return; done = true; - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->connectionDisconnected( m_userIndex , reason ); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->connectionDisconnected(m_userIndex, reason); - // 4J Stu - TU-1 hotfix - // Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - // In the (now unlikely) event that the host connections times out, allow the player to save their game - if(g_NetworkManager.IsHost() && - (reason == DisconnectPacket::eDisconnect_TimeOut || reason == DisconnectPacket::eDisconnect_Overflow) && - m_userIndex == ProfileManager.GetPrimaryPad() && - !MinecraftServer::saveOnExitAnswered() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, ProfileManager.GetPrimaryPad(),&ClientConnection::HostDisconnectReturned,NULL, app.GetStringTable()); - } - else - { - app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); - } + // 4J Stu - TU-1 hotfix + // Fix for #13191 - The host of a game can get a message informing them that + // the connection to the server has been lost In the (now unlikely) event + // that the host connections times out, allow the player to save their game + if (g_NetworkManager.IsHost() && + (reason == DisconnectPacket::eDisconnect_TimeOut || + reason == DisconnectPacket::eDisconnect_Overflow) && + m_userIndex == ProfileManager.GetPrimaryPad() && + !MinecraftServer::saveOnExitAnswered()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, + ProfileManager.GetPrimaryPad(), + &ClientConnection::HostDisconnectReturned, NULL, + app.GetStringTable()); + } else { + app.SetAction(m_userIndex, eAppAction_ExitWorld, (void*)TRUE); + } - //minecraft->setLevel(NULL); - //minecraft->setScreen(new DisconnectedScreen(L"disconnect.lost", reason, reasonObjects)); + // minecraft->setLevel(NULL); + // minecraft->setScreen(new DisconnectedScreen(L"disconnect.lost", reason, + // reasonObjects)); } -void ClientConnection::sendAndDisconnect(std::shared_ptr packet) -{ +void ClientConnection::sendAndDisconnect(std::shared_ptr packet) { if (done) return; connection->send(packet); connection->sendAndQuit(); } -void ClientConnection::send(std::shared_ptr packet) -{ +void ClientConnection::send(std::shared_ptr packet) { if (done) return; connection->send(packet); } -void ClientConnection::handleTakeItemEntity(std::shared_ptr packet) -{ +void ClientConnection::handleTakeItemEntity( + std::shared_ptr packet) { std::shared_ptr from = getEntity(packet->itemId); - std::shared_ptr to = std::dynamic_pointer_cast(getEntity(packet->playerId)); + std::shared_ptr to = + std::dynamic_pointer_cast(getEntity(packet->playerId)); - // 4J - the original game could assume that if getEntity didn't find the player, it must be the local player. We - // need to search all local players - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->playerId ) - { - isLocalPlayer = true; - to = minecraft->localplayers[i]; - break; - } - } - } + // 4J - the original game could assume that if getEntity didn't find the + // player, it must be the local player. We need to search all local players + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->playerId) { + isLocalPlayer = true; + to = minecraft->localplayers[i]; + break; + } + } + } - if (to == NULL) - { - // Don't know if this should ever really happen, but seems safest to try and remove the entity that has been collected even if we can't - // create a particle as we don't know what really collected it - level->removeEntity(packet->itemId); + if (to == NULL) { + // Don't know if this should ever really happen, but seems safest to try + // and remove the entity that has been collected even if we can't create + // a particle as we don't know what really collected it + level->removeEntity(packet->itemId); return; } - if (from != NULL) - { - // If this is a local player, then we only want to do processing for it if this connection is associated with the player it is for. In - // particular, we don't want to remove the item entity until we are processing it for the right connection, or else we won't have a valid - // "from" reference if we've already removed the item for an earlier processed connection - if( isLocalPlayer ) - { - std::shared_ptr player = std::dynamic_pointer_cast(to); + if (from != NULL) { + // If this is a local player, then we only want to do processing for it + // if this connection is associated with the player it is for. In + // particular, we don't want to remove the item entity until we are + // processing it for the right connection, or else we won't have a valid + // "from" reference if we've already removed the item for an earlier + // processed connection + if (isLocalPlayer) { + std::shared_ptr player = + std::dynamic_pointer_cast(to); - // 4J Stu - Fix for #10213 - UI: Local clients cannot progress through the tutorial normally. - // We only send this packet once if many local players can see the event, so make sure we update - // the tutorial for the player that actually picked up the item - int playerPad = player->GetXboxPad(); + // 4J Stu - Fix for #10213 - UI: Local clients cannot progress + // through the tutorial normally. We only send this packet once if + // many local players can see the event, so make sure we update the + // tutorial for the player that actually picked up the item + int playerPad = player->GetXboxPad(); - if( minecraft->localgameModes[playerPad] != NULL ) - { - // 4J-PB - add in the XP orb sound - if(from->GetType() == eTYPE_EXPERIENCEORB) - { - float fPitch=((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f; - app.DebugPrintf("XP Orb with pitch %f\n",fPitch); - level->playSound(from, eSoundType_RANDOM_ORB, 0.2f, fPitch); - } - else - { - level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - } + if (minecraft->localgameModes[playerPad] != NULL) { + // 4J-PB - add in the XP orb sound + if (from->GetType() == eTYPE_EXPERIENCEORB) { + float fPitch = + ((random->nextFloat() - random->nextFloat()) * 0.7f + + 1.0f) * + 2.0f; + app.DebugPrintf("XP Orb with pitch %f\n", fPitch); + level->playSound(from, eSoundType_RANDOM_ORB, 0.2f, fPitch); + } else { + level->playSound( + from, eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + + 1.0f) * + 2.0f); + } - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); - level->removeEntity(packet->itemId); - } - else - { - // Don't know if this should ever really happen, but seems safest to try and remove the entity that has been collected even if it - // somehow isn't an itementity - level->removeEntity(packet->itemId); - } - } - else - { - level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); - level->removeEntity(packet->itemId); - } + minecraft->particleEngine->add( + std::shared_ptr( + new TakeAnimationParticle(minecraft->level, from, to, + -0.5f))); + level->removeEntity(packet->itemId); + } else { + // Don't know if this should ever really happen, but seems + // safest to try and remove the entity that has been collected + // even if it somehow isn't an itementity + level->removeEntity(packet->itemId); + } + } else { + level->playSound( + from, eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * + 2.0f); + minecraft->particleEngine->add( + std::shared_ptr( + new TakeAnimationParticle(minecraft->level, from, to, + -0.5f))); + level->removeEntity(packet->itemId); + } + } +} + +void ClientConnection::handleChat(std::shared_ptr packet) { + std::wstring message; + int iPos; + bool displayOnGui = true; + + std::wstring playerDisplayName = L""; + std::wstring sourceDisplayName = L""; + + // On platforms other than Xbox One this just sets display name to gamertag + if (packet->m_stringArgs.size() >= 1) + playerDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[0]); + if (packet->m_stringArgs.size() >= 2) + sourceDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[1]); + + switch (packet->m_messageType) { + case ChatPacket::e_ChatBedOccupied: + message = app.GetString(IDS_TILE_BED_OCCUPIED); + break; + case ChatPacket::e_ChatBedNoSleep: + message = app.GetString(IDS_TILE_BED_NO_SLEEP); + break; + case ChatPacket::e_ChatBedNotValid: + message = app.GetString(IDS_TILE_BED_NOT_VALID); + break; + case ChatPacket::e_ChatBedNotSafe: + message = app.GetString(IDS_TILE_BED_NOTSAFE); + break; + case ChatPacket::e_ChatBedPlayerSleep: + message = app.GetString(IDS_TILE_BED_PLAYERSLEEP); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatBedMeSleep: + message = app.GetString(IDS_TILE_BED_MESLEEP); + break; + case ChatPacket::e_ChatPlayerJoinedGame: + message = app.GetString(IDS_PLAYER_JOINED); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerLeftGame: + message = app.GetString(IDS_PLAYER_LEFT); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerKickedFromGame: + message = app.GetString(IDS_PLAYER_KICKED); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatCannotPlaceLava: + displayOnGui = false; + app.SetGlobalXuiAction(eAppAction_DisplayLavaMessage); + break; + case ChatPacket::e_ChatDeathInFire: + message = app.GetString(IDS_DEATH_INFIRE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathOnFire: + message = app.GetString(IDS_DEATH_ONFIRE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathLava: + message = app.GetString(IDS_DEATH_LAVA); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathInWall: + message = app.GetString(IDS_DEATH_INWALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathDrown: + message = app.GetString(IDS_DEATH_DROWN); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathStarve: + message = app.GetString(IDS_DEATH_STARVE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathCactus: + message = app.GetString(IDS_DEATH_CACTUS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathFall: + message = app.GetString(IDS_DEATH_FALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathOutOfWorld: + message = app.GetString(IDS_DEATH_OUTOFWORLD); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathGeneric: + message = app.GetString(IDS_DEATH_GENERIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathExplosion: + message = app.GetString(IDS_DEATH_EXPLOSION); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathMagic: + message = app.GetString(IDS_DEATH_MAGIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathAnvil: + message = app.GetString(IDS_DEATH_FALLING_ANVIL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathFallingBlock: + message = app.GetString(IDS_DEATH_FALLING_TILE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathDragonBreath: + message = app.GetString(IDS_DEATH_DRAGON_BREATH); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathMob: + message = app.GetString(IDS_DEATH_MOB); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + break; + case ChatPacket::e_ChatDeathPlayer: + message = app.GetString(IDS_DEATH_PLAYER); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + break; + case ChatPacket::e_ChatDeathArrow: + message = app.GetString(IDS_DEATH_ARROW); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathFireball: + message = app.GetString(IDS_DEATH_FIREBALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = + replaceAll(message, L"{*SOURCE*}", packet->m_stringArgs[1]); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathThrown: + message = app.GetString(IDS_DEATH_THROWN); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathIndirectMagic: + message = app.GetString(IDS_DEATH_INDIRECT_MAGIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathThorns: + message = app.GetString(IDS_DEATH_THORNS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatPlayerEnteredEnd: + message = app.GetString(IDS_PLAYER_ENTERED_END); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerLeftEnd: + message = app.GetString(IDS_PLAYER_LEFT_END); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + + case ChatPacket::e_ChatPlayerMaxEnemies: + message = app.GetString(IDS_MAX_ENEMIES_SPAWNED); + break; + // Spawn eggs + case ChatPacket::e_ChatPlayerMaxVillagers: + message = app.GetString(IDS_MAX_VILLAGERS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxPigsSheepCows: + message = app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxChickens: + message = app.GetString(IDS_MAX_CHICKENS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxSquid: + message = app.GetString(IDS_MAX_SQUID_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxMooshrooms: + message = app.GetString(IDS_MAX_MOOSHROOMS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxWolves: + message = app.GetString(IDS_MAX_WOLVES_SPAWNED); + break; + + // Breeding + case ChatPacket::e_ChatPlayerMaxBredPigsSheepCows: + message = app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED); + break; + case ChatPacket::e_ChatPlayerMaxBredChickens: + message = app.GetString(IDS_MAX_CHICKENS_BRED); + break; + case ChatPacket::e_ChatPlayerMaxBredMooshrooms: + message = app.GetString(IDS_MAX_MUSHROOMCOWS_BRED); + break; + + case ChatPacket::e_ChatPlayerMaxBredWolves: + message = app.GetString(IDS_MAX_WOLVES_BRED); + break; + + // can't shear the mooshroom + case ChatPacket::e_ChatPlayerCantShearMooshroom: + message = app.GetString(IDS_CANT_SHEAR_MOOSHROOM); + break; + + // Paintings/Item Frames + case ChatPacket::e_ChatPlayerMaxHangingEntities: + message = app.GetString(IDS_MAX_HANGINGENTITIES); + break; + // Enemy spawn eggs in peaceful + case ChatPacket::e_ChatPlayerCantSpawnInPeaceful: + message = app.GetString(IDS_CANT_SPAWN_IN_PEACEFUL); + break; + + // Enemy spawn eggs in peaceful + case ChatPacket::e_ChatPlayerMaxBoats: + message = app.GetString(IDS_MAX_BOATS); + break; + + case ChatPacket::e_ChatCommandTeleportSuccess: + message = app.GetString(IDS_COMMAND_TELEPORT_SUCCESS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*DESTINATION*}", + packet->m_stringArgs[1]); + } else { + message = replaceAll( + message, L"{*DESTINATION*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatCommandTeleportMe: + message = app.GetString(IDS_COMMAND_TELEPORT_ME); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatCommandTeleportToMe: + message = app.GetString(IDS_COMMAND_TELEPORT_TO_ME); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + + default: + message = playerDisplayName; + break; } + // flag that a message is a death message + bool bIsDeathMessage = + (packet->m_messageType >= ChatPacket::e_ChatDeathInFire) && + (packet->m_messageType <= ChatPacket::e_ChatDeathDragonBreath); + + if (displayOnGui) + minecraft->gui->addMessage(message, m_userIndex, bIsDeathMessage); } -void ClientConnection::handleChat(std::shared_ptr packet) -{ - std::wstring message; - int iPos; - bool displayOnGui = true; - - std::wstring playerDisplayName = L""; - std::wstring sourceDisplayName = L""; - - // On platforms other than Xbox One this just sets display name to gamertag - if (packet->m_stringArgs.size() >= 1) playerDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[0]); - if (packet->m_stringArgs.size() >= 2) sourceDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[1]); - - switch(packet->m_messageType) - { - case ChatPacket::e_ChatBedOccupied: - message = app.GetString(IDS_TILE_BED_OCCUPIED); - break; - case ChatPacket::e_ChatBedNoSleep: - message = app.GetString(IDS_TILE_BED_NO_SLEEP); - break; - case ChatPacket::e_ChatBedNotValid: - message = app.GetString(IDS_TILE_BED_NOT_VALID); - break; - case ChatPacket::e_ChatBedNotSafe: - message = app.GetString(IDS_TILE_BED_NOTSAFE); - break; - case ChatPacket::e_ChatBedPlayerSleep: - message=app.GetString(IDS_TILE_BED_PLAYERSLEEP); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatBedMeSleep: - message=app.GetString(IDS_TILE_BED_MESLEEP); - break; - case ChatPacket::e_ChatPlayerJoinedGame: - message=app.GetString(IDS_PLAYER_JOINED); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerLeftGame: - message=app.GetString(IDS_PLAYER_LEFT); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerKickedFromGame: - message=app.GetString(IDS_PLAYER_KICKED); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatCannotPlaceLava: - displayOnGui = false; - app.SetGlobalXuiAction(eAppAction_DisplayLavaMessage); - break; - case ChatPacket::e_ChatDeathInFire: - message=app.GetString(IDS_DEATH_INFIRE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathOnFire: - message=app.GetString(IDS_DEATH_ONFIRE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathLava: - message=app.GetString(IDS_DEATH_LAVA); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathInWall: - message=app.GetString(IDS_DEATH_INWALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathDrown: - message=app.GetString(IDS_DEATH_DROWN); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathStarve: - message=app.GetString(IDS_DEATH_STARVE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathCactus: - message=app.GetString(IDS_DEATH_CACTUS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathFall: - message=app.GetString(IDS_DEATH_FALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathOutOfWorld: - message=app.GetString(IDS_DEATH_OUTOFWORLD); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathGeneric: - message=app.GetString(IDS_DEATH_GENERIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathExplosion: - message=app.GetString(IDS_DEATH_EXPLOSION); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathMagic: - message=app.GetString(IDS_DEATH_MAGIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathAnvil: - message=app.GetString(IDS_DEATH_FALLING_ANVIL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathFallingBlock: - message=app.GetString(IDS_DEATH_FALLING_TILE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathDragonBreath: - message=app.GetString(IDS_DEATH_DRAGON_BREATH); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathMob: - message=app.GetString(IDS_DEATH_MOB); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - break; - case ChatPacket::e_ChatDeathPlayer: - message=app.GetString(IDS_DEATH_PLAYER); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - break; - case ChatPacket::e_ChatDeathArrow: - message=app.GetString(IDS_DEATH_ARROW); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathFireball: - message=app.GetString(IDS_DEATH_FIREBALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",packet->m_stringArgs[1]); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathThrown: - message=app.GetString(IDS_DEATH_THROWN); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathIndirectMagic: - message=app.GetString(IDS_DEATH_INDIRECT_MAGIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathThorns: - message=app.GetString(IDS_DEATH_THORNS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatPlayerEnteredEnd: - message=app.GetString(IDS_PLAYER_ENTERED_END); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerLeftEnd: - message=app.GetString(IDS_PLAYER_LEFT_END); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - - case ChatPacket::e_ChatPlayerMaxEnemies: - message=app.GetString(IDS_MAX_ENEMIES_SPAWNED); - break; - // Spawn eggs - case ChatPacket::e_ChatPlayerMaxVillagers: - message=app.GetString(IDS_MAX_VILLAGERS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxPigsSheepCows: - message=app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxChickens: - message=app.GetString(IDS_MAX_CHICKENS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxSquid: - message=app.GetString(IDS_MAX_SQUID_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxMooshrooms: - message=app.GetString(IDS_MAX_MOOSHROOMS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxWolves: - message=app.GetString(IDS_MAX_WOLVES_SPAWNED); - break; - - // Breeding - case ChatPacket::e_ChatPlayerMaxBredPigsSheepCows: - message=app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED); - break; - case ChatPacket::e_ChatPlayerMaxBredChickens: - message=app.GetString(IDS_MAX_CHICKENS_BRED); - break; - case ChatPacket::e_ChatPlayerMaxBredMooshrooms: - message=app.GetString(IDS_MAX_MUSHROOMCOWS_BRED); - break; - - case ChatPacket::e_ChatPlayerMaxBredWolves: - message=app.GetString(IDS_MAX_WOLVES_BRED); - break; - - // can't shear the mooshroom - case ChatPacket::e_ChatPlayerCantShearMooshroom: - message=app.GetString(IDS_CANT_SHEAR_MOOSHROOM); - break; - - // Paintings/Item Frames - case ChatPacket::e_ChatPlayerMaxHangingEntities: - message=app.GetString(IDS_MAX_HANGINGENTITIES); - break; - // Enemy spawn eggs in peaceful - case ChatPacket::e_ChatPlayerCantSpawnInPeaceful: - message=app.GetString(IDS_CANT_SPAWN_IN_PEACEFUL); - break; - - // Enemy spawn eggs in peaceful - case ChatPacket::e_ChatPlayerMaxBoats: - message=app.GetString(IDS_MAX_BOATS); - break; - - case ChatPacket::e_ChatCommandTeleportSuccess: - message=app.GetString(IDS_COMMAND_TELEPORT_SUCCESS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*DESTINATION*}",packet->m_stringArgs[1]); - } - else - { - message = replaceAll(message,L"{*DESTINATION*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatCommandTeleportMe: - message=app.GetString(IDS_COMMAND_TELEPORT_ME); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatCommandTeleportToMe: - message=app.GetString(IDS_COMMAND_TELEPORT_TO_ME); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - - default: - message = playerDisplayName; - break; - } - - // flag that a message is a death message - bool bIsDeathMessage = (packet->m_messageType>=ChatPacket::e_ChatDeathInFire) && (packet->m_messageType<=ChatPacket::e_ChatDeathDragonBreath); - - if( displayOnGui ) minecraft->gui->addMessage(message,m_userIndex, bIsDeathMessage); -} - -void ClientConnection::handleAnimate(std::shared_ptr packet) -{ +void ClientConnection::handleAnimate(std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - if (packet->action == AnimatePacket::SWING) - { + if (packet->action == AnimatePacket::SWING) { std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL) player->swing(); - } - else if (packet->action == AnimatePacket::HURT) - { + if (player != NULL) player->swing(); + } else if (packet->action == AnimatePacket::HURT) { e->animateHurt(); - } - else if (packet->action == AnimatePacket::WAKE_UP) - { + } else if (packet->action == AnimatePacket::WAKE_UP) { std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL) player->stopSleepInBed(false, false, false); + if (player != NULL) player->stopSleepInBed(false, false, false); + } else if (packet->action == AnimatePacket::RESPAWN) { + } else if (packet->action == AnimatePacket::CRITICAL_HIT) { + std::shared_ptr critParticle = + std::shared_ptr( + new CritParticle(minecraft->level, e)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); + } else if (packet->action == AnimatePacket::MAGIC_CRITICAL_HIT) { + std::shared_ptr critParticle = + std::shared_ptr( + new CritParticle(minecraft->level, e, eParticleType_magicCrit)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); + } else if (packet->action == AnimatePacket::EAT && + std::dynamic_pointer_cast(e) != NULL) { } - else if (packet->action == AnimatePacket::RESPAWN) - { - } - else if (packet->action == AnimatePacket::CRITICAL_HIT) - { - std::shared_ptr critParticle = std::shared_ptr( new CritParticle(minecraft->level, e) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add( critParticle ); - } - else if (packet->action == AnimatePacket::MAGIC_CRITICAL_HIT) - { - std::shared_ptr critParticle = std::shared_ptr( new CritParticle(minecraft->level, e, eParticleType_magicCrit) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); - } - else if (packet->action == AnimatePacket::EAT && std::dynamic_pointer_cast(e) != NULL) - { - } - } -void ClientConnection::handleEntityActionAtPosition(std::shared_ptr packet) -{ +void ClientConnection::handleEntityActionAtPosition( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - if (packet->action == EntityActionAtPositionPacket::START_SLEEP) - { + if (packet->action == EntityActionAtPositionPacket::START_SLEEP) { std::shared_ptr player = std::dynamic_pointer_cast(e); player->startSleepInBed(packet->x, packet->y, packet->z); - if( player == minecraft->localplayers[m_userIndex] ) - { - TelemetryManager->RecordEnemyKilledOrOvercome(m_userIndex, 0, player->y, 0, 0, 0, 0, eTelemetryInGame_UseBed); - } + if (player == minecraft->localplayers[m_userIndex]) { + TelemetryManager->RecordEnemyKilledOrOvercome( + m_userIndex, 0, player->y, 0, 0, 0, 0, eTelemetryInGame_UseBed); + } } } -void ClientConnection::handlePreLogin(std::shared_ptr packet) -{ - fprintf(stderr, "[LOGIN-CLI] handlePreLogin entered, isHost=%d, userIdx=%d\n", (int)g_NetworkManager.IsHost(), m_userIndex); +void ClientConnection::handlePreLogin(std::shared_ptr packet) { + fprintf(stderr, + "[LOGIN-CLI] handlePreLogin entered, isHost=%d, userIdx=%d\n", + (int)g_NetworkManager.IsHost(), m_userIndex); #if 1 - // 4J - Check that we can play with all the players already in the game who have Friends-Only UGC set - bool canPlay = true; - bool canPlayLocal = true; - bool isAtLeastOneFriend = g_NetworkManager.IsHost(); - bool isFriendsWithHost = true; - bool cantPlayContentRestricted = false; - - if(!g_NetworkManager.IsHost()) - { - // set the game host settings - app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings); + // 4J - Check that we can play with all the players already in the game who + // have Friends-Only UGC set + bool canPlay = true; + bool canPlayLocal = true; + bool isAtLeastOneFriend = g_NetworkManager.IsHost(); + bool isFriendsWithHost = true; + bool cantPlayContentRestricted = false; - // 4J-PB - if we go straight in from the menus via an invite, we won't have the DLC info - if(app.GetTMSGlobalFileListRead()==false) - { - app.SetTMSAction(ProfileManager.GetPrimaryPad(),eTMSAction_TMSPP_RetrieveFiles_RunPlayGame); - } - } + if (!g_NetworkManager.IsHost()) { + // set the game host settings + app.SetGameHostOption(eGameHostOption_All, packet->m_serverSettings); + + // 4J-PB - if we go straight in from the menus via an invite, we won't + // have the DLC info + if (app.GetTMSGlobalFileListRead() == false) { + app.SetTMSAction(ProfileManager.GetPrimaryPad(), + eTMSAction_TMSPP_RetrieveFiles_RunPlayGame); + } + } #ifdef _XBOX - if(!g_NetworkManager.IsHost() && !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(ProfileManager.IsSignedIn(m_userIndex) && ProfileManager.IsGuest(idx)) - { - canPlay = false; - isFriendsWithHost = false; - } - else - { - PlayerUID playerXuid = INVALID_XUID; - if( ProfileManager.IsSignedInLive(idx) ) - { - ProfileManager.GetXUID(idx,&playerXuid,true); - } - if( playerXuid != INVALID_XUID ) - { - // Is this user friends with the host player? - int result = 0; - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); - if(error == ERROR_SUCCESS && result == 0) - { - canPlay = false; - isFriendsWithHost = false; - } - } - } - if(!canPlay) break; - } - } - else - { - if(ProfileManager.IsSignedIn(m_userIndex) && ProfileManager.IsGuest(m_userIndex)) - { - canPlay = false; - isFriendsWithHost = false; - } - else - { - PlayerUID playerXuid = INVALID_XUID; - if( ProfileManager.IsSignedInLive(m_userIndex) ) - { - ProfileManager.GetXUID(m_userIndex,&playerXuid,true); - } - if( playerXuid != INVALID_XUID ) - { - // Is this user friends with the host player? - int result = 0; - const unsigned int error = XUserAreUsersFriends(m_userIndex,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); - if(error == ERROR_SUCCESS && result == 0) - { - canPlay = false; - isFriendsWithHost = false; - } - } - } - } - } + if (!g_NetworkManager.IsHost() && + !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (ProfileManager.IsSignedIn(m_userIndex) && + ProfileManager.IsGuest(idx)) { + canPlay = false; + isFriendsWithHost = false; + } else { + PlayerUID playerXuid = INVALID_XUID; + if (ProfileManager.IsSignedInLive(idx)) { + ProfileManager.GetXUID(idx, &playerXuid, true); + } + if (playerXuid != INVALID_XUID) { + // Is this user friends with the host player? + int result = 0; + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[packet->m_hostIndex], 1, + &result, NULL); + if (error == ERROR_SUCCESS && result == 0) { + canPlay = false; + isFriendsWithHost = false; + } + } + } + if (!canPlay) break; + } + } else { + if (ProfileManager.IsSignedIn(m_userIndex) && + ProfileManager.IsGuest(m_userIndex)) { + canPlay = false; + isFriendsWithHost = false; + } else { + PlayerUID playerXuid = INVALID_XUID; + if (ProfileManager.IsSignedInLive(m_userIndex)) { + ProfileManager.GetXUID(m_userIndex, &playerXuid, true); + } + if (playerXuid != INVALID_XUID) { + // Is this user friends with the host player? + int result = 0; + const unsigned int error = XUserAreUsersFriends( + m_userIndex, + &packet->m_playerXuids[packet->m_hostIndex], 1, &result, + NULL); + if (error == ERROR_SUCCESS && result == 0) { + canPlay = false; + isFriendsWithHost = false; + } + } + } + } + } - if( canPlay ) - { - for(std::uint8_t i = 0; i < packet->m_dwPlayerCount; ++i) - { - bool localPlayer = false; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( ProfileManager.IsSignedInLive(idx) ) - { - // need to use the XUID here - PlayerUID playerXUID = INVALID_XUID; - if( !ProfileManager.IsGuest( idx ) ) - { - // Guest don't have an offline XUID as they cannot play offline, so use their online one - ProfileManager.GetXUID(idx,&playerXUID,true); - } - if( ProfileManager.AreXUIDSEqual(playerXUID,packet->m_playerXuids[i]) ) localPlayer = true; - } - else if (ProfileManager.IsSignedIn(idx)) - { - // If we aren't signed into live then they have to be a local player - localPlayer = true; - } - } - if(!localPlayer) - { - // First check our own permissions to see if we can play with this player - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - canPlayLocal = ProfileManager.CanViewPlayerCreatedContent(m_userIndex,false,&packet->m_playerXuids[i],1); + if (canPlay) { + for (std::uint8_t i = 0; i < packet->m_dwPlayerCount; ++i) { + bool localPlayer = false; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (ProfileManager.IsSignedInLive(idx)) { + // need to use the XUID here + PlayerUID playerXUID = INVALID_XUID; + if (!ProfileManager.IsGuest(idx)) { + // Guest don't have an offline XUID as they cannot play + // offline, so use their online one + ProfileManager.GetXUID(idx, &playerXUID, true); + } + if (ProfileManager.AreXUIDSEqual(playerXUID, + packet->m_playerXuids[i])) + localPlayer = true; + } else if (ProfileManager.IsSignedIn(idx)) { + // If we aren't signed into live then they have to be a + // local player + localPlayer = true; + } + } + if (!localPlayer) { + // First check our own permissions to see if we can play with + // this player + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + canPlayLocal = ProfileManager.CanViewPlayerCreatedContent( + m_userIndex, false, &packet->m_playerXuids[i], 1); - // 4J Stu - Everyone joining needs to have at least one friend in the game - // Local players are implied friends - if(!isAtLeastOneFriend) - { - int result = 0; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) - { - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); - if(error == ERROR_SUCCESS && result != 0) isAtLeastOneFriend = true; - } - } - } - } - else - { - // Friends with the primary player on this system - isAtLeastOneFriend = true; + // 4J Stu - Everyone joining needs to have at least one + // friend in the game Local players are implied friends + if (!isAtLeastOneFriend) { + int result = 0; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; + ++idx) { + if (ProfileManager.IsSignedIn(idx) && + !ProfileManager.IsGuest(idx)) { + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[i], 1, &result, + NULL); + if (error == ERROR_SUCCESS && result != 0) + isAtLeastOneFriend = true; + } + } + } + } else { + // Friends with the primary player on this system + isAtLeastOneFriend = true; - canPlayLocal = ProfileManager.CanViewPlayerCreatedContent(m_userIndex,true,&packet->m_playerXuids[i],1); - } + canPlayLocal = ProfileManager.CanViewPlayerCreatedContent( + m_userIndex, true, &packet->m_playerXuids[i], 1); + } - // If we can play with them, then check if they can play with us - if( canPlayLocal && ( packet->m_friendsOnlyBits & (1<m_friendsOnlyBits & (1 << i))) { + // If this is the primary pad then check all local players + // against the list in the packet (this happens when joining + // the game for the first time) If not the primary pad, then + // just check against this index. It happens on joining at + // the start, but more importantly players trying to join + // during the game + bool thisQuadrantOnly = true; + if (m_userIndex == ProfileManager.GetPrimaryPad()) + thisQuadrantOnly = false; - int result = 0; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( (!thisQuadrantOnly || m_userIndex == idx) && ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) - { - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); - if(error == ERROR_SUCCESS) canPlay &= (result != 0); - } - if(!canPlay) break; - } - } - if(!canPlay || !canPlayLocal) break; - } - } - } + int result = 0; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if ((!thisQuadrantOnly || m_userIndex == idx) && + ProfileManager.IsSignedIn(idx) && + !ProfileManager.IsGuest(idx)) { + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[i], 1, &result, + NULL); + if (error == ERROR_SUCCESS) + canPlay &= (result != 0); + } + if (!canPlay) break; + } + } + if (!canPlay || !canPlayLocal) break; + } + } + } #else - // TODO - handle this kind of things for non-360 platforms - canPlay = true; - canPlayLocal = true; - isAtLeastOneFriend = true; - cantPlayContentRestricted= false; + // TODO - handle this kind of things for non-360 platforms + canPlay = true; + canPlayLocal = true; + isAtLeastOneFriend = true; + cantPlayContentRestricted = false; -#if ( defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) - if(!g_NetworkManager.IsHost() && !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - bool bChatRestricted=false; + if (!g_NetworkManager.IsHost() && + !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + bool bChatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, true, &bChatRestricted, NULL, NULL); - // Chat restricted orbis players can still play online + // Chat restricted orbis players can still play online #ifndef __ORBIS__ - canPlay = !bChatRestricted; + canPlay = !bChatRestricted; #endif - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - // Is this user friends with the host player? - bool isFriend = true; - unsigned int friendCount = 0; + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + // Is this user friends with the host player? + bool isFriend = true; + unsigned int friendCount = 0; #ifdef __PS3__ - int ret = sceNpBasicGetFriendListEntryCount(&friendCount); + int ret = sceNpBasicGetFriendListEntryCount(&friendCount); #elif defined __PSVITA__ - sce::Toolkit::NP::Utilities::Future friendList; - int ret = -1; - if(!CGameNetworkManager::usingAdhocMode()) // we don't need to be friends in PSN for adhoc mode - { - int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, false); - if(ret == SCE_TOOLKIT_NP_SUCCESS) - { - if( friendList.hasResult() ) - { - friendCount = friendList.get()->size(); - } - } - } -#else // __ORBIS__ + sce::Toolkit::NP::Utilities::Future + friendList; + int ret = -1; + if (!CGameNetworkManager::usingAdhocMode()) // we don't need to be + // friends in PSN for + // adhoc mode + { + int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist( + &friendList, false); + if (ret == SCE_TOOLKIT_NP_SUCCESS) { + if (friendList.hasResult()) { + friendCount = friendList.get()->size(); + } + } + } +#else // __ORBIS__ - sce::Toolkit::NP::Utilities::Future friendList; + sce::Toolkit::NP::Utilities::Future + friendList; - sce::Toolkit::NP::FriendInfoRequest requestParam; - memset(&requestParam,0,sizeof(requestParam)); - requestParam.flag = SCE_TOOLKIT_NP_FRIENDS_LIST_ALL; - requestParam.limit = 0; - requestParam.offset = 0; - requestParam.userInfo.userId = ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); + sce::Toolkit::NP::FriendInfoRequest requestParam; + memset(&requestParam, 0, sizeof(requestParam)); + requestParam.flag = SCE_TOOLKIT_NP_FRIENDS_LIST_ALL; + requestParam.limit = 0; + requestParam.offset = 0; + requestParam.userInfo.userId = + ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); - int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, &requestParam, false); - if( ret == 0 ) - { - if( friendList.hasResult() ) - { - friendCount = friendList.get()->size(); - } - } + int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist( + &friendList, &requestParam, false); + if (ret == 0) { + if (friendList.hasResult()) { + friendCount = friendList.get()->size(); + } + } #endif - if( ret == 0 ) - { - isFriend = false; - SceNpId npid; - for( unsigned int i = 0; i < friendCount; i++ ) - { + if (ret == 0) { + isFriend = false; + SceNpId npid; + for (unsigned int i = 0; i < friendCount; i++) { #ifdef __PS3__ - ret = sceNpBasicGetFriendListEntry( i, &npid ); + ret = sceNpBasicGetFriendListEntry(i, &npid); #else - npid = friendList.get()->at(i).npid; + npid = friendList.get()->at(i).npid; #endif - if( ret == 0 ) - { - if(strcmp(npid.handle.data, packet->m_playerXuids[packet->m_hostIndex].getOnlineID()) == 0) - { - isFriend = true; - break; - } - } - } - } + if (ret == 0) { + if (strcmp(npid.handle.data, + packet->m_playerXuids[packet->m_hostIndex] + .getOnlineID()) == 0) { + isFriend = true; + break; + } + } + } + } - if( !isFriend ) - { - canPlay = FALSE; - isFriendsWithHost = FALSE; - } - } - } - // is it an online game, and a player has chat restricted? - else if(!g_NetworkManager.IsLocalGame()) - { - // if the player is chat restricted, then they can't play an online game - bool bChatRestricted=false; - bool bContentRestricted=false; + if (!isFriend) { + canPlay = FALSE; + isFriendsWithHost = FALSE; + } + } + } + // is it an online game, and a player has chat restricted? + else if (!g_NetworkManager.IsLocalGame()) { + // if the player is chat restricted, then they can't play an online game + bool bChatRestricted = false; + bool bContentRestricted = false; - // If this is a pre-login packet for the first player on the machine, then accumulate up these flags for everyone signed in. We can handle exiting the game - // much more cleanly at this point by exiting the level, rather than waiting for a prelogin packet for the other players, when we have to exit the player - // which seems to be very unstable at the point of starting up the game - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,false,&bChatRestricted,&bContentRestricted,NULL); - } - else - { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,&bContentRestricted,NULL); - } + // If this is a pre-login packet for the first player on the machine, + // then accumulate up these flags for everyone signed in. We can handle + // exiting the game much more cleanly at this point by exiting the + // level, rather than waiting for a prelogin packet for the other + // players, when we have to exit the player which seems to be very + // unstable at the point of starting up the game + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, false, &bChatRestricted, &bContentRestricted, + NULL); + } else { + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, true, &bChatRestricted, &bContentRestricted, NULL); + } - // Chat restricted orbis players can still play online + // Chat restricted orbis players can still play online #ifndef __ORBIS__ - canPlayLocal = !bChatRestricted; + canPlayLocal = !bChatRestricted; #endif - cantPlayContentRestricted = bContentRestricted ? 1 : 0; - } - + cantPlayContentRestricted = bContentRestricted ? 1 : 0; + } #endif #ifdef _XBOX_ONE - if(!g_NetworkManager.IsHost() && m_userIndex == ProfileManager.GetPrimaryPad()) - { - long long startTime = System::currentTimeMillis(); + if (!g_NetworkManager.IsHost() && + m_userIndex == ProfileManager.GetPrimaryPad()) { + long long startTime = System::currentTimeMillis(); - auto friendsXuids = DQRNetworkManager::GetFriends(); + auto friendsXuids = DQRNetworkManager::GetFriends(); - if (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - // Check that the user has at least one friend in the game - isAtLeastOneFriend = false; + if (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + // Check that the user has at least one friend in the game + isAtLeastOneFriend = false; - for (int i = 0; i < friendsXuids->Size; i++) - { - auto friendsXuid = friendsXuids->GetAt(i); + for (int i = 0; i < friendsXuids->Size; i++) { + auto friendsXuid = friendsXuids->GetAt(i); - // Check this friend against each player, if we find them we have at least one friend - for (int j = 0; j < g_NetworkManager.GetPlayerCount(); j++) - { - Platform::String^ xboxUserId = ref new Platform::String(g_NetworkManager.GetPlayerByIndex(j)->GetUID().toString().data()); - if (friendsXuid == xboxUserId) - { - isAtLeastOneFriend = true; - break; - } - } - } + // Check this friend against each player, if we find them we + // have at least one friend + for (int j = 0; j < g_NetworkManager.GetPlayerCount(); j++) { + Platform::String ^ xboxUserId = ref new Platform::String( + g_NetworkManager.GetPlayerByIndex(j) + ->GetUID() + .toString() + .data()); + if (friendsXuid == xboxUserId) { + isAtLeastOneFriend = true; + break; + } + } + } - app.DebugPrintf("ClientConnection::handlePreLogin: User has at least one friend? %s\n", isAtLeastOneFriend ? "Yes" : "No"); - } - else - { - // Check that the user is friends with the host - bool isFriend = false; + app.DebugPrintf( + "ClientConnection::handlePreLogin: User has at least one " + "friend? %s\n", + isAtLeastOneFriend ? "Yes" : "No"); + } else { + // Check that the user is friends with the host + bool isFriend = false; - Platform::String^ hostXboxUserId = ref new Platform::String(g_NetworkManager.GetHostPlayer()->GetUID().toString().data()); + Platform::String ^ hostXboxUserId = ref new Platform::String( + g_NetworkManager.GetHostPlayer()->GetUID().toString().data()); - for (int i = 0; i < friendsXuids->Size; i++) - { - if (friendsXuids->GetAt(i) == hostXboxUserId) - { - isFriend = true; - break; - } - } + for (int i = 0; i < friendsXuids->Size; i++) { + if (friendsXuids->GetAt(i) == hostXboxUserId) { + isFriend = true; + break; + } + } - if( !isFriend ) - { - canPlay = FALSE; - isFriendsWithHost = FALSE; - } + if (!isFriend) { + canPlay = FALSE; + isFriendsWithHost = FALSE; + } - app.DebugPrintf("ClientConnection::handlePreLogin: User is friends with the host? %s\n", isFriendsWithHost ? "Yes" : "No"); - } + app.DebugPrintf( + "ClientConnection::handlePreLogin: User is friends with the " + "host? %s\n", + isFriendsWithHost ? "Yes" : "No"); + } - app.DebugPrintf("ClientConnection::handlePreLogin: Friendship checks took %i ms\n", System::currentTimeMillis() - startTime); - } + app.DebugPrintf( + "ClientConnection::handlePreLogin: Friendship checks took %i ms\n", + System::currentTimeMillis() - startTime); + } #endif -#endif // _XBOX +#endif // _XBOX - if(!canPlay || !canPlayLocal || !isAtLeastOneFriend || cantPlayContentRestricted) - { + if (!canPlay || !canPlayLocal || !isAtLeastOneFriend || + cantPlayContentRestricted) { #ifndef __PS3__ - DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_NoUGC_Remote; + DisconnectPacket::eDisconnectReason reason = + DisconnectPacket::eDisconnect_NoUGC_Remote; #else - DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_None; -#endif - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; - else if(!isAtLeastOneFriend) reason = DisconnectPacket::eDisconnect_NoFriendsInGame; - else if(!canPlayLocal) reason = DisconnectPacket::eDisconnect_NoUGC_AllLocal; - else if(cantPlayContentRestricted) reason = DisconnectPacket::eDisconnect_ContentRestricted_AllLocal; + DisconnectPacket::eDisconnectReason reason = + DisconnectPacket::eDisconnect_None; +#endif + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + if (!isFriendsWithHost) + reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; + else if (!isAtLeastOneFriend) + reason = DisconnectPacket::eDisconnect_NoFriendsInGame; + else if (!canPlayLocal) + reason = DisconnectPacket::eDisconnect_NoUGC_AllLocal; + else if (cantPlayContentRestricted) + reason = + DisconnectPacket::eDisconnect_ContentRestricted_AllLocal; - app.DebugPrintf("Exiting world on handling Pre-Login packet due UGC privileges: %d\n", reason); - app.SetDisconnectReason( reason ); - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); - } - else - { - if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; - else if(!canPlayLocal) reason = DisconnectPacket::eDisconnect_NoUGC_Single_Local; - else if(cantPlayContentRestricted) reason = DisconnectPacket::eDisconnect_ContentRestricted_Single_Local; + app.DebugPrintf( + "Exiting world on handling Pre-Login packet due UGC " + "privileges: %d\n", + reason); + app.SetDisconnectReason(reason); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ExitWorld, + (void*)TRUE); + } else { + if (!isFriendsWithHost) + reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; + else if (!canPlayLocal) + reason = DisconnectPacket::eDisconnect_NoUGC_Single_Local; + else if (cantPlayContentRestricted) + reason = DisconnectPacket:: + eDisconnect_ContentRestricted_Single_Local; - app.DebugPrintf("Exiting player %d on handling Pre-Login packet due UGC privileges: %d\n", m_userIndex, reason); - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - if(!isFriendsWithHost) ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NOTALLOWED_FRIENDSOFFRIENDS, uiIDA,1,m_userIndex,NULL,NULL, app.GetStringTable()); - else ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL, uiIDA,1,m_userIndex,NULL,NULL, app.GetStringTable()); + app.DebugPrintf( + "Exiting player %d on handling Pre-Login packet due UGC " + "privileges: %d\n", + m_userIndex, reason); + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + if (!isFriendsWithHost) + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, IDS_NOTALLOWED_FRIENDSOFFRIENDS, uiIDA, + 1, m_userIndex, NULL, NULL, app.GetStringTable()); + else + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, + IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL, uiIDA, + 1, m_userIndex, NULL, NULL, app.GetStringTable()); - app.SetDisconnectReason( reason ); + app.SetDisconnectReason(reason); - // 4J-PB - this locks up on the read and write threads not closing down, because they are trying to lock the incoming critsec when it's already locked by this thread -// Minecraft::GetInstance()->connectionDisconnected( m_userIndex , reason ); -// done = true; -// connection->flush(); -// connection->close(reason); -// app.SetAction(m_userIndex,eAppAction_ExitPlayer); + // 4J-PB - this locks up on the read and write threads not closing + // down, because they are trying to lock the incoming critsec when + // it's already locked by this thread + // Minecraft::GetInstance()->connectionDisconnected( + // m_userIndex , reason ); done = true; connection->flush(); + // connection->close(reason); + // app.SetAction(m_userIndex,eAppAction_ExitPlayer); - // 4J-PB - doing this instead - app.SetAction(m_userIndex,eAppAction_ExitPlayerPreLogin); - } - } - else - { - // Texture pack handling - // If we have the texture pack for the game, load it - // If we don't then send a packet to the host to request it. We need to send this before the LoginPacket so that it gets handled first, - // as once the LoginPacket is received on the client the game is close to starting - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->skins->selectTexturePackById(packet->m_texturePackId) ) - { - app.DebugPrintf("Selected texture pack %d from Pre-Login packet\n", packet->m_texturePackId); - } - else - { - app.DebugPrintf("Could not select texture pack %d from Pre-Login packet, requesting from host\n", packet->m_texturePackId); + // 4J-PB - doing this instead + app.SetAction(m_userIndex, eAppAction_ExitPlayerPreLogin); + } + } else { + // Texture pack handling + // If we have the texture pack for the game, load it + // If we don't then send a packet to the host to request it. We need to + // send this before the LoginPacket so that it gets handled first, as + // once the LoginPacket is received on the client the game is close to + // starting + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->skins->selectTexturePackById( + packet->m_texturePackId)) { + app.DebugPrintf( + "Selected texture pack %d from Pre-Login packet\n", + packet->m_texturePackId); + } else { + app.DebugPrintf( + "Could not select texture pack %d from Pre-Login packet, " + "requesting from host\n", + packet->m_texturePackId); - // 4J-PB - we need to upsell the texture pack to the player - //app.SetAction(m_userIndex,eAppAction_TexturePackRequired); - // Let the player go into the game, and we'll check that they are using the right texture pack when in - } - } + // 4J-PB - we need to upsell the texture pack to the player + // app.SetAction(m_userIndex,eAppAction_TexturePackRequired); + // Let the player go into the game, and we'll check that they + // are using the right texture pack when in + } + } - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCPreLoginReceived * 100)/ (eCCConnected)); - } - // need to use the XUID here - PlayerUID offlineXUID = INVALID_XUID; - PlayerUID onlineXUID = INVALID_XUID; - if( ProfileManager.IsSignedInLive(m_userIndex) ) - { - // Guest don't have an offline XUID as they cannot play offline, so use their online one - ProfileManager.GetXUID(m_userIndex,&onlineXUID,true); - } + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCPreLoginReceived * 100) / (eCCConnected)); + } + // need to use the XUID here + PlayerUID offlineXUID = INVALID_XUID; + PlayerUID onlineXUID = INVALID_XUID; + if (ProfileManager.IsSignedInLive(m_userIndex)) { + // Guest don't have an offline XUID as they cannot play offline, so + // use their online one + ProfileManager.GetXUID(m_userIndex, &onlineXUID, true); + } #ifdef __PSVITA__ - if(CGameNetworkManager::usingAdhocMode() && onlineXUID.getOnlineID()[0] == 0) - { - // player doesn't have an online UID, set it from the player name - onlineXUID.setForAdhoc(); - } + if (CGameNetworkManager::usingAdhocMode() && + onlineXUID.getOnlineID()[0] == 0) { + // player doesn't have an online UID, set it from the player name + onlineXUID.setForAdhoc(); + } #endif - // On PS3, all non-signed in players (even guests) can get a useful offlineXUID -#if !(defined __PS3__ || defined _DURANGO ) - if( !ProfileManager.IsGuest( m_userIndex ) ) + // On PS3, all non-signed in players (even guests) can get a useful + // offlineXUID +#if !(defined __PS3__ || defined _DURANGO) + if (!ProfileManager.IsGuest(m_userIndex)) #endif - { - // All other players we use their offline XUID so that they can play the game offline - ProfileManager.GetXUID(m_userIndex,&offlineXUID,false); - } - bool allAllowed = false; - bool friendsAllowed = false; - ProfileManager.AllowedPlayerCreatedContent(m_userIndex,true,&allAllowed,&friendsAllowed); - fprintf(stderr, "[LOGIN] Sending LoginPacket: user=%ls netVer=%d userIdx=%d isHost=%d\n", - minecraft->user->name.c_str(), SharedConstants::NETWORK_PROTOCOL_VERSION, m_userIndex, (int)g_NetworkManager.IsHost()); - send( std::shared_ptr( new LoginPacket(minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, offlineXUID, onlineXUID, (!allAllowed && friendsAllowed), - packet->m_ugcPlayersVersion, app.GetPlayerSkinId(m_userIndex), app.GetPlayerCapeId(m_userIndex), ProfileManager.IsGuest( m_userIndex )))); - fprintf(stderr, "[LOGIN] LoginPacket sent successfully\n"); + { + // All other players we use their offline XUID so that they can play + // the game offline + ProfileManager.GetXUID(m_userIndex, &offlineXUID, false); + } + bool allAllowed = false; + bool friendsAllowed = false; + ProfileManager.AllowedPlayerCreatedContent( + m_userIndex, true, &allAllowed, &friendsAllowed); + fprintf(stderr, + "[LOGIN] Sending LoginPacket: user=%ls netVer=%d userIdx=%d " + "isHost=%d\n", + minecraft->user->name.c_str(), + SharedConstants::NETWORK_PROTOCOL_VERSION, m_userIndex, + (int)g_NetworkManager.IsHost()); + send(std::shared_ptr(new LoginPacket( + minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, + offlineXUID, onlineXUID, (!allAllowed && friendsAllowed), + packet->m_ugcPlayersVersion, app.GetPlayerSkinId(m_userIndex), + app.GetPlayerCapeId(m_userIndex), + ProfileManager.IsGuest(m_userIndex)))); + fprintf(stderr, "[LOGIN] LoginPacket sent successfully\n"); - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCLoginSent * 100)/ (eCCConnected)); - } - } + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCLoginSent * 100) / (eCCConnected)); + } + } #else - // 4J - removed + // 4J - removed if (packet->loginKey.equals("-")) { - send(new LoginPacket(minecraft->user.name, SharedConstants.NETWORK_PROTOCOL_VERSION)); + send(new LoginPacket(minecraft->user.name, + SharedConstants.NETWORK_PROTOCOL_VERSION)); } else { try { - URL url = new URL("http://www.minecraft->net/game/joinserver.jsp?user=" + minecraft->user.name + "&sessionId=" + minecraft->user.sessionId + "&serverId=" + packet->loginKey); - BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); + URL url = + new URL("http://www.minecraft->net/game/joinserver.jsp?user=" + + minecraft->user.name + + "&sessionId=" + minecraft->user.sessionId + + "&serverId=" + packet->loginKey); + BufferedReader br = + new BufferedReader(new InputStreamReader(url.openStream())); String msg = br.readLine(); br.close(); if (msg.equalsIgnoreCase("ok")) { - send(new LoginPacket(minecraft->user.name, SharedConstants.NETWORK_PROTOCOL_VERSION)); + send(new LoginPacket(minecraft->user.name, + SharedConstants.NETWORK_PROTOCOL_VERSION)); } else { connection.close("disconnect.loginFailedInfo", msg); } } catch (Exception e) { e.printStackTrace(); - connection.close("disconnect.genericReason", "Internal client error: " + e.toString()); + connection.close("disconnect.genericReason", + "Internal client error: " + e.toString()); } } #endif } -void ClientConnection::close() -{ - // If it's already done, then we don't need to do anything here. And in fact trying to do something could cause a crash - if(done) return; +void ClientConnection::close() { + // If it's already done, then we don't need to do anything here. And in fact + // trying to do something could cause a crash + if (done) return; done = true; connection->flush(); - connection->close(DisconnectPacket::eDisconnect_Closed); + connection->close(DisconnectPacket::eDisconnect_Closed); } -void ClientConnection::handleAddMob(std::shared_ptr packet) -{ - double x = packet->x / 32.0; - double y = packet->y / 32.0; - double z = packet->z / 32.0; - float yRot = packet->yRot * 360 / 256.0f; - float xRot = packet->xRot * 360 / 256.0f; +void ClientConnection::handleAddMob(std::shared_ptr packet) { + double x = packet->x / 32.0; + double y = packet->y / 32.0; + double z = packet->z / 32.0; + float yRot = packet->yRot * 360 / 256.0f; + float xRot = packet->xRot * 360 / 256.0f; - std::shared_ptr mob = std::dynamic_pointer_cast(EntityIO::newById(packet->type, level)); - mob->xp = packet->x; - mob->yp = packet->y; - mob->zp = packet->z; - mob->yHeadRot = packet->yHeadRot * 360 / 256.0f; - mob->yRotp = packet->yRot; - mob->xRotp = packet->xRot; + std::shared_ptr mob = + std::dynamic_pointer_cast(EntityIO::newById(packet->type, level)); + mob->xp = packet->x; + mob->yp = packet->y; + mob->zp = packet->z; + mob->yHeadRot = packet->yHeadRot * 360 / 256.0f; + mob->yRotp = packet->yRot; + mob->xRotp = packet->xRot; - std::vector > *subEntities = mob->getSubEntities(); - if (subEntities != NULL) - { - int offs = packet->id - mob->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - //subEntities[i].entityId += offs; - (*it)->entityId += offs; - } - } + std::vector >* subEntities = mob->getSubEntities(); + if (subEntities != NULL) { + int offs = packet->id - mob->entityId; + // for (int i = 0; i < subEntities.length; i++) + for (AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); + ++it) { + // subEntities[i].entityId += offs; + (*it)->entityId += offs; + } + } - mob->entityId = packet->id; + mob->entityId = packet->id; -// printf("\t\t\t\t%d: Add mob rot %d\n",packet->id,packet->yRot); + // printf("\t\t\t\t%d: Add mob rot %d\n",packet->id,packet->yRot); - mob->absMoveTo(x, y, z, yRot, xRot); - mob->xd = packet->xd / 8000.0f; - mob->yd = packet->yd / 8000.0f; - mob->zd = packet->zd / 8000.0f; - level->putEntity(packet->id, mob); + mob->absMoveTo(x, y, z, yRot, xRot); + mob->xd = packet->xd / 8000.0f; + mob->yd = packet->yd / 8000.0f; + mob->zd = packet->zd / 8000.0f; + level->putEntity(packet->id, mob); - std::vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) - { - mob->getEntityData()->assignValues(unpackedData); - } + std::vector >* unpackedData = + packet->getUnpackedData(); + if (unpackedData != NULL) { + mob->getEntityData()->assignValues(unpackedData); + } - // Fix for #65236 - TU8: Content: Gameplay: Magma Cubes' have strange hit boxes. - // 4J Stu - Slimes have a different BB depending on their size which is set in the entity data, so update the BB - if(mob->GetType() == eTYPE_SLIME || mob->GetType() == eTYPE_LAVASLIME) - { - std::shared_ptr slime = std::dynamic_pointer_cast(mob); - slime->setSize( slime->getSize() ); - } + // Fix for #65236 - TU8: Content: Gameplay: Magma Cubes' have strange hit + // boxes. 4J Stu - Slimes have a different BB depending on their size which + // is set in the entity data, so update the BB + if (mob->GetType() == eTYPE_SLIME || mob->GetType() == eTYPE_LAVASLIME) { + std::shared_ptr slime = std::dynamic_pointer_cast(mob); + slime->setSize(slime->getSize()); + } } -void ClientConnection::handleSetTime(std::shared_ptr packet) -{ - minecraft->level->setTime(packet->time); +void ClientConnection::handleSetTime(std::shared_ptr packet) { + minecraft->level->setTime(packet->time); } -void ClientConnection::handleSetSpawn(std::shared_ptr packet) -{ - //minecraft->player->setRespawnPosition(new Pos(packet->x, packet->y, packet->z)); - minecraft->localplayers[m_userIndex]->setRespawnPosition(new Pos(packet->x, packet->y, packet->z)); +void ClientConnection::handleSetSpawn( + std::shared_ptr packet) { + // minecraft->player->setRespawnPosition(new Pos(packet->x, packet->y, + // packet->z)); + minecraft->localplayers[m_userIndex]->setRespawnPosition( + new Pos(packet->x, packet->y, packet->z)); minecraft->level->getLevelData()->setSpawn(packet->x, packet->y, packet->z); - } -void ClientConnection::handleRidePacket(std::shared_ptr packet) -{ +void ClientConnection::handleRidePacket( + std::shared_ptr packet) { std::shared_ptr rider = getEntity(packet->riderId); std::shared_ptr ridden = getEntity(packet->riddenId); - std::shared_ptr boat = std::dynamic_pointer_cast(ridden); - //if (packet->riderId == minecraft->player->entityId) rider = minecraft->player; - if (packet->riderId == minecraft->localplayers[m_userIndex]->entityId) - { - rider = minecraft->localplayers[m_userIndex]; + std::shared_ptr boat = std::dynamic_pointer_cast(ridden); + // if (packet->riderId == minecraft->player->entityId) rider = + // minecraft->player; + if (packet->riderId == minecraft->localplayers[m_userIndex]->entityId) { + rider = minecraft->localplayers[m_userIndex]; - if (boat) boat->setDoLerp(false); - } - else if (boat) - { - boat->setDoLerp(true); - } + if (boat) boat->setDoLerp(false); + } else if (boat) { + boat->setDoLerp(true); + } if (rider == NULL) return; - rider->ride(ridden); + rider->ride(ridden); } -void ClientConnection::handleEntityEvent(std::shared_ptr packet) -{ +void ClientConnection::handleEntityEvent( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->entityId); if (e != NULL) e->handleEntityEvent(packet->eventId); } -std::shared_ptr ClientConnection::getEntity(int entityId) -{ - //if (entityId == minecraft->player->entityId) - if(entityId == minecraft->localplayers[m_userIndex]->entityId) - { - //return minecraft->player; - return minecraft->localplayers[m_userIndex]; - } - return level->getEntity(entityId); +std::shared_ptr ClientConnection::getEntity(int entityId) { + // if (entityId == minecraft->player->entityId) + if (entityId == minecraft->localplayers[m_userIndex]->entityId) { + // return minecraft->player; + return minecraft->localplayers[m_userIndex]; + } + return level->getEntity(entityId); } -void ClientConnection::handleSetHealth(std::shared_ptr packet) -{ - //minecraft->player->hurtTo(packet->health); - minecraft->localplayers[m_userIndex]->hurtTo(packet->health,packet->damageSource); - minecraft->localplayers[m_userIndex]->getFoodData()->setFoodLevel(packet->food); - minecraft->localplayers[m_userIndex]->getFoodData()->setSaturation(packet->saturation); +void ClientConnection::handleSetHealth( + std::shared_ptr packet) { + // minecraft->player->hurtTo(packet->health); + minecraft->localplayers[m_userIndex]->hurtTo(packet->health, + packet->damageSource); + minecraft->localplayers[m_userIndex]->getFoodData()->setFoodLevel( + packet->food); + minecraft->localplayers[m_userIndex]->getFoodData()->setSaturation( + packet->saturation); - // We need food - if(packet->food < FoodConstants::HEAL_LEVEL - 1) - { - if(minecraft->localgameModes[m_userIndex] != NULL && !minecraft->localgameModes[m_userIndex]->hasInfiniteItems() ) - { - minecraft->localgameModes[m_userIndex]->getTutorial()->changeTutorialState(e_Tutorial_State_Food_Bar); - } - } + // We need food + if (packet->food < FoodConstants::HEAL_LEVEL - 1) { + if (minecraft->localgameModes[m_userIndex] != NULL && + !minecraft->localgameModes[m_userIndex]->hasInfiniteItems()) { + minecraft->localgameModes[m_userIndex] + ->getTutorial() + ->changeTutorialState(e_Tutorial_State_Food_Bar); + } + } } -void ClientConnection::handleSetExperience(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->setExperienceValues(packet->experienceProgress, packet->totalExperience, packet->experienceLevel); +void ClientConnection::handleSetExperience( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->setExperienceValues( + packet->experienceProgress, packet->totalExperience, + packet->experienceLevel); } -void ClientConnection::handleTexture(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - // Server side also needs to store a list of those clients waiting to get a texture the server doesn't have yet - // so that it can send it out to them when it comes in +void ClientConnection::handleTexture(std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way Server side also needs to store a list of those clients waiting + // to get a texture the server doesn't have yet so that it can send it out + // to them when it comes in - if(packet->dataBytes==0) - { - // Request for texture + if (packet->dataBytes == 0) { + // Request for texture #ifndef _CONTENT_PACKAGE - wprintf(L"Client received request for custom texture %ls\n",packet->textureName.c_str()); + wprintf(L"Client received request for custom texture %ls\n", + packet->textureName.c_str()); #endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); - } - } - else - { - // Response with texture data + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(packet->textureName, pbData, dwBytes))); + } + } else { + // Response with texture data #ifndef _CONTENT_PACKAGE - wprintf(L"Client received custom texture %ls\n",packet->textureName.c_str()); + wprintf(L"Client received custom texture %ls\n", + packet->textureName.c_str()); #endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dataBytes); - Minecraft::GetInstance()->handleClientTextureReceived(packet->textureName); - } + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dataBytes); + Minecraft::GetInstance()->handleClientTextureReceived( + packet->textureName); + } } -void ClientConnection::handleTextureAndGeometry(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - // Server side also needs to store a list of those clients waiting to get a texture the server doesn't have yet - // so that it can send it out to them when it comes in +void ClientConnection::handleTextureAndGeometry( + std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way Server side also needs to store a list of those clients waiting + // to get a texture the server doesn't have yet so that it can send it out + // to them when it comes in - if(packet->dwTextureBytes==0) - { - // Request for texture + if (packet->dwTextureBytes == 0) { + // Request for texture #ifndef _CONTENT_PACKAGE - wprintf(L"Client received request for custom texture and geometry %ls\n",packet->textureName.c_str()); + wprintf( + L"Client received request for custom texture and geometry %ls\n", + packet->textureName.c_str()); #endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); + DLCSkinFile* pDLCSkinFile = + app.m_dlcManager.getSkinFile(packet->textureName); - if(dwBytes!=0) - { - if(pDLCSkinFile) - { - if(pDLCSkinFile->getAdditionalBoxesCount()!=0) - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,pDLCSkinFile) ) ); - } - else - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes) ) ); - } - } - else - { - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); + if (dwBytes != 0) { + if (pDLCSkinFile) { + if (pDLCSkinFile->getAdditionalBoxesCount() != 0) { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwBytes, + pDLCSkinFile))); + } else { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwBytes))); + } + } else { + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(packet->dwSkinID); - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,app.GetAdditionalSkinBoxes(packet->dwSkinID),uiAnimOverrideBitmask) ) ); - } - } - } - else - { - // Response with texture data + send(std::shared_ptr( + new TextureAndGeometryPacket( + packet->textureName, pbData, dwBytes, + app.GetAdditionalSkinBoxes(packet->dwSkinID), + uiAnimOverrideBitmask))); + } + } + } else { + // Response with texture data #ifndef _CONTENT_PACKAGE - wprintf(L"Client received custom TextureAndGeometry %ls\n",packet->textureName.c_str()); + wprintf(L"Client received custom TextureAndGeometry %ls\n", + packet->textureName.c_str()); #endif - // Add the texture data - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dwTextureBytes); - // Add the geometry data - if(packet->dwBoxC!=0) - { - app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); - } - // Add the anim override - app.SetAnimOverrideBitmask(packet->dwSkinID,packet->uiAnimOverrideBitmask); + // Add the texture data + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dwTextureBytes); + // Add the geometry data + if (packet->dwBoxC != 0) { + app.SetAdditionalSkinBoxes(packet->dwSkinID, packet->BoxDataA, + packet->dwBoxC); + } + // Add the anim override + app.SetAnimOverrideBitmask(packet->dwSkinID, + packet->uiAnimOverrideBitmask); - // clear out the pending texture request - Minecraft::GetInstance()->handleClientTextureReceived(packet->textureName); - } + // clear out the pending texture request + Minecraft::GetInstance()->handleClientTextureReceived( + packet->textureName); + } } -void ClientConnection::handleTextureChange(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); +void ClientConnection::handleTextureChange( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + std::shared_ptr player = std::dynamic_pointer_cast(e); if (e == NULL) return; - std::shared_ptr player = std::dynamic_pointer_cast(e); - if( e == NULL) return; - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->id ) - { - isLocalPlayer = true; - break; - } - } - } - if(isLocalPlayer) return; + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->id) { + isLocalPlayer = true; + break; + } + } + } + if (isLocalPlayer) return; - switch(packet->action) - { - case TextureChangePacket::e_TextureChange_Skin: - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); + switch (packet->action) { + case TextureChangePacket::e_TextureChange_Skin: + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); + wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); #endif - break; - case TextureChangePacket::e_TextureChange_Cape: - player->setCustomCape( Player::getCapeIdFromPath( packet->path ) ); - //player->customTextureUrl2 = packet->path; + break; + case TextureChangePacket::e_TextureChange_Cape: + player->setCustomCape(Player::getCapeIdFromPath(packet->path)); + // player->customTextureUrl2 = packet->path; #ifndef _CONTENT_PACKAGE - wprintf(L"Cape for remote player %ls has changed to %ls\n", player->name.c_str(), player->customTextureUrl2.c_str() ); + wprintf(L"Cape for remote player %ls has changed to %ls\n", + player->name.c_str(), player->customTextureUrl2.c_str()); #endif - break; - } - - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( minecraft->addPendingClientTextureRequest(packet->path) ) - { + break; + } + + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (minecraft->addPendingClientTextureRequest(packet->path)) { #ifndef _CONTENT_PACKAGE - wprintf(L"handleTextureChange - Client sending texture packet to get custom skin %ls for player %ls\n",packet->path.c_str(), player->name.c_str()); + wprintf( + L"handleTextureChange - Client sending texture packet to get " + L"custom skin %ls for player %ls\n", + packet->path.c_str(), player->name.c_str()); #endif - send(std::shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - } + send(std::shared_ptr( + new TexturePacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } } -void ClientConnection::handleTextureAndGeometryChange(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); - if (e == NULL) return; - std::shared_ptr player = std::dynamic_pointer_cast(e); - if( e == NULL) return; +void ClientConnection::handleTextureAndGeometryChange( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + std::shared_ptr player = std::dynamic_pointer_cast(e); + if (e == NULL) return; - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->id ) - { - isLocalPlayer = true; - break; - } - } - } - if(isLocalPlayer) return; + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->id) { + isLocalPlayer = true; + break; + } + } + } + if (isLocalPlayer) return; - - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); + wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); #endif - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( minecraft->addPendingClientTextureRequest(packet->path) ) - { + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (minecraft->addPendingClientTextureRequest(packet->path)) { #ifndef _CONTENT_PACKAGE - wprintf(L"handleTextureAndGeometryChange - Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n",packet->path.c_str(), player->name.c_str()); + wprintf( + L"handleTextureAndGeometryChange - Client sending " + L"TextureAndGeometryPacket to get custom skin %ls for player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); #endif - send(std::shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - - } + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } } -void ClientConnection::handleRespawn(std::shared_ptr packet) -{ - //if (packet->dimension != minecraft->player->dimension) - if( packet->dimension != minecraft->localplayers[m_userIndex]->dimension || packet->mapSeed != minecraft->localplayers[m_userIndex]->level->getSeed() ) - { - int oldDimension = minecraft->localplayers[m_userIndex]->dimension; +void ClientConnection::handleRespawn(std::shared_ptr packet) { + // if (packet->dimension != minecraft->player->dimension) + if (packet->dimension != minecraft->localplayers[m_userIndex]->dimension || + packet->mapSeed != + minecraft->localplayers[m_userIndex]->level->getSeed()) { + int oldDimension = minecraft->localplayers[m_userIndex]->dimension; started = false; - // Remove client connection from this level - level->removeClientConnection(this, false); + // Remove client connection from this level + level->removeClientConnection(this, false); - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) - { - dimensionLevel = new MultiPlayerLevel(this, new LevelSettings(packet->mapSeed, packet->playerGameType, false, minecraft->level->getLevelData()->isHardcore(), packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->getLevel(packet->dimension); + if (dimensionLevel == NULL) { + dimensionLevel = new MultiPlayerLevel( + this, + new LevelSettings( + packet->mapSeed, packet->playerGameType, false, + minecraft->level->getLevelData()->isHardcore(), + packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - // 4J Stu - We want to shared the savedDataStorage between both levels - //if( dimensionLevel->savedDataStorage != NULL ) - //{ - // Don't need to delete it here as it belongs to a client connection while will delete it when it's done - // delete dimensionLevel->savedDataStorage;+ - //} - dimensionLevel->savedDataStorage = level->savedDataStorage; + // 4J Stu - We want to shared the savedDataStorage between both + // levels + // if( dimensionLevel->savedDataStorage != NULL ) + //{ + // Don't need to delete it here as it belongs to a client connection + // while will delete it when it's done + // delete dimensionLevel->savedDataStorage;+ + //} + dimensionLevel->savedDataStorage = level->savedDataStorage; - dimensionLevel->difficulty = packet->difficulty; // 4J Added - app.DebugPrintf("dimensionLevel->difficulty - Difficulty = %d\n",packet->difficulty); + dimensionLevel->difficulty = packet->difficulty; // 4J Added + app.DebugPrintf("dimensionLevel->difficulty - Difficulty = %d\n", + packet->difficulty); - dimensionLevel->isClientSide = true; - } - else - { - dimensionLevel->addClientConnection(this); - } + dimensionLevel->isClientSide = true; + } else { + dimensionLevel->addClientConnection(this); + } - // Remove the player entity from the current level - level->removeEntity( std::shared_ptr(minecraft->localplayers[m_userIndex]) ); + // Remove the player entity from the current level + level->removeEntity( + std::shared_ptr(minecraft->localplayers[m_userIndex])); - level = dimensionLevel; - - // Whilst calling setLevel, make sure that minecraft::player is set up to be correct for this - // connection - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - minecraft->setLevel(dimensionLevel); - minecraft->player = lastPlayer; + level = dimensionLevel; - TelemetryManager->RecordLevelExit(m_userIndex, eSen_LevelExitStatus_Succeeded); - - //minecraft->player->dimension = packet->dimension; - minecraft->localplayers[m_userIndex]->dimension = packet->dimension; - //minecraft->setScreen(new ReceivingLevelScreen(this)); -// minecraft->addPendingLocalConnection(m_userIndex, this); + // Whilst calling setLevel, make sure that minecraft::player is set up + // to be correct for this connection + std::shared_ptr lastPlayer = minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + minecraft->setLevel(dimensionLevel); + minecraft->player = lastPlayer; + + TelemetryManager->RecordLevelExit(m_userIndex, + eSen_LevelExitStatus_Succeeded); + + // minecraft->player->dimension = packet->dimension; + minecraft->localplayers[m_userIndex]->dimension = packet->dimension; + // minecraft->setScreen(new ReceivingLevelScreen(this)); + // minecraft->addPendingLocalConnection(m_userIndex, this); #ifdef _XBOX - TelemetryManager->RecordLevelStart(m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); + TelemetryManager->RecordLevelStart( + m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, + app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); #endif - if( minecraft->localgameModes[m_userIndex] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_userIndex]; - gameMode->getTutorial()->showTutorialPopup(false); - } + if (minecraft->localgameModes[m_userIndex] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_userIndex]; + gameMode->getTutorial()->showTutorialPopup(false); + } - // 4J-JEV: Fix for Durango #156334 - Content: UI: Rich Presence 'In the Nether' message is updating with a 3 to 10 minute delay. - minecraft->localplayers[m_userIndex]->updateRichPresence(); + // 4J-JEV: Fix for Durango #156334 - Content: UI: Rich Presence 'In the + // Nether' message is updating with a 3 to 10 minute delay. + minecraft->localplayers[m_userIndex]->updateRichPresence(); - ConnectionProgressParams *param = new ConnectionProgressParams(); - param->iPad = m_userIndex; - if( packet->dimension == -1) - { - param->stringId = IDS_PROGRESS_ENTERING_NETHER; - } - else if( oldDimension == -1) - { - param->stringId = IDS_PROGRESS_LEAVING_NETHER; - } - else if( packet->dimension == 1) - { - param->stringId = IDS_PROGRESS_ENTERING_END; - } - else if( oldDimension == 1) - { - param->stringId = IDS_PROGRESS_LEAVING_END; - } - param->showTooltips = false; - param->setFailTimer = false; + ConnectionProgressParams* param = new ConnectionProgressParams(); + param->iPad = m_userIndex; + if (packet->dimension == -1) { + param->stringId = IDS_PROGRESS_ENTERING_NETHER; + } else if (oldDimension == -1) { + param->stringId = IDS_PROGRESS_LEAVING_NETHER; + } else if (packet->dimension == 1) { + param->stringId = IDS_PROGRESS_ENTERING_END; + } else if (oldDimension == 1) { + param->stringId = IDS_PROGRESS_LEAVING_END; + } + param->showTooltips = false; + param->setFailTimer = false; - // 4J Stu - Fix for #13543 - Crash: Game crashes if entering a portal with the inventory menu open - ui.CloseUIScenes( m_userIndex ); + // 4J Stu - Fix for #13543 - Crash: Game crashes if entering a portal + // with the inventory menu open + ui.CloseUIScenes(m_userIndex); - if(app.GetLocalPlayerCount()>1) - { - ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); - } - else - { - ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); - } - - app.SetAction( m_userIndex, eAppAction_WaitForDimensionChangeComplete); + if (app.GetLocalPlayerCount() > 1) { + ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); + } else { + ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); + } + + app.SetAction(m_userIndex, eAppAction_WaitForDimensionChangeComplete); } - //minecraft->respawnPlayer(minecraft->player->GetXboxPad(),true, packet->dimension); - - // Wrap respawnPlayer call up in code to set & restore the player/gamemode etc. as some things - // in there assume that we are set up for the player that the respawn is coming in for - int oldIndex = minecraft->getLocalPlayerIdx(); - minecraft->setLocalPlayerIdx(m_userIndex); - minecraft->respawnPlayer(minecraft->localplayers[m_userIndex]->GetXboxPad(),packet->dimension,packet->m_newEntityId); - ((MultiPlayerGameMode *) minecraft->localgameModes[m_userIndex])->setLocalMode(packet->playerGameType); - minecraft->setLocalPlayerIdx(oldIndex); + // minecraft->respawnPlayer(minecraft->player->GetXboxPad(),true, + // packet->dimension); + + // Wrap respawnPlayer call up in code to set & restore the player/gamemode + // etc. as some things in there assume that we are set up for the player + // that the respawn is coming in for + int oldIndex = minecraft->getLocalPlayerIdx(); + minecraft->setLocalPlayerIdx(m_userIndex); + minecraft->respawnPlayer(minecraft->localplayers[m_userIndex]->GetXboxPad(), + packet->dimension, packet->m_newEntityId); + ((MultiPlayerGameMode*)minecraft->localgameModes[m_userIndex]) + ->setLocalMode(packet->playerGameType); + minecraft->setLocalPlayerIdx(oldIndex); } -void ClientConnection::handleExplosion(std::shared_ptr packet) -{ - if(!packet->m_bKnockbackOnly) - { - //app.DebugPrintf("Received ExplodePacket with explosion data\n"); - PIXBeginNamedEvent(0,"Handling explosion"); - Explosion *e = new Explosion(minecraft->level, nullptr, packet->x, packet->y, packet->z, packet->r); - PIXBeginNamedEvent(0,"Finalizing"); +void ClientConnection::handleExplosion(std::shared_ptr packet) { + if (!packet->m_bKnockbackOnly) { + // app.DebugPrintf("Received ExplodePacket with explosion data\n"); + PIXBeginNamedEvent(0, "Handling explosion"); + Explosion* e = new Explosion(minecraft->level, nullptr, packet->x, + packet->y, packet->z, packet->r); + PIXBeginNamedEvent(0, "Finalizing"); - // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: Gameplay: After detonating bunch of TNT, game enters unresponsive state for couple of seconds. - // The changes we are making here have been decided by the server, so we don't need to add them to the vector that resets tiles changes made - // on the client as we KNOW that the server is matching these changes - MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)minecraft->level; - mpLevel->enableResetChanges(false); - // 4J - now directly pass a pointer to the toBlow array in the packet rather than copying around - e->finalizeExplosion(true, &packet->toBlow); - mpLevel->enableResetChanges(true); - PIXEndNamedEvent(); - PIXEndNamedEvent(); - delete e; - } - else - { - //app.DebugPrintf("Received ExplodePacket with knockback only data\n"); - } + // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: + // Gameplay: After detonating bunch of TNT, game enters unresponsive + // state for couple of seconds. The changes we are making here have been + // decided by the server, so we don't need to add them to the vector + // that resets tiles changes made on the client as we KNOW that the + // server is matching these changes + MultiPlayerLevel* mpLevel = (MultiPlayerLevel*)minecraft->level; + mpLevel->enableResetChanges(false); + // 4J - now directly pass a pointer to the toBlow array in the packet + // rather than copying around + e->finalizeExplosion(true, &packet->toBlow); + mpLevel->enableResetChanges(true); + PIXEndNamedEvent(); + PIXEndNamedEvent(); + delete e; + } else { + // app.DebugPrintf("Received ExplodePacket with knockback only data\n"); + } - //app.DebugPrintf("Adding knockback (%f,%f,%f) for player %d\n", packet->getKnockbackX(), packet->getKnockbackY(), packet->getKnockbackZ(), m_userIndex); - minecraft->localplayers[m_userIndex]->xd += packet->getKnockbackX(); - minecraft->localplayers[m_userIndex]->yd += packet->getKnockbackY(); - minecraft->localplayers[m_userIndex]->zd += packet->getKnockbackZ(); + // app.DebugPrintf("Adding knockback (%f,%f,%f) for player %d\n", + // packet->getKnockbackX(), packet->getKnockbackY(), + // packet->getKnockbackZ(), m_userIndex); + minecraft->localplayers[m_userIndex]->xd += packet->getKnockbackX(); + minecraft->localplayers[m_userIndex]->yd += packet->getKnockbackY(); + minecraft->localplayers[m_userIndex]->zd += packet->getKnockbackZ(); } -void ClientConnection::handleContainerOpen(std::shared_ptr packet) -{ - bool failed = false; - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - switch(packet->type) - { - case ContainerOpenPacket::CONTAINER: - { - if( player->openContainer(std::shared_ptr( new SimpleContainer(packet->title, packet->size) ))) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::FURNACE: - { - if( player->openFurnace(std::shared_ptr( new FurnaceTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::BREWING_STAND: - { - if( player->openBrewingStand(std::shared_ptr( new BrewingStandTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::TRAP: - { - if( player->openTrap(std::shared_ptr( new DispenserTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::WORKBENCH: - { - if( player->startCrafting(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::ENCHANTMENT: - { - if( player->startEnchanting(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::TRADER_NPC: - { - std::shared_ptr csm = std::shared_ptr(new ClientSideMerchant(player,packet->title)); - csm->createContainer(); - if(player->openTrading(csm)) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::REPAIR_TABLE: - { - if(player->startRepairing(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z))) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - }; +void ClientConnection::handleContainerOpen( + std::shared_ptr packet) { + bool failed = false; + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + switch (packet->type) { + case ContainerOpenPacket::CONTAINER: { + if (player->openContainer(std::shared_ptr( + new SimpleContainer(packet->title, packet->size)))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::FURNACE: { + if (player->openFurnace(std::shared_ptr( + new FurnaceTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::BREWING_STAND: { + if (player->openBrewingStand( + std::shared_ptr( + new BrewingStandTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::TRAP: { + if (player->openTrap(std::shared_ptr( + new DispenserTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::WORKBENCH: { + if (player->startCrafting(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::ENCHANTMENT: { + if (player->startEnchanting(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::TRADER_NPC: { + std::shared_ptr csm = + std::shared_ptr( + new ClientSideMerchant(player, packet->title)); + csm->createContainer(); + if (player->openTrading(csm)) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::REPAIR_TABLE: { + if (player->startRepairing(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + }; - if(failed) - { - // Failed - if we've got a non-inventory container currently here, close that, which locally should put us back - // to not having a container open, and should send a containerclose to the server so it doesn't have a container open. - // If we don't have a non-inventory container open, just send the packet, and again we ought to be in sync with the server. - if( player->containerMenu != player->inventoryMenu ) - { - ui.CloseUIScenes(m_userIndex); - } - else - { - send(std::shared_ptr(new ContainerClosePacket(packet->containerId))); - } - } + if (failed) { + // Failed - if we've got a non-inventory container currently here, close + // that, which locally should put us back to not having a container + // open, and should send a containerclose to the server so it doesn't + // have a container open. If we don't have a non-inventory container + // open, just send the packet, and again we ought to be in sync with the + // server. + if (player->containerMenu != player->inventoryMenu) { + ui.CloseUIScenes(m_userIndex); + } else { + send(std::shared_ptr( + new ContainerClosePacket(packet->containerId))); + } + } } -void ClientConnection::handleContainerSetSlot(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED ) - { +void ClientConnection::handleContainerSetSlot( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED) { player->inventory->setCarried(packet->item); - } - else - { - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { - // 4J Stu - Reworked a bit to fix a bug where things being collected while the creative menu was up replaced items in the creative menu - if(packet->slot >= 36 && packet->slot < 36 + 9) - { - std::shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) - { - if (lastItem == NULL || lastItem->count < packet->item->count) - { - packet->item->popTime = Inventory::POP_TIME_DURATION; - } - } - } - player->inventoryMenu->setItem(packet->slot, packet->item); - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else { + if (packet->containerId == + AbstractContainerMenu::CONTAINER_ID_INVENTORY) { + // 4J Stu - Reworked a bit to fix a bug where things being collected + // while the creative menu was up replaced items in the creative + // menu + if (packet->slot >= 36 && packet->slot < 36 + 9) { + std::shared_ptr lastItem = + player->inventoryMenu->getSlot(packet->slot)->getItem(); + if (packet->item != NULL) { + if (lastItem == NULL || + lastItem->count < packet->item->count) { + packet->item->popTime = Inventory::POP_TIME_DURATION; + } + } + } + player->inventoryMenu->setItem(packet->slot, packet->item); + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setItem(packet->slot, packet->item); } } } -void ClientConnection::handleContainerAck(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - AbstractContainerMenu *menu = NULL; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { +void ClientConnection::handleContainerAck( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + AbstractContainerMenu* menu = NULL; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { menu = player->inventoryMenu; - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else if (packet->containerId == player->containerMenu->containerId) { menu = player->containerMenu; } - if (menu != NULL) - { - if (!packet->accepted) - { - send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) )); + if (menu != NULL) { + if (!packet->accepted) { + send(std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, true))); } } } -void ClientConnection::handleContainerContent(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { +void ClientConnection::handleContainerContent( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { player->inventoryMenu->setAll(&packet->items); - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setAll(&packet->items); } } -void ClientConnection::handleSignUpdate(std::shared_ptr packet) -{ - app.DebugPrintf("ClientConnection::handleSignUpdate - "); - if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); +void ClientConnection::handleSignUpdate( + std::shared_ptr packet) { + app.DebugPrintf("ClientConnection::handleSignUpdate - "); + if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + minecraft->level->getTileEntity(packet->x, packet->y, packet->z); - // 4J-PB - on a client connecting, the line below fails - if (std::dynamic_pointer_cast(te) != NULL) - { - std::shared_ptr ste = std::dynamic_pointer_cast(te); - for (int i = 0; i < MAX_SIGN_LINES; i++) - { - ste->SetMessage(i,packet->lines[i]); + // 4J-PB - on a client connecting, the line below fails + if (std::dynamic_pointer_cast(te) != NULL) { + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + for (int i = 0; i < MAX_SIGN_LINES; i++) { + ste->SetMessage(i, packet->lines[i]); } - app.DebugPrintf("verified = %d\tCensored = %d\n",packet->m_bVerified,packet->m_bCensored); - ste->SetVerified(packet->m_bVerified); - ste->SetCensored(packet->m_bCensored); + app.DebugPrintf("verified = %d\tCensored = %d\n", + packet->m_bVerified, packet->m_bCensored); + ste->SetVerified(packet->m_bVerified); + ste->SetCensored(packet->m_bCensored); - ste->setChanged(); + ste->setChanged(); + } else { + app.DebugPrintf( + "std::dynamic_pointer_cast(te) == NULL\n"); } - else - { - app.DebugPrintf("std::dynamic_pointer_cast(te) == NULL\n"); - } + } else { + app.DebugPrintf("hasChunkAt failed\n"); } - else - { - app.DebugPrintf("hasChunkAt failed\n"); - } } -void ClientConnection::handleTileEntityData(std::shared_ptr packet) -{ - if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); +void ClientConnection::handleTileEntityData( + std::shared_ptr packet) { + if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + minecraft->level->getTileEntity(packet->x, packet->y, packet->z); - if (te != NULL) - { - if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && std::dynamic_pointer_cast(te) != NULL) - { - std::dynamic_pointer_cast(te)->load(packet->tag); - } - //else if (packet.type == TileEntityDataPacket.TYPE_ADV_COMMAND && (te instanceof CommandBlockEntity)) - //{ - // ((CommandBlockEntity) te).load(packet.tag); - //} - //else if (packet.type == TileEntityDataPacket.TYPE_BEACON && (te instanceof BeaconTileEntity)) - //{ - // ((BeaconTileEntity) te).load(packet.tag); - //} - else if (packet->type == TileEntityDataPacket::TYPE_SKULL && std::dynamic_pointer_cast(te) != NULL) - { - std::dynamic_pointer_cast(te)->load(packet->tag); - } - } - } + if (te != NULL) { + if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && + std::dynamic_pointer_cast(te) != NULL) { + std::dynamic_pointer_cast(te)->load( + packet->tag); + } + // else if (packet.type == TileEntityDataPacket.TYPE_ADV_COMMAND && + // (te instanceof CommandBlockEntity)) + //{ + // ((CommandBlockEntity) te).load(packet.tag); + // } + // else if (packet.type == TileEntityDataPacket.TYPE_BEACON && (te + // instanceof BeaconTileEntity)) + //{ + // ((BeaconTileEntity) te).load(packet.tag); + // } + else if (packet->type == TileEntityDataPacket::TYPE_SKULL && + std::dynamic_pointer_cast(te) != NULL) { + std::dynamic_pointer_cast(te)->load( + packet->tag); + } + } + } } -void ClientConnection::handleContainerSetData(std::shared_ptr packet) -{ +void ClientConnection::handleContainerSetData( + std::shared_ptr packet) { onUnhandledPacket(packet); - if (minecraft->localplayers[m_userIndex]->containerMenu != NULL && minecraft->localplayers[m_userIndex]->containerMenu->containerId == packet->containerId) - { - minecraft->localplayers[m_userIndex]->containerMenu->setData(packet->id, packet->value); + if (minecraft->localplayers[m_userIndex]->containerMenu != NULL && + minecraft->localplayers[m_userIndex]->containerMenu->containerId == + packet->containerId) { + minecraft->localplayers[m_userIndex]->containerMenu->setData( + packet->id, packet->value); } } -void ClientConnection::handleSetEquippedItem(std::shared_ptr packet) -{ +void ClientConnection::handleSetEquippedItem( + std::shared_ptr packet) { std::shared_ptr entity = getEntity(packet->entity); - if (entity != NULL) - { - // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - entity->setEquippedSlot(packet->slot, packet->getItem() ); + if (entity != NULL) { + // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer + // Encountered: TU7: Content: Art: Aura of enchanted item is not + // displayed for other players in online game + entity->setEquippedSlot(packet->slot, packet->getItem()); } } -void ClientConnection::handleContainerClose(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->closeContainer(); +void ClientConnection::handleContainerClose( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->closeContainer(); } -void ClientConnection::handleTileEvent(std::shared_ptr packet) -{ - PIXBeginNamedEvent(0,"Handle tile event\n"); - minecraft->level->tileEvent(packet->x, packet->y, packet->z, packet->tile, packet->b0, packet->b1); - PIXEndNamedEvent(); +void ClientConnection::handleTileEvent( + std::shared_ptr packet) { + PIXBeginNamedEvent(0, "Handle tile event\n"); + minecraft->level->tileEvent(packet->x, packet->y, packet->z, packet->tile, + packet->b0, packet->b1); + PIXEndNamedEvent(); } -void ClientConnection::handleTileDestruction(std::shared_ptr packet) -{ - minecraft->level->destroyTileProgress(packet->getEntityId(), packet->getX(), packet->getY(), packet->getZ(), packet->getState()); +void ClientConnection::handleTileDestruction( + std::shared_ptr packet) { + minecraft->level->destroyTileProgress(packet->getEntityId(), packet->getX(), + packet->getY(), packet->getZ(), + packet->getState()); } -bool ClientConnection::canHandleAsyncPackets() -{ - return minecraft != NULL && minecraft->level != NULL && minecraft->localplayers[m_userIndex] != NULL && level != NULL; +bool ClientConnection::canHandleAsyncPackets() { + return minecraft != NULL && minecraft->level != NULL && + minecraft->localplayers[m_userIndex] != NULL && level != NULL; } -void ClientConnection::handleGameEvent(std::shared_ptr gameEventPacket) -{ +void ClientConnection::handleGameEvent( + std::shared_ptr gameEventPacket) { int event = gameEventPacket->_event; - int param = gameEventPacket->param; - if (event >= 0 && event < GameEventPacket::EVENT_LANGUAGE_ID_LENGTH) - { - if (GameEventPacket::EVENT_LANGUAGE_ID[event] > 0) // 4J - was NULL check - { - minecraft->localplayers[m_userIndex]->displayClientMessage(GameEventPacket::EVENT_LANGUAGE_ID[event]); + int param = gameEventPacket->param; + if (event >= 0 && event < GameEventPacket::EVENT_LANGUAGE_ID_LENGTH) { + if (GameEventPacket::EVENT_LANGUAGE_ID[event] > + 0) // 4J - was NULL check + { + minecraft->localplayers[m_userIndex]->displayClientMessage( + GameEventPacket::EVENT_LANGUAGE_ID[event]); } } - if (event == GameEventPacket::START_RAINING) - { + if (event == GameEventPacket::START_RAINING) { level->getLevelData()->setRaining(true); level->setRainLevel(1); - } - else if (event == GameEventPacket::STOP_RAINING) - { + } else if (event == GameEventPacket::STOP_RAINING) { level->getLevelData()->setRaining(false); level->setRainLevel(0); - } - else if (event == GameEventPacket::CHANGE_GAME_MODE) - { - minecraft->localgameModes[m_userIndex]->setLocalMode(GameType::byId(param)); - } - else if (event == GameEventPacket::WIN_GAME) - { - ui.SetWinUserIndex(static_cast(gameEventPacket->param)); - + } else if (event == GameEventPacket::CHANGE_GAME_MODE) { + minecraft->localgameModes[m_userIndex]->setLocalMode( + GameType::byId(param)); + } else if (event == GameEventPacket::WIN_GAME) { + ui.SetWinUserIndex(static_cast(gameEventPacket->param)); + #ifdef _XBOX - // turn off the gamertags in splitscreen for the primary player, since they are about to be made fullscreen - ui.HideAllGameUIElements(); + // turn off the gamertags in splitscreen for the primary player, since + // they are about to be made fullscreen + ui.HideAllGameUIElements(); - // Hide the other players scenes - ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); + // Hide the other players scenes + ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); - // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); - // Temporarily make this scene fullscreen - CXuiSceneBase::SetPlayerBaseScenePosition( ProfileManager.GetPrimaryPad(), CXuiSceneBase::e_BaseScene_Fullscreen ); + // This just allows it to be shown + if (minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) + minecraft->localgameModes[ProfileManager.GetPrimaryPad()] + ->getTutorial() + ->showTutorialPopup(false); + // Temporarily make this scene fullscreen + CXuiSceneBase::SetPlayerBaseScenePosition( + ProfileManager.GetPrimaryPad(), + CXuiSceneBase::e_BaseScene_Fullscreen); - app.CloseXuiScenesAndNavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_EndPoem); + app.CloseXuiScenesAndNavigateToScene(ProfileManager.GetPrimaryPad(), + eUIScene_EndPoem); #else - app.DebugPrintf("handleGameEvent packet for WIN_GAME - %d\n", m_userIndex); - // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); - ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, NULL, eUILayer_Scene, eUIGroup_Fullscreen); + app.DebugPrintf("handleGameEvent packet for WIN_GAME - %d\n", + m_userIndex); + // This just allows it to be shown + if (minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) + minecraft->localgameModes[ProfileManager.GetPrimaryPad()] + ->getTutorial() + ->showTutorialPopup(false); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, + NULL, eUILayer_Scene, eUIGroup_Fullscreen); #endif - } - else if( event == GameEventPacket::START_SAVING ) - { - if(!g_NetworkManager.IsHost()) - { - // Move app started to here so that it happens immediately otherwise back-to-back START/STOP packets - // leave the client stuck in the loading screen - app.SetGameStarted(false); - app.SetAction( ProfileManager.GetPrimaryPad(), eAppAction_RemoteServerSave ); - } - } - else if( event == GameEventPacket::STOP_SAVING ) - { - if(!g_NetworkManager.IsHost() ) app.SetGameStarted(true); - } + } else if (event == GameEventPacket::START_SAVING) { + if (!g_NetworkManager.IsHost()) { + // Move app started to here so that it happens immediately otherwise + // back-to-back START/STOP packets leave the client stuck in the + // loading screen + app.SetGameStarted(false); + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_RemoteServerSave); + } + } else if (event == GameEventPacket::STOP_SAVING) { + if (!g_NetworkManager.IsHost()) app.SetGameStarted(true); + } } -void ClientConnection::handleComplexItemData(std::shared_ptr packet) -{ - if (packet->itemType == Item::map->id) - { - MapItem::getSavedData(packet->itemId, minecraft->level)->handleComplexItemData(packet->data); - } - else - { -// System.out.println("Unknown itemid: " + packet->itemId); // 4J removed - } +void ClientConnection::handleComplexItemData( + std::shared_ptr packet) { + if (packet->itemType == Item::map->id) { + MapItem::getSavedData(packet->itemId, minecraft->level) + ->handleComplexItemData(packet->data); + } else { + // System.out.println("Unknown itemid: " + packet->itemId); + //// 4J removed + } } +void ClientConnection::handleLevelEvent( + std::shared_ptr packet) { + switch (packet->type) { + case LevelEvent::SOUND_DRAGON_DEATH: { + Minecraft* pMinecraft = Minecraft::GetInstance(); + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + if (pMinecraft->localplayers[i] != NULL && + pMinecraft->localplayers[i]->level != NULL && + pMinecraft->localplayers[i]->level->dimension->id == 1) { + pMinecraft->localplayers[i]->awardStat( + GenericStats::completeTheEnd(), + GenericStats::param_noArgs()); + } + } + } + minecraft->level->levelEvent(packet->type, packet->x, packet->y, + packet->z, packet->data); - -void ClientConnection::handleLevelEvent(std::shared_ptr packet) -{ - switch(packet->type) - { - case LevelEvent::SOUND_DRAGON_DEATH: - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - if(pMinecraft->localplayers[i] != NULL && pMinecraft->localplayers[i]->level != NULL && pMinecraft->localplayers[i]->level->dimension->id == 1) - { - pMinecraft->localplayers[i]->awardStat(GenericStats::completeTheEnd(),GenericStats::param_noArgs()); - } - } - } - minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); - - break; - default: - minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); - break; - } + break; + default: + minecraft->level->levelEvent(packet->type, packet->x, packet->y, + packet->z, packet->data); + break; + } } -void ClientConnection::handleAwardStat(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->awardStatFromServer(GenericStats::stat(packet->statId), packet->getParamData()); +void ClientConnection::handleAwardStat( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->awardStatFromServer( + GenericStats::stat(packet->statId), packet->getParamData()); } -void ClientConnection::handleUpdateMobEffect(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->entityId); - if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; +void ClientConnection::handleUpdateMobEffect( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->entityId); + if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; - ( std::dynamic_pointer_cast(e) )->addEffect(new MobEffectInstance(packet->effectId, packet->effectDurationTicks, packet->effectAmplifier)); + (std::dynamic_pointer_cast(e)) + ->addEffect(new MobEffectInstance(packet->effectId, + packet->effectDurationTicks, + packet->effectAmplifier)); } -void ClientConnection::handleRemoveMobEffect(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->entityId); - if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; +void ClientConnection::handleRemoveMobEffect( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->entityId); + if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; - ( std::dynamic_pointer_cast(e) )->removeEffectNoUpdate(packet->effectId); + (std::dynamic_pointer_cast(e))->removeEffectNoUpdate(packet->effectId); } -bool ClientConnection::isServerPacketListener() -{ - return false; -} +bool ClientConnection::isServerPacketListener() { return false; } -void ClientConnection::handlePlayerInfo(std::shared_ptr packet) -{ - unsigned int startingPrivileges = app.GetPlayerPrivileges(packet->m_networkSmallId); +void ClientConnection::handlePlayerInfo( + std::shared_ptr packet) { + unsigned int startingPrivileges = + app.GetPlayerPrivileges(packet->m_networkSmallId); - INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerBySmallId(packet->m_networkSmallId); + INetworkPlayer* networkPlayer = + g_NetworkManager.GetPlayerBySmallId(packet->m_networkSmallId); - if(networkPlayer != NULL && networkPlayer->IsHost()) - { - // Some settings should always be considered on for the host player - Player::enableAllPlayerPrivileges(startingPrivileges,true); - Player::setPlayerGamePrivilege(startingPrivileges,Player::ePlayerGamePrivilege_HOST,1); - } + if (networkPlayer != NULL && networkPlayer->IsHost()) { + // Some settings should always be considered on for the host player + Player::enableAllPlayerPrivileges(startingPrivileges, true); + Player::setPlayerGamePrivilege(startingPrivileges, + Player::ePlayerGamePrivilege_HOST, 1); + } - // 4J Stu - Repurposed this packet for player info that we want - app.UpdatePlayerInfo(packet->m_networkSmallId, packet->m_playerColourIndex, packet->m_playerPrivileges); + // 4J Stu - Repurposed this packet for player info that we want + app.UpdatePlayerInfo(packet->m_networkSmallId, packet->m_playerColourIndex, + packet->m_playerPrivileges); - std::shared_ptr entity = getEntity(packet->m_entityId); - if(entity != NULL && entity->GetType() == eTYPE_PLAYER) - { - std::shared_ptr player = std::dynamic_pointer_cast(entity); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_playerPrivileges); - } - if(networkPlayer != NULL && networkPlayer->IsLocal()) - { - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - std::shared_ptr localPlayer = minecraft->localplayers[i]; - if(localPlayer != NULL && localPlayer->connection != NULL && localPlayer->connection->getNetworkPlayer() == networkPlayer ) - { - localPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All,packet->m_playerPrivileges); - displayPrivilegeChanges(localPlayer,startingPrivileges); - break; - } - } - } + std::shared_ptr entity = getEntity(packet->m_entityId); + if (entity != NULL && entity->GetType() == eTYPE_PLAYER) { + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_playerPrivileges); + } + if (networkPlayer != NULL && networkPlayer->IsLocal()) { + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + std::shared_ptr localPlayer = + minecraft->localplayers[i]; + if (localPlayer != NULL && localPlayer->connection != NULL && + localPlayer->connection->getNetworkPlayer() == networkPlayer) { + localPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_All, + packet->m_playerPrivileges); + displayPrivilegeChanges(localPlayer, startingPrivileges); + break; + } + } + } - // 4J Stu - I don't think we care about this, so not converting it (came from 1.8.2) + // 4J Stu - I don't think we care about this, so not converting it (came + // from 1.8.2) #if 0 PlayerInfo pi = playerInfoMap.get(packet.name); if (pi == null && packet.add) { @@ -3037,326 +3189,377 @@ void ClientConnection::handlePlayerInfo(std::shared_ptr packet #endif } - -void ClientConnection::displayPrivilegeChanges(std::shared_ptr player, unsigned int oldPrivileges) -{ - int userIndex = player->GetXboxPad(); - unsigned int newPrivileges = player->getAllPlayerGamePrivileges(); - Player::EPlayerGamePrivileges priv = (Player::EPlayerGamePrivileges)0; - bool privOn = false; - for(unsigned int i = 0; i < Player::ePlayerGamePrivilege_MAX; ++i) - { - priv = (Player::EPlayerGamePrivileges) i; - if( Player::getPlayerGamePrivilege(newPrivileges,priv) != Player::getPlayerGamePrivilege(oldPrivileges,priv)) - { - privOn = Player::getPlayerGamePrivilege(newPrivileges,priv); - std::wstring message = L""; - if(app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) - { - switch(priv) - { - case Player::ePlayerGamePrivilege_CannotMine: - if(privOn) message = app.GetString(IDS_PRIV_MINE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_MINE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotBuild: - if(privOn) message = app.GetString(IDS_PRIV_BUILD_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_BUILD_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches: - if(privOn) message = app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanUseContainers: - if(privOn) message = app.GetString(IDS_PRIV_USE_CONTAINERS_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_USE_CONTAINERS_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackAnimals: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackMobs: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackPlayers: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_OFF); - break; - default: - break; - }; - } - switch(priv) - { - case Player::ePlayerGamePrivilege_Op: - if(privOn) message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_OFF); - break; - default: - break; - }; - if(app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0) - { - switch(priv) - { - case Player::ePlayerGamePrivilege_CanFly: - if(privOn) message = app.GetString(IDS_PRIV_FLY_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_FLY_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_ClassicHunger: - if(privOn) message = app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_Invisible: - if(privOn) message = app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_Invulnerable: - if(privOn) message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleInvisible: - if(privOn) message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleFly: - if(privOn) message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleClassicHunger: - if(privOn) message = app.GetString(IDS_PRIV_CAN_EXHAUSTION_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_EXHAUSTION_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanTeleport: - if(privOn) message = app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_OFF); - break; - default: - break; - }; - } - if(!message.empty()) minecraft->gui->addMessage(message,userIndex); - } - } +void ClientConnection::displayPrivilegeChanges( + std::shared_ptr player, + unsigned int oldPrivileges) { + int userIndex = player->GetXboxPad(); + unsigned int newPrivileges = player->getAllPlayerGamePrivileges(); + Player::EPlayerGamePrivileges priv = (Player::EPlayerGamePrivileges)0; + bool privOn = false; + for (unsigned int i = 0; i < Player::ePlayerGamePrivilege_MAX; ++i) { + priv = (Player::EPlayerGamePrivileges)i; + if (Player::getPlayerGamePrivilege(newPrivileges, priv) != + Player::getPlayerGamePrivilege(oldPrivileges, priv)) { + privOn = Player::getPlayerGamePrivilege(newPrivileges, priv); + std::wstring message = L""; + if (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) { + switch (priv) { + case Player::ePlayerGamePrivilege_CannotMine: + if (privOn) + message = app.GetString(IDS_PRIV_MINE_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_MINE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotBuild: + if (privOn) + message = app.GetString(IDS_PRIV_BUILD_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_BUILD_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches: + if (privOn) + message = + app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanUseContainers: + if (privOn) + message = app.GetString( + IDS_PRIV_USE_CONTAINERS_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_USE_CONTAINERS_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackAnimals: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_ATTACK_ANIMAL_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackMobs: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackPlayers: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_ATTACK_PLAYER_TOGGLE_OFF); + break; + default: + break; + }; + } + switch (priv) { + case Player::ePlayerGamePrivilege_Op: + if (privOn) + message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_OFF); + break; + default: + break; + }; + if (app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0) { + switch (priv) { + case Player::ePlayerGamePrivilege_CanFly: + if (privOn) + message = app.GetString(IDS_PRIV_FLY_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_FLY_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_ClassicHunger: + if (privOn) + message = + app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_Invisible: + if (privOn) + message = + app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_Invulnerable: + if (privOn) + message = + app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleInvisible: + if (privOn) + message = + app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_CAN_INVISIBLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleFly: + if (privOn) + message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleClassicHunger: + if (privOn) + message = app.GetString( + IDS_PRIV_CAN_EXHAUSTION_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_CAN_EXHAUSTION_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanTeleport: + if (privOn) + message = + app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_OFF); + break; + default: + break; + }; + } + if (!message.empty()) + minecraft->gui->addMessage(message, userIndex); + } + } } -void ClientConnection::handleKeepAlive(std::shared_ptr packet) -{ - send(std::shared_ptr(new KeepAlivePacket(packet->id))); +void ClientConnection::handleKeepAlive( + std::shared_ptr packet) { + send(std::shared_ptr(new KeepAlivePacket(packet->id))); } -void ClientConnection::handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - player->abilities.flying = playerAbilitiesPacket->isFlying(); - player->abilities.instabuild = playerAbilitiesPacket->canInstabuild(); - player->abilities.invulnerable = playerAbilitiesPacket->isInvulnerable(); - player->abilities.mayfly = playerAbilitiesPacket->canFly(); - player->abilities.setFlyingSpeed(playerAbilitiesPacket->getFlyingSpeed()); +void ClientConnection::handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket) { + std::shared_ptr player = minecraft->localplayers[m_userIndex]; + player->abilities.flying = playerAbilitiesPacket->isFlying(); + player->abilities.instabuild = playerAbilitiesPacket->canInstabuild(); + player->abilities.invulnerable = playerAbilitiesPacket->isInvulnerable(); + player->abilities.mayfly = playerAbilitiesPacket->canFly(); + player->abilities.setFlyingSpeed(playerAbilitiesPacket->getFlyingSpeed()); } -void ClientConnection::handleSoundEvent(std::shared_ptr packet) -{ - minecraft->level->playLocalSound(packet->getX(), packet->getY(), packet->getZ(), packet->getSound(), packet->getVolume(), packet->getPitch()); +void ClientConnection::handleSoundEvent( + std::shared_ptr packet) { + minecraft->level->playLocalSound(packet->getX(), packet->getY(), + packet->getZ(), packet->getSound(), + packet->getVolume(), packet->getPitch()); } -void ClientConnection::handleCustomPayload(std::shared_ptr customPayloadPacket) -{ - if (CustomPayloadPacket::TRADER_LIST_PACKET.compare(customPayloadPacket->identifier) == 0) - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream input(&bais); - int containerId = input.readInt(); - if (ui.IsSceneInStack(m_userIndex, eUIScene_TradingMenu) && containerId == minecraft->localplayers[m_userIndex]->containerMenu->containerId) - { - std::shared_ptr trader = nullptr; +void ClientConnection::handleCustomPayload( + std::shared_ptr customPayloadPacket) { + if (CustomPayloadPacket::TRADER_LIST_PACKET.compare( + customPayloadPacket->identifier) == 0) { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream input(&bais); + int containerId = input.readInt(); + if (ui.IsSceneInStack(m_userIndex, eUIScene_TradingMenu) && + containerId == minecraft->localplayers[m_userIndex] + ->containerMenu->containerId) { + std::shared_ptr trader = nullptr; #ifdef _XBOX - HXUIOBJ scene = app.GetCurrentScene(m_userIndex); - HXUICLASS thisClass = XuiFindClass( L"CXuiSceneTrading" ); - HXUICLASS objClass = XuiGetObjectClass( scene ); + HXUIOBJ scene = app.GetCurrentScene(m_userIndex); + HXUICLASS thisClass = XuiFindClass(L"CXuiSceneTrading"); + HXUICLASS objClass = XuiGetObjectClass(scene); - // Also returns TRUE if they are the same (which is what we want) - if( XuiClassDerivesFrom( objClass, thisClass ) ) - { - CXuiSceneTrading *screen; - HRESULT hr = XuiObjectFromHandle(scene, (void **) &screen); - if (FAILED(hr)) return; - trader = screen->getMerchant(); - } + // Also returns TRUE if they are the same (which is what we want) + if (XuiClassDerivesFrom(objClass, thisClass)) { + CXuiSceneTrading* screen; + HRESULT hr = XuiObjectFromHandle(scene, (void**)&screen); + if (FAILED(hr)) return; + trader = screen->getMerchant(); + } #else - UIScene *scene = ui.GetTopScene(m_userIndex, eUILayer_Scene); - UIScene_TradingMenu *screen = (UIScene_TradingMenu *)scene; - trader = screen->getMerchant(); + UIScene* scene = ui.GetTopScene(m_userIndex, eUILayer_Scene); + UIScene_TradingMenu* screen = (UIScene_TradingMenu*)scene; + trader = screen->getMerchant(); #endif - - MerchantRecipeList *recipeList = MerchantRecipeList::createFromStream(&input); - trader->overrideOffers(recipeList); - } - } + + MerchantRecipeList* recipeList = + MerchantRecipeList::createFromStream(&input); + trader->overrideOffers(recipeList); + } + } } -Connection *ClientConnection::getConnection() -{ - return connection; -} +Connection* ClientConnection::getConnection() { return connection; } // 4J Added -void ClientConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) - { - app.SetGameHostOption(eGameHostOption_All, packet->data); - } - else if(packet->action==ServerSettingsChangedPacket::HOST_DIFFICULTY) - { - for(unsigned int i = 0; i < minecraft->levels.length; ++i) - { - if( minecraft->levels[i] != NULL ) - { - app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); - minecraft->levels[i]->difficulty = packet->data; - } - } - } - else - { - //options - //minecraft->options->SetGamertagSetting((packet->data==0)?false:true); - app.SetGameHostOption(eGameHostOption_Gamertags, packet->data); - } - +void ClientConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + if (packet->action == ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) { + app.SetGameHostOption(eGameHostOption_All, packet->data); + } else if (packet->action == ServerSettingsChangedPacket::HOST_DIFFICULTY) { + for (unsigned int i = 0; i < minecraft->levels.length; ++i) { + if (minecraft->levels[i] != NULL) { + app.DebugPrintf( + "ClientConnection::handleServerSettingsChanged - " + "Difficulty = %d", + packet->data); + minecraft->levels[i]->difficulty = packet->data; + } + } + } else { + // options + // minecraft->options->SetGamertagSetting((packet->data==0)?false:true); + app.SetGameHostOption(eGameHostOption_Gamertags, packet->data); + } } -void ClientConnection::handleXZ(std::shared_ptr packet) -{ - if(packet->action==XZPacket::STRONGHOLD) - { - minecraft->levels[0]->getLevelData()->setXStronghold(packet->x); - minecraft->levels[0]->getLevelData()->setZStronghold(packet->z); - minecraft->levels[0]->getLevelData()->setHasStronghold(); - } +void ClientConnection::handleXZ(std::shared_ptr packet) { + if (packet->action == XZPacket::STRONGHOLD) { + minecraft->levels[0]->getLevelData()->setXStronghold(packet->x); + minecraft->levels[0]->getLevelData()->setZStronghold(packet->z); + minecraft->levels[0]->getLevelData()->setHasStronghold(); + } } -void ClientConnection::handleUpdateProgress(std::shared_ptr packet) -{ - if(!g_NetworkManager.IsHost() ) Minecraft::GetInstance()->progressRenderer->progressStagePercentage( packet->m_percentage ); +void ClientConnection::handleUpdateProgress( + std::shared_ptr packet) { + if (!g_NetworkManager.IsHost()) + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + packet->m_percentage); } -void ClientConnection::handleUpdateGameRuleProgressPacket(std::shared_ptr packet) -{ - const wchar_t *string = app.GetGameRulesString(packet->m_messageId); - if(string != NULL) - { - std::wstring message(string); - message = GameRuleDefinition::generateDescriptionString(packet->m_definitionType,message,packet->m_data.data,packet->m_data.length); - if(minecraft->localgameModes[m_userIndex]!=NULL) - { - minecraft->localgameModes[m_userIndex]->getTutorial()->setMessage(message, packet->m_icon, packet->m_auxValue); - } - } - // If this rule has a data tag associated with it, then we save that in user profile data - if(packet->m_dataTag > 0 && packet->m_dataTag <= 32) - { - app.DebugPrintf("handleUpdateGameRuleProgressPacket: Data tag is in range, so updating profile data\n"); - app.SetSpecialTutorialCompletionFlag(m_userIndex, packet->m_dataTag - 1); - } - delete [] packet->m_data.data; +void ClientConnection::handleUpdateGameRuleProgressPacket( + std::shared_ptr packet) { + const wchar_t* string = app.GetGameRulesString(packet->m_messageId); + if (string != NULL) { + std::wstring message(string); + message = GameRuleDefinition::generateDescriptionString( + packet->m_definitionType, message, packet->m_data.data, + packet->m_data.length); + if (minecraft->localgameModes[m_userIndex] != NULL) { + minecraft->localgameModes[m_userIndex]->getTutorial()->setMessage( + message, packet->m_icon, packet->m_auxValue); + } + } + // If this rule has a data tag associated with it, then we save that in user + // profile data + if (packet->m_dataTag > 0 && packet->m_dataTag <= 32) { + app.DebugPrintf( + "handleUpdateGameRuleProgressPacket: Data tag is in range, so " + "updating profile data\n"); + app.SetSpecialTutorialCompletionFlag(m_userIndex, + packet->m_dataTag - 1); + } + delete[] packet->m_data.data; } // 4J Stu - TU-1 hotfix -// Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost -int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - // 4J-PB - if they have a trial texture pack, they don't get to save the world - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; +// Fix for #13191 - The host of a game can get a message informing them that the +// connection to the server has been lost +int ClientConnection::HostDisconnectReturned( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + // 4J-PB - if they have a trial texture pack, they don't get to save the + // world + if (!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + DLCTexturePack* pDLCTexPack = (DLCTexturePack*)tPack; - DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - // no upsell, we're about to quit - MinecraftServer::getInstance()->setSaveOnExit( false ); - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - } - } + DLCPack* pDLCPack = + pDLCTexPack->getDLCInfoParentPack(); // tPack->getDLCPack(); + if (!pDLCPack->hasPurchasedFile(DLCManager::e_DLCType_Texture, L"")) { + // no upsell, we're about to quit + MinecraftServer::getInstance()->setSaveOnExit(false); + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + } + } #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Give the player the option to save their game - // does the save exist? - bool bSaveExists; - StorageManager.DoesSaveExist(&bSaveExists); - // 4J-PB - we check if the save exists inside the libs - // we need to ask if they are sure they want to overwrite the existing game - if(bSaveExists && StorageManager.GetSaveDisabled()) - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_CONFIRM_CANCEL; - uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL, app.GetStringTable()); - } - else + // Give the player the option to save their game + // does the save exist? + bool bSaveExists; + StorageManager.DoesSaveExist(&bSaveExists); + // 4J-PB - we check if the save exists inside the libs + // we need to ask if they are sure they want to overwrite the existing game + if (bSaveExists && StorageManager.GetSaveDisabled()) { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_CONFIRM_CANCEL; + uiIDA[1] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, + 2, ProfileManager.GetPrimaryPad(), + &ClientConnection::ExitGameAndSaveReturned, NULL, + app.GetStringTable()); + } else #else - // Give the player the option to save their game - // does the save exist? - bool bSaveExists; - StorageManager.DoesSaveExist(&bSaveExists); - // 4J-PB - we check if the save exists inside the libs - // we need to ask if they are sure they want to overwrite the existing game - if(bSaveExists) - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_CONFIRM_CANCEL; - uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL, app.GetStringTable()); - } - else + // Give the player the option to save their game + // does the save exist? + bool bSaveExists; + StorageManager.DoesSaveExist(&bSaveExists); + // 4J-PB - we check if the save exists inside the libs + // we need to ask if they are sure they want to overwrite the existing game + if (bSaveExists) { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_CONFIRM_CANCEL; + uiIDA[1] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, + 2, ProfileManager.GetPrimaryPad(), + &ClientConnection::ExitGameAndSaveReturned, NULL, + app.GetStringTable()); + } else #endif - { + { #if defined(_XBOX_ONE) || defined(__ORBIS__) - StorageManager.SetSaveDisabled(false); + StorageManager.SetSaveDisabled(false); #endif - MinecraftServer::getInstance()->setSaveOnExit( true ); - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - } + MinecraftServer::getInstance()->setSaveOnExit(true); + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + } - return 0; + return 0; } -int ClientConnection::ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - // results switched for this dialog - if(result==C4JStorage::EMessage_ResultDecline) - { - //INT saveOrCheckpointId = 0; - //bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); - //SentientManager.RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), saveOrCheckpointId); +int ClientConnection::ExitGameAndSaveReturned( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + // results switched for this dialog + if (result == C4JStorage::EMessage_ResultDecline) { + // INT saveOrCheckpointId = 0; + // bool validSave = + // StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); + // SentientManager.RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), + // saveOrCheckpointId); #if defined(_XBOX_ONE) || defined(__ORBIS__) - StorageManager.SetSaveDisabled(false); + StorageManager.SetSaveDisabled(false); #endif - MinecraftServer::getInstance()->setSaveOnExit( true ); - } - else - { - MinecraftServer::getInstance()->setSaveOnExit( false ); - } - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - return 0; + MinecraftServer::getInstance()->setSaveOnExit(true); + } else { + MinecraftServer::getInstance()->setSaveOnExit(false); + } + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + return 0; } -// -std::wstring ClientConnection::GetDisplayNameByGamertag(std::wstring gamertag) -{ +// +std::wstring ClientConnection::GetDisplayNameByGamertag(std::wstring gamertag) { #ifdef _DURANGO - std::wstring displayName = g_NetworkManager.GetDisplayNameByGamertag(gamertag); - return displayName; + std::wstring displayName = + g_NetworkManager.GetDisplayNameByGamertag(gamertag); + return displayName; #else - return gamertag; + return gamertag; #endif } diff --git a/Minecraft.Client/Network/ClientConnection.h b/Minecraft.Client/Network/ClientConnection.h index f901e98fa..58d1dfd77 100644 --- a/Minecraft.Client/Network/ClientConnection.h +++ b/Minecraft.Client/Network/ClientConnection.h @@ -6,81 +6,97 @@ class SavedDataStorage; class Socket; class MultiplayerLocalPlayer; -class ClientConnection : public PacketListener -{ +class ClientConnection : public PacketListener { private: - enum eClientConnectionConnectingState - { - eCCPreLoginSent = 0, - eCCPreLoginReceived, - eCCLoginSent, - eCCLoginReceived, - eCCConnected - }; + enum eClientConnectionConnectingState { + eCCPreLoginSent = 0, + eCCPreLoginReceived, + eCCLoginSent, + eCCLoginReceived, + eCCConnected + }; + private: - bool done; - Connection *connection; + bool done; + Connection* connection; + public: - std::wstring message; - bool createdOk; // 4J added + std::wstring message; + bool createdOk; // 4J added private: - Minecraft *minecraft; - MultiPlayerLevel *level; + Minecraft* minecraft; + MultiPlayerLevel* level; bool started; - // 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm not going to use it at the moment - //Map playerInfoMap = new HashMap(); + // 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm + // not going to use it at the moment + // Map playerInfoMap = new HashMap(); public: - //List playerInfos = new ArrayList(); + // List playerInfos = new ArrayList(); - int maxPlayers; + int maxPlayers; public: - bool isStarted() { return started; } // 4J Added - bool isClosed() { return done; } // 4J Added - Socket *getSocket() { return connection->getSocket(); } // 4J Added + bool isStarted() { return started; } // 4J Added + bool isClosed() { return done; } // 4J Added + Socket* getSocket() { return connection->getSocket(); } // 4J Added private: - int m_userIndex; // 4J Added + int m_userIndex; // 4J Added public: - SavedDataStorage *savedDataStorage; - ClientConnection(Minecraft *minecraft, const std::wstring& ip, int port); - ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex = -1); - ~ClientConnection(); + SavedDataStorage* savedDataStorage; + ClientConnection(Minecraft* minecraft, const std::wstring& ip, int port); + ClientConnection(Minecraft* minecraft, Socket* socket, int iUserIndex = -1); + ~ClientConnection(); void tick(); - INetworkPlayer *getNetworkPlayer(); + INetworkPlayer* getNetworkPlayer(); virtual void handleLogin(std::shared_ptr packet); virtual void handleAddEntity(std::shared_ptr packet); - virtual void handleAddExperienceOrb(std::shared_ptr packet); - virtual void handleAddGlobalEntity(std::shared_ptr packet); + virtual void handleAddExperienceOrb( + std::shared_ptr packet); + virtual void handleAddGlobalEntity( + std::shared_ptr packet); virtual void handleAddPainting(std::shared_ptr packet); - virtual void handleSetEntityMotion(std::shared_ptr packet); - virtual void handleSetEntityData(std::shared_ptr packet); + virtual void handleSetEntityMotion( + std::shared_ptr packet); + virtual void handleSetEntityData( + std::shared_ptr packet); virtual void handleAddPlayer(std::shared_ptr packet); - virtual void handleTeleportEntity(std::shared_ptr packet); + virtual void handleTeleportEntity( + std::shared_ptr packet); virtual void handleMoveEntity(std::shared_ptr packet); - virtual void handleRotateMob(std::shared_ptr packet); - virtual void handleMoveEntitySmall(std::shared_ptr packet); - virtual void handleRemoveEntity(std::shared_ptr packet); - virtual void handleMovePlayer(std::shared_ptr packet); + virtual void handleRotateMob(std::shared_ptr packet); + virtual void handleMoveEntitySmall( + std::shared_ptr packet); + virtual void handleRemoveEntity( + std::shared_ptr packet); + virtual void handleMovePlayer(std::shared_ptr packet); - Random *random; - - // 4J Added - virtual void handleChunkVisibilityArea(std::shared_ptr packet); + Random* random; - virtual void handleChunkVisibility(std::shared_ptr packet); - virtual void handleChunkTilesUpdate(std::shared_ptr packet); - virtual void handleBlockRegionUpdate(std::shared_ptr packet); + // 4J Added + virtual void handleChunkVisibilityArea( + std::shared_ptr packet); + + virtual void handleChunkVisibility( + std::shared_ptr packet); + virtual void handleChunkTilesUpdate( + std::shared_ptr packet); + virtual void handleBlockRegionUpdate( + std::shared_ptr packet); virtual void handleTileUpdate(std::shared_ptr packet); virtual void handleDisconnect(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); void sendAndDisconnect(std::shared_ptr packet); void send(std::shared_ptr packet); - virtual void handleTakeItemEntity(std::shared_ptr packet); + virtual void handleTakeItemEntity( + std::shared_ptr packet); virtual void handleChat(std::shared_ptr packet); virtual void handleAnimate(std::shared_ptr packet); - virtual void handleEntityActionAtPosition(std::shared_ptr packet); + virtual void handleEntityActionAtPosition( + std::shared_ptr packet); virtual void handlePreLogin(std::shared_ptr packet); void close(); virtual void handleAddMob(std::shared_ptr packet); @@ -88,53 +104,79 @@ public: virtual void handleSetSpawn(std::shared_ptr packet); virtual void handleRidePacket(std::shared_ptr packet); virtual void handleEntityEvent(std::shared_ptr packet); + private: - std::shared_ptr getEntity(int entityId); - std::wstring GetDisplayNameByGamertag(std::wstring gamertag); + std::shared_ptr getEntity(int entityId); + std::wstring GetDisplayNameByGamertag(std::wstring gamertag); + public: virtual void handleSetHealth(std::shared_ptr packet); - virtual void handleSetExperience(std::shared_ptr packet); + virtual void handleSetExperience( + std::shared_ptr packet); virtual void handleRespawn(std::shared_ptr packet); virtual void handleExplosion(std::shared_ptr packet); - virtual void handleContainerOpen(std::shared_ptr packet); - virtual void handleContainerSetSlot(std::shared_ptr packet); + virtual void handleContainerOpen( + std::shared_ptr packet); + virtual void handleContainerSetSlot( + std::shared_ptr packet); virtual void handleContainerAck(std::shared_ptr packet); - virtual void handleContainerContent(std::shared_ptr packet); + virtual void handleContainerContent( + std::shared_ptr packet); virtual void handleSignUpdate(std::shared_ptr packet); - virtual void handleTileEntityData(std::shared_ptr packet); - virtual void handleContainerSetData(std::shared_ptr packet); - virtual void handleSetEquippedItem(std::shared_ptr packet); - virtual void handleContainerClose(std::shared_ptr packet); + virtual void handleTileEntityData( + std::shared_ptr packet); + virtual void handleContainerSetData( + std::shared_ptr packet); + virtual void handleSetEquippedItem( + std::shared_ptr packet); + virtual void handleContainerClose( + std::shared_ptr packet); virtual void handleTileEvent(std::shared_ptr packet); - virtual void handleTileDestruction(std::shared_ptr packet); - virtual bool canHandleAsyncPackets(); - virtual void handleGameEvent(std::shared_ptr gameEventPacket); - virtual void handleComplexItemData(std::shared_ptr packet); + virtual void handleTileDestruction( + std::shared_ptr packet); + virtual bool canHandleAsyncPackets(); + virtual void handleGameEvent( + std::shared_ptr gameEventPacket); + virtual void handleComplexItemData( + std::shared_ptr packet); virtual void handleLevelEvent(std::shared_ptr packet); virtual void handleAwardStat(std::shared_ptr packet); - virtual void handleUpdateMobEffect(std::shared_ptr packet); - virtual void handleRemoveMobEffect(std::shared_ptr packet); - virtual bool isServerPacketListener(); - virtual void handlePlayerInfo(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); - virtual void handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket); - virtual void handleSoundEvent(std::shared_ptr packet); - virtual void handleCustomPayload(std::shared_ptr customPayloadPacket); - virtual Connection *getConnection(); + virtual void handleUpdateMobEffect( + std::shared_ptr packet); + virtual void handleRemoveMobEffect( + std::shared_ptr packet); + virtual bool isServerPacketListener(); + virtual void handlePlayerInfo(std::shared_ptr packet); + virtual void handleKeepAlive(std::shared_ptr packet); + virtual void handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket); + virtual void handleSoundEvent(std::shared_ptr packet); + virtual void handleCustomPayload( + std::shared_ptr customPayloadPacket); + virtual Connection* getConnection(); - // 4J Added - virtual void handleServerSettingsChanged(std::shared_ptr packet); - virtual void handleTexture(std::shared_ptr packet); - virtual void handleTextureAndGeometry(std::shared_ptr packet); - virtual void handleUpdateProgress(std::shared_ptr packet); + // 4J Added + virtual void handleServerSettingsChanged( + std::shared_ptr packet); + virtual void handleTexture(std::shared_ptr packet); + virtual void handleTextureAndGeometry( + std::shared_ptr packet); + virtual void handleUpdateProgress( + std::shared_ptr packet); - // 4J Added - static int HostDisconnectReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); - static int ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); - virtual void handleTextureChange(std::shared_ptr packet); - virtual void handleTextureAndGeometryChange(std::shared_ptr packet); - virtual void handleUpdateGameRuleProgressPacket(std::shared_ptr packet); - virtual void handleXZ(std::shared_ptr packet); + // 4J Added + static int HostDisconnectReturned(void* pParam, int iPad, + C4JStorage::EMessageResult result); + static int ExitGameAndSaveReturned(void* pParam, int iPad, + C4JStorage::EMessageResult result); + virtual void handleTextureChange( + std::shared_ptr packet); + virtual void handleTextureAndGeometryChange( + std::shared_ptr packet); + virtual void handleUpdateGameRuleProgressPacket( + std::shared_ptr packet); + virtual void handleXZ(std::shared_ptr packet); - void displayPrivilegeChanges(std::shared_ptr player, unsigned int oldPrivileges); + void displayPrivilegeChanges(std::shared_ptr player, + unsigned int oldPrivileges); }; diff --git a/Minecraft.Client/Network/MultiPlayerChunkCache.cpp b/Minecraft.Client/Network/MultiPlayerChunkCache.cpp index f4e3f7d0b..74648c2ad 100644 --- a/Minecraft.Client/Network/MultiPlayerChunkCache.cpp +++ b/Minecraft.Client/Network/MultiPlayerChunkCache.cpp @@ -10,297 +10,287 @@ #include "../../Minecraft.World/Blocks/Tile.h" #include "../../Minecraft.World/Level/WaterLevelChunk.h" -MultiPlayerChunkCache::MultiPlayerChunkCache(Level *level) -{ - XZSIZE = level->dimension->getXZSize(); // 4J Added - XZOFFSET = XZSIZE/2; // 4J Added - m_XZSize = XZSIZE; - hasData = new bool[XZSIZE * XZSIZE]; - memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE); +MultiPlayerChunkCache::MultiPlayerChunkCache(Level* level) { + XZSIZE = level->dimension->getXZSize(); // 4J Added + XZOFFSET = XZSIZE / 2; // 4J Added + m_XZSize = XZSIZE; + hasData = new bool[XZSIZE * XZSIZE]; + memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE); - emptyChunk = new EmptyLevelChunk(level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0); + emptyChunk = new EmptyLevelChunk( + level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0); - // For normal world dimension, create a chunk that can be used to create the illusion of infinite water at the edge of the world - if( level->dimension->id == 0 ) - { - byteArray bytes = byteArray(16 * 16 * 128); + // For normal world dimension, create a chunk that can be used to create the + // illusion of infinite water at the edge of the world + if (level->dimension->id == 0) { + byteArray bytes = byteArray(16 * 16 * 128); - // Superflat.... make grass, not water... - if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - unsigned char tileId = 0; - if( y == 3 ) tileId = Tile::grass_Id; - else if( y <= 2 ) tileId = Tile::dirt_Id; + // Superflat.... make grass, not water... + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + unsigned char tileId = 0; + if (y == 3) + tileId = Tile::grass_Id; + else if (y <= 2) + tileId = Tile::dirt_Id; - bytes[x << 11 | z << 7 | y] = tileId; - } - } - else - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - unsigned char tileId = 0; - if( y <= ( level->getSeaLevel() - 10 ) ) tileId = Tile::rock_Id; - else if( y < level->getSeaLevel() ) tileId = Tile::calmWater_Id; + bytes[x << 11 | z << 7 | y] = tileId; + } + } else { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + unsigned char tileId = 0; + if (y <= (level->getSeaLevel() - 10)) + tileId = Tile::rock_Id; + else if (y < level->getSeaLevel()) + tileId = Tile::calmWater_Id; - bytes[x << 11 | z << 7 | y] = tileId; - } - } + bytes[x << 11 | z << 7 | y] = tileId; + } + } - waterChunk = new WaterLevelChunk(level, bytes, 0, 0); + waterChunk = new WaterLevelChunk(level, bytes, 0, 0); - delete[] bytes.data; + delete[] bytes.data; - if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - if( y >= 3 ) - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); - } - } - } - else - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - if( y >= ( level->getSeaLevel() - 1 ) ) - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); - } - else - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,2); - } - } - } - } - else - { - waterChunk = NULL; - } + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + if (y >= 3) { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 15); + } + } + } else { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + if (y >= (level->getSeaLevel() - 1)) { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 15); + } else { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 2); + } + } + } + } else { + waterChunk = NULL; + } - this->level = level; + this->level = level; - this->cache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); - InitializeCriticalSectionAndSpinCount(&m_csLoadCreate,4000); + this->cache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); + InitializeCriticalSectionAndSpinCount(&m_csLoadCreate, 4000); } -MultiPlayerChunkCache::~MultiPlayerChunkCache() -{ - delete emptyChunk; - delete waterChunk; - delete cache; - delete hasData; +MultiPlayerChunkCache::~MultiPlayerChunkCache() { + delete emptyChunk; + delete waterChunk; + delete cache; + delete hasData; - AUTO_VAR(itEnd, loadedChunkList.end()); - for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) - delete *it; + AUTO_VAR(itEnd, loadedChunkList.end()); + for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) delete *it; - DeleteCriticalSection(&m_csLoadCreate); + DeleteCriticalSection(&m_csLoadCreate); } - -bool MultiPlayerChunkCache::hasChunk(int x, int z) -{ - // This cache always claims to have chunks, although it might actually just return empty data if it doesn't have anything - return true; +bool MultiPlayerChunkCache::hasChunk(int x, int z) { + // This cache always claims to have chunks, although it might actually just + // return empty data if it doesn't have anything + return true; } // 4J added - find out if we actually really do have a chunk in our cache -bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if we aren't, then consider that we do have that chunk as we'll be able to use the water chunk there - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return true; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; - int idx = ix * XZSIZE + iz; +bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level - if we aren't, then consider + // that we do have that chunk as we'll be able to use the water chunk there + if ((ix < 0) || (ix >= XZSIZE)) return true; + if ((iz < 0) || (iz >= XZSIZE)) return true; + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) - { - return false; - } - return hasData[idx]; + LevelChunk* chunk = cache[idx]; + if (chunk == NULL) { + return false; + } + return hasData[idx]; } -void MultiPlayerChunkCache::drop(int x, int z) -{ - // 4J Stu - We do want to drop any entities in the chunks, especially for the case when a player is dead as they will - // not get the RemoveEntity packet if an entity is removed. - LevelChunk *chunk = getChunk(x, z); - if (!chunk->isEmpty()) - { - // Added parameter here specifies that we don't want to delete tile entities, as they won't get recreated unless they've got update packets - // The tile entities are in general only created on the client by virtue of the chunk rebuild - chunk->unload(false); +void MultiPlayerChunkCache::drop(int x, int z) { + // 4J Stu - We do want to drop any entities in the chunks, especially for + // the case when a player is dead as they will not get the RemoveEntity + // packet if an entity is removed. + LevelChunk* chunk = getChunk(x, z); + if (!chunk->isEmpty()) { + // Added parameter here specifies that we don't want to delete tile + // entities, as they won't get recreated unless they've got update + // packets The tile entities are in general only created on the client + // by virtue of the chunk rebuild + chunk->unload(false); - // 4J - We just want to clear out the entities in the chunk, but everything else should be valid - chunk->loaded = true; + // 4J - We just want to clear out the entities in the chunk, but + // everything else should be valid + chunk->loaded = true; } } -LevelChunk *MultiPlayerChunkCache::create(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - LevelChunk *lastChunk = chunk; +LevelChunk* MultiPlayerChunkCache::create(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + if ((iz < 0) || (iz >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + int idx = ix * XZSIZE + iz; + LevelChunk* chunk = cache[idx]; + LevelChunk* lastChunk = chunk; - if( chunk == NULL ) - { - EnterCriticalSection(&m_csLoadCreate); + if (chunk == NULL) { + EnterCriticalSection(&m_csLoadCreate); - //LevelChunk *chunk; - if( g_NetworkManager.IsHost() ) // force here to disable sharing of data - { - // 4J-JEV: We are about to use shared data, abort if the server is stopped and the data is deleted. - if (MinecraftServer::getInstance()->serverHalted()) return NULL; + // LevelChunk *chunk; + if (g_NetworkManager.IsHost()) // force here to disable sharing of data + { + // 4J-JEV: We are about to use shared data, abort if the server is + // stopped and the data is deleted. + if (MinecraftServer::getInstance()->serverHalted()) return NULL; - // If we're the host, then don't create the chunk, share data from the server's copy + // If we're the host, then don't create the chunk, share data from + // the server's copy #ifdef _LARGE_WORLDS - LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunkLoadedOrUnloaded(x,z); + LevelChunk* serverChunk = + MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunkLoadedOrUnloaded(x, z); #else - LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunk(x,z); + LevelChunk* serverChunk = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunk(x, z); #endif - chunk = new LevelChunk(level, x, z, serverChunk); - // Let renderer know that this chunk has been created - it might have made render data from the EmptyChunk if it got to a chunk before the server sent it - level->setTilesDirty( x * 16 , 0 , z * 16 , x * 16 + 15, 127, z * 16 + 15); - hasData[idx] = true; - } - else - { - // Passing an empty array into the LevelChunk ctor, which it now detects and sets up the chunk as compressed & empty - byteArray bytes; + chunk = new LevelChunk(level, x, z, serverChunk); + // Let renderer know that this chunk has been created - it might + // have made render data from the EmptyChunk if it got to a chunk + // before the server sent it + level->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, 127, + z * 16 + 15); + hasData[idx] = true; + } else { + // Passing an empty array into the LevelChunk ctor, which it now + // detects and sets up the chunk as compressed & empty + byteArray bytes; - chunk = new LevelChunk(level, bytes, x, z); + chunk = new LevelChunk(level, bytes, x, z); - // 4J - changed to use new methods for lighting - chunk->setSkyLightDataAllBright(); -// Arrays::fill(chunk->skyLight->data, (uint8_t) 255); - } - - chunk->loaded = true; + // 4J - changed to use new methods for lighting + chunk->setSkyLightDataAllBright(); + // Arrays::fill(chunk->skyLight->data, (uint8_t) + //255); + } - LeaveCriticalSection(&m_csLoadCreate); + chunk->loaded = true; -#if ( defined _WIN64 || defined __LP64__ ) - if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk ) + LeaveCriticalSection(&m_csLoadCreate); + +#if (defined _WIN64 || defined __LP64__) + if (InterlockedCompareExchangeRelease64( + (LONG64*)&cache[idx], (LONG64)chunk, (LONG64)lastChunk) == + (LONG64)lastChunk) #else - if( InterlockedCompareExchangeRelease((LONG *)&cache[idx],(LONG)chunk,(LONG)lastChunk) == (LONG)lastChunk ) -#endif // _DURANGO - { - // If we're sharing with the server, we'll need to calculate our heightmap now, which isn't shared. If we aren't sharing with the server, - // then this will be calculated when the chunk data arrives. - if( g_NetworkManager.IsHost() ) - { - chunk->recalcHeightmapOnly(); - } + if (InterlockedCompareExchangeRelease((LONG*)&cache[idx], (LONG)chunk, + (LONG)lastChunk) == + (LONG)lastChunk) +#endif // _DURANGO + { + // If we're sharing with the server, we'll need to calculate our + // heightmap now, which isn't shared. If we aren't sharing with the + // server, then this will be calculated when the chunk data arrives. + if (g_NetworkManager.IsHost()) { + chunk->recalcHeightmapOnly(); + } - // Successfully updated the cache - EnterCriticalSection(&m_csLoadCreate); - loadedChunkList.push_back(chunk); - LeaveCriticalSection(&m_csLoadCreate); - } - else - { - // Something else must have updated the cache. Return that chunk and discard this one. This really shouldn't be happening - // in multiplayer - delete chunk; - return cache[idx]; - } + // Successfully updated the cache + EnterCriticalSection(&m_csLoadCreate); + loadedChunkList.push_back(chunk); + LeaveCriticalSection(&m_csLoadCreate); + } else { + // Something else must have updated the cache. Return that chunk and + // discard this one. This really shouldn't be happening in + // multiplayer + delete chunk; + return cache[idx]; + } - } - else - { - chunk->load(); - } + } else { + chunk->load(); + } - return chunk; + return chunk; } -LevelChunk *MultiPlayerChunkCache::getChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - int idx = ix * XZSIZE + iz; +LevelChunk* MultiPlayerChunkCache::getChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + if ((iz < 0) || (iz >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) - { - return emptyChunk; - } - else - { - return chunk; - } + LevelChunk* chunk = cache[idx]; + if (chunk == NULL) { + return emptyChunk; + } else { + return chunk; + } } -bool MultiPlayerChunkCache::save(bool force, ProgressListener *progressListener) -{ - return true; +bool MultiPlayerChunkCache::save(bool force, + ProgressListener* progressListener) { + return true; } -bool MultiPlayerChunkCache::tick() -{ - return false; +bool MultiPlayerChunkCache::tick() { return false; } + +bool MultiPlayerChunkCache::shouldSave() { return false; } + +void MultiPlayerChunkCache::postProcess(ChunkSource* parent, int x, int z) {} + +std::vector* MultiPlayerChunkCache::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + return NULL; } -bool MultiPlayerChunkCache::shouldSave() -{ - return false; +TilePos* MultiPlayerChunkCache::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } -void MultiPlayerChunkCache::postProcess(ChunkSource *parent, int x, int z) -{ +std::wstring MultiPlayerChunkCache::gatherStats() { + EnterCriticalSection(&m_csLoadCreate); + int size = (int)loadedChunkList.size(); + LeaveCriticalSection(&m_csLoadCreate); + return L"MultiplayerChunkCache: " + _toString(size); } -std::vector *MultiPlayerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - return NULL; -} - -TilePos *MultiPlayerChunkCache::findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z) -{ - return NULL; -} - -std::wstring MultiPlayerChunkCache::gatherStats() -{ - EnterCriticalSection(&m_csLoadCreate); - int size = (int)loadedChunkList.size(); - LeaveCriticalSection(&m_csLoadCreate); - return L"MultiplayerChunkCache: " + _toString(size); - -} - -void MultiPlayerChunkCache::dataReceived(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return; - int idx = ix * XZSIZE + iz; - hasData[idx] = true; +void MultiPlayerChunkCache::dataReceived(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return; + if ((iz < 0) || (iz >= XZSIZE)) return; + int idx = ix * XZSIZE + iz; + hasData[idx] = true; } \ No newline at end of file diff --git a/Minecraft.Client/Network/MultiPlayerChunkCache.h b/Minecraft.Client/Network/MultiPlayerChunkCache.h index a9df81eac..09710048d 100644 --- a/Minecraft.Client/Network/MultiPlayerChunkCache.h +++ b/Minecraft.Client/Network/MultiPlayerChunkCache.h @@ -3,45 +3,48 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" #include "../../Minecraft.World/Level/RandomLevelSource.h" - class ServerChunkCache; -// 4J - various alterations here to make this thread safe, and operate as a fixed sized cache -class MultiPlayerChunkCache : public ChunkSource -{ - friend class LevelRenderer; +// 4J - various alterations here to make this thread safe, and operate as a +// fixed sized cache +class MultiPlayerChunkCache : public ChunkSource { + friend class LevelRenderer; + private: - LevelChunk *emptyChunk; - LevelChunk *waterChunk; + LevelChunk* emptyChunk; + LevelChunk* waterChunk; - std::vector loadedChunkList; + std::vector loadedChunkList; - LevelChunk **cache; - // 4J - added for multithreaded support - CRITICAL_SECTION m_csLoadCreate; - // 4J - size of cache is defined by size of one side - must be even - int XZSIZE; - int XZOFFSET; - bool *hasData; + LevelChunk** cache; + // 4J - added for multithreaded support + CRITICAL_SECTION m_csLoadCreate; + // 4J - size of cache is defined by size of one side - must be even + int XZSIZE; + int XZOFFSET; + bool* hasData; - Level *level; + Level* level; public: - MultiPlayerChunkCache(Level *level); - ~MultiPlayerChunkCache(); + MultiPlayerChunkCache(Level* level); + ~MultiPlayerChunkCache(); virtual bool hasChunk(int x, int z); - virtual bool reallyHasChunk(int x, int z); + virtual bool reallyHasChunk(int x, int z); virtual void drop(int x, int z); - virtual LevelChunk *create(int x, int z); - virtual LevelChunk *getChunk(int x, int z); - virtual bool save(bool force, ProgressListener *progressListener); + virtual LevelChunk* create(int x, int z); + virtual LevelChunk* getChunk(int x, int z); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); - virtual void postProcess(ChunkSource *parent, int x, int z); + virtual void postProcess(ChunkSource* parent, int x, int z); virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); - virtual void dataReceived(int x, int z); // 4J added + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); + virtual void dataReceived(int x, int z); // 4J added - virtual LevelChunk **getCache() { return cache; } // 4J added + virtual LevelChunk** getCache() { return cache; } // 4J added }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PendingConnection.cpp b/Minecraft.Client/Network/PendingConnection.cpp index 80bc0f043..bd86e35e4 100644 --- a/Minecraft.Client/Network/PendingConnection.cpp +++ b/Minecraft.Client/Network/PendingConnection.cpp @@ -19,112 +19,108 @@ // #include "PS3/Network/NetworkPlayerSony.h" // #endif -Random *PendingConnection::random = new Random(); +Random* PendingConnection::random = new Random(); -PendingConnection::PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id) -{ - // 4J - added initialisers - done = false; +PendingConnection::PendingConnection(MinecraftServer* server, Socket* socket, + const std::wstring& id) { + // 4J - added initialisers + done = false; _tick = 0; name = L""; acceptedLogin = nullptr; - loginKey = L""; + loginKey = L""; this->server = server; connection = new Connection(socket, id, this); connection->fakeLag = FAKE_LAG; } -PendingConnection::~PendingConnection() -{ - delete connection; -} +PendingConnection::~PendingConnection() { delete connection; } -void PendingConnection::tick() -{ - if (acceptedLogin != NULL) - { +void PendingConnection::tick() { + if (acceptedLogin != NULL) { this->handleAcceptedLogin(acceptedLogin); acceptedLogin = nullptr; } - if (_tick++ == MAX_TICKS_BEFORE_LOGIN) - { + if (_tick++ == MAX_TICKS_BEFORE_LOGIN) { disconnect(DisconnectPacket::eDisconnect_LoginTooLong); - } - else - { + } else { connection->tick(); } } -void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) -{ - // try { // 4J - removed try/catch -// logger.info("Disconnecting " + getName() + ": " + reason); - fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n", reason, _tick); - app.DebugPrintf("Pending connection disconnect: %d\n", reason ); - connection->send( std::shared_ptr( new DisconnectPacket(reason) ) ); - connection->sendAndQuit(); - done = true; -// } catch (Exception e) { -// e.printStackTrace(); -// } +void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) { + // try { // 4J - removed try/catch + // logger.info("Disconnecting " + getName() + ": " + reason); + fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n", + reason, _tick); + app.DebugPrintf("Pending connection disconnect: %d\n", reason); + connection->send( + std::shared_ptr(new DisconnectPacket(reason))); + connection->sendAndQuit(); + done = true; + // } catch (Exception e) { + // e.printStackTrace(); + // } } -void PendingConnection::handlePreLogin(std::shared_ptr packet) -{ - if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) - { - app.DebugPrintf("Netcode version is %d not equal to %d\n", packet->m_netcodeVersion, MINECRAFT_NET_VERSION); - if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION) - { +void PendingConnection::handlePreLogin(std::shared_ptr packet) { + if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) { + app.DebugPrintf("Netcode version is %d not equal to %d\n", + packet->m_netcodeVersion, MINECRAFT_NET_VERSION); + if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION) { disconnect(DisconnectPacket::eDisconnect_OutdatedServer); - } - else - { + } else { disconnect(DisconnectPacket::eDisconnect_OutdatedClient); } return; } -// printf("Server: handlePreLogin\n"); - name = packet->loginKey; // 4J Stu - Change from the login packet as we know better on client end during the pre-login packet - sendPreLoginResponse(); + // printf("Server: handlePreLogin\n"); + name = + packet->loginKey; // 4J Stu - Change from the login packet as we know + // better on client end during the pre-login packet + sendPreLoginResponse(); } -void PendingConnection::sendPreLoginResponse() -{ - // 4J Stu - Calculate the players with UGC privileges set - PlayerUID *ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS]; - std::uint8_t ugcXuidCount = 0; - std::uint8_t hostIndex = 0; - std::uint8_t ugcFriendsOnlyBits = 0; - char szUniqueMapName[14]; +void PendingConnection::sendPreLoginResponse() { + // 4J Stu - Calculate the players with UGC privileges set + PlayerUID* ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS]; + std::uint8_t ugcXuidCount = 0; + std::uint8_t hostIndex = 0; + std::uint8_t ugcFriendsOnlyBits = 0; + char szUniqueMapName[14]; - StorageManager.GetSaveUniqueFilename(szUniqueMapName); + StorageManager.GetSaveUniqueFilename(szUniqueMapName); - PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) - { - std::shared_ptr player = *it; - // If the offline Xuid is invalid but the online one is not then that's guest which we should ignore - // If the online Xuid is invalid but the offline one is not then we are definitely an offline game so dont care about UGC - - // PADDY - this is failing when a local player with chat restrictions joins an online game + PlayerList* playerList = MinecraftServer::getInstance()->getPlayers(); + for (AUTO_VAR(it, playerList->players.begin()); + it != playerList->players.end(); ++it) { + std::shared_ptr player = *it; + // If the offline Xuid is invalid but the online one is not then that's + // guest which we should ignore If the online Xuid is invalid but the + // offline one is not then we are definitely an offline game so dont + // care about UGC - if( player != NULL && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) - { - if( player->connection->m_friendsOnlyUGC ) - { - ugcFriendsOnlyBits |= (1<connection->m_onlineXUID; + // PADDY - this is failing when a local player with chat restrictions + // joins an online game - if( player->connection->getNetworkPlayer() != NULL && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; + if (player != NULL && + player->connection->m_offlineXUID != INVALID_XUID && + player->connection->m_onlineXUID != INVALID_XUID) { + if (player->connection->m_friendsOnlyUGC) { + ugcFriendsOnlyBits |= (1 << ugcXuidCount); + } + // Need to use the online XUID otherwise friend checks will fail on + // the client + ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID; - ++ugcXuidCount; - } - } + if (player->connection->getNetworkPlayer() != NULL && + player->connection->getNetworkPlayer()->IsHost()) + hostIndex = ugcXuidCount; + + ++ugcXuidCount; + } + } #if 0 if (false)// server->onlineMode) // 4J - removed @@ -134,47 +130,44 @@ void PendingConnection::sendPreLoginResponse() } else #endif - { - connection->send( std::shared_ptr( new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits, server->m_ugcPlayersVersion,szUniqueMapName,app.GetGameHostOption(eGameHostOption_All),hostIndex, server->m_texturePackId) ) ); + { + connection->send(std::shared_ptr( + new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits, + server->m_ugcPlayersVersion, szUniqueMapName, + app.GetGameHostOption(eGameHostOption_All), + hostIndex, server->m_texturePackId))); } } -void PendingConnection::handleLogin(std::shared_ptr packet) -{ - fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n", packet->clientVersion); - //name = packet->userName; - if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) - { - app.DebugPrintf("Client version is %d not equal to %d\n", packet->clientVersion, SharedConstants::NETWORK_PROTOCOL_VERSION); - if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) - { +void PendingConnection::handleLogin(std::shared_ptr packet) { + fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n", + packet->clientVersion); + // name = packet->userName; + if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) { + app.DebugPrintf("Client version is %d not equal to %d\n", + packet->clientVersion, + SharedConstants::NETWORK_PROTOCOL_VERSION); + if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) { disconnect(DisconnectPacket::eDisconnect_OutdatedServer); - } - else - { + } else { disconnect(DisconnectPacket::eDisconnect_OutdatedClient); } return; } - //if (true)// 4J removed !server->onlineMode) - bool sentDisconnect = false; + // if (true)// 4J removed !server->onlineMode) + bool sentDisconnect = false; - if( sentDisconnect ) - { - // Do nothing - } - else if( server->getPlayers()->isXuidBanned( packet->m_onlineXuid ) ) - { - disconnect(DisconnectPacket::eDisconnect_Banned); - } - else - { + if (sentDisconnect) { + // Do nothing + } else if (server->getPlayers()->isXuidBanned(packet->m_onlineXuid)) { + disconnect(DisconnectPacket::eDisconnect_Banned); + } else { handleAcceptedLogin(packet); } - //else - { - //4J - removed + // else + { + // 4J - removed #if 0 new Thread() { public void run() { @@ -197,75 +190,71 @@ void PendingConnection::handleLogin(std::shared_ptr packet) }.start(); #endif } - } -void PendingConnection::handleAcceptedLogin(std::shared_ptr packet) -{ - if(packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) - { - // Send the pre-login packet again with the new list of players - sendPreLoginResponse(); - return; - } +void PendingConnection::handleAcceptedLogin( + std::shared_ptr packet) { + if (packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) { + // Send the pre-login packet again with the new list of players + sendPreLoginResponse(); + return; + } - // Guests use the online xuid, everyone else uses the offline one - PlayerUID playerXuid = packet->m_offlineXuid; - if(playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; + // Guests use the online xuid, everyone else uses the offline one + PlayerUID playerXuid = packet->m_offlineXuid; + if (playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; - std::shared_ptr playerEntity = server->getPlayers()->getPlayerForLogin(this, name, playerXuid,packet->m_onlineXuid); - if (playerEntity != NULL) - { + std::shared_ptr playerEntity = + server->getPlayers()->getPlayerForLogin(this, name, playerXuid, + packet->m_onlineXuid); + if (playerEntity != NULL) { server->getPlayers()->placeNewPlayer(connection, playerEntity, packet); - connection = NULL; // We've moved responsibility for this over to the new PlayerConnection, NULL so we don't delete our reference to it here in our dtor + connection = NULL; // We've moved responsibility for this over to the + // new PlayerConnection, NULL so we don't delete our + // reference to it here in our dtor } done = true; - } -void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ -// logger.info(getName() + " lost connection"); +void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { + // logger.info(getName() + " lost connection"); done = true; } -void PendingConnection::handleGetInfo(std::shared_ptr packet) -{ - //try { - //String message = server->motd + "§" + server->players->getPlayerCount() + "§" + server->players->getMaxPlayers(); - //connection->send(new DisconnectPacket(message)); - connection->send(std::shared_ptr(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull) ) ); - connection->sendAndQuit(); - server->connection->removeSpamProtection(connection->getSocket()); - done = true; - //} catch (Exception e) { - // e.printStackTrace(); - //} +void PendingConnection::handleGetInfo(std::shared_ptr packet) { + // try { + // String message = server->motd + "§" + server->players->getPlayerCount() + + // "§" + server->players->getMaxPlayers(); connection->send(new + // DisconnectPacket(message)); + connection->send(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull))); + connection->sendAndQuit(); + server->connection->removeSpamProtection(connection->getSocket()); + done = true; + //} catch (Exception e) { + // e.printStackTrace(); + //} } -void PendingConnection::handleKeepAlive(std::shared_ptr packet) -{ - // Ignore +void PendingConnection::handleKeepAlive( + std::shared_ptr packet) { + // Ignore } -void PendingConnection::onUnhandledPacket(std::shared_ptr packet) -{ - disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); +void PendingConnection::onUnhandledPacket(std::shared_ptr packet) { + disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); } -void PendingConnection::send(std::shared_ptr packet) -{ - connection->send(packet); +void PendingConnection::send(std::shared_ptr packet) { + connection->send(packet); } -std::wstring PendingConnection::getName() -{ - return L"Unimplemented"; -// if (name != null) return name + " [" + connection.getRemoteAddress().toString() + "]"; -// return connection.getRemoteAddress().toString(); +std::wstring PendingConnection::getName() { + return L"Unimplemented"; + // if (name != null) return name + " [" + + // connection.getRemoteAddress().toString() + "]"; return + // connection.getRemoteAddress().toString(); } -bool PendingConnection::isServerPacketListener() -{ - return true; -} +bool PendingConnection::isServerPacketListener() { return true; } diff --git a/Minecraft.Client/Network/PendingConnection.h b/Minecraft.Client/Network/PendingConnection.h index 1f79508ff..8ee23c434 100644 --- a/Minecraft.Client/Network/PendingConnection.h +++ b/Minecraft.Client/Network/PendingConnection.h @@ -6,43 +6,47 @@ class LoginPacket; class Connection; class Random; - -class PendingConnection : public PacketListener -{ +class PendingConnection : public PacketListener { private: - static const int FAKE_LAG = 0; - static const int MAX_TICKS_BEFORE_LOGIN = 20 * 30 * 10; // 10 minutes instead of 20 sec for Linux theres just no login yet + static const int FAKE_LAG = 0; + static const int MAX_TICKS_BEFORE_LOGIN = + 20 * 30 * + 10; // 10 minutes instead of 20 sec for Linux theres just no login yet -// public static Logger logger = Logger.getLogger("Minecraft"); - static Random *random; + // public static Logger logger = Logger.getLogger("Minecraft"); + static Random* random; public: - Connection *connection; + Connection* connection; + public: - bool done; + bool done; + private: - MinecraftServer *server; + MinecraftServer* server; int _tick; std::wstring name; std::shared_ptr acceptedLogin; std::wstring loginKey; public: - PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id); - ~PendingConnection(); + PendingConnection(MinecraftServer* server, Socket* socket, + const std::wstring& id); + ~PendingConnection(); void tick(); void disconnect(DisconnectPacket::eDisconnectReason reason); virtual void handlePreLogin(std::shared_ptr packet); virtual void handleLogin(std::shared_ptr packet); virtual void handleAcceptedLogin(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); - virtual void handleGetInfo(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); + virtual void handleGetInfo(std::shared_ptr packet); + virtual void handleKeepAlive(std::shared_ptr packet); virtual void onUnhandledPacket(std::shared_ptr packet); void send(std::shared_ptr packet); std::wstring getName(); virtual bool isServerPacketListener(); private: - void sendPreLoginResponse(); + void sendPreLoginResponse(); }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PlayerChunkMap.cpp b/Minecraft.Client/Network/PlayerChunkMap.cpp index 0f86fc0bf..95812270b 100644 --- a/Minecraft.Client/Network/PlayerChunkMap.cpp +++ b/Minecraft.Client/Network/PlayerChunkMap.cpp @@ -12,142 +12,153 @@ #include "../../Minecraft.World/Platform/System.h" #include "PlayerList.h" -PlayerChunkMap::PlayerChunk::PlayerChunk(int x, int z, PlayerChunkMap *pcm) : pos(x,z) -{ - // 4J - added initialisers - changes = 0; - changedTiles = shortArray(MAX_CHANGES_BEFORE_RESEND); - xChangeMin = xChangeMax = 0; - yChangeMin = yChangeMax = 0; - zChangeMin = zChangeMax = 0; - parent = pcm; // 4J added - ticksToNextRegionUpdate = 0; // 4J added - prioritised = false; // 4J added +PlayerChunkMap::PlayerChunk::PlayerChunk(int x, int z, PlayerChunkMap* pcm) + : pos(x, z) { + // 4J - added initialisers + changes = 0; + changedTiles = shortArray(MAX_CHANGES_BEFORE_RESEND); + xChangeMin = xChangeMax = 0; + yChangeMin = yChangeMax = 0; + zChangeMin = zChangeMax = 0; + parent = pcm; // 4J added + ticksToNextRegionUpdate = 0; // 4J added + prioritised = false; // 4J added parent->getLevel()->cache->create(x, z); - // 4J - added make sure our lights are up to date as soon as we make it. This is of particular concern for local clients, who have their data - // shared as soon as the chunkvisibilitypacket is sent, and so could potentially create render data for this chunk before it has been properly lit. - while( parent->getLevel()->updateLights() ) - ; + // 4J - added make sure our lights are up to date as soon as we make it. + // This is of particular concern for local clients, who have their data + // shared as soon as the chunkvisibilitypacket is sent, and so could + // potentially create render data for this chunk before it has been properly + // lit. + while (parent->getLevel()->updateLights()); } -PlayerChunkMap::PlayerChunk::~PlayerChunk() -{ - delete[] changedTiles.data; //4jcraft, changed to [] +PlayerChunkMap::PlayerChunk::~PlayerChunk() { + delete[] changedTiles.data; // 4jcraft, changed to [] } -// 4J added - construct an an array of flags that indicate which entities are still waiting to have network packets sent out to say that they have been removed -// If there aren't any entities to be flagged, this function does nothing. If there *are* entities to be added, uses the removedFound as an input to -// determine if the flag array has already been initialised at all - if it has been, then just adds flags to it; if it hasn't, then memsets the output -// flag array and adds to it for this ServerPlayer. -void PlayerChunkMap::flagEntitiesToBeRemoved(unsigned int *flags, bool *flagToBeRemoved) -{ - for(AUTO_VAR(it,players.begin()); it != players.end(); it++) - { - std::shared_ptr serverPlayer = *it; - serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); - } +// 4J added - construct an an array of flags that indicate which entities are +// still waiting to have network packets sent out to say that they have been +// removed If there aren't any entities to be flagged, this function does +// nothing. If there *are* entities to be added, uses the removedFound as an +// input to determine if the flag array has already been initialised at all - if +// it has been, then just adds flags to it; if it hasn't, then memsets the +// output flag array and adds to it for this ServerPlayer. +void PlayerChunkMap::flagEntitiesToBeRemoved(unsigned int* flags, + bool* flagToBeRemoved) { + for (AUTO_VAR(it, players.begin()); it != players.end(); it++) { + std::shared_ptr serverPlayer = *it; + serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); + } } -void PlayerChunkMap::PlayerChunk::add(std::shared_ptr player, bool sendPacket /*= true*/) -{ - //app.DebugPrintf("--- Adding player to chunk x=%d\tz=%d\n",x, z); - if (find(players.begin(),players.end(),player) != players.end()) - { - // 4J-PB - At the start of the game, lots of chunks are added, and we can then move into an area that is outside the diameter of our starting area, - // but is inside the area loaded at the start. - app.DebugPrintf("--- Adding player to chunk x=%d\t z=%d, but they are already in there!\n",pos.x, pos.z); - return; +void PlayerChunkMap::PlayerChunk::add(std::shared_ptr player, + bool sendPacket /*= true*/) { + // app.DebugPrintf("--- Adding player to chunk x=%d\tz=%d\n",x, z); + if (find(players.begin(), players.end(), player) != players.end()) { + // 4J-PB - At the start of the game, lots of chunks are added, and we + // can then move into an area that is outside the diameter of our + // starting area, but is inside the area loaded at the start. + app.DebugPrintf( + "--- Adding player to chunk x=%d\t z=%d, but they are already in " + "there!\n", + pos.x, pos.z); + return; - //assert(false); -// 4J - was throw new IllegalStateException("Failed to add player. " + player + " already is in chunk " + x + ", " + z); - } + // assert(false); + // 4J - was throw new IllegalStateException("Failed + // to add player. " + player + " already is in chunk " + x + ", " + z); + } player->seenChunks.insert(pos); - // 4J Added the sendPacket check. See PlayerChunkMap::add for the usage - if( sendPacket ) player->connection->send( std::shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, true) ) ); + // 4J Added the sendPacket check. See PlayerChunkMap::add for the usage + if (sendPacket) + player->connection->send(std::shared_ptr( + new ChunkVisibilityPacket(pos.x, pos.z, true))); - players.push_back(player); - - player->chunksToSend.push_back(pos); + players.push_back(player); + + player->chunksToSend.push_back(pos); #ifdef _LARGE_WORLDS - parent->getLevel()->cache->dontDrop(pos.x, pos.z); // 4J Added; + parent->getLevel()->cache->dontDrop(pos.x, pos.z); // 4J Added; #endif } -void PlayerChunkMap::PlayerChunk::remove(std::shared_ptr player) -{ - PlayerChunkMap::PlayerChunk *toDelete = NULL; +void PlayerChunkMap::PlayerChunk::remove(std::shared_ptr player) { + PlayerChunkMap::PlayerChunk* toDelete = NULL; - //app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove x=%d\tz=%d\n",x,z); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if ( it == players.end()) - { - app.DebugPrintf("--- INFO - Removing player from chunk x=%d\t z=%d, but they are not in that chunk!\n",pos.x, pos.z); + // app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove + // x=%d\tz=%d\n",x,z); + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (it == players.end()) { + app.DebugPrintf( + "--- INFO - Removing player from chunk x=%d\t z=%d, but they are " + "not in that chunk!\n", + pos.x, pos.z); - return; - } + return; + } players.erase(it); - if (players.size() == 0) - { + if (players.size() == 0) { __int64 id = (pos.x + 0x7fffffffLL) | ((pos.z + 0x7fffffffLL) << 32); - AUTO_VAR(it, parent->chunks.find(id)); - if( it != parent->chunks.end() ) - { - toDelete = it->second; // Don't delete until the end of the function, as this might be this instance - parent->chunks.erase(it); - } - if (changes > 0) - { - AUTO_VAR(it, find(parent->changedChunks.begin(),parent->changedChunks.end(),this)); - parent->changedChunks.erase(it); + AUTO_VAR(it, parent->chunks.find(id)); + if (it != parent->chunks.end()) { + toDelete = it->second; // Don't delete until the end of the + // function, as this might be this instance + parent->chunks.erase(it); + } + if (changes > 0) { + AUTO_VAR(it, find(parent->changedChunks.begin(), + parent->changedChunks.end(), this)); + parent->changedChunks.erase(it); } parent->getLevel()->cache->drop(pos.x, pos.z); } player->chunksToSend.remove(pos); - // 4J - I don't think there's any point sending these anymore, as we don't need to unload chunks with fixed sized maps - // 4J - We do need to send these to unload entities in chunks when players are dead. If we do not and the entity is removed - // while they are dead, that entity will remain in the clients world - if (player->connection != NULL && player->seenChunks.find(pos) != player->seenChunks.end()) - { - INetworkPlayer *thisNetPlayer = player->connection->getNetworkPlayer(); - bool noOtherPlayersFound = true; - - if( thisNetPlayer != NULL ) - { - for( AUTO_VAR(it, players.begin()); it < players.end(); ++it ) - { - std::shared_ptr currPlayer = *it; - INetworkPlayer *currNetPlayer = currPlayer->connection->getNetworkPlayer(); - if( currNetPlayer != NULL && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) - { - noOtherPlayersFound = false; - break; - } - } - if(noOtherPlayersFound) - { - //wprintf(L"Sending ChunkVisiblity packet false for chunk (%d,%d) to player %ls\n", x, z, player->name.c_str() ); - player->connection->send( std::shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, false) ) ); - } - } - else - { - //app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer is NULL\n"); - } + // 4J - I don't think there's any point sending these anymore, as we don't + // need to unload chunks with fixed sized maps 4J - We do need to send these + // to unload entities in chunks when players are dead. If we do not and the + // entity is removed while they are dead, that entity will remain in the + // clients world + if (player->connection != NULL && + player->seenChunks.find(pos) != player->seenChunks.end()) { + INetworkPlayer* thisNetPlayer = player->connection->getNetworkPlayer(); + bool noOtherPlayersFound = true; + + if (thisNetPlayer != NULL) { + for (AUTO_VAR(it, players.begin()); it < players.end(); ++it) { + std::shared_ptr currPlayer = *it; + INetworkPlayer* currNetPlayer = + currPlayer->connection->getNetworkPlayer(); + if (currNetPlayer != NULL && + currNetPlayer->IsSameSystem(thisNetPlayer) && + currPlayer->seenChunks.find(pos) != + currPlayer->seenChunks.end()) { + noOtherPlayersFound = false; + break; + } + } + if (noOtherPlayersFound) { + // wprintf(L"Sending ChunkVisiblity packet false for chunk + // (%d,%d) to player %ls\n", x, z, player->name.c_str() ); + player->connection->send(std::shared_ptr( + new ChunkVisibilityPacket(pos.x, pos.z, false))); + } + } else { + // app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer + // is NULL\n"); + } } - delete toDelete; + delete toDelete; } -void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) -{ - if (changes == 0) - { +void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) { + if (changes == 0) { parent->changedChunks.push_back(this); xChangeMin = xChangeMax = x; yChangeMin = yChangeMax = y; @@ -162,12 +173,10 @@ void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) if (zChangeMin > z) zChangeMin = z; if (zChangeMax < z) zChangeMax = z; - if (changes < MAX_CHANGES_BEFORE_RESEND) - { - short id = (short) ((x << 12) | (z << 8) | (y)); + if (changes < MAX_CHANGES_BEFORE_RESEND) { + short id = (short)((x << 12) | (z << 8) | (y)); - for (int i = 0; i < changes; i++) - { + for (int i = 0; i < changes; i++) { if (changedTiles[i] == id) return; } @@ -175,146 +184,143 @@ void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) } } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerChunkMap::PlayerChunk::prioritiseTileChanges() -{ - prioritised = true; +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerChunkMap::PlayerChunk::prioritiseTileChanges() { + prioritised = true; } -void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr packet) -{ - std::vector< std::shared_ptr > sentTo; - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr packet) { + std::vector > sentTo; + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - // 4J - don't send to a player we've already sent this data to that shares the same machine. TileUpdatePacket, - // ChunkTilesUpdatePacket and SignUpdatePacket all used to limit themselves to sending once to each machine - // by only sending to the primary player on each machine. This was causing trouble for split screen - // as updates were only coming in for the region round this one player. Now these packets can be sent to any - // player, but we try to restrict the network impact this has by not resending to the one machine - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( dontSend ) - { - continue; - } + // 4J - don't send to a player we've already sent this data to that + // shares the same machine. TileUpdatePacket, ChunkTilesUpdatePacket and + // SignUpdatePacket all used to limit themselves to sending once to each + // machine by only sending to the primary player on each machine. This + // was causing trouble for split screen as updates were only coming in + // for the region round this one player. Now these packets can be sent + // to any player, but we try to restrict the network impact this has by + // not resending to the one machine + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (dontSend) { + continue; + } - // 4J Changed to get the flag index for the player before we send a packet. This flag is updated when we queue - // for send the first BlockRegionUpdatePacket for this chunk to that player/players system. Therefore there is no need to - // send tile updates or other updates until that has been sent - int flagIndex = ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); - if (player->seenChunks.find(pos) != player->seenChunks.end() && (player->connection->isLocal() || g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),flagIndex) )) - { + // 4J Changed to get the flag index for the player before we send a + // packet. This flag is updated when we queue for send the first + // BlockRegionUpdatePacket for this chunk to that player/players system. + // Therefore there is no need to send tile updates or other updates + // until that has been sent + int flagIndex = + ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); + if (player->seenChunks.find(pos) != player->seenChunks.end() && + (player->connection->isLocal() || + g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), flagIndex))) { player->connection->send(packet); - sentTo.push_back(player); + sentTo.push_back(player); } } - // Now also check round all the players that are involved in this game. We also want to send the packet - // to them if their system hasn't received it already, but they have received the first BlockRegionUpdatePacket for this - // chunk + // Now also check round all the players that are involved in this game. We + // also want to send the packet to them if their system hasn't received it + // already, but they have received the first BlockRegionUpdatePacket for + // this chunk - // Make sure we are only doing this for BlockRegionUpdatePacket, ChunkTilesUpdatePacket and TileUpdatePacket. - // We'll be potentially sending to players who aren't on the same level as this packet is intended for, - // and only these 3 packets have so far been updated to be able to encode the level so they are robust - // enough to cope with this - if(!( ( packet->getId() == 51 ) || ( packet->getId() == 52 ) || ( packet->getId() == 53 ) ) ) - { - return; - } + // Make sure we are only doing this for BlockRegionUpdatePacket, + // ChunkTilesUpdatePacket and TileUpdatePacket. We'll be potentially sending + // to players who aren't on the same level as this packet is intended for, + // and only these 3 packets have so far been updated to be able to encode + // the level so they are robust enough to cope with this + if (!((packet->getId() == 51) || (packet->getId() == 52) || + (packet->getId() == 53))) { + return; + } - for( int i = 0; i < parent->level->getServer()->getPlayers()->players.size(); i++ ) - { - std::shared_ptr player = parent->level->getServer()->getPlayers()->players[i]; - // Don't worry about local players, they get all their updates through sharing level with the server anyway - if ( player->connection == NULL ) continue; - if( player->connection->isLocal() ) continue; + for (int i = 0; + i < parent->level->getServer()->getPlayers()->players.size(); i++) { + std::shared_ptr player = + parent->level->getServer()->getPlayers()->players[i]; + // Don't worry about local players, they get all their updates through + // sharing level with the server anyway + if (player->connection == NULL) continue; + if (player->connection->isLocal()) continue; - // Don't worry about this player if they haven't had this chunk yet (this flag will be the - // same for all players on the same system) - int flagIndex = ServerPlayer::getFlagIndexForChunk(pos,parent->dimension); - if(!g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),flagIndex)) continue; + // Don't worry about this player if they haven't had this chunk yet + // (this flag will be the same for all players on the same system) + int flagIndex = + ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); + if (!g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), flagIndex)) + continue; - // From here on the same rules as in the loop above - don't send it if we've already sent to the same system - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( !dontSend ) - { + // From here on the same rules as in the loop above - don't send it if + // we've already sent to the same system + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (!dontSend) { player->connection->send(packet); - sentTo.push_back(player); - } - } + sentTo.push_back(player); + } + } } -bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) -{ - bool didRegionUpdate = false; - ServerLevel *level = parent->getLevel(); - if( ticksToNextRegionUpdate > 0 ) ticksToNextRegionUpdate--; - if (changes == 0) - { - prioritised = false; - return false; - } - if (changes == 1) - { +bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) { + bool didRegionUpdate = false; + ServerLevel* level = parent->getLevel(); + if (ticksToNextRegionUpdate > 0) ticksToNextRegionUpdate--; + if (changes == 0) { + prioritised = false; + return false; + } + if (changes == 1) { int x = pos.x * 16 + xChangeMin; int y = yChangeMin; int z = pos.z * 16 + zChangeMin; - broadcast( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - if (level->isEntityTile(x, y, z)) - { + broadcast(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + if (level->isEntityTile(x, y, z)) { broadcast(level->getTileEntity(x, y, z)); } - } - else if (changes == MAX_CHANGES_BEFORE_RESEND) - { - // 4J added, to allow limiting of region update packets created - if( !prioritised ) - { - if( !allowRegionUpdate || ( ticksToNextRegionUpdate > 0 ) ) - { - return false; - } - } + } else if (changes == MAX_CHANGES_BEFORE_RESEND) { + // 4J added, to allow limiting of region update packets created + if (!prioritised) { + if (!allowRegionUpdate || (ticksToNextRegionUpdate > 0)) { + return false; + } + } yChangeMin = yChangeMin / 2 * 2; yChangeMax = (yChangeMax / 2 + 1) * 2; @@ -325,271 +331,241 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) int ys = yChangeMax - yChangeMin + 2; int zs = zChangeMax - zChangeMin + 1; - // Fix for buf #95007 : TCR #001 BAS Game Stability: TU12: Code: Compliance: More than 192 dropped items causes game to freeze or crash. - // Block region update packets can only encode ys in a range of 1 - 256 - if( ys > 256 ) ys = 256; + // Fix for buf #95007 : TCR #001 BAS Game Stability: TU12: Code: + // Compliance: More than 192 dropped items causes game to freeze or + // crash. Block region update packets can only encode ys in a range of 1 + // - 256 + if (ys > 256) ys = 256; - broadcast( std::shared_ptr( new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level) ) ); - std::vector > *tes = level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, zp + zs); - for (unsigned int i = 0; i < tes->size(); i++) - { + broadcast(std::shared_ptr( + new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level))); + std::vector >* tes = + level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, + zp + zs); + for (unsigned int i = 0; i < tes->size(); i++) { broadcast(tes->at(i)); } - delete tes; - ticksToNextRegionUpdate = MIN_TICKS_BETWEEN_REGION_UPDATE; - didRegionUpdate = true; - } - else - { - // 4J As we only get here if changes is less than MAX_CHANGES_BEFORE_RESEND (10) we only need to send a byte value in the packet - broadcast( std::shared_ptr( new ChunkTilesUpdatePacket(pos.x, pos.z, changedTiles, (uint8_t)changes, level) ) ); - for (int i = 0; i < changes; i++) - { + delete tes; + ticksToNextRegionUpdate = MIN_TICKS_BETWEEN_REGION_UPDATE; + didRegionUpdate = true; + } else { + // 4J As we only get here if changes is less than + // MAX_CHANGES_BEFORE_RESEND (10) we only need to send a byte value in + // the packet + broadcast( + std::shared_ptr(new ChunkTilesUpdatePacket( + pos.x, pos.z, changedTiles, (uint8_t)changes, level))); + for (int i = 0; i < changes; i++) { int x = pos.x * 16 + ((changedTiles[i] >> 12) & 15); int y = ((changedTiles[i]) & 255); int z = pos.z * 16 + ((changedTiles[i] >> 8) & 15); - if (level->isEntityTile(x, y, z)) - { -// System.out.println("Sending!"); + if (level->isEntityTile(x, y, z)) { + // System.out.println("Sending!"); broadcast(level->getTileEntity(x, y, z)); } } } changes = 0; - prioritised = false; - return didRegionUpdate; + prioritised = false; + return didRegionUpdate; } -void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr te) -{ - if (te != NULL) - { +void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr te) { + if (te != NULL) { std::shared_ptr p = te->getUpdatePacket(); - if (p != NULL) - { + if (p != NULL) { broadcast(p); } } } -PlayerChunkMap::PlayerChunkMap(ServerLevel *level, int dimension, int radius) -{ - assert(radius <= MAX_VIEW_DISTANCE); - assert(radius >= MIN_VIEW_DISTANCE); +PlayerChunkMap::PlayerChunkMap(ServerLevel* level, int dimension, int radius) { + assert(radius <= MAX_VIEW_DISTANCE); + assert(radius >= MIN_VIEW_DISTANCE); this->radius = radius; this->level = level; - this->dimension = dimension; + this->dimension = dimension; } -PlayerChunkMap::~PlayerChunkMap() -{ - for( AUTO_VAR(it, chunks.begin()); it != chunks.end(); it++ ) - { - delete it->second; - } +PlayerChunkMap::~PlayerChunkMap() { + for (AUTO_VAR(it, chunks.begin()); it != chunks.end(); it++) { + delete it->second; + } } -ServerLevel *PlayerChunkMap::getLevel() -{ - return level; -} +ServerLevel* PlayerChunkMap::getLevel() { return level; } -void PlayerChunkMap::tick() -{ - // 4J - some changes here so that we only send one region update per tick. The chunks themselves also - // limit their resend rate to once every MIN_TICKS_BETWEEN_REGION_UPDATE ticks - bool regionUpdateSent = false; - for (unsigned int i = 0; i < changedChunks.size();) - { - regionUpdateSent |= changedChunks[i]->broadcastChanges(!regionUpdateSent); - // Changes will be 0 if the chunk actually sent something, in which case we can delete it from this array - if( changedChunks[i]->changes == 0 ) - { - changedChunks[i] = changedChunks.back(); - changedChunks.pop_back(); - } - else - { - // Limiting of some kind means we didn't send this chunk so move onto the next - i++; - } +void PlayerChunkMap::tick() { + // 4J - some changes here so that we only send one region update per tick. + // The chunks themselves also limit their resend rate to once every + // MIN_TICKS_BETWEEN_REGION_UPDATE ticks + bool regionUpdateSent = false; + for (unsigned int i = 0; i < changedChunks.size();) { + regionUpdateSent |= + changedChunks[i]->broadcastChanges(!regionUpdateSent); + // Changes will be 0 if the chunk actually sent something, in which case + // we can delete it from this array + if (changedChunks[i]->changes == 0) { + changedChunks[i] = changedChunks.back(); + changedChunks.pop_back(); + } else { + // Limiting of some kind means we didn't send this chunk so move + // onto the next + i++; + } } - for( unsigned int i = 0; i < players.size(); i++ ) - { - tickAddRequests(players[i]); - } + for (unsigned int i = 0; i < players.size(); i++) { + tickAddRequests(players[i]); + } - // 4J Stu - Added 1.1 but not relevant to us as we never no 0 players anyway, and don't think we should be dropping stuff - //if (players.isEmpty()) { - // ServerLevel level = server.getLevel(this.dimension); - // Dimension dimension = level.dimension; - // if (!dimension.mayRespawn()) { - // level.cache.dropAll(); - // } - //} + // 4J Stu - Added 1.1 but not relevant to us as we never no 0 players + // anyway, and don't think we should be dropping stuff + // if (players.isEmpty()) { + // ServerLevel level = server.getLevel(this.dimension); + // Dimension dimension = level.dimension; + // if (!dimension.mayRespawn()) { + // level.cache.dropAll(); + // } + //} } -bool PlayerChunkMap::hasChunk(int x, int z) -{ +bool PlayerChunkMap::hasChunk(int x, int z) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - return chunks.find(id) != chunks.end(); + return chunks.find(id) != chunks.end(); } -PlayerChunkMap::PlayerChunk *PlayerChunkMap::getChunk(int x, int z, bool create) -{ +PlayerChunkMap::PlayerChunk* PlayerChunkMap::getChunk(int x, int z, + bool create) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - PlayerChunk *chunk = NULL; - if( it != chunks.end() ) - { - chunk = it->second; - } - else if ( create) - { + PlayerChunk* chunk = NULL; + if (it != chunks.end()) { + chunk = it->second; + } else if (create) { chunk = new PlayerChunk(x, z, this); chunks[id] = chunk; } - return chunk; + return chunk; } -// 4J - added. If a chunk exists, add a player to it straight away. If it doesn't exist, -// queue a request for it to be created. -void PlayerChunkMap::getChunkAndAddPlayer(int x, int z, std::shared_ptr player) -{ +// 4J - added. If a chunk exists, add a player to it straight away. If it +// doesn't exist, queue a request for it to be created. +void PlayerChunkMap::getChunkAndAddPlayer( + int x, int z, std::shared_ptr player) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - if( it != chunks.end() ) - { - it->second->add(player); - } - else - { - addRequests.push_back(PlayerChunkAddRequest(x,z,player)); - } + if (it != chunks.end()) { + it->second->add(player); + } else { + addRequests.push_back(PlayerChunkAddRequest(x, z, player)); + } } -// 4J - added. If the chunk and player are in the queue to be added, remove from there. Otherwise -// attempt to remove from main chunk map. -void PlayerChunkMap::getChunkAndRemovePlayer(int x, int z, std::shared_ptr player) -{ - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { - if( ( it->x == x ) && - ( it->z == z ) && - ( it->player == player ) ) - { - addRequests.erase(it); - return; - } - } +// 4J - added. If the chunk and player are in the queue to be added, remove from +// there. Otherwise attempt to remove from main chunk map. +void PlayerChunkMap::getChunkAndRemovePlayer( + int x, int z, std::shared_ptr player) { + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++) { + if ((it->x == x) && (it->z == z) && (it->player == player)) { + addRequests.erase(it); + return; + } + } __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - if( it != chunks.end() ) - { - it->second->remove(player); - } + if (it != chunks.end()) { + it->second->remove(player); + } } -// 4J - added - actually create & add player to a playerchunk, if there is one queued for this player. -void PlayerChunkMap::tickAddRequests(std::shared_ptr player) -{ - if( addRequests.size() ) - { - // Find the nearest chunk request to the player - int px = (int)player->x; - int pz = (int)player->z; - int minDistSq = -1; - - AUTO_VAR(itNearest, addRequests.end()); - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { - if( it->player == player ) - { - int xm = ( it->x * 16 ) + 8; - int zm = ( it->z * 16 ) + 8; - int distSq = (xm - px) * (xm - px) + - (zm - pz) * (zm - pz); - if( ( minDistSq == -1 ) || ( distSq < minDistSq ) ) - { - minDistSq = distSq; - itNearest = it; - } - } - } +// 4J - added - actually create & add player to a playerchunk, if there is one +// queued for this player. +void PlayerChunkMap::tickAddRequests(std::shared_ptr player) { + if (addRequests.size()) { + // Find the nearest chunk request to the player + int px = (int)player->x; + int pz = (int)player->z; + int minDistSq = -1; - // If we found one at all, then do this one - if( itNearest != addRequests.end() ) - { - getChunk(itNearest->x, itNearest->z, true)->add(itNearest->player); - addRequests.erase(itNearest); - return; - } - } + AUTO_VAR(itNearest, addRequests.end()); + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++) { + if (it->player == player) { + int xm = (it->x * 16) + 8; + int zm = (it->z * 16) + 8; + int distSq = (xm - px) * (xm - px) + (zm - pz) * (zm - pz); + if ((minDistSq == -1) || (distSq < minDistSq)) { + minDistSq = distSq; + itNearest = it; + } + } + } + + // If we found one at all, then do this one + if (itNearest != addRequests.end()) { + getChunk(itNearest->x, itNearest->z, true)->add(itNearest->player); + addRequests.erase(itNearest); + return; + } + } } -void PlayerChunkMap::broadcastTileUpdate(std::shared_ptr packet, int x, int y, int z) -{ +void PlayerChunkMap::broadcastTileUpdate(std::shared_ptr packet, int x, + int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->broadcast(packet); } } -void PlayerChunkMap::tileChanged(int x, int y, int z) -{ +void PlayerChunkMap::tileChanged(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->tileChanged(x & 15, y, z & 15); } } -bool PlayerChunkMap::isTrackingTile(int x, int y, int z) -{ +bool PlayerChunkMap::isTrackingTile(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if( chunk ) return true; - return false; + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk) return true; + return false; } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerChunkMap::prioritiseTileChanges(int x, int y, int z) -{ +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerChunkMap::prioritiseTileChanges(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->prioritiseTileChanges(); } } -void PlayerChunkMap::add(std::shared_ptr player) -{ - static int direction[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, {0, -1} }; +void PlayerChunkMap::add(std::shared_ptr player) { + static int direction[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; - int xc = (int) player->x >> 4; - int zc = (int) player->z >> 4; + int xc = (int)player->x >> 4; + int zc = (int)player->z >> 4; player->lastMoveX = player->x; player->lastMoveZ = player->z; -// for (int x = xc - radius; x <= xc + radius; x++) -// for (int z = zc - radius; z <= zc + radius; z++) { -// getChunk(x, z, true).add(player); -// } + // for (int x = xc - radius; x <= xc + radius; x++) + // for (int z = zc - radius; z <= zc + radius; z++) { + // getChunk(x, z, true).add(player); + // } // CraftBukkit start int facing = 0; @@ -600,30 +576,28 @@ void PlayerChunkMap::add(std::shared_ptr player) // Origin getChunk(xc, zc, true)->add(player, false); - // 4J Added so we send an area packet rather than one visibility packet per chunk - int minX, maxX, minZ, maxZ; - minX = maxX = xc; - minZ = maxZ = zc; + // 4J Added so we send an area packet rather than one visibility packet per + // chunk + int minX, maxX, minZ, maxZ; + minX = maxX = xc; + minZ = maxZ = zc; // All but the last leg - for (int legSize = 1; legSize <= size * 2; legSize++) - { - for (int leg = 0; leg < 2; leg++) - { - int *dir = direction[facing++ % 4]; + for (int legSize = 1; legSize <= size * 2; legSize++) { + for (int leg = 0; leg < 2; leg++) { + int* dir = direction[facing++ % 4]; - for (int k = 0; k < legSize; k++) - { + for (int k = 0; k < legSize; k++) { dx += dir[0]; dz += dir[1]; - int targetX, targetZ; - targetX = xc + dx; - targetZ = zc + dz; - if( targetX > maxX ) maxX = targetX; - if( targetX < minX ) minX = targetX; - if( targetZ > maxZ ) maxZ = targetZ; - if( targetZ < minZ ) minZ = targetZ; + int targetX, targetZ; + targetX = xc + dx; + targetZ = zc + dz; + if (targetX > maxX) maxX = targetX; + if (targetX < minX) minX = targetX; + if (targetZ > maxZ) maxZ = targetZ; + if (targetZ < minZ) minZ = targetZ; getChunk(targetX, targetZ, true)->add(player, false); } @@ -632,67 +606,59 @@ void PlayerChunkMap::add(std::shared_ptr player) // Final leg facing %= 4; - for (int k = 0; k < size * 2; k++) - { + for (int k = 0; k < size * 2; k++) { dx += direction[facing][0]; dz += direction[facing][1]; - int targetX, targetZ; - targetX = xc + dx; - targetZ = zc + dz; - if( targetX > maxX ) maxX = targetX; - if( targetX < minX ) minX = targetX; - if( targetZ > maxZ ) maxZ = targetZ; - if( targetZ < minZ ) minZ = targetZ; + int targetX, targetZ; + targetX = xc + dx; + targetZ = zc + dz; + if (targetX > maxX) maxX = targetX; + if (targetX < minX) minX = targetX; + if (targetZ > maxZ) maxZ = targetZ; + if (targetZ < minZ) minZ = targetZ; getChunk(targetX, targetZ, true)->add(player, false); } // CraftBukkit end - player->connection->send( std::shared_ptr( new ChunkVisibilityAreaPacket(minX, maxX, minZ, maxZ) ) ); + player->connection->send(std::shared_ptr( + new ChunkVisibilityAreaPacket(minX, maxX, minZ, maxZ))); #ifdef _LARGE_WORLDS - getLevel()->cache->dontDrop(xc,zc); + getLevel()->cache->dontDrop(xc, zc); #endif - players.push_back(player); - + players.push_back(player); } -void PlayerChunkMap::remove(std::shared_ptr player) -{ - int xc = ((int) player->lastMoveX) >> 4; - int zc = ((int) player->lastMoveZ) >> 4; +void PlayerChunkMap::remove(std::shared_ptr player) { + int xc = ((int)player->lastMoveX) >> 4; + int zc = ((int)player->lastMoveZ) >> 4; for (int x = xc - radius; x <= xc + radius; x++) - for (int z = zc - radius; z <= zc + radius; z++) - { - PlayerChunk *playerChunk = getChunk(x, z, false); + for (int z = zc - radius; z <= zc + radius; z++) { + PlayerChunk* playerChunk = getChunk(x, z, false); if (playerChunk != NULL) playerChunk->remove(player); } - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( players.size() > 0 && it != players.end() ) - players.erase(find(players.begin(),players.end(),player)); - - // 4J - added - also remove any queued requests to be added to playerchunks here - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); ) - { - if( it->player == player ) - { - it = addRequests.erase(it); - } - else - { - ++it; - } - } + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (players.size() > 0 && it != players.end()) + players.erase(find(players.begin(), players.end(), player)); + // 4J - added - also remove any queued requests to be added to playerchunks + // here + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end();) { + if (it->player == player) { + it = addRequests.erase(it); + } else { + ++it; + } + } } -bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) -{ - // If the distance between x and xc +bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) { + // If the distance between x and xc int xd = x - xc; int zd = z - zc; if (xd < -radius || xd > radius) return false; @@ -700,101 +666,91 @@ bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) return true; } -// 4J - have changed this so that we queue requests to add the player to chunks if they -// need to be created, so that we aren't creating potentially 20 chunks per player per tick -void PlayerChunkMap::move(std::shared_ptr player) -{ - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; +// 4J - have changed this so that we queue requests to add the player to chunks +// if they need to be created, so that we aren't creating potentially 20 chunks +// per player per tick +void PlayerChunkMap::move(std::shared_ptr player) { + int xc = ((int)player->x) >> 4; + int zc = ((int)player->z) >> 4; double _xd = player->lastMoveX - player->x; double _zd = player->lastMoveZ - player->z; double dist = _xd * _xd + _zd * _zd; if (dist < 8 * 8) return; - int last_xc = ((int) player->lastMoveX) >> 4; - int last_zc = ((int) player->lastMoveZ) >> 4; + int last_xc = ((int)player->lastMoveX) >> 4; + int last_zc = ((int)player->lastMoveZ) >> 4; int xd = xc - last_xc; int zd = zc - last_zc; if (xd == 0 && zd == 0) return; - for (int x = xc - radius; x <= xc + radius; x++) - for (int z = zc - radius; z <= zc + radius; z++) - { - if (!chunkInRange(x, z, last_xc, last_zc)) - { - // 4J - changed from separate getChunk & add so we can wrap these operations up and queue - getChunkAndAddPlayer(x, z, player); - } + for (int x = xc - radius; x <= xc + radius; x++) + for (int z = zc - radius; z <= zc + radius; z++) { + if (!chunkInRange(x, z, last_xc, last_zc)) { + // 4J - changed from separate getChunk & add so we can wrap + // these operations up and queue + getChunkAndAddPlayer(x, z, player); + } - if (!chunkInRange(x - xd, z - zd, xc, zc)) - { - // 4J - changed from separate getChunk & remove so we can wrap these operations up and queue - getChunkAndRemovePlayer(x - xd, z - zd, player); - } + if (!chunkInRange(x - xd, z - zd, xc, zc)) { + // 4J - changed from separate getChunk & remove so we can wrap + // these operations up and queue + getChunkAndRemovePlayer(x - xd, z - zd, player); + } } player->lastMoveX = player->x; player->lastMoveZ = player->z; } -int PlayerChunkMap::getMaxRange() -{ - return radius * 16 - 16; +int PlayerChunkMap::getMaxRange() { return radius * 16 - 16; } + +bool PlayerChunkMap::isPlayerIn(std::shared_ptr player, + int xChunk, int zChunk) { + PlayerChunk* chunk = getChunk(xChunk, zChunk, false); + + if (chunk == NULL) { + return false; + } else { + AUTO_VAR(it1, + find(chunk->players.begin(), chunk->players.end(), player)); + AUTO_VAR(it2, find(player->chunksToSend.begin(), + player->chunksToSend.end(), chunk->pos)); + return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); + } + + // return chunk == NULL ? false : chunk->players->contains(player) && + // !player->chunksToSend->contains(chunk->pos); } -bool PlayerChunkMap::isPlayerIn(std::shared_ptr player, int xChunk, int zChunk) -{ - PlayerChunk *chunk = getChunk(xChunk, zChunk, false); - - if(chunk == NULL) - { - return false; - } - else - { - AUTO_VAR(it1, find(chunk->players.begin(), chunk->players.end(), player)); - AUTO_VAR(it2, find(player->chunksToSend.begin(), player->chunksToSend.end(), chunk->pos)); - return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); - } - - //return chunk == NULL ? false : chunk->players->contains(player) && !player->chunksToSend->contains(chunk->pos); -} - -int PlayerChunkMap::convertChunkRangeToBlock(int radius) -{ - return radius * 16 - 16; +int PlayerChunkMap::convertChunkRangeToBlock(int radius) { + return radius * 16 - 16; } // AP added for Vita so the range can be increased once the level starts -void PlayerChunkMap::setRadius(int newRadius) -{ - if( radius != newRadius ) - { - PlayerList* players = level->getServer()->getPlayerList(); - for( int i = 0;i < players->players.size();i += 1 ) - { - std::shared_ptr player = players->players[i]; - if( player->level == level ) - { - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; +void PlayerChunkMap::setRadius(int newRadius) { + if (radius != newRadius) { + PlayerList* players = level->getServer()->getPlayerList(); + for (int i = 0; i < players->players.size(); i += 1) { + std::shared_ptr player = players->players[i]; + if (player->level == level) { + int xc = ((int)player->x) >> 4; + int zc = ((int)player->z) >> 4; - for (int x = xc - newRadius; x <= xc + newRadius; x++) - for (int z = zc - newRadius; z <= zc + newRadius; z++) - { - // check if this chunk is outside the old radius area - if ( x < xc - radius || x > xc + radius || z < zc - radius || z > zc + radius ) - { - getChunkAndAddPlayer(x, z, player); - } - } - } - } + for (int x = xc - newRadius; x <= xc + newRadius; x++) + for (int z = zc - newRadius; z <= zc + newRadius; z++) { + // check if this chunk is outside the old radius area + if (x < xc - radius || x > xc + radius || + z < zc - radius || z > zc + radius) { + getChunkAndAddPlayer(x, z, player); + } + } + } + } - assert(radius <= MAX_VIEW_DISTANCE); - assert(radius >= MIN_VIEW_DISTANCE); - this->radius = newRadius; - } + assert(radius <= MAX_VIEW_DISTANCE); + assert(radius >= MIN_VIEW_DISTANCE); + this->radius = newRadius; + } } diff --git a/Minecraft.Client/Network/PlayerChunkMap.h b/Minecraft.Client/Network/PlayerChunkMap.h index 9c9df9f0f..61ace4de2 100644 --- a/Minecraft.Client/Network/PlayerChunkMap.h +++ b/Minecraft.Client/Network/PlayerChunkMap.h @@ -7,35 +7,34 @@ class MinecraftServer; class Packet; class TileEntity; - -class PlayerChunkMap -{ +class PlayerChunkMap { public: #ifdef _LARGE_WORLDS - static const int MAX_VIEW_DISTANCE = 30; + static const int MAX_VIEW_DISTANCE = 30; #else - static const int MAX_VIEW_DISTANCE = 15; + static const int MAX_VIEW_DISTANCE = 15; #endif - static const int MIN_VIEW_DISTANCE = 3; - static const int MAX_CHANGES_BEFORE_RESEND = 10; - static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10; + static const int MIN_VIEW_DISTANCE = 3; + static const int MAX_CHANGES_BEFORE_RESEND = 10; + static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10; - // 4J - added - class PlayerChunkAddRequest - { - public: - int x,z; - std::shared_ptr player; - PlayerChunkAddRequest(int x, int z, std::shared_ptr player ) : x(x), z(z), player(player) {} - }; + // 4J - added + class PlayerChunkAddRequest { + public: + int x, z; + std::shared_ptr player; + PlayerChunkAddRequest(int x, int z, + std::shared_ptr player) + : x(x), z(z), player(player) {} + }; - class PlayerChunk - { - friend class PlayerChunkMap; - private: - PlayerChunkMap *parent; // 4J added - std::vector > players; - //int x, z; + class PlayerChunk { + friend class PlayerChunkMap; + + private: + PlayerChunkMap* parent; // 4J added + std::vector > players; + // int x, z; ChunkPos pos; shortArray changedTiles; @@ -43,63 +42,73 @@ public: int xChangeMin, xChangeMax; int yChangeMin, yChangeMax; int zChangeMin, zChangeMax; - int ticksToNextRegionUpdate; // 4J added - bool prioritised; // 4J added + int ticksToNextRegionUpdate; // 4J added + bool prioritised; // 4J added - public: - PlayerChunk(int x, int z, PlayerChunkMap *pcm); - ~PlayerChunk(); + public: + PlayerChunk(int x, int z, PlayerChunkMap* pcm); + ~PlayerChunk(); - // 4J Added sendPacket param so we can aggregate the initial send into one much smaller packet + // 4J Added sendPacket param so we can aggregate the initial send into + // one much smaller packet void add(std::shared_ptr player, bool sendPacket = true); void remove(std::shared_ptr player); void tileChanged(int x, int y, int z); - void prioritiseTileChanges(); // 4J added + void prioritiseTileChanges(); // 4J added void broadcast(std::shared_ptr packet); - bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm + bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm - private: - void broadcast(std::shared_ptr te); + private: + void broadcast(std::shared_ptr te); }; public: - std::vector > players; - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + std::vector > players; + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added private: - std::unordered_map<__int64,PlayerChunk *,LongKeyHash,LongKeyEq> chunks; // 4J - was LongHashMap - std::vector changedChunks; - std::vector addRequests; // 4J added - void tickAddRequests(std::shared_ptr player); // 4J added + std::unordered_map<__int64, PlayerChunk*, LongKeyHash, LongKeyEq> + chunks; // 4J - was LongHashMap + std::vector changedChunks; + std::vector addRequests; // 4J added + void tickAddRequests(std::shared_ptr player); // 4J added - ServerLevel *level; + ServerLevel* level; int radius; - int dimension; + int dimension; public: - PlayerChunkMap(ServerLevel *level, int dimension, int radius); - ~PlayerChunkMap(); - ServerLevel *getLevel(); + PlayerChunkMap(ServerLevel* level, int dimension, int radius); + ~PlayerChunkMap(); + ServerLevel* getLevel(); void tick(); - bool hasChunk(int x, int z); + bool hasChunk(int x, int z); + private: - PlayerChunk *getChunk(int x, int z, bool create); - void getChunkAndAddPlayer(int x, int z, std::shared_ptr player); // 4J added - void getChunkAndRemovePlayer(int x, int z, std::shared_ptr player); // 4J added + PlayerChunk* getChunk(int x, int z, bool create); + void getChunkAndAddPlayer( + int x, int z, std::shared_ptr player); // 4J added + void getChunkAndRemovePlayer( + int x, int z, std::shared_ptr player); // 4J added public: - void broadcastTileUpdate(std::shared_ptr packet, int x, int y, int z); + void broadcastTileUpdate(std::shared_ptr packet, int x, int y, + int z); void tileChanged(int x, int y, int z); - bool isTrackingTile(int x, int y, int z); // 4J added - void prioritiseTileChanges(int x, int y, int z); // 4J added + bool isTrackingTile(int x, int y, int z); // 4J added + void prioritiseTileChanges(int x, int y, int z); // 4J added void add(std::shared_ptr player); void remove(std::shared_ptr player); -private: - bool chunkInRange(int x, int z, int xc, int zc); -public: - void move(std::shared_ptr player); - int getMaxRange(); - bool isPlayerIn(std::shared_ptr player, int xChunk, int zChunk); - static int convertChunkRangeToBlock(int radius); - // AP added for Vita - void setRadius(int newRadius); +private: + bool chunkInRange(int x, int z, int xc, int zc); + +public: + void move(std::shared_ptr player); + int getMaxRange(); + bool isPlayerIn(std::shared_ptr player, int xChunk, + int zChunk); + static int convertChunkRangeToBlock(int radius); + + // AP added for Vita + void setRadius(int newRadius); }; diff --git a/Minecraft.Client/Network/PlayerConnection.cpp b/Minecraft.Client/Network/PlayerConnection.cpp index b5b494e81..bc6a1be76 100644 --- a/Minecraft.Client/Network/PlayerConnection.cpp +++ b/Minecraft.Client/Network/PlayerConnection.cpp @@ -34,609 +34,617 @@ Random PlayerConnection::random; -PlayerConnection::PlayerConnection(MinecraftServer *server, Connection *connection, std::shared_ptr player) -{ - // 4J - added initialisers - done = false; - tickCount = 0; - aboveGroundTickCount = 0; - xLastOk = yLastOk = zLastOk = 0; - synched = true; - didTick = false; - lastKeepAliveId = 0; - lastKeepAliveTime = 0; - lastKeepAliveTick = 0; - chatSpamTickCount = 0; - dropSpamTickCount = 0; +PlayerConnection::PlayerConnection(MinecraftServer* server, + Connection* connection, + std::shared_ptr player) { + // 4J - added initialisers + done = false; + tickCount = 0; + aboveGroundTickCount = 0; + xLastOk = yLastOk = zLastOk = 0; + synched = true; + didTick = false; + lastKeepAliveId = 0; + lastKeepAliveTime = 0; + lastKeepAliveTick = 0; + chatSpamTickCount = 0; + dropSpamTickCount = 0; - this->server = server; - this->connection = connection; - connection->setListener(this); - this->player = player; -// player->connection = this; // 4J - moved out as we can't assign in a ctor - InitializeCriticalSection(&done_cs); + this->server = server; + this->connection = connection; + connection->setListener(this); + this->player = player; + // player->connection = this; // 4J - moved out as we can't + //assign in a ctor + InitializeCriticalSection(&done_cs); - m_bCloseOnTick = false; - m_bWasKicked = false; + m_bCloseOnTick = false; + m_bWasKicked = false; - m_friendsOnlyUGC = false; - m_offlineXUID = INVALID_XUID; - m_onlineXUID = INVALID_XUID; - m_bHasClientTickedOnce = false; + m_friendsOnlyUGC = false; + m_offlineXUID = INVALID_XUID; + m_onlineXUID = INVALID_XUID; + m_bHasClientTickedOnce = false; - setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); + setShowOnMaps( + app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false); } -PlayerConnection::~PlayerConnection() -{ - delete connection; - DeleteCriticalSection(&done_cs); +PlayerConnection::~PlayerConnection() { + delete connection; + DeleteCriticalSection(&done_cs); } -void PlayerConnection::tick() -{ - if( done ) return; +void PlayerConnection::tick() { + if (done) return; - if( m_bCloseOnTick ) - { - disconnect( DisconnectPacket::eDisconnect_Closed ); - return; - } + if (m_bCloseOnTick) { + disconnect(DisconnectPacket::eDisconnect_Closed); + return; + } - didTick = false; - tickCount++; - connection->tick(); - if(done) return; + didTick = false; + tickCount++; + connection->tick(); + if (done) return; - if ((tickCount - lastKeepAliveTick) > 20 * 1) - { - lastKeepAliveTick = tickCount; - lastKeepAliveTime = System::nanoTime() / 1000000; - lastKeepAliveId = random.nextInt(); - send( std::shared_ptr( new KeepAlivePacket(lastKeepAliveId) ) ); - } -// if (!didTick) { -// player->doTick(false); -// } - - if (chatSpamTickCount > 0) - { - chatSpamTickCount--; - } - if (dropSpamTickCount > 0) - { - dropSpamTickCount--; - } + if ((tickCount - lastKeepAliveTick) > 20 * 1) { + lastKeepAliveTick = tickCount; + lastKeepAliveTime = System::nanoTime() / 1000000; + lastKeepAliveId = random.nextInt(); + send(std::shared_ptr( + new KeepAlivePacket(lastKeepAliveId))); + } + // if (!didTick) { + // player->doTick(false); + // } + + if (chatSpamTickCount > 0) { + chatSpamTickCount--; + } + if (dropSpamTickCount > 0) { + dropSpamTickCount--; + } } -void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) -{ - EnterCriticalSection(&done_cs); - if( done ) - { - LeaveCriticalSection(&done_cs); - return; - } +void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) { + EnterCriticalSection(&done_cs); + if (done) { + LeaveCriticalSection(&done_cs); + return; + } - app.DebugPrintf("PlayerConnection disconect reason: %d\n", reason ); - player->disconnect(); + app.DebugPrintf("PlayerConnection disconect reason: %d\n", reason); + player->disconnect(); - // 4J Stu - Need to remove the player from the receiving list before their socket is NULLed so that we can find another player on their system - server->getPlayers()->removePlayerFromReceiving( player ); - send( std::shared_ptr( new DisconnectPacket(reason) )); - connection->sendAndQuit(); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); - if(getWasKicked()) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); - } - - server->getPlayers()->remove(player); - done = true; - LeaveCriticalSection(&done_cs); + // 4J Stu - Need to remove the player from the receiving list before their + // socket is NULLed so that we can find another player on their system + server->getPlayers()->removePlayerFromReceiving(player); + send(std::shared_ptr(new DisconnectPacket(reason))); + connection->sendAndQuit(); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + player->name + L" left the game.") ) ); + if (getWasKicked()) { + server->getPlayers()->broadcastAll( + std::shared_ptr(new ChatPacket( + player->name, ChatPacket::e_ChatPlayerKickedFromGame))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame))); + } + + server->getPlayers()->remove(player); + done = true; + LeaveCriticalSection(&done_cs); } -void PlayerConnection::handlePlayerInput(std::shared_ptr packet) -{ - player->setPlayerInput(packet->getXa(), packet->getYa(), packet->isJumping(), packet->isSneaking(), packet->getXRot(), packet->getYRot()); +void PlayerConnection::handlePlayerInput( + std::shared_ptr packet) { + player->setPlayerInput(packet->getXa(), packet->getYa(), + packet->isJumping(), packet->isSneaking(), + packet->getXRot(), packet->getYRot()); } -void PlayerConnection::handleMovePlayer(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); +void PlayerConnection::handleMovePlayer( + std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); - didTick = true; - if(synched) m_bHasClientTickedOnce = true; + didTick = true; + if (synched) m_bHasClientTickedOnce = true; - if (player->wonGame) return; + if (player->wonGame) return; - if (!synched) - { - double yDiff = packet->y - yLastOk; - if (packet->x == xLastOk && yDiff * yDiff < 0.01 && packet->z == zLastOk) - { - synched = true; - } - } + if (!synched) { + double yDiff = packet->y - yLastOk; + if (packet->x == xLastOk && yDiff * yDiff < 0.01 && + packet->z == zLastOk) { + synched = true; + } + } - if (synched) - { - if (player->riding != NULL) - { - - float yRotT = player->yRot; - float xRotT = player->xRot; - player->riding->positionRider(); - double xt = player->x; - double yt = player->y; - double zt = player->z; - double xxa = 0; - double zza = 0; - if (packet->hasRot) - { - yRotT = packet->yRot; - xRotT = packet->xRot; - } - if (packet->hasPos && packet->y == -999 && packet->yView == -999) - { - // CraftBukkit start - if (abs(packet->x) > 1 || abs(packet->z) > 1) - { - //System.err.println(player.name + " was caught trying to crash the server with an invalid position."); + if (synched) { + if (player->riding != NULL) { + float yRotT = player->yRot; + float xRotT = player->xRot; + player->riding->positionRider(); + double xt = player->x; + double yt = player->y; + double zt = player->z; + double xxa = 0; + double zza = 0; + if (packet->hasRot) { + yRotT = packet->yRot; + xRotT = packet->xRot; + } + if (packet->hasPos && packet->y == -999 && packet->yView == -999) { + // CraftBukkit start + if (abs(packet->x) > 1 || abs(packet->z) > 1) { + // System.err.println(player.name + " was caught trying to + // crash the server with an invalid position."); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls was caught trying to crash the server with an invalid position.", player->name.c_str()); + wprintf( + L"%ls was caught trying to crash the server with an " + L"invalid position.", + player->name.c_str()); #endif - disconnect(DisconnectPacket::eDisconnect_IllegalPosition);//"Nope!"); - return; - } - // CraftBukkit end - xxa = packet->x; - zza = packet->z; - } + disconnect(DisconnectPacket:: + eDisconnect_IllegalPosition); //"Nope!"); + return; + } + // CraftBukkit end + xxa = packet->x; + zza = packet->z; + } + player->onGround = packet->onGround; - player->onGround = packet->onGround; + player->doTick(false); + player->move(xxa, 0, zza); + player->absMoveTo(xt, yt, zt, yRotT, xRotT); + player->xd = xxa; + player->zd = zza; + if (player->riding != NULL) level->forceTick(player->riding, true); + if (player->riding != NULL) player->riding->positionRider(); + server->getPlayers()->move(player); + xLastOk = player->x; + yLastOk = player->y; + zLastOk = player->z; + ((Level*)level)->tick(player); - player->doTick(false); - player->move(xxa, 0, zza); - player->absMoveTo(xt, yt, zt, yRotT, xRotT); - player->xd = xxa; - player->zd = zza; - if (player->riding != NULL) level->forceTick(player->riding, true); - if (player->riding != NULL) player->riding->positionRider(); - server->getPlayers()->move(player); - xLastOk = player->x; - yLastOk = player->y; - zLastOk = player->z; - ((Level *)level)->tick(player); + return; + } - return; - } + if (player->isSleeping()) { + player->doTick(false); + player->absMoveTo(xLastOk, yLastOk, zLastOk, player->yRot, + player->xRot); + ((Level*)level)->tick(player); + return; + } - if (player->isSleeping()) - { - player->doTick(false); - player->absMoveTo(xLastOk, yLastOk, zLastOk, player->yRot, player->xRot); - ((Level *)level)->tick(player); - return; - } + double startY = player->y; + xLastOk = player->x; + yLastOk = player->y; + zLastOk = player->z; - double startY = player->y; - xLastOk = player->x; - yLastOk = player->y; - zLastOk = player->z; + double xt = player->x; + double yt = player->y; + double zt = player->z; + float yRotT = player->yRot; + float xRotT = player->xRot; - double xt = player->x; - double yt = player->y; - double zt = player->z; + if (packet->hasPos && packet->y == -999 && packet->yView == -999) { + packet->hasPos = false; + } - float yRotT = player->yRot; - float xRotT = player->xRot; + if (packet->hasPos) { + xt = packet->x; + yt = packet->y; + zt = packet->z; + double yd = packet->yView - packet->y; + if (!player->isSleeping() && (yd > 1.65 || yd < 0.1)) { + disconnect(DisconnectPacket::eDisconnect_IllegalStance); + // logger.warning(player->name + " had an illegal + // stance: " + yd); + return; + } + if (abs(packet->x) > 32000000 || abs(packet->z) > 32000000) { + disconnect(DisconnectPacket::eDisconnect_IllegalPosition); + return; + } + } + if (packet->hasRot) { + yRotT = packet->yRot; + xRotT = packet->xRot; + } - if (packet->hasPos && packet->y == -999 && packet->yView == -999) - { - packet->hasPos = false; - } + // 4J Stu Added to stop server player y pos being different than client + // when flying + if (player->abilities.mayfly || player->isAllowedToFly()) { + player->abilities.flying = packet->isFlying; + } else + player->abilities.flying = false; - if (packet->hasPos) - { - xt = packet->x; - yt = packet->y; - zt = packet->z; - double yd = packet->yView - packet->y; - if (!player->isSleeping() && (yd > 1.65 || yd < 0.1)) - { - disconnect(DisconnectPacket::eDisconnect_IllegalStance); -// logger.warning(player->name + " had an illegal stance: " + yd); - return; - } - if (abs(packet->x) > 32000000 || abs(packet->z) > 32000000) - { - disconnect(DisconnectPacket::eDisconnect_IllegalPosition); - return; - } - } - if (packet->hasRot) - { - yRotT = packet->yRot; - xRotT = packet->xRot; - } + player->doTick(false); + player->ySlideOffset = 0; + player->absMoveTo(xLastOk, yLastOk, zLastOk, yRotT, xRotT); - // 4J Stu Added to stop server player y pos being different than client when flying - if(player->abilities.mayfly || player->isAllowedToFly() ) - { - player->abilities.flying = packet->isFlying; - } - else player->abilities.flying = false; + if (!synched) return; - player->doTick(false); - player->ySlideOffset = 0; - player->absMoveTo(xLastOk, yLastOk, zLastOk, yRotT, xRotT); + double xDist = xt - player->x; + double yDist = yt - player->y; + double zDist = zt - player->z; - if (!synched) return; + double dist = xDist * xDist + yDist * yDist + zDist * zDist; - double xDist = xt - player->x; - double yDist = yt - player->y; - double zDist = zt - player->z; - - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - - // 4J-PB - removing this one for now - /*if (dist > 100.0f) - { + // 4J-PB - removing this one for now + /*if (dist > 100.0f) + { // logger.warning(player->name + " moved too quickly!"); - disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); -// System.out.println("Moved too quickly at " + xt + ", " + yt + ", " + zt); -// teleport(player->x, player->y, player->z, player->yRot, player->xRot); - return; - } - */ + disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); +// System.out.println("Moved too quickly at " + xt + ", " + yt + +", " + zt); +// teleport(player->x, player->y, player->z, player->yRot, +player->xRot); return; + } + */ - float r = 1 / 16.0f; - bool oldOk = level->getCubes(player, player->bb->copy()->shrink(r, r, r))->empty(); + float r = 1 / 16.0f; + bool oldOk = + level->getCubes(player, player->bb->copy()->shrink(r, r, r)) + ->empty(); - if (player->onGround && !packet->onGround && yDist > 0) - { - // assume the player made a jump - player->causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); - } + if (player->onGround && !packet->onGround && yDist > 0) { + // assume the player made a jump + player->causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); + } - player->move(xDist, yDist, zDist); + player->move(xDist, yDist, zDist); - // 4J Stu - It is possible that we are no longer synched (eg By moving into an End Portal), so we should stop any further movement based on this packet - // Fix for #87764 - Code: Gameplay: Host cannot move and experiences End World Chunks flickering, while in Splitscreen Mode - // and Fix for #87788 - Code: Gameplay: Client cannot move and experiences End World Chunks flickering, while in Splitscreen Mode - if (!synched) return; + // 4J Stu - It is possible that we are no longer synched (eg By moving + // into an End Portal), so we should stop any further movement based on + // this packet Fix for #87764 - Code: Gameplay: Host cannot move and + // experiences End World Chunks flickering, while in Splitscreen Mode + // and Fix for #87788 - Code: Gameplay: Client cannot move and + // experiences End World Chunks flickering, while in Splitscreen Mode + if (!synched) return; - player->onGround = packet->onGround; - // Since server players don't call travel we check food exhaustion - // here - player->checkMovementStatistiscs(xDist, yDist, zDist); + player->onGround = packet->onGround; + // Since server players don't call travel we check food exhaustion + // here + player->checkMovementStatistiscs(xDist, yDist, zDist); - double oyDist = yDist; + double oyDist = yDist; - xDist = xt - player->x; - yDist = yt - player->y; + xDist = xt - player->x; + yDist = yt - player->y; - // 4J-PB - line below will always be true! - if (yDist > -0.5 || yDist < 0.5) - { - yDist = 0; - } - zDist = zt - player->z; - dist = xDist * xDist + yDist * yDist + zDist * zDist; - bool fail = false; - if (dist > 0.25 * 0.25 && !player->isSleeping() && !player->gameMode->isCreative() && !player->isAllowedToFly()) - { - fail = true; + // 4J-PB - line below will always be true! + if (yDist > -0.5 || yDist < 0.5) { + yDist = 0; + } + zDist = zt - player->z; + dist = xDist * xDist + yDist * yDist + zDist * zDist; + bool fail = false; + if (dist > 0.25 * 0.25 && !player->isSleeping() && + !player->gameMode->isCreative() && !player->isAllowedToFly()) { + fail = true; // logger.warning(player->name + " moved wrongly!"); // System.out.println("Got position " + xt + ", " + yt + ", " + zt); -// System.out.println("Expected " + player->x + ", " + player->y + ", " + player->z); +// System.out.println("Expected " + player->x + ", " + player->y + ", +// " + player->z); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls moved wrongly!\n",player->name.c_str()); - app.DebugPrintf("Got position %f, %f, %f\n", xt,yt,zt); - app.DebugPrintf("Expected %f, %f, %f\n", player->x, player->y, player->z); + wprintf(L"%ls moved wrongly!\n", player->name.c_str()); + app.DebugPrintf("Got position %f, %f, %f\n", xt, yt, zt); + app.DebugPrintf("Expected %f, %f, %f\n", player->x, player->y, + player->z); #endif - } - player->absMoveTo(xt, yt, zt, yRotT, xRotT); + } + player->absMoveTo(xt, yt, zt, yRotT, xRotT); - bool newOk = level->getCubes(player, player->bb->copy()->shrink(r, r, r))->empty(); - if (oldOk && (fail || !newOk) && !player->isSleeping()) - { - teleport(xLastOk, yLastOk, zLastOk, yRotT, xRotT); - return; - } - AABB *testBox = player->bb->copy()->grow(r, r, r)->expand(0, -0.55, 0); - // && server.level.getCubes(player, testBox).size() == 0 - if (!server->isFlightAllowed() && !player->gameMode->isCreative() && !level->containsAnyBlocks(testBox) && !player->isAllowedToFly() ) - { - if (oyDist >= (-0.5f / 16.0f)) - { - aboveGroundTickCount++; - if (aboveGroundTickCount > 80) - { -// logger.warning(player->name + " was kicked for floating too long!"); + bool newOk = + level->getCubes(player, player->bb->copy()->shrink(r, r, r)) + ->empty(); + if (oldOk && (fail || !newOk) && !player->isSleeping()) { + teleport(xLastOk, yLastOk, zLastOk, yRotT, xRotT); + return; + } + AABB* testBox = player->bb->copy()->grow(r, r, r)->expand(0, -0.55, 0); + // && server.level.getCubes(player, testBox).size() == 0 + if (!server->isFlightAllowed() && !player->gameMode->isCreative() && + !level->containsAnyBlocks(testBox) && !player->isAllowedToFly()) { + if (oyDist >= (-0.5f / 16.0f)) { + aboveGroundTickCount++; + if (aboveGroundTickCount > 80) { +// logger.warning(player->name + " was kicked for floating +// too long!"); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls was kicked for floating too long!\n", player->name.c_str()); + wprintf(L"%ls was kicked for floating too long!\n", + player->name.c_str()); #endif - disconnect(DisconnectPacket::eDisconnect_NoFlying); - return; - } - } - } - else - { - aboveGroundTickCount = 0; - } - - player->onGround = packet->onGround; - server->getPlayers()->move(player); - player->doCheckFallDamage(player->y - startY, packet->onGround); - } + disconnect(DisconnectPacket::eDisconnect_NoFlying); + return; + } + } + } else { + aboveGroundTickCount = 0; + } + player->onGround = packet->onGround; + server->getPlayers()->move(player); + player->doCheckFallDamage(player->y - startY, packet->onGround); + } } -void PlayerConnection::teleport(double x, double y, double z, float yRot, float xRot, bool sendPacket /*= true*/) -{ - synched = false; - xLastOk = x; - yLastOk = y; - zLastOk = z; - player->absMoveTo(x, y, z, yRot, xRot); - // 4J - note that 1.62 is added to the height here as the client connection that receives this will presume it represents y + heightOffset at that end - // This is different to the way that height is sent back to the server, where it represents the bottom of the player bounding volume - if(sendPacket) player->connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(x, y + 1.62f, y, z, yRot, xRot, false, false) ) ); +void PlayerConnection::teleport(double x, double y, double z, float yRot, + float xRot, bool sendPacket /*= true*/) { + synched = false; + xLastOk = x; + yLastOk = y; + zLastOk = z; + player->absMoveTo(x, y, z, yRot, xRot); + // 4J - note that 1.62 is added to the height here as the client connection + // that receives this will presume it represents y + heightOffset at that + // end This is different to the way that height is sent back to the server, + // where it represents the bottom of the player bounding volume + if (sendPacket) + player->connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + x, y + 1.62f, y, z, yRot, xRot, false, false))); } -void PlayerConnection::handlePlayerAction(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); +void PlayerConnection::handlePlayerAction( + std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); - if (packet->action == PlayerActionPacket::DROP_ITEM) - { - player->drop(); - return; - } - else if (packet->action == PlayerActionPacket::RELEASE_USE_ITEM) - { - player->releaseUsingItem(); - return; - } - // 4J Stu - We don't have ops, so just use the levels setting - bool canEditSpawn = level->canEditSpawn; // = level->dimension->id != 0 || server->players->isOp(player->name); - bool shouldVerifyLocation = false; - if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) shouldVerifyLocation = true; - if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) shouldVerifyLocation = true; + if (packet->action == PlayerActionPacket::DROP_ITEM) { + player->drop(); + return; + } else if (packet->action == PlayerActionPacket::RELEASE_USE_ITEM) { + player->releaseUsingItem(); + return; + } + // 4J Stu - We don't have ops, so just use the levels setting + bool canEditSpawn = + level->canEditSpawn; // = level->dimension->id != 0 || + // server->players->isOp(player->name); + bool shouldVerifyLocation = false; + if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) + shouldVerifyLocation = true; + if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) + shouldVerifyLocation = true; - int x = packet->x; - int y = packet->y; - int z = packet->z; - if (shouldVerifyLocation) - { - double xDist = player->x - (x + 0.5); - // there is a mismatch between the player's camera and the player's - // position, so add 1.5 blocks - double yDist = player->y - (y + 0.5) + 1.5; - double zDist = player->z - (z + 0.5); - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - if (dist > 6 * 6) - { - return; - } - if (y >= server->getMaxBuildHeight()) - { - return; - } - } - Pos *spawnPos = level->getSharedSpawnPos(); - int xd = (int) Mth::abs((float)(x - spawnPos->x)); - int zd = (int) Mth::abs((float)(z - spawnPos->z)); - delete spawnPos; - if (xd > zd) zd = xd; - if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) - { - if (zd > 16 || canEditSpawn) player->gameMode->startDestroyBlock(x, y, z, packet->face); - else player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + int x = packet->x; + int y = packet->y; + int z = packet->z; + if (shouldVerifyLocation) { + double xDist = player->x - (x + 0.5); + // there is a mismatch between the player's camera and the player's + // position, so add 1.5 blocks + double yDist = player->y - (y + 0.5) + 1.5; + double zDist = player->z - (z + 0.5); + double dist = xDist * xDist + yDist * yDist + zDist * zDist; + if (dist > 6 * 6) { + return; + } + if (y >= server->getMaxBuildHeight()) { + return; + } + } + Pos* spawnPos = level->getSharedSpawnPos(); + int xd = (int)Mth::abs((float)(x - spawnPos->x)); + int zd = (int)Mth::abs((float)(z - spawnPos->z)); + delete spawnPos; + if (xd > zd) zd = xd; + if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) { + if (zd > 16 || canEditSpawn) + player->gameMode->startDestroyBlock(x, y, z, packet->face); + else + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); - } - else if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) - { - player->gameMode->stopDestroyBlock(x, y, z); - server->getPlayers()->prioritiseTileChanges(x, y, z, level->dimension->id); // 4J added - make sure that the update packets for this get prioritised over other general world updates - if (level->getTile(x, y, z) != 0) player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } - else if (packet->action == PlayerActionPacket::ABORT_DESTROY_BLOCK) - { - player->gameMode->abortDestroyBlock(x, y, z); - if (level->getTile(x, y, z) != 0) player->connection->send(std::shared_ptr( new TileUpdatePacket(x, y, z, level))); - } - else if (packet->action == PlayerActionPacket::GET_UPDATED_BLOCK) - { - double xDist = player->x - (x + 0.5); - double yDist = player->y - (y + 0.5); - double zDist = player->z - (z + 0.5); - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - if (dist < 16 * 16) - { - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } - } - - // 4J Stu - Don't change the levels state - //level->canEditSpawn = false; + } else if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) { + player->gameMode->stopDestroyBlock(x, y, z); + server->getPlayers()->prioritiseTileChanges( + x, y, z, + level->dimension + ->id); // 4J added - make sure that the update packets for this + // get prioritised over other general world updates + if (level->getTile(x, y, z) != 0) + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } else if (packet->action == PlayerActionPacket::ABORT_DESTROY_BLOCK) { + player->gameMode->abortDestroyBlock(x, y, z); + if (level->getTile(x, y, z) != 0) + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } else if (packet->action == PlayerActionPacket::GET_UPDATED_BLOCK) { + double xDist = player->x - (x + 0.5); + double yDist = player->y - (y + 0.5); + double zDist = player->z - (z + 0.5); + double dist = xDist * xDist + yDist * yDist + zDist * zDist; + if (dist < 16 * 16) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } + } + // 4J Stu - Don't change the levels state + // level->canEditSpawn = false; } -void PlayerConnection::handleUseItem(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); - std::shared_ptr item = player->inventory->getSelected(); - bool informClient = false; - int x = packet->getX(); - int y = packet->getY(); - int z = packet->getZ(); - int face = packet->getFace(); - - // 4J Stu - We don't have ops, so just use the levels setting - bool canEditSpawn = level->canEditSpawn; // = level->dimension->id != 0 || server->players->isOp(player->name); - if (packet->getFace() == 255) - { - if (item == NULL) return; - player->gameMode->useItem(player, level, item); - } - else if ((packet->getY() < server->getMaxBuildHeight() - 1) || (packet->getFace() != Facing::UP && packet->getY() < server->getMaxBuildHeight())) - { - Pos *spawnPos = level->getSharedSpawnPos(); - int xd = (int) Mth::abs((float)(x - spawnPos->x)); - int zd = (int) Mth::abs((float)(z - spawnPos->z)); - delete spawnPos; - if (xd > zd) zd = xd; - if (synched && player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) < 8 * 8) - { - if (zd > 16 || canEditSpawn) - { - player->gameMode->useItemOn(player, level, item, x, y, z, face, packet->getClickX(), packet->getClickY(), packet->getClickZ()); - } - } +void PlayerConnection::handleUseItem(std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); + std::shared_ptr item = player->inventory->getSelected(); + bool informClient = false; + int x = packet->getX(); + int y = packet->getY(); + int z = packet->getZ(); + int face = packet->getFace(); - informClient = true; - } - else - { - //player->connection->send(std::shared_ptr(new ChatPacket("\u00A77Height limit for building is " + server->maxBuildHeight))); - informClient = true; - } + // 4J Stu - We don't have ops, so just use the levels setting + bool canEditSpawn = + level->canEditSpawn; // = level->dimension->id != 0 || + // server->players->isOp(player->name); + if (packet->getFace() == 255) { + if (item == NULL) return; + player->gameMode->useItem(player, level, item); + } else if ((packet->getY() < server->getMaxBuildHeight() - 1) || + (packet->getFace() != Facing::UP && + packet->getY() < server->getMaxBuildHeight())) { + Pos* spawnPos = level->getSharedSpawnPos(); + int xd = (int)Mth::abs((float)(x - spawnPos->x)); + int zd = (int)Mth::abs((float)(z - spawnPos->z)); + delete spawnPos; + if (xd > zd) zd = xd; + if (synched && + player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) < 8 * 8) { + if (zd > 16 || canEditSpawn) { + player->gameMode->useItemOn( + player, level, item, x, y, z, face, packet->getClickX(), + packet->getClickY(), packet->getClickZ()); + } + } - if (informClient) - { + informClient = true; + } else { + // player->connection->send(std::shared_ptr(new + // ChatPacket("\u00A77Height limit for building is " + + // server->maxBuildHeight))); + informClient = true; + } - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + if (informClient) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - - // 4J - Fixes an issue where pistons briefly disappear when retracting. The pistons themselves shouldn't have their change from being pistonBase_Id to pistonMovingPiece_Id - // directly sent to the client, as this will happen on the client as a result of it actioning (via a tile event) the retraction of the piston locally. However, by putting a switch - // beside a piston and then performing an action on the side of it facing a piston, the following line of code will send a TileUpdatePacket containing the change to pistonMovingPiece_Id - // to the client, and this packet is received before the piston retract action happens - when the piston retract then occurs, it doesn't work properly because the piston tile - // isn't what it is expecting. - if( level->getTile(x,y,z) != Tile::pistonMovingPiece_Id ) - { - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - } + // 4J - Fixes an issue where pistons briefly disappear when retracting. + // The pistons themselves shouldn't have their change from being + // pistonBase_Id to pistonMovingPiece_Id directly sent to the client, + // as this will happen on the client as a result of it actioning (via a + // tile event) the retraction of the piston locally. However, by putting + // a switch beside a piston and then performing an action on the side of + // it facing a piston, the following line of code will send a + // TileUpdatePacket containing the change to pistonMovingPiece_Id to the + // client, and this packet is received before the piston retract action + // happens - when the piston retract then occurs, it doesn't work + // properly because the piston tile isn't what it is expecting. + if (level->getTile(x, y, z) != Tile::pistonMovingPiece_Id) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } + } - item = player->inventory->getSelected(); - if (item != NULL && item->count == 0) - { - player->inventory->items[player->inventory->selected] = nullptr; - item = nullptr; - } + item = player->inventory->getSelected(); + if (item != NULL && item->count == 0) { + player->inventory->items[player->inventory->selected] = nullptr; + item = nullptr; + } - if (item == NULL || item->getUseDuration() == 0) - { - player->ignoreSlotUpdateHack = true; - player->inventory->items[player->inventory->selected] = ItemInstance::clone(player->inventory->items[player->inventory->selected]); - Slot *s = player->containerMenu->getSlotFor(player->inventory, player->inventory->selected); - player->containerMenu->broadcastChanges(); - player->ignoreSlotUpdateHack = false; + if (item == NULL || item->getUseDuration() == 0) { + player->ignoreSlotUpdateHack = true; + player->inventory->items[player->inventory->selected] = + ItemInstance::clone( + player->inventory->items[player->inventory->selected]); + Slot* s = player->containerMenu->getSlotFor( + player->inventory, player->inventory->selected); + player->containerMenu->broadcastChanges(); + player->ignoreSlotUpdateHack = false; - if (!ItemInstance::matches(player->inventory->getSelected(), packet->getItem())) - { - send( std::shared_ptr( new ContainerSetSlotPacket(player->containerMenu->containerId, s->index, player->inventory->getSelected()) ) ); - } - } - - // 4J Stu - Don't change the levels state - //level->canEditSpawn = false; + if (!ItemInstance::matches(player->inventory->getSelected(), + packet->getItem())) { + send(std::shared_ptr( + new ContainerSetSlotPacket(player->containerMenu->containerId, + s->index, + player->inventory->getSelected()))); + } + } + // 4J Stu - Don't change the levels state + // level->canEditSpawn = false; } -void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ - EnterCriticalSection(&done_cs); - if( done ) return; -// logger.info(player.name + " lost connection: " + reason); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); - if(getWasKicked()) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); - } - server->getPlayers()->remove(player); - done = true; - LeaveCriticalSection(&done_cs); +void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { + EnterCriticalSection(&done_cs); + if (done) return; + // logger.info(player.name + " lost connection: " + reason); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + player->name + L" left the game.") ) ); + if (getWasKicked()) { + server->getPlayers()->broadcastAll( + std::shared_ptr(new ChatPacket( + player->name, ChatPacket::e_ChatPlayerKickedFromGame))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame))); + } + server->getPlayers()->remove(player); + done = true; + LeaveCriticalSection(&done_cs); } -void PlayerConnection::onUnhandledPacket(std::shared_ptr packet) -{ -// logger.warning(getClass() + " wasn't prepared to deal with a " + packet.getClass()); - disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); +void PlayerConnection::onUnhandledPacket(std::shared_ptr packet) { + // logger.warning(getClass() + " wasn't prepared to deal with a " + + // packet.getClass()); + disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); } -void PlayerConnection::send(std::shared_ptr packet) -{ - if( connection->getSocket() != NULL ) - { - if( !server->getPlayers()->canReceiveAllPackets( player ) ) - { - // Check if we are allowed to send this packet type - if( !Packet::canSendToAnyClient(packet) ) - { - //wprintf(L"Not the systems primary player, so not sending them a packet : %ls / %d\n", player->name.c_str(), packet->getId() ); - return; - } - } - connection->send(packet); - } +void PlayerConnection::send(std::shared_ptr packet) { + if (connection->getSocket() != NULL) { + if (!server->getPlayers()->canReceiveAllPackets(player)) { + // Check if we are allowed to send this packet type + if (!Packet::canSendToAnyClient(packet)) { + // wprintf(L"Not the systems primary player, so not sending them + // a packet : %ls / %d\n", player->name.c_str(), packet->getId() + // ); + return; + } + } + connection->send(packet); + } } // 4J Added -void PlayerConnection::queueSend(std::shared_ptr packet) -{ - if( connection->getSocket() != NULL ) - { - if( !server->getPlayers()->canReceiveAllPackets( player ) ) - { - // Check if we are allowed to send this packet type - if( !Packet::canSendToAnyClient(packet) ) - { - //wprintf(L"Not the systems primary player, so not queueing them a packet : %ls\n", connection->getSocket()->getPlayer()->GetGamertag() ); - return; - } - } - connection->queueSend(packet); - } +void PlayerConnection::queueSend(std::shared_ptr packet) { + if (connection->getSocket() != NULL) { + if (!server->getPlayers()->canReceiveAllPackets(player)) { + // Check if we are allowed to send this packet type + if (!Packet::canSendToAnyClient(packet)) { + // wprintf(L"Not the systems primary player, so not queueing + // them a packet : %ls\n", + // connection->getSocket()->getPlayer()->GetGamertag() ); + return; + } + } + connection->queueSend(packet); + } } -void PlayerConnection::handleSetCarriedItem(std::shared_ptr packet) -{ - if (packet->slot < 0 || packet->slot >= Inventory::getSelectionSize()) - { -// logger.warning(player.name + " tried to set an invalid carried item"); - return; - } - player->inventory->selected = packet->slot; +void PlayerConnection::handleSetCarriedItem( + std::shared_ptr packet) { + if (packet->slot < 0 || packet->slot >= Inventory::getSelectionSize()) { + // logger.warning(player.name + " tried to set an invalid carried + // item"); + return; + } + player->inventory->selected = packet->slot; } -void PlayerConnection::handleChat(std::shared_ptr packet) -{ - // 4J - TODO +void PlayerConnection::handleChat(std::shared_ptr packet) { + // 4J - TODO #if 0 std::wstring message = packet->message; if (message.length() > SharedConstants::maxChatLength) @@ -670,756 +678,850 @@ void PlayerConnection::handleChat(std::shared_ptr packet) #endif } -void PlayerConnection::handleCommand(const std::wstring& message) -{ - // 4J - TODO +void PlayerConnection::handleCommand(const std::wstring& message) { + // 4J - TODO #if 0 server.getCommandDispatcher().performCommand(player, message); #endif } -void PlayerConnection::handleAnimate(std::shared_ptr packet) -{ - if (packet->action == AnimatePacket::SWING) - { - player->swing(); - } -} - -void PlayerConnection::handlePlayerCommand(std::shared_ptr packet) -{ - if (packet->action == PlayerCommandPacket::START_SNEAKING) - { - player->setSneaking(true); - } - else if (packet->action == PlayerCommandPacket::STOP_SNEAKING) - { - player->setSneaking(false); - } - else if (packet->action == PlayerCommandPacket::START_SPRINTING) - { - player->setSprinting(true); - } - else if (packet->action == PlayerCommandPacket::STOP_SPRINTING) - { - player->setSprinting(false); - } - else if (packet->action == PlayerCommandPacket::STOP_SLEEPING) - { - player->stopSleepInBed(false, true, true); - synched = false; - } - else if (packet->action == PlayerCommandPacket::START_IDLEANIM) - { - player->setIsIdle(true); - } - else if (packet->action == PlayerCommandPacket::STOP_IDLEANIM) - { - player->setIsIdle(false); - } - -} - -void PlayerConnection::setShowOnMaps(bool bVal) -{ - player->setShowOnMaps(bVal); -} - -void PlayerConnection::handleDisconnect(std::shared_ptr packet) -{ - // 4J Stu - Need to remove the player from the receiving list before their socket is NULLed so that we can find another player on their system - server->getPlayers()->removePlayerFromReceiving( player ); - connection->close(DisconnectPacket::eDisconnect_Quitting); -} - -int PlayerConnection::countDelayedPackets() -{ - return connection->countDelayedPackets(); -} - -void PlayerConnection::info(const std::wstring& string) -{ - // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( std::shared_ptr( new ChatPacket(L"§7" + string) ) ); -} - -void PlayerConnection::warn(const std::wstring& string) -{ - // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( std::shared_ptr( new ChatPacket(L"§9" + string) ) ); -} - -std::wstring PlayerConnection::getConsoleName() -{ - return player->name; -} - -void PlayerConnection::handleInteract(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); - std::shared_ptr target = level->getEntity(packet->target); - - // Fix for #8218 - Gameplay: Attacking zombies from a different level often results in no hits being registered - // 4J Stu - If the client says that we hit something, then agree with it. The canSee can fail here as it checks - // a ray from head->head, but we may actually be looking at a different part of the entity that can be seen - // even though the ray is blocked. - if (target != NULL) // && player->canSee(target) && player->distanceToSqr(target) < 6 * 6) - { - //boole canSee = player->canSee(target); - //double maxDist = 6 * 6; - //if (!canSee) - //{ - // maxDist = 3 * 3; - //} - - //if (player->distanceToSqr(target) < maxDist) - //{ - if (packet->action == InteractPacket::INTERACT) - { - player->interact(target); - } - else if (packet->action == InteractPacket::ATTACK) - { - player->attack(target); - } - //} - } - -} - -bool PlayerConnection::canHandleAsyncPackets() -{ - return true; -} - -void PlayerConnection::handleTexture(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - - if(packet->dataBytes==0) - { - // Request for texture -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); -#endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); - - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); - } - else - { - m_texturesRequested.push_back( packet->textureName ); - } - } - else - { - // Response with texture data -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received custom texture %ls\n",packet->textureName.c_str()); -#endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dataBytes); - server->connection->handleTextureReceived(packet->textureName); - } -} - -void PlayerConnection::handleTextureAndGeometry(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - - if(packet->dwTextureBytes==0) - { - // Request for texture and geometry -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); -#endif - std::uint8_t *pbData=NULL; - unsigned int dwTextureBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwTextureBytes); - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); - - if(dwTextureBytes!=0) - { - - if(pDLCSkinFile) - { - if(pDLCSkinFile->getAdditionalBoxesCount()!=0) - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); - } - else - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes) ) ); - } - } - else - { - // we don't have the dlc skin, so retrieve the data from the app store - std::vector *pvSkinBoxes = app.GetAdditionalSkinBoxes(packet->dwSkinID); - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); - - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pvSkinBoxes,uiAnimOverrideBitmask) ) ); - } - } - else - { - m_texturesRequested.push_back( packet->textureName ); - } - } - else - { - // Response with texture and geometry data -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received custom texture %ls and geometry\n",packet->textureName.c_str()); -#endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dwTextureBytes); - - // add the geometry to the app list - if(packet->dwBoxC!=0) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Adding skin boxes for skin id %X, box count %d\n",packet->dwSkinID,packet->dwBoxC); -#endif - app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); - } - // Add the anim override - app.SetAnimOverrideBitmask(packet->dwSkinID,packet->uiAnimOverrideBitmask); - - player->setCustomSkin(packet->dwSkinID); - - server->connection->handleTextureAndGeometryReceived(packet->textureName); - } -} - -void PlayerConnection::handleTextureReceived(const std::wstring &textureName) -{ - // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) - { - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(textureName,&pbData,&dwBytes); - - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(textureName,pbData,dwBytes) ) ); - m_texturesRequested.erase(it); - } - } -} - -void PlayerConnection::handleTextureAndGeometryReceived(const std::wstring &textureName) -{ - // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) - { - std::uint8_t *pbData=NULL; - unsigned int dwTextureBytes=0; - app.GetMemFileDetails(textureName,&pbData,&dwTextureBytes); - DLCSkinFile *pDLCSkinFile=app.m_dlcManager.getSkinFile(textureName); - - if(dwTextureBytes!=0) - { - if(pDLCSkinFile && (pDLCSkinFile->getAdditionalBoxesCount()!=0)) - { - send( std::shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); - } - else - { - // get the data from the app - std::uint32_t dwSkinID = app.getSkinIdFromPath(textureName); - std::vector *pvSkinBoxes = app.GetAdditionalSkinBoxes(dwSkinID); - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(dwSkinID); - - send( std::shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask) ) ); - } - m_texturesRequested.erase(it); - } - } -} - -void PlayerConnection::handleTextureChange(std::shared_ptr packet) -{ - switch(packet->action) - { - case TextureChangePacket::e_TextureChange_Skin: - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); -#ifndef _CONTENT_PACKAGE - wprintf(L"Skin for server player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); -#endif - break; - case TextureChangePacket::e_TextureChange_Cape: - player->setCustomCape( Player::getCapeIdFromPath( packet->path ) ); - //player->customTextureUrl2 = packet->path; -#ifndef _CONTENT_PACKAGE - wprintf(L"Cape for server player %ls has changed to %ls\n", player->name.c_str(), player->customTextureUrl2.c_str() ); -#endif - break; - } - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( server->connection->addPendingTextureRequest(packet->path)) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",packet->path.c_str(), player->name.c_str()); -#endif - send(std::shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - } - server->getPlayers()->broadcastAll( std::shared_ptr( new TextureChangePacket(player,packet->action,packet->path) ), player->dimension ); -} - -void PlayerConnection::handleTextureAndGeometryChange(std::shared_ptr packet) -{ - - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); -#ifndef _CONTENT_PACKAGE - wprintf(L"PlayerConnection::handleTextureAndGeometryChange - Skin for server player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); -#endif - - - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( server->connection->addPendingTextureRequest(packet->path)) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",packet->path.c_str(), player->name.c_str()); -#endif - send(std::shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - - player->setCustomSkin(packet->dwSkinID); - - // If we already have the texture, then we already have the model parts too - //app.SetAdditionalSkinBoxes(packet->dwSkinID,) - //DebugBreak(); - } - server->getPlayers()->broadcastAll( std::shared_ptr( new TextureAndGeometryChangePacket(player,packet->path) ), player->dimension ); -} - -void PlayerConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) - { - // Need to check that this player has permission to change each individual setting? - - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) - { - app.SetGameHostOption(eGameHostOption_FireSpreads, app.GetGameHostOption(packet->data,eGameHostOption_FireSpreads)); - app.SetGameHostOption(eGameHostOption_TNT, app.GetGameHostOption(packet->data,eGameHostOption_TNT)); - - server->getPlayers()->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS,app.GetGameHostOption(eGameHostOption_All) ) ) ); - - // Update the QoS data - g_NetworkManager.UpdateAndSetGameSessionData(); - } - } -} - -void PlayerConnection::handleKickPlayer(std::shared_ptr packet) -{ - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) - { - server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); - } -} - -void PlayerConnection::handleGameCommand(std::shared_ptr packet) -{ - MinecraftServer::getInstance()->getCommandDispatcher()->performCommand(player, packet->command, packet->data); -} - -void PlayerConnection::handleClientCommand(std::shared_ptr packet) -{ - if (packet->action == ClientCommandPacket::PERFORM_RESPAWN) - { - if (player->wonGame) - { - player = server->getPlayers()->respawn(player, player->m_enteredEndExitPortal?0:player->dimension, true); - } - //else if (player.getLevel().getLevelData().isHardcore()) - //{ - // if (server.isSingleplayer() && player.name.equals(server.getSingleplayerName())) - // { - // player.connection.disconnect("You have died. Game over, man, it's game over!"); - // server.selfDestruct(); - // } - // else - // { - // BanEntry ban = new BanEntry(player.name); - // ban.setReason("Death in Hardcore"); - - // server.getPlayers().getBans().add(ban); - // player.connection.disconnect("You have died. Game over, man, it's game over!"); - // } - //} - else - { - if (player->getHealth() > 0) return; - player = server->getPlayers()->respawn(player, 0, false); - } - } -} - -void PlayerConnection::handleRespawn(std::shared_ptr packet) -{ -} - -void PlayerConnection::handleContainerClose(std::shared_ptr packet) -{ - player->doCloseContainer(); -} - -#ifndef _CONTENT_PACKAGE -void PlayerConnection::handleContainerSetSlot(std::shared_ptr packet) -{ - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED ) - { - player->inventory->setCarried(packet->item); +void PlayerConnection::handleAnimate(std::shared_ptr packet) { + if (packet->action == AnimatePacket::SWING) { + player->swing(); } - else - { - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY && packet->slot >= 36 && packet->slot < 36 + 9) - { - std::shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) - { - if (lastItem == NULL || lastItem->count < packet->item->count) - { +} + +void PlayerConnection::handlePlayerCommand( + std::shared_ptr packet) { + if (packet->action == PlayerCommandPacket::START_SNEAKING) { + player->setSneaking(true); + } else if (packet->action == PlayerCommandPacket::STOP_SNEAKING) { + player->setSneaking(false); + } else if (packet->action == PlayerCommandPacket::START_SPRINTING) { + player->setSprinting(true); + } else if (packet->action == PlayerCommandPacket::STOP_SPRINTING) { + player->setSprinting(false); + } else if (packet->action == PlayerCommandPacket::STOP_SLEEPING) { + player->stopSleepInBed(false, true, true); + synched = false; + } else if (packet->action == PlayerCommandPacket::START_IDLEANIM) { + player->setIsIdle(true); + } else if (packet->action == PlayerCommandPacket::STOP_IDLEANIM) { + player->setIsIdle(false); + } +} + +void PlayerConnection::setShowOnMaps(bool bVal) { player->setShowOnMaps(bVal); } + +void PlayerConnection::handleDisconnect( + std::shared_ptr packet) { + // 4J Stu - Need to remove the player from the receiving list before their + // socket is NULLed so that we can find another player on their system + server->getPlayers()->removePlayerFromReceiving(player); + connection->close(DisconnectPacket::eDisconnect_Quitting); +} + +int PlayerConnection::countDelayedPackets() { + return connection->countDelayedPackets(); +} + +void PlayerConnection::info(const std::wstring& string) { + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // send( std::shared_ptr( new ChatPacket(L"§7" + string) ) ); +} + +void PlayerConnection::warn(const std::wstring& string) { + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // send( std::shared_ptr( new ChatPacket(L"§9" + string) ) ); +} + +std::wstring PlayerConnection::getConsoleName() { return player->name; } + +void PlayerConnection::handleInteract(std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); + std::shared_ptr target = level->getEntity(packet->target); + + // Fix for #8218 - Gameplay: Attacking zombies from a different level often + // results in no hits being registered 4J Stu - If the client says that we + // hit something, then agree with it. The canSee can fail here as it checks + // a ray from head->head, but we may actually be looking at a different part + // of the entity that can be seen even though the ray is blocked. + if (target != NULL) // && player->canSee(target) && + // player->distanceToSqr(target) < 6 * 6) + { + // boole canSee = player->canSee(target); + // double maxDist = 6 * 6; + // if (!canSee) + //{ + // maxDist = 3 * 3; + // } + + // if (player->distanceToSqr(target) < maxDist) + //{ + if (packet->action == InteractPacket::INTERACT) { + player->interact(target); + } else if (packet->action == InteractPacket::ATTACK) { + player->attack(target); + } + //} + } +} + +bool PlayerConnection::canHandleAsyncPackets() { return true; } + +void PlayerConnection::handleTexture(std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way + + if (packet->dataBytes == 0) { + // Request for texture +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received request for custom texture %ls\n", + packet->textureName.c_str()); +#endif + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); + + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(packet->textureName, pbData, dwBytes))); + } else { + m_texturesRequested.push_back(packet->textureName); + } + } else { + // Response with texture data +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received custom texture %ls\n", + packet->textureName.c_str()); +#endif + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dataBytes); + server->connection->handleTextureReceived(packet->textureName); + } +} + +void PlayerConnection::handleTextureAndGeometry( + std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way + + if (packet->dwTextureBytes == 0) { + // Request for texture and geometry +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received request for custom texture %ls\n", + packet->textureName.c_str()); +#endif + std::uint8_t* pbData = NULL; + unsigned int dwTextureBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwTextureBytes); + DLCSkinFile* pDLCSkinFile = + app.m_dlcManager.getSkinFile(packet->textureName); + + if (dwTextureBytes != 0) { + if (pDLCSkinFile) { + if (pDLCSkinFile->getAdditionalBoxesCount() != 0) { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwTextureBytes, + pDLCSkinFile))); + } else { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwTextureBytes))); + } + } else { + // we don't have the dlc skin, so retrieve the data from the app + // store + std::vector* pvSkinBoxes = + app.GetAdditionalSkinBoxes(packet->dwSkinID); + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(packet->dwSkinID); + + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, pbData, + dwTextureBytes, pvSkinBoxes, + uiAnimOverrideBitmask))); + } + } else { + m_texturesRequested.push_back(packet->textureName); + } + } else { + // Response with texture and geometry data +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received custom texture %ls and geometry\n", + packet->textureName.c_str()); +#endif + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dwTextureBytes); + + // add the geometry to the app list + if (packet->dwBoxC != 0) { +#ifndef _CONTENT_PACKAGE + wprintf(L"Adding skin boxes for skin id %X, box count %d\n", + packet->dwSkinID, packet->dwBoxC); +#endif + app.SetAdditionalSkinBoxes(packet->dwSkinID, packet->BoxDataA, + packet->dwBoxC); + } + // Add the anim override + app.SetAnimOverrideBitmask(packet->dwSkinID, + packet->uiAnimOverrideBitmask); + + player->setCustomSkin(packet->dwSkinID); + + server->connection->handleTextureAndGeometryReceived( + packet->textureName); + } +} + +void PlayerConnection::handleTextureReceived(const std::wstring& textureName) { + // This sends the server received texture out to any other players waiting + // for the data + AUTO_VAR(it, find(m_texturesRequested.begin(), m_texturesRequested.end(), + textureName)); + if (it != m_texturesRequested.end()) { + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(textureName, &pbData, &dwBytes); + + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(textureName, pbData, dwBytes))); + m_texturesRequested.erase(it); + } + } +} + +void PlayerConnection::handleTextureAndGeometryReceived( + const std::wstring& textureName) { + // This sends the server received texture out to any other players waiting + // for the data + AUTO_VAR(it, find(m_texturesRequested.begin(), m_texturesRequested.end(), + textureName)); + if (it != m_texturesRequested.end()) { + std::uint8_t* pbData = NULL; + unsigned int dwTextureBytes = 0; + app.GetMemFileDetails(textureName, &pbData, &dwTextureBytes); + DLCSkinFile* pDLCSkinFile = app.m_dlcManager.getSkinFile(textureName); + + if (dwTextureBytes != 0) { + if (pDLCSkinFile && + (pDLCSkinFile->getAdditionalBoxesCount() != 0)) { + send(std::shared_ptr( + new TextureAndGeometryPacket( + textureName, pbData, dwTextureBytes, pDLCSkinFile))); + } else { + // get the data from the app + std::uint32_t dwSkinID = app.getSkinIdFromPath(textureName); + std::vector* pvSkinBoxes = + app.GetAdditionalSkinBoxes(dwSkinID); + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(dwSkinID); + + send(std::shared_ptr( + new TextureAndGeometryPacket(textureName, pbData, + dwTextureBytes, pvSkinBoxes, + uiAnimOverrideBitmask))); + } + m_texturesRequested.erase(it); + } + } +} + +void PlayerConnection::handleTextureChange( + std::shared_ptr packet) { + switch (packet->action) { + case TextureChangePacket::e_TextureChange_Skin: + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); +#ifndef _CONTENT_PACKAGE + wprintf(L"Skin for server player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); +#endif + break; + case TextureChangePacket::e_TextureChange_Cape: + player->setCustomCape(Player::getCapeIdFromPath(packet->path)); + // player->customTextureUrl2 = packet->path; +#ifndef _CONTENT_PACKAGE + wprintf(L"Cape for server player %ls has changed to %ls\n", + player->name.c_str(), player->customTextureUrl2.c_str()); +#endif + break; + } + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (server->connection->addPendingTextureRequest(packet->path)) { +#ifndef _CONTENT_PACKAGE + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); +#endif + send(std::shared_ptr( + new TexturePacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new TextureChangePacket(player, packet->action, packet->path)), + player->dimension); +} + +void PlayerConnection::handleTextureAndGeometryChange( + std::shared_ptr packet) { + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); +#ifndef _CONTENT_PACKAGE + wprintf( + L"PlayerConnection::handleTextureAndGeometryChange - Skin for server " + L"player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); +#endif + + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (server->connection->addPendingTextureRequest(packet->path)) { +#ifndef _CONTENT_PACKAGE + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); +#endif + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + + player->setCustomSkin(packet->dwSkinID); + + // If we already have the texture, then we already have the model parts + // too + // app.SetAdditionalSkinBoxes(packet->dwSkinID,) + // DebugBreak(); + } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new TextureAndGeometryChangePacket(player, packet->path)), + player->dimension); +} + +void PlayerConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + if (packet->action == ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) { + // Need to check that this player has permission to change each + // individual setting? + + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + app.SetGameHostOption( + eGameHostOption_FireSpreads, + app.GetGameHostOption(packet->data, + eGameHostOption_FireSpreads)); + app.SetGameHostOption( + eGameHostOption_TNT, + app.GetGameHostOption(packet->data, eGameHostOption_TNT)); + + server->getPlayers()->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, + app.GetGameHostOption(eGameHostOption_All)))); + + // Update the QoS data + g_NetworkManager.UpdateAndSetGameSessionData(); + } + } +} + +void PlayerConnection::handleKickPlayer( + std::shared_ptr packet) { + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); + } +} + +void PlayerConnection::handleGameCommand( + std::shared_ptr packet) { + MinecraftServer::getInstance()->getCommandDispatcher()->performCommand( + player, packet->command, packet->data); +} + +void PlayerConnection::handleClientCommand( + std::shared_ptr packet) { + if (packet->action == ClientCommandPacket::PERFORM_RESPAWN) { + if (player->wonGame) { + player = server->getPlayers()->respawn( + player, player->m_enteredEndExitPortal ? 0 : player->dimension, + true); + } + // else if (player.getLevel().getLevelData().isHardcore()) + //{ + // if (server.isSingleplayer() && + //player.name.equals(server.getSingleplayerName())) + // { + // player.connection.disconnect("You have died. Game over, + //man, it's game over!"); server.selfDestruct(); + // } + // else + // { + // BanEntry ban = new BanEntry(player.name); + // ban.setReason("Death in Hardcore"); + + // server.getPlayers().getBans().add(ban); + // player.connection.disconnect("You have died. Game over, + //man, it's game over!"); + // } + //} + else { + if (player->getHealth() > 0) return; + player = server->getPlayers()->respawn(player, 0, false); + } + } +} + +void PlayerConnection::handleRespawn(std::shared_ptr packet) {} + +void PlayerConnection::handleContainerClose( + std::shared_ptr packet) { + player->doCloseContainer(); +} + +#ifndef _CONTENT_PACKAGE +void PlayerConnection::handleContainerSetSlot( + std::shared_ptr packet) { + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED) { + player->inventory->setCarried(packet->item); + } else { + if (packet->containerId == + AbstractContainerMenu::CONTAINER_ID_INVENTORY && + packet->slot >= 36 && packet->slot < 36 + 9) { + std::shared_ptr lastItem = + player->inventoryMenu->getSlot(packet->slot)->getItem(); + if (packet->item != NULL) { + if (lastItem == NULL || lastItem->count < packet->item->count) { packet->item->popTime = Inventory::POP_TIME_DURATION; } } - player->inventoryMenu->setItem(packet->slot, packet->item); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - else if (packet->containerId == player->containerMenu->containerId) - { + player->inventoryMenu->setItem(packet->slot, packet->item); + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setItem(packet->slot, packet->item); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; } } } #endif -void PlayerConnection::handleContainerClick(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId && player->containerMenu->isSynched(player)) - { - std::shared_ptr clicked = player->containerMenu->clicked(packet->slotNum, packet->buttonNum, packet->quickKey?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); +void PlayerConnection::handleContainerClick( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId && + player->containerMenu->isSynched(player)) { + std::shared_ptr clicked = player->containerMenu->clicked( + packet->slotNum, packet->buttonNum, + packet->quickKey ? AbstractContainerMenu::CLICK_QUICK_MOVE + : AbstractContainerMenu::CLICK_PICKUP, + player); - if (ItemInstance::matches(packet->item, clicked)) - { - // Yep, you sure did click what you claimed to click! - player->connection->send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) ) ); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - else - { - // No, you clicked the wrong thing! - expectedAcks[player->containerMenu->containerId] = packet->uid; - player->connection->send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, false) ) ); - player->containerMenu->setSynched(player, false); + if (ItemInstance::matches(packet->item, clicked)) { + // Yep, you sure did click what you claimed to click! + player->connection->send( + std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, true))); + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } else { + // No, you clicked the wrong thing! + expectedAcks[player->containerMenu->containerId] = packet->uid; + player->connection->send( + std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, false))); + player->containerMenu->setSynched(player, false); - std::vector > items; - for (unsigned int i = 0; i < player->containerMenu->slots->size(); i++) - { - items.push_back(player->containerMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->containerMenu, &items); - -// player.containerMenu.broadcastChanges(); - } - } + std::vector > items; + for (unsigned int i = 0; i < player->containerMenu->slots->size(); + i++) { + items.push_back(player->containerMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->containerMenu, &items); + // player.containerMenu.broadcastChanges(); + } + } } -void PlayerConnection::handleContainerButtonClick(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId && player->containerMenu->isSynched(player)) - { - player->containerMenu->clickMenuButton(player, packet->buttonId); - player->containerMenu->broadcastChanges(); - } +void PlayerConnection::handleContainerButtonClick( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId && + player->containerMenu->isSynched(player)) { + player->containerMenu->clickMenuButton(player, packet->buttonId); + player->containerMenu->broadcastChanges(); + } } -void PlayerConnection::handleSetCreativeModeSlot(std::shared_ptr packet) -{ - if (player->gameMode->isCreative()) - { - bool drop = packet->slotNum < 0; - std::shared_ptr item = packet->item; +void PlayerConnection::handleSetCreativeModeSlot( + std::shared_ptr packet) { + if (player->gameMode->isCreative()) { + bool drop = packet->slotNum < 0; + std::shared_ptr item = packet->item; - if(item != NULL && item->id == Item::map_Id) - { - int mapScale = 3; + if (item != NULL && item->id == Item::map_Id) { + int mapScale = 3; #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); + int centreXC = (int)(Math::round(player->x / scale) * scale); + int centreZC = (int)(Math::round(player->z / scale) * scale); #else - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - int centreXC = 0; - int centreZC = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the + // world, since we can fit the whole world in our map + int centreXC = 0; + int centreZC = 0; #endif - item->setAuxValue( player->level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale) ); + item->setAuxValue(player->level->getAuxValueForMap( + player->getXuid(), player->dimension, centreXC, centreZC, + mapScale)); - std::shared_ptr data = MapItem::getSavedData(item->getAuxValue(), player->level); - // 4J Stu - We only have one map per player per dimension, so don't reset the one that they have - // when a new one is created - wchar_t buf[64]; - swprintf(buf,64,L"map_%d", item->getAuxValue()); - std::wstring id = std::wstring(buf); - if( data == NULL ) - { - data = std::shared_ptr( new MapItemSavedData(id) ); - } - player->level->setSavedData(id, (std::shared_ptr ) data); + std::shared_ptr data = + MapItem::getSavedData(item->getAuxValue(), player->level); + // 4J Stu - We only have one map per player per dimension, so don't + // reset the one that they have when a new one is created + wchar_t buf[64]; + swprintf(buf, 64, L"map_%d", item->getAuxValue()); + std::wstring id = std::wstring(buf); + if (data == NULL) { + data = + std::shared_ptr(new MapItemSavedData(id)); + } + player->level->setSavedData(id, (std::shared_ptr)data); - data->scale = mapScale; - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - data->x = centreXC; - data->z = centreZC; - data->dimension = (std::uint8_t) player->level->dimension->id; - data->setDirty(); - } + data->scale = mapScale; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the + // world, since we can fit the whole world in our map + data->x = centreXC; + data->z = centreZC; + data->dimension = (std::uint8_t)player->level->dimension->id; + data->setDirty(); + } - bool validSlot = (packet->slotNum >= InventoryMenu::CRAFT_SLOT_START && packet->slotNum < (InventoryMenu::USE_ROW_SLOT_START + Inventory::getSelectionSize())); - bool validItem = item == NULL || (item->id < Item::items.length && item->id >= 0 && Item::items[item->id] != NULL); - bool validData = item == NULL || (item->getAuxValue() >= 0 && item->count > 0 && item->count <= 64); + bool validSlot = (packet->slotNum >= InventoryMenu::CRAFT_SLOT_START && + packet->slotNum < (InventoryMenu::USE_ROW_SLOT_START + + Inventory::getSelectionSize())); + bool validItem = + item == NULL || (item->id < Item::items.length && item->id >= 0 && + Item::items[item->id] != NULL); + bool validData = item == NULL || (item->getAuxValue() >= 0 && + item->count > 0 && item->count <= 64); - if (validSlot && validItem && validData) - { - if (item == NULL) - { - player->inventoryMenu->setItem(packet->slotNum, nullptr); - } - else - { - player->inventoryMenu->setItem(packet->slotNum, item ); - } - player->inventoryMenu->setSynched(player, true); - // player.slotChanged(player.inventoryMenu, packet.slotNum, player.inventoryMenu.getSlot(packet.slotNum).getItem()); - } - else if (drop && validItem && validData) - { - if (dropSpamTickCount < SharedConstants::TICKS_PER_SECOND * 10) - { - dropSpamTickCount += SharedConstants::TICKS_PER_SECOND; - // drop item - std::shared_ptr dropped = player->drop(item); - if (dropped != NULL) - { - dropped->setShortLifeTime(); - } - } - } + if (validSlot && validItem && validData) { + if (item == NULL) { + player->inventoryMenu->setItem(packet->slotNum, nullptr); + } else { + player->inventoryMenu->setItem(packet->slotNum, item); + } + player->inventoryMenu->setSynched(player, true); + // player.slotChanged(player.inventoryMenu, + // packet.slotNum, + // player.inventoryMenu.getSlot(packet.slotNum).getItem()); + } else if (drop && validItem && validData) { + if (dropSpamTickCount < SharedConstants::TICKS_PER_SECOND * 10) { + dropSpamTickCount += SharedConstants::TICKS_PER_SECOND; + // drop item + std::shared_ptr dropped = player->drop(item); + if (dropped != NULL) { + dropped->setShortLifeTime(); + } + } + } - if( item != NULL && item->id == Item::map_Id ) - { - // 4J Stu - Maps need to have their aux value update, so the client should always be assumed to be wrong - // This is how the Java works, as the client also incorrectly predicts the auxvalue of the mapItem - std::vector > items; - for (unsigned int i = 0; i < player->inventoryMenu->slots->size(); i++) - { - items.push_back(player->inventoryMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->inventoryMenu, &items); - } - } + if (item != NULL && item->id == Item::map_Id) { + // 4J Stu - Maps need to have their aux value update, so the client + // should always be assumed to be wrong This is how the Java works, + // as the client also incorrectly predicts the auxvalue of the + // mapItem + std::vector > items; + for (unsigned int i = 0; i < player->inventoryMenu->slots->size(); + i++) { + items.push_back(player->inventoryMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->inventoryMenu, &items); + } + } } -void PlayerConnection::handleContainerAck(std::shared_ptr packet) -{ - AUTO_VAR(it, expectedAcks.find(player->containerMenu->containerId)); +void PlayerConnection::handleContainerAck( + std::shared_ptr packet) { + AUTO_VAR(it, expectedAcks.find(player->containerMenu->containerId)); - if (it != expectedAcks.end() && packet->uid == it->second && player->containerMenu->containerId == packet->containerId && !player->containerMenu->isSynched(player)) - { - player->containerMenu->setSynched(player, true); - } + if (it != expectedAcks.end() && packet->uid == it->second && + player->containerMenu->containerId == packet->containerId && + !player->containerMenu->isSynched(player)) { + player->containerMenu->setSynched(player, true); + } } -void PlayerConnection::handleSignUpdate(std::shared_ptr packet) -{ - app.DebugPrintf("PlayerConnection::handleSignUpdate\n"); +void PlayerConnection::handleSignUpdate( + std::shared_ptr packet) { + app.DebugPrintf("PlayerConnection::handleSignUpdate\n"); - ServerLevel *level = server->getLevel(player->dimension); - if (level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = level->getTileEntity(packet->x, packet->y, packet->z); + ServerLevel* level = server->getLevel(player->dimension); + if (level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + level->getTileEntity(packet->x, packet->y, packet->z); - if (std::dynamic_pointer_cast(te) != NULL) - { - std::shared_ptr ste = std::dynamic_pointer_cast(te); - if (!ste->isEditable()) - { - server->warn(L"Player " + player->name + L" just tried to change non-editable sign"); - return; - } - } - - // 4J-JEV: Changed to allow characters to display as a []. - if (std::dynamic_pointer_cast(te) != NULL) - { - int x = packet->x; - int y = packet->y; - int z = packet->z; - std::shared_ptr ste = std::dynamic_pointer_cast(te); - for (int i = 0; i < 4; i++) - { - std::wstring lineText = packet->lines[i].substr(0,15); - ste->SetMessage( i, lineText ); - } - ste->SetVerified(false); - ste->setChanged(); - level->sendTileUpdated(x, y, z); - } - } + if (std::dynamic_pointer_cast(te) != NULL) { + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + if (!ste->isEditable()) { + server->warn(L"Player " + player->name + + L" just tried to change non-editable sign"); + return; + } + } + // 4J-JEV: Changed to allow characters to display as a []. + if (std::dynamic_pointer_cast(te) != NULL) { + int x = packet->x; + int y = packet->y; + int z = packet->z; + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + for (int i = 0; i < 4; i++) { + std::wstring lineText = packet->lines[i].substr(0, 15); + ste->SetMessage(i, lineText); + } + ste->SetVerified(false); + ste->setChanged(); + level->sendTileUpdated(x, y, z); + } + } } -void PlayerConnection::handleKeepAlive(std::shared_ptr packet) -{ - if (packet->id == lastKeepAliveId) - { - int time = (int) (System::nanoTime() / 1000000 - lastKeepAliveTime); - player->latency = (player->latency * 3 + time) / 4; - } +void PlayerConnection::handleKeepAlive( + std::shared_ptr packet) { + if (packet->id == lastKeepAliveId) { + int time = (int)(System::nanoTime() / 1000000 - lastKeepAliveTime); + player->latency = (player->latency * 3 + time) / 4; + } } -void PlayerConnection::handlePlayerInfo(std::shared_ptr packet) -{ - // Need to check that this player has permission to change each individual setting? +void PlayerConnection::handlePlayerInfo( + std::shared_ptr packet) { + // Need to check that this player has permission to change each individual + // setting? - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator() ) - { - std::shared_ptr serverPlayer; - // Find the player being edited - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) - { - std::shared_ptr checkingPlayer = *it; - if(checkingPlayer->connection->getNetworkPlayer() != NULL && checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == packet->m_networkSmallId) - { - serverPlayer = checkingPlayer; - break; - } - } + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + std::shared_ptr serverPlayer; + // Find the player being edited + for (AUTO_VAR(it, server->getPlayers()->players.begin()); + it != server->getPlayers()->players.end(); ++it) { + std::shared_ptr checkingPlayer = *it; + if (checkingPlayer->connection->getNetworkPlayer() != NULL && + checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == + packet->m_networkSmallId) { + serverPlayer = checkingPlayer; + break; + } + } - if(serverPlayer != NULL) - { - unsigned int origPrivs = serverPlayer->getAllPlayerGamePrivileges(); + if (serverPlayer != NULL) { + unsigned int origPrivs = serverPlayer->getAllPlayerGamePrivileges(); - bool trustPlayers = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; - bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; - if(serverPlayer == player) - { - GameType *gameType = Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ? GameType::CREATIVE : GameType::SURVIVAL; - gameType = LevelSettings::validateGameType(gameType->getId()); - if (serverPlayer->gameMode->getGameModeForPlayer() != gameType) - { + bool trustPlayers = + app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; + bool cheats = + app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; + if (serverPlayer == player) { + GameType* gameType = + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CreativeMode) + ? GameType::CREATIVE + : GameType::SURVIVAL; + gameType = LevelSettings::validateGameType(gameType->getId()); + if (serverPlayer->gameMode->getGameModeForPlayer() != + gameType) { #ifndef _CONTENT_PACKAGE - wprintf(L"Setting %ls to game mode %d\n", serverPlayer->name.c_str(), gameType); + wprintf(L"Setting %ls to game mode %d\n", + serverPlayer->name.c_str(), gameType); #endif - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ); - serverPlayer->gameMode->setGameModeForPlayer(gameType); - serverPlayer->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, gameType->getId()) )); - } - else - { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CreativeMode, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CreativeMode)); + serverPlayer->gameMode->setGameModeForPlayer(gameType); + serverPlayer->connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::CHANGE_GAME_MODE, + gameType->getId()))); + } else { #ifndef _CONTENT_PACKAGE - wprintf(L"%ls already has game mode %d\n", serverPlayer->name.c_str(), gameType); + wprintf(L"%ls already has game mode %d\n", + serverPlayer->name.c_str(), gameType); #endif - } - if(cheats) - { - // Editing self - bool canBeInvisible = Player::getPlayerGamePrivilege(origPrivs, Player::ePlayerGamePrivilege_CanToggleInvisible) != 0; - if(canBeInvisible)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invisible,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Invisible) ); - if(canBeInvisible)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invulnerable,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Invulnerable) ); + } + if (cheats) { + // Editing self + bool canBeInvisible = + Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CanToggleInvisible) != + 0; + if (canBeInvisible) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Invisible, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Invisible)); + if (canBeInvisible) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Invulnerable, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Invulnerable)); - bool inCreativeMode = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CreativeMode) != 0; - if(!inCreativeMode) - { - bool canFly = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CanToggleFly); - bool canChangeHunger = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CanToggleClassicHunger); + bool inCreativeMode = + Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CreativeMode) != 0; + if (!inCreativeMode) { + bool canFly = Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CanToggleFly); + bool canChangeHunger = Player::getPlayerGamePrivilege( + origPrivs, + Player:: + ePlayerGamePrivilege_CanToggleClassicHunger); - if(canFly)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanFly,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanFly) ); - if(canChangeHunger)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_ClassicHunger,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_ClassicHunger) ); - } - } - } - else - { - // Editing someone else - if(!trustPlayers && !serverPlayer->connection->getNetworkPlayer()->IsHost()) - { - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotMine) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotBuild) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackPlayers,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotAttackPlayers) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackAnimals,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotAttackAnimals) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseContainers,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanUseContainers) ); - } + if (canFly) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanFly, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanFly)); + if (canChangeHunger) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_ClassicHunger, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_ClassicHunger)); + } + } + } else { + // Editing someone else + if (!trustPlayers && + !serverPlayer->connection->getNetworkPlayer()->IsHost()) { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotMine, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotMine)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotBuild, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotBuild)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackPlayers, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotAttackPlayers)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackAnimals, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotAttackAnimals)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanUseDoorsAndSwitches)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseContainers, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanUseContainers)); + } - if(networkPlayer->IsHost()) - { - if(cheats) - { - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleInvisible,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleInvisible) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleFly,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleFly) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleClassicHunger,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleClassicHunger) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanTeleport,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanTeleport) ); - } - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Op,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Op) ); - } - } + if (networkPlayer->IsHost()) { + if (cheats) { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleInvisible, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanToggleInvisible)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleFly, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanToggleFly)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleClassicHunger, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanToggleClassicHunger)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanTeleport, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanTeleport)); + } + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Op, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Op)); + } + } - server->getPlayers()->broadcastAll( std::shared_ptr( new PlayerInfoPacket( serverPlayer ) ) ); - } - } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new PlayerInfoPacket(serverPlayer))); + } + } } -bool PlayerConnection::isServerPacketListener() -{ - return true; +bool PlayerConnection::isServerPacketListener() { return true; } + +void PlayerConnection::handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket) { + player->abilities.flying = + playerAbilitiesPacket->isFlying() && player->abilities.mayfly; } -void PlayerConnection::handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket) -{ - player->abilities.flying = playerAbilitiesPacket->isFlying() && player->abilities.mayfly; -} - -//void handleChatAutoComplete(ChatAutoCompletePacket packet) { +// void handleChatAutoComplete(ChatAutoCompletePacket packet) { // StringBuilder result = new StringBuilder(); -// for (String candidate : server.getAutoCompletions(player, packet.getMessage())) { -// if (result.length() > 0) result.append("\0"); +// for (String candidate : server.getAutoCompletions(player, +//packet.getMessage())) { if (result.length() > 0) result.append("\0"); // result.append(candidate); // } @@ -1427,13 +1529,13 @@ void PlayerConnection::handlePlayerAbilities(std::shared_ptr packet) +// void handleClientInformation(std::shared_ptr packet) //{ // player->updateOptions(packet); -//} +// } -void PlayerConnection::handleCustomPayload(std::shared_ptr customPayloadPacket) -{ +void PlayerConnection::handleCustomPayload( + std::shared_ptr customPayloadPacket) { #if 0 if (CustomPayloadPacket.CUSTOM_BOOK_PACKET.equals(customPayloadPacket.identifier)) { @@ -1473,245 +1575,267 @@ void PlayerConnection::handleCustomPayload(std::shared_ptr } else #endif - if (CustomPayloadPacket::TRADER_SELECTION_PACKET.compare(customPayloadPacket->identifier) == 0) - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream input(&bais); - int selection = input.readInt(); + if (CustomPayloadPacket::TRADER_SELECTION_PACKET.compare( + customPayloadPacket->identifier) == 0) { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream input(&bais); + int selection = input.readInt(); - AbstractContainerMenu *menu = player->containerMenu; - if (dynamic_cast(menu)) - { - ((MerchantMenu *) menu)->setSelectionHint(selection); - } - } - else if (CustomPayloadPacket::SET_ITEM_NAME_PACKET.compare(customPayloadPacket->identifier) == 0) - { - RepairMenu *menu = dynamic_cast( player->containerMenu); - if (menu) - { - if (customPayloadPacket->data.data == NULL || customPayloadPacket->data.length < 1) - { - menu->setItemName(L""); - } - else - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream dis(&bais); - std::wstring name = dis.readUTF(); - if (name.length() <= 30) - { - menu->setItemName(name); - } - } - } - } + AbstractContainerMenu* menu = player->containerMenu; + if (dynamic_cast(menu)) { + ((MerchantMenu*)menu)->setSelectionHint(selection); + } + } else if (CustomPayloadPacket::SET_ITEM_NAME_PACKET.compare( + customPayloadPacket->identifier) == 0) { + RepairMenu* menu = dynamic_cast(player->containerMenu); + if (menu) { + if (customPayloadPacket->data.data == NULL || + customPayloadPacket->data.length < 1) { + menu->setItemName(L""); + } else { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream dis(&bais); + std::wstring name = dis.readUTF(); + if (name.length() <= 30) { + menu->setItemName(name); + } + } + } + } } // 4J Added -void PlayerConnection::handleDebugOptions(std::shared_ptr packet) -{ - //Player player = std::dynamic_pointer_cast( player->shared_from_this() ); - player->SetDebugOptions(packet->m_uiVal); +void PlayerConnection::handleDebugOptions( + std::shared_ptr packet) { + // Player player = std::dynamic_pointer_cast( + // player->shared_from_this() ); + player->SetDebugOptions(packet->m_uiVal); } -void PlayerConnection::handleCraftItem(std::shared_ptr packet) -{ - int iRecipe = packet->recipe; +void PlayerConnection::handleCraftItem( + std::shared_ptr packet) { + int iRecipe = packet->recipe; - if(iRecipe == -1) - return; + if (iRecipe == -1) return; - Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); - std::shared_ptr pTempItemInst=pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); + Recipy::INGREDIENTS_REQUIRED* pRecipeIngredientsRequired = + Recipes::getInstance()->getRecipeIngredientsArray(); + std::shared_ptr pTempItemInst = + pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); - if(app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<onCraftedBy(player->level, std::dynamic_pointer_cast( player->shared_from_this() ), pTempItemInst->count ); - if(player->inventory->add(pTempItemInst)==false ) - { - // no room in inventory, so throw it down - player->drop(pTempItemInst); - } - } - else - { + if (app.DebugSettingsOn() && + (player->GetDebugOptions() & (1L << eDebugSetting_CraftAnything))) { + pTempItemInst->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + pTempItemInst->count); + if (player->inventory->add(pTempItemInst) == false) { + // no room in inventory, so throw it down + player->drop(pTempItemInst); + } + } else { + // TODO 4J Stu - Assume at the moment that the client can work this out + // for us... + // if(pRecipeIngredientsRequired[iRecipe].bCanMake) + //{ + pTempItemInst->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + pTempItemInst->count); - - // TODO 4J Stu - Assume at the moment that the client can work this out for us... - //if(pRecipeIngredientsRequired[iRecipe].bCanMake) - //{ - pTempItemInst->onCraftedBy(player->level, std::dynamic_pointer_cast( player->shared_from_this() ), pTempItemInst->count ); + // and remove those resources from your inventory + for (int i = 0; i < pRecipeIngredientsRequired[iRecipe].iIngC; i++) { + for (int j = 0; j < pRecipeIngredientsRequired[iRecipe].iIngValA[i]; + j++) { + std::shared_ptr ingItemInst = nullptr; + // do we need to remove a specific aux value? + if (pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i] != + Recipes::ANY_AUX_VALUE) { + ingItemInst = player->inventory->getResourceItem( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i], + pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); + player->inventory->removeResource( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i], + pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); + } else { + ingItemInst = player->inventory->getResourceItem( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); + player->inventory->removeResource( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); + } - // and remove those resources from your inventory - for(int i=0;i ingItemInst = nullptr; - // do we need to remove a specific aux value? - if(pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]!=Recipes::ANY_AUX_VALUE) - { - ingItemInst = player->inventory->getResourceItem( pRecipeIngredientsRequired[iRecipe].iIngIDA[i],pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i] ); - player->inventory->removeResource(pRecipeIngredientsRequired[iRecipe].iIngIDA[i],pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); - } - else - { - ingItemInst = player->inventory->getResourceItem( pRecipeIngredientsRequired[iRecipe].iIngIDA[i] ); - player->inventory->removeResource(pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); - } + // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when + // crafting Cake + if (ingItemInst != NULL) { + if (ingItemInst->getItem()->hasCraftingRemainingItem()) { + // replace item with remaining result + player->inventory->add( + std::shared_ptr(new ItemInstance( + ingItemInst->getItem() + ->getCraftingRemainingItem()))); + } + } + } + } - // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when crafting Cake - if (ingItemInst != NULL) - { - if (ingItemInst->getItem()->hasCraftingRemainingItem()) - { - // replace item with remaining result - player->inventory->add( std::shared_ptr( new ItemInstance(ingItemInst->getItem()->getCraftingRemainingItem()) ) ); - } + // 4J Stu - Fix for #13119 - We should add the item after we remove the + // ingredients + if (player->inventory->add(pTempItemInst) == false) { + // no room in inventory, so throw it down + player->drop(pTempItemInst); + } - } - } - } - - // 4J Stu - Fix for #13119 - We should add the item after we remove the ingredients - if(player->inventory->add(pTempItemInst)==false ) - { - // no room in inventory, so throw it down - player->drop(pTempItemInst); - } + if (pTempItemInst->id == Item::map_Id) { + // 4J Stu - Maps need to have their aux value update, so the client + // should always be assumed to be wrong This is how the Java works, + // as the client also incorrectly predicts the auxvalue of the + // mapItem + std::vector > items; + for (unsigned int i = 0; i < player->containerMenu->slots->size(); + i++) { + items.push_back(player->containerMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->containerMenu, &items); + } else { + // Do same hack as PlayerConnection::handleContainerClick does - do + // our broadcast of changes just now, but with a hack so it just + // thinks it has sent things but hasn't really. This will stop the + // client getting a message back confirming the current inventory + // items, which might then arrive after another local change has + // been made on the client and be stale. + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } + } - if( pTempItemInst->id == Item::map_Id ) - { - // 4J Stu - Maps need to have their aux value update, so the client should always be assumed to be wrong - // This is how the Java works, as the client also incorrectly predicts the auxvalue of the mapItem - std::vector > items; - for (unsigned int i = 0; i < player->containerMenu->slots->size(); i++) - { - items.push_back(player->containerMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->containerMenu, &items); - } - else - { - // Do same hack as PlayerConnection::handleContainerClick does - do our broadcast of changes just now, but with a hack so it just thinks it has sent - // things but hasn't really. This will stop the client getting a message back confirming the current inventory items, which might then arrive - // after another local change has been made on the client and be stale. - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - } - - // handle achievements - switch(pTempItemInst->id ) - { - case Tile::workBench_Id: player->awardStat(GenericStats::buildWorkbench(), GenericStats::param_buildWorkbench()); break; - case Item::pickAxe_wood_Id: player->awardStat(GenericStats::buildPickaxe(), GenericStats::param_buildPickaxe()); break; - case Tile::furnace_Id: player->awardStat(GenericStats::buildFurnace(), GenericStats::param_buildFurnace()); break; - case Item::hoe_wood_Id: player->awardStat(GenericStats::buildHoe(), GenericStats::param_buildHoe()); break; - case Item::bread_Id: player->awardStat(GenericStats::makeBread(), GenericStats::param_makeBread()); break; - case Item::cake_Id: player->awardStat(GenericStats::bakeCake(), GenericStats::param_bakeCake()); break; - case Item::pickAxe_stone_Id: player->awardStat(GenericStats::buildBetterPickaxe(), GenericStats::param_buildBetterPickaxe()); break; - case Item::sword_wood_Id: player->awardStat(GenericStats::buildSword(), GenericStats::param_buildSword()); break; - case Tile::dispenser_Id: player->awardStat(GenericStats::dispenseWithThis(), GenericStats::param_dispenseWithThis()); break; - case Tile::enchantTable_Id: player->awardStat(GenericStats::enchantments(), GenericStats::param_enchantments()); break; - case Tile::bookshelf_Id: player->awardStat(GenericStats::bookcase(), GenericStats::param_bookcase()); break; - } - //} - // ELSE The server thinks the client was wrong... + // handle achievements + switch (pTempItemInst->id) { + case Tile::workBench_Id: + player->awardStat(GenericStats::buildWorkbench(), + GenericStats::param_buildWorkbench()); + break; + case Item::pickAxe_wood_Id: + player->awardStat(GenericStats::buildPickaxe(), + GenericStats::param_buildPickaxe()); + break; + case Tile::furnace_Id: + player->awardStat(GenericStats::buildFurnace(), + GenericStats::param_buildFurnace()); + break; + case Item::hoe_wood_Id: + player->awardStat(GenericStats::buildHoe(), + GenericStats::param_buildHoe()); + break; + case Item::bread_Id: + player->awardStat(GenericStats::makeBread(), + GenericStats::param_makeBread()); + break; + case Item::cake_Id: + player->awardStat(GenericStats::bakeCake(), + GenericStats::param_bakeCake()); + break; + case Item::pickAxe_stone_Id: + player->awardStat(GenericStats::buildBetterPickaxe(), + GenericStats::param_buildBetterPickaxe()); + break; + case Item::sword_wood_Id: + player->awardStat(GenericStats::buildSword(), + GenericStats::param_buildSword()); + break; + case Tile::dispenser_Id: + player->awardStat(GenericStats::dispenseWithThis(), + GenericStats::param_dispenseWithThis()); + break; + case Tile::enchantTable_Id: + player->awardStat(GenericStats::enchantments(), + GenericStats::param_enchantments()); + break; + case Tile::bookshelf_Id: + player->awardStat(GenericStats::bookcase(), + GenericStats::param_bookcase()); + break; + } + //} + // ELSE The server thinks the client was wrong... } +void PlayerConnection::handleTradeItem( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId) { + MerchantMenu* menu = (MerchantMenu*)player->containerMenu; -void PlayerConnection::handleTradeItem(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId) - { - MerchantMenu *menu = (MerchantMenu *)player->containerMenu; + MerchantRecipeList* offers = menu->getMerchant()->getOffers(player); - MerchantRecipeList *offers = menu->getMerchant()->getOffers(player); + if (offers) { + int selectedShopItem = packet->offer; + if (selectedShopItem < offers->size()) { + MerchantRecipe* activeRecipe = offers->at(selectedShopItem); + if (!activeRecipe->isDeprecated()) { + // Do we have the ingredients? + std::shared_ptr buyAItem = + activeRecipe->getBuyAItem(); + std::shared_ptr buyBItem = + activeRecipe->getBuyBItem(); - if(offers) - { - int selectedShopItem = packet->offer; - if( selectedShopItem < offers->size() ) - { - MerchantRecipe *activeRecipe = offers->at(selectedShopItem); - if(!activeRecipe->isDeprecated()) - { - // Do we have the ingredients? - std::shared_ptr buyAItem = activeRecipe->getBuyAItem(); - std::shared_ptr buyBItem = activeRecipe->getBuyBItem(); + int buyAMatches = player->inventory->countMatches(buyAItem); + int buyBMatches = player->inventory->countMatches(buyBItem); + if ((buyAItem != NULL && buyAMatches >= buyAItem->count) && + (buyBItem == NULL || buyBMatches >= buyBItem->count)) { + menu->getMerchant()->notifyTrade(activeRecipe); - int buyAMatches = player->inventory->countMatches(buyAItem); - int buyBMatches = player->inventory->countMatches(buyBItem); - if( (buyAItem != NULL && buyAMatches >= buyAItem->count) && (buyBItem == NULL || buyBMatches >= buyBItem->count) ) - { - menu->getMerchant()->notifyTrade(activeRecipe); + // Remove the items we are purchasing with + player->inventory->removeResources(buyAItem); + player->inventory->removeResources(buyBItem); - // Remove the items we are purchasing with - player->inventory->removeResources(buyAItem); - player->inventory->removeResources(buyBItem); + // Add the item we have purchased + std::shared_ptr result = + activeRecipe->getSellItem()->copy(); - // Add the item we have purchased - std::shared_ptr result = activeRecipe->getSellItem()->copy(); - - // 4J JEV - Award itemsBought stat. - player->awardStat( - GenericStats::itemsBought(result->getItem()->id), - GenericStats::param_itemsBought( - result->getItem()->id, - result->getAuxValue(), - result->GetCount() - ) - ); - - if (!player->inventory->add(result)) - { - player->drop(result); - } - } - } - } - } - } + // 4J JEV - Award itemsBought stat. + player->awardStat( + GenericStats::itemsBought(result->getItem()->id), + GenericStats::param_itemsBought( + result->getItem()->id, result->getAuxValue(), + result->GetCount())); + + if (!player->inventory->add(result)) { + player->drop(result); + } + } + } + } + } + } } -INetworkPlayer *PlayerConnection::getNetworkPlayer() -{ - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; +INetworkPlayer* PlayerConnection::getNetworkPlayer() { + if (connection != NULL && connection->getSocket() != NULL) + return connection->getSocket()->getPlayer(); + else + return NULL; } -bool PlayerConnection::isLocal() -{ - if( connection->getSocket() == NULL ) - { - return false; - } - else - { - bool isLocal = connection->getSocket()->isLocal(); - return connection->getSocket()->isLocal(); - } +bool PlayerConnection::isLocal() { + if (connection->getSocket() == NULL) { + return false; + } else { + bool isLocal = connection->getSocket()->isLocal(); + return connection->getSocket()->isLocal(); + } } -bool PlayerConnection::isGuest() -{ - if( connection->getSocket() == NULL ) - { - return false; - } - else - { - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - bool isGuest = false; - if(networkPlayer != NULL) - { - isGuest = networkPlayer->IsGuest() == TRUE; - } - return isGuest; - } +bool PlayerConnection::isGuest() { + if (connection->getSocket() == NULL) { + return false; + } else { + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + bool isGuest = false; + if (networkPlayer != NULL) { + isGuest = networkPlayer->IsGuest() == TRUE; + } + return isGuest; + } } diff --git a/Minecraft.Client/Network/PlayerConnection.h b/Minecraft.Client/Network/PlayerConnection.h index ae8ec4881..16c0e90dc 100644 --- a/Minecraft.Client/Network/PlayerConnection.h +++ b/Minecraft.Client/Network/PlayerConnection.h @@ -8,132 +8,152 @@ class Connection; class ServerPlayer; class INetworkPlayer; - - -class PlayerConnection : public PacketListener, public ConsoleInputSource -{ -// public static Logger logger = Logger.getLogger("Minecraft"); +class PlayerConnection : public PacketListener, public ConsoleInputSource { + // public static Logger logger = Logger.getLogger("Minecraft"); public: - Connection *connection; + Connection* connection; bool done; - CRITICAL_SECTION done_cs; + CRITICAL_SECTION done_cs; - // 4J Stu - Added this so that we can manage UGC privileges - PlayerUID m_offlineXUID, m_onlineXUID; - bool m_friendsOnlyUGC; + // 4J Stu - Added this so that we can manage UGC privileges + PlayerUID m_offlineXUID, m_onlineXUID; + bool m_friendsOnlyUGC; private: - MinecraftServer *server; + MinecraftServer* server; std::shared_ptr player; int tickCount; int aboveGroundTickCount; bool didTick; - int lastKeepAliveId; - __int64 lastKeepAliveTime; - static Random random; - __int64 lastKeepAliveTick; - int chatSpamTickCount; - int dropSpamTickCount; + int lastKeepAliveId; + __int64 lastKeepAliveTime; + static Random random; + __int64 lastKeepAliveTick; + int chatSpamTickCount; + int dropSpamTickCount; - bool m_bHasClientTickedOnce; + bool m_bHasClientTickedOnce; public: - PlayerConnection(MinecraftServer *server, Connection *connection, std::shared_ptr player); - ~PlayerConnection(); + PlayerConnection(MinecraftServer* server, Connection* connection, + std::shared_ptr player); + ~PlayerConnection(); void tick(); void disconnect(DisconnectPacket::eDisconnectReason reason); private: - double xLastOk, yLastOk, zLastOk; + double xLastOk, yLastOk, zLastOk; bool synched; public: - virtual void handlePlayerInput(std::shared_ptr packet); + virtual void handlePlayerInput(std::shared_ptr packet); virtual void handleMovePlayer(std::shared_ptr packet); - void teleport(double x, double y, double z, float yRot, float xRot, bool sendPacket = true); // 4J Added sendPacket param + void teleport(double x, double y, double z, float yRot, float xRot, + bool sendPacket = true); // 4J Added sendPacket param virtual void handlePlayerAction(std::shared_ptr packet); virtual void handleUseItem(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); virtual void onUnhandledPacket(std::shared_ptr packet); void send(std::shared_ptr packet); - void queueSend(std::shared_ptr packet); // 4J Added - virtual void handleSetCarriedItem(std::shared_ptr packet); + void queueSend(std::shared_ptr packet); // 4J Added + virtual void handleSetCarriedItem( + std::shared_ptr packet); virtual void handleChat(std::shared_ptr packet); + private: - void handleCommand(const std::wstring& message); + void handleCommand(const std::wstring& message); + public: - virtual void handleAnimate(std::shared_ptr packet); - virtual void handlePlayerCommand(std::shared_ptr packet); + virtual void handleAnimate(std::shared_ptr packet); + virtual void handlePlayerCommand( + std::shared_ptr packet); virtual void handleDisconnect(std::shared_ptr packet); int countDelayedPackets(); virtual void info(const std::wstring& string); virtual void warn(const std::wstring& string); virtual std::wstring getConsoleName(); virtual void handleInteract(std::shared_ptr packet); - bool canHandleAsyncPackets(); - virtual void handleClientCommand(std::shared_ptr packet); + bool canHandleAsyncPackets(); + virtual void handleClientCommand( + std::shared_ptr packet); virtual void handleRespawn(std::shared_ptr packet); - virtual void handleContainerClose(std::shared_ptr packet); + virtual void handleContainerClose( + std::shared_ptr packet); private: - std::unordered_map expectedAcks; + std::unordered_map expectedAcks; public: - // 4J Stu - Handlers only valid in debug mode -#ifndef _CONTENT_PACKAGE - virtual void handleContainerSetSlot(std::shared_ptr packet); + // 4J Stu - Handlers only valid in debug mode +#ifndef _CONTENT_PACKAGE + virtual void handleContainerSetSlot( + std::shared_ptr packet); #endif - virtual void handleContainerClick(std::shared_ptr packet); - virtual void handleContainerButtonClick(std::shared_ptr packet); - virtual void handleSetCreativeModeSlot(std::shared_ptr packet); + virtual void handleContainerClick( + std::shared_ptr packet); + virtual void handleContainerButtonClick( + std::shared_ptr packet); + virtual void handleSetCreativeModeSlot( + std::shared_ptr packet); virtual void handleContainerAck(std::shared_ptr packet); virtual void handleSignUpdate(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); - virtual void handlePlayerInfo(std::shared_ptr packet); // 4J Added + virtual void handleKeepAlive(std::shared_ptr packet); + virtual void handlePlayerInfo( + std::shared_ptr packet); // 4J Added virtual bool isServerPacketListener(); - virtual void handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket); - virtual void handleCustomPayload(std::shared_ptr customPayloadPacket); + virtual void handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket); + virtual void handleCustomPayload( + std::shared_ptr customPayloadPacket); - // 4J Added - virtual void handleCraftItem(std::shared_ptr packet); - virtual void handleTradeItem(std::shared_ptr packet); - virtual void handleDebugOptions(std::shared_ptr packet); - virtual void handleTexture(std::shared_ptr packet); - virtual void handleTextureAndGeometry(std::shared_ptr packet); - virtual void handleTextureChange(std::shared_ptr packet); - virtual void handleTextureAndGeometryChange(std::shared_ptr packet); - virtual void handleServerSettingsChanged(std::shared_ptr packet); - virtual void handleKickPlayer(std::shared_ptr packet); - virtual void handleGameCommand(std::shared_ptr packet); + // 4J Added + virtual void handleCraftItem(std::shared_ptr packet); + virtual void handleTradeItem(std::shared_ptr packet); + virtual void handleDebugOptions(std::shared_ptr packet); + virtual void handleTexture(std::shared_ptr packet); + virtual void handleTextureAndGeometry( + std::shared_ptr packet); + virtual void handleTextureChange( + std::shared_ptr packet); + virtual void handleTextureAndGeometryChange( + std::shared_ptr packet); + virtual void handleServerSettingsChanged( + std::shared_ptr packet); + virtual void handleKickPlayer(std::shared_ptr packet); + virtual void handleGameCommand(std::shared_ptr packet); - INetworkPlayer *getNetworkPlayer(); - bool isLocal(); - bool isGuest(); + INetworkPlayer* getNetworkPlayer(); + bool isLocal(); + bool isGuest(); - // 4J Added as we need to set this from outside sometimes - void setPlayer(std::shared_ptr player) { this->player = player; } - std::shared_ptr getPlayer() { return player; } + // 4J Added as we need to set this from outside sometimes + void setPlayer(std::shared_ptr player) { + this->player = player; + } + std::shared_ptr getPlayer() { return player; } - // 4J Added to signal a disconnect from another thread - void closeOnTick() { m_bCloseOnTick = true; } + // 4J Added to signal a disconnect from another thread + void closeOnTick() { m_bCloseOnTick = true; } - // 4J Added so that we can send on textures that get received after this connection requested them - void handleTextureReceived(const std::wstring &textureName); - void handleTextureAndGeometryReceived(const std::wstring &textureName); + // 4J Added so that we can send on textures that get received after this + // connection requested them + void handleTextureReceived(const std::wstring& textureName); + void handleTextureAndGeometryReceived(const std::wstring& textureName); - void setShowOnMaps(bool bVal); + void setShowOnMaps(bool bVal); - void setWasKicked() { m_bWasKicked = true; } - bool getWasKicked() { return m_bWasKicked; } + void setWasKicked() { m_bWasKicked = true; } + bool getWasKicked() { return m_bWasKicked; } - // 4J Added - bool hasClientTickedOnce() { return m_bHasClientTickedOnce; } + // 4J Added + bool hasClientTickedOnce() { return m_bHasClientTickedOnce; } private: - bool m_bCloseOnTick; - std::vector m_texturesRequested; + bool m_bCloseOnTick; + std::vector m_texturesRequested; - bool m_bWasKicked; + bool m_bWasKicked; }; diff --git a/Minecraft.Client/Network/PlayerInfo.h b/Minecraft.Client/Network/PlayerInfo.h index ba0f3413c..f31d59572 100644 --- a/Minecraft.Client/Network/PlayerInfo.h +++ b/Minecraft.Client/Network/PlayerInfo.h @@ -1,15 +1,12 @@ #pragma once - -class PlayerInfo -{ +class PlayerInfo { public: - std::wstring name; - int latency; + std::wstring name; + int latency; - PlayerInfo(const std::wstring &name) - { - this->name = name; - latency = 0; - } + PlayerInfo(const std::wstring& name) { + this->name = name; + latency = 0; + } }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PlayerList.cpp b/Minecraft.Client/Network/PlayerList.cpp index 1f48183c8..9f32610d8 100644 --- a/Minecraft.Client/Network/PlayerList.cpp +++ b/Minecraft.Client/Network/PlayerList.cpp @@ -31,604 +31,692 @@ #include "../Platform/Common/Network/Sony/NetworkPlayerSony.h" #endif -// 4J - this class is fairly substantially altered as there didn't seem any point in porting code for banning, whitelisting, ops etc. +// 4J - this class is fairly substantially altered as there didn't seem any +// point in porting code for banning, whitelisting, ops etc. -PlayerList::PlayerList(MinecraftServer *server) -{ - playerIo = NULL; +PlayerList::PlayerList(MinecraftServer* server) { + playerIo = NULL; this->server = server; - sendAllPlayerInfoIn = 0; - overrideGameMode = NULL; - allowCheatsForAllPlayers = false; + sendAllPlayerInfoIn = 0; + overrideGameMode = NULL; + allowCheatsForAllPlayers = false; #ifdef __PSVITA__ - viewDistance = 3; + viewDistance = 3; #elif defined _LARGE_WORLDS - viewDistance = 16; + viewDistance = 16; #else - viewDistance = 10; + viewDistance = 10; #endif - //int viewDistance = server->settings->getInt(L"view-distance", 10); + // int viewDistance = server->settings->getInt(L"view-distance", 10); maxPlayers = server->settings->getInt(L"max-players", 20); doWhiteList = false; - - InitializeCriticalSection(&m_kickPlayersCS); - InitializeCriticalSection(&m_closePlayersCS); + + InitializeCriticalSection(&m_kickPlayersCS); + InitializeCriticalSection(&m_closePlayersCS); } -PlayerList::~PlayerList() -{ - for( AUTO_VAR(it, players.begin()); it < players.end(); it++ ) - { - (*it)->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency - delete (*it)->gameMode; // Gamemode also needs deleted as it references back to this player - (*it)->gameMode = NULL; - } +PlayerList::~PlayerList() { + for (AUTO_VAR(it, players.begin()); it < players.end(); it++) { + (*it)->connection = nullptr; // Must remove reference to connection, or + // else there is a circular dependency + delete (*it)->gameMode; // Gamemode also needs deleted as it references + // back to this player + (*it)->gameMode = NULL; + } - DeleteCriticalSection(&m_kickPlayersCS); - DeleteCriticalSection(&m_closePlayersCS); + DeleteCriticalSection(&m_kickPlayersCS); + DeleteCriticalSection(&m_closePlayersCS); } -void PlayerList::placeNewPlayer(Connection *connection, std::shared_ptr player, std::shared_ptr packet) -{ - bool newPlayer = load(player); - player->setLevel(server->getLevel(player->dimension)); - player->gameMode->setLevel((ServerLevel *) player->level); +void PlayerList::placeNewPlayer(Connection* connection, + std::shared_ptr player, + std::shared_ptr packet) { + bool newPlayer = load(player); + player->setLevel(server->getLevel(player->dimension)); + player->gameMode->setLevel((ServerLevel*)player->level); - // Make sure these privileges are always turned off for the host player - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && networkPlayer->IsHost()) - { - player->enableAllPlayerPrivileges(true); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST,1); - } + // Make sure these privileges are always turned off for the host player + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + if (networkPlayer != NULL && networkPlayer->IsHost()) { + player->enableAllPlayerPrivileges(true); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST, 1); + } #if defined(__PS3__) || defined(__ORBIS__) - // PS3 networking library doesn't automatically assign PlayerUIDs to the network players for anything remote, so need to tell it what to set from the data in this packet now - if( !g_NetworkManager.IsLocalGame() ) - { - if( networkPlayer != NULL ) - { - ((NetworkPlayerSony *)networkPlayer)->SetUID( packet->m_onlineXuid ); - } - } + // PS3 networking library doesn't automatically assign PlayerUIDs to the + // network players for anything remote, so need to tell it what to set from + // the data in this packet now + if (!g_NetworkManager.IsLocalGame()) { + if (networkPlayer != NULL) { + ((NetworkPlayerSony*)networkPlayer)->SetUID(packet->m_onlineXuid); + } + } #endif - // 4J Stu - TU-1 hotfix - // Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down - validatePlayerSpawnPosition(player); + // 4J Stu - TU-1 hotfix + // Fix for #13150 - When a player loads/joins a game after saving/leaving in + // the nether, sometimes they are spawned on top of the nether and cannot + // mine down + validatePlayerSpawnPosition(player); -// logger.info(getName() + " logged in with entity id " + playerEntity.entityId + " at (" + playerEntity.x + ", " + playerEntity.y + ", " + playerEntity.z + ")"); + // logger.info(getName() + " logged in with entity id " + + // playerEntity.entityId + " at (" + playerEntity.x + ", " + + // playerEntity.y + ", " + playerEntity.z + ")"); - ServerLevel *level = server->getLevel(player->dimension); + ServerLevel* level = server->getLevel(player->dimension); - std::uint8_t playerIndex = 0; - { - bool usedIndexes[MINECRAFT_NET_MAX_PLAYERS]; - ZeroMemory( &usedIndexes, MINECRAFT_NET_MAX_PLAYERS * sizeof(bool) ); - for(AUTO_VAR(it, players.begin()); it < players.end(); ++it) - { - usedIndexes[ (int)(*it)->getPlayerIndex() ] = true; - } - for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) - { - if(!usedIndexes[i]) - { - playerIndex = i; - break; - } - } - } - player->setPlayerIndex( playerIndex ); - player->setCustomSkin( packet->m_playerSkinId ); - player->setCustomCape( packet->m_playerCapeId ); + std::uint8_t playerIndex = 0; + { + bool usedIndexes[MINECRAFT_NET_MAX_PLAYERS]; + ZeroMemory(&usedIndexes, MINECRAFT_NET_MAX_PLAYERS * sizeof(bool)); + for (AUTO_VAR(it, players.begin()); it < players.end(); ++it) { + usedIndexes[(int)(*it)->getPlayerIndex()] = true; + } + for (unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { + if (!usedIndexes[i]) { + playerIndex = i; + break; + } + } + } + player->setPlayerIndex(playerIndex); + player->setCustomSkin(packet->m_playerSkinId); + player->setCustomCape(packet->m_playerCapeId); - // 4J-JEV: Moved this here so we can send player-model texture and geometry data. - std::shared_ptr playerConnection = std::shared_ptr(new PlayerConnection(server, connection, player)); - //player->connection = playerConnection; // Used to be assigned in PlayerConnection ctor but moved out so we can use std::shared_ptr + // 4J-JEV: Moved this here so we can send player-model texture and geometry + // data. + std::shared_ptr playerConnection = + std::shared_ptr( + new PlayerConnection(server, connection, player)); + // player->connection = playerConnection; // Used to be assigned in + // PlayerConnection ctor but moved out so we can use std::shared_ptr - if(newPlayer) - { - int mapScale = 3; + if (newPlayer) { + int mapScale = 3; #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); + int centreXC = (int)(Math::round(player->x / scale) * scale); + int centreZC = (int)(Math::round(player->z / scale) * scale); #else - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - int centreXC = 0; - int centreZC = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, + // since we can fit the whole world in our map + int centreXC = 0; + int centreZC = 0; #endif - // 4J Added - Give every player a map the first time they join a server - player->inventory->setItem( 9, std::shared_ptr( new ItemInstance(Item::map_Id, 1, level->getAuxValueForMap(player->getXuid(),0,centreXC, centreZC, mapScale ) ) ) ); - if(app.getGameRuleDefinitions() != NULL) - { - app.getGameRuleDefinitions()->postProcessPlayer(player); - } - } + // 4J Added - Give every player a map the first time they join a server + player->inventory->setItem( + 9, std::shared_ptr(new ItemInstance( + Item::map_Id, 1, + level->getAuxValueForMap(player->getXuid(), 0, centreXC, + centreZC, mapScale)))); + if (app.getGameRuleDefinitions() != NULL) { + app.getGameRuleDefinitions()->postProcessPlayer(player); + } + } - if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) - { - if( server->getConnection()->addPendingTextureRequest(player->customTextureUrl)) - { + if (!player->customTextureUrl.empty() && + player->customTextureUrl.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl)) { + if (server->getConnection()->addPendingTextureRequest( + player->customTextureUrl)) { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + player->customTextureUrl.c_str(), player->name.c_str()); #endif - playerConnection->send(std::shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); - } - } - else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); - } + playerConnection->send(std::shared_ptr( + new TextureAndGeometryPacket(player->customTextureUrl, NULL, + 0))); + } + } else if (!player->customTextureUrl.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl, NULL, 0); + } - if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - if( server->getConnection()->addPendingTextureRequest(player->customTextureUrl2)) - { + if (!player->customTextureUrl2.empty() && + player->customTextureUrl2.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl2)) { + if (server->getConnection()->addPendingTextureRequest( + player->customTextureUrl2)) { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + player->customTextureUrl2.c_str(), player->name.c_str()); #endif - playerConnection->send(std::shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); - } - } - else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); - } + playerConnection->send(std::shared_ptr( + new TexturePacket(player->customTextureUrl2, NULL, 0))); + } + } else if (!player->customTextureUrl2.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl2)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl2, NULL, 0); + } - player->setIsGuest( packet->m_isGuest ); + player->setIsGuest(packet->m_isGuest); - Pos *spawnPos = level->getSharedSpawnPos(); + Pos* spawnPos = level->getSharedSpawnPos(); - updatePlayerGameMode(player, nullptr, level); + updatePlayerGameMode(player, nullptr, level); - // Update the privileges with the correct game mode - GameType *gameType = Player::getPlayerGamePrivilege(player->getAllPlayerGamePrivileges(),Player::ePlayerGamePrivilege_CreativeMode) ? GameType::CREATIVE : GameType::SURVIVAL; - gameType = LevelSettings::validateGameType(gameType->getId()); - if (player->gameMode->getGameModeForPlayer() != gameType) - { - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,player->gameMode->getGameModeForPlayer()->getId() ); - } + // Update the privileges with the correct game mode + GameType* gameType = Player::getPlayerGamePrivilege( + player->getAllPlayerGamePrivileges(), + Player::ePlayerGamePrivilege_CreativeMode) + ? GameType::CREATIVE + : GameType::SURVIVAL; + gameType = LevelSettings::validateGameType(gameType->getId()); + if (player->gameMode->getGameModeForPlayer() != gameType) { + player->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CreativeMode, + player->gameMode->getGameModeForPlayer()->getId()); + } - //std::shared_ptr playerConnection = std::shared_ptr(new PlayerConnection(server, connection, player)); - player->connection = playerConnection; // Used to be assigned in PlayerConnection ctor but moved out so we can use std::shared_ptr + // std::shared_ptr playerConnection = + // std::shared_ptr(new PlayerConnection(server, + // connection, player)); + player->connection = + playerConnection; // Used to be assigned in PlayerConnection ctor but + // moved out so we can use std::shared_ptr - // 4J Added to store UGC settings - playerConnection->m_friendsOnlyUGC = packet->m_friendsOnlyUGC; - playerConnection->m_offlineXUID = packet->m_offlineXuid; - playerConnection->m_onlineXUID = packet->m_onlineXuid; + // 4J Added to store UGC settings + playerConnection->m_friendsOnlyUGC = packet->m_friendsOnlyUGC; + playerConnection->m_offlineXUID = packet->m_offlineXuid; + playerConnection->m_onlineXUID = packet->m_onlineXuid; - // This player is now added to the list, so incrementing this value invalidates all previous PreLogin packets - if(packet->m_friendsOnlyUGC) ++server->m_ugcPlayersVersion; + // This player is now added to the list, so incrementing this value + // invalidates all previous PreLogin packets + if (packet->m_friendsOnlyUGC) ++server->m_ugcPlayersVersion; - addPlayerToReceiving( player ); + addPlayerToReceiving(player); - playerConnection->send( std::shared_ptr( new LoginPacket(L"", player->entityId, level->getLevelData()->getGenerator(), level->getSeed(), player->gameMode->getGameModeForPlayer()->getId(), - (std::uint8_t) level->dimension->id, (std::uint8_t) level->getMaxBuildHeight(), (std::uint8_t) getMaxPlayers(), - level->difficulty, TelemetryManager->GetMultiplayerInstanceID(), playerIndex, level->useNewSeaLevel(), player->getAllPlayerGamePrivileges(), - level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale() ) ) ); - playerConnection->send( std::shared_ptr( new SetSpawnPositionPacket(spawnPos->x, spawnPos->y, spawnPos->z) ) ); - playerConnection->send( std::shared_ptr( new PlayerAbilitiesPacket(&player->abilities)) ); - delete spawnPos; + playerConnection->send(std::shared_ptr(new LoginPacket( + L"", player->entityId, level->getLevelData()->getGenerator(), + level->getSeed(), player->gameMode->getGameModeForPlayer()->getId(), + (std::uint8_t)level->dimension->id, + (std::uint8_t)level->getMaxBuildHeight(), (std::uint8_t)getMaxPlayers(), + level->difficulty, TelemetryManager->GetMultiplayerInstanceID(), + playerIndex, level->useNewSeaLevel(), + player->getAllPlayerGamePrivileges(), + level->getLevelData()->getXZSize(), + level->getLevelData()->getHellScale()))); + playerConnection->send(std::shared_ptr( + new SetSpawnPositionPacket(spawnPos->x, spawnPos->y, spawnPos->z))); + playerConnection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&player->abilities))); + delete spawnPos; - sendLevelInfo(player, level); + sendLevelInfo(player, level); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + playerEntity->name + L" joined the game.") ) ); - broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame) ) ); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + playerEntity->name + L" joined the game.") ) ); + broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame))); - MemSect(14); - add(player); - MemSect(0); + MemSect(14); + add(player); + MemSect(0); - player->doTick(true, true, false); // 4J - added - force sending of the nearest chunk before the player is teleported, so we have somewhere to arrive on... - playerConnection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + player->doTick( + true, true, + false); // 4J - added - force sending of the nearest chunk before the + // player is teleported, so we have somewhere to arrive on... + playerConnection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - server->getConnection()->addPlayerConnection(playerConnection); - playerConnection->send( std::shared_ptr( new SetTimePacket(level->getTime()) ) ); + server->getConnection()->addPlayerConnection(playerConnection); + playerConnection->send( + std::shared_ptr(new SetTimePacket(level->getTime()))); - AUTO_VAR(activeEffects, player->getActiveEffects()); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; - playerConnection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } + AUTO_VAR(activeEffects, player->getActiveEffects()); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; + playerConnection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } - player->initMenu(); + player->initMenu(); - // If we are joining at the same time as someone in the end on this system is travelling through the win portal, - // then we should set our wonGame flag to true so that respawning works when the EndPoem is closed - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) - { - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && servPlayer->wonGame ) - { - player->wonGame = true; - break; - } - } - } + // If we are joining at the same time as someone in the end on this system + // is travelling through the win portal, then we should set our wonGame flag + // to true so that respawning works when the EndPoem is closed + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL) { + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + std::shared_ptr servPlayer = *it; + INetworkPlayer* checkPlayer = + servPlayer->connection->getNetworkPlayer(); + if (thisPlayer != checkPlayer && checkPlayer != NULL && + thisPlayer->IsSameSystem(checkPlayer) && servPlayer->wonGame) { + player->wonGame = true; + break; + } + } + } } -void PlayerList::setLevel(ServerLevelArray levels) -{ - playerIo = levels[0]->getLevelStorage()->getPlayerIO(); +void PlayerList::setLevel(ServerLevelArray levels) { + playerIo = levels[0]->getLevelStorage()->getPlayerIO(); } -void PlayerList::changeDimension(std::shared_ptr player, ServerLevel *from) -{ - ServerLevel *to = player->getLevel(); +void PlayerList::changeDimension(std::shared_ptr player, + ServerLevel* from) { + ServerLevel* to = player->getLevel(); - if (from != NULL) from->getChunkMap()->remove(player); - to->getChunkMap()->add(player); + if (from != NULL) from->getChunkMap()->remove(player); + to->getChunkMap()->add(player); - to->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + to->cache->create(((int)player->x) >> 4, ((int)player->z) >> 4); } -int PlayerList::getMaxRange() -{ - return PlayerChunkMap::convertChunkRangeToBlock(getViewDistance()); +int PlayerList::getMaxRange() { + return PlayerChunkMap::convertChunkRangeToBlock(getViewDistance()); } - // 4J Changed return val to bool to check if new player or loaded player -bool PlayerList::load(std::shared_ptr player) -{ - return playerIo->load(player); +// 4J Changed return val to bool to check if new player or loaded player +bool PlayerList::load(std::shared_ptr player) { + return playerIo->load(player); } -void PlayerList::save(std::shared_ptr player) -{ - playerIo->save(player); +void PlayerList::save(std::shared_ptr player) { + playerIo->save(player); } // 4J Stu - TU-1 hotifx -// Add this function to take some of the code from the PlayerList::add function with the fixes -// for checking spawn area, especially in the nether. These needed to be done in a different order from before -// Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down -void PlayerList::validatePlayerSpawnPosition(std::shared_ptr player) -{ - // 4J Stu - Some adjustments to make sure the current players position is correct - // Make sure that the player is on the ground, and in the centre x/z of the current column - app.DebugPrintf("Original pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); +// Add this function to take some of the code from the PlayerList::add function +// with the fixes for checking spawn area, especially in the nether. These +// needed to be done in a different order from before Fix for #13150 - When a +// player loads/joins a game after saving/leaving in the nether, sometimes they +// are spawned on top of the nether and cannot mine down +void PlayerList::validatePlayerSpawnPosition( + std::shared_ptr player) { + // 4J Stu - Some adjustments to make sure the current players position is + // correct Make sure that the player is on the ground, and in the centre x/z + // of the current column + app.DebugPrintf("Original pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - double targetX = 0; - if(player->x < 0) targetX = Mth::ceil(player->x) - 0.5; - else targetX = Mth::floor(player->x) + 0.5; + double targetX = 0; + if (player->x < 0) + targetX = Mth::ceil(player->x) - 0.5; + else + targetX = Mth::floor(player->x) + 0.5; - double targetY = floor(player->y); + double targetY = floor(player->y); - double targetZ = 0; - if(player->z < 0) targetZ = Mth::ceil(player->z) - 0.5; - else targetZ = Mth::floor(player->z) + 0.5; + double targetZ = 0; + if (player->z < 0) + targetZ = Mth::ceil(player->z) - 0.5; + else + targetZ = Mth::floor(player->z) + 0.5; - player->setPos(targetX, targetY, targetZ); + player->setPos(targetX, targetY, targetZ); - app.DebugPrintf("New pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); + app.DebugPrintf("New pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - ServerLevel *level = server->getLevel(player->dimension); - while (level->getCubes(player, player->bb)->size() != 0) - { + ServerLevel* level = server->getLevel(player->dimension); + while (level->getCubes(player, player->bb)->size() != 0) { player->setPos(player->x, player->y + 1, player->z); } - app.DebugPrintf("Final pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); + app.DebugPrintf("Final pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - // 4J Stu - If we are in the nether and the above while loop has put us above the nether then we have a problem - // Finding a valid, safe spawn point is potentially computationally expensive (may have to hunt through a large part - // of the nether) so move the player to their spawn position in the overworld so that they do not lose their inventory - // 4J Stu - We also use this mechanism to force a spawn point in the overworld for players who were in the save when the reset nether option was applied - if(level->dimension->id == -1 && player->y > 125) - { - app.DebugPrintf("Player in the nether tried to spawn at y = %f, moving to overworld\n", player->y); - player->setLevel(server->getLevel(0)); - player->gameMode->setLevel(server->getLevel(0)); - player->dimension = 0; + // 4J Stu - If we are in the nether and the above while loop has put us + // above the nether then we have a problem Finding a valid, safe spawn point + // is potentially computationally expensive (may have to hunt through a + // large part of the nether) so move the player to their spawn position in + // the overworld so that they do not lose their inventory 4J Stu - We also + // use this mechanism to force a spawn point in the overworld for players + // who were in the save when the reset nether option was applied + if (level->dimension->id == -1 && player->y > 125) { + app.DebugPrintf( + "Player in the nether tried to spawn at y = %f, moving to " + "overworld\n", + player->y); + player->setLevel(server->getLevel(0)); + player->gameMode->setLevel(server->getLevel(0)); + player->dimension = 0; - level = server->getLevel(player->dimension); + level = server->getLevel(player->dimension); - Pos *levelSpawn = level->getSharedSpawnPos(); - player->setPos(levelSpawn->x, levelSpawn->y, levelSpawn->z); - delete levelSpawn; + Pos* levelSpawn = level->getSharedSpawnPos(); + player->setPos(levelSpawn->x, levelSpawn->y, levelSpawn->z); + delete levelSpawn; - Pos *bedPosition = player->getRespawnPosition(); - if (bedPosition != NULL) - { - Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(player->dimension), bedPosition); - if (respawnPosition != NULL) - { - player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); - player->setRespawnPosition(bedPosition); - } - delete bedPosition; - } - while (level->getCubes(player, player->bb)->size() != 0) - { - player->setPos(player->x, player->y + 1, player->z); - } - - app.DebugPrintf("Updated pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); - } + Pos* bedPosition = player->getRespawnPosition(); + if (bedPosition != NULL) { + Pos* respawnPosition = Player::checkBedValidRespawnPosition( + server->getLevel(player->dimension), bedPosition); + if (respawnPosition != NULL) { + player->moveTo(respawnPosition->x + 0.5f, + respawnPosition->y + 0.1f, + respawnPosition->z + 0.5f, 0, 0); + player->setRespawnPosition(bedPosition); + } + delete bedPosition; + } + while (level->getCubes(player, player->bb)->size() != 0) { + player->setPos(player->x, player->y + 1, player->z); + } + + app.DebugPrintf("Updated pos is %f, %f, %f in dimension %d\n", + player->x, player->y, player->z, player->dimension); + } } -void PlayerList::add(std::shared_ptr player) -{ - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(player->name, true, 1000) ) ); - if( player->connection->getNetworkPlayer() ) - { - broadcastAll(std::shared_ptr( new PlayerInfoPacket( player ) ) ); - } +void PlayerList::add(std::shared_ptr player) { + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(player->name, true, 1000) ) ); + if (player->connection->getNetworkPlayer()) { + broadcastAll( + std::shared_ptr(new PlayerInfoPacket(player))); + } players.push_back(player); - // 4J Added - addPlayerToReceiving(player); + // 4J Added + addPlayerToReceiving(player); // Ensure the area the player is spawning in is loaded! - ServerLevel *level = server->getLevel(player->dimension); + ServerLevel* level = server->getLevel(player->dimension); - // 4J Stu - TU-1 hotfix - // Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down - // Some code from here has been moved to the above validatePlayerSpawnPosition function + // 4J Stu - TU-1 hotfix + // Fix for #13150 - When a player loads/joins a game after saving/leaving in + // the nether, sometimes they are spawned on top of the nether and cannot + // mine down Some code from here has been moved to the above + // validatePlayerSpawnPosition function - // 4J Stu - Swapped these lines about so that we get the chunk visiblity packet way ahead of all the add tracked entity packets - // Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”. + // 4J Stu - Swapped these lines about so that we get the chunk visiblity + // packet way ahead of all the add tracked entity packets Fix for #9169 - + // ART : Sign text is replaced with the words “Awaiting approval”. changeDimension(player, NULL); level->addEntity(player); - for (int i = 0; i < players.size(); i++) - { - std::shared_ptr op = players.at(i); - //player->connection->send(std::shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); - if( op->connection->getNetworkPlayer() ) - { - player->connection->send(std::shared_ptr( new PlayerInfoPacket( op ) ) ); - } - } + for (int i = 0; i < players.size(); i++) { + std::shared_ptr op = players.at(i); + // player->connection->send(std::shared_ptr( new + // PlayerInfoPacket(op->name, true, op->latency) ) ); + if (op->connection->getNetworkPlayer()) { + player->connection->send( + std::shared_ptr(new PlayerInfoPacket(op))); + } + } - if(level->isAtLeastOnePlayerSleeping()) - { - std::shared_ptr firstSleepingPlayer = nullptr; - for (unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr thisPlayer = players[i]; - if(thisPlayer->isSleeping()) - { - if(firstSleepingPlayer == NULL) firstSleepingPlayer = thisPlayer; - thisPlayer->connection->send(std::shared_ptr( new ChatPacket(thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); - } - } - player->connection->send(std::shared_ptr( new ChatPacket(firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep))); - } + if (level->isAtLeastOnePlayerSleeping()) { + std::shared_ptr firstSleepingPlayer = nullptr; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr thisPlayer = players[i]; + if (thisPlayer->isSleeping()) { + if (firstSleepingPlayer == NULL) + firstSleepingPlayer = thisPlayer; + thisPlayer->connection->send( + std::shared_ptr(new ChatPacket( + thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); + } + } + player->connection->send(std::shared_ptr(new ChatPacket( + firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep))); + } } -void PlayerList::move(std::shared_ptr player) -{ - player->getLevel()->getChunkMap()->move(player); +void PlayerList::move(std::shared_ptr player) { + player->getLevel()->getChunkMap()->move(player); } -void PlayerList::remove(std::shared_ptr player) -{ +void PlayerList::remove(std::shared_ptr player) { save(player); - //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map - if(player->isGuest()) playerIo->deleteMapFilesForPlayer(player); - ServerLevel *level = player->getLevel(); + // 4J Stu - We don't want to save the map data for guests, so when we are + // sure that the player is gone delete the map + if (player->isGuest()) playerIo->deleteMapFilesForPlayer(player); + ServerLevel* level = player->getLevel(); level->removeEntity(player); level->getChunkMap()->remove(player); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( it != players.end() ) - { - players.erase(it); - } - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(player->name, false, 9999) ) ); + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (it != players.end()) { + players.erase(it); + } + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(player->name, false, 9999) ) ); - removePlayerFromReceiving(player); - player->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency - delete player->gameMode; // Gamemode also needs deleted as it references back to this player - player->gameMode = NULL; + removePlayerFromReceiving(player); + player->connection = nullptr; // Must remove reference to connection, or + // else there is a circular dependency + delete player->gameMode; // Gamemode also needs deleted as it references + // back to this player + player->gameMode = NULL; - // 4J Stu - Save all the players currently in the game, which will also free up unused map id slots if required, and remove old players - saveAll(NULL,false); + // 4J Stu - Save all the players currently in the game, which will also free + // up unused map id slots if required, and remove old players + saveAll(NULL, false); } -std::shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendingConnection, const std::wstring& userName, PlayerUID xuid, PlayerUID onlineXuid) -{ - if (players.size() >= maxPlayers) - { +std::shared_ptr PlayerList::getPlayerForLogin( + PendingConnection* pendingConnection, const std::wstring& userName, + PlayerUID xuid, PlayerUID onlineXuid) { + if (players.size() >= maxPlayers) { pendingConnection->disconnect(DisconnectPacket::eDisconnect_ServerFull); return std::shared_ptr(); } - - std::shared_ptr player = std::shared_ptr(new ServerPlayer(server, server->getLevel(0), userName, new ServerPlayerGameMode(server->getLevel(0)) )); - player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor - player->setXuid( xuid ); // 4J Added - player->setOnlineXuid( onlineXuid ); // 4J Added - // Work out the base server player settings - INetworkPlayer *networkPlayer = pendingConnection->connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && !networkPlayer->IsHost()) - { - player->enableAllPlayerPrivileges( app.GetGameHostOption(eGameHostOption_TrustPlayers)>0 ); - } + std::shared_ptr player = std::shared_ptr( + new ServerPlayer(server, server->getLevel(0), userName, + new ServerPlayerGameMode(server->getLevel(0)))); + player->gameMode->player = player; // 4J added as had to remove this + // assignment from ServerPlayer ctor + player->setXuid(xuid); // 4J Added + player->setOnlineXuid(onlineXuid); // 4J Added - // 4J Added - LevelRuleset *serverRuleDefs = app.getGameRuleDefinitions(); - if(serverRuleDefs != NULL) - { - player->gameMode->setGameRules( GameRuleDefinition::generateNewGameRulesInstance(GameRulesInstance::eGameRulesInstanceType_ServerPlayer, serverRuleDefs, pendingConnection->connection) ); - } + // Work out the base server player settings + INetworkPlayer* networkPlayer = + pendingConnection->connection->getSocket()->getPlayer(); + if (networkPlayer != NULL && !networkPlayer->IsHost()) { + player->enableAllPlayerPrivileges( + app.GetGameHostOption(eGameHostOption_TrustPlayers) > 0); + } + + // 4J Added + LevelRuleset* serverRuleDefs = app.getGameRuleDefinitions(); + if (serverRuleDefs != NULL) { + player->gameMode->setGameRules( + GameRuleDefinition::generateNewGameRulesInstance( + GameRulesInstance::eGameRulesInstanceType_ServerPlayer, + serverRuleDefs, pendingConnection->connection)); + } return player; } -std::shared_ptr PlayerList::respawn(std::shared_ptr serverPlayer, int targetDimension, bool keepAllPlayerData) -{ - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. - bool isPrimary = canReceiveAllPackets(serverPlayer); // Is this the primary player in its current dimension? - int oldDimension = serverPlayer->dimension; - bool isEmptying = ( targetDimension != oldDimension); // We're not emptying this dimension on this machine if this player is going back into the same dimension +std::shared_ptr PlayerList::respawn( + std::shared_ptr serverPlayer, int targetDimension, + bool keepAllPlayerData) { + // How we handle the entity tracker depends on whether we are the primary + // player currently, and whether there will be any player in the same system + // in the same dimension once we finish respawning. + bool isPrimary = canReceiveAllPackets( + serverPlayer); // Is this the primary player in its current dimension? + int oldDimension = serverPlayer->dimension; + bool isEmptying = + (targetDimension != + oldDimension); // We're not emptying this dimension on this machine if + // this player is going back into the same dimension - // Also consider if there is another player on this machine which is in the same dimension and can take over as primary player - if( isEmptying ) - { - INetworkPlayer *thisPlayer = serverPlayer->connection->getNetworkPlayer(); + // Also consider if there is another player on this machine which is in the + // same dimension and can take over as primary player + if (isEmptying) { + INetworkPlayer* thisPlayer = + serverPlayer->connection->getNetworkPlayer(); - for( unsigned int i = 0; i < players.size(); i++ ) - { - std::shared_ptr ep = players[i]; - if( ep == serverPlayer ) continue; - if( ep->dimension != oldDimension ) continue; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr ep = players[i]; + if (ep == serverPlayer) continue; + if (ep->dimension != oldDimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // There's another player here in the same dimension - we're not the last one out - isEmptying = false; - } - } - } + INetworkPlayer* otherPlayer = ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + // There's another player here in the same dimension - we're not + // the last one out + isEmptying = false; + } + } + } - // Now we know where we stand, the actions to take are as follows: - // (1) if this isn't the primary player, then we just need to remove it from the entity tracker - // (2) if this Is the primary player then: - // (a) if isEmptying is true, then remove the player from the tracker, and send "remove entity" packets for anything seen (this is the original behaviour of the code) - // (b) if isEmptying is false, then we'll be transferring control of entity tracking to another player + // Now we know where we stand, the actions to take are as follows: + // (1) if this isn't the primary player, then we just need to remove it from + // the entity tracker (2) if this Is the primary player then: + // (a) if isEmptying is true, then remove the player from the + //tracker, and send "remove entity" packets for anything seen (this is the + //original behaviour of the code) (b) if isEmptying is false, then we'll be + //transferring control of entity tracking to another player - if( isPrimary ) - { - if( isEmptying ) - { - app.DebugPrintf("Emptying this dimension\n"); - serverPlayer->getLevel()->getTracker()->clear(serverPlayer); - } - else - { - app.DebugPrintf("Transferring... storing flags\n"); - serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); - } - } - else - { - app.DebugPrintf("Not primary player\n"); - serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); - } + if (isPrimary) { + if (isEmptying) { + app.DebugPrintf("Emptying this dimension\n"); + serverPlayer->getLevel()->getTracker()->clear(serverPlayer); + } else { + app.DebugPrintf("Transferring... storing flags\n"); + serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); + } + } else { + app.DebugPrintf("Not primary player\n"); + serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); + } - serverPlayer->getLevel()->getChunkMap()->remove(serverPlayer); - AUTO_VAR(it, find(players.begin(),players.end(),serverPlayer)); - if( it != players.end() ) - { - players.erase(it); - } - server->getLevel(serverPlayer->dimension)->removeEntityImmediately(serverPlayer); + serverPlayer->getLevel()->getChunkMap()->remove(serverPlayer); + AUTO_VAR(it, find(players.begin(), players.end(), serverPlayer)); + if (it != players.end()) { + players.erase(it); + } + server->getLevel(serverPlayer->dimension) + ->removeEntityImmediately(serverPlayer); - Pos *bedPosition = serverPlayer->getRespawnPosition(); + Pos* bedPosition = serverPlayer->getRespawnPosition(); - removePlayerFromReceiving(serverPlayer); + removePlayerFromReceiving(serverPlayer); serverPlayer->dimension = targetDimension; - EDefaultSkins skin = serverPlayer->getPlayerDefaultSkin(); - std::uint8_t playerIndex = serverPlayer->getPlayerIndex(); + EDefaultSkins skin = serverPlayer->getPlayerDefaultSkin(); + std::uint8_t playerIndex = serverPlayer->getPlayerIndex(); - PlayerUID playerXuid = serverPlayer->getXuid(); - PlayerUID playerOnlineXuid = serverPlayer->getOnlineXuid(); - - std::shared_ptr player = std::shared_ptr(new ServerPlayer(server, server->getLevel(serverPlayer->dimension), serverPlayer->name, new ServerPlayerGameMode(server->getLevel(serverPlayer->dimension)))); - player->restoreFrom(serverPlayer, keepAllPlayerData); - if (keepAllPlayerData) - { - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - player->inventory->selected = serverPlayer->inventory->selected; - } - player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor - player->setXuid( playerXuid ); // 4J Added - player->setOnlineXuid( playerOnlineXuid ); // 4J Added + PlayerUID playerXuid = serverPlayer->getXuid(); + PlayerUID playerOnlineXuid = serverPlayer->getOnlineXuid(); - // 4J Stu - Don't reuse the id. If we do, then the player can be re-added after being removed, but the add packet gets sent before the remove packet - //player->entityId = serverPlayer->entityId; + std::shared_ptr player = std::shared_ptr( + new ServerPlayer(server, server->getLevel(serverPlayer->dimension), + serverPlayer->name, + new ServerPlayerGameMode( + server->getLevel(serverPlayer->dimension)))); + player->restoreFrom(serverPlayer, keepAllPlayerData); + if (keepAllPlayerData) { + // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal + // replaces the Player's currently held item with the first one from the + // Quickbar + player->inventory->selected = serverPlayer->inventory->selected; + } + player->gameMode->player = player; // 4J added as had to remove this + // assignment from ServerPlayer ctor + player->setXuid(playerXuid); // 4J Added + player->setOnlineXuid(playerOnlineXuid); // 4J Added + + // 4J Stu - Don't reuse the id. If we do, then the player can be re-added + // after being removed, but the add packet gets sent before the remove + // packet + // player->entityId = serverPlayer->entityId; player->connection = serverPlayer->connection; - player->setPlayerDefaultSkin( skin ); - player->setIsGuest( serverPlayer->isGuest() ); - player->setPlayerIndex( playerIndex ); - player->setCustomSkin( serverPlayer->getCustomSkin() ); - player->setCustomCape( serverPlayer->getCustomCape() ); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, serverPlayer->getAllPlayerGamePrivileges()); - player->gameMode->setGameRules( serverPlayer->gameMode->getGameRules() ); - player->dimension = targetDimension; + player->setPlayerDefaultSkin(skin); + player->setIsGuest(serverPlayer->isGuest()); + player->setPlayerIndex(playerIndex); + player->setCustomSkin(serverPlayer->getCustomSkin()); + player->setCustomCape(serverPlayer->getCustomCape()); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + serverPlayer->getAllPlayerGamePrivileges()); + player->gameMode->setGameRules(serverPlayer->gameMode->getGameRules()); + player->dimension = targetDimension; - // 4J Stu - Added this as we need to know earlier if the player is the player for this connection so that - // we can work out if they are the primary for the system and can receive all packets - player->connection->setPlayer( player ); + // 4J Stu - Added this as we need to know earlier if the player is the + // player for this connection so that we can work out if they are the + // primary for the system and can receive all packets + player->connection->setPlayer(player); - addPlayerToReceiving(player); + addPlayerToReceiving(player); - ServerLevel *level = server->getLevel(serverPlayer->dimension); + ServerLevel* level = server->getLevel(serverPlayer->dimension); - // reset the player's game mode (first pick from old, then copy level if - // necessary) - updatePlayerGameMode(player, serverPlayer, level); + // reset the player's game mode (first pick from old, then copy level if + // necessary) + updatePlayerGameMode(player, serverPlayer, level); - if(serverPlayer->wonGame && targetDimension == oldDimension && serverPlayer->getHealth() > 0) - { - // If the player is still alive and respawning to the same dimension, they are just being added back from someone else viewing the Win screen - player->moveTo(serverPlayer->x, serverPlayer->y, serverPlayer->z, serverPlayer->yRot, serverPlayer->xRot); - if(bedPosition != NULL) - { - player->setRespawnPosition(bedPosition); - delete bedPosition; - } - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - player->inventory->selected = serverPlayer->inventory->selected; - } - else if (bedPosition != NULL) - { - Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(serverPlayer->dimension), bedPosition); - if (respawnPosition != NULL) - { - player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); + if (serverPlayer->wonGame && targetDimension == oldDimension && + serverPlayer->getHealth() > 0) { + // If the player is still alive and respawning to the same dimension, + // they are just being added back from someone else viewing the Win + // screen + player->moveTo(serverPlayer->x, serverPlayer->y, serverPlayer->z, + serverPlayer->yRot, serverPlayer->xRot); + if (bedPosition != NULL) { player->setRespawnPosition(bedPosition); + delete bedPosition; } - else - { - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0) ) ); + // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal + // replaces the Player's currently held item with the first one from the + // Quickbar + player->inventory->selected = serverPlayer->inventory->selected; + } else if (bedPosition != NULL) { + Pos* respawnPosition = Player::checkBedValidRespawnPosition( + server->getLevel(serverPlayer->dimension), bedPosition); + if (respawnPosition != NULL) { + player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, + respawnPosition->z + 0.5f, 0, 0); + player->setRespawnPosition(bedPosition); + } else { + player->connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0))); } - delete bedPosition; + delete bedPosition; } // Ensure the area the player is spawning in is loaded! - level->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + level->cache->create(((int)player->x) >> 4, ((int)player->z) >> 4); - while (!level->getCubes(player, player->bb)->empty()) - { + while (!level->getCubes(player, player->bb)->empty()) { player->setPos(player->x, player->y + 1, player->z); } - player->connection->send( std::shared_ptr( new RespawnPacket((char) player->dimension, player->level->getSeed(), player->level->getMaxBuildHeight(), - player->gameMode->getGameModeForPlayer(), level->difficulty, level->getLevelData()->getGenerator(), - player->level->useNewSeaLevel(), player->entityId, level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale()) ) ); - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + player->connection->send(std::shared_ptr(new RespawnPacket( + (char)player->dimension, player->level->getSeed(), + player->level->getMaxBuildHeight(), + player->gameMode->getGameModeForPlayer(), level->difficulty, + level->getLevelData()->getGenerator(), player->level->useNewSeaLevel(), + player->entityId, level->getLevelData()->getXZSize(), + level->getLevelData()->getHellScale()))); + player->connection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - if(keepAllPlayerData) - { - std::vector *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + if (keepAllPlayerData) { + std::vector* activeEffects = + player->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; - player->connection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } - delete activeEffects; - player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); - } + player->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } + delete activeEffects; + player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); + } sendLevelInfo(player, level); @@ -638,365 +726,354 @@ std::shared_ptr PlayerList::respawn(std::shared_ptr player->initMenu(); - // 4J-JEV - Dying before this point in the tutorial is pretty annoying, - // making sure to remove health/hunger and give you back your meat. - if( Minecraft::GetInstance()->isTutorial() - && (!Minecraft::GetInstance()->gameMode->getTutorial()->isStateCompleted(e_Tutorial_State_Food_Bar)) ) - { - app.getGameRuleDefinitions()->postProcessPlayer(player); - } + // 4J-JEV - Dying before this point in the tutorial is pretty annoying, + // making sure to remove health/hunger and give you back your meat. + if (Minecraft::GetInstance()->isTutorial() && + (!Minecraft::GetInstance()->gameMode->getTutorial()->isStateCompleted( + e_Tutorial_State_Food_Bar))) { + app.getGameRuleDefinitions()->postProcessPlayer(player); + } - if( oldDimension == 1 && player->dimension != 1 ) - { - player->displayClientMessage(IDS_PLAYER_LEFT_END); - } + if (oldDimension == 1 && player->dimension != 1) { + player->displayClientMessage(IDS_PLAYER_LEFT_END); + } return player; - } -void PlayerList::toggleDimension(std::shared_ptr player, int targetDimension) -{ - int lastDimension = player->dimension; - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. - bool isPrimary = canReceiveAllPackets(player); // Is this the primary player in its current dimension? - bool isEmptying = true; +void PlayerList::toggleDimension(std::shared_ptr player, + int targetDimension) { + int lastDimension = player->dimension; + // How we handle the entity tracker depends on whether we are the primary + // player currently, and whether there will be any player in the same system + // in the same dimension once we finish respawning. + bool isPrimary = canReceiveAllPackets( + player); // Is this the primary player in its current dimension? + bool isEmptying = true; - // Also consider if there is another player on this machine which is in the same dimension and can take over as primary player - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); + // Also consider if there is another player on this machine which is in the + // same dimension and can take over as primary player + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - for( unsigned int i = 0; i < players.size(); i++ ) - { - std::shared_ptr ep = players[i]; - if( ep == player ) continue; - if( ep->dimension != lastDimension ) continue; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr ep = players[i]; + if (ep == player) continue; + if (ep->dimension != lastDimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // There's another player here in the same dimension - we're not the last one out - isEmptying = false; - } - } + INetworkPlayer* otherPlayer = ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + // There's another player here in the same dimension - we're not the + // last one out + isEmptying = false; + } + } + // Now we know where we stand, the actions to take are as follows: + // (1) if this isn't the primary player, then we just need to remove it from + // the entity tracker (2) if this Is the primary player then: + // (a) if isEmptying is true, then remove the player from the + //tracker, and send "remove entity" packets for anything seen (this is the + //original behaviour of the code) (b) if isEmptying is false, then we'll be + //transferring control of entity tracking to another player - // Now we know where we stand, the actions to take are as follows: - // (1) if this isn't the primary player, then we just need to remove it from the entity tracker - // (2) if this Is the primary player then: - // (a) if isEmptying is true, then remove the player from the tracker, and send "remove entity" packets for anything seen (this is the original behaviour of the code) - // (b) if isEmptying is false, then we'll be transferring control of entity tracking to another player + if (isPrimary) { + if (isEmptying) { + app.DebugPrintf("Toggle... Emptying this dimension\n"); + player->getLevel()->getTracker()->clear(player); + } else { + app.DebugPrintf("Toggle... transferring\n"); + player->getLevel()->getTracker()->removeEntity(player); + } + } else { + app.DebugPrintf("Toggle... Not primary player\n"); + player->getLevel()->getTracker()->removeEntity(player); + } - if( isPrimary ) - { - if( isEmptying ) - { - app.DebugPrintf("Toggle... Emptying this dimension\n"); - player->getLevel()->getTracker()->clear(player); - } - else - { - app.DebugPrintf("Toggle... transferring\n"); - player->getLevel()->getTracker()->removeEntity(player); - } - } - else - { - app.DebugPrintf("Toggle... Not primary player\n"); - player->getLevel()->getTracker()->removeEntity(player); - } + ServerLevel* oldLevel = server->getLevel(player->dimension); - ServerLevel *oldLevel = server->getLevel(player->dimension); + // 4J Stu - Do this much earlier so we don't end up unloading chunks in the + // wrong dimension + player->getLevel()->getChunkMap()->remove(player); - // 4J Stu - Do this much earlier so we don't end up unloading chunks in the wrong dimension - player->getLevel()->getChunkMap()->remove(player); - - if(player->dimension != 1 && targetDimension == 1) - { - player->displayClientMessage(IDS_PLAYER_ENTERED_END); - } - else if( player->dimension == 1 ) - { - player->displayClientMessage(IDS_PLAYER_LEFT_END); - } + if (player->dimension != 1 && targetDimension == 1) { + player->displayClientMessage(IDS_PLAYER_ENTERED_END); + } else if (player->dimension == 1) { + player->displayClientMessage(IDS_PLAYER_LEFT_END); + } player->dimension = targetDimension; - ServerLevel *newLevel = server->getLevel(player->dimension); + ServerLevel* newLevel = server->getLevel(player->dimension); - // 4J Stu - Fix for #46423 - TU5: Art: Code: No burning animation visible after entering The Nether while burning - player->clearFire(); // Stop burning if travelling through a portal + // 4J Stu - Fix for #46423 - TU5: Art: Code: No burning animation visible + // after entering The Nether while burning + player->clearFire(); // Stop burning if travelling through a portal - // 4J Stu Added so that we remove entities from the correct level, after the respawn packet we will be in the wrong level - player->flushEntitiesToRemove(); + // 4J Stu Added so that we remove entities from the correct level, after the + // respawn packet we will be in the wrong level + player->flushEntitiesToRemove(); - player->connection->send( std::shared_ptr( new RespawnPacket((char) player->dimension, newLevel->getSeed(), newLevel->getMaxBuildHeight(), - player->gameMode->getGameModeForPlayer(), newLevel->difficulty, newLevel->getLevelData()->getGenerator(), - newLevel->useNewSeaLevel(), player->entityId, newLevel->getLevelData()->getXZSize(), newLevel->getLevelData()->getHellScale()) ) ); + player->connection->send(std::shared_ptr(new RespawnPacket( + (char)player->dimension, newLevel->getSeed(), + newLevel->getMaxBuildHeight(), player->gameMode->getGameModeForPlayer(), + newLevel->difficulty, newLevel->getLevelData()->getGenerator(), + newLevel->useNewSeaLevel(), player->entityId, + newLevel->getLevelData()->getXZSize(), + newLevel->getLevelData()->getHellScale()))); oldLevel->removeEntityImmediately(player); player->removed = false; double xt = player->x; double zt = player->z; - double scale = newLevel->getLevelData()->getHellScale(); // 4J Scale was 8 but this is all we can fit in - if (player->dimension == -1) - { + double scale = + newLevel->getLevelData() + ->getHellScale(); // 4J Scale was 8 but this is all we can fit in + if (player->dimension == -1) { xt /= scale; zt /= scale; player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - if (player->isAlive()) - { + if (player->isAlive()) { oldLevel->tick(player, false); } - } - else if (player->dimension == 0) - { + } else if (player->dimension == 0) { xt *= scale; zt *= scale; player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - if (player->isAlive()) - { + if (player->isAlive()) { + oldLevel->tick(player, false); + } + } else { + Pos* p = newLevel->getDimensionSpecificSpawn(); + + xt = p->x; + player->y = p->y; + zt = p->z; + delete p; + player->moveTo(xt, player->y, zt, 90, 0); + if (player->isAlive()) { oldLevel->tick(player, false); } } - else - { - Pos *p = newLevel->getDimensionSpecificSpawn(); - xt = p->x; - player->y = p->y; - zt = p->z; - delete p; - player->moveTo(xt, player->y, zt, 90, 0); - if (player->isAlive()) - { - oldLevel->tick(player, false); - } - } - - removePlayerFromReceiving(player, false, lastDimension); - addPlayerToReceiving(player); - - if (lastDimension == 1) - { - } - else - { - xt = (double) Mth::clamp((int) xt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); - zt = (double) Mth::clamp((int) zt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); - if (player->isAlive()) - { - newLevel->addEntity(player); - player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - newLevel->tick(player, false); - newLevel->cache->autoCreate = true; - (new PortalForcer())->force(newLevel, player); - newLevel->cache->autoCreate = false; - } - } + removePlayerFromReceiving(player, false, lastDimension); + addPlayerToReceiving(player); + if (lastDimension == 1) { + } else { + xt = (double)Mth::clamp((int)xt, -Level::MAX_LEVEL_SIZE + 128, + Level::MAX_LEVEL_SIZE - 128); + zt = (double)Mth::clamp((int)zt, -Level::MAX_LEVEL_SIZE + 128, + Level::MAX_LEVEL_SIZE - 128); + if (player->isAlive()) { + newLevel->addEntity(player); + player->moveTo(xt, player->y, zt, player->yRot, player->xRot); + newLevel->tick(player, false); + newLevel->cache->autoCreate = true; + (new PortalForcer())->force(newLevel, player); + newLevel->cache->autoCreate = false; + } + } player->setLevel(newLevel); changeDimension(player, oldLevel); - player->gameMode->setLevel(newLevel); + player->gameMode->setLevel(newLevel); - // Resend the teleport if we haven't yet sent the chunk they will land on - if( !g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),ServerPlayer::getFlagIndexForChunk( ChunkPos(player->xChunk,player->zChunk), player->level->dimension->id ) ) ) - { - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot, false); - // Force sending of the current chunk - player->doTick(true, true, true); - } - - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + // Resend the teleport if we haven't yet sent the chunk they will land on + if (!g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), + ServerPlayer::getFlagIndexForChunk( + ChunkPos(player->xChunk, player->zChunk), + player->level->dimension->id))) { + player->connection->teleport(player->x, player->y, player->z, + player->yRot, player->xRot, false); + // Force sending of the current chunk + player->doTick(true, true, true); + } - // 4J Stu - Fix for #64683 - Customer Encountered: TU7: Content: Gameplay: Potion effects are removed after using the Nether Portal - std::vector *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + player->connection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - player->connection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } - delete activeEffects; - player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); + // 4J Stu - Fix for #64683 - Customer Encountered: TU7: Content: Gameplay: + // Potion effects are removed after using the Nether Portal + std::vector* activeEffects = player->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; + + player->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } + delete activeEffects; + player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); sendLevelInfo(player, newLevel); sendAllPlayerInfo(player); } -void PlayerList::tick() -{ - // 4J - brought changes to how often this is sent forward from 1.2.3 - if (++sendAllPlayerInfoIn > SEND_PLAYER_INFO_INTERVAL) - { +void PlayerList::tick() { + // 4J - brought changes to how often this is sent forward from 1.2.3 + if (++sendAllPlayerInfoIn > SEND_PLAYER_INFO_INTERVAL) { sendAllPlayerInfoIn = 0; } - if (sendAllPlayerInfoIn < players.size()) - { - std::shared_ptr op = players[sendAllPlayerInfoIn]; - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); - if( op->connection->getNetworkPlayer() ) - { - broadcastAll(std::shared_ptr( new PlayerInfoPacket( op ) ) ); - } - } + if (sendAllPlayerInfoIn < players.size()) { + std::shared_ptr op = players[sendAllPlayerInfoIn]; + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(op->name, true, op->latency) ) ); + if (op->connection->getNetworkPlayer()) { + broadcastAll( + std::shared_ptr(new PlayerInfoPacket(op))); + } + } - EnterCriticalSection(&m_closePlayersCS); - while(!m_smallIdsToClose.empty()) - { - std::uint8_t smallId = m_smallIdsToClose.front(); - m_smallIdsToClose.pop_front(); + EnterCriticalSection(&m_closePlayersCS); + while (!m_smallIdsToClose.empty()) { + std::uint8_t smallId = m_smallIdsToClose.front(); + m_smallIdsToClose.pop_front(); - std::shared_ptr player = nullptr; + std::shared_ptr player = nullptr; - for(unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr p = players.at(i); - // 4J Stu - May be being a bit overprotective with all the NULL checks, but adding late in TU7 so want to be safe - if (p != NULL && p->connection != NULL && p->connection->connection != NULL && p->connection->connection->getSocket() != NULL && p->connection->connection->getSocket()->getSmallId() == smallId ) - { - player = p; - break; - } - } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr p = players.at(i); + // 4J Stu - May be being a bit overprotective with all the NULL + // checks, but adding late in TU7 so want to be safe + if (p != NULL && p->connection != NULL && + p->connection->connection != NULL && + p->connection->connection->getSocket() != NULL && + p->connection->connection->getSocket()->getSmallId() == + smallId) { + player = p; + break; + } + } - if (player != NULL) - { - player->connection->disconnect( DisconnectPacket::eDisconnect_Closed ); - } - } - LeaveCriticalSection(&m_closePlayersCS); + if (player != NULL) { + player->connection->disconnect( + DisconnectPacket::eDisconnect_Closed); + } + } + LeaveCriticalSection(&m_closePlayersCS); - EnterCriticalSection(&m_kickPlayersCS); - while(!m_smallIdsToKick.empty()) - { - std::uint8_t smallId = m_smallIdsToKick.front(); - m_smallIdsToKick.pop_front(); - INetworkPlayer *selectedPlayer = g_NetworkManager.GetPlayerBySmallId(smallId); - if( selectedPlayer != NULL ) - { - if( selectedPlayer->IsLocal() != TRUE ) - { -//#ifdef _XBOX - PlayerUID xuid = selectedPlayer->GetUID(); - // Kick this player from the game - std::shared_ptr player = nullptr; + EnterCriticalSection(&m_kickPlayersCS); + while (!m_smallIdsToKick.empty()) { + std::uint8_t smallId = m_smallIdsToKick.front(); + m_smallIdsToKick.pop_front(); + INetworkPlayer* selectedPlayer = + g_NetworkManager.GetPlayerBySmallId(smallId); + if (selectedPlayer != NULL) { + if (selectedPlayer->IsLocal() != TRUE) { + // #ifdef _XBOX + PlayerUID xuid = selectedPlayer->GetUID(); + // Kick this player from the game + std::shared_ptr player = nullptr; - for(unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr p = players.at(i); - PlayerUID playersXuid = p->getOnlineXuid(); - if (p != NULL && ProfileManager.AreXUIDSEqual(playersXuid, xuid ) ) - { - player = p; - break; - } - } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr p = players.at(i); + PlayerUID playersXuid = p->getOnlineXuid(); + if (p != NULL && + ProfileManager.AreXUIDSEqual(playersXuid, xuid)) { + player = p; + break; + } + } - if (player != NULL) - { - m_bannedXuids.push_back( player->getOnlineXuid() ); - // 4J Stu - If we have kicked a player, make sure that they have no privileges if they later try to join the world when trust players is off - player->enableAllPlayerPrivileges( false ); - player->connection->setWasKicked(); - player->connection->send( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Kicked) )); - } -//#endif - } - } - } - LeaveCriticalSection(&m_kickPlayersCS); + if (player != NULL) { + m_bannedXuids.push_back(player->getOnlineXuid()); + // 4J Stu - If we have kicked a player, make sure that they + // have no privileges if they later try to join the world + // when trust players is off + player->enableAllPlayerPrivileges(false); + player->connection->setWasKicked(); + player->connection->send( + std::shared_ptr(new DisconnectPacket( + DisconnectPacket::eDisconnect_Kicked))); + } + // #endif + } + } + } + LeaveCriticalSection(&m_kickPlayersCS); - // Check our receiving players, and if they are dead see if we can replace them - for(unsigned int dim = 0; dim < 2; ++dim) - { - for(unsigned int i = 0; i < receiveAllPlayers[dim].size(); ++i) - { - std::shared_ptr currentPlayer = receiveAllPlayers[dim][i]; - if(currentPlayer->removed) - { - std::shared_ptr newPlayer = findAlivePlayerOnSystem(currentPlayer); - if(newPlayer != NULL) - { - receiveAllPlayers[dim][i] = newPlayer; - app.DebugPrintf("Replacing primary player %ls with %ls in dimension %d\n", currentPlayer->name.c_str(), newPlayer->name.c_str(), dim); - } - } - } - } + // Check our receiving players, and if they are dead see if we can replace + // them + for (unsigned int dim = 0; dim < 2; ++dim) { + for (unsigned int i = 0; i < receiveAllPlayers[dim].size(); ++i) { + std::shared_ptr currentPlayer = + receiveAllPlayers[dim][i]; + if (currentPlayer->removed) { + std::shared_ptr newPlayer = + findAlivePlayerOnSystem(currentPlayer); + if (newPlayer != NULL) { + receiveAllPlayers[dim][i] = newPlayer; + app.DebugPrintf( + "Replacing primary player %ls with %ls in dimension " + "%d\n", + currentPlayer->name.c_str(), newPlayer->name.c_str(), + dim); + } + } + } + } } -bool PlayerList::isTrackingTile(int x, int y, int z, int dimension) -{ - return server->getLevel(dimension)->getChunkMap()->isTrackingTile(x, y, z); +bool PlayerList::isTrackingTile(int x, int y, int z, int dimension) { + return server->getLevel(dimension)->getChunkMap()->isTrackingTile(x, y, z); } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerList::prioritiseTileChanges(int x, int y, int z, int dimension) -{ - server->getLevel(dimension)->getChunkMap()->prioritiseTileChanges(x, y, z); +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerList::prioritiseTileChanges(int x, int y, int z, int dimension) { + server->getLevel(dimension)->getChunkMap()->prioritiseTileChanges(x, y, z); } -void PlayerList::broadcastAll(std::shared_ptr packet) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastAll(std::shared_ptr packet) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; player->connection->send(packet); } } -void PlayerList::broadcastAll(std::shared_ptr packet, int dimension) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastAll(std::shared_ptr packet, int dimension) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; if (player->dimension == dimension) player->connection->send(packet); } } -std::wstring PlayerList::getPlayerNames() -{ +std::wstring PlayerList::getPlayerNames() { std::wstring msg; - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { if (i > 0) msg += L", "; msg += players[i]->name; } return msg; } -bool PlayerList::isWhiteListed(const std::wstring& name) -{ - return true; -} +bool PlayerList::isWhiteListed(const std::wstring& name) { return true; } -bool PlayerList::isOp(const std::wstring& name) -{ - return false; -} +bool PlayerList::isOp(const std::wstring& name) { return false; } -bool PlayerList::isOp(std::shared_ptr player) -{ - bool cheatsEnabled = app.GetGameHostOption(eGameHostOption_CheatsEnabled); +bool PlayerList::isOp(std::shared_ptr player) { + bool cheatsEnabled = app.GetGameHostOption(eGameHostOption_CheatsEnabled); #ifdef _DEBUG_MENUS_ENABLED - cheatsEnabled = cheatsEnabled || app.GetUseDPadForDebug(); + cheatsEnabled = cheatsEnabled || app.GetUseDPadForDebug(); #endif - INetworkPlayer *networkPlayer = player->connection->getNetworkPlayer(); - bool isOp = cheatsEnabled && (player->isModerator() || (networkPlayer != NULL && networkPlayer->IsHost())); - return isOp; + INetworkPlayer* networkPlayer = player->connection->getNetworkPlayer(); + bool isOp = + cheatsEnabled && (player->isModerator() || + (networkPlayer != NULL && networkPlayer->IsHost())); + return isOp; } -std::shared_ptr PlayerList::getPlayer(const std::wstring& name) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +std::shared_ptr PlayerList::getPlayer(const std::wstring& name) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (p->name == name) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway - { + if (p->name == + name) // 4J - used to be case insensitive (using equalsIgnoreCase) + // - imagine we'll be shifting to XUIDs anyway + { return p; } } @@ -1004,83 +1081,77 @@ std::shared_ptr PlayerList::getPlayer(const std::wstring& name) } // 4J Added -std::shared_ptr PlayerList::getPlayer(PlayerUID uid) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +std::shared_ptr PlayerList::getPlayer(PlayerUID uid) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (p->getXuid() == uid || p->getOnlineXuid() == uid) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway - { + if (p->getXuid() == uid || + p->getOnlineXuid() == uid) // 4J - used to be case insensitive + // (using equalsIgnoreCase) - imagine + // we'll be shifting to XUIDs anyway + { return p; } } return nullptr; } -void PlayerList::sendMessage(const std::wstring& name, const std::wstring& message) -{ +void PlayerList::sendMessage(const std::wstring& name, + const std::wstring& message) { std::shared_ptr player = getPlayer(name); - if (player != NULL) - { - player->connection->send( std::shared_ptr( new ChatPacket(message) ) ); + if (player != NULL) { + player->connection->send( + std::shared_ptr(new ChatPacket(message))); } } -void PlayerList::broadcast(double x, double y, double z, double range, int dimension, std::shared_ptr packet) -{ - broadcast(nullptr, x, y, z, range, dimension, packet); +void PlayerList::broadcast(double x, double y, double z, double range, + int dimension, std::shared_ptr packet) { + broadcast(nullptr, x, y, z, range, dimension, packet); } -void PlayerList::broadcast(std::shared_ptr except, double x, double y, double z, double range, int dimension, std::shared_ptr packet) -{ - // 4J - altered so that we don't send to the same machine more than once. Add the source player to the machines we have "sent" to as it doesn't need to go to that - // machine either - std::vector< std::shared_ptr > sentTo; - if( except != NULL ) - { - sentTo.push_back(std::dynamic_pointer_cast(except)); - } +void PlayerList::broadcast(std::shared_ptr except, double x, double y, + double z, double range, int dimension, + std::shared_ptr packet) { + // 4J - altered so that we don't send to the same machine more than once. + // Add the source player to the machines we have "sent" to as it doesn't + // need to go to that machine either + std::vector > sentTo; + if (except != NULL) { + sentTo.push_back(std::dynamic_pointer_cast(except)); + } - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; if (p == except) continue; if (p->dimension != dimension) continue; - // 4J - don't send to the same machine more than once - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = p->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( dontSend ) - { - continue; - } - + // 4J - don't send to the same machine more than once + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = p->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (dontSend) { + continue; + } double xd = x - p->x; double yd = y - p->y; double zd = z - p->z; - if (xd * xd + yd * yd + zd * zd < range * range) - { -#if 0 // _DEBUG + if (xd * xd + yd * yd + zd * zd < range * range) { +#if 0 // _DEBUG std::shared_ptr SoundPacket= std::dynamic_pointer_cast(packet); if(SoundPacket) @@ -1092,364 +1163,343 @@ void PlayerList::broadcast(std::shared_ptr except, double x, double y, d } #endif p->connection->send(packet); - sentTo.push_back( p ); + sentTo.push_back(p); } } - } -void PlayerList::broadcastToAllOps(const std::wstring& message) -{ - std::shared_ptr chatPacket = std::shared_ptr( new ChatPacket(message) ); - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastToAllOps(const std::wstring& message) { + std::shared_ptr chatPacket = + std::shared_ptr(new ChatPacket(message)); + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (isOp(p->name)) - { + if (isOp(p->name)) { p->connection->send(chatPacket); } } } -bool PlayerList::sendTo(const std::wstring& name, std::shared_ptr packet) -{ +bool PlayerList::sendTo(const std::wstring& name, + std::shared_ptr packet) { std::shared_ptr player = getPlayer(name); - if (player != NULL) - { + if (player != NULL) { player->connection->send(packet); return true; } return false; } -void PlayerList::saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps /*= false*/) -{ - if(progressListener != NULL) progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); - // 4J - playerIo can be NULL if we have have to exit a game really early on due to network failure - if(playerIo) - { - playerIo->saveAllCachedData(); - for (unsigned int i = 0; i < players.size(); i++) - { - playerIo->save(players[i]); - - //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map - if(bDeleteGuestMaps && players[i]->isGuest()) playerIo->deleteMapFilesForPlayer(players[i]); +void PlayerList::saveAll(ProgressListener* progressListener, + bool bDeleteGuestMaps /*= false*/) { + if (progressListener != NULL) + progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); + // 4J - playerIo can be NULL if we have have to exit a game really early on + // due to network failure + if (playerIo) { + playerIo->saveAllCachedData(); + for (unsigned int i = 0; i < players.size(); i++) { + playerIo->save(players[i]); - if(progressListener != NULL) progressListener->progressStagePercentage((i * 100)/ ((int)players.size())); - } - playerIo->clearOldPlayerFiles(); - playerIo->saveMapIdLookup(); - } -} + // 4J Stu - We don't want to save the map data for guests, so when + // we are sure that the player is gone delete the map + if (bDeleteGuestMaps && players[i]->isGuest()) + playerIo->deleteMapFilesForPlayer(players[i]); -void PlayerList::whiteList(const std::wstring& playerName) -{ -} - -void PlayerList::blackList(const std::wstring& playerName) -{ -} - -void PlayerList::reloadWhitelist() -{ -} - -void PlayerList::sendLevelInfo(std::shared_ptr player, ServerLevel *level) -{ - player->connection->send( std::shared_ptr( new SetTimePacket(level->getTime()) ) ); - if (level->isRaining()) - { - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + if (progressListener != NULL) + progressListener->progressStagePercentage( + (i * 100) / ((int)players.size())); + } + playerIo->clearOldPlayerFiles(); + playerIo->saveMapIdLookup(); } - else - { - // 4J Stu - Fix for #44836 - Customer Encountered: Out of Sync Weather [A-10] - // If it was raining when the player left the level, and is now not raining we need to make sure that state is updated - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); - } - - // send the stronghold position if there is one - if((level->dimension->id==0) && level->getLevelData()->getHasStronghold()) - { - player->connection->send( std::shared_ptr( new XZPacket(XZPacket::STRONGHOLD,level->getLevelData()->getXStronghold(),level->getLevelData()->getZStronghold()) ) ); - } } -void PlayerList::sendAllPlayerInfo(std::shared_ptr player) -{ +void PlayerList::whiteList(const std::wstring& playerName) {} + +void PlayerList::blackList(const std::wstring& playerName) {} + +void PlayerList::reloadWhitelist() {} + +void PlayerList::sendLevelInfo(std::shared_ptr player, + ServerLevel* level) { + player->connection->send( + std::shared_ptr(new SetTimePacket(level->getTime()))); + if (level->isRaining()) { + player->connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_RAINING, 0))); + } else { + // 4J Stu - Fix for #44836 - Customer Encountered: Out of Sync Weather + // [A-10] If it was raining when the player left the level, and is now + // not raining we need to make sure that state is updated + player->connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_RAINING, 0))); + } + + // send the stronghold position if there is one + if ((level->dimension->id == 0) && + level->getLevelData()->getHasStronghold()) { + player->connection->send(std::shared_ptr(new XZPacket( + XZPacket::STRONGHOLD, level->getLevelData()->getXStronghold(), + level->getLevelData()->getZStronghold()))); + } +} + +void PlayerList::sendAllPlayerInfo(std::shared_ptr player) { player->refreshContainer(player->inventoryMenu); player->resetSentInfo(); } -int PlayerList::getPlayerCount() -{ - return (int)players.size(); +int PlayerList::getPlayerCount() { return (int)players.size(); } + +int PlayerList::getPlayerCount(ServerLevel* level) { + int count = 0; + + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + if ((*it)->level == level) ++count; + } + + return count; } -int PlayerList::getPlayerCount(ServerLevel *level) -{ - int count = 0; +int PlayerList::getMaxPlayers() { return maxPlayers; } - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - if( (*it)->level == level ) ++count; - } +MinecraftServer* PlayerList::getServer() { return server; } - return count; +int PlayerList::getViewDistance() { return viewDistance; } + +void PlayerList::setOverrideGameMode(GameType* gameMode) { + this->overrideGameMode = gameMode; } -int PlayerList::getMaxPlayers() -{ - return maxPlayers; +void PlayerList::updatePlayerGameMode(std::shared_ptr newPlayer, + std::shared_ptr oldPlayer, + Level* level) { + // reset the player's game mode (first pick from old, then copy level if + // necessary) + if (oldPlayer != NULL) { + newPlayer->gameMode->setGameModeForPlayer( + oldPlayer->gameMode->getGameModeForPlayer()); + } else if (overrideGameMode != NULL) { + newPlayer->gameMode->setGameModeForPlayer(overrideGameMode); + } + newPlayer->gameMode->updateGameMode(level->getLevelData()->getGameType()); } -MinecraftServer *PlayerList::getServer() -{ - return server; +void PlayerList::setAllowCheatsForAllPlayers(bool allowCommands) { + this->allowCheatsForAllPlayers = allowCommands; } -int PlayerList::getViewDistance() -{ - return viewDistance; +std::shared_ptr PlayerList::findAlivePlayerOnSystem( + std::shared_ptr player) { + int dimIndex, playerDim; + dimIndex = playerDim = player->dimension; + if (dimIndex == -1) + dimIndex = 1; + else if (dimIndex == 1) + dimIndex = 2; + + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL) { + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; + + INetworkPlayer* otherPlayer = + newPlayer->connection->getNetworkPlayer(); + + if (!newPlayer->removed && newPlayer != player && + newPlayer->dimension == playerDim && otherPlayer != NULL && + otherPlayer->IsSameSystem(thisPlayer)) { + return newPlayer; + } + } + } + + return nullptr; } -void PlayerList::setOverrideGameMode(GameType *gameMode) -{ - this->overrideGameMode = gameMode; -} - -void PlayerList::updatePlayerGameMode(std::shared_ptr newPlayer, std::shared_ptr oldPlayer, Level *level) -{ - - // reset the player's game mode (first pick from old, then copy level if - // necessary) - if (oldPlayer != NULL) - { - newPlayer->gameMode->setGameModeForPlayer(oldPlayer->gameMode->getGameModeForPlayer()); - } - else if (overrideGameMode != NULL) - { - newPlayer->gameMode->setGameModeForPlayer(overrideGameMode); - } - newPlayer->gameMode->updateGameMode(level->getLevelData()->getGameType()); -} - -void PlayerList::setAllowCheatsForAllPlayers(bool allowCommands) -{ - this->allowCheatsForAllPlayers = allowCommands; -} - -std::shared_ptr PlayerList::findAlivePlayerOnSystem(std::shared_ptr player) -{ - int dimIndex, playerDim; - dimIndex = playerDim = player->dimension; - if( dimIndex == -1 ) dimIndex = 1; - else if( dimIndex == 1) dimIndex = 2; - - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) - { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; - - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); - - if( !newPlayer->removed && - newPlayer != player && - newPlayer->dimension == playerDim && - otherPlayer != NULL && - otherPlayer->IsSameSystem( thisPlayer ) - ) - { - return newPlayer; - } - } - } - - return nullptr; -} - -void PlayerList::removePlayerFromReceiving(std::shared_ptr player, bool usePlayerDimension /*= true*/, int dimension /*= 0*/) -{ - int dimIndex, playerDim; - dimIndex = playerDim = usePlayerDimension ? player->dimension : dimension; - if( dimIndex == -1 ) dimIndex = 1; - else if( dimIndex == 1) dimIndex = 2; +void PlayerList::removePlayerFromReceiving(std::shared_ptr player, + bool usePlayerDimension /*= true*/, + int dimension /*= 0*/) { + int dimIndex, playerDim; + dimIndex = playerDim = usePlayerDimension ? player->dimension : dimension; + if (dimIndex == -1) + dimIndex = 1; + else if (dimIndex == 1) + dimIndex = 2; #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Requesting remove player %ls as primary in dimension %d\n", player->name.c_str(), dimIndex); + app.DebugPrintf("Requesting remove player %ls as primary in dimension %d\n", + player->name.c_str(), dimIndex); #endif - bool playerRemoved = false; + bool playerRemoved = false; - AUTO_VAR(it, find( receiveAllPlayers[dimIndex].begin(), receiveAllPlayers[dimIndex].end(), player)); - if( it != receiveAllPlayers[dimIndex].end() ) - { + AUTO_VAR(it, find(receiveAllPlayers[dimIndex].begin(), + receiveAllPlayers[dimIndex].end(), player)); + if (it != receiveAllPlayers[dimIndex].end()) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Removing player %ls as primary in dimension %d\n", player->name.c_str(), dimIndex); + app.DebugPrintf( + "Remove: Removing player %ls as primary in dimension %d\n", + player->name.c_str(), dimIndex); #endif - receiveAllPlayers[dimIndex].erase(it); - playerRemoved = true; - } + receiveAllPlayers[dimIndex].erase(it); + playerRemoved = true; + } - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL && playerRemoved ) - { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL && playerRemoved) { + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); + INetworkPlayer* otherPlayer = + newPlayer->connection->getNetworkPlayer(); - if( newPlayer != player && - newPlayer->dimension == playerDim && - otherPlayer != NULL && - otherPlayer->IsSameSystem( thisPlayer ) - ) - { + if (newPlayer != player && newPlayer->dimension == playerDim && + otherPlayer != NULL && otherPlayer->IsSameSystem(thisPlayer)) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Adding player %ls as primary in dimension %d\n", newPlayer->name.c_str(), dimIndex); + app.DebugPrintf( + "Remove: Adding player %ls as primary in dimension %d\n", + newPlayer->name.c_str(), dimIndex); #endif - receiveAllPlayers[dimIndex].push_back( newPlayer ); - break; - } - } - } - else if( thisPlayer == NULL ) - { + receiveAllPlayers[dimIndex].push_back(newPlayer); + break; + } + } + } else if (thisPlayer == NULL) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Qnet player for %ls was NULL so re-checking all players\n", player->name.c_str() ); + app.DebugPrintf( + "Remove: Qnet player for %ls was NULL so re-checking all players\n", + player->name.c_str()); #endif - // 4J Stu - Something went wrong, or possibly the QNet player left before we got here. - // Re-check all active players and make sure they have someone on their system to receive all packets - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; - INetworkPlayer *checkingPlayer = newPlayer->connection->getNetworkPlayer(); + // 4J Stu - Something went wrong, or possibly the QNet player left + // before we got here. Re-check all active players and make sure they + // have someone on their system to receive all packets + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; + INetworkPlayer* checkingPlayer = + newPlayer->connection->getNetworkPlayer(); - if( checkingPlayer != NULL ) - { - int newPlayerDim = 0; - if( newPlayer->dimension == -1 ) newPlayerDim = 1; - else if( newPlayer->dimension == 1) newPlayerDim = 2; - bool foundPrimary = false; - for(AUTO_VAR(it, receiveAllPlayers[newPlayerDim].begin()); it != receiveAllPlayers[newPlayerDim].end(); ++it) - { - std::shared_ptr primaryPlayer = *it; - INetworkPlayer *primPlayer = primaryPlayer->connection->getNetworkPlayer(); - if(primPlayer != NULL && checkingPlayer->IsSameSystem( primPlayer ) ) - { - foundPrimary = true; - break; - } - } - if(!foundPrimary) - { + if (checkingPlayer != NULL) { + int newPlayerDim = 0; + if (newPlayer->dimension == -1) + newPlayerDim = 1; + else if (newPlayer->dimension == 1) + newPlayerDim = 2; + bool foundPrimary = false; + for (AUTO_VAR(it, receiveAllPlayers[newPlayerDim].begin()); + it != receiveAllPlayers[newPlayerDim].end(); ++it) { + std::shared_ptr primaryPlayer = *it; + INetworkPlayer* primPlayer = + primaryPlayer->connection->getNetworkPlayer(); + if (primPlayer != NULL && + checkingPlayer->IsSameSystem(primPlayer)) { + foundPrimary = true; + break; + } + } + if (!foundPrimary) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Adding player %ls as primary in dimension %d\n", newPlayer->name.c_str(), newPlayerDim); + app.DebugPrintf( + "Remove: Adding player %ls as primary in dimension " + "%d\n", + newPlayer->name.c_str(), newPlayerDim); #endif - receiveAllPlayers[newPlayerDim].push_back( newPlayer ); - } - } - } - } + receiveAllPlayers[newPlayerDim].push_back(newPlayer); + } + } + } + } } -void PlayerList::addPlayerToReceiving(std::shared_ptr player) -{ - int playerDim = 0; - if( player->dimension == -1 ) playerDim = 1; - else if( player->dimension == 1) playerDim = 2; +void PlayerList::addPlayerToReceiving(std::shared_ptr player) { + int playerDim = 0; + if (player->dimension == -1) + playerDim = 1; + else if (player->dimension == 1) + playerDim = 2; #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Requesting add player %ls as primary in dimension %d\n", player->name.c_str(), playerDim); + app.DebugPrintf("Requesting add player %ls as primary in dimension %d\n", + player->name.c_str(), playerDim); #endif - bool shouldAddPlayer = true; + bool shouldAddPlayer = true; - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { + if (thisPlayer == NULL) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Add: Qnet player for player %ls is NULL so not adding them\n", player->name.c_str() ); + app.DebugPrintf( + "Add: Qnet player for player %ls is NULL so not adding them\n", + player->name.c_str()); #endif - shouldAddPlayer = false; - } - else - { - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) - { - std::shared_ptr oldPlayer = *it; - INetworkPlayer *checkingPlayer = oldPlayer->connection->getNetworkPlayer(); - if(checkingPlayer != NULL && checkingPlayer->IsSameSystem( thisPlayer ) ) - { - shouldAddPlayer = false; - break; - } - } - } - - if( shouldAddPlayer ) - { + shouldAddPlayer = false; + } else { + for (AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); + it != receiveAllPlayers[playerDim].end(); ++it) { + std::shared_ptr oldPlayer = *it; + INetworkPlayer* checkingPlayer = + oldPlayer->connection->getNetworkPlayer(); + if (checkingPlayer != NULL && + checkingPlayer->IsSameSystem(thisPlayer)) { + shouldAddPlayer = false; + break; + } + } + } + + if (shouldAddPlayer) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Add: Adding player %ls as primary in dimension %d\n", player->name.c_str(), playerDim); + app.DebugPrintf("Add: Adding player %ls as primary in dimension %d\n", + player->name.c_str(), playerDim); #endif - receiveAllPlayers[playerDim].push_back( player ); - } + receiveAllPlayers[playerDim].push_back(player); + } } -bool PlayerList::canReceiveAllPackets(std::shared_ptr player) -{ - int playerDim = 0; - if( player->dimension == -1 ) playerDim = 1; - else if( player->dimension == 1) playerDim = 2; - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) - { - std::shared_ptr newPlayer = *it; - if(newPlayer == player) - { - return true; - } - } - return false; +bool PlayerList::canReceiveAllPackets(std::shared_ptr player) { + int playerDim = 0; + if (player->dimension == -1) + playerDim = 1; + else if (player->dimension == 1) + playerDim = 2; + for (AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); + it != receiveAllPlayers[playerDim].end(); ++it) { + std::shared_ptr newPlayer = *it; + if (newPlayer == player) { + return true; + } + } + return false; } -void PlayerList::kickPlayerByShortId(std::uint8_t networkSmallId) -{ - EnterCriticalSection(&m_kickPlayersCS); - m_smallIdsToKick.push_back(networkSmallId); - LeaveCriticalSection(&m_kickPlayersCS); +void PlayerList::kickPlayerByShortId(std::uint8_t networkSmallId) { + EnterCriticalSection(&m_kickPlayersCS); + m_smallIdsToKick.push_back(networkSmallId); + LeaveCriticalSection(&m_kickPlayersCS); } -void PlayerList::closePlayerConnectionBySmallId(std::uint8_t networkSmallId) -{ - EnterCriticalSection(&m_closePlayersCS); - m_smallIdsToClose.push_back(networkSmallId); - LeaveCriticalSection(&m_closePlayersCS); +void PlayerList::closePlayerConnectionBySmallId(std::uint8_t networkSmallId) { + EnterCriticalSection(&m_closePlayersCS); + m_smallIdsToClose.push_back(networkSmallId); + LeaveCriticalSection(&m_closePlayersCS); } -bool PlayerList::isXuidBanned(PlayerUID xuid) -{ - if( xuid == INVALID_XUID ) return false; +bool PlayerList::isXuidBanned(PlayerUID xuid) { + if (xuid == INVALID_XUID) return false; - bool banned = false; + bool banned = false; - for( AUTO_VAR(it, m_bannedXuids.begin()); it != m_bannedXuids.end(); ++it ) - { - if( ProfileManager.AreXUIDSEqual( xuid, *it ) ) - { - banned = true; - break; - } - } + for (AUTO_VAR(it, m_bannedXuids.begin()); it != m_bannedXuids.end(); ++it) { + if (ProfileManager.AreXUIDSEqual(xuid, *it)) { + banned = true; + break; + } + } - return banned; + return banned; } // AP added for Vita so the range can be increased once the level starts -void PlayerList::setViewDistance(int newViewDistance) -{ - viewDistance = newViewDistance; +void PlayerList::setViewDistance(int newViewDistance) { + viewDistance = newViewDistance; } diff --git a/Minecraft.Client/Network/PlayerList.h b/Minecraft.Client/Network/PlayerList.h index 50a00ea91..d810bcebe 100644 --- a/Minecraft.Client/Network/PlayerList.h +++ b/Minecraft.Client/Network/PlayerList.h @@ -15,114 +15,136 @@ class ProgressListener; class GameType; class LoginPacket; - - -class PlayerList -{ +class PlayerList { private: - static const int SEND_PLAYER_INFO_INTERVAL = 20 * 10; // 4J - brought forward from 1.2.3 -// public static Logger logger = Logger.getLogger("Minecraft"); + static const int SEND_PLAYER_INFO_INTERVAL = + 20 * 10; // 4J - brought forward from 1.2.3 + // public static Logger logger = Logger.getLogger("Minecraft"); public: - std::vector > players; + std::vector > players; private: - MinecraftServer *server; + MinecraftServer* server; unsigned int maxPlayers; - // 4J Added - std::vector m_bannedXuids; - std::deque m_smallIdsToKick; - CRITICAL_SECTION m_kickPlayersCS; - std::deque m_smallIdsToClose; - CRITICAL_SECTION m_closePlayersCS; -/* 4J - removed - Set bans = new HashSet(); - Set ipBans = new HashSet(); - Set ops = new HashSet(); - Set whitelist = new HashSet(); - File banFile, ipBanFile, opFile, whiteListFile; - */ - PlayerIO *playerIo; + // 4J Added + std::vector m_bannedXuids; + std::deque m_smallIdsToKick; + CRITICAL_SECTION m_kickPlayersCS; + std::deque m_smallIdsToClose; + CRITICAL_SECTION m_closePlayersCS; + /* 4J - removed + Set bans = new HashSet(); + Set ipBans = new HashSet(); + Set ops = new HashSet(); + Set whitelist = new HashSet(); + File banFile, ipBanFile, opFile, whiteListFile; + */ + PlayerIO* playerIo; bool doWhiteList; - GameType *overrideGameMode; - bool allowCheatsForAllPlayers; - int viewDistance; + GameType* overrideGameMode; + bool allowCheatsForAllPlayers; + int viewDistance; - int sendAllPlayerInfoIn; + int sendAllPlayerInfoIn; + + // 4J Added to maintain which players in which dimensions can receive all + // packet types + std::vector > receiveAllPlayers[3]; - // 4J Added to maintain which players in which dimensions can receive all packet types - std::vector > receiveAllPlayers[3]; private: - std::shared_ptr findAlivePlayerOnSystem(std::shared_ptr currentPlayer); + std::shared_ptr findAlivePlayerOnSystem( + std::shared_ptr currentPlayer); public: - void removePlayerFromReceiving(std::shared_ptr player, bool usePlayerDimension = true, int dimension = 0); - void addPlayerToReceiving(std::shared_ptr player); - bool canReceiveAllPackets(std::shared_ptr player); + void removePlayerFromReceiving(std::shared_ptr player, + bool usePlayerDimension = true, + int dimension = 0); + void addPlayerToReceiving(std::shared_ptr player); + bool canReceiveAllPackets(std::shared_ptr player); public: - PlayerList(MinecraftServer *server); - ~PlayerList(); - void placeNewPlayer(Connection *connection, std::shared_ptr player, std::shared_ptr packet); + PlayerList(MinecraftServer* server); + ~PlayerList(); + void placeNewPlayer(Connection* connection, + std::shared_ptr player, + std::shared_ptr packet); void setLevel(ServerLevelArray levels); - void changeDimension(std::shared_ptr player, ServerLevel *from); + void changeDimension(std::shared_ptr player, + ServerLevel* from); int getMaxRange(); - bool load(std::shared_ptr player); // 4J Changed return val to bool to check if new player or loaded player + bool load(std::shared_ptr + player); // 4J Changed return val to bool to check if new + // player or loaded player protected: - void save(std::shared_ptr player); + void save(std::shared_ptr player); + public: - void validatePlayerSpawnPosition(std::shared_ptr player); // 4J Added + void validatePlayerSpawnPosition( + std::shared_ptr player); // 4J Added void add(std::shared_ptr player); void move(std::shared_ptr player); void remove(std::shared_ptr player); - std::shared_ptr getPlayerForLogin(PendingConnection *pendingConnection, const std::wstring& userName, PlayerUID xuid, PlayerUID OnlineXuid); - std::shared_ptr respawn(std::shared_ptr serverPlayer, int targetDimension, bool keepAllPlayerData); - void toggleDimension(std::shared_ptr player, int targetDimension); + std::shared_ptr getPlayerForLogin( + PendingConnection* pendingConnection, const std::wstring& userName, + PlayerUID xuid, PlayerUID OnlineXuid); + std::shared_ptr respawn( + std::shared_ptr serverPlayer, int targetDimension, + bool keepAllPlayerData); + void toggleDimension(std::shared_ptr player, + int targetDimension); void tick(); - bool isTrackingTile(int x, int y, int z, int dimension); // 4J added - void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added + bool isTrackingTile(int x, int y, int z, int dimension); // 4J added + void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added void broadcastAll(std::shared_ptr packet); void broadcastAll(std::shared_ptr packet, int dimension); std::wstring getPlayerNames(); public: - bool isWhiteListed(const std::wstring& name); + bool isWhiteListed(const std::wstring& name); bool isOp(const std::wstring& name); - bool isOp(std::shared_ptr player); // 4J Added + bool isOp(std::shared_ptr player); // 4J Added std::shared_ptr getPlayer(const std::wstring& name); - std::shared_ptr getPlayer(PlayerUID uid); + std::shared_ptr getPlayer(PlayerUID uid); void sendMessage(const std::wstring& name, const std::wstring& message); - void broadcast(double x, double y, double z, double range, int dimension, std::shared_ptr packet); - void broadcast(std::shared_ptr except, double x, double y, double z, double range, int dimension, std::shared_ptr packet); + void broadcast(double x, double y, double z, double range, int dimension, + std::shared_ptr packet); + void broadcast(std::shared_ptr except, double x, double y, double z, + double range, int dimension, std::shared_ptr packet); void broadcastToAllOps(const std::wstring& message); bool sendTo(const std::wstring& name, std::shared_ptr packet); - // 4J Added ProgressListener *progressListener param and bDeleteGuestMaps param - void saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps = false); + // 4J Added ProgressListener *progressListener param and bDeleteGuestMaps + // param + void saveAll(ProgressListener* progressListener, + bool bDeleteGuestMaps = false); void whiteList(const std::wstring& playerName); void blackList(const std::wstring& playerName); -// Set getWhiteList(); / 4J removed + // Set getWhiteList(); / 4J removed void reloadWhitelist(); - void sendLevelInfo(std::shared_ptr player, ServerLevel *level); + void sendLevelInfo(std::shared_ptr player, + ServerLevel* level); void sendAllPlayerInfo(std::shared_ptr player); - int getPlayerCount(); - int getPlayerCount(ServerLevel *level); // 4J Added - int getMaxPlayers(); - MinecraftServer *getServer(); - int getViewDistance(); - void setOverrideGameMode(GameType *gameMode); + int getPlayerCount(); + int getPlayerCount(ServerLevel* level); // 4J Added + int getMaxPlayers(); + MinecraftServer* getServer(); + int getViewDistance(); + void setOverrideGameMode(GameType* gameMode); private: - void updatePlayerGameMode(std::shared_ptr newPlayer, std::shared_ptr oldPlayer, Level *level); + void updatePlayerGameMode(std::shared_ptr newPlayer, + std::shared_ptr oldPlayer, + Level* level); public: - void setAllowCheatsForAllPlayers(bool allowCommands); + void setAllowCheatsForAllPlayers(bool allowCommands); - // 4J Added - void kickPlayerByShortId(std::uint8_t networkSmallId); - void closePlayerConnectionBySmallId(std::uint8_t networkSmallId); - bool isXuidBanned(PlayerUID xuid); - // AP added for Vita so the range can be increased once the level starts - void setViewDistance(int newViewDistance); + // 4J Added + void kickPlayerByShortId(std::uint8_t networkSmallId); + void closePlayerConnectionBySmallId(std::uint8_t networkSmallId); + bool isXuidBanned(PlayerUID xuid); + // AP added for Vita so the range can be increased once the level starts + void setViewDistance(int newViewDistance); }; diff --git a/Minecraft.Client/Network/ServerChunkCache.cpp b/Minecraft.Client/Network/ServerChunkCache.cpp index e05c890b1..09d4f6ce3 100644 --- a/Minecraft.Client/Network/ServerChunkCache.cpp +++ b/Minecraft.Client/Network/ServerChunkCache.cpp @@ -12,956 +12,1014 @@ #include "../../Minecraft.World/IO/Streams/Compression.h" #include "../../Minecraft.World/Level/Storage/OldChunkStorage.h" -ServerChunkCache::ServerChunkCache(ServerLevel *level, ChunkStorage *storage, ChunkSource *source) -{ - XZSIZE = source->m_XZSize; // 4J Added - XZOFFSET = XZSIZE/2; // 4J Added +ServerChunkCache::ServerChunkCache(ServerLevel* level, ChunkStorage* storage, + ChunkSource* source) { + XZSIZE = source->m_XZSize; // 4J Added + XZOFFSET = XZSIZE / 2; // 4J Added - autoCreate = false; // 4J added - - emptyChunk = new EmptyLevelChunk(level, byteArray( Level::CHUNK_TILE_COUNT ), 0, 0); + autoCreate = false; // 4J added + + emptyChunk = + new EmptyLevelChunk(level, byteArray(Level::CHUNK_TILE_COUNT), 0, 0); this->level = level; this->storage = storage; this->source = source; - this->m_XZSize = source->m_XZSize; + this->m_XZSize = source->m_XZSize; - this->cache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); + this->cache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); #ifdef _LARGE_WORLDS - m_unloadedCache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(m_unloadedCache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); + m_unloadedCache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(m_unloadedCache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); #endif - InitializeCriticalSectionAndSpinCount(&m_csLoadCreate,4000); + InitializeCriticalSectionAndSpinCount(&m_csLoadCreate, 4000); } // 4J-PB added -ServerChunkCache::~ServerChunkCache() -{ - delete emptyChunk; - delete cache; - delete source; +ServerChunkCache::~ServerChunkCache() { + delete emptyChunk; + delete cache; + delete source; #ifdef _LARGE_WORLDS - for(unsigned int i = 0; i < XZSIZE * XZSIZE; ++i) - { - delete m_unloadedCache[i]; - } - delete m_unloadedCache; + for (unsigned int i = 0; i < XZSIZE * XZSIZE; ++i) { + delete m_unloadedCache[i]; + } + delete m_unloadedCache; #endif - AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) - delete *it; - DeleteCriticalSection(&m_csLoadCreate); + AUTO_VAR(itEnd, m_loadedChunkList.end()); + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) delete *it; + DeleteCriticalSection(&m_csLoadCreate); } -bool ServerChunkCache::hasChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - // 4J Stu - Request for chunks outside the range always return an emptyChunk, so just return true here to say we have it - // If we return false entities less than 2 chunks from the edge do not tick properly due to them requiring a certain radius - // of chunks around them when they tick - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return true; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; - int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc == NULL ) return false; - return true; +bool ServerChunkCache::hasChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + // 4J Stu - Request for chunks outside the range always return an + // emptyChunk, so just return true here to say we have it If we return false + // entities less than 2 chunks from the edge do not tick properly due to + // them requiring a certain radius of chunks around them when they tick + if ((ix < 0) || (ix >= XZSIZE)) return true; + if ((iz < 0) || (iz >= XZSIZE)) return true; + int idx = ix * XZSIZE + iz; + LevelChunk* lc = cache[idx]; + if (lc == NULL) return false; + return true; } -std::vector *ServerChunkCache::getLoadedChunkList() -{ - return &m_loadedChunkList; +std::vector* ServerChunkCache::getLoadedChunkList() { + return &m_loadedChunkList; } -void ServerChunkCache::drop(int x, int z) -{ - // 4J - we're not dropping things anymore now that we have a fixed sized cache +void ServerChunkCache::drop(int x, int z) { + // 4J - we're not dropping things anymore now that we have a fixed sized + // cache #ifdef _LARGE_WORLDS - bool canDrop = false; -// if (level->dimension->mayRespawn()) -// { -// Pos *spawnPos = level->getSharedSpawnPos(); -// int xd = x * 16 + 8 - spawnPos->x; -// int zd = z * 16 + 8 - spawnPos->z; -// delete spawnPos; -// int r = 128; -// if (xd < -r || xd > r || zd < -r || zd > r) -// { -// canDrop = true; -//} -// } -// else - { - canDrop = true; - } - if(canDrop) - { - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return; - int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; + bool canDrop = false; + // if (level->dimension->mayRespawn()) + // { + // Pos *spawnPos = level->getSharedSpawnPos(); + // int xd = x * 16 + 8 - spawnPos->x; + // int zd = z * 16 + 8 - spawnPos->z; + // delete spawnPos; + // int r = 128; + // if (xd < -r || xd > r || zd < -r || zd > r) + // { + // canDrop = true; + //} + // } + // else + { + canDrop = true; + } + if (canDrop) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return; + if ((iz < 0) || (iz >= XZSIZE)) return; + int idx = ix * XZSIZE + iz; + LevelChunk* chunk = cache[idx]; - if(chunk) - { - m_toDrop.push_back(chunk); - } - } + if (chunk) { + m_toDrop.push_back(chunk); + } + } #endif } -void ServerChunkCache::dropAll() -{ +void ServerChunkCache::dropAll() { #ifdef _LARGE_WORLDS - for (LevelChunk *chunk : m_loadedChunkList) - { - drop(chunk->x, chunk->z); -} + for (LevelChunk* chunk : m_loadedChunkList) { + drop(chunk->x, chunk->z); + } #endif } // 4J - this is the original (and virtual) interface to create -LevelChunk *ServerChunkCache::create(int x, int z) -{ - return create(x, z, false); +LevelChunk* ServerChunkCache::create(int x, int z) { + return create(x, z, false); } -LevelChunk *ServerChunkCache::create(int x, int z, bool asyncPostProcess) // 4J - added extra parameter +LevelChunk* ServerChunkCache::create( + int x, int z, bool asyncPostProcess) // 4J - added extra parameter { - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - LevelChunk *lastChunk = chunk; + LevelChunk* chunk = cache[idx]; + LevelChunk* lastChunk = chunk; - if( ( chunk == NULL ) || ( chunk->x != x ) || ( chunk->z != z ) ) - { - EnterCriticalSection(&m_csLoadCreate); + if ((chunk == NULL) || (chunk->x != x) || (chunk->z != z)) { + EnterCriticalSection(&m_csLoadCreate); chunk = load(x, z); - if (chunk == NULL) - { - if (source == NULL) - { + if (chunk == NULL) { + if (source == NULL) { chunk = emptyChunk; - } - else - { + } else { chunk = source->getChunk(x, z); } } - if (chunk != NULL) - { - chunk->load(); - } + if (chunk != NULL) { + chunk->load(); + } - LeaveCriticalSection(&m_csLoadCreate); + LeaveCriticalSection(&m_csLoadCreate); -#if ( defined _WIN64 || defined __LP64__ ) - if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk ) +#if (defined _WIN64 || defined __LP64__) + if (InterlockedCompareExchangeRelease64( + (LONG64*)&cache[idx], (LONG64)chunk, (LONG64)lastChunk) == + (LONG64)lastChunk) #else - if( InterlockedCompareExchangeRelease((LONG *)&cache[idx],(LONG)chunk,(LONG)lastChunk) == (LONG)lastChunk ) -#endif // _DURANGO - { - // Successfully updated the cache - EnterCriticalSection(&m_csLoadCreate); - // 4J - added - this will run a recalcHeightmap if source is a randomlevelsource, which has been split out from source::getChunk so that - // we are doing it after the chunk has been added to the cache - otherwise a lot of the lighting fails as lights aren't added if the chunk - // they are in fail ServerChunkCache::hasChunk. - source->lightChunk(chunk); + if (InterlockedCompareExchangeRelease((LONG*)&cache[idx], (LONG)chunk, + (LONG)lastChunk) == + (LONG)lastChunk) +#endif // _DURANGO + { + // Successfully updated the cache + EnterCriticalSection(&m_csLoadCreate); + // 4J - added - this will run a recalcHeightmap if source is a + // randomlevelsource, which has been split out from source::getChunk + // so that we are doing it after the chunk has been added to the + // cache - otherwise a lot of the lighting fails as lights aren't + // added if the chunk they are in fail ServerChunkCache::hasChunk. + source->lightChunk(chunk); - updatePostProcessFlags( x, z ); + updatePostProcessFlags(x, z); - m_loadedChunkList.push_back(chunk); + m_loadedChunkList.push_back(chunk); - // 4J - If post-processing is to be async, then let the server know about requests rather than processing directly here. Note that - // these hasChunk() checks appear to be incorrect - the chunks checked by these map out as: - // - // 1. 2. 3. 4. - // oxx xxo ooo ooo - // oPx Poo oox xoo - // ooo ooo oPx Pxo - // - // where P marks the chunk that is being considered for postprocessing, and x marks chunks that needs to be loaded. It would seem that the - // chunks which need to be loaded should stay the same relative to the chunk to be processed, but the hasChunk checks in 3 cases check again - // the chunk which is to be processed itself rather than (what I presume to be) the correct position. - // Don't think we should change in case it alters level creation. + // 4J - If post-processing is to be async, then let the server know + // about requests rather than processing directly here. Note that + // these hasChunk() checks appear to be incorrect - the chunks + // checked by these map out as: + // + // 1. 2. 3. 4. + // oxx xxo ooo ooo + // oPx Poo oox xoo + // ooo ooo oPx Pxo + // + // where P marks the chunk that is being considered for + // postprocessing, and x marks chunks that needs to be loaded. It + // would seem that the chunks which need to be loaded should stay + // the same relative to the chunk to be processed, but the hasChunk + // checks in 3 cases check again the chunk which is to be processed + // itself rather than (what I presume to be) the correct position. + // Don't think we should change in case it alters level creation. - if( asyncPostProcess ) - { - // 4J Stu - TODO This should also be calling the same code as chunk->checkPostProcess, but then we cannot guarantee we are in the server add the post-process request - if ( ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0) && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x, z); - if (hasChunk(x - 1, z) && ((getChunk(x - 1, z)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x - 1, z); - if (hasChunk(x, z - 1) && ((getChunk(x, z - 1)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x, z - 1); - if (hasChunk(x - 1, z - 1) && ((getChunk(x - 1, z - 1)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x - 1, z - 1); - } - else - { - chunk->checkPostProcess(this, this, x, z); - } + if (asyncPostProcess) { + // 4J Stu - TODO This should also be calling the same code as + // chunk->checkPostProcess, but then we cannot guarantee we are + // in the server add the post-process request + if (((chunk->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && + hasChunk(x + 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest(this, + x, z); + if (hasChunk(x - 1, z) && + ((getChunk(x - 1, z)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && + hasChunk(x - 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x - 1, z); + if (hasChunk(x, z - 1) && + ((getChunk(x, z - 1)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && + hasChunk(x + 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x, z - 1); + if (hasChunk(x - 1, z - 1) && + ((getChunk(x - 1, z - 1)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && + hasChunk(x - 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x - 1, z - 1); + } else { + chunk->checkPostProcess(this, this, x, z); + } - // 4J - Now try and fix up any chests that were saved pre-1.8.2. We don't want to do this to this particular chunk as we don't know if all its neighbours are loaded yet, and we - // need the neighbours to be able to work out the facing direction for the chests. Therefore process any neighbouring chunk that loading this chunk would be the last neighbour for. - // 5 cases illustrated below, where P is the chunk to be processed, T is this chunk, and x are other chunks that need to be checked for being present + // 4J - Now try and fix up any chests that were saved pre-1.8.2. We + // don't want to do this to this particular chunk as we don't know + // if all its neighbours are loaded yet, and we need the neighbours + // to be able to work out the facing direction for the chests. + // Therefore process any neighbouring chunk that loading this chunk + // would be the last neighbour for. 5 cases illustrated below, where + // P is the chunk to be processed, T is this chunk, and x are other + // chunks that need to be checked for being present - // 1. 2. 3. 4. 5. - // ooooo ooxoo ooooo ooooo ooooo - // oxooo oxPxo oooxo ooooo ooxoo - // xPToo ooToo ooTPx ooToo oxPxo (in 5th case P and T are same) - // oxooo ooooo oooxo oxPxo ooxoo - // ooooo ooooo ooooo ooxoo ooooo + // 1. 2. 3. 4. 5. + // ooooo ooxoo ooooo ooooo ooooo + // oxooo oxPxo oooxo ooooo ooxoo + // xPToo ooToo ooTPx ooToo oxPxo (in 5th case P and T are + // same) oxooo ooooo oooxo oxPxo ooxoo ooooo ooooo + // ooooo ooxoo ooooo - if( hasChunk( x - 1, z ) && hasChunk( x - 2, z ) && hasChunk( x - 1, z + 1 ) && hasChunk( x - 1, z - 1 ) ) chunk->checkChests( this, x - 1, z ); - if( hasChunk( x, z + 1) && hasChunk( x , z + 2 ) && hasChunk( x - 1, z + 1 ) && hasChunk( x + 1, z + 1 ) ) chunk->checkChests( this, x, z + 1); - if( hasChunk( x + 1, z ) && hasChunk( x + 2, z ) && hasChunk( x + 1, z + 1 ) && hasChunk( x + 1, z - 1 ) ) chunk->checkChests( this, x + 1, z ); - if( hasChunk( x, z - 1) && hasChunk( x , z - 2 ) && hasChunk( x - 1, z - 1 ) && hasChunk( x + 1, z - 1 ) ) chunk->checkChests( this, x, z - 1); - if( hasChunk( x - 1, z ) && hasChunk( x + 1, z ) && hasChunk ( x, z - 1 ) && hasChunk( x, z + 1 ) ) chunk->checkChests( this, x, z ); + if (hasChunk(x - 1, z) && hasChunk(x - 2, z) && + hasChunk(x - 1, z + 1) && hasChunk(x - 1, z - 1)) + chunk->checkChests(this, x - 1, z); + if (hasChunk(x, z + 1) && hasChunk(x, z + 2) && + hasChunk(x - 1, z + 1) && hasChunk(x + 1, z + 1)) + chunk->checkChests(this, x, z + 1); + if (hasChunk(x + 1, z) && hasChunk(x + 2, z) && + hasChunk(x + 1, z + 1) && hasChunk(x + 1, z - 1)) + chunk->checkChests(this, x + 1, z); + if (hasChunk(x, z - 1) && hasChunk(x, z - 2) && + hasChunk(x - 1, z - 1) && hasChunk(x + 1, z - 1)) + chunk->checkChests(this, x, z - 1); + if (hasChunk(x - 1, z) && hasChunk(x + 1, z) && + hasChunk(x, z - 1) && hasChunk(x, z + 1)) + chunk->checkChests(this, x, z); - LeaveCriticalSection(&m_csLoadCreate); - } - else - { - // Something else must have updated the cache. Return that chunk and discard this one - chunk->unload(true); - delete chunk; - return cache[idx]; - } + LeaveCriticalSection(&m_csLoadCreate); + } else { + // Something else must have updated the cache. Return that chunk and + // discard this one + chunk->unload(true); + delete chunk; + return cache[idx]; + } } #ifdef __PS3__ - Sleep(1); -#endif // __PS3__ + Sleep(1); +#endif // __PS3__ return chunk; - } -// 4J Stu - Split out this function so that we get a chunk without loading entities -// This is used when sharing server chunk data on the main thread -LevelChunk *ServerChunkCache::getChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; +// 4J Stu - Split out this function so that we get a chunk without loading +// entities This is used when sharing server chunk data on the main thread +LevelChunk* ServerChunkCache::getChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc ) - { - return lc; - } + LevelChunk* lc = cache[idx]; + if (lc) { + return lc; + } - if( level->isFindingSpawn || autoCreate ) - { - return create(x, z); - } + if (level->isFindingSpawn || autoCreate) { + return create(x, z); + } - return emptyChunk; + return emptyChunk; } #ifdef _LARGE_WORLDS -// 4J added - this special variation on getChunk also checks the unloaded chunk cache. It is called on a host machine from the client-side level when: -// (1) Trying to determine whether the client blocks and data are the same as those on the server, so we can start sharing them -// (2) Trying to resync the lighting data from the server to the client -// As such it is really important that we don't return emptyChunk in these situations, when we actually still have the block/data/lighting in the unloaded cache -LevelChunk *ServerChunkCache::getChunkLoadedOrUnloaded(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; +// 4J added - this special variation on getChunk also checks the unloaded chunk +// cache. It is called on a host machine from the client-side level when: (1) +// Trying to determine whether the client blocks and data are the same as those +// on the server, so we can start sharing them (2) Trying to resync the lighting +// data from the server to the client As such it is really important that we +// don't return emptyChunk in these situations, when we actually still have the +// block/data/lighting in the unloaded cache +LevelChunk* ServerChunkCache::getChunkLoadedOrUnloaded(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc ) - { - return lc; - } + LevelChunk* lc = cache[idx]; + if (lc) { + return lc; + } - lc = m_unloadedCache[idx]; - if( lc ) - { - return lc; -} + lc = m_unloadedCache[idx]; + if (lc) { + return lc; + } - if( level->isFindingSpawn || autoCreate ) - { - return create(x, z); - } + if (level->isFindingSpawn || autoCreate) { + return create(x, z); + } - return emptyChunk; + return emptyChunk; } #endif // 4J Added // #ifdef _LARGE_WORLDS -void ServerChunkCache::dontDrop(int x, int z) -{ - LevelChunk *chunk = getChunk(x,z); - m_toDrop.erase(std::remove(m_toDrop.begin(), m_toDrop.end(), chunk), m_toDrop.end()); +void ServerChunkCache::dontDrop(int x, int z) { + LevelChunk* chunk = getChunk(x, z); + m_toDrop.erase(std::remove(m_toDrop.begin(), m_toDrop.end(), chunk), + m_toDrop.end()); } #endif -LevelChunk *ServerChunkCache::load(int x, int z) -{ +LevelChunk* ServerChunkCache::load(int x, int z) { if (storage == NULL) return NULL; - LevelChunk *levelChunk = NULL; + LevelChunk* levelChunk = NULL; #ifdef _LARGE_WORLDS - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - int idx = ix * XZSIZE + iz; - levelChunk = m_unloadedCache[idx]; - m_unloadedCache[idx] = NULL; - if(levelChunk == NULL) + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + int idx = ix * XZSIZE + iz; + levelChunk = m_unloadedCache[idx]; + m_unloadedCache[idx] = NULL; + if (levelChunk == NULL) #endif - { - levelChunk = storage->load(level, x, z); - } - if (levelChunk != NULL) - { + { + levelChunk = storage->load(level, x, z); + } + if (levelChunk != NULL) { levelChunk->lastSaveTime = level->getTime(); } return levelChunk; } -void ServerChunkCache::saveEntities(LevelChunk *levelChunk) -{ +void ServerChunkCache::saveEntities(LevelChunk* levelChunk) { if (storage == NULL) return; storage->saveEntities(level, levelChunk); } -void ServerChunkCache::save(LevelChunk *levelChunk) -{ - if (storage == NULL) return; +void ServerChunkCache::save(LevelChunk* levelChunk) { + if (storage == NULL) return; - levelChunk->lastSaveTime = level->getTime(); - storage->save(level, levelChunk); + levelChunk->lastSaveTime = level->getTime(); + storage->save(level, levelChunk); } // 4J added -void ServerChunkCache::updatePostProcessFlag(short flag, int x, int z, int xo, int zo, LevelChunk *lc) -{ - if( hasChunk( x + xo, z + zo ) ) - { - LevelChunk *lc2 = getChunk(x + xo, z + zo); - if( lc2 != emptyChunk ) // Will only be empty chunk of this is the edge (we've already checked hasChunk so won't just be a missing chunk) - { - if( lc2->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) - { - lc->terrainPopulated |= flag; - } - } - else - { - // The edge - always consider as post-processed - lc->terrainPopulated |= flag; - } - } +void ServerChunkCache::updatePostProcessFlag(short flag, int x, int z, int xo, + int zo, LevelChunk* lc) { + if (hasChunk(x + xo, z + zo)) { + LevelChunk* lc2 = getChunk(x + xo, z + zo); + if (lc2 != emptyChunk) // Will only be empty chunk of this is the edge + // (we've already checked hasChunk so won't just + // be a missing chunk) + { + if (lc2->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) { + lc->terrainPopulated |= flag; + } + } else { + // The edge - always consider as post-processed + lc->terrainPopulated |= flag; + } + } } -// 4J added - normally we try and set these flags when a chunk is post-processed. However, when setting in a north or easterly direction the -// affected chunks might not themselves exist, so we need to check the flags also when creating new chunks. -void ServerChunkCache::updatePostProcessFlags(int x, int z) -{ - LevelChunk *lc = getChunk(x, z); - if( lc != emptyChunk ) - { - // First check if any of our neighbours are post-processed, that should affect OUR flags - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromS, x, z, 0, -1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromSW, x, z, -1, -1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromW, x, z, -1, 0, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromNW, x, z, -1, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromN, x, z, 0, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromNE, x, z, 1, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromE, x, z, 1, 0, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromSE, x, z, 1, -1, lc ); +// 4J added - normally we try and set these flags when a chunk is +// post-processed. However, when setting in a north or easterly direction the +// affected chunks might not themselves exist, so we need to check the flags +// also when creating new chunks. +void ServerChunkCache::updatePostProcessFlags(int x, int z) { + LevelChunk* lc = getChunk(x, z); + if (lc != emptyChunk) { + // First check if any of our neighbours are post-processed, that should + // affect OUR flags + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromS, x, z, 0, -1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromSW, x, z, -1, -1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromW, x, z, -1, 0, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromNW, x, z, -1, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromN, x, z, 0, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromNE, x, z, 1, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromE, x, z, 1, 0, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromSE, x, z, 1, -1, + lc); - // Then, if WE are post-processed, check that our neighbour's flags are also set - if( lc->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) - { - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, z - 1 ); - } - } + // Then, if WE are post-processed, check that our neighbour's flags are + // also set + if (lc->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) { + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, + z - 1); + } + } - flagPostProcessComplete(0, x, z); + flagPostProcessComplete(0, x, z); } -// 4J added - add a flag to a chunk to say that one of its neighbours has completed post-processing. If this completes the set of -// chunks which can actually set tile tiles in this chunk (sTerrainPopulatedAllAffecting), then this is a good point to compress this chunk. -// If this completes the set of all 8 neighbouring chunks that have been fully post-processed, then this is a good time to fix up some -// lighting things that need all the tiles to be in place in the region into which they might propagate. -void ServerChunkCache::flagPostProcessComplete(short flag, int x, int z) -{ - // Set any extra flags for this chunk to indicate which neighbours have now had their post-processing done - if( !hasChunk(x, z) ) return; +// 4J added - add a flag to a chunk to say that one of its neighbours has +// completed post-processing. If this completes the set of chunks which can +// actually set tile tiles in this chunk (sTerrainPopulatedAllAffecting), then +// this is a good point to compress this chunk. If this completes the set of all +// 8 neighbouring chunks that have been fully post-processed, then this is a +// good time to fix up some lighting things that need all the tiles to be in +// place in the region into which they might propagate. +void ServerChunkCache::flagPostProcessComplete(short flag, int x, int z) { + // Set any extra flags for this chunk to indicate which neighbours have now + // had their post-processing done + if (!hasChunk(x, z)) return; - LevelChunk *lc = level->getChunk( x, z ); - if( lc == emptyChunk ) return; + LevelChunk* lc = level->getChunk(x, z); + if (lc == emptyChunk) return; - lc->terrainPopulated |= flag; + lc->terrainPopulated |= flag; - // Are all neighbouring chunks which could actually place tiles on this chunk complete? (This is ones to W, SW, S) - if( ( lc->terrainPopulated & LevelChunk::sTerrainPopulatedAllAffecting ) == LevelChunk::sTerrainPopulatedAllAffecting ) - { - // Do the compression of data & lighting at this point - PIXBeginNamedEvent(0,"Compressing lighting/blocks"); + // Are all neighbouring chunks which could actually place tiles on this + // chunk complete? (This is ones to W, SW, S) + if ((lc->terrainPopulated & LevelChunk::sTerrainPopulatedAllAffecting) == + LevelChunk::sTerrainPopulatedAllAffecting) { + // Do the compression of data & lighting at this point + PIXBeginNamedEvent(0, "Compressing lighting/blocks"); - // Check, using lower blocks as a reference, if we've already compressed - no point doing this multiple times, which - // otherwise we will do as we aren't checking for the flags transitioning in the if statement we're in here - if( !lc->isLowerBlockStorageCompressed() ) - lc->compressBlocks(); - if( !lc->isLowerBlockLightStorageCompressed() ) - lc->compressLighting(); - if( !lc->isLowerDataStorageCompressed() ) - lc->compressData(); - - PIXEndNamedEvent(); - } + // Check, using lower blocks as a reference, if we've already compressed + // - no point doing this multiple times, which otherwise we will do as + // we aren't checking for the flags transitioning in the if statement + // we're in here + if (!lc->isLowerBlockStorageCompressed()) lc->compressBlocks(); + if (!lc->isLowerBlockLightStorageCompressed()) lc->compressLighting(); + if (!lc->isLowerDataStorageCompressed()) lc->compressData(); - // Are all neighbouring chunks And this one now post-processed? - if( lc->terrainPopulated == LevelChunk::sTerrainPopulatedAllNeighbours ) - { - // Special lighting patching for schematics first - app.processSchematicsLighting(lc); + PIXEndNamedEvent(); + } - // This would be a good time to fix up any lighting for this chunk since all the geometry that could affect it should now be in place - PIXBeginNamedEvent(0,"Recheck gaps"); - if( lc->level->dimension->id != 1 ) - { - lc->recheckGaps(true); - } - PIXEndNamedEvent(); + // Are all neighbouring chunks And this one now post-processed? + if (lc->terrainPopulated == LevelChunk::sTerrainPopulatedAllNeighbours) { + // Special lighting patching for schematics first + app.processSchematicsLighting(lc); - // Do a checkLight on any tiles which are lava. - PIXBeginNamedEvent(0,"Light lava (this)"); - lc->lightLava(); - PIXEndNamedEvent(); + // This would be a good time to fix up any lighting for this chunk since + // all the geometry that could affect it should now be in place + PIXBeginNamedEvent(0, "Recheck gaps"); + if (lc->level->dimension->id != 1) { + lc->recheckGaps(true); + } + PIXEndNamedEvent(); - // Flag as now having this post-post-processing stage completed - lc->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; - } + // Do a checkLight on any tiles which are lava. + PIXBeginNamedEvent(0, "Light lava (this)"); + lc->lightLava(); + PIXEndNamedEvent(); + + // Flag as now having this post-post-processing stage completed + lc->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; + } } -void ServerChunkCache::postProcess(ChunkSource *parent, int x, int z ) -{ - LevelChunk *chunk = getChunk(x, z); - if ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0 ) - { - if (source != NULL) - { - PIXBeginNamedEvent(0,"Main post processing"); +void ServerChunkCache::postProcess(ChunkSource* parent, int x, int z) { + LevelChunk* chunk = getChunk(x, z); + if ((chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == + 0) { + if (source != NULL) { + PIXBeginNamedEvent(0, "Main post processing"); source->postProcess(parent, x, z); - PIXEndNamedEvent(); + PIXEndNamedEvent(); chunk->markUnsaved(); } - // Flag not only this chunk as being post-processed, but also all the chunks that this post-processing might affect. We can guarantee that these - // chunks exist as that's determined before post-processing can even run - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromHere; + // Flag not only this chunk as being post-processed, but also all the + // chunks that this post-processing might affect. We can guarantee that + // these chunks exist as that's determined before post-processing can + // even run + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromHere; - // If we are an edge chunk, fill in missing flags from sides that will never post-process - if(x == -XZOFFSET) // Furthest west - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; - } - if(x == (XZOFFSET - 1 )) // Furthest east - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromE; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; - } - if(z == -XZOFFSET) // Furthest south - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromS; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; - } - if(z == (XZOFFSET - 1)) // Furthest north - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromN; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; - } + // If we are an edge chunk, fill in missing flags from sides that will + // never post-process + if (x == -XZOFFSET) // Furthest west + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; + } + if (x == (XZOFFSET - 1)) // Furthest east + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromE; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; + } + if (z == -XZOFFSET) // Furthest south + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromS; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; + } + if (z == (XZOFFSET - 1)) // Furthest north + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromN; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; + } - // Set flags for post-processing being complete for neighbouring chunks. This also performs actions if this post-processing completes - // a full set of post-processing flags for one of these neighbours. - flagPostProcessComplete(0, x, z ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, z - 1 ); + // Set flags for post-processing being complete for neighbouring chunks. + // This also performs actions if this post-processing completes a full + // set of post-processing flags for one of these neighbours. + flagPostProcessComplete(0, x, z); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, + z - 1); } } // 4J Added for suspend -bool ServerChunkCache::saveAllEntities() -{ - PIXBeginNamedEvent(0, "Save all entities"); +bool ServerChunkCache::saveAllEntities() { + PIXBeginNamedEvent(0, "Save all entities"); - PIXBeginNamedEvent(0, "saving to NBT"); - EnterCriticalSection(&m_csLoadCreate); - for(AUTO_VAR(it,m_loadedChunkList.begin()); it != m_loadedChunkList.end(); ++it) - { - storage->saveEntities(level, *it); - } - LeaveCriticalSection(&m_csLoadCreate); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "saving to NBT"); + EnterCriticalSection(&m_csLoadCreate); + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != m_loadedChunkList.end(); + ++it) { + storage->saveEntities(level, *it); + } + LeaveCriticalSection(&m_csLoadCreate); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Flushing"); - storage->flush(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Flushing"); + storage->flush(); + PIXEndNamedEvent(); - PIXEndNamedEvent(); - return true; + PIXEndNamedEvent(); + return true; } -bool ServerChunkCache::save(bool force, ProgressListener *progressListener) -{ - EnterCriticalSection(&m_csLoadCreate); +bool ServerChunkCache::save(bool force, ProgressListener* progressListener) { + EnterCriticalSection(&m_csLoadCreate); int saves = 0; - // 4J - added this to support progressListner - int count = 0; - if (progressListener != NULL) - { + // 4J - added this to support progressListner + int count = 0; + if (progressListener != NULL) { AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) - { - LevelChunk *chunk = *it; - if (chunk->shouldSave(force)) - { + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) { + LevelChunk* chunk = *it; + if (chunk->shouldSave(force)) { count++; } } } int cc = 0; - bool maxSavesReached = false; + bool maxSavesReached = false; - if(!force) - { - //app.DebugPrintf("Unsaved chunks = %d\n", level->getUnsavedChunkCount() ); - // Single threaded implementation for small saves - for (unsigned int i = 0; i < m_loadedChunkList.size(); i++) - { - LevelChunk *chunk = m_loadedChunkList[i]; + if (!force) { + // app.DebugPrintf("Unsaved chunks = %d\n", + // level->getUnsavedChunkCount() ); + // Single threaded implementation for small saves + for (unsigned int i = 0; i < m_loadedChunkList.size(); i++) { + LevelChunk* chunk = m_loadedChunkList[i]; #ifndef SPLIT_SAVES - if (force && !chunk->dontSave) saveEntities(chunk); + if (force && !chunk->dontSave) saveEntities(chunk); #endif - if (chunk->shouldSave(force)) - { - save(chunk); - chunk->setUnsaved(false); - if (++saves == MAX_SAVES && !force) - { - LeaveCriticalSection(&m_csLoadCreate); - return false; - } + if (chunk->shouldSave(force)) { + save(chunk); + chunk->setUnsaved(false); + if (++saves == MAX_SAVES && !force) { + LeaveCriticalSection(&m_csLoadCreate); + return false; + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } - } - } - else - { -#if 1 //_LARGE_WORLDS - // 4J Stu - We have multiple for threads for all saving as part of the storage, so use that rather than new threads here + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (++cc % 10 == 0) { + progressListener->progressStagePercentage(cc * 100 / + count); + } + } + } + } + } else { +#if 1 //_LARGE_WORLDS + // 4J Stu - We have multiple for threads for all saving as part of the + // storage, so use that rather than new threads here - // Created a roughly sorted list to match the order that the files were created in McRegionChunkStorage::McRegionChunkStorage. - // This is to minimise the amount of data that needs to be moved round when creating a new level. + // Created a roughly sorted list to match the order that the files were + // created in McRegionChunkStorage::McRegionChunkStorage. This is to + // minimise the amount of data that needs to be moved round when + // creating a new level. - std::vector sortedChunkList; + std::vector sortedChunkList; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && + (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } - // Push all the chunks to be saved to the compression threads - for (unsigned int i = 0; i < sortedChunkList.size();++i) - { - LevelChunk *chunk = sortedChunkList[i]; - if (force && !chunk->dontSave) saveEntities(chunk); - if (chunk->shouldSave(force)) - { - save(chunk); - chunk->setUnsaved(false); - if (++saves == MAX_SAVES && !force) - { - LeaveCriticalSection(&m_csLoadCreate); - return false; - } + // Push all the chunks to be saved to the compression threads + for (unsigned int i = 0; i < sortedChunkList.size(); ++i) { + LevelChunk* chunk = sortedChunkList[i]; + if (force && !chunk->dontSave) saveEntities(chunk); + if (chunk->shouldSave(force)) { + save(chunk); + chunk->setUnsaved(false); + if (++saves == MAX_SAVES && !force) { + LeaveCriticalSection(&m_csLoadCreate); + return false; + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } - // Wait if we are building up too big a queue of chunks to be written - on PS3 this has been seen to cause so much data to be queued that we run out of - // out of memory when saving after exploring a full map - storage->WaitIfTooManyQueuedChunks(); - } + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (++cc % 10 == 0) { + progressListener->progressStagePercentage(cc * 100 / + count); + } + } + } + // Wait if we are building up too big a queue of chunks to be + // written - on PS3 this has been seen to cause so much data to be + // queued that we run out of out of memory when saving after + // exploring a full map + storage->WaitIfTooManyQueuedChunks(); + } - // Wait for the storage threads to be complete - storage->WaitForAll(); + // Wait for the storage threads to be complete + storage->WaitForAll(); #else - // Multithreaded implementation for larger saves + // Multithreaded implementation for larger saves - C4JThread::Event *wakeEvent[3]; // This sets off the threads that are waiting to continue - C4JThread::Event *notificationEvent[3]; // These are signalled by the threads to let us know they are complete - C4JThread *saveThreads[3]; - SaveThreadData threadData[3]; - ZeroMemory(&threadData[0], sizeof(SaveThreadData)); - ZeroMemory(&threadData[1], sizeof(SaveThreadData)); - ZeroMemory(&threadData[2], sizeof(SaveThreadData)); + C4JThread::Event* wakeEvent[3]; // This sets off the threads that are + // waiting to continue + C4JThread::Event* + notificationEvent[3]; // These are signalled by the threads to let + // us know they are complete + C4JThread* saveThreads[3]; + SaveThreadData threadData[3]; + ZeroMemory(&threadData[0], sizeof(SaveThreadData)); + ZeroMemory(&threadData[1], sizeof(SaveThreadData)); + ZeroMemory(&threadData[2], sizeof(SaveThreadData)); - for(unsigned int i = 0; i < 3; ++i) - { - saveThreads[i] = NULL; - - threadData[i].cache = this; + for (unsigned int i = 0; i < 3; ++i) { + saveThreads[i] = NULL; - wakeEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); - threadData[i].wakeEvent = wakeEvent[i]; - - notificationEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); - threadData[i].notificationEvent = notificationEvent[i]; + threadData[i].cache = this; - if(i==0) threadData[i].useSharedThreadStorage = true; - else threadData[i].useSharedThreadStorage = false; - } + wakeEvent[i] = + new C4JThread::Event(); // CreateEvent(NULL,FALSE,FALSE,NULL); + threadData[i].wakeEvent = wakeEvent[i]; - LevelChunk *chunk = NULL; - std::uint8_t workingThreads; - bool chunkSet = false; + notificationEvent[i] = + new C4JThread::Event(); // CreateEvent(NULL,FALSE,FALSE,NULL); + threadData[i].notificationEvent = notificationEvent[i]; - // Created a roughly sorted list to match the order that the files were created in McRegionChunkStorage::McRegionChunkStorage. - // This is to minimise the amount of data that needs to be moved round when creating a new level. + if (i == 0) + threadData[i].useSharedThreadStorage = true; + else + threadData[i].useSharedThreadStorage = false; + } - std::vector sortedChunkList; + LevelChunk* chunk = NULL; + std::uint8_t workingThreads; + bool chunkSet = false; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - - for (unsigned int i = 0; i < sortedChunkList.size();) - { - workingThreads = 0; - PIXBeginNamedEvent(0,"Setting tasks for save threads\n"); - for(unsigned int j = 0; j < 3; ++j) - { - chunkSet = false; + // Created a roughly sorted list to match the order that the files were + // created in McRegionChunkStorage::McRegionChunkStorage. This is to + // minimise the amount of data that needs to be moved round when + // creating a new level. - while(!chunkSet && i < sortedChunkList.size()) - { - chunk = sortedChunkList[i]; + std::vector sortedChunkList; - threadData[j].saveEntities = (force && !chunk->dontSave); + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && + (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } - if (chunk->shouldSave(force) || threadData[j].saveEntities) - { - chunkSet = true; - ++workingThreads; + for (unsigned int i = 0; i < sortedChunkList.size();) { + workingThreads = 0; + PIXBeginNamedEvent(0, "Setting tasks for save threads\n"); + for (unsigned int j = 0; j < 3; ++j) { + chunkSet = false; - threadData[j].chunkToSave = chunk; + while (!chunkSet && i < sortedChunkList.size()) { + chunk = sortedChunkList[i]; - //app.DebugPrintf("Chunk to save set for thread %d\n", j); + threadData[j].saveEntities = (force && !chunk->dontSave); - if(saveThreads[j] == NULL) - { - char threadName[256]; - sprintf(threadName,"Save thread %d\n",j); - SetThreadName(0, threadName); + if (chunk->shouldSave(force) || + threadData[j].saveEntities) { + chunkSet = true; + ++workingThreads; - //saveThreads[j] = CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); - saveThreads[j] = new C4JThread(runSaveThreadProc,(void *)&threadData[j],threadName); + threadData[j].chunkToSave = chunk; + // app.DebugPrintf("Chunk to save set for thread %d\n", + // j); - //app.DebugPrintf("Created new thread: %s\n",threadName); + if (saveThreads[j] == NULL) { + char threadName[256]; + sprintf(threadName, "Save thread %d\n", j); + SetThreadName(0, threadName); - // Threads 1,3 and 5 are generally idle so use them (this call waits on thread 2) - if(j == 0) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_A); //XSetThreadProcessor( saveThreads[j], 1); - else if(j == 1) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_B); //XSetThreadProcessor( saveThreads[j], 3); - else if(j == 2) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_C); //XSetThreadProcessor( saveThreads[j], 5); + // saveThreads[j] = + // CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); + saveThreads[j] = new C4JThread( + runSaveThreadProc, (void*)&threadData[j], + threadName); - //ResumeThread( saveThreads[j] ); - saveThreads[j]->Run(); - } + // app.DebugPrintf("Created new thread: + // %s\n",threadName); - if (++saves == MAX_SAVES && !force) - { - maxSavesReached = true; - break; + // Threads 1,3 and 5 are generally idle so use them + // (this call waits on thread 2) + if (j == 0) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_A); // XSetThreadProcessor( + // saveThreads[j], + // 1); + else if (j == 1) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_B); // XSetThreadProcessor( + // saveThreads[j], + // 3); + else if (j == 2) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_C); // XSetThreadProcessor( + // saveThreads[j], + // 5); - //LeaveCriticalSection(&m_csLoadCreate); - // TODO Should we be returning from here? Probably not - //return false; - } + // ResumeThread( saveThreads[j] ); + saveThreads[j]->Run(); + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (count > 0 && ++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } + if (++saves == MAX_SAVES && !force) { + maxSavesReached = true; + break; - ++i; - } + // LeaveCriticalSection(&m_csLoadCreate); + // TODO Should we be returning from here? Probably + // not + // return false; + } - if( !chunkSet ) - { - threadData[j].chunkToSave = NULL; - //app.DebugPrintf("No chunk to save set for thread %d\n",j); - } - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Waking save threads\n"); - // Start the worker threads going - for(unsigned int k = 0; k < 3; ++k) - { - //app.DebugPrintf("Waking save thread %d\n",k); - threadData[k].wakeEvent->Set(); //SetEvent(threadData[k].wakeEvent); - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Waiting for completion of save threads\n"); - //app.DebugPrintf("Waiting for %d save thread(s) to complete\n", workingThreads); + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (count > 0 && ++cc % 10 == 0) { + progressListener->progressStagePercentage( + cc * 100 / count); + } + } + } - // Wait for the worker threads to complete - //WaitForMultipleObjects(workingThreads,notificationEvent,TRUE,INFINITE); - // 4J Stu - TODO This isn't ideal as it's not a perfect re-implmentation of the Xbox behaviour - for(unsigned int k = 0; k < workingThreads; ++k) - { - threadData[k].notificationEvent->WaitForSignal(INFINITE); - } - PIXEndNamedEvent(); - if( maxSavesReached ) break; - } + ++i; + } - //app.DebugPrintf("Clearing up worker threads\n"); - // Stop all the worker threads by giving them nothing to process then telling them to start - unsigned char validThreads = 0; - for(unsigned int i = 0; i < 3; ++i) - { - //app.DebugPrintf("Settings chunk to NULL for save thread %d\n", i); - threadData[i].chunkToSave = NULL; + if (!chunkSet) { + threadData[j].chunkToSave = NULL; + // app.DebugPrintf("No chunk to save set for thread + // %d\n",j); + } + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Waking save threads\n"); + // Start the worker threads going + for (unsigned int k = 0; k < 3; ++k) { + // app.DebugPrintf("Waking save thread %d\n",k); + threadData[k] + .wakeEvent->Set(); // SetEvent(threadData[k].wakeEvent); + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Waiting for completion of save threads\n"); + // app.DebugPrintf("Waiting for %d save thread(s) to complete\n", + // workingThreads); - //app.DebugPrintf("Setting wake event for save thread %d\n",i); - threadData[i].wakeEvent->Set(); //SetEvent(threadData[i].wakeEvent); + // Wait for the worker threads to complete + // WaitForMultipleObjects(workingThreads,notificationEvent,TRUE,INFINITE); + // 4J Stu - TODO This isn't ideal as it's not a perfect + // re-implmentation of the Xbox behaviour + for (unsigned int k = 0; k < workingThreads; ++k) { + threadData[k].notificationEvent->WaitForSignal(INFINITE); + } + PIXEndNamedEvent(); + if (maxSavesReached) break; + } - if(saveThreads[i] != NULL) ++validThreads; - } + // app.DebugPrintf("Clearing up worker threads\n"); + // Stop all the worker threads by giving them nothing to process then + // telling them to start + unsigned char validThreads = 0; + for (unsigned int i = 0; i < 3; ++i) { + // app.DebugPrintf("Settings chunk to NULL for save thread %d\n", + // i); + threadData[i].chunkToSave = NULL; - //WaitForMultipleObjects(validThreads,saveThreads,TRUE,INFINITE); - // 4J Stu - TODO This isn't ideal as it's not a perfect re-implmentation of the Xbox behaviour - for(unsigned int k = 0; k < validThreads; ++k) - { - saveThreads[k]->WaitForCompletion(INFINITE);; - } + // app.DebugPrintf("Setting wake event for save thread %d\n",i); + threadData[i] + .wakeEvent->Set(); // SetEvent(threadData[i].wakeEvent); - for(unsigned int i = 0; i < 3; ++i) - { - //app.DebugPrintf("Closing handles for save thread %d\n", i); - delete threadData[i].wakeEvent; //CloseHandle(threadData[i].wakeEvent); - delete threadData[i].notificationEvent; //CloseHandle(threadData[i].notificationEvent); - delete saveThreads[i]; //CloseHandle(saveThreads[i]); - } + if (saveThreads[i] != NULL) ++validThreads; + } + + // WaitForMultipleObjects(validThreads,saveThreads,TRUE,INFINITE); + // 4J Stu - TODO This isn't ideal as it's not a perfect + // re-implmentation of the Xbox behaviour + for (unsigned int k = 0; k < validThreads; ++k) { + saveThreads[k]->WaitForCompletion(INFINITE); + ; + } + + for (unsigned int i = 0; i < 3; ++i) { + // app.DebugPrintf("Closing handles for save thread %d\n", i); + delete threadData[i] + .wakeEvent; // CloseHandle(threadData[i].wakeEvent); + delete threadData[i] + .notificationEvent; // CloseHandle(threadData[i].notificationEvent); + delete saveThreads[i]; // CloseHandle(saveThreads[i]); + } #endif - } + } - if (force) - { - if (storage == NULL) - { - LeaveCriticalSection(&m_csLoadCreate); - return true; - } + if (force) { + if (storage == NULL) { + LeaveCriticalSection(&m_csLoadCreate); + return true; + } storage->flush(); } - LeaveCriticalSection(&m_csLoadCreate); + LeaveCriticalSection(&m_csLoadCreate); return !maxSavesReached; - } -bool ServerChunkCache::tick() -{ - if (!level->noSave) - { +bool ServerChunkCache::tick() { + if (!level->noSave) { #ifdef _LARGE_WORLDS - for (int i = 0; i < 100; i++) - { - if (!m_toDrop.empty()) - { - LevelChunk *chunk = m_toDrop.front(); - if(!chunk->isUnloaded()) - { - save(chunk); - saveEntities(chunk); - chunk->unload(true); + for (int i = 0; i < 100; i++) { + if (!m_toDrop.empty()) { + LevelChunk* chunk = m_toDrop.front(); + if (!chunk->isUnloaded()) { + save(chunk); + saveEntities(chunk); + chunk->unload(true); - //loadedChunks.remove(cp); - //loadedChunkList.remove(chunk); - AUTO_VAR(it, std::find( m_loadedChunkList.begin(), m_loadedChunkList.end(), chunk) ); - if(it != m_loadedChunkList.end()) m_loadedChunkList.erase(it); + // loadedChunks.remove(cp); + // loadedChunkList.remove(chunk); + AUTO_VAR(it, std::find(m_loadedChunkList.begin(), + m_loadedChunkList.end(), chunk)); + if (it != m_loadedChunkList.end()) + m_loadedChunkList.erase(it); - int ix = chunk->x + XZOFFSET; - int iz = chunk->z + XZOFFSET; - int idx = ix * XZSIZE + iz; - m_unloadedCache[idx] = chunk; - cache[idx] = NULL; - } - m_toDrop.pop_front(); - } - } + int ix = chunk->x + XZOFFSET; + int iz = chunk->z + XZOFFSET; + int idx = ix * XZSIZE + iz; + m_unloadedCache[idx] = chunk; + cache[idx] = NULL; + } + m_toDrop.pop_front(); + } + } #endif if (storage != NULL) storage->tick(); } return source->tick(); - } -bool ServerChunkCache::shouldSave() -{ - return !level->noSave; +bool ServerChunkCache::shouldSave() { return !level->noSave; } + +std::wstring ServerChunkCache::gatherStats() { + return L"ServerChunkCache: "; // + _toString(loadedChunks.size()) + L" + // Drop: " + _toString(toDrop.size()); } -std::wstring ServerChunkCache::gatherStats() -{ - return L"ServerChunkCache: ";// + _toString(loadedChunks.size()) + L" Drop: " + _toString(toDrop.size()); +std::vector* ServerChunkCache::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + return source->getMobsAt(mobCategory, x, y, z); } -std::vector *ServerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - return source->getMobsAt(mobCategory, x, y, z); +TilePos* ServerChunkCache::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return source->findNearestMapFeature(level, featureName, x, y, z); } -TilePos *ServerChunkCache::findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z) -{ - return source->findNearestMapFeature(level, featureName, x, y, z); -} - -int ServerChunkCache::runSaveThreadProc(void *lpParam) -{ - SaveThreadData *params = static_cast(lpParam); - - if(params->useSharedThreadStorage) - { - Compression::UseDefaultThreadStorage(); - OldChunkStorage::UseDefaultThreadStorage(); - } - else - { - Compression::CreateNewThreadStorage(); - OldChunkStorage::CreateNewThreadStorage(); - } - - // Wait for the producer thread to tell us to start - params->wakeEvent->WaitForSignal(INFINITE); //WaitForSingleObject(params->wakeEvent,INFINITE); - - //app.DebugPrintf("Save thread has started\n"); - - while(params->chunkToSave != NULL) - { - PIXBeginNamedEvent(0,"Saving entities"); - //app.DebugPrintf("Save thread has started processing a chunk\n"); - if (params->saveEntities) params->cache->saveEntities(params->chunkToSave); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Saving chunk"); - - params->cache->save(params->chunkToSave); - params->chunkToSave->setUnsaved(false); - - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Notifying and waiting for next chunk"); - - // Inform the producer thread that we are done with this chunk - params->notificationEvent->Set(); //SetEvent(params->notificationEvent); - - //app.DebugPrintf("Save thread has alerted producer that it is complete\n"); - - // Wait for the producer thread to tell us to go again - params->wakeEvent->WaitForSignal(INFINITE); //WaitForSingleObject(params->wakeEvent,INFINITE); - PIXEndNamedEvent(); - } - - //app.DebugPrintf("Thread is exiting as it has no chunk to process\n"); - - if(!params->useSharedThreadStorage) - { - Compression::ReleaseThreadStorage(); - OldChunkStorage::ReleaseThreadStorage(); - } - - return 0; +int ServerChunkCache::runSaveThreadProc(void* lpParam) { + SaveThreadData* params = static_cast(lpParam); + + if (params->useSharedThreadStorage) { + Compression::UseDefaultThreadStorage(); + OldChunkStorage::UseDefaultThreadStorage(); + } else { + Compression::CreateNewThreadStorage(); + OldChunkStorage::CreateNewThreadStorage(); + } + + // Wait for the producer thread to tell us to start + params->wakeEvent->WaitForSignal( + INFINITE); // WaitForSingleObject(params->wakeEvent,INFINITE); + + // app.DebugPrintf("Save thread has started\n"); + + while (params->chunkToSave != NULL) { + PIXBeginNamedEvent(0, "Saving entities"); + // app.DebugPrintf("Save thread has started processing a chunk\n"); + if (params->saveEntities) + params->cache->saveEntities(params->chunkToSave); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Saving chunk"); + + params->cache->save(params->chunkToSave); + params->chunkToSave->setUnsaved(false); + + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Notifying and waiting for next chunk"); + + // Inform the producer thread that we are done with this chunk + params->notificationEvent + ->Set(); // SetEvent(params->notificationEvent); + + // app.DebugPrintf("Save thread has alerted producer that it is + // complete\n"); + + // Wait for the producer thread to tell us to go again + params->wakeEvent->WaitForSignal( + INFINITE); // WaitForSingleObject(params->wakeEvent,INFINITE); + PIXEndNamedEvent(); + } + + // app.DebugPrintf("Thread is exiting as it has no chunk to process\n"); + + if (!params->useSharedThreadStorage) { + Compression::ReleaseThreadStorage(); + OldChunkStorage::ReleaseThreadStorage(); + } + + return 0; } diff --git a/Minecraft.Client/Network/ServerChunkCache.h b/Minecraft.Client/Network/ServerChunkCache.h index e127ccd71..c086728a0 100644 --- a/Minecraft.Client/Network/ServerChunkCache.h +++ b/Minecraft.Client/Network/ServerChunkCache.h @@ -8,94 +8,99 @@ class ServerLevel; -class ServerChunkCache : public ChunkSource -{ +class ServerChunkCache : public ChunkSource { +private: + // std::unordered_set toDrop; +private: + LevelChunk* emptyChunk; + ChunkSource* source; + ChunkStorage* storage; + +public: + bool autoCreate; private: -// std::unordered_set toDrop; -private: - LevelChunk *emptyChunk; - ChunkSource *source; - ChunkStorage *storage; -public: - bool autoCreate; -private: - LevelChunk **cache; - std::vector m_loadedChunkList; - ServerLevel *level; + LevelChunk** cache; + std::vector m_loadedChunkList; + ServerLevel* level; #ifdef _LARGE_WORLDS - std::deque m_toDrop; - LevelChunk **m_unloadedCache; + std::deque m_toDrop; + LevelChunk** m_unloadedCache; #endif - // 4J - added for multithreaded support - CRITICAL_SECTION m_csLoadCreate; - // 4J - size of cache is defined by size of one side - must be even - int XZSIZE; - int XZOFFSET; + // 4J - added for multithreaded support + CRITICAL_SECTION m_csLoadCreate; + // 4J - size of cache is defined by size of one side - must be even + int XZSIZE; + int XZOFFSET; public: - ServerChunkCache(ServerLevel *level, ChunkStorage *storage, ChunkSource *source); - virtual ~ServerChunkCache(); + ServerChunkCache(ServerLevel* level, ChunkStorage* storage, + ChunkSource* source); + virtual ~ServerChunkCache(); virtual bool hasChunk(int x, int z); - std::vector *getLoadedChunkList(); + std::vector* getLoadedChunkList(); void drop(int x, int z); - void dropAll(); - virtual LevelChunk *create(int x, int z); - LevelChunk *create(int x, int z, bool asyncPostProcess ); // 4J added - virtual LevelChunk *getChunk(int x, int z); -#ifdef _LARGE_WORLDS - LevelChunk *getChunkLoadedOrUnloaded(int x, int z); // 4J added + void dropAll(); + virtual LevelChunk* create(int x, int z); + LevelChunk* create(int x, int z, bool asyncPostProcess); // 4J added + virtual LevelChunk* getChunk(int x, int z); +#ifdef _LARGE_WORLDS + LevelChunk* getChunkLoadedOrUnloaded(int x, int z); // 4J added #endif - virtual LevelChunk **getCache() { return cache; } // 4J added + virtual LevelChunk** getCache() { return cache; } // 4J added - // 4J-JEV Added; Remove chunk from the toDrop queue. -#ifdef _LARGE_WORLDS - void dontDrop(int x, int z); + // 4J-JEV Added; Remove chunk from the toDrop queue. +#ifdef _LARGE_WORLDS + void dontDrop(int x, int z); #endif private: - LevelChunk *load(int x, int z); - void saveEntities(LevelChunk *levelChunk); - void save(LevelChunk *levelChunk); + LevelChunk* load(int x, int z); + void saveEntities(LevelChunk* levelChunk); + void save(LevelChunk* levelChunk); - void updatePostProcessFlag(short flag, int x, int z, int xo, int zo, LevelChunk *lc); // 4J added - void updatePostProcessFlags(int x, int z); // 4J added - void flagPostProcessComplete(short flag, int x, int z); // 4J added + void updatePostProcessFlag(short flag, int x, int z, int xo, int zo, + LevelChunk* lc); // 4J added + void updatePostProcessFlags(int x, int z); // 4J added + void flagPostProcessComplete(short flag, int x, int z); // 4J added public: - virtual void postProcess(ChunkSource *parent, int x, int z); - + virtual void postProcess(ChunkSource* parent, int x, int z); private: #ifdef _LARGE_WORLDS - static const int MAX_SAVES = 20; + static const int MAX_SAVES = 20; #else - // 4J Stu - Was 24, but lowering it drastically so that we can trickle save chunks - static const int MAX_SAVES = 1; + // 4J Stu - Was 24, but lowering it drastically so that we can trickle save + // chunks + static const int MAX_SAVES = 1; #endif public: - virtual bool saveAllEntities(); - virtual bool save(bool force, ProgressListener *progressListener); + virtual bool saveAllEntities(); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); private: - typedef struct _SaveThreadData - { - ServerChunkCache *cache; - LevelChunk *chunkToSave; - bool saveEntities; - bool useSharedThreadStorage; - C4JThread::Event *notificationEvent; - C4JThread::Event *wakeEvent; // This is a handle to the one fired by the producer thread - } SaveThreadData; + typedef struct _SaveThreadData { + ServerChunkCache* cache; + LevelChunk* chunkToSave; + bool saveEntities; + bool useSharedThreadStorage; + C4JThread::Event* notificationEvent; + C4JThread::Event* wakeEvent; // This is a handle to the one fired by + // the producer thread + } SaveThreadData; public: - static int runSaveThreadProc(void *lpParam); + static int runSaveThreadProc(void* lpParam); }; diff --git a/Minecraft.Client/Network/ServerCommandDispatcher.cpp b/Minecraft.Client/Network/ServerCommandDispatcher.cpp index 205c0f51f..6d86fd41c 100644 --- a/Minecraft.Client/Network/ServerCommandDispatcher.cpp +++ b/Minecraft.Client/Network/ServerCommandDispatcher.cpp @@ -7,69 +7,72 @@ #include "../Commands/TeleportCommand.h" #include "ServerCommandDispatcher.h" -ServerCommandDispatcher::ServerCommandDispatcher() -{ - addCommand(new TimeCommand()); - addCommand(new GameModeCommand()); - addCommand(new DefaultGameModeCommand()); - addCommand(new KillCommand()); - addCommand(new ToggleDownfallCommand()); - addCommand(new ExperienceCommand()); - addCommand(new TeleportCommand()); - addCommand(new GiveItemCommand()); - addCommand(new EnchantItemCommand()); - //addCommand(new EmoteCommand()); - //addCommand(new ShowSeedCommand()); - //addCommand(new HelpCommand()); - //addCommand(new DebugCommand()); - //addCommand(new MessageCommand()); +ServerCommandDispatcher::ServerCommandDispatcher() { + addCommand(new TimeCommand()); + addCommand(new GameModeCommand()); + addCommand(new DefaultGameModeCommand()); + addCommand(new KillCommand()); + addCommand(new ToggleDownfallCommand()); + addCommand(new ExperienceCommand()); + addCommand(new TeleportCommand()); + addCommand(new GiveItemCommand()); + addCommand(new EnchantItemCommand()); + // addCommand(new EmoteCommand()); + // addCommand(new ShowSeedCommand()); + // addCommand(new HelpCommand()); + // addCommand(new DebugCommand()); + // addCommand(new MessageCommand()); - //if (MinecraftServer::getInstance()->isDedicatedServer()) - //{ - // addCommand(new OpCommand()); - // addCommand(new DeOpCommand()); - // addCommand(new StopCommand()); - // addCommand(new SaveAllCommand()); - // addCommand(new SaveOffCommand()); - // addCommand(new SaveOnCommand()); - // addCommand(new BanIpCommand()); - // addCommand(new PardonIpCommand()); - // addCommand(new BanPlayerCommand()); - // addCommand(new ListBansCommand()); - // addCommand(new PardonPlayerCommand()); - // addCommand(new KickCommand()); - // addCommand(new ListPlayersCommand()); - // addCommand(new BroadcastCommand()); - // addCommand(new WhitelistCommand()); - //} - //else - //{ - // addCommand(new PublishLocalServerCommand()); - //} + // if (MinecraftServer::getInstance()->isDedicatedServer()) + //{ + // addCommand(new OpCommand()); + // addCommand(new DeOpCommand()); + // addCommand(new StopCommand()); + // addCommand(new SaveAllCommand()); + // addCommand(new SaveOffCommand()); + // addCommand(new SaveOnCommand()); + // addCommand(new BanIpCommand()); + // addCommand(new PardonIpCommand()); + // addCommand(new BanPlayerCommand()); + // addCommand(new ListBansCommand()); + // addCommand(new PardonPlayerCommand()); + // addCommand(new KickCommand()); + // addCommand(new ListPlayersCommand()); + // addCommand(new BroadcastCommand()); + // addCommand(new WhitelistCommand()); + // } + // else + //{ + // addCommand(new PublishLocalServerCommand()); + // } - // addCommand(new ServerTempDebugCommand()); + // addCommand(new ServerTempDebugCommand()); - Command::setLogger(this); + Command::setLogger(this); } -void ServerCommandDispatcher::logAdminCommand(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message, int customData, const std::wstring& additionalMessage) -{ - PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); - //for (Player player : MinecraftServer.getInstance().getPlayers().players) - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) - { - std::shared_ptr player = *it; - if (player != source && playerList->isOp(player)) - { - // TODO: Change chat packet to be able to send more bits of data - // 4J Stu - Take this out until we can add the name of the player performing the action. Also if the target is a mod then maybe don't need the message? - //player->sendMessage(message, messageType, customData, additionalMessage); - //player->sendMessage("\u00A77\u00A7o[" + source.getName() + ": " + player.localize(message, args) + "]"); - } - } +void ServerCommandDispatcher::logAdminCommand( + std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, const std::wstring& message, + int customData, const std::wstring& additionalMessage) { + PlayerList* playerList = MinecraftServer::getInstance()->getPlayers(); + // for (Player player : MinecraftServer.getInstance().getPlayers().players) + for (AUTO_VAR(it, playerList->players.begin()); + it != playerList->players.end(); ++it) { + std::shared_ptr player = *it; + if (player != source && playerList->isOp(player)) { + // TODO: Change chat packet to be able to send more bits of data + // 4J Stu - Take this out until we can add the name of the player + // performing the action. Also if the target is a mod then maybe + // don't need the message? + // player->sendMessage(message, messageType, customData, + // additionalMessage); player->sendMessage("\u00A77\u00A7o[" + + // source.getName() + ": " + player.localize(message, args) + "]"); + } + } - if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) - { - source->sendMessage(message, messageType, customData, additionalMessage); - } + if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) { + source->sendMessage(message, messageType, customData, + additionalMessage); + } } \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerCommandDispatcher.h b/Minecraft.Client/Network/ServerCommandDispatcher.h index 8f5261914..bd3906018 100644 --- a/Minecraft.Client/Network/ServerCommandDispatcher.h +++ b/Minecraft.Client/Network/ServerCommandDispatcher.h @@ -3,9 +3,12 @@ #include "../../Minecraft.World/Commands/CommandDispatcher.h" #include "../../Minecraft.World/Commands/AdminLogCommand.h" -class ServerCommandDispatcher : public CommandDispatcher, public AdminLogCommand -{ +class ServerCommandDispatcher : public CommandDispatcher, + public AdminLogCommand { public: - ServerCommandDispatcher(); - void logAdminCommand(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L""); + ServerCommandDispatcher(); + void logAdminCommand(std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message = L"", int customData = -1, + const std::wstring& additionalMessage = L""); }; \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerConnection.cpp b/Minecraft.Client/Network/ServerConnection.cpp index bef81d0d6..65801536b 100644 --- a/Minecraft.Client/Network/ServerConnection.cpp +++ b/Minecraft.Client/Network/ServerConnection.cpp @@ -9,196 +9,187 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../Level/MultiPlayerLevel.h" -ServerConnection::ServerConnection(MinecraftServer *server) -{ - // 4J - added initialiser - connectionCounter = 0; - InitializeCriticalSection(&pending_cs); +ServerConnection::ServerConnection(MinecraftServer* server) { + // 4J - added initialiser + connectionCounter = 0; + InitializeCriticalSection(&pending_cs); - this->server = server; + this->server = server; } -ServerConnection::~ServerConnection() -{ - DeleteCriticalSection(&pending_cs); +ServerConnection::~ServerConnection() { DeleteCriticalSection(&pending_cs); } + +// 4J - added to handle incoming connections, to replace thread that original +// used to have +void ServerConnection::NewIncomingSocket(Socket* socket) { + std::shared_ptr unconnectedClient = + std::shared_ptr(new PendingConnection( + server, socket, + L"Connection #" + _toString(connectionCounter++))); + handleConnection(unconnectedClient); } -// 4J - added to handle incoming connections, to replace thread that original used to have -void ServerConnection::NewIncomingSocket(Socket *socket) -{ - std::shared_ptr unconnectedClient = std::shared_ptr(new PendingConnection(server, socket, L"Connection #" + _toString(connectionCounter++))); - handleConnection(unconnectedClient); +void ServerConnection::addPlayerConnection( + std::shared_ptr uc) { + players.push_back(uc); } -void ServerConnection::addPlayerConnection(std::shared_ptr uc) -{ - players.push_back(uc); +void ServerConnection::handleConnection(std::shared_ptr uc) { + EnterCriticalSection(&pending_cs); + pending.push_back(uc); + LeaveCriticalSection(&pending_cs); } -void ServerConnection::handleConnection(std::shared_ptr uc) -{ - EnterCriticalSection(&pending_cs); - pending.push_back(uc); - LeaveCriticalSection(&pending_cs); -} - -void ServerConnection::stop() -{ - EnterCriticalSection(&pending_cs); - for (unsigned int i = 0; i < pending.size(); i++) - { +void ServerConnection::stop() { + EnterCriticalSection(&pending_cs); + for (unsigned int i = 0; i < pending.size(); i++) { std::shared_ptr uc = pending[i]; uc->connection->close(DisconnectPacket::eDisconnect_Closed); } - LeaveCriticalSection(&pending_cs); + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; player->connection->close(DisconnectPacket::eDisconnect_Closed); } } -void ServerConnection::tick() -{ - { - // MGH - changed this so that the the CS lock doesn't cover the tick (was causing a lockup when 2 players tried to join) - EnterCriticalSection(&pending_cs); - std::vector< std::shared_ptr > tempPending = pending; - LeaveCriticalSection(&pending_cs); +void ServerConnection::tick() { + { + // MGH - changed this so that the the CS lock doesn't cover the tick + // (was causing a lockup when 2 players tried to join) + EnterCriticalSection(&pending_cs); + std::vector > tempPending = pending; + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < tempPending.size(); i++) - { - std::shared_ptr uc = tempPending[i]; - // try { // 4J - removed try/catch - uc->tick(); - // } catch (Exception e) { - // uc.disconnect("Internal server error"); - // logger.log(Level.WARNING, "Failed to handle packet: " + e, e); - // } - if(uc->connection != NULL) uc->connection->flush(); - } - } + for (unsigned int i = 0; i < tempPending.size(); i++) { + std::shared_ptr uc = tempPending[i]; + // try { // 4J - removed try/catch + uc->tick(); + // } catch (Exception e) { + // uc.disconnect("Internal server error"); + // logger.log(Level.WARNING, "Failed to handle packet: " + // + e, e); + // } + if (uc->connection != NULL) uc->connection->flush(); + } + } - // now remove from the pending list - EnterCriticalSection(&pending_cs); - for (unsigned int i = 0; i < pending.size(); i++) - if (pending[i]->done) - { - pending.erase(pending.begin()+i); - i--; - } - LeaveCriticalSection(&pending_cs); + // now remove from the pending list + EnterCriticalSection(&pending_cs); + for (unsigned int i = 0; i < pending.size(); i++) + if (pending[i]->done) { + pending.erase(pending.begin() + i); + i--; + } + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - std::shared_ptr serverPlayer = player->getPlayer(); - if( serverPlayer ) - { - serverPlayer->doChunkSendingTick(false); - } -// try { // 4J - removed try/catch - player->tick(); -// } catch (Exception e) { -// logger.log(Level.WARNING, "Failed to handle packet: " + e, e); -// player.disconnect("Internal server error"); -// } - if (player->done) - { - players.erase(players.begin()+i); - i--; + std::shared_ptr serverPlayer = player->getPlayer(); + if (serverPlayer) { + serverPlayer->doChunkSendingTick(false); + } + // try { // 4J - removed try/catch + player->tick(); + // } catch (Exception e) { + // logger.log(Level.WARNING, "Failed to handle packet: " + e, + // e); player.disconnect("Internal server error"); + // } + if (player->done) { + players.erase(players.begin() + i); + i--; } player->connection->flush(); } - } -bool ServerConnection::addPendingTextureRequest(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.push_back(textureName); - return true; - } +bool ServerConnection::addPendingTextureRequest( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it == m_pendingTextureRequests.end()) { + m_pendingTextureRequests.push_back(textureName); + return true; + } - // 4J Stu - We want to request this texture from everyone, if we have a duplicate it's most likely because the first person we asked for it didn't have it - // eg They selected a skin then deleted the skin pack. The side effect of this change is that in certain cases we can send a few more requests, and receive - // a few more responses if people join with the same skin in a short space of time - return true; + // 4J Stu - We want to request this texture from everyone, if we have a + // duplicate it's most likely because the first person we asked for it + // didn't have it eg They selected a skin then deleted the skin pack. The + // side effect of this change is that in certain cases we can send a few + // more requests, and receive a few more responses if people join with the + // same skin in a short space of time + return true; } -void ServerConnection::handleTextureReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } - for (unsigned int i = 0; i < players.size(); i++) - { +void ServerConnection::handleTextureReceived(const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - if (!player->done) - { - player->handleTextureReceived(textureName); + if (!player->done) { + player->handleTextureReceived(textureName); } } } -void ServerConnection::handleTextureAndGeometryReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } - for (unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr player = players[i]; - if (!player->done) - { - player->handleTextureAndGeometryReceived(textureName); - } - } +void ServerConnection::handleTextureAndGeometryReceived( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr player = players[i]; + if (!player->done) { + player->handleTextureAndGeometryReceived(textureName); + } + } } -void ServerConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); +void ServerConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + Minecraft* pMinecraft = Minecraft::GetInstance(); - if(packet->action==ServerSettingsChangedPacket::HOST_DIFFICULTY) - { - for(unsigned int i = 0; i < pMinecraft->levels.length; ++i) - { - if( pMinecraft->levels[i] != NULL ) - { - app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); - pMinecraft->levels[i]->difficulty = packet->data; - } - } - } -// else if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// options -// { -// app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings) -// } -// else -// { -// unsigned char ucData=(unsigned char)packet->data; -// if(ucData&1) -// { -// // hide gamertags -// pMinecraft->options->SetGamertagSetting(true); -// } -// else -// { -// pMinecraft->options->SetGamertagSetting(false); -// } -// -// for (unsigned int i = 0; i < players.size(); i++) -// { -// std::shared_ptr playerconnection = players[i]; -// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); -// } -// } + if (packet->action == ServerSettingsChangedPacket::HOST_DIFFICULTY) { + for (unsigned int i = 0; i < pMinecraft->levels.length; ++i) { + if (pMinecraft->levels[i] != NULL) { + app.DebugPrintf( + "ClientConnection::handleServerSettingsChanged - " + "Difficulty = %d", + packet->data); + pMinecraft->levels[i]->difficulty = packet->data; + } + } + } + // else + // if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// + // options + // { + // app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings) + // } + // else + // { + // unsigned char ucData=(unsigned char)packet->data; + // if(ucData&1) + // { + // // hide gamertags + // pMinecraft->options->SetGamertagSetting(true); + // } + // else + // { + // pMinecraft->options->SetGamertagSetting(false); + // } + // + // for (unsigned int i = 0; i < players.size(); i++) + // { + // std::shared_ptr playerconnection = + // players[i]; + // playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); + // } + // } } \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerConnection.h b/Minecraft.Client/Network/ServerConnection.h index 501315756..77a341df9 100644 --- a/Minecraft.Client/Network/ServerConnection.h +++ b/Minecraft.Client/Network/ServerConnection.h @@ -5,45 +5,52 @@ class MinecraftServer; class Socket; class ServerSettingsChangedPacket; - - -class ServerConnection -{ -// public static Logger logger = Logger.getLogger("Minecraft"); +class ServerConnection { + // public static Logger logger = Logger.getLogger("Minecraft"); private: -// ServerSocket serverSocket; -// private Thread listenThread; + // ServerSocket serverSocket; + // private Thread listenThread; public: - volatile bool running; + volatile bool running; + private: - int connectionCounter; + int connectionCounter; + private: - CRITICAL_SECTION pending_cs; // 4J added - std::vector< std::shared_ptr > pending; - std::vector< std::shared_ptr > players; + CRITICAL_SECTION pending_cs; // 4J added + std::vector > pending; + std::vector > players; - // 4J - When the server requests a texture, it should add it to here while we are waiting for it - std::vector m_pendingTextureRequests; -public: - MinecraftServer *server; + // 4J - When the server requests a texture, it should add it to here while + // we are waiting for it + std::vector m_pendingTextureRequests; public: - ServerConnection(MinecraftServer *server); // 4J - removed params InetAddress address, int port); - ~ServerConnection(); - void NewIncomingSocket(Socket *socket); // 4J - added + MinecraftServer* server; - void removeSpamProtection(Socket *socket) { }// 4J Stu - Not implemented as not required +public: + ServerConnection( + MinecraftServer* + server); // 4J - removed params InetAddress address, int port); + ~ServerConnection(); + void NewIncomingSocket(Socket* socket); // 4J - added + + void removeSpamProtection(Socket* socket) { + } // 4J Stu - Not implemented as not required void addPlayerConnection(std::shared_ptr uc); + private: - void handleConnection(std::shared_ptr uc); + void handleConnection(std::shared_ptr uc); + public: - void stop(); + void stop(); void tick(); - // 4J Added - bool addPendingTextureRequest(const std::wstring &textureName); - void handleTextureReceived(const std::wstring &textureName); - void handleTextureAndGeometryReceived(const std::wstring &textureName); - void handleServerSettingsChanged(std::shared_ptr packet); + // 4J Added + bool addPendingTextureRequest(const std::wstring& textureName); + void handleTextureReceived(const std::wstring& textureName); + void handleTextureAndGeometryReceived(const std::wstring& textureName); + void handleServerSettingsChanged( + std::shared_ptr packet); }; diff --git a/Minecraft.Client/Network/ServerInterface.h b/Minecraft.Client/Network/ServerInterface.h index 883b2106d..55f692c4f 100644 --- a/Minecraft.Client/Network/ServerInterface.h +++ b/Minecraft.Client/Network/ServerInterface.h @@ -1,29 +1,29 @@ #pragma once - -class ServerInterface -{ - virtual int getConfigInt(const std::wstring &name, int defaultValue) = 0; - virtual std::wstring getConfigString(const std::wstring &name, const std::wstring &defaultValue) = 0; - virtual bool getConfigBoolean(const std::wstring &name, bool defaultValue) = 0; - virtual void setProperty(std::wstring &propertyName, void *value) = 0; - virtual void configSave() = 0; - virtual std::wstring getConfigPath() = 0; - virtual std::wstring getServerIp() = 0; - virtual int getServerPort() = 0; - virtual std::wstring getServerName() = 0; - virtual std::wstring getServerVersion() = 0; - virtual int getPlayerCount() = 0; - virtual int getMaxPlayers() = 0; - virtual std::wstring[] getPlayerNames() = 0; - virtual std::wstring getWorldName() = 0; - virtual std::wstring getPluginNames() = 0; - virtual void disablePlugin() = 0; - virtual std::wstring runCommand(const std::wstring &command) = 0; - virtual bool isDebugging() = 0; - // Logging - virtual void info(const std::wstring &string) = 0; - virtual void warn(const std::wstring &string) = 0; - virtual void error(const std::wstring &string) = 0; - virtual void debug(const std::wstring &string) = 0; +class ServerInterface { + virtual int getConfigInt(const std::wstring& name, int defaultValue) = 0; + virtual std::wstring getConfigString(const std::wstring& name, + const std::wstring& defaultValue) = 0; + virtual bool getConfigBoolean(const std::wstring& name, + bool defaultValue) = 0; + virtual void setProperty(std::wstring& propertyName, void* value) = 0; + virtual void configSave() = 0; + virtual std::wstring getConfigPath() = 0; + virtual std::wstring getServerIp() = 0; + virtual int getServerPort() = 0; + virtual std::wstring getServerName() = 0; + virtual std::wstring getServerVersion() = 0; + virtual int getPlayerCount() = 0; + virtual int getMaxPlayers() = 0; + virtual std::wstring[] getPlayerNames() = 0; + virtual std::wstring getWorldName() = 0; + virtual std::wstring getPluginNames() = 0; + virtual void disablePlugin() = 0; + virtual std::wstring runCommand(const std::wstring& command) = 0; + virtual bool isDebugging() = 0; + // Logging + virtual void info(const std::wstring& string) = 0; + virtual void warn(const std::wstring& string) = 0; + virtual void error(const std::wstring& string) = 0; + virtual void debug(const std::wstring& string) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c index 96fe64b4e..b3407dfb4 100644 --- a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c +++ b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c @@ -22,16 +22,15 @@ #define false 0 // Iggy GDraw support functions - normally in the Iggy library, stubbed here -void * IggyGDrawMallocAnnotated(SINTa size, const char *file, int line) { - (void)file; (void)line; +void* IggyGDrawMallocAnnotated(SINTa size, const char* file, int line) { + (void)file; + (void)line; return malloc((size_t)size); } -void IggyGDrawFree(void *ptr) { - free(ptr); -} +void IggyGDrawFree(void* ptr) { free(ptr); } -void IggyGDrawSendWarning(Iggy *f, char const *message, ...) { +void IggyGDrawSendWarning(Iggy* f, char const* message, ...) { (void)f; va_list args; va_start(args, message); @@ -41,8 +40,9 @@ void IggyGDrawSendWarning(Iggy *f, char const *message, ...) { va_end(args); } -void IggyDiscardVertexBufferCallback(void *owner, void *buf) { - (void)owner; (void)buf; +void IggyDiscardVertexBufferCallback(void* owner, void* buf) { + (void)owner; + (void)buf; } /////////////////////////////////////////////////////////////////////////////// @@ -55,61 +55,67 @@ void IggyDiscardVertexBufferCallback(void *owner, void *buf) { // The shared code calls them by name and the real functions are used directly. // -#define GDRAW_GL_EXTENSION_LIST \ -/* identifier import procname */ \ -/* GL_ARB_vertex_buffer_object */ \ -GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \ -GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \ -GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \ -GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \ -GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \ -GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \ -GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \ -GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", ENABLEVERTEXATTRIBARRAYARB) \ -GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", DISABLEVERTEXATTRIBARRAYARB) \ -/* GL_ARB_shader_objects */ \ -GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \ -GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \ -GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \ -GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \ -GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ -GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ -GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \ -GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \ -GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \ -GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \ -GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \ -GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \ -GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ -GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ -GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \ -GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \ -GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \ -/* GL_ARB_vertex_shader */ \ -GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \ -/* Missing from WGL but needed by shared code */ \ -GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \ -/* GL_EXT_framebuffer_object */ \ -GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \ -GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \ -GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \ -GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \ -GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \ -GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \ -GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \ -GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", CHECKFRAMEBUFFERSTATUSEXT) \ -GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", FRAMEBUFFERRENDERBUFFEREXT) \ -GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", FRAMEBUFFERTEXTURE2DEXT) \ -GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \ -/* GL_EXT_framebuffer_blit */ \ -GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \ -/* GL_EXT_framebuffer_multisample */ \ -GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT",RENDERBUFFERSTORAGEMULTISAMPLEEXT) \ -/* */ +#define GDRAW_GL_EXTENSION_LIST \ + /* identifier import procname */ \ + /* GL_ARB_vertex_buffer_object */ \ + GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \ + GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \ + GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \ + GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \ + GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \ + GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \ + GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \ + GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", \ + ENABLEVERTEXATTRIBARRAYARB) \ + GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", \ + DISABLEVERTEXATTRIBARRAYARB) \ + /* GL_ARB_shader_objects */ \ + GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \ + GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \ + GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \ + GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \ + GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ + GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ + GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \ + GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \ + GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \ + GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \ + GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \ + GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \ + GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ + GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ + GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \ + GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \ + GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \ + /* GL_ARB_vertex_shader */ \ + GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \ + /* Missing from WGL but needed by shared code */ \ + GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \ + /* GL_EXT_framebuffer_object */ \ + GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \ + GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \ + GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \ + GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \ + GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \ + GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \ + GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \ + GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", \ + CHECKFRAMEBUFFERSTATUSEXT) \ + GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", \ + FRAMEBUFFERRENDERBUFFEREXT) \ + GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", \ + FRAMEBUFFERTEXTURE2DEXT) \ + GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \ + /* GL_EXT_framebuffer_blit */ \ + GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \ + /* GL_EXT_framebuffer_multisample */ \ + GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT", \ + RENDERBUFFERSTORAGEMULTISAMPLEEXT) \ + /* */ -#define gdraw_GLx_(id) gdraw_GL_##id -#define GDRAW_GLx_(id) GDRAW_GL_##id -#define GDRAW_SHADERS "gdraw_gl_shaders.inl" +#define gdraw_GLx_(id) gdraw_GL_##id +#define GDRAW_GLx_(id) GDRAW_GL_##id +#define GDRAW_SHADERS "gdraw_gl_shaders.inl" // On Linux, GLhandleARB is void* (not GLuint) but the shader functions // actually return/take GLuint values. Use GLuint as our handle type, @@ -123,20 +129,18 @@ typedef gdraw_gl_resourcetype gdraw_resourcetype; GDRAW_GL_EXTENSION_LIST #undef GLE -static void load_extensions(void) -{ - #define GLE(id, import, procname) gl##id = (PFNGL##procname##PROC) SDL_GL_GetProcAddress("gl" import); +static void load_extensions(void) { +#define GLE(id, import, procname) \ + gl##id = (PFNGL##procname##PROC)SDL_GL_GetProcAddress("gl" import); GDRAW_GL_EXTENSION_LIST - #undef GLE +#undef GLE } -static void clear_renderstate_platform_specific(void) -{ +static void clear_renderstate_platform_specific(void) { glDisable(GL_ALPHA_TEST); } -static void error_msg_platform_specific(const char *msg) -{ +static void error_msg_platform_specific(const char* msg) { fprintf(stderr, "[GDraw GL] %s\n", msg); } @@ -151,7 +155,10 @@ static void error_msg_platform_specific(const char *msg) #ifdef RR_BREAK #undef RR_BREAK #endif -#define RR_BREAK() do { fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); } while(0) +#define RR_BREAK() \ + do { \ + fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); \ + } while (0) #include "../../../Windows64/Iggy/gdraw/gdraw_gl_shared.inl" @@ -160,32 +167,42 @@ static void error_msg_platform_specific(const char *msg) // Initialization and platform-specific functionality // -GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) -{ +GDrawFunctions* gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) { static const TextureFormatDesc tex_formats[] = { - { IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, - { IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 }, - { IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0, GL_UNSIGNED_BYTE }, - { 0, 0, 0, 0, 0, 0, 0 }, + {IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA, + GL_UNSIGNED_SHORT_4_4_4_4}, + {IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA, + GL_UNSIGNED_SHORT_5_5_5_1}, + {IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0, + GL_UNSIGNED_BYTE}, + {0, 0, 0, 0, 0, 0, 0}, }; - GDrawFunctions *funcs; - const char *s; + GDrawFunctions* funcs; + const char* s; GLint n; // check for the extensions we need - s = (const char *) glGetString(GL_EXTENSIONS); + s = (const char*)glGetString(GL_EXTENSIONS); if (s == NULL) { - fprintf(stderr, "[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL context not current?\n"); + fprintf(stderr, + "[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL " + "context not current?\n"); assert(s != NULL); return NULL; } @@ -199,8 +216,7 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) !hasext(s, "GL_EXT_framebuffer_object") || !hasext(s, "GL_ARB_shader_objects") || !hasext(s, "GL_ARB_vertex_shader") || - !hasext(s, "GL_ARB_fragment_shader")) - { + !hasext(s, "GL_ARB_fragment_shader")) { fprintf(stderr, "[GDraw GL] Required GL extensions not available\n"); return NULL; } @@ -211,17 +227,17 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) load_extensions(); funcs = create_context(w, h); - if (!funcs) - return NULL; + if (!funcs) return NULL; gdraw->tex_formats = tex_formats; // check for optional extensions - gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL - gdraw->has_depth24 = true; // we just assume. - gdraw->has_texture_max_level = true; // core on regular GL + gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL + gdraw->has_depth24 = true; // we just assume. + gdraw->has_texture_max_level = true; // core on regular GL - if (hasext(s, "GL_EXT_packed_depth_stencil")) gdraw->has_packed_depth_stencil = true; + if (hasext(s, "GL_EXT_packed_depth_stencil")) + gdraw->has_packed_depth_stencil = true; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n); gdraw->has_conditional_non_power_of_two = n < 8192; @@ -234,7 +250,9 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) opengl_check(); - fprintf(stderr, "[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h, msaa_samples); + fprintf(stderr, + "[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h, + msaa_samples); return funcs; } @@ -243,14 +261,15 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) // 4J-specific custom draw functions // -void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) -{ +void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion* region, + F32* matrix) { // Same as BeginCustomDraw but uses different depth param clear_renderstate(); - gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, depth_from_id(0), 1); + gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, + depth_from_id(0), 1); } -void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) -{ +void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion* region, + F32* matrix) { gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, 0.0f, 0); } diff --git a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h index 7210565d2..cd8cc8281 100644 --- a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h +++ b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h @@ -8,35 +8,49 @@ extern "C" { #endif -typedef enum gdraw_gl_resourcetype -{ - GDRAW_GL_RESOURCE_rendertarget, - GDRAW_GL_RESOURCE_texture, - GDRAW_GL_RESOURCE_vertexbuffer, +typedef enum gdraw_gl_resourcetype { + GDRAW_GL_RESOURCE_rendertarget, + GDRAW_GL_RESOURCE_texture, + GDRAW_GL_RESOURCE_vertexbuffer, - GDRAW_GL_RESOURCE__count, + GDRAW_GL_RESOURCE__count, } gdraw_gl_resourcetype; struct IggyCustomDrawCallbackRegion; -extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type, S32 num_handles, S32 num_bytes); -extern GDrawFunctions * gdraw_GL_CreateContext(S32 min_w, S32 min_h, S32 msaa_samples); +extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type, + S32 num_handles, S32 num_bytes); +extern GDrawFunctions* gdraw_GL_CreateContext(S32 min_w, S32 min_h, + S32 msaa_samples); extern void gdraw_GL_DestroyContext(void); -extern void gdraw_GL_SetTileOrigin(S32 vx, S32 vy, unsigned int framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer +extern void gdraw_GL_SetTileOrigin( + S32 vx, S32 vy, + unsigned int + framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer extern void gdraw_GL_NoMoreGDrawThisFrame(void); -extern GDrawTexture *gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle, S32 width, S32 height, int has_mipmaps); -extern void gdraw_GL_WrappedTextureChange(GDrawTexture *tex, S32 new_gl_texture_handle, S32 new_width, S32 new_height, int new_has_mipmaps); -extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture *tex); +extern GDrawTexture* gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle, + S32 width, S32 height, + int has_mipmaps); +extern void gdraw_GL_WrappedTextureChange(GDrawTexture* tex, + S32 new_gl_texture_handle, + S32 new_width, S32 new_height, + int new_has_mipmaps); +extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture* tex); -extern void gdraw_GL_BeginCustomDraw(struct IggyCustomDrawCallbackRegion *region, float *matrix); -extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion *region); +extern void gdraw_GL_BeginCustomDraw( + struct IggyCustomDrawCallbackRegion* region, float* matrix); +extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion* region); -extern void gdraw_GL_CalculateCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); -extern void gdraw_GL_BeginCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); +extern void gdraw_GL_CalculateCustomDraw_4J( + struct IggyCustomDrawCallbackRegion* region, float* matrix); +extern void gdraw_GL_BeginCustomDraw_4J( + struct IggyCustomDrawCallbackRegion* region, float* matrix); -extern GDrawTexture * gdraw_GL_MakeTextureFromResource(unsigned char *resource_file, S32 resource_len, IggyFileTextureRaw *texture); -extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture *tex); +extern GDrawTexture* gdraw_GL_MakeTextureFromResource( + unsigned char* resource_file, S32 resource_len, + IggyFileTextureRaw* texture); +extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture* tex); #ifdef __cplusplus } diff --git a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp index ebb870584..3c82b10a2 100644 --- a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp +++ b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp @@ -2,4 +2,6 @@ #include "LinuxLeaderboardManager.h" -LeaderboardManager *LeaderboardManager::m_instance = new LinuxLeaderboardManager(); //Singleton instance of the LeaderboardManager \ No newline at end of file +LeaderboardManager* LeaderboardManager::m_instance = + new LinuxLeaderboardManager(); // Singleton instance of the + // LeaderboardManager \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h index 50696c37d..641622381 100644 --- a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h +++ b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h @@ -2,35 +2,50 @@ #include "../../Common/Leaderboards/LeaderboardManager.h" -class LinuxLeaderboardManager : public LeaderboardManager -{ +class LinuxLeaderboardManager : public LeaderboardManager { public: - virtual void Tick() {} + virtual void Tick() {} - //Open a session - virtual bool OpenSession() { return true; } + // Open a session + virtual bool OpenSession() { return true; } - //Close a session - virtual void CloseSession() {} + // Close a session + virtual void CloseSession() {} - //Delete a session - virtual void DeleteSession() {} + // Delete a session + virtual void DeleteSession() {} - //Write the given stats - //This is called synchronously and will not free any memory allocated for views when it is done + // Write the given stats + // This is called synchronously and will not free any memory allocated for + // views when it is done - virtual bool WriteStats(unsigned int viewCount, ViewIn views) { return false; } + virtual bool WriteStats(unsigned int viewCount, ViewIn views) { + return false; + } - virtual bool ReadStats_Friends(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID) { return false; } - virtual bool ReadStats_MyScore(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID, unsigned int readCount) { return false; } - virtual bool ReadStats_TopRank(LeaderboardReadListener *callback, int difficulty, EStatsType type, unsigned int startIndex, unsigned int readCount) { return false; } + virtual bool ReadStats_Friends(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + PlayerUID myUID) { + return false; + } + virtual bool ReadStats_MyScore(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + PlayerUID myUID, unsigned int readCount) { + return false; + } + virtual bool ReadStats_TopRank(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + unsigned int startIndex, + unsigned int readCount) { + return false; + } - //Perform a flush of the stats - virtual void FlushStats() {} + // Perform a flush of the stats + virtual void FlushStats() {} - //Cancel the current operation - virtual void CancelOperation() {} + // Cancel the current operation + virtual void CancelOperation() {} - //Is the leaderboard manager idle. - virtual bool isIdle() { return true; } + // Is the leaderboard manager idle. + virtual bool isIdle() { return true; } }; diff --git a/Minecraft.Client/Platform/Linux/LinuxGL.cpp b/Minecraft.Client/Platform/Linux/LinuxGL.cpp index 29d312b35..fd4919b0b 100644 --- a/Minecraft.Client/Platform/Linux/LinuxGL.cpp +++ b/Minecraft.Client/Platform/Linux/LinuxGL.cpp @@ -9,96 +9,81 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/IO/Streams/ByteBuffer.h" - -int glGenTextures() -{ - GLuint id = 0; - ::glGenTextures(1, &id); - return (int)id; +int glGenTextures() { + GLuint id = 0; + ::glGenTextures(1, &id); + return (int)id; } -void glGenTextures(IntBuffer *buf) -{ - GLuint id = 0; - ::glGenTextures(1, &id); - buf->put((int)id); - buf->flip(); +void glGenTextures(IntBuffer* buf) { + GLuint id = 0; + ::glGenTextures(1, &id); + buf->put((int)id); + buf->flip(); } -void glDeleteTextures(int id) -{ - GLuint uid = (GLuint)id; - ::glDeleteTextures(1, &uid); +void glDeleteTextures(int id) { + GLuint uid = (GLuint)id; + ::glDeleteTextures(1, &uid); } -void glDeleteTextures(IntBuffer *buf) -{ - int id = buf->get(0); - GLuint uid = (GLuint)id; - ::glDeleteTextures(1, &uid); +void glDeleteTextures(IntBuffer* buf) { + int id = buf->get(0); + GLuint uid = (GLuint)id; + ::glDeleteTextures(1, &uid); } -void glLight(int light, int pname, FloatBuffer *params) -{ - ::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer()); +void glLight(int light, int pname, FloatBuffer* params) { + ::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer()); } -void glLightModel(int pname, FloatBuffer *params) -{ - ::glLightModelfv((GLenum)pname, params->_getDataPointer()); +void glLightModel(int pname, FloatBuffer* params) { + ::glLightModelfv((GLenum)pname, params->_getDataPointer()); } -void glGetFloat(int pname, FloatBuffer *params) -{ - ::glGetFloatv((GLenum)pname, params->_getDataPointer()); +void glGetFloat(int pname, FloatBuffer* params) { + ::glGetFloatv((GLenum)pname, params->_getDataPointer()); } -void glTexGen(int coord, int pname, FloatBuffer *params) -{ - ::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer()); +void glTexGen(int coord, int pname, FloatBuffer* params) { + ::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer()); } -void glFog(int pname, FloatBuffer *params) -{ - ::glFogfv((GLenum)pname, params->_getDataPointer()); +void glFog(int pname, FloatBuffer* params) { + ::glFogfv((GLenum)pname, params->_getDataPointer()); } -void glTexCoordPointer(int size, int type, FloatBuffer *pointer) -{ - ::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); +void glTexCoordPointer(int size, int type, FloatBuffer* pointer) { + ::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); } -void glNormalPointer(int type, ByteBuffer *pointer) -{ - ::glNormalPointer((GLenum)type, 0, pointer->getBuffer()); +void glNormalPointer(int type, ByteBuffer* pointer) { + ::glNormalPointer((GLenum)type, 0, pointer->getBuffer()); } -void glColorPointer(int size, bool normalized, int stride, ByteBuffer *pointer) -{ - (void)normalized; - ::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer()); +void glColorPointer(int size, bool normalized, int stride, + ByteBuffer* pointer) { + (void)normalized; + ::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer()); } -void glVertexPointer(int size, int type, FloatBuffer *pointer) -{ - ::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); +void glVertexPointer(int size, int type, FloatBuffer* pointer) { + ::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); } -void glEndList(int) -{ - ::glEndList(); +void glEndList(int) { ::glEndList(); } + +void glTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int format, int type, + ByteBuffer* pixels) { + void* data = pixels ? pixels->getBuffer() : nullptr; + ::glTexImage2D((GLenum)target, level, internalformat, width, height, border, + (GLenum)format, (GLenum)type, data); } -void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer *pixels) -{ - void *data = pixels ? pixels->getBuffer() : nullptr; - ::glTexImage2D((GLenum)target, level, internalformat, width, height, border, (GLenum)format, (GLenum)type, data); -} - -void glCallLists(IntBuffer *lists) -{ - int count = lists->limit() - lists->position(); - ::glCallLists(count, GL_INT, lists->getBuffer()); +void glCallLists(IntBuffer* lists) { + int count = lists->limit() - lists->position(); + ::glCallLists(count, GL_INT, lists->getBuffer()); } static PFNGLGENQUERIESARBPROC _glGenQueriesARB = nullptr; @@ -107,55 +92,52 @@ static PFNGLENDQUERYARBPROC _glEndQueryARB = nullptr; static PFNGLGETQUERYOBJECTUIVARBPROC _glGetQueryObjectuivARB = nullptr; static bool _queriesInitialized = false; -static void initQueryFuncs() -{ - if (_queriesInitialized) return; - _queriesInitialized = true; - _glGenQueriesARB = (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB"); - _glBeginQueryARB = (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB"); - _glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB"); - _glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym(RTLD_DEFAULT, "glGetQueryObjectuivARB"); +static void initQueryFuncs() { + if (_queriesInitialized) return; + _queriesInitialized = true; + _glGenQueriesARB = + (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB"); + _glBeginQueryARB = + (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB"); + _glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB"); + _glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym( + RTLD_DEFAULT, "glGetQueryObjectuivARB"); } -void glGenQueriesARB(IntBuffer *buf) -{ - initQueryFuncs(); - if (_glGenQueriesARB) - { - GLuint id = 0; - _glGenQueriesARB(1, &id); - buf->put((int)id); - buf->flip(); - } +void glGenQueriesARB(IntBuffer* buf) { + initQueryFuncs(); + if (_glGenQueriesARB) { + GLuint id = 0; + _glGenQueriesARB(1, &id); + buf->put((int)id); + buf->flip(); + } } -void glBeginQueryARB(int target, int id) -{ - initQueryFuncs(); - if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id); +void glBeginQueryARB(int target, int id) { + initQueryFuncs(); + if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id); } -void glEndQueryARB(int target) -{ - initQueryFuncs(); - if (_glEndQueryARB) _glEndQueryARB((GLenum)target); +void glEndQueryARB(int target) { + initQueryFuncs(); + if (_glEndQueryARB) _glEndQueryARB((GLenum)target); } -void glGetQueryObjectuARB(int id, int pname, IntBuffer *params) -{ - initQueryFuncs(); - if (_glGetQueryObjectuivARB) - { - GLuint val = 0; - _glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val); - params->put((int)val); - params->flip(); - } +void glGetQueryObjectuARB(int id, int pname, IntBuffer* params) { + initQueryFuncs(); + if (_glGetQueryObjectuivARB) { + GLuint val = 0; + _glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val); + params->put((int)val); + params->flip(); + } } -void glReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer *pixels) -{ - ::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type, pixels->getBuffer()); +void glReadPixels(int x, int y, int width, int height, int format, int type, + ByteBuffer* pixels) { + ::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type, + pixels->getBuffer()); } #endif diff --git a/Minecraft.Client/Platform/Linux/Linux_App.cpp b/Minecraft.Client/Platform/Linux/Linux_App.cpp index 332537d07..0193d2840 100644 --- a/Minecraft.Client/Platform/Linux/Linux_App.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_App.cpp @@ -13,64 +13,55 @@ CConsoleMinecraftApp app; -#define CONTEXT_GAME_STATE 0 +#define CONTEXT_GAME_STATE 0 -CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() -{ +CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() {} + +void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) { + ProfileManager.SetRichPresenceContextValue(iPad, CONTEXT_GAME_STATE, + contextId); } -void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) -{ - ProfileManager.SetRichPresenceContextValue(iPad,CONTEXT_GAME_STATE,contextId); -} - -void CConsoleMinecraftApp::StoreLaunchData() -{ -} -void CConsoleMinecraftApp::ExitGame() -{ -} -void CConsoleMinecraftApp::FatalLoadError() -{ - app.DebugPrintf("CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n"); +void CConsoleMinecraftApp::StoreLaunchData() {} +void CConsoleMinecraftApp::ExitGame() {} +void CConsoleMinecraftApp::FatalLoadError() { + app.DebugPrintf( + "CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n"); assert(0); } -void CConsoleMinecraftApp::CaptureSaveThumbnail() -{ -} -void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize) -{ -} -void CConsoleMinecraftApp::ReleaseSaveThumbnail() -{ -} +void CConsoleMinecraftApp::CaptureSaveThumbnail() {} +void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t** thumbnailData, + unsigned int* thumbnailSize) {} +void CConsoleMinecraftApp::ReleaseSaveThumbnail() {} -void CConsoleMinecraftApp::GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize) -{ -} +void CConsoleMinecraftApp::GetScreenshot(int iPad, + std::uint8_t** screenshotData, + unsigned int* screenshotSize) {} -void CConsoleMinecraftApp::TemporaryCreateGameStart() -{ - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit +void CConsoleMinecraftApp::TemporaryCreateGameStart() { + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_Main::OnInit app.setLevelGenerationOptions(NULL); // From CScene_Main::RunPlayGame - Minecraft *pMinecraft=Minecraft::GetInstance(); + Minecraft* pMinecraft = Minecraft::GetInstance(); app.ReleaseSaveThumbnail(); ProfileManager.SetLockedProfile(0); pMinecraft->user->name = L"Windows"; app.ApplyGameSettingsChanged(0); - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameJoinLoad::OnInit + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_MultiGameJoinLoad::OnInit MinecraftServer::resetFlags(); // From CScene_MultiGameJoinLoad::OnNotifyPressEx - app.SetTutorialMode( false ); + app.SetTutorialMode(false); app.SetCorruptSaveDeleted(false); - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameCreate::CreateGame + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_MultiGameCreate::CreateGame app.ClearTerrainFeaturePosition(); std::wstring wWorldName = L"TestWorld"; @@ -79,60 +70,62 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() StorageManager.SetSaveTitle(wWorldName.c_str()); bool isFlat = false; - __int64 seedValue = 0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal); // 4J - was (new Random())->nextLong() - now trying to actually find a seed to suit our requirements + __int64 seedValue = + 0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal); + // // 4J - was (new Random())->nextLong() - now trying to actually + // find a seed to suit our requirements - NetworkGameInitData *param = new NetworkGameInitData(); + NetworkGameInitData* param = new NetworkGameInitData(); param->seed = seedValue; param->saveData = NULL; - app.SetGameHostOption(eGameHostOption_Difficulty,0); - app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); - app.SetGameHostOption(eGameHostOption_Gamertags,1); - app.SetGameHostOption(eGameHostOption_BedrockFog,1); + app.SetGameHostOption(eGameHostOption_Difficulty, 0); + app.SetGameHostOption(eGameHostOption_FriendsOfFriends, 0); + app.SetGameHostOption(eGameHostOption_Gamertags, 1); + app.SetGameHostOption(eGameHostOption_BedrockFog, 1); - app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId() ); // LevelSettings::GAMETYPE_SURVIVAL - app.SetGameHostOption(eGameHostOption_LevelType, 0 ); - app.SetGameHostOption(eGameHostOption_Structures, 1 ); - app.SetGameHostOption(eGameHostOption_BonusChest, 0 ); + app.SetGameHostOption( + eGameHostOption_GameType, + GameType::CREATIVE->getId()); // LevelSettings::GAMETYPE_SURVIVAL + app.SetGameHostOption(eGameHostOption_LevelType, 0); + app.SetGameHostOption(eGameHostOption_Structures, 1); + app.SetGameHostOption(eGameHostOption_BonusChest, 0); app.SetGameHostOption(eGameHostOption_PvP, 1); - app.SetGameHostOption(eGameHostOption_TrustPlayers, 1 ); - app.SetGameHostOption(eGameHostOption_FireSpreads, 1 ); - app.SetGameHostOption(eGameHostOption_TNT, 1 ); + app.SetGameHostOption(eGameHostOption_TrustPlayers, 1); + app.SetGameHostOption(eGameHostOption_FireSpreads, 1); + app.SetGameHostOption(eGameHostOption_TNT, 1); app.SetGameHostOption(eGameHostOption_HostCanFly, 1); app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1); - app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1 ); + app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1); - param->settings = app.GetGameHostOption( eGameHostOption_All ); + param->settings = app.GetGameHostOption(eGameHostOption_All); g_NetworkManager.FakeLocalPlayerJoined(); - LoadingInputParams *loadingParams = new LoadingInputParams(); + LoadingInputParams* loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; loadingParams->lpParam = (LPVOID)param; // Reset the autosave time app.SetAutosaveTimerTime(); - C4JThread* thread = new C4JThread(loadingParams->func, loadingParams->lpParam, "RunNetworkGame"); + C4JThread* thread = new C4JThread(loadingParams->func, + loadingParams->lpParam, "RunNetworkGame"); thread->Run(); } -int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT) -{ +int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR* wchTMSFile, + bool bFilenameIncludesExtension, + eFileExtensionType eEXT) { return -1; } -int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile) -{ +int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile) { return -1; } + +int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile, + eFileExtensionType eExt) { return -1; } -int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt) -{ - return -1; -} - -void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) -{ -} +void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) {} diff --git a/Minecraft.Client/Platform/Linux/Linux_App.h b/Minecraft.Client/Platform/Linux/Linux_App.h index f15afd928..bdbe65d95 100644 --- a/Minecraft.Client/Platform/Linux/Linux_App.h +++ b/Minecraft.Client/Platform/Linux/Linux_App.h @@ -1,34 +1,38 @@ #pragma once -class CConsoleMinecraftApp : public CMinecraftApp -{ +class CConsoleMinecraftApp : public CMinecraftApp { public: - CConsoleMinecraftApp(); + CConsoleMinecraftApp(); - virtual void SetRichPresenceContext(int iPad, int contextId); + virtual void SetRichPresenceContext(int iPad, int contextId); - virtual void StoreLaunchData(); - virtual void ExitGame(); - virtual void FatalLoadError(); + virtual void StoreLaunchData(); + virtual void ExitGame(); + virtual void FatalLoadError(); - virtual void CaptureSaveThumbnail(); - virtual void GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize); - virtual void ReleaseSaveThumbnail(); - virtual void GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize); + virtual void CaptureSaveThumbnail(); + virtual void GetSaveThumbnail(std::uint8_t** thumbnailData, + unsigned int* thumbnailSize); + virtual void ReleaseSaveThumbnail(); + virtual void GetScreenshot(int iPad, std::uint8_t** screenshotData, + unsigned int* screenshotSize); - virtual int LoadLocalTMSFile(WCHAR *wchTMSFile); - virtual int LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt); + virtual int LoadLocalTMSFile(WCHAR* wchTMSFile); + virtual int LoadLocalTMSFile(WCHAR* wchTMSFile, eFileExtensionType eExt); - virtual void FreeLocalTMSFiles(eTMSFileType eType); - virtual int GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT=eFileExtensionType_PNG); + virtual void FreeLocalTMSFiles(eTMSFileType eType); + virtual int GetLocalTMSFileIndex( + WCHAR* wchTMSFile, bool bFilenameIncludesExtension, + eFileExtensionType eEXT = eFileExtensionType_PNG); - // BANNED LEVEL LIST - virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} + // BANNED LEVEL LIST + virtual void ReadBannedList(int iPad, eTMSAction action = (eTMSAction)0, + bool bCallback = false) {} - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable* GetStringTable() { return NULL; } - // original code - virtual void TemporaryCreateGameStart(); + // original code + virtual void TemporaryCreateGameStart(); }; extern CConsoleMinecraftApp app; diff --git a/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp b/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp index 14729679c..58087546d 100644 --- a/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp @@ -4,7 +4,7 @@ #include "../../../Minecraft.World/Platform/stdafx.h" #include -//#include +// #include #include #if defined(__linux__) && defined(__GLIBC__) #include @@ -12,20 +12,29 @@ #include static void sigsegv_handler(int sig) { const char msg[] = "\n=== SIGNAL CAUGHT: "; - write(STDERR_FILENO, msg, sizeof(msg)-1); + write(STDERR_FILENO, msg, sizeof(msg) - 1); char signum[8]; int len = 0; int s = sig; - if (s == 0) { signum[len++] = '0'; } - else { char tmp[8]; int tl = 0; while(s > 0) { tmp[tl++] = '0' + (s%10); s /= 10; } for(int i = tl-1; i >= 0; i--) signum[len++] = tmp[i]; } + if (s == 0) { + signum[len++] = '0'; + } else { + char tmp[8]; + int tl = 0; + while (s > 0) { + tmp[tl++] = '0' + (s % 10); + s /= 10; + } + for (int i = tl - 1; i >= 0; i--) signum[len++] = tmp[i]; + } write(STDERR_FILENO, signum, len); const char msg1b[] = " ===\n"; - write(STDERR_FILENO, msg1b, sizeof(msg1b)-1); - void *array[64]; + write(STDERR_FILENO, msg1b, sizeof(msg1b) - 1); + void* array[64]; int size = backtrace(array, 64); backtrace_symbols_fd(array, size, STDERR_FILENO); const char msg2[] = "=== END BACKTRACE ===\n"; - write(STDERR_FILENO, msg2, sizeof(msg2)-1); + write(STDERR_FILENO, msg2, sizeof(msg2) - 1); _exit(139); } #endif @@ -49,10 +58,10 @@ static void sigsegv_handler(int sig) { #include "../../../Minecraft.World/Util/ThreadName.h" #include "../../GameState/StatsCounter.h" #include "../../UI/Screens/ConnectScreen.h" -//#include "../Durango/Social/SocialManager.h" -//#include "../Common/Leaderboards/LeaderboardManager.h" -//#include "../Common/XUI/XUI_Scene_Container.h" -//#include "NetworkManager.h" +// #include "../Durango/Social/SocialManager.h" +// #include "../Common/Leaderboards/LeaderboardManager.h" +// #include "../Common/XUI/XUI_Scene_Container.h" +// #include "NetworkManager.h" #include "../../Rendering/Tesselator.h" #include "../../GameState/Options.h" #include "../Orbis/Sentient/SentientManager.h" @@ -65,195 +74,348 @@ static void sigsegv_handler(int sig) { // #include "../Orbis/Network/Orbis_NPToolkit.h" // #include "../Orbis/Network/SonyVoiceChat_Orbis.h" -#define THEME_NAME "584111F70AAAAAAA" -#define THEME_FILESIZE 2797568 +#define THEME_NAME "584111F70AAAAAAA" +#define THEME_FILESIZE 2797568 -//#define THREE_MB 3145728 // minimum save size (checking for this on a selected device) -//#define FIVE_MB 5242880 // minimum save size (checking for this on a selected device) -//#define FIFTY_TWO_MB (1024*1024*52) // Maximum TCR space required for a save (checking for this on a selected device) -#define FIFTY_ONE_MB (1000000*51) // Maximum TCR space required for a save is 52MB (checking for this on a selected device) +// #define THREE_MB 3145728 // minimum save size (checking for this on a +// selected device) #define FIVE_MB 5242880 // minimum save size (checking for +// this on a selected device) #define FIFTY_TWO_MB (1024*1024*52) // Maximum TCR +// space required for a save (checking for this on a selected device) +#define FIFTY_ONE_MB \ + (1000000 * 51) // Maximum TCR space required for a save is 52MB (checking + // for this on a selected device) -//#define PROFILE_VERSION 3 // new version for the interim bug fix 166 TU -#define NUM_PROFILE_VALUES 5 +// #define PROFILE_VERSION 3 // new version for the interim bug fix 166 TU +#define NUM_PROFILE_VALUES 5 #define NUM_PROFILE_SETTINGS 4 -DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= -{ - #ifdef _XBOX +DWORD dwProfileSettingsA[NUM_PROFILE_VALUES] = { +#ifdef _XBOX XPROFILE_OPTION_CONTROLLER_VIBRATION, XPROFILE_GAMER_YAXIS_INVERSION, XPROFILE_GAMER_CONTROL_SENSITIVITY, XPROFILE_GAMER_ACTION_MOVEMENT_CONTROL, XPROFILE_TITLE_SPECIFIC1, - #else - 0,0,0,0,0 - #endif +#else + 0, 0, 0, 0, 0 +#endif }; //------------------------------------------------------------------------------------- -// Time Since fAppTime is a float, we need to keep the quadword app time -// as a LARGE_INTEGER so that we don't lose precision after running -// for a long time. +// Time Since fAppTime is a float, we need to keep the quadword app +// time +// as a LARGE_INTEGER so that we don't lose precision after +// running for a long time. //------------------------------------------------------------------------------------- // functions for storing and converting rich presence strings from wchar to utf8 -uint8_t * AddRichPresenceString(int iID); +uint8_t* AddRichPresenceString(int iID); void FreeRichPresenceStrings(); BOOL g_bWidescreen = TRUE; - -void DefineActions(void) -{ - // The app needs to define the actions required, and the possible mappings for these +void DefineActions(void) { + // The app needs to define the actions required, and the possible mappings + // for these // Split into Menu actions, and in-game actions - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); } #if 0 @@ -299,29 +461,27 @@ pd3dPP, ppDevice ); } #endif -//#define MEMORY_TRACKING +// #define MEMORY_TRACKING #ifdef MEMORY_TRACKING void ResetMem(); void DumpMem(); void MemPixStuff(); #else -void MemSect(int sect) -{ -} +void MemSect(int sect) {} #endif #ifndef __linux__ -HINSTANCE g_hInst = NULL; -HWND g_hWnd = NULL; -D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; -D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; -ID3D11Device* g_pd3dDevice = NULL; -ID3D11DeviceContext* g_pImmediateContext = NULL; -IDXGISwapChain* g_pSwapChain = NULL; +HINSTANCE g_hInst = NULL; +HWND g_hWnd = NULL; +D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; +D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; +ID3D11Device* g_pd3dDevice = NULL; +ID3D11DeviceContext* g_pImmediateContext = NULL; +IDXGISwapChain* g_pSwapChain = NULL; ID3D11RenderTargetView* g_pRenderTargetView = NULL; ID3D11DepthStencilView* g_pDepthStencilView = NULL; -ID3D11Texture2D* g_pDepthStencilBuffer = NULL; +ID3D11Texture2D* g_pDepthStencilBuffer = NULL; // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) @@ -333,20 +493,18 @@ ID3D11Texture2D* g_pDepthStencilBuffer = NULL; // WM_DESTROY - post a quit message and return // // -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ +LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; - switch (message) - { + switch (message) { case WM_COMMAND: - wmId = LOWORD(wParam); + wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: - switch (wmId) - { + switch (wmId) { case IDM_EXIT: DestroyWindow(hWnd); break; @@ -354,43 +512,41 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) return DefWindowProc(hWnd, message, wParam, lParam); } break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - // TODO: Add any drawing code here... - EndPaint(hWnd, &ps); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + // TODO: Add any drawing code here... + EndPaint(hWnd, &ps); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + default: + return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } - // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // -ATOM MyRegisterClass(HINSTANCE hInstance) -{ +ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = WndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hInstance; - wcex.hIcon = LoadIcon(hInstance, "Minecraft"); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = "Minecraft"; - wcex.lpszClassName = "MinecraftClass"; - wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = LoadIcon(hInstance, "Minecraft"); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wcex.lpszMenuName = "Minecraft"; + wcex.lpszClassName = "MinecraftClass"; + wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } @@ -405,15 +561,14 @@ ATOM MyRegisterClass(HINSTANCE hInstance) // In this function, we save the instance handle in a global variable and // create and display the main program window. // -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) -{ - g_hInst = hInstance; // Store instance handle in our global variable +BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { + g_hInst = hInstance; // Store instance handle in our global variable g_hWnd = CreateWindow("MinecraftClass", "Minecraft", WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); + CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, + hInstance, NULL); - if (!g_hWnd) - { + if (!g_hWnd) { return FALSE; } @@ -423,42 +578,38 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) return TRUE; } - //-------------------------------------------------------------------------------------- // Create Direct3D device and swap chain //-------------------------------------------------------------------------------------- -HRESULT InitDevice() -{ +HRESULT InitDevice() { HRESULT hr = S_OK; RECT rc; - GetClientRect( g_hWnd, &rc ); + GetClientRect(g_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; - #ifdef _DEBUG +#ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; - #endif +#endif - D3D_DRIVER_TYPE driverTypes[] = - { + D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; - UINT numDriverTypes = ARRAYSIZE( driverTypes ); + UINT numDriverTypes = ARRAYSIZE(driverTypes); - D3D_FEATURE_LEVEL featureLevels[] = - { + D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; - UINT numFeatureLevels = ARRAYSIZE( featureLevels ); + UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory( &sd, sizeof( sd ) ); + ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; @@ -471,22 +622,22 @@ HRESULT InitDevice() sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; - for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) - { + for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; + driverTypeIndex++) { g_driverType = driverTypes[driverTypeIndex]; - hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, - D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); - if( HRESULT_SUCCEEDED( hr ) ) - break; + hr = D3D11CreateDeviceAndSwapChain( + NULL, g_driverType, NULL, createDeviceFlags, featureLevels, + numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, + &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext); + if (HRESULT_SUCCEEDED(hr)) break; } - if( FAILED( hr ) ) - return hr; + if (FAILED(hr)) return hr; // Create a render target view ID3D11Texture2D* pBackBuffer = NULL; - hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); - if( FAILED( hr ) ) - return hr; + hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), + (LPVOID*)&pBackBuffer); + if (FAILED(hr)) return hr; // Create a depth stencil buffer D3D11_TEXTURE2D_DESC descDepth; @@ -502,21 +653,24 @@ HRESULT InitDevice() descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; - hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); + hr = + g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); D3D11_DEPTH_STENCIL_VIEW_DESC descDSView; descDSView.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDSView.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSView.Texture2D.MipSlice = 0; - hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); + hr = g_pd3dDevice->CreateDepthStencilView( + g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); - hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); + hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, + &g_pRenderTargetView); pBackBuffer->Release(); - if( FAILED( hr ) ) - return hr; + if (FAILED(hr)) return hr; - g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView ); + g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, + g_pDepthStencilView); // Setup the viewport D3D11_VIEWPORT vp; @@ -526,54 +680,48 @@ HRESULT InitDevice() vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; - g_pImmediateContext->RSSetViewports( 1, &vp ); + g_pImmediateContext->RSSetViewports(1, &vp); RenderManager.Initialise(g_pd3dDevice, g_pSwapChain); return S_OK; } - //-------------------------------------------------------------------------------------- // Render the frame //-------------------------------------------------------------------------------------- -void Render() -{ +void Render() { // Just clear the backbuffer - float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red,green,blue,alpha + float ClearColor[4] = {0.0f, 0.125f, 0.3f, 1.0f}; // red,green,blue,alpha - g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor ); - g_pSwapChain->Present( 0, 0 ); + g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, ClearColor); + g_pSwapChain->Present(0, 0); } - //-------------------------------------------------------------------------------------- // Clean up the objects we've created //-------------------------------------------------------------------------------------- -void CleanupDevice() -{ - if( g_pImmediateContext ) g_pImmediateContext->ClearState(); +void CleanupDevice() { + if (g_pImmediateContext) g_pImmediateContext->ClearState(); - if( g_pRenderTargetView ) g_pRenderTargetView->Release(); - if( g_pSwapChain ) g_pSwapChain->Release(); - if( g_pImmediateContext ) g_pImmediateContext->Release(); - if( g_pd3dDevice ) g_pd3dDevice->Release(); + if (g_pRenderTargetView) g_pRenderTargetView->Release(); + if (g_pSwapChain) g_pSwapChain->Release(); + if (g_pImmediateContext) g_pImmediateContext->Release(); + if (g_pd3dDevice) g_pd3dDevice->Release(); } #endif -int StartMinecraftThreadProc( void* lpParameter ) -{ +int StartMinecraftThreadProc(void* lpParameter) { Vec3::UseDefaultThreadStorage(); AABB::UseDefaultThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); + Tesselator::CreateNewThreadStorage(1024 * 1024); RenderManager.InitialiseContext(); - Minecraft::start(std::wstring(),std::wstring()); + Minecraft::start(std::wstring(), std::wstring()); delete Tesselator::getInstance(); return 0; } -int main(int argc, const char *argv[] ) -{ +int main(int argc, const char* argv[]) { #if defined(__linux__) && defined(__GLIBC__) struct sigaction sa; sa.sa_handler = sigsegv_handler; @@ -602,13 +750,11 @@ int main(int argc, const char *argv[] ) reqH = atoi(argv[++i]); } } - if (reqW > 0 && reqH > 0) - RenderManager.SetWindowSize(reqW, reqH); - if (fs) - RenderManager.SetFullscreen(true); + if (reqW > 0 && reqH > 0) RenderManager.SetWindowSize(reqW, reqH); + if (fs) RenderManager.SetFullscreen(true); } - #if 0 +#if 0 // Main message loop MSG msg = {0}; while( WM_QUIT != msg.message ) @@ -627,13 +773,14 @@ Render(); return (int) msg.wParam; #endif -static bool bTrialTimerDisplayed=true; + static bool bTrialTimerDisplayed = true; #ifdef MEMORY_TRACKING -ResetMem(); -MEMORYSTATUS memStat; -GlobalMemoryStatus(&memStat); -printf("RESETMEM start: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); + ResetMem(); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("RESETMEM start: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); #endif #if 0 @@ -661,180 +808,188 @@ return -1; #endif -RenderManager.Initialise(); + RenderManager.Initialise(); -// Read the file containing the product codes -app.DebugPrintf("---ReadProductCodes()\n"); + // Read the file containing the product codes + app.DebugPrintf("---ReadProductCodes()\n"); -app.loadMediaArchive(); -app.loadStringTable(); + app.loadMediaArchive(); + app.loadStringTable(); // fuck you ui.init(1920, 1080); -// storage manager is needed for the trial key check -StorageManager.Init(0,app.GetString(IDS_DEFAULT_SAVENAME),(char*)"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,(LPVOID)&app,(char*)""); + // storage manager is needed for the trial key check + StorageManager.Init(0, app.GetString(IDS_DEFAULT_SAVENAME), + (char*)"savegame.dat", FIFTY_ONE_MB, + &CConsoleMinecraftApp::DisplaySavingMessage, + (LPVOID)&app, (char*)""); -//////////////// -// Initialise // -//////////////// + //////////////// + // Initialise // + //////////////// -app.InitTime(); + app.InitTime(); -// Set the number of possible joypad layouts that the user can switch between, and the number of actions -InputManager.Initialise(1,5,MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); + // Set the number of possible joypad layouts that the user can switch + // between, and the number of actions + InputManager.Initialise(1, 5, MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); -// Set the default joypad action mappings for Minecraft -DefineActions(); -InputManager.SetJoypadMapVal(0,0); -InputManager.SetKeyRepeatRate(0.3f,0.2f); + // Set the default joypad action mappings for Minecraft + DefineActions(); + InputManager.SetJoypadMapVal(0, 0); + InputManager.SetKeyRepeatRate(0.3f, 0.2f); -// Initialise the profile manager with the game Title ID, Offer ID, a profile version number, and the number of profile values and settings + // Initialise the profile manager with the game Title ID, Offer ID, a + // profile version number, and the number of profile values and settings -ProfileManager.Initialise(TITLEID_MINECRAFT, - app.m_dwOfferID, - PROFILE_VERSION_10, - NUM_PROFILE_VALUES, - NUM_PROFILE_SETTINGS, - dwProfileSettingsA, - app.GAME_DEFINED_PROFILE_DATA_BYTES*XUSER_MAX_COUNT, - &app.uiGameDefinedDataChangedBitmask -); + ProfileManager.Initialise( + TITLEID_MINECRAFT, app.m_dwOfferID, PROFILE_VERSION_10, + NUM_PROFILE_VALUES, NUM_PROFILE_SETTINGS, dwProfileSettingsA, + app.GAME_DEFINED_PROFILE_DATA_BYTES * XUSER_MAX_COUNT, + &app.uiGameDefinedDataChangedBitmask); -// set a function to be called when there's a sign in change, so we can exit a level if the primary player signs out -ProfileManager.SetSignInChangeCallback(&CConsoleMinecraftApp::SignInChangeCallback, &app); + // set a function to be called when there's a sign in change, so we can exit + // a level if the primary player signs out + ProfileManager.SetSignInChangeCallback( + &CConsoleMinecraftApp::SignInChangeCallback, &app); -// Set a callback for when there is a read error on profile data -//StorageManager.SetProfileReadErrorCallback(&CConsoleMinecraftApp::ProfileReadErrorCallback, &app); + // Set a callback for when there is a read error on profile data + // StorageManager.SetProfileReadErrorCallback(&CConsoleMinecraftApp::ProfileReadErrorCallback, + // &app); + // QNet needs to be setup after profile manager, as we do not want its + // Notify listener to handle XN_SYS_SIGNINCHANGED notifications. This does + // mean that we need to have a callback in the ProfileManager for + // XN_LIVE_INVITE_ACCEPTED for QNet. -// QNet needs to be setup after profile manager, as we do not want its Notify listener to handle -// XN_SYS_SIGNINCHANGED notifications. This does mean that we need to have a callback in the -// ProfileManager for XN_LIVE_INVITE_ACCEPTED for QNet. - -g_NetworkManager.Initialise(); - -// debug switch to trial version -ProfileManager.SetDebugFullOverride(true); -// Initialise TLS for tesselator, for this main thread -Tesselator::CreateNewThreadStorage(1024*1024); -// Initialise TLS for AABB and Vec3 pools, for this main thread -AABB::CreateNewThreadStorage(); -Vec3::CreateNewThreadStorage(); -IntCache::CreateNewThreadStorage(); -Compression::CreateNewThreadStorage(); -OldChunkStorage::CreateNewThreadStorage(); -Level::enableLightingCache(); -Tile::CreateNewThreadStorage(); - -Minecraft::main(); - -// Minecraft::main () used to call Minecraft::Start, but this takes ~2.5 seconds, so now running this in another thread -// so we can do some basic renderer calls whilst it is happening. This is at attempt to stop getting TRC failure on SubmitDone taking > 5 seconds on boot -C4JThread *minecraftThread = new C4JThread(&StartMinecraftThreadProc, NULL, "Running minecraft start"); -minecraftThread->Run(); -do -{ - RenderManager.StartFrame(); - Sleep(20); - RenderManager.Present(); -} while (minecraftThread->isRunning()); -delete minecraftThread; - -// Re-acquire the GL context in the main thread. -// StartMinecraftThreadProc calls InitialiseContext() which moves the context -// to the init thread for texture loading; we must reclaim it here before -// any further OpenGL calls in the main render loop. -RenderManager.InitialiseContext(); - -Minecraft *pMinecraft=Minecraft::GetInstance(); - -app.InitGameSettings(); - -app.InitialiseTips(); -while (!RenderManager.ShouldClose()) { -RenderManager.StartFrame(); -app.UpdateTime(); -PIXBeginNamedEvent(0,"Input manager tick"); -InputManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Profile manager tick"); -ProfileManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Storage manager tick"); -StorageManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Render manager tick"); -RenderManager.Tick(); -PIXEndNamedEvent(); - -// Tick the social networking manager. -PIXBeginNamedEvent(0,"Social network manager tick"); -// CSocialManager::Instance()->Tick(); -PIXEndNamedEvent(); - -// Tick sentient. -PIXBeginNamedEvent(0,"Sentient tick"); -MemSect(37); -// SentientManager.Tick(); -MemSect(0); -PIXEndNamedEvent(); - -PIXBeginNamedEvent(0,"Network manager do work #1"); -g_NetworkManager.DoWork(); -PIXEndNamedEvent(); - -// Render game graphics. -// On Linux, always call run_middle() so mc->screen (TitleScreen etc.) renders -// even when the game session has not yet started (Iggy Flash UI is unavailable). -pMinecraft->run_middle(); -if(app.GetGameStarted()) -{ - app.SetAppPaused( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) ); -} -else -{ - MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); - MemSect(0); - pMinecraft->textures->tick(true,false); - IntCache::Reset(); - if( app.GetReallyChangingSessionType() ) - { - pMinecraft->tickAllConnections(); // Added to stop timing out when we are waiting after converting to an offline game - } -} -pMinecraft->soundEngine->playMusicTick(); - -static bool bInitnet=false; - -if(bInitnet) -{ g_NetworkManager.Initialise(); -} + + // debug switch to trial version + ProfileManager.SetDebugFullOverride(true); + // Initialise TLS for tesselator, for this main thread + Tesselator::CreateNewThreadStorage(1024 * 1024); + // Initialise TLS for AABB and Vec3 pools, for this main thread + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::CreateNewThreadStorage(); + OldChunkStorage::CreateNewThreadStorage(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); + + Minecraft::main(); + + // Minecraft::main () used to call Minecraft::Start, but this takes ~2.5 + // seconds, so now running this in another thread so we can do some basic + // renderer calls whilst it is happening. This is at attempt to stop getting + // TRC failure on SubmitDone taking > 5 seconds on boot + C4JThread* minecraftThread = new C4JThread(&StartMinecraftThreadProc, NULL, + "Running minecraft start"); + minecraftThread->Run(); + do { + RenderManager.StartFrame(); + Sleep(20); + RenderManager.Present(); + } while (minecraftThread->isRunning()); + delete minecraftThread; + + // Re-acquire the GL context in the main thread. + // StartMinecraftThreadProc calls InitialiseContext() which moves the + // context to the init thread for texture loading; we must reclaim it here + // before any further OpenGL calls in the main render loop. + RenderManager.InitialiseContext(); + + Minecraft* pMinecraft = Minecraft::GetInstance(); + + app.InitGameSettings(); + + app.InitialiseTips(); + while (!RenderManager.ShouldClose()) { + RenderManager.StartFrame(); + app.UpdateTime(); + PIXBeginNamedEvent(0, "Input manager tick"); + InputManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Profile manager tick"); + ProfileManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Storage manager tick"); + StorageManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Render manager tick"); + RenderManager.Tick(); + PIXEndNamedEvent(); + + // Tick the social networking manager. + PIXBeginNamedEvent(0, "Social network manager tick"); + // CSocialManager::Instance()->Tick(); + PIXEndNamedEvent(); + + // Tick sentient. + PIXBeginNamedEvent(0, "Sentient tick"); + MemSect(37); + // SentientManager.Tick(); + MemSect(0); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Network manager do work #1"); + g_NetworkManager.DoWork(); + PIXEndNamedEvent(); + + // Render game graphics. + // On Linux, always call run_middle() so mc->screen (TitleScreen etc.) + // renders even when the game session has not yet started (Iggy Flash UI + // is unavailable). + pMinecraft->run_middle(); + if (app.GetGameStarted()) { + app.SetAppPaused( + g_NetworkManager.IsLocalGame() && + g_NetworkManager.GetPlayerCount() == 1 && + ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())); + } else { + MemSect(28); + pMinecraft->soundEngine->tick(NULL, 0.0f); + MemSect(0); + pMinecraft->textures->tick(true, false); + IntCache::Reset(); + if (app.GetReallyChangingSessionType()) { + pMinecraft + ->tickAllConnections(); // Added to stop timing out when we + // are waiting after converting to + // an offline game + } + } + pMinecraft->soundEngine->playMusicTick(); + + static bool bInitnet = false; + + if (bInitnet) { + g_NetworkManager.Initialise(); + } #ifdef MEMORY_TRACKING -static bool bResetMemTrack = false; -static bool bDumpMemTrack = false; + static bool bResetMemTrack = false; + static bool bDumpMemTrack = false; -MemPixStuff(); + MemPixStuff(); -if( bResetMemTrack ) -{ - ResetMem(); - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); - printf("RESETMEM: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); - bResetMemTrack = false; -} + if (bResetMemTrack) { + ResetMem(); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("RESETMEM: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); + bResetMemTrack = false; + } -if( bDumpMemTrack ) -{ - DumpMem(); - bDumpMemTrack = false; - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); - printf("DUMPMEM: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); - printf("Renderer used: %d\n",RenderManager.CBuffSize(-1)); -} + if (bDumpMemTrack) { + DumpMem(); + bDumpMemTrack = false; + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("DUMPMEM: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); + printf("Renderer used: %d\n", RenderManager.CBuffSize(-1)); + } #endif #if 0 static bool bDumpTextureUsage = false; @@ -844,8 +999,8 @@ RenderManager.TextureGetStats(); bDumpTextureUsage = false; } #endif -ui.tick(); -ui.render(); + ui.tick(); + ui.render(); #if 0 app.HandleButtonPresses(); @@ -886,51 +1041,47 @@ pDevice->SetSamplerState(0,SamplerStateModes[i],SamplerStateA[i]); RenderManager.Set_matrixDirty(); #endif -// Present the frame. -RenderManager.Present(); + // Present the frame. + RenderManager.Present(); -ui.CheckMenuDisplayed(); -PIXBeginNamedEvent(0,"Profile load check"); -// has the game defined profile data been changed (by a profile load) -if(app.uiGameDefinedDataChangedBitmask!=0) -{ - void *pData; - for(int i=0;istats[i]->clear(); + pMinecraft->stats[i]->parse(pData); + } } - else - { - // force debug mask off - app.ActionDebugMask(i,true); - } - #endif - // clear the stats first - there could have beena signout and sign back in in the menus - // need to clear the player stats - can't assume it'll be done in setlevel - we may not be in the game - pMinecraft->stats[ i ]->clear(); - pMinecraft->stats[i]->parse(pData); + + // clear the flag + app.uiGameDefinedDataChangedBitmask = 0; } + PIXEndNamedEvent(); - } - - // clear the flag - app.uiGameDefinedDataChangedBitmask=0; -} -PIXEndNamedEvent(); - -PIXBeginNamedEvent(0,"Network manager do work #2"); -g_NetworkManager.DoWork(); -PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Network manager do work #2"); + g_NetworkManager.DoWork(); + PIXEndNamedEvent(); #if 0 PIXBeginNamedEvent(0,"Misc extra xui"); @@ -938,143 +1089,136 @@ PIXBeginNamedEvent(0,"Misc extra xui"); hr = XuiTimersRun(); #endif -// Any threading type things to deal with from the xui side? -app.HandleXuiActions(); + // Any threading type things to deal with from the xui side? + app.HandleXuiActions(); #if 0 PIXEndNamedEvent(); #endif -// 4J-PB - Update the trial timer display if we are in the trial version -if(!ProfileManager.IsFullVersion()) -{ - // display the trial timer - if(app.GetGameStarted()) - { - // 4J-PB - if the game is paused, add the elapsed time to the trial timer count so it doesn't tick down - if(app.IsAppPaused()) - { - app.UpdateTrialPausedTimer(); + // 4J-PB - Update the trial timer display if we are in the trial version + if (!ProfileManager.IsFullVersion()) { + // display the trial timer + if (app.GetGameStarted()) { + // 4J-PB - if the game is paused, add the elapsed time to the + // trial timer count so it doesn't tick down + if (app.IsAppPaused()) { + app.UpdateTrialPausedTimer(); + } + ui.UpdateTrialTimer(ProfileManager.GetPrimaryPad()); + } + } else { + // need to turn off the trial timer if it was on , and we've + // unlocked the full version + if (bTrialTimerDisplayed) { + ui.ShowTrialTimer(false); + bTrialTimerDisplayed = false; + } } - ui.UpdateTrialTimer(ProfileManager.GetPrimaryPad()); - } -} -else -{ - // need to turn off the trial timer if it was on , and we've unlocked the full version - if(bTrialTimerDisplayed) - { - ui.ShowTrialTimer(false); - bTrialTimerDisplayed=false; - } -} -// Fix for #7318 - Title crashes after short soak in the leaderboards menu -// A memory leak was caused because the icon renderer kept creating new Vec3's because the pool wasn't reset -Vec3::resetPool(); -} // end game loop + // Fix for #7318 - Title crashes after short soak in the leaderboards + // menu A memory leak was caused because the icon renderer kept creating + // new Vec3's because the pool wasn't reset + Vec3::resetPool(); + } // end game loop - // Graceful shutdown: destroy GL context and GLFW before any C++ dtors run. - // Without this, static/global destructors that touch GL objects cause SIGSEGV. - RenderManager.Shutdown(); - _exit(0); -} // end main + // Graceful shutdown: destroy GL context and GLFW before any C++ dtors run. + // Without this, static/global destructors that touch GL objects cause + // SIGSEGV. + RenderManager.Shutdown(); + _exit(0); +} // end main // Free resources, unregister custom classes, and exit. // app.Uninit(); // g_pd3dDevice->Release(); - -std::vector vRichPresenceStrings; +std::vector vRichPresenceStrings; // convert std::wstring to UTF-8 string // wchar_t is 32bit on all Linux systems, and interpreted as UTF-32 -// the code base stores all strings internally as UCS-2 (16bit, subset of UTF-16), -// which, scince it only stores BMP code points, is trivially convertable -// to UTF-32 as well as UTF-16. hence this parser simply parses UTF-32 +// the code base stores all strings internally as UCS-2 (16bit, subset of +// UTF-16), which, scince it only stores BMP code points, is trivially +// convertable to UTF-32 as well as UTF-16. hence this parser simply parses +// UTF-32 // all implementations of libc (including glibc, musl, uClibc...) implement -// wchar_t as 4byte/32bit (scince around 1999), it would break the libc ABI, +// wchar_t as 4byte/32bit (scince around 1999), it would break the libc ABI, // if this ever will get changed, hence this assert -static_assert( sizeof(wchar_t) == 4, "Linux with non 32bit wchar_t"); +static_assert(sizeof(wchar_t) == 4, "Linux with non 32bit wchar_t"); -std::string wstring_to_utf8 (const std::wstring& str) -{ - std::string result; - // preallocation, so it will never need to resize. - // same allocation size as for the 4byte wstring representation. - // it well get destructed instantly, in the function that it gets called from - result.reserve(str.size() * 4); +std::string wstring_to_utf8(const std::wstring& str) { + std::string result; + // preallocation, so it will never need to resize. + // same allocation size as for the 4byte wstring representation. + // it well get destructed instantly, in the function that it gets called + // from + result.reserve(str.size() * 4); - for (size_t i = 0; i < str.size(); ++i) { - uint32_t cp = static_cast(str[i]); + for (size_t i = 0; i < str.size(); ++i) { + uint32_t cp = static_cast(str[i]); - // outside of valid unicode range or preserved UTF-16 surrogate pairs (just in case) - if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { - cp = 0xFFFD; // unicode replacement character - } + // outside of valid unicode range or preserved UTF-16 surrogate pairs + // (just in case) + if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { + cp = 0xFFFD; // unicode replacement character + } - if (cp < 0x80) { - // ASCII - result += static_cast(cp); - // extract multibyte unicode into multiple bytes of UTF-8 - } else if (cp < 0x800) { - result += static_cast(0xC0 | (cp >> 6)); - result += static_cast(0x80 | (cp & 0x3F)); - } else if (cp < 0x10000) { - result += static_cast(0xE0 | (cp >> 12)); - result += static_cast(0x80 | ((cp >> 6) & 0x3F)); - result += static_cast(0x80 | (cp & 0x3F)); - } else { - result += static_cast(0xF0 | (cp >> 18)); - result += static_cast(0x80 | ((cp >> 12) & 0x3F)); - result += static_cast(0x80 | ((cp >> 6) & 0x3F)); - result += static_cast(0x80 | (cp & 0x3F)); - } - } + if (cp < 0x80) { + // ASCII + result += static_cast(cp); + // extract multibyte unicode into multiple bytes of UTF-8 + } else if (cp < 0x800) { + result += static_cast(0xC0 | (cp >> 6)); + result += static_cast(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + result += static_cast(0xE0 | (cp >> 12)); + result += static_cast(0x80 | ((cp >> 6) & 0x3F)); + result += static_cast(0x80 | (cp & 0x3F)); + } else { + result += static_cast(0xF0 | (cp >> 18)); + result += static_cast(0x80 | ((cp >> 12) & 0x3F)); + result += static_cast(0x80 | ((cp >> 6) & 0x3F)); + result += static_cast(0x80 | (cp & 0x3F)); + } + } - return result; + return result; } -uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) -{ - LPCWSTR wchString=app.GetString(iID); +uint8_t* mallocAndCreateUTF8ArrayFromString(int iID) { + LPCWSTR wchString = app.GetString(iID); std::wstring srcString = wchString; std::string dstString = wstring_to_utf8(srcString); - int dst_len = dstString.size()+1; - uint8_t *strUtf8=(uint8_t *)malloc(dst_len); + int dst_len = dstString.size() + 1; + uint8_t* strUtf8 = (uint8_t*)malloc(dst_len); memcpy(strUtf8, dstString.c_str(), dst_len); return strUtf8; } -uint8_t * AddRichPresenceString(int iID) -{ - uint8_t *strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); - if( strUtf8 != NULL ) - { +uint8_t* AddRichPresenceString(int iID) { + uint8_t* strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); + if (strUtf8 != NULL) { vRichPresenceStrings.push_back(strUtf8); } return strUtf8; } -void FreeRichPresenceStrings() -{ - uint8_t *strUtf8; - for(int i=0;i allocCounts; +std::unordered_map allocCounts; bool trackEnable = false; bool trackStarted = false; volatile size_t sizeCheckMin = 1160; @@ -1083,11 +1227,9 @@ volatile int sectCheck = 48; CRITICAL_SECTION memCS; DWORD tlsIdx; -LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) -{ - if( !trackStarted ) - { - void *p = XMemAllocDefault(dwSize,dwAllocAttributes); +LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) { + if (!trackStarted) { + void* p = XMemAllocDefault(dwSize, dwAllocAttributes); size_t realSize = XMemSizeDefault(p, dwAllocAttributes); totalAllocGen += realSize; return p; @@ -1095,26 +1237,24 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) EnterCriticalSection(&memCS); - void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); - size_t realSize = XMemSizeDefault(p,dwAllocAttributes) - 16; + void* p = XMemAllocDefault(dwSize + 16, dwAllocAttributes); + size_t realSize = XMemSizeDefault(p, dwAllocAttributes) - 16; - if( trackEnable ) - { - #if 1 - int sect = ((int) TlsGetValue(tlsIdx)) & 0x3f; - *(((unsigned char *)p)+realSize) = sect; + if (trackEnable) { +#if 1 + int sect = ((int)TlsGetValue(tlsIdx)) & 0x3f; + *(((unsigned char*)p) + realSize) = sect; - if( ( realSize >= sizeCheckMin ) && ( realSize <= sizeCheckMax ) && ( ( sect == sectCheck ) || ( sectCheck == -1 ) ) ) - { + if ((realSize >= sizeCheckMin) && (realSize <= sizeCheckMax) && + ((sect == sectCheck) || (sectCheck == -1))) { app.DebugPrintf("Found one\n"); } - #endif +#endif - if( p ) - { + if (p) { totalAllocGen += realSize; trackEnable = false; - int key = ( sect << 26 ) | realSize; + int key = (sect << 26) | realSize; int oldCount = allocCounts[key]; allocCounts[key] = oldCount + 1; @@ -1127,86 +1267,74 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) return p; } -void* operator new (size_t size) -{ - return (unsigned char *)XMemAlloc(size,MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP)); +void* operator new(size_t size) { + return (unsigned char*)XMemAlloc( + size, MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP)); } -void operator delete (void *p) -{ - XMemFree(p,MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP)); +void operator delete(void* p) { + XMemFree(p, MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP)); } -void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) -{ +void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) { bool special = false; - if( dwAllocAttributes == 0 ) - { - dwAllocAttributes = MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP); + if (dwAllocAttributes == 0) { + dwAllocAttributes = MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP); special = true; } - if(!trackStarted ) - { + if (!trackStarted) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes); XMemFreeDefault(pAddress, dwAllocAttributes); totalAllocGen -= realSize; return; } EnterCriticalSection(&memCS); - if( pAddress ) - { + if (pAddress) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - if(trackEnable) - { - int sect = *(((unsigned char *)pAddress)+realSize); + if (trackEnable) { + int sect = *(((unsigned char*)pAddress) + realSize); totalAllocGen -= realSize; trackEnable = false; - int key = ( sect << 26 ) | realSize; + int key = (sect << 26) | realSize; int oldCount = allocCounts[key]; allocCounts[key] = oldCount - 1; trackEnable = true; - } XMemFreeDefault(pAddress, dwAllocAttributes); } LeaveCriticalSection(&memCS); } -SIZE_T WINAPI XMemSize( - PVOID pAddress, - DWORD dwAllocAttributes -) -{ - if( trackStarted ) - { +SIZE_T WINAPI XMemSize(PVOID pAddress, DWORD dwAllocAttributes) { + if (trackStarted) { return XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - } - else - { + } else { return XMemSizeDefault(pAddress, dwAllocAttributes); } } - -void DumpMem() -{ +void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) - { - if(it->second > 0 ) - { - app.DebugPrintf("%d %d %d %d\n",( it->first >> 26 ) & 0x3f,it->first & 0x03ffffff, it->second, (it->first & 0x03ffffff) * it->second); - totalLeak += ( it->first & 0x03ffffff ) * it->second; + for (AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++) { + if (it->second > 0) { + app.DebugPrintf("%d %d %d %d\n", (it->first >> 26) & 0x3f, + it->first & 0x03ffffff, it->second, + (it->first & 0x03ffffff) * it->second); + totalLeak += (it->first & 0x03ffffff) * it->second; } } - app.DebugPrintf("Total %d\n",totalLeak); + app.DebugPrintf("Total %d\n", totalLeak); } -void ResetMem() -{ - if( !trackStarted ) - { +void ResetMem() { + if (!trackStarted) { trackEnable = true; trackStarted = true; totalAllocGen = 0; @@ -1220,44 +1348,38 @@ void ResetMem() LeaveCriticalSection(&memCS); } -void MemSect(int section) -{ +void MemSect(int section) { unsigned int value = (unsigned int)TlsGetValue(tlsIdx); - if( section == 0 ) // pop + if (section == 0) // pop { value = (value >> 6) & 0x03ffffff; - } - else - { + } else { value = (value << 6) | section; } TlsSetValue(tlsIdx, (LPVOID)value); } -void MemPixStuff() -{ +void MemPixStuff() { const int MAX_SECT = 46; int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) - { - if(it->second > 0 ) - { - int sect = ( it->first >> 26 ) & 0x3f; + for (AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++) { + if (it->second > 0) { + int sect = (it->first >> 26) & 0x3f; int bytes = it->first & 0x03ffffff; totals[sect] += bytes * it->second; } } unsigned int allSectsTotal = 0; - for( int i = 0; i < MAX_SECT; i++ ) - { + for (int i = 0; i < MAX_SECT; i++) { allSectsTotal += totals[i]; - PIXAddNamedCounter(((float)totals[i])/1024.0f,"MemSect%d",i); + PIXAddNamedCounter(((float)totals[i]) / 1024.0f, "MemSect%d", i); } - PIXAddNamedCounter(((float)allSectsTotal)/(4096.0f),"MemSect total pages"); + PIXAddNamedCounter(((float)allSectsTotal) / (4096.0f), + "MemSect total pages"); } #endif diff --git a/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp b/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp index cd0866a57..1077d1921 100644 --- a/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp @@ -8,6 +8,9 @@ void ShutdownManager::StartShutdown() {} void ShutdownManager::MainThreadHandleShutdown() {} void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/) {} -void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/, C4JThread::EventArray * /*eventArray*/) {} -bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) { return true; } +void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/, + C4JThread::EventArray* /*eventArray*/) {} +bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) { + return true; +} void ShutdownManager::HasFinished(ShutdownManager::EThreadId /*threadId*/) {} diff --git a/Minecraft.Client/Platform/Linux/Linux_UIController.cpp b/Minecraft.Client/Platform/Linux/Linux_UIController.cpp index 4e4fe1c58..8a9d09eed 100644 --- a/Minecraft.Client/Platform/Linux/Linux_UIController.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_UIController.cpp @@ -12,115 +12,105 @@ ConsoleUIController ui; -void ConsoleUIController::init(S32 w, S32 h) -{ +void ConsoleUIController::init(S32 w, S32 h) { #ifdef _ENABLEIGGY - // Shared init - preInit(w, h); + // Shared init + preInit(w, h); - //init - gdraw_funcs = gdraw_GL_CreateContext(w, h, 0); + // init + gdraw_funcs = gdraw_GL_CreateContext(w, h, 0); - if (!gdraw_funcs) - { - app.DebugPrintf("Failed to initialise GDraw GL!\n"); - fprintf(stderr, "[Linux_UIController] Failed to initialise GDraw GL!\n"); - // nott fatal for now - } - else - { + if (!gdraw_funcs) { + app.DebugPrintf("Failed to initialise GDraw GL!\n"); + fprintf(stderr, + "[Linux_UIController] Failed to initialise GDraw GL!\n"); + // nott fatal for now + } else { + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000, + 16 * 1024 * 1024); + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000, + 128 * 1024 * 1024); + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10, + 32 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000, 16 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000, 128 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10, 32 * 1024 * 1024); + IggySetGDraw(gdraw_funcs); + } - IggySetGDraw(gdraw_funcs); - } - - postInit(); + postInit(); #endif } -void ConsoleUIController::render() -{ +void ConsoleUIController::render() { #ifdef _ENABLEIGGY - if (!gdraw_funcs) - return; + if (!gdraw_funcs) return; - gdraw_GL_SetTileOrigin(0, 0, 0); + gdraw_GL_SetTileOrigin(0, 0, 0); - // render - renderScenes(); + // render + renderScenes(); - gdraw_GL_NoMoreGDrawThisFrame(); + gdraw_GL_NoMoreGDrawThisFrame(); #endif } -void ConsoleUIController::beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion) -{ - gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); +void ConsoleUIController::beginIggyCustomDraw4J( + IggyCustomDrawCallbackRegion* region, CustomDrawData* customDrawRegion) { + gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); } -CustomDrawData *ConsoleUIController::setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region) -{ - CustomDrawData *customDrawRegion = new CustomDrawData(); - customDrawRegion->x0 = region->x0; - customDrawRegion->x1 = region->x1; - customDrawRegion->y0 = region->y0; - customDrawRegion->y1 = region->y1; +CustomDrawData* ConsoleUIController::setupCustomDraw( + UIScene* scene, IggyCustomDrawCallbackRegion* region) { + CustomDrawData* customDrawRegion = new CustomDrawData(); + customDrawRegion->x0 = region->x0; + customDrawRegion->x1 = region->x1; + customDrawRegion->y0 = region->y0; + customDrawRegion->y1 = region->y1; - - gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); + gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); - setupCustomDrawGameStateAndMatrices(scene, customDrawRegion); + setupCustomDrawGameStateAndMatrices(scene, customDrawRegion); - return customDrawRegion; + return customDrawRegion; } -CustomDrawData *ConsoleUIController::calculateCustomDraw(IggyCustomDrawCallbackRegion *region) -{ - CustomDrawData *customDrawRegion = new CustomDrawData(); - customDrawRegion->x0 = region->x0; - customDrawRegion->x1 = region->x1; - customDrawRegion->y0 = region->y0; - customDrawRegion->y1 = region->y1; +CustomDrawData* ConsoleUIController::calculateCustomDraw( + IggyCustomDrawCallbackRegion* region) { + CustomDrawData* customDrawRegion = new CustomDrawData(); + customDrawRegion->x0 = region->x0; + customDrawRegion->x1 = region->x1; + customDrawRegion->y0 = region->y0; + customDrawRegion->y1 = region->y1; - gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat); + gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat); - return customDrawRegion; + return customDrawRegion; } -void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion *region) -{ - endCustomDrawGameStateAndMatrices(); +void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion* region) { + endCustomDrawGameStateAndMatrices(); - gdraw_GL_EndCustomDraw(region); + gdraw_GL_EndCustomDraw(region); } -void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) -{ - gdraw_GL_SetTileOrigin(xPos, yPos, 0); +void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) { + gdraw_GL_SetTileOrigin(xPos, yPos, 0); } -GDrawTexture *ConsoleUIController::getSubstitutionTexture(int textureId) -{ - // todo impl - return nullptr; +GDrawTexture* ConsoleUIController::getSubstitutionTexture(int textureId) { + // todo impl + return nullptr; } -void ConsoleUIController::destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle) -{ - if (handle) - gdraw_GL_WrappedTextureDestroy(handle); +void ConsoleUIController::destroySubstitutionTexture(void* destroyCallBackData, + GDrawTexture* handle) { + if (handle) gdraw_GL_WrappedTextureDestroy(handle); } -void ConsoleUIController::shutdown() -{ +void ConsoleUIController::shutdown() { #ifdef _ENABLEIGGY - if (gdraw_funcs) - { - gdraw_GL_DestroyContext(); - gdraw_funcs = nullptr; - } + if (gdraw_funcs) { + gdraw_GL_DestroyContext(); + gdraw_funcs = nullptr; + } #endif } \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Linux_UIController.h b/Minecraft.Client/Platform/Linux/Linux_UIController.h index 6ed6934b0..aac328809 100644 --- a/Minecraft.Client/Platform/Linux/Linux_UIController.h +++ b/Minecraft.Client/Platform/Linux/Linux_UIController.h @@ -2,26 +2,29 @@ #include "../Common/UI/UIController.h" -class ConsoleUIController : public UIController -{ +class ConsoleUIController : public UIController { public: - void init(S32 w, S32 h); + void init(S32 w, S32 h); - void render(); - void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion); - virtual CustomDrawData *setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region); - virtual CustomDrawData *calculateCustomDraw(IggyCustomDrawCallbackRegion *region); - virtual void endCustomDraw(IggyCustomDrawCallbackRegion *region); + void render(); + void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion* region, + CustomDrawData* customDrawRegion); + virtual CustomDrawData* setupCustomDraw( + UIScene* scene, IggyCustomDrawCallbackRegion* region); + virtual CustomDrawData* calculateCustomDraw( + IggyCustomDrawCallbackRegion* region); + virtual void endCustomDraw(IggyCustomDrawCallbackRegion* region); protected: - virtual void setTileOrigin(S32 xPos, S32 yPos); + virtual void setTileOrigin(S32 xPos, S32 yPos); public: - GDrawTexture *getSubstitutionTexture(int textureId); - void destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle); + GDrawTexture* getSubstitutionTexture(int textureId); + void destroySubstitutionTexture(void* destroyCallBackData, + GDrawTexture* handle); public: - void shutdown(); + void shutdown(); }; extern ConsoleUIController ui; \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Social/SocialManager.h b/Minecraft.Client/Platform/Linux/Social/SocialManager.h index 278fb91a9..b225d8a39 100644 --- a/Minecraft.Client/Platform/Linux/Social/SocialManager.h +++ b/Minecraft.Client/Platform/Linux/Social/SocialManager.h @@ -5,17 +5,11 @@ #ifndef _SOCIAL_MANAGER_H #define _SOCIAL_MANAGER_H -enum ESocialNetwork -{ - eFacebook = 0, - eNumSocialNetworks -}; +enum ESocialNetwork { eFacebook = 0, eNumSocialNetworks }; -class CSocialManager -{ +class CSocialManager { public: - static CSocialManager* Instance() - { + static CSocialManager* Instance() { static CSocialManager s_instance; return &s_instance; } @@ -23,21 +17,21 @@ public: void Initialise() {} void Tick() {} - bool RefreshPostingCapability() { return false; } - bool IsTitleAllowedToPostAnything() { return false; } - bool IsTitleAllowedToPostImages() { return false; } - bool IsTitleAllowedToPostLinks() { return false; } - bool AreAllUsersAllowedToPostImages() { return false; } + bool RefreshPostingCapability() { return false; } + bool IsTitleAllowedToPostAnything() { return false; } + bool IsTitleAllowedToPostImages() { return false; } + bool IsTitleAllowedToPostLinks() { return false; } + bool AreAllUsersAllowedToPostImages() { return false; } - bool PostLinkToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } - bool PostImageToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } + bool PostLinkToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; } + bool PostImageToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; } - void SetSocialPostText( const WCHAR*, const WCHAR*, const WCHAR* ) {} + void SetSocialPostText(const WCHAR*, const WCHAR*, const WCHAR*) {} private: CSocialManager() {} - CSocialManager( const CSocialManager& ); - CSocialManager& operator=( const CSocialManager& ); + CSocialManager(const CSocialManager&); + CSocialManager& operator=(const CSocialManager&); }; -#endif // _SOCIAL_MANAGER_H +#endif // _SOCIAL_MANAGER_H diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h index cfde54c6c..f70026843 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h @@ -11,334 +11,413 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - enum ContainmentType - { - DISJOINT = 0, - INTERSECTS = 1, - CONTAINS = 2 - }; +enum ContainmentType { DISJOINT = 0, INTERSECTS = 1, CONTAINS = 2 }; - enum PlaneIntersectionType - { - FRONT = 0, - INTERSECTING = 1, - BACK = 2 - }; +enum PlaneIntersectionType { FRONT = 0, INTERSECTING = 1, BACK = 2 }; - struct BoundingBox; - struct BoundingOrientedBox; - struct BoundingFrustum; +struct BoundingBox; +struct BoundingOrientedBox; +struct BoundingFrustum; #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4324 4820) - // C4324: alignment padding warnings - // C4820: Off by default noise +#pragma warning(disable : 4324 4820) +// C4324: alignment padding warnings +// C4820: Off by default noise #endif - //------------------------------------------------------------------------------------- - // Bounding sphere - //------------------------------------------------------------------------------------- - struct BoundingSphere - { - XMFLOAT3 Center; // Center of the sphere. - float Radius; // Radius of the sphere. - - // Creators - BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {} - - BoundingSphere(const BoundingSphere&) = default; - BoundingSphere& operator=(const BoundingSphere&) = default; - - BoundingSphere(BoundingSphere&&) = default; - BoundingSphere& operator=(BoundingSphere&&) = default; - - constexpr BoundingSphere(_In_ const XMFLOAT3& center, _In_ float radius) noexcept - : Center(center), Radius(radius) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - // Transform the sphere - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-sphere test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-sphere test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-sphere test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test sphere against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateMerged(_Out_ BoundingSphere& Out, _In_ const BoundingSphere& S1, _In_ const BoundingSphere& S2) noexcept; - - static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingBox& box) noexcept; - static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingOrientedBox& box) noexcept; - - static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - - static void CreateFromFrustum(_Out_ BoundingSphere& Out, _In_ const BoundingFrustum& fr) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Axis-aligned bounding box - //------------------------------------------------------------------------------------- - struct BoundingBox - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Center; // Center of the box. - XMFLOAT3 Extents; // Distance from the center to each side. - - // Creators - BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {} - - BoundingBox(const BoundingBox&) = default; - BoundingBox& operator=(const BoundingBox&) = default; - - BoundingBox(BoundingBox&&) = default; - BoundingBox& operator=(BoundingBox&&) = default; - - constexpr BoundingBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents) noexcept - : Center(center), Extents(extents) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the box - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-Box test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-box test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-Box test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test box against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1, _In_ const BoundingBox& b2) noexcept; - - static void CreateFromSphere(_Out_ BoundingBox& Out, _In_ const BoundingSphere& sh) noexcept; - - static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out, _In_ FXMVECTOR pt1, _In_ FXMVECTOR pt2) noexcept; - static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Oriented bounding box - //------------------------------------------------------------------------------------- - struct BoundingOrientedBox - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Center; // Center of the box. - XMFLOAT3 Extents; // Distance from the center to each side. - XMFLOAT4 Orientation; // Unit quaternion representing rotation (box -> world). - - // Creators - BoundingOrientedBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {} - - BoundingOrientedBox(const BoundingOrientedBox&) = default; - BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default; - - BoundingOrientedBox(BoundingOrientedBox&&) = default; - BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default; - - constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents, _In_ const XMFLOAT4& orientation) noexcept - : Center(center), Extents(extents), Orientation(orientation) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the box - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-OrientedBox test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-OrientedBox test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-OrientedBox test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test OrientedBox against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out, _In_ const BoundingBox& box) noexcept; - - static void CreateFromPoints(_Out_ BoundingOrientedBox& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Bounding frustum - //------------------------------------------------------------------------------------- - struct BoundingFrustum - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Origin; // Origin of the frustum (and projection). - XMFLOAT4 Orientation; // Quaternion representing rotation. - - float RightSlope; // Positive X (X/Z) - float LeftSlope; // Negative X - float TopSlope; // Positive Y (Y/Z) - float BottomSlope; // Negative Y - float Near, Far; // Z of the near plane and far plane. - - // Creators - BoundingFrustum() noexcept : - Origin(0, 0, 0), Orientation(0, 0, 0, 1.f), RightSlope(1.f), LeftSlope(-1.f), - TopSlope(1.f), BottomSlope(-1.f), Near(0), Far(1.f) {} - - BoundingFrustum(const BoundingFrustum&) = default; - BoundingFrustum& operator=(const BoundingFrustum&) = default; - - BoundingFrustum(BoundingFrustum&&) = default; - BoundingFrustum& operator=(BoundingFrustum&&) = default; - - constexpr BoundingFrustum(_In_ const XMFLOAT3& origin, _In_ const XMFLOAT4& orientation, - _In_ float rightSlope, _In_ float leftSlope, _In_ float topSlope, _In_ float bottomSlope, - _In_ float nearPlane, _In_ float farPlane) noexcept - : Origin(origin), Orientation(orientation), - RightSlope(rightSlope), LeftSlope(leftSlope), TopSlope(topSlope), BottomSlope(bottomSlope), - Near(nearPlane), Far(farPlane) {} - BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept; - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the frustum - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - // Frustum-Frustum test - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-Frustum test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-Frustum test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-Frustum test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test frustum against six planes (see BoundingFrustum::GetPlanes) - - void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane, _Out_opt_ XMVECTOR* RightPlane, - _Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane, _Out_opt_ XMVECTOR* BottomPlane) const noexcept; - // Create 6 Planes representation of Frustum - - // Static methods - static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX Projection, bool rhcoords = false) noexcept; - }; - - //----------------------------------------------------------------------------- - // Triangle intersection testing routines. - //----------------------------------------------------------------------------- - namespace TriangleTests - { - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _In_ FXMVECTOR V0, _In_ GXMVECTOR V1, _In_ HXMVECTOR V2, _Out_ float& Dist) noexcept; - // Ray-Triangle - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1, _In_ FXMVECTOR A2, _In_ GXMVECTOR B0, _In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept; - // Triangle-Triangle - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ GXMVECTOR Plane) noexcept; - // Plane-Triangle - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, +//------------------------------------------------------------------------------------- +// Bounding sphere +//------------------------------------------------------------------------------------- +struct BoundingSphere { + XMFLOAT3 Center; // Center of the sphere. + float Radius; // Radius of the sphere. + + // Creators + BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {} + + BoundingSphere(const BoundingSphere&) = default; + BoundingSphere& operator=(const BoundingSphere&) = default; + + BoundingSphere(BoundingSphere&&) = default; + BoundingSphere& operator=(BoundingSphere&&) = default; + + constexpr BoundingSphere(_In_ const XMFLOAT3& center, + _In_ float radius) noexcept + : Center(center), Radius(radius) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + // Transform the sphere + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-sphere test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-sphere test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-sphere test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test sphere against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateMerged(_Out_ BoundingSphere& Out, + _In_ const BoundingSphere& S1, + _In_ const BoundingSphere& S2) noexcept; + + static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, + _In_ const BoundingBox& box) noexcept; + static void CreateFromBoundingBox( + _Out_ BoundingSphere& Out, + _In_ const BoundingOrientedBox& box) noexcept; + + static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; + + static void CreateFromFrustum(_Out_ BoundingSphere& Out, + _In_ const BoundingFrustum& fr) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Axis-aligned bounding box +//------------------------------------------------------------------------------------- +struct BoundingBox { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Center; // Center of the box. + XMFLOAT3 Extents; // Distance from the center to each side. + + // Creators + BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {} + + BoundingBox(const BoundingBox&) = default; + BoundingBox& operator=(const BoundingBox&) = default; + + BoundingBox(BoundingBox&&) = default; + BoundingBox& operator=(BoundingBox&&) = default; + + constexpr BoundingBox(_In_ const XMFLOAT3& center, + _In_ const XMFLOAT3& extents) noexcept + : Center(center), Extents(extents) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingBox& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the box + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-Box test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-box test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-Box test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test box against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1, + _In_ const BoundingBox& b2) noexcept; + + static void CreateFromSphere(_Out_ BoundingBox& Out, + _In_ const BoundingSphere& sh) noexcept; + + static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out, + _In_ FXMVECTOR pt1, + _In_ FXMVECTOR pt2) noexcept; + static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Oriented bounding box +//------------------------------------------------------------------------------------- +struct BoundingOrientedBox { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Center; // Center of the box. + XMFLOAT3 Extents; // Distance from the center to each side. + XMFLOAT4 + Orientation; // Unit quaternion representing rotation (box -> world). + + // Creators + BoundingOrientedBox() noexcept + : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {} + + BoundingOrientedBox(const BoundingOrientedBox&) = default; + BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default; + + BoundingOrientedBox(BoundingOrientedBox&&) = default; + BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default; + + constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center, + _In_ const XMFLOAT3& extents, + _In_ const XMFLOAT4& orientation) noexcept + : Center(center), Extents(extents), Orientation(orientation) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the box + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-OrientedBox test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-OrientedBox test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-OrientedBox test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test OrientedBox against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out, + _In_ const BoundingBox& box) noexcept; + + static void CreateFromPoints(_Out_ BoundingOrientedBox& Out, + _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Bounding frustum +//------------------------------------------------------------------------------------- +struct BoundingFrustum { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Origin; // Origin of the frustum (and projection). + XMFLOAT4 Orientation; // Quaternion representing rotation. + + float RightSlope; // Positive X (X/Z) + float LeftSlope; // Negative X + float TopSlope; // Positive Y (Y/Z) + float BottomSlope; // Negative Y + float Near, Far; // Z of the near plane and far plane. + + // Creators + BoundingFrustum() noexcept + : Origin(0, 0, 0), + Orientation(0, 0, 0, 1.f), + RightSlope(1.f), + LeftSlope(-1.f), + TopSlope(1.f), + BottomSlope(-1.f), + Near(0), + Far(1.f) {} + + BoundingFrustum(const BoundingFrustum&) = default; + BoundingFrustum& operator=(const BoundingFrustum&) = default; + + BoundingFrustum(BoundingFrustum&&) = default; + BoundingFrustum& operator=(BoundingFrustum&&) = default; + + constexpr BoundingFrustum(_In_ const XMFLOAT3& origin, + _In_ const XMFLOAT4& orientation, + _In_ float rightSlope, _In_ float leftSlope, + _In_ float topSlope, _In_ float bottomSlope, + _In_ float nearPlane, + _In_ float farPlane) noexcept + : Origin(origin), + Orientation(orientation), + RightSlope(rightSlope), + LeftSlope(leftSlope), + TopSlope(topSlope), + BottomSlope(bottomSlope), + Near(nearPlane), + Far(farPlane) {} + BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept; + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the frustum + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + // Frustum-Frustum test + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-Frustum test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-Frustum test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin, + _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-Frustum test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test frustum against six planes (see BoundingFrustum::GetPlanes) + + void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane, + _Out_opt_ XMVECTOR* RightPlane, + _Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane, + _Out_opt_ XMVECTOR* BottomPlane) const noexcept; + // Create 6 Planes representation of Frustum + + // Static methods + static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out, + _In_ FXMMATRIX Projection, + bool rhcoords = false) noexcept; +}; + +//----------------------------------------------------------------------------- +// Triangle intersection testing routines. +//----------------------------------------------------------------------------- +namespace TriangleTests { +bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _In_ FXMVECTOR V0, _In_ GXMVECTOR V1, + _In_ HXMVECTOR V2, _Out_ float& Dist) noexcept; +// Ray-Triangle + +bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1, + _In_ FXMVECTOR A2, _In_ GXMVECTOR B0, + _In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept; +// Triangle-Triangle + +PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0, + _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2, + _In_ GXMVECTOR Plane) noexcept; +// Plane-Triangle + +ContainmentType XM_CALLCONV +ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ GXMVECTOR Plane0, _In_ HXMVECTOR Plane1, _In_ HXMVECTOR Plane2, - _In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4, _In_ CXMVECTOR Plane5) noexcept; - // Test a triangle against six planes at once (see BoundingFrustum::GetPlanes) - } + _In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4, + _In_ CXMVECTOR Plane5) noexcept; +// Test a triangle against six planes at once (see BoundingFrustum::GetPlanes) +} // namespace TriangleTests #ifdef _MSC_VER #pragma warning(pop) #endif - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4068 4365 4616 6001) - // C4068/4616: ignore unknown pragmas - // C4365: Off by default noise - // C6001: False positives +// C4068/4616: ignore unknown pragmas +// C4365: Off by default noise +// C6001: False positives #endif #ifdef _PREFAST_ @@ -366,5 +445,4 @@ namespace DirectX #pragma warning(pop) #endif -} // namespace DirectX - +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h index 962971e39..30bd3d852 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h @@ -11,302 +11,490 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - namespace Colors - { - // Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace - XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.941176534f, 0.972549081f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.980392218f, 0.921568692f, 0.843137324f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.498039246f, 1.f, 0.831372619f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Azure = { { { 0.941176534f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Beige = { { { 0.960784376f, 0.960784376f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.894117713f, 0.768627524f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.921568692f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.541176498f, 0.168627456f, 0.886274576f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Brown = { { { 0.647058845f, 0.164705887f, 0.164705887f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.870588303f, 0.721568644f, 0.529411793f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.372549027f, 0.619607866f, 0.627451003f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.498039246f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.823529482f, 0.411764741f, 0.117647067f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.498039246f, 0.313725501f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.392156899f, 0.584313750f, 0.929411829f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.972549081f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.862745166f, 0.078431375f, 0.235294133f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.545098066f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.721568644f, 0.525490224f, 0.043137256f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.662745118f, 0.662745118f, 0.662745118f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.392156899f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.741176486f, 0.717647076f, 0.419607878f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.545098066f, 0.f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.333333343f, 0.419607878f, 0.184313729f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.549019635f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.600000024f, 0.196078449f, 0.800000072f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.545098066f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.913725555f, 0.588235319f, 0.478431404f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.560784340f, 0.737254918f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.282352954f, 0.239215702f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.184313729f, 0.309803933f, 0.309803933f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.807843208f, 0.819607913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.580392182f, 0.f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.078431375f, 0.576470613f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.749019623f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.411764741f, 0.411764741f, 0.411764741f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.117647067f, 0.564705908f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.698039234f, 0.133333340f, 0.133333340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.980392218f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.133333340f, 0.545098066f, 0.133333340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.862745166f, 0.862745166f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.972549081f, 0.972549081f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.843137324f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.854902029f, 0.647058845f, 0.125490203f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gray = { { { 0.501960814f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.501960814f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.678431392f, 1.f, 0.184313729f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.941176534f, 1.f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.411764741f, 0.705882370f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.803921640f, 0.360784322f, 0.360784322f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.294117659f, 0.f, 0.509803951f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.941176534f, 0.901960850f, 0.549019635f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.901960850f, 0.901960850f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.941176534f, 0.960784376f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.486274540f, 0.988235354f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.980392218f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.678431392f, 0.847058892f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.941176534f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.878431439f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.980392218f, 0.980392218f, 0.823529482f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.827451050f, 0.827451050f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.564705908f, 0.933333397f, 0.564705908f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.713725507f, 0.756862819f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.627451003f, 0.478431404f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.125490203f, 0.698039234f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.529411793f, 0.807843208f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.466666698f, 0.533333361f, 0.600000024f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.690196097f, 0.768627524f, 0.870588303f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.878431439f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.196078449f, 0.803921640f, 0.196078449f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Linen = { { { 0.980392218f, 0.941176534f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.501960814f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.400000036f, 0.803921640f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.729411781f, 0.333333343f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.576470613f, 0.439215720f, 0.858823597f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.235294133f, 0.701960802f, 0.443137288f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.482352972f, 0.407843173f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.980392218f, 0.603921592f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.282352954f, 0.819607913f, 0.800000072f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.780392230f, 0.082352944f, 0.521568656f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.098039225f, 0.098039225f, 0.439215720f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.960784376f, 1.f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.894117713f, 0.882353008f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.894117713f, 0.709803939f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.870588303f, 0.678431392f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.992156923f, 0.960784376f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Olive = { { { 0.501960814f, 0.501960814f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.419607878f, 0.556862772f, 0.137254909f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.647058845f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.270588249f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.854902029f, 0.439215720f, 0.839215755f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.933333397f, 0.909803987f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.596078455f, 0.984313786f, 0.596078455f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.686274529f, 0.933333397f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.858823597f, 0.439215720f, 0.576470613f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.937254965f, 0.835294187f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.854902029f, 0.725490212f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Peru = { { { 0.803921640f, 0.521568656f, 0.247058839f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.752941251f, 0.796078503f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Plum = { { { 0.866666734f, 0.627451003f, 0.866666734f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.690196097f, 0.878431439f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Purple = { { { 0.501960814f, 0.f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.737254918f, 0.560784340f, 0.560784340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.254901975f, 0.411764741f, 0.882353008f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.545098066f, 0.270588249f, 0.074509807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.980392218f, 0.501960814f, 0.447058856f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.956862807f, 0.643137276f, 0.376470625f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.180392161f, 0.545098066f, 0.341176480f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.960784376f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.627451003f, 0.321568638f, 0.176470593f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Silver = { { { 0.752941251f, 0.752941251f, 0.752941251f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.529411793f, 0.807843208f, 0.921568692f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.415686309f, 0.352941185f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.439215720f, 0.501960814f, 0.564705908f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.980392218f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.498039246f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.274509817f, 0.509803951f, 0.705882370f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tan = { { { 0.823529482f, 0.705882370f, 0.549019635f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.847058892f, 0.749019623f, 0.847058892f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.388235331f, 0.278431386f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; - XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.250980407f, 0.878431439f, 0.815686345f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Violet = { { { 0.933333397f, 0.509803951f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.960784376f, 0.870588303f, 0.701960802f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.960784376f, 0.960784376f, 0.960784376f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.603921592f, 0.803921640f, 0.196078449f, 1.f } } }; +namespace Colors { +// Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace +XMGLOBALCONST XMVECTORF32 AliceBlue = { + {{0.941176534f, 0.972549081f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 AntiqueWhite = { + {{0.980392218f, 0.921568692f, 0.843137324f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aquamarine = { + {{0.498039246f, 1.f, 0.831372619f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Azure = {{{0.941176534f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Beige = { + {{0.960784376f, 0.960784376f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.894117713f, 0.768627524f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { + {{1.f, 0.921568692f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlueViolet = { + {{0.541176498f, 0.168627456f, 0.886274576f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Brown = { + {{0.647058845f, 0.164705887f, 0.164705887f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BurlyWood = { + {{0.870588303f, 0.721568644f, 0.529411793f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CadetBlue = { + {{0.372549027f, 0.619607866f, 0.627451003f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.498039246f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chocolate = { + {{0.823529482f, 0.411764741f, 0.117647067f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.498039246f, 0.313725501f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CornflowerBlue = { + {{0.392156899f, 0.584313750f, 0.929411829f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.972549081f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Crimson = { + {{0.862745166f, 0.078431375f, 0.235294133f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.545098066f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { + {{0.721568644f, 0.525490224f, 0.043137256f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGray = { + {{0.662745118f, 0.662745118f, 0.662745118f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.392156899f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkKhaki = { + {{0.741176486f, 0.717647076f, 0.419607878f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkMagenta = { + {{0.545098066f, 0.f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { + {{0.333333343f, 0.419607878f, 0.184313729f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.549019635f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrchid = { + {{0.600000024f, 0.196078449f, 0.800000072f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.545098066f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSalmon = { + {{0.913725555f, 0.588235319f, 0.478431404f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { + {{0.560784340f, 0.737254918f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { + {{0.282352954f, 0.239215702f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateGray = { + {{0.184313729f, 0.309803933f, 0.309803933f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkTurquoise = { + {{0.f, 0.807843208f, 0.819607913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkViolet = { + {{0.580392182f, 0.f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.078431375f, 0.576470613f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.749019623f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DimGray = { + {{0.411764741f, 0.411764741f, 0.411764741f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DodgerBlue = { + {{0.117647067f, 0.564705908f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Firebrick = { + {{0.698039234f, 0.133333340f, 0.133333340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 FloralWhite = { + {{1.f, 0.980392218f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 ForestGreen = { + {{0.133333340f, 0.545098066f, 0.133333340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gainsboro = { + {{0.862745166f, 0.862745166f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GhostWhite = { + {{0.972549081f, 0.972549081f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.843137324f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Goldenrod = { + {{0.854902029f, 0.647058845f, 0.125490203f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gray = { + {{0.501960814f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.501960814f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GreenYellow = { + {{0.678431392f, 1.f, 0.184313729f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.941176534f, 1.f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.411764741f, 0.705882370f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 IndianRed = { + {{0.803921640f, 0.360784322f, 0.360784322f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Indigo = {{{0.294117659f, 0.f, 0.509803951f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Khaki = { + {{0.941176534f, 0.901960850f, 0.549019635f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lavender = { + {{0.901960850f, 0.901960850f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LavenderBlush = { + {{1.f, 0.941176534f, 0.960784376f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LawnGreen = { + {{0.486274540f, 0.988235354f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LemonChiffon = { + {{1.f, 0.980392218f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightBlue = { + {{0.678431392f, 0.847058892f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCoral = { + {{0.941176534f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.878431439f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { + {{0.980392218f, 0.980392218f, 0.823529482f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGray = { + {{0.827451050f, 0.827451050f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGreen = { + {{0.564705908f, 0.933333397f, 0.564705908f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightPink = { + {{1.f, 0.713725507f, 0.756862819f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSalmon = { + {{1.f, 0.627451003f, 0.478431404f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSeaGreen = { + {{0.125490203f, 0.698039234f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSkyBlue = { + {{0.529411793f, 0.807843208f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSlateGray = { + {{0.466666698f, 0.533333361f, 0.600000024f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSteelBlue = { + {{0.690196097f, 0.768627524f, 0.870588303f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.878431439f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LimeGreen = { + {{0.196078449f, 0.803921640f, 0.196078449f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Linen = { + {{0.980392218f, 0.941176534f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Maroon = {{{0.501960814f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumAquamarine = { + {{0.400000036f, 0.803921640f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumOrchid = { + {{0.729411781f, 0.333333343f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumPurple = { + {{0.576470613f, 0.439215720f, 0.858823597f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { + {{0.235294133f, 0.701960802f, 0.443137288f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { + {{0.482352972f, 0.407843173f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { + {{0.f, 0.980392218f, 0.603921592f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumTurquoise = { + {{0.282352954f, 0.819607913f, 0.800000072f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumVioletRed = { + {{0.780392230f, 0.082352944f, 0.521568656f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MidnightBlue = { + {{0.098039225f, 0.098039225f, 0.439215720f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MintCream = { + {{0.960784376f, 1.f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MistyRose = { + {{1.f, 0.894117713f, 0.882353008f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.894117713f, 0.709803939f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 NavajoWhite = { + {{1.f, 0.870588303f, 0.678431392f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OldLace = { + {{0.992156923f, 0.960784376f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Olive = {{{0.501960814f, 0.501960814f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OliveDrab = { + {{0.419607878f, 0.556862772f, 0.137254909f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.647058845f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.270588249f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orchid = { + {{0.854902029f, 0.439215720f, 0.839215755f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { + {{0.933333397f, 0.909803987f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGreen = { + {{0.596078455f, 0.984313786f, 0.596078455f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleTurquoise = { + {{0.686274529f, 0.933333397f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleVioletRed = { + {{0.858823597f, 0.439215720f, 0.576470613f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PapayaWhip = { + {{1.f, 0.937254965f, 0.835294187f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PeachPuff = { + {{1.f, 0.854902029f, 0.725490212f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Peru = { + {{0.803921640f, 0.521568656f, 0.247058839f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.752941251f, 0.796078503f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Plum = { + {{0.866666734f, 0.627451003f, 0.866666734f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PowderBlue = { + {{0.690196097f, 0.878431439f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Purple = {{{0.501960814f, 0.f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RosyBrown = { + {{0.737254918f, 0.560784340f, 0.560784340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RoyalBlue = { + {{0.254901975f, 0.411764741f, 0.882353008f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SaddleBrown = { + {{0.545098066f, 0.270588249f, 0.074509807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Salmon = { + {{0.980392218f, 0.501960814f, 0.447058856f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SandyBrown = { + {{0.956862807f, 0.643137276f, 0.376470625f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaGreen = { + {{0.180392161f, 0.545098066f, 0.341176480f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.960784376f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Sienna = { + {{0.627451003f, 0.321568638f, 0.176470593f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Silver = { + {{0.752941251f, 0.752941251f, 0.752941251f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SkyBlue = { + {{0.529411793f, 0.807843208f, 0.921568692f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateBlue = { + {{0.415686309f, 0.352941185f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateGray = { + {{0.439215720f, 0.501960814f, 0.564705908f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.980392218f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.498039246f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SteelBlue = { + {{0.274509817f, 0.509803951f, 0.705882370f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tan = { + {{0.823529482f, 0.705882370f, 0.549019635f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Thistle = { + {{0.847058892f, 0.749019623f, 0.847058892f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.388235331f, 0.278431386f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}}; +XMGLOBALCONST XMVECTORF32 Turquoise = { + {{0.250980407f, 0.878431439f, 0.815686345f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Violet = { + {{0.933333397f, 0.509803951f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Wheat = { + {{0.960784376f, 0.870588303f, 0.701960802f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 WhiteSmoke = { + {{0.960784376f, 0.960784376f, 0.960784376f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 YellowGreen = { + {{0.603921592f, 0.803921640f, 0.196078449f, 1.f}}}; - } // namespace Colors +} // namespace Colors - namespace ColorsLinear - { - // Standard colors (Red/Green/Blue/Alpha) in linear colorspace - XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.871367335f, 0.938685894f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.955973506f, 0.830770075f, 0.679542601f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.212230787f, 1.f, 0.658374965f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Azure = { { { 0.871367335f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Beige = { { { 0.913098991f, 0.913098991f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.775822461f, 0.552011609f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.830770075f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.254152179f, 0.024157630f, 0.760524750f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Brown = { { { 0.376262218f, 0.023153365f, 0.023153365f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.730461001f, 0.479320228f, 0.242281199f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.114435382f, 0.341914445f, 0.351532698f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.212230787f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.644479871f, 0.141263321f, 0.012983031f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.212230787f, 0.080219828f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.127437726f, 0.300543845f, 0.846873462f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.938685894f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.715693772f, 0.006995410f, 0.045186214f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.258182913f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.479320228f, 0.238397658f, 0.003346536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.396755308f, 0.396755308f, 0.396755308f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.127437726f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.508881450f, 0.473531544f, 0.147027299f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.258182913f, 0.f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.090841733f, 0.147027299f, 0.028426038f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.262250721f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.318546832f, 0.031896040f, 0.603827536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.258182913f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.814846814f, 0.304987371f, 0.194617867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.274677366f, 0.502886593f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.064803280f, 0.046665095f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.028426038f, 0.078187428f, 0.078187428f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.617206752f, 0.637597024f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.296138316f, 0.f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.006995410f, 0.291770697f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.520995677f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.141263321f, 0.141263321f, 0.141263321f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.012983031f, 0.278894335f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.445201248f, 0.015996292f, 0.015996292f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.955973506f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.015996292f, 0.258182913f, 0.015996292f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.715693772f, 0.715693772f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.938685894f, 0.938685894f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.679542601f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.701102138f, 0.376262218f, 0.014443844f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gray = { { { 0.215860531f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.215860531f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.417885154f, 1.f, 0.028426038f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.871367335f, 1.f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.141263321f, 0.456411064f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.610495746f, 0.107023112f, 0.107023112f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.070360109f, 0.f, 0.223227978f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.871367335f, 0.791298151f, 0.262250721f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.791298151f, 0.791298151f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.871367335f, 0.913098991f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.201556295f, 0.973445475f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.955973506f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.417885154f, 0.686685443f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.871367335f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.745404482f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.955973506f, 0.955973506f, 0.644479871f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.651405811f, 0.651405811f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.278894335f, 0.854992807f, 0.278894335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.467783839f, 0.533276618f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.351532698f, 0.194617867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.014443844f, 0.445201248f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.242281199f, 0.617206752f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.184475034f, 0.246201396f, 0.318546832f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.434153706f, 0.552011609f, 0.730461001f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.745404482f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.031896040f, 0.610495746f, 0.031896040f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Linen = { { { 0.955973506f, 0.871367335f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.215860531f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.132868364f, 0.610495746f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.491020888f, 0.090841733f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.291770697f, 0.162029430f, 0.708376050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.045186214f, 0.450785846f, 0.165132239f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.198069349f, 0.138431653f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.955973506f, 0.323143244f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.064803280f, 0.637597024f, 0.603827536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.571125031f, 0.007499032f, 0.234550655f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.009721218f, 0.009721218f, 0.162029430f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.913098991f, 1.f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.775822461f, 0.752942443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.775822461f, 0.462077051f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.730461001f, 0.417885154f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.982250869f, 0.913098991f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Olive = { { { 0.215860531f, 0.215860531f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.147027299f, 0.270497859f, 0.016807375f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.376262218f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.059511241f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.701102138f, 0.162029430f, 0.672443330f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.854992807f, 0.806952477f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.313988745f, 0.964686573f, 0.313988745f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.428690553f, 0.854992807f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.708376050f, 0.162029430f, 0.291770697f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.863157392f, 0.665387452f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.701102138f, 0.485149980f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Peru = { { { 0.610495746f, 0.234550655f, 0.049706575f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.527115345f, 0.597202003f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Plum = { { { 0.723055363f, 0.351532698f, 0.723055363f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.434153706f, 0.745404482f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Purple = { { { 0.215860531f, 0.f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.502886593f, 0.274677366f, 0.274677366f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.052860655f, 0.141263321f, 0.752942443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.258182913f, 0.059511241f, 0.006512091f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.955973506f, 0.215860531f, 0.168269455f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.904661357f, 0.371237785f, 0.116970696f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.027320892f, 0.258182913f, 0.095307484f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.913098991f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.351532698f, 0.084376216f, 0.026241222f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Silver = { { { 0.527115345f, 0.527115345f, 0.527115345f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.242281199f, 0.617206752f, 0.830770075f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.144128501f, 0.102241747f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.162029430f, 0.215860531f, 0.278894335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.955973506f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.212230787f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.061246071f, 0.223227978f, 0.456411064f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tan = { { { 0.644479871f, 0.456411064f, 0.262250721f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.686685443f, 0.520995677f, 0.686685443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.124771863f, 0.063010029f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; - XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.051269468f, 0.745404482f, 0.630757332f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Violet = { { { 0.854992807f, 0.223227978f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.913098991f, 0.730461001f, 0.450785846f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.913098991f, 0.913098991f, 0.913098991f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.323143244f, 0.610495746f, 0.031896040f, 1.f } } }; +namespace ColorsLinear { +// Standard colors (Red/Green/Blue/Alpha) in linear colorspace +XMGLOBALCONST XMVECTORF32 AliceBlue = { + {{0.871367335f, 0.938685894f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 AntiqueWhite = { + {{0.955973506f, 0.830770075f, 0.679542601f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aquamarine = { + {{0.212230787f, 1.f, 0.658374965f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Azure = {{{0.871367335f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Beige = { + {{0.913098991f, 0.913098991f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.775822461f, 0.552011609f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { + {{1.f, 0.830770075f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlueViolet = { + {{0.254152179f, 0.024157630f, 0.760524750f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Brown = { + {{0.376262218f, 0.023153365f, 0.023153365f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BurlyWood = { + {{0.730461001f, 0.479320228f, 0.242281199f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CadetBlue = { + {{0.114435382f, 0.341914445f, 0.351532698f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.212230787f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chocolate = { + {{0.644479871f, 0.141263321f, 0.012983031f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.212230787f, 0.080219828f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CornflowerBlue = { + {{0.127437726f, 0.300543845f, 0.846873462f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.938685894f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Crimson = { + {{0.715693772f, 0.006995410f, 0.045186214f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.258182913f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { + {{0.479320228f, 0.238397658f, 0.003346536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGray = { + {{0.396755308f, 0.396755308f, 0.396755308f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.127437726f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkKhaki = { + {{0.508881450f, 0.473531544f, 0.147027299f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkMagenta = { + {{0.258182913f, 0.f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { + {{0.090841733f, 0.147027299f, 0.028426038f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.262250721f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrchid = { + {{0.318546832f, 0.031896040f, 0.603827536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.258182913f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSalmon = { + {{0.814846814f, 0.304987371f, 0.194617867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { + {{0.274677366f, 0.502886593f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { + {{0.064803280f, 0.046665095f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateGray = { + {{0.028426038f, 0.078187428f, 0.078187428f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkTurquoise = { + {{0.f, 0.617206752f, 0.637597024f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkViolet = { + {{0.296138316f, 0.f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.006995410f, 0.291770697f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.520995677f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DimGray = { + {{0.141263321f, 0.141263321f, 0.141263321f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DodgerBlue = { + {{0.012983031f, 0.278894335f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Firebrick = { + {{0.445201248f, 0.015996292f, 0.015996292f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 FloralWhite = { + {{1.f, 0.955973506f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 ForestGreen = { + {{0.015996292f, 0.258182913f, 0.015996292f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gainsboro = { + {{0.715693772f, 0.715693772f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GhostWhite = { + {{0.938685894f, 0.938685894f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.679542601f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Goldenrod = { + {{0.701102138f, 0.376262218f, 0.014443844f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gray = { + {{0.215860531f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.215860531f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GreenYellow = { + {{0.417885154f, 1.f, 0.028426038f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.871367335f, 1.f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.141263321f, 0.456411064f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 IndianRed = { + {{0.610495746f, 0.107023112f, 0.107023112f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Indigo = {{{0.070360109f, 0.f, 0.223227978f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Khaki = { + {{0.871367335f, 0.791298151f, 0.262250721f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lavender = { + {{0.791298151f, 0.791298151f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LavenderBlush = { + {{1.f, 0.871367335f, 0.913098991f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LawnGreen = { + {{0.201556295f, 0.973445475f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LemonChiffon = { + {{1.f, 0.955973506f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightBlue = { + {{0.417885154f, 0.686685443f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCoral = { + {{0.871367335f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.745404482f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { + {{0.955973506f, 0.955973506f, 0.644479871f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGray = { + {{0.651405811f, 0.651405811f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGreen = { + {{0.278894335f, 0.854992807f, 0.278894335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightPink = { + {{1.f, 0.467783839f, 0.533276618f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSalmon = { + {{1.f, 0.351532698f, 0.194617867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSeaGreen = { + {{0.014443844f, 0.445201248f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSkyBlue = { + {{0.242281199f, 0.617206752f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSlateGray = { + {{0.184475034f, 0.246201396f, 0.318546832f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSteelBlue = { + {{0.434153706f, 0.552011609f, 0.730461001f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.745404482f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LimeGreen = { + {{0.031896040f, 0.610495746f, 0.031896040f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Linen = { + {{0.955973506f, 0.871367335f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Maroon = {{{0.215860531f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumAquamarine = { + {{0.132868364f, 0.610495746f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumOrchid = { + {{0.491020888f, 0.090841733f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumPurple = { + {{0.291770697f, 0.162029430f, 0.708376050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { + {{0.045186214f, 0.450785846f, 0.165132239f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { + {{0.198069349f, 0.138431653f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { + {{0.f, 0.955973506f, 0.323143244f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumTurquoise = { + {{0.064803280f, 0.637597024f, 0.603827536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumVioletRed = { + {{0.571125031f, 0.007499032f, 0.234550655f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MidnightBlue = { + {{0.009721218f, 0.009721218f, 0.162029430f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MintCream = { + {{0.913098991f, 1.f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MistyRose = { + {{1.f, 0.775822461f, 0.752942443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.775822461f, 0.462077051f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 NavajoWhite = { + {{1.f, 0.730461001f, 0.417885154f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OldLace = { + {{0.982250869f, 0.913098991f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Olive = {{{0.215860531f, 0.215860531f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OliveDrab = { + {{0.147027299f, 0.270497859f, 0.016807375f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.376262218f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.059511241f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orchid = { + {{0.701102138f, 0.162029430f, 0.672443330f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { + {{0.854992807f, 0.806952477f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGreen = { + {{0.313988745f, 0.964686573f, 0.313988745f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleTurquoise = { + {{0.428690553f, 0.854992807f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleVioletRed = { + {{0.708376050f, 0.162029430f, 0.291770697f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PapayaWhip = { + {{1.f, 0.863157392f, 0.665387452f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PeachPuff = { + {{1.f, 0.701102138f, 0.485149980f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Peru = { + {{0.610495746f, 0.234550655f, 0.049706575f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.527115345f, 0.597202003f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Plum = { + {{0.723055363f, 0.351532698f, 0.723055363f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PowderBlue = { + {{0.434153706f, 0.745404482f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Purple = {{{0.215860531f, 0.f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RosyBrown = { + {{0.502886593f, 0.274677366f, 0.274677366f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RoyalBlue = { + {{0.052860655f, 0.141263321f, 0.752942443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SaddleBrown = { + {{0.258182913f, 0.059511241f, 0.006512091f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Salmon = { + {{0.955973506f, 0.215860531f, 0.168269455f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SandyBrown = { + {{0.904661357f, 0.371237785f, 0.116970696f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaGreen = { + {{0.027320892f, 0.258182913f, 0.095307484f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.913098991f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Sienna = { + {{0.351532698f, 0.084376216f, 0.026241222f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Silver = { + {{0.527115345f, 0.527115345f, 0.527115345f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SkyBlue = { + {{0.242281199f, 0.617206752f, 0.830770075f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateBlue = { + {{0.144128501f, 0.102241747f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateGray = { + {{0.162029430f, 0.215860531f, 0.278894335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.955973506f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.212230787f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SteelBlue = { + {{0.061246071f, 0.223227978f, 0.456411064f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tan = { + {{0.644479871f, 0.456411064f, 0.262250721f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Thistle = { + {{0.686685443f, 0.520995677f, 0.686685443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.124771863f, 0.063010029f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}}; +XMGLOBALCONST XMVECTORF32 Turquoise = { + {{0.051269468f, 0.745404482f, 0.630757332f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Violet = { + {{0.854992807f, 0.223227978f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Wheat = { + {{0.913098991f, 0.730461001f, 0.450785846f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 WhiteSmoke = { + {{0.913098991f, 0.913098991f, 0.913098991f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 YellowGreen = { + {{0.323143244f, 0.610495746f, 0.031896040f, 1.f}}}; - } // namespace ColorsLinear - -} // namespace DirectX +} // namespace ColorsLinear +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h index b11c37c6e..0beb3a724 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h @@ -19,7 +19,10 @@ #error DirectX Math requires Visual C++ 2017 or later. #endif -#if defined(_MSC_VER) && !defined(_M_ARM) && !defined(_M_ARM64) && !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) && (!_MANAGED) && (!_M_CEE) && (!defined(_M_IX86_FP) || (_M_IX86_FP > 1)) && !defined(_XM_NO_INTRINSICS_) && !defined(_XM_VECTORCALL_) +#if defined(_MSC_VER) && !defined(_M_ARM) && !defined(_M_ARM64) && \ + !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) && (!_MANAGED) && \ + (!_M_CEE) && (!defined(_M_IX86_FP) || (_M_IX86_FP > 1)) && \ + !defined(_XM_NO_INTRINSICS_) && !defined(_XM_VECTORCALL_) #define _XM_VECTORCALL_ 1 #endif @@ -35,25 +38,31 @@ #if (__cplusplus >= 201402L) #define XM_DEPRECATED [[deprecated]] #elif defined(__GNUC__) -#define XM_DEPRECATED __attribute__ ((deprecated)) +#define XM_DEPRECATED __attribute__((deprecated)) #else -#define XM_DEPRECATED __declspec(deprecated("This is deprecated and will be removed in a future version.")) +#define XM_DEPRECATED \ + __declspec(deprecated( \ + "This is deprecated and will be removed in a future version.")) #endif #endif -#if !defined(_XM_AVX2_INTRINSICS_) && defined(__AVX2__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_AVX2_INTRINSICS_) && defined(__AVX2__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_AVX2_INTRINSICS_ #endif -#if !defined(_XM_FMA3_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_FMA3_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_FMA3_INTRINSICS_ #endif -#if !defined(_XM_F16C_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_F16C_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_F16C_INTRINSICS_ #endif -#if !defined(_XM_F16C_INTRINSICS_) && defined(__F16C__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_F16C_INTRINSICS_) && defined(__F16C__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_F16C_INTRINSICS_ #endif @@ -65,7 +74,8 @@ #define _XM_AVX_INTRINSICS_ #endif -#if !defined(_XM_AVX_INTRINSICS_) && defined(__AVX__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_AVX_INTRINSICS_) && defined(__AVX__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_AVX_INTRINSICS_ #endif @@ -81,27 +91,34 @@ #define _XM_SSE_INTRINSICS_ #endif -#if !defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) -#if (defined(_M_IX86) || defined(_M_X64) || __i386__ || __x86_64__) && !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) +#if !defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_SSE_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) +#if (defined(_M_IX86) || defined(_M_X64) || __i386__ || __x86_64__) && \ + !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) #define _XM_SSE_INTRINSICS_ -#elif defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || __arm__ || __aarch64__ +#elif defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || __arm__ || __aarch64__ #define _XM_ARM_NEON_INTRINSICS_ #elif !defined(_XM_NO_INTRINSICS_) #error DirectX Math does not support this target #endif -#endif // !_XM_ARM_NEON_INTRINSICS_ && !_XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // !_XM_ARM_NEON_INTRINSICS_ && !_XM_SSE_INTRINSICS_ && + // !_XM_NO_INTRINSICS_ -#if defined(_XM_SSE_INTRINSICS_) && defined(_MSC_VER) && (_MSC_VER >= 1920) && !defined(__clang__) && !defined(_XM_SVML_INTRINSICS_) && !defined(_XM_DISABLE_INTEL_SVML_) +#if defined(_XM_SSE_INTRINSICS_) && defined(_MSC_VER) && (_MSC_VER >= 1920) && \ + !defined(__clang__) && !defined(_XM_SVML_INTRINSICS_) && \ + !defined(_XM_DISABLE_INTEL_SVML_) #define _XM_SVML_INTRINSICS_ #endif -#if !defined(_XM_NO_XMVECTOR_OVERLOADS_) && (defined(__clang__) || defined(__GNUC__)) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_NO_XMVECTOR_OVERLOADS_) && \ + (defined(__clang__) || defined(__GNUC__)) && !defined(_XM_NO_INTRINSICS_) #define _XM_NO_XMVECTOR_OVERLOADS_ #endif #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4514 4820) +#pragma warning(disable : 4514 4820) // C4514/4820: Off by default noise #endif #include @@ -124,7 +141,8 @@ #pragma warning(pop) #endif -#if (defined(__clang__) || defined(__GNUC__)) && (__x86_64__ || __i386__) && !defined(__MINGW32__) +#if (defined(__clang__) || defined(__GNUC__)) && (__x86_64__ || __i386__) && \ + !defined(__MINGW32__) #include #endif @@ -145,13 +163,14 @@ #endif #elif defined(_XM_ARM_NEON_INTRINSICS_) -#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC)) +#if defined(_MSC_VER) && !defined(__clang__) && \ + (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC)) #include #else #include #endif #endif -#endif // !_XM_NO_INTRINSICS_ +#endif // !_XM_NO_INTRINSICS_ #include "sal.h" #include @@ -170,8 +189,8 @@ #define XM_ALIGNED_DATA(x) alignas(x) #define XM_ALIGNED_STRUCT(x) struct alignas(x) #elif defined(__GNUC__) -#define XM_ALIGNED_DATA(x) __attribute__ ((aligned(x))) -#define XM_ALIGNED_STRUCT(x) struct __attribute__ ((aligned(x))) +#define XM_ALIGNED_DATA(x) __attribute__((aligned(x))) +#define XM_ALIGNED_STRUCT(x) struct __attribute__((aligned(x))) #else #define XM_ALIGNED_DATA(x) __declspec(align(x)) #define XM_ALIGNED_STRUCT(x) __declspec(align(x)) struct @@ -190,57 +209,57 @@ #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) #if defined(_XM_NO_MOVNT_) -#define XM_STREAM_PS( p, a ) _mm_store_ps((p), (a)) -#define XM256_STREAM_PS( p, a ) _mm256_store_ps((p), (a)) +#define XM_STREAM_PS(p, a) _mm_store_ps((p), (a)) +#define XM256_STREAM_PS(p, a) _mm256_store_ps((p), (a)) #define XM_SFENCE() #else -#define XM_STREAM_PS( p, a ) _mm_stream_ps((p), (a)) -#define XM256_STREAM_PS( p, a ) _mm256_stream_ps((p), (a)) +#define XM_STREAM_PS(p, a) _mm_stream_ps((p), (a)) +#define XM256_STREAM_PS(p, a) _mm256_stream_ps((p), (a)) #define XM_SFENCE() _mm_sfence() #endif #if defined(_XM_FMA3_INTRINSICS_) -#define XM_FMADD_PS( a, b, c ) _mm_fmadd_ps((a), (b), (c)) -#define XM_FNMADD_PS( a, b, c ) _mm_fnmadd_ps((a), (b), (c)) +#define XM_FMADD_PS(a, b, c) _mm_fmadd_ps((a), (b), (c)) +#define XM_FNMADD_PS(a, b, c) _mm_fnmadd_ps((a), (b), (c)) #else -#define XM_FMADD_PS( a, b, c ) _mm_add_ps(_mm_mul_ps((a), (b)), (c)) -#define XM_FNMADD_PS( a, b, c ) _mm_sub_ps((c), _mm_mul_ps((a), (b))) +#define XM_FMADD_PS(a, b, c) _mm_add_ps(_mm_mul_ps((a), (b)), (c)) +#define XM_FNMADD_PS(a, b, c) _mm_sub_ps((c), _mm_mul_ps((a), (b))) #endif #if defined(_XM_AVX_INTRINSICS_) && defined(_XM_FAVOR_INTEL_) -#define XM_PERMUTE_PS( v, c ) _mm_permute_ps((v), c ) +#define XM_PERMUTE_PS(v, c) _mm_permute_ps((v), c) #else -#define XM_PERMUTE_PS( v, c ) _mm_shuffle_ps((v), (v), c ) +#define XM_PERMUTE_PS(v, c) _mm_shuffle_ps((v), (v), c) #endif #if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ < 11) -#define XM_LOADU_SI16( p ) _mm_cvtsi32_si128(*reinterpret_cast(p)) +#define XM_LOADU_SI16(p) \ + _mm_cvtsi32_si128(*reinterpret_cast(p)) #else -#define XM_LOADU_SI16( p ) _mm_loadu_si16(p) +#define XM_LOADU_SI16(p) _mm_loadu_si16(p) #endif -#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) #if defined(__clang__) || defined(__GNUC__) -#define XM_PREFETCH( a ) __builtin_prefetch(a) +#define XM_PREFETCH(a) __builtin_prefetch(a) #elif defined(_MSC_VER) -#define XM_PREFETCH( a ) __prefetch(a) +#define XM_PREFETCH(a) __prefetch(a) #else -#define XM_PREFETCH( a ) +#define XM_PREFETCH(a) #endif -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ -namespace DirectX -{ +namespace DirectX { - /**************************************************************************** - * - * Constant definitions - * - ****************************************************************************/ +/**************************************************************************** + * + * Constant definitions + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XM_PI) #undef XM_PI @@ -266,47 +285,47 @@ namespace DirectX #undef XM_CACHE_LINE_SIZE #endif - constexpr float XM_PI = 3.141592654f; - constexpr float XM_2PI = 6.283185307f; - constexpr float XM_1DIVPI = 0.318309886f; - constexpr float XM_1DIV2PI = 0.159154943f; - constexpr float XM_PIDIV2 = 1.570796327f; - constexpr float XM_PIDIV4 = 0.785398163f; +constexpr float XM_PI = 3.141592654f; +constexpr float XM_2PI = 6.283185307f; +constexpr float XM_1DIVPI = 0.318309886f; +constexpr float XM_1DIV2PI = 0.159154943f; +constexpr float XM_PIDIV2 = 1.570796327f; +constexpr float XM_PIDIV4 = 0.785398163f; - constexpr uint32_t XM_SELECT_0 = 0x00000000; - constexpr uint32_t XM_SELECT_1 = 0xFFFFFFFF; +constexpr uint32_t XM_SELECT_0 = 0x00000000; +constexpr uint32_t XM_SELECT_1 = 0xFFFFFFFF; - constexpr uint32_t XM_PERMUTE_0X = 0; - constexpr uint32_t XM_PERMUTE_0Y = 1; - constexpr uint32_t XM_PERMUTE_0Z = 2; - constexpr uint32_t XM_PERMUTE_0W = 3; - constexpr uint32_t XM_PERMUTE_1X = 4; - constexpr uint32_t XM_PERMUTE_1Y = 5; - constexpr uint32_t XM_PERMUTE_1Z = 6; - constexpr uint32_t XM_PERMUTE_1W = 7; +constexpr uint32_t XM_PERMUTE_0X = 0; +constexpr uint32_t XM_PERMUTE_0Y = 1; +constexpr uint32_t XM_PERMUTE_0Z = 2; +constexpr uint32_t XM_PERMUTE_0W = 3; +constexpr uint32_t XM_PERMUTE_1X = 4; +constexpr uint32_t XM_PERMUTE_1Y = 5; +constexpr uint32_t XM_PERMUTE_1Z = 6; +constexpr uint32_t XM_PERMUTE_1W = 7; - constexpr uint32_t XM_SWIZZLE_X = 0; - constexpr uint32_t XM_SWIZZLE_Y = 1; - constexpr uint32_t XM_SWIZZLE_Z = 2; - constexpr uint32_t XM_SWIZZLE_W = 3; +constexpr uint32_t XM_SWIZZLE_X = 0; +constexpr uint32_t XM_SWIZZLE_Y = 1; +constexpr uint32_t XM_SWIZZLE_Z = 2; +constexpr uint32_t XM_SWIZZLE_W = 3; - constexpr uint32_t XM_CRMASK_CR6 = 0x000000F0; - constexpr uint32_t XM_CRMASK_CR6TRUE = 0x00000080; - constexpr uint32_t XM_CRMASK_CR6FALSE = 0x00000020; - constexpr uint32_t XM_CRMASK_CR6BOUNDS = XM_CRMASK_CR6FALSE; +constexpr uint32_t XM_CRMASK_CR6 = 0x000000F0; +constexpr uint32_t XM_CRMASK_CR6TRUE = 0x00000080; +constexpr uint32_t XM_CRMASK_CR6FALSE = 0x00000020; +constexpr uint32_t XM_CRMASK_CR6BOUNDS = XM_CRMASK_CR6FALSE; -#if defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || __arm__ || __aarch64__ - constexpr size_t XM_CACHE_LINE_SIZE = 128; +#if defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || __arm__ || __aarch64__ +constexpr size_t XM_CACHE_LINE_SIZE = 128; #else - constexpr size_t XM_CACHE_LINE_SIZE = 64; +constexpr size_t XM_CACHE_LINE_SIZE = 64; #endif - - /**************************************************************************** - * - * Macros - * - ****************************************************************************/ +/**************************************************************************** + * + * Macros + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XMComparisonAllTrue) #undef XMComparisonAllTrue @@ -318,35 +337,52 @@ namespace DirectX #undef XMComparisonAnyOutOfBounds #endif - // Unit conversion +// Unit conversion - constexpr float XMConvertToRadians(float fDegrees) noexcept { return fDegrees * (XM_PI / 180.0f); } - constexpr float XMConvertToDegrees(float fRadians) noexcept { return fRadians * (180.0f / XM_PI); } +constexpr float XMConvertToRadians(float fDegrees) noexcept { + return fDegrees * (XM_PI / 180.0f); +} +constexpr float XMConvertToDegrees(float fRadians) noexcept { + return fRadians * (180.0f / XM_PI); +} - // Condition register evaluation proceeding a recording (R) comparison +// Condition register evaluation proceeding a recording (R) comparison - constexpr bool XMComparisonAllTrue(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6TRUE) == XM_CRMASK_CR6TRUE; } - constexpr bool XMComparisonAnyTrue(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6FALSE) != XM_CRMASK_CR6FALSE; } - constexpr bool XMComparisonAllFalse(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6FALSE) == XM_CRMASK_CR6FALSE; } - constexpr bool XMComparisonAnyFalse(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6TRUE) != XM_CRMASK_CR6TRUE; } - constexpr bool XMComparisonMixed(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6) == 0; } - constexpr bool XMComparisonAllInBounds(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6BOUNDS) == XM_CRMASK_CR6BOUNDS; } - constexpr bool XMComparisonAnyOutOfBounds(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6BOUNDS) != XM_CRMASK_CR6BOUNDS; } +constexpr bool XMComparisonAllTrue(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6TRUE) == XM_CRMASK_CR6TRUE; +} +constexpr bool XMComparisonAnyTrue(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6FALSE) != XM_CRMASK_CR6FALSE; +} +constexpr bool XMComparisonAllFalse(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6FALSE) == XM_CRMASK_CR6FALSE; +} +constexpr bool XMComparisonAnyFalse(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6TRUE) != XM_CRMASK_CR6TRUE; +} +constexpr bool XMComparisonMixed(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6) == 0; +} +constexpr bool XMComparisonAllInBounds(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6BOUNDS) == XM_CRMASK_CR6BOUNDS; +} +constexpr bool XMComparisonAnyOutOfBounds(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6BOUNDS) != XM_CRMASK_CR6BOUNDS; +} - - /**************************************************************************** - * - * Data types - * - ****************************************************************************/ +/**************************************************************************** + * + * Data types + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4068 4201 4365 4324 4820) - // C4068: ignore unknown pragmas - // C4201: nonstandard extension used : nameless struct/union - // C4365: Off by default noise - // C4324/4820: padding warnings +#pragma warning(disable : 4068 4201 4365 4324 4820) +// C4068: ignore unknown pragmas +// C4201: nonstandard extension used : nameless struct/union +// C4365: Off by default noise +// C4324/4820: padding warnings #endif #ifdef _PREFAST_ @@ -356,470 +392,500 @@ namespace DirectX //------------------------------------------------------------------------------ #if defined(_XM_NO_INTRINSICS_) - struct __vector4 - { - union - { - float vector4_f32[4]; - uint32_t vector4_u32[4]; - }; +struct __vector4 { + union { + float vector4_f32[4]; + uint32_t vector4_u32[4]; }; -#endif // _XM_NO_INTRINSICS_ +}; +#endif // _XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ - // Vector intrinsic: Four 32 bit floating point components aligned on a 16 byte - // boundary and mapped to hardware vector registers +//------------------------------------------------------------------------------ +// Vector intrinsic: Four 32 bit floating point components aligned on a 16 byte +// boundary and mapped to hardware vector registers #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - using XMVECTOR = __m128; +using XMVECTOR = __m128; #elif defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - using XMVECTOR = float32x4_t; +using XMVECTOR = float32x4_t; #else - using XMVECTOR = __vector4; +using XMVECTOR = __vector4; #endif - // Fix-up for (1st-3rd) XMVECTOR parameters that are pass-in-register for x86, ARM, ARM64, and vector call; by reference otherwise -#if ( defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64) || _XM_VECTORCALL_ || __i386__ || __arm__ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR FXMVECTOR; +// Fix-up for (1st-3rd) XMVECTOR parameters that are pass-in-register for x86, +// ARM, ARM64, and vector call; by reference otherwise +#if (defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64) || \ + _XM_VECTORCALL_ || __i386__ || __arm__ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR FXMVECTOR; #else - typedef const XMVECTOR& FXMVECTOR; +typedef const XMVECTOR& FXMVECTOR; #endif - // Fix-up for (4th) XMVECTOR parameter to pass in-register for ARM, ARM64, and vector call; by reference otherwise -#if ( defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __arm__ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR GXMVECTOR; +// Fix-up for (4th) XMVECTOR parameter to pass in-register for ARM, ARM64, and +// vector call; by reference otherwise +#if (defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __arm__ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR GXMVECTOR; #else - typedef const XMVECTOR& GXMVECTOR; +typedef const XMVECTOR& GXMVECTOR; #endif - // Fix-up for (5th & 6th) XMVECTOR parameter to pass in-register for ARM64 and vector call; by reference otherwise -#if ( defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR HXMVECTOR; +// Fix-up for (5th & 6th) XMVECTOR parameter to pass in-register for ARM64 and +// vector call; by reference otherwise +#if (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR HXMVECTOR; #else - typedef const XMVECTOR& HXMVECTOR; +typedef const XMVECTOR& HXMVECTOR; #endif - // Fix-up for (7th+) XMVECTOR parameters to pass by reference - typedef const XMVECTOR& CXMVECTOR; +// Fix-up for (7th+) XMVECTOR parameters to pass by reference +typedef const XMVECTOR& CXMVECTOR; - //------------------------------------------------------------------------------ - // Conversion types for constants - XM_ALIGNED_STRUCT(16) XMVECTORF32 - { - union - { - float f[4]; - XMVECTOR v; - }; - - inline operator XMVECTOR() const noexcept { return v; } - inline operator const float* () const noexcept { return f; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +//------------------------------------------------------------------------------ +// Conversion types for constants +XM_ALIGNED_STRUCT(16) XMVECTORF32 { + union { + float f[4]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORI32 - { - union - { - int32_t i[4]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } + inline operator const float*() const noexcept { return f; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORI32 { + union { + int32_t i[4]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORU8 - { - union - { - uint8_t u[16]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORU8 { + union { + uint8_t u[16]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORU32 - { - union - { - uint32_t u[4]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORU32 { + union { + uint32_t u[4]; + XMVECTOR v; }; - //------------------------------------------------------------------------------ - // Vector operators + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; + +//------------------------------------------------------------------------------ +// Vector operators #ifndef _XM_NO_XMVECTOR_OVERLOADS_ - XMVECTOR XM_CALLCONV operator+ (FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV operator- (FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator+(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator-(FXMVECTOR V) noexcept; - XMVECTOR& XM_CALLCONV operator+= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator-= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator*= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator/= (XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator+=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator-=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator*=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator/=(XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& operator*= (XMVECTOR& V, float S) noexcept; - XMVECTOR& operator/= (XMVECTOR& V, float S) noexcept; +XMVECTOR& operator*=(XMVECTOR& V, float S) noexcept; +XMVECTOR& operator/=(XMVECTOR& V, float S) noexcept; - XMVECTOR XM_CALLCONV operator+ (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator- (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator* (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator/ (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator* (FXMVECTOR V, float S) noexcept; - XMVECTOR XM_CALLCONV operator* (float S, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV operator/ (FXMVECTOR V, float S) noexcept; +XMVECTOR XM_CALLCONV operator+(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator-(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator*(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator/(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator*(FXMVECTOR V, float S) noexcept; +XMVECTOR XM_CALLCONV operator*(float S, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator/(FXMVECTOR V, float S) noexcept; #endif /* !_XM_NO_XMVECTOR_OVERLOADS_ */ - //------------------------------------------------------------------------------ - // Matrix type: Sixteen 32 bit floating point components aligned on a - // 16 byte boundary and mapped to four hardware vector registers +//------------------------------------------------------------------------------ +// Matrix type: Sixteen 32 bit floating point components aligned on a +// 16 byte boundary and mapped to four hardware vector registers - struct XMMATRIX; +struct XMMATRIX; - // Fix-up for (1st) XMMATRIX parameter to pass in-register for ARM64 and vector call; by reference otherwise -#if ( defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMMATRIX FXMMATRIX; +// Fix-up for (1st) XMMATRIX parameter to pass in-register for ARM64 and vector +// call; by reference otherwise +#if (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMMATRIX FXMMATRIX; #else - typedef const XMMATRIX& FXMMATRIX; +typedef const XMMATRIX& FXMMATRIX; #endif - // Fix-up for (2nd+) XMMATRIX parameters to pass by reference - typedef const XMMATRIX& CXMMATRIX; +// Fix-up for (2nd+) XMMATRIX parameters to pass by reference +typedef const XMMATRIX& CXMMATRIX; #ifdef _XM_NO_INTRINSICS_ - struct XMMATRIX - #else - XM_ALIGNED_STRUCT(16) XMMATRIX - #endif - { - #ifdef _XM_NO_INTRINSICS_ - union - { - XMVECTOR r[4]; - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - float _41, _42, _43, _44; - }; - float m[4][4]; - }; - #else +struct XMMATRIX +#else +XM_ALIGNED_STRUCT(16) +XMMATRIX +#endif +{ +#ifdef _XM_NO_INTRINSICS_ + union { XMVECTOR r[4]; - #endif - - XMMATRIX() = default; - - XMMATRIX(const XMMATRIX&) = default; - - #if defined(_MSC_VER) && (_MSC_FULL_VER < 191426431) - XMMATRIX& operator= (const XMMATRIX& M) noexcept { r[0] = M.r[0]; r[1] = M.r[1]; r[2] = M.r[2]; r[3] = M.r[3]; return *this; } - #else - XMMATRIX& operator=(const XMMATRIX&) = default; - - XMMATRIX(XMMATRIX&&) = default; - XMMATRIX& operator=(XMMATRIX&&) = default; - #endif - - constexpr XMMATRIX(FXMVECTOR R0, FXMVECTOR R1, FXMVECTOR R2, CXMVECTOR R3) noexcept : r{ R0,R1,R2,R3 } {} - XMMATRIX(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept; - explicit XMMATRIX(_In_reads_(16) const float* pArray) noexcept; - - #ifdef _XM_NO_INTRINSICS_ - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - #endif - - XMMATRIX operator+ () const noexcept { return *this; } - XMMATRIX operator- () const noexcept; - - XMMATRIX& XM_CALLCONV operator+= (FXMMATRIX M) noexcept; - XMMATRIX& XM_CALLCONV operator-= (FXMMATRIX M) noexcept; - XMMATRIX& XM_CALLCONV operator*= (FXMMATRIX M) noexcept; - XMMATRIX& operator*= (float S) noexcept; - XMMATRIX& operator/= (float S) noexcept; - - XMMATRIX XM_CALLCONV operator+ (FXMMATRIX M) const noexcept; - XMMATRIX XM_CALLCONV operator- (FXMMATRIX M) const noexcept; - XMMATRIX XM_CALLCONV operator* (FXMMATRIX M) const noexcept; - XMMATRIX operator* (float S) const noexcept; - XMMATRIX operator/ (float S) const noexcept; - - friend XMMATRIX XM_CALLCONV operator* (float S, FXMMATRIX M) noexcept; + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; + float _41, _42, _43, _44; + }; + float m[4][4]; }; +#else + XMVECTOR r[4]; +#endif - //------------------------------------------------------------------------------ - // 2D Vector; 32 bit floating point components - struct XMFLOAT2 - { - float x; - float y; + XMMATRIX() = default; - XMFLOAT2() = default; + XMMATRIX(const XMMATRIX&) = default; - XMFLOAT2(const XMFLOAT2&) = default; - XMFLOAT2& operator=(const XMFLOAT2&) = default; +#if defined(_MSC_VER) && (_MSC_FULL_VER < 191426431) + XMMATRIX& operator=(const XMMATRIX& M) noexcept { + r[0] = M.r[0]; + r[1] = M.r[1]; + r[2] = M.r[2]; + r[3] = M.r[3]; + return *this; + } +#else + XMMATRIX& operator=(const XMMATRIX&) = default; - XMFLOAT2(XMFLOAT2&&) = default; - XMFLOAT2& operator=(XMFLOAT2&&) = default; + XMMATRIX(XMMATRIX&&) = default; + XMMATRIX& operator=(XMMATRIX&&) = default; +#endif - constexpr XMFLOAT2(float _x, float _y) noexcept : x(_x), y(_y) {} - explicit XMFLOAT2(_In_reads_(2) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} + constexpr XMMATRIX(FXMVECTOR R0, FXMVECTOR R1, FXMVECTOR R2, + CXMVECTOR R3) noexcept + : r{R0, R1, R2, R3} {} + XMMATRIX(float m00, float m01, float m02, float m03, float m10, float m11, + float m12, float m13, float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33) noexcept; + explicit XMMATRIX(_In_reads_(16) const float* pArray) noexcept; - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT2&) const = default; - auto operator <=> (const XMFLOAT2&) const = default; - #endif - }; +#ifdef _XM_NO_INTRINSICS_ + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } +#endif - // 2D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT2A : public XMFLOAT2 - { - using XMFLOAT2::XMFLOAT2; - }; + XMMATRIX operator+() const noexcept { return *this; } + XMMATRIX operator-() const noexcept; - //------------------------------------------------------------------------------ - // 2D Vector; 32 bit signed integer components - struct XMINT2 - { - int32_t x; - int32_t y; + XMMATRIX& XM_CALLCONV operator+=(FXMMATRIX M) noexcept; + XMMATRIX& XM_CALLCONV operator-=(FXMMATRIX M) noexcept; + XMMATRIX& XM_CALLCONV operator*=(FXMMATRIX M) noexcept; + XMMATRIX& operator*=(float S) noexcept; + XMMATRIX& operator/=(float S) noexcept; - XMINT2() = default; + XMMATRIX XM_CALLCONV operator+(FXMMATRIX M) const noexcept; + XMMATRIX XM_CALLCONV operator-(FXMMATRIX M) const noexcept; + XMMATRIX XM_CALLCONV operator*(FXMMATRIX M) const noexcept; + XMMATRIX operator*(float S) const noexcept; + XMMATRIX operator/(float S) const noexcept; - XMINT2(const XMINT2&) = default; - XMINT2& operator=(const XMINT2&) = default; + friend XMMATRIX XM_CALLCONV operator*(float S, FXMMATRIX M) noexcept; +}; - XMINT2(XMINT2&&) = default; - XMINT2& operator=(XMINT2&&) = default; +//------------------------------------------------------------------------------ +// 2D Vector; 32 bit floating point components +struct XMFLOAT2 { + float x; + float y; - constexpr XMINT2(int32_t _x, int32_t _y) noexcept : x(_x), y(_y) {} - explicit XMINT2(_In_reads_(2) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} + XMFLOAT2() = default; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT2&) const = default; - auto operator <=> (const XMINT2&) const = default; - #endif - }; + XMFLOAT2(const XMFLOAT2&) = default; + XMFLOAT2& operator=(const XMFLOAT2&) = default; - // 2D Vector; 32 bit unsigned integer components - struct XMUINT2 - { - uint32_t x; - uint32_t y; + XMFLOAT2(XMFLOAT2&&) = default; + XMFLOAT2& operator=(XMFLOAT2&&) = default; - XMUINT2() = default; + constexpr XMFLOAT2(float _x, float _y) noexcept : x(_x), y(_y) {} + explicit XMFLOAT2(_In_reads_(2) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMUINT2(const XMUINT2&) = default; - XMUINT2& operator=(const XMUINT2&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT2&) const = default; + auto operator<=>(const XMFLOAT2&) const = default; +#endif +}; - XMUINT2(XMUINT2&&) = default; - XMUINT2& operator=(XMUINT2&&) = default; +// 2D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT2A : public XMFLOAT2 { using XMFLOAT2::XMFLOAT2; }; - constexpr XMUINT2(uint32_t _x, uint32_t _y) noexcept : x(_x), y(_y) {} - explicit XMUINT2(_In_reads_(2) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} +//------------------------------------------------------------------------------ +// 2D Vector; 32 bit signed integer components +struct XMINT2 { + int32_t x; + int32_t y; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT2&) const = default; - auto operator <=> (const XMUINT2&) const = default; - #endif - }; + XMINT2() = default; - //------------------------------------------------------------------------------ - // 3D Vector; 32 bit floating point components - struct XMFLOAT3 - { - float x; - float y; - float z; + XMINT2(const XMINT2&) = default; + XMINT2& operator=(const XMINT2&) = default; - XMFLOAT3() = default; + XMINT2(XMINT2&&) = default; + XMINT2& operator=(XMINT2&&) = default; - XMFLOAT3(const XMFLOAT3&) = default; - XMFLOAT3& operator=(const XMFLOAT3&) = default; + constexpr XMINT2(int32_t _x, int32_t _y) noexcept : x(_x), y(_y) {} + explicit XMINT2(_In_reads_(2) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMFLOAT3(XMFLOAT3&&) = default; - XMFLOAT3& operator=(XMFLOAT3&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMINT2&) const = default; + auto operator<=>(const XMINT2&) const = default; +#endif +}; - constexpr XMFLOAT3(float _x, float _y, float _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMFLOAT3(_In_reads_(3) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - }; +// 2D Vector; 32 bit unsigned integer components +struct XMUINT2 { + uint32_t x; + uint32_t y; - // 3D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT3A : public XMFLOAT3 - { - using XMFLOAT3::XMFLOAT3; - }; + XMUINT2() = default; - //------------------------------------------------------------------------------ - // 3D Vector; 32 bit signed integer components - struct XMINT3 - { - int32_t x; - int32_t y; - int32_t z; + XMUINT2(const XMUINT2&) = default; + XMUINT2& operator=(const XMUINT2&) = default; - XMINT3() = default; + XMUINT2(XMUINT2&&) = default; + XMUINT2& operator=(XMUINT2&&) = default; - XMINT3(const XMINT3&) = default; - XMINT3& operator=(const XMINT3&) = default; + constexpr XMUINT2(uint32_t _x, uint32_t _y) noexcept : x(_x), y(_y) {} + explicit XMUINT2(_In_reads_(2) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMINT3(XMINT3&&) = default; - XMINT3& operator=(XMINT3&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT2&) const = default; + auto operator<=>(const XMUINT2&) const = default; +#endif +}; - constexpr XMINT3(int32_t _x, int32_t _y, int32_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMINT3(_In_reads_(3) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +//------------------------------------------------------------------------------ +// 3D Vector; 32 bit floating point components +struct XMFLOAT3 { + float x; + float y; + float z; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT3&) const = default; - auto operator <=> (const XMINT3&) const = default; - #endif - }; + XMFLOAT3() = default; - // 3D Vector; 32 bit unsigned integer components - struct XMUINT3 - { - uint32_t x; - uint32_t y; - uint32_t z; + XMFLOAT3(const XMFLOAT3&) = default; + XMFLOAT3& operator=(const XMFLOAT3&) = default; - XMUINT3() = default; + XMFLOAT3(XMFLOAT3&&) = default; + XMFLOAT3& operator=(XMFLOAT3&&) = default; - XMUINT3(const XMUINT3&) = default; - XMUINT3& operator=(const XMUINT3&) = default; + constexpr XMFLOAT3(float _x, float _y, float _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMFLOAT3(_In_reads_(3) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +}; - XMUINT3(XMUINT3&&) = default; - XMUINT3& operator=(XMUINT3&&) = default; +// 3D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT3A : public XMFLOAT3 { using XMFLOAT3::XMFLOAT3; }; - constexpr XMUINT3(uint32_t _x, uint32_t _y, uint32_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMUINT3(_In_reads_(3) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +//------------------------------------------------------------------------------ +// 3D Vector; 32 bit signed integer components +struct XMINT3 { + int32_t x; + int32_t y; + int32_t z; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT3&) const = default; - auto operator <=> (const XMUINT3&) const = default; - #endif - }; + XMINT3() = default; - //------------------------------------------------------------------------------ - // 4D Vector; 32 bit floating point components - struct XMFLOAT4 - { - float x; - float y; - float z; - float w; + XMINT3(const XMINT3&) = default; + XMINT3& operator=(const XMINT3&) = default; - XMFLOAT4() = default; + XMINT3(XMINT3&&) = default; + XMINT3& operator=(XMINT3&&) = default; - XMFLOAT4(const XMFLOAT4&) = default; - XMFLOAT4& operator=(const XMFLOAT4&) = default; + constexpr XMINT3(int32_t _x, int32_t _y, int32_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMINT3(_In_reads_(3) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMFLOAT4(XMFLOAT4&&) = default; - XMFLOAT4& operator=(XMFLOAT4&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMINT3&) const = default; + auto operator<=>(const XMINT3&) const = default; +#endif +}; - constexpr XMFLOAT4(float _x, float _y, float _z, float _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMFLOAT4(_In_reads_(4) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} +// 3D Vector; 32 bit unsigned integer components +struct XMUINT3 { + uint32_t x; + uint32_t y; + uint32_t z; - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4&) const = default; - auto operator <=> (const XMFLOAT4&) const = default; - #endif - }; + XMUINT3() = default; - // 4D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4A : public XMFLOAT4 - { - using XMFLOAT4::XMFLOAT4; - }; + XMUINT3(const XMUINT3&) = default; + XMUINT3& operator=(const XMUINT3&) = default; - //------------------------------------------------------------------------------ - // 4D Vector; 32 bit signed integer components - struct XMINT4 - { - int32_t x; - int32_t y; - int32_t z; - int32_t w; + XMUINT3(XMUINT3&&) = default; + XMUINT3& operator=(XMUINT3&&) = default; - XMINT4() = default; + constexpr XMUINT3(uint32_t _x, uint32_t _y, uint32_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMUINT3(_In_reads_(3) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMINT4(const XMINT4&) = default; - XMINT4& operator=(const XMINT4&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT3&) const = default; + auto operator<=>(const XMUINT3&) const = default; +#endif +}; - XMINT4(XMINT4&&) = default; - XMINT4& operator=(XMINT4&&) = default; +//------------------------------------------------------------------------------ +// 4D Vector; 32 bit floating point components +struct XMFLOAT4 { + float x; + float y; + float z; + float w; - constexpr XMINT4(int32_t _x, int32_t _y, int32_t _z, int32_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMINT4(_In_reads_(4) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMFLOAT4() = default; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT4&) const = default; - auto operator <=> (const XMINT4&) const = default; - #endif - }; + XMFLOAT4(const XMFLOAT4&) = default; + XMFLOAT4& operator=(const XMFLOAT4&) = default; - // 4D Vector; 32 bit unsigned integer components - struct XMUINT4 - { - uint32_t x; - uint32_t y; - uint32_t z; - uint32_t w; + XMFLOAT4(XMFLOAT4&&) = default; + XMFLOAT4& operator=(XMFLOAT4&&) = default; - XMUINT4() = default; + constexpr XMFLOAT4(float _x, float _y, float _z, float _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMFLOAT4(_In_reads_(4) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUINT4(const XMUINT4&) = default; - XMUINT4& operator=(const XMUINT4&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4&) const = default; + auto operator<=>(const XMFLOAT4&) const = default; +#endif +}; - XMUINT4(XMUINT4&&) = default; - XMUINT4& operator=(XMUINT4&&) = default; +// 4D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4A : public XMFLOAT4 { using XMFLOAT4::XMFLOAT4; }; - constexpr XMUINT4(uint32_t _x, uint32_t _y, uint32_t _z, uint32_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUINT4(_In_reads_(4) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} +//------------------------------------------------------------------------------ +// 4D Vector; 32 bit signed integer components +struct XMINT4 { + int32_t x; + int32_t y; + int32_t z; + int32_t w; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT4&) const = default; - auto operator <=> (const XMUINT4&) const = default; - #endif - }; + XMINT4() = default; + + XMINT4(const XMINT4&) = default; + XMINT4& operator=(const XMINT4&) = default; + + XMINT4(XMINT4&&) = default; + XMINT4& operator=(XMINT4&&) = default; + + constexpr XMINT4(int32_t _x, int32_t _y, int32_t _z, int32_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMINT4(_In_reads_(4) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + +#if (__cplusplus >= 202002L) + bool operator==(const XMINT4&) const = default; + auto operator<=>(const XMINT4&) const = default; +#endif +}; + +// 4D Vector; 32 bit unsigned integer components +struct XMUINT4 { + uint32_t x; + uint32_t y; + uint32_t z; + uint32_t w; + + XMUINT4() = default; + + XMUINT4(const XMUINT4&) = default; + XMUINT4& operator=(const XMUINT4&) = default; + + XMUINT4(XMUINT4&&) = default; + XMUINT4& operator=(XMUINT4&&) = default; + + constexpr XMUINT4(uint32_t _x, uint32_t _y, uint32_t _z, + uint32_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUINT4(_In_reads_(4) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT4&) const = default; + auto operator<=>(const XMUINT4&) const = default; +#endif +}; #ifdef __clang__ #pragma clang diagnostic push @@ -829,197 +895,229 @@ namespace DirectX #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" #endif - //------------------------------------------------------------------------------ - // 3x3 Matrix: 32 bit floating point components - struct XMFLOAT3X3 - { - union - { - struct - { - float _11, _12, _13; - float _21, _22, _23; - float _31, _32, _33; - }; - float m[3][3]; +//------------------------------------------------------------------------------ +// 3x3 Matrix: 32 bit floating point components +struct XMFLOAT3X3 { + union { + struct { + float _11, _12, _13; + float _21, _22, _23; + float _31, _32, _33; }; - - XMFLOAT3X3() = default; - - XMFLOAT3X3(const XMFLOAT3X3&) = default; - XMFLOAT3X3& operator=(const XMFLOAT3X3&) = default; - - XMFLOAT3X3(XMFLOAT3X3&&) = default; - XMFLOAT3X3& operator=(XMFLOAT3X3&&) = default; - - constexpr XMFLOAT3X3(float m00, float m01, float m02, - float m10, float m11, float m12, - float m20, float m21, float m22) noexcept - : _11(m00), _12(m01), _13(m02), - _21(m10), _22(m11), _23(m12), - _31(m20), _32(m21), _33(m22) - {} - explicit XMFLOAT3X3(_In_reads_(9) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT3X3&) const = default; - auto operator <=> (const XMFLOAT3X3&) const = default; - #endif + float m[3][3]; }; - //------------------------------------------------------------------------------ - // 4x3 Row-major Matrix: 32 bit floating point components - struct XMFLOAT4X3 - { - union - { - struct - { - float _11, _12, _13; - float _21, _22, _23; - float _31, _32, _33; - float _41, _42, _43; - }; - float m[4][3]; - float f[12]; + XMFLOAT3X3() = default; + + XMFLOAT3X3(const XMFLOAT3X3&) = default; + XMFLOAT3X3& operator=(const XMFLOAT3X3&) = default; + + XMFLOAT3X3(XMFLOAT3X3&&) = default; + XMFLOAT3X3& operator=(XMFLOAT3X3&&) = default; + + constexpr XMFLOAT3X3(float m00, float m01, float m02, float m10, float m11, + float m12, float m20, float m21, float m22) noexcept + : _11(m00), + _12(m01), + _13(m02), + _21(m10), + _22(m11), + _23(m12), + _31(m20), + _32(m21), + _33(m22) {} + explicit XMFLOAT3X3(_In_reads_(9) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT3X3&) const = default; + auto operator<=>(const XMFLOAT3X3&) const = default; +#endif +}; + +//------------------------------------------------------------------------------ +// 4x3 Row-major Matrix: 32 bit floating point components +struct XMFLOAT4X3 { + union { + struct { + float _11, _12, _13; + float _21, _22, _23; + float _31, _32, _33; + float _41, _42, _43; }; - - XMFLOAT4X3() = default; - - XMFLOAT4X3(const XMFLOAT4X3&) = default; - XMFLOAT4X3& operator=(const XMFLOAT4X3&) = default; - - XMFLOAT4X3(XMFLOAT4X3&&) = default; - XMFLOAT4X3& operator=(XMFLOAT4X3&&) = default; - - constexpr XMFLOAT4X3(float m00, float m01, float m02, - float m10, float m11, float m12, - float m20, float m21, float m22, - float m30, float m31, float m32) noexcept - : _11(m00), _12(m01), _13(m02), - _21(m10), _22(m11), _23(m12), - _31(m20), _32(m21), _33(m22), - _41(m30), _42(m31), _43(m32) - {} - explicit XMFLOAT4X3(_In_reads_(12) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4X3&) const = default; - auto operator <=> (const XMFLOAT4X3&) const = default; - #endif + float m[4][3]; + float f[12]; }; - // 4x3 Row-major Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4X3A : public XMFLOAT4X3 - { - using XMFLOAT4X3::XMFLOAT4X3; - }; + XMFLOAT4X3() = default; - //------------------------------------------------------------------------------ - // 3x4 Column-major Matrix: 32 bit floating point components - struct XMFLOAT3X4 - { - union - { - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - }; - float m[3][4]; - float f[12]; + XMFLOAT4X3(const XMFLOAT4X3&) = default; + XMFLOAT4X3& operator=(const XMFLOAT4X3&) = default; + + XMFLOAT4X3(XMFLOAT4X3&&) = default; + XMFLOAT4X3& operator=(XMFLOAT4X3&&) = default; + + constexpr XMFLOAT4X3(float m00, float m01, float m02, float m10, float m11, + float m12, float m20, float m21, float m22, float m30, + float m31, float m32) noexcept + : _11(m00), + _12(m01), + _13(m02), + _21(m10), + _22(m11), + _23(m12), + _31(m20), + _32(m21), + _33(m22), + _41(m30), + _42(m31), + _43(m32) {} + explicit XMFLOAT4X3(_In_reads_(12) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4X3&) const = default; + auto operator<=>(const XMFLOAT4X3&) const = default; +#endif +}; + +// 4x3 Row-major Matrix: 32 bit floating point components aligned on a 16 byte +// boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4X3A : public XMFLOAT4X3 { + using XMFLOAT4X3::XMFLOAT4X3; +}; + +//------------------------------------------------------------------------------ +// 3x4 Column-major Matrix: 32 bit floating point components +struct XMFLOAT3X4 { + union { + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; }; - - XMFLOAT3X4() = default; - - XMFLOAT3X4(const XMFLOAT3X4&) = default; - XMFLOAT3X4& operator=(const XMFLOAT3X4&) = default; - - XMFLOAT3X4(XMFLOAT3X4&&) = default; - XMFLOAT3X4& operator=(XMFLOAT3X4&&) = default; - - constexpr XMFLOAT3X4(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23) noexcept - : _11(m00), _12(m01), _13(m02), _14(m03), - _21(m10), _22(m11), _23(m12), _24(m13), - _31(m20), _32(m21), _33(m22), _34(m23) - {} - explicit XMFLOAT3X4(_In_reads_(12) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT3X4&) const = default; - auto operator <=> (const XMFLOAT3X4&) const = default; - #endif + float m[3][4]; + float f[12]; }; - // 3x4 Column-major Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT3X4A : public XMFLOAT3X4 - { - using XMFLOAT3X4::XMFLOAT3X4; - }; + XMFLOAT3X4() = default; - //------------------------------------------------------------------------------ - // 4x4 Matrix: 32 bit floating point components - struct XMFLOAT4X4 - { - union - { - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - float _41, _42, _43, _44; - }; - float m[4][4]; + XMFLOAT3X4(const XMFLOAT3X4&) = default; + XMFLOAT3X4& operator=(const XMFLOAT3X4&) = default; + + XMFLOAT3X4(XMFLOAT3X4&&) = default; + XMFLOAT3X4& operator=(XMFLOAT3X4&&) = default; + + constexpr XMFLOAT3X4(float m00, float m01, float m02, float m03, float m10, + float m11, float m12, float m13, float m20, float m21, + float m22, float m23) noexcept + : _11(m00), + _12(m01), + _13(m02), + _14(m03), + _21(m10), + _22(m11), + _23(m12), + _24(m13), + _31(m20), + _32(m21), + _33(m22), + _34(m23) {} + explicit XMFLOAT3X4(_In_reads_(12) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT3X4&) const = default; + auto operator<=>(const XMFLOAT3X4&) const = default; +#endif +}; + +// 3x4 Column-major Matrix: 32 bit floating point components aligned on a 16 +// byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT3X4A : public XMFLOAT3X4 { + using XMFLOAT3X4::XMFLOAT3X4; +}; + +//------------------------------------------------------------------------------ +// 4x4 Matrix: 32 bit floating point components +struct XMFLOAT4X4 { + union { + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; + float _41, _42, _43, _44; }; - - XMFLOAT4X4() = default; - - XMFLOAT4X4(const XMFLOAT4X4&) = default; - XMFLOAT4X4& operator=(const XMFLOAT4X4&) = default; - - XMFLOAT4X4(XMFLOAT4X4&&) = default; - XMFLOAT4X4& operator=(XMFLOAT4X4&&) = default; - - constexpr XMFLOAT4X4(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept - : _11(m00), _12(m01), _13(m02), _14(m03), - _21(m10), _22(m11), _23(m12), _24(m13), - _31(m20), _32(m21), _33(m22), _34(m23), - _41(m30), _42(m31), _43(m32), _44(m33) - {} - explicit XMFLOAT4X4(_In_reads_(16) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4X4&) const = default; - auto operator <=> (const XMFLOAT4X4&) const = default; - #endif + float m[4][4]; }; - // 4x4 Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4X4A : public XMFLOAT4X4 - { - using XMFLOAT4X4::XMFLOAT4X4; - }; + XMFLOAT4X4() = default; - //////////////////////////////////////////////////////////////////////////////// + XMFLOAT4X4(const XMFLOAT4X4&) = default; + XMFLOAT4X4& operator=(const XMFLOAT4X4&) = default; + + XMFLOAT4X4(XMFLOAT4X4&&) = default; + XMFLOAT4X4& operator=(XMFLOAT4X4&&) = default; + + constexpr XMFLOAT4X4(float m00, float m01, float m02, float m03, float m10, + float m11, float m12, float m13, float m20, float m21, + float m22, float m23, float m30, float m31, float m32, + float m33) noexcept + : _11(m00), + _12(m01), + _13(m02), + _14(m03), + _21(m10), + _22(m11), + _23(m12), + _24(m13), + _31(m20), + _32(m21), + _33(m22), + _34(m23), + _41(m30), + _42(m31), + _43(m32), + _44(m33) {} + explicit XMFLOAT4X4(_In_reads_(16) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4X4&) const = default; + auto operator<=>(const XMFLOAT4X4&) const = default; +#endif +}; + +// 4x4 Matrix: 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4X4A : public XMFLOAT4X4 { + using XMFLOAT4X4::XMFLOAT4X4; +}; + +//////////////////////////////////////////////////////////////////////////////// #ifdef __clang__ #pragma clang diagnostic pop @@ -1037,10 +1135,14 @@ namespace DirectX * ****************************************************************************/ - XMVECTOR XM_CALLCONV XMConvertVectorIntToFloat(FXMVECTOR VInt, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorFloatToInt(FXMVECTOR VFloat, uint32_t MulExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorUIntToFloat(FXMVECTOR VUInt, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorFloatToUInt(FXMVECTOR VFloat, uint32_t MulExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorIntToFloat(FXMVECTOR VInt, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorFloatToInt(FXMVECTOR VFloat, + uint32_t MulExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorUIntToFloat(FXMVECTOR VUInt, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorFloatToUInt(FXMVECTOR VFloat, + uint32_t MulExponent) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorSetBinaryConstant) #undef XMVectorSetBinaryConstant @@ -1048,169 +1150,232 @@ namespace DirectX #undef XMVectorSplatConstantInt #endif - XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, uint32_t C2, uint32_t C3) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, + uint32_t C2, + uint32_t C3) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept; - /**************************************************************************** - * - * Load operations - * - ****************************************************************************/ +/**************************************************************************** + * + * Load operations + * + ****************************************************************************/ - XMVECTOR XM_CALLCONV XMLoadInt(_In_ const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat(_In_ const float* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt(_In_ const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat(_In_ const float* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt2(_In_reads_(2) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt2A(_In_reads_(2) const uint32_t* PSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat2(_In_ const XMFLOAT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat2A(_In_ const XMFLOAT2A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt2(_In_ const XMINT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt2(_In_ const XMUINT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt2(_In_reads_(2) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt2A(_In_reads_(2) + const uint32_t* PSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat2(_In_ const XMFLOAT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat2A(_In_ const XMFLOAT2A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt2(_In_ const XMINT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt2(_In_ const XMUINT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt3(_In_reads_(3) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt3A(_In_reads_(3) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3(_In_ const XMFLOAT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3A(_In_ const XMFLOAT3A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt3(_In_ const XMINT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt3(_In_ const XMUINT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt3(_In_reads_(3) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt3A(_In_reads_(3) + const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3(_In_ const XMFLOAT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3A(_In_ const XMFLOAT3A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt3(_In_ const XMINT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt3(_In_ const XMUINT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt4(_In_reads_(4) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt4A(_In_reads_(4) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat4(_In_ const XMFLOAT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat4A(_In_ const XMFLOAT4A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt4(_In_ const XMINT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt4(_In_ const XMUINT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt4(_In_reads_(4) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt4A(_In_reads_(4) + const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat4(_In_ const XMFLOAT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat4A(_In_ const XMFLOAT4A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt4(_In_ const XMINT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt4(_In_ const XMUINT4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x3(_In_ const XMFLOAT3X3* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x3(_In_ const XMFLOAT4X3* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x3A(_In_ const XMFLOAT4X3A* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x4(_In_ const XMFLOAT3X4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x4A(_In_ const XMFLOAT3X4A* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x4(_In_ const XMFLOAT4X4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x4A(_In_ const XMFLOAT4X4A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x3(_In_ const XMFLOAT3X3* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x3(_In_ const XMFLOAT4X3* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x3A(_In_ const XMFLOAT4X3A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x4(_In_ const XMFLOAT3X4* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x4A(_In_ const XMFLOAT3X4A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x4(_In_ const XMFLOAT4X4* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x4A(_In_ const XMFLOAT4X4A* pSource) noexcept; - /**************************************************************************** - * - * Store operations - * - ****************************************************************************/ +/**************************************************************************** + * + * Store operations + * + ****************************************************************************/ - void XM_CALLCONV XMStoreInt(_Out_ uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat(_Out_ float* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt(_Out_ uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat(_Out_ float* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt2(_Out_writes_(2) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt2A(_Out_writes_(2) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat2(_Out_ XMFLOAT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat2A(_Out_ XMFLOAT2A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt2(_Out_ XMINT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt2(_Out_ XMUINT2* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt2(_Out_writes_(2) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt2A(_Out_writes_(2) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat2(_Out_ XMFLOAT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat2A(_Out_ XMFLOAT2A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt2(_Out_ XMINT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt2(_Out_ XMUINT2* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt3(_Out_writes_(3) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt3A(_Out_writes_(3) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3(_Out_ XMFLOAT3* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3A(_Out_ XMFLOAT3A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt3(_Out_ XMINT3* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt3(_Out_ XMUINT3* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt3(_Out_writes_(3) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt3A(_Out_writes_(3) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3(_Out_ XMFLOAT3* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3A(_Out_ XMFLOAT3A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt3(_Out_ XMINT3* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt3(_Out_ XMUINT3* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt4(_Out_writes_(4) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt4A(_Out_writes_(4) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat4(_Out_ XMFLOAT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat4A(_Out_ XMFLOAT4A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt4(_Out_ XMINT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt4(_Out_ XMUINT4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt4(_Out_writes_(4) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt4A(_Out_writes_(4) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat4(_Out_ XMFLOAT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat4A(_Out_ XMFLOAT4A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt4(_Out_ XMINT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt4(_Out_ XMUINT4* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3x3(_Out_ XMFLOAT3X3* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x3(_Out_ XMFLOAT4X3* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x3A(_Out_ XMFLOAT4X3A* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat3x4(_Out_ XMFLOAT3X4* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat3x4A(_Out_ XMFLOAT3X4A* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x4(_Out_ XMFLOAT4X4* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x4A(_Out_ XMFLOAT4X4A* pDestination, _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x3(_Out_ XMFLOAT3X3* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x3(_Out_ XMFLOAT4X3* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x3A(_Out_ XMFLOAT4X3A* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x4(_Out_ XMFLOAT3X4* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x4A(_Out_ XMFLOAT3X4A* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x4(_Out_ XMFLOAT4X4* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x4A(_Out_ XMFLOAT4X4A* pDestination, + _In_ FXMMATRIX M) noexcept; - /**************************************************************************** - * - * General vector operations - * - ****************************************************************************/ +/**************************************************************************** + * + * General vector operations + * + ****************************************************************************/ - XMVECTOR XM_CALLCONV XMVectorZero() noexcept; - XMVECTOR XM_CALLCONV XMVectorSet(float x, float y, float z, float w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetInt(uint32_t x, uint32_t y, uint32_t z, uint32_t w) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicate(float Value) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicatePtr(_In_ const float* pValue) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicateInt(uint32_t Value) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicateIntPtr(_In_ const uint32_t* pValue) noexcept; - XMVECTOR XM_CALLCONV XMVectorTrueInt() noexcept; - XMVECTOR XM_CALLCONV XMVectorFalseInt() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatX(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatY(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatZ(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatW(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatOne() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatInfinity() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatQNaN() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatEpsilon() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatSignMask() noexcept; +XMVECTOR XM_CALLCONV XMVectorZero() noexcept; +XMVECTOR XM_CALLCONV XMVectorSet(float x, float y, float z, float w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetInt(uint32_t x, uint32_t y, uint32_t z, + uint32_t w) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicate(float Value) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicatePtr(_In_ const float* pValue) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicateInt(uint32_t Value) noexcept; +XMVECTOR XM_CALLCONV +XMVectorReplicateIntPtr(_In_ const uint32_t* pValue) noexcept; +XMVECTOR XM_CALLCONV XMVectorTrueInt() noexcept; +XMVECTOR XM_CALLCONV XMVectorFalseInt() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatX(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatY(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatZ(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatW(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatOne() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatInfinity() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatQNaN() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatEpsilon() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatSignMask() noexcept; - float XM_CALLCONV XMVectorGetByIndex(FXMVECTOR V, size_t i) noexcept; - float XM_CALLCONV XMVectorGetX(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetY(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetZ(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetW(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetByIndex(FXMVECTOR V, size_t i) noexcept; +float XM_CALLCONV XMVectorGetX(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetY(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetZ(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetW(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetByIndexPtr(_Out_ float* f, _In_ FXMVECTOR V, _In_ size_t i) noexcept; - void XM_CALLCONV XMVectorGetXPtr(_Out_ float* x, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetYPtr(_Out_ float* y, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetZPtr(_Out_ float* z, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetWPtr(_Out_ float* w, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetByIndexPtr(_Out_ float* f, _In_ FXMVECTOR V, + _In_ size_t i) noexcept; +void XM_CALLCONV XMVectorGetXPtr(_Out_ float* x, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetYPtr(_Out_ float* y, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetZPtr(_Out_ float* z, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetWPtr(_Out_ float* w, _In_ FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntByIndex(FXMVECTOR V, size_t i) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntX(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntY(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntZ(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntW(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntByIndex(FXMVECTOR V, size_t i) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntX(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntY(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntZ(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntW(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntByIndexPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V, _In_ size_t i) noexcept; - void XM_CALLCONV XMVectorGetIntXPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntYPtr(_Out_ uint32_t* y, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntZPtr(_Out_ uint32_t* z, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntWPtr(_Out_ uint32_t* w, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntByIndexPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V, + _In_ size_t i) noexcept; +void XM_CALLCONV XMVectorGetIntXPtr(_Out_ uint32_t* x, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntYPtr(_Out_ uint32_t* y, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntZPtr(_Out_ uint32_t* z, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntWPtr(_Out_ uint32_t* w, + _In_ FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetByIndex(FXMVECTOR V, float f, size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetX(FXMVECTOR V, float x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetY(FXMVECTOR V, float y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetZ(FXMVECTOR V, float z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetW(FXMVECTOR V, float w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetByIndex(FXMVECTOR V, float f, + size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetX(FXMVECTOR V, float x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetY(FXMVECTOR V, float y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetZ(FXMVECTOR V, float z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetW(FXMVECTOR V, float w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetByIndexPtr(_In_ FXMVECTOR V, _In_ const float* f, _In_ size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetXPtr(_In_ FXMVECTOR V, _In_ const float* x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetYPtr(_In_ FXMVECTOR V, _In_ const float* y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetZPtr(_In_ FXMVECTOR V, _In_ const float* z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetWPtr(_In_ FXMVECTOR V, _In_ const float* w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetByIndexPtr(_In_ FXMVECTOR V, + _In_ const float* f, + _In_ size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetXPtr(_In_ FXMVECTOR V, + _In_ const float* x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetYPtr(_In_ FXMVECTOR V, + _In_ const float* y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetZPtr(_In_ FXMVECTOR V, + _In_ const float* z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetWPtr(_In_ FXMVECTOR V, + _In_ const float* w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntByIndex(FXMVECTOR V, uint32_t x, size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntX(FXMVECTOR V, uint32_t x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntY(FXMVECTOR V, uint32_t y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntZ(FXMVECTOR V, uint32_t z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntW(FXMVECTOR V, uint32_t w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntByIndex(FXMVECTOR V, uint32_t x, + size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntX(FXMVECTOR V, uint32_t x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntY(FXMVECTOR V, uint32_t y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntZ(FXMVECTOR V, uint32_t z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntW(FXMVECTOR V, uint32_t w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntByIndexPtr(_In_ FXMVECTOR V, _In_ const uint32_t* x, _In_ size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntXPtr(_In_ FXMVECTOR V, _In_ const uint32_t* x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntYPtr(_In_ FXMVECTOR V, _In_ const uint32_t* y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntZPtr(_In_ FXMVECTOR V, _In_ const uint32_t* z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntWPtr(_In_ FXMVECTOR V, _In_ const uint32_t* w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntByIndexPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* x, + _In_ size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntXPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntYPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntZPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntWPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* w) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorSwizzle) #undef XMVectorSwizzle #endif - XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V, uint32_t E0, uint32_t E1, uint32_t E2, uint32_t E3) noexcept; - XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2, uint32_t PermuteX, uint32_t PermuteY, uint32_t PermuteZ, uint32_t PermuteW) noexcept; - XMVECTOR XM_CALLCONV XMVectorSelectControl(uint32_t VectorIndex0, uint32_t VectorIndex1, uint32_t VectorIndex2, uint32_t VectorIndex3) noexcept; - XMVECTOR XM_CALLCONV XMVectorSelect(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Control) noexcept; - XMVECTOR XM_CALLCONV XMVectorMergeXY(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMergeZW(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V, uint32_t E0, uint32_t E1, + uint32_t E2, uint32_t E3) noexcept; +XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2, + uint32_t PermuteX, uint32_t PermuteY, + uint32_t PermuteZ, + uint32_t PermuteW) noexcept; +XMVECTOR XM_CALLCONV XMVectorSelectControl(uint32_t VectorIndex0, + uint32_t VectorIndex1, + uint32_t VectorIndex2, + uint32_t VectorIndex3) noexcept; +XMVECTOR XM_CALLCONV XMVectorSelect(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Control) noexcept; +XMVECTOR XM_CALLCONV XMVectorMergeXY(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMergeZW(FXMVECTOR V1, FXMVECTOR V2) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorShiftLeft) #undef XMVectorShiftLeft @@ -1219,791 +1384,1308 @@ namespace DirectX #undef XMVectorInsert #endif - XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS, uint32_t VSLeftRotateElements, - uint32_t Select0, uint32_t Select1, uint32_t Select2, uint32_t Select3) noexcept; - - XMVECTOR XM_CALLCONV XMVectorEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualIntR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - XMVECTOR XM_CALLCONV XMVectorNotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterOrEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorLess(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorLessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorInBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - XMVECTOR XM_CALLCONV XMVectorInBoundsR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, _In_ FXMVECTOR Bounds) noexcept; - - XMVECTOR XM_CALLCONV XMVectorIsNaN(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorIsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVectorMin(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMax(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorRound(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTruncate(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorFloor(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCeiling(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorClamp(FXMVECTOR V, FXMVECTOR Min, FXMVECTOR Max) noexcept; - XMVECTOR XM_CALLCONV XMVectorSaturate(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVectorAndInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorAndCInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorOrInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorXorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - - XMVECTOR XM_CALLCONV XMVectorNegate(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorAdd(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSum(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorAddAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSubtract(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSubtractAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMultiply(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMultiplyAdd(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVectorDivide(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNegativeMultiplySubtract(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVectorScale(FXMVECTOR V, float ScaleFactor) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSqrtEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSqrt(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalSqrtEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalSqrt(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp2(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp10(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExpE(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog2(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog10(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLogE(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorPow(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorAbs(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorMod(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorModAngles(FXMVECTOR Angles) noexcept; - XMVECTOR XM_CALLCONV XMVectorSin(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSinEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCos(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCosEst(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorSinCos(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorSinCosEst(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, _In_ FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTan(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTanEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSinH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCosH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTanH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorASin(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorASinEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorACos(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorACosEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATanEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan2(FXMVECTOR Y, FXMVECTOR X) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan2Est(FXMVECTOR Y, FXMVECTOR X) noexcept; - XMVECTOR XM_CALLCONV XMVectorLerp(FXMVECTOR V0, FXMVECTOR V1, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorLerpV(FXMVECTOR V0, FXMVECTOR V1, FXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorHermite(FXMVECTOR Position0, FXMVECTOR Tangent0, FXMVECTOR Position1, GXMVECTOR Tangent1, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorHermiteV(FXMVECTOR Position0, FXMVECTOR Tangent0, FXMVECTOR Position1, GXMVECTOR Tangent1, HXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorCatmullRom(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR Position3, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorCatmullRomV(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR Position3, HXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorBaryCentric(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, float f, float g) noexcept; - XMVECTOR XM_CALLCONV XMVectorBaryCentricV(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR F, HXMVECTOR G) noexcept; - - /**************************************************************************** - * - * 2D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector2Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector2NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector2IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector2IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector2Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector2ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector2Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector2Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector2RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector2Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2LinePointDistance(FXMVECTOR LinePoint1, FXMVECTOR LinePoint2, FXMVECTOR Point) noexcept; - XMVECTOR XM_CALLCONV XMVector2IntersectLine(FXMVECTOR Line1Point1, FXMVECTOR Line1Point2, FXMVECTOR Line2Point1, GXMVECTOR Line2Point2) noexcept; - XMVECTOR XM_CALLCONV XMVector2Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector2TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector2TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT2* XM_CALLCONV XMVector2TransformCoordStream(_Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) XMFLOAT2* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector2TransformNormal(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT2* XM_CALLCONV XMVector2TransformNormalStream(_Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) XMFLOAT2* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - - /**************************************************************************** - * - * 3D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector3Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector3NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector3IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector3IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector3Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector3ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector3Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector3Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector3RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector3Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3LinePointDistance(FXMVECTOR LinePoint1, FXMVECTOR LinePoint2, FXMVECTOR Point) noexcept; - void XM_CALLCONV XMVector3ComponentsFromNormal(_Out_ XMVECTOR* pParallel, _Out_ XMVECTOR* pPerpendicular, _In_ FXMVECTOR V, _In_ FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector3Rotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; - XMVECTOR XM_CALLCONV XMVector3InverseRotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; - XMVECTOR XM_CALLCONV XMVector3Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector3TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3TransformCoordStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3TransformNormal(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3TransformNormalStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3Project(FXMVECTOR V, float ViewportX, float ViewportY, float ViewportWidth, float ViewportHeight, float ViewportMinZ, float ViewportMaxZ, - FXMMATRIX Projection, CXMMATRIX View, CXMMATRIX World) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3ProjectStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, - _In_ float ViewportX, _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, _In_ float ViewportMinZ, _In_ float ViewportMaxZ, - _In_ FXMMATRIX Projection, _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; - XMVECTOR XM_CALLCONV XMVector3Unproject(FXMVECTOR V, float ViewportX, float ViewportY, float ViewportWidth, float ViewportHeight, float ViewportMinZ, float ViewportMaxZ, - FXMMATRIX Projection, CXMMATRIX View, CXMMATRIX World) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3UnprojectStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, - _In_ float ViewportX, _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, _In_ float ViewportMinZ, _In_ float ViewportMaxZ, - _In_ FXMMATRIX Projection, _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; - - /**************************************************************************** - * - * 4D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector4Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector4NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector4IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector4IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector4Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector4Cross(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVector4LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector4ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector4Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector4Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector4RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector4Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector4Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector4TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (VectorCount - 1)) const XMFLOAT4* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - - /**************************************************************************** - * - * Matrix operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMMatrixIsNaN(FXMMATRIX M) noexcept; - bool XM_CALLCONV XMMatrixIsInfinite(FXMMATRIX M) noexcept; - bool XM_CALLCONV XMMatrixIsIdentity(FXMMATRIX M) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixMultiply(FXMMATRIX M1, CXMMATRIX M2) noexcept; - XMMATRIX XM_CALLCONV XMMatrixMultiplyTranspose(FXMMATRIX M1, CXMMATRIX M2) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranspose(FXMMATRIX M) noexcept; - XMMATRIX XM_CALLCONV XMMatrixInverse(_Out_opt_ XMVECTOR* pDeterminant, _In_ FXMMATRIX M) noexcept; - XMMATRIX XM_CALLCONV XMMatrixVectorTensorProduct(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMMatrixDeterminant(FXMMATRIX M) noexcept; - - _Success_(return) - bool XM_CALLCONV XMMatrixDecompose(_Out_ XMVECTOR* outScale, _Out_ XMVECTOR* outRotQuat, _Out_ XMVECTOR* outTrans, _In_ FXMMATRIX M) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixIdentity() noexcept; - XMMATRIX XM_CALLCONV XMMatrixSet(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranslation(float OffsetX, float OffsetY, float OffsetZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranslationFromVector(FXMVECTOR Offset) noexcept; - XMMATRIX XM_CALLCONV XMMatrixScaling(float ScaleX, float ScaleY, float ScaleZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixScalingFromVector(FXMVECTOR Scale) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationX(float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationY(float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationZ(float Angle) noexcept; - - // Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) - XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYaw(float Pitch, float Yaw, float Roll) noexcept; - - // Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis (Angles.z) - XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixRotationNormal(FXMVECTOR NormalAxis, float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationAxis(FXMVECTOR Axis, float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationQuaternion(FXMVECTOR Quaternion) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTransformation2D(FXMVECTOR ScalingOrigin, float ScalingOrientation, FXMVECTOR Scaling, - FXMVECTOR RotationOrigin, float Rotation, GXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTransformation(FXMVECTOR ScalingOrigin, FXMVECTOR ScalingOrientationQuaternion, FXMVECTOR Scaling, - GXMVECTOR RotationOrigin, HXMVECTOR RotationQuaternion, HXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixAffineTransformation2D(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, float Rotation, FXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixAffineTransformation(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, FXMVECTOR RotationQuaternion, GXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixReflect(FXMVECTOR ReflectionPlane) noexcept; - XMMATRIX XM_CALLCONV XMMatrixShadow(FXMVECTOR ShadowPlane, FXMVECTOR LightPosition) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixLookAtLH(FXMVECTOR EyePosition, FXMVECTOR FocusPosition, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookAtRH(FXMVECTOR EyePosition, FXMVECTOR FocusPosition, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookToLH(FXMVECTOR EyePosition, FXMVECTOR EyeDirection, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookToRH(FXMVECTOR EyePosition, FXMVECTOR EyeDirection, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveLH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveRH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovLH(float FovAngleY, float AspectRatio, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovRH(float FovAngleY, float AspectRatio, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterLH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterRH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicLH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicRH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterLH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterRH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - - - /**************************************************************************** - * - * Quaternion operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMQuaternionEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - bool XM_CALLCONV XMQuaternionNotEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - - bool XM_CALLCONV XMQuaternionIsNaN(FXMVECTOR Q) noexcept; - bool XM_CALLCONV XMQuaternionIsInfinite(FXMVECTOR Q) noexcept; - bool XM_CALLCONV XMQuaternionIsIdentity(FXMVECTOR Q) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionDot(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionMultiply(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLengthSq(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionReciprocalLength(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLength(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionNormalizeEst(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionNormalize(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionConjugate(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionInverse(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLn(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionExp(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSlerp(FXMVECTOR Q0, FXMVECTOR Q1, float t) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSlerpV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSquad(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR Q3, float t) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSquadV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR Q3, HXMVECTOR T) noexcept; - void XM_CALLCONV XMQuaternionSquadSetup(_Out_ XMVECTOR* pA, _Out_ XMVECTOR* pB, _Out_ XMVECTOR* pC, _In_ FXMVECTOR Q0, _In_ FXMVECTOR Q1, _In_ FXMVECTOR Q2, _In_ GXMVECTOR Q3) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionBaryCentric(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, float f, float g) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionBaryCentricV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR F, HXMVECTOR G) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionIdentity() noexcept; - - // Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) - XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYaw(float Pitch, float Yaw, float Roll) noexcept; - - // Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis (Angles.z) - XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionRotationNormal(FXMVECTOR NormalAxis, float Angle) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionRotationAxis(FXMVECTOR Axis, float Angle) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionRotationMatrix(FXMMATRIX M) noexcept; - - void XM_CALLCONV XMQuaternionToAxisAngle(_Out_ XMVECTOR* pAxis, _Out_ float* pAngle, _In_ FXMVECTOR Q) noexcept; - - /**************************************************************************** - * - * Plane operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMPlaneEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; - bool XM_CALLCONV XMPlaneNearEqual(FXMVECTOR P1, FXMVECTOR P2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMPlaneNotEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; - - bool XM_CALLCONV XMPlaneIsNaN(FXMVECTOR P) noexcept; - bool XM_CALLCONV XMPlaneIsInfinite(FXMVECTOR P) noexcept; - - XMVECTOR XM_CALLCONV XMPlaneDot(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneDotCoord(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneDotNormal(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneNormalizeEst(FXMVECTOR P) noexcept; - XMVECTOR XM_CALLCONV XMPlaneNormalize(FXMVECTOR P) noexcept; - XMVECTOR XM_CALLCONV XMPlaneIntersectLine(FXMVECTOR P, FXMVECTOR LinePoint1, FXMVECTOR LinePoint2) noexcept; - void XM_CALLCONV XMPlaneIntersectPlane(_Out_ XMVECTOR* pLinePoint1, _Out_ XMVECTOR* pLinePoint2, _In_ FXMVECTOR P1, _In_ FXMVECTOR P2) noexcept; - - // Transforms a plane given an inverse transpose matrix - XMVECTOR XM_CALLCONV XMPlaneTransform(FXMVECTOR P, FXMMATRIX ITM) noexcept; - - // Transforms an array of planes given an inverse transpose matrix - XMFLOAT4* XM_CALLCONV XMPlaneTransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (PlaneCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (PlaneCount - 1)) const XMFLOAT4* pInputStream, - _In_ size_t InputStride, _In_ size_t PlaneCount, _In_ FXMMATRIX ITM) noexcept; - - XMVECTOR XM_CALLCONV XMPlaneFromPointNormal(FXMVECTOR Point, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMPlaneFromPoints(FXMVECTOR Point1, FXMVECTOR Point2, FXMVECTOR Point3) noexcept; - - /**************************************************************************** - * - * Color operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMColorEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorNotEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorGreater(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorGreaterOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorLess(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorLessOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - - bool XM_CALLCONV XMColorIsNaN(FXMVECTOR C) noexcept; - bool XM_CALLCONV XMColorIsInfinite(FXMVECTOR C) noexcept; - - XMVECTOR XM_CALLCONV XMColorNegative(FXMVECTOR C) noexcept; - XMVECTOR XM_CALLCONV XMColorModulate(FXMVECTOR C1, FXMVECTOR C2) noexcept; - XMVECTOR XM_CALLCONV XMColorAdjustSaturation(FXMVECTOR C, float Saturation) noexcept; - XMVECTOR XM_CALLCONV XMColorAdjustContrast(FXMVECTOR C, float Contrast) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToHSL(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorHSLToRGB(FXMVECTOR hsl) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToHSV(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorHSVToRGB(FXMVECTOR hsv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV_HD(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB_HD(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV_UHD(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB_UHD(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToXYZ(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorXYZToRGB(FXMVECTOR xyz) noexcept; - - XMVECTOR XM_CALLCONV XMColorXYZToSRGB(FXMVECTOR xyz) noexcept; - XMVECTOR XM_CALLCONV XMColorSRGBToXYZ(FXMVECTOR srgb) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToSRGB(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorSRGBToRGB(FXMVECTOR srgb) noexcept; - - - /**************************************************************************** - * - * Miscellaneous operations - * - ****************************************************************************/ - - bool XMVerifyCPUSupport() noexcept; - - XMVECTOR XM_CALLCONV XMFresnelTerm(FXMVECTOR CosIncidentAngle, FXMVECTOR RefractionIndex) noexcept; - - bool XMScalarNearEqual(float S1, float S2, float Epsilon) noexcept; - float XMScalarModAngle(float Value) noexcept; - - float XMScalarSin(float Value) noexcept; - float XMScalarSinEst(float Value) noexcept; - - float XMScalarCos(float Value) noexcept; - float XMScalarCosEst(float Value) noexcept; - - void XMScalarSinCos(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; - void XMScalarSinCosEst(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; - - float XMScalarASin(float Value) noexcept; - float XMScalarASinEst(float Value) noexcept; - - float XMScalarACos(float Value) noexcept; - float XMScalarACosEst(float Value) noexcept; - - /**************************************************************************** - * - * Templates - * - ****************************************************************************/ +XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS, + uint32_t VSLeftRotateElements, + uint32_t Select0, uint32_t Select1, + uint32_t Select2, + uint32_t Select3) noexcept; + +XMVECTOR XM_CALLCONV XMVectorEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualIntR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +XMVECTOR XM_CALLCONV XMVectorNotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterOrEqual(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterOrEqualR(_Out_ uint32_t* pCR, + _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorLess(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorLessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorInBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; +XMVECTOR XM_CALLCONV XMVectorInBoundsR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, + _In_ FXMVECTOR Bounds) noexcept; + +XMVECTOR XM_CALLCONV XMVectorIsNaN(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorIsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVectorMin(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMax(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorRound(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTruncate(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorFloor(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCeiling(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorClamp(FXMVECTOR V, FXMVECTOR Min, + FXMVECTOR Max) noexcept; +XMVECTOR XM_CALLCONV XMVectorSaturate(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVectorAndInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorAndCInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorOrInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorXorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; + +XMVECTOR XM_CALLCONV XMVectorNegate(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorAdd(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSum(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorAddAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSubtract(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSubtractAngles(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMultiply(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMultiplyAdd(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVectorDivide(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNegativeMultiplySubtract(FXMVECTOR V1, + FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVectorScale(FXMVECTOR V, float ScaleFactor) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSqrtEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSqrt(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalSqrtEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalSqrt(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp2(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp10(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExpE(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog2(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog10(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLogE(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorPow(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorAbs(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorMod(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorModAngles(FXMVECTOR Angles) noexcept; +XMVECTOR XM_CALLCONV XMVectorSin(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSinEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCos(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCosEst(FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorSinCos(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorSinCosEst(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, + _In_ FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTan(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTanEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSinH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCosH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTanH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorASin(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorASinEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorACos(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorACosEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATanEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan2(FXMVECTOR Y, FXMVECTOR X) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan2Est(FXMVECTOR Y, FXMVECTOR X) noexcept; +XMVECTOR XM_CALLCONV XMVectorLerp(FXMVECTOR V0, FXMVECTOR V1, float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorLerpV(FXMVECTOR V0, FXMVECTOR V1, + FXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorHermite(FXMVECTOR Position0, FXMVECTOR Tangent0, + FXMVECTOR Position1, GXMVECTOR Tangent1, + float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorHermiteV(FXMVECTOR Position0, FXMVECTOR Tangent0, + FXMVECTOR Position1, GXMVECTOR Tangent1, + HXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorCatmullRom(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, + GXMVECTOR Position3, float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorCatmullRomV(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, + GXMVECTOR Position3, + HXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorBaryCentric(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, float f, + float g) noexcept; +XMVECTOR XM_CALLCONV XMVectorBaryCentricV(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, GXMVECTOR F, + HXMVECTOR G) noexcept; + +/**************************************************************************** + * + * 2D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector2Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector2NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector2IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector2IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector2Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector2ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector2Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector2Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector2RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector2Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2LinePointDistance(FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2, + FXMVECTOR Point) noexcept; +XMVECTOR XM_CALLCONV XMVector2IntersectLine(FXMVECTOR Line1Point1, + FXMVECTOR Line1Point2, + FXMVECTOR Line2Point1, + GXMVECTOR Line2Point2) noexcept; +XMVECTOR XM_CALLCONV XMVector2Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector2TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector2TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT2* XM_CALLCONV XMVector2TransformCoordStream( + _Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) + XMFLOAT2* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector2TransformNormal(FXMVECTOR V, + FXMMATRIX M) noexcept; +XMFLOAT2* XM_CALLCONV XMVector2TransformNormalStream( + _Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) + XMFLOAT2* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; + +/**************************************************************************** + * + * 3D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector3Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector3NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector3IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector3IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector3Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector3ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector3Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector3Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector3RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector3Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3LinePointDistance(FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2, + FXMVECTOR Point) noexcept; +void XM_CALLCONV XMVector3ComponentsFromNormal(_Out_ XMVECTOR* pParallel, + _Out_ XMVECTOR* pPerpendicular, + _In_ FXMVECTOR V, + _In_ FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector3Rotate(FXMVECTOR V, + FXMVECTOR RotationQuaternion) noexcept; +XMVECTOR XM_CALLCONV +XMVector3InverseRotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; +XMVECTOR XM_CALLCONV XMVector3Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector3TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3TransformCoordStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3TransformNormal(FXMVECTOR V, + FXMMATRIX M) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3TransformNormalStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3Project(FXMVECTOR V, float ViewportX, + float ViewportY, float ViewportWidth, + float ViewportHeight, float ViewportMinZ, + float ViewportMaxZ, FXMMATRIX Projection, + CXMMATRIX View, CXMMATRIX World) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3ProjectStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, _In_ float ViewportX, + _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, + _In_ float ViewportMinZ, _In_ float ViewportMaxZ, _In_ FXMMATRIX Projection, + _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; +XMVECTOR XM_CALLCONV XMVector3Unproject(FXMVECTOR V, float ViewportX, + float ViewportY, float ViewportWidth, + float ViewportHeight, + float ViewportMinZ, float ViewportMaxZ, + FXMMATRIX Projection, CXMMATRIX View, + CXMMATRIX World) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3UnprojectStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, _In_ float ViewportX, + _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, + _In_ float ViewportMinZ, _In_ float ViewportMaxZ, _In_ FXMMATRIX Projection, + _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; + +/**************************************************************************** + * + * 4D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector4Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector4NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector4IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector4IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector4Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector4Cross(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVector4LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector4ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector4Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector4Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector4RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector4Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector4Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector4TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (VectorCount - 1)) + const XMFLOAT4* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; + +/**************************************************************************** + * + * Matrix operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMMatrixIsNaN(FXMMATRIX M) noexcept; +bool XM_CALLCONV XMMatrixIsInfinite(FXMMATRIX M) noexcept; +bool XM_CALLCONV XMMatrixIsIdentity(FXMMATRIX M) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixMultiply(FXMMATRIX M1, CXMMATRIX M2) noexcept; +XMMATRIX XM_CALLCONV XMMatrixMultiplyTranspose(FXMMATRIX M1, + CXMMATRIX M2) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranspose(FXMMATRIX M) noexcept; +XMMATRIX XM_CALLCONV XMMatrixInverse(_Out_opt_ XMVECTOR* pDeterminant, + _In_ FXMMATRIX M) noexcept; +XMMATRIX XM_CALLCONV XMMatrixVectorTensorProduct(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMMatrixDeterminant(FXMMATRIX M) noexcept; + +_Success_(return) bool XM_CALLCONV + XMMatrixDecompose(_Out_ XMVECTOR* outScale, _Out_ XMVECTOR* outRotQuat, + _Out_ XMVECTOR* outTrans, _In_ FXMMATRIX M) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixIdentity() noexcept; +XMMATRIX XM_CALLCONV XMMatrixSet(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, + float m33) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranslation(float OffsetX, float OffsetY, + float OffsetZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranslationFromVector(FXMVECTOR Offset) noexcept; +XMMATRIX XM_CALLCONV XMMatrixScaling(float ScaleX, float ScaleY, + float ScaleZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixScalingFromVector(FXMVECTOR Scale) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationX(float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationY(float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationZ(float Angle) noexcept; + +// Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) +XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYaw(float Pitch, float Yaw, + float Roll) noexcept; + +// Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis +// (Angles.z) +XMMATRIX XM_CALLCONV +XMMatrixRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixRotationNormal(FXMVECTOR NormalAxis, + float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationAxis(FXMVECTOR Axis, float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationQuaternion(FXMVECTOR Quaternion) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTransformation2D( + FXMVECTOR ScalingOrigin, float ScalingOrientation, FXMVECTOR Scaling, + FXMVECTOR RotationOrigin, float Rotation, GXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTransformation( + FXMVECTOR ScalingOrigin, FXMVECTOR ScalingOrientationQuaternion, + FXMVECTOR Scaling, GXMVECTOR RotationOrigin, HXMVECTOR RotationQuaternion, + HXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV +XMMatrixAffineTransformation2D(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, + float Rotation, FXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixAffineTransformation( + FXMVECTOR Scaling, FXMVECTOR RotationOrigin, FXMVECTOR RotationQuaternion, + GXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixReflect(FXMVECTOR ReflectionPlane) noexcept; +XMMATRIX XM_CALLCONV XMMatrixShadow(FXMVECTOR ShadowPlane, + FXMVECTOR LightPosition) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixLookAtLH(FXMVECTOR EyePosition, + FXMVECTOR FocusPosition, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookAtRH(FXMVECTOR EyePosition, + FXMVECTOR FocusPosition, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookToLH(FXMVECTOR EyePosition, + FXMVECTOR EyeDirection, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookToRH(FXMVECTOR EyePosition, + FXMVECTOR EyeDirection, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveLH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveRH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovLH(float FovAngleY, + float AspectRatio, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovRH(float FovAngleY, + float AspectRatio, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterLH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterRH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicLH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicRH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterLH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterRH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; + +/**************************************************************************** + * + * Quaternion operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMQuaternionEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +bool XM_CALLCONV XMQuaternionNotEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; + +bool XM_CALLCONV XMQuaternionIsNaN(FXMVECTOR Q) noexcept; +bool XM_CALLCONV XMQuaternionIsInfinite(FXMVECTOR Q) noexcept; +bool XM_CALLCONV XMQuaternionIsIdentity(FXMVECTOR Q) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionDot(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionMultiply(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLengthSq(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionReciprocalLength(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLength(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionNormalizeEst(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionNormalize(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionConjugate(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionInverse(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLn(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionExp(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSlerp(FXMVECTOR Q0, FXMVECTOR Q1, + float t) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSlerpV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSquad(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, + GXMVECTOR Q3, float t) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSquadV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, GXMVECTOR Q3, + HXMVECTOR T) noexcept; +void XM_CALLCONV XMQuaternionSquadSetup(_Out_ XMVECTOR* pA, _Out_ XMVECTOR* pB, + _Out_ XMVECTOR* pC, _In_ FXMVECTOR Q0, + _In_ FXMVECTOR Q1, _In_ FXMVECTOR Q2, + _In_ GXMVECTOR Q3) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionBaryCentric(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, float f, + float g) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionBaryCentricV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, GXMVECTOR F, + HXMVECTOR G) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionIdentity() noexcept; + +// Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) +XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYaw(float Pitch, float Yaw, + float Roll) noexcept; + +// Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis +// (Angles.z) +XMVECTOR XM_CALLCONV +XMQuaternionRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionRotationNormal(FXMVECTOR NormalAxis, + float Angle) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionRotationAxis(FXMVECTOR Axis, + float Angle) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionRotationMatrix(FXMMATRIX M) noexcept; + +void XM_CALLCONV XMQuaternionToAxisAngle(_Out_ XMVECTOR* pAxis, + _Out_ float* pAngle, + _In_ FXMVECTOR Q) noexcept; + +/**************************************************************************** + * + * Plane operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMPlaneEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; +bool XM_CALLCONV XMPlaneNearEqual(FXMVECTOR P1, FXMVECTOR P2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMPlaneNotEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; + +bool XM_CALLCONV XMPlaneIsNaN(FXMVECTOR P) noexcept; +bool XM_CALLCONV XMPlaneIsInfinite(FXMVECTOR P) noexcept; + +XMVECTOR XM_CALLCONV XMPlaneDot(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneDotCoord(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneDotNormal(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneNormalizeEst(FXMVECTOR P) noexcept; +XMVECTOR XM_CALLCONV XMPlaneNormalize(FXMVECTOR P) noexcept; +XMVECTOR XM_CALLCONV XMPlaneIntersectLine(FXMVECTOR P, FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2) noexcept; +void XM_CALLCONV XMPlaneIntersectPlane(_Out_ XMVECTOR* pLinePoint1, + _Out_ XMVECTOR* pLinePoint2, + _In_ FXMVECTOR P1, + _In_ FXMVECTOR P2) noexcept; + +// Transforms a plane given an inverse transpose matrix +XMVECTOR XM_CALLCONV XMPlaneTransform(FXMVECTOR P, FXMMATRIX ITM) noexcept; + +// Transforms an array of planes given an inverse transpose matrix +XMFLOAT4* XM_CALLCONV XMPlaneTransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (PlaneCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (PlaneCount - 1)) + const XMFLOAT4* pInputStream, + _In_ size_t InputStride, _In_ size_t PlaneCount, + _In_ FXMMATRIX ITM) noexcept; + +XMVECTOR XM_CALLCONV XMPlaneFromPointNormal(FXMVECTOR Point, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMPlaneFromPoints(FXMVECTOR Point1, FXMVECTOR Point2, + FXMVECTOR Point3) noexcept; + +/**************************************************************************** + * + * Color operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMColorEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorNotEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorGreater(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorGreaterOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorLess(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorLessOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; + +bool XM_CALLCONV XMColorIsNaN(FXMVECTOR C) noexcept; +bool XM_CALLCONV XMColorIsInfinite(FXMVECTOR C) noexcept; + +XMVECTOR XM_CALLCONV XMColorNegative(FXMVECTOR C) noexcept; +XMVECTOR XM_CALLCONV XMColorModulate(FXMVECTOR C1, FXMVECTOR C2) noexcept; +XMVECTOR XM_CALLCONV XMColorAdjustSaturation(FXMVECTOR C, + float Saturation) noexcept; +XMVECTOR XM_CALLCONV XMColorAdjustContrast(FXMVECTOR C, + float Contrast) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToHSL(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorHSLToRGB(FXMVECTOR hsl) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToHSV(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorHSVToRGB(FXMVECTOR hsv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV_HD(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB_HD(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV_UHD(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB_UHD(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToXYZ(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorXYZToRGB(FXMVECTOR xyz) noexcept; + +XMVECTOR XM_CALLCONV XMColorXYZToSRGB(FXMVECTOR xyz) noexcept; +XMVECTOR XM_CALLCONV XMColorSRGBToXYZ(FXMVECTOR srgb) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToSRGB(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorSRGBToRGB(FXMVECTOR srgb) noexcept; + +/**************************************************************************** + * + * Miscellaneous operations + * + ****************************************************************************/ + +bool XMVerifyCPUSupport() noexcept; + +XMVECTOR XM_CALLCONV XMFresnelTerm(FXMVECTOR CosIncidentAngle, + FXMVECTOR RefractionIndex) noexcept; + +bool XMScalarNearEqual(float S1, float S2, float Epsilon) noexcept; +float XMScalarModAngle(float Value) noexcept; + +float XMScalarSin(float Value) noexcept; +float XMScalarSinEst(float Value) noexcept; + +float XMScalarCos(float Value) noexcept; +float XMScalarCosEst(float Value) noexcept; + +void XMScalarSinCos(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; +void XMScalarSinCosEst(_Out_ float* pSin, _Out_ float* pCos, + float Value) noexcept; + +float XMScalarASin(float Value) noexcept; +float XMScalarASinEst(float Value) noexcept; + +float XMScalarACos(float Value) noexcept; +float XMScalarACosEst(float Value) noexcept; + +/**************************************************************************** + * + * Templates + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XMMin) #undef XMMin #undef XMMax #endif - template inline T XMMin(T a, T b) noexcept { return (a < b) ? a : b; } - template inline T XMMax(T a, T b) noexcept { return (a > b) ? a : b; } +template +inline T XMMin(T a, T b) noexcept { + return (a < b) ? a : b; +} +template +inline T XMMax(T a, T b) noexcept { + return (a > b) ? a : b; +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) // PermuteHelper internal template (SSE only) - namespace MathInternal - { - // Slow path fallback for permutes that do not map to a single SSE shuffle opcode. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept - { - static const XMVECTORU32 selectMask = - { { { - WhichX ? 0xFFFFFFFF : 0, - WhichY ? 0xFFFFFFFF : 0, - WhichZ ? 0xFFFFFFFF : 0, - WhichW ? 0xFFFFFFFF : 0, - } } }; +namespace MathInternal { +// Slow path fallback for permutes that do not map to a single SSE shuffle +// opcode. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + static const XMVECTORU32 selectMask = {{{ + WhichX ? 0xFFFFFFFF : 0, + WhichY ? 0xFFFFFFFF : 0, + WhichZ ? 0xFFFFFFFF : 0, + WhichW ? 0xFFFFFFFF : 0, + }}}; - XMVECTOR shuffled1 = XM_PERMUTE_PS(v1, Shuffle); - XMVECTOR shuffled2 = XM_PERMUTE_PS(v2, Shuffle); + XMVECTOR shuffled1 = XM_PERMUTE_PS(v1, Shuffle); + XMVECTOR shuffled2 = XM_PERMUTE_PS(v2, Shuffle); - XMVECTOR masked1 = _mm_andnot_ps(selectMask, shuffled1); - XMVECTOR masked2 = _mm_and_ps(selectMask, shuffled2); + XMVECTOR masked1 = _mm_andnot_ps(selectMask, shuffled1); + XMVECTOR masked2 = _mm_and_ps(selectMask, shuffled2); - return _mm_or_ps(masked1, masked2); - } - }; - - // Fast path for permutes that only read from the first vector. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR) noexcept { return XM_PERMUTE_PS(v1, Shuffle); } - }; - - // Fast path for permutes that only read from the second vector. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR, FXMVECTOR v2) noexcept { return XM_PERMUTE_PS(v2, Shuffle); } - }; - - // Fast path for permutes that read XY from the first vector, ZW from the second. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { return _mm_shuffle_ps(v1, v2, Shuffle); } - }; - - // Fast path for permutes that read XY from the second vector, ZW from the first. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { return _mm_shuffle_ps(v2, v1, Shuffle); } - }; + return _mm_or_ps(masked1, masked2); } +}; -#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ - - // General permute template - template - inline XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2) noexcept - { - static_assert(PermuteX <= 7, "PermuteX template parameter out of range"); - static_assert(PermuteY <= 7, "PermuteY template parameter out of range"); - static_assert(PermuteZ <= 7, "PermuteZ template parameter out of range"); - static_assert(PermuteW <= 7, "PermuteW template parameter out of range"); - - #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - constexpr uint32_t Shuffle = _MM_SHUFFLE(PermuteW & 3, PermuteZ & 3, PermuteY & 3, PermuteX & 3); - - constexpr bool WhichX = PermuteX > 3; - constexpr bool WhichY = PermuteY > 3; - constexpr bool WhichZ = PermuteZ > 3; - constexpr bool WhichW = PermuteW > 3; - - return MathInternal::PermuteHelper::Permute(V1, V2); - #else - - return XMVectorPermute(V1, V2, PermuteX, PermuteY, PermuteZ, PermuteW); - - #endif +// Fast path for permutes that only read from the first vector. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR) noexcept { + return XM_PERMUTE_PS(v1, Shuffle); } +}; - // Special-case permute templates - template<> constexpr XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 3>(FXMVECTOR V1, FXMVECTOR) noexcept { return V1; } - template<> constexpr XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 7>(FXMVECTOR, FXMVECTOR V2) noexcept { return V2; } +// Fast path for permutes that only read from the second vector. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR, FXMVECTOR v2) noexcept { + return XM_PERMUTE_PS(v2, Shuffle); + } +}; + +// Fast path for permutes that read XY from the first vector, ZW from the +// second. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + return _mm_shuffle_ps(v1, v2, Shuffle); + } +}; + +// Fast path for permutes that read XY from the second vector, ZW from the +// first. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + return _mm_shuffle_ps(v2, v1, Shuffle); + } +}; +} // namespace MathInternal + +#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ + +// General permute template +template +inline XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + static_assert(PermuteX <= 7, "PermuteX template parameter out of range"); + static_assert(PermuteY <= 7, "PermuteY template parameter out of range"); + static_assert(PermuteZ <= 7, "PermuteZ template parameter out of range"); + static_assert(PermuteW <= 7, "PermuteW template parameter out of range"); #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_movelh_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<6, 7, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_movehl_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_unpacklo_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_unpackhi_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_castpd_ps(_mm_unpackhi_pd(_mm_castps_pd(V1), _mm_castps_pd(V2))); } + constexpr uint32_t Shuffle = + _MM_SHUFFLE(PermuteW & 3, PermuteZ & 3, PermuteY & 3, PermuteX & 3); + + constexpr bool WhichX = PermuteX > 3; + constexpr bool WhichY = PermuteY > 3; + constexpr bool WhichZ = PermuteZ > 3; + constexpr bool WhichW = PermuteW > 3; + + return MathInternal::PermuteHelper::Permute(V1, V2); +#else + + return XMVectorPermute(V1, V2, PermuteX, PermuteY, PermuteZ, PermuteW); + +#endif +} + +// Special-case permute templates +template <> +constexpr XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 3>(FXMVECTOR V1, + FXMVECTOR) noexcept { + return V1; +} +template <> +constexpr XMVECTOR XM_CALLCONV +XMVectorPermute<4, 5, 6, 7>(FXMVECTOR, FXMVECTOR V2) noexcept { + return V2; +} + +#if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_movelh_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<6, 7, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_movehl_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_unpacklo_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_unpackhi_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_castpd_ps(_mm_unpackhi_pd(_mm_castps_pd(V1), _mm_castps_pd(V2))); +} #endif #if defined(_XM_SSE4_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x3); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x4); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x5); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x6); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x7); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x8); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x9); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xA); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xB); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xC); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xD); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xE); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x3); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x4); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x5); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x6); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x7); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x8); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x9); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xA); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xB); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xC); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xD); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xE); +} #endif #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - // If the indices are all in the range 0-3 or 4-7, then use XMVectorSwizzle instead - // The mirror cases are not spelled out here as the programmer can always swap the arguments - // (i.e. prefer permutes where the X element comes from the V1 vector instead of the V2 vector) +// If the indices are all in the range 0-3 or 4-7, then use XMVectorSwizzle +// instead The mirror cases are not spelled out here as the programmer can +// always swap the arguments (i.e. prefer permutes where the X element comes +// from the V1 vector instead of the V2 vector) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_low_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vrev64_f32(vget_low_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_low_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), + vrev64_f32(vget_low_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_high_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vrev64_f32(vget_high_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_high_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), + vrev64_f32(vget_high_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_high_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vrev64_f32(vget_high_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_high_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), + vrev64_f32(vget_high_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_low_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vrev64_f32(vget_low_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_low_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), + vrev64_f32(vget_low_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 2, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vtrnq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 5, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vtrnq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 2, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vtrnq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 5, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vtrnq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vzipq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vzipq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vzipq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vzipq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 2, 4, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vuzpq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 3, 5, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vuzpq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 2, 4, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vuzpq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 3, 5, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vuzpq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 2, 3, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 4, 5, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 3); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 2, 3, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 4, 5, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 3); +} -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - // General swizzle template - template - inline XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V) noexcept - { - static_assert(SwizzleX <= 3, "SwizzleX template parameter out of range"); - static_assert(SwizzleY <= 3, "SwizzleY template parameter out of range"); - static_assert(SwizzleZ <= 3, "SwizzleZ template parameter out of range"); - static_assert(SwizzleW <= 3, "SwizzleW template parameter out of range"); - - #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - return XM_PERMUTE_PS(V, _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX)); - #else - - return XMVectorSwizzle(V, SwizzleX, SwizzleY, SwizzleZ, SwizzleW); - - #endif - } - - // Specialized swizzles - template<> constexpr XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 2, 3>(FXMVECTOR V) noexcept { return V; } +// General swizzle template +template +inline XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V) noexcept { + static_assert(SwizzleX <= 3, "SwizzleX template parameter out of range"); + static_assert(SwizzleY <= 3, "SwizzleY template parameter out of range"); + static_assert(SwizzleZ <= 3, "SwizzleZ template parameter out of range"); + static_assert(SwizzleW <= 3, "SwizzleW template parameter out of range"); #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { return _mm_movelh_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { return _mm_movehl_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { return _mm_unpacklo_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { return _mm_unpackhi_ps(V, V); } + return XM_PERMUTE_PS(V, + _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX)); +#else + + return XMVectorSwizzle(V, SwizzleX, SwizzleY, SwizzleZ, SwizzleW); + +#endif +} + +// Specialized swizzles +template <> +constexpr XMVECTOR XM_CALLCONV +XMVectorSwizzle<0, 1, 2, 3>(FXMVECTOR V) noexcept { + return V; +} + +#if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { + return _mm_movelh_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { + return _mm_movehl_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { + return _mm_unpacklo_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { + return _mm_unpackhi_ps(V, V); +} #endif #if defined(_XM_SSE3_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { return _mm_moveldup_ps(V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { return _mm_movehdup_ps(V); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { + return _mm_moveldup_ps(V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { + return _mm_movehdup_ps(V); +} #endif -#if defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) && defined(_XM_FAVOR_INTEL_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { return _mm_broadcastss_ps(V); } +#if defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) && \ + defined(_XM_FAVOR_INTEL_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { + return _mm_broadcastss_ps(V); +} #endif #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_low_f32(V), 0); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 1, 1>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_low_f32(V), 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 2, 2>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_high_f32(V), 0); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 3, 3, 3>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_high_f32(V), 1); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_low_f32(V), 0); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 1, 1>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_low_f32(V), 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 2, 2>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_high_f32(V), 0); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 3, 3, 3>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_high_f32(V), 1); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 3, 2>(FXMVECTOR V) noexcept { return vrev64q_f32(V); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 3, 2>(FXMVECTOR V) noexcept { + return vrev64q_f32(V); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { float32x2_t vt = vget_low_f32(V); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { float32x2_t vt = vget_high_f32(V); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 1, 0>(FXMVECTOR V) noexcept { float32x2_t vt = vrev64_f32(vget_low_f32(V)); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 3, 2>(FXMVECTOR V) noexcept { float32x2_t vt = vrev64_f32(vget_high_f32(V)); return vcombine_f32(vt, vt); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { + float32x2_t vt = vget_low_f32(V); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { + float32x2_t vt = vget_high_f32(V); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 1, 0>(FXMVECTOR V) noexcept { + float32x2_t vt = vrev64_f32(vget_low_f32(V)); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 3, 2>(FXMVECTOR V) noexcept { + float32x2_t vt = vrev64_f32(vget_high_f32(V)); + return vcombine_f32(vt, vt); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 3, 2>(FXMVECTOR V) noexcept { return vcombine_f32(vget_low_f32(V), vrev64_f32(vget_high_f32(V))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 2, 3>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V)), vget_high_f32(V)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 1, 0>(FXMVECTOR V) noexcept { return vcombine_f32(vget_high_f32(V), vrev64_f32(vget_low_f32(V))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 0, 1>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V)), vget_low_f32(V)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 1, 0>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V)), vrev64_f32(vget_low_f32(V))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 3, 2>(FXMVECTOR V) noexcept { + return vcombine_f32(vget_low_f32(V), vrev64_f32(vget_high_f32(V))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 2, 3>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V)), vget_high_f32(V)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 1, 0>(FXMVECTOR V) noexcept { + return vcombine_f32(vget_high_f32(V), vrev64_f32(vget_low_f32(V))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 0, 1>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V)), vget_low_f32(V)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 1, 0>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V)), + vrev64_f32(vget_low_f32(V))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { return vtrnq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { return vtrnq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { + return vtrnq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { + return vtrnq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { return vzipq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { return vzipq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { + return vzipq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { + return vzipq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 2, 0, 2>(FXMVECTOR V) noexcept { return vuzpq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 3, 1, 3>(FXMVECTOR V) noexcept { return vuzpq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 2, 0, 2>(FXMVECTOR V) noexcept { + return vuzpq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 3, 1, 3>(FXMVECTOR V) noexcept { + return vuzpq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 2, 3, 0>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 0, 1>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 0, 1, 2>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 3); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 2, 3, 0>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 0, 1>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 0, 1, 2>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 3); +} -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - template - inline XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorPermute(V1, V2); - } +template +inline XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorPermute(V1, V2); +} - template - inline XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorSwizzle(V); - } +template +inline XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorSwizzle(V); +} - template - inline XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorSwizzle<(4 - Elements) & 3, (5 - Elements) & 3, (6 - Elements) & 3, (7 - Elements) & 3>(V); - } +template +inline XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorSwizzle<(4 - Elements) & 3, (5 - Elements) & 3, + (6 - Elements) & 3, (7 - Elements) & 3>(V); +} - template - inline XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS) noexcept - { - XMVECTOR Control = XMVectorSelectControl(Select0 & 1, Select1 & 1, Select2 & 1, Select3 & 1); - return XMVectorSelect(VD, XMVectorRotateLeft(VS), Control); - } +template +inline XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, + FXMVECTOR VS) noexcept { + XMVECTOR Control = XMVectorSelectControl(Select0 & 1, Select1 & 1, + Select2 & 1, Select3 & 1); + return XMVectorSelect(VD, XMVectorRotateLeft(VS), + Control); +} - /**************************************************************************** - * - * Globals - * - ****************************************************************************/ +/**************************************************************************** + * + * Globals + * + ****************************************************************************/ - // The purpose of the following global constants is to prevent redundant - // reloading of the constants when they are referenced by more than one - // separate inline math routine called within the same function. Declaring - // a constant locally within a routine is sufficient to prevent redundant - // reloads of that constant when that single routine is called multiple - // times in a function, but if the constant is used (and declared) in a - // separate math routine it would be reloaded. +// The purpose of the following global constants is to prevent redundant +// reloading of the constants when they are referenced by more than one +// separate inline math routine called within the same function. Declaring +// a constant locally within a routine is sufficient to prevent redundant +// reloads of that constant when that single routine is called multiple +// times in a function, but if the constant is used (and declared) in a +// separate math routine it would be reloaded. #ifndef XMGLOBALCONST #if defined(__GNUC__) && !defined(__MINGW32__) @@ -2013,162 +2695,274 @@ namespace DirectX #endif #endif - XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients0 = { { { -0.16666667f, +0.0083333310f, -0.00019840874f, +2.7525562e-06f } } }; - XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients1 = { { { -2.3889859e-08f, -0.16665852f /*Est1*/, +0.0083139502f /*Est2*/, -0.00018524670f /*Est3*/ } } }; - XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients0 = { { { -0.5f, +0.041666638f, -0.0013888378f, +2.4760495e-05f } } }; - XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients1 = { { { -2.6051615e-07f, -0.49992746f /*Est1*/, +0.041493919f /*Est2*/, -0.0012712436f /*Est3*/ } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients0 = { { { 1.0f, 0.333333333f, 0.133333333f, 5.396825397e-2f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients1 = { { { 2.186948854e-2f, 8.863235530e-3f, 3.592128167e-3f, 1.455834485e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients2 = { { { 5.900274264e-4f, 2.391290764e-4f, 9.691537707e-5f, 3.927832950e-5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients0 = { { { +1.5707963050f, -0.2145988016f, +0.0889789874f, -0.0501743046f } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients1 = { { { +0.0308918810f, -0.0170881256f, +0.0066700901f, -0.0012624911f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients0 = { { { -0.3333314528f, +0.1999355085f, -0.1420889944f, +0.1065626393f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients1 = { { { -0.0752896400f, +0.0429096138f, -0.0161657367f, +0.0028662257f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients0 = { { { +0.999866f, +0.999866f, +0.999866f, +0.999866f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients1 = { { { -0.3302995f, +0.180141f, -0.085133f, +0.0208351f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanEstCoefficients = { { { 2.484f, -1.954923183e-1f, 2.467401101f, XM_1DIVPI } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcEstCoefficients = { { { +1.5707288f, -0.2121144f, +0.0742610f, -0.0187293f } } }; - XMGLOBALCONST XMVECTORF32 g_XMPiConstants0 = { { { XM_PI, XM_2PI, XM_1DIVPI, XM_1DIV2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR0 = { { { 1.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR1 = { { { 0.0f, 1.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR2 = { { { 0.0f, 0.0f, 1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR3 = { { { 0.0f, 0.0f, 0.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR0 = { { { -1.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR1 = { { { 0.0f, -1.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR2 = { { { 0.0f, 0.0f, -1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR3 = { { { 0.0f, 0.0f, 0.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegativeZero = { { { 0x80000000, 0x80000000, 0x80000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegate3 = { { { 0x80000000, 0x80000000, 0x80000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskXY = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMask3 = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX = { { { 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskY = { { { 0x00000000, 0xFFFFFFFF, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskZ = { { { 0x00000000, 0x00000000, 0xFFFFFFFF, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskW = { { { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF } } }; - XMGLOBALCONST XMVECTORF32 g_XMOne = { { { 1.0f, 1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMOne3 = { { { 1.0f, 1.0f, 1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMZero = { { { 0.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTwo = { { { 2.f, 2.f, 2.f, 2.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMFour = { { { 4.f, 4.f, 4.f, 4.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMSix = { { { 6.f, 6.f, 6.f, 6.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeOne = { { { -1.0f, -1.0f, -1.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMOneHalf = { { { 0.5f, 0.5f, 0.5f, 0.5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeOneHalf = { { { -0.5f, -0.5f, -0.5f, -0.5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeTwoPi = { { { -XM_2PI, -XM_2PI, -XM_2PI, -XM_2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativePi = { { { -XM_PI, -XM_PI, -XM_PI, -XM_PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMHalfPi = { { { XM_PIDIV2, XM_PIDIV2, XM_PIDIV2, XM_PIDIV2 } } }; - XMGLOBALCONST XMVECTORF32 g_XMPi = { { { XM_PI, XM_PI, XM_PI, XM_PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMReciprocalPi = { { { XM_1DIVPI, XM_1DIVPI, XM_1DIVPI, XM_1DIVPI } } }; - XMGLOBALCONST XMVECTORF32 g_XMTwoPi = { { { XM_2PI, XM_2PI, XM_2PI, XM_2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMReciprocalTwoPi = { { { XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMEpsilon = { { { 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f } } }; - XMGLOBALCONST XMVECTORI32 g_XMInfinity = { { { 0x7F800000, 0x7F800000, 0x7F800000, 0x7F800000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMQNaN = { { { 0x7FC00000, 0x7FC00000, 0x7FC00000, 0x7FC00000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMQNaNTest = { { { 0x007FFFFF, 0x007FFFFF, 0x007FFFFF, 0x007FFFFF } } }; - XMGLOBALCONST XMVECTORI32 g_XMAbsMask = { { { 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF } } }; - XMGLOBALCONST XMVECTORI32 g_XMFltMin = { { { 0x00800000, 0x00800000, 0x00800000, 0x00800000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFltMax = { { { 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegOneMask = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskA8R8G8B8 = { { { 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipA8R8G8B8 = { { { 0x00000000, 0x00000000, 0x00000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixAA8R8G8B8 = { { { 0.0f, 0.0f, 0.0f, float(0x80000000U) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeA8R8G8B8 = { { { 1.0f / (255.0f * float(0x10000)), 1.0f / (255.0f * float(0x100)), 1.0f / 255.0f, 1.0f / (255.0f * float(0x1000000)) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskA2B10G10R10 = { { { 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipA2B10G10R10 = { { { 0x00000200, 0x00080000, 0x20000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixAA2B10G10R10 = { { { -512.0f, -512.0f * float(0x400), -512.0f * float(0x100000), float(0x80000000U) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeA2B10G10R10 = { { { 1.0f / 511.0f, 1.0f / (511.0f * float(0x400)), 1.0f / (511.0f * float(0x100000)), 1.0f / (3.0f * float(0x40000000)) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16 = { { { 0x0000FFFF, 0xFFFF0000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16 = { { { 0x00008000, 0x00000000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16 = { { { -32768.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16 = { { { 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16Z16W16 = { { { 0x0000FFFF, 0x0000FFFF, 0xFFFF0000, 0xFFFF0000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16Z16W16 = { { { 0x00008000, 0x00008000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16Z16W16 = { { { -32768.0f, -32768.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16Z16W16 = { { { 1.0f / 32767.0f, 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 1.0f / (32767.0f * 65536.0f) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNoFraction = { { { 8388608.0f, 8388608.0f, 8388608.0f, 8388608.0f } } }; - XMGLOBALCONST XMVECTORI32 g_XMMaskByte = { { { 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateX = { { { -1.0f, 1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateY = { { { 1.0f, -1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateZ = { { { 1.0f, 1.0f, -1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateW = { { { 1.0f, 1.0f, 1.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect0101 = { { { XM_SELECT_0, XM_SELECT_1, XM_SELECT_0, XM_SELECT_1 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1010 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORI32 g_XMOneHalfMinusEpsilon = { { { 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1000 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_0, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1100 = { { { XM_SELECT_1, XM_SELECT_1, XM_SELECT_0, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1110 = { { { XM_SELECT_1, XM_SELECT_1, XM_SELECT_1, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1011 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_1 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixupY16 = { { { 1.0f, 1.0f / 65536.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixupY16W16 = { { { 1.0f, 1.0f, 1.0f / 65536.0f, 1.0f / 65536.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipY = { { { 0, 0x80000000, 0, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipZ = { { { 0, 0, 0x80000000, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipW = { { { 0, 0, 0, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipYZ = { { { 0, 0x80000000, 0x80000000, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipZW = { { { 0, 0, 0x80000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipYW = { { { 0, 0x80000000, 0, 0x80000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMMaskDec4 = { { { 0x3FF, 0x3FF << 10, 0x3FF << 20, static_cast(0xC0000000) } } }; - XMGLOBALCONST XMVECTORI32 g_XMXorDec4 = { { { 0x200, 0x200 << 10, 0x200 << 20, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddUDec4 = { { { 0, 0, 0, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddDec4 = { { { -512.0f, -512.0f * 1024.0f, -512.0f * 1024.0f * 1024.0f, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMMulDec4 = { { { 1.0f, 1.0f / 1024.0f, 1.0f / (1024.0f * 1024.0f), 1.0f / (1024.0f * 1024.0f * 1024.0f) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskByte4 = { { { 0xFF, 0xFF00, 0xFF0000, 0xFF000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMXorByte4 = { { { 0x80, 0x8000, 0x800000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddByte4 = { { { -128.0f, -128.0f * 256.0f, -128.0f * 65536.0f, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixUnsigned = { { { 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMMaxInt = { { { 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMMaxUInt = { { { 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMUnsignedFix = { { { 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbScale = { { { 12.92f, 12.92f, 12.92f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbA = { { { 0.055f, 0.055f, 0.055f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbA1 = { { { 1.055f, 1.055f, 1.055f, 1.0f } } }; - XMGLOBALCONST XMVECTORI32 g_XMExponentBias = { { { 127, 127, 127, 127 } } }; - XMGLOBALCONST XMVECTORI32 g_XMSubnormalExponent = { { { -126, -126, -126, -126 } } }; - XMGLOBALCONST XMVECTORI32 g_XMNumTrailing = { { { 23, 23, 23, 23 } } }; - XMGLOBALCONST XMVECTORI32 g_XMMinNormal = { { { 0x00800000, 0x00800000, 0x00800000, 0x00800000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegInfinity = { { { 0xFF800000, 0xFF800000, 0xFF800000, 0xFF800000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegQNaN = { { { 0xFFC00000, 0xFFC00000, 0xFFC00000, 0xFFC00000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMBin128 = { { { 0x43000000, 0x43000000, 0x43000000, 0x43000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMBinNeg150 = { { { 0xC3160000, 0xC3160000, 0xC3160000, 0xC3160000 } } }; - XMGLOBALCONST XMVECTORI32 g_XM253 = { { { 253, 253, 253, 253 } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst1 = { { { -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst2 = { { { +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst3 = { { { -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst4 = { { { +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst5 = { { { -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst6 = { { { +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst7 = { { { -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst0 = { { { +1.442693f, +1.442693f, +1.442693f, +1.442693f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst1 = { { { -0.721242f, -0.721242f, -0.721242f, -0.721242f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst2 = { { { +0.479384f, +0.479384f, +0.479384f, +0.479384f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst3 = { { { -0.350295f, -0.350295f, -0.350295f, -0.350295f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst4 = { { { +0.248590f, +0.248590f, +0.248590f, +0.248590f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst5 = { { { -0.145700f, -0.145700f, -0.145700f, -0.145700f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst6 = { { { +0.057148f, +0.057148f, +0.057148f, +0.057148f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst7 = { { { -0.010578f, -0.010578f, -0.010578f, -0.010578f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLgE = { { { +1.442695f, +1.442695f, +1.442695f, +1.442695f } } }; - XMGLOBALCONST XMVECTORF32 g_XMInvLgE = { { { +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLg10 = { { { +3.321928f, +3.321928f, +3.321928f, +3.321928f } } }; - XMGLOBALCONST XMVECTORF32 g_XMInvLg10 = { { { +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_UByteMax = { { { 255.0f, 255.0f, 255.0f, 255.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ByteMin = { { { -127.0f, -127.0f, -127.0f, -127.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ByteMax = { { { 127.0f, 127.0f, 127.0f, 127.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ShortMin = { { { -32767.0f, -32767.0f, -32767.0f, -32767.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ShortMax = { { { 32767.0f, 32767.0f, 32767.0f, 32767.0f } } }; - XMGLOBALCONST XMVECTORF32 g_UShortMax = { { { 65535.0f, 65535.0f, 65535.0f, 65535.0f } } }; +XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients0 = { + {{-0.16666667f, +0.0083333310f, -0.00019840874f, +2.7525562e-06f}}}; +XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients1 = { + {{-2.3889859e-08f, -0.16665852f /*Est1*/, +0.0083139502f /*Est2*/, + -0.00018524670f /*Est3*/}}}; +XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients0 = { + {{-0.5f, +0.041666638f, -0.0013888378f, +2.4760495e-05f}}}; +XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients1 = { + {{-2.6051615e-07f, -0.49992746f /*Est1*/, +0.041493919f /*Est2*/, + -0.0012712436f /*Est3*/}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients0 = { + {{1.0f, 0.333333333f, 0.133333333f, 5.396825397e-2f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients1 = { + {{2.186948854e-2f, 8.863235530e-3f, 3.592128167e-3f, 1.455834485e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients2 = { + {{5.900274264e-4f, 2.391290764e-4f, 9.691537707e-5f, 3.927832950e-5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients0 = { + {{+1.5707963050f, -0.2145988016f, +0.0889789874f, -0.0501743046f}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients1 = { + {{+0.0308918810f, -0.0170881256f, +0.0066700901f, -0.0012624911f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients0 = { + {{-0.3333314528f, +0.1999355085f, -0.1420889944f, +0.1065626393f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients1 = { + {{-0.0752896400f, +0.0429096138f, -0.0161657367f, +0.0028662257f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients0 = { + {{+0.999866f, +0.999866f, +0.999866f, +0.999866f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients1 = { + {{-0.3302995f, +0.180141f, -0.085133f, +0.0208351f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanEstCoefficients = { + {{2.484f, -1.954923183e-1f, 2.467401101f, XM_1DIVPI}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcEstCoefficients = { + {{+1.5707288f, -0.2121144f, +0.0742610f, -0.0187293f}}}; +XMGLOBALCONST XMVECTORF32 g_XMPiConstants0 = { + {{XM_PI, XM_2PI, XM_1DIVPI, XM_1DIV2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR0 = {{{1.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR1 = {{{0.0f, 1.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR2 = {{{0.0f, 0.0f, 1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR3 = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR0 = {{{-1.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR1 = {{{0.0f, -1.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR2 = {{{0.0f, 0.0f, -1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR3 = {{{0.0f, 0.0f, 0.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegativeZero = { + {{0x80000000, 0x80000000, 0x80000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegate3 = { + {{0x80000000, 0x80000000, 0x80000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskXY = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMask3 = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX = { + {{0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskY = { + {{0x00000000, 0xFFFFFFFF, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskZ = { + {{0x00000000, 0x00000000, 0xFFFFFFFF, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskW = { + {{0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF}}}; +XMGLOBALCONST XMVECTORF32 g_XMOne = {{{1.0f, 1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMOne3 = {{{1.0f, 1.0f, 1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMZero = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTwo = {{{2.f, 2.f, 2.f, 2.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMFour = {{{4.f, 4.f, 4.f, 4.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMSix = {{{6.f, 6.f, 6.f, 6.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeOne = {{{-1.0f, -1.0f, -1.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMOneHalf = {{{0.5f, 0.5f, 0.5f, 0.5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeOneHalf = { + {{-0.5f, -0.5f, -0.5f, -0.5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeTwoPi = { + {{-XM_2PI, -XM_2PI, -XM_2PI, -XM_2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativePi = {{{-XM_PI, -XM_PI, -XM_PI, -XM_PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMHalfPi = { + {{XM_PIDIV2, XM_PIDIV2, XM_PIDIV2, XM_PIDIV2}}}; +XMGLOBALCONST XMVECTORF32 g_XMPi = {{{XM_PI, XM_PI, XM_PI, XM_PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMReciprocalPi = { + {{XM_1DIVPI, XM_1DIVPI, XM_1DIVPI, XM_1DIVPI}}}; +XMGLOBALCONST XMVECTORF32 g_XMTwoPi = {{{XM_2PI, XM_2PI, XM_2PI, XM_2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMReciprocalTwoPi = { + {{XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMEpsilon = { + {{1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f}}}; +XMGLOBALCONST XMVECTORI32 g_XMInfinity = { + {{0x7F800000, 0x7F800000, 0x7F800000, 0x7F800000}}}; +XMGLOBALCONST XMVECTORI32 g_XMQNaN = { + {{0x7FC00000, 0x7FC00000, 0x7FC00000, 0x7FC00000}}}; +XMGLOBALCONST XMVECTORI32 g_XMQNaNTest = { + {{0x007FFFFF, 0x007FFFFF, 0x007FFFFF, 0x007FFFFF}}}; +XMGLOBALCONST XMVECTORI32 g_XMAbsMask = { + {{0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF}}}; +XMGLOBALCONST XMVECTORI32 g_XMFltMin = { + {{0x00800000, 0x00800000, 0x00800000, 0x00800000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFltMax = { + {{0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegOneMask = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskA8R8G8B8 = { + {{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipA8R8G8B8 = { + {{0x00000000, 0x00000000, 0x00000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixAA8R8G8B8 = { + {{0.0f, 0.0f, 0.0f, float(0x80000000U)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeA8R8G8B8 = { + {{1.0f / (255.0f * float(0x10000)), 1.0f / (255.0f * float(0x100)), + 1.0f / 255.0f, 1.0f / (255.0f * float(0x1000000))}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskA2B10G10R10 = { + {{0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipA2B10G10R10 = { + {{0x00000200, 0x00080000, 0x20000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixAA2B10G10R10 = { + {{-512.0f, -512.0f * float(0x400), -512.0f * float(0x100000), + float(0x80000000U)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeA2B10G10R10 = { + {{1.0f / 511.0f, 1.0f / (511.0f * float(0x400)), + 1.0f / (511.0f * float(0x100000)), 1.0f / (3.0f * float(0x40000000))}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16 = { + {{0x0000FFFF, 0xFFFF0000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16 = { + {{0x00008000, 0x00000000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16 = {{{-32768.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16 = { + {{1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16Z16W16 = { + {{0x0000FFFF, 0x0000FFFF, 0xFFFF0000, 0xFFFF0000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16Z16W16 = { + {{0x00008000, 0x00008000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16Z16W16 = { + {{-32768.0f, -32768.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16Z16W16 = { + {{1.0f / 32767.0f, 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), + 1.0f / (32767.0f * 65536.0f)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNoFraction = { + {{8388608.0f, 8388608.0f, 8388608.0f, 8388608.0f}}}; +XMGLOBALCONST XMVECTORI32 g_XMMaskByte = { + {{0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateX = {{{-1.0f, 1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateY = {{{1.0f, -1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateZ = {{{1.0f, 1.0f, -1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateW = {{{1.0f, 1.0f, 1.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect0101 = { + {{XM_SELECT_0, XM_SELECT_1, XM_SELECT_0, XM_SELECT_1}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1010 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORI32 g_XMOneHalfMinusEpsilon = { + {{0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1000 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_0, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1100 = { + {{XM_SELECT_1, XM_SELECT_1, XM_SELECT_0, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1110 = { + {{XM_SELECT_1, XM_SELECT_1, XM_SELECT_1, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1011 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_1}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixupY16 = { + {{1.0f, 1.0f / 65536.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixupY16W16 = { + {{1.0f, 1.0f, 1.0f / 65536.0f, 1.0f / 65536.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipY = {{{0, 0x80000000, 0, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipZ = {{{0, 0, 0x80000000, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipW = {{{0, 0, 0, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipYZ = {{{0, 0x80000000, 0x80000000, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipZW = {{{0, 0, 0x80000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipYW = {{{0, 0x80000000, 0, 0x80000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMMaskDec4 = { + {{0x3FF, 0x3FF << 10, 0x3FF << 20, static_cast(0xC0000000)}}}; +XMGLOBALCONST XMVECTORI32 g_XMXorDec4 = { + {{0x200, 0x200 << 10, 0x200 << 20, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddUDec4 = {{{0, 0, 0, 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddDec4 = { + {{-512.0f, -512.0f * 1024.0f, -512.0f * 1024.0f * 1024.0f, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMMulDec4 = { + {{1.0f, 1.0f / 1024.0f, 1.0f / (1024.0f * 1024.0f), + 1.0f / (1024.0f * 1024.0f * 1024.0f)}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskByte4 = { + {{0xFF, 0xFF00, 0xFF0000, 0xFF000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMXorByte4 = { + {{0x80, 0x8000, 0x800000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddByte4 = { + {{-128.0f, -128.0f * 256.0f, -128.0f * 65536.0f, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixUnsigned = { + {{32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, + 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMMaxInt = { + {{65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, + 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMMaxUInt = { + {{65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, + 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMUnsignedFix = { + {{32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, + 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbScale = {{{12.92f, 12.92f, 12.92f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbA = {{{0.055f, 0.055f, 0.055f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbA1 = {{{1.055f, 1.055f, 1.055f, 1.0f}}}; +XMGLOBALCONST XMVECTORI32 g_XMExponentBias = {{{127, 127, 127, 127}}}; +XMGLOBALCONST XMVECTORI32 g_XMSubnormalExponent = {{{-126, -126, -126, -126}}}; +XMGLOBALCONST XMVECTORI32 g_XMNumTrailing = {{{23, 23, 23, 23}}}; +XMGLOBALCONST XMVECTORI32 g_XMMinNormal = { + {{0x00800000, 0x00800000, 0x00800000, 0x00800000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegInfinity = { + {{0xFF800000, 0xFF800000, 0xFF800000, 0xFF800000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegQNaN = { + {{0xFFC00000, 0xFFC00000, 0xFFC00000, 0xFFC00000}}}; +XMGLOBALCONST XMVECTORI32 g_XMBin128 = { + {{0x43000000, 0x43000000, 0x43000000, 0x43000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMBinNeg150 = { + {{0xC3160000, 0xC3160000, 0xC3160000, 0xC3160000}}}; +XMGLOBALCONST XMVECTORI32 g_XM253 = {{{253, 253, 253, 253}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst1 = { + {{-6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst2 = { + {{+2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst3 = { + {{-5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst4 = { + {{+9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst5 = { + {{-1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst6 = { + {{+1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst7 = { + {{-1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst0 = { + {{+1.442693f, +1.442693f, +1.442693f, +1.442693f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst1 = { + {{-0.721242f, -0.721242f, -0.721242f, -0.721242f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst2 = { + {{+0.479384f, +0.479384f, +0.479384f, +0.479384f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst3 = { + {{-0.350295f, -0.350295f, -0.350295f, -0.350295f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst4 = { + {{+0.248590f, +0.248590f, +0.248590f, +0.248590f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst5 = { + {{-0.145700f, -0.145700f, -0.145700f, -0.145700f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst6 = { + {{+0.057148f, +0.057148f, +0.057148f, +0.057148f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst7 = { + {{-0.010578f, -0.010578f, -0.010578f, -0.010578f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLgE = { + {{+1.442695f, +1.442695f, +1.442695f, +1.442695f}}}; +XMGLOBALCONST XMVECTORF32 g_XMInvLgE = { + {{+6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLg10 = { + {{+3.321928f, +3.321928f, +3.321928f, +3.321928f}}}; +XMGLOBALCONST XMVECTORF32 g_XMInvLg10 = { + {{+3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_UByteMax = {{{255.0f, 255.0f, 255.0f, 255.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ByteMin = {{{-127.0f, -127.0f, -127.0f, -127.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ByteMax = {{{127.0f, 127.0f, 127.0f, 127.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ShortMin = { + {{-32767.0f, -32767.0f, -32767.0f, -32767.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ShortMax = { + {{32767.0f, 32767.0f, 32767.0f, 32767.0f}}}; +XMGLOBALCONST XMVECTORF32 g_UShortMax = { + {{65535.0f, 65535.0f, 65535.0f, 65535.0f}}}; - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4068 4214 4204 4365 4616 4640 6001 6101) - // C4068/4616: ignore unknown pragmas - // C4214/4204: nonstandard extension used - // C4365/4640: Off by default noise - // C6001/6101: False positives +#pragma warning(disable : 4068 4214 4204 4365 4616 4640 6001 6101) +// C4068/4616: ignore unknown pragmas +// C4214/4204: nonstandard extension used +// C4365/4640: Off by default noise +// C6001/6101: False positives #endif #ifdef _PREFAST_ @@ -2187,94 +2981,97 @@ namespace DirectX //------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, uint32_t C2, uint32_t C3) noexcept - { - #if defined(_XM_NO_INTRINSICS_) - XMVECTORU32 vResult; - vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; - vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; - vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; - vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; - return vResult.v; - #elif defined(_XM_ARM_NEON_INTRINSICS_) - XMVECTORU32 vResult; - vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; - vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; - vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; - vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; - return vResult.v; - #else // XM_SSE_INTRINSICS_ - static const XMVECTORU32 g_vMask1 = { { { 1, 1, 1, 1 } } }; - // Move the parms to a vector - __m128i vTemp = _mm_set_epi32(static_cast(C3), static_cast(C2), static_cast(C1), static_cast(C0)); - // Mask off the low bits - vTemp = _mm_and_si128(vTemp, g_vMask1); - // 0xFFFFFFFF on true bits - vTemp = _mm_cmpeq_epi32(vTemp, g_vMask1); - // 0xFFFFFFFF -> 1.0f, 0x00000000 -> 0.0f - vTemp = _mm_and_si128(vTemp, g_XMOne); - return _mm_castsi128_ps(vTemp); - #endif - } +inline XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, + uint32_t C2, + uint32_t C3) noexcept { +#if defined(_XM_NO_INTRINSICS_) + XMVECTORU32 vResult; + vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; + vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; + vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; + vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; + return vResult.v; +#elif defined(_XM_ARM_NEON_INTRINSICS_) + XMVECTORU32 vResult; + vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; + vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; + vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; + vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; + return vResult.v; +#else // XM_SSE_INTRINSICS_ + static const XMVECTORU32 g_vMask1 = {{{1, 1, 1, 1}}}; + // Move the parms to a vector + __m128i vTemp = _mm_set_epi32(static_cast(C3), static_cast(C2), + static_cast(C1), static_cast(C0)); + // Mask off the low bits + vTemp = _mm_and_si128(vTemp, g_vMask1); + // 0xFFFFFFFF on true bits + vTemp = _mm_cmpeq_epi32(vTemp, g_vMask1); + // 0xFFFFFFFF -> 1.0f, 0x00000000 -> 0.0f + vTemp = _mm_and_si128(vTemp, g_XMOne); + return _mm_castsi128_ps(vTemp); +#endif +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept - { - assert(IntConstant >= -16 && IntConstant <= 15); - assert(DivExponent < 32); - #if defined(_XM_NO_INTRINSICS_) +inline XMVECTOR XM_CALLCONV +XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept { + assert(IntConstant >= -16 && IntConstant <= 15); + assert(DivExponent < 32); +#if defined(_XM_NO_INTRINSICS_) - using DirectX::XMConvertVectorIntToFloat; + using DirectX::XMConvertVectorIntToFloat; - XMVECTORI32 V = { { { IntConstant, IntConstant, IntConstant, IntConstant } } }; - return XMConvertVectorIntToFloat(V.v, DivExponent); + XMVECTORI32 V = {{{IntConstant, IntConstant, IntConstant, IntConstant}}}; + return XMConvertVectorIntToFloat(V.v, DivExponent); - #elif defined(_XM_ARM_NEON_INTRINSICS_) - // Splat the int - int32x4_t vScale = vdupq_n_s32(IntConstant); - // Convert to a float - XMVECTOR vResult = vcvtq_f32_s32(vScale); - // Convert DivExponent into 1.0f/(1<(&vScale)[0]); - return vResult; - #else // XM_SSE_INTRINSICS_ - // Splat the int - __m128i vScale = _mm_set1_epi32(IntConstant); - // Convert to a float - XMVECTOR vResult = _mm_cvtepi32_ps(vScale); - // Convert DivExponent into 1.0f/(1<(uScale)); - // Multiply by the reciprocal (Perform a right shift by DivExponent) - vResult = _mm_mul_ps(vResult, _mm_castsi128_ps(vScale)); - return vResult; - #endif - } +#elif defined(_XM_ARM_NEON_INTRINSICS_) + // Splat the int + int32x4_t vScale = vdupq_n_s32(IntConstant); + // Convert to a float + XMVECTOR vResult = vcvtq_f32_s32(vScale); + // Convert DivExponent into 1.0f/(1<(&vScale)[0]); + return vResult; +#else // XM_SSE_INTRINSICS_ + // Splat the int + __m128i vScale = _mm_set1_epi32(IntConstant); + // Convert to a float + XMVECTOR vResult = _mm_cvtepi32_ps(vScale); + // Convert DivExponent into 1.0f/(1<(uScale)); + // Multiply by the reciprocal (Perform a right shift by DivExponent) + vResult = _mm_mul_ps(vResult, _mm_castsi128_ps(vScale)); + return vResult; +#endif +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept - { - assert(IntConstant >= -16 && IntConstant <= 15); - #if defined(_XM_NO_INTRINSICS_) +inline XMVECTOR XM_CALLCONV +XMVectorSplatConstantInt(int32_t IntConstant) noexcept { + assert(IntConstant >= -16 && IntConstant <= 15); +#if defined(_XM_NO_INTRINSICS_) - XMVECTORI32 V = { { { IntConstant, IntConstant, IntConstant, IntConstant } } }; - return V.v; + XMVECTORI32 V = {{{IntConstant, IntConstant, IntConstant, IntConstant}}}; + return V.v; - #elif defined(_XM_ARM_NEON_INTRINSICS_) - int32x4_t V = vdupq_n_s32(IntConstant); - return reinterpret_cast(&V)[0]; - #else // XM_SSE_INTRINSICS_ - __m128i V = _mm_set1_epi32(IntConstant); - return _mm_castsi128_ps(V); - #endif - } +#elif defined(_XM_ARM_NEON_INTRINSICS_) + int32x4_t V = vdupq_n_s32(IntConstant); + return reinterpret_cast(&V)[0]; +#else // XM_SSE_INTRINSICS_ + __m128i V = _mm_set1_epi32(IntConstant); + return _mm_castsi128_ps(V); +#endif +} #include "DirectXMathConvert.inl" #include "DirectXMathVector.inl" @@ -2291,5 +3088,4 @@ namespace DirectX #pragma warning(pop) #endif -} // namespace DirectX - +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h index 8eb49113d..2487c67eb 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h @@ -11,1249 +11,1319 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - namespace PackedVector - { - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4201 4365 4324 4996) - // C4201: nonstandard extension used - // C4365: Off by default noise - // C4324: alignment padding warnings - // C4996: deprecation warnings - #endif +namespace PackedVector { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4201 4365 4324 4996) +// C4201: nonstandard extension used +// C4365: Off by default noise +// C4324: alignment padding warnings +// C4996: deprecation warnings +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wgnu-anonymous-struct" - #pragma clang diagnostic ignored "-Wnested-anon-types" - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-anonymous-struct" +#pragma clang diagnostic ignored "-Wnested-anon-types" +#endif - //------------------------------------------------------------------------------ - // ARGB Color; 8-8-8-8 bit unsigned normalized integer components packed into - // a 32 bit integer. The normalized color is packed into 32 bits using 8 bit - // unsigned, normalized integers for the alpha, red, green, and blue components. - // The alpha component is stored in the most significant bits and the blue - // component in the least significant bits (A8R8G8B8): - // [32] aaaaaaaa rrrrrrrr gggggggg bbbbbbbb [0] - struct XMCOLOR - { - union - { - struct - { - uint8_t b; // Blue: 0/255 to 255/255 - uint8_t g; // Green: 0/255 to 255/255 - uint8_t r; // Red: 0/255 to 255/255 - uint8_t a; // Alpha: 0/255 to 255/255 - }; - uint32_t c; - }; - - XMCOLOR() = default; - - XMCOLOR(const XMCOLOR&) = default; - XMCOLOR& operator=(const XMCOLOR&) = default; - - XMCOLOR(XMCOLOR&&) = default; - XMCOLOR& operator=(XMCOLOR&&) = default; - - constexpr XMCOLOR(uint32_t Color) noexcept : c(Color) {} - XMCOLOR(float _r, float _g, float _b, float _a) noexcept; - explicit XMCOLOR(_In_reads_(4) const float* pArray) noexcept; - - operator uint32_t () const noexcept { return c; } - - XMCOLOR& operator= (const uint32_t Color) noexcept { c = Color; return *this; } +//------------------------------------------------------------------------------ +// ARGB Color; 8-8-8-8 bit unsigned normalized integer components packed into +// a 32 bit integer. The normalized color is packed into 32 bits using 8 bit +// unsigned, normalized integers for the alpha, red, green, and blue components. +// The alpha component is stored in the most significant bits and the blue +// component in the least significant bits (A8R8G8B8): +// [32] aaaaaaaa rrrrrrrr gggggggg bbbbbbbb [0] +struct XMCOLOR { + union { + struct { + uint8_t b; // Blue: 0/255 to 255/255 + uint8_t g; // Green: 0/255 to 255/255 + uint8_t r; // Red: 0/255 to 255/255 + uint8_t a; // Alpha: 0/255 to 255/255 }; + uint32_t c; + }; - //------------------------------------------------------------------------------ - // 16 bit floating point number consisting of a sign bit, a 5 bit biased - // exponent, and a 10 bit mantissa - using HALF = uint16_t; + XMCOLOR() = default; - //------------------------------------------------------------------------------ - // 2D Vector; 16 bit floating point components - struct XMHALF2 - { - union - { - struct - { - HALF x; - HALF y; - }; - uint32_t v; - }; + XMCOLOR(const XMCOLOR&) = default; + XMCOLOR& operator=(const XMCOLOR&) = default; - XMHALF2() = default; + XMCOLOR(XMCOLOR&&) = default; + XMCOLOR& operator=(XMCOLOR&&) = default; - XMHALF2(const XMHALF2&) = default; - XMHALF2& operator=(const XMHALF2&) = default; + constexpr XMCOLOR(uint32_t Color) noexcept : c(Color) {} + XMCOLOR(float _r, float _g, float _b, float _a) noexcept; + explicit XMCOLOR(_In_reads_(4) const float* pArray) noexcept; - XMHALF2(XMHALF2&&) = default; - XMHALF2& operator=(XMHALF2&&) = default; + operator uint32_t() const noexcept { return c; } - explicit constexpr XMHALF2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMHALF2(HALF _x, HALF _y) noexcept : x(_x), y(_y) {} - explicit XMHALF2(_In_reads_(2) const HALF* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMHALF2(float _x, float _y) noexcept; - explicit XMHALF2(_In_reads_(2) const float* pArray) noexcept; + XMCOLOR& operator=(const uint32_t Color) noexcept { + c = Color; + return *this; + } +}; - XMHALF2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 16 bit floating point number consisting of a sign bit, a 5 bit biased +// exponent, and a 10 bit mantissa +using HALF = uint16_t; + +//------------------------------------------------------------------------------ +// 2D Vector; 16 bit floating point components +struct XMHALF2 { + union { + struct { + HALF x; + HALF y; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 2D Vector; 16 bit signed normalized integer components - struct XMSHORTN2 - { - union - { - struct - { - int16_t x; - int16_t y; - }; - uint32_t v; - }; + XMHALF2() = default; - XMSHORTN2() = default; + XMHALF2(const XMHALF2&) = default; + XMHALF2& operator=(const XMHALF2&) = default; - XMSHORTN2(const XMSHORTN2&) = default; - XMSHORTN2& operator=(const XMSHORTN2&) = default; + XMHALF2(XMHALF2&&) = default; + XMHALF2& operator=(XMHALF2&&) = default; - XMSHORTN2(XMSHORTN2&&) = default; - XMSHORTN2& operator=(XMSHORTN2&&) = default; + explicit constexpr XMHALF2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMHALF2(HALF _x, HALF _y) noexcept : x(_x), y(_y) {} + explicit XMHALF2(_In_reads_(2) const HALF* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMHALF2(float _x, float _y) noexcept; + explicit XMHALF2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMSHORTN2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMSHORTN2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} - explicit XMSHORTN2(_In_reads_(2) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMSHORTN2(float _x, float _y) noexcept; - explicit XMSHORTN2(_In_reads_(2) const float* pArray) noexcept; + XMHALF2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORTN2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 2D Vector; 16 bit signed normalized integer components +struct XMSHORTN2 { + union { + struct { + int16_t x; + int16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit signed integer components - struct XMSHORT2 - { - union - { - struct - { - int16_t x; - int16_t y; - }; - uint32_t v; - }; + XMSHORTN2() = default; - XMSHORT2() = default; + XMSHORTN2(const XMSHORTN2&) = default; + XMSHORTN2& operator=(const XMSHORTN2&) = default; - XMSHORT2(const XMSHORT2&) = default; - XMSHORT2& operator=(const XMSHORT2&) = default; + XMSHORTN2(XMSHORTN2&&) = default; + XMSHORTN2& operator=(XMSHORTN2&&) = default; - XMSHORT2(XMSHORT2&&) = default; - XMSHORT2& operator=(XMSHORT2&&) = default; + explicit constexpr XMSHORTN2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMSHORTN2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} + explicit XMSHORTN2(_In_reads_(2) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMSHORTN2(float _x, float _y) noexcept; + explicit XMSHORTN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMSHORT2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMSHORT2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} - explicit XMSHORT2(_In_reads_(2) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMSHORT2(float _x, float _y) noexcept; - explicit XMSHORT2(_In_reads_(2) const float* pArray) noexcept; + XMSHORTN2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORT2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit signed integer components +struct XMSHORT2 { + union { + struct { + int16_t x; + int16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit unsigned normalized integer components - struct XMUSHORTN2 - { - union - { - struct - { - uint16_t x; - uint16_t y; - }; - uint32_t v; - }; + XMSHORT2() = default; - XMUSHORTN2() = default; + XMSHORT2(const XMSHORT2&) = default; + XMSHORT2& operator=(const XMSHORT2&) = default; - XMUSHORTN2(const XMUSHORTN2&) = default; - XMUSHORTN2& operator=(const XMUSHORTN2&) = default; + XMSHORT2(XMSHORT2&&) = default; + XMSHORT2& operator=(XMSHORT2&&) = default; - XMUSHORTN2(XMUSHORTN2&&) = default; - XMUSHORTN2& operator=(XMUSHORTN2&&) = default; + explicit constexpr XMSHORT2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMSHORT2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} + explicit XMSHORT2(_In_reads_(2) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMSHORT2(float _x, float _y) noexcept; + explicit XMSHORT2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUSHORTN2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORTN2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} - explicit XMUSHORTN2(_In_reads_(2) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUSHORTN2(float _x, float _y) noexcept; - explicit XMUSHORTN2(_In_reads_(2) const float* pArray) noexcept; + XMSHORT2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORTN2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit unsigned normalized integer components +struct XMUSHORTN2 { + union { + struct { + uint16_t x; + uint16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit unsigned integer components - struct XMUSHORT2 - { - union - { - struct - { - uint16_t x; - uint16_t y; - }; - uint32_t v; - }; + XMUSHORTN2() = default; - XMUSHORT2() = default; + XMUSHORTN2(const XMUSHORTN2&) = default; + XMUSHORTN2& operator=(const XMUSHORTN2&) = default; - XMUSHORT2(const XMUSHORT2&) = default; - XMUSHORT2& operator=(const XMUSHORT2&) = default; + XMUSHORTN2(XMUSHORTN2&&) = default; + XMUSHORTN2& operator=(XMUSHORTN2&&) = default; - XMUSHORT2(XMUSHORT2&&) = default; - XMUSHORT2& operator=(XMUSHORT2&&) = default; + explicit constexpr XMUSHORTN2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORTN2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} + explicit XMUSHORTN2(_In_reads_(2) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUSHORTN2(float _x, float _y) noexcept; + explicit XMUSHORTN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUSHORT2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORT2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} - explicit XMUSHORT2(_In_reads_(2) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUSHORT2(float _x, float _y) noexcept; - explicit XMUSHORT2(_In_reads_(2) const float* pArray) noexcept; + XMUSHORTN2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORT2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit unsigned integer components +struct XMUSHORT2 { + union { + struct { + uint16_t x; + uint16_t y; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 2D Vector; 8 bit signed normalized integer components - struct XMBYTEN2 - { - union - { - struct - { - int8_t x; - int8_t y; - }; - uint16_t v; - }; + XMUSHORT2() = default; - XMBYTEN2() = default; + XMUSHORT2(const XMUSHORT2&) = default; + XMUSHORT2& operator=(const XMUSHORT2&) = default; - XMBYTEN2(const XMBYTEN2&) = default; - XMBYTEN2& operator=(const XMBYTEN2&) = default; + XMUSHORT2(XMUSHORT2&&) = default; + XMUSHORT2& operator=(XMUSHORT2&&) = default; - XMBYTEN2(XMBYTEN2&&) = default; - XMBYTEN2& operator=(XMBYTEN2&&) = default; + explicit constexpr XMUSHORT2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORT2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} + explicit XMUSHORT2(_In_reads_(2) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUSHORT2(float _x, float _y) noexcept; + explicit XMUSHORT2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMBYTEN2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMBYTEN2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} - explicit XMBYTEN2(_In_reads_(2) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMBYTEN2(float _x, float _y) noexcept; - explicit XMBYTEN2(_In_reads_(2) const float* pArray) noexcept; + XMUSHORT2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTEN2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 2D Vector; 8 bit signed normalized integer components +struct XMBYTEN2 { + union { + struct { + int8_t x; + int8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit signed integer components - struct XMBYTE2 - { - union - { - struct - { - int8_t x; - int8_t y; - }; - uint16_t v; - }; + XMBYTEN2() = default; - XMBYTE2() = default; + XMBYTEN2(const XMBYTEN2&) = default; + XMBYTEN2& operator=(const XMBYTEN2&) = default; - XMBYTE2(const XMBYTE2&) = default; - XMBYTE2& operator=(const XMBYTE2&) = default; + XMBYTEN2(XMBYTEN2&&) = default; + XMBYTEN2& operator=(XMBYTEN2&&) = default; - XMBYTE2(XMBYTE2&&) = default; - XMBYTE2& operator=(XMBYTE2&&) = default; + explicit constexpr XMBYTEN2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMBYTEN2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} + explicit XMBYTEN2(_In_reads_(2) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMBYTEN2(float _x, float _y) noexcept; + explicit XMBYTEN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMBYTE2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMBYTE2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} - explicit XMBYTE2(_In_reads_(2) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMBYTE2(float _x, float _y) noexcept; - explicit XMBYTE2(_In_reads_(2) const float* pArray) noexcept; + XMBYTEN2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTE2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit signed integer components +struct XMBYTE2 { + union { + struct { + int8_t x; + int8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit unsigned normalized integer components - struct XMUBYTEN2 - { - union - { - struct - { - uint8_t x; - uint8_t y; - }; - uint16_t v; - }; + XMBYTE2() = default; - XMUBYTEN2() = default; + XMBYTE2(const XMBYTE2&) = default; + XMBYTE2& operator=(const XMBYTE2&) = default; - XMUBYTEN2(const XMUBYTEN2&) = default; - XMUBYTEN2& operator=(const XMUBYTEN2&) = default; + XMBYTE2(XMBYTE2&&) = default; + XMBYTE2& operator=(XMBYTE2&&) = default; - XMUBYTEN2(XMUBYTEN2&&) = default; - XMUBYTEN2& operator=(XMUBYTEN2&&) = default; + explicit constexpr XMBYTE2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMBYTE2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} + explicit XMBYTE2(_In_reads_(2) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMBYTE2(float _x, float _y) noexcept; + explicit XMBYTE2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUBYTEN2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUBYTEN2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} - explicit XMUBYTEN2(_In_reads_(2) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUBYTEN2(float _x, float _y) noexcept; - explicit XMUBYTEN2(_In_reads_(2) const float* pArray) noexcept; + XMBYTE2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTEN2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit unsigned normalized integer components +struct XMUBYTEN2 { + union { + struct { + uint8_t x; + uint8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit unsigned integer components - struct XMUBYTE2 - { - union - { - struct - { - uint8_t x; - uint8_t y; - }; - uint16_t v; - }; + XMUBYTEN2() = default; - XMUBYTE2() = default; + XMUBYTEN2(const XMUBYTEN2&) = default; + XMUBYTEN2& operator=(const XMUBYTEN2&) = default; - XMUBYTE2(const XMUBYTE2&) = default; - XMUBYTE2& operator=(const XMUBYTE2&) = default; + XMUBYTEN2(XMUBYTEN2&&) = default; + XMUBYTEN2& operator=(XMUBYTEN2&&) = default; - XMUBYTE2(XMUBYTE2&&) = default; - XMUBYTE2& operator=(XMUBYTE2&&) = default; + explicit constexpr XMUBYTEN2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUBYTEN2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} + explicit XMUBYTEN2(_In_reads_(2) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUBYTEN2(float _x, float _y) noexcept; + explicit XMUBYTEN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUBYTE2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUBYTE2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} - explicit XMUBYTE2(_In_reads_(2) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUBYTE2(float _x, float _y) noexcept; - explicit XMUBYTE2(_In_reads_(2) const float* pArray) noexcept; + XMUBYTEN2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTE2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit unsigned integer components +struct XMUBYTE2 { + union { + struct { + uint8_t x; + uint8_t y; }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 5/6/5 unsigned integer components - struct XMU565 - { - union - { - struct - { - uint16_t x : 5; // 0 to 31 - uint16_t y : 6; // 0 to 63 - uint16_t z : 5; // 0 to 31 - }; - uint16_t v; - }; + XMUBYTE2() = default; - XMU565() = default; + XMUBYTE2(const XMUBYTE2&) = default; + XMUBYTE2& operator=(const XMUBYTE2&) = default; - XMU565(const XMU565&) = default; - XMU565& operator=(const XMU565&) = default; + XMUBYTE2(XMUBYTE2&&) = default; + XMUBYTE2& operator=(XMUBYTE2&&) = default; - XMU565(XMU565&&) = default; - XMU565& operator=(XMU565&&) = default; + explicit constexpr XMUBYTE2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUBYTE2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} + explicit XMUBYTE2(_In_reads_(2) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUBYTE2(float _x, float _y) noexcept; + explicit XMUBYTE2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMU565(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMU565(uint8_t _x, uint8_t _y, uint8_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMU565(_In_reads_(3) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMU565(float _x, float _y, float _z) noexcept; - explicit XMU565(_In_reads_(3) const float* pArray) noexcept; + XMUBYTE2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint16_t () const noexcept { return v; } - - XMU565& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 5/6/5 unsigned integer components +struct XMU565 { + union { + struct { + uint16_t x : 5; // 0 to 31 + uint16_t y : 6; // 0 to 63 + uint16_t z : 5; // 0 to 31 }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 11/11/10 floating-point components - // The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent - // and 6-bit mantissa for x component, a 5-bit biased exponent and - // 6-bit mantissa for y component, a 5-bit biased exponent and a 5-bit - // mantissa for z. The z component is stored in the most significant bits - // and the x component in the least significant bits. No sign bits so - // all partial-precision numbers are positive. - // (Z10Y11X11): [32] ZZZZZzzz zzzYYYYY yyyyyyXX XXXxxxxx [0] - struct XMFLOAT3PK - { - union - { - struct - { - uint32_t xm : 6; // x-mantissa - uint32_t xe : 5; // x-exponent - uint32_t ym : 6; // y-mantissa - uint32_t ye : 5; // y-exponent - uint32_t zm : 5; // z-mantissa - uint32_t ze : 5; // z-exponent - }; - uint32_t v; - }; + XMU565() = default; - XMFLOAT3PK() = default; + XMU565(const XMU565&) = default; + XMU565& operator=(const XMU565&) = default; - XMFLOAT3PK(const XMFLOAT3PK&) = default; - XMFLOAT3PK& operator=(const XMFLOAT3PK&) = default; + XMU565(XMU565&&) = default; + XMU565& operator=(XMU565&&) = default; - XMFLOAT3PK(XMFLOAT3PK&&) = default; - XMFLOAT3PK& operator=(XMFLOAT3PK&&) = default; + explicit constexpr XMU565(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMU565(uint8_t _x, uint8_t _y, uint8_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMU565(_In_reads_(3) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} + XMU565(float _x, float _y, float _z) noexcept; + explicit XMU565(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMFLOAT3PK(uint32_t Packed) noexcept : v(Packed) {} - XMFLOAT3PK(float _x, float _y, float _z) noexcept; - explicit XMFLOAT3PK(_In_reads_(3) const float* pArray) noexcept; + operator uint16_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMU565& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMFLOAT3PK& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 11/11/10 floating-point components +// The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent +// and 6-bit mantissa for x component, a 5-bit biased exponent and +// 6-bit mantissa for y component, a 5-bit biased exponent and a 5-bit +// mantissa for z. The z component is stored in the most significant bits +// and the x component in the least significant bits. No sign bits so +// all partial-precision numbers are positive. +// (Z10Y11X11): [32] ZZZZZzzz zzzYYYYY yyyyyyXX XXXxxxxx [0] +struct XMFLOAT3PK { + union { + struct { + uint32_t xm : 6; // x-mantissa + uint32_t xe : 5; // x-exponent + uint32_t ym : 6; // y-mantissa + uint32_t ye : 5; // y-exponent + uint32_t zm : 5; // z-mantissa + uint32_t ze : 5; // z-exponent }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 9/9/9 floating-point components with shared 5-bit exponent - // The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent - // with 9-bit mantissa for the x, y, and z component. The shared exponent - // is stored in the most significant bits and the x component mantissa is in - // the least significant bits. No sign bits so all partial-precision numbers - // are positive. - // (E5Z9Y9X9): [32] EEEEEzzz zzzzzzyy yyyyyyyx xxxxxxxx [0] - struct XMFLOAT3SE - { - union - { - struct - { - uint32_t xm : 9; // x-mantissa - uint32_t ym : 9; // y-mantissa - uint32_t zm : 9; // z-mantissa - uint32_t e : 5; // shared exponent - }; - uint32_t v; - }; + XMFLOAT3PK() = default; - XMFLOAT3SE() = default; + XMFLOAT3PK(const XMFLOAT3PK&) = default; + XMFLOAT3PK& operator=(const XMFLOAT3PK&) = default; - XMFLOAT3SE(const XMFLOAT3SE&) = default; - XMFLOAT3SE& operator=(const XMFLOAT3SE&) = default; + XMFLOAT3PK(XMFLOAT3PK&&) = default; + XMFLOAT3PK& operator=(XMFLOAT3PK&&) = default; - XMFLOAT3SE(XMFLOAT3SE&&) = default; - XMFLOAT3SE& operator=(XMFLOAT3SE&&) = default; + explicit constexpr XMFLOAT3PK(uint32_t Packed) noexcept : v(Packed) {} + XMFLOAT3PK(float _x, float _y, float _z) noexcept; + explicit XMFLOAT3PK(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMFLOAT3SE(uint32_t Packed) noexcept : v(Packed) {} - XMFLOAT3SE(float _x, float _y, float _z) noexcept; - explicit XMFLOAT3SE(_In_reads_(3) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMFLOAT3PK& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMFLOAT3SE& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 9/9/9 floating-point components with shared 5-bit exponent +// The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent +// with 9-bit mantissa for the x, y, and z component. The shared exponent +// is stored in the most significant bits and the x component mantissa is in +// the least significant bits. No sign bits so all partial-precision numbers +// are positive. +// (E5Z9Y9X9): [32] EEEEEzzz zzzzzzyy yyyyyyyx xxxxxxxx [0] +struct XMFLOAT3SE { + union { + struct { + uint32_t xm : 9; // x-mantissa + uint32_t ym : 9; // y-mantissa + uint32_t zm : 9; // z-mantissa + uint32_t e : 5; // shared exponent }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 16 bit floating point components - struct XMHALF4 - { - union - { - struct - { - HALF x; - HALF y; - HALF z; - HALF w; - }; - uint64_t v; - }; + XMFLOAT3SE() = default; - XMHALF4() = default; + XMFLOAT3SE(const XMFLOAT3SE&) = default; + XMFLOAT3SE& operator=(const XMFLOAT3SE&) = default; - XMHALF4(const XMHALF4&) = default; - XMHALF4& operator=(const XMHALF4&) = default; + XMFLOAT3SE(XMFLOAT3SE&&) = default; + XMFLOAT3SE& operator=(XMFLOAT3SE&&) = default; - XMHALF4(XMHALF4&&) = default; - XMHALF4& operator=(XMHALF4&&) = default; + explicit constexpr XMFLOAT3SE(uint32_t Packed) noexcept : v(Packed) {} + XMFLOAT3SE(float _x, float _y, float _z) noexcept; + explicit XMFLOAT3SE(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMHALF4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMHALF4(HALF _x, HALF _y, HALF _z, HALF _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMHALF4(_In_reads_(4) const HALF* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMHALF4(float _x, float _y, float _z, float _w) noexcept; - explicit XMHALF4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - XMHALF4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } + XMFLOAT3SE& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; + +//------------------------------------------------------------------------------ +// 4D Vector; 16 bit floating point components +struct XMHALF4 { + union { + struct { + HALF x; + HALF y; + HALF z; + HALF w; }; + uint64_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 16 bit signed normalized integer components - struct XMSHORTN4 - { - union - { - struct - { - int16_t x; - int16_t y; - int16_t z; - int16_t w; - }; - uint64_t v; - }; + XMHALF4() = default; - XMSHORTN4() = default; + XMHALF4(const XMHALF4&) = default; + XMHALF4& operator=(const XMHALF4&) = default; - XMSHORTN4(const XMSHORTN4&) = default; - XMSHORTN4& operator=(const XMSHORTN4&) = default; + XMHALF4(XMHALF4&&) = default; + XMHALF4& operator=(XMHALF4&&) = default; - XMSHORTN4(XMSHORTN4&&) = default; - XMSHORTN4& operator=(XMSHORTN4&&) = default; + explicit constexpr XMHALF4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMHALF4(HALF _x, HALF _y, HALF _z, HALF _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMHALF4(_In_reads_(4) const HALF* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMHALF4(float _x, float _y, float _z, float _w) noexcept; + explicit XMHALF4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMSHORTN4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMSHORTN4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMSHORTN4(_In_reads_(4) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMSHORTN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMSHORTN4(_In_reads_(4) const float* pArray) noexcept; + XMHALF4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORTN4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D Vector; 16 bit signed normalized integer components +struct XMSHORTN4 { + union { + struct { + int16_t x; + int16_t y; + int16_t z; + int16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit signed integer components - struct XMSHORT4 - { - union - { - struct - { - int16_t x; - int16_t y; - int16_t z; - int16_t w; - }; - uint64_t v; - }; + XMSHORTN4() = default; - XMSHORT4() = default; + XMSHORTN4(const XMSHORTN4&) = default; + XMSHORTN4& operator=(const XMSHORTN4&) = default; - XMSHORT4(const XMSHORT4&) = default; - XMSHORT4& operator=(const XMSHORT4&) = default; + XMSHORTN4(XMSHORTN4&&) = default; + XMSHORTN4& operator=(XMSHORTN4&&) = default; - XMSHORT4(XMSHORT4&&) = default; - XMSHORT4& operator=(XMSHORT4&&) = default; + explicit constexpr XMSHORTN4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMSHORTN4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMSHORTN4(_In_reads_(4) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMSHORTN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMSHORTN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMSHORT4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMSHORT4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMSHORT4(_In_reads_(4) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMSHORT4(float _x, float _y, float _z, float _w) noexcept; - explicit XMSHORT4(_In_reads_(4) const float* pArray) noexcept; + XMSHORTN4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORT4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit signed integer components +struct XMSHORT4 { + union { + struct { + int16_t x; + int16_t y; + int16_t z; + int16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit unsigned normalized integer components - struct XMUSHORTN4 - { - union - { - struct - { - uint16_t x; - uint16_t y; - uint16_t z; - uint16_t w; - }; - uint64_t v; - }; + XMSHORT4() = default; - XMUSHORTN4() = default; + XMSHORT4(const XMSHORT4&) = default; + XMSHORT4& operator=(const XMSHORT4&) = default; - XMUSHORTN4(const XMUSHORTN4&) = default; - XMUSHORTN4& operator=(const XMUSHORTN4&) = default; + XMSHORT4(XMSHORT4&&) = default; + XMSHORT4& operator=(XMSHORT4&&) = default; - XMUSHORTN4(XMUSHORTN4&&) = default; - XMUSHORTN4& operator=(XMUSHORTN4&&) = default; + explicit constexpr XMSHORT4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMSHORT4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMSHORT4(_In_reads_(4) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMSHORT4(float _x, float _y, float _z, float _w) noexcept; + explicit XMSHORT4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUSHORTN4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORTN4(uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUSHORTN4(_In_reads_(4) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUSHORTN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUSHORTN4(_In_reads_(4) const float* pArray) noexcept; + XMSHORT4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORTN4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit unsigned normalized integer components +struct XMUSHORTN4 { + union { + struct { + uint16_t x; + uint16_t y; + uint16_t z; + uint16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit unsigned integer components - struct XMUSHORT4 - { - union - { - struct - { - uint16_t x; - uint16_t y; - uint16_t z; - uint16_t w; - }; - uint64_t v; - }; + XMUSHORTN4() = default; - XMUSHORT4() = default; + XMUSHORTN4(const XMUSHORTN4&) = default; + XMUSHORTN4& operator=(const XMUSHORTN4&) = default; - XMUSHORT4(const XMUSHORT4&) = default; - XMUSHORT4& operator=(const XMUSHORT4&) = default; + XMUSHORTN4(XMUSHORTN4&&) = default; + XMUSHORTN4& operator=(XMUSHORTN4&&) = default; - XMUSHORT4(XMUSHORT4&&) = default; - XMUSHORT4& operator=(XMUSHORT4&&) = default; + explicit constexpr XMUSHORTN4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORTN4(uint16_t _x, uint16_t _y, uint16_t _z, + uint16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUSHORTN4(_In_reads_(4) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUSHORTN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUSHORTN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUSHORT4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORT4(uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUSHORT4(_In_reads_(4) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUSHORT4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUSHORT4(_In_reads_(4) const float* pArray) noexcept; + XMUSHORTN4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORT4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit unsigned integer components +struct XMUSHORT4 { + union { + struct { + uint16_t x; + uint16_t y; + uint16_t z; + uint16_t w; }; + uint64_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // normalized integer for the w component and 10 bit signed, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMXDECN4 - { - union - { - struct - { - int32_t x : 10; // -511/511 to 511/511 - int32_t y : 10; // -511/511 to 511/511 - int32_t z : 10; // -511/511 to 511/511 - uint32_t w : 2; // 0/3 to 3/3 - }; - uint32_t v; - }; + XMUSHORT4() = default; - XMXDECN4() = default; + XMUSHORT4(const XMUSHORT4&) = default; + XMUSHORT4& operator=(const XMUSHORT4&) = default; - XMXDECN4(const XMXDECN4&) = default; - XMXDECN4& operator=(const XMXDECN4&) = default; + XMUSHORT4(XMUSHORT4&&) = default; + XMUSHORT4& operator=(XMUSHORT4&&) = default; - XMXDECN4(XMXDECN4&&) = default; - XMXDECN4& operator=(XMXDECN4&&) = default; + explicit constexpr XMUSHORT4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORT4(uint16_t _x, uint16_t _y, uint16_t _z, + uint16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUSHORT4(_In_reads_(4) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUSHORT4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUSHORT4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMXDECN4(uint32_t Packed) : v(Packed) {} - XMXDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMXDECN4(_In_reads_(4) const float* pArray) noexcept; + XMUSHORT4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint32_t () const noexcept { return v; } - - XMXDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// normalized integer for the w component and 10 bit signed, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMXDECN4 { + union { + struct { + int32_t x : 10; // -511/511 to 511/511 + int32_t y : 10; // -511/511 to 511/511 + int32_t z : 10; // -511/511 to 511/511 + uint32_t w : 2; // 0/3 to 3/3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned - // integer for the w component and 10 bit signed integers for the - // z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMXDEC4 - { - union - { - struct - { - int32_t x : 10; // -511 to 511 - int32_t y : 10; // -511 to 511 - int32_t z : 10; // -511 to 511 - uint32_t w : 2; // 0 to 3 - }; - uint32_t v; - }; + XMXDECN4() = default; - XMXDEC4() = default; + XMXDECN4(const XMXDECN4&) = default; + XMXDECN4& operator=(const XMXDECN4&) = default; - XMXDEC4(const XMXDEC4&) = default; - XMXDEC4& operator=(const XMXDEC4&) = default; + XMXDECN4(XMXDECN4&&) = default; + XMXDECN4& operator=(XMXDECN4&&) = default; - XMXDEC4(XMXDEC4&&) = default; - XMXDEC4& operator=(XMXDEC4&&) = default; + explicit constexpr XMXDECN4(uint32_t Packed) : v(Packed) {} + XMXDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMXDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMXDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMXDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMXDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMXDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMXDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned +// integer for the w component and 10 bit signed integers for the +// z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMXDEC4 { + union { + struct { + int32_t x : 10; // -511 to 511 + int32_t y : 10; // -511 to 511 + int32_t z : 10; // -511 to 511 + uint32_t w : 2; // 0 to 3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit signed, - // normalized integer for the w component and 10 bit signed, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMDECN4 - { - union - { - struct - { - int32_t x : 10; // -511/511 to 511/511 - int32_t y : 10; // -511/511 to 511/511 - int32_t z : 10; // -511/511 to 511/511 - int32_t w : 2; // -1/1 to 1/1 - }; - uint32_t v; - }; + XMXDEC4() = default; - XMDECN4() = default; + XMXDEC4(const XMXDEC4&) = default; + XMXDEC4& operator=(const XMXDEC4&) = default; - XMDECN4(const XMDECN4&) = default; - XMDECN4& operator=(const XMDECN4&) = default; + XMXDEC4(XMXDEC4&&) = default; + XMXDEC4& operator=(XMXDEC4&&) = default; - XMDECN4(XMDECN4&&) = default; - XMDECN4& operator=(XMDECN4&&) = default; + explicit constexpr XMXDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMXDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMXDEC4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMDECN4(uint32_t Packed) noexcept : v(Packed) {} - XMDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMDECN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMXDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit signed, +// normalized integer for the w component and 10 bit signed, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMDECN4 { + union { + struct { + int32_t x : 10; // -511/511 to 511/511 + int32_t y : 10; // -511/511 to 511/511 + int32_t z : 10; // -511/511 to 511/511 + int32_t w : 2; // -1/1 to 1/1 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The 4D Vector is packed into 32 bits as follows: a 2 bit signed, - // integer for the w component and 10 bit signed integers for the - // z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMDEC4 - { - union - { - struct - { - int32_t x : 10; // -511 to 511 - int32_t y : 10; // -511 to 511 - int32_t z : 10; // -511 to 511 - int32_t w : 2; // -1 to 1 - }; - uint32_t v; - }; + XMDECN4() = default; - XMDEC4() = default; + XMDECN4(const XMDECN4&) = default; + XMDECN4& operator=(const XMDECN4&) = default; - XMDEC4(const XMDEC4&) = default; - XMDEC4& operator=(const XMDEC4&) = default; + XMDECN4(XMDECN4&&) = default; + XMDECN4& operator=(XMDECN4&&) = default; - XMDEC4(XMDEC4&&) = default; - XMDEC4& operator=(XMDEC4&&) = default; + explicit constexpr XMDECN4(uint32_t Packed) noexcept : v(Packed) {} + XMDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The 4D Vector is packed into 32 bits as follows: a 2 bit signed, +// integer for the w component and 10 bit signed integers for the +// z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMDEC4 { + union { + struct { + int32_t x : 10; // -511 to 511 + int32_t y : 10; // -511 to 511 + int32_t z : 10; // -511 to 511 + int32_t w : 2; // -1 to 1 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // normalized integer for the w component and 10 bit unsigned, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMUDECN4 - { - union - { - struct - { - uint32_t x : 10; // 0/1023 to 1023/1023 - uint32_t y : 10; // 0/1023 to 1023/1023 - uint32_t z : 10; // 0/1023 to 1023/1023 - uint32_t w : 2; // 0/3 to 3/3 - }; - uint32_t v; - }; + XMDEC4() = default; - XMUDECN4() = default; + XMDEC4(const XMDEC4&) = default; + XMDEC4& operator=(const XMDEC4&) = default; - XMUDECN4(const XMUDECN4&) = default; - XMUDECN4& operator=(const XMUDECN4&) = default; + XMDEC4(XMDEC4&&) = default; + XMDEC4& operator=(XMDEC4&&) = default; - XMUDECN4(XMUDECN4&&) = default; - XMUDECN4& operator=(XMUDECN4&&) = default; + explicit constexpr XMDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMDEC4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUDECN4(uint32_t Packed) noexcept : v(Packed) {} - XMUDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUDECN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// normalized integer for the w component and 10 bit unsigned, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMUDECN4 { + union { + struct { + uint32_t x : 10; // 0/1023 to 1023/1023 + uint32_t y : 10; // 0/1023 to 1023/1023 + uint32_t z : 10; // 0/1023 to 1023/1023 + uint32_t w : 2; // 0/3 to 3/3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // integer for the w component and 10 bit unsigned integers - // for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMUDEC4 - { - union - { - struct - { - uint32_t x : 10; // 0 to 1023 - uint32_t y : 10; // 0 to 1023 - uint32_t z : 10; // 0 to 1023 - uint32_t w : 2; // 0 to 3 - }; - uint32_t v; - }; + XMUDECN4() = default; - XMUDEC4() = default; + XMUDECN4(const XMUDECN4&) = default; + XMUDECN4& operator=(const XMUDECN4&) = default; - XMUDEC4(const XMUDEC4&) = default; - XMUDEC4& operator=(const XMUDEC4&) = default; + XMUDECN4(XMUDECN4&&) = default; + XMUDECN4& operator=(XMUDECN4&&) = default; - XMUDEC4(XMUDEC4&&) = default; - XMUDEC4& operator=(XMUDEC4&&) = default; + explicit constexpr XMUDECN4(uint32_t Packed) noexcept : v(Packed) {} + XMUDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMUDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMUDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// integer for the w component and 10 bit unsigned integers +// for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMUDEC4 { + union { + struct { + uint32_t x : 10; // 0 to 1023 + uint32_t y : 10; // 0 to 1023 + uint32_t z : 10; // 0 to 1023 + uint32_t w : 2; // 0 to 3 }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 8 bit signed normalized integer components - struct XMBYTEN4 - { - union - { - struct - { - int8_t x; - int8_t y; - int8_t z; - int8_t w; - }; - uint32_t v; - }; + XMUDEC4() = default; - XMBYTEN4() = default; + XMUDEC4(const XMUDEC4&) = default; + XMUDEC4& operator=(const XMUDEC4&) = default; - XMBYTEN4(const XMBYTEN4&) = default; - XMBYTEN4& operator=(const XMBYTEN4&) = default; + XMUDEC4(XMUDEC4&&) = default; + XMUDEC4& operator=(XMUDEC4&&) = default; - XMBYTEN4(XMBYTEN4&&) = default; - XMBYTEN4& operator=(XMBYTEN4&&) = default; + explicit constexpr XMUDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMUDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUDEC4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMBYTEN4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMBYTEN4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMBYTEN4(_In_reads_(4) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMBYTEN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMBYTEN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - XMBYTEN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } + XMUDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; + +//------------------------------------------------------------------------------ +// 4D Vector; 8 bit signed normalized integer components +struct XMBYTEN4 { + union { + struct { + int8_t x; + int8_t y; + int8_t z; + int8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit signed integer components - struct XMBYTE4 - { - union - { - struct - { - int8_t x; - int8_t y; - int8_t z; - int8_t w; - }; - uint32_t v; - }; + XMBYTEN4() = default; - XMBYTE4() = default; + XMBYTEN4(const XMBYTEN4&) = default; + XMBYTEN4& operator=(const XMBYTEN4&) = default; - XMBYTE4(const XMBYTE4&) = default; - XMBYTE4& operator=(const XMBYTE4&) = default; + XMBYTEN4(XMBYTEN4&&) = default; + XMBYTEN4& operator=(XMBYTEN4&&) = default; - XMBYTE4(XMBYTE4&&) = default; - XMBYTE4& operator=(XMBYTE4&&) = default; + constexpr XMBYTEN4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMBYTEN4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMBYTEN4(_In_reads_(4) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMBYTEN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMBYTEN4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMBYTE4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMBYTE4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMBYTE4(_In_reads_(4) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMBYTE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMBYTE4(_In_reads_(4) const float* pArray) noexcept; + XMBYTEN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTE4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit signed integer components +struct XMBYTE4 { + union { + struct { + int8_t x; + int8_t y; + int8_t z; + int8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit unsigned normalized integer components - struct XMUBYTEN4 - { - union - { - struct - { - uint8_t x; - uint8_t y; - uint8_t z; - uint8_t w; - }; - uint32_t v; - }; + XMBYTE4() = default; - XMUBYTEN4() = default; + XMBYTE4(const XMBYTE4&) = default; + XMBYTE4& operator=(const XMBYTE4&) = default; - XMUBYTEN4(const XMUBYTEN4&) = default; - XMUBYTEN4& operator=(const XMUBYTEN4&) = default; + XMBYTE4(XMBYTE4&&) = default; + XMBYTE4& operator=(XMBYTE4&&) = default; - XMUBYTEN4(XMUBYTEN4&&) = default; - XMUBYTEN4& operator=(XMUBYTEN4&&) = default; + constexpr XMBYTE4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMBYTE4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMBYTE4(_In_reads_(4) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMBYTE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMBYTE4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMUBYTEN4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMUBYTEN4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMUBYTEN4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUBYTEN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUBYTEN4(_In_reads_(4) const float* pArray) noexcept; + XMBYTE4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTEN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit unsigned normalized integer components +struct XMUBYTEN4 { + union { + struct { + uint8_t x; + uint8_t y; + uint8_t z; + uint8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit unsigned integer components - struct XMUBYTE4 - { - union - { - struct - { - uint8_t x; - uint8_t y; - uint8_t z; - uint8_t w; - }; - uint32_t v; - }; + XMUBYTEN4() = default; - XMUBYTE4() = default; + XMUBYTEN4(const XMUBYTEN4&) = default; + XMUBYTEN4& operator=(const XMUBYTEN4&) = default; - XMUBYTE4(const XMUBYTE4&) = default; - XMUBYTE4& operator=(const XMUBYTE4&) = default; + XMUBYTEN4(XMUBYTEN4&&) = default; + XMUBYTEN4& operator=(XMUBYTEN4&&) = default; - XMUBYTE4(XMUBYTE4&&) = default; - XMUBYTE4& operator=(XMUBYTE4&&) = default; + constexpr XMUBYTEN4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMUBYTEN4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMUBYTEN4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUBYTEN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUBYTEN4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMUBYTE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMUBYTE4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMUBYTE4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUBYTE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUBYTE4(_In_reads_(4) const float* pArray) noexcept; + XMUBYTEN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTE4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit unsigned integer components +struct XMUBYTE4 { + union { + struct { + uint8_t x; + uint8_t y; + uint8_t z; + uint8_t w; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D vector; 4 bit unsigned integer components - struct XMUNIBBLE4 - { - union - { - struct - { - uint16_t x : 4; // 0 to 15 - uint16_t y : 4; // 0 to 15 - uint16_t z : 4; // 0 to 15 - uint16_t w : 4; // 0 to 15 - }; - uint16_t v; - }; + XMUBYTE4() = default; - XMUNIBBLE4() = default; + XMUBYTE4(const XMUBYTE4&) = default; + XMUBYTE4& operator=(const XMUBYTE4&) = default; - XMUNIBBLE4(const XMUNIBBLE4&) = default; - XMUNIBBLE4& operator=(const XMUNIBBLE4&) = default; + XMUBYTE4(XMUBYTE4&&) = default; + XMUBYTE4& operator=(XMUBYTE4&&) = default; - XMUNIBBLE4(XMUNIBBLE4&&) = default; - XMUNIBBLE4& operator=(XMUNIBBLE4&&) = default; + constexpr XMUBYTE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMUBYTE4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMUBYTE4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUBYTE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUBYTE4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUNIBBLE4(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUNIBBLE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUNIBBLE4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUNIBBLE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUNIBBLE4(_In_reads_(4) const float* pArray) noexcept; + XMUBYTE4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint16_t () const noexcept { return v; } - - XMUNIBBLE4& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D vector; 4 bit unsigned integer components +struct XMUNIBBLE4 { + union { + struct { + uint16_t x : 4; // 0 to 15 + uint16_t y : 4; // 0 to 15 + uint16_t z : 4; // 0 to 15 + uint16_t w : 4; // 0 to 15 }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 4D vector: 5/5/5/1 unsigned integer components - struct XMU555 - { - union - { - struct - { - uint16_t x : 5; // 0 to 31 - uint16_t y : 5; // 0 to 31 - uint16_t z : 5; // 0 to 31 - uint16_t w : 1; // 0 or 1 - }; - uint16_t v; - }; + XMUNIBBLE4() = default; - XMU555() = default; + XMUNIBBLE4(const XMUNIBBLE4&) = default; + XMUNIBBLE4& operator=(const XMUNIBBLE4&) = default; - XMU555(const XMU555&) = default; - XMU555& operator=(const XMU555&) = default; + XMUNIBBLE4(XMUNIBBLE4&&) = default; + XMUNIBBLE4& operator=(XMUNIBBLE4&&) = default; - XMU555(XMU555&&) = default; - XMU555& operator=(XMU555&&) = default; + explicit constexpr XMUNIBBLE4(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUNIBBLE4(uint8_t _x, uint8_t _y, uint8_t _z, + uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUNIBBLE4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUNIBBLE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUNIBBLE4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMU555(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMU555(uint8_t _x, uint8_t _y, uint8_t _z, bool _w) noexcept : x(_x), y(_y), z(_z), w(_w ? 0x1 : 0) {} - XMU555(_In_reads_(3) const uint8_t* pArray, _In_ bool _w) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(_w ? 0x1 : 0) {} - XMU555(float _x, float _y, float _z, bool _w) noexcept; - XMU555(_In_reads_(3) const float* pArray, _In_ bool _w) noexcept; + operator uint16_t() const noexcept { return v; } - operator uint16_t () const noexcept { return v; } + XMUNIBBLE4& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMU555& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D vector: 5/5/5/1 unsigned integer components +struct XMU555 { + union { + struct { + uint16_t x : 5; // 0 to 31 + uint16_t y : 5; // 0 to 31 + uint16_t z : 5; // 0 to 31 + uint16_t w : 1; // 0 or 1 }; + uint16_t v; + }; - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif + XMU555() = default; - /**************************************************************************** - * - * Data conversion operations - * - ****************************************************************************/ + XMU555(const XMU555&) = default; + XMU555& operator=(const XMU555&) = default; - float XMConvertHalfToFloat(HALF Value) noexcept; - float* XMConvertHalfToFloatStream(_Out_writes_bytes_(sizeof(float) + OutputStride * (HalfCount - 1)) float* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(HALF) + InputStride * (HalfCount - 1)) const HALF* pInputStream, - _In_ size_t InputStride, _In_ size_t HalfCount) noexcept; - HALF XMConvertFloatToHalf(float Value) noexcept; - HALF* XMConvertFloatToHalfStream(_Out_writes_bytes_(sizeof(HALF) + OutputStride * (FloatCount - 1)) HALF* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(float) + InputStride * (FloatCount - 1)) const float* pInputStream, - _In_ size_t InputStride, _In_ size_t FloatCount) noexcept; + XMU555(XMU555&&) = default; + XMU555& operator=(XMU555&&) = default; - /**************************************************************************** - * - * Load operations - * - ****************************************************************************/ + explicit constexpr XMU555(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMU555(uint8_t _x, uint8_t _y, uint8_t _z, bool _w) noexcept + : x(_x), y(_y), z(_z), w(_w ? 0x1 : 0) {} + XMU555(_In_reads_(3) const uint8_t* pArray, _In_ bool _w) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(_w ? 0x1 : 0) {} + XMU555(float _x, float _y, float _z, bool _w) noexcept; + XMU555(_In_reads_(3) const float* pArray, _In_ bool _w) noexcept; - XMVECTOR XM_CALLCONV XMLoadColor(_In_ const XMCOLOR* pSource) noexcept; + operator uint16_t() const noexcept { return v; } - XMVECTOR XM_CALLCONV XMLoadHalf2(_In_ const XMHALF2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShortN2(_In_ const XMSHORTN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShort2(_In_ const XMSHORT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShortN2(_In_ const XMUSHORTN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShort2(_In_ const XMUSHORT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByteN2(_In_ const XMBYTEN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByte2(_In_ const XMBYTE2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByteN2(_In_ const XMUBYTEN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByte2(_In_ const XMUBYTE2* pSource) noexcept; + XMU555& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMVECTOR XM_CALLCONV XMLoadU565(_In_ const XMU565* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3PK(_In_ const XMFLOAT3PK* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3SE(_In_ const XMFLOAT3SE* pSource) noexcept; +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif - XMVECTOR XM_CALLCONV XMLoadHalf4(_In_ const XMHALF4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShortN4(_In_ const XMSHORTN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShort4(_In_ const XMSHORT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShortN4(_In_ const XMUSHORTN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShort4(_In_ const XMUSHORT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadXDecN4(_In_ const XMXDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDecN4(_In_ const XMUDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDecN4_XR(_In_ const XMUDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDec4(_In_ const XMUDEC4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByteN4(_In_ const XMBYTEN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByte4(_In_ const XMBYTE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByteN4(_In_ const XMUBYTEN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByte4(_In_ const XMUBYTE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUNibble4(_In_ const XMUNIBBLE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadU555(_In_ const XMU555* pSource) noexcept; +/**************************************************************************** + * + * Data conversion operations + * + ****************************************************************************/ - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable : 4996) - // C4996: ignore deprecation warning - #endif +float XMConvertHalfToFloat(HALF Value) noexcept; +float* XMConvertHalfToFloatStream( + _Out_writes_bytes_(sizeof(float) + + OutputStride * (HalfCount - 1)) float* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(HALF) + InputStride * (HalfCount - 1)) + const HALF* pInputStream, + _In_ size_t InputStride, _In_ size_t HalfCount) noexcept; +HALF XMConvertFloatToHalf(float Value) noexcept; +HALF* XMConvertFloatToHalfStream( + _Out_writes_bytes_(sizeof(HALF) + OutputStride * (FloatCount - 1)) + HALF* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(float) + InputStride * (FloatCount - 1)) + const float* pInputStream, + _In_ size_t InputStride, _In_ size_t FloatCount) noexcept; - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #endif +/**************************************************************************** + * + * Load operations + * + ****************************************************************************/ - #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +XMVECTOR XM_CALLCONV XMLoadColor(_In_ const XMCOLOR* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadDecN4(_In_ const XMDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadHalf2(_In_ const XMHALF2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShortN2(_In_ const XMSHORTN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShort2(_In_ const XMSHORT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShortN2(_In_ const XMUSHORTN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShort2(_In_ const XMUSHORT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByteN2(_In_ const XMBYTEN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByte2(_In_ const XMBYTE2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByteN2(_In_ const XMUBYTEN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByte2(_In_ const XMUBYTE2* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadDec4(_In_ const XMDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadU565(_In_ const XMU565* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3PK(_In_ const XMFLOAT3PK* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3SE(_In_ const XMFLOAT3SE* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadXDec4(_In_ const XMXDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadHalf4(_In_ const XMHALF4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShortN4(_In_ const XMSHORTN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShort4(_In_ const XMSHORT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShortN4(_In_ const XMUSHORTN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShort4(_In_ const XMUSHORT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadXDecN4(_In_ const XMXDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDecN4(_In_ const XMUDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDecN4_XR(_In_ const XMUDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDec4(_In_ const XMUDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByteN4(_In_ const XMBYTEN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByte4(_In_ const XMBYTE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByteN4(_In_ const XMUBYTEN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByte4(_In_ const XMUBYTE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUNibble4(_In_ const XMUNIBBLE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadU555(_In_ const XMU555* pSource) noexcept; - #ifdef __GNUC__ - #pragma GCC diagnostic pop - #endif - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) +// C4996: ignore deprecation warning +#endif - /**************************************************************************** - * - * Store operations - * - ****************************************************************************/ +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif - void XM_CALLCONV XMStoreColor(_Out_ XMCOLOR* pDestination, _In_ FXMVECTOR V) noexcept; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif - void XM_CALLCONV XMStoreHalf2(_Out_ XMHALF2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShortN2(_Out_ XMSHORTN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShort2(_Out_ XMSHORT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShortN2(_Out_ XMUSHORTN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShort2(_Out_ XMUSHORT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByteN2(_Out_ XMBYTEN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByte2(_Out_ XMBYTE2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByteN2(_Out_ XMUBYTEN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByte2(_Out_ XMUBYTE2* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadDecN4(_In_ const XMDECN4* pSource) noexcept; - void XM_CALLCONV XMStoreU565(_Out_ XMU565* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3PK(_Out_ XMFLOAT3PK* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3SE(_Out_ XMFLOAT3SE* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadDec4(_In_ const XMDEC4* pSource) noexcept; - void XM_CALLCONV XMStoreHalf4(_Out_ XMHALF4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShortN4(_Out_ XMSHORTN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShort4(_Out_ XMSHORT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShortN4(_Out_ XMUSHORTN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShort4(_Out_ XMUSHORT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreXDecN4(_Out_ XMXDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDecN4(_Out_ XMUDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDecN4_XR(_Out_ XMUDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDec4(_Out_ XMUDEC4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByteN4(_Out_ XMBYTEN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByte4(_Out_ XMBYTE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByteN4(_Out_ XMUBYTEN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByte4(_Out_ XMUBYTE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUNibble4(_Out_ XMUNIBBLE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreU555(_Out_ XMU555* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadXDec4(_In_ const XMXDEC4* pSource) noexcept; - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable : 4996) - // C4996: ignore deprecation warning - #endif +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #endif +/**************************************************************************** + * + * Store operations + * + ****************************************************************************/ - #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +void XM_CALLCONV XMStoreColor(_Out_ XMCOLOR* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreDecN4(_Out_ XMDECN4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreHalf2(_Out_ XMHALF2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShortN2(_Out_ XMSHORTN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShort2(_Out_ XMSHORT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShortN2(_Out_ XMUSHORTN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShort2(_Out_ XMUSHORT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByteN2(_Out_ XMBYTEN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByte2(_Out_ XMBYTE2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByteN2(_Out_ XMUBYTEN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByte2(_Out_ XMUBYTE2* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreDec4(_Out_ XMDEC4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreU565(_Out_ XMU565* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3PK(_Out_ XMFLOAT3PK* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3SE(_Out_ XMFLOAT3SE* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreXDec4(_Out_ XMXDEC4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreHalf4(_Out_ XMHALF4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShortN4(_Out_ XMSHORTN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShort4(_Out_ XMSHORT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShortN4(_Out_ XMUSHORTN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShort4(_Out_ XMUSHORT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreXDecN4(_Out_ XMXDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDecN4(_Out_ XMUDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDecN4_XR(_Out_ XMUDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDec4(_Out_ XMUDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByteN4(_Out_ XMBYTEN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByte4(_Out_ XMBYTE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByteN4(_Out_ XMUBYTEN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByte4(_Out_ XMUBYTE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUNibble4(_Out_ XMUNIBBLE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreU555(_Out_ XMU555* pDestination, + _In_ FXMVECTOR V) noexcept; - #ifdef __GNUC__ - #pragma GCC diagnostic pop - #endif - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) +// C4996: ignore deprecation warning +#endif - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4068 4214 4204 4365 4616 6001 6101) - // C4068/4616: ignore unknown pragmas - // C4214/4204: nonstandard extension used - // C4365: Off by default noise - // C6001/6101: False positives - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif - #ifdef _PREFAST_ - #pragma prefast(push) - #pragma prefast(disable : 25000, "FXMVECTOR is 16 bytes") - #pragma prefast(disable : 26495, "Union initialization confuses /analyze") - #endif +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wunknown-warning-option" - #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" - #endif +XM_DEPRECATED +void XM_CALLCONV XMStoreDecN4(_Out_ XMDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; - #include "DirectXPackedVector.inl" +XM_DEPRECATED +void XM_CALLCONV XMStoreDec4(_Out_ XMDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _PREFAST_ - #pragma prefast(pop) - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif - } // namespace PackedVector +XM_DEPRECATED +void XM_CALLCONV XMStoreXDec4(_Out_ XMXDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; -} // namespace DirectX +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4068 4214 4204 4365 4616 6001 6101) +// C4068/4616: ignore unknown pragmas +// C4214/4204: nonstandard extension used +// C4365: Off by default noise +// C6001/6101: False positives +#endif + +#ifdef _PREFAST_ +#pragma prefast(push) +#pragma prefast(disable : 25000, "FXMVECTOR is 16 bytes") +#pragma prefast(disable : 26495, "Union initialization confuses /analyze") +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" +#endif + +#include "DirectXPackedVector.inl" + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _PREFAST_ +#pragma prefast(pop) +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif +} // namespace PackedVector + +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h index f4c53898e..eaf7074c3 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h @@ -149,77 +149,86 @@ #define _SAL_VERSION 20 #endif -#ifdef _PREFAST_ // [ +#ifdef _PREFAST_ // [ // choose attribute or __declspec implementation -#ifndef _USE_DECLSPECS_FOR_SAL // [ +#ifndef _USE_DECLSPECS_FOR_SAL // [ #define _USE_DECLSPECS_FOR_SAL 1 -#endif // ] +#endif // ] -#if _USE_DECLSPECS_FOR_SAL // [ +#if _USE_DECLSPECS_FOR_SAL // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 0 -#elif !defined(_USE_ATTRIBUTES_FOR_SAL) // ][ -#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ +#elif !defined(_USE_ATTRIBUTES_FOR_SAL) // ][ +#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ #define _USE_ATTRIBUTES_FOR_SAL 1 -#else // ][ +#else // ][ #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] -#endif // ] +#endif // ] +#endif // ] - -#if !_USE_DECLSPECS_FOR_SAL // [ -#if !_USE_ATTRIBUTES_FOR_SAL // [ -#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ +#if !_USE_DECLSPECS_FOR_SAL // [ +#if !_USE_ATTRIBUTES_FOR_SAL // [ +#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 1 -#else // ][ +#else // ][ #undef _USE_DECLSPECS_FOR_SAL -#define _USE_DECLSPECS_FOR_SAL 1 -#endif // ] -#endif // ] -#endif // ] +#define _USE_DECLSPECS_FOR_SAL 1 +#endif // ] +#endif // ] +#endif // ] #else // Disable expansion of SAL macros in non-Prefast mode to // improve compiler throughput. -#ifndef _USE_DECLSPECS_FOR_SAL // [ +#ifndef _USE_DECLSPECS_FOR_SAL // [ #define _USE_DECLSPECS_FOR_SAL 0 -#endif // ] -#ifndef _USE_ATTRIBUTES_FOR_SAL // [ +#endif // ] +#ifndef _USE_ATTRIBUTES_FOR_SAL // [ #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] +#endif // ] -#endif // ] +#endif // ] // safeguard for MIDL and RC builds -#if _USE_DECLSPECS_FOR_SAL && ( defined( MIDL_PASS ) || defined(__midl) || defined(RC_INVOKED) || !defined(_PREFAST_) ) /*IFSTRIP=IGN*/ // [ +#if _USE_DECLSPECS_FOR_SAL && (defined(MIDL_PASS) || defined(__midl) || defined(RC_INVOKED) || \ + !defined(_PREFAST_)) /*IFSTRIP=IGN*/ // [ #undef _USE_DECLSPECS_FOR_SAL #define _USE_DECLSPECS_FOR_SAL 0 -#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL && ( !defined(_MSC_EXTENSIONS) || defined( MIDL_PASS ) || defined(__midl) || defined(RC_INVOKED) ) /*IFSTRIP=IGN*/ // [ +#endif // ] +#if _USE_ATTRIBUTES_FOR_SAL && (!defined(_MSC_EXTENSIONS) || defined(MIDL_PASS) || \ + defined(__midl) || defined(RC_INVOKED)) /*IFSTRIP=IGN*/ // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] +#endif // ] #if _USE_DECLSPECS_FOR_SAL || _USE_ATTRIBUTES_FOR_SAL // Special enum type for Y/N/M -enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; +enum __SAL_YesNo { _SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default }; #endif #if defined(BUILD_WINDOWS) && !_USE_ATTRIBUTES_FOR_SAL /*IFSTRIP=IGN*/ -#define _SAL1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL1_1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.1") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL1_2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.2") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "2") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.1") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.2") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "2") _GrouP_(annotes _SAL_nop_impl_) #else -#define _SAL1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1") _Group_(annotes _SAL_nop_impl_) -#define _SAL1_1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.1") _Group_(annotes _SAL_nop_impl_) -#define _SAL1_2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.2") _Group_(annotes _SAL_nop_impl_) -#define _SAL2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "2") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.1") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.2") _Group_(annotes _SAL_nop_impl_) +#define _SAL2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "2") _Group_(annotes _SAL_nop_impl_) #endif //============================================================================ @@ -232,63 +241,64 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _At_(target, annos) specifies that the annotations listed in 'annos' is to // be applied to 'target' rather than to the identifier which is the current // lexical target. -#define _At_(target, annos) _At_impl_(target, annos _SAL_nop_impl_) +#define _At_(target, annos) _At_impl_(target, annos _SAL_nop_impl_) // _At_buffer_(target, iter, bound, annos) is similar to _At_, except that // target names a buffer, and each annotation in annos is applied to each // element of target up to bound, with the variable named in iter usable // by the annotations to refer to relevant offsets within target. -#define _At_buffer_(target, iter, bound, annos) _At_buffer_impl_(target, iter, bound, annos _SAL_nop_impl_) +#define _At_buffer_(target, iter, bound, annos) \ + _At_buffer_impl_(target, iter, bound, annos _SAL_nop_impl_) // _When_(expr, annos) specifies that the annotations listed in 'annos' only // apply when 'expr' evaluates to non-zero. -#define _When_(expr, annos) _When_impl_(expr, annos _SAL_nop_impl_) -#define _Group_(annos) _Group_impl_(annos _SAL_nop_impl_) -#define _GrouP_(annos) _GrouP_impl_(annos _SAL_nop_impl_) +#define _When_(expr, annos) _When_impl_(expr, annos _SAL_nop_impl_) +#define _Group_(annos) _Group_impl_(annos _SAL_nop_impl_) +#define _GrouP_(annos) _GrouP_impl_(annos _SAL_nop_impl_) // indicates whether normal post conditions apply to a function -#define _Success_(expr) _SAL2_Source_(_Success_, (expr), _Success_impl_(expr)) +#define _Success_(expr) _SAL2_Source_(_Success_, (expr), _Success_impl_(expr)) // indicates whether post conditions apply to a function returning // the type that this annotation is applied to -#define _Return_type_success_(expr) _SAL2_Source_(_Return_type_success_, (expr), _Success_impl_(expr)) +#define _Return_type_success_(expr) \ + _SAL2_Source_(_Return_type_success_, (expr), _Success_impl_(expr)) // Establish postconditions that apply only if the function does not succeed -#define _On_failure_(annos) _On_failure_impl_(annos _SAL_nop_impl_) +#define _On_failure_(annos) _On_failure_impl_(annos _SAL_nop_impl_) // Establish postconditions that apply in both success and failure cases. // Only applicable with functions that have _Success_ or _Return_type_succss_. -#define _Always_(annos) _Always_impl_(annos _SAL_nop_impl_) +#define _Always_(annos) _Always_impl_(annos _SAL_nop_impl_) // Usable on a function definition. Asserts that a function declaration is // in scope, and its annotations are to be used. There are no other annotations // allowed on the function definition. -#define _Use_decl_annotations_ _Use_decl_anno_impl_ +#define _Use_decl_annotations_ _Use_decl_anno_impl_ // _Notref_ may precede a _Deref_ or "real" annotation, and removes one // level of dereference if the parameter is a C++ reference (&). If the // net deref on a "real" annotation is negative, it is simply discarded. -#define _Notref_ _Notref_impl_ +#define _Notref_ _Notref_impl_ // Annotations for defensive programming styles. -#define _Pre_defensive_ _SA_annotes0(SAL_pre_defensive) -#define _Post_defensive_ _SA_annotes0(SAL_post_defensive) +#define _Pre_defensive_ _SA_annotes0(SAL_pre_defensive) +#define _Post_defensive_ _SA_annotes0(SAL_post_defensive) -#define _In_defensive_(annotes) _Pre_defensive_ _Group_(annotes) -#define _Out_defensive_(annotes) _Post_defensive_ _Group_(annotes) -#define _Inout_defensive_(annotes) _Pre_defensive_ _Post_defensive_ _Group_(annotes) +#define _In_defensive_(annotes) _Pre_defensive_ _Group_(annotes) +#define _Out_defensive_(annotes) _Post_defensive_ _Group_(annotes) +#define _Inout_defensive_(annotes) _Pre_defensive_ _Post_defensive_ _Group_(annotes) //============================================================================ // _In_\_Out_ Layer: //============================================================================ // Reserved pointer parameters, must always be NULL. -#define _Reserved_ _SAL2_Source_(_Reserved_, (), _Pre1_impl_(__null_impl)) +#define _Reserved_ _SAL2_Source_(_Reserved_, (), _Pre1_impl_(__null_impl)) // _Const_ allows specification that any namable memory location is considered // readonly for a given call. -#define _Const_ _SAL2_Source_(_Const_, (), _Pre1_impl_(__readaccess_impl_notref)) - +#define _Const_ _SAL2_Source_(_Const_, (), _Pre1_impl_(__readaccess_impl_notref)) // Input parameters -------------------------- @@ -296,35 +306,51 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _In_ by itself can be used with non-pointer types (although it is redundant). // e.g. void SetPoint( _In_ const POINT* pPT ); -#define _In_ _SAL2_Source_(_In_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_ _Deref_pre1_impl_(__readaccess_impl_notref)) -#define _In_opt_ _SAL2_Source_(_In_opt_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_ _Deref_pre_readonly_) +#define _In_ \ + _SAL2_Source_(_In_, (), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre_valid_impl_ _Deref_pre1_impl_(__readaccess_impl_notref)) +#define _In_opt_ \ + _SAL2_Source_(_In_opt_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_ _Deref_pre_readonly_) // nullterminated 'in' parameters. // e.g. void CopyStr( _In_z_ const char* szFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); -#define _In_z_ _SAL2_Source_(_In_z_, (), _In_ _Pre1_impl_(__zterm_impl)) -#define _In_opt_z_ _SAL2_Source_(_In_opt_z_, (), _In_opt_ _Pre1_impl_(__zterm_impl)) - +#define _In_z_ _SAL2_Source_(_In_z_, (), _In_ _Pre1_impl_(__zterm_impl)) +#define _In_opt_z_ _SAL2_Source_(_In_opt_z_, (), _In_opt_ _Pre1_impl_(__zterm_impl)) // 'input' buffers with given size -#define _In_reads_(size) _SAL2_Source_(_In_reads_, (size), _Pre_count_(size) _Deref_pre_readonly_) -#define _In_reads_opt_(size) _SAL2_Source_(_In_reads_opt_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_reads_bytes_(size) _SAL2_Source_(_In_reads_bytes_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_reads_bytes_opt_(size) _SAL2_Source_(_In_reads_bytes_opt_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) -#define _In_reads_z_(size) _SAL2_Source_(_In_reads_z_, (size), _In_reads_(size) _Pre_z_) -#define _In_reads_opt_z_(size) _SAL2_Source_(_In_reads_opt_z_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_ _Pre_opt_z_) -#define _In_reads_or_z_(size) _SAL2_Source_(_In_reads_or_z_, (size), _In_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) -#define _In_reads_or_z_opt_(size) _SAL2_Source_(_In_reads_or_z_opt_, (size), _In_opt_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) - +#define _In_reads_(size) _SAL2_Source_(_In_reads_, (size), _Pre_count_(size) _Deref_pre_readonly_) +#define _In_reads_opt_(size) \ + _SAL2_Source_(_In_reads_opt_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_reads_bytes_(size) \ + _SAL2_Source_(_In_reads_bytes_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_reads_bytes_opt_(size) \ + _SAL2_Source_(_In_reads_bytes_opt_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_reads_z_(size) _SAL2_Source_(_In_reads_z_, (size), _In_reads_(size) _Pre_z_) +#define _In_reads_opt_z_(size) \ + _SAL2_Source_(_In_reads_opt_z_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_ _Pre_opt_z_) +#define _In_reads_or_z_(size) \ + _SAL2_Source_(_In_reads_or_z_, (size), \ + _In_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) \ + _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) +#define _In_reads_or_z_opt_(size) \ + _SAL2_Source_(_In_reads_or_z_opt_, (size), \ + _In_opt_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) \ + _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) // 'input' buffers valid to the given end pointer -#define _In_reads_to_ptr_(ptr) _SAL2_Source_(_In_reads_to_ptr_, (ptr), _Pre_ptrdiff_count_(ptr) _Deref_pre_readonly_) -#define _In_reads_to_ptr_opt_(ptr) _SAL2_Source_(_In_reads_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_) -#define _In_reads_to_ptr_z_(ptr) _SAL2_Source_(_In_reads_to_ptr_z_, (ptr), _In_reads_to_ptr_(ptr) _Pre_z_) -#define _In_reads_to_ptr_opt_z_(ptr) _SAL2_Source_(_In_reads_to_ptr_opt_z_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_ _Pre_opt_z_) - - +#define _In_reads_to_ptr_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_, (ptr), _Pre_ptrdiff_count_(ptr) _Deref_pre_readonly_) +#define _In_reads_to_ptr_opt_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_) +#define _In_reads_to_ptr_z_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_z_, (ptr), _In_reads_to_ptr_(ptr) _Pre_z_) +#define _In_reads_to_ptr_opt_z_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_opt_z_, (ptr), \ + _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_ _Pre_opt_z_) // Output parameters -------------------------- @@ -333,31 +359,53 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _Outptr_/_Outref) (see below) are typically used to return pointers via parameters. // e.g. void GetPoint( _Out_ POINT* pPT ); -#define _Out_ _SAL2_Source_(_Out_, (), _Out_impl_) -#define _Out_opt_ _SAL2_Source_(_Out_opt_, (), _Out_opt_impl_) +#define _Out_ _SAL2_Source_(_Out_, (), _Out_impl_) +#define _Out_opt_ _SAL2_Source_(_Out_opt_, (), _Out_opt_impl_) -#define _Out_writes_(size) _SAL2_Source_(_Out_writes_, (size), _Pre_cap_(size) _Post_valid_impl_) -#define _Out_writes_opt_(size) _SAL2_Source_(_Out_writes_opt_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) -#define _Out_writes_bytes_(size) _SAL2_Source_(_Out_writes_bytes_, (size), _Pre_bytecap_(size) _Post_valid_impl_) -#define _Out_writes_bytes_opt_(size) _SAL2_Source_(_Out_writes_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) -#define _Out_writes_z_(size) _SAL2_Source_(_Out_writes_z_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_writes_opt_z_(size) _SAL2_Source_(_Out_writes_opt_z_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_writes_(size) _SAL2_Source_(_Out_writes_, (size), _Pre_cap_(size) _Post_valid_impl_) +#define _Out_writes_opt_(size) \ + _SAL2_Source_(_Out_writes_opt_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) +#define _Out_writes_bytes_(size) \ + _SAL2_Source_(_Out_writes_bytes_, (size), _Pre_bytecap_(size) _Post_valid_impl_) +#define _Out_writes_bytes_opt_(size) \ + _SAL2_Source_(_Out_writes_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) +#define _Out_writes_z_(size) \ + _SAL2_Source_(_Out_writes_z_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_writes_opt_z_(size) \ + _SAL2_Source_(_Out_writes_opt_z_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_writes_to_(size,count) _SAL2_Source_(_Out_writes_to_, (size,count), _Pre_cap_(size) _Post_valid_impl_ _Post_count_(count)) -#define _Out_writes_to_opt_(size,count) _SAL2_Source_(_Out_writes_to_opt_, (size,count), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_count_(count)) -#define _Out_writes_all_(size) _SAL2_Source_(_Out_writes_all_, (size), _Out_writes_to_(_Old_(size), _Old_(size))) -#define _Out_writes_all_opt_(size) _SAL2_Source_(_Out_writes_all_opt_, (size), _Out_writes_to_opt_(_Old_(size), _Old_(size))) +#define _Out_writes_to_(size, count) \ + _SAL2_Source_(_Out_writes_to_, (size, count), \ + _Pre_cap_(size) _Post_valid_impl_ _Post_count_(count)) +#define _Out_writes_to_opt_(size, count) \ + _SAL2_Source_(_Out_writes_to_opt_, (size, count), \ + _Pre_opt_cap_(size) _Post_valid_impl_ _Post_count_(count)) +#define _Out_writes_all_(size) \ + _SAL2_Source_(_Out_writes_all_, (size), _Out_writes_to_(_Old_(size), _Old_(size))) +#define _Out_writes_all_opt_(size) \ + _SAL2_Source_(_Out_writes_all_opt_, (size), _Out_writes_to_opt_(_Old_(size), _Old_(size))) -#define _Out_writes_bytes_to_(size,count) _SAL2_Source_(_Out_writes_bytes_to_, (size,count), _Pre_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_writes_bytes_to_opt_(size,count) _SAL2_Source_(_Out_writes_bytes_to_opt_, (size,count), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_writes_bytes_all_(size) _SAL2_Source_(_Out_writes_bytes_all_, (size), _Out_writes_bytes_to_(_Old_(size), _Old_(size))) -#define _Out_writes_bytes_all_opt_(size) _SAL2_Source_(_Out_writes_bytes_all_opt_, (size), _Out_writes_bytes_to_opt_(_Old_(size), _Old_(size))) - -#define _Out_writes_to_ptr_(ptr) _SAL2_Source_(_Out_writes_to_ptr_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_) -#define _Out_writes_to_ptr_opt_(ptr) _SAL2_Source_(_Out_writes_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_) -#define _Out_writes_to_ptr_z_(ptr) _SAL2_Source_(_Out_writes_to_ptr_z_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) -#define _Out_writes_to_ptr_opt_z_(ptr) _SAL2_Source_(_Out_writes_to_ptr_opt_z_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) +#define _Out_writes_bytes_to_(size, count) \ + _SAL2_Source_(_Out_writes_bytes_to_, (size, count), \ + _Pre_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_writes_bytes_to_opt_(size, count) \ + _SAL2_Source_(_Out_writes_bytes_to_opt_, (size, count), \ + _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_writes_bytes_all_(size) \ + _SAL2_Source_(_Out_writes_bytes_all_, (size), _Out_writes_bytes_to_(_Old_(size), _Old_(size))) +#define _Out_writes_bytes_all_opt_(size) \ + _SAL2_Source_(_Out_writes_bytes_all_opt_, (size), \ + _Out_writes_bytes_to_opt_(_Old_(size), _Old_(size))) +#define _Out_writes_to_ptr_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_) +#define _Out_writes_to_ptr_opt_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_) +#define _Out_writes_to_ptr_z_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_z_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) +#define _Out_writes_to_ptr_opt_z_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_opt_z_, (ptr), \ + _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) // Inout parameters ---------------------------- @@ -366,36 +414,65 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // void ModifyPoint( _Inout_ POINT* pPT ); // void ModifyPointByRef( _Inout_ POINT& pPT ); -#define _Inout_ _SAL2_Source_(_Inout_, (), _Prepost_valid_) -#define _Inout_opt_ _SAL2_Source_(_Inout_opt_, (), _Prepost_opt_valid_) +#define _Inout_ _SAL2_Source_(_Inout_, (), _Prepost_valid_) +#define _Inout_opt_ _SAL2_Source_(_Inout_opt_, (), _Prepost_opt_valid_) // For modifying string buffers // void toupper( _Inout_z_ char* sz ); -#define _Inout_z_ _SAL2_Source_(_Inout_z_, (), _Prepost_z_) -#define _Inout_opt_z_ _SAL2_Source_(_Inout_opt_z_, (), _Prepost_opt_z_) +#define _Inout_z_ _SAL2_Source_(_Inout_z_, (), _Prepost_z_) +#define _Inout_opt_z_ _SAL2_Source_(_Inout_opt_z_, (), _Prepost_opt_z_) // For modifying buffers with explicit element size -#define _Inout_updates_(size) _SAL2_Source_(_Inout_updates_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_opt_(size) _SAL2_Source_(_Inout_updates_opt_, (size), _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_z_(size) _SAL2_Source_(_Inout_updates_z_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) _Post1_impl_(__zterm_impl)) -#define _Inout_updates_opt_z_(size) _SAL2_Source_(_Inout_updates_opt_z_, (size), _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) _Post1_impl_(__zterm_impl)) +#define _Inout_updates_(size) \ + _SAL2_Source_(_Inout_updates_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_opt_(size) \ + _SAL2_Source_(_Inout_updates_opt_, (size), \ + _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_z_(size) \ + _SAL2_Source_(_Inout_updates_z_, (size), \ + _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) \ + _Post1_impl_(__zterm_impl)) +#define _Inout_updates_opt_z_(size) \ + _SAL2_Source_(_Inout_updates_opt_z_, (size), \ + _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) \ + _Post1_impl_(__zterm_impl)) -#define _Inout_updates_to_(size,count) _SAL2_Source_(_Inout_updates_to_, (size,count), _Out_writes_to_(size,count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) -#define _Inout_updates_to_opt_(size,count) _SAL2_Source_(_Inout_updates_to_opt_, (size,count), _Out_writes_to_opt_(size,count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) +#define _Inout_updates_to_(size, count) \ + _SAL2_Source_(_Inout_updates_to_, (size, count), \ + _Out_writes_to_(size, count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) +#define _Inout_updates_to_opt_(size, count) \ + _SAL2_Source_(_Inout_updates_to_opt_, (size, count), \ + _Out_writes_to_opt_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) -#define _Inout_updates_all_(size) _SAL2_Source_(_Inout_updates_all_, (size), _Inout_updates_to_(_Old_(size), _Old_(size))) -#define _Inout_updates_all_opt_(size) _SAL2_Source_(_Inout_updates_all_opt_, (size), _Inout_updates_to_opt_(_Old_(size), _Old_(size))) +#define _Inout_updates_all_(size) \ + _SAL2_Source_(_Inout_updates_all_, (size), _Inout_updates_to_(_Old_(size), _Old_(size))) +#define _Inout_updates_all_opt_(size) \ + _SAL2_Source_(_Inout_updates_all_opt_, (size), _Inout_updates_to_opt_(_Old_(size), _Old_(size))) // For modifying buffers with explicit byte size -#define _Inout_updates_bytes_(size) _SAL2_Source_(_Inout_updates_bytes_, (size), _Pre_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_bytes_opt_(size) _SAL2_Source_(_Inout_updates_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_bytes_(size) \ + _SAL2_Source_(_Inout_updates_bytes_, (size), \ + _Pre_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_bytes_opt_(size) \ + _SAL2_Source_(_Inout_updates_bytes_opt_, (size), \ + _Pre_opt_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_bytes_to_(size,count) _SAL2_Source_(_Inout_updates_bytes_to_, (size,count), _Out_writes_bytes_to_(size,count) _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) -#define _Inout_updates_bytes_to_opt_(size,count) _SAL2_Source_(_Inout_updates_bytes_to_opt_, (size,count), _Out_writes_bytes_to_opt_(size,count) _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) - -#define _Inout_updates_bytes_all_(size) _SAL2_Source_(_Inout_updates_bytes_all_, (size), _Inout_updates_bytes_to_(_Old_(size), _Old_(size))) -#define _Inout_updates_bytes_all_opt_(size) _SAL2_Source_(_Inout_updates_bytes_all_opt_, (size), _Inout_updates_bytes_to_opt_(_Old_(size), _Old_(size))) +#define _Inout_updates_bytes_to_(size, count) \ + _SAL2_Source_(_Inout_updates_bytes_to_, (size, count), \ + _Out_writes_bytes_to_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) +#define _Inout_updates_bytes_to_opt_(size, count) \ + _SAL2_Source_(_Inout_updates_bytes_to_opt_, (size, count), \ + _Out_writes_bytes_to_opt_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) +#define _Inout_updates_bytes_all_(size) \ + _SAL2_Source_(_Inout_updates_bytes_all_, (size), \ + _Inout_updates_bytes_to_(_Old_(size), _Old_(size))) +#define _Inout_updates_bytes_all_opt_(size) \ + _SAL2_Source_(_Inout_updates_bytes_all_opt_, (size), \ + _Inout_updates_bytes_to_opt_(_Old_(size), _Old_(size))) // Pointer to pointer parameters ------------------------- @@ -406,7 +483,8 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // and initializes memory and returns the pointer to the new LPWSTR in *ppwsz. // // _Outptr_opt_ - describes parameters that are allowed to be NULL. -// _Outptr_*_result_maybenull_ - describes parameters where the called function might return NULL to the caller. +// _Outptr_*_result_maybenull_ - describes parameters where the called function might return NULL +// to the caller. // // Example: // void MyFunc(_Outptr_opt_ int **ppData1, _Outptr_result_maybenull_ int **ppData2); @@ -415,94 +493,203 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // MyFunc(&pData1, &pData2); // ok: both non-NULL // if (*pData1 == *pData2) ... // error: pData2 might be NULL after call -#define _Outptr_ _SAL2_Source_(_Outptr_, (), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) -#define _Outptr_result_maybenull_ _SAL2_Source_(_Outptr_result_maybenull_, (), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) -#define _Outptr_opt_ _SAL2_Source_(_Outptr_opt_, (), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) -#define _Outptr_opt_result_maybenull_ _SAL2_Source_(_Outptr_opt_result_maybenull_, (), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) +#define _Outptr_ \ + _SAL2_Source_(_Outptr_, (), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) +#define _Outptr_result_maybenull_ \ + _SAL2_Source_(_Outptr_result_maybenull_, (), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) +#define _Outptr_opt_ \ + _SAL2_Source_(_Outptr_opt_, (), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) +#define _Outptr_opt_result_maybenull_ \ + _SAL2_Source_(_Outptr_opt_result_maybenull_, (), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) // Annotations for _Outptr_ parameters returning pointers to null terminated strings. -#define _Outptr_result_z_ _SAL2_Source_(_Outptr_result_z_, (), _Out_impl_ _Deref_post_z_) -#define _Outptr_opt_result_z_ _SAL2_Source_(_Outptr_opt_result_z_, (), _Out_opt_impl_ _Deref_post_z_) -#define _Outptr_result_maybenull_z_ _SAL2_Source_(_Outptr_result_maybenull_z_, (), _Out_impl_ _Deref_post_opt_z_) -#define _Outptr_opt_result_maybenull_z_ _SAL2_Source_(_Outptr_opt_result_maybenull_z_, (), _Out_opt_impl_ _Deref_post_opt_z_) +#define _Outptr_result_z_ _SAL2_Source_(_Outptr_result_z_, (), _Out_impl_ _Deref_post_z_) +#define _Outptr_opt_result_z_ \ + _SAL2_Source_(_Outptr_opt_result_z_, (), _Out_opt_impl_ _Deref_post_z_) +#define _Outptr_result_maybenull_z_ \ + _SAL2_Source_(_Outptr_result_maybenull_z_, (), _Out_impl_ _Deref_post_opt_z_) +#define _Outptr_opt_result_maybenull_z_ \ + _SAL2_Source_(_Outptr_opt_result_maybenull_z_, (), _Out_opt_impl_ _Deref_post_opt_z_) -// Annotations for _Outptr_ parameters where the output pointer is set to NULL if the function fails. +// Annotations for _Outptr_ parameters where the output pointer is set to NULL if the function +// fails. -#define _Outptr_result_nullonfailure_ _SAL2_Source_(_Outptr_result_nullonfailure_, (), _Outptr_ _On_failure_(_Deref_post_null_)) -#define _Outptr_opt_result_nullonfailure_ _SAL2_Source_(_Outptr_opt_result_nullonfailure_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) +#define _Outptr_result_nullonfailure_ \ + _SAL2_Source_(_Outptr_result_nullonfailure_, (), _Outptr_ _On_failure_(_Deref_post_null_)) +#define _Outptr_opt_result_nullonfailure_ \ + _SAL2_Source_(_Outptr_opt_result_nullonfailure_, (), \ + _Outptr_opt_ _On_failure_(_Deref_post_null_)) // Annotations for _Outptr_ parameters which return a pointer to a ref-counted COM object, // following the COM convention of setting the output to NULL on failure. // The current implementation is identical to _Outptr_result_nullonfailure_. // For pointers to types that are not COM objects, _Outptr_result_nullonfailure_ is preferred. -#define _COM_Outptr_ _SAL2_Source_(_COM_Outptr_, (), _Outptr_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_result_maybenull_ _SAL2_Source_(_COM_Outptr_result_maybenull_, (), _Outptr_result_maybenull_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_opt_ _SAL2_Source_(_COM_Outptr_opt_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_opt_result_maybenull_ _SAL2_Source_(_COM_Outptr_opt_result_maybenull_, (), _Outptr_opt_result_maybenull_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_ _SAL2_Source_(_COM_Outptr_, (), _Outptr_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_result_maybenull_ \ + _SAL2_Source_(_COM_Outptr_result_maybenull_, (), \ + _Outptr_result_maybenull_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_opt_ \ + _SAL2_Source_(_COM_Outptr_opt_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_opt_result_maybenull_ \ + _SAL2_Source_(_COM_Outptr_opt_result_maybenull_, (), \ + _Outptr_opt_result_maybenull_ _On_failure_(_Deref_post_null_)) -// Annotations for _Outptr_ parameters returning a pointer to buffer with a specified number of elements/bytes +// Annotations for _Outptr_ parameters returning a pointer to buffer with a specified number of +// elements/bytes -#define _Outptr_result_buffer_(size) _SAL2_Source_(_Outptr_result_buffer_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) -#define _Outptr_opt_result_buffer_(size) _SAL2_Source_(_Outptr_opt_result_buffer_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) -#define _Outptr_result_buffer_to_(size, count) _SAL2_Source_(_Outptr_result_buffer_to_, (size, count), _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), __count_impl(count))) -#define _Outptr_opt_result_buffer_to_(size, count) _SAL2_Source_(_Outptr_opt_result_buffer_to_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), __count_impl(count))) +#define _Outptr_result_buffer_(size) \ + _SAL2_Source_(_Outptr_result_buffer_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) +#define _Outptr_opt_result_buffer_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) +#define _Outptr_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outptr_result_buffer_to_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), \ + __count_impl(count))) +#define _Outptr_opt_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_buffer_to_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), \ + __count_impl(count))) -#define _Outptr_result_buffer_all_(size) _SAL2_Source_(_Outptr_result_buffer_all_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) -#define _Outptr_opt_result_buffer_all_(size) _SAL2_Source_(_Outptr_opt_result_buffer_all_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) +#define _Outptr_result_buffer_all_(size) \ + _SAL2_Source_(_Outptr_result_buffer_all_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) +#define _Outptr_opt_result_buffer_all_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_all_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) -#define _Outptr_result_buffer_maybenull_(size) _SAL2_Source_(_Outptr_result_buffer_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) -#define _Outptr_opt_result_buffer_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_buffer_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) -#define _Outptr_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_result_buffer_to_maybenull_, (size, count), _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), __count_impl(count))) -#define _Outptr_opt_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_opt_result_buffer_to_maybenull_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), __count_impl(count))) +#define _Outptr_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_buffer_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) +#define _Outptr_opt_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) +#define _Outptr_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_result_buffer_to_maybenull_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), \ + __count_impl(count))) +#define _Outptr_opt_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_buffer_to_maybenull_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), \ + __count_impl(count))) -#define _Outptr_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outptr_result_buffer_all_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) -#define _Outptr_opt_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_buffer_all_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) +#define _Outptr_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_buffer_all_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) +#define _Outptr_opt_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_all_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) -#define _Outptr_result_bytebuffer_(size) _SAL2_Source_(_Outptr_result_bytebuffer_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) -#define _Outptr_opt_result_bytebuffer_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) -#define _Outptr_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outptr_result_bytebuffer_to_, (size, count), _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) -#define _Outptr_opt_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) +#define _Outptr_result_bytebuffer_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) +#define _Outptr_opt_result_bytebuffer_(size) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) +#define _Outptr_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outptr_result_bytebuffer_to_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) +#define _Outptr_opt_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) -#define _Outptr_result_bytebuffer_all_(size) _SAL2_Source_(_Outptr_result_bytebuffer_all_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) -#define _Outptr_opt_result_bytebuffer_all_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_all_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) +#define _Outptr_result_bytebuffer_all_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_all_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) +#define _Outptr_opt_result_bytebuffer_all_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_all_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) -#define _Outptr_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outptr_result_bytebuffer_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) -#define _Outptr_opt_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) -#define _Outptr_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_result_bytebuffer_to_maybenull_, (size, count), _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) -#define _Outptr_opt_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_maybenull_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) +#define _Outptr_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) +#define _Outptr_opt_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) +#define _Outptr_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_result_bytebuffer_to_maybenull_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) +#define _Outptr_opt_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_maybenull_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) -#define _Outptr_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outptr_result_bytebuffer_all_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) -#define _Outptr_opt_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_all_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) +#define _Outptr_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_all_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) +#define _Outptr_opt_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_all_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) // Annotations for output reference to pointer parameters. -#define _Outref_ _SAL2_Source_(_Outref_, (), _Out_impl_ _Post_notnull_) -#define _Outref_result_maybenull_ _SAL2_Source_(_Outref_result_maybenull_, (), _Pre2_impl_(__notnull_impl_notref, __cap_c_one_notref_impl) _Post_maybenull_ _Post_valid_impl_) +#define _Outref_ _SAL2_Source_(_Outref_, (), _Out_impl_ _Post_notnull_) +#define _Outref_result_maybenull_ \ + _SAL2_Source_(_Outref_result_maybenull_, (), \ + _Pre2_impl_(__notnull_impl_notref, __cap_c_one_notref_impl) \ + _Post_maybenull_ _Post_valid_impl_) -#define _Outref_result_buffer_(size) _SAL2_Source_(_Outref_result_buffer_, (size), _Outref_ _Post1_impl_(__cap_impl(size))) -#define _Outref_result_bytebuffer_(size) _SAL2_Source_(_Outref_result_bytebuffer_, (size), _Outref_ _Post1_impl_(__bytecap_impl(size))) -#define _Outref_result_buffer_to_(size, count) _SAL2_Source_(_Outref_result_buffer_to_, (size, count), _Outref_result_buffer_(size) _Post1_impl_(__count_impl(count))) -#define _Outref_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outref_result_bytebuffer_to_, (size, count), _Outref_result_bytebuffer_(size) _Post1_impl_(__bytecount_impl(count))) -#define _Outref_result_buffer_all_(size) _SAL2_Source_(_Outref_result_buffer_all_, (size), _Outref_result_buffer_to_(size, _Old_(size))) -#define _Outref_result_bytebuffer_all_(size) _SAL2_Source_(_Outref_result_bytebuffer_all_, (size), _Outref_result_bytebuffer_to_(size, _Old_(size))) +#define _Outref_result_buffer_(size) \ + _SAL2_Source_(_Outref_result_buffer_, (size), _Outref_ _Post1_impl_(__cap_impl(size))) +#define _Outref_result_bytebuffer_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_, (size), _Outref_ _Post1_impl_(__bytecap_impl(size))) +#define _Outref_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outref_result_buffer_to_, (size, count), \ + _Outref_result_buffer_(size) _Post1_impl_(__count_impl(count))) +#define _Outref_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outref_result_bytebuffer_to_, (size, count), \ + _Outref_result_bytebuffer_(size) _Post1_impl_(__bytecount_impl(count))) +#define _Outref_result_buffer_all_(size) \ + _SAL2_Source_(_Outref_result_buffer_all_, (size), _Outref_result_buffer_to_(size, _Old_(size))) +#define _Outref_result_bytebuffer_all_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_all_, (size), \ + _Outref_result_bytebuffer_to_(size, _Old_(size))) -#define _Outref_result_buffer_maybenull_(size) _SAL2_Source_(_Outref_result_buffer_maybenull_, (size), _Outref_result_maybenull_ _Post1_impl_(__cap_impl(size))) -#define _Outref_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outref_result_bytebuffer_maybenull_, (size), _Outref_result_maybenull_ _Post1_impl_(__bytecap_impl(size))) -#define _Outref_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outref_result_buffer_to_maybenull_, (size, count), _Outref_result_buffer_maybenull_(size) _Post1_impl_(__count_impl(count))) -#define _Outref_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outref_result_bytebuffer_to_maybenull_, (size, count), _Outref_result_bytebuffer_maybenull_(size) _Post1_impl_(__bytecount_impl(count))) -#define _Outref_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outref_result_buffer_all_maybenull_, (size), _Outref_result_buffer_to_maybenull_(size, _Old_(size))) -#define _Outref_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outref_result_bytebuffer_all_maybenull_, (size), _Outref_result_bytebuffer_to_maybenull_(size, _Old_(size))) +#define _Outref_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outref_result_buffer_maybenull_, (size), \ + _Outref_result_maybenull_ _Post1_impl_(__cap_impl(size))) +#define _Outref_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_maybenull_, (size), \ + _Outref_result_maybenull_ _Post1_impl_(__bytecap_impl(size))) +#define _Outref_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outref_result_buffer_to_maybenull_, (size, count), \ + _Outref_result_buffer_maybenull_(size) _Post1_impl_(__count_impl(count))) +#define _Outref_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outref_result_bytebuffer_to_maybenull_, (size, count), \ + _Outref_result_bytebuffer_maybenull_(size) \ + _Post1_impl_(__bytecount_impl(count))) +#define _Outref_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outref_result_buffer_all_maybenull_, (size), \ + _Outref_result_buffer_to_maybenull_(size, _Old_(size))) +#define _Outref_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_all_maybenull_, (size), \ + _Outref_result_bytebuffer_to_maybenull_(size, _Old_(size))) // Annotations for output reference to pointer parameters that guarantee // that the pointer is set to NULL on failure. -#define _Outref_result_nullonfailure_ _SAL2_Source_(_Outref_result_nullonfailure_, (), _Outref_ _On_failure_(_Post_null_)) - -// Generic annotations to set output value of a by-pointer or by-reference parameter to null/zero on failure. -#define _Result_nullonfailure_ _SAL2_Source_(_Result_nullonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Post_null_)) -#define _Result_zeroonfailure_ _SAL2_Source_(_Result_zeroonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Out_range_(==, 0))) +#define _Outref_result_nullonfailure_ \ + _SAL2_Source_(_Outref_result_nullonfailure_, (), _Outref_ _On_failure_(_Post_null_)) +// Generic annotations to set output value of a by-pointer or by-reference parameter to null/zero on +// failure. +#define _Result_nullonfailure_ \ + _SAL2_Source_(_Result_nullonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Post_null_)) +#define _Result_zeroonfailure_ \ + _SAL2_Source_(_Result_zeroonfailure_, (), \ + _On_failure_(_Notref_impl_ _Deref_impl_ _Out_range_(==, 0))) // return values ------------------------------- @@ -512,92 +699,146 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // describing conditions that hold for return values after the call // e.g. _Ret_z_ CString::operator const WCHAR*() const throw(); -#define _Ret_z_ _SAL2_Source_(_Ret_z_, (), _Ret2_impl_(__notnull_impl, __zterm_impl) _Ret_valid_impl_) -#define _Ret_maybenull_z_ _SAL2_Source_(_Ret_maybenull_z_, (), _Ret2_impl_(__maybenull_impl,__zterm_impl) _Ret_valid_impl_) +#define _Ret_z_ \ + _SAL2_Source_(_Ret_z_, (), _Ret2_impl_(__notnull_impl, __zterm_impl) _Ret_valid_impl_) +#define _Ret_maybenull_z_ \ + _SAL2_Source_(_Ret_maybenull_z_, (), \ + _Ret2_impl_(__maybenull_impl, __zterm_impl) _Ret_valid_impl_) // used with allocated but not yet initialized objects -#define _Ret_notnull_ _SAL2_Source_(_Ret_notnull_, (), _Ret1_impl_(__notnull_impl)) -#define _Ret_maybenull_ _SAL2_Source_(_Ret_maybenull_, (), _Ret1_impl_(__maybenull_impl)) -#define _Ret_null_ _SAL2_Source_(_Ret_null_, (), _Ret1_impl_(__null_impl)) +#define _Ret_notnull_ _SAL2_Source_(_Ret_notnull_, (), _Ret1_impl_(__notnull_impl)) +#define _Ret_maybenull_ _SAL2_Source_(_Ret_maybenull_, (), _Ret1_impl_(__maybenull_impl)) +#define _Ret_null_ _SAL2_Source_(_Ret_null_, (), _Ret1_impl_(__null_impl)) // used with allocated and initialized objects // returns single valid object -#define _Ret_valid_ _SAL2_Source_(_Ret_valid_, (), _Ret1_impl_(__notnull_impl_notref) _Ret_valid_impl_) +#define _Ret_valid_ \ + _SAL2_Source_(_Ret_valid_, (), _Ret1_impl_(__notnull_impl_notref) _Ret_valid_impl_) // returns pointer to initialized buffer of specified size -#define _Ret_writes_(size) _SAL2_Source_(_Ret_writes_, (size), _Ret2_impl_(__notnull_impl, __count_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_z_(size) _SAL2_Source_(_Ret_writes_z_, (size), _Ret3_impl_(__notnull_impl, __count_impl(size), __zterm_impl) _Ret_valid_impl_) -#define _Ret_writes_bytes_(size) _SAL2_Source_(_Ret_writes_bytes_, (size), _Ret2_impl_(__notnull_impl, __bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_maybenull_(size) _SAL2_Source_(_Ret_writes_maybenull_, (size), _Ret2_impl_(__maybenull_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_maybenull_z_(size) _SAL2_Source_(_Ret_writes_maybenull_z_, (size), _Ret3_impl_(__maybenull_impl,__count_impl(size),__zterm_impl) _Ret_valid_impl_) -#define _Ret_writes_bytes_maybenull_(size) _SAL2_Source_(_Ret_writes_bytes_maybenull_, (size), _Ret2_impl_(__maybenull_impl,__bytecount_impl(size)) _Ret_valid_impl_) - -// returns pointer to partially initialized buffer, with total size 'size' and initialized size 'count' -#define _Ret_writes_to_(size,count) _SAL2_Source_(_Ret_writes_to_, (size,count), _Ret3_impl_(__notnull_impl, __cap_impl(size), __count_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_bytes_to_(size,count) _SAL2_Source_(_Ret_writes_bytes_to_, (size,count), _Ret3_impl_(__notnull_impl, __bytecap_impl(size), __bytecount_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_to_maybenull_(size,count) _SAL2_Source_(_Ret_writes_to_maybenull_, (size,count), _Ret3_impl_(__maybenull_impl, __cap_impl(size), __count_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_bytes_to_maybenull_(size,count) _SAL2_Source_(_Ret_writes_bytes_to_maybenull_, (size,count), _Ret3_impl_(__maybenull_impl, __bytecap_impl(size), __bytecount_impl(count)) _Ret_valid_impl_) +#define _Ret_writes_(size) \ + _SAL2_Source_(_Ret_writes_, (size), \ + _Ret2_impl_(__notnull_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_z_(size) \ + _SAL2_Source_(_Ret_writes_z_, (size), \ + _Ret3_impl_(__notnull_impl, __count_impl(size), __zterm_impl) _Ret_valid_impl_) +#define _Ret_writes_bytes_(size) \ + _SAL2_Source_(_Ret_writes_bytes_, (size), \ + _Ret2_impl_(__notnull_impl, __bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_maybenull_(size) \ + _SAL2_Source_(_Ret_writes_maybenull_, (size), \ + _Ret2_impl_(__maybenull_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_maybenull_z_(size) \ + _SAL2_Source_(_Ret_writes_maybenull_z_, (size), \ + _Ret3_impl_(__maybenull_impl, __count_impl(size), __zterm_impl) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_maybenull_(size) \ + _SAL2_Source_(_Ret_writes_bytes_maybenull_, (size), \ + _Ret2_impl_(__maybenull_impl, __bytecount_impl(size)) _Ret_valid_impl_) +// returns pointer to partially initialized buffer, with total size 'size' and initialized size +// 'count' +#define _Ret_writes_to_(size, count) \ + _SAL2_Source_(_Ret_writes_to_, (size, count), \ + _Ret3_impl_(__notnull_impl, __cap_impl(size), __count_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_to_(size, count) \ + _SAL2_Source_(_Ret_writes_bytes_to_, (size, count), \ + _Ret3_impl_(__notnull_impl, __bytecap_impl(size), __bytecount_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_to_maybenull_(size, count) \ + _SAL2_Source_(_Ret_writes_to_maybenull_, (size, count), \ + _Ret3_impl_(__maybenull_impl, __cap_impl(size), __count_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_to_maybenull_(size, count) \ + _SAL2_Source_(_Ret_writes_bytes_to_maybenull_, (size, count), \ + _Ret3_impl_(__maybenull_impl, __bytecap_impl(size), __bytecount_impl(count)) \ + _Ret_valid_impl_) // Annotations for strict type checking -#define _Points_to_data_ _SAL2_Source_(_Points_to_data_, (), _Pre_ _Points_to_data_impl_) -#define _Literal_ _SAL2_Source_(_Literal_, (), _Pre_ _Literal_impl_) -#define _Notliteral_ _SAL2_Source_(_Notliteral_, (), _Pre_ _Notliteral_impl_) +#define _Points_to_data_ _SAL2_Source_(_Points_to_data_, (), _Pre_ _Points_to_data_impl_) +#define _Literal_ _SAL2_Source_(_Literal_, (), _Pre_ _Literal_impl_) +#define _Notliteral_ _SAL2_Source_(_Notliteral_, (), _Pre_ _Notliteral_impl_) // Check the return value of a function e.g. _Check_return_ ErrorCode Foo(); -#define _Check_return_ _SAL2_Source_(_Check_return_, (), _Check_return_impl_) -#define _Must_inspect_result_ _SAL2_Source_(_Must_inspect_result_, (), _Must_inspect_impl_ _Check_return_impl_) +#define _Check_return_ _SAL2_Source_(_Check_return_, (), _Check_return_impl_) +#define _Must_inspect_result_ \ + _SAL2_Source_(_Must_inspect_result_, (), _Must_inspect_impl_ _Check_return_impl_) // e.g. MyPrintF( _Printf_format_string_ const WCHAR* wzFormat, ... ); -#define _Printf_format_string_ _SAL2_Source_(_Printf_format_string_, (), _Printf_format_string_impl_) -#define _Scanf_format_string_ _SAL2_Source_(_Scanf_format_string_, (), _Scanf_format_string_impl_) -#define _Scanf_s_format_string_ _SAL2_Source_(_Scanf_s_format_string_, (), _Scanf_s_format_string_impl_) +#define _Printf_format_string_ \ + _SAL2_Source_(_Printf_format_string_, (), _Printf_format_string_impl_) +#define _Scanf_format_string_ _SAL2_Source_(_Scanf_format_string_, (), _Scanf_format_string_impl_) +#define _Scanf_s_format_string_ \ + _SAL2_Source_(_Scanf_s_format_string_, (), _Scanf_s_format_string_impl_) -#define _Format_string_impl_(kind,where) _SA_annotes2(SAL_IsFormatString2, kind, where) -#define _Printf_format_string_params_(x) _SAL2_Source_(_Printf_format_string_params_, (x), _Format_string_impl_("printf", x)) -#define _Scanf_format_string_params_(x) _SAL2_Source_(_Scanf_format_string_params_, (x), _Format_string_impl_("scanf", x)) -#define _Scanf_s_format_string_params_(x) _SAL2_Source_(_Scanf_s_format_string_params_, (x), _Format_string_impl_("scanf_s", x)) +#define _Format_string_impl_(kind, where) _SA_annotes2(SAL_IsFormatString2, kind, where) +#define _Printf_format_string_params_(x) \ + _SAL2_Source_(_Printf_format_string_params_, (x), _Format_string_impl_("printf", x)) +#define _Scanf_format_string_params_(x) \ + _SAL2_Source_(_Scanf_format_string_params_, (x), _Format_string_impl_("scanf", x)) +#define _Scanf_s_format_string_params_(x) \ + _SAL2_Source_(_Scanf_s_format_string_params_, (x), _Format_string_impl_("scanf_s", x)) // annotations to express value of integral or pointer parameter -#define _In_range_(lb,ub) _SAL2_Source_(_In_range_, (lb,ub), _In_range_impl_(lb,ub)) -#define _Out_range_(lb,ub) _SAL2_Source_(_Out_range_, (lb,ub), _Out_range_impl_(lb,ub)) -#define _Ret_range_(lb,ub) _SAL2_Source_(_Ret_range_, (lb,ub), _Ret_range_impl_(lb,ub)) -#define _Deref_in_range_(lb,ub) _SAL2_Source_(_Deref_in_range_, (lb,ub), _Deref_in_range_impl_(lb,ub)) -#define _Deref_out_range_(lb,ub) _SAL2_Source_(_Deref_out_range_, (lb,ub), _Deref_out_range_impl_(lb,ub)) -#define _Deref_ret_range_(lb,ub) _SAL2_Source_(_Deref_ret_range_, (lb,ub), _Deref_ret_range_impl_(lb,ub)) -#define _Pre_equal_to_(expr) _SAL2_Source_(_Pre_equal_to_, (expr), _In_range_(==, expr)) -#define _Post_equal_to_(expr) _SAL2_Source_(_Post_equal_to_, (expr), _Out_range_(==, expr)) +#define _In_range_(lb, ub) _SAL2_Source_(_In_range_, (lb, ub), _In_range_impl_(lb, ub)) +#define _Out_range_(lb, ub) _SAL2_Source_(_Out_range_, (lb, ub), _Out_range_impl_(lb, ub)) +#define _Ret_range_(lb, ub) _SAL2_Source_(_Ret_range_, (lb, ub), _Ret_range_impl_(lb, ub)) +#define _Deref_in_range_(lb, ub) \ + _SAL2_Source_(_Deref_in_range_, (lb, ub), _Deref_in_range_impl_(lb, ub)) +#define _Deref_out_range_(lb, ub) \ + _SAL2_Source_(_Deref_out_range_, (lb, ub), _Deref_out_range_impl_(lb, ub)) +#define _Deref_ret_range_(lb, ub) \ + _SAL2_Source_(_Deref_ret_range_, (lb, ub), _Deref_ret_range_impl_(lb, ub)) +#define _Pre_equal_to_(expr) _SAL2_Source_(_Pre_equal_to_, (expr), _In_range_(==, expr)) +#define _Post_equal_to_(expr) _SAL2_Source_(_Post_equal_to_, (expr), _Out_range_(==, expr)) // annotation to express that a value (usually a field of a mutable class) // is not changed by a function call -#define _Unchanged_(e) _SAL2_Source_(_Unchanged_, (e), _At_(e, _Post_equal_to_(_Old_(e)) _Const_)) +#define _Unchanged_(e) _SAL2_Source_(_Unchanged_, (e), _At_(e, _Post_equal_to_(_Old_(e)) _Const_)) // Annotations to allow expressing generalized pre and post conditions. // 'cond' may be any valid SAL expression that is considered to be true as a precondition // or postcondition (respsectively). -#define _Pre_satisfies_(cond) _SAL2_Source_(_Pre_satisfies_, (cond), _Pre_satisfies_impl_(cond)) -#define _Post_satisfies_(cond) _SAL2_Source_(_Post_satisfies_, (cond), _Post_satisfies_impl_(cond)) +#define _Pre_satisfies_(cond) _SAL2_Source_(_Pre_satisfies_, (cond), _Pre_satisfies_impl_(cond)) +#define _Post_satisfies_(cond) _SAL2_Source_(_Post_satisfies_, (cond), _Post_satisfies_impl_(cond)) // Annotations to express struct, class and field invariants -#define _Struct_size_bytes_(size) _SAL2_Source_(_Struct_size_bytes_, (size), _Writable_bytes_(size)) +#define _Struct_size_bytes_(size) _SAL2_Source_(_Struct_size_bytes_, (size), _Writable_bytes_(size)) -#define _Field_size_(size) _SAL2_Source_(_Field_size_, (size), _Notnull_ _Writable_elements_(size)) -#define _Field_size_opt_(size) _SAL2_Source_(_Field_size_opt_, (size), _Maybenull_ _Writable_elements_(size)) -#define _Field_size_part_(size, count) _SAL2_Source_(_Field_size_part_, (size, count), _Notnull_ _Writable_elements_(size) _Readable_elements_(count)) -#define _Field_size_part_opt_(size, count) _SAL2_Source_(_Field_size_part_opt_, (size, count), _Maybenull_ _Writable_elements_(size) _Readable_elements_(count)) -#define _Field_size_full_(size) _SAL2_Source_(_Field_size_full_, (size), _Field_size_part_(size, size)) -#define _Field_size_full_opt_(size) _SAL2_Source_(_Field_size_full_opt_, (size), _Field_size_part_opt_(size, size)) +#define _Field_size_(size) _SAL2_Source_(_Field_size_, (size), _Notnull_ _Writable_elements_(size)) +#define _Field_size_opt_(size) \ + _SAL2_Source_(_Field_size_opt_, (size), _Maybenull_ _Writable_elements_(size)) +#define _Field_size_part_(size, count) \ + _SAL2_Source_(_Field_size_part_, (size, count), \ + _Notnull_ _Writable_elements_(size) _Readable_elements_(count)) +#define _Field_size_part_opt_(size, count) \ + _SAL2_Source_(_Field_size_part_opt_, (size, count), \ + _Maybenull_ _Writable_elements_(size) _Readable_elements_(count)) +#define _Field_size_full_(size) \ + _SAL2_Source_(_Field_size_full_, (size), _Field_size_part_(size, size)) +#define _Field_size_full_opt_(size) \ + _SAL2_Source_(_Field_size_full_opt_, (size), _Field_size_part_opt_(size, size)) -#define _Field_size_bytes_(size) _SAL2_Source_(_Field_size_bytes_, (size), _Notnull_ _Writable_bytes_(size)) -#define _Field_size_bytes_opt_(size) _SAL2_Source_(_Field_size_bytes_opt_, (size), _Maybenull_ _Writable_bytes_(size)) -#define _Field_size_bytes_part_(size, count) _SAL2_Source_(_Field_size_bytes_part_, (size, count), _Notnull_ _Writable_bytes_(size) _Readable_bytes_(count)) -#define _Field_size_bytes_part_opt_(size, count) _SAL2_Source_(_Field_size_bytes_part_opt_, (size, count), _Maybenull_ _Writable_bytes_(size) _Readable_bytes_(count)) -#define _Field_size_bytes_full_(size) _SAL2_Source_(_Field_size_bytes_full_, (size), _Field_size_bytes_part_(size, size)) -#define _Field_size_bytes_full_opt_(size) _SAL2_Source_(_Field_size_bytes_full_opt_, (size), _Field_size_bytes_part_opt_(size, size)) +#define _Field_size_bytes_(size) \ + _SAL2_Source_(_Field_size_bytes_, (size), _Notnull_ _Writable_bytes_(size)) +#define _Field_size_bytes_opt_(size) \ + _SAL2_Source_(_Field_size_bytes_opt_, (size), _Maybenull_ _Writable_bytes_(size)) +#define _Field_size_bytes_part_(size, count) \ + _SAL2_Source_(_Field_size_bytes_part_, (size, count), \ + _Notnull_ _Writable_bytes_(size) _Readable_bytes_(count)) +#define _Field_size_bytes_part_opt_(size, count) \ + _SAL2_Source_(_Field_size_bytes_part_opt_, (size, count), \ + _Maybenull_ _Writable_bytes_(size) _Readable_bytes_(count)) +#define _Field_size_bytes_full_(size) \ + _SAL2_Source_(_Field_size_bytes_full_, (size), _Field_size_bytes_part_(size, size)) +#define _Field_size_bytes_full_opt_(size) \ + _SAL2_Source_(_Field_size_bytes_full_opt_, (size), _Field_size_bytes_part_opt_(size, size)) -#define _Field_z_ _SAL2_Source_(_Field_z_, (), _Null_terminated_) +#define _Field_z_ _SAL2_Source_(_Field_z_, (), _Null_terminated_) -#define _Field_range_(min,max) _SAL2_Source_(_Field_range_, (min,max), _Field_range_impl_(min,max)) +#define _Field_range_(min, max) \ + _SAL2_Source_(_Field_range_, (min, max), _Field_range_impl_(min, max)) //============================================================================ // _Pre_\_Post_ Layer: @@ -607,47 +848,59 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // Raw Pre/Post for declaring custom pre/post conditions // -#define _Pre_ _Pre_impl_ -#define _Post_ _Post_impl_ +#define _Pre_ _Pre_impl_ +#define _Post_ _Post_impl_ // // Validity property // -#define _Valid_ _Valid_impl_ -#define _Notvalid_ _Notvalid_impl_ -#define _Maybevalid_ _Maybevalid_impl_ +#define _Valid_ _Valid_impl_ +#define _Notvalid_ _Notvalid_impl_ +#define _Maybevalid_ _Maybevalid_impl_ // // Buffer size properties // // Expressing buffer sizes without specifying pre or post condition -#define _Readable_bytes_(size) _SAL2_Source_(_Readable_bytes_, (size), _Readable_bytes_impl_(size)) -#define _Readable_elements_(size) _SAL2_Source_(_Readable_elements_, (size), _Readable_elements_impl_(size)) -#define _Writable_bytes_(size) _SAL2_Source_(_Writable_bytes_, (size), _Writable_bytes_impl_(size)) -#define _Writable_elements_(size) _SAL2_Source_(_Writable_elements_, (size), _Writable_elements_impl_(size)) +#define _Readable_bytes_(size) _SAL2_Source_(_Readable_bytes_, (size), _Readable_bytes_impl_(size)) +#define _Readable_elements_(size) \ + _SAL2_Source_(_Readable_elements_, (size), _Readable_elements_impl_(size)) +#define _Writable_bytes_(size) _SAL2_Source_(_Writable_bytes_, (size), _Writable_bytes_impl_(size)) +#define _Writable_elements_(size) \ + _SAL2_Source_(_Writable_elements_, (size), _Writable_elements_impl_(size)) -#define _Null_terminated_ _SAL2_Source_(_Null_terminated_, (), _Null_terminated_impl_) -#define _NullNull_terminated_ _SAL2_Source_(_NullNull_terminated_, (), _NullNull_terminated_impl_) +#define _Null_terminated_ _SAL2_Source_(_Null_terminated_, (), _Null_terminated_impl_) +#define _NullNull_terminated_ _SAL2_Source_(_NullNull_terminated_, (), _NullNull_terminated_impl_) // Expressing buffer size as pre or post condition -#define _Pre_readable_size_(size) _SAL2_Source_(_Pre_readable_size_, (size), _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_writable_size_(size) _SAL2_Source_(_Pre_writable_size_, (size), _Pre1_impl_(__cap_impl(size))) -#define _Pre_readable_byte_size_(size) _SAL2_Source_(_Pre_readable_byte_size_, (size), _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Pre_writable_byte_size_(size) _SAL2_Source_(_Pre_writable_byte_size_, (size), _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_readable_size_(size) \ + _SAL2_Source_(_Pre_readable_size_, (size), _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) +#define _Pre_writable_size_(size) \ + _SAL2_Source_(_Pre_writable_size_, (size), _Pre1_impl_(__cap_impl(size))) +#define _Pre_readable_byte_size_(size) \ + _SAL2_Source_(_Pre_readable_byte_size_, (size), \ + _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Pre_writable_byte_size_(size) \ + _SAL2_Source_(_Pre_writable_byte_size_, (size), _Pre1_impl_(__bytecap_impl(size))) -#define _Post_readable_size_(size) _SAL2_Source_(_Post_readable_size_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Post_writable_size_(size) _SAL2_Source_(_Post_writable_size_, (size), _Post1_impl_(__cap_impl(size))) -#define _Post_readable_byte_size_(size) _SAL2_Source_(_Post_readable_byte_size_, (size), _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_writable_byte_size_(size) _SAL2_Source_(_Post_writable_byte_size_, (size), _Post1_impl_(__bytecap_impl(size))) +#define _Post_readable_size_(size) \ + _SAL2_Source_(_Post_readable_size_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Post_writable_size_(size) \ + _SAL2_Source_(_Post_writable_size_, (size), _Post1_impl_(__cap_impl(size))) +#define _Post_readable_byte_size_(size) \ + _SAL2_Source_(_Post_readable_byte_size_, (size), \ + _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Post_writable_byte_size_(size) \ + _SAL2_Source_(_Post_writable_byte_size_, (size), _Post1_impl_(__bytecap_impl(size))) // // Pointer null-ness properties // -#define _Null_ _Null_impl_ -#define _Notnull_ _Notnull_impl_ -#define _Maybenull_ _Maybenull_impl_ +#define _Null_ _Null_impl_ +#define _Notnull_ _Notnull_impl_ +#define _Maybenull_ _Maybenull_impl_ // // _Pre_ annotations --- @@ -656,21 +909,23 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // e.g. int strlen( _Pre_z_ const char* sz ); // buffer is a zero terminated string -#define _Pre_z_ _SAL2_Source_(_Pre_z_, (), _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Pre_z_ _SAL2_Source_(_Pre_z_, (), _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) // valid size unknown or indicated by type (e.g.:LPSTR) -#define _Pre_valid_ _SAL2_Source_(_Pre_valid_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) -#define _Pre_opt_valid_ _SAL2_Source_(_Pre_opt_valid_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) +#define _Pre_valid_ \ + _SAL2_Source_(_Pre_valid_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) +#define _Pre_opt_valid_ \ + _SAL2_Source_(_Pre_opt_valid_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) -#define _Pre_invalid_ _SAL2_Source_(_Pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) +#define _Pre_invalid_ _SAL2_Source_(_Pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) // Overrides recursive valid when some field is not yet initialized when using _Inout_ -#define _Pre_unknown_ _SAL2_Source_(_Pre_unknown_, (), _Pre1_impl_(__maybevalid_impl)) +#define _Pre_unknown_ _SAL2_Source_(_Pre_unknown_, (), _Pre1_impl_(__maybevalid_impl)) // used with allocated but not yet initialized objects -#define _Pre_notnull_ _SAL2_Source_(_Pre_notnull_, (), _Pre1_impl_(__notnull_impl_notref)) -#define _Pre_maybenull_ _SAL2_Source_(_Pre_maybenull_, (), _Pre1_impl_(__maybenull_impl_notref)) -#define _Pre_null_ _SAL2_Source_(_Pre_null_, (), _Pre1_impl_(__null_impl_notref)) +#define _Pre_notnull_ _SAL2_Source_(_Pre_notnull_, (), _Pre1_impl_(__notnull_impl_notref)) +#define _Pre_maybenull_ _SAL2_Source_(_Pre_maybenull_, (), _Pre1_impl_(__maybenull_impl_notref)) +#define _Pre_null_ _SAL2_Source_(_Pre_null_, (), _Pre1_impl_(__null_impl_notref)) // // _Post_ annotations --- @@ -679,25 +934,24 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // void CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_ char* szFrom, size_t cchFrom ); // buffer will be a zero-terminated string after the call -#define _Post_z_ _SAL2_Source_(_Post_z_, (), _Post1_impl_(__zterm_impl) _Post_valid_impl_) +#define _Post_z_ _SAL2_Source_(_Post_z_, (), _Post1_impl_(__zterm_impl) _Post_valid_impl_) // e.g. HRESULT InitStruct( _Post_valid_ Struct* pobj ); -#define _Post_valid_ _SAL2_Source_(_Post_valid_, (), _Post_valid_impl_) -#define _Post_invalid_ _SAL2_Source_(_Post_invalid_, (), _Deref_post1_impl_(__notvalid_impl)) +#define _Post_valid_ _SAL2_Source_(_Post_valid_, (), _Post_valid_impl_) +#define _Post_invalid_ _SAL2_Source_(_Post_invalid_, (), _Deref_post1_impl_(__notvalid_impl)) // e.g. void free( _Post_ptr_invalid_ void* pv ); -#define _Post_ptr_invalid_ _SAL2_Source_(_Post_ptr_invalid_, (), _Post1_impl_(__notvalid_impl)) +#define _Post_ptr_invalid_ _SAL2_Source_(_Post_ptr_invalid_, (), _Post1_impl_(__notvalid_impl)) // e.g. void ThrowExceptionIfNull( _Post_notnull_ const void* pv ); -#define _Post_notnull_ _SAL2_Source_(_Post_notnull_, (), _Post1_impl_(__notnull_impl)) +#define _Post_notnull_ _SAL2_Source_(_Post_notnull_, (), _Post1_impl_(__notnull_impl)) // e.g. HRESULT GetObject(_Outptr_ _On_failure_(_At_(*p, _Post_null_)) T **p); -#define _Post_null_ _SAL2_Source_(_Post_null_, (), _Post1_impl_(__null_impl)) +#define _Post_null_ _SAL2_Source_(_Post_null_, (), _Post1_impl_(__null_impl)) -#define _Post_maybenull_ _SAL2_Source_(_Post_maybenull_, (), _Post1_impl_(__maybenull_impl)) - -#define _Prepost_z_ _SAL2_Source_(_Prepost_z_, (), _Pre_z_ _Post_z_) +#define _Post_maybenull_ _SAL2_Source_(_Post_maybenull_, (), _Post1_impl_(__maybenull_impl)) +#define _Prepost_z_ _SAL2_Source_(_Prepost_z_, (), _Pre_z_ _Post_z_) // #pragma region Input Buffer SAL 1 compatibility macros @@ -798,679 +1052,1483 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // e.g. void SetCharRange( _In_count_(cch) const char* rgch, size_t cch ) // valid buffer extent described by another parameter -#define _In_count_(size) _SAL1_1_Source_(_In_count_, (size), _Pre_count_(size) _Deref_pre_readonly_) -#define _In_opt_count_(size) _SAL1_1_Source_(_In_opt_count_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_bytecount_(size) _SAL1_1_Source_(_In_bytecount_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_(size) _SAL1_1_Source_(_In_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_count_(size) _SAL1_1_Source_(_In_count_, (size), _Pre_count_(size) _Deref_pre_readonly_) +#define _In_opt_count_(size) \ + _SAL1_1_Source_(_In_opt_count_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_bytecount_(size) \ + _SAL1_1_Source_(_In_bytecount_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) // valid buffer extent described by a constant extression -#define _In_count_c_(size) _SAL1_1_Source_(_In_count_c_, (size), _Pre_count_c_(size) _Deref_pre_readonly_) -#define _In_opt_count_c_(size) _SAL1_1_Source_(_In_opt_count_c_, (size), _Pre_opt_count_c_(size) _Deref_pre_readonly_) -#define _In_bytecount_c_(size) _SAL1_1_Source_(_In_bytecount_c_, (size), _Pre_bytecount_c_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_c_(size) _SAL1_1_Source_(_In_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_count_c_(size) \ + _SAL1_1_Source_(_In_count_c_, (size), _Pre_count_c_(size) _Deref_pre_readonly_) +#define _In_opt_count_c_(size) \ + _SAL1_1_Source_(_In_opt_count_c_, (size), _Pre_opt_count_c_(size) _Deref_pre_readonly_) +#define _In_bytecount_c_(size) \ + _SAL1_1_Source_(_In_bytecount_c_, (size), _Pre_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) // nullterminated 'input' buffers with given size // e.g. void SetCharRange( _In_count_(cch) const char* rgch, size_t cch ) // nullterminated valid buffer extent described by another parameter -#define _In_z_count_(size) _SAL1_1_Source_(_In_z_count_, (size), _Pre_z_ _Pre_count_(size) _Deref_pre_readonly_) -#define _In_opt_z_count_(size) _SAL1_1_Source_(_In_opt_z_count_, (size), _Pre_opt_z_ _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_z_bytecount_(size) _SAL1_1_Source_(_In_z_bytecount_, (size), _Pre_z_ _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_opt_z_bytecount_(size) _SAL1_1_Source_(_In_opt_z_bytecount_, (size), _Pre_opt_z_ _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_z_count_(size) \ + _SAL1_1_Source_(_In_z_count_, (size), _Pre_z_ _Pre_count_(size) _Deref_pre_readonly_) +#define _In_opt_z_count_(size) \ + _SAL1_1_Source_(_In_opt_z_count_, (size), \ + _Pre_opt_z_ _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_z_bytecount_(size) \ + _SAL1_1_Source_(_In_z_bytecount_, (size), _Pre_z_ _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_In_opt_z_bytecount_, (size), \ + _Pre_opt_z_ _Pre_opt_bytecount_(size) _Deref_pre_readonly_) // nullterminated valid buffer extent described by a constant extression -#define _In_z_count_c_(size) _SAL1_1_Source_(_In_z_count_c_, (size), _Pre_z_ _Pre_count_c_(size) _Deref_pre_readonly_) -#define _In_opt_z_count_c_(size) _SAL1_1_Source_(_In_opt_z_count_c_, (size), _Pre_opt_z_ _Pre_opt_count_c_(size) _Deref_pre_readonly_) -#define _In_z_bytecount_c_(size) _SAL1_1_Source_(_In_z_bytecount_c_, (size), _Pre_z_ _Pre_bytecount_c_(size) _Deref_pre_readonly_) -#define _In_opt_z_bytecount_c_(size) _SAL1_1_Source_(_In_opt_z_bytecount_c_, (size), _Pre_opt_z_ _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_z_count_c_(size) \ + _SAL1_1_Source_(_In_z_count_c_, (size), _Pre_z_ _Pre_count_c_(size) _Deref_pre_readonly_) +#define _In_opt_z_count_c_(size) \ + _SAL1_1_Source_(_In_opt_z_count_c_, (size), \ + _Pre_opt_z_ _Pre_opt_count_c_(size) _Deref_pre_readonly_) +#define _In_z_bytecount_c_(size) \ + _SAL1_1_Source_(_In_z_bytecount_c_, (size), \ + _Pre_z_ _Pre_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_opt_z_bytecount_c_(size) \ + _SAL1_1_Source_(_In_opt_z_bytecount_c_, (size), \ + _Pre_opt_z_ _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) // buffer capacity is described by another pointer -// e.g. void Foo( _In_ptrdiff_count_(pchMax) const char* pch, const char* pchMax ) { while pch < pchMax ) pch++; } -#define _In_ptrdiff_count_(size) _SAL1_1_Source_(_In_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size) _Deref_pre_readonly_) -#define _In_opt_ptrdiff_count_(size) _SAL1_1_Source_(_In_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size) _Deref_pre_readonly_) +// e.g. void Foo( _In_ptrdiff_count_(pchMax) const char* pch, const char* pchMax ) { while pch < +// pchMax ) pch++; } +#define _In_ptrdiff_count_(size) \ + _SAL1_1_Source_(_In_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size) _Deref_pre_readonly_) +#define _In_opt_ptrdiff_count_(size) \ + _SAL1_1_Source_(_In_opt_ptrdiff_count_, (size), \ + _Pre_opt_ptrdiff_count_(size) _Deref_pre_readonly_) // 'x' version for complex expressions that are not supported by the current compiler version // e.g. void Set3ColMatrix( _In_count_x_(3*cRows) const Elem* matrix, int cRows ); -#define _In_count_x_(size) _SAL1_1_Source_(_In_count_x_, (size), _Pre_count_x_(size) _Deref_pre_readonly_) -#define _In_opt_count_x_(size) _SAL1_1_Source_(_In_opt_count_x_, (size), _Pre_opt_count_x_(size) _Deref_pre_readonly_) -#define _In_bytecount_x_(size) _SAL1_1_Source_(_In_bytecount_x_, (size), _Pre_bytecount_x_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_x_(size) _SAL1_1_Source_(_In_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Deref_pre_readonly_) - +#define _In_count_x_(size) \ + _SAL1_1_Source_(_In_count_x_, (size), _Pre_count_x_(size) _Deref_pre_readonly_) +#define _In_opt_count_x_(size) \ + _SAL1_1_Source_(_In_opt_count_x_, (size), _Pre_opt_count_x_(size) _Deref_pre_readonly_) +#define _In_bytecount_x_(size) \ + _SAL1_1_Source_(_In_bytecount_x_, (size), _Pre_bytecount_x_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Deref_pre_readonly_) // 'out' with buffer size // e.g. void GetIndices( _Out_cap_(cIndices) int* rgIndices, size_t cIndices ); // buffer capacity is described by another parameter -#define _Out_cap_(size) _SAL1_1_Source_(_Out_cap_, (size), _Pre_cap_(size) _Post_valid_impl_) -#define _Out_opt_cap_(size) _SAL1_1_Source_(_Out_opt_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) -#define _Out_bytecap_(size) _SAL1_1_Source_(_Out_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_(size) _SAL1_1_Source_(_Out_opt_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) +#define _Out_cap_(size) _SAL1_1_Source_(_Out_cap_, (size), _Pre_cap_(size) _Post_valid_impl_) +#define _Out_opt_cap_(size) \ + _SAL1_1_Source_(_Out_opt_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) +#define _Out_bytecap_(size) \ + _SAL1_1_Source_(_Out_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) // buffer capacity is described by a constant expression -#define _Out_cap_c_(size) _SAL1_1_Source_(_Out_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_) -#define _Out_opt_cap_c_(size) _SAL1_1_Source_(_Out_opt_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_) -#define _Out_bytecap_c_(size) _SAL1_1_Source_(_Out_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_c_(size) _SAL1_1_Source_(_Out_opt_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_) +#define _Out_cap_c_(size) _SAL1_1_Source_(_Out_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_) +#define _Out_opt_cap_c_(size) \ + _SAL1_1_Source_(_Out_opt_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_) +#define _Out_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_) // buffer capacity is described by another parameter multiplied by a constant expression -#define _Out_cap_m_(mult,size) _SAL1_1_Source_(_Out_cap_m_, (mult,size), _Pre_cap_m_(mult,size) _Post_valid_impl_) -#define _Out_opt_cap_m_(mult,size) _SAL1_1_Source_(_Out_opt_cap_m_, (mult,size), _Pre_opt_cap_m_(mult,size) _Post_valid_impl_) -#define _Out_z_cap_m_(mult,size) _SAL1_1_Source_(_Out_z_cap_m_, (mult,size), _Pre_cap_m_(mult,size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_m_(mult,size) _SAL1_1_Source_(_Out_opt_z_cap_m_, (mult,size), _Pre_opt_cap_m_(mult,size) _Post_valid_impl_ _Post_z_) +#define _Out_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_cap_m_, (mult, size), _Pre_cap_m_(mult, size) _Post_valid_impl_) +#define _Out_opt_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_opt_cap_m_, (mult, size), _Pre_opt_cap_m_(mult, size) _Post_valid_impl_) +#define _Out_z_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_z_cap_m_, (mult, size), _Pre_cap_m_(mult, size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_opt_z_cap_m_, (mult, size), \ + _Pre_opt_cap_m_(mult, size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by another pointer -// e.g. void Foo( _Out_ptrdiff_cap_(pchMax) char* pch, const char* pchMax ) { while pch < pchMax ) pch++; } -#define _Out_ptrdiff_cap_(size) _SAL1_1_Source_(_Out_ptrdiff_cap_, (size), _Pre_ptrdiff_cap_(size) _Post_valid_impl_) -#define _Out_opt_ptrdiff_cap_(size) _SAL1_1_Source_(_Out_opt_ptrdiff_cap_, (size), _Pre_opt_ptrdiff_cap_(size) _Post_valid_impl_) +// e.g. void Foo( _Out_ptrdiff_cap_(pchMax) char* pch, const char* pchMax ) { while pch < pchMax ) +// pch++; } +#define _Out_ptrdiff_cap_(size) \ + _SAL1_1_Source_(_Out_ptrdiff_cap_, (size), _Pre_ptrdiff_cap_(size) _Post_valid_impl_) +#define _Out_opt_ptrdiff_cap_(size) \ + _SAL1_1_Source_(_Out_opt_ptrdiff_cap_, (size), _Pre_opt_ptrdiff_cap_(size) _Post_valid_impl_) // buffer capacity is described by a complex expression -#define _Out_cap_x_(size) _SAL1_1_Source_(_Out_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_) -#define _Out_opt_cap_x_(size) _SAL1_1_Source_(_Out_opt_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_) -#define _Out_bytecap_x_(size) _SAL1_1_Source_(_Out_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_x_(size) _SAL1_1_Source_(_Out_opt_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_) +#define _Out_cap_x_(size) _SAL1_1_Source_(_Out_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_) +#define _Out_opt_cap_x_(size) \ + _SAL1_1_Source_(_Out_opt_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_) +#define _Out_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_) // a zero terminated string is filled into a buffer of given capacity // e.g. void CopyStr( _In_z_ const char* szFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); // buffer capacity is described by another parameter -#define _Out_z_cap_(size) _SAL1_1_Source_(_Out_z_cap_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_(size) _SAL1_1_Source_(_Out_opt_z_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_(size) _SAL1_1_Source_(_Out_z_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_(size) \ + _SAL1_1_Source_(_Out_z_cap_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by a constant expression -#define _Out_z_cap_c_(size) _SAL1_1_Source_(_Out_z_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_c_(size) _SAL1_1_Source_(_Out_opt_z_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_c_(size) _SAL1_1_Source_(_Out_z_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_c_(size) \ + _SAL1_1_Source_(_Out_z_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_c_, (size), \ + _Pre_opt_bytecap_c_(size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by a complex expression -#define _Out_z_cap_x_(size) _SAL1_1_Source_(_Out_z_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_x_(size) _SAL1_1_Source_(_Out_opt_z_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_x_(size) _SAL1_1_Source_(_Out_z_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_x_(size) \ + _SAL1_1_Source_(_Out_z_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_x_, (size), \ + _Pre_opt_bytecap_x_(size) _Post_valid_impl_ _Post_z_) // a zero terminated string is filled into a buffer of given capacity -// e.g. size_t CopyCharRange( _In_count_(cchFrom) const char* rgchFrom, size_t cchFrom, _Out_cap_post_count_(cchTo,return)) char* rgchTo, size_t cchTo ); -#define _Out_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_cap_post_count_, (cap,count), _Pre_cap_(cap) _Post_valid_impl_ _Post_count_(count)) -#define _Out_opt_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_opt_cap_post_count_, (cap,count), _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_count_(count)) -#define _Out_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_bytecap_post_bytecount_, (cap,count), _Pre_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_opt_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_opt_bytecap_post_bytecount_, (cap,count), _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) +// e.g. size_t CopyCharRange( _In_count_(cchFrom) const char* rgchFrom, size_t cchFrom, +// _Out_cap_post_count_(cchTo,return)) char* rgchTo, size_t cchTo ); +#define _Out_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_cap_post_count_, (cap, count), \ + _Pre_cap_(cap) _Post_valid_impl_ _Post_count_(count)) +#define _Out_opt_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_opt_cap_post_count_, (cap, count), \ + _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_count_(count)) +#define _Out_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_bytecap_post_bytecount_, (cap, count), \ + _Pre_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_opt_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_opt_bytecap_post_bytecount_, (cap, count), \ + _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) // a zero terminated string is filled into a buffer of given capacity -// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Out_z_cap_post_count_(cchTo,return+1) char* szTo, size_t cchTo ); -#define _Out_z_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_z_cap_post_count_, (cap,count), _Pre_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) -#define _Out_opt_z_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_opt_z_cap_post_count_, (cap,count), _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) -#define _Out_z_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_z_bytecap_post_bytecount_, (cap,count), _Pre_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) -#define _Out_opt_z_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_opt_z_bytecap_post_bytecount_, (cap,count), _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) +// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Out_z_cap_post_count_(cchTo,return+1) char* +// szTo, size_t cchTo ); +#define _Out_z_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_z_cap_post_count_, (cap, count), \ + _Pre_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) +#define _Out_opt_z_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_opt_z_cap_post_count_, (cap, count), \ + _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) +#define _Out_z_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_z_bytecap_post_bytecount_, (cap, count), \ + _Pre_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) +#define _Out_opt_z_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_post_bytecount_, (cap, count), \ + _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) // only use with dereferenced arguments e.g. '*pcch' -#define _Out_capcount_(capcount) _SAL1_1_Source_(_Out_capcount_, (capcount), _Pre_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) -#define _Out_opt_capcount_(capcount) _SAL1_1_Source_(_Out_opt_capcount_, (capcount), _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) -#define _Out_bytecapcount_(capcount) _SAL1_1_Source_(_Out_bytecapcount_, (capcount), _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) -#define _Out_opt_bytecapcount_(capcount) _SAL1_1_Source_(_Out_opt_bytecapcount_, (capcount), _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) +#define _Out_capcount_(capcount) \ + _SAL1_1_Source_(_Out_capcount_, (capcount), \ + _Pre_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) +#define _Out_opt_capcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_capcount_, (capcount), \ + _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) +#define _Out_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_bytecapcount_, (capcount), \ + _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) +#define _Out_opt_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_bytecapcount_, (capcount), \ + _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) -#define _Out_capcount_x_(capcount) _SAL1_1_Source_(_Out_capcount_x_, (capcount), _Pre_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) -#define _Out_opt_capcount_x_(capcount) _SAL1_1_Source_(_Out_opt_capcount_x_, (capcount), _Pre_opt_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) -#define _Out_bytecapcount_x_(capcount) _SAL1_1_Source_(_Out_bytecapcount_x_, (capcount), _Pre_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) -#define _Out_opt_bytecapcount_x_(capcount) _SAL1_1_Source_(_Out_opt_bytecapcount_x_, (capcount), _Pre_opt_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) +#define _Out_capcount_x_(capcount) \ + _SAL1_1_Source_(_Out_capcount_x_, (capcount), \ + _Pre_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) +#define _Out_opt_capcount_x_(capcount) \ + _SAL1_1_Source_(_Out_opt_capcount_x_, (capcount), \ + _Pre_opt_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) +#define _Out_bytecapcount_x_(capcount) \ + _SAL1_1_Source_(_Out_bytecapcount_x_, (capcount), \ + _Pre_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) +#define _Out_opt_bytecapcount_x_(capcount) \ + _SAL1_1_Source_(_Out_opt_bytecapcount_x_, (capcount), \ + _Pre_opt_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) // e.g. GetString( _Out_z_capcount_(*pLen+1) char* sz, size_t* pLen ); -#define _Out_z_capcount_(capcount) _SAL1_1_Source_(_Out_z_capcount_, (capcount), _Pre_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) -#define _Out_opt_z_capcount_(capcount) _SAL1_1_Source_(_Out_opt_z_capcount_, (capcount), _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) -#define _Out_z_bytecapcount_(capcount) _SAL1_1_Source_(_Out_z_bytecapcount_, (capcount), _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) -#define _Out_opt_z_bytecapcount_(capcount) _SAL1_1_Source_(_Out_opt_z_bytecapcount_, (capcount), _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) - +#define _Out_z_capcount_(capcount) \ + _SAL1_1_Source_(_Out_z_capcount_, (capcount), \ + _Pre_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) +#define _Out_opt_z_capcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_z_capcount_, (capcount), \ + _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) +#define _Out_z_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_z_bytecapcount_, (capcount), \ + _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) +#define _Out_opt_z_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_z_bytecapcount_, (capcount), \ + _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) // 'inout' buffers with initialized elements before and after the call // e.g. void ModifyIndices( _Inout_count_(cIndices) int* rgIndices, size_t cIndices ); -#define _Inout_count_(size) _SAL1_1_Source_(_Inout_count_, (size), _Prepost_count_(size)) -#define _Inout_opt_count_(size) _SAL1_1_Source_(_Inout_opt_count_, (size), _Prepost_opt_count_(size)) -#define _Inout_bytecount_(size) _SAL1_1_Source_(_Inout_bytecount_, (size), _Prepost_bytecount_(size)) -#define _Inout_opt_bytecount_(size) _SAL1_1_Source_(_Inout_opt_bytecount_, (size), _Prepost_opt_bytecount_(size)) +#define _Inout_count_(size) _SAL1_1_Source_(_Inout_count_, (size), _Prepost_count_(size)) +#define _Inout_opt_count_(size) \ + _SAL1_1_Source_(_Inout_opt_count_, (size), _Prepost_opt_count_(size)) +#define _Inout_bytecount_(size) \ + _SAL1_1_Source_(_Inout_bytecount_, (size), _Prepost_bytecount_(size)) +#define _Inout_opt_bytecount_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_, (size), _Prepost_opt_bytecount_(size)) -#define _Inout_count_c_(size) _SAL1_1_Source_(_Inout_count_c_, (size), _Prepost_count_c_(size)) -#define _Inout_opt_count_c_(size) _SAL1_1_Source_(_Inout_opt_count_c_, (size), _Prepost_opt_count_c_(size)) -#define _Inout_bytecount_c_(size) _SAL1_1_Source_(_Inout_bytecount_c_, (size), _Prepost_bytecount_c_(size)) -#define _Inout_opt_bytecount_c_(size) _SAL1_1_Source_(_Inout_opt_bytecount_c_, (size), _Prepost_opt_bytecount_c_(size)) +#define _Inout_count_c_(size) _SAL1_1_Source_(_Inout_count_c_, (size), _Prepost_count_c_(size)) +#define _Inout_opt_count_c_(size) \ + _SAL1_1_Source_(_Inout_opt_count_c_, (size), _Prepost_opt_count_c_(size)) +#define _Inout_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_bytecount_c_, (size), _Prepost_bytecount_c_(size)) +#define _Inout_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_c_, (size), _Prepost_opt_bytecount_c_(size)) // nullterminated 'inout' buffers with initialized elements before and after the call // e.g. void ModifyIndices( _Inout_count_(cIndices) int* rgIndices, size_t cIndices ); -#define _Inout_z_count_(size) _SAL1_1_Source_(_Inout_z_count_, (size), _Prepost_z_ _Prepost_count_(size)) -#define _Inout_opt_z_count_(size) _SAL1_1_Source_(_Inout_opt_z_count_, (size), _Prepost_z_ _Prepost_opt_count_(size)) -#define _Inout_z_bytecount_(size) _SAL1_1_Source_(_Inout_z_bytecount_, (size), _Prepost_z_ _Prepost_bytecount_(size)) -#define _Inout_opt_z_bytecount_(size) _SAL1_1_Source_(_Inout_opt_z_bytecount_, (size), _Prepost_z_ _Prepost_opt_bytecount_(size)) +#define _Inout_z_count_(size) \ + _SAL1_1_Source_(_Inout_z_count_, (size), _Prepost_z_ _Prepost_count_(size)) +#define _Inout_opt_z_count_(size) \ + _SAL1_1_Source_(_Inout_opt_z_count_, (size), _Prepost_z_ _Prepost_opt_count_(size)) +#define _Inout_z_bytecount_(size) \ + _SAL1_1_Source_(_Inout_z_bytecount_, (size), _Prepost_z_ _Prepost_bytecount_(size)) +#define _Inout_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecount_, (size), _Prepost_z_ _Prepost_opt_bytecount_(size)) -#define _Inout_z_count_c_(size) _SAL1_1_Source_(_Inout_z_count_c_, (size), _Prepost_z_ _Prepost_count_c_(size)) -#define _Inout_opt_z_count_c_(size) _SAL1_1_Source_(_Inout_opt_z_count_c_, (size), _Prepost_z_ _Prepost_opt_count_c_(size)) -#define _Inout_z_bytecount_c_(size) _SAL1_1_Source_(_Inout_z_bytecount_c_, (size), _Prepost_z_ _Prepost_bytecount_c_(size)) -#define _Inout_opt_z_bytecount_c_(size) _SAL1_1_Source_(_Inout_opt_z_bytecount_c_, (size), _Prepost_z_ _Prepost_opt_bytecount_c_(size)) +#define _Inout_z_count_c_(size) \ + _SAL1_1_Source_(_Inout_z_count_c_, (size), _Prepost_z_ _Prepost_count_c_(size)) +#define _Inout_opt_z_count_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_count_c_, (size), _Prepost_z_ _Prepost_opt_count_c_(size)) +#define _Inout_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_z_bytecount_c_, (size), _Prepost_z_ _Prepost_bytecount_c_(size)) +#define _Inout_opt_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecount_c_, (size), _Prepost_z_ _Prepost_opt_bytecount_c_(size)) -#define _Inout_ptrdiff_count_(size) _SAL1_1_Source_(_Inout_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size)) -#define _Inout_opt_ptrdiff_count_(size) _SAL1_1_Source_(_Inout_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size)) +#define _Inout_ptrdiff_count_(size) \ + _SAL1_1_Source_(_Inout_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size)) +#define _Inout_opt_ptrdiff_count_(size) \ + _SAL1_1_Source_(_Inout_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size)) -#define _Inout_count_x_(size) _SAL1_1_Source_(_Inout_count_x_, (size), _Prepost_count_x_(size)) -#define _Inout_opt_count_x_(size) _SAL1_1_Source_(_Inout_opt_count_x_, (size), _Prepost_opt_count_x_(size)) -#define _Inout_bytecount_x_(size) _SAL1_1_Source_(_Inout_bytecount_x_, (size), _Prepost_bytecount_x_(size)) -#define _Inout_opt_bytecount_x_(size) _SAL1_1_Source_(_Inout_opt_bytecount_x_, (size), _Prepost_opt_bytecount_x_(size)) +#define _Inout_count_x_(size) _SAL1_1_Source_(_Inout_count_x_, (size), _Prepost_count_x_(size)) +#define _Inout_opt_count_x_(size) \ + _SAL1_1_Source_(_Inout_opt_count_x_, (size), _Prepost_opt_count_x_(size)) +#define _Inout_bytecount_x_(size) \ + _SAL1_1_Source_(_Inout_bytecount_x_, (size), _Prepost_bytecount_x_(size)) +#define _Inout_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_x_, (size), _Prepost_opt_bytecount_x_(size)) // e.g. void AppendToLPSTR( _In_ LPCSTR szFrom, _Inout_cap_(cchTo) LPSTR* szTo, size_t cchTo ); -#define _Inout_cap_(size) _SAL1_1_Source_(_Inout_cap_, (size), _Pre_valid_cap_(size) _Post_valid_) -#define _Inout_opt_cap_(size) _SAL1_1_Source_(_Inout_opt_cap_, (size), _Pre_opt_valid_cap_(size) _Post_valid_) -#define _Inout_bytecap_(size) _SAL1_1_Source_(_Inout_bytecap_, (size), _Pre_valid_bytecap_(size) _Post_valid_) -#define _Inout_opt_bytecap_(size) _SAL1_1_Source_(_Inout_opt_bytecap_, (size), _Pre_opt_valid_bytecap_(size) _Post_valid_) +#define _Inout_cap_(size) _SAL1_1_Source_(_Inout_cap_, (size), _Pre_valid_cap_(size) _Post_valid_) +#define _Inout_opt_cap_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_, (size), _Pre_opt_valid_cap_(size) _Post_valid_) +#define _Inout_bytecap_(size) \ + _SAL1_1_Source_(_Inout_bytecap_, (size), _Pre_valid_bytecap_(size) _Post_valid_) +#define _Inout_opt_bytecap_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_, (size), _Pre_opt_valid_bytecap_(size) _Post_valid_) -#define _Inout_cap_c_(size) _SAL1_1_Source_(_Inout_cap_c_, (size), _Pre_valid_cap_c_(size) _Post_valid_) -#define _Inout_opt_cap_c_(size) _SAL1_1_Source_(_Inout_opt_cap_c_, (size), _Pre_opt_valid_cap_c_(size) _Post_valid_) -#define _Inout_bytecap_c_(size) _SAL1_1_Source_(_Inout_bytecap_c_, (size), _Pre_valid_bytecap_c_(size) _Post_valid_) -#define _Inout_opt_bytecap_c_(size) _SAL1_1_Source_(_Inout_opt_bytecap_c_, (size), _Pre_opt_valid_bytecap_c_(size) _Post_valid_) +#define _Inout_cap_c_(size) \ + _SAL1_1_Source_(_Inout_cap_c_, (size), _Pre_valid_cap_c_(size) _Post_valid_) +#define _Inout_opt_cap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_c_, (size), _Pre_opt_valid_cap_c_(size) _Post_valid_) +#define _Inout_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_bytecap_c_, (size), _Pre_valid_bytecap_c_(size) _Post_valid_) +#define _Inout_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_c_, (size), _Pre_opt_valid_bytecap_c_(size) _Post_valid_) -#define _Inout_cap_x_(size) _SAL1_1_Source_(_Inout_cap_x_, (size), _Pre_valid_cap_x_(size) _Post_valid_) -#define _Inout_opt_cap_x_(size) _SAL1_1_Source_(_Inout_opt_cap_x_, (size), _Pre_opt_valid_cap_x_(size) _Post_valid_) -#define _Inout_bytecap_x_(size) _SAL1_1_Source_(_Inout_bytecap_x_, (size), _Pre_valid_bytecap_x_(size) _Post_valid_) -#define _Inout_opt_bytecap_x_(size) _SAL1_1_Source_(_Inout_opt_bytecap_x_, (size), _Pre_opt_valid_bytecap_x_(size) _Post_valid_) +#define _Inout_cap_x_(size) \ + _SAL1_1_Source_(_Inout_cap_x_, (size), _Pre_valid_cap_x_(size) _Post_valid_) +#define _Inout_opt_cap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_x_, (size), _Pre_opt_valid_cap_x_(size) _Post_valid_) +#define _Inout_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_bytecap_x_, (size), _Pre_valid_bytecap_x_(size) _Post_valid_) +#define _Inout_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_x_, (size), _Pre_opt_valid_bytecap_x_(size) _Post_valid_) // inout string buffers with writable size // e.g. void AppendStr( _In_z_ const char* szFrom, _Inout_z_cap_(cchTo) char* szTo, size_t cchTo ); -#define _Inout_z_cap_(size) _SAL1_1_Source_(_Inout_z_cap_, (size), _Pre_z_cap_(size) _Post_z_) -#define _Inout_opt_z_cap_(size) _SAL1_1_Source_(_Inout_opt_z_cap_, (size), _Pre_opt_z_cap_(size) _Post_z_) -#define _Inout_z_bytecap_(size) _SAL1_1_Source_(_Inout_z_bytecap_, (size), _Pre_z_bytecap_(size) _Post_z_) -#define _Inout_opt_z_bytecap_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_, (size), _Pre_opt_z_bytecap_(size) _Post_z_) +#define _Inout_z_cap_(size) _SAL1_1_Source_(_Inout_z_cap_, (size), _Pre_z_cap_(size) _Post_z_) +#define _Inout_opt_z_cap_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_, (size), _Pre_opt_z_cap_(size) _Post_z_) +#define _Inout_z_bytecap_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_, (size), _Pre_z_bytecap_(size) _Post_z_) +#define _Inout_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_, (size), _Pre_opt_z_bytecap_(size) _Post_z_) -#define _Inout_z_cap_c_(size) _SAL1_1_Source_(_Inout_z_cap_c_, (size), _Pre_z_cap_c_(size) _Post_z_) -#define _Inout_opt_z_cap_c_(size) _SAL1_1_Source_(_Inout_opt_z_cap_c_, (size), _Pre_opt_z_cap_c_(size) _Post_z_) -#define _Inout_z_bytecap_c_(size) _SAL1_1_Source_(_Inout_z_bytecap_c_, (size), _Pre_z_bytecap_c_(size) _Post_z_) -#define _Inout_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_c_, (size), _Pre_opt_z_bytecap_c_(size) _Post_z_) - -#define _Inout_z_cap_x_(size) _SAL1_1_Source_(_Inout_z_cap_x_, (size), _Pre_z_cap_x_(size) _Post_z_) -#define _Inout_opt_z_cap_x_(size) _SAL1_1_Source_(_Inout_opt_z_cap_x_, (size), _Pre_opt_z_cap_x_(size) _Post_z_) -#define _Inout_z_bytecap_x_(size) _SAL1_1_Source_(_Inout_z_bytecap_x_, (size), _Pre_z_bytecap_x_(size) _Post_z_) -#define _Inout_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_x_, (size), _Pre_opt_z_bytecap_x_(size) _Post_z_) +#define _Inout_z_cap_c_(size) _SAL1_1_Source_(_Inout_z_cap_c_, (size), _Pre_z_cap_c_(size) _Post_z_) +#define _Inout_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_c_, (size), _Pre_opt_z_cap_c_(size) _Post_z_) +#define _Inout_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_c_, (size), _Pre_z_bytecap_c_(size) _Post_z_) +#define _Inout_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_c_, (size), _Pre_opt_z_bytecap_c_(size) _Post_z_) +#define _Inout_z_cap_x_(size) _SAL1_1_Source_(_Inout_z_cap_x_, (size), _Pre_z_cap_x_(size) _Post_z_) +#define _Inout_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_x_, (size), _Pre_opt_z_cap_x_(size) _Post_z_) +#define _Inout_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_x_, (size), _Pre_z_bytecap_x_(size) _Post_z_) +#define _Inout_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_x_, (size), _Pre_opt_z_bytecap_x_(size) _Post_z_) // returning pointers to valid objects -#define _Ret_ _SAL1_1_Source_(_Ret_, (), _Ret_valid_) -#define _Ret_opt_ _SAL1_1_Source_(_Ret_opt_, (), _Ret_opt_valid_) +#define _Ret_ _SAL1_1_Source_(_Ret_, (), _Ret_valid_) +#define _Ret_opt_ _SAL1_1_Source_(_Ret_opt_, (), _Ret_opt_valid_) // annotations to express 'boundedness' of integral value parameter -#define _In_bound_ _SAL1_1_Source_(_In_bound_, (), _In_bound_impl_) -#define _Out_bound_ _SAL1_1_Source_(_Out_bound_, (), _Out_bound_impl_) -#define _Ret_bound_ _SAL1_1_Source_(_Ret_bound_, (), _Ret_bound_impl_) -#define _Deref_in_bound_ _SAL1_1_Source_(_Deref_in_bound_, (), _Deref_in_bound_impl_) -#define _Deref_out_bound_ _SAL1_1_Source_(_Deref_out_bound_, (), _Deref_out_bound_impl_) -#define _Deref_inout_bound_ _SAL1_1_Source_(_Deref_inout_bound_, (), _Deref_in_bound_ _Deref_out_bound_) -#define _Deref_ret_bound_ _SAL1_1_Source_(_Deref_ret_bound_, (), _Deref_ret_bound_impl_) +#define _In_bound_ _SAL1_1_Source_(_In_bound_, (), _In_bound_impl_) +#define _Out_bound_ _SAL1_1_Source_(_Out_bound_, (), _Out_bound_impl_) +#define _Ret_bound_ _SAL1_1_Source_(_Ret_bound_, (), _Ret_bound_impl_) +#define _Deref_in_bound_ _SAL1_1_Source_(_Deref_in_bound_, (), _Deref_in_bound_impl_) +#define _Deref_out_bound_ _SAL1_1_Source_(_Deref_out_bound_, (), _Deref_out_bound_impl_) +#define _Deref_inout_bound_ \ + _SAL1_1_Source_(_Deref_inout_bound_, (), _Deref_in_bound_ _Deref_out_bound_) +#define _Deref_ret_bound_ _SAL1_1_Source_(_Deref_ret_bound_, (), _Deref_ret_bound_impl_) // e.g. HRESULT HrCreatePoint( _Deref_out_opt_ POINT** ppPT ); -#define _Deref_out_ _SAL1_1_Source_(_Deref_out_, (), _Out_ _Deref_post_valid_) -#define _Deref_out_opt_ _SAL1_1_Source_(_Deref_out_opt_, (), _Out_ _Deref_post_opt_valid_) -#define _Deref_opt_out_ _SAL1_1_Source_(_Deref_opt_out_, (), _Out_opt_ _Deref_post_valid_) -#define _Deref_opt_out_opt_ _SAL1_1_Source_(_Deref_opt_out_opt_, (), _Out_opt_ _Deref_post_opt_valid_) +#define _Deref_out_ _SAL1_1_Source_(_Deref_out_, (), _Out_ _Deref_post_valid_) +#define _Deref_out_opt_ _SAL1_1_Source_(_Deref_out_opt_, (), _Out_ _Deref_post_opt_valid_) +#define _Deref_opt_out_ _SAL1_1_Source_(_Deref_opt_out_, (), _Out_opt_ _Deref_post_valid_) +#define _Deref_opt_out_opt_ \ + _SAL1_1_Source_(_Deref_opt_out_opt_, (), _Out_opt_ _Deref_post_opt_valid_) // e.g. void CloneString( _In_z_ const WCHAR* wzFrom, _Deref_out_z_ WCHAR** pWzTo ); -#define _Deref_out_z_ _SAL1_1_Source_(_Deref_out_z_, (), _Out_ _Deref_post_z_) -#define _Deref_out_opt_z_ _SAL1_1_Source_(_Deref_out_opt_z_, (), _Out_ _Deref_post_opt_z_) -#define _Deref_opt_out_z_ _SAL1_1_Source_(_Deref_opt_out_z_, (), _Out_opt_ _Deref_post_z_) -#define _Deref_opt_out_opt_z_ _SAL1_1_Source_(_Deref_opt_out_opt_z_, (), _Out_opt_ _Deref_post_opt_z_) +#define _Deref_out_z_ _SAL1_1_Source_(_Deref_out_z_, (), _Out_ _Deref_post_z_) +#define _Deref_out_opt_z_ _SAL1_1_Source_(_Deref_out_opt_z_, (), _Out_ _Deref_post_opt_z_) +#define _Deref_opt_out_z_ _SAL1_1_Source_(_Deref_opt_out_z_, (), _Out_opt_ _Deref_post_z_) +#define _Deref_opt_out_opt_z_ \ + _SAL1_1_Source_(_Deref_opt_out_opt_z_, (), _Out_opt_ _Deref_post_opt_z_) // // _Deref_pre_ --- // -// describing conditions for array elements of dereferenced pointer parameters that must be met before the call +// describing conditions for array elements of dereferenced pointer parameters that must be met +// before the call // e.g. void SaveStringArray( _In_count_(cStrings) _Deref_pre_z_ const WCHAR* const rgpwch[] ); -#define _Deref_pre_z_ _SAL1_1_Source_(_Deref_pre_z_, (), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__zterm_impl) _Pre_valid_impl_) -#define _Deref_pre_opt_z_ _SAL1_1_Source_(_Deref_pre_opt_z_, (), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Deref_pre_z_ \ + _SAL1_1_Source_(_Deref_pre_z_, (), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_z_ \ + _SAL1_1_Source_(_Deref_pre_opt_z_, (), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) -// e.g. void FillInArrayOfStr32( _In_count_(cStrings) _Deref_pre_cap_c_(32) _Deref_post_z_ WCHAR* const rgpwch[] ); -// buffer capacity is described by another parameter -#define _Deref_pre_cap_(size) _SAL1_1_Source_(_Deref_pre_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) -#define _Deref_pre_opt_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) -#define _Deref_pre_bytecap_(size) _SAL1_1_Source_(_Deref_pre_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size))) -#define _Deref_pre_opt_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size))) +// e.g. void FillInArrayOfStr32( _In_count_(cStrings) _Deref_pre_cap_c_(32) _Deref_post_z_ WCHAR* +// const rgpwch[] ); buffer capacity is described by another parameter +#define _Deref_pre_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) +#define _Deref_pre_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_impl(size))) +#define _Deref_pre_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size))) +#define _Deref_pre_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size))) // buffer capacity is described by a constant expression -#define _Deref_pre_cap_c_(size) _SAL1_1_Source_(_Deref_pre_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size))) -#define _Deref_pre_opt_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size))) -#define _Deref_pre_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size))) -#define _Deref_pre_opt_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size))) +#define _Deref_pre_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size))) +#define _Deref_pre_opt_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size))) +#define _Deref_pre_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size))) +#define _Deref_pre_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size))) // buffer capacity is described by a complex condition -#define _Deref_pre_cap_x_(size) _SAL1_1_Source_(_Deref_pre_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size))) -#define _Deref_pre_opt_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size))) -#define _Deref_pre_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size))) -#define _Deref_pre_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size))) +#define _Deref_pre_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size))) +#define _Deref_pre_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size))) +#define _Deref_pre_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size))) +#define _Deref_pre_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size))) // convenience macros for nullterminated buffers with given capacity -#define _Deref_pre_z_cap_(size) _SAL1_1_Source_(_Deref_pre_z_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_cap_c_(size) _SAL1_1_Source_(_Deref_pre_z_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_cap_x_(size) _SAL1_1_Source_(_Deref_pre_z_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) // known capacity and valid but unknown readable extent -#define _Deref_pre_valid_cap_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_cap_c_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_cap_x_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) // e.g. void SaveMatrix( _In_count_(n) _Deref_pre_count_(n) const Elem** matrix, size_t n ); // valid buffer extent is described by another parameter -#define _Deref_pre_count_(size) _SAL1_1_Source_(_Deref_pre_count_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_(size) _SAL1_1_Source_(_Deref_pre_opt_count_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_(size) _SAL1_1_Source_(_Deref_pre_bytecount_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_(size) \ + _SAL1_1_Source_(_Deref_pre_count_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_count_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) // valid buffer extent is described by a constant expression -#define _Deref_pre_count_c_(size) _SAL1_1_Source_(_Deref_pre_count_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_c_(size) _SAL1_1_Source_(_Deref_pre_opt_count_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_c_(size) _SAL1_1_Source_(_Deref_pre_bytecount_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_c_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_c_(size) \ + _SAL1_1_Source_(_Deref_pre_count_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_count_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) // valid buffer extent is described by a complex expression -#define _Deref_pre_count_x_(size) _SAL1_1_Source_(_Deref_pre_count_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_x_(size) _SAL1_1_Source_(_Deref_pre_opt_count_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_x_(size) _SAL1_1_Source_(_Deref_pre_bytecount_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_x_(size) \ + _SAL1_1_Source_(_Deref_pre_count_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) // e.g. void PrintStringArray( _In_count_(cElems) _Deref_pre_valid_ LPCSTR rgStr[], size_t cElems ); -#define _Deref_pre_valid_ _SAL1_1_Source_(_Deref_pre_valid_, (), _Deref_pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_ _SAL1_1_Source_(_Deref_pre_opt_valid_, (), _Deref_pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) -#define _Deref_pre_invalid_ _SAL1_1_Source_(_Deref_pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) +#define _Deref_pre_valid_ \ + _SAL1_1_Source_(_Deref_pre_valid_, (), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_ \ + _SAL1_1_Source_(_Deref_pre_opt_valid_, (), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) +#define _Deref_pre_invalid_ \ + _SAL1_1_Source_(_Deref_pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) -#define _Deref_pre_notnull_ _SAL1_1_Source_(_Deref_pre_notnull_, (), _Deref_pre1_impl_(__notnull_impl_notref)) -#define _Deref_pre_maybenull_ _SAL1_1_Source_(_Deref_pre_maybenull_, (), _Deref_pre1_impl_(__maybenull_impl_notref)) -#define _Deref_pre_null_ _SAL1_1_Source_(_Deref_pre_null_, (), _Deref_pre1_impl_(__null_impl_notref)) +#define _Deref_pre_notnull_ \ + _SAL1_1_Source_(_Deref_pre_notnull_, (), _Deref_pre1_impl_(__notnull_impl_notref)) +#define _Deref_pre_maybenull_ \ + _SAL1_1_Source_(_Deref_pre_maybenull_, (), _Deref_pre1_impl_(__maybenull_impl_notref)) +#define _Deref_pre_null_ \ + _SAL1_1_Source_(_Deref_pre_null_, (), _Deref_pre1_impl_(__null_impl_notref)) // restrict access rights -#define _Deref_pre_readonly_ _SAL1_1_Source_(_Deref_pre_readonly_, (), _Deref_pre1_impl_(__readaccess_impl_notref)) -#define _Deref_pre_writeonly_ _SAL1_1_Source_(_Deref_pre_writeonly_, (), _Deref_pre1_impl_(__writeaccess_impl_notref)) +#define _Deref_pre_readonly_ \ + _SAL1_1_Source_(_Deref_pre_readonly_, (), _Deref_pre1_impl_(__readaccess_impl_notref)) +#define _Deref_pre_writeonly_ \ + _SAL1_1_Source_(_Deref_pre_writeonly_, (), _Deref_pre1_impl_(__writeaccess_impl_notref)) // // _Deref_post_ --- // -// describing conditions for array elements or dereferenced pointer parameters that hold after the call +// describing conditions for array elements or dereferenced pointer parameters that hold after the +// call // e.g. void CloneString( _In_z_ const Wchar_t* wzIn _Out_ _Deref_post_z_ WCHAR** pWzOut ); -#define _Deref_post_z_ _SAL1_1_Source_(_Deref_post_z_, (), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__zterm_impl) _Post_valid_impl_) -#define _Deref_post_opt_z_ _SAL1_1_Source_(_Deref_post_opt_z_, (), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__zterm_impl) _Post_valid_impl_) +#define _Deref_post_z_ \ + _SAL1_1_Source_(_Deref_post_z_, (), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__zterm_impl) \ + _Post_valid_impl_) +#define _Deref_post_opt_z_ \ + _SAL1_1_Source_(_Deref_post_opt_z_, (), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__zterm_impl) \ + _Post_valid_impl_) // e.g. HRESULT HrAllocateMemory( size_t cb, _Out_ _Deref_post_bytecap_(cb) void** ppv ); // buffer capacity is described by another parameter -#define _Deref_post_cap_(size) _SAL1_1_Source_(_Deref_post_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size))) -#define _Deref_post_opt_cap_(size) _SAL1_1_Source_(_Deref_post_opt_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_impl(size))) -#define _Deref_post_bytecap_(size) _SAL1_1_Source_(_Deref_post_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size))) -#define _Deref_post_opt_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size))) +#define _Deref_post_cap_(size) \ + _SAL1_1_Source_(_Deref_post_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size))) +#define _Deref_post_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size))) +#define _Deref_post_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size))) +#define _Deref_post_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size))) // buffer capacity is described by a constant expression -#define _Deref_post_cap_c_(size) _SAL1_1_Source_(_Deref_post_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size))) -#define _Deref_post_opt_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size))) -#define _Deref_post_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size))) -#define _Deref_post_opt_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size))) +#define _Deref_post_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size))) +#define _Deref_post_opt_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size))) +#define _Deref_post_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size))) +#define _Deref_post_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size))) // buffer capacity is described by a complex expression -#define _Deref_post_cap_x_(size) _SAL1_1_Source_(_Deref_post_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size))) -#define _Deref_post_opt_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size))) -#define _Deref_post_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size))) -#define _Deref_post_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size))) +#define _Deref_post_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size))) +#define _Deref_post_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size))) +#define _Deref_post_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size))) +#define _Deref_post_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size))) // convenience macros for nullterminated buffers with given capacity -#define _Deref_post_z_cap_(size) _SAL1_1_Source_(_Deref_post_z_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_cap_c_(size) _SAL1_1_Source_(_Deref_post_z_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_cap_x_(size) _SAL1_1_Source_(_Deref_post_z_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_x_impl(size)) _Post_valid_impl_) // known capacity and valid but unknown readable extent -#define _Deref_post_valid_cap_(size) _SAL1_1_Source_(_Deref_post_valid_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) \ + _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_cap_c_(size) _SAL1_1_Source_(_Deref_post_valid_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_cap_x_(size) _SAL1_1_Source_(_Deref_post_valid_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) -// e.g. HRESULT HrAllocateZeroInitializedMemory( size_t cb, _Out_ _Deref_post_bytecount_(cb) void** ppv ); -// valid buffer extent is described by another parameter -#define _Deref_post_count_(size) _SAL1_1_Source_(_Deref_post_count_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_(size) _SAL1_1_Source_(_Deref_post_opt_count_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_(size) _SAL1_1_Source_(_Deref_post_bytecount_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +// e.g. HRESULT HrAllocateZeroInitializedMemory( size_t cb, _Out_ _Deref_post_bytecount_(cb) void** +// ppv ); valid buffer extent is described by another parameter +#define _Deref_post_count_(size) \ + _SAL1_1_Source_(_Deref_post_count_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) // buffer capacity is described by a constant expression -#define _Deref_post_count_c_(size) _SAL1_1_Source_(_Deref_post_count_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_c_(size) _SAL1_1_Source_(_Deref_post_opt_count_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_c_(size) _SAL1_1_Source_(_Deref_post_bytecount_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_c_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_count_c_(size) \ + _SAL1_1_Source_(_Deref_post_count_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) // buffer capacity is described by a complex expression -#define _Deref_post_count_x_(size) _SAL1_1_Source_(_Deref_post_count_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_x_(size) _SAL1_1_Source_(_Deref_post_opt_count_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_x_(size) _SAL1_1_Source_(_Deref_post_bytecount_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_count_x_(size) \ + _SAL1_1_Source_(_Deref_post_count_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -// e.g. void GetStrings( _Out_count_(cElems) _Deref_post_valid_ LPSTR const rgStr[], size_t cElems ); -#define _Deref_post_valid_ _SAL1_1_Source_(_Deref_post_valid_, (), _Deref_post1_impl_(__notnull_impl_notref) _Post_valid_impl_) -#define _Deref_post_opt_valid_ _SAL1_1_Source_(_Deref_post_opt_valid_, (), _Deref_post1_impl_(__maybenull_impl_notref) _Post_valid_impl_) +// e.g. void GetStrings( _Out_count_(cElems) _Deref_post_valid_ LPSTR const rgStr[], size_t cElems +// ); +#define _Deref_post_valid_ \ + _SAL1_1_Source_(_Deref_post_valid_, (), \ + _Deref_post1_impl_(__notnull_impl_notref) _Post_valid_impl_) +#define _Deref_post_opt_valid_ \ + _SAL1_1_Source_(_Deref_post_opt_valid_, (), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Post_valid_impl_) -#define _Deref_post_notnull_ _SAL1_1_Source_(_Deref_post_notnull_, (), _Deref_post1_impl_(__notnull_impl_notref)) -#define _Deref_post_maybenull_ _SAL1_1_Source_(_Deref_post_maybenull_, (), _Deref_post1_impl_(__maybenull_impl_notref)) -#define _Deref_post_null_ _SAL1_1_Source_(_Deref_post_null_, (), _Deref_post1_impl_(__null_impl_notref)) +#define _Deref_post_notnull_ \ + _SAL1_1_Source_(_Deref_post_notnull_, (), _Deref_post1_impl_(__notnull_impl_notref)) +#define _Deref_post_maybenull_ \ + _SAL1_1_Source_(_Deref_post_maybenull_, (), _Deref_post1_impl_(__maybenull_impl_notref)) +#define _Deref_post_null_ \ + _SAL1_1_Source_(_Deref_post_null_, (), _Deref_post1_impl_(__null_impl_notref)) // // _Deref_ret_ --- // -#define _Deref_ret_z_ _SAL1_1_Source_(_Deref_ret_z_, (), _Deref_ret1_impl_(__notnull_impl_notref) _Deref_ret1_impl_(__zterm_impl)) -#define _Deref_ret_opt_z_ _SAL1_1_Source_(_Deref_ret_opt_z_, (), _Deref_ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__zterm_impl)) +#define _Deref_ret_z_ \ + _SAL1_1_Source_(_Deref_ret_z_, (), \ + _Deref_ret1_impl_(__notnull_impl_notref) _Deref_ret1_impl_(__zterm_impl)) +#define _Deref_ret_opt_z_ \ + _SAL1_1_Source_(_Deref_ret_opt_z_, (), \ + _Deref_ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__zterm_impl)) // // special _Deref_ --- // -#define _Deref2_pre_readonly_ _SAL1_1_Source_(_Deref2_pre_readonly_, (), _Deref2_pre1_impl_(__readaccess_impl_notref)) +#define _Deref2_pre_readonly_ \ + _SAL1_1_Source_(_Deref2_pre_readonly_, (), _Deref2_pre1_impl_(__readaccess_impl_notref)) // // _Ret_ --- // // e.g. _Ret_opt_valid_ LPSTR void* CloneSTR( _Pre_valid_ LPSTR src ); -#define _Ret_opt_valid_ _SAL1_1_Source_(_Ret_opt_valid_, (), _Ret1_impl_(__maybenull_impl_notref) _Ret_valid_impl_) -#define _Ret_opt_z_ _SAL1_1_Source_(_Ret_opt_z_, (), _Ret2_impl_(__maybenull_impl,__zterm_impl) _Ret_valid_impl_) +#define _Ret_opt_valid_ \ + _SAL1_1_Source_(_Ret_opt_valid_, (), _Ret1_impl_(__maybenull_impl_notref) _Ret_valid_impl_) +#define _Ret_opt_z_ \ + _SAL1_1_Source_(_Ret_opt_z_, (), _Ret2_impl_(__maybenull_impl, __zterm_impl) _Ret_valid_impl_) // e.g. _Ret_opt_bytecap_(cb) void* AllocateMemory( size_t cb ); // Buffer capacity is described by another parameter -#define _Ret_cap_(size) _SAL1_1_Source_(_Ret_cap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_impl(size))) -#define _Ret_opt_cap_(size) _SAL1_1_Source_(_Ret_opt_cap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_impl(size))) -#define _Ret_bytecap_(size) _SAL1_1_Source_(_Ret_bytecap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) -#define _Ret_opt_bytecap_(size) _SAL1_1_Source_(_Ret_opt_bytecap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) +#define _Ret_cap_(size) \ + _SAL1_1_Source_(_Ret_cap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_impl(size))) +#define _Ret_opt_cap_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_impl(size))) +#define _Ret_bytecap_(size) \ + _SAL1_1_Source_(_Ret_bytecap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) +#define _Ret_opt_bytecap_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) // Buffer capacity is described by a constant expression -#define _Ret_cap_c_(size) _SAL1_1_Source_(_Ret_cap_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) -#define _Ret_opt_cap_c_(size) _SAL1_1_Source_(_Ret_opt_cap_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) -#define _Ret_bytecap_c_(size) _SAL1_1_Source_(_Ret_bytecap_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) -#define _Ret_opt_bytecap_c_(size) _SAL1_1_Source_(_Ret_opt_bytecap_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) +#define _Ret_cap_c_(size) \ + _SAL1_1_Source_(_Ret_cap_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) +#define _Ret_opt_cap_c_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) +#define _Ret_bytecap_c_(size) \ + _SAL1_1_Source_(_Ret_bytecap_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) +#define _Ret_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) // Buffer capacity is described by a complex condition -#define _Ret_cap_x_(size) _SAL1_1_Source_(_Ret_cap_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) -#define _Ret_opt_cap_x_(size) _SAL1_1_Source_(_Ret_opt_cap_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) -#define _Ret_bytecap_x_(size) _SAL1_1_Source_(_Ret_bytecap_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) -#define _Ret_opt_bytecap_x_(size) _SAL1_1_Source_(_Ret_opt_bytecap_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) +#define _Ret_cap_x_(size) \ + _SAL1_1_Source_(_Ret_cap_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) +#define _Ret_opt_cap_x_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) +#define _Ret_bytecap_x_(size) \ + _SAL1_1_Source_(_Ret_bytecap_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) +#define _Ret_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) // return value is nullterminated and capacity is given by another parameter -#define _Ret_z_cap_(size) _SAL1_1_Source_(_Ret_z_cap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__cap_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_cap_(size) _SAL1_1_Source_(_Ret_opt_z_cap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__cap_impl(size)) _Ret_valid_impl_) -#define _Ret_z_bytecap_(size) _SAL1_1_Source_(_Ret_z_bytecap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecap_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_bytecap_(size) _SAL1_1_Source_(_Ret_opt_z_bytecap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecap_impl(size)) _Ret_valid_impl_) +#define _Ret_z_cap_(size) \ + _SAL1_1_Source_(_Ret_z_cap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl, __cap_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_z_cap_(size) \ + _SAL1_1_Source_(_Ret_opt_z_cap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __cap_impl(size)) _Ret_valid_impl_) +#define _Ret_z_bytecap_(size) \ + _SAL1_1_Source_(_Ret_z_bytecap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecap_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Ret_opt_z_bytecap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecap_impl(size)) _Ret_valid_impl_) // e.g. _Ret_opt_bytecount_(cb) void* AllocateZeroInitializedMemory( size_t cb ); // Valid Buffer extent is described by another parameter -#define _Ret_count_(size) _SAL1_1_Source_(_Ret_count_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_(size) _SAL1_1_Source_(_Ret_opt_count_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_(size) _SAL1_1_Source_(_Ret_bytecount_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_(size) _SAL1_1_Source_(_Ret_opt_bytecount_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_count_(size) \ + _SAL1_1_Source_(_Ret_count_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_(size) \ + _SAL1_1_Source_(_Ret_opt_count_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_(size) \ + _SAL1_1_Source_(_Ret_bytecount_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) \ + _Ret_valid_impl_) // Valid Buffer extent is described by a constant expression -#define _Ret_count_c_(size) _SAL1_1_Source_(_Ret_count_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_c_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_c_(size) _SAL1_1_Source_(_Ret_opt_count_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_c_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_c_(size) _SAL1_1_Source_(_Ret_bytecount_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_c_(size) _SAL1_1_Source_(_Ret_opt_bytecount_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) _Ret_valid_impl_) +#define _Ret_count_c_(size) \ + _SAL1_1_Source_(_Ret_count_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_c_(size) \ + _SAL1_1_Source_(_Ret_opt_count_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_c_(size) \ + _SAL1_1_Source_(_Ret_bytecount_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) \ + _Ret_valid_impl_) // Valid Buffer extent is described by a complex expression -#define _Ret_count_x_(size) _SAL1_1_Source_(_Ret_count_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_x_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_x_(size) _SAL1_1_Source_(_Ret_opt_count_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_x_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_x_(size) _SAL1_1_Source_(_Ret_bytecount_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_x_(size) _SAL1_1_Source_(_Ret_opt_bytecount_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) _Ret_valid_impl_) +#define _Ret_count_x_(size) \ + _SAL1_1_Source_(_Ret_count_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_x_(size) \ + _SAL1_1_Source_(_Ret_opt_count_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_x_(size) \ + _SAL1_1_Source_(_Ret_bytecount_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) \ + _Ret_valid_impl_) // return value is nullterminated and length is given by another parameter -#define _Ret_z_count_(size) _SAL1_1_Source_(_Ret_z_count_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_count_(size) _SAL1_1_Source_(_Ret_opt_z_count_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_z_bytecount_(size) _SAL1_1_Source_(_Ret_z_bytecount_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_bytecount_(size) _SAL1_1_Source_(_Ret_opt_z_bytecount_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecount_impl(size)) _Ret_valid_impl_) - +#define _Ret_z_count_(size) \ + _SAL1_1_Source_(_Ret_z_count_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_count_(size) \ + _SAL1_1_Source_(_Ret_opt_z_count_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_z_bytecount_(size) \ + _SAL1_1_Source_(_Ret_z_bytecount_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_Ret_opt_z_bytecount_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecount_impl(size)) _Ret_valid_impl_) // _Pre_ annotations --- -#define _Pre_opt_z_ _SAL1_1_Source_(_Pre_opt_z_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Pre_opt_z_ \ + _SAL1_1_Source_(_Pre_opt_z_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) // restrict access rights -#define _Pre_readonly_ _SAL1_1_Source_(_Pre_readonly_, (), _Pre1_impl_(__readaccess_impl_notref)) -#define _Pre_writeonly_ _SAL1_1_Source_(_Pre_writeonly_, (), _Pre1_impl_(__writeaccess_impl_notref)) +#define _Pre_readonly_ _SAL1_1_Source_(_Pre_readonly_, (), _Pre1_impl_(__readaccess_impl_notref)) +#define _Pre_writeonly_ _SAL1_1_Source_(_Pre_writeonly_, (), _Pre1_impl_(__writeaccess_impl_notref)) // e.g. void FreeMemory( _Pre_bytecap_(cb) _Post_ptr_invalid_ void* pv, size_t cb ); // buffer capacity described by another parameter -#define _Pre_cap_(size) _SAL1_1_Source_(_Pre_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size))) -#define _Pre_opt_cap_(size) _SAL1_1_Source_(_Pre_opt_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size))) -#define _Pre_bytecap_(size) _SAL1_1_Source_(_Pre_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) -#define _Pre_opt_bytecap_(size) _SAL1_1_Source_(_Pre_opt_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_cap_(size) \ + _SAL1_1_Source_(_Pre_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size))) +#define _Pre_opt_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size))) +#define _Pre_bytecap_(size) \ + _SAL1_1_Source_(_Pre_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_opt_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) // buffer capacity described by a constant expression -#define _Pre_cap_c_(size) _SAL1_1_Source_(_Pre_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) -#define _Pre_opt_cap_c_(size) _SAL1_1_Source_(_Pre_opt_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) -#define _Pre_bytecap_c_(size) _SAL1_1_Source_(_Pre_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) -#define _Pre_opt_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) -#define _Pre_cap_c_one_ _SAL1_1_Source_(_Pre_cap_c_one_, (), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) -#define _Pre_opt_cap_c_one_ _SAL1_1_Source_(_Pre_opt_cap_c_one_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) +#define _Pre_cap_c_(size) \ + _SAL1_1_Source_(_Pre_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) +#define _Pre_opt_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) +#define _Pre_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) +#define _Pre_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) +#define _Pre_cap_c_one_ \ + _SAL1_1_Source_(_Pre_cap_c_one_, (), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) +#define _Pre_opt_cap_c_one_ \ + _SAL1_1_Source_(_Pre_opt_cap_c_one_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) // buffer capacity is described by another parameter multiplied by a constant expression -#define _Pre_cap_m_(mult,size) _SAL1_1_Source_(_Pre_cap_m_, (mult,size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__mult_impl(mult,size))) -#define _Pre_opt_cap_m_(mult,size) _SAL1_1_Source_(_Pre_opt_cap_m_, (mult,size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__mult_impl(mult,size))) +#define _Pre_cap_m_(mult, size) \ + _SAL1_1_Source_(_Pre_cap_m_, (mult, size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__mult_impl(mult, size))) +#define _Pre_opt_cap_m_(mult, size) \ + _SAL1_1_Source_(_Pre_opt_cap_m_, (mult, size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__mult_impl(mult, size))) // buffer capacity described by size of other buffer, only used by dangerous legacy APIs // e.g. int strcpy(_Pre_cap_for_(src) char* dst, const char* src); -#define _Pre_cap_for_(param) _SAL1_1_Source_(_Pre_cap_for_, (param), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) -#define _Pre_opt_cap_for_(param) _SAL1_1_Source_(_Pre_opt_cap_for_, (param), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) +#define _Pre_cap_for_(param) \ + _SAL1_1_Source_(_Pre_cap_for_, (param), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) +#define _Pre_opt_cap_for_(param) \ + _SAL1_1_Source_(_Pre_opt_cap_for_, (param), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) // buffer capacity described by a complex condition -#define _Pre_cap_x_(size) _SAL1_1_Source_(_Pre_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) -#define _Pre_opt_cap_x_(size) _SAL1_1_Source_(_Pre_opt_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) -#define _Pre_bytecap_x_(size) _SAL1_1_Source_(_Pre_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) -#define _Pre_opt_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) +#define _Pre_cap_x_(size) \ + _SAL1_1_Source_(_Pre_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) +#define _Pre_opt_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) +#define _Pre_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) +#define _Pre_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) // buffer capacity described by the difference to another pointer parameter -#define _Pre_ptrdiff_cap_(ptr) _SAL1_1_Source_(_Pre_ptrdiff_cap_, (ptr), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) -#define _Pre_opt_ptrdiff_cap_(ptr) _SAL1_1_Source_(_Pre_opt_ptrdiff_cap_, (ptr), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) +#define _Pre_ptrdiff_cap_(ptr) \ + _SAL1_1_Source_(_Pre_ptrdiff_cap_, (ptr), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) +#define _Pre_opt_ptrdiff_cap_(ptr) \ + _SAL1_1_Source_(_Pre_opt_ptrdiff_cap_, (ptr), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) -// e.g. void AppendStr( _Pre_z_ const char* szFrom, _Pre_z_cap_(cchTo) _Post_z_ char* szTo, size_t cchTo ); -#define _Pre_z_cap_(size) _SAL1_1_Source_(_Pre_z_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_(size) _SAL1_1_Source_(_Pre_opt_z_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_(size) _SAL1_1_Source_(_Pre_z_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) +// e.g. void AppendStr( _Pre_z_ const char* szFrom, _Pre_z_cap_(cchTo) _Post_z_ char* szTo, size_t +// cchTo ); +#define _Pre_z_cap_(size) \ + _SAL1_1_Source_(_Pre_z_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl, __cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_z_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_z_cap_c_(size) _SAL1_1_Source_(_Pre_z_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_c_(size) _SAL1_1_Source_(_Pre_opt_z_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_c_(size) _SAL1_1_Source_(_Pre_z_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_z_cap_c_(size) \ + _SAL1_1_Source_(_Pre_z_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_z_cap_x_(size) _SAL1_1_Source_(_Pre_z_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_x_(size) _SAL1_1_Source_(_Pre_opt_z_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_x_(size) _SAL1_1_Source_(_Pre_z_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_z_cap_x_(size) \ + _SAL1_1_Source_(_Pre_z_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) // known capacity and valid but unknown readable extent -#define _Pre_valid_cap_(size) _SAL1_1_Source_(_Pre_valid_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_(size) _SAL1_1_Source_(_Pre_valid_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) \ + _Pre_valid_impl_) -#define _Pre_valid_cap_c_(size) _SAL1_1_Source_(_Pre_valid_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_c_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_c_(size) _SAL1_1_Source_(_Pre_valid_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_c_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) \ + _Pre_valid_impl_) -#define _Pre_valid_cap_x_(size) _SAL1_1_Source_(_Pre_valid_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_x_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_x_(size) _SAL1_1_Source_(_Pre_valid_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_x_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) \ + _Pre_valid_impl_) -// e.g. void AppendCharRange( _Pre_count_(cchFrom) const char* rgFrom, size_t cchFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); -// Valid buffer extent described by another parameter -#define _Pre_count_(size) _SAL1_1_Source_(_Pre_count_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_(size) _SAL1_1_Source_(_Pre_opt_count_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_(size) _SAL1_1_Source_(_Pre_bytecount_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_(size) _SAL1_1_Source_(_Pre_opt_bytecount_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +// e.g. void AppendCharRange( _Pre_count_(cchFrom) const char* rgFrom, size_t cchFrom, +// _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); Valid buffer extent described by another parameter +#define _Pre_count_(size) \ + _SAL1_1_Source_(_Pre_count_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_(size) \ + _SAL1_1_Source_(_Pre_opt_count_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_(size) \ + _SAL1_1_Source_(_Pre_bytecount_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by a constant expression -#define _Pre_count_c_(size) _SAL1_1_Source_(_Pre_count_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_c_(size) _SAL1_1_Source_(_Pre_opt_count_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_c_(size) _SAL1_1_Source_(_Pre_bytecount_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_c_(size) _SAL1_1_Source_(_Pre_opt_bytecount_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Pre_count_c_(size) \ + _SAL1_1_Source_(_Pre_count_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_c_(size) \ + _SAL1_1_Source_(_Pre_opt_count_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_c_(size) \ + _SAL1_1_Source_(_Pre_bytecount_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by a complex expression -#define _Pre_count_x_(size) _SAL1_1_Source_(_Pre_count_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_x_(size) _SAL1_1_Source_(_Pre_opt_count_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_x_(size) _SAL1_1_Source_(_Pre_bytecount_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_x_(size) _SAL1_1_Source_(_Pre_opt_bytecount_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Pre_count_x_(size) \ + _SAL1_1_Source_(_Pre_count_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_x_(size) \ + _SAL1_1_Source_(_Pre_opt_count_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_x_(size) \ + _SAL1_1_Source_(_Pre_bytecount_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by the difference to another pointer parameter -#define _Pre_ptrdiff_count_(ptr) _SAL1_1_Source_(_Pre_ptrdiff_count_, (ptr), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) -#define _Pre_opt_ptrdiff_count_(ptr) _SAL1_1_Source_(_Pre_opt_ptrdiff_count_, (ptr), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) +#define _Pre_ptrdiff_count_(ptr) \ + _SAL1_1_Source_(_Pre_ptrdiff_count_, (ptr), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) \ + _Pre_valid_impl_) +#define _Pre_opt_ptrdiff_count_(ptr) \ + _SAL1_1_Source_(_Pre_opt_ptrdiff_count_, (ptr), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) +// char * strncpy(_Out_cap_(_Count) _Post_maybez_ char * _Dest, _In_z_ const char * _Source, _In_ +// size_t _Count) buffer maybe zero-terminated after the call +#define _Post_maybez_ _SAL1_1_Source_(_Post_maybez_, (), _Post1_impl_(__maybezterm_impl)) -// char * strncpy(_Out_cap_(_Count) _Post_maybez_ char * _Dest, _In_z_ const char * _Source, _In_ size_t _Count) -// buffer maybe zero-terminated after the call -#define _Post_maybez_ _SAL1_1_Source_(_Post_maybez_, (), _Post1_impl_(__maybezterm_impl)) - -// e.g. SIZE_T HeapSize( _In_ HANDLE hHeap, DWORD dwFlags, _Pre_notnull_ _Post_bytecap_(return) LPCVOID lpMem ); -#define _Post_cap_(size) _SAL1_1_Source_(_Post_cap_, (size), _Post1_impl_(__cap_impl(size))) -#define _Post_bytecap_(size) _SAL1_1_Source_(_Post_bytecap_, (size), _Post1_impl_(__bytecap_impl(size))) +// e.g. SIZE_T HeapSize( _In_ HANDLE hHeap, DWORD dwFlags, _Pre_notnull_ _Post_bytecap_(return) +// LPCVOID lpMem ); +#define _Post_cap_(size) _SAL1_1_Source_(_Post_cap_, (size), _Post1_impl_(__cap_impl(size))) +#define _Post_bytecap_(size) \ + _SAL1_1_Source_(_Post_bytecap_, (size), _Post1_impl_(__bytecap_impl(size))) // e.g. int strlen( _In_z_ _Post_count_(return+1) const char* sz ); -#define _Post_count_(size) _SAL1_1_Source_(_Post_count_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_(size) _SAL1_1_Source_(_Post_bytecount_, (size), _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_count_c_(size) _SAL1_1_Source_(_Post_count_c_, (size), _Post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_c_(size) _SAL1_1_Source_(_Post_bytecount_c_, (size), _Post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Post_count_x_(size) _SAL1_1_Source_(_Post_count_x_, (size), _Post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_x_(size) _SAL1_1_Source_(_Post_bytecount_x_, (size), _Post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Post_count_(size) \ + _SAL1_1_Source_(_Post_count_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_(size) \ + _SAL1_1_Source_(_Post_bytecount_, (size), \ + _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Post_count_c_(size) \ + _SAL1_1_Source_(_Post_count_c_, (size), _Post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_c_(size) \ + _SAL1_1_Source_(_Post_bytecount_c_, (size), \ + _Post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Post_count_x_(size) \ + _SAL1_1_Source_(_Post_count_x_, (size), _Post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_x_(size) \ + _SAL1_1_Source_(_Post_bytecount_x_, (size), \ + _Post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_count_(return+1) char* szFrom, size_t cchFrom ); -#define _Post_z_count_(size) _SAL1_1_Source_(_Post_z_count_, (size), _Post2_impl_(__zterm_impl,__count_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_(size) _SAL1_1_Source_(_Post_z_bytecount_, (size), _Post2_impl_(__zterm_impl,__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_z_count_c_(size) _SAL1_1_Source_(_Post_z_count_c_, (size), _Post2_impl_(__zterm_impl,__count_c_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_c_(size) _SAL1_1_Source_(_Post_z_bytecount_c_, (size), _Post2_impl_(__zterm_impl,__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Post_z_count_x_(size) _SAL1_1_Source_(_Post_z_count_x_, (size), _Post2_impl_(__zterm_impl,__count_x_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_x_(size) _SAL1_1_Source_(_Post_z_bytecount_x_, (size), _Post2_impl_(__zterm_impl,__bytecount_x_impl(size)) _Post_valid_impl_) +// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_count_(return+1) char* +// szFrom, size_t cchFrom ); +#define _Post_z_count_(size) \ + _SAL1_1_Source_(_Post_z_count_, (size), \ + _Post2_impl_(__zterm_impl, __count_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_impl(size)) _Post_valid_impl_) +#define _Post_z_count_c_(size) \ + _SAL1_1_Source_(_Post_z_count_c_, (size), \ + _Post2_impl_(__zterm_impl, __count_c_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_c_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_c_impl(size)) _Post_valid_impl_) +#define _Post_z_count_x_(size) \ + _SAL1_1_Source_(_Post_z_count_x_, (size), \ + _Post2_impl_(__zterm_impl, __count_x_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_x_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_x_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_x_impl(size)) _Post_valid_impl_) // // _Prepost_ --- // // describing conditions that hold before and after the function call -#define _Prepost_opt_z_ _SAL1_1_Source_(_Prepost_opt_z_, (), _Pre_opt_z_ _Post_z_) +#define _Prepost_opt_z_ _SAL1_1_Source_(_Prepost_opt_z_, (), _Pre_opt_z_ _Post_z_) -#define _Prepost_count_(size) _SAL1_1_Source_(_Prepost_count_, (size), _Pre_count_(size) _Post_count_(size)) -#define _Prepost_opt_count_(size) _SAL1_1_Source_(_Prepost_opt_count_, (size), _Pre_opt_count_(size) _Post_count_(size)) -#define _Prepost_bytecount_(size) _SAL1_1_Source_(_Prepost_bytecount_, (size), _Pre_bytecount_(size) _Post_bytecount_(size)) -#define _Prepost_opt_bytecount_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Post_bytecount_(size)) -#define _Prepost_count_c_(size) _SAL1_1_Source_(_Prepost_count_c_, (size), _Pre_count_c_(size) _Post_count_c_(size)) -#define _Prepost_opt_count_c_(size) _SAL1_1_Source_(_Prepost_opt_count_c_, (size), _Pre_opt_count_c_(size) _Post_count_c_(size)) -#define _Prepost_bytecount_c_(size) _SAL1_1_Source_(_Prepost_bytecount_c_, (size), _Pre_bytecount_c_(size) _Post_bytecount_c_(size)) -#define _Prepost_opt_bytecount_c_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Post_bytecount_c_(size)) -#define _Prepost_count_x_(size) _SAL1_1_Source_(_Prepost_count_x_, (size), _Pre_count_x_(size) _Post_count_x_(size)) -#define _Prepost_opt_count_x_(size) _SAL1_1_Source_(_Prepost_opt_count_x_, (size), _Pre_opt_count_x_(size) _Post_count_x_(size)) -#define _Prepost_bytecount_x_(size) _SAL1_1_Source_(_Prepost_bytecount_x_, (size), _Pre_bytecount_x_(size) _Post_bytecount_x_(size)) -#define _Prepost_opt_bytecount_x_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Post_bytecount_x_(size)) +#define _Prepost_count_(size) \ + _SAL1_1_Source_(_Prepost_count_, (size), _Pre_count_(size) _Post_count_(size)) +#define _Prepost_opt_count_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_, (size), _Pre_opt_count_(size) _Post_count_(size)) +#define _Prepost_bytecount_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_, (size), _Pre_bytecount_(size) _Post_bytecount_(size)) +#define _Prepost_opt_bytecount_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_, (size), \ + _Pre_opt_bytecount_(size) _Post_bytecount_(size)) +#define _Prepost_count_c_(size) \ + _SAL1_1_Source_(_Prepost_count_c_, (size), _Pre_count_c_(size) _Post_count_c_(size)) +#define _Prepost_opt_count_c_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_c_, (size), _Pre_opt_count_c_(size) _Post_count_c_(size)) +#define _Prepost_bytecount_c_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_c_, (size), _Pre_bytecount_c_(size) _Post_bytecount_c_(size)) +#define _Prepost_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_c_, (size), \ + _Pre_opt_bytecount_c_(size) _Post_bytecount_c_(size)) +#define _Prepost_count_x_(size) \ + _SAL1_1_Source_(_Prepost_count_x_, (size), _Pre_count_x_(size) _Post_count_x_(size)) +#define _Prepost_opt_count_x_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_x_, (size), _Pre_opt_count_x_(size) _Post_count_x_(size)) +#define _Prepost_bytecount_x_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_x_, (size), _Pre_bytecount_x_(size) _Post_bytecount_x_(size)) +#define _Prepost_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_x_, (size), \ + _Pre_opt_bytecount_x_(size) _Post_bytecount_x_(size)) -#define _Prepost_valid_ _SAL1_1_Source_(_Prepost_valid_, (), _Pre_valid_ _Post_valid_) -#define _Prepost_opt_valid_ _SAL1_1_Source_(_Prepost_opt_valid_, (), _Pre_opt_valid_ _Post_valid_) +#define _Prepost_valid_ _SAL1_1_Source_(_Prepost_valid_, (), _Pre_valid_ _Post_valid_) +#define _Prepost_opt_valid_ _SAL1_1_Source_(_Prepost_opt_valid_, (), _Pre_opt_valid_ _Post_valid_) // // _Deref_ --- // // short version for _Deref_pre_ _Deref_post_ -// describing conditions for array elements or dereferenced pointer parameters that hold before and after the call +// describing conditions for array elements or dereferenced pointer parameters that hold before and +// after the call -#define _Deref_prepost_z_ _SAL1_1_Source_(_Deref_prepost_z_, (), _Deref_pre_z_ _Deref_post_z_) -#define _Deref_prepost_opt_z_ _SAL1_1_Source_(_Deref_prepost_opt_z_, (), _Deref_pre_opt_z_ _Deref_post_opt_z_) +#define _Deref_prepost_z_ _SAL1_1_Source_(_Deref_prepost_z_, (), _Deref_pre_z_ _Deref_post_z_) +#define _Deref_prepost_opt_z_ \ + _SAL1_1_Source_(_Deref_prepost_opt_z_, (), _Deref_pre_opt_z_ _Deref_post_opt_z_) -#define _Deref_prepost_cap_(size) _SAL1_1_Source_(_Deref_prepost_cap_, (size), _Deref_pre_cap_(size) _Deref_post_cap_(size)) -#define _Deref_prepost_opt_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_cap_, (size), _Deref_pre_opt_cap_(size) _Deref_post_opt_cap_(size)) -#define _Deref_prepost_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_bytecap_, (size), _Deref_pre_bytecap_(size) _Deref_post_bytecap_(size)) -#define _Deref_prepost_opt_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecap_, (size), _Deref_pre_opt_bytecap_(size) _Deref_post_opt_bytecap_(size)) +#define _Deref_prepost_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_cap_, (size), _Deref_pre_cap_(size) _Deref_post_cap_(size)) +#define _Deref_prepost_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_cap_, (size), \ + _Deref_pre_opt_cap_(size) _Deref_post_opt_cap_(size)) +#define _Deref_prepost_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecap_, (size), \ + _Deref_pre_bytecap_(size) _Deref_post_bytecap_(size)) +#define _Deref_prepost_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecap_, (size), \ + _Deref_pre_opt_bytecap_(size) _Deref_post_opt_bytecap_(size)) -#define _Deref_prepost_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_cap_x_, (size), _Deref_pre_cap_x_(size) _Deref_post_cap_x_(size)) -#define _Deref_prepost_opt_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_cap_x_, (size), _Deref_pre_opt_cap_x_(size) _Deref_post_opt_cap_x_(size)) -#define _Deref_prepost_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_bytecap_x_, (size), _Deref_pre_bytecap_x_(size) _Deref_post_bytecap_x_(size)) -#define _Deref_prepost_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecap_x_, (size), _Deref_pre_opt_bytecap_x_(size) _Deref_post_opt_bytecap_x_(size)) +#define _Deref_prepost_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_cap_x_, (size), _Deref_pre_cap_x_(size) _Deref_post_cap_x_(size)) +#define _Deref_prepost_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_cap_x_, (size), \ + _Deref_pre_opt_cap_x_(size) _Deref_post_opt_cap_x_(size)) +#define _Deref_prepost_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecap_x_, (size), \ + _Deref_pre_bytecap_x_(size) _Deref_post_bytecap_x_(size)) +#define _Deref_prepost_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecap_x_, (size), \ + _Deref_pre_opt_bytecap_x_(size) _Deref_post_opt_bytecap_x_(size)) -#define _Deref_prepost_z_cap_(size) _SAL1_1_Source_(_Deref_prepost_z_cap_, (size), _Deref_pre_z_cap_(size) _Deref_post_z_cap_(size)) -#define _Deref_prepost_opt_z_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_z_cap_, (size), _Deref_pre_opt_z_cap_(size) _Deref_post_opt_z_cap_(size)) -#define _Deref_prepost_z_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_z_bytecap_, (size), _Deref_pre_z_bytecap_(size) _Deref_post_z_bytecap_(size)) -#define _Deref_prepost_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_z_bytecap_, (size), _Deref_pre_opt_z_bytecap_(size) _Deref_post_opt_z_bytecap_(size)) +#define _Deref_prepost_z_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_z_cap_, (size), _Deref_pre_z_cap_(size) _Deref_post_z_cap_(size)) +#define _Deref_prepost_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_z_cap_, (size), \ + _Deref_pre_opt_z_cap_(size) _Deref_post_opt_z_cap_(size)) +#define _Deref_prepost_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_z_bytecap_, (size), \ + _Deref_pre_z_bytecap_(size) _Deref_post_z_bytecap_(size)) +#define _Deref_prepost_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_z_bytecap_, (size), \ + _Deref_pre_opt_z_bytecap_(size) _Deref_post_opt_z_bytecap_(size)) -#define _Deref_prepost_valid_cap_(size) _SAL1_1_Source_(_Deref_prepost_valid_cap_, (size), _Deref_pre_valid_cap_(size) _Deref_post_valid_cap_(size)) -#define _Deref_prepost_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_, (size), _Deref_pre_opt_valid_cap_(size) _Deref_post_opt_valid_cap_(size)) -#define _Deref_prepost_valid_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_valid_bytecap_, (size), _Deref_pre_valid_bytecap_(size) _Deref_post_valid_bytecap_(size)) -#define _Deref_prepost_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_, (size), _Deref_pre_opt_valid_bytecap_(size) _Deref_post_opt_valid_bytecap_(size)) +#define _Deref_prepost_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_cap_, (size), \ + _Deref_pre_valid_cap_(size) _Deref_post_valid_cap_(size)) +#define _Deref_prepost_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_, (size), \ + _Deref_pre_opt_valid_cap_(size) _Deref_post_opt_valid_cap_(size)) +#define _Deref_prepost_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_bytecap_, (size), \ + _Deref_pre_valid_bytecap_(size) _Deref_post_valid_bytecap_(size)) +#define _Deref_prepost_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_, (size), \ + _Deref_pre_opt_valid_bytecap_(size) _Deref_post_opt_valid_bytecap_(size)) -#define _Deref_prepost_valid_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_valid_cap_x_, (size), _Deref_pre_valid_cap_x_(size) _Deref_post_valid_cap_x_(size)) -#define _Deref_prepost_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_x_, (size), _Deref_pre_opt_valid_cap_x_(size) _Deref_post_opt_valid_cap_x_(size)) -#define _Deref_prepost_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_valid_bytecap_x_, (size), _Deref_pre_valid_bytecap_x_(size) _Deref_post_valid_bytecap_x_(size)) -#define _Deref_prepost_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_x_, (size), _Deref_pre_opt_valid_bytecap_x_(size) _Deref_post_opt_valid_bytecap_x_(size)) +#define _Deref_prepost_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_cap_x_, (size), \ + _Deref_pre_valid_cap_x_(size) _Deref_post_valid_cap_x_(size)) +#define _Deref_prepost_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_x_, (size), \ + _Deref_pre_opt_valid_cap_x_(size) _Deref_post_opt_valid_cap_x_(size)) +#define _Deref_prepost_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_bytecap_x_, (size), \ + _Deref_pre_valid_bytecap_x_(size) _Deref_post_valid_bytecap_x_(size)) +#define _Deref_prepost_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_x_, (size), \ + _Deref_pre_opt_valid_bytecap_x_(size) _Deref_post_opt_valid_bytecap_x_(size)) -#define _Deref_prepost_count_(size) _SAL1_1_Source_(_Deref_prepost_count_, (size), _Deref_pre_count_(size) _Deref_post_count_(size)) -#define _Deref_prepost_opt_count_(size) _SAL1_1_Source_(_Deref_prepost_opt_count_, (size), _Deref_pre_opt_count_(size) _Deref_post_opt_count_(size)) -#define _Deref_prepost_bytecount_(size) _SAL1_1_Source_(_Deref_prepost_bytecount_, (size), _Deref_pre_bytecount_(size) _Deref_post_bytecount_(size)) -#define _Deref_prepost_opt_bytecount_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecount_, (size), _Deref_pre_opt_bytecount_(size) _Deref_post_opt_bytecount_(size)) +#define _Deref_prepost_count_(size) \ + _SAL1_1_Source_(_Deref_prepost_count_, (size), _Deref_pre_count_(size) _Deref_post_count_(size)) +#define _Deref_prepost_opt_count_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_count_, (size), \ + _Deref_pre_opt_count_(size) _Deref_post_opt_count_(size)) +#define _Deref_prepost_bytecount_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecount_, (size), \ + _Deref_pre_bytecount_(size) _Deref_post_bytecount_(size)) +#define _Deref_prepost_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecount_, (size), \ + _Deref_pre_opt_bytecount_(size) _Deref_post_opt_bytecount_(size)) -#define _Deref_prepost_count_x_(size) _SAL1_1_Source_(_Deref_prepost_count_x_, (size), _Deref_pre_count_x_(size) _Deref_post_count_x_(size)) -#define _Deref_prepost_opt_count_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_count_x_, (size), _Deref_pre_opt_count_x_(size) _Deref_post_opt_count_x_(size)) -#define _Deref_prepost_bytecount_x_(size) _SAL1_1_Source_(_Deref_prepost_bytecount_x_, (size), _Deref_pre_bytecount_x_(size) _Deref_post_bytecount_x_(size)) -#define _Deref_prepost_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecount_x_, (size), _Deref_pre_opt_bytecount_x_(size) _Deref_post_opt_bytecount_x_(size)) +#define _Deref_prepost_count_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_count_x_, (size), \ + _Deref_pre_count_x_(size) _Deref_post_count_x_(size)) +#define _Deref_prepost_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_count_x_, (size), \ + _Deref_pre_opt_count_x_(size) _Deref_post_opt_count_x_(size)) +#define _Deref_prepost_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecount_x_, (size), \ + _Deref_pre_bytecount_x_(size) _Deref_post_bytecount_x_(size)) +#define _Deref_prepost_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecount_x_, (size), \ + _Deref_pre_opt_bytecount_x_(size) _Deref_post_opt_bytecount_x_(size)) -#define _Deref_prepost_valid_ _SAL1_1_Source_(_Deref_prepost_valid_, (), _Deref_pre_valid_ _Deref_post_valid_) -#define _Deref_prepost_opt_valid_ _SAL1_1_Source_(_Deref_prepost_opt_valid_, (), _Deref_pre_opt_valid_ _Deref_post_opt_valid_) +#define _Deref_prepost_valid_ \ + _SAL1_1_Source_(_Deref_prepost_valid_, (), _Deref_pre_valid_ _Deref_post_valid_) +#define _Deref_prepost_opt_valid_ \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_, (), _Deref_pre_opt_valid_ _Deref_post_opt_valid_) // // _Deref_ // // used with references to arrays -#define _Deref_out_z_cap_c_(size) _SAL1_1_Source_(_Deref_out_z_cap_c_, (size), _Deref_pre_cap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_cap_c_(size) _SAL1_1_Source_(_Deref_inout_z_cap_c_, (size), _Deref_pre_z_cap_c_(size) _Deref_post_z_) -#define _Deref_out_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_out_z_bytecap_c_, (size), _Deref_pre_bytecap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_inout_z_bytecap_c_, (size), _Deref_pre_z_bytecap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_ _SAL1_1_Source_(_Deref_inout_z_, (), _Deref_prepost_z_) +#define _Deref_out_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_out_z_cap_c_, (size), _Deref_pre_cap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_inout_z_cap_c_, (size), _Deref_pre_z_cap_c_(size) _Deref_post_z_) +#define _Deref_out_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_out_z_bytecap_c_, (size), _Deref_pre_bytecap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_inout_z_bytecap_c_, (size), _Deref_pre_z_bytecap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_ _SAL1_1_Source_(_Deref_inout_z_, (), _Deref_prepost_z_) // #pragma endregion Input Buffer SAL 1 compatibility macros - //============================================================================ // Implementation Layer: //============================================================================ - // Naming conventions: // A symbol the begins with _SA_ is for the machinery of creating any // annotations; many of those come from sourceannotations.h in the case @@ -1487,141 +2545,149 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // but it does form a complete annotation; usually they are used to build // up even higher level annotations. - -#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ // Sharable "_impl" macros: these can be shared between the various annotation // forms but are part of the implementation of the macros. These are collected // here to assure that only necessary differences in the annotations // exist. -#define _Always_impl_(annos) _Group_(annos _SAL_nop_impl_) _On_failure_impl_(annos _SAL_nop_impl_) -#define _Bound_impl_ _SA_annotes0(SAL_bound) -#define _Field_range_impl_(min,max) _Range_impl_(min,max) -#define _Literal_impl_ _SA_annotes1(SAL_constant, __yes) -#define _Maybenull_impl_ _SA_annotes1(SAL_null, __maybe) -#define _Maybevalid_impl_ _SA_annotes1(SAL_valid, __maybe) +#define _Always_impl_(annos) _Group_(annos _SAL_nop_impl_) _On_failure_impl_(annos _SAL_nop_impl_) +#define _Bound_impl_ _SA_annotes0(SAL_bound) +#define _Field_range_impl_(min, max) _Range_impl_(min, max) +#define _Literal_impl_ _SA_annotes1(SAL_constant, __yes) +#define _Maybenull_impl_ _SA_annotes1(SAL_null, __maybe) +#define _Maybevalid_impl_ _SA_annotes1(SAL_valid, __maybe) #define _Must_inspect_impl_ _Post_impl_ _SA_annotes0(SAL_mustInspect) -#define _Notliteral_impl_ _SA_annotes1(SAL_constant, __no) -#define _Notnull_impl_ _SA_annotes1(SAL_null, __no) -#define _Notvalid_impl_ _SA_annotes1(SAL_valid, __no) -#define _NullNull_terminated_impl_ _Group_(_SA_annotes1(SAL_nullTerminated, __yes) _SA_annotes1(SAL_readableTo,inexpressibleCount("NullNull terminated string"))) -#define _Null_impl_ _SA_annotes1(SAL_null, __yes) -#define _Null_terminated_impl_ _SA_annotes1(SAL_nullTerminated, __yes) -#define _Out_impl_ _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ -#define _Out_opt_impl_ _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ -#define _Points_to_data_impl_ _At_(*_Curr_, _SA_annotes1(SAL_mayBePointer, __no)) -#define _Post_satisfies_impl_(cond) _Post_impl_ _Satisfies_impl_(cond) -#define _Post_valid_impl_ _Post1_impl_(__valid_impl) -#define _Pre_satisfies_impl_(cond) _Pre_impl_ _Satisfies_impl_(cond) -#define _Pre_valid_impl_ _Pre1_impl_(__valid_impl) -#define _Range_impl_(min,max) _SA_annotes2(SAL_range, min, max) -#define _Readable_bytes_impl_(size) _SA_annotes1(SAL_readableTo, byteCount(size)) -#define _Readable_elements_impl_(size) _SA_annotes1(SAL_readableTo, elementCount(size)) -#define _Ret_valid_impl_ _Ret1_impl_(__valid_impl) -#define _Satisfies_impl_(cond) _SA_annotes1(SAL_satisfies, cond) -#define _Valid_impl_ _SA_annotes1(SAL_valid, __yes) -#define _Writable_bytes_impl_(size) _SA_annotes1(SAL_writableTo, byteCount(size)) -#define _Writable_elements_impl_(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define _Notliteral_impl_ _SA_annotes1(SAL_constant, __no) +#define _Notnull_impl_ _SA_annotes1(SAL_null, __no) +#define _Notvalid_impl_ _SA_annotes1(SAL_valid, __no) +#define _NullNull_terminated_impl_ \ + _Group_(_SA_annotes1(SAL_nullTerminated, __yes) \ + _SA_annotes1(SAL_readableTo, inexpressibleCount("NullNull terminated string"))) +#define _Null_impl_ _SA_annotes1(SAL_null, __yes) +#define _Null_terminated_impl_ _SA_annotes1(SAL_nullTerminated, __yes) +#define _Out_impl_ \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ +#define _Out_opt_impl_ \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ +#define _Points_to_data_impl_ _At_(*_Curr_, _SA_annotes1(SAL_mayBePointer, __no)) +#define _Post_satisfies_impl_(cond) _Post_impl_ _Satisfies_impl_(cond) +#define _Post_valid_impl_ _Post1_impl_(__valid_impl) +#define _Pre_satisfies_impl_(cond) _Pre_impl_ _Satisfies_impl_(cond) +#define _Pre_valid_impl_ _Pre1_impl_(__valid_impl) +#define _Range_impl_(min, max) _SA_annotes2(SAL_range, min, max) +#define _Readable_bytes_impl_(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define _Readable_elements_impl_(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define _Ret_valid_impl_ _Ret1_impl_(__valid_impl) +#define _Satisfies_impl_(cond) _SA_annotes1(SAL_satisfies, cond) +#define _Valid_impl_ _SA_annotes1(SAL_valid, __yes) +#define _Writable_bytes_impl_(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define _Writable_elements_impl_(size) _SA_annotes1(SAL_writableTo, elementCount(size)) -#define _In_range_impl_(min,max) _Pre_impl_ _Range_impl_(min,max) -#define _Out_range_impl_(min,max) _Post_impl_ _Range_impl_(min,max) -#define _Ret_range_impl_(min,max) _Post_impl_ _Range_impl_(min,max) -#define _Deref_in_range_impl_(min,max) _Deref_pre_impl_ _Range_impl_(min,max) -#define _Deref_out_range_impl_(min,max) _Deref_post_impl_ _Range_impl_(min,max) -#define _Deref_ret_range_impl_(min,max) _Deref_post_impl_ _Range_impl_(min,max) +#define _In_range_impl_(min, max) _Pre_impl_ _Range_impl_(min, max) +#define _Out_range_impl_(min, max) _Post_impl_ _Range_impl_(min, max) +#define _Ret_range_impl_(min, max) _Post_impl_ _Range_impl_(min, max) +#define _Deref_in_range_impl_(min, max) _Deref_pre_impl_ _Range_impl_(min, max) +#define _Deref_out_range_impl_(min, max) _Deref_post_impl_ _Range_impl_(min, max) +#define _Deref_ret_range_impl_(min, max) _Deref_post_impl_ _Range_impl_(min, max) -#define _Deref_pre_impl_ _Pre_impl_ _Notref_impl_ _Deref_impl_ -#define _Deref_post_impl_ _Post_impl_ _Notref_impl_ _Deref_impl_ +#define _Deref_pre_impl_ _Pre_impl_ _Notref_impl_ _Deref_impl_ +#define _Deref_post_impl_ _Post_impl_ _Notref_impl_ _Deref_impl_ // The following are for the implementation machinery, and are not // suitable for annotating general code. // We're tying to phase this out, someday. The parser quotes the param. -#define __AuToQuOtE _SA_annotes0(SAL_AuToQuOtE) +#define __AuToQuOtE _SA_annotes0(SAL_AuToQuOtE) // Normally the parser does some simple type checking of annotation params, // defer that check to the plugin. -#define __deferTypecheck _SA_annotes0(SAL_deferTypecheck) +#define __deferTypecheck _SA_annotes0(SAL_deferTypecheck) -#define _SA_SPECSTRIZE( x ) #x -#define _SAL_nop_impl_ /* nothing */ -#define __nop_impl(x) x +#define _SA_SPECSTRIZE(x) #x +#define _SAL_nop_impl_ /* nothing */ +#define __nop_impl(x) x #endif - -#if _USE_ATTRIBUTES_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL // [ // Using attributes for sal #include "codeanalysis\sourceannotations.h" +#define _SA_annotes0(n) [SAL_annotes(Name = #n)] +#define _SA_annotes1(n, pp1) [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1))] +#define _SA_annotes2(n, pp1, pp2) \ + [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1), p2 = _SA_SPECSTRIZE(pp2))] +#define _SA_annotes3(n, pp1, pp2, pp3) \ + [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1), p2 = _SA_SPECSTRIZE(pp2), \ + p3 = _SA_SPECSTRIZE(pp3))] -#define _SA_annotes0(n) [SAL_annotes(Name=#n)] -#define _SA_annotes1(n,pp1) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1))] -#define _SA_annotes2(n,pp1,pp2) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1), p2=_SA_SPECSTRIZE(pp2))] -#define _SA_annotes3(n,pp1,pp2,pp3) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1), p2=_SA_SPECSTRIZE(pp2), p3=_SA_SPECSTRIZE(pp3))] - -#define _Pre_impl_ [SAL_pre] -#define _Post_impl_ [SAL_post] -#define _Deref_impl_ [SAL_deref] -#define _Notref_impl_ [SAL_notref] - +#define _Pre_impl_ [SAL_pre] +#define _Post_impl_ [SAL_post] +#define _Deref_impl_ [SAL_deref] +#define _Notref_impl_ [SAL_notref] // Declare a function to be an annotation or primop (respectively). // Done this way so that they don't appear in the regular compiler's // namespace. -#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun; -#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun; -#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; +#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun; +#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun; +#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; // Benign declspec needed here for WindowsPREfast -#define __In_impl_ [SA_Pre(Valid=SA_Yes)] [SA_Pre(Deref=1, Notref=1, Access=SA_Read)] __declspec("SAL_pre SAL_valid") +#define __In_impl_ \ + [SA_Pre(Valid = SA_Yes)][SA_Pre(Deref = 1, Notref = 1, Access = SA_Read)] \ + __declspec("SAL_pre SAL_valid") -#elif _USE_DECLSPECS_FOR_SAL // ][ +#elif _USE_DECLSPECS_FOR_SAL // ][ // Using declspecs for sal -#define _SA_annotes0(n) __declspec(#n) -#define _SA_annotes1(n,pp1) __declspec(#n "(" _SA_SPECSTRIZE(pp1) ")" ) -#define _SA_annotes2(n,pp1,pp2) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) ")") -#define _SA_annotes3(n,pp1,pp2,pp3) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) "," _SA_SPECSTRIZE(pp3) ")") +#define _SA_annotes0(n) __declspec(#n) +#define _SA_annotes1(n, pp1) __declspec(#n "(" _SA_SPECSTRIZE(pp1) ")") +#define _SA_annotes2(n, pp1, pp2) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) ")") +#define _SA_annotes3(n, pp1, pp2, pp3) \ + __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) "," _SA_SPECSTRIZE(pp3) ")") -#define _Pre_impl_ _SA_annotes0(SAL_pre) -#define _Post_impl_ _SA_annotes0(SAL_post) -#define _Deref_impl_ _SA_annotes0(SAL_deref) -#define _Notref_impl_ _SA_annotes0(SAL_notref) +#define _Pre_impl_ _SA_annotes0(SAL_pre) +#define _Post_impl_ _SA_annotes0(SAL_post) +#define _Deref_impl_ _SA_annotes0(SAL_deref) +#define _Notref_impl_ _SA_annotes0(SAL_notref) // Declare a function to be an annotation or primop (respectively). // Done this way so that they don't appear in the regular compiler's // namespace. -#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun +#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun -#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun +#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun -#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; +#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; -#define __In_impl_ _Pre_impl_ _SA_annotes0(SAL_valid) _Pre_impl_ _Deref_impl_ _Notref_impl_ _SA_annotes0(SAL_readonly) +#define __In_impl_ \ + _Pre_impl_ _SA_annotes0(SAL_valid) \ + _Pre_impl_ _Deref_impl_ _Notref_impl_ _SA_annotes0(SAL_readonly) -#else // ][ +#else // ][ // Using "nothing" for sal #define _SA_annotes0(n) -#define _SA_annotes1(n,pp1) -#define _SA_annotes2(n,pp1,pp2) -#define _SA_annotes3(n,pp1,pp2,pp3) +#define _SA_annotes1(n, pp1) +#define _SA_annotes2(n, pp1, pp2) +#define _SA_annotes3(n, pp1, pp2, pp3) #define __ANNOTATION(fun) #define __PRIMOP(type, fun) #define __QUALIFIER(type, fun) -#endif // ] +#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ // Declare annotations that need to be declared. __ANNOTATION(SAL_useHeader(void)); __ANNOTATION(SAL_bound(void)); -__ANNOTATION(SAL_allocator(void)); //??? resolve with PFD +__ANNOTATION(SAL_allocator(void)); //??? resolve with PFD __ANNOTATION(SAL_file_parser(__AuToQuOtE __In_impl_ char *, __In_impl_ char *)); __ANNOTATION(SAL_source_code_content(__In_impl_ char *)); __ANNOTATION(SAL_analysisHint(__AuToQuOtE __In_impl_ char *)); @@ -1638,7 +2704,7 @@ __ANNOTATION(SAL_post_type(__AuToQuOtE __In_impl_ char *)); __ANNOTATION(SAL_volatile(void)); __ANNOTATION(SAL_nonvolatile(void)); __ANNOTATION(SAL_entrypoint(__AuToQuOtE __In_impl_ char *, __AuToQuOtE __In_impl_ char *)); -__ANNOTATION(SAL_blocksOn(__In_impl_ void*)); +__ANNOTATION(SAL_blocksOn(__In_impl_ void *)); __ANNOTATION(SAL_mustInspect(void)); // Only appears in model files, but needs to be declared. @@ -1647,410 +2713,400 @@ __ANNOTATION(SAL_TypeName(__AuToQuOtE __In_impl_ char *)); // To be declared well-known soon. __ANNOTATION(SAL_interlocked(void);) -#pragma warning (suppress: 28227 28241) +#pragma warning(suppress : 28227 28241) __ANNOTATION(SAL_name(__In_impl_ char *, __In_impl_ char *, __In_impl_ char *);) __PRIMOP(char *, _Macro_value_(__In_impl_ char *)); __PRIMOP(int, _Macro_defined_(__In_impl_ char *)); __PRIMOP(char *, _Strstr_(__In_impl_ char *, __In_impl_ char *)); -#endif // ] +#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL // [ -#define _Check_return_impl_ [SA_Post(MustCheck=SA_Yes)] +#define _Check_return_impl_ [SA_Post(MustCheck = SA_Yes)] -#define _Success_impl_(expr) [SA_Success(Condition=#expr)] -#define _On_failure_impl_(annos) [SAL_context(p1="SAL_failed")] _Group_(_Post_impl_ _Group_(annos _SAL_nop_impl_)) +#define _Success_impl_(expr) [SA_Success(Condition = #expr)] +#define _On_failure_impl_(annos) \ + [SAL_context(p1 = "SAL_failed")] _Group_(_Post_impl_ _Group_(annos _SAL_nop_impl_)) -#define _Printf_format_string_impl_ [SA_FormatString(Style="printf")] -#define _Scanf_format_string_impl_ [SA_FormatString(Style="scanf")] -#define _Scanf_s_format_string_impl_ [SA_FormatString(Style="scanf_s")] +#define _Printf_format_string_impl_ [SA_FormatString(Style = "printf")] +#define _Scanf_format_string_impl_ [SA_FormatString(Style = "scanf")] +#define _Scanf_s_format_string_impl_ [SA_FormatString(Style = "scanf_s")] -#define _In_bound_impl_ [SA_PreBound(Deref=0)] -#define _Out_bound_impl_ [SA_PostBound(Deref=0)] -#define _Ret_bound_impl_ [SA_PostBound(Deref=0)] -#define _Deref_in_bound_impl_ [SA_PreBound(Deref=1)] -#define _Deref_out_bound_impl_ [SA_PostBound(Deref=1)] -#define _Deref_ret_bound_impl_ [SA_PostBound(Deref=1)] +#define _In_bound_impl_ [SA_PreBound(Deref = 0)] +#define _Out_bound_impl_ [SA_PostBound(Deref = 0)] +#define _Ret_bound_impl_ [SA_PostBound(Deref = 0)] +#define _Deref_in_bound_impl_ [SA_PreBound(Deref = 1)] +#define _Deref_out_bound_impl_ [SA_PostBound(Deref = 1)] +#define _Deref_ret_bound_impl_ [SA_PostBound(Deref = 1)] -#define __valid_impl Valid=SA_Yes -#define __maybevalid_impl Valid=SA_Maybe -#define __notvalid_impl Valid=SA_No +#define __valid_impl Valid = SA_Yes +#define __maybevalid_impl Valid = SA_Maybe +#define __notvalid_impl Valid = SA_No -#define __null_impl Null=SA_Yes -#define __maybenull_impl Null=SA_Maybe -#define __notnull_impl Null=SA_No +#define __null_impl Null = SA_Yes +#define __maybenull_impl Null = SA_Maybe +#define __notnull_impl Null = SA_No -#define __null_impl_notref Null=SA_Yes,Notref=1 -#define __maybenull_impl_notref Null=SA_Maybe,Notref=1 -#define __notnull_impl_notref Null=SA_No,Notref=1 +#define __null_impl_notref Null = SA_Yes, Notref = 1 +#define __maybenull_impl_notref Null = SA_Maybe, Notref = 1 +#define __notnull_impl_notref Null = SA_No, Notref = 1 -#define __zterm_impl NullTerminated=SA_Yes -#define __maybezterm_impl NullTerminated=SA_Maybe -#define __maybzterm_impl NullTerminated=SA_Maybe -#define __notzterm_impl NullTerminated=SA_No +#define __zterm_impl NullTerminated = SA_Yes +#define __maybezterm_impl NullTerminated = SA_Maybe +#define __maybzterm_impl NullTerminated = SA_Maybe +#define __notzterm_impl NullTerminated = SA_No -#define __readaccess_impl Access=SA_Read -#define __writeaccess_impl Access=SA_Write -#define __allaccess_impl Access=SA_ReadWrite +#define __readaccess_impl Access = SA_Read +#define __writeaccess_impl Access = SA_Write +#define __allaccess_impl Access = SA_ReadWrite -#define __readaccess_impl_notref Access=SA_Read,Notref=1 -#define __writeaccess_impl_notref Access=SA_Write,Notref=1 -#define __allaccess_impl_notref Access=SA_ReadWrite,Notref=1 +#define __readaccess_impl_notref Access = SA_Read, Notref = 1 +#define __writeaccess_impl_notref Access = SA_Write, Notref = 1 +#define __allaccess_impl_notref Access = SA_ReadWrite, Notref = 1 -#if _MSC_VER >= 1610 /*IFSTRIP=IGN*/ // [ +#if _MSC_VER >= 1610 /*IFSTRIP=IGN*/ // [ // For SAL2, we need to expect general expressions. -#define __cap_impl(size) WritableElements="\n"#size -#define __bytecap_impl(size) WritableBytes="\n"#size -#define __bytecount_impl(size) ValidBytes="\n"#size -#define __count_impl(size) ValidElements="\n"#size +#define __cap_impl(size) WritableElements = "\n" #size +#define __bytecap_impl(size) WritableBytes = "\n" #size +#define __bytecount_impl(size) ValidBytes = "\n" #size +#define __count_impl(size) ValidElements = "\n" #size -#else // ][ +#else // ][ -#define __cap_impl(size) WritableElements=#size -#define __bytecap_impl(size) WritableBytes=#size -#define __bytecount_impl(size) ValidBytes=#size -#define __count_impl(size) ValidElements=#size +#define __cap_impl(size) WritableElements = #size +#define __bytecap_impl(size) WritableBytes = #size +#define __bytecount_impl(size) ValidBytes = #size +#define __count_impl(size) ValidElements = #size -#endif // ] +#endif // ] -#define __cap_c_impl(size) WritableElementsConst=size -#define __cap_c_one_notref_impl WritableElementsConst=1,Notref=1 -#define __cap_for_impl(param) WritableElementsLength=#param -#define __cap_x_impl(size) WritableElements="\n@"#size +#define __cap_c_impl(size) WritableElementsConst = size +#define __cap_c_one_notref_impl WritableElementsConst = 1, Notref = 1 +#define __cap_for_impl(param) WritableElementsLength = #param +#define __cap_x_impl(size) WritableElements = "\n@" #size -#define __bytecap_c_impl(size) WritableBytesConst=size -#define __bytecap_x_impl(size) WritableBytes="\n@"#size +#define __bytecap_c_impl(size) WritableBytesConst = size +#define __bytecap_x_impl(size) WritableBytes = "\n@" #size -#define __mult_impl(mult,size) __cap_impl((mult)*(size)) +#define __mult_impl(mult, size) __cap_impl((mult) * (size)) -#define __count_c_impl(size) ValidElementsConst=size -#define __count_x_impl(size) ValidElements="\n@"#size +#define __count_c_impl(size) ValidElementsConst = size +#define __count_x_impl(size) ValidElements = "\n@" #size -#define __bytecount_c_impl(size) ValidBytesConst=size -#define __bytecount_x_impl(size) ValidBytes="\n@"#size +#define __bytecount_c_impl(size) ValidBytesConst = size +#define __bytecount_x_impl(size) ValidBytes = "\n@" #size +#define _At_impl_(target, annos) [SAL_at(p1 = #target)] _Group_(annos) +#define _At_buffer_impl_(target, iter, bound, annos) \ + [SAL_at_buffer(p1 = #target, p2 = #iter, p3 = #bound)] _Group_(annos) +#define _When_impl_(expr, annos) [SAL_when(p1 = #expr)] _Group_(annos) -#define _At_impl_(target, annos) [SAL_at(p1=#target)] _Group_(annos) -#define _At_buffer_impl_(target, iter, bound, annos) [SAL_at_buffer(p1=#target, p2=#iter, p3=#bound)] _Group_(annos) -#define _When_impl_(expr, annos) [SAL_when(p1=#expr)] _Group_(annos) +#define _Group_impl_(annos) [SAL_begin] annos[SAL_end] +#define _GrouP_impl_(annos) [SAL_BEGIN] annos[SAL_END] -#define _Group_impl_(annos) [SAL_begin] annos [SAL_end] -#define _GrouP_impl_(annos) [SAL_BEGIN] annos [SAL_END] +#define _Use_decl_anno_impl_ _SA_annotes0(SAL_useHeader) // this is a special case! -#define _Use_decl_anno_impl_ _SA_annotes0(SAL_useHeader) // this is a special case! +#define _Pre1_impl_(p1) [SA_Pre(p1)] +#define _Pre2_impl_(p1, p2) [SA_Pre(p1, p2)] +#define _Pre3_impl_(p1, p2, p3) [SA_Pre(p1, p2, p3)] -#define _Pre1_impl_(p1) [SA_Pre(p1)] -#define _Pre2_impl_(p1,p2) [SA_Pre(p1,p2)] -#define _Pre3_impl_(p1,p2,p3) [SA_Pre(p1,p2,p3)] +#define _Post1_impl_(p1) [SA_Post(p1)] +#define _Post2_impl_(p1, p2) [SA_Post(p1, p2)] +#define _Post3_impl_(p1, p2, p3) [SA_Post(p1, p2, p3)] -#define _Post1_impl_(p1) [SA_Post(p1)] -#define _Post2_impl_(p1,p2) [SA_Post(p1,p2)] -#define _Post3_impl_(p1,p2,p3) [SA_Post(p1,p2,p3)] +#define _Ret1_impl_(p1) [SA_Post(p1)] +#define _Ret2_impl_(p1, p2) [SA_Post(p1, p2)] +#define _Ret3_impl_(p1, p2, p3) [SA_Post(p1, p2, p3)] -#define _Ret1_impl_(p1) [SA_Post(p1)] -#define _Ret2_impl_(p1,p2) [SA_Post(p1,p2)] -#define _Ret3_impl_(p1,p2,p3) [SA_Post(p1,p2,p3)] +#define _Deref_pre1_impl_(p1) [SA_Pre(Deref = 1, p1)] +#define _Deref_pre2_impl_(p1, p2) [SA_Pre(Deref = 1, p1, p2)] +#define _Deref_pre3_impl_(p1, p2, p3) [SA_Pre(Deref = 1, p1, p2, p3)] -#define _Deref_pre1_impl_(p1) [SA_Pre(Deref=1,p1)] -#define _Deref_pre2_impl_(p1,p2) [SA_Pre(Deref=1,p1,p2)] -#define _Deref_pre3_impl_(p1,p2,p3) [SA_Pre(Deref=1,p1,p2,p3)] +#define _Deref_post1_impl_(p1) [SA_Post(Deref = 1, p1)] +#define _Deref_post2_impl_(p1, p2) [SA_Post(Deref = 1, p1, p2)] +#define _Deref_post3_impl_(p1, p2, p3) [SA_Post(Deref = 1, p1, p2, p3)] +#define _Deref_ret1_impl_(p1) [SA_Post(Deref = 1, p1)] +#define _Deref_ret2_impl_(p1, p2) [SA_Post(Deref = 1, p1, p2)] +#define _Deref_ret3_impl_(p1, p2, p3) [SA_Post(Deref = 1, p1, p2, p3)] -#define _Deref_post1_impl_(p1) [SA_Post(Deref=1,p1)] -#define _Deref_post2_impl_(p1,p2) [SA_Post(Deref=1,p1,p2)] -#define _Deref_post3_impl_(p1,p2,p3) [SA_Post(Deref=1,p1,p2,p3)] - -#define _Deref_ret1_impl_(p1) [SA_Post(Deref=1,p1)] -#define _Deref_ret2_impl_(p1,p2) [SA_Post(Deref=1,p1,p2)] -#define _Deref_ret3_impl_(p1,p2,p3) [SA_Post(Deref=1,p1,p2,p3)] - -#define _Deref2_pre1_impl_(p1) [SA_Pre(Deref=2,Notref=1,p1)] -#define _Deref2_post1_impl_(p1) [SA_Post(Deref=2,Notref=1,p1)] -#define _Deref2_ret1_impl_(p1) [SA_Post(Deref=2,Notref=1,p1)] +#define _Deref2_pre1_impl_(p1) [SA_Pre(Deref = 2, Notref = 1, p1)] +#define _Deref2_post1_impl_(p1) [SA_Post(Deref = 2, Notref = 1, p1)] +#define _Deref2_ret1_impl_(p1) [SA_Post(Deref = 2, Notref = 1, p1)] // Obsolete -- may be needed for transition to attributes. -#define __inner_typefix(ctype) [SAL_typefix(p1=_SA_SPECSTRIZE(ctype))] -#define __inner_exceptthat [SAL_except] +#define __inner_typefix(ctype) [SAL_typefix(p1 = _SA_SPECSTRIZE(ctype))] +#define __inner_exceptthat [SAL_except] +#elif _USE_DECLSPECS_FOR_SAL // ][ -#elif _USE_DECLSPECS_FOR_SAL // ][ +#define _Check_return_impl_ __post _SA_annotes0(SAL_checkReturn) -#define _Check_return_impl_ __post _SA_annotes0(SAL_checkReturn) +#define _Success_impl_(expr) _SA_annotes1(SAL_success, expr) +#define _On_failure_impl_(annos) \ + _SA_annotes1(SAL_context, SAL_failed) _Group_(_Post_impl_ _Group_(_SAL_nop_impl_ annos)) -#define _Success_impl_(expr) _SA_annotes1(SAL_success, expr) -#define _On_failure_impl_(annos) _SA_annotes1(SAL_context, SAL_failed) _Group_(_Post_impl_ _Group_(_SAL_nop_impl_ annos)) +#define _Printf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "printf") +#define _Scanf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf") +#define _Scanf_s_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf_s") -#define _Printf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "printf") -#define _Scanf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf") -#define _Scanf_s_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf_s") +#define _In_bound_impl_ _Pre_impl_ _Bound_impl_ +#define _Out_bound_impl_ _Post_impl_ _Bound_impl_ +#define _Ret_bound_impl_ _Post_impl_ _Bound_impl_ +#define _Deref_in_bound_impl_ _Deref_pre_impl_ _Bound_impl_ +#define _Deref_out_bound_impl_ _Deref_post_impl_ _Bound_impl_ +#define _Deref_ret_bound_impl_ _Deref_post_impl_ _Bound_impl_ -#define _In_bound_impl_ _Pre_impl_ _Bound_impl_ -#define _Out_bound_impl_ _Post_impl_ _Bound_impl_ -#define _Ret_bound_impl_ _Post_impl_ _Bound_impl_ -#define _Deref_in_bound_impl_ _Deref_pre_impl_ _Bound_impl_ -#define _Deref_out_bound_impl_ _Deref_post_impl_ _Bound_impl_ -#define _Deref_ret_bound_impl_ _Deref_post_impl_ _Bound_impl_ +#define __null_impl _SA_annotes0(SAL_null) // _SA_annotes1(SAL_null, __yes) +#define __notnull_impl _SA_annotes0(SAL_notnull) // _SA_annotes1(SAL_null, __no) +#define __maybenull_impl _SA_annotes0(SAL_maybenull) // _SA_annotes1(SAL_null, __maybe) +#define __valid_impl _SA_annotes0(SAL_valid) // _SA_annotes1(SAL_valid, __yes) +#define __notvalid_impl _SA_annotes0(SAL_notvalid) // _SA_annotes1(SAL_valid, __no) +#define __maybevalid_impl _SA_annotes0(SAL_maybevalid) // _SA_annotes1(SAL_valid, __maybe) -#define __null_impl _SA_annotes0(SAL_null) // _SA_annotes1(SAL_null, __yes) -#define __notnull_impl _SA_annotes0(SAL_notnull) // _SA_annotes1(SAL_null, __no) -#define __maybenull_impl _SA_annotes0(SAL_maybenull) // _SA_annotes1(SAL_null, __maybe) +#define __null_impl_notref _Notref_ _Null_impl_ +#define __maybenull_impl_notref _Notref_ _Maybenull_impl_ +#define __notnull_impl_notref _Notref_ _Notnull_impl_ -#define __valid_impl _SA_annotes0(SAL_valid) // _SA_annotes1(SAL_valid, __yes) -#define __notvalid_impl _SA_annotes0(SAL_notvalid) // _SA_annotes1(SAL_valid, __no) -#define __maybevalid_impl _SA_annotes0(SAL_maybevalid) // _SA_annotes1(SAL_valid, __maybe) +#define __zterm_impl _SA_annotes1(SAL_nullTerminated, __yes) +#define __maybezterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) +#define __maybzterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) +#define __notzterm_impl _SA_annotes1(SAL_nullTerminated, __no) -#define __null_impl_notref _Notref_ _Null_impl_ -#define __maybenull_impl_notref _Notref_ _Maybenull_impl_ -#define __notnull_impl_notref _Notref_ _Notnull_impl_ +#define __readaccess_impl _SA_annotes1(SAL_access, 0x1) +#define __writeaccess_impl _SA_annotes1(SAL_access, 0x2) +#define __allaccess_impl _SA_annotes1(SAL_access, 0x3) -#define __zterm_impl _SA_annotes1(SAL_nullTerminated, __yes) -#define __maybezterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) -#define __maybzterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) -#define __notzterm_impl _SA_annotes1(SAL_nullTerminated, __no) - -#define __readaccess_impl _SA_annotes1(SAL_access, 0x1) -#define __writeaccess_impl _SA_annotes1(SAL_access, 0x2) -#define __allaccess_impl _SA_annotes1(SAL_access, 0x3) - -#define __readaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x1) +#define __readaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x1) #define __writeaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x2) -#define __allaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x3) +#define __allaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x3) -#define __cap_impl(size) _SA_annotes1(SAL_writableTo,elementCount(size)) -#define __cap_c_impl(size) _SA_annotes1(SAL_writableTo,elementCount(size)) -#define __cap_c_one_notref_impl _Notref_ _SA_annotes1(SAL_writableTo,elementCount(1)) -#define __cap_for_impl(param) _SA_annotes1(SAL_writableTo,inexpressibleCount(sizeof(param))) -#define __cap_x_impl(size) _SA_annotes1(SAL_writableTo,inexpressibleCount(#size)) +#define __cap_impl(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define __cap_c_impl(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define __cap_c_one_notref_impl _Notref_ _SA_annotes1(SAL_writableTo, elementCount(1)) +#define __cap_for_impl(param) _SA_annotes1(SAL_writableTo, inexpressibleCount(sizeof(param))) +#define __cap_x_impl(size) _SA_annotes1(SAL_writableTo, inexpressibleCount(#size)) -#define __bytecap_impl(size) _SA_annotes1(SAL_writableTo,byteCount(size)) -#define __bytecap_c_impl(size) _SA_annotes1(SAL_writableTo,byteCount(size)) -#define __bytecap_x_impl(size) _SA_annotes1(SAL_writableTo,inexpressibleCount(#size)) +#define __bytecap_impl(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define __bytecap_c_impl(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define __bytecap_x_impl(size) _SA_annotes1(SAL_writableTo, inexpressibleCount(#size)) -#define __mult_impl(mult,size) _SA_annotes1(SAL_writableTo,(mult)*(size)) +#define __mult_impl(mult, size) _SA_annotes1(SAL_writableTo, (mult) * (size)) -#define __count_impl(size) _SA_annotes1(SAL_readableTo,elementCount(size)) -#define __count_c_impl(size) _SA_annotes1(SAL_readableTo,elementCount(size)) -#define __count_x_impl(size) _SA_annotes1(SAL_readableTo,inexpressibleCount(#size)) +#define __count_impl(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define __count_c_impl(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define __count_x_impl(size) _SA_annotes1(SAL_readableTo, inexpressibleCount(#size)) -#define __bytecount_impl(size) _SA_annotes1(SAL_readableTo,byteCount(size)) -#define __bytecount_c_impl(size) _SA_annotes1(SAL_readableTo,byteCount(size)) -#define __bytecount_x_impl(size) _SA_annotes1(SAL_readableTo,inexpressibleCount(#size)) +#define __bytecount_impl(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define __bytecount_c_impl(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define __bytecount_x_impl(size) _SA_annotes1(SAL_readableTo, inexpressibleCount(#size)) -#define _At_impl_(target, annos) _SA_annotes0(SAL_at(target)) _Group_(annos) -#define _At_buffer_impl_(target, iter, bound, annos) _SA_annotes3(SAL_at_buffer, target, iter, bound) _Group_(annos) -#define _Group_impl_(annos) _SA_annotes0(SAL_begin) annos _SA_annotes0(SAL_end) -#define _GrouP_impl_(annos) _SA_annotes0(SAL_BEGIN) annos _SA_annotes0(SAL_END) -#define _When_impl_(expr, annos) _SA_annotes0(SAL_when(expr)) _Group_(annos) +#define _At_impl_(target, annos) _SA_annotes0(SAL_at(target)) _Group_(annos) +#define _At_buffer_impl_(target, iter, bound, annos) \ + _SA_annotes3(SAL_at_buffer, target, iter, bound) _Group_(annos) +#define _Group_impl_(annos) _SA_annotes0(SAL_begin) annos _SA_annotes0(SAL_end) +#define _GrouP_impl_(annos) _SA_annotes0(SAL_BEGIN) annos _SA_annotes0(SAL_END) +#define _When_impl_(expr, annos) _SA_annotes0(SAL_when(expr)) _Group_(annos) -#define _Use_decl_anno_impl_ __declspec("SAL_useHeader()") // this is a special case! +#define _Use_decl_anno_impl_ __declspec("SAL_useHeader()") // this is a special case! -#define _Pre1_impl_(p1) _Pre_impl_ p1 -#define _Pre2_impl_(p1,p2) _Pre_impl_ p1 _Pre_impl_ p2 -#define _Pre3_impl_(p1,p2,p3) _Pre_impl_ p1 _Pre_impl_ p2 _Pre_impl_ p3 +#define _Pre1_impl_(p1) _Pre_impl_ p1 +#define _Pre2_impl_(p1, p2) _Pre_impl_ p1 _Pre_impl_ p2 +#define _Pre3_impl_(p1, p2, p3) _Pre_impl_ p1 _Pre_impl_ p2 _Pre_impl_ p3 -#define _Post1_impl_(p1) _Post_impl_ p1 -#define _Post2_impl_(p1,p2) _Post_impl_ p1 _Post_impl_ p2 -#define _Post3_impl_(p1,p2,p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 +#define _Post1_impl_(p1) _Post_impl_ p1 +#define _Post2_impl_(p1, p2) _Post_impl_ p1 _Post_impl_ p2 +#define _Post3_impl_(p1, p2, p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 -#define _Ret1_impl_(p1) _Post_impl_ p1 -#define _Ret2_impl_(p1,p2) _Post_impl_ p1 _Post_impl_ p2 -#define _Ret3_impl_(p1,p2,p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 +#define _Ret1_impl_(p1) _Post_impl_ p1 +#define _Ret2_impl_(p1, p2) _Post_impl_ p1 _Post_impl_ p2 +#define _Ret3_impl_(p1, p2, p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 -#define _Deref_pre1_impl_(p1) _Deref_pre_impl_ p1 -#define _Deref_pre2_impl_(p1,p2) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 -#define _Deref_pre3_impl_(p1,p2,p3) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 _Deref_pre_impl_ p3 +#define _Deref_pre1_impl_(p1) _Deref_pre_impl_ p1 +#define _Deref_pre2_impl_(p1, p2) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 +#define _Deref_pre3_impl_(p1, p2, p3) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 _Deref_pre_impl_ p3 -#define _Deref_post1_impl_(p1) _Deref_post_impl_ p1 -#define _Deref_post2_impl_(p1,p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 -#define _Deref_post3_impl_(p1,p2,p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 +#define _Deref_post1_impl_(p1) _Deref_post_impl_ p1 +#define _Deref_post2_impl_(p1, p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 +#define _Deref_post3_impl_(p1, p2, p3) \ + _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 -#define _Deref_ret1_impl_(p1) _Deref_post_impl_ p1 -#define _Deref_ret2_impl_(p1,p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 -#define _Deref_ret3_impl_(p1,p2,p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 +#define _Deref_ret1_impl_(p1) _Deref_post_impl_ p1 +#define _Deref_ret2_impl_(p1, p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 +#define _Deref_ret3_impl_(p1, p2, p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 -#define _Deref2_pre1_impl_(p1) _Deref_pre_impl_ _Notref_impl_ _Deref_impl_ p1 -#define _Deref2_post1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 -#define _Deref2_ret1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_pre1_impl_(p1) _Deref_pre_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_post1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_ret1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 -#define __inner_typefix(ctype) _SA_annotes1(SAL_typefix, ctype) -#define __inner_exceptthat _SA_annotes0(SAL_except) +#define __inner_typefix(ctype) _SA_annotes1(SAL_typefix, ctype) +#define __inner_exceptthat _SA_annotes0(SAL_except) -#elif defined(_MSC_EXTENSIONS) && !defined( MIDL_PASS ) && !defined(__midl) && !defined(RC_INVOKED) && defined(_PFT_VER) && _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // ][ +#elif defined(_MSC_EXTENSIONS) && !defined(MIDL_PASS) && !defined(__midl) && \ + !defined(RC_INVOKED) && defined(_PFT_VER) && _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // ][ // minimum attribute expansion for foreground build -#pragma push_macro( "SA" ) -#pragma push_macro( "REPEATABLE" ) +#pragma push_macro("SA") +#pragma push_macro("REPEATABLE") -#ifdef __cplusplus // [ -#define SA( id ) id +#ifdef __cplusplus // [ +#define SA(id) id #define REPEATABLE [repeatable] #else // !__cplusplus // ][ -#define SA( id ) SA_##id +#define SA(id) SA_##id #define REPEATABLE -#endif // !__cplusplus // ] +#endif // !__cplusplus // ] REPEATABLE -[source_annotation_attribute( SA( Parameter ) )] -struct __P_impl -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Parameter))] struct __P_impl { +#ifdef __cplusplus // [ __P_impl(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __P_impl __P_impl; REPEATABLE -[source_annotation_attribute( SA( ReturnValue ) )] -struct __R_impl -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(ReturnValue))] struct __R_impl { +#ifdef __cplusplus // [ __R_impl(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __R_impl __R_impl; -[source_annotation_attribute( SA( Method ) )] -struct __M_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Method))] struct __M_ { +#ifdef __cplusplus // [ __M_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __M_ __M_; -[source_annotation_attribute( SA( All ) )] -struct __A_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(All))] struct __A_ { +#ifdef __cplusplus // [ __A_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __A_ __A_; -[source_annotation_attribute( SA( Field ) )] -struct __F_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Field))] struct __F_ { +#ifdef __cplusplus // [ __F_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __F_ __F_; -#pragma pop_macro( "REPEATABLE" ) -#pragma pop_macro( "SA" ) - +#pragma pop_macro("REPEATABLE") +#pragma pop_macro("SA") #define _SAL_nop_impl_ -#define _At_impl_(target, annos) [__A_(__d_=0)] -#define _At_buffer_impl_(target, iter, bound, annos) [__A_(__d_=0)] -#define _When_impl_(expr, annos) annos -#define _Group_impl_(annos) annos -#define _GrouP_impl_(annos) annos -#define _Use_decl_anno_impl_ [__M_(__d_=0)] +#define _At_impl_(target, annos) [__A_(__d_ = 0)] +#define _At_buffer_impl_(target, iter, bound, annos) [__A_(__d_ = 0)] +#define _When_impl_(expr, annos) annos +#define _Group_impl_(annos) annos +#define _GrouP_impl_(annos) annos +#define _Use_decl_anno_impl_ [__M_(__d_ = 0)] -#define _Points_to_data_impl_ [__P_impl(__d_=0)] -#define _Literal_impl_ [__P_impl(__d_=0)] -#define _Notliteral_impl_ [__P_impl(__d_=0)] +#define _Points_to_data_impl_ [__P_impl(__d_ = 0)] +#define _Literal_impl_ [__P_impl(__d_ = 0)] +#define _Notliteral_impl_ [__P_impl(__d_ = 0)] -#define _Pre_valid_impl_ [__P_impl(__d_=0)] -#define _Post_valid_impl_ [__P_impl(__d_=0)] -#define _Ret_valid_impl_ [__R_impl(__d_=0)] +#define _Pre_valid_impl_ [__P_impl(__d_ = 0)] +#define _Post_valid_impl_ [__P_impl(__d_ = 0)] +#define _Ret_valid_impl_ [__R_impl(__d_ = 0)] -#define _Check_return_impl_ [__R_impl(__d_=0)] -#define _Must_inspect_impl_ [__R_impl(__d_=0)] +#define _Check_return_impl_ [__R_impl(__d_ = 0)] +#define _Must_inspect_impl_ [__R_impl(__d_ = 0)] -#define _Success_impl_(expr) [__M_(__d_=0)] -#define _On_failure_impl_(expr) [__M_(__d_=0)] -#define _Always_impl_(expr) [__M_(__d_=0)] +#define _Success_impl_(expr) [__M_(__d_ = 0)] +#define _On_failure_impl_(expr) [__M_(__d_ = 0)] +#define _Always_impl_(expr) [__M_(__d_ = 0)] -#define _Printf_format_string_impl_ [__P_impl(__d_=0)] -#define _Scanf_format_string_impl_ [__P_impl(__d_=0)] -#define _Scanf_s_format_string_impl_ [__P_impl(__d_=0)] +#define _Printf_format_string_impl_ [__P_impl(__d_ = 0)] +#define _Scanf_format_string_impl_ [__P_impl(__d_ = 0)] +#define _Scanf_s_format_string_impl_ [__P_impl(__d_ = 0)] -#define _Raises_SEH_exception_impl_ [__M_(__d_=0)] -#define _Maybe_raises_SEH_exception_impl_ [__M_(__d_=0)] +#define _Raises_SEH_exception_impl_ [__M_(__d_ = 0)] +#define _Maybe_raises_SEH_exception_impl_ [__M_(__d_ = 0)] -#define _In_bound_impl_ [__P_impl(__d_=0)] -#define _Out_bound_impl_ [__P_impl(__d_=0)] -#define _Ret_bound_impl_ [__R_impl(__d_=0)] -#define _Deref_in_bound_impl_ [__P_impl(__d_=0)] -#define _Deref_out_bound_impl_ [__P_impl(__d_=0)] -#define _Deref_ret_bound_impl_ [__R_impl(__d_=0)] +#define _In_bound_impl_ [__P_impl(__d_ = 0)] +#define _Out_bound_impl_ [__P_impl(__d_ = 0)] +#define _Ret_bound_impl_ [__R_impl(__d_ = 0)] +#define _Deref_in_bound_impl_ [__P_impl(__d_ = 0)] +#define _Deref_out_bound_impl_ [__P_impl(__d_ = 0)] +#define _Deref_ret_bound_impl_ [__R_impl(__d_ = 0)] -#define _Range_impl_(min,max) [__P_impl(__d_=0)] -#define _In_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Out_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Ret_range_impl_(min,max) [__R_impl(__d_=0)] -#define _Deref_in_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Deref_out_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Deref_ret_range_impl_(min,max) [__R_impl(__d_=0)] +#define _Range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _In_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Out_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Ret_range_impl_(min, max) [__R_impl(__d_ = 0)] +#define _Deref_in_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Deref_out_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Deref_ret_range_impl_(min, max) [__R_impl(__d_ = 0)] -#define _Field_range_impl_(min,max) [__F_(__d_=0)] +#define _Field_range_impl_(min, max) [__F_(__d_ = 0)] -#define _Pre_satisfies_impl_(cond) [__A_(__d_=0)] -#define _Post_satisfies_impl_(cond) [__A_(__d_=0)] -#define _Satisfies_impl_(cond) [__A_(__d_=0)] +#define _Pre_satisfies_impl_(cond) [__A_(__d_ = 0)] +#define _Post_satisfies_impl_(cond) [__A_(__d_ = 0)] +#define _Satisfies_impl_(cond) [__A_(__d_ = 0)] -#define _Null_impl_ [__A_(__d_=0)] -#define _Notnull_impl_ [__A_(__d_=0)] -#define _Maybenull_impl_ [__A_(__d_=0)] +#define _Null_impl_ [__A_(__d_ = 0)] +#define _Notnull_impl_ [__A_(__d_ = 0)] +#define _Maybenull_impl_ [__A_(__d_ = 0)] -#define _Valid_impl_ [__A_(__d_=0)] -#define _Notvalid_impl_ [__A_(__d_=0)] -#define _Maybevalid_impl_ [__A_(__d_=0)] +#define _Valid_impl_ [__A_(__d_ = 0)] +#define _Notvalid_impl_ [__A_(__d_ = 0)] +#define _Maybevalid_impl_ [__A_(__d_ = 0)] -#define _Readable_bytes_impl_(size) [__A_(__d_=0)] -#define _Readable_elements_impl_(size) [__A_(__d_=0)] -#define _Writable_bytes_impl_(size) [__A_(__d_=0)] -#define _Writable_elements_impl_(size) [__A_(__d_=0)] +#define _Readable_bytes_impl_(size) [__A_(__d_ = 0)] +#define _Readable_elements_impl_(size) [__A_(__d_ = 0)] +#define _Writable_bytes_impl_(size) [__A_(__d_ = 0)] +#define _Writable_elements_impl_(size) [__A_(__d_ = 0)] -#define _Null_terminated_impl_ [__A_(__d_=0)] -#define _NullNull_terminated_impl_ [__A_(__d_=0)] +#define _Null_terminated_impl_ [__A_(__d_ = 0)] +#define _NullNull_terminated_impl_ [__A_(__d_ = 0)] -#define _Pre_impl_ [__P_impl(__d_=0)] -#define _Pre1_impl_(p1) [__P_impl(__d_=0)] -#define _Pre2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Pre3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Pre_impl_ [__P_impl(__d_ = 0)] +#define _Pre1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Pre2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Pre3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Post_impl_ [__P_impl(__d_=0)] -#define _Post1_impl_(p1) [__P_impl(__d_=0)] -#define _Post2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Post3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Post_impl_ [__P_impl(__d_ = 0)] +#define _Post1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Post2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Post3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Ret1_impl_(p1) [__R_impl(__d_=0)] -#define _Ret2_impl_(p1,p2) [__R_impl(__d_=0)] -#define _Ret3_impl_(p1,p2,p3) [__R_impl(__d_=0)] +#define _Ret1_impl_(p1) [__R_impl(__d_ = 0)] +#define _Ret2_impl_(p1, p2) [__R_impl(__d_ = 0)] +#define _Ret3_impl_(p1, p2, p3) [__R_impl(__d_ = 0)] -#define _Deref_pre1_impl_(p1) [__P_impl(__d_=0)] -#define _Deref_pre2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Deref_pre3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Deref_pre1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Deref_pre2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Deref_pre3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Deref_post1_impl_(p1) [__P_impl(__d_=0)] -#define _Deref_post2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Deref_post3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Deref_post1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Deref_post2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Deref_post3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Deref_ret1_impl_(p1) [__R_impl(__d_=0)] -#define _Deref_ret2_impl_(p1,p2) [__R_impl(__d_=0)] -#define _Deref_ret3_impl_(p1,p2,p3) [__R_impl(__d_=0)] +#define _Deref_ret1_impl_(p1) [__R_impl(__d_ = 0)] +#define _Deref_ret2_impl_(p1, p2) [__R_impl(__d_ = 0)] +#define _Deref_ret3_impl_(p1, p2, p3) [__R_impl(__d_ = 0)] -#define _Deref2_pre1_impl_(p1) //[__P_impl(__d_=0)] -#define _Deref2_post1_impl_(p1) //[__P_impl(__d_=0)] -#define _Deref2_ret1_impl_(p1) //[__P_impl(__d_=0)] - -#else // ][ +#define _Deref2_pre1_impl_(p1) //[__P_impl(__d_=0)] +#define _Deref2_post1_impl_(p1) //[__P_impl(__d_=0)] +#define _Deref2_ret1_impl_(p1) //[__P_impl(__d_=0)] +#else // ][ #define _SAL_nop_impl_ X @@ -2087,13 +3143,13 @@ typedef struct __F_ __F_; #define _Deref_out_bound_impl_ #define _Deref_ret_bound_impl_ -#define _Range_impl_(min,max) -#define _In_range_impl_(min,max) -#define _Out_range_impl_(min,max) -#define _Ret_range_impl_(min,max) -#define _Deref_in_range_impl_(min,max) -#define _Deref_out_range_impl_(min,max) -#define _Deref_ret_range_impl_(min,max) +#define _Range_impl_(min, max) +#define _In_range_impl_(min, max) +#define _Out_range_impl_(min, max) +#define _Ret_range_impl_(min, max) +#define _Deref_in_range_impl_(min, max) +#define _Deref_out_range_impl_(min, max) +#define _Deref_ret_range_impl_(min, max) #define _Satisfies_impl_(expr) #define _Pre_satisfies_impl_(expr) @@ -2107,33 +3163,33 @@ typedef struct __F_ __F_; #define _Notvalid_impl_ #define _Maybevalid_impl_ -#define _Field_range_impl_(min,max) +#define _Field_range_impl_(min, max) #define _Pre_impl_ #define _Pre1_impl_(p1) -#define _Pre2_impl_(p1,p2) -#define _Pre3_impl_(p1,p2,p3) +#define _Pre2_impl_(p1, p2) +#define _Pre3_impl_(p1, p2, p3) #define _Post_impl_ #define _Post1_impl_(p1) -#define _Post2_impl_(p1,p2) -#define _Post3_impl_(p1,p2,p3) +#define _Post2_impl_(p1, p2) +#define _Post3_impl_(p1, p2, p3) #define _Ret1_impl_(p1) -#define _Ret2_impl_(p1,p2) -#define _Ret3_impl_(p1,p2,p3) +#define _Ret2_impl_(p1, p2) +#define _Ret3_impl_(p1, p2, p3) #define _Deref_pre1_impl_(p1) -#define _Deref_pre2_impl_(p1,p2) -#define _Deref_pre3_impl_(p1,p2,p3) +#define _Deref_pre2_impl_(p1, p2) +#define _Deref_pre3_impl_(p1, p2, p3) #define _Deref_post1_impl_(p1) -#define _Deref_post2_impl_(p1,p2) -#define _Deref_post3_impl_(p1,p2,p3) +#define _Deref_post2_impl_(p1, p2) +#define _Deref_post3_impl_(p1, p2, p3) #define _Deref_ret1_impl_(p1) -#define _Deref_ret2_impl_(p1,p2) -#define _Deref_ret3_impl_(p1,p2,p3) +#define _Deref_ret2_impl_(p1, p2) +#define _Deref_ret3_impl_(p1, p2, p3) #define _Deref2_pre1_impl_(p1) #define _Deref2_post1_impl_(p1) @@ -2151,7 +3207,7 @@ typedef struct __F_ __F_; #define __inner_typefix(ctype) #define __inner_exceptthat -#endif // ] +#endif // ] // This section contains the deprecated annotations @@ -2360,17 +3416,16 @@ typedef struct __F_ __F_; #define __specstrings -#ifdef __cplusplus // [ -#ifndef __nothrow // [ -# define __nothrow NOTHROW_DECL -#endif // ] +#ifdef __cplusplus // [ +#ifndef __nothrow // [ +#define __nothrow NOTHROW_DECL +#endif // ] extern "C" { -#else // ][ -#ifndef __nothrow // [ -# define __nothrow -#endif // ] -#endif /* #ifdef __cplusplus */ // ] - +#else // ][ +#ifndef __nothrow // [ +#define __nothrow +#endif // ] +#endif /* #ifdef __cplusplus */ // ] /* ------------------------------------------------------------------------------- @@ -2387,248 +3442,246 @@ extern "C" { are defined into nothing, and do not affect the compiled code. */ -#if !defined(__midl) && defined(_PREFAST_) // [ +#if !defined(__midl) && defined(_PREFAST_) // [ - /* - In the primitive "SAL_*" annotations "SAL" stands for Standard - Annotation Language. These "SAL_*" annotations are the - primitives the compiler understands and high-level MACROs - will decompose into these primivates. - */ +/* + In the primitive "SAL_*" annotations "SAL" stands for Standard + Annotation Language. These "SAL_*" annotations are the + primitives the compiler understands and high-level MACROs + will decompose into these primivates. +*/ - #define _SA_SPECSTRIZE( x ) #x +#define _SA_SPECSTRIZE(x) #x - /* - __notnull p - __maybenull p +/* + __notnull p + __maybenull p - Annotates a pointer p. States that pointer p is never null or maybe null. - */ + Annotates a pointer p. States that pointer p is never null or maybe null. +*/ - #define __notnull _Notnull_impl_ - #define __maybenull _Maybenull_impl_ +#define __notnull _Notnull_impl_ +#define __maybenull _Maybenull_impl_ - /* - __readonly l - __notreadonly l - __maybereadonly l +/* + __readonly l + __notreadonly l + __maybereadonly l - Annotates a location l. States that location l is not modified after - this point. If the annotation is placed on the precondition state of - a function, the restriction only applies until the postcondition state - of the function. __maybereadonly states that the annotated location - may be modified, whereas __notreadonly states that a location must be - modified. - */ + Annotates a location l. States that location l is not modified after + this point. If the annotation is placed on the precondition state of + a function, the restriction only applies until the postcondition state + of the function. __maybereadonly states that the annotated location + may be modified, whereas __notreadonly states that a location must be + modified. +*/ - #define __readonly _Pre1_impl_(__readaccess_impl) - #define __notreadonly _Pre1_impl_(__allaccess_impl) - #define __maybereadonly _Pre1_impl_(__readaccess_impl) +#define __readonly _Pre1_impl_(__readaccess_impl) +#define __notreadonly _Pre1_impl_(__allaccess_impl) +#define __maybereadonly _Pre1_impl_(__readaccess_impl) - /* - __valid v - __notvalid v - __maybevalid v +/* + __valid v + __notvalid v + __maybevalid v - Annotates any value v. States that the value satisfies all properties of - valid values of its type. For example, for a string buffer, valid means - that the buffer pointer is either NULL or points to a NULL-terminated string. - */ + Annotates any value v. States that the value satisfies all properties of + valid values of its type. For example, for a string buffer, valid means + that the buffer pointer is either NULL or points to a NULL-terminated string. +*/ - #define __valid _Valid_impl_ - #define __notvalid _Notvalid_impl_ - #define __maybevalid _Maybevalid_impl_ +#define __valid _Valid_impl_ +#define __notvalid _Notvalid_impl_ +#define __maybevalid _Maybevalid_impl_ - /* - __readableTo(extent) p +/* + __readableTo(extent) p - Annotates a buffer pointer p. If the buffer can be read, extent describes - how much of the buffer is readable. For a reader of the buffer, this is - an explicit permission to read up to that amount, rather than a restriction to - read only up to it. - */ + Annotates a buffer pointer p. If the buffer can be read, extent describes + how much of the buffer is readable. For a reader of the buffer, this is + an explicit permission to read up to that amount, rather than a restriction to + read only up to it. +*/ - #define __readableTo(extent) _SA_annotes1(SAL_readableTo, extent) +#define __readableTo(extent) _SA_annotes1(SAL_readableTo, extent) - /* +/* - __elem_readableTo(size) + __elem_readableTo(size) - Annotates a buffer pointer p as being readable to size elements. - */ + Annotates a buffer pointer p as being readable to size elements. +*/ - #define __elem_readableTo(size) _SA_annotes1(SAL_readableTo, elementCount( size )) +#define __elem_readableTo(size) _SA_annotes1(SAL_readableTo, elementCount(size)) - /* - __byte_readableTo(size) +/* + __byte_readableTo(size) - Annotates a buffer pointer p as being readable to size bytes. - */ - #define __byte_readableTo(size) _SA_annotes1(SAL_readableTo, byteCount(size)) + Annotates a buffer pointer p as being readable to size bytes. +*/ +#define __byte_readableTo(size) _SA_annotes1(SAL_readableTo, byteCount(size)) - /* - __writableTo(extent) p +/* + __writableTo(extent) p - Annotates a buffer pointer p. If the buffer can be modified, extent - describes how much of the buffer is writable (usually the allocation - size). For a writer of the buffer, this is an explicit permission to - write up to that amount, rather than a restriction to write only up to it. - */ - #define __writableTo(size) _SA_annotes1(SAL_writableTo, size) + Annotates a buffer pointer p. If the buffer can be modified, extent + describes how much of the buffer is writable (usually the allocation + size). For a writer of the buffer, this is an explicit permission to + write up to that amount, rather than a restriction to write only up to it. +*/ +#define __writableTo(size) _SA_annotes1(SAL_writableTo, size) - /* - __elem_writableTo(size) +/* + __elem_writableTo(size) - Annotates a buffer pointer p as being writable to size elements. - */ - #define __elem_writableTo(size) _SA_annotes1(SAL_writableTo, elementCount( size )) + Annotates a buffer pointer p as being writable to size elements. +*/ +#define __elem_writableTo(size) _SA_annotes1(SAL_writableTo, elementCount(size)) - /* - __byte_writableTo(size) +/* + __byte_writableTo(size) - Annotates a buffer pointer p as being writable to size bytes. - */ - #define __byte_writableTo(size) _SA_annotes1(SAL_writableTo, byteCount( size)) + Annotates a buffer pointer p as being writable to size bytes. +*/ +#define __byte_writableTo(size) _SA_annotes1(SAL_writableTo, byteCount(size)) - /* - __deref p +/* + __deref p - Annotates a pointer p. The next annotation applies one dereference down - in the type. If readableTo(p, size) then the next annotation applies to - all elements *(p+i) for which i satisfies the size. If p is a pointer - to a struct, the next annotation applies to all fields of the struct. - */ - #define __deref _Deref_impl_ + Annotates a pointer p. The next annotation applies one dereference down + in the type. If readableTo(p, size) then the next annotation applies to + all elements *(p+i) for which i satisfies the size. If p is a pointer + to a struct, the next annotation applies to all fields of the struct. +*/ +#define __deref _Deref_impl_ - /* - __pre __next_annotation +/* + __pre __next_annotation - The next annotation applies in the precondition state - */ - #define __pre _Pre_impl_ + The next annotation applies in the precondition state +*/ +#define __pre _Pre_impl_ - /* - __post __next_annotation +/* + __post __next_annotation - The next annotation applies in the postcondition state - */ - #define __post _Post_impl_ + The next annotation applies in the postcondition state +*/ +#define __post _Post_impl_ - /* - __precond() +/* + __precond() - When is true, the next annotation applies in the precondition state - (currently not enabled) - */ - #define __precond(expr) __pre + When is true, the next annotation applies in the precondition state + (currently not enabled) +*/ +#define __precond(expr) __pre - /* - __postcond() +/* + __postcond() - When is true, the next annotation applies in the postcondition state - (currently not enabled) - */ - #define __postcond(expr) __post + When is true, the next annotation applies in the postcondition state + (currently not enabled) +*/ +#define __postcond(expr) __post - /* - __exceptthat +/* + __exceptthat - Given a set of annotations Q containing __exceptthat maybeP, the effect of - the except clause is to erase any P or notP annotations (explicit or - implied) within Q at the same level of dereferencing that the except - clause appears, and to replace it with maybeP. + Given a set of annotations Q containing __exceptthat maybeP, the effect of + the except clause is to erase any P or notP annotations (explicit or + implied) within Q at the same level of dereferencing that the except + clause appears, and to replace it with maybeP. - Example 1: __valid __pre_except_maybenull on a pointer p means that the - pointer may be null, and is otherwise valid, thus overriding - the implicit notnull annotation implied by __valid on - pointers. + Example 1: __valid __pre_except_maybenull on a pointer p means that the + pointer may be null, and is otherwise valid, thus overriding + the implicit notnull annotation implied by __valid on + pointers. - Example 2: __valid __deref __pre_except_maybenull on an int **p means - that p is not null (implied by valid), but the elements - pointed to by p could be null, and are otherwise valid. - */ - #define __exceptthat __inner_exceptthat + Example 2: __valid __deref __pre_except_maybenull on an int **p means + that p is not null (implied by valid), but the elements + pointed to by p could be null, and are otherwise valid. +*/ +#define __exceptthat __inner_exceptthat - /* - _refparam +/* + _refparam - Added to all out parameter macros to indicate that they are all reference - parameters. - */ - #define __refparam _Notref_ __deref __notreadonly + Added to all out parameter macros to indicate that they are all reference + parameters. +*/ +#define __refparam _Notref_ __deref __notreadonly - /* - __inner_* +/* + __inner_* - Helper macros that directly correspond to certain high-level annotations. + Helper macros that directly correspond to certain high-level annotations. - */ +*/ - /* - Macros to classify the entrypoints and indicate their category. +/* + Macros to classify the entrypoints and indicate their category. - Pre-defined control point categories include: RPC, LPC, DeviceDriver, UserToKernel, ISAPI, COM. + Pre-defined control point categories include: RPC, LPC, DeviceDriver, UserToKernel, ISAPI, COM. - */ - #define __inner_control_entrypoint(category) _SA_annotes2(SAL_entrypoint, controlEntry, category) +*/ +#define __inner_control_entrypoint(category) _SA_annotes2(SAL_entrypoint, controlEntry, category) +/* + Pre-defined data entry point categories include: Registry, File, Network. +*/ +#define __inner_data_entrypoint(category) _SA_annotes2(SAL_entrypoint, dataEntry, category) - /* - Pre-defined data entry point categories include: Registry, File, Network. - */ - #define __inner_data_entrypoint(category) _SA_annotes2(SAL_entrypoint, dataEntry, category) +#define __inner_override _SA_annotes0(__override) +#define __inner_callback _SA_annotes0(__callback) +#define __inner_blocksOn(resource) _SA_annotes1(SAL_blocksOn, resource) - #define __inner_override _SA_annotes0(__override) - #define __inner_callback _SA_annotes0(__callback) - #define __inner_blocksOn(resource) _SA_annotes1(SAL_blocksOn, resource) +#define __post_except_maybenull __post __inner_exceptthat _Maybenull_impl_ +#define __pre_except_maybenull __pre __inner_exceptthat _Maybenull_impl_ - #define __post_except_maybenull __post __inner_exceptthat _Maybenull_impl_ - #define __pre_except_maybenull __pre __inner_exceptthat _Maybenull_impl_ +#define __post_deref_except_maybenull __post __deref __inner_exceptthat _Maybenull_impl_ +#define __pre_deref_except_maybenull __pre __deref __inner_exceptthat _Maybenull_impl_ - #define __post_deref_except_maybenull __post __deref __inner_exceptthat _Maybenull_impl_ - #define __pre_deref_except_maybenull __pre __deref __inner_exceptthat _Maybenull_impl_ +#define __inexpressible_readableTo(size) _Readable_elements_impl_(_Inexpressible_(size)) +#define __inexpressible_writableTo(size) _Writable_elements_impl_(_Inexpressible_(size)) - #define __inexpressible_readableTo(size) _Readable_elements_impl_(_Inexpressible_(size)) - #define __inexpressible_writableTo(size) _Writable_elements_impl_(_Inexpressible_(size)) +#else // ][ +#define __notnull +#define __deref +#define __maybenull +#define __readonly +#define __notreadonly +#define __maybereadonly +#define __valid +#define __notvalid +#define __maybevalid +#define __readableTo(extent) +#define __elem_readableTo(size) +#define __byte_readableTo(size) +#define __writableTo(size) +#define __elem_writableTo(size) +#define __byte_writableTo(size) +#define __pre +#define __post +#define __precond(expr) +#define __postcond(expr) +#define __exceptthat +#define __inner_override +#define __inner_callback +#define __inner_blocksOn(resource) +#define __refparam +#define __inner_control_entrypoint(category) +#define __inner_data_entrypoint(category) +#define __post_except_maybenull +#define __pre_except_maybenull +#define __post_deref_except_maybenull +#define __pre_deref_except_maybenull -#else // ][ - #define __notnull - #define __deref - #define __maybenull - #define __readonly - #define __notreadonly - #define __maybereadonly - #define __valid - #define __notvalid - #define __maybevalid - #define __readableTo(extent) - #define __elem_readableTo(size) - #define __byte_readableTo(size) - #define __writableTo(size) - #define __elem_writableTo(size) - #define __byte_writableTo(size) - #define __pre - #define __post - #define __precond(expr) - #define __postcond(expr) - #define __exceptthat - #define __inner_override - #define __inner_callback - #define __inner_blocksOn(resource) - #define __refparam - #define __inner_control_entrypoint(category) - #define __inner_data_entrypoint(category) +#define __inexpressible_readableTo(size) +#define __inexpressible_writableTo(size) - #define __post_except_maybenull - #define __pre_except_maybenull - #define __post_deref_except_maybenull - #define __pre_deref_except_maybenull - - #define __inexpressible_readableTo(size) - #define __inexpressible_writableTo(size) - -#endif /* #if !defined(__midl) && defined(_PREFAST_) */ // ] +#endif /* #if !defined(__midl) && defined(_PREFAST_) */ // ] /* ------------------------------------------------------------------------------- @@ -2640,194 +3693,441 @@ buffer, use the table in the buffer annotations section. ------------------------------------------------------------------------------- */ -#define __ecount(size) _SAL1_Source_(__ecount, (size), __notnull __elem_writableTo(size)) -#define __bcount(size) _SAL1_Source_(__bcount, (size), __notnull __byte_writableTo(size)) -#define __in_ecount(size) _SAL1_Source_(__in_ecount, (size), _In_reads_(size)) -#define __in_bcount(size) _SAL1_Source_(__in_bcount, (size), _In_reads_bytes_(size)) -#define __in_z _SAL1_Source_(__in_z, (), _In_z_) -#define __in_ecount_z(size) _SAL1_Source_(__in_ecount_z, (size), _In_reads_z_(size)) -#define __in_bcount_z(size) _SAL1_Source_(__in_bcount_z, (size), __in_bcount(size) __pre __nullterminated) -#define __in_nz _SAL1_Source_(__in_nz, (), __in) -#define __in_ecount_nz(size) _SAL1_Source_(__in_ecount_nz, (size), __in_ecount(size)) -#define __in_bcount_nz(size) _SAL1_Source_(__in_bcount_nz, (size), __in_bcount(size)) -#define __out_ecount(size) _SAL1_Source_(__out_ecount, (size), _Out_writes_(size)) -#define __out_bcount(size) _SAL1_Source_(__out_bcount, (size), _Out_writes_bytes_(size)) -#define __out_ecount_part(size,length) _SAL1_Source_(__out_ecount_part, (size,length), _Out_writes_to_(size,length)) -#define __out_bcount_part(size,length) _SAL1_Source_(__out_bcount_part, (size,length), _Out_writes_bytes_to_(size,length)) -#define __out_ecount_full(size) _SAL1_Source_(__out_ecount_full, (size), _Out_writes_all_(size)) -#define __out_bcount_full(size) _SAL1_Source_(__out_bcount_full, (size), _Out_writes_bytes_all_(size)) -#define __out_z _SAL1_Source_(__out_z, (), __post __valid __refparam __post __nullterminated) -#define __out_z_opt _SAL1_Source_(__out_z_opt, (), __post __valid __refparam __post __nullterminated __pre_except_maybenull) -#define __out_ecount_z(size) _SAL1_Source_(__out_ecount_z, (size), __ecount(size) __post __valid __refparam __post __nullterminated) -#define __out_bcount_z(size) _SAL1_Source_(__out_bcount_z, (size), __bcount(size) __post __valid __refparam __post __nullterminated) -#define __out_ecount_part_z(size,length) _SAL1_Source_(__out_ecount_part_z, (size,length), __out_ecount_part(size,length) __post __nullterminated) -#define __out_bcount_part_z(size,length) _SAL1_Source_(__out_bcount_part_z, (size,length), __out_bcount_part(size,length) __post __nullterminated) -#define __out_ecount_full_z(size) _SAL1_Source_(__out_ecount_full_z, (size), __out_ecount_full(size) __post __nullterminated) -#define __out_bcount_full_z(size) _SAL1_Source_(__out_bcount_full_z, (size), __out_bcount_full(size) __post __nullterminated) -#define __out_nz _SAL1_Source_(__out_nz, (), __post __valid __refparam) -#define __out_nz_opt _SAL1_Source_(__out_nz_opt, (), __post __valid __refparam __post_except_maybenull_) -#define __out_ecount_nz(size) _SAL1_Source_(__out_ecount_nz, (size), __ecount(size) __post __valid __refparam) -#define __out_bcount_nz(size) _SAL1_Source_(__out_bcount_nz, (size), __bcount(size) __post __valid __refparam) -#define __inout _SAL1_Source_(__inout, (), _Inout_) -#define __inout_ecount(size) _SAL1_Source_(__inout_ecount, (size), _Inout_updates_(size)) -#define __inout_bcount(size) _SAL1_Source_(__inout_bcount, (size), _Inout_updates_bytes_(size)) -#define __inout_ecount_part(size,length) _SAL1_Source_(__inout_ecount_part, (size,length), _Inout_updates_to_(size,length)) -#define __inout_bcount_part(size,length) _SAL1_Source_(__inout_bcount_part, (size,length), _Inout_updates_bytes_to_(size,length)) -#define __inout_ecount_full(size) _SAL1_Source_(__inout_ecount_full, (size), _Inout_updates_all_(size)) -#define __inout_bcount_full(size) _SAL1_Source_(__inout_bcount_full, (size), _Inout_updates_bytes_all_(size)) -#define __inout_z _SAL1_Source_(__inout_z, (), _Inout_z_) -#define __inout_ecount_z(size) _SAL1_Source_(__inout_ecount_z, (size), _Inout_updates_z_(size)) -#define __inout_bcount_z(size) _SAL1_Source_(__inout_bcount_z, (size), __inout_bcount(size) __pre __nullterminated __post __nullterminated) -#define __inout_nz _SAL1_Source_(__inout_nz, (), __inout) -#define __inout_ecount_nz(size) _SAL1_Source_(__inout_ecount_nz, (size), __inout_ecount(size)) -#define __inout_bcount_nz(size) _SAL1_Source_(__inout_bcount_nz, (size), __inout_bcount(size)) -#define __ecount_opt(size) _SAL1_Source_(__ecount_opt, (size), __ecount(size) __pre_except_maybenull) -#define __bcount_opt(size) _SAL1_Source_(__bcount_opt, (size), __bcount(size) __pre_except_maybenull) -#define __in_opt _SAL1_Source_(__in_opt, (), _In_opt_) -#define __in_ecount_opt(size) _SAL1_Source_(__in_ecount_opt, (size), _In_reads_opt_(size)) -#define __in_bcount_opt(size) _SAL1_Source_(__in_bcount_opt, (size), _In_reads_bytes_opt_(size)) -#define __in_z_opt _SAL1_Source_(__in_z_opt, (), _In_opt_z_) -#define __in_ecount_z_opt(size) _SAL1_Source_(__in_ecount_z_opt, (size), __in_ecount_opt(size) __pre __nullterminated) -#define __in_bcount_z_opt(size) _SAL1_Source_(__in_bcount_z_opt, (size), __in_bcount_opt(size) __pre __nullterminated) -#define __in_nz_opt _SAL1_Source_(__in_nz_opt, (), __in_opt) -#define __in_ecount_nz_opt(size) _SAL1_Source_(__in_ecount_nz_opt, (size), __in_ecount_opt(size)) -#define __in_bcount_nz_opt(size) _SAL1_Source_(__in_bcount_nz_opt, (size), __in_bcount_opt(size)) -#define __out_opt _SAL1_Source_(__out_opt, (), _Out_opt_) -#define __out_ecount_opt(size) _SAL1_Source_(__out_ecount_opt, (size), _Out_writes_opt_(size)) -#define __out_bcount_opt(size) _SAL1_Source_(__out_bcount_opt, (size), _Out_writes_bytes_opt_(size)) -#define __out_ecount_part_opt(size,length) _SAL1_Source_(__out_ecount_part_opt, (size,length), __out_ecount_part(size,length) __pre_except_maybenull) -#define __out_bcount_part_opt(size,length) _SAL1_Source_(__out_bcount_part_opt, (size,length), __out_bcount_part(size,length) __pre_except_maybenull) -#define __out_ecount_full_opt(size) _SAL1_Source_(__out_ecount_full_opt, (size), __out_ecount_full(size) __pre_except_maybenull) -#define __out_bcount_full_opt(size) _SAL1_Source_(__out_bcount_full_opt, (size), __out_bcount_full(size) __pre_except_maybenull) -#define __out_ecount_z_opt(size) _SAL1_Source_(__out_ecount_z_opt, (size), __out_ecount_opt(size) __post __nullterminated) -#define __out_bcount_z_opt(size) _SAL1_Source_(__out_bcount_z_opt, (size), __out_bcount_opt(size) __post __nullterminated) -#define __out_ecount_part_z_opt(size,length) _SAL1_Source_(__out_ecount_part_z_opt, (size,length), __out_ecount_part_opt(size,length) __post __nullterminated) -#define __out_bcount_part_z_opt(size,length) _SAL1_Source_(__out_bcount_part_z_opt, (size,length), __out_bcount_part_opt(size,length) __post __nullterminated) -#define __out_ecount_full_z_opt(size) _SAL1_Source_(__out_ecount_full_z_opt, (size), __out_ecount_full_opt(size) __post __nullterminated) -#define __out_bcount_full_z_opt(size) _SAL1_Source_(__out_bcount_full_z_opt, (size), __out_bcount_full_opt(size) __post __nullterminated) -#define __out_ecount_nz_opt(size) _SAL1_Source_(__out_ecount_nz_opt, (size), __out_ecount_opt(size) __post __nullterminated) -#define __out_bcount_nz_opt(size) _SAL1_Source_(__out_bcount_nz_opt, (size), __out_bcount_opt(size) __post __nullterminated) -#define __inout_opt _SAL1_Source_(__inout_opt, (), _Inout_opt_) -#define __inout_ecount_opt(size) _SAL1_Source_(__inout_ecount_opt, (size), __inout_ecount(size) __pre_except_maybenull) -#define __inout_bcount_opt(size) _SAL1_Source_(__inout_bcount_opt, (size), __inout_bcount(size) __pre_except_maybenull) -#define __inout_ecount_part_opt(size,length) _SAL1_Source_(__inout_ecount_part_opt, (size,length), __inout_ecount_part(size,length) __pre_except_maybenull) -#define __inout_bcount_part_opt(size,length) _SAL1_Source_(__inout_bcount_part_opt, (size,length), __inout_bcount_part(size,length) __pre_except_maybenull) -#define __inout_ecount_full_opt(size) _SAL1_Source_(__inout_ecount_full_opt, (size), __inout_ecount_full(size) __pre_except_maybenull) -#define __inout_bcount_full_opt(size) _SAL1_Source_(__inout_bcount_full_opt, (size), __inout_bcount_full(size) __pre_except_maybenull) -#define __inout_z_opt _SAL1_Source_(__inout_z_opt, (), __inout_opt __pre __nullterminated __post __nullterminated) -#define __inout_ecount_z_opt(size) _SAL1_Source_(__inout_ecount_z_opt, (size), __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) -#define __inout_ecount_z_opt(size) _SAL1_Source_(__inout_ecount_z_opt, (size), __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) -#define __inout_bcount_z_opt(size) _SAL1_Source_(__inout_bcount_z_opt, (size), __inout_bcount_opt(size)) -#define __inout_nz_opt _SAL1_Source_(__inout_nz_opt, (), __inout_opt) -#define __inout_ecount_nz_opt(size) _SAL1_Source_(__inout_ecount_nz_opt, (size), __inout_ecount_opt(size)) -#define __inout_bcount_nz_opt(size) _SAL1_Source_(__inout_bcount_nz_opt, (size), __inout_bcount_opt(size)) -#define __deref_ecount(size) _SAL1_Source_(__deref_ecount, (size), _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) __post _Notref_ __deref _Notref_ __notnull __post __deref __elem_writableTo(size)) -#define __deref_bcount(size) _SAL1_Source_(__deref_bcount, (size), _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) __post _Notref_ __deref _Notref_ __notnull __post __deref __byte_writableTo(size)) -#define __deref_out _SAL1_Source_(__deref_out, (), _Outptr_) -#define __deref_out_ecount(size) _SAL1_Source_(__deref_out_ecount, (size), _Outptr_result_buffer_(size)) -#define __deref_out_bcount(size) _SAL1_Source_(__deref_out_bcount, (size), _Outptr_result_bytebuffer_(size)) -#define __deref_out_ecount_part(size,length) _SAL1_Source_(__deref_out_ecount_part, (size,length), _Outptr_result_buffer_to_(size,length)) -#define __deref_out_bcount_part(size,length) _SAL1_Source_(__deref_out_bcount_part, (size,length), _Outptr_result_bytebuffer_to_(size,length)) -#define __deref_out_ecount_full(size) _SAL1_Source_(__deref_out_ecount_full, (size), __deref_out_ecount_part(size,size)) -#define __deref_out_bcount_full(size) _SAL1_Source_(__deref_out_bcount_full, (size), __deref_out_bcount_part(size,size)) -#define __deref_out_z _SAL1_Source_(__deref_out_z, (), _Outptr_result_z_) -#define __deref_out_ecount_z(size) _SAL1_Source_(__deref_out_ecount_z, (size), __deref_out_ecount(size) __post __deref __nullterminated) -#define __deref_out_bcount_z(size) _SAL1_Source_(__deref_out_bcount_z, (size), __deref_out_bcount(size) __post __deref __nullterminated) -#define __deref_out_nz _SAL1_Source_(__deref_out_nz, (), __deref_out) -#define __deref_out_ecount_nz(size) _SAL1_Source_(__deref_out_ecount_nz, (size), __deref_out_ecount(size)) -#define __deref_out_bcount_nz(size) _SAL1_Source_(__deref_out_bcount_nz, (size), __deref_out_ecount(size)) -#define __deref_inout _SAL1_Source_(__deref_inout, (), _Notref_ __notnull _Notref_ __elem_readableTo(1) __pre __deref __valid __post _Notref_ __deref __valid __refparam) -#define __deref_inout_z _SAL1_Source_(__deref_inout_z, (), __deref_inout __pre __deref __nullterminated __post _Notref_ __deref __nullterminated) -#define __deref_inout_ecount(size) _SAL1_Source_(__deref_inout_ecount, (size), __deref_inout __pre __deref __elem_writableTo(size) __post _Notref_ __deref __elem_writableTo(size)) -#define __deref_inout_bcount(size) _SAL1_Source_(__deref_inout_bcount, (size), __deref_inout __pre __deref __byte_writableTo(size) __post _Notref_ __deref __byte_writableTo(size)) -#define __deref_inout_ecount_part(size,length) _SAL1_Source_(__deref_inout_ecount_part, (size,length), __deref_inout_ecount(size) __pre __deref __elem_readableTo(length) __post __deref __elem_readableTo(length)) -#define __deref_inout_bcount_part(size,length) _SAL1_Source_(__deref_inout_bcount_part, (size,length), __deref_inout_bcount(size) __pre __deref __byte_readableTo(length) __post __deref __byte_readableTo(length)) -#define __deref_inout_ecount_full(size) _SAL1_Source_(__deref_inout_ecount_full, (size), __deref_inout_ecount_part(size,size)) -#define __deref_inout_bcount_full(size) _SAL1_Source_(__deref_inout_bcount_full, (size), __deref_inout_bcount_part(size,size)) -#define __deref_inout_ecount_z(size) _SAL1_Source_(__deref_inout_ecount_z, (size), __deref_inout_ecount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_bcount_z(size) _SAL1_Source_(__deref_inout_bcount_z, (size), __deref_inout_bcount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_nz _SAL1_Source_(__deref_inout_nz, (), __deref_inout) -#define __deref_inout_ecount_nz(size) _SAL1_Source_(__deref_inout_ecount_nz, (size), __deref_inout_ecount(size)) -#define __deref_inout_bcount_nz(size) _SAL1_Source_(__deref_inout_bcount_nz, (size), __deref_inout_ecount(size)) -#define __deref_ecount_opt(size) _SAL1_Source_(__deref_ecount_opt, (size), __deref_ecount(size) __post_deref_except_maybenull) -#define __deref_bcount_opt(size) _SAL1_Source_(__deref_bcount_opt, (size), __deref_bcount(size) __post_deref_except_maybenull) -#define __deref_out_opt _SAL1_Source_(__deref_out_opt, (), __deref_out __post_deref_except_maybenull) -#define __deref_out_ecount_opt(size) _SAL1_Source_(__deref_out_ecount_opt, (size), __deref_out_ecount(size) __post_deref_except_maybenull) -#define __deref_out_bcount_opt(size) _SAL1_Source_(__deref_out_bcount_opt, (size), __deref_out_bcount(size) __post_deref_except_maybenull) -#define __deref_out_ecount_part_opt(size,length) _SAL1_Source_(__deref_out_ecount_part_opt, (size,length), __deref_out_ecount_part(size,length) __post_deref_except_maybenull) -#define __deref_out_bcount_part_opt(size,length) _SAL1_Source_(__deref_out_bcount_part_opt, (size,length), __deref_out_bcount_part(size,length) __post_deref_except_maybenull) -#define __deref_out_ecount_full_opt(size) _SAL1_Source_(__deref_out_ecount_full_opt, (size), __deref_out_ecount_full(size) __post_deref_except_maybenull) -#define __deref_out_bcount_full_opt(size) _SAL1_Source_(__deref_out_bcount_full_opt, (size), __deref_out_bcount_full(size) __post_deref_except_maybenull) -#define __deref_out_z_opt _SAL1_Source_(__deref_out_z_opt, (), _Outptr_result_maybenull_z_) -#define __deref_out_ecount_z_opt(size) _SAL1_Source_(__deref_out_ecount_z_opt, (size), __deref_out_ecount_opt(size) __post __deref __nullterminated) -#define __deref_out_bcount_z_opt(size) _SAL1_Source_(__deref_out_bcount_z_opt, (size), __deref_out_bcount_opt(size) __post __deref __nullterminated) -#define __deref_out_nz_opt _SAL1_Source_(__deref_out_nz_opt, (), __deref_out_opt) -#define __deref_out_ecount_nz_opt(size) _SAL1_Source_(__deref_out_ecount_nz_opt, (size), __deref_out_ecount_opt(size)) -#define __deref_out_bcount_nz_opt(size) _SAL1_Source_(__deref_out_bcount_nz_opt, (size), __deref_out_bcount_opt(size)) -#define __deref_inout_opt _SAL1_Source_(__deref_inout_opt, (), __deref_inout __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_opt(size) _SAL1_Source_(__deref_inout_ecount_opt, (size), __deref_inout_ecount(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_opt(size) _SAL1_Source_(__deref_inout_bcount_opt, (size), __deref_inout_bcount(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_part_opt(size,length) _SAL1_Source_(__deref_inout_ecount_part_opt, (size,length), __deref_inout_ecount_part(size,length) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_part_opt(size,length) _SAL1_Source_(__deref_inout_bcount_part_opt, (size,length), __deref_inout_bcount_part(size,length) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_full_opt(size) _SAL1_Source_(__deref_inout_ecount_full_opt, (size), __deref_inout_ecount_full(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_full_opt(size) _SAL1_Source_(__deref_inout_bcount_full_opt, (size), __deref_inout_bcount_full(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_z_opt _SAL1_Source_(__deref_inout_z_opt, (), __deref_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_ecount_z_opt(size) _SAL1_Source_(__deref_inout_ecount_z_opt, (size), __deref_inout_ecount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_bcount_z_opt(size) _SAL1_Source_(__deref_inout_bcount_z_opt, (size), __deref_inout_bcount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_nz_opt _SAL1_Source_(__deref_inout_nz_opt, (), __deref_inout_opt) -#define __deref_inout_ecount_nz_opt(size) _SAL1_Source_(__deref_inout_ecount_nz_opt, (size), __deref_inout_ecount_opt(size)) -#define __deref_inout_bcount_nz_opt(size) _SAL1_Source_(__deref_inout_bcount_nz_opt, (size), __deref_inout_bcount_opt(size)) -#define __deref_opt_ecount(size) _SAL1_Source_(__deref_opt_ecount, (size), __deref_ecount(size) __pre_except_maybenull) -#define __deref_opt_bcount(size) _SAL1_Source_(__deref_opt_bcount, (size), __deref_bcount(size) __pre_except_maybenull) -#define __deref_opt_out _SAL1_Source_(__deref_opt_out, (), _Outptr_opt_) -#define __deref_opt_out_z _SAL1_Source_(__deref_opt_out_z, (), _Outptr_opt_result_z_) -#define __deref_opt_out_ecount(size) _SAL1_Source_(__deref_opt_out_ecount, (size), __deref_out_ecount(size) __pre_except_maybenull) -#define __deref_opt_out_bcount(size) _SAL1_Source_(__deref_opt_out_bcount, (size), __deref_out_bcount(size) __pre_except_maybenull) -#define __deref_opt_out_ecount_part(size,length) _SAL1_Source_(__deref_opt_out_ecount_part, (size,length), __deref_out_ecount_part(size,length) __pre_except_maybenull) -#define __deref_opt_out_bcount_part(size,length) _SAL1_Source_(__deref_opt_out_bcount_part, (size,length), __deref_out_bcount_part(size,length) __pre_except_maybenull) -#define __deref_opt_out_ecount_full(size) _SAL1_Source_(__deref_opt_out_ecount_full, (size), __deref_out_ecount_full(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_full(size) _SAL1_Source_(__deref_opt_out_bcount_full, (size), __deref_out_bcount_full(size) __pre_except_maybenull) -#define __deref_opt_inout _SAL1_Source_(__deref_opt_inout, (), _Inout_opt_) -#define __deref_opt_inout_ecount(size) _SAL1_Source_(__deref_opt_inout_ecount, (size), __deref_inout_ecount(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount(size) _SAL1_Source_(__deref_opt_inout_bcount, (size), __deref_inout_bcount(size) __pre_except_maybenull) -#define __deref_opt_inout_ecount_part(size,length) _SAL1_Source_(__deref_opt_inout_ecount_part, (size,length), __deref_inout_ecount_part(size,length) __pre_except_maybenull) -#define __deref_opt_inout_bcount_part(size,length) _SAL1_Source_(__deref_opt_inout_bcount_part, (size,length), __deref_inout_bcount_part(size,length) __pre_except_maybenull) -#define __deref_opt_inout_ecount_full(size) _SAL1_Source_(__deref_opt_inout_ecount_full, (size), __deref_inout_ecount_full(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_full(size) _SAL1_Source_(__deref_opt_inout_bcount_full, (size), __deref_inout_bcount_full(size) __pre_except_maybenull) -#define __deref_opt_inout_z _SAL1_Source_(__deref_opt_inout_z, (), __deref_opt_inout __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_ecount_z(size) _SAL1_Source_(__deref_opt_inout_ecount_z, (size), __deref_opt_inout_ecount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_bcount_z(size) _SAL1_Source_(__deref_opt_inout_bcount_z, (size), __deref_opt_inout_bcount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_nz _SAL1_Source_(__deref_opt_inout_nz, (), __deref_opt_inout) -#define __deref_opt_inout_ecount_nz(size) _SAL1_Source_(__deref_opt_inout_ecount_nz, (size), __deref_opt_inout_ecount(size)) -#define __deref_opt_inout_bcount_nz(size) _SAL1_Source_(__deref_opt_inout_bcount_nz, (size), __deref_opt_inout_bcount(size)) -#define __deref_opt_ecount_opt(size) _SAL1_Source_(__deref_opt_ecount_opt, (size), __deref_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_bcount_opt(size) _SAL1_Source_(__deref_opt_bcount_opt, (size), __deref_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_opt _SAL1_Source_(__deref_opt_out_opt, (), _Outptr_opt_result_maybenull_) -#define __deref_opt_out_ecount_opt(size) _SAL1_Source_(__deref_opt_out_ecount_opt, (size), __deref_out_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_opt(size) _SAL1_Source_(__deref_opt_out_bcount_opt, (size), __deref_out_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_ecount_part_opt(size,length) _SAL1_Source_(__deref_opt_out_ecount_part_opt, (size,length), __deref_out_ecount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_out_bcount_part_opt(size,length) _SAL1_Source_(__deref_opt_out_bcount_part_opt, (size,length), __deref_out_bcount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_out_ecount_full_opt(size) _SAL1_Source_(__deref_opt_out_ecount_full_opt, (size), __deref_out_ecount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_full_opt(size) _SAL1_Source_(__deref_opt_out_bcount_full_opt, (size), __deref_out_bcount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_out_z_opt _SAL1_Source_(__deref_opt_out_z_opt, (), __post __deref __valid __refparam __pre_except_maybenull __pre_deref_except_maybenull __post_deref_except_maybenull __post __deref __nullterminated) -#define __deref_opt_out_ecount_z_opt(size) _SAL1_Source_(__deref_opt_out_ecount_z_opt, (size), __deref_opt_out_ecount_opt(size) __post __deref __nullterminated) -#define __deref_opt_out_bcount_z_opt(size) _SAL1_Source_(__deref_opt_out_bcount_z_opt, (size), __deref_opt_out_bcount_opt(size) __post __deref __nullterminated) -#define __deref_opt_out_nz_opt _SAL1_Source_(__deref_opt_out_nz_opt, (), __deref_opt_out_opt) -#define __deref_opt_out_ecount_nz_opt(size) _SAL1_Source_(__deref_opt_out_ecount_nz_opt, (size), __deref_opt_out_ecount_opt(size)) -#define __deref_opt_out_bcount_nz_opt(size) _SAL1_Source_(__deref_opt_out_bcount_nz_opt, (size), __deref_opt_out_bcount_opt(size)) -#define __deref_opt_inout_opt _SAL1_Source_(__deref_opt_inout_opt, (), __deref_inout_opt __pre_except_maybenull) -#define __deref_opt_inout_ecount_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_opt, (size), __deref_inout_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_opt, (size), __deref_inout_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_ecount_part_opt(size,length) _SAL1_Source_(__deref_opt_inout_ecount_part_opt, (size,length), __deref_inout_ecount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_inout_bcount_part_opt(size,length) _SAL1_Source_(__deref_opt_inout_bcount_part_opt, (size,length), __deref_inout_bcount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_inout_ecount_full_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_full_opt, (size), __deref_inout_ecount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_full_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_full_opt, (size), __deref_inout_bcount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_z_opt _SAL1_Source_(__deref_opt_inout_z_opt, (), __deref_opt_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_ecount_z_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_z_opt, (size), __deref_opt_inout_ecount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_bcount_z_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_z_opt, (size), __deref_opt_inout_bcount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_nz_opt _SAL1_Source_(__deref_opt_inout_nz_opt, (), __deref_opt_inout_opt) -#define __deref_opt_inout_ecount_nz_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_nz_opt, (size), __deref_opt_inout_ecount_opt(size)) -#define __deref_opt_inout_bcount_nz_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_nz_opt, (size), __deref_opt_inout_bcount_opt(size)) +#define __ecount(size) _SAL1_Source_(__ecount, (size), __notnull __elem_writableTo(size)) +#define __bcount(size) _SAL1_Source_(__bcount, (size), __notnull __byte_writableTo(size)) +#define __in_ecount(size) _SAL1_Source_(__in_ecount, (size), _In_reads_(size)) +#define __in_bcount(size) _SAL1_Source_(__in_bcount, (size), _In_reads_bytes_(size)) +#define __in_z _SAL1_Source_(__in_z, (), _In_z_) +#define __in_ecount_z(size) _SAL1_Source_(__in_ecount_z, (size), _In_reads_z_(size)) +#define __in_bcount_z(size) \ + _SAL1_Source_(__in_bcount_z, (size), __in_bcount(size) __pre __nullterminated) +#define __in_nz _SAL1_Source_(__in_nz, (), __in) +#define __in_ecount_nz(size) _SAL1_Source_(__in_ecount_nz, (size), __in_ecount(size)) +#define __in_bcount_nz(size) _SAL1_Source_(__in_bcount_nz, (size), __in_bcount(size)) +#define __out_ecount(size) _SAL1_Source_(__out_ecount, (size), _Out_writes_(size)) +#define __out_bcount(size) _SAL1_Source_(__out_bcount, (size), _Out_writes_bytes_(size)) +#define __out_ecount_part(size, length) \ + _SAL1_Source_(__out_ecount_part, (size, length), _Out_writes_to_(size, length)) +#define __out_bcount_part(size, length) \ + _SAL1_Source_(__out_bcount_part, (size, length), _Out_writes_bytes_to_(size, length)) +#define __out_ecount_full(size) _SAL1_Source_(__out_ecount_full, (size), _Out_writes_all_(size)) +#define __out_bcount_full(size) \ + _SAL1_Source_(__out_bcount_full, (size), _Out_writes_bytes_all_(size)) +#define __out_z _SAL1_Source_(__out_z, (), __post __valid __refparam __post __nullterminated) +#define __out_z_opt \ + _SAL1_Source_(__out_z_opt, (), \ + __post __valid __refparam __post __nullterminated __pre_except_maybenull) +#define __out_ecount_z(size) \ + _SAL1_Source_(__out_ecount_z, (size), \ + __ecount(size) __post __valid __refparam __post __nullterminated) +#define __out_bcount_z(size) \ + _SAL1_Source_(__out_bcount_z, (size), \ + __bcount(size) __post __valid __refparam __post __nullterminated) +#define __out_ecount_part_z(size, length) \ + _SAL1_Source_(__out_ecount_part_z, (size, length), \ + __out_ecount_part(size, length) __post __nullterminated) +#define __out_bcount_part_z(size, length) \ + _SAL1_Source_(__out_bcount_part_z, (size, length), \ + __out_bcount_part(size, length) __post __nullterminated) +#define __out_ecount_full_z(size) \ + _SAL1_Source_(__out_ecount_full_z, (size), __out_ecount_full(size) __post __nullterminated) +#define __out_bcount_full_z(size) \ + _SAL1_Source_(__out_bcount_full_z, (size), __out_bcount_full(size) __post __nullterminated) +#define __out_nz _SAL1_Source_(__out_nz, (), __post __valid __refparam) +#define __out_nz_opt \ + _SAL1_Source_(__out_nz_opt, (), __post __valid __refparam __post_except_maybenull_) +#define __out_ecount_nz(size) \ + _SAL1_Source_(__out_ecount_nz, (size), __ecount(size) __post __valid __refparam) +#define __out_bcount_nz(size) \ + _SAL1_Source_(__out_bcount_nz, (size), __bcount(size) __post __valid __refparam) +#define __inout _SAL1_Source_(__inout, (), _Inout_) +#define __inout_ecount(size) _SAL1_Source_(__inout_ecount, (size), _Inout_updates_(size)) +#define __inout_bcount(size) _SAL1_Source_(__inout_bcount, (size), _Inout_updates_bytes_(size)) +#define __inout_ecount_part(size, length) \ + _SAL1_Source_(__inout_ecount_part, (size, length), _Inout_updates_to_(size, length)) +#define __inout_bcount_part(size, length) \ + _SAL1_Source_(__inout_bcount_part, (size, length), _Inout_updates_bytes_to_(size, length)) +#define __inout_ecount_full(size) \ + _SAL1_Source_(__inout_ecount_full, (size), _Inout_updates_all_(size)) +#define __inout_bcount_full(size) \ + _SAL1_Source_(__inout_bcount_full, (size), _Inout_updates_bytes_all_(size)) +#define __inout_z _SAL1_Source_(__inout_z, (), _Inout_z_) +#define __inout_ecount_z(size) _SAL1_Source_(__inout_ecount_z, (size), _Inout_updates_z_(size)) +#define __inout_bcount_z(size) \ + _SAL1_Source_(__inout_bcount_z, (size), \ + __inout_bcount(size) __pre __nullterminated __post __nullterminated) +#define __inout_nz _SAL1_Source_(__inout_nz, (), __inout) +#define __inout_ecount_nz(size) _SAL1_Source_(__inout_ecount_nz, (size), __inout_ecount(size)) +#define __inout_bcount_nz(size) _SAL1_Source_(__inout_bcount_nz, (size), __inout_bcount(size)) +#define __ecount_opt(size) \ + _SAL1_Source_(__ecount_opt, (size), __ecount(size) __pre_except_maybenull) +#define __bcount_opt(size) \ + _SAL1_Source_(__bcount_opt, (size), __bcount(size) __pre_except_maybenull) +#define __in_opt _SAL1_Source_(__in_opt, (), _In_opt_) +#define __in_ecount_opt(size) _SAL1_Source_(__in_ecount_opt, (size), _In_reads_opt_(size)) +#define __in_bcount_opt(size) _SAL1_Source_(__in_bcount_opt, (size), _In_reads_bytes_opt_(size)) +#define __in_z_opt _SAL1_Source_(__in_z_opt, (), _In_opt_z_) +#define __in_ecount_z_opt(size) \ + _SAL1_Source_(__in_ecount_z_opt, (size), __in_ecount_opt(size) __pre __nullterminated) +#define __in_bcount_z_opt(size) \ + _SAL1_Source_(__in_bcount_z_opt, (size), __in_bcount_opt(size) __pre __nullterminated) +#define __in_nz_opt _SAL1_Source_(__in_nz_opt, (), __in_opt) +#define __in_ecount_nz_opt(size) _SAL1_Source_(__in_ecount_nz_opt, (size), __in_ecount_opt(size)) +#define __in_bcount_nz_opt(size) _SAL1_Source_(__in_bcount_nz_opt, (size), __in_bcount_opt(size)) +#define __out_opt _SAL1_Source_(__out_opt, (), _Out_opt_) +#define __out_ecount_opt(size) _SAL1_Source_(__out_ecount_opt, (size), _Out_writes_opt_(size)) +#define __out_bcount_opt(size) _SAL1_Source_(__out_bcount_opt, (size), _Out_writes_bytes_opt_(size)) +#define __out_ecount_part_opt(size, length) \ + _SAL1_Source_(__out_ecount_part_opt, (size, length), \ + __out_ecount_part(size, length) __pre_except_maybenull) +#define __out_bcount_part_opt(size, length) \ + _SAL1_Source_(__out_bcount_part_opt, (size, length), \ + __out_bcount_part(size, length) __pre_except_maybenull) +#define __out_ecount_full_opt(size) \ + _SAL1_Source_(__out_ecount_full_opt, (size), __out_ecount_full(size) __pre_except_maybenull) +#define __out_bcount_full_opt(size) \ + _SAL1_Source_(__out_bcount_full_opt, (size), __out_bcount_full(size) __pre_except_maybenull) +#define __out_ecount_z_opt(size) \ + _SAL1_Source_(__out_ecount_z_opt, (size), __out_ecount_opt(size) __post __nullterminated) +#define __out_bcount_z_opt(size) \ + _SAL1_Source_(__out_bcount_z_opt, (size), __out_bcount_opt(size) __post __nullterminated) +#define __out_ecount_part_z_opt(size, length) \ + _SAL1_Source_(__out_ecount_part_z_opt, (size, length), \ + __out_ecount_part_opt(size, length) __post __nullterminated) +#define __out_bcount_part_z_opt(size, length) \ + _SAL1_Source_(__out_bcount_part_z_opt, (size, length), \ + __out_bcount_part_opt(size, length) __post __nullterminated) +#define __out_ecount_full_z_opt(size) \ + _SAL1_Source_(__out_ecount_full_z_opt, (size), \ + __out_ecount_full_opt(size) __post __nullterminated) +#define __out_bcount_full_z_opt(size) \ + _SAL1_Source_(__out_bcount_full_z_opt, (size), \ + __out_bcount_full_opt(size) __post __nullterminated) +#define __out_ecount_nz_opt(size) \ + _SAL1_Source_(__out_ecount_nz_opt, (size), __out_ecount_opt(size) __post __nullterminated) +#define __out_bcount_nz_opt(size) \ + _SAL1_Source_(__out_bcount_nz_opt, (size), __out_bcount_opt(size) __post __nullterminated) +#define __inout_opt _SAL1_Source_(__inout_opt, (), _Inout_opt_) +#define __inout_ecount_opt(size) \ + _SAL1_Source_(__inout_ecount_opt, (size), __inout_ecount(size) __pre_except_maybenull) +#define __inout_bcount_opt(size) \ + _SAL1_Source_(__inout_bcount_opt, (size), __inout_bcount(size) __pre_except_maybenull) +#define __inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__inout_ecount_part_opt, (size, length), \ + __inout_ecount_part(size, length) __pre_except_maybenull) +#define __inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__inout_bcount_part_opt, (size, length), \ + __inout_bcount_part(size, length) __pre_except_maybenull) +#define __inout_ecount_full_opt(size) \ + _SAL1_Source_(__inout_ecount_full_opt, (size), __inout_ecount_full(size) __pre_except_maybenull) +#define __inout_bcount_full_opt(size) \ + _SAL1_Source_(__inout_bcount_full_opt, (size), __inout_bcount_full(size) __pre_except_maybenull) +#define __inout_z_opt \ + _SAL1_Source_(__inout_z_opt, (), __inout_opt __pre __nullterminated __post __nullterminated) +#define __inout_ecount_z_opt(size) \ + _SAL1_Source_(__inout_ecount_z_opt, (size), \ + __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) +#define __inout_ecount_z_opt(size) \ + _SAL1_Source_(__inout_ecount_z_opt, (size), \ + __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) +#define __inout_bcount_z_opt(size) \ + _SAL1_Source_(__inout_bcount_z_opt, (size), __inout_bcount_opt(size)) +#define __inout_nz_opt _SAL1_Source_(__inout_nz_opt, (), __inout_opt) +#define __inout_ecount_nz_opt(size) \ + _SAL1_Source_(__inout_ecount_nz_opt, (size), __inout_ecount_opt(size)) +#define __inout_bcount_nz_opt(size) \ + _SAL1_Source_(__inout_bcount_nz_opt, (size), __inout_bcount_opt(size)) +#define __deref_ecount(size) \ + _SAL1_Source_( \ + __deref_ecount, (size), \ + _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) \ + __post _Notref_ __deref _Notref_ __notnull __post __deref __elem_writableTo(size)) +#define __deref_bcount(size) \ + _SAL1_Source_( \ + __deref_bcount, (size), \ + _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) \ + __post _Notref_ __deref _Notref_ __notnull __post __deref __byte_writableTo(size)) +#define __deref_out _SAL1_Source_(__deref_out, (), _Outptr_) +#define __deref_out_ecount(size) \ + _SAL1_Source_(__deref_out_ecount, (size), _Outptr_result_buffer_(size)) +#define __deref_out_bcount(size) \ + _SAL1_Source_(__deref_out_bcount, (size), _Outptr_result_bytebuffer_(size)) +#define __deref_out_ecount_part(size, length) \ + _SAL1_Source_(__deref_out_ecount_part, (size, length), _Outptr_result_buffer_to_(size, length)) +#define __deref_out_bcount_part(size, length) \ + _SAL1_Source_(__deref_out_bcount_part, (size, length), \ + _Outptr_result_bytebuffer_to_(size, length)) +#define __deref_out_ecount_full(size) \ + _SAL1_Source_(__deref_out_ecount_full, (size), __deref_out_ecount_part(size, size)) +#define __deref_out_bcount_full(size) \ + _SAL1_Source_(__deref_out_bcount_full, (size), __deref_out_bcount_part(size, size)) +#define __deref_out_z _SAL1_Source_(__deref_out_z, (), _Outptr_result_z_) +#define __deref_out_ecount_z(size) \ + _SAL1_Source_(__deref_out_ecount_z, (size), \ + __deref_out_ecount(size) __post __deref __nullterminated) +#define __deref_out_bcount_z(size) \ + _SAL1_Source_(__deref_out_bcount_z, (size), \ + __deref_out_bcount(size) __post __deref __nullterminated) +#define __deref_out_nz _SAL1_Source_(__deref_out_nz, (), __deref_out) +#define __deref_out_ecount_nz(size) \ + _SAL1_Source_(__deref_out_ecount_nz, (size), __deref_out_ecount(size)) +#define __deref_out_bcount_nz(size) \ + _SAL1_Source_(__deref_out_bcount_nz, (size), __deref_out_ecount(size)) +#define __deref_inout \ + _SAL1_Source_(__deref_inout, (), \ + _Notref_ __notnull _Notref_ __elem_readableTo(1) \ + __pre __deref __valid __post _Notref_ __deref __valid __refparam) +#define __deref_inout_z \ + _SAL1_Source_( \ + __deref_inout_z, (), \ + __deref_inout __pre __deref __nullterminated __post _Notref_ __deref __nullterminated) +#define __deref_inout_ecount(size) \ + _SAL1_Source_(__deref_inout_ecount, (size), \ + __deref_inout __pre __deref __elem_writableTo(size) \ + __post _Notref_ __deref __elem_writableTo(size)) +#define __deref_inout_bcount(size) \ + _SAL1_Source_(__deref_inout_bcount, (size), \ + __deref_inout __pre __deref __byte_writableTo(size) \ + __post _Notref_ __deref __byte_writableTo(size)) +#define __deref_inout_ecount_part(size, length) \ + _SAL1_Source_(__deref_inout_ecount_part, (size, length), \ + __deref_inout_ecount(size) __pre __deref __elem_readableTo(length) \ + __post __deref __elem_readableTo(length)) +#define __deref_inout_bcount_part(size, length) \ + _SAL1_Source_(__deref_inout_bcount_part, (size, length), \ + __deref_inout_bcount(size) __pre __deref __byte_readableTo(length) \ + __post __deref __byte_readableTo(length)) +#define __deref_inout_ecount_full(size) \ + _SAL1_Source_(__deref_inout_ecount_full, (size), __deref_inout_ecount_part(size, size)) +#define __deref_inout_bcount_full(size) \ + _SAL1_Source_(__deref_inout_bcount_full, (size), __deref_inout_bcount_part(size, size)) +#define __deref_inout_ecount_z(size) \ + _SAL1_Source_(__deref_inout_ecount_z, (size), \ + __deref_inout_ecount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_bcount_z(size) \ + _SAL1_Source_(__deref_inout_bcount_z, (size), \ + __deref_inout_bcount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_nz _SAL1_Source_(__deref_inout_nz, (), __deref_inout) +#define __deref_inout_ecount_nz(size) \ + _SAL1_Source_(__deref_inout_ecount_nz, (size), __deref_inout_ecount(size)) +#define __deref_inout_bcount_nz(size) \ + _SAL1_Source_(__deref_inout_bcount_nz, (size), __deref_inout_ecount(size)) +#define __deref_ecount_opt(size) \ + _SAL1_Source_(__deref_ecount_opt, (size), __deref_ecount(size) __post_deref_except_maybenull) +#define __deref_bcount_opt(size) \ + _SAL1_Source_(__deref_bcount_opt, (size), __deref_bcount(size) __post_deref_except_maybenull) +#define __deref_out_opt \ + _SAL1_Source_(__deref_out_opt, (), __deref_out __post_deref_except_maybenull) +#define __deref_out_ecount_opt(size) \ + _SAL1_Source_(__deref_out_ecount_opt, (size), \ + __deref_out_ecount(size) __post_deref_except_maybenull) +#define __deref_out_bcount_opt(size) \ + _SAL1_Source_(__deref_out_bcount_opt, (size), \ + __deref_out_bcount(size) __post_deref_except_maybenull) +#define __deref_out_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_out_ecount_part_opt, (size, length), \ + __deref_out_ecount_part(size, length) __post_deref_except_maybenull) +#define __deref_out_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_out_bcount_part_opt, (size, length), \ + __deref_out_bcount_part(size, length) __post_deref_except_maybenull) +#define __deref_out_ecount_full_opt(size) \ + _SAL1_Source_(__deref_out_ecount_full_opt, (size), \ + __deref_out_ecount_full(size) __post_deref_except_maybenull) +#define __deref_out_bcount_full_opt(size) \ + _SAL1_Source_(__deref_out_bcount_full_opt, (size), \ + __deref_out_bcount_full(size) __post_deref_except_maybenull) +#define __deref_out_z_opt _SAL1_Source_(__deref_out_z_opt, (), _Outptr_result_maybenull_z_) +#define __deref_out_ecount_z_opt(size) \ + _SAL1_Source_(__deref_out_ecount_z_opt, (size), \ + __deref_out_ecount_opt(size) __post __deref __nullterminated) +#define __deref_out_bcount_z_opt(size) \ + _SAL1_Source_(__deref_out_bcount_z_opt, (size), \ + __deref_out_bcount_opt(size) __post __deref __nullterminated) +#define __deref_out_nz_opt _SAL1_Source_(__deref_out_nz_opt, (), __deref_out_opt) +#define __deref_out_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_out_ecount_nz_opt, (size), __deref_out_ecount_opt(size)) +#define __deref_out_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_out_bcount_nz_opt, (size), __deref_out_bcount_opt(size)) +#define __deref_inout_opt \ + _SAL1_Source_(__deref_inout_opt, (), \ + __deref_inout __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_opt, (size), \ + __deref_inout_ecount(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_opt, (size), \ + __deref_inout_bcount(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_inout_ecount_part_opt, (size, length), \ + __deref_inout_ecount_part(size, length) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_inout_bcount_part_opt, (size, length), \ + __deref_inout_bcount_part(size, length) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_full_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_full_opt, (size), \ + __deref_inout_ecount_full(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_full_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_full_opt, (size), \ + __deref_inout_bcount_full(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_z_opt \ + _SAL1_Source_( \ + __deref_inout_z_opt, (), \ + __deref_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_ecount_z_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_z_opt, (size), \ + __deref_inout_ecount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_bcount_z_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_z_opt, (size), \ + __deref_inout_bcount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_nz_opt _SAL1_Source_(__deref_inout_nz_opt, (), __deref_inout_opt) +#define __deref_inout_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_nz_opt, (size), __deref_inout_ecount_opt(size)) +#define __deref_inout_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_nz_opt, (size), __deref_inout_bcount_opt(size)) +#define __deref_opt_ecount(size) \ + _SAL1_Source_(__deref_opt_ecount, (size), __deref_ecount(size) __pre_except_maybenull) +#define __deref_opt_bcount(size) \ + _SAL1_Source_(__deref_opt_bcount, (size), __deref_bcount(size) __pre_except_maybenull) +#define __deref_opt_out _SAL1_Source_(__deref_opt_out, (), _Outptr_opt_) +#define __deref_opt_out_z _SAL1_Source_(__deref_opt_out_z, (), _Outptr_opt_result_z_) +#define __deref_opt_out_ecount(size) \ + _SAL1_Source_(__deref_opt_out_ecount, (size), __deref_out_ecount(size) __pre_except_maybenull) +#define __deref_opt_out_bcount(size) \ + _SAL1_Source_(__deref_opt_out_bcount, (size), __deref_out_bcount(size) __pre_except_maybenull) +#define __deref_opt_out_ecount_part(size, length) \ + _SAL1_Source_(__deref_opt_out_ecount_part, (size, length), \ + __deref_out_ecount_part(size, length) __pre_except_maybenull) +#define __deref_opt_out_bcount_part(size, length) \ + _SAL1_Source_(__deref_opt_out_bcount_part, (size, length), \ + __deref_out_bcount_part(size, length) __pre_except_maybenull) +#define __deref_opt_out_ecount_full(size) \ + _SAL1_Source_(__deref_opt_out_ecount_full, (size), \ + __deref_out_ecount_full(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_full(size) \ + _SAL1_Source_(__deref_opt_out_bcount_full, (size), \ + __deref_out_bcount_full(size) __pre_except_maybenull) +#define __deref_opt_inout _SAL1_Source_(__deref_opt_inout, (), _Inout_opt_) +#define __deref_opt_inout_ecount(size) \ + _SAL1_Source_(__deref_opt_inout_ecount, (size), \ + __deref_inout_ecount(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount(size) \ + _SAL1_Source_(__deref_opt_inout_bcount, (size), \ + __deref_inout_bcount(size) __pre_except_maybenull) +#define __deref_opt_inout_ecount_part(size, length) \ + _SAL1_Source_(__deref_opt_inout_ecount_part, (size, length), \ + __deref_inout_ecount_part(size, length) __pre_except_maybenull) +#define __deref_opt_inout_bcount_part(size, length) \ + _SAL1_Source_(__deref_opt_inout_bcount_part, (size, length), \ + __deref_inout_bcount_part(size, length) __pre_except_maybenull) +#define __deref_opt_inout_ecount_full(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_full, (size), \ + __deref_inout_ecount_full(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_full(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_full, (size), \ + __deref_inout_bcount_full(size) __pre_except_maybenull) +#define __deref_opt_inout_z \ + _SAL1_Source_( \ + __deref_opt_inout_z, (), \ + __deref_opt_inout __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_ecount_z(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_z, (size), \ + __deref_opt_inout_ecount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_bcount_z(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_z, (size), \ + __deref_opt_inout_bcount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_nz _SAL1_Source_(__deref_opt_inout_nz, (), __deref_opt_inout) +#define __deref_opt_inout_ecount_nz(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_nz, (size), __deref_opt_inout_ecount(size)) +#define __deref_opt_inout_bcount_nz(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_nz, (size), __deref_opt_inout_bcount(size)) +#define __deref_opt_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_ecount_opt, (size), __deref_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_bcount_opt, (size), __deref_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_opt _SAL1_Source_(__deref_opt_out_opt, (), _Outptr_opt_result_maybenull_) +#define __deref_opt_out_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_opt, (size), \ + __deref_out_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_opt, (size), \ + __deref_out_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_out_ecount_part_opt, (size, length), \ + __deref_out_ecount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_out_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_out_bcount_part_opt, (size, length), \ + __deref_out_bcount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_out_ecount_full_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_full_opt, (size), \ + __deref_out_ecount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_full_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_full_opt, (size), \ + __deref_out_bcount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_out_z_opt \ + _SAL1_Source_( \ + __deref_opt_out_z_opt, (), \ + __post __deref __valid __refparam __pre_except_maybenull __pre_deref_except_maybenull \ + __post_deref_except_maybenull __post __deref __nullterminated) +#define __deref_opt_out_ecount_z_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_z_opt, (size), \ + __deref_opt_out_ecount_opt(size) __post __deref __nullterminated) +#define __deref_opt_out_bcount_z_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_z_opt, (size), \ + __deref_opt_out_bcount_opt(size) __post __deref __nullterminated) +#define __deref_opt_out_nz_opt _SAL1_Source_(__deref_opt_out_nz_opt, (), __deref_opt_out_opt) +#define __deref_opt_out_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_nz_opt, (size), __deref_opt_out_ecount_opt(size)) +#define __deref_opt_out_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_nz_opt, (size), __deref_opt_out_bcount_opt(size)) +#define __deref_opt_inout_opt \ + _SAL1_Source_(__deref_opt_inout_opt, (), __deref_inout_opt __pre_except_maybenull) +#define __deref_opt_inout_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_opt, (size), \ + __deref_inout_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_opt, (size), \ + __deref_inout_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_inout_ecount_part_opt, (size, length), \ + __deref_inout_ecount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_inout_bcount_part_opt, (size, length), \ + __deref_inout_bcount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_inout_ecount_full_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_full_opt, (size), \ + __deref_inout_ecount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_full_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_full_opt, (size), \ + __deref_inout_bcount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_z_opt \ + _SAL1_Source_( \ + __deref_opt_inout_z_opt, (), \ + __deref_opt_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_ecount_z_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_z_opt, (size), \ + __deref_opt_inout_ecount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_bcount_z_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_z_opt, (size), \ + __deref_opt_inout_bcount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_nz_opt _SAL1_Source_(__deref_opt_inout_nz_opt, (), __deref_opt_inout_opt) +#define __deref_opt_inout_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_nz_opt, (size), __deref_opt_inout_ecount_opt(size)) +#define __deref_opt_inout_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_nz_opt, (size), __deref_opt_inout_bcount_opt(size)) /* ------------------------------------------------------------------------------- @@ -2839,59 +4139,58 @@ of each annotation, see the advanced annotations section. ------------------------------------------------------------------------------- */ -#define __success(expr) _Success_(expr) -#define __nullterminated _Null_terminated_ +#define __success(expr) _Success_(expr) +#define __nullterminated _Null_terminated_ #define __nullnullterminated -#define __clr_reserved _SAL1_Source_(__reserved, (), _Reserved_) -#define __checkReturn _SAL1_Source_(__checkReturn, (), _Check_return_) -#define __typefix(ctype) _SAL1_Source_(__typefix, (ctype), __inner_typefix(ctype)) -#define __override __inner_override -#define __callback __inner_callback -#define __format_string _Printf_format_string_ -#define __blocksOn(resource) __inner_blocksOn(resource) -#define __control_entrypoint(category) __inner_control_entrypoint(category) -#define __data_entrypoint(category) __inner_data_entrypoint(category) -#define __useHeader _Use_decl_anno_impl_ -#define __on_failure(annotes) _On_failure_impl_(annotes _SAL_nop_impl_) +#define __clr_reserved _SAL1_Source_(__reserved, (), _Reserved_) +#define __checkReturn _SAL1_Source_(__checkReturn, (), _Check_return_) +#define __typefix(ctype) _SAL1_Source_(__typefix, (ctype), __inner_typefix(ctype)) +#define __override __inner_override +#define __callback __inner_callback +#define __format_string _Printf_format_string_ +#define __blocksOn(resource) __inner_blocksOn(resource) +#define __control_entrypoint(category) __inner_control_entrypoint(category) +#define __data_entrypoint(category) __inner_data_entrypoint(category) +#define __useHeader _Use_decl_anno_impl_ +#define __on_failure(annotes) _On_failure_impl_(annotes _SAL_nop_impl_) #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) (0) #endif -#ifndef __fallthrough // [ +#ifndef __fallthrough // [ #if __has_cpp_attribute(fallthrough) #define __fallthrough [[fallthrough]] #else #define __fallthrough #endif -#endif // ] +#endif // ] -#ifndef __analysis_assume // [ -#ifdef _PREFAST_ // [ +#ifndef __analysis_assume // [ +#ifdef _PREFAST_ // [ #define __analysis_assume(expr) __assume(expr) -#else // ][ +#else // ][ #define __analysis_assume(expr) -#endif // ] -#endif // ] +#endif // ] +#endif // ] -#ifndef _Analysis_assume_ // [ -#ifdef _PREFAST_ // [ +#ifndef _Analysis_assume_ // [ +#ifdef _PREFAST_ // [ #define _Analysis_assume_(expr) __assume(expr) -#else // ][ +#else // ][ #define _Analysis_assume_(expr) -#endif // ] -#endif // ] +#endif // ] +#endif // ] -#define _Analysis_noreturn_ _SAL2_Source_(_Analysis_noreturn_, (), _SA_annotes0(SAL_terminates)) +#define _Analysis_noreturn_ _SAL2_Source_(_Analysis_noreturn_, (), _SA_annotes0(SAL_terminates)) -#ifdef _PREFAST_ // [ -__inline __nothrow -void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); +#ifdef _PREFAST_ // [ +__inline __nothrow void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); #define _Analysis_assume_nullterminated_(x) __AnalysisAssumeNullterminated(x) -#else // ][ +#else // ][ #define _Analysis_assume_nullterminated_(x) -#endif // ] +#endif // ] // // Set the analysis mode (global flags to analysis). @@ -2900,7 +4199,7 @@ void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); // // Synthesize a unique symbol. -#define ___MKID(x, y) x ## y +#define ___MKID(x, y) x##y #define __MKID(x, y) ___MKID(x, y) #define __GENSYM(x) __MKID(x, __COUNTER__) @@ -2908,9 +4207,8 @@ __ANNOTATION(SAL_analysisMode(__AuToQuOtE __In_impl_ char *mode);) #define _Analysis_mode_impl_(mode) _SA_annotes1(SAL_analysisMode, #mode) -#define _Analysis_mode_(mode) \ - typedef _Analysis_mode_impl_(mode) int \ - __GENSYM(__prefast_analysis_mode_flag); +#define _Analysis_mode_(mode) \ + typedef _Analysis_mode_impl_(mode) int __GENSYM(__prefast_analysis_mode_flag); // The following are predefined: // _Analysis_operator_new_throw_ (operator new throws) @@ -2919,23 +4217,23 @@ __ANNOTATION(SAL_analysisMode(__AuToQuOtE __In_impl_ char *mode);) // // Function class annotations. -__ANNOTATION(SAL_functionClassNew(__In_impl_ char*);) -__PRIMOP(int, _In_function_class_(__In_impl_ char*);) -#define _In_function_class_(x) _In_function_class_(#x) +__ANNOTATION(SAL_functionClassNew(__In_impl_ char *);) +__PRIMOP(int, _In_function_class_(__In_impl_ char *);) +#define _In_function_class_(x) _In_function_class_(#x) -#define _Function_class_(x) _SA_annotes1(SAL_functionClassNew, #x) +#define _Function_class_(x) _SA_annotes1(SAL_functionClassNew, #x) /* * interlocked operand used in interlocked instructions */ -//#define _Interlocked_operand_ _Pre_ _SA_annotes0(SAL_interlocked) +// #define _Interlocked_operand_ _Pre_ _SA_annotes0(SAL_interlocked) -#define _Enum_is_bitflag_ _SA_annotes0(SAL_enumIsBitflag) -#define _Strict_type_match_ _SA_annotes0(SAL_strictType2) +#define _Enum_is_bitflag_ _SA_annotes0(SAL_enumIsBitflag) +#define _Strict_type_match_ _SA_annotes0(SAL_strictType2) -#define _Maybe_raises_SEH_exception_ _Pre_ _SA_annotes1(SAL_inTry,__yes) -#define _Raises_SEH_exception_ _Group_(_Maybe_raises_SEH_exception_ _Analysis_noreturn_) +#define _Maybe_raises_SEH_exception_ _Pre_ _SA_annotes1(SAL_inTry, __yes) +#define _Raises_SEH_exception_ _Group_(_Maybe_raises_SEH_exception_ _Analysis_noreturn_) -#ifdef __cplusplus // [ +#ifdef __cplusplus // [ } -#endif // ] \ No newline at end of file +#endif // ] \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h b/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h index efa4a9c6b..8e66424cc 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h @@ -32,4 +32,4 @@ #include "xbox_stubs.h" #include "iggy_stubs.h" -#endif // STUBS_H \ No newline at end of file +#endif // STUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h index 52edb5625..7d6175c6c 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h @@ -8,12 +8,11 @@ using namespace DirectX; -typedef struct _RECT -{ - LONG left; - LONG top; - LONG right; - LONG bottom; +typedef struct _RECT { + LONG left; + LONG top; + LONG right; + LONG bottom; } RECT, *PRECT; // stole- i mean borrowed from OrbisStubs.h @@ -27,45 +26,42 @@ typedef void ID3D11Buffer; // typedef DWORD (*PTHREAD_START_ROUTINE)( LPVOID lpThreadParameter); // typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; -// Used only by windows/durango gdraw and UIController. Will be unnecessary once we have our own -// UIController stubs. +// Used only by windows/durango gdraw and UIController. Will be unnecessary once +// we have our own UIController stubs. typedef void ID3D11ShaderResourceView; typedef void ID3D11Resource; typedef void ID3D11Texture2D; typedef void D3D11_TEXTURE2D_DESC; -enum D3D11_BLEND -{ - D3D11_BLEND_ZERO = 1, - D3D11_BLEND_ONE = 2, - D3D11_BLEND_SRC_COLOR = 3, - D3D11_BLEND_INV_SRC_COLOR = 4, - D3D11_BLEND_SRC_ALPHA = 5, - D3D11_BLEND_INV_SRC_ALPHA = 6, - D3D11_BLEND_DEST_ALPHA = 7, - D3D11_BLEND_INV_DEST_ALPHA = 8, - D3D11_BLEND_DEST_COLOR = 9, - D3D11_BLEND_INV_DEST_COLOR = 10, - D3D11_BLEND_SRC_ALPHA_SAT = 11, - D3D11_BLEND_BLEND_FACTOR = 14, - D3D11_BLEND_INV_BLEND_FACTOR = 15, - D3D11_BLEND_SRC1_COLOR = 16, - D3D11_BLEND_INV_SRC1_COLOR = 17, - D3D11_BLEND_SRC1_ALPHA = 18, - D3D11_BLEND_INV_SRC1_ALPHA = 19 +enum D3D11_BLEND { + D3D11_BLEND_ZERO = 1, + D3D11_BLEND_ONE = 2, + D3D11_BLEND_SRC_COLOR = 3, + D3D11_BLEND_INV_SRC_COLOR = 4, + D3D11_BLEND_SRC_ALPHA = 5, + D3D11_BLEND_INV_SRC_ALPHA = 6, + D3D11_BLEND_DEST_ALPHA = 7, + D3D11_BLEND_INV_DEST_ALPHA = 8, + D3D11_BLEND_DEST_COLOR = 9, + D3D11_BLEND_INV_DEST_COLOR = 10, + D3D11_BLEND_SRC_ALPHA_SAT = 11, + D3D11_BLEND_BLEND_FACTOR = 14, + D3D11_BLEND_INV_BLEND_FACTOR = 15, + D3D11_BLEND_SRC1_COLOR = 16, + D3D11_BLEND_INV_SRC1_COLOR = 17, + D3D11_BLEND_SRC1_ALPHA = 18, + D3D11_BLEND_INV_SRC1_ALPHA = 19 }; - -enum D3D11_COMPARISON_FUNC -{ - D3D11_COMPARISON_NEVER = 1, - D3D11_COMPARISON_LESS = 2, - D3D11_COMPARISON_EQUAL = 3, - D3D11_COMPARISON_LESS_EQUAL = 4, - D3D11_COMPARISON_GREATER = 5, - D3D11_COMPARISON_NOT_EQUAL = 6, - D3D11_COMPARISON_GREATER_EQUAL = 7, - D3D11_COMPARISON_ALWAYS = 8 +enum D3D11_COMPARISON_FUNC { + D3D11_COMPARISON_NEVER = 1, + D3D11_COMPARISON_LESS = 2, + D3D11_COMPARISON_EQUAL = 3, + D3D11_COMPARISON_LESS_EQUAL = 4, + D3D11_COMPARISON_GREATER = 5, + D3D11_COMPARISON_NOT_EQUAL = 6, + D3D11_COMPARISON_GREATER_EQUAL = 7, + D3D11_COMPARISON_ALWAYS = 8 }; -#endif // D3D11STUBS_H \ No newline at end of file +#endif // D3D11STUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h index 220dbe7fa..97e1cd80a 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h @@ -3,225 +3,258 @@ #pragma once - #include "../../Windows64/Iggy/include/iggy.h" -#define STUBBED {} +#define STUBBED \ + { \ + } -RADEXPFUNC inline IggyValuePath * RADEXPLINK IggyPlayerRootPath(Iggy *f) { - STUBBED; - return nullptr; +RADEXPFUNC inline IggyValuePath* RADEXPLINK IggyPlayerRootPath(Iggy* f) { + STUBBED; + return nullptr; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyPlayerCallMethodRS(Iggy *f, IggyDataValue *result, IggyValuePath *target, IggyName methodname, S32 numargs, IggyDataValue *args) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyPlayerCallMethodRS(Iggy* f, IggyDataValue* result, IggyValuePath* target, + IggyName methodname, S32 numargs, IggyDataValue* args) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy *player) { - STUBBED; -} -RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy *f, S32 w, S32 h) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy* player) { STUBBED; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy* f, S32 w, + S32 h) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy *f) { - STUBBED; -} +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy* f) { STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy *f, S32 x0, S32 y0, S32 x1, S32 y1, S32 padding) { - STUBBED; -} -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy *f) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy* f, S32 x0, S32 y0, + S32 x1, S32 y1, + S32 padding) { + STUBBED; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy* f) { STUBBED; } // Each fake Iggy player gets its own state block struct FakeIggyPlayer { - int tickCount; - bool needsTick; - IggyProperties props; - void *userdata; + int tickCount; + bool needsTick; + IggyProperties props; + void* userdata; }; -// Simple player pool +// Simple player pool static FakeIggyPlayer s_fakePlayers[64]; static int s_fakePlayerCount = 0; -RADEXPFUNC inline Iggy * RADEXPLINK IggyPlayerCreateFromMemory( - void const * data, - U32 data_size_in_bytes, - IggyPlayerConfig *config) { - if(s_fakePlayerCount >= 64) return nullptr; - FakeIggyPlayer *fp = &s_fakePlayers[s_fakePlayerCount++]; - fp->tickCount = 0; - fp->needsTick = true; - fp->userdata = nullptr; - // Default to 1920x1080 at 30fps - memset(&fp->props, 0, sizeof(fp->props)); - fp->props.movie_width_in_pixels = 1920; - fp->props.movie_height_in_pixels = 1080; - fp->props.movie_frame_rate_from_file_in_fps = 30.0f; - fp->props.movie_frame_rate_current_in_fps = 30.0f; - fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n", s_fakePlayerCount-1, data, data_size_in_bytes); - return (Iggy*)fp; +RADEXPFUNC inline Iggy* RADEXPLINK IggyPlayerCreateFromMemory( + void const* data, U32 data_size_in_bytes, IggyPlayerConfig* config) { + if (s_fakePlayerCount >= 64) return nullptr; + FakeIggyPlayer* fp = &s_fakePlayers[s_fakePlayerCount++]; + fp->tickCount = 0; + fp->needsTick = true; + fp->userdata = nullptr; + // Default to 1920x1080 at 30fps + memset(&fp->props, 0, sizeof(fp->props)); + fp->props.movie_width_in_pixels = 1920; + fp->props.movie_height_in_pixels = 1080; + fp->props.movie_frame_rate_from_file_in_fps = 30.0f; + fp->props.movie_frame_rate_current_in_fps = 30.0f; + fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n", + s_fakePlayerCount - 1, data, data_size_in_bytes); + return (Iggy*)fp; } -static FakeIggyPlayer* getFakePlayer(Iggy *player) { - return (FakeIggyPlayer*)player; +static FakeIggyPlayer* getFakePlayer(Iggy* player) { + return (FakeIggyPlayer*)player; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) { fp->tickCount = 0; fp->needsTick = true; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) { + fp->tickCount = 0; + fp->needsTick = true; + } } -RADEXPFUNC inline IggyProperties * RADEXPLINK IggyPlayerProperties(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) return &fp->props; - static IggyProperties defaultProps = {}; - return &defaultProps; +RADEXPFUNC inline IggyProperties* RADEXPLINK +IggyPlayerProperties(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) return &fp->props; + static IggyProperties defaultProps = {}; + return &defaultProps; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy *player, void *userdata) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) fp->userdata = userdata; +RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy* player, + void* userdata) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) fp->userdata = userdata; } -RADEXPFUNC inline IggyName RADEXPLINK IggyPlayerCreateFastName(Iggy *f, IggyUTF16 const *name, S32 len) { - STUBBED; - return 0; +RADEXPFUNC inline IggyName RADEXPLINK +IggyPlayerCreateFastName(Iggy* f, IggyUTF16 const* name, S32 len) { + STUBBED; + return 0; } -RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo(Iggy *player, IggyLibrary lib, char const *category_string, S32 category_stringlen, S32 iteration, IggyMemoryUseInfo *data) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo( + Iggy* player, IggyLibrary lib, char const* category_string, + S32 category_stringlen, S32 iteration, IggyMemoryUseInfo* data) { + STUBBED; + return false; } -RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp && fp->needsTick) return true; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp && fp->needsTick) return true; + return false; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) { - fp->tickCount++; - // Allow one tick per frame cycle - fp->needsTick = false; - } +RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) { + fp->tickCount++; + // Allow one tick per frame cycle + fp->needsTick = false; + } } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy *f) { - // Re-arm tick for next frame - FakeIggyPlayer *fp = getFakePlayer(f); - if(fp) fp->needsTick = true; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy* f) { + // Re-arm tick for next frame + FakeIggyPlayer* fp = getFakePlayer(f); + if (fp) fp->needsTick = true; } -RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent *event, IggyKeyevent event_type, IggyKeycode keycode, IggyKeyloc keyloc) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent* event, + IggyKeyevent event_type, + IggyKeycode keycode, + IggyKeyloc keyloc) { + STUBBED; } -RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS(Iggy *player, IggyEvent *event, IggyEventResult *result) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS( + Iggy* player, IggyEvent* event, IggyEventResult* result) { + STUBBED; + return false; } -RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char* fontname, + S32 namelen_in_bytes, + U32 fontflags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8(const IggyBitmapFontProvider *bmf, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8( + const IggyBitmapFontProvider* bmf, const char* fontname, + S32 namelen_in_bytes, U32 fontflags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8(const char *request_name, S32 request_namelen, U32 request_flags, const char *result_name, S32 result_namelen, U32 result_flags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8( + const char* request_name, S32 request_namelen, U32 request_flags, + const char* result_name, S32 result_namelen, U32 result_flags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8(const void *truetype_storage, S32 ttc_index, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8( + const void* truetype_storage, S32 ttc_index, const char* fontname, + S32 namelen_in_bytes, U32 fontflags) { + STUBBED; } -RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef(IggyValuePath *result, IggyValuePath *parent, char const *text_utf8) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef( + IggyValuePath* result, IggyValuePath* parent, char const* text_utf8) { + STUBBED; + return false; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool *result) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyValueGetBooleanRS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, rrbool* result) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8(const char *fontname, S32 len, U32 fontflags, S32 fallback_codepoint) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8( + const char* fontname, S32 len, U32 fontflags, S32 fallback_codepoint) { + STUBBED; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetF64RS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, F64 *result) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyValueGetF64RS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, F64* result) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline rrbool RADEXPLINK IggyValueSetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool value) { - STUBBED; - return true; +RADEXPFUNC inline rrbool RADEXPLINK +IggyValueSetBooleanRS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, rrbool value) { + STUBBED; + return true; } -RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator *allocator) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator* allocator) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetWarningCallback(Iggy_WarningFunction *error, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK +IggySetWarningCallback(Iggy_WarningFunction* error, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8(Iggy_TraceFunctionUTF8 *trace_utf8, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8( + Iggy_TraceFunctionUTF8* trace_utf8, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetFontCachingCalculationBuffer( - S32 max_chars, - void *optional_temp_buffer, - S32 optional_temp_buffer_size_in_bytes) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK +IggySetFontCachingCalculationBuffer(S32 max_chars, void* optional_temp_buffer, + S32 optional_temp_buffer_size_in_bytes) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback(Iggy_CustomDrawCallback *custom_draw, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback( + Iggy_CustomDrawCallback* custom_draw, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16(Iggy_AS3ExternalFunctionUTF16 *as3_external_function_utf16, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16( + Iggy_AS3ExternalFunctionUTF16* as3_external_function_utf16, + void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent *event, S32 x, S32 y) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent* event, + S32 x, S32 y) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks(Iggy_TextureSubstitutionCreateCallback *texture_create, Iggy_TextureSubstitutionDestroyCallback *texture_destroy, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks( + Iggy_TextureSubstitutionCreateCallback* texture_create, + Iggy_TextureSubstitutionDestroyCallback* texture_destroy, + void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void * RADEXPLINK IggyPlayerGetUserdata(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) return fp->userdata; - return 0; +RADEXPFUNC inline void* RADEXPLINK IggyPlayerGetUserdata(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) return fp->userdata; + return 0; } -RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16( - IggyUTF16 const * url_utf16_null_terminated, - void const * data, - U32 data_size_in_bytes, - IggyPlayerConfig *config) { - STUBBED; - return 0; +RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16( + IggyUTF16 const* url_utf16_null_terminated, void const* data, + U32 data_size_in_bytes, IggyPlayerConfig* config) { + STUBBED; + return 0; } RADEXPFUNC inline void RADEXPLINK IggyLibraryDestroy(IggyLibrary lib) { - STUBBED; + STUBBED; } // Iggy is fake -static GDrawFunctions *s_iggy_gdraw_funcs = 0; -RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions *gdraw_funcs) { - s_iggy_gdraw_funcs = gdraw_funcs; +static GDrawFunctions* s_iggy_gdraw_funcs = 0; +RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions* gdraw_funcs) { + s_iggy_gdraw_funcs = gdraw_funcs; } // Audio stubs -RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { - STUBBED; -} +RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { STUBBED; } // Explorer/Perfmon, shit implmentation -RADEXPFUNC inline void * RADEXPLINK IggyExpCreate(const char *host, int port, void *storage, int storage_size) { - STUBBED; - return 0; +RADEXPFUNC inline void* RADEXPLINK IggyExpCreate(const char* host, int port, + void* storage, + int storage_size) { + STUBBED; + return 0; } -RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy *player, void *explorer) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy* player, + void* explorer) { + STUBBED; } -RADEXPFUNC inline void * RADEXPLINK IggyPerfmonCreate(void *(*alloc_func)(unsigned long), void (*free_func)(void *), void *user) { - STUBBED; - return 0; -} -RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void *perfmon) { - STUBBED; +RADEXPFUNC inline void* RADEXPLINK IggyPerfmonCreate( + void* (*alloc_func)(unsigned long), void (*free_func)(void*), void* user) { + STUBBED; + return 0; } +RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void* perfmon) { STUBBED; } // GDraw memory/warning functions are defined in gdraw_glfw.c (C linkage) -// Juicey you stupid idiot do NOT define them here +// Juicey you stupid idiot do NOT define them here -#endif // IGGYSTUBS_H \ No newline at end of file +#endif // IGGYSTUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h index 7fc8f0891..452562fad 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h @@ -9,7 +9,7 @@ #define TRUE true #define FALSE false -#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length)) +#define RtlZeroMemory(Destination, Length) memset((Destination), 0, (Length)) #define ZeroMemory RtlZeroMemory #define WINAPI @@ -18,10 +18,10 @@ #define S_OK 0 typedef unsigned int DWORD; -typedef const char *LPCSTR; +typedef const char* LPCSTR; typedef bool BOOL; -typedef BOOL *PBOOL; -typedef BOOL *LPBOOL; +typedef BOOL* PBOOL; +typedef BOOL* LPBOOL; typedef void* LPVOID; typedef wchar_t WCHAR; typedef unsigned char BYTE; @@ -60,7 +60,7 @@ typedef struct { typedef long long LONGLONG; typedef size_t SIZE_T; typedef WCHAR *LPWSTR, *PWSTR; -typedef unsigned char boolean; // java brainrot +typedef unsigned char boolean; // java brainrot #define __debugbreak() #define __int32 int #define CONST const @@ -71,13 +71,13 @@ typedef unsigned long ULONG; typedef short SHORT; typedef float FLOAT; -#define ERROR_SUCCESS 0L -#define ERROR_IO_PENDING 997L // dderror -#define ERROR_CANCELLED 1223L -//#define S_OK ((HRESULT)0x00000000L) -#define S_FALSE ((HRESULT)0x00000001L) +#define ERROR_SUCCESS 0L +#define ERROR_IO_PENDING 997L // dderror +#define ERROR_CANCELLED 1223L +// #define S_OK ((HRESULT)0x00000000L) +#define S_FALSE ((HRESULT)0x00000001L) -#define INFINITE 0xFFFFFFFF // Infinite timeout +#define INFINITE 0xFFFFFFFF // Infinite timeout #define PAGE_READWRITE 0x04 #define MEM_LARGE_PAGES 0x20000000 @@ -100,13 +100,13 @@ typedef float FLOAT; #define TRUNCATE_EXISTING 5 #define WAIT_TIMEOUT 258 -#define FILE_FLAG_WRITE_THROUGH 0x80000000 -#define FILE_FLAG_OVERLAPPED 0x40000000 -#define FILE_FLAG_NO_BUFFERING 0x20000000 -#define FILE_FLAG_RANDOM_ACCESS 0x10000000 -#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000 -#define FILE_FLAG_DELETE_ON_CLOSE 0x04000000 -#define FILE_FLAG_BACKUP_SEMANTICS 0x02000000 +#define FILE_FLAG_WRITE_THROUGH 0x80000000 +#define FILE_FLAG_OVERLAPPED 0x40000000 +#define FILE_FLAG_NO_BUFFERING 0x20000000 +#define FILE_FLAG_RANDOM_ACCESS 0x10000000 +#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000 +#define FILE_FLAG_DELETE_ON_CLOSE 0x04000000 +#define FILE_FLAG_BACKUP_SEMANTICS 0x02000000 #define FILE_ATTRIBUTE_READONLY 0x00000001 #define FILE_ATTRIBUTE_HIDDEN 0x00000002 @@ -115,64 +115,64 @@ typedef float FLOAT; #define FILE_ATTRIBUTE_ARCHIVE 0x00000020 #define FILE_ATTRIBUTE_NORMAL 0x00000080 #define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) -#define INVALID_FILE_SIZE ((DWORD)-1) -#define INVALID_SET_FILE_POINTER ((DWORD)-1) +#define INVALID_FILE_ATTRIBUTES ((DWORD) - 1) +#define INVALID_FILE_SIZE ((DWORD) - 1) +#define INVALID_SET_FILE_POINTER ((DWORD) - 1) #define FILE_BEGIN SEEK_SET #define FILE_CURRENT SEEK_CUR #define FILE_END SEEK_END -#define PAGE_NOACCESS 0x01 -#define PAGE_READONLY 0x02 -#define PAGE_READWRITE 0x04 -#define PAGE_WRITECOPY 0x08 -#define PAGE_EXECUTE 0x10 -#define PAGE_EXECUTE_READ 0x20 +#define PAGE_NOACCESS 0x01 +#define PAGE_READONLY 0x02 +#define PAGE_READWRITE 0x04 +#define PAGE_WRITECOPY 0x08 +#define PAGE_EXECUTE 0x10 +#define PAGE_EXECUTE_READ 0x20 #define PAGE_EXECUTE_READWRITE 0x40 -#define PAGE_EXECUTE_WRITECOPY 0x80 -#define PAGE_GUARD 0x100 -#define PAGE_NOCACHE 0x200 -#define PAGE_WRITECOMBINE 0x400 -#define PAGE_USER_READONLY 0x1000 -#define PAGE_USER_READWRITE 0x2000 -#define MEM_COMMIT 0x1000 -#define MEM_RESERVE 0x2000 -#define MEM_DECOMMIT 0x4000 -#define MEM_RELEASE 0x8000 -#define MEM_FREE 0x10000 -#define MEM_PRIVATE 0x20000 -#define MEM_RESET 0x80000 -#define MEM_TOP_DOWN 0x100000 -#define MEM_NOZERO 0x800000 -#define MEM_LARGE_PAGES 0x20000000 -#define MEM_HEAP 0x40000000 -#define MEM_16MB_PAGES 0x80000000 +#define PAGE_EXECUTE_WRITECOPY 0x80 +#define PAGE_GUARD 0x100 +#define PAGE_NOCACHE 0x200 +#define PAGE_WRITECOMBINE 0x400 +#define PAGE_USER_READONLY 0x1000 +#define PAGE_USER_READWRITE 0x2000 +#define MEM_COMMIT 0x1000 +#define MEM_RESERVE 0x2000 +#define MEM_DECOMMIT 0x4000 +#define MEM_RELEASE 0x8000 +#define MEM_FREE 0x10000 +#define MEM_PRIVATE 0x20000 +#define MEM_RESET 0x80000 +#define MEM_TOP_DOWN 0x100000 +#define MEM_NOZERO 0x800000 +#define MEM_LARGE_PAGES 0x20000000 +#define MEM_HEAP 0x40000000 +#define MEM_16MB_PAGES 0x80000000 -#define THREAD_BASE_PRIORITY_LOWRT 15 // value that gets a thread to LowRealtime-1 -#define THREAD_BASE_PRIORITY_MAX 2 // maximum thread base priority boost -#define THREAD_BASE_PRIORITY_MIN -2 // minimum thread base priority boost -#define THREAD_BASE_PRIORITY_IDLE -15 // value that gets a thread to idle +#define THREAD_BASE_PRIORITY_LOWRT \ + 15 // value that gets a thread to LowRealtime-1 +#define THREAD_BASE_PRIORITY_MAX 2 // maximum thread base priority boost +#define THREAD_BASE_PRIORITY_MIN -2 // minimum thread base priority boost +#define THREAD_BASE_PRIORITY_IDLE -15 // value that gets a thread to idle -#define THREAD_PRIORITY_LOWEST THREAD_BASE_PRIORITY_MIN -#define THREAD_PRIORITY_BELOW_NORMAL (THREAD_PRIORITY_LOWEST+1) -#define THREAD_PRIORITY_NORMAL 0 -#define THREAD_PRIORITY_HIGHEST THREAD_BASE_PRIORITY_MAX -#define THREAD_PRIORITY_ABOVE_NORMAL (THREAD_PRIORITY_HIGHEST-1) -#define THREAD_PRIORITY_ERROR_RETURN (MAXLONG) +#define THREAD_PRIORITY_LOWEST THREAD_BASE_PRIORITY_MIN +#define THREAD_PRIORITY_BELOW_NORMAL (THREAD_PRIORITY_LOWEST + 1) +#define THREAD_PRIORITY_NORMAL 0 +#define THREAD_PRIORITY_HIGHEST THREAD_BASE_PRIORITY_MAX +#define THREAD_PRIORITY_ABOVE_NORMAL (THREAD_PRIORITY_HIGHEST - 1) +#define THREAD_PRIORITY_ERROR_RETURN (MAXLONG) -#define THREAD_PRIORITY_TIME_CRITICAL THREAD_BASE_PRIORITY_LOWRT -#define THREAD_PRIORITY_IDLE THREAD_BASE_PRIORITY_IDLE +#define THREAD_PRIORITY_TIME_CRITICAL THREAD_BASE_PRIORITY_LOWRT +#define THREAD_PRIORITY_IDLE THREAD_BASE_PRIORITY_IDLE -#define IGNORE 0 // Ignore signal -#define INFINITE 0xFFFFFFFF // Infinite timeout -#define STATUS_WAIT_0 ((DWORD )0x00000000L) -#define WAIT_OBJECT_0 ((STATUS_WAIT_0 ) + 0 ) -#define STATUS_PENDING ((DWORD )0x00000103L) -#define STILL_ACTIVE STATUS_PENDING +#define IGNORE 0 // Ignore signal +#define INFINITE 0xFFFFFFFF // Infinite timeout +#define STATUS_WAIT_0 ((DWORD)0x00000000L) +#define WAIT_OBJECT_0 ((STATUS_WAIT_0) + 0) +#define STATUS_PENDING ((DWORD)0x00000103L) +#define STILL_ACTIVE STATUS_PENDING - -#define INVALID_HANDLE_VALUE ((HANDLE)(ULONG_PTR)-1) +#define INVALID_HANDLE_VALUE ((HANDLE)(ULONG_PTR) - 1) // https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime typedef struct _FILETIME { @@ -181,14 +181,14 @@ typedef struct _FILETIME { } FILETIME, *PFILETIME, *LPFILETIME; typedef struct _MEMORYSTATUS { - DWORD dwLength; - DWORD dwMemoryLoad; - SIZE_T dwTotalPhys; - SIZE_T dwAvailPhys; - SIZE_T dwTotalPageFile; - SIZE_T dwAvailPageFile; - SIZE_T dwTotalVirtual; - SIZE_T dwAvailVirtual; + DWORD dwLength; + DWORD dwMemoryLoad; + SIZE_T dwTotalPhys; + SIZE_T dwAvailPhys; + SIZE_T dwTotalPageFile; + SIZE_T dwAvailPageFile; + SIZE_T dwTotalVirtual; + SIZE_T dwAvailVirtual; } MEMORYSTATUS, *LPMEMORYSTATUS; typedef struct _WIN32_FIND_DATAA { @@ -227,7 +227,7 @@ typedef VOID* XMEMDECOMPRESSION_CONTEXT; // internal search state for FindFirstFile/FindNextFile typedef struct _LINUXSTUBS_FIND_HANDLE { - DIR *dir; + DIR* dir; char dirpath[MAX_PATH]; char pattern[MAX_PATH]; } _LINUXSTUBS_FIND_HANDLE; @@ -255,14 +255,16 @@ typedef HINSTANCE HMODULE; #define _HRESULT_TYPEDEF_(_sc) _sc -#define FAILED(Status) ((HRESULT)(Status)<0) -#define MAKE_HRESULT(sev,fac,code) \ - ((HRESULT) (((unsigned int)(sev)<<31) | ((unsigned int)(fac)<<16) | ((unsigned int)(code))) ) -#define MAKE_SCODE(sev,fac,code) \ - ((SCODE) (((unsigned int)(sev)<<31) | ((unsigned int)(fac)<<16) | ((unsigned int)(code))) ) -#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L) -#define E_ABORT _HRESULT_TYPEDEF_(0x80004004L) -#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L) +#define FAILED(Status) ((HRESULT)(Status) < 0) +#define MAKE_HRESULT(sev, fac, code) \ + ((HRESULT)(((unsigned int)(sev) << 31) | ((unsigned int)(fac) << 16) | \ + ((unsigned int)(code)))) +#define MAKE_SCODE(sev, fac, code) \ + ((SCODE)(((unsigned int)(sev) << 31) | ((unsigned int)(fac) << 16) | \ + ((unsigned int)(code)))) +#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L) +#define E_ABORT _HRESULT_TYPEDEF_(0x80004004L) +#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L) typedef pthread_mutex_t RTL_CRITICAL_SECTION; typedef pthread_mutex_t* PRTL_CRITICAL_SECTION; @@ -271,8 +273,8 @@ typedef RTL_CRITICAL_SECTION CRITICAL_SECTION; typedef PRTL_CRITICAL_SECTION PCRITICAL_SECTION; typedef PRTL_CRITICAL_SECTION LPCRITICAL_SECTION; -static inline void InitializeCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void InitializeCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); @@ -280,73 +282,61 @@ static inline void InitializeCriticalSection(PRTL_CRITICAL_SECTION CriticalSecti pthread_mutexattr_destroy(&attr); } -static inline void InitializeCriticalSectionAndSpinCount(PRTL_CRITICAL_SECTION CriticalSection, ULONG SpinCount) -{ +static inline void InitializeCriticalSectionAndSpinCount( + PRTL_CRITICAL_SECTION CriticalSection, ULONG SpinCount) { // no spin count required because we use a recursive mutex InitializeCriticalSection(CriticalSection); } -static inline void DeleteCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void DeleteCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_destroy(CriticalSection); } -static inline void EnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void EnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_lock(CriticalSection); } -static inline void LeaveCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void LeaveCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_unlock(CriticalSection); } -static inline ULONG TryEnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline ULONG TryEnterCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { return pthread_mutex_trylock(CriticalSection) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsalloc -static inline DWORD TlsAlloc(VOID) -{ +static inline DWORD TlsAlloc(VOID) { pthread_key_t key; - if (pthread_key_create(&key, NULL) == 0) - return key; + if (pthread_key_create(&key, NULL) == 0) return key; return TLS_OUT_OF_INDEXES; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsfree -static inline BOOL TlsFree(DWORD dwTlsIndex) -{ +static inline BOOL TlsFree(DWORD dwTlsIndex) { return pthread_key_delete(dwTlsIndex) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsgetvalue -static inline LPVOID TlsGetValue(DWORD dwTlsIndex) -{ +static inline LPVOID TlsGetValue(DWORD dwTlsIndex) { return pthread_getspecific(dwTlsIndex); } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlssetvalue -static inline BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) -{ +static inline BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) { return pthread_setspecific(dwTlsIndex, lpTlsValue) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalmemorystatus -static inline VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) -{ - // TODO: Parse /proc/meminfo and set lpBuffer based on that. Probably will also need another - // different codepath for macOS too. +static inline VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) { + // TODO: Parse /proc/meminfo and set lpBuffer based on that. Probably will + // also need another different codepath for macOS too. } -static inline DWORD GetLastError(VOID) -{ - return errno; -} +static inline DWORD GetLastError(VOID) { return errno; } -static inline VOID Sleep(DWORD dwMilliseconds) -{ +static inline VOID Sleep(DWORD dwMilliseconds) { struct timespec ts; ts.tv_nsec = (dwMilliseconds * 1000000) % 1000000000; ts.tv_sec = dwMilliseconds / 1000; @@ -358,18 +348,16 @@ static inline VOID Sleep(DWORD dwMilliseconds) } static inline LONG64 InterlockedCompareExchangeRelease64( - LONG64 volatile *Destination, - LONG64 Exchange, - LONG64 Comperand) -{ + LONG64 volatile* Destination, LONG64 Exchange, LONG64 Comperand) { LONG64 expected = Comperand; - __atomic_compare_exchange_n(Destination, &expected, Exchange, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED); + __atomic_compare_exchange_n(Destination, &expected, Exchange, false, + __ATOMIC_RELEASE, __ATOMIC_RELAXED); return expected; } -// internal helper: convert time_t to FILETIME (100ns intervals since 1601-01-01) -static inline FILETIME _TimeToFileTime(time_t t) -{ +// internal helper: convert time_t to FILETIME (100ns intervals since +// 1601-01-01) +static inline FILETIME _TimeToFileTime(time_t t) { const ULONGLONG EPOCH_DIFF = 11644473600ULL; ULONGLONG val = ((ULONGLONG)t + EPOCH_DIFF) * 10000000ULL; FILETIME ft; @@ -379,11 +367,13 @@ static inline FILETIME _TimeToFileTime(time_t t) } // internal helper: fill WIN32_FIND_DATAA from stat + name -static inline void _FillFindData(const char *name, const struct stat *st, WIN32_FIND_DATAA *out) -{ +static inline void _FillFindData(const char* name, const struct stat* st, + WIN32_FIND_DATAA* out) { memset(out, 0, sizeof(*out)); - out->dwFileAttributes = S_ISDIR(st->st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; - if (!(st->st_mode & S_IWUSR)) out->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; + out->dwFileAttributes = + S_ISDIR(st->st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; + if (!(st->st_mode & S_IWUSR)) + out->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; if (name[0] == '.') out->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; out->ftCreationTime = _TimeToFileTime(st->st_mtime); out->ftLastAccessTime = _TimeToFileTime(st->st_atime); @@ -393,116 +383,158 @@ static inline void _FillFindData(const char *name, const struct stat *st, WIN32_ strncpy(out->cFileName, name, MAX_PATH - 1); } -static inline HANDLE CreateFileA(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ +static inline HANDLE CreateFileA(const char* lpFileName, DWORD dwDesiredAccess, + DWORD dwShareMode, void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { int flags = 0; - if ((dwDesiredAccess & GENERIC_READ) && (dwDesiredAccess & GENERIC_WRITE)) flags = O_RDWR; - else if (dwDesiredAccess & GENERIC_WRITE) flags = O_WRONLY; - else flags = O_RDONLY; + if ((dwDesiredAccess & GENERIC_READ) && (dwDesiredAccess & GENERIC_WRITE)) + flags = O_RDWR; + else if (dwDesiredAccess & GENERIC_WRITE) + flags = O_WRONLY; + else + flags = O_RDONLY; - switch (dwCreationDisposition) - { - case CREATE_NEW: flags |= O_CREAT | O_EXCL; break; - case CREATE_ALWAYS: flags |= O_CREAT | O_TRUNC; break; - case OPEN_EXISTING: break; - case OPEN_ALWAYS: flags |= O_CREAT; break; - case TRUNCATE_EXISTING: flags |= O_TRUNC; break; + switch (dwCreationDisposition) { + case CREATE_NEW: + flags |= O_CREAT | O_EXCL; + break; + case CREATE_ALWAYS: + flags |= O_CREAT | O_TRUNC; + break; + case OPEN_EXISTING: + break; + case OPEN_ALWAYS: + flags |= O_CREAT; + break; + case TRUNCATE_EXISTING: + flags |= O_TRUNC; + break; } int fd = open(lpFileName, flags, 0644); return fd == -1 ? INVALID_HANDLE_VALUE : (HANDLE)(intptr_t)fd; } -static inline HANDLE CreateFileW(const wchar_t *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ +static inline HANDLE CreateFileW(const wchar_t* lpFileName, + DWORD dwDesiredAccess, DWORD dwShareMode, + void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { char narrowBuf[1024]; wcstombs(narrowBuf, lpFileName, sizeof(narrowBuf)); narrowBuf[sizeof(narrowBuf) - 1] = '\0'; - return CreateFileA(narrowBuf, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + return CreateFileA(narrowBuf, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline HANDLE CreateFile(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ - return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +static inline HANDLE CreateFile(const char* lpFileName, DWORD dwDesiredAccess, + DWORD dwShareMode, void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { + return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline HANDLE CreateFile(const wchar_t *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ - return CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +static inline HANDLE CreateFile(const wchar_t* lpFileName, + DWORD dwDesiredAccess, DWORD dwShareMode, + void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { + return CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline BOOL CloseHandle(HANDLE hObject) -{ +static inline BOOL CloseHandle(HANDLE hObject) { if (hObject == INVALID_HANDLE_VALUE) return FALSE; return close((int)(intptr_t)hObject) == 0; } -static inline DWORD GetFileSize(HANDLE hFile, DWORD *lpFileSizeHigh) -{ +static inline DWORD GetFileSize(HANDLE hFile, DWORD* lpFileSizeHigh) { struct stat st{}; - if (fstat((int)(intptr_t)hFile, &st) != 0) { if (lpFileSizeHigh) *lpFileSizeHigh = 0; return INVALID_FILE_SIZE; } - if (lpFileSizeHigh) *lpFileSizeHigh = (DWORD)((st.st_size >> 32) & 0xFFFFFFFF); + if (fstat((int)(intptr_t)hFile, &st) != 0) { + if (lpFileSizeHigh) *lpFileSizeHigh = 0; + return INVALID_FILE_SIZE; + } + if (lpFileSizeHigh) + *lpFileSizeHigh = (DWORD)((st.st_size >> 32) & 0xFFFFFFFF); return (DWORD)(st.st_size & 0xFFFFFFFF); } -static inline BOOL GetFileSizeEx(HANDLE hFile, LARGE_INTEGER *lpFileSize) -{ +static inline BOOL GetFileSizeEx(HANDLE hFile, LARGE_INTEGER* lpFileSize) { struct stat st{}; if (fstat((int)(intptr_t)hFile, &st) != 0) return FALSE; - if (lpFileSize) { lpFileSize->QuadPart = st.st_size; lpFileSize->LowPart = (DWORD)(st.st_size & 0xFFFFFFFF); lpFileSize->HighPart = (LONG)(st.st_size >> 32); } + if (lpFileSize) { + lpFileSize->QuadPart = st.st_size; + lpFileSize->LowPart = (DWORD)(st.st_size & 0xFFFFFFFF); + lpFileSize->HighPart = (LONG)(st.st_size >> 32); + } return TRUE; } -static inline BOOL ReadFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToRead, DWORD *lpNumberOfBytesRead, void *lpOverlapped) -{ +static inline BOOL ReadFile(HANDLE hFile, void* lpBuffer, + DWORD nNumberOfBytesToRead, + DWORD* lpNumberOfBytesRead, void* lpOverlapped) { ssize_t n = read((int)(intptr_t)hFile, lpBuffer, nNumberOfBytesToRead); if (lpNumberOfBytesRead) *lpNumberOfBytesRead = n >= 0 ? (DWORD)n : 0; return n >= 0; } -static inline BOOL WriteFile(HANDLE hFile, const void *lpBuffer, DWORD nNumberOfBytesToWrite, DWORD *lpNumberOfBytesWritten, void *lpOverlapped) -{ +static inline BOOL WriteFile(HANDLE hFile, const void* lpBuffer, + DWORD nNumberOfBytesToWrite, + DWORD* lpNumberOfBytesWritten, + void* lpOverlapped) { ssize_t n = write((int)(intptr_t)hFile, lpBuffer, nNumberOfBytesToWrite); if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = n >= 0 ? (DWORD)n : 0; return n >= 0; } -static inline DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, LONG *lpDistanceToMoveHigh, DWORD dwMoveMethod) -{ +static inline DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, + LONG* lpDistanceToMoveHigh, + DWORD dwMoveMethod) { off_t offset = lDistanceToMove; if (lpDistanceToMoveHigh) offset |= ((off_t)*lpDistanceToMoveHigh << 32); off_t result = lseek((int)(intptr_t)hFile, offset, dwMoveMethod); - if (result == (off_t)-1) { if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = -1; return INVALID_SET_FILE_POINTER; } + if (result == (off_t)-1) { + if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = -1; + return INVALID_SET_FILE_POINTER; + } if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = (LONG)(result >> 32); return (DWORD)(result & 0xFFFFFFFF); } -static inline DWORD GetFileAttributesA(const char *lpFileName) -{ +static inline DWORD GetFileAttributesA(const char* lpFileName) { struct stat st{}; if (stat(lpFileName, &st) != 0) return INVALID_FILE_ATTRIBUTES; - DWORD attrs = S_ISDIR(st.st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; + DWORD attrs = + S_ISDIR(st.st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; if (!(st.st_mode & S_IWUSR)) attrs |= FILE_ATTRIBUTE_READONLY; - const char *base = strrchr(lpFileName, '/'); base = base ? base + 1 : lpFileName; + const char* base = strrchr(lpFileName, '/'); + base = base ? base + 1 : lpFileName; if (base[0] == '.') attrs |= FILE_ATTRIBUTE_HIDDEN; return attrs; } -static inline DWORD GetFileAttributes(const char *lpFileName) -{ +static inline DWORD GetFileAttributes(const char* lpFileName) { return GetFileAttributesA(lpFileName); } -static inline BOOL GetFileAttributesExA(const char *lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, void *lpFileInformation) -{ - if (fInfoLevelId != GetFileExInfoStandard || !lpFileInformation) return FALSE; +static inline BOOL GetFileAttributesExA(const char* lpFileName, + GET_FILEEX_INFO_LEVELS fInfoLevelId, + void* lpFileInformation) { + if (fInfoLevelId != GetFileExInfoStandard || !lpFileInformation) + return FALSE; struct stat st{}; if (stat(lpFileName, &st) != 0) return FALSE; - WIN32_FILE_ATTRIBUTE_DATA *out = (WIN32_FILE_ATTRIBUTE_DATA *)lpFileInformation; + WIN32_FILE_ATTRIBUTE_DATA* out = + (WIN32_FILE_ATTRIBUTE_DATA*)lpFileInformation; out->dwFileAttributes = GetFileAttributesA(lpFileName); out->ftCreationTime = _TimeToFileTime(st.st_mtime); out->ftLastAccessTime = _TimeToFileTime(st.st_atime); @@ -512,215 +544,229 @@ static inline BOOL GetFileAttributesExA(const char *lpFileName, GET_FILEEX_INFO_ return TRUE; } -static inline BOOL GetFileAttributesEx(const char *lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, void *lpFileInformation) -{ +static inline BOOL GetFileAttributesEx(const char* lpFileName, + GET_FILEEX_INFO_LEVELS fInfoLevelId, + void* lpFileInformation) { return GetFileAttributesExA(lpFileName, fInfoLevelId, lpFileInformation); } -static inline BOOL CreateDirectoryA(const char *lpPathName, void *lpSecurityAttributes) -{ +static inline BOOL CreateDirectoryA(const char* lpPathName, + void* lpSecurityAttributes) { return mkdir(lpPathName, 0755) == 0; } -static inline BOOL CreateDirectory(const char *lpPathName, void *lpSecurityAttributes) -{ +static inline BOOL CreateDirectory(const char* lpPathName, + void* lpSecurityAttributes) { return CreateDirectoryA(lpPathName, lpSecurityAttributes); } -static inline BOOL DeleteFileA(const char *lpFileName) -{ +static inline BOOL DeleteFileA(const char* lpFileName) { return unlink(lpFileName) == 0; } -static inline BOOL DeleteFile(const char *lpFileName) -{ +static inline BOOL DeleteFile(const char* lpFileName) { return DeleteFileA(lpFileName); } -static inline BOOL MoveFileA(const char *lpExistingFileName, const char *lpNewFileName) -{ +static inline BOOL MoveFileA(const char* lpExistingFileName, + const char* lpNewFileName) { return rename(lpExistingFileName, lpNewFileName) == 0; } -static inline BOOL MoveFile(const char *lpExistingFileName, const char *lpNewFileName) -{ +static inline BOOL MoveFile(const char* lpExistingFileName, + const char* lpNewFileName) { return MoveFileA(lpExistingFileName, lpNewFileName); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfilea -static inline HANDLE FindFirstFileA(const char *lpFileName, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline HANDLE FindFirstFileA(const char* lpFileName, + WIN32_FIND_DATAA* lpFindFileData) { if (!lpFileName || !lpFindFileData) return INVALID_HANDLE_VALUE; char dirpath[MAX_PATH], pattern[MAX_PATH]; - const char *sep = strrchr(lpFileName, '/'); - if (sep) - { + const char* sep = strrchr(lpFileName, '/'); + if (sep) { size_t len = sep - lpFileName; if (len >= MAX_PATH) return INVALID_HANDLE_VALUE; - strncpy(dirpath, lpFileName, len); dirpath[len] = '\0'; + strncpy(dirpath, lpFileName, len); + dirpath[len] = '\0'; strncpy(pattern, sep + 1, MAX_PATH - 1); - } - else - { + } else { strncpy(dirpath, ".", MAX_PATH - 1); strncpy(pattern, lpFileName, MAX_PATH - 1); } - DIR *dir = opendir(dirpath); + DIR* dir = opendir(dirpath); if (!dir) return INVALID_HANDLE_VALUE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)malloc(sizeof(_LINUXSTUBS_FIND_HANDLE)); - if (!fh) { closedir(dir); return INVALID_HANDLE_VALUE; } + _LINUXSTUBS_FIND_HANDLE* fh = + (_LINUXSTUBS_FIND_HANDLE*)malloc(sizeof(_LINUXSTUBS_FIND_HANDLE)); + if (!fh) { + closedir(dir); + return INVALID_HANDLE_VALUE; + } fh->dir = dir; strncpy(fh->dirpath, dirpath, MAX_PATH - 1); strncpy(fh->pattern, pattern, MAX_PATH - 1); - struct dirent *ent; - while ((ent = readdir(fh->dir)) != NULL) - { - if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; - if (fnmatch(fh->pattern, ent->d_name, 0) == 0) - { + struct dirent* ent; + while ((ent = readdir(fh->dir)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + if (fnmatch(fh->pattern, ent->d_name, 0) == 0) { char fullpath[MAX_PATH * 2]; - snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, ent->d_name); + snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, + ent->d_name); struct stat st{}; - if (stat(fullpath, &st) == 0) _FillFindData(ent->d_name, &st, lpFindFileData); - else { memset(lpFindFileData, 0, sizeof(*lpFindFileData)); strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); } + if (stat(fullpath, &st) == 0) + _FillFindData(ent->d_name, &st, lpFindFileData); + else { + memset(lpFindFileData, 0, sizeof(*lpFindFileData)); + strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); + } return (HANDLE)fh; } } - closedir(fh->dir); free(fh); + closedir(fh->dir); + free(fh); return INVALID_HANDLE_VALUE; } -static inline HANDLE FindFirstFile(const char *lpFileName, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline HANDLE FindFirstFile(const char* lpFileName, + WIN32_FIND_DATAA* lpFindFileData) { return FindFirstFileA(lpFileName, lpFindFileData); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findnextfilea -static inline BOOL FindNextFileA(HANDLE hFindFile, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline BOOL FindNextFileA(HANDLE hFindFile, + WIN32_FIND_DATAA* lpFindFileData) { if (hFindFile == INVALID_HANDLE_VALUE || !lpFindFileData) return FALSE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)hFindFile; + _LINUXSTUBS_FIND_HANDLE* fh = (_LINUXSTUBS_FIND_HANDLE*)hFindFile; - struct dirent *ent; - while ((ent = readdir(fh->dir)) != NULL) - { - if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; - if (fnmatch(fh->pattern, ent->d_name, 0) == 0) - { + struct dirent* ent; + while ((ent = readdir(fh->dir)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + if (fnmatch(fh->pattern, ent->d_name, 0) == 0) { char fullpath[MAX_PATH * 2]; - snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, ent->d_name); + snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, + ent->d_name); struct stat st{}; - if (stat(fullpath, &st) == 0) _FillFindData(ent->d_name, &st, lpFindFileData); - else { memset(lpFindFileData, 0, sizeof(*lpFindFileData)); strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); } + if (stat(fullpath, &st) == 0) + _FillFindData(ent->d_name, &st, lpFindFileData); + else { + memset(lpFindFileData, 0, sizeof(*lpFindFileData)); + strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); + } return TRUE; } } return FALSE; } -static inline BOOL FindNextFile(HANDLE hFindFile, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline BOOL FindNextFile(HANDLE hFindFile, + WIN32_FIND_DATAA* lpFindFileData) { return FindNextFileA(hFindFile, lpFindFileData); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findclose -static inline BOOL FindClose(HANDLE hFindFile) -{ +static inline BOOL FindClose(HANDLE hFindFile) { if (hFindFile == INVALID_HANDLE_VALUE) return FALSE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)hFindFile; - closedir(fh->dir); free(fh); + _LINUXSTUBS_FIND_HANDLE* fh = (_LINUXSTUBS_FIND_HANDLE*)hFindFile; + closedir(fh->dir); + free(fh); return TRUE; } -// internal helper: convert FILETIME (100ns since 1601) to time_t (seconds since 1970) -static inline time_t _FileTimeToTimeT(const FILETIME& ft) -{ +// internal helper: convert FILETIME (100ns since 1601) to time_t (seconds since +// 1970) +static inline time_t _FileTimeToTimeT(const FILETIME& ft) { ULONGLONG val = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime; - const ULONGLONG EPOCH_DIFF = 116444736000000000ULL; // 100ns intervals between 1601-01-01 and 1970-01-01 + const ULONGLONG EPOCH_DIFF = + 116444736000000000ULL; // 100ns intervals between 1601-01-01 and + // 1970-01-01 return (time_t)((val - EPOCH_DIFF) / 10000000ULL); } // internal helper: read the current wall clock into a timespec -static inline void _CurrentTimeSpec(struct timespec *ts) -{ +static inline void _CurrentTimeSpec(struct timespec* ts) { #ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, ts); #else struct timeval tv; gettimeofday(&tv, NULL); - ts->tv_sec = tv.tv_sec; + ts->tv_sec = tv.tv_sec; ts->tv_nsec = tv.tv_usec * 1000; #endif } // internal helper: fill SYSTEMTIME from a broken-down tm + nanosecond remainder -static inline void _FillSystemTime(const struct tm *tm, long tv_nsec, LPSYSTEMTIME lpSystemTime) -{ - lpSystemTime->wYear = tm->tm_year + 1900; - lpSystemTime->wMonth = tm->tm_mon + 1; - lpSystemTime->wDayOfWeek = tm->tm_wday; // 0 = Sunday - lpSystemTime->wDay = tm->tm_mday; - lpSystemTime->wHour = tm->tm_hour; - lpSystemTime->wMinute = tm->tm_min; - lpSystemTime->wSecond = tm->tm_sec; - lpSystemTime->wMilliseconds = (WORD)(tv_nsec / 1000000); // ns to ms +static inline void _FillSystemTime(const struct tm* tm, long tv_nsec, + LPSYSTEMTIME lpSystemTime) { + lpSystemTime->wYear = tm->tm_year + 1900; + lpSystemTime->wMonth = tm->tm_mon + 1; + lpSystemTime->wDayOfWeek = tm->tm_wday; // 0 = Sunday + lpSystemTime->wDay = tm->tm_mday; + lpSystemTime->wHour = tm->tm_hour; + lpSystemTime->wMinute = tm->tm_min; + lpSystemTime->wSecond = tm->tm_sec; + lpSystemTime->wMilliseconds = (WORD)(tv_nsec / 1000000); // ns to ms } // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime -static inline VOID GetSystemTime(LPSYSTEMTIME lpSystemTime) -{ - struct timespec ts; _CurrentTimeSpec(&ts); - struct tm tm; gmtime_r(&ts.tv_sec, &tm); // UTC +static inline VOID GetSystemTime(LPSYSTEMTIME lpSystemTime) { + struct timespec ts; + _CurrentTimeSpec(&ts); + struct tm tm; + gmtime_r(&ts.tv_sec, &tm); // UTC _FillSystemTime(&tm, ts.tv_nsec, lpSystemTime); } // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlocaltime -static inline VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) -{ - struct timespec ts; _CurrentTimeSpec(&ts); - struct tm tm; localtime_r(&ts.tv_sec, &tm); // local time +static inline VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) { + struct timespec ts; + _CurrentTimeSpec(&ts); + struct tm tm; + localtime_r(&ts.tv_sec, &tm); // local time _FillSystemTime(&tm, ts.tv_nsec, lpSystemTime); } // https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-systemtimetofiletime -static inline BOOL SystemTimeToFileTime(const SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime) -{ +static inline BOOL SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, + LPFILETIME lpFileTime) { struct tm tm = {}; tm.tm_year = lpSystemTime->wYear - 1900; - tm.tm_mon = lpSystemTime->wMonth - 1; + tm.tm_mon = lpSystemTime->wMonth - 1; tm.tm_mday = lpSystemTime->wDay; tm.tm_hour = lpSystemTime->wHour; - tm.tm_min = lpSystemTime->wMinute; - tm.tm_sec = lpSystemTime->wSecond; + tm.tm_min = lpSystemTime->wMinute; + tm.tm_sec = lpSystemTime->wSecond; time_t t = timegm(&tm); if (t == (time_t)-1) return FALSE; ULONGLONG ft = ((ULONGLONG)t + 11644473600ULL) * 10000000ULL; ft += lpSystemTime->wMilliseconds * 10000ULL; - lpFileTime->dwLowDateTime = (DWORD)(ft & 0xFFFFFFFF); + lpFileTime->dwLowDateTime = (DWORD)(ft & 0xFFFFFFFF); lpFileTime->dwHighDateTime = (DWORD)(ft >> 32); return TRUE; } // https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-filetimetosystemtime -static inline BOOL FileTimeToSystemTime(const FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime) -{ - ULONGLONG ft = ((ULONGLONG)lpFileTime->dwHighDateTime << 32) | lpFileTime->dwLowDateTime; +static inline BOOL FileTimeToSystemTime(const FILETIME* lpFileTime, + LPSYSTEMTIME lpSystemTime) { + ULONGLONG ft = ((ULONGLONG)lpFileTime->dwHighDateTime << 32) | + lpFileTime->dwLowDateTime; time_t t = _FileTimeToTimeT(*lpFileTime); long remainder_ns = (long)((ft % 10000000ULL) * 100); - struct tm tm; gmtime_r(&t, &tm); // UTC + struct tm tm; + gmtime_r(&t, &tm); // UTC _FillSystemTime(&tm, remainder_ns, lpSystemTime); return TRUE; } -static inline DWORD GetTickCount() -{ +static inline DWORD GetTickCount() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -728,41 +774,36 @@ static inline DWORD GetTickCount() return (long long)ts.tv_sec * 1000 + (long long)ts.tv_nsec / 1000000; } -static inline BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency) -{ - // nanoseconds - lpFrequency->QuadPart = 1000000000; - return false; +static inline BOOL QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency) { + // nanoseconds + lpFrequency->QuadPart = 1000000000; + return false; } - -static inline BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount) -{ +static inline BOOL QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); // nanoseconds - lpPerformanceCount->QuadPart = ((long long)ts.tv_sec * 1000000000) + (long long)ts.tv_nsec; + lpPerformanceCount->QuadPart = + ((long long)ts.tv_sec * 1000000000) + (long long)ts.tv_nsec; return true; } // https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa -static inline VOID OutputDebugStringA(LPCSTR lpOutputString) -{ +static inline VOID OutputDebugStringA(LPCSTR lpOutputString) { if (!lpOutputString) return; fputs(lpOutputString, stderr); } // https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringw -static inline VOID OutputDebugStringW(LPCWSTR lpOutputString) -{ +static inline VOID OutputDebugStringW(LPCWSTR lpOutputString) { if (!lpOutputString) return; fprintf(stderr, "%ls", lpOutputString); } -static inline VOID OutputDebugString(LPCSTR lpOutputString) -{ +static inline VOID OutputDebugString(LPCSTR lpOutputString) { return OutputDebugStringA(lpOutputString); } @@ -782,7 +823,8 @@ static inline HANDLE CreateEvent(int manual_reset, int initial_state) { return (HANDLE)ev; } -static inline HANDLE CreateEvent(void*, BOOL manual_reset, BOOL initial_state, void*) { +static inline HANDLE CreateEvent(void*, BOOL manual_reset, BOOL initial_state, + void*) { return CreateEvent(manual_reset, initial_state); } @@ -791,8 +833,10 @@ static inline BOOL SetEvent(HANDLE hEvent) { if (!ev) return FALSE; pthread_mutex_lock(&ev->mutex); ev->signaled = 1; - if (ev->manual_reset) pthread_cond_broadcast(&ev->cond); - else pthread_cond_signal(&ev->cond); + if (ev->manual_reset) + pthread_cond_broadcast(&ev->cond); + else + pthread_cond_signal(&ev->cond); pthread_mutex_unlock(&ev->mutex); return TRUE; } @@ -819,7 +863,10 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += dwMilliseconds / 1000; ts.tv_nsec += (dwMilliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; } + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000; + } while (!ev->signaled) { if (pthread_cond_timedwait(&ev->cond, &ev->mutex, &ts) != 0) { pthread_mutex_unlock(&ev->mutex); @@ -827,7 +874,10 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { } } } else { - if (!ev->signaled) { pthread_mutex_unlock(&ev->mutex); return WAIT_TIMEOUT; } + if (!ev->signaled) { + pthread_mutex_unlock(&ev->mutex); + return WAIT_TIMEOUT; + } } if (!ev->manual_reset) ev->signaled = 0; pthread_mutex_unlock(&ev->mutex); @@ -835,25 +885,32 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { } struct LinuxThread; -static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds); +static inline DWORD _WaitForThread(struct LinuxThread* lt, + DWORD dwMilliseconds); static inline DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { if (!hHandle) return WAIT_FAILED; - // Check if this is a thread handle (LinuxThread has magic number as first field) + // Check if this is a thread handle (LinuxThread has magic number as first + // field) if (*(int*)hHandle == HANDLE_TYPE_THREAD) { return _WaitForThread((struct LinuxThread*)hHandle, dwMilliseconds); } return _WaitForEvent((Event*)hHandle, dwMilliseconds); } -static inline DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) { +static inline DWORD WaitForMultipleObjects(DWORD nCount, + const HANDLE* lpHandles, + BOOL bWaitAll, + DWORD dwMilliseconds) { if (bWaitAll) { - for (DWORD i = 0; i < nCount; i++) WaitForSingleObject(lpHandles[i], dwMilliseconds); + for (DWORD i = 0; i < nCount; i++) + WaitForSingleObject(lpHandles[i], dwMilliseconds); return WAIT_OBJECT_0; } for (int pass = 0; pass < 1000; pass++) { for (DWORD i = 0; i < nCount; i++) { - if (WaitForSingleObject(lpHandles[i], 0) == WAIT_OBJECT_0) return WAIT_OBJECT_0 + i; + if (WaitForSingleObject(lpHandles[i], 0) == WAIT_OBJECT_0) + return WAIT_OBJECT_0 + i; } usleep(1000); } @@ -890,7 +947,8 @@ struct LinuxThread { static inline void* _linux_thread_entry(void* arg) { LinuxThread* lt = (LinuxThread*)arg; pthread_mutex_lock(<->suspendMutex); - while (lt->suspended) pthread_cond_wait(<->suspendCond, <->suspendMutex); + while (lt->suspended) + pthread_cond_wait(<->suspendCond, <->suspendMutex); pthread_mutex_unlock(<->suspendMutex); lt->exitCode = lt->func(lt->param); // Signal completion @@ -901,7 +959,8 @@ static inline void* _linux_thread_entry(void* arg) { return NULL; } -static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) { +static inline DWORD _WaitForThread(struct LinuxThread* lt, + DWORD dwMilliseconds) { pthread_mutex_lock(<->completionMutex); if (lt->completed) { pthread_mutex_unlock(<->completionMutex); @@ -912,15 +971,20 @@ static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) return WAIT_TIMEOUT; } if (dwMilliseconds == INFINITE) { - while (!lt->completed) pthread_cond_wait(<->completionCond, <->completionMutex); + while (!lt->completed) + pthread_cond_wait(<->completionCond, <->completionMutex); } else { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += dwMilliseconds / 1000; ts.tv_nsec += (dwMilliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; } + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000; + } while (!lt->completed) { - if (pthread_cond_timedwait(<->completionCond, <->completionMutex, &ts) != 0) { + if (pthread_cond_timedwait(<->completionCond, + <->completionMutex, &ts) != 0) { pthread_mutex_unlock(<->completionMutex); return WAIT_TIMEOUT; } @@ -932,7 +996,10 @@ static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) static DWORD g_nextThreadId = 1000; -static inline HANDLE CreateThread(void*, SIZE_T stackSize, LPTHREAD_START_ROUTINE lpStartAddress, void* lpParameter, DWORD dwCreationFlags, DWORD* lpThreadId) { +static inline HANDLE CreateThread(void*, SIZE_T stackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + void* lpParameter, DWORD dwCreationFlags, + DWORD* lpThreadId) { LinuxThread* lt = (LinuxThread*)calloc(1, sizeof(LinuxThread)); lt->handleType = HANDLE_TYPE_THREAD; lt->func = lpStartAddress; @@ -965,7 +1032,8 @@ static inline DWORD ResumeThread(HANDLE hThread) { } static inline BOOL SetThreadPriority(HANDLE hThread, int nPriority) { - (void)hThread; (void)nPriority; + (void)hThread; + (void)nPriority; return TRUE; } @@ -984,7 +1052,7 @@ static inline HANDLE GetCurrentThread() { return (HANDLE)(unsigned long)pthread_self(); } -template +template static inline int sprintf_s(char (&buf)[N], const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -995,13 +1063,13 @@ static inline int sprintf_s(char (&buf)[N], const char* fmt, ...) { static inline int sprintf_s(char* buf, size_t sz, const char* fmt, ...) { va_list args; - va_start(args, fmt); // fucking horrid + va_start(args, fmt); // fucking horrid int ret = vsnprintf(buf, sz, fmt, args); va_end(args); return ret; } -template +template static inline int swprintf_s(wchar_t (&buf)[N], const wchar_t* fmt, ...) { va_list args; va_start(args, fmt); @@ -1020,29 +1088,36 @@ static inline int swprintf_s(wchar_t* buf, size_t sz, const wchar_t* fmt, ...) { static inline HMODULE GetModuleHandle(LPCSTR lpModuleName) { return 0; } -static inline LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { +static inline LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, + DWORD flAllocationType, DWORD flProtect) { // MEM_COMMIT | MEM_RESERVE → mmap anonymous int prot = 0; - if (flProtect == 0x04 /*PAGE_READWRITE*/) prot = PROT_READ | PROT_WRITE; - else if (flProtect == 0x40 /*PAGE_EXECUTE_READWRITE*/) prot = PROT_READ | PROT_WRITE | PROT_EXEC; - else if (flProtect == 0x02 /*PAGE_READONLY*/) prot = PROT_READ; - else prot = PROT_READ | PROT_WRITE; // default + if (flProtect == 0x04 /*PAGE_READWRITE*/) + prot = PROT_READ | PROT_WRITE; + else if (flProtect == 0x40 /*PAGE_EXECUTE_READWRITE*/) + prot = PROT_READ | PROT_WRITE | PROT_EXEC; + else if (flProtect == 0x02 /*PAGE_READONLY*/) + prot = PROT_READ; + else + prot = PROT_READ | PROT_WRITE; // default int flags = MAP_PRIVATE | MAP_ANONYMOUS; if (lpAddress != NULL) flags |= MAP_FIXED; - void *p = mmap(lpAddress, dwSize, prot, flags, -1, 0); + void* p = mmap(lpAddress, dwSize, prot, flags, -1, 0); if (p == MAP_FAILED) return NULL; return p; } -static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { +static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, + DWORD dwFreeType) { if (lpAddress == NULL) return FALSE; // MEM_RELEASE (0x8000) frees the whole region if (dwFreeType == 0x8000 /*MEM_RELEASE*/) { - // dwSize should be 0 for MEM_RELEASE per Win32 API, but we don't track allocation sizes - // Use dwSize if provided, otherwise this is a best-effort - if (dwSize == 0) dwSize = 4096; // minimum page + // dwSize should be 0 for MEM_RELEASE per Win32 API, but we don't track + // allocation sizes Use dwSize if provided, otherwise this is a + // best-effort + if (dwSize == 0) dwSize = 4096; // minimum page munmap(lpAddress, dwSize); } else { // MEM_DECOMMIT (0x4000) - just decommit (make inaccessible) @@ -1058,4 +1133,4 @@ static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType #define _strnicmp strncasecmp #define _wcsnicmp wcsncasecmp -#endif // WINAPISTUBS_H +#endif // WINAPISTUBS_H diff --git a/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h index a5bfca2b9..6b4901e9d 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h @@ -4,7 +4,7 @@ // //============================================================================= -#if !defined( XBOXSTUBS_H ) && !defined( _X360 ) +#if !defined(XBOXSTUBS_H) && !defined(_X360) #define XBOXSTUBS_H #ifdef _WIN32 @@ -12,7 +12,7 @@ #endif // DecalOverdose: not available in 4J -//#include "tier0/platform.h" +// #include "tier0/platform.h" #define POSIX @@ -23,66 +23,65 @@ typedef long long int int64; #define FORCEINLINE inline // Content creation/open flags -#define XCONTENTFLAG_NONE 0x00 -#define XCONTENTFLAG_CREATENEW 0x00 -#define XCONTENTFLAG_CREATEALWAYS 0x00 -#define XCONTENTFLAG_OPENEXISTING 0x00 -#define XCONTENTFLAG_OPENALWAYS 0x00 -#define XCONTENTFLAG_TRUNCATEEXISTING 0x00 +#define XCONTENTFLAG_NONE 0x00 +#define XCONTENTFLAG_CREATENEW 0x00 +#define XCONTENTFLAG_CREATEALWAYS 0x00 +#define XCONTENTFLAG_OPENEXISTING 0x00 +#define XCONTENTFLAG_OPENALWAYS 0x00 +#define XCONTENTFLAG_TRUNCATEEXISTING 0x00 // Content attributes -#define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00 -#define XCONTENTFLAG_NODEVICE_TRANSFER 0x00 -#define XCONTENTFLAG_STRONG_SIGNED 0x00 -#define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00 -#define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00 +#define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00 +#define XCONTENTFLAG_NODEVICE_TRANSFER 0x00 +#define XCONTENTFLAG_STRONG_SIGNED 0x00 +#define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00 +#define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00 // Console device ports -#define XDEVICE_PORT0 0 -#define XDEVICE_PORT1 1 -#define XDEVICE_PORT2 2 -#define XDEVICE_PORT3 3 +#define XDEVICE_PORT0 0 +#define XDEVICE_PORT1 1 +#define XDEVICE_PORT2 2 +#define XDEVICE_PORT3 3 // #define XUSER_MAX_COUNT 4 -#define XUSER_INDEX_NONE 0x000000FE +#define XUSER_INDEX_NONE 0x000000FE -#define XBX_CLR_DEFAULT 0xFF000000 -#define XBX_CLR_WARNING 0x0000FFFF -#define XBX_CLR_ERROR 0x000000FF +#define XBX_CLR_DEFAULT 0xFF000000 +#define XBX_CLR_WARNING 0x0000FFFF +#define XBX_CLR_ERROR 0x000000FF -#define XBOX_MINBORDERSAFE 0 -#define XBOX_MAXBORDERSAFE 0 +#define XBOX_MINBORDERSAFE 0 +#define XBOX_MAXBORDERSAFE 0 -typedef enum -{ - XK_NULL, - XK_BUTTON_UP, - XK_BUTTON_DOWN, - XK_BUTTON_LEFT, - XK_BUTTON_RIGHT, - XK_BUTTON_START, - XK_BUTTON_BACK, - XK_BUTTON_STICK1, - XK_BUTTON_STICK2, - XK_BUTTON_A, - XK_BUTTON_B, - XK_BUTTON_X, - XK_BUTTON_Y, - XK_BUTTON_LEFT_SHOULDER, - XK_BUTTON_RIGHT_SHOULDER, - XK_BUTTON_LTRIGGER, - XK_BUTTON_RTRIGGER, - XK_STICK1_UP, - XK_STICK1_DOWN, - XK_STICK1_LEFT, - XK_STICK1_RIGHT, - XK_STICK2_UP, - XK_STICK2_DOWN, - XK_STICK2_LEFT, - XK_STICK2_RIGHT, - XK_MAX_KEYS, +typedef enum { + XK_NULL, + XK_BUTTON_UP, + XK_BUTTON_DOWN, + XK_BUTTON_LEFT, + XK_BUTTON_RIGHT, + XK_BUTTON_START, + XK_BUTTON_BACK, + XK_BUTTON_STICK1, + XK_BUTTON_STICK2, + XK_BUTTON_A, + XK_BUTTON_B, + XK_BUTTON_X, + XK_BUTTON_Y, + XK_BUTTON_LEFT_SHOULDER, + XK_BUTTON_RIGHT_SHOULDER, + XK_BUTTON_LTRIGGER, + XK_BUTTON_RTRIGGER, + XK_STICK1_UP, + XK_STICK1_DOWN, + XK_STICK1_LEFT, + XK_STICK1_RIGHT, + XK_STICK2_UP, + XK_STICK2_DOWN, + XK_STICK2_LEFT, + XK_STICK2_RIGHT, + XK_MAX_KEYS, } xKey_t; -//typedef enum +// typedef enum //{ // XVRB_NONE, // off // XVRB_ERROR, // fatal error @@ -90,74 +89,70 @@ typedef enum // XVRB_WARNING, // non-fatal warnings // XVRB_STATUS, // status reports // XVRB_ALL, -//} xverbose_e; +// } xverbose_e; #ifdef POSIX typedef DWORD COLORREF; #endif #ifndef INVALID_HANDLE_VALUE -#define INVALID_HANDLE_VALUE ((HANDLE)-1) +#define INVALID_HANDLE_VALUE ((HANDLE) - 1) #endif // typedef struct { -// IN_ADDR ina; // IP address (zero if not static/DHCP) -// IN_ADDR inaOnline; // Online IP address (zero if not online) -// WORD wPortOnline; // Online port -// BYTE abEnet[6]; // Ethernet MAC address -// BYTE abOnline[20]; // Online identification -// } XNADDR; +// IN_ADDR ina; // IP address (zero if not +// static/DHCP) IN_ADDR inaOnline; // Online IP address +// (zero if not online) WORD wPortOnline; // Online +// port BYTE abEnet[6]; // Ethernet MAC address BYTE +// abOnline[20]; // Online identification } XNADDR; typedef int XNADDR; typedef uint64 XUID; typedef struct { - BYTE ab[8]; // xbox to xbox key identifier + BYTE ab[8]; // xbox to xbox key identifier } XNKID; typedef struct { - BYTE ab[16]; // xbox to xbox key exchange key + BYTE ab[16]; // xbox to xbox key exchange key } XNKEY; -typedef struct _XSESSION_INFO -{ - XNKID sessionID; // 8 bytes - XNADDR hostAddress; // 36 bytes - XNKEY keyExchangeKey; // 16 bytes +typedef struct _XSESSION_INFO { + XNKID sessionID; // 8 bytes + XNADDR hostAddress; // 36 bytes + XNKEY keyExchangeKey; // 16 bytes } XSESSION_INFO, *PXSESSION_INFO; -typedef struct _XSESSION_REGISTRANT -{ - uint64 qwMachineID; - DWORD bTrustworthiness; - DWORD bNumUsers; - XUID *rgUsers; +typedef struct _XSESSION_REGISTRANT { + uint64 qwMachineID; + DWORD bTrustworthiness; + DWORD bNumUsers; + XUID* rgUsers; } XSESSION_REGISTRANT; -typedef struct _XSESSION_REGISTRATION_RESULTS -{ - DWORD wNumRegistrants; - XSESSION_REGISTRANT *rgRegistrants; +typedef struct _XSESSION_REGISTRATION_RESULTS { + DWORD wNumRegistrants; + XSESSION_REGISTRANT* rgRegistrants; } XSESSION_REGISTRATION_RESULTS, *PXSESSION_REGISTRATION_RESULTS; -#define XSESSION_CREATE_HOST 0 -#define XUSER_DATA_TYPE_INT32 0 -#define XSESSION_CREATE_USES_ARBITRATION 0 -#define XNET_QOS_LISTEN_ENABLE 0 -#define XNET_QOS_LISTEN_DISABLE 0 -#define XNET_QOS_LISTEN_SET_DATA 0 +#define XSESSION_CREATE_HOST 0 +#define XUSER_DATA_TYPE_INT32 0 +#define XSESSION_CREATE_USES_ARBITRATION 0 +#define XNET_QOS_LISTEN_ENABLE 0 +#define XNET_QOS_LISTEN_DISABLE 0 +#define XNET_QOS_LISTEN_SET_DATA 0 -FORCEINLINE void XBX_ProcessEvents() {} -FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; } -FORCEINLINE int XBX_GetPrimaryUserId() { return 0; } -FORCEINLINE void XBX_SetPrimaryUserId( DWORD idx ) {} -FORCEINLINE int XBX_GetStorageDeviceId() { return 0; } -FORCEINLINE void XBX_SetStorageDeviceId( DWORD idx ) {} -FORCEINLINE const char *XBX_GetLanguageString() { return ""; } -FORCEINLINE bool XBX_IsLocalized() { return false; } +FORCEINLINE void XBX_ProcessEvents() {} +FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; } +FORCEINLINE int XBX_GetPrimaryUserId() { return 0; } +FORCEINLINE void XBX_SetPrimaryUserId(DWORD idx) {} +FORCEINLINE int XBX_GetStorageDeviceId() { return 0; } +FORCEINLINE void XBX_SetStorageDeviceId(DWORD idx) {} +FORCEINLINE const char* XBX_GetLanguageString() { return ""; } +FORCEINLINE bool XBX_IsLocalized() { return false; } -#define XBX_INVALID_STORAGE_ID ((DWORD) -1) -#define XBX_STORAGE_DECLINED ((DWORD) -2) +#define XBX_INVALID_STORAGE_ID ((DWORD) - 1) +#define XBX_STORAGE_DECLINED ((DWORD) - 2) -#endif // XBOXSTUBS_H +#endif // XBOXSTUBS_H diff --git a/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp b/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp index c2d65ab1b..e8f5bd3a0 100644 --- a/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp +++ b/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp @@ -18,13 +18,18 @@ void PIXSetMarkerDeprecated(int a, const char* b, ...) {} #include "../Xbox/Network/NetworkPlayerXbox.h" -NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p) : m_qnetPlayer(p), m_pSocket(nullptr) {} +NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p) + : m_qnetPlayer(p), m_pSocket(nullptr) {} IQNetPlayer* NetworkPlayerXbox::GetQNetPlayer() { return m_qnetPlayer; } unsigned char NetworkPlayerXbox::GetSmallId() { return 0; } void NetworkPlayerXbox::SendData(INetworkPlayer*, const void*, int, bool) {} bool NetworkPlayerXbox::IsSameSystem(INetworkPlayer*) { return false; } -int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) { return 0; } -int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) { return 0; } +int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) { + return 0; +} +int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) { + return 0; +} int NetworkPlayerXbox::GetCurrentRtt() { return 0; } bool NetworkPlayerXbox::IsHost() { return false; } bool NetworkPlayerXbox::IsGuest() { return false; } diff --git a/Minecraft.Client/Player/EntityTracker.cpp b/Minecraft.Client/Player/EntityTracker.cpp index 2b318b5ea..802f7480d 100644 --- a/Minecraft.Client/Player/EntityTracker.cpp +++ b/Minecraft.Client/Player/EntityTracker.cpp @@ -20,210 +20,212 @@ #include "../../Minecraft.World/Util/BasicTypeContainers.h" #include "../Network/PlayerConnection.h" -EntityTracker::EntityTracker(ServerLevel *level) -{ +EntityTracker::EntityTracker(ServerLevel* level) { this->level = level; maxRange = level->getServer()->getPlayers()->getMaxRange(); } -void EntityTracker::addEntity(std::shared_ptr e) -{ - if (e->GetType() == eTYPE_SERVERPLAYER) - { +void EntityTracker::addEntity(std::shared_ptr e) { + if (e->GetType() == eTYPE_SERVERPLAYER) { addEntity(e, 32 * 16, 2); - std::shared_ptr player = std::dynamic_pointer_cast(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - if( (*it)->e != player ) - { - (*it)->updatePlayer(this, player); - } - } - } - else if (e->GetType() == eTYPE_FISHINGHOOK) addEntity(e, 16 * 4, 5, true); - else if (e->GetType() == eTYPE_SMALL_FIREBALL) addEntity(e, 16 * 4, 10, false); - else if (e->GetType() == eTYPE_DRAGON_FIREBALL) addEntity(e, 16 * 4, 10, false); // 4J Added TU9 - else if (e->GetType() == eTYPE_ARROW) addEntity(e, 16 * 4, 20, false); - else if (e->GetType() == eTYPE_FIREBALL) addEntity(e, 16 * 4, 10, false); - else if (e->GetType() == eTYPE_SNOWBALL) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNENDERPEARL) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL ) addEntity(e, 16 * 4, 4, true); - else if (e->GetType() == eTYPE_THROWNEGG) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNPOTION ) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNEXPBOTTLE) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_ITEMENTITY) addEntity(e, 16 * 4, 20, true); - else if (e->GetType() == eTYPE_MINECART) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_BOAT) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_SQUID) addEntity(e, 16 * 4, 3, true); - else if (std::dynamic_pointer_cast(e)!=NULL) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_ENDERDRAGON ) addEntity(e, 16 * 10, 3, true); - else if (e->GetType() == eTYPE_PRIMEDTNT) addEntity(e, 16 * 10, 10, true); - else if (e->GetType() == eTYPE_FALLINGTILE) addEntity(e, 16 * 10, 20, true); - else if (e->GetType() == eTYPE_PAINTING) addEntity(e, 16 * 10, INT_MAX, false); - else if (e->GetType() == eTYPE_EXPERIENCEORB) addEntity(e, 16 * 10, 20, true); - else if (e->GetType() == eTYPE_ENDER_CRYSTAL) addEntity(e, 16 * 16, INT_MAX, false); - else if (e->GetType() == eTYPE_ITEM_FRAME) addEntity(e, 16 * 10, INT_MAX, false); + std::shared_ptr player = + std::dynamic_pointer_cast(e); + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + if ((*it)->e != player) { + (*it)->updatePlayer(this, player); + } + } + } else if (e->GetType() == eTYPE_FISHINGHOOK) + addEntity(e, 16 * 4, 5, true); + else if (e->GetType() == eTYPE_SMALL_FIREBALL) + addEntity(e, 16 * 4, 10, false); + else if (e->GetType() == eTYPE_DRAGON_FIREBALL) + addEntity(e, 16 * 4, 10, false); // 4J Added TU9 + else if (e->GetType() == eTYPE_ARROW) + addEntity(e, 16 * 4, 20, false); + else if (e->GetType() == eTYPE_FIREBALL) + addEntity(e, 16 * 4, 10, false); + else if (e->GetType() == eTYPE_SNOWBALL) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNENDERPEARL) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) + addEntity(e, 16 * 4, 4, true); + else if (e->GetType() == eTYPE_THROWNEGG) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNPOTION) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNEXPBOTTLE) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_ITEMENTITY) + addEntity(e, 16 * 4, 20, true); + else if (e->GetType() == eTYPE_MINECART) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_BOAT) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_SQUID) + addEntity(e, 16 * 4, 3, true); + else if (std::dynamic_pointer_cast(e) != NULL) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_ENDERDRAGON) + addEntity(e, 16 * 10, 3, true); + else if (e->GetType() == eTYPE_PRIMEDTNT) + addEntity(e, 16 * 10, 10, true); + else if (e->GetType() == eTYPE_FALLINGTILE) + addEntity(e, 16 * 10, 20, true); + else if (e->GetType() == eTYPE_PAINTING) + addEntity(e, 16 * 10, INT_MAX, false); + else if (e->GetType() == eTYPE_EXPERIENCEORB) + addEntity(e, 16 * 10, 20, true); + else if (e->GetType() == eTYPE_ENDER_CRYSTAL) + addEntity(e, 16 * 16, INT_MAX, false); + else if (e->GetType() == eTYPE_ITEM_FRAME) + addEntity(e, 16 * 10, INT_MAX, false); } -void EntityTracker::addEntity(std::shared_ptr e, int range, int updateInterval) -{ - addEntity(e, range, updateInterval, false); +void EntityTracker::addEntity(std::shared_ptr e, int range, + int updateInterval) { + addEntity(e, range, updateInterval, false); } -void EntityTracker::addEntity(std::shared_ptr e, int range, int updateInterval, bool trackDeltas) -{ +void EntityTracker::addEntity(std::shared_ptr e, int range, + int updateInterval, bool trackDeltas) { if (range > maxRange) range = maxRange; - if (entityMap.find(e->entityId) != entityMap.end()) - { - assert(false); // Entity already tracked - } - if( e->entityId >= 2048 ) - { - __debugbreak(); - } - std::shared_ptr te = std::shared_ptr( new TrackedEntity(e, range, updateInterval, trackDeltas) ); - entities.insert(te); + if (entityMap.find(e->entityId) != entityMap.end()) { + assert(false); // Entity already tracked + } + if (e->entityId >= 2048) { + __debugbreak(); + } + std::shared_ptr te = std::shared_ptr( + new TrackedEntity(e, range, updateInterval, trackDeltas)); + entities.insert(te); entityMap[e->entityId] = te; te->updatePlayers(this, &level->players); } -// 4J - have split removeEntity into two bits - it used to do the equivalent of EntityTracker::removePlayer followed by EntityTracker::removeEntity. -// This is to allow us to now choose to remove the player as a "seenBy" only when the player has actually been removed from the level's own player array -void EntityTracker::removeEntity(std::shared_ptr e) -{ - AUTO_VAR(it, entityMap.find(e->entityId)); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - entityMap.erase(it); - entities.erase(te); - te->broadcastRemoved(); - } -} - -void EntityTracker::removePlayer(std::shared_ptr e) -{ - if (e->GetType() == eTYPE_SERVERPLAYER) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - (*it)->removePlayer(player); - } +// 4J - have split removeEntity into two bits - it used to do the equivalent of +// EntityTracker::removePlayer followed by EntityTracker::removeEntity. This is +// to allow us to now choose to remove the player as a "seenBy" only when the +// player has actually been removed from the level's own player array +void EntityTracker::removeEntity(std::shared_ptr e) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + entityMap.erase(it); + entities.erase(te); + te->broadcastRemoved(); } } -void EntityTracker::tick() -{ - std::vector > movedPlayers; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - te->tick(this, &level->players); - if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) - { - movedPlayers.push_back(std::dynamic_pointer_cast(te->e)); +void EntityTracker::removePlayer(std::shared_ptr e) { + if (e->GetType() == eTYPE_SERVERPLAYER) { + std::shared_ptr player = + std::dynamic_pointer_cast(e); + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + (*it)->removePlayer(player); } - } + } +} - // 4J Stu - If one player on a system is updated, then make sure they all are as they all have their - // range extended to include entities visible by any other player on the system - // Fix for #11194 - Gameplay: Host player and their split-screen avatars can become invisible and invulnerable to client. - MinecraftServer *server = MinecraftServer::getInstance(); - for( unsigned int i = 0; i < server->getPlayers()->players.size(); i++ ) - { - std::shared_ptr ep = server->getPlayers()->players[i]; - if( ep->dimension != level->dimension->id ) continue; +void EntityTracker::tick() { + std::vector > movedPlayers; + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + te->tick(this, &level->players); + if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) { + movedPlayers.push_back( + std::dynamic_pointer_cast(te->e)); + } + } - if( ep->connection == NULL ) continue; - INetworkPlayer *thisPlayer = ep->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) continue; + // 4J Stu - If one player on a system is updated, then make sure they all + // are as they all have their range extended to include entities visible by + // any other player on the system Fix for #11194 - Gameplay: Host player and + // their split-screen avatars can become invisible and invulnerable to + // client. + MinecraftServer* server = MinecraftServer::getInstance(); + for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) { + std::shared_ptr ep = server->getPlayers()->players[i]; + if (ep->dimension != level->dimension->id) continue; - bool addPlayer = false; - for (unsigned int j = 0; j < movedPlayers.size(); j++) - { - std::shared_ptr sp = movedPlayers[j]; + if (ep->connection == NULL) continue; + INetworkPlayer* thisPlayer = ep->connection->getNetworkPlayer(); + if (thisPlayer == NULL) continue; - if( sp == ep ) break; + bool addPlayer = false; + for (unsigned int j = 0; j < movedPlayers.size(); j++) { + std::shared_ptr sp = movedPlayers[j]; - if(sp->connection == NULL) continue; - INetworkPlayer *otherPlayer = sp->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - addPlayer = true; - break; - } - } - if( addPlayer ) movedPlayers.push_back( ep ); - } + if (sp == ep) break; - for (unsigned int i = 0; i < movedPlayers.size(); i++) - { + if (sp->connection == NULL) continue; + INetworkPlayer* otherPlayer = sp->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + addPlayer = true; + break; + } + } + if (addPlayer) movedPlayers.push_back(ep); + } + + for (unsigned int i = 0; i < movedPlayers.size(); i++) { std::shared_ptr player = movedPlayers[i]; - if(player->connection == NULL) continue; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - if (te->e != player) - { + if (player->connection == NULL) continue; + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + if (te->e != player) { te->updatePlayer(this, player); } - } + } } - // 4J Stu - We want to do this for dead players as they don't tick normally - for(AUTO_VAR(it, level->players.begin()); it != level->players.end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - if(!player->isAlive()) - { - player->flushEntitiesToRemove(); - } - } + // 4J Stu - We want to do this for dead players as they don't tick normally + for (AUTO_VAR(it, level->players.begin()); it != level->players.end(); + ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + if (!player->isAlive()) { + player->flushEntitiesToRemove(); + } + } } -void EntityTracker::broadcast(std::shared_ptr e, std::shared_ptr packet) -{ - AUTO_VAR(it, entityMap.find( e->entityId )); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - te->broadcast(packet); - } +void EntityTracker::broadcast(std::shared_ptr e, + std::shared_ptr packet) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + te->broadcast(packet); + } } -void EntityTracker::broadcastAndSend(std::shared_ptr e, std::shared_ptr packet) -{ - AUTO_VAR(it, entityMap.find( e->entityId )); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - te->broadcastAndSend(packet); - } +void EntityTracker::broadcastAndSend(std::shared_ptr e, + std::shared_ptr packet) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + te->broadcastAndSend(packet); + } } -void EntityTracker::clear(std::shared_ptr serverPlayer) -{ - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - te->clear(serverPlayer); - } +void EntityTracker::clear(std::shared_ptr serverPlayer) { + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + te->clear(serverPlayer); + } } // AP added for Vita so the range can be increased once the level starts -void EntityTracker::updateMaxRange() -{ +void EntityTracker::updateMaxRange() { maxRange = level->getServer()->getPlayers()->getMaxRange(); } - -std::shared_ptr EntityTracker::getTracker(std::shared_ptr e) -{ - AUTO_VAR(it, entityMap.find(e->entityId)); - if( it != entityMap.end() ) - { - return it->second; - } - return nullptr; +std::shared_ptr EntityTracker::getTracker( + std::shared_ptr e) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + return it->second; + } + return nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/Player/EntityTracker.h b/Minecraft.Client/Player/EntityTracker.h index d3d9a32fe..3a0fb8471 100644 --- a/Minecraft.Client/Player/EntityTracker.h +++ b/Minecraft.Client/Player/EntityTracker.h @@ -7,30 +7,30 @@ class TrackedEntity; class MinecraftServer; class Packet; - - -class EntityTracker -{ +class EntityTracker { private: - ServerLevel *level; - std::unordered_set > entities; - std::unordered_map , IntKeyHash2, IntKeyEq> entityMap; // was IntHashMap + ServerLevel* level; + std::unordered_set > entities; + std::unordered_map, IntKeyHash2, + IntKeyEq> + entityMap; // was IntHashMap int maxRange; public: - EntityTracker(ServerLevel *level); + EntityTracker(ServerLevel* level); void addEntity(std::shared_ptr e); void addEntity(std::shared_ptr e, int range, int updateInterval); - void addEntity(std::shared_ptr e, int range, int updateInterval, bool trackDeltas); + void addEntity(std::shared_ptr e, int range, int updateInterval, + bool trackDeltas); void removeEntity(std::shared_ptr e); - void removePlayer(std::shared_ptr e); // 4J added + void removePlayer(std::shared_ptr e); // 4J added void tick(); void broadcast(std::shared_ptr e, std::shared_ptr packet); - void broadcastAndSend(std::shared_ptr e, std::shared_ptr packet); + void broadcastAndSend(std::shared_ptr e, + std::shared_ptr packet); void clear(std::shared_ptr serverPlayer); - void updateMaxRange(); // AP added for Vita + void updateMaxRange(); // AP added for Vita - - // 4J-JEV: Added, needed access to tracked entity of a riders mount. - std::shared_ptr getTracker(std::shared_ptr entity); + // 4J-JEV: Added, needed access to tracked entity of a riders mount. + std::shared_ptr getTracker(std::shared_ptr entity); }; diff --git a/Minecraft.Client/Player/LocalPlayer.cpp b/Minecraft.Client/Player/LocalPlayer.cpp index 3d8a38895..fca63774d 100644 --- a/Minecraft.Client/Player/LocalPlayer.cpp +++ b/Minecraft.Client/Player/LocalPlayer.cpp @@ -53,241 +53,210 @@ #include "../../Minecraft.World/Stats/CommonStats.h" #endif +LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, User* user, + int dimension) + : Player(level) { + flyX = flyY = flyZ = 0.0f; // 4J added + m_awardedThisSession = 0; + sprintTriggerTime = 0; + sprintTriggerRegisteredReturn = false; + twoJumpsRegistered = false; + sprintTime = 0; + m_uiInactiveTicks = 0; -LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension) : Player(level) -{ - flyX = flyY = flyZ = 0.0f; // 4J added - m_awardedThisSession = 0; - - sprintTriggerTime = 0; - sprintTriggerRegisteredReturn = false; - twoJumpsRegistered = false; - sprintTime = 0; - m_uiInactiveTicks=0; - - yBob = xBob = yBobO = xBobO = 0.0f; + yBob = xBob = yBobO = xBobO = 0.0f; this->minecraft = minecraft; this->dimension = dimension; - if (user != NULL && user->name.length() > 0) - { - customTextureUrl = L"http://s3.amazonaws.com/MinecraftSkins/" + user->name + L".png"; + if (user != NULL && user->name.length() > 0) { + customTextureUrl = + L"http://s3.amazonaws.com/MinecraftSkins/" + user->name + L".png"; } - if( user != NULL ) - { - this->name = user->name; - m_UUID = name; - //wprintf(L"Created LocalPlayer with name %ls\n", name.c_str() ); - // check to see if this player's xuid is in the list of special players - MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) - { - customTextureUrl=pMojangData->wchSkin; - } + if (user != NULL) { + this->name = user->name; + m_UUID = name; + // wprintf(L"Created LocalPlayer with name %ls\n", name.c_str() ); + // check to see if this player's xuid is in the list of special players + MOJANG_DATA* pMojangData = app.GetMojangDataForXuid(getOnlineXuid()); + if (pMojangData) { + customTextureUrl = pMojangData->wchSkin; + } + } + input = NULL; + m_iPad = -1; + m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; // assume singleplayer default + m_bPlayerRespawned = false; + ullButtonsPressed = 0LL; + ullDpad_last = ullDpad_this = ullDpad_filtered = 0; - } - input = NULL; - m_iPad = -1; - m_iScreenSection=C4JRender::VIEWPORT_TYPE_FULLSCREEN; // assume singleplayer default - m_bPlayerRespawned=false; - ullButtonsPressed=0LL; - ullDpad_last = ullDpad_this = ullDpad_filtered = 0; + // 4J-PB - moved in from the minecraft structure + // ticks=0; + missTime = 0; + lastClickTick[0] = 0; + lastClickTick[1] = 0; + isRaining = false; - // 4J-PB - moved in from the minecraft structure - //ticks=0; - missTime=0; - lastClickTick[0] = 0; - lastClickTick[1] = 0; - isRaining=false; + m_bIsIdle = false; + m_iThirdPersonView = 0; - m_bIsIdle = false; - m_iThirdPersonView=0; + // 4J Stu - Added for telemetry + SetSessionTimerStart(); - // 4J Stu - Added for telemetry - SetSessionTimerStart(); + // 4J - added for auto repeat in creative mode + lastClickState = lastClick_invalid; + lastClickTolerance = 0.0f; - // 4J - added for auto repeat in creative mode - lastClickState = lastClick_invalid; - lastClickTolerance = 0.0f; - - m_bHasAwardedStayinFrosty = false; + m_bHasAwardedStayinFrosty = false; } -LocalPlayer::~LocalPlayer() -{ - if( this->input != NULL ) - delete input; +LocalPlayer::~LocalPlayer() { + if (this->input != NULL) delete input; } // 4J - added noEntityCubes parameter -void LocalPlayer::move(double xa, double ya, double za, bool noEntityCubes) -{ - if (ClientConstants::DEADMAU5_CAMERA_CHEATS) - { - if (shared_from_this() == minecraft->player && minecraft->options->isFlying) - { +void LocalPlayer::move(double xa, double ya, double za, bool noEntityCubes) { + if (ClientConstants::DEADMAU5_CAMERA_CHEATS) { + if (shared_from_this() == minecraft->player && + minecraft->options->isFlying) { noPhysics = true; - float tmp = walkDist; // update - calculateFlight((float) xa, (float) ya, (float) za); + float tmp = walkDist; // update + calculateFlight((float)xa, (float)ya, (float)za); fallDistance = 0.0f; yd = 0.0f; Player::move(flyX, flyY, flyZ, noEntityCubes); onGround = true; walkDist = tmp; - } - else - { + } else { noPhysics = false; Player::move(xa, ya, za, noEntityCubes); } - } - else - { + } else { Player::move(xa, ya, za, noEntityCubes); } - } -void LocalPlayer::calculateFlight(float xa, float ya, float za) -{ +void LocalPlayer::calculateFlight(float xa, float ya, float za) { xa = xa * minecraft->options->flySpeed; ya = 0; za = za * minecraft->options->flySpeed; - flyX = smoothFlyX.getNewDeltaValue(xa, .35f * minecraft->options->sensitivity); - flyY = smoothFlyY.getNewDeltaValue(ya, .35f * minecraft->options->sensitivity); - flyZ = smoothFlyZ.getNewDeltaValue(za, .35f * minecraft->options->sensitivity); - + flyX = + smoothFlyX.getNewDeltaValue(xa, .35f * minecraft->options->sensitivity); + flyY = + smoothFlyY.getNewDeltaValue(ya, .35f * minecraft->options->sensitivity); + flyZ = + smoothFlyZ.getNewDeltaValue(za, .35f * minecraft->options->sensitivity); } -void LocalPlayer::serverAiStep() -{ +void LocalPlayer::serverAiStep() { Player::serverAiStep(); - - if( abilities.flying && abilities.mayfly ) - { - // snap y rotation for flying to nearest 90 degrees in world space - float fMag = sqrtf(input->xa * input->xa + input->ya * input->ya); - // Don't bother for tiny inputs - if( fMag >= 0.1f ) - { - // Get angle (in player rotated space) of input controls - float yRotInput = atan2f(input->ya, input->xa) * (180.0f / PI); - // Now get in world space - float yRotFinal = yRotInput + yRot; - // Snap this to nearest 90 degrees - float yRotSnapped = floorf((yRotFinal / 45.0f) + 0.5f) * 45.0f; - // Find out how much we had to move to do this snap - float yRotDiff = yRotSnapped - yRotFinal; - // Apply the same difference to the player rotated space angle - float yRotInputAdjust = yRotInput + yRotDiff; - - // Calculate final x/y player-space movement required - this->xxa = cos(yRotInputAdjust * ( PI / 180.0f) ) * fMag; - this->yya = sin(yRotInputAdjust * ( PI / 180.0f) ) * fMag; - } - else - { - this->xxa = input->xa; - this->yya = input->ya; - } - } - else - { - this->xxa = input->xa; - this->yya = input->ya; - } + + if (abilities.flying && abilities.mayfly) { + // snap y rotation for flying to nearest 90 degrees in world space + float fMag = sqrtf(input->xa * input->xa + input->ya * input->ya); + // Don't bother for tiny inputs + if (fMag >= 0.1f) { + // Get angle (in player rotated space) of input controls + float yRotInput = atan2f(input->ya, input->xa) * (180.0f / PI); + // Now get in world space + float yRotFinal = yRotInput + yRot; + // Snap this to nearest 90 degrees + float yRotSnapped = floorf((yRotFinal / 45.0f) + 0.5f) * 45.0f; + // Find out how much we had to move to do this snap + float yRotDiff = yRotSnapped - yRotFinal; + // Apply the same difference to the player rotated space angle + float yRotInputAdjust = yRotInput + yRotDiff; + + // Calculate final x/y player-space movement required + this->xxa = cos(yRotInputAdjust * (PI / 180.0f)) * fMag; + this->yya = sin(yRotInputAdjust * (PI / 180.0f)) * fMag; + } else { + this->xxa = input->xa; + this->yya = input->ya; + } + } else { + this->xxa = input->xa; + this->yya = input->ya; + } this->jumping = input->jumping; - yBobO = yBob; - xBobO = xBob; - xBob += (xRot - xBob) * 0.5; - yBob += (yRot - yBob) * 0.5; + yBobO = yBob; + xBobO = xBob; + xBob += (xRot - xBob) * 0.5; + yBob += (yRot - yBob) * 0.5; - // TODO 4J - Remove - //if (input->jumping) - // mapPlayerChunk(8); + // TODO 4J - Remove + // if (input->jumping) + // mapPlayerChunk(8); } -bool LocalPlayer::isEffectiveAI() -{ - return true; -} +bool LocalPlayer::isEffectiveAI() { return true; } -void LocalPlayer::aiStep() -{ - if (sprintTime > 0) - { - sprintTime--; - if (sprintTime == 0) - { - setSprinting(false); - } - } - if (sprintTriggerTime > 0) sprintTriggerTime--; - if (minecraft->gameMode->isCutScene()) - { - x = z = 0.5; - x = 0; - z = 0; - yRot = tickCount / 12.0f; - xRot = 10; - y = 68.5; - return; - } +void LocalPlayer::aiStep() { + if (sprintTime > 0) { + sprintTime--; + if (sprintTime == 0) { + setSprinting(false); + } + } + if (sprintTriggerTime > 0) sprintTriggerTime--; + if (minecraft->gameMode->isCutScene()) { + x = z = 0.5; + x = 0; + z = 0; + yRot = tickCount / 12.0f; + xRot = 10; + y = 68.5; + return; + } oPortalTime = portalTime; - if (isInsidePortal) - { - if (!level->isClientSide) - { + if (isInsidePortal) { + if (!level->isClientSide) { if (riding != NULL) this->ride(nullptr); } if (minecraft->screen != NULL) minecraft->setScreen(NULL); - if (portalTime == 0) - { - minecraft->soundEngine->playUI(eSoundType_PORTAL_TRIGGER, 1, random->nextFloat() * 0.4f + 0.8f); + if (portalTime == 0) { + minecraft->soundEngine->playUI(eSoundType_PORTAL_TRIGGER, 1, + random->nextFloat() * 0.4f + 0.8f); } portalTime += 1 / 80.0f; - if (portalTime >= 1) - { + if (portalTime >= 1) { portalTime = 1; } isInsidePortal = false; - } - else if (hasEffect(MobEffect::confusion) && getEffect(MobEffect::confusion)->getDuration() > (SharedConstants::TICKS_PER_SECOND * 3)) - { - portalTime += 1 / 150.0f; - if (portalTime > 1) - { - portalTime = 1; - } - } - else - { + } else if (hasEffect(MobEffect::confusion) && + getEffect(MobEffect::confusion)->getDuration() > + (SharedConstants::TICKS_PER_SECOND * 3)) { + portalTime += 1 / 150.0f; + if (portalTime > 1) { + portalTime = 1; + } + } else { if (portalTime > 0) portalTime -= 1 / 20.0f; if (portalTime < 0) portalTime = 0; } if (changingDimensionDelay > 0) changingDimensionDelay--; - bool wasJumping = input->jumping; - float runTreshold = 0.8f; + bool wasJumping = input->jumping; + float runTreshold = 0.8f; - bool wasRunning = input->ya >= runTreshold; - //input->tick( std::dynamic_pointer_cast( shared_from_this() ) ); - // 4J-PB - make it a localplayer - input->tick( this ); - if (isUsingItem()) - { - input->xa *= 0.2f; - input->ya *= 0.2f; - sprintTriggerTime = 0; - } - // this.heightOffset = input.sneaking?1.30f:1.62f; // 4J - this was already commented out - if (input->sneaking) // 4J - removed - TODO replace - { + bool wasRunning = input->ya >= runTreshold; + // input->tick( std::dynamic_pointer_cast( shared_from_this() ) ); + // 4J-PB - make it a localplayer + input->tick(this); + if (isUsingItem()) { + input->xa *= 0.2f; + input->ya *= 0.2f; + sprintTriggerTime = 0; + } + // this.heightOffset = input.sneaking?1.30f:1.62f; // 4J - this was already + // commented out + if (input->sneaking) // 4J - removed - TODO replace + { if (ySlideOffset < 0.2f) ySlideOffset = 0.2f; } @@ -296,777 +265,740 @@ void LocalPlayer::aiStep() checkInTile(x + bbWidth * 0.35, bb->y0 + 0.5, z - bbWidth * 0.35); checkInTile(x + bbWidth * 0.35, bb->y0 + 0.5, z + bbWidth * 0.35); - bool enoughFoodToSprint = getFoodData()->getFoodLevel() > FoodConstants::MAX_FOOD * FoodConstants::FOOD_SATURATION_LOW; + bool enoughFoodToSprint = + getFoodData()->getFoodLevel() > + FoodConstants::MAX_FOOD * FoodConstants::FOOD_SATURATION_LOW; - // 4J Stu - If we can fly, then we should be able to sprint without requiring food. This is particularly a problem for people who save a survival - // world with low food, then reload it in creative. - if(abilities.mayfly || isAllowedToFly() ) enoughFoodToSprint = true; + // 4J Stu - If we can fly, then we should be able to sprint without + // requiring food. This is particularly a problem for people who save a + // survival world with low food, then reload it in creative. + if (abilities.mayfly || isAllowedToFly()) enoughFoodToSprint = true; - // 4J - altered this slightly to make sure that the joypad returns to below returnTreshold in between registering two movements up to runThreshold - if (onGround && !isSprinting() && enoughFoodToSprint && !isUsingItem() && !hasEffect(MobEffect::blindness)) - { - if( !wasRunning && (input->ya >= runTreshold) ) - { - if (sprintTriggerTime == 0) - { - sprintTriggerTime = 7; - sprintTriggerRegisteredReturn = false; - } - else - { - if( sprintTriggerRegisteredReturn ) - { - setSprinting(true); - sprintTriggerTime = 0; - sprintTriggerRegisteredReturn = false; - } - } - } - else if( ( sprintTriggerTime > 0 ) && ( input->ya == 0.0f ) ) // ya of 0.0f here signifies that we have returned to the deadzone - { - sprintTriggerRegisteredReturn = true; - } - else if (input->sprintKey) - { - setSprinting(true); - } - } - if (isSneaking()) sprintTriggerTime = 0; - // 4J-PB - try not stopping sprint on collision - //if (isSprinting() && (input->ya < runTreshold || horizontalCollision || !enoughFoodToSprint)) - if (isSprinting() && ((input->ya < runTreshold && !input->sprintKey) || !enoughFoodToSprint)) - { - setSprinting(false); - } + // 4J - altered this slightly to make sure that the joypad returns to below + // returnTreshold in between registering two movements up to runThreshold + if (onGround && !isSprinting() && enoughFoodToSprint && !isUsingItem() && + !hasEffect(MobEffect::blindness)) { + if (!wasRunning && (input->ya >= runTreshold)) { + if (sprintTriggerTime == 0) { + sprintTriggerTime = 7; + sprintTriggerRegisteredReturn = false; + } else { + if (sprintTriggerRegisteredReturn) { + setSprinting(true); + sprintTriggerTime = 0; + sprintTriggerRegisteredReturn = false; + } + } + } else if ((sprintTriggerTime > 0) && + (input->ya == 0.0f)) // ya of 0.0f here signifies that we + // have returned to the deadzone + { + sprintTriggerRegisteredReturn = true; + } else if (input->sprintKey) { + setSprinting(true); + } + } + if (isSneaking()) sprintTriggerTime = 0; + // 4J-PB - try not stopping sprint on collision + // if (isSprinting() && (input->ya < runTreshold || horizontalCollision || + // !enoughFoodToSprint)) + if (isSprinting() && ((input->ya < runTreshold && !input->sprintKey) || + !enoughFoodToSprint)) { + setSprinting(false); + } - // 4J Stu - Fix for #52705 - Customer Encountered: Player can fly in bed while being in Creative mode. - if (!isSleeping() && (abilities.mayfly || isAllowedToFly() )) - { - // 4J altered to require jump button to released after being tapped twice to trigger move between flying / not flying - if (!wasJumping && input->jumping) - { - if (jumpTriggerTime == 0) - { - jumpTriggerTime = 10; // was 7 - twoJumpsRegistered = false; - } - else - { - twoJumpsRegistered = true; - } - } - else if( ( !input->jumping ) && ( jumpTriggerTime > 0 ) && twoJumpsRegistered ) - { + // 4J Stu - Fix for #52705 - Customer Encountered: Player can fly in bed + // while being in Creative mode. + if (!isSleeping() && (abilities.mayfly || isAllowedToFly())) { + // 4J altered to require jump button to released after being tapped + // twice to trigger move between flying / not flying + if (!wasJumping && input->jumping) { + if (jumpTriggerTime == 0) { + jumpTriggerTime = 10; // was 7 + twoJumpsRegistered = false; + } else { + twoJumpsRegistered = true; + } + } else if ((!input->jumping) && (jumpTriggerTime > 0) && + twoJumpsRegistered) { #ifndef _CONTENT_PACKAGE - printf("flying was %s\n", abilities.flying ? "on" : "off"); + printf("flying was %s\n", abilities.flying ? "on" : "off"); #endif - abilities.flying = !abilities.flying; + abilities.flying = !abilities.flying; #ifndef _CONTENT_PACKAGE - printf("flying is %s\n", abilities.flying ? "on" : "off"); + printf("flying is %s\n", abilities.flying ? "on" : "off"); #endif - jumpTriggerTime = 0; - twoJumpsRegistered = false; - if( abilities.flying ) input->sneaking = false; // 4J added - would we ever intentially want to go into flying mode whilst sneaking? - } - } - else if(abilities.flying) - { + jumpTriggerTime = 0; + twoJumpsRegistered = false; + if (abilities.flying) + input->sneaking = + false; // 4J added - would we ever intentially want to go + // into flying mode whilst sneaking? + } + } else if (abilities.flying) { #ifdef _DEBUG_MENUS_ENABLED - if(!abilities.debugflying) + if (!abilities.debugflying) #endif - { - abilities.flying = false; - } - } - + { + abilities.flying = false; + } + } - if (abilities.flying) - { - // yd = 0; - // 4J - note that the 0.42 added for going down is to make it match with what happens when you jump - jumping itself adds 0.42 to yd in Mob::jumpFromGround - if (ullButtonsPressed & (1LL<jumping) - { - noJumpDelay = 0; - yd += 0.15; - } + if (abilities.flying) { + // yd = 0; + // 4J - note that the 0.42 added for going down is to make it match with + // what happens when you jump - jumping itself adds 0.42 to yd in + // Mob::jumpFromGround + if (ullButtonsPressed & (1LL << MINECRAFT_ACTION_SNEAK_TOGGLE)) + yd -= + (0.15 + 0.42); // 4J - for flying mode, + // MINECRAFT_ACTION_SNEAK_TOGGLE isn't a toggle + // but just indicates that this button is down + if (input->jumping) { + noJumpDelay = 0; + yd += 0.15; + } - // snap y rotation to nearest 90 degree axis aligned value - float yRotSnapped = floorf((yRot / 90.0f) + 0.5f) * 90.0f; + // snap y rotation to nearest 90 degree axis aligned value + float yRotSnapped = floorf((yRot / 90.0f) + 0.5f) * 90.0f; - if(InputManager.GetJoypadMapVal(m_iPad) == 0) - { - if( ullDpad_filtered & (1LL<options->isFlying ) - { - Vec3* viewVector = getViewVector(1.0f); - - // 4J-PB - To let the player build easily while flying, we need to change this - -#ifdef _DEBUG_MENUS_ENABLED - if(abilities.debugflying) - { - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; - } - else -#endif - { - if( isSprinting() ) - { - // Accelrate up to full speed if we are sprinting, moving in the direction of the view vector - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; - - float scale = ((float)(SPRINT_DURATION - sprintTime))/10.0f; - scale = scale * scale; - if ( scale > 1.0f ) scale = 1.0f; - flyX *= scale; - flyY *= scale; - flyZ *= scale; - } - else - { - flyX = 0.0f; - flyY = 0.0f; - flyZ = 0.0f; - if( ullDpad_filtered & (1LL< PLAYER_IDLE_TIME ) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_IDLE,false); - m_bIsIdle = true; - } - else if ( m_bIsIdle && InputManager.GetIdleSeconds( m_iPad ) < PLAYER_IDLE_TIME ) - { - // Are we offline or online, and how many players are there - if(g_NetworkManager.GetPlayerCount()>1) - { - // only do it for this player here - each player will run this code - if(g_NetworkManager.IsLocalGame()) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYEROFFLINE,false); - } - else - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER,false); - } - } - else - { - if(g_NetworkManager.IsLocalGame()) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE,false); - } - else - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER_1P,false); - } - } - updateRichPresence(); - m_bIsIdle = false; - } -} + if (abilities.flying) // minecraft->options->isFlying ) + { + Vec3* viewVector = getViewVector(1.0f); -void LocalPlayer::changeDimension(int i) -{ - if (!level->isClientSide) - { - if (dimension == 1 && i == 1) - { - awardStat(GenericStats::winGame(), GenericStats::param_noArgs()); - //minecraft.setScreen(new WinScreen()); -#ifndef _CONTENT_PACKAGE - app.DebugPrintf("LocalPlayer::changeDimension from 1 to 1 but WinScreen has not been implemented.\n"); - __debugbreak(); + // 4J-PB - To let the player build easily while flying, we need to + // change this + +#ifdef _DEBUG_MENUS_ENABLED + if (abilities.debugflying) { + flyX = (float)viewVector->x * input->ya; + flyY = (float)viewVector->y * input->ya; + flyZ = (float)viewVector->z * input->ya; + } else #endif - } - else - { - awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); + { + if (isSprinting()) { + // Accelrate up to full speed if we are sprinting, moving in the + // direction of the view vector + flyX = (float)viewVector->x * input->ya; + flyY = (float)viewVector->y * input->ya; + flyZ = (float)viewVector->z * input->ya; - minecraft->soundEngine->playUI(eSoundType_PORTAL_TRAVEL, 1, random->nextFloat() * 0.4f + 0.8f); - } - } + float scale = ((float)(SPRINT_DURATION - sprintTime)) / 10.0f; + scale = scale * scale; + if (scale > 1.0f) scale = 1.0f; + flyX *= scale; + flyY *= scale; + flyZ *= scale; + } else { + flyX = 0.0f; + flyY = 0.0f; + flyZ = 0.0f; + if (ullDpad_filtered & (1LL << MINECRAFT_ACTION_DPAD_UP)) { + flyY = 0.1f; + } + if (ullDpad_filtered & (1LL << MINECRAFT_ACTION_DPAD_DOWN)) { + flyY = -0.1f; + } + } + } + + Player::move(flyX, flyY, flyZ); + + fallDistance = 0.0f; + yd = 0.0f; + onGround = true; + } + + // Check if the player is idle and the rich presence needs updated + if (!m_bIsIdle && InputManager.GetIdleSeconds(m_iPad) > PLAYER_IDLE_TIME) { + ProfileManager.SetCurrentGameActivity(m_iPad, CONTEXT_PRESENCE_IDLE, + false); + m_bIsIdle = true; + } else if (m_bIsIdle && + InputManager.GetIdleSeconds(m_iPad) < PLAYER_IDLE_TIME) { + // Are we offline or online, and how many players are there + if (g_NetworkManager.GetPlayerCount() > 1) { + // only do it for this player here - each player will run this code + if (g_NetworkManager.IsLocalGame()) { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYEROFFLINE, false); + } else { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER, false); + } + } else { + if (g_NetworkManager.IsLocalGame()) { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE, false); + } else { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER_1P, false); + } + } + updateRichPresence(); + m_bIsIdle = false; + } } -float LocalPlayer::getFieldOfViewModifier() -{ - float targetFov = 1.0f; +void LocalPlayer::changeDimension(int i) { + if (!level->isClientSide) { + if (dimension == 1 && i == 1) { + awardStat(GenericStats::winGame(), GenericStats::param_noArgs()); + // minecraft.setScreen(new WinScreen()); +#ifndef _CONTENT_PACKAGE + app.DebugPrintf( + "LocalPlayer::changeDimension from 1 to 1 but WinScreen has " + "not been implemented.\n"); + __debugbreak(); +#endif + } else { + awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); - // modify for movement - if (abilities.flying) targetFov *= 1.1f; - targetFov *= ((walkingSpeed * getWalkingSpeedModifier()) / defaultWalkSpeed + 1) / 2; - - // modify for bow =) - if (isUsingItem() && getUseItem()->id == Item::bow->id) - { - int ticksHeld = getTicksUsingItem(); - float scale = (float) ticksHeld / BowItem::MAX_DRAW_DURATION; - if (scale > 1) - { - scale = 1; - } - else - { - scale *= scale; - } - targetFov *= 1.0f - scale * .15f; - } - - return targetFov; + minecraft->soundEngine->playUI(eSoundType_PORTAL_TRAVEL, 1, + random->nextFloat() * 0.4f + 0.8f); + } + } } -void LocalPlayer::addAdditonalSaveData(CompoundTag *entityTag) -{ +float LocalPlayer::getFieldOfViewModifier() { + float targetFov = 1.0f; + + // modify for movement + if (abilities.flying) targetFov *= 1.1f; + targetFov *= + ((walkingSpeed * getWalkingSpeedModifier()) / defaultWalkSpeed + 1) / 2; + + // modify for bow =) + if (isUsingItem() && getUseItem()->id == Item::bow->id) { + int ticksHeld = getTicksUsingItem(); + float scale = (float)ticksHeld / BowItem::MAX_DRAW_DURATION; + if (scale > 1) { + scale = 1; + } else { + scale *= scale; + } + targetFov *= 1.0f - scale * .15f; + } + + return targetFov; +} + +void LocalPlayer::addAdditonalSaveData(CompoundTag* entityTag) { Player::addAdditonalSaveData(entityTag); entityTag->putInt(L"Score", score); } -void LocalPlayer::readAdditionalSaveData(CompoundTag *entityTag) -{ +void LocalPlayer::readAdditionalSaveData(CompoundTag* entityTag) { Player::readAdditionalSaveData(entityTag); score = entityTag->getInt(L"Score"); } -void LocalPlayer::closeContainer() -{ +void LocalPlayer::closeContainer() { Player::closeContainer(); minecraft->setScreen(NULL); - // 4J - Close any xui here - // Fix for #9164 - CRASH: MP: Title crashes upon opening a chest and having another user destroy it. - ui.PlayUISFX(eSFX_Back); - ui.CloseUIScenes( m_iPad ); + // 4J - Close any xui here + // Fix for #9164 - CRASH: MP: Title crashes upon opening a chest and having + // another user destroy it. + ui.PlayUISFX(eSFX_Back); + ui.CloseUIScenes(m_iPad); } -void LocalPlayer::openTextEdit(std::shared_ptr sign) -{ - bool success = app.LoadSignEntryMenu(GetXboxPad(), sign ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new TextEditScreen(sign)); +void LocalPlayer::openTextEdit(std::shared_ptr sign) { + bool success = app.LoadSignEntryMenu(GetXboxPad(), sign); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new TextEditScreen(sign)); } -bool LocalPlayer::openContainer(std::shared_ptr container) -{ - bool success = app.LoadContainerMenu(GetXboxPad(), inventory, container ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new ContainerScreen(inventory, container)); - return success; +bool LocalPlayer::openContainer(std::shared_ptr container) { + bool success = app.LoadContainerMenu(GetXboxPad(), inventory, container); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new ContainerScreen(inventory, container)); + return success; } -bool LocalPlayer::startCrafting(int x, int y, int z) -{ - bool success = app.LoadCrafting3x3Menu(GetXboxPad(), std::dynamic_pointer_cast( shared_from_this() ), x, y, z ); - if( success ) ui.PlayUISFX(eSFX_Press); - //app.LoadXuiCraftMenu(0,inventory, level, x, y, z); - //minecraft->setScreen(new CraftingScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startCrafting(int x, int y, int z) { + bool success = app.LoadCrafting3x3Menu( + GetXboxPad(), + std::dynamic_pointer_cast(shared_from_this()), x, y, z); + if (success) ui.PlayUISFX(eSFX_Press); + // app.LoadXuiCraftMenu(0,inventory, level, x, y, z); + // minecraft->setScreen(new CraftingScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::startEnchanting(int x, int y, int z) -{ - bool success = app.LoadEnchantingMenu(GetXboxPad(), inventory, x, y, z, level ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new EnchantmentScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startEnchanting(int x, int y, int z) { + bool success = + app.LoadEnchantingMenu(GetXboxPad(), inventory, x, y, z, level); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new EnchantmentScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::startRepairing(int x, int y, int z) -{ - bool success = app.LoadRepairingMenu(GetXboxPad(), inventory, level, x, y, z ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new RepairScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startRepairing(int x, int y, int z) { + bool success = + app.LoadRepairingMenu(GetXboxPad(), inventory, level, x, y, z); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new RepairScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::openFurnace(std::shared_ptr furnace) -{ - bool success = app.LoadFurnaceMenu(GetXboxPad(),inventory, furnace); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new FurnaceScreen(inventory, furnace)); - return success; +bool LocalPlayer::openFurnace(std::shared_ptr furnace) { + bool success = app.LoadFurnaceMenu(GetXboxPad(), inventory, furnace); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new FurnaceScreen(inventory, furnace)); + return success; } -bool LocalPlayer::openBrewingStand(std::shared_ptr brewingStand) -{ - bool success = app.LoadBrewingStandMenu(GetXboxPad(),inventory, brewingStand); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new BrewingStandScreen(inventory, brewingStand)); - return success; +bool LocalPlayer::openBrewingStand( + std::shared_ptr brewingStand) { + bool success = + app.LoadBrewingStandMenu(GetXboxPad(), inventory, brewingStand); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new BrewingStandScreen(inventory, brewingStand)); + return success; } -bool LocalPlayer::openTrap(std::shared_ptr trap) -{ - bool success = app.LoadTrapMenu(GetXboxPad(),inventory, trap); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new TrapScreen(inventory, trap)); - return success; +bool LocalPlayer::openTrap(std::shared_ptr trap) { + bool success = app.LoadTrapMenu(GetXboxPad(), inventory, trap); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new TrapScreen(inventory, trap)); + return success; } -bool LocalPlayer::openTrading(std::shared_ptr traderTarget) -{ - bool success = app.LoadTradingMenu(GetXboxPad(),inventory, traderTarget, level); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new MerchantScreen(inventory, traderTarget, level)); - return success; +bool LocalPlayer::openTrading(std::shared_ptr traderTarget) { + bool success = + app.LoadTradingMenu(GetXboxPad(), inventory, traderTarget, level); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new MerchantScreen(inventory, traderTarget, level)); + return success; } -void LocalPlayer::crit(std::shared_ptr e) -{ - std::shared_ptr critParticle = std::shared_ptr( new CritParticle((Level *)minecraft->level, e) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); +void LocalPlayer::crit(std::shared_ptr e) { + std::shared_ptr critParticle = std::shared_ptr( + new CritParticle((Level*)minecraft->level, e)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); } -void LocalPlayer::magicCrit(std::shared_ptr e) -{ - std::shared_ptr critParticle = std::shared_ptr( new CritParticle((Level *)minecraft->level, e, eParticleType_magicCrit) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); +void LocalPlayer::magicCrit(std::shared_ptr e) { + std::shared_ptr critParticle = std::shared_ptr( + new CritParticle((Level*)minecraft->level, e, eParticleType_magicCrit)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); } -void LocalPlayer::take(std::shared_ptr e, int orgCount) -{ - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle((Level *)minecraft->level, e, shared_from_this(), -0.5f) ) ); +void LocalPlayer::take(std::shared_ptr e, int orgCount) { + minecraft->particleEngine->add( + std::shared_ptr(new TakeAnimationParticle( + (Level*)minecraft->level, e, shared_from_this(), -0.5f))); } -void LocalPlayer::chat(const std::wstring& message) -{ -} +void LocalPlayer::chat(const std::wstring& message) {} -bool LocalPlayer::isSneaking() -{ - return input->sneaking && !m_isSleeping; -} +bool LocalPlayer::isSneaking() { return input->sneaking && !m_isSleeping; } -void LocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) -{ +void LocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) { int dmg = getHealth() - newHealth; - if (dmg <= 0) - { + if (dmg <= 0) { setHealth(newHealth); - if (dmg < 0) - { + if (dmg < 0) { invulnerableTime = invulnerableDuration / 2; } - } - else - { + } else { lastHurt = dmg; setHealth(getHealth()); invulnerableTime = invulnerableDuration; - actuallyHurt(DamageSource::genericSource,dmg); + actuallyHurt(DamageSource::genericSource, dmg); hurtTime = hurtDuration = 10; } + if (this->health <= 0) { + int deathTime = (int)(level->getTime() % Level::TICKS_PER_DAY) / 1000; + int carriedId = + inventory->getSelected() == NULL ? 0 : inventory->getSelected()->id; + TelemetryManager->RecordPlayerDiedOrFailed(GetXboxPad(), 0, y, 0, 0, + carriedId, 0, damageSource); - if( this->health <= 0) - { - int deathTime = (int)(level->getTime() % Level::TICKS_PER_DAY)/1000; - int carriedId = inventory->getSelected() == NULL ? 0 : inventory->getSelected()->id; - TelemetryManager->RecordPlayerDiedOrFailed(GetXboxPad(), 0, y, 0, 0, carriedId, 0, damageSource); - - // if there are any xuiscenes up for this player, close them - if(ui.GetMenuDisplayed(GetXboxPad())) - { - ui.CloseUIScenes(GetXboxPad()); - } - } - -} - -void LocalPlayer::respawn() -{ - // Select the right payer to respawn - minecraft->respawnPlayer(GetXboxPad(), 0, 0); -} - -void LocalPlayer::animateRespawn() -{ -// Player.animateRespawn(this, level); -} - -void LocalPlayer::displayClientMessage(int messageId) -{ - minecraft->gui->displayClientMessage(messageId, GetXboxPad()); -} - -void LocalPlayer::awardStat(Stat *stat, byteArray param) -{ -#ifdef _DURANGO - // 4J-JEV: Maybe we want to fine tune this later? #TODO - if ( !ProfileManager.IsGuest(GetXboxPad()) - && app.CanRecordStatsAndAchievements() - && ProfileManager.IsFullVersion() - ) - { - stat->handleParamBlob(std::dynamic_pointer_cast(shared_from_this()), param); - } - delete [] param.data; -#else - int count = CommonStats::readParam(param); - delete [] param.data; - - if (!app.CanRecordStatsAndAchievements()) return; - if (stat == NULL) return; - - if (stat->isAchievement()) - { - Achievement *ach = (Achievement *) stat; - // 4J-PB - changed to attempt to award everytime - the award may need a storage device, so needs a primary player, and the player may not have been a primary player when they first 'got' the award - // so let the award manager figure it out - //if (!minecraft->stats[m_iPad]->hasTaken(ach)) - { - // 4J-PB - Don't display the java popup - //minecraft->achievementPopup->popup(ach); - - // 4J Stu - Added this function in the libraries as some achievements don't get awarded to all players - // e.g. Splitscreen players cannot get theme/avatar/gamerpic and Trial players cannot get any - // This causes some extreme flooding of some awards - if(ProfileManager.CanBeAwarded(m_iPad, ach->getAchievementID() ) ) - { - // 4J Stu - We don't (currently) care about the gamerscore, so setting to a default of 0 points - TelemetryManager->RecordAchievementUnlocked(m_iPad,ach->getAchievementID(),0); - - // 4J Stu - Some awards cause a menu to popup. This can be bad, especially if you are surrounded by mobs! - // We cannot pause the game unless in offline single player, but lets at least do it then - if( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ProfileManager.GetAwardType(ach->getAchievementID() ) != eAwardType_Achievement ) - { - ui.CloseUIScenes(m_iPad); - ui.NavigateToScene(m_iPad,eUIScene_PauseMenu); - } - } - - // 4J-JEV: To stop spamming trophies. - unsigned long long achBit = ((unsigned long long)1) << ach->getAchievementID(); - if ( !(achBit & m_awardedThisSession) ) - { - ProfileManager.Award(m_iPad, ach->getAchievementID()); - if (ProfileManager.IsFullVersion()) - m_awardedThisSession |= achBit; - } + // if there are any xuiscenes up for this player, close them + if (ui.GetMenuDisplayed(GetXboxPad())) { + ui.CloseUIScenes(GetXboxPad()); } - minecraft->stats[m_iPad]->award(stat, level->difficulty, count); } - else - { - // 4J : WESTY : Added for new achievements. - StatsCounter* pStats = minecraft->stats[m_iPad]; +} + +void LocalPlayer::respawn() { + // Select the right payer to respawn + minecraft->respawnPlayer(GetXboxPad(), 0, 0); +} + +void LocalPlayer::animateRespawn() { + // Player.animateRespawn(this, level); +} + +void LocalPlayer::displayClientMessage(int messageId) { + minecraft->gui->displayClientMessage(messageId, GetXboxPad()); +} + +void LocalPlayer::awardStat(Stat* stat, byteArray param) { +#ifdef _DURANGO + // 4J-JEV: Maybe we want to fine tune this later? #TODO + if (!ProfileManager.IsGuest(GetXboxPad()) && + app.CanRecordStatsAndAchievements() && ProfileManager.IsFullVersion()) { + stat->handleParamBlob( + std::dynamic_pointer_cast(shared_from_this()), param); + } + delete[] param.data; +#else + int count = CommonStats::readParam(param); + delete[] param.data; + + if (!app.CanRecordStatsAndAchievements()) return; + if (stat == NULL) return; + + if (stat->isAchievement()) { + Achievement* ach = (Achievement*)stat; + // 4J-PB - changed to attempt to award everytime - the award may need a + // storage device, so needs a primary player, and the player may not + // have been a primary player when they first 'got' the award so let the + // award manager figure it out + // if (!minecraft->stats[m_iPad]->hasTaken(ach)) + { + // 4J-PB - Don't display the java popup + // minecraft->achievementPopup->popup(ach); + + // 4J Stu - Added this function in the libraries as some + // achievements don't get awarded to all players e.g. Splitscreen + // players cannot get theme/avatar/gamerpic and Trial players cannot + // get any This causes some extreme flooding of some awards + if (ProfileManager.CanBeAwarded(m_iPad, ach->getAchievementID())) { + // 4J Stu - We don't (currently) care about the gamerscore, so + // setting to a default of 0 points + TelemetryManager->RecordAchievementUnlocked( + m_iPad, ach->getAchievementID(), 0); + + // 4J Stu - Some awards cause a menu to popup. This can be bad, + // especially if you are surrounded by mobs! We cannot pause the + // game unless in offline single player, but lets at least do it + // then + if (g_NetworkManager.IsLocalGame() && + g_NetworkManager.GetPlayerCount() == 1 && + ProfileManager.GetAwardType(ach->getAchievementID()) != + eAwardType_Achievement) { + ui.CloseUIScenes(m_iPad); + ui.NavigateToScene(m_iPad, eUIScene_PauseMenu); + } + } + + // 4J-JEV: To stop spamming trophies. + unsigned long long achBit = ((unsigned long long)1) + << ach->getAchievementID(); + if (!(achBit & m_awardedThisSession)) { + ProfileManager.Award(m_iPad, ach->getAchievementID()); + if (ProfileManager.IsFullVersion()) + m_awardedThisSession |= achBit; + } + } + minecraft->stats[m_iPad]->award(stat, level->difficulty, count); + } else { + // 4J : WESTY : Added for new achievements. + StatsCounter* pStats = minecraft->stats[m_iPad]; pStats->award(stat, level->difficulty, count); - // 4J-JEV: Check achievements for unlocks. + // 4J-JEV: Check achievements for unlocks. - // LEADER OF THE PACK - if ( stat == GenericStats::tamedEntity(eTYPE_WOLF) ) - { - // Check to see if we have befriended 5 wolves! Is this really the best place to do this??!! - if ( pStats->getTotalValue(GenericStats::tamedEntity(eTYPE_WOLF)) >= 5 ) - { - awardStat(GenericStats::leaderOfThePack(), GenericStats::param_noArgs()); - } - } + // LEADER OF THE PACK + if (stat == GenericStats::tamedEntity(eTYPE_WOLF)) { + // Check to see if we have befriended 5 wolves! Is this really the + // best place to do this??!! + if (pStats->getTotalValue(GenericStats::tamedEntity(eTYPE_WOLF)) >= + 5) { + awardStat(GenericStats::leaderOfThePack(), + GenericStats::param_noArgs()); + } + } - // MOAR TOOLS - { - Stat *toolStats[4][5]; - toolStats[0][0] = GenericStats::itemsCrafted(Item::shovel_wood->id); - toolStats[0][1] = GenericStats::itemsCrafted(Item::shovel_stone->id); - toolStats[0][2] = GenericStats::itemsCrafted(Item::shovel_iron->id); - toolStats[0][3] = GenericStats::itemsCrafted(Item::shovel_diamond->id); - toolStats[0][4] = GenericStats::itemsCrafted(Item::shovel_gold->id); - toolStats[1][0] = GenericStats::itemsCrafted(Item::pickAxe_wood->id); - toolStats[1][1] = GenericStats::itemsCrafted(Item::pickAxe_stone->id); - toolStats[1][2] = GenericStats::itemsCrafted(Item::pickAxe_iron->id); - toolStats[1][3] = GenericStats::itemsCrafted(Item::pickAxe_diamond->id); - toolStats[1][4] = GenericStats::itemsCrafted(Item::pickAxe_gold->id); - toolStats[2][0] = GenericStats::itemsCrafted(Item::hatchet_wood->id); - toolStats[2][1] = GenericStats::itemsCrafted(Item::hatchet_stone->id); - toolStats[2][2] = GenericStats::itemsCrafted(Item::hatchet_iron->id); - toolStats[2][3] = GenericStats::itemsCrafted(Item::hatchet_diamond->id); - toolStats[2][4] = GenericStats::itemsCrafted(Item::hatchet_gold->id); - toolStats[3][0] = GenericStats::itemsCrafted(Item::hoe_wood->id); - toolStats[3][1] = GenericStats::itemsCrafted(Item::hoe_stone->id); - toolStats[3][2] = GenericStats::itemsCrafted(Item::hoe_iron->id); - toolStats[3][3] = GenericStats::itemsCrafted(Item::hoe_diamond->id); - toolStats[3][4] = GenericStats::itemsCrafted(Item::hoe_gold->id); - - bool justCraftedTool = false; - for (int i=0; i<4; i++) - { - for (int j=0; j<5; j++) - { - if ( stat == toolStats[i][j] ) - { - justCraftedTool = true; - break; - } - } - } + // MOAR TOOLS + { + Stat* toolStats[4][5]; + toolStats[0][0] = GenericStats::itemsCrafted(Item::shovel_wood->id); + toolStats[0][1] = + GenericStats::itemsCrafted(Item::shovel_stone->id); + toolStats[0][2] = GenericStats::itemsCrafted(Item::shovel_iron->id); + toolStats[0][3] = + GenericStats::itemsCrafted(Item::shovel_diamond->id); + toolStats[0][4] = GenericStats::itemsCrafted(Item::shovel_gold->id); + toolStats[1][0] = + GenericStats::itemsCrafted(Item::pickAxe_wood->id); + toolStats[1][1] = + GenericStats::itemsCrafted(Item::pickAxe_stone->id); + toolStats[1][2] = + GenericStats::itemsCrafted(Item::pickAxe_iron->id); + toolStats[1][3] = + GenericStats::itemsCrafted(Item::pickAxe_diamond->id); + toolStats[1][4] = + GenericStats::itemsCrafted(Item::pickAxe_gold->id); + toolStats[2][0] = + GenericStats::itemsCrafted(Item::hatchet_wood->id); + toolStats[2][1] = + GenericStats::itemsCrafted(Item::hatchet_stone->id); + toolStats[2][2] = + GenericStats::itemsCrafted(Item::hatchet_iron->id); + toolStats[2][3] = + GenericStats::itemsCrafted(Item::hatchet_diamond->id); + toolStats[2][4] = + GenericStats::itemsCrafted(Item::hatchet_gold->id); + toolStats[3][0] = GenericStats::itemsCrafted(Item::hoe_wood->id); + toolStats[3][1] = GenericStats::itemsCrafted(Item::hoe_stone->id); + toolStats[3][2] = GenericStats::itemsCrafted(Item::hoe_iron->id); + toolStats[3][3] = GenericStats::itemsCrafted(Item::hoe_diamond->id); + toolStats[3][4] = GenericStats::itemsCrafted(Item::hoe_gold->id); - if (justCraftedTool) - { - bool awardNow = true; - for (int i=0; i<4; i++) - { - bool craftedThisTool = false; - for (int j=0; j<5; j++) - { - if ( pStats->getTotalValue(toolStats[i][j]) > 0 ) - craftedThisTool = true; - } + bool justCraftedTool = false; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 5; j++) { + if (stat == toolStats[i][j]) { + justCraftedTool = true; + break; + } + } + } - if (!craftedThisTool) - { - awardNow = false; - break; - } - } + if (justCraftedTool) { + bool awardNow = true; + for (int i = 0; i < 4; i++) { + bool craftedThisTool = false; + for (int j = 0; j < 5; j++) { + if (pStats->getTotalValue(toolStats[i][j]) > 0) + craftedThisTool = true; + } - if (awardNow) - { - awardStat(GenericStats::MOARTools(), GenericStats::param_noArgs()); - } - } - - } + if (!craftedThisTool) { + awardNow = false; + break; + } + } + + if (awardNow) { + awardStat(GenericStats::MOARTools(), + GenericStats::param_noArgs()); + } + } + } #ifdef _XBOX - // AWARD: Have we killed 10 creepers? - if ( pStats->getTotalValue( GenericStats::killsCreeper() ) >= 10 ) - { - awardStat( GenericStats::kill10Creepers(), GenericStats::param_noArgs()); - } + // AWARD: Have we killed 10 creepers? + if (pStats->getTotalValue(GenericStats::killsCreeper()) >= 10) { + awardStat(GenericStats::kill10Creepers(), + GenericStats::param_noArgs()); + } - // AWARD : Have we been playing for 100 game days? - if ( pStats->getTotalValue( GenericStats::timePlayed() ) >= ( Level::TICKS_PER_DAY * 100 ) ) - { - awardStat( GenericStats::play100Days(), GenericStats::param_noArgs()); - } - // AWARD : Have we mined 100 blocks? - if ( pStats->getTotalValue( GenericStats::totalBlocksMined() ) >= 100 ) - { - awardStat( GenericStats::mine100Blocks(), GenericStats::param_noArgs()); - } + // AWARD : Have we been playing for 100 game days? + if (pStats->getTotalValue(GenericStats::timePlayed()) >= + (Level::TICKS_PER_DAY * 100)) { + awardStat(GenericStats::play100Days(), + GenericStats::param_noArgs()); + } + // AWARD : Have we mined 100 blocks? + if (pStats->getTotalValue(GenericStats::totalBlocksMined()) >= 100) { + awardStat(GenericStats::mine100Blocks(), + GenericStats::param_noArgs()); + } #endif #ifdef _EXTENDED_ACHIEVEMENTS - // AWARD : Porkchop, cook and eat a porkchop. - { - Stat *cookPorkchop, *eatPorkchop; - cookPorkchop = GenericStats::itemsCrafted(Item::porkChop_cooked_Id); - eatPorkchop = GenericStats::itemsUsed(Item::porkChop_cooked_Id); + // AWARD : Porkchop, cook and eat a porkchop. + { + Stat *cookPorkchop, *eatPorkchop; + cookPorkchop = GenericStats::itemsCrafted(Item::porkChop_cooked_Id); + eatPorkchop = GenericStats::itemsUsed(Item::porkChop_cooked_Id); - if ( stat == cookPorkchop || stat == eatPorkchop ) - { - int numCookPorkchop, numEatPorkchop; - numCookPorkchop = pStats->getTotalValue(cookPorkchop); - numEatPorkchop = pStats->getTotalValue(eatPorkchop); + if (stat == cookPorkchop || stat == eatPorkchop) { + int numCookPorkchop, numEatPorkchop; + numCookPorkchop = pStats->getTotalValue(cookPorkchop); + numEatPorkchop = pStats->getTotalValue(eatPorkchop); - app.DebugPrintf( - "[AwardStat] Check unlock 'Porkchop': " - "pork_cooked=%i, pork_eaten=%i.\n", - numCookPorkchop, numEatPorkchop - ); + app.DebugPrintf( + "[AwardStat] Check unlock 'Porkchop': " + "pork_cooked=%i, pork_eaten=%i.\n", + numCookPorkchop, numEatPorkchop); - if ( (0 < numCookPorkchop) && (0 < numEatPorkchop) ) - { - awardStat( GenericStats::porkChop(), GenericStats::param_porkChop() ); - } - } - } + if ((0 < numCookPorkchop) && (0 < numEatPorkchop)) { + awardStat(GenericStats::porkChop(), + GenericStats::param_porkChop()); + } + } + } - // AWARD : Passing the Time, play for 100 minecraft days. - { - Stat *timePlayed = GenericStats::timePlayed(); + // AWARD : Passing the Time, play for 100 minecraft days. + { + Stat* timePlayed = GenericStats::timePlayed(); - if ( stat == timePlayed ) - { - int iPlayedTicks, iRequiredTicks; - iPlayedTicks = pStats->getTotalValue(timePlayed); - iRequiredTicks = Level::TICKS_PER_DAY * 100; + if (stat == timePlayed) { + int iPlayedTicks, iRequiredTicks; + iPlayedTicks = pStats->getTotalValue(timePlayed); + iRequiredTicks = Level::TICKS_PER_DAY * 100; - /* app.DebugPrintf( - "[AwardStat] Check unlock 'Passing the Time': " - "total_ticks=%i, req=%i.\n", - iPlayedTicks, iRequiredTicks - ); */ + /* app.DebugPrintf( + "[AwardStat] Check unlock 'Passing the Time': " + "total_ticks=%i, req=%i.\n", + iPlayedTicks, iRequiredTicks + ); */ - if (iPlayedTicks >= iRequiredTicks) - { - awardStat( GenericStats::passingTheTime(), GenericStats::param_passingTheTime() ); - } - } - } + if (iPlayedTicks >= iRequiredTicks) { + awardStat(GenericStats::passingTheTime(), + GenericStats::param_passingTheTime()); + } + } + } - // AWARD : The Haggler, Acquire 30 emeralds. - { - Stat *emeraldMined, *emeraldBought; - emeraldMined = GenericStats::blocksMined(Tile::emeraldOre_Id); - emeraldBought = GenericStats::itemsBought(Item::emerald_Id); + // AWARD : The Haggler, Acquire 30 emeralds. + { + Stat *emeraldMined, *emeraldBought; + emeraldMined = GenericStats::blocksMined(Tile::emeraldOre_Id); + emeraldBought = GenericStats::itemsBought(Item::emerald_Id); - if ( stat == emeraldMined || stat == emeraldBought ) - { - int numEmeraldMined, numEmeraldBought, totalSum; - numEmeraldMined = pStats->getTotalValue(emeraldMined); - numEmeraldBought = pStats->getTotalValue(emeraldBought); - totalSum = numEmeraldMined + numEmeraldBought; - - app.DebugPrintf( - "[AwardStat] Check unlock 'The Haggler': " - "emerald_mined=%i, emerald_bought=%i, sum=%i.\n", - numEmeraldMined, numEmeraldBought, totalSum - ); + if (stat == emeraldMined || stat == emeraldBought) { + int numEmeraldMined, numEmeraldBought, totalSum; + numEmeraldMined = pStats->getTotalValue(emeraldMined); + numEmeraldBought = pStats->getTotalValue(emeraldBought); + totalSum = numEmeraldMined + numEmeraldBought; - if (totalSum >= 30) awardStat( GenericStats::theHaggler(), GenericStats::param_theHaggler() ); - } - } + app.DebugPrintf( + "[AwardStat] Check unlock 'The Haggler': " + "emerald_mined=%i, emerald_bought=%i, sum=%i.\n", + numEmeraldMined, numEmeraldBought, totalSum); - // AWARD : Pot Planter, craft and place a flowerpot. - { - Stat *craftFlowerpot, *placeFlowerpot; - craftFlowerpot = GenericStats::itemsCrafted(Item::flowerPot_Id); - placeFlowerpot = GenericStats::blocksPlaced(Tile::flowerPot_Id); + if (totalSum >= 30) + awardStat(GenericStats::theHaggler(), + GenericStats::param_theHaggler()); + } + } - if ( stat == craftFlowerpot || stat == placeFlowerpot ) - { - if ( (pStats->getTotalValue(craftFlowerpot) > 0) && (pStats->getTotalValue(placeFlowerpot) > 0) ) - { - awardStat( GenericStats::potPlanter(), GenericStats::param_potPlanter() ); - } - } - } + // AWARD : Pot Planter, craft and place a flowerpot. + { + Stat *craftFlowerpot, *placeFlowerpot; + craftFlowerpot = GenericStats::itemsCrafted(Item::flowerPot_Id); + placeFlowerpot = GenericStats::blocksPlaced(Tile::flowerPot_Id); - // AWARD : It's a Sign, craft and place a sign. - { - Stat *craftSign, *placeWallsign, *placeSignpost; - craftSign = GenericStats::itemsCrafted(Item::sign_Id); - placeWallsign = GenericStats::blocksPlaced(Tile::wallSign_Id); - placeSignpost = GenericStats::blocksPlaced(Tile::sign_Id); + if (stat == craftFlowerpot || stat == placeFlowerpot) { + if ((pStats->getTotalValue(craftFlowerpot) > 0) && + (pStats->getTotalValue(placeFlowerpot) > 0)) { + awardStat(GenericStats::potPlanter(), + GenericStats::param_potPlanter()); + } + } + } - if ( stat == craftSign || stat == placeWallsign || stat == placeSignpost ) - { - int numCraftedSigns, numPlacedWallSign, numPlacedSignpost; - numCraftedSigns = pStats->getTotalValue(craftSign); - numPlacedWallSign = pStats->getTotalValue(placeWallsign); - numPlacedSignpost = pStats->getTotalValue(placeSignpost); + // AWARD : It's a Sign, craft and place a sign. + { + Stat *craftSign, *placeWallsign, *placeSignpost; + craftSign = GenericStats::itemsCrafted(Item::sign_Id); + placeWallsign = GenericStats::blocksPlaced(Tile::wallSign_Id); + placeSignpost = GenericStats::blocksPlaced(Tile::sign_Id); - app.DebugPrintf( - "[AwardStat] Check unlock 'It's a Sign': " - "crafted=%i, placedWallSigns=%i, placedSignposts=%i.\n", - numCraftedSigns, numPlacedWallSign, numPlacedSignpost - ); + if (stat == craftSign || stat == placeWallsign || + stat == placeSignpost) { + int numCraftedSigns, numPlacedWallSign, numPlacedSignpost; + numCraftedSigns = pStats->getTotalValue(craftSign); + numPlacedWallSign = pStats->getTotalValue(placeWallsign); + numPlacedSignpost = pStats->getTotalValue(placeSignpost); - if ( (numCraftedSigns>0) && ((numPlacedWallSign+numPlacedSignpost)>0) ) - { - awardStat( GenericStats::itsASign(), GenericStats::param_itsASign()); - } - } - } + app.DebugPrintf( + "[AwardStat] Check unlock 'It's a Sign': " + "crafted=%i, placedWallSigns=%i, placedSignposts=%i.\n", + numCraftedSigns, numPlacedWallSign, numPlacedSignpost); - // AWARD : Rainbow Collection, collect all different colours of wool. - { - bool justPickedupWool = false; - - for (int i=0; i<16; i++) - if ( stat == GenericStats::itemsCollected(Tile::cloth_Id, i) ) - justPickedupWool = true; + if ((numCraftedSigns > 0) && + ((numPlacedWallSign + numPlacedSignpost) > 0)) { + awardStat(GenericStats::itsASign(), + GenericStats::param_itsASign()); + } + } + } - if (justPickedupWool) - { - unsigned int woolCount = 0; - - for (unsigned int i = 0; i < 16; i++) - { - if (pStats->getTotalValue(GenericStats::itemsCollected(Tile::cloth_Id, i)) > 0) - woolCount++; - } + // AWARD : Rainbow Collection, collect all different colours of wool. + { + bool justPickedupWool = false; - if (woolCount >= 16) awardStat( GenericStats::rainbowCollection(), GenericStats::param_rainbowCollection() ); - } - } + for (int i = 0; i < 16; i++) + if (stat == GenericStats::itemsCollected(Tile::cloth_Id, i)) + justPickedupWool = true; - // AWARD : Adventuring Time, visit at least 17 biomes - { - bool justEnteredBiome = false; + if (justPickedupWool) { + unsigned int woolCount = 0; - for (int i=0; i<23; i++) - if ( stat == GenericStats::enteredBiome(i) ) - justEnteredBiome = true; + for (unsigned int i = 0; i < 16; i++) { + if (pStats->getTotalValue(GenericStats::itemsCollected( + Tile::cloth_Id, i)) > 0) + woolCount++; + } - if (justEnteredBiome) - { - unsigned int biomeCount = 0; + if (woolCount >= 16) + awardStat(GenericStats::rainbowCollection(), + GenericStats::param_rainbowCollection()); + } + } - for (unsigned int i = 0; i < 23; i++) - { - if (pStats->getTotalValue(GenericStats::enteredBiome(i)) > 0) - biomeCount++; - } + // AWARD : Adventuring Time, visit at least 17 biomes + { + bool justEnteredBiome = false; - if (biomeCount >= 17) awardStat( GenericStats::adventuringTime(), GenericStats::param_adventuringTime() ); - } - } + for (int i = 0; i < 23; i++) + if (stat == GenericStats::enteredBiome(i)) + justEnteredBiome = true; + + if (justEnteredBiome) { + unsigned int biomeCount = 0; + + for (unsigned int i = 0; i < 23; i++) { + if (pStats->getTotalValue(GenericStats::enteredBiome(i)) > + 0) + biomeCount++; + } + + if (biomeCount >= 17) + awardStat(GenericStats::adventuringTime(), + GenericStats::param_adventuringTime()); + } + } #endif - } + } #endif } -bool LocalPlayer::isSolidBlock(int x, int y, int z) -{ - return level->isSolidBlockingTile(x, y, z); +bool LocalPlayer::isSolidBlock(int x, int y, int z) { + return level->isSolidBlockingTile(x, y, z); } -bool LocalPlayer::checkInTile(double x, double y, double z) -{ +bool LocalPlayer::checkInTile(double x, double y, double z) { int xTile = Mth::floor(x); int yTile = Mth::floor(y); int zTile = Mth::floor(z); @@ -1074,32 +1006,32 @@ bool LocalPlayer::checkInTile(double x, double y, double z) double xd = x - xTile; double zd = z - zTile; - if (isSolidBlock(xTile, yTile, zTile) || isSolidBlock(xTile, yTile + 1, zTile)) - { - bool west = !isSolidBlock(xTile - 1, yTile, zTile) && !isSolidBlock(xTile - 1, yTile + 1, zTile); - bool east = !isSolidBlock(xTile + 1, yTile, zTile) && !isSolidBlock(xTile + 1, yTile + 1, zTile); - bool north = !isSolidBlock(xTile, yTile, zTile - 1) && !isSolidBlock(xTile, yTile + 1, zTile - 1); - bool south = !isSolidBlock(xTile, yTile, zTile + 1) && !isSolidBlock(xTile, yTile + 1, zTile + 1); + if (isSolidBlock(xTile, yTile, zTile) || + isSolidBlock(xTile, yTile + 1, zTile)) { + bool west = !isSolidBlock(xTile - 1, yTile, zTile) && + !isSolidBlock(xTile - 1, yTile + 1, zTile); + bool east = !isSolidBlock(xTile + 1, yTile, zTile) && + !isSolidBlock(xTile + 1, yTile + 1, zTile); + bool north = !isSolidBlock(xTile, yTile, zTile - 1) && + !isSolidBlock(xTile, yTile + 1, zTile - 1); + bool south = !isSolidBlock(xTile, yTile, zTile + 1) && + !isSolidBlock(xTile, yTile + 1, zTile + 1); int dir = -1; double closest = 9999; - if (west && xd < closest) - { + if (west && xd < closest) { closest = xd; dir = 0; } - if (east && 1 - xd < closest) - { + if (east && 1 - xd < closest) { closest = 1 - xd; dir = 1; } - if (north && zd < closest) - { + if (north && zd < closest) { closest = zd; dir = 4; } - if (south && 1 - zd < closest) - { + if (south && 1 - zd < closest) { closest = 1 - zd; dir = 5; } @@ -1112,508 +1044,456 @@ bool LocalPlayer::checkInTile(double x, double y, double z) } return false; - } -void LocalPlayer::setSprinting(bool value) -{ - Player::setSprinting(value); - if (value == false) sprintTime = 0; - else sprintTime = SPRINT_DURATION; +void LocalPlayer::setSprinting(bool value) { + Player::setSprinting(value); + if (value == false) + sprintTime = 0; + else + sprintTime = SPRINT_DURATION; } -void LocalPlayer::setExperienceValues(float experienceProgress, int totalExp, int experienceLevel) -{ - this->experienceProgress = experienceProgress; - this->totalExperience = totalExp; - this->experienceLevel = experienceLevel; +void LocalPlayer::setExperienceValues(float experienceProgress, int totalExp, + int experienceLevel) { + this->experienceProgress = experienceProgress; + this->totalExperience = totalExp; + this->experienceLevel = experienceLevel; } -bool LocalPlayer::hasPermission(EGameCommand command) -{ - return level->getLevelData()->getAllowCommands(); +bool LocalPlayer::hasPermission(EGameCommand command) { + return level->getLevelData()->getAllowCommands(); } -void LocalPlayer::onCrafted(std::shared_ptr item) -{ - if( minecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; - gameMode->getTutorial()->onCrafted(item); - } +void LocalPlayer::onCrafted(std::shared_ptr item) { + if (minecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_iPad]; + gameMode->getTutorial()->onCrafted(item); + } } -void LocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) -{ - setCustomSkin(skinId); +void LocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) { + setCustomSkin(skinId); } -void LocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) -{ - setCustomCape(capeId); +void LocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) { + setCustomCape(capeId); } // 4J TODO - Remove #include "../../Minecraft.World/Level/LevelChunk.h" -void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) -{ - int cx = this->xChunk; - int cz = this->zChunk; +void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) { + int cx = this->xChunk; + int cz = this->zChunk; - int pZ = ((int) floor(this->z)) %16; - int pX = ((int) floor(this->x)) %16; + int pZ = ((int)floor(this->z)) % 16; + int pX = ((int)floor(this->x)) % 16; - std::cout <<"player in chunk ("<x<<","<y<<","<z<<")\n"; + std::cout << "player in chunk (" << cx << "," << cz << ") at (" << this->x + << "," << this->y << "," << this->z << ")\n"; - for (int v = -1; v < 2; v++) - for (unsigned int z = 0; z < 16; z++) - { - for (int u = -1; u < 2; u++) - for (unsigned int x = 0; x < 16; x++) - { - LevelChunk *cc = level->getChunk(cx+u, cz+v); - if ( x==pX && z==pZ && u==0 && v==0) - std::cout << "O"; - else for (unsigned int y = 127; y > 0; y--) - { - int t = cc->getTile(x,y,z); - if (flagTileType != 0 && t == flagTileType) { std::cout << "@"; break; } - else if (t != 0 && t < 10) { std::cout << t; break; } - else if (t > 0) { std::cout << "#"; break; } - } - } - std::cout << "\n"; - } + for (int v = -1; v < 2; v++) + for (unsigned int z = 0; z < 16; z++) { + for (int u = -1; u < 2; u++) + for (unsigned int x = 0; x < 16; x++) { + LevelChunk* cc = level->getChunk(cx + u, cz + v); + if (x == pX && z == pZ && u == 0 && v == 0) + std::cout << "O"; + else + for (unsigned int y = 127; y > 0; y--) { + int t = cc->getTile(x, y, z); + if (flagTileType != 0 && t == flagTileType) { + std::cout << "@"; + break; + } else if (t != 0 && t < 10) { + std::cout << t; + break; + } else if (t > 0) { + std::cout << "#"; + break; + } + } + } + std::cout << "\n"; + } - std::cout << "\n"; + std::cout << "\n"; } - -void LocalPlayer::handleMouseDown(int button, bool down) -{ - // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) - { - return; - } +void LocalPlayer::handleMouseDown(int button, bool down) { + // 4J Stu - We should not accept any input while asleep, except the above to + // wake up + if (isSleeping() && level != NULL && level->isClientSide) { + return; + } if (!down) missTime = 0; if (button == 0 && missTime > 0) return; - if (down && minecraft->hitResult != NULL && minecraft->hitResult->type == HitResult::TILE && button == 0) - { + if (down && minecraft->hitResult != NULL && + minecraft->hitResult->type == HitResult::TILE && button == 0) { int x = minecraft->hitResult->x; int y = minecraft->hitResult->y; int z = minecraft->hitResult->z; - // 4J - addition to stop layer mining out of the top or bottom of the world - // 4J Stu - Allow this for The End - if( ( ( y == 0 ) || ( ( y == 127 ) && level->dimension->hasCeiling ) ) && level->dimension->id != 1 ) return; + // 4J - addition to stop layer mining out of the top or bottom of the + // world 4J Stu - Allow this for The End + if (((y == 0) || ((y == 127) && level->dimension->hasCeiling)) && + level->dimension->id != 1) + return; - minecraft->gameMode->continueDestroyBlock(x, y, z, minecraft->hitResult->f); - - if(mayBuild(x,y,z)) - { - minecraft->particleEngine->crack(x, y, z, minecraft->hitResult->f); - swing(); - } - } - else - { + minecraft->gameMode->continueDestroyBlock(x, y, z, + minecraft->hitResult->f); + + if (mayBuild(x, y, z)) { + minecraft->particleEngine->crack(x, y, z, minecraft->hitResult->f); + swing(); + } + } else { minecraft->gameMode->stopDestroyBlock(); } } -bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) -{ - if( buttonPressed ) - { - if( lastClickState == lastClick_oldRepeat ) - { - return false; - } +bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) { + if (buttonPressed) { + if (lastClickState == lastClick_oldRepeat) { + return false; + } - // Are we in an auto-repeat situation? - If so only tell the game that we've clicked if we move more than a unit away from our last - // click position in any axis - if( lastClickState != lastClick_invalid ) - { - // If we're in disabled mode already (set when sprinting) then don't do anything - if we're sprinting, we don't auto-repeat at all. - // With auto repeat on, we can quickly place fires causing photosensitivity issues due to rapid flashing - if( lastClickState == lastClick_disabled ) return false; - // If we've started sprinting, go into this mode & also don't do anything - // Ignore repeate when sleeping - if( isSprinting() ) - { - lastClickState = lastClick_disabled; - return false; - } + // Are we in an auto-repeat situation? - If so only tell the game that + // we've clicked if we move more than a unit away from our last click + // position in any axis + if (lastClickState != lastClick_invalid) { + // If we're in disabled mode already (set when sprinting) then don't + // do anything - if we're sprinting, we don't auto-repeat at all. + // With auto repeat on, we can quickly place fires causing + // photosensitivity issues due to rapid flashing + if (lastClickState == lastClick_disabled) return false; + // If we've started sprinting, go into this mode & also don't do + // anything Ignore repeate when sleeping + if (isSprinting()) { + lastClickState = lastClick_disabled; + return false; + } - // Get distance from last click point in each axis - float dX = (float)x - lastClickX; - float dY = (float)y - lastClickY; - float dZ = (float)z - lastClickZ; - bool newClick = false; + // Get distance from last click point in each axis + float dX = (float)x - lastClickX; + float dY = (float)y - lastClickY; + float dZ = (float)z - lastClickZ; + bool newClick = false; - float ddx = dX - lastClickdX; - float ddy = dY - lastClickdY; - float ddz = dZ - lastClickdZ; + float ddx = dX - lastClickdX; + float ddy = dY - lastClickdY; + float ddz = dZ - lastClickdZ; - if( lastClickState == lastClick_moving ) - { - float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz ); - if( deltaChange < 0.01f ) - { - lastClickState = lastClick_stopped; - lastClickTolerance = 0.0f; - } - } - else if( lastClickState == lastClick_stopped ) - { - float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz ); - if( deltaChange >= 0.01f ) - { - lastClickState = lastClick_moving; - lastClickTolerance = 0.0f; - } - else - { - lastClickTolerance += 0.1f; - if( lastClickTolerance > 0.7f ) - { - lastClickTolerance = 0.0f; - lastClickState = lastClick_init; - } - } - } + if (lastClickState == lastClick_moving) { + float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz); + if (deltaChange < 0.01f) { + lastClickState = lastClick_stopped; + lastClickTolerance = 0.0f; + } + } else if (lastClickState == lastClick_stopped) { + float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz); + if (deltaChange >= 0.01f) { + lastClickState = lastClick_moving; + lastClickTolerance = 0.0f; + } else { + lastClickTolerance += 0.1f; + if (lastClickTolerance > 0.7f) { + lastClickTolerance = 0.0f; + lastClickState = lastClick_init; + } + } + } - lastClickdX = dX; - lastClickdY = dY; - lastClickdZ = dZ; + lastClickdX = dX; + lastClickdY = dY; + lastClickdZ = dZ; - // If we have moved more than one unit in any one axis, then register a new click - // The new click position is normalised at one unit in the direction of movement, so that we don't gradually drift away if we detect the movement a fraction over - // the unit distance each time + // If we have moved more than one unit in any one axis, then + // register a new click The new click position is normalised at one + // unit in the direction of movement, so that we don't gradually + // drift away if we detect the movement a fraction over the unit + // distance each time - if( fabsf(dX) >= 1.0f ) - { - dX= ( dX < 0.0f ) ? ceilf(dX) : floorf(dX); - newClick = true; - } - else if( fabsf(dY) >= 1.0f ) - { - dY= ( dY < 0.0f ) ? ceilf(dY) : floorf(dY); - newClick = true; - } - else if( fabsf(dZ) >= 1.0f ) - { - dZ= ( dZ < 0.0f ) ? ceilf(dZ) : floorf(dZ); - newClick = true; - } + if (fabsf(dX) >= 1.0f) { + dX = (dX < 0.0f) ? ceilf(dX) : floorf(dX); + newClick = true; + } else if (fabsf(dY) >= 1.0f) { + dY = (dY < 0.0f) ? ceilf(dY) : floorf(dY); + newClick = true; + } else if (fabsf(dZ) >= 1.0f) { + dZ = (dZ < 0.0f) ? ceilf(dZ) : floorf(dZ); + newClick = true; + } - if( ( !newClick ) && ( lastClickTolerance > 0.0f ) ) - { - float fTarget = 1.0f - lastClickTolerance; + if ((!newClick) && (lastClickTolerance > 0.0f)) { + float fTarget = 1.0f - lastClickTolerance; - if( fabsf(dX) >= fTarget ) newClick = true; - if( fabsf(dY) >= fTarget ) newClick = true; - if( fabsf(dZ) >= fTarget ) newClick = true; - } + if (fabsf(dX) >= fTarget) newClick = true; + if (fabsf(dY) >= fTarget) newClick = true; + if (fabsf(dZ) >= fTarget) newClick = true; + } - if( newClick ) - { - lastClickX += dX; - lastClickY += dY; - lastClickZ += dZ; + if (newClick) { + lastClickX += dX; + lastClickY += dY; + lastClickZ += dZ; - // Get a more accurate pick from the position where the new click should ideally have come from, rather than - // where we happen to be now (ie a rounded number of units from the last Click position) - double oldX = x; - double oldY = y; - double oldZ = z; - x = lastClickX; - y = lastClickY; - z = lastClickZ; + // Get a more accurate pick from the position where the new + // click should ideally have come from, rather than where we + // happen to be now (ie a rounded number of units from the last + // Click position) + double oldX = x; + double oldY = y; + double oldZ = z; + x = lastClickX; + y = lastClickY; + z = lastClickZ; - minecraft->gameRenderer->pick(1); + minecraft->gameRenderer->pick(1); - x = oldX; - y = oldY; - z = oldZ; + x = oldX; + y = oldY; + z = oldZ; - handleMouseClick(button); - - if( lastClickState == lastClick_stopped ) - { - lastClickState = lastClick_init; - lastClickTolerance = 0.0f; - } - else - { - lastClickState = lastClick_moving; - lastClickTolerance = 0.0f; - } - } - } - else - { - // First click - just record position & handle - lastClickX = (float)x; - lastClickY = (float)y; - lastClickZ = (float)z; - // If we actually placed an item, then move into the init state as we are going to be doing the special creative mode auto repeat - bool itemPlaced = handleMouseClick(button); - // If we're sprinting or riding, don't auto-repeat at all. With auto repeat on, we can quickly place fires causing photosensitivity issues due to rapid flashing - // Also ignore repeats when the player is sleeping - if( isSprinting() || isRiding() || isSleeping() ) - { - lastClickState = lastClick_disabled; - } - else - { - if( itemPlaced ) - { - lastClickState = lastClick_init; - lastClickTolerance = 0.0f; - } - else - { - // Didn't place an item - might actually be activating a switch or door or something - just do a standard auto repeat in this case - lastClickState = lastClick_oldRepeat; - } - } - return true; - } - } - else - { - lastClickState = lastClick_invalid; - } - return false; + handleMouseClick(button); + if (lastClickState == lastClick_stopped) { + lastClickState = lastClick_init; + lastClickTolerance = 0.0f; + } else { + lastClickState = lastClick_moving; + lastClickTolerance = 0.0f; + } + } + } else { + // First click - just record position & handle + lastClickX = (float)x; + lastClickY = (float)y; + lastClickZ = (float)z; + // If we actually placed an item, then move into the init state as + // we are going to be doing the special creative mode auto repeat + bool itemPlaced = handleMouseClick(button); + // If we're sprinting or riding, don't auto-repeat at all. With auto + // repeat on, we can quickly place fires causing photosensitivity + // issues due to rapid flashing Also ignore repeats when the player + // is sleeping + if (isSprinting() || isRiding() || isSleeping()) { + lastClickState = lastClick_disabled; + } else { + if (itemPlaced) { + lastClickState = lastClick_init; + lastClickTolerance = 0.0f; + } else { + // Didn't place an item - might actually be activating a + // switch or door or something - just do a standard auto + // repeat in this case + lastClickState = lastClick_oldRepeat; + } + } + return true; + } + } else { + lastClickState = lastClick_invalid; + } + return false; } -bool LocalPlayer::handleMouseClick(int button) -{ - bool returnItemPlaced = false; +bool LocalPlayer::handleMouseClick(int button) { + bool returnItemPlaced = false; - if (button == 0 && missTime > 0) return false; - if (button == 0) - { - //app.DebugPrintf("handleMouseClick - Player %d is swinging\n",GetXboxPad()); - swing(); - } + if (button == 0 && missTime > 0) return false; + if (button == 0) { + // app.DebugPrintf("handleMouseClick - Player %d is + // swinging\n",GetXboxPad()); + swing(); + } - bool mayUse = true; + bool mayUse = true; - // 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button + // 4J-PB - Adding a special case in here for sleeping in a bed in a + // multiplayer game - we need to wake up, and we don't have the + // inbedchatscreen with a button - if(button==1 && (isSleeping() && level != NULL && level->isClientSide)) - { - if(lastClickState == lastClick_oldRepeat) return false; + if (button == 1 && (isSleeping() && level != NULL && level->isClientSide)) { + if (lastClickState == lastClick_oldRepeat) return false; + std::shared_ptr mplp = + std::dynamic_pointer_cast( + shared_from_this()); - std::shared_ptr mplp = std::dynamic_pointer_cast( shared_from_this() ); + if (mplp && mplp->connection) mplp->StopSleeping(); + } + // 4J Stu - We should not accept any input while asleep, except the above to + // wake up + if (isSleeping() && level != NULL && level->isClientSide) { + return false; + } - if(mplp && mplp->connection) mplp->StopSleeping(); - - } - // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) - { - return false; - } + std::shared_ptr oldItem = inventory->getSelected(); - std::shared_ptr oldItem = inventory->getSelected(); + if (minecraft->hitResult == NULL) { + if (button == 0 && + minecraft->localgameModes[GetXboxPad()]->hasMissTime()) + missTime = 10; + } else if (minecraft->hitResult->type == HitResult::ENTITY) { + if (button == 0) { + minecraft->gameMode->attack(minecraft->localplayers[GetXboxPad()], + minecraft->hitResult->entity); + } + if (button == 1) { + // 4J-PB - if we milk a cow here, and end up with a bucket of milk, + // the if (mayUse && button == 1) further down will then empty our + // bucket if we're pointing at a tile It looks like interact really + // should be returning a result so we can check this, but it's + // possibly just the milk bucket that causes a problem - if (minecraft->hitResult == NULL) - { - if (button == 0 && minecraft->localgameModes[GetXboxPad()]->hasMissTime()) missTime = 10; - } - else if (minecraft->hitResult->type == HitResult::ENTITY) - { - if (button == 0) - { - minecraft->gameMode->attack(minecraft->localplayers[GetXboxPad()], minecraft->hitResult->entity); - } - if (button == 1) - { - // 4J-PB - if we milk a cow here, and end up with a bucket of milk, the if (mayUse && button == 1) further down will - // then empty our bucket if we're pointing at a tile - // It looks like interact really should be returning a result so we can check this, but it's possibly just the - // milk bucket that causes a problem + if (minecraft->hitResult->entity->GetType() == eTYPE_COW) { + // If I have an empty bucket in my hand, it's going to be filled + // with milk, so turn off mayUse + std::shared_ptr item = inventory->getSelected(); + if (item && (item->id == Item::bucket_empty_Id)) { + mayUse = false; + } + } + if (minecraft->gameMode->interact( + minecraft->localplayers[GetXboxPad()], + minecraft->hitResult->entity)) { + mayUse = false; + } + } + } else if (minecraft->hitResult->type == HitResult::TILE) { + int x = minecraft->hitResult->x; + int y = minecraft->hitResult->y; + int z = minecraft->hitResult->z; + int face = minecraft->hitResult->f; - if(minecraft->hitResult->entity->GetType()==eTYPE_COW) - { - // If I have an empty bucket in my hand, it's going to be filled with milk, so turn off mayUse - std::shared_ptr item = inventory->getSelected(); - if(item && (item->id==Item::bucket_empty_Id)) - { - mayUse=false; - } - } - if( minecraft->gameMode->interact(minecraft->localplayers[GetXboxPad()], minecraft->hitResult->entity) ) - { - mayUse = false; - } - } - } - else if (minecraft->hitResult->type == HitResult::TILE) - { - int x = minecraft->hitResult->x; - int y = minecraft->hitResult->y; - int z = minecraft->hitResult->z; - int face = minecraft->hitResult->f; + if (button == 0) { + // 4J - addition to stop layer mining out of the top or bottom of + // the world 4J Stu - Allow this for The End + if (!((y == 0) || ((y == 127) && level->dimension->hasCeiling)) || + level->dimension->id == 1) { + minecraft->gameMode->startDestroyBlock(x, y, z, + minecraft->hitResult->f); + } + } else { + std::shared_ptr item = oldItem; + int oldCount = item != NULL ? item->count : 0; + bool usedItem = false; + if (minecraft->gameMode->useItemOn( + minecraft->localplayers[GetXboxPad()], level, item, x, y, z, + face, minecraft->hitResult->pos, false, &usedItem)) { + // Presume that if we actually used the held item, then we've + // placed it + if (usedItem) { + returnItemPlaced = true; + } + mayUse = false; + // app.DebugPrintf("Player %d is swinging\n",GetXboxPad()); + swing(); + } + if (item == NULL) { + return false; + } - if (button == 0) - { - // 4J - addition to stop layer mining out of the top or bottom of the world - // 4J Stu - Allow this for The End - if( !( ( y == 0 ) || ( ( y == 127 ) && level->dimension->hasCeiling ) ) || level->dimension->id == 1 ) - { - minecraft->gameMode->startDestroyBlock(x, y, z, minecraft->hitResult->f); - } - } - else - { - std::shared_ptr item = oldItem; - int oldCount = item != NULL ? item->count : 0; - bool usedItem = false; - if (minecraft->gameMode->useItemOn(minecraft->localplayers[GetXboxPad()], level, item, x, y, z, face, minecraft->hitResult->pos, false, &usedItem)) - { - // Presume that if we actually used the held item, then we've placed it - if( usedItem ) - { - returnItemPlaced = true; - } - mayUse = false; - //app.DebugPrintf("Player %d is swinging\n",GetXboxPad()); - swing(); - } - if (item == NULL) - { - return false; - } + if (item->count == 0) { + inventory->items[inventory->selected] = nullptr; + } else if (item->count != oldCount || + minecraft->localgameModes[GetXboxPad()] + ->hasInfiniteItems()) { + minecraft->gameRenderer->itemInHandRenderer->itemPlaced(); + } + } + } - if (item->count == 0) - { - inventory->items[inventory->selected] = nullptr; - } - else if (item->count != oldCount || minecraft->localgameModes[GetXboxPad()]->hasInfiniteItems()) - { - minecraft->gameRenderer->itemInHandRenderer->itemPlaced(); - } - } - } - - if (mayUse && button == 1) - { - std::shared_ptr item = inventory->getSelected(); - if (item != NULL) - { - if (minecraft->gameMode->useItem(minecraft->localplayers[GetXboxPad()], level, item)) - { - minecraft->gameRenderer->itemInHandRenderer->itemUsed(); - } - } - } - return returnItemPlaced; + if (mayUse && button == 1) { + std::shared_ptr item = inventory->getSelected(); + if (item != NULL) { + if (minecraft->gameMode->useItem( + minecraft->localplayers[GetXboxPad()], level, item)) { + minecraft->gameRenderer->itemInHandRenderer->itemUsed(); + } + } + } + return returnItemPlaced; } -void LocalPlayer::updateRichPresence() -{ - if((m_iPad!=-1)/* && !ui.GetMenuDisplayed(m_iPad)*/ ) - { - std::shared_ptr selectedItem = inventory->getSelected(); - if(selectedItem != NULL && selectedItem->id == Item::fishingRod_Id) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_FISHING); - } - else if(selectedItem != NULL && selectedItem->id == Item::map_Id) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_MAP); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_MINECART); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_BOATING); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_PIG); - } - else if( this->dimension == -1 ) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_NETHER); - } - else if( minecraft->soundEngine->GetIsPlayingStreamingCDMusic() ) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_CD); - } - else - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_BLANK); - } - } +void LocalPlayer::updateRichPresence() { + if ((m_iPad != -1) /* && !ui.GetMenuDisplayed(m_iPad)*/) { + std::shared_ptr selectedItem = inventory->getSelected(); + if (selectedItem != NULL && selectedItem->id == Item::fishingRod_Id) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_FISHING); + } else if (selectedItem != NULL && selectedItem->id == Item::map_Id) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_MAP); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, + CONTEXT_GAME_STATE_RIDING_MINECART); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_BOATING); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_RIDING_PIG); + } else if (this->dimension == -1) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_NETHER); + } else if (minecraft->soundEngine->GetIsPlayingStreamingCDMusic()) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_CD); + } else { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_BLANK); + } + } } // 4J Stu - Added for telemetry -void LocalPlayer::SetSessionTimerStart(void) -{ - m_sessionTimeStart=app.getAppTime(); - m_dimensionTimeStart=m_sessionTimeStart; +void LocalPlayer::SetSessionTimerStart(void) { + m_sessionTimeStart = app.getAppTime(); + m_dimensionTimeStart = m_sessionTimeStart; } -float LocalPlayer::getSessionTimer(void) -{ - return app.getAppTime()-m_sessionTimeStart; +float LocalPlayer::getSessionTimer(void) { + return app.getAppTime() - m_sessionTimeStart; } -float LocalPlayer::getAndResetChangeDimensionTimer() -{ - float appTime = app.getAppTime(); - float returnVal = appTime - m_dimensionTimeStart; - m_dimensionTimeStart = appTime; - return returnVal; +float LocalPlayer::getAndResetChangeDimensionTimer() { + float appTime = app.getAppTime(); + float returnVal = appTime - m_dimensionTimeStart; + m_dimensionTimeStart = appTime; + return returnVal; } -void LocalPlayer::handleCollectItem(std::shared_ptr item) -{ - if(item != NULL) - { - unsigned int itemCountAnyAux = 0; - unsigned int itemCountThisAux = 0; - for (unsigned int k = 0; k < inventory->items.length; ++k) - { - if (inventory->items[k] != NULL) - { - // do they have the item - if(inventory->items[k]->id == item->id) - { - unsigned int quantity = inventory->items[k]->GetCount(); +void LocalPlayer::handleCollectItem(std::shared_ptr item) { + if (item != NULL) { + unsigned int itemCountAnyAux = 0; + unsigned int itemCountThisAux = 0; + for (unsigned int k = 0; k < inventory->items.length; ++k) { + if (inventory->items[k] != NULL) { + // do they have the item + if (inventory->items[k]->id == item->id) { + unsigned int quantity = inventory->items[k]->GetCount(); - itemCountAnyAux += quantity; + itemCountAnyAux += quantity; - if( inventory->items[k]->getAuxValue() == item->getAuxValue() ) - { - itemCountThisAux += quantity; - } - } - } - } - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; - gameMode->getTutorial()->onTake(item, itemCountAnyAux, itemCountThisAux); - } + if (inventory->items[k]->getAuxValue() == + item->getAuxValue()) { + itemCountThisAux += quantity; + } + } + } + } + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_iPad]; + gameMode->getTutorial()->onTake(item, itemCountAnyAux, + itemCountThisAux); + } - if(ui.IsContainerMenuDisplayed(m_iPad)) - { - ui.HandleInventoryUpdated(m_iPad); - } + if (ui.IsContainerMenuDisplayed(m_iPad)) { + ui.HandleInventoryUpdated(m_iPad); + } } -void LocalPlayer::SetPlayerAdditionalModelParts(std::vectorpAdditionalModelParts) -{ - m_pAdditionalModelParts=pAdditionalModelParts; +void LocalPlayer::SetPlayerAdditionalModelParts( + std::vector pAdditionalModelParts) { + m_pAdditionalModelParts = pAdditionalModelParts; } diff --git a/Minecraft.Client/Player/LocalPlayer.h b/Minecraft.Client/Player/LocalPlayer.h index cb8b5dfa1..28edd6270 100644 --- a/Minecraft.Client/Player/LocalPlayer.h +++ b/Minecraft.Client/Player/LocalPlayer.h @@ -14,187 +14,199 @@ class Input; class Stat; class Minecraft; - - // Time in seconds before the players presence is update to Idle #define PLAYER_IDLE_TIME 300 -class LocalPlayer : public Player -{ +class LocalPlayer : public Player { public: - static const int SPRINT_DURATION = 20 * 30; + static const int SPRINT_DURATION = 20 * 30; + + Input* input; - Input *input; protected: - Minecraft *minecraft; - int sprintTriggerTime; - bool sprintTriggerRegisteredReturn; // 4J added - bool twoJumpsRegistered; // 4J added + Minecraft* minecraft; + int sprintTriggerTime; + bool sprintTriggerRegisteredReturn; // 4J added + bool twoJumpsRegistered; // 4J added - unsigned int m_uiInactiveTicks; // To measure time for idle anims + unsigned int m_uiInactiveTicks; // To measure time for idle anims - unsigned long long m_awardedThisSession; + unsigned long long m_awardedThisSession; - // 4J - Last time we checked for achievement uunlocks. - //long long m_lastAchievementUpdate; + // 4J - Last time we checked for achievement uunlocks. + // long long m_lastAchievementUpdate; public: - int sprintTime; + int sprintTime; - float yBob, xBob; - float yBobO, xBobO; + float yBob, xBob; + float yBobO, xBobO; - LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension); - virtual ~LocalPlayer(); + LocalPlayer(Minecraft* minecraft, Level* level, User* user, int dimension); + virtual ~LocalPlayer(); - void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter + void move( + double xa, double ya, double za, + bool noEntityCubes = false); // 4J - added noEntityCubes parameter - - int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for single player - __uint64 ullButtonsPressed; // Stores the button presses, since the inputmanager can be ticked faster than the minecraft - // player tick, and a button press and release combo can be missed in the minecraft::tick + int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for + // single player + __uint64 + ullButtonsPressed; // Stores the button presses, since the inputmanager + // can be ticked faster than the minecraft player + // tick, and a button press and release combo can be + // missed in the minecraft::tick - __uint64 ullDpad_last; - __uint64 ullDpad_this; - __uint64 ullDpad_filtered; + __uint64 ullDpad_last; + __uint64 ullDpad_this; + __uint64 ullDpad_filtered; - // 4J-PB - moved these in from the minecraft structure, since they are per player things for splitscreen - //int ticks; - int missTime; - int lastClickTick[2]; - bool isRaining ; - int m_iThirdPersonView; + // 4J-PB - moved these in from the minecraft structure, since they are per + // player things for splitscreen + // int ticks; + int missTime; + int lastClickTick[2]; + bool isRaining; + int m_iThirdPersonView; - bool m_bHasAwardedStayinFrosty; + bool m_bHasAwardedStayinFrosty; private: - float flyX, flyY, flyZ; - -protected: - // 4J-PB - player's xbox pad - int m_iPad; + float flyX, flyY, flyZ; - bool m_bIsIdle; +protected: + // 4J-PB - player's xbox pad + int m_iPad; + + bool m_bIsIdle; private: // local player fly // -------------------------------------------------------------------------- // smooth camera settings - SmoothFloat smoothFlyX; + SmoothFloat smoothFlyX; SmoothFloat smoothFlyY; SmoothFloat smoothFlyZ; void calculateFlight(float xa, float ya, float za); public: - virtual void serverAiStep(); + virtual void serverAiStep(); protected: - bool isEffectiveAI(); + bool isEffectiveAI(); public: virtual void aiStep(); - virtual void changeDimension(int i); - virtual float getFieldOfViewModifier(); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *entityTag); + virtual void changeDimension(int i); + virtual float getFieldOfViewModifier(); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* entityTag); virtual void closeContainer(); virtual void openTextEdit(std::shared_ptr sign); - virtual bool openContainer(std::shared_ptr container); // 4J added bool return - virtual bool startCrafting(int x, int y, int z); // 4J added bool return - virtual bool startEnchanting(int x, int y, int z); // 4J added bool return - virtual bool startRepairing(int x, int y, int z); - virtual bool openFurnace(std::shared_ptr furnace); // 4J added bool return - virtual bool openBrewingStand(std::shared_ptr brewingStand); // 4J added bool return - virtual bool openTrap(std::shared_ptr trap); // 4J added bool return - virtual bool openTrading(std::shared_ptr traderTarget); - virtual void crit(std::shared_ptr e); - virtual void magicCrit(std::shared_ptr e); + virtual bool openContainer( + std::shared_ptr container); // 4J added bool return + virtual bool startCrafting(int x, int y, int z); // 4J added bool return + virtual bool startEnchanting(int x, int y, int z); // 4J added bool return + virtual bool startRepairing(int x, int y, int z); + virtual bool openFurnace( + std::shared_ptr furnace); // 4J added bool return + virtual bool openBrewingStand(std::shared_ptr + brewingStand); // 4J added bool return + virtual bool openTrap( + std::shared_ptr trap); // 4J added bool return + virtual bool openTrading(std::shared_ptr traderTarget); + virtual void crit(std::shared_ptr e); + virtual void magicCrit(std::shared_ptr e); virtual void take(std::shared_ptr e, int orgCount); virtual void chat(const std::wstring& message); - virtual bool isSneaking(); - //virtual bool isIdle(); + virtual bool isSneaking(); + // virtual bool isIdle(); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); virtual void respawn(); virtual void animateRespawn(); virtual void displayClientMessage(int messageId); - virtual void awardStat(Stat *stat, byteArray param); - virtual int ThirdPersonView() { return m_iThirdPersonView;} - // 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like original, 2 reversed mode - virtual void SetThirdPersonView(int val) {m_iThirdPersonView=val;} + virtual void awardStat(Stat* stat, byteArray param); + virtual int ThirdPersonView() { return m_iThirdPersonView; } + // 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like + // original, 2 reversed mode + virtual void SetThirdPersonView(int val) { m_iThirdPersonView = val; } - void ResetInactiveTicks() { m_uiInactiveTicks=0;} - unsigned int GetInactiveTicks() { return m_uiInactiveTicks;} - void IncrementInactiveTicks() { if(m_uiInactiveTicks<255) m_uiInactiveTicks++;} + void ResetInactiveTicks() { m_uiInactiveTicks = 0; } + unsigned int GetInactiveTicks() { return m_uiInactiveTicks; } + void IncrementInactiveTicks() { + if (m_uiInactiveTicks < 255) m_uiInactiveTicks++; + } - void mapPlayerChunk(unsigned int); - // 4J-PB - xbox pad for this player - void SetXboxPad(int iPad) {m_iPad=iPad;} - int GetXboxPad() {return m_iPad;} - void SetPlayerRespawned(bool bVal) {m_bPlayerRespawned=bVal;} - bool GetPlayerRespawned() {return m_bPlayerRespawned;} + void mapPlayerChunk(unsigned int); + // 4J-PB - xbox pad for this player + void SetXboxPad(int iPad) { m_iPad = iPad; } + int GetXboxPad() { return m_iPad; } + void SetPlayerRespawned(bool bVal) { m_bPlayerRespawned = bVal; } + bool GetPlayerRespawned() { return m_bPlayerRespawned; } - // 4J-PB - Moved these in here from the minecraft structure since they are local player related - void handleMouseDown(int button, bool down); - bool handleMouseClick(int button); + // 4J-PB - Moved these in here from the minecraft structure since they are + // local player related + void handleMouseDown(int button, bool down); + bool handleMouseClick(int button); - // 4J - added for improved autorepeat - bool creativeModeHandleMouseClick(int button, bool buttonPressed); - float lastClickX; - float lastClickY; - float lastClickZ; - float lastClickdX; - float lastClickdY; - float lastClickdZ; - enum eLastClickState - { - lastClick_invalid, - lastClick_init, - lastClick_moving, - lastClick_stopped, - lastClick_oldRepeat, - lastClick_disabled - }; - float lastClickTolerance; - int lastClickState; + // 4J - added for improved autorepeat + bool creativeModeHandleMouseClick(int button, bool buttonPressed); + float lastClickX; + float lastClickY; + float lastClickZ; + float lastClickdX; + float lastClickdY; + float lastClickdZ; + enum eLastClickState { + lastClick_invalid, + lastClick_init, + lastClick_moving, + lastClick_stopped, + lastClick_oldRepeat, + lastClick_disabled + }; + float lastClickTolerance; + int lastClickState; - // 4J Stu - Added to allow callback to tutorial to stay within Minecraft.Client - virtual void onCrafted(std::shared_ptr item); + // 4J Stu - Added to allow callback to tutorial to stay within + // Minecraft.Client + virtual void onCrafted(std::shared_ptr item); - virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); - virtual void setAndBroadcastCustomCape(std::uint32_t capeId); + virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); + virtual void setAndBroadcastCustomCape(std::uint32_t capeId); private: - bool isSolidBlock(int x, int y, int z); - bool m_bPlayerRespawned; + bool isSolidBlock(int x, int y, int z); + bool m_bPlayerRespawned; protected: - bool checkInTile(double x, double y, double z); + bool checkInTile(double x, double y, double z); public: - void setSprinting(bool value); - void setExperienceValues(float experienceProgress, int totalExp, int experienceLevel); + void setSprinting(bool value); + void setExperienceValues(float experienceProgress, int totalExp, + int experienceLevel); - bool hasPermission(EGameCommand command); + bool hasPermission(EGameCommand command); - void updateRichPresence(); + void updateRichPresence(); - // 4J Stu - Added for telemetry - float m_sessionTimeStart; - float m_dimensionTimeStart; + // 4J Stu - Added for telemetry + float m_sessionTimeStart; + float m_dimensionTimeStart; public: - void SetSessionTimerStart(void); - float getSessionTimer(void); + void SetSessionTimerStart(void); + float getSessionTimer(void); - float getAndResetChangeDimensionTimer(); + float getAndResetChangeDimensionTimer(); - virtual void handleCollectItem(std::shared_ptr item); - void SetPlayerAdditionalModelParts(std::vectorpAdditionalModelParts); + virtual void handleCollectItem(std::shared_ptr item); + void SetPlayerAdditionalModelParts( + std::vector pAdditionalModelParts); private: - std::vector m_pAdditionalModelParts; + std::vector m_pAdditionalModelParts; }; - - diff --git a/Minecraft.Client/Player/MultiPlayerGameMode.cpp b/Minecraft.Client/Player/MultiPlayerGameMode.cpp index 4e5e0426d..8d9957c3e 100644 --- a/Minecraft.Client/Player/MultiPlayerGameMode.cpp +++ b/Minecraft.Client/Player/MultiPlayerGameMode.cpp @@ -13,9 +13,9 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.inventory.h" #include "../../Minecraft.World/Headers/net.minecraft.h" -MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection) -{ - // 4J - added initialisers +MultiPlayerGameMode::MultiPlayerGameMode(Minecraft* minecraft, + ClientConnection* connection) { + // 4J - added initialisers xDestroyBlock = -1; yDestroyBlock = -1; zDestroyBlock = -1; @@ -24,112 +24,102 @@ MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection destroyTicks = 0; destroyDelay = 0; isDestroying = false; - carriedItem = 0; - localPlayerMode = GameType::SURVIVAL; - this->minecraft = minecraft; - this->connection = connection; + carriedItem = 0; + localPlayerMode = GameType::SURVIVAL; + this->minecraft = minecraft; + this->connection = connection; } -void MultiPlayerGameMode::creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face) -{ - if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) - { - gameMode->destroyBlock(x, y, z, face); - } +void MultiPlayerGameMode::creativeDestroyBlock(Minecraft* minecraft, + MultiPlayerGameMode* gameMode, + int x, int y, int z, int face) { + if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) { + gameMode->destroyBlock(x, y, z, face); + } } -void MultiPlayerGameMode::adjustPlayer(std::shared_ptr player) -{ - localPlayerMode->updatePlayerAbilities(&player->abilities); +void MultiPlayerGameMode::adjustPlayer(std::shared_ptr player) { + localPlayerMode->updatePlayerAbilities(&player->abilities); } -bool MultiPlayerGameMode::isCutScene() -{ - return false; +bool MultiPlayerGameMode::isCutScene() { return false; } + +void MultiPlayerGameMode::setLocalMode(GameType* mode) { + localPlayerMode = mode; + localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities); } -void MultiPlayerGameMode::setLocalMode(GameType *mode) -{ - localPlayerMode = mode; - localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities); +void MultiPlayerGameMode::initPlayer(std::shared_ptr player) { + player->yRot = -180; } -void MultiPlayerGameMode::initPlayer(std::shared_ptr player) -{ - player->yRot = -180; +bool MultiPlayerGameMode::canHurtPlayer() { + return localPlayerMode->isSurvival(); } -bool MultiPlayerGameMode::canHurtPlayer() -{ - return localPlayerMode->isSurvival(); -} +bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) { + if (localPlayerMode->isReadOnly()) { + return false; + } -bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) -{ - if (localPlayerMode->isReadOnly()) - { - return false; - } + Level* level = minecraft->level; + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; - Level *level = minecraft->level; - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; + if (oldTile == NULL) return false; - if (oldTile == NULL) return false; + level->levelEvent( + LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + int data = level->getData(x, y, z); + bool changed = level->setTile(x, y, z, 0); + if (changed) { + oldTile->destroy(level, x, y, z, data); + } - int data = level->getData(x, y, z); - bool changed = level->setTile(x, y, z, 0); - if (changed) - { - oldTile->destroy(level, x, y, z, data); - } - - if (!localPlayerMode->isCreative()) - { - std::shared_ptr item = minecraft->player->getSelectedItem(); - if (item != NULL) - { - item->mineBlock(level, oldTile->id, x, y, z, minecraft->player); - if (item->count == 0) - { - minecraft->player->removeSelectedItem(); - } - } - } + if (!localPlayerMode->isCreative()) { + std::shared_ptr item = + minecraft->player->getSelectedItem(); + if (item != NULL) { + item->mineBlock(level, oldTile->id, x, y, z, minecraft->player); + if (item->count == 0) { + minecraft->player->removeSelectedItem(); + } + } + } return changed; } -void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) -{ - if(!minecraft->player->isAllowedToMine()) return; - if (localPlayerMode->isReadOnly()) - { - return; - } +void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->isAllowedToMine()) return; + if (localPlayerMode->isReadOnly()) { + return; + } - if (localPlayerMode->isCreative()) - { - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) )); - creativeDestroyBlock(minecraft, this, x, y, z, face); - destroyDelay = 5; - } - else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock || z != zDestroyBlock) - { - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); + if (localPlayerMode->isCreative()) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); + creativeDestroyBlock(minecraft, this, x, y, z, face); + destroyDelay = 5; + } else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock || + z != zDestroyBlock) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); int t = minecraft->level->getTile(x, y, z); - if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); + if (t > 0 && destroyProgress == 0) + Tile::tiles[t]->attack(minecraft->level, x, y, z, + minecraft->player); if (t > 0 && - (Tile::tiles[t]->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z) >= 1 || - (app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getDestroyProgress( + minecraft->player, minecraft->player->level, x, y, z) >= 1 || + (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_InstantDestroy)))) { destroyBlock(x, y, z, face); - } - else - { + } else { isDestroying = true; xDestroyBlock = x; yDestroyBlock = y; @@ -137,342 +127,351 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); + minecraft->level->destroyTileProgress( + minecraft->player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, (int)(destroyProgress * 10) - 1); } } - } -void MultiPlayerGameMode::stopDestroyBlock() -{ - if (isDestroying) - { - connection->send(std::shared_ptr(new PlayerActionPacket(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1))); - } +void MultiPlayerGameMode::stopDestroyBlock() { + if (isDestroying) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, + yDestroyBlock, zDestroyBlock, -1))); + } - isDestroying = false; - destroyProgress = 0; - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); + isDestroying = false; + destroyProgress = 0; + minecraft->level->destroyTileProgress(minecraft->player->entityId, + xDestroyBlock, yDestroyBlock, + zDestroyBlock, -1); } -void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if(!minecraft->player->isAllowedToMine()) return; +void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->isAllowedToMine()) return; ensureHasSentCarriedItem(); -// connection.send(new PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x, y, z, face)); + // connection.send(new + // PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x, + // y, z, face)); - if (destroyDelay > 0) - { + if (destroyDelay > 0) { destroyDelay--; return; } - if (localPlayerMode->isCreative()) - { - destroyDelay = 5; - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); - creativeDestroyBlock(minecraft, this, x, y, z, face); - return; - } + if (localPlayerMode->isCreative()) { + destroyDelay = 5; + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); + creativeDestroyBlock(minecraft, this, x, y, z, face); + return; + } - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { int t = minecraft->level->getTile(x, y, z); - if (t == 0) - { + if (t == 0) { isDestroying = false; return; } - Tile *tile = Tile::tiles[t]; + Tile* tile = Tile::tiles[t]; - destroyProgress += tile->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z); + destroyProgress += tile->getDestroyProgress( + minecraft->player, minecraft->player->level, x, y, z); - if (destroyTicks % 4 == 0) - { - if (tile != NULL) - { - int iStepSound=tile->soundType->getStepSound(); + if (destroyTicks % 4 == 0) { + if (tile != NULL) { + int iStepSound = tile->soundType->getStepSound(); - minecraft->soundEngine->play(iStepSound, x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); + minecraft->soundEngine->play( + iStepSound, x + 0.5f, y + 0.5f, z + 0.5f, + (tile->soundType->getVolume() + 1) / 8, + tile->soundType->getPitch() * 0.5f); } } destroyTicks++; - if (destroyProgress >= 1) - { + if (destroyProgress >= 1) { isDestroying = false; - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face) ) ); - destroyBlock(x, y, z, face); + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face))); + destroyBlock(x, y, z, face); destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; destroyDelay = 5; } - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); - } - else - { + minecraft->level->destroyTileProgress( + minecraft->player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, (int)(destroyProgress * 10) - 1); + } else { startDestroyBlock(x, y, z, face); } - } -float MultiPlayerGameMode::getPickRange() -{ - if (localPlayerMode->isCreative()) - { - return 5.0f; - } - return 4.5f; +float MultiPlayerGameMode::getPickRange() { + if (localPlayerMode->isCreative()) { + return 5.0f; + } + return 4.5f; } -void MultiPlayerGameMode::tick() -{ +void MultiPlayerGameMode::tick() { ensureHasSentCarriedItem(); oDestroyProgress = destroyProgress; - //minecraft->soundEngine->playMusicTick(); + // minecraft->soundEngine->playMusicTick(); } -void MultiPlayerGameMode::ensureHasSentCarriedItem() -{ +void MultiPlayerGameMode::ensureHasSentCarriedItem() { int newItem = minecraft->player->inventory->selected; - if (newItem != carriedItem) - { + if (newItem != carriedItem) { carriedItem = newItem; - connection->send( std::shared_ptr( new SetCarriedItemPacket(carriedItem) ) ); + connection->send(std::shared_ptr( + new SetCarriedItemPacket(carriedItem))); } } -bool MultiPlayerGameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly, bool *pbUsedItem) -{ - if( pbUsedItem ) *pbUsedItem = false; // Did we actually use the held item? +bool MultiPlayerGameMode::useItemOn(std::shared_ptr player, + Level* level, + std::shared_ptr item, int x, + int y, int z, int face, Vec3* hit, + bool bTestUseOnly, bool* pbUsedItem) { + if (pbUsedItem) *pbUsedItem = false; // Did we actually use the held item? - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(!bTestUseOnly) - { - ensureHasSentCarriedItem(); - } - float clickX = (float) hit->x - x; - float clickY = (float) hit->y - y; - float clickZ = (float) hit->z - z; - bool didSomething = false; - int t = level->getTile(x, y, z); - - if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) - { - if(bTestUseOnly) - { - switch(t) - { - case Tile::recordPlayer_Id: - case Tile::bed_Id: // special case for a bed - if (Tile::tiles[t]->TestUse(level, x, y, z, player )) - { - return true; - } - else if (t==Tile::bed_Id) // 4J-JEV: You can still use items on record players (ie. set fire to them). - { - // bed is too far away, or something - return false; - } - break; - default: - if (Tile::tiles[t]->TestUse()) return true; - break; - } - } - else - { - if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) didSomething = true; - } - } + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (!bTestUseOnly) { + ensureHasSentCarriedItem(); + } + float clickX = (float)hit->x - x; + float clickY = (float)hit->y - y; + float clickZ = (float)hit->z - z; + bool didSomething = false; + int t = level->getTile(x, y, z); - if (!didSomething && item != NULL && dynamic_cast(item->getItem())) - { - TileItem *tile = dynamic_cast(item->getItem()); - if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; - } + if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) { + if (bTestUseOnly) { + switch (t) { + case Tile::recordPlayer_Id: + case Tile::bed_Id: // special case for a bed + if (Tile::tiles[t]->TestUse(level, x, y, z, player)) { + return true; + } else if (t == Tile::bed_Id) // 4J-JEV: You can still use + // items on record players + // (ie. set fire to them). + { + // bed is too far away, or something + return false; + } + break; + default: + if (Tile::tiles[t]->TestUse()) return true; + break; + } + } else { + if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, + clickY, clickZ)) + didSomething = true; + } + } - // 4J Stu - In Java we send the use packet before the above check for item being NULL - // so the following never gets executed but the packet still gets sent (for opening chests etc) - if(item != NULL) - { - if(!didSomething && player->isAllowedToUse(item)) - { - if (localPlayerMode->isCreative()) - { - int aux = item->getAuxValue(); - int count = item->count; - didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly); - item->setAuxValue(aux); - item->count = count; - } - else - { - didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly); - } - if( didSomething ) - { - if( pbUsedItem ) *pbUsedItem = true; - } - } - } - else - { - // 4J - Bit of a hack, however seems preferable to any larger changes which would have more chance of causing unwanted side effects. - // If we aren't going to be actually performing the use method locally, then call this method with its "soundOnly" parameter set to true. - // This is an addition from the java version, and as its name suggests, doesn't actually perform the use locally but just makes any sounds that - // are meant to be directly caused by this. If we don't do this, then the sounds never happen as the tile's use method is only called on the - // server, and that won't allow any sounds that are directly made, or broadcast back level events to us that would make the sound, since we are - // the source of the event. - if( ( t > 0 ) && ( !bTestUseOnly ) && player->isAllowedToUse(Tile::tiles[t]) ) - { - Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ, true); - } - } + if (!didSomething && item != NULL && + dynamic_cast(item->getItem())) { + TileItem* tile = dynamic_cast(item->getItem()); + if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; + } - // 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server - // doesn't think it has to update us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - if(!bTestUseOnly) - { - connection->send( std::shared_ptr( new UseItemPacket(x, y, z, face, player->inventory->getSelected(), clickX, clickY, clickZ) ) ); - } + // 4J Stu - In Java we send the use packet before the above check for item + // being NULL so the following never gets executed but the packet still gets + // sent (for opening chests etc) + if (item != NULL) { + if (!didSomething && player->isAllowedToUse(item)) { + if (localPlayerMode->isCreative()) { + int aux = item->getAuxValue(); + int count = item->count; + didSomething = item->useOn(player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnly); + item->setAuxValue(aux); + item->count = count; + } else { + didSomething = item->useOn(player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnly); + } + if (didSomething) { + if (pbUsedItem) *pbUsedItem = true; + } + } + } else { + // 4J - Bit of a hack, however seems preferable to any larger changes + // which would have more chance of causing unwanted side effects. If we + // aren't going to be actually performing the use method locally, then + // call this method with its "soundOnly" parameter set to true. This is + // an addition from the java version, and as its name suggests, doesn't + // actually perform the use locally but just makes any sounds that are + // meant to be directly caused by this. If we don't do this, then the + // sounds never happen as the tile's use method is only called on the + // server, and that won't allow any sounds that are directly made, or + // broadcast back level events to us that would make the sound, since we + // are the source of the event. + if ((t > 0) && (!bTestUseOnly) && + player->isAllowedToUse(Tile::tiles[t])) { + Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, + clickZ, true); + } + } + + // 4J Stu - Do the action before we send the packet, so that our predicted + // count is sent in the packet and the server doesn't think it has to update + // us Fix for #7904 - Gameplay: Players can dupe torches by throwing them + // repeatedly into water. + if (!bTestUseOnly) { + connection->send(std::shared_ptr( + new UseItemPacket(x, y, z, face, player->inventory->getSelected(), + clickX, clickY, clickZ))); + } return didSomething; } -bool MultiPlayerGameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - if(!player->isAllowedToUse(item)) return false; +bool MultiPlayerGameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly) { + if (!player->isAllowedToUse(item)) return false; - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(!bTestUseOnly) - { - ensureHasSentCarriedItem(); - } + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (!bTestUseOnly) { + ensureHasSentCarriedItem(); + } - // 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server - // doesn't think it has to update us, or can update us if we are wrong - // Fix for #13120 - Using a bucket of water or lava in the spawn area (centre of the map) causes the inventory to get out of sync + // 4J Stu - Do the action before we send the packet, so that our predicted + // count is sent in the packet and the server doesn't think it has to update + // us, or can update us if we are wrong Fix for #13120 - Using a bucket of + // water or lava in the spawn area (centre of the map) causes the inventory + // to get out of sync bool result = false; - - // 4J-PB added for tooltips to test use only - if(bTestUseOnly) - { - result = item->TestUse(level, player); - } - else - { - int oldCount = item->count; - std::shared_ptr itemInstance = item->use(level, player); - if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount)) - { - player->inventory->items[player->inventory->selected] = itemInstance; - if (itemInstance->count == 0) - { - player->inventory->items[player->inventory->selected] = nullptr; - } - result = true; - } - } - - if(!bTestUseOnly) - { - connection->send( std::shared_ptr( new UseItemPacket(-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0) ) ); - } + + // 4J-PB added for tooltips to test use only + if (bTestUseOnly) { + result = item->TestUse(level, player); + } else { + int oldCount = item->count; + std::shared_ptr itemInstance = item->use(level, player); + if ((itemInstance != NULL && itemInstance != item) || + (itemInstance != NULL && itemInstance->count != oldCount)) { + player->inventory->items[player->inventory->selected] = + itemInstance; + if (itemInstance->count == 0) { + player->inventory->items[player->inventory->selected] = nullptr; + } + result = true; + } + } + + if (!bTestUseOnly) { + connection->send(std::shared_ptr(new UseItemPacket( + -1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0))); + } return result; } -std::shared_ptr MultiPlayerGameMode::createPlayer(Level *level) -{ - return std::shared_ptr( new MultiplayerLocalPlayer(minecraft, level, minecraft->user, connection) ); +std::shared_ptr MultiPlayerGameMode::createPlayer( + Level* level) { + return std::shared_ptr(new MultiplayerLocalPlayer( + minecraft, level, minecraft->user, connection)); } -void MultiPlayerGameMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ +void MultiPlayerGameMode::attack(std::shared_ptr player, + std::shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send( std::shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::ATTACK) ) ); + connection->send(std::shared_ptr(new InteractPacket( + player->entityId, entity->entityId, InteractPacket::ATTACK))); player->attack(entity); } -bool MultiPlayerGameMode::interact(std::shared_ptr player, std::shared_ptr entity) -{ +bool MultiPlayerGameMode::interact(std::shared_ptr player, + std::shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send(std::shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::INTERACT) ) ); + connection->send(std::shared_ptr(new InteractPacket( + player->entityId, entity->entityId, InteractPacket::INTERACT))); return player->interact(entity); } -std::shared_ptr MultiPlayerGameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player) -{ +std::shared_ptr MultiPlayerGameMode::handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player) { short changeUid = player->containerMenu->backup(player->inventory); - std::shared_ptr clicked = player->containerMenu->clicked(slotNum, buttonNum, quickKeyHeld?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); - connection->send( std::shared_ptr( new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, clicked, changeUid) ) ); + std::shared_ptr clicked = player->containerMenu->clicked( + slotNum, buttonNum, + quickKeyHeld ? AbstractContainerMenu::CLICK_QUICK_MOVE + : AbstractContainerMenu::CLICK_PICKUP, + player); + connection->send(std::shared_ptr( + new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, + clicked, changeUid))); return clicked; } -void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, int buttonId) -{ - connection->send(std::shared_ptr( new ContainerButtonClickPacket(containerId, buttonId) )); +void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, + int buttonId) { + connection->send(std::shared_ptr( + new ContainerButtonClickPacket(containerId, buttonId))); } -void MultiPlayerGameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, int slot) -{ - if (localPlayerMode->isCreative()) - { - connection->send(std::shared_ptr( new SetCreativeModeSlotPacket(slot, clicked) ) ); - } +void MultiPlayerGameMode::handleCreativeModeItemAdd( + std::shared_ptr clicked, int slot) { + if (localPlayerMode->isCreative()) { + connection->send(std::shared_ptr( + new SetCreativeModeSlotPacket(slot, clicked))); + } } -void MultiPlayerGameMode::handleCreativeModeItemDrop(std::shared_ptr clicked) -{ - if (localPlayerMode->isCreative() && clicked != NULL) - { - connection->send(std::shared_ptr( new SetCreativeModeSlotPacket(-1, clicked) ) ); - } +void MultiPlayerGameMode::handleCreativeModeItemDrop( + std::shared_ptr clicked) { + if (localPlayerMode->isCreative() && clicked != NULL) { + connection->send(std::shared_ptr( + new SetCreativeModeSlotPacket(-1, clicked))); + } } -void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr player) -{ - ensureHasSentCarriedItem(); - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255) ) ); - player->releaseUsingItem(); +void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr player) { + ensureHasSentCarriedItem(); + connection->send(std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255))); + player->releaseUsingItem(); } -bool MultiPlayerGameMode::hasExperience() -{ - return true; +bool MultiPlayerGameMode::hasExperience() { return true; } + +bool MultiPlayerGameMode::hasMissTime() { + return !localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasMissTime() -{ - return !localPlayerMode->isCreative(); +bool MultiPlayerGameMode::hasInfiniteItems() { + return localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasInfiniteItems() -{ - return localPlayerMode->isCreative(); +bool MultiPlayerGameMode::hasFarPickRange() { + return localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasFarPickRange() -{ - return localPlayerMode->isCreative(); -} - -bool MultiPlayerGameMode::handleCraftItem(int recipe, std::shared_ptr player) -{ +bool MultiPlayerGameMode::handleCraftItem(int recipe, + std::shared_ptr player) { short changeUid = player->containerMenu->backup(player->inventory); - connection->send( std::shared_ptr( new CraftItemPacket(recipe, changeUid) ) ); + connection->send(std::shared_ptr( + new CraftItemPacket(recipe, changeUid))); return true; } -void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr player) -{ - player->SetDebugOptions(uiVal); - connection->send( std::shared_ptr( new DebugOptionsPacket(uiVal) ) ); +void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, + std::shared_ptr player) { + player->SetDebugOptions(uiVal); + connection->send( + std::shared_ptr(new DebugOptionsPacket(uiVal))); } diff --git a/Minecraft.Client/Player/MultiPlayerGameMode.h b/Minecraft.Client/Player/MultiPlayerGameMode.h index 34396aebd..d136461c6 100644 --- a/Minecraft.Client/Player/MultiPlayerGameMode.h +++ b/Minecraft.Client/Player/MultiPlayerGameMode.h @@ -4,65 +4,80 @@ class ClientConnection; class GameType; class Vec3; -class MultiPlayerGameMode -{ +class MultiPlayerGameMode { private: - int xDestroyBlock; + int xDestroyBlock; int yDestroyBlock; int zDestroyBlock; float destroyProgress; float oDestroyProgress; - int destroyTicks; // 4J was float but doesn't seem to need to be + int destroyTicks; // 4J was float but doesn't seem to need to be int destroyDelay; bool isDestroying; - GameType *localPlayerMode; - ClientConnection *connection; + GameType* localPlayerMode; + ClientConnection* connection; protected: - Minecraft *minecraft; + Minecraft* minecraft; public: - MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection); - virtual ~MultiPlayerGameMode(){} - static void creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face); - void adjustPlayer(std::shared_ptr player); - bool isCutScene(); - void setLocalMode(GameType *mode); + MultiPlayerGameMode(Minecraft* minecraft, ClientConnection* connection); + virtual ~MultiPlayerGameMode() {} + static void creativeDestroyBlock(Minecraft* minecraft, + MultiPlayerGameMode* gameMode, int x, + int y, int z, int face); + void adjustPlayer(std::shared_ptr player); + bool isCutScene(); + void setLocalMode(GameType* mode); virtual void initPlayer(std::shared_ptr player); - virtual bool canHurtPlayer(); + virtual bool canHurtPlayer(); virtual bool destroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face); virtual void stopDestroyBlock(); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual float getPickRange(); virtual void tick(); -private: - int carriedItem; private: - void ensureHasSentCarriedItem(); + int carriedItem; + +private: + void ensureHasSentCarriedItem(); + public: - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=NULL); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - virtual std::shared_ptr createPlayer(Level *level); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); - virtual bool interact(std::shared_ptr player, std::shared_ptr entity); - virtual std::shared_ptr handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player); - virtual void handleInventoryButtonClick(int containerId, int buttonId); - virtual void handleCreativeModeItemAdd(std::shared_ptr clicked, int slot); - virtual void handleCreativeModeItemDrop(std::shared_ptr clicked); - virtual void releaseUsingItem(std::shared_ptr player); - virtual bool hasExperience(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); - - // 4J Stu - Added so we can send packets for this in the network game - virtual bool handleCraftItem(int recipe, std::shared_ptr player); - virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr player); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, Vec3* hit, + bool bTestUseOnly = false, bool* pbUsedItem = NULL); + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly = false); + virtual std::shared_ptr createPlayer(Level* level); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); + virtual bool interact(std::shared_ptr player, + std::shared_ptr entity); + virtual std::shared_ptr handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player); + virtual void handleInventoryButtonClick(int containerId, int buttonId); + virtual void handleCreativeModeItemAdd( + std::shared_ptr clicked, int slot); + virtual void handleCreativeModeItemDrop( + std::shared_ptr clicked); + virtual void releaseUsingItem(std::shared_ptr player); + virtual bool hasExperience(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); - // 4J Stu - Added for tutorial checks - virtual bool isInputAllowed(int mapping) { return true; } - virtual bool isTutorial() { return false; } - virtual Tutorial *getTutorial() { return NULL; } + // 4J Stu - Added so we can send packets for this in the network game + virtual bool handleCraftItem(int recipe, std::shared_ptr player); + virtual void handleDebugOptions(unsigned int uiVal, + std::shared_ptr player); + + // 4J Stu - Added for tutorial checks + virtual bool isInputAllowed(int mapping) { return true; } + virtual bool isTutorial() { return false; } + virtual Tutorial* getTutorial() { return NULL; } }; diff --git a/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp b/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp index 3b9a9e676..8b79bcadc 100644 --- a/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp +++ b/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp @@ -1,5 +1,5 @@ #include "../Platform/stdafx.h" -//#include "../../Minecraft.World/Util/JavaMath.h" +// #include "../../Minecraft.World/Util/JavaMath.h" #include "MultiPlayerLocalPlayer.h" #include "../Network/ClientConnection.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" @@ -13,91 +13,107 @@ #include "../../Minecraft.World/Level/LevelData.h" #include "../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" - - - -MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection) : LocalPlayer(minecraft, level, user, level->dimension->id) -{ - // 4J - added initialisers +MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft* minecraft, + Level* level, User* user, + ClientConnection* connection) + : LocalPlayer(minecraft, level, user, level->dimension->id) { + // 4J - added initialisers flashOnSetHealth = false; - xLast = yLast1 = yLast2 = zLast = 0; + xLast = yLast1 = yLast2 = zLast = 0; yRotLast = xRotLast = 0; - lastOnGround = false; + lastOnGround = false; lastSneaked = false; - lastIdle = false; - lastSprinting = false; + lastIdle = false; + lastSprinting = false; positionReminder = 0; this->connection = connection; } -bool MultiplayerLocalPlayer::hurt(DamageSource *source, int dmg) -{ - return false; +bool MultiplayerLocalPlayer::hurt(DamageSource* source, int dmg) { + return false; } -void MultiplayerLocalPlayer::heal(int heal) -{ -} +void MultiplayerLocalPlayer::heal(int heal) {} -void MultiplayerLocalPlayer::tick() -{ - // 4J Added - // 4J-PB - changing this to a game host option ot hide gamertags - //bool bIsisPrimaryHost=g_NetworkManager.IsHost() && (ProfileManager.GetPrimaryPad()==m_iPad); +void MultiplayerLocalPlayer::tick() { + // 4J Added + // 4J-PB - changing this to a game host option ot hide gamertags + // bool bIsisPrimaryHost=g_NetworkManager.IsHost() && + // (ProfileManager.GetPrimaryPad()==m_iPad); - /*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) != m_bShownOnMaps) - { - m_bShownOnMaps = (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); - if (m_bShownOnMaps) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) ) ); - }*/ + /*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) != + m_bShownOnMaps) + { + m_bShownOnMaps = + (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); if + (m_bShownOnMaps) connection->send( std::shared_ptr( new + PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) ) + ); else connection->send( std::shared_ptr( new + PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) ) + ); + }*/ - if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return; + if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return; - double tempX = x, tempY = y, tempZ = z; + double tempX = x, tempY = y, tempZ = z; LocalPlayer::tick(); - - //if( !minecraft->localgameModes[m_iPad]->isTutorial() || minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z) ) - if(minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z)) - { - sendPosition(); - } - else - { - //app.Debugprintf("Cannot move to position (%f, %f, %f), falling back to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ); - this->setPos(tempX, y, tempZ); - } + + // if( !minecraft->localgameModes[m_iPad]->isTutorial() || + // minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, + // tempY, tempZ, x, y, z) ) + if (minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition( + tempX, tempY, tempZ, x, y, z)) { + sendPosition(); + } else { + // app.Debugprintf("Cannot move to position (%f, %f, %f), falling back + // to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ); + this->setPos(tempX, y, tempZ); + } } -void MultiplayerLocalPlayer::sendPosition() -{ - bool sprinting = isSprinting(); - if (sprinting != lastSprinting) - { - if (sprinting) connection->send(std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SPRINTING))); - else connection->send(std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); +void MultiplayerLocalPlayer::sendPosition() { + bool sprinting = isSprinting(); + if (sprinting != lastSprinting) { + if (sprinting) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_SPRINTING))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); - lastSprinting = sprinting; - } + lastSprinting = sprinting; + } bool sneaking = isSneaking(); - if (sneaking != lastSneaked) - { - if (sneaking) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SNEAKING) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SNEAKING) ) ); + if (sneaking != lastSneaked) { + if (sneaking) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_SNEAKING))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SNEAKING))); lastSneaked = sneaking; } - bool idle = isIdle(); - if (idle != lastIdle) - { - if (idle) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_IDLEANIM) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM) ) ); + bool idle = isIdle(); + if (idle != lastIdle) { + if (idle) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_IDLEANIM))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM))); - lastIdle = idle; - } + lastIdle = idle; + } double xdd = x - xLast; double ydd1 = bb->y0 - yLast1; @@ -106,266 +122,244 @@ void MultiplayerLocalPlayer::sendPosition() double rydd = yRot - yRotLast; double rxdd = xRot - xRotLast; - bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || positionReminder >= POSITION_REMINDER_INTERVAL; + bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || + positionReminder >= POSITION_REMINDER_INTERVAL; bool rot = rydd != 0 || rxdd != 0; - if (riding != NULL) - { - connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying) ) ); + if (riding != NULL) { + connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying))); move = false; - } - else - { - if (move && rot) - { - connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying) ) ); - } - else if (move) - { - connection->send( std::shared_ptr( new MovePlayerPacket::Pos(x, bb->y0, y, z, onGround, abilities.flying) ) ); - } - else if (rot) - { - connection->send( std::shared_ptr( new MovePlayerPacket::Rot(yRot, xRot, onGround, abilities.flying) ) ); - } - else - { - connection->send( std::shared_ptr( new MovePlayerPacket(onGround, abilities.flying) ) ); + } else { + if (move && rot) { + connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying))); + } else if (move) { + connection->send( + std::shared_ptr(new MovePlayerPacket::Pos( + x, bb->y0, y, z, onGround, abilities.flying))); + } else if (rot) { + connection->send( + std::shared_ptr(new MovePlayerPacket::Rot( + yRot, xRot, onGround, abilities.flying))); + } else { + connection->send(std::shared_ptr( + new MovePlayerPacket(onGround, abilities.flying))); } } - positionReminder++; + positionReminder++; lastOnGround = onGround; - if (move) - { + if (move) { xLast = x; yLast1 = bb->y0; yLast2 = y; zLast = z; - positionReminder = 0; + positionReminder = 0; } - if (rot) - { + if (rot) { yRotLast = yRot; xRotLast = xRot; } - } -std::shared_ptr MultiplayerLocalPlayer::drop() -{ - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0) ) ); - return nullptr; +std::shared_ptr MultiplayerLocalPlayer::drop() { + connection->send(std::shared_ptr( + new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0))); + return nullptr; } -void MultiplayerLocalPlayer::reallyDrop(std::shared_ptr itemEntity) -{ +void MultiplayerLocalPlayer::reallyDrop( + std::shared_ptr itemEntity) {} + +void MultiplayerLocalPlayer::chat(const std::wstring& message) { + connection->send(std::shared_ptr(new ChatPacket(message))); } -void MultiplayerLocalPlayer::chat(const std::wstring& message) -{ - connection->send( std::shared_ptr( new ChatPacket(message) ) ); +void MultiplayerLocalPlayer::swing() { + LocalPlayer::swing(); + connection->send(std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::SWING))); } -void MultiplayerLocalPlayer::swing() -{ - LocalPlayer::swing(); - connection->send( std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) ); - +void MultiplayerLocalPlayer::respawn() { + connection->send(std::shared_ptr( + new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN))); } -void MultiplayerLocalPlayer::respawn() -{ - connection->send( std::shared_ptr( new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN))); -} - - -void MultiplayerLocalPlayer::actuallyHurt(DamageSource *source, int dmg) -{ - setHealth(getHealth() - dmg); +void MultiplayerLocalPlayer::actuallyHurt(DamageSource* source, int dmg) { + setHealth(getHealth() - dmg); } // 4J Added override to capture event for tutorial messages -void MultiplayerLocalPlayer::completeUsingItem() -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->completeUsingItem(useItem); - } - Player::completeUsingItem(); +void MultiplayerLocalPlayer::completeUsingItem() { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->completeUsingItem(useItem); + } + Player::completeUsingItem(); } -void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); - } - Player::onEffectAdded(effect); +void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); + } + Player::onEffectAdded(effect); } - -void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); - } - Player::onEffectUpdated(effect); +void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); + } + Player::onEffectUpdated(effect); } - -void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()],true); - } - Player::onEffectRemoved(effect); +void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()], true); + } + Player::onEffectRemoved(effect); } -void MultiplayerLocalPlayer::closeContainer() -{ - connection->send( std::shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); +void MultiplayerLocalPlayer::closeContainer() { + connection->send(std::shared_ptr( + new ContainerClosePacket(containerMenu->containerId))); inventory->setCarried(nullptr); LocalPlayer::closeContainer(); } -void MultiplayerLocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) -{ - if (flashOnSetHealth) - { - LocalPlayer::hurtTo(newHealth, damageSource); - } - else - { - setHealth(newHealth); - flashOnSetHealth = true; - } +void MultiplayerLocalPlayer::hurtTo(int newHealth, + ETelemetryChallenges damageSource) { + if (flashOnSetHealth) { + LocalPlayer::hurtTo(newHealth, damageSource); + } else { + setHealth(newHealth); + flashOnSetHealth = true; + } } -void MultiplayerLocalPlayer::awardStat(Stat *stat, byteArray param) -{ - if (stat == NULL) - { - delete [] param.data; +void MultiplayerLocalPlayer::awardStat(Stat* stat, byteArray param) { + if (stat == NULL) { + delete[] param.data; return; } - if (stat->awardLocallyOnly) - { - LocalPlayer::awardStat(stat, param); - } - else - { - delete [] param.data; + if (stat->awardLocallyOnly) { + LocalPlayer::awardStat(stat, param); + } else { + delete[] param.data; return; } } -void MultiplayerLocalPlayer::awardStatFromServer(Stat *stat, byteArray param) -{ - if ( stat != NULL && !stat->awardLocallyOnly ) - { - LocalPlayer::awardStat(stat, param); - } - else delete [] param.data; +void MultiplayerLocalPlayer::awardStatFromServer(Stat* stat, byteArray param) { + if (stat != NULL && !stat->awardLocallyOnly) { + LocalPlayer::awardStat(stat, param); + } else + delete[] param.data; } -void MultiplayerLocalPlayer::onUpdateAbilities() -{ - connection->send(std::shared_ptr(new PlayerAbilitiesPacket(&abilities))); +void MultiplayerLocalPlayer::onUpdateAbilities() { + connection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&abilities))); } -bool MultiplayerLocalPlayer::isLocalPlayer() -{ - return true; +bool MultiplayerLocalPlayer::isLocalPlayer() { return true; } + +void MultiplayerLocalPlayer::ride(std::shared_ptr e) { + bool wasRiding = riding != NULL; + LocalPlayer::ride(e); + bool isRiding = riding != NULL; + + if (isRiding) { + ETelemetryChallenges eventType = eTelemetryChallenges_Unknown; + if (this->riding != NULL) { + switch (riding->GetType()) { + case eTYPE_BOAT: + eventType = eTelemetryInGame_Ride_Boat; + break; + case eTYPE_MINECART: + eventType = eTelemetryInGame_Ride_Minecart; + break; + case eTYPE_PIG: + eventType = eTelemetryInGame_Ride_Pig; + break; + default: + break; + }; + } + TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0, + 0, 0, eventType); + } + + updateRichPresence(); + + Minecraft* pMinecraft = Minecraft::GetInstance(); + + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + if (wasRiding && !isRiding) { + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Gameplay); + } else if (!wasRiding && isRiding) { + if (std::dynamic_pointer_cast(e) != NULL) + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Riding_Minecart); + else if (std::dynamic_pointer_cast(e) != NULL) + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Riding_Boat); + } + } } -void MultiplayerLocalPlayer::ride(std::shared_ptr e) -{ - bool wasRiding = riding != NULL; - LocalPlayer::ride(e); - bool isRiding = riding != NULL; - - if( isRiding ) - { - ETelemetryChallenges eventType = eTelemetryChallenges_Unknown; - if( this->riding != NULL ) - { - switch(riding->GetType()) - { - case eTYPE_BOAT: - eventType = eTelemetryInGame_Ride_Boat; - break; - case eTYPE_MINECART: - eventType = eTelemetryInGame_Ride_Minecart; - break; - case eTYPE_PIG: - eventType = eTelemetryInGame_Ride_Pig; - break; - default: - break; - }; - } - TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0, 0, 0, eventType); - } - - updateRichPresence(); - - Minecraft *pMinecraft = Minecraft::GetInstance(); - - if( pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(wasRiding && !isRiding) - { - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Gameplay); - } - else if (!wasRiding && isRiding) - { - if(std::dynamic_pointer_cast(e) != NULL) - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Minecart); - else if(std::dynamic_pointer_cast(e) != NULL) - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Boat); - } - } -} - -void MultiplayerLocalPlayer::StopSleeping() -{ - connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SLEEPING) ) ); +void MultiplayerLocalPlayer::StopSleeping() { + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SLEEPING))); } // 4J Added -void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) -{ - std::uint32_t oldSkinIndex = getCustomSkin(); - LocalPlayer::setCustomSkin(skinId); +void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) { + std::uint32_t oldSkinIndex = getCustomSkin(); + LocalPlayer::setCustomSkin(skinId); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin() ); + wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", + name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin()); #endif - if(getCustomSkin() != oldSkinIndex) connection->send( std::shared_ptr( new TextureAndGeometryChangePacket( shared_from_this(), app.GetPlayerSkinName(GetXboxPad()) ) ) ); + if (getCustomSkin() != oldSkinIndex) + connection->send(std::shared_ptr( + new TextureAndGeometryChangePacket( + shared_from_this(), app.GetPlayerSkinName(GetXboxPad())))); } -void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) -{ - std::uint32_t oldCapeIndex = getCustomCape(); - LocalPlayer::setCustomCape(capeId); +void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) { + std::uint32_t oldCapeIndex = getCustomCape(); + LocalPlayer::setCustomCape(capeId); #ifndef _CONTENT_PACKAGE - wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), customTextureUrl2.c_str()); + wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), + customTextureUrl2.c_str()); #endif - if(getCustomCape() != oldCapeIndex) connection->send( std::shared_ptr( new TextureChangePacket( shared_from_this(), TextureChangePacket::e_TextureChange_Cape, app.GetPlayerCapeName(GetXboxPad()) ) ) ); + if (getCustomCape() != oldCapeIndex) + connection->send( + std::shared_ptr(new TextureChangePacket( + shared_from_this(), TextureChangePacket::e_TextureChange_Cape, + app.GetPlayerCapeName(GetXboxPad())))); } diff --git a/Minecraft.Client/Player/MultiPlayerLocalPlayer.h b/Minecraft.Client/Player/MultiPlayerLocalPlayer.h index ea66686c0..b865dd566 100644 --- a/Minecraft.Client/Player/MultiPlayerLocalPlayer.h +++ b/Minecraft.Client/Player/MultiPlayerLocalPlayer.h @@ -7,68 +7,80 @@ class ClientConnection; class Minecraft; class Level; -class MultiplayerLocalPlayer : public LocalPlayer -{ +class MultiplayerLocalPlayer : public LocalPlayer { private: - static const int POSITION_REMINDER_INTERVAL = SharedConstants::TICKS_PER_SECOND; + static const int POSITION_REMINDER_INTERVAL = + SharedConstants::TICKS_PER_SECOND; + public: - ClientConnection *connection; + ClientConnection* connection; + private: bool flashOnSetHealth; + public: - MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection); + MultiplayerLocalPlayer(Minecraft* minecraft, Level* level, User* user, + ClientConnection* connection); + private: - double xLast, yLast1, yLast2, zLast; + double xLast, yLast1, yLast2, zLast; float yRotLast, xRotLast; + public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); virtual void heal(int heal); virtual void tick(); -private: - bool lastOnGround; - bool lastSneaked; - bool lastIdle; - bool lastSprinting; - int positionReminder; -public: - void sendPosition(); - using Player::drop; - virtual std::shared_ptr drop(); -protected: - virtual void reallyDrop(std::shared_ptr itemEntity); +private: + bool lastOnGround; + bool lastSneaked; + bool lastIdle; + bool lastSprinting; + int positionReminder; + public: - virtual void chat(const std::wstring& message); + void sendPosition(); + + using Player::drop; + virtual std::shared_ptr drop(); + +protected: + virtual void reallyDrop(std::shared_ptr itemEntity); + +public: + virtual void chat(const std::wstring& message); virtual void swing(); virtual void respawn(); + protected: - virtual void actuallyHurt(DamageSource *source, int dmg); + virtual void actuallyHurt(DamageSource* source, int dmg); - // 4J Added override to capture event for tutorial messages - virtual void completeUsingItem(); + // 4J Added override to capture event for tutorial messages + virtual void completeUsingItem(); + + // 4J Added overrides to capture events for tutorial + virtual void onEffectAdded(MobEffectInstance* effect); + virtual void onEffectUpdated(MobEffectInstance* effect); + virtual void onEffectRemoved(MobEffectInstance* effect); - // 4J Added overrides to capture events for tutorial - virtual void onEffectAdded(MobEffectInstance *effect); - virtual void onEffectUpdated(MobEffectInstance *effect); - virtual void onEffectRemoved(MobEffectInstance *effect); public: - virtual void closeContainer(); + virtual void closeContainer(); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); - virtual void awardStat(Stat *stat, byteArray param); - void awardStatFromServer(Stat *stat, byteArray param); - void onUpdateAbilities(); - bool isLocalPlayer(); + virtual void awardStat(Stat* stat, byteArray param); + void awardStatFromServer(Stat* stat, byteArray param); + void onUpdateAbilities(); + bool isLocalPlayer(); - // 4J - send the custom skin texture data if there is one - //void CustomSkin(PBYTE pbData, DWORD dwBytes); + // 4J - send the custom skin texture data if there is one + // void CustomSkin(PBYTE pbData, DWORD dwBytes); - // 4J Overriding this so we can flag an event for the tutorial - virtual void ride(std::shared_ptr e); + // 4J Overriding this so we can flag an event for the tutorial + virtual void ride(std::shared_ptr e); - // 4J - added for the Stop Sleeping - virtual void StopSleeping(); + // 4J - added for the Stop Sleeping + virtual void StopSleeping(); - // 4J Added - virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); - virtual void setAndBroadcastCustomCape(std::uint32_t capeId); + // 4J Added + virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); + virtual void setAndBroadcastCustomCape(std::uint32_t capeId); }; diff --git a/Minecraft.Client/Player/RemotePlayer.cpp b/Minecraft.Client/Player/RemotePlayer.cpp index 5e554cbab..cd81b5743 100644 --- a/Minecraft.Client/Player/RemotePlayer.cpp +++ b/Minecraft.Client/Player/RemotePlayer.cpp @@ -3,45 +3,39 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../Minecraft.World/Util/Mth.h" -RemotePlayer::RemotePlayer(Level *level, const std::wstring& name) : Player(level) -{ - // 4J - added initialisers - hasStartedUsingItem = false; - lSteps = 0; - lx = ly = lz = lyr = lxr = 0.0; - fallTime = 0.0f; +RemotePlayer::RemotePlayer(Level* level, const std::wstring& name) + : Player(level) { + // 4J - added initialisers + hasStartedUsingItem = false; + lSteps = 0; + lx = ly = lz = lyr = lxr = 0.0; + fallTime = 0.0f; this->name = name; - m_UUID = name; - app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str() ); + m_UUID = name; + app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str()); heightOffset = 0; this->footSize = 0; - if (name.length() > 0) - { - customTextureUrl = L"";//L"http://s3.amazonaws.com/MinecraftSkins/" + name + L".png"; + if (name.length() > 0) { + customTextureUrl = L""; // L"http://s3.amazonaws.com/MinecraftSkins/" + + // name + L".png"; } - this->noPhysics = true; + this->noPhysics = true; bedOffsetY = 4 / 16.0f; this->viewScale = 10; } -void RemotePlayer::setDefaultHeadHeight() -{ - heightOffset = 0; -} +void RemotePlayer::setDefaultHeadHeight() { heightOffset = 0; } -bool RemotePlayer::hurt(DamageSource *source, int dmg) -{ - return true; -} +bool RemotePlayer::hurt(DamageSource* source, int dmg) { return true; } -void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ -// heightOffset = 0; +void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + // heightOffset = 0; lx = x; ly = y; lz = z; @@ -51,8 +45,7 @@ void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, lSteps = steps; } -void RemotePlayer::tick() -{ +void RemotePlayer::tick() { bedOffsetY = 0 / 16.0f; Player::tick(); @@ -64,50 +57,43 @@ void RemotePlayer::tick() walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; walkAnimPos += walkAnimSpeed; - if (!hasStartedUsingItem && isUsingItemFlag() && inventory->items[inventory->selected] != NULL) - { - std::shared_ptr item = inventory->items[inventory->selected]; - startUsingItem(inventory->items[inventory->selected], Item::items[item->id]->getUseDuration(item)); - hasStartedUsingItem = true; - } - else if (hasStartedUsingItem && !isUsingItemFlag()) - { - stopUsingItem(); - hasStartedUsingItem = false; - } + if (!hasStartedUsingItem && isUsingItemFlag() && + inventory->items[inventory->selected] != NULL) { + std::shared_ptr item = + inventory->items[inventory->selected]; + startUsingItem(inventory->items[inventory->selected], + Item::items[item->id]->getUseDuration(item)); + hasStartedUsingItem = true; + } else if (hasStartedUsingItem && !isUsingItemFlag()) { + stopUsingItem(); + hasStartedUsingItem = false; + } - // if (eatItem != null) { - // if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) { - // spawnEatParticles(eatItem, 5); - // } - // eatItemTickCount--; - // if (eatItemTickCount <= 0) { - // spawnEatParticles(eatItem, 16); - // swing(); - // eatItem = null; - // } - // } + // if (eatItem != null) { + // if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) { + // spawnEatParticles(eatItem, 5); + // } + // eatItemTickCount--; + // if (eatItemTickCount <= 0) { + // spawnEatParticles(eatItem, 16); + // swing(); + // eatItem = null; + // } + // } } -float RemotePlayer::getShadowHeightOffs() -{ - return 0; -} +float RemotePlayer::getShadowHeightOffs() { return 0; } -void RemotePlayer::aiStep() -{ +void RemotePlayer::aiStep() { Player::serverAiStep(); - if (lSteps > 0) - { + if (lSteps > 0) { double xt = x + (lx - x) / lSteps; double yt = y + (ly - y) / lSteps; double zt = z + (lz - z) / lSteps; double yrd = lyr - yRot; - while (yrd < -180) - yrd += 360; - while (yrd >= 180) - yrd -= 360; + while (yrd < -180) yrd += 360; + while (yrd >= 180) yrd -= 360; yRot += (float)((yrd) / lSteps); xRot += (float)((lxr - xRot) / lSteps); @@ -118,35 +104,29 @@ void RemotePlayer::aiStep() } oBob = bob; - float tBob = (float) Mth::sqrt(xd * xd + zd * zd); - float tTilt = (float) atan(-yd * 0.2f) * 15.0f; + float tBob = (float)Mth::sqrt(xd * xd + zd * zd); + float tTilt = (float)atan(-yd * 0.2f) * 15.0f; if (tBob > 0.1f) tBob = 0.1f; if (!onGround || getHealth() <= 0) tBob = 0; if (onGround || getHealth() <= 0) tTilt = 0; bob += (tBob - bob) * 0.4f; tilt += (tTilt - tilt) * 0.8f; - } -// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game -void RemotePlayer::setEquippedSlot(int slot, std::shared_ptr item) -{ - if (slot == 0) - { +// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer +// Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for +// other players in online game +void RemotePlayer::setEquippedSlot(int slot, + std::shared_ptr item) { + if (slot == 0) { inventory->items[inventory->selected] = item; - } - else - { + } else { inventory->armor[slot - 1] = item; } } -void RemotePlayer::animateRespawn() -{ -// Player.animateRespawn(this, level); +void RemotePlayer::animateRespawn() { + // Player.animateRespawn(this, level); } -float RemotePlayer::getHeadHeight() -{ - return 1.82f; -} \ No newline at end of file +float RemotePlayer::getHeadHeight() { return 1.82f; } \ No newline at end of file diff --git a/Minecraft.Client/Player/RemotePlayer.h b/Minecraft.Client/Player/RemotePlayer.h index 7082a10c0..47ac32c21 100644 --- a/Minecraft.Client/Player/RemotePlayer.h +++ b/Minecraft.Client/Player/RemotePlayer.h @@ -4,30 +4,39 @@ class Input; -class RemotePlayer : public Player -{ +class RemotePlayer : public Player { private: - bool hasStartedUsingItem; + bool hasStartedUsingItem; + public: - Input *input; - RemotePlayer(Level *level, const std::wstring& name); + Input* input; + RemotePlayer(Level* level, const std::wstring& name); + protected: - virtual void setDefaultHeadHeight(); + virtual void setDefaultHeadHeight(); + public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); + private: - int lSteps; + int lSteps; double lx, ly, lz, lyr, lxr; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); float fallTime; virtual void tick(); virtual float getShadowHeightOffs(); virtual void aiStep(); - virtual void setEquippedSlot(int slot, std::shared_ptr item);// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game + virtual void setEquippedSlot( + int slot, std::shared_ptr + item); // 4J Stu - Brought forward change from 1.3 to fix + // #64688 - Customer Encountered: TU7: Content: + // Art: Aura of enchanted item is not displayed + // for other players in online game virtual void animateRespawn(); - virtual float getHeadHeight(); - bool hasPermission(EGameCommand command) { return false; } + virtual float getHeadHeight(); + bool hasPermission(EGameCommand command) { return false; } }; \ No newline at end of file diff --git a/Minecraft.Client/Player/ServerPlayer.cpp b/Minecraft.Client/Player/ServerPlayer.cpp index 5de88dafe..9de4edcfc 100644 --- a/Minecraft.Client/Player/ServerPlayer.cpp +++ b/Minecraft.Client/Player/ServerPlayer.cpp @@ -27,278 +27,266 @@ #include "../../Minecraft.World/Level/LevelChunk.h" #include "../Rendering/LevelRenderer.h" -ServerPlayer::ServerPlayer(MinecraftServer *server, Level *level, const std::wstring& name, ServerPlayerGameMode *gameMode) : Player(level) -{ - // 4J - added initialisers - connection = nullptr; +ServerPlayer::ServerPlayer(MinecraftServer* server, Level* level, + const std::wstring& name, + ServerPlayerGameMode* gameMode) + : Player(level) { + // 4J - added initialisers + connection = nullptr; lastMoveX = lastMoveZ = 0; spewTimer = 0; - lastSentHealth = -99999999; - lastSentFood = -99999999; - lastFoodSaturationZero = true; - lastSentExp = -99999999; + lastSentHealth = -99999999; + lastSentFood = -99999999; + lastFoodSaturationZero = true; + lastSentExp = -99999999; invulnerableTime = 20 * 3; - containerCounter = 0; - ignoreSlotUpdateHack = false; - latency = 0; - wonGame = false; - m_enteredEndExitPortal = false; - lastCarried = ItemInstanceArray(5); - viewDistance = 10; - - // 4jcraft added (0 initialized) - m_lastDamageSource = eTelemetryChallenges_Unknown; + containerCounter = 0; + ignoreSlotUpdateHack = false; + latency = 0; + wonGame = false; + m_enteredEndExitPortal = false; + lastCarried = ItemInstanceArray(5); + viewDistance = 10; -// gameMode->player = this; // 4J - removed to avoid use of shared_from_this in ctor, now set up externally + // 4jcraft added (0 initialized) + m_lastDamageSource = eTelemetryChallenges_Unknown; + + // gameMode->player = this; // 4J - removed to avoid use of + // shared_from_this in ctor, now set up externally this->gameMode = gameMode; - Pos *spawnPos = level->getSharedSpawnPos(); + Pos* spawnPos = level->getSharedSpawnPos(); int xx = spawnPos->x; int zz = spawnPos->z; int yy = spawnPos->y; - delete spawnPos; + delete spawnPos; - if (!level->dimension->hasCeiling && level->getLevelData()->getGameType() != GameType::ADVENTURE) - { - level->isFindingSpawn = true; + if (!level->dimension->hasCeiling && + level->getLevelData()->getGameType() != GameType::ADVENTURE) { + level->isFindingSpawn = true; - // 4J added - do additional checking that we aren't putting the player in deep water. Give up after 20 or goes just - // in case the spawnPos is somehow in a really bad spot and we would just lock here. - int waterDepth = 0; - int attemptCount = 0; - int xx2, yy2, zz2; + // 4J added - do additional checking that we aren't putting the player + // in deep water. Give up after 20 or goes just in case the spawnPos is + // somehow in a really bad spot and we would just lock here. + int waterDepth = 0; + int attemptCount = 0; + int xx2, yy2, zz2; - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; - bool playerNear = false; - do - { - // Also check that we aren't straying outside of the map - do - { - xx2 = xx + random->nextInt(20) - 10; - zz2 = zz + random->nextInt(20) - 10; - } while ( ( xx2 > maxXZ ) || ( xx2 < minXZ ) || ( zz2 > maxXZ ) || ( zz2 < minXZ ) ); - yy2 = level->getTopSolidBlock(xx2, zz2); + bool playerNear = false; + do { + // Also check that we aren't straying outside of the map + do { + xx2 = xx + random->nextInt(20) - 10; + zz2 = zz + random->nextInt(20) - 10; + } while ((xx2 > maxXZ) || (xx2 < minXZ) || (zz2 > maxXZ) || + (zz2 < minXZ)); + yy2 = level->getTopSolidBlock(xx2, zz2); - waterDepth = 0; - int yw = yy2; - while( ( yw < 128 ) && - (( level->getTile(xx2,yw,zz2) == Tile::water_Id ) || - ( level->getTile(xx2,yw,zz2) == Tile::calmWater_Id )) ) - { - yw++; - waterDepth++; - } - attemptCount++; - playerNear = ( level->getNearestPlayer(xx + 0.5, yy, zz + 0.5,3) != NULL ); - } while ( ( waterDepth > 1 ) && (!playerNear) && ( attemptCount < 20 ) ); - xx = xx2; - yy = yy2; - zz = zz2; + waterDepth = 0; + int yw = yy2; + while ((yw < 128) && + ((level->getTile(xx2, yw, zz2) == Tile::water_Id) || + (level->getTile(xx2, yw, zz2) == Tile::calmWater_Id))) { + yw++; + waterDepth++; + } + attemptCount++; + playerNear = + (level->getNearestPlayer(xx + 0.5, yy, zz + 0.5, 3) != NULL); + } while ((waterDepth > 1) && (!playerNear) && (attemptCount < 20)); + xx = xx2; + yy = yy2; + zz = zz2; - level->isFindingSpawn = false; + level->isFindingSpawn = false; } - heightOffset = 0; // 4J - this height used to be set up after moveTo, but that ends up with the y value being incorrect as it depends on this offset + heightOffset = + 0; // 4J - this height used to be set up after moveTo, but that ends up + // with the y value being incorrect as it depends on this offset this->moveTo(xx + 0.5, yy, zz + 0.5, 0, 0); this->server = server; footSize = 0; this->name = name; - m_UUID = name; + m_UUID = name; - // 4J Added - lastBrupSendTickCount = 0; + // 4J Added + lastBrupSendTickCount = 0; } -ServerPlayer::~ServerPlayer() -{ - delete [] lastCarried.data; +ServerPlayer::~ServerPlayer() { delete[] lastCarried.data; } + +// 4J added - add bits to a flag array that is passed in, to represent those +// entities which have small Ids, and are in our vector of entitiesToRemove. If +// there aren't any entities to be flagged, this function does nothing. If there +// *are* entities to be added, uses the removedFound as an input to determine if +// the flag array has already been initialised at all - if it has been, then +// just adds flags to it; if it hasn't, then memsets the output flag array and +// adds to it for this ServerPlayer. +void ServerPlayer::flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound) { + if (entitiesToRemove.empty()) { + return; + } + if ((*removedFound) == false) { + *removedFound = true; + memset(flags, 0, 2048 / 32); + } + + AUTO_VAR(it, entitiesToRemove.begin()); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != entitiesToRemove.end(); + it++) { + int index = *it; + if (index < 2048) { + unsigned int i = index / 32; + unsigned int j = index % 32; + unsigned int uiMask = 0x80000000 >> j; + + flags[i] |= uiMask; + } + } } -// 4J added - add bits to a flag array that is passed in, to represent those entities which have small Ids, and are in our vector of entitiesToRemove. -// If there aren't any entities to be flagged, this function does nothing. If there *are* entities to be added, uses the removedFound as an input to -// determine if the flag array has already been initialised at all - if it has been, then just adds flags to it; if it hasn't, then memsets the output -// flag array and adds to it for this ServerPlayer. -void ServerPlayer::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound) -{ - if( entitiesToRemove.empty() ) - { - return; - } - if( ( *removedFound ) == false ) - { - *removedFound = true; - memset(flags, 0, 2048/32); - } +void ServerPlayer::readAdditionalSaveData(CompoundTag* entityTag) { + Player::readAdditionalSaveData(entityTag); - AUTO_VAR(it, entitiesToRemove.begin() ); - for( AUTO_VAR(it, entitiesToRemove.begin()); it != entitiesToRemove.end(); it++ ) - { - int index = *it; - if( index < 2048 ) - { - unsigned int i = index / 32; - unsigned int j = index % 32; - unsigned int uiMask = 0x80000000 >> j; + if (entityTag->contains(L"playerGameType")) { + // 4J Stu - We do not want to change the game mode for the player, + // instead we let the server override it globally + // gameMode->setGameModeForPlayer(GameType::byId(entityTag->getInt(L"playerGameType"))); + } - flags[i] |= uiMask; - } - } + GameRulesInstance* grs = gameMode->getGameRules(); + if (entityTag->contains(L"GameRules") && grs != NULL) { + byteArray ba = entityTag->getByteArray(L"GameRules"); + ByteArrayInputStream bais(ba); + DataInputStream dis(&bais); + grs->read(&dis); + dis.close(); + bais.close(); + // delete [] ba.data; + } } -void ServerPlayer::readAdditionalSaveData(CompoundTag *entityTag) -{ - Player::readAdditionalSaveData(entityTag); +void ServerPlayer::addAdditonalSaveData(CompoundTag* entityTag) { + Player::addAdditonalSaveData(entityTag); - if (entityTag->contains(L"playerGameType")) - { - // 4J Stu - We do not want to change the game mode for the player, instead we let the server override it globally - //gameMode->setGameModeForPlayer(GameType::byId(entityTag->getInt(L"playerGameType"))); - } + GameRulesInstance* grs = gameMode->getGameRules(); + if (grs != NULL) { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); + grs->write(&dos); + entityTag->putByteArray(L"GameRules", baos.buf); + baos.buf.data = NULL; + dos.close(); + baos.close(); + } - GameRulesInstance *grs = gameMode->getGameRules(); - if (entityTag->contains(L"GameRules") && grs != NULL) - { - byteArray ba = entityTag->getByteArray(L"GameRules"); - ByteArrayInputStream bais(ba); - DataInputStream dis(&bais); - grs->read(&dis); - dis.close(); - bais.close(); - //delete [] ba.data; - } + // 4J Stu - We do not want to change the game mode for the player, instead + // we let the server override it globally + // entityTag->putInt(L"playerGameType", + // gameMode->getGameModeForPlayer()->getId()); } -void ServerPlayer::addAdditonalSaveData(CompoundTag *entityTag) -{ - Player::addAdditonalSaveData(entityTag); - - GameRulesInstance *grs = gameMode->getGameRules(); - if (grs != NULL) - { - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - grs->write(&dos); - entityTag->putByteArray(L"GameRules", baos.buf); - baos.buf.data = NULL; - dos.close(); - baos.close(); - } - - // 4J Stu - We do not want to change the game mode for the player, instead we let the server override it globally - //entityTag->putInt(L"playerGameType", gameMode->getGameModeForPlayer()->getId()); +void ServerPlayer::withdrawExperienceLevels(int amount) { + Player::withdrawExperienceLevels(amount); + lastSentExp = -1; } -void ServerPlayer::withdrawExperienceLevels(int amount) -{ - Player::withdrawExperienceLevels(amount); - lastSentExp = -1; -} +void ServerPlayer::initMenu() { containerMenu->addSlotListener(this); } -void ServerPlayer::initMenu() -{ - containerMenu->addSlotListener(this); -} +ItemInstanceArray ServerPlayer::getEquipmentSlots() { return lastCarried; } -ItemInstanceArray ServerPlayer::getEquipmentSlots() -{ - return lastCarried; -} +void ServerPlayer::setDefaultHeadHeight() { heightOffset = 0; } -void ServerPlayer::setDefaultHeadHeight() -{ - heightOffset = 0; -} +float ServerPlayer::getHeadHeight() { return 1.62f; } -float ServerPlayer::getHeadHeight() -{ - return 1.62f; -} - -void ServerPlayer::tick() -{ +void ServerPlayer::tick() { gameMode->tick(); if (invulnerableTime > 0) invulnerableTime--; containerMenu->broadcastChanges(); - // 4J-JEV, hook for Durango event 'EnteredNewBiome'. - Biome *newBiome = level->getBiome(x,z); - if (newBiome != currentBiome) - { - awardStat( - GenericStats::enteredBiome(newBiome->id), - GenericStats::param_enteredBiome(newBiome->id) - ); - currentBiome = newBiome; - } + // 4J-JEV, hook for Durango event 'EnteredNewBiome'. + Biome* newBiome = level->getBiome(x, z); + if (newBiome != currentBiome) { + awardStat(GenericStats::enteredBiome(newBiome->id), + GenericStats::param_enteredBiome(newBiome->id)); + currentBiome = newBiome; + } - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { std::shared_ptr currentCarried = getCarried(i); - if (currentCarried != lastCarried[i]) - { - getLevel()->getTracker()->broadcast(shared_from_this(), std::shared_ptr( new SetEquippedItemPacket(this->entityId, i, currentCarried) ) ); + if (currentCarried != lastCarried[i]) { + getLevel()->getTracker()->broadcast( + shared_from_this(), + std::shared_ptr( + new SetEquippedItemPacket(this->entityId, i, + currentCarried))); lastCarried[i] = currentCarried; } } - flushEntitiesToRemove(); + flushEntitiesToRemove(); } // 4J Stu - Split out here so that we can call this from other places -void ServerPlayer::flushEntitiesToRemove() -{ - if (!entitiesToRemove.empty()) - { - int sz = entitiesToRemove.size(); - int amount = std::min(sz, RemoveEntitiesPacket::MAX_PER_PACKET); - intArray ids(amount); - int pos = 0; +void ServerPlayer::flushEntitiesToRemove() { + if (!entitiesToRemove.empty()) { + int sz = entitiesToRemove.size(); + int amount = std::min(sz, RemoveEntitiesPacket::MAX_PER_PACKET); + intArray ids(amount); + int pos = 0; - AUTO_VAR(it, entitiesToRemove.begin() ); - while (it != entitiesToRemove.end() && pos < amount) - { - ids[pos++] = *it; - it = entitiesToRemove.erase(it); - } + AUTO_VAR(it, entitiesToRemove.begin()); + while (it != entitiesToRemove.end() && pos < amount) { + ids[pos++] = *it; + it = entitiesToRemove.erase(it); + } - connection->send(std::shared_ptr(new RemoveEntitiesPacket(ids))); - } + connection->send(std::shared_ptr( + new RemoveEntitiesPacket(ids))); + } } - -// 4J - have split doTick into 3 bits, so that we can call the doChunkSendingTick separately, but still do the equivalent of what calling a full doTick used to do, by calling this method -void ServerPlayer::doTick(bool sendChunks, bool dontDelayChunks/*=false*/, bool ignorePortal/*=false*/) -{ - doTickA(); - if( sendChunks ) - { - doChunkSendingTick(dontDelayChunks); - } - doTickB(ignorePortal); +// 4J - have split doTick into 3 bits, so that we can call the +// doChunkSendingTick separately, but still do the equivalent of what calling a +// full doTick used to do, by calling this method +void ServerPlayer::doTick(bool sendChunks, bool dontDelayChunks /*=false*/, + bool ignorePortal /*=false*/) { + doTickA(); + if (sendChunks) { + doChunkSendingTick(dontDelayChunks); + } + doTickB(ignorePortal); } -void ServerPlayer::doTickA() -{ +void ServerPlayer::doTickA() { Player::tick(); - for (unsigned int i = 0; i < inventory->getContainerSize(); i++) - { + for (unsigned int i = 0; i < inventory->getContainerSize(); i++) { std::shared_ptr ie = inventory->getItem(i); - if (ie != NULL) - { - // 4J - removed condition. These were getting lower priority than tile update packets etc. on the slow outbound queue, and so were extremely slow to send sometimes, - // particularly at the start of a game. They don't typically seem to be massive and shouldn't be send when there isn't actually any updating to do. - if (Item::items[ie->id]->isComplex() ) // && connection->countDelayedPackets() <= 2) - { - std::shared_ptr packet = (dynamic_cast(Item::items[ie->id])->getUpdatePacket(ie, level, std::dynamic_pointer_cast( shared_from_this() ) ) ); - if (packet != NULL) - { + if (ie != NULL) { + // 4J - removed condition. These were getting lower priority than + // tile update packets etc. on the slow outbound queue, and so were + // extremely slow to send sometimes, particularly at the start of a + // game. They don't typically seem to be massive and shouldn't be + // send when there isn't actually any updating to do. + if (Item::items[ie->id] + ->isComplex()) // && connection->countDelayedPackets() <= + // 2) + { + std::shared_ptr packet = + (dynamic_cast(Item::items[ie->id]) + ->getUpdatePacket(ie, level, + std::dynamic_pointer_cast( + shared_from_this()))); + if (packet != NULL) { connection->send(packet); } } @@ -306,488 +294,552 @@ void ServerPlayer::doTickA() } } -// 4J - split off the chunk sending bit of the tick here from ::doTick so we can do this exactly once per player per server tick -void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) -{ -// printf("[%d] %s: sendChunks: %d, empty: %d\n",tickCount, connection->getNetworkPlayer()->GetUID().getOnlineID(),sendChunks,chunksToSend.empty()); - if (!chunksToSend.empty()) - { +// 4J - split off the chunk sending bit of the tick here from ::doTick so we can +// do this exactly once per player per server tick +void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) { + // printf("[%d] %s: sendChunks: %d, empty: %d\n",tickCount, + //connection->getNetworkPlayer()->GetUID().getOnlineID(),sendChunks,chunksToSend.empty()); + if (!chunksToSend.empty()) { ChunkPos nearest = chunksToSend.front(); - bool nearestValid = false; + bool nearestValid = false; - // 4J - reinstated and optimised some code that was commented out in the original, to make sure that we always - // send the nearest chunk to the player. The original uses the bukkit sorting thing to try and avoid doing this, but - // the player can quickly wander away from the centre of the spiral of chunks that that method creates, long before transmission - // of them is complete. + // 4J - reinstated and optimised some code that was commented out in the + // original, to make sure that we always send the nearest chunk to the + // player. The original uses the bukkit sorting thing to try and avoid + // doing this, but the player can quickly wander away from the centre of + // the spiral of chunks that that method creates, long before + // transmission of them is complete. double dist = DBL_MAX; - for( AUTO_VAR(it, chunksToSend.begin()); it != chunksToSend.end(); it++ ) - { + for (AUTO_VAR(it, chunksToSend.begin()); it != chunksToSend.end(); + it++) { ChunkPos chunk = *it; - if( level->isChunkFinalised(chunk.x, chunk.z) ) - { - double newDist = chunk.distanceToSqr(x, z); - if ( (!nearestValid) || (newDist < dist) ) - { - nearest = chunk; - dist = chunk.distanceToSqr(x, z); - nearestValid = true; - } - } + if (level->isChunkFinalised(chunk.x, chunk.z)) { + double newDist = chunk.distanceToSqr(x, z); + if ((!nearestValid) || (newDist < dist)) { + nearest = chunk; + dist = chunk.distanceToSqr(x, z); + nearestValid = true; + } + } } -// if (nearest != NULL) // 4J - removed as we don't have references here - if( nearestValid ) - { + // if (nearest != NULL) // 4J - removed as we don't have + // references here + if (nearestValid) { bool okToSend = false; -// if (dist < 32 * 32) okToSend = true; - if( connection->isLocal() ) - { - if( !connection->done ) okToSend = true; - } - else - { - bool canSendOnSlowQueue = MinecraftServer::canSendOnSlowQueue(connection->getNetworkPlayer()); - -// app.DebugPrintf("%ls: canSendOnSlowQueue %d, countDelayedPackets %d GetSendQueueSizeBytes %d done: %d", -// connection->getNetworkPlayer()->GetUID().toString().c_str(), -// canSendOnSlowQueue, connection->countDelayedPackets(), -// g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( NULL, true ), -// connection->done); - - if( dontDelayChunks || - (canSendOnSlowQueue && - (connection->countDelayedPackets() < 4 )&& + // if (dist < 32 * 32) okToSend = true; + if (connection->isLocal()) { + if (!connection->done) okToSend = true; + } else { + bool canSendOnSlowQueue = MinecraftServer::canSendOnSlowQueue( + connection->getNetworkPlayer()); + + // app.DebugPrintf("%ls: + //canSendOnSlowQueue %d, countDelayedPackets %d + //GetSendQueueSizeBytes %d done: %d", + // connection->getNetworkPlayer()->GetUID().toString().c_str(), + // canSendOnSlowQueue, + //connection->countDelayedPackets(), + // g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( + //NULL, true ), connection->done); + + if (dontDelayChunks || + (canSendOnSlowQueue && + (connection->countDelayedPackets() < 4) && #ifdef _XBOX_ONE - // The network manager on xbox one doesn't currently split data into slow & fast queues - since we can only measure - // both together then bytes provides a better metric than count of data items to determine if we should avoid queueing too much up - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( NULL, true ) < 8192 )&& + // The network manager on xbox one doesn't currently split + // data into slow & fast queues - since we can only measure + // both together then bytes provides a better metric than + // count of data items to determine if we should avoid + // queueing too much up + (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( + NULL, true) < 8192) && #else - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ) < 4 )&& -#endif - //(tickCount - lastBrupSendTickCount) > (connection->getNetworkPlayer()->GetCurrentRtt()>>4) && - !connection->done) ) - { - lastBrupSendTickCount = tickCount; - okToSend = true; - MinecraftServer::s_slowQueuePacketSent = true; + (g_NetworkManager.GetHostPlayer() + ->GetSendQueueSizeMessages(NULL, true) < 4) && +#endif + //(tickCount - lastBrupSendTickCount) > + //(connection->getNetworkPlayer()->GetCurrentRtt()>>4) && + !connection->done)) { + lastBrupSendTickCount = tickCount; + okToSend = true; + MinecraftServer::s_slowQueuePacketSent = true; -// static std::unordered_map mapLastTime; -// __int64 thisTime = System::currentTimeMillis(); -// __int64 lastTime = mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; -// app.DebugPrintf(" - OK to send (%d ms since last)\n", thisTime - lastTime); -// mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] = thisTime; - } - else - { -// app.DebugPrintf(" - \n"); - } - } + // static + //std::unordered_map mapLastTime; + // __int64 thisTime = + //System::currentTimeMillis(); + // __int64 lastTime = + //mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; + // app.DebugPrintf(" - OK + //to send (%d ms since last)\n", thisTime - lastTime); + // mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] + //= thisTime; + } else { + // app.DebugPrintf(" - \n"); + } + } - if (okToSend) - { - ServerLevel *level = server->getLevel(dimension); - int flagIndex = getFlagIndexForChunk(nearest,this->level->dimension->id); + if (okToSend) { + ServerLevel* level = server->getLevel(dimension); + int flagIndex = + getFlagIndexForChunk(nearest, this->level->dimension->id); chunksToSend.remove(nearest); - bool chunkDataSent = false; + bool chunkDataSent = false; - // Don't send the chunk to the local machine - the chunks there are mapped directly to the server chunks. We could potentially stop this process earlier on by not adding - // to the chunksToSend list, but that would stop the tile entities being broadcast too - if( !connection->isLocal() ) // force here to disable sharing of data - { - // Don't send the chunk if we've set a flag to say that we've already sent it to this machine. This stops two things - // (1) Sending a chunk to multiple players doing split screen on one machine - // (2) Sending a chunk that we've already sent as the player moves around. The original version of the game resends these, since it maintains - // a region of active chunks round each player in the "infinite" world, but in our finite world, we don't ever request that chunks be - // unloaded on the client and so just gradually build up more and more of the finite set of chunks as the player moves - if( !g_NetworkManager.SystemFlagGet(connection->getNetworkPlayer(),flagIndex) ) - { -// app.DebugPrintf("Creating BRUP for %d %d\n",nearest.x, nearest.z); - PIXBeginNamedEvent(0,"Creation BRUP for sending\n"); - std::shared_ptr packet = std::shared_ptr( new BlockRegionUpdatePacket(nearest.x * 16, 0, nearest.z * 16, 16, Level::maxBuildHeight, 16, level) ); - PIXEndNamedEvent(); - if( dontDelayChunks ) packet->shouldDelay = false; + // Don't send the chunk to the local machine - the chunks there + // are mapped directly to the server chunks. We could + // potentially stop this process earlier on by not adding to the + // chunksToSend list, but that would stop the tile entities + // being broadcast too + if (!connection + ->isLocal()) // force here to disable sharing of data + { + // Don't send the chunk if we've set a flag to say that + // we've already sent it to this machine. This stops two + // things (1) Sending a chunk to multiple players doing + // split screen on one machine (2) Sending a chunk that + // we've already sent as the player moves around. The + // original version of the game resends these, since it + // maintains + // a region of active chunks round each player in the + // "infinite" world, but in our finite world, we don't + // ever request that chunks be unloaded on the client + // and so just gradually build up more and more of the + // finite set of chunks as the player moves + if (!g_NetworkManager.SystemFlagGet( + connection->getNetworkPlayer(), flagIndex)) { + // app.DebugPrintf("Creating + //BRUP for %d %d\n",nearest.x, nearest.z); + PIXBeginNamedEvent(0, "Creation BRUP for sending\n"); + std::shared_ptr packet = + std::shared_ptr( + new BlockRegionUpdatePacket( + nearest.x * 16, 0, nearest.z * 16, 16, + Level::maxBuildHeight, 16, level)); + PIXEndNamedEvent(); + if (dontDelayChunks) packet->shouldDelay = false; - if( packet->shouldDelay == true ) - { - // Other than the first packet we always want these initial chunks to be sent over - // QNet at a lower priority - connection->queueSend( packet ); - } - else - { - connection->send( packet ); - } - // Set flag to say we have send this block already to this system - g_NetworkManager.SystemFlagSet(connection->getNetworkPlayer(),flagIndex); + if (packet->shouldDelay == true) { + // Other than the first packet we always want these + // initial chunks to be sent over QNet at a lower + // priority + connection->queueSend(packet); + } else { + connection->send(packet); + } + // Set flag to say we have send this block already to + // this system + g_NetworkManager.SystemFlagSet( + connection->getNetworkPlayer(), flagIndex); - chunkDataSent = true; - } - } - else - { - // For local connections, we'll need to copy the lighting data over from server to client at this point. This is to try and keep lighting as similar as possible to the java version, - // where client & server are individually responsible for maintaining their lighting (since 1.2.3). This is really an alternative to sending the lighting data over the fake local - // network connection at this point. + chunkDataSent = true; + } + } else { + // For local connections, we'll need to copy the lighting + // data over from server to client at this point. This is to + // try and keep lighting as similar as possible to the java + // version, where client & server are individually + // responsible for maintaining their lighting (since 1.2.3). + // This is really an alternative to sending the lighting + // data over the fake local network connection at this + // point. - MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id); - if( clientLevel ) - { - LevelChunk *lc = clientLevel->getChunk( nearest.x, nearest.z ); - lc->reSyncLighting(); - lc->recalcHeightmapOnly(); - clientLevel->setTilesDirty(nearest.x * 16 + 1, 1, nearest.z * 16 + 1, - nearest.x * 16 + 14, Level::maxBuildHeight - 2, nearest.z * 16 + 14 ); - } - } - // Don't send TileEntity data until we have sent the block data - if( connection->isLocal() || chunkDataSent) - { - std::vector > *tes = level->getTileEntitiesInRegion(nearest.x * 16, 0, nearest.z * 16, nearest.x * 16 + 16, Level::maxBuildHeight, nearest.z * 16 + 16); - for (unsigned int i = 0; i < tes->size(); i++) - { - // 4J Stu - Added delay param to ensure that these arrive after the BRUPs from above - // Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”. - broadcast(tes->at(i), !connection->isLocal() && !dontDelayChunks); - } - delete tes; - } + MultiPlayerLevel* clientLevel = + Minecraft::GetInstance()->getLevel( + level->dimension->id); + if (clientLevel) { + LevelChunk* lc = + clientLevel->getChunk(nearest.x, nearest.z); + lc->reSyncLighting(); + lc->recalcHeightmapOnly(); + clientLevel->setTilesDirty( + nearest.x * 16 + 1, 1, nearest.z * 16 + 1, + nearest.x * 16 + 14, Level::maxBuildHeight - 2, + nearest.z * 16 + 14); + } + } + // Don't send TileEntity data until we have sent the block data + if (connection->isLocal() || chunkDataSent) { + std::vector >* tes = + level->getTileEntitiesInRegion( + nearest.x * 16, 0, nearest.z * 16, + nearest.x * 16 + 16, Level::maxBuildHeight, + nearest.z * 16 + 16); + for (unsigned int i = 0; i < tes->size(); i++) { + // 4J Stu - Added delay param to ensure that these + // arrive after the BRUPs from above Fix for #9169 - ART + // : Sign text is replaced with the words “Awaiting + // approval”. + broadcast(tes->at(i), + !connection->isLocal() && !dontDelayChunks); + } + delete tes; + } } } } } -void ServerPlayer::doTickB(bool ignorePortal) -{ +void ServerPlayer::doTickB(bool ignorePortal) { #ifndef _CONTENT_PACKAGE - // check if there's a debug dimension change requested - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<dimension->id == 0 ) - { - ignorePortal=false; - isInsidePortal=true; - portalTime=1; - } - unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id == 0 ) -// { -// server->players->toggleDimension( std::dynamic_pointer_cast( shared_from_this() ), 1 ); -// } -// unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); -// app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id != 0 ) - { - ignorePortal=false; - isInsidePortal=true; - portalTime=1; - } - unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id == 0) { + ignorePortal = false; + isInsidePortal = true; + portalTime = 1; + } + unsigned int uiVal = + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + uiVal & ~(1L << eDebugSetting_GoToNether)); + } + // else if + // (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<dimension->id == 0 ) + // { + // server->players->toggleDimension( + // std::dynamic_pointer_cast( shared_from_this() ), 1 ); + // } + // unsigned int + // uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + // app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id != 0) { + ignorePortal = false; + isInsidePortal = true; + portalTime = 1; + } + unsigned int uiVal = + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + app.SetGameSettingsDebugMask( + ProfileManager.GetPrimaryPad(), + uiVal & ~(1L << eDebugSetting_GoToOverworld)); + } #endif - if(!ignorePortal) - { - if (isInsidePortal) - { - if (server->isNetherEnabled()) - { - if (containerMenu != inventoryMenu) - { - closeContainer(); - } - if (riding != NULL) - { - this->ride(riding); - } - else - { + if (!ignorePortal) { + if (isInsidePortal) { + if (server->isNetherEnabled()) { + if (containerMenu != inventoryMenu) { + closeContainer(); + } + if (riding != NULL) { + this->ride(riding); + } else { + portalTime += 1 / 80.0f; + if (portalTime >= 1) { + portalTime = 1; + changingDimensionDelay = 10; - portalTime += 1 / 80.0f; - if (portalTime >= 1) - { - portalTime = 1; - changingDimensionDelay = 10; + int targetDimension = 0; + if (dimension == -1) + targetDimension = 0; + else + targetDimension = -1; - int targetDimension = 0; - if (dimension == -1) targetDimension = 0; - else targetDimension = -1; + server->getPlayers()->toggleDimension( + std::dynamic_pointer_cast( + shared_from_this()), + targetDimension); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; - server->getPlayers()->toggleDimension( std::dynamic_pointer_cast( shared_from_this() ), targetDimension ); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - - //awardStat(Achievements::portal); - } - } - isInsidePortal = false; - } - } - else - { - if (portalTime > 0) portalTime -= 1 / 20.0f; - if (portalTime < 0) portalTime = 0; - } - if (changingDimensionDelay > 0) changingDimensionDelay--; - } - - if (getHealth() != lastSentHealth || lastSentFood != foodData.getFoodLevel() || ((foodData.getSaturationLevel() == 0) != lastFoodSaturationZero)) - { - // 4J Stu - Added m_lastDamageSource for telemetry //4jcraft, nice but you never initialized it - connection->send( std::shared_ptr( new SetHealthPacket(getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), m_lastDamageSource) ) ); - lastSentHealth = getHealth(); - lastSentFood = foodData.getFoodLevel(); - lastFoodSaturationZero = foodData.getSaturationLevel() == 0; + // awardStat(Achievements::portal); + } + } + isInsidePortal = false; + } + } else { + if (portalTime > 0) portalTime -= 1 / 20.0f; + if (portalTime < 0) portalTime = 0; + } + if (changingDimensionDelay > 0) changingDimensionDelay--; } - if (totalExperience != lastSentExp) - { - lastSentExp = totalExperience; - connection->send( std::shared_ptr( new SetExperiencePacket(experienceProgress, totalExperience, experienceLevel) ) ); - } + if (getHealth() != lastSentHealth || + lastSentFood != foodData.getFoodLevel() || + ((foodData.getSaturationLevel() == 0) != lastFoodSaturationZero)) { + // 4J Stu - Added m_lastDamageSource for telemetry //4jcraft, nice but + // you never initialized it + connection->send(std::shared_ptr(new SetHealthPacket( + getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), + m_lastDamageSource))); + lastSentHealth = getHealth(); + lastSentFood = foodData.getFoodLevel(); + lastFoodSaturationZero = foodData.getSaturationLevel() == 0; + } + if (totalExperience != lastSentExp) { + lastSentExp = totalExperience; + connection->send( + std::shared_ptr(new SetExperiencePacket( + experienceProgress, totalExperience, experienceLevel))); + } } -std::shared_ptr ServerPlayer::getCarried(int slot) -{ +std::shared_ptr ServerPlayer::getCarried(int slot) { if (slot == 0) return inventory->getSelected(); return inventory->armor[slot - 1]; } -void ServerPlayer::die(DamageSource *source) -{ - server->getPlayers()->broadcastAll(source->getDeathMessagePacket(std::dynamic_pointer_cast(shared_from_this()))); - inventory->dropAll(); +void ServerPlayer::die(DamageSource* source) { + server->getPlayers()->broadcastAll(source->getDeathMessagePacket( + std::dynamic_pointer_cast(shared_from_this()))); + inventory->dropAll(); } -bool ServerPlayer::hurt(DamageSource *dmgSource, int dmg) -{ +bool ServerPlayer::hurt(DamageSource* dmgSource, int dmg) { if (invulnerableTime > 0) return false; - if (dynamic_cast(dmgSource) != NULL) - { - // 4J Stu - Fix for #46422 - TU5: Crash: Gameplay: Crash when being hit by a trap using a dispenser - // getEntity returns the owner of projectiles, and this would never be the arrow. The owner is sometimes NULL. - std::shared_ptr source = dmgSource->getDirectEntity(); + if (dynamic_cast(dmgSource) != NULL) { + // 4J Stu - Fix for #46422 - TU5: Crash: Gameplay: Crash when being hit + // by a trap using a dispenser getEntity returns the owner of + // projectiles, and this would never be the arrow. The owner is + // sometimes NULL. + std::shared_ptr source = dmgSource->getDirectEntity(); - - if (std::dynamic_pointer_cast(source) != NULL && (!server->pvp || !std::dynamic_pointer_cast(source)->isAllowedToAttackPlayers()) ) - { - return false; - } + if (std::dynamic_pointer_cast(source) != NULL && + (!server->pvp || !std::dynamic_pointer_cast(source) + ->isAllowedToAttackPlayers())) { + return false; + } - if (source != NULL && source->GetType() == eTYPE_ARROW) - { - std::shared_ptr arrow = std::dynamic_pointer_cast(source); - if (std::dynamic_pointer_cast(arrow->owner) != NULL && (!server->pvp || !std::dynamic_pointer_cast(arrow->owner)->isAllowedToAttackPlayers()) ) - { - return false; - } - } + if (source != NULL && source->GetType() == eTYPE_ARROW) { + std::shared_ptr arrow = + std::dynamic_pointer_cast(source); + if (std::dynamic_pointer_cast(arrow->owner) != NULL && + (!server->pvp || + !std::dynamic_pointer_cast(arrow->owner) + ->isAllowedToAttackPlayers())) { + return false; + } + } } bool returnVal = Player::hurt(dmgSource, dmg); - if( returnVal ) - { - // 4J Stu - Work out the source of this damage for telemetry - m_lastDamageSource = eTelemetryChallenges_Unknown; + if (returnVal) { + // 4J Stu - Work out the source of this damage for telemetry + m_lastDamageSource = eTelemetryChallenges_Unknown; - if(dmgSource == DamageSource::fall) m_lastDamageSource = eTelemetryPlayerDeathSource_Fall; - else if(dmgSource == DamageSource::onFire || dmgSource == DamageSource::inFire) m_lastDamageSource = eTelemetryPlayerDeathSource_Fire; - else if(dmgSource == DamageSource::lava) m_lastDamageSource = eTelemetryPlayerDeathSource_Lava; - else if(dmgSource == DamageSource::drown) m_lastDamageSource = eTelemetryPlayerDeathSource_Water; - else if(dmgSource == DamageSource::inWall) m_lastDamageSource = eTelemetryPlayerDeathSource_Suffocate; - else if(dmgSource == DamageSource::outOfWorld) m_lastDamageSource = eTelemetryPlayerDeathSource_OutOfWorld; - else if(dmgSource == DamageSource::cactus) m_lastDamageSource = eTelemetryPlayerDeathSource_Cactus; - else - { - std::shared_ptr source = dmgSource->getEntity(); - if( source != NULL ) - { - switch(source->GetType()) - { - case eTYPE_PLAYER: - case eTYPE_SERVERPLAYER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Player_Weapon; - break; - case eTYPE_WOLF: - m_lastDamageSource = eTelemetryPlayerDeathSource_Wolf; - break; - case eTYPE_CREEPER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Explosion_Creeper; - break; - case eTYPE_SKELETON: - m_lastDamageSource = eTelemetryPlayerDeathSource_Skeleton; - break; - case eTYPE_SPIDER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Spider; - break; - case eTYPE_ZOMBIE: - m_lastDamageSource = eTelemetryPlayerDeathSource_Zombie; - break; - case eTYPE_PIGZOMBIE: - m_lastDamageSource = eTelemetryPlayerDeathSource_ZombiePigman; - break; - case eTYPE_GHAST: - m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; - break; - case eTYPE_SLIME: - m_lastDamageSource = eTelemetryPlayerDeathSource_Slime; - break; - case eTYPE_PRIMEDTNT: - m_lastDamageSource = eTelemetryPlayerDeathSource_Explosion_Tnt; - break; - case eTYPE_ARROW: - if ((std::dynamic_pointer_cast(source))->owner != NULL) - { - std::shared_ptr attacker = (std::dynamic_pointer_cast(source))->owner; - if (attacker != NULL) - { - switch(attacker->GetType()) - { - case eTYPE_SKELETON: - m_lastDamageSource = eTelemetryPlayerDeathSource_Skeleton; - break; - case eTYPE_PLAYER: - case eTYPE_SERVERPLAYER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Player_Arrow; - break; - } - } - } - break; - case eTYPE_FIREBALL: - m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; - break; - }; - } - }; - } + if (dmgSource == DamageSource::fall) + m_lastDamageSource = eTelemetryPlayerDeathSource_Fall; + else if (dmgSource == DamageSource::onFire || + dmgSource == DamageSource::inFire) + m_lastDamageSource = eTelemetryPlayerDeathSource_Fire; + else if (dmgSource == DamageSource::lava) + m_lastDamageSource = eTelemetryPlayerDeathSource_Lava; + else if (dmgSource == DamageSource::drown) + m_lastDamageSource = eTelemetryPlayerDeathSource_Water; + else if (dmgSource == DamageSource::inWall) + m_lastDamageSource = eTelemetryPlayerDeathSource_Suffocate; + else if (dmgSource == DamageSource::outOfWorld) + m_lastDamageSource = eTelemetryPlayerDeathSource_OutOfWorld; + else if (dmgSource == DamageSource::cactus) + m_lastDamageSource = eTelemetryPlayerDeathSource_Cactus; + else { + std::shared_ptr source = dmgSource->getEntity(); + if (source != NULL) { + switch (source->GetType()) { + case eTYPE_PLAYER: + case eTYPE_SERVERPLAYER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Player_Weapon; + break; + case eTYPE_WOLF: + m_lastDamageSource = eTelemetryPlayerDeathSource_Wolf; + break; + case eTYPE_CREEPER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Explosion_Creeper; + break; + case eTYPE_SKELETON: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Skeleton; + break; + case eTYPE_SPIDER: + m_lastDamageSource = eTelemetryPlayerDeathSource_Spider; + break; + case eTYPE_ZOMBIE: + m_lastDamageSource = eTelemetryPlayerDeathSource_Zombie; + break; + case eTYPE_PIGZOMBIE: + m_lastDamageSource = + eTelemetryPlayerDeathSource_ZombiePigman; + break; + case eTYPE_GHAST: + m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; + break; + case eTYPE_SLIME: + m_lastDamageSource = eTelemetryPlayerDeathSource_Slime; + break; + case eTYPE_PRIMEDTNT: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Explosion_Tnt; + break; + case eTYPE_ARROW: + if ((std::dynamic_pointer_cast(source))->owner != + NULL) { + std::shared_ptr attacker = + (std::dynamic_pointer_cast(source)) + ->owner; + if (attacker != NULL) { + switch (attacker->GetType()) { + case eTYPE_SKELETON: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Skeleton; + break; + case eTYPE_PLAYER: + case eTYPE_SERVERPLAYER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Player_Arrow; + break; + } + } + } + break; + case eTYPE_FIREBALL: + m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; + break; + }; + } + }; + } - return returnVal; + return returnVal; } -bool ServerPlayer::isPlayerVersusPlayer() -{ - return server->pvp; -} +bool ServerPlayer::isPlayerVersusPlayer() { return server->pvp; } -void ServerPlayer::changeDimension(int i) -{ - if(!connection->hasClientTickedOnce()) return; +void ServerPlayer::changeDimension(int i) { + if (!connection->hasClientTickedOnce()) return; - if (dimension == 1 && i == 1) - { - app.DebugPrintf("Start win game\n"); - awardStat(GenericStats::winGame(), GenericStats::param_winGame()); + if (dimension == 1 && i == 1) { + app.DebugPrintf("Start win game\n"); + awardStat(GenericStats::winGame(), GenericStats::param_winGame()); - // All players on the same system as this player should also be removed from the game while the Win screen is shown - INetworkPlayer *thisPlayer = connection->getNetworkPlayer(); + // All players on the same system as this player should also be removed + // from the game while the Win screen is shown + INetworkPlayer* thisPlayer = connection->getNetworkPlayer(); - if(!wonGame) - { - level->removeEntity(shared_from_this()); - wonGame = true; - m_enteredEndExitPortal = true; // We only flag this for the player in the portal - connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()) ) ); - app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); - } - if(thisPlayer != NULL) - { - for(AUTO_VAR(it, MinecraftServer::getInstance()->getPlayers()->players.begin()); it != MinecraftServer::getInstance()->getPlayers()->players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && !servPlayer->wonGame ) - { - servPlayer->wonGame = true; - servPlayer->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex() ) ) ); - app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); - } - } - } - app.DebugPrintf("End win game\n"); - } - else - { - awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); + if (!wonGame) { + level->removeEntity(shared_from_this()); + wonGame = true; + m_enteredEndExitPortal = + true; // We only flag this for the player in the portal + connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()))); + app.DebugPrintf("Sending packet to %d\n", + thisPlayer->GetUserIndex()); + } + if (thisPlayer != NULL) { + for (AUTO_VAR(it, MinecraftServer::getInstance() + ->getPlayers() + ->players.begin()); + it != + MinecraftServer::getInstance()->getPlayers()->players.end(); + ++it) { + std::shared_ptr servPlayer = *it; + INetworkPlayer* checkPlayer = + servPlayer->connection->getNetworkPlayer(); + if (thisPlayer != checkPlayer && checkPlayer != NULL && + thisPlayer->IsSameSystem(checkPlayer) && + !servPlayer->wonGame) { + servPlayer->wonGame = true; + servPlayer->connection->send( + std::shared_ptr( + new GameEventPacket(GameEventPacket::WIN_GAME, + thisPlayer->GetUserIndex()))); + app.DebugPrintf("Sending packet to %d\n", + thisPlayer->GetUserIndex()); + } + } + } + app.DebugPrintf("End win game\n"); + } else { + awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); - Pos *pos = server->getLevel(i)->getDimensionSpecificSpawn(); - if (pos != NULL) - { - connection->teleport(pos->x, pos->y, pos->z, 0, 0); - delete pos; - } - server->getPlayers()->toggleDimension( std::dynamic_pointer_cast(shared_from_this()), 1); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - } + Pos* pos = server->getLevel(i)->getDimensionSpecificSpawn(); + if (pos != NULL) { + connection->teleport(pos->x, pos->y, pos->z, 0, 0); + delete pos; + } + server->getPlayers()->toggleDimension( + std::dynamic_pointer_cast(shared_from_this()), 1); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; + } } // 4J Added delay param -void ServerPlayer::broadcast(std::shared_ptr te, bool delay /*= false*/) -{ - if (te != NULL) - { +void ServerPlayer::broadcast(std::shared_ptr te, + bool delay /*= false*/) { + if (te != NULL) { std::shared_ptr p = te->getUpdatePacket(); - if (p != NULL) - { - p->shouldDelay = delay; - if(delay) connection->queueSend(p); - else connection->send(p); + if (p != NULL) { + p->shouldDelay = delay; + if (delay) + connection->queueSend(p); + else + connection->send(p); } } } -void ServerPlayer::take(std::shared_ptr e, int orgCount) -{ - if (!e->removed) - { - EntityTracker *entityTracker = getLevel()->getTracker(); - if (e->GetType() == eTYPE_ITEMENTITY) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); +void ServerPlayer::take(std::shared_ptr e, int orgCount) { + if (!e->removed) { + EntityTracker* entityTracker = getLevel()->getTracker(); + if (e->GetType() == eTYPE_ITEMENTITY) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); } - if (e->GetType() == eTYPE_ARROW) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); - } - if (e->GetType() == eTYPE_EXPERIENCEORB) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); + if (e->GetType() == eTYPE_ARROW) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); + } + if (e->GetType() == eTYPE_EXPERIENCEORB) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); } } Player::take(e, orgCount); containerMenu->broadcastChanges(); } -void ServerPlayer::swing() -{ - if (!swinging) - { +void ServerPlayer::swing() { + if (!swinging) { swingTime = -1; swinging = true; - getLevel()->getTracker()->broadcast(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) ); + getLevel()->getTracker()->broadcast( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::SWING))); } } -Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, bool bTestUse) -{ +Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, + bool bTestUse) { BedSleepingResult result = Player::startSleepInBed(x, y, z, bTestUse); - if (result == OK) - { - std::shared_ptr p = std::shared_ptr( new EntityActionAtPositionPacket(shared_from_this(), EntityActionAtPositionPacket::START_SLEEP, x, y, z) ); + if (result == OK) { + std::shared_ptr p = + std::shared_ptr( + new EntityActionAtPositionPacket( + shared_from_this(), + EntityActionAtPositionPacket::START_SLEEP, x, y, z)); getLevel()->getTracker()->broadcast(shared_from_this(), p); connection->teleport(this->x, this->y, this->z, yRot, xRot); connection->send(p); @@ -795,210 +847,215 @@ Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, boo return result; } -void ServerPlayer::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint) -{ - if (isSleeping()) - { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::WAKE_UP) ) ); +void ServerPlayer::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint) { + if (isSleeping()) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::WAKE_UP))); } Player::stopSleepInBed(forcefulWakeUp, updateLevelList, saveRespawnPoint); if (connection != NULL) connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::ride(std::shared_ptr e) -{ +void ServerPlayer::ride(std::shared_ptr e) { Player::ride(e); - connection->send( std::shared_ptr( new SetRidingPacket(shared_from_this(), riding) ) ); + connection->send(std::shared_ptr( + new SetRidingPacket(shared_from_this(), riding))); - // 4J Removed this - The act of riding will be handled on the client and will change the position - // of the player. If we also teleport it then we can end up with a repeating movements, e.g. bouncing - // up and down after exiting a boat due to slight differences in position on the client and server - //connection->teleport(x, y, z, yRot, xRot); + // 4J Removed this - The act of riding will be handled on the client and + // will change the position of the player. If we also teleport it then we + // can end up with a repeating movements, e.g. bouncing up and down after + // exiting a boat due to slight differences in position on the client and + // server + // connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::checkFallDamage(double ya, bool onGround) -{ +void ServerPlayer::checkFallDamage(double ya, bool onGround) {} + +void ServerPlayer::doCheckFallDamage(double ya, bool onGround) { + Player::checkFallDamage(ya, onGround); } -void ServerPlayer::doCheckFallDamage(double ya, bool onGround) -{ - Player::checkFallDamage(ya, onGround); +void ServerPlayer::nextContainerCounter() { + containerCounter = (containerCounter % 100) + 1; } -void ServerPlayer::nextContainerCounter() -{ - containerCounter = (containerCounter % 100) + 1; +bool ServerPlayer::startCrafting(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::WORKBENCH, 0, 9))); + containerMenu = new CraftingMenu(inventory, level, x, y, z); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open crafting container when one was " + "already open\n"); + } + + return true; } -bool ServerPlayer::startCrafting(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::WORKBENCH, 0, 9) ) ); - containerMenu = new CraftingMenu(inventory, level, x, y, z); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open crafting container when one was already open\n"); - } - - return true; +bool ServerPlayer::startEnchanting(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::ENCHANTMENT, 0, 9))); + containerMenu = new EnchantmentMenu(inventory, level, x, y, z); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open enchanting container when one was " + "already open\n"); + } + + return true; } -bool ServerPlayer::startEnchanting(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::ENCHANTMENT, 0, 9) )); - containerMenu = new EnchantmentMenu(inventory, level, x, y, z); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } +bool ServerPlayer::startRepairing(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::REPAIR_TABLE, 0, 9))); + containerMenu = new RepairMenu( + inventory, level, x, y, z, + std::dynamic_pointer_cast(shared_from_this())); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open enchanting container when one was " + "already open\n"); + } - return true; + return true; } -bool ServerPlayer::startRepairing(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr ( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::REPAIR_TABLE, 0, 9)) ); - containerMenu = new RepairMenu(inventory, level, x, y, z, std::dynamic_pointer_cast(shared_from_this())); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } +bool ServerPlayer::openContainer(std::shared_ptr container) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::CONTAINER, + container->getName(), container->getContainerSize()))); - return true; + containerMenu = new ContainerMenu(inventory, container); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open container when one was already open\n"); + } + + return true; } -bool ServerPlayer::openContainer(std::shared_ptr container) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::CONTAINER, container->getName(), container->getContainerSize()) ) ); +bool ServerPlayer::openFurnace(std::shared_ptr furnace) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::FURNACE, 0, + furnace->getContainerSize()))); + containerMenu = new FurnaceMenu(inventory, furnace); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open furnace when one was already open\n"); + } - containerMenu = new ContainerMenu(inventory, container); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open container when one was already open\n"); - } - - return true; + return true; } -bool ServerPlayer::openFurnace(std::shared_ptr furnace) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::FURNACE, 0, furnace->getContainerSize()) ) ); - containerMenu = new FurnaceMenu(inventory, furnace); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open furnace when one was already open\n"); - } +bool ServerPlayer::openTrap(std::shared_ptr trap) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send(std::shared_ptr( + new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRAP, + 0, trap->getContainerSize()))); + containerMenu = new TrapMenu(inventory, trap); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open dispenser when one was already open\n"); + } - return true; + return true; } -bool ServerPlayer::openTrap(std::shared_ptr trap) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRAP, 0, trap->getContainerSize()) ) ); - containerMenu = new TrapMenu(inventory, trap); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open dispenser when one was already open\n"); - } - - return true; +bool ServerPlayer::openBrewingStand( + std::shared_ptr brewingStand) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::BREWING_STAND, 0, + brewingStand->getContainerSize()))); + containerMenu = new BrewingStandMenu(inventory, brewingStand); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open brewing stand when one was already " + "open\n"); + } + + return true; } -bool ServerPlayer::openBrewingStand(std::shared_ptr brewingStand) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::BREWING_STAND, 0, brewingStand->getContainerSize()))); - containerMenu = new BrewingStandMenu(inventory, brewingStand); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open brewing stand when one was already open\n"); - } +bool ServerPlayer::openTrading(std::shared_ptr traderTarget) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + containerMenu = new MerchantMenu(inventory, traderTarget, level); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + std::shared_ptr container = + ((MerchantMenu*)containerMenu)->getTradeContainer(); - return true; + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::TRADER_NPC, + container->getName(), container->getContainerSize()))); + + MerchantRecipeList* offers = traderTarget->getOffers( + std::dynamic_pointer_cast(shared_from_this())); + if (offers != NULL) { + ByteArrayOutputStream rawOutput; + DataOutputStream output(&rawOutput); + + // just to make sure the offers are matched to the container + output.writeInt(containerCounter); + offers->writeToStream(&output); + + connection->send(std::shared_ptr( + new CustomPayloadPacket(CustomPayloadPacket::TRADER_LIST_PACKET, + rawOutput.toByteArray()))); + } + } else { + app.DebugPrintf( + "ServerPlayer tried to open trading menu when one was already " + "open\n"); + } + + return true; } -bool ServerPlayer::openTrading(std::shared_ptr traderTarget) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - containerMenu = new MerchantMenu(inventory, traderTarget, level); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - std::shared_ptr container = ((MerchantMenu *) containerMenu)->getTradeContainer(); - - connection->send(std::shared_ptr(new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRADER_NPC, container->getName(), container->getContainerSize()))); - - MerchantRecipeList *offers = traderTarget->getOffers(std::dynamic_pointer_cast(shared_from_this())); - if (offers != NULL) - { - ByteArrayOutputStream rawOutput; - DataOutputStream output(&rawOutput); - - // just to make sure the offers are matched to the container - output.writeInt(containerCounter); - offers->writeToStream(&output); - - connection->send(std::shared_ptr( new CustomPayloadPacket(CustomPayloadPacket::TRADER_LIST_PACKET, rawOutput.toByteArray()))); - } - } - else - { - app.DebugPrintf("ServerPlayer tried to open trading menu when one was already open\n"); - } - - return true; -} - -void ServerPlayer::slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr item) -{ - if (dynamic_cast(container->getSlot(slotIndex))) - { +void ServerPlayer::slotChanged(AbstractContainerMenu* container, int slotIndex, + std::shared_ptr item) { + if (dynamic_cast(container->getSlot(slotIndex))) { return; } - if (ignoreSlotUpdateHack) - { + if (ignoreSlotUpdateHack) { // Do not send this packet! // // This is a horrible hack that makes sure that inventory clicks @@ -1007,28 +1064,29 @@ void ServerPlayer::slotChanged(AbstractContainerMenu *container, int slotIndex, return; } - connection->send( std::shared_ptr( new ContainerSetSlotPacket(container->containerId, slotIndex, item) ) ); - + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(container->containerId, slotIndex, item))); } -void ServerPlayer::refreshContainer(AbstractContainerMenu *menu) -{ - std::vector > *items = menu->getItems(); - refreshContainer(menu, items); - delete items; +void ServerPlayer::refreshContainer(AbstractContainerMenu* menu) { + std::vector >* items = menu->getItems(); + refreshContainer(menu, items); + delete items; } -void ServerPlayer::refreshContainer(AbstractContainerMenu *container, std::vector > *items) -{ - connection->send( std::shared_ptr( new ContainerSetContentPacket(container->containerId, items) ) ); - connection->send( std::shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); +void ServerPlayer::refreshContainer( + AbstractContainerMenu* container, + std::vector >* items) { + connection->send(std::shared_ptr( + new ContainerSetContentPacket(container->containerId, items))); + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(-1, -1, inventory->getCarried()))); } -void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, int value) -{ - // 4J - added, so that furnace updates also have this hack - if (ignoreSlotUpdateHack) - { +void ServerPlayer::setContainerData(AbstractContainerMenu* container, int id, + int value) { + // 4J - added, so that furnace updates also have this hack + if (ignoreSlotUpdateHack) { // Do not send this packet! // // This is a horrible hack that makes sure that inventory clicks @@ -1036,408 +1094,449 @@ void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, in // client again. return; } - connection->send( std::shared_ptr( new ContainerSetDataPacket(container->containerId, id, value) ) ); + connection->send(std::shared_ptr( + new ContainerSetDataPacket(container->containerId, id, value))); } -void ServerPlayer::closeContainer() -{ - connection->send( std::shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); +void ServerPlayer::closeContainer() { + connection->send(std::shared_ptr( + new ContainerClosePacket(containerMenu->containerId))); doCloseContainer(); } -void ServerPlayer::broadcastCarriedItem() -{ - if (ignoreSlotUpdateHack) - { +void ServerPlayer::broadcastCarriedItem() { + if (ignoreSlotUpdateHack) { // Do not send this packet! // This is a horrible hack that makes sure that inventory clicks // that the client correctly predicted don't get sent out to the // client again. return; } - connection->send( std::shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(-1, -1, inventory->getCarried()))); } -void ServerPlayer::doCloseContainer() -{ - containerMenu->removed( std::dynamic_pointer_cast( shared_from_this() ) ); +void ServerPlayer::doCloseContainer() { + containerMenu->removed( + std::dynamic_pointer_cast(shared_from_this())); containerMenu = inventoryMenu; } -void ServerPlayer::setPlayerInput(float xa, float ya, bool jumping, bool sneaking, float xRot, float yRot) -{ +void ServerPlayer::setPlayerInput(float xa, float ya, bool jumping, + bool sneaking, float xRot, float yRot) { xxa = xa; yya = ya; this->jumping = jumping; - this->setSneaking(sneaking); - this->xRot = xRot; + this->setSneaking(sneaking); + this->xRot = xRot; this->yRot = yRot; } -void ServerPlayer::awardStat(Stat *stat, byteArray param) -{ - if (stat == NULL) - { - delete [] param.data; - return; - } +void ServerPlayer::awardStat(Stat* stat, byteArray param) { + if (stat == NULL) { + delete[] param.data; + return; + } - if (!stat->awardLocallyOnly) - { + if (!stat->awardLocallyOnly) { #ifndef _DURANGO - int count = *((int*)param.data); - delete [] param.data; + int count = *((int*)param.data); + delete[] param.data; - while (count > 100) - { - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, 100) ) ); + while (count > 100) { + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, 100))); count -= 100; } - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, count) ) ); + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, count))); #else - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, param) ) ); - // byteArray deleted in AwardStatPacket destructor. + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, param))); + // byteArray deleted in AwardStatPacket destructor. #endif - } - else delete [] param.data; + } else + delete[] param.data; } -void ServerPlayer::disconnect() -{ +void ServerPlayer::disconnect() { if (riding != NULL) ride(riding); - if (rider.lock() != NULL) rider.lock()->ride(shared_from_this() ); - if (this->m_isSleeping) - { + if (rider.lock() != NULL) rider.lock()->ride(shared_from_this()); + if (this->m_isSleeping) { stopSleepInBed(true, false, false); } } -void ServerPlayer::resetSentInfo() -{ - lastSentHealth = -99999999; +void ServerPlayer::resetSentInfo() { lastSentHealth = -99999999; } + +void ServerPlayer::displayClientMessage(int messageId) { + ChatPacket::EChatPacketMessage messageType = ChatPacket::e_ChatCustom; + // Convert the message id to an enum that will not change between game + // versions + switch (messageId) { + case IDS_TILE_BED_OCCUPIED: + messageType = ChatPacket::e_ChatBedOccupied; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NO_SLEEP: + messageType = ChatPacket::e_ChatBedNoSleep; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NOT_VALID: + messageType = ChatPacket::e_ChatBedNotValid; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NOTSAFE: + messageType = ChatPacket::e_ChatBedNotSafe; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_PLAYERSLEEP: + messageType = ChatPacket::e_ChatBedPlayerSleep; + // broadcast to all the other players in the game + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatBedPlayerSleep))); + } else { + player->connection->send(std::shared_ptr( + new ChatPacket(name, ChatPacket::e_ChatBedMeSleep))); + } + } + return; + break; + case IDS_PLAYER_ENTERED_END: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerEnteredEnd))); + } + } + break; + case IDS_PLAYER_LEFT_END: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send(std::shared_ptr( + new ChatPacket(name, ChatPacket::e_ChatPlayerLeftEnd))); + } + } + break; + case IDS_TILE_BED_MESLEEP: + messageType = ChatPacket::e_ChatBedMeSleep; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + + case IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxPigsSheepCows))); + } + } + break; + case IDS_MAX_CHICKENS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxChickens))); + } + } + break; + case IDS_MAX_SQUID_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxSquid))); + } + } + break; + case IDS_MAX_WOLVES_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxWolves))); + } + } + break; + case IDS_MAX_MOOSHROOMS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxMooshrooms))); + } + } + break; + case IDS_MAX_ENEMIES_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxEnemies))); + } + } + break; + + case IDS_MAX_VILLAGERS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxVillagers))); + } + } + break; + case IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, + ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); + } + } + break; + case IDS_MAX_CHICKENS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredChickens))); + } + } + break; + case IDS_MAX_MUSHROOMCOWS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); + } + } + break; + + case IDS_MAX_WOLVES_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredWolves))); + } + } + break; + + case IDS_CANT_SHEAR_MOOSHROOM: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerCantShearMooshroom))); + } + } + break; + + case IDS_MAX_HANGINGENTITIES: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxHangingEntities))); + } + } + break; + case IDS_CANT_SPAWN_IN_PEACEFUL: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, + ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); + } + } + break; + + case IDS_MAX_BOATS: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBoats))); + } + } + break; + + default: + app.DebugPrintf( + "Tried to send a chat packet to the player with an unhandled " + "messageId\n"); + assert(false); + break; + } + + // Language *language = Language::getInstance(); + // std::wstring languageString = + // app.GetString(messageId);//language->getElement(messageId); + // connection->send( std::shared_ptr( new ChatPacket(L"", + // messageType) ) ); } -void ServerPlayer::displayClientMessage(int messageId) -{ - ChatPacket::EChatPacketMessage messageType = ChatPacket::e_ChatCustom; - // Convert the message id to an enum that will not change between game versions - switch(messageId) - { - case IDS_TILE_BED_OCCUPIED: - messageType = ChatPacket::e_ChatBedOccupied; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NO_SLEEP: - messageType = ChatPacket::e_ChatBedNoSleep; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NOT_VALID: - messageType = ChatPacket::e_ChatBedNotValid; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NOTSAFE: - messageType = ChatPacket::e_ChatBedNotSafe; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_PLAYERSLEEP: - messageType = ChatPacket::e_ChatBedPlayerSleep; - // broadcast to all the other players in the game - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedPlayerSleep))); - } - else - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedMeSleep))); - } - } - return; - break; - case IDS_PLAYER_ENTERED_END: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerEnteredEnd))); - } - } - break; - case IDS_PLAYER_LEFT_END: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerLeftEnd))); - } - } - break; - case IDS_TILE_BED_MESLEEP: - messageType = ChatPacket::e_ChatBedMeSleep; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - - case IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxPigsSheepCows))); - } - } - break; - case IDS_MAX_CHICKENS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxChickens))); - } - } - break; - case IDS_MAX_SQUID_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxSquid))); - } - } - break; - case IDS_MAX_WOLVES_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxWolves))); - } - } - break; - case IDS_MAX_MOOSHROOMS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxMooshrooms))); - } - } - break; - case IDS_MAX_ENEMIES_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxEnemies))); - } - } - break; - - case IDS_MAX_VILLAGERS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxVillagers))); - } - } - break; - case IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); - } - } - break; - case IDS_MAX_CHICKENS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredChickens))); - } - } - break; - case IDS_MAX_MUSHROOMCOWS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); - } - } - break; - - case IDS_MAX_WOLVES_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredWolves))); - } - } - break; - - case IDS_CANT_SHEAR_MOOSHROOM: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantShearMooshroom))); - } - } - break; - - - case IDS_MAX_HANGINGENTITIES: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxHangingEntities))); - } - } - break; - case IDS_CANT_SPAWN_IN_PEACEFUL: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); - } - } - break; - - case IDS_MAX_BOATS: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBoats))); - } - } - break; - - default: - app.DebugPrintf("Tried to send a chat packet to the player with an unhandled messageId\n"); - assert( false ); - break; - } - - //Language *language = Language::getInstance(); - //std::wstring languageString = app.GetString(messageId);//language->getElement(messageId); - //connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); +void ServerPlayer::completeUsingItem() { + connection->send(std::shared_ptr( + new EntityEventPacket(entityId, EntityEvent::USE_ITEM_COMPLETE))); + Player::completeUsingItem(); } -void ServerPlayer::completeUsingItem() -{ - connection->send(std::shared_ptr( new EntityEventPacket(entityId, EntityEvent::USE_ITEM_COMPLETE) ) ); - Player::completeUsingItem(); +void ServerPlayer::startUsingItem(std::shared_ptr instance, + int duration) { + Player::startUsingItem(instance, duration); + + if (instance != NULL && instance->getItem() != NULL && + instance->getItem()->getUseAnimation(instance) == UseAnim_eat) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::EAT))); + } } -void ServerPlayer::startUsingItem(std::shared_ptr instance, int duration) -{ - Player::startUsingItem(instance, duration); - - if (instance != NULL && instance->getItem() != NULL && instance->getItem()->getUseAnimation(instance) == UseAnim_eat) - { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::EAT) ) ); - } +void ServerPlayer::restoreFrom(std::shared_ptr oldPlayer, + bool restoreAll) { + Player::restoreFrom(oldPlayer, restoreAll); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; + entitiesToRemove = + std::dynamic_pointer_cast(oldPlayer)->entitiesToRemove; } -void ServerPlayer::restoreFrom(std::shared_ptr oldPlayer, bool restoreAll) -{ - Player::restoreFrom(oldPlayer, restoreAll); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - entitiesToRemove = std::dynamic_pointer_cast(oldPlayer)->entitiesToRemove; +void ServerPlayer::onEffectAdded(MobEffectInstance* effect) { + Player::onEffectAdded(effect); + connection->send(std::shared_ptr( + new UpdateMobEffectPacket(entityId, effect))); } -void ServerPlayer::onEffectAdded(MobEffectInstance *effect) -{ - Player::onEffectAdded(effect); - connection->send(std::shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::onEffectUpdated(MobEffectInstance* effect) { + Player::onEffectUpdated(effect); + connection->send(std::shared_ptr( + new UpdateMobEffectPacket(entityId, effect))); } - -void ServerPlayer::onEffectUpdated(MobEffectInstance *effect) -{ - Player::onEffectUpdated(effect); - connection->send(std::shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::onEffectRemoved(MobEffectInstance* effect) { + Player::onEffectRemoved(effect); + connection->send(std::shared_ptr( + new RemoveMobEffectPacket(entityId, effect))); } - -void ServerPlayer::onEffectRemoved(MobEffectInstance *effect) -{ - Player::onEffectRemoved(effect); - connection->send(std::shared_ptr( new RemoveMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::teleportTo(double x, double y, double z) { + connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::teleportTo(double x, double y, double z) -{ - connection->teleport(x, y, z, yRot, xRot); +void ServerPlayer::crit(std::shared_ptr entity) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), std::shared_ptr(new AnimatePacket( + entity, AnimatePacket::CRITICAL_HIT))); } -void ServerPlayer::crit(std::shared_ptr entity) -{ - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(entity, AnimatePacket::CRITICAL_HIT) )); +void ServerPlayer::magicCrit(std::shared_ptr entity) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), std::shared_ptr(new AnimatePacket( + entity, AnimatePacket::MAGIC_CRITICAL_HIT))); } -void ServerPlayer::magicCrit(std::shared_ptr entity) -{ - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(entity, AnimatePacket::MAGIC_CRITICAL_HIT) )); +void ServerPlayer::onUpdateAbilities() { + if (connection == NULL) return; + connection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&abilities))); } -void ServerPlayer::onUpdateAbilities() -{ - if (connection == NULL) return; - connection->send(std::shared_ptr(new PlayerAbilitiesPacket(&abilities))); +ServerLevel* ServerPlayer::getLevel() { return (ServerLevel*)level; } + +void ServerPlayer::setGameMode(GameType* mode) { + gameMode->setGameModeForPlayer(mode); + connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, mode->getId()))); } -ServerLevel *ServerPlayer::getLevel() -{ - return (ServerLevel *) level; +void ServerPlayer::sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type /*= e_ChatCustom*/, + int customData /*= -1*/, const std::wstring& additionalMessage /*= L""*/) { + connection->send(std::shared_ptr( + new ChatPacket(message, type, customData, additionalMessage))); } -void ServerPlayer::setGameMode(GameType *mode) -{ - gameMode->setGameModeForPlayer(mode); - connection->send(std::shared_ptr(new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, mode->getId()))); -} - -void ServerPlayer::sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type /*= e_ChatCustom*/, int customData /*= -1*/, const std::wstring& additionalMessage /*= L""*/) -{ - connection->send(std::shared_ptr(new ChatPacket(message,type,customData,additionalMessage))); -} - -bool ServerPlayer::hasPermission(EGameCommand command) -{ - return server->getPlayers()->isOp(std::dynamic_pointer_cast(shared_from_this())); +bool ServerPlayer::hasPermission(EGameCommand command) { + return server->getPlayers()->isOp( + std::dynamic_pointer_cast(shared_from_this())); } // 4J - Don't use -//void ServerPlayer::updateOptions(std::shared_ptr packet) +// void ServerPlayer::updateOptions(std::shared_ptr +// packet) //{ // // 4J - Don't need // //if (language.getLanguageList().containsKey(packet.getLanguage())) @@ -1446,7 +1545,8 @@ bool ServerPlayer::hasPermission(EGameCommand command) // //} // // int dist = 16 * 16 >> packet->getViewDistance(); -// if (dist > PlayerChunkMap::MIN_VIEW_DISTANCE && dist < PlayerChunkMap::MAX_VIEW_DISTANCE) +// if (dist > PlayerChunkMap::MIN_VIEW_DISTANCE && dist < +//PlayerChunkMap::MAX_VIEW_DISTANCE) // { // this->viewDistance = dist; // } @@ -1455,64 +1555,63 @@ bool ServerPlayer::hasPermission(EGameCommand command) // canChatColor = packet->getChatColors(); // // // 4J - Don't need -// //if (server.isSingleplayer() && server.getSingleplayerName().equals(name)) +// //if (server.isSingleplayer() && +//server.getSingleplayerName().equals(name)) // //{ // // server.setDifficulty(packet.getDifficulty()); // //} //} -int ServerPlayer::getViewDistance() -{ - return viewDistance; -} +int ServerPlayer::getViewDistance() { return viewDistance; } -//bool ServerPlayer::canChatInColor() +// bool ServerPlayer::canChatInColor() //{ // return canChatColor; -//} +// } // -//int ServerPlayer::getChatVisibility() +// int ServerPlayer::getChatVisibility() //{ // return chatVisibility; -//} +// } -// Get an index that can be used to uniquely reference this chunk from either dimension -int ServerPlayer::getFlagIndexForChunk(const ChunkPos& pos, int dimension) -{ - // Scale pos x & z up by 16 as getGlobalIndexForChunk is expecting tile rather than chunk coords - return LevelRenderer::getGlobalIndexForChunk(pos.x * 16 , 0, pos.z * 16, dimension ) / (Level::maxBuildHeight / 16); // dividing here by number of renderer chunks in one column; +// Get an index that can be used to uniquely reference this chunk from either +// dimension +int ServerPlayer::getFlagIndexForChunk(const ChunkPos& pos, int dimension) { + // Scale pos x & z up by 16 as getGlobalIndexForChunk is expecting tile + // rather than chunk coords + return LevelRenderer::getGlobalIndexForChunk(pos.x * 16, 0, pos.z * 16, + dimension) / + (Level::maxBuildHeight / + 16); // dividing here by number of renderer chunks in one column; } // 4J Added, returns a number which is subtracted from the default view distance -int ServerPlayer::getPlayerViewDistanceModifier() -{ - int value = 0; +int ServerPlayer::getPlayerViewDistanceModifier() { + int value = 0; - if( !connection->isLocal() ) - { - INetworkPlayer *player = connection->getNetworkPlayer(); + if (!connection->isLocal()) { + INetworkPlayer* player = connection->getNetworkPlayer(); - if( player != NULL ) - { - int rtt = player->GetCurrentRtt(); + if (player != NULL) { + int rtt = player->GetCurrentRtt(); - value = rtt >> 6; + value = rtt >> 6; - if(value > 4) value = 4; - } - } + if (value > 4) value = 4; + } + } - return value; + return value; } -void ServerPlayer::handleCollectItem(std::shared_ptr item) -{ - if(gameMode->getGameRules() != NULL) gameMode->getGameRules()->onCollectItem(item); +void ServerPlayer::handleCollectItem(std::shared_ptr item) { + if (gameMode->getGameRules() != NULL) + gameMode->getGameRules()->onCollectItem(item); } #ifndef _CONTENT_PACKAGE -void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, double nXRot) -{ - connection->teleport(x, y, z, nYRot, nXRot); +void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, + double nXRot) { + connection->teleport(x, y, z, nYRot, nXRot); } #endif diff --git a/Minecraft.Client/Player/ServerPlayer.h b/Minecraft.Client/Player/ServerPlayer.h index 378186ebb..f3f4c5c45 100644 --- a/Minecraft.Client/Player/ServerPlayer.h +++ b/Minecraft.Client/Player/ServerPlayer.h @@ -12,153 +12,183 @@ class Entity; class BrewingStandTileEntity; class Merchant; - -class ServerPlayer : public Player, public net_minecraft_world_inventory::ContainerListener -{ +class ServerPlayer : public Player, + public net_minecraft_world_inventory::ContainerListener { public: - eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; } - std::shared_ptr connection; - MinecraftServer *server; - ServerPlayerGameMode *gameMode; + eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; } + std::shared_ptr connection; + MinecraftServer* server; + ServerPlayerGameMode* gameMode; double lastMoveX, lastMoveZ; std::list chunksToSend; - std::vector entitiesToRemove; + std::vector entitiesToRemove; std::unordered_set seenChunks; int spewTimer; - // 4J-Added, for 'Adventure Time' achievement. - Biome *currentBiome; + // 4J-Added, for 'Adventure Time' achievement. + Biome* currentBiome; private: - int lastSentHealth; - int lastSentFood; - bool lastFoodSaturationZero; - int lastSentExp; + int lastSentHealth; + int lastSentFood; + bool lastFoodSaturationZero; + int lastSentExp; int invulnerableTime; - int viewDistance; - int lastBrupSendTickCount; // 4J Added + int viewDistance; + int lastBrupSendTickCount; // 4J Added public: - ServerPlayer(MinecraftServer *server, Level *level, const std::wstring& name, ServerPlayerGameMode *gameMode); - ~ServerPlayer(); - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + ServerPlayer(MinecraftServer* server, Level* level, + const std::wstring& name, ServerPlayerGameMode* gameMode); + ~ServerPlayer(); + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added - virtual void readAdditionalSaveData(CompoundTag *entityTag); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void withdrawExperienceLevels(int amount); + virtual void readAdditionalSaveData(CompoundTag* entityTag); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void withdrawExperienceLevels(int amount); void initMenu(); private: - ItemInstanceArray lastCarried; + ItemInstanceArray lastCarried; public: - virtual ItemInstanceArray getEquipmentSlots(); + virtual ItemInstanceArray getEquipmentSlots(); + protected: - virtual void setDefaultHeadHeight(); + virtual void setDefaultHeadHeight(); + public: - virtual float getHeadHeight(); + virtual float getHeadHeight(); virtual void tick(); - void flushEntitiesToRemove(); + void flushEntitiesToRemove(); virtual std::shared_ptr getCarried(int slot); - virtual void die(DamageSource *source); - virtual bool hurt(DamageSource *dmgSource, int dmg); - virtual bool isPlayerVersusPlayer(); - void doTick(bool sendChunks, bool dontDelayChunks = false, bool ignorePortal = false); - void doTickA(); - void doChunkSendingTick(bool dontDelayChunks); - void doTickB(bool ignorePortal); - virtual void changeDimension(int i); + virtual void die(DamageSource* source); + virtual bool hurt(DamageSource* dmgSource, int dmg); + virtual bool isPlayerVersusPlayer(); + void doTick(bool sendChunks, bool dontDelayChunks = false, + bool ignorePortal = false); + void doTickA(); + void doChunkSendingTick(bool dontDelayChunks); + void doTickB(bool ignorePortal); + virtual void changeDimension(int i); + private: - void broadcast(std::shared_ptr te, bool delay = false); + void broadcast(std::shared_ptr te, bool delay = false); + public: virtual void take(std::shared_ptr e, int orgCount); virtual void swing(); - virtual BedSleepingResult startSleepInBed(int x, int y, int z, bool bTestUse = false); + virtual BedSleepingResult startSleepInBed(int x, int y, int z, + bool bTestUse = false); public: - virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); + virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint); virtual void ride(std::shared_ptr e); + protected: - virtual void checkFallDamage(double ya, bool onGround); -public: - void doCheckFallDamage(double ya, bool onGround); -private: - int containerCounter; -public: - bool ignoreSlotUpdateHack; - int latency; - bool wonGame; - bool m_enteredEndExitPortal; // 4J Added - -private: - void nextContainerCounter(); + virtual void checkFallDamage(double ya, bool onGround); public: - virtual bool startCrafting(int x, int y, int z); // 4J added bool return - virtual bool startEnchanting(int x, int y, int z); // 4J added bool return - virtual bool startRepairing(int x, int y, int z); // 4J added bool return - virtual bool openContainer(std::shared_ptr container); // 4J added bool return - virtual bool openFurnace(std::shared_ptr furnace); // 4J added bool return - virtual bool openTrap(std::shared_ptr trap); // 4J added bool return - virtual bool openBrewingStand(std::shared_ptr brewingStand); // 4J added bool return - virtual bool openTrading(std::shared_ptr traderTarget); // 4J added bool return - virtual void slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr item); - void refreshContainer(AbstractContainerMenu *menu); - virtual void refreshContainer(AbstractContainerMenu *container, std::vector > *items); - virtual void setContainerData(AbstractContainerMenu *container, int id, int value); + void doCheckFallDamage(double ya, bool onGround); + +private: + int containerCounter; + +public: + bool ignoreSlotUpdateHack; + int latency; + bool wonGame; + bool m_enteredEndExitPortal; // 4J Added + +private: + void nextContainerCounter(); + +public: + virtual bool startCrafting(int x, int y, int z); // 4J added bool return + virtual bool startEnchanting(int x, int y, int z); // 4J added bool return + virtual bool startRepairing(int x, int y, int z); // 4J added bool return + virtual bool openContainer( + std::shared_ptr container); // 4J added bool return + virtual bool openFurnace( + std::shared_ptr furnace); // 4J added bool return + virtual bool openTrap( + std::shared_ptr trap); // 4J added bool return + virtual bool openBrewingStand(std::shared_ptr + brewingStand); // 4J added bool return + virtual bool openTrading( + std::shared_ptr traderTarget); // 4J added bool return + virtual void slotChanged(AbstractContainerMenu* container, int slotIndex, + std::shared_ptr item); + void refreshContainer(AbstractContainerMenu* menu); + virtual void refreshContainer( + AbstractContainerMenu* container, + std::vector >* items); + virtual void setContainerData(AbstractContainerMenu* container, int id, + int value); virtual void closeContainer(); void broadcastCarriedItem(); void doCloseContainer(); - void setPlayerInput(float xa, float ya, bool jumping, bool sneaking, float xRot, float yRot); + void setPlayerInput(float xa, float ya, bool jumping, bool sneaking, + float xRot, float yRot); - virtual void awardStat(Stat *stat, byteArray param); + virtual void awardStat(Stat* stat, byteArray param); - void disconnect(); + void disconnect(); void resetSentInfo(); virtual void displayClientMessage(int messageId); protected: - virtual void completeUsingItem(); + virtual void completeUsingItem(); public: - virtual void startUsingItem(std::shared_ptr instance, int duration); - virtual void restoreFrom(std::shared_ptr oldPlayer, bool restoreAll); + virtual void startUsingItem(std::shared_ptr instance, + int duration); + virtual void restoreFrom(std::shared_ptr oldPlayer, + bool restoreAll); protected: - virtual void onEffectAdded(MobEffectInstance *effect); - virtual void onEffectUpdated(MobEffectInstance *effect); - virtual void onEffectRemoved(MobEffectInstance *effect); + virtual void onEffectAdded(MobEffectInstance* effect); + virtual void onEffectUpdated(MobEffectInstance* effect); + virtual void onEffectRemoved(MobEffectInstance* effect); public: - virtual void teleportTo(double x, double y, double z); + virtual void teleportTo(double x, double y, double z); virtual void crit(std::shared_ptr entity); virtual void magicCrit(std::shared_ptr entity); - void onUpdateAbilities(); - ServerLevel *getLevel(); - void setGameMode(GameType *mode); - void sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L""); - bool hasPermission(EGameCommand command); - // 4J - Don't use - //void updateOptions(std::shared_ptr packet); - int getViewDistance(); - //bool canChatInColor(); - //int getChatVisibility(); + void onUpdateAbilities(); + ServerLevel* getLevel(); + void setGameMode(GameType* mode); + void sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, + int customData = -1, const std::wstring& additionalMessage = L""); + bool hasPermission(EGameCommand command); + // 4J - Don't use + // void updateOptions(std::shared_ptr packet); + int getViewDistance(); + // bool canChatInColor(); + // int getChatVisibility(); public: - - static int getFlagIndexForChunk(const ChunkPos& pos, int dimension); // 4J - added - int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is subtracted from the default view distance + static int getFlagIndexForChunk(const ChunkPos& pos, + int dimension); // 4J - added + int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is + // subtracted from the default view + // distance public: - // 4J Stu - Added hooks for the game rules - virtual void handleCollectItem(std::shared_ptr item); + // 4J Stu - Added hooks for the game rules + virtual void handleCollectItem(std::shared_ptr item); #ifndef _CONTENT_PACKAGE - void debug_setPosition(double,double,double,double,double); + void debug_setPosition(double, double, double, double, double); #endif protected: - // 4J Added to record telemetry of player deaths, this should store the last source of damage - ETelemetryChallenges m_lastDamageSource; + // 4J Added to record telemetry of player deaths, this should store the last + // source of damage + ETelemetryChallenges m_lastDamageSource; }; diff --git a/Minecraft.Client/Player/ServerPlayerGameMode.cpp b/Minecraft.Client/Player/ServerPlayerGameMode.cpp index 50a1a5d55..cabbf4189 100644 --- a/Minecraft.Client/Player/ServerPlayerGameMode.cpp +++ b/Minecraft.Client/Player/ServerPlayerGameMode.cpp @@ -13,363 +13,341 @@ #include "../Level/MultiPlayerLevel.h" #include "../Rendering/LevelRenderer.h" -ServerPlayerGameMode::ServerPlayerGameMode(Level *level) -{ - // 4J - added initialisers - isDestroyingBlock = false; +ServerPlayerGameMode::ServerPlayerGameMode(Level* level) { + // 4J - added initialisers + isDestroyingBlock = false; destroyProgressStart = 0; xDestroyBlock = yDestroyBlock = zDestroyBlock = 0; gameTicks = 0; hasDelayedDestroy = false; delayedDestroyX = delayedDestroyY = delayedDestroyZ = 0; delayedTickStart = 0; - lastSentState = -1; - gameModeForPlayer = GameType::NOT_SET; + lastSentState = -1; + gameModeForPlayer = GameType::NOT_SET; - this->level = level; + this->level = level; - // 4J Added - m_gameRules = NULL; + // 4J Added + m_gameRules = NULL; } -ServerPlayerGameMode::~ServerPlayerGameMode() -{ - if(m_gameRules!=NULL) delete m_gameRules; +ServerPlayerGameMode::~ServerPlayerGameMode() { + if (m_gameRules != NULL) delete m_gameRules; } -void ServerPlayerGameMode::setGameModeForPlayer(GameType *gameModeForPlayer) -{ - this->gameModeForPlayer = gameModeForPlayer; - - gameModeForPlayer->updatePlayerAbilities(&(player->abilities)); - player->onUpdateAbilities(); +void ServerPlayerGameMode::setGameModeForPlayer(GameType* gameModeForPlayer) { + this->gameModeForPlayer = gameModeForPlayer; + gameModeForPlayer->updatePlayerAbilities(&(player->abilities)); + player->onUpdateAbilities(); } -GameType *ServerPlayerGameMode::getGameModeForPlayer() -{ - return gameModeForPlayer; +GameType* ServerPlayerGameMode::getGameModeForPlayer() { + return gameModeForPlayer; } -bool ServerPlayerGameMode::isSurvival() -{ - return gameModeForPlayer->isSurvival(); +bool ServerPlayerGameMode::isSurvival() { + return gameModeForPlayer->isSurvival(); } -bool ServerPlayerGameMode::isCreative() -{ - return gameModeForPlayer->isCreative(); +bool ServerPlayerGameMode::isCreative() { + return gameModeForPlayer->isCreative(); } -void ServerPlayerGameMode::updateGameMode(GameType *gameType) -{ - if (gameModeForPlayer == GameType::NOT_SET) - { - gameModeForPlayer = gameType; - } - setGameModeForPlayer(gameModeForPlayer); +void ServerPlayerGameMode::updateGameMode(GameType* gameType) { + if (gameModeForPlayer == GameType::NOT_SET) { + gameModeForPlayer = gameType; + } + setGameModeForPlayer(gameModeForPlayer); } -void ServerPlayerGameMode::tick() -{ +void ServerPlayerGameMode::tick() { gameTicks++; - if (hasDelayedDestroy) - { + if (hasDelayedDestroy) { int ticksSpentDestroying = gameTicks - delayedTickStart; - int t = level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ); - if (t == 0) - { - hasDelayedDestroy = false; - } - else - { - Tile *tile = Tile::tiles[t]; - float destroyProgress = tile->getDestroyProgress(player, player->level, delayedDestroyX, delayedDestroyY, delayedDestroyZ) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); + int t = + level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ); + if (t == 0) { + hasDelayedDestroy = false; + } else { + Tile* tile = Tile::tiles[t]; + float destroyProgress = + tile->getDestroyProgress(player, player->level, delayedDestroyX, + delayedDestroyY, delayedDestroyZ) * + (ticksSpentDestroying + 1); + int state = (int)(destroyProgress * 10); - if (state != lastSentState) - { - level->destroyTileProgress(player->entityId, delayedDestroyX, delayedDestroyY, delayedDestroyZ, state); - lastSentState = state; - } - if (destroyProgress >= 1) - { - hasDelayedDestroy = false; - destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ); - } - } - } - else if (isDestroyingBlock) - { - int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock); - Tile *tile = Tile::tiles[t]; - - if (tile == NULL) - { - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); - lastSentState = -1; - isDestroyingBlock = false; - } - else - { - int ticksSpentDestroying = gameTicks - destroyProgressStart; - float destroyProgress = tile->getDestroyProgress(player, player->level, xDestroyBlock, yDestroyBlock, zDestroyBlock) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); - - if (state != lastSentState) - { - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, state); - lastSentState = state; - } - } - } -} - -void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) -{ - if(!player->isAllowedToMine()) return; - - if (gameModeForPlayer->isReadOnly()) - { - return; - } - - if (isCreative()) - { - if(!level->extinguishFire(nullptr, x, y, z, face)) - { - destroyBlock(x, y, z); - } - return; - } - level->extinguishFire(player, x, y, z, face); - destroyProgressStart = gameTicks; - float progress = 1.0f; - int t = level->getTile(x, y, z); - if (t > 0) - { - Tile::tiles[t]->attack(level, x, y, z, player); - progress = Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z); - } - - if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<destroyTileProgress(player->entityId, x, y, z, state); - lastSentState = state; - } -} - -void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) -{ - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { -// int ticksSpentDestroying = gameTicks - destroyProgressStart; - - int t = level->getTile(x, y, z); - if (t != 0) - { - Tile *tile = Tile::tiles[t]; - - // MGH - removed checking for the destroy progress here, it has already been checked on the client before it sent the packet. - // fixes issues with this failing to destroy because of packets bunching up -// float destroyProgress = tile->getDestroyProgress(player, player->level, x, y, z) * (ticksSpentDestroying + 1); -// if (destroyProgress >= .7f || bIgnoreDestroyProgress) - { - isDestroyingBlock = false; - level->destroyTileProgress(player->entityId, x, y, z, -1); - destroyBlock(x, y, z); + if (state != lastSentState) { + level->destroyTileProgress(player->entityId, delayedDestroyX, + delayedDestroyY, delayedDestroyZ, + state); + lastSentState = state; + } + if (destroyProgress >= 1) { + hasDelayedDestroy = false; + destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ); + } + } + } else if (isDestroyingBlock) { + int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock); + Tile* tile = Tile::tiles[t]; + + if (tile == NULL) { + level->destroyTileProgress(player->entityId, xDestroyBlock, + yDestroyBlock, zDestroyBlock, -1); + lastSentState = -1; + isDestroyingBlock = false; + } else { + int ticksSpentDestroying = gameTicks - destroyProgressStart; + float destroyProgress = + tile->getDestroyProgress(player, player->level, xDestroyBlock, + yDestroyBlock, zDestroyBlock) * + (ticksSpentDestroying + 1); + int state = (int)(destroyProgress * 10); + + if (state != lastSentState) { + level->destroyTileProgress(player->entityId, xDestroyBlock, + yDestroyBlock, zDestroyBlock, state); + lastSentState = state; } -// else if (!hasDelayedDestroy) -// { -// isDestroyingBlock = false; -// hasDelayedDestroy = true; -// delayedDestroyX = x; -// delayedDestroyY = y; -// delayedDestroyZ = z; -// delayedTickStart = destroyProgressStart; -// } } } } -void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) -{ - isDestroyingBlock = false; - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); +void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) { + if (!player->isAllowedToMine()) return; + + if (gameModeForPlayer->isReadOnly()) { + return; + } + + if (isCreative()) { + if (!level->extinguishFire(nullptr, x, y, z, face)) { + destroyBlock(x, y, z); + } + return; + } + level->extinguishFire(player, x, y, z, face); + destroyProgressStart = gameTicks; + float progress = 1.0f; + int t = level->getTile(x, y, z); + if (t > 0) { + Tile::tiles[t]->attack(level, x, y, z, player); + progress = + Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z); + } + + if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() && + (player->GetDebugOptions() & + (1L << eDebugSetting_InstantDestroy))))) { + destroyBlock(x, y, z); + } else { + isDestroyingBlock = true; + xDestroyBlock = x; + yDestroyBlock = y; + zDestroyBlock = z; + int state = (int)(progress * 10); + level->destroyTileProgress(player->entityId, x, y, z, state); + lastSentState = state; + } } -bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) -{ - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; +void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { + // int ticksSpentDestroying = gameTicks - destroyProgressStart; + + int t = level->getTile(x, y, z); + if (t != 0) { + Tile* tile = Tile::tiles[t]; + + // MGH - removed checking for the destroy progress here, it has + // already been checked on the client before it sent the packet. + // fixes issues with this failing to destroy + //because of packets bunching up + // float destroyProgress = + // tile->getDestroyProgress(player, player->level, x, y, + // z) * (ticksSpentDestroying + 1); if (destroyProgress + // >= .7f || bIgnoreDestroyProgress) + { + isDestroyingBlock = false; + level->destroyTileProgress(player->entityId, x, y, z, -1); + destroyBlock(x, y, z); + } + // else if (!hasDelayedDestroy) + // { + // isDestroyingBlock = false; + // hasDelayedDestroy = true; + // delayedDestroyX = x; + // delayedDestroyY = y; + // delayedDestroyZ = z; + // delayedTickStart = destroyProgressStart; + // } + } + } +} + +void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) { + isDestroyingBlock = false; + level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, -1); +} + +bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) { + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; int data = level->getData(x, y, z); - if (oldTile != NULL) - { - oldTile->playerWillDestroy(level, x, y, z, data, player); - } + if (oldTile != NULL) { + oldTile->playerWillDestroy(level, x, y, z, data, player); + } bool changed = level->setTile(x, y, z, 0); - if (oldTile != NULL && changed) - { + if (oldTile != NULL && changed) { oldTile->destroy(level, x, y, z, data); } return changed; } -bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) -{ - if (gameModeForPlayer->isReadOnly()) - { - return false; - } +bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) { + if (gameModeForPlayer->isReadOnly()) { + return false; + } int t = level->getTile(x, y, z); int data = level->getData(x, y, z); - - level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); - - // 4J - In creative mode, the point where we need to tell the renderer that we are about to destroy a tile via destroyingTileAt is quite complicated. - // If the player being told is remote, then we always want the client to do it as it does the final update. If the player being told is local, - // then we need to update the renderer Here if we are sharing data between host & client as this is the final point where the original data is still intact. - // If the player being told is local, and we aren't sharing data between host & client, then we can just treat it as if it is a remote player and - // it can update the renderer. - bool clientToUpdateRenderer = false; - if( isCreative() ) - { - clientToUpdateRenderer = true; - if( std::dynamic_pointer_cast(player)->connection->isLocal() ) - { - // Establish whether we are sharing this chunk between client & server - MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id); - if( clientLevel ) - { - LevelChunk *lc = clientLevel->getChunkAt( x, z ); -#ifdef SHARING_ENABLED - if( lc->sharingTilesAndData ) - { - // We are sharing - this is the last point we can tell the renderer - Minecraft::GetInstance()->levelRenderer->destroyedTileManager->destroyingTileAt( clientLevel, x, y, z ); - // Don't need to ask the client to do this too - clientToUpdateRenderer = false; - } + level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + + // 4J - In creative mode, the point where we need to tell the renderer that + // we are about to destroy a tile via destroyingTileAt is quite complicated. + // If the player being told is remote, then we always want the client to do + // it as it does the final update. If the player being told is local, then + // we need to update the renderer Here if we are sharing data between host & + // client as this is the final point where the original data is still + // intact. If the player being told is local, and we aren't sharing data + // between host & client, then we can just treat it as if it is a remote + // player and it can update the renderer. + bool clientToUpdateRenderer = false; + if (isCreative()) { + clientToUpdateRenderer = true; + if (std::dynamic_pointer_cast(player) + ->connection->isLocal()) { + // Establish whether we are sharing this chunk between client & + // server + MultiPlayerLevel* clientLevel = + Minecraft::GetInstance()->getLevel(level->dimension->id); + if (clientLevel) { + LevelChunk* lc = clientLevel->getChunkAt(x, z); +#ifdef SHARING_ENABLED + if (lc->sharingTilesAndData) { + // We are sharing - this is the last point we can tell the + // renderer + Minecraft::GetInstance() + ->levelRenderer->destroyedTileManager->destroyingTileAt( + clientLevel, x, y, z); + + // Don't need to ask the client to do this too + clientToUpdateRenderer = false; + } #endif - } - } - } + } + } + } bool changed = superDestroyBlock(x, y, z); - if (isCreative()) - { - std::shared_ptr tup = std::shared_ptr( new TileUpdatePacket(x, y, z, level) ); - // 4J - a bit of a hack here, but if we want to tell the client that it needs to inform the renderer of a block being destroyed, then send a block 255 instead of a 0. This is handled in ClientConnection::handleTileUpdate - if( tup->block == 0 ) - { - if( clientToUpdateRenderer ) tup->block = 255; - } - player->connection->send( tup ); - } - else - { - std::shared_ptr item = player->getSelectedItem(); - bool canDestroy = player->canDestroy(Tile::tiles[t]); - if (item != NULL) - { - item->mineBlock(level, t, x, y, z, player); - if (item->count == 0) - { - player->removeSelectedItem(); - } - } - if (changed && canDestroy) - { - Tile::tiles[t]->playerDestroy(level, player, x, y, z, data); - } - } + if (isCreative()) { + std::shared_ptr tup = + std::shared_ptr( + new TileUpdatePacket(x, y, z, level)); + // 4J - a bit of a hack here, but if we want to tell the client that it + // needs to inform the renderer of a block being destroyed, then send a + // block 255 instead of a 0. This is handled in + // ClientConnection::handleTileUpdate + if (tup->block == 0) { + if (clientToUpdateRenderer) tup->block = 255; + } + player->connection->send(tup); + } else { + std::shared_ptr item = player->getSelectedItem(); + bool canDestroy = player->canDestroy(Tile::tiles[t]); + if (item != NULL) { + item->mineBlock(level, t, x, y, z, player); + if (item->count == 0) { + player->removeSelectedItem(); + } + } + if (changed && canDestroy) { + Tile::tiles[t]->playerDestroy(level, player, x, y, z, data); + } + } return changed; - } -bool ServerPlayerGameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - if(!player->isAllowedToUse(item)) return false; +bool ServerPlayerGameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly) { + if (!player->isAllowedToUse(item)) return false; int oldCount = item->count; - int oldAux = item->getAuxValue(); + int oldAux = item->getAuxValue(); std::shared_ptr itemInstance = item->use(level, player); - if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount) || (itemInstance != NULL && itemInstance->getUseDuration() > 0)) - { + if ((itemInstance != NULL && itemInstance != item) || + (itemInstance != NULL && itemInstance->count != oldCount) || + (itemInstance != NULL && itemInstance->getUseDuration() > 0)) { player->inventory->items[player->inventory->selected] = itemInstance; - if (isCreative()) - { - itemInstance->count = oldCount; - itemInstance->setAuxValue(oldAux); - } - if (itemInstance->count == 0) - { + if (isCreative()) { + itemInstance->count = oldCount; + itemInstance->setAuxValue(oldAux); + } + if (itemInstance->count == 0) { player->inventory->items[player->inventory->selected] = nullptr; } return true; } return false; - } -bool ServerPlayerGameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly, bool *pbUsedItem) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - int t = level->getTile(x, y, z); - if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) - { - if(bTestUseOnOnly) - { - if (Tile::tiles[t]->TestUse()) return true; - } - else - { - if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) - { - if(m_gameRules != NULL) m_gameRules->onUseTile(t,x,y,z); - return true; - } - } - } - +bool ServerPlayerGameMode::useItemOn(std::shared_ptr player, + Level* level, + std::shared_ptr item, int x, + int y, int z, int face, float clickX, + float clickY, float clickZ, + bool bTestUseOnOnly, bool* pbUsedItem) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + int t = level->getTile(x, y, z); + if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) { + if (bTestUseOnOnly) { + if (Tile::tiles[t]->TestUse()) return true; + } else { + if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, + clickY, clickZ)) { + if (m_gameRules != NULL) m_gameRules->onUseTile(t, x, y, z); + return true; + } + } + } + if (item == NULL || !player->isAllowedToUse(item)) return false; - if (isCreative()) - { - int aux = item->getAuxValue(); - int count = item->count; - bool success = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ); - item->setAuxValue(aux); - item->count = count; - return success; - } - else - { - return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); - } + if (isCreative()) { + int aux = item->getAuxValue(); + int count = item->count; + bool success = + item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ); + item->setAuxValue(aux); + item->count = count; + return success; + } else { + return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, + bTestUseOnOnly); + } } -void ServerPlayerGameMode::setLevel(ServerLevel *newLevel) -{ - level = newLevel; -} +void ServerPlayerGameMode::setLevel(ServerLevel* newLevel) { level = newLevel; } // 4J Added -void ServerPlayerGameMode::setGameRules(GameRulesInstance *rules) -{ - if(m_gameRules != NULL) delete m_gameRules; - m_gameRules = rules; +void ServerPlayerGameMode::setGameRules(GameRulesInstance* rules) { + if (m_gameRules != NULL) delete m_gameRules; + m_gameRules = rules; } \ No newline at end of file diff --git a/Minecraft.Client/Player/ServerPlayerGameMode.h b/Minecraft.Client/Player/ServerPlayerGameMode.h index c590f11e8..74440c69a 100644 --- a/Minecraft.Client/Player/ServerPlayerGameMode.h +++ b/Minecraft.Client/Player/ServerPlayerGameMode.h @@ -6,17 +6,16 @@ class ServerLevel; class GameRulesInstance; class GameType; -class ServerPlayerGameMode -{ +class ServerPlayerGameMode { public: - Level *level; - std::shared_ptr player; + Level* level; + std::shared_ptr player; private: - GameType *gameModeForPlayer; + GameType* gameModeForPlayer; private: - bool isDestroyingBlock; + bool isDestroyingBlock; int destroyProgressStart; int xDestroyBlock, yDestroyBlock, zDestroyBlock; int gameTicks; @@ -24,24 +23,25 @@ private: bool hasDelayedDestroy; int delayedDestroyX, delayedDestroyY, delayedDestroyZ; int delayedTickStart; - int lastSentState; + int lastSentState; private: - // 4J Added - GameRulesInstance *m_gameRules; -public: - void setGameRules(GameRulesInstance *rules); - GameRulesInstance *getGameRules() { return m_gameRules; } + // 4J Added + GameRulesInstance* m_gameRules; public: - ServerPlayerGameMode(Level *level); - ~ServerPlayerGameMode(); + void setGameRules(GameRulesInstance* rules); + GameRulesInstance* getGameRules() { return m_gameRules; } - void setGameModeForPlayer(GameType *gameModeForPlayer); - GameType *getGameModeForPlayer(); - bool isSurvival(); - bool isCreative(); - void updateGameMode(GameType *gameType); +public: + ServerPlayerGameMode(Level* level); + ~ServerPlayerGameMode(); + + void setGameModeForPlayer(GameType* gameModeForPlayer); + GameType* getGameModeForPlayer(); + bool isSurvival(); + bool isCreative(); + void updateGameMode(GameType* gameType); void tick(); void startDestroyBlock(int x, int y, int z, int face); @@ -53,8 +53,12 @@ private: public: bool destroyBlock(int x, int y, int z); - bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); + bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, bool bTestUseOnly = false); + bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, int z, + int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly = false, bool* pbUsedItem = NULL); - void setLevel(ServerLevel *newLevel); + void setLevel(ServerLevel* newLevel); }; \ No newline at end of file diff --git a/Minecraft.Client/Player/TrackedEntity.cpp b/Minecraft.Client/Player/TrackedEntity.cpp index fb10ea8d1..c6f58808b 100644 --- a/Minecraft.Client/Player/TrackedEntity.cpp +++ b/Minecraft.Client/Player/TrackedEntity.cpp @@ -20,19 +20,19 @@ #include "../Network/PlayerChunkMap.h" #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ -TrackedEntity::TrackedEntity(std::shared_ptr e, int range, int updateInterval, bool trackDelta) -{ - // 4J added initialisers +TrackedEntity::TrackedEntity(std::shared_ptr e, int range, + int updateInterval, bool trackDelta) { + // 4J added initialisers xap = yap = zap = 0; tickCount = 0; - xpu = ypu = zpu = 0; + xpu = ypu = zpu = 0; updatedPlayerVisibility = false; teleportDelay = 0; - moved = false; - - this->e = e; + moved = false; + + this->e = e; this->range = range; this->updateInterval = updateInterval; this->trackDelta = trackDelta; @@ -43,16 +43,15 @@ TrackedEntity::TrackedEntity(std::shared_ptr e, int range, int updateInt yRotp = Mth::floor(e->yRot * 256 / 360); xRotp = Mth::floor(e->xRot * 256 / 360); - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); } int c0a = 0, c0b = 0, c1a = 0, c1b = 0, c1c = 0, c2a = 0, c2b = 0; -void TrackedEntity::tick(EntityTracker *tracker, std::vector > *players) -{ +void TrackedEntity::tick(EntityTracker* tracker, + std::vector >* players) { moved = false; - if (!updatedPlayerVisibility || e->distanceToSqr(xpu, ypu, zpu) > 4 * 4) - { + if (!updatedPlayerVisibility || e->distanceToSqr(xpu, ypu, zpu) > 4 * 4) { xpu = e->x; ypu = e->y; zpu = e->z; @@ -61,870 +60,949 @@ void TrackedEntity::tick(EntityTracker *tracker, std::vectorriding) - { - wasRiding = e->riding; - broadcast(std::shared_ptr(new SetRidingPacket(e, e->riding))); - } - - // Moving forward special case for item frames - if (e->GetType()== eTYPE_ITEM_FRAME && tickCount % 10 == 0) - { - std::shared_ptr frame = std::dynamic_pointer_cast (e); - std::shared_ptr item = frame->getItem(); - - if (item != NULL && item->getItem()->id == Item::map_Id && !e->removed) - { - std::shared_ptr data = Item::map->getSavedData(item, e->level); - for (AUTO_VAR(it,players->begin() ); it != players->end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - data->tickCarriedBy(player, item); - - if (!player->removed && player->connection && player->connection->countDelayedPackets() <= 5) - { - std::shared_ptr packet = Item::map->getUpdatePacket(item, e->level, player); - if (packet != NULL) player->connection->send(packet); - } - } - } - - std::shared_ptr entityData = e->getEntityData(); - if (entityData->isDirty()) - { - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - } - else - { - if(e->riding == NULL) - { - teleportDelay++; - if (tickCount++ % updateInterval == 0 || e->hasImpulse) - { - int xn = Mth::floor(this->e->x * 32.0); - int yn = Mth::floor(this->e->y * 32.0); - int zn = Mth::floor(this->e->z * 32.0); - int yRotn = Mth::floor(e->yRot * 256 / 360); - int xRotn = Mth::floor(e->xRot * 256 / 360); - - - int xa = xn - xp; - int ya = yn - yp; - int za = zn - zp; - - std::shared_ptr packet = nullptr; - - // 4J - this pos flag used to be set based on abs(xn) etc. but that just seems wrong - bool pos = abs(xa) >= TOLERANCE_LEVEL || abs(ya) >= TOLERANCE_LEVEL || abs(za) >= TOLERANCE_LEVEL; - // 4J - changed rotation to be generally sent as a delta as well as position - int yRota = yRotn - yRotp; - int xRota = xRotn - xRotp; - // Keep rotation deltas in +/- 180 degree range - while( yRota > 127 ) yRota -= 256; - while( yRota < -128 ) yRota += 256; - while( xRota > 127 ) xRota -= 256; - while( xRota < -128 ) xRota += 256; - - bool rot = abs(yRota) >= TOLERANCE_LEVEL || abs(xRota) >= TOLERANCE_LEVEL; - - if (xa < -128 || xa >= 128 || ya < -128 || ya >= 128 || za < -128 || za >= 128 - // 4J Stu - I fixed the initialisation of teleportDelay in the ctor, but we managed this far without out - // and would prefer not to have all the extra traffix so ignore it - // 4J Stu - Fix for #9579 - GAMEPLAY: Boats with a player in them slowly sink under the water over time, and with no player in them they float into the sky. - || (e->GetType() == eTYPE_BOAT && teleportDelay > 20 * 20) - ) - { - teleportDelay = 0; - packet = std::shared_ptr( new TeleportEntityPacket(e->entityId, xn, yn, zn, (uint8_t) yRotn, (uint8_t) xRotn) ); - // printf("%d: New teleport rot %d\n",e->entityId,yRotn); - yRotp = yRotn; - xRotp = xRotn; - } - else - { - if (pos && rot) - { - // 4J If the movement is small enough, and there's no xrot, then use the new smaller packets - if( ( xa >= -16 ) && ( xa <= 15 ) && - ( za >= -16 ) && ( za <= 15 ) && - ( ya >= -32 ) && ( ya <= 31 ) && - ( xRota == 0 )) - { - // Clamp rotations that are too big - if( yRota < -16 ) - { - yRota = -16; - yRotn = yRotp + yRota; - } - else if( yRota > 15 ) - { - yRota = 15; - yRotn = yRotp + yRota; - } - // 5 bits each for x & z, and 6 for y - packet = std::shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, 0 ) ); - c0a++; - } - else - { - packet = std::shared_ptr( new MoveEntityPacket::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, (char) xRota) ); - // printf("%d: New posrot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); - c0b++; - } - } - else if (pos) - { - // 4J If the movement is small enough, then use the new smaller packets - if( ( xa >= -8 ) && ( xa <= 7 ) && - ( za >= -8 ) && ( za <= 7 ) && - ( ya >= -16 ) && ( ya <= 15 ) ) - { - // 4 bits each for x & z, and 5 for y - packet = std::shared_ptr( new MoveEntityPacketSmall::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); - c1a++; - } - - else if( ( xa >= -16 ) && ( xa <= 15 ) && - ( za >= -16 ) && ( za <= 15 ) && - ( ya >= -32 ) && ( ya <= 31 ) ) - { - // use the packet with small packet with rotation if we can - 5 bits each for x & z, and 6 for y - still a byte less than the alternative - packet = std::shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, 0, 0 )); - c1b++; - } - else - { - packet = std::shared_ptr( new MoveEntityPacket::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); - c1c++; - } - } - else if (rot) - { - // 4J If there's no x rotation, then use the new smaller packet type - if( xRota == 0 ) - { - // Clamp rotations that are too big - if( yRota < -16 ) - { - yRota = -16; - yRotn = yRotp + yRota; - } - else if( yRota > 15 ) - { - yRota = 15; - yRotn = yRotp + yRota; - } - packet = std::shared_ptr( new MoveEntityPacketSmall::Rot(e->entityId, (char) yRota, 0) ); - c2a++; - } - else - { - // printf("%d: New rot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); - packet = std::shared_ptr( new MoveEntityPacket::Rot(e->entityId, (char) yRota, (char) xRota) ); - c2b++; - } - } - } - - if (trackDelta) - { - double xad = e->xd - xap; - double yad = e->yd - yap; - double zad = e->zd - zap; - - double max = 0.02; - - double diff = xad * xad + yad * yad + zad * zad; - - if (diff > max * max || (diff > 0 && e->xd == 0 && e->yd == 0 && e->zd == 0)) - { - xap = e->xd; - yap = e->yd; - zap = e->zd; - broadcast( std::shared_ptr( new SetEntityMotionPacket(e->entityId, xap, yap, zap) ) ); - } - - } - - if (packet != NULL) - { - broadcast(packet); - } - - std::shared_ptr entityData = e->getEntityData(); - - if (entityData->isDirty()) - { - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - - int yHeadRot = Mth::floor(e->getYHeadRot() * 256 / 360); - if (abs(yHeadRot - yHeadRotp) >= TOLERANCE_LEVEL) - { - broadcast(std::shared_ptr(new RotateHeadPacket(e->entityId, (uint8_t) yHeadRot))); - yHeadRotp = yHeadRot; - } - - if (pos) - { - xp = xn; - yp = yn; - zp = zn; - } - if (rot) - { - yRotp = yRotn; - xRotp = xRotn; - } - - // if( std::dynamic_pointer_cast(e) != NULL ) - // { - // printf("%d: %d + %d = %d (%f)\n",e->entityId,xRotp,xRota,xRotn,e->xRot); - // } - } - - } - else // 4J-JEV: Added: Mobs in minecarts weren't synching their invisibility. - { - std::shared_ptr entityData = e->getEntityData(); - if (entityData->isDirty()) - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - e->hasImpulse = false; - } - - if (e->hurtMarked) - { - // broadcast(new AnimatePacket(e, AnimatePacket.HURT)); - broadcastAndSend( std::shared_ptr( new SetEntityMotionPacket(e) ) ); - e->hurtMarked = false; + if (wasRiding != e->riding) { + wasRiding = e->riding; + broadcast(std::shared_ptr( + new SetRidingPacket(e, e->riding))); } + // Moving forward special case for item frames + if (e->GetType() == eTYPE_ITEM_FRAME && tickCount % 10 == 0) { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + std::shared_ptr item = frame->getItem(); + + if (item != NULL && item->getItem()->id == Item::map_Id && + !e->removed) { + std::shared_ptr data = + Item::map->getSavedData(item, e->level); + for (AUTO_VAR(it, players->begin()); it != players->end(); ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + data->tickCarriedBy(player, item); + + if (!player->removed && player->connection && + player->connection->countDelayedPackets() <= 5) { + std::shared_ptr packet = + Item::map->getUpdatePacket(item, e->level, player); + if (packet != NULL) player->connection->send(packet); + } + } + } + + std::shared_ptr entityData = e->getEntityData(); + if (entityData->isDirty()) { + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, false))); + } + } else { + if (e->riding == NULL) { + teleportDelay++; + if (tickCount++ % updateInterval == 0 || e->hasImpulse) { + int xn = Mth::floor(this->e->x * 32.0); + int yn = Mth::floor(this->e->y * 32.0); + int zn = Mth::floor(this->e->z * 32.0); + int yRotn = Mth::floor(e->yRot * 256 / 360); + int xRotn = Mth::floor(e->xRot * 256 / 360); + + int xa = xn - xp; + int ya = yn - yp; + int za = zn - zp; + + std::shared_ptr packet = nullptr; + + // 4J - this pos flag used to be set based on abs(xn) etc. but + // that just seems wrong + bool pos = abs(xa) >= TOLERANCE_LEVEL || + abs(ya) >= TOLERANCE_LEVEL || + abs(za) >= TOLERANCE_LEVEL; + // 4J - changed rotation to be generally sent as a delta as well + // as position + int yRota = yRotn - yRotp; + int xRota = xRotn - xRotp; + // Keep rotation deltas in +/- 180 degree range + while (yRota > 127) yRota -= 256; + while (yRota < -128) yRota += 256; + while (xRota > 127) xRota -= 256; + while (xRota < -128) xRota += 256; + + bool rot = abs(yRota) >= TOLERANCE_LEVEL || + abs(xRota) >= TOLERANCE_LEVEL; + + if (xa < -128 || xa >= 128 || ya < -128 || ya >= 128 || + za < -128 || + za >= 128 + // 4J Stu - I fixed the initialisation of teleportDelay in + // the ctor, but we managed this far without out and would + // prefer not to have all the extra traffix so ignore it 4J + // Stu - Fix for #9579 - GAMEPLAY: Boats with a player in + // them slowly sink under the water over time, and with no + // player in them they float into the sky. + || + (e->GetType() == eTYPE_BOAT && teleportDelay > 20 * 20)) { + teleportDelay = 0; + packet = std::shared_ptr( + new TeleportEntityPacket(e->entityId, xn, yn, zn, + (uint8_t)yRotn, + (uint8_t)xRotn)); + // printf("%d: New teleport rot + //%d\n",e->entityId,yRotn); + yRotp = yRotn; + xRotp = xRotn; + } else { + if (pos && rot) { + // 4J If the movement is small enough, and there's no + // xrot, then use the new smaller packets + if ((xa >= -16) && (xa <= 15) && (za >= -16) && + (za <= 15) && (ya >= -32) && (ya <= 31) && + (xRota == 0)) { + // Clamp rotations that are too big + if (yRota < -16) { + yRota = -16; + yRotn = yRotp + yRota; + } else if (yRota > 15) { + yRota = 15; + yRotn = yRotp + yRota; + } + // 5 bits each for x & z, and 6 for y + packet = std::shared_ptr( + new MoveEntityPacketSmall::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + (char)yRota, 0)); + c0a++; + } else { + packet = std::shared_ptr( + new MoveEntityPacket::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + (char)yRota, (char)xRota)); + // printf("%d: New + //posrot %d + %d = + //%d\n",e->entityId,yRotp,yRota,yRotn); + c0b++; + } + } else if (pos) { + // 4J If the movement is small enough, then use the new + // smaller packets + if ((xa >= -8) && (xa <= 7) && (za >= -8) && + (za <= 7) && (ya >= -16) && (ya <= 15)) { + // 4 bits each for x & z, and 5 for y + packet = std::shared_ptr( + new MoveEntityPacketSmall::Pos( + e->entityId, (char)xa, (char)ya, (char)za)); + c1a++; + } + + else if ((xa >= -16) && (xa <= 15) && (za >= -16) && + (za <= 15) && (ya >= -32) && (ya <= 31)) { + // use the packet with small packet with rotation if + // we can - 5 bits each for x & z, and 6 for y - + // still a byte less than the alternative + packet = std::shared_ptr( + new MoveEntityPacketSmall::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + 0, 0)); + c1b++; + } else { + packet = std::shared_ptr( + new MoveEntityPacket::Pos(e->entityId, (char)xa, + (char)ya, (char)za)); + c1c++; + } + } else if (rot) { + // 4J If there's no x rotation, then use the new smaller + // packet type + if (xRota == 0) { + // Clamp rotations that are too big + if (yRota < -16) { + yRota = -16; + yRotn = yRotp + yRota; + } else if (yRota > 15) { + yRota = 15; + yRotn = yRotp + yRota; + } + packet = std::shared_ptr( + new MoveEntityPacketSmall::Rot(e->entityId, + (char)yRota, 0)); + c2a++; + } else { + // printf("%d: New + //rot %d + %d = + //%d\n",e->entityId,yRotp,yRota,yRotn); + packet = std::shared_ptr( + new MoveEntityPacket::Rot( + e->entityId, (char)yRota, (char)xRota)); + c2b++; + } + } + } + + if (trackDelta) { + double xad = e->xd - xap; + double yad = e->yd - yap; + double zad = e->zd - zap; + + double max = 0.02; + + double diff = xad * xad + yad * yad + zad * zad; + + if (diff > max * max || + (diff > 0 && e->xd == 0 && e->yd == 0 && e->zd == 0)) { + xap = e->xd; + yap = e->yd; + zap = e->zd; + broadcast(std::shared_ptr( + new SetEntityMotionPacket(e->entityId, xap, yap, + zap))); + } + } + + if (packet != NULL) { + broadcast(packet); + } + + std::shared_ptr entityData = + e->getEntityData(); + + if (entityData->isDirty()) { + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, + false))); + } + + int yHeadRot = Mth::floor(e->getYHeadRot() * 256 / 360); + if (abs(yHeadRot - yHeadRotp) >= TOLERANCE_LEVEL) { + broadcast(std::shared_ptr( + new RotateHeadPacket(e->entityId, (uint8_t)yHeadRot))); + yHeadRotp = yHeadRot; + } + + if (pos) { + xp = xn; + yp = yn; + zp = zn; + } + if (rot) { + yRotp = yRotn; + xRotp = xRotn; + } + + // if( std::dynamic_pointer_cast(e) + //!= NULL ) + // { + // printf("%d: %d + %d = %d + //(%f)\n",e->entityId,xRotp,xRota,xRotn,e->xRot); + // } + } + + } else // 4J-JEV: Added: Mobs in minecarts weren't synching their + // invisibility. + { + std::shared_ptr entityData = e->getEntityData(); + if (entityData->isDirty()) + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, false))); + } + e->hasImpulse = false; + } + + if (e->hurtMarked) { + // broadcast(new AnimatePacket(e, AnimatePacket.HURT)); + broadcastAndSend(std::shared_ptr( + new SetEntityMotionPacket(e))); + e->hurtMarked = false; + } } -void TrackedEntity::broadcast(std::shared_ptr packet) -{ - if( Packet::canSendToAnyClient( packet ) ) - { - // 4J-PB - due to the knockback on a player being hit, we need to send to all players, but limit the network traffic here to players that have not already had it sent to their system - std::vector< std::shared_ptr > sentTo; +void TrackedEntity::broadcast(std::shared_ptr packet) { + if (Packet::canSendToAnyClient(packet)) { + // 4J-PB - due to the knockback on a player being hit, we need to send + // to all players, but limit the network traffic here to players that + // have not already had it sent to their system + std::vector > sentTo; - // 4J - don't send to a player we've already sent this data to that shares the same machine. - // EntityMotionPacket used to limit themselves to sending once to each machine - // by only sending to the primary player on each machine. This was causing trouble for split screen - // as only the primary player would get a knockback velocity. Now these packets can be sent to any - // player, but we try to restrict the network impact this has by not resending to the one machine + // 4J - don't send to a player we've already sent this data to that + // shares the same machine. EntityMotionPacket used to limit themselves + // to sending once to each machine by only sending to the primary player + // on each machine. This was causing trouble for split screen as only + // the primary player would get a knockback velocity. Now these packets + // can be sent to any player, but we try to restrict the network impact + // this has by not resending to the one machine - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - std::shared_ptr player = *it; - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer =player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - // #ifdef _DEBUG - // std::shared_ptr emp= std::dynamic_pointer_cast (packet); - // if(emp!=NULL) - // { - // app.DebugPrintf("Not sending this SetEntityMotionPacket to player - it's already been sent to a player on their console\n"); - // } - // #endif - } - } - } - } - if( dontSend ) - { - continue; - } + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + std::shared_ptr player = *it; + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = + player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + // #ifdef _DEBUG + // std::shared_ptr + // emp= + // std::dynamic_pointer_cast + // (packet); if(emp!=NULL) + // { + // app.DebugPrintf("Not + // sending this SetEntityMotionPacket to player - + // it's already been sent to a player on their + // console\n"); + // } + // #endif + } + } + } + } + if (dontSend) { + continue; + } + (*it)->connection->send(packet); + sentTo.push_back(player); + } + } else { + // This packet hasn't got canSendToAnyClient set, so just send to + // everyone here, and it - (*it)->connection->send(packet); - sentTo.push_back(player); - } - } - else - { - // This packet hasn't got canSendToAnyClient set, so just send to everyone here, and it - - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - (*it)->connection->send(packet); - } - } + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + (*it)->connection->send(packet); + } + } } -void TrackedEntity::broadcastAndSend(std::shared_ptr packet) -{ - std::vector< std::shared_ptr > sentTo; +void TrackedEntity::broadcastAndSend(std::shared_ptr packet) { + std::vector > sentTo; broadcast(packet); - std::shared_ptr sp = std::dynamic_pointer_cast(e); - if (sp != NULL && sp->connection) - { + std::shared_ptr sp = + std::dynamic_pointer_cast(e); + if (sp != NULL && sp->connection) { sp->connection->send(packet); } } -void TrackedEntity::broadcastRemoved() -{ - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - (*it)->entitiesToRemove.push_back(e->entityId); - } +void TrackedEntity::broadcastRemoved() { + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + (*it)->entitiesToRemove.push_back(e->entityId); + } } -void TrackedEntity::removePlayer(std::shared_ptr sp) -{ - AUTO_VAR(it, seenBy.find( sp )); - if( it != seenBy.end() ) - { - seenBy.erase( it ); - } +void TrackedEntity::removePlayer(std::shared_ptr sp) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { + seenBy.erase(it); + } } // 4J-JEV: Added for code reuse. -TrackedEntity::eVisibility TrackedEntity::isVisible(EntityTracker *tracker, std::shared_ptr sp, bool forRider) -{ - // 4J Stu - We call update players when the entity has moved more than a certain amount at the start of it's tick - // Before this call we set xpu, ypu and zpu to the entities new position, but xp,yp and zp are the old position until later in the tick. - // Therefore we should use the new position for visibility checks - double xd = sp->x - xpu; //xp / 32; - double zd = sp->z - zpu; //zp / 32; +TrackedEntity::eVisibility TrackedEntity::isVisible( + EntityTracker* tracker, std::shared_ptr sp, bool forRider) { + // 4J Stu - We call update players when the entity has moved more than a + // certain amount at the start of it's tick Before this call we set xpu, ypu + // and zpu to the entities new position, but xp,yp and zp are the old + // position until later in the tick. Therefore we should use the new + // position for visibility checks + double xd = sp->x - xpu; // xp / 32; + double zd = sp->z - zpu; // zp / 32; - int playersRange = range; - if( playersRange > TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE ) - { - playersRange -= sp->getPlayerViewDistanceModifier(); - } + int playersRange = range; + if (playersRange > TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE) { + playersRange -= sp->getPlayerViewDistanceModifier(); + } - bool bVisible = xd >= -playersRange && xd <= playersRange && zd >= -playersRange && zd <= playersRange; - bool canBeSeenBy = canBySeenBy(sp); + bool bVisible = xd >= -playersRange && xd <= playersRange && + zd >= -playersRange && zd <= playersRange; + bool canBeSeenBy = canBySeenBy(sp); - // 4J - added. Try and find other players who are in the same dimension as this one and on the same machine, and extend our visibility - // so things are consider visible to this player if they are near the other one. This is because we only send entity tracking info to - // players who canReceiveAllPackets(). - if(!bVisible) - { - MinecraftServer *server = MinecraftServer::getInstance(); - INetworkPlayer *thisPlayer = sp->connection->getNetworkPlayer(); - if( thisPlayer ) - { - for( unsigned int i = 0; i < server->getPlayers()->players.size(); i++ ) - { - // Consider extra players, but not if they are the entity we are tracking, or the player we've been passed as input, or in another dimension - std::shared_ptr ep = server->getPlayers()->players[i]; - if( ep == sp ) continue; - if( ep == e ) continue; - if( ep->dimension != sp->dimension ) continue; + // 4J - added. Try and find other players who are in the same dimension as + // this one and on the same machine, and extend our visibility so things are + // consider visible to this player if they are near the other one. This is + // because we only send entity tracking info to players who + // canReceiveAllPackets(). + if (!bVisible) { + MinecraftServer* server = MinecraftServer::getInstance(); + INetworkPlayer* thisPlayer = sp->connection->getNetworkPlayer(); + if (thisPlayer) { + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + // Consider extra players, but not if they are the entity we are + // tracking, or the player we've been passed as input, or in + // another dimension + std::shared_ptr ep = + server->getPlayers()->players[i]; + if (ep == sp) continue; + if (ep == e) continue; + if (ep->dimension != sp->dimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // 4J Stu - We call update players when the entity has moved more than a certain amount at the start of it's tick - // Before this call we set xpu, ypu and zpu to the entities new position, but xp,yp and zp are the old position until later in the tick. - // Therefore we should use the new position for visibility checks - double xd = ep->x - xpu; //xp / 32; - double zd = ep->z - zpu; //zp / 32; - bVisible |= ( xd >= -playersRange && xd <= playersRange && zd >= -playersRange && zd <= playersRange ); - canBeSeenBy |= canBySeenBy(ep); - } - } - } - } + INetworkPlayer* otherPlayer = + ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + // 4J Stu - We call update players when the entity has moved + // more than a certain amount at the start of it's tick + // Before this call we set xpu, ypu and zpu to the entities + // new position, but xp,yp and zp are the old position until + // later in the tick. Therefore we should use the new + // position for visibility checks + double xd = ep->x - xpu; // xp / 32; + double zd = ep->z - zpu; // zp / 32; + bVisible |= (xd >= -playersRange && xd <= playersRange && + zd >= -playersRange && zd <= playersRange); + canBeSeenBy |= canBySeenBy(ep); + } + } + } + } - // 4J Stu - We need to ensure that we send the mount before the rider, so check that the player has been added to the seenBy list - if(forRider) - { - canBeSeenBy = canBeSeenBy && (seenBy.find(sp) != seenBy.end()); - } + // 4J Stu - We need to ensure that we send the mount before the rider, so + // check that the player has been added to the seenBy list + if (forRider) { + canBeSeenBy = canBeSeenBy && (seenBy.find(sp) != seenBy.end()); + } - // 4J-JEV: ADDED! An entities mount has to be visible before the entity visible, - // this is to ensure that the mount is already in the client's game when the rider is added. - if (canBeSeenBy && bVisible && e->riding != NULL) - { - return tracker->getTracker(e->riding)->isVisible(tracker, sp, true); - } - else if (canBeSeenBy && bVisible) return eVisibility_SeenAndVisible; - else if (bVisible) return eVisibility_IsVisible; - else return eVisibility_NotVisible; + // 4J-JEV: ADDED! An entities mount has to be visible before the entity + // visible, this is to ensure that the mount is already in the client's game + // when the rider is added. + if (canBeSeenBy && bVisible && e->riding != NULL) { + return tracker->getTracker(e->riding)->isVisible(tracker, sp, true); + } else if (canBeSeenBy && bVisible) + return eVisibility_SeenAndVisible; + else if (bVisible) + return eVisibility_IsVisible; + else + return eVisibility_NotVisible; } -void TrackedEntity::updatePlayer(EntityTracker *tracker, std::shared_ptr sp) -{ +void TrackedEntity::updatePlayer(EntityTracker* tracker, + std::shared_ptr sp) { if (sp == e) return; - eVisibility visibility = this->isVisible(tracker, sp); - - if ( visibility == eVisibility_SeenAndVisible - && seenBy.find(sp) == seenBy.end() ) - { + eVisibility visibility = this->isVisible(tracker, sp); + + if (visibility == eVisibility_SeenAndVisible && + seenBy.find(sp) == seenBy.end()) { seenBy.insert(sp); - std::shared_ptr packet = getAddEntityPacket(); + std::shared_ptr packet = getAddEntityPacket(); sp->connection->send(packet); - xap = e->xd; - yap = e->yd; - zap = e->zd; + xap = e->xd; + yap = e->yd; + zap = e->zd; - std::shared_ptr plr = std::dynamic_pointer_cast(e); - if (plr != NULL) - { - app.DebugPrintf( "TrackedEntity:: Player '%ls' is now visible to player '%ls', %s.\n", - plr->name.c_str(), sp->name.c_str(), - (e->riding==NULL?"not riding minecart":"in minecart") - ); - } - - // 4J Stu brought forward to fix when Item Frames - if (!e->getEntityData()->isEmpty() && !(std::dynamic_pointer_cast(packet))) - { - sp->connection->send(std::shared_ptr( new SetEntityDataPacket(e->entityId, e->getEntityData(), true))); - } - - if (this->trackDelta) - { - sp->connection->send( std::shared_ptr( new SetEntityMotionPacket(e->entityId, e->xd, e->yd, e->zd) ) ); + std::shared_ptr plr = std::dynamic_pointer_cast(e); + if (plr != NULL) { + app.DebugPrintf( + "TrackedEntity:: Player '%ls' is now visible to player '%ls', " + "%s.\n", + plr->name.c_str(), sp->name.c_str(), + (e->riding == NULL ? "not riding minecart" : "in minecart")); } - if (e->riding != NULL) - { - sp->connection->send(std::shared_ptr(new SetRidingPacket(e, e->riding))); - } + // 4J Stu brought forward to fix when Item Frames + if (!e->getEntityData()->isEmpty() && + !(std::dynamic_pointer_cast(packet))) { + sp->connection->send( + std::shared_ptr(new SetEntityDataPacket( + e->entityId, e->getEntityData(), true))); + } + + if (this->trackDelta) { + sp->connection->send(std::shared_ptr( + new SetEntityMotionPacket(e->entityId, e->xd, e->yd, e->zd))); + } + + if (e->riding != NULL) { + sp->connection->send(std::shared_ptr( + new SetRidingPacket(e, e->riding))); + } ItemInstanceArray equipped = e->getEquipmentSlots(); - if (equipped.data != NULL) - { - for (unsigned int i = 0; i < equipped.length; i++) - { - sp->connection->send( std::shared_ptr( new SetEquippedItemPacket(e->entityId, i, equipped[i]) ) ); + if (equipped.data != NULL) { + for (unsigned int i = 0; i < equipped.length; i++) { + sp->connection->send(std::shared_ptr( + new SetEquippedItemPacket(e->entityId, i, equipped[i]))); } } - if (std::dynamic_pointer_cast(e) != NULL) - { + if (std::dynamic_pointer_cast(e) != NULL) { std::shared_ptr spe = std::dynamic_pointer_cast(e); - if (spe->isSleeping()) - { - sp->connection->send( std::shared_ptr( new EntityActionAtPositionPacket(e, EntityActionAtPositionPacket::START_SLEEP, Mth::floor(e->x), Mth::floor(e->y), Mth::floor(e->z)) ) ); + if (spe->isSleeping()) { + sp->connection->send( + std::shared_ptr( + new EntityActionAtPositionPacket( + e, EntityActionAtPositionPacket::START_SLEEP, + Mth::floor(e->x), Mth::floor(e->y), + Mth::floor(e->z)))); } } - if (std::dynamic_pointer_cast(e) != NULL) - { - std::shared_ptr mob = std::dynamic_pointer_cast(e); - std::vector *activeEffects = mob->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + if (std::dynamic_pointer_cast(e) != NULL) { + std::shared_ptr mob = std::dynamic_pointer_cast(e); + std::vector* activeEffects = + mob->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); + it != activeEffects->end(); ++it) { + MobEffectInstance* effect = *it; - sp->connection->send(std::shared_ptr( new UpdateMobEffectPacket(e->entityId, effect) ) ); - } - delete activeEffects; - } - } - else if (visibility == eVisibility_NotVisible) - { - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) - { + sp->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(e->entityId, effect))); + } + delete activeEffects; + } + } else if (visibility == eVisibility_NotVisible) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); } } - } -bool TrackedEntity::canBySeenBy(std::shared_ptr player) -{ - // 4J - for some reason this isn't currently working, and is causing players to not appear until we are really close to them. Not sure - // what the conflict is between the java & our version, but removing for now as it is causing issues and we shouldn't *really* need it - // TODO - investigate further +bool TrackedEntity::canBySeenBy(std::shared_ptr player) { + // 4J - for some reason this isn't currently working, and is causing players + // to not appear until we are really close to them. Not sure what the + // conflict is between the java & our version, but removing for now as it is + // causing issues and we shouldn't *really* need it + // TODO - investigate further - return true; -// return player->getLevel()->getChunkMap()->isPlayerIn(player, e->xChunk, e->zChunk); + return true; + // return player->getLevel()->getChunkMap()->isPlayerIn(player, e->xChunk, + //e->zChunk); } -void TrackedEntity::updatePlayers(EntityTracker *tracker, std::vector > *players) -{ - for (unsigned int i = 0; i < players->size(); i++) - { - updatePlayer(tracker, std::dynamic_pointer_cast( players->at(i) ) ); +void TrackedEntity::updatePlayers( + EntityTracker* tracker, std::vector >* players) { + for (unsigned int i = 0; i < players->size(); i++) { + updatePlayer(tracker, + std::dynamic_pointer_cast(players->at(i))); } } -std::shared_ptr TrackedEntity::getAddEntityPacket() -{ - if (e->removed) - { - app.DebugPrintf("Fetching addPacket for removed entity - %ls\n", e->getAName().c_str()); - } - - // 4J-PB - replacing with a switch, rather than tons of ifs - if (std::dynamic_pointer_cast(e) != NULL) - { - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp) ); - } - - switch(e->GetType()) - { - case eTYPE_ITEMENTITY: - { - std::shared_ptr packet = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp) ); - return packet; - } - break; - case eTYPE_SERVERPLAYER: - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - PlayerUID xuid = INVALID_XUID; - PlayerUID OnlineXuid = INVALID_XUID; - if( player != NULL ) - { - xuid = player->getXuid(); - OnlineXuid = player->getOnlineXuid(); - } - // 4J Added yHeadRotp param to fix #102563 - TU12: Content: Gameplay: When one of the Players is idle for a few minutes his head turns 180 degrees. - return std::shared_ptr( new AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp, yHeadRotp ) ); - } - break; - case eTYPE_MINECART: - { - std::shared_ptr minecart = std::dynamic_pointer_cast(e); - if (minecart->type == Minecart::RIDEABLE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::CHEST) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::FURNACE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_BOAT: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ENDERDRAGON: - { - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp ) ); - } - break; - case eTYPE_FISHINGHOOK: - { - std::shared_ptr owner = std::dynamic_pointer_cast(e)->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ARROW: - { - std::shared_ptr owner = (std::dynamic_pointer_cast(e))->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_SNOWBALL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_THROWNPOTION: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_POTION, ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp)); - } - break; - case eTYPE_THROWNEXPBOTTLE: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_THROWNENDERPEARL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_EYEOFENDERSIGNAL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_SMALL_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_DRAGON_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_THROWNEGG: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_PRIMEDTNT: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ENDER_CRYSTAL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_FALLINGTILE: - { - std::shared_ptr ft = std::dynamic_pointer_cast(e); - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_PAINTING: - { - return std::shared_ptr( new AddPaintingPacket(std::dynamic_pointer_cast(e)) ); - } - break; - case eTYPE_ITEM_FRAME: - { - std::shared_ptr frame = std::dynamic_pointer_cast(e); - { - - int ix= (int)frame->xTile; - int iy= (int)frame->yTile; - int iz= (int)frame->zTile; - app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } - - std::shared_ptr packet = std::shared_ptr(new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); - packet->x = Mth::floor(frame->xTile * 32.0f); - packet->y = Mth::floor(frame->yTile * 32.0f); - packet->z = Mth::floor(frame->zTile * 32.0f); - return packet; - } - break; - case eTYPE_EXPERIENCEORB: - { - return std::shared_ptr( new AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); - } - break; - default: - assert(false); - break; - } -/* - if (e->GetType() == eTYPE_ITEMENTITY) - { - std::shared_ptr itemEntity = std::dynamic_pointer_cast(e); - std::shared_ptr packet = std::shared_ptr( new AddItemEntityPacket(itemEntity, xp, yp, zp) ); - itemEntity->x = packet->x / 32.0; - itemEntity->y = packet->y / 32.0; - itemEntity->z = packet->z / 32.0; - return packet; +std::shared_ptr TrackedEntity::getAddEntityPacket() { + if (e->removed) { + app.DebugPrintf("Fetching addPacket for removed entity - %ls\n", + e->getAName().c_str()); } - if (e->GetType() == eTYPE_SERVERPLAYER ) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - XUID xuid = INVALID_XUID; - XUID OnlineXuid = INVALID_XUID; - if( player != NULL ) - { - xuid = player->getXuid(); - OnlineXuid = player->getOnlineXuid(); - } - return std::shared_ptr( new AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp ) ); + // 4J-PB - replacing with a switch, rather than tons of ifs + if (std::dynamic_pointer_cast(e) != NULL) { + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + return std::shared_ptr( + new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, + xp, yp, zp, yHeadRotp)); } - if (e->GetType() == eTYPE_MINECART) - { - std::shared_ptr minecart = std::dynamic_pointer_cast(e); - if (minecart->type == Minecart::RIDEABLE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::CHEST) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::FURNACE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_BOAT) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); - } - if (std::dynamic_pointer_cast(e) != NULL) - { - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ENDERDRAGON) - { - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp ) ); - } - if (e->GetType() == eTYPE_FISHINGHOOK) - { - std::shared_ptr owner = std::dynamic_pointer_cast(e)->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ARROW) - { - std::shared_ptr owner = (std::dynamic_pointer_cast(e))->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_SNOWBALL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_THROWNPOTION) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_POTION, ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp)); - } - if (e->GetType() == eTYPE_THROWNEXPBOTTLE) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_THROWNENDERPEARL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_SMALL_FIREBALL) - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = NULL; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - if (e->GetType() == eTYPE_FIREBALL) - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = NULL; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - if (e->GetType() == eTYPE_THROWNEGG) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_PRIMEDTNT) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ENDER_CRYSTAL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_FALLINGTILE) - { - std::shared_ptr ft = std::dynamic_pointer_cast(e); - if (ft->tile == Tile::sand_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_SAND, yRotp, xRotp, xp, yp, zp) ); - if (ft->tile == Tile::gravel_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_GRAVEL, yRotp, xRotp, xp, yp, zp) ); - if (ft->tile == Tile::dragonEgg_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_EGG, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_PAINTING) - { - return std::shared_ptr( new AddPaintingPacket(std::dynamic_pointer_cast(e)) ); - } - if (e->GetType() == eTYPE_ITEM_FRAME) - { - std::shared_ptr frame = std::dynamic_pointer_cast(e); - { - int ix= (int)frame->xTile; - int iy= (int)frame->yTile; - int iz= (int)frame->zTile; - app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } + switch (e->GetType()) { + case eTYPE_ITEMENTITY: { + std::shared_ptr packet = + std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp)); + return packet; + } break; + case eTYPE_SERVERPLAYER: { + std::shared_ptr player = + std::dynamic_pointer_cast(e); + PlayerUID xuid = INVALID_XUID; + PlayerUID OnlineXuid = INVALID_XUID; + if (player != NULL) { + xuid = player->getXuid(); + OnlineXuid = player->getOnlineXuid(); + } + // 4J Added yHeadRotp param to fix #102563 - TU12: Content: + // Gameplay: When one of the Players is idle for a few minutes his + // head turns 180 degrees. + return std::shared_ptr(new AddPlayerPacket( + std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, + zp, yRotp, xRotp, yHeadRotp)); + } break; + case eTYPE_MINECART: { + std::shared_ptr minecart = + std::dynamic_pointer_cast(e); + if (minecart->type == Minecart::RIDEABLE) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, + yRotp, xRotp, xp, yp, zp)); + if (minecart->type == Minecart::CHEST) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, + yRotp, xRotp, xp, yp, zp)); + if (minecart->type == Minecart::FURNACE) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_BOAT: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_ENDERDRAGON: { + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + return std::shared_ptr( + new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, + xRotp, xp, yp, zp, yHeadRotp)); + } break; + case eTYPE_FISHINGHOOK: { + std::shared_ptr owner = + std::dynamic_pointer_cast(e)->owner; + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FISH_HOOK, + owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, + yp, zp)); + } break; + case eTYPE_ARROW: { + std::shared_ptr owner = + (std::dynamic_pointer_cast(e))->owner; + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ARROW, + owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, + yp, zp)); + } break; + case eTYPE_SNOWBALL: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNPOTION: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::THROWN_POTION, + ((std::dynamic_pointer_cast(e)) + ->getPotionValue()), + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNEXPBOTTLE: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNENDERPEARL: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_EYEOFENDERSIGNAL: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_SMALL_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, + yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_DRAGON_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::DRAGON_FIRE_BALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, 0, + yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, + xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_THROWNEGG: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_PRIMEDTNT: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_ENDER_CRYSTAL: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_FALLINGTILE: { + std::shared_ptr ft = + std::dynamic_pointer_cast(e); + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_PAINTING: { + return std::shared_ptr( + new AddPaintingPacket(std::dynamic_pointer_cast(e))); + } break; + case eTYPE_ITEM_FRAME: { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + { + int ix = (int)frame->xTile; + int iy = (int)frame->yTile; + int iz = (int)frame->zTile; + app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n", ix, iy, iz); + } - std::shared_ptr packet = std::shared_ptr(new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); - packet->x = Mth::floor(frame->xTile * 32.0f); - packet->y = Mth::floor(frame->yTile * 32.0f); - packet->z = Mth::floor(frame->zTile * 32.0f); - return packet; - } - if (e->GetType() == eTYPE_EXPERIENCEORB) - { - return std::shared_ptr( new AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); + std::shared_ptr packet = + std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, + frame->dir, yRotp, xRotp, xp, yp, zp)); + packet->x = Mth::floor(frame->xTile * 32.0f); + packet->y = Mth::floor(frame->yTile * 32.0f); + packet->z = Mth::floor(frame->zTile * 32.0f); + return packet; + } break; + case eTYPE_EXPERIENCEORB: { + return std::shared_ptr( + new AddExperienceOrbPacket( + std::dynamic_pointer_cast(e))); + } break; + default: + assert(false); + break; } - assert(false); - */ - return nullptr; + /* + if (e->GetType() == eTYPE_ITEMENTITY) + { + std::shared_ptr itemEntity = + std::dynamic_pointer_cast(e); + std::shared_ptr packet = + std::shared_ptr( new AddItemEntityPacket(itemEntity, + xp, yp, zp) ); itemEntity->x = packet->x / 32.0; itemEntity->y = + packet->y / 32.0; itemEntity->z = packet->z / 32.0; return packet; + } + + if (e->GetType() == eTYPE_SERVERPLAYER ) + { + std::shared_ptr player = + std::dynamic_pointer_cast(e); XUID xuid = INVALID_XUID; + XUID OnlineXuid = INVALID_XUID; + if( player != NULL ) + { + xuid = player->getXuid(); + OnlineXuid = player->getOnlineXuid(); + } + return std::shared_ptr( new + AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, + xp, yp, zp, yRotp, xRotp ) ); + } + if (e->GetType() == eTYPE_MINECART) + { + std::shared_ptr minecart = + std::dynamic_pointer_cast(e); if (minecart->type == + Minecart::RIDEABLE) return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, + yp, zp) ); if (minecart->type == Minecart::CHEST) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); if + (minecart->type == Minecart::FURNACE) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_BOAT) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); + } + if (std::dynamic_pointer_cast(e) != NULL) + { + return std::shared_ptr( new + AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp) + ); + } + if (e->GetType() == eTYPE_ENDERDRAGON) + { + return std::shared_ptr( new + AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp + ) ); + } + if (e->GetType() == eTYPE_FISHINGHOOK) + { + std::shared_ptr owner = + std::dynamic_pointer_cast(e)->owner; return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : + e->entityId, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_ARROW) + { + std::shared_ptr owner = + (std::dynamic_pointer_cast(e))->owner; return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, + yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_SNOWBALL) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_THROWNPOTION) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_POTION, + ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, + xRotp, xp, yp, zp)); + } + if (e->GetType() == eTYPE_THROWNEXPBOTTLE) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_THROWNENDERPEARL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_SMALL_FIREBALL) + { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = NULL; + if (fb->owner != NULL) + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp) ); + } + else + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, + yp, zp) ); + } + aep->xa = (int) (fb->xPower * 8000); + aep->ya = (int) (fb->yPower * 8000); + aep->za = (int) (fb->zPower * 8000); + return aep; + } + if (e->GetType() == eTYPE_FIREBALL) + { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); std::shared_ptr + aep = NULL; if (fb->owner != NULL) + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, + xRotp, xp, yp, zp) ); + } + else + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, + zp) ); + } + aep->xa = (int) (fb->xPower * 8000); + aep->ya = (int) (fb->yPower * 8000); + aep->za = (int) (fb->zPower * 8000); + return aep; + } + if (e->GetType() == eTYPE_THROWNEGG) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_PRIMEDTNT) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_ENDER_CRYSTAL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, + zp) ); + } + if (e->GetType() == eTYPE_FALLINGTILE) + { + std::shared_ptr ft = + std::dynamic_pointer_cast(e); if (ft->tile == Tile::sand_Id) + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FALLING_SAND, yRotp, xRotp, xp, yp, zp) ); if (ft->tile + == Tile::gravel_Id) return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FALLING_GRAVEL, yRotp, xRotp, xp, yp, + zp) ); if (ft->tile == Tile::dragonEgg_Id) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FALLING_EGG, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_PAINTING) + { + return std::shared_ptr( new + AddPaintingPacket(std::dynamic_pointer_cast(e)) ); + } + if (e->GetType() == eTYPE_ITEM_FRAME) + { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + { + + int ix= (int)frame->xTile; + int iy= (int)frame->yTile; + int iz= (int)frame->zTile; + app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); + } + + std::shared_ptr packet = + std::shared_ptr(new AddEntityPacket(e, + AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); + packet->x = Mth::floor(frame->xTile * 32.0f); + packet->y = Mth::floor(frame->yTile * 32.0f); + packet->z = Mth::floor(frame->zTile * 32.0f); + return packet; + } + if (e->GetType() == eTYPE_EXPERIENCEORB) + { + return std::shared_ptr( new + AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); + } + assert(false); + */ + return nullptr; } -void TrackedEntity::clear(std::shared_ptr sp) -{ - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) - { +void TrackedEntity::clear(std::shared_ptr sp) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); } diff --git a/Minecraft.Client/Player/TrackedEntity.h b/Minecraft.Client/Player/TrackedEntity.h index 70df9da3e..4a879eb03 100644 --- a/Minecraft.Client/Player/TrackedEntity.h +++ b/Minecraft.Client/Player/TrackedEntity.h @@ -1,21 +1,19 @@ #pragma once class Entity; -//class ServerPlayer; +// class ServerPlayer; #include "ServerPlayer.h" class Packet; - class EntityTracker; #define TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE 4 -class TrackedEntity -{ +class TrackedEntity { private: - static const int TOLERANCE_LEVEL = 4; + static const int TOLERANCE_LEVEL = 4; public: - std::shared_ptr e; + std::shared_ptr e; int range, updateInterval; int xp, yp, zp, yRotp, xRotp, yHeadRotp; @@ -23,43 +21,51 @@ public: int tickCount; private: - double xpu, ypu, zpu; + double xpu, ypu, zpu; bool updatedPlayerVisibility; bool trackDelta; int teleportDelay; - std::shared_ptr wasRiding; + std::shared_ptr wasRiding; public: - bool moved; + bool moved; - std::unordered_set , PlayerKeyHash, PlayerKeyEq > seenBy; + std::unordered_set, PlayerKeyHash, + PlayerKeyEq> + seenBy; - TrackedEntity(std::shared_ptr e, int range, int updateInterval, bool trackDelta); + TrackedEntity(std::shared_ptr e, int range, int updateInterval, + bool trackDelta); - void tick(EntityTracker *tracker, std::vector > *players); + void tick(EntityTracker* tracker, + std::vector >* players); void broadcast(std::shared_ptr packet); void broadcastAndSend(std::shared_ptr packet); void broadcastRemoved(); void removePlayer(std::shared_ptr sp); private: - bool canBySeenBy(std::shared_ptr player); + bool canBySeenBy(std::shared_ptr player); - enum eVisibility - { - eVisibility_NotVisible = 0, - eVisibility_IsVisible = 1, - eVisibility_SeenAndVisible = 2, - }; + enum eVisibility { + eVisibility_NotVisible = 0, + eVisibility_IsVisible = 1, + eVisibility_SeenAndVisible = 2, + }; + + eVisibility isVisible(EntityTracker* tracker, + std::shared_ptr sp, + bool forRider = false); // 4J Added forRider - eVisibility isVisible(EntityTracker *tracker, std::shared_ptr sp, bool forRider = false); // 4J Added forRider - public: - void updatePlayer(EntityTracker *tracker, std::shared_ptr sp); - void updatePlayers(EntityTracker *tracker, std::vector > *players); + void updatePlayer(EntityTracker* tracker, std::shared_ptr sp); + void updatePlayers(EntityTracker* tracker, + std::vector >* players); + private: - void sendEntityData(std::shared_ptr conn); - std::shared_ptr getAddEntityPacket(); + void sendEntityData(std::shared_ptr conn); + std::shared_ptr getAddEntityPacket(); + public: void clear(std::shared_ptr sp); }; diff --git a/Minecraft.Client/Player/User.cpp b/Minecraft.Client/Player/User.cpp index 514070b54..3c5ac9fe0 100644 --- a/Minecraft.Client/Player/User.cpp +++ b/Minecraft.Client/Player/User.cpp @@ -2,10 +2,9 @@ #include "User.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -std::vector User::allowedTiles; +std::vector User::allowedTiles; -void User::staticCtor() -{ +void User::staticCtor() { allowedTiles.push_back(Tile::rock); allowedTiles.push_back(Tile::stoneBrick); allowedTiles.push_back(Tile::redBrick); @@ -38,8 +37,7 @@ void User::staticCtor() allowedTiles.push_back(Tile::obsidian); } -User::User(const std::wstring& name, const std::wstring& sessionId) -{ +User::User(const std::wstring& name, const std::wstring& sessionId) { this->name = name; this->sessionId = sessionId; } diff --git a/Minecraft.Client/Player/User.h b/Minecraft.Client/Player/User.h index 7650b7cc2..8ab308bd6 100644 --- a/Minecraft.Client/Player/User.h +++ b/Minecraft.Client/Player/User.h @@ -1,14 +1,12 @@ #pragma once - -class User -{ +class User { public: - static std::vector allowedTiles; - static void staticCtor(); - std::wstring name; - std::wstring sessionId; - std::wstring mpPassword; + static std::vector allowedTiles; + static void staticCtor(); + std::wstring name; + std::wstring sessionId; + std::wstring mpPassword; - User(const std::wstring& name, const std::wstring& sessionId); + User(const std::wstring& name, const std::wstring& sessionId); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Camera.cpp b/Minecraft.Client/Rendering/Camera.cpp index 8a2338f1d..e085cf06c 100644 --- a/Minecraft.Client/Rendering/Camera.cpp +++ b/Minecraft.Client/Rendering/Camera.cpp @@ -10,10 +10,10 @@ float Camera::xPlayerOffs = 0.0f; float Camera::yPlayerOffs = 0.0f; float Camera::zPlayerOffs = 0.0f; -//IntBuffer *Camera::viewport = MemoryTracker::createIntBuffer(16); -FloatBuffer *Camera::modelview = MemoryTracker::createFloatBuffer(16); -FloatBuffer *Camera::projection = MemoryTracker::createFloatBuffer(16); -//FloatBuffer *Camera::position = MemoryTracker::createFloatBuffer(3); +// IntBuffer *Camera::viewport = MemoryTracker::createIntBuffer(16); +FloatBuffer* Camera::modelview = MemoryTracker::createFloatBuffer(16); +FloatBuffer* Camera::projection = MemoryTracker::createFloatBuffer(16); +// FloatBuffer *Camera::position = MemoryTracker::createFloatBuffer(3); float Camera::xa = 0.0f; float Camera::ya = 0.0f; @@ -21,58 +21,59 @@ float Camera::za = 0.0f; float Camera::xa2 = 0.0f; float Camera::za2 = 0.0f; -void Camera::prepare(std::shared_ptr player, bool mirror) -{ +void Camera::prepare(std::shared_ptr player, bool mirror) { glGetFloat(GL_MODELVIEW_MATRIX, modelview); glGetFloat(GL_PROJECTION_MATRIX, projection); - /* Original java code for reference - glGetInteger(GL_VIEWPORT, viewport); + /* Original java code for reference +glGetInteger(GL_VIEWPORT, viewport); - float x = (viewport.get(0) + viewport.get(2)) / 2; - float y = (viewport.get(1) + viewport.get(3)) / 2; - gluUnProject(x, y, 0, modelview, projection, viewport, position); +float x = (viewport.get(0) + viewport.get(2)) / 2; +float y = (viewport.get(1) + viewport.get(3)) / 2; +gluUnProject(x, y, 0, modelview, projection, viewport, position); - xPlayerOffs = position->get(0); - yPlayerOffs = position->get(1); - zPlayerOffs = position->get(2); - */ +xPlayerOffs = position->get(0); +yPlayerOffs = position->get(1); +zPlayerOffs = position->get(2); + */ - // Xbox conversion here... note that we don't bother getting the viewport as this is just working out how to get a (0,0,0) point in clip space to pass into the inverted - // combined model/view/projection matrix, so we just need to get this matrix and get its translation as an equivalent. - XMMATRIX _modelview, _proj, _final, _invert; - XMVECTOR _det; - XMFLOAT4 trans; + // Xbox conversion here... note that we don't bother getting the viewport as + // this is just working out how to get a (0,0,0) point in clip space to pass + // into the inverted combined model/view/projection matrix, so we just need + // to get this matrix and get its translation as an equivalent. + XMMATRIX _modelview, _proj, _final, _invert; + XMVECTOR _det; + XMFLOAT4 trans; - memcpy( &_modelview, modelview->_getDataPointer(), 64 ); - memcpy( &_proj, projection->_getDataPointer(), 64 ); + memcpy(&_modelview, modelview->_getDataPointer(), 64); + memcpy(&_proj, projection->_getDataPointer(), 64); -#if ( defined __ORBIS__ ) || ( defined __PSVITA__ ) - _modelview = transpose(_modelview); - _proj = transpose(_proj); - _final = _modelview * _proj; - _invert = sce::Vectormath::Simd::Aos::inverse(_final); - xPlayerOffs = _invert.getElem(0,3) / _invert.getElem(3,3); - yPlayerOffs = _invert.getElem(1,3) / _invert.getElem(3,3); - zPlayerOffs = _invert.getElem(2,3) / _invert.getElem(3,3); -#elif defined __PS3__ - _modelview = transpose(_modelview); - _proj = transpose(_proj); - _final = _modelview * _proj; - _invert = Vectormath::Aos::inverse(_final); - xPlayerOffs = _invert.getElem(0,3) / _invert.getElem(3,3); - yPlayerOffs = _invert.getElem(1,3) / _invert.getElem(3,3); - zPlayerOffs = _invert.getElem(2,3) / _invert.getElem(3,3); +#if (defined __ORBIS__) || (defined __PSVITA__) + _modelview = transpose(_modelview); + _proj = transpose(_proj); + _final = _modelview * _proj; + _invert = sce::Vectormath::Simd::Aos::inverse(_final); + xPlayerOffs = _invert.getElem(0, 3) / _invert.getElem(3, 3); + yPlayerOffs = _invert.getElem(1, 3) / _invert.getElem(3, 3); + zPlayerOffs = _invert.getElem(2, 3) / _invert.getElem(3, 3); +#elif defined __PS3__ + _modelview = transpose(_modelview); + _proj = transpose(_proj); + _final = _modelview * _proj; + _invert = Vectormath::Aos::inverse(_final); + xPlayerOffs = _invert.getElem(0, 3) / _invert.getElem(3, 3); + yPlayerOffs = _invert.getElem(1, 3) / _invert.getElem(3, 3); + zPlayerOffs = _invert.getElem(2, 3) / _invert.getElem(3, 3); #else - _final = XMMatrixMultiply( _modelview, _proj ); - _det = XMMatrixDeterminant(_final); - _invert = XMMatrixInverse(&_det, _final); + _final = XMMatrixMultiply(_modelview, _proj); + _det = XMMatrixDeterminant(_final); + _invert = XMMatrixInverse(&_det, _final); - XMStoreFloat4(&trans,_invert.r[3]); + XMStoreFloat4(&trans, _invert.r[3]); - xPlayerOffs = trans.x / trans.w; - yPlayerOffs = trans.y / trans.w; - zPlayerOffs = trans.z / trans.w; + xPlayerOffs = trans.x / trans.w; + yPlayerOffs = trans.y / trans.w; + zPlayerOffs = trans.z / trans.w; #endif int flipCamera = mirror ? 1 : 0; @@ -88,15 +89,14 @@ void Camera::prepare(std::shared_ptr player, bool mirror) ya = cosf(xRot * PI / 180.0f); } -TilePos *Camera::getCameraTilePos(std::shared_ptr player, double alpha) -{ - return new TilePos(getCameraPos(player, alpha)); +TilePos* Camera::getCameraTilePos(std::shared_ptr player, double alpha) { + return new TilePos(getCameraPos(player, alpha)); } -Vec3 *Camera::getCameraPos(std::shared_ptr player, double alpha) -{ +Vec3* Camera::getCameraPos(std::shared_ptr player, double alpha) { double xx = player->xo + (player->x - player->xo) * alpha; - double yy = player->yo + (player->y - player->yo) * alpha + player->getHeadHeight(); + double yy = + player->yo + (player->y - player->yo) * alpha + player->getHeadHeight(); double zz = player->zo + (player->z - player->zo) * alpha; double xt = xx + Camera::xPlayerOffs * 1; @@ -106,17 +106,15 @@ Vec3 *Camera::getCameraPos(std::shared_ptr player, double alpha) return Vec3::newTemp(xt, yt, zt); } -int Camera::getBlockAt(Level *level, std::shared_ptr player, float alpha) -{ - Vec3 *p = Camera::getCameraPos(player, alpha); +int Camera::getBlockAt(Level* level, std::shared_ptr player, float alpha) { + Vec3* p = Camera::getCameraPos(player, alpha); TilePos tp = TilePos(p); int t = level->getTile(tp.x, tp.y, tp.z); - if (t != 0 && Tile::tiles[t]->material->isLiquid()) - { - float hh = LiquidTile::getHeight(level->getData(tp.x, tp.y, tp.z)) - 1 / 9.0f; + if (t != 0 && Tile::tiles[t]->material->isLiquid()) { + float hh = + LiquidTile::getHeight(level->getData(tp.x, tp.y, tp.z)) - 1 / 9.0f; float h = tp.y + 1 - hh; - if (p->y >= h) - { + if (p->y >= h) { t = level->getTile(tp.x, tp.y + 1, tp.z); } } diff --git a/Minecraft.Client/Rendering/Camera.h b/Minecraft.Client/Rendering/Camera.h index 1d42f58fa..019a6efa7 100644 --- a/Minecraft.Client/Rendering/Camera.h +++ b/Minecraft.Client/Rendering/Camera.h @@ -2,31 +2,30 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/IO/Streams/IntBuffer.h" - class TilePos; class Vec3; class Player; class Mob; -class Camera -{ +class Camera { public: - static float xPlayerOffs; + static float xPlayerOffs; static float yPlayerOffs; static float zPlayerOffs; private: -// static IntBuffer *viewport; - static FloatBuffer *modelview; - static FloatBuffer *projection; -// static FloatBuffer *position; + // static IntBuffer *viewport; + static FloatBuffer* modelview; + static FloatBuffer* projection; + // static FloatBuffer *position; public: - static float xa, ya, za, xa2, za2; + static float xa, ya, za, xa2, za2; - static void prepare(std::shared_ptr player, bool mirror); + static void prepare(std::shared_ptr player, bool mirror); - static TilePos *getCameraTilePos(std::shared_ptr player, double alpha); - static Vec3 *getCameraPos(std::shared_ptr player, double alpha); - static int getBlockAt(Level *level, std::shared_ptr player, float alpha); + static TilePos* getCameraTilePos(std::shared_ptr player, double alpha); + static Vec3* getCameraPos(std::shared_ptr player, double alpha); + static int getBlockAt(Level* level, std::shared_ptr player, + float alpha); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Chunk.cpp b/Minecraft.Client/Rendering/Chunk.cpp index cbf5bb4a3..746d29d79 100644 --- a/Minecraft.Client/Rendering/Chunk.cpp +++ b/Minecraft.Client/Rendering/Chunk.cpp @@ -22,1024 +22,1068 @@ int Chunk::updates = 0; #ifdef _LARGE_WORLDS unsigned int Chunk::tlsIdx = TlsAlloc(); -void Chunk::CreateNewThreadStorage() -{ - unsigned char *tileIds = new unsigned char[16 * 16 * Level::maxBuildHeight]; - TlsSetValue(tlsIdx, tileIds); +void Chunk::CreateNewThreadStorage() { + unsigned char* tileIds = new unsigned char[16 * 16 * Level::maxBuildHeight]; + TlsSetValue(tlsIdx, tileIds); } -void Chunk::ReleaseThreadStorage() -{ - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); - delete tileIds; +void Chunk::ReleaseThreadStorage() { + unsigned char* tileIds = (unsigned char*)TlsGetValue(tlsIdx); + delete tileIds; } -unsigned char *Chunk::GetTileIdsStorage() -{ - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); - return tileIds; +unsigned char* Chunk::GetTileIdsStorage() { + unsigned char* tileIds = (unsigned char*)TlsGetValue(tlsIdx); + return tileIds; } #else // 4J Stu - Don't want this when multi-threaded -Tesselator *Chunk::t = Tesselator::getInstance(); +Tesselator* Chunk::t = Tesselator::getInstance(); #endif -LevelRenderer *Chunk::levelRenderer; +LevelRenderer* Chunk::levelRenderer; -// TODO - 4J see how input entity vector is set up and decide what way is best to pass this to the function -Chunk::Chunk(Level *level, LevelRenderer::rteMap &globalRenderableTileEntities, CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, int z, ClipChunk *clipChunk) - : globalRenderableTileEntities( &globalRenderableTileEntities ), globalRenderableTileEntities_cs(&globalRenderableTileEntities_cs) -{ - clipChunk->visible = false; - bb = NULL; - id = 0; +// TODO - 4J see how input entity vector is set up and decide what way is best +// to pass this to the function +Chunk::Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities, + CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, + int z, ClipChunk* clipChunk) + : globalRenderableTileEntities(&globalRenderableTileEntities), + globalRenderableTileEntities_cs(&globalRenderableTileEntities_cs) { + clipChunk->visible = false; + bb = NULL; + id = 0; - this->level = level; - //this->globalRenderableTileEntities = globalRenderableTileEntities; + this->level = level; + // this->globalRenderableTileEntities = globalRenderableTileEntities; - assigned = false; - this->clipChunk = clipChunk; - setPos(x, y, z); + assigned = false; + this->clipChunk = clipChunk; + setPos(x, y, z); } -void Chunk::setPos(int x, int y, int z) -{ - if(assigned && (x == this->x && y == this->y && z == this->z)) return; +void Chunk::setPos(int x, int y, int z) { + if (assigned && (x == this->x && y == this->y && z == this->z)) return; - reset(); + reset(); - this->x = x; - this->y = y; - this->z = z; - xm = x + XZSIZE / 2; - ym = y + SIZE / 2; - zm = z + XZSIZE / 2; - clipChunk->xm = xm; - clipChunk->ym = ym; - clipChunk->zm = zm; + this->x = x; + this->y = y; + this->z = z; + xm = x + XZSIZE / 2; + ym = y + SIZE / 2; + zm = z + XZSIZE / 2; + clipChunk->xm = xm; + clipChunk->ym = ym; + clipChunk->zm = zm; - clipChunk->globalIdx = LevelRenderer::getGlobalIndexForChunk(x, y, z, level); + clipChunk->globalIdx = + LevelRenderer::getGlobalIndexForChunk(x, y, z, level); #if 1 - // 4J - we're not using offsetted renderlists anymore, so just set the full position of this chunk into x/y/zRenderOffs where - // it will be used directly in the renderlist of this chunk - xRenderOffs = x; - yRenderOffs = y; - zRenderOffs = z; - xRender = 0; - yRender = 0; - zRender = 0; + // 4J - we're not using offsetted renderlists anymore, so just set the full + // position of this chunk into x/y/zRenderOffs where it will be used + // directly in the renderlist of this chunk + xRenderOffs = x; + yRenderOffs = y; + zRenderOffs = z; + xRender = 0; + yRender = 0; + zRender = 0; #else - xRenderOffs = x & 1023; - yRenderOffs = y; - zRenderOffs = z & 1023; - xRender = x - xRenderOffs; - yRender = y - yRenderOffs; - zRender = z - zRenderOffs; + xRenderOffs = x & 1023; + yRenderOffs = y; + zRenderOffs = z & 1023; + xRender = x - xRenderOffs; + yRender = y - yRenderOffs; + zRender = z - zRenderOffs; #endif - float g = 6.0f; - // 4J - changed to just set the value rather than make a new one, if we've already created storage - if( bb == NULL ) - { - bb = AABB::newPermanent(-g, -g, -g, XZSIZE+g, SIZE+g, XZSIZE+g); - } - else - { - // 4J MGH - bounds are relative to the position now, so the AABB will be setup already, either above, or from the tesselator bounds. -// bb->set(-g, -g, -g, SIZE+g, SIZE+g, SIZE+g); - } - clipChunk->aabb[0] = bb->x0 + x; - clipChunk->aabb[1] = bb->y0 + y; - clipChunk->aabb[2] = bb->z0 + z; - clipChunk->aabb[3] = bb->x1 + x; - clipChunk->aabb[4] = bb->y1 + y; - clipChunk->aabb[5] = bb->z1 + z; + float g = 6.0f; + // 4J - changed to just set the value rather than make a new one, if we've + // already created storage + if (bb == NULL) { + bb = AABB::newPermanent(-g, -g, -g, XZSIZE + g, SIZE + g, XZSIZE + g); + } else { + // 4J MGH - bounds are relative to the position now, so the AABB will be + // setup already, either above, or from the tesselator bounds. + // bb->set(-g, -g, -g, SIZE+g, SIZE+g, SIZE+g); + } + clipChunk->aabb[0] = bb->x0 + x; + clipChunk->aabb[1] = bb->y0 + y; + clipChunk->aabb[2] = bb->z0 + z; + clipChunk->aabb[3] = bb->x1 + x; + clipChunk->aabb[4] = bb->y1 + y; + clipChunk->aabb[5] = bb->z1 + z; - assigned = true; + assigned = true; - EnterCriticalSection(&levelRenderer->m_csDirtyChunks); - unsigned char refCount = levelRenderer->incGlobalChunkRefCount(x, y, z, level); -// printf("\t\t [inc] refcount %d at %d, %d, %d\n",refCount,x,y,z); + EnterCriticalSection(&levelRenderer->m_csDirtyChunks); + unsigned char refCount = + levelRenderer->incGlobalChunkRefCount(x, y, z, level); + // printf("\t\t [inc] refcount %d at %d, %d, %d\n",refCount,x,y,z); -// int idx = levelRenderer->getGlobalIndexForChunk(x, y, z, level); + // int idx = levelRenderer->getGlobalIndexForChunk(x, y, z, level); - // If we're the first thing to be referencing this, mark it up as dirty to get rebuilt - if( refCount == 1 ) - { -// printf("Setting %d %d %d dirty [%d]\n",x,y,z, idx); - // Chunks being made dirty in this way can be very numerous (eg the full visible area of the world at start up, or a whole edge of the world when moving). - // On account of this, don't want to stick them into our lock free queue that we would normally use for letting the render update thread know about this chunk. - // Instead, just set the flag to say this is dirty, and then pass a special value of 1 through to the lock free stack which lets that thread know that at least - // one chunk other than the ones in the stack itself have been made dirty. - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY ); + // If we're the first thing to be referencing this, mark it up as dirty to + // get rebuilt + if (refCount == 1) { + // printf("Setting %d %d %d dirty [%d]\n",x,y,z, idx); + // Chunks being made dirty in this way can be very numerous (eg the full + // visible area of the world at start up, or a whole edge of the world + // when moving). On account of this, don't want to stick them into our + // lock free queue that we would normally use for letting the render + // update thread know about this chunk. Instead, just set the flag to + // say this is dirty, and then pass a special value of 1 through to the + // lock free stack which lets that thread know that at least one chunk + // other than the ones in the stack itself have been made dirty. + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); #ifdef _XBOX - PIXSetMarker(0,"Non-stack event pushed"); + PIXSetMarker(0, "Non-stack event pushed"); #else - PIXSetMarkerDeprecated(0,"Non-stack event pushed"); + PIXSetMarkerDeprecated(0, "Non-stack event pushed"); #endif - } + } - LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); - - + LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); } -void Chunk::translateToPos() -{ - glTranslatef((float)xRenderOffs, (float)yRenderOffs, (float)zRenderOffs); +void Chunk::translateToPos() { + glTranslatef((float)xRenderOffs, (float)yRenderOffs, (float)zRenderOffs); } +Chunk::Chunk() {} -Chunk::Chunk() -{ +void Chunk::makeCopyForRebuild(Chunk* source) { + this->level = source->level; + this->x = source->x; + this->y = source->y; + this->z = source->z; + this->xRender = source->xRender; + this->yRender = source->yRender; + this->zRender = source->zRender; + this->xRenderOffs = source->xRenderOffs; + this->yRenderOffs = source->yRenderOffs; + this->zRenderOffs = source->zRenderOffs; + this->xm = source->xm; + this->ym = source->ym; + this->zm = source->zm; + this->bb = source->bb; + this->clipChunk = NULL; + this->id = source->id; + this->globalRenderableTileEntities = source->globalRenderableTileEntities; + this->globalRenderableTileEntities_cs = + source->globalRenderableTileEntities_cs; } -void Chunk::makeCopyForRebuild(Chunk *source) -{ - this->level = source->level; - this->x = source->x; - this->y = source->y; - this->z = source->z; - this->xRender = source->xRender; - this->yRender = source->yRender; - this->zRender = source->zRender; - this->xRenderOffs = source->xRenderOffs; - this->yRenderOffs = source->yRenderOffs; - this->zRenderOffs = source->zRenderOffs; - this->xm = source->xm; - this->ym = source->ym; - this->zm = source->zm; - this->bb = source->bb; - this->clipChunk = NULL; - this->id = source->id; - this->globalRenderableTileEntities = source->globalRenderableTileEntities; - this->globalRenderableTileEntities_cs = source->globalRenderableTileEntities_cs; -} - -void Chunk::rebuild() -{ - PIXBeginNamedEvent(0,"Rebuilding chunk %d, %d, %d", x, y, z); +void Chunk::rebuild() { + PIXBeginNamedEvent(0, "Rebuilding chunk %d, %d, %d", x, y, z); #if defined __PS3__ && !defined DISABLE_SPU_CODE - rebuild_SPU(); - return; -#endif // __PS3__ + rebuild_SPU(); + return; +#endif // __PS3__ -// if (!dirty) return; - PIXBeginNamedEvent(0,"Rebuild section A"); - -#ifdef _LARGE_WORLDS - Tesselator *t = Tesselator::getInstance(); -#else - Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser being set at the wrong time -#endif - - updates++; - - int x0 = x; - int y0 = y; - int z0 = z; - int x1 = x + XZSIZE; - int y1 = y + SIZE; - int z1 = z + XZSIZE; - - LevelChunk::touchedSky = false; - -// std::unordered_set > oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); // 4J removed this & next line -// renderableTileEntities.clear(); - - std::vector > renderableTileEntities; // 4J - added - - int r = 1; - - int lists = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level) * 2; - lists += levelRenderer->chunkLists; - - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Rebuild section B"); - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // 4J - optimisation begins. - - // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, - // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently - // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. + // if (!dirty) return; + PIXBeginNamedEvent(0, "Rebuild section A"); #ifdef _LARGE_WORLDS - unsigned char *tileIds = GetTileIdsStorage(); + Tesselator* t = Tesselator::getInstance(); #else - static unsigned char tileIds[16 * 16 * Level::maxBuildHeight]; + Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser + // being set at the wrong time #endif - byteArray tileArray = byteArray(tileIds, 16 * 16 * Level::maxBuildHeight); - level->getChunkAt(x,z)->getBlockData(tileArray); // 4J - TODO - now our data has been re-arranged, we could just extra the vertical slice of this chunk rather than the whole thing - LevelSource *region = new Region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); - TileRenderer *tileRenderer = new TileRenderer(region, this->x, this->y, this->z, tileIds); + updates++; - // AP - added a caching system for Chunk::rebuild to take advantage of - // Basically we're storing of copy of the tileIDs array inside the region so that calls to Region::getTile can grab data - // more quickly from this array rather than calling CompressedTileStorage. On the Vita the total thread time spent in - // Region::getTile went from 20% to 4%. + int x0 = x; + int y0 = y; + int z0 = z; + int x1 = x + XZSIZE; + int y1 = y + SIZE; + int z1 = z + XZSIZE; + + LevelChunk::touchedSky = false; + + // std::unordered_set > + //oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); + //// 4J removed this & next line renderableTileEntities.clear(); + + std::vector > + renderableTileEntities; // 4J - added + + int r = 1; + + int lists = levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, + level) * + 2; + lists += levelRenderer->chunkLists; + + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Rebuild section B"); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 4J - optimisation begins. + + // Get the data for the level chunk that this render chunk is it (level + // chunk is 16 x 16 x 128, render chunk is 16 x 16 x 16. We wouldn't have to + // actually get all of it if the data was ordered differently, but currently + // it is ordered by x then z then y so just getting a small range of y out + // of it would involve getting the whole thing into the cache anyway. + +#ifdef _LARGE_WORLDS + unsigned char* tileIds = GetTileIdsStorage(); +#else + static unsigned char tileIds[16 * 16 * Level::maxBuildHeight]; +#endif + byteArray tileArray = byteArray(tileIds, 16 * 16 * Level::maxBuildHeight); + level->getChunkAt(x, z)->getBlockData( + tileArray); // 4J - TODO - now our data has been re-arranged, we could + // just extra the vertical slice of this chunk rather than + // the whole thing + + LevelSource* region = + new Region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); + TileRenderer* tileRenderer = + new TileRenderer(region, this->x, this->y, this->z, tileIds); + + // AP - added a caching system for Chunk::rebuild to take advantage of + // Basically we're storing of copy of the tileIDs array inside the region so + // that calls to Region::getTile can grab data more quickly from this array + // rather than calling CompressedTileStorage. On the Vita the total thread + // time spent in Region::getTile went from 20% to 4%. #ifdef __PSVITA__ - int xc = x >> 4; - int zc = z >> 4; - ((Region*)region)->setCachedTiles(tileIds, xc, zc); + int xc = x >> 4; + int zc = z >> 4; + ((Region*)region)->setCachedTiles(tileIds, xc, zc); #endif - // We now go through the vertical section of this level chunk that we are interested in and try and establish - // (1) if it is completely empty - // (2) if any of the tiles can be quickly determined to not need rendering because they are in the middle of other tiles and - // so can't be seen. A large amount (> 60% in tests) of tiles that call tesselateInWorld in the unoptimised version - // of this function fall into this category. By far the largest category of these are tiles in solid regions of rock. - bool empty = true; - for( int yy = y0; yy < y1; yy++ ) - { - for( int zz = 0; zz < 16; zz++ ) - { - for( int xx = 0; xx < 16; xx++ ) - { - // 4J Stu - tile data is ordered in 128 blocks of full width, lower 128 then upper 128 - int indexY = yy; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + // We now go through the vertical section of this level chunk that we are + // interested in and try and establish (1) if it is completely empty (2) if + // any of the tiles can be quickly determined to not need rendering because + // they are in the middle of other tiles and + // so can't be seen. A large amount (> 60% in tests) of tiles that call + // tesselateInWorld in the unoptimised version of this function fall + // into this category. By far the largest category of these are tiles in + // solid regions of rock. + bool empty = true; + for (int yy = y0; yy < y1; yy++) { + for (int zz = 0; zz < 16; zz++) { + for (int xx = 0; xx < 16; xx++) { + // 4J Stu - tile data is ordered in 128 blocks of full width, + // lower 128 then upper 128 + int indexY = yy; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - unsigned char tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ]; - if( tileId > 0 ) empty = false; + unsigned char tileId = + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (tileId > 0) empty = false; - // Don't bother trying to work out neighbours for this tile if we are at the edge of the chunk - apart from the very - // bottom of the world where we shouldn't ever be able to see - if( yy == (Level::maxBuildHeight - 1) ) continue; - if(( xx == 0 ) || ( xx == 15 )) continue; - if(( zz == 0 ) || ( zz == 15 )) continue; - - // Establish whether this tile and its neighbours are all made of rock, dirt, unbreakable tiles, or have already - // been determined to meet this criteria themselves and have a tile of 255 set. - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx - 1 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 1 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz - 1 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 1 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - // Treat the bottom of the world differently - we shouldn't ever be able to look up at this, so consider tiles as invisible - // if they are surrounded on sides other than the bottom - if( yy > 0 ) - { - int indexYMinusOne = yy - 1; - int yMinusOneOffset = 0; - if(indexYMinusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexYMinusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - yMinusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - tileId = tileIds[ yMinusOneOffset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | indexYMinusOne ) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - } - int indexYPlusOne = yy + 1; - int yPlusOneOffset = 0; - if(indexYPlusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexYPlusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - yPlusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - tileId = tileIds[ yPlusOneOffset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | indexYPlusOne ) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; + // Don't bother trying to work out neighbours for this tile if + // we are at the edge of the chunk - apart from the very bottom + // of the world where we shouldn't ever be able to see + if (yy == (Level::maxBuildHeight - 1)) continue; + if ((xx == 0) || (xx == 15)) continue; + if ((zz == 0) || (zz == 15)) continue; - // This tile is surrounded. Flag it as not requiring to be rendered by setting its id to 255. - tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ] = 0xff; - } - } - } - PIXEndNamedEvent(); - // Nothing at all to do for this chunk? - if( empty ) - { - // 4J - added - clear any renderer data associated with this - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } + // Establish whether this tile and its neighbours are all made + // of rock, dirt, unbreakable tiles, or have already been + // determined to meet this criteria themselves and have a tile + // of 255 set. + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx - 1) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 1) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 0) << 11) | ((zz - 1) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 0) << 11) | ((zz + 1) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + // Treat the bottom of the world differently - we shouldn't ever + // be able to look up at this, so consider tiles as invisible if + // they are surrounded on sides other than the bottom + if (yy > 0) { + int indexYMinusOne = yy - 1; + int yMinusOneOffset = 0; + if (indexYMinusOne >= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexYMinusOne -= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + yMinusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } + tileId = tileIds[yMinusOneOffset + (((xx + 0) << 11) | + ((zz + 0) << 7) | + indexYMinusOne)]; + if (!((tileId == Tile::rock_Id) || + (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + } + int indexYPlusOne = yy + 1; + int yPlusOneOffset = 0; + if (indexYPlusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexYPlusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + yPlusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } + tileId = + tileIds[yPlusOneOffset + (((xx + 0) << 11) | + ((zz + 0) << 7) | indexYPlusOne)]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; - delete region; - delete tileRenderer; - return; - } - // 4J - optimisation ends - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // This tile is surrounded. Flag it as not requiring to be + // rendered by setting its id to 255. + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))] = 0xff; + } + } + } + PIXEndNamedEvent(); + // Nothing at all to do for this chunk? + if (empty) { + // 4J - added - clear any renderer data associated with this + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } - PIXBeginNamedEvent(0,"Rebuild section C"); - Tesselator::Bounds bounds; // 4J MGH - added - { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. - float g = 6.0f; - bounds.boundingBox[0] = -g; - bounds.boundingBox[1] = -g; - bounds.boundingBox[2] = -g; - bounds.boundingBox[3] = XZSIZE+g; - bounds.boundingBox[4] = SIZE+g; - bounds.boundingBox[5] = XZSIZE+g; - } - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - bool renderNextLayer = false; - bool rendered = false; + delete region; + delete tileRenderer; + return; + } + // 4J - optimisation ends + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - bool started = false; + PIXBeginNamedEvent(0, "Rebuild section C"); + Tesselator::Bounds bounds; // 4J MGH - added + { + // this was the old default clip bounds for the chunk, set in + // Chunk::setPos. + float g = 6.0f; + bounds.boundingBox[0] = -g; + bounds.boundingBox[1] = -g; + bounds.boundingBox[2] = -g; + bounds.boundingBox[3] = XZSIZE + g; + bounds.boundingBox[4] = SIZE + g; + bounds.boundingBox[5] = XZSIZE + g; + } + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + bool renderNextLayer = false; + bool rendered = false; - // 4J - changed loop order here to leave y as the innermost loop for better cache performance - for (int z = z0; z < z1; z++) - { - for (int x = x0; x < x1; x++) - { - for (int y = y0; y < y1; y++) - { - // 4J Stu - tile data is ordered in 128 blocks of full width, lower 128 then upper 128 - int indexY = y; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + bool started = false; - // 4J - get tile from those copied into our local array in earlier optimisation - unsigned char tileId = tileIds[ offset + ( ( ( x - x0 ) << 11 ) | ( ( z - z0 ) << 7 ) | indexY) ]; - // If flagged as not visible, drop out straight away - if( tileId == 0xff ) continue; -// int tileId = region->getTile(x,y,z); - if (tileId > 0) - { - if (!started) - { - started = true; + // 4J - changed loop order here to leave y as the innermost loop for + // better cache performance + for (int z = z0; z < z1; z++) { + for (int x = x0; x < x1; x++) { + for (int y = y0; y < y1; y++) { + // 4J Stu - tile data is ordered in 128 blocks of full + // width, lower 128 then upper 128 + int indexY = y; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - MemSect(31); - glNewList(lists + currentLayer, GL_COMPILE); - MemSect(0); - glPushMatrix(); - glDepthMask(true); // 4J added - t->useCompactVertices(false); // 4J added - translateToPos(); - float ss = 1.000001f; - // 4J - have removed this scale as I don't think we should need it, and have now optimised the vertex - // shader so it doesn't do anything other than translate with this matrix anyway + // 4J - get tile from those copied into our local array in + // earlier optimisation + unsigned char tileId = + tileIds[offset + + (((x - x0) << 11) | ((z - z0) << 7) | indexY)]; + // If flagged as not visible, drop out straight away + if (tileId == 0xff) continue; + // int tileId = + //region->getTile(x,y,z); + if (tileId > 0) { + if (!started) { + started = true; + + MemSect(31); + glNewList(lists + currentLayer, GL_COMPILE); + MemSect(0); + glPushMatrix(); + glDepthMask(true); // 4J added + t->useCompactVertices(false); // 4J added + translateToPos(); + float ss = 1.000001f; + // 4J - have removed this scale as I don't think we + // should need it, and have now optimised the vertex + // shader so it doesn't do anything other than + // translate with this matrix anyway #if 0 glTranslatef(-zs / 2.0f, -ys / 2.0f, -zs / 2.0f); glScalef(ss, ss, ss); glTranslatef(zs / 2.0f, ys / 2.0f, zs / 2.0f); #endif - t->begin(); - t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); - } - - Tile *tile = Tile::tiles[tileId]; - if (currentLayer == 0 && tile->isEntityTile()) - { - std::shared_ptr et = region->getTileEntity(x, y, z); - if (TileEntityRenderDispatcher::instance->hasRenderer(et)) - { - renderableTileEntities.push_back(et); - } - } - int renderLayer = tile->getRenderLayer(); + t->begin(); + t->offset((float)(-this->x), (float)(-this->y), + (float)(-this->z)); + } - if (renderLayer != currentLayer) - { - renderNextLayer = true; - } - else if (renderLayer == currentLayer) - { - rendered |= tileRenderer->tesselateInWorld(tile, x, y, z); - } - } - } - } - } + Tile* tile = Tile::tiles[tileId]; + if (currentLayer == 0 && tile->isEntityTile()) { + std::shared_ptr et = + region->getTileEntity(x, y, z); + if (TileEntityRenderDispatcher::instance + ->hasRenderer(et)) { + renderableTileEntities.push_back(et); + } + } + int renderLayer = tile->getRenderLayer(); + + if (renderLayer != currentLayer) { + renderNextLayer = true; + } else if (renderLayer == currentLayer) { + rendered |= + tileRenderer->tesselateInWorld(tile, x, y, z); + } + } + } + } + } #ifdef __PSVITA__ - if( currentLayer==0 ) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_CUT_OUT); - } + if (currentLayer == 0) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_CUT_OUT); + } #endif - if (started) - { + if (started) { #ifdef __PSVITA__ - // AP - make sure we don't attempt to render chunks without cutout geometry - if( t->getCutOutFound() ) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_CUT_OUT); - } + // AP - make sure we don't attempt to render chunks without cutout + // geometry + if (t->getCutOutFound()) { + levelRenderer->setGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_CUT_OUT); + } #endif - t->end(); - bounds.addBounds(t->bounds); // 4J MGH - added - glPopMatrix(); - glEndList(); - t->useCompactVertices(false); // 4J added - t->offset(0, 0, 0); - } - else - { - rendered = false; - } + t->end(); + bounds.addBounds(t->bounds); // 4J MGH - added + glPopMatrix(); + glEndList(); + t->useCompactVertices(false); // 4J added + t->offset(0, 0, 0); + } else { + rendered = false; + } - if (rendered) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - } - else - { - // 4J - added - clear any renderer data associated with this unused list - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } - if((currentLayer==0)&&(!renderNextLayer)) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY1); - RenderManager.CBuffClear(lists + 1); - break; - } - } + if (rendered) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); + } else { + // 4J - added - clear any renderer data associated with this unused + // list + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } + if ((currentLayer == 0) && (!renderNextLayer)) { + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY1); + RenderManager.CBuffClear(lists + 1); + break; + } + } - // 4J MGH - added this to take the bound from the value calc'd in the tesselator - if( bb ) - { - bb->set(bounds.boundingBox[0], bounds.boundingBox[1], bounds.boundingBox[2], - bounds.boundingBox[3], bounds.boundingBox[4], bounds.boundingBox[5]); - } + // 4J MGH - added this to take the bound from the value calc'd in the + // tesselator + if (bb) { + bb->set(bounds.boundingBox[0], bounds.boundingBox[1], + bounds.boundingBox[2], bounds.boundingBox[3], + bounds.boundingBox[4], bounds.boundingBox[5]); + } - delete tileRenderer; - delete region; + delete tileRenderer; + delete region; - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Rebuild section D"); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Rebuild section D"); - // 4J - have rewritten the way that tile entities are stored globally to make it work more easily with split screen. Chunks are now - // stored globally in the levelrenderer, in a hashmap with a special key made up from the dimension and chunk position (using same index - // as is used for global flags) + // 4J - have rewritten the way that tile entities are stored globally to + // make it work more easily with split screen. Chunks are now stored + // globally in the levelrenderer, in a hashmap with a special key made up + // from the dimension and chunk position (using same index as is used for + // global flags) #if 1 - int key = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level); - EnterCriticalSection(globalRenderableTileEntities_cs); - if( renderableTileEntities.size() ) - { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. - // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones + int key = + levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, level); + EnterCriticalSection(globalRenderableTileEntities_cs); + if (renderableTileEntities.size()) { + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + // We've got some renderable tile entities that we want associated + // with this chunk, and an existing list of things that used to be. + // We need to flag any that we don't need any more to be removed, + // keep those that we do, and add any new ones - // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } + // First pass - flag everything already existing to be removed + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } - // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); - if( it2 == it->second.end() ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - else - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageKeep); - } - } - } - else - { - // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - } - } - else - { - // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - } - } - LeaveCriticalSection(globalRenderableTileEntities_cs); - PIXEndNamedEvent(); + // Now go through the current list. If these are already in the + // list, then unflag the remove flag. If they aren't, then add + for (int i = 0; i < renderableTileEntities.size(); i++) { + AUTO_VAR(it2, find(it->second.begin(), it->second.end(), + renderableTileEntities[i])); + if (it2 == it->second.end()) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } else { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageKeep); + } + } + } else { + // Easy case - nothing already existing for this chunk. Add them all + // in. + for (int i = 0; i < renderableTileEntities.size(); i++) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } + } + } else { + // Another easy case - we don't want any renderable tile entities + // associated with this chunk. Flag all to be removed. + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } + } + } + LeaveCriticalSection(globalRenderableTileEntities_cs); + PIXEndNamedEvent(); #else - // Find the removed ones: + // Find the removed ones: - // 4J - original code for this section: - /* - Set newTileEntities = new HashSet(); - newTileEntities.addAll(renderableTileEntities); - newTileEntities.removeAll(oldTileEntities); - globalRenderableTileEntities.addAll(newTileEntities); + // 4J - original code for this section: + /* + Set newTileEntities = new HashSet(); + newTileEntities.addAll(renderableTileEntities); + newTileEntities.removeAll(oldTileEntities); + globalRenderableTileEntities.addAll(newTileEntities); - oldTileEntities.removeAll(renderableTileEntities); - globalRenderableTileEntities.removeAll(oldTileEntities); - */ - + oldTileEntities.removeAll(renderableTileEntities); + globalRenderableTileEntities.removeAll(oldTileEntities); + */ - std::unordered_set > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); - for( std::unordered_set >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) - { - newTileEntities.erase(*it); - } + std::unordered_set > newTileEntities( + renderableTileEntities.begin(), renderableTileEntities.end()); - // 4J - newTileEntities is now renderableTileEntities with any old ones from oldTileEntitesRemoved (so just new things added) + AUTO_VAR(endIt, oldTileEntities.end()); + for (std::unordered_set >::iterator it = + oldTileEntities.begin(); + it != endIt; it++) { + newTileEntities.erase(*it); + } - EnterCriticalSection(globalRenderableTileEntities_cs); - endIt = newTileEntities.end(); - for( std::unordered_set >::iterator it = newTileEntities.begin(); it != endIt; it++ ) - { - globalRenderableTileEntities->push_back(*it); - } + // 4J - newTileEntities is now renderableTileEntities with any old ones from + // oldTileEntitesRemoved (so just new things added) - // 4J - All these new things added to globalRenderableTileEntities + EnterCriticalSection(globalRenderableTileEntities_cs); + endIt = newTileEntities.end(); + for (std::unordered_set >::iterator it = + newTileEntities.begin(); + it != endIt; it++) { + globalRenderableTileEntities->push_back(*it); + } - AUTO_VAR(endItRTE, renderableTileEntities.end()); - for( std::vector >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) - { - oldTileEntities.erase(*it); - } - // 4J - oldTileEntities is now the removed items - std::vector >::iterator it = globalRenderableTileEntities->begin(); - while( it != globalRenderableTileEntities->end() ) - { - if( oldTileEntities.find(*it) != oldTileEntities.end() ) - { - it = globalRenderableTileEntities->erase(it); - } - else - { - ++it; - } - } + // 4J - All these new things added to globalRenderableTileEntities - LeaveCriticalSection(globalRenderableTileEntities_cs); + AUTO_VAR(endItRTE, renderableTileEntities.end()); + for (std::vector >::iterator it = + renderableTileEntities.begin(); + it != endItRTE; it++) { + oldTileEntities.erase(*it); + } + // 4J - oldTileEntities is now the removed items + std::vector >::iterator it = + globalRenderableTileEntities->begin(); + while (it != globalRenderableTileEntities->end()) { + if (oldTileEntities.find(*it) != oldTileEntities.end()) { + it = globalRenderableTileEntities->erase(it); + } else { + ++it; + } + } + + LeaveCriticalSection(globalRenderableTileEntities_cs); #endif - // 4J - These removed items are now also removed from globalRenderableTileEntities - - if( LevelChunk::touchedSky ) - { - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - else - { - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED); - PIXEndNamedEvent(); - return; + // 4J - These removed items are now also removed from + // globalRenderableTileEntities + if (LevelChunk::touchedSky) { + levelRenderer->clearGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } else { + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED); + PIXEndNamedEvent(); + return; } - #ifdef __PS3__ ChunkRebuildData g_rebuildDataIn __attribute__((__aligned__(16))); ChunkRebuildData g_rebuildDataOut __attribute__((__aligned__(16))); TileCompressData_SPU g_tileCompressDataIn __attribute__((__aligned__(16))); -unsigned char* g_tileCompressDataOut = (unsigned char*)&g_rebuildDataIn.m_tileIds; +unsigned char* g_tileCompressDataOut = + (unsigned char*)&g_rebuildDataIn.m_tileIds; #define TILE_RENDER_SPU +void RunSPURebuild() { + static C4JSpursJobQueue::Port p("C4JSpursJob_ChunkUpdate"); + C4JSpursJob_CompressedTile tileJob(&g_tileCompressDataIn, + g_tileCompressDataOut); + C4JSpursJob_ChunkUpdate chunkJob(&g_rebuildDataIn, &g_rebuildDataOut); -void RunSPURebuild() -{ + if (g_rebuildDataIn.m_currentLayer == + 0) // only need to create the tiles on the first layer + { + p.submitJob(&tileJob); + p.submitSync(); + } - static C4JSpursJobQueue::Port p("C4JSpursJob_ChunkUpdate"); - C4JSpursJob_CompressedTile tileJob(&g_tileCompressDataIn,g_tileCompressDataOut); - C4JSpursJob_ChunkUpdate chunkJob(&g_rebuildDataIn, &g_rebuildDataOut); + p.submitJob(&chunkJob); + p.waitForCompletion(); - if(g_rebuildDataIn.m_currentLayer == 0) // only need to create the tiles on the first layer - { - p.submitJob(&tileJob); - p.submitSync(); - } - - p.submitJob(&chunkJob); - p.waitForCompletion(); - - assert(g_rebuildDataIn.m_x0 == g_rebuildDataOut.m_x0); + assert(g_rebuildDataIn.m_x0 == g_rebuildDataOut.m_x0); } -void Chunk::rebuild_SPU() -{ +void Chunk::rebuild_SPU() { + // if (!dirty) return; + Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser + // being set at the wrong time + updates++; -// if (!dirty) return; - Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser being set at the wrong time - updates++; + int x0 = x; + int y0 = y; + int z0 = z; + int x1 = x + SIZE; + int y1 = y + SIZE; + int z1 = z + SIZE; - int x0 = x; - int y0 = y; - int z0 = z; - int x1 = x + SIZE; - int y1 = y + SIZE; - int z1 = z + SIZE; + LevelChunk::touchedSky = false; - LevelChunk::touchedSky = false; + // std::unordered_set > + //oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); + //// 4J removed this & next line renderableTileEntities.clear(); -// std::unordered_set > oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); // 4J removed this & next line -// renderableTileEntities.clear(); + std::vector > + renderableTileEntities; // 4J - added - std::vector > renderableTileEntities; // 4J - added + // List newTileEntities = new ArrayList(); + // newTileEntities.clear(); + // renderableTileEntities.clear(); -// List newTileEntities = new ArrayList(); -// newTileEntities.clear(); -// renderableTileEntities.clear(); + int r = 1; - int r = 1; + Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); + TileRenderer tileRenderer(®ion); - Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); - TileRenderer tileRenderer(®ion); + int lists = levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, + level) * + 2; + lists += levelRenderer->chunkLists; - int lists = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level) * 2; - lists += levelRenderer->chunkLists; + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 4J - optimisation begins. - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // 4J - optimisation begins. + // Get the data for the level chunk that this render chunk is it (level + // chunk is 16 x 16 x 128, render chunk is 16 x 16 x 16. We wouldn't have to + // actually get all of it if the data was ordered differently, but currently + // it is ordered by x then z then y so just getting a small range of y out + // of it would involve getting the whole thing into the cache anyway. + ChunkRebuildData* pOutData = NULL; + g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); - // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, - // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently - // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. - ChunkRebuildData* pOutData = NULL; - g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); + Tesselator::Bounds bounds; + { + // this was the old default clip bounds for the chunk, set in + // Chunk::setPos. + float g = 6.0f; + bounds.boundingBox[0] = -g; + bounds.boundingBox[1] = -g; + bounds.boundingBox[2] = -g; + bounds.boundingBox[3] = SIZE + g; + bounds.boundingBox[4] = SIZE + g; + bounds.boundingBox[5] = SIZE + g; + } - Tesselator::Bounds bounds; - { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. - float g = 6.0f; - bounds.boundingBox[0] = -g; - bounds.boundingBox[1] = -g; - bounds.boundingBox[2] = -g; - bounds.boundingBox[3] = SIZE+g; - bounds.boundingBox[4] = SIZE+g; - bounds.boundingBox[5] = SIZE+g; - } + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + bool rendered = false; - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - bool rendered = false; - - { - glNewList(lists + currentLayer, GL_COMPILE); - MemSect(0); - glPushMatrix(); - glDepthMask(true); // 4J added - t->useCompactVertices(false); // 4J added - translateToPos(); - float ss = 1.000001f; - // 4J - have removed this scale as I don't think we should need it, and have now optimised the vertex - // shader so it doesn't do anything other than translate with this matrix anyway - #if 0 + { + glNewList(lists + currentLayer, GL_COMPILE); + MemSect(0); + glPushMatrix(); + glDepthMask(true); // 4J added + t->useCompactVertices(false); // 4J added + translateToPos(); + float ss = 1.000001f; + // 4J - have removed this scale as I don't think we should need it, + // and have now optimised the vertex shader so it doesn't do + // anything other than translate with this matrix anyway +#if 0 glTranslatef(-zs / 2.0f, -ys / 2.0f, -zs / 2.0f); glScalef(ss, ss, ss); glTranslatef(zs / 2.0f, ys / 2.0f, zs / 2.0f); - #endif - t->begin(); - t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); - } +#endif + t->begin(); + t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); + } - g_rebuildDataIn.copyFromTesselator(); - intArray_SPU tesselatorArray((unsigned int*)g_rebuildDataIn.m_tesselator.m_PPUArray); - g_rebuildDataIn.m_tesselator._array = &tesselatorArray; - g_rebuildDataIn.m_currentLayer = currentLayer; - #ifdef TILE_RENDER_SPU - g_tileCompressDataIn.setForChunk(®ion, x0, y0, z0); - RunSPURebuild(); - g_rebuildDataOut.storeInTesselator(); - pOutData = &g_rebuildDataOut; - #else - g_rebuildDataIn.disableUnseenTiles(); - TileRenderer_SPU *pTileRenderer = new TileRenderer_SPU(&g_rebuildDataIn); - g_rebuildDataIn.tesselateAllTiles(pTileRenderer); - g_rebuildDataIn.storeInTesselator(); - pOutData = &g_rebuildDataIn; - #endif - if(pOutData->m_flags & ChunkRebuildData::e_flag_Rendered) - rendered = true; - - // 4J - changed loop order here to leave y as the innermost loop for better cache performance - for (int z = z0; z < z1; z++) - { - for (int x = x0; x < x1; x++) - { - for (int y = y0; y < y1; y++) - { - // 4J - get tile from those copied into our local array in earlier optimisation - unsigned char tileId = pOutData->getTile(x,y,z); - if (tileId > 0) - { - if (currentLayer == 0 && Tile::tiles[tileId]->isEntityTile()) - { - std::shared_ptr et = region.getTileEntity(x, y, z); - if (TileEntityRenderDispatcher::instance->hasRenderer(et)) - { - renderableTileEntities.push_back(et); - } - } - int flags = pOutData->getFlags(x,y,z); - if(flags & ChunkRebuildData::e_flag_SPURenderCodeMissing) - { - - Tile *tile = Tile::tiles[tileId]; - int renderLayer = tile->getRenderLayer(); - - if (renderLayer != currentLayer) - { - // renderNextLayer = true; - } - else if (renderLayer == currentLayer) - { - //if(currentLayer == 0) - // numRenderedLayer0++; - rendered |= tileRenderer.tesselateInWorld(tile, x, y, z); - } - } - } - } - } - } - - - { - t->end(); - bounds.addBounds(t->bounds); - glPopMatrix(); - glEndList(); - t->useCompactVertices(false); // 4J added - t->offset(0, 0, 0); - } - if (rendered) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - } - else - { - // 4J - added - clear any renderer data associated with this unused list - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } - - } - - if( bb ) - { - bb->set(bounds.boundingBox[0], bounds.boundingBox[1], bounds.boundingBox[2], - bounds.boundingBox[3], bounds.boundingBox[4], bounds.boundingBox[5]); - } - - - if(pOutData->m_flags & ChunkRebuildData::e_flag_TouchedSky) - LevelChunk::touchedSky = true; - - - // 4J - have rewritten the way that tile entities are stored globally to make it work more easily with split screen. Chunks are now - // stored globally in the levelrenderer, in a hashmap with a special key made up from the dimension and chunk position (using same index - // as is used for global flags) -#if 1 - int key = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level); - EnterCriticalSection(globalRenderableTileEntities_cs); - if( renderableTileEntities.size() ) - { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. - // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones - - // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - - // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); - if( it2 == it->second.end() ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - else - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageKeep); - } - } - } - else - { - // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - } - } - else - { - // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - } - } - LeaveCriticalSection(globalRenderableTileEntities_cs); + g_rebuildDataIn.copyFromTesselator(); + intArray_SPU tesselatorArray( + (unsigned int*)g_rebuildDataIn.m_tesselator.m_PPUArray); + g_rebuildDataIn.m_tesselator._array = &tesselatorArray; + g_rebuildDataIn.m_currentLayer = currentLayer; +#ifdef TILE_RENDER_SPU + g_tileCompressDataIn.setForChunk(®ion, x0, y0, z0); + RunSPURebuild(); + g_rebuildDataOut.storeInTesselator(); + pOutData = &g_rebuildDataOut; #else - // Find the removed ones: + g_rebuildDataIn.disableUnseenTiles(); + TileRenderer_SPU* pTileRenderer = + new TileRenderer_SPU(&g_rebuildDataIn); + g_rebuildDataIn.tesselateAllTiles(pTileRenderer); + g_rebuildDataIn.storeInTesselator(); + pOutData = &g_rebuildDataIn; +#endif + if (pOutData->m_flags & ChunkRebuildData::e_flag_Rendered) + rendered = true; - // 4J - original code for this section: - /* - Set newTileEntities = new HashSet(); - newTileEntities.addAll(renderableTileEntities); - newTileEntities.removeAll(oldTileEntities); - globalRenderableTileEntities.addAll(newTileEntities); + // 4J - changed loop order here to leave y as the innermost loop for + // better cache performance + for (int z = z0; z < z1; z++) { + for (int x = x0; x < x1; x++) { + for (int y = y0; y < y1; y++) { + // 4J - get tile from those copied into our local array in + // earlier optimisation + unsigned char tileId = pOutData->getTile(x, y, z); + if (tileId > 0) { + if (currentLayer == 0 && + Tile::tiles[tileId]->isEntityTile()) { + std::shared_ptr et = + region.getTileEntity(x, y, z); + if (TileEntityRenderDispatcher::instance + ->hasRenderer(et)) { + renderableTileEntities.push_back(et); + } + } + int flags = pOutData->getFlags(x, y, z); + if (flags & + ChunkRebuildData::e_flag_SPURenderCodeMissing) { + Tile* tile = Tile::tiles[tileId]; + int renderLayer = tile->getRenderLayer(); - oldTileEntities.removeAll(renderableTileEntities); - globalRenderableTileEntities.removeAll(oldTileEntities); - */ - + if (renderLayer != currentLayer) { + // renderNextLayer + //= true; + } else if (renderLayer == currentLayer) { + // if(currentLayer == 0) + // numRenderedLayer0++; + rendered |= tileRenderer.tesselateInWorld( + tile, x, y, z); + } + } + } + } + } + } - std::unordered_set > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); - for( std::unordered_set >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) - { - newTileEntities.erase(*it); - } + { + t->end(); + bounds.addBounds(t->bounds); + glPopMatrix(); + glEndList(); + t->useCompactVertices(false); // 4J added + t->offset(0, 0, 0); + } + if (rendered) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); + } else { + // 4J - added - clear any renderer data associated with this unused + // list + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } + } - // 4J - newTileEntities is now renderableTileEntities with any old ones from oldTileEntitesRemoved (so just new things added) + if (bb) { + bb->set(bounds.boundingBox[0], bounds.boundingBox[1], + bounds.boundingBox[2], bounds.boundingBox[3], + bounds.boundingBox[4], bounds.boundingBox[5]); + } - EnterCriticalSection(globalRenderableTileEntities_cs); - endIt = newTileEntities.end(); - for( std::unordered_set >::iterator it = newTileEntities.begin(); it != endIt; it++ ) - { - globalRenderableTileEntities.push_back(*it); - } + if (pOutData->m_flags & ChunkRebuildData::e_flag_TouchedSky) + LevelChunk::touchedSky = true; - // 4J - All these new things added to globalRenderableTileEntities + // 4J - have rewritten the way that tile entities are stored globally to + // make it work more easily with split screen. Chunks are now stored + // globally in the levelrenderer, in a hashmap with a special key made up + // from the dimension and chunk position (using same index as is used for + // global flags) +#if 1 + int key = + levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, level); + EnterCriticalSection(globalRenderableTileEntities_cs); + if (renderableTileEntities.size()) { + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + // We've got some renderable tile entities that we want associated + // with this chunk, and an existing list of things that used to be. + // We need to flag any that we don't need any more to be removed, + // keep those that we do, and add any new ones - AUTO_VAR(endItRTE, renderableTileEntities.end()); - for( std::vector >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) - { - oldTileEntities.erase(*it); - } - // 4J - oldTileEntities is now the removed items - std::vector >::iterator it = globalRenderableTileEntities->begin(); - while( it != globalRenderableTileEntities->end() ) - { - if( oldTileEntities.find(*it) != oldTileEntities.end() ) - { - it = globalRenderableTileEntities->erase(it); - } - else - { - ++it; - } - } + // First pass - flag everything already existing to be removed + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } - LeaveCriticalSection(globalRenderableTileEntities_cs); + // Now go through the current list. If these are already in the + // list, then unflag the remove flag. If they aren't, then add + for (int i = 0; i < renderableTileEntities.size(); i++) { + AUTO_VAR(it2, find(it->second.begin(), it->second.end(), + renderableTileEntities[i])); + if (it2 == it->second.end()) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } else { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageKeep); + } + } + } else { + // Easy case - nothing already existing for this chunk. Add them all + // in. + for (int i = 0; i < renderableTileEntities.size(); i++) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } + } + } else { + // Another easy case - we don't want any renderable tile entities + // associated with this chunk. Flag all to be removed. + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } + } + } + LeaveCriticalSection(globalRenderableTileEntities_cs); +#else + // Find the removed ones: + + // 4J - original code for this section: + /* + Set newTileEntities = new HashSet(); + newTileEntities.addAll(renderableTileEntities); + newTileEntities.removeAll(oldTileEntities); + globalRenderableTileEntities.addAll(newTileEntities); + + oldTileEntities.removeAll(renderableTileEntities); + globalRenderableTileEntities.removeAll(oldTileEntities); + */ + + std::unordered_set > newTileEntities( + renderableTileEntities.begin(), renderableTileEntities.end()); + + AUTO_VAR(endIt, oldTileEntities.end()); + for (std::unordered_set >::iterator it = + oldTileEntities.begin(); + it != endIt; it++) { + newTileEntities.erase(*it); + } + + // 4J - newTileEntities is now renderableTileEntities with any old ones from + // oldTileEntitesRemoved (so just new things added) + + EnterCriticalSection(globalRenderableTileEntities_cs); + endIt = newTileEntities.end(); + for (std::unordered_set >::iterator it = + newTileEntities.begin(); + it != endIt; it++) { + globalRenderableTileEntities.push_back(*it); + } + + // 4J - All these new things added to globalRenderableTileEntities + + AUTO_VAR(endItRTE, renderableTileEntities.end()); + for (std::vector >::iterator it = + renderableTileEntities.begin(); + it != endItRTE; it++) { + oldTileEntities.erase(*it); + } + // 4J - oldTileEntities is now the removed items + std::vector >::iterator it = + globalRenderableTileEntities->begin(); + while (it != globalRenderableTileEntities->end()) { + if (oldTileEntities.find(*it) != oldTileEntities.end()) { + it = globalRenderableTileEntities->erase(it); + } else { + ++it; + } + } + + LeaveCriticalSection(globalRenderableTileEntities_cs); #endif - // 4J - These removed items are now also removed from globalRenderableTileEntities - - if( LevelChunk::touchedSky ) - { - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - else - { - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED); - return; + // 4J - These removed items are now also removed from + // globalRenderableTileEntities + if (LevelChunk::touchedSky) { + levelRenderer->clearGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } else { + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED); + return; } -#endif // _PS3_ +#endif // _PS3_ - -float Chunk::distanceToSqr(std::shared_ptr player) const -{ - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym); - float zd = (float) (player->z - zm); - return xd * xd + yd * yd + zd * zd; +float Chunk::distanceToSqr(std::shared_ptr player) const { + float xd = (float)(player->x - xm); + float yd = (float)(player->y - ym); + float zd = (float)(player->z - zm); + return xd * xd + yd * yd + zd * zd; } -float Chunk::squishedDistanceToSqr(std::shared_ptr player) -{ - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym) * 2; - float zd = (float) (player->z - zm); - return xd * xd + yd * yd + zd * zd; +float Chunk::squishedDistanceToSqr(std::shared_ptr player) { + float xd = (float)(player->x - xm); + float yd = (float)(player->y - ym) * 2; + float zd = (float)(player->z - zm); + return xd * xd + yd * yd + zd * zd; } -void Chunk::reset() -{ - if( assigned ) - { - EnterCriticalSection(&levelRenderer->m_csDirtyChunks); - unsigned char refCount = levelRenderer->decGlobalChunkRefCount(x, y, z, level); - assigned = false; -// printf("\t\t [dec] refcount %d at %d, %d, %d\n",refCount,x,y,z); - if( refCount == 0 ) - { - int lists = levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; - if(lists >= 0) - { - lists += levelRenderer->chunkLists; - for (int i = 0; i < 2; i++) - { - // 4J - added - clear any renderer data associated with this unused list - RenderManager.CBuffClear(lists + i); - } - levelRenderer->setGlobalChunkFlags(x, y, z, level, 0); - } - } - LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); - } +void Chunk::reset() { + if (assigned) { + EnterCriticalSection(&levelRenderer->m_csDirtyChunks); + unsigned char refCount = + levelRenderer->decGlobalChunkRefCount(x, y, z, level); + assigned = false; + // printf("\t\t [dec] refcount %d at %d, %d, + //%d\n",refCount,x,y,z); + if (refCount == 0) { + int lists = + levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; + if (lists >= 0) { + lists += levelRenderer->chunkLists; + for (int i = 0; i < 2; i++) { + // 4J - added - clear any renderer data associated with this + // unused list + RenderManager.CBuffClear(lists + i); + } + levelRenderer->setGlobalChunkFlags(x, y, z, level, 0); + } + } + LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); + } - clipChunk->visible = false; + clipChunk->visible = false; } -void Chunk::_delete() -{ - reset(); - level = NULL; +void Chunk::_delete() { + reset(); + level = NULL; } -int Chunk::getList(int layer) -{ - if (!clipChunk->visible) return -1; +int Chunk::getList(int layer) { + if (!clipChunk->visible) return -1; - int lists = levelRenderer->getGlobalIndexForChunk(x, y, z,level) * 2; - lists += levelRenderer->chunkLists; + int lists = levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; + lists += levelRenderer->chunkLists; - bool empty = levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); - if (!empty) return lists + layer; - return -1; + bool empty = levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); + if (!empty) return lists + layer; + return -1; } -void Chunk::cull(Culler *culler) -{ - clipChunk->visible = culler->isVisible(bb); +void Chunk::cull(Culler* culler) { clipChunk->visible = culler->isVisible(bb); } + +void Chunk::renderBB() { + // glCallList(lists + 2); // 4J - removed - TODO put back in } -void Chunk::renderBB() -{ -// glCallList(lists + 2); // 4J - removed - TODO put back in +bool Chunk::isEmpty() { + if (!levelRenderer->getGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED)) + return false; + return levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTYBOTH); } -bool Chunk::isEmpty() -{ - if (!levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED)) return false; - return levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTYBOTH); +void Chunk::setDirty() { + // 4J - not used, but if this starts being used again then we'll need to + // investigate how best to handle it. + __debugbreak(); + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); } -void Chunk::setDirty() -{ - // 4J - not used, but if this starts being used again then we'll need to investigate how best to handle it. - __debugbreak(); - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY); -} - -void Chunk::clearDirty() -{ - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY); +void Chunk::clearDirty() { + levelRenderer->clearGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); #ifdef _CRITICAL_CHUNKS - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_CRITICAL); + levelRenderer->clearGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_CRITICAL); #endif } -Chunk::~Chunk() -{ - delete bb; -} +Chunk::~Chunk() { delete bb; } -bool Chunk::emptyFlagSet(int layer) -{ - return levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); +bool Chunk::emptyFlagSet(int layer) { + return levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); } diff --git a/Minecraft.Client/Rendering/Chunk.h b/Minecraft.Client/Rendering/Chunk.h index efcdfc914..23d5ef532 100644 --- a/Minecraft.Client/Rendering/Chunk.h +++ b/Minecraft.Client/Rendering/Chunk.h @@ -8,80 +8,85 @@ class Level; class TileEntity; class Entity; - -class ClipChunk -{ +class ClipChunk { public: - Chunk *chunk; - int globalIdx; - bool visible; - float aabb[6]; - int xm, ym, zm; + Chunk* chunk; + int globalIdx; + bool visible; + float aabb[6]; + int xm, ym, zm; }; -class Chunk -{ +class Chunk { private: - static const int XZSIZE = LevelRenderer::CHUNK_XZSIZE; - static const int SIZE = LevelRenderer::CHUNK_SIZE; + static const int XZSIZE = LevelRenderer::CHUNK_XZSIZE; + static const int SIZE = LevelRenderer::CHUNK_SIZE; public: - Level *level; - static LevelRenderer *levelRenderer; + Level* level; + static LevelRenderer* levelRenderer; + private: #ifndef _LARGE_WORLDS - static Tesselator *t; + static Tesselator* t; #else - static unsigned int tlsIdx; + static unsigned int tlsIdx; + public: - static void CreateNewThreadStorage(); - static void ReleaseThreadStorage(); - static unsigned char *GetTileIdsStorage(); + static void CreateNewThreadStorage(); + static void ReleaseThreadStorage(); + static unsigned char* GetTileIdsStorage(); #endif - + public: - static int updates; + static int updates; int x, y, z; int xRender, yRender, zRender; int xRenderOffs, yRenderOffs, zRenderOffs; - + int xm, ym, zm; - AABB *bb; - ClipChunk *clipChunk; + AABB* bb; + ClipChunk* clipChunk; int id; -//public: -// std::vector > renderableTileEntities; // 4J - removed - + // public: + // std::vector > renderableTileEntities; + //// 4J - removed + private: - LevelRenderer::rteMap *globalRenderableTileEntities; - CRITICAL_SECTION *globalRenderableTileEntities_cs; - bool assigned; + LevelRenderer::rteMap* globalRenderableTileEntities; + CRITICAL_SECTION* globalRenderableTileEntities_cs; + bool assigned; + public: - Chunk(Level *level, LevelRenderer::rteMap &globalRenderableTileEntities, CRITICAL_SECTION &globalRenderableTileEntities_cs, int x, int y, int z, ClipChunk *clipChunk); - Chunk(); + Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities, + CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, + int z, ClipChunk* clipChunk); + Chunk(); void setPos(int x, int y, int z); + private: - void translateToPos(); + void translateToPos(); + public: - void makeCopyForRebuild(Chunk *source); - void rebuild(); + void makeCopyForRebuild(Chunk* source); + void rebuild(); #ifdef __PS3__ - void rebuild_SPU(); -#endif // __PS3__ - float distanceToSqr(std::shared_ptr player) const; + void rebuild_SPU(); +#endif // __PS3__ + float distanceToSqr(std::shared_ptr player) const; float squishedDistanceToSqr(std::shared_ptr player); void reset(); void _delete(); int getList(int layer); - void cull(Culler *culler); - void renderBB() ; + void cull(Culler* culler); + void renderBB(); bool isEmpty(); void setDirty(); - void clearDirty(); // 4J added - bool emptyFlagSet(int layer); - ~Chunk(); + void clearDirty(); // 4J added + bool emptyFlagSet(int layer); + ~Chunk(); }; diff --git a/Minecraft.Client/Rendering/Cube.cpp b/Minecraft.Client/Rendering/Cube.cpp index e3124c41f..259eb9cac 100644 --- a/Minecraft.Client/Rendering/Cube.cpp +++ b/Minecraft.Client/Rendering/Cube.cpp @@ -3,35 +3,35 @@ #include "Models/ModelPart.h" #include "Cube.h" - - // 4J - added - helper function to set up vertex arrays -VertexArray Cube::VertexArray4(Vertex *v0, Vertex *v1, Vertex *v2, Vertex *v3) -{ - VertexArray ret = VertexArray(4); - ret[0] = v0; - ret[1] = v1; - ret[2] = v2; - ret[3] = v3; +VertexArray Cube::VertexArray4(Vertex* v0, Vertex* v1, Vertex* v2, Vertex* v3) { + VertexArray ret = VertexArray(4); + ret[0] = v0; + ret[1] = v1; + ret[2] = v2; + ret[3] = v3; - return ret; + return ret; } -//void Cube::addBox(float x0, float y0, float z0, int w, int h, int d, float g) -Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g, int faceMask /* = 63 */, bool bFlipPoly3UVs) : // 4J - added faceMask, added bFlipPoly3UVs to reverse the uvs back so player skins display right - x0(x0), - y0(y0), - z0(z0), - x1(x0 + w), - y1(y0 + h), - z1(z0 + d) -{ -// this->x0 = x0; -// this->y0 = y0; -// this->z0 = z0; -// this->x1 = x0 + w; -// this->y1 = y0 + h; -// this->z1 = z0 + d; +// void Cube::addBox(float x0, float y0, float z0, int w, int h, int d, float g) +Cube::Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, + float z0, int w, int h, int d, float g, int faceMask /* = 63 */, + bool bFlipPoly3UVs) + : // 4J - added faceMask, added bFlipPoly3UVs to reverse the uvs back so + // player skins display right + x0(x0), + y0(y0), + z0(z0), + x1(x0 + w), + y1(y0 + h), + z1(z0 + d) { + // this->x0 = x0; + // this->y0 = y0; + // this->z0 = z0; + // this->x1 = x0 + w; + // this->y1 = y0 + h; + // this->z1 = z0 + d; vertices = VertexArray(8); polygons = PolygonArray(6); @@ -47,22 +47,21 @@ Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, y1 += g; z1 += g; - if (modelPart->bMirror) - { + if (modelPart->bMirror) { float tmp = x1; x1 = x0; x0 = tmp; } - Vertex *u0 = new Vertex(x0, y0, z0, 0, 0); - Vertex *u1 = new Vertex(x1, y0, z0, 0, 8); - Vertex *u2 = new Vertex(x1, y1, z0, 8, 8); - Vertex *u3 = new Vertex(x0, y1, z0, 8, 0); - - Vertex *l0 = new Vertex(x0, y0, z1, 0, 0); - Vertex *l1 = new Vertex(x1, y0, z1, 0, 8); - Vertex *l2 = new Vertex(x1, y1, z1, 8, 8); - Vertex *l3 = new Vertex(x0, y1, z1, 8, 0); + Vertex* u0 = new Vertex(x0, y0, z0, 0, 0); + Vertex* u1 = new Vertex(x1, y0, z0, 0, 8); + Vertex* u2 = new Vertex(x1, y1, z0, 8, 8); + Vertex* u3 = new Vertex(x0, y1, z0, 8, 0); + + Vertex* l0 = new Vertex(x0, y0, z1, 0, 0); + Vertex* l1 = new Vertex(x1, y0, z1, 0, 8); + Vertex* l2 = new Vertex(x1, y1, z1, 8, 8); + Vertex* l3 = new Vertex(x0, y1, z1, 8, 0); vertices[0] = u0; vertices[1] = u1; @@ -73,41 +72,61 @@ Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, vertices[6] = l2; vertices[7] = l3; - // 4J - added ability to mask individual faces - int faceCount = 0; - if( faceMask & 1 ) polygons[faceCount++] = new _Polygon(VertexArray4(l1, u1, u2, l2), xTexOffs + d + w, yTexOffs + d, xTexOffs + d + w + d, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Right - if( faceMask & 2 ) polygons[faceCount++] = new _Polygon(VertexArray4(u0, l0, l3, u3), xTexOffs + 0, yTexOffs + d, xTexOffs + d, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Left - if( faceMask & 4 ) polygons[faceCount++] = new _Polygon(VertexArray4(l1, l0, u0, u1), xTexOffs + d, yTexOffs + 0, xTexOffs + d + w, yTexOffs + d, modelPart->xTexSize, modelPart->yTexSize); // Up - if(bFlipPoly3UVs) - { - if( faceMask & 8 ) polygons[faceCount++] = new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, yTexOffs + 0, xTexOffs + d + w + w, yTexOffs + d, modelPart->xTexSize, modelPart->yTexSize); // Down - } - else - { - if( faceMask & 8 ) polygons[faceCount++] = new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, yTexOffs + d, xTexOffs + d + w + w, yTexOffs + 0, modelPart->xTexSize, modelPart->yTexSize); // Down - } - if( faceMask & 16 ) polygons[faceCount++] = new _Polygon(VertexArray4(u1, u0, u3, u2), xTexOffs + d, yTexOffs + d, xTexOffs + d + w, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Front - if( faceMask & 32 ) polygons[faceCount++] = new _Polygon(VertexArray4(l0, l1, l2, l3), xTexOffs + d + w + d, yTexOffs + d, xTexOffs + d + w + d + w, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Back - polygons.length = faceCount; + // 4J - added ability to mask individual faces + int faceCount = 0; + if (faceMask & 1) + polygons[faceCount++] = + new _Polygon(VertexArray4(l1, u1, u2, l2), xTexOffs + d + w, + yTexOffs + d, xTexOffs + d + w + d, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Right + if (faceMask & 2) + polygons[faceCount++] = + new _Polygon(VertexArray4(u0, l0, l3, u3), xTexOffs + 0, + yTexOffs + d, xTexOffs + d, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Left + if (faceMask & 4) + polygons[faceCount++] = + new _Polygon(VertexArray4(l1, l0, u0, u1), xTexOffs + d, + yTexOffs + 0, xTexOffs + d + w, yTexOffs + d, + modelPart->xTexSize, modelPart->yTexSize); // Up + if (bFlipPoly3UVs) { + if (faceMask & 8) + polygons[faceCount++] = + new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, + yTexOffs + 0, xTexOffs + d + w + w, yTexOffs + d, + modelPart->xTexSize, modelPart->yTexSize); // Down + } else { + if (faceMask & 8) + polygons[faceCount++] = + new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, + yTexOffs + d, xTexOffs + d + w + w, yTexOffs + 0, + modelPart->xTexSize, modelPart->yTexSize); // Down + } + if (faceMask & 16) + polygons[faceCount++] = + new _Polygon(VertexArray4(u1, u0, u3, u2), xTexOffs + d, + yTexOffs + d, xTexOffs + d + w, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Front + if (faceMask & 32) + polygons[faceCount++] = new _Polygon( + VertexArray4(l0, l1, l2, l3), xTexOffs + d + w + d, yTexOffs + d, + xTexOffs + d + w + d + w, yTexOffs + d + h, modelPart->xTexSize, + modelPart->yTexSize); // Back + polygons.length = faceCount; - if (modelPart->bMirror) - { + if (modelPart->bMirror) { for (unsigned int i = 0; i < polygons.length; i++) polygons[i]->mirror(); } } - -void Cube::render(Tesselator *t,float scale) -{ - for (int i = 0; i < polygons.length; i++) - { - polygons[i]->render(t, scale); - } +void Cube::render(Tesselator* t, float scale) { + for (int i = 0; i < polygons.length; i++) { + polygons[i]->render(t, scale); + } } -Cube *Cube::setId(const std::wstring &id) -{ - this->id = id; - return this; +Cube* Cube::setId(const std::wstring& id) { + this->id = id; + return this; } diff --git a/Minecraft.Client/Rendering/Cube.h b/Minecraft.Client/Rendering/Cube.h index eafa57ba5..549672e45 100644 --- a/Minecraft.Client/Rendering/Cube.h +++ b/Minecraft.Client/Rendering/Cube.h @@ -5,25 +5,25 @@ class Model; -class Cube -{ - +class Cube { private: - VertexArray vertices; + VertexArray vertices; PolygonArray polygons; - -public: - - const float x0, y0, z0, x1, y1, z1; - std::wstring id; public: - Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g, int faceMask = 63, bool bFlipPoly3UVs = false); // 4J - added faceMask + const float x0, y0, z0, x1, y1, z1; + std::wstring id; + +public: + Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, + float z0, int w, int h, int d, float g, int faceMask = 63, + bool bFlipPoly3UVs = false); // 4J - added faceMask private: - VertexArray VertexArray4(Vertex *v0, Vertex *v1, Vertex *v2, Vertex *v3); // 4J added + VertexArray VertexArray4(Vertex* v0, Vertex* v1, Vertex* v2, + Vertex* v3); // 4J added public: - void render(Tesselator *t,float scale); - Cube *setId(const std::wstring &id); + void render(Tesselator* t, float scale); + Cube* setId(const std::wstring& id); }; diff --git a/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp b/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp index f72d825e2..87ef63f07 100644 --- a/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp +++ b/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp @@ -1,21 +1,16 @@ #include "../../Platform/stdafx.h" -#include "AllowAllCuller.h" +#include "AllowAllCuller.h" -bool AllowAllCuller::isVisible(AABB *bb) -{ - return true; +bool AllowAllCuller::isVisible(AABB* bb) { return true; } + +bool AllowAllCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + return true; } -bool AllowAllCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return true; +bool AllowAllCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + return true; } -bool AllowAllCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return true; -} - -void AllowAllCuller::prepare(double xOff, double yOff, double zOff) -{ -} \ No newline at end of file +void AllowAllCuller::prepare(double xOff, double yOff, double zOff) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/AllowAllCuller.h b/Minecraft.Client/Rendering/Culling/AllowAllCuller.h index 5b866049e..3851d6114 100644 --- a/Minecraft.Client/Rendering/Culling/AllowAllCuller.h +++ b/Minecraft.Client/Rendering/Culling/AllowAllCuller.h @@ -1,11 +1,12 @@ #pragma once #include "Culler.h" -class AllowAllCuller -{ +class AllowAllCuller { public: - virtual bool isVisible(AABB *bb); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual void prepare(double xOff, double yOff, double zOff); + virtual bool isVisible(AABB* bb); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual void prepare(double xOff, double yOff, double zOff); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/Culler.h b/Minecraft.Client/Rendering/Culling/Culler.h index 83ab87ef0..a84da40c9 100644 --- a/Minecraft.Client/Rendering/Culling/Culler.h +++ b/Minecraft.Client/Rendering/Culling/Culler.h @@ -1,11 +1,12 @@ #pragma once #include "../../../Minecraft.World/Util/AABB.h" -class Culler -{ +class Culler { public: - virtual bool isVisible(AABB *bb) = 0; - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) = 0; - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) = 0; - virtual void prepare(double xOff, double yOff, double zOff) = 0; + virtual bool isVisible(AABB* bb) = 0; + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) = 0; + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) = 0; + virtual void prepare(double xOff, double yOff, double zOff) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp index a93002c59..cfb90360b 100644 --- a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp +++ b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp @@ -3,14 +3,14 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../Chunk.h" -DirtyChunkSorter::DirtyChunkSorter(std::shared_ptr cameraEntity, int playerIndex) // 4J - added player index +DirtyChunkSorter::DirtyChunkSorter(std::shared_ptr cameraEntity, + int playerIndex) // 4J - added player index { - this->cameraEntity = cameraEntity; - this->playerIndex = playerIndex; + this->cameraEntity = cameraEntity; + this->playerIndex = playerIndex; } -bool DirtyChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const -{ +bool DirtyChunkSorter::operator()(const Chunk* c0, const Chunk* c1) const { bool i0 = c0->clipChunk->visible; bool i1 = c1->clipChunk->visible; if (i0 && !i1) return false; @@ -22,5 +22,5 @@ bool DirtyChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const if (d0 < d1) return false; if (d0 > d1) return true; - return c0->id >= c1->id; // 4J - was c0.id < c1.id ? 1 : -1 + return c0->id >= c1->id; // 4J - was c0.id < c1.id ? 1 : -1 } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h index 0de6efda3..523a8754e 100644 --- a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h +++ b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h @@ -2,13 +2,13 @@ class Chunk; class Mob; -class DirtyChunkSorter -{ +class DirtyChunkSorter { private: - std::shared_ptr cameraEntity; - int playerIndex; // 4J added + std::shared_ptr cameraEntity; + int playerIndex; // 4J added public: - DirtyChunkSorter(std::shared_ptr cameraEntity, int playerIndex); // 4J - added player index - bool operator()(const Chunk *a, const Chunk *b) const; + DirtyChunkSorter(std::shared_ptr cameraEntity, + int playerIndex); // 4J - added player index + bool operator()(const Chunk* a, const Chunk* b) const; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp index f67380a0a..09ff30e06 100644 --- a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp +++ b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp @@ -3,22 +3,22 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../Chunk.h" -DistanceChunkSorter::DistanceChunkSorter(std::shared_ptr player) -{ +DistanceChunkSorter::DistanceChunkSorter(std::shared_ptr player) { ix = -player->x; iy = -player->y; iz = -player->z; } -bool DistanceChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const -{ +bool DistanceChunkSorter::operator()(const Chunk* c0, const Chunk* c1) const { double xd0 = c0->xm + ix; double yd0 = c0->ym + iy; double zd0 = c0->zm + iz; - + double xd1 = c1->xm + ix; double yd1 = c1->ym + iy; double zd1 = c1->zm + iz; - return (((xd0 * xd0 + yd0 * yd0 + zd0 * zd0) - (xd1 * xd1 + yd1 * yd1 + zd1 * zd1)) * 1024) < 0.0; + return (((xd0 * xd0 + yd0 * yd0 + zd0 * zd0) - + (xd1 * xd1 + yd1 * yd1 + zd1 * zd1)) * + 1024) < 0.0; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h index 461ec79a1..2557d9ece 100644 --- a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h +++ b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h @@ -2,12 +2,11 @@ class Entity; class Chunk; -class DistanceChunkSorter -{ +class DistanceChunkSorter { private: - double ix, iy, iz; + double ix, iy, iz; public: DistanceChunkSorter(std::shared_ptr player); - bool operator()(const Chunk *a, const Chunk *b) const; + bool operator()(const Chunk* a, const Chunk* b) const; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp b/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp index 8c6d5beb5..7b07efaaf 100644 --- a/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp +++ b/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp @@ -2,98 +2,96 @@ #include "ViewportCuller.h" #include "../../../Minecraft.World/Util/Mth.h" -ViewportCuller::Face::Face(double x, double y, double z, float yRot, float xRot) -{ +ViewportCuller::Face::Face(double x, double y, double z, float yRot, + float xRot) { this->xc = x; this->yc = y; this->zc = z; - + xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); yd = -Mth::sin(xRot / 180 * PI); - - cullOffs = xc*xd+yc*yd+zc*zd; -} - -bool ViewportCuller::Face::inFront(double x, double y, double z, double r) -{ - return x*xd+y*yd+z*zd>cullOffs-r; + + cullOffs = xc * xd + yc * yd + zc * zd; } -bool ViewportCuller::Face::inFront(double x0, double y0, double z0, double x1, double y1, double z1) -{ - if ( - x0*xd+y0*yd+z0*zd>cullOffs || - x1*xd+y0*yd+z0*zd>cullOffs || - x0*xd+y1*yd+z0*zd>cullOffs || - x1*xd+y1*yd+z0*zd>cullOffs || - x0*xd+y0*yd+z1*zd>cullOffs || - x1*xd+y0*yd+z1*zd>cullOffs || - x0*xd+y1*yd+z1*zd>cullOffs || - x1*xd+y1*yd+z1*zd>cullOffs - ) return true; +bool ViewportCuller::Face::inFront(double x, double y, double z, double r) { + return x * xd + y * yd + z * zd > cullOffs - r; +} + +bool ViewportCuller::Face::inFront(double x0, double y0, double z0, double x1, + double y1, double z1) { + if (x0 * xd + y0 * yd + z0 * zd > cullOffs || + x1 * xd + y0 * yd + z0 * zd > cullOffs || + x0 * xd + y1 * yd + z0 * zd > cullOffs || + x1 * xd + y1 * yd + z0 * zd > cullOffs || + x0 * xd + y0 * yd + z1 * zd > cullOffs || + x1 * xd + y0 * yd + z1 * zd > cullOffs || + x0 * xd + y1 * yd + z1 * zd > cullOffs || + x1 * xd + y1 * yd + z1 * zd > cullOffs) + return true; return false; } -bool ViewportCuller::Face::fullyInFront(double x0, double y0, double z0, double x1, double y1, double z1) -{ - if ( x0*xd+y0*yd+z0*zd mob, double fogDistance, float a) -{ - float yRot = mob->yRotO+(mob->yRot-mob->yRotO)*a; - float xRot = mob->xRotO+(mob->xRot-mob->xRotO)*a; - - double x = mob->xOld+(mob->x-mob->xOld)*a; - double y = mob->yOld+(mob->y-mob->yOld)*a; - double z = mob->zOld+(mob->z-mob->zOld)*a; +ViewportCuller::ViewportCuller(std::shared_ptr mob, double fogDistance, + float a) { + float yRot = mob->yRotO + (mob->yRot - mob->yRotO) * a; + float xRot = mob->xRotO + (mob->xRot - mob->xRotO) * a; - double xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - double zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - double yd = -Mth::sin(xRot / 180 * PI); + double x = mob->xOld + (mob->x - mob->xOld) * a; + double y = mob->yOld + (mob->y - mob->yOld) * a; + double z = mob->zOld + (mob->z - mob->zOld) * a; - float xFov = 30; - float yFov = 45; - faces[0] = Face(x, y, z, yRot, xRot); - faces[1] = Face(x, y, z, yRot+xFov, xRot); - faces[2] = Face(x, y, z, yRot-xFov, xRot); - faces[3] = Face(x, y, z, yRot, xRot+yFov); - faces[4] = Face(x, y, z, yRot, xRot-yFov); - faces[5] = Face(x+xd*fogDistance, y+yd*fogDistance, z+zd*fogDistance, yRot+180, -xRot); + double xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + double zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + double yd = -Mth::sin(xRot / 180 * PI); + + float xFov = 30; + float yFov = 45; + faces[0] = Face(x, y, z, yRot, xRot); + faces[1] = Face(x, y, z, yRot + xFov, xRot); + faces[2] = Face(x, y, z, yRot - xFov, xRot); + faces[3] = Face(x, y, z, yRot, xRot + yFov); + faces[4] = Face(x, y, z, yRot, xRot - yFov); + faces[5] = Face(x + xd * fogDistance, y + yd * fogDistance, + z + zd * fogDistance, yRot + 180, -xRot); } -bool ViewportCuller::isVisible(AABB bb) -{ - return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); +bool ViewportCuller::isVisible(AABB bb) { + return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); } -bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - x0-=xOff; - y0-=yOff; - z0-=zOff; - x1-=xOff; - y1-=yOff; - z1-=zOff; - double xd = (x1-x0)/2.0f; - double yd = (y1-y0)/2.0f; - double zd = (z1-z0)/2.0f; - - double xc = x0+xd; - double yc = y0+yd; - double zc = z0+zd; - double r = _max(xd, yd, zd)*1.5f; - +bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + x0 -= xOff; + y0 -= yOff; + z0 -= zOff; + x1 -= xOff; + y1 -= yOff; + z1 -= zOff; + double xd = (x1 - x0) / 2.0f; + double yd = (y1 - y0) / 2.0f; + double zd = (z1 - z0) / 2.0f; + + double xc = x0 + xd; + double yc = y0 + yd; + double zc = z0 + zd; + double r = _max(xd, yd, zd) * 1.5f; + if (!faces[0].inFront(xc, yc, zc, r)) return false; if (!faces[1].inFront(xc, yc, zc, r)) return false; if (!faces[2].inFront(xc, yc, zc, r)) return false; @@ -108,26 +106,25 @@ bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, d if (!faces[4].inFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[5].inFront(x0, y0, z0, x1, y1, z1)) return false; return true; - } -bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - x0-=xOff; - y0-=yOff; - z0-=zOff; - x1-=xOff; - y1-=yOff; - z1-=zOff; +bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + x0 -= xOff; + y0 -= yOff; + z0 -= zOff; + x1 -= xOff; + y1 -= yOff; + z1 -= zOff; - double xd = (x1-x0)/2.0f; - double yd = (y1-y0)/2.0f; - double zd = (z1-z0)/2.0f; - - double xc = x0+xd; - double yc = y0+yd; - double zc = z0+zd; - double r = _max(xd, yd, zd)*1.5f; + double xd = (x1 - x0) / 2.0f; + double yd = (y1 - y0) / 2.0f; + double zd = (z1 - z0) / 2.0f; + + double xc = x0 + xd; + double yc = y0 + yd; + double zc = z0 + zd; + double r = _max(xd, yd, zd) * 1.5f; if (!faces[0].inFront(xc, yc, zc, r)) return false; if (!faces[1].inFront(xc, yc, zc, r)) return false; @@ -135,8 +132,7 @@ bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double if (!faces[3].inFront(xc, yc, zc, r)) return false; if (!faces[4].inFront(xc, yc, zc, r)) return false; if (!faces[5].inFront(xc, yc, zc, r)) return false; - - + if (!faces[0].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[1].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[2].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; @@ -146,13 +142,11 @@ bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double return true; } -double ViewportCuller::_max(double a, double b, double c) -{ - return (a>b?a>c?c:a:b>c?b:c); +double ViewportCuller::_max(double a, double b, double c) { + return (a > b ? a > c ? c : a : b > c ? b : c); } -void ViewportCuller::prepare(double xOff, double yOff, double zOff) -{ +void ViewportCuller::prepare(double xOff, double yOff, double zOff) { this->xOff = xOff; this->yOff = yOff; this->zOff = zOff; diff --git a/Minecraft.Client/Rendering/Culling/ViewportCuller.h b/Minecraft.Client/Rendering/Culling/ViewportCuller.h index 251f17130..0d634f9b1 100644 --- a/Minecraft.Client/Rendering/Culling/ViewportCuller.h +++ b/Minecraft.Client/Rendering/Culling/ViewportCuller.h @@ -3,33 +3,41 @@ #include "../../../Minecraft.World/Entities/Mob.h" class Mob; -class ViewportCuller : public Culler -{ +class ViewportCuller : public Culler { private: - class Face - { - private: + class Face { + private: double xc, yc, zc; double xd, yd, zd; double cullOffs; - public: - Face() {} // 4J - added so we can declare an array of these (unitialised) in the class - Face(double x, double y, double z, float yRot, float xRot); + + public: + Face() {} // 4J - added so we can declare an array of these + // (unitialised) in the class + Face(double x, double y, double z, float yRot, float xRot); bool inFront(double x, double y, double z, double r); - bool inFront(double x0, double y0, double z0, double x1, double y1, double z1); - bool fullyInFront(double x0, double y0, double z0, double x1, double y1, double z1); + bool inFront(double x0, double y0, double z0, double x1, double y1, + double z1); + bool fullyInFront(double x0, double y0, double z0, double x1, double y1, + double z1); }; private: - Face faces[6]; + Face faces[6]; double xOff, yOff, zOff; + public: - ViewportCuller(std::shared_ptr mob, double fogDistance, float a); + ViewportCuller(std::shared_ptr mob, double fogDistance, float a); virtual bool isVisible(AABB bb); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + private: - double _max(double a, double b, double c); // 4J - renamed from _max due to #define conflict in stdlib + double _max( + double a, double b, + double c); // 4J - renamed from _max due to #define conflict in stdlib public: virtual void prepare(double xOff, double yOff, double zOff); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp index 85d475925..83d7764e5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp @@ -3,29 +3,34 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.projectile.h" #include "../../../Minecraft.World/Util/Mth.h" -void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Arrow rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr arrow = std::dynamic_pointer_cast(_arrow); - bindTexture(TN_ITEM_ARROWS); // 4J - was L"/item/arrows.png" +void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Arrow rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr arrow = std::dynamic_pointer_cast(_arrow); + bindTexture(TN_ITEM_ARROWS); // 4J - was L"/item/arrows.png" glPushMatrix(); - float yRot = arrow->yRot; - float xRot = arrow->xRot; - float yRotO = arrow->yRotO; - float xRotO = arrow->xRotO; - if( ( yRot - yRotO ) > 180.0f ) yRot -= 360.0f; - else if( ( yRot - yRotO ) < -180.0f ) yRot += 360.0f; - if( ( xRot - xRotO ) > 180.0f ) xRot -= 360.0f; - else if( ( xRot - xRotO ) < -180.0f ) xRot += 360.0f; + float yRot = arrow->yRot; + float xRot = arrow->xRot; + float yRotO = arrow->yRotO; + float xRotO = arrow->xRotO; + if ((yRot - yRotO) > 180.0f) + yRot -= 360.0f; + else if ((yRot - yRotO) < -180.0f) + yRot += 360.0f; + if ((xRot - xRotO) > 180.0f) + xRot -= 360.0f; + else if ((xRot - xRotO) < -180.0f) + xRot += 360.0f; glTranslatef((float)x, (float)y, (float)z); glRotatef(yRotO + (yRot - yRotO) * a - 90, 0, 1, 0); glRotatef(xRotO + (xRot - xRotO) * a, 0, 0, 1); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); int type = 0; float u0 = 0 / 32.0f; @@ -39,10 +44,9 @@ void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, d float v12 = (10 + type * 10) / 32.0f; float ss = 0.9f / 16.0f; glEnable(GL_RESCALE_NORMAL); - float shake = arrow->shakeTime-a; - if (shake>0) - { - float pow = -Mth::sin(shake*3)*shake; + float shake = arrow->shakeTime - a; + if (shake > 0) { + float pow = -Mth::sin(shake * 3) * shake; glRotatef(pow, 0, 0, 1); } glRotatef(45, 1, 0, 0); @@ -50,35 +54,46 @@ void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, d glTranslatef(-4, 0, 0); -// glNormal3f(ss, 0, 0); // 4J - changed to use tesselator + // glNormal3f(ss, 0, 0); // 4J - changed to use tesselator t->begin(); - t->normal(1,0,0); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v12)); + t->normal(1, 0, 0); + t->vertexUV((float)(-7), (float)(-2), (float)(-2), (float)(u02), + (float)(v02)); + t->vertexUV((float)(-7), (float)(-2), (float)(+2), (float)(u12), + (float)(v02)); + t->vertexUV((float)(-7), (float)(+2), (float)(+2), (float)(u12), + (float)(v12)); + t->vertexUV((float)(-7), (float)(+2), (float)(-2), (float)(u02), + (float)(v12)); t->end(); -// glNormal3f(-ss, 0, 0); // 4J - changed to use tesselator + // glNormal3f(-ss, 0, 0); // 4J - changed to use tesselator t->begin(); - t->normal(-1,0,0); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v12)); + t->normal(-1, 0, 0); + t->vertexUV((float)(-7), (float)(+2), (float)(-2), (float)(u02), + (float)(v02)); + t->vertexUV((float)(-7), (float)(+2), (float)(+2), (float)(u12), + (float)(v02)); + t->vertexUV((float)(-7), (float)(-2), (float)(+2), (float)(u12), + (float)(v12)); + t->vertexUV((float)(-7), (float)(-2), (float)(-2), (float)(u02), + (float)(v12)); t->end(); - for (int i = 0; i < 4; i++) - { - + for (int i = 0; i < 4; i++) { glRotatef(90, 1, 0, 0); -// glNormal3f(0, 0, ss); // 4J - changed to use tesselator + // glNormal3f(0, 0, ss); // 4J - changed to use + // tesselator t->begin(); - t->normal(0,0,1); - t->vertexUV((float)(-8), (float)( -2), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+8), (float)( -2), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+8), (float)( +2), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-8), (float)( +2), (float)( 0), (float)( u0), (float)( v1)); + t->normal(0, 0, 1); + t->vertexUV((float)(-8), (float)(-2), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+8), (float)(-2), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+8), (float)(+2), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-8), (float)(+2), (float)(0), (float)(u0), + (float)(v1)); t->end(); } glDisable(GL_RESCALE_NORMAL); diff --git a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h index 3348fc332..0491c6990 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class ArrowRenderer : public EntityRenderer -{ +class ArrowRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr _arrow, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _arrow, double x, double y, + double z, float rot, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp index 9e2f4bcee..8670234d2 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp @@ -3,22 +3,21 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "BlazeRenderer.h" -BlazeRenderer::BlazeRenderer() : MobRenderer(new BlazeModel(), 0.5f) -{ - this->modelVersion = ((BlazeModel *) model)->modelVersion(); +BlazeRenderer::BlazeRenderer() : MobRenderer(new BlazeModel(), 0.5f) { + this->modelVersion = ((BlazeModel*)model)->modelVersion(); } -void BlazeRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void BlazeRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - int modelVersion = ((BlazeModel *) model)->modelVersion(); - if (modelVersion != this->modelVersion) - { - this->modelVersion = modelVersion; - model = new BlazeModel(); - } - MobRenderer::render(mob, x, y, z, rot, a); + int modelVersion = ((BlazeModel*)model)->modelVersion(); + if (modelVersion != this->modelVersion) { + this->modelVersion = modelVersion; + model = new BlazeModel(); + } + MobRenderer::render(mob, x, y, z, rot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h index 0ee973cab..12284da6b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class BlazeRenderer : public MobRenderer -{ +class BlazeRenderer : public MobRenderer { private: - int modelVersion; + int modelVersion; public: - BlazeRenderer(); + BlazeRenderer(); - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp index 270ee1eff..3018a7c8e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp @@ -4,37 +4,37 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Util/Mth.h" -BoatRenderer::BoatRenderer() : EntityRenderer() -{ +BoatRenderer::BoatRenderer() : EntityRenderer() { this->shadowRadius = 0.5f; model = new BoatModel(); } -void BoatRenderer::render(std::shared_ptr _boat, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr boat = std::dynamic_pointer_cast(_boat); +void BoatRenderer::render(std::shared_ptr _boat, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr boat = std::dynamic_pointer_cast(_boat); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); - glRotatef(180-rot, 0, 1, 0); + glRotatef(180 - rot, 0, 1, 0); float hurt = boat->getHurtTime() - a; float dmg = boat->getDamage() - a; - if (dmg<0) dmg = 0; - if (hurt>0) - { - glRotatef(Mth::sin(hurt)*hurt*dmg/10*boat->getHurtDir(), 1, 0, 0); + if (dmg < 0) dmg = 0; + if (hurt > 0) { + glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * boat->getHurtDir(), 1, 0, + 0); } - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - float ss = 12/16.0f; + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + float ss = 12 / 16.0f; glScalef(ss, ss, ss); - glScalef(1/ss, 1/ss, 1/ss); + glScalef(1 / ss, 1 / ss, 1 / ss); - bindTexture(TN_ITEM_BOAT); // 4J was L"/item/boat.png" + bindTexture(TN_ITEM_BOAT); // 4J was L"/item/boat.png" glScalef(-1, -1, 1); model->render(boat, 0, 0, -0.1f, 0, 0, 1 / 16.0f, true); glPopMatrix(); diff --git a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h index c4bb03128..06e490794 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h @@ -1,13 +1,13 @@ #pragma once #include "EntityRenderer.h" -class BoatRenderer : public EntityRenderer -{ +class BoatRenderer : public EntityRenderer { protected: - Model *model; + Model* model; public: - BoatRenderer(); + BoatRenderer(); - virtual void render(std::shared_ptr boat, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr boat, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp index 20c9e3031..f2050f311 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp @@ -6,100 +6,94 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -ChestRenderer::ChestRenderer() -{ - chestModel = new ChestModel(); - largeChestModel = new LargeChestModel(); +ChestRenderer::ChestRenderer() { + chestModel = new ChestModel(); + largeChestModel = new LargeChestModel(); } -ChestRenderer::~ChestRenderer() -{ - delete chestModel; - delete largeChestModel; +ChestRenderer::~ChestRenderer() { + delete chestModel; + delete largeChestModel; } -void ChestRenderer::render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr chest = std::dynamic_pointer_cast(_chest); +void ChestRenderer::render(std::shared_ptr _chest, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr chest = + std::dynamic_pointer_cast(_chest); - int data; + int data; - if (!chest->hasLevel()) - { - data = 0; - } - else - { - Tile *tile = chest->getTile(); - data = chest->getData(); + if (!chest->hasLevel()) { + data = 0; + } else { + Tile* tile = chest->getTile(); + data = chest->getData(); - if (tile != NULL && data == 0) - { - ((ChestTile *) tile)->recalcLockDir(chest->getLevel(), chest->x, chest->y, chest->z); - data = chest->getData(); - } + if (tile != NULL && data == 0) { + ((ChestTile*)tile) + ->recalcLockDir(chest->getLevel(), chest->x, chest->y, + chest->z); + data = chest->getData(); + } - chest->checkNeighbors(); - } - if (chest->n.lock() != NULL || chest->w.lock() != NULL) return; + chest->checkNeighbors(); + } + if (chest->n.lock() != NULL || chest->w.lock() != NULL) return; + ChestModel* model; + if (chest->e.lock() != NULL || chest->s.lock() != NULL) { + model = largeChestModel; + bindTexture(TN_TILE_LARGE_CHEST); // 4J Was "/item/largechest.png" + } else { + model = chestModel; + bindTexture(TN_TILE_CHEST); // 4J Was "/item/chest.png" + } - ChestModel *model; - if (chest->e.lock() != NULL || chest->s.lock() != NULL) - { - model = largeChestModel; - bindTexture(TN_TILE_LARGE_CHEST); // 4J Was "/item/largechest.png" - } - else - { - model = chestModel; - bindTexture(TN_TILE_CHEST); // 4J Was "/item/chest.png" - } + glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + // if( setColor ) glColor4f(1, 1, 1, 1); + if (setColor) glColor4f(1, 1, 1, alpha); + glTranslatef((float)x, (float)y + 1, (float)z + 1); + glScalef(1, -1, -1); - glPushMatrix(); - glEnable(GL_RESCALE_NORMAL); - //if( setColor ) glColor4f(1, 1, 1, 1); - if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); - glScalef(1, -1, -1); + glTranslatef(0.5f, 0.5f, 0.5f); + int rot = 0; + if (data == 2) rot = 180; + if (data == 3) rot = 0; + if (data == 4) rot = 90; + if (data == 5) rot = -90; - glTranslatef(0.5f, 0.5f, 0.5f); - int rot = 0; - if (data == 2) rot = 180; - if (data == 3) rot = 0; - if (data == 4) rot = 90; - if (data == 5) rot = -90; + if (data == 2 && chest->e.lock() != NULL) { + glTranslatef(1, 0, 0); + } + if (data == 5 && chest->s.lock() != NULL) { + glTranslatef(0, 0, -1); + } + glRotatef(rot, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); - if (data == 2 && chest->e.lock() != NULL) - { - glTranslatef(1, 0, 0); - } - if (data == 5 && chest->s.lock() != NULL) - { - glTranslatef(0, 0, -1); - } - glRotatef(rot, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); + float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; + if (chest->n.lock() != NULL) { + float open2 = + chest->n.lock()->oOpenness + + (chest->n.lock()->openness - chest->n.lock()->oOpenness) * a; + if (open2 > open) open = open2; + } + if (chest->w.lock() != NULL) { + float open2 = + chest->w.lock()->oOpenness + + (chest->w.lock()->openness - chest->w.lock()->oOpenness) * a; + if (open2 > open) open = open2; + } - float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; - if (chest->n.lock() != NULL) - { - float open2 = chest->n.lock()->oOpenness + (chest->n.lock()->openness - chest->n.lock()->oOpenness) * a; - if (open2 > open) open = open2; - } - if (chest->w.lock() != NULL) - { - float open2 = chest->w.lock()->oOpenness + (chest->w.lock()->openness - chest->w.lock()->oOpenness) * a; - if (open2 > open) open = open2; - } + open = 1 - open; + open = 1 - open * open * open; - open = 1 - open; - open = 1 - open * open * open; - - model->lid->xRot = -(open * PI / 2); - model->render(useCompiled); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( setColor ) glColor4f(1, 1, 1, 1); + model->lid->xRot = -(open * PI / 2); + model->render(useCompiled); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (setColor) glColor4f(1, 1, 1, 1); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h index ffd4da033..9fe5ba593 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h @@ -4,15 +4,16 @@ class ChestModel; -class ChestRenderer : public TileEntityRenderer -{ +class ChestRenderer : public TileEntityRenderer { private: - ChestModel *chestModel; - ChestModel *largeChestModel; + ChestModel* chestModel; + ChestModel* largeChestModel; public: - ChestRenderer(); - ~ChestRenderer(); + ChestRenderer(); + ~ChestRenderer(); - void render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + void render(std::shared_ptr _chest, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp index a718c8bff..dbc846b12 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp @@ -3,22 +3,21 @@ #include "ChickenRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -ChickenRenderer::ChickenRenderer(Model *model, float shadow) : MobRenderer(model,shadow) -{ +ChickenRenderer::ChickenRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void ChickenRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void ChickenRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} +float ChickenRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); -float ChickenRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float flap = mob->oFlap + (mob->flap - mob->oFlap) * a; + float flapSpeed = mob->oFlapSpeed + (mob->flapSpeed - mob->oFlapSpeed) * a; - float flap = mob->oFlap+(mob->flap-mob->oFlap)*a; - float flapSpeed = mob->oFlapSpeed+(mob->flapSpeed-mob->oFlapSpeed)*a; - - return (Mth::sin(flap)+1)*flapSpeed; + return (Mth::sin(flap) + 1) * flapSpeed; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h index 2c33176d5..642c0ed00 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h @@ -1,11 +1,12 @@ #pragma once #include "MobRenderer.h" -class ChickenRenderer : public MobRenderer -{ +class ChickenRenderer : public MobRenderer { public: - ChickenRenderer(Model *model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + ChickenRenderer(Model* model, float shadow); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + protected: - virtual float getBob(std::shared_ptr _mob, float a); + virtual float getBob(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp index 34385c584..34206f879 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp @@ -1,11 +1,10 @@ #include "../../Platform/stdafx.h" #include "CowRenderer.h" -CowRenderer::CowRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ -} +CowRenderer::CowRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} -void CowRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); +void CowRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h index 0dabaf290..14b5b9230 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h @@ -1,9 +1,9 @@ #pragma once #include "MobRenderer.h" -class CowRenderer : public MobRenderer -{ +class CowRenderer : public MobRenderer { public: - CowRenderer(Model *model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + CowRenderer(Model* model, float shadow); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp index d9079bf8d..c3ada0872 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp @@ -4,13 +4,11 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Util/Mth.h" -CreeperRenderer::CreeperRenderer() : MobRenderer( new CreeperModel(), 0.5f ) -{ - armorModel = new CreeperModel(2); +CreeperRenderer::CreeperRenderer() : MobRenderer(new CreeperModel(), 0.5f) { + armorModel = new CreeperModel(2); } -void CreeperRenderer::scale(std::shared_ptr mob, float a) -{ +void CreeperRenderer::scale(std::shared_ptr mob, float a) { std::shared_ptr creeper = std::dynamic_pointer_cast(mob); float g = creeper->getSwelling(a); @@ -25,15 +23,17 @@ void CreeperRenderer::scale(std::shared_ptr mob, float a) glScalef(s, hs, s); } -int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) -{ - std::shared_ptr creeper = std::dynamic_pointer_cast(mob); +int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, + float a) { + std::shared_ptr creeper = std::dynamic_pointer_cast(mob); float step = creeper->getSwelling(a); - if ((int) (step * 10) % 2 == 0) return 0; + if ((int)(step * 10) % 2 == 0) return 0; - int _a = (int) (step * 0.2f * 255) + 25; // 4J - added 25 here as our entities are rendered with alpha test still enabled, and so anything less is invisible + int _a = (int)(step * 0.2f * 255) + + 25; // 4J - added 25 here as our entities are rendered with alpha + // test still enabled, and so anything less is invisible if (_a < 0) _a = 0; if (_a > 255) _a = 255; @@ -44,19 +44,20 @@ int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, float a return (_a << 24) | (r << 16) | (g << 8) | b; } -int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isPowered()) - { - if (mob->isInvisible()) glDepthMask(false); - else glDepthMask(true); +int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + if (mob->isPowered()) { + if (mob->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (layer == 1) - { + if (layer == 1) { float time = mob->tickCount + a; - bindTexture(TN_POWERED_CREEPER);// was L"/armor/power.png"); + bindTexture(TN_POWERED_CREEPER); // was L"/armor/power.png"); glMatrixMode(GL_TEXTURE); glLoadIdentity(); float uo = time * 0.01f; @@ -71,8 +72,7 @@ int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) glBlendFunc(GL_ONE, GL_ONE); return 1; } - if (layer == 2) - { + if (layer == 2) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); @@ -81,10 +81,9 @@ int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) } } return -1; - } -int CreeperRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, float a) -{ - return -1; +int CreeperRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, + float a) { + return -1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h index 3afd511bc..75b34d344 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h @@ -1,16 +1,17 @@ #pragma once #include "MobRenderer.h" -class CreeperRenderer: public MobRenderer -{ +class CreeperRenderer : public MobRenderer { private: - Model *armorModel; + Model* armorModel; public: - CreeperRenderer(); + CreeperRenderer(); + protected: - virtual void scale(std::shared_ptr _mob, float a); + virtual void scale(std::shared_ptr _mob, float a); virtual int getOverlayColor(std::shared_ptr mob, float br, float a); virtual int prepareArmor(std::shared_ptr mob, int layer, float a); - virtual int prepareArmorOverlay(std::shared_ptr _mob, int layer, float a); + virtual int prepareArmorOverlay(std::shared_ptr _mob, int layer, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp index a79b23e6e..ad631c6df 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp @@ -2,10 +2,11 @@ #include "DefaultRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.h" -void DefaultRenderer::render(std::shared_ptr entity, double x, double y, double z, float rot, float a) -{ +void DefaultRenderer::render(std::shared_ptr entity, double x, double y, + double z, float rot, float a) { glPushMatrix(); -// 4J - removed following line as doesn't really make any sense -// render(entity->bb, (x-entity->xOld), (y-entity->yOld), (z-entity->zOld)); + // 4J - removed following line as doesn't really make any sense + // render(entity->bb, (x-entity->xOld), (y-entity->yOld), + // (z-entity->zOld)); glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h index 651a99c15..6811a800d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class DefaultRenderer : public EntityRenderer -{ +class DefaultRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr entity, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp index 99db92af5..b7a66b504 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp @@ -4,56 +4,53 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "EnchantTableRenderer.h" -EnchantTableRenderer::EnchantTableRenderer() -{ - bookModel = new BookModel(); -} +EnchantTableRenderer::EnchantTableRenderer() { bookModel = new BookModel(); } -EnchantTableRenderer::~EnchantTableRenderer() -{ - delete bookModel; -} +EnchantTableRenderer::~EnchantTableRenderer() { delete bookModel; } -void EnchantTableRenderer::render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr table = std::dynamic_pointer_cast(_table); +void EnchantTableRenderer::render(std::shared_ptr _table, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr table = + std::dynamic_pointer_cast(_table); #ifdef __PSVITA__ - // AP - the book pages are made with 0 depth so the front and back polys are at the same location. This can cause z-fighting if culling is disabled which can sometimes happen - // depending on what object was last seen so make sure culling is always enabled. Should this be a problem for other platforms? - glEnable(GL_CULL_FACE); + // AP - the book pages are made with 0 depth so the front and back polys are + // at the same location. This can cause z-fighting if culling is disabled + // which can sometimes happen depending on what object was last seen so make + // sure culling is always enabled. Should this be a problem for other + // platforms? + glEnable(GL_CULL_FACE); #endif - glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y + 12 / 16.0f, (float) z + 0.5f); + glPushMatrix(); + glTranslatef((float)x + 0.5f, (float)y + 12 / 16.0f, (float)z + 0.5f); - float tt = table->time + a; + float tt = table->time + a; - glTranslatef(0, 0.1f + sin(tt * 0.1f) * 0.01f, 0); - float orot = (table->rot - table->oRot); - while (orot >= PI) - orot -= PI * 2; - while (orot < -PI) - orot += PI * 2; + glTranslatef(0, 0.1f + sin(tt * 0.1f) * 0.01f, 0); + float orot = (table->rot - table->oRot); + while (orot >= PI) orot -= PI * 2; + while (orot < -PI) orot += PI * 2; - float yRot = table->oRot + orot * a; + float yRot = table->oRot + orot * a; - glRotatef(-yRot * 180 / PI, 0, 1, 0); - glRotatef(80, 0, 0, 1); - bindTexture(TN_ITEM_BOOK); // 4J was "/item/book.png" + glRotatef(-yRot * 180 / PI, 0, 1, 0); + glRotatef(80, 0, 0, 1); + bindTexture(TN_ITEM_BOOK); // 4J was "/item/book.png" - float ff1 = table->oFlip + (table->flip - table->oFlip) * a + 0.25f; - float ff2 = table->oFlip + (table->flip - table->oFlip) * a + 0.75f; - ff1 = (ff1 - Mth::fastFloor(ff1)) * 1.6f - 0.3f; - ff2 = (ff2 - Mth::fastFloor(ff2)) * 1.6f - 0.3f; + float ff1 = table->oFlip + (table->flip - table->oFlip) * a + 0.25f; + float ff2 = table->oFlip + (table->flip - table->oFlip) * a + 0.75f; + ff1 = (ff1 - Mth::fastFloor(ff1)) * 1.6f - 0.3f; + ff2 = (ff2 - Mth::fastFloor(ff2)) * 1.6f - 0.3f; - if (ff1 < 0) ff1 = 0; - if (ff2 < 0) ff2 = 0; - if (ff1 > 1) ff1 = 1; - if (ff2 > 1) ff2 = 1; + if (ff1 < 0) ff1 = 0; + if (ff2 < 0) ff2 = 0; + if (ff1 > 1) ff1 = 1; + if (ff2 > 1) ff2 = 1; - float o = table->oOpen + (table->open - table->oOpen) * a; - bookModel->render(nullptr, tt, ff1, ff2, o, 0, 1 / 16.0f,true); - glPopMatrix(); + float o = table->oOpen + (table->open - table->oOpen) * a; + bookModel->render(nullptr, tt, ff1, ff2, o, 0, 1 / 16.0f, true); + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h index 774857191..fa7de9dcf 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h @@ -4,16 +4,18 @@ class BookModel; -class EnchantTableRenderer : public TileEntityRenderer -{ - friend class CXuiCtrlEnchantmentBook; - friend class UIControl_EnchantmentBook; +class EnchantTableRenderer : public TileEntityRenderer { + friend class CXuiCtrlEnchantmentBook; + friend class UIControl_EnchantmentBook; + private: - BookModel *bookModel; + BookModel* bookModel; public: - EnchantTableRenderer(); - ~EnchantTableRenderer(); + EnchantTableRenderer(); + ~EnchantTableRenderer(); - virtual void render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); + virtual void render(std::shared_ptr _table, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp index 5ba499998..876c48d2e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp @@ -3,50 +3,51 @@ #include "../Models/ModelPart.h" #include "EnderChestRenderer.h" -void EnderChestRenderer::render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr chest = std::dynamic_pointer_cast(_chest); +void EnderChestRenderer::render(std::shared_ptr _chest, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr chest = + std::dynamic_pointer_cast(_chest); - int data = 0; + int data = 0; - if (chest->hasLevel()) - { - data = chest->getData(); - } + if (chest->hasLevel()) { + data = chest->getData(); + } - bindTexture(TN_TILE_ENDER_CHEST); //"/item/enderchest.png"); + bindTexture(TN_TILE_ENDER_CHEST); //"/item/enderchest.png"); - glPushMatrix(); - glEnable(GL_RESCALE_NORMAL); - //glColor4f(1, 1, 1, 1); - if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); - glScalef(1, -1, -1); + glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + // glColor4f(1, 1, 1, 1); + if (setColor) glColor4f(1, 1, 1, alpha); + glTranslatef((float)x, (float)y + 1, (float)z + 1); + glScalef(1, -1, -1); - glTranslatef(0.5f, 0.5f, 0.5f); - int rot = 0; - if (data == 2) rot = 180; - if (data == 3) rot = 0; - if (data == 4) rot = 90; - if (data == 5) rot = -90; + glTranslatef(0.5f, 0.5f, 0.5f); + int rot = 0; + if (data == 2) rot = 180; + if (data == 3) rot = 0; + if (data == 4) rot = 90; + if (data == 5) rot = -90; - // if (data == 2) { - // glTranslatef(1, 0, 0); - // } - // if (data == 5) { - // glTranslatef(0, 0, -1); - // } - glRotatef(rot, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); + // if (data == 2) { + // glTranslatef(1, 0, 0); + // } + // if (data == 5) { + // glTranslatef(0, 0, -1); + // } + glRotatef(rot, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); - float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; - open = 1 - open; - open = 1 - open * open * open; + float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; + open = 1 - open; + open = 1 - open * open * open; - chestModel.lid->xRot = -(open * PI / 2); - chestModel.render(useCompiled); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( setColor ) glColor4f(1, 1, 1, 1); + chestModel.lid->xRot = -(open * PI / 2); + chestModel.render(useCompiled); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (setColor) glColor4f(1, 1, 1, 1); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h index ab7b65547..b6df8e638 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h @@ -3,11 +3,12 @@ #include "TileEntityRenderer.h" #include "../Models/ChestModel.h" -class EnderChestRenderer : public TileEntityRenderer -{ +class EnderChestRenderer : public TileEntityRenderer { private: - ChestModel chestModel; + ChestModel chestModel; public: - void render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + void render(std::shared_ptr _chest, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp index 3b5e232a0..fb9dad13c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp @@ -3,31 +3,32 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.boss.enderdragon.h" #include "EnderCrystalRenderer.h" -EnderCrystalRenderer::EnderCrystalRenderer() -{ - currentModel = -1; - this->shadowRadius = 0.5f; +EnderCrystalRenderer::EnderCrystalRenderer() { + currentModel = -1; + this->shadowRadius = 0.5f; } -void EnderCrystalRenderer::render(std::shared_ptr _crystal, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type EnderCrystal rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr crystal = std::dynamic_pointer_cast(_crystal); - if (currentModel != EnderCrystalModel::MODEL_ID) - { - model = new EnderCrystalModel(0); - currentModel = EnderCrystalModel::MODEL_ID; - } +void EnderCrystalRenderer::render(std::shared_ptr _crystal, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type EnderCrystal rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr crystal = + std::dynamic_pointer_cast(_crystal); + if (currentModel != EnderCrystalModel::MODEL_ID) { + model = new EnderCrystalModel(0); + currentModel = EnderCrystalModel::MODEL_ID; + } + float tt = crystal->time + a; + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); + bindTexture( + TN_MOB_ENDERDRAGON_ENDERCRYSTAL); // 4J was + // "/mob/enderdragon/crystal.png" + float hh = sin(tt * 0.2f) / 2 + 0.5f; + hh = hh * hh + hh; + model->render(crystal, 0, tt * 3, hh * 0.2f, 0, 0, 1 / 16.0f, true); - float tt = crystal->time + a; - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); - bindTexture(TN_MOB_ENDERDRAGON_ENDERCRYSTAL); // 4J was "/mob/enderdragon/crystal.png" - float hh = sin(tt * 0.2f) / 2 + 0.5f; - hh = hh * hh + hh; - model->render(crystal, 0, tt * 3, hh * 0.2f, 0, 0, 1 / 16.0f, true); - - glPopMatrix(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h index 5ac644d15..caa764121 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h @@ -4,14 +4,14 @@ class Model; -class EnderCrystalRenderer : public EntityRenderer -{ +class EnderCrystalRenderer : public EntityRenderer { private: - int currentModel; - Model *model; + int currentModel; + Model* model; public: - EnderCrystalRenderer(); + EnderCrystalRenderer(); - virtual void render(std::shared_ptr _crystal, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _crystal, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp index 9b2cbee0a..09a6e1d0e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp @@ -8,260 +8,278 @@ std::shared_ptr EnderDragonRenderer::bossInstance; int EnderDragonRenderer::currentModel; -EnderDragonRenderer::EnderDragonRenderer() : MobRenderer(new DragonModel(0), 0.5f) -{ - currentModel = 0; - dragonModel = (DragonModel *) model; - this->setArmor(model); +EnderDragonRenderer::EnderDragonRenderer() + : MobRenderer(new DragonModel(0), 0.5f) { + currentModel = 0; + dragonModel = (DragonModel*)model; + this->setArmor(model); } -void EnderDragonRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EnderDragonRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - // 4J - reorganised a bit so we can free allocations - double lpComponents[3]; - doubleArray lp = doubleArray(lpComponents, 3); - mob->getLatencyPos(lp, 7, a); - float yr = lp[0]; - //mob->getLatencyPos(lp, 5, a); - //float rot2 = lp[1]; - //mob->getLatencyPos(lp, 10,a); - //rot2 -= lp[1]; - float rot2 = mob->getTilt(a); + // 4J - reorganised a bit so we can free allocations + double lpComponents[3]; + doubleArray lp = doubleArray(lpComponents, 3); + mob->getLatencyPos(lp, 7, a); + float yr = lp[0]; + // mob->getLatencyPos(lp, 5, a); + // float rot2 = lp[1]; + // mob->getLatencyPos(lp, 10,a); + // rot2 -= lp[1]; + float rot2 = mob->getTilt(a); - glRotatef(-yr, 0, 1, 0); - - glRotatef(rot2, 1, 0, 0); - //glRotatef(rot2 * 10, 1, 0, 0); + glRotatef(-yr, 0, 1, 0); - glTranslatef(0, 0, 1); - if (mob->deathTime > 0) - { - float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; - fall = sqrt(fall); - if (fall > 1) fall = 1; - glRotatef(fall * getFlipDegrees(mob), 0, 0, 1); - } + glRotatef(rot2, 1, 0, 0); + // glRotatef(rot2 * 10, 1, 0, 0); + + glTranslatef(0, 0, 1); + if (mob->deathTime > 0) { + float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; + fall = sqrt(fall); + if (fall > 1) fall = 1; + glRotatef(fall * getFlipDegrees(mob), 0, 0, 1); + } } -void EnderDragonRenderer::renderModel(std::shared_ptr _mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EnderDragonRenderer::renderModel(std::shared_ptr _mob, float wp, + float ws, float bob, + float headRotMinusBodyRot, float headRotx, + float scale) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - if (mob->dragonDeathTime > 0) - { - float tt = (mob->dragonDeathTime / 200.0f); - glDepthFunc(GL_LEQUAL); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, tt); - bindTexture(mob->customTextureUrl, TN_MOB_ENDERDRAGON_SHUFFLE); // 4J was "/mob/enderdragon/shuffle.png" - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - glAlphaFunc(GL_GREATER, 0.1f); + if (mob->dragonDeathTime > 0) { + float tt = (mob->dragonDeathTime / 200.0f); + glDepthFunc(GL_LEQUAL); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, tt); + bindTexture( + mob->customTextureUrl, + TN_MOB_ENDERDRAGON_SHUFFLE); // 4J was + // "/mob/enderdragon/shuffle.png" + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); + glAlphaFunc(GL_GREATER, 0.1f); - glDepthFunc(GL_EQUAL); - } + glDepthFunc(GL_EQUAL); + } + bindTexture(mob->customTextureUrl, mob->getTexture()); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - bindTexture(mob->customTextureUrl, mob->getTexture()); - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - - if (mob->hurtTime > 0) - { - glDepthFunc(GL_EQUAL); - glDisable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(1, 0, 0, 0.5f); + if (mob->hurtTime > 0) { + glDepthFunc(GL_EQUAL); + glDisable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(1, 0, 0, 0.5f); #ifdef __PSVITA__ - // AP - not sure that the usecompiled flag is supposed to be false. This makes it really slow on vita. Making it true still seems to look the same - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); + // AP - not sure that the usecompiled flag is supposed to be false. This + // makes it really slow on vita. Making it true still seems to look the + // same + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); #else - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, false); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + false); #endif - glEnable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - glDepthFunc(GL_LEQUAL); - } + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + } } -void EnderDragonRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - EnderDragonRenderer::bossInstance = mob; - if (currentModel != DragonModel::MODEL_ID) - { - model = new DragonModel(0); - currentModel = DragonModel::MODEL_ID; - } - MobRenderer::render(mob, x, y, z, rot, a); - if (mob->nearestCrystal != NULL) - { - float tt = mob->nearestCrystal->time + a; - float hh = sin(tt * 0.2f) / 2 + 0.5f; - hh = (hh * hh + hh) * 0.2f; +void EnderDragonRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + EnderDragonRenderer::bossInstance = mob; + if (currentModel != DragonModel::MODEL_ID) { + model = new DragonModel(0); + currentModel = DragonModel::MODEL_ID; + } + MobRenderer::render(mob, x, y, z, rot, a); + if (mob->nearestCrystal != NULL) { + float tt = mob->nearestCrystal->time + a; + float hh = sin(tt * 0.2f) / 2 + 0.5f; + hh = (hh * hh + hh) * 0.2f; - float xd = (float) (mob->nearestCrystal->x - mob->x - (mob->xo - mob->x) * (1 - a)); - float yd = (float) (hh + mob->nearestCrystal->y - 1 - mob->y - (mob->yo - mob->y) * (1 - a)); - float zd = (float) (mob->nearestCrystal->z - mob->z - (mob->zo - mob->z) * (1 - a)); + float xd = (float)(mob->nearestCrystal->x - mob->x - + (mob->xo - mob->x) * (1 - a)); + float yd = (float)(hh + mob->nearestCrystal->y - 1 - mob->y - + (mob->yo - mob->y) * (1 - a)); + float zd = (float)(mob->nearestCrystal->z - mob->z - + (mob->zo - mob->z) * (1 - a)); - float sdd = sqrt(xd * xd + zd * zd); - float dd = sqrt(xd * xd + yd * yd + zd * zd); + float sdd = sqrt(xd * xd + zd * zd); + float dd = sqrt(xd * xd + yd * yd + zd * zd); - // this fixes a problem when the dragon is hit and the beam goes black because the diffuse colour isn't being reset in MobRenderer::render - glColor4f(1, 1, 1, 1); + // this fixes a problem when the dragon is hit and the beam goes black + // because the diffuse colour isn't being reset in MobRenderer::render + glColor4f(1, 1, 1, 1); - glPushMatrix(); - glTranslatef((float) x, (float) y + 2, (float) z); - glRotatef((float) (-atan2(zd, xd)) * 180.0f / PI - 90.0f, 0, 1, 0); - glRotatef((float) (-atan2(sdd, yd)) * 180.0f / PI - 90.0f, 1, 0, 0); + glPushMatrix(); + glTranslatef((float)x, (float)y + 2, (float)z); + glRotatef((float)(-atan2(zd, xd)) * 180.0f / PI - 90.0f, 0, 1, 0); + glRotatef((float)(-atan2(sdd, yd)) * 180.0f / PI - 90.0f, 1, 0, 0); - // 4J-PB - Rotating the healing beam too - static float fRot=0.0f; - glRotatef(fRot, 0, 0, 1); - fRot+=0.5f; // 4J - rate of rotation changed from 5.0 to 0.5 for photosensitivity reasons - if(fRot>=360.0f) - { - fRot=0.0f; - } + // 4J-PB - Rotating the healing beam too + static float fRot = 0.0f; + glRotatef(fRot, 0, 0, 1); + fRot += 0.5f; // 4J - rate of rotation changed from 5.0 to 0.5 for + // photosensitivity reasons + if (fRot >= 360.0f) { + fRot = 0.0f; + } - Tesselator *t = Tesselator::getInstance(); - Lighting::turnOff(); - glDisable(GL_CULL_FACE); + Tesselator* t = Tesselator::getInstance(); + Lighting::turnOff(); + glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); - bindTexture(TN_MOB_ENDERDRAGON_BEAM); // 4J was "/mob/enderdragon/beam.png" + bindTexture( + TN_MOB_ENDERDRAGON_BEAM); // 4J was "/mob/enderdragon/beam.png" - glShadeModel(GL_SMOOTH); + glShadeModel(GL_SMOOTH); - float v0 = 0 - (mob->tickCount + a) * 0.005f; // 4J - rate of movement changed from 0.01 to 0.005 for photosensitivity reasons - float v1 = sqrt(xd * xd + yd * yd + zd * zd) / 32.0f - (mob->tickCount + a) * 0.005f; + float v0 = 0 - (mob->tickCount + a) * + 0.005f; // 4J - rate of movement changed from 0.01 + // to 0.005 for photosensitivity reasons + float v1 = sqrt(xd * xd + yd * yd + zd * zd) / 32.0f - + (mob->tickCount + a) * 0.005f; - t->begin(GL_TRIANGLE_STRIP); + t->begin(GL_TRIANGLE_STRIP); - int steps = 8; - for (int i = 0; i <= steps; i++) - { - double d=i % steps * PI * 2 / steps; - float s = sin(i % steps * PI * 2 / steps) * 0.75f; - float c = cos(i % steps * PI * 2 / steps) * 0.75f; - float u = i % steps * 1.0f / steps; - //t->color(0x000000); - t->vertexUV(s * 0.2f, c * 0.2f, 0, u, v1); - //t->color(0xffffff); - t->vertexUV(s, c, dd, u, v0); - } + int steps = 8; + for (int i = 0; i <= steps; i++) { + double d = i % steps * PI * 2 / steps; + float s = sin(i % steps * PI * 2 / steps) * 0.75f; + float c = cos(i % steps * PI * 2 / steps) * 0.75f; + float u = i % steps * 1.0f / steps; + // t->color(0x000000); + t->vertexUV(s * 0.2f, c * 0.2f, 0, u, v1); + // t->color(0xffffff); + t->vertexUV(s, c, dd, u, v0); + } - t->end(); - glEnable(GL_CULL_FACE); - glShadeModel(GL_FLAT); - glDisable(GL_BLEND); + t->end(); + glEnable(GL_CULL_FACE); + glShadeModel(GL_FLAT); + glDisable(GL_BLEND); - glPopMatrix(); - Lighting::turnOn(); - } + glPopMatrix(); + Lighting::turnOn(); + } } -void EnderDragonRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - Tesselator *t = Tesselator::getInstance(); +void EnderDragonRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + Tesselator* t = Tesselator::getInstance(); - if (mob->dragonDeathTime > 0) - { - Lighting::turnOff(); - float tt = ((mob->dragonDeathTime + a) / 200.0f); - float overDrive = 0; - if (tt > 0.8f) - { - overDrive = (tt - 0.8f) / 0.2f; - } - - Random random(432); - glDisable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDisable(GL_ALPHA_TEST); - glEnable(GL_CULL_FACE); - glDepthMask(false); - glPushMatrix(); - glTranslatef(0, -1, -2); - for (int i = 0; i < (tt + tt * tt) / 2 * 60; i++) - { - glRotatef(random.nextFloat() * 360, 1, 0, 0); - glRotatef(random.nextFloat() * 360, 0, 1, 0); - glRotatef(random.nextFloat() * 360, 0, 0, 1); - glRotatef(random.nextFloat() * 360, 1, 0, 0); - glRotatef(random.nextFloat() * 360, 0, 1, 0); - glRotatef(random.nextFloat() * 360 + tt * 90, 0, 0, 1); - t->begin(GL_TRIANGLE_FAN); - float dist = random.nextFloat() * 20 + 5 + overDrive * 10; - float w = random.nextFloat() * 2 + 1 + overDrive * 2; - t->color(0xffffff, (int) (255 * (1 - overDrive))); - t->vertex(0, 0, 0); - t->color(0xff00ff, 0); - t->vertex(-0.866 * w, dist, -0.5f * w); - t->vertex(+0.866 * w, dist, -0.5f * w); - t->vertex(0, dist, 1 * w); - t->vertex(-0.866 * w, dist, -0.5f * w); - t->end(); - } - glPopMatrix(); - glDepthMask(true); - glDisable(GL_CULL_FACE); - glDisable(GL_BLEND); - glShadeModel(GL_FLAT); - glColor4f(1, 1, 1, 1); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); - Lighting::turnOn(); - } + if (mob->dragonDeathTime > 0) { + Lighting::turnOff(); + float tt = ((mob->dragonDeathTime + a) / 200.0f); + float overDrive = 0; + if (tt > 0.8f) { + overDrive = (tt - 0.8f) / 0.2f; + } + Random random(432); + glDisable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDisable(GL_ALPHA_TEST); + glEnable(GL_CULL_FACE); + glDepthMask(false); + glPushMatrix(); + glTranslatef(0, -1, -2); + for (int i = 0; i < (tt + tt * tt) / 2 * 60; i++) { + glRotatef(random.nextFloat() * 360, 1, 0, 0); + glRotatef(random.nextFloat() * 360, 0, 1, 0); + glRotatef(random.nextFloat() * 360, 0, 0, 1); + glRotatef(random.nextFloat() * 360, 1, 0, 0); + glRotatef(random.nextFloat() * 360, 0, 1, 0); + glRotatef(random.nextFloat() * 360 + tt * 90, 0, 0, 1); + t->begin(GL_TRIANGLE_FAN); + float dist = random.nextFloat() * 20 + 5 + overDrive * 10; + float w = random.nextFloat() * 2 + 1 + overDrive * 2; + t->color(0xffffff, (int)(255 * (1 - overDrive))); + t->vertex(0, 0, 0); + t->color(0xff00ff, 0); + t->vertex(-0.866 * w, dist, -0.5f * w); + t->vertex(+0.866 * w, dist, -0.5f * w); + t->vertex(0, dist, 1 * w); + t->vertex(-0.866 * w, dist, -0.5f * w); + t->end(); + } + glPopMatrix(); + glDepthMask(true); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glShadeModel(GL_FLAT); + glColor4f(1, 1, 1, 1); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); + Lighting::turnOn(); + } } -int EnderDragonRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +int EnderDragonRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - if (layer == 1) - { - glDepthFunc(GL_LEQUAL); - } - if (layer != 0) return -1; + if (layer == 1) { + glDepthFunc(GL_LEQUAL); + } + if (layer != 0) return -1; - bindTexture(TN_MOB_ENDERDRAGON_ENDEREYES); // 4J was "/mob/enderdragon/ender_eyes.png" - float br = 1; - glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + bindTexture( + TN_MOB_ENDERDRAGON_ENDEREYES); // 4J was + // "/mob/enderdragon/ender_eyes.png" + float br = 1; + glEnable(GL_BLEND); + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - glBlendFunc(GL_ONE, GL_ONE); - glDisable(GL_LIGHTING); - glDepthFunc(GL_EQUAL); + glBlendFunc(GL_ONE, GL_ONE); + glDisable(GL_LIGHTING); + glDepthFunc(GL_EQUAL); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = 0xf0f0; - int u = col % 65536; - int v = col / 65536; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = 0xf0f0; + int u = col % 65536; + int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glEnable(GL_LIGHTING); - glColor4f(1, 1, 1, br); - return 1; + glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, br); + return 1; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h index 095e2cf28..25659a509 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h @@ -7,30 +7,33 @@ class EnderDragon; #endif class DragonModel; -class EnderDragonRenderer : public MobRenderer -{ +class EnderDragonRenderer : public MobRenderer { public: - static std::shared_ptr bossInstance; + static std::shared_ptr bossInstance; private: - static int currentModel; + static int currentModel; protected: - DragonModel *dragonModel; + DragonModel* dragonModel; public: - EnderDragonRenderer(); + EnderDragonRenderer(); protected: - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); protected: - void renderModel(std::shared_ptr _mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale); + void renderModel(std::shared_ptr _mob, float wp, float ws, + float bob, float headRotMinusBodyRot, float headRotx, + float scale); public: - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); - virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp index cfb91c452..14f7420e2 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp @@ -4,104 +4,104 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -EndermanRenderer::EndermanRenderer() : MobRenderer(new EndermanModel(), 0.5f) -{ - model = (EndermanModel *) MobRenderer::model; - this->setArmor(model); +EndermanRenderer::EndermanRenderer() : MobRenderer(new EndermanModel(), 0.5f) { + model = (EndermanModel*)MobRenderer::model; + this->setArmor(model); } -void EndermanRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EndermanRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - model->carrying = mob->getCarryingTile() > 0; - model->creepy = mob->isCreepy(); + model->carrying = mob->getCarryingTile() > 0; + model->creepy = mob->isCreepy(); - if (mob->isCreepy()) - { - double d = 0.02; - x += random.nextGaussian() * d; - z += random.nextGaussian() * d; - } + if (mob->isCreepy()) { + double d = 0.02; + x += random.nextGaussian() * d; + z += random.nextGaussian() * d; + } - MobRenderer::render(mob, x, y, z, rot, a); + MobRenderer::render(mob, x, y, z, rot, a); } -void EndermanRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EndermanRenderer::additionalRendering(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(_mob, a); + MobRenderer::additionalRendering(_mob, a); - if (mob->getCarryingTile() > 0) - { - glEnable(GL_RESCALE_NORMAL); - glPushMatrix(); + if (mob->getCarryingTile() > 0) { + glEnable(GL_RESCALE_NORMAL); + glPushMatrix(); - float s = 8 / 16.0f; - glTranslatef(-0 / 16.0f, 11 / 16.0f, -12 / 16.0f); - s *= 1.00f; - glRotatef(20, 1, 0, 0); - glRotatef(45, 0, 1, 0); - glScalef(s, -s, s); + float s = 8 / 16.0f; + glTranslatef(-0 / 16.0f, 11 / 16.0f, -12 / 16.0f); + s *= 1.00f; + glRotatef(20, 1, 0, 0); + glRotatef(45, 0, 1, 0); + glScalef(s, -s, s); + if (SharedConstants::TEXTURE_LIGHTING) { + int col = mob->getLightColor(a); + int u = col % 65536; + int v = col / 65536; - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = mob->getLightColor(a); - int u = col % 65536; - int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } - - glColor4f(1, 1, 1, 1); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - tileRenderer->renderTile(Tile::tiles[mob->getCarryingTile()], mob->getCarryingData(), 1); - glPopMatrix(); - glDisable(GL_RESCALE_NORMAL); - } + glColor4f(1, 1, 1, 1); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + tileRenderer->renderTile(Tile::tiles[mob->getCarryingTile()], + mob->getCarryingData(), 1); + glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); + } } -int EndermanRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +int EndermanRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (layer != 0) return -1; + if (layer != 0) return -1; - bindTexture(TN_MOB_ENDERMAN_EYES); // 4J was L"/mob/enderman_eyes.png" - float br = 1; - glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + bindTexture(TN_MOB_ENDERMAN_EYES); // 4J was L"/mob/enderman_eyes.png" + float br = 1; + glEnable(GL_BLEND); + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - glBlendFunc(GL_ONE, GL_ONE); - glDisable(GL_LIGHTING); + glBlendFunc(GL_ONE, GL_ONE); + glDisable(GL_LIGHTING); - if (mob->isInvisible()) glDepthMask(false); - else glDepthMask(true); + if (mob->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = 0xf0f0; - int u = col % 65536; - int v = col / 65536; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = 0xf0f0; + int u = col % 65536; + int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glEnable(GL_LIGHTING); - glColor4f(1, 1, 1, br); - return 1; + glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, br); + return 1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h index eaf6393e7..1c1693cc1 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h @@ -5,18 +5,18 @@ class EnderMan; class EndermanModel; -class EndermanRenderer : public MobRenderer -{ +class EndermanRenderer : public MobRenderer { private: - EndermanModel *model; - Random random; + EndermanModel* model; + Random random; public: - EndermanRenderer(); + EndermanRenderer(); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); protected: - virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp index b6b681e28..4e59b19d3 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp @@ -76,117 +76,127 @@ double EntityRenderDispatcher::xOff = 0.0; double EntityRenderDispatcher::yOff = 0.0; double EntityRenderDispatcher::zOff = 0.0; -EntityRenderDispatcher *EntityRenderDispatcher::instance = NULL; +EntityRenderDispatcher* EntityRenderDispatcher::instance = NULL; -void EntityRenderDispatcher::staticCtor() -{ - instance = new EntityRenderDispatcher(); +void EntityRenderDispatcher::staticCtor() { + instance = new EntityRenderDispatcher(); } -EntityRenderDispatcher::EntityRenderDispatcher() -{ - glEnable(GL_LIGHTING); - renderers[eTYPE_SPIDER] = new SpiderRenderer(); - renderers[eTYPE_CAVESPIDER] = new SpiderRenderer(); - renderers[eTYPE_PIG] = new PigRenderer(new PigModel(), new PigModel(0.5f), 0.7f); - renderers[eTYPE_SHEEP] = new SheepRenderer(new SheepModel(), new SheepFurModel(), 0.7f); - renderers[eTYPE_COW] = new CowRenderer(new CowModel(), 0.7f); - renderers[eTYPE_MUSHROOMCOW] = new MushroomCowRenderer(new CowModel(), 0.7f); - renderers[eTYPE_WOLF] = new WolfRenderer(new WolfModel(), new WolfModel(), 0.5f); - renderers[eTYPE_CHICKEN] = new ChickenRenderer(new ChickenModel(), 0.3f); - renderers[eTYPE_OZELOT] = new OzelotRenderer(new OzelotModel(), 0.4f); - renderers[eTYPE_SILVERFISH] = new SilverfishRenderer(); - renderers[eTYPE_CREEPER] = new CreeperRenderer(); - renderers[eTYPE_ENDERMAN] = new EndermanRenderer(); - renderers[eTYPE_SNOWMAN] = new SnowManRenderer(); - renderers[eTYPE_SKELETON] = new HumanoidMobRenderer(new SkeletonModel(), 0.5f); - renderers[eTYPE_BLAZE] = new BlazeRenderer(); - renderers[eTYPE_ZOMBIE] = new ZombieRenderer(); - renderers[eTYPE_PIGZOMBIE] = new HumanoidMobRenderer(new ZombieModel(), 0.5f); - renderers[eTYPE_SLIME] = new SlimeRenderer(new SlimeModel(16), new SlimeModel(0), 0.25f); - renderers[eTYPE_LAVASLIME] = new LavaSlimeRenderer(); - renderers[eTYPE_PLAYER] = new PlayerRenderer(); - renderers[eTYPE_GIANT] = new GiantMobRenderer(new ZombieModel(), 0.5f, 6); - renderers[eTYPE_GHAST] = new GhastRenderer(); - renderers[eTYPE_SQUID] = new SquidRenderer(new SquidModel(), 0.7f); - renderers[eTYPE_VILLAGER] = new VillagerRenderer(); - renderers[eTYPE_VILLAGERGOLEM] = new VillagerGolemRenderer(); - renderers[eTYPE_MOB] = new MobRenderer(new HumanoidModel(), 0.5f); - renderers[eTYPE_ENDERDRAGON] = new EnderDragonRenderer(); - renderers[eTYPE_ENDER_CRYSTAL] = new EnderCrystalRenderer(); - renderers[eTYPE_ENTITY] = new DefaultRenderer(); - renderers[eTYPE_PAINTING] = new PaintingRenderer(); - renderers[eTYPE_ITEM_FRAME] = new ItemFrameRenderer(); - renderers[eTYPE_ARROW] = new ArrowRenderer(); - renderers[eTYPE_SNOWBALL] = new ItemSpriteRenderer(Item::snowBall); - renderers[eTYPE_THROWNENDERPEARL] = new ItemSpriteRenderer(Item::enderPearl); - renderers[eTYPE_EYEOFENDERSIGNAL] = new ItemSpriteRenderer(Item::eyeOfEnder); - renderers[eTYPE_THROWNEGG] = new ItemSpriteRenderer(Item::egg); - renderers[eTYPE_THROWNPOTION] = new ItemSpriteRenderer(Item::potion, PotionBrewing::THROWABLE_MASK); - renderers[eTYPE_THROWNEXPBOTTLE] = new ItemSpriteRenderer(Item::expBottle); - renderers[eTYPE_FIREBALL] = new FireballRenderer(2.0f); - renderers[eTYPE_SMALL_FIREBALL] = new FireballRenderer(0.5f); - renderers[eTYPE_DRAGON_FIREBALL] = new FireballRenderer(2.0f); // 4J Added TU9 - renderers[eTYPE_ITEMENTITY] = new ItemRenderer(); - renderers[eTYPE_EXPERIENCEORB] = new ExperienceOrbRenderer(); - renderers[eTYPE_PRIMEDTNT] = new TntRenderer(); - renderers[eTYPE_FALLINGTILE] = new FallingTileRenderer(); - renderers[eTYPE_MINECART] = new MinecartRenderer(); - renderers[eTYPE_BOAT] = new BoatRenderer(); - renderers[eTYPE_FISHINGHOOK] = new FishingHookRenderer(); - renderers[eTYPE_LIGHTNINGBOLT] = new LightningBoltRenderer(); - renderers[eTYPE_ARROW] = new ArrowRenderer(); - glDisable(GL_LIGHTING); +EntityRenderDispatcher::EntityRenderDispatcher() { + glEnable(GL_LIGHTING); + renderers[eTYPE_SPIDER] = new SpiderRenderer(); + renderers[eTYPE_CAVESPIDER] = new SpiderRenderer(); + renderers[eTYPE_PIG] = + new PigRenderer(new PigModel(), new PigModel(0.5f), 0.7f); + renderers[eTYPE_SHEEP] = + new SheepRenderer(new SheepModel(), new SheepFurModel(), 0.7f); + renderers[eTYPE_COW] = new CowRenderer(new CowModel(), 0.7f); + renderers[eTYPE_MUSHROOMCOW] = + new MushroomCowRenderer(new CowModel(), 0.7f); + renderers[eTYPE_WOLF] = + new WolfRenderer(new WolfModel(), new WolfModel(), 0.5f); + renderers[eTYPE_CHICKEN] = new ChickenRenderer(new ChickenModel(), 0.3f); + renderers[eTYPE_OZELOT] = new OzelotRenderer(new OzelotModel(), 0.4f); + renderers[eTYPE_SILVERFISH] = new SilverfishRenderer(); + renderers[eTYPE_CREEPER] = new CreeperRenderer(); + renderers[eTYPE_ENDERMAN] = new EndermanRenderer(); + renderers[eTYPE_SNOWMAN] = new SnowManRenderer(); + renderers[eTYPE_SKELETON] = + new HumanoidMobRenderer(new SkeletonModel(), 0.5f); + renderers[eTYPE_BLAZE] = new BlazeRenderer(); + renderers[eTYPE_ZOMBIE] = new ZombieRenderer(); + renderers[eTYPE_PIGZOMBIE] = + new HumanoidMobRenderer(new ZombieModel(), 0.5f); + renderers[eTYPE_SLIME] = + new SlimeRenderer(new SlimeModel(16), new SlimeModel(0), 0.25f); + renderers[eTYPE_LAVASLIME] = new LavaSlimeRenderer(); + renderers[eTYPE_PLAYER] = new PlayerRenderer(); + renderers[eTYPE_GIANT] = new GiantMobRenderer(new ZombieModel(), 0.5f, 6); + renderers[eTYPE_GHAST] = new GhastRenderer(); + renderers[eTYPE_SQUID] = new SquidRenderer(new SquidModel(), 0.7f); + renderers[eTYPE_VILLAGER] = new VillagerRenderer(); + renderers[eTYPE_VILLAGERGOLEM] = new VillagerGolemRenderer(); + renderers[eTYPE_MOB] = new MobRenderer(new HumanoidModel(), 0.5f); + renderers[eTYPE_ENDERDRAGON] = new EnderDragonRenderer(); + renderers[eTYPE_ENDER_CRYSTAL] = new EnderCrystalRenderer(); + renderers[eTYPE_ENTITY] = new DefaultRenderer(); + renderers[eTYPE_PAINTING] = new PaintingRenderer(); + renderers[eTYPE_ITEM_FRAME] = new ItemFrameRenderer(); + renderers[eTYPE_ARROW] = new ArrowRenderer(); + renderers[eTYPE_SNOWBALL] = new ItemSpriteRenderer(Item::snowBall); + renderers[eTYPE_THROWNENDERPEARL] = + new ItemSpriteRenderer(Item::enderPearl); + renderers[eTYPE_EYEOFENDERSIGNAL] = + new ItemSpriteRenderer(Item::eyeOfEnder); + renderers[eTYPE_THROWNEGG] = new ItemSpriteRenderer(Item::egg); + renderers[eTYPE_THROWNPOTION] = + new ItemSpriteRenderer(Item::potion, PotionBrewing::THROWABLE_MASK); + renderers[eTYPE_THROWNEXPBOTTLE] = new ItemSpriteRenderer(Item::expBottle); + renderers[eTYPE_FIREBALL] = new FireballRenderer(2.0f); + renderers[eTYPE_SMALL_FIREBALL] = new FireballRenderer(0.5f); + renderers[eTYPE_DRAGON_FIREBALL] = + new FireballRenderer(2.0f); // 4J Added TU9 + renderers[eTYPE_ITEMENTITY] = new ItemRenderer(); + renderers[eTYPE_EXPERIENCEORB] = new ExperienceOrbRenderer(); + renderers[eTYPE_PRIMEDTNT] = new TntRenderer(); + renderers[eTYPE_FALLINGTILE] = new FallingTileRenderer(); + renderers[eTYPE_MINECART] = new MinecartRenderer(); + renderers[eTYPE_BOAT] = new BoatRenderer(); + renderers[eTYPE_FISHINGHOOK] = new FishingHookRenderer(); + renderers[eTYPE_LIGHTNINGBOLT] = new LightningBoltRenderer(); + renderers[eTYPE_ARROW] = new ArrowRenderer(); + glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) - { - it->second->init(this); - } + AUTO_VAR(itEnd, renderers.end()); + for (classToRendererMap::iterator it = renderers.begin(); it != itEnd; + it++) { + it->second->init(this); + } - isGuiRender = false; // 4J added + isGuiRender = false; // 4J added } -EntityRenderer *EntityRenderDispatcher::getRenderer(eINSTANCEOF e) -{ - //EntityRenderer * r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist +EntityRenderer* EntityRenderDispatcher::getRenderer(eINSTANCEOF e) { + // EntityRenderer * r = renderers[e]; + AUTO_VAR(it, renderers.find(e)); // 4J Stu - The .at and [] accessors + // insert elements if they don't exist - if( it == renderers.end() ) - { - // New renderer mapping required in above table - __debugbreak(); - } - /* 4J - not doing this hierarchical search anymore. We need to explicitly add renderers for any eINSTANCEOF type that we want to be able to render - if (it == renderers.end() && e != Entity::_class) - { - EntityRenderer *r = getRenderer(dynamic_cast( e->getSuperclass() )); - renderers.insert( classToRendererMap::value_type( e, r ) ); - return r; - //assert(false); - }*/ - return it->second; + if (it == renderers.end()) { + // New renderer mapping required in above table + __debugbreak(); + } + /* 4J - not doing this hierarchical search anymore. We need to explicitly +add renderers for any eINSTANCEOF type that we want to be able to render if (it +== renderers.end() && e != Entity::_class) + { + EntityRenderer *r = getRenderer(dynamic_cast( +e->getSuperclass() )); renderers.insert( classToRendererMap::value_type( e, r ) +); return r; + //assert(false); +}*/ + return it->second; } -EntityRenderer *EntityRenderDispatcher::getRenderer(std::shared_ptr e) -{ - return getRenderer(e->GetType()); +EntityRenderer* EntityRenderDispatcher::getRenderer(std::shared_ptr e) { + return getRenderer(e->GetType()); } -void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, Options *options, float a) -{ +void EntityRenderDispatcher::prepare(Level* level, Textures* textures, + Font* font, std::shared_ptr player, + Options* options, float a) { this->level = level; this->textures = textures; this->options = options; this->cameraEntity = player; this->font = font; - if (player->isSleeping()) - { - int t = level->getTile(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - if (t == Tile::bed_Id) - { - int data = level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + if (player->isSleeping()) { + int t = level->getTile(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + if (t == Tile::bed_Id) { + int data = + level->getData(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); int direction = data & 3; playerRotY = (float)(direction * 90 + 180); @@ -197,45 +207,38 @@ void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *fon playerRotX = player->xRotO + (player->xRot - player->xRotO) * a; } - std::shared_ptr pl = std::dynamic_pointer_cast(player); - if (pl->ThirdPersonView() == 2) - { - playerRotY += 180; - } + std::shared_ptr pl = std::dynamic_pointer_cast(player); + if (pl->ThirdPersonView() == 2) { + playerRotY += 180; + } xPlayer = player->xOld + (player->x - player->xOld) * a; yPlayer = player->yOld + (player->y - player->yOld) * a; zPlayer = player->zOld + (player->z - player->zOld) * a; - } -void EntityRenderDispatcher::render(std::shared_ptr entity, float a) -{ +void EntityRenderDispatcher::render(std::shared_ptr entity, float a) { double x = entity->xOld + (entity->x - entity->xOld) * a; double y = entity->yOld + (entity->y - entity->yOld) * a; double z = entity->zOld + (entity->z - entity->zOld) * a; - // Fix for #61057 - TU7: Gameplay: Boat is glitching when player float forward and turning. - // Fix to handle the case that yRot and yRotO wrap over the 0/360 line - float rotDiff = entity->yRot - entity->yRotO; - if( rotDiff > 180 || rotDiff < -180) - { - if(entity->yRot > entity->yRotO) - { - rotDiff = (entity->yRot - 360) - entity->yRotO; - } - else - { - rotDiff = entity->yRot - (entity->yRotO - 360); - } - } - float r = entity->yRotO + (rotDiff) * a; - + // Fix for #61057 - TU7: Gameplay: Boat is glitching when player float + // forward and turning. Fix to handle the case that yRot and yRotO wrap over + // the 0/360 line + float rotDiff = entity->yRot - entity->yRotO; + if (rotDiff > 180 || rotDiff < -180) { + if (entity->yRot > entity->yRotO) { + rotDiff = (entity->yRot - 360) - entity->yRotO; + } else { + rotDiff = entity->yRot - (entity->yRotO - 360); + } + } + float r = entity->yRotO + (rotDiff)*a; + int col = entity->getLightColor(a); - if (entity->isOnFire()) - { - col = SharedConstants::FULLBRIGHT_LIGHTVALUE; - } + if (entity->isOnFire()) { + col = SharedConstants::FULLBRIGHT_LIGHTVALUE; + } int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); @@ -244,37 +247,32 @@ void EntityRenderDispatcher::render(std::shared_ptr entity, float a) render(entity, x - xOff, y - yOff, z - zOff, r, a); } -void EntityRenderDispatcher::render(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bItemFrame, bool bRenderPlayerShadow) -{ - EntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) - { - renderer->SetItemFrame(bItemFrame); - - renderer->render(entity, x, y, z, rot, a); +void EntityRenderDispatcher::render(std::shared_ptr entity, double x, + double y, double z, float rot, float a, + bool bItemFrame, bool bRenderPlayerShadow) { + EntityRenderer* renderer = getRenderer(entity); + if (renderer != NULL) { + renderer->SetItemFrame(bItemFrame); + + renderer->render(entity, x, y, z, rot, a); renderer->postRender(entity, x, y, z, rot, a, bRenderPlayerShadow); } } -double EntityRenderDispatcher::distanceToSqr(double x, double y, double z) -{ +double EntityRenderDispatcher::distanceToSqr(double x, double y, double z) { double xd = x - xPlayer; double yd = y - yPlayer; double zd = z - zPlayer; return xd * xd + yd * yd + zd * zd; } -Font *EntityRenderDispatcher::getFont() -{ - return font; -} +Font* EntityRenderDispatcher::getFont() { return font; } -void EntityRenderDispatcher::registerTerrainTextures(IconRegister *iconRegister) -{ - //for (EntityRenderer renderer : renderers.values()) - for(AUTO_VAR(it, renderers.begin()); it != renderers.end(); ++it) - { - EntityRenderer *renderer = it->second; - renderer->registerTerrainTextures(iconRegister); - } +void EntityRenderDispatcher::registerTerrainTextures( + IconRegister* iconRegister) { + // for (EntityRenderer renderer : renderers.values()) + for (AUTO_VAR(it, renderers.begin()); it != renderers.end(); ++it) { + EntityRenderer* renderer = it->second; + renderer->registerTerrainTextures(iconRegister); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h index 92ac51da6..4e6b50a31 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h @@ -4,46 +4,53 @@ #include "../../../Minecraft.World/Util/JavaIntHash.h" class font; - -class EntityRenderDispatcher -{ +class EntityRenderDispatcher { public: - static void staticCtor(); // 4J added + static void staticCtor(); // 4J added private: - typedef std::unordered_map classToRendererMap; - classToRendererMap renderers; - // 4J - was: -// Map, EntityRenderer> renderers = new HashMap, EntityRenderer>(); + typedef std::unordered_map + classToRendererMap; + classToRendererMap renderers; + // 4J - was: + // Map, EntityRenderer> renderers + //= new HashMap, EntityRenderer>(); public: - static EntityRenderDispatcher *instance; + static EntityRenderDispatcher* instance; + private: - Font *font; + Font* font; public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; - Textures *textures; - ItemInHandRenderer *itemInHandRenderer; - Level *level; + Textures* textures; + ItemInHandRenderer* itemInHandRenderer; + Level* level; std::shared_ptr cameraEntity; float playerRotY; float playerRotX; - Options *options; - bool isGuiRender; // 4J added + Options* options; + bool isGuiRender; // 4J added double xPlayer, yPlayer, zPlayer; private: - EntityRenderDispatcher(); + EntityRenderDispatcher(); + public: - EntityRenderer *getRenderer(eINSTANCEOF e); - EntityRenderer *getRenderer(std::shared_ptr e); - void prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, Options *options, float a); + EntityRenderer* getRenderer(eINSTANCEOF e); + EntityRenderer* getRenderer(std::shared_ptr e); + void prepare(Level* level, Textures* textures, Font* font, + std::shared_ptr player, Options* options, float a); void render(std::shared_ptr entity, float a); - void render(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bItemFrame = false, bool bRenderPlayerShadow = true); - void setLevel(Level *level); + void render(std::shared_ptr entity, double x, double y, double z, + float rot, float a, bool bItemFrame = false, + bool bRenderPlayerShadow = true); + void setLevel(Level* level); double distanceToSqr(double x, double y, double z); - Font *getFont(); - void registerTerrainTextures(IconRegister *iconRegister); + Font* getFont(); + void registerTerrainTextures(IconRegister* iconRegister); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp index 7d3614bd0..485254d0a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp @@ -13,128 +13,115 @@ #include "../../Player/LocalPlayer.h" // 4J - added -EntityRenderer::EntityRenderer() -{ - model = NULL; - tileRenderer = new TileRenderer(); +EntityRenderer::EntityRenderer() { + model = NULL; + tileRenderer = new TileRenderer(); shadowRadius = 0; shadowStrength = 1.0f; } -EntityRenderer::~EntityRenderer() -{ - delete tileRenderer; -} +EntityRenderer::~EntityRenderer() { delete tileRenderer; } -void EntityRenderer::bindTexture(int resourceName) -{ +void EntityRenderer::bindTexture(int resourceName) { entityRenderDispatcher->textures->bindTexture(resourceName); } -void EntityRenderer::bindTexture(const std::wstring& resourceName) -{ +void EntityRenderer::bindTexture(const std::wstring& resourceName) { entityRenderDispatcher->textures->bindTexture(resourceName); } -bool EntityRenderer::bindTexture(const std::wstring& urlTexture, int backupTexture) -{ - Textures *t = entityRenderDispatcher->textures; +bool EntityRenderer::bindTexture(const std::wstring& urlTexture, + int backupTexture) { + Textures* t = entityRenderDispatcher->textures; - // 4J-PB - no http textures on the xbox, mem textures instead - - //int id = t->loadHttpTexture(urlTexture, backupTexture); - int id = t->loadMemTexture(urlTexture, backupTexture); + // 4J-PB - no http textures on the xbox, mem textures instead - if (id >= 0) - { - glBindTexture(GL_TEXTURE_2D, id); - t->clearLastBoundId(); + // int id = t->loadHttpTexture(urlTexture, backupTexture); + int id = t->loadMemTexture(urlTexture, backupTexture); + + if (id >= 0) { + glBindTexture(GL_TEXTURE_2D, id); + t->clearLastBoundId(); return true; - } - else - { + } else { return false; } } -bool EntityRenderer::bindTexture(const std::wstring& urlTexture, const std::wstring& backupTexture) -{ - Textures *t = entityRenderDispatcher->textures; +bool EntityRenderer::bindTexture(const std::wstring& urlTexture, + const std::wstring& backupTexture) { + Textures* t = entityRenderDispatcher->textures; - // 4J-PB - no http textures on the xbox, mem textures instead - - //int id = t->loadHttpTexture(urlTexture, backupTexture); - int id = t->loadMemTexture(urlTexture, backupTexture); + // 4J-PB - no http textures on the xbox, mem textures instead - if (id >= 0) - { - glBindTexture(GL_TEXTURE_2D, id); - t->clearLastBoundId(); + // int id = t->loadHttpTexture(urlTexture, backupTexture); + int id = t->loadMemTexture(urlTexture, backupTexture); + + if (id >= 0) { + glBindTexture(GL_TEXTURE_2D, id); + t->clearLastBoundId(); return true; - } - else - { + } else { return false; } } -void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, double z, float a) -{ +void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, + double z, float a) { glDisable(GL_LIGHTING); - Icon *fire1 = Tile::fire->getTextureLayer(0); - Icon *fire2 = Tile::fire->getTextureLayer(1); + Icon* fire1 = Tile::fire->getTextureLayer(0); + Icon* fire2 = Tile::fire->getTextureLayer(1); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); float s = e->bbWidth * 1.4f; glScalef(s, s, s); - MemSect(31); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float r = 0.5f; float xo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = (float)(e->y - e->bb->y0); glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); - glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); + glTranslatef(0, 0, -0.3f + ((int)h) * 0.02f); glColor4f(1, 1, 1, 1); float zo = 0; int ss = 0; t->begin(); - while (h > 0) - { - Icon *tex = NULL; - if (ss % 2 == 0) - { + while (h > 0) { + Icon* tex = NULL; + if (ss % 2 == 0) { tex = fire1; - } - else - { + } else { tex = fire2; } - float u0 = tex->getU0(); - float v0 = tex->getV0(); - float u1 = tex->getU1(); - float v1 = tex->getV1(); + float u0 = tex->getU0(); + float v0 = tex->getV0(); + float u1 = tex->getU1(); + float v1 = tex->getV1(); - if (ss / 2 % 2 == 0) - { + if (ss / 2 % 2 == 0) { float tmp = u1; u1 = u0; u0 = tmp; } - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( zo), (float)( u1), (float)( v1)); - t->vertexUV((float)(-r - xo), (float)( 0 - yo), (float)( zo), (float)( u0), (float)( v1)); - t->vertexUV((float)(-r - xo), (float)( 1.4f - yo), (float)( zo), (float)( u0), (float)( v0)); - t->vertexUV((float)(r - xo), (float)( 1.4f - yo), (float)( zo), (float)( u1), (float)( v0)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(zo), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-r - xo), (float)(0 - yo), (float)(zo), (float)(u0), + (float)(v1)); + t->vertexUV((float)(-r - xo), (float)(1.4f - yo), (float)(zo), + (float)(u0), (float)(v0)); + t->vertexUV((float)(r - xo), (float)(1.4f - yo), (float)(zo), + (float)(u1), (float)(v0)); h -= 0.45f; yo -= 0.45f; r *= 0.9f; @@ -144,57 +131,53 @@ void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, t->end(); glPopMatrix(); glEnable(GL_LIGHTING); - } -void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a) -{ - glDisable(GL_LIGHTING); +void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a) { + glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - MemSect(31); - entityRenderDispatcher->textures->bindTexture(TN__CLAMP__MISC_SHADOW);//L"%clamp%/misc/shadow.png")); - MemSect(0); + MemSect(31); + entityRenderDispatcher->textures->bindTexture( + TN__CLAMP__MISC_SHADOW); // L"%clamp%/misc/shadow.png")); + MemSect(0); - Level *level = getLevel(); + Level* level = getLevel(); glDepthMask(false); float r = shadowRadius; - std::shared_ptr mob = std::dynamic_pointer_cast(e); - bool isLocalPlayer = false; - float fYLocalPlayerShadowOffset=0.0f; + std::shared_ptr mob = std::dynamic_pointer_cast(e); + bool isLocalPlayer = false; + float fYLocalPlayerShadowOffset = 0.0f; - //if (std::dynamic_pointer_cast(e) != NULL) - if (mob != NULL) - { - //std::shared_ptr mob = std::dynamic_pointer_cast(e); - r *= mob->getSizeScale(); + // if (std::dynamic_pointer_cast(e) != NULL) + if (mob != NULL) { + // std::shared_ptr mob = std::dynamic_pointer_cast(e); + r *= mob->getSizeScale(); - std::shared_ptr animal = std::dynamic_pointer_cast(mob); - if (animal != NULL) - { - if (animal->isBaby()) - { - r *= 0.5f; - } - } + std::shared_ptr animal = std::dynamic_pointer_cast(mob); + if (animal != NULL) { + if (animal->isBaby()) { + r *= 0.5f; + } + } - if(std::dynamic_pointer_cast(mob)!=NULL) - { - isLocalPlayer=true; - } - } + if (std::dynamic_pointer_cast(mob) != NULL) { + isLocalPlayer = true; + } + } double ex = e->xOld + (e->x - e->xOld) * a; double ey = e->yOld + (e->y - e->yOld) * a + e->getShadowHeightOffs(); - // 4J-PB - local players seem to have a position at their head, and remote players have a foot position. - // get the shadow to render by changing the check here depending on the player type - if(isLocalPlayer) - { - ey-=1.62; - fYLocalPlayerShadowOffset=-1.62f; - } + // 4J-PB - local players seem to have a position at their head, and remote + // players have a foot position. get the shadow to render by changing the + // check here depending on the player type + if (isLocalPlayer) { + ey -= 1.62; + fYLocalPlayerShadowOffset = -1.62f; + } double ez = e->zOld + (e->z - e->zOld) * a; int x0 = Mth::floor(ex - r); @@ -205,45 +188,48 @@ void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, int z1 = Mth::floor(ez + r); double xo = x - ex; - double yo = y - ey; + double yo = y - ey; double zo = z - ez; - Tesselator *tt = Tesselator::getInstance(); + Tesselator* tt = Tesselator::getInstance(); tt->begin(); for (int xt = x0; xt <= x1; xt++) for (int yt = y0; yt <= y1; yt++) - for (int zt = z0; zt <= z1; zt++) - { - int t = level->getTile(xt, yt - 1, zt); - if (t > 0 && level->getRawBrightness(xt, yt, zt) > 3) - { - renderTileShadow(Tile::tiles[t], x, y + e->getShadowHeightOffs() + fYLocalPlayerShadowOffset, z, xt, yt , zt, pow, r, xo, yo + e->getShadowHeightOffs() + fYLocalPlayerShadowOffset, zo); - } + for (int zt = z0; zt <= z1; zt++) { + int t = level->getTile(xt, yt - 1, zt); + if (t > 0 && level->getRawBrightness(xt, yt, zt) > 3) { + renderTileShadow(Tile::tiles[t], x, + y + e->getShadowHeightOffs() + + fYLocalPlayerShadowOffset, + z, xt, yt, zt, pow, r, xo, + yo + e->getShadowHeightOffs() + + fYLocalPlayerShadowOffset, + zo); + } } tt->end(); glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); glDepthMask(true); - glEnable(GL_LIGHTING); - + glEnable(GL_LIGHTING); } -Level *EntityRenderer::getLevel() -{ - return entityRenderDispatcher->level; -} +Level* EntityRenderer::getLevel() { return entityRenderDispatcher->level; } -void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, int xt, int yt, int zt, float pow, float r, double xo, double yo, double zo) -{ - Tesselator *t = Tesselator::getInstance(); +void EntityRenderer::renderTileShadow(Tile* tt, double x, double y, double z, + int xt, int yt, int zt, float pow, + float r, double xo, double yo, + double zo) { + Tesselator* t = Tesselator::getInstance(); if (!tt->isCubeShaped()) return; - double a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * getLevel()->getBrightness(xt, yt, zt); + double a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * + getLevel()->getBrightness(xt, yt, zt); if (a < 0) return; if (a > 1) a = 1; - - t->color(1.0f, 1.0f, 1.0f, (float) a); + + t->color(1.0f, 1.0f, 1.0f, (float)a); // glColor4f(1, 1, 1, (float) a); double x0 = xt + tt->getShapeX0() + xo; @@ -252,159 +238,160 @@ void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, in double z0 = zt + tt->getShapeZ0() + zo; double z1 = zt + tt->getShapeZ1() + zo; - float u0 = (float) ((x - (x0)) / 2 / r + 0.5f); - float u1 = (float) ((x - (x1)) / 2 / r + 0.5f); - float v0 = (float) ((z - (z0)) / 2 / r + 0.5f); - float v1 = (float) ((z - (z1)) / 2 / r + 0.5f); + float u0 = (float)((x - (x0)) / 2 / r + 0.5f); + float u1 = (float)((x - (x1)) / 2 / r + 0.5f); + float v0 = (float)((z - (z0)) / 2 / r + 0.5f); + float v1 = (float)((z - (z1)) / 2 / r + 0.5f); // u0 = 0; // v0 = 0; // u1 = 1; // v1 = 1; - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); } -void EntityRenderer::render(AABB *bb, double xo, double yo, double zo) -{ +void EntityRenderer::render(AABB* bb, double xo, double yo, double zo) { glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glColor4f(1, 1, 1, 1); t->begin(); t->offset((float)xo, (float)yo, (float)zo); t->normal(0, 0, -1); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); t->normal(0, 0, 1); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); t->normal(0, -1, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); t->normal(0, 1, 0); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); t->normal(-1, 0, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); t->normal(1, 0, 0); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); t->offset(0, 0, 0); t->end(); glEnable(GL_TEXTURE_2D); // model.render(0, 1) } -void EntityRenderer::renderFlat(AABB *bb) -{ - Tesselator *t = Tesselator::getInstance(); +void EntityRenderer::renderFlat(AABB* bb) { + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); t->end(); } -void EntityRenderer::renderFlat(float x0, float y0, float z0, float x1, float y1, float z1) -{ - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertex(x0, y1, z0); - t->vertex(x1, y1, z0); - t->vertex(x1, y0, z0); - t->vertex(x0, y0, z0); - t->vertex(x0, y0, z1); - t->vertex(x1, y0, z1); - t->vertex(x1, y1, z1); - t->vertex(x0, y1, z1); - t->vertex(x0, y0, z0); - t->vertex(x1, y0, z0); - t->vertex(x1, y0, z1); - t->vertex(x0, y0, z1); - t->vertex(x0, y1, z1); - t->vertex(x1, y1, z1); - t->vertex(x1, y1, z0); - t->vertex(x0, y1, z0); - t->vertex(x0, y0, z1); - t->vertex(x0, y1, z1); - t->vertex(x0, y1, z0); - t->vertex(x0, y0, z0); - t->vertex(x1, y0, z0); - t->vertex(x1, y1, z0); - t->vertex(x1, y1, z1); - t->vertex(x1, y0, z1); - t->end(); +void EntityRenderer::renderFlat(float x0, float y0, float z0, float x1, + float y1, float z1) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertex(x0, y1, z0); + t->vertex(x1, y1, z0); + t->vertex(x1, y0, z0); + t->vertex(x0, y0, z0); + t->vertex(x0, y0, z1); + t->vertex(x1, y0, z1); + t->vertex(x1, y1, z1); + t->vertex(x0, y1, z1); + t->vertex(x0, y0, z0); + t->vertex(x1, y0, z0); + t->vertex(x1, y0, z1); + t->vertex(x0, y0, z1); + t->vertex(x0, y1, z1); + t->vertex(x1, y1, z1); + t->vertex(x1, y1, z0); + t->vertex(x0, y1, z0); + t->vertex(x0, y0, z1); + t->vertex(x0, y1, z1); + t->vertex(x0, y1, z0); + t->vertex(x0, y0, z0); + t->vertex(x1, y0, z0); + t->vertex(x1, y1, z0); + t->vertex(x1, y1, z1); + t->vertex(x1, y0, z1); + t->end(); } -void EntityRenderer::init(EntityRenderDispatcher *entityRenderDispatcher) -{ - this->entityRenderDispatcher = entityRenderDispatcher; +void EntityRenderer::init(EntityRenderDispatcher* entityRenderDispatcher) { + this->entityRenderDispatcher = entityRenderDispatcher; } -void EntityRenderer::postRender(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bRenderPlayerShadow) -{ - if( !entityRenderDispatcher->isGuiRender ) // 4J - added, don't render shadow in gui as it uses its own blending, and we have globally enabled blending for interface opacity - { - if (bRenderPlayerShadow && entityRenderDispatcher->options->fancyGraphics && shadowRadius > 0 && !entity->isInvisible()) - { - double dist = entityRenderDispatcher->distanceToSqr(entity->x, entity->y, entity->z); - float pow = (float) ((1 - dist / (16.0f * 16.0f)) * shadowStrength); - if (pow > 0) - { - renderShadow(entity, x, y, z, pow, a); - } - } - } - if (entity->isOnFire()) renderFlame(entity, x, y, z, a); +void EntityRenderer::postRender(std::shared_ptr entity, double x, + double y, double z, float rot, float a, + bool bRenderPlayerShadow) { + if (!entityRenderDispatcher + ->isGuiRender) // 4J - added, don't render shadow in gui as it + // uses its own blending, and we have globally + // enabled blending for interface opacity + { + if (bRenderPlayerShadow && + entityRenderDispatcher->options->fancyGraphics && + shadowRadius > 0 && !entity->isInvisible()) { + double dist = entityRenderDispatcher->distanceToSqr( + entity->x, entity->y, entity->z); + float pow = (float)((1 - dist / (16.0f * 16.0f)) * shadowStrength); + if (pow > 0) { + renderShadow(entity, x, y, z, pow, a); + } + } + } + if (entity->isOnFire()) renderFlame(entity, x, y, z, a); } -Font *EntityRenderer::getFont() -{ - return entityRenderDispatcher->getFont(); -} +Font* EntityRenderer::getFont() { return entityRenderDispatcher->getFont(); } -void EntityRenderer::registerTerrainTextures(IconRegister *iconRegister) -{ -} \ No newline at end of file +void EntityRenderer::registerTerrainTextures(IconRegister* iconRegister) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h index 4337d84d1..21a7969ce 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h @@ -11,55 +11,69 @@ class Level; class AABB; class IconRegister; - - class EntityRenderDispatcher; class Font; // 4J - this was originally a generic of type EntityRenderer -class EntityRenderer -{ - friend class PlayerRenderer; // 4J Added to allow PlayerRenderer to call renderShadow +class EntityRenderer { + friend class PlayerRenderer; // 4J Added to allow PlayerRenderer to call + // renderShadow protected: - EntityRenderDispatcher *entityRenderDispatcher; + EntityRenderDispatcher* entityRenderDispatcher; private: - Model *model; // 4J - TODO - check why exactly this is here, it seems to get shadowed by classes inheriting from this by their own + Model* model; // 4J - TODO - check why exactly this is here, it seems to + // get shadowed by classes inheriting from this by their own protected: - TileRenderer *tileRenderer; // 4J - changed to protected so derived classes can use instead of shadowing their own + TileRenderer* tileRenderer; // 4J - changed to protected so derived classes + // can use instead of shadowing their own protected: - float shadowRadius; + float shadowRadius; float shadowStrength; public: - EntityRenderer(); // 4J - added - virtual ~EntityRenderer(); + EntityRenderer(); // 4J - added + virtual ~EntityRenderer(); + public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float rot, float a) = 0; + virtual void render(std::shared_ptr entity, double x, double y, + double z, float rot, float a) = 0; + protected: - virtual void bindTexture(int resourceName); // 4J - added - virtual void bindTexture(const std::wstring& resourceName); + virtual void bindTexture(int resourceName); // 4J - added + virtual void bindTexture(const std::wstring& resourceName); + + virtual bool bindTexture(const std::wstring& urlTexture, + int backupTexture); // 4J added + virtual bool bindTexture(const std::wstring& urlTexture, + const std::wstring& backupTexture); - virtual bool bindTexture(const std::wstring& urlTexture, int backupTexture); // 4J added - virtual bool bindTexture(const std::wstring& urlTexture, const std::wstring& backupTexture); private: - virtual void renderFlame(std::shared_ptr e, double x, double y, double z, float a); - virtual void renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a); + virtual void renderFlame(std::shared_ptr e, double x, double y, + double z, float a); + virtual void renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a); - virtual Level *getLevel(); - virtual void renderTileShadow(Tile *tt, double x, double y, double z, int xt, int yt, int zt, float pow, float r, double xo, double yo, double zo); -public: - virtual void render(AABB *bb, double xo, double yo, double zo); - static void renderFlat(AABB *bb); - static void renderFlat(float x0, float y0, float z0, float x1, float y1, float z1); - virtual void init(EntityRenderDispatcher *entityRenderDispatcher); - virtual void postRender(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bRenderPlayerShadow); - virtual Font *getFont(); - virtual void registerTerrainTextures(IconRegister *iconRegister); + virtual Level* getLevel(); + virtual void renderTileShadow(Tile* tt, double x, double y, double z, + int xt, int yt, int zt, float pow, float r, + double xo, double yo, double zo); public: - // 4J Added - virtual Model *getModel() { return model; } - virtual void SetItemFrame(bool bSet) {} + virtual void render(AABB* bb, double xo, double yo, double zo); + static void renderFlat(AABB* bb); + static void renderFlat(float x0, float y0, float z0, float x1, float y1, + float z1); + virtual void init(EntityRenderDispatcher* entityRenderDispatcher); + virtual void postRender(std::shared_ptr entity, double x, double y, + double z, float rot, float a, + bool bRenderPlayerShadow); + virtual Font* getFont(); + virtual void registerTerrainTextures(IconRegister* iconRegister); + +public: + // 4J Added + virtual Model* getModel() { return model; } + virtual void SetItemFrame(bool bSet) {} }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp index 844260ea5..0d6423815 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp @@ -3,22 +3,21 @@ #include "TileEntityRenderDispatcher.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" -EntityTileRenderer *EntityTileRenderer::instance = new EntityTileRenderer; +EntityTileRenderer* EntityTileRenderer::instance = new EntityTileRenderer; -EntityTileRenderer::EntityTileRenderer() -{ - chest = std::shared_ptr(new ChestTileEntity()); - enderChest = std::shared_ptr(new EnderChestTileEntity()); +EntityTileRenderer::EntityTileRenderer() { + chest = std::shared_ptr(new ChestTileEntity()); + enderChest = + std::shared_ptr(new EnderChestTileEntity()); } -void EntityTileRenderer::render(Tile *tile, int data, float brightness, float alpha, bool setColor, bool useCompiled) -{ - if (tile->id == Tile::enderChest_Id) - { - TileEntityRenderDispatcher::instance->render(enderChest, 0, 0, 0, 0, setColor, alpha, useCompiled); - } - else - { - TileEntityRenderDispatcher::instance->render(chest, 0, 0, 0, 0, setColor, alpha, useCompiled); - } +void EntityTileRenderer::render(Tile* tile, int data, float brightness, + float alpha, bool setColor, bool useCompiled) { + if (tile->id == Tile::enderChest_Id) { + TileEntityRenderDispatcher::instance->render( + enderChest, 0, 0, 0, 0, setColor, alpha, useCompiled); + } else { + TileEntityRenderDispatcher::instance->render( + chest, 0, 0, 0, 0, setColor, alpha, useCompiled); + } } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h index 14ba6bfc6..a9d5ab6e1 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h @@ -4,16 +4,19 @@ class ChestTileEntity; class EnderChestTileEntity; class Tile; -class EntityTileRenderer - { - public: - static EntityTileRenderer *instance; +class EntityTileRenderer { +public: + static EntityTileRenderer* instance; - private: - std::shared_ptr chest; - std::shared_ptr enderChest; +private: + std::shared_ptr chest; + std::shared_ptr enderChest; - public: - EntityTileRenderer(); - void render(Tile *tile, int data, float brightness, float alpha, bool setColor = true, bool useCompiled = true); // 4J - added setColor parameter and alpha for chest in the crafting menu, and added useCompiled +public: + EntityTileRenderer(); + void render(Tile* tile, int data, float brightness, float alpha, + bool setColor = true, + bool useCompiled = + true); // 4J - added setColor parameter and alpha for chest + // in the crafting menu, and added useCompiled }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp index 78ec3bceb..a5e767353 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp @@ -8,84 +8,78 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Util/JavaMath.h" -ExperienceOrbRenderer::ExperienceOrbRenderer() -{ - // 4J In class Java initialisors - tileRenderer = new TileRenderer(); - setColor = true; +ExperienceOrbRenderer::ExperienceOrbRenderer() { + // 4J In class Java initialisors + tileRenderer = new TileRenderer(); + setColor = true; - this->shadowRadius = 0.15f; - this->shadowStrength = 0.75f; + this->shadowRadius = 0.15f; + this->shadowStrength = 0.75f; } +void ExperienceOrbRenderer::render(std::shared_ptr _orb, double x, + double y, double z, float rot, float a) { + std::shared_ptr orb = + std::dynamic_pointer_cast(_orb); + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); -void ExperienceOrbRenderer::render(std::shared_ptr _orb, double x, double y, double z, float rot, float a) -{ - std::shared_ptr orb = std::dynamic_pointer_cast(_orb); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + int icon = orb->getIcon(); + bindTexture(TN_ITEM_EXPERIENCE_ORB); // 4J was L"/item/xporb.png" + Tesselator* t = Tesselator::getInstance(); - int icon = orb->getIcon(); - bindTexture(TN_ITEM_EXPERIENCE_ORB); // 4J was L"/item/xporb.png" - Tesselator *t = Tesselator::getInstance(); + float u0 = ((icon % 4) * 16 + 0) / 64.0f; + float u1 = ((icon % 4) * 16 + 16) / 64.0f; + float v0 = ((icon / 4) * 16 + 0) / 64.0f; + float v1 = ((icon / 4) * 16 + 16) / 64.0f; - float u0 = ((icon % 4) * 16 + 0) / 64.0f; - float u1 = ((icon % 4) * 16 + 16) / 64.0f; - float v0 = ((icon / 4) * 16 + 0) / 64.0f; - float v1 = ((icon / 4) * 16 + 16) / 64.0f; + float r = 1.0f; + float xo = 0.5f; + float yo = 0.25f; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = orb->getLightColor(a); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } else { + float br = orb->getBrightness(a); + glColor4f(br, br, br, 1); + } + float br = 255.0f; + float rr = (orb->tickCount + a) / 2; + int rc = (int)((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); + int gc = (int)(br); + int bc = (int)((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); + int col = rc << 16 | gc << 8 | bc; + glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); + glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); + float s = 0.3f; + glScalef(s, s, s); + t->begin(); + t->color(col, 128); + t->normal(0, 1, 0); + t->vertexUV(0 - xo, 0 - yo, 0, u0, v1); + t->vertexUV(r - xo, 0 - yo, 0, u1, v1); + t->vertexUV(r - xo, 1 - yo, 0, u1, v0); + t->vertexUV(0 - xo, 1 - yo, 0, u0, v0); + t->end(); - float r = 1.0f; - float xo = 0.5f; - float yo = 0.25f; - - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = orb->getLightColor(a); - int u = col % 65536; - int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } - else - { - float br = orb->getBrightness(a); - glColor4f(br, br, br, 1); - } - float br = 255.0f; - float rr = (orb->tickCount + a) / 2; - int rc = (int) ((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); - int gc = (int) (br); - int bc = (int) ((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); - int col = rc << 16 | gc << 8 | bc; - glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); - glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); - float s = 0.3f; - glScalef(s, s, s); - t->begin(); - t->color(col, 128); - t->normal(0, 1, 0); - t->vertexUV(0 - xo, 0 - yo, 0, u0, v1); - t->vertexUV(r - xo, 0 - yo, 0, u1, v1); - t->vertexUV(r - xo, 1 - yo, 0, u1, v0); - t->vertexUV(0 - xo, 1 - yo, 0, u0, v0); - t->end(); - - glDisable(GL_BLEND); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); + glDisable(GL_BLEND); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); } -void ExperienceOrbRenderer::blit(int x, int y, int sx, int sy, int w, int h) -{ - float blitOffset = 0; - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertexUV(x + 0, y + h, blitOffset, (sx + 0) * us, (sy + h) * vs); - t->vertexUV(x + w, y + h, blitOffset, (sx + w) * us, (sy + h) * vs); - t->vertexUV(x + w, y + 0, blitOffset, (sx + w) * us, (sy + 0) * vs); - t->vertexUV(x + 0, y + 0, blitOffset, (sx + 0) * us, (sy + 0) * vs); - t->end(); +void ExperienceOrbRenderer::blit(int x, int y, int sx, int sy, int w, int h) { + float blitOffset = 0; + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertexUV(x + 0, y + h, blitOffset, (sx + 0) * us, (sy + h) * vs); + t->vertexUV(x + w, y + h, blitOffset, (sx + w) * us, (sy + h) * vs); + t->vertexUV(x + w, y + 0, blitOffset, (sx + w) * us, (sy + 0) * vs); + t->vertexUV(x + 0, y + 0, blitOffset, (sx + 0) * us, (sy + 0) * vs); + t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h index 5237ecb8d..2812f9280 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h @@ -2,16 +2,16 @@ #include "EntityRenderer.h" -class ExperienceOrbRenderer : public EntityRenderer -{ +class ExperienceOrbRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - bool setColor; + bool setColor; - ExperienceOrbRenderer(); + ExperienceOrbRenderer(); - void render(std::shared_ptr _orb, double x, double y, double z, float rot, float a); - void blit(int x, int y, int sx, int sy, int w, int h); + void render(std::shared_ptr _orb, double x, double y, double z, + float rot, float a); + void blit(int x, int y, int sx, int sy, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp index dc046ec1f..d47bf7efa 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp @@ -6,51 +6,57 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" #include "EntityRenderDispatcher.h" -FallingTileRenderer::FallingTileRenderer() : EntityRenderer() -{ - tileRenderer = new TileRenderer(); - this->shadowRadius = 0.5f; +FallingTileRenderer::FallingTileRenderer() : EntityRenderer() { + tileRenderer = new TileRenderer(); + this->shadowRadius = 0.5f; } -void FallingTileRenderer::render(std::shared_ptr _tile, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr tile = std::dynamic_pointer_cast(_tile); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); +void FallingTileRenderer::render(std::shared_ptr _tile, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr tile = + std::dynamic_pointer_cast(_tile); + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - Tile *tt = Tile::tiles[tile->tile]; + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + Tile* tt = Tile::tiles[tile->tile]; - Level *level = tile->getLevel(); + Level* level = tile->getLevel(); - glDisable(GL_LIGHTING); - glColor4f(1, 1, 1, 1); // 4J added - this wouldn't be needed in real opengl as the block render has vertex colours and so this isn't use, but our pretend gl always modulates with this - if (tt == Tile::anvil && tt->getRenderShape() == Tile::SHAPE_ANVIL) - { - tileRenderer->level = level; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, -Mth::floor(tile->z) - 0.5f); - tileRenderer->tesselateAnvilInWorld((AnvilTile *) tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); - t->offset(0, 0, 0); - t->end(); - } - else if (tt == Tile::dragonEgg) - { - tileRenderer->level = level; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, -Mth::floor(tile->z) - 0.5f); - tileRenderer->tesselateInWorld(tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z)); - t->offset(0, 0, 0); - t->end(); - } - else if( tt != NULL ) - { - tileRenderer->setShape(tt); - tileRenderer->renderBlock(tt, level, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); - } - glEnable(GL_LIGHTING); - glPopMatrix(); + glDisable(GL_LIGHTING); + glColor4f(1, 1, 1, + 1); // 4J added - this wouldn't be needed in real opengl as the + // block render has vertex colours and so this isn't use, but + // our pretend gl always modulates with this + if (tt == Tile::anvil && tt->getRenderShape() == Tile::SHAPE_ANVIL) { + tileRenderer->level = level; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, + -Mth::floor(tile->z) - 0.5f); + tileRenderer->tesselateAnvilInWorld((AnvilTile*)tt, Mth::floor(tile->x), + Mth::floor(tile->y), + Mth::floor(tile->z), tile->data); + t->offset(0, 0, 0); + t->end(); + } else if (tt == Tile::dragonEgg) { + tileRenderer->level = level; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, + -Mth::floor(tile->z) - 0.5f); + tileRenderer->tesselateInWorld( + tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z)); + t->offset(0, 0, 0); + t->end(); + } else if (tt != NULL) { + tileRenderer->setShape(tt); + tileRenderer->renderBlock(tt, level, Mth::floor(tile->x), + Mth::floor(tile->y), Mth::floor(tile->z), + tile->data); + } + glEnable(GL_LIGHTING); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h index c3181c968..30772c7de 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h @@ -1,14 +1,13 @@ #pragma once #include "EntityRenderer.h" - -class FallingTileRenderer : public EntityRenderer -{ +class FallingTileRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - FallingTileRenderer(); + FallingTileRenderer(); - virtual void render(std::shared_ptr _tile, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _tile, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp index cfbf5e334..32c72d991 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp @@ -7,27 +7,27 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -FireballRenderer::FireballRenderer(float scale) -{ - this->scale = scale; -} +FireballRenderer::FireballRenderer(float scale) { this->scale = scale; } -void FireballRenderer::render(std::shared_ptr _fireball, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr fireball = std::dynamic_pointer_cast(_fireball); +void FireballRenderer::render(std::shared_ptr _fireball, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr fireball = + std::dynamic_pointer_cast(_fireball); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); float s = scale; glScalef(s / 1.0f, s / 1.0f, s / 1.0f); - Icon *icon = Item::fireball->getIcon(fireball->GetType()==eTYPE_DRAGON_FIREBALL?1:0);//14 + 2 * 16; - MemSect(31); - bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + Icon* icon = Item::fireball->getIcon( + fireball->GetType() == eTYPE_DRAGON_FIREBALL ? 1 : 0); // 14 + 2 * 16; + MemSect(31); + bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float u0 = icon->getU0(); float u1 = icon->getU1(); @@ -42,66 +42,72 @@ void FireballRenderer::render(std::shared_ptr _fireball, double x, doubl glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); - } // 4J Added override. Based on EntityRenderer::renderFlame -void FireballRenderer::renderFlame(std::shared_ptr e, double x, double y, double z, float a) -{ - glDisable(GL_LIGHTING); - Icon *tex = Tile::fire->getTextureLayer(0); +void FireballRenderer::renderFlame(std::shared_ptr e, double x, + double y, double z, float a) { + glDisable(GL_LIGHTING); + Icon* tex = Tile::fire->getTextureLayer(0); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); float s = e->bbWidth * 1.4f; glScalef(s, s, s); - MemSect(31); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float r = 1.0f; float xo = 0.5f; -// float yo = 0.0f; + // float yo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = (float)(e->y - e->bb->y0); - //glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); + // glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); - glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); - glTranslatef(0,0,0.1f); - //glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); + glTranslatef(0, 0, 0.1f); + // glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); glColor4f(1, 1, 1, 1); // glRotatef(-playerRotX, 1, 0, 0); float zo = 0; t->begin(); - t->normal(0, 1, 0); + t->normal(0, 1, 0); - float u0 = tex->getU0(); - float v0 = tex->getV0(); - float u1 = tex->getU1(); - float v1 = tex->getV1(); + float u0 = tex->getU0(); + float v0 = tex->getV0(); + float u1 = tex->getU1(); + float v1 = tex->getV1(); - float tmp = u1; - u1 = u0; - u0 = tmp; + float tmp = u1; + u1 = u0; + u0 = tmp; - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1.4f - yo), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1.4f - yo), (float)( 0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1.4f - yo), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1.4f - yo), (float)(0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); diff --git a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h index 201e3aad1..cbe2fb37d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h @@ -1,17 +1,18 @@ #pragma once #include "EntityRenderer.h" -class FireballRenderer : public EntityRenderer -{ +class FireballRenderer : public EntityRenderer { private: - float scale; + float scale; public: - FireballRenderer(float scale); + FireballRenderer(float scale); - virtual void render(std::shared_ptr _fireball, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _fireball, double x, double y, + double z, float rot, float a); private: - // 4J Added override - virtual void renderFlame(std::shared_ptr e, double x, double y, double z, float a); + // 4J Added override + virtual void renderFlame(std::shared_ptr e, double x, double y, + double z, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp index 4f30ed9cf..b329752fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp @@ -8,27 +8,28 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../Player/MultiPlayerLocalPlayer.h" -void FishingHookRenderer::render(std::shared_ptr _hook, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr hook = std::dynamic_pointer_cast(_hook); +void FishingHookRenderer::render(std::shared_ptr _hook, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr hook = + std::dynamic_pointer_cast(_hook); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); int xi = 1; int yi = 2; - bindTexture(TN_PARTICLES); // 4J was L"/particles.png" - Tesselator *t = Tesselator::getInstance(); + bindTexture(TN_PARTICLES); // 4J was L"/particles.png" + Tesselator* t = Tesselator::getInstance(); float u0 = ((xi) * 8 + 0) / 128.0f; float u1 = ((xi) * 8 + 8) / 128.0f; float v0 = ((yi) * 8 + 0) / 128.0f; float v1 = ((yi) * 8 + 8) / 128.0f; - float r = 1.0f; float xo = 0.5f; float yo = 0.5f; @@ -37,62 +38,79 @@ void FishingHookRenderer::render(std::shared_ptr _hook, double x, double glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); - - if (hook->owner != NULL) - { + if (hook->owner != NULL) { float swing = hook->owner->getAttackAnim(a); - float swing2 = (float) Mth::sin((sqrt(swing)) * PI); + float swing2 = (float)Mth::sin((sqrt(swing)) * PI); - - Vec3 *vv = Vec3::newTemp(-0.5, 0.03, 0.8); - vv->xRot(-(hook->owner->xRotO + (hook->owner->xRot - hook->owner->xRotO) * a) * PI / 180); - vv->yRot(-(hook->owner->yRotO + (hook->owner->yRot - hook->owner->yRotO) * a) * PI / 180); + Vec3* vv = Vec3::newTemp(-0.5, 0.03, 0.8); + vv->xRot(-(hook->owner->xRotO + + (hook->owner->xRot - hook->owner->xRotO) * a) * + PI / 180); + vv->yRot(-(hook->owner->yRotO + + (hook->owner->yRot - hook->owner->yRotO) * a) * + PI / 180); vv->yRot(swing2 * 0.5f); vv->xRot(-swing2 * 0.7f); - double xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a + vv->x; - double yp = hook->owner->yo + (hook->owner->y - hook->owner->yo) * a + vv->y; - double zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a + vv->z; - double yOffset = hook->owner != std::dynamic_pointer_cast(Minecraft::GetInstance()->player) ? hook->owner->getHeadHeight() : 0; + double xp = + hook->owner->xo + (hook->owner->x - hook->owner->xo) * a + vv->x; + double yp = + hook->owner->yo + (hook->owner->y - hook->owner->yo) * a + vv->y; + double zp = + hook->owner->zo + (hook->owner->z - hook->owner->zo) * a + vv->z; + double yOffset = hook->owner != std::dynamic_pointer_cast( + Minecraft::GetInstance()->player) + ? hook->owner->getHeadHeight() + : 0; - // 4J-PB - changing this to be per player - //if (this->entityRenderDispatcher->options->thirdPersonView) - if (hook->owner->ThirdPersonView() > 0) - { - float rr = (float) (hook->owner->yBodyRotO + (hook->owner->yBodyRot - hook->owner->yBodyRotO) * a) * PI / 180; - double ss = Mth::sin((float) rr); - double cc = Mth::cos((float) rr); - xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a - cc * 0.35 - ss * 0.85; - yp = hook->owner->yo + yOffset + (hook->owner->y - hook->owner->yo) * a - 0.45; - zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a - ss * 0.35 + cc * 0.85; + // 4J-PB - changing this to be per player + // if (this->entityRenderDispatcher->options->thirdPersonView) + if (hook->owner->ThirdPersonView() > 0) { + float rr = + (float)(hook->owner->yBodyRotO + + (hook->owner->yBodyRot - hook->owner->yBodyRotO) * a) * + PI / 180; + double ss = Mth::sin((float)rr); + double cc = Mth::cos((float)rr); + xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a - + cc * 0.35 - ss * 0.85; + yp = hook->owner->yo + yOffset + + (hook->owner->y - hook->owner->yo) * a - 0.45; + zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a - + ss * 0.35 + cc * 0.85; } double xh = hook->xo + (hook->x - hook->xo) * a; double yh = hook->yo + (hook->y - hook->yo) * a + 4 / 16.0f; double zh = hook->zo + (hook->z - hook->zo) * a; - double xa = (float) (xp - xh); - double ya = (float) (yp - yh); - double za = (float) (zp - zh); + double xa = (float)(xp - xh); + double ya = (float)(yp - yh); + double za = (float)(zp - zh); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); t->begin(GL_LINE_STRIP); t->color(0x000000); int steps = 16; - for (int i = 0; i <= steps; i++) - { - float aa = i / (float) steps; - t->vertex((float)(x + xa * aa), (float)( y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), (float)( z + za * aa)); + for (int i = 0; i <= steps; i++) { + float aa = i / (float)steps; + t->vertex((float)(x + xa * aa), + (float)(y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), + (float)(z + za * aa)); } t->end(); glEnable(GL_LIGHTING); diff --git a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h index 338bc6046..9e49dcf46 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class FishingHookRenderer : public EntityRenderer -{ -public: - virtual void render(std::shared_ptr _hook, double x, double y, double z, float rot, float a); +class FishingHookRenderer : public EntityRenderer { +public: + virtual void render(std::shared_ptr _hook, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp index 059d5ef02..29637645d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp @@ -3,19 +3,16 @@ #include "../Models/GhastModel.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -GhastRenderer::GhastRenderer() : MobRenderer(new GhastModel(), 0.5f) -{ -} +GhastRenderer::GhastRenderer() : MobRenderer(new GhastModel(), 0.5f) {} -void GhastRenderer::scale(std::shared_ptr mob, float a) -{ - std::shared_ptr ghast = std::dynamic_pointer_cast(mob); - - float ss = (ghast->oCharge+(ghast->charge-ghast->oCharge)*a)/20.0f; - if (ss<0) ss = 0; - ss = 1/(ss*ss*ss*ss*ss*2+1); - float s = (8+ss)/2; - float hs = (8+1/ss)/2; - glScalef(hs, s, hs); - glColor4f(1, 1, 1, 1); +void GhastRenderer::scale(std::shared_ptr mob, float a) { + std::shared_ptr ghast = std::dynamic_pointer_cast(mob); + + float ss = (ghast->oCharge + (ghast->charge - ghast->oCharge) * a) / 20.0f; + if (ss < 0) ss = 0; + ss = 1 / (ss * ss * ss * ss * ss * 2 + 1); + float s = (8 + ss) / 2; + float hs = (8 + 1 / ss) / 2; + glScalef(hs, s, hs); + glColor4f(1, 1, 1, 1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h index 1bd3131f8..d552871fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h @@ -1,11 +1,10 @@ #pragma once #include "MobRenderer.h" -class GhastRenderer : public MobRenderer -{ +class GhastRenderer : public MobRenderer { public: - GhastRenderer(); + GhastRenderer(); protected: - virtual void scale(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp index 8bbd3d2fd..7e6035b0d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp @@ -1,12 +1,11 @@ #include "../../Platform/stdafx.h" -#include "GiantMobRenderer.h" +#include "GiantMobRenderer.h" -GiantMobRenderer::GiantMobRenderer(Model *model, float shadow, float _scale) : MobRenderer(model, shadow *_scale) -{ - this->_scale = _scale; +GiantMobRenderer::GiantMobRenderer(Model* model, float shadow, float _scale) + : MobRenderer(model, shadow * _scale) { + this->_scale = _scale; } -void GiantMobRenderer::scale(std::shared_ptr mob, float a) -{ - glScalef(_scale, _scale, _scale); +void GiantMobRenderer::scale(std::shared_ptr mob, float a) { + glScalef(_scale, _scale, _scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h index c40708631..872592147 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h @@ -1,14 +1,13 @@ #pragma once #include "MobRenderer.h" -class GiantMobRenderer : public MobRenderer -{ +class GiantMobRenderer : public MobRenderer { private: - float _scale; + float _scale; public: - GiantMobRenderer(Model *model, float shadow, float scale); + GiantMobRenderer(Model* model, float shadow, float scale); protected: - virtual void scale(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp index f5c357940..2b9406c30 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp @@ -10,121 +10,115 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Headers/net.minecraft.h" -void HumanoidMobRenderer::_init(HumanoidModel *humanoidModel, float scale) -{ - this->humanoidModel = humanoidModel; - this->_scale = scale; - armorParts1 = NULL; - armorParts2 = NULL; +void HumanoidMobRenderer::_init(HumanoidModel* humanoidModel, float scale) { + this->humanoidModel = humanoidModel; + this->_scale = scale; + armorParts1 = NULL; + armorParts2 = NULL; } -HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow) : MobRenderer(humanoidModel, shadow) -{ - _init(humanoidModel, 1.0f); +HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel* humanoidModel, + float shadow) + : MobRenderer(humanoidModel, shadow) { + _init(humanoidModel, 1.0f); } -HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow, float scale) : MobRenderer(humanoidModel, shadow) -{ - _init(humanoidModel, scale); +HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel* humanoidModel, + float shadow, float scale) + : MobRenderer(humanoidModel, shadow) { + _init(humanoidModel, scale); - createArmorParts(); + createArmorParts(); } -void HumanoidMobRenderer::createArmorParts() -{ - armorParts1 = new HumanoidModel(1.0f); - armorParts2 = new HumanoidModel(0.5f); +void HumanoidMobRenderer::createArmorParts() { + armorParts1 = new HumanoidModel(1.0f); + armorParts2 = new HumanoidModel(0.5f); } -void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, float a) -{ - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : mob->getBrightness(a); - glColor3f(brightness, brightness, brightness); +void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, + float a) { + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1 : mob->getBrightness(a); + glColor3f(brightness, brightness, brightness); std::shared_ptr item = mob->getCarriedItem(); - std::shared_ptr headGear = mob->getArmor(3); + std::shared_ptr headGear = mob->getArmor(3); - if (headGear != NULL) - { - // don't render the pumpkin of skulls for the skins with that disabled - // 4J-PB - need to disable rendering armour/skulls/pumpkins for some special skins (Daleks) + if (headGear != NULL) { + // don't render the pumpkin of skulls for the skins with that disabled + // 4J-PB - need to disable rendering armour/skulls/pumpkins for some + // special skins (Daleks) - if((mob->getAnimOverrideBitmask()&(1<head->translateTo(1 / 16.0f); + if ((mob->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_DontRenderArmour)) == 0) { + glPushMatrix(); + humanoidModel->head->translateTo(1 / 16.0f); - if (headGear->getItem()->id < 256) - { - if (Tile::tiles[headGear->id] != NULL && TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, -s); - } + if (headGear->getItem()->id < 256) { + if (Tile::tiles[headGear->id] != NULL && + TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, -s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); - } - else if (headGear->getItem()->id == Item::skull_Id) - { - float s = 17 / 16.0f; - glScalef(s, -s, -s); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); + } else if (headGear->getItem()->id == Item::skull_Id) { + float s = 17 / 16.0f; + glScalef(s, -s, -s); - std::wstring extra = L""; - if (headGear->hasTag() && headGear->getTag()->contains(L"SkullOwner")) - { - extra = headGear->getTag()->getString(L"SkullOwner"); - } - SkullTileRenderer::instance->renderSkull(-0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), extra); - } + std::wstring extra = L""; + if (headGear->hasTag() && + headGear->getTag()->contains(L"SkullOwner")) { + extra = headGear->getTag()->getString(L"SkullOwner"); + } + SkullTileRenderer::instance->renderSkull( + -0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), + extra); + } - glPopMatrix(); - } - } + glPopMatrix(); + } + } - if (item != NULL) - { + if (item != NULL) { glPushMatrix(); - if (model->young) - { - float s = 0.5f; - glTranslatef(0 / 16.0f, 10 / 16.0f, 0 / 16.0f); - glRotatef(-20, -1, 0, 0); - glScalef(s, s, s); - } + if (model->young) { + float s = 0.5f; + glTranslatef(0 / 16.0f, 10 / 16.0f, 0 / 16.0f); + glRotatef(-20, -1, 0, 0); + glScalef(s, s, s); + } humanoidModel->arm0->translateTo(1 / 16.0f); glTranslatef(-1 / 16.0f, 7 / 16.0f, 1 / 16.0f); - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) - { + if (item->id < 256 && + TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { float s = 8 / 16.0f; glTranslatef(-0 / 16.0f, 3 / 16.0f, -5 / 16.0f); s *= 0.75f; glRotatef(20, 1, 0, 0); glRotatef(45, 0, 1, 0); glScalef(-s, -s, s); - } - else if (item->id == Item::bow_Id) - { - float s = 10 / 16.0f; - glTranslatef(0/16.0f, 2 / 16.0f, 5 / 16.0f); - glRotatef(-20, 0, 1, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else if (Item::items[item->id]->isHandEquipped()) - { + } else if (item->id == Item::bow_Id) { + float s = 10 / 16.0f; + glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); + glRotatef(-20, 0, 1, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else if (Item::items[item->id]->isHandEquipped()) { float s = 10 / 16.0f; glTranslatef(0, 3 / 16.0f, 0); glScalef(s, -s, s); glRotatef(-100, 1, 0, 0); glRotatef(45, 0, 1, 0); - } - else - { + } else { float s = 6 / 16.0f; glTranslatef(+4 / 16.0f, +3 / 16.0f, -3 / 16.0f); glScalef(s, s, s); @@ -133,18 +127,17 @@ void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, float a) glRotatef(20, 0, 0, 1); } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 0); - if (item->getItem()->hasMultipleSpriteLayers()) - { - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 1); - } - + this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, + 0); + if (item->getItem()->hasMultipleSpriteLayers()) { + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, 1); + } + glPopMatrix(); } - } -void HumanoidMobRenderer::scale(std::shared_ptr mob, float a) -{ - glScalef(_scale, _scale, _scale); +void HumanoidMobRenderer::scale(std::shared_ptr mob, float a) { + glScalef(_scale, _scale, _scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h index 76c9169b5..42488e2d9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h @@ -3,20 +3,22 @@ class HumanoidModel; class Giant; -class HumanoidMobRenderer : public MobRenderer -{ +class HumanoidMobRenderer : public MobRenderer { protected: - HumanoidModel *humanoidModel; - float _scale; - HumanoidModel *armorParts1; - HumanoidModel *armorParts2; + HumanoidModel* humanoidModel; + float _scale; + HumanoidModel* armorParts1; + HumanoidModel* armorParts2; + + void _init(HumanoidModel* humanoidModel, float scale); - void _init(HumanoidModel *humanoidModel, float scale); public: - HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow); - HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow, float scale); + HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow); + HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow, + float scale); + protected: - virtual void createArmorParts(); - virtual void additionalRendering(std::shared_ptr mob, float a); - void scale(std::shared_ptr mob, float a); + virtual void createArmorParts(); + virtual void additionalRendering(std::shared_ptr mob, float a); + void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp index fb077f206..d9846a6a0 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp @@ -2,7 +2,7 @@ #include "ItemRenderer.h" #include "TileRenderer.h" #include "EntityRenderDispatcher.h" -//#include "ItemFrame" +// #include "ItemFrame" #include "ItemFrameRenderer.h" #include "../../../Minecraft.World/Util/JavaMath.h" @@ -18,167 +18,175 @@ #include "../../Textures/CompassTexture.h" #include "../Minimap.h" -void ItemFrameRenderer::registerTerrainTextures(IconRegister *iconRegister) -{ - backTexture = iconRegister->registerIcon(L"itemframe_back"); +void ItemFrameRenderer::registerTerrainTextures(IconRegister* iconRegister) { + backTexture = iconRegister->registerIcon(L"itemframe_back"); } -void ItemFrameRenderer::render(std::shared_ptr _itemframe, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type EnderCrystal rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr itemFrame = std::dynamic_pointer_cast(_itemframe); +void ItemFrameRenderer::render(std::shared_ptr _itemframe, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type EnderCrystal rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr itemFrame = + std::dynamic_pointer_cast(_itemframe); - glPushMatrix(); - float xOffs = (float) (itemFrame->x - x) - 0.5f; - float yOffs = (float) (itemFrame->y - y) - 0.5f; - float zOffs = (float) (itemFrame->z - z) - 0.5f; + glPushMatrix(); + float xOffs = (float)(itemFrame->x - x) - 0.5f; + float yOffs = (float)(itemFrame->y - y) - 0.5f; + float zOffs = (float)(itemFrame->z - z) - 0.5f; - int xt = itemFrame->xTile + Direction::STEP_X[itemFrame->dir]; - int yt = itemFrame->yTile; - int zt = itemFrame->zTile + Direction::STEP_Z[itemFrame->dir]; + int xt = itemFrame->xTile + Direction::STEP_X[itemFrame->dir]; + int yt = itemFrame->yTile; + int zt = itemFrame->zTile + Direction::STEP_Z[itemFrame->dir]; - glTranslatef((float) xt - xOffs, (float) yt - yOffs, (float) zt - zOffs); + glTranslatef((float)xt - xOffs, (float)yt - yOffs, (float)zt - zOffs); - drawFrame(itemFrame); - drawItem(itemFrame); + drawFrame(itemFrame); + drawItem(itemFrame); - glPopMatrix(); + glPopMatrix(); } +void ItemFrameRenderer::drawFrame(std::shared_ptr itemFrame) { + Minecraft* pMinecraft = Minecraft::GetInstance(); -void ItemFrameRenderer::drawFrame(std::shared_ptr itemFrame) -{ - Minecraft *pMinecraft=Minecraft::GetInstance(); + glPushMatrix(); + entityRenderDispatcher->textures->bindTexture(TN_TERRAIN); + glRotatef(itemFrame->yRot, 0, 1, 0); - glPushMatrix(); - entityRenderDispatcher->textures->bindTexture(TN_TERRAIN); - glRotatef(itemFrame->yRot, 0, 1, 0); + Tile* wood = Tile::wood; + float depth = 1.0f / 16.0f; + float width = 12.0f / 16.0f; + float widthHalf = width / 2.0f; - Tile *wood = Tile::wood; - float depth = 1.0f / 16.0f; - float width = 12.0f / 16.0f; - float widthHalf = width / 2.0f; + // Back + glPushMatrix(); - // Back - glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf + 1.0f / 16.0f, + 0.5f - widthHalf + 1.0f / 16.0f, depth * .5f, + 0.5f + widthHalf - 1.0f / 16.0f, + 0.5f + widthHalf - 1.0f / 16.0f); + tileRenderer->setFixedTexture(backTexture); + tileRenderer->renderTile(wood, 0, 1); + tileRenderer->clearFixedTexture(); + tileRenderer->clearFixedShape(); + glPopMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf + 1.0f / 16.0f, 0.5f - widthHalf + 1.0f / 16.0f, depth * .5f, 0.5f + widthHalf - 1.0f / 16.0f, 0.5f + widthHalf - 1.0f / 16.0f); - tileRenderer->setFixedTexture(backTexture); - tileRenderer->renderTile(wood, 0, 1); - tileRenderer->clearFixedTexture(); - tileRenderer->clearFixedShape(); - glPopMatrix(); + tileRenderer->setFixedTexture( + Tile::wood->getTexture(Facing::UP, TreeTile::BIRCH_TRUNK)); - tileRenderer->setFixedTexture(Tile::wood->getTexture(Facing::UP, TreeTile::BIRCH_TRUNK)); + // Bottom + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, + depth + 0.0001f, depth + 0.5f - widthHalf, + 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Bottom - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth + 0.0001f, depth + 0.5f - widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Top + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f + widthHalf - depth, 0.5f - widthHalf, + depth + 0.0001f, 0.5f + widthHalf, + 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Top - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f + widthHalf - depth, 0.5f - widthHalf, depth + 0.0001f, 0.5f + widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Right + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth, + 0.5f + widthHalf, depth + 0.5f - widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Right - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth, 0.5f + widthHalf, depth + 0.5f - widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Left + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f + widthHalf - depth, + depth, 0.5f + widthHalf, 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Left - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f + widthHalf - depth, depth, 0.5f + widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + tileRenderer->clearFixedShape(); + tileRenderer->clearFixedTexture(); - tileRenderer->clearFixedShape(); - tileRenderer->clearFixedTexture(); - - glPopMatrix(); + glPopMatrix(); } -void ItemFrameRenderer::drawItem(std::shared_ptr entity) -{ - Minecraft *pMinecraft=Minecraft::GetInstance(); +void ItemFrameRenderer::drawItem(std::shared_ptr entity) { + Minecraft* pMinecraft = Minecraft::GetInstance(); - std::shared_ptr instance = entity->getItem(); - if (instance == NULL) return; + std::shared_ptr instance = entity->getItem(); + if (instance == NULL) return; - std::shared_ptr itemEntity = std::shared_ptr(new ItemEntity(entity->level, 0, 0, 0, instance)); - itemEntity->getItem()->count = 1; - itemEntity->bobOffs = 0; + std::shared_ptr itemEntity = std::shared_ptr( + new ItemEntity(entity->level, 0, 0, 0, instance)); + itemEntity->getItem()->count = 1; + itemEntity->bobOffs = 0; - glPushMatrix(); + glPushMatrix(); - glTranslatef((-7.25f / 16.0f) * Direction::STEP_X[entity->dir], -0.18f, (-7.25f / 16.0f) * Direction::STEP_Z[entity->dir]); - glRotatef(180 + entity->yRot, 0, 1, 0); - glRotatef(-90 * entity->getRotation(), 0, 0, 1); + glTranslatef((-7.25f / 16.0f) * Direction::STEP_X[entity->dir], -0.18f, + (-7.25f / 16.0f) * Direction::STEP_Z[entity->dir]); + glRotatef(180 + entity->yRot, 0, 1, 0); + glRotatef(-90 * entity->getRotation(), 0, 0, 1); - switch (entity->getRotation()) - { - case 1: - glTranslatef(-0.16f, -0.16f, 0); - break; - case 2: - glTranslatef(0, -0.32f, 0); - break; - case 3: - glTranslatef(0.16f, -0.16f, 0); - break; - } + switch (entity->getRotation()) { + case 1: + glTranslatef(-0.16f, -0.16f, 0); + break; + case 2: + glTranslatef(0, -0.32f, 0); + break; + case 3: + glTranslatef(0.16f, -0.16f, 0); + break; + } - if (itemEntity->getItem()->getItem() == Item::map) - { - entityRenderDispatcher->textures->bindTexture(TN_MISC_MAPBG); - Tesselator *t = Tesselator::getInstance(); + if (itemEntity->getItem()->getItem() == Item::map) { + entityRenderDispatcher->textures->bindTexture(TN_MISC_MAPBG); + Tesselator* t = Tesselator::getInstance(); - glRotatef(180, 0, 1, 0); - glRotatef(180, 0, 0, 1); - glScalef(1.0f / 256.0f, 1.0f / 256.0f, 1.0f / 256.0f); - glTranslatef(-65, -107, -3); - glNormal3f(0, 0, -1); - t->begin(); - int vo = 7; - t->vertexUV(0 - vo, 128 + vo, 0, 0, 1); - t->vertexUV(128 + vo, 128 + vo, 0, 1, 1); - t->vertexUV(128 + vo, 0 - vo, 0, 1, 0); - t->vertexUV(0 - vo, 0 - vo, 0, 0, 0); - t->end(); + glRotatef(180, 0, 1, 0); + glRotatef(180, 0, 0, 1); + glScalef(1.0f / 256.0f, 1.0f / 256.0f, 1.0f / 256.0f); + glTranslatef(-65, -107, -3); + glNormal3f(0, 0, -1); + t->begin(); + int vo = 7; + t->vertexUV(0 - vo, 128 + vo, 0, 0, 1); + t->vertexUV(128 + vo, 128 + vo, 0, 1, 1); + t->vertexUV(128 + vo, 0 - vo, 0, 1, 0); + t->vertexUV(0 - vo, 0 - vo, 0, 0, 0); + t->end(); - std::shared_ptr data = Item::map->getSavedData(itemEntity->getItem(), entity->level); - if (data != NULL) - { - entityRenderDispatcher->itemInHandRenderer->minimap->render(nullptr, entityRenderDispatcher->textures, data, entity->entityId); - } - } - else - { - if (itemEntity->getItem()->getItem() == Item::compass) - { - CompassTexture *ct = CompassTexture::instance; - double compassRot = ct->rot; - double compassRotA = ct->rota; - ct->rot = 0; - ct->rota = 0; - ct->updateFromPosition(entity->level, entity->x, entity->z, Mth::wrapDegrees( (float)(180 + entity->dir * 90) ), false, true); - ct->rot = compassRot; - ct->rota = compassRotA; - } + std::shared_ptr data = + Item::map->getSavedData(itemEntity->getItem(), entity->level); + if (data != NULL) { + entityRenderDispatcher->itemInHandRenderer->minimap->render( + nullptr, entityRenderDispatcher->textures, data, + entity->entityId); + } + } else { + if (itemEntity->getItem()->getItem() == Item::compass) { + CompassTexture* ct = CompassTexture::instance; + double compassRot = ct->rot; + double compassRotA = ct->rota; + ct->rot = 0; + ct->rota = 0; + ct->updateFromPosition( + entity->level, entity->x, entity->z, + Mth::wrapDegrees((float)(180 + entity->dir * 90)), false, true); + ct->rot = compassRot; + ct->rota = compassRotA; + } - EntityRenderDispatcher::instance->render(itemEntity, 0, 0, 0, 0, 0, true); + EntityRenderDispatcher::instance->render(itemEntity, 0, 0, 0, 0, 0, + true); - if (itemEntity->getItem()->getItem() == Item::compass) - { - CompassTexture *ct = CompassTexture::instance; - ct->cycleFrames(); - } - } - - glPopMatrix(); + if (itemEntity->getItem()->getItem() == Item::compass) { + CompassTexture* ct = CompassTexture::instance; + ct->cycleFrames(); + } + } + + glPopMatrix(); } - diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h index 263344138..12626a614 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h @@ -1,17 +1,17 @@ #pragma once #include "EntityRenderer.h" -class ItemFrameRenderer : public EntityRenderer -{ +class ItemFrameRenderer : public EntityRenderer { private: - Icon *backTexture; + Icon* backTexture; - //@Override + //@Override public: - void registerTerrainTextures(IconRegister *iconRegister); - virtual void render(std::shared_ptr _itemframe, double x, double y, double z, float rot, float a); + void registerTerrainTextures(IconRegister* iconRegister); + virtual void render(std::shared_ptr _itemframe, double x, double y, + double z, float rot, float a); private: - void drawFrame(std::shared_ptr itemFrame); - void drawItem(std::shared_ptr entity); + void drawFrame(std::shared_ptr itemFrame); + void drawItem(std::shared_ptr entity); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp index bdefd3748..92e3fa52d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp @@ -20,151 +20,153 @@ int ItemInHandRenderer::list = -1; int ItemInHandRenderer::listGlint = -1; -ItemInHandRenderer::ItemInHandRenderer(Minecraft *mc, bool optimisedMinimap) -{ - // 4J - added - height = 0; - oHeight = 0; - selectedItem = nullptr; - tileRenderer = new TileRenderer(); - lastSlot = -1; +ItemInHandRenderer::ItemInHandRenderer(Minecraft* mc, bool optimisedMinimap) { + // 4J - added + height = 0; + oHeight = 0; + selectedItem = nullptr; + tileRenderer = new TileRenderer(); + lastSlot = -1; this->mc = mc; - minimap = new Minimap(mc->font, mc->options, mc->textures, optimisedMinimap); + minimap = + new Minimap(mc->font, mc->options, mc->textures, optimisedMinimap); - // 4J - replaced mesh that is used to render held items with individual cubes, so we can make it all join up properly without seams. This - // has a lot more quads in it than the original, so is now precompiled with a UV matrix offset to put it in the final place for the - // current icon. Compile it on demand for the first ItemInHandRenderer (list is static) - if( list == -1 ) - { - list = MemoryTracker::genLists(1); - float dd = 1 / 16.0f; + // 4J - replaced mesh that is used to render held items with individual + // cubes, so we can make it all join up properly without seams. This has a + // lot more quads in it than the original, so is now precompiled with a UV + // matrix offset to put it in the final place for the current icon. Compile + // it on demand for the first ItemInHandRenderer (list is static) + if (list == -1) { + list = MemoryTracker::genLists(1); + float dd = 1 / 16.0f; - glNewList(list, GL_COMPILE); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for( int yp = 0; yp < 16; yp++ ) - for( int xp = 0; xp < 16; xp++ ) - { - float u = (15-xp) / 256.0f; - float v = (15-yp) / 256.0f; - u += 0.5f / 256.0f; - v += 0.5f / 256.0f; - float x0 = xp / 16.0f; - float x1 = x0 + 1.0f/16.0f; - float y0 = yp / 16.0f; - float y1 = y0 + 1.0f/16.0f; - float z0 = 0.0f; - float z1 = -dd; + glNewList(list, GL_COMPILE); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int yp = 0; yp < 16; yp++) + for (int xp = 0; xp < 16; xp++) { + float u = (15 - xp) / 256.0f; + float v = (15 - yp) / 256.0f; + u += 0.5f / 256.0f; + v += 0.5f / 256.0f; + float x0 = xp / 16.0f; + float x1 = x0 + 1.0f / 16.0f; + float y0 = yp / 16.0f; + float y1 = y0 + 1.0f / 16.0f; + float z0 = 0.0f; + float z1 = -dd; - t->normal(0, 0, 1); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x1, y1, z0, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->normal(0, 0, -1); - t->vertexUV(x0, y1, z1, u, v); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->vertexUV(x0, y0, z1, u, v); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u, v); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->vertexUV(x0, y1, z1, u, v); - t->normal(1, 0, 0); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x1, y1, z0, u, v); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->normal(0, 1, 0); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x0, y0, z1, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->normal(0, -1, 0); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x0, y1, z1, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->vertexUV(x1, y1, z0, u, v); - } - t->end(); - glEndList(); - } + t->normal(0, 0, 1); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->normal(0, 0, -1); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x0, y0, z1, u, v); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->normal(1, 0, 0); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->normal(0, 1, 0); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->normal(0, -1, 0); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + } + t->end(); + glEndList(); + } - // Also create special object for glint overlays - this is the same as the previous one, with a different UV scalings, and depth test set to equal - if( listGlint == -1 ) - { - listGlint = MemoryTracker::genLists(1); - float dd = 1 / 16.0f; + // Also create special object for glint overlays - this is the same as the + // previous one, with a different UV scalings, and depth test set to equal + if (listGlint == -1) { + listGlint = MemoryTracker::genLists(1); + float dd = 1 / 16.0f; - glNewList(listGlint, GL_COMPILE); - glDepthFunc(GL_EQUAL); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for( int yp = 0; yp < 16; yp++ ) - for( int xp = 0; xp < 16; xp++ ) - { - float u0 = (15-xp) / 16.0f; - float v0 = (15-yp) / 16.0f; - float u1 = u0 - (1.0f/16.0f); - float v1 = v0 - (1.0f/16.0f);; + glNewList(listGlint, GL_COMPILE); + glDepthFunc(GL_EQUAL); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int yp = 0; yp < 16; yp++) + for (int xp = 0; xp < 16; xp++) { + float u0 = (15 - xp) / 16.0f; + float v0 = (15 - yp) / 16.0f; + float u1 = u0 - (1.0f / 16.0f); + float v1 = v0 - (1.0f / 16.0f); + ; - float x0 = xp / 16.0f; - float x1 = x0 + 1.0f/16.0f; - float y0 = yp / 16.0f; - float y1 = y0 + 1.0f/16.0f; - float z0 = 0.0f; - float z1 = -dd; + float x0 = xp / 16.0f; + float x1 = x0 + 1.0f / 16.0f; + float y0 = yp / 16.0f; + float y1 = y0 + 1.0f / 16.0f; + float z0 = 0.0f; + float z1 = -dd; - float br = 0.76f; - t->color(0.5f * br, 0.25f * br, 0.8f * br, 1.0f); // MGH - added the color here, as the glColour below wasn't making it through to render - - t->normal(0, 0, 1); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y1, z0, u1, v1); - t->vertexUV(x0, y1, z0, u0, v1); - t->normal(0, 0, -1); - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y0, z1, u1, v0); - t->vertexUV(x0, y0, z1, u0, v0); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u0, v0); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x0, y1, z0, u0, v1); - t->vertexUV(x0, y1, z1, u0, v1); - t->normal(1, 0, 0); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y1, z0, u1, v1); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y0, z1, u1, v0); - t->normal(0, 1, 0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x0, y0, z1, u0, v0); - t->vertexUV(x1, y0, z1, u1, v0); - t->normal(0, -1, 0); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x0, y1, z0, u0, v1); - t->vertexUV(x1, y1, z0, u1, v1); - } - t->end(); - glDepthFunc(GL_LEQUAL); - glEndList(); - } + float br = 0.76f; + t->color(0.5f * br, 0.25f * br, 0.8f * br, + 1.0f); // MGH - added the color here, as the glColour + // below wasn't making it through to render + t->normal(0, 0, 1); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y1, z0, u1, v1); + t->vertexUV(x0, y1, z0, u0, v1); + t->normal(0, 0, -1); + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y0, z1, u1, v0); + t->vertexUV(x0, y0, z1, u0, v0); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u0, v0); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x0, y1, z0, u0, v1); + t->vertexUV(x0, y1, z1, u0, v1); + t->normal(1, 0, 0); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y1, z0, u1, v1); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v0); + t->normal(0, 1, 0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x0, y0, z1, u0, v0); + t->vertexUV(x1, y0, z1, u1, v0); + t->normal(0, -1, 0); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x0, y1, z0, u0, v1); + t->vertexUV(x1, y1, z0, u1, v1); + } + t->end(); + glDepthFunc(GL_LEQUAL); + glEndList(); + } } -void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptr item, int layer, bool setColor/* = true*/) -{ - // 4J - code borrowed from render method below, although not factoring in brightness as that should already be being taken into account - // by texture lighting. This is for colourising things held in 3rd person view. - if ( (setColor) && (item != NULL) ) - { - int col = Item::items[item->id]->getColor(item,0); +void ItemInHandRenderer::renderItem(std::shared_ptr mob, + std::shared_ptr item, + int layer, bool setColor /* = true*/) { + // 4J - code borrowed from render method below, although not factoring in + // brightness as that should already be being taken into account by texture + // lighting. This is for colourising things held in 3rd person view. + if ((setColor) && (item != NULL)) { + int col = Item::items[item->id]->getColor(item, 0); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; @@ -173,57 +175,57 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptrid]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) - { - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - tileRenderer->renderTile(tile, item->getAuxValue(), SharedConstants::TEXTURE_LIGHTING ? 1.0f : mob->getBrightness(1)); // 4J - change brought forward from 1.8.2 - } - else - { - MemSect(31); - Icon *icon = mob->getItemInHandIcon(item, layer); - if (icon == NULL) - { - glPopMatrix(); - MemSect(0); - return; - } - - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + Tile* tile = Tile::tiles[item->id]; + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && + TileRenderer::canRender(tile->getRenderShape())) { + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + tileRenderer->renderTile( + tile, item->getAuxValue(), + SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : mob->getBrightness( + 1)); // 4J - change brought forward from 1.8.2 + } else { + MemSect(31); + Icon* icon = mob->getItemInHandIcon(item, layer); + if (icon == NULL) { + glPopMatrix(); + MemSect(0); + return; } - else - { - mc->textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + + if (item->getIconType() == Icon::TYPE_TERRAIN) { + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else { + mc->textures->bindTexture( + TN_GUI_ITEMS); // 4J was L"/gui/items.png" } - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(0); + Tesselator* t = Tesselator::getInstance(); - // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. - int iconWidth = icon->getWidth(); - int LOD = -1; // Default to not doing anything special with LOD forcing - if( iconWidth == 32 ) - { - LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 map - } - else if( iconWidth == 64 ) - { - LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 map - } - RenderManager.StateSetForceLOD(LOD); + // Consider forcing the mipmap LOD level to use, if this is to be + // rendered from a larger than standard source texture. + int iconWidth = icon->getWidth(); + int LOD = -1; // Default to not doing anything special with LOD forcing + if (iconWidth == 32) { + LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 + // map + } else if (iconWidth == 64) { + LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 + // map + } + RenderManager.StateSetForceLOD(LOD); - // 4J Original comment - // Yes, these are backwards. - // No, I don't know why. - // 4J Stu - Make them the right way round...u coords were swapped - float u0 = icon->getU0(); - float u1 = icon->getU1(); - float v0 = icon->getV0(); - float v1 = icon->getV1(); + // 4J Original comment + // Yes, these are backwards. + // No, I don't know why. + // 4J Stu - Make them the right way round...u coords were swapped + float u0 = icon->getU0(); + float u1 = icon->getU1(); + float v0 = icon->getV0(); + float v1 = icon->getV1(); float xo = 0.0f; float yo = 0.3f; @@ -238,30 +240,35 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptrgetSourceWidth(), icon->getSourceHeight(), 1 / 16.0f, false); + renderItem3D(t, u0, v0, u1, v1, icon->getSourceWidth(), + icon->getSourceHeight(), 1 / 16.0f, false); - if (item != NULL && item->isFoil() && layer == 0) - { + if (item != NULL && item->isFoil() && layer == 0) { glDepthFunc(GL_EQUAL); glDisable(GL_LIGHTING); - mc->textures->bind(mc->textures->loadTexture(TN__BLUR__MISC_GLINT)); // 4J was L"%blur%/misc/glint.png" + mc->textures->bind(mc->textures->loadTexture( + TN__BLUR__MISC_GLINT)); // 4J was L"%blur%/misc/glint.png" glEnable(GL_BLEND); glBlendFunc(GL_SRC_COLOR, GL_ONE); float br = 0.76f; - glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); // MGH - for some reason this colour isn't making it through to the render, so I've added to the tesselator for the glint geom above - glMatrixMode(GL_TEXTURE); - glPushMatrix(); - float ss = 1 / 8.0f; - glScalef(ss, ss, ss); - float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; - glTranslatef(sx, 0, 0); - glRotatef(-50, 0, 0, 1); + glColor4f(0.5f * br, 0.25f * br, 0.8f * br, + 1); // MGH - for some reason this colour isn't making it + // through to the render, so I've added to the + // tesselator for the glint geom above + glMatrixMode(GL_TEXTURE); + glPushMatrix(); + float ss = 1 / 8.0f; + glScalef(ss, ss, ss); + float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; + glTranslatef(sx, 0, 0); + glRotatef(-50, 0, 0, 1); renderItem3D(t, 0, 0, 1, 1, 256, 256, 1 / 16.0f, true); glPopMatrix(); glPushMatrix(); glScalef(ss, ss, ss); - sx = System::currentTimeMillis() % (3000 + 1873) / (3000 + 1873.0f) * 8; + sx = System::currentTimeMillis() % (3000 + 1873) / + (3000 + 1873.0f) * 8; glTranslatef(-sx, 0, 0); glRotatef(10, 0, 0, 1); renderItem3D(t, 0, 0, 1, 1, 256, 256, 1 / 16.0f, true); @@ -272,7 +279,7 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptr mob, std::shared_ptrplayer || !mc->level) return; @@ -318,26 +325,28 @@ void ItemInHandRenderer::render(float a) float h = oHeight + (height - oHeight) * a; std::shared_ptr player = mc->player; - // 4J - added so we can adjust the position of the hands for horizontal & vertical split screens - float fudgeX = 0.0f; - float fudgeY = 0.0f; - float fudgeZ = 0.0f; - bool splitHoriz = false; - std::shared_ptr localPlayer = std::dynamic_pointer_cast(player); - if( localPlayer ) - { - if( localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM || - localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP ) - { - fudgeY = 0.08f; - splitHoriz = true; - } - else if( localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || - localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT ) - { - fudgeX = -0.18f; - } - } + // 4J - added so we can adjust the position of the hands for horizontal & + // vertical split screens + float fudgeX = 0.0f; + float fudgeY = 0.0f; + float fudgeZ = 0.0f; + bool splitHoriz = false; + std::shared_ptr localPlayer = + std::dynamic_pointer_cast(player); + if (localPlayer) { + if (localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM || + localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_TOP) { + fudgeY = 0.08f; + splitHoriz = true; + } else if (localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || + localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT) { + fudgeX = -0.18f; + } + } float xr = player->xRotO + (player->xRot - player->xRotO) * a; @@ -347,60 +356,61 @@ void ItemInHandRenderer::render(float a) Lighting::turnOn(); glPopMatrix(); - if (localPlayer) - { - float xrr = localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; - float yrr = localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; - // 4J - was using player->xRot and yRot directly here rather than interpolating between old & current with a - float yr = player->yRotO + (player->yRot - player->yRotO) * a; + if (localPlayer) { + float xrr = + localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; + float yrr = + localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; + // 4J - was using player->xRot and yRot directly here rather than + // interpolating between old & current with a + float yr = player->yRotO + (player->yRot - player->yRotO) * a; glRotatef((xr - xrr) * 0.1f, 1, 0, 0); glRotatef((yr - yrr) * 0.1f, 0, 1, 0); } std::shared_ptr item = selectedItem; - float br = mc->level->getBrightness(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // 4J - change brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { + float br = mc->level->getBrightness( + Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { br = 1; - int col = mc->level->getLightColor(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z), 0); + int col = mc->level->getLightColor(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z), 0); int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); } - if (item != NULL) - { - int col = Item::items[item->id]->getColor(item,0); + if (item != NULL) { + int col = Item::items[item->id]->getColor(item, 0); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; glColor4f(br * red, br * g, br * b, 1); + } else { + glColor4f(br, br, br, 1); } - else - { - glColor4f(br, br, br, 1); - } - if (item != NULL && item->id == Item::map->id) - { + if (item != NULL && item->id == Item::map->id) { glPushMatrix(); float d = 0.8f; - // 4J - move the map away a bit if we're in horizontal split screen, so it doesn't clip out of the save zone - if( splitHoriz ) - { - glTranslatef(0.0f, 0.0f, -0.3f ); - } + // 4J - move the map away a bit if we're in horizontal split screen, so + // it doesn't clip out of the save zone + if (splitHoriz) { + glTranslatef(0.0f, 0.0f, -0.3f); + } { float swing = player->getAttackAnim(a); float swing1 = Mth::sin(swing * PI); float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, -swing1 * 0.2f); + glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, + -swing1 * 0.2f); } float tilt = 1 - xr / 45.0f + 0.1f; @@ -408,20 +418,23 @@ void ItemInHandRenderer::render(float a) if (tilt > 1) tilt = 1; tilt = -Mth::cos(tilt * PI) * 0.5f + 0.5f; - glTranslatef(0.0f, 0.0f * d - (1 - h) * 1.2f - tilt * 0.5f + 0.04f, -0.9f * d); + glTranslatef(0.0f, 0.0f * d - (1 - h) * 1.2f - tilt * 0.5f + 0.04f, + -0.9f * d); glRotatef(90, 0, 1, 0); glRotatef((tilt) * -85, 0, 0, 1); glEnable(GL_RESCALE_NORMAL); - { - // 4J-PB - if we've got a player texture, use that - //glBindTexture(GL_TEXTURE_2D, mc->textures->loadHttpTexture(mc->player->customTextureUrl, mc->player->getTexture())); - glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture(mc->player->customTextureUrl, mc->player->getTexture())); - mc->textures->clearLastBoundId(); - for (int i = 0; i < 2; i++) - { + // 4J-PB - if we've got a player texture, use that + // glBindTexture(GL_TEXTURE_2D, + // mc->textures->loadHttpTexture(mc->player->customTextureUrl, + // mc->player->getTexture())); + glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture( + mc->player->customTextureUrl, + mc->player->getTexture())); + mc->textures->clearLastBoundId(); + for (int i = 0; i < 2; i++) { int flip = i * 2 - 1; glPushMatrix(); @@ -431,17 +444,21 @@ void ItemInHandRenderer::render(float a) glRotatef(59, 0, 0, 1); glRotatef((float)(-65 * flip), 0, 1, 0); - EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(mc->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + EntityRenderer* er = + EntityRenderDispatcher::instance->getRenderer(mc->player); + PlayerRenderer* playerRenderer = (PlayerRenderer*)er; float ss = 1; glScalef(ss, ss, ss); - // Can't turn off the hand if the player is holding a map - std::shared_ptr itemInstance = player->inventory->getSelected(); - if ((itemInstance && (itemInstance->getItem()->id==Item::map_Id)) || app.GetGameSettings(localPlayer->GetXboxPad(),eGameSetting_DisplayHand)!=0 ) - { - playerRenderer->renderHand(); - } + // Can't turn off the hand if the player is holding a map + std::shared_ptr itemInstance = + player->inventory->getSelected(); + if ((itemInstance && + (itemInstance->getItem()->id == Item::map_Id)) || + app.GetGameSettings(localPlayer->GetXboxPad(), + eGameSetting_DisplayHand) != 0) { + playerRenderer->renderHand(); + } glPopMatrix(); } } @@ -466,43 +483,48 @@ void ItemInHandRenderer::render(float a) float s = 2 / 128.0f; glScalef(s, s, s); - MemSect(31); - mc->textures->bindTexture(TN_MISC_MAPBG); // 4J was L"/misc/mapbg.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + mc->textures->bindTexture(TN_MISC_MAPBG); // 4J was L"/misc/mapbg.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); -// glNormal3f(0, 0, -1); // 4J - changed to use tesselator + // glNormal3f(0, 0, -1); // 4J - changed to use tesselator t->begin(); - int vo = 7; - t->normal(0,0,-1); - t->vertexUV((float)(0 - vo), (float)( 128 + vo), (float)( 0), (float)( 0), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 128 + vo), (float)( 0), (float)( 1), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 0 - vo), (float)( 0), (float)( 1), (float)( 0)); - t->vertexUV((float)(0 - vo), (float)( 0 - vo), (float)( 0), (float)( 0), (float)( 0)); + int vo = 7; + t->normal(0, 0, -1); + t->vertexUV((float)(0 - vo), (float)(128 + vo), (float)(0), (float)(0), + (float)(1)); + t->vertexUV((float)(128 + vo), (float)(128 + vo), (float)(0), + (float)(1), (float)(1)); + t->vertexUV((float)(128 + vo), (float)(0 - vo), (float)(0), (float)(1), + (float)(0)); + t->vertexUV((float)(0 - vo), (float)(0 - vo), (float)(0), (float)(0), + (float)(0)); t->end(); - std::shared_ptr data = Item::map->getSavedData(item, mc->level); - PIXBeginNamedEvent(0,"Minimap render"); - if(data != NULL) minimap->render(mc->player, mc->textures, data, mc->player->entityId); - PIXEndNamedEvent(); + std::shared_ptr data = + Item::map->getSavedData(item, mc->level); + PIXBeginNamedEvent(0, "Minimap render"); + if (data != NULL) + minimap->render(mc->player, mc->textures, data, + mc->player->entityId); + PIXEndNamedEvent(); glPopMatrix(); - } - else if (item != NULL) - { + } else if (item != NULL) { glPushMatrix(); float d = 0.8f; #if defined __ORBIS__ || defined __PS3__ - static const float swingPowFactor = 1.0f; + static const float swingPowFactor = 1.0f; #else - static const float swingPowFactor = 4.0f; // 4J added, to slow the swing down when nearest the player for avoiding luminance flash issues + static const float swingPowFactor = + 4.0f; // 4J added, to slow the swing down when nearest the player + // for avoiding luminance flash issues #endif - if (player->getUseItemDuration() > 0) - { + if (player->getUseItemDuration() > 0) { UseAnim anim = item->getUseAnimation(); - if ( (anim == UseAnim_eat) || (anim == UseAnim_drink) ) - { + if ((anim == UseAnim_eat) || (anim == UseAnim_drink)) { float t = (player->getUseItemDuration() - a + 1); float swing = 1 - (t / item->getUseDuration()); @@ -511,63 +533,62 @@ void ItemInHandRenderer::render(float a) is = is * is * is; is = is * is * is; float iss = 1 - is; - glTranslatef(0, Mth::abs(Mth::cos(t / 4 * PI) * 0.1f) * (swing > 0.2 ? 1 : 0), 0); + glTranslatef(0, + Mth::abs(Mth::cos(t / 4 * PI) * 0.1f) * + (swing > 0.2 ? 1 : 0), + 0); glTranslatef(iss * 0.6f, -iss * 0.5f, 0); glRotatef(iss * 90, 0, 1, 0); glRotatef(iss * 10, 1, 0, 0); glRotatef(iss * 30, 0, 0, 1); } + } else { + float swing = powf(player->getAttackAnim(a), swingPowFactor); + + float swing1 = Mth::sin(swing * PI); + float swing2 = Mth::sin((sqrt(swing)) * PI); + glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, + -swing1 * 0.2f); } - else - { - float swing = powf(player->getAttackAnim(a),swingPowFactor); - - float swing1 = Mth::sin(swing * PI); - float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, -swing1 * 0.2f); - - } glTranslatef(0.7f * d, -0.65f * d - (1 - h) * 0.6f, -0.9f * d); - glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added + glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added glRotatef(45, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); - float swing = powf(player->getAttackAnim(a),swingPowFactor); - float swing3 = Mth::sin(swing * swing * PI); - float swing2 = Mth::sin(sqrt(swing) * PI); - glRotatef(-swing3 * 20, 0, 1, 0); - glRotatef(-swing2 * 20, 0, 0, 1); - glRotatef(-swing2 * 80, 1, 0, 0); + float swing = powf(player->getAttackAnim(a), swingPowFactor); + float swing3 = Mth::sin(swing * swing * PI); + float swing2 = Mth::sin(sqrt(swing) * PI); + glRotatef(-swing3 * 20, 0, 1, 0); + glRotatef(-swing2 * 20, 0, 0, 1); + glRotatef(-swing2 * 80, 1, 0, 0); float ss = 0.4f; glScalef(ss, ss, ss); - if (player->getUseItemDuration() > 0) - { + if (player->getUseItemDuration() > 0) { UseAnim anim = item->getUseAnimation(); - if (anim == UseAnim_block) - { + if (anim == UseAnim_block) { glTranslatef(-0.5f, 0.2f, 0.0f); glRotatef(30, 0, 1, 0); glRotatef(-80, 1, 0, 0); glRotatef(60, 0, 1, 0); - } - else if (anim == UseAnim_bow) - { - + } else if (anim == UseAnim_bow) { glRotatef(-18, 0, 0, 1); glRotatef(-12, 0, 1, 0); glRotatef(-8, 1, 0, 0); glTranslatef(-0.9f, 0.2f, 0.0f); - float timeHeld = (item->getUseDuration() - (player->getUseItemDuration() - a + 1)); - float pow = timeHeld / (float) (BowItem::MAX_DRAW_DURATION); + float timeHeld = (item->getUseDuration() - + (player->getUseItemDuration() - a + 1)); + float pow = timeHeld / (float)(BowItem::MAX_DRAW_DURATION); pow = ((pow * pow) + pow * 2) / 3; if (pow > 1) pow = 1; - if (pow > 0.1f) - { - glTranslatef(0, Mth::sin((timeHeld - 0.1f) * 1.3f) * 0.01f * (pow - 0.1f), 0); + if (pow > 0.1f) { + glTranslatef(0, + Mth::sin((timeHeld - 0.1f) * 1.3f) * 0.01f * + (pow - 0.1f), + 0); } glTranslatef(0, 0, pow * 0.1f); @@ -582,35 +603,28 @@ void ItemInHandRenderer::render(float a) } } - - if (item->getItem()->isMirroredArt()) - { + if (item->getItem()->isMirroredArt()) { glRotatef(180, 0, 1, 0); } - if (item->getItem()->hasMultipleSpriteLayers()) - { + if (item->getItem()->hasMultipleSpriteLayers()) { // special case for potions, refactor this when we get more // items that have two layers renderItem(player, item, 0, false); - int col = Item::items[item->id]->getColor(item, 1); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + int col = Item::items[item->id]->getColor(item, 1); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f(br * red, br * g, br * b, 1); + glColor4f(br * red, br * g, br * b, 1); renderItem(player, item, 1, false); - } - else - { + } else { renderItem(player, item, 0, false); } glPopMatrix(); - } - else if (!player->isInvisible()) - { + } else if (!player->isInvisible()) { glPushMatrix(); float d = 0.8f; @@ -619,11 +633,12 @@ void ItemInHandRenderer::render(float a) float swing1 = Mth::sin(swing * PI); float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.3f, Mth::sin(sqrt(swing) * PI * 2) * 0.4f, -swing1 * 0.4f); + glTranslatef(-swing2 * 0.3f, Mth::sin(sqrt(swing) * PI * 2) * 0.4f, + -swing1 * 0.4f); } glTranslatef(0.8f * d, -0.75f * d - (1 - h) * 0.6f, -0.9f * d); - glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added + glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added glRotatef(45, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); @@ -635,14 +650,18 @@ void ItemInHandRenderer::render(float a) glRotatef(-swing3 * 20, 0, 0, 1); } - // 4J-PB - if we've got a player texture, use that + // 4J-PB - if we've got a player texture, use that - //glBindTexture(GL_TEXTURE_2D, mc->textures->loadHttpTexture(mc->player->customTextureUrl, mc->player->getTexture())); + // glBindTexture(GL_TEXTURE_2D, + // mc->textures->loadHttpTexture(mc->player->customTextureUrl, + // mc->player->getTexture())); - MemSect(31); - glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture(mc->player->customTextureUrl, mc->player->getTexture())); - MemSect(0); - mc->textures->clearLastBoundId(); + MemSect(31); + glBindTexture(GL_TEXTURE_2D, + mc->textures->loadMemTexture(mc->player->customTextureUrl, + mc->player->getTexture())); + MemSect(0); + mc->textures->clearLastBoundId(); glTranslatef(-1.0f, +3.6f, +3.5f); glRotatef(120, 0, 0, 1); glRotatef(180 + 20, 1, 0, 0); @@ -650,87 +669,79 @@ void ItemInHandRenderer::render(float a) glScalef(1.5f / 24.0f * 16, 1.5f / 24.0f * 16, 1.5f / 24.0f * 16); glTranslatef(5.6f, 0, 0); - EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(mc->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + EntityRenderer* er = + EntityRenderDispatcher::instance->getRenderer(mc->player); + PlayerRenderer* playerRenderer = (PlayerRenderer*)er; float ss = 1; glScalef(ss, ss, ss); - MemSect(31); - // Can't turn off the hand if the player is holding a map - std::shared_ptr itemInstance = player->inventory->getSelected(); + MemSect(31); + // Can't turn off the hand if the player is holding a map + std::shared_ptr itemInstance = + player->inventory->getSelected(); - if ( (itemInstance && (itemInstance->getItem()->id==Item::map_Id)) || app.GetGameSettings(localPlayer->GetXboxPad(),eGameSetting_DisplayHand)!=0 ) - { - playerRenderer->renderHand(); - } - MemSect(0); + if ((itemInstance && (itemInstance->getItem()->id == Item::map_Id)) || + app.GetGameSettings(localPlayer->GetXboxPad(), + eGameSetting_DisplayHand) != 0) { + playerRenderer->renderHand(); + } + MemSect(0); glPopMatrix(); } glDisable(GL_RESCALE_NORMAL); Lighting::turnOff(); - } -void ItemInHandRenderer::renderScreenEffect(float a) -{ +void ItemInHandRenderer::renderScreenEffect(float a) { glDisable(GL_ALPHA_TEST); - if (mc->player->isOnFire()) - { - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); + if (mc->player->isOnFire()) { + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); renderFire(a); } - - if (mc->player->isInWall()) // Inside a tile + if (mc->player->isInWall()) // Inside a tile { int x = Mth::floor(mc->player->x); int y = Mth::floor(mc->player->y); int z = Mth::floor(mc->player->z); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); int tile = mc->level->getTile(x, y, z); - if (mc->level->isSolidBlockingTile(x, y, z)) - { + if (mc->level->isSolidBlockingTile(x, y, z)) { renderTex(a, Tile::tiles[tile]->getTexture(2)); - } - else - { - for (int i = 0; i < 8; i++) - { + } else { + for (int i = 0; i < 8; i++) { float xo = ((i >> 0) % 2 - 0.5f) * mc->player->bbWidth * 0.9f; float yo = ((i >> 1) % 2 - 0.5f) * mc->player->bbHeight * 0.2f; float zo = ((i >> 2) % 2 - 0.5f) * mc->player->bbWidth * 0.9f; int xt = Mth::floor(x + xo); int yt = Mth::floor(y + yo); int zt = Mth::floor(z + zo); - if (mc->level->isSolidBlockingTile(xt, yt, zt)) - { + if (mc->level->isSolidBlockingTile(xt, yt, zt)) { tile = mc->level->getTile(xt, yt, zt); } } } - if (Tile::tiles[tile] != NULL) renderTex(a, Tile::tiles[tile]->getTexture(2)); + if (Tile::tiles[tile] != NULL) + renderTex(a, Tile::tiles[tile]->getTexture(2)); } - if (mc->player->isUnderLiquid(Material::water)) - { - MemSect(31); - mc->textures->bindTexture(TN_MISC_WATER); // 4J was L"/misc/water.png" - MemSect(0); + if (mc->player->isUnderLiquid(Material::water)) { + MemSect(31); + mc->textures->bindTexture(TN_MISC_WATER); // 4J was L"/misc/water.png" + MemSect(0); renderWater(a); } glEnable(GL_ALPHA_TEST); - } -void ItemInHandRenderer::renderTex(float a, Icon *slot) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderTex(float a, Icon* slot) { + Tesselator* t = Tesselator::getInstance(); float br = 0.1f; br = 0.1f; @@ -751,20 +762,22 @@ void ItemInHandRenderer::renderTex(float a, Icon *slot) float v1 = slot->getV1(); t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); glColor4f(1, 1, 1, 1); - } -void ItemInHandRenderer::renderWater(float a) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderWater(float a) { + Tesselator* t = Tesselator::getInstance(); float br = mc->player->getBrightness(a); glColor4f(br, br, br, 0.5f); @@ -785,35 +798,36 @@ void ItemInHandRenderer::renderWater(float a) float vo = +mc->player->xRot / 64.0f; t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( size + uo), (float)( size + vo)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( 0 + uo), (float)( size + vo)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( 0 + uo), (float)( 0 + vo)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( size + uo), (float)( 0 + vo)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(size + uo), + (float)(size + vo)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(0 + uo), + (float)(size + vo)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(0 + uo), + (float)(0 + vo)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(size + uo), + (float)(0 + vo)); t->end(); glPopMatrix(); glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - } -void ItemInHandRenderer::renderFire(float a) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderFire(float a) { + Tesselator* t = Tesselator::getInstance(); glColor4f(1, 1, 1, 0.9f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); float size = 1; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { glPushMatrix(); - Icon *slot = Tile::fire->getTextureLayer(1); + Icon* slot = Tile::fire->getTextureLayer(1); - float u0 = slot->getU0(true); - float u1 = slot->getU1(true); - float v0 = slot->getV0(true); - float v1 = slot->getV1(true); + float u0 = slot->getU0(true); + float u1 = slot->getU1(true); + float v0 = slot->getV0(true); + float v1 = slot->getV1(true); float x0 = (0 - size) / 2; float x1 = x0 + size; @@ -824,33 +838,35 @@ void ItemInHandRenderer::renderFire(float a) glRotatef((i * 2 - 1) * 10.0f, 0, 1, 0); t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); } glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - } -void ItemInHandRenderer::tick() -{ +void ItemInHandRenderer::tick() { oHeight = height; - std::shared_ptr player = mc->player; std::shared_ptr nextTile = player->inventory->getSelected(); - bool matches = lastSlot == player->inventory->selected && nextTile == selectedItem; - if (selectedItem == NULL && nextTile == NULL) - { + bool matches = + lastSlot == player->inventory->selected && nextTile == selectedItem; + if (selectedItem == NULL && nextTile == NULL) { matches = true; } - if (nextTile != NULL && selectedItem != NULL && nextTile != selectedItem && nextTile->id == selectedItem->id && nextTile->getAuxValue() == selectedItem->getAuxValue()) - { + if (nextTile != NULL && selectedItem != NULL && nextTile != selectedItem && + nextTile->id == selectedItem->id && + nextTile->getAuxValue() == selectedItem->getAuxValue()) { selectedItem = nextTile; matches = true; } @@ -862,21 +878,12 @@ void ItemInHandRenderer::tick() if (dd > max) dd = max; height += dd; - if (height < 0.1f) - { + if (height < 0.1f) { selectedItem = nextTile; lastSlot = player->inventory->selected; } - } -void ItemInHandRenderer::itemPlaced() -{ - height = 0; -} - -void ItemInHandRenderer::itemUsed() -{ - height = 0; -} +void ItemInHandRenderer::itemPlaced() { height = 0; } +void ItemInHandRenderer::itemUsed() { height = 0; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h index 975dd3606..682b3c183 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h @@ -7,34 +7,41 @@ class Mob; class TileRenderer; class Tesselator; -class ItemInHandRenderer -{ +class ItemInHandRenderer { private: - Minecraft *mc; + Minecraft* mc; std::shared_ptr selectedItem; float height; float oHeight; - TileRenderer *tileRenderer; - static int list, listGlint; + TileRenderer* tileRenderer; + static int list, listGlint; public: - // 4J Stu - Made public so we can use it from ItemFramRenderer - Minimap *minimap; + // 4J Stu - Made public so we can use it from ItemFramRenderer + Minimap* minimap; public: - ItemInHandRenderer(Minecraft *mc, bool optimisedMinimap = true); // 4J Added optimisedMinimap param - void renderItem(std::shared_ptr mob, std::shared_ptr item, int layer, bool setColor = true); // 4J added setColor parameter - static void renderItem3D(Tesselator *t, float u0, float v0, float u1, float v1, int width, int height, float depth, bool isGlint); // 4J added isGlint parameter + ItemInHandRenderer( + Minecraft* mc, + bool optimisedMinimap = true); // 4J Added optimisedMinimap param + void renderItem(std::shared_ptr mob, + std::shared_ptr item, int layer, + bool setColor = true); // 4J added setColor parameter + static void renderItem3D(Tesselator* t, float u0, float v0, float u1, + float v1, int width, int height, float depth, + bool isGlint); // 4J added isGlint parameter public: void render(float a); void renderScreenEffect(float a); + private: - void renderTex(float a, Icon *slot); + void renderTex(float a, Icon* slot); void renderWater(float a); void renderFire(float a); int lastSlot; + public: - void tick(); + void tick(); void itemPlaced(); void itemUsed(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp index bcf70eeb2..cdfeab6fb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp @@ -11,172 +11,162 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.h" #include "../../GameState/Options.h" -ItemRenderer::ItemRenderer() : EntityRenderer() -{ +ItemRenderer::ItemRenderer() : EntityRenderer() { random = new Random(); setColor = true; - blitOffset = 0; + blitOffset = 0; this->shadowRadius = 0.15f; this->shadowStrength = 0.75f; - // 4J added - m_bItemFrame= false; + // 4J added + m_bItemFrame = false; } -ItemRenderer::~ItemRenderer() -{ - delete random; -} +ItemRenderer::~ItemRenderer() { delete random; } -void ItemRenderer::render(std::shared_ptr _itemEntity, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr itemEntity = std::dynamic_pointer_cast(_itemEntity); +void ItemRenderer::render(std::shared_ptr _itemEntity, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr itemEntity = + std::dynamic_pointer_cast(_itemEntity); random->setSeed(187); std::shared_ptr item = itemEntity->getItem(); glPushMatrix(); - float bob = Mth::sin((itemEntity->age + a) / 10.0f + itemEntity->bobOffs) * 0.1f + 0.1f; - float spin = ((itemEntity->age + a) / 20.0f + itemEntity->bobOffs) * Mth::RADDEG; + float bob = + Mth::sin((itemEntity->age + a) / 10.0f + itemEntity->bobOffs) * 0.1f + + 0.1f; + float spin = + ((itemEntity->age + a) / 20.0f + itemEntity->bobOffs) * Mth::RADDEG; int count = 1; if (itemEntity->getItem()->count > 1) count = 2; if (itemEntity->getItem()->count > 5) count = 3; if (itemEntity->getItem()->count > 20) count = 4; - glTranslatef((float) x, (float) y + bob, (float) z); + glTranslatef((float)x, (float)y + bob, (float)z); glEnable(GL_RESCALE_NORMAL); - Tile *tile = Tile::tiles[item->id]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) - { + Tile* tile = Tile::tiles[item->id]; + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && + TileRenderer::canRender(tile->getRenderShape())) { glRotatef(spin, 0, 1, 0); - if (m_bItemFrame) - { - glScalef(1.25f, 1.25f, 1.25f); - glTranslatef(0, 0.05f, 0); - glRotatef(-90, 0, 1, 0); - } + if (m_bItemFrame) { + glScalef(1.25f, 1.25f, 1.25f); + glTranslatef(0, 0.05f, 0); + glRotatef(-90, 0, 1, 0); + } - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" float s = 1 / 4.0f; - int shape = tile->getRenderShape(); - if (shape == Tile::SHAPE_CROSS_TEXTURE || shape == Tile::SHAPE_STEM || shape == Tile::SHAPE_LEVER || shape == Tile::SHAPE_TORCH ) - { + int shape = tile->getRenderShape(); + if (shape == Tile::SHAPE_CROSS_TEXTURE || shape == Tile::SHAPE_STEM || + shape == Tile::SHAPE_LEVER || shape == Tile::SHAPE_TORCH) { s = 0.5f; } glScalef(s, s, s); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { glPushMatrix(); - if (i > 0) - { + if (i > 0) { float xo = (random->nextFloat() * 2 - 1) * 0.2f / s; float yo = (random->nextFloat() * 2 - 1) * 0.2f / s; float zo = (random->nextFloat() * 2 - 1) * 0.2f / s; glTranslatef(xo, yo, zo); } - // 4J - change brought forward from 1.8.2 - float br = SharedConstants::TEXTURE_LIGHTING ? 1.0f : itemEntity->getBrightness(a); + // 4J - change brought forward from 1.8.2 + float br = SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : itemEntity->getBrightness(a); tileRenderer->renderTile(tile, item->getAuxValue(), br); glPopMatrix(); } - } - else if (item->getItem()->hasMultipleSpriteLayers()) - { - if (m_bItemFrame) - { - glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); - glTranslatef(0, -0.05f, 0); - glDisable(GL_LIGHTING); - } - else - { - glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - } - - bindTexture(TN_GUI_ITEMS); // 4J was "/gui/items.png" - - for (int layer = 0; layer <= 1; layer++) - { - random->setSeed(187); - Icon *icon = item->getItem()->getLayerIcon(item->getAuxValue(), layer); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : itemEntity->getBrightness(a); - if (setColor) - { - int col = Item::items[item->id]->getColor(item, layer); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - - glColor4f(red * brightness, g * brightness, b * brightness, 1); - renderItemBillboard(itemEntity, icon, count, a, red * brightness, g * brightness, b * brightness); - } - else - { - renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); - } - } - } - else - { - if (m_bItemFrame) - { - glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); - glTranslatef(0, -0.05f, 0); - glDisable(GL_LIGHTING); - } - else - { - glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - } - - // 4J Stu - For rendering the static compass, we give it a non-zero aux value - if(item->id == Item::compass_Id) item->setAuxValue(255); - Icon *icon = item->getIcon(); - if(item->id == Item::compass_Id) item->setAuxValue(0); - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else if (item->getItem()->hasMultipleSpriteLayers()) { + if (m_bItemFrame) { + glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); + glTranslatef(0, -0.05f, 0); + glDisable(GL_LIGHTING); + } else { + glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } - else - { - bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + + bindTexture(TN_GUI_ITEMS); // 4J was "/gui/items.png" + + for (int layer = 0; layer <= 1; layer++) { + random->setSeed(187); + Icon* icon = + item->getItem()->getLayerIcon(item->getAuxValue(), layer); + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : itemEntity->getBrightness(a); + if (setColor) { + int col = Item::items[item->id]->getColor(item, layer); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + + glColor4f(red * brightness, g * brightness, b * brightness, 1); + renderItemBillboard(itemEntity, icon, count, a, + red * brightness, g * brightness, + b * brightness); + } else { + renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); + } + } + } else { + if (m_bItemFrame) { + glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); + glTranslatef(0, -0.05f, 0); + glDisable(GL_LIGHTING); + } else { + glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } - if (setColor) - { - int col = Item::items[item->id]->getColor(item,0); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : itemEntity->getBrightness(a); - glColor4f(red * brightness, g * brightness, b * brightness, 1); - renderItemBillboard(itemEntity, icon, count, a, red * brightness, g * brightness, b * brightness); - } - else - { - renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); - } + // 4J Stu - For rendering the static compass, we give it a non-zero aux + // value + if (item->id == Item::compass_Id) item->setAuxValue(255); + Icon* icon = item->getIcon(); + if (item->id == Item::compass_Id) item->setAuxValue(0); + if (item->getIconType() == Icon::TYPE_TERRAIN) { + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else { + bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + } + if (setColor) { + int col = Item::items[item->id]->getColor(item, 0); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : itemEntity->getBrightness(a); - } - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( m_bItemFrame ) - { - glEnable(GL_LIGHTING); - } + glColor4f(red * brightness, g * brightness, b * brightness, 1); + renderItemBillboard(itemEntity, icon, count, a, red * brightness, + g * brightness, b * brightness); + } else { + renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); + } + } + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (m_bItemFrame) { + glEnable(GL_LIGHTING); + } } -void ItemRenderer::renderItemBillboard(std::shared_ptr entity, Icon *icon, int count, float a, float red, float green, float blue) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemRenderer::renderItemBillboard(std::shared_ptr entity, + Icon* icon, int count, float a, + float red, float green, float blue) { + Tesselator* t = Tesselator::getInstance(); - if (icon == NULL) icon = entityRenderDispatcher->textures->getMissingIcon(entity->getItem()->getIconType()); + if (icon == NULL) + icon = entityRenderDispatcher->textures->getMissingIcon( + entity->getItem()->getIconType()); float u0 = icon->getU0(); float u1 = icon->getU1(); float v0 = icon->getV0(); @@ -186,430 +176,450 @@ void ItemRenderer::renderItemBillboard(std::shared_ptr entity, Icon float xo = 0.5f; float yo = 0.25f; - if (entityRenderDispatcher->options->fancyGraphics) - { - // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. - int iconWidth = icon->getWidth(); - int LOD = -1; // Default to not doing anything special with LOD forcing - if( iconWidth == 32 ) - { - LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 map - } - else if( iconWidth == 64 ) - { - LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 map - } - RenderManager.StateSetForceLOD(LOD); + if (entityRenderDispatcher->options->fancyGraphics) { + // Consider forcing the mipmap LOD level to use, if this is to be + // rendered from a larger than standard source texture. + int iconWidth = icon->getWidth(); + int LOD = -1; // Default to not doing anything special with LOD forcing + if (iconWidth == 32) { + LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 + // map + } else if (iconWidth == 64) { + LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 + // map + } + RenderManager.StateSetForceLOD(LOD); - glPushMatrix(); - if (m_bItemFrame) - { - glRotatef(180, 0, 1, 0); - } - else - { - glRotatef(((entity->age + a) / 20.0f + entity->bobOffs) * Mth::RADDEG, 0, 1, 0); - } + glPushMatrix(); + if (m_bItemFrame) { + glRotatef(180, 0, 1, 0); + } else { + glRotatef( + ((entity->age + a) / 20.0f + entity->bobOffs) * Mth::RADDEG, 0, + 1, 0); + } - float width = 1 / 16.0f; - float margin = 0.35f / 16.0f; - std::shared_ptr item = entity->getItem(); - int items = item->count; + float width = 1 / 16.0f; + float margin = 0.35f / 16.0f; + std::shared_ptr item = entity->getItem(); + int items = item->count; - if (items < 2) - { - count = 1; - } - else if (items < 16) - { - count = 2; - } - else if (items < 32) - { - count = 3; - } - else - { - count = 4; - } + if (items < 2) { + count = 1; + } else if (items < 16) { + count = 2; + } else if (items < 32) { + count = 3; + } else { + count = 4; + } - glTranslatef(-xo, -yo, -((width + margin) * count / 2)); + glTranslatef(-xo, -yo, -((width + margin) * count / 2)); - for (int i = 0; i < count; i++) - { - glTranslatef(0, 0, width + margin); - if (item->getIconType() == Icon::TYPE_TERRAIN && Tile::tiles[item->id] != NULL) - { - bindTexture(TN_TERRAIN); // Was L"/terrain.png"); - } - else - { - bindTexture(TN_GUI_ITEMS); //L"/gui/items.png"); - } - glColor4f(red, green, blue, 1); - // 4J Stu - u coords were swapped in Java - //ItemInHandRenderer::renderItem3D(t, u1, v0, u0, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false); - ItemInHandRenderer::renderItem3D(t, u0, v0, u1, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false); + for (int i = 0; i < count; i++) { + glTranslatef(0, 0, width + margin); + if (item->getIconType() == Icon::TYPE_TERRAIN && + Tile::tiles[item->id] != NULL) { + bindTexture(TN_TERRAIN); // Was L"/terrain.png"); + } else { + bindTexture(TN_GUI_ITEMS); // L"/gui/items.png"); + } + glColor4f(red, green, blue, 1); + // 4J Stu - u coords were swapped in Java + // ItemInHandRenderer::renderItem3D(t, u1, v0, u0, v1, + // icon->getSourceWidth(), icon->getSourceHeight(), width, false); + ItemInHandRenderer::renderItem3D( + t, u0, v0, u1, v1, icon->getSourceWidth(), + icon->getSourceHeight(), width, false); - if (item != NULL && item->isFoil()) - { - glDepthFunc(GL_EQUAL); - glDisable(GL_LIGHTING); - entityRenderDispatcher->textures->bindTexture(TN__BLUR__MISC_GLINT); // was L"%blur%/misc/glint.png"); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_COLOR, GL_ONE); - float br = 0.76f; - glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); - glMatrixMode(GL_TEXTURE); - glPushMatrix(); - float ss = 1 / 8.0f; - glScalef(ss, ss, ss); - float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; - glTranslatef(sx, 0, 0); - glRotatef(-50, 0, 0, 1); + if (item != NULL && item->isFoil()) { + glDepthFunc(GL_EQUAL); + glDisable(GL_LIGHTING); + entityRenderDispatcher->textures->bindTexture( + TN__BLUR__MISC_GLINT); // was L"%blur%/misc/glint.png"); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_COLOR, GL_ONE); + float br = 0.76f; + glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); + glMatrixMode(GL_TEXTURE); + glPushMatrix(); + float ss = 1 / 8.0f; + glScalef(ss, ss, ss); + float sx = + Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; + glTranslatef(sx, 0, 0); + glRotatef(-50, 0, 0, 1); - ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, true); - glPopMatrix(); - glPushMatrix(); - glScalef(ss, ss, ss); - sx = Minecraft::currentTimeMillis() % (3000 + 1873) / (3000 + 1873.0f) * 8; - glTranslatef(-sx, 0, 0); - glRotatef(10, 0, 0, 1); - ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, true); - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - glDisable(GL_BLEND); - glEnable(GL_LIGHTING); - glDepthFunc(GL_LEQUAL); - } - } + ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, + true); + glPopMatrix(); + glPushMatrix(); + glScalef(ss, ss, ss); + sx = Minecraft::currentTimeMillis() % (3000 + 1873) / + (3000 + 1873.0f) * 8; + glTranslatef(-sx, 0, 0); + glRotatef(10, 0, 0, 1); + ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, + true); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glDisable(GL_BLEND); + glEnable(GL_LIGHTING); + glDepthFunc(GL_LEQUAL); + } + } - glPopMatrix(); + glPopMatrix(); - RenderManager.StateSetForceLOD(-1); - } - else - { - for (int i = 0; i < count; i++) - { - glPushMatrix(); - if (i > 0) - { - float _xo = (random->nextFloat() * 2 - 1) * 0.3f; - float _yo = (random->nextFloat() * 2 - 1) * 0.3f; - float _zo = (random->nextFloat() * 2 - 1) * 0.3f; - glTranslatef(_xo, _yo, _zo); - } - if (!m_bItemFrame) glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); - glColor4f(red, green, blue, 1); - t->begin(); - t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); - t->end(); + RenderManager.StateSetForceLOD(-1); + } else { + for (int i = 0; i < count; i++) { + glPushMatrix(); + if (i > 0) { + float _xo = (random->nextFloat() * 2 - 1) * 0.3f; + float _yo = (random->nextFloat() * 2 - 1) * 0.3f; + float _zo = (random->nextFloat() * 2 - 1) * 0.3f; + glTranslatef(_xo, _yo, _zo); + } + if (!m_bItemFrame) + glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); + glColor4f(red, green, blue, 1); + t->begin(); + t->normal(0, 1, 0); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), + (float)(u1), (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), + (float)(u0), (float)(v0)); + t->end(); - glPopMatrix(); - } -} + glPopMatrix(); + } + } } -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScale, float fAlpha) -{ - renderGuiItem(font,textures,item,x,y,fScale,fScale,fAlpha, true); +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, + float y, float fScale, float fAlpha) { + renderGuiItem(font, textures, item, x, y, fScale, fScale, fAlpha, true); } #ifdef _XBOX -extern IDirect3DDevice9 *g_pD3DDevice; +extern IDirect3DDevice9* g_pD3DDevice; #endif -// 4J - this used to take x and y as ints, and no scale and alpha - but this interface is now implemented as a wrapper round this more fully featured one -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScaleX,float fScaleY, float fAlpha, bool useCompiled) -{ - int itemId = item->id; - int itemAuxValue = item->getAuxValue(); - Icon *itemIcon = item->getIcon(); +// 4J - this used to take x and y as ints, and no scale and alpha - but this +// interface is now implemented as a wrapper round this more fully featured one +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, + float y, float fScaleX, float fScaleY, + float fAlpha, bool useCompiled) { + int itemId = item->id; + int itemAuxValue = item->getAuxValue(); + Icon* itemIcon = item->getIcon(); - if (item->getIconType() == Icon::TYPE_TERRAIN && TileRenderer::canRender(Tile::tiles[itemId]->getRenderShape())) - { - PIXBeginNamedEvent(0,"3D gui item render %d\n",itemId); - MemSect(31); - textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); - MemSect(0); + if (item->getIconType() == Icon::TYPE_TERRAIN && + TileRenderer::canRender(Tile::tiles[itemId]->getRenderShape())) { + PIXBeginNamedEvent(0, "3D gui item render %d\n", itemId); + MemSect(31); + textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + MemSect(0); - Tile *tile = Tile::tiles[itemId]; + Tile* tile = Tile::tiles[itemId]; glPushMatrix(); - // 4J - original code left here for reference - // 4jcraft: re-enable said original code to fix hotbar block rendering + // 4J - original code left here for reference + // 4jcraft: re-enable said original code to fix hotbar block rendering #if 1 - glTranslatef((float)(x), (float)(y), 0.0f); - //glScalef(fScale, fScale, fScale); - glScalef(fScaleX, fScaleY, 1.0f); // 4jcraft: tweaked to use the new variables - glTranslatef(-2.0f,3.0f, -3.0f + blitOffset); - glScalef(10.0f, 10.0f, 10.0f); + glTranslatef((float)(x), (float)(y), 0.0f); + // glScalef(fScale, fScale, fScale); + glScalef(fScaleX, fScaleY, + 1.0f); // 4jcraft: tweaked to use the new variables + glTranslatef(-2.0f, 3.0f, -3.0f + blitOffset); + glScalef(10.0f, 10.0f, 10.0f); glTranslatef(1.0f, 0.5f, 8.0f); glScalef(1.0f, 1.0f, -1.0f); glRotatef(180.0f + 30.0f, 1.0f, 0.0f, 0.0f); glRotatef(45.0f, 0.0f, 1.0f, 0.0f); #else - glTranslatef(x, y, 0.0f); // Translate to screen coords - glScalef(16.0f*fScaleX, 16.0f*fScaleY, 1.0f); // Scale to 0 to 16*scale range - glTranslatef(0.5f,0.5f,0.0f); // Translate to 0 to 1 range - glScalef(0.55f,0.55f, -1.0f); // Scale to occupy full -0.5 to 0.5 bounding region (just touching top & bottom) - // 0.55 comes from 1/(1+sqrt(2)/sqrt(3)) which is determined by the angles that the cube is rotated in an orthographic projection - glRotatef(180.0f + 30.0f, 1.0f, 0.0f, 0.0f); // Rotate round x axis (centre at origin) - glRotatef(45.0f, 0.0f, 1.0f, 0.0f); // Rotate round y axis (centre at origin) + glTranslatef(x, y, 0.0f); // Translate to screen coords + glScalef(16.0f * fScaleX, 16.0f * fScaleY, + 1.0f); // Scale to 0 to 16*scale range + glTranslatef(0.5f, 0.5f, 0.0f); // Translate to 0 to 1 range + glScalef( + 0.55f, 0.55f, + -1.0f); // Scale to occupy full -0.5 to 0.5 bounding region (just + // touching top & bottom) 0.55 comes from + // 1/(1+sqrt(2)/sqrt(3)) which is determined by the angles + // that the cube is rotated in an orthographic projection + glRotatef(180.0f + 30.0f, 1.0f, 0.0f, + 0.0f); // Rotate round x axis (centre at origin) + glRotatef(45.0f, 0.0f, 1.0f, + 0.0f); // Rotate round y axis (centre at origin) #endif - // 4J-PB - pass the alpha value in - the grass block render has the top surface coloured differently to the rest of the block + // 4J-PB - pass the alpha value in - the grass block render has the top + // surface coloured differently to the rest of the block glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); tileRenderer->renderTile(tile, itemAuxValue, 1, fAlpha, useCompiled); glPopMatrix(); - PIXEndNamedEvent(); - } - else if (Item::items[itemId]->hasMultipleSpriteLayers()) - { - PIXBeginNamedEvent(0,"Potion gui item render %d\n",itemIcon); - // special double-layered - glDisable(GL_LIGHTING); - textures->bindTexture(TN_GUI_ITEMS); // "/gui/items.png" - - for (int layer = 0; layer <= 1; layer++) - { - Icon *fillingIcon = Item::items[itemId]->getLayerIcon(itemAuxValue, layer); - - int col = Item::items[itemId]->getColor(item, layer); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - - if (setColor) glColor4f(r, g, b, fAlpha); - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - blit(x, y, fillingIcon, 16 * fScaleX, 16 * fScaleY); - } - else - { - blit((int)x, (int)y, fillingIcon, 16, 16); - } - } - glEnable(GL_LIGHTING); - PIXEndNamedEvent(); - } - else - { - PIXBeginNamedEvent(0,"2D gui item render %d\n",itemIcon); + PIXEndNamedEvent(); + } else if (Item::items[itemId]->hasMultipleSpriteLayers()) { + PIXBeginNamedEvent(0, "Potion gui item render %d\n", itemIcon); + // special double-layered glDisable(GL_LIGHTING); - MemSect(31); - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); + textures->bindTexture(TN_GUI_ITEMS); // "/gui/items.png" + + for (int layer = 0; layer <= 1; layer++) { + Icon* fillingIcon = + Item::items[itemId]->getLayerIcon(itemAuxValue, layer); + + int col = Item::items[itemId]->getColor(item, layer); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + + if (setColor) glColor4f(r, g, b, fAlpha); + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + blit(x, y, fillingIcon, 16 * fScaleX, 16 * fScaleY); + } else { + blit((int)x, (int)y, fillingIcon, 16, 16); + } } - else - { - textures->bindTexture(TN_GUI_ITEMS);//L"/gui/items.png")); + glEnable(GL_LIGHTING); + PIXEndNamedEvent(); + } else { + PIXBeginNamedEvent(0, "2D gui item render %d\n", itemIcon); + glDisable(GL_LIGHTING); + MemSect(31); + if (item->getIconType() == Icon::TYPE_TERRAIN) { + textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + } else { + textures->bindTexture( + TN_GUI_ITEMS); // L"/gui/items.png")); #ifdef _XBOX - // 4J - make sure we've got linear sampling on minification here as non-mipmapped things like this currently - // default to having point sampling, which makes very small icons render rather badly - g_pD3DDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); + // 4J - make sure we've got linear sampling on + // minification here as non-mipmapped things + // like this currently + // default to having point sampling, which makes very small icons + // render rather badly + g_pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); #endif + } + MemSect(0); - } - MemSect(0); + if (itemIcon == NULL) { + itemIcon = textures->getMissingIcon(item->getIconType()); + } - if (itemIcon == NULL) - { - itemIcon = textures->getMissingIcon(item->getIconType()); - } - - int col = Item::items[itemId]->getColor(item,0); + int col = Item::items[itemId]->getColor(item, 0); float r = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; if (setColor) glColor4f(r, g, b, fAlpha); - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - blit(x, y, itemIcon, 16 * fScaleX, 16 * fScaleY); - } - else - { - blit((int)x, (int)y, itemIcon, 16, 16); - } + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + blit(x, y, itemIcon, 16 * fScaleX, 16 * fScaleY); + } else { + blit((int)x, (int)y, itemIcon, 16, 16); + } glEnable(GL_LIGHTING); - PIXEndNamedEvent(); - + PIXEndNamedEvent(); } glEnable(GL_CULL_FACE); - } // 4J - original interface, now just a wrapper for preceding overload -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, int x, int y) -{ - renderGuiItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f ); +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y) { + renderGuiItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f); } -// 4J - this used to take x and y as ints, and no scale, alpha or foil - but this interface is now implemented as a wrapper round this more fully featured one -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y,float fScale,float fAlpha, bool isFoil) -{ - if(item==NULL) return; - renderAndDecorateItem(font, textures, item, x, y,fScale, fScale, fAlpha, isFoil, true); +// 4J - this used to take x and y as ints, and no scale, alpha or foil - but +// this interface is now implemented as a wrapper round this more fully featured +// one +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + float x, float y, float fScale, float fAlpha, bool isFoil) { + if (item == NULL) return; + renderAndDecorateItem(font, textures, item, x, y, fScale, fScale, fAlpha, + isFoil, true); } -// 4J - added isConstantBlended and blendFactor parameters. This is true if the gui item is being rendered from a context where it already has blending enabled to do general interface fading -// (ie from the gui rather than xui). In this case we dno't want to enable/disable blending, and do need to restore the blend state when we are done. -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y,float fScaleX, float fScaleY,float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled) -{ - if (item == NULL) - { +// 4J - added isConstantBlended and blendFactor parameters. This is true if the +// gui item is being rendered from a context where it already has blending +// enabled to do general interface fading (ie from the gui rather than xui). In +// this case we dno't want to enable/disable blending, and do need to restore +// the blend state when we are done. +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + float x, float y, float fScaleX, float fScaleY, float fAlpha, bool isFoil, + bool isConstantBlended, bool useCompiled) { + if (item == NULL) { return; } - renderGuiItem(font, textures, item, x, y,fScaleX,fScaleY,fAlpha, useCompiled); - - if (isFoil || item->isFoil()) - { - glDepthFunc(GL_GREATER); - glDisable(GL_LIGHTING); - glDepthMask(false); - textures->bindTexture(TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" - blitOffset -= 50; - if( !isConstantBlended ) glEnable(GL_BLEND); - - glBlendFunc(GL_DST_COLOR, GL_ONE); // 4J - changed blend equation from GL_DST_COLOR, GL_DST_COLOR so we can fade this out + renderGuiItem(font, textures, item, x, y, fScaleX, fScaleY, fAlpha, + useCompiled); - float blendFactor = isConstantBlended ? Gui::currentGuiBlendFactor : 1.0f; + if (isFoil || item->isFoil()) { + glDepthFunc(GL_GREATER); + glDisable(GL_LIGHTING); + glDepthMask(false); + textures->bindTexture( + TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" + blitOffset -= 50; + if (!isConstantBlended) glEnable(GL_BLEND); - glColor4f(0.5f * blendFactor, 0.25f * blendFactor, 0.8f * blendFactor, 1); // 4J - scale back colourisation with blendFactor - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - // 4J Stu - Scales were multiples of 20, making 16 to not overlap in xui scenes - blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 16 * fScaleX, 16 * fScaleY); - } - else - { - blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 20, 20); - } - glColor4f(1.0f, 1.0f, 1.0f, 1); // 4J added - if( !isConstantBlended ) glDisable(GL_BLEND); + glBlendFunc(GL_DST_COLOR, + GL_ONE); // 4J - changed blend equation from GL_DST_COLOR, + // GL_DST_COLOR so we can fade this out - glDepthMask(true); - blitOffset += 50; - glEnable(GL_LIGHTING); - glDepthFunc(GL_LEQUAL); + float blendFactor = + isConstantBlended ? Gui::currentGuiBlendFactor : 1.0f; - if( isConstantBlended ) glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - } + glColor4f(0.5f * blendFactor, 0.25f * blendFactor, 0.8f * blendFactor, + 1); // 4J - scale back colourisation with blendFactor + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + // 4J Stu - Scales were multiples of 20, making 16 to not overlap in + // xui scenes + blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, + 16 * fScaleX, 16 * fScaleY); + } else { + blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 20, 20); + } + glColor4f(1.0f, 1.0f, 1.0f, 1); // 4J added + if (!isConstantBlended) glDisable(GL_BLEND); + + glDepthMask(true); + blitOffset += 50; + glEnable(GL_LIGHTING); + glDepthFunc(GL_LEQUAL); + + if (isConstantBlended) + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + } } // 4J - original interface, now just a wrapper for preceding overload -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, int x, int y) -{ - renderAndDecorateItem( font, textures, item, (float)x, (float)y, 1.0f, 1.0f, item->isFoil() ); +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + int x, int y) { + renderAndDecorateItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f, + item->isFoil()); } -// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering accuracy), and to align -// final pixels to the final screen resolution -void ItemRenderer::blitGlint(int id, float x, float y, float w, float h) -{ - float us = 1.0f / 64.0f / 4; - float vs = 1.0f / 64.0f / 4; +// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering +// accuracy), and to align final pixels to the final screen resolution +void ItemRenderer::blitGlint(int id, float x, float y, float w, float h) { + float us = 1.0f / 64.0f / 4; + float vs = 1.0f / 64.0f / 4; - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - for (int i = 0; i < 2; i++) - { - if (i == 0) glBlendFunc(GL_SRC_COLOR, GL_ONE); - if (i == 1) glBlendFunc(GL_SRC_COLOR, GL_ONE); - float sx = Minecraft::currentTimeMillis() % (3000 + i * 1873) / (3000.0f + i * 1873) * 256; - float sy = 0; - Tesselator *t = Tesselator::getInstance(); - float vv = 4; - if (i == 1) vv = -1; - t->begin(); - t->vertexUV(xx0f, yy1f, blitOffset, (sx + h * vv) * us, (sy + h) * vs); - t->vertexUV(xx1f, yy1f, blitOffset, (sx + w + h * vv) * us, (sy + h) * vs); - t->vertexUV(xx1f, yy0f, blitOffset, (sx + w) * us, (sy + 0) * vs); - t->vertexUV(xx0f, yy0f, blitOffset, (sx + 0) * us, (sy + 0) * vs); - t->end(); - } + for (int i = 0; i < 2; i++) { + if (i == 0) glBlendFunc(GL_SRC_COLOR, GL_ONE); + if (i == 1) glBlendFunc(GL_SRC_COLOR, GL_ONE); + float sx = Minecraft::currentTimeMillis() % (3000 + i * 1873) / + (3000.0f + i * 1873) * 256; + float sy = 0; + Tesselator* t = Tesselator::getInstance(); + float vv = 4; + if (i == 1) vv = -1; + t->begin(); + t->vertexUV(xx0f, yy1f, blitOffset, (sx + h * vv) * us, (sy + h) * vs); + t->vertexUV(xx1f, yy1f, blitOffset, (sx + w + h * vv) * us, + (sy + h) * vs); + t->vertexUV(xx1f, yy0f, blitOffset, (sx + w) * us, (sy + 0) * vs); + t->vertexUV(xx0f, yy0f, blitOffset, (sx + 0) * us, (sy + 0) * vs); + t->end(); + } } -void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, float fAlpha) -{ - renderGuiItemDecorations(font, textures, item, x, y, L"", fAlpha); +void ItemRenderer::renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, + int x, int y, float fAlpha) { + renderGuiItemDecorations(font, textures, item, x, y, L"", fAlpha); } -void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, const std::wstring &countText, float fAlpha) -{ - if (item == NULL) - { +void ItemRenderer::renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, + int x, int y, + const std::wstring& countText, + float fAlpha) { + if (item == NULL) { return; } - - glEnable(GL_BLEND); - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)(fAlpha * 0xff))<<24)); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - if (item->count > 1 || !countText.empty() || item->GetForceNumberDisplay()) - { - MemSect(31); + + glEnable(GL_BLEND); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)(fAlpha * 0xff)) << 24)); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + if (item->count > 1 || !countText.empty() || + item->GetForceNumberDisplay()) { + MemSect(31); std::wstring amount = countText; - if(amount.empty()) - { - int count = item->count; - if(count > 64) - { - amount = _toString(64) + L"+"; - } - else - { - amount = _toString(item->count); - } - } - MemSect(0); + if (amount.empty()) { + int count = item->count; + if (count > 64) { + amount = _toString(64) + L"+"; + } else { + amount = _toString(item->count); + } + } + MemSect(0); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); - font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, 0xffffff); + font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, + 0xffffff); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); } - if (item->isDamaged()) - { - int p = (int) Math::round(13.0 - (double) item->getDamageValue() * 13.0 / (double) item->getMaxDamage()); - int cc = (int) Math::round(255.0 - (double) item->getDamageValue() * 255.0 / (double) item->getMaxDamage()); + if (item->isDamaged()) { + int p = (int)Math::round(13.0 - (double)item->getDamageValue() * 13.0 / + (double)item->getMaxDamage()); + int cc = + (int)Math::round(255.0 - (double)item->getDamageValue() * 255.0 / + (double)item->getMaxDamage()); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); int ca = (255 - cc) << 16 | (cc) << 8; int cb = ((255 - cc) / 4) << 16 | (255 / 4) << 8; @@ -617,127 +627,140 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std: fillRect(t, x + 2, y + 13, 12, 1, cb); fillRect(t, x + 2, y + 13, p, 1, ca); + glEnable(GL_TEXTURE_2D); + glEnable(GL_LIGHTING); + glEnable(GL_DEPTH_TEST); + glColor4f(1, 1, 1, 1); + } else if (item->hasPotionStrengthBar()) { + glDisable(GL_LIGHTING); + glDisable(GL_DEPTH_TEST); + glDisable(GL_TEXTURE_2D); + + Tesselator* t = Tesselator::getInstance(); + + fillRect(t, x + 3, y + 13, 11, 2, 0x000000); + // fillRect(t, x + 2, y + 13, 13, 1, 0x1dabc0); + fillRect(t, x + 3, y + 13, + m_iPotionStrengthBarWidth[item->GetPotionStrength()], 2, + 0x00e1eb); + fillRect(t, x + 2 + 3, y + 13, 1, 2, 0x000000); + fillRect(t, x + 2 + 3 + 3, y + 13, 1, 2, 0x000000); + fillRect(t, x + 2 + 3 + 3 + 3, y + 13, 1, 2, 0x000000); + glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glColor4f(1, 1, 1, 1); } - else if(item->hasPotionStrengthBar()) - { - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - glDisable(GL_TEXTURE_2D); - - Tesselator *t = Tesselator::getInstance(); - - fillRect(t, x + 3, y + 13, 11, 2, 0x000000); - //fillRect(t, x + 2, y + 13, 13, 1, 0x1dabc0); - fillRect(t, x + 3, y + 13, m_iPotionStrengthBarWidth[item->GetPotionStrength()], 2, 0x00e1eb); - fillRect(t, x + 2 + 3, y + 13, 1, 2, 0x000000); - fillRect(t, x + 2 + 3+3, y + 13, 1, 2, 0x000000); - fillRect(t, x + 2 + 3+3+3, y + 13, 1, 2, 0x000000); - - - glEnable(GL_TEXTURE_2D); - glEnable(GL_LIGHTING); - glEnable(GL_DEPTH_TEST); - glColor4f(1, 1, 1, 1); - } - glDisable(GL_BLEND); + glDisable(GL_BLEND); } -const int ItemRenderer::m_iPotionStrengthBarWidth[]= -{ - 3,6,9,11 -}; +const int ItemRenderer::m_iPotionStrengthBarWidth[] = {3, 6, 9, 11}; -void ItemRenderer::fillRect(Tesselator *t, int x, int y, int w, int h, int c) -{ - t->begin(); - t->color(c); - t->vertex((float)(x + 0), (float)( y + 0), (float)( 0)); - t->vertex((float)(x + 0), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + 0), (float)( 0)); - t->end(); +void ItemRenderer::fillRect(Tesselator* t, int x, int y, int w, int h, int c) { + t->begin(); + t->color(c); + t->vertex((float)(x + 0), (float)(y + 0), (float)(0)); + t->vertex((float)(x + 0), (float)(y + h), (float)(0)); + t->vertex((float)(x + w), (float)(y + h), (float)(0)); + t->vertex((float)(x + w), (float)(y + 0), (float)(0)); + t->end(); } -// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering accuracy), and to align -// final pixels to the final screen resolution -void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) -{ - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); +// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering +// accuracy), and to align final pixels to the final screen resolution +void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) { + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for + // physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float f = (0.5f * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; - t->vertexUV(xx0f, yy1f, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 16) * vs)); - t->vertexUV(xx1f, yy1f, (float)( blitOffset), (float)( (sx + 16) * us), (float)( (sy + 16) * vs)); - t->vertexUV(xx1f, yy0f, (float)( blitOffset), (float)( (sx + 16) * us), (float)( (sy + 0) * vs)); - t->vertexUV(xx0f, yy0f, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); - t->end(); + t->vertexUV(xx0f, yy1f, (float)(blitOffset), (float)((sx + 0) * us), + (float)((sy + 16) * vs)); + t->vertexUV(xx1f, yy1f, (float)(blitOffset), (float)((sx + 16) * us), + (float)((sy + 16) * vs)); + t->vertexUV(xx1f, yy0f, (float)(blitOffset), (float)((sx + 16) * us), + (float)((sy + 0) * vs)); + t->vertexUV(xx0f, yy0f, (float)(blitOffset), (float)((sx + 0) * us), + (float)((sy + 0) * vs)); + t->end(); } -void ItemRenderer::blit(float x, float y, Icon *tex, float w, float h) -{ - Tesselator *t = Tesselator::getInstance(); - t->begin(); +void ItemRenderer::blit(float x, float y, Icon* tex, float w, float h) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for + // physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float f = (0.5f * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; - t->vertexUV(xx0f, yy1f, blitOffset, tex->getU0(true), tex->getV1(true)); - t->vertexUV(xx1f, yy1f, blitOffset, tex->getU1(true), tex->getV1(true)); - t->vertexUV(xx1f, yy0f, blitOffset, tex->getU1(true), tex->getV0(true)); - t->vertexUV(xx0f, yy0f, blitOffset, tex->getU0(true), tex->getV0(true)); - t->end(); + t->vertexUV(xx0f, yy1f, blitOffset, tex->getU0(true), tex->getV1(true)); + t->vertexUV(xx1f, yy1f, blitOffset, tex->getU1(true), tex->getV1(true)); + t->vertexUV(xx1f, yy0f, blitOffset, tex->getU1(true), tex->getV0(true)); + t->vertexUV(xx0f, yy0f, blitOffset, tex->getU0(true), tex->getV0(true)); + t->end(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h index f2f68a254..d3e0df372 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h @@ -6,47 +6,77 @@ class ItemInstance; class Random; class ItemEntity; -class ItemRenderer : public EntityRenderer -{ +class ItemRenderer : public EntityRenderer { private: -// TileRenderer *tileRenderer; // 4J - removed - this is shadowing the tilerenderer from entityrenderer - Random *random; - bool m_bItemFrame; + // TileRenderer *tileRenderer; // 4J - removed - this is shadowing the + //tilerenderer from entityrenderer + Random* random; + bool m_bItemFrame; + public: - bool setColor; - float blitOffset; + bool setColor; + float blitOffset; ItemRenderer(); - virtual ~ItemRenderer(); - virtual void render(std::shared_ptr _itemEntity, double x, double y, double z, float rot, float a); + virtual ~ItemRenderer(); + virtual void render(std::shared_ptr _itemEntity, double x, double y, + double z, float rot, float a); private: - virtual void renderItemBillboard(std::shared_ptr entity, Icon *icon, int count, float a, float red, float green, float blue); + virtual void renderItemBillboard(std::shared_ptr entity, + Icon* icon, int count, float a, float red, + float green, float blue); public: - // 4J - original 2 interface variants - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, int x, int y); - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, int x, int y); - // 4J - new interfaces added - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScale, float fAlpha); - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScaleX,float fScaleY, float fAlpha, bool useCompiled); // 4J Added useCompiled - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y, float fScale, float fAlpha, bool isFoil); - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y, float fScaleX, float fScaleY, float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled = true); // 4J - added isConstantBlended and useCompiled + // 4J - original 2 interface variants + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, int x, int y); + void renderAndDecorateItem(Font* font, Textures* textures, + const std::shared_ptr item, int x, + int y); + // 4J - new interfaces added + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, float y, + float fScale, float fAlpha); + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, float y, + float fScaleX, float fScaleY, float fAlpha, + bool useCompiled); // 4J Added useCompiled + void renderAndDecorateItem(Font* font, Textures* textures, + const std::shared_ptr item, + float x, float y, float fScale, float fAlpha, + bool isFoil); + void renderAndDecorateItem( + Font* font, Textures* textures, + const std::shared_ptr item, float x, float y, + float fScaleX, float fScaleY, float fAlpha, bool isFoil, + bool isConstantBlended, + bool useCompiled = + true); // 4J - added isConstantBlended and useCompiled - // 4J Added - virtual void SetItemFrame(bool bSet) {m_bItemFrame=bSet;} + // 4J Added + virtual void SetItemFrame(bool bSet) { m_bItemFrame = bSet; } - static const int m_iPotionStrengthBarWidth[4]; + static const int m_iPotionStrengthBarWidth[4]; private: - void blitGlint(int id, float x, float y, float w, float h); // 4J - changed x,y,w,h to floats + void blitGlint(int id, float x, float y, float w, + float h); // 4J - changed x,y,w,h to floats public: - void renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, float fAlpha = 1.0f); - void renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, const std::wstring &countText, float fAlpha = 1.0f); + void renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y, float fAlpha = 1.0f); + void renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y, const std::wstring& countText, + float fAlpha = 1.0f); + private: - void fillRect(Tesselator *t, int x, int y, int w, int h, int c); + void fillRect(Tesselator* t, int x, int y, int w, int h, int c); + public: - void blit(float x, float y, int sx, int sy, float w, float h); // 4J - changed x,y,w,h to floats - void blit(float x, float y, Icon *tex, float w, float h); + void blit(float x, float y, int sx, int sy, float w, + float h); // 4J - changed x,y,w,h to floats + void blit(float x, float y, Icon* tex, float w, float h); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp index 0966845a2..51d3a9ba3 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp @@ -6,58 +6,57 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -ItemSpriteRenderer::ItemSpriteRenderer(Item *sourceItem, int sourceItemAuxValue /*= 0*/) : EntityRenderer() -{ - this->sourceItem = sourceItem; - this->sourceItemAuxValue = sourceItemAuxValue; +ItemSpriteRenderer::ItemSpriteRenderer(Item* sourceItem, + int sourceItemAuxValue /*= 0*/) + : EntityRenderer() { + this->sourceItem = sourceItem; + this->sourceItemAuxValue = sourceItemAuxValue; } -//ItemSpriteRenderer::ItemSpriteRenderer(int icon) : EntityRenderer() +// ItemSpriteRenderer::ItemSpriteRenderer(int icon) : EntityRenderer() //{ // this(sourceItem, 0); -//} +// } -void ItemSpriteRenderer::render(std::shared_ptr e, double x, double y, double z, float rot, float a) -{ - // the icon is already cached in the item object, so there should not be any performance impact by not caching it here - Icon *icon = sourceItem->getIcon(sourceItemAuxValue); - if (icon == NULL) - { - return; - } +void ItemSpriteRenderer::render(std::shared_ptr e, double x, double y, + double z, float rot, float a) { + // the icon is already cached in the item object, so there should not be any + // performance impact by not caching it here + Icon* icon = sourceItem->getIcon(sourceItemAuxValue); + if (icon == NULL) { + return; + } glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - bindTexture(TN_GUI_ITEMS); // 4J - was L"/gui/items.png" - Tesselator *t = Tesselator::getInstance(); + bindTexture(TN_GUI_ITEMS); // 4J - was L"/gui/items.png" + Tesselator* t = Tesselator::getInstance(); - if (icon == PotionItem::getTexture(PotionItem::THROWABLE_ICON) ) - { + if (icon == PotionItem::getTexture(PotionItem::THROWABLE_ICON)) { + int col = PotionBrewing::getColorValue( + (std::dynamic_pointer_cast(e))->getPotionValue(), + false); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - int col = PotionBrewing::getColorValue((std::dynamic_pointer_cast(e) )->getPotionValue(), false); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + glColor3f(red, g, b); + glPushMatrix(); + renderIcon(t, PotionItem::getTexture(PotionItem::CONTENTS_ICON)); + glPopMatrix(); + glColor3f(1, 1, 1); + } + renderIcon(t, icon); - glColor3f(red, g, b); - glPushMatrix(); - renderIcon(t, PotionItem::getTexture(PotionItem::CONTENTS_ICON)); - glPopMatrix(); - glColor3f(1, 1, 1); - } - - renderIcon(t, icon); - - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); } -void ItemSpriteRenderer::renderIcon(Tesselator *t, Icon *icon) -{ +void ItemSpriteRenderer::renderIcon(Tesselator* t, Icon* icon) { float u0 = icon->getU0(); float u1 = icon->getU1(); float v0 = icon->getV0(); @@ -71,9 +70,13 @@ void ItemSpriteRenderer::renderIcon(Tesselator *t, Icon *icon) glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( r - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( r - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(r - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(r - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h index e83597839..103e5aaa6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h @@ -3,16 +3,17 @@ class Item; -class ItemSpriteRenderer : public EntityRenderer -{ +class ItemSpriteRenderer : public EntityRenderer { private: - Item *sourceItem; - int sourceItemAuxValue; + Item* sourceItem; + int sourceItemAuxValue; + public: - ItemSpriteRenderer(Item *sourceItem, int sourceItemAuxValue = 0); - //ItemSpriteRenderer(Item *icon); - virtual void render(std::shared_ptr e, double x, double y, double z, float rot, float a); + ItemSpriteRenderer(Item* sourceItem, int sourceItemAuxValue = 0); + // ItemSpriteRenderer(Item *icon); + virtual void render(std::shared_ptr e, double x, double y, double z, + float rot, float a); private: - void renderIcon(Tesselator *t, Icon *icon); + void renderIcon(Tesselator* t, Icon* icon); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp index 27987b9ac..b75b36ae5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp @@ -3,34 +3,36 @@ #include "../Models/LavaSlimeModel.h" #include "LavaSlimeRenderer.h" -LavaSlimeRenderer::LavaSlimeRenderer() : MobRenderer(new LavaSlimeModel(), .25f) -{ - this->modelVersion = ((LavaSlimeModel *) model)->getModelVersion(); +LavaSlimeRenderer::LavaSlimeRenderer() + : MobRenderer(new LavaSlimeModel(), .25f) { + this->modelVersion = ((LavaSlimeModel*)model)->getModelVersion(); } -void LavaSlimeRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type LavaSlime rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - int modelVersion = ((LavaSlimeModel *) model)->getModelVersion(); - if (modelVersion != this->modelVersion) - { - this->modelVersion = modelVersion; - model = new LavaSlimeModel(); - app.DebugPrintf("new lava slime model\n"); - } - MobRenderer::render(mob, x, y, z, rot, a); +void LavaSlimeRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type LavaSlime rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + int modelVersion = ((LavaSlimeModel*)model)->getModelVersion(); + if (modelVersion != this->modelVersion) { + this->modelVersion = modelVersion; + model = new LavaSlimeModel(); + app.DebugPrintf("new lava slime model\n"); + } + MobRenderer::render(mob, x, y, z, rot, a); } -void LavaSlimeRenderer::scale(std::shared_ptr _slime, float a) -{ - // 4J - original version used generics and thus had an input parameter of type LavaSlime rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - int size = slime->getSize(); - float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / (size * 0.5f + 1); - float w = 1 / (ss + 1); - float s = size; - glScalef(w * s, 1 / w * s, w * s); +void LavaSlimeRenderer::scale(std::shared_ptr _slime, float a) { + // 4J - original version used generics and thus had an input parameter of + // type LavaSlime rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr slime = + std::dynamic_pointer_cast(_slime); + int size = slime->getSize(); + float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / + (size * 0.5f + 1); + float w = 1 / (ss + 1); + float s = size; + glScalef(w * s, 1 / w * s, w * s); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h index 29afb390e..0afc0b515 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h @@ -2,16 +2,16 @@ #include "MobRenderer.h" -class LavaSlimeRenderer : public MobRenderer -{ +class LavaSlimeRenderer : public MobRenderer { private: - int modelVersion; + int modelVersion; public: - LavaSlimeRenderer(); + LavaSlimeRenderer(); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void scale(std::shared_ptr _slime, float a); + virtual void scale(std::shared_ptr _slime, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp index cb5ba79ee..fe4321e12 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp @@ -3,27 +3,27 @@ #include "../Tesselator.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.global.h" -void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr bolt = std::dynamic_pointer_cast(_bolt); +void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr bolt = + std::dynamic_pointer_cast(_bolt); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); - double xOffs[8]; double zOffs[8]; double xOff = 0; double zOff = 0; { - Random *random = new Random(bolt->seed); - for (int h = 7; h >= 0; h--) - { + Random* random = new Random(bolt->seed); + for (int h = 7; h >= 0; h--) { xOffs[h] = xOff; zOffs[h] = zOff; xOff += random->nextInt(11) - 5; @@ -31,28 +31,22 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub } } - for (int r = 0; r < 4; r++) - { - Random *random = new Random(bolt->seed); - for (int p = 0; p < 3; p++) - { + for (int r = 0; r < 4; r++) { + Random* random = new Random(bolt->seed); + for (int p = 0; p < 3; p++) { int hs = 7; int ht = 0; if (p > 0) hs = 7 - p; if (p > 0) ht = hs - 2; double xo0 = xOffs[hs] - xOff; double zo0 = zOffs[hs] - zOff; - for (int h = hs; h >= ht; h--) - { + for (int h = hs; h >= ht; h--) { double xo1 = xo0; double zo1 = zo0; - if (p == 0) - { + if (p == 0) { xo0 += random->nextInt(11) - 5; zo0 += random->nextInt(11) - 5; - } - else - { + } else { xo0 += random->nextInt(31) - 15; zo0 += random->nextInt(31) - 15; } @@ -65,10 +59,9 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub if (p == 0) rr1 *= (h * 0.1 + 1); double rr2 = (0.1 + r * 0.2); - if (p == 0) rr2 *= ((h-1) * 0.1 + 1); + if (p == 0) rr2 *= ((h - 1) * 0.1 + 1); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { double xx1 = x + 0.5 - rr1; double zz1 = z + 0.5 - rr1; if (i == 1 || i == 2) xx1 += rr1 * 2; @@ -79,9 +72,10 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub if (i == 1 || i == 2) xx2 += rr2 * 2; if (i == 2 || i == 3) zz2 += rr2 * 2; - t->vertex((float)(xx2 + xo0), (float)( y + (h) * 16), (float)( zz2 + zo0)); - t->vertex((float)(xx1 + xo1), (float)( y + (h + 1) * 16), (float)( zz1 + zo1)); - + t->vertex((float)(xx2 + xo0), (float)(y + (h) * 16), + (float)(zz2 + zo0)); + t->vertex((float)(xx1 + xo1), (float)(y + (h + 1) * 16), + (float)(zz1 + zo1)); } t->end(); @@ -89,9 +83,7 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub } } - glDisable(GL_BLEND); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); - } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h index bf5c7c82c..a2437037e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class LightningBoltRenderer : public EntityRenderer -{ +class LightningBoltRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr bolt, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr bolt, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp index e5928f55b..ddfdc0be9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp @@ -4,28 +4,29 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -MinecartRenderer::MinecartRenderer() -{ +MinecartRenderer::MinecartRenderer() { this->shadowRadius = 0.5f; model = new MinecartModel(); } -void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr cart = std::dynamic_pointer_cast(_cart); +void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr cart = std::dynamic_pointer_cast(_cart); glPushMatrix(); - + // 4jcraft added a bunch of casts to prever overflow int64_t seed = (int64_t)((uint64_t)cart->entityId * 493286711ULL); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 4392167121ULL) + ((uint64_t)seed * 98761ULL)); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 4392167121ULL) + + ((uint64_t)seed * 98761ULL)); - float xo = ((((seed >> 16) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - float yo = ((((seed >> 20) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - float zo = ((((seed >> 24) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float xo = ((((seed >> 16) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float yo = ((((seed >> 20) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float zo = ((((seed >> 24) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - glTranslatef(xo, yo, zo); + glTranslatef(xo, yo, zo); double xx = cart->xOld + (cart->x - cart->xOld) * a; double yy = cart->yOld + (cart->y - cart->yOld) * a; @@ -33,14 +34,13 @@ void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, double r = 0.3f; - Vec3 *p = cart->getPos(xx, yy, zz); + Vec3* p = cart->getPos(xx, yy, zz); float xRot = cart->xRotO + (cart->xRot - cart->xRotO) * a; - if (p != NULL) - { - Vec3 *p0 = cart->getPosOffs(xx, yy, zz, r); - Vec3 *p1 = cart->getPosOffs(xx, yy, zz, -r); + if (p != NULL) { + Vec3* p0 = cart->getPosOffs(xx, yy, zz, r); + Vec3* p1 = cart->getPosOffs(xx, yy, zz, -r); if (p0 == NULL) p0 = p; if (p1 == NULL) p1 = p; @@ -48,60 +48,52 @@ void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, y += (p0->y + p1->y) / 2 - yy; z += p->z - zz; - Vec3 *dir = p1->add(-p0->x, -p0->y, -p0->z); - if (dir->length() == 0) - { - } - else - { + Vec3* dir = p1->add(-p0->x, -p0->y, -p0->z); + if (dir->length() == 0) { + } else { dir = dir->normalize(); - rot = (float) (atan2(dir->z, dir->x) * 180 / PI); - xRot = (float) (atan(dir->y) * 73); + rot = (float)(atan2(dir->z, dir->x) * 180 / PI); + xRot = (float)(atan(dir->y) * 73); } } - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glRotatef(180 - rot, 0, 1, 0); glRotatef(-xRot, 0, 0, 1); float hurt = cart->getHurtTime() - a; float dmg = cart->getDamage() - a; if (dmg < 0) dmg = 0; - if (hurt > 0) - { - glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * cart->getHurtDir(), 1, 0, 0); + if (hurt > 0) { + glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * cart->getHurtDir(), 1, 0, + 0); } - if (cart->type != Minecart::RIDEABLE) - { - glPushMatrix(); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + if (cart->type != Minecart::RIDEABLE) { + glPushMatrix(); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" float ss = 12 / 16.0f; glScalef(ss, ss, ss); - // 4J - changes here brought forward from 1.2.3 - if (cart->type == Minecart::CHEST) - { - glTranslatef(0 / 16.0f, 8 / 16.0f, 0 / 16.0f); - TileRenderer *tr = new TileRenderer(); - tr->renderTile(Tile::chest, 0, cart->getBrightness(a)); - delete tr; - } - else if (cart->type == Minecart::FURNACE) - { - glTranslatef(0, 6 / 16.0f, 0); - TileRenderer *tr = new TileRenderer(); - tr->renderTile(Tile::furnace, 0, cart->getBrightness(a)); - delete tr; - } - glPopMatrix(); - glColor4f(1, 1, 1, 1); + // 4J - changes here brought forward from 1.2.3 + if (cart->type == Minecart::CHEST) { + glTranslatef(0 / 16.0f, 8 / 16.0f, 0 / 16.0f); + TileRenderer* tr = new TileRenderer(); + tr->renderTile(Tile::chest, 0, cart->getBrightness(a)); + delete tr; + } else if (cart->type == Minecart::FURNACE) { + glTranslatef(0, 6 / 16.0f, 0); + TileRenderer* tr = new TileRenderer(); + tr->renderTile(Tile::furnace, 0, cart->getBrightness(a)); + delete tr; + } + glPopMatrix(); + glColor4f(1, 1, 1, 1); } - bindTexture(TN_ITEM_CART); // 4J - was L"/item/cart.png" + bindTexture(TN_ITEM_CART); // 4J - was L"/item/cart.png" glScalef(-1, -1, 1); // model.render(0, 0, cart->getLootContent() * 7.1f - 0.1f, 0, 0, 1 / -// 16.0f); + // 16.0f); model->render(cart, 0, 0, -0.1f, 0, 0, 1 / 16.0f, true); glPopMatrix(); - } diff --git a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h index 6902a3bf2..5c0ee7c35 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "EntityRenderer.h" -class MinecartRenderer : public EntityRenderer -{ +class MinecartRenderer : public EntityRenderer { protected: - Model *model; + Model* model; public: - MinecartRenderer(); - void render(std::shared_ptr _cart, double x, double y, double z, float rot, float a); + MinecartRenderer(); + void render(std::shared_ptr _cart, double x, double y, double z, + float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp index f14e58f01..18493e235 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp @@ -8,34 +8,28 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "EntityRenderDispatcher.h" -MobRenderer::MobRenderer(Model *model, float shadow) : EntityRenderer() -{ +MobRenderer::MobRenderer(Model* model, float shadow) : EntityRenderer() { this->model = model; this->shadowRadius = shadow; - this->armor = NULL; + this->armor = NULL; } -void MobRenderer::setArmor(Model *armor) -{ - this->armor = armor; +void MobRenderer::setArmor(Model* armor) { this->armor = armor; } + +float MobRenderer::rotlerp(float from, float to, float a) { + float diff = to - from; + while (diff < -180) diff += 360; + while (diff >= 180) diff -= 360; + return from + a * diff; } -float MobRenderer::rotlerp(float from, float to, float a) -{ - float diff = to - from; - while (diff < -180) - diff += 360; - while (diff >= 180) - diff -= 360; - return from + a * diff; -} - -void MobRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - added - this used to use generics so the input parameter could be a mob (or derived type), but we aren't - // able to do that so dynamically casting to get the more specific type here. - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void MobRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - added - this used to use generics so the input parameter could be a + // mob (or derived type), but we aren't able to do that so dynamically + // casting to get the more specific type here. + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); glPushMatrix(); glDisable(GL_CULL_FACE); @@ -43,235 +37,236 @@ void MobRenderer::render(std::shared_ptr _mob, double x, double y, doubl if (armor != NULL) armor->attackTime = model->attackTime; model->riding = mob->isRiding(); if (armor != NULL) armor->riding = model->riding; - model->young = mob->isBaby(); - if (armor != NULL) armor->young = model->young; + model->young = mob->isBaby(); + if (armor != NULL) armor->young = model->young; - // 4J - removed try/catch -// try -// { - float bodyRot = rotlerp(mob->yBodyRotO, mob->yBodyRot, a); - float headRot = rotlerp(mob->yHeadRotO, mob->yHeadRot, a); + // 4J - removed try/catch + // try + // { + float bodyRot = rotlerp(mob->yBodyRotO, mob->yBodyRot, a); + float headRot = rotlerp(mob->yHeadRotO, mob->yHeadRot, a); - if (mob->isRiding() && std::dynamic_pointer_cast(mob->riding)) - { - std::shared_ptr riding = std::dynamic_pointer_cast(mob->riding); - bodyRot = rotlerp(riding->yBodyRotO, riding->yBodyRot, a); + if (mob->isRiding() && std::dynamic_pointer_cast(mob->riding)) { + std::shared_ptr riding = + std::dynamic_pointer_cast(mob->riding); + bodyRot = rotlerp(riding->yBodyRotO, riding->yBodyRot, a); - float headDiff = Mth::wrapDegrees(headRot - bodyRot); - if (headDiff < -85) headDiff = -85; - if (headDiff >= 85) headDiff = +85; - bodyRot = headRot - headDiff; - if (headDiff * headDiff > 50 * 50) - { - bodyRot += headDiff * 0.2f; - } - } - - float headRotx = (mob->xRotO + (mob->xRot - mob->xRotO) * a); - - setupPosition(mob, x, y, z); - - float bob = getBob(mob, a); - setupRotations(mob, bob, bodyRot, a); - - float _scale = 1 / 16.0f; - glEnable(GL_RESCALE_NORMAL); - glScalef(-1, -1, 1); - - scale(mob, a); - glTranslatef(0, -24 * _scale - 0.125f / 16.0f, 0); - - - float ws = mob->walkAnimSpeedO + (mob->walkAnimSpeed - mob->walkAnimSpeedO) * a; - float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a); - if (mob->isBaby()) - { - wp *= 3.0f; - } - - if (ws > 1) ws = 1; - - MemSect(31); - bindTexture(mob->customTextureUrl, mob->getTexture()); - MemSect(0); - glEnable(GL_ALPHA_TEST); - - model->prepareMobModel(mob, wp, ws, a); - renderModel(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - int armorType = prepareArmor(mob, i, a); - if (armorType > 0) - { - armor->prepareMobModel(mob, wp, ws, a); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, true); - if ((armorType & 0xf0) == 16) - { - prepareSecondPassArmor(mob, i, a); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, true); - } - // 4J - added condition here for rendering player as part of the gui. Avoiding rendering the glint here as it involves using its own blending, and for gui rendering - // we are globally blending to be able to offer user configurable gui opacity. Note that I really don't know why GL_BLEND is turned off at the end of the first - // armour layer anyway, or why alpha testing is turned on... but we definitely don't want to be turning blending off during the gui render. - if( !entityRenderDispatcher->isGuiRender ) - { - if ((armorType & 0xf) == 0xf) //MGH - fix for missing enchantment glow - { - float time = mob->tickCount + a; - bindTexture(TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" - glEnable(GL_BLEND); - float br = 0.5f; - glColor4f(br, br, br, 1); - glDepthFunc(GL_EQUAL); - glDepthMask(false); - - for (int j = 0; j < 2; j++) - { - glDisable(GL_LIGHTING); - float brr = 0.76f; - glColor4f(0.5f * brr, 0.25f * brr, 0.8f * brr, 1); - glBlendFunc(GL_SRC_COLOR, GL_ONE); - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - float uo = time * (0.001f + j * 0.003f) * 20; - float ss = 1 / 3.0f; - glScalef(ss, ss, ss); - glRotatef(30 - (j) * 60.0f, 0, 0, 1); - glTranslatef(0, uo, 0); - glMatrixMode(GL_MODELVIEW); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - } - - glColor4f(1, 1, 1, 1); - glMatrixMode(GL_TEXTURE); - glDepthMask(true); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glEnable(GL_LIGHTING); - glDisable(GL_BLEND); - glDepthFunc(GL_LEQUAL); - - } - glDisable(GL_BLEND); - } - glEnable(GL_ALPHA_TEST); - } + float headDiff = Mth::wrapDegrees(headRot - bodyRot); + if (headDiff < -85) headDiff = -85; + if (headDiff >= 85) headDiff = +85; + bodyRot = headRot - headDiff; + if (headDiff * headDiff > 50 * 50) { + bodyRot += headDiff * 0.2f; } + } - glDepthMask(true); + float headRotx = (mob->xRotO + (mob->xRot - mob->xRotO) * a); - additionalRendering(mob, a); - float br = mob->getBrightness(a); - int overlayColor = getOverlayColor(mob, br, a); - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); + setupPosition(mob, x, y, z); - if (((overlayColor >> 24) & 0xff) > 0 || mob->hurtTime > 0 || mob->deathTime > 0) - { - glDisable(GL_TEXTURE_2D); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthFunc(GL_EQUAL); + float bob = getBob(mob, a); + setupRotations(mob, bob, bodyRot, a); - // 4J - changed these renders to not use the compiled version of their models, because otherwise the render states set - // about (in particular the depth & alpha test) don't work with our command buffer versions - if (mob->hurtTime > 0 || mob->deathTime > 0) - { - glColor4f(br, 0, 0, 0.4f); - model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - if (prepareArmorOverlay(mob, i, a) >= 0) - { - glColor4f(br, 0, 0, 0.4f); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - } - } + float _scale = 1 / 16.0f; + glEnable(GL_RESCALE_NORMAL); + glScalef(-1, -1, 1); + + scale(mob, a); + glTranslatef(0, -24 * _scale - 0.125f / 16.0f, 0); + + float ws = + mob->walkAnimSpeedO + (mob->walkAnimSpeed - mob->walkAnimSpeedO) * a; + float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a); + if (mob->isBaby()) { + wp *= 3.0f; + } + + if (ws > 1) ws = 1; + + MemSect(31); + bindTexture(mob->customTextureUrl, mob->getTexture()); + MemSect(0); + glEnable(GL_ALPHA_TEST); + + model->prepareMobModel(mob, wp, ws, a); + renderModel(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + int armorType = prepareArmor(mob, i, a); + if (armorType > 0) { + armor->prepareMobModel(mob, wp, ws, a); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + true); + if ((armorType & 0xf0) == 16) { + prepareSecondPassArmor(mob, i, a); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, true); } + // 4J - added condition here for rendering player as part of the + // gui. Avoiding rendering the glint here as it involves using its + // own blending, and for gui rendering we are globally blending to + // be able to offer user configurable gui opacity. Note that I + // really don't know why GL_BLEND is turned off at the end of the + // first armour layer anyway, or why alpha testing is turned on... + // but we definitely don't want to be turning blending off during + // the gui render. + if (!entityRenderDispatcher->isGuiRender) { + if ((armorType & 0xf) == + 0xf) // MGH - fix for missing enchantment glow + { + float time = mob->tickCount + a; + bindTexture( + TN__BLUR__MISC_GLINT); // 4J was + // "%blur%/misc/glint.png" + glEnable(GL_BLEND); + float br = 0.5f; + glColor4f(br, br, br, 1); + glDepthFunc(GL_EQUAL); + glDepthMask(false); - if (((overlayColor >> 24) & 0xff) > 0) - { - float r = ((overlayColor >> 16) & 0xff) / 255.0f; - float g = ((overlayColor >> 8) & 0xff) / 255.0f; - float b = ((overlayColor) & 0xff) / 255.0f; - float aa = ((overlayColor >> 24) & 0xff) / 255.0f; - glColor4f(r, g, b, aa); - model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - if (prepareArmorOverlay(mob, i, a) >= 0) - { - glColor4f(r, g, b, aa); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); + for (int j = 0; j < 2; j++) { + glDisable(GL_LIGHTING); + float brr = 0.76f; + glColor4f(0.5f * brr, 0.25f * brr, 0.8f * brr, 1); + glBlendFunc(GL_SRC_COLOR, GL_ONE); + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + float uo = time * (0.001f + j * 0.003f) * 20; + float ss = 1 / 3.0f; + glScalef(ss, ss, ss); + glRotatef(30 - (j) * 60.0f, 0, 0, 1); + glTranslatef(0, uo, 0); + glMatrixMode(GL_MODELVIEW); + armor->render(mob, wp, ws, bob, headRot - bodyRot, + headRotx, _scale, false); } - } - } - glDepthFunc(GL_LEQUAL); - glDisable(GL_BLEND); + glColor4f(1, 1, 1, 1); + glMatrixMode(GL_TEXTURE); + glDepthMask(true); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glEnable(GL_LIGHTING); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + } + glDisable(GL_BLEND); + } glEnable(GL_ALPHA_TEST); - glEnable(GL_TEXTURE_2D); } - glDisable(GL_RESCALE_NORMAL); -// } -//catch (Exception e) { - // // System.out.println("Failed: " + modelNames[model]); - // e.printStackTrace(); - // } - glActiveTexture(GL_TEXTURE1); - glEnable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); + } + + glDepthMask(true); + + additionalRendering(mob, a); + float br = mob->getBrightness(a); + int overlayColor = getOverlayColor(mob, br, a); + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); + + if (((overlayColor >> 24) & 0xff) > 0 || mob->hurtTime > 0 || + mob->deathTime > 0) { + glDisable(GL_TEXTURE_2D); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthFunc(GL_EQUAL); + + // 4J - changed these renders to not use the compiled version of their + // models, because otherwise the render states set about (in particular + // the depth & alpha test) don't work with our command buffer versions + if (mob->hurtTime > 0 || mob->deathTime > 0) { + glColor4f(br, 0, 0, 0.4f); + model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + false); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + if (prepareArmorOverlay(mob, i, a) >= 0) { + glColor4f(br, 0, 0, 0.4f); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, false); + } + } + } + + if (((overlayColor >> 24) & 0xff) > 0) { + float r = ((overlayColor >> 16) & 0xff) / 255.0f; + float g = ((overlayColor >> 8) & 0xff) / 255.0f; + float b = ((overlayColor) & 0xff) / 255.0f; + float aa = ((overlayColor >> 24) & 0xff) / 255.0f; + glColor4f(r, g, b, aa); + model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + false); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + if (prepareArmorOverlay(mob, i, a) >= 0) { + glColor4f(r, g, b, aa); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, false); + } + } + } + + glDepthFunc(GL_LEQUAL); + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glEnable(GL_TEXTURE_2D); + } + glDisable(GL_RESCALE_NORMAL); + // } + // catch (Exception e) { + // // System.out.println("Failed: " + modelNames[model]); + // e.printStackTrace(); + // } + glActiveTexture(GL_TEXTURE1); + glEnable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); glEnable(GL_CULL_FACE); glPopMatrix(); - MemSect(31); + MemSect(31); renderName(mob, x, y, z); - MemSect(0); + MemSect(0); } -void MobRenderer::renderModel(std::shared_ptr mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale) -{ - std::shared_ptr player = std::dynamic_pointer_cast(Minecraft::GetInstance()->player); +void MobRenderer::renderModel(std::shared_ptr mob, float wp, float ws, + float bob, float headRotMinusBodyRot, + float headRotx, float scale) { + std::shared_ptr player = + std::dynamic_pointer_cast(Minecraft::GetInstance()->player); - bindTexture(mob->customTextureUrl, mob->getTexture()); - if (!mob->isInvisible()) - { - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - } - else if ( !mob->isInvisibleTo(player) ) - { - glPushMatrix(); + bindTexture(mob->customTextureUrl, mob->getTexture()); + if (!mob->isInvisible()) { + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); + } else if (!mob->isInvisibleTo(player)) { + glPushMatrix(); glColor4f(1, 1, 1, 0.15f); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glAlphaFunc(GL_GREATER, 1.0f / 255.0f); - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); glDisable(GL_BLEND); glAlphaFunc(GL_GREATER, .1f); glPopMatrix(); glDepthMask(true); - } - else - { - model->setupAnim(wp, ws, bob, headRotMinusBodyRot, headRotx, scale);//, mob); - } + } else { + model->setupAnim(wp, ws, bob, headRotMinusBodyRot, headRotx, + scale); //, mob); + } } -void MobRenderer::setupPosition(std::shared_ptr mob, double x, double y, double z) -{ - glTranslatef((float) x, (float) y, (float) z); +void MobRenderer::setupPosition(std::shared_ptr mob, double x, double y, + double z) { + glTranslatef((float)x, (float)y, (float)z); } -void MobRenderer::setupRotations(std::shared_ptr mob, float bob, float bodyRot, float a) -{ +void MobRenderer::setupRotations(std::shared_ptr mob, float bob, + float bodyRot, float a) { glRotatef(180 - bodyRot, 0, 1, 0); - if (mob->deathTime > 0) - { + if (mob->deathTime > 0) { float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; fall = (float)sqrt(fall); if (fall > 1) fall = 1; @@ -279,86 +274,71 @@ void MobRenderer::setupRotations(std::shared_ptr mob, float bob, float body } } -float MobRenderer::getAttackAnim(std::shared_ptr mob, float a) -{ - return mob->getAttackAnim(a); +float MobRenderer::getAttackAnim(std::shared_ptr mob, float a) { + return mob->getAttackAnim(a); } -float MobRenderer::getBob(std::shared_ptr mob, float a) -{ - return (mob->tickCount + a); +float MobRenderer::getBob(std::shared_ptr mob, float a) { + return (mob->tickCount + a); } -void MobRenderer::additionalRendering(std::shared_ptr mob, float a) -{ +void MobRenderer::additionalRendering(std::shared_ptr mob, float a) {} + +int MobRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, + float a) { + return prepareArmor(mob, layer, a); } -int MobRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, float a) -{ - return prepareArmor(mob, layer, a); +int MobRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) { + return -1; } -int MobRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) -{ - return -1; +void MobRenderer::prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a) {} + +float MobRenderer::getFlipDegrees(std::shared_ptr mob) { return 90; } + +int MobRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) { + return 0; } -void MobRenderer::prepareSecondPassArmor(std::shared_ptr mob, int layer, float a) -{ -} +void MobRenderer::scale(std::shared_ptr mob, float a) {} -float MobRenderer::getFlipDegrees(std::shared_ptr mob) -{ - return 90; -} - -int MobRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) -{ - return 0; -} - -void MobRenderer::scale(std::shared_ptr mob, float a) -{ -} - -void MobRenderer::renderName(std::shared_ptr mob, double x, double y, double z) -{ - if (Minecraft::renderDebug()) - { - //renderNameTag(mob, _toString(mob->entityId), x, y, z, 64); +void MobRenderer::renderName(std::shared_ptr mob, double x, double y, + double z) { + if (Minecraft::renderDebug()) { + // renderNameTag(mob, _toString(mob->entityId), x, y, z, 64); } } // 4J Added parameter for color here so that we can colour players names -void MobRenderer::renderNameTag(std::shared_ptr mob, const std::wstring& OriginalName, double x, double y, double z, int maxDist, int color /*= 0xffffffff*/) -{ - - if ( app.GetGameSettings(eGameSetting_DisplayHUD)==0 ) - { - // 4J-PB - turn off gamertag render - return; - } - - if(app.GetGameHostOption(eGameHostOption_Gamertags)==0) - { - // turn off gamertags if the host has set them off - return; - } - - float dist = mob->distanceTo(entityRenderDispatcher->cameraEntity); - - if (dist > maxDist) - { +void MobRenderer::renderNameTag(std::shared_ptr mob, + const std::wstring& OriginalName, double x, + double y, double z, int maxDist, + int color /*= 0xffffffff*/) { + if (app.GetGameSettings(eGameSetting_DisplayHUD) == 0) { + // 4J-PB - turn off gamertag render return; } - Font *font = getFont(); + if (app.GetGameHostOption(eGameHostOption_Gamertags) == 0) { + // turn off gamertags if the host has set them off + return; + } + + float dist = mob->distanceTo(entityRenderDispatcher->cameraEntity); + + if (dist > maxDist) { + return; + } + + Font* font = getFont(); float size = 1.60f; float s = 1 / 60.0f * size; glPushMatrix(); - glTranslatef((float) x + 0, (float) y + 2.3f, (float) z); + glTranslatef((float)x + 0, (float)y + 2.3f, (float)z); glNormal3f(0, 1, 0); glRotatef(-this->entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -367,147 +347,134 @@ void MobRenderer::renderNameTag(std::shared_ptr mob, const std::wstring& Or glScalef(-s, -s, s); glDisable(GL_LIGHTING); - // 4J Stu - If it's beyond readable distance, then just render a coloured box - int readableDist = PLAYER_NAME_READABLE_FULLSCREEN; - if( !RenderManager.IsHiDef() ) - { - readableDist = PLAYER_NAME_READABLE_DISTANCE_SD; - } - else if ( app.GetLocalPlayerCount() > 2 ) - { - readableDist = PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN; - } + // 4J Stu - If it's beyond readable distance, then just render a coloured + // box + int readableDist = PLAYER_NAME_READABLE_FULLSCREEN; + if (!RenderManager.IsHiDef()) { + readableDist = PLAYER_NAME_READABLE_DISTANCE_SD; + } else if (app.GetLocalPlayerCount() > 2) { + readableDist = PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN; + } - float textOpacity = 1.0f; - if( dist >= readableDist ) - { - int diff = dist - readableDist; + float textOpacity = 1.0f; + if (dist >= readableDist) { + int diff = dist - readableDist; - textOpacity /= (diff/2); + textOpacity /= (diff / 2); - if( diff > readableDist ) textOpacity = 0.0f; - } + if (diff > readableDist) textOpacity = 0.0f; + } - if( textOpacity < 0.0f ) textOpacity = 0.0f; - if( textOpacity > 1.0f ) textOpacity = 1.0f; - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Tesselator *t = Tesselator::getInstance(); + if (textOpacity < 0.0f) textOpacity = 0.0f; + if (textOpacity > 1.0f) textOpacity = 1.0f; - int offs = 0; - std::shared_ptr player = std::dynamic_pointer_cast(mob); - if (player != NULL && app.isXuidDeadmau5( player->getXuid() ) ) offs = -10; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Tesselator* t = Tesselator::getInstance(); - std::wstring playerName; - WCHAR wchName[2]; + int offs = 0; + std::shared_ptr player = std::dynamic_pointer_cast(mob); + if (player != NULL && app.isXuidDeadmau5(player->getXuid())) offs = -10; + + std::wstring playerName; + WCHAR wchName[2]; #if defined(__PS3__) || defined(__ORBIS__) - // Check we have all the font characters for this player name - switch(player->GetPlayerNameValidState()) - { - case Player::ePlayerNameValid_NotSet: - if(font->AllCharactersValid(OriginalName)) - { - playerName=OriginalName; - player->SetPlayerNameValidState(true); - } - else - { - memset(wchName,0,sizeof(WCHAR)*2); - swprintf(wchName, 2, L"%d",player->getPlayerIndex()+1); - playerName=wchName; - player->SetPlayerNameValidState(false); - } - break; - case Player::ePlayerNameValid_True: - playerName=OriginalName; - break; - case Player::ePlayerNameValid_False: - memset(wchName,0,sizeof(WCHAR)*2); - swprintf(wchName, 2, L"%d",player->getPlayerIndex()+1); - playerName=wchName; - break; - } + // Check we have all the font characters for this player name + switch (player->GetPlayerNameValidState()) { + case Player::ePlayerNameValid_NotSet: + if (font->AllCharactersValid(OriginalName)) { + playerName = OriginalName; + player->SetPlayerNameValidState(true); + } else { + memset(wchName, 0, sizeof(WCHAR) * 2); + swprintf(wchName, 2, L"%d", player->getPlayerIndex() + 1); + playerName = wchName; + player->SetPlayerNameValidState(false); + } + break; + case Player::ePlayerNameValid_True: + playerName = OriginalName; + break; + case Player::ePlayerNameValid_False: + memset(wchName, 0, sizeof(WCHAR) * 2); + swprintf(wchName, 2, L"%d", player->getPlayerIndex() + 1); + playerName = wchName; + break; + } #else - playerName=OriginalName; + playerName = OriginalName; #endif - if( textOpacity > 0.0f ) - { - glColor4f(1.0f,1.0f,1.0f,textOpacity); + if (textOpacity > 0.0f) { + glColor4f(1.0f, 1.0f, 1.0f, textOpacity); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); - glDisable(GL_TEXTURE_2D); + glDisable(GL_TEXTURE_2D); - t->begin(); - int w = font->width(playerName) / 2; + t->begin(); + int w = font->width(playerName) / 2; - if( textOpacity < 1.0f ) - { - t->color(color, 255 * textOpacity); - } - else - { - t->color(0.0f, 0.0f, 0.0f, 0.25f); - } - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->end(); - - glEnable(GL_DEPTH_TEST); - glDepthMask(true); - glDepthFunc(GL_ALWAYS); - glLineWidth(2.0f); - t->begin(GL_LINE_STRIP); - t->color(color, 255 * textOpacity); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->end(); - glDepthFunc(GL_LEQUAL); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); + if (textOpacity < 1.0f) { + t->color(color, 255 * textOpacity); + } else { + t->color(0.0f, 0.0f, 0.0f, 0.25f); + } + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->end(); - glEnable(GL_TEXTURE_2D); - font->draw(playerName, -font->width(playerName) / 2, offs, 0x20ffffff); - glEnable(GL_DEPTH_TEST); - - glDepthMask(true); - } + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + glDepthFunc(GL_ALWAYS); + glLineWidth(2.0f); + t->begin(GL_LINE_STRIP); + t->color(color, 255 * textOpacity); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->end(); + glDepthFunc(GL_LEQUAL); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); + + glEnable(GL_TEXTURE_2D); + font->draw(playerName, -font->width(playerName) / 2, offs, 0x20ffffff); + glEnable(GL_DEPTH_TEST); + + glDepthMask(true); + } + + if (textOpacity < 1.0f) { + glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + t->begin(); + int w = font->width(playerName) / 2; + t->color(color, 255); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->end(); + glDepthFunc(GL_LEQUAL); + glEnable(GL_TEXTURE_2D); - if( textOpacity < 1.0f ) - { - glColor4f(1.0f,1.0f,1.0f,1.0f); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - t->begin(); - int w = font->width(playerName) / 2; - t->color(color, 255); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->end(); - glDepthFunc(GL_LEQUAL); - glEnable(GL_TEXTURE_2D); - glTranslatef(0.0f, 0.0f, -0.04f); - } + } + + if (textOpacity > 0.0f) { + int textColor = (((int)(textOpacity * 255) << 24) | 0xffffff); + font->draw(playerName, -font->width(playerName) / 2, offs, textColor); + } - if( textOpacity > 0.0f ) - { - int textColor = ( ( (int)(textOpacity*255) << 24 ) | 0xffffff ); - font->draw(playerName, -font->width(playerName) / 2, offs, textColor); - } - glEnable(GL_LIGHTING); glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h index 7cefa63e7..3f432ccd6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h @@ -2,45 +2,57 @@ #include "EntityRenderer.h" class Mob; - #define PLAYER_NAME_READABLE_FULLSCREEN 16 #define PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN 8 #define PLAYER_NAME_READABLE_DISTANCE_SD 8 -// 4J - this used to be a generic : public class MobRenderer extends EntityRenderer -class MobRenderer : public EntityRenderer -{ +// 4J - this used to be a generic : public class MobRenderer +// extends EntityRenderer +class MobRenderer : public EntityRenderer { private: - static const int MAX_ARMOR_LAYERS = 4; + static const int MAX_ARMOR_LAYERS = 4; protected: - Model *model; - Model *armor; + Model* model; + Model* armor; public: - MobRenderer(Model *model, float shadow); - virtual void setArmor(Model *armor); + MobRenderer(Model* model, float shadow); + virtual void setArmor(Model* armor); + private: - float rotlerp(float from, float to, float a); + float rotlerp(float from, float to, float a); + public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); + protected: - virtual void renderModel(std::shared_ptr mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale); - virtual void setupPosition(std::shared_ptr mob, double x, double y, double z); - virtual void setupRotations(std::shared_ptr mob, float bob, float bodyRot, float a); + virtual void renderModel(std::shared_ptr mob, float wp, float ws, + float bob, float headRotMinusBodyRot, + float headRotx, float scale); + virtual void setupPosition(std::shared_ptr mob, double x, double y, + double z); + virtual void setupRotations(std::shared_ptr mob, float bob, + float bodyRot, float a); virtual float getAttackAnim(std::shared_ptr mob, float a); virtual float getBob(std::shared_ptr mob, float a); virtual void additionalRendering(std::shared_ptr mob, float a); - virtual int prepareArmorOverlay(std::shared_ptr mob, int layer, float a); + virtual int prepareArmorOverlay(std::shared_ptr mob, int layer, + float a); virtual int prepareArmor(std::shared_ptr mob, int layer, float a); - virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, float a); + virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a); virtual float getFlipDegrees(std::shared_ptr mob); virtual int getOverlayColor(std::shared_ptr mob, float br, float a); virtual void scale(std::shared_ptr mob, float a); - virtual void renderName(std::shared_ptr mob, double x, double y, double z); - virtual void renderNameTag(std::shared_ptr mob, const std::wstring& name, double x, double y, double z, int maxDist, int color = 0xff000000); + virtual void renderName(std::shared_ptr mob, double x, double y, + double z); + virtual void renderNameTag(std::shared_ptr mob, + const std::wstring& name, double x, double y, + double z, int maxDist, int color = 0xff000000); public: - // 4J Added - virtual Model *getModel() { return model; } + // 4J Added + virtual Model* getModel() { return model; } }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp index aa82227dd..9cad4a1eb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp @@ -5,21 +5,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.h" -void MobSpawnerRenderer::render(std::shared_ptr _spawner, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr spawner = std::dynamic_pointer_cast(_spawner); +void MobSpawnerRenderer::render(std::shared_ptr _spawner, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr spawner = + std::dynamic_pointer_cast(_spawner); - glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y, (float) z + 0.5f); + glPushMatrix(); + glTranslatef((float)x + 0.5f, (float)y, (float)z + 0.5f); std::shared_ptr e = spawner->getDisplayEntity(); - if (e != NULL) - { + if (e != NULL) { e->setLevel(spawner->level); float s = 7 / 16.0f; glTranslatef(0, 0.4f, 0); - glRotatef((float) (spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, 0, 1, 0); + glRotatef( + (float)(spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, + 0, 1, 0); glRotatef(-30, 1, 0, 0); glTranslatef(0, -0.4f, 0); glScalef(s, s, s); diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h index 1b6b6109e..b66593105 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h @@ -1,11 +1,13 @@ #pragma once #include "TileEntityRenderer.h" - -class MobSpawnerRenderer : public TileEntityRenderer -{ +class MobSpawnerRenderer : public TileEntityRenderer { private: - std::unordered_map > models; + std::unordered_map > models; + public: - virtual void render(std::shared_ptr _spawner, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + virtual void render(std::shared_ptr _spawner, double x, + double y, double z, float a, bool setColor, + float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp index a1efc1cc9..50ea811e6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp @@ -5,46 +5,49 @@ #include "../Models/ModelPart.h" #include "MushroomCowRenderer.h" -MushroomCowRenderer::MushroomCowRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +MushroomCowRenderer::MushroomCowRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void MushroomCowRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type MushroomCow rather than std::shared_ptr we have here - do + // some casting around instead + // std::shared_ptr mob = + // std::dynamic_pointer_cast(_mob); + + // 4J Stu - No need to do the cast, just pass through as-is + MobRenderer::render(_mob, x, y, z, rot, a); } -void MushroomCowRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type MushroomCow rather than std::shared_ptr we have here - - // do some casting around instead - //std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void MushroomCowRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type MushroomCow rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + if (mob->isBaby()) return; + bindTexture(TN_TERRAIN); // 4J was "/terrain.png" + glEnable(GL_CULL_FACE); + glPushMatrix(); + glScalef(1, -1, 1); + glTranslatef(0.2f, 0.4f, 0.5f); + glRotatef(42, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glTranslatef(0.1f, 0, -0.6f); + glRotatef(42, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glPopMatrix(); - // 4J Stu - No need to do the cast, just pass through as-is - MobRenderer::render(_mob, x, y, z, rot, a); -} + glPushMatrix(); + ((QuadrupedModel*)model)->head->translateTo(1 / 16.0f); + glScalef(1, -1, 1); + glTranslatef(0, 0.75f, -0.2f); + glRotatef(12, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glPopMatrix(); -void MushroomCowRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type MushroomCow rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - if (mob->isBaby()) return; - bindTexture(TN_TERRAIN); // 4J was "/terrain.png" - glEnable(GL_CULL_FACE); - glPushMatrix(); - glScalef(1, -1, 1); - glTranslatef(0.2f, 0.4f, 0.5f); - glRotatef(42, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glTranslatef(0.1f, 0, -0.6f); - glRotatef(42, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glPopMatrix(); - - glPushMatrix(); - ((QuadrupedModel *) model)->head->translateTo(1 / 16.0f); - glScalef(1, -1, 1); - glTranslatef(0, 0.75f, -0.2f); - glRotatef(12, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glPopMatrix(); - - glDisable(GL_CULL_FACE); + glDisable(GL_CULL_FACE); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h index 8d01ea818..3631d5456 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class MushroomCowRenderer : public MobRenderer -{ +class MushroomCowRenderer : public MobRenderer { public: - MushroomCowRenderer(Model *model, float shadow); + MushroomCowRenderer(Model* model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp index 8b36de448..385caed40 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp @@ -2,23 +2,21 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" #include "OcelotRenderer.h" -OzelotRenderer::OzelotRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +OzelotRenderer::OzelotRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void OzelotRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void OzelotRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} - -void OzelotRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::scale(mob, a); - if (mob->isTame()) - { - glScalef(.8f, .8f, .8f); - } +void OzelotRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + MobRenderer::scale(mob, a); + if (mob->isTame()) { + glScalef(.8f, .8f, .8f); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h index a9fc1223b..e262f6a2d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class OzelotRenderer : public MobRenderer -{ +class OzelotRenderer : public MobRenderer { public: - OzelotRenderer(Model *model, float shadow); + OzelotRenderer(Model* model, float shadow); - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - void scale(std::shared_ptr _mob, float a); + void scale(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp index 4e948f5d1..04870f3b9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp @@ -6,25 +6,24 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Util/Mth.h" -PaintingRenderer::PaintingRenderer() -{ - random = new Random(); -} +PaintingRenderer::PaintingRenderer() { random = new Random(); } + +void PaintingRenderer::render(std::shared_ptr _painting, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr painting = + std::dynamic_pointer_cast(_painting); -void PaintingRenderer::render(std::shared_ptr _painting, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr painting = std::dynamic_pointer_cast(_painting); - random->setSeed(187); glPushMatrix(); glTranslatef((float)x, (float)y, (float)z); glRotatef(rot, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); - bindTexture(TN_ART_KZ); // 4J was L"/art/kz.png" + bindTexture(TN_ART_KZ); // 4J was L"/art/kz.png" - Painting::Motive *motive = painting->motive; + Painting::Motive* motive = painting->motive; float s = 1 / 16.0f; glScalef(s, s, s); @@ -33,8 +32,8 @@ void PaintingRenderer::render(std::shared_ptr _painting, double x, doubl glPopMatrix(); } -void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, int h, int uo, int vo) -{ +void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, + int h, int uo, int vo) { float xx0 = -w / 2.0f; float yy0 = -h / 2.0f; @@ -42,8 +41,7 @@ void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, float z1 = +0.5f; for (int xs = 0; xs < w / 16; xs++) - for (int ys = 0; ys < h / 16; ys++) - { + for (int ys = 0; ys < h / 16; ys++) { float x0 = xx0 + (xs + 1) * 16; float x1 = xx0 + (xs) * 16; float y0 = yy0 + (ys + 1) * 16; @@ -71,57 +69,80 @@ void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, float sv0 = (0) / 256.0f; float sv1 = (0 + 16) / 256.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); t->normal(0, 0, -1); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( fu1), (float)( fv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( fu0), (float)( fv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( fu0), (float)( fv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( fu1), (float)( fv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(fu1), + (float)(fv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(fu0), + (float)(fv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(fu0), + (float)(fv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(fu1), + (float)(fv1)); t->normal(0, 0, 1); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( bu0), (float)( bv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( bu1), (float)( bv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( bu1), (float)( bv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( bu0), (float)( bv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(bu0), + (float)(bv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(bu1), + (float)(bv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(bu1), + (float)(bv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(bu0), + (float)(bv1)); t->normal(0, 1, 0); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( uu0), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( uu1), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( uu1), (float)( uv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( uu0), (float)( uv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(uu0), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(uu1), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(uu1), + (float)(uv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(uu0), + (float)(uv1)); t->normal(0, -1, 0); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( uu0), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( uu1), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( uu1), (float)( uv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( uu0), (float)( uv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(uu0), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(uu1), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(uu1), + (float)(uv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(uu0), + (float)(uv1)); t->normal(-1, 0, 0); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( su1), (float)( sv0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( su1), (float)( sv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( su0), (float)( sv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( su0), (float)( sv0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(su1), + (float)(sv0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(su1), + (float)(sv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(su0), + (float)(sv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(su0), + (float)(sv0)); t->normal(1, 0, 0); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( su1), (float)( sv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( su1), (float)( sv1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( su0), (float)( sv1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( su0), (float)( sv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(su1), + (float)(sv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(su1), + (float)(sv1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(su0), + (float)(sv1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(su0), + (float)(sv0)); t->end(); } - } -void PaintingRenderer::setBrightness(std::shared_ptr painting, float ss, float ya) -{ +void PaintingRenderer::setBrightness(std::shared_ptr painting, + float ss, float ya) { int x = Mth::floor(painting->x); - int y = Mth::floor(painting->y + ya/16.0f); + int y = Mth::floor(painting->y + ya / 16.0f); int z = Mth::floor(painting->z); - if (painting->dir == 0) x = Mth::floor(painting->x + ss/16.0f); - if (painting->dir == 1) z = Mth::floor(painting->z - ss/16.0f); - if (painting->dir == 2) x = Mth::floor(painting->x - ss/16.0f); - if (painting->dir == 3) z = Mth::floor(painting->z + ss/16.0f); + if (painting->dir == 0) x = Mth::floor(painting->x + ss / 16.0f); + if (painting->dir == 1) z = Mth::floor(painting->z - ss / 16.0f); + if (painting->dir == 2) x = Mth::floor(painting->x - ss / 16.0f); + if (painting->dir == 3) z = Mth::floor(painting->z + ss / 16.0f); int col = this->entityRenderDispatcher->level->getLightColor(x, y, z, 0); int u = col % 65536; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h index f940c1694..43c65e7ef 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h @@ -4,16 +4,17 @@ class Painting; class Random; -class PaintingRenderer : public EntityRenderer -{ +class PaintingRenderer : public EntityRenderer { private: - Random *random; + Random* random; public: - PaintingRenderer(); // 4J -added - virtual void render(std::shared_ptr _painting, double x, double y, double z, float rot, float a); + PaintingRenderer(); // 4J -added + virtual void render(std::shared_ptr _painting, double x, double y, + double z, float rot, float a); private: - void renderPainting(std::shared_ptr painting, int w, int h, int uo, int vo); + void renderPainting(std::shared_ptr painting, int w, int h, + int uo, int vo); void setBrightness(std::shared_ptr painting, float ss, float ya); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp index 047877d04..648b4b5fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp @@ -2,23 +2,23 @@ #include "PigRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -PigRenderer::PigRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model,shadow) -{ - setArmor(armor); +PigRenderer::PigRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -int PigRenderer::prepareArmor(std::shared_ptr _pig, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr pig = std::dynamic_pointer_cast(_pig); +int PigRenderer::prepareArmor(std::shared_ptr _pig, int layer, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr pig = std::dynamic_pointer_cast(_pig); - MemSect(31); - bindTexture(TN_MOB_SADDLE); // 4J was L"/mob/saddle.png" - MemSect(0); + MemSect(31); + bindTexture(TN_MOB_SADDLE); // 4J was L"/mob/saddle.png" + MemSect(0); return (layer == 0 && pig->hasSaddle()) ? 1 : -1; } -void PigRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} \ No newline at end of file +void PigRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); +} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h index 9dc3edfac..a209366f5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h @@ -1,13 +1,14 @@ #pragma once #include "MobRenderer.h" -class PigRenderer : public MobRenderer -{ +class PigRenderer : public MobRenderer { public: - PigRenderer(Model *model, Model *armor, float shadow); + PigRenderer(Model* model, Model* armor, float shadow); + protected: - virtual int prepareArmor(std::shared_ptr _pig, int layer, float a); + virtual int prepareArmor(std::shared_ptr _pig, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp index a50dfe886..40c68bfaf 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp @@ -7,24 +7,31 @@ #include "../../../Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -PistonPieceRenderer::PistonPieceRenderer() -{ - tileRenderer = NULL; -} +PistonPieceRenderer::PistonPieceRenderer() { tileRenderer = NULL; } -void PistonPieceRenderer::render(std::shared_ptr _entity, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr entity = std::dynamic_pointer_cast(_entity); +void PistonPieceRenderer::render(std::shared_ptr _entity, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr entity = + std::dynamic_pointer_cast(_entity); - Tile *tile = Tile::tiles[entity->getId()]; - if (tile != NULL && entity->getProgress(a) <= 1) // 4J - changed condition from < to <= as our chunk update is async to main thread and so we can have to render these with progress of 1 - { - Tesselator *t = Tesselator::getInstance(); + Tile* tile = Tile::tiles[entity->getId()]; + if (tile != NULL && + entity->getProgress(a) <= + 1) // 4J - changed condition from < to <= as our chunk update is + // async to main thread and so we can have to render these with + // progress of 1 + { + Tesselator* t = Tesselator::getInstance(); bindTexture(TN_TERRAIN); Lighting::turnOff(); - glColor4f(1, 1, 1, 1); // 4J added - this wouldn't be needed in real opengl as the block render has vertex colours and so this isn't use, but our pretend gl always modulates with this + glColor4f(1, 1, 1, + 1); // 4J added - this wouldn't be needed in real opengl as + // the block render has vertex colours and so this isn't + // use, but our pretend gl always modulates with this glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); @@ -32,37 +39,41 @@ void PistonPieceRenderer::render(std::shared_ptr _entity, double x, t->begin(); - t->offset((float) x - entity->x + entity->getXOff(a), (float) y - entity->y + entity->getYOff(a), (float) z - entity->z + entity->getZOff(a)); + t->offset((float)x - entity->x + entity->getXOff(a), + (float)y - entity->y + entity->getYOff(a), + (float)z - entity->z + entity->getZOff(a)); t->color(1, 1, 1); - if (tile == Tile::pistonExtension && entity->getProgress(a) < 0.5f) - { + if (tile == Tile::pistonExtension && entity->getProgress(a) < 0.5f) { // extending arms may appear through the base block - tileRenderer->tesselatePistonArmNoCulling(tile, entity->x, entity->y, entity->z, false, entity->getData()); - } - else if (entity->isSourcePiston() && !entity->isExtending()) - { + tileRenderer->tesselatePistonArmNoCulling(tile, entity->x, + entity->y, entity->z, + false, entity->getData()); + } else if (entity->isSourcePiston() && !entity->isExtending()) { // special case for withdrawing the arm back into the base - Tile::pistonExtension->setOverrideTopTexture(((PistonBaseTile *) tile)->getPlatformTexture()); - tileRenderer->tesselatePistonArmNoCulling(Tile::pistonExtension, entity->x, entity->y, entity->z, entity->getProgress(a) < 0.5f, entity->getData()); + Tile::pistonExtension->setOverrideTopTexture( + ((PistonBaseTile*)tile)->getPlatformTexture()); + tileRenderer->tesselatePistonArmNoCulling( + Tile::pistonExtension, entity->x, entity->y, entity->z, + entity->getProgress(a) < 0.5f, entity->getData()); Tile::pistonExtension->clearOverrideTopTexture(); - t->offset((float) x - entity->x, (float) y - entity->y, (float) z - entity->z); - tileRenderer->tesselatePistonBaseForceExtended(tile, entity->x, entity->y, entity->z, entity->getData()); - } - else - { - tileRenderer->tesselateInWorldNoCulling(tile, entity->x, entity->y, entity->z, entity->getData(), entity); + t->offset((float)x - entity->x, (float)y - entity->y, + (float)z - entity->z); + tileRenderer->tesselatePistonBaseForceExtended( + tile, entity->x, entity->y, entity->z, entity->getData()); + } else { + tileRenderer->tesselateInWorldNoCulling(tile, entity->x, entity->y, + entity->z, + entity->getData(), entity); } t->offset(0, 0, 0); t->end(); Lighting::turnOn(); } +} -} - -void PistonPieceRenderer::onNewLevel(Level *level) -{ - delete tileRenderer; - tileRenderer = new TileRenderer(level); +void PistonPieceRenderer::onNewLevel(Level* level) { + delete tileRenderer; + tileRenderer = new TileRenderer(level); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h index 90061b109..fbeeba4ae 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h @@ -3,13 +3,14 @@ class PistonPieceEntity; class TileRenderer; -class PistonPieceRenderer : public TileEntityRenderer -{ +class PistonPieceRenderer : public TileEntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - PistonPieceRenderer(); - virtual void render(std::shared_ptr _entity, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param - virtual void onNewLevel(Level *level); + PistonPieceRenderer(); + virtual void render(std::shared_ptr _entity, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param + virtual void onNewLevel(Level* level); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp index bc0bbb6ab..88c8b3c07 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp @@ -13,61 +13,60 @@ #include "../../../Minecraft.World/Headers/net.minecraft.h" #include "../../../Minecraft.World/Util/StringHelpers.h" -const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = -{ - 0xff000000, // WHITE (represents the "white" player, but using black as the colour) - 0xff33cc33, // GREEN - 0xffcc3333, // RED - 0xff3333cc, // BLUE -#ifndef __PSVITA__ // only 4 player on Vita - 0xffcc33cc, // PINK - 0xffcc6633, // ORANGE - 0xffcccc33, // YELLOW - 0xff33dccc, // TURQUOISE +const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = + { + 0xff000000, // WHITE (represents the "white" player, but using black as + // the colour) + 0xff33cc33, // GREEN + 0xffcc3333, // RED + 0xff3333cc, // BLUE +#ifndef __PSVITA__ // only 4 player on Vita + 0xffcc33cc, // PINK + 0xffcc6633, // ORANGE + 0xffcccc33, // YELLOW + 0xff33dccc, // TURQUOISE #endif }; -const std::wstring PlayerRenderer::MATERIAL_NAMES[5] = { L"cloth", L"chain", L"iron", L"diamond", L"gold" }; +const std::wstring PlayerRenderer::MATERIAL_NAMES[5] = { + L"cloth", L"chain", L"iron", L"diamond", L"gold"}; -PlayerRenderer::PlayerRenderer() : MobRenderer( new HumanoidModel(0), 0.5f ) -{ - humanoidModel = (HumanoidModel *) model; +PlayerRenderer::PlayerRenderer() : MobRenderer(new HumanoidModel(0), 0.5f) { + humanoidModel = (HumanoidModel*)model; armorParts1 = new HumanoidModel(1.0f); armorParts2 = new HumanoidModel(0.5f); } -unsigned int PlayerRenderer::getNametagColour(int index) -{ - if( index >= 0 && index < MINECRAFT_NET_MAX_PLAYERS) - { - return s_nametagColors[index]; - } - return 0xFF000000; +unsigned int PlayerRenderer::getNametagColour(int index) { + if (index >= 0 && index < MINECRAFT_NET_MAX_PLAYERS) { + return s_nametagColors[index]; + } + return 0xFF000000; } -int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr player = std::dynamic_pointer_cast(_player); +int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr player = std::dynamic_pointer_cast(_player); - // 4J-PB - need to disable rendering armour for some special skins (Daleks) - unsigned int uiAnimOverrideBitmask=player->getAnimOverrideBitmask(); - if(uiAnimOverrideBitmask&(1<getAnimOverrideBitmask(); + if (uiAnimOverrideBitmask & (1 << HumanoidModel::eAnim_DontRenderArmour)) { + return -1; + } - std::shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) - { - Item *item = itemInstance->getItem(); - if (dynamic_cast(item)) - { - ArmorItem *armorItem = dynamic_cast(item); - bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + L"_" + _toString(layer == 2 ? 2 : 1) + L".png"); + std::shared_ptr itemInstance = + player->inventory->getArmor(3 - layer); + if (itemInstance != NULL) { + Item* item = itemInstance->getItem(); + if (dynamic_cast(item)) { + ArmorItem* armorItem = dynamic_cast(item); + bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + + L"_" + _toString(layer == 2 ? 2 : 1) + L".png"); - HumanoidModel *armor = layer == 2 ? armorParts2 : armorParts1; + HumanoidModel* armor = layer == 2 ? armorParts2 : armorParts1; armor->head->visible = layer == 0; armor->hair->visible = layer == 0; @@ -78,197 +77,196 @@ int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, float armor->leg1->visible = layer == 2 || layer == 3; setArmor(armor); - if (armor != NULL) armor->attackTime = model->attackTime; - if (armor != NULL) armor->riding = model->riding; - if (armor != NULL) armor->young = model->young; + if (armor != NULL) armor->attackTime = model->attackTime; + if (armor != NULL) armor->riding = model->riding; + if (armor != NULL) armor->young = model->young; - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); - if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) - { - int color = armorItem->getColor(itemInstance); - float red = (float) ((color >> 16) & 0xFF) / 0xFF; - float green = (float) ((color >> 8) & 0xFF) / 0xFF; - float blue = (float) (color & 0xFF) / 0xFF; - glColor3f(brightness * red, brightness * green, brightness * blue); + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : player->getBrightness(a); + if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) { + int color = armorItem->getColor(itemInstance); + float red = (float)((color >> 16) & 0xFF) / 0xFF; + float green = (float)((color >> 8) & 0xFF) / 0xFF; + float blue = (float)(color & 0xFF) / 0xFF; + glColor3f(brightness * red, brightness * green, + brightness * blue); - if (itemInstance->isEnchanted()) return 0x1f; - return 0x10; - } - else - { - glColor3f(brightness, brightness, brightness); - } + if (itemInstance->isEnchanted()) return 0x1f; + return 0x10; + } else { + glColor3f(brightness, brightness, brightness); + } - if (itemInstance->isEnchanted()) return 0xf; + if (itemInstance->isEnchanted()) return 0xf; return 1; } } return -1; - } -void PlayerRenderer::prepareSecondPassArmor(std::shared_ptr _player, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr player = std::dynamic_pointer_cast(_player); - std::shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) - { - Item *item = itemInstance->getItem(); - if (dynamic_cast(item)) - { - ArmorItem *armorItem = dynamic_cast(item); - bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + L"_" + _toString(layer == 2 ? 2 : 1) + L"_b.png"); +void PlayerRenderer::prepareSecondPassArmor(std::shared_ptr _player, + int layer, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr player = std::dynamic_pointer_cast(_player); + std::shared_ptr itemInstance = + player->inventory->getArmor(3 - layer); + if (itemInstance != NULL) { + Item* item = itemInstance->getItem(); + if (dynamic_cast(item)) { + ArmorItem* armorItem = dynamic_cast(item); + bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + + L"_" + _toString(layer == 2 ? 2 : 1) + L"_b.png"); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); - glColor3f(brightness, brightness, brightness); - } - } + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : player->getBrightness(a); + glColor3f(brightness, brightness, brightness); + } + } } -void PlayerRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if(mob->hasInvisiblePrivilege()) return; + if (mob->hasInvisiblePrivilege()) return; std::shared_ptr item = mob->inventory->getSelected(); - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != NULL ? 1 : 0; - if (item != NULL) - { - if (mob->getUseItemDuration() > 0) - { - UseAnim anim = item->getUseAnimation(); - if (anim == UseAnim_block) - { - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = 3; - } - else if (anim == UseAnim_bow) - { - armorParts1->bowAndArrow = armorParts2->bowAndArrow = humanoidModel->bowAndArrow = true; - } - } - } - // 4J added, for 3rd person view of eating - if( item != NULL && mob->getUseItemDuration() > 0 && item->getUseAnimation() == UseAnim_eat ) - { - // These factors are largely lifted from ItemInHandRenderer to try and keep the 3rd person eating animation as similar as possible + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = item != NULL ? 1 : 0; + if (item != NULL) { + if (mob->getUseItemDuration() > 0) { + UseAnim anim = item->getUseAnimation(); + if (anim == UseAnim_block) { + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = 3; + } else if (anim == UseAnim_bow) { + armorParts1->bowAndArrow = armorParts2->bowAndArrow = + humanoidModel->bowAndArrow = true; + } + } + } + // 4J added, for 3rd person view of eating + if (item != NULL && mob->getUseItemDuration() > 0 && + item->getUseAnimation() == UseAnim_eat) { + // These factors are largely lifted from ItemInHandRenderer to try and + // keep the 3rd person eating animation as similar as possible float t = (mob->getUseItemDuration() - a + 1); float swing = 1 - (t / item->getUseDuration()); - armorParts1->eating = armorParts2->eating = humanoidModel->eating = true; - armorParts1->eating_t = armorParts2->eating_t = humanoidModel->eating_t = t; - armorParts1->eating_swing = armorParts2->eating_swing = humanoidModel->eating_swing = swing; - } - else - { - armorParts1->eating = armorParts2->eating = humanoidModel->eating = false; - } + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + true; + armorParts1->eating_t = armorParts2->eating_t = + humanoidModel->eating_t = t; + armorParts1->eating_swing = armorParts2->eating_swing = + humanoidModel->eating_swing = swing; + } else { + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + false; + } - armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = mob->isSneaking(); + armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = + mob->isSneaking(); double yp = y - mob->heightOffset; - if (mob->isSneaking() && (std::dynamic_pointer_cast(mob) == NULL)) - { + if (mob->isSneaking() && + (std::dynamic_pointer_cast(mob) == NULL)) { yp -= 2 / 16.0f; } - // Check if an idle animation is needed - if(mob->getAnimOverrideBitmask()&(1<isIdle()) - { - humanoidModel->idle=true; - armorParts1->idle=true; - armorParts2->idle=true; - } - else - { - humanoidModel->idle=false; - armorParts1->idle=false; - armorParts2->idle=false; - } - } - else - { - humanoidModel->idle=false; - armorParts1->idle=false; - armorParts2->idle=false; - } + // Check if an idle animation is needed + if (mob->getAnimOverrideBitmask() & (1 << HumanoidModel::eAnim_HasIdle)) { + if (mob->isIdle()) { + humanoidModel->idle = true; + armorParts1->idle = true; + armorParts2->idle = true; + } else { + humanoidModel->idle = false; + armorParts1->idle = false; + armorParts2->idle = false; + } + } else { + humanoidModel->idle = false; + armorParts1->idle = false; + armorParts2->idle = false; + } - // 4J-PB - any additional parts to turn on for this player (skin dependent) - std::vector *pAdditionalModelParts=mob->GetAdditionalModelParts(); - //turn them on - if(pAdditionalModelParts!=NULL) - { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) - { - ModelPart *pModelPart=*it; + // 4J-PB - any additional parts to turn on for this player (skin dependent) + std::vector* pAdditionalModelParts = + mob->GetAdditionalModelParts(); + // turn them on + if (pAdditionalModelParts != NULL) { + for (AUTO_VAR(it, pAdditionalModelParts->begin()); + it != pAdditionalModelParts->end(); ++it) { + ModelPart* pModelPart = *it; - pModelPart->visible=true; - } - } + pModelPart->visible = true; + } + } MobRenderer::render(mob, x, yp, z, rot, a); - // turn them off again - if(pAdditionalModelParts && pAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) - { - ModelPart *pModelPart=*it; - - pModelPart->visible=false; - } - } - armorParts1->bowAndArrow = armorParts2->bowAndArrow = humanoidModel->bowAndArrow = false; - armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = false; - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = 0; + // turn them off again + if (pAdditionalModelParts && pAdditionalModelParts->size() != 0) { + for (AUTO_VAR(it, pAdditionalModelParts->begin()); + it != pAdditionalModelParts->end(); ++it) { + ModelPart* pModelPart = *it; + pModelPart->visible = false; + } + } + armorParts1->bowAndArrow = armorParts2->bowAndArrow = + humanoidModel->bowAndArrow = false; + armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = + false; + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = 0; } -void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, double z) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, + double z) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (Minecraft::renderNames() && mob != entityRenderDispatcher->cameraEntity - && !mob->isInvisibleTo(Minecraft::GetInstance()->player) ) // 4J-JEV: Todo, move to LivingEntityRenderer. - { + if (Minecraft::renderNames() && + mob != entityRenderDispatcher->cameraEntity && + !mob->isInvisibleTo( + Minecraft::GetInstance() + ->player)) // 4J-JEV: Todo, move to LivingEntityRenderer. + { float size = 1.60f; float s = 1 / 60.0f * size; double dist = mob->distanceToSqr(entityRenderDispatcher->cameraEntity); float maxDist = mob->isSneaking() ? 32.0f : 64.0f; - if (dist < maxDist * maxDist) - { - // Truncate display names longer than 16 char + if (dist < maxDist * maxDist) { + // Truncate display names longer than 16 char std::wstring msg = mob->getDisplayName(); - if (msg.length() > 16) - { - msg.resize(16); - msg += L"..."; - } + if (msg.length() > 16) { + msg.resize(16); + msg += L"..."; + } - if (mob->isSneaking()) - { - if ( app.GetGameSettings(eGameSetting_DisplayHUD)==0 ) - { - // 4J-PB - turn off gamertag render - return; - } + if (mob->isSneaking()) { + if (app.GetGameSettings(eGameSetting_DisplayHUD) == 0) { + // 4J-PB - turn off gamertag render + return; + } - if(app.GetGameHostOption(eGameHostOption_Gamertags)==0) - { - // turn off gamertags if the host has set them off - return; - } + if (app.GetGameHostOption(eGameHostOption_Gamertags) == 0) { + // turn off gamertags if the host has set them off + return; + } - Font *font = getFont(); + Font* font = getFont(); glPushMatrix(); - glTranslatef((float) x + 0, (float) y + 2.3f, (float) z); + glTranslatef((float)x + 0, (float)y + 2.3f, (float)z); glNormal3f(0, 1, 0); glRotatef(-this->entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -277,20 +275,20 @@ void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, d glScalef(-s, -s, s); glDisable(GL_LIGHTING); - glTranslatef(0, (float) 0.25f / s, 0); + glTranslatef(0, (float)0.25f / s, 0); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glDisable(GL_TEXTURE_2D); t->begin(); int w = font->width(msg) / 2; t->color(0.0f, 0.0f, 0.0f, 0.25f); - t->vertex((float)(-w - 1), (float)( -1), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1), (float)( 0)); + t->vertex((float)(-w - 1), (float)(-1), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1), (float)(0)); t->end(); glEnable(GL_TEXTURE_2D); glDepthMask(true); @@ -299,76 +297,72 @@ void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, d glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); glPopMatrix(); - } - else - { - if (mob->isSleeping()) - { - renderNameTag(mob, msg, x, y - 1.5f, z, 64, s_nametagColors[mob->getPlayerIndex()]); - } - else - { - renderNameTag(mob, msg, x, y, z, 64, s_nametagColors[mob->getPlayerIndex()]); + } else { + if (mob->isSleeping()) { + renderNameTag(mob, msg, x, y - 1.5f, z, 64, + s_nametagColors[mob->getPlayerIndex()]); + } else { + renderNameTag(mob, msg, x, y, z, 64, + s_nametagColors[mob->getPlayerIndex()]); } } } } - } -void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - MobRenderer::additionalRendering(_mob,a); +void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) { + MobRenderer::additionalRendering(_mob, a); - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); std::shared_ptr headGear = mob->inventory->getArmor(3); - if (headGear != NULL) - { - // don't render the pumpkin for the skins - unsigned int uiAnimOverrideBitmask = mob->getSkinAnimOverrideBitmask( mob->getCustomSkin()); + if (headGear != NULL) { + // don't render the pumpkin for the skins + unsigned int uiAnimOverrideBitmask = + mob->getSkinAnimOverrideBitmask(mob->getCustomSkin()); - if((uiAnimOverrideBitmask&(1<head->translateTo(1 / 16.0f); + if ((uiAnimOverrideBitmask & + (1 << HumanoidModel::eAnim_DontRenderArmour)) == 0) { + glPushMatrix(); + humanoidModel->head->translateTo(1 / 16.0f); - if(headGear->getItem()->id < 256) - { - if (TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, s); - } + if (headGear->getItem()->id < 256) { + if (TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); - } - else if (headGear->getItem()->id == Item::skull_Id) - { - float s = 17 / 16.0f; - glScalef(s, -s, -s); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); + } else if (headGear->getItem()->id == Item::skull_Id) { + float s = 17 / 16.0f; + glScalef(s, -s, -s); - std::wstring extra = L""; - if (headGear->hasTag() && headGear->getTag()->contains(L"SkullOwner")) - { - extra = headGear->getTag()->getString(L"SkullOwner"); - } - SkullTileRenderer::instance->renderSkull(-0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), extra); - } + std::wstring extra = L""; + if (headGear->hasTag() && + headGear->getTag()->contains(L"SkullOwner")) { + extra = headGear->getTag()->getString(L"SkullOwner"); + } + SkullTileRenderer::instance->renderSkull( + -0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), + extra); + } - glPopMatrix(); - } + glPopMatrix(); + } } - // need to add a custom texture for deadmau5 - if (mob != NULL && app.isXuidDeadmau5( mob->getXuid() ) && bindTexture(mob->customTextureUrl, L"" )) - { - for (int i = 0; i < 2; i++) - { - float yr = (mob->yRotO + (mob->yRot - mob->yRotO) * a) - (mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a); + // need to add a custom texture for deadmau5 + if (mob != NULL && app.isXuidDeadmau5(mob->getXuid()) && + bindTexture(mob->customTextureUrl, L"")) { + for (int i = 0; i < 2; i++) { + float yr = (mob->yRotO + (mob->yRot - mob->yRotO) * a) - + (mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a); float xr = mob->xRotO + (mob->xRot - mob->xRotO) * a; glPushMatrix(); glRotatef(yr, 0, 1, 0); @@ -380,116 +374,107 @@ void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) float s = 8 / 6.0f; glScalef(s, s, s); - humanoidModel->renderEars(1 / 16.0f,true); + humanoidModel->renderEars(1 / 16.0f, true); glPopMatrix(); } } -//4J-PB -// if (bindTexture(mob->cloakTexture, L"" )) - if (bindTexture(mob->customTextureUrl2, L"" ) && !mob->isInvisible()) - { + // 4J-PB + // if (bindTexture(mob->cloakTexture, L"" )) + if (bindTexture(mob->customTextureUrl2, L"") && !mob->isInvisible()) { glPushMatrix(); glTranslatef(0, 0, 2 / 16.0f); - double xd = (mob->xCloakO + (mob->xCloak - mob->xCloakO) * a) - (mob->xo + (mob->x - mob->xo) * a); - double yd = (mob->yCloakO + (mob->yCloak - mob->yCloakO) * a) - (mob->yo + (mob->y - mob->yo) * a); - double zd = (mob->zCloakO + (mob->zCloak - mob->zCloakO) * a) - (mob->zo + (mob->z - mob->zo) * a); + double xd = (mob->xCloakO + (mob->xCloak - mob->xCloakO) * a) - + (mob->xo + (mob->x - mob->xo) * a); + double yd = (mob->yCloakO + (mob->yCloak - mob->yCloakO) * a) - + (mob->yo + (mob->y - mob->yo) * a); + double zd = (mob->zCloakO + (mob->zCloak - mob->zCloakO) * a) - + (mob->zo + (mob->z - mob->zo) * a); float yr = mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a; double xa = Mth::sin(yr * PI / 180); double za = -Mth::cos(yr * PI / 180); - float flap = (float) yd * 10; + float flap = (float)yd * 10; if (flap < -6) flap = -6; if (flap > 32) flap = 32; - float lean = (float) (xd * xa + zd * za) * 100; - float lean2 = (float) (xd * za - zd * xa) * 100; + float lean = (float)(xd * xa + zd * za) * 100; + float lean2 = (float)(xd * za - zd * xa) * 100; if (lean < 0) lean = 0; float pow = mob->oBob + (mob->bob - mob->oBob) * a; - flap += sin((mob->walkDistO + (mob->walkDist - mob->walkDistO) * a) * 6) * 32 * pow; - if (mob->isSneaking()) - { + flap += + sin((mob->walkDistO + (mob->walkDist - mob->walkDistO) * a) * 6) * + 32 * pow; + if (mob->isSneaking()) { flap += 25; } - // 4J Stu - Fix for sprint-flying causing the cape to rotate up by 180 degrees or more - float xRot = 6.0f + lean / 2 + flap; - if(xRot > 64.0f) xRot = 64.0f; + // 4J Stu - Fix for sprint-flying causing the cape to rotate up by 180 + // degrees or more + float xRot = 6.0f + lean / 2 + flap; + if (xRot > 64.0f) xRot = 64.0f; glRotatef(xRot, 1, 0, 0); glRotatef(lean2 / 2, 0, 0, 1); glRotatef(-lean2 / 2, 0, 1, 0); glRotatef(180, 0, 1, 0); - humanoidModel->renderCloak(1 / 16.0f,true); + humanoidModel->renderCloak(1 / 16.0f, true); glPopMatrix(); } - std::shared_ptr item = mob->inventory->getSelected(); - if (item != NULL) - { + if (item != NULL) { glPushMatrix(); humanoidModel->arm0->translateTo(1 / 16.0f); glTranslatef(-1 / 16.0f, 7 / 16.0f, 1 / 16.0f); - if (mob->fishing != NULL) - { - item = std::shared_ptr( new ItemInstance(Item::stick) ); + if (mob->fishing != NULL) { + item = std::shared_ptr(new ItemInstance(Item::stick)); } - UseAnim anim = UseAnim_none;//null; - if (mob->getUseItemDuration() > 0) - { - anim = item->getUseAnimation(); - } + UseAnim anim = UseAnim_none; // null; + if (mob->getUseItemDuration() > 0) { + anim = item->getUseAnimation(); + } - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) - { + if (item->id < 256 && + TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { float s = 8 / 16.0f; glTranslatef(-0 / 16.0f, 3 / 16.0f, -5 / 16.0f); s *= 0.75f; glRotatef(20, 1, 0, 0); glRotatef(45, 0, 1, 0); glScalef(s, -s, s); - } - else if (item->id == Item::bow->id) - { - float s = 10 / 16.0f; - glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); - glRotatef(-20, 0, 1, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else if (Item::items[item->id]->isHandEquipped()) - { - float s = 10 / 16.0f; - if (Item::items[item->id]->isMirroredArt()) - { - glRotatef(180, 0, 0, 1); - glTranslatef(0, -2 / 16.0f, 0); - } - if (mob->getUseItemDuration() > 0) - { - if (anim == UseAnim_block) - { - glTranslatef(0.05f, 0, -0.1f); - glRotatef(-50, 0, 1, 0); - glRotatef(-10, 1, 0, 0); - glRotatef(-60, 0, 0, 1); - } - } - glTranslatef(0, 3 / 16.0f, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else - { + } else if (item->id == Item::bow->id) { + float s = 10 / 16.0f; + glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); + glRotatef(-20, 0, 1, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else if (Item::items[item->id]->isHandEquipped()) { + float s = 10 / 16.0f; + if (Item::items[item->id]->isMirroredArt()) { + glRotatef(180, 0, 0, 1); + glTranslatef(0, -2 / 16.0f, 0); + } + if (mob->getUseItemDuration() > 0) { + if (anim == UseAnim_block) { + glTranslatef(0.05f, 0, -0.1f); + glRotatef(-50, 0, 1, 0); + glRotatef(-10, 1, 0, 0); + glRotatef(-60, 0, 0, 1); + } + } + glTranslatef(0, 3 / 16.0f, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else { float s = 6 / 16.0f; glTranslatef(+4 / 16.0f, +3 / 16.0f, -3 / 16.0f); glScalef(s, s, s); @@ -498,88 +483,81 @@ void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) glRotatef(20, 0, 0, 1); } - if (item->getItem()->hasMultipleSpriteLayers()) - { - for (int layer = 0; layer <= 1; layer++) - { - int col = item->getItem()->getColor(item,layer); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + if (item->getItem()->hasMultipleSpriteLayers()) { + for (int layer = 0; layer <= 1; layer++) { + int col = item->getItem()->getColor(item, layer); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f(red, g, b, 1); - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, layer, false); - } - } - else - { - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 0); - } + glColor4f(red, g, b, 1); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, layer, false); + } + } else { + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, 0); + } glPopMatrix(); } - } -void PlayerRenderer::scale(std::shared_ptr player, float a) -{ +void PlayerRenderer::scale(std::shared_ptr player, float a) { float s = 15 / 16.0f; glScalef(s, s, s); } -void PlayerRenderer::renderHand() -{ - humanoidModel->m_uiAnimOverrideBitmask = Minecraft::GetInstance()->player->getAnimOverrideBitmask(); - armorParts1->eating = armorParts2->eating = humanoidModel->eating = humanoidModel->idle = false; +void PlayerRenderer::renderHand() { + humanoidModel->m_uiAnimOverrideBitmask = + Minecraft::GetInstance()->player->getAnimOverrideBitmask(); + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + humanoidModel->idle = false; humanoidModel->attackTime = 0; humanoidModel->setupAnim(0, 0, 0, 0, 0, 1 / 16.0f); - // 4J-PB - does this skin have its arm0 disabled? (Dalek, etc) - if((humanoidModel->m_uiAnimOverrideBitmask&(1<arm0->render(1 / 16.0f,true); - } + // 4J-PB - does this skin have its arm0 disabled? (Dalek, etc) + if ((humanoidModel->m_uiAnimOverrideBitmask & + (1 << HumanoidModel::eAnim_DisableRenderArm0)) == 0) { + humanoidModel->arm0->render(1 / 16.0f, true); + } } -void PlayerRenderer::setupPosition(std::shared_ptr _mob, double x, double y, double z) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::setupPosition(std::shared_ptr _mob, double x, + double y, double z) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isAlive() && mob->isSleeping()) - { - MobRenderer::setupPosition(mob, x + mob->bedOffsetX, y + mob->bedOffsetY, z + mob->bedOffsetZ); + if (mob->isAlive() && mob->isSleeping()) { + MobRenderer::setupPosition(mob, x + mob->bedOffsetX, + y + mob->bedOffsetY, z + mob->bedOffsetZ); - } - else - { + } else { MobRenderer::setupPosition(mob, x, y, z); } } -void PlayerRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isAlive() && mob->isSleeping()) - { + if (mob->isAlive() && mob->isSleeping()) { glRotatef(mob->getSleepRotation(), 0, 1, 0); glRotatef(getFlipDegrees(mob), 0, 0, 1); glRotatef(270, 0, 1, 0); - } - else - { + } else { MobRenderer::setupRotations(mob, bob, bodyRot, a); } } // 4J Added override to stop rendering shadow if player is invisible -void PlayerRenderer::renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a) -{ - if(app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) > 0) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL && player->hasInvisiblePrivilege()) return; - } - EntityRenderer::renderShadow(e,x,y,z,pow,a); +void PlayerRenderer::renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a) { + if (app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) > 0) { + std::shared_ptr player = std::dynamic_pointer_cast(e); + if (player != NULL && player->hasInvisiblePrivilege()) return; + } + EntityRenderer::renderShadow(e, x, y, z, pow, a); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h index b47d36238..3d2118366 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h @@ -3,40 +3,49 @@ #include "../../../Minecraft.World/Player/Player.h" class HumanoidModel; - -class PlayerRenderer : public MobRenderer -{ +class PlayerRenderer : public MobRenderer { private: - // 4J Added - static const unsigned int s_nametagColors[MINECRAFT_NET_MAX_PLAYERS]; + // 4J Added + static const unsigned int s_nametagColors[MINECRAFT_NET_MAX_PLAYERS]; - HumanoidModel *humanoidModel; - HumanoidModel *armorParts1; - HumanoidModel *armorParts2; + HumanoidModel* humanoidModel; + HumanoidModel* armorParts1; + HumanoidModel* armorParts2; public: - PlayerRenderer(); + PlayerRenderer(); - static unsigned int getNametagColour(int index); + static unsigned int getNametagColour(int index); private: - static const std::wstring MATERIAL_NAMES[5]; + static const std::wstring MATERIAL_NAMES[5]; protected: - virtual int prepareArmor(std::shared_ptr _player, int layer, float a); - virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr _player, int layer, float a); + virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a); + public: - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + protected: - virtual void renderName(std::shared_ptr _mob, double x, double y, double z); + virtual void renderName(std::shared_ptr _mob, double x, double y, + double z); virtual void additionalRendering(std::shared_ptr _mob, float a); virtual void scale(std::shared_ptr _player, float a); -public: - void renderHand(); -protected: - virtual void setupPosition(std::shared_ptr _mob, double x, double y, double z); - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); -private: - virtual void renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a); // 4J Added override +public: + void renderHand(); + +protected: + virtual void setupPosition(std::shared_ptr _mob, double x, double y, + double z); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); + +private: + virtual void renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, + float a); // 4J Added override }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp index 50619a156..2cb865c0d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp @@ -6,41 +6,37 @@ CRITICAL_SECTION ProgressRenderer::s_progress; -ProgressRenderer::ProgressRenderer(Minecraft *minecraft) -{ - status = -1; - title = -1; - lastTime = System::currentTimeMillis(); - noAbort = false; - this->minecraft = minecraft; - this->m_eType=eProgressStringType_ID; +ProgressRenderer::ProgressRenderer(Minecraft* minecraft) { + status = -1; + title = -1; + lastTime = System::currentTimeMillis(); + noAbort = false; + this->minecraft = minecraft; + this->m_eType = eProgressStringType_ID; } -void ProgressRenderer::progressStart(int title) -{ - noAbort = false; - _progressStart(title); +void ProgressRenderer::progressStart(int title) { + noAbort = false; + _progressStart(title); } -void ProgressRenderer::progressStartNoAbort(int string) -{ - noAbort = true; +void ProgressRenderer::progressStartNoAbort(int string) { + noAbort = true; _progressStart(string); } -void ProgressRenderer::_progressStart(int title) -{ - // 4J Stu - Removing all progressRenderer rendering. This will be replaced on the xbox - if (!minecraft->running) - { +void ProgressRenderer::_progressStart(int title) { + // 4J Stu - Removing all progressRenderer rendering. This will be replaced + // on the xbox + if (!minecraft->running) { if (noAbort) return; -// throw new StopGameException(); // 4J - removed + // throw new StopGameException(); // 4J - removed } - - EnterCriticalSection( &ProgressRenderer::s_progress ); - lastPercent = 0; + + EnterCriticalSection(&ProgressRenderer::s_progress); + lastPercent = 0; this->title = title; - LeaveCriticalSection( &ProgressRenderer::s_progress ); + LeaveCriticalSection(&ProgressRenderer::s_progress); #if 0 ScreenSizeCalculator ssc(minecraft->options, minecraft->width, minecraft->height); @@ -55,30 +51,27 @@ void ProgressRenderer::_progressStart(int title) #endif } -void ProgressRenderer::progressStage(int status) -{ - if (!minecraft->running) - { +void ProgressRenderer::progressStage(int status) { + if (!minecraft->running) { if (noAbort) return; -// throw new StopGameException(); // 4J - removed + // throw new StopGameException(); // 4J - removed } - lastTime = 0; - EnterCriticalSection( &ProgressRenderer::s_progress ); - setType(eProgressStringType_ID); + EnterCriticalSection(&ProgressRenderer::s_progress); + setType(eProgressStringType_ID); this->status = status; - LeaveCriticalSection( &ProgressRenderer::s_progress ); + LeaveCriticalSection(&ProgressRenderer::s_progress); progressStagePercentage(-1); lastTime = 0; } -void ProgressRenderer::progressStagePercentage(int i) -{ - // 4J Stu - Removing all progressRenderer rendering. This will be replaced on the xbox - EnterCriticalSection( &ProgressRenderer::s_progress ); - lastPercent = i; - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::progressStagePercentage(int i) { + // 4J Stu - Removing all progressRenderer rendering. This will be replaced + // on the xbox + EnterCriticalSection(&ProgressRenderer::s_progress); + lastPercent = i; + LeaveCriticalSection(&ProgressRenderer::s_progress); #if 0 if (!minecraft->running) @@ -155,60 +148,51 @@ void ProgressRenderer::progressStagePercentage(int i) #endif } -int ProgressRenderer::getCurrentPercent() -{ - int returnValue = 0; - EnterCriticalSection( &ProgressRenderer::s_progress ); - returnValue = lastPercent; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentPercent() { + int returnValue = 0; + EnterCriticalSection(&ProgressRenderer::s_progress); + returnValue = lastPercent; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -int ProgressRenderer::getCurrentTitle() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - int returnValue = title; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentTitle() { + EnterCriticalSection(&ProgressRenderer::s_progress); + int returnValue = title; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -int ProgressRenderer::getCurrentStatus() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - int returnValue = status; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentStatus() { + EnterCriticalSection(&ProgressRenderer::s_progress); + int returnValue = status; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -ProgressRenderer::eProgressStringType ProgressRenderer::getType() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - eProgressStringType returnValue = m_eType; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +ProgressRenderer::eProgressStringType ProgressRenderer::getType() { + EnterCriticalSection(&ProgressRenderer::s_progress); + eProgressStringType returnValue = m_eType; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -void ProgressRenderer::setType(eProgressStringType eType) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - m_eType=eType; - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::setType(eProgressStringType eType) { + EnterCriticalSection(&ProgressRenderer::s_progress); + m_eType = eType; + LeaveCriticalSection(&ProgressRenderer::s_progress); } -void ProgressRenderer::progressStage(std::wstring &wstrText) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - m_wstrText=wstrText; - setType(eProgressStringType_String); - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::progressStage(std::wstring& wstrText) { + EnterCriticalSection(&ProgressRenderer::s_progress); + m_wstrText = wstrText; + setType(eProgressStringType_String); + LeaveCriticalSection(&ProgressRenderer::s_progress); } -std::wstring& ProgressRenderer::getProgressString(void) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - std::wstring &temp=m_wstrText; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return temp; +std::wstring& ProgressRenderer::getProgressString(void) { + EnterCriticalSection(&ProgressRenderer::s_progress); + std::wstring& temp = m_wstrText; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return temp; } - - diff --git a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h index bb3446c4c..28ba3c68b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h @@ -1,43 +1,42 @@ #pragma once #include "../../../Minecraft.World/Util/ProgressListener.h" -class ProgressRenderer : public ProgressListener -{ +class ProgressRenderer : public ProgressListener { public: - enum eProgressStringType - { - eProgressStringType_ID, - eProgressStringType_String, // 4J-PB added for updating the bytes read on a save transfer - }; + enum eProgressStringType { + eProgressStringType_ID, + eProgressStringType_String, // 4J-PB added for updating the bytes read + // on a save transfer + }; - static CRITICAL_SECTION s_progress; + static CRITICAL_SECTION s_progress; - int getCurrentPercent(); - int getCurrentTitle(); - int getCurrentStatus(); - std::wstring& getProgressString(void); - ProgressRenderer::eProgressStringType getType(); + int getCurrentPercent(); + int getCurrentTitle(); + int getCurrentStatus(); + std::wstring& getProgressString(void); + ProgressRenderer::eProgressStringType getType(); private: - int lastPercent; + int lastPercent; private: - int status; - Minecraft *minecraft; + int status; + Minecraft* minecraft; int title; __int64 lastTime; bool noAbort; - std::wstring m_wstrText; - eProgressStringType m_eType; + std::wstring m_wstrText; + eProgressStringType m_eType; - void setType(eProgressStringType eType); + void setType(eProgressStringType eType); public: - ProgressRenderer(Minecraft *minecraft); + ProgressRenderer(Minecraft* minecraft); virtual void progressStart(int title); virtual void progressStartNoAbort(int string); void _progressStart(int title); - virtual void progressStage(int status); - virtual void progressStage(std::wstring &wstrText); + virtual void progressStage(int status); + virtual void progressStage(std::wstring& wstrText); virtual void progressStagePercentage(int i); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp index c0c65d6f3..7a99f5a43 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp @@ -3,32 +3,39 @@ #include "../../Player/MultiPlayerLocalPlayer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -SheepRenderer::SheepRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - setArmor(armor); +SheepRenderer::SheepRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -int SheepRenderer::prepareArmor(std::shared_ptr _sheep, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr sheep = std::dynamic_pointer_cast(_sheep); +int SheepRenderer::prepareArmor(std::shared_ptr _sheep, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr sheep = std::dynamic_pointer_cast(_sheep); if (layer == 0 && !sheep->isSheared() && - !sheep->isInvisibleTo(Minecraft::GetInstance()->player)) // 4J-JEV: Todo, merge with java fix (for invisible sheep armour) in '1.7.5'. - { - MemSect(31); - bindTexture(TN_MOB_SHEEP_FUR); // 4J was L"/mob/sheep_fur.png" - MemSect(0); - // 4J - change brought forward from 1.8.2 - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1.0f : sheep->getBrightness(a); + !sheep->isInvisibleTo( + Minecraft::GetInstance() + ->player)) // 4J-JEV: Todo, merge with java fix (for invisible + // sheep armour) in '1.7.5'. + { + MemSect(31); + bindTexture(TN_MOB_SHEEP_FUR); // 4J was L"/mob/sheep_fur.png" + MemSect(0); + // 4J - change brought forward from 1.8.2 + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1.0f : sheep->getBrightness(a); int color = sheep->getColor(); - glColor3f(brightness * Sheep::COLOR[color][0], brightness * Sheep::COLOR[color][1], brightness * Sheep::COLOR[color][2]); + glColor3f(brightness * Sheep::COLOR[color][0], + brightness * Sheep::COLOR[color][1], + brightness * Sheep::COLOR[color][2]); return 1; } return -1; } -void SheepRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} +void SheepRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); +} diff --git a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h index 637c53d04..cd4ff0e97 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h @@ -1,14 +1,14 @@ #pragma once #include "MobRenderer.h" -class SheepRenderer : public MobRenderer -{ +class SheepRenderer : public MobRenderer { public: - SheepRenderer(Model *model, Model *armor, float shadow); + SheepRenderer(Model* model, Model* armor, float shadow); protected: - virtual int prepareArmor(std::shared_ptr _sheep, int layer, float a); + virtual int prepareArmor(std::shared_ptr _sheep, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp index d49f23f17..3d1ecd2e9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp @@ -7,30 +7,26 @@ #include "../../../Minecraft.World/Entities/Entity.h" #include "../../../Minecraft.World/Level/Level.h" +SignRenderer::SignRenderer() { signModel = new SignModel(); } -SignRenderer::SignRenderer() -{ - signModel = new SignModel(); -} +void SignRenderer::render(std::shared_ptr _sign, double x, double y, + double z, float a, bool setColor, float alpha, + bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr sign = + std::dynamic_pointer_cast(_sign); -void SignRenderer::render(std::shared_ptr _sign, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr sign = std::dynamic_pointer_cast(_sign); - - Tile *tile = sign->getTile(); + Tile* tile = sign->getTile(); glPushMatrix(); float size = 16 / 24.0f; - if (tile == Tile::sign) - { - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + if (tile == Tile::sign) { + glTranslatef((float)x + 0.5f, (float)y + 0.75f * size, (float)z + 0.5f); float rot = sign->getData() * 360 / 16.0f; glRotatef(-rot, 0, 1, 0); signModel->cube2->visible = true; - } - else - { + } else { int face = sign->getData(); float rot = 0; @@ -38,20 +34,20 @@ void SignRenderer::render(std::shared_ptr _sign, double x, double y, if (face == 4) rot = 90; if (face == 5) rot = -90; - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + glTranslatef((float)x + 0.5f, (float)y + 0.75f * size, (float)z + 0.5f); glRotatef(-rot, 0, 1, 0); glTranslatef(0, -5 / 16.0f, -7 / 16.0f); signModel->cube2->visible = false; } - bindTexture(TN_ITEM_SIGN); // 4J was L"/item/sign.png" + bindTexture(TN_ITEM_SIGN); // 4J was L"/item/sign.png" glPushMatrix(); glScalef(size, -size, -size); signModel->render(true); glPopMatrix(); - Font *font = getFont(); + Font* font = getFont(); float s = 1 / 60.0f * size; glTranslatef(0, 0.5f * size, 0.07f * size); @@ -59,62 +55,56 @@ void SignRenderer::render(std::shared_ptr _sign, double x, double y, glNormal3f(0, 0, -1 * s); glDepthMask(false); - int col = Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Sign_Text); - std::wstring msg; - // need to send the new data - // Get the current language setting from the console - std::uint32_t dwLanguage = XGetLanguage( ); + int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Sign_Text); + std::wstring msg; + // need to send the new data + // Get the current language setting from the console + std::uint32_t dwLanguage = XGetLanguage(); - for (int i = 0; i < MAX_SIGN_LINES; i++) // 4J - was sign.messages.length - { - if(sign->IsVerified()) - { - if(sign->IsCensored()) - { - switch(dwLanguage) - { - case XC_LANGUAGE_KOREAN: - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - msg = L"Censored";// In-game font, so English only - break; - default: - msg = app.GetString(IDS_STRINGVERIFY_CENSORED); - break; - } - } - else - { - msg = sign->GetMessage(i); - } - } - else - { - switch(dwLanguage) - { - case XC_LANGUAGE_KOREAN: - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - msg = L"Awaiting Approval";// In-game font, so English only - break; - default: - msg = app.GetString(IDS_STRINGVERIFY_AWAITING_APPROVAL); - break; - } - } - - if (i == sign->GetSelectedLine()) - { - msg = L"> " + msg + L" <"; - font->draw(msg, -font->width(msg) / 2, i * 10 - (MAX_SIGN_LINES) * 5, col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + for (int i = 0; i < MAX_SIGN_LINES; i++) // 4J - was sign.messages.length + { + if (sign->IsVerified()) { + if (sign->IsCensored()) { + switch (dwLanguage) { + case XC_LANGUAGE_KOREAN: + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + msg = L"Censored"; // In-game font, so English only + break; + default: + msg = app.GetString(IDS_STRINGVERIFY_CENSORED); + break; + } + } else { + msg = sign->GetMessage(i); + } + } else { + switch (dwLanguage) { + case XC_LANGUAGE_KOREAN: + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + msg = + L"Awaiting Approval"; // In-game font, so English only + break; + default: + msg = app.GetString(IDS_STRINGVERIFY_AWAITING_APPROVAL); + break; + } } - else - { - font->draw(msg, -font->width(msg) / 2, i * 10 - (MAX_SIGN_LINES) * 5, col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + + if (i == sign->GetSelectedLine()) { + msg = L"> " + msg + L" <"; + font->draw(msg, -font->width(msg) / 2, + i * 10 - (MAX_SIGN_LINES) * 5, + col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + } else { + font->draw(msg, -font->width(msg) / 2, + i * 10 - (MAX_SIGN_LINES) * 5, + col); // 4J - (MAX_SIGN_LINES) was sign.messages.length } } glDepthMask(true); glColor4f(1, 1, 1, 1); glPopMatrix(); - } diff --git a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h index d7411af43..cc763391b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h @@ -2,11 +2,13 @@ #include "TileEntityRenderer.h" class SignModel; -class SignRenderer : public TileEntityRenderer -{ +class SignRenderer : public TileEntityRenderer { private: - SignModel *signModel; + SignModel* signModel; + public: - SignRenderer(); // 4J - added - virtual void render(std::shared_ptr sign, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + SignRenderer(); // 4J - added + virtual void render(std::shared_ptr sign, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp index 6da4ed073..61df0e757 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp @@ -3,21 +3,19 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../Models/SilverfishModel.h" -SilverfishRenderer::SilverfishRenderer() : MobRenderer(new SilverfishModel(), 0.3f) -{ +SilverfishRenderer::SilverfishRenderer() + : MobRenderer(new SilverfishModel(), 0.3f) {} + +float SilverfishRenderer::getFlipDegrees(std::shared_ptr spider) { + return 180; } -float SilverfishRenderer::getFlipDegrees(std::shared_ptr spider) -{ - return 180; +void SilverfishRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void SilverfishRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} - -int SilverfishRenderer::prepareArmor(std::shared_ptr _silverfish, int layer, float a) -{ - return -1; +int SilverfishRenderer::prepareArmor(std::shared_ptr _silverfish, + int layer, float a) { + return -1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h index 91ff2e456..eadf51cfe 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h @@ -4,20 +4,20 @@ class Silverfish; -class SilverfishRenderer : public MobRenderer -{ +class SilverfishRenderer : public MobRenderer { private: - //int modelVersion; + // int modelVersion; public: - SilverfishRenderer(); + SilverfishRenderer(); protected: - float getFlipDegrees(std::shared_ptr spider); + float getFlipDegrees(std::shared_ptr spider); public: - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - int prepareArmor(std::shared_ptr _silverfish, int layer, float a); + int prepareArmor(std::shared_ptr _silverfish, int layer, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp index 8d389f87a..ef501bb4a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp @@ -5,108 +5,110 @@ #include "../Models/SkeletonHeadModel.h" #include "SkullTileRenderer.h" -SkullTileRenderer *SkullTileRenderer::instance = NULL; +SkullTileRenderer* SkullTileRenderer::instance = NULL; -SkullTileRenderer::SkullTileRenderer() -{ - skeletonModel = new SkeletonHeadModel(0, 0, 64, 32); - zombieModel = new SkeletonHeadModel(0, 0, 64, 64); +SkullTileRenderer::SkullTileRenderer() { + skeletonModel = new SkeletonHeadModel(0, 0, 64, 32); + zombieModel = new SkeletonHeadModel(0, 0, 64, 64); } -SkullTileRenderer::~SkullTileRenderer() -{ - delete skeletonModel; - delete zombieModel; +SkullTileRenderer::~SkullTileRenderer() { + delete skeletonModel; + delete zombieModel; } -void SkullTileRenderer::render(std::shared_ptr _skull, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - std::shared_ptr skull = std::dynamic_pointer_cast(_skull); - renderSkull((float) x, (float) y, (float) z, skull->getData() & SkullTile::PLACEMENT_MASK, skull->getRotation() * 360 / 16.0f, skull->getSkullType(), skull->getExtraType()); +void SkullTileRenderer::render(std::shared_ptr _skull, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + std::shared_ptr skull = + std::dynamic_pointer_cast(_skull); + renderSkull((float)x, (float)y, (float)z, + skull->getData() & SkullTile::PLACEMENT_MASK, + skull->getRotation() * 360 / 16.0f, skull->getSkullType(), + skull->getExtraType()); } -void SkullTileRenderer::init(TileEntityRenderDispatcher *tileEntityRenderDispatcher) -{ - TileEntityRenderer::init(tileEntityRenderDispatcher); - instance = this; +void SkullTileRenderer::init( + TileEntityRenderDispatcher* tileEntityRenderDispatcher) { + TileEntityRenderer::init(tileEntityRenderDispatcher); + instance = this; } -void SkullTileRenderer::renderSkull(float x, float y, float z, int face, float rot, int type, const std::wstring &extra) -{ - Model *model = skeletonModel; +void SkullTileRenderer::renderSkull(float x, float y, float z, int face, + float rot, int type, + const std::wstring& extra) { + Model* model = skeletonModel; - switch (type) - { - case SkullTileEntity::TYPE_WITHER: - bindTexture(TN_MOB_WITHER_SKELETON); - break; - case SkullTileEntity::TYPE_ZOMBIE: - bindTexture(TN_MOB_ZOMBIE); - //model = zombieModel; - break; - case SkullTileEntity::TYPE_CHAR: - //if (!extra.empty()) - //{ - // std::wstring url = "http://skins.minecraft.net/MinecraftSkins/" + StringUtil.stripColor(extra) + ".png"; + switch (type) { + case SkullTileEntity::TYPE_WITHER: + bindTexture(TN_MOB_WITHER_SKELETON); + break; + case SkullTileEntity::TYPE_ZOMBIE: + bindTexture(TN_MOB_ZOMBIE); + // model = zombieModel; + break; + case SkullTileEntity::TYPE_CHAR: + // if (!extra.empty()) + //{ + // std::wstring url = "http://skins.minecraft.net/MinecraftSkins/" + //+ StringUtil.stripColor(extra) + ".png"; - // if (!instance->tileEntityRenderDispatcher->textures->hasHttpTexture(url)) - // { - // instance->tileEntityRenderDispatcher->textures->addHttpTexture(url, new MobSkinTextureProcessor()); - // } + // if + //(!instance->tileEntityRenderDispatcher->textures->hasHttpTexture(url)) + // { + // instance->tileEntityRenderDispatcher->textures->addHttpTexture(url, + //new MobSkinTextureProcessor()); + // } - // bindTexture(url, "/mob/char.png"); - //} - //else - { - bindTexture(TN_MOB_CHAR); - } - break; - case SkullTileEntity::TYPE_CREEPER: - bindTexture(TN_MOB_CREEPER); - break; - case SkullTileEntity::TYPE_SKELETON: - default: - bindTexture(TN_MOB_SKELETON); - break; - } + // bindTexture(url, "/mob/char.png"); + //} + // else + { + bindTexture(TN_MOB_CHAR); + } + break; + case SkullTileEntity::TYPE_CREEPER: + bindTexture(TN_MOB_CREEPER); + break; + case SkullTileEntity::TYPE_SKELETON: + default: + bindTexture(TN_MOB_SKELETON); + break; + } - glPushMatrix(); - glDisable(GL_CULL_FACE); + glPushMatrix(); + glDisable(GL_CULL_FACE); - if (face != Facing::UP) - { - switch (face) - { - case Facing::NORTH: - glTranslatef(x + 0.5f, y + .25f, z + 0.74f); - break; - case Facing::SOUTH: - glTranslatef(x + 0.5f, y + .25f, z + 0.26f); - rot = 180.0f; - break; - case Facing::WEST: - glTranslatef(x + 0.74f, y + .25f, z + 0.5f); - rot = 270.0f; - break; - case Facing::EAST: - default: - glTranslatef(x + 0.26f, y + .25f, z + 0.5f); - rot = 90.0f; - break; - } - } - else - { - glTranslatef(x + 0.5f, y, z + 0.5f); - } + if (face != Facing::UP) { + switch (face) { + case Facing::NORTH: + glTranslatef(x + 0.5f, y + .25f, z + 0.74f); + break; + case Facing::SOUTH: + glTranslatef(x + 0.5f, y + .25f, z + 0.26f); + rot = 180.0f; + break; + case Facing::WEST: + glTranslatef(x + 0.74f, y + .25f, z + 0.5f); + rot = 270.0f; + break; + case Facing::EAST: + default: + glTranslatef(x + 0.26f, y + .25f, z + 0.5f); + rot = 90.0f; + break; + } + } else { + glTranslatef(x + 0.5f, y, z + 0.5f); + } - float scale = 1 / 16.0f; - glEnable(GL_RESCALE_NORMAL); - glScalef(-1, -1, 1); + float scale = 1 / 16.0f; + glEnable(GL_RESCALE_NORMAL); + glScalef(-1, -1, 1); - glEnable(GL_ALPHA_TEST); + glEnable(GL_ALPHA_TEST); - model->render(nullptr, 0, 0, 0, rot, 0, scale,true); + model->render(nullptr, 0, 0, 0, rot, 0, scale, true); - glPopMatrix(); + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h index e2ef38605..8f47eb6da 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h @@ -4,21 +4,22 @@ class SkeletonHeadModel; -class SkullTileRenderer : public TileEntityRenderer -{ +class SkullTileRenderer : public TileEntityRenderer { public: - static SkullTileRenderer *instance; + static SkullTileRenderer* instance; private: - // note: this head fits most mobs, just change texture - SkeletonHeadModel *skeletonModel; - SkeletonHeadModel *zombieModel; + // note: this head fits most mobs, just change texture + SkeletonHeadModel* skeletonModel; + SkeletonHeadModel* zombieModel; public: - SkullTileRenderer(); - ~SkullTileRenderer(); + SkullTileRenderer(); + ~SkullTileRenderer(); - void render(std::shared_ptr skull, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled = true); - void init(TileEntityRenderDispatcher *tileEntityRenderDispatcher); - void renderSkull(float x, float y, float z, int face, float rot, int type, const std::wstring &extra); + void render(std::shared_ptr skull, double x, double y, double z, + float a, bool setColor, float alpha, bool useCompiled = true); + void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); + void renderSkull(float x, float y, float z, int face, float rot, int type, + const std::wstring& extra); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp index 77f03f7c9..19ee0cad0 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp @@ -1,21 +1,21 @@ #include "../../Platform/stdafx.h" -#include "SlimeRenderer.h" +#include "SlimeRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -SlimeRenderer::SlimeRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - this->armor = armor; +SlimeRenderer::SlimeRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + this->armor = armor; } -int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); +int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - if (slime->isInvisible()) return 0; + if (slime->isInvisible()) return 0; - if (layer == 0) - { + if (layer == 0) { setArmor(armor); glEnable(GL_NORMALIZE); @@ -24,21 +24,21 @@ int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, float a) return 1; } - if (layer == 1) - { + if (layer == 1) { glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); } return -1; } -void SlimeRenderer::scale(std::shared_ptr _slime, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); +void SlimeRenderer::scale(std::shared_ptr _slime, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - float size = (float) slime->getSize(); - float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / (size * 0.5f + 1); + float size = (float)slime->getSize(); + float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / + (size * 0.5f + 1); float w = 1 / (ss + 1); glScalef(w * size, 1 / w * size, w * size); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h index 86de3a76e..0ab5ae7a9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h @@ -1,13 +1,14 @@ #pragma once #include "MobRenderer.h" -class SlimeRenderer : public MobRenderer -{ +class SlimeRenderer : public MobRenderer { private: - Model *armor; + Model* armor; + public: - SlimeRenderer(Model *model, Model *armor, float shadow); + SlimeRenderer(Model* model, Model* armor, float shadow); + protected: - virtual int prepareArmor(std::shared_ptr _slime, int layer, float a); + virtual int prepareArmor(std::shared_ptr _slime, int layer, float a); virtual void scale(std::shared_ptr _slime, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp index 0032a6e5e..039ec74d8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp @@ -7,35 +7,35 @@ #include "EntityRenderDispatcher.h" #include "SnowManRenderer.h" -SnowManRenderer::SnowManRenderer() : MobRenderer(new SnowManModel(), 0.5f) -{ - model = (SnowManModel *) MobRenderer::model; - this->setArmor(model); +SnowManRenderer::SnowManRenderer() : MobRenderer(new SnowManModel(), 0.5f) { + model = (SnowManModel*)MobRenderer::model; + this->setArmor(model); } -void SnowManRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type SnowMan rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void SnowManRenderer::additionalRendering(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type SnowMan rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - std::shared_ptr headGear = std::shared_ptr( new ItemInstance(Tile::pumpkin, 1) ); - if (headGear != NULL && headGear->getItem()->id < 256) - { - glPushMatrix(); - model->head->translateTo(1 / 16.0f); + MobRenderer::additionalRendering(mob, a); + std::shared_ptr headGear = + std::shared_ptr(new ItemInstance(Tile::pumpkin, 1)); + if (headGear != NULL && headGear->getItem()->id < 256) { + glPushMatrix(); + model->head->translateTo(1 / 16.0f); - if (TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -5.5f / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, s); - } + if (TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -5.5f / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); - glPopMatrix(); - } + glPopMatrix(); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h index ab003fe68..62a14b0e7 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h @@ -4,14 +4,13 @@ class SnowManModel; -class SnowManRenderer : public MobRenderer -{ +class SnowManRenderer : public MobRenderer { private: - SnowManModel *model; + SnowManModel* model; public: - SnowManRenderer(); + SnowManRenderer(); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp index dcfa2fd1d..527e77034 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp @@ -3,59 +3,63 @@ #include "../Models/SpiderModel.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -SpiderRenderer::SpiderRenderer() : MobRenderer(new SpiderModel(), 1.0f) -{ - this->setArmor(new SpiderModel()); +SpiderRenderer::SpiderRenderer() : MobRenderer(new SpiderModel(), 1.0f) { + this->setArmor(new SpiderModel()); } -float SpiderRenderer::getFlipDegrees(std::shared_ptr spider) -{ - return 180; +float SpiderRenderer::getFlipDegrees(std::shared_ptr spider) { + return 180; } -int SpiderRenderer::prepareArmor(std::shared_ptr _spider, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr spider = std::dynamic_pointer_cast(_spider); +int SpiderRenderer::prepareArmor(std::shared_ptr _spider, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr spider = std::dynamic_pointer_cast(_spider); - if (layer!=0) return -1; - MemSect(31); - bindTexture(TN_MOB_SPIDER_EYES); // 4J was L"/mob/spider_eyes.png" - MemSect(0); - // 4J - changes brought forward from 1.8.2 - float br = 1.0f; // was (1-spider->getBrightness(1))*0.5f; + if (layer != 0) return -1; + MemSect(31); + bindTexture(TN_MOB_SPIDER_EYES); // 4J was L"/mob/spider_eyes.png" + MemSect(0); + // 4J - changes brought forward from 1.8.2 + float br = 1.0f; // was (1-spider->getBrightness(1))*0.5f; glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - // 4J - changes brought forward from 1.8.2 - glBlendFunc(GL_ONE, GL_ONE); - if (spider->isInvisible()) glDepthMask(false); - else glDepthMask(true); + // 4J - changes brought forward from 1.8.2 + glBlendFunc(GL_ONE, GL_ONE); + if (spider->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (SharedConstants::TEXTURE_LIGHTING) - { - // 4J - was 0xf0f0 but that looks like it is a mistake - maybe meant to be 0xf000f0 to enable both sky & block lighting? choosing 0x00f0 here instead - // as most likely replicates what the java game does, without breaking our lighting (which doesn't like UVs out of the 0 to 255 range) - int col = 0x00f0; + if (SharedConstants::TEXTURE_LIGHTING) { + // 4J - was 0xf0f0 but that looks like it is a mistake - maybe meant to + // be 0xf000f0 to enable both sky & block lighting? choosing 0x00f0 here + // instead as most likely replicates what the java game does, without + // breaking our lighting (which doesn't like UVs out of the 0 to 255 + // range) + int col = 0x00f0; int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); } - // 4J - this doesn't seem right - surely there should be an else in here? + // 4J - this doesn't seem right - surely there should be an else in here? glColor4f(1, 1, 1, br); return 1; } -void SpiderRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - float scale = mob->getModelScale(); - glScalef(scale, scale, scale); +void SpiderRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float scale = mob->getModelScale(); + glScalef(scale, scale, scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h index 7946ed467..cf7906472 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "MobRenderer.h" -class SpiderRenderer : public MobRenderer -{ +class SpiderRenderer : public MobRenderer { public: - SpiderRenderer(); + SpiderRenderer(); + protected: - virtual float getFlipDegrees(std::shared_ptr spider); + virtual float getFlipDegrees(std::shared_ptr spider); virtual int prepareArmor(std::shared_ptr _spider, int layer, float a); - void scale(std::shared_ptr _mob, float a); + void scale(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp index 12cb1a2c2..aa140dd6c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp @@ -2,19 +2,19 @@ #include "SquidRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -SquidRenderer::SquidRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +SquidRenderer::SquidRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void SquidRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void SquidRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} - -void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); float bodyXRot = (mob->xBodyRotO + (mob->xBodyRot - mob->xBodyRotO) * a); float bodyZRot = (mob->zBodyRotO + (mob->zBodyRot - mob->zBodyRotO) * a); @@ -26,10 +26,11 @@ void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, float b glTranslatef(0, -1.2f, 0); } -float SquidRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +float SquidRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - return mob->oldTentacleAngle + (mob->tentacleAngle - mob->oldTentacleAngle) * a; + return mob->oldTentacleAngle + + (mob->tentacleAngle - mob->oldTentacleAngle) * a; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h index 13270b5f1..0da4dddd8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h @@ -1,15 +1,16 @@ #pragma once #include "MobRenderer.h" -class SquidRenderer : public MobRenderer -{ +class SquidRenderer : public MobRenderer { public: - SquidRenderer(Model *model, float shadow); + SquidRenderer(Model* model, float shadow); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); protected: - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); virtual float getBob(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp index a9971f71d..f39b3297c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp @@ -7,123 +7,127 @@ #include "../../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "TheEndPortalRenderer.h" -void TheEndPortalRenderer::render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr table = std::dynamic_pointer_cast(_table); - float xx = (float) (tileEntityRenderDispatcher->xPlayer); - float yy = (float) (tileEntityRenderDispatcher->yPlayer); - float zz = (float) (tileEntityRenderDispatcher->zPlayer); +void TheEndPortalRenderer::render(std::shared_ptr _table, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr table = + std::dynamic_pointer_cast(_table); + float xx = (float)(tileEntityRenderDispatcher->xPlayer); + float yy = (float)(tileEntityRenderDispatcher->yPlayer); + float zz = (float)(tileEntityRenderDispatcher->zPlayer); - glDisable(GL_LIGHTING); + glDisable(GL_LIGHTING); - Random random(31100); + Random random(31100); - float hoff = (12) / 16.0f; - for (int i = 0; i < 16; i++) - { - glPushMatrix(); + float hoff = (12) / 16.0f; + for (int i = 0; i < 16; i++) { + glPushMatrix(); - float dist = (16 - (i)); - float sscale = 1 / 16.0f; + float dist = (16 - (i)); + float sscale = 1 / 16.0f; - float br = 1.0f / (dist + 1); - if (i == 0) - { - this->bindTexture(TN_MISC_TUNNEL); // 4J was "/misc/tunnel.png" - br = 0.1f; - dist = 65; - sscale = 1 / 8.0f; - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - if (i == 1) - { - this->bindTexture(TN_MISC_PARTICLEFIELD); // 4J was "/misc/particlefield.png" - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE); - sscale = 1 / 2.0f; - } + float br = 1.0f / (dist + 1); + if (i == 0) { + this->bindTexture(TN_MISC_TUNNEL); // 4J was "/misc/tunnel.png" + br = 0.1f; + dist = 65; + sscale = 1 / 8.0f; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + if (i == 1) { + this->bindTexture( + TN_MISC_PARTICLEFIELD); // 4J was "/misc/particlefield.png" + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); + sscale = 1 / 2.0f; + } - float dd = (float) -(y + hoff); - { - float ss1 = (float) (dd + Camera::yPlayerOffs); - float ss2 = (float) (dd + dist + Camera::yPlayerOffs); - float s = ss1 / ss2; - s = (float) (y + hoff) + s; + float dd = (float)-(y + hoff); + { + float ss1 = (float)(dd + Camera::yPlayerOffs); + float ss2 = (float)(dd + dist + Camera::yPlayerOffs); + float s = ss1 / ss2; + s = (float)(y + hoff) + s; - glTranslatef(xx, s, zz); - } - // 4J - note that the glTexGeni/glEnable calls don't actually do anything in our opengl wrapper version, everything is currently just inferred from the glTexGen calls. + glTranslatef(xx, s, zz); + } + // 4J - note that the glTexGeni/glEnable calls don't actually do + // anything in our opengl wrapper version, everything is currently just + // inferred from the glTexGen calls. - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); + glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGen(GL_S, GL_OBJECT_PLANE, getBuffer(1, 0, 0, 0)); - glTexGen(GL_T, GL_OBJECT_PLANE, getBuffer(0, 0, 1, 0)); - glTexGen(GL_R, GL_OBJECT_PLANE, getBuffer(0, 0, 0, 1)); - glTexGen(GL_Q, GL_EYE_PLANE, getBuffer(0, 1, 0, 0)); + glTexGen(GL_S, GL_OBJECT_PLANE, getBuffer(1, 0, 0, 0)); + glTexGen(GL_T, GL_OBJECT_PLANE, getBuffer(0, 0, 1, 0)); + glTexGen(GL_R, GL_OBJECT_PLANE, getBuffer(0, 0, 0, 1)); + glTexGen(GL_Q, GL_EYE_PLANE, getBuffer(0, 1, 0, 0)); - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - glEnable(GL_TEXTURE_GEN_R); - glEnable(GL_TEXTURE_GEN_Q); + glEnable(GL_TEXTURE_GEN_S); + glEnable(GL_TEXTURE_GEN_T); + glEnable(GL_TEXTURE_GEN_R); + glEnable(GL_TEXTURE_GEN_Q); + glPopMatrix(); + glMatrixMode(GL_TEXTURE); - glPopMatrix(); - glMatrixMode(GL_TEXTURE); + glPushMatrix(); + glLoadIdentity(); - glPushMatrix(); - glLoadIdentity(); + glTranslatef(0, (System::currentTimeMillis() % 700000 / 700000.0f), 0); + glScalef(sscale, sscale, sscale); + glTranslatef(0.5f, 0.5f, 0); + glRotatef((i * i * 4321 + i * 9) * 2.0f, 0, 0, 1); + glTranslatef(-0.5f, -0.5f, 0); + glTranslatef(-xx, -zz, -yy); + float ss1 = (float)(dd + Camera::yPlayerOffs); + glTranslatef(Camera::xPlayerOffs * dist / ss1, + Camera::zPlayerOffs * dist / ss1, -yy); - glTranslatef(0, (System::currentTimeMillis() % 700000 / 700000.0f), 0); - glScalef(sscale, sscale, sscale); - glTranslatef(0.5f, 0.5f, 0); - glRotatef((i * i * 4321 + i * 9) * 2.0f, 0, 0, 1); - glTranslatef(-0.5f, -0.5f, 0); - glTranslatef(-xx, -zz, -yy); - float ss1 = (float) (dd + Camera::yPlayerOffs); - glTranslatef(Camera::xPlayerOffs * dist / ss1, Camera::zPlayerOffs * dist / ss1, -yy); + Tesselator* t = Tesselator::getInstance(); + t->useProjectedTexture( + true); // 4J added - turns on both the generation of texture + // coordinates in the vertex shader & perspective divide of + // the texture coord in the pixel shader + t->begin(); - Tesselator *t = Tesselator::getInstance(); - t->useProjectedTexture(true); // 4J added - turns on both the generation of texture coordinates in the vertex shader & perspective divide of the texture coord in the pixel shader - t->begin(); + float r = random.nextFloat() * 0.5f + 0.1f; + float g = random.nextFloat() * 0.5f + 0.4f; + float b = random.nextFloat() * 0.5f + 0.5f; + if (i == 0) r = g = b = 1; + t->color(r * br, g * br, b * br, 1.0f); + t->vertex(x, y + hoff, z); + t->vertex(x, y + hoff, z + 1); + t->vertex(x + 1, y + hoff, z + 1); + t->vertex(x + 1, y + hoff, z); + t->end(); - float r = random.nextFloat() * 0.5f + 0.1f; - float g = random.nextFloat() * 0.5f + 0.4f; - float b = random.nextFloat() * 0.5f + 0.5f; - if (i == 0) r = g = b = 1; - t->color(r * br, g * br, b * br, 1.0f); - t->vertex(x, y + hoff, z); - t->vertex(x, y + hoff, z + 1); - t->vertex(x + 1, y + hoff, z + 1); - t->vertex(x + 1, y + hoff, z); - t->end(); + t->useProjectedTexture(false); // 4J added + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + } + glDisable(GL_BLEND); - t->useProjectedTexture(false); // 4J added - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - } - glDisable(GL_BLEND); - - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - glDisable(GL_TEXTURE_GEN_R); - glDisable(GL_TEXTURE_GEN_Q); - glEnable(GL_LIGHTING); + glDisable(GL_TEXTURE_GEN_S); + glDisable(GL_TEXTURE_GEN_T); + glDisable(GL_TEXTURE_GEN_R); + glDisable(GL_TEXTURE_GEN_Q); + glEnable(GL_LIGHTING); } -TheEndPortalRenderer::TheEndPortalRenderer() -{ - lb = MemoryTracker::createFloatBuffer(16); +TheEndPortalRenderer::TheEndPortalRenderer() { + lb = MemoryTracker::createFloatBuffer(16); } -FloatBuffer *TheEndPortalRenderer::getBuffer(float a, float b, float c, float d) -{ - lb->clear(); - lb->put(a)->put(b)->put(c)->put(d); - lb->flip(); - return lb; +FloatBuffer* TheEndPortalRenderer::getBuffer(float a, float b, float c, + float d) { + lb->clear(); + lb->put(a)->put(b)->put(c)->put(d); + lb->flip(); + return lb; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h index fe489275e..e2b9ed564 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h @@ -2,15 +2,16 @@ #include "TileEntityRenderer.h" -class TheEndPortalRenderer : public TileEntityRenderer -{ +class TheEndPortalRenderer : public TileEntityRenderer { public: - virtual void render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); + virtual void render(std::shared_ptr _table, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); - FloatBuffer *lb; + FloatBuffer* lb; - TheEndPortalRenderer(); + TheEndPortalRenderer(); private: - FloatBuffer *getBuffer(float a, float b, float c, float d); + FloatBuffer* getBuffer(float a, float b, float c, float d); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp index b55ff111a..9d82d0885 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp @@ -14,89 +14,89 @@ #include "SkullTileRenderer.h" #include "EnderChestRenderer.h" -TileEntityRenderDispatcher *TileEntityRenderDispatcher::instance = NULL; +TileEntityRenderDispatcher* TileEntityRenderDispatcher::instance = NULL; double TileEntityRenderDispatcher::xOff = 0; double TileEntityRenderDispatcher::yOff = 0; double TileEntityRenderDispatcher::zOff = 0; -void TileEntityRenderDispatcher::staticCtor() -{ - instance = new TileEntityRenderDispatcher(); +void TileEntityRenderDispatcher::staticCtor() { + instance = new TileEntityRenderDispatcher(); } -TileEntityRenderDispatcher::TileEntityRenderDispatcher() -{ - // 4J -a dded - font = NULL; +TileEntityRenderDispatcher::TileEntityRenderDispatcher() { + // 4J -a dded + font = NULL; textures = NULL; level = NULL; cameraEntity = nullptr; playerRotY = 0.0f; - playerRotX = 0.0f;; + playerRotX = 0.0f; + ; xPlayer = yPlayer = zPlayer = 0; - glEnable(GL_LIGHTING); - renderers[eTYPE_SIGNTILEENTITY] = new SignRenderer(); - renderers[eTYPE_MOBSPAWNERTILEENTITY] = new MobSpawnerRenderer(); - renderers[eTYPE_PISTONPIECEENTITY] = new PistonPieceRenderer(); - renderers[eTYPE_CHESTTILEENTITY] = new ChestRenderer(); - renderers[eTYPE_ENDERCHESTTILEENTITY] = new EnderChestRenderer(); - renderers[eTYPE_ENCHANTMENTTABLEENTITY] = new EnchantTableRenderer(); - renderers[eTYPE_THEENDPORTALTILEENTITY] = new TheEndPortalRenderer(); - renderers[eTYPE_SKULLTILEENTITY] = new SkullTileRenderer(); - renderers[eTYPE_FURNACETILEENTITY] = NULL; - glDisable(GL_LIGHTING); + glEnable(GL_LIGHTING); + renderers[eTYPE_SIGNTILEENTITY] = new SignRenderer(); + renderers[eTYPE_MOBSPAWNERTILEENTITY] = new MobSpawnerRenderer(); + renderers[eTYPE_PISTONPIECEENTITY] = new PistonPieceRenderer(); + renderers[eTYPE_CHESTTILEENTITY] = new ChestRenderer(); + renderers[eTYPE_ENDERCHESTTILEENTITY] = new EnderChestRenderer(); + renderers[eTYPE_ENCHANTMENTTABLEENTITY] = new EnchantTableRenderer(); + renderers[eTYPE_THEENDPORTALTILEENTITY] = new TheEndPortalRenderer(); + renderers[eTYPE_SKULLTILEENTITY] = new SkullTileRenderer(); + renderers[eTYPE_FURNACETILEENTITY] = NULL; + glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToTileRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) - { - if(it->second) it->second->init(this); + AUTO_VAR(itEnd, renderers.end()); + for (classToTileRendererMap::iterator it = renderers.begin(); it != itEnd; + it++) { + if (it->second) it->second->init(this); } } -TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) -{ - TileEntityRenderer *r = NULL; - //TileEntityRenderer *r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist +TileEntityRenderer* TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) { + TileEntityRenderer* r = NULL; + // TileEntityRenderer *r = renderers[e]; + AUTO_VAR(it, renderers.find(e)); // 4J Stu - The .at and [] accessors + // insert elements if they don't exist - if( it == renderers.end() ) - { - return NULL; - } - -/* 4J - not doing this hierarchical search anymore. We need to explicitly add renderers for any eINSTANCEOF type that we want to be able to render - if (it == renderers.end() && e != TileEntity::_class) - { - r = getRenderer(dynamic_cast( e->getSuperclass() )); - // 4J - added condition here to only add if a valid renderer found - if( r ) renderers.insert( classToTileRendererMap::value_type( e, r ) ); - //assert(false); + if (it == renderers.end()) { + return NULL; } - else if(it != renderers.end() && e != TileEntity::_class) - r = (*it).second; - */ - return it->second; + /* 4J - not doing this hierarchical search anymore. We need to explicitly + add renderers for any eINSTANCEOF type that we want to be able to render + if (it == renderers.end() && e != TileEntity::_class) + { + r = getRenderer(dynamic_cast( + e->getSuperclass() )); + // 4J - added condition here to only add if a valid renderer + found if( r ) renderers.insert( classToTileRendererMap::value_type( e, r + ) ); + //assert(false); + } + else if(it != renderers.end() && e != TileEntity::_class) + r = (*it).second; + */ + + return it->second; } -bool TileEntityRenderDispatcher::hasRenderer(std::shared_ptr e) -{ - return getRenderer(e) != NULL; +bool TileEntityRenderDispatcher::hasRenderer(std::shared_ptr e) { + return getRenderer(e) != NULL; } -TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(std::shared_ptr e) -{ +TileEntityRenderer* TileEntityRenderDispatcher::getRenderer( + std::shared_ptr e) { if (e == NULL) return NULL; return getRenderer(e->GetType()); } -void TileEntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, float a) -{ - if( this->level != level ) - { - setLevel( level ); - } +void TileEntityRenderDispatcher::prepare(Level* level, Textures* textures, + Font* font, + std::shared_ptr player, float a) { + if (this->level != level) { + setLevel(level); + } this->textures = textures; this->cameraEntity = player; this->font = font; @@ -109,21 +109,17 @@ void TileEntityRenderDispatcher::prepare(Level *level, Textures *textures, Font zPlayer = player->zOld + (player->z - player->zOld) * a; } -void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, bool setColor/*=true*/) -{ - if (e->distanceToSqr(xPlayer, yPlayer, zPlayer) < 64 * 64) - { - // 4J - changes brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { +void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, + bool setColor /*=true*/) { + if (e->distanceToSqr(xPlayer, yPlayer, zPlayer) < 64 * 64) { + // 4J - changes brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { int col = level->getLightColor(e->x, e->y, e->z, 0); int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); - } - else - { + } else { float br = level->getBrightness(e->x, e->y, e->z); glColor4f(br, br, br, 1); } @@ -131,34 +127,29 @@ void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, } } -void TileEntityRenderDispatcher::render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor/*=true*/, float alpha, bool useCompiled) -{ - TileEntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) - { +void TileEntityRenderDispatcher::render(std::shared_ptr entity, + double x, double y, double z, float a, + bool setColor /*=true*/, float alpha, + bool useCompiled) { + TileEntityRenderer* renderer = getRenderer(entity); + if (renderer != NULL) { renderer->render(entity, x, y, z, a, setColor, alpha, useCompiled); } } -void TileEntityRenderDispatcher::setLevel(Level *level) -{ - this->level = level; +void TileEntityRenderDispatcher::setLevel(Level* level) { + this->level = level; - for( AUTO_VAR(it, renderers.begin()); it != renderers.end(); it++ ) - { - if(it->second) it->second->onNewLevel(level); - } + for (AUTO_VAR(it, renderers.begin()); it != renderers.end(); it++) { + if (it->second) it->second->onNewLevel(level); + } } -double TileEntityRenderDispatcher::distanceToSqr(double x, double y, double z) -{ +double TileEntityRenderDispatcher::distanceToSqr(double x, double y, double z) { double xd = x - xPlayer; double yd = y - yPlayer; double zd = z - zPlayer; return xd * xd + yd * yd + zd * zd; } -Font *TileEntityRenderDispatcher::getFont() -{ - return font; -} +Font* TileEntityRenderDispatcher::getFont() { return font; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h index 01eaa3652..b23e78aa8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h @@ -6,41 +6,46 @@ class Level; class TileEntityRenderer; class TileEntity; -class TileEntityRenderDispatcher -{ +class TileEntityRenderDispatcher { public: - static void staticCtor(); // 4J added + static void staticCtor(); // 4J added private: - typedef std::unordered_map classToTileRendererMap; - classToTileRendererMap renderers; + typedef std::unordered_map + classToTileRendererMap; + classToTileRendererMap renderers; public: - static TileEntityRenderDispatcher *instance; + static TileEntityRenderDispatcher* instance; + private: - Font *font; + Font* font; public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; - Textures *textures; - Level *level; + Textures* textures; + Level* level; std::shared_ptr cameraEntity; float playerRotY; float playerRotX; double xPlayer, yPlayer, zPlayer; private: - TileEntityRenderDispatcher(); + TileEntityRenderDispatcher(); public: - TileEntityRenderer *getRenderer(eINSTANCEOF e); + TileEntityRenderer* getRenderer(eINSTANCEOF e); bool hasRenderer(std::shared_ptr e); - TileEntityRenderer * getRenderer(std::shared_ptr e); - void prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, float a); - void render(std::shared_ptr e, float a, bool setColor = true); - void render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor = true, float alpha=1.0f, bool useCompiled = true); // 4J Added useCompiled - void setLevel(Level *level); - double distanceToSqr(double x, double y, double z); - Font *getFont(); + TileEntityRenderer* getRenderer(std::shared_ptr e); + void prepare(Level* level, Textures* textures, Font* font, + std::shared_ptr player, float a); + void render(std::shared_ptr e, float a, bool setColor = true); + void render(std::shared_ptr entity, double x, double y, + double z, float a, bool setColor = true, float alpha = 1.0f, + bool useCompiled = true); // 4J Added useCompiled + void setLevel(Level* level); + double distanceToSqr(double x, double y, double z); + Font* getFont(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp index 62621fada..08af4cbb7 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp @@ -2,29 +2,26 @@ #include "TileEntityRenderer.h" #include "TileEntityRenderDispatcher.h" -void TileEntityRenderer::bindTexture(int resourceName) -{ - Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadTexture(resourceName)); +void TileEntityRenderer::bindTexture(int resourceName) { + Textures* t = tileEntityRenderDispatcher->textures; + if (t != NULL) t->bind(t->loadTexture(resourceName)); } -void TileEntityRenderer::bindTexture(const std::wstring& urlTexture, int backupTexture) -{ - Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadHttpTexture(urlTexture, backupTexture)); +void TileEntityRenderer::bindTexture(const std::wstring& urlTexture, + int backupTexture) { + Textures* t = tileEntityRenderDispatcher->textures; + if (t != NULL) t->bind(t->loadHttpTexture(urlTexture, backupTexture)); } -Level *TileEntityRenderer::getLevel() -{ - return tileEntityRenderDispatcher->level; +Level* TileEntityRenderer::getLevel() { + return tileEntityRenderDispatcher->level; } -void TileEntityRenderer::init(TileEntityRenderDispatcher *tileEntityRenderDispatcher) -{ - this->tileEntityRenderDispatcher = tileEntityRenderDispatcher; +void TileEntityRenderer::init( + TileEntityRenderDispatcher* tileEntityRenderDispatcher) { + this->tileEntityRenderDispatcher = tileEntityRenderDispatcher; } -Font *TileEntityRenderer::getFont() -{ - return tileEntityRenderDispatcher->getFont(); +Font* TileEntityRenderer::getFont() { + return tileEntityRenderDispatcher->getFont(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h index e9c4c1887..005ae2c26 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h @@ -5,19 +5,27 @@ class TileEntity; class Level; class Font; -class TileEntityRenderer -{ +class TileEntityRenderer { protected: - TileEntityRenderDispatcher *tileEntityRenderDispatcher; + TileEntityRenderDispatcher* tileEntityRenderDispatcher; + public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) = 0; // 4J added setColor param and alpha and useCompiled - virtual void onNewLevel(Level *level) {} + virtual void render(std::shared_ptr entity, double x, double y, + double z, float a, bool setColor, float alpha, + bool useCompiled) = 0; // 4J added setColor param and + // alpha and useCompiled + virtual void onNewLevel(Level* level) {} + protected: - void bindTexture(int resourceName); // 4J - changed from std::wstring to int - void bindTexture(const std::wstring& urlTexture, int backupTexture); // 4J - changed from std::wstring to int + void bindTexture( + int resourceName); // 4J - changed from std::wstring to int + void bindTexture( + const std::wstring& urlTexture, + int backupTexture); // 4J - changed from std::wstring to int private: - Level *getLevel(); + Level* getLevel(); + public: - virtual void init(TileEntityRenderDispatcher *tileEntityRenderDispatcher); - Font *getFont(); + virtual void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); + Font* getFont(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp index a5961ab02..0b082a170 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp @@ -15,432 +15,429 @@ bool TileRenderer::fancy = true; -const float smallUV = ( 1.0f / 16.0f ); +const float smallUV = (1.0f / 16.0f); -void TileRenderer::_init() -{ - fixedTexture = NULL; - xFlipTexture = false; - noCulling = false; - blsmooth = 1; - applyAmbienceOcclusion = false; - setColor = true; - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; +void TileRenderer::_init() { + fixedTexture = NULL; + xFlipTexture = false; + noCulling = false; + blsmooth = 1; + applyAmbienceOcclusion = false; + setColor = true; + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; - tileShapeX0 = 0.0; - tileShapeX1 = 0.0; - tileShapeY0 = 0.0; - tileShapeY1 = 0.0; - tileShapeZ0 = 0.0; - tileShapeZ1 = 0.0; - fixedShape = false; - smoothShapeLighting = false; - minecraft = Minecraft::GetInstance(); + tileShapeX0 = 0.0; + tileShapeX1 = 0.0; + tileShapeY0 = 0.0; + tileShapeY1 = 0.0; + tileShapeZ0 = 0.0; + tileShapeZ1 = 0.0; + fixedShape = false; + smoothShapeLighting = false; + minecraft = Minecraft::GetInstance(); - xMin = 0; - yMin = 0; - zMin = 0; - cache = NULL; + xMin = 0; + yMin = 0; + zMin = 0; + cache = NULL; } -bool TileRenderer::isTranslucentAt(LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - assert (id >= 0 ); - assert (id <= 32 * 32 * 32); - if( cache[id] & cache_isTranslucentAt_valid ) return ( ( cache[id] & cache_isTranslucentAt_flag ) == cache_isTranslucentAt_flag ); +bool TileRenderer::isTranslucentAt(LevelSource* level, int x, int y, int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + assert(id >= 0); + assert(id <= 32 * 32 * 32); + if (cache[id] & cache_isTranslucentAt_valid) + return ((cache[id] & cache_isTranslucentAt_flag) == + cache_isTranslucentAt_flag); - bool ret = Tile::transculent[level->getTile(x,y,z)]; + bool ret = Tile::transculent[level->getTile(x, y, z)]; - if( ret ) - { - cache[id] |= cache_isTranslucentAt_valid | cache_isTranslucentAt_flag; - } - else - { - cache[id] |= cache_isTranslucentAt_valid; - } - return ret; - } - } - return Tile::transculent[level->getTile(x,y,z)]; + if (ret) { + cache[id] |= + cache_isTranslucentAt_valid | cache_isTranslucentAt_flag; + } else { + cache[id] |= cache_isTranslucentAt_valid; + } + return ret; + } + } + return Tile::transculent[level->getTile(x, y, z)]; } -float TileRenderer::getShadeBrightness(Tile *tt, LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - if( cache[id] & cache_isSolidBlockingTile_valid ) return ( ( cache[id] & cache_isSolidBlockingTile_flag ) ? 0.2f : 1.0f); +float TileRenderer::getShadeBrightness(Tile* tt, LevelSource* level, int x, + int y, int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + if (cache[id] & cache_isSolidBlockingTile_valid) + return ((cache[id] & cache_isSolidBlockingTile_flag) ? 0.2f + : 1.0f); - bool isSolidBlocking = level->isSolidBlockingTile(x, y, z); + bool isSolidBlocking = level->isSolidBlockingTile(x, y, z); - if( isSolidBlocking ) - { - cache[id] |= cache_isSolidBlockingTile_valid | cache_isSolidBlockingTile_flag; - } - else - { - cache[id] |= cache_isSolidBlockingTile_valid; - } - return ( isSolidBlocking ? 0.2f : 1.0f); - } - } - return tt->getShadeBrightness(level, x, y, z); + if (isSolidBlocking) { + cache[id] |= cache_isSolidBlockingTile_valid | + cache_isSolidBlockingTile_flag; + } else { + cache[id] |= cache_isSolidBlockingTile_valid; + } + return (isSolidBlocking ? 0.2f : 1.0f); + } + } + return tt->getShadeBrightness(level, x, y, z); } -int TileRenderer::getLightColor( Tile *tt, LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - // Don't use the cache for liquid tiles, as they are the only type that seem to have their own implementation of getLightColor that actually is important. - // Without this we get patches of dark water where their lighting value is 0, it needs to pull in light from the tile above to work - if( ( tt->id >= Tile::water_Id ) && ( tt->id <= Tile::calmLava_Id ) ) return tt->getLightColor(level, x, y, z); +int TileRenderer::getLightColor(Tile* tt, LevelSource* level, int x, int y, + int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + // Don't use the cache for liquid tiles, as they are the only type + // that seem to have their own implementation of getLightColor that + // actually is important. Without this we get patches of dark water + // where their lighting value is 0, it needs to pull in light from + // the tile above to work + if ((tt->id >= Tile::water_Id) && (tt->id <= Tile::calmLava_Id)) + return tt->getLightColor(level, x, y, z); - if( cache[id] & cache_getLightColor_valid ) return cache[id] & cache_getLightColor_mask; + if (cache[id] & cache_getLightColor_valid) + return cache[id] & cache_getLightColor_mask; - // Not in cache. Have we got the tile type cached? We can pass this as a parameter to Tile::getLightColor( or -1 if we don't) so that underlying things - // don't have to get the tile again. - int tileId = -1; - int xx = x - xMin; - int zz = z - zMin; - if( ( xx >= 0 ) && ( xx <= 15 ) && ( zz >= 0 ) && ( zz <= 15 ) && ( y >= 0 ) && ( y < Level::maxBuildHeight ) ) - { - int indexY = y; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + // Not in cache. Have we got the tile type cached? We can pass this + // as a parameter to Tile::getLightColor( or -1 if we don't) so that + // underlying things don't have to get the tile again. + int tileId = -1; + int xx = x - xMin; + int zz = z - zMin; + if ((xx >= 0) && (xx <= 15) && (zz >= 0) && (zz <= 15) && + (y >= 0) && (y < Level::maxBuildHeight)) { + int indexY = y; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - unsigned char ucTileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ]; - // Tiles that were determined to be invisible (by being surrounded by solid stuff) will be set to 255 rather than their actual ID - if( ucTileId != 255 ) - { - tileId = (int)ucTileId; - } - } - int ret = tt->getLightColor(level, x, y, z, tileId); - cache[id] |= ( ( ret & cache_getLightColor_mask ) | cache_getLightColor_valid ); - return ret; - } - } - return tt->getLightColor(level, x, y, z); + unsigned char ucTileId = + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + // Tiles that were determined to be invisible (by being + // surrounded by solid stuff) will be set to 255 rather than + // their actual ID + if (ucTileId != 255) { + tileId = (int)ucTileId; + } + } + int ret = tt->getLightColor(level, x, y, z, tileId); + cache[id] |= + ((ret & cache_getLightColor_mask) | cache_getLightColor_valid); + return ret; + } + } + return tt->getLightColor(level, x, y, z); } -TileRenderer::TileRenderer( LevelSource* level, int xMin, int yMin, int zMin, unsigned char *tileIds ) -{ - this->level = level; - _init(); - this->xMin = xMin; - this->yMin = yMin; - this->zMin = zMin; - this->xMin2 = xMin-2; - this->yMin2 = yMin-2; - this->zMin2 = zMin-2; - this->tileIds = tileIds; - cache = new unsigned int[32*32*32]; - XMemSet(cache,0,32*32*32*sizeof(unsigned int)); +TileRenderer::TileRenderer(LevelSource* level, int xMin, int yMin, int zMin, + unsigned char* tileIds) { + this->level = level; + _init(); + this->xMin = xMin; + this->yMin = yMin; + this->zMin = zMin; + this->xMin2 = xMin - 2; + this->yMin2 = yMin - 2; + this->zMin2 = zMin - 2; + this->tileIds = tileIds; + cache = new unsigned int[32 * 32 * 32]; + XMemSet(cache, 0, 32 * 32 * 32 * sizeof(unsigned int)); } -TileRenderer::~TileRenderer() -{ - delete[] cache; //4jcraft, changed to [] +TileRenderer::~TileRenderer() { + delete[] cache; // 4jcraft, changed to [] } -TileRenderer::TileRenderer( LevelSource* level ) -{ - this->level = level; - _init(); +TileRenderer::TileRenderer(LevelSource* level) { + this->level = level; + _init(); } -TileRenderer::TileRenderer() -{ - this->level = NULL; - _init(); +TileRenderer::TileRenderer() { + this->level = NULL; + _init(); } -void TileRenderer::setFixedTexture( Icon *fixedTexture ) -{ - this->fixedTexture = fixedTexture; +void TileRenderer::setFixedTexture(Icon* fixedTexture) { + this->fixedTexture = fixedTexture; } -void TileRenderer::clearFixedTexture() -{ - this->fixedTexture = NULL; +void TileRenderer::clearFixedTexture() { this->fixedTexture = NULL; } + +bool TileRenderer::hasFixedTexture() { return fixedTexture != NULL; } + +void TileRenderer::setShape(float x0, float y0, float z0, float x1, float y1, + float z1) { + if (!fixedShape) { + tileShapeX0 = x0; + tileShapeX1 = x1; + tileShapeY0 = y0; + tileShapeY1 = y1; + tileShapeZ0 = z0; + tileShapeZ1 = z1; + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + } } -bool TileRenderer::hasFixedTexture() -{ - return fixedTexture != NULL; +void TileRenderer::setShape(Tile* tt) { + if (!fixedShape) { + tileShapeX0 = tt->getShapeX0(); + tileShapeX1 = tt->getShapeX1(); + tileShapeY0 = tt->getShapeY0(); + tileShapeY1 = tt->getShapeY1(); + tileShapeZ0 = tt->getShapeZ0(); + tileShapeZ1 = tt->getShapeZ1(); + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + } } -void TileRenderer::setShape(float x0, float y0, float z0, float x1, float y1, float z1) -{ - if (!fixedShape) - { - tileShapeX0 = x0; - tileShapeX1 = x1; - tileShapeY0 = y0; - tileShapeY1 = y1; - tileShapeZ0 = z0; - tileShapeZ1 = z1; - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); - } +void TileRenderer::setFixedShape(float x0, float y0, float z0, float x1, + float y1, float z1) { + tileShapeX0 = x0; + tileShapeX1 = x1; + tileShapeY0 = y0; + tileShapeY1 = y1; + tileShapeZ0 = z0; + tileShapeZ1 = z1; + fixedShape = true; + + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); } -void TileRenderer::setShape(Tile *tt) +void TileRenderer::clearFixedShape() { fixedShape = false; } + +void TileRenderer::tesselateInWorldFixedTexture( + Tile* tile, int x, int y, int z, + Icon* fixedTexture) // 4J renamed to differentiate from tesselateInWorld { - if (!fixedShape) - { - tileShapeX0 = tt->getShapeX0(); - tileShapeX1 = tt->getShapeX1(); - tileShapeY0 = tt->getShapeY0(); - tileShapeY1 = tt->getShapeY1(); - tileShapeZ0 = tt->getShapeZ0(); - tileShapeZ1 = tt->getShapeZ1(); - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); - } + this->setFixedTexture(fixedTexture); + tesselateInWorld(tile, x, y, z); + this->clearFixedTexture(); } -void TileRenderer::setFixedShape(float x0, float y0, float z0, float x1, float y1, float z1) +void TileRenderer::tesselateInWorldNoCulling( + Tile* tile, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - tileShapeX0 = x0; - tileShapeX1 = x1; - tileShapeY0 = y0; - tileShapeY1 = y1; - tileShapeZ0 = z0; - tileShapeZ1 = z1; - fixedShape = true; - - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + noCulling = true; + tesselateInWorld(tile, x, y, z, forceData); + noCulling = false; } -void TileRenderer::clearFixedShape() +bool TileRenderer::tesselateInWorld( + Tile* tt, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - fixedShape = false; + Tesselator* t = Tesselator::getInstance(); + int shape = tt->getRenderShape(); + tt->updateShape(level, x, y, z, forceData, forceEntity); + // AP - now that the culling is done earlier we don't need to call setShape + // until later on (only for SHAPE_BLOCK) + if (shape != Tile::SHAPE_BLOCK) { + setShape(tt); + } + t->setMipmapEnable(Tile::mipmapEnable[tt->id]); // 4J added + + bool retVal = false; + switch (shape) { + case Tile::SHAPE_BLOCK: { + // 4J - added these faceFlags so we can detect whether this block is + // going to have no visible faces and early out the original code + // checked noCulling and shouldRenderFace directly where faceFlags + // is used now AP - I moved this check from + // tesselateBlockInWorldWithAmbienceOcclusionTexLighting to be even + // earlier to speed up early rejection. The flags are then passed + // down to avoid creating them again. These changes in combination + // have more than halved the time it takes to reject a block on Vita + int faceFlags = 0; + if (noCulling) { + faceFlags = 0x3f; + } else { + // these block types can take advantage of a faster version of + // shouldRenderFace there are others but this is an easy check + // which covers the majority Note: This now covers rock, grass, + // dirt, stoneBrice, wood, sapling, unbreakable, sand, gravel, + // goldOre, ironOre, coalOre, treeTrunk + if ((tt->id <= Tile::unbreakable_Id) || + ((tt->id >= Tile::sand_Id) && + (tt->id <= Tile::treeTrunk_Id))) { + faceFlags = tt->getFaceFlags(level, x, y, z); + } else { + faceFlags |= + tt->shouldRenderFace(level, x, y - 1, z, 0) ? 0x01 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y + 1, z, 1) ? 0x02 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y, z - 1, 2) ? 0x04 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y, z + 1, 3) ? 0x08 : 0; + faceFlags |= + tt->shouldRenderFace(level, x - 1, y, z, 4) ? 0x10 : 0; + faceFlags |= + tt->shouldRenderFace(level, x + 1, y, z, 5) ? 0x20 : 0; + } + } + if (faceFlags == 0) { + retVal = false; + break; + } + + // now we need to set the shape + setShape(tt); + + retVal = tesselateBlockInWorld(tt, x, y, z, faceFlags); + } break; + case Tile::SHAPE_TREE: + retVal = tesselateTreeInWorld(tt, x, y, z); + break; + case Tile::SHAPE_QUARTZ: + retVal = tesselateQuartzInWorld(tt, x, y, z); + break; + case Tile::SHAPE_WATER: + retVal = tesselateWaterInWorld(tt, x, y, z); + break; + case Tile::SHAPE_CACTUS: + retVal = tesselateCactusInWorld(tt, x, y, z); + break; + case Tile::SHAPE_CROSS_TEXTURE: + retVal = tesselateCrossInWorld(tt, x, y, z); + break; + case Tile::SHAPE_STEM: + retVal = tesselateStemInWorld(tt, x, y, z); + break; + case Tile::SHAPE_LILYPAD: + retVal = tesselateLilypadInWorld(tt, x, y, z); + break; + case Tile::SHAPE_ROWS: + retVal = tesselateRowInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TORCH: + retVal = tesselateTorchInWorld(tt, x, y, z); + break; + case Tile::SHAPE_FIRE: + retVal = tesselateFireInWorld((FireTile*)tt, x, y, z); + break; + case Tile::SHAPE_RED_DUST: + retVal = tesselateDustInWorld(tt, x, y, z); + break; + case Tile::SHAPE_LADDER: + retVal = tesselateLadderInWorld(tt, x, y, z); + break; + case Tile::SHAPE_DOOR: + retVal = tesselateDoorInWorld(tt, x, y, z); + break; + case Tile::SHAPE_RAIL: + retVal = tesselateRailInWorld((RailTile*)tt, x, y, z); + break; + case Tile::SHAPE_STAIRS: + retVal = tesselateStairsInWorld((StairTile*)tt, x, y, z); + break; + case Tile::SHAPE_EGG: + retVal = tesselateEggInWorld((EggTile*)tt, x, y, z); + break; + case Tile::SHAPE_FENCE: + retVal = tesselateFenceInWorld((FenceTile*)tt, x, y, z); + break; + case Tile::SHAPE_WALL: + retVal = tesselateWallInWorld((WallTile*)tt, x, y, z); + break; + case Tile::SHAPE_LEVER: + retVal = tesselateLeverInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TRIPWIRE_SOURCE: + retVal = tesselateTripwireSourceInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TRIPWIRE: + retVal = tesselateTripwireInWorld(tt, x, y, z); + break; + case Tile::SHAPE_BED: + retVal = tesselateBedInWorld(tt, x, y, z); + break; + case Tile::SHAPE_DIODE: + retVal = tesselateDiodeInWorld((DiodeTile*)tt, x, y, z); + break; + case Tile::SHAPE_PISTON_BASE: + retVal = tesselatePistonBaseInWorld(tt, x, y, z, false, forceData); + break; + case Tile::SHAPE_PISTON_EXTENSION: + retVal = + tesselatePistonExtensionInWorld(tt, x, y, z, true, forceData); + break; + case Tile::SHAPE_IRON_FENCE: + retVal = tesselateThinFenceInWorld((ThinFenceTile*)tt, x, y, z); + break; + case Tile::SHAPE_VINE: + retVal = tesselateVineInWorld(tt, x, y, z); + break; + case Tile::SHAPE_FENCE_GATE: + retVal = tesselateFenceGateInWorld((FenceGateTile*)tt, x, y, z); + break; + case Tile::SHAPE_CAULDRON: + retVal = tesselateCauldronInWorld((CauldronTile*)tt, x, y, z); + break; + case Tile::SHAPE_FLOWER_POT: + retVal = tesselateFlowerPotInWorld((FlowerPotTile*)tt, x, y, z); + break; + case Tile::SHAPE_ANVIL: + retVal = tesselateAnvilInWorld((AnvilTile*)tt, x, y, z); + break; + case Tile::SHAPE_BREWING_STAND: + retVal = + tesselateBrewingStandInWorld((BrewingStandTile*)tt, x, y, z); + break; + case Tile::SHAPE_PORTAL_FRAME: + retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile*)tt, + x, y, z); + break; + case Tile::SHAPE_COCOA: + retVal = tesselateCocoaInWorld((CocoaTile*)tt, x, y, z); + break; + }; + + t->setMipmapEnable(true); // 4J added + return retVal; } -void TileRenderer::tesselateInWorldFixedTexture( Tile* tile, int x, int y, int z, Icon *fixedTexture ) // 4J renamed to differentiate from tesselateInWorld -{ - this->setFixedTexture(fixedTexture); - tesselateInWorld( tile, x, y, z ); - this->clearFixedTexture(); -} - -void TileRenderer::tesselateInWorldNoCulling( Tile* tile, int x, int y, int z, int forceData, - std::shared_ptr< TileEntity > forceEntity ) // 4J added forceData, forceEntity param -{ - noCulling = true; - tesselateInWorld( tile, x, y, z, forceData ); - noCulling = false; -} - -bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceData, - std::shared_ptr< TileEntity > forceEntity ) // 4J added forceData, forceEntity param -{ - Tesselator* t = Tesselator::getInstance(); - int shape = tt->getRenderShape(); - tt->updateShape( level, x, y, z, forceData, forceEntity ); - // AP - now that the culling is done earlier we don't need to call setShape until later on (only for SHAPE_BLOCK) - if( shape != Tile::SHAPE_BLOCK ) - { - setShape(tt); - } - t->setMipmapEnable( Tile::mipmapEnable[tt->id] ); // 4J added - - bool retVal = false; - switch(shape) - { - case Tile::SHAPE_BLOCK: - { - // 4J - added these faceFlags so we can detect whether this block is going to have no visible faces and early out - // the original code checked noCulling and shouldRenderFace directly where faceFlags is used now - // AP - I moved this check from tesselateBlockInWorldWithAmbienceOcclusionTexLighting to be even earlier to speed up early rejection. - // The flags are then passed down to avoid creating them again. - // These changes in combination have more than halved the time it takes to reject a block on Vita - int faceFlags = 0; - if ( noCulling ) - { - faceFlags = 0x3f; - } - else - { - // these block types can take advantage of a faster version of shouldRenderFace - // there are others but this is an easy check which covers the majority - // Note: This now covers rock, grass, dirt, stoneBrice, wood, sapling, unbreakable, sand, gravel, goldOre, ironOre, coalOre, treeTrunk - if( ( tt->id <= Tile::unbreakable_Id ) || - ( ( tt->id >= Tile::sand_Id ) && ( tt->id <= Tile::treeTrunk_Id ) ) ) - { - faceFlags = tt->getFaceFlags( level, x, y, z ); - } - else - { - faceFlags |= tt->shouldRenderFace( level, x, y - 1, z, 0 ) ? 0x01 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y + 1, z, 1 ) ? 0x02 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y, z - 1, 2 ) ? 0x04 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y, z + 1, 3 ) ? 0x08 : 0; - faceFlags |= tt->shouldRenderFace( level, x - 1, y, z, 4 ) ? 0x10 : 0; - faceFlags |= tt->shouldRenderFace( level, x + 1, y, z, 5 ) ? 0x20 : 0; - } - } - if ( faceFlags == 0 ) - { - retVal = false; - break; - } - - // now we need to set the shape - setShape(tt); - - retVal = tesselateBlockInWorld( tt, x, y, z, faceFlags ); - } - break; - case Tile::SHAPE_TREE: - retVal = tesselateTreeInWorld(tt, x, y, z); - break; - case Tile::SHAPE_QUARTZ: - retVal = tesselateQuartzInWorld(tt, x, y, z); - break; - case Tile::SHAPE_WATER: - retVal = tesselateWaterInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_CACTUS: - retVal = tesselateCactusInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_CROSS_TEXTURE: - retVal = tesselateCrossInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_STEM: - retVal = tesselateStemInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_LILYPAD: - retVal = tesselateLilypadInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_ROWS: - retVal = tesselateRowInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_TORCH: - retVal = tesselateTorchInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_FIRE: - retVal = tesselateFireInWorld( (FireTile *)tt, x, y, z ); - break; - case Tile::SHAPE_RED_DUST: - retVal = tesselateDustInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_LADDER: - retVal = tesselateLadderInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_DOOR: - retVal = tesselateDoorInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_RAIL: - retVal = tesselateRailInWorld( ( RailTile* )tt, x, y, z ); - break; - case Tile::SHAPE_STAIRS: - retVal = tesselateStairsInWorld( (StairTile *)tt, x, y, z ); - break; - case Tile::SHAPE_EGG: - retVal = tesselateEggInWorld((EggTile*) tt, x, y, z); - break; - case Tile::SHAPE_FENCE: - retVal = tesselateFenceInWorld( ( FenceTile* )tt, x, y, z ); - break; - case Tile::SHAPE_WALL: - retVal = tesselateWallInWorld( (WallTile *) tt, x, y, z); - break; - case Tile::SHAPE_LEVER: - retVal = tesselateLeverInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_TRIPWIRE_SOURCE: - retVal = tesselateTripwireSourceInWorld(tt, x, y, z); - break; - case Tile::SHAPE_TRIPWIRE: - retVal = tesselateTripwireInWorld(tt, x, y, z); - break; - case Tile::SHAPE_BED: - retVal = tesselateBedInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_DIODE: - retVal = tesselateDiodeInWorld( (DiodeTile *)tt, x, y, z ); - break; - case Tile::SHAPE_PISTON_BASE: - retVal = tesselatePistonBaseInWorld( tt, x, y, z, false, forceData ); - break; - case Tile::SHAPE_PISTON_EXTENSION: - retVal = tesselatePistonExtensionInWorld( tt, x, y, z, true, forceData ); - break; - case Tile::SHAPE_IRON_FENCE: - retVal = tesselateThinFenceInWorld( ( ThinFenceTile* )tt, x, y, z ); - break; - case Tile::SHAPE_VINE: - retVal = tesselateVineInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_FENCE_GATE: - retVal = tesselateFenceGateInWorld( ( FenceGateTile* )tt, x, y, z ); - break; - case Tile::SHAPE_CAULDRON: - retVal = tesselateCauldronInWorld((CauldronTile* ) tt, x, y, z); - break; - case Tile::SHAPE_FLOWER_POT: - retVal = tesselateFlowerPotInWorld((FlowerPotTile *) tt, x, y, z); - break; - case Tile::SHAPE_ANVIL: - retVal = tesselateAnvilInWorld((AnvilTile *) tt, x, y, z); - break; - case Tile::SHAPE_BREWING_STAND: - retVal = tesselateBrewingStandInWorld((BrewingStandTile* ) tt, x, y, z); - break; - case Tile::SHAPE_PORTAL_FRAME: - retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile *)tt, x, y, z); - break; - case Tile::SHAPE_COCOA: - retVal = tesselateCocoaInWorld((CocoaTile *) tt, x, y, z); - break; - }; - - - t->setMipmapEnable( true ); // 4J added - return retVal; - -} - -bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile* tt, + int x, int y, int z) { int data = level->getData(x, y, z); int direction = data & 3; - if (direction == Direction::SOUTH) - { + if (direction == Direction::SOUTH) { upFlip = FLIP_180; - } - else if (direction == Direction::EAST) - { + } else if (direction == Direction::EAST) { upFlip = FLIP_CW; - } - else if (direction == Direction::WEST) - { + } else if (direction == Direction::WEST) { upFlip = FLIP_CCW; } - if (!TheEndPortalFrameTile::hasEye(data)) - { + if (!TheEndPortalFrameTile::hasEye(data)) { setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); tesselateBlockInWorld(tt, x, y, z); @@ -448,283 +445,263 @@ bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int return true; } - noCulling = true; + noCulling = true; setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); tesselateBlockInWorld(tt, x, y, z); setFixedTexture(tt->getEye()); - setShape(4.0f / 16.0f, 13.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, 1, 12.0f / 16.0f); + setShape(4.0f / 16.0f, 13.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, 1, + 12.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - noCulling = false; + noCulling = false; clearFixedTexture(); upFlip = FLIP_NONE; return true; } -bool TileRenderer::tesselateBedInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateBedInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); - int direction = BedTile::getDirection( data ); - bool isHead = BedTile::isHeadPiece( data ); + int data = level->getData(x, y, z); + int direction = BedTile::getDirection(data); + bool isHead = BedTile::isHeadPiece(data); - float c10 = 0.5f; - float c11 = 1.0f; - float c2 = 0.8f; - float c3 = 0.6f; + float c10 = 0.5f; + float c11 = 1.0f; + float c2 = 0.8f; + float c3 = 0.6f; - float r11 = c11; - float g11 = c11; - float b11 = c11; + float r11 = c11; + float g11 = c11; + float b11 = c11; - float r10 = c10; - float r2 = c2; - float r3 = c3; + float r10 = c10; + float r2 = c2; + float r3 = c3; - float g10 = c10; - float g2 = c2; - float g3 = c3; + float g10 = c10; + float g2 = c2; + float g3 = c3; - float b10 = c10; - float b2 = c2; - float b3 = c3; + float b10 = c10; + float b2 = c2; + float b3 = c3; - // 4J - change brought forward from 1.8.2 - int centerColor; - float centerBrightness; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + // 4J - change brought forward from 1.8.2 + int centerColor; + float centerBrightness; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - // render wooden underside - { - // 4J - change brought forward from 1.8.2 - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( centerColor ); - t->color( r10, g10, b10 ); - } - else - { - t->color( r10 * centerBrightness, g10 * centerBrightness, b10 * centerBrightness ); - } + // render wooden underside + { + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(centerColor); + t->color(r10, g10, b10); + } else { + t->color(r10 * centerBrightness, g10 * centerBrightness, + b10 * centerBrightness); + } - Icon *tex = getTexture( tt, level, x, y, z, Facing::DOWN ); + Icon* tex = getTexture(tt, level, x, y, z, Facing::DOWN); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float x0 = x + tileShapeX0; - float x1 = x + tileShapeX1; - float y0 = y + tileShapeY0 + 3.0 / 16.0; - float z0 = z + tileShapeZ0; - float z1 = z + tileShapeZ1; + float x0 = x + tileShapeX0; + float x1 = x + tileShapeX1; + float y0 = y + tileShapeY0 + 3.0 / 16.0; + float z0 = z + tileShapeZ0; + float z1 = z + tileShapeZ1; - t->vertexUV( x0 , y0 , z1 , u0 , v1 ); - t->vertexUV( x0 , y0 , z0 , u0 , v0 ); - t->vertexUV( x1 , y0 , z0 , u1 , v0 ); - t->vertexUV( x1 , y0 , z1 , u1 , v1 ); - } + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v1); + } - // render bed top - // 4J - change brought forward from 1.8.2 - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float brightness = tt->getBrightness( level, x, y + 1, z ); - t->color( r11 * brightness, g11 * brightness, b11 * brightness ); - } + // render bed top + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float brightness = tt->getBrightness(level, x, y + 1, z); + t->color(r11 * brightness, g11 * brightness, b11 * brightness); + } - Icon *tex = getTexture( tt, level, x, y, z, Facing::UP ); + Icon* tex = getTexture(tt, level, x, y, z, Facing::UP); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float topLeftU = u0; - float topRightU = u1; - float topLeftV = v0; - float topRightV = v0; - float bottomLeftU = u0; - float bottomRightU = u1; - float bottomLeftV = v1; - float bottomRightV = v1; + float topLeftU = u0; + float topRightU = u1; + float topLeftV = v0; + float topRightV = v0; + float bottomLeftU = u0; + float bottomRightU = u1; + float bottomLeftV = v1; + float bottomRightV = v1; - if ( direction == Direction::SOUTH ) - { - // rotate 90 degrees clockwise - topRightU = u0; - topLeftV = v1; - bottomLeftU = u1; - bottomRightV = v0; - } - else if ( direction == Direction::NORTH ) - { - // rotate 90 degrees counter-clockwise - topLeftU = u1; - topRightV = v1; - bottomRightU = u0; - bottomLeftV = v0; - } - else if ( direction == Direction::EAST ) - { - // rotate 180 degrees - topLeftU = u1; - topRightV = v1; - bottomRightU = u0; - bottomLeftV = v0; - topRightU = u0; - topLeftV = v1; - bottomLeftU = u1; - bottomRightV = v0; - } + if (direction == Direction::SOUTH) { + // rotate 90 degrees clockwise + topRightU = u0; + topLeftV = v1; + bottomLeftU = u1; + bottomRightV = v0; + } else if (direction == Direction::NORTH) { + // rotate 90 degrees counter-clockwise + topLeftU = u1; + topRightV = v1; + bottomRightU = u0; + bottomLeftV = v0; + } else if (direction == Direction::EAST) { + // rotate 180 degrees + topLeftU = u1; + topRightV = v1; + bottomRightU = u0; + bottomLeftV = v0; + topRightU = u0; + topLeftV = v1; + bottomLeftU = u1; + bottomRightV = v0; + } - float x0 = x + tileShapeX0; - float x1 = x + tileShapeX1; - float y1 = y + tileShapeY1; - float z0 = z + tileShapeZ0; - float z1 = z + tileShapeZ1; + float x0 = x + tileShapeX0; + float x1 = x + tileShapeX1; + float y1 = y + tileShapeY1; + float z0 = z + tileShapeZ0; + float z1 = z + tileShapeZ1; - t->vertexUV( x1 , y1 , z1 , bottomLeftU ,bottomLeftV ); - t->vertexUV( x1 , y1 , z0 , topLeftU , topLeftV ); - t->vertexUV( x0 , y1 , z0 , topRightU ,topRightV ); - t->vertexUV( x0 , y1 , z1 , bottomRightU ,bottomRightV ); + t->vertexUV(x1, y1, z1, bottomLeftU, bottomLeftV); + t->vertexUV(x1, y1, z0, topLeftU, topLeftV); + t->vertexUV(x0, y1, z0, topRightU, topRightV); + t->vertexUV(x0, y1, z1, bottomRightU, bottomRightV); - // determine which edge to skip (the one between foot and head piece) - int skipEdge = Direction::DIRECTION_FACING[direction]; - if ( isHead ) - { - skipEdge = Direction::DIRECTION_FACING[Direction::DIRECTION_OPPOSITE[direction]]; - } - // and which edge to x-flip - int flipEdge = Facing::WEST; - switch ( direction ) - { - case Direction::NORTH: - break; - case Direction::SOUTH: - flipEdge = Facing::EAST; - break; - case Direction::EAST: - flipEdge = Facing::NORTH; - break; - case Direction::WEST: - flipEdge = Facing::SOUTH; - break; - } + // determine which edge to skip (the one between foot and head piece) + int skipEdge = Direction::DIRECTION_FACING[direction]; + if (isHead) { + skipEdge = Direction::DIRECTION_FACING + [Direction::DIRECTION_OPPOSITE[direction]]; + } + // and which edge to x-flip + int flipEdge = Facing::WEST; + switch (direction) { + case Direction::NORTH: + break; + case Direction::SOUTH: + flipEdge = Facing::EAST; + break; + case Direction::EAST: + flipEdge = Facing::NORTH; + break; + case Direction::WEST: + flipEdge = Facing::SOUTH; + break; + } - if ( ( skipEdge != Facing::NORTH ) && ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, Facing::NORTH ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - xFlipTexture = flipEdge == Facing::NORTH; - renderNorth( tt, x, y, z, getTexture( tt, level, x, y, z, 2 ) ); - } + if ((skipEdge != Facing::NORTH) && + (noCulling || + tt->shouldRenderFace(level, x, y, z - 1, Facing::NORTH))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + xFlipTexture = flipEdge == Facing::NORTH; + renderNorth(tt, x, y, z, getTexture(tt, level, x, y, z, 2)); + } - if ( ( skipEdge != Facing::SOUTH ) && ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, Facing::SOUTH ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if ((skipEdge != Facing::SOUTH) && + (noCulling || + tt->shouldRenderFace(level, x, y, z + 1, Facing::SOUTH))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - xFlipTexture = flipEdge == Facing::SOUTH; - renderSouth( tt, x, y, z, getTexture( tt, level, x, y, z, 3 ) ); - } + xFlipTexture = flipEdge == Facing::SOUTH; + renderSouth(tt, x, y, z, getTexture(tt, level, x, y, z, 3)); + } - if ( ( skipEdge != Facing::WEST ) && ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, Facing::WEST ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - xFlipTexture = flipEdge == Facing::WEST; - renderWest( tt, x, y, z, getTexture( tt, level, x, y, z, 4 ) ); - } - - if ( ( skipEdge != Facing::EAST ) && ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, Facing::EAST ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - xFlipTexture = flipEdge == Facing::EAST; - renderEast( tt, x, y, z, getTexture( tt, level, x, y, z, 5 ) ); - } - xFlipTexture = false; - return true; + if ((skipEdge != Facing::WEST) && + (noCulling || tt->shouldRenderFace(level, x - 1, y, z, Facing::WEST))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + xFlipTexture = flipEdge == Facing::WEST; + renderWest(tt, x, y, z, getTexture(tt, level, x, y, z, 4)); + } + if ((skipEdge != Facing::EAST) && + (noCulling || tt->shouldRenderFace(level, x + 1, y, z, Facing::EAST))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + xFlipTexture = flipEdge == Facing::EAST; + renderEast(tt, x, y, z, getTexture(tt, level, x, y, z, 5)); + } + xFlipTexture = false; + return true; } -bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile* tt, int x, + int y, int z) { // bounding box first - setShape(7.0f / 16.0f, 0.0f, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, 9.0f / 16.0f); + setShape(7.0f / 16.0f, 0.0f, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, + 9.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); setFixedTexture(tt->getBaseTexture()); - setShape(9.0f / 16.0f, 0.0f, 5.0f / 16.0f, 15.0f / 16.0f, 2 / 16.0f, 11.0f / 16.0f); + setShape(9.0f / 16.0f, 0.0f, 5.0f / 16.0f, 15.0f / 16.0f, 2 / 16.0f, + 11.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - setShape(2.0f / 16.0f, 0.0f, 1.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, 7.0f / 16.0f); + setShape(2.0f / 16.0f, 0.0f, 1.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, + 7.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - setShape(2.0f / 16.0f, 0.0f, 9.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, 15.0f / 16.0f); + setShape(2.0f / 16.0f, 0.0f, 9.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, + 15.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); clearFixedTexture(); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float br; - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { t->tex2(getLightColor(tt, level, x, y, z)); br = 1; - } - else - { + } else { br = tt->getBrightness(level, x, y, z); } int col = tt->getColor(level, x, y, z); @@ -734,30 +711,27 @@ bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int t->color(br * r, br * g, br * b); - Icon *tex = getTexture(tt, 0, 0); + Icon* tex = getTexture(tt, 0, 0); - if (hasFixedTexture()) tex = fixedTexture; - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); int data = level->getData(x, y, z); - for (int arm = 0; arm < 3; arm++) - { - + for (int arm = 0; arm < 3; arm++) { float angle = arm * PI * 2.0f / 3.0f + PI * 0.5f; - float u0 = tex->getU(8, true); - float u1 = tex->getU1(true); - if ((data & (1 << arm)) != 0) - { + float u0 = tex->getU(8, true); + float u1 = tex->getU1(true); + if ((data & (1 << arm)) != 0) { u1 = tex->getU0(true); } - float x0 = x + 8.0f / 16.0f; - float x1 = x + 8.0f / 16.0f + sin(angle) * 8.0f / 16.0f; - float z0 = z + 8.0f / 16.0f; - float z1 = z + 8.0f / 16.0f + cos(angle) * 8.0f / 16.0f; + float x0 = x + 8.0f / 16.0f; + float x1 = x + 8.0f / 16.0f + sin(angle) * 8.0f / 16.0f; + float z0 = z + 8.0f / 16.0f; + float z1 = z + 8.0f / 16.0f + cos(angle) * 8.0f / 16.0f; t->vertexUV(x0, y + 1.0f, z0, u0, v0); t->vertexUV(x0, y + 0.0f, z0, u0, v1); @@ -775,21 +749,18 @@ bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int return true; } -bool TileRenderer::tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateCauldronInWorld(CauldronTile* tt, int x, int y, + int z) { // bounding box first tesselateBlockInWorld(tt, x, y, z); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float br; - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { t->tex2(getLightColor(tt, level, x, y, z)); br = 1; - } - else - { + } else { br = tt->getBrightness(level, x, y, z); } int col = tt->getColor(level, x, y, z); @@ -800,3034 +771,3032 @@ bool TileRenderer::tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int t->color(br * r, br * g, br * b); // render inside - Icon *insideTex = tt->getTexture(Facing::NORTH); - const float cWidth = ( 2.0f / 16.0f ) - ( 1.0f / 128.0f ); // 4J - Moved by 1/128th (smallest movement possible with our vertex storage) to remove gap at edge of cauldron + Icon* insideTex = tt->getTexture(Facing::NORTH); + const float cWidth = + (2.0f / 16.0f) - + (1.0f / + 128.0f); // 4J - Moved by 1/128th (smallest movement possible with our + // vertex storage) to remove gap at edge of cauldron renderEast(tt, x - 1.0f + cWidth, y, z, insideTex); renderWest(tt, x + 1.0f - cWidth, y, z, insideTex); renderSouth(tt, x, y, z - 1.0f + cWidth, insideTex); renderNorth(tt, x, y, z + 1.0f - cWidth, insideTex); - Icon *bottomTex = CauldronTile::getTexture(CauldronTile::TEXTURE_INSIDE); + Icon* bottomTex = CauldronTile::getTexture(CauldronTile::TEXTURE_INSIDE); renderFaceUp(tt, x, y - 1.0f + 4.0f / 16.0f, z, bottomTex); renderFaceDown(tt, x, y + 1.0f - 12.0f / 16.0f, z, bottomTex); int waterLevel = level->getData(x, y, z); - if (waterLevel > 0) - { - Icon *liquidTex = LiquidTile::getTexture(LiquidTile::TEXTURE_WATER_STILL); + if (waterLevel > 0) { + Icon* liquidTex = + LiquidTile::getTexture(LiquidTile::TEXTURE_WATER_STILL); - if (waterLevel > 3) - { + if (waterLevel > 3) { waterLevel = 3; } - renderFaceUp(tt, x, y - 1.0f + (6.0f + waterLevel * 3.0f) / 16.0f, z, liquidTex); + renderFaceUp(tt, x, y - 1.0f + (6.0f + waterLevel * 3.0f) / 16.0f, z, + liquidTex); } return true; - } -bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, int z) -{ - // bounding box first - tesselateBlockInWorld(tt, x, y, z); +bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile* tt, int x, int y, + int z) { + // bounding box first + tesselateBlockInWorld(tt, x, y, z); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - float br; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - br = 1; - } - else - { - br = tt->getBrightness(level, x, y, z); - } - int col = tt->getColor(level, x, y, z); - Icon *tex = getTexture(tt, 0); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + Icon* tex = getTexture(tt, 0); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if (GameRenderer::anaglyph3d) - { - float cr = (r * 30 + g * 59 + b * 11) / 100; - float cg = (r * 30 + g * 70) / (100); - float cb = (r * 30 + b * 70) / (100); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color(br * r, br * g, br * b); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - // render inside + // render inside - float halfWidth = (6.0f / 16.0f) / 2 - 0.001f; - renderEast(tt, x - 0.5f + halfWidth, y, z, tex); - renderWest(tt, x + 0.5f - halfWidth, y, z, tex); - renderSouth(tt, x, y, z - 0.5f + halfWidth, tex); - renderNorth(tt, x, y, z + 0.5f - halfWidth, tex); + float halfWidth = (6.0f / 16.0f) / 2 - 0.001f; + renderEast(tt, x - 0.5f + halfWidth, y, z, tex); + renderWest(tt, x + 0.5f - halfWidth, y, z, tex); + renderSouth(tt, x, y, z - 0.5f + halfWidth, tex); + renderNorth(tt, x, y, z + 0.5f - halfWidth, tex); - renderFaceUp(tt, x, y - 0.5f + halfWidth + 3.0f / 16.0f, z, getTexture(Tile::dirt)); + renderFaceUp(tt, x, y - 0.5f + halfWidth + 3.0f / 16.0f, z, + getTexture(Tile::dirt)); - int type = level->getData(x, y, z); + int type = level->getData(x, y, z); - if (type != 0) - { - float xOff = 0; - float yOff = 4; - float zOff = 0; - Tile *plant = NULL; + if (type != 0) { + float xOff = 0; + float yOff = 4; + float zOff = 0; + Tile* plant = NULL; - switch (type) - { - case FlowerPotTile::TYPE_FLOWER_RED: - plant = Tile::rose; - break; - case FlowerPotTile::TYPE_FLOWER_YELLOW: - plant = Tile::flower; - break; - case FlowerPotTile::TYPE_MUSHROOM_BROWN: - plant = Tile::mushroom1; - break; - case FlowerPotTile::TYPE_MUSHROOM_RED: - plant = Tile::mushroom2; - break; - } + switch (type) { + case FlowerPotTile::TYPE_FLOWER_RED: + plant = Tile::rose; + break; + case FlowerPotTile::TYPE_FLOWER_YELLOW: + plant = Tile::flower; + break; + case FlowerPotTile::TYPE_MUSHROOM_BROWN: + plant = Tile::mushroom1; + break; + case FlowerPotTile::TYPE_MUSHROOM_RED: + plant = Tile::mushroom2; + break; + } - t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); + t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); - if (plant != NULL) - { - tesselateInWorld(plant, x, y, z); - } - else - { - if (type == FlowerPotTile::TYPE_CACTUS) - { + if (plant != NULL) { + tesselateInWorld(plant, x, y, z); + } else { + if (type == FlowerPotTile::TYPE_CACTUS) { + // Force drawing of all faces else the cactus misses faces + // when a block is adjacent + noCulling = true; - // Force drawing of all faces else the cactus misses faces - // when a block is adjacent - noCulling = true; + float halfSize = 0.25f / 2; + setShape(0.5f - halfSize, 0.0f, 0.5f - halfSize, + 0.5f + halfSize, 0.25f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); + setShape(0.5f - halfSize, 0.25f, 0.5f - halfSize, + 0.5f + halfSize, 0.5f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); + setShape(0.5f - halfSize, 0.5f, 0.5f - halfSize, + 0.5f + halfSize, 0.75f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); - float halfSize = 0.25f / 2; - setShape(0.5f - halfSize, 0.0f, 0.5f - halfSize, 0.5f + halfSize, 0.25f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); - setShape(0.5f - halfSize, 0.25f, 0.5f - halfSize, 0.5f + halfSize, 0.5f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); - setShape(0.5f - halfSize, 0.5f, 0.5f - halfSize, 0.5f + halfSize, 0.75f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); + noCulling = false; - noCulling = false; + setShape(0, 0, 0, 1, 1, 1); + } else if (type == FlowerPotTile::TYPE_SAPLING_DEFAULT) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_DEFAULT, x, + y, z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_BIRCH) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_BIRCH, x, y, + z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_EVERGREEN) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_EVERGREEN, x, + y, z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_JUNGLE) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_JUNGLE, x, y, + z, 0.75f); + } else if (type == FlowerPotTile::TYPE_FERN) { + col = Tile::tallgrass->getColor(level, x, y, z); + r = ((col >> 16) & 0xff) / 255.0f; + g = ((col >> 8) & 0xff) / 255.0f; + b = ((col) & 0xff) / 255.0f; + t->color(br * r, br * g, br * b); + tesselateCrossTexture(Tile::tallgrass, TallGrass::FERN, x, y, z, + 0.75f); + } else if (type == FlowerPotTile::TYPE_DEAD_BUSH) { + tesselateCrossTexture(Tile::deadBush, TallGrass::FERN, x, y, z, + 0.75f); + } + } - setShape(0, 0, 0, 1, 1, 1); - } - else if (type == FlowerPotTile::TYPE_SAPLING_DEFAULT) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_DEFAULT, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_BIRCH) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_BIRCH, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_EVERGREEN) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_EVERGREEN, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_JUNGLE) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_JUNGLE, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_FERN) - { - col = Tile::tallgrass->getColor(level, x, y, z); - r = ((col >> 16) & 0xff) / 255.0f; - g = ((col >> 8) & 0xff) / 255.0f; - b = ((col) & 0xff) / 255.0f; - t->color(br * r, br * g, br * b); - tesselateCrossTexture(Tile::tallgrass, TallGrass::FERN, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_DEAD_BUSH) - { - tesselateCrossTexture(Tile::deadBush, TallGrass::FERN, x, y, z, 0.75f); - } - } + t->addOffset(-xOff / 16.0f, -yOff / 16.0f, -zOff / 16.0f); + } - t->addOffset(-xOff / 16.0f, -yOff / 16.0f, -zOff / 16.0f); - } - - return true; + return true; } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z) -{ - return tesselateAnvilInWorld(tt, x, y, z, level->getData(x, y, z)); - +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z) { + return tesselateAnvilInWorld(tt, x, y, z, level->getData(x, y, z)); } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, + int data) { + Tesselator* t = Tesselator::getInstance(); - float br; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - br = 1; - } - else - { - br = tt->getBrightness(level, x, y, z); - } - int col = tt->getColor(level, x, y, z); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if (GameRenderer::anaglyph3d) - { - float cr = (r * 30 + g * 59 + b * 11) / 100; - float cg = (r * 30 + g * 70) / (100); - float cb = (r * 30 + b * 70) / (100); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color(br * r, br * g, br * b); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - return tesselateAnvilInWorld(tt, x, y, z, data, false); + return tesselateAnvilInWorld(tt, x, y, z, data, false); } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data, bool render) -{ - int facing = render ? 0 : data & 3; - bool rotate = false; - float bottom = 0; +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, + int data, bool render) { + int facing = render ? 0 : data & 3; + bool rotate = false; + float bottom = 0; - switch (facing) - { - case Direction::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - break; - case Direction::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - break; - case Direction::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - rotate = true; - break; - case Direction::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - rotate = true; - break; - } + switch (facing) { + case Direction::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + break; + case Direction::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + break; + case Direction::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + rotate = true; + break; + case Direction::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + rotate = true; + break; + } - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_BASE, bottom, 12.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_JOINT, bottom, 8.0f / 16.0f, 1.0f / 16.0f, 10.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_COLUMN, bottom, 4.0f / 16.0f, 5.0f / 16.0f, 8.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_TOP, bottom, 10.0f / 16.0f, 6.0f / 16.0f, 16.0f / 16.0f, rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_BASE, bottom, + 12.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_JOINT, bottom, + 8.0f / 16.0f, 1.0f / 16.0f, 10.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_COLUMN, bottom, + 4.0f / 16.0f, 5.0f / 16.0f, 8.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_TOP, bottom, + 10.0f / 16.0f, 6.0f / 16.0f, 16.0f / 16.0f, + rotate, render, data); - setShape(0, 0, 0, 1, 1, 1); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; + setShape(0, 0, 0, 1, 1, 1); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; - return true; + return true; } -float TileRenderer::tesselateAnvilPiece(AnvilTile *tt, int x, int y, int z, int part, float bottom, float width, float height, float length, bool rotate, bool render, int data) -{ - if (rotate) - { - float swap = width; - width = length; - length = swap; - } +float TileRenderer::tesselateAnvilPiece(AnvilTile* tt, int x, int y, int z, + int part, float bottom, float width, + float height, float length, bool rotate, + bool render, int data) { + if (rotate) { + float swap = width; + width = length; + length = swap; + } - width /= 2; - length /= 2; + width /= 2; + length /= 2; - tt->part = part; - setShape(0.5f - width, bottom, 0.5f - length, 0.5f + width, bottom + height, 0.5f + length); + tt->part = part; + setShape(0.5f - width, bottom, 0.5f - length, 0.5f + width, bottom + height, + 0.5f + length); - if (render) - { - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->normal(0, -1, 0); - renderFaceDown(tt, 0, 0, 0, getTexture(tt, 0, data)); - t->end(); + if (render) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tt, 0, 0, 0, getTexture(tt, 0, data)); + t->end(); - t->begin(); - t->normal(0, 1, 0); - renderFaceUp(tt, 0, 0, 0, getTexture(tt, 1, data)); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tt, 0, 0, 0, getTexture(tt, 1, data)); + t->end(); - t->begin(); - t->normal(0, 0, -1); - renderNorth(tt, 0, 0, 0, getTexture(tt, 2, data)); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tt, 0, 0, 0, getTexture(tt, 2, data)); + t->end(); - t->begin(); - t->normal(0, 0, 1); - renderSouth(tt, 0, 0, 0, getTexture(tt, 3, data)); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tt, 0, 0, 0, getTexture(tt, 3, data)); + t->end(); - t->begin(); - t->normal(-1, 0, 0); - renderWest(tt, 0, 0, 0, getTexture(tt, 4, data)); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tt, 0, 0, 0, getTexture(tt, 4, data)); + t->end(); - t->begin(); - t->normal(1, 0, 0); - renderEast(tt, 0, 0, 0, getTexture(tt, 5, data)); - t->end(); - } - else - { - tesselateBlockInWorld(tt, x, y, z); - } + t->begin(); + t->normal(1, 0, 0); + renderEast(tt, 0, 0, 0, getTexture(tt, 5, data)); + t->end(); + } else { + tesselateBlockInWorld(tt, x, y, z); + } - return bottom + height; + return bottom + height; } -bool TileRenderer::tesselateTorchInWorld( Tile* tt, int x, int y, int z ) -{ - int dir = level->getData( x, y, z ); +bool TileRenderer::tesselateTorchInWorld(Tile* tt, int x, int y, int z) { + int dir = level->getData(x, y, z); - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - } - - float r = 0.40f; - float r2 = 0.5f - r; - float h = 0.20f; - if ( dir == 1 ) - { - tesselateTorch( tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0 ); - } - else if ( dir == 2 ) - { - tesselateTorch( tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0 ); - } - else if ( dir == 3 ) - { - tesselateTorch( tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0 ); - } - else if ( dir == 4 ) - { - tesselateTorch( tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0 ); - } - else - { - tesselateTorch( tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0 ); - } - return true; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } + float r = 0.40f; + float r2 = 0.5f - r; + float h = 0.20f; + if (dir == 1) { + tesselateTorch(tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0); + } else if (dir == 2) { + tesselateTorch(tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0); + } else if (dir == 3) { + tesselateTorch(tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0); + } else if (dir == 4) { + tesselateTorch(tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0); + } else { + tesselateTorch(tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0); + } + return true; } -bool TileRenderer::tesselateDiodeInWorld(DiodeTile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - tesselateDiodeInWorld(tt, x, y, z, level->getData(x, y, z) & DiodeTile::DIRECTION_MASK); + tesselateDiodeInWorld(tt, x, y, z, + level->getData(x, y, z) & DiodeTile::DIRECTION_MASK); - return true; + return true; } -void TileRenderer::tesselateDiodeInWorld( DiodeTile* tt, int x, int y, int z, int dir ) -{ - // render half-block edges - tesselateBlockInWorld( tt, x, y, z ); +void TileRenderer::tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z, + int dir) { + // render half-block edges + tesselateBlockInWorld(tt, x, y, z); - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } - int data = level->getData(x, y, z); + int data = level->getData(x, y, z); - // 4J Stu - This block gets moved in a later version, but we don't need that yet - // BEGIN TORCH SECTION - { - int dir = data & DiodeTile::DIRECTION_MASK; - int delay = ( data & DiodeTile::DELAY_MASK ) >> DiodeTile::DELAY_SHIFT; - float h = -3.0f / 16.0f; - float transmitterX = 0.0f; - float transmitterZ = 0.0f; - float receiverX = 0.0f; - float receiverZ = 0.0f; + // 4J Stu - This block gets moved in a later version, but we don't need that + // yet BEGIN TORCH SECTION + { + int dir = data & DiodeTile::DIRECTION_MASK; + int delay = (data & DiodeTile::DELAY_MASK) >> DiodeTile::DELAY_SHIFT; + float h = -3.0f / 16.0f; + float transmitterX = 0.0f; + float transmitterZ = 0.0f; + float receiverX = 0.0f; + float receiverZ = 0.0f; - switch ( dir ) - { - case Direction::SOUTH: - receiverZ = -5.0f / 16.0f; - transmitterZ = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::NORTH: - receiverZ = 5.0f / 16.0f; - transmitterZ = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::EAST: - receiverX = -5.0f / 16.0f; - transmitterX = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::WEST: - receiverX = 5.0f / 16.0f; - transmitterX = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - } + switch (dir) { + case Direction::SOUTH: + receiverZ = -5.0f / 16.0f; + transmitterZ = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::NORTH: + receiverZ = 5.0f / 16.0f; + transmitterZ = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::EAST: + receiverX = -5.0f / 16.0f; + transmitterX = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::WEST: + receiverX = 5.0f / 16.0f; + transmitterX = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + } - // render transmitter - tesselateTorch( tt, x + transmitterX, y + h, z + transmitterZ, 0.0f, 0.0f, 0 ); - // render receiver - tesselateTorch( tt, x + receiverX, y + h, z + receiverZ, 0.0f, 0.0f, 0 ); - } - // END TORCH SECTION + // render transmitter + tesselateTorch(tt, x + transmitterX, y + h, z + transmitterZ, 0.0f, + 0.0f, 0); + // render receiver + tesselateTorch(tt, x + receiverX, y + h, z + receiverZ, 0.0f, 0.0f, 0); + } + // END TORCH SECTION - Icon *tex = getTexture(tt, Facing::UP, data); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + Icon* tex = getTexture(tt, Facing::UP, data); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float r = 2.0f / 16.0f; + float r = 2.0f / 16.0f; - float x0 = ( float )( x + 1.0f ); - float x1 = ( float )( x + 1.0f ); - float x2 = ( float )( x + 0.0f ); - float x3 = ( float )( x + 0.0f ); + float x0 = (float)(x + 1.0f); + float x1 = (float)(x + 1.0f); + float x2 = (float)(x + 0.0f); + float x3 = (float)(x + 0.0f); - float z0 = ( float )( z + 0.0f ); - float z1 = ( float )( z + 1.0f ); - float z2 = ( float )( z + 1.0f ); - float z3 = ( float )( z + 0.0f ); + float z0 = (float)(z + 0.0f); + float z1 = (float)(z + 1.0f); + float z2 = (float)(z + 1.0f); + float z3 = (float)(z + 0.0f); - float y0 = ( float )( y + r ); + float y0 = (float)(y + r); - if ( dir == Direction::NORTH ) - { - // rotate 180 degrees - x0 = x1 = ( float )( x + 0.0f ); - x2 = x3 = ( float )( x + 1.0f ); - z0 = z3 = ( float )( z + 1.0f ); - z1 = z2 = ( float )( z + 0.0f ); - } - else if ( dir == Direction::EAST ) - { - // rotate 90 degrees counter-clockwise - x0 = x3 = ( float )( x + 0.0f ); - x1 = x2 = ( float )( x + 1.0f ); - z0 = z1 = ( float )( z + 0.0f ); - z2 = z3 = ( float )( z + 1.0f ); - } - else if ( dir == Direction::WEST ) - { - // rotate 90 degrees clockwise - x0 = x3 = ( float )( x + 1.0f ); - x1 = x2 = ( float )( x + 0.0f ); - z0 = z1 = ( float )( z + 1.0f ); - z2 = z3 = ( float )( z + 0.0f ); - } + if (dir == Direction::NORTH) { + // rotate 180 degrees + x0 = x1 = (float)(x + 0.0f); + x2 = x3 = (float)(x + 1.0f); + z0 = z3 = (float)(z + 1.0f); + z1 = z2 = (float)(z + 0.0f); + } else if (dir == Direction::EAST) { + // rotate 90 degrees counter-clockwise + x0 = x3 = (float)(x + 0.0f); + x1 = x2 = (float)(x + 1.0f); + z0 = z1 = (float)(z + 0.0f); + z2 = z3 = (float)(z + 1.0f); + } else if (dir == Direction::WEST) { + // rotate 90 degrees clockwise + x0 = x3 = (float)(x + 1.0f); + x1 = x2 = (float)(x + 0.0f); + z0 = z1 = (float)(z + 1.0f); + z2 = z3 = (float)(z + 0.0f); + } - t->vertexUV( x3 , y0 , z3 , u0 , v0 ); - t->vertexUV( x2 , y0 , z2 , u0 , v1 ); - t->vertexUV( x1 , y0 , z1 , u1 , v1 ); - t->vertexUV( x0 , y0 , z0 , u1 , v0 ); + t->vertexUV(x3, y0, z3, u0, v0); + t->vertexUV(x2, y0, z2, u0, v1); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x0, y0, z0, u1, v0); } -void TileRenderer::tesselatePistonBaseForceExtended( Tile* tile, int x, int y, int z, int forceData ) // 4J added forceData param +void TileRenderer::tesselatePistonBaseForceExtended( + Tile* tile, int x, int y, int z, int forceData) // 4J added forceData param { - noCulling = true; - tesselatePistonBaseInWorld( tile, x, y, z, true, forceData ); - noCulling = false; + noCulling = true; + tesselatePistonBaseInWorld(tile, x, y, z, true, forceData); + noCulling = false; } -bool TileRenderer::tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bool forceExtended, int forceData ) // 4J added forceData param +bool TileRenderer::tesselatePistonBaseInWorld( + Tile* tt, int x, int y, int z, bool forceExtended, + int forceData) // 4J added forceData param { - int data = ( forceData == -1 ) ? level->getData( x, y, z ) : forceData; - bool extended = forceExtended || ( data & PistonBaseTile::EXTENDED_BIT ) != 0; - int facing = PistonBaseTile::getFacing( data ); + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; + bool extended = forceExtended || (data & PistonBaseTile::EXTENDED_BIT) != 0; + int facing = PistonBaseTile::getFacing(data); - const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; + const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - if ( extended ) - { - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - setShape( 0.0f, thickness, 0.0f, 1.0f, 1.0f, 1.0f ); - break; - case Facing::UP: - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f - thickness, 1.0f ); - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, thickness, 1.0f, 1.0f, 1.0f ); - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f - thickness ); - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - setShape( thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f ); - break; - } - // weird way of telling the piston to use the - // "inside" texture for the forward-facing edge - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); - tesselateBlockInWorld( tt, x, y, z ); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); - } - else - { - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - break; - case Facing::UP: - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - break; - } - tesselateBlockInWorld( tt, x, y, z ); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - } - - return true; + if (extended) { + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + setShape(0.0f, thickness, 0.0f, 1.0f, 1.0f, 1.0f); + break; + case Facing::UP: + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f - thickness, 1.0f); + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + setShape(0.0f, 0.0f, thickness, 1.0f, 1.0f, 1.0f); + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f - thickness); + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + setShape(thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + setShape(0.0f, 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f); + break; + } + // weird way of telling the piston to use the + // "inside" texture for the forward-facing edge + ((PistonBaseTile*)tt) + ->updateShape((float)tileShapeX0, (float)tileShapeY0, + (float)tileShapeZ0, (float)tileShapeX1, + (float)tileShapeY1, (float)tileShapeZ1); + tesselateBlockInWorld(tt, x, y, z); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + ((PistonBaseTile*)tt) + ->updateShape((float)tileShapeX0, (float)tileShapeY0, + (float)tileShapeZ0, (float)tileShapeX1, + (float)tileShapeY1, (float)tileShapeZ1); + } else { + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + break; + case Facing::UP: + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + break; + } + tesselateBlockInWorld(tt, x, y, z); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + } + return true; } -void TileRenderer::renderPistonArmUpDown( float x0, float x1, float y0, float y1, float z0, float z1, float br, - float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmUpDown(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); - - t->vertexUV( x0, y1, z0, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x1, y0, z1, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->color(br, br, br); + t->vertexUV(x0, y1, z0, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x1, y0, z1, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::renderPistonArmNorthSouth( float x0, float x1, float y0, float y1, float z0, float z1, - float br, float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmNorthSouth(float x0, float x1, float y0, + float y1, float z0, float z1, + float br, float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); + t->color(br, br, br); - t->vertexUV( x0, y0, z1, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x1, y1, z0, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->vertexUV(x0, y0, z1, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x1, y1, z0, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::renderPistonArmEastWest( float x0, float x1, float y0, float y1, float z0, float z1, float br, - float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmEastWest(float x0, float x1, float y0, + float y1, float z0, float z1, + float br, float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); + t->color(br, br, br); - t->vertexUV( x1, y0, z0, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x0, y1, z1, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->vertexUV(x1, y0, z0, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x0, y1, z1, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::tesselatePistonArmNoCulling( Tile* tile, int x, int y, int z, bool fullArm, int forceData ) // 4J added forceData param +void TileRenderer::tesselatePistonArmNoCulling( + Tile* tile, int x, int y, int z, bool fullArm, + int forceData) // 4J added forceData param { - noCulling = true; - tesselatePistonExtensionInWorld( tile, x, y, z, fullArm ); - noCulling = false; + noCulling = true; + tesselatePistonExtensionInWorld(tile, x, y, z, fullArm); + noCulling = false; } -bool TileRenderer::tesselatePistonExtensionInWorld( Tile* tt, int x, int y, int z, bool fullArm, int forceData ) // 4J added forceData param +bool TileRenderer::tesselatePistonExtensionInWorld( + Tile* tt, int x, int y, int z, bool fullArm, + int forceData) // 4J added forceData param { - int data = ( forceData == -1 ) ? level->getData( x, y, z ) : forceData; - int facing = PistonExtensionTile::getFacing( data ); + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; + int facing = PistonExtensionTile::getFacing(data); - const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - const float leftEdge = ( 8.0f - ( PistonBaseTile::PLATFORM_THICKNESS / 2.0f ) ) / 16.0f; - const float rightEdge = ( 8.0f + ( PistonBaseTile::PLATFORM_THICKNESS / 2.0f ) ) / 16.0f; - const float br = tt->getBrightness( level, x, y, z ); - const float armLength = fullArm ? 1.0f : 0.5f; - const float armLengthPixels = fullArm ? 16.0f : 8.0f; + const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; + const float leftEdge = + (8.0f - (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float rightEdge = + (8.0f + (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float br = tt->getBrightness(level, x, y, z); + const float armLength = fullArm ? 1.0f : 0.5f; + const float armLengthPixels = fullArm ? 16.0f : 8.0f; - Tesselator* t = Tesselator::getInstance(); - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, thickness, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + Tesselator* t = Tesselator::getInstance(); + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + setShape(0.0f, 0.0f, 0.0f, 1.0f, thickness, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmUpDown( x + leftEdge, x + rightEdge, y + thickness, y + thickness + armLength, - z + rightEdge, z + rightEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + leftEdge, y + thickness, y + thickness + armLength, z + leftEdge, - z + leftEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + leftEdge, x + leftEdge, y + thickness, y + thickness + armLength, z + leftEdge, - z + rightEdge, br * 0.6f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + rightEdge, y + thickness, y + thickness + armLength, - z + rightEdge, z + leftEdge, br * 0.6f, armLengthPixels ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmUpDown(x + leftEdge, x + rightEdge, y + thickness, + y + thickness + armLength, z + rightEdge, + z + rightEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + leftEdge, y + thickness, + y + thickness + armLength, z + leftEdge, + z + leftEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + leftEdge, x + leftEdge, y + thickness, + y + thickness + armLength, z + leftEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + rightEdge, y + thickness, + y + thickness + armLength, z + rightEdge, + z + leftEdge, br * 0.6f, armLengthPixels); - break; - case Facing::UP: - setShape( 0.0f, 1.0f - thickness, 0.0f, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + break; + case Facing::UP: + setShape(0.0f, 1.0f - thickness, 0.0f, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmUpDown( x + leftEdge, x + rightEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + rightEdge, z + rightEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + leftEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + leftEdge, z + leftEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + leftEdge, x + leftEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + leftEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + rightEdge, y - thickness + 1.0f - armLength, - y - thickness + 1.0f, z + rightEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, thickness ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmUpDown(x + leftEdge, x + rightEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + rightEdge, + z + rightEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + leftEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + leftEdge, + z + leftEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + leftEdge, x + leftEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + leftEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + rightEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + rightEdge, + z + leftEdge, br * 0.6f, armLengthPixels); + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, thickness); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmNorthSouth( x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, z + thickness, - z + thickness + armLength, br * 0.6f, armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, z + thickness, - z + thickness + armLength, br * 0.6f, armLengthPixels ); - renderPistonArmNorthSouth( x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, z + thickness, - z + thickness + armLength, br * 0.5f, armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, z + thickness, - z + thickness + armLength, br, armLengthPixels ); - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - setShape( 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmNorthSouth(x + leftEdge, x + leftEdge, y + rightEdge, + y + leftEdge, z + thickness, + z + thickness + armLength, br * 0.6f, + armLengthPixels); + renderPistonArmNorthSouth(x + rightEdge, x + rightEdge, + y + leftEdge, y + rightEdge, + z + thickness, z + thickness + armLength, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth(x + leftEdge, x + rightEdge, y + leftEdge, + y + leftEdge, z + thickness, + z + thickness + armLength, br * 0.5f, + armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, + z + thickness, z + thickness + armLength, br, armLengthPixels); + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + setShape(0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmNorthSouth( x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.6f, - armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.6f, - armLengthPixels ); - renderPistonArmNorthSouth( x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.5f, - armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br, armLengthPixels ); - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - setShape( 0.0f, 0.0f, 0.0f, thickness, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmNorthSouth( + x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth( + x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.5f, armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, br, + armLengthPixels); + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + setShape(0.0f, 0.0f, 0.0f, thickness, 1.0f, 1.0f); + tesselateBlockInWorld( + tt, x, y, + z); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld - t->tex2( getLightColor(tt, level, x, y , z ) ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + leftEdge, y + leftEdge, - z + rightEdge, z + leftEdge, br * 0.5f, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + rightEdge, y + rightEdge, - z + leftEdge, z + rightEdge, br, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + leftEdge, y + rightEdge, - z + leftEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + rightEdge, y + leftEdge, - z + rightEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - setShape( 1.0f - thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor(tt, level, x, y, z)); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + leftEdge, y + leftEdge, z + rightEdge, + z + leftEdge, br * 0.5f, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + rightEdge, y + rightEdge, z + leftEdge, + z + rightEdge, br, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + leftEdge, y + rightEdge, z + leftEdge, + z + leftEdge, br * 0.6f, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + rightEdge, y + leftEdge, z + rightEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + setShape(1.0f - thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + leftEdge, - y + leftEdge, z + rightEdge, z + leftEdge, br * 0.5f, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + rightEdge, - y + rightEdge, z + leftEdge, z + rightEdge, br, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + leftEdge, - y + rightEdge, z + leftEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + rightEdge, - y + leftEdge, z + rightEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - break; - } - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - - return true; + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + leftEdge, + y + leftEdge, z + rightEdge, z + leftEdge, + br * 0.5f, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + rightEdge, + y + rightEdge, z + leftEdge, z + rightEdge, + br, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + leftEdge, + y + rightEdge, z + leftEdge, z + leftEdge, + br * 0.6f, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + rightEdge, + y + leftEdge, z + rightEdge, z + rightEdge, + br * 0.6f, armLengthPixels); + break; + } + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + return true; } -bool TileRenderer::tesselateLeverInWorld( Tile* tt, int x, int y, int z ) -{ - int data = level->getData( x, y, z ); +bool TileRenderer::tesselateLeverInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); - int dir = data & 7; - bool flipped = ( data & 8 ) > 0; + int dir = data & 7; + bool flipped = (data & 8) > 0; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - bool hadFixed = hasFixedTexture(); - if (!hadFixed) this->setFixedTexture(getTexture(Tile::stoneBrick)); - float w1 = 4.0f / 16.0f; - float w2 = 3.0f / 16.0f; - float h = 3.0f / 16.0f; + bool hadFixed = hasFixedTexture(); + if (!hadFixed) this->setFixedTexture(getTexture(Tile::stoneBrick)); + float w1 = 4.0f / 16.0f; + float w2 = 3.0f / 16.0f; + float h = 3.0f / 16.0f; - if ( dir == 5 ) - { - setShape( 0.5f - w2, 0.0f, 0.5f - w1, 0.5f + w2, h, 0.5f + w1 ); - } - else if ( dir == 6 ) - { - setShape( 0.5f - w1, 0.0f, 0.5f - w2, 0.5f + w1, h, 0.5f + w2 ); - } - else if ( dir == 4 ) - { - setShape( 0.5f - w2, 0.5f - w1, 1.0f - h, 0.5f + w2, 0.5f + w1, 1.0f ); - } - else if ( dir == 3 ) - { - setShape( 0.5f - w2, 0.5f - w1, 0, 0.5f + w2, 0.5f + w1, h ); - } - else if ( dir == 2 ) - { - setShape( 1.0f - h, 0.5f - w1, 0.5f - w2, 1.0f, 0.5f + w1, 0.5f + w2 ); - } - else if ( dir == 1 ) - { - setShape( 0, 0.5f - w1, 0.5f - w2, h, 0.5f + w1, 0.5f + w2 ); - } - else if (dir == 0) - { - setShape(0.5f - w1, 1 - h, 0.5f - w2, 0.5f + w1, 1, 0.5f + w2); - } - else if (dir == 7) - { - setShape(0.5f - w2, 1 - h, 0.5f - w1, 0.5f + w2, 1, 0.5f + w1); - } - this->tesselateBlockInWorld( tt, x, y, z ); + if (dir == 5) { + setShape(0.5f - w2, 0.0f, 0.5f - w1, 0.5f + w2, h, 0.5f + w1); + } else if (dir == 6) { + setShape(0.5f - w1, 0.0f, 0.5f - w2, 0.5f + w1, h, 0.5f + w2); + } else if (dir == 4) { + setShape(0.5f - w2, 0.5f - w1, 1.0f - h, 0.5f + w2, 0.5f + w1, 1.0f); + } else if (dir == 3) { + setShape(0.5f - w2, 0.5f - w1, 0, 0.5f + w2, 0.5f + w1, h); + } else if (dir == 2) { + setShape(1.0f - h, 0.5f - w1, 0.5f - w2, 1.0f, 0.5f + w1, 0.5f + w2); + } else if (dir == 1) { + setShape(0, 0.5f - w1, 0.5f - w2, h, 0.5f + w1, 0.5f + w2); + } else if (dir == 0) { + setShape(0.5f - w1, 1 - h, 0.5f - w2, 0.5f + w1, 1, 0.5f + w2); + } else if (dir == 7) { + setShape(0.5f - w2, 1 - h, 0.5f - w1, 0.5f + w2, 1, 0.5f + w1); + } + this->tesselateBlockInWorld(tt, x, y, z); - if ( !hadFixed ) this->clearFixedTexture(); + if (!hadFixed) this->clearFixedTexture(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - Icon *tex = getTexture(tt, 0); + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - Vec3* corners[8]; - float xv = 1.0f / 16.0f; - float zv = 1.0f / 16.0f; - float yv = 10.0f / 16.0f; - corners[0] = Vec3::newTemp( -xv, -0, -zv ); - corners[1] = Vec3::newTemp( +xv, -0, -zv ); - corners[2] = Vec3::newTemp( +xv, -0, +zv ); - corners[3] = Vec3::newTemp( -xv, -0, +zv ); - corners[4] = Vec3::newTemp( -xv, +yv, -zv ); - corners[5] = Vec3::newTemp( +xv, +yv, -zv ); - corners[6] = Vec3::newTemp( +xv, +yv, +zv ); - corners[7] = Vec3::newTemp( -xv, +yv, +zv ); + Vec3* corners[8]; + float xv = 1.0f / 16.0f; + float zv = 1.0f / 16.0f; + float yv = 10.0f / 16.0f; + corners[0] = Vec3::newTemp(-xv, -0, -zv); + corners[1] = Vec3::newTemp(+xv, -0, -zv); + corners[2] = Vec3::newTemp(+xv, -0, +zv); + corners[3] = Vec3::newTemp(-xv, -0, +zv); + corners[4] = Vec3::newTemp(-xv, +yv, -zv); + corners[5] = Vec3::newTemp(+xv, +yv, -zv); + corners[6] = Vec3::newTemp(+xv, +yv, +zv); + corners[7] = Vec3::newTemp(-xv, +yv, +zv); - for ( int i = 0; i < 8; i++ ) - { - if ( flipped ) - { - corners[i]->z -= 1 / 16.0f; - corners[i]->xRot( 40 * PI / 180 ); - } - else - { - corners[i]->z += 1 / 16.0f; - corners[i]->xRot( -40 * PI / 180 ); - } - if (dir == 0 || dir == 7) - { - corners[i]->zRot(180 * PI / 180); - } - if ( dir == 6 || dir == 0 ) - { - corners[i]->yRot( 90 * PI / 180 ); - } + for (int i = 0; i < 8; i++) { + if (flipped) { + corners[i]->z -= 1 / 16.0f; + corners[i]->xRot(40 * PI / 180); + } else { + corners[i]->z += 1 / 16.0f; + corners[i]->xRot(-40 * PI / 180); + } + if (dir == 0 || dir == 7) { + corners[i]->zRot(180 * PI / 180); + } + if (dir == 6 || dir == 0) { + corners[i]->yRot(90 * PI / 180); + } - if ( dir > 0 && dir < 5 ) - { - corners[i]->y -= 6 / 16.0f; - corners[i]->xRot( 90 * PI / 180 ); + if (dir > 0 && dir < 5) { + corners[i]->y -= 6 / 16.0f; + corners[i]->xRot(90 * PI / 180); - if ( dir == 4 ) corners[i]->yRot( 0 * PI / 180 ); - if ( dir == 3 ) corners[i]->yRot( 180 * PI / 180 ); - if ( dir == 2 ) corners[i]->yRot( 90 * PI / 180 ); - if ( dir == 1 ) corners[i]->yRot( -90 * PI / 180 ); + if (dir == 4) corners[i]->yRot(0 * PI / 180); + if (dir == 3) corners[i]->yRot(180 * PI / 180); + if (dir == 2) corners[i]->yRot(90 * PI / 180); + if (dir == 1) corners[i]->yRot(-90 * PI / 180); - corners[i]->x += x + 0.5; - corners[i]->y += y + 8 / 16.0f; - corners[i]->z += z + 0.5; - } - else if (dir == 0 || dir == 7) - { - corners[i]->x += x + 0.5; - corners[i]->y += y + 14 / 16.0f; - corners[i]->z += z + 0.5; - } - else - { - corners[i]->x += x + 0.5; - corners[i]->y += y + 2 / 16.0f; - corners[i]->z += z + 0.5; - } - } - - Vec3* c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; - for ( int i = 0; i < 6; i++ ) - { - if ( i == 0 ) - { - u0 = tex->getU(7, true); - v0 = tex->getV(6, true); - u1 = tex->getU(9, true); - v1 = tex->getV(8, true); - } - else if ( i == 2 ) - { - u0 = tex->getU(7, true); - v0 = tex->getV(6, true); - u1 = tex->getU(9, true); - v1 = tex->getV1(true); - } - if ( i == 0 ) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - } - else if ( i == 1 ) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if ( i == 2 ) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - } - else if ( i == 3 ) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if ( i == 4 ) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if ( i == 5 ) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV( ( float )( c0->x ), ( float )( c0->y ), ( float )( c0->z ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c1->x ), ( float )( c1->y ), ( float )( c1->z ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c2->x ), ( float )( c2->y ), ( float )( c2->z ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( c3->x ), ( float )( c3->y ), ( float )( c3->z ), ( float )( u0 ), ( float )( v0 ) ); - } - return true; + corners[i]->x += x + 0.5; + corners[i]->y += y + 8 / 16.0f; + corners[i]->z += z + 0.5; + } else if (dir == 0 || dir == 7) { + corners[i]->x += x + 0.5; + corners[i]->y += y + 14 / 16.0f; + corners[i]->z += z + 0.5; + } else { + corners[i]->x += x + 0.5; + corners[i]->y += y + 2 / 16.0f; + corners[i]->z += z + 0.5; + } + } + Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + for (int i = 0; i < 6; i++) { + if (i == 0) { + u0 = tex->getU(7, true); + v0 = tex->getV(6, true); + u1 = tex->getU(9, true); + v1 = tex->getV(8, true); + } else if (i == 2) { + u0 = tex->getU(7, true); + v0 = tex->getV(6, true); + u1 = tex->getU(9, true); + v1 = tex->getV1(true); + } + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV((float)(c0->x), (float)(c0->y), (float)(c0->z), (float)(u0), + (float)(v1)); + t->vertexUV((float)(c1->x), (float)(c1->y), (float)(c1->z), (float)(u1), + (float)(v1)); + t->vertexUV((float)(c2->x), (float)(c2->y), (float)(c2->z), (float)(u1), + (float)(v0)); + t->vertexUV((float)(c3->x), (float)(c3->y), (float)(c3->z), (float)(u0), + (float)(v0)); + } + return true; } -bool TileRenderer::tesselateTripwireSourceInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); - int data = level->getData(x, y, z); - int dir = data & TripWireSourceTile::MASK_DIR; - bool attached = (data & TripWireSourceTile::MASK_ATTACHED) == TripWireSourceTile::MASK_ATTACHED; - bool powered = (data & TripWireSourceTile::MASK_POWERED) == TripWireSourceTile::MASK_POWERED; - bool suspended = !level->isTopSolidBlocking(x, y - 1, z); +bool TileRenderer::tesselateTripwireSourceInWorld(Tile* tt, int x, int y, + int z) { + Tesselator* t = Tesselator::getInstance(); + int data = level->getData(x, y, z); + int dir = data & TripWireSourceTile::MASK_DIR; + bool attached = (data & TripWireSourceTile::MASK_ATTACHED) == + TripWireSourceTile::MASK_ATTACHED; + bool powered = (data & TripWireSourceTile::MASK_POWERED) == + TripWireSourceTile::MASK_POWERED; + bool suspended = !level->isTopSolidBlocking(x, y - 1, z); - bool hadFixed = hasFixedTexture(); - if (!hadFixed) this->setFixedTexture(getTexture(Tile::wood)); + bool hadFixed = hasFixedTexture(); + if (!hadFixed) this->setFixedTexture(getTexture(Tile::wood)); - float boxHeight = 4 / 16.0f; - float boxWidth = 2 / 16.0f; - float boxDepth = 2 / 16.0f; + float boxHeight = 4 / 16.0f; + float boxWidth = 2 / 16.0f; + float boxDepth = 2 / 16.0f; - float boxy0 = 0.3f - boxHeight; - float boxy1 = 0.3f + boxHeight; - if (dir == Direction::NORTH) - { - setShape(0.5f - boxWidth, boxy0, 1 - boxDepth, 0.5f + boxWidth, boxy1, 1); - } - else if (dir == Direction::SOUTH) - { - setShape(0.5f - boxWidth, boxy0, 0, 0.5f + boxWidth, boxy1, boxDepth); - } - else if (dir == Direction::WEST) - { - setShape(1 - boxDepth, boxy0, 0.5f - boxWidth, 1, boxy1, 0.5f + boxWidth); - } - else if (dir == Direction::EAST) - { - setShape(0, boxy0, 0.5f - boxWidth, boxDepth, boxy1, 0.5f + boxWidth); - } + float boxy0 = 0.3f - boxHeight; + float boxy1 = 0.3f + boxHeight; + if (dir == Direction::NORTH) { + setShape(0.5f - boxWidth, boxy0, 1 - boxDepth, 0.5f + boxWidth, boxy1, + 1); + } else if (dir == Direction::SOUTH) { + setShape(0.5f - boxWidth, boxy0, 0, 0.5f + boxWidth, boxy1, boxDepth); + } else if (dir == Direction::WEST) { + setShape(1 - boxDepth, boxy0, 0.5f - boxWidth, 1, boxy1, + 0.5f + boxWidth); + } else if (dir == Direction::EAST) { + setShape(0, boxy0, 0.5f - boxWidth, boxDepth, boxy1, 0.5f + boxWidth); + } - this->tesselateBlockInWorld(tt, x, y, z); - if (!hadFixed) this->clearFixedTexture(); + this->tesselateBlockInWorld(tt, x, y, z); + if (!hadFixed) this->clearFixedTexture(); - float brightness; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - brightness = 1; - } - else - { - brightness = tt->getBrightness(level, x, y, z); - } - if (Tile::lightEmission[tt->id] > 0) brightness = 1.0f; - t->color(brightness, brightness, brightness); - Icon *tex = getTexture(tt, 0); + float brightness; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + brightness = 1; + } else { + brightness = tt->getBrightness(level, x, y, z); + } + if (Tile::lightEmission[tt->id] > 0) brightness = 1.0f; + t->color(brightness, brightness, brightness); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; - double u0 = tex->getU0(); - double v0 = tex->getV0(); - double u1 = tex->getU1(); - double v1 = tex->getV1(); + if (hasFixedTexture()) tex = fixedTexture; + double u0 = tex->getU0(); + double v0 = tex->getV0(); + double u1 = tex->getU1(); + double v1 = tex->getV1(); - Vec3 *corners[8]; - float stickWidth = 0.75f / 16.0f; - float stickHeight = 0.75f / 16.0f; - float stickLength = 5 / 16.0f; - corners[0] = Vec3::newTemp(-stickWidth, -0, -stickHeight); - corners[1] = Vec3::newTemp(+stickWidth, -0, -stickHeight); - corners[2] = Vec3::newTemp(+stickWidth, -0, +stickHeight); - corners[3] = Vec3::newTemp(-stickWidth, -0, +stickHeight); - corners[4] = Vec3::newTemp(-stickWidth, +stickLength, -stickHeight); - corners[5] = Vec3::newTemp(+stickWidth, +stickLength, -stickHeight); - corners[6] = Vec3::newTemp(+stickWidth, +stickLength, +stickHeight); - corners[7] = Vec3::newTemp(-stickWidth, +stickLength, +stickHeight); + Vec3* corners[8]; + float stickWidth = 0.75f / 16.0f; + float stickHeight = 0.75f / 16.0f; + float stickLength = 5 / 16.0f; + corners[0] = Vec3::newTemp(-stickWidth, -0, -stickHeight); + corners[1] = Vec3::newTemp(+stickWidth, -0, -stickHeight); + corners[2] = Vec3::newTemp(+stickWidth, -0, +stickHeight); + corners[3] = Vec3::newTemp(-stickWidth, -0, +stickHeight); + corners[4] = Vec3::newTemp(-stickWidth, +stickLength, -stickHeight); + corners[5] = Vec3::newTemp(+stickWidth, +stickLength, -stickHeight); + corners[6] = Vec3::newTemp(+stickWidth, +stickLength, +stickHeight); + corners[7] = Vec3::newTemp(-stickWidth, +stickLength, +stickHeight); - for (int i = 0; i < 8; i++) - { - corners[i]->z += 1 / 16.0f; + for (int i = 0; i < 8; i++) { + corners[i]->z += 1 / 16.0f; - if (powered) - { - corners[i]->xRot(30 * PI / 180); - corners[i]->y -= 7 / 16.0f; - } - else if (attached) - { - corners[i]->xRot(5 * PI / 180); - corners[i]->y -= 7 / 16.0f; - } - else - { - corners[i]->xRot(-40 * PI / 180); - corners[i]->y -= 6 / 16.0f; - } + if (powered) { + corners[i]->xRot(30 * PI / 180); + corners[i]->y -= 7 / 16.0f; + } else if (attached) { + corners[i]->xRot(5 * PI / 180); + corners[i]->y -= 7 / 16.0f; + } else { + corners[i]->xRot(-40 * PI / 180); + corners[i]->y -= 6 / 16.0f; + } - corners[i]->xRot(90 * PI / 180); + corners[i]->xRot(90 * PI / 180); - if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); - if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); - if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); - if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); + if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); + if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); + if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); + if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); - corners[i]->x += x + 0.5; - corners[i]->y += y + 5 / 16.0f; - corners[i]->z += z + 0.5; - } + corners[i]->x += x + 0.5; + corners[i]->y += y + 5 / 16.0f; + corners[i]->z += z + 0.5; + } - Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; - int stickX0 = 7; - int stickX1 = 9; - int stickY0 = 9; - int stickY1 = 16; + Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + int stickX0 = 7; + int stickX1 = 9; + int stickY0 = 9; + int stickY1 = 16; - for (int i = 0; i < 6; i++) - { - if (i == 0) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - u0 = tex->getU(stickX0); - v0 = tex->getV(stickY0); - u1 = tex->getU(stickX1); - v1 = tex->getV(stickY0 + 2); - } - else if (i == 1) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if (i == 2) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - u0 = tex->getU(stickX0); - v0 = tex->getV(stickY0); - u1 = tex->getU(stickX1); - v1 = tex->getV(stickY1); - } - else if (i == 3) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if (i == 4) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if (i == 5) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV(c0->x, c0->y, c0->z, u0, v1); - t->vertexUV(c1->x, c1->y, c1->z, u1, v1); - t->vertexUV(c2->x, c2->y, c2->z, u1, v0); - t->vertexUV(c3->x, c3->y, c3->z, u0, v0); - } + for (int i = 0; i < 6; i++) { + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + u0 = tex->getU(stickX0); + v0 = tex->getV(stickY0); + u1 = tex->getU(stickX1); + v1 = tex->getV(stickY0 + 2); + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + u0 = tex->getU(stickX0); + v0 = tex->getV(stickY0); + u1 = tex->getU(stickX1); + v1 = tex->getV(stickY1); + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV(c0->x, c0->y, c0->z, u0, v1); + t->vertexUV(c1->x, c1->y, c1->z, u1, v1); + t->vertexUV(c2->x, c2->y, c2->z, u1, v0); + t->vertexUV(c3->x, c3->y, c3->z, u0, v0); + } + float hoopWidth = 1.5f / 16.0f; + float hoopHeight = 1.5f / 16.0f; + float hoopLength = 0.5f / 16.0f; + corners[0] = Vec3::newTemp(-hoopWidth, -0, -hoopHeight); + corners[1] = Vec3::newTemp(+hoopWidth, -0, -hoopHeight); + corners[2] = Vec3::newTemp(+hoopWidth, -0, +hoopHeight); + corners[3] = Vec3::newTemp(-hoopWidth, -0, +hoopHeight); + corners[4] = Vec3::newTemp(-hoopWidth, +hoopLength, -hoopHeight); + corners[5] = Vec3::newTemp(+hoopWidth, +hoopLength, -hoopHeight); + corners[6] = Vec3::newTemp(+hoopWidth, +hoopLength, +hoopHeight); + corners[7] = Vec3::newTemp(-hoopWidth, +hoopLength, +hoopHeight); - float hoopWidth = 1.5f / 16.0f; - float hoopHeight = 1.5f / 16.0f; - float hoopLength = 0.5f / 16.0f; - corners[0] = Vec3::newTemp(-hoopWidth, -0, -hoopHeight); - corners[1] = Vec3::newTemp(+hoopWidth, -0, -hoopHeight); - corners[2] = Vec3::newTemp(+hoopWidth, -0, +hoopHeight); - corners[3] = Vec3::newTemp(-hoopWidth, -0, +hoopHeight); - corners[4] = Vec3::newTemp(-hoopWidth, +hoopLength, -hoopHeight); - corners[5] = Vec3::newTemp(+hoopWidth, +hoopLength, -hoopHeight); - corners[6] = Vec3::newTemp(+hoopWidth, +hoopLength, +hoopHeight); - corners[7] = Vec3::newTemp(-hoopWidth, +hoopLength, +hoopHeight); + for (int i = 0; i < 8; i++) { + corners[i]->z += 3.5f / 16.0f; - for (int i = 0; i < 8; i++) - { - corners[i]->z += 3.5f / 16.0f; + if (powered) { + corners[i]->y -= 1.5 / 16.0f; + corners[i]->z -= 2.6 / 16.0f; + corners[i]->xRot(0 * PI / 180); + } else if (attached) { + corners[i]->y += 0.25 / 16.0f; + corners[i]->z -= 2.75 / 16.0f; + corners[i]->xRot(10 * PI / 180); + } else { + corners[i]->xRot(50 * PI / 180); + } - if (powered) - { - corners[i]->y -= 1.5 / 16.0f; - corners[i]->z -= 2.6 / 16.0f; - corners[i]->xRot(0 * PI / 180); - } - else if (attached) - { - corners[i]->y += 0.25 / 16.0f; - corners[i]->z -= 2.75 / 16.0f; - corners[i]->xRot(10 * PI / 180); - } - else - { - corners[i]->xRot(50 * PI / 180); - } + if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); + if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); + if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); + if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); - if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); - if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); - if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); - if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); + corners[i]->x += x + 0.5; + corners[i]->y += y + 5 / 16.0f; + corners[i]->z += z + 0.5; + } - corners[i]->x += x + 0.5; - corners[i]->y += y + 5 / 16.0f; - corners[i]->z += z + 0.5; - } + int hoopX0 = 5; + int hoopX1 = 11; + int hoopY0 = 3; + int hoopY1 = 9; - int hoopX0 = 5; - int hoopX1 = 11; - int hoopY0 = 3; - int hoopY1 = 9; + for (int i = 0; i < 6; i++) { + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + u0 = tex->getU(hoopX0); + v0 = tex->getV(hoopY0); + u1 = tex->getU(hoopX1); + v1 = tex->getV(hoopY1); + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + u0 = tex->getU(hoopX0); + v0 = tex->getV(hoopY0); + u1 = tex->getU(hoopX1); + v1 = tex->getV(hoopY0 + 2); + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV(c0->x, c0->y, c0->z, u0, v1); + t->vertexUV(c1->x, c1->y, c1->z, u1, v1); + t->vertexUV(c2->x, c2->y, c2->z, u1, v0); + t->vertexUV(c3->x, c3->y, c3->z, u0, v0); + } - for (int i = 0; i < 6; i++) - { - if (i == 0) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - u0 = tex->getU(hoopX0); - v0 = tex->getV(hoopY0); - u1 = tex->getU(hoopX1); - v1 = tex->getV(hoopY1); - } - else if (i == 1) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if (i == 2) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - u0 = tex->getU(hoopX0); - v0 = tex->getV(hoopY0); - u1 = tex->getU(hoopX1); - v1 = tex->getV(hoopY0 + 2); - } - else if (i == 3) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if (i == 4) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if (i == 5) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV(c0->x, c0->y, c0->z, u0, v1); - t->vertexUV(c1->x, c1->y, c1->z, u1, v1); - t->vertexUV(c2->x, c2->y, c2->z, u1, v0); - t->vertexUV(c3->x, c3->y, c3->z, u0, v0); - } + if (attached) { + double hoopBottomY = corners[0]->y; + float width = 0.5f / 16.0f; + float top = 0.5f - (width / 2); + float bottom = top + width; + Icon* wireTex = getTexture(Tile::tripWire); + double wireX0 = wireTex->getU0(); + double wireY0 = wireTex->getV(attached ? 2 : 0); + double wireX1 = wireTex->getU1(); + double wireY1 = wireTex->getV(attached ? 4 : 2); + double floating = (suspended ? 3.5f : 1.5f) / 16.0; - if (attached) - { - double hoopBottomY = corners[0]->y; - float width = 0.5f / 16.0f; - float top = 0.5f - (width / 2); - float bottom = top + width; - Icon *wireTex = getTexture(Tile::tripWire); - double wireX0 = wireTex->getU0(); - double wireY0 = wireTex->getV(attached ? 2 : 0); - double wireX1 = wireTex->getU1(); - double wireY1 = wireTex->getV(attached ? 4 : 2); - double floating = (suspended ? 3.5f : 1.5f) / 16.0; + brightness = tt->getBrightness(level, x, y, z) * 0.75f; + t->color(brightness, brightness, brightness); - brightness = tt->getBrightness(level, x, y, z) * 0.75f; - t->color(brightness, brightness, brightness); + if (dir == Direction::NORTH) { + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - if (dir == Direction::NORTH) - { - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX0, wireY0); + t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + } else if (dir == Direction::SOUTH) { + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX1, wireY1); + t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX1, wireY0); - t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX0, wireY0); - t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - } - else if (dir == Direction::SOUTH) - { - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX1, wireY1); - t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + } else if (dir == Direction::WEST) { + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - } - else if (dir == Direction::WEST) - { - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + } else { + t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - } - else - { - t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX0, wireY0); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + } + } - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - } - } - - return true; + return true; } -bool TileRenderer::tesselateTripwireInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); - int data = level->getData(x, y, z); - bool attached = (data & TripWireTile::MASK_ATTACHED) == TripWireTile::MASK_ATTACHED; - bool suspended = (data & TripWireTile::MASK_SUSPENDED) == TripWireTile::MASK_SUSPENDED; +bool TileRenderer::tesselateTripwireInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, 0); + int data = level->getData(x, y, z); + bool attached = + (data & TripWireTile::MASK_ATTACHED) == TripWireTile::MASK_ATTACHED; + bool suspended = + (data & TripWireTile::MASK_SUSPENDED) == TripWireTile::MASK_SUSPENDED; - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - float brightness; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - } - brightness = tt->getBrightness(level, x, y, z) * 0.75f; - t->color(brightness, brightness, brightness); + float brightness; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + } + brightness = tt->getBrightness(level, x, y, z) * 0.75f; + t->color(brightness, brightness, brightness); - double wireX0 = tex->getU0(); - double wireY0 = tex->getV(attached ? 2 : 0); - double wireX1 = tex->getU1(); - double wireY1 = tex->getV(attached ? 4 : 2); - double floating = (suspended ? 3.5f : 1.5f) / 16.0; + double wireX0 = tex->getU0(); + double wireY0 = tex->getV(attached ? 2 : 0); + double wireX1 = tex->getU1(); + double wireY1 = tex->getV(attached ? 4 : 2); + double floating = (suspended ? 3.5f : 1.5f) / 16.0; - bool w = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::WEST); - bool e = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::EAST); - bool n = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::NORTH); - bool s = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::SOUTH); + bool w = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::WEST); + bool e = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::EAST); + bool n = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::NORTH); + bool s = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::SOUTH); - float width = 0.5f / 16.0f; - float top = 0.5f - (width / 2); - float bottom = top + width; + float width = 0.5f / 16.0f; + float top = 0.5f - (width / 2); + float bottom = top + width; - if (!n && !e && !s && !w) - { - n = true; - s = true; - } + if (!n && !e && !s && !w) { + n = true; + s = true; + } - if (n) - { - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + if (n) { + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - } - if (n || (s && !e && !w)) - { - t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + } + if (n || (s && !e && !w)) { + t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); - } - if (s || (n && !e && !w)) - { - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); + } + if (s || (n && !e && !w)) { + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - } - if (s) - { - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + } + if (s) { + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - } + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + } - if (w) - { - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + if (w) { + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - } - if (w || (e && !n && !s)) - { - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + } + if (w || (e && !n && !s)) { + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - } - if (e || (w && !n && !s)) - { - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + } + if (e || (w && !n && !s)) { + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); - } - if (e) - { - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); + } + if (e) { + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - } + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + } - return true; + return true; } -bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateFireInWorld(FireTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *firstTex = tt->getTextureLayer(0); - Icon *secondTex = tt->getTextureLayer(1); - Icon *tex = firstTex; + Icon* firstTex = tt->getTextureLayer(0); + Icon* secondTex = tt->getTextureLayer(1); + Icon* tex = firstTex; - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->color( 1.0f, 1.0f, 1.0f ); - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); - float h = 1.4f; + if (SharedConstants::TEXTURE_LIGHTING) { + t->color(1.0f, 1.0f, 1.0f); + t->tex2(getLightColor(tt, level, x, y, z)); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); + float h = 1.4f; - if ( level->isTopSolidBlocking( x, y - 1, z ) || Tile::fire->canBurn( level, x, y - 1, z ) ) - { - float x0 = x + 0.5f + 0.2f; - float x1 = x + 0.5f - 0.2f; - float z0 = z + 0.5f + 0.2f; - float z1 = z + 0.5f - 0.2f; + if (level->isTopSolidBlocking(x, y - 1, z) || + Tile::fire->canBurn(level, x, y - 1, z)) { + float x0 = x + 0.5f + 0.2f; + float x1 = x + 0.5f - 0.2f; + float z0 = z + 0.5f + 0.2f; + float z1 = z + 0.5f - 0.2f; - float x0_ = x + 0.5f - 0.3f; - float x1_ = x + 0.5f + 0.3f; - float z0_ = z + 0.5f - 0.3f; - float z1_ = z + 0.5f + 0.3f; + float x0_ = x + 0.5f - 0.3f; + float x1_ = x + 0.5f + 0.3f; + float z0_ = z + 0.5f - 0.3f; + float z1_ = z + 0.5f + 0.3f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1), (float)(u0), + (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z1_), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z1_), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z0_), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z0_), (float)(u0), + (float)(v0)); - x0 = x + 0.5f - 0.5f; - x1 = x + 0.5f + 0.5f; - z0 = z + 0.5f - 0.5f; - z1 = z + 0.5f + 0.5f; + x0 = x + 0.5f - 0.5f; + x1 = x + 0.5f + 0.5f; + z0 = z + 0.5f - 0.5f; + z1 = z + 0.5f + 0.5f; - x0_ = x + 0.5f - 0.4f; - x1_ = x + 0.5f + 0.4f; - z0_ = z + 0.5f - 0.4f; - z1_ = z + 0.5f + 0.4f; + x0_ = x + 0.5f - 0.4f; + x1_ = x + 0.5f + 0.4f; + z0_ = z + 0.5f - 0.4f; + z1_ = z + 0.5f + 0.4f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), (float)(u1), + (float)(v0)); - tex = firstTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = firstTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z1_), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z1_), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - } - else - { - float r = 0.2f; - float yo = 1 / 16.0f; - if ( ( ( x + y + z ) & 1 ) == 1 ) - { - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); - } - if ( ( ( x / 2 + y / 2 + z / 2 ) & 1 ) == 1 ) - { - float tmp = u1; - u1 = u0; - u0 = tmp; - } - if ( Tile::fire->canBurn( level, x - 1, y, z ) ) - { - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z0_), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z0_), (float)(u1), + (float)(v0)); + } else { + float r = 0.2f; + float yo = 1 / 16.0f; + if (((x + y + z) & 1) == 1) { + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); + } + if (((x / 2 + y / 2 + z / 2) & 1) == 1) { + float tmp = u1; + u1 = u0; + u0 = tmp; + } + if (Tile::fire->canBurn(level, x - 1, y, z)) { + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 0.0f), + (float)(u0), (float)(v0)); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x + 1, y, z ) ) - { - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 0.0f), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + } + if (Tile::fire->canBurn(level, x + 1, y, z)) { + t->vertexUV((float)(x + 1 - r), (float)(y + h + yo), + (float)(z + 0.0f), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 - 0), (float)(y + 0 + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1 - 0), (float)(y + 0 + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 - r), (float)(y + h + yo), + (float)(z + 1.0f), (float)(u1), (float)(v0)); - t->vertexUV( ( float )( x + 1.0f - r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f - 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f - 0 ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f - r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y, z - 1 ) ) - { - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1.0f - r), (float)(y + h + yo), + (float)(z + 1.0f), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1.0f - 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f - 0), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f - r), (float)(y + h + yo), + (float)(z + 0.0f), (float)(u0), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y, z - 1)) { + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), (float)(z + r), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), (float)(z + r), + (float)(u0), (float)(v0)); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y, z + 1 ) ) - { - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), (float)(z + r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), (float)(z + r), + (float)(u1), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y, z + 1)) { + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u1), (float)(v0)); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u0 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y + 1.0f, z ) ) - { - double x0 = x + 0.5f + 0.5f; - double x1 = x + 0.5f - 0.5f; - double z0 = z + 0.5f + 0.5f; - double z1 = z + 0.5f - 0.5f; + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u0), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y + 1.0f, z)) { + double x0 = x + 0.5f + 0.5f; + double x1 = x + 0.5f - 0.5f; + double z0 = z + 0.5f + 0.5f; + double z1 = z + 0.5f - 0.5f; - double x0_ = x + 0.5f - 0.5f; - double x1_ = x + 0.5f + 0.5f; - double z0_ = z + 0.5f - 0.5f; - double z1_ = z + 0.5f + 0.5f; + double x0_ = x + 0.5f - 0.5f; + double x1_ = x + 0.5f + 0.5f; + double z0_ = z + 0.5f - 0.5f; + double z1_ = z + 0.5f + 0.5f; - tex = firstTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = firstTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - y += 1; - h = -0.2f; + y += 1; + h = -0.2f; - if ( ( ( x + y + z ) & 1 ) == 0 ) - { - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v0 ) ); + if (((x + y + z) & 1) == 0) { + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), + (float)(u0), (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v0 ) ); - } - else - { - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0.0f), (float)(z + 1.0f), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0.0f), (float)(z + 0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), + (float)(u0), (float)(v0)); + } else { + t->vertexUV((float)(x + 0.0f), (float)(y + h), (float)(z1_), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f), (float)(z1), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f), (float)(z1), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h), (float)(z1_), + (float)(u0), (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - } - } - } - - return true; + t->vertexUV((float)(x + 1.0f), (float)(y + h), (float)(z0_), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f), (float)(z0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f), (float)(z0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h), (float)(z0_), + (float)(u0), (float)(v0)); + } + } + } + return true; } -bool TileRenderer::tesselateDustInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateDustInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); - Icon *crossTexture = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS); - Icon *lineTexture = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE); - Icon *crossTextureOverlay = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS_OVERLAY); - Icon *lineTextureOverlay = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE_OVERLAY); + int data = level->getData(x, y, z); + Icon* crossTexture = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS); + Icon* lineTexture = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE); + Icon* crossTextureOverlay = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS_OVERLAY); + Icon* lineTextureOverlay = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE_OVERLAY); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - // 4J Stu - not used any more - //float pow = ( data / 15.0f ); - //float red = pow * 0.6f + 0.4f; - //if ( data == 0 ) red = 0.3f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + // 4J Stu - not used any more + // float pow = ( data / 15.0f ); + // float red = pow * 0.6f + 0.4f; + // if ( data == 0 ) red = 0.3f; - //float green = pow * pow * 0.7f - 0.5f; - //float blue = pow * pow * 0.6f - 0.7f; - //if ( green < 0 ) green = 0; - //if ( blue < 0 ) blue = 0; + // float green = pow * pow * 0.7f - 0.5f; + // float blue = pow * pow * 0.6f - 0.7f; + // if ( green < 0 ) green = 0; + // if ( blue < 0 ) blue = 0; - unsigned int colour = 0; - if(data == 0) - { - colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustUnlit ); - } - else - { - unsigned int minColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMin ); - unsigned int maxColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMax ); + unsigned int colour = 0; + if (data == 0) { + colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustUnlit); + } else { + unsigned int minColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMin); + unsigned int maxColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMax); - uint8_t redComponent = ((minColour>>16)&0xFF) + (( (maxColour>>16)&0xFF - (minColour>>16)&0xFF)*( (data-1)/14.0f)); - uint8_t greenComponent = ((minColour>>8)&0xFF) + (( (maxColour>>8)&0xFF - (minColour>>8)&0xFF)*( (data-1)/14.0f)); - uint8_t blueComponent = ((minColour)&0xFF) + (( (maxColour)&0xFF - (minColour)&0xFF)*( (data-1)/14.0f)); + uint8_t redComponent = + ((minColour >> 16) & 0xFF) + + (((maxColour >> 16) & 0xFF - (minColour >> 16) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t greenComponent = + ((minColour >> 8) & 0xFF) + + (((maxColour >> 8) & 0xFF - (minColour >> 8) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t blueComponent = + ((minColour) & 0xFF) + + (((maxColour) & 0xFF - (minColour) & 0xFF) * ((data - 1) / 14.0f)); - colour = redComponent<<16 | greenComponent<<8 | blueComponent; - } + colour = redComponent << 16 | greenComponent << 8 | blueComponent; + } - float red = ((colour>>16)&0xFF)/255.0f; - float green = ((colour>>8)&0xFF)/255.0f; - float blue = (colour&0xFF)/255.0f; + float red = ((colour >> 16) & 0xFF) / 255.0f; + float green = ((colour >> 8) & 0xFF) / 255.0f; + float blue = (colour & 0xFF) / 255.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->color( red, green, blue ); - } - else - { - t->color( br * red, br * green, br * blue ); - } - const float dustOffset = 0.25f / 16.0f; - const float overlayOffset = 0.25f / 16.0f; + if (SharedConstants::TEXTURE_LIGHTING) { + t->color(red, green, blue); + } else { + t->color(br * red, br * green, br * blue); + } + const float dustOffset = 0.25f / 16.0f; + const float overlayOffset = 0.25f / 16.0f; - bool w = RedStoneDustTile::shouldConnectTo( level, x - 1, y, z, Direction::WEST ) - || ( !level->isSolidBlockingTile( x - 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x - 1, y - 1, z, - Direction::UNDEFINED ) ); - bool e = RedStoneDustTile::shouldConnectTo( level, x + 1, y, z, Direction::EAST ) - || ( !level->isSolidBlockingTile( x + 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x + 1, y - 1, z, - Direction::UNDEFINED ) ); - bool n = RedStoneDustTile::shouldConnectTo( level, x, y, z - 1, Direction::NORTH ) - || ( !level->isSolidBlockingTile( x, y, z - 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y - 1, z - 1, - Direction::UNDEFINED ) ); - bool s = RedStoneDustTile::shouldConnectTo( level, x, y, z + 1, Direction::SOUTH ) - || ( !level->isSolidBlockingTile( x, y, z + 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y - 1, z + 1, - Direction::UNDEFINED ) ); - if ( !level->isSolidBlockingTile( x, y + 1, z ) ) - { - if ( level->isSolidBlockingTile( x - 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x - 1, y + 1, z, - Direction::UNDEFINED ) ) w - = true; - if ( level->isSolidBlockingTile( x + 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x + 1, y + 1, z, - Direction::UNDEFINED ) ) e - = true; - if ( level->isSolidBlockingTile( x, y, z - 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y + 1, z - 1, - Direction::UNDEFINED ) ) n - = true; - if ( level->isSolidBlockingTile( x, y, z + 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y + 1, z + 1, - Direction::UNDEFINED ) ) s - = true; - } - float x0 = ( float )( x + 0.0f ); - float x1 = ( float )( x + 1.0f ); - float z0 = ( float )( z + 0.0f ); - float z1 = ( float )( z + 1.0f ); + bool w = RedStoneDustTile::shouldConnectTo(level, x - 1, y, z, + Direction::WEST) || + (!level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x - 1, y - 1, z, + Direction::UNDEFINED)); + bool e = RedStoneDustTile::shouldConnectTo(level, x + 1, y, z, + Direction::EAST) || + (!level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x + 1, y - 1, z, + Direction::UNDEFINED)); + bool n = RedStoneDustTile::shouldConnectTo(level, x, y, z - 1, + Direction::NORTH) || + (!level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldConnectTo(level, x, y - 1, z - 1, + Direction::UNDEFINED)); + bool s = RedStoneDustTile::shouldConnectTo(level, x, y, z + 1, + Direction::SOUTH) || + (!level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldConnectTo(level, x, y - 1, z + 1, + Direction::UNDEFINED)); + if (!level->isSolidBlockingTile(x, y + 1, z)) { + if (level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x - 1, y + 1, z, + Direction::UNDEFINED)) + w = true; + if (level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x + 1, y + 1, z, + Direction::UNDEFINED)) + e = true; + if (level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldConnectTo(level, x, y + 1, z - 1, + Direction::UNDEFINED)) + n = true; + if (level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldConnectTo(level, x, y + 1, z + 1, + Direction::UNDEFINED)) + s = true; + } + float x0 = (float)(x + 0.0f); + float x1 = (float)(x + 1.0f); + float z0 = (float)(z + 0.0f); + float z1 = (float)(z + 1.0f); - int pic = 0; - if ( ( w || e ) && ( !n && !s ) ) pic = 1; - if ( ( n || s ) && ( !e && !w ) ) pic = 2; + int pic = 0; + if ((w || e) && (!n && !s)) pic = 1; + if ((n || s) && (!e && !w)) pic = 2; - if ( pic == 0 ) - { -// if ( e || n || s || w ) - int u0 = 0; - int v0 = 0; - int u1 = SharedConstants::WORLD_RESOLUTION; - int v1 = SharedConstants::WORLD_RESOLUTION; + if (pic == 0) { + // if ( e || n || s || w ) + int u0 = 0; + int v0 = 0; + int u1 = SharedConstants::WORLD_RESOLUTION; + int v1 = SharedConstants::WORLD_RESOLUTION; - int cutDistance = 5; - if (!w) x0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!w) u0 += cutDistance; - if (!e) x1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!e) u1 -= cutDistance; - if (!n) z0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!n) v0 += cutDistance; - if (!s) z1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!s) v1 -= cutDistance; - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTexture->getU(u1, true), crossTexture->getV(v1) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTexture->getU(u1, true), crossTexture->getV(v0) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTexture->getU(u0, true), crossTexture->getV(v0) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTexture->getU(u0, true), crossTexture->getV(v1) ); + int cutDistance = 5; + if (!w) x0 += cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!w) u0 += cutDistance; + if (!e) x1 -= cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!e) u1 -= cutDistance; + if (!n) z0 += cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!n) v0 += cutDistance; + if (!s) z1 -= cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!s) v1 -= cutDistance; + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + crossTexture->getU(u1, true), crossTexture->getV(v1)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + crossTexture->getU(u1, true), crossTexture->getV(v0)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + crossTexture->getU(u0, true), crossTexture->getV(v0)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + crossTexture->getU(u0, true), crossTexture->getV(v1)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTextureOverlay->getU(u1, true), crossTextureOverlay->getV(v1, true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTextureOverlay->getU(u1, true), crossTextureOverlay->getV(v0, true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTextureOverlay->getU(u0, true), crossTextureOverlay->getV(v0, true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTextureOverlay->getU(u0, true), crossTextureOverlay->getV(v1, true) ); - } - else if ( pic == 1 ) - { - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + crossTextureOverlay->getU(u1, true), + crossTextureOverlay->getV(v1, true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + crossTextureOverlay->getU(u1, true), + crossTextureOverlay->getV(v0, true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + crossTextureOverlay->getU(u0, true), + crossTextureOverlay->getV(v0, true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + crossTextureOverlay->getU(u0, true), + crossTextureOverlay->getV(v1, true)); + } else if (pic == 1) { + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV1(true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + lineTexture->getU1(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + lineTexture->getU0(true), lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + } else { + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV1(true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - } + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + } - if ( !level->isSolidBlockingTile( x, y + 1, z ) ) - { - const float yStretch = .35f / 16.0f; + if (!level->isSolidBlockingTile(x, y + 1, z)) { + const float yStretch = .35f / 16.0f; - if ( level->isSolidBlockingTile( x - 1, y, z ) && level->getTile( x - 1, y + 1, z ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV1(true) ); + if (level->isSolidBlockingTile(x - 1, y, z) && + level->getTile(x - 1, y + 1, z) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + dustOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 0), (float)(z + 1), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 0), (float)(z + 0), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTexture->getU1(true), + lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - } - if ( level->isSolidBlockingTile( x + 1, y, z ) && level->getTile( x + 1, y + 1, z ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + overlayOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 0), + (float)(z + 1), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 0), + (float)(z + 0), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + } + if (level->isSolidBlockingTile(x + 1, y, z) && + level->getTile(x + 1, y + 1, z) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 0), + (float)(z + 1), lineTexture->getU0(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTexture->getU1(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 0), + (float)(z + 0), lineTexture->getU0(true), + lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - } - if ( level->isSolidBlockingTile( x, y, z - 1 ) && level->getTile( x, y + 1, z - 1 ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + 1 - overlayOffset), (float)(y + 0), + (float)(z + 1), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1 - overlayOffset), + (float)(y + 1 + yStretch), (float)(z + 1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1 - overlayOffset), + (float)(y + 1 + yStretch), (float)(z + 0), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 1 - overlayOffset), (float)(y + 0), + (float)(z + 0), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + } + if (level->isSolidBlockingTile(x, y, z - 1) && + level->getTile(x, y + 1, z - 1) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z + dustOffset), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + dustOffset), lineTexture->getU1(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + dustOffset), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z + dustOffset), + lineTexture->getU0(true), lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - } - if ( level->isSolidBlockingTile( x, y, z + 1 ) && level->getTile( x, y + 1, z + 1 ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + } + if (level->isSolidBlockingTile(x, y, z + 1) && + level->getTile(x, y + 1, z + 1) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + 1 - dustOffset), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + 1 - dustOffset), lineTexture->getU0(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + 1 - dustOffset), lineTexture->getU0(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + 1 - dustOffset), lineTexture->getU1(true), + lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - } - } - - - return true; + t->color(br, br, br); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + } + } + return true; } -bool TileRenderer::tesselateRailInWorld( RailTile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); +bool TileRenderer::tesselateRailInWorld(RailTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); + int data = level->getData(x, y, z); - Icon *tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; + Icon* tex = getTexture(tt, 0, data); + if (hasFixedTexture()) tex = fixedTexture; - if ( tt->isUsesDataBit() ) - { - data &= RailTile::RAIL_DIRECTION_MASK; - } + if (tt->isUsesDataBit()) { + data &= RailTile::RAIL_DIRECTION_MASK; + } - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float r = 1 / 16.0f; + float r = 1 / 16.0f; - float x0 = ( float )( x + 1 ); - float x1 = ( float )( x + 1 ); - float x2 = ( float )( x + 0 ); - float x3 = ( float )( x + 0 ); + float x0 = (float)(x + 1); + float x1 = (float)(x + 1); + float x2 = (float)(x + 0); + float x3 = (float)(x + 0); - float z0 = ( float )( z + 0 ); - float z1 = ( float )( z + 1 ); - float z2 = ( float )( z + 1 ); - float z3 = ( float )( z + 0 ); + float z0 = (float)(z + 0); + float z1 = (float)(z + 1); + float z2 = (float)(z + 1); + float z3 = (float)(z + 0); - float y0 = ( float )( y + r ); - float y1 = ( float )( y + r ); - float y2 = ( float )( y + r ); - float y3 = ( float )( y + r ); + float y0 = (float)(y + r); + float y1 = (float)(y + r); + float y2 = (float)(y + r); + float y3 = (float)(y + r); - if ( data == 1 || data == 2 || data == 3 || data == 7 ) - { - x0 = x3 = ( float )( x + 1 ); - x1 = x2 = ( float )( x + 0 ); - z0 = z1 = ( float )( z + 1 ); - z2 = z3 = ( float )( z + 0 ); - } - else if ( data == 8 ) - { - x0 = x1 = ( float )( x + 0 ); - x2 = x3 = ( float )( x + 1 ); - z0 = z3 = ( float )( z + 1 ); - z1 = z2 = ( float )( z + 0 ); - } - else if ( data == 9 ) - { - x0 = x3 = ( float )( x + 0 ); - x1 = x2 = ( float )( x + 1 ); - z0 = z1 = ( float )( z + 0 ); - z2 = z3 = ( float )( z + 1 ); - } + if (data == 1 || data == 2 || data == 3 || data == 7) { + x0 = x3 = (float)(x + 1); + x1 = x2 = (float)(x + 0); + z0 = z1 = (float)(z + 1); + z2 = z3 = (float)(z + 0); + } else if (data == 8) { + x0 = x1 = (float)(x + 0); + x2 = x3 = (float)(x + 1); + z0 = z3 = (float)(z + 1); + z1 = z2 = (float)(z + 0); + } else if (data == 9) { + x0 = x3 = (float)(x + 0); + x1 = x2 = (float)(x + 1); + z0 = z1 = (float)(z + 0); + z2 = z3 = (float)(z + 1); + } - if ( data == 2 || data == 4 ) - { - y0 += 1; - y3 += 1; - } - else if ( data == 3 || data == 5 ) - { - y1 += 1; - y2 += 1; - } + if (data == 2 || data == 4) { + y0 += 1; + y3 += 1; + } else if (data == 3 || data == 5) { + y1 += 1; + y2 += 1; + } - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x2 ), ( float )( y2 ), ( float )( z2 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x3 ), ( float )( y3 ), ( float )( z3 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x2), (float)(y2), (float)(z2), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x3), (float)(y3), (float)(z3), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x3 ), ( float )( y3 ), ( float )( z3 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x2 ), ( float )( y2 ), ( float )( z2 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - return true; + t->vertexUV((float)(x3), (float)(y3), (float)(z3), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x2), (float)(y2), (float)(z2), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); + return true; } -bool TileRenderer::tesselateLadderInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateLadderInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - float br = 1; - t->color( br, br, br ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + float br = 1; + t->color(br, br, br); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - int face = level->getData( x, y, z ); + int face = level->getData(x, y, z); - float o = 0 / 16.0f; - float r = 0.05f; - if ( face == 5 ) - { - t->vertexUV( ( float )( x + r ), ( float )( y + 1 + o ), ( float )( z + 1 + - o ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 0 - o ), ( float )( z + 1 + - o ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 0 - o ), ( float )( z + 0 - - o ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 + o ), ( float )( z + 0 - - o ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( face == 4 ) - { - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 0 - o ), ( float )( z + 1 + - o ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 1 + o ), ( float )( z + 1 + - o ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 1 + o ), ( float )( z + 0 - - o ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 0 - o ), ( float )( z + 0 - - o ), ( float )( u0 ), ( float )( v1 ) ); - } - if ( face == 3 ) - { - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 0 - o ), ( float )( z + - r ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 1 + o ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 1 + o ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 0 - o ), ( float )( z + - r ), ( float )( u0 ), ( float )( v1 ) ); - } - if ( face == 2 ) - { - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 1 + o ), ( float )( z + 1 - - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 0 - o ), ( float )( z + 1 - - r ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 0 - o ), ( float )( z + 1 - - r ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 1 + o ), ( float )( z + 1 - - r ), ( float )( u1 ), ( float )( v0 ) ); - } - - return true; + float o = 0 / 16.0f; + float r = 0.05f; + if (face == 5) { + t->vertexUV((float)(x + r), (float)(y + 1 + o), (float)(z + 1 + o), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + r), (float)(y + 0 - o), (float)(z + 1 + o), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 0 - o), (float)(z + 0 - o), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 1 + o), (float)(z + 0 - o), + (float)(u1), (float)(v0)); + } + if (face == 4) { + t->vertexUV((float)(x + 1 - r), (float)(y + 0 - o), (float)(z + 1 + o), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 - r), (float)(y + 1 + o), (float)(z + 1 + o), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1 - r), (float)(y + 1 + o), (float)(z + 0 - o), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 - r), (float)(y + 0 - o), (float)(z + 0 - o), + (float)(u0), (float)(v1)); + } + if (face == 3) { + t->vertexUV((float)(x + 1 + o), (float)(y + 0 - o), (float)(z + r), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 + o), (float)(y + 1 + o), (float)(z + r), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0 - o), (float)(y + 1 + o), (float)(z + r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 0 - o), (float)(y + 0 - o), (float)(z + r), + (float)(u0), (float)(v1)); + } + if (face == 2) { + t->vertexUV((float)(x + 1 + o), (float)(y + 1 + o), (float)(z + 1 - r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 + o), (float)(y + 0 - o), (float)(z + 1 - r), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0 - o), (float)(y + 0 - o), (float)(z + 1 - r), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0 - o), (float)(y + 1 + o), (float)(z + 1 - r), + (float)(u1), (float)(v0)); + } + return true; } -bool TileRenderer::tesselateVineInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateVineInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; + float br = 1; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + } else { + br = tt->getBrightness(level, x, y, z); + } + { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - float br = 1; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - { - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + t->color(br * r, br * g, br * b); + } - t->color( br * r, br * g, br * b ); - } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float r = 0.05f; + int facings = level->getData(x, y, z); - float r = 0.05f; - int facings = level->getData( x, y, z ); + if ((facings & VineTile::VINE_WEST) != 0) { + t->vertexUV(x + r, y + 1, z + 1, u0, v0); + t->vertexUV(x + r, y + 0, z + 1, u0, v1); + t->vertexUV(x + r, y + 0, z + 0, u1, v1); + t->vertexUV(x + r, y + 1, z + 0, u1, v0); - if ( ( facings & VineTile::VINE_WEST ) != 0 ) - { - t->vertexUV( x + r, y + 1, z + 1, u0, v0 ); - t->vertexUV( x + r, y + 0, z + 1, u0, v1 ); - t->vertexUV( x + r, y + 0, z + 0, u1, v1 ); - t->vertexUV( x + r, y + 1, z + 0, u1, v0 ); + t->vertexUV(x + r, y + 1, z + 0, u1, v0); + t->vertexUV(x + r, y + 0, z + 0, u1, v1); + t->vertexUV(x + r, y + 0, z + 1, u0, v1); + t->vertexUV(x + r, y + 1, z + 1, u0, v0); + } + if ((facings & VineTile::VINE_EAST) != 0) { + t->vertexUV(x + 1 - r, y + 0, z + 1, u1, v1); + t->vertexUV(x + 1 - r, y + 1, z + 1, u1, v0); + t->vertexUV(x + 1 - r, y + 1, z + 0, u0, v0); + t->vertexUV(x + 1 - r, y + 0, z + 0, u0, v1); - t->vertexUV( x + r, y + 1, z + 0, u1, v0 ); - t->vertexUV( x + r, y + 0, z + 0, u1, v1 ); - t->vertexUV( x + r, y + 0, z + 1, u0, v1 ); - t->vertexUV( x + r, y + 1, z + 1, u0, v0 ); - } - if ( ( facings & VineTile::VINE_EAST ) != 0 ) - { - t->vertexUV( x + 1 - r, y + 0, z + 1, u1, v1 ); - t->vertexUV( x + 1 - r, y + 1, z + 1, u1, v0 ); - t->vertexUV( x + 1 - r, y + 1, z + 0, u0, v0 ); - t->vertexUV( x + 1 - r, y + 0, z + 0, u0, v1 ); + t->vertexUV(x + 1 - r, y + 0, z + 0, u0, v1); + t->vertexUV(x + 1 - r, y + 1, z + 0, u0, v0); + t->vertexUV(x + 1 - r, y + 1, z + 1, u1, v0); + t->vertexUV(x + 1 - r, y + 0, z + 1, u1, v1); + } + if ((facings & VineTile::VINE_NORTH) != 0) { + t->vertexUV(x + 1, y + 0, z + r, u1, v1); + t->vertexUV(x + 1, y + 1, z + r, u1, v0); + t->vertexUV(x + 0, y + 1, z + r, u0, v0); + t->vertexUV(x + 0, y + 0, z + r, u0, v1); - t->vertexUV( x + 1 - r, y + 0, z + 0, u0, v1 ); - t->vertexUV( x + 1 - r, y + 1, z + 0, u0, v0 ); - t->vertexUV( x + 1 - r, y + 1, z + 1, u1, v0 ); - t->vertexUV( x + 1 - r, y + 0, z + 1, u1, v1 ); - } - if ( ( facings & VineTile::VINE_NORTH ) != 0 ) - { - t->vertexUV( x + 1, y + 0, z + r, u1, v1 ); - t->vertexUV( x + 1, y + 1, z + r, u1, v0 ); - t->vertexUV( x + 0, y + 1, z + r, u0, v0 ); - t->vertexUV( x + 0, y + 0, z + r, u0, v1 ); + t->vertexUV(x + 0, y + 0, z + r, u0, v1); + t->vertexUV(x + 0, y + 1, z + r, u0, v0); + t->vertexUV(x + 1, y + 1, z + r, u1, v0); + t->vertexUV(x + 1, y + 0, z + r, u1, v1); + } + if ((facings & VineTile::VINE_SOUTH) != 0) { + t->vertexUV(x + 1, y + 1, z + 1 - r, u0, v0); + t->vertexUV(x + 1, y + 0, z + 1 - r, u0, v1); + t->vertexUV(x + 0, y + 0, z + 1 - r, u1, v1); + t->vertexUV(x + 0, y + 1, z + 1 - r, u1, v0); - t->vertexUV( x + 0, y + 0, z + r, u0, v1 ); - t->vertexUV( x + 0, y + 1, z + r, u0, v0 ); - t->vertexUV( x + 1, y + 1, z + r, u1, v0 ); - t->vertexUV( x + 1, y + 0, z + r, u1, v1 ); - } - if ( ( facings & VineTile::VINE_SOUTH ) != 0 ) - { - t->vertexUV( x + 1, y + 1, z + 1 - r, u0, v0 ); - t->vertexUV( x + 1, y + 0, z + 1 - r, u0, v1 ); - t->vertexUV( x + 0, y + 0, z + 1 - r, u1, v1 ); - t->vertexUV( x + 0, y + 1, z + 1 - r, u1, v0 ); + t->vertexUV(x + 0, y + 1, z + 1 - r, u1, v0); + t->vertexUV(x + 0, y + 0, z + 1 - r, u1, v1); + t->vertexUV(x + 1, y + 0, z + 1 - r, u0, v1); + t->vertexUV(x + 1, y + 1, z + 1 - r, u0, v0); + } + if (level->isSolidBlockingTile(x, y + 1, z)) { + t->vertexUV(x + 1, y + 1 - r, z + 0, u0, v0); + t->vertexUV(x + 1, y + 1 - r, z + 1, u0, v1); + t->vertexUV(x + 0, y + 1 - r, z + 1, u1, v1); + t->vertexUV(x + 0, y + 1 - r, z + 0, u1, v0); + } - t->vertexUV( x + 0, y + 1, z + 1 - r, u1, v0 ); - t->vertexUV( x + 0, y + 0, z + 1 - r, u1, v1 ); - t->vertexUV( x + 1, y + 0, z + 1 - r, u0, v1 ); - t->vertexUV( x + 1, y + 1, z + 1 - r, u0, v0 ); - } - if ( level->isSolidBlockingTile( x, y + 1, z ) ) - { - t->vertexUV( x + 1, y + 1 - r, z + 0, u0, v0 ); - t->vertexUV( x + 1, y + 1 - r, z + 1, u0, v1 ); - t->vertexUV( x + 0, y + 1 - r, z + 1, u1, v1 ); - t->vertexUV( x + 0, y + 1 - r, z + 0, u1, v0 ); - } - - return true; + return true; } -bool TileRenderer::tesselateThinFenceInWorld( ThinFenceTile* tt, int x, int y, int z ) -{ - int depth = level->getMaxBuildHeight(); - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, + int z) { + int depth = level->getMaxBuildHeight(); + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - Icon *tex; - Icon *edgeTex; + Icon* tex; + Icon* edgeTex; - if ( hasFixedTexture() ) - { - tex = fixedTexture; - edgeTex = fixedTexture; - } - else - { - int data = level->getData( x, y, z ); - tex = getTexture( tt, 0, data ); - edgeTex = tt->getEdgeTexture(); - } + if (hasFixedTexture()) { + tex = fixedTexture; + edgeTex = fixedTexture; + } else { + int data = level->getData(x, y, z); + tex = getTexture(tt, 0, data); + edgeTex = tt->getEdgeTexture(); + } - int xt = tex->getX(); - int yt = tex->getY(); - float u0 = tex->getU0(true); - float u1 = tex->getU(8, true); - float u2 = tex->getU1(true); - float v0 = tex->getV0(true); - float v2 = tex->getV1(true); + int xt = tex->getX(); + int yt = tex->getY(); + float u0 = tex->getU0(true); + float u1 = tex->getU(8, true); + float u2 = tex->getU1(true); + float v0 = tex->getV0(true); + float v2 = tex->getV1(true); - int xet = edgeTex->getX(); - int yet = edgeTex->getY(); + int xet = edgeTex->getX(); + int yet = edgeTex->getY(); - float iu0 = edgeTex->getU(7, true); - float iu1 = edgeTex->getU(9, true); - float iv0 = edgeTex->getV0(true); - float iv1 = edgeTex->getV(8, true); - float iv2 = edgeTex->getV1(true); + float iu0 = edgeTex->getU(7, true); + float iu1 = edgeTex->getU(9, true); + float iv0 = edgeTex->getV0(true); + float iv1 = edgeTex->getV(8, true); + float iv2 = edgeTex->getV1(true); - float x0 = (float)x; - float x1 = x + 0.5f; - float x2 = x + 1.0f; - float z0 = (float)z; - float z1 = z + 0.5f; - float z2 = z + 1.0f; - float ix0 = x + 0.5f - 1.0f / 16.0f; - float ix1 = x + 0.5f + 1.0f / 16.0f; - float iz0 = z + 0.5f - 1.0f / 16.0f; - float iz1 = z + 0.5f + 1.0f / 16.0f; + float x0 = (float)x; + float x1 = x + 0.5f; + float x2 = x + 1.0f; + float z0 = (float)z; + float z1 = z + 0.5f; + float z2 = z + 1.0f; + float ix0 = x + 0.5f - 1.0f / 16.0f; + float ix1 = x + 0.5f + 1.0f / 16.0f; + float iz0 = z + 0.5f - 1.0f / 16.0f; + float iz1 = z + 0.5f + 1.0f / 16.0f; - bool n = tt->attachsTo( level->getTile( x, y, z - 1 ) ); - bool s = tt->attachsTo( level->getTile( x, y, z + 1 ) ); - bool w = tt->attachsTo( level->getTile( x - 1, y, z ) ); - bool e = tt->attachsTo( level->getTile( x + 1, y, z ) ); + bool n = tt->attachsTo(level->getTile(x, y, z - 1)); + bool s = tt->attachsTo(level->getTile(x, y, z + 1)); + bool w = tt->attachsTo(level->getTile(x - 1, y, z)); + bool e = tt->attachsTo(level->getTile(x + 1, y, z)); - bool up = tt->shouldRenderFace( level, x, y + 1, z, Facing::UP ); - bool down = tt->shouldRenderFace( level, x, y - 1, z, Facing::DOWN ); + bool up = tt->shouldRenderFace(level, x, y + 1, z, Facing::UP); + bool down = tt->shouldRenderFace(level, x, y - 1, z, Facing::DOWN); - const float noZFightingOffset = 0.01f; - const float noZFightingOffsetB = 0.005; + const float noZFightingOffset = 0.01f; + const float noZFightingOffsetB = 0.005; - if ( ( w && e ) || ( !w && !e && !n && !s ) ) - { - t->vertexUV( x0, y + 1, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v2 ); - t->vertexUV( x2, y + 0, z1, u2, v2 ); - t->vertexUV( x2, y + 1, z1, u2, v0 ); + if ((w && e) || (!w && !e && !n && !s)) { + t->vertexUV(x0, y + 1, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v2); + t->vertexUV(x2, y + 0, z1, u2, v2); + t->vertexUV(x2, y + 1, z1, u2, v0); - t->vertexUV( x2, y + 1, z1, u0, v0 ); - t->vertexUV( x2, y + 0, z1, u0, v2 ); - t->vertexUV( x0, y + 0, z1, u2, v2 ); - t->vertexUV( x0, y + 1, z1, u2, v0 ); + t->vertexUV(x2, y + 1, z1, u0, v0); + t->vertexUV(x2, y + 0, z1, u0, v2); + t->vertexUV(x0, y + 0, z1, u2, v2); + t->vertexUV(x0, y + 1, z1, u2, v0); - if ( up ) - { - // small edge texture - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); + if (up) { + // small edge texture + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - } - else - { - if ( y < ( depth - 1 ) && level->isEmptyTile( x - 1, y + 1, z ) ) - { - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv2); + } else { + if (y < (depth - 1) && level->isEmptyTile(x - 1, y + 1, z)) { + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - } - if ( y < ( depth - 1 ) && level->isEmptyTile( x + 1, y + 1, z ) ) - { - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + } + if (y < (depth - 1) && level->isEmptyTile(x + 1, y + 1, z)) { + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - } - } - if ( down ) - { - // small edge texture - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + } + } + if (down) { + // small edge texture + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv2 ); - } - else - { - if ( y > 1 && level->isEmptyTile( x - 1, y - 1, z ) ) - { - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv2); + } else { + if (y > 1 && level->isEmptyTile(x - 1, y - 1, z)) { + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - } - if ( y > 1 && level->isEmptyTile( x + 1, y - 1, z ) ) - { - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + } + if (y > 1 && level->isEmptyTile(x + 1, y - 1, z)) { + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - } - } - } - else if ( w && !e ) - { - // half-step towards west - t->vertexUV( x0, y + 1, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v2 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 1, z1, u1, v0 ); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + } + } + } else if (w && !e) { + // half-step towards west + t->vertexUV(x0, y + 1, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v2); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 1, z1, u1, v0); - t->vertexUV( x1, y + 1, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v2 ); - t->vertexUV( x0, y + 0, z1, u1, v2 ); - t->vertexUV( x0, y + 1, z1, u1, v0 ); + t->vertexUV(x1, y + 1, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v2); + t->vertexUV(x0, y + 0, z1, u1, v2); + t->vertexUV(x0, y + 1, z1, u1, v0); - // small edge texture - if ( !s && !n ) - { - t->vertexUV( x1, y + 1, iz1, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz1, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz0, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz0, iu1, iv0 ); + // small edge texture + if (!s && !n) { + t->vertexUV(x1, y + 1, iz1, iu0, iv0); + t->vertexUV(x1, y + 0, iz1, iu0, iv2); + t->vertexUV(x1, y + 0, iz0, iu1, iv2); + t->vertexUV(x1, y + 1, iz0, iu1, iv0); - t->vertexUV( x1, y + 1, iz0, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz1, iu1, iv0 ); - } + t->vertexUV(x1, y + 1, iz0, iu0, iv0); + t->vertexUV(x1, y + 0, iz0, iu0, iv2); + t->vertexUV(x1, y + 0, iz1, iu1, iv2); + t->vertexUV(x1, y + 1, iz1, iu1, iv0); + } - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x - 1, y + 1, z ) ) ) - { - // small edge texture - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); + if (up || (y < (depth - 1) && level->isEmptyTile(x - 1, y + 1, z))) { + // small edge texture + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x - 1, y - 1, z ) ) ) - { - // small edge texture - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + } + if (down || (y > 1 && level->isEmptyTile(x - 1, y - 1, z))) { + // small edge texture + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - } + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + } - } - else if ( !w && e ) - { - // half-step towards east - t->vertexUV( x1, y + 1, z1, u1, v0 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x2, y + 0, z1, u2, v2 ); - t->vertexUV( x2, y + 1, z1, u2, v0 ); + } else if (!w && e) { + // half-step towards east + t->vertexUV(x1, y + 1, z1, u1, v0); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x2, y + 0, z1, u2, v2); + t->vertexUV(x2, y + 1, z1, u2, v0); - t->vertexUV( x2, y + 1, z1, u1, v0 ); - t->vertexUV( x2, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 0, z1, u2, v2 ); - t->vertexUV( x1, y + 1, z1, u2, v0 ); + t->vertexUV(x2, y + 1, z1, u1, v0); + t->vertexUV(x2, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 0, z1, u2, v2); + t->vertexUV(x1, y + 1, z1, u2, v0); - // small edge texture - if ( !s && !n ) - { - t->vertexUV( x1, y + 1, iz0, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz1, iu1, iv0 ); + // small edge texture + if (!s && !n) { + t->vertexUV(x1, y + 1, iz0, iu0, iv0); + t->vertexUV(x1, y + 0, iz0, iu0, iv2); + t->vertexUV(x1, y + 0, iz1, iu1, iv2); + t->vertexUV(x1, y + 1, iz1, iu1, iv0); - t->vertexUV( x1, y + 1, iz1, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz1, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz0, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz0, iu1, iv0 ); - } + t->vertexUV(x1, y + 1, iz1, iu0, iv0); + t->vertexUV(x1, y + 0, iz1, iu0, iv2); + t->vertexUV(x1, y + 0, iz0, iu1, iv2); + t->vertexUV(x1, y + 1, iz0, iu1, iv0); + } - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x + 1, y + 1, z ) ) ) - { - // small edge texture - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); + if (up || (y < (depth - 1) && level->isEmptyTile(x + 1, y + 1, z))) { + // small edge texture + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x + 1, y - 1, z ) ) ) - { - // small edge texture - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + } + if (down || (y > 1 && level->isEmptyTile(x + 1, y - 1, z))) { + // small edge texture + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - } + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + } + } - } + if ((n && s) || (!w && !e && !n && !s)) { + // straight north-south + t->vertexUV(x1, y + 1, z2, u0, v0); + t->vertexUV(x1, y + 0, z2, u0, v2); + t->vertexUV(x1, y + 0, z0, u2, v2); + t->vertexUV(x1, y + 1, z0, u2, v0); - if ( ( n && s ) || ( !w && !e && !n && !s ) ) - { - // straight north-south - t->vertexUV( x1, y + 1, z2, u0, v0 ); - t->vertexUV( x1, y + 0, z2, u0, v2 ); - t->vertexUV( x1, y + 0, z0, u2, v2 ); - t->vertexUV( x1, y + 1, z0, u2, v0 ); + t->vertexUV(x1, y + 1, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v2); + t->vertexUV(x1, y + 0, z2, u2, v2); + t->vertexUV(x1, y + 1, z2, u2, v0); - t->vertexUV( x1, y + 1, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v2 ); - t->vertexUV( x1, y + 0, z2, u2, v2 ); - t->vertexUV( x1, y + 1, z2, u2, v0 ); + if (up) { + // small edge texture + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu0, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); - if ( up ) - { - // small edge texture - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu0, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu0, iv2); + } else { + if (y < (depth - 1) && level->isEmptyTile(x, y + 1, z - 1)) { + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv0); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu0, iv2 ); - } - else - { - if ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z - 1 ) ) - { - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv0); + } + if (y < (depth - 1) && level->isEmptyTile(x, y + 1, z + 1)) { + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv0 ); - } - if ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z + 1 ) ) - { - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv1); + } + } + if (down) { + // small edge texture + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu0, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv1 ); - } - } - if ( down ) - { - // small edge texture - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu0, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu0, iv2); + } else { + if (y > 1 && level->isEmptyTile(x, y - 1, z - 1)) { + // north half-step + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv0); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu0, iv2 ); - } - else - { - if ( y > 1 && level->isEmptyTile( x, y - 1, z - 1 ) ) - { - // north half-step - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv0); + } + if (y > 1 && level->isEmptyTile(x, y - 1, z + 1)) { + // south half-step + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv0 ); - } - if ( y > 1 && level->isEmptyTile( x, y - 1, z + 1 ) ) - { - // south half-step - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv1); + } + } - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv1 ); - } - } + } else if (n && !s) { + // half-step towards north + t->vertexUV(x1, y + 1, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v2); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 1, z1, u1, v0); - } - else if ( n && !s ) - { - // half-step towards north - t->vertexUV( x1, y + 1, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v2 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 1, z1, u1, v0 ); + t->vertexUV(x1, y + 1, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v2); + t->vertexUV(x1, y + 0, z0, u1, v2); + t->vertexUV(x1, y + 1, z0, u1, v0); - t->vertexUV( x1, y + 1, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v2 ); - t->vertexUV( x1, y + 0, z0, u1, v2 ); - t->vertexUV( x1, y + 1, z0, u1, v0 ); + // small edge texture + if (!e && !w) { + t->vertexUV(ix0, y + 1, z1, iu0, iv0); + t->vertexUV(ix0, y + 0, z1, iu0, iv2); + t->vertexUV(ix1, y + 0, z1, iu1, iv2); + t->vertexUV(ix1, y + 1, z1, iu1, iv0); - // small edge texture - if ( !e && !w ) - { - t->vertexUV( ix0, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix0, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1, z1, iu1, iv0 ); + t->vertexUV(ix1, y + 1, z1, iu0, iv0); + t->vertexUV(ix1, y + 0, z1, iu0, iv2); + t->vertexUV(ix0, y + 0, z1, iu1, iv2); + t->vertexUV(ix0, y + 1, z1, iu1, iv0); + } - t->vertexUV( ix1, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix1, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix0, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix0, y + 1, z1, iu1, iv0 ); - } + if (up || (y < (depth - 1) && level->isEmptyTile(x, y + 1, z - 1))) { + // small edge texture + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv0); - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z - 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv0); + } - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv0 ); - } + if (down || (y > 1 && level->isEmptyTile(x, y - 1, z - 1))) { + // small edge texture + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv0); - if ( down || ( y > 1 && level->isEmptyTile( x, y - 1, z - 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv0); + } - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv0 ); - } + } else if (!n && s) { + // half-step towards south + t->vertexUV(x1, y + 1, z1, u1, v0); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 0, z2, u2, v2); + t->vertexUV(x1, y + 1, z2, u2, v0); - } - else if ( !n && s ) - { - // half-step towards south - t->vertexUV( x1, y + 1, z1, u1, v0 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 0, z2, u2, v2 ); - t->vertexUV( x1, y + 1, z2, u2, v0 ); + t->vertexUV(x1, y + 1, z2, u1, v0); + t->vertexUV(x1, y + 0, z2, u1, v2); + t->vertexUV(x1, y + 0, z1, u2, v2); + t->vertexUV(x1, y + 1, z1, u2, v0); - t->vertexUV( x1, y + 1, z2, u1, v0 ); - t->vertexUV( x1, y + 0, z2, u1, v2 ); - t->vertexUV( x1, y + 0, z1, u2, v2 ); - t->vertexUV( x1, y + 1, z1, u2, v0 ); + // small edge texture + if (!e && !w) { + t->vertexUV(ix1, y + 1, z1, iu0, iv0); + t->vertexUV(ix1, y + 0, z1, iu0, iv2); + t->vertexUV(ix0, y + 0, z1, iu1, iv2); + t->vertexUV(ix0, y + 1, z1, iu1, iv0); - // small edge texture - if ( !e && !w ) - { - t->vertexUV( ix1, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix1, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix0, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix0, y + 1, z1, iu1, iv0 ); + t->vertexUV(ix0, y + 1, z1, iu0, iv0); + t->vertexUV(ix0, y + 0, z1, iu0, iv2); + t->vertexUV(ix1, y + 0, z1, iu1, iv2); + t->vertexUV(ix1, y + 1, z1, iu1, iv0); + } - t->vertexUV( ix0, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix0, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1, z1, iu1, iv0 ); - } + if (up || (y < (depth - 1) && level->isEmptyTile(x, y + 1, z + 1))) { + // small edge texture + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv1); - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z + 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv1); + } + if (down || (y > 1 && level->isEmptyTile(x, y - 1, z + 1))) { + // small edge texture + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv1 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x, y - 1, z + 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv1); + } + } - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv1 ); - } - - } - - return true; + return true; } -bool TileRenderer::tesselateCrossInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateCrossInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - float xt = (float)x; - float yt = (float)y; - float zt = (float)z; + float xt = (float)x; + float yt = (float)y; + float zt = (float)z; - if (tt == Tile::tallgrass) - { - // 4jcraft add a bunch of casts to prevent overflow (i pray to god) - int64_t seed = ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + ((uint64_t)seed * 11ULL)); + if (tt == Tile::tallgrass) { + // 4jcraft add a bunch of casts to prevent overflow (i pray to god) + int64_t seed = + ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + + ((uint64_t)seed * 11ULL)); - xt += ((((seed >> 16) & 0xf) / 15.0f) - 0.5f) * 0.5f; - yt += ((((seed >> 20) & 0xf) / 15.0f) - 1.0f) * 0.2f; - zt += ((((seed >> 24) & 0xf) / 15.0f) - 0.5f) * 0.5f; - } + xt += ((((seed >> 16) & 0xf) / 15.0f) - 0.5f) * 0.5f; + yt += ((((seed >> 20) & 0xf) / 15.0f) - 1.0f) * 0.2f; + zt += ((((seed >> 24) & 0xf) / 15.0f) - 0.5f) * 0.5f; + } - tesselateCrossTexture( tt, level->getData( x, y, z ), xt, yt, zt, 1 ); - return true; + tesselateCrossTexture(tt, level->getData(x, y, z), xt, yt, zt, 1); + return true; } -bool TileRenderer::tesselateStemInWorld( Tile* _tt, int x, int y, int z ) -{ - StemTile* tt = ( StemTile* )_tt; - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateStemInWorld(Tile* _tt, int x, int y, int z) { + StemTile* tt = (StemTile*)_tt; + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30.0f + g * 59.0f + b * 11.0f ) / 100.0f; - float cg = ( r * 30.0f + g * 70.0f ) / ( 100.0f ); - float cb = ( r * 30.0f + b * 70.0f ) / ( 100.0f ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30.0f + g * 59.0f + b * 11.0f) / 100.0f; + float cg = (r * 30.0f + g * 70.0f) / (100.0f); + float cb = (r * 30.0f + b * 70.0f) / (100.0f); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - tt->updateShape( level, x, y, z ); - int dir = tt->getConnectDir( level, x, y, z ); - if ( dir < 0 ) - { - tesselateStemTexture( tt, level->getData( x, y, z ), tileShapeY1, x, y - 1 / 16.0f, z ); - } - else - { - tesselateStemTexture( tt, level->getData( x, y, z ), 0.5f, x, y - 1 / 16.0f, z ); - tesselateStemDirTexture( tt, level->getData( x, y, z ), dir, tileShapeY1, x, y - 1 / 16.0f, z ); - } - return true; + tt->updateShape(level, x, y, z); + int dir = tt->getConnectDir(level, x, y, z); + if (dir < 0) { + tesselateStemTexture(tt, level->getData(x, y, z), tileShapeY1, x, + y - 1 / 16.0f, z); + } else { + tesselateStemTexture(tt, level->getData(x, y, z), 0.5f, x, + y - 1 / 16.0f, z); + tesselateStemDirTexture(tt, level->getData(x, y, z), dir, tileShapeY1, + x, y - 1 / 16.0f, z); + } + return true; } -bool TileRenderer::tesselateRowInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateRowInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } - tesselateRowTexture( tt, level->getData( x, y, z ), x, y - 1.0f / 16.0f, z ); - return true; + tesselateRowTexture(tt, level->getData(x, y, z), x, y - 1.0f / 16.0f, z); + return true; } -void TileRenderer::tesselateTorch( Tile* tt, float x, float y, float z, float xxa, float zza, int data ) -{ - Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, Facing::DOWN, data); +void TileRenderer::tesselateTorch(Tile* tt, float x, float y, float z, + float xxa, float zza, int data) { + Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, Facing::DOWN, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float ut0 = tex->getU(7, true); - float vt0 = tex->getV(6, true); - float ut1 = tex->getU(9, true); - float vt1 = tex->getV(8, true); + float ut0 = tex->getU(7, true); + float vt0 = tex->getV(6, true); + float ut1 = tex->getU(9, true); + float vt1 = tex->getV(8, true); - float ub0 = tex->getU(7, true); - float vb0 = tex->getV(13, true); - float ub1 = tex->getU(9, true); - float vb1 = tex->getV(15, true); + float ub0 = tex->getU(7, true); + float vb0 = tex->getV(13, true); + float ub1 = tex->getU(9, true); + float vb1 = tex->getV(15, true); - x += 0.5f; - z += 0.5f; + x += 0.5f; + z += 0.5f; - float x0 = x - 0.5f; - float x1 = x + 0.5f; - float z0 = z - 0.5f; - float z1 = z + 0.5f; - float r = 1 / 16.0f; + float x0 = x - 0.5f; + float x1 = x + 0.5f; + float z0 = z - 0.5f; + float z1 = z + 0.5f; + float r = 1 / 16.0f; - float h = 10.0f / 16.0f; - t->vertexUV( ( float )( x + xxa * ( 1 - h ) - r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) - r ), ut0, vt0 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) - r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) + r ), ut0, vt1 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) + r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) + r ), ut1, vt1 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) + r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) - r ), ut1, vt0 ); + float h = 10.0f / 16.0f; + t->vertexUV((float)(x + xxa * (1 - h) - r), (float)(y + h), + (float)(z + zza * (1 - h) - r), ut0, vt0); + t->vertexUV((float)(x + xxa * (1 - h) - r), (float)(y + h), + (float)(z + zza * (1 - h) + r), ut0, vt1); + t->vertexUV((float)(x + xxa * (1 - h) + r), (float)(y + h), + (float)(z + zza * (1 - h) + r), ut1, vt1); + t->vertexUV((float)(x + xxa * (1 - h) + r), (float)(y + h), + (float)(z + zza * (1 - h) - r), ut1, vt0); - t->vertexUV( (float)(x + r + xxa), (float) y, (float)(z - r + zza), ub1, vb0); - t->vertexUV( (float)(x + r + xxa), (float) y, (float)(z + r + zza), ub1, vb1); - t->vertexUV( (float)(x - r + xxa), (float) y, (float)(z + r + zza), ub0, vb1); - t->vertexUV( (float)(x - r + xxa), (float) y, (float)(z - r + zza), ub0, vb0); + t->vertexUV((float)(x + r + xxa), (float)y, (float)(z - r + zza), ub1, vb0); + t->vertexUV((float)(x + r + xxa), (float)y, (float)(z + r + zza), ub1, vb1); + t->vertexUV((float)(x - r + xxa), (float)y, (float)(z + r + zza), ub0, vb1); + t->vertexUV((float)(x - r + xxa), (float)y, (float)(z - r + zza), ub0, vb0); - t->vertexUV( ( float )( x - r ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x - r + xxa ), ( float )( y + 0 ), ( float )( z0 + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x - r + xxa ), ( float )( y + 0 ), ( float )( z1 + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x - r ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x - r), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x - r + xxa), (float)(y + 0), (float)(z0 + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x - r + xxa), (float)(y + 0), (float)(z1 + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x - r), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + xxa + r ), ( float )( y + 0 ), ( float )( z1 + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + xxa + r ), ( float )( y + 0 ), ( float )( z0 + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + r), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + xxa + r), (float)(y + 0), (float)(z1 + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + xxa + r), (float)(y + 0), (float)(z0 + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z + r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 + xxa ), ( float )( y + 0 ), ( float )( z + r + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 + xxa ), ( float )( y + 0 ), ( float )( z + r + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z + r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z + r), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0 + xxa), (float)(y + 0), (float)(z + r + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x1 + xxa), (float)(y + 0), (float)(z + r + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z + r), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 + xxa ), ( float )( y + 0 ), ( float )( z - r + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 + xxa ), ( float )( y + 0 ), ( float )( z - r + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z - r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z - r), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1 + xxa), (float)(y + 0), (float)(z - r + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x0 + xxa), (float)(y + 0), (float)(z - r + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z - r), (float)(u1), + (float)(v0)); } -void TileRenderer::tesselateCrossTexture( Tile* tt, int data, float x, float y, float z, float scale ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateCrossTexture(Tile* tt, int data, float x, float y, + float z, float scale) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0, data); + Icon* tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float width = 0.45 * scale; - float x0 = x + 0.5 - width; - float x1 = x + 0.5 + width; - float z0 = z + 0.5 - width; - float z1 = z + 0.5 + width; + float width = 0.45 * scale; + float x0 = x + 0.5 - width; + float x1 = x + 0.5 + width; + float z0 = z + 0.5 - width; + float z1 = z + 0.5 + width; - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z1), (float)(u1), + (float)(v0)); } -void TileRenderer::tesselateStemTexture( Tile* tt, int data, float h, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateStemTexture(Tile* tt, int data, float h, float x, + float y, float z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0, data); + Icon* tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV(h * SharedConstants::WORLD_RESOLUTION, true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV(h * SharedConstants::WORLD_RESOLUTION, true); - float x0 = x + 0.5f - 0.45f; - float x1 = x + 0.5f + 0.45f; - float z0 = z + 0.5f - 0.45f; - float z1 = z + 0.5f + 0.45f; + float x0 = x + 0.5f - 0.45f; + float x1 = x + 0.5f + 0.45f; + float z0 = z + 0.5f - 0.45f; + float z1 = z + 0.5f + 0.45f; - t->vertexUV( x0, y + h, z0, u0, v0 ); - t->vertexUV( x0, y + 0, z0, u0, v1 ); - t->vertexUV( x1, y + 0, z1, u1, v1 ); - t->vertexUV( x1, y + h, z1, u1, v0 ); + t->vertexUV(x0, y + h, z0, u0, v0); + t->vertexUV(x0, y + 0, z0, u0, v1); + t->vertexUV(x1, y + 0, z1, u1, v1); + t->vertexUV(x1, y + h, z1, u1, v0); - t->vertexUV( x1, y + h, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v1 ); - t->vertexUV( x0, y + 0, z0, u1, v1 ); - t->vertexUV( x0, y + h, z0, u1, v0 ); + t->vertexUV(x1, y + h, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v1); + t->vertexUV(x0, y + 0, z0, u1, v1); + t->vertexUV(x0, y + h, z0, u1, v0); - t->vertexUV( x0, y + h, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v1 ); - t->vertexUV( x1, y + 0, z0, u1, v1 ); - t->vertexUV( x1, y + h, z0, u1, v0 ); + t->vertexUV(x0, y + h, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v1); + t->vertexUV(x1, y + 0, z0, u1, v1); + t->vertexUV(x1, y + h, z0, u1, v0); - t->vertexUV( x1, y + h, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v1 ); - t->vertexUV( x0, y + 0, z1, u1, v1 ); - t->vertexUV( x0, y + h, z1, u1, v0 ); + t->vertexUV(x1, y + h, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v1); + t->vertexUV(x0, y + 0, z1, u1, v1); + t->vertexUV(x0, y + h, z1, u1, v0); } -bool TileRenderer::tesselateLilypadInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateLilypadInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, Facing::UP); + Icon* tex = getTexture(tt, Facing::UP); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; float h = 0.25f / 16.0f; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); // 4jcraft add a bunch of casts to prevent overflow (i pray to god) - int64_t seed = ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + ((uint64_t)seed * 11ULL)); - int dir = (int) ((seed >> 16) & 0x3); - - + int64_t seed = + ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + + ((uint64_t)seed * 11ULL)); + int dir = (int)((seed >> 16) & 0x3); t->tex2(getLightColor(tt, level, x, y, z)); @@ -3848,2128 +3817,2111 @@ bool TileRenderer::tesselateLilypadInWorld(Tile *tt, int x, int y, int z) t->vertexUV(xx + c + s, y + h, zz - c + s, u1, v0); t->vertexUV(xx + c - s, y + h, zz + c + s, u0, v0); - return true; } -void TileRenderer::tesselateStemDirTexture( StemTile* tt, int data, int dir, float h, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateStemDirTexture(StemTile* tt, int data, int dir, + float h, float x, float y, float z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = tt->getAngledTexture(); + Icon* tex = tt->getAngledTexture(); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float x0 = x + 0.5f - 0.5f; - float x1 = x + 0.5f + 0.5f; - float z0 = z + 0.5f - 0.5f; - float z1 = z + 0.5f + 0.5f; + float x0 = x + 0.5f - 0.5f; + float x1 = x + 0.5f + 0.5f; + float z0 = z + 0.5f - 0.5f; + float z1 = z + 0.5f + 0.5f; - float xm = x + 0.5f; - float zm = z + 0.5f; + float xm = x + 0.5f; + float zm = z + 0.5f; - if ( ( dir + 1 ) / 2 % 2 == 1 ) - { - float tmp = u1; - u1 = u0; - u0 = tmp; - } + if ((dir + 1) / 2 % 2 == 1) { + float tmp = u1; + u1 = u0; + u0 = tmp; + } - if ( dir < 2 ) - { - t->vertexUV( x0, y + h, zm, u0, v0 ); - t->vertexUV( x0, y + 0, zm, u0, v1 ); - t->vertexUV( x1, y + 0, zm, u1, v1 ); - t->vertexUV( x1, y + h, zm, u1, v0 ); + if (dir < 2) { + t->vertexUV(x0, y + h, zm, u0, v0); + t->vertexUV(x0, y + 0, zm, u0, v1); + t->vertexUV(x1, y + 0, zm, u1, v1); + t->vertexUV(x1, y + h, zm, u1, v0); - t->vertexUV( x1, y + h, zm, u1, v0 ); - t->vertexUV( x1, y + 0, zm, u1, v1 ); - t->vertexUV( x0, y + 0, zm, u0, v1 ); - t->vertexUV( x0, y + h, zm, u0, v0 ); - } - else - { - t->vertexUV( xm, y + h, z1, u0, v0 ); - t->vertexUV( xm, y + 0, z1, u0, v1 ); - t->vertexUV( xm, y + 0, z0, u1, v1 ); - t->vertexUV( xm, y + h, z0, u1, v0 ); + t->vertexUV(x1, y + h, zm, u1, v0); + t->vertexUV(x1, y + 0, zm, u1, v1); + t->vertexUV(x0, y + 0, zm, u0, v1); + t->vertexUV(x0, y + h, zm, u0, v0); + } else { + t->vertexUV(xm, y + h, z1, u0, v0); + t->vertexUV(xm, y + 0, z1, u0, v1); + t->vertexUV(xm, y + 0, z0, u1, v1); + t->vertexUV(xm, y + h, z0, u1, v0); - t->vertexUV( xm, y + h, z0, u1, v0 ); - t->vertexUV( xm, y + 0, z0, u1, v1 ); - t->vertexUV( xm, y + 0, z1, u0, v1 ); - t->vertexUV( xm, y + h, z1, u0, v0 ); - } + t->vertexUV(xm, y + h, z0, u1, v0); + t->vertexUV(xm, y + 0, z0, u1, v1); + t->vertexUV(xm, y + 0, z1, u0, v1); + t->vertexUV(xm, y + h, z1, u0, v0); + } } +void TileRenderer::tesselateRowTexture(Tile* tt, int data, float x, float y, + float z) { + Tesselator* t = Tesselator::getInstance(); -void TileRenderer::tesselateRowTexture( Tile* tt, int data, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, 0, data); - Icon *tex = getTexture(tt, 0, data); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float x0 = x + 0.5f - 0.25f; + float x1 = x + 0.5f + 0.25f; + float z0 = z + 0.5f - 0.5f; + float z1 = z + 0.5f + 0.5f; - float x0 = x + 0.5f - 0.25f; - float x1 = x + 0.5f + 0.25f; - float z0 = z + 0.5f - 0.5f; - float z1 = z + 0.5f + 0.5f; + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + x0 = x + 0.5f - 0.5f; + x1 = x + 0.5f + 0.5f; + z0 = z + 0.5f - 0.25f; + z1 = z + 0.5f + 0.25f; - x0 = x + 0.5f - 0.5f; - x1 = x + 0.5f + 0.5f; - z0 = z + 0.5f - 0.25f; - z1 = z + 0.5f + 0.25f; + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); } -bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) -{ - // 4J Java comment - // TODO: This all needs to change. Somehow. - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateWaterInWorld(Tile* tt, int x, int y, int z) { + // 4J Java comment + // TODO: This all needs to change. Somehow. + Tesselator* t = Tesselator::getInstance(); - int col = tt->getColor( level, x, y, z ); - float r = ( col >> 16 & 0xff ) / 255.0f; - float g = ( col >> 8 & 0xff ) / 255.0f; - float b = ( col & 0xff ) / 255.0f; - bool up = tt->shouldRenderFace( level, x, y + 1, z, 1 ); - bool down = tt->shouldRenderFace( level, x, y - 1, z, 0 ); - bool dirs[4]; - dirs[0] = tt->shouldRenderFace( level, x, y, z - 1, 2 ); - dirs[1] = tt->shouldRenderFace( level, x, y, z + 1, 3 ); - dirs[2] = tt->shouldRenderFace( level, x - 1, y, z, 4 ); - dirs[3] = tt->shouldRenderFace( level, x + 1, y, z, 5 ); + int col = tt->getColor(level, x, y, z); + float r = (col >> 16 & 0xff) / 255.0f; + float g = (col >> 8 & 0xff) / 255.0f; + float b = (col & 0xff) / 255.0f; + bool up = tt->shouldRenderFace(level, x, y + 1, z, 1); + bool down = tt->shouldRenderFace(level, x, y - 1, z, 0); + bool dirs[4]; + dirs[0] = tt->shouldRenderFace(level, x, y, z - 1, 2); + dirs[1] = tt->shouldRenderFace(level, x, y, z + 1, 3); + dirs[2] = tt->shouldRenderFace(level, x - 1, y, z, 4); + dirs[3] = tt->shouldRenderFace(level, x + 1, y, z, 5); - if ( !up && !down && !dirs[0] && !dirs[1] && !dirs[2] && !dirs[3] ) return false; + if (!up && !down && !dirs[0] && !dirs[1] && !dirs[2] && !dirs[3]) + return false; - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - double yo0 = 0; - double yo1 = 1; + double yo0 = 0; + double yo1 = 1; - Material* m = tt->material; - int data = level->getData( x, y, z ); + Material* m = tt->material; + int data = level->getData(x, y, z); - float h0 = getWaterHeight( x, y, z, m ); - float h1 = getWaterHeight( x, y, z + 1, m ); - float h2 = getWaterHeight( x + 1, y, z + 1, m ); - float h3 = getWaterHeight( x + 1, y, z, m ); + float h0 = getWaterHeight(x, y, z, m); + float h1 = getWaterHeight(x, y, z + 1, m); + float h2 = getWaterHeight(x + 1, y, z + 1, m); + float h3 = getWaterHeight(x + 1, y, z, m); float offs = 0.001f; - // 4J - added. Farm tiles often found beside water, but they consider themselves non-solid as they only extend up to 15.0f / 16.0f. - // If the max height of this water is below that level, don't bother rendering sides bordering onto farmland. - float maxh = h0; - if ( h1 > maxh ) maxh = h1; - if ( h2 > maxh ) maxh = h2; - if ( h3 > maxh ) maxh = h3; - if ( maxh <= ( 15.0f / 16.0f ) ) - { - if ( level->getTile( x, y, z - 1 ) == Tile::farmland_Id ) - { - dirs[0] = false; - } - if ( level->getTile( x, y, z + 1 ) == Tile::farmland_Id ) - { - dirs[1] = false; - } - if ( level->getTile( x - 1, y, z ) == Tile::farmland_Id ) - { - dirs[2] = false; - } - if ( level->getTile( x + 1, y, z ) == Tile::farmland_Id ) - { - dirs[3] = false; - } - } + // 4J - added. Farm tiles often found beside water, but they consider + // themselves non-solid as they only extend up to 15.0f / 16.0f. If the max + // height of this water is below that level, don't bother rendering sides + // bordering onto farmland. + float maxh = h0; + if (h1 > maxh) maxh = h1; + if (h2 > maxh) maxh = h2; + if (h3 > maxh) maxh = h3; + if (maxh <= (15.0f / 16.0f)) { + if (level->getTile(x, y, z - 1) == Tile::farmland_Id) { + dirs[0] = false; + } + if (level->getTile(x, y, z + 1) == Tile::farmland_Id) { + dirs[1] = false; + } + if (level->getTile(x - 1, y, z) == Tile::farmland_Id) { + dirs[2] = false; + } + if (level->getTile(x + 1, y, z) == Tile::farmland_Id) { + dirs[3] = false; + } + } - if ( noCulling || up ) - { - changed = true; - Icon *tex = getTexture( tt, 1, data ); - float angle = ( float )LiquidTile::getSlopeAngle( level, x, y, z, m ); - if ( angle > -999 ) - { - tex = getTexture( tt, 2, data ); - } + if (noCulling || up) { + changed = true; + Icon* tex = getTexture(tt, 1, data); + float angle = (float)LiquidTile::getSlopeAngle(level, x, y, z, m); + if (angle > -999) { + tex = getTexture(tt, 2, data); + } h0 -= offs; h1 -= offs; h2 -= offs; h3 -= offs; - float u00, u01, u10, u11; - float v00, v01, v10, v11; - if ( angle < -999 ) - { - u00 = tex->getU(0, true); - v00 = tex->getV(0, true); - u01 = u00; - v01 = tex->getV(SharedConstants::WORLD_RESOLUTION, true); - u10 = tex->getU(SharedConstants::WORLD_RESOLUTION, true); - v10 = v01; - u11 = u10; - v11 = v00; - } - else - { - float s = Mth::sin(angle) * .25f; - float c = Mth::cos(angle) * .25f; - float cc = SharedConstants::WORLD_RESOLUTION * .5f; - u00 = tex->getU(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); - v00 = tex->getV(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); - u01 = tex->getU(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); - v01 = tex->getV(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); - u10 = tex->getU(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); - v10 = tex->getV(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); - u11 = tex->getU(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); - v11 = tex->getV(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); - } + float u00, u01, u10, u11; + float v00, v01, v10, v11; + if (angle < -999) { + u00 = tex->getU(0, true); + v00 = tex->getV(0, true); + u01 = u00; + v01 = tex->getV(SharedConstants::WORLD_RESOLUTION, true); + u10 = tex->getU(SharedConstants::WORLD_RESOLUTION, true); + v10 = v01; + u11 = u10; + v11 = v00; + } else { + float s = Mth::sin(angle) * .25f; + float c = Mth::cos(angle) * .25f; + float cc = SharedConstants::WORLD_RESOLUTION * .5f; + u00 = tex->getU(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); + v00 = tex->getV(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); + u01 = tex->getU(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); + v01 = tex->getV(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); + u10 = tex->getU(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); + v10 = tex->getV(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); + u11 = tex->getU(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); + v11 = tex->getV(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); + } - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - t->color( c11 * br * r, c11 * br * g, c11 * br * b ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h0 ), ( float )( z + 0.0f ), u00, v00 ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h1 ), ( float )( z + 1.0f ), u01, v01 ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h2 ), ( float )( z + 1.0f ), u10, v10 ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h3 ), ( float )( z + 0.0f ), u11, v11 ); - } + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + t->color(c11 * br * r, c11 * br * g, c11 * br * b); + t->vertexUV((float)(x + 0.0f), (float)(y + h0), (float)(z + 0.0f), u00, + v00); + t->vertexUV((float)(x + 0.0f), (float)(y + h1), (float)(z + 1.0f), u01, + v01); + t->vertexUV((float)(x + 1.0f), (float)(y + h2), (float)(z + 1.0f), u10, + v10); + t->vertexUV((float)(x + 1.0f), (float)(y + h3), (float)(z + 0.0f), u11, + v11); + } - if ( noCulling || down ) - { - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y - 1, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y - 1, z ); - } - t->color( c10 * br, c10 * br, c10 * br ); - renderFaceDown( tt, x, y + offs, z, getTexture( tt, 0 ) ); - changed = true; - } + if (noCulling || down) { + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y - 1, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y - 1, z); + } + t->color(c10 * br, c10 * br, c10 * br); + renderFaceDown(tt, x, y + offs, z, getTexture(tt, 0)); + changed = true; + } - for ( int face = 0; face < 4; face++ ) - { - int xt = x; - int yt = y; - int zt = z; + for (int face = 0; face < 4; face++) { + int xt = x; + int yt = y; + int zt = z; - if ( face == 0 ) zt--; - if ( face == 1 ) zt++; - if ( face == 2 ) xt--; - if ( face == 3 ) xt++; + if (face == 0) zt--; + if (face == 1) zt++; + if (face == 2) xt--; + if (face == 3) xt++; - Icon *tex = getTexture(tt, face + 2, data); + Icon* tex = getTexture(tt, face + 2, data); - if ( noCulling || dirs[face] ) - { - float hh0; - float hh1; - float x0, z0, x1, z1; - if ( face == 0 ) - { - hh0 = ( float )( h0 ); - hh1 = ( float )( h3 ); - x0 = ( float )( x ); - x1 = ( float )( x + 1 ); - z0 = ( float )( z + offs); - z1 = ( float )( z + offs); - } - else if ( face == 1 ) - { - hh0 = ( float )( h2 ); - hh1 = ( float )( h1 ); - x0 = ( float )( x + 1 ); - x1 = ( float )( x ); - z0 = ( float )( z + 1 - offs); - z1 = ( float )( z + 1 - offs); - } - else if ( face == 2 ) - { - hh0 = ( float )( h1 ); - hh1 = ( float )( h0 ); - x0 = ( float )( x + offs); - x1 = ( float )( x + offs); - z0 = ( float )( z + 1 ); - z1 = ( float )( z ); - } - else - { - hh0 = ( float )( h3 ); - hh1 = ( float )( h2 ); - x0 = ( float )( x + 1 - offs); - x1 = ( float )( x + 1 - offs); - z0 = ( float )( z ); - z1 = ( float )( z + 1 ); - } + if (noCulling || dirs[face]) { + float hh0; + float hh1; + float x0, z0, x1, z1; + if (face == 0) { + hh0 = (float)(h0); + hh1 = (float)(h3); + x0 = (float)(x); + x1 = (float)(x + 1); + z0 = (float)(z + offs); + z1 = (float)(z + offs); + } else if (face == 1) { + hh0 = (float)(h2); + hh1 = (float)(h1); + x0 = (float)(x + 1); + x1 = (float)(x); + z0 = (float)(z + 1 - offs); + z1 = (float)(z + 1 - offs); + } else if (face == 2) { + hh0 = (float)(h1); + hh1 = (float)(h0); + x0 = (float)(x + offs); + x1 = (float)(x + offs); + z0 = (float)(z + 1); + z1 = (float)(z); + } else { + hh0 = (float)(h3); + hh1 = (float)(h2); + x0 = (float)(x + 1 - offs); + x1 = (float)(x + 1 - offs); + z0 = (float)(z); + z1 = (float)(z + 1); + } + changed = true; + float u0 = tex->getU(0, true); + float u1 = tex->getU(SharedConstants::WORLD_RESOLUTION * .5f, true); - changed = true; - float u0 = tex->getU(0, true); - float u1 = tex->getU(SharedConstants::WORLD_RESOLUTION * .5f, true); + int yTex = tex->getY(); + float v01 = + tex->getV((1 - hh0) * SharedConstants::WORLD_RESOLUTION * .5f); + float v02 = + tex->getV((1 - hh1) * SharedConstants::WORLD_RESOLUTION * .5f); + float v1 = tex->getV(SharedConstants::WORLD_RESOLUTION * .5f, true); - int yTex = tex->getY(); - float v01 = tex->getV((1 - hh0) * SharedConstants::WORLD_RESOLUTION * .5f); - float v02 = tex->getV((1 - hh1) * SharedConstants::WORLD_RESOLUTION * .5f); - float v1 = tex->getV(SharedConstants::WORLD_RESOLUTION * .5f, true); + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, xt, yt, zt)); + br = 1; + } else { + br = tt->getBrightness(level, xt, yt, zt); + } + if (face < 2) + br *= c2; + else + br *= c3; - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, xt, yt, zt ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, xt, yt, zt ); - } - if ( face < 2 ) br *= c2; - else - br *= c3; + t->color(c11 * br * r, c11 * br * g, c11 * br * b); + t->vertexUV((float)(x0), (float)(y + hh0), (float)(z0), (float)(u0), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y + hh1), (float)(z1), (float)(u1), + (float)(v02)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + } + } - t->color( c11 * br * r, c11 * br * g, c11 * br * b ); - t->vertexUV( ( float )( x0 ), ( float )( y + hh0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + hh1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v02 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - - } - - } - - tileShapeY0 = yo0; - tileShapeY1 = yo1; - - return changed; + tileShapeY0 = yo0; + tileShapeY1 = yo1; + return changed; } -float TileRenderer::getWaterHeight( int x, int y, int z, Material* m ) -{ - int count = 0; - float h = 0; - for ( int i = 0; i < 4; i++ ) - { - int xx = x - ( i & 1 ); - int yy = y; - int zz = z - ( ( i >> 1 ) & 1 ); - if ( level->getMaterial( xx, yy + 1, zz ) == m ) - { - return 1; - } - Material* tm = level->getMaterial( xx, yy, zz ); - if ( tm == m ) - { - int d = level->getData( xx, yy, zz ); - if ( d >= 8 || d == 0 ) - { - h += ( LiquidTile::getHeight( d ) )* 10; - count += 10; - } - h += LiquidTile::getHeight( d ); - count++; - } - else if ( !tm->isSolid() ) - { - h += 1; - count++; - } - } - return 1 - h / count; +float TileRenderer::getWaterHeight(int x, int y, int z, Material* m) { + int count = 0; + float h = 0; + for (int i = 0; i < 4; i++) { + int xx = x - (i & 1); + int yy = y; + int zz = z - ((i >> 1) & 1); + if (level->getMaterial(xx, yy + 1, zz) == m) { + return 1; + } + Material* tm = level->getMaterial(xx, yy, zz); + if (tm == m) { + int d = level->getData(xx, yy, zz); + if (d >= 8 || d == 0) { + h += (LiquidTile::getHeight(d)) * 10; + count += 10; + } + h += LiquidTile::getHeight(d); + count++; + } else if (!tm->isSolid()) { + h += 1; + count++; + } + } + return 1 - h / count; } -void TileRenderer::renderBlock( Tile* tt, Level* level, int x, int y, int z ) -{ - renderBlock(tt, level, x, y, z, 0); +void TileRenderer::renderBlock(Tile* tt, Level* level, int x, int y, int z) { + renderBlock(tt, level, x, y, z, 0); } -void TileRenderer::renderBlock(Tile *tt, Level *level, int x, int y, int z, int data) -{ - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; +void TileRenderer::renderBlock(Tile* tt, Level* level, int x, int y, int z, + int data) { + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - Tesselator* t = Tesselator::getInstance(); - t->begin(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - float center = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z ); - float br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y - 1, z ); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + } + float center = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z); + float br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y - 1, z); - if ( br < center ) br = center; - t->color( c10 * br, c10 * br, c10 * br ); - renderFaceDown( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 0, data ) ); + if (br < center) br = center; + t->color(c10 * br, c10 * br, c10 * br); + renderFaceDown(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 0, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y + 1, z ); - if ( br < center ) br = center; - t->color( c11 * br, c11 * br, c11 * br ); - renderFaceUp( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 1, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y + 1, z); + if (br < center) br = center; + t->color(c11 * br, c11 * br, c11 * br); + renderFaceUp(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 1, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z - 1 ); - if ( br < center ) br = center; - t->color( c2 * br, c2 * br, c2 * br ); - renderNorth( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 2, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z - 1); + if (br < center) br = center; + t->color(c2 * br, c2 * br, c2 * br); + renderNorth(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 2, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z + 1 ); - if ( br < center ) br = center; - t->color( c2 * br, c2 * br, c2 * br ); - renderSouth( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 3, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z + 1); + if (br < center) br = center; + t->color(c2 * br, c2 * br, c2 * br); + renderSouth(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 3, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x - 1, y, z ); - if ( br < center ) br = center; - t->color( c3 * br, c3 * br, c3 * br ); - renderWest( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 4, data ) ); - - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x + 1, y, z ); - if ( br < center ) br = center; - t->color( c3 * br, c3 * br, c3 * br ); - renderEast( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 5, data ) ); - t->end(); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x - 1, y, z); + if (br < center) br = center; + t->color(c3 * br, c3 * br, c3 * br); + renderWest(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 4, data)); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x + 1, y, z); + if (br < center) br = center; + t->color(c3 * br, c3 * br, c3 * br); + renderEast(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 5, data)); + t->end(); } -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - if ( Tile::lightEmission[tt->id] == 0 )//4J - TODO/remove (Minecraft::useAmbientOcclusion()) - { - return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( tt, x, y, z, r, g, b, 0 ); - } - else - { - return tesselateBlockInWorld( tt, x, y, z, r, g, b ); - } + if (Tile::lightEmission[tt->id] == + 0) // 4J - TODO/remove (Minecraft::useAmbientOcclusion()) + { + return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + tt, x, y, z, r, g, b, 0); + } else { + return tesselateBlockInWorld(tt, x, y, z, r, g, b); + } } // AP - added this version to be able to pass the face flags down -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z, int faceFlags ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z, + int faceFlags) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - if ( Tile::lightEmission[tt->id] == 0 )//4J - TODO/remove (Minecraft::useAmbientOcclusion()) - { - return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( tt, x, y, z, r, g, b, faceFlags ); - } - else - { - return tesselateBlockInWorld( tt, x, y, z, r, g, b ); - } + if (Tile::lightEmission[tt->id] == + 0) // 4J - TODO/remove (Minecraft::useAmbientOcclusion()) + { + return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + tt, x, y, z, r, g, b, faceFlags); + } else { + return tesselateBlockInWorld(tt, x, y, z, r, g, b); + } } -bool TileRenderer::tesselateTreeInWorld(Tile *tt, int x, int y, int z) -{ - int data = level->getData(x, y, z); - int facing = data & TreeTile::MASK_FACING; +bool TileRenderer::tesselateTreeInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); + int facing = data & TreeTile::MASK_FACING; - if (facing == TreeTile::FACING_X) - { - northFlip = FLIP_CW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CW; - } - else if (facing == TreeTile::FACING_Z) - { - eastFlip = FLIP_CW; - westFlip = FLIP_CW; - } + if (facing == TreeTile::FACING_X) { + northFlip = FLIP_CW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CW; + } else if (facing == TreeTile::FACING_Z) { + eastFlip = FLIP_CW; + westFlip = FLIP_CW; + } - bool result = tesselateBlockInWorld(tt, x, y, z); + bool result = tesselateBlockInWorld(tt, x, y, z); - eastFlip = 0; - northFlip = 0; - southFlip = 0; - westFlip = 0; - upFlip = 0; - downFlip = 0; + eastFlip = 0; + northFlip = 0; + southFlip = 0; + westFlip = 0; + upFlip = 0; + downFlip = 0; - return result; + return result; } -bool TileRenderer::tesselateQuartzInWorld(Tile *tt, int x, int y, int z) -{ - int data = level->getData(x, y, z); +bool TileRenderer::tesselateQuartzInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); - if (data == QuartzBlockTile::TYPE_LINES_X) - { - northFlip = FLIP_CW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CW; - } - else if (data == QuartzBlockTile::TYPE_LINES_Z) - { - eastFlip = FLIP_CW; - westFlip = FLIP_CW; - } + if (data == QuartzBlockTile::TYPE_LINES_X) { + northFlip = FLIP_CW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CW; + } else if (data == QuartzBlockTile::TYPE_LINES_Z) { + eastFlip = FLIP_CW; + westFlip = FLIP_CW; + } - bool result = tesselateBlockInWorld(tt, x, y, z); + bool result = tesselateBlockInWorld(tt, x, y, z); - eastFlip = 0; - northFlip = 0; - southFlip = 0; - westFlip = 0; - upFlip = 0; - downFlip = 0; + eastFlip = 0; + northFlip = 0; + southFlip = 0; + westFlip = 0; + upFlip = 0; + downFlip = 0; - return result; + return result; } -bool TileRenderer::tesselateCocoaInWorld(CocoaTile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateCocoaInWorld(CocoaTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(getLightColor(tt, level, x, y, z)); - t->color(1.0f, 1.0f, 1.0f); - } - else - { - float br = tt->getBrightness(level, x, y, z); - if (Tile::lightEmission[tt->id] > 0) br = 1.0f; - t->color(br, br, br); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } - int data = level->getData(x, y, z); - int dir = DirectionalTile::getDirection(data); - int age = CocoaTile::getAge(data); - Icon *tex = tt->getTextureForAge(age); + int data = level->getData(x, y, z); + int dir = DirectionalTile::getDirection(data); + int age = CocoaTile::getAge(data); + Icon* tex = tt->getTextureForAge(age); - int cocoaWidth = 4 + age * 2; - int cocoaHeight = 5 + age * 2; + int cocoaWidth = 4 + age * 2; + int cocoaHeight = 5 + age * 2; - double us = 15.0 - cocoaWidth; - double ue = 15.0; - double vs = 4.0; - double ve = 4.0 + cocoaHeight; - double u0 = tex->getU(us, true); - double u1 = tex->getU(ue, true); - double v0 = tex->getV(vs, true); - double v1 = tex->getV(ve, true); + double us = 15.0 - cocoaWidth; + double ue = 15.0; + double vs = 4.0; + double ve = 4.0 + cocoaHeight; + double u0 = tex->getU(us, true); + double u1 = tex->getU(ue, true); + double v0 = tex->getV(vs, true); + double v1 = tex->getV(ve, true); + double offX = 0; + double offZ = 0; - double offX = 0; - double offZ = 0; + switch (dir) { + case Direction::NORTH: + offX = 8.0 - cocoaWidth / 2; + offZ = 1.0; + break; + case Direction::SOUTH: + offX = 8.0 - cocoaWidth / 2; + offZ = 15.0 - cocoaWidth; + break; + case Direction::EAST: + offX = 15.0 - cocoaWidth; + offZ = 8.0 - cocoaWidth / 2; + break; + case Direction::WEST: + offX = 1.0; + offZ = 8.0 - cocoaWidth / 2; + break; + } - switch (dir) - { - case Direction::NORTH: - offX = 8.0 - cocoaWidth / 2; - offZ = 1.0; - break; - case Direction::SOUTH: - offX = 8.0 - cocoaWidth / 2; - offZ = 15.0 - cocoaWidth; - break; - case Direction::EAST: - offX = 15.0 - cocoaWidth; - offZ = 8.0 - cocoaWidth / 2; - break; - case Direction::WEST: - offX = 1.0; - offZ = 8.0 - cocoaWidth / 2; - break; - } + double x0 = x + offX / 16.0; + double x1 = x + (offX + cocoaWidth) / 16.0; + double y0 = y + (12.0 - cocoaHeight) / 16.0; + double y1 = y + 12.0 / 16.0; + double z0 = z + offZ / 16.0; + double z1 = z + (offZ + cocoaWidth) / 16.0; - double x0 = x + offX / 16.0; - double x1 = x + (offX + cocoaWidth) / 16.0; - double y0 = y + (12.0 - cocoaHeight) / 16.0; - double y1 = y + 12.0 / 16.0; - double z0 = z + offZ / 16.0; - double z1 = z + (offZ + cocoaWidth) / 16.0; + // west + { + t->vertexUV(x0, y0, z0, u0, v1); + t->vertexUV(x0, y0, z1, u1, v1); + t->vertexUV(x0, y1, z1, u1, v0); + t->vertexUV(x0, y1, z0, u0, v0); + } + // east + { + t->vertexUV(x1, y0, z1, u0, v1); + t->vertexUV(x1, y0, z0, u1, v1); + t->vertexUV(x1, y1, z0, u1, v0); + t->vertexUV(x1, y1, z1, u0, v0); + } + // north + { + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x1, y1, z0, u0, v0); + } + // south + { + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x1, y1, z1, u1, v0); + t->vertexUV(x0, y1, z1, u0, v0); + } - // west - { - t->vertexUV(x0, y0, z0, u0, v1); - t->vertexUV(x0, y0, z1, u1, v1); - t->vertexUV(x0, y1, z1, u1, v0); - t->vertexUV(x0, y1, z0, u0, v0); - } - // east - { - t->vertexUV(x1, y0, z1, u0, v1); - t->vertexUV(x1, y0, z0, u1, v1); - t->vertexUV(x1, y1, z0, u1, v0); - t->vertexUV(x1, y1, z1, u0, v0); - } - // north - { - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x1, y1, z0, u0, v0); - } - // south - { - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x1, y0, z1, u1, v1); - t->vertexUV(x1, y1, z1, u1, v0); - t->vertexUV(x0, y1, z1, u0, v0); - } + int topWidth = cocoaWidth; + if (age >= 2) { + // special case because the top piece didn't fit + topWidth--; + } - int topWidth = cocoaWidth; - if (age >= 2) - { - // special case because the top piece didn't fit - topWidth--; - } + u0 = tex->getU0(true); + u1 = tex->getU(topWidth, true); + v0 = tex->getV0(true); + v1 = tex->getV(topWidth, true); - u0 = tex->getU0(true); - u1 = tex->getU(topWidth, true); - v0 = tex->getV0(true); - v1 = tex->getV(topWidth, true); + // top + { + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y1, z0, u1, v0); + t->vertexUV(x0, y1, z0, u0, v0); + } + // bottom + { + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x0, y0, z1, u0, v1); + } - // top - { - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y1, z0, u1, v0); - t->vertexUV(x0, y1, z0, u0, v0); - } - // bottom - { - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y0, z1, u1, v1); - t->vertexUV(x0, y0, z1, u0, v1); - } + // stalk + u0 = tex->getU(12, true); + u1 = tex->getU1(true); + v0 = tex->getV0(true); + v1 = tex->getV(4, true); - // stalk - u0 = tex->getU(12, true); - u1 = tex->getU1(true); - v0 = tex->getV0(true); - v1 = tex->getV(4, true); + offX = 8; + offZ = 0; - offX = 8; - offZ = 0; + switch (dir) { + case Direction::NORTH: + offX = 8.0; + offZ = 0.0; + break; + case Direction::SOUTH: + offX = 8; + offZ = 12; + { + double temp = u0; + u0 = u1; + u1 = temp; + } + break; + case Direction::EAST: + offX = 12.0; + offZ = 8.0; + { + double temp = u0; + u0 = u1; + u1 = temp; + } + break; + case Direction::WEST: + offX = 0.0; + offZ = 8.0; + break; + } - switch (dir) - { - case Direction::NORTH: - offX = 8.0; - offZ = 0.0; - break; - case Direction::SOUTH: - offX = 8; - offZ = 12; - { - double temp = u0; - u0 = u1; - u1 = temp; - } - break; - case Direction::EAST: - offX = 12.0; - offZ = 8.0; - { - double temp = u0; - u0 = u1; - u1 = temp; - } - break; - case Direction::WEST: - offX = 0.0; - offZ = 8.0; - break; - } + x0 = x + offX / 16.0; + x1 = x + (offX + 4.0) / 16.0; + y0 = y + 12.0 / 16.0; + y1 = y + 16.0 / 16.0; + z0 = z + offZ / 16.0; + z1 = z + (offZ + 4.0) / 16.0; + if (dir == Direction::NORTH || dir == Direction::SOUTH) { + // west + { + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y1, z1, u0, v0); + t->vertexUV(x0, y1, z0, u1, v0); + } + // east + { + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x0, y1, z1, u0, v0); + } + } else if (dir == Direction::WEST || dir == Direction::EAST) { + // north + { + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x1, y1, z0, u0, v0); + } + // south + { + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x1, y1, z0, u0, v0); + t->vertexUV(x0, y1, z0, u1, v0); + } + } - x0 = x + offX / 16.0; - x1 = x + (offX + 4.0) / 16.0; - y0 = y + 12.0 / 16.0; - y1 = y + 16.0 / 16.0; - z0 = z + offZ / 16.0; - z1 = z + (offZ + 4.0) / 16.0; - if (dir == Direction::NORTH || dir == Direction::SOUTH) - { - // west - { - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x0, y1, z1, u0, v0); - t->vertexUV(x0, y1, z0, u1, v0); - } - // east - { - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x0, y1, z1, u0, v0); - } - } - else if (dir == Direction::WEST || dir == Direction::EAST) - { - // north - { - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x1, y1, z0, u0, v0); - } - // south - { - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x1, y1, z0, u0, v0); - t->vertexUV(x0, y1, z0, u1, v0); - } - } - - - return true; + return true; } // 4J - brought changes forward from 1.8.2 -bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* tt, int pX, int pY, int pZ, - float pBaseRed, float pBaseGreen, - float pBaseBlue, int faceFlags ) -{ - // 4J - the texture is (originally) obtained for each face in the block, if those faces are visible. For a lot of blocks, - // the textures don't vary from face to face - this is particularly an issue for leaves as they not only don't vary between faces, - // but they also happen to draw a lot of faces, and the code for determining which texture to use is more complex than in most - // cases. Optimisation here then to store a uniform texture where appropriate (could be extended beyond leaves) that will stop - // any other faces being evaluated. - Icon *uniformTex = NULL; - int id = tt->id; - if( id == Tile::leaves_Id ) - { - uniformTex = getTexture(tt, level, pX, pY, pZ, 0); - } - // 4J - added these faceFlags so we can detect whether this block is going to have no visible faces and early out - // the original code checked noCulling and shouldRenderFace directly where faceFlags is used now - // AP - I moved a copy of these face checks to have an even earlier out - // check if the faceFlags have indeed been set - if( faceFlags == 0 ) - { - if ( noCulling ) - { - faceFlags = 0x3f; - } - else - { - faceFlags |= tt->shouldRenderFace( level, pX, pY - 1, pZ, 0 ) ? 0x01 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY + 1, pZ, 1 ) ? 0x02 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY, pZ - 1, 2 ) ? 0x04 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY, pZ + 1, 3 ) ? 0x08 : 0; - faceFlags |= tt->shouldRenderFace( level, pX - 1, pY, pZ, 4 ) ? 0x10 : 0; - faceFlags |= tt->shouldRenderFace( level, pX + 1, pY, pZ, 5 ) ? 0x20 : 0; - } - if ( faceFlags == 0 ) - { - return false; - } - } - // If we are only rendering the bottom face and we're at the bottom of the world, we shouldn't be able to see this - don't render anything - if( ( faceFlags == 1 ) && ( pY == 0 ) ) - { - return false; - } +bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, + float pBaseBlue, int faceFlags) { + // 4J - the texture is (originally) obtained for each face in the block, if + // those faces are visible. For a lot of blocks, the textures don't vary + // from face to face - this is particularly an issue for leaves as they not + // only don't vary between faces, but they also happen to draw a lot of + // faces, and the code for determining which texture to use is more complex + // than in most cases. Optimisation here then to store a uniform texture + // where appropriate (could be extended beyond leaves) that will stop any + // other faces being evaluated. + Icon* uniformTex = NULL; + int id = tt->id; + if (id == Tile::leaves_Id) { + uniformTex = getTexture(tt, level, pX, pY, pZ, 0); + } + // 4J - added these faceFlags so we can detect whether this block is going + // to have no visible faces and early out the original code checked + // noCulling and shouldRenderFace directly where faceFlags is used now AP - + // I moved a copy of these face checks to have an even earlier out check if + // the faceFlags have indeed been set + if (faceFlags == 0) { + if (noCulling) { + faceFlags = 0x3f; + } else { + faceFlags |= + tt->shouldRenderFace(level, pX, pY - 1, pZ, 0) ? 0x01 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY + 1, pZ, 1) ? 0x02 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY, pZ - 1, 2) ? 0x04 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY, pZ + 1, 3) ? 0x08 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX - 1, pY, pZ, 4) ? 0x10 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX + 1, pY, pZ, 5) ? 0x20 : 0; + } + if (faceFlags == 0) { + return false; + } + } + // If we are only rendering the bottom face and we're at the bottom of the + // world, we shouldn't be able to see this - don't render anything + if ((faceFlags == 1) && (pY == 0)) { + return false; + } - applyAmbienceOcclusion = true; - float ll1 = ll000; - float ll2 = ll000; - float ll3 = ll000; - float ll4 = ll000; - bool tint0 = true; - bool tint1 = true; - bool tint2 = true; - bool tint3 = true; - bool tint4 = true; - bool tint5 = true; + applyAmbienceOcclusion = true; + float ll1 = ll000; + float ll2 = ll000; + float ll3 = ll000; + float ll4 = ll000; + bool tint0 = true; + bool tint1 = true; + bool tint2 = true; + bool tint3 = true; + bool tint4 = true; + bool tint5 = true; + ll000 = getShadeBrightness(tt, level, pX, pY, pZ); + llx00 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0y0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll00z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llX00 = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0Y0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); + ll00Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); - ll000 = getShadeBrightness(tt, level, pX, pY, pZ ); - llx00 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0y0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll00z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llX00 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0Y0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); - ll00Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); + // 4J - these changes brought forward from 1.2.3 + int centerColor = getLightColor(tt, level, pX, pY, pZ); + int ccx00 = centerColor; + int cc0y0 = centerColor; + int cc00z = centerColor; + int ccX00 = centerColor; + int cc0Y0 = centerColor; + int cc00Z = centerColor; - // 4J - these changes brought forward from 1.2.3 - int centerColor = getLightColor(tt, level, pX, pY, pZ ); - int ccx00 = centerColor; - int cc0y0 = centerColor; - int cc00z = centerColor; - int ccX00 = centerColor; - int cc0Y0 = centerColor; - int cc00Z = centerColor; + if (tileShapeY0 <= 0 || !level->isSolidRenderTile(pX, pY - 1, pZ)) + cc0y0 = getLightColor(tt, level, pX, pY - 1, pZ); + if (tileShapeY1 >= 1 || !level->isSolidRenderTile(pX, pY + 1, pZ)) + cc0Y0 = getLightColor(tt, level, pX, pY + 1, pZ); + if (tileShapeX0 <= 0 || !level->isSolidRenderTile(pX - 1, pY, pZ)) + ccx00 = getLightColor(tt, level, pX - 1, pY, pZ); + if (tileShapeX1 >= 1 || !level->isSolidRenderTile(pX + 1, pY, pZ)) + ccX00 = getLightColor(tt, level, pX + 1, pY, pZ); + if (tileShapeZ0 <= 0 || !level->isSolidRenderTile(pX, pY, pZ - 1)) + cc00z = getLightColor(tt, level, pX, pY, pZ - 1); + if (tileShapeZ1 >= 1 || !level->isSolidRenderTile(pX, pY, pZ + 1)) + cc00Z = getLightColor(tt, level, pX, pY, pZ + 1); - if (tileShapeY0 <= 0 || !level->isSolidRenderTile(pX, pY - 1, pZ)) cc0y0 = getLightColor(tt, level, pX, pY - 1, pZ); - if (tileShapeY1 >= 1 || !level->isSolidRenderTile(pX, pY + 1, pZ)) cc0Y0 = getLightColor(tt, level, pX, pY + 1, pZ); - if (tileShapeX0 <= 0 || !level->isSolidRenderTile(pX - 1, pY, pZ)) ccx00 = getLightColor(tt, level, pX - 1, pY, pZ); - if (tileShapeX1 >= 1 || !level->isSolidRenderTile(pX + 1, pY, pZ)) ccX00 = getLightColor(tt, level, pX + 1, pY, pZ); - if (tileShapeZ0 <= 0 || !level->isSolidRenderTile(pX, pY, pZ - 1)) cc00z = getLightColor(tt, level, pX, pY, pZ - 1); - if (tileShapeZ1 >= 1 || !level->isSolidRenderTile(pX, pY, pZ + 1)) cc00Z = getLightColor(tt, level, pX, pY, pZ + 1); + Tesselator* t = Tesselator::getInstance(); + t->tex2(0xf000f); - Tesselator* t = Tesselator::getInstance(); - t->tex2( 0xf000f ); + llTransXY0 = isTranslucentAt(level, pX + 1, pY + 1, pZ); + llTransXy0 = isTranslucentAt(level, pX + 1, pY - 1, pZ); + llTransX0Z = isTranslucentAt(level, pX + 1, pY, pZ + 1); + llTransX0z = isTranslucentAt(level, pX + 1, pY, pZ - 1); + llTransxY0 = isTranslucentAt(level, pX - 1, pY + 1, pZ); + llTransxy0 = isTranslucentAt(level, pX - 1, pY - 1, pZ); + llTransx0z = isTranslucentAt(level, pX - 1, pY, pZ - 1); + llTransx0Z = isTranslucentAt(level, pX - 1, pY, pZ + 1); + llTrans0YZ = isTranslucentAt(level, pX, pY + 1, pZ + 1); + llTrans0Yz = isTranslucentAt(level, pX, pY + 1, pZ - 1); + llTrans0yZ = isTranslucentAt(level, pX, pY - 1, pZ + 1); + llTrans0yz = isTranslucentAt(level, pX, pY - 1, pZ - 1); - llTransXY0 = isTranslucentAt( level, pX + 1, pY + 1, pZ ); - llTransXy0 = isTranslucentAt( level, pX + 1, pY - 1, pZ ); - llTransX0Z = isTranslucentAt( level, pX + 1, pY, pZ + 1 ); - llTransX0z = isTranslucentAt( level, pX + 1, pY, pZ - 1 ); - llTransxY0 = isTranslucentAt( level, pX - 1, pY + 1, pZ ); - llTransxy0 = isTranslucentAt( level, pX - 1, pY - 1, pZ ); - llTransx0z = isTranslucentAt( level, pX - 1, pY, pZ - 1 ); - llTransx0Z = isTranslucentAt( level, pX - 1, pY, pZ + 1 ); - llTrans0YZ = isTranslucentAt( level, pX, pY + 1, pZ + 1 ); - llTrans0Yz = isTranslucentAt( level, pX, pY + 1, pZ - 1 ); - llTrans0yZ = isTranslucentAt( level, pX, pY - 1, pZ + 1 ); - llTrans0yz = isTranslucentAt( level, pX, pY - 1, pZ - 1 ); + if (uniformTex == NULL) { + if (getTexture(tt)->getFlags() == Icon::IS_GRASS_TOP) + tint0 = tint2 = tint3 = tint4 = tint5 = false; + } + if (hasFixedTexture()) tint0 = tint2 = tint3 = tint4 = tint5 = false; - if( uniformTex == NULL ) - { - if ( getTexture(tt)->getFlags() == Icon::IS_GRASS_TOP ) tint0 = tint2 = tint3 = tint4 = tint5 = false; - } - if ( hasFixedTexture() ) tint0 = tint2 = tint3 = tint4 = tint5 = false; + if (faceFlags & 0x01) { + if (blsmooth > 0) { + if (tileShapeY0 <= 0) + pY--; // 4J - condition brought forward from 1.2.3 - if ( faceFlags & 0x01 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeY0 <= 0 ) pY--; // 4J - condition brought forward from 1.2.3 + ccxy0 = getLightColor(tt, level, pX - 1, pY, pZ); + cc0yz = getLightColor(tt, level, pX, pY, pZ - 1); + cc0yZ = getLightColor(tt, level, pX, pY, pZ + 1); + ccXy0 = getLightColor(tt, level, pX + 1, pY, pZ); - ccxy0 = getLightColor(tt, level, pX - 1, pY, pZ ); - cc0yz = getLightColor(tt, level, pX, pY, pZ - 1 ); - cc0yZ = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccXy0 = getLightColor(tt, level, pX + 1, pY, pZ ); + llxy0 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0yz = getShadeBrightness(tt, level, pX, pY, pZ - 1); + ll0yZ = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llXy0 = getShadeBrightness(tt, level, pX + 1, pY, pZ); - llxy0 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0yz = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - ll0yZ = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llXy0 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); + if (llTrans0yz || llTransxy0) { + llxyz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1); + ccxyz = getLightColor(tt, level, pX - 1, pY, pZ - 1); + } else { + llxyz = llxy0; + ccxyz = ccxy0; + } + if (llTrans0yZ || llTransxy0) { + llxyZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1); + ccxyZ = getLightColor(tt, level, pX - 1, pY, pZ + 1); + } else { + llxyZ = llxy0; + ccxyZ = ccxy0; + } + if (llTrans0yz || llTransXy0) { + llXyz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1); + ccXyz = getLightColor(tt, level, pX + 1, pY, pZ - 1); + } else { + llXyz = llXy0; + ccXyz = ccXy0; + } + if (llTrans0yZ || llTransXy0) { + llXyZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1); + ccXyZ = getLightColor(tt, level, pX + 1, pY, pZ + 1); + } else { + llXyZ = llXy0; + ccXyZ = ccXy0; + } - if ( llTrans0yz || llTransxy0 ) - { - llxyz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1 ); - ccxyz = getLightColor(tt, level, pX - 1, pY, pZ - 1 ); - } - else - { - llxyz = llxy0; - ccxyz = ccxy0; - } - if ( llTrans0yZ || llTransxy0 ) - { - llxyZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1 ); - ccxyZ = getLightColor(tt, level, pX - 1, pY, pZ + 1 ); - } - else - { - llxyZ = llxy0; - ccxyZ = ccxy0; - } - if ( llTrans0yz || llTransXy0 ) - { - llXyz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1 ); - ccXyz = getLightColor(tt, level, pX + 1, pY, pZ - 1 ); - } - else - { - llXyz = llXy0; - ccXyz = ccXy0; - } - if ( llTrans0yZ || llTransXy0 ) - { - llXyZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1 ); - ccXyZ = getLightColor(tt, level, pX + 1, pY, pZ + 1 ); - } - else - { - llXyZ = llXy0; - ccXyZ = ccXy0; - } + if (tileShapeY0 <= 0) + pY++; // 4J - condition brought forward from 1.2.3 + ll1 = (llxyZ + llxy0 + ll0yZ + ll0y0) / 4.0f; + ll4 = (ll0yZ + ll0y0 + llXyZ + llXy0) / 4.0f; + ll3 = (ll0y0 + ll0yz + llXy0 + llXyz) / 4.0f; + ll2 = (llxy0 + llxyz + ll0y0 + ll0yz) / 4.0f; - if ( tileShapeY0 <= 0 ) pY++; // 4J - condition brought forward from 1.2.3 - ll1 = ( llxyZ + llxy0 + ll0yZ + ll0y0 ) / 4.0f; - ll4 = ( ll0yZ + ll0y0 + llXyZ + llXy0 ) / 4.0f; - ll3 = ( ll0y0 + ll0yz + llXy0 + llXyz ) / 4.0f; - ll2 = ( llxy0 + llxyz + ll0y0 + ll0yz ) / 4.0f; + tc1 = blend(ccxyZ, ccxy0, cc0yZ, cc0y0); + tc4 = blend(cc0yZ, ccXyZ, ccXy0, cc0y0); + tc3 = blend(cc0yz, ccXy0, ccXyz, cc0y0); + tc2 = blend(ccxy0, ccxyz, cc0yz, cc0y0); + } else { + ll1 = ll2 = ll3 = ll4 = ll0y0; + tc1 = tc2 = tc3 = tc4 = ccxy0; + } + c1r = c2r = c3r = c4r = (tint0 ? pBaseRed : 1.0f) * 0.5f; + c1g = c2g = c3g = c4g = (tint0 ? pBaseGreen : 1.0f) * 0.5f; + c1b = c2b = c3b = c4b = (tint0 ? pBaseBlue : 1.0f) * 0.5f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend( ccxyZ, ccxy0, cc0yZ, cc0y0 ); - tc4 = blend( cc0yZ, ccXyZ, ccXy0, cc0y0 ); - tc3 = blend( cc0yz, ccXy0, ccXyz, cc0y0 ); - tc2 = blend( ccxy0, ccxyz, cc0yz, cc0y0 ); - } - else - { - ll1 = ll2 = ll3 = ll4 = ll0y0; - tc1 = tc2 = tc3 = tc4 = ccxy0; - } - c1r = c2r = c3r = c4r = ( tint0 ? pBaseRed : 1.0f ) * 0.5f; - c1g = c2g = c3g = c4g = ( tint0 ? pBaseGreen : 1.0f ) * 0.5f; - c1b = c2b = c3b = c4b = ( tint0 ? pBaseBlue : 1.0f ) * 0.5f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + renderFaceDown( + tt, (double)pX, (double)pY, (double)pZ, + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 0)); + } + if (faceFlags & 0x02) { + if (blsmooth > 0) { + if (tileShapeY1 >= 1) + pY++; // 4J - condition brought forward from 1.2.3 - renderFaceDown( tt, ( double )pX, ( double )pY, ( double )pZ, uniformTex ? uniformTex : getTexture( tt, level, pX, pY, pZ, 0 ) ); - } - if ( faceFlags & 0x02 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeY1 >= 1 ) pY++; // 4J - condition brought forward from 1.2.3 + ccxY0 = getLightColor(tt, level, pX - 1, pY, pZ); + ccXY0 = getLightColor(tt, level, pX + 1, pY, pZ); + cc0Yz = getLightColor(tt, level, pX, pY, pZ - 1); + cc0YZ = getLightColor(tt, level, pX, pY, pZ + 1); - ccxY0 = getLightColor(tt, level, pX - 1, pY, pZ ); - ccXY0 = getLightColor(tt, level, pX + 1, pY, pZ ); - cc0Yz = getLightColor(tt, level, pX, pY, pZ - 1 ); - cc0YZ = getLightColor(tt, level, pX, pY, pZ + 1 ); + llxY0 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + llXY0 = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0Yz = getShadeBrightness(tt, level, pX, pY, pZ - 1); + ll0YZ = getShadeBrightness(tt, level, pX, pY, pZ + 1); - llxY0 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - llXY0 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0Yz = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - ll0YZ = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); + if (llTrans0Yz || llTransxY0) { + llxYz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1); + ccxYz = getLightColor(tt, level, pX - 1, pY, pZ - 1); + } else { + llxYz = llxY0; + ccxYz = ccxY0; + } + if (llTrans0Yz || llTransXY0) { + llXYz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1); + ccXYz = getLightColor(tt, level, pX + 1, pY, pZ - 1); + } else { + llXYz = llXY0; + ccXYz = ccXY0; + } + if (llTrans0YZ || llTransxY0) { + llxYZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1); + ccxYZ = getLightColor(tt, level, pX - 1, pY, pZ + 1); + } else { + llxYZ = llxY0; + ccxYZ = ccxY0; + } + if (llTrans0YZ || llTransXY0) { + llXYZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1); + ccXYZ = getLightColor(tt, level, pX + 1, pY, pZ + 1); + } else { + llXYZ = llXY0; + ccXYZ = ccXY0; + } + if (tileShapeY1 >= 1) + pY--; // 4J - condition brought forward from 1.2.3 - if ( llTrans0Yz || llTransxY0 ) - { - llxYz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1 ); - ccxYz = getLightColor(tt, level, pX - 1, pY, pZ - 1 ); - } - else - { - llxYz = llxY0; - ccxYz = ccxY0; - } - if ( llTrans0Yz || llTransXY0 ) - { - llXYz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1 ); - ccXYz = getLightColor(tt, level, pX + 1, pY, pZ - 1 ); - } - else - { - llXYz = llXY0; - ccXYz = ccXY0; - } - if ( llTrans0YZ || llTransxY0 ) - { - llxYZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1 ); - ccxYZ = getLightColor(tt, level, pX - 1, pY, pZ + 1 ); - } - else - { - llxYZ = llxY0; - ccxYZ = ccxY0; - } - if ( llTrans0YZ || llTransXY0 ) - { - llXYZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1 ); - ccXYZ = getLightColor(tt, level, pX + 1, pY, pZ + 1 ); - } - else - { - llXYZ = llXY0; - ccXYZ = ccXY0; - } - if ( tileShapeY1 >= 1 ) pY--; // 4J - condition brought forward from 1.2.3 + ll4 = (llxYZ + llxY0 + ll0YZ + ll0Y0) / 4.0f; + ll1 = (ll0YZ + ll0Y0 + llXYZ + llXY0) / 4.0f; + ll2 = (ll0Y0 + ll0Yz + llXY0 + llXYz) / 4.0f; + ll3 = (llxY0 + llxYz + ll0Y0 + ll0Yz) / 4.0f; - ll4 = ( llxYZ + llxY0 + ll0YZ + ll0Y0 ) / 4.0f; - ll1 = ( ll0YZ + ll0Y0 + llXYZ + llXY0 ) / 4.0f; - ll2 = ( ll0Y0 + ll0Yz + llXY0 + llXYz ) / 4.0f; - ll3 = ( llxY0 + llxYz + ll0Y0 + ll0Yz ) / 4.0f; + tc4 = blend(ccxYZ, ccxY0, cc0YZ, cc0Y0); + tc1 = blend(cc0YZ, ccXYZ, ccXY0, cc0Y0); + tc2 = blend(cc0Yz, ccXY0, ccXYz, cc0Y0); + tc3 = blend(ccxY0, ccxYz, cc0Yz, cc0Y0); + } else { + ll1 = ll2 = ll3 = ll4 = ll0Y0; + tc1 = tc2 = tc3 = tc4 = cc0Y0; + } + c1r = c2r = c3r = c4r = (tint1 ? pBaseRed : 1.0f); + c1g = c2g = c3g = c4g = (tint1 ? pBaseGreen : 1.0f); + c1b = c2b = c3b = c4b = (tint1 ? pBaseBlue : 1.0f); + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + renderFaceUp( + tt, (double)pX, (double)pY, (double)pZ, + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 1)); + } + if (faceFlags & 0x04) { + if (blsmooth > 0) { + if (tileShapeZ0 <= 0) + pZ--; // 4J - condition brought forward from 1.2.3 + llx0z = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0yz = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll0Yz = getShadeBrightness(tt, level, pX, pY + 1, pZ); + llX0z = getShadeBrightness(tt, level, pX + 1, pY, pZ); - tc4 = blend( ccxYZ, ccxY0, cc0YZ, cc0Y0 ); - tc1 = blend( cc0YZ, ccXYZ, ccXY0, cc0Y0 ); - tc2 = blend( cc0Yz, ccXY0, ccXYz, cc0Y0 ); - tc3 = blend( ccxY0, ccxYz, cc0Yz, cc0Y0 ); - } - else - { - ll1 = ll2 = ll3 = ll4 = ll0Y0; - tc1 = tc2 = tc3 = tc4 = cc0Y0; - } - c1r = c2r = c3r = c4r = ( tint1 ? pBaseRed : 1.0f ); - c1g = c2g = c3g = c4g = ( tint1 ? pBaseGreen : 1.0f ); - c1b = c2b = c3b = c4b = ( tint1 ? pBaseBlue : 1.0f ); - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - renderFaceUp( tt, ( double )pX, ( double )pY, ( double )pZ, uniformTex ? uniformTex : getTexture( tt, level, pX, pY, pZ, 1 ) ); - } - if ( faceFlags & 0x04 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeZ0 <= 0 ) pZ--; // 4J - condition brought forward from 1.2.3 - llx0z = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0yz = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll0Yz = getShadeBrightness(tt, level, pX, pY + 1, pZ ); - llX0z = getShadeBrightness(tt, level, pX + 1, pY, pZ ); + ccx0z = getLightColor(tt, level, pX - 1, pY, pZ); + cc0yz = getLightColor(tt, level, pX, pY - 1, pZ); + cc0Yz = getLightColor(tt, level, pX, pY + 1, pZ); + ccX0z = getLightColor(tt, level, pX + 1, pY, pZ); - ccx0z = getLightColor(tt, level, pX - 1, pY, pZ ); - cc0yz = getLightColor(tt, level, pX, pY - 1, pZ ); - cc0Yz = getLightColor(tt, level, pX, pY + 1, pZ ); - ccX0z = getLightColor(tt, level, pX + 1, pY, pZ ); + if (llTransx0z || llTrans0yz) { + llxyz = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ); + ccxyz = getLightColor(tt, level, pX - 1, pY - 1, pZ); + } else { + llxyz = llx0z; + ccxyz = ccx0z; + } + if (llTransx0z || llTrans0Yz) { + llxYz = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ); + ccxYz = getLightColor(tt, level, pX - 1, pY + 1, pZ); + } else { + llxYz = llx0z; + ccxYz = ccx0z; + } + if (llTransX0z || llTrans0yz) { + llXyz = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ); + ccXyz = getLightColor(tt, level, pX + 1, pY - 1, pZ); + } else { + llXyz = llX0z; + ccXyz = ccX0z; + } + if (llTransX0z || llTrans0Yz) { + llXYz = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ); + ccXYz = getLightColor(tt, level, pX + 1, pY + 1, pZ); + } else { + llXYz = llX0z; + ccXYz = ccX0z; + } + if (tileShapeZ0 <= 0) + pZ++; // 4J - condition brought forward from 1.2.3 - if ( llTransx0z || llTrans0yz ) - { - llxyz = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ ); - ccxyz = getLightColor(tt, level, pX - 1, pY - 1, pZ ); - } - else - { - llxyz = llx0z; - ccxyz = ccx0z; - } - if ( llTransx0z || llTrans0Yz ) - { - llxYz = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ ); - ccxYz = getLightColor(tt, level, pX - 1, pY + 1, pZ ); - } - else - { - llxYz = llx0z; - ccxYz = ccx0z; - } - if ( llTransX0z || llTrans0yz ) - { - llXyz = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ ); - ccXyz = getLightColor(tt, level, pX + 1, pY - 1, pZ ); - } - else - { - llXyz = llX0z; - ccXyz = ccX0z; - } - if ( llTransX0z || llTrans0Yz ) - { - llXYz = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ ); - ccXYz = getLightColor(tt, level, pX + 1, pY + 1, pZ ); - } - else - { - llXYz = llX0z; - ccXYz = ccX0z; - } - if ( tileShapeZ0 <= 0 ) pZ++; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX + // until we work out exactly what its peformance + // implications are/what it fixes + { + float _ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; + float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; + float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; + float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + + _ll2 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + + _ll4 * (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + ll2 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + + _ll2 * tileShapeY1 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + + _ll4 * (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); + ll3 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + + _ll2 * tileShapeY0 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + + _ll4 * (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + ll4 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + + _ll2 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + + _ll4 * (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); - if (smoothShapeLighting && false) //minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; - float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; - float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; - float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); + int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); + int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); + int _tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); + int _tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX0), + tileShapeY1 * tileShapeX0, + (1.0 - tileShapeY1) * tileShapeX0, + (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX1), + tileShapeY1 * tileShapeX1, + (1.0 - tileShapeY1) * tileShapeX1, + (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX1), + tileShapeY0 * tileShapeX1, + (1.0 - tileShapeY0) * tileShapeX1, + (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX0), + tileShapeY0 * tileShapeX0, + (1.0 - tileShapeY0) * tileShapeX0, + (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); + } else { + ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; + ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; + ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; + ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); - int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); - int _tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); - int _tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX0), tileShapeY1 * tileShapeX0, (1.0 - tileShapeY1) * tileShapeX0, (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX1), tileShapeY1 * tileShapeX1, (1.0 - tileShapeY1) * tileShapeX1, (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX1), tileShapeY0 * tileShapeX1, (1.0 - tileShapeY0) * tileShapeX1, (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX0), tileShapeY0 * tileShapeX0, (1.0 - tileShapeY0) * tileShapeX0, (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); - } else { - ll1 = ( llx0z + llxYz + ll00z + ll0Yz ) / 4.0f; - ll2 = ( ll00z + ll0Yz + llX0z + llXYz ) / 4.0f; - ll3 = ( ll0yz + ll00z + llXyz + llX0z ) / 4.0f; - ll4 = ( llxyz + llx0z + ll0yz + ll00z ) / 4.0f; + tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); + tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); + tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); + tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); + } + } else { + ll1 = ll2 = ll3 = ll4 = ll00z; + tc1 = tc2 = tc3 = tc4 = cc00z; + } + c1r = c2r = c3r = c4r = (tint2 ? pBaseRed : 1.0f) * 0.8f; + c1g = c2g = c3g = c4g = (tint2 ? pBaseGreen : 1.0f) * 0.8f; + c1b = c2b = c3b = c4b = (tint2 ? pBaseBlue : 1.0f) * 0.8f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend( ccx0z, ccxYz, cc0Yz, cc00z ); - tc2 = blend( cc0Yz, ccX0z, ccXYz, cc00z ); - tc3 = blend( cc0yz, ccXyz, ccX0z, cc00z ); - tc4 = blend( ccxyz, ccx0z, cc0yz, cc00z ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = ll00z; - tc1 = tc2 = tc3 = tc4 = cc00z; - } - c1r = c2r = c3r = c4r = ( tint2 ? pBaseRed : 1.0f ) * 0.8f; - c1g = c2g = c3g = c4g = ( tint2 ? pBaseGreen : 1.0f ) * 0.8f; - c1b = c2b = c3b = c4b = ( tint2 ? pBaseBlue : 1.0f ) * 0.8f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 2); + renderNorth(tt, (double)pX, (double)pY, (double)pZ, tex); - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 2); - renderNorth( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderNorth(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x08) { + if (blsmooth > 0) { + if (tileShapeZ1 >= 1) + pZ++; // 4J - condition brought forward from 1.2.3 - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderNorth( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x08 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeZ1 >= 1 ) pZ++; // 4J - condition brought forward from 1.2.3 + llx0Z = getShadeBrightness(tt, level, pX - 1, pY, pZ); + llX0Z = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0yZ = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll0YZ = getShadeBrightness(tt, level, pX, pY + 1, pZ); - llx0Z = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - llX0Z = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0yZ = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll0YZ = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccx0Z = getLightColor(tt, level, pX - 1, pY, pZ); + ccX0Z = getLightColor(tt, level, pX + 1, pY, pZ); + cc0yZ = getLightColor(tt, level, pX, pY - 1, pZ); + cc0YZ = getLightColor(tt, level, pX, pY + 1, pZ); - ccx0Z = getLightColor(tt, level, pX - 1, pY, pZ ); - ccX0Z = getLightColor(tt, level, pX + 1, pY, pZ ); - cc0yZ = getLightColor(tt, level, pX, pY - 1, pZ ); - cc0YZ = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransx0Z || llTrans0yZ) { + llxyZ = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ); + ccxyZ = getLightColor(tt, level, pX - 1, pY - 1, pZ); + } else { + llxyZ = llx0Z; + ccxyZ = ccx0Z; + } + if (llTransx0Z || llTrans0YZ) { + llxYZ = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ); + ccxYZ = getLightColor(tt, level, pX - 1, pY + 1, pZ); + } else { + llxYZ = llx0Z; + ccxYZ = ccx0Z; + } + if (llTransX0Z || llTrans0yZ) { + llXyZ = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ); + ccXyZ = getLightColor(tt, level, pX + 1, pY - 1, pZ); + } else { + llXyZ = llX0Z; + ccXyZ = ccX0Z; + } + if (llTransX0Z || llTrans0YZ) { + llXYZ = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ); + ccXYZ = getLightColor(tt, level, pX + 1, pY + 1, pZ); + } else { + llXYZ = llX0Z; + ccXYZ = ccX0Z; + } + if (tileShapeZ1 >= 1) + pZ--; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until + // we work out exactly what its peformance implications + // are/what it fixes + { + float _ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; + float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; + float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; + float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + + _ll4 * tileShapeY1 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + ll2 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + + _ll4 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); + ll3 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + + _ll4 * tileShapeY0 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + ll4 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + + _ll4 * tileShapeY1 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); - if ( llTransx0Z || llTrans0yZ ) - { - llxyZ = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ ); - ccxyZ = getLightColor(tt, level, pX - 1, pY - 1, pZ ); - } - else - { - llxyZ = llx0Z; - ccxyZ = ccx0Z; - } - if ( llTransx0Z || llTrans0YZ ) - { - llxYZ = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ ); - ccxYZ = getLightColor(tt, level, pX - 1, pY + 1, pZ ); - } - else - { - llxYZ = llx0Z; - ccxYZ = ccx0Z; - } - if ( llTransX0Z || llTrans0yZ ) - { - llXyZ = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ ); - ccXyZ = getLightColor(tt, level, pX + 1, pY - 1, pZ ); - } - else - { - llXyZ = llX0Z; - ccXyZ = ccX0Z; - } - if ( llTransX0Z || llTrans0YZ ) - { - llXYZ = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ ); - ccXYZ = getLightColor(tt, level, pX + 1, pY + 1, pZ ); - } - else - { - llXYZ = llX0Z; - ccXYZ = ccX0Z; - } - if ( tileShapeZ1 >= 1 ) pZ--; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; - float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; - float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; - float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); + int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); + int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); + int _tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); + int _tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX0), + (1.0 - tileShapeY1) * (1.0 - tileShapeX0), + (1.0 - tileShapeY1) * tileShapeX0, + tileShapeY1 * tileShapeX0); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX0), + (1.0 - tileShapeY0) * (1.0 - tileShapeX0), + (1.0 - tileShapeY0) * tileShapeX0, + tileShapeY0 * tileShapeX0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX1), + (1.0 - tileShapeY0) * (1.0 - tileShapeX1), + (1.0 - tileShapeY0) * tileShapeX1, + tileShapeY0 * tileShapeX1); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX1), + (1.0 - tileShapeY1) * (1.0 - tileShapeX1), + (1.0 - tileShapeY1) * tileShapeX1, + tileShapeY1 * tileShapeX1); + } else { + ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; + ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; + ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; + ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); - int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); - int _tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); - int _tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX0), (1.0 - tileShapeY1) * (1.0 - tileShapeX0), (1.0 - tileShapeY1) * tileShapeX0, tileShapeY1 * tileShapeX0); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX0), (1.0 - tileShapeY0) * (1.0 - tileShapeX0), (1.0 - tileShapeY0) * tileShapeX0, tileShapeY0 * tileShapeX0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX1), (1.0 - tileShapeY0) * (1.0 - tileShapeX1), (1.0 - tileShapeY0) * tileShapeX1, tileShapeY0 * tileShapeX1); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX1), (1.0 - tileShapeY1) * (1.0 - tileShapeX1), (1.0 - tileShapeY1) * tileShapeX1, tileShapeY1 * tileShapeX1); - } - else - { - ll1 = ( llx0Z + llxYZ + ll00Z + ll0YZ ) / 4.0f; - ll4 = ( ll00Z + ll0YZ + llX0Z + llXYZ ) / 4.0f; - ll3 = ( ll0yZ + ll00Z + llXyZ + llX0Z ) / 4.0f; - ll2 = ( llxyZ + llx0Z + ll0yZ + ll00Z ) / 4.0f; + tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); + tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); + tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); + tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); + } + } else { + ll1 = ll2 = ll3 = ll4 = ll00Z; + tc1 = tc2 = tc3 = tc4 = cc00Z; + } + c1r = c2r = c3r = c4r = (tint3 ? pBaseRed : 1.0f) * 0.8f; + c1g = c2g = c3g = c4g = (tint3 ? pBaseGreen : 1.0f) * 0.8f; + c1b = c2b = c3b = c4b = (tint3 ? pBaseBlue : 1.0f) * 0.8f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 3); + renderSouth(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderSouth(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x10) { + if (blsmooth > 0) { + if (tileShapeX0 <= 0) + pX--; // 4J - condition brought forward from 1.2.3 + llxy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + llx0z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llx0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llxY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); - tc1 = blend( ccx0Z, ccxYZ, cc0YZ, cc00Z ); - tc4 = blend( cc0YZ, ccX0Z, ccXYZ, cc00Z ); - tc3 = blend( cc0yZ, ccXyZ, ccX0Z, cc00Z ); - tc2 = blend( ccxyZ, ccx0Z, cc0yZ, cc00Z ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = ll00Z; - tc1 = tc2 = tc3 = tc4 = cc00Z; - } - c1r = c2r = c3r = c4r = ( tint3 ? pBaseRed : 1.0f ) * 0.8f; - c1g = c2g = c3g = c4g = ( tint3 ? pBaseGreen : 1.0f ) * 0.8f; - c1b = c2b = c3b = c4b = ( tint3 ? pBaseBlue : 1.0f ) * 0.8f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 3); - renderSouth( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderSouth( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x10 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeX0 <= 0 ) pX--; // 4J - condition brought forward from 1.2.3 - llxy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - llx0z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llx0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llxY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccxy0 = getLightColor(tt, level, pX, pY - 1, pZ); + ccx0z = getLightColor(tt, level, pX, pY, pZ - 1); + ccx0Z = getLightColor(tt, level, pX, pY, pZ + 1); + ccxY0 = getLightColor(tt, level, pX, pY + 1, pZ); - ccxy0 = getLightColor(tt, level, pX, pY - 1, pZ ); - ccx0z = getLightColor(tt, level, pX, pY, pZ - 1 ); - ccx0Z = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccxY0 = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransx0z || llTransxy0) { + llxyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1); + ccxyz = getLightColor(tt, level, pX, pY - 1, pZ - 1); + } else { + llxyz = llx0z; + ccxyz = ccx0z; + } + if (llTransx0Z || llTransxy0) { + llxyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1); + ccxyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1); + } else { + llxyZ = llx0Z; + ccxyZ = ccx0Z; + } + if (llTransx0z || llTransxY0) { + llxYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1); + ccxYz = getLightColor(tt, level, pX, pY + 1, pZ - 1); + } else { + llxYz = llx0z; + ccxYz = ccx0z; + } + if (llTransx0Z || llTransxY0) { + llxYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1); + ccxYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1); + } else { + llxYZ = llx0Z; + ccxYZ = ccx0Z; + } + if (tileShapeX0 <= 0) + pX++; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until we + // work out exactly what its peformance implications + // are/what it fixes + { + float _ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; + float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; + float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; + float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * tileShapeZ1 + + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + + _ll4 * (1.0 - tileShapeY1) * tileShapeZ1); + ll2 = (float)(_ll1 * tileShapeY1 * tileShapeZ0 + + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + + _ll4 * (1.0 - tileShapeY1) * tileShapeZ0); + ll3 = (float)(_ll1 * tileShapeY0 * tileShapeZ0 + + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + + _ll4 * (1.0 - tileShapeY0) * tileShapeZ0); + ll4 = (float)(_ll1 * tileShapeY0 * tileShapeZ1 + + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + + _ll4 * (1.0 - tileShapeY0) * tileShapeZ1); - if ( llTransx0z || llTransxy0 ) - { - llxyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1 ); - ccxyz = getLightColor(tt, level, pX, pY - 1, pZ - 1 ); - } - else - { - llxyz = llx0z; - ccxyz = ccx0z; - } - if ( llTransx0Z || llTransxy0 ) - { - llxyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1 ); - ccxyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1 ); - } - else - { - llxyZ = llx0Z; - ccxyZ = ccx0Z; - } - if ( llTransx0z || llTransxY0 ) - { - llxYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1 ); - ccxYz = getLightColor(tt, level, pX, pY + 1, pZ - 1 ); - } - else - { - llxYz = llx0z; - ccxYz = ccx0z; - } - if ( llTransx0Z || llTransxY0 ) - { - llxYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1 ); - ccxYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1 ); - } - else - { - llxYZ = llx0Z; - ccxYZ = ccx0Z; - } - if ( tileShapeX0 <= 0 ) pX++; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; - float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; - float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; - float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ1); - ll2 = (float) (_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ0); - ll3 = (float) (_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ0); - ll4 = (float) (_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ1); + int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); + int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); + int _tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); + int _tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ1, + tileShapeY1 * (1.0 - tileShapeZ1), + (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), + (1.0 - tileShapeY1) * tileShapeZ1); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ0, + tileShapeY1 * (1.0 - tileShapeZ0), + (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), + (1.0 - tileShapeY1) * tileShapeZ0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ0, + tileShapeY0 * (1.0 - tileShapeZ0), + (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), + (1.0 - tileShapeY0) * tileShapeZ0); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ1, + tileShapeY0 * (1.0 - tileShapeZ1), + (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), + (1.0 - tileShapeY0) * tileShapeZ1); + } else { + ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; + ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; + ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; + ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); - int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); - int _tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); - int _tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ1, tileShapeY1 * (1.0 - tileShapeZ1), (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), (1.0 - tileShapeY1) * tileShapeZ1); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ0, tileShapeY1 * (1.0 - tileShapeZ0), (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), (1.0 - tileShapeY1) * tileShapeZ0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ0, tileShapeY0 * (1.0 - tileShapeZ0), (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), (1.0 - tileShapeY0) * tileShapeZ0); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ1, tileShapeY0 * (1.0 - tileShapeZ1), (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), (1.0 - tileShapeY0) * tileShapeZ1); - } - else - { - ll4 = ( llxy0 + llxyZ + llx00 + llx0Z ) / 4.0f; - ll1 = ( llx00 + llx0Z + llxY0 + llxYZ ) / 4.0f; - ll2 = ( llx0z + llx00 + llxYz + llxY0 ) / 4.0f; - ll3 = ( llxyz + llxy0 + llx0z + llx00 ) / 4.0f; + tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); + tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); + tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); + tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); + } + } else { + ll1 = ll2 = ll3 = ll4 = llx00; + tc1 = tc2 = tc3 = tc4 = ccx00; + } + c1r = c2r = c3r = c4r = (tint4 ? pBaseRed : 1.0f) * 0.6f; + c1g = c2g = c3g = c4g = (tint4 ? pBaseGreen : 1.0f) * 0.6f; + c1b = c2b = c3b = c4b = (tint4 ? pBaseBlue : 1.0f) * 0.6f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 4); + renderWest(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderWest(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x20) { + if (blsmooth > 0) { + if (tileShapeX1 >= 1) + pX++; // 4J - condition brought forward from 1.2.3 + llXy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + llX0z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llX0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llXY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); - tc4 = blend( ccxy0, ccxyZ, ccx0Z, ccx00 ); - tc1 = blend( ccx0Z, ccxY0, ccxYZ, ccx00 ); - tc2 = blend( ccx0z, ccxYz, ccxY0, ccx00 ); - tc3 = blend( ccxyz, ccxy0, ccx0z, ccx00 ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = llx00; - tc1 = tc2 = tc3 = tc4 = ccx00; - } - c1r = c2r = c3r = c4r = ( tint4 ? pBaseRed : 1.0f ) * 0.6f; - c1g = c2g = c3g = c4g = ( tint4 ? pBaseGreen : 1.0f ) * 0.6f; - c1b = c2b = c3b = c4b = ( tint4 ? pBaseBlue : 1.0f ) * 0.6f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 4); - renderWest( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderWest( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x20 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeX1 >= 1 ) pX++; // 4J - condition brought forward from 1.2.3 - llXy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - llX0z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llX0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llXY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccXy0 = getLightColor(tt, level, pX, pY - 1, pZ); + ccX0z = getLightColor(tt, level, pX, pY, pZ - 1); + ccX0Z = getLightColor(tt, level, pX, pY, pZ + 1); + ccXY0 = getLightColor(tt, level, pX, pY + 1, pZ); - ccXy0 = getLightColor(tt, level, pX, pY - 1, pZ ); - ccX0z = getLightColor(tt, level, pX, pY, pZ - 1 ); - ccX0Z = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccXY0 = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransXy0 || llTransX0z) { + llXyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1); + ccXyz = getLightColor(tt, level, pX, pY - 1, pZ - 1); + } else { + llXyz = llX0z; + ccXyz = ccX0z; + } + if (llTransXy0 || llTransX0Z) { + llXyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1); + ccXyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1); + } else { + llXyZ = llX0Z; + ccXyZ = ccX0Z; + } + if (llTransXY0 || llTransX0z) { + llXYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1); + ccXYz = getLightColor(tt, level, pX, pY + 1, pZ - 1); + } else { + llXYz = llX0z; + ccXYz = ccX0z; + } + if (llTransXY0 || llTransX0Z) { + llXYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1); + ccXYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1); + } else { + llXYZ = llX0Z; + ccXYZ = ccX0Z; + } + if (tileShapeX1 >= 1) + pX--; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until we + // work out exactly what its peformance implications + // are/what it fixes + { + float _ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; + float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; + float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; + float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; + ll1 = (float)(_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + + _ll4 * tileShapeY0 * tileShapeZ1); + ll2 = (float)(_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + + _ll4 * tileShapeY0 * tileShapeZ0); + ll3 = (float)(_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + + _ll4 * tileShapeY1 * tileShapeZ0); + ll4 = (float)(_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + + _ll4 * tileShapeY1 * tileShapeZ1); - if ( llTransXy0 || llTransX0z ) - { - llXyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1 ); - ccXyz = getLightColor(tt, level, pX, pY - 1, pZ - 1 ); - } - else - { - llXyz = llX0z; - ccXyz = ccX0z; - } - if ( llTransXy0 || llTransX0Z ) - { - llXyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1 ); - ccXyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1 ); - } - else - { - llXyZ = llX0Z; - ccXyZ = ccX0Z; - } - if ( llTransXY0 || llTransX0z ) - { - llXYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1 ); - ccXYz = getLightColor(tt, level, pX, pY + 1, pZ - 1 ); - } - else - { - llXYz = llX0z; - ccXYz = ccX0z; - } - if ( llTransXY0 || llTransX0Z ) - { - llXYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1 ); - ccXYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1 ); - } - else - { - llXYZ = llX0Z; - ccXYZ = ccX0Z; - } - if ( tileShapeX1 >= 1 ) pX--; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; - float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; - float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; - float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - ll1 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 - * tileShapeZ1); - ll2 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 - * tileShapeZ0); - ll3 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 - * tileShapeZ0); - ll4 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 - * tileShapeZ1); + int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); + int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); + int _tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); + int _tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY0) * tileShapeZ1, + (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), + tileShapeY0 * (1.0 - tileShapeZ1), + tileShapeY0 * tileShapeZ1); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY0) * tileShapeZ0, + (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), + tileShapeY0 * (1.0 - tileShapeZ0), + tileShapeY0 * tileShapeZ0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY1) * tileShapeZ0, + (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), + tileShapeY1 * (1.0 - tileShapeZ0), + tileShapeY1 * tileShapeZ0); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY1) * tileShapeZ1, + (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), + tileShapeY1 * (1.0 - tileShapeZ1), + tileShapeY1 * tileShapeZ1); + } else { + ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; + ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; + ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; + ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); - int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); - int _tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); - int _tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY0) * tileShapeZ1, (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), tileShapeY0 * (1.0 - tileShapeZ1), tileShapeY0 * tileShapeZ1); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY0) * tileShapeZ0, (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), tileShapeY0 * (1.0 - tileShapeZ0), tileShapeY0 * tileShapeZ0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY1) * tileShapeZ0, (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), tileShapeY1 * (1.0 - tileShapeZ0), tileShapeY1 * tileShapeZ0); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY1) * tileShapeZ1, (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), tileShapeY1 * (1.0 - tileShapeZ1), tileShapeY1 * tileShapeZ1); - } - else - { - ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; - ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; - ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; - ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; + tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); + tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); + tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); + tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); + } + } else { + ll1 = ll2 = ll3 = ll4 = llX00; + tc1 = tc2 = tc3 = tc4 = ccX00; + } + c1r = c2r = c3r = c4r = (tint5 ? pBaseRed : 1.0f) * 0.6f; + c1g = c2g = c3g = c4g = (tint5 ? pBaseGreen : 1.0f) * 0.6f; + c1b = c2b = c3b = c4b = (tint5 ? pBaseBlue : 1.0f) * 0.6f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); - tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); - tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); - tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = llX00; - tc1 = tc2 = tc3 = tc4 = ccX00; - } - c1r = c2r = c3r = c4r = ( tint5 ? pBaseRed : 1.0f ) * 0.6f; - c1g = c2g = c3g = c4g = ( tint5 ? pBaseGreen : 1.0f ) * 0.6f; - c1b = c2b = c3b = c4b = ( tint5 ? pBaseBlue : 1.0f ) * 0.6f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 5); + renderEast(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 5); - renderEast( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture()) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderEast( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - applyAmbienceOcclusion = false; - - return true; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderEast(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + applyAmbienceOcclusion = false; + return true; } // 4J - brought forward from 1.8.2 -int TileRenderer::blend( int a, int b, int c, int def ) -{ - if ( a == 0 ) a = def; - if ( b == 0 ) b = def; - if ( c == 0 ) c = def; - return ( ( a + b + c + def ) >> 2 ) & 0xff00ff; +int TileRenderer::blend(int a, int b, int c, int def) { + if (a == 0) a = def; + if (b == 0) b = def; + if (c == 0) c = def; + return ((a + b + c + def) >> 2) & 0xff00ff; } -int TileRenderer::blend(int a, int b, int c, int d, double fa, double fb, double fc, double fd) -{ - - int top = (int) ((double) ((a >> 16) & 0xff) * fa + (double) ((b >> 16) & 0xff) * fb + (double) ((c >> 16) & 0xff) * fc + (double) ((d >> 16) & 0xff) * fd) & 0xff; - int bottom = (int) ((double) (a & 0xff) * fa + (double) (b & 0xff) * fb + (double) (c & 0xff) * fc + (double) (d & 0xff) * fd) & 0xff; - return (top << 16) | bottom; +int TileRenderer::blend(int a, int b, int c, int d, double fa, double fb, + double fc, double fd) { + int top = (int)((double)((a >> 16) & 0xff) * fa + + (double)((b >> 16) & 0xff) * fb + + (double)((c >> 16) & 0xff) * fc + + (double)((d >> 16) & 0xff) * fd) & + 0xff; + int bottom = (int)((double)(a & 0xff) * fa + (double)(b & 0xff) * fb + + (double)(c & 0xff) * fc + (double)(d & 0xff) * fd) & + 0xff; + return (top << 16) | bottom; } -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ) -{ - applyAmbienceOcclusion = false; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, + float g, float b) { + applyAmbienceOcclusion = false; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - float r11 = c11 * r; - float g11 = c11 * g; - float b11 = c11 * b; + float r11 = c11 * r; + float g11 = c11 * g; + float b11 = c11 * b; - float r10 = c10; - float r2 = c2; - float r3 = c3; + float r10 = c10; + float r2 = c2; + float r3 = c3; - float g10 = c10; - float g2 = c2; - float g3 = c3; + float g10 = c10; + float g2 = c2; + float g3 = c3; - float b10 = c10; - float b2 = c2; - float b3 = c3; + float b10 = c10; + float b2 = c2; + float b3 = c3; - if ( tt != Tile::grass ) - { - r10 *= r; - r2 *= r; - r3 *= r; + if (tt != Tile::grass) { + r10 *= r; + r2 *= r; + r3 *= r; - g10 *= g; - g2 *= g; - g3 *= g; + g10 *= g; + g2 *= g; + g3 *= g; - b10 *= b; - b2 *= b; - b3 *= b; - } + b10 *= b; + b2 *= b; + b3 *= b; + } - int centerColor = 0; - float centerBrightness = 0.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + int centerColor = 0; + float centerBrightness = 0.0f; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - if ( noCulling || tt->shouldRenderFace( level, x, y - 1, z, Facing::DOWN ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( r10, g10, b10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - t->color( r10 * br, g10 * br, b10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture(tt, level, x, y, z, 0 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y - 1, z, Facing::DOWN)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(r10, g10, b10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + t->color(r10 * br, g10 * br, b10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y + 1, z, Facing::UP ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 != 1 && !tt->material->isLiquid() ) br = centerBrightness; - t->color( r11 * br, g11 * br, b11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture(tt, level, x, y, z, 1 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y + 1, z, Facing::UP)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 != 1 && !tt->material->isLiquid()) + br = centerBrightness; + t->color(r11 * br, g11 * br, b11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, Facing::NORTH ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if (noCulling || tt->shouldRenderFace(level, x, y, z - 1, Facing::NORTH)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - Icon *tex = getTexture(tt, level, x, y, z, 2); - renderNorth( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r2 * r, g2 * g, b2 * b ); - renderNorth( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + Icon* tex = getTexture(tt, level, x, y, z, 2); + renderNorth(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r2 * r, g2 * g, b2 * b); + renderNorth(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, Facing::SOUTH ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 3); - renderSouth( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r2 * r, g2 * g, b2 * b ); - renderSouth( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y, z + 1, Facing::SOUTH)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 3); + renderSouth(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r2 * r, g2 * g, b2 * b); + renderSouth(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, Facing::WEST ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 4); - renderWest( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r3 * r, g3 * g, b3 * b ); - renderWest( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x - 1, y, z, Facing::WEST)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 4); + renderWest(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r3 * r, g3 * g, b3 * b); + renderWest(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, Facing::EAST ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 5); - renderEast( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r3 * r, g3 * g, b3 * b ); - renderEast( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } - - return changed; + if (noCulling || tt->shouldRenderFace(level, x + 1, y, z, Facing::EAST)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 5); + renderEast(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r3 * r, g3 * g, b3 * b); + renderEast(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } + return changed; } -bool TileRenderer::tesselateCactusInWorld( Tile* tt, int x, int y, int z ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateCactusInWorld(Tile* tt, int x, int y, int z) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - return tesselateCactusInWorld( tt, x, y, z, r, g, b ); + return tesselateCactusInWorld(tt, x, y, z, r, g, b); } -bool TileRenderer::tesselateCactusInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateCactusInWorld(Tile* tt, int x, int y, int z, + float r, float g, float b) { + Tesselator* t = Tesselator::getInstance(); - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - float r10 = c10 * r; - float r11 = c11 * r; - float r2 = c2 * r; - float r3 = c3 * r; + float r10 = c10 * r; + float r11 = c11 * r; + float r2 = c2 * r; + float r3 = c3 * r; - float g10 = c10 * g; - float g11 = c11 * g; - float g2 = c2 * g; - float g3 = c3 * g; + float g10 = c10 * g; + float g11 = c11 * g; + float g2 = c2 * g; + float g3 = c3 * g; - float b10 = c10 * b; - float b11 = c11 * b; - float b2 = c2 * b; - float b3 = c3 * b; + float b10 = c10 * b; + float b11 = c11 * b; + float b2 = c2 * b; + float b3 = c3 * b; - float s = 1 / 16.0f; + float s = 1 / 16.0f; - float centerBrightness = 0.0f; - int centerColor = 0; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + float centerBrightness = 0.0f; + int centerColor = 0; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - if ( noCulling || tt->shouldRenderFace( level, x, y - 1, z, 0 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( r10, g10, b10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - t->color( r10 * br, g10 * br, b10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture( tt, level, x, y, z, 0 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y - 1, z, 0)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(r10, g10, b10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + t->color(r10 * br, g10 * br, b10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y + 1, z, 1 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 != 1 && !tt->material->isLiquid() ) br = centerBrightness; - t->color( r11 * br, g11 * br, b11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture( tt, level, x, y, z, 1 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y + 1, z, 1)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 != 1 && !tt->material->isLiquid()) + br = centerBrightness; + t->color(r11 * br, g11 * br, b11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, 2 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - t->addOffset( 0, 0, s ); - renderNorth( tt, x, y, z, getTexture(tt, level, x, y, z, 2 ) ); - t->addOffset( 0, 0, -s ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y, z - 1, 2)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + t->addOffset(0, 0, s); + renderNorth(tt, x, y, z, getTexture(tt, level, x, y, z, 2)); + t->addOffset(0, 0, -s); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, 3 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if (noCulling || tt->shouldRenderFace(level, x, y, z + 1, 3)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - t->addOffset( 0, 0, -s ); - renderSouth( tt, x, y, z, getTexture(tt, level, x, y, z, 3 ) ); - t->addOffset( 0, 0, s ); - changed = true; - } + t->addOffset(0, 0, -s); + renderSouth(tt, x, y, z, getTexture(tt, level, x, y, z, 3)); + t->addOffset(0, 0, s); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, 4 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - t->addOffset( s, 0, 0 ); - renderWest( tt, x, y, z, getTexture(tt, level, x, y, z, 4 ) ); - t->addOffset( -s, 0, 0 ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x - 1, y, z, 4)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + t->addOffset(s, 0, 0); + renderWest(tt, x, y, z, getTexture(tt, level, x, y, z, 4)); + t->addOffset(-s, 0, 0); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, 5 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - t->addOffset( -s, 0, 0 ); - renderEast( tt, x, y, z, getTexture(tt, level, x, y, z, 5 ) ); - t->addOffset( s, 0, 0 ); - changed = true; - } - - return changed; + if (noCulling || tt->shouldRenderFace(level, x + 1, y, z, 5)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + t->addOffset(-s, 0, 0); + renderEast(tt, x, y, z, getTexture(tt, level, x, y, z, 5)); + t->addOffset(s, 0, 0); + changed = true; + } + return changed; } -bool TileRenderer::tesselateFenceInWorld( FenceTile* tt, int x, int y, int z ) -{ - bool changed = false; +bool TileRenderer::tesselateFenceInWorld(FenceTile* tt, int x, int y, int z) { + bool changed = false; - float a = 6 / 16.0f; - float b = 10 / 16.0f; + float a = 6 / 16.0f; + float b = 10 / 16.0f; - setShape( a, 0, a, b, 1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; + setShape(a, 0, a, b, 1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; - bool vertical = false; - bool horizontal = false; + bool vertical = false; + bool horizontal = false; - if (tt->connectsTo(level, x - 1, y, z) || tt->connectsTo(level, x + 1, y, z)) vertical = true; - if (tt->connectsTo(level, x, y, z - 1) || tt->connectsTo(level, x, y, z + 1)) horizontal = true; + if (tt->connectsTo(level, x - 1, y, z) || + tt->connectsTo(level, x + 1, y, z)) + vertical = true; + if (tt->connectsTo(level, x, y, z - 1) || + tt->connectsTo(level, x, y, z + 1)) + horizontal = true; - bool l = tt->connectsTo(level, x - 1, y, z); - bool r = tt->connectsTo(level, x + 1, y, z); - bool u = tt->connectsTo(level, x, y, z - 1); - bool d = tt->connectsTo(level, x, y, z + 1); + bool l = tt->connectsTo(level, x - 1, y, z); + bool r = tt->connectsTo(level, x + 1, y, z); + bool u = tt->connectsTo(level, x, y, z - 1); + bool d = tt->connectsTo(level, x, y, z + 1); - if ( !vertical && !horizontal ) vertical = true; + if (!vertical && !horizontal) vertical = true; - a = 7 / 16.0f; - b = 9 / 16.0f; - float h0 = 12 / 16.0f; - float h1 = 15 / 16.0f; + a = 7 / 16.0f; + b = 9 / 16.0f; + float h0 = 12 / 16.0f; + float h1 = 15 / 16.0f; - float x0 = l ? 0 : a; - float x1 = r ? 1 : b; - float z0 = u ? 0 : a; - float z1 = d ? 1 : b; - if ( vertical ) - { - setShape( x0, h0, a, x1, h1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } - if ( horizontal ) - { - setShape( a, h0, z0, b, h1, z1 ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } + float x0 = l ? 0 : a; + float x1 = r ? 1 : b; + float z0 = u ? 0 : a; + float z1 = d ? 1 : b; + if (vertical) { + setShape(x0, h0, a, x1, h1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } + if (horizontal) { + setShape(a, h0, z0, b, h1, z1); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } - h0 = 6 / 16.0f; - h1 = 9 / 16.0f; - if ( vertical ) - { - setShape( x0, h0, a, x1, h1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } - if ( horizontal ) - { - setShape( a, h0, z0, b, h1, z1 ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } + h0 = 6 / 16.0f; + h1 = 9 / 16.0f; + if (vertical) { + setShape(x0, h0, a, x1, h1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } + if (horizontal) { + setShape(a, h0, z0, b, h1, z1); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } - tt->updateShape(level, x, y, z); + tt->updateShape(level, x, y, z); - return changed; + return changed; } -bool TileRenderer::tesselateWallInWorld(WallTile *tt, int x, int y, int z) -{ - bool w = tt->connectsTo(level, x - 1, y, z); - bool e = tt->connectsTo(level, x + 1, y, z); - bool n = tt->connectsTo(level, x, y, z - 1); - bool s = tt->connectsTo(level, x, y, z + 1); +bool TileRenderer::tesselateWallInWorld(WallTile* tt, int x, int y, int z) { + bool w = tt->connectsTo(level, x - 1, y, z); + bool e = tt->connectsTo(level, x + 1, y, z); + bool n = tt->connectsTo(level, x, y, z - 1); + bool s = tt->connectsTo(level, x, y, z + 1); - bool vertical = (n && s && !w && !e); - bool horizontal = (!n && !s && w && e); - bool emptyAbove = level->isEmptyTile(x, y + 1, z); + bool vertical = (n && s && !w && !e); + bool horizontal = (!n && !s && w && e); + bool emptyAbove = level->isEmptyTile(x, y + 1, z); - if ((!vertical && !horizontal) || !emptyAbove) - { - // center post - setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); - tesselateBlockInWorld(tt, x, y, z); + if ((!vertical && !horizontal) || !emptyAbove) { + // center post + setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, + .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, + .5f + WallTile::POST_WIDTH); + tesselateBlockInWorld(tt, x, y, z); - if (w) - { - setShape(0, 0, .5f - WallTile::WALL_WIDTH, .5f - WallTile::POST_WIDTH, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (e) - { - setShape(.5f + WallTile::POST_WIDTH, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (n) - { - setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, .5f - WallTile::POST_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (s) - { - setShape(.5f - WallTile::WALL_WIDTH, 0, .5f + WallTile::POST_WIDTH, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); - tesselateBlockInWorld(tt, x, y, z); - } - } - else if (vertical) - { - // north-south wall - setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); - tesselateBlockInWorld(tt, x, y, z); - } - else - { - // west-east wall - setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } + if (w) { + setShape(0, 0, .5f - WallTile::WALL_WIDTH, + .5f - WallTile::POST_WIDTH, WallTile::WALL_HEIGHT, + .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (e) { + setShape(.5f + WallTile::POST_WIDTH, 0, .5f - WallTile::WALL_WIDTH, + 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (n) { + setShape(.5f - WallTile::WALL_WIDTH, 0, 0, + .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, + .5f - WallTile::POST_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (s) { + setShape(.5f - WallTile::WALL_WIDTH, 0, .5f + WallTile::POST_WIDTH, + .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); + tesselateBlockInWorld(tt, x, y, z); + } + } else if (vertical) { + // north-south wall + setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, + WallTile::WALL_HEIGHT, 1); + tesselateBlockInWorld(tt, x, y, z); + } else { + // west-east wall + setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, + .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } - tt->updateShape(level, x, y, z); - return true; + tt->updateShape(level, x, y, z); + return true; } -bool TileRenderer::tesselateEggInWorld(EggTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateEggInWorld(EggTile* tt, int x, int y, int z) { bool changed = false; int y0 = 0; - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int ww = 0; int hh = 1; if (i == 0) ww = 2; if (i == 1) ww = 3; if (i == 2) ww = 4; - if (i == 3) - { + if (i == 3) { ww = 5; hh = 2; } - if (i == 4) - { + if (i == 4) { ww = 6; hh = 3; } - if (i == 5) - { + if (i == 5) { ww = 7; hh = 5; } - if (i == 6) - { + if (i == 6) { ww = 6; hh = 2; } @@ -5988,8 +5940,8 @@ bool TileRenderer::tesselateEggInWorld(EggTile *tt, int x, int y, int z) return changed; } -bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile* tt, int x, int y, + int z) { bool changed = true; int data = level->getData(x, y, z); @@ -6003,23 +5955,25 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in float h20 = 5 / 16.0f; float h21 = 16 / 16.0f; - if (((direction == Direction::NORTH || direction == Direction::SOUTH) && level->getTile(x - 1, y, z) == Tile::cobbleWall_Id && level->getTile(x + 1, y, z) == Tile::cobbleWall_Id) - || ((direction == Direction::EAST || direction == Direction::WEST) && level->getTile(x, y, z - 1) == Tile::cobbleWall_Id && level->getTile(x, y, z + 1) == Tile::cobbleWall_Id)) - { - h00 -= 3.0f / 16.0f; - h01 -= 3.0f / 16.0f; - h10 -= 3.0f / 16.0f; - h11 -= 3.0f / 16.0f; - h20 -= 3.0f / 16.0f; - h21 -= 3.0f / 16.0f; - } + if (((direction == Direction::NORTH || direction == Direction::SOUTH) && + level->getTile(x - 1, y, z) == Tile::cobbleWall_Id && + level->getTile(x + 1, y, z) == Tile::cobbleWall_Id) || + ((direction == Direction::EAST || direction == Direction::WEST) && + level->getTile(x, y, z - 1) == Tile::cobbleWall_Id && + level->getTile(x, y, z + 1) == Tile::cobbleWall_Id)) { + h00 -= 3.0f / 16.0f; + h01 -= 3.0f / 16.0f; + h10 -= 3.0f / 16.0f; + h11 -= 3.0f / 16.0f; + h20 -= 3.0f / 16.0f; + h21 -= 3.0f / 16.0f; + } - noCulling = true; + noCulling = true; // edge sticks - if (direction == Direction::EAST || direction == Direction::WEST) - { - upFlip = FLIP_CW; + if (direction == Direction::EAST || direction == Direction::WEST) { + upFlip = FLIP_CW; float x0 = 7 / 16.0f; float x1 = 9 / 16.0f; float z0 = 0 / 16.0f; @@ -6031,10 +5985,8 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in z1 = 16 / 16.0f; setShape(x0, h20, z0, x1, h21, z1); tesselateBlockInWorld(tt, x, y, z); - upFlip = FLIP_NONE; - } - else - { + upFlip = FLIP_NONE; + } else { float x0 = 0 / 16.0f; float x1 = 2 / 16.0f; float z0 = 7 / 16.0f; @@ -6047,1127 +5999,1117 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in setShape(x0, h20, z0, x1, h21, z1); tesselateBlockInWorld(tt, x, y, z); } - if (isOpen) - { - if (direction == Direction::NORTH || direction == Direction::SOUTH) - { - upFlip = FLIP_CW; - } - if (direction == Direction::EAST) - { + if (isOpen) { + if (direction == Direction::NORTH || direction == Direction::SOUTH) { + upFlip = FLIP_CW; + } + if (direction == Direction::EAST) { + const float z00 = 0 / 16.0f; + const float z01 = 2 / 16.0f; + const float z10 = 14 / 16.0f; + const float z11 = 16 / 16.0f; - const float z00 = 0 / 16.0f; - const float z01 = 2 / 16.0f; - const float z10 = 14 / 16.0f; - const float z11 = 16 / 16.0f; + const float x0 = 9 / 16.0f; + const float x1 = 13 / 16.0f; + const float x2 = 15 / 16.0f; - const float x0 = 9 / 16.0f; - const float x1 = 13 / 16.0f; - const float x2 = 15 / 16.0f; + setShape(x1, h00, z00, x2, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z10, x2, h11, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z00, x2, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z10, x2, h11, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z00, x1, h01, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z10, x1, h01, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z00, x1, h01, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z10, x1, h01, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z00, x1, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z10, x1, h11, z11); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::WEST) { + const float z00 = 0 / 16.0f; + const float z01 = 2 / 16.0f; + const float z10 = 14 / 16.0f; + const float z11 = 16 / 16.0f; - setShape(x0, h10, z00, x1, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z10, x1, h11, z11); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::WEST) - { - const float z00 = 0 / 16.0f; - const float z01 = 2 / 16.0f; - const float z10 = 14 / 16.0f; - const float z11 = 16 / 16.0f; + const float x0 = 1 / 16.0f; + const float x1 = 3 / 16.0f; + const float x2 = 7 / 16.0f; - const float x0 = 1 / 16.0f; - const float x1 = 3 / 16.0f; - const float x2 = 7 / 16.0f; + setShape(x0, h00, z00, x1, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z10, x1, h11, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z00, x1, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z10, x1, h11, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z00, x2, h01, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z10, x2, h01, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z00, x2, h01, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z10, x2, h01, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h10, z00, x2, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h10, z10, x2, h11, z11); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::SOUTH) { + const float x00 = 0 / 16.0f; + const float x01 = 2 / 16.0f; + const float x10 = 14 / 16.0f; + const float x11 = 16 / 16.0f; - setShape(x1, h10, z00, x2, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h10, z10, x2, h11, z11); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::SOUTH) - { + const float z0 = 9 / 16.0f; + const float z1 = 13 / 16.0f; + const float z2 = 15 / 16.0f; - const float x00 = 0 / 16.0f; - const float x01 = 2 / 16.0f; - const float x10 = 14 / 16.0f; - const float x11 = 16 / 16.0f; + setShape(x00, h00, z1, x01, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z1, x11, h11, z2); + tesselateBlockInWorld(tt, x, y, z); - const float z0 = 9 / 16.0f; - const float z1 = 13 / 16.0f; - const float z2 = 15 / 16.0f; + setShape(x00, h00, z0, x01, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z0, x11, h01, z1); + tesselateBlockInWorld(tt, x, y, z); - setShape(x00, h00, z1, x01, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z1, x11, h11, z2); - tesselateBlockInWorld(tt, x, y, z); + setShape(x00, h10, z0, x01, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h10, z0, x11, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::NORTH) { + const float x00 = 0 / 16.0f; + const float x01 = 2 / 16.0f; + const float x10 = 14 / 16.0f; + const float x11 = 16 / 16.0f; - setShape(x00, h00, z0, x01, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z0, x11, h01, z1); - tesselateBlockInWorld(tt, x, y, z); + const float z0 = 1 / 16.0f; + const float z1 = 3 / 16.0f; + const float z2 = 7 / 16.0f; - setShape(x00, h10, z0, x01, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h10, z0, x11, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::NORTH) - { - const float x00 = 0 / 16.0f; - const float x01 = 2 / 16.0f; - const float x10 = 14 / 16.0f; - const float x11 = 16 / 16.0f; + setShape(x00, h00, z0, x01, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z0, x11, h11, z1); + tesselateBlockInWorld(tt, x, y, z); - const float z0 = 1 / 16.0f; - const float z1 = 3 / 16.0f; - const float z2 = 7 / 16.0f; + setShape(x00, h00, z1, x01, h01, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z1, x11, h01, z2); + tesselateBlockInWorld(tt, x, y, z); - setShape(x00, h00, z0, x01, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z0, x11, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - - setShape(x00, h00, z1, x01, h01, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z1, x11, h01, z2); - tesselateBlockInWorld(tt, x, y, z); - - setShape(x00, h10, z1, x01, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h10, z1, x11, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - } - } - else - { - if (direction == Direction::EAST || direction == Direction::WEST) - { - upFlip = FLIP_CW; - float x0 = 7 / 16.0f; - float x1 = 9 / 16.0f; - float z0 = 6 / 16.0f; - float z1 = 8 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 8 / 16.0f; - z1 = 10 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 10 / 16.0f; - z1 = 14 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 2 / 16.0f; - z1 = 6 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - } - else - { - float x0 = 6 / 16.0f; - float x1 = 8 / 16.0f; - float z0 = 7 / 16.0f; - float z1 = 9 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 8 / 16.0f; - x1 = 10 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 10 / 16.0f; - x1 = 14 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 2 / 16.0f; - x1 = 6 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - - } - } - noCulling = false; - upFlip = FLIP_NONE; + setShape(x00, h10, z1, x01, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h10, z1, x11, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + } + } else { + if (direction == Direction::EAST || direction == Direction::WEST) { + upFlip = FLIP_CW; + float x0 = 7 / 16.0f; + float x1 = 9 / 16.0f; + float z0 = 6 / 16.0f; + float z1 = 8 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 8 / 16.0f; + z1 = 10 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 10 / 16.0f; + z1 = 14 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 2 / 16.0f; + z1 = 6 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } else { + float x0 = 6 / 16.0f; + float x1 = 8 / 16.0f; + float z0 = 7 / 16.0f; + float z1 = 9 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 8 / 16.0f; + x1 = 10 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 10 / 16.0f; + x1 = 14 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 2 / 16.0f; + x1 = 6 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } + } + noCulling = false; + upFlip = FLIP_NONE; setShape(0, 0, 0, 1, 1, 1); return changed; } -bool TileRenderer::tesselateStairsInWorld( StairTile* tt, int x, int y, int z ) -{ - tt->setBaseShape(level, x, y, z); - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); +bool TileRenderer::tesselateStairsInWorld(StairTile* tt, int x, int y, int z) { + tt->setBaseShape(level, x, y, z); + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); - bool checkInnerPiece = tt->setStepShape(level, x, y, z); - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); + bool checkInnerPiece = tt->setStepShape(level, x, y, z); + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); - if (checkInnerPiece) - { - if (tt->setInnerPieceShape(level, x, y, z)) - { - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); - } - } - return true; + if (checkInnerPiece) { + if (tt->setInnerPieceShape(level, x, y, z)) { + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); + } + } + return true; } -bool TileRenderer::tesselateDoorInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateDoorInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - // skip rendering if the other half of the door is missing, - // to avoid rendering doors that are about to be removed - int data = level->getData(x, y, z); - if ((data & DoorTile::UPPER_BIT) != 0) - { - if (level->getTile(x, y - 1, z) != tt->id) - { - return false; - } - } - else { - if (level->getTile(x, y + 1, z) != tt->id) - { - return false; - } - } + // skip rendering if the other half of the door is missing, + // to avoid rendering doors that are about to be removed + int data = level->getData(x, y, z); + if ((data & DoorTile::UPPER_BIT) != 0) { + if (level->getTile(x, y - 1, z) != tt->id) { + return false; + } + } else { + if (level->getTile(x, y + 1, z) != tt->id) { + return false; + } + } - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - int centerColor = 0; - float centerBrightness = 0.0f; + int centerColor = 0; + float centerBrightness = 0.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(c10, c10, c10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + if (tileShapeY0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c10 * br, c10 * br, c10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( c10, c10, c10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - if ( tileShapeY0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c10 * br, c10 * br, c10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture(tt, level, x, y, z, 0 ) ); - changed = true; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(c11, c11, c11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c11 * br, c11 * br, c11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( c11, c11, c11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c11 * br, c11 * br, c11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture(tt, level, x, y, z, 1 ) ); - changed = true; - - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( c2, c2, c2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c2 * br, c2 * br, c2 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 2 ); - renderNorth( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( c2, c2, c2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c2 * br, c2 * br, c2 * br ); - } - Icon *tex = getTexture( tt, level, x, y, z, 3 ); - renderSouth( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( c3, c3, c3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c3 * br, c3 * br, c3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 4 ); - renderWest( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( c3, c3, c3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c3 * br, c3 * br, c3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 5 ); - renderEast( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - return changed; + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(c2, c2, c2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c2 * br, c2 * br, c2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 2); + renderNorth(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(c2, c2, c2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c2 * br, c2 * br, c2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 3); + renderSouth(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(c3, c3, c3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c3 * br, c3 * br, c3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 4); + renderWest(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(c3, c3, c3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c3 * br, c3 * br, c3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 5); + renderEast(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + return changed; } -void TileRenderer::renderFaceDown( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderFaceDown(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - float u00 = tex->getU(tileShapeX0 * 16.0f, true); - float u11 = tex->getU(tileShapeX1 * 16.0f, true); - float v00 = tex->getV(tileShapeZ0 * 16.0f, true); - float v11 = tex->getV(tileShapeZ1 * 16.0f, true); + if (hasFixedTexture()) tex = fixedTexture; + float u00 = tex->getU(tileShapeX0 * 16.0f, true); + float u11 = tex->getU(tileShapeX1 * 16.0f, true); + float v00 = tex->getV(tileShapeZ0 * 16.0f, true); + float v11 = tex->getV(tileShapeZ1 * 16.0f, true); - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( downFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeZ0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - u11 = tex->getU(tileShapeZ1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + if (downFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeZ0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + u11 = tex->getU(tileShapeZ1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( downFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (downFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( downFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (downFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y0), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z0), (float)(u01), (float)(v01), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y0), (float)(z1), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderFaceUp( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderFaceUp(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - float u00 = tex->getU(tileShapeX0 * 16.0f, true); - float u11 = tex->getU(tileShapeX1 * 16.0f, true); - float v00 = tex->getV(tileShapeZ0 * 16.0f, true); - float v11 = tex->getV(tileShapeZ1 * 16.0f, true); + if (hasFixedTexture()) tex = fixedTexture; + float u00 = tex->getU(tileShapeX0 * 16.0f, true); + float u11 = tex->getU(tileShapeX1 * 16.0f, true); + float v00 = tex->getV(tileShapeZ0 * 16.0f, true); + float v11 = tex->getV(tileShapeZ1 * 16.0f, true); - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - float u01 = u11, u10 = u00, v01 = v00, v10 = v11; + float u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( upFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeZ0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - u11 = tex->getU(tileShapeZ1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); + if (upFlip == FLIP_CW) { + u00 = tex->getU(tileShapeZ0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + u11 = tex->getU(tileShapeZ1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( upFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (upFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( upFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (upFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c2r, c2g, c2b, tc2, - ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y1), (float)(z0), (float)(u01), (float)(v01), + c2r, c2g, c2b, tc2, (float)(x0), (float)(y1), + (float)(z0), (float)(u00), (float)(v00), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y1), (float)(z1), + (float)(u10), (float)(v10), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u10), + (float)(v10)); + } else { + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u10), + (float)(v10)); + } } -void TileRenderer::renderNorth( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderNorth(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeX0 * 16.0f, true); - double u11 = tex->getU(tileShapeX1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeX0 * 16.0f, true); + double u11 = tex->getU(tileShapeX1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( northFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); + if (northFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( northFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeX1 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeX0 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (northFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeX1 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeX0 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( northFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (northFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y1), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z0), (float)(u10), (float)(v10), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y0), (float)(z0), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderSouth( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderSouth(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeX0 * 16.0f, true); - double u11 = tex->getU(tileShapeX1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeX0 * 16.0f, true); + double u11 = tex->getU(tileShapeX1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( southFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); + if (southFlip == FLIP_CW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( southFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (southFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( southFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (southFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z1 = z + tileShapeZ1; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z1 = z + tileShapeZ1; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y0), (float)(z1), (float)(u10), (float)(v10), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z1), (float)(u11), (float)(v11), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y1), (float)(z1), + (float)(u01), (float)(v01), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + } } -void TileRenderer::renderWest( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderWest(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeZ0 * 16.0f, true); - double u11 = tex->getU(tileShapeZ1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeZ0 * 16.0f, true); + double u11 = tex->getU(tileShapeZ1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( westFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); + if (westFlip == FLIP_CW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( westFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeZ1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (westFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeZ0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeZ1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( westFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (westFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x0 = x + tileShapeX0; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x0 = x + tileShapeX0; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y1), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x0), (float)(y0), + (float)(z0), (float)(u10), (float)(v10), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y0), (float)(z1), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderEast( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderEast(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeZ0 * 16.0f, true); - double u11 = tex->getU(tileShapeZ1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeZ0 * 16.0f, true); + double u11 = tex->getU(tileShapeZ1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( eastFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + if (eastFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( eastFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeZ1 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeZ0 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (eastFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeZ1 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeZ0 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( eastFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (eastFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y0), (float)(z0), (float)(u11), (float)(v11), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y1), + (float)(z0), (float)(u01), (float)(v01), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y1), (float)(z1), + (float)(u00), (float)(v00), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + } else { + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + } } -void TileRenderer::renderCube( Tile* tile, float alpha ) -{ - int shape = tile->getRenderShape(); - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderCube(Tile* tile, float alpha) { + int shape = tile->getRenderShape(); + Tesselator* t = Tesselator::getInstance(); - if ( shape == Tile::SHAPE_BLOCK ) - { - tile->updateDefaultShape(); - glTranslatef( -0.5f, -0.5f, -0.5f ); - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + if (shape == Tile::SHAPE_BLOCK) { + tile->updateDefaultShape(); + glTranslatef(-0.5f, -0.5f, -0.5f); + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - t->begin(); - t->color( c11, c11, c11, alpha ); - renderFaceDown( tile, 0, 0, 0,getTexture(tile, 0 ) ); - t->color( c10, c10, c10, alpha ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->color( c2, c2, c2, alpha ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->color( c3, c3, c3, alpha ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); + t->begin(); + t->color(c11, c11, c11, alpha); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->color(c10, c10, c10, alpha); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->color(c2, c2, c2, alpha); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->color(c3, c3, c3, alpha); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); - t->end(); - - glTranslatef( 0.5f, 0.5f, 0.5f ); - } + t->end(); + glTranslatef(0.5f, 0.5f, 0.5f); + } } -void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAlpha, bool useCompiled ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderTile(Tile* tile, int data, float brightness, + float fAlpha, bool useCompiled) { + Tesselator* t = Tesselator::getInstance(); - bool isGrass = tile->id == Tile::grass_Id; + bool isGrass = tile->id == Tile::grass_Id; - if (tile == Tile::dispenser || tile == Tile::furnace) // || tile == Tile.dropper - { - data = 3; - } + if (tile == Tile::dispenser || + tile == Tile::furnace) // || tile == Tile.dropper + { + data = 3; + } - if ( setColor ) - { - int col = tile->getColor( data ); - if (isGrass) - { + if (setColor) { + int col = tile->getColor(data); + if (isGrass) { col = 0xffffff; } - float red = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f( red * brightness, g * brightness, b * brightness, fAlpha ); - } + glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); + } - int shape = tile->getRenderShape(); - setShape(tile); + int shape = tile->getRenderShape(); + setShape(tile); - t->setMipmapEnable( Tile::mipmapEnable[tile->id] ); // 4J added + t->setMipmapEnable(Tile::mipmapEnable[tile->id]); // 4J added - if ( shape == Tile::SHAPE_BLOCK || shape == Tile::SHAPE_TREE || shape == Tile::SHAPE_QUARTZ || shape == Tile::SHAPE_PISTON_BASE || shape == Tile::SHAPE_PORTAL_FRAME ) - { - if ( shape == Tile::SHAPE_PISTON_BASE ) - { - data = Facing::UP; - } + if (shape == Tile::SHAPE_BLOCK || shape == Tile::SHAPE_TREE || + shape == Tile::SHAPE_QUARTZ || shape == Tile::SHAPE_PISTON_BASE || + shape == Tile::SHAPE_PORTAL_FRAME) { + if (shape == Tile::SHAPE_PISTON_BASE) { + data = Facing::UP; + } - tile->updateDefaultShape(); - setShape(tile); - glRotatef(90, 0, 1, 0); + tile->updateDefaultShape(); + setShape(tile); + glRotatef(90, 0, 1, 0); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0, data ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7176,23 +7118,21 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); } - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1, data ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2, data ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7200,21 +7140,20 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3, data ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7222,21 +7161,20 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4, data ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7244,196 +7182,172 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5, data ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; - glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); + glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - else if ( shape == Tile::SHAPE_CROSS_TEXTURE ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateCrossTexture( tile, data, -0.5f, -0.5f, -0.5f, 1 ); - t->end(); - } - else if (shape == Tile::SHAPE_STEM) - { - t->begin(); - t->normal(0, -1, 0); - tile->updateDefaultShape(); - tesselateStemTexture(tile, data, tileShapeY1, -0.5f, -0.5f, -0.5f); - t->end(); - } - else if (shape == Tile::SHAPE_LILYPAD) - { + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_CROSS_TEXTURE) { + t->begin(); + t->normal(0, -1, 0); + tesselateCrossTexture(tile, data, -0.5f, -0.5f, -0.5f, 1); + t->end(); + } else if (shape == Tile::SHAPE_STEM) { + t->begin(); + t->normal(0, -1, 0); + tile->updateDefaultShape(); + tesselateStemTexture(tile, data, tileShapeY1, -0.5f, -0.5f, -0.5f); + t->end(); + } else if (shape == Tile::SHAPE_LILYPAD) { t->begin(); t->normal(0, -1, 0); tile->updateDefaultShape(); t->end(); - } - else if ( shape == Tile::SHAPE_CACTUS ) - { - tile->updateDefaultShape(); - glTranslatef( -0.5f, -0.5f, -0.5f ); - float s = 1 / 16.0f; - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); + } else if (shape == Tile::SHAPE_CACTUS) { + tile->updateDefaultShape(); + glTranslatef(-0.5f, -0.5f, -0.5f); + float s = 1 / 16.0f; + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - t->addOffset( 0, 0, s ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->addOffset( 0, 0, -s ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + t->addOffset(0, 0, s); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->addOffset(0, 0, -s); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - t->addOffset( 0, 0, -s ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->addOffset( 0, 0, s ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + t->addOffset(0, 0, -s); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->addOffset(0, 0, s); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - t->addOffset( s, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->addOffset( -s, 0, 0 ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + t->addOffset(s, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->addOffset(-s, 0, 0); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - t->addOffset( -s, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->addOffset( s, 0, 0 ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + t->addOffset(-s, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->addOffset(s, 0, 0); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - else if (shape == Tile::SHAPE_ENTITYTILE_ANIMATED) - { - glRotatef(90, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); - EntityTileRenderer::instance->render(tile, data, brightness, fAlpha, setColor, useCompiled); - glEnable(GL_RESCALE_NORMAL); - } - else if ( shape == Tile::SHAPE_ROWS ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateRowTexture( tile, data, -0.5f, -0.5f, -0.5f ); - t->end(); - } - else if ( shape == Tile::SHAPE_TORCH ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateTorch( tile, -0.5f, -0.5f, -0.5f, 0, 0, 0 ); - t->end(); - } - else if ( shape == Tile::SHAPE_STAIRS ) - { - for ( int i = 0; i < 2; i++ ) - { - if ( i == 0 ) setShape( 0, 0, 0, 1, 1, 0.5f ); - if ( i == 1 ) setShape( 0, 0, 0.5f, 1, 0.5f, 1 ); + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_ENTITYTILE_ANIMATED) { + glRotatef(90, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); + EntityTileRenderer::instance->render(tile, data, brightness, fAlpha, + setColor, useCompiled); + glEnable(GL_RESCALE_NORMAL); + } else if (shape == Tile::SHAPE_ROWS) { + t->begin(); + t->normal(0, -1, 0); + tesselateRowTexture(tile, data, -0.5f, -0.5f, -0.5f); + t->end(); + } else if (shape == Tile::SHAPE_TORCH) { + t->begin(); + t->normal(0, -1, 0); + tesselateTorch(tile, -0.5f, -0.5f, -0.5f, 0, 0, 0); + t->end(); + } else if (shape == Tile::SHAPE_STAIRS) { + for (int i = 0; i < 2; i++) { + if (i == 0) setShape(0, 0, 0, 1, 1, 0.5f); + if (i == 1) setShape(0, 0, 0.5f, 1, 0.5f, 1); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - } - else if (shape == Tile::SHAPE_EGG) - { + glTranslatef(0.5f, 0.5f, 0.5f); + } + } else if (shape == Tile::SHAPE_EGG) { int y0 = 0; glTranslatef(-0.5f, -0.5f, -0.5f); t->begin(); - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int ww = 0; int hh = 1; if (i == 0) ww = 2; if (i == 1) ww = 3; if (i == 2) ww = 4; - if (i == 3) - { + if (i == 3) { ww = 5; hh = 2; } - if (i == 4) - { + if (i == 4) { ww = 6; hh = 3; } - if (i == 5) - { + if (i == 5) { ww = 7; hh = 5; } - if (i == 6) - { + if (i == 6) { ww = 6; hh = 2; } @@ -7444,73 +7358,72 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl y0 += hh; setShape(0.5f - w, yy0, 0.5f - w, 0.5f + w, yy1, 0.5f + w); t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, getTexture(tile,0)); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, getTexture(tile,1)); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, getTexture(tile,2)); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, getTexture(tile,3)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, getTexture(tile,4)); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, getTexture(tile,5)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); } t->end(); glTranslatef(0.5f, 0.5f, 0.5f); setShape(0, 0, 0, 1, 1, 1); - } - - else if ( shape == Tile::SHAPE_FENCE ) - { - for ( int i = 0; i < 4; i++ ) - { - float w = 2 / 16.0f; - if ( i == 0 ) setShape( 0.5f - w, 0, 0, 0.5f + w, 1, w * 2 ); - if ( i == 1 ) setShape( 0.5f - w, 0, 1 - w * 2, 0.5f + w, 1, 1 ); - w = 1 / 16.0f; - if ( i == 2 ) setShape( 0.5f - w, 1 - w * 3, -w * 2, 0.5f + w, 1 - w, 1 + w * 2 ); - if ( i == 3 ) setShape( 0.5f - w, 0.5f - w * 3, -w * 2, 0.5f + w, 0.5f - w, 1 + w * 2 ); - - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); - - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); - - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->end(); - - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->end(); - - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->end(); - - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->end(); - - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - setShape( 0, 0, 0, 1, 1, 1 ); } - else if (shape == Tile::SHAPE_FENCE_GATE) - { - for (int i = 0; i < 3; i++) - { + + else if (shape == Tile::SHAPE_FENCE) { + for (int i = 0; i < 4; i++) { + float w = 2 / 16.0f; + if (i == 0) setShape(0.5f - w, 0, 0, 0.5f + w, 1, w * 2); + if (i == 1) setShape(0.5f - w, 0, 1 - w * 2, 0.5f + w, 1, 1); + w = 1 / 16.0f; + if (i == 2) + setShape(0.5f - w, 1 - w * 3, -w * 2, 0.5f + w, 1 - w, + 1 + w * 2); + if (i == 3) + setShape(0.5f - w, 0.5f - w * 3, -w * 2, 0.5f + w, 0.5f - w, + 1 + w * 2); + + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); + + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); + + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->end(); + + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->end(); + + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->end(); + + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->end(); + + glTranslatef(0.5f, 0.5f, 0.5f); + } + setShape(0, 0, 0, 1, 1, 1); + } else if (shape == Tile::SHAPE_FENCE_GATE) { + for (int i = 0; i < 3; i++) { float w = 1 / 16.0f; if (i == 0) setShape(0.5f - w, .3f, 0, 0.5f + w, 1, w * 2); if (i == 1) setShape(0.5f - w, .3f, 1 - w * 2, 0.5f + w, 1, 1); @@ -7520,176 +7433,170 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glTranslatef(-0.5f, -0.5f, -0.5f); t->begin(); t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, getTexture(tile,0)); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); t->end(); t->begin(); t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, getTexture(tile,1)); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); t->end(); t->begin(); t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, getTexture(tile,2)); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); t->end(); t->begin(); t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, getTexture(tile,3)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); t->end(); t->begin(); t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, getTexture(tile,4)); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); t->end(); t->begin(); t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, getTexture(tile,5)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); t->end(); glTranslatef(0.5f, 0.5f, 0.5f); } - } - else if (shape == Tile::SHAPE_WALL) - { - for (int i = 0; i < 2; i++) - { - if (i == 0) setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - if (i == 1) setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); + } else if (shape == Tile::SHAPE_WALL) { + for (int i = 0; i < 2; i++) { + if (i == 0) + setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, + WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); + if (i == 1) + setShape(.5f - WallTile::POST_WIDTH, 0, + .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, + WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); - glTranslatef(-0.5f, -0.5f, -0.5f); - t->begin(); - t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, tile->getTexture(0, data)); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, tile->getTexture(0, data)); + t->end(); - t->begin(); - t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, tile->getTexture(1, data)); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, tile->getTexture(1, data)); + t->end(); - t->begin(); - t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, tile->getTexture(2, data)); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, tile->getTexture(2, data)); + t->end(); - t->begin(); - t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, tile->getTexture(3, data)); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, tile->getTexture(3, data)); + t->end(); - t->begin(); - t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, tile->getTexture(4, data)); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, tile->getTexture(4, data)); + t->end(); - t->begin(); - t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, tile->getTexture(5, data)); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, tile->getTexture(5, data)); + t->end(); - glTranslatef(0.5f, 0.5f, 0.5f); - } - setShape(0, 0, 0, 1, 1, 1); - } - else if (shape == Tile::SHAPE_ANVIL) - { - glTranslatef(-0.5f, -0.5f, -0.5f); - tesselateAnvilInWorld((AnvilTile *) tile, 0, 0, 0, data, true); - glTranslatef(0.5f, 0.5f, 0.5f); - } - else if ( shape == Tile::SHAPE_PORTAL_FRAME ) - { - // 4J added - setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); + glTranslatef(0.5f, 0.5f, 0.5f); + } + setShape(0, 0, 0, 1, 1, 1); + } else if (shape == Tile::SHAPE_ANVIL) { + glTranslatef(-0.5f, -0.5f, -0.5f); + tesselateAnvilInWorld((AnvilTile*)tile, 0, 0, 0, data, true); + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_PORTAL_FRAME) { + // 4J added + setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0, 0 ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1, 0)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2, 0)); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3, 0)); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4, 0 ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4, 0)); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5, 0 ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5, 0)); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); + glTranslatef(0.5f, 0.5f, 0.5f); - tile->updateDefaultShape(); - - } - t->setMipmapEnable( true ); // 4J added + tile->updateDefaultShape(); + } + t->setMipmapEnable(true); // 4J added } -bool TileRenderer::canRender( int renderShape ) -{ - if ( renderShape == Tile::SHAPE_BLOCK ) return true; - if ( renderShape == Tile::SHAPE_TREE ) return true; - if ( renderShape == Tile::SHAPE_QUARTZ) return true; - if ( renderShape == Tile::SHAPE_CACTUS ) return true; - if ( renderShape == Tile::SHAPE_STAIRS ) return true; - if ( renderShape == Tile::SHAPE_FENCE ) return true; - if ( renderShape == Tile::SHAPE_EGG) return true; - if ( renderShape == Tile::SHAPE_ENTITYTILE_ANIMATED) return true; - if ( renderShape == Tile::SHAPE_FENCE_GATE) return true; - if ( renderShape == Tile::SHAPE_PISTON_BASE ) return true; - if ( renderShape == Tile::SHAPE_PORTAL_FRAME ) return true; - if ( renderShape == Tile::SHAPE_WALL) return true; - if ( renderShape == Tile::SHAPE_ANVIL) return true; - return false; +bool TileRenderer::canRender(int renderShape) { + if (renderShape == Tile::SHAPE_BLOCK) return true; + if (renderShape == Tile::SHAPE_TREE) return true; + if (renderShape == Tile::SHAPE_QUARTZ) return true; + if (renderShape == Tile::SHAPE_CACTUS) return true; + if (renderShape == Tile::SHAPE_STAIRS) return true; + if (renderShape == Tile::SHAPE_FENCE) return true; + if (renderShape == Tile::SHAPE_EGG) return true; + if (renderShape == Tile::SHAPE_ENTITYTILE_ANIMATED) return true; + if (renderShape == Tile::SHAPE_FENCE_GATE) return true; + if (renderShape == Tile::SHAPE_PISTON_BASE) return true; + if (renderShape == Tile::SHAPE_PORTAL_FRAME) return true; + if (renderShape == Tile::SHAPE_WALL) return true; + if (renderShape == Tile::SHAPE_ANVIL) return true; + return false; } -Icon *TileRenderer::getTexture(Tile *tile, LevelSource *level, int x, int y, int z, int face) -{ - return getTextureOrMissing(tile->getTexture(level, x, y, z, face)); +Icon* TileRenderer::getTexture(Tile* tile, LevelSource* level, int x, int y, + int z, int face) { + return getTextureOrMissing(tile->getTexture(level, x, y, z, face)); } -Icon *TileRenderer::getTexture(Tile *tile, int face, int data) -{ - return getTextureOrMissing(tile->getTexture(face, data)); +Icon* TileRenderer::getTexture(Tile* tile, int face, int data) { + return getTextureOrMissing(tile->getTexture(face, data)); } -Icon *TileRenderer::getTexture(Tile *tile, int face) -{ - return getTextureOrMissing(tile->getTexture(face)); +Icon* TileRenderer::getTexture(Tile* tile, int face) { + return getTextureOrMissing(tile->getTexture(face)); } -Icon *TileRenderer::getTexture(Tile *tile) -{ - return getTextureOrMissing(tile->getTexture(Facing::UP)); +Icon* TileRenderer::getTexture(Tile* tile) { + return getTextureOrMissing(tile->getTexture(Facing::UP)); } -Icon *TileRenderer::getTextureOrMissing(Icon *icon) -{ - if (icon == NULL) return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); +Icon* TileRenderer::getTextureOrMissing(Icon* icon) { + if (icon == NULL) + return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Pass on the Alpha Cut out flag to the tesselator - Tesselator* t = Tesselator::getInstance(); - t->setAlphaCutOut( icon->getFlags() & Icon::IS_ALPHA_CUT_OUT ); + // AP - alpha cut out is expensive on vita. Pass on the Alpha Cut out flag + // to the tesselator + Tesselator* t = Tesselator::getInstance(); + t->setAlphaCutOut(icon->getFlags() & Icon::IS_ALPHA_CUT_OUT); #endif - return icon; + return icon; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h index 34f926a7e..5f34f0989 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h @@ -24,188 +24,233 @@ class WallTile; class Icon; class Minecraft; -class TileRenderer -{ - friend class FallingTileRenderer; - private: - LevelSource* level; - Icon *fixedTexture; - bool xFlipTexture; - bool noCulling; - public : - static bool fancy; - bool setColor; - - float tileShapeX0; - float tileShapeX1; - float tileShapeY0; - float tileShapeY1; - float tileShapeZ0; - float tileShapeZ1; - bool fixedShape; - bool smoothShapeLighting; - Minecraft *minecraft; - ///////////////////////////////////////// Data caching - std::unordered_map getLightColorCount; - int xMin, yMin, zMin; - int xMin2, yMin2, zMin2; - int getLightColor( Tile *tt, LevelSource *level, int x, int y, int z); - float getShadeBrightness( Tile *tt, LevelSource *level, int x, int y, int z); - bool isTranslucentAt( LevelSource *level, int x, int y, int z); - unsigned int *cache; - unsigned char *tileIds; - static const unsigned int cache_getLightColor_valid = 0x80000000; - static const unsigned int cache_isTranslucentAt_valid = 0x40000000; - static const unsigned int cache_isSolidBlockingTile_valid = 0x20000000; - static const unsigned int cache_getLightColor_mask = 0x00f000f0; - static const unsigned int cache_isTranslucentAt_flag = 0x00000001; - static const unsigned int cache_isSolidBlockingTile_flag = 0x00000002; - ///////////////////////////////////////// - - void _init(); - -public: - TileRenderer( LevelSource* level, int xMin, int yMin, int zMin, unsigned char *tileIds ); - TileRenderer( LevelSource* level ); - TileRenderer(); - ~TileRenderer(); - void setFixedTexture( Icon *fixedTexture ); - void clearFixedTexture(); - bool hasFixedTexture(); - void setShape(float x0, float y0, float z0, float x1, float y1, float z1); - void setShape(Tile *tt); - void setFixedShape(float x0, float y0, float z0, float x1, float y1, float z1); - void clearFixedShape(); - - void tesselateInWorldFixedTexture( Tile* tile, int x, int y, int z, Icon *fixedTexture ); // 4J renamed to differentiate from tesselateInWorld - void tesselateInWorldNoCulling( Tile* tile, int x, int y, int z, int forceData = -1, - std::shared_ptr< TileEntity > forceEntity = std::shared_ptr< TileEntity >() ); // 4J added forceData, forceEntity param - bool tesselateInWorld( Tile* tt, int x, int y, int z, int forceData = -1, std::shared_ptr< TileEntity > forceEntity = - std::shared_ptr< TileEntity >() ); // 4J added forceData, forceEntity param - - private: - bool tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int x, int y, int z); - bool tesselateBedInWorld( Tile* tt, int x, int y, int z ); - bool tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int y, int z); - bool tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int z); - bool tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, int z); - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z); - -public: - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data); +class TileRenderer { + friend class FallingTileRenderer; private: - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data, bool render); - float tesselateAnvilPiece(AnvilTile *tt, int x, int y, int z, int part, float bottom, float width, float height, float length, bool rotate, bool render, int data); + LevelSource* level; + Icon* fixedTexture; + bool xFlipTexture; + bool noCulling; public: - bool tesselateTorchInWorld( Tile* tt, int x, int y, int z ); + static bool fancy; + bool setColor; + + float tileShapeX0; + float tileShapeX1; + float tileShapeY0; + float tileShapeY1; + float tileShapeZ0; + float tileShapeZ1; + bool fixedShape; + bool smoothShapeLighting; + Minecraft* minecraft; + ///////////////////////////////////////// Data caching + std::unordered_map getLightColorCount; + int xMin, yMin, zMin; + int xMin2, yMin2, zMin2; + int getLightColor(Tile* tt, LevelSource* level, int x, int y, int z); + float getShadeBrightness(Tile* tt, LevelSource* level, int x, int y, int z); + bool isTranslucentAt(LevelSource* level, int x, int y, int z); + unsigned int* cache; + unsigned char* tileIds; + static const unsigned int cache_getLightColor_valid = 0x80000000; + static const unsigned int cache_isTranslucentAt_valid = 0x40000000; + static const unsigned int cache_isSolidBlockingTile_valid = 0x20000000; + static const unsigned int cache_getLightColor_mask = 0x00f000f0; + static const unsigned int cache_isTranslucentAt_flag = 0x00000001; + static const unsigned int cache_isSolidBlockingTile_flag = 0x00000002; + ///////////////////////////////////////// + + void _init(); + +public: + TileRenderer(LevelSource* level, int xMin, int yMin, int zMin, + unsigned char* tileIds); + TileRenderer(LevelSource* level); + TileRenderer(); + ~TileRenderer(); + void setFixedTexture(Icon* fixedTexture); + void clearFixedTexture(); + bool hasFixedTexture(); + void setShape(float x0, float y0, float z0, float x1, float y1, float z1); + void setShape(Tile* tt); + void setFixedShape(float x0, float y0, float z0, float x1, float y1, + float z1); + void clearFixedShape(); + + void tesselateInWorldFixedTexture( + Tile* tile, int x, int y, int z, + Icon* + fixedTexture); // 4J renamed to differentiate from tesselateInWorld + void tesselateInWorldNoCulling( + Tile* tile, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + bool tesselateInWorld( + Tile* tt, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + private: - bool tesselateDiodeInWorld(DiodeTile *tt, int x, int y, int z); - void tesselateDiodeInWorld( DiodeTile* tt, int x, int y, int z, int dir ); - static const int FLIP_NONE = 0, FLIP_CW = 1, FLIP_CCW = 2, FLIP_180 = 3; + bool tesselateAirPortalFrameInWorld(TheEndPortalFrameTile* tt, int x, int y, + int z); + bool tesselateBedInWorld(Tile* tt, int x, int y, int z); + bool tesselateBrewingStandInWorld(BrewingStandTile* tt, int x, int y, + int z); + bool tesselateCauldronInWorld(CauldronTile* tt, int x, int y, int z); + bool tesselateFlowerPotInWorld(FlowerPotTile* tt, int x, int y, int z); + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z); - int northFlip; - int southFlip; - int eastFlip; - int westFlip; - int upFlip; - int downFlip; - public: - void tesselatePistonBaseForceExtended( Tile* tile, int x, int y, int z, int forceData = -1 ); // 4J added data param - private: - bool tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bool forceExtended, int forceData = -1 ); // 4J added data param - void renderPistonArmUpDown( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - void renderPistonArmNorthSouth( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - void renderPistonArmEastWest( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - public: - void tesselatePistonArmNoCulling( Tile* tile, int x, int y, int z, bool fullArm, int forceData = -1 ); // 4J added data param - private: - bool tesselatePistonExtensionInWorld( Tile* tt, int x, int y, int z, bool fullArm, int forceData = -1 ); // 4J added data param - public: - bool tesselateLeverInWorld( Tile* tt, int x, int y, int z ); - bool tesselateTripwireSourceInWorld(Tile *tt, int x, int y, int z); - bool tesselateTripwireInWorld(Tile *tt, int x, int y, int z); - bool tesselateFireInWorld( FireTile* tt, int x, int y, int z ); - bool tesselateDustInWorld( Tile* tt, int x, int y, int z ); - bool tesselateRailInWorld( RailTile* tt, int x, int y, int z ); - bool tesselateLadderInWorld( Tile* tt, int x, int y, int z ); - bool tesselateVineInWorld( Tile* tt, int x, int y, int z ); - bool tesselateThinFenceInWorld( ThinFenceTile* tt, int x, int y, int z ); - bool tesselateCrossInWorld( Tile* tt, int x, int y, int z ); - bool tesselateStemInWorld( Tile* _tt, int x, int y, int z ); - bool tesselateRowInWorld( Tile* tt, int x, int y, int z ); - void tesselateTorch( Tile* tt, float x, float y, float z, float xxa, float zza, int data ); - void tesselateCrossTexture( Tile* tt, int data, float x, float y, float z, float scale ); - void tesselateStemTexture( Tile* tt, int data, float h, float x, float y, float z ); - bool tesselateLilypadInWorld(Tile *tt, int x, int y, int z); - void tesselateStemDirTexture( StemTile* tt, int data, int dir, float h, float x, float y, float z ); +public: + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, int data); - void tesselateRowTexture( Tile* tt, int data, float x, float y, float z ); - bool tesselateWaterInWorld( Tile* tt, int x, int y, int z ); - private: - float getWaterHeight( int x, int y, int z, Material* m ); - public: - void renderBlock( Tile* tt, Level* level, int x, int y, int z ); - void renderBlock(Tile *tt, Level *level, int x, int y, int z, int data); - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z ); - // AP - added so we can cull earlier - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z, int faceFlags ); - bool tesselateTreeInWorld(Tile *tt, int x, int y, int z); - bool tesselateQuartzInWorld(Tile *tt, int x, int y, int z); - bool tesselateCocoaInWorld(CocoaTile *tt, int x, int y, int z); +private: + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, int data, + bool render); + float tesselateAnvilPiece(AnvilTile* tt, int x, int y, int z, int part, + float bottom, float width, float height, + float length, bool rotate, bool render, int data); - private: - bool applyAmbienceOcclusion; - float ll000, llx00, ll0y0, ll00z, llX00, ll0Y0, ll00Z; - float llxyz, llxy0, llxyZ, ll0yz, ll0yZ, llXyz, llXy0; - float llXyZ, llxYz, llxY0, llxYZ, ll0Yz, llXYz, llXY0; - float ll0YZ, llXYZ, llx0z, llX0z, llx0Z, llX0Z; - // 4J - brought forward changes from 1.8.2 - int ccx00, cc00z, cc0Y0, cc00Z; - int ccxyz, ccxy0, ccxyZ, cc0yz, cc0yZ, ccXyz, ccXy0; - int ccXyZ, ccxYz, ccxY0, ccxYZ, cc0Yz, ccXYz, ccXY0; - int cc0YZ, ccXYZ, ccx0z, ccX0z, ccx0Z, ccX0Z; - int blsmooth; - int tc1, tc2, tc3, tc4; // 4J - brought forward changes from 1.8.2 - float c1r, c2r, c3r, c4r; - float c1g, c2g, c3g, c4g; - float c1b, c2b, c3b, c4b; - bool llTrans0Yz, llTransXY0, llTransxY0, llTrans0YZ; - bool llTransx0z, llTransX0Z, llTransx0Z, llTransX0z; - bool llTrans0yz, llTransXy0, llTransxy0, llTrans0yZ; +public: + bool tesselateTorchInWorld(Tile* tt, int x, int y, int z); - public: - // 4J - brought forward changes from 1.8.2 - // AP - added faceFlags so we can cull earlier - bool tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* tt, int pX, int pY, int pZ, float pBaseRed, - float pBaseGreen, float pBaseBlue, int faceFlags ); - private: - int blend( int a, int b, int c, int def ); - int blend(int a, int b, int c, int d, double fa, double fb, double fc, double fd); - public: - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ); - bool tesselateCactusInWorld( Tile* tt, int x, int y, int z ); - bool tesselateCactusInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ); - bool tesselateFenceInWorld( FenceTile* tt, int x, int y, int z ); - bool tesselateWallInWorld(WallTile *tt, int x, int y, int z); - bool tesselateEggInWorld(EggTile *tt, int x, int y, int z); - bool tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, int z); - bool tesselateStairsInWorld( StairTile* tt, int x, int y, int z ); - bool tesselateDoorInWorld( Tile* tt, int x, int y, int z ); - void renderFaceUp( Tile* tt, double x, double y, double z, Icon *tex ); - void renderFaceDown( Tile* tt, double x, double y, double z, Icon *tex ); - void renderNorth( Tile* tt, double x, double y, double z, Icon *tex ); - void renderSouth( Tile* tt, double x, double y, double z, Icon *tex ); - void renderWest( Tile* tt, double x, double y, double z, Icon *tex ); - void renderEast( Tile* tt, double x, double y, double z, Icon *tex ); - void renderCube( Tile* tile, float alpha ); - void renderTile( Tile* tile, int data, float brightness, float fAlpha = 1.0f, bool useCompiled = true ); // 4J Added useCompiled - static bool canRender( int renderShape ); - Icon *getTexture(Tile *tile, LevelSource *level, int x, int y, int z, int face); +private: + bool tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z); + void tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z, int dir); + static const int FLIP_NONE = 0, FLIP_CW = 1, FLIP_CCW = 2, FLIP_180 = 3; - Icon *getTexture(Tile *tile, int face, int data); - Icon *getTexture(Tile *tile, int face); - Icon *getTexture(Tile *tile); - Icon *getTextureOrMissing(Icon *icon); + int northFlip; + int southFlip; + int eastFlip; + int westFlip; + int upFlip; + int downFlip; + +public: + void tesselatePistonBaseForceExtended( + Tile* tile, int x, int y, int z, + int forceData = -1); // 4J added data param +private: + bool tesselatePistonBaseInWorld(Tile* tt, int x, int y, int z, + bool forceExtended, + int forceData = -1); // 4J added data param + void renderPistonArmUpDown(float x0, float x1, float y0, float y1, float z0, + float z1, float br, float armLengthPixels); + void renderPistonArmNorthSouth(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels); + void renderPistonArmEastWest(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels); + +public: + void tesselatePistonArmNoCulling( + Tile* tile, int x, int y, int z, bool fullArm, + int forceData = -1); // 4J added data param +private: + bool tesselatePistonExtensionInWorld( + Tile* tt, int x, int y, int z, bool fullArm, + int forceData = -1); // 4J added data param +public: + bool tesselateLeverInWorld(Tile* tt, int x, int y, int z); + bool tesselateTripwireSourceInWorld(Tile* tt, int x, int y, int z); + bool tesselateTripwireInWorld(Tile* tt, int x, int y, int z); + bool tesselateFireInWorld(FireTile* tt, int x, int y, int z); + bool tesselateDustInWorld(Tile* tt, int x, int y, int z); + bool tesselateRailInWorld(RailTile* tt, int x, int y, int z); + bool tesselateLadderInWorld(Tile* tt, int x, int y, int z); + bool tesselateVineInWorld(Tile* tt, int x, int y, int z); + bool tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, int z); + bool tesselateCrossInWorld(Tile* tt, int x, int y, int z); + bool tesselateStemInWorld(Tile* _tt, int x, int y, int z); + bool tesselateRowInWorld(Tile* tt, int x, int y, int z); + void tesselateTorch(Tile* tt, float x, float y, float z, float xxa, + float zza, int data); + void tesselateCrossTexture(Tile* tt, int data, float x, float y, float z, + float scale); + void tesselateStemTexture(Tile* tt, int data, float h, float x, float y, + float z); + bool tesselateLilypadInWorld(Tile* tt, int x, int y, int z); + void tesselateStemDirTexture(StemTile* tt, int data, int dir, float h, + float x, float y, float z); + + void tesselateRowTexture(Tile* tt, int data, float x, float y, float z); + bool tesselateWaterInWorld(Tile* tt, int x, int y, int z); + +private: + float getWaterHeight(int x, int y, int z, Material* m); + +public: + void renderBlock(Tile* tt, Level* level, int x, int y, int z); + void renderBlock(Tile* tt, Level* level, int x, int y, int z, int data); + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z); + // AP - added so we can cull earlier + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, int faceFlags); + bool tesselateTreeInWorld(Tile* tt, int x, int y, int z); + bool tesselateQuartzInWorld(Tile* tt, int x, int y, int z); + bool tesselateCocoaInWorld(CocoaTile* tt, int x, int y, int z); + +private: + bool applyAmbienceOcclusion; + float ll000, llx00, ll0y0, ll00z, llX00, ll0Y0, ll00Z; + float llxyz, llxy0, llxyZ, ll0yz, ll0yZ, llXyz, llXy0; + float llXyZ, llxYz, llxY0, llxYZ, ll0Yz, llXYz, llXY0; + float ll0YZ, llXYZ, llx0z, llX0z, llx0Z, llX0Z; + // 4J - brought forward changes from 1.8.2 + int ccx00, cc00z, cc0Y0, cc00Z; + int ccxyz, ccxy0, ccxyZ, cc0yz, cc0yZ, ccXyz, ccXy0; + int ccXyZ, ccxYz, ccxY0, ccxYZ, cc0Yz, ccXYz, ccXY0; + int cc0YZ, ccXYZ, ccx0z, ccX0z, ccx0Z, ccX0Z; + int blsmooth; + int tc1, tc2, tc3, tc4; // 4J - brought forward changes from 1.8.2 + float c1r, c2r, c3r, c4r; + float c1g, c2g, c3g, c4g; + float c1b, c2b, c3b, c4b; + bool llTrans0Yz, llTransXY0, llTransxY0, llTrans0YZ; + bool llTransx0z, llTransX0Z, llTransx0Z, llTransX0z; + bool llTrans0yz, llTransXy0, llTransxy0, llTrans0yZ; + +public: + // 4J - brought forward changes from 1.8.2 + // AP - added faceFlags so we can cull earlier + bool tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, + float pBaseBlue, int faceFlags); + +private: + int blend(int a, int b, int c, int def); + int blend(int a, int b, int c, int d, double fa, double fb, double fc, + double fd); + +public: + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, float g, + float b); + bool tesselateCactusInWorld(Tile* tt, int x, int y, int z); + bool tesselateCactusInWorld(Tile* tt, int x, int y, int z, float r, float g, + float b); + bool tesselateFenceInWorld(FenceTile* tt, int x, int y, int z); + bool tesselateWallInWorld(WallTile* tt, int x, int y, int z); + bool tesselateEggInWorld(EggTile* tt, int x, int y, int z); + bool tesselateFenceGateInWorld(FenceGateTile* tt, int x, int y, int z); + bool tesselateStairsInWorld(StairTile* tt, int x, int y, int z); + bool tesselateDoorInWorld(Tile* tt, int x, int y, int z); + void renderFaceUp(Tile* tt, double x, double y, double z, Icon* tex); + void renderFaceDown(Tile* tt, double x, double y, double z, Icon* tex); + void renderNorth(Tile* tt, double x, double y, double z, Icon* tex); + void renderSouth(Tile* tt, double x, double y, double z, Icon* tex); + void renderWest(Tile* tt, double x, double y, double z, Icon* tex); + void renderEast(Tile* tt, double x, double y, double z, Icon* tex); + void renderCube(Tile* tile, float alpha); + void renderTile(Tile* tile, int data, float brightness, float fAlpha = 1.0f, + bool useCompiled = true); // 4J Added useCompiled + static bool canRender(int renderShape); + Icon* getTexture(Tile* tile, LevelSource* level, int x, int y, int z, + int face); + + Icon* getTexture(Tile* tile, int face, int data); + Icon* getTexture(Tile* tile, int face); + Icon* getTexture(Tile* tile); + Icon* getTextureOrMissing(Icon* icon); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp index 4bce1b017..0ceabb23a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp @@ -4,21 +4,20 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -TntRenderer::TntRenderer() -{ - tileRenderer = new TileRenderer(); - this->shadowRadius = 0.5f; +TntRenderer::TntRenderer() { + tileRenderer = new TileRenderer(); + this->shadowRadius = 0.5f; } -void TntRenderer::render(std::shared_ptr _tnt, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr tnt = std::dynamic_pointer_cast(_tnt); +void TntRenderer::render(std::shared_ptr _tnt, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr tnt = std::dynamic_pointer_cast(_tnt); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); - if (tnt->life - a + 1 < 10) - { + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); + if (tnt->life - a + 1 < 10) { float g = 1 - ((tnt->life - a + 1) / 10.0f); if (g < 0) g = 0; if (g > 1) g = 1; @@ -29,20 +28,22 @@ void TntRenderer::render(std::shared_ptr _tnt, double x, double y, doubl } float br = (1 - ((tnt->life - a + 1) / 100.0f)) * 0.8f; - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - // 4J - change brought forward from 1.8.2 - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1.0f : tnt->getBrightness(a); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + // 4J - change brought forward from 1.8.2 + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1.0f : tnt->getBrightness(a); tileRenderer->renderTile(Tile::tnt, 0, brightness); - if (tnt->life / 5 % 2 == 0) - { + if (tnt->life / 5 % 2 == 0) { glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); glColor4f(1, 1, 1, br); - tileRenderer->setColor = false; // 4J added so that renderTile doesn't set its own colour here + tileRenderer->setColor = false; // 4J added so that renderTile doesn't + // set its own colour here tileRenderer->renderTile(Tile::tnt, 0, 1); - tileRenderer->setColor = true; // 4J added so that renderTile doesn't set its own colour here + tileRenderer->setColor = true; // 4J added so that renderTile doesn't + // set its own colour here glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); glEnable(GL_LIGHTING); diff --git a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h index 1f70c8dae..64a679364 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "EntityRenderer.h" -class TntRenderer : public EntityRenderer -{ +class TntRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - TntRenderer(); - virtual void render(std::shared_ptr _tnt, double x, double y, double z, float rot, float a); + TntRenderer(); + virtual void render(std::shared_ptr _tnt, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp index 2ec228b68..046b41d7c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp @@ -5,65 +5,69 @@ #include "../Models/ModelPart.h" #include "VillagerGolemRenderer.h" -VillagerGolemRenderer::VillagerGolemRenderer() : MobRenderer(new VillagerGolemModel(), 0.5f) -{ - golemModel = (VillagerGolemModel *) model; +VillagerGolemRenderer::VillagerGolemRenderer() + : MobRenderer(new VillagerGolemModel(), 0.5f) { + golemModel = (VillagerGolemModel*)model; } -int VillagerGolemRenderer::prepareArmor(VillagerGolemModel *villagerGolem, int layer, float a) -{ - return -1; +int VillagerGolemRenderer::prepareArmor(VillagerGolemModel* villagerGolem, + int layer, float a) { + return -1; } -void VillagerGolemRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); +void VillagerGolemRenderer::render(std::shared_ptr mob, double x, + double y, double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void VillagerGolemRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::setupRotations(mob, bob, bodyRot, a); - if (mob->walkAnimSpeed < 0.01) return; +void VillagerGolemRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::setupRotations(mob, bob, bodyRot, a); + if (mob->walkAnimSpeed < 0.01) return; - float p = 13; - float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a) + 6; - float triangleWave = (abs(fmod(wp ,p) - p * 0.5f) - p * 0.25f) / (p * 0.25f); - glRotatef(6.5f * triangleWave, 0, 0, 1); + float p = 13; + float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a) + 6; + float triangleWave = + (abs(fmod(wp, p) - p * 0.5f) - p * 0.25f) / (p * 0.25f); + glRotatef(6.5f * triangleWave, 0, 0, 1); } -void VillagerGolemRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - if (mob->getOfferFlowerTick() == 0) return; +void VillagerGolemRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + if (mob->getOfferFlowerTick() == 0) return; - glEnable(GL_RESCALE_NORMAL); - glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + glPushMatrix(); - // dont ask me how I got the flower into his hand. - glRotatef(5 + 180 * golemModel->arm0->xRot / PI, 1, 0, 0); - glTranslatef(-11 / 16.0f, 20 / 16.0f, -15 / 16.0f); - glRotatef(90, 1, 0, 0); - float s = 0.8f; - glScalef(s, -s, s); + // dont ask me how I got the flower into his hand. + glRotatef(5 + 180 * golemModel->arm0->xRot / PI, 1, 0, 0); + glTranslatef(-11 / 16.0f, 20 / 16.0f, -15 / 16.0f); + glRotatef(90, 1, 0, 0); + float s = 0.8f; + glScalef(s, -s, s); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = mob->getLightColor(a); - int u = col % 65536; - int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + if (SharedConstants::TEXTURE_LIGHTING) { + int col = mob->getLightColor(a); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glColor4f(1, 1, 1, 1); - bindTexture(TN_TERRAIN); //"/terrain.png"); - tileRenderer->renderTile(Tile::rose, 0, 1); - glPopMatrix(); - glDisable(GL_RESCALE_NORMAL); + glColor4f(1, 1, 1, 1); + bindTexture(TN_TERRAIN); //"/terrain.png"); + tileRenderer->renderTile(Tile::rose, 0, 1); + glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h index 185e38d4c..52c200940 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h @@ -4,21 +4,22 @@ class VillagerGolemModel; -class VillagerGolemRenderer : public MobRenderer -{ +class VillagerGolemRenderer : public MobRenderer { private: - VillagerGolemModel *golemModel; + VillagerGolemModel* golemModel; public: - VillagerGolemRenderer(); + VillagerGolemRenderer(); protected: - int prepareArmor(VillagerGolemModel *villagerGolem, int layer, float a); + int prepareArmor(VillagerGolemModel* villagerGolem, int layer, float a); public: - void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr mob, double x, double y, double z, + float rot, float a); protected: - void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); - void additionalRendering(std::shared_ptr mob, float a); + void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, + float a); + void additionalRendering(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp index 3dc0037e3..ebba76fed 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp @@ -3,40 +3,37 @@ #include "../Models/VillagerModel.h" #include "VillagerRenderer.h" -VillagerRenderer::VillagerRenderer() : MobRenderer(new VillagerModel(0), 0.5f) -{ - villagerModel = (VillagerModel *) model; +VillagerRenderer::VillagerRenderer() : MobRenderer(new VillagerModel(0), 0.5f) { + villagerModel = (VillagerModel*)model; } -int VillagerRenderer::prepareArmor(std::shared_ptr villager, int layer, float a) -{ - return -1; +int VillagerRenderer::prepareArmor(std::shared_ptr villager, int layer, + float a) { + return -1; } -void VillagerRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); +void VillagerRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void VillagerRenderer::renderName(std::shared_ptr mob, double x, double y, double z) -{ +void VillagerRenderer::renderName(std::shared_ptr mob, double x, double y, + double z) {} + +void VillagerRenderer::additionalRendering(std::shared_ptr mob, float a) { + MobRenderer::additionalRendering(mob, a); } -void VillagerRenderer::additionalRendering(std::shared_ptr mob, float a) -{ - MobRenderer::additionalRendering(mob, a); -} - -void VillagerRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - float s = 15 / 16.0f; - if (mob->getAge() < 0) - { - s *= 0.5; - shadowRadius = 0.25f; - } else shadowRadius = 0.5f; - glScalef(s, s, s); +void VillagerRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float s = 15 / 16.0f; + if (mob->getAge() < 0) { + s *= 0.5; + shadowRadius = 0.25f; + } else + shadowRadius = 0.5f; + glScalef(s, s, s); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h index 1263f4850..90d2591b8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h @@ -4,22 +4,23 @@ class VillagerModel; -class VillagerRenderer : public MobRenderer -{ +class VillagerRenderer : public MobRenderer { protected: - VillagerModel *villagerModel; + VillagerModel* villagerModel; public: - VillagerRenderer(); + VillagerRenderer(); protected: - virtual int prepareArmor(std::shared_ptr villager, int layer, float a); + virtual int prepareArmor(std::shared_ptr villager, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); protected: - virtual void renderName(std::shared_ptr mob, double x, double y, double z); - virtual void additionalRendering(std::shared_ptr mob, float a); - virtual void scale(std::shared_ptr player, float a); + virtual void renderName(std::shared_ptr mob, double x, double y, + double z); + virtual void additionalRendering(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr player, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp index 26a92255c..12731b706 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp @@ -3,40 +3,41 @@ #include "../../Player/MultiPlayerLocalPlayer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -WolfRenderer::WolfRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - setArmor(armor); +WolfRenderer::WolfRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -float WolfRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +float WolfRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - return mob->getTailAngle(); + return mob->getTailAngle(); } -int WolfRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) -{ - if (mob->isInvisibleTo(Minecraft::GetInstance()->player)) return -1; // 4J-JEV: Todo, merge with java fix in '1.7.5'. +int WolfRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) { + if (mob->isInvisibleTo(Minecraft::GetInstance()->player)) + return -1; // 4J-JEV: Todo, merge with java fix in '1.7.5'. - std::shared_ptr wolf = std::dynamic_pointer_cast(mob); - if (layer == 0 && wolf->isWet()) - { - float brightness = wolf->getBrightness(a) * wolf->getWetShade(a); - bindTexture(wolf->getTexture()); - glColor3f(brightness, brightness, brightness); + std::shared_ptr wolf = std::dynamic_pointer_cast(mob); + if (layer == 0 && wolf->isWet()) { + float brightness = wolf->getBrightness(a) * wolf->getWetShade(a); + bindTexture(wolf->getTexture()); + glColor3f(brightness, brightness, brightness); - return 1; - } - if (layer == 1 && wolf->isTame()) - { - bindTexture(TN_MOB_WOLF_COLLAR); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : wolf->getBrightness(a); - int color = wolf->getCollarColor(); - glColor3f(brightness * Sheep::COLOR[color][0], brightness * Sheep::COLOR[color][1], brightness * Sheep::COLOR[color][2]); + return 1; + } + if (layer == 1 && wolf->isTame()) { + bindTexture(TN_MOB_WOLF_COLLAR); + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1 : wolf->getBrightness(a); + int color = wolf->getCollarColor(); + glColor3f(brightness * Sheep::COLOR[color][0], + brightness * Sheep::COLOR[color][1], + brightness * Sheep::COLOR[color][2]); - return 1; - } - return -1; + return 1; + } + return -1; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h index 218951c9e..45d5c264f 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h @@ -1,11 +1,11 @@ #pragma once #include "MobRenderer.h" -class WolfRenderer : public MobRenderer -{ +class WolfRenderer : public MobRenderer { public: - WolfRenderer(Model *model, Model *armor, float shadow); + WolfRenderer(Model* model, Model* armor, float shadow); + protected: virtual float getBob(std::shared_ptr _mob, float a); - virtual int prepareArmor(std::shared_ptr mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr mob, int layer, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp index 6831b2bd1..2fce366fb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp @@ -4,88 +4,81 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "ZombieRenderer.h" -ZombieRenderer::ZombieRenderer() : HumanoidMobRenderer(new ZombieModel(), .5f, 1.0f) -{ - modelVersion = 1; - defaultModel = humanoidModel; - villagerModel = new VillagerZombieModel(); +ZombieRenderer::ZombieRenderer() + : HumanoidMobRenderer(new ZombieModel(), .5f, 1.0f) { + modelVersion = 1; + defaultModel = humanoidModel; + villagerModel = new VillagerZombieModel(); - defaultArmorParts1 = NULL; - defaultArmorParts2 = NULL; + defaultArmorParts1 = NULL; + defaultArmorParts2 = NULL; - villagerArmorParts1 = NULL; - villagerArmorParts2 = NULL; + villagerArmorParts1 = NULL; + villagerArmorParts2 = NULL; - createArmorParts(); + createArmorParts(); } -void ZombieRenderer::createArmorParts() -{ - delete armorParts1; - delete armorParts2; +void ZombieRenderer::createArmorParts() { + delete armorParts1; + delete armorParts2; - armorParts1 = new ZombieModel(1.0f, true); - armorParts2 = new ZombieModel(0.5f, true); + armorParts1 = new ZombieModel(1.0f, true); + armorParts2 = new ZombieModel(0.5f, true); - defaultArmorParts1 = armorParts1; - defaultArmorParts2 = armorParts2; + defaultArmorParts1 = armorParts1; + defaultArmorParts2 = armorParts2; - villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); - villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); + villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); + villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); } -int ZombieRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - return HumanoidMobRenderer::prepareArmor(_mob, layer, a); +int ZombieRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + return HumanoidMobRenderer::prepareArmor(_mob, layer, a); } -void ZombieRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - HumanoidMobRenderer::render(_mob, x, y, z, rot, a); +void ZombieRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + HumanoidMobRenderer::render(_mob, x, y, z, rot, a); } -void ZombieRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - HumanoidMobRenderer::additionalRendering(_mob, a); +void ZombieRenderer::additionalRendering(std::shared_ptr _mob, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + HumanoidMobRenderer::additionalRendering(_mob, a); } -void ZombieRenderer::swapArmor(std::shared_ptr mob) -{ - if (mob->isVillager()) - { - //if (modelVersion != villagerModel->version()) - //{ - // villagerModel = new VillagerZombieModel(); - // modelVersion = villagerModel->version(); - // villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); - // villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); - //} - model = villagerModel; - armorParts1 = villagerArmorParts1; - armorParts2 = villagerArmorParts2; - } - else - { - model = defaultModel; - armorParts1 = defaultArmorParts1; - armorParts2 = defaultArmorParts2; - } +void ZombieRenderer::swapArmor(std::shared_ptr mob) { + if (mob->isVillager()) { + // if (modelVersion != villagerModel->version()) + //{ + // villagerModel = new VillagerZombieModel(); + // modelVersion = villagerModel->version(); + // villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); + // villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); + // } + model = villagerModel; + armorParts1 = villagerArmorParts1; + armorParts2 = villagerArmorParts2; + } else { + model = defaultModel; + armorParts1 = defaultArmorParts1; + armorParts2 = defaultArmorParts2; + } - humanoidModel = (HumanoidModel *) model; + humanoidModel = (HumanoidModel*)model; } -void ZombieRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isConverting()) - { - bodyRot += (float) (cos(mob->tickCount * 3.25) * PI * .25f); - } - HumanoidMobRenderer::setupRotations(mob, bob, bodyRot, a); +void ZombieRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + if (mob->isConverting()) { + bodyRot += (float)(cos(mob->tickCount * 3.25) * PI * .25f); + } + HumanoidMobRenderer::setupRotations(mob, bob, bodyRot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h index b727659a6..5ab79f053 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h @@ -5,37 +5,38 @@ class VillagerZombieModel; class Zombie; -class ZombieRenderer : public HumanoidMobRenderer -{ +class ZombieRenderer : public HumanoidMobRenderer { private: - HumanoidModel *defaultModel; - VillagerZombieModel *villagerModel; + HumanoidModel* defaultModel; + VillagerZombieModel* villagerModel; protected: - HumanoidModel *defaultArmorParts1; - HumanoidModel *defaultArmorParts2; - HumanoidModel *villagerArmorParts1; - HumanoidModel *villagerArmorParts2; + HumanoidModel* defaultArmorParts1; + HumanoidModel* defaultArmorParts2; + HumanoidModel* villagerArmorParts1; + HumanoidModel* villagerArmorParts2; private: - int modelVersion; + int modelVersion; public: - ZombieRenderer(); + ZombieRenderer(); protected: - void createArmorParts(); - int prepareArmor(std::shared_ptr _mob, int layer, float a); + void createArmorParts(); + int prepareArmor(std::shared_ptr _mob, int layer, float a); public: - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - void additionalRendering(std::shared_ptr _mob, float a); + void additionalRendering(std::shared_ptr _mob, float a); private: - void swapArmor(std::shared_ptr mob); + void swapArmor(std::shared_ptr mob); protected: - void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Frustum.cpp b/Minecraft.Client/Rendering/Frustum.cpp index c8d6655cc..1144a7d5f 100644 --- a/Minecraft.Client/Rendering/Frustum.cpp +++ b/Minecraft.Client/Rendering/Frustum.cpp @@ -2,39 +2,37 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "Frustum.h" -Frustum *Frustum::frustum = new Frustum(); +Frustum* Frustum::frustum = new Frustum(); -Frustum::Frustum() -{ - _proj = MemoryTracker::createFloatBuffer(16); - _modl = MemoryTracker::createFloatBuffer(16); - _clip = MemoryTracker::createFloatBuffer(16); +Frustum::Frustum() { + _proj = MemoryTracker::createFloatBuffer(16); + _modl = MemoryTracker::createFloatBuffer(16); + _clip = MemoryTracker::createFloatBuffer(16); } -Frustum::~Frustum() -{ - delete _proj; - delete _modl; - delete _clip; +Frustum::~Frustum() { + delete _proj; + delete _modl; + delete _clip; } - -FrustumData *Frustum::getFrustum() -{ - frustum->calculateFrustum(); +FrustumData* Frustum::getFrustum() { + frustum->calculateFrustum(); return frustum; } +///////////////////////////////// NORMALIZE PLANE +///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This normalizes a plane (A side) from a given frustum. +///// +///////////////////////////////// NORMALIZE PLANE +///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///// - ///// This normalizes a plane (A side) from a given frustum. - ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - -void Frustum::normalizePlane(float **frustum, int side) -{ - float magnitude = (float) sqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); +void Frustum::normalizePlane(float** frustum, int side) { + float magnitude = (float)sqrt(frustum[side][A] * frustum[side][A] + + frustum[side][B] * frustum[side][B] + + frustum[side][C] * frustum[side][C]); // Then we divide the plane's values by it's magnitude. // This makes it easier to work with. @@ -44,8 +42,7 @@ void Frustum::normalizePlane(float **frustum, int side) frustum[side][D] /= magnitude; } -void Frustum::calculateFrustum() -{ +void Frustum::calculateFrustum() { _proj->clear(); _modl->clear(); _clip->clear(); @@ -58,34 +55,51 @@ void Frustum::calculateFrustum() // By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix. // This also stores it in an array of [16]. glGetFloat(GL_MODELVIEW_MATRIX, _modl); - + _proj->flip()->limit(16); _proj->get(&proj); _modl->flip()->limit(16); _modl->get(&modl); - // Now that we have our modelview and projection matrix, if we combine these 2 matrices, - // it will give us our clipping planes. To combine 2 matrices, we multiply them. + // Now that we have our modelview and projection matrix, if we combine these + // 2 matrices, it will give us our clipping planes. To combine 2 matrices, + // we multiply them. - clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12]; - clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13]; - clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14]; - clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15]; + clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + + modl[3] * proj[12]; + clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + + modl[3] * proj[13]; + clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + + modl[3] * proj[14]; + clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + + modl[3] * proj[15]; - clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12]; - clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13]; - clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14]; - clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15]; + clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + + modl[7] * proj[12]; + clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + + modl[7] * proj[13]; + clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + + modl[7] * proj[14]; + clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + + modl[7] * proj[15]; - clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12]; - clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13]; - clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14]; - clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15]; + clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + + modl[11] * proj[12]; + clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + + modl[11] * proj[13]; + clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + + modl[11] * proj[14]; + clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + + modl[11] * proj[15]; - clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12]; - clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13]; - clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14]; - clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15]; + clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + + modl[15] * proj[12]; + clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + + modl[15] * proj[13]; + clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + + modl[15] * proj[14]; + clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + + modl[15] * proj[15]; // Now we actually want to get the sides of the frustum. To do this we take // the clipping planes we received above and extract the sides from them. diff --git a/Minecraft.Client/Rendering/Frustum.h b/Minecraft.Client/Rendering/Frustum.h index 4ce37160f..a556a919c 100644 --- a/Minecraft.Client/Rendering/Frustum.h +++ b/Minecraft.Client/Rendering/Frustum.h @@ -1,29 +1,30 @@ #pragma once #include "FrustumData.h" -class Frustum : public FrustumData -{ +class Frustum : public FrustumData { private: - static Frustum *frustum; + static Frustum* frustum; public: - static FrustumData *getFrustum(); + static FrustumData* getFrustum(); - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///////////////////////////////// NORMALIZE PLANE + ///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This normalizes a plane (A side) from a given frustum. ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///////////////////////////////// NORMALIZE PLANE + ///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* private: - void normalizePlane(float **frustum, int side); + void normalizePlane(float** frustum, int side); - FloatBuffer *_proj; - FloatBuffer *_modl; - FloatBuffer *_clip; + FloatBuffer* _proj; + FloatBuffer* _modl; + FloatBuffer* _clip; void calculateFrustum(); - Frustum(); - ~Frustum(); + Frustum(); + ~Frustum(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumCuller.cpp b/Minecraft.Client/Rendering/FrustumCuller.cpp index d842e3cf3..e2ab78c7f 100644 --- a/Minecraft.Client/Rendering/FrustumCuller.cpp +++ b/Minecraft.Client/Rendering/FrustumCuller.cpp @@ -1,29 +1,26 @@ #include "../Platform/stdafx.h" #include "FrustumCuller.h" -FrustumCuller::FrustumCuller() -{ - frustum = Frustum::getFrustum(); -} +FrustumCuller::FrustumCuller() { frustum = Frustum::getFrustum(); } -void FrustumCuller::prepare(double xOff, double yOff, double zOff) -{ +void FrustumCuller::prepare(double xOff, double yOff, double zOff) { this->xOff = xOff; this->yOff = yOff; this->zOff = zOff; } -bool FrustumCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return frustum->cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); +bool FrustumCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + return frustum->cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, + x1 - xOff, y1 - yOff, z1 - zOff); } -bool FrustumCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return frustum->cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); +bool FrustumCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + return frustum->cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, + y1 - yOff, z1 - zOff); } -bool FrustumCuller::isVisible(AABB *bb) -{ - return cubeInFrustum(bb->x0, bb->y0, bb->z0, bb->x1, bb->y1, bb->z1); +bool FrustumCuller::isVisible(AABB* bb) { + return cubeInFrustum(bb->x0, bb->y0, bb->z0, bb->x1, bb->y1, bb->z1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumCuller.h b/Minecraft.Client/Rendering/FrustumCuller.h index 5197ef10d..a14814c1d 100644 --- a/Minecraft.Client/Rendering/FrustumCuller.h +++ b/Minecraft.Client/Rendering/FrustumCuller.h @@ -3,15 +3,17 @@ #include "Culling/Culler.h" #include "Frustum.h" -class FrustumCuller : public Culler -{ +class FrustumCuller : public Culler { public: - FrustumData *frustum; - FrustumCuller(); - double xOff, yOff, zOff; + FrustumData* frustum; + FrustumCuller(); + double xOff, yOff, zOff; + public: - virtual void prepare(double xOff, double yOff, double zOff); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool isVisible(AABB *bb); + virtual void prepare(double xOff, double yOff, double zOff); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool isVisible(AABB* bb); }; diff --git a/Minecraft.Client/Rendering/FrustumData.cpp b/Minecraft.Client/Rendering/FrustumData.cpp index 525785fae..a5f11b768 100644 --- a/Minecraft.Client/Rendering/FrustumData.cpp +++ b/Minecraft.Client/Rendering/FrustumData.cpp @@ -1,90 +1,131 @@ #include "../Platform/stdafx.h" -#include "FrustumData.h" +#include "FrustumData.h" float** m_Frustum; - -FrustumData::FrustumData() -{ - m_Frustum = new float *[16]; - for( int i = 0; i < 16; i++ ) m_Frustum[i] = new float[16]; - proj = floatArray( 16 ); - modl = floatArray( 16 ); - clip = floatArray( 16 ); +FrustumData::FrustumData() { + m_Frustum = new float*[16]; + for (int i = 0; i < 16; i++) m_Frustum[i] = new float[16]; + proj = floatArray(16); + modl = floatArray(16); + clip = floatArray(16); } -FrustumData::~FrustumData() -{ - delete[] proj.data; - delete[] modl.data; - delete[] clip.data; - for( int i = 0; i < 16; i++ ) delete[] m_Frustum[i]; - delete[] m_Frustum; +FrustumData::~FrustumData() { + delete[] proj.data; + delete[] modl.data; + delete[] clip.data; + for (int i = 0; i < 16; i++) delete[] m_Frustum[i]; + delete[] m_Frustum; } -bool FrustumData::pointInFrustum(float x, float y, float z) -{ - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= 0) - { +bool FrustumData::pointInFrustum(float x, float y, float z) { + for (int i = 0; i < 6; i++) { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + + m_Frustum[i][D] <= + 0) { return false; } } - + return true; } -bool FrustumData::sphereInFrustum(float x, float y, float z, float radius) -{ - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= -radius) - { - return false; - } - } - - return true; -} - -bool FrustumData::cubeFullyInFrustum(double x1, double y1, double z1, double x2, double y2, double z2) -{ - for (int i = 0; i < 6; i++) - { - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; +bool FrustumData::sphereInFrustum(float x, float y, float z, float radius) { + for (int i = 0; i < 6; i++) { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + + m_Frustum[i][D] <= + -radius) { + return false; + } } - + return true; } -bool FrustumData::cubeInFrustum(double x1, double y1, double z1, double x2, double y2, double z2) -{ - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - +bool FrustumData::cubeFullyInFrustum(double x1, double y1, double z1, double x2, + double y2, double z2) { + for (int i = 0; i < 6; i++) { + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0)) + return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0)) + return false; + } + + return true; +} + +bool FrustumData::cubeInFrustum(double x1, double y1, double z1, double x2, + double y2, double z2) { + for (int i = 0; i < 6; i++) { + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0) + continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > + 0) + continue; + return false; } - + return true; } -bool FrustumData::isVisible(AABB *aabb) -{ - return cubeInFrustum(aabb->x0, aabb->y0, aabb->z0, aabb->x1, aabb->y1, aabb->z1); +bool FrustumData::isVisible(AABB* aabb) { + return cubeInFrustum(aabb->x0, aabb->y0, aabb->z0, aabb->x1, aabb->y1, + aabb->z1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumData.h b/Minecraft.Client/Rendering/FrustumData.h index 314e0b111..1a61d4ae3 100644 --- a/Minecraft.Client/Rendering/FrustumData.h +++ b/Minecraft.Client/Rendering/FrustumData.h @@ -1,35 +1,36 @@ #pragma once #include "../../Minecraft.World/Util/AABB.h" -class FrustumData -{ +class FrustumData { public: - //enum FrustumSide - static const int RIGHT = 0; // The RIGHT side of the frustum - static const int LEFT = 1; // The LEFT side of the frustum - static const int BOTTOM = 2; // The BOTTOM side of the frustum - static const int TOP = 3; // The TOP side of the frustum - static const int BACK = 4; // The BACK side of the frustum - static const int FRONT = 5; // The FRONT side of the frustum + // enum FrustumSide + static const int RIGHT = 0; // The RIGHT side of the frustum + static const int LEFT = 1; // The LEFT side of the frustum + static const int BOTTOM = 2; // The BOTTOM side of the frustum + static const int TOP = 3; // The TOP side of the frustum + static const int BACK = 4; // The BACK side of the frustum + static const int FRONT = 5; // The FRONT side of the frustum // Like above, instead of saying a number for the ABC and D of the plane, we // want to be more descriptive. - static const int A = 0; // The X value of the plane's normal - static const int B = 1; // The Y value of the plane's normal - static const int C = 2; // The Z value of the plane's normal - static const int D = 3; // The distance the plane is from the origin + static const int A = 0; // The X value of the plane's normal + static const int B = 1; // The Y value of the plane's normal + static const int C = 2; // The Z value of the plane's normal + static const int D = 3; // The distance the plane is from the origin float** m_Frustum; floatArray proj; floatArray modl; floatArray clip; - FrustumData(); - ~FrustumData(); + FrustumData(); + ~FrustumData(); bool pointInFrustum(float x, float y, float z); bool sphereInFrustum(float x, float y, float z, float radius); - bool cubeFullyInFrustum(double x1, double y1, double z1, double x2, double y2, double z2); - bool cubeInFrustum(double x1, double y1, double z1, double x2, double y2, double z2); - bool isVisible(AABB *aabb); + bool cubeFullyInFrustum(double x1, double y1, double z1, double x2, + double y2, double z2); + bool cubeInFrustum(double x1, double y1, double z1, double x2, double y2, + double z2); + bool isVisible(AABB* aabb); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/GameRenderer.cpp b/Minecraft.Client/Rendering/GameRenderer.cpp index 9f45d145c..6b0d32724 100644 --- a/Minecraft.Client/Rendering/GameRenderer.cpp +++ b/Minecraft.Client/Rendering/GameRenderer.cpp @@ -53,664 +53,635 @@ bool GameRenderer::anaglyph3d = false; int GameRenderer::anaglyphPass = 0; #ifdef MULTITHREAD_ENABLE -C4JThread* GameRenderer::m_updateThread; +C4JThread* GameRenderer::m_updateThread; C4JThread::EventArray* GameRenderer::m_updateEvents; bool GameRenderer::nearThingsToDo = false; bool GameRenderer::updateRunning = false; -std::vector GameRenderer::m_deleteStackByte; -std::vector GameRenderer::m_deleteStackSparseLightStorage; -std::vector GameRenderer::m_deleteStackCompressedTileStorage; -std::vector GameRenderer::m_deleteStackSparseDataStorage; +std::vector GameRenderer::m_deleteStackByte; +std::vector GameRenderer::m_deleteStackSparseLightStorage; +std::vector + GameRenderer::m_deleteStackCompressedTileStorage; +std::vector GameRenderer::m_deleteStackSparseDataStorage; #endif CRITICAL_SECTION GameRenderer::m_csDeleteStack; -GameRenderer::GameRenderer(Minecraft *mc) -{ - // 4J - added this block of initialisers - renderDistance = 0; - _tick = 0; - hovered = nullptr; - thirdDistance = 4; - thirdDistanceO = 4; - thirdRotation = 0; - thirdRotationO = 0; - thirdTilt = 0; - thirdTiltO = 0; +GameRenderer::GameRenderer(Minecraft* mc) { + // 4J - added this block of initialisers + renderDistance = 0; + _tick = 0; + hovered = nullptr; + thirdDistance = 4; + thirdDistanceO = 4; + thirdRotation = 0; + thirdRotationO = 0; + thirdTilt = 0; + thirdTiltO = 0; accumulatedSmoothXO = 0; - accumulatedSmoothYO = 0; + accumulatedSmoothYO = 0; tickSmoothXO = 0; - tickSmoothYO = 0; - lastTickA = 0; + tickSmoothYO = 0; + lastTickA = 0; - cameraPos = Vec3::newPermanent(0.0f,0.0f,0.0f); + cameraPos = Vec3::newPermanent(0.0f, 0.0f, 0.0f); - fovOffset = 0; - fovOffsetO = 0; - cameraRoll = 0; - cameraRollO = 0; - for( int i = 0; i < 4; i++ ) - { - fov[i] = 0.0f; - oFov[i] = 0.0f; - tFov[i] = 0.0f; - } - isInClouds = false; - zoom = 1; - zoom_x = 0; - zoom_y = 0; - rainXa = NULL; - rainZa = NULL; - lastActiveTime = Minecraft::currentTimeMillis(); - lastNsTime = 0; - random = new Random(); - rainSoundTime = 0; - xMod = 0; - yMod = 0; - lb = MemoryTracker::createFloatBuffer(16); - fr = 0.0f; - fg = 0.0f; - fb = 0.0f; - fogBrO = 0.0f; - fogBr = 0.0f; - cameraFlip = 0; - _updateLightTexture = false; - blr = 0.0f; - blrt = 0.0f; - blg = 0.0f; - blgt = 0.0f; + fovOffset = 0; + fovOffsetO = 0; + cameraRoll = 0; + cameraRollO = 0; + for (int i = 0; i < 4; i++) { + fov[i] = 0.0f; + oFov[i] = 0.0f; + tFov[i] = 0.0f; + } + isInClouds = false; + zoom = 1; + zoom_x = 0; + zoom_y = 0; + rainXa = NULL; + rainZa = NULL; + lastActiveTime = Minecraft::currentTimeMillis(); + lastNsTime = 0; + random = new Random(); + rainSoundTime = 0; + xMod = 0; + yMod = 0; + lb = MemoryTracker::createFloatBuffer(16); + fr = 0.0f; + fg = 0.0f; + fb = 0.0f; + fogBrO = 0.0f; + fogBr = 0.0f; + cameraFlip = 0; + _updateLightTexture = false; + blr = 0.0f; + blrt = 0.0f; + blg = 0.0f; + blgt = 0.0f; + m_fov = 70.0f; - m_fov=70.0f; + // 4J Stu - Init these so they are setup before the tick + for (int i = 0; i < 4; i++) { + fov[i] = oFov[i] = 1.0f; + } - // 4J Stu - Init these so they are setup before the tick - for( int i = 0; i < 4; i++ ) - { - fov[i] = oFov[i] = 1.0f; - } + this->mc = mc; + itemInHandRenderer = NULL; - this->mc = mc; - itemInHandRenderer = NULL; + // 4J-PB - set up the local players iteminhand renderers here - needs to be + // done with lighting enabled so that the render geometry gets compiled + // correctly + glEnable(GL_LIGHTING); + mc->localitemInHandRenderers[0] = + new ItemInHandRenderer(mc); // itemInHandRenderer; + mc->localitemInHandRenderers[1] = new ItemInHandRenderer(mc); + mc->localitemInHandRenderers[2] = new ItemInHandRenderer(mc); + mc->localitemInHandRenderers[3] = new ItemInHandRenderer(mc); + glDisable(GL_LIGHTING); - // 4J-PB - set up the local players iteminhand renderers here - needs to be done with lighting enabled so that the render geometry gets compiled correctly - glEnable(GL_LIGHTING); - mc->localitemInHandRenderers[0] = new ItemInHandRenderer(mc);//itemInHandRenderer; - mc->localitemInHandRenderers[1] = new ItemInHandRenderer(mc); - mc->localitemInHandRenderers[2] = new ItemInHandRenderer(mc); - mc->localitemInHandRenderers[3] = new ItemInHandRenderer(mc); - glDisable(GL_LIGHTING); - - // 4J - changes brought forward from 1.8.2 - BufferedImage *img = new BufferedImage(16, 16, BufferedImage::TYPE_INT_RGB); - for( int i = 0; i < NUM_LIGHT_TEXTURES; i++ ) - { - lightTexture[i] = mc->textures->getTexture(img); // 4J - changed to one light texture per level to support split screen - } - delete img; + // 4J - changes brought forward from 1.8.2 + BufferedImage* img = new BufferedImage(16, 16, BufferedImage::TYPE_INT_RGB); + for (int i = 0; i < NUM_LIGHT_TEXTURES; i++) { + lightTexture[i] = + mc->textures->getTexture(img); // 4J - changed to one light texture + // per level to support split screen + } + delete img; #ifdef __PS3__ - // we're using the RSX now to upload textures to vram, so we need the main ram textures allocated from io space - for(int i=0;iSet(eUpdateEventIsFinished); + m_updateEvents = new C4JThread::EventArray( + eUpdateEventCount, C4JThread::EventArray::e_modeAutoClear); + m_updateEvents->Set(eUpdateEventIsFinished); - InitializeCriticalSection(&m_csDeleteStack); - m_updateThread = new C4JThread(runUpdate, NULL, "Chunk update"); + InitializeCriticalSection(&m_csDeleteStack); + m_updateThread = new C4JThread(runUpdate, NULL, "Chunk update"); #ifdef __PS3__ - m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); -#endif// __PS3__ - m_updateThread->SetProcessor(CPU_CORE_CHUNK_UPDATE); - m_updateThread->Run(); + m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); +#endif // __PS3__ + m_updateThread->SetProcessor(CPU_CORE_CHUNK_UPDATE); + m_updateThread->Run(); #endif } // 4J Stu Added to go with 1.8.2 change -GameRenderer::~GameRenderer() -{ - if(rainXa != NULL) delete [] rainXa; - if(rainZa != NULL) delete [] rainZa; +GameRenderer::~GameRenderer() { + if (rainXa != NULL) delete[] rainXa; + if (rainZa != NULL) delete[] rainZa; } -void GameRenderer::tick(bool first) // 4J - add bFirst -{ - tickFov(); - tickLightTexture(); // 4J - change brought forward from 1.8.2 - fogBrO = fogBr; - thirdDistanceO = thirdDistance; - thirdRotationO = thirdRotation; - thirdTiltO = thirdTilt; - fovOffsetO = fovOffset; - cameraRollO = cameraRoll; +void GameRenderer::tick(bool first) // 4J - add bFirst +{ + tickFov(); + tickLightTexture(); // 4J - change brought forward from 1.8.2 + fogBrO = fogBr; + thirdDistanceO = thirdDistance; + thirdRotationO = thirdRotation; + thirdTiltO = thirdTilt; + fovOffsetO = fovOffset; + cameraRollO = cameraRoll; - if (ClientConstants::DEADMAU5_CAMERA_CHEATS) - { - if (mc->screen == NULL) - { - float distanceDelta = 0; - float rotationDelta = 0; - float tiltDelta = 0; - float rollDelta = 0; + if (ClientConstants::DEADMAU5_CAMERA_CHEATS) { + if (mc->screen == NULL) { + float distanceDelta = 0; + float rotationDelta = 0; + float tiltDelta = 0; + float rollDelta = 0; - if (Keyboard::isKeyDown(Keyboard::KEY_U)) - { - distanceDelta -= .3f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_O)) - { - distanceDelta += .3f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_J)) - { - rotationDelta += 8.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_L)) - { - rotationDelta -= 8.0f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_I)) - { - tiltDelta += 6.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_K)) - { - tiltDelta -= 6.0f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_Y) && Keyboard::isKeyDown(Keyboard::KEY_H)) - { - fovOffset = 0; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_Y)) - { - fovOffset -= 3.0f; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_H)) - { - fovOffset += 3.0f; - } - if (Keyboard::isKeyDown(Keyboard::KEY_N) && Keyboard::isKeyDown(Keyboard::KEY_M)) - { - cameraRoll = 0; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_N)) - { - rollDelta -= 8.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_M)) - { - rollDelta += 8.0f * mc->options->cameraSpeed; - } + if (Keyboard::isKeyDown(Keyboard::KEY_U)) { + distanceDelta -= .3f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_O)) { + distanceDelta += .3f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_J)) { + rotationDelta += 8.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_L)) { + rotationDelta -= 8.0f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_I)) { + tiltDelta += 6.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_K)) { + tiltDelta -= 6.0f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_Y) && + Keyboard::isKeyDown(Keyboard::KEY_H)) { + fovOffset = 0; + } else if (Keyboard::isKeyDown(Keyboard::KEY_Y)) { + fovOffset -= 3.0f; + } else if (Keyboard::isKeyDown(Keyboard::KEY_H)) { + fovOffset += 3.0f; + } + if (Keyboard::isKeyDown(Keyboard::KEY_N) && + Keyboard::isKeyDown(Keyboard::KEY_M)) { + cameraRoll = 0; + } else if (Keyboard::isKeyDown(Keyboard::KEY_N)) { + rollDelta -= 8.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_M)) { + rollDelta += 8.0f * mc->options->cameraSpeed; + } - if (mc->options->smoothCamera) - { - distanceDelta = smoothDistance.getNewDeltaValue(distanceDelta, .5f * mc->options->sensitivity); - rotationDelta = smoothRotation.getNewDeltaValue(rotationDelta, .5f * mc->options->sensitivity); - tiltDelta = smoothTilt.getNewDeltaValue(tiltDelta, .5f * mc->options->sensitivity); - rollDelta = smoothRoll.getNewDeltaValue(rollDelta, .5f * mc->options->sensitivity); - } - thirdDistance += distanceDelta; - thirdRotation += rotationDelta; - thirdTilt += tiltDelta; - cameraRoll += rollDelta; - } - } + if (mc->options->smoothCamera) { + distanceDelta = smoothDistance.getNewDeltaValue( + distanceDelta, .5f * mc->options->sensitivity); + rotationDelta = smoothRotation.getNewDeltaValue( + rotationDelta, .5f * mc->options->sensitivity); + tiltDelta = smoothTilt.getNewDeltaValue( + tiltDelta, .5f * mc->options->sensitivity); + rollDelta = smoothRoll.getNewDeltaValue( + rollDelta, .5f * mc->options->sensitivity); + } + thirdDistance += distanceDelta; + thirdRotation += rotationDelta; + thirdTilt += tiltDelta; + cameraRoll += rollDelta; + } + } - if (mc->options->smoothCamera) - { + if (mc->options->smoothCamera) { // update player view in tick() instead of render() to maintain -// camera movement regardless of FPS + // camera movement regardless of FPS float ss = mc->options->sensitivity * 0.6f + 0.2f; float sens = (ss * ss * ss) * 8; - tickSmoothXO = smoothTurnX.getNewDeltaValue(accumulatedSmoothXO, 0.05f * sens); - tickSmoothYO = smoothTurnY.getNewDeltaValue(accumulatedSmoothYO, 0.05f * sens); + tickSmoothXO = + smoothTurnX.getNewDeltaValue(accumulatedSmoothXO, 0.05f * sens); + tickSmoothYO = + smoothTurnY.getNewDeltaValue(accumulatedSmoothYO, 0.05f * sens); lastTickA = 0; accumulatedSmoothXO = 0; accumulatedSmoothYO = 0; } - if (mc->cameraTargetPlayer == NULL) - { - mc->cameraTargetPlayer = std::dynamic_pointer_cast(mc->player); - } + if (mc->cameraTargetPlayer == NULL) { + mc->cameraTargetPlayer = std::dynamic_pointer_cast(mc->player); + } - float brr = mc->level->getBrightness(Mth::floor(mc->cameraTargetPlayer->x), Mth::floor(mc->cameraTargetPlayer->y), Mth::floor(mc->cameraTargetPlayer->z)); - float whiteness = (3 - mc->options->viewDistance) / 3.0f; - float fogBrT = brr * (1 - whiteness) + whiteness; - fogBr += (fogBrT - fogBr) * 0.1f; + float brr = mc->level->getBrightness(Mth::floor(mc->cameraTargetPlayer->x), + Mth::floor(mc->cameraTargetPlayer->y), + Mth::floor(mc->cameraTargetPlayer->z)); + float whiteness = (3 - mc->options->viewDistance) / 3.0f; + float fogBrT = brr * (1 - whiteness) + whiteness; + fogBr += (fogBrT - fogBr) * 0.1f; - itemInHandRenderer->tick(); + itemInHandRenderer->tick(); - PIXBeginNamedEvent(0,"Rain tick"); - tickRain(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Rain tick"); + tickRain(); + PIXEndNamedEvent(); - if( mc->player != mc->localplayers[ProfileManager.GetPrimaryPad()] ) return; // 4J added for split screen - only do rest of processing for once per frame + if (mc->player != mc->localplayers[ProfileManager.GetPrimaryPad()]) + return; // 4J added for split screen - only do rest of processing for + // once per frame - _tick++; + _tick++; } -void GameRenderer::pick(float a) -{ - if (mc->cameraTargetPlayer == NULL) return; - if (mc->level == NULL) return; +void GameRenderer::pick(float a) { + if (mc->cameraTargetPlayer == NULL) return; + if (mc->level == NULL) return; - double range = mc->gameMode->getPickRange(); - delete mc->hitResult; - MemSect(31); - mc->hitResult = mc->cameraTargetPlayer->pick(range, a); - MemSect(0); + double range = mc->gameMode->getPickRange(); + delete mc->hitResult; + MemSect(31); + mc->hitResult = mc->cameraTargetPlayer->pick(range, a); + MemSect(0); - // 4J - added - stop blocks right at the edge of the world from being pickable so we shouldn't be able to directly destroy or create anything there - if( mc->hitResult ) - { - int maxxz = ( ( mc->level->chunkSource->m_XZSize / 2 ) * 16 ) - 2; - int minxz = ( -( mc->level->chunkSource->m_XZSize / 2 ) * 16 ) + 1; + // 4J - added - stop blocks right at the edge of the world from being + // pickable so we shouldn't be able to directly destroy or create anything + // there + if (mc->hitResult) { + int maxxz = ((mc->level->chunkSource->m_XZSize / 2) * 16) - 2; + int minxz = (-(mc->level->chunkSource->m_XZSize / 2) * 16) + 1; - // Don't select the tops of the very edge blocks, or the sides of the next blocks in - // 4J Stu - Only block the sides that are facing an outside block - int hitx = mc->hitResult->x; - int hitz = mc->hitResult->z; - int face = mc->hitResult->f; - if( face == Facing::WEST && hitx < 0 ) hitx -= 1; - if( face == Facing::EAST && hitx > 0 ) hitx += 1; - if( face == Facing::NORTH && hitz < 0 ) hitz -= 1; - if( face == Facing::SOUTH && hitz > 0 ) hitz += 1; + // Don't select the tops of the very edge blocks, or the sides of the + // next blocks in 4J Stu - Only block the sides that are facing an + // outside block + int hitx = mc->hitResult->x; + int hitz = mc->hitResult->z; + int face = mc->hitResult->f; + if (face == Facing::WEST && hitx < 0) hitx -= 1; + if (face == Facing::EAST && hitx > 0) hitx += 1; + if (face == Facing::NORTH && hitz < 0) hitz -= 1; + if (face == Facing::SOUTH && hitz > 0) hitz += 1; - if( ( hitx < minxz ) || ( hitx > maxxz) || - ( hitz < minxz ) || ( hitz > maxxz) ) - { - delete mc->hitResult; - mc->hitResult = NULL; - } - } + if ((hitx < minxz) || (hitx > maxxz) || (hitz < minxz) || + (hitz > maxxz)) { + delete mc->hitResult; + mc->hitResult = NULL; + } + } - double dist = range; - Vec3 *from = mc->cameraTargetPlayer->getPos(a); + double dist = range; + Vec3* from = mc->cameraTargetPlayer->getPos(a); - if (mc->gameMode->hasFarPickRange()) - { - dist = range = 6; - } - else - { - if (dist > 3) dist = 3; - range = dist; - } + if (mc->gameMode->hasFarPickRange()) { + dist = range = 6; + } else { + if (dist > 3) dist = 3; + range = dist; + } - if (mc->hitResult != NULL) - { - dist = mc->hitResult->pos->distanceTo(from); - } + if (mc->hitResult != NULL) { + dist = mc->hitResult->pos->distanceTo(from); + } - Vec3 *b = mc->cameraTargetPlayer->getViewVector(a); - Vec3 *to = from->add(b->x * range, b->y * range, b->z * range); + Vec3* b = mc->cameraTargetPlayer->getViewVector(a); + Vec3* to = from->add(b->x * range, b->y * range, b->z * range); hovered = nullptr; float overlap = 1; - std::vector > *objects = mc->level->getEntities(mc->cameraTargetPlayer, mc->cameraTargetPlayer->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); + std::vector >* objects = mc->level->getEntities( + mc->cameraTargetPlayer, + mc->cameraTargetPlayer->bb + ->expand(b->x * (range), b->y * (range), b->z * (range)) + ->grow(overlap, overlap, overlap)); double nearest = dist; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //objects->at(i); + AUTO_VAR(itEnd, objects->end()); + for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // objects->at(i); if (!e->isPickable()) continue; - float rr = e->getPickRadius(); - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (bb->contains(from)) - { - if (0 < nearest || nearest == 0) - { - hovered = e; - nearest = 0; - } - } - else if (p != NULL) - { - double dd = from->distanceTo(p->pos); - if (dd < nearest || nearest == 0) - { - hovered = e; - nearest = dd; - } - } - delete p; - } + float rr = e->getPickRadius(); + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (bb->contains(from)) { + if (0 < nearest || nearest == 0) { + hovered = e; + nearest = 0; + } + } else if (p != NULL) { + double dd = from->distanceTo(p->pos); + if (dd < nearest || nearest == 0) { + hovered = e; + nearest = dd; + } + } + delete p; + } - if (hovered != NULL) - { - if (nearest < dist || (mc->hitResult == NULL)) - { - if( mc->hitResult != NULL ) - delete mc->hitResult; - mc->hitResult = new HitResult(hovered); - } - } + if (hovered != NULL) { + if (nearest < dist || (mc->hitResult == NULL)) { + if (mc->hitResult != NULL) delete mc->hitResult; + mc->hitResult = new HitResult(hovered); + } + } } -void GameRenderer::SetFovVal(float fov) -{ - m_fov=fov; -} +void GameRenderer::SetFovVal(float fov) { m_fov = fov; } -float GameRenderer::GetFovVal() -{ - return m_fov; -} +float GameRenderer::GetFovVal() { return m_fov; } -void GameRenderer::tickFov() -{ - std::shared_ptrplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); +void GameRenderer::tickFov() { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - int playerIdx = player ? player->GetXboxPad() : 0; + int playerIdx = player ? player->GetXboxPad() : 0; tFov[playerIdx] = player->getFieldOfViewModifier(); oFov[playerIdx] = fov[playerIdx]; fov[playerIdx] += (tFov[playerIdx] - fov[playerIdx]) * 0.5f; } -float GameRenderer::getFov(float a, bool applyEffects) -{ - if (cameraFlip > 0 ) return 90; +float GameRenderer::getFov(float a, bool applyEffects) { + if (cameraFlip > 0) return 90; - std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - int playerIdx = player ? player->GetXboxPad() : 0; - float fov = m_fov;//70; - if (applyEffects) - { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + int playerIdx = player ? player->GetXboxPad() : 0; + float fov = m_fov; // 70; + if (applyEffects) { fov += mc->options->fov * 40; - fov *= this->oFov[playerIdx] + (this->fov[playerIdx] - this->oFov[playerIdx]) * a; + fov *= this->oFov[playerIdx] + + (this->fov[playerIdx] - this->oFov[playerIdx]) * a; } - if (player->getHealth() <= 0) - { - float duration = player->deathTime + a; + if (player->getHealth() <= 0) { + float duration = player->deathTime + a; - fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1); - } + fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1); + } int t = Camera::getBlockAt(mc->level, player, a); - if (t != 0 && Tile::tiles[t]->material == Material::water) fov = fov * 60 / 70; - - return fov + fovOffsetO + (fovOffset - fovOffsetO) * a; + if (t != 0 && Tile::tiles[t]->material == Material::water) + fov = fov * 60 / 70; + return fov + fovOffsetO + (fovOffset - fovOffsetO) * a; } -void GameRenderer::bobHurt(float a) -{ - std::shared_ptr player = mc->cameraTargetPlayer; +void GameRenderer::bobHurt(float a) { + std::shared_ptr player = mc->cameraTargetPlayer; - float hurt = player->hurtTime - a; + float hurt = player->hurtTime - a; - if (player->getHealth() <= 0) - { - float duration = player->deathTime + a; + if (player->getHealth() <= 0) { + float duration = player->deathTime + a; - glRotatef(40 - (40 * 200) / (duration + 200), 0, 0, 1); - } + glRotatef(40 - (40 * 200) / (duration + 200), 0, 0, 1); + } - if (hurt < 0) return; - hurt /= player->hurtDuration; - hurt = (float) Mth::sin(hurt * hurt * hurt * hurt * PI); + if (hurt < 0) return; + hurt /= player->hurtDuration; + hurt = (float)Mth::sin(hurt * hurt * hurt * hurt * PI); - float rr = player->hurtDir; - - - glRotatef(-rr, 0, 1, 0); - glRotatef(-hurt * 14, 0, 0, 1); - glRotatef(+rr, 0, 1, 0); + float rr = player->hurtDir; + glRotatef(-rr, 0, 1, 0); + glRotatef(-hurt * 14, 0, 0, 1); + glRotatef(+rr, 0, 1, 0); } -void GameRenderer::bobView(float a) -{ - std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - if(player==NULL) - { - return; - } - //std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); +void GameRenderer::bobView(float a) { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + if (player == NULL) { + return; + } + // std::shared_ptr player = + // std::dynamic_pointer_cast(mc->cameraTargetPlayer); - float wda = player->walkDist - player->walkDistO; - float b = -(player->walkDist + wda * a); - float bob = player->oBob + (player->bob - player->oBob) * a; - float tilt = player->oTilt + (player->tilt - player->oTilt) * a; - glTranslatef((float) Mth::sin(b * PI) * bob * 0.5f, -(float) abs(Mth::cos(b * PI) * bob), 0); - glRotatef((float) Mth::sin(b * PI) * bob * 3, 0, 0, 1); - glRotatef((float) abs(Mth::cos(b * PI - 0.2f) * bob) * 5, 1, 0, 0); - glRotatef((float) tilt, 1, 0, 0); + float wda = player->walkDist - player->walkDistO; + float b = -(player->walkDist + wda * a); + float bob = player->oBob + (player->bob - player->oBob) * a; + float tilt = player->oTilt + (player->tilt - player->oTilt) * a; + glTranslatef((float)Mth::sin(b * PI) * bob * 0.5f, + -(float)abs(Mth::cos(b * PI) * bob), 0); + glRotatef((float)Mth::sin(b * PI) * bob * 3, 0, 0, 1); + glRotatef((float)abs(Mth::cos(b * PI - 0.2f) * bob) * 5, 1, 0, 0); + glRotatef((float)tilt, 1, 0, 0); } -void GameRenderer::moveCameraToPlayer(float a) -{ - std::shared_ptr player = mc->cameraTargetPlayer; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - float heightOffset = player->heightOffset - 1.62f; +void GameRenderer::moveCameraToPlayer(float a) { + std::shared_ptr player = mc->cameraTargetPlayer; + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + float heightOffset = player->heightOffset - 1.62f; - double x = player->xo + (player->x - player->xo) * a; - double y = player->yo + (player->y - player->yo) * a - heightOffset; - double z = player->zo + (player->z - player->zo) * a; + double x = player->xo + (player->x - player->xo) * a; + double y = player->yo + (player->y - player->yo) * a - heightOffset; + double z = player->zo + (player->z - player->zo) * a; + glRotatef(cameraRollO + (cameraRoll - cameraRollO) * a, 0, 0, 1); - glRotatef(cameraRollO + (cameraRoll - cameraRollO) * a, 0, 0, 1); + if (player->isSleeping()) { + heightOffset += 1.0; + glTranslatef(0.0f, 0.3f, 0); + if (!mc->options->fixedCamera) { + int t = + mc->level->getTile(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + if (t == Tile::bed_Id) { + int data = mc->level->getData(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z)); - if (player->isSleeping()) - { - heightOffset += 1.0; - glTranslatef(0.0f, 0.3f, 0); - if (!mc->options->fixedCamera) - { - int t = mc->level->getTile(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - if (t == Tile::bed_Id) - { - int data = mc->level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + int direction = data & 3; + glRotatef((float)direction * 90, 0.0f, 1.0f, 0.0f); + } + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, + 0, -1, 0); + glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, -1, 0, + 0); + } + } + // 4J-PB - changing this to be per player + // else if (mc->options->thirdPersonView) + else if (localplayer->ThirdPersonView()) { + double cameraDist = + thirdDistanceO + (thirdDistance - thirdDistanceO) * a; - int direction = data & 3; - glRotatef((float)direction * 90,0.0f, 1.0f, 0.0f); - } - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, -1, 0); - glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, -1, 0, 0); - } - } - // 4J-PB - changing this to be per player - //else if (mc->options->thirdPersonView) - else if (localplayer->ThirdPersonView()) - { - double cameraDist = thirdDistanceO + (thirdDistance - thirdDistanceO) * a; + if (mc->options->fixedCamera) { + float rotationY = + thirdRotationO + (thirdRotation - thirdRotationO) * a; + float xRot = thirdTiltO + (thirdTilt - thirdTiltO) * a; - if (mc->options->fixedCamera) - { + glTranslatef(0, 0, (float)-cameraDist); + glRotatef(xRot, 1, 0, 0); + glRotatef(rotationY, 0, 1, 0); + } else { + // 4J - corrected bug where this used to just take player->xRot & + // yRot directly and so wasn't taking into account interpolation, + // allowing camera to go through walls + float yRot = player->yRotO + (player->yRot - player->yRotO) * a; + float xRot = player->xRotO + (player->xRot - player->xRotO) * a; - float rotationY = thirdRotationO + (thirdRotation - thirdRotationO) * a; - float xRot = thirdTiltO + (thirdTilt - thirdTiltO) * a; + // Thirdperson view values are now 0 for disabled, 1 for original + // mode, 2 for reversed. + if (localplayer->ThirdPersonView() == 2) { + // Reverse y rotation - note that this is only used in doing + // collision to calculate our view distance, the actual rotation + // itself is just below this else {} block + yRot += 180.0f; + } - glTranslatef(0, 0, (float) -cameraDist); - glRotatef(xRot, 1, 0, 0); - glRotatef(rotationY, 0, 1, 0); - } - else - { - // 4J - corrected bug where this used to just take player->xRot & yRot directly and so wasn't taking into account interpolation, allowing camera to go through walls - float yRot = player->yRotO + (player->yRot - player->yRotO) * a; - float xRot = player->xRotO + (player->xRot - player->xRotO) * a; + double xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * + cameraDist; + double zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * + cameraDist; + double yd = -Mth::sin(xRot / 180 * PI) * cameraDist; - // Thirdperson view values are now 0 for disabled, 1 for original mode, 2 for reversed. - if( localplayer->ThirdPersonView() == 2 ) - { - // Reverse y rotation - note that this is only used in doing collision to calculate our view - // distance, the actual rotation itself is just below this else {} block - yRot += 180.0f; - } + for (int i = 0; i < 8; i++) { + float xo = (float)((i & 1) * 2 - 1); + float yo = (float)(((i >> 1) & 1) * 2 - 1); + float zo = (float)(((i >> 2) & 1) * 2 - 1); - double xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist; - double zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist; - double yd = -Mth::sin(xRot / 180 * PI) * cameraDist; + xo *= 0.1f; + yo *= 0.1f; + zo *= 0.1f; - for (int i = 0; i < 8; i++) - { - float xo = (float)((i & 1) * 2 - 1); - float yo = (float)(((i >> 1) & 1) * 2 - 1); - float zo = (float)(((i >> 2) & 1) * 2 - 1); + // 4J - corrected bug here where zo was also added to x + // component + HitResult* hr = mc->level->clip( + Vec3::newTemp(x + xo, y + yo, z + zo), + Vec3::newTemp(x - xd + xo, y - yd + yo, z - zd + zo)); + if (hr != NULL) { + double dist = hr->pos->distanceTo(Vec3::newTemp(x, y, z)); + if (dist < cameraDist) cameraDist = dist; + delete hr; + } + } - xo *= 0.1f; - yo *= 0.1f; - zo *= 0.1f; + // 4J - removed extra rotations here that aren't needed because our + // xRot/yRot don't ever deviate from the player's view direction + // glRotatef(player->xRot - xRot, 1, 0, 0); + // glRotatef(player->yRot - yRot, 0, 1, 0); + glTranslatef(0, 0, (float)-cameraDist); + // glRotatef(yRot - player->yRot, 0, 1, 0); + // glRotatef(xRot - player->xRot, 1, 0, 0); + } + } else { + glTranslatef(0, 0, -0.1f); + } - // 4J - corrected bug here where zo was also added to x component - HitResult *hr = mc->level->clip(Vec3::newTemp(x + xo, y + yo, z + zo), Vec3::newTemp(x - xd + xo, y - yd + yo, z - zd + zo)); - if (hr != NULL) - { - double dist = hr->pos->distanceTo(Vec3::newTemp(x, y, z)); - if (dist < cameraDist) cameraDist = dist; - delete hr; - } - } + if (!mc->options->fixedCamera) { + glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, 1, 0, 0); + if (localplayer->ThirdPersonView() == 2) { + // Third person view is now 0 for disabled, 1 for original, 2 for + // flipped + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a, 0, 1, + 0); + } else { + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, + 0, 1, 0); + } + } - // 4J - removed extra rotations here that aren't needed because our xRot/yRot don't ever - // deviate from the player's view direction -// glRotatef(player->xRot - xRot, 1, 0, 0); -// glRotatef(player->yRot - yRot, 0, 1, 0); - glTranslatef(0, 0, (float) -cameraDist); -// glRotatef(yRot - player->yRot, 0, 1, 0); -// glRotatef(xRot - player->xRot, 1, 0, 0); - } - } - else - { - glTranslatef(0, 0, -0.1f); - } + glTranslatef(0, heightOffset, 0); - if (!mc->options->fixedCamera) - { - glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, 1, 0, 0); - if( localplayer->ThirdPersonView() == 2 ) - { - // Third person view is now 0 for disabled, 1 for original, 2 for flipped - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a, 0, 1, 0); - } - else - { - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, 1, 0); - } - } - - glTranslatef(0, heightOffset, 0); - - x = player->xo + (player->x - player->xo) * a; - y = player->yo + (player->y - player->yo) * a - heightOffset; - z = player->zo + (player->z - player->zo) * a; - - isInClouds = mc->levelRenderer->isInCloud(x, y, z, a); + x = player->xo + (player->x - player->xo) * a; + y = player->yo + (player->y - player->yo) * a - heightOffset; + z = player->zo + (player->z - player->zo) * a; + isInClouds = mc->levelRenderer->isInCloud(x, y, z, a); } - -void GameRenderer::zoomRegion(double zoom, double xa, double ya) -{ - this->zoom = zoom; - this->zoom_x = xa; - this->zoom_y = ya; +void GameRenderer::zoomRegion(double zoom, double xa, double ya) { + this->zoom = zoom; + this->zoom_x = xa; + this->zoom_y = ya; } -void GameRenderer::unZoomRegion() -{ - zoom = 1; +void GameRenderer::unZoomRegion() { zoom = 1; } + +// 4J added as we have more complex adjustments to make for fov & aspect on +// account of viewports +void GameRenderer::getFovAndAspect(float& fov, float& aspect, float a, + bool applyEffects) { + // 4J - split out aspect ratio and fov here so we can adjust for viewports - + // we might need to revisit these as avoid pixel streching, its UGLEYYY + { + int fbw = mc->width; + int fbh = mc->height; + RenderManager.GetFramebufferSize(fbw, fbh); + aspect = fbw / (float)fbh; + } + fov = getFov(a, applyEffects); + + if ((mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP) || + (mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) { + aspect *= 2.0f; + fov *= 0.7f; // Reduce FOV to make things less fish-eye, at the expense + // of reducing vertical FOV from single player mode + } else if ((mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT) || + (mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT)) { + // Ideally I'd like to make the fov bigger here, but if I do then you an + // see that the arm isn't very long... + aspect *= 0.5f; + } } -// 4J added as we have more complex adjustments to make for fov & aspect on account of viewports -void GameRenderer::getFovAndAspect(float& fov, float& aspect, float a, bool applyEffects) -{ - // 4J - split out aspect ratio and fov here so we can adjust for viewports - we might need to revisit these as - // avoid pixel streching, its UGLEYYY - { - int fbw = mc->width; - int fbh = mc->height; - RenderManager.GetFramebufferSize(fbw, fbh); - aspect = fbw / (float) fbh; - } - fov = getFov(a, applyEffects); +void GameRenderer::setupCamera(float a, int eye) { + renderDistance = (float)(16 * 16 >> (mc->options->viewDistance)); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); - if( ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP ) || - ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM ) ) - { - aspect *= 2.0f; - fov *= 0.7f; // Reduce FOV to make things less fish-eye, at the expense of reducing vertical FOV from single player mode - } - else if( ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT ) || - ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT) ) - { - // Ideally I'd like to make the fov bigger here, but if I do then you an see that the arm isn't very long... - aspect *= 0.5f; - } -} + float stereoScale = 0.07f; + if (mc->options->anaglyph3d) + glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); -void GameRenderer::setupCamera(float a, int eye) -{ - renderDistance = (float)(16 * 16 >> (mc->options->viewDistance)); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + // 4J - have split out fov & aspect calculation so we can take into account + // viewports + float aspect, fov; + getFovAndAspect(fov, aspect, a, true); - float stereoScale = 0.07f; - if (mc->options->anaglyph3d) glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); + if (zoom != 1) { + glTranslatef((float)zoom_x, (float)-zoom_y, 0); + glScaled(zoom, zoom, 1); + } + gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - // 4J - have split out fov & aspect calculation so we can take into account viewports - float aspect, fov; - getFovAndAspect(fov, aspect, a, true); - - if (zoom != 1) - { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); - glScaled(zoom, zoom, 1); - } - gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - - if (mc->gameMode->isCutScene()) - { + if (mc->gameMode->isCutScene()) { float s = 1 / 1.5f; glScalef(1, s, 1); } - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); - bobHurt(a); + bobHurt(a); - // 4J-PB - this is a per-player option - //if (mc->options->bobView) bobView(a); - - bool bNoLegAnim =(mc->player->getAnimOverrideBitmask()&(1<player->getAnimOverrideBitmask()&(1<options->bobView) bobView(a); - if(app.GetGameSettings(mc->player->GetXboxPad(),eGameSetting_ViewBob) && !mc->player->abilities.flying && !bNoLegAnim && !bNoBobbingAnim) bobView(a); + bool bNoLegAnim = (mc->player->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_NoLegAnim)) != 0; + bool bNoBobbingAnim = (mc->player->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_NoBobbing)) != 0; - float pt = mc->player->oPortalTime + (mc->player->portalTime - mc->player->oPortalTime) * a; - if (pt > 0) - { + if (app.GetGameSettings(mc->player->GetXboxPad(), eGameSetting_ViewBob) && + !mc->player->abilities.flying && !bNoLegAnim && !bNoBobbingAnim) + bobView(a); + + float pt = mc->player->oPortalTime + + (mc->player->portalTime - mc->player->oPortalTime) * a; + if (pt > 0) { int multiplier = 20; - if (mc->player->hasEffect(MobEffect::confusion)) - { + if (mc->player->hasEffect(MobEffect::confusion)) { multiplier = 7; } - float skew = 5 / (pt * pt + 5) - pt * 0.04f; - skew *= skew; - glRotatef((_tick + a) * multiplier, 0, 1, 1); - glScalef(1 / skew, 1, 1); - glRotatef(-(_tick + a) * multiplier, 0, 1, 1); - } + float skew = 5 / (pt * pt + 5) - pt * 0.04f; + skew *= skew; + glRotatef((_tick + a) * multiplier, 0, 1, 1); + glScalef(1 / skew, 1, 1); + glRotatef(-(_tick + a) * multiplier, 0, 1, 1); + } + moveCameraToPlayer(a); - moveCameraToPlayer(a); - - if (cameraFlip > 0) - { + if (cameraFlip > 0) { int i = cameraFlip - 1; if (i == 1) glRotatef(90, 0, 1, 0); if (i == 2) glRotatef(180, 0, 1, 0); @@ -720,113 +691,124 @@ void GameRenderer::setupCamera(float a, int eye) } } -void GameRenderer::renderItemInHand(float a, int eye) -{ - if (cameraFlip > 0) return; +void GameRenderer::renderItemInHand(float a, int eye) { + if (cameraFlip > 0) return; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - // 4J-PB - to turn off the hand for screenshots, but not when the item held is a map - if ( localplayer!=NULL) - { - std::shared_ptr item = localplayer->inventory->getSelected(); - if(!(item && item->getItem()->id==Item::map_Id) && app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_DisplayHand)==0 ) return; - } - - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + // 4J-PB - to turn off the hand for screenshots, but not when the item held + // is a map + if (localplayer != NULL) { + std::shared_ptr item = + localplayer->inventory->getSelected(); + if (!(item && item->getItem()->id == Item::map_Id) && + app.GetGameSettings(localplayer->GetXboxPad(), + eGameSetting_DisplayHand) == 0) + return; + } + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); float stereoScale = 0.07f; - if (mc->options->anaglyph3d) glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); + if (mc->options->anaglyph3d) + glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); - // 4J - have split out fov & aspect calculation so we can take into account viewports - float fov, aspect; - getFovAndAspect(fov, aspect, a, false); + // 4J - have split out fov & aspect calculation so we can take into account + // viewports + float fov, aspect; + getFovAndAspect(fov, aspect, a, false); - if (zoom != 1) - { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); + if (zoom != 1) { + glTranslatef((float)zoom_x, (float)-zoom_y, 0); glScaled(zoom, zoom, 1); } gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - if (mc->gameMode->isCutScene()) - { + if (mc->gameMode->isCutScene()) { float s = 1 / 1.5f; glScalef(1, s, 1); } glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); + if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); - glPushMatrix(); - bobHurt(a); + glPushMatrix(); + bobHurt(a); - // 4J-PB - changing this to be per player - //if (mc->options->bobView) bobView(a); - bool bNoLegAnim =(localplayer->getAnimOverrideBitmask()&( (1<GetXboxPad(),eGameSetting_ViewBob) && !localplayer->abilities.flying && !bNoLegAnim) bobView(a); + // 4J-PB - changing this to be per player + // if (mc->options->bobView) bobView(a); + bool bNoLegAnim = (localplayer->getAnimOverrideBitmask() & + ((1 << HumanoidModel::eAnim_NoLegAnim) | + (1 << HumanoidModel::eAnim_NoBobbing))) != 0; + if (app.GetGameSettings(localplayer->GetXboxPad(), eGameSetting_ViewBob) && + !localplayer->abilities.flying && !bNoLegAnim) + bobView(a); - // 4J-PB - changing this to be per player - //if (!mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) - if (!localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) - { - if (!mc->options->hideGui && !mc->gameMode->isCutScene()) - { - turnOnLightLayer(a, true); - PIXBeginNamedEvent(0,"Item in hand render"); - // 4jcraft: add null pointer check to itemInHandRenderer to prevent a occasional seg fault - if (itemInHandRenderer != nullptr) { - itemInHandRenderer->render(a); - } - PIXEndNamedEvent(); - turnOffLightLayer(a); - } - } - glPopMatrix(); - // 4J-PB - changing this to be per player - //if (!mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) - if (!localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) - { - // 4jcraft: add null pointer check to itemInHandRenderer to prevent a occasional seg fault - if (itemInHandRenderer != nullptr) { - itemInHandRenderer->renderScreenEffect(a); - } - bobHurt(a); - } - // 4J-PB - changing this to be per player - //if (mc->options->bobView) bobView(a); - if(app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_ViewBob) && !localplayer->abilities.flying && !bNoLegAnim) bobView(a); + // 4J-PB - changing this to be per player + // if (!mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) + if (!localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) { + if (!mc->options->hideGui && !mc->gameMode->isCutScene()) { + turnOnLightLayer(a, true); + PIXBeginNamedEvent(0, "Item in hand render"); + // 4jcraft: add null pointer check to itemInHandRenderer to prevent + // a occasional seg fault + if (itemInHandRenderer != nullptr) { + itemInHandRenderer->render(a); + } + PIXEndNamedEvent(); + turnOffLightLayer(a); + } + } + glPopMatrix(); + // 4J-PB - changing this to be per player + // if (!mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) + if (!localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) { + // 4jcraft: add null pointer check to itemInHandRenderer to prevent a + // occasional seg fault + if (itemInHandRenderer != nullptr) { + itemInHandRenderer->renderScreenEffect(a); + } + bobHurt(a); + } + // 4J-PB - changing this to be per player + // if (mc->options->bobView) bobView(a); + if (app.GetGameSettings(localplayer->GetXboxPad(), eGameSetting_ViewBob) && + !localplayer->abilities.flying && !bNoLegAnim) + bobView(a); } // 4J - change brought forward from 1.8.2 -void GameRenderer::turnOffLightLayer(double alpha) -{ // 4J - TODO - // 4jcraft: manually handle this in order to ensure that the light layer is turned off correctly +void GameRenderer::turnOffLightLayer( + double alpha) { // 4J - TODO + // 4jcraft: manually handle this in order to ensure that + // the light layer is turned off correctly #if 1 - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { glClientActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE1); - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); glDisable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); + glBindTexture(GL_TEXTURE_2D, 0); glClientActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE0); } #endif - //RenderManager.TextureBindVertex(-1); + // RenderManager.TextureBindVertex(-1); } // 4J - change brought forward from 1.8.2 -void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) -{ // 4J - TODO +void GameRenderer::turnOnLightLayer(double alpha, + bool scaleLight) { // 4J - TODO #if 0 if (SharedConstants::TEXTURE_LIGHTING) { @@ -854,9 +836,10 @@ void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) glActiveTexture(GL_TEXTURE0); } #endif - // update light texture - // todo: check implementation of getLightTexture. - RenderManager.TextureBindVertex(getLightTexture(mc->player->GetXboxPad(), mc->level), scaleLight); + // update light texture + // todo: check implementation of getLightTexture. + RenderManager.TextureBindVertex( + getLightTexture(mc->player->GetXboxPad(), mc->level), scaleLight); #if 0 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -866,10 +849,11 @@ void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) } // 4J - change brought forward from 1.8.2 -void GameRenderer::tickLightTexture() -{ - blrt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); - blgt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); +void GameRenderer::tickLightTexture() { + blrt += (float)((Math::random() - Math::random()) * Math::random() * + Math::random()); + blgt += (float)((Math::random() - Math::random()) * Math::random() * + Math::random()); blrt *= 0.9; blgt *= 0.9; blr += (blrt - blr) * 1; @@ -877,158 +861,147 @@ void GameRenderer::tickLightTexture() _updateLightTexture = true; } -void GameRenderer::updateLightTexture(float a) -{ - // 4J-JEV: Now doing light textures on PER PLAYER basis. - // 4J - we *had* added separate light textures for all dimensions, and this loop to update them all here - for(int j = 0; j < XUSER_MAX_COUNT; j++ ) - { - // Loop over all the players - std::shared_ptr player = Minecraft::GetInstance()->localplayers[j]; - if (player == NULL) continue; +void GameRenderer::updateLightTexture(float a) { + // 4J-JEV: Now doing light textures on PER PLAYER basis. + // 4J - we *had* added separate light textures for all dimensions, and this + // loop to update them all here + for (int j = 0; j < XUSER_MAX_COUNT; j++) { + // Loop over all the players + std::shared_ptr player = + Minecraft::GetInstance()->localplayers[j]; + if (player == NULL) continue; - Level *level = player->level; // 4J - was mc->level when it was just to update the one light texture - - float skyDarken1 = level->getSkyDarken((float) 1); - for (int i = 0; i < 256; i++) - { - float darken = skyDarken1 * 0.95f + 0.05f; - float sky = level->dimension->brightnessRamp[i / 16] * darken; - float block = level->dimension->brightnessRamp[i % 16] * (blr * 0.1f + 1.5f); + Level* level = player->level; // 4J - was mc->level when it was just to + // update the one light texture - if (level->lightningBoltTime > 0) - { - sky = level->dimension->brightnessRamp[i / 16]; - } + float skyDarken1 = level->getSkyDarken((float)1); + for (int i = 0; i < 256; i++) { + float darken = skyDarken1 * 0.95f + 0.05f; + float sky = level->dimension->brightnessRamp[i / 16] * darken; + float block = + level->dimension->brightnessRamp[i % 16] * (blr * 0.1f + 1.5f); - float rs = sky * (skyDarken1 * 0.65f + 0.35f); - float gs = sky * (skyDarken1 * 0.65f + 0.35f); - float bs = sky; + if (level->lightningBoltTime > 0) { + sky = level->dimension->brightnessRamp[i / 16]; + } - float rb = block; - float gb = block * ((block * 0.6f + 0.4f) * 0.6f + 0.4f); - float bb = block * ((block * block) * 0.6f + 0.4f); + float rs = sky * (skyDarken1 * 0.65f + 0.35f); + float gs = sky * (skyDarken1 * 0.65f + 0.35f); + float bs = sky; - float _r = (rs + rb); - float _g = (gs + gb); - float _b = (bs + bb); + float rb = block; + float gb = block * ((block * 0.6f + 0.4f) * 0.6f + 0.4f); + float bb = block * ((block * block) * 0.6f + 0.4f); - _r = _r * 0.96f + 0.03f; - _g = _g * 0.96f + 0.03f; - _b = _b * 0.96f + 0.03f; + float _r = (rs + rb); + float _g = (gs + gb); + float _b = (bs + bb); - if (level->dimension->id == 1) - { - _r = (0.22f + rb * 0.75f); - _g = (0.28f + gb * 0.75f); - _b = (0.25f + bb * 0.75f); - } + _r = _r * 0.96f + 0.03f; + _g = _g * 0.96f + 0.03f; + _b = _b * 0.96f + 0.03f; - if (player->hasEffect(MobEffect::nightVision)) - { - float scale = getNightVisionScale(player, a); - { - float dist = 1.0f / _r; - if (dist > (1.0f / _g)) - { - dist = (1.0f / _g); - } - if (dist > (1.0f / _b)) - { - dist = (1.0f / _b); - } - _r = _r * (1.0f - scale) + (_r * dist) * scale; - _g = _g * (1.0f - scale) + (_g * dist) * scale; - _b = _b * (1.0f - scale) + (_b * dist) * scale; - } - } + if (level->dimension->id == 1) { + _r = (0.22f + rb * 0.75f); + _g = (0.28f + gb * 0.75f); + _b = (0.25f + bb * 0.75f); + } - float brightness = 0.0f; // 4J - TODO - was mc->options->gamma; - if (_r > 1) _r = 1; - if (_g > 1) _g = 1; - if (_b > 1) _b = 1; + if (player->hasEffect(MobEffect::nightVision)) { + float scale = getNightVisionScale(player, a); + { + float dist = 1.0f / _r; + if (dist > (1.0f / _g)) { + dist = (1.0f / _g); + } + if (dist > (1.0f / _b)) { + dist = (1.0f / _b); + } + _r = _r * (1.0f - scale) + (_r * dist) * scale; + _g = _g * (1.0f - scale) + (_g * dist) * scale; + _b = _b * (1.0f - scale) + (_b * dist) * scale; + } + } - float ir = 1 - _r; - float ig = 1 - _g; - float ib = 1 - _b; - ir = 1 - (ir * ir * ir * ir); - ig = 1 - (ig * ig * ig * ig); - ib = 1 - (ib * ib * ib * ib); - _r = _r * (1 - brightness) + ir * brightness; - _g = _g * (1 - brightness) + ig * brightness; - _b = _b * (1 - brightness) + ib * brightness; + float brightness = 0.0f; // 4J - TODO - was mc->options->gamma; + if (_r > 1) _r = 1; + if (_g > 1) _g = 1; + if (_b > 1) _b = 1; + float ir = 1 - _r; + float ig = 1 - _g; + float ib = 1 - _b; + ir = 1 - (ir * ir * ir * ir); + ig = 1 - (ig * ig * ig * ig); + ib = 1 - (ib * ib * ib * ib); + _r = _r * (1 - brightness) + ir * brightness; + _g = _g * (1 - brightness) + ig * brightness; + _b = _b * (1 - brightness) + ib * brightness; - _r = _r * 0.96f + 0.03f; - _g = _g * 0.96f + 0.03f; - _b = _b * 0.96f + 0.03f; + _r = _r * 0.96f + 0.03f; + _g = _g * 0.96f + 0.03f; + _b = _b * 0.96f + 0.03f; + if (_r > 1) _r = 1; + if (_g > 1) _g = 1; + if (_b > 1) _b = 1; + if (_r < 0) _r = 0; + if (_g < 0) _g = 0; + if (_b < 0) _b = 0; - if (_r > 1) _r = 1; - if (_g > 1) _g = 1; - if (_b > 1) _b = 1; - if (_r < 0) _r = 0; - if (_g < 0) _g = 0; - if (_b < 0) _b = 0; + int a = 255; + int r = (int)(_r * 255); + int g = (int)(_g * 255); + int b = (int)(_b * 255); - int a = 255; - int r = (int) (_r * 255); - int g = (int) (_g * 255); - int b = (int) (_b * 255); - -#if ( defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__ ) - lightPixels[j][i] = a << 24 | b << 16 | g << 8 | r; -#elif ( defined _XBOX || defined __ORBIS__ ) - lightPixels[j][i] = a << 24 | r << 16 | g << 8 | b; +#if (defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__) + lightPixels[j][i] = a << 24 | b << 16 | g << 8 | r; +#elif (defined _XBOX || defined __ORBIS__) + lightPixels[j][i] = a << 24 | r << 16 | g << 8 | b; #else - lightPixels[j][i] = r << 24 | g << 16 | b << 8 | a; + lightPixels[j][i] = r << 24 | g << 16 | b << 8 | a; #endif - } + } - mc->textures->replaceTextureDirect( lightPixels[j], 16, 16, getLightTexture(j,level) ); - } + mc->textures->replaceTextureDirect(lightPixels[j], 16, 16, + getLightTexture(j, level)); + } } -float GameRenderer::getNightVisionScale(std::shared_ptr player, float a) -{ - int duration = player->getEffect(MobEffect::nightVision)->getDuration(); - if (duration > (SharedConstants::TICKS_PER_SECOND * 10)) - { - return 1.0f; - } - else - { - float flash = std::max(0.0f, (float)duration - a); - return .7f + Mth::sin(flash * PI * .05f) * .3f; // was: .7 + sin(flash*pi*0.2) * .3 - } +float GameRenderer::getNightVisionScale(std::shared_ptr player, + float a) { + int duration = player->getEffect(MobEffect::nightVision)->getDuration(); + if (duration > (SharedConstants::TICKS_PER_SECOND * 10)) { + return 1.0f; + } else { + float flash = std::max(0.0f, (float)duration - a); + return .7f + Mth::sin(flash * PI * .05f) * + .3f; // was: .7 + sin(flash*pi*0.2) * .3 + } } -// 4J added, so we can have a light texture for each player to support split screen -int GameRenderer::getLightTexture(int iPad, Level *level) -{ - // Turn the current dimenions id into an index from 0 to 2 - // int idx = level->dimension->id; - // if( idx == -1 ) idx = 2; +// 4J added, so we can have a light texture for each player to support split +// screen +int GameRenderer::getLightTexture(int iPad, Level* level) { + // Turn the current dimenions id into an index from 0 to 2 + // int idx = level->dimension->id; + // if( idx == -1 ) idx = 2; - return lightTexture[iPad]; // 4J-JEV: Changing to Per Player lighting textures. + return lightTexture[iPad]; // 4J-JEV: Changing to Per Player lighting + // textures. } -void GameRenderer::render(float a, bool bFirst) -{ - if( _updateLightTexture && bFirst) updateLightTexture(a); - if (Display::isActive()) - { - lastActiveTime = System::currentTimeMillis(); - } - else - { - if (System::currentTimeMillis() - lastActiveTime > 500) - { - mc->pauseGame(); - } - } +void GameRenderer::render(float a, bool bFirst) { + if (_updateLightTexture && bFirst) updateLightTexture(a); + if (Display::isActive()) { + lastActiveTime = System::currentTimeMillis(); + } else { + if (System::currentTimeMillis() - lastActiveTime > 500) { + mc->pauseGame(); + } + } -#if 0 // 4J - TODO +#if 0 // 4J - TODO if (mc->mouseGrabbed) { mc->mouseHandler.poll(); @@ -1066,579 +1039,585 @@ void GameRenderer::render(float a, bool bFirst) } #endif - if (mc->noRender) return; - GameRenderer::anaglyph3d = mc->options->anaglyph3d; + if (mc->noRender) return; + GameRenderer::anaglyph3d = mc->options->anaglyph3d; -{ - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - ScreenSizeCalculator ssc(mc->options, mc->width, mc->height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - int xMouse = Mouse::getX() * screenWidth / fbw; - int yMouse = screenHeight - Mouse::getY() * screenHeight / fbh - 1; + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + ScreenSizeCalculator ssc(mc->options, mc->width, mc->height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + int xMouse = Mouse::getX() * screenWidth / fbw; + int yMouse = screenHeight - Mouse::getY() * screenHeight / fbh - 1; - int maxFps = getFpsCap(mc->options->framerateLimit); + int maxFps = getFpsCap(mc->options->framerateLimit); - if (mc->level != NULL) - { - if (maxFps == 0) - { - renderLevel(a, 0); - } - else - { - renderLevel(a, lastNsTime + 1000000000 / maxFps); - } + if (mc->level != NULL) { + if (maxFps == 0) { + renderLevel(a, 0); + } else { + renderLevel(a, lastNsTime + 1000000000 / maxFps); + } - lastNsTime = System::nanoTime(); + lastNsTime = System::nanoTime(); + if (!mc->options->hideGui || mc->screen != NULL) { + mc->gui->render(a, mc->screen != NULL, xMouse, yMouse); + } + } else { + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + } + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + setupGuiScreen(); - if (!mc->options->hideGui || mc->screen != NULL) - { - mc->gui->render(a, mc->screen != NULL, xMouse, yMouse); - } - } - else - { - { - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - } - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - setupGuiScreen(); - - lastNsTime = System::nanoTime(); - } - - - if (mc->screen != NULL) - { - glClear(GL_DEPTH_BUFFER_BIT); - mc->screen->render(xMouse, yMouse, a); - if (mc->screen != NULL && mc->screen->particles != NULL) mc->screen->particles->render(a); - } + lastNsTime = System::nanoTime(); + } + if (mc->screen != NULL) { + glClear(GL_DEPTH_BUFFER_BIT); + mc->screen->render(xMouse, yMouse, a); + if (mc->screen != NULL && mc->screen->particles != NULL) + mc->screen->particles->render(a); + } + } } -} -void GameRenderer::renderLevel(float a) -{ - renderLevel(a, 0); -} +void GameRenderer::renderLevel(float a) { renderLevel(a, 0); } #ifdef MULTITHREAD_ENABLE // Request that an item be deleted, when it is safe to do so -void GameRenderer::AddForDelete(std::uint8_t *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackByte.push_back(deleteThis); +void GameRenderer::AddForDelete(std::uint8_t* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackByte.push_back(deleteThis); } -void GameRenderer::AddForDelete(SparseLightStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackSparseLightStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(SparseLightStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackSparseLightStorage.push_back(deleteThis); } -void GameRenderer::AddForDelete(CompressedTileStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackCompressedTileStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(CompressedTileStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackCompressedTileStorage.push_back(deleteThis); } -void GameRenderer::AddForDelete(SparseDataStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackSparseDataStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(SparseDataStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackSparseDataStorage.push_back(deleteThis); } -void GameRenderer::FinishedReassigning() -{ - LeaveCriticalSection(&m_csDeleteStack); +void GameRenderer::FinishedReassigning() { + LeaveCriticalSection(&m_csDeleteStack); } -int GameRenderer::runUpdate(void *lpParam) -{ - Minecraft *minecraft = Minecraft::GetInstance(); - Vec3::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); - Compression::UseDefaultThreadStorage(); - RenderManager.InitialiseContext(); +int GameRenderer::runUpdate(void* lpParam) { + Minecraft* minecraft = Minecraft::GetInstance(); + Vec3::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Tesselator::CreateNewThreadStorage(1024 * 1024); + Compression::UseDefaultThreadStorage(); + RenderManager.InitialiseContext(); #ifdef _LARGE_WORLDS - Chunk::CreateNewThreadStorage(); + Chunk::CreateNewThreadStorage(); #endif - Tile::CreateNewThreadStorage(); + Tile::CreateNewThreadStorage(); - ShutdownManager::HasStarted(ShutdownManager::eRenderChunkUpdateThread,m_updateEvents); - while(ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread)) - { - //m_updateEvents->Clear(eUpdateEventIsFinished); - //m_updateEvents->WaitForSingle(eUpdateCanRun,INFINITE); - // 4J Stu - We Need to have this happen atomically to avoid deadlocks - m_updateEvents->WaitForAll(INFINITE); + ShutdownManager::HasStarted(ShutdownManager::eRenderChunkUpdateThread, + m_updateEvents); + while ( + ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread)) { + // m_updateEvents->Clear(eUpdateEventIsFinished); + // m_updateEvents->WaitForSingle(eUpdateCanRun,INFINITE); + // 4J Stu - We Need to have this happen atomically to avoid deadlocks + m_updateEvents->WaitForAll(INFINITE); - if( !ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread) ) - { - break; - } + if (!ShutdownManager::ShouldRun( + ShutdownManager::eRenderChunkUpdateThread)) { + break; + } - m_updateEvents->Set(eUpdateCanRun); + m_updateEvents->Set(eUpdateCanRun); -// PIXBeginNamedEvent(0,"Updating dirty chunks %d",(count++)&7); + // PIXBeginNamedEvent(0,"Updating dirty chunks + //%d",(count++)&7); - // Update chunks atomically until there aren't any very near ones left - they will be deferred for rendering - // until the call to CBuffDeferredModeEnd if we have anything near to render here - // Now limiting maximum number of updates that can be deferred as have noticed that with redstone clock circuits, it is possible to create - // things that need constant updating, so if you stand near them, the render data Never gets updated and the game just keeps going until it runs out of render memory... - int count = 0; - static const int MAX_DEFERRED_UPDATES = 10; - bool shouldContinue = false; - do - { - shouldContinue = minecraft->levelRenderer->updateDirtyChunks(); - count++; - } while ( shouldContinue && count < MAX_DEFERRED_UPDATES ); + // Update chunks atomically until there aren't any very near ones left - + // they will be deferred for rendering until the call to + // CBuffDeferredModeEnd if we have anything near to render here Now + // limiting maximum number of updates that can be deferred as have + // noticed that with redstone clock circuits, it is possible to create + // things that need constant updating, so if you stand near them, the + // render data Never gets updated and the game just keeps going until it + // runs out of render memory... + int count = 0; + static const int MAX_DEFERRED_UPDATES = 10; + bool shouldContinue = false; + do { + shouldContinue = minecraft->levelRenderer->updateDirtyChunks(); + count++; + } while (shouldContinue && count < MAX_DEFERRED_UPDATES); -// while( minecraft->levelRenderer->updateDirtyChunks() ) -// ; - RenderManager.CBuffDeferredModeEnd(); + // while( minecraft->levelRenderer->updateDirtyChunks() ) + // ; + RenderManager.CBuffDeferredModeEnd(); - // If any renderable tile entities were flagged in this last block of chunk(s) that were udpated, then change their - // flags to say that this deferred chunk is over and they are actually safe to be removed now - minecraft->levelRenderer->fullyFlagRenderableTileEntitiesToBeRemoved(); + // If any renderable tile entities were flagged in this last block of + // chunk(s) that were udpated, then change their flags to say that this + // deferred chunk is over and they are actually safe to be removed now + minecraft->levelRenderer->fullyFlagRenderableTileEntitiesToBeRemoved(); - // We've got stacks for things that can only safely be deleted whilst this thread isn't updating things - delete those things now - EnterCriticalSection(&m_csDeleteStack); - for(unsigned int i = 0; i < m_deleteStackByte.size(); i++ ) - { - delete m_deleteStackByte[i]; - } - m_deleteStackByte.clear(); - for(unsigned int i = 0; i < m_deleteStackSparseLightStorage.size(); i++ ) - { - delete m_deleteStackSparseLightStorage[i]; - } - m_deleteStackSparseLightStorage.clear(); - for(unsigned int i = 0; i < m_deleteStackCompressedTileStorage.size(); i++ ) - { - delete m_deleteStackCompressedTileStorage[i]; - } - m_deleteStackCompressedTileStorage.clear(); - for(unsigned int i = 0; i < m_deleteStackSparseDataStorage.size(); i++ ) - { - delete m_deleteStackSparseDataStorage[i]; - } - m_deleteStackSparseDataStorage.clear(); - LeaveCriticalSection(&m_csDeleteStack); - -// PIXEndNamedEvent(); + // We've got stacks for things that can only safely be deleted whilst + // this thread isn't updating things - delete those things now + EnterCriticalSection(&m_csDeleteStack); + for (unsigned int i = 0; i < m_deleteStackByte.size(); i++) { + delete m_deleteStackByte[i]; + } + m_deleteStackByte.clear(); + for (unsigned int i = 0; i < m_deleteStackSparseLightStorage.size(); + i++) { + delete m_deleteStackSparseLightStorage[i]; + } + m_deleteStackSparseLightStorage.clear(); + for (unsigned int i = 0; i < m_deleteStackCompressedTileStorage.size(); + i++) { + delete m_deleteStackCompressedTileStorage[i]; + } + m_deleteStackCompressedTileStorage.clear(); + for (unsigned int i = 0; i < m_deleteStackSparseDataStorage.size(); + i++) { + delete m_deleteStackSparseDataStorage[i]; + } + m_deleteStackSparseDataStorage.clear(); + LeaveCriticalSection(&m_csDeleteStack); - AABB::resetPool(); - Vec3::resetPool(); - IntCache::Reset(); - m_updateEvents->Set(eUpdateEventIsFinished); - } + // PIXEndNamedEvent(); - ShutdownManager::HasFinished(ShutdownManager::eRenderChunkUpdateThread); - return 0; + AABB::resetPool(); + Vec3::resetPool(); + IntCache::Reset(); + m_updateEvents->Set(eUpdateEventIsFinished); + } + + ShutdownManager::HasFinished(ShutdownManager::eRenderChunkUpdateThread); + return 0; } #endif -void GameRenderer::EnableUpdateThread() -{ +void GameRenderer::EnableUpdateThread() { // #ifdef __PS3__ // MGH - disable the update on PS3 for now // return; // #endif #ifdef MULTITHREAD_ENABLE - if( updateRunning) return; - app.DebugPrintf("------------------EnableUpdateThread--------------------\n"); - updateRunning = true; - m_updateEvents->Set(eUpdateCanRun); - m_updateEvents->Set(eUpdateEventIsFinished); + if (updateRunning) return; + app.DebugPrintf( + "------------------EnableUpdateThread--------------------\n"); + updateRunning = true; + m_updateEvents->Set(eUpdateCanRun); + m_updateEvents->Set(eUpdateEventIsFinished); #endif } -void GameRenderer::DisableUpdateThread() -{ +void GameRenderer::DisableUpdateThread() { // #ifdef __PS3__ // MGH - disable the update on PS3 for now // return; // #endif #ifdef MULTITHREAD_ENABLE - if( !updateRunning) return; - app.DebugPrintf("------------------DisableUpdateThread--------------------\n"); - updateRunning = false; - m_updateEvents->Clear(eUpdateCanRun); - m_updateEvents->WaitForSingle(eUpdateEventIsFinished,INFINITE); + if (!updateRunning) return; + app.DebugPrintf( + "------------------DisableUpdateThread--------------------\n"); + updateRunning = false; + m_updateEvents->Clear(eUpdateCanRun); + m_updateEvents->WaitForSingle(eUpdateEventIsFinished, INFINITE); #endif } -void GameRenderer::renderLevel(float a, __int64 until) -{ -// if (updateLightTexture) updateLightTexture(); // 4J - TODO - Java 1.0.1 has this line enabled, should check why - don't want to put it in now in case it breaks split-screen +void GameRenderer::renderLevel(float a, __int64 until) { + // if (updateLightTexture) updateLightTexture(); // 4J - TODO - + //Java 1.0.1 has this line enabled, should check why - don't want to put it + //in now in case it breaks split-screen - glEnable(GL_CULL_FACE); - glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); - // Is this the primary player? Only do the updating of chunks if it is. This controls the creation of render data for each chunk - all of this we are only - // going to do for the primary player, and the other players can just view whatever they have loaded in - we're sharing render data between players. - bool updateChunks = ( mc->player == mc->localplayers[ProfileManager.GetPrimaryPad()] ); + // Is this the primary player? Only do the updating of chunks if it is. This + // controls the creation of render data for each chunk - all of this we are + // only going to do for the primary player, and the other players can just + // view whatever they have loaded in - we're sharing render data between + // players. + bool updateChunks = + (mc->player == mc->localplayers[ProfileManager.GetPrimaryPad()]); -// if (mc->cameraTargetPlayer == NULL) // 4J - removed condition as we want to update this is mc->player changes for different local players - { - mc->cameraTargetPlayer = mc->player; - } - pick(a); + // if (mc->cameraTargetPlayer == NULL) // 4J - removed condition as we + //want to update this is mc->player changes for different local players + { + mc->cameraTargetPlayer = mc->player; + } + pick(a); - std::shared_ptr cameraEntity = mc->cameraTargetPlayer; - LevelRenderer *levelRenderer = mc->levelRenderer; - ParticleEngine *particleEngine = mc->particleEngine; - double xOff = cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * a; - double yOff = cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * a; - double zOff = cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * a; + std::shared_ptr cameraEntity = mc->cameraTargetPlayer; + LevelRenderer* levelRenderer = mc->levelRenderer; + ParticleEngine* particleEngine = mc->particleEngine; + double xOff = + cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * a; + double yOff = + cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * a; + double zOff = + cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * a; - for (int i = 0; i < 2; i++) - { - if (mc->options->anaglyph3d) - { - GameRenderer::anaglyphPass = i; - if (GameRenderer::anaglyphPass == 0) glColorMask(false, true, true, false); - else glColorMask(true, false, false, false); - } + for (int i = 0; i < 2; i++) { + if (mc->options->anaglyph3d) { + GameRenderer::anaglyphPass = i; + if (GameRenderer::anaglyphPass == 0) + glColorMask(false, true, true, false); + else + glColorMask(true, false, false, false); + } + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + } + setupClearColor(a); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glEnable(GL_CULL_FACE); - { - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - } - setupClearColor(a); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glEnable(GL_CULL_FACE); + setupCamera(a, i); + Camera::prepare(mc->player, mc->player->ThirdPersonView() == 2); - setupCamera(a, i); - Camera::prepare(mc->player, mc->player->ThirdPersonView() == 2); + Frustum::getFrustum(); + if (mc->options->viewDistance < 2) { + setupFog(-1, a); + levelRenderer->renderSky(a); + if (mc->skins->getSelected()->getId() == 1026) + levelRenderer->renderHaloRing(a); + } + // 4jcraft: needs to be enabled for proper transparent texturing on low + // render dists this was done in renderSky() for the far and normal + // dists but was missing here, UPDATE: Also needed for the nether, so + // just enable it unconditionally + glEnable(GL_ALPHA_TEST); + glEnable(GL_FOG); + setupFog(1, a); - Frustum::getFrustum(); - if (mc->options->viewDistance < 2) - { - setupFog(-1, a); - levelRenderer->renderSky(a); - if(mc->skins->getSelected()->getId() == 1026 ) levelRenderer->renderHaloRing(a); - } - // 4jcraft: needs to be enabled for proper transparent texturing on low render dists - // this was done in renderSky() for the far and normal dists but was missing here, - // UPDATE: Also needed for the nether, so just enable it unconditionally - glEnable(GL_ALPHA_TEST); - glEnable(GL_FOG); - setupFog(1, a); + if (mc->options->ambientOcclusion) { + GL11::glShadeModel(GL11::GL_SMOOTH); + } - if (mc->options->ambientOcclusion) - { - GL11::glShadeModel(GL11::GL_SMOOTH); - } + PIXBeginNamedEvent(0, "Culling"); + MemSect(31); + // Culler *frustum = new FrustumCuller(); + FrustumCuller frustObj; + Culler* frustum = &frustObj; + MemSect(0); + frustum->prepare(xOff, yOff, zOff); - PIXBeginNamedEvent(0,"Culling"); - MemSect(31); -// Culler *frustum = new FrustumCuller(); - FrustumCuller frustObj; - Culler *frustum = &frustObj; - MemSect(0); - frustum->prepare(xOff, yOff, zOff); - - mc->levelRenderer->cull(frustum, a); - PIXEndNamedEvent(); + mc->levelRenderer->cull(frustum, a); + PIXEndNamedEvent(); #ifndef MULTITHREAD_ENABLE - if ( (i == 0) && updateChunks ) // 4J - added updateChunks condition - { - int PIXPass = 0; - PIXBeginNamedEvent(0,"Updating dirty chunks"); - do - { - PIXBeginNamedEvent(0,"Updating dirty chunks pass %d",PIXPass++); - bool retval = mc->levelRenderer->updateDirtyChunks(cameraEntity, false); - PIXEndNamedEvent(); - if( retval ) break; + if ((i == 0) && updateChunks) // 4J - added updateChunks condition + { + int PIXPass = 0; + PIXBeginNamedEvent(0, "Updating dirty chunks"); + do { + PIXBeginNamedEvent(0, "Updating dirty chunks pass %d", + PIXPass++); + bool retval = + mc->levelRenderer->updateDirtyChunks(cameraEntity, false); + PIXEndNamedEvent(); + if (retval) break; + if (until == 0) break; - if (until == 0) break; - - __int64 diff = until - System::nanoTime(); - if (diff < 0) break; - if (diff > 1000000000) break; - } while (true); - PIXEndNamedEvent(); - } + __int64 diff = until - System::nanoTime(); + if (diff < 0) break; + if (diff > 1000000000) break; + } while (true); + PIXEndNamedEvent(); + } #endif - setupFog(0, a); - glEnable(GL_FOG); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Lighting::turnOff(); - PIXBeginNamedEvent(0,"Level render"); - levelRenderer->render(cameraEntity, 0, a, updateChunks); - PIXEndNamedEvent(); + setupFog(0, a); + glEnable(GL_FOG); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Lighting::turnOff(); + PIXBeginNamedEvent(0, "Level render"); + levelRenderer->render(cameraEntity, 0, a, updateChunks); + PIXEndNamedEvent(); - GL11::glShadeModel(GL11::GL_FLAT); + GL11::glShadeModel(GL11::GL_FLAT); - if (cameraFlip == 0 ) - { - Lighting::turnOn(); - PIXBeginNamedEvent(0,"Entity render"); - // 4J - for entities, don't include the "a" factor that interpolates from the old to new position, as the AABBs for the entities are already fully at the new position - // This fixes flickering minecarts, and pigs that you are riding on - frustum->prepare(cameraEntity->x,cameraEntity->y,cameraEntity->z); - // 4J Stu - When rendering entities, in the end if the dragon is hurt or we have a lot of entities we can end up wrapping - // our index into the temp Vec3 cache and overwrite the one that was storing the camera position - // Fix for #77745 - TU9: Content: Gameplay: Items and mobs not belonging to end world are disappearing when Enderdragon is damaged. - Vec3 *cameraPosTemp = cameraEntity->getPos(a); - cameraPos->x = cameraPosTemp->x; - cameraPos->y = cameraPosTemp->y; - cameraPos->z = cameraPosTemp->z; - levelRenderer->renderEntities(cameraPos, frustum, a); + if (cameraFlip == 0) { + Lighting::turnOn(); + PIXBeginNamedEvent(0, "Entity render"); + // 4J - for entities, don't include the "a" factor that interpolates + // from the old to new position, as the AABBs for the entities are + // already fully at the new position This fixes flickering + // minecarts, and pigs that you are riding on + frustum->prepare(cameraEntity->x, cameraEntity->y, cameraEntity->z); + // 4J Stu - When rendering entities, in the end if the dragon is + // hurt or we have a lot of entities we can end up wrapping our + // index into the temp Vec3 cache and overwrite the one that was + // storing the camera position Fix for #77745 - TU9: Content: + // Gameplay: Items and mobs not belonging to end world are + // disappearing when Enderdragon is damaged. + Vec3* cameraPosTemp = cameraEntity->getPos(a); + cameraPos->x = cameraPosTemp->x; + cameraPos->y = cameraPosTemp->y; + cameraPos->z = cameraPosTemp->z; + levelRenderer->renderEntities(cameraPos, frustum, a); #ifdef __PSVITA__ - // AP - make sure we're using the Alpha cut out effect for particles - glEnable(GL_ALPHA_TEST); + // AP - make sure we're using the Alpha cut out effect for particles + glEnable(GL_ALPHA_TEST); #endif - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Particle render"); - turnOnLightLayer(a); // 4J - brought forward from 1.8.2 - particleEngine->renderLit(cameraEntity, a); - Lighting::turnOff(); - setupFog(0, a); - particleEngine->render(cameraEntity, a); - PIXEndNamedEvent(); - turnOffLightLayer(a); // 4J - brought forward from 1.8.2 + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Particle render"); + turnOnLightLayer(a); // 4J - brought forward from 1.8.2 + particleEngine->renderLit(cameraEntity, a); + Lighting::turnOff(); + setupFog(0, a); + particleEngine->render(cameraEntity, a); + PIXEndNamedEvent(); + turnOffLightLayer(a); // 4J - brought forward from 1.8.2 - std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - if (mc->hitResult != NULL && cameraEntity->isUnderLiquid(Material::water) && player!=NULL) //&& !mc->options.hideGui) - { - //std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - glDisable(GL_ALPHA_TEST); - levelRenderer->renderHit(player, mc->hitResult, 0, player->inventory->getSelected(), a); - levelRenderer->renderHitOutline(player, mc->hitResult, 0, player->inventory->getSelected(), a); - glEnable(GL_ALPHA_TEST); - } - } + std::shared_ptr player = + std::dynamic_pointer_cast(cameraEntity); + if (mc->hitResult != NULL && + cameraEntity->isUnderLiquid(Material::water) && + player != NULL) //&& !mc->options.hideGui) + { + // std::shared_ptr player = + // std::dynamic_pointer_cast(cameraEntity); + glDisable(GL_ALPHA_TEST); + levelRenderer->renderHit(player, mc->hitResult, 0, + player->inventory->getSelected(), a); + levelRenderer->renderHitOutline( + player, mc->hitResult, 0, player->inventory->getSelected(), + a); + glEnable(GL_ALPHA_TEST); + } + } glDisable(GL_BLEND); glEnable(GL_CULL_FACE); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(true); - setupFog(0, a); - glEnable(GL_BLEND); - glDisable(GL_CULL_FACE); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - // 4J - have changed this fancy rendering option to work with our command buffers. The original used to use frame buffer flags to disable - // writing to colour when doing the z-only pass, but that value gets obliterated by our command buffers. Using alpha blend function instead - // to achieve the same effect. - if (true) // (mc->options->fancyGraphics) - { - if (mc->options->ambientOcclusion) - { - GL11::glShadeModel(GL11::GL_SMOOTH); - } + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthMask(true); + setupFog(0, a); + glEnable(GL_BLEND); + glDisable(GL_CULL_FACE); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + // 4J - have changed this fancy rendering option to work with our + // command buffers. The original used to use frame buffer flags to + // disable writing to colour when doing the z-only pass, but that value + // gets obliterated by our command buffers. Using alpha blend function + // instead to achieve the same effect. + if (true) // (mc->options->fancyGraphics) + { + if (mc->options->ambientOcclusion) { + GL11::glShadeModel(GL11::GL_SMOOTH); + } - glBlendFunc(GL_ZERO, GL_ONE); - PIXBeginNamedEvent(0,"Fancy second pass - writing z"); - int visibleWaterChunks = levelRenderer->render(cameraEntity, 1, a, updateChunks); - PIXEndNamedEvent(); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_ZERO, GL_ONE); + PIXBeginNamedEvent(0, "Fancy second pass - writing z"); + int visibleWaterChunks = + levelRenderer->render(cameraEntity, 1, a, updateChunks); + PIXEndNamedEvent(); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - if (visibleWaterChunks > 0) - { - PIXBeginNamedEvent(0,"Fancy second pass - actual rendering"); - levelRenderer->render(cameraEntity, 1, a, updateChunks); // 4J - chanaged, used to be renderSameAsLast but we don't support that anymore - PIXEndNamedEvent(); - } + if (visibleWaterChunks > 0) { + PIXBeginNamedEvent(0, "Fancy second pass - actual rendering"); + levelRenderer->render( + cameraEntity, 1, a, + updateChunks); // 4J - chanaged, used to be + // renderSameAsLast but we don't support + // that anymore + PIXEndNamedEvent(); + } - GL11::glShadeModel(GL11::GL_FLAT); - } - else - { - PIXBeginNamedEvent(0,"Second pass level render"); - levelRenderer->render(cameraEntity, 1, a, updateChunks); - PIXEndNamedEvent(); - } + GL11::glShadeModel(GL11::GL_FLAT); + } else { + PIXBeginNamedEvent(0, "Second pass level render"); + levelRenderer->render(cameraEntity, 1, a, updateChunks); + PIXEndNamedEvent(); + } + glDepthMask(true); + glEnable(GL_CULL_FACE); + glDisable(GL_BLEND); - glDepthMask(true); - glEnable(GL_CULL_FACE); - glDisable(GL_BLEND); + if (zoom == 1 && (std::dynamic_pointer_cast(cameraEntity) != + NULL)) //&& !mc->options.hideGui) + { + if (mc->hitResult != NULL && + !cameraEntity->isUnderLiquid(Material::water)) { + std::shared_ptr player = + std::dynamic_pointer_cast(cameraEntity); + glDisable(GL_ALPHA_TEST); + levelRenderer->renderHit(player, mc->hitResult, 0, + player->inventory->getSelected(), a); + levelRenderer->renderHitOutline( + player, mc->hitResult, 0, player->inventory->getSelected(), + a); + glEnable(GL_ALPHA_TEST); + } + } - if (zoom == 1 && (std::dynamic_pointer_cast(cameraEntity)!=NULL)) //&& !mc->options.hideGui) - { - if (mc->hitResult != NULL && !cameraEntity->isUnderLiquid(Material::water)) - { - std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - glDisable(GL_ALPHA_TEST); - levelRenderer->renderHit(player, mc->hitResult, 0, player->inventory->getSelected(), a); - levelRenderer->renderHitOutline(player, mc->hitResult, 0, player->inventory->getSelected(), a); - glEnable(GL_ALPHA_TEST); - } - } + /* 4J - moved rain rendering to after clouds so that it alpha blends + onto them properly PIXBeginNamedEvent(0,"Rendering snow and rain"); + renderSnowAndRain(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); + */ - /* 4J - moved rain rendering to after clouds so that it alpha blends onto them properly - PIXBeginNamedEvent(0,"Rendering snow and rain"); - renderSnowAndRain(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); - */ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + levelRenderer->renderDestroyAnimation( + Tesselator::getInstance(), + std::dynamic_pointer_cast(cameraEntity), a); + glDisable(GL_BLEND); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - levelRenderer->renderDestroyAnimation(Tesselator::getInstance(), std::dynamic_pointer_cast(cameraEntity), a); - glDisable(GL_BLEND); + if (mc->options->isCloudsOn()) { + glPushMatrix(); + setupFog(0, a); + glEnable(GL_FOG); + PIXBeginNamedEvent(0, "Rendering clouds"); + levelRenderer->renderClouds(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); + setupFog(1, a); + glPopMatrix(); + } - if (mc->options->isCloudsOn()) - { - glPushMatrix(); - setupFog(0, a); - glEnable(GL_FOG); - PIXBeginNamedEvent(0,"Rendering clouds"); - levelRenderer->renderClouds(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); - setupFog(1, a); - glPopMatrix(); - } + // 4J - rain rendering moved here so that it renders after clouds & can + // blend properly onto them + setupFog(0, a); + glEnable(GL_FOG); + PIXBeginNamedEvent(0, "Rendering snow and rain"); + renderSnowAndRain(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); - // 4J - rain rendering moved here so that it renders after clouds & can blend properly onto them - setupFog(0, a); - glEnable(GL_FOG); - PIXBeginNamedEvent(0,"Rendering snow and rain"); - renderSnowAndRain(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); + if (zoom == 1) { + glClear(GL_DEPTH_BUFFER_BIT); + renderItemInHand(a, i); + } - - if (zoom == 1) - { - glClear(GL_DEPTH_BUFFER_BIT); - renderItemInHand(a, i); - } - - - if (!mc->options->anaglyph3d) - { - return; - } - } - glColorMask(true, true, true, false); + if (!mc->options->anaglyph3d) { + return; + } + } + glColorMask(true, true, true, false); } -void GameRenderer::tickRain() -{ - float rainLevel = mc->level->getRainLevel(1); +void GameRenderer::tickRain() { + float rainLevel = mc->level->getRainLevel(1); - if (!mc->options->fancyGraphics) rainLevel /= 2; - if (rainLevel == 0) return; + if (!mc->options->fancyGraphics) rainLevel /= 2; + if (rainLevel == 0) return; - rainLevel /= ( mc->levelRenderer->activePlayers() + 1 ); + rainLevel /= (mc->levelRenderer->activePlayers() + 1); - random->setSeed(_tick * 312987231l); - std::shared_ptr player = mc->cameraTargetPlayer; - Level *level = mc->level; + random->setSeed(_tick * 312987231l); + std::shared_ptr player = mc->cameraTargetPlayer; + Level* level = mc->level; - int x0 = Mth::floor(player->x); - int y0 = Mth::floor(player->y); - int z0 = Mth::floor(player->z); + int x0 = Mth::floor(player->x); + int y0 = Mth::floor(player->y); + int z0 = Mth::floor(player->z); - int r = 10; + int r = 10; - double rainPosX = 0; - double rainPosY = 0; - double rainPosZ = 0; - int rainPosSamples = 0; + double rainPosX = 0; + double rainPosY = 0; + double rainPosZ = 0; + int rainPosSamples = 0; - int rainCount = (int) (100 * rainLevel * rainLevel); - if (mc->options->particles == 1) - { + int rainCount = (int)(100 * rainLevel * rainLevel); + if (mc->options->particles == 1) { rainCount >>= 1; - } else if (mc->options->particles == 2) - { + } else if (mc->options->particles == 2) { rainCount = 0; } - for (int i = 0; i < rainCount; i++) - { - int x = x0 + random->nextInt(r) - random->nextInt(r); - int z = z0 + random->nextInt(r) - random->nextInt(r); - int y = level->getTopRainBlock(x, z); - int t = level->getTile(x, y - 1, z); - Biome *biome = level->getBiome(x,z); - if (y <= y0 + r && y >= y0 - r && biome->hasRain() && biome->getTemperature() >= 0.2f) - { - float xa = random->nextFloat(); - float za = random->nextFloat(); - if (t > 0) - { - if (Tile::tiles[t]->material == Material::lava) - { - mc->particleEngine->add( std::shared_ptr( new SmokeParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, 0, 0) ) ); - } - else - { - if (random->nextInt(++rainPosSamples) == 0) - { - rainPosX = x + xa; - rainPosY = y + 0.1f - Tile::tiles[t]->getShapeY0(); - rainPosZ = z + za; - } - mc->particleEngine->add( std::shared_ptr( new WaterDropParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za) ) ); - } - } - } - } - - - if (rainPosSamples > 0 && random->nextInt(3) < rainSoundTime++) - { - rainSoundTime = 0; - MemSect(24); - if (rainPosY > player->y + 1 && level->getTopRainBlock(Mth::floor(player->x), Mth::floor(player->z)) > Mth::floor(player->y)) - { - mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, eSoundType_AMBIENT_WEATHER_RAIN, 0.1f, 0.5f); - } - else - { - mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, eSoundType_AMBIENT_WEATHER_RAIN, 0.2f, 1.0f); - } - MemSect(0); - } + for (int i = 0; i < rainCount; i++) { + int x = x0 + random->nextInt(r) - random->nextInt(r); + int z = z0 + random->nextInt(r) - random->nextInt(r); + int y = level->getTopRainBlock(x, z); + int t = level->getTile(x, y - 1, z); + Biome* biome = level->getBiome(x, z); + if (y <= y0 + r && y >= y0 - r && biome->hasRain() && + biome->getTemperature() >= 0.2f) { + float xa = random->nextFloat(); + float za = random->nextFloat(); + if (t > 0) { + if (Tile::tiles[t]->material == Material::lava) { + mc->particleEngine->add( + std::shared_ptr(new SmokeParticle( + level, x + xa, + y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, + 0, 0))); + } else { + if (random->nextInt(++rainPosSamples) == 0) { + rainPosX = x + xa; + rainPosY = y + 0.1f - Tile::tiles[t]->getShapeY0(); + rainPosZ = z + za; + } + mc->particleEngine->add(std::shared_ptr( + new WaterDropParticle( + level, x + xa, + y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za))); + } + } + } + } + if (rainPosSamples > 0 && random->nextInt(3) < rainSoundTime++) { + rainSoundTime = 0; + MemSect(24); + if (rainPosY > player->y + 1 && + level->getTopRainBlock(Mth::floor(player->x), + Mth::floor(player->z)) > + Mth::floor(player->y)) { + mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, + eSoundType_AMBIENT_WEATHER_RAIN, 0.1f, + 0.5f); + } else { + mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, + eSoundType_AMBIENT_WEATHER_RAIN, 0.2f, + 1.0f); + } + MemSect(0); + } } // 4J - this whole function updated from 1.8.2 -void GameRenderer::renderSnowAndRain(float a) -{ - float rainLevel = mc->level->getRainLevel(a); - if (rainLevel <= 0) return; +void GameRenderer::renderSnowAndRain(float a) { + float rainLevel = mc->level->getRainLevel(a); + if (rainLevel <= 0) return; - // 4J - rain is relatively low poly, but high fill-rate - better to clip it - RenderManager.StateSetEnableViewportClipPlanes(true); + // 4J - rain is relatively low poly, but high fill-rate - better to clip it + RenderManager.StateSetEnableViewportClipPlanes(true); - this->turnOnLightLayer(a); + this->turnOnLightLayer(a); - if (rainXa == NULL) - { + if (rainXa == NULL) { rainXa = new float[32 * 32]; rainZa = new float[32 * 32]; - for (int z = 0; z < 32; z++) - { - for (int x = 0; x < 32; x++) - { + for (int z = 0; z < 32; z++) { + for (int x = 0; x < 32; x++) { float xa = x - 16; float za = z - 16; float d = Mth::sqrt(xa * xa + za * za); @@ -1648,218 +1627,236 @@ void GameRenderer::renderSnowAndRain(float a) } } - std::shared_ptr player = mc->cameraTargetPlayer; - Level *level = mc->level; + std::shared_ptr player = mc->cameraTargetPlayer; + Level* level = mc->level; - int x0 = Mth::floor(player->x); - int y0 = Mth::floor(player->y); - int z0 = Mth::floor(player->z); + int x0 = Mth::floor(player->x); + int y0 = Mth::floor(player->y); + int z0 = Mth::floor(player->z); - Tesselator *t = Tesselator::getInstance(); - glDisable(GL_CULL_FACE); - glNormal3f(0, 1, 0); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glAlphaFunc(GL_GREATER, 0.01f); + Tesselator* t = Tesselator::getInstance(); + glDisable(GL_CULL_FACE); + glNormal3f(0, 1, 0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glAlphaFunc(GL_GREATER, 0.01f); - MemSect(31); - mc->textures->bindTexture(TN_ENVIRONMENT_SNOW); // 4J was L"/environment/snow.png" - MemSect(0); + MemSect(31); + mc->textures->bindTexture( + TN_ENVIRONMENT_SNOW); // 4J was L"/environment/snow.png" + MemSect(0); - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; - int yMin = Mth::floor(yo); + int yMin = Mth::floor(yo); + int r = 5; + // 4J - was if(mc.options.fancyGraphics) r = 10; + switch (mc->levelRenderer->activePlayers()) { + case 1: + default: + r = 9; + break; + case 2: + r = 7; + break; + case 3: + r = 5; + break; + case 4: + r = 5; + break; + } - int r = 5; - // 4J - was if(mc.options.fancyGraphics) r = 10; - switch( mc->levelRenderer->activePlayers() ) - { - case 1: - default: - r = 9; - break; - case 2: - r = 7; - break; - case 3: - r = 5; - break; - case 4: - r = 5; - break; - } + // 4J - some changes made here to access biome through new interface that + // caches results in levelchunk flags, as an optimisation - // 4J - some changes made here to access biome through new interface that caches results in levelchunk flags, as an optimisation - int mode = -1; float time = _tick + a; glColor4f(1, 1, 1, 1); - for (int x = x0 - r; x <= x0 + r; x++) - for (int z = z0 - r; z <= z0 + r; z++) - { + for (int x = x0 - r; x <= x0 + r; x++) + for (int z = z0 - r; z <= z0 + r; z++) { int rainSlot = (z - z0 + 16) * 32 + (x - x0 + 16); float xa = rainXa[rainSlot] * 0.5f; float za = rainZa[rainSlot] * 0.5f; - - // 4J - changes here brought forward from 1.8.2 - Biome *b = level->getBiome(x, z); - if (!b->hasRain() && !b->hasSnow()) continue; - int floor = level->getTopRainBlock(x, z); + // 4J - changes here brought forward from 1.8.2 + Biome* b = level->getBiome(x, z); + if (!b->hasRain() && !b->hasSnow()) continue; - int yy0 = y0 - r; - int yy1 = y0 + r; + int floor = level->getTopRainBlock(x, z); - if (yy0 < floor) yy0 = floor; - if (yy1 < floor) yy1 = floor; - float s = 1; + int yy0 = y0 - r; + int yy1 = y0 + r; + + if (yy0 < floor) yy0 = floor; + if (yy1 < floor) yy1 = floor; + float s = 1; int yl = floor; if (yl < yMin) yl = yMin; - if (yy0 != yy1) - { - random->setSeed((x * x * 3121 + x * 45238971) ^ (z * z * 418711 + z * 13761)); + if (yy0 != yy1) { + random->setSeed((x * x * 3121 + x * 45238971) ^ + (z * z * 418711 + z * 13761)); - // 4J - changes here brought forward from 1.8.2 - float temp = b->getTemperature(); - if (level->getBiomeSource()->scaleTemp(temp, floor) >= 0.15f) - { - if (mode != 0) - { + // 4J - changes here brought forward from 1.8.2 + float temp = b->getTemperature(); + if (level->getBiomeSource()->scaleTemp(temp, floor) >= 0.15f) { + if (mode != 0) { if (mode >= 0) t->end(); mode = 0; mc->textures->bindTexture(TN_ENVIRONMENT_RAIN); t->begin(); } - float ra = (((_tick + x * x * 3121 + x * 45238971 + z * z * 418711 + z * 13761) & 31) + a) / 32.0f * (3 + random->nextFloat()); + float ra = (((_tick + x * x * 3121 + x * 45238971 + + z * z * 418711 + z * 13761) & + 31) + + a) / + 32.0f * (3 + random->nextFloat()); - double xd = (x + 0.5f) - player->x; - double zd = (z + 0.5f) - player->z; - float dd = (float) Mth::sqrt(xd * xd + zd * zd) / r; + double xd = (x + 0.5f) - player->x; + double zd = (z + 0.5f) - player->z; + float dd = (float)Mth::sqrt(xd * xd + zd * zd) / r; float br = 1; t->offset(-xo * 1, -yo * 1, -zo * 1); #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time - float Alpha = ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel; - int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; - t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, - br, br, br, Alpha, br, br, br, 0, tex2); + // AP - this will set up the 4 vertices in half the time + float Alpha = ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel; + int tex2 = + (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; + t->tileRainQuad( + x - xa + 0.5, yy0, z - za + 0.5, 0 * s, + yy0 * s / 4.0f + ra * s, x + xa + 0.5, yy0, + z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s, + yy1 * s / 4.0f + ra * s, x - xa + 0.5, yy1, + z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, br, br, + br, Alpha, br, br, br, 0, tex2); #else t->tex2(level->getLightColor(x, yl, z, 0)); - t->color(br, br, br, ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel); - t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, yy0 * s / 4.0f + ra * s); - t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s); - // 4jcraft: this color call made rain invisible - // t->color(br, br, br, 0.0f); // 4J - added to soften the top visible edge of the rain - t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s); - t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s); + t->color(br, br, br, + ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel); + t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, + yy0 * s / 4.0f + ra * s); + t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s, + yy0 * s / 4.0f + ra * s); + // 4jcraft: this color call made rain invisible + // t->color(br, br, br, 0.0f); + // // 4J - added to soften the top visible edge of the rain + t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s, + yy1 * s / 4.0f + ra * s); + t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s, + yy1 * s / 4.0f + ra * s); #endif - t->offset(0, 0, 0); - t->end(); - } - else - { - if (mode != 1) - { + t->offset(0, 0, 0); + t->end(); + } else { + if (mode != 1) { if (mode >= 0) t->end(); mode = 1; mc->textures->bindTexture(TN_ENVIRONMENT_SNOW); t->begin(); } float ra = (((_tick) & 511) + a) / 512.0f; - float uo = random->nextFloat() + time * 0.01f * (float) random->nextGaussian(); - float vo = random->nextFloat() + time * (float) random->nextGaussian() * 0.001f; + float uo = random->nextFloat() + + time * 0.01f * (float)random->nextGaussian(); + float vo = random->nextFloat() + + time * (float)random->nextGaussian() * 0.001f; double xd = (x + 0.5f) - player->x; double zd = (z + 0.5f) - player->z; - float dd = (float) sqrt(xd * xd + zd * zd) / r; + float dd = (float)sqrt(xd * xd + zd * zd) / r; float br = 1; t->offset(-xo * 1, -yo * 1, -zo * 1); #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time - float Alpha = ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel; - int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; - t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, - br, br, br, Alpha, br, br, br, Alpha, tex2); + // AP - this will set up the 4 vertices in half the time + float Alpha = ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel; + int tex2 = + (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; + t->tileRainQuad( + x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, + yy0 * s / 4.0f + ra * s + vo, x + xa + 0.5, yy0, + z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, + yy1 * s / 4.0f + ra * s + vo, x - xa + 0.5, yy1, + z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, + br, br, br, Alpha, br, br, br, Alpha, tex2); #else - t->tex2((level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4); - t->color(br, br, br, ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel); - t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, yy0 * s / 4.0f + ra * s + vo); - t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo); - t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo); - t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo); + t->tex2((level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / + 4); + t->color(br, br, br, + ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel); + t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, + yy0 * s / 4.0f + ra * s + vo); + t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, + yy0 * s / 4.0f + ra * s + vo); + t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, + yy1 * s / 4.0f + ra * s + vo); + t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, + yy1 * s / 4.0f + ra * s + vo); #endif t->offset(0, 0, 0); } - } - } + } + } - if( mode >= 0 ) t->end(); - glEnable(GL_CULL_FACE); - glDisable(GL_BLEND); - glAlphaFunc(GL_GREATER, 0.1f); - this->turnOffLightLayer(a); + if (mode >= 0) t->end(); + glEnable(GL_CULL_FACE); + glDisable(GL_BLEND); + glAlphaFunc(GL_GREATER, 0.1f); + this->turnOffLightLayer(a); - RenderManager.StateSetEnableViewportClipPlanes(false); + RenderManager.StateSetEnableViewportClipPlanes(false); } // 4J - added forceScale parameter -void GameRenderer::setupGuiScreen(int forceScale /*=-1*/) -{ - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - ScreenSizeCalculator ssc(mc->options, mc->width, mc->height, forceScale); +void GameRenderer::setupGuiScreen(int forceScale /*=-1*/) { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + ScreenSizeCalculator ssc(mc->options, mc->width, mc->height, forceScale); - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); } -void GameRenderer::setupClearColor(float a) -{ - Level *level = mc->level; - std::shared_ptr player = mc->cameraTargetPlayer; +void GameRenderer::setupClearColor(float a) { + Level* level = mc->level; + std::shared_ptr player = mc->cameraTargetPlayer; - float whiteness = 1.0f / (4 - mc->options->viewDistance); - whiteness = 1 - (float) pow((double)whiteness, 0.25); + float whiteness = 1.0f / (4 - mc->options->viewDistance); + whiteness = 1 - (float)pow((double)whiteness, 0.25); - Vec3 *skyColor = level->getSkyColor(mc->cameraTargetPlayer, a); - float sr = (float) skyColor->x; - float sg = (float) skyColor->y; - float sb = (float) skyColor->z; + Vec3* skyColor = level->getSkyColor(mc->cameraTargetPlayer, a); + float sr = (float)skyColor->x; + float sg = (float)skyColor->y; + float sb = (float)skyColor->z; - Vec3 *fogColor = level->getFogColor(a); - fr = (float) fogColor->x; - fg = (float) fogColor->y; - fb = (float) fogColor->z; + Vec3* fogColor = level->getFogColor(a); + fr = (float)fogColor->x; + fg = (float)fogColor->y; + fb = (float)fogColor->z; - if (mc->options->viewDistance < 2) - { - Vec3 *sunAngle = Mth::sin(level->getSunAngle(a)) > 0 ? Vec3::newTemp(-1, 0, 0) : Vec3::newTemp(1, 0, 0); - float d = (float) player->getViewVector(a)->dot(sunAngle); + if (mc->options->viewDistance < 2) { + Vec3* sunAngle = Mth::sin(level->getSunAngle(a)) > 0 + ? Vec3::newTemp(-1, 0, 0) + : Vec3::newTemp(1, 0, 0); + float d = (float)player->getViewVector(a)->dot(sunAngle); if (d < 0) d = 0; - if (d > 0) - { - float *c = level->dimension->getSunriseColor(level->getTimeOfDay(a), a); - if (c != NULL) - { + if (d > 0) { + float* c = + level->dimension->getSunriseColor(level->getTimeOfDay(a), a); + if (c != NULL) { d *= c[3]; fr = fr * (1 - d) + c[0] * d; fg = fg * (1 - d) + c[1] * d; @@ -1868,83 +1865,76 @@ void GameRenderer::setupClearColor(float a) } } - fr += (sr - fr) * whiteness; - fg += (sg - fg) * whiteness; - fb += (sb - fb) * whiteness; + fr += (sr - fr) * whiteness; + fg += (sg - fg) * whiteness; + fb += (sb - fb) * whiteness; - float rainLevel = level->getRainLevel(a); - if (rainLevel > 0) - { - float ba = 1 - rainLevel * 0.5f; - float bb = 1 - rainLevel * 0.4f; - fr *= ba; - fg *= ba; - fb *= bb; - } - float thunderLevel = level->getThunderLevel(a); - if (thunderLevel > 0) - { - float ba = 1 - thunderLevel * 0.5f; - fr *= ba; - fg *= ba; - fb *= ba; - } + float rainLevel = level->getRainLevel(a); + if (rainLevel > 0) { + float ba = 1 - rainLevel * 0.5f; + float bb = 1 - rainLevel * 0.4f; + fr *= ba; + fg *= ba; + fb *= bb; + } + float thunderLevel = level->getThunderLevel(a); + if (thunderLevel > 0) { + float ba = 1 - thunderLevel * 0.5f; + fr *= ba; + fg *= ba; + fb *= ba; + } - int t = Camera::getBlockAt(mc->level, player, a); - if (isInClouds) - { - Vec3 *cc = level->getCloudColor(a); - fr = (float) cc->x; - fg = (float) cc->y; - fb = (float) cc->z; - } - else if (t != 0 && Tile::tiles[t]->material == Material::water) - { - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Water_Clear_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + int t = Camera::getBlockAt(mc->level, player, a); + if (isInClouds) { + Vec3* cc = level->getCloudColor(a); + fr = (float)cc->x; + fg = (float)cc->y; + fb = (float)cc->z; + } else if (t != 0 && Tile::tiles[t]->material == Material::water) { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Water_Clear_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - fr = (float)redComponent/256;//0.02f; - fg = (float)greenComponent/256;//0.02f; - fb = (float)blueComponent/256;//0.2f; - } - else if (t != 0 && Tile::tiles[t]->material == Material::lava) - { - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Lava_Clear_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + fr = (float)redComponent / 256; // 0.02f; + fg = (float)greenComponent / 256; // 0.02f; + fb = (float)blueComponent / 256; // 0.2f; + } else if (t != 0 && Tile::tiles[t]->material == Material::lava) { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Lava_Clear_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - fr = (float)redComponent/256;//0.6f; - fg = (float)greenComponent/256;//0.1f; - fb = (float)blueComponent/256;//0.00f; - } + fr = (float)redComponent / 256; // 0.6f; + fg = (float)greenComponent / 256; // 0.1f; + fb = (float)blueComponent / 256; // 0.00f; + } - float brr = fogBrO + (fogBr - fogBrO) * a; - fr *= brr; - fg *= brr; - fb *= brr; + float brr = fogBrO + (fogBr - fogBrO) * a; + fr *= brr; + fg *= brr; + fb *= brr; - double yy = (player->yOld + (player->y - player->yOld) * a) * level->dimension->getClearColorScale(); // 4J - getClearColorScale brought forward from 1.2.3 + double yy = + (player->yOld + (player->y - player->yOld) * a) * + level->dimension->getClearColorScale(); // 4J - getClearColorScale + // brought forward from 1.2.3 - if (player->hasEffect(MobEffect::blindness)) - { + if (player->hasEffect(MobEffect::blindness)) { int duration = player->getEffect(MobEffect::blindness)->getDuration(); - if (duration < 20) - { - yy = yy * (1.0f - (float) duration / 20.0f); - } - else - { + if (duration < 20) { + yy = yy * (1.0f - (float)duration / 20.0f); + } else { yy = 0; } } - if (yy < 1) - { + if (yy < 1) { if (yy < 0) yy = 0; yy = yy * yy; fr *= yy; @@ -1952,260 +1942,235 @@ void GameRenderer::setupClearColor(float a) fb *= yy; } - if (player->hasEffect(MobEffect::nightVision)) - { - float scale = getNightVisionScale(mc->player, a); - { - float dist = FLT_MAX; // MGH - changed this to avoid divide by zero - if ( (fr > 0) && (dist > (1.0f / fr)) ) - { - dist = (1.0f / fr); - } - if ( (fg > 0) && (dist > (1.0f / fg)) ) - { - dist = (1.0f / fg); - } - if ( (fb > 0) && (dist > (1.0f / fb)) ) - { - dist = (1.0f / fb); - } - fr = fr * (1.0f - scale) + (fr * dist) * scale; - fg = fg * (1.0f - scale) + (fg * dist) * scale; - fb = fb * (1.0f - scale) + (fb * dist) * scale; - } - } - - if (mc->options->anaglyph3d) - { - float frr = (fr * 30 + fg * 59 + fb * 11) / 100; - float fgg = (fr * 30 + fg * 70) / (100); - float fbb = (fr * 30 + fb * 70) / (100); - - fr = frr; - fg = fgg; - fb = fbb; - } - - glClearColor(fr, fg, fb, 0.0f); - -} - -void GameRenderer::setupFog(int i, float alpha) -{ - std::shared_ptr player = mc->cameraTargetPlayer; - - // 4J - check for creative mode brought forward from 1.2.3 - bool creative = false; - if (std::dynamic_pointer_cast(player) ) - { - creative = (std::dynamic_pointer_cast(player))->abilities.instabuild; + if (player->hasEffect(MobEffect::nightVision)) { + float scale = getNightVisionScale(mc->player, a); + { + float dist = FLT_MAX; // MGH - changed this to avoid divide by zero + if ((fr > 0) && (dist > (1.0f / fr))) { + dist = (1.0f / fr); + } + if ((fg > 0) && (dist > (1.0f / fg))) { + dist = (1.0f / fg); + } + if ((fb > 0) && (dist > (1.0f / fb))) { + dist = (1.0f / fb); + } + fr = fr * (1.0f - scale) + (fr * dist) * scale; + fg = fg * (1.0f - scale) + (fg * dist) * scale; + fb = fb * (1.0f - scale) + (fb * dist) * scale; + } } - if (i == 999) - { - __debugbreak(); - // 4J TODO - /* - glFog(GL_FOG_COLOR, getBuffer(0, 0, 0, 1)); - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, 0); - glFogf(GL_FOG_END, 8); + if (mc->options->anaglyph3d) { + float frr = (fr * 30 + fg * 59 + fb * 11) / 100; + float fgg = (fr * 30 + fg * 70) / (100); + float fbb = (fr * 30 + fb * 70) / (100); - if (GLContext.getCapabilities().GL_NV_fog_distance) { - glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); - } + fr = frr; + fg = fgg; + fb = fbb; + } - glFogf(GL_FOG_START, 0); - */ + glClearColor(fr, fg, fb, 0.0f); +} + +void GameRenderer::setupFog(int i, float alpha) { + std::shared_ptr player = mc->cameraTargetPlayer; + + // 4J - check for creative mode brought forward from 1.2.3 + bool creative = false; + if (std::dynamic_pointer_cast(player)) { + creative = + (std::dynamic_pointer_cast(player))->abilities.instabuild; + } + + if (i == 999) { + __debugbreak(); + // 4J TODO + /* +glFog(GL_FOG_COLOR, getBuffer(0, 0, 0, 1)); +glFogi(GL_FOG_MODE, GL_LINEAR); +glFogf(GL_FOG_START, 0); +glFogf(GL_FOG_END, 8); + +if (GLContext.getCapabilities().GL_NV_fog_distance) { + glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, +NVFogDistance.GL_EYE_RADIAL_NV); +} + +glFogf(GL_FOG_START, 0); + */ return; } - glFog(GL_FOG_COLOR, getBuffer(fr, fg, fb, 1)); - glNormal3f(0, -1, 0); - glColor4f(1, 1, 1, 1); + glFog(GL_FOG_COLOR, getBuffer(fr, fg, fb, 1)); + glNormal3f(0, -1, 0); + glColor4f(1, 1, 1, 1); int t = Camera::getBlockAt(mc->level, player, alpha); - if (player->hasEffect(MobEffect::blindness)) - { + if (player->hasEffect(MobEffect::blindness)) { float distance = 5.0f; int duration = player->getEffect(MobEffect::blindness)->getDuration(); - if (duration < 20) - { - distance = 5.0f + (renderDistance - 5.0f) * (1.0f - (float) duration / 20.0f); + if (duration < 20) { + distance = 5.0f + (renderDistance - 5.0f) * + (1.0f - (float)duration / 20.0f); } glFogi(GL_FOG_MODE, GL_LINEAR); - if (i < 0) - { + if (i < 0) { glFogf(GL_FOG_START, 0); glFogf(GL_FOG_END, distance * 0.8f); - } - else - { + } else { glFogf(GL_FOG_START, distance * 0.25f); glFogf(GL_FOG_END, distance); } - // 4J - TODO investigate implementing this -// if (GLContext.getCapabilities().GL_NV_fog_distance) -// { -// glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); -// } - } - else if (isInClouds) - { - glFogi(GL_FOG_MODE, GL_EXP); - glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_In_Cloud_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + // 4J - TODO investigate implementing this + // if (GLContext.getCapabilities().GL_NV_fog_distance) + // { + // glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, + // NVFogDistance.GL_EYE_RADIAL_NV); + // } + } else if (isInClouds) { + glFogi(GL_FOG_MODE, GL_EXP); + glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - float rr = (float)redComponent/256;//1.0f; - float gg = (float)greenComponent/256;//1.0f; - float bb = (float)blueComponent/256;//1.0f; + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_In_Cloud_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + float rr = (float)redComponent / 256; // 1.0f; + float gg = (float)greenComponent / 256; // 1.0f; + float bb = (float)blueComponent / 256; // 1.0f; - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else if (t > 0 && Tile::tiles[t]->material == Material::water) - { - glFogi(GL_FOG_MODE, GL_EXP); - if (player->hasEffect(MobEffect::waterBreathing)) - { - glFogf(GL_FOG_DENSITY, 0.05f); // was 0.06 - } - else - { - glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - } - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Water_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); - float rr = (float)redComponent/256;//0.4f; - float gg = (float)greenComponent/256;//0.4f; - float bb = (float)blueComponent/256;//0.9f; + rr = rrr; + gg = ggg; + bb = bbb; + } + } else if (t > 0 && Tile::tiles[t]->material == Material::water) { + glFogi(GL_FOG_MODE, GL_EXP); + if (player->hasEffect(MobEffect::waterBreathing)) { + glFogf(GL_FOG_DENSITY, 0.05f); // was 0.06 + } else { + glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 + } - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Water_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else if (t > 0 && Tile::tiles[t]->material == Material::lava) - { - glFogi(GL_FOG_MODE, GL_EXP); - glFogf(GL_FOG_DENSITY, 2.0f); // was 0.06 - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Lava_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + float rr = (float)redComponent / 256; // 0.4f; + float gg = (float)greenComponent / 256; // 0.4f; + float bb = (float)blueComponent / 256; // 0.9f; - float rr = (float)redComponent/256;//0.4f; - float gg = (float)greenComponent/256;//0.3f; - float bb = (float)blueComponent/256;//0.3f; + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + rr = rrr; + gg = ggg; + bb = bbb; + } + } else if (t > 0 && Tile::tiles[t]->material == Material::lava) { + glFogi(GL_FOG_MODE, GL_EXP); + glFogf(GL_FOG_DENSITY, 2.0f); // was 0.06 - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else - { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Lava_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); + + float rr = (float)redComponent / 256; // 0.4f; + float gg = (float)greenComponent / 256; // 0.3f; + float bb = (float)blueComponent / 256; // 0.3f; + + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); + + rr = rrr; + gg = ggg; + bb = bbb; + } + } else { float distance = renderDistance; - if (!mc->level->dimension->hasCeiling) - { - // 4J - test for doing bedrockfog brought forward from 1.2.3 - if (mc->level->dimension->hasBedrockFog() && !creative) - { - double yy = ((player->getLightColor(alpha) & 0xf00000) >> 20) / 16.0 + (player->yOld + (player->y - player->yOld) * alpha + 4) / 32; - if (yy < 1) - { - if (yy < 0) yy = 0; - yy = yy * yy; - float dist = 100 * (float) yy; - if (dist < 5) dist = 5; - if (distance > dist) distance = dist; - } - } - } - - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, distance * 0.25f); - glFogf(GL_FOG_END, distance); - if (i < 0) - { - glFogf(GL_FOG_START, 0); - glFogf(GL_FOG_END, distance * 0.8f); + if (!mc->level->dimension->hasCeiling) { + // 4J - test for doing bedrockfog brought forward from 1.2.3 + if (mc->level->dimension->hasBedrockFog() && !creative) { + double yy = + ((player->getLightColor(alpha) & 0xf00000) >> 20) / 16.0 + + (player->yOld + (player->y - player->yOld) * alpha + 4) / + 32; + if (yy < 1) { + if (yy < 0) yy = 0; + yy = yy * yy; + float dist = 100 * (float)yy; + if (dist < 5) dist = 5; + if (distance > dist) distance = dist; + } + } } - else - { - glFogf(GL_FOG_START, distance * 0.25f); - glFogf(GL_FOG_END, distance); + + glFogi(GL_FOG_MODE, GL_LINEAR); + glFogf(GL_FOG_START, distance * 0.25f); + glFogf(GL_FOG_END, distance); + if (i < 0) { + glFogf(GL_FOG_START, 0); + glFogf(GL_FOG_END, distance * 0.8f); + } else { + glFogf(GL_FOG_START, distance * 0.25f); + glFogf(GL_FOG_END, distance); } - /* 4J - removed - TODO investigate - if (GLContext.getCapabilities().GL_NV_fog_distance) - { - glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); - } - */ + /* 4J - removed - TODO investigate + if (GLContext.getCapabilities().GL_NV_fog_distance) + { + glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, + NVFogDistance.GL_EYE_RADIAL_NV); + } + */ - if (mc->level->dimension->isFoggyAt((int) player->x, (int) player->z)) - { - glFogf(GL_FOG_START, distance * 0.05f); - glFogf(GL_FOG_END, std::min(distance, 16 * 16 * .75f) * .5f); - } - } - - glEnable(GL_COLOR_MATERIAL); - glColorMaterial(GL_FRONT, GL_AMBIENT); + if (mc->level->dimension->isFoggyAt((int)player->x, (int)player->z)) { + glFogf(GL_FOG_START, distance * 0.05f); + glFogf(GL_FOG_END, std::min(distance, 16 * 16 * .75f) * .5f); + } + } + glEnable(GL_COLOR_MATERIAL); + glColorMaterial(GL_FRONT, GL_AMBIENT); } -FloatBuffer *GameRenderer::getBuffer(float a, float b, float c, float d) -{ - lb->clear(); - lb->put(a)->put(b)->put(c)->put(d); - lb->flip(); - return lb; +FloatBuffer* GameRenderer::getBuffer(float a, float b, float c, float d) { + lb->clear(); + lb->put(a)->put(b)->put(c)->put(d); + lb->flip(); + return lb; } -int GameRenderer::getFpsCap(int option) -{ - int maxFps = 200; - if (option == 1) maxFps = 120; - if (option == 2) maxFps = 35; - #ifndef ENABLE_VSYNC - if (option == 3) maxFps = 0; - #endif - return maxFps; +int GameRenderer::getFpsCap(int option) { + int maxFps = 200; + if (option == 1) maxFps = 120; + if (option == 2) maxFps = 35; +#ifndef ENABLE_VSYNC + if (option == 3) maxFps = 0; +#endif + return maxFps; } -void GameRenderer::updateAllChunks() -{ -// mc->levelRenderer->updateDirtyChunks(mc->cameraTargetPlayer, true); +void GameRenderer::updateAllChunks() { + // mc->levelRenderer->updateDirtyChunks(mc->cameraTargetPlayer, true); } diff --git a/Minecraft.Client/Rendering/GameRenderer.h b/Minecraft.Client/Rendering/GameRenderer.h index eec06278e..c6012c18a 100644 --- a/Minecraft.Client/Rendering/GameRenderer.h +++ b/Minecraft.Client/Rendering/GameRenderer.h @@ -12,19 +12,20 @@ class SparseDataStorage; #include "../../Minecraft.World/Util/SmoothFloat.h" #include "../../Minecraft.World/Util/C4JThread.h" -class GameRenderer -{ +class GameRenderer { public: - static bool anaglyph3d; + static bool anaglyph3d; static int anaglyphPass; private: - Minecraft *mc; + Minecraft* mc; float renderDistance; + public: - ItemInHandRenderer *itemInHandRenderer; + ItemInHandRenderer* itemInHandRenderer; + private: - int _tick; + int _tick; std::shared_ptr hovered; // smooth camera movement @@ -32,140 +33,158 @@ private: SmoothFloat smoothTurnY; // third-person distance etc - SmoothFloat smoothDistance; - SmoothFloat smoothRotation; - SmoothFloat smoothTilt; - SmoothFloat smoothRoll; - float thirdDistance; - float thirdDistanceO; - float thirdRotation; - float thirdRotationO; - float thirdTilt; - float thirdTiltO; + SmoothFloat smoothDistance; + SmoothFloat smoothRotation; + SmoothFloat smoothTilt; + SmoothFloat smoothRoll; + float thirdDistance; + float thirdDistanceO; + float thirdRotation; + float thirdRotationO; + float thirdTilt; + float thirdTiltO; float accumulatedSmoothXO, accumulatedSmoothYO; float tickSmoothXO, tickSmoothYO, lastTickA; - Vec3 *cameraPos; // 4J added + Vec3* cameraPos; // 4J added // fov modification - float fovOffset; - float fovOffsetO; + float fovOffset; + float fovOffsetO; // roll modification float cameraRoll; float cameraRollO; - // 4J - changes brought forward from 1.8.2 - static const int NUM_LIGHT_TEXTURES = 4;// * 3; - int lightTexture[NUM_LIGHT_TEXTURES]; // 4J - changed so that we have one lightTexture per level, to support split screen - int getLightTexture(int iPad, Level *level); // 4J added - intArray lightPixels[NUM_LIGHT_TEXTURES]; + // 4J - changes brought forward from 1.8.2 + static const int NUM_LIGHT_TEXTURES = 4; // * 3; + int lightTexture[NUM_LIGHT_TEXTURES]; // 4J - changed so that we have one + // lightTexture per level, to support + // split screen + int getLightTexture(int iPad, Level* level); // 4J added + intArray lightPixels[NUM_LIGHT_TEXTURES]; - float fov[4]; - float oFov[4]; - float tFov[4]; + float fov[4]; + float oFov[4]; + float tFov[4]; bool isInClouds; - float m_fov; -public: - GameRenderer(Minecraft *mc); - ~GameRenderer(); - void SetFovVal(float fov); - float GetFovVal(); + float m_fov; public: - void tick(bool bFirst); + GameRenderer(Minecraft* mc); + ~GameRenderer(); + void SetFovVal(float fov); + float GetFovVal(); + +public: + void tick(bool bFirst); void pick(float a); + private: - void tickFov(); - float getFov(float a, bool applyEffects); + void tickFov(); + float getFov(float a, bool applyEffects); void bobHurt(float a); void bobView(float a); void moveCameraToPlayer(float a); double zoom; double zoom_x; double zoom_y; + public: - void zoomRegion(double zoom, double xa, double ya); + void zoomRegion(double zoom, double xa, double ya); void unZoomRegion(); + private: - void getFovAndAspect(float& fov, float& aspect, float a, bool applyEffects); // 4J added + void getFovAndAspect(float& fov, float& aspect, float a, + bool applyEffects); // 4J added public: - void setupCamera(float a, int eye); + void setupCamera(float a, int eye); + private: void renderItemInHand(float a, int eye); __int64 lastActiveTime; __int64 lastNsTime; - // 4J - changes brought forward from 1.8.2 - bool _updateLightTexture; + // 4J - changes brought forward from 1.8.2 + bool _updateLightTexture; + public: - float blr; - float blrt; - float blg; - float blgt; - void turnOffLightLayer(double alpha); - void turnOnLightLayer(double alpha, bool scaleLight = false); + float blr; + float blrt; + float blg; + float blgt; + void turnOffLightLayer(double alpha); + void turnOnLightLayer(double alpha, bool scaleLight = false); + private: - void tickLightTexture(); - void updateLightTexture(float a); - float getNightVisionScale(std::shared_ptr player, float a); + void tickLightTexture(); + void updateLightTexture(float a); + float getNightVisionScale(std::shared_ptr player, float a); + public: - void render(float a, bool bFirst); // 4J added bFirst + void render(float a, bool bFirst); // 4J added bFirst void renderLevel(float a); void renderLevel(float a, __int64 until); + private: - Random *random; + Random* random; int rainSoundTime; void tickRain(); + private: - // 4J - brought forward from 1.8.2 - float *rainXa; - float *rainZa; + // 4J - brought forward from 1.8.2 + float* rainXa; + float* rainZa; + protected: - void renderSnowAndRain(float a); + void renderSnowAndRain(float a); volatile int xMod; volatile int yMod; -public: - void setupGuiScreen(int forceScale=-1); // 4J - added forceScale parameter - FloatBuffer *lb; +public: + void setupGuiScreen( + int forceScale = -1); // 4J - added forceScale parameter + + FloatBuffer* lb; float fr; float fg; float fb; + private: - void setupClearColor(float a); + void setupClearColor(float a); float fogBrO, fogBr; - int cameraFlip; + int cameraFlip; void setupFog(int i, float alpha); - FloatBuffer *getBuffer(float a, float b, float c, float d); - static int getFpsCap(int option); + FloatBuffer* getBuffer(float a, float b, float c, float d); + static int getFpsCap(int option); + public: - void updateAllChunks(); + void updateAllChunks(); #ifdef MULTITHREAD_ENABLE - static C4JThread* m_updateThread; - static int runUpdate(void *lpParam); - static C4JThread::EventArray* m_updateEvents; - enum EUpdateEvents - { - eUpdateCanRun, - eUpdateEventIsFinished, - eUpdateEventCount, - }; - static bool nearThingsToDo; - static bool updateRunning; + static C4JThread* m_updateThread; + static int runUpdate(void* lpParam); + static C4JThread::EventArray* m_updateEvents; + enum EUpdateEvents { + eUpdateCanRun, + eUpdateEventIsFinished, + eUpdateEventCount, + }; + static bool nearThingsToDo; + static bool updateRunning; #endif - static std::vector m_deleteStackByte; - static std::vector m_deleteStackSparseLightStorage; - static std::vector m_deleteStackCompressedTileStorage; - static std::vector m_deleteStackSparseDataStorage; - static CRITICAL_SECTION m_csDeleteStack; - static void AddForDelete(std::uint8_t *deleteThis); - static void AddForDelete(SparseLightStorage *deleteThis); - static void AddForDelete(CompressedTileStorage *deleteThis); - static void AddForDelete(SparseDataStorage *deleteThis); - static void FinishedReassigning(); - void EnableUpdateThread(); - void DisableUpdateThread(); + static std::vector m_deleteStackByte; + static std::vector m_deleteStackSparseLightStorage; + static std::vector + m_deleteStackCompressedTileStorage; + static std::vector m_deleteStackSparseDataStorage; + static CRITICAL_SECTION m_csDeleteStack; + static void AddForDelete(std::uint8_t* deleteThis); + static void AddForDelete(SparseLightStorage* deleteThis); + static void AddForDelete(CompressedTileStorage* deleteThis); + static void AddForDelete(SparseDataStorage* deleteThis); + static void FinishedReassigning(); + void EnableUpdateThread(); + void DisableUpdateThread(); }; diff --git a/Minecraft.Client/Rendering/LevelRenderer.cpp b/Minecraft.Client/Rendering/LevelRenderer.cpp index 1fb33a247..da691360b 100644 --- a/Minecraft.Client/Rendering/LevelRenderer.cpp +++ b/Minecraft.Client/Rendering/LevelRenderer.cpp @@ -65,1082 +65,1130 @@ #include "../Platform/PS3/SPU_Tasks/LevelRenderer_FindNearestChunk/LevelRenderer_FindNearestChunk.h" #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" -static LevelRenderer_cull_DataIn g_cullDataIn[4] __attribute__((__aligned__(16))); -static LevelRenderer_FindNearestChunk_DataIn g_findNearestChunkDataIn __attribute__((__aligned__(16))); +static LevelRenderer_cull_DataIn g_cullDataIn[4] + __attribute__((__aligned__(16))); +static LevelRenderer_FindNearestChunk_DataIn g_findNearestChunkDataIn + __attribute__((__aligned__(16))); #endif const unsigned int HALO_RING_RADIUS = 100; #ifdef _LARGE_WORLDS Chunk LevelRenderer::permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; -C4JThread *LevelRenderer::rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; -C4JThread::EventArray *LevelRenderer::s_rebuildCompleteEvents; -C4JThread::Event *LevelRenderer::s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; +C4JThread* LevelRenderer::rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; +C4JThread::EventArray* LevelRenderer::s_rebuildCompleteEvents; +C4JThread::Event* LevelRenderer::s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; -// This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side -// so that we can render the "infinite" sea at the edges. Currently defined as: -const int overworldSize = LEVEL_MAX_WIDTH + LevelRenderer::PLAYER_VIEW_DISTANCE + LevelRenderer::PLAYER_VIEW_DISTANCE; -const int netherSize = HELL_LEVEL_MAX_WIDTH + 2; // 4J Stu - The plus 2 is really just to make our total chunk count a multiple of 8 for the flags, we will never see these in the nether +// This defines the maximum size of renderable level, must be big enough to cope +// with actual size of level + view distance at each side so that we can render +// the "infinite" sea at the edges. Currently defined as: +const int overworldSize = LEVEL_MAX_WIDTH + + LevelRenderer::PLAYER_VIEW_DISTANCE + + LevelRenderer::PLAYER_VIEW_DISTANCE; +const int netherSize = + HELL_LEVEL_MAX_WIDTH + + 2; // 4J Stu - The plus 2 is really just to make our total chunk count a + // multiple of 8 for the flags, we will never see these in the nether const int endSize = END_LEVEL_MAX_WIDTH; -const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = { overworldSize, netherSize, endSize }; -const int LevelRenderer::DIMENSION_OFFSETS[3] = { 0, (overworldSize * overworldSize * CHUNK_Y_COUNT) , (overworldSize * overworldSize * CHUNK_Y_COUNT) + ( netherSize * netherSize * CHUNK_Y_COUNT ) }; +const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = {overworldSize, netherSize, + endSize}; +const int LevelRenderer::DIMENSION_OFFSETS[3] = { + 0, (overworldSize * overworldSize * CHUNK_Y_COUNT), + (overworldSize * overworldSize * CHUNK_Y_COUNT) + + (netherSize * netherSize * CHUNK_Y_COUNT)}; #else -// This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side -// so that we can render the "infinite" sea at the edges. Currently defined as: -// Dimension idx 0 (overworld) : 80 ( = 54 + 13 + 13 ) -// Dimension idx 1 (nether) : 44 ( = 18 + 13 + 13 ) -// Dimension idx 2 (the end) : 44 ( = 18 + 13 + 13 ) +// This defines the maximum size of renderable level, must be big enough to cope +// with actual size of level + view distance at each side so that we can render +// the "infinite" sea at the edges. Currently defined as: Dimension idx 0 +// (overworld) : 80 ( = 54 + 13 + 13 ) Dimension idx 1 (nether) : 44 ( = 18 + +// 13 + 13 ) Dimension idx 2 (the end) : 44 ( = 18 + 13 + 13 ) -const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = { 80, 44, 44 }; +const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = {80, 44, 44}; -// Linked directly to the sizes in the previous array, these next values dictate the start offset for each dimension index into the global array for these things. -// Each dimension uses MAX_LEVEL_RENDER_SIZE[i]^2 * 8 indices, as a MAX_LEVEL_RENDER_SIZE * MAX_LEVEL_RENDER_SIZE * 8 sized cube of references. +// Linked directly to the sizes in the previous array, these next values dictate +// the start offset for each dimension index into the global array for these +// things. Each dimension uses MAX_LEVEL_RENDER_SIZE[i]^2 * 8 indices, as a +// MAX_LEVEL_RENDER_SIZE * MAX_LEVEL_RENDER_SIZE * 8 sized cube of references. -const int LevelRenderer::DIMENSION_OFFSETS[3] = { 0, (80 * 80 * CHUNK_Y_COUNT) , (80 * 80 * CHUNK_Y_COUNT) + ( 44 * 44 * CHUNK_Y_COUNT ) }; +const int LevelRenderer::DIMENSION_OFFSETS[3] = { + 0, (80 * 80 * CHUNK_Y_COUNT), + (80 * 80 * CHUNK_Y_COUNT) + (44 * 44 * CHUNK_Y_COUNT)}; #endif -LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) -{ - breakingTextures = NULL; +LevelRenderer::LevelRenderer(Minecraft* mc, Textures* textures) { + breakingTextures = NULL; - for( int i = 0; i < 4; i++ ) - { - level[i] = NULL; - tileRenderer[i] = NULL; - xOld[i] = -9999; - yOld[i] = -9999; - zOld[i] = -9999; - } - xChunks= yChunks= zChunks = 0; - chunkLists = 0; + for (int i = 0; i < 4; i++) { + level[i] = NULL; + tileRenderer[i] = NULL; + xOld[i] = -9999; + yOld[i] = -9999; + zOld[i] = -9999; + } + xChunks = yChunks = zChunks = 0; + chunkLists = 0; - ticks = 0; - starList= skyList= darkList = 0; - xMinChunk= yMinChunk= zMinChunk = 0; - xMaxChunk= yMaxChunk= zMaxChunk = 0; - lastViewDistance = -1; - noEntityRenderFrames = 2; - totalEntities = 0; - renderedEntities = 0; - culledEntities = 0; - chunkFixOffs = 0; - frame = 0; - repeatList = MemoryTracker::genLists(1); + ticks = 0; + starList = skyList = darkList = 0; + xMinChunk = yMinChunk = zMinChunk = 0; + xMaxChunk = yMaxChunk = zMaxChunk = 0; + lastViewDistance = -1; + noEntityRenderFrames = 2; + totalEntities = 0; + renderedEntities = 0; + culledEntities = 0; + chunkFixOffs = 0; + frame = 0; + repeatList = MemoryTracker::genLists(1); - destroyProgress = 0.0f; + destroyProgress = 0.0f; - totalChunks= offscreenChunks= occludedChunks= renderedChunks= emptyChunks = 0; - for( int i = 0; i < 4; i++ ) - { - // sortedChunks[i] = NULL; // 4J - removed - not sorting our chunks anymore - chunks[i] = ClipChunkArray(); - lastPlayerCount[i] = 0; - } + totalChunks = offscreenChunks = occludedChunks = renderedChunks = + emptyChunks = 0; + for (int i = 0; i < 4; i++) { + // sortedChunks[i] = NULL; // 4J - removed - not sorting + //our chunks anymore + chunks[i] = ClipChunkArray(); + lastPlayerCount[i] = 0; + } - InitializeCriticalSection(&m_csDirtyChunks); - InitializeCriticalSection(&m_csRenderableTileEntities); + InitializeCriticalSection(&m_csDirtyChunks); + InitializeCriticalSection(&m_csRenderableTileEntities); #ifdef _LARGE_WORLDS - InitializeCriticalSection(&m_csChunkFlags); + InitializeCriticalSection(&m_csChunkFlags); #endif - dirtyChunkPresent = false; - lastDirtyChunkFound = 0; + dirtyChunkPresent = false; + lastDirtyChunkFound = 0; - this->mc = mc; - this->textures = textures; + this->mc = mc; + this->textures = textures; - chunkLists = MemoryTracker::genLists(getGlobalChunkCount()*2); // *2 here is because there is one renderlist per chunk here for each of the opaque & transparent layers - globalChunkFlags = new unsigned char[getGlobalChunkCount()]; - memset(globalChunkFlags, 0, getGlobalChunkCount()); + chunkLists = MemoryTracker::genLists( + getGlobalChunkCount() * + 2); // *2 here is because there is one renderlist per chunk here for + // each of the opaque & transparent layers + globalChunkFlags = new unsigned char[getGlobalChunkCount()]; + memset(globalChunkFlags, 0, getGlobalChunkCount()); - starList = MemoryTracker::genLists(4); + starList = MemoryTracker::genLists(4); - glPushMatrix(); - glNewList(starList, GL_COMPILE); - renderStars(); - glEndList(); + glPushMatrix(); + glNewList(starList, GL_COMPILE); + renderStars(); + glEndList(); - // 4J added - create geometry for rendering clouds - createCloudMesh(); + // 4J added - create geometry for rendering clouds + createCloudMesh(); - glPopMatrix(); + glPopMatrix(); + Tesselator* t = Tesselator::getInstance(); + skyList = starList + 1; + glNewList(skyList, GL_COMPILE); + glDepthMask(false); // 4J - added to get depth mask disabled within the + // command buffer + float yy; + int s = 64; + int d = (256 / s) + 2; + yy = (float)(16); + for (int xx = -s * d; xx <= s * d; xx += s) { + for (int zz = -s * d; zz <= s * d; zz += s) { + t->begin(); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + s)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + s)); + t->end(); + } + } + glEndList(); + darkList = starList + 2; + glNewList(darkList, GL_COMPILE); + yy = -(float)(16); + t->begin(); + for (int xx = -s * d; xx <= s * d; xx += s) { + for (int zz = -s * d; zz <= s * d; zz += s) { + t->vertex((float)(xx + s), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + s)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + s)); + } + } + t->end(); + glEndList(); - Tesselator *t = Tesselator::getInstance(); - skyList = starList + 1; - glNewList(skyList, GL_COMPILE); - glDepthMask(false); // 4J - added to get depth mask disabled within the command buffer - float yy; - int s = 64; - int d = (256 / s) + 2; - yy = (float) (16); - for (int xx = -s * d; xx <= s * d; xx += s) - { - for (int zz = -s * d; zz <= s * d; zz += s) - { - t->begin(); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); - t->end(); - } - } - glEndList(); + // HALO ring for the texture pack + { + const unsigned int ARC_SEGMENTS = 50; + const float VERTICAL_OFFSET = + HALO_RING_RADIUS * 999 / + 1000; // How much we raise the circle origin to make the circle + // curve back towards us + const int WIDTH = 10; + const float ARC_RADIANS = 2.0f * PI / ARC_SEGMENTS; + const float HALF_ARC_SEG = ARC_SEGMENTS / 2; + const float WIDE_ARC_SEGS = ARC_SEGMENTS / 8; + const float WIDE_ARC_SEGS_SQR = WIDE_ARC_SEGS * WIDE_ARC_SEGS; - darkList = starList + 2; - glNewList(darkList, GL_COMPILE); - yy = -(float) (16); - t->begin(); - for (int xx = -s * d; xx <= s * d; xx += s) - { - for (int zz = -s * d; zz <= s * d; zz += s) - { - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); - } - } - t->end(); - glEndList(); + float u = 0.0f; + float width = WIDTH; - // HALO ring for the texture pack - { - const unsigned int ARC_SEGMENTS = 50; - const float VERTICAL_OFFSET = HALO_RING_RADIUS * 999/1000; // How much we raise the circle origin to make the circle curve back towards us - const int WIDTH = 10; - const float ARC_RADIANS = 2.0f*PI/ARC_SEGMENTS; - const float HALF_ARC_SEG = ARC_SEGMENTS/2; - const float WIDE_ARC_SEGS = ARC_SEGMENTS/8; - const float WIDE_ARC_SEGS_SQR = WIDE_ARC_SEGS * WIDE_ARC_SEGS; + haloRingList = starList + 3; + glNewList(haloRingList, GL_COMPILE); + t->begin(GL_TRIANGLE_STRIP); + t->color(0xffffff); - float u = 0.0f; - float width = WIDTH; + for (unsigned int i = 0; i <= ARC_SEGMENTS; ++i) { + float DIFF = abs(i - HALF_ARC_SEG); + if (DIFF < (HALF_ARC_SEG - WIDE_ARC_SEGS)) + DIFF = 0; + else + DIFF -= (HALF_ARC_SEG - WIDE_ARC_SEGS); + width = 1 + ((DIFF * DIFF) / (WIDE_ARC_SEGS_SQR)) * WIDTH; + t->vertexUV( + (HALO_RING_RADIUS * cos(i * ARC_RADIANS)) - VERTICAL_OFFSET, + (HALO_RING_RADIUS * sin(i * ARC_RADIANS)), 0 - width, u, 0); + t->vertexUV( + (HALO_RING_RADIUS * cos(i * ARC_RADIANS)) - VERTICAL_OFFSET, + (HALO_RING_RADIUS * sin(i * ARC_RADIANS)), 0 + width, u, 1); + //--u; + u -= 0.25; + } + t->end(); + glEndList(); + } - haloRingList = starList + 3; - glNewList(haloRingList, GL_COMPILE); - t->begin(GL_TRIANGLE_STRIP); - t->color(0xffffff); + Chunk::levelRenderer = this; - for(unsigned int i = 0; i <= ARC_SEGMENTS; ++i) - { - float DIFF = abs(i - HALF_ARC_SEG); - if(DIFF<(HALF_ARC_SEG-WIDE_ARC_SEGS)) DIFF = 0; - else DIFF-=(HALF_ARC_SEG-WIDE_ARC_SEGS); - width = 1 + ( (DIFF * DIFF) / (WIDE_ARC_SEGS_SQR) ) * WIDTH; - t->vertexUV((HALO_RING_RADIUS * cos(i*ARC_RADIANS)) - VERTICAL_OFFSET, (HALO_RING_RADIUS * sin(i*ARC_RADIANS)), 0-width, u, 0); - t->vertexUV((HALO_RING_RADIUS * cos(i*ARC_RADIANS)) - VERTICAL_OFFSET, (HALO_RING_RADIUS * sin(i*ARC_RADIANS)), 0+width, u, 1); - //--u; - u -= 0.25; - } - t->end(); - glEndList(); - } + destroyedTileManager = new DestroyedTileManager(); - Chunk::levelRenderer = this; - - destroyedTileManager = new DestroyedTileManager(); - - dirtyChunksLockFreeStack.Initialize(); + dirtyChunksLockFreeStack.Initialize(); #ifdef __PS3__ - m_jobPort_CullSPU = new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_cull"); - m_jobPort_FindNearestChunk = new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_FindNearestChunk"); -#endif // __PS3__ + m_jobPort_CullSPU = + new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_cull"); + m_jobPort_FindNearestChunk = new C4JSpursJobQueue::Port( + "C4JSpursJob_LevelRenderer_FindNearestChunk"); +#endif // __PS3__ } -void LevelRenderer::renderStars() -{ - Random random = Random(10842); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for (int i = 0; i < 1500; i++) - { - double x = random.nextFloat() * 2 - 1; - double y = random.nextFloat() * 2 - 1; - double z = random.nextFloat() * 2 - 1; - double ss = 0.15f + random.nextFloat() * 0.10f; - double d = x * x + y * y + z * z; - if (d < 1 && d > 0.01) - { - d = 1 / sqrt(d); - x *= d; - y *= d; - z *= d; - double xp = x * 160; // 4J - moved further away (were 100) as they were cutting through far chunks - double yp = y * 160; - double zp = z * 160; +void LevelRenderer::renderStars() { + Random random = Random(10842); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int i = 0; i < 1500; i++) { + double x = random.nextFloat() * 2 - 1; + double y = random.nextFloat() * 2 - 1; + double z = random.nextFloat() * 2 - 1; + double ss = 0.15f + random.nextFloat() * 0.10f; + double d = x * x + y * y + z * z; + if (d < 1 && d > 0.01) { + d = 1 / sqrt(d); + x *= d; + y *= d; + z *= d; + double xp = x * 160; // 4J - moved further away (were 100) as they + // were cutting through far chunks + double yp = y * 160; + double zp = z * 160; - double yRot = atan2(x, z); - double ySin = sin(yRot); - double yCos = cos(yRot); + double yRot = atan2(x, z); + double ySin = sin(yRot); + double yCos = cos(yRot); - double xRot = atan2(sqrt(x * x + z * z), y); - double xSin = sin(xRot); - double xCos = cos(xRot); + double xRot = atan2(sqrt(x * x + z * z), y); + double xSin = sin(xRot); + double xCos = cos(xRot); - double zRot = random.nextDouble() * PI * 2; - double zSin = sin(zRot); - double zCos = cos(zRot); + double zRot = random.nextDouble() * PI * 2; + double zSin = sin(zRot); + double zCos = cos(zRot); - for (int c = 0; c < 4; c++) - { - double ___xo = 0; - double ___yo = ((c & 2) - 1) * ss; - double ___zo = (((c + 1) & 2) - 1) * ss; + for (int c = 0; c < 4; c++) { + double ___xo = 0; + double ___yo = ((c & 2) - 1) * ss; + double ___zo = (((c + 1) & 2) - 1) * ss; - double __xo = ___xo; - double __yo = ___yo * zCos - ___zo * zSin; - double __zo = ___zo * zCos + ___yo * zSin; + double __xo = ___xo; + double __yo = ___yo * zCos - ___zo * zSin; + double __zo = ___zo * zCos + ___yo * zSin; - double _zo = __zo; - double _yo = __yo * xSin + __xo * xCos; - double _xo = __xo * xSin - __yo * xCos; + double _zo = __zo; + double _yo = __yo * xSin + __xo * xCos; + double _xo = __xo * xSin - __yo * xCos; - double xo = _xo * ySin - _zo * yCos; - double yo = _yo; - double zo = _zo * ySin + _xo * yCos; - - t->vertex((float)(xp + xo), (float)( yp + yo), (float)( zp + zo)); - } - } - } - t->end(); + double xo = _xo * ySin - _zo * yCos; + double yo = _yo; + double zo = _zo * ySin + _xo * yCos; + t->vertex((float)(xp + xo), (float)(yp + yo), (float)(zp + zo)); + } + } + } + t->end(); } +void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel* level) { + if (this->level[playerIndex] != NULL) { + // Remove listener for this level if this is the last player referencing + // it + Level* prevLevel = this->level[playerIndex]; + int refCount = 0; + for (int i = 0; i < 4; i++) { + if (this->level[i] == prevLevel) refCount++; + } + if (refCount == 1) { + this->level[playerIndex]->removeListener(this); + } + } -void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) -{ - if (this->level[playerIndex] != NULL) - { - // Remove listener for this level if this is the last player referencing it - Level *prevLevel = this->level[playerIndex]; - int refCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( this->level[i] == prevLevel ) refCount++; - } - if( refCount == 1 ) - { - this->level[playerIndex]->removeListener(this); - } - } + xOld[playerIndex] = -9999; + yOld[playerIndex] = -9999; + zOld[playerIndex] = -9999; - xOld[playerIndex] = -9999; - yOld[playerIndex] = -9999; - zOld[playerIndex] = -9999; + this->level[playerIndex] = level; + if (tileRenderer[playerIndex] != NULL) { + delete tileRenderer[playerIndex]; + } + tileRenderer[playerIndex] = new TileRenderer(level); + if (level != NULL) { + // If we're the only player referencing this level, add a new listener + // for it + int refCount = 0; + for (int i = 0; i < 4; i++) { + if (this->level[i] == level) refCount++; + } + if (refCount == 1) { + level->addListener(this); + } - this->level[playerIndex] = level; - if( tileRenderer[playerIndex] != NULL ) - { - delete tileRenderer[playerIndex]; - } - tileRenderer[playerIndex] = new TileRenderer(level); - if (level != NULL) - { - // If we're the only player referencing this level, add a new listener for it - int refCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( this->level[i] == level ) refCount++; - } - if( refCount == 1 ) - { - level->addListener(this); - } + allChanged(playerIndex); + } else { + // printf("NULLing player %d, chunks @ + //0x%x\n",playerIndex,chunks[playerIndex]); + if (chunks[playerIndex].data != NULL) { + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + chunks[playerIndex][i].chunk->_delete(); + delete chunks[playerIndex][i].chunk; + } + delete chunks[playerIndex].data; + chunks[playerIndex].data = NULL; + chunks[playerIndex].length = 0; + // delete sortedChunks[playerIndex]; // 4J - + //removed - not sorting our chunks anymore sortedChunks[playerIndex] + //= NULL; // 4J - removed - not sorting our chunks anymore + } - allChanged(playerIndex); - } - else - { - // printf("NULLing player %d, chunks @ 0x%x\n",playerIndex,chunks[playerIndex]); - if( chunks[playerIndex].data != NULL ) - { - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - chunks[playerIndex][i].chunk->_delete(); - delete chunks[playerIndex][i].chunk; - } - delete chunks[playerIndex].data; - chunks[playerIndex].data = NULL; - chunks[playerIndex].length = 0; - // delete sortedChunks[playerIndex]; // 4J - removed - not sorting our chunks anymore - // sortedChunks[playerIndex] = NULL; // 4J - removed - not sorting our chunks anymore - } - - // 4J Stu - If we do this for splitscreen players leaving, then all the tile entities in the world dissappear - // We should only do this when actually exiting the game, so only when the primary player sets there level to NULL - if(playerIndex == ProfileManager.GetPrimaryPad()) renderableTileEntities.clear(); - } + // 4J Stu - If we do this for splitscreen players leaving, then all the + // tile entities in the world dissappear We should only do this when + // actually exiting the game, so only when the primary player sets there + // level to NULL + if (playerIndex == ProfileManager.GetPrimaryPad()) + renderableTileEntities.clear(); + } } -void LevelRenderer::AddDLCSkinsToMemTextures() -{ - for(int i=0;iaddMemTexture(app.vSkinNames[i], new MobSkinMemTextureProcessor()); - } +void LevelRenderer::AddDLCSkinsToMemTextures() { + for (int i = 0; i < app.vSkinNames.size(); i++) { + textures->addMemTexture(app.vSkinNames[i], + new MobSkinMemTextureProcessor()); + } } -void LevelRenderer::allChanged() -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added - allChanged(playerIndex); +void LevelRenderer::allChanged() { + int playerIndex = mc->player->GetXboxPad(); // 4J added + allChanged(playerIndex); } -int LevelRenderer::activePlayers() -{ - int playerCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( level[i] ) playerCount++; - } - return playerCount; +int LevelRenderer::activePlayers() { + int playerCount = 0; + for (int i = 0; i < 4; i++) { + if (level[i]) playerCount++; + } + return playerCount; } -void LevelRenderer::allChanged(int playerIndex) -{ - // 4J Stu - This was required by the threaded Minecraft::tick(). If we need to add it back then: - // If this CS is entered before DisableUpdateThread is called then (on 360 at least) we can get a - // deadlock when starting a game in splitscreen. - //EnterCriticalSection(&m_csDirtyChunks); - if( level[playerIndex] == NULL ) - { - return; - } +void LevelRenderer::allChanged(int playerIndex) { + // 4J Stu - This was required by the threaded Minecraft::tick(). If we need + // to add it back then: If this CS is entered before DisableUpdateThread is + // called then (on 360 at least) we can get a deadlock when starting a game + // in splitscreen. + // EnterCriticalSection(&m_csDirtyChunks); + if (level[playerIndex] == NULL) { + return; + } - Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); + Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); - Tile::leaves->setFancy(mc->options->fancyGraphics); - lastViewDistance = mc->options->viewDistance; + Tile::leaves->setFancy(mc->options->fancyGraphics); + lastViewDistance = mc->options->viewDistance; - // Calculate size of area we can render based on number of players we need to render for - int dist = (int)sqrtf( (float)PLAYER_RENDER_AREA / (float)activePlayers() ); + // Calculate size of area we can render based on number of players we need + // to render for + int dist = (int)sqrtf((float)PLAYER_RENDER_AREA / (float)activePlayers()); - // AP - poor little Vita just can't cope with such a big area + // AP - poor little Vita just can't cope with such a big area #ifdef __PSVITA__ - dist = 10; + dist = 10; #endif - lastPlayerCount[playerIndex] = activePlayers(); + lastPlayerCount[playerIndex] = activePlayers(); - xChunks = dist; - yChunks = Level::maxBuildHeight / CHUNK_SIZE; - zChunks = dist; + xChunks = dist; + yChunks = Level::maxBuildHeight / CHUNK_SIZE; + zChunks = dist; - if( chunks[playerIndex].data != NULL ) - { - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - chunks[playerIndex][i].chunk->_delete(); - delete chunks[playerIndex][i].chunk; - } - delete chunks[playerIndex].data; - // delete sortedChunks[playerIndex]; // 4J - removed - not sorting our chunks anymore - } + if (chunks[playerIndex].data != NULL) { + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + chunks[playerIndex][i].chunk->_delete(); + delete chunks[playerIndex][i].chunk; + } + delete chunks[playerIndex].data; + // delete sortedChunks[playerIndex]; // 4J - removed + //- not sorting our chunks anymore + } - chunks[playerIndex] = ClipChunkArray(xChunks * yChunks * zChunks); - // sortedChunks[playerIndex] = new std::vector(xChunks * yChunks * zChunks); // 4J - removed - not sorting our chunks anymore - int id = 0; - int count = 0; + chunks[playerIndex] = ClipChunkArray(xChunks * yChunks * zChunks); + // sortedChunks[playerIndex] = new std::vector(xChunks * yChunks * + //zChunks); // 4J - removed - not sorting our chunks anymore + int id = 0; + int count = 0; - xMinChunk = 0; - yMinChunk = 0; - zMinChunk = 0; - xMaxChunk = xChunks; - yMaxChunk = yChunks; - zMaxChunk = zChunks; + xMinChunk = 0; + yMinChunk = 0; + zMinChunk = 0; + xMaxChunk = xChunks; + yMaxChunk = yChunks; + zMaxChunk = zChunks; - // 4J removed - we now only fully clear this on exiting the game (setting level to NULL). Apart from that, the chunk rebuilding is responsible for maintaining this - // renderableTileEntities.clear(); + // 4J removed - we now only fully clear this on exiting the game (setting + // level to NULL). Apart from that, the chunk rebuilding is responsible for + // maintaining this + // renderableTileEntities.clear(); - for (int x = 0; x < xChunks; x++) - { - for (int y = 0; y < yChunks; y++) - { - for (int z = 0; z < zChunks; z++) - { - chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk = new Chunk(level[playerIndex], renderableTileEntities, m_csRenderableTileEntities, x * CHUNK_XZSIZE, y * CHUNK_SIZE, z * CHUNK_XZSIZE, &chunks[playerIndex][(z * yChunks + y) * xChunks + x]); - chunks[playerIndex][(z * yChunks + y) * xChunks + x].visible = true; - chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk->id = count++; - // sortedChunks[playerIndex]->at((z * yChunks + y) * xChunks + x) = chunks[playerIndex]->at((z * yChunks + y) * xChunks + x); // 4J - removed - not sorting our chunks anymore + for (int x = 0; x < xChunks; x++) { + for (int y = 0; y < yChunks; y++) { + for (int z = 0; z < zChunks; z++) { + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk = + new Chunk( + level[playerIndex], renderableTileEntities, + m_csRenderableTileEntities, x * CHUNK_XZSIZE, + y * CHUNK_SIZE, z * CHUNK_XZSIZE, + &chunks[playerIndex][(z * yChunks + y) * xChunks + x]); + chunks[playerIndex][(z * yChunks + y) * xChunks + x].visible = + true; + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk->id = + count++; + // sortedChunks[playerIndex]->at((z + //* yChunks + y) * xChunks + x) = chunks[playerIndex]->at((z * + //yChunks + y) * xChunks + x); // 4J - removed - not sorting + //our chunks anymore - id += 3; - } - } - } - nonStackDirtyChunksAdded(); + id += 3; + } + } + } + nonStackDirtyChunksAdded(); - if (level[playerIndex] != NULL) - { - std::shared_ptr player = mc->cameraTargetPlayer; - if (player != NULL) - { - this->resortChunks(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks anymore - } - } + if (level[playerIndex] != NULL) { + std::shared_ptr player = mc->cameraTargetPlayer; + if (player != NULL) { + this->resortChunks(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), + //DistanceChunkSorter(player)); // 4J - removed - not sorting + //our chunks anymore + } + } - noEntityRenderFrames = 2; + noEntityRenderFrames = 2; - Minecraft::GetInstance()->gameRenderer->EnableUpdateThread(); + Minecraft::GetInstance()->gameRenderer->EnableUpdateThread(); - // 4J Stu - Remove. See comment above. - //LeaveCriticalSection(&m_csDirtyChunks); + // 4J Stu - Remove. See comment above. + // LeaveCriticalSection(&m_csDirtyChunks); } -void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +void LevelRenderer::renderEntities(Vec3* cam, Culler* culler, float a) { + int playerIndex = mc->player->GetXboxPad(); // 4J added - // 4J Stu - Set these up every time, even when not rendering as other things (like particle render) may depend on it for those frames. - TileEntityRenderDispatcher::instance->prepare(level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, a); - EntityRenderDispatcher::instance->prepare(level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, mc->options, a); + // 4J Stu - Set these up every time, even when not rendering as other things + // (like particle render) may depend on it for those frames. + TileEntityRenderDispatcher::instance->prepare( + level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, a); + EntityRenderDispatcher::instance->prepare(level[playerIndex], textures, + mc->font, mc->cameraTargetPlayer, + mc->options, a); - if (noEntityRenderFrames > 0) - { - noEntityRenderFrames--; - return; - } + if (noEntityRenderFrames > 0) { + noEntityRenderFrames--; + return; + } - totalEntities = 0; - renderedEntities = 0; - culledEntities = 0; + totalEntities = 0; + renderedEntities = 0; + culledEntities = 0; - std::shared_ptr player = mc->cameraTargetPlayer; + std::shared_ptr player = mc->cameraTargetPlayer; - EntityRenderDispatcher::xOff = (player->xOld + (player->x - player->xOld) * a); - EntityRenderDispatcher::yOff = (player->yOld + (player->y - player->yOld) * a); - EntityRenderDispatcher::zOff = (player->zOld + (player->z - player->zOld) * a); - TileEntityRenderDispatcher::xOff = (player->xOld + (player->x - player->xOld) * a); - TileEntityRenderDispatcher::yOff = (player->yOld + (player->y - player->yOld) * a); - TileEntityRenderDispatcher::zOff = (player->zOld + (player->z - player->zOld) * a); + EntityRenderDispatcher::xOff = + (player->xOld + (player->x - player->xOld) * a); + EntityRenderDispatcher::yOff = + (player->yOld + (player->y - player->yOld) * a); + EntityRenderDispatcher::zOff = + (player->zOld + (player->z - player->zOld) * a); + TileEntityRenderDispatcher::xOff = + (player->xOld + (player->x - player->xOld) * a); + TileEntityRenderDispatcher::yOff = + (player->yOld + (player->y - player->yOld) * a); + TileEntityRenderDispatcher::zOff = + (player->zOld + (player->z - player->zOld) * a); - mc->gameRenderer->turnOnLightLayer(a, true); // 4J - brought forward from 1.8.2 + mc->gameRenderer->turnOnLightLayer( + a, true); // 4J - brought forward from 1.8.2 - std::vector > entities = level[playerIndex]->getAllEntities(); - totalEntities = (int)entities.size(); + std::vector > entities = + level[playerIndex]->getAllEntities(); + totalEntities = (int)entities.size(); - AUTO_VAR(itEndGE, level[playerIndex]->globalEntities.end()); - for (AUTO_VAR(it, level[playerIndex]->globalEntities.begin()); it != itEndGE; it++) - { - std::shared_ptr entity = *it; //level->globalEntities[i]; - renderedEntities++; - if (entity->shouldRender(cam)) EntityRenderDispatcher::instance->render(entity, a); - } + AUTO_VAR(itEndGE, level[playerIndex]->globalEntities.end()); + for (AUTO_VAR(it, level[playerIndex]->globalEntities.begin()); + it != itEndGE; it++) { + std::shared_ptr entity = *it; // level->globalEntities[i]; + renderedEntities++; + if (entity->shouldRender(cam)) + EntityRenderDispatcher::instance->render(entity, a); + } - AUTO_VAR(itEndEnts, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEndEnts; it++) - { - std::shared_ptr entity = *it; //entities[i]; + AUTO_VAR(itEndEnts, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEndEnts; it++) { + std::shared_ptr entity = *it; // entities[i]; - if ((entity->shouldRender(cam) && (entity->noCulling || culler->isVisible(entity->bb)))) - { - // 4J-PB - changing this to be per player - //if (entity == mc->cameraTargetPlayer && !mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) continue; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); + if ((entity->shouldRender(cam) && + (entity->noCulling || culler->isVisible(entity->bb)))) { + // 4J-PB - changing this to be per player + // if (entity == mc->cameraTargetPlayer && + // !mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) continue; + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - if (localplayer && entity == mc->cameraTargetPlayer && !localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) continue; + if (localplayer && entity == mc->cameraTargetPlayer && + !localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) + continue; - if (!level[playerIndex]->hasChunkAt(Mth::floor(entity->x), 0, Mth::floor(entity->z))) - { - continue; - } - renderedEntities++; - EntityRenderDispatcher::instance->render(entity, a); - } - } + if (!level[playerIndex]->hasChunkAt(Mth::floor(entity->x), 0, + Mth::floor(entity->z))) { + continue; + } + renderedEntities++; + EntityRenderDispatcher::instance->render(entity, a); + } + } - Lighting::turnOn(); - // 4J - have restructed this so that the tile entities are stored within a hashmap by chunk/dimension index. The index - // is calculated in the same way as the global flags. - EnterCriticalSection(&m_csRenderableTileEntities); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end(); it++) - { - int idx = it->first; - // Don't render if it isn't in the same dimension as this player - if( !isGlobalIndexInSameDimension(idx, level[playerIndex]) ) continue; + Lighting::turnOn(); + // 4J - have restructed this so that the tile entities are stored within a + // hashmap by chunk/dimension index. The index is calculated in the same way + // as the global flags. + EnterCriticalSection(&m_csRenderableTileEntities); + for (AUTO_VAR(it, renderableTileEntities.begin()); + it != renderableTileEntities.end(); it++) { + int idx = it->first; + // Don't render if it isn't in the same dimension as this player + if (!isGlobalIndexInSameDimension(idx, level[playerIndex])) continue; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++) - { - TileEntityRenderDispatcher::instance->render(*it2, a); - } - } + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + TileEntityRenderDispatcher::instance->render(*it2, a); + } + } - // Now consider if any of these renderable tile entities have been flagged for removal, and if so, remove - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end();) - { - int idx = it->first; + // Now consider if any of these renderable tile entities have been flagged + // for removal, and if so, remove + for (AUTO_VAR(it, renderableTileEntities.begin()); + it != renderableTileEntities.end();) { + int idx = it->first; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); ) - { - // If it has been flagged for removal, remove - if((*it2)->shouldRemoveForRender()) - { - it2 = it->second.erase(it2); - } - else - { - it2++; - } - } + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end();) { + // If it has been flagged for removal, remove + if ((*it2)->shouldRemoveForRender()) { + it2 = it->second.erase(it2); + } else { + it2++; + } + } - // If there aren't any entities left for this key, then delete the key - if( it->second.size() == 0 ) - { - it = renderableTileEntities.erase(it); - } - else - { - it++; - } - } + // If there aren't any entities left for this key, then delete the key + if (it->second.size() == 0) { + it = renderableTileEntities.erase(it); + } else { + it++; + } + } - LeaveCriticalSection(&m_csRenderableTileEntities); + LeaveCriticalSection(&m_csRenderableTileEntities); - mc->gameRenderer->turnOffLightLayer(a); // 4J - brought forward from 1.8.2 + mc->gameRenderer->turnOffLightLayer(a); // 4J - brought forward from 1.8.2 } -std::wstring LevelRenderer::gatherStats1() -{ - return L"C: " + _toString(renderedChunks) + L"/" + _toString(totalChunks) + L". F: " + _toString(offscreenChunks) + L", O: " + _toString(occludedChunks) + L", E: " + _toString(emptyChunks); +std::wstring LevelRenderer::gatherStats1() { + return L"C: " + _toString(renderedChunks) + L"/" + + _toString(totalChunks) + L". F: " + + _toString(offscreenChunks) + L", O: " + + _toString(occludedChunks) + L", E: " + + _toString(emptyChunks); } -std::wstring LevelRenderer::gatherStats2() -{ - return L"E: " + _toString(renderedEntities) + L"/" + _toString(totalEntities) + L". B: " + _toString(culledEntities) + L", I: " + _toString((totalEntities - culledEntities) - renderedEntities); +std::wstring LevelRenderer::gatherStats2() { + return L"E: " + _toString(renderedEntities) + L"/" + + _toString(totalEntities) + L". B: " + + _toString(culledEntities) + L", I: " + + _toString((totalEntities - culledEntities) - renderedEntities); } -void LevelRenderer::resortChunks(int xc, int yc, int zc) -{ - EnterCriticalSection(&m_csDirtyChunks); - xc -= CHUNK_XZSIZE / 2; - yc -= CHUNK_SIZE / 2; - zc -= CHUNK_XZSIZE / 2; - xMinChunk = INT_MAX; - yMinChunk = INT_MAX; - zMinChunk = INT_MAX; - xMaxChunk = INT_MIN; - yMaxChunk = INT_MIN; - zMaxChunk = INT_MIN; +void LevelRenderer::resortChunks(int xc, int yc, int zc) { + EnterCriticalSection(&m_csDirtyChunks); + xc -= CHUNK_XZSIZE / 2; + yc -= CHUNK_SIZE / 2; + zc -= CHUNK_XZSIZE / 2; + xMinChunk = INT_MAX; + yMinChunk = INT_MAX; + zMinChunk = INT_MAX; + xMaxChunk = INT_MIN; + yMaxChunk = INT_MIN; + zMaxChunk = INT_MIN; - int playerIndex = mc->player->GetXboxPad(); // 4J added + int playerIndex = mc->player->GetXboxPad(); // 4J added - int s2 = xChunks * CHUNK_XZSIZE; - int s1 = s2 / 2; + int s2 = xChunks * CHUNK_XZSIZE; + int s1 = s2 / 2; - for (int x = 0; x < xChunks; x++) - { - int xx = x * CHUNK_XZSIZE; + for (int x = 0; x < xChunks; x++) { + int xx = x * CHUNK_XZSIZE; - int xOff = (xx + s1 - xc); - if (xOff < 0) xOff -= (s2 - 1); - xOff /= s2; - xx -= xOff * s2; + int xOff = (xx + s1 - xc); + if (xOff < 0) xOff -= (s2 - 1); + xOff /= s2; + xx -= xOff * s2; - if (xx < xMinChunk) xMinChunk = xx; - if (xx > xMaxChunk) xMaxChunk = xx; + if (xx < xMinChunk) xMinChunk = xx; + if (xx > xMaxChunk) xMaxChunk = xx; - for (int z = 0; z < zChunks; z++) - { - int zz = z * CHUNK_XZSIZE; - int zOff = (zz + s1 - zc); - if (zOff < 0) zOff -= (s2 - 1); - zOff /= s2; - zz -= zOff * s2; + for (int z = 0; z < zChunks; z++) { + int zz = z * CHUNK_XZSIZE; + int zOff = (zz + s1 - zc); + if (zOff < 0) zOff -= (s2 - 1); + zOff /= s2; + zz -= zOff * s2; - if (zz < zMinChunk) zMinChunk = zz; - if (zz > zMaxChunk) zMaxChunk = zz; + if (zz < zMinChunk) zMinChunk = zz; + if (zz > zMaxChunk) zMaxChunk = zz; - for (int y = 0; y < yChunks; y++) - { - int yy = y * CHUNK_SIZE; - if (yy < yMinChunk) yMinChunk = yy; - if (yy > yMaxChunk) yMaxChunk = yy; + for (int y = 0; y < yChunks; y++) { + int yy = y * CHUNK_SIZE; + if (yy < yMinChunk) yMinChunk = yy; + if (yy > yMaxChunk) yMaxChunk = yy; - Chunk *chunk = chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk; - chunk->setPos(xx, yy, zz); - } - } - } - nonStackDirtyChunksAdded(); - LeaveCriticalSection(&m_csDirtyChunks); + Chunk* chunk = + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk; + chunk->setPos(xx, yy, zz); + } + } + } + nonStackDirtyChunksAdded(); + LeaveCriticalSection(&m_csDirtyChunks); } -int LevelRenderer::render(std::shared_ptr player, int layer, double alpha, bool updateChunks) -{ - int playerIndex = mc->player->GetXboxPad(); +int LevelRenderer::render(std::shared_ptr player, int layer, double alpha, + bool updateChunks) { + int playerIndex = mc->player->GetXboxPad(); - // 4J - added - if the number of players has changed, we need to rebuild things for the new draw distance this will require - if( lastPlayerCount[playerIndex] != activePlayers() ) - { - allChanged(); - } - else if (mc->options->viewDistance != lastViewDistance) - { - allChanged(); - } + // 4J - added - if the number of players has changed, we need to rebuild + // things for the new draw distance this will require + if (lastPlayerCount[playerIndex] != activePlayers()) { + allChanged(); + } else if (mc->options->viewDistance != lastViewDistance) { + allChanged(); + } - if (layer == 0) - { - totalChunks = 0; - offscreenChunks = 0; - occludedChunks = 0; - renderedChunks = 0; - emptyChunks = 0; - } + if (layer == 0) { + totalChunks = 0; + offscreenChunks = 0; + occludedChunks = 0; + renderedChunks = 0; + emptyChunks = 0; + } - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - double xd = player->x - xOld[playerIndex]; - double yd = player->y - yOld[playerIndex]; - double zd = player->z - zOld[playerIndex]; + double xd = player->x - xOld[playerIndex]; + double yd = player->y - yOld[playerIndex]; + double zd = player->z - zOld[playerIndex]; - if (xd * xd + yd * yd + zd * zd > 4 * 4) - { - xOld[playerIndex] = player->x; - yOld[playerIndex] = player->y; - zOld[playerIndex] = player->z; + if (xd * xd + yd * yd + zd * zd > 4 * 4) { + xOld[playerIndex] = player->x; + yOld[playerIndex] = player->y; + zOld[playerIndex] = player->z; - resortChunks(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks anymore - } - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); - glColor4f(1, 1, 1, 1); + resortChunks(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), + //DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks + //anymore + } + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); - int count = renderChunks(0, (int)chunks[playerIndex].length, layer, alpha); - - return count; + int count = renderChunks(0, (int)chunks[playerIndex].length, layer, alpha); + return count; } #ifdef __PSVITA__ #include // this is need to sort the chunks by depth -typedef struct -{ - int Index; - float Depth; +typedef struct { + int Index; + float Depth; } SChunckSort; -int compare (const void * a, const void * b) -{ - return ( ((SChunckSort*)a)->Depth - ((SChunckSort*)b)->Depth ); +int compare(const void* a, const void* b) { + return (((SChunckSort*)a)->Depth - ((SChunckSort*)b)->Depth); } #endif -int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) { + int playerIndex = mc->player->GetXboxPad(); // 4J added #if 1 - // 4J - cut down version, we're not using offsetted render lists, or a sorted chunk list, anymore - mc->gameRenderer->turnOnLightLayer(alpha); // 4J - brought forward from 1.8.2 - std::shared_ptr player = mc->cameraTargetPlayer; - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + // 4J - cut down version, we're not using offsetted render lists, or a + // sorted chunk list, anymore + mc->gameRenderer->turnOnLightLayer( + alpha); // 4J - brought forward from 1.8.2 + std::shared_ptr player = mc->cameraTargetPlayer; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - glPushMatrix(); - glTranslatef((float)-xOff, (float)-yOff, (float)-zOff); + glPushMatrix(); + glTranslatef((float)-xOff, (float)-yOff, (float)-zOff); #ifdef __PSVITA__ - // AP - also set the camera position so we can work out if a chunk is fogged or not - RenderManager.SetCameraPosition((float)-xOff, (float)-yOff, (float)-zOff); + // AP - also set the camera position so we can work out if a chunk is fogged + // or not + RenderManager.SetCameraPosition((float)-xOff, (float)-yOff, (float)-zOff); #endif #if defined __PS3__ && !defined DISABLE_SPU_CODE - // pre- calc'd on the SPU - int count = 0; - waitForCull_SPU(); - if(layer == 0) - { - count = g_cullDataIn[playerIndex].numToRender_layer0; - RenderManager.CBuffCallMultiple(g_cullDataIn[playerIndex].listArray_layer0, count); - } - else // layer == 1 - { - count = g_cullDataIn[playerIndex].numToRender_layer1; - RenderManager.CBuffCallMultiple(g_cullDataIn[playerIndex].listArray_layer1, count); - } + // pre- calc'd on the SPU + int count = 0; + waitForCull_SPU(); + if (layer == 0) { + count = g_cullDataIn[playerIndex].numToRender_layer0; + RenderManager.CBuffCallMultiple( + g_cullDataIn[playerIndex].listArray_layer0, count); + } else // layer == 1 + { + count = g_cullDataIn[playerIndex].numToRender_layer1; + RenderManager.CBuffCallMultiple( + g_cullDataIn[playerIndex].listArray_layer1, count); + } -#else // __PS3__ +#else // __PS3__ #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. First render all the non-alpha cut outs - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. First render all the non-alpha + // cut outs + glDisable(GL_ALPHA_TEST); #endif - bool first = true; - int count = 0; - int dbgNotVisible = 0, dbgNoIdx = 0, dbgEmpty = 0, dbgCalled = 0, dbgCallOk = 0; - ClipChunk *pClipChunk = chunks[playerIndex].data; - unsigned char emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; - for( int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++ ) - { - if( !pClipChunk->visible ) { dbgNotVisible++; continue; } - if( pClipChunk->globalIdx == -1 ) { dbgNoIdx++; continue; } - if( ( globalChunkFlags[pClipChunk->globalIdx] & emptyFlag ) == emptyFlag ) { dbgEmpty++; continue; } + bool first = true; + int count = 0; + int dbgNotVisible = 0, dbgNoIdx = 0, dbgEmpty = 0, dbgCalled = 0, + dbgCallOk = 0; + ClipChunk* pClipChunk = chunks[playerIndex].data; + unsigned char emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; + for (int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++) { + if (!pClipChunk->visible) { + dbgNotVisible++; + continue; + } + if (pClipChunk->globalIdx == -1) { + dbgNoIdx++; + continue; + } + if ((globalChunkFlags[pClipChunk->globalIdx] & emptyFlag) == + emptyFlag) { + dbgEmpty++; + continue; + } - // List can be calculated directly from the chunk's global idex - int list = pClipChunk->globalIdx * 2 + layer; - list += chunkLists; + // List can be calculated directly from the chunk's global idex + int list = pClipChunk->globalIdx * 2 + layer; + list += chunkLists; - dbgCalled++; - if(RenderManager.CBuffCall(list, first)) - { - first = false; - dbgCallOk++; - } - count++; - } - static int _dbgRC = 0; - _dbgRC++; - if (_dbgRC <= 2 || (_dbgRC % 3000 == 0)) { - fprintf(stderr, "[RENDER] renderChunks frame=%d layer=%d total=%d notVis=%d noIdx=%d empty=%d called=%d callOk=%d chunkLists=%d\n", - _dbgRC, layer, chunks[playerIndex].length, dbgNotVisible, dbgNoIdx, dbgEmpty, dbgCalled, dbgCallOk, chunkLists); - fflush(stderr); - } + dbgCalled++; + if (RenderManager.CBuffCall(list, first)) { + first = false; + dbgCallOk++; + } + count++; + } + static int _dbgRC = 0; + _dbgRC++; + if (_dbgRC <= 2 || (_dbgRC % 3000 == 0)) { + fprintf(stderr, + "[RENDER] renderChunks frame=%d layer=%d total=%d notVis=%d " + "noIdx=%d empty=%d called=%d callOk=%d chunkLists=%d\n", + _dbgRC, layer, chunks[playerIndex].length, dbgNotVisible, + dbgNoIdx, dbgEmpty, dbgCalled, dbgCallOk, chunkLists); + fflush(stderr); + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Now we render all the alpha cut outs - glEnable(GL_ALPHA_TEST); - RenderManager.StateSetForceLOD(0); // AP - force mipmapping off for cut outs - first = true; - pClipChunk = chunks[playerIndex].data; - emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; - for( int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++ ) - { - if( !pClipChunk->visible ) continue; // This will be set if the chunk isn't visible, or isn't compiled, or has both empty flags set - if( pClipChunk->globalIdx == -1 ) continue; // Not sure if we should ever encounter this... TODO check - if( ( globalChunkFlags[pClipChunk->globalIdx] & emptyFlag ) == emptyFlag ) continue; // Check that this particular layer isn't empty - if( !(globalChunkFlags[pClipChunk->globalIdx] & LevelRenderer::CHUNK_FLAG_CUT_OUT) ) continue; // Does this chunk contain any cut out geometry + // AP - alpha cut out is expensive on vita. Now we render all the alpha cut + // outs + glEnable(GL_ALPHA_TEST); + RenderManager.StateSetForceLOD( + 0); // AP - force mipmapping off for cut outs + first = true; + pClipChunk = chunks[playerIndex].data; + emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; + for (int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++) { + if (!pClipChunk->visible) + continue; // This will be set if the chunk isn't visible, or isn't + // compiled, or has both empty flags set + if (pClipChunk->globalIdx == -1) + continue; // Not sure if we should ever encounter this... TODO + // check + if ((globalChunkFlags[pClipChunk->globalIdx] & emptyFlag) == emptyFlag) + continue; // Check that this particular layer isn't empty + if (!(globalChunkFlags[pClipChunk->globalIdx] & + LevelRenderer::CHUNK_FLAG_CUT_OUT)) + continue; // Does this chunk contain any cut out geometry - // List can be calculated directly from the chunk's global idex - int list = pClipChunk->globalIdx * 2 + layer; - list += chunkLists; + // List can be calculated directly from the chunk's global idex + int list = pClipChunk->globalIdx * 2 + layer; + list += chunkLists; - if(RenderManager.CBuffCallCutOut(list, first)) - { - first = false; - } - } - RenderManager.StateSetForceLOD(-1); // AP - back to normal mipmapping + if (RenderManager.CBuffCallCutOut(list, first)) { + first = false; + } + } + RenderManager.StateSetForceLOD(-1); // AP - back to normal mipmapping #endif -#endif // __PS3__ +#endif // __PS3__ - glPopMatrix(); - mc->gameRenderer->turnOffLightLayer(alpha); // 4J - brought forward from 1.8.2 + glPopMatrix(); + mc->gameRenderer->turnOffLightLayer( + alpha); // 4J - brought forward from 1.8.2 #else - _renderChunks.clear(); - // int p = 0; - int count = 0; - for (int i = from; i < to; i++) - { - if (layer == 0) - { - totalChunks++; - if (sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer)) emptyChunks++; - else if (!sortedChunks[playerIndex]->at(i)->visible) offscreenChunks++; - else renderedChunks++; - } + _renderChunks.clear(); + // int p = 0; + int count = 0; + for (int i = from; i < to; i++) { + if (layer == 0) { + totalChunks++; + if (sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer)) + emptyChunks++; + else if (!sortedChunks[playerIndex]->at(i)->visible) + offscreenChunks++; + else + renderedChunks++; + } - // if (!sortedChunks[i].empty[layer] && sortedChunks[i].visible && (sortedChunks[i].occlusion_visible)) { - if (!(sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer) && sortedChunks[playerIndex]->at(i)->visible )) - { - int list = sortedChunks[playerIndex]->at(i)->getList(layer); - if (list >= 0) - { - _renderChunks.push_back(sortedChunks[playerIndex]->at(i)); - count++; - } - } - } + // if (!sortedChunks[i].empty[layer] && + // sortedChunks[i].visible && + // (sortedChunks[i].occlusion_visible)) { + if (!(sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer) && + sortedChunks[playerIndex]->at(i)->visible)) { + int list = sortedChunks[playerIndex]->at(i)->getList(layer); + if (list >= 0) { + _renderChunks.push_back(sortedChunks[playerIndex]->at(i)); + count++; + } + } + } - std::shared_ptr player = mc->cameraTargetPlayer; - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + std::shared_ptr player = mc->cameraTargetPlayer; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - int lists = 0; - for (int l = 0; l < RENDERLISTS_LENGTH; l++) - { - renderLists[l].clear(); - } + int lists = 0; + for (int l = 0; l < RENDERLISTS_LENGTH; l++) { + renderLists[l].clear(); + } - AUTO_VAR(itEnd, _renderChunks.end()); - for (AUTO_VAR(it, _renderChunks.begin()); it != itEnd; it++) - { - Chunk *chunk = *it; //_renderChunks[i]; + AUTO_VAR(itEnd, _renderChunks.end()); + for (AUTO_VAR(it, _renderChunks.begin()); it != itEnd; it++) { + Chunk* chunk = *it; //_renderChunks[i]; - int list = -1; - for (int l = 0; l < lists; l++) - { - if (renderLists[l].isAt(chunk->xRender, chunk->yRender, chunk->zRender)) - { - list = l; - } - } - if (list < 0) - { - list = lists++; - renderLists[list].init(chunk->xRender, chunk->yRender, chunk->zRender, xOff, yOff, zOff); - } + int list = -1; + for (int l = 0; l < lists; l++) { + if (renderLists[l].isAt(chunk->xRender, chunk->yRender, + chunk->zRender)) { + list = l; + } + } + if (list < 0) { + list = lists++; + renderLists[list].init(chunk->xRender, chunk->yRender, + chunk->zRender, xOff, yOff, zOff); + } - renderLists[list].add(chunk->getList(layer)); - } + renderLists[list].add(chunk->getList(layer)); + } - renderSameAsLast(layer, alpha); + renderSameAsLast(layer, alpha); #endif - return count; - + return count; } - -void LevelRenderer::renderSameAsLast(int layer, double alpha) -{ - for (int i = 0; i < RENDERLISTS_LENGTH; i++) - { - renderLists[i].render(); - } +void LevelRenderer::renderSameAsLast(int layer, double alpha) { + for (int i = 0; i < RENDERLISTS_LENGTH; i++) { + renderLists[i].render(); + } } -void LevelRenderer::tick() -{ - ticks++; +void LevelRenderer::tick() { + ticks++; - if ((ticks % SharedConstants::TICKS_PER_SECOND) == 0) - { - AUTO_VAR(it , destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) - { - BlockDestructionProgress *block = it->second; + if ((ticks % SharedConstants::TICKS_PER_SECOND) == 0) { + AUTO_VAR(it, destroyingBlocks.begin()); + while (it != destroyingBlocks.end()) { + BlockDestructionProgress* block = it->second; - int updatedRenderTick = block->getUpdatedRenderTick(); + int updatedRenderTick = block->getUpdatedRenderTick(); - if (ticks - updatedRenderTick > (SharedConstants::TICKS_PER_SECOND * 20)) - { - delete it->second; - it = destroyingBlocks.erase(it); - } - else - { - ++it; - } - } - } + if (ticks - updatedRenderTick > + (SharedConstants::TICKS_PER_SECOND * 20)) { + delete it->second; + it = destroyingBlocks.erase(it); + } else { + ++it; + } + } + } } -void LevelRenderer::renderSky(float alpha) -{ - if (mc->level->dimension->id == 1) - { - glDisable(GL_FOG); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); +void LevelRenderer::renderSky(float alpha) { + if (mc->level->dimension->id == 1) { + glDisable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); + glDepthMask(false); + textures->bind(textures->loadTexture( + TN_MISC_TUNNEL)); // 4J was L"/1_2_2/misc/tunnel.png" + Tesselator* t = Tesselator::getInstance(); + t->setMipmapEnable(false); + for (int i = 0; i < 6; i++) { + glPushMatrix(); + if (i == 1) glRotatef(90, 1, 0, 0); + if (i == 2) glRotatef(-90, 1, 0, 0); + if (i == 3) glRotatef(180, 1, 0, 0); + if (i == 4) glRotatef(90, 0, 0, 1); + if (i == 5) glRotatef(-90, 0, 0, 1); + t->begin(); + t->color(0x282828); + t->vertexUV(-100, -100, -100, 0, 0); + t->vertexUV(-100, -100, +100, 0, 16); + t->vertexUV(+100, -100, +100, 16, 16); + t->vertexUV(+100, -100, -100, 16, 0); + t->end(); + glPopMatrix(); + } + t->setMipmapEnable(true); + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); - glDepthMask(false); - textures->bind(textures->loadTexture(TN_MISC_TUNNEL)); // 4J was L"/1_2_2/misc/tunnel.png" - Tesselator *t = Tesselator::getInstance(); - t->setMipmapEnable(false); - for (int i = 0; i < 6; i++) - { - glPushMatrix(); - if (i == 1) glRotatef(90, 1, 0, 0); - if (i == 2) glRotatef(-90, 1, 0, 0); - if (i == 3) glRotatef(180, 1, 0, 0); - if (i == 4) glRotatef(90, 0, 0, 1); - if (i == 5) glRotatef(-90, 0, 0, 1); - t->begin(); - t->color(0x282828); - t->vertexUV(-100, -100, -100, 0, 0); - t->vertexUV(-100, -100, +100, 0, 16); - t->vertexUV(+100, -100, +100, 16, 16); - t->vertexUV(+100, -100, -100, 16, 0); - t->end(); - glPopMatrix(); - } - t->setMipmapEnable(true); - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); + return; + } - return; - } + if (!mc->level->dimension->isNaturalDimension()) return; - if (!mc->level->dimension->isNaturalDimension()) return; + glDisable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_2D); + int playerIndex = mc->player->GetXboxPad(); + Vec3* sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); + float sr = (float)sc->x; + float sg = (float)sc->y; + float sb = (float)sc->z; - int playerIndex = mc->player->GetXboxPad(); - Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + if (mc->options->anaglyph3d) { + float srr = (sr * 30 + sg * 59 + sb * 11) / 100; + float sgg = (sr * 30 + sg * 70) / (100); + float sbb = (sr * 30 + sb * 70) / (100); - if (mc->options->anaglyph3d) - { - float srr = (sr * 30 + sg * 59 + sb * 11) / 100; - float sgg = (sr * 30 + sg * 70) / (100); - float sbb = (sr * 30 + sb * 70) / (100); + sr = srr; + sg = sgg; + sb = sbb; + } - sr = srr; - sg = sgg; - sb = sbb; - } + glColor3f(sr, sg, sb); - glColor3f(sr, sg, sb); + Tesselator* t = Tesselator::getInstance(); - Tesselator *t = Tesselator::getInstance(); - - glDepthMask(false); + glDepthMask(false); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. + glDisable(GL_ALPHA_TEST); #endif - glEnable(GL_FOG); - glColor3f(sr, sg, sb); - glCallList(skyList); + glEnable(GL_FOG); + glColor3f(sr, sg, sb); + glCallList(skyList); - glDisable(GL_FOG); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); + glDisable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); - float *c = level[playerIndex]->dimension->getSunriseColor(level[playerIndex]->getTimeOfDay(alpha), alpha); - if (c != NULL) - { - glDisable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); + float* c = level[playerIndex]->dimension->getSunriseColor( + level[playerIndex]->getTimeOfDay(alpha), alpha); + if (c != NULL) { + glDisable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); - glPushMatrix(); - { - glRotatef(90, 1, 0, 0); - glRotatef(Mth::sin(level[playerIndex]->getSunAngle(alpha)) < 0 ? 180 : 0, 0, 0, 1); - glRotatef(90, 0, 0, 1); + glPushMatrix(); + { + glRotatef(90, 1, 0, 0); + glRotatef( + Mth::sin(level[playerIndex]->getSunAngle(alpha)) < 0 ? 180 : 0, + 0, 0, 1); + glRotatef(90, 0, 0, 1); - float r = c[0]; - float g = c[1]; - float b = c[2]; - if (mc->options->anaglyph3d) - { - float srr = (r * 30 + g * 59 + b * 11) / 100; - float sgg = (r * 30 + g * 70) / (100); - float sbb = (r * 30 + b * 70) / (100); + float r = c[0]; + float g = c[1]; + float b = c[2]; + if (mc->options->anaglyph3d) { + float srr = (r * 30 + g * 59 + b * 11) / 100; + float sgg = (r * 30 + g * 70) / (100); + float sbb = (r * 30 + b * 70) / (100); - r = srr; - g = sgg; - b = sbb; - } + r = srr; + g = sgg; + b = sbb; + } - t->begin(GL_TRIANGLE_FAN); - t->color(r, g, b, c[3]); + t->begin(GL_TRIANGLE_FAN); + t->color(r, g, b, c[3]); - t->vertex((float)(0), (float)( 100), (float)( 0)); - int steps = 16; - t->color(c[0], c[1], c[2], 0.0f); - for (int i = 0; i <= steps; i++) - { - float a = i * PI * 2 / steps; - float _sin = Mth::sin(a); - float _cos = Mth::cos(a); - t->vertex((float)(_sin * 120), (float)( _cos * 120), (float)( -_cos * 40 * c[3])); - } - t->end(); - } - glPopMatrix(); - glShadeModel(GL_FLAT); - } + t->vertex((float)(0), (float)(100), (float)(0)); + int steps = 16; + t->color(c[0], c[1], c[2], 0.0f); + for (int i = 0; i <= steps; i++) { + float a = i * PI * 2 / steps; + float _sin = Mth::sin(a); + float _cos = Mth::cos(a); + t->vertex((float)(_sin * 120), (float)(_cos * 120), + (float)(-_cos * 40 * c[3])); + } + t->end(); + } + glPopMatrix(); + glShadeModel(GL_FLAT); + } - glEnable(GL_TEXTURE_2D); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glPushMatrix(); - { - float rainBrightness = 1 - level[playerIndex]->getRainLevel(alpha); - float xp = 0; - float yp = 0; - float zp = 0; - glColor4f(1, 1, 1, rainBrightness); - glTranslatef(xp, yp, zp); - glRotatef(-90, 0, 1, 0); - glRotatef(level[playerIndex]->getTimeOfDay(alpha) * 360, 1, 0, 0); - float ss = 30; + glEnable(GL_TEXTURE_2D); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glPushMatrix(); + { + float rainBrightness = 1 - level[playerIndex]->getRainLevel(alpha); + float xp = 0; + float yp = 0; + float zp = 0; + glColor4f(1, 1, 1, rainBrightness); + glTranslatef(xp, yp, zp); + glRotatef(-90, 0, 1, 0); + glRotatef(level[playerIndex]->getTimeOfDay(alpha) * 360, 1, 0, 0); + float ss = 30; - MemSect(31); - textures->bindTexture(TN_TERRAIN_SUN); // 4J was L"/terrain/sun.png" - MemSect(0); - t->begin(); - t->vertexUV((float)(-ss), (float)( 100), (float)( -ss), (float)( 0), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( -ss), (float)( 1), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( +ss), (float)( 1), (float)( 1)); - t->vertexUV((float)(-ss), (float)( 100), (float)( +ss), (float)( 0), (float)( 1)); - t->end(); + MemSect(31); + textures->bindTexture(TN_TERRAIN_SUN); // 4J was L"/terrain/sun.png" + MemSect(0); + t->begin(); + t->vertexUV((float)(-ss), (float)(100), (float)(-ss), (float)(0), + (float)(0)); + t->vertexUV((float)(+ss), (float)(100), (float)(-ss), (float)(1), + (float)(0)); + t->vertexUV((float)(+ss), (float)(100), (float)(+ss), (float)(1), + (float)(1)); + t->vertexUV((float)(-ss), (float)(100), (float)(+ss), (float)(0), + (float)(1)); + t->end(); - ss = 20; - textures->bindTexture(TN_TERRAIN_MOON_PHASES); // 4J was L"/1_2_2/terrain/moon_phases.png" - int phase = level[playerIndex]->getMoonPhase(alpha); - int u = phase % 4; - int v = phase / 4 % 2; - float u0 = (u + 0) / 4.0f; - float v0 = (v + 0) / 2.0f; - float u1 = (u + 1) / 4.0f; - float v1 = (v + 1) / 2.0f; - t->begin(); - t->vertexUV(-ss, -100, +ss, u1, v1); - t->vertexUV(+ss, -100, +ss, u0, v1); - t->vertexUV(+ss, -100, -ss, u0, v0); - t->vertexUV(-ss, -100, -ss, u1, v0); - t->end(); + ss = 20; + textures->bindTexture( + TN_TERRAIN_MOON_PHASES); // 4J was + // L"/1_2_2/terrain/moon_phases.png" + int phase = level[playerIndex]->getMoonPhase(alpha); + int u = phase % 4; + int v = phase / 4 % 2; + float u0 = (u + 0) / 4.0f; + float v0 = (v + 0) / 2.0f; + float u1 = (u + 1) / 4.0f; + float v1 = (v + 1) / 2.0f; + t->begin(); + t->vertexUV(-ss, -100, +ss, u1, v1); + t->vertexUV(+ss, -100, +ss, u0, v1); + t->vertexUV(+ss, -100, -ss, u0, v0); + t->vertexUV(-ss, -100, -ss, u1, v0); + t->end(); - glDisable(GL_TEXTURE_2D); - float br = level[playerIndex]->getStarBrightness(alpha) * rainBrightness; - if (br > 0) - { - glColor4f(br, br, br, br); - glCallList(starList); - } - glColor4f(1, 1, 1, 1); - } - glDisable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glEnable(GL_FOG); + glDisable(GL_TEXTURE_2D); + float br = + level[playerIndex]->getStarBrightness(alpha) * rainBrightness; + if (br > 0) { + glColor4f(br, br, br, br); + glCallList(starList); + } + glColor4f(1, 1, 1, 1); + } + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glEnable(GL_FOG); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. + glDisable(GL_ALPHA_TEST); #endif - glPopMatrix(); - glDisable(GL_TEXTURE_2D); - glColor3f(0, 0, 0); + glPopMatrix(); + glDisable(GL_TEXTURE_2D); + glColor3f(0, 0, 0); - double yy = mc->player->getPos(alpha)->y - level[playerIndex]->getHorizonHeight(); // 4J - getHorizonHeight moved forward from 1.2.3 - if (yy < 0) - { - glPushMatrix(); - glTranslatef(0, -(float) (-12), 0); - glCallList(darkList); - glPopMatrix(); + double yy = + mc->player->getPos(alpha)->y - + level[playerIndex]->getHorizonHeight(); // 4J - getHorizonHeight moved + // forward from 1.2.3 + if (yy < 0) { + glPushMatrix(); + glTranslatef(0, -(float)(-12), 0); + glCallList(darkList); + glPopMatrix(); - // 4J - can't work out what this big black box is for. Taking it out until someone misses it... it causes a big black box to visible appear in 3rd person mode whilst under the ground. + // 4J - can't work out what this big black box is for. Taking it out + // until someone misses it... it causes a big black box to visible + // appear in 3rd person mode whilst under the ground. #if 0 float ss = 1; float yo = -(float) (yy + 65); @@ -1176,465 +1224,472 @@ void LevelRenderer::renderSky(float alpha) t->vertex(+ss, y0, -ss); t->end(); #endif - } + } - if (level[playerIndex]->dimension->hasGround()) - { - glColor3f(sr * 0.2f + 0.04f, sg * 0.2f + 0.04f, sb * 0.6f + 0.1f); - } - else - { - glColor3f(sr, sg, sb); - } - glPushMatrix(); - glTranslatef(0, -(float) (yy - 16), 0); - glCallList(darkList); - glPopMatrix(); - glEnable(GL_TEXTURE_2D); + if (level[playerIndex]->dimension->hasGround()) { + glColor3f(sr * 0.2f + 0.04f, sg * 0.2f + 0.04f, sb * 0.6f + 0.1f); + } else { + glColor3f(sr, sg, sb); + } + glPushMatrix(); + glTranslatef(0, -(float)(yy - 16), 0); + glCallList(darkList); + glPopMatrix(); + glEnable(GL_TEXTURE_2D); - glDepthMask(true); + glDepthMask(true); } -void LevelRenderer::renderHaloRing(float alpha) -{ +void LevelRenderer::renderHaloRing(float alpha) { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - if (!mc->level->dimension->isNaturalDimension()) return; + if (!mc->level->dimension->isNaturalDimension()) return; - glDisable(GL_ALPHA_TEST); - glDisable(GL_TEXTURE_2D); - glDepthMask(false); - glEnable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glDisable(GL_TEXTURE_2D); + glDepthMask(false); + glEnable(GL_FOG); - int playerIndex = mc->player->GetXboxPad(); + int playerIndex = mc->player->GetXboxPad(); - Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + Vec3* sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); + float sr = (float)sc->x; + float sg = (float)sc->y; + float sb = (float)sc->z; - // Rough lumninance calculation - float Y = (sr+sr+sb+sg+sg+sg)/6; - float br = 0.6f + (Y*0.4f); - //app.DebugPrintf("Luminance = %f, brightness = %f\n", Y, br); - glColor3f(br,br,br); + // Rough lumninance calculation + float Y = (sr + sr + sb + sg + sg + sg) / 6; + float br = 0.6f + (Y * 0.4f); + // app.DebugPrintf("Luminance = %f, brightness = %f\n", Y, br); + glColor3f(br, br, br); - // Fog at the base near the world - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, HALO_RING_RADIUS); - glFogf(GL_FOG_END, HALO_RING_RADIUS * 0.20f); + // Fog at the base near the world + glFogi(GL_FOG_MODE, GL_LINEAR); + glFogf(GL_FOG_START, HALO_RING_RADIUS); + glFogf(GL_FOG_END, HALO_RING_RADIUS * 0.20f); - Lighting::turnOn(); + Lighting::turnOn(); - glDepthMask(false); - textures->bindTexture(L"misc/haloRing.png"); // 4J was L"/1_2_2/misc/tunnel.png" - Tesselator *t = Tesselator::getInstance(); - bool prev = t->setMipmapEnable(true); + glDepthMask(false); + textures->bindTexture( + L"misc/haloRing.png"); // 4J was L"/1_2_2/misc/tunnel.png" + Tesselator* t = Tesselator::getInstance(); + bool prev = t->setMipmapEnable(true); - glPushMatrix(); - glRotatef(-90, 1, 0, 0); - glRotatef(90, 0, 1, 0); - glCallList(haloRingList); - glPopMatrix(); - t->setMipmapEnable(prev); + glPushMatrix(); + glRotatef(-90, 1, 0, 0); + glRotatef(90, 0, 1, 0); + glCallList(haloRingList); + glPopMatrix(); + t->setMipmapEnable(prev); - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); - glDisable(GL_FOG); + glDisable(GL_FOG); #endif } -void LevelRenderer::renderClouds(float alpha) -{ - int iTicks=ticks; - int playerIndex = mc->player->GetXboxPad(); +void LevelRenderer::renderClouds(float alpha) { + int iTicks = ticks; + int playerIndex = mc->player->GetXboxPad(); - // if the primary player has clouds off, so do all players on this machine - if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Clouds)==0) - { - return; - } + // if the primary player has clouds off, so do all players on this machine + if (app.GetGameSettings(ProfileManager.GetPrimaryPad(), + eGameSetting_Clouds) == 0) { + return; + } - // debug setting added to keep it at day time - if (!mc->level->dimension->isNaturalDimension()) return; + // debug setting added to keep it at day time + if (!mc->level->dimension->isNaturalDimension()) return; - if (mc->options->fancyGraphics) - { - renderAdvancedClouds(alpha); - return; - } + if (mc->options->fancyGraphics) { + renderAdvancedClouds(alpha); + return; + } - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); - int s = 32; - int d = 256 / s; - Tesselator *t = Tesselator::getInstance(); + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_FreezeTime)) { + iTicks = m_freezeticks; + } + } + glDisable(GL_CULL_FACE); + float yOffs = + (float)(mc->cameraTargetPlayer->yOld + + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * + alpha); + int s = 32; + int d = 256 / s; + Tesselator* t = Tesselator::getInstance(); - textures->bindTexture(TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + textures->bindTexture( + TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + Vec3* cc = level[playerIndex]->getCloudColor(alpha); + float cr = (float)cc->x; + float cg = (float)cc->y; + float cb = (float)cc->z; - if (mc->options->anaglyph3d) - { - float crr = (cr * 30 + cg * 59 + cb * 11) / 100; - float cgg = (cr * 30 + cg * 70) / (100); - float cbb = (cr * 30 + cb * 70) / (100); + if (mc->options->anaglyph3d) { + float crr = (cr * 30 + cg * 59 + cb * 11) / 100; + float cgg = (cr * 30 + cg * 70) / (100); + float cbb = (cr * 30 + cb * 70) / (100); - cr = crr; - cg = cgg; - cb = cbb; - } + cr = crr; + cg = cgg; + cb = cbb; + } + float scale = 1 / 2048.0f; + double time = (ticks + alpha); + double xo = + mc->cameraTargetPlayer->xo + + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + + time * 0.03f; + double zo = + mc->cameraTargetPlayer->zo + + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha; + int xOffs = Mth::floor(xo / 2048); + int zOffs = Mth::floor(zo / 2048); + xo -= xOffs * 2048; + zo -= zOffs * 2048; - float scale = 1 / 2048.0f; + float yy = (float)(level[playerIndex]->dimension->getCloudHeight() - yOffs + + 0.33f); + float uo = (float)(xo * scale); + float vo = (float)(zo * scale); + t->begin(); - double time = (ticks + alpha); - double xo = mc->cameraTargetPlayer->xo + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + time * 0.03f; - double zo = mc->cameraTargetPlayer->zo + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha; - int xOffs = Mth::floor(xo / 2048); - int zOffs = Mth::floor(zo / 2048); - xo -= xOffs * 2048; - zo -= zOffs * 2048; + t->color(cr, cg, cb, 0.8f); + for (int xx = -s * d; xx < +s * d; xx += s) { + for (int zz = -s * d; zz < +s * d; zz += s) { + t->vertexUV((float)(xx + 0), (float)(yy), (float)(zz + s), + (float)((xx + 0) * scale + uo), + (float)((zz + s) * scale + vo)); + t->vertexUV((float)(xx + s), (float)(yy), (float)(zz + s), + (float)((xx + s) * scale + uo), + (float)((zz + s) * scale + vo)); + t->vertexUV((float)(xx + s), (float)(yy), (float)(zz + 0), + (float)((xx + s) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xx + 0), (float)(yy), (float)(zz + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } + t->end(); - float yy = (float) (level[playerIndex]->dimension->getCloudHeight() - yOffs + 0.33f); - float uo = (float) (xo * scale); - float vo = (float) (zo * scale); - t->begin(); + glColor4f(1, 1, 1, 1.0f); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); - t->color(cr, cg, cb, 0.8f); - for (int xx = -s * d; xx < +s * d; xx += s) - { - for (int zz = -s * d; zz < +s * d; zz += s) - { - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + s), (float)( (xx + 0) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + s), (float)( (xx + s) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + 0), (float)( (xx + s) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } - t->end(); - - glColor4f(1, 1, 1, 1.0f); - glDisable(GL_BLEND); - glEnable(GL_CULL_FACE); - - if(app.DebugSettingsOn()) - { - - if(!(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.7f, 0.7f, 0.7f, 0.8f); - t->normal(0, -1, 0); - t->vertexUV(x0, y0, z0, u, v ); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - t->vertexUV(x0, y0, z1, u, v ); - } - } - t->end(); - } - if( ( i == 1 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(1.0f, 1.0f, 1.0f, 0.8f); - t->normal(0, 1, 0); - t->vertexUV(x0, y1, z1, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x0, y1, z0, u, v ); - } - } - t->end(); - } - if( ( i == 2 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.9f, 0.9f, 0.9f, 0.8f); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u, v ); - t->vertexUV(x0, y1, z1, u, v ); - t->vertexUV(x0, y1, z0, u, v ); - t->vertexUV(x0, y0, z0, u, v ); - } - } - t->end(); - } - if( ( i == 3 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.9f, 0.9f, 0.9f, 0.8f); - t->normal(1, 0, 0); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - } - } - t->end(); - } - if( ( i == 4 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.8f, 0.8f, 0.8f, 0.8f); - t->normal(-1, 0, 0); - t->vertexUV(x0, y1, z0, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x0, y0, z0, u, v ); - } - } - t->end(); - } - if( ( i == 5 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.8f, 0.8f, 0.8f, 0.8f); - t->normal(1, 0, 0); - t->vertexUV(x0, y0, z1, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x0, y1, z1, u, v ); - } - } - t->end(); - } - glEndList(); - } + if ((i == 0) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.7f, 0.7f, 0.7f, 0.8f); + t->normal(0, -1, 0); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x0, y0, z1, u, v); + } + } + t->end(); + } + if ((i == 1) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(1.0f, 1.0f, 1.0f, 0.8f); + t->normal(0, 1, 0); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + } + } + t->end(); + } + if ((i == 2) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.9f, 0.9f, 0.9f, 0.8f); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + } + } + t->end(); + } + if ((i == 3) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.9f, 0.9f, 0.9f, 0.8f); + t->normal(1, 0, 0); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + } + } + t->end(); + } + if ((i == 4) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.8f, 0.8f, 0.8f, 0.8f); + t->normal(-1, 0, 0); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + } + } + t->end(); + } + if ((i == 5) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.8f, 0.8f, 0.8f, 0.8f); + t->normal(1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + } + } + t->end(); + } + glEndList(); + } } -void LevelRenderer::renderAdvancedClouds(float alpha) -{ - // MGH - added, we were getting dark clouds sometimes on PS3, with this being setup incorrectly - glMultiTexCoord2f(GL_TEXTURE1, 0, 0); +void LevelRenderer::renderAdvancedClouds(float alpha) { + // MGH - added, we were getting dark clouds sometimes on PS3, with this + // being setup incorrectly + glMultiTexCoord2f(GL_TEXTURE1, 0, 0); + // 4J - most of our viewports are now rendered with no clip planes but using + // stencilling to limit the area drawn to. Clouds have a relatively large + // fill area compared to the number of vertices that they have, and so + // enabling clipping here to try and reduce fill rate cost. + RenderManager.StateSetEnableViewportClipPlanes(true); + float yOffs = + (float)(mc->cameraTargetPlayer->yOld + + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * + alpha); + Tesselator* t = Tesselator::getInstance(); + int playerIndex = mc->player->GetXboxPad(); - // 4J - most of our viewports are now rendered with no clip planes but using stencilling to limit the area drawn to. Clouds have a relatively large fill area compared to - // the number of vertices that they have, and so enabling clipping here to try and reduce fill rate cost. - RenderManager.StateSetEnableViewportClipPlanes(true); - float yOffs = (float) (mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); - Tesselator *t = Tesselator::getInstance(); - int playerIndex = mc->player->GetXboxPad(); + int iTicks = ticks; - int iTicks=ticks; + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_FreezeTime)) { + iTicks = m_freezeticks; + } + } - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<cameraTargetPlayer->xo + + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + + time * 0.03f) / + ss; + double zo = + (mc->cameraTargetPlayer->zo + + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha) / + ss + + 0.33f; + float yy = (float)(level[playerIndex]->dimension->getCloudHeight() - yOffs + + 0.33f); + int xOffs = Mth::floor(xo / 2048); + int zOffs = Mth::floor(zo / 2048); + xo -= xOffs * 2048; + zo -= zOffs * 2048; - double time = (ticks + alpha); - double xo = (mc->cameraTargetPlayer->xo + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + time * 0.03f) / ss; - double zo = (mc->cameraTargetPlayer->zo + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha) / ss + 0.33f; - float yy = (float) (level[playerIndex]->dimension->getCloudHeight() - yOffs + 0.33f); - int xOffs = Mth::floor(xo / 2048); - int zOffs = Mth::floor(zo / 2048); - xo -= xOffs * 2048; - zo -= zOffs * 2048; + // 4J - we are now conditionally rendering the clouds in two ways + // (1) if we are (by our y height) in the clouds, then we render in a mode + // quite like the original, with no backface culling, and decisions on which + // sides of the clouds to render based on the positions of the 8x8 blocks of + // cloud texels (2) if we aren't in the clouds, then we do a simpler form of + // rendering with backface culling on This is because the complex sort of + // rendering is really there so that the clouds seem more solid when you + // might be in them, but it has more risk of artifacts so we don't want to + // do it when not necessary - // 4J - we are now conditionally rendering the clouds in two ways - // (1) if we are (by our y height) in the clouds, then we render in a mode quite like the original, with no backface culling, and - // decisions on which sides of the clouds to render based on the positions of the 8x8 blocks of cloud texels - // (2) if we aren't in the clouds, then we do a simpler form of rendering with backface culling on - // This is because the complex sort of rendering is really there so that the clouds seem more solid when you might be in them, but it has more risk of artifacts so - // we don't want to do it when not necessary + // 4jcraft: not needed for the tesselator-based implementation + // bool noBFCMode = ( (yy > -h - 1) && (yy <= h + 1) ); + // if( noBFCMode ) + // { + // glDisable(GL_CULL_FACE); + // } + // else + // { + // glEnable(GL_CULL_FACE); + // } - // 4jcraft: not needed for the tesselator-based implementation - // bool noBFCMode = ( (yy > -h - 1) && (yy <= h + 1) ); - // if( noBFCMode ) - // { - // glDisable(GL_CULL_FACE); - // } - // else - // { - // glEnable(GL_CULL_FACE); - // } + MemSect(31); + textures->bindTexture( + TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" + MemSect(0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - MemSect(31); - textures->bindTexture(TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" - MemSect(0); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Vec3* cc = level[playerIndex]->getCloudColor(alpha); + float cr = (float)cc->x; + float cg = (float)cc->y; + float cb = (float)cc->z; - Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + if (mc->options->anaglyph3d) { + float crr = (cr * 30 + cg * 59 + cb * 11) / 100; + float cgg = (cr * 30 + cg * 70) / (100); + float cbb = (cr * 30 + cb * 70) / (100); - if (mc->options->anaglyph3d) - { - float crr = (cr * 30 + cg * 59 + cb * 11) / 100; - float cgg = (cr * 30 + cg * 70) / (100); - float cbb = (cr * 30 + cb * 70) / (100); + cr = crr; + cg = cgg; + cb = cbb; + } - cr = crr; - cg = cgg; - cb = cbb; - } + float uo = (float)(xo * 0); + float vo = (float)(zo * 0); - float uo = (float) (xo * 0); - float vo = (float) (zo * 0); + float scale = 1 / 256.0f; - float scale = 1 / 256.0f; + uo = (float)(Mth::floor(xo)) * scale; + vo = (float)(Mth::floor(zo)) * scale; + // 4J - keep our UVs +ve - there's a small bug in the xbox GPU that + // incorrectly rounds small -ve UVs (between -1/(64*size) and 0) up to 0, + // which leaves gaps in our clouds... + while (uo < 1.0f) uo += 1.0f; + while (vo < 1.0f) vo += 1.0f; - uo = (float) (Mth::floor(xo)) * scale; - vo = (float) (Mth::floor(zo)) * scale; - // 4J - keep our UVs +ve - there's a small bug in the xbox GPU that incorrectly rounds small -ve UVs (between -1/(64*size) and 0) up to 0, which leaves gaps in our clouds... - while( uo < 1.0f ) uo += 1.0f; - while( vo < 1.0f ) vo += 1.0f; + float xoffs = (float)(xo - Mth::floor(xo)); + float zoffs = (float)(zo - Mth::floor(zo)); - float xoffs = (float) (xo - Mth::floor(xo)); - float zoffs = (float) (zo - Mth::floor(zo)); + int D = 8; - int D = 8; + int radius = 3; + if (activePlayers() > 2) + radius = 2; // 4J - reduce the cloud render distance a bit for 3 & 4 + // player split screen + float e = 1 / 1024.0f; + glScalef(ss, 1, ss); + FrustumData* pFrustumData = Frustum::getFrustum(); + for (int pass = 0; pass < 2; pass++) { + if (pass == 0) { + // 4J - changed to use blend rather than color mask to avoid writing + // to frame buffer, to work with our command buffers + glBlendFunc(GL_ZERO, GL_ONE); + // glColorMask(false, false, false, false); + } else { + // 4J - changed to use blend rather than color mask to avoid writing + // to frame buffer, to work with our command buffers + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + // glColorMask(true, true, true, true); + } + for (int xPos = -radius + 1; xPos <= radius; xPos++) { + for (int zPos = -radius + 1; zPos <= radius; zPos++) { + // 4J - reimplemented the clouds with full cube-per-texel + // geometry to get rid of seams. This is a huge amount more + // quads to render, so now using command buffers to render each + // section to cut CPU hit. - int radius = 3; - if( activePlayers() > 2 ) radius = 2; // 4J - reduce the cloud render distance a bit for 3 & 4 player split screen - float e = 1 / 1024.0f; - glScalef(ss, 1, ss); - FrustumData* pFrustumData = Frustum::getFrustum(); - for (int pass = 0; pass < 2; pass++) - { - if (pass == 0) - { - // 4J - changed to use blend rather than color mask to avoid writing to frame buffer, to work with our command buffers - glBlendFunc(GL_ZERO, GL_ONE); - // glColorMask(false, false, false, false); - } - else - { - // 4J - changed to use blend rather than color mask to avoid writing to frame buffer, to work with our command buffers - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - // glColorMask(true, true, true, true); - } - for (int xPos = -radius + 1; xPos <= radius; xPos++) - { - for (int zPos = -radius + 1; zPos <= radius; zPos++) - { - // 4J - reimplemented the clouds with full cube-per-texel geometry to get rid of seams. This is a huge amount more quads to render, so - // now using command buffers to render each section to cut CPU hit. - - // 4jcraft: switch back to the tesselator-based implementation of cloud renders + // 4jcraft: switch back to the tesselator-based implementation + // of cloud renders #if 0 float xx = (float)(xPos * D); float zz = (float)(zPos * D); @@ -1710,909 +1765,1096 @@ void LevelRenderer::renderAdvancedClouds(float alpha) glLoadIdentity(); glMatrixMode(GL_MODELVIEW); #else - glDisable(GL_CULL_FACE); - t->begin(); - float xx = (float)(xPos * D); - float zz = (float)(zPos * D); - float xp = xx - xoffs; - float zp = zz - zoffs; + glDisable(GL_CULL_FACE); + t->begin(); + float xx = (float)(xPos * D); + float zz = (float)(zPos * D); + float xp = xx - xoffs; + float zp = zz - zoffs; + if (yy > -h - 1) { + t->color(cr * 0.7f, cg * 0.7f, cb * 0.7f, 0.8f); + t->normal(0, -1, 0); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + D), (float)((xx + 0) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + D), (float)((xx + D) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + 0), (float)((xx + D) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + 0), (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } - if (yy > -h - 1) - { - t->color(cr * 0.7f, cg * 0.7f, cb * 0.7f, 0.8f); - t->normal(0, -1, 0); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + D), (float)( (xx + 0) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + D), (float)( (xx + D) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + 0), (float)( (xx + D) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } + if (yy <= h + 1) { + t->color(cr, cg, cb, 0.8f); + t->normal(0, 1, 0); + t->vertexUV((float)(xp + 0), (float)(yy + h - e), + (float)(zp + D), (float)((xx + 0) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h - e), + (float)(zp + D), (float)((xx + D) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h - e), + (float)(zp + 0), (float)((xx + D) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + h - e), + (float)(zp + 0), (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } - if (yy <= h + 1) - { - t->color(cr, cg, cb, 0.8f); - t->normal(0, 1, 0); - t->vertexUV((float)(xp + 0), (float)( yy + h - e), (float)( zp + D), (float)( (xx + 0) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h - e), (float)( zp + D), (float)( (xx + D) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h - e), (float)( zp + 0), (float)( (xx + D) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + h - e), (float)( zp + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } + t->color(cr * 0.9f, cg * 0.9f, cb * 0.9f, 0.8f); + if (xPos > -1) { + t->normal(-1, 0, 0); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + i + 0), (float)(yy + 0), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + h), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + h), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + 0), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } - t->color(cr * 0.9f, cg * 0.9f, cb * 0.9f, 0.8f); - if (xPos > -1) - { - t->normal(-1, 0, 0); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + i + 0), (float)( yy + 0), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + h), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + h), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + 0), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } + if (xPos <= 1) { + t->normal(+1, 0, 0); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + 0), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + h), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + h), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + 0), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } - if (xPos <= 1) - { - t->normal(+1, 0, 0); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + 0), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + h), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + h), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + 0), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } + t->color(cr * 0.8f, cg * 0.8f, cb * 0.8f, 0.8f); + if (zPos > -1) { + t->normal(0, 0, -1); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + 0), (float)(yy + h), + (float)(zp + i + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h), + (float)(zp + i + 0), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + i + 0), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + i + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + } + } - t->color(cr * 0.8f, cg * 0.8f, cb * 0.8f, 0.8f); - if (zPos > -1) - { - t->normal(0, 0, -1); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + 0), (float)( yy + h), (float)( zp + i + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h), (float)( zp + i + 0), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + i + 0), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + i + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - } - } - - if (zPos <= 1) - { - t->normal(0, 0, 1); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + 0), (float)( yy + h), (float)( zp + i + 1 - e), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h), (float)( zp + i + 1 - e), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + i + 1 - e), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + i + 1 - e), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - } - } - t->end(); + if (zPos <= 1) { + t->normal(0, 0, 1); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + 0), (float)(yy + h), + (float)(zp + i + 1 - e), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h), + (float)(zp + i + 1 - e), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + i + 1 - e), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + i + 1 - e), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + } + } + t->end(); #endif - } - } - } + } + } + } - glColor4f(1, 1, 1, 1.0f); - glDisable(GL_BLEND); - glEnable(GL_CULL_FACE); + glColor4f(1, 1, 1, 1.0f); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); - - if(app.DebugSettingsOn()) - { - if(!(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L< > nearestClipChunks; + std::list > nearestClipChunks; #endif - ClipChunk *nearChunk = NULL; // Nearest chunk that is dirty - int veryNearCount = 0; - int minDistSq = 0x7fffffff; // Distances to this chunk + ClipChunk* nearChunk = NULL; // Nearest chunk that is dirty + int veryNearCount = 0; + int minDistSq = 0x7fffffff; // Distances to this chunk + // Set a flag if we should only rebuild existing chunks, not create anything + // new + unsigned int memAlloc = RenderManager.CBuffSize(-1); + /* + static int throttle = 0; + if( ( throttle % 100 ) == 0 ) + { + app.DebugPrintf("CBuffSize: %d\n",memAlloc/(1024*1024)); + } + throttle++; + */ + PIXAddNamedCounter(((float)memAlloc) / (1024.0f * 1024.0f), + "Command buffer allocations"); + bool onlyRebuild = (memAlloc >= MAX_COMMANDBUFFER_ALLOCATIONS); + EnterCriticalSection(&m_csDirtyChunks); - // Set a flag if we should only rebuild existing chunks, not create anything new - unsigned int memAlloc = RenderManager.CBuffSize(-1); - /* - static int throttle = 0; - if( ( throttle % 100 ) == 0 ) - { - app.DebugPrintf("CBuffSize: %d\n",memAlloc/(1024*1024)); - } - throttle++; - */ - PIXAddNamedCounter(((float)memAlloc)/(1024.0f*1024.0f),"Command buffer allocations"); - bool onlyRebuild = ( memAlloc >= MAX_COMMANDBUFFER_ALLOCATIONS ); - EnterCriticalSection(&m_csDirtyChunks); + // Move any dirty chunks stored in the lock free stack into global flags + int index = 0; - // Move any dirty chunks stored in the lock free stack into global flags - int index = 0; - - do - { - // See comment on dirtyChunksLockFreeStack.Push() regarding details of this casting/subtracting -2. - index = (size_t)dirtyChunksLockFreeStack.Pop(); + do { + // See comment on dirtyChunksLockFreeStack.Push() regarding details of + // this casting/subtracting -2. + index = (size_t)dirtyChunksLockFreeStack.Pop(); #ifdef _CRITICAL_CHUNKS - int oldIndex = index; - index &= 0x0fffffff; // remove the top bit that marked the chunk as non-critical + int oldIndex = index; + index &= 0x0fffffff; // remove the top bit that marked the chunk as + // non-critical #endif - if( index == 1 ) dirtyChunkPresent = true; // 1 is a special value passed to let this thread know that a chunk which isn't on this stack has been set to dirty - else if( index > 1 ) - { - int i2 = index - 2; - if( i2 >= DIMENSION_OFFSETS[2] ) - { - i2 -= DIMENSION_OFFSETS[2]; - int y2 = i2 & (CHUNK_Y_COUNT-1); - i2 /= CHUNK_Y_COUNT; - int z2 = i2 / MAX_LEVEL_RENDER_SIZE[2]; - int x2 = i2 - z2 * MAX_LEVEL_RENDER_SIZE[2]; - x2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; - z2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; - } - setGlobalChunkFlag(index - 2, CHUNK_FLAG_DIRTY); + if (index == 1) + dirtyChunkPresent = + true; // 1 is a special value passed to let this thread know + // that a chunk which isn't on this stack has been set to + // dirty + else if (index > 1) { + int i2 = index - 2; + if (i2 >= DIMENSION_OFFSETS[2]) { + i2 -= DIMENSION_OFFSETS[2]; + int y2 = i2 & (CHUNK_Y_COUNT - 1); + i2 /= CHUNK_Y_COUNT; + int z2 = i2 / MAX_LEVEL_RENDER_SIZE[2]; + int x2 = i2 - z2 * MAX_LEVEL_RENDER_SIZE[2]; + x2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; + z2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; + } + setGlobalChunkFlag(index - 2, CHUNK_FLAG_DIRTY); #ifdef _CRITICAL_CHUNKS - if( !(oldIndex & 0x10000000) ) // was this chunk not marked as non-critical. Ugh double negatives - { - setGlobalChunkFlag(index - 2, CHUNK_FLAG_CRITICAL); - } + if (!(oldIndex & 0x10000000)) // was this chunk not marked as + // non-critical. Ugh double negatives + { + setGlobalChunkFlag(index - 2, CHUNK_FLAG_CRITICAL); + } #endif - dirtyChunkPresent = true; - } - } while( index ); + dirtyChunkPresent = true; + } + } while (index); - // Only bother searching round all the chunks if we have some dirty chunk(s) - if( dirtyChunkPresent ) - { - lastDirtyChunkFound = System::currentTimeMillis(); - PIXBeginNamedEvent(0,"Finding nearest chunk\n"); + // Only bother searching round all the chunks if we have some dirty chunk(s) + if (dirtyChunkPresent) { + lastDirtyChunkFound = System::currentTimeMillis(); + PIXBeginNamedEvent(0, "Finding nearest chunk\n"); #if defined __PS3__ && !defined DISABLE_SPU_CODE - // find the nearest chunk with a spu task, copy all the data over here for uploading to SPU - g_findNearestChunkDataIn.numGlobalChunks = getGlobalChunkCount(); - g_findNearestChunkDataIn.pGlobalChunkFlags = globalChunkFlags; - g_findNearestChunkDataIn.onlyRebuild = onlyRebuild; - g_findNearestChunkDataIn.lowerOffset = (int)&((LevelChunk*)0)->lowerBlocks; // dodgy bit of class structure poking, as we don't want to try and get the whole of LevelChunk copmpiling on SPU - g_findNearestChunkDataIn.upperOffset = (int)&((LevelChunk*)0)->upperBlocks; - g_findNearestChunkDataIn.xChunks = xChunks; - g_findNearestChunkDataIn.yChunks = yChunks; - g_findNearestChunkDataIn.zChunks = zChunks; + // find the nearest chunk with a spu task, copy all the data over here + // for uploading to SPU + g_findNearestChunkDataIn.numGlobalChunks = getGlobalChunkCount(); + g_findNearestChunkDataIn.pGlobalChunkFlags = globalChunkFlags; + g_findNearestChunkDataIn.onlyRebuild = onlyRebuild; + g_findNearestChunkDataIn.lowerOffset = + (int)&((LevelChunk*)0) + ->lowerBlocks; // dodgy bit of class structure poking, as we + // don't want to try and get the whole of + // LevelChunk copmpiling on SPU + g_findNearestChunkDataIn.upperOffset = + (int)&((LevelChunk*)0)->upperBlocks; + g_findNearestChunkDataIn.xChunks = xChunks; + g_findNearestChunkDataIn.yChunks = yChunks; + g_findNearestChunkDataIn.zChunks = zChunks; - for(int i=0;i<4;i++) - { - g_findNearestChunkDataIn.chunks[i] = (LevelRenderer_FindNearestChunk_DataIn::ClipChunk*)chunks[i].data; - g_findNearestChunkDataIn.chunkLengths[i] = chunks[i].length; - g_findNearestChunkDataIn.level[i] = level[i]; - g_findNearestChunkDataIn.playerData[i].bValid = mc->localplayers[i] != NULL; - if(mc->localplayers[i] != NULL) - { - g_findNearestChunkDataIn.playerData[i].x = mc->localplayers[i]->x; - g_findNearestChunkDataIn.playerData[i].y = mc->localplayers[i]->y; - g_findNearestChunkDataIn.playerData[i].z = mc->localplayers[i]->z; + for (int i = 0; i < 4; i++) { + g_findNearestChunkDataIn.chunks[i] = + (LevelRenderer_FindNearestChunk_DataIn::ClipChunk*)chunks[i] + .data; + g_findNearestChunkDataIn.chunkLengths[i] = chunks[i].length; + g_findNearestChunkDataIn.level[i] = level[i]; + g_findNearestChunkDataIn.playerData[i].bValid = + mc->localplayers[i] != NULL; + if (mc->localplayers[i] != NULL) { + g_findNearestChunkDataIn.playerData[i].x = + mc->localplayers[i]->x; + g_findNearestChunkDataIn.playerData[i].y = + mc->localplayers[i]->y; + g_findNearestChunkDataIn.playerData[i].z = + mc->localplayers[i]->z; + } + if (level[i] != NULL) { + g_findNearestChunkDataIn.multiplayerChunkCache[i].XZOFFSET = + ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZOFFSET; + g_findNearestChunkDataIn.multiplayerChunkCache[i].XZSIZE = + ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZSIZE; + g_findNearestChunkDataIn.multiplayerChunkCache[i].cache = + (void**)((MultiPlayerChunkCache*)(level[i]->chunkSource)) + ->cache; + } + } - } - if(level[i] != NULL) - { - g_findNearestChunkDataIn.multiplayerChunkCache[i].XZOFFSET = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZOFFSET; - g_findNearestChunkDataIn.multiplayerChunkCache[i].XZSIZE = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZSIZE; - g_findNearestChunkDataIn.multiplayerChunkCache[i].cache = (void**)((MultiPlayerChunkCache*)(level[i]->chunkSource))->cache; - } - - } - - // assert(sizeof(LevelRenderer_FindNearestChunk_DataIn::Chunk) == sizeof(Chunk)); - C4JSpursJob_LevelRenderer_FindNearestChunk findJob(&g_findNearestChunkDataIn); - m_jobPort_FindNearestChunk->submitJob(&findJob); - m_jobPort_FindNearestChunk->waitForCompletion(); - nearChunk = (ClipChunk*)g_findNearestChunkDataIn.nearChunk; - veryNearCount = g_findNearestChunkDataIn.veryNearCount; -#else // __PS3__ + // assert(sizeof(LevelRenderer_FindNearestChunk_DataIn::Chunk) + // == sizeof(Chunk)); + C4JSpursJob_LevelRenderer_FindNearestChunk findJob( + &g_findNearestChunkDataIn); + m_jobPort_FindNearestChunk->submitJob(&findJob); + m_jobPort_FindNearestChunk->waitForCompletion(); + nearChunk = (ClipChunk*)g_findNearestChunkDataIn.nearChunk; + veryNearCount = g_findNearestChunkDataIn.veryNearCount; +#else // __PS3__ #ifdef _LARGE_WORLDS - int maxNearestChunks = MAX_CONCURRENT_CHUNK_REBUILDS; - // 4J Stu - On XboxOne we should cut this down if in a constrained state so the saving threads get more time + int maxNearestChunks = MAX_CONCURRENT_CHUNK_REBUILDS; + // 4J Stu - On XboxOne we should cut this down if in a constrained state + // so the saving threads get more time #endif - // Find nearest chunk that is dirty - for( int p = 0; p < XUSER_MAX_COUNT; p++ ) - { - // It's possible that the localplayers member can be set to NULL on the main thread when a player chooses to exit the game - // So take a reference to the player object now. As it is a std::shared_ptr it should live as long as we need it - std::shared_ptr player = mc->localplayers[p]; - if( player == NULL ) continue; - if( chunks[p].data == NULL ) continue; - if( level[p] == NULL ) continue; - if( chunks[p].length != xChunks * zChunks * CHUNK_Y_COUNT ) continue; - int px = (int)player->x; - int py = (int)player->y; - int pz = (int)player->z; + // Find nearest chunk that is dirty + for (int p = 0; p < XUSER_MAX_COUNT; p++) { + // It's possible that the localplayers member can be set to NULL on + // the main thread when a player chooses to exit the game So take a + // reference to the player object now. As it is a std::shared_ptr it + // should live as long as we need it + std::shared_ptr player = mc->localplayers[p]; + if (player == NULL) continue; + if (chunks[p].data == NULL) continue; + if (level[p] == NULL) continue; + if (chunks[p].length != xChunks * zChunks * CHUNK_Y_COUNT) continue; + int px = (int)player->x; + int py = (int)player->y; + int pz = (int)player->z; -// app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} ",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, xChunks, zChunks); + // app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} + //",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, + //xChunks, zChunks); - int considered = 0; - int wouldBeNearButEmpty = 0; - for( int x = 0; x < xChunks; x++ ) - { - for( int z = 0; z < zChunks; z++ ) - { - for( int y = 0; y < CHUNK_Y_COUNT; y++ ) - { - ClipChunk *pClipChunk = &chunks[p][(z * yChunks + y) * xChunks + x]; - // Get distance to this chunk - deliberately not calling the chunk's method of doing this to avoid overheads (passing entitie, type conversion etc.) that this involves - int xd = pClipChunk->xm - px; - int yd = pClipChunk->ym - py; - int zd = pClipChunk->zm - pz; - int distSq = xd * xd + yd * yd + zd * zd; - int distSqWeighted = xd * xd + yd * yd * 4 + zd * zd; // Weighting against y to prioritise things in same x/z plane as player first + int considered = 0; + int wouldBeNearButEmpty = 0; + for (int x = 0; x < xChunks; x++) { + for (int z = 0; z < zChunks; z++) { + for (int y = 0; y < CHUNK_Y_COUNT; y++) { + ClipChunk* pClipChunk = + &chunks[p][(z * yChunks + y) * xChunks + x]; + // Get distance to this chunk - deliberately not calling + // the chunk's method of doing this to avoid overheads + // (passing entitie, type conversion etc.) that this + // involves + int xd = pClipChunk->xm - px; + int yd = pClipChunk->ym - py; + int zd = pClipChunk->zm - pz; + int distSq = xd * xd + yd * yd + zd * zd; + int distSqWeighted = + xd * xd + yd * yd * 4 + + zd * + zd; // Weighting against y to prioritise things + // in same x/z plane as player first - if( globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_DIRTY ) - { - if( (!onlyRebuild) || - globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_COMPILED || - ( distSq < 20 * 20 ) ) // Always rebuild really near things or else building (say) at tower up into empty blocks when we are low on memory will not create render data - { - considered++; - // Is this chunk nearer than our nearest? + if (globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_DIRTY) { + if ((!onlyRebuild) || + globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_COMPILED || + (distSq < + 20 * 20)) // Always rebuild really near things + // or else building (say) at tower + // up into empty blocks when we are + // low on memory will not create + // render data + { + considered++; + // Is this chunk nearer than our nearest? #ifdef _LARGE_WORLDS - bool isNearer = nearestClipChunks.empty(); - AUTO_VAR(itNearest, nearestClipChunks.begin()); - for(; itNearest != nearestClipChunks.end(); ++itNearest) - { - isNearer = distSqWeighted < itNearest->second; - if(isNearer) break; - } - isNearer = isNearer || (nearestClipChunks.size() < maxNearestChunks); + bool isNearer = nearestClipChunks.empty(); + AUTO_VAR(itNearest, nearestClipChunks.begin()); + for (; itNearest != nearestClipChunks.end(); + ++itNearest) { + isNearer = + distSqWeighted < itNearest->second; + if (isNearer) break; + } + isNearer = + isNearer || (nearestClipChunks.size() < + maxNearestChunks); #else - bool isNearer = distSqWeighted < minDistSq; + bool isNearer = distSqWeighted < minDistSq; #endif #ifdef _CRITICAL_CHUNKS - // AP - this will make sure that if a deferred grouping has started, only critical chunks go into that - // grouping, even if a non-critical chunk is closer. - if( (!veryNearCount && isNearer) || - (distSq < 20 * 20 && (globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_CRITICAL)) ) + // AP - this will make sure that if a deferred + // grouping has started, only critical chunks go + // into that grouping, even if a non-critical + // chunk is closer. + if ((!veryNearCount && isNearer) || + (distSq < 20 * 20 && + (globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_CRITICAL))) #else - if( isNearer ) + if (isNearer) #endif - { - // At this point we've got a chunk that we would like to consider for rendering, at least based on its proximity to the player(s). - // Its *quite* quick to generate empty render data for render chunks, but if we let the rebuilding do that then the after rebuilding we will have - // to start searching for the next nearest chunk from scratch again. Instead, its better to detect empty chunks at this stage, flag them up as not dirty - // (and empty), and carry on. The levelchunk's isRenderChunkEmpty method can be quite optimal as it can make use of the chunk's data compression to detect - // emptiness without actually testing as many data items as uncompressed data would. - Chunk *chunk = pClipChunk->chunk; - LevelChunk *lc = level[p]->getChunkAt(chunk->x,chunk->z); - if( !lc->isRenderChunkEmpty(y * 16) ) - { - nearChunk = pClipChunk; - minDistSq = distSqWeighted; + { + // At this point we've got a chunk that we + // would like to consider for rendering, at + // least based on its proximity to the + // player(s). Its *quite* quick to generate + // empty render data for render chunks, but + // if we let the rebuilding do that then the + // after rebuilding we will have to start + // searching for the next nearest chunk from + // scratch again. Instead, its better to + // detect empty chunks at this stage, flag + // them up as not dirty (and empty), and + // carry on. The levelchunk's + // isRenderChunkEmpty method can be quite + // optimal as it can make use of the chunk's + // data compression to detect emptiness + // without actually testing as many data + // items as uncompressed data would. + Chunk* chunk = pClipChunk->chunk; + LevelChunk* lc = level[p]->getChunkAt( + chunk->x, chunk->z); + if (!lc->isRenderChunkEmpty(y * 16)) { + nearChunk = pClipChunk; + minDistSq = distSqWeighted; #ifdef _LARGE_WORLDS - nearestClipChunks.insert(itNearest, std::pair(nearChunk, minDistSq) ); - if(nearestClipChunks.size() > maxNearestChunks) - { - nearestClipChunks.pop_back(); - } + nearestClipChunks.insert( + itNearest, + std::pair( + nearChunk, minDistSq)); + if (nearestClipChunks.size() > + maxNearestChunks) { + nearestClipChunks.pop_back(); + } #endif - } - else - { - chunk->clearDirty(); - globalChunkFlags[ pClipChunk->globalIdx ] |= CHUNK_FLAG_EMPTYBOTH; - wouldBeNearButEmpty++; - } - } + } else { + chunk->clearDirty(); + globalChunkFlags[pClipChunk + ->globalIdx] |= + CHUNK_FLAG_EMPTYBOTH; + wouldBeNearButEmpty++; + } + } #ifdef _CRITICAL_CHUNKS - // AP - is the chunk near and also critical - if( distSq < 20 * 20 && ((globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_CRITICAL)) ) + // AP - is the chunk near and also critical + if (distSq < 20 * 20 && + ((globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_CRITICAL))) #else - if( distSq < 20 * 20 ) + if (distSq < 20 * 20) #endif - { - veryNearCount++; - } - } - } - } - } - } -// app.DebugPrintf("[%d,%d,%d]\n",nearestClipChunks.empty(),considered,wouldBeNearButEmpty); - } -#endif // __PS3__ - PIXEndNamedEvent(); - } + { + veryNearCount++; + } + } + } + } + } + } + // app.DebugPrintf("[%d,%d,%d]\n",nearestClipChunks.empty(),considered,wouldBeNearButEmpty); + } +#endif // __PS3__ + PIXEndNamedEvent(); + } - - - Chunk *chunk = NULL; + Chunk* chunk = NULL; #ifdef _LARGE_WORLDS - if(!nearestClipChunks.empty()) - { - int index = 0; - for(AUTO_VAR(it, nearestClipChunks.begin()); it != nearestClipChunks.end(); ++it) - { - chunk = it->first->chunk; - // If this chunk is very near, then move the renderer into a deferred mode. This won't commit any command buffers - // for rendering until we call CBuffDeferredModeEnd(), allowing us to group any near changes into an atomic unit. This - // is essential so we don't temporarily create any holes in the environment whilst updating one chunk and not the neighbours. - // The "ver near" aspect of this is just a cosmetic nicety - exactly the same thing would happen further away, but we just don't - // care about it so much from terms of visual impact. - if( veryNearCount > 0 ) - { - RenderManager.CBuffDeferredModeStart(); - } - // Build this chunk & return false to continue processing - chunk->clearDirty(); - // Take a copy of the details that are required for chunk rebuilding, and rebuild That instead of the original chunk data. This is done within - // the m_csDirtyChunks critical section, which means that any chunks can't be repositioned whilst we are doing this copy. The copy will then - // be guaranteed to be consistent whilst rebuilding takes place outside of that critical section. - permaChunk[index].makeCopyForRebuild(chunk); - ++index; - } - LeaveCriticalSection(&m_csDirtyChunks); + if (!nearestClipChunks.empty()) { + int index = 0; + for (AUTO_VAR(it, nearestClipChunks.begin()); + it != nearestClipChunks.end(); ++it) { + chunk = it->first->chunk; + // If this chunk is very near, then move the renderer into a + // deferred mode. This won't commit any command buffers for + // rendering until we call CBuffDeferredModeEnd(), allowing us to + // group any near changes into an atomic unit. This is essential so + // we don't temporarily create any holes in the environment whilst + // updating one chunk and not the neighbours. The "ver near" aspect + // of this is just a cosmetic nicety - exactly the same thing would + // happen further away, but we just don't care about it so much from + // terms of visual impact. + if (veryNearCount > 0) { + RenderManager.CBuffDeferredModeStart(); + } + // Build this chunk & return false to continue processing + chunk->clearDirty(); + // Take a copy of the details that are required for chunk + // rebuilding, and rebuild That instead of the original chunk data. + // This is done within the m_csDirtyChunks critical section, which + // means that any chunks can't be repositioned whilst we are doing + // this copy. The copy will then be guaranteed to be consistent + // whilst rebuilding takes place outside of that critical section. + permaChunk[index].makeCopyForRebuild(chunk); + ++index; + } + LeaveCriticalSection(&m_csDirtyChunks); - --index; // Bring it back into 0 counted range + --index; // Bring it back into 0 counted range - for(int i = MAX_CHUNK_REBUILD_THREADS - 1; i >= 0; --i) - { - // Set the events that won't run - if( (i+1) > index) s_rebuildCompleteEvents->Set(i); - else break; - } + for (int i = MAX_CHUNK_REBUILD_THREADS - 1; i >= 0; --i) { + // Set the events that won't run + if ((i + 1) > index) + s_rebuildCompleteEvents->Set(i); + else + break; + } - for(; index >=0; --index) - { - bool bAtomic = false; - if((veryNearCount > 0)) - bAtomic = true; //MGH - if veryNearCount, then we're trying to rebuild atomically, so do it all on the main thread + for (; index >= 0; --index) { + bool bAtomic = false; + if ((veryNearCount > 0)) + bAtomic = true; // MGH - if veryNearCount, then we're trying + // to rebuild atomically, so do it all on the + // main thread - if( bAtomic || (index == 0) ) - { - //PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d %d",chunk->x, chunk->y, chunk->z); - // static __int64 totalTime = 0; - // static __int64 countTime = 0; - // __int64 startTime = System::currentTimeMillis(); + if (bAtomic || (index == 0)) { + // PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d + // %d",chunk->x, chunk->y, chunk->z); static __int64 totalTime = + //0; static __int64 countTime = 0; + // __int64 startTime = System::currentTimeMillis(); - //app.DebugPrintf("Rebuilding permaChunk %d\n", index); + // app.DebugPrintf("Rebuilding permaChunk %d\n", index); - permaChunk[index].rebuild(); + permaChunk[index].rebuild(); - if(index !=0) - s_rebuildCompleteEvents->Set(index-1); // MGH - this rebuild happening on the main thread instead, mark the thread it should have been running on as complete + if (index != 0) + s_rebuildCompleteEvents->Set( + index - 1); // MGH - this rebuild happening on the main + // thread instead, mark the thread it + // should have been running on as complete - // __int64 endTime = System::currentTimeMillis(); - // totalTime += (endTime - startTime); - // countTime++; - // printf("%d : %f\n", countTime, (float)totalTime / (float)countTime); - //PIXEndNamedEvent(); - } - // 4J Stu - Ignore this path when in constrained mode on Xbox One - else - { - // Activate thread to rebuild this chunk - s_activationEventA[index - 1]->Set(); - } - } + // __int64 endTime = System::currentTimeMillis(); + // totalTime += (endTime - startTime); + // countTime++; + // printf("%d : %f\n", countTime, (float)totalTime + /// (float)countTime); PIXEndNamedEvent(); + } + // 4J Stu - Ignore this path when in constrained mode on Xbox One + else { + // Activate thread to rebuild this chunk + s_activationEventA[index - 1]->Set(); + } + } - // Wait for the other threads to be done as well - s_rebuildCompleteEvents->WaitForAll(INFINITE); - } + // Wait for the other threads to be done as well + s_rebuildCompleteEvents->WaitForAll(INFINITE); + } #else - if( nearChunk ) - { - chunk = nearChunk->chunk; - PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d %d",chunk->x, chunk->y, chunk->z); - // If this chunk is very near, then move the renderer into a deferred mode. This won't commit any command buffers - // for rendering until we call CBuffDeferredModeEnd(), allowing us to group any near changes into an atomic unit. This - // is essential so we don't temporarily create any holes in the environment whilst updating one chunk and not the neighbours. - // The "ver near" aspect of this is just a cosmetic nicety - exactly the same thing would happen further away, but we just don't - // care about it so much from terms of visual impact. - if( veryNearCount > 0 ) - { - RenderManager.CBuffDeferredModeStart(); - } - // Build this chunk & return false to continue processing - chunk->clearDirty(); - // Take a copy of the details that are required for chunk rebuilding, and rebuild That instead of the original chunk data. This is done within - // the m_csDirtyChunks critical section, which means that any chunks can't be repositioned whilst we are doing this copy. The copy will then - // be guaranteed to be consistent whilst rebuilding takes place outside of that critical section. - static Chunk permaChunk; - permaChunk.makeCopyForRebuild(chunk); - LeaveCriticalSection(&m_csDirtyChunks); - // static __int64 totalTime = 0; - // static __int64 countTime = 0; - // __int64 startTime = System::currentTimeMillis(); - permaChunk.rebuild(); - // __int64 endTime = System::currentTimeMillis(); - // totalTime += (endTime - startTime); - // countTime++; - // printf("%d : %f\n", countTime, (float)totalTime / (float)countTime); - PIXEndNamedEvent(); - } + if (nearChunk) { + chunk = nearChunk->chunk; + PIXBeginNamedEvent(0, "Rebuilding near chunk %d %d %d", chunk->x, + chunk->y, chunk->z); + // If this chunk is very near, then move the renderer into a deferred + // mode. This won't commit any command buffers for rendering until we + // call CBuffDeferredModeEnd(), allowing us to group any near changes + // into an atomic unit. This is essential so we don't temporarily create + // any holes in the environment whilst updating one chunk and not the + // neighbours. The "ver near" aspect of this is just a cosmetic nicety - + // exactly the same thing would happen further away, but we just don't + // care about it so much from terms of visual impact. + if (veryNearCount > 0) { + RenderManager.CBuffDeferredModeStart(); + } + // Build this chunk & return false to continue processing + chunk->clearDirty(); + // Take a copy of the details that are required for chunk rebuilding, + // and rebuild That instead of the original chunk data. This is done + // within the m_csDirtyChunks critical section, which means that any + // chunks can't be repositioned whilst we are doing this copy. The copy + // will then be guaranteed to be consistent whilst rebuilding takes + // place outside of that critical section. + static Chunk permaChunk; + permaChunk.makeCopyForRebuild(chunk); + LeaveCriticalSection(&m_csDirtyChunks); + // static __int64 totalTime = 0; + // static __int64 countTime = 0; + // __int64 startTime = System::currentTimeMillis(); + permaChunk.rebuild(); + // __int64 endTime = System::currentTimeMillis(); + // totalTime += (endTime - startTime); + // countTime++; + // printf("%d : %f\n", countTime, (float)totalTime / + //(float)countTime); + PIXEndNamedEvent(); + } #endif - else - { - // Nothing to do - clear flags that there are things to process, unless it's been a while since we found any dirty chunks in which case force a check next time through - if( ( System::currentTimeMillis() - lastDirtyChunkFound ) > FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS ) - { - dirtyChunkPresent = true; - } - else - { - dirtyChunkPresent = false; - } - LeaveCriticalSection(&m_csDirtyChunks); + else { + // Nothing to do - clear flags that there are things to process, unless + // it's been a while since we found any dirty chunks in which case force + // a check next time through + if ((System::currentTimeMillis() - lastDirtyChunkFound) > + FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS) { + dirtyChunkPresent = true; + } else { + dirtyChunkPresent = false; + } + LeaveCriticalSection(&m_csDirtyChunks); #ifdef __PS3__ - Sleep(5); -#endif // __PS3__ - return false; - } + Sleep(5); +#endif // __PS3__ + return false; + } - // If there was more than one very near thing found in our initial assessment, then return true so that we will keep doing the other one(s) - // in an atomic unit - if( veryNearCount > 1 ) - { - destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount ); - return true; - } - // If the chunk we've just built was near, and it has been marked dirty at some point while we are rebuilding, also return true so - // we can rebuild the same thing atomically - if its data was changed during creating render data, it may well be invalid - if( ( veryNearCount == 1 ) && getGlobalChunkFlag(chunk->x, chunk->y, chunk->z, chunk->level, CHUNK_FLAG_DIRTY ) ) - { - destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount + 1); - return true; - } + // If there was more than one very near thing found in our initial + // assessment, then return true so that we will keep doing the other one(s) + // in an atomic unit + if (veryNearCount > 1) { + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount); + return true; + } + // If the chunk we've just built was near, and it has been marked dirty at + // some point while we are rebuilding, also return true so we can rebuild + // the same thing atomically - if its data was changed during creating + // render data, it may well be invalid + if ((veryNearCount == 1) && + getGlobalChunkFlag(chunk->x, chunk->y, chunk->z, chunk->level, + CHUNK_FLAG_DIRTY)) { + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount + 1); + return true; + } - if( nearChunk ) destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount ); + if (nearChunk) + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount); - return false; + return false; } +void LevelRenderer::renderHit(std::shared_ptr player, HitResult* h, + int mode, + std::shared_ptr inventoryItem, + float a) { + Tesselator* t = Tesselator::getInstance(); + glEnable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glColor4f( + 1, 1, 1, + ((float)(Mth::sin(Minecraft::currentTimeMillis() / 100.0f)) * 0.2f + + 0.4f) * + 0.5f); + if (mode != 0 && inventoryItem != NULL) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + float br = + (Mth::sin(Minecraft::currentTimeMillis() / 100.0f) * 0.2f + 0.8f); + glColor4f( + br, br, br, + (Mth::sin(Minecraft::currentTimeMillis() / 200.0f) * 0.2f + 0.5f)); -void LevelRenderer::renderHit(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a) -{ - Tesselator *t = Tesselator::getInstance(); - glEnable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glColor4f(1, 1, 1, ((float) (Mth::sin(Minecraft::currentTimeMillis() / 100.0f)) * 0.2f + 0.4f) * 0.5f); - if (mode != 0 && inventoryItem != NULL) - { - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - float br = (Mth::sin(Minecraft::currentTimeMillis() / 100.0f) * 0.2f + 0.8f); - glColor4f(br, br, br, (Mth::sin(Minecraft::currentTimeMillis() / 200.0f) * 0.2f + 0.5f)); - - textures->bindTexture(TN_TERRAIN); //L"/terrain.png"); - } - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); + textures->bindTexture(TN_TERRAIN); // L"/terrain.png"); + } + glDisable(GL_BLEND); + glDisable(GL_ALPHA_TEST); } -void LevelRenderer::renderDestroyAnimation(Tesselator *t, std::shared_ptr player, float a) -{ - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; +void LevelRenderer::renderDestroyAnimation(Tesselator* t, + std::shared_ptr player, + float a) { + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; - int playerIndex = mc->player->GetXboxPad(); - if (!destroyingBlocks.empty()) - { - glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); + int playerIndex = mc->player->GetXboxPad(); + if (!destroyingBlocks.empty()) { + glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); - textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - glColor4f(1, 1, 1, 0.5f); - glPushMatrix(); + textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + glColor4f(1, 1, 1, 0.5f); + glPushMatrix(); - glDisable(GL_ALPHA_TEST); + glDisable(GL_ALPHA_TEST); - glPolygonOffset(-3.0f, -3.0f); - glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-3.0f, -3.0f); + glEnable(GL_POLYGON_OFFSET_FILL); - glEnable(GL_ALPHA_TEST); - t->begin(); + glEnable(GL_ALPHA_TEST); + t->begin(); #ifdef __PSVITA__ - // AP : fix for bug 4952. No amount of polygon offset will push this close enough to be seen above the second tile layer when looking straight down - // so just add on a little bit of y to fix this. hacky hacky - t->offset((float)-xo, (float)-yo + 0.01f,(float) -zo); + // AP : fix for bug 4952. No amount of polygon offset will push this + // close enough to be seen above the second tile layer when looking + // straight down so just add on a little bit of y to fix this. hacky + // hacky + t->offset((float)-xo, (float)-yo + 0.01f, (float)-zo); #else - t->offset((float)-xo, (float)-yo,(float) -zo); + t->offset((float)-xo, (float)-yo, (float)-zo); #endif - t->noColor(); + t->noColor(); - AUTO_VAR(it, destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) - { - BlockDestructionProgress *block = it->second; - double xd = block->getX() - xo; - double yd = block->getY() - yo; - double zd = block->getZ() - zo; + AUTO_VAR(it, destroyingBlocks.begin()); + while (it != destroyingBlocks.end()) { + BlockDestructionProgress* block = it->second; + double xd = block->getX() - xo; + double yd = block->getY() - yo; + double zd = block->getZ() - zo; - if (xd * xd + yd * yd + zd * zd < 32 * 32) // 4J MGH - now only culling instead of removing, as the list is shared in split screen - { - int iPad = mc->player->GetXboxPad(); // 4J added - int tileId = level[iPad]->getTile(block->getX(), block->getY(), block->getZ()); - Tile *tile = tileId > 0 ? Tile::tiles[tileId] : NULL; - if (tile == NULL) tile = Tile::rock; - tileRenderer[iPad]->tesselateInWorldFixedTexture(tile, block->getX(), block->getY(), block->getZ(), breakingTextures[block->getProgress()]); // 4J renamed to differentiate from tesselateInWorld - } - ++it; - } + if (xd * xd + yd * yd + zd * zd < + 32 * 32) // 4J MGH - now only culling instead of removing, as + // the list is shared in split screen + { + int iPad = mc->player->GetXboxPad(); // 4J added + int tileId = level[iPad]->getTile(block->getX(), block->getY(), + block->getZ()); + Tile* tile = tileId > 0 ? Tile::tiles[tileId] : NULL; + if (tile == NULL) tile = Tile::rock; + tileRenderer[iPad]->tesselateInWorldFixedTexture( + tile, block->getX(), block->getY(), block->getZ(), + breakingTextures + [block->getProgress()]); // 4J renamed to differentiate + // from tesselateInWorld + } + ++it; + } - t->end(); - t->offset(0, 0, 0); - glDisable(GL_ALPHA_TEST); - /* - * for (int i = 0; i < 6; i++) { tile.renderFace(t, h.x, h.y, - * h.z, i, 15 * 16 + (int) (destroyProgress * 10)); } - */ - glPolygonOffset(0.0f, 0.0f); - glDisable(GL_POLYGON_OFFSET_FILL); - glEnable(GL_ALPHA_TEST); + t->end(); + t->offset(0, 0, 0); + glDisable(GL_ALPHA_TEST); + /* + * for (int i = 0; i < 6; i++) { tile.renderFace(t, h.x, h.y, + * h.z, i, 15 * 16 + (int) (destroyProgress * 10)); } + */ + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_ALPHA_TEST); - glDepthMask(true); - glPopMatrix(); - } + glDepthMask(true); + glPopMatrix(); + } } -void LevelRenderer::renderHitOutline(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a) -{ +void LevelRenderer::renderHitOutline( + std::shared_ptr player, HitResult* h, int mode, + std::shared_ptr inventoryItem, float a) { + if (mode == 0 && h->type == HitResult::TILE) { + int iPad = mc->player->GetXboxPad(); // 4J added - if (mode == 0 && h->type == HitResult::TILE) - { - int iPad = mc->player->GetXboxPad(); // 4J added + // 4J-PB - If Display HUD is false, don't render the hit outline + if (app.GetGameSettings(iPad, eGameSetting_DisplayHUD) == 0) return; - // 4J-PB - If Display HUD is false, don't render the hit outline - if ( app.GetGameSettings(iPad,eGameSetting_DisplayHUD)==0 ) return; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(0, 0, 0, 0.4f); + glLineWidth(2.0f); + glDisable(GL_TEXTURE_2D); + glDepthMask(false); + float ss = 0.002f; + int tileId = level[iPad]->getTile(h->x, h->y, h->z); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(0, 0, 0, 0.4f); - glLineWidth(2.0f); - glDisable(GL_TEXTURE_2D); - glDepthMask(false); - float ss = 0.002f; - int tileId = level[iPad]->getTile(h->x, h->y, h->z); - - if (tileId > 0) - { - Tile::tiles[tileId]->updateShape(level[iPad], h->x, h->y, h->z); - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; - render(Tile::tiles[tileId]->getTileAABB(level[iPad], h->x, h->y, h->z)->grow(ss, ss, ss)->cloneMove(-xo, -yo, -zo)); - } - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - } + if (tileId > 0) { + Tile::tiles[tileId]->updateShape(level[iPad], h->x, h->y, h->z); + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; + render(Tile::tiles[tileId] + ->getTileAABB(level[iPad], h->x, h->y, h->z) + ->grow(ss, ss, ss) + ->cloneMove(-xo, -yo, -zo)); + } + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + } } -void LevelRenderer::render(AABB *b) -{ - Tesselator *t = Tesselator::getInstance(); +void LevelRenderer::render(AABB* b) { + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->end(); + t->begin(GL_LINE_STRIP); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->end(); - t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->end(); + t->begin(GL_LINE_STRIP); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->end(); - t->begin(GL_LINES); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); - t->end(); + t->begin(GL_LINES); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z1)); + t->end(); } -void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) // 4J - added level param +void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level) // 4J - added level param { - // 4J - level is passed if this is coming from setTilesDirty, which could come from when connection is being ticked outside of normal level tick, and player won't - // be set up - if( level == NULL ) level = this->level[mc->player->GetXboxPad()]; - // EnterCriticalSection(&m_csDirtyChunks); - int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); - int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); - int _z0 = Mth::intFloorDiv(z0, CHUNK_XZSIZE); - int _x1 = Mth::intFloorDiv(x1, CHUNK_XZSIZE); - int _y1 = Mth::intFloorDiv(y1, CHUNK_SIZE); - int _z1 = Mth::intFloorDiv(z1, CHUNK_XZSIZE); + // 4J - level is passed if this is coming from setTilesDirty, which could + // come from when connection is being ticked outside of normal level tick, + // and player won't be set up + if (level == NULL) level = this->level[mc->player->GetXboxPad()]; + // EnterCriticalSection(&m_csDirtyChunks); + int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); + int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); + int _z0 = Mth::intFloorDiv(z0, CHUNK_XZSIZE); + int _x1 = Mth::intFloorDiv(x1, CHUNK_XZSIZE); + int _y1 = Mth::intFloorDiv(y1, CHUNK_SIZE); + int _z1 = Mth::intFloorDiv(z1, CHUNK_XZSIZE); - for (int x = _x0; x <= _x1; x++) - { - for (int y = _y0; y <= _y1; y++) - { - for (int z = _z0; z <= _z1; z++) - { - // printf("Setting %d %d %d dirty\n",x,y,z); - int index = getGlobalIndexForChunk(x * 16, y * 16, z * 16, level); - // Rather than setting the flags directly, add any dirty chunks into a lock free stack - this avoids having to lock m_csDirtyChunks . - // These chunks are then added to the global flags in the render update thread. - // An XLockFreeQueue actually implements a queue of pointers to its templated type, and I don't want to have to go allocating ints here just to store the - // pointer to them in a queue. Hence actually pretending that the int Is a pointer here. Our Index has a a valid range from 0 to something quite big, - // but including zero. The lock free queue, since it thinks it is dealing with pointers, uses a NULL pointer to signify that a Pop hasn't succeeded. - // We also want to reserve one special value (of 1 ) for use when multiple chunks not individually listed are made dirty. Therefore adding 2 to our - // index value here to move our valid range from 1 to something quite big + 2 - if( index > -1 ) - { + for (int x = _x0; x <= _x1; x++) { + for (int y = _y0; y <= _y1; y++) { + for (int z = _z0; z <= _z1; z++) { + // printf("Setting %d %d %d + //dirty\n",x,y,z); + int index = + getGlobalIndexForChunk(x * 16, y * 16, z * 16, level); + // Rather than setting the flags directly, add any dirty chunks + // into a lock free stack - this avoids having to lock + // m_csDirtyChunks . These chunks are then added to the global + // flags in the render update thread. An XLockFreeQueue actually + // implements a queue of pointers to its templated type, and I + // don't want to have to go allocating ints here just to store + // the pointer to them in a queue. Hence actually pretending + // that the int Is a pointer here. Our Index has a a valid range + // from 0 to something quite big, but including zero. The lock + // free queue, since it thinks it is dealing with pointers, uses + // a NULL pointer to signify that a Pop hasn't succeeded. We + // also want to reserve one special value (of 1 ) for use when + // multiple chunks not individually listed are made dirty. + // Therefore adding 2 to our index value here to move our valid + // range from 1 to something quite big + 2 + if (index > -1) { #ifdef _CRITICAL_CHUNKS - index += 2; + index += 2; - // AP - by the time we reach this function the area passed in has a 1 block border added to it to make sure geometry and lighting is updated correctly. - // Some of those blocks will only need lighting updated so it is acceptable to not have those blocks grouped in the deferral system as the mismatch - // will hardly be noticable. The blocks that need geometry updated will be adjacent to the original, non-bordered area. - // This bit of code will mark a chunk as 'non-critical' if all of the blocks inside it are NOT adjacent to the original area. This has the greatest effect - // when digging a single block. Only 6 of the blocks out of the possible 26 are actually adjacent to the original block. The other 20 only need lighting updated. - // Note I have noticed a new side effect of this system where it's possible to see into the sides of water but this is acceptable compared to seeing through - // the entire landscape. - // is the left or right most block just inside this chunk - if( ((x0 & 15) == 15 && x == _x0) || ((x1 & 15) == 0 && x == _x1) ) - { - // is the front, back, top or bottom most block just inside this chunk - if( ((z0 & 15) == 15 && z == _z0) || ((z1 & 15) == 0 && z == _z1) || - ((y0 & 15) == 15 && y == _y0) || ((y1 & 15) == 0 && y == _y1)) - { - index |= 0x10000000; - } - } - else - { - // is the front or back most block just inside this chunk - if( ((z0 & 15) == 15 && z == _z0) || ((z1 & 15) == 0 && z == _z1) ) - { - // is the top or bottom most block just inside this chunk - if( ((y0 & 15) == 15 && y == _y0) || ((y1 & 15) == 0 && y == _y1)) - { - index |= 0x10000000; - } - } - } + // AP - by the time we reach this function the area passed + // in has a 1 block border added to it to make sure geometry + // and lighting is updated correctly. Some of those blocks + // will only need lighting updated so it is acceptable to + // not have those blocks grouped in the deferral system as + // the mismatch will hardly be noticable. The blocks that + // need geometry updated will be adjacent to the original, + // non-bordered area. This bit of code will mark a chunk as + // 'non-critical' if all of the blocks inside it are NOT + // adjacent to the original area. This has the greatest + // effect when digging a single block. Only 6 of the blocks + // out of the possible 26 are actually adjacent to the + // original block. The other 20 only need lighting updated. + // Note I have noticed a new side effect of this system + // where it's possible to see into the sides of water but + // this is acceptable compared to seeing through the entire + // landscape. is the left or right most block just inside + // this chunk + if (((x0 & 15) == 15 && x == _x0) || + ((x1 & 15) == 0 && x == _x1)) { + // is the front, back, top or bottom most block just + // inside this chunk + if (((z0 & 15) == 15 && z == _z0) || + ((z1 & 15) == 0 && z == _z1) || + ((y0 & 15) == 15 && y == _y0) || + ((y1 & 15) == 0 && y == _y1)) { + index |= 0x10000000; + } + } else { + // is the front or back most block just inside this + // chunk + if (((z0 & 15) == 15 && z == _z0) || + ((z1 & 15) == 0 && z == _z1)) { + // is the top or bottom most block just inside this + // chunk + if (((y0 & 15) == 15 && y == _y0) || + ((y1 & 15) == 0 && y == _y1)) { + index |= 0x10000000; + } + } + } - dirtyChunksLockFreeStack.Push((int *)(index)); + dirtyChunksLockFreeStack.Push((int*)(index)); #else - dirtyChunksLockFreeStack.Push((int *)(intptr_t)(uintptr_t)(index + 2)); + dirtyChunksLockFreeStack.Push( + (int*)(intptr_t)(uintptr_t)(index + 2)); #endif #ifdef _XBOX - PIXSetMarker(0,"Setting chunk %d %d %d dirty",x * 16,y * 16,z * 16); + PIXSetMarker(0, "Setting chunk %d %d %d dirty", x * 16, + y * 16, z * 16); #else - PIXSetMarkerDeprecated(0,"Setting chunk %d %d %d dirty",x * 16,y * 16,z * 16); + PIXSetMarkerDeprecated(0, "Setting chunk %d %d %d dirty", + x * 16, y * 16, z * 16); #endif - } - // setGlobalChunkFlag(x * 16, y * 16, z * 16, level, CHUNK_FLAG_DIRTY); - } - } - } - // LeaveCriticalSection(&m_csDirtyChunks); + } + // setGlobalChunkFlag(x * 16, y * + //16, z * 16, level, CHUNK_FLAG_DIRTY); + } + } + } + // LeaveCriticalSection(&m_csDirtyChunks); } -void LevelRenderer::tileChanged(int x, int y, int z) -{ - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); +void LevelRenderer::tileChanged(int x, int y, int z) { + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); } -void LevelRenderer::tileLightChanged(int x, int y, int z) -{ - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); +void LevelRenderer::tileLightChanged(int x, int y, int z) { + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); } -void LevelRenderer::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) // 4J - added level param +void LevelRenderer::setTilesDirty(int x0, int y0, int z0, int x1, int y1, + int z1, + Level* level) // 4J - added level param { - setDirty(x0 - 1, y0 - 1, z0 - 1, x1 + 1, y1 + 1, z1 + 1, level); + setDirty(x0 - 1, y0 - 1, z0 - 1, x1 + 1, y1 + 1, z1 + 1, level); } -bool inline clip(float *bb, float *frustum) -{ - for (int i = 0; i < 6; ++i, frustum += 4) - { - if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; +bool inline clip(float* bb, float* frustum) { + for (int i = 0; i < 6; ++i, frustum += 4) { + if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; - return false; - } + return false; + } - return true; + return true; } #ifdef __PS3__ -int g_listArray_layer0[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); // 8000 -int g_listArray_layer1[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); -float g_zDepth_layer0[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); // 8000 -float g_zDepth_layer1[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); +int g_listArray_layer0[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); // 8000 +int g_listArray_layer1[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); +float g_zDepth_layer0[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); // 8000 +float g_zDepth_layer1[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); volatile bool g_useIdent = false; volatile float g_maxDepthRender = 1000; volatile float g_maxHeightRender = -1000; volatile float g_offMulVal = 1; -void LevelRenderer::cull_SPU(int playerIndex, Culler *culler, float a) -{ - if(m_bSPUCullStarted[playerIndex]) - { - return; // running already - } +void LevelRenderer::cull_SPU(int playerIndex, Culler* culler, float a) { + if (m_bSPUCullStarted[playerIndex]) { + return; // running already + } - FrustumCuller *fc = (FrustumCuller *)culler; - FrustumData *fd = fc->frustum; - float fdraw[6 * 4]; - for( int i = 0; i < 6; i++ ) - { - double fx = fd->m_Frustum[i][0]; - double fy = fd->m_Frustum[i][1]; - double fz = fd->m_Frustum[i][2]; - fdraw[i * 4 + 0] = (float)fx; - fdraw[i * 4 + 1] = (float)fy; - fdraw[i * 4 + 2] = (float)fz; - fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + ( fx * -fc->xOff ) + ( fy * - fc->yOff ) + ( fz * -fc->zOff )); - } + FrustumCuller* fc = (FrustumCuller*)culler; + FrustumData* fd = fc->frustum; + float fdraw[6 * 4]; + for (int i = 0; i < 6; i++) { + double fx = fd->m_Frustum[i][0]; + double fy = fd->m_Frustum[i][1]; + double fz = fd->m_Frustum[i][2]; + fdraw[i * 4 + 0] = (float)fx; + fdraw[i * 4 + 1] = (float)fy; + fdraw[i * 4 + 2] = (float)fz; + fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + (fx * -fc->xOff) + + (fy * -fc->yOff) + (fz * -fc->zOff)); + } - memcpy(&g_cullDataIn[playerIndex].fdraw, fdraw, sizeof(fdraw)); - g_cullDataIn[playerIndex].numClipChunks = chunks[playerIndex].length; - g_cullDataIn[playerIndex].pClipChunks = (ClipChunk_SPU*)chunks[playerIndex].data; - g_cullDataIn[playerIndex].numGlobalChunks = getGlobalChunkCount(); - g_cullDataIn[playerIndex].pGlobalChunkFlags = globalChunkFlags; - g_cullDataIn[playerIndex].chunkLists = chunkLists; - g_cullDataIn[playerIndex].listArray_layer0 = g_listArray_layer0[playerIndex]; - g_cullDataIn[playerIndex].listArray_layer1 = g_listArray_layer1[playerIndex]; - g_cullDataIn[playerIndex].zDepth_layer0 = g_zDepth_layer0[playerIndex]; - g_cullDataIn[playerIndex].zDepth_layer1 = g_zDepth_layer1[playerIndex]; - g_cullDataIn[playerIndex].maxDepthRender = g_maxDepthRender; - g_cullDataIn[playerIndex].maxHeightRender = g_maxHeightRender; + memcpy(&g_cullDataIn[playerIndex].fdraw, fdraw, sizeof(fdraw)); + g_cullDataIn[playerIndex].numClipChunks = chunks[playerIndex].length; + g_cullDataIn[playerIndex].pClipChunks = + (ClipChunk_SPU*)chunks[playerIndex].data; + g_cullDataIn[playerIndex].numGlobalChunks = getGlobalChunkCount(); + g_cullDataIn[playerIndex].pGlobalChunkFlags = globalChunkFlags; + g_cullDataIn[playerIndex].chunkLists = chunkLists; + g_cullDataIn[playerIndex].listArray_layer0 = + g_listArray_layer0[playerIndex]; + g_cullDataIn[playerIndex].listArray_layer1 = + g_listArray_layer1[playerIndex]; + g_cullDataIn[playerIndex].zDepth_layer0 = g_zDepth_layer0[playerIndex]; + g_cullDataIn[playerIndex].zDepth_layer1 = g_zDepth_layer1[playerIndex]; + g_cullDataIn[playerIndex].maxDepthRender = g_maxDepthRender; + g_cullDataIn[playerIndex].maxHeightRender = g_maxHeightRender; - if(g_useIdent) - g_cullDataIn[playerIndex].clipMat = Vectormath::Aos::Matrix4::identity(); - else - { - memcpy(&g_cullDataIn[playerIndex].clipMat, &fc->frustum->modl[0], sizeof(float) * 16); - g_cullDataIn[playerIndex].clipMat[3][0] = -fc->xOff; - g_cullDataIn[playerIndex].clipMat[3][1] = -fc->yOff; - g_cullDataIn[playerIndex].clipMat[3][2] = -fc->zOff; - } + if (g_useIdent) + g_cullDataIn[playerIndex].clipMat = + Vectormath::Aos::Matrix4::identity(); + else { + memcpy(&g_cullDataIn[playerIndex].clipMat, &fc->frustum->modl[0], + sizeof(float) * 16); + g_cullDataIn[playerIndex].clipMat[3][0] = -fc->xOff; + g_cullDataIn[playerIndex].clipMat[3][1] = -fc->yOff; + g_cullDataIn[playerIndex].clipMat[3][2] = -fc->zOff; + } + C4JSpursJob_LevelRenderer_cull cullJob(&g_cullDataIn[playerIndex]); + C4JSpursJob_LevelRenderer_zSort sortJob(&g_cullDataIn[playerIndex]); - C4JSpursJob_LevelRenderer_cull cullJob(&g_cullDataIn[playerIndex]); - C4JSpursJob_LevelRenderer_zSort sortJob(&g_cullDataIn[playerIndex]); - - m_jobPort_CullSPU->submitJob(&cullJob); - m_jobPort_CullSPU->submitSync(); - // static int doSort = false; - // if(doSort) - { - m_jobPort_CullSPU->submitJob(&sortJob); - } - // doSort ^= 1; - m_bSPUCullStarted[playerIndex] = true; + m_jobPort_CullSPU->submitJob(&cullJob); + m_jobPort_CullSPU->submitSync(); + // static int doSort = false; + // if(doSort) + { + m_jobPort_CullSPU->submitJob(&sortJob); + } + // doSort ^= 1; + m_bSPUCullStarted[playerIndex] = true; } -void LevelRenderer::waitForCull_SPU() -{ - m_jobPort_CullSPU->waitForCompletion(); - int playerIndex = mc->player->GetXboxPad(); // 4J added - m_bSPUCullStarted[playerIndex] = false; +void LevelRenderer::waitForCull_SPU() { + m_jobPort_CullSPU->waitForCompletion(); + int playerIndex = mc->player->GetXboxPad(); // 4J added + m_bSPUCullStarted[playerIndex] = false; } -#endif // __PS3__ +#endif // __PS3__ -void LevelRenderer::cull(Culler *culler, float a) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +void LevelRenderer::cull(Culler* culler, float a) { + int playerIndex = mc->player->GetXboxPad(); // 4J added #if defined __PS3__ && !defined DISABLE_SPU_CODE - cull_SPU(playerIndex, culler, a); - return; -#endif // __PS3__ + cull_SPU(playerIndex, culler, a); + return; +#endif // __PS3__ + FrustumCuller* fc = (FrustumCuller*)culler; + FrustumData* fd = fc->frustum; + float fdraw[6 * 4]; + for (int i = 0; i < 6; i++) { + double fx = fd->m_Frustum[i][0]; + double fy = fd->m_Frustum[i][1]; + double fz = fd->m_Frustum[i][2]; + fdraw[i * 4 + 0] = (float)fx; + fdraw[i * 4 + 1] = (float)fy; + fdraw[i * 4 + 2] = (float)fz; + fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + (fx * -fc->xOff) + + (fy * -fc->yOff) + (fz * -fc->zOff)); + } - FrustumCuller *fc = (FrustumCuller *)culler; - FrustumData *fd = fc->frustum; - float fdraw[6 * 4]; - for( int i = 0; i < 6; i++ ) - { - double fx = fd->m_Frustum[i][0]; - double fy = fd->m_Frustum[i][1]; - double fz = fd->m_Frustum[i][2]; - fdraw[i * 4 + 0] = (float)fx; - fdraw[i * 4 + 1] = (float)fy; - fdraw[i * 4 + 2] = (float)fz; - fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + ( fx * -fc->xOff ) + ( fy * - fc->yOff ) + ( fz * -fc->zOff )); - } + ClipChunk* pClipChunk = chunks[playerIndex].data; + int vis = 0; + int total = 0; + int numWrong = 0; + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + unsigned char flags = pClipChunk->globalIdx == -1 + ? 0 + : globalChunkFlags[pClipChunk->globalIdx]; - ClipChunk *pClipChunk = chunks[playerIndex].data; - int vis = 0; - int total = 0; - int numWrong = 0; - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - unsigned char flags = pClipChunk->globalIdx == -1 ? 0 : globalChunkFlags[ pClipChunk->globalIdx ]; - - if ( (flags & CHUNK_FLAG_COMPILED ) && ( ( flags & CHUNK_FLAG_EMPTYBOTH ) != CHUNK_FLAG_EMPTYBOTH ) ) - { - bool clipres = clip(pClipChunk->aabb, fdraw); - pClipChunk->visible = clipres; - if( pClipChunk->visible ) vis++; - total++; - } - else - { - pClipChunk->visible = false; - } - pClipChunk++; - } + if ((flags & CHUNK_FLAG_COMPILED) && + ((flags & CHUNK_FLAG_EMPTYBOTH) != CHUNK_FLAG_EMPTYBOTH)) { + bool clipres = clip(pClipChunk->aabb, fdraw); + pClipChunk->visible = clipres; + if (pClipChunk->visible) vis++; + total++; + } else { + pClipChunk->visible = false; + } + pClipChunk++; + } } -void LevelRenderer::playStreamingMusic(const std::wstring& name, int x, int y, int z) -{ - if (name != L"") - { - mc->gui->setNowPlaying(L"C418 - " + name); - } - mc->soundEngine->playStreaming(name, (float) x, (float) y, (float) z, 1, 1); +void LevelRenderer::playStreamingMusic(const std::wstring& name, int x, int y, + int z) { + if (name != L"") { + mc->gui->setNowPlaying(L"C418 - " + name); + } + mc->soundEngine->playStreaming(name, (float)x, (float)y, (float)z, 1, 1); } -void LevelRenderer::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist) -{ - // 4J-PB - removed in 1.4 +void LevelRenderer::playSound(int iSound, double x, double y, double z, + float volume, float pitch, float fSoundClipDist) { + // 4J-PB - removed in 1.4 - //float dd = 16; - /*if (volume > 1) fSoundClipDist *= volume; + // float dd = 16; + /*if (volume > 1) fSoundClipDist *= volume; - // 4J - find min distance to any players rather than just the current one - float minDistSq = FLT_MAX; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( mc->localplayers[i] ) - { - float distSq = mc->localplayers[i]->distanceToSqr(x, y, z ); - if( distSq < minDistSq ) - { - minDistSq = distSq; - } - } - } + // 4J - find min distance to any players rather than just the current one + float minDistSq = FLT_MAX; + for( int i = 0; i < XUSER_MAX_COUNT; i++ ) + { + if( mc->localplayers[i] ) + { + float distSq = mc->localplayers[i]->distanceToSqr(x, y, z ); + if( distSq < minDistSq ) + { + minDistSq = distSq; + } + } + } - if (minDistSq < fSoundClipDist * fSoundClipDist) - { - mc->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, pitch); - } */ + if (minDistSq < fSoundClipDist * fSoundClipDist) + { + mc->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, + pitch); + } */ } -void LevelRenderer::playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist) -{ -} +void LevelRenderer::playSound(std::shared_ptr entity, int iSound, + double x, double y, double z, float volume, + float pitch, float fSoundClipDist) {} // 4J-PB - original function. I've changed to an enum instead of string compares -// 4J removed - +// 4J removed - /* -void LevelRenderer::addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) +void LevelRenderer::addParticle(const std::wstring& name, double x, double y, +double z, double xa, double ya, double za) { -if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) return; +if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) +return; double xd = mc->cameraTargetPlayer->x - x; double yd = mc->cameraTargetPlayer->y - y; @@ -2623,318 +2865,384 @@ if (xd * xd + yd * yd + zd * zd > particleDistance * particleDistance) return; int playerIndex = mc->player->GetXboxPad(); // 4J added -if (name== L"bubble") mc->particleEngine->add(std::shared_ptr( new BubbleParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"smoke") mc->particleEngine->add(std::shared_ptr( new SmokeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"note") mc->particleEngine->add(std::shared_ptr( new NoteParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"portal") mc->particleEngine->add(std::shared_ptr( new PortalParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"explode") mc->particleEngine->add(std::shared_ptr( new ExplodeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"flame") mc->particleEngine->add(std::shared_ptr( new FlameParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"lava") mc->particleEngine->add(std::shared_ptr( new LavaParticle(level[playerIndex], x, y, z) ) ); -else if (name== L"footstep") mc->particleEngine->add(std::shared_ptr( new FootstepParticle(textures, level[playerIndex], x, y, z) ) ); -else if (name== L"splash") mc->particleEngine->add(std::shared_ptr( new SplashParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"largesmoke") mc->particleEngine->add(std::shared_ptr( new SmokeParticle(level[playerIndex], x, y, z, xa, ya, za, 2.5f) ) ); -else if (name== L"reddust") mc->particleEngine->add(std::shared_ptr( new RedDustParticle(level[playerIndex], x, y, z, (float) xa, (float) ya, (float) za) ) ); -else if (name== L"snowballpoof") mc->particleEngine->add(std::shared_ptr( new BreakingItemParticle(level[playerIndex], x, y, z, Item::snowBall) ) ); -else if (name== L"snowshovel") mc->particleEngine->add(std::shared_ptr( new SnowShovelParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"slime") mc->particleEngine->add(std::shared_ptr( new BreakingItemParticle(level[playerIndex], x, y, z, Item::slimeBall)) ) ; -else if (name== L"heart") mc->particleEngine->add(std::shared_ptr( new HeartParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); +if (name== L"bubble") mc->particleEngine->add(std::shared_ptr( +new BubbleParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"smoke") mc->particleEngine->add(std::shared_ptr( new +SmokeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"note") mc->particleEngine->add(std::shared_ptr( new +NoteParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"portal") mc->particleEngine->add(std::shared_ptr( new +PortalParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"explode") mc->particleEngine->add(std::shared_ptr( new +ExplodeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"flame") mc->particleEngine->add(std::shared_ptr( new +FlameParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"lava") mc->particleEngine->add(std::shared_ptr( new +LavaParticle(level[playerIndex], x, y, z) ) ); else if (name== L"footstep") +mc->particleEngine->add(std::shared_ptr( new +FootstepParticle(textures, level[playerIndex], x, y, z) ) ); else if (name== +L"splash") mc->particleEngine->add(std::shared_ptr( new +SplashParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"largesmoke") mc->particleEngine->add(std::shared_ptr( new +SmokeParticle(level[playerIndex], x, y, z, xa, ya, za, 2.5f) ) ); else if +(name== L"reddust") mc->particleEngine->add(std::shared_ptr( +new RedDustParticle(level[playerIndex], x, y, z, (float) xa, (float) ya, (float) +za) ) ); else if (name== L"snowballpoof") +mc->particleEngine->add(std::shared_ptr( new +BreakingItemParticle(level[playerIndex], x, y, z, Item::snowBall) ) ); else if +(name== L"snowshovel") +mc->particleEngine->add(std::shared_ptr( new +SnowShovelParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"slime") mc->particleEngine->add(std::shared_ptr( new +BreakingItemParticle(level[playerIndex], x, y, z, Item::slimeBall)) ) ; else if +(name== L"heart") mc->particleEngine->add(std::shared_ptr( new +HeartParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); } */ -void LevelRenderer::addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za) -{ - addParticleInternal( eParticleType, x, y, z, xa, ya, za ); +void LevelRenderer::addParticle(ePARTICLE_TYPE eParticleType, double x, + double y, double z, double xa, double ya, + double za) { + addParticleInternal(eParticleType, x, y, z, xa, ya, za); } -std::shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za) -{ - if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) - { - return nullptr; - } +std::shared_ptr LevelRenderer::addParticleInternal( + ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, + double ya, double za) { + if (mc == NULL || mc->cameraTargetPlayer == NULL || + mc->particleEngine == NULL) { + return nullptr; + } - // 4J added - do some explicit checking for NaN. The normal depth clipping seems to generally work for NaN (ie they get rejected), except on optimised PS3 code which - // reverses the logic on the comparison with particleDistanceSquared and gets the opposite result to what you might expect. - if( Double::isNaN(x) ) return nullptr; - if( Double::isNaN(y) ) return nullptr; - if( Double::isNaN(z) ) return nullptr; + // 4J added - do some explicit checking for NaN. The normal depth clipping + // seems to generally work for NaN (ie they get rejected), except on + // optimised PS3 code which reverses the logic on the comparison with + // particleDistanceSquared and gets the opposite result to what you might + // expect. + if (Double::isNaN(x)) return nullptr; + if (Double::isNaN(y)) return nullptr; + if (Double::isNaN(z)) return nullptr; - int particleLevel = mc->options->particles; + int particleLevel = mc->options->particles; - Level *lev; - int playerIndex = mc->player->GetXboxPad(); // 4J added - lev = level[playerIndex]; + Level* lev; + int playerIndex = mc->player->GetXboxPad(); // 4J added + lev = level[playerIndex]; - if (particleLevel == 1) - { - // when playing at "decreased" particle level, randomly filter - // particles by setting the level to "minimal" - if (level[playerIndex]->random->nextInt(3) == 0) - { - particleLevel = 2; - } - } + if (particleLevel == 1) { + // when playing at "decreased" particle level, randomly filter + // particles by setting the level to "minimal" + if (level[playerIndex]->random->nextInt(3) == 0) { + particleLevel = 2; + } + } - // 4J - the java code doesn't distance cull these two particle types, we need to implement this behaviour differently as our distance check is - // mixed up with other things - bool distCull = true; - if ( (eParticleType == eParticleType_hugeexplosion) || (eParticleType == eParticleType_largeexplode) || (eParticleType == eParticleType_dragonbreath) ) - { - distCull = false; - } + // 4J - the java code doesn't distance cull these two particle types, we + // need to implement this behaviour differently as our distance check is + // mixed up with other things + bool distCull = true; + if ((eParticleType == eParticleType_hugeexplosion) || + (eParticleType == eParticleType_largeexplode) || + (eParticleType == eParticleType_dragonbreath)) { + distCull = false; + } - // 4J - this is a bit of hack to get communication through from the level itself, but if Minecraft::animateTickLevel is NULL then - // we are to behave as normal, and if it is set, then we should use that as a pointer to the level the particle is to be created with - // rather than try to work it out from the current player. This is because in this state we are calling from a loop that is trying - // to amalgamate particle creation between all players for a particular level. Also don't do distance clipping as it isn't for a particular - // player, and distance is already taken into account before we get here anyway by the code in Level::animateTickDoWork - if( mc->animateTickLevel == NULL ) - { - double particleDistanceSquared = 16 * 16; - double xd = 0.0f; - double yd = 0.0f; - double zd = 0.0f; + // 4J - this is a bit of hack to get communication through from the level + // itself, but if Minecraft::animateTickLevel is NULL then we are to behave + // as normal, and if it is set, then we should use that as a pointer to the + // level the particle is to be created with rather than try to work it out + // from the current player. This is because in this state we are calling + // from a loop that is trying to amalgamate particle creation between all + // players for a particular level. Also don't do distance clipping as it + // isn't for a particular player, and distance is already taken into account + // before we get here anyway by the code in Level::animateTickDoWork + if (mc->animateTickLevel == NULL) { + double particleDistanceSquared = 16 * 16; + double xd = 0.0f; + double yd = 0.0f; + double zd = 0.0f; - // 4J Stu - Changed this as we need to check all local players in case one of them is in range of this particle - // Fix for #13454 - art : note blocks do not show notes - bool inRange = false; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - std::shared_ptr thisPlayer = mc->localplayers[i]; - if(thisPlayer != NULL && level[i] == lev) - { - xd = thisPlayer->x - x; - yd = thisPlayer->y - y; - zd = thisPlayer->z - z; - if (xd * xd + yd * yd + zd * zd <= particleDistanceSquared) inRange = true; - } - } - if( (!inRange) && distCull ) return nullptr; - } - else - { - lev = mc->animateTickLevel; - } + // 4J Stu - Changed this as we need to check all local players in case + // one of them is in range of this particle Fix for #13454 - art : note + // blocks do not show notes + bool inRange = false; + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + std::shared_ptr thisPlayer = mc->localplayers[i]; + if (thisPlayer != NULL && level[i] == lev) { + xd = thisPlayer->x - x; + yd = thisPlayer->y - y; + zd = thisPlayer->z - z; + if (xd * xd + yd * yd + zd * zd <= particleDistanceSquared) + inRange = true; + } + } + if ((!inRange) && distCull) return nullptr; + } else { + lev = mc->animateTickLevel; + } - if (particleLevel > 1) - { - // TODO: If any of the particles below are necessary even if - // particles are turned off, then modify this if statement - return nullptr; - } + if (particleLevel > 1) { + // TODO: If any of the particles below are necessary even if + // particles are turned off, then modify this if statement + return nullptr; + } - std::shared_ptr particle; + std::shared_ptr particle; - switch(eParticleType) - { - case eParticleType_hugeexplosion: - particle = std::shared_ptr(new HugeExplosionSeedParticle(lev, x, y, z, xa, ya, za)); - break; - case eParticleType_largeexplode: - particle = std::shared_ptr(new HugeExplosionParticle(textures, lev, x, y, z, xa, ya, za)); - break; + switch (eParticleType) { + case eParticleType_hugeexplosion: + particle = std::shared_ptr( + new HugeExplosionSeedParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_largeexplode: + particle = std::shared_ptr( + new HugeExplosionParticle(textures, lev, x, y, z, xa, ya, za)); + break; - case eParticleType_bubble: - particle = std::shared_ptr( new BubbleParticle(lev, x, y, z, xa, ya, za) ); - break; + case eParticleType_bubble: + particle = std::shared_ptr( + new BubbleParticle(lev, x, y, z, xa, ya, za)); + break; - case eParticleType_suspended: - particle = std::shared_ptr( new SuspendedParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_depthsuspend: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_townaura: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_crit: - { - std::shared_ptr critParticle2 = std::shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); - critParticle2->CritParticle2PostConstructor(); - particle = std::shared_ptr( critParticle2 ); - // request from 343 to set pink for the needler in the Halo Texture Pack - // Set particle colour from colour-table. - unsigned int cStart = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_CritStart ); - unsigned int cEnd = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_CritEnd ); + case eParticleType_suspended: + particle = std::shared_ptr( + new SuspendedParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_depthsuspend: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_townaura: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_crit: { + std::shared_ptr critParticle2 = + std::shared_ptr( + new CritParticle2(lev, x, y, z, xa, ya, za)); + critParticle2->CritParticle2PostConstructor(); + particle = std::shared_ptr(critParticle2); + // request from 343 to set pink for the needler in the Halo Texture + // Pack Set particle colour from colour-table. + unsigned int cStart = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_CritStart); + unsigned int cEnd = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_CritEnd); - // If the start and end colours are the same, just set that colour, otherwise random between them - if(cStart==cEnd) - { - critParticle2->SetAgeUniformly(); - particle->setColor( ( (cStart>>16)&0xFF )/255.0f, ( (cStart>>8)&0xFF )/255.0, ( cStart&0xFF )/255.0 ); - } - else - { - float fStart=((float)(cStart&0xFF)); - float fDiff=(float)((cEnd-cStart)&0xFF); + // If the start and end colours are the same, just set that colour, + // otherwise random between them + if (cStart == cEnd) { + critParticle2->SetAgeUniformly(); + particle->setColor(((cStart >> 16) & 0xFF) / 255.0f, + ((cStart >> 8) & 0xFF) / 255.0, + (cStart & 0xFF) / 255.0); + } else { + float fStart = ((float)(cStart & 0xFF)); + float fDiff = (float)((cEnd - cStart) & 0xFF); - float fCol = (fStart + (Math::random() * fDiff))/255.0f; - particle->setColor( fCol, fCol, fCol ); - } - } - break; - case eParticleType_magicCrit: - { - std::shared_ptr critParticle2 = std::shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); - critParticle2->CritParticle2PostConstructor(); - particle = std::shared_ptr(critParticle2); - particle->setColor(particle->getRedCol() * 0.3f, particle->getGreenCol() * 0.8f, particle->getBlueCol()); - particle->setNextMiscAnimTex(); - } - break; - case eParticleType_smoke: - particle = std::shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_endportal: // 4J - Added. - { - SmokeParticle *tmp = new SmokeParticle(lev, x, y, z, xa, ya, za); + float fCol = (fStart + (Math::random() * fDiff)) / 255.0f; + particle->setColor(fCol, fCol, fCol); + } + } break; + case eParticleType_magicCrit: { + std::shared_ptr critParticle2 = + std::shared_ptr( + new CritParticle2(lev, x, y, z, xa, ya, za)); + critParticle2->CritParticle2PostConstructor(); + particle = std::shared_ptr(critParticle2); + particle->setColor(particle->getRedCol() * 0.3f, + particle->getGreenCol() * 0.8f, + particle->getBlueCol()); + particle->setNextMiscAnimTex(); + } break; + case eParticleType_smoke: + particle = std::shared_ptr( + new SmokeParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_endportal: // 4J - Added. + { + SmokeParticle* tmp = new SmokeParticle(lev, x, y, z, xa, ya, za); - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_EnderPortal ); - tmp->setColor( ( (col>>16)&0xFF )/255.0f, ( (col>>8)&0xFF )/255.0, ( col&0xFF )/255.0 ); + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_EnderPortal); + tmp->setColor(((col >> 16) & 0xFF) / 255.0f, + ((col >> 8) & 0xFF) / 255.0, (col & 0xFF) / 255.0); - particle = std::shared_ptr(tmp); - } - break; - case eParticleType_mobSpell: - particle = std::shared_ptr(new SpellParticle(lev, x, y, z, 0, 0, 0)); - particle->setColor((float) xa, (float) ya, (float) za); - break; - case eParticleType_spell: - particle = std::shared_ptr( new SpellParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_instantSpell: - particle = std::shared_ptr(new SpellParticle(lev, x, y, z, xa, ya, za)); - std::dynamic_pointer_cast(particle)->setBaseTex(9 * 16); - break; - case eParticleType_note: - particle = std::shared_ptr( new NoteParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_netherportal: - particle = std::shared_ptr( new NetherPortalParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_ender: - particle = std::shared_ptr( new EnderParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_enchantmenttable: - particle = std::shared_ptr(new EchantmentTableParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_explode: - particle = std::shared_ptr( new ExplodeParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_flame: - particle = std::shared_ptr( new FlameParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_lava: - particle = std::shared_ptr( new LavaParticle(lev, x, y, z) ); - break; - case eParticleType_footstep: - particle = std::shared_ptr( new FootstepParticle(textures, lev, x, y, z) ); - break; - case eParticleType_splash: - particle = std::shared_ptr( new SplashParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_largesmoke: - particle = std::shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za, 2.5f) ); - break; - case eParticleType_reddust: - particle = std::shared_ptr( new RedDustParticle(lev, x, y, z, (float) xa, (float) ya, (float) za) ); - break; - case eParticleType_snowballpoof: - particle = std::shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::snowBall, textures) ); - break; - case eParticleType_dripWater: - particle = std::shared_ptr( new DripParticle(lev, x, y, z, Material::water) ); - break; - case eParticleType_dripLava: - particle = std::shared_ptr( new DripParticle(lev, x, y, z, Material::lava) ); - break; - case eParticleType_snowshovel: - particle = std::shared_ptr( new SnowShovelParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_slime: - particle = std::shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::slimeBall, textures)); - break; - case eParticleType_heart: - particle = std::shared_ptr( new HeartParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_angryVillager: - particle = std::shared_ptr( new HeartParticle(lev, x, y + 0.5f, z, xa, ya, za) ); - particle->setMiscTex(1 + 16 * 5); - particle->setColor(1, 1, 1); - break; - case eParticleType_happyVillager: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - particle->setMiscTex(2 + 16 * 5); - particle->setColor(1, 1, 1); - break; - case eParticleType_dragonbreath: - particle = std::shared_ptr( new DragonBreathParticle(lev, x, y, z, xa, ya, za) ); - break; - default: - if( ( eParticleType >= eParticleType_iconcrack_base ) && ( eParticleType <= eParticleType_iconcrack_last ) ) - { - int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = std::shared_ptr(new BreakingItemParticle(lev, x, y, z, xa, ya, za, Item::items[id], textures, data)); - } - else if( ( eParticleType >= eParticleType_tilecrack_base ) && ( eParticleType <= eParticleType_tilecrack_last ) ) - { - int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = std::dynamic_pointer_cast( std::shared_ptr(new TerrainParticle(lev, x, y, z, xa, ya, za, Tile::tiles[id], 0, data, textures))->init(data) ); - } - } + particle = std::shared_ptr(tmp); + } break; + case eParticleType_mobSpell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, 0, 0, 0)); + particle->setColor((float)xa, (float)ya, (float)za); + break; + case eParticleType_spell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_instantSpell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, xa, ya, za)); + std::dynamic_pointer_cast(particle)->setBaseTex(9 * + 16); + break; + case eParticleType_note: + particle = std::shared_ptr( + new NoteParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_netherportal: + particle = std::shared_ptr( + new NetherPortalParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_ender: + particle = std::shared_ptr( + new EnderParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_enchantmenttable: + particle = std::shared_ptr( + new EchantmentTableParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_explode: + particle = std::shared_ptr( + new ExplodeParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_flame: + particle = std::shared_ptr( + new FlameParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_lava: + particle = + std::shared_ptr(new LavaParticle(lev, x, y, z)); + break; + case eParticleType_footstep: + particle = std::shared_ptr( + new FootstepParticle(textures, lev, x, y, z)); + break; + case eParticleType_splash: + particle = std::shared_ptr( + new SplashParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_largesmoke: + particle = std::shared_ptr( + new SmokeParticle(lev, x, y, z, xa, ya, za, 2.5f)); + break; + case eParticleType_reddust: + particle = std::shared_ptr(new RedDustParticle( + lev, x, y, z, (float)xa, (float)ya, (float)za)); + break; + case eParticleType_snowballpoof: + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, Item::snowBall, textures)); + break; + case eParticleType_dripWater: + particle = std::shared_ptr( + new DripParticle(lev, x, y, z, Material::water)); + break; + case eParticleType_dripLava: + particle = std::shared_ptr( + new DripParticle(lev, x, y, z, Material::lava)); + break; + case eParticleType_snowshovel: + particle = std::shared_ptr( + new SnowShovelParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_slime: + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, Item::slimeBall, textures)); + break; + case eParticleType_heart: + particle = std::shared_ptr( + new HeartParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_angryVillager: + particle = std::shared_ptr( + new HeartParticle(lev, x, y + 0.5f, z, xa, ya, za)); + particle->setMiscTex(1 + 16 * 5); + particle->setColor(1, 1, 1); + break; + case eParticleType_happyVillager: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + particle->setMiscTex(2 + 16 * 5); + particle->setColor(1, 1, 1); + break; + case eParticleType_dragonbreath: + particle = std::shared_ptr( + new DragonBreathParticle(lev, x, y, z, xa, ya, za)); + break; + default: + if ((eParticleType >= eParticleType_iconcrack_base) && + (eParticleType <= eParticleType_iconcrack_last)) { + int id = PARTICLE_CRACK_ID(eParticleType), + data = PARTICLE_CRACK_DATA(eParticleType); + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, xa, ya, za, Item::items[id], textures, data)); + } else if ((eParticleType >= eParticleType_tilecrack_base) && + (eParticleType <= eParticleType_tilecrack_last)) { + int id = PARTICLE_CRACK_ID(eParticleType), + data = PARTICLE_CRACK_DATA(eParticleType); + particle = std::dynamic_pointer_cast( + std::shared_ptr( + new TerrainParticle(lev, x, y, z, xa, ya, za, + Tile::tiles[id], 0, data, textures)) + ->init(data)); + } + } - if (particle != NULL) - { - mc->particleEngine->add(particle); - } + if (particle != NULL) { + mc->particleEngine->add(particle); + } - return particle; + return particle; } -void LevelRenderer::entityAdded(std::shared_ptr entity) -{ - entity->prepareCustomTextures(); - // 4J - these empty string comparisons used to check for NULL references, but we don't have string pointers (currently) in entities, - // hopefully this should be equivalent - /* 4J - removed temp */ - //if (entity->customTextureUrl != L"") textures->addHttpTexture(entity->customTextureUrl, new MobSkinTextureProcessor()); - //if (entity->customTextureUrl2 != L"") textures->addHttpTexture(entity->customTextureUrl2, new MobSkinTextureProcessor()); - - // 4J-PB - adding these from global title storage - if (entity->customTextureUrl != L"") - { - textures->addMemTexture(entity->customTextureUrl, new MobSkinMemTextureProcessor()); - } - if (entity->customTextureUrl2 != L"") - { - textures->addMemTexture(entity->customTextureUrl2, new MobSkinMemTextureProcessor()); - } - - // if (entity->customTextureUrl2 != L"") textures->addHttpTexture(entity->customTextureUrl2, new MobSkinTextureProcessor()); +void LevelRenderer::entityAdded(std::shared_ptr entity) { + entity->prepareCustomTextures(); + // 4J - these empty string comparisons used to check for NULL references, + // but we don't have string pointers (currently) in entities, hopefully this + // should be equivalent + /* 4J - removed temp */ + // if (entity->customTextureUrl != L"") + // textures->addHttpTexture(entity->customTextureUrl, new + // MobSkinTextureProcessor()); if (entity->customTextureUrl2 != L"") + // textures->addHttpTexture(entity->customTextureUrl2, new + // MobSkinTextureProcessor()); + // 4J-PB - adding these from global title storage + if (entity->customTextureUrl != L"") { + textures->addMemTexture(entity->customTextureUrl, + new MobSkinMemTextureProcessor()); + } + if (entity->customTextureUrl2 != L"") { + textures->addMemTexture(entity->customTextureUrl2, + new MobSkinMemTextureProcessor()); + } + // if (entity->customTextureUrl2 != L"") + // textures->addHttpTexture(entity->customTextureUrl2, new + // MobSkinTextureProcessor()); } -void LevelRenderer::entityRemoved(std::shared_ptr entity) -{ - /* 4J - removed temp - if (entity->customTextureUrl != L"") textures->removeHttpTexture(entity->customTextureUrl); - if (entity->customTextureUrl2 != L"") textures->removeHttpTexture(entity->customTextureUrl2); - */ - if (entity->customTextureUrl != L"") - { - textures->removeMemTexture(entity->customTextureUrl); - } - if (entity->customTextureUrl2 != L"") - { - textures->removeMemTexture(entity->customTextureUrl2); - } +void LevelRenderer::entityRemoved(std::shared_ptr entity) { + /* 4J - removed temp + if (entity->customTextureUrl != L"") + textures->removeHttpTexture(entity->customTextureUrl); if + (entity->customTextureUrl2 != L"") + textures->removeHttpTexture(entity->customTextureUrl2); + */ + if (entity->customTextureUrl != L"") { + textures->removeMemTexture(entity->customTextureUrl); + } + if (entity->customTextureUrl2 != L"") { + textures->removeMemTexture(entity->customTextureUrl2); + } } -void LevelRenderer::skyColorChanged() -{ - // 4J - no longer used +void LevelRenderer::skyColorChanged() { + // 4J - no longer used #if 0 EnterCriticalSection(&m_csDirtyChunks); for( int i = 0; i < getGlobalChunkCountForOverworld(); i++ ) @@ -2948,718 +3256,743 @@ void LevelRenderer::skyColorChanged() #endif } -void LevelRenderer::clear() -{ - MemoryTracker::releaseLists(chunkLists); +void LevelRenderer::clear() { MemoryTracker::releaseLists(chunkLists); } + +void LevelRenderer::levelEvent(std::shared_ptr source, int type, int x, + int y, int z, int data) { + int playerIndex = mc->player->GetXboxPad(); // 4J added + Random* random = level[playerIndex]->random; + switch (type) { + // case LevelEvent::SOUND_WITHER_BOSS_SPAWN: + case LevelEvent::SOUND_DRAGON_DEATH: + if (mc->cameraTargetPlayer != NULL) { + // play the sound at an offset from the player + double dx = x - mc->cameraTargetPlayer->x; + double dy = y - mc->cameraTargetPlayer->y; + double dz = z - mc->cameraTargetPlayer->z; + + double len = sqrt(dx * dx + dy * dy + dz * dz); + double sx = mc->cameraTargetPlayer->x; + double sy = mc->cameraTargetPlayer->y; + double sz = mc->cameraTargetPlayer->z; + + if (len > 0) { + sx += (dx / len) * 2; + sy += (dy / len) * 2; + sz += (dz / len) * 2; + } + + level[playerIndex]->playLocalSound( + sx, sy, sz, eSoundType_MOB_ENDERDRAGON_END, 5.0f, 1.0f); + } + break; + case LevelEvent::SOUND_CLICK_FAIL: + // level[playerIndex]->playSound(x, y, z, + // L"random.click", 1.0f, 1.2f); + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, + 1.0f, 1.2f); + break; + case LevelEvent::SOUND_CLICK: + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, + 1.0f, 1.0f); + break; + case LevelEvent::SOUND_LAUNCH: + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_BOW, + 1.0f, 1.2f); + break; + case LevelEvent::PARTICLES_SHOOT: { + int xd = (data % 3) - 1; + int zd = (data / 3 % 3) - 1; + double xp = x + xd * 0.6 + 0.5; + double yp = y + 0.5; + double zp = z + zd * 0.6 + 0.5; + for (int i = 0; i < 10; i++) { + double pow = random->nextDouble() * 0.2 + 0.01; + double xs = + xp + xd * 0.01 + (random->nextDouble() - 0.5) * zd * 0.5; + double ys = yp + (random->nextDouble() - 0.5) * 0.5; + double zs = + zp + zd * 0.01 + (random->nextDouble() - 0.5) * xd * 0.5; + double xsa = xd * pow + random->nextGaussian() * 0.01; + double ysa = -0.03 + random->nextGaussian() * 0.01; + double zsa = zd * pow + random->nextGaussian() * 0.01; + addParticle(eParticleType_smoke, xs, ys, zs, xsa, ysa, zsa); + } + break; + } + case LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH: { + double xp = x + 0.5; + double yp = y; + double zp = z + 0.5; + + ePARTICLE_TYPE particle = + PARTICLE_ICONCRACK(Item::eyeOfEnder->id, 0); + for (int i = 0; i < 8; i++) { + addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, + random->nextDouble() * 0.2, + random->nextGaussian() * .15); + } + for (double a = 0; a < PI * 2.0; a += PI * 0.05) { + addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, + zp + sin(a) * 5, cos(a) * -5, 0, sin(a) * -5); + addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, + zp + sin(a) * 5, cos(a) * -7, 0, sin(a) * -7); + } + + } break; + case LevelEvent::PARTICLES_POTION_SPLASH: { + double xp = x; + double yp = y; + double zp = z; + + ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::potion->id, 0); + for (int i = 0; i < 8; i++) { + addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, + random->nextDouble() * 0.2, + random->nextGaussian() * 0.15); + } + + int colorValue = Item::potion->getColor(data); + + float red = (float)((colorValue >> 16) & 0xff) / 255.0f; + float green = (float)((colorValue >> 8) & 0xff) / 255.0f; + float blue = (float)((colorValue >> 0) & 0xff) / 255.0f; + + ePARTICLE_TYPE particleName = eParticleType_spell; + if (Item::potion->hasInstantenousEffects(data)) { + particleName = eParticleType_instantSpell; + } + + for (int i = 0; i < 100; i++) { + double dist = random->nextDouble() * ThrownPotion::SPLASH_RANGE; + double angle = random->nextDouble() * PI * 2; + double xs = cos(angle) * dist; + double ys = 0.01 + random->nextDouble() * 0.5; + double zs = sin(angle) * dist; + + std::shared_ptr spellParticle = + addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, + zp + zs * 0.1, xs, ys, zs); + if (spellParticle != NULL) { + float randBrightness = 0.75f + random->nextFloat() * 0.25f; + spellParticle->setColor(red * randBrightness, + green * randBrightness, + blue * randBrightness); + spellParticle->setPower((float)dist); + } + } + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_GLASS, 1, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } break; + case LevelEvent::ENDERDRAGON_FIREBALL_SPLASH: { + double xp = x; + double yp = y; + double zp = z; + + ePARTICLE_TYPE particleName = eParticleType_dragonbreath; + + for (int i = 0; i < 200; i++) { + double dist = + random->nextDouble() * DragonFireball::SPLASH_RANGE; + double angle = random->nextDouble() * PI * 2; + double xs = cos(angle) * dist; + double ys = 0.01 + random->nextDouble() * 0.5; + double zs = sin(angle) * dist; + + std::shared_ptr acidParticle = + addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, + zp + zs * 0.1, xs, ys, zs); + if (acidParticle != NULL) { + float randBrightness = 0.75f + random->nextFloat() * 0.25f; + acidParticle->setPower((float)dist); + } + } + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_EXPLODE, 1, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } break; + case LevelEvent::PARTICLES_DESTROY_BLOCK: { + int t = data & Tile::TILE_NUM_MASK; + if (t > 0) { + Tile* oldTile = Tile::tiles[t]; + mc->soundEngine->play(oldTile->soundType->getBreakSound(), + x + 0.5f, y + 0.5f, z + 0.5f, + (oldTile->soundType->getVolume() + 1) / 2, + oldTile->soundType->getPitch() * 0.8f); + } + + mc->particleEngine->destroy(x, y, z, data & Tile::TILE_NUM_MASK, + (data >> Tile::TILE_NUM_SHIFT) & 0xff); + break; + } + case LevelEvent::PARTICLES_MOBTILE_SPAWN: { + for (int i = 0; i < 20; i++) { + double xP = x + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + double yP = y + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + double zP = z + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + + level[playerIndex]->addParticle(eParticleType_smoke, xP, yP, zP, + 0, 0, 0); + level[playerIndex]->addParticle(eParticleType_flame, xP, yP, zP, + 0, 0, 0); + } + break; + } + case LevelEvent::SOUND_OPEN_DOOR: + if (Math::random() < 0.5) { + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_OPEN, + 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } else { + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_CLOSE, + 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } + break; + case LevelEvent::SOUND_FIZZ: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, + 2.6f + (random->nextFloat() - random->nextFloat()) * 0.8f); + break; + case LevelEvent::SOUND_ANVIL_BROKEN: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_BREAK, + 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_ANVIL_USED: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_USE, 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_ANVIL_LAND: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_LAND, + 0.3f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_PLAY_RECORDING: { + RecordingItem* rci = + dynamic_cast(Item::items[data]); + if (rci != NULL) { + level[playerIndex]->playStreamingMusic(rci->recording, x, y, z); + } else { + // 4J-PB - only play streaming music if there isn't already some + // playing - the CD playing may have finished, and game music + // started playing already + if (!mc->soundEngine->GetIsPlayingStreamingGameMusic()) { + level[playerIndex]->playStreamingMusic( + L"", x, y, z); // 4J - used to pass NULL, but using + // empty string here now instead + } + } + mc->localplayers[playerIndex]->updateRichPresence(); + } break; + // 4J - new level event sounds brought forward from 1.2.3 + case LevelEvent::SOUND_GHAST_WARNING: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_CHARGE, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, + 80.0f); + break; + case LevelEvent::SOUND_GHAST_FIREBALL: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_FIREBALL, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, + 80.0f); + break; + case LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_DOOR_CRASH: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD_BREAK, + 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_IRON_DOOR: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_METAL, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_INFECTED: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_INFECT, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + + 1.0f); //, false); + break; + case LevelEvent::SOUND_ZOMBIE_CONVERTED: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_UNFECT, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + + 1.0f); //, false); + break; + // 4J Added TU9 to fix #77475 - TU9: Content: Art: Dragon egg + // teleport particle effect isn't present. + case LevelEvent::END_EGG_TELEPORT: + // 4J Added to show the paricles when the End egg teleports after + // being attacked + EggTile::generateTeleportParticles(level[playerIndex], x, y, z, + data); + break; + } } -void LevelRenderer::levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added - Random *random = level[playerIndex]->random; - switch (type) - { - //case LevelEvent::SOUND_WITHER_BOSS_SPAWN: - case LevelEvent::SOUND_DRAGON_DEATH: - if (mc->cameraTargetPlayer != NULL) - { - // play the sound at an offset from the player - double dx = x - mc->cameraTargetPlayer->x; - double dy = y - mc->cameraTargetPlayer->y; - double dz = z - mc->cameraTargetPlayer->z; +void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, + int progress) { + if (progress < 0 || progress >= 10) { + AUTO_VAR(it, destroyingBlocks.find(id)); + if (it != destroyingBlocks.end()) { + delete it->second; + destroyingBlocks.erase(it); + } + // destroyingBlocks.remove(id); + } else { + BlockDestructionProgress* entry = NULL; - double len = sqrt(dx * dx + dy * dy + dz * dz); - double sx = mc->cameraTargetPlayer->x; - double sy = mc->cameraTargetPlayer->y; - double sz = mc->cameraTargetPlayer->z; + AUTO_VAR(it, destroyingBlocks.find(id)); + if (it != destroyingBlocks.end()) entry = it->second; - if (len > 0) - { - sx += (dx / len) * 2; - sy += (dy / len) * 2; - sz += (dz / len) * 2; - } - - level[playerIndex]->playLocalSound(sx, sy, sz, eSoundType_MOB_ENDERDRAGON_END, 5.0f, 1.0f); - } - break; - case LevelEvent::SOUND_CLICK_FAIL: - //level[playerIndex]->playSound(x, y, z, L"random.click", 1.0f, 1.2f); - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, 1.0f, 1.2f); - break; - case LevelEvent::SOUND_CLICK: - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, 1.0f, 1.0f); - break; - case LevelEvent::SOUND_LAUNCH: - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_BOW, 1.0f, 1.2f); - break; - case LevelEvent::PARTICLES_SHOOT: - { - int xd = (data % 3) - 1; - int zd = (data / 3 % 3) - 1; - double xp = x + xd * 0.6 + 0.5; - double yp = y + 0.5; - double zp = z + zd * 0.6 + 0.5; - for (int i = 0; i < 10; i++) - { - double pow = random->nextDouble() * 0.2 + 0.01; - double xs = xp + xd * 0.01 + (random->nextDouble() - 0.5) * zd * 0.5; - double ys = yp + (random->nextDouble() - 0.5) * 0.5; - double zs = zp + zd * 0.01 + (random->nextDouble() - 0.5) * xd * 0.5; - double xsa = xd * pow + random->nextGaussian() * 0.01; - double ysa = -0.03 + random->nextGaussian() * 0.01; - double zsa = zd * pow + random->nextGaussian() * 0.01; - addParticle(eParticleType_smoke, xs, ys, zs, xsa, ysa, zsa); - } - break; - } - case LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH: - { - double xp = x + 0.5; - double yp = y; - double zp = z + 0.5; - - ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::eyeOfEnder->id,0); - for (int i = 0; i < 8; i++) - { - addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, random->nextDouble() * 0.2, random->nextGaussian() * .15); - } - for (double a = 0; a < PI * 2.0; a += PI * 0.05) - { - addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, zp + sin(a) * 5, cos(a) * -5, 0, sin(a) * -5); - addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, zp + sin(a) * 5, cos(a) * -7, 0, sin(a) * -7); - } - - } - break; - case LevelEvent::PARTICLES_POTION_SPLASH: - { - double xp = x; - double yp = y; - double zp = z; - - ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::potion->id,0); - for (int i = 0; i < 8; i++) - { - addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, random->nextDouble() * 0.2, random->nextGaussian() * 0.15); - } - - - int colorValue = Item::potion->getColor(data); - - float red = (float) ((colorValue >> 16) & 0xff) / 255.0f; - float green = (float) ((colorValue >> 8) & 0xff) / 255.0f; - float blue = (float) ((colorValue >> 0) & 0xff) / 255.0f; - - ePARTICLE_TYPE particleName = eParticleType_spell; - if (Item::potion->hasInstantenousEffects(data)) - { - particleName = eParticleType_instantSpell; - } - - for (int i = 0; i < 100; i++) - { - double dist = random->nextDouble() * ThrownPotion::SPLASH_RANGE; - double angle = random->nextDouble() * PI * 2; - double xs = cos(angle) * dist; - double ys = 0.01 + random->nextDouble() * 0.5; - double zs = sin(angle) * dist; - - std::shared_ptr spellParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (spellParticle != NULL) - { - float randBrightness = 0.75f + random->nextFloat() * 0.25f; - spellParticle->setColor(red * randBrightness, green * randBrightness, blue * randBrightness); - spellParticle->setPower((float) dist); - } - } - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_GLASS, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::ENDERDRAGON_FIREBALL_SPLASH: - { - double xp = x; - double yp = y; - double zp = z; - - ePARTICLE_TYPE particleName = eParticleType_dragonbreath; - - for (int i = 0; i < 200; i++) - { - double dist = random->nextDouble() * DragonFireball::SPLASH_RANGE; - double angle = random->nextDouble() * PI * 2; - double xs = cos(angle) * dist; - double ys = 0.01 + random->nextDouble() * 0.5; - double zs = sin(angle) * dist; - - std::shared_ptr acidParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (acidParticle != NULL) - { - float randBrightness = 0.75f + random->nextFloat() * 0.25f; - acidParticle->setPower((float) dist); - } - } - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_EXPLODE, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::PARTICLES_DESTROY_BLOCK: - { - int t = data & Tile::TILE_NUM_MASK; - if (t > 0) - { - Tile *oldTile = Tile::tiles[t]; - mc->soundEngine->play(oldTile->soundType->getBreakSound(), x + 0.5f, y + 0.5f, z + 0.5f, (oldTile->soundType->getVolume() + 1) / 2, oldTile->soundType->getPitch() * 0.8f); - } - - mc->particleEngine->destroy(x, y, z, data & Tile::TILE_NUM_MASK, (data >> Tile::TILE_NUM_SHIFT) & 0xff); - break; - } - case LevelEvent::PARTICLES_MOBTILE_SPAWN: - { - for (int i = 0; i < 20; i++) - { - - double xP = x + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - double yP = y + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - double zP = z + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - - level[playerIndex]->addParticle(eParticleType_smoke, xP, yP, zP, 0, 0, 0); - level[playerIndex]->addParticle(eParticleType_flame, xP, yP, zP, 0, 0, 0); - } - break; - } - case LevelEvent::SOUND_OPEN_DOOR: - if (Math::random() < 0.5) - { - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_OPEN, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } else { - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_CLOSE, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::SOUND_FIZZ: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, 2.6f + (random->nextFloat() - random->nextFloat()) * 0.8f); - break; - case LevelEvent::SOUND_ANVIL_BROKEN: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_BREAK, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_ANVIL_USED: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_USE, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_ANVIL_LAND: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_LAND, 0.3f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_PLAY_RECORDING: - { - RecordingItem *rci = dynamic_cast(Item::items[data]); - if (rci != NULL) - { - level[playerIndex]->playStreamingMusic(rci->recording, x, y, z); - } - else - { - // 4J-PB - only play streaming music if there isn't already some playing - the CD playing may have finished, and game music started playing already - if(!mc->soundEngine->GetIsPlayingStreamingGameMusic()) - { - level[playerIndex]->playStreamingMusic(L"", x, y, z); // 4J - used to pass NULL, but using empty string here now instead - } - } - mc->localplayers[playerIndex]->updateRichPresence(); - } - break; - // 4J - new level event sounds brought forward from 1.2.3 - case LevelEvent::SOUND_GHAST_WARNING: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_CHARGE, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, 80.0f); - break; - case LevelEvent::SOUND_GHAST_FIREBALL: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_FIREBALL, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, 80.0f); - break; - case LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_DOOR_CRASH: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD_BREAK, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_IRON_DOOR: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_METAL, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_INFECTED: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_INFECT, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f);//, false); - break; - case LevelEvent::SOUND_ZOMBIE_CONVERTED: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_UNFECT, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f);//, false); - break; - // 4J Added TU9 to fix #77475 - TU9: Content: Art: Dragon egg teleport particle effect isn't present. - case LevelEvent::END_EGG_TELEPORT: - // 4J Added to show the paricles when the End egg teleports after being attacked - EggTile::generateTeleportParticles(level[playerIndex],x,y,z,data); - break; - } + if (entry == NULL || entry->getX() != x || entry->getY() != y || + entry->getZ() != z) { + entry = new BlockDestructionProgress(id, x, y, z); + destroyingBlocks.insert( + std::unordered_map::value_type( + id, entry)); + } + entry->setProgress(progress); + entry->updateTick(ticks); + } } -void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, int progress) -{ - if (progress < 0 || progress >= 10) - { - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) - { - delete it->second; - destroyingBlocks.erase(it); - } - //destroyingBlocks.remove(id); - } - else - { - BlockDestructionProgress *entry = NULL; +void LevelRenderer::registerTextures(IconRegister* iconRegister) { + breakingTextures = new Icon*[10]; - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) entry = it->second; - - if (entry == NULL || entry->getX() != x || entry->getY() != y || entry->getZ() != z) - { - entry = new BlockDestructionProgress(id, x, y, z); - destroyingBlocks.insert( std::unordered_map::value_type(id, entry) ); - } - - entry->setProgress(progress); - entry->updateTick(ticks); - } -} - -void LevelRenderer::registerTextures(IconRegister *iconRegister) -{ - breakingTextures = new Icon*[10]; - - for (int i = 0; i < 10; i++) - { - breakingTextures[i] = iconRegister->registerIcon(L"destroy_" + _toString(i) ); - } + for (int i = 0; i < 10; i++) { + breakingTextures[i] = + iconRegister->registerIcon(L"destroy_" + _toString(i)); + } } // Gets a dimension index (0, 1, or 2) from an id ( 0, -1, 1) -int LevelRenderer::getDimensionIndexFromId(int id) -{ - return ( 3 - id ) % 3; +int LevelRenderer::getDimensionIndexFromId(int id) { return (3 - id) % 3; } + +// 4J - added for new render list handling. Render lists used to be allocated +// per chunk, but these are now allocated per fixed chunk position in our (now +// finite) maps. +int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, Level* level) { + return getGlobalIndexForChunk(x, y, z, level->dimension->id); } -// 4J - added for new render list handling. Render lists used to be allocated per chunk, but these are now allocated per fixed chunk position -// in our (now finite) maps. -int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, Level *level) -{ - return getGlobalIndexForChunk(x,y,z,level->dimension->id); +int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, + int dimensionId) { + int dimIdx = getDimensionIndexFromId(dimensionId); + // int xx = ( x / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); + // int yy = y / CHUNK_SIZE; + // int zz = ( z / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); + int xx = (Mth::intFloorDiv(x, CHUNK_XZSIZE)) + + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); + int yy = Mth::intFloorDiv(y, CHUNK_SIZE); + int zz = (Mth::intFloorDiv(z, CHUNK_XZSIZE)) + + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); + + if ((xx < 0) || (xx >= MAX_LEVEL_RENDER_SIZE[dimIdx])) return -1; + if ((zz < 0) || (zz >= MAX_LEVEL_RENDER_SIZE[dimIdx])) return -1; + if ((yy < 0) || (yy >= CHUNK_Y_COUNT)) return -1; + + int dimOffset = DIMENSION_OFFSETS[dimIdx]; + + int offset = dimOffset; // Offset caused by current dimension + offset += (zz * MAX_LEVEL_RENDER_SIZE[dimIdx] + xx) * + CHUNK_Y_COUNT; // Offset by x/z pos + offset += yy; // Offset by y pos + + return offset; } -int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, int dimensionId) -{ - int dimIdx = getDimensionIndexFromId(dimensionId); - //int xx = ( x / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); - //int yy = y / CHUNK_SIZE; - //int zz = ( z / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); - int xx = ( Mth::intFloorDiv(x, CHUNK_XZSIZE)) + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); - int yy = Mth::intFloorDiv(y, CHUNK_SIZE); - int zz = ( Mth::intFloorDiv(z, CHUNK_XZSIZE)) + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); - - if( ( xx < 0 ) || ( xx >= MAX_LEVEL_RENDER_SIZE[dimIdx] ) ) return -1; - if( ( zz < 0 ) || ( zz >= MAX_LEVEL_RENDER_SIZE[dimIdx] ) ) return -1; - if( ( yy < 0 ) || ( yy >= CHUNK_Y_COUNT ) ) return -1; - - int dimOffset = DIMENSION_OFFSETS[dimIdx]; - - int offset = dimOffset; // Offset caused by current dimension - offset += ( zz * MAX_LEVEL_RENDER_SIZE[dimIdx] + xx ) * CHUNK_Y_COUNT; // Offset by x/z pos - offset += yy; // Offset by y pos - - return offset; +bool LevelRenderer::isGlobalIndexInSameDimension(int idx, Level* level) { + int dim = getDimensionIndexFromId(level->dimension->id); + int idxDim = 0; + if (idx >= DIMENSION_OFFSETS[2]) + idxDim = 2; + else if (idx >= DIMENSION_OFFSETS[1]) + idxDim = 1; + return (dim == idxDim); } -bool LevelRenderer::isGlobalIndexInSameDimension( int idx, Level *level) -{ - int dim = getDimensionIndexFromId(level->dimension->id); - int idxDim = 0; - if( idx >= DIMENSION_OFFSETS[2] ) idxDim = 2; - else if ( idx >= DIMENSION_OFFSETS[1] ) idxDim = 1; - return (dim == idxDim); +int LevelRenderer::getGlobalChunkCount() { + return (MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * + CHUNK_Y_COUNT) + + (MAX_LEVEL_RENDER_SIZE[1] * MAX_LEVEL_RENDER_SIZE[1] * + CHUNK_Y_COUNT) + + (MAX_LEVEL_RENDER_SIZE[2] * MAX_LEVEL_RENDER_SIZE[2] * + CHUNK_Y_COUNT); } -int LevelRenderer::getGlobalChunkCount() -{ - return ( MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * CHUNK_Y_COUNT ) + - ( MAX_LEVEL_RENDER_SIZE[1] * MAX_LEVEL_RENDER_SIZE[1] * CHUNK_Y_COUNT ) + - ( MAX_LEVEL_RENDER_SIZE[2] * MAX_LEVEL_RENDER_SIZE[2] * CHUNK_Y_COUNT ); +int LevelRenderer::getGlobalChunkCountForOverworld() { + return (MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * + CHUNK_Y_COUNT); } -int LevelRenderer::getGlobalChunkCountForOverworld() -{ - return ( MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * CHUNK_Y_COUNT ); +unsigned char LevelRenderer::getGlobalChunkFlags(int x, int y, int z, + Level* level) { + int index = getGlobalIndexForChunk(x, y, z, level); + if (index == -1) { + return 0; + } else { + return globalChunkFlags[index]; + } } -unsigned char LevelRenderer::getGlobalChunkFlags(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index == -1 ) - { - return 0; - } - else - { - return globalChunkFlags[ index ]; - } -} - -void LevelRenderer::setGlobalChunkFlags(int x, int y, int z, Level *level, unsigned char flags) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::setGlobalChunkFlags(int x, int y, int z, Level* level, + unsigned char flags) { + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] = flags; + globalChunkFlags[index] = flags; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::setGlobalChunkFlag(int index, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; +void LevelRenderer::setGlobalChunkFlag(int index, unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; - if( index != -1 ) - { + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] |= sflag; + globalChunkFlags[index] |= sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::setGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::setGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] |= sflag; + globalChunkFlags[index] |= sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::clearGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::clearGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] &= ~sflag; + globalChunkFlags[index] &= ~sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -bool LevelRenderer::getGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index == -1 ) - { - return false; - } - else - { - return ( globalChunkFlags[ index ] & sflag ) == sflag; - } +bool LevelRenderer::getGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index == -1) { + return false; + } else { + return (globalChunkFlags[index] & sflag) == sflag; + } } -unsigned char LevelRenderer::incGlobalChunkRefCount(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { - unsigned char flags = globalChunkFlags[ index ]; - unsigned char refCount = (flags >> CHUNK_FLAG_REF_SHIFT ) & CHUNK_FLAG_REF_MASK; - refCount++; - flags &= ~(CHUNK_FLAG_REF_MASK<> CHUNK_FLAG_REF_SHIFT) & CHUNK_FLAG_REF_MASK; + refCount++; + flags &= ~(CHUNK_FLAG_REF_MASK << CHUNK_FLAG_REF_SHIFT); + flags |= refCount << CHUNK_FLAG_REF_SHIFT; + globalChunkFlags[index] = flags; + return refCount; + } else { + return 0; + } } -unsigned char LevelRenderer::decGlobalChunkRefCount(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { - unsigned char flags = globalChunkFlags[ index ]; - unsigned char refCount = (flags >> CHUNK_FLAG_REF_SHIFT ) & CHUNK_FLAG_REF_MASK; - refCount--; - flags &= ~(CHUNK_FLAG_REF_MASK<> CHUNK_FLAG_REF_SHIFT) & CHUNK_FLAG_REF_MASK; + refCount--; + flags &= ~(CHUNK_FLAG_REF_MASK << CHUNK_FLAG_REF_SHIFT); + flags |= refCount << CHUNK_FLAG_REF_SHIFT; + globalChunkFlags[index] = flags; - return refCount; - } - else - { - return 0; - } + return refCount; + } else { + return 0; + } } // 4J added -void LevelRenderer::fullyFlagRenderableTileEntitiesToBeRemoved() -{ - EnterCriticalSection(&m_csRenderableTileEntities); - AUTO_VAR(itChunkEnd, renderableTileEntities.end()); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != itChunkEnd; it++) - { - AUTO_VAR(itTEEnd, it->second.end()); - for( AUTO_VAR(it2, it->second.begin()); it2 != itTEEnd; it2++ ) - { - (*it2)->upgradeRenderRemoveStage(); - } - } - LeaveCriticalSection(&m_csRenderableTileEntities); +void LevelRenderer::fullyFlagRenderableTileEntitiesToBeRemoved() { + EnterCriticalSection(&m_csRenderableTileEntities); + AUTO_VAR(itChunkEnd, renderableTileEntities.end()); + for (AUTO_VAR(it, renderableTileEntities.begin()); it != itChunkEnd; it++) { + AUTO_VAR(itTEEnd, it->second.end()); + for (AUTO_VAR(it2, it->second.begin()); it2 != itTEEnd; it2++) { + (*it2)->upgradeRenderRemoveStage(); + } + } + LeaveCriticalSection(&m_csRenderableTileEntities); } -LevelRenderer::DestroyedTileManager::RecentTile::RecentTile(int x, int y, int z, Level *level) : x(x), y(y), z(z), level(level) -{ - timeout_ticks = 20; - rebuilt = false; +LevelRenderer::DestroyedTileManager::RecentTile::RecentTile(int x, int y, int z, + Level* level) + : x(x), y(y), z(z), level(level) { + timeout_ticks = 20; + rebuilt = false; } -LevelRenderer::DestroyedTileManager::RecentTile::~RecentTile() -{ - for( AUTO_VAR(it, boxes.begin()); it!= boxes.end(); it++ ) - { - delete *it; - } +LevelRenderer::DestroyedTileManager::RecentTile::~RecentTile() { + for (AUTO_VAR(it, boxes.begin()); it != boxes.end(); it++) { + delete *it; + } } -LevelRenderer::DestroyedTileManager::DestroyedTileManager() -{ - InitializeCriticalSection(&m_csDestroyedTiles); +LevelRenderer::DestroyedTileManager::DestroyedTileManager() { + InitializeCriticalSection(&m_csDestroyedTiles); } -LevelRenderer::DestroyedTileManager::~DestroyedTileManager() -{ - DeleteCriticalSection(&m_csDestroyedTiles); - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++ ) - { - delete m_destroyedTiles[i]; - } +LevelRenderer::DestroyedTileManager::~DestroyedTileManager() { + DeleteCriticalSection(&m_csDestroyedTiles); + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + delete m_destroyedTiles[i]; + } } +// For game to let this manager know that a tile is about to be destroyed (must +// be called before it actually is) +void LevelRenderer::DestroyedTileManager::destroyingTileAt(Level* level, int x, + int y, int z) { + EnterCriticalSection(&m_csDestroyedTiles); -// For game to let this manager know that a tile is about to be destroyed (must be called before it actually is) -void LevelRenderer::DestroyedTileManager::destroyingTileAt( Level *level, int x, int y, int z ) -{ - EnterCriticalSection(&m_csDestroyedTiles); + // Store a list of AABBs that the tile to be destroyed would have made, + // before we go and destroy it. This is made slightly more complicated as + // the addAABBs method for tiles adds temporary AABBs and we need permanent + // ones, so make a temporary list and then copy over - // Store a list of AABBs that the tile to be destroyed would have made, before we go and destroy it. This - // is made slightly more complicated as the addAABBs method for tiles adds temporary AABBs and we need permanent - // ones, so make a temporary list and then copy over + RecentTile* recentTile = new RecentTile(x, y, z, level); + AABB* box = AABB::newTemp((float)x, (float)y, (float)z, (float)(x + 1), + (float)(y + 1), (float)(z + 1)); + Tile* tile = Tile::tiles[level->getTile(x, y, z)]; - RecentTile *recentTile = new RecentTile(x, y, z, level); - AABB *box = AABB::newTemp((float)x, (float)y, (float)z, (float)(x+1), (float)(y+1), (float)(z+1)); - Tile *tile = Tile::tiles[level->getTile(x, y, z)]; + if (tile != NULL) { + tile->addAABBs(level, x, y, z, box, &recentTile->boxes, nullptr); + } - if (tile != NULL) - { - tile->addAABBs(level, x, y, z, box, &recentTile->boxes, nullptr); - } + // Make these temporary AABBs into permanently allocated AABBs + for (unsigned int i = 0; i < recentTile->boxes.size(); i++) { + recentTile->boxes[i] = AABB::newPermanent( + recentTile->boxes[i]->x0, recentTile->boxes[i]->y0, + recentTile->boxes[i]->z0, recentTile->boxes[i]->x1, + recentTile->boxes[i]->y1, recentTile->boxes[i]->z1); + } - // Make these temporary AABBs into permanently allocated AABBs - for( unsigned int i = 0; i < recentTile->boxes.size(); i++ ) - { - recentTile->boxes[i] = AABB::newPermanent(recentTile->boxes[i]->x0, - recentTile->boxes[i]->y0, - recentTile->boxes[i]->z0, - recentTile->boxes[i]->x1, - recentTile->boxes[i]->y1, - recentTile->boxes[i]->z1); - } + m_destroyedTiles.push_back(recentTile); - m_destroyedTiles.push_back( recentTile ); - - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -// For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile render chunk) has been updated -void LevelRenderer::DestroyedTileManager::updatedChunkAt(Level *level, int x, int y, int z, int veryNearCount) -{ - EnterCriticalSection(&m_csDestroyedTiles); +// For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile +// render chunk) has been updated +void LevelRenderer::DestroyedTileManager::updatedChunkAt(Level* level, int x, + int y, int z, + int veryNearCount) { + EnterCriticalSection(&m_csDestroyedTiles); - // There's 2 stages to this. This function is called when a renderer chunk has been rebuilt, but that chunk's render data might be grouped atomically with - // changes to other very near chunks. Therefore, we don't want to consider the render data to be fully updated until the chunk that it is in has been - // rebuilt, AND there aren't any very near things waiting to be rebuilt. + // There's 2 stages to this. This function is called when a renderer chunk + // has been rebuilt, but that chunk's render data might be grouped + // atomically with changes to other very near chunks. Therefore, we don't + // want to consider the render data to be fully updated until the chunk that + // it is in has been rebuilt, AND there aren't any very near things waiting + // to be rebuilt. - // First pass through - see if any tiles are within the chunk which is being rebuilt, and mark up by setting their rebuilt flag - bool printed = false; - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++) - { - if( ( m_destroyedTiles[i]->level == level ) && - ( m_destroyedTiles[i]->x >= x ) && ( m_destroyedTiles[i]->x < ( x + 16 ) ) && - ( m_destroyedTiles[i]->y >= y ) && ( m_destroyedTiles[i]->y < ( y + 16 ) ) && - ( m_destroyedTiles[i]->z >= z ) && ( m_destroyedTiles[i]->z < ( z + 16 ) ) ) - { - printed = true; - m_destroyedTiles[i]->rebuilt = true; - } - } + // First pass through - see if any tiles are within the chunk which is being + // rebuilt, and mark up by setting their rebuilt flag + bool printed = false; + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + if ((m_destroyedTiles[i]->level == level) && + (m_destroyedTiles[i]->x >= x) && + (m_destroyedTiles[i]->x < (x + 16)) && + (m_destroyedTiles[i]->y >= y) && + (m_destroyedTiles[i]->y < (y + 16)) && + (m_destroyedTiles[i]->z >= z) && + (m_destroyedTiles[i]->z < (z + 16))) { + printed = true; + m_destroyedTiles[i]->rebuilt = true; + } + } - // Now go through every tile that has been marked up as already being rebuilt, and fully remove it once there aren't going to be any more - // very near chunks. This might not happen on the same call to this function that rebuilt the chunk with the tile in. - if( veryNearCount <= 1 ) - { - for( unsigned int i = 0; i < m_destroyedTiles.size(); ) - { - if( m_destroyedTiles[i]->rebuilt ) - { - printed = true; - delete m_destroyedTiles[i]; - m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; - m_destroyedTiles.pop_back(); - } - else - { - i++; - } - } - } + // Now go through every tile that has been marked up as already being + // rebuilt, and fully remove it once there aren't going to be any more very + // near chunks. This might not happen on the same call to this function that + // rebuilt the chunk with the tile in. + if (veryNearCount <= 1) { + for (unsigned int i = 0; i < m_destroyedTiles.size();) { + if (m_destroyedTiles[i]->rebuilt) { + printed = true; + delete m_destroyedTiles[i]; + m_destroyedTiles[i] = + m_destroyedTiles[m_destroyedTiles.size() - 1]; + m_destroyedTiles.pop_back(); + } else { + i++; + } + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -// For game to get any AABBs that the user should be colliding with as render data has not yet been updated -void LevelRenderer::DestroyedTileManager::addAABBs( Level *level, AABB *box, AABBList *boxes ) -{ - EnterCriticalSection(&m_csDestroyedTiles); +// For game to get any AABBs that the user should be colliding with as render +// data has not yet been updated +void LevelRenderer::DestroyedTileManager::addAABBs(Level* level, AABB* box, + AABBList* boxes) { + EnterCriticalSection(&m_csDestroyedTiles); - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++ ) - { - if( m_destroyedTiles[i]->level == level ) - { - for( unsigned int j = 0; j < m_destroyedTiles[i]->boxes.size(); j++ ) - { - // If we find any AABBs intersecting the region we are interested in, add them to the output list, making a temp AABB copy so that we can destroy our own copy - // without worrying about the lifespan of the copy we've passed out - if( m_destroyedTiles[i]->boxes[j]->intersects( box ) ) - { - boxes->push_back(AABB::newTemp( m_destroyedTiles[i]->boxes[j]->x0, - m_destroyedTiles[i]->boxes[j]->y0, - m_destroyedTiles[i]->boxes[j]->z0, - m_destroyedTiles[i]->boxes[j]->x1, - m_destroyedTiles[i]->boxes[j]->y1, - m_destroyedTiles[i]->boxes[j]->z1 ) ); - } - } - } - } + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + if (m_destroyedTiles[i]->level == level) { + for (unsigned int j = 0; j < m_destroyedTiles[i]->boxes.size(); + j++) { + // If we find any AABBs intersecting the region we are + // interested in, add them to the output list, making a temp + // AABB copy so that we can destroy our own copy without + // worrying about the lifespan of the copy we've passed out + if (m_destroyedTiles[i]->boxes[j]->intersects(box)) { + boxes->push_back( + AABB::newTemp(m_destroyedTiles[i]->boxes[j]->x0, + m_destroyedTiles[i]->boxes[j]->y0, + m_destroyedTiles[i]->boxes[j]->z0, + m_destroyedTiles[i]->boxes[j]->x1, + m_destroyedTiles[i]->boxes[j]->y1, + m_destroyedTiles[i]->boxes[j]->z1)); + } + } + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -void LevelRenderer::DestroyedTileManager::tick() -{ - EnterCriticalSection(&m_csDestroyedTiles); +void LevelRenderer::DestroyedTileManager::tick() { + EnterCriticalSection(&m_csDestroyedTiles); - // Remove any tiles that have timed out - for( unsigned int i = 0; i < m_destroyedTiles.size(); ) - { - if( --m_destroyedTiles[i]->timeout_ticks == 0 ) - { - delete m_destroyedTiles[i]; - m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; - m_destroyedTiles.pop_back(); - } - else - { - i++; - } - } + // Remove any tiles that have timed out + for (unsigned int i = 0; i < m_destroyedTiles.size();) { + if (--m_destroyedTiles[i]->timeout_ticks == 0) { + delete m_destroyedTiles[i]; + m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; + m_destroyedTiles.pop_back(); + } else { + i++; + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } #ifdef _LARGE_WORLDS -void LevelRenderer::staticCtor() -{ - s_rebuildCompleteEvents = new C4JThread::EventArray(MAX_CHUNK_REBUILD_THREADS); - char threadName[256]; - for(unsigned int i = 0; i < MAX_CHUNK_REBUILD_THREADS; ++i) - { - sprintf(threadName,"Rebuild Chunk Thread %d\n",i); - rebuildThreads[i] = new C4JThread(rebuildChunkThreadProc,(void *)(intptr_t)i,threadName); +void LevelRenderer::staticCtor() { + s_rebuildCompleteEvents = + new C4JThread::EventArray(MAX_CHUNK_REBUILD_THREADS); + char threadName[256]; + for (unsigned int i = 0; i < MAX_CHUNK_REBUILD_THREADS; ++i) { + sprintf(threadName, "Rebuild Chunk Thread %d\n", i); + rebuildThreads[i] = new C4JThread(rebuildChunkThreadProc, + (void*)(intptr_t)i, threadName); - s_activationEventA[i] = new C4JThread::Event(); + s_activationEventA[i] = new C4JThread::Event(); - // Threads 1,3 and 5 are generally idle so use them - if((i%3) == 0) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_A); - else if((i%3) == 1) - { - rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_B); + // Threads 1,3 and 5 are generally idle so use them + if ((i % 3) == 0) + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_A); + else if ((i % 3) == 1) { + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_B); #ifdef __ORBIS__ - rebuildThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + rebuildThreads[i]->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also + // used for Matching 2, and that + // priority of that seems to be + // always at default no matter + // what we set it to. Prioritise + // this below Matching 2. #endif - } - else if((i%3) == 2) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_C); + } else if ((i % 3) == 2) + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_C); - //ResumeThread( saveThreads[j] ); - rebuildThreads[i]->Run(); - } + // ResumeThread( saveThreads[j] ); + rebuildThreads[i]->Run(); + } } -int LevelRenderer::rebuildChunkThreadProc(void *lpParam) -{ - Vec3::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); - RenderManager.InitialiseContext(); - Chunk::CreateNewThreadStorage(); - Tile::CreateNewThreadStorage(); - - int index = (int)(uintptr_t)lpParam; - - while(true) - - { - s_activationEventA[index]->WaitForSignal(INFINITE); +int LevelRenderer::rebuildChunkThreadProc(void* lpParam) { + Vec3::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Tesselator::CreateNewThreadStorage(1024 * 1024); + RenderManager.InitialiseContext(); + Chunk::CreateNewThreadStorage(); + Tile::CreateNewThreadStorage(); - //app.DebugPrintf("Rebuilding permaChunk %d\n", index + 1); - permaChunk[index + 1].rebuild(); + int index = (int)(uintptr_t)lpParam; - // Inform the producer thread that we are done with this chunk - s_rebuildCompleteEvents->Set(index); - } + while (true) - return 0; + { + s_activationEventA[index]->WaitForSignal(INFINITE); + + // app.DebugPrintf("Rebuilding permaChunk %d\n", index + 1); + permaChunk[index + 1].rebuild(); + + // Inform the producer thread that we are done with this chunk + s_rebuildCompleteEvents->Set(index); + } + + return 0; } #endif -// This is called when chunks require rebuilding, but they haven't been added individually to the dirtyChunksLockFreeStack. Once in this -// state, the rebuilding thread will keep assuming there are dirty chunks until it has had a full pass through the chunks and found no dirty ones -void LevelRenderer::nonStackDirtyChunksAdded() -{ - dirtyChunksLockFreeStack.Push((int *)1); +// This is called when chunks require rebuilding, but they haven't been added +// individually to the dirtyChunksLockFreeStack. Once in this state, the +// rebuilding thread will keep assuming there are dirty chunks until it has had +// a full pass through the chunks and found no dirty ones +void LevelRenderer::nonStackDirtyChunksAdded() { + dirtyChunksLockFreeStack.Push((int*)1); } diff --git a/Minecraft.Client/Rendering/LevelRenderer.h b/Minecraft.Client/Rendering/LevelRenderer.h index 65a82d4be..da75e8345 100644 --- a/Minecraft.Client/Rendering/LevelRenderer.h +++ b/Minecraft.Client/Rendering/LevelRenderer.h @@ -6,7 +6,7 @@ #include "../../Minecraft.World/Level/Level.h" #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ #ifdef __PS3__ #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" #endif @@ -25,255 +25,313 @@ class BlockDestructionProgress; class IconRegister; class Tesselator; - -// AP - this is a system that works out which chunks actually need to be grouped together via the deferral system when doing chunk::rebuild. Doing this will reduce the number -// of chunks built in a single group and reduce the chance of seeing through the landscape when digging near the edges/corners of a chunk. -// I've added another chunk flag to mark a chunk critical so it swipes a bit from the reference count value (goes to 3 bits to 2). This works on Vita because it doesn't have -// split screen reference counting. +// AP - this is a system that works out which chunks actually need to be grouped +// together via the deferral system when doing chunk::rebuild. Doing this will +// reduce the number of chunks built in a single group and reduce the chance of +// seeing through the landscape when digging near the edges/corners of a chunk. +// I've added another chunk flag to mark a chunk critical so it swipes a bit +// from the reference count value (goes to 3 bits to 2). This works on Vita +// because it doesn't have split screen reference counting. #ifdef __PSVITA__ #define _CRITICAL_CHUNKS #endif -class LevelRenderer : public LevelListener -{ - friend class Chunk; +class LevelRenderer : public LevelListener { + friend class Chunk; + public: - static const int CHUNK_XZSIZE = 16; + static const int CHUNK_XZSIZE = 16; #ifdef _LARGE_WORLDS - static const int CHUNK_SIZE = 16; + static const int CHUNK_SIZE = 16; #else - static const int CHUNK_SIZE = 16; + static const int CHUNK_SIZE = 16; #endif - static const int CHUNK_Y_COUNT = Level::maxBuildHeight / CHUNK_SIZE; + static const int CHUNK_Y_COUNT = Level::maxBuildHeight / CHUNK_SIZE; #if defined _XBOX_ONE - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 512 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 512 * 1024 * 1024; // 4J - added #elif defined __ORBIS__ - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 448 * 1024 * 1024; // 4J - added - hard limit is 512 so giving a lot of headroom here for fragmentation (have seen 16MB lost to fragmentation in multiplayer crash dump before) + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 448 * 1024 * + 1024; // 4J - added - hard limit is 512 so giving a lot of headroom + // here for fragmentation (have seen 16MB lost to fragmentation + // in multiplayer crash dump before) #elif defined __PS3__ - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 110 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 110 * 1024 * 1024; // 4J - added #else - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 55 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 55 * 1024 * 1024; // 4J - added #endif public: - LevelRenderer(Minecraft *mc, Textures *textures); -private: - void renderStars(); - void createCloudMesh(); // 4J added -public: - void setLevel(int playerIndex, MultiPlayerLevel *level); - void allChanged(); - void allChanged(int playerIndex); + LevelRenderer(Minecraft* mc, Textures* textures); - // 4J-PB added - void AddDLCSkinsToMemTextures(); -public: - void renderEntities(Vec3 *cam, Culler *culler, float a); - std::wstring gatherStats1(); - std::wstring gatherStats2(); private: - void resortChunks(int xc, int yc, int zc); + void renderStars(); + void createCloudMesh(); // 4J added public: - int render(std::shared_ptr player, int layer, double alpha, bool updateChunks); -private: - int renderChunks(int from, int to, int layer, double alpha); -public: - int activePlayers(); // 4J - added -public: - void renderSameAsLast(int layer, double alpha); - void tick(); - void renderSky(float alpha); - void renderHaloRing(float alpha); - void renderClouds(float alpha); - bool isInCloud(double x, double y, double z, float alpha); - void renderAdvancedClouds(float alpha); - bool updateDirtyChunks(); + void setLevel(int playerIndex, MultiPlayerLevel* level); + void allChanged(); + void allChanged(int playerIndex); + + // 4J-PB added + void AddDLCSkinsToMemTextures(); public: - void renderHit(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a); - void renderDestroyAnimation(Tesselator *t, std::shared_ptr player, float a); - void renderHitOutline(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a); - void render(AABB *b); - void setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param - void tileChanged(int x, int y, int z); - void tileLightChanged(int x, int y, int z); - void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param + void renderEntities(Vec3* cam, Culler* culler, float a); + std::wstring gatherStats1(); + std::wstring gatherStats2(); + +private: + void resortChunks(int xc, int yc, int zc); + +public: + int render(std::shared_ptr player, int layer, double alpha, + bool updateChunks); + +private: + int renderChunks(int from, int to, int layer, double alpha); + +public: + int activePlayers(); // 4J - added +public: + void renderSameAsLast(int layer, double alpha); + void tick(); + void renderSky(float alpha); + void renderHaloRing(float alpha); + void renderClouds(float alpha); + bool isInCloud(double x, double y, double z, float alpha); + void renderAdvancedClouds(float alpha); + bool updateDirtyChunks(); + +public: + void renderHit(std::shared_ptr player, HitResult* h, int mode, + std::shared_ptr inventoryItem, float a); + void renderDestroyAnimation(Tesselator* t, std::shared_ptr player, + float a); + void renderHitOutline(std::shared_ptr player, HitResult* h, + int mode, std::shared_ptr inventoryItem, + float a); + void render(AABB* b); + void setDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param + void tileChanged(int x, int y, int z); + void tileLightChanged(int x, int y, int z); + void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param #ifdef __PS3__ - void cull_SPU(int playerIndex, Culler *culler, float a); - void waitForCull_SPU(); - C4JSpursJobQueue::Port* m_jobPort_CullSPU; - C4JSpursJobQueue::Port* m_jobPort_FindNearestChunk; - bool m_bSPUCullStarted[4]; -#endif // __PS3__ - void cull(Culler *culler, float a); - void playStreamingMusic(const std::wstring& name, int x, int y, int z); - void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f); - void playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f); - void addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za); // 4J added - std::shared_ptr addParticleInternal(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za); // 4J added - void entityAdded(std::shared_ptr entity); - void entityRemoved(std::shared_ptr entity); - void playerRemoved(std::shared_ptr entity) {} // 4J added - for when a player is removed from the level's player array, not just the entity storage - void skyColorChanged(); - void clear(); - void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data); - void destroyTileProgress(int id, int x, int y, int z, int progress); - void registerTextures(IconRegister *iconRegister); + void cull_SPU(int playerIndex, Culler* culler, float a); + void waitForCull_SPU(); + C4JSpursJobQueue::Port* m_jobPort_CullSPU; + C4JSpursJobQueue::Port* m_jobPort_FindNearestChunk; + bool m_bSPUCullStarted[4]; +#endif // __PS3__ + void cull(Culler* culler, float a); + void playStreamingMusic(const std::wstring& name, int x, int y, int z); + void playSound(int iSound, double x, double y, double z, float volume, + float pitch, float fSoundClipDist = 16.0f); + void playSound(std::shared_ptr entity, int iSound, double x, + double y, double z, float volume, float pitch, + float fSoundClipDist = 16.0f); + void addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, + double xa, double ya, double za); // 4J added + std::shared_ptr addParticleInternal(ePARTICLE_TYPE eParticleType, + double x, double y, double z, + double xa, double ya, + double za); // 4J added + void entityAdded(std::shared_ptr entity); + void entityRemoved(std::shared_ptr entity); + void playerRemoved(std::shared_ptr entity) { + } // 4J added - for when a player is removed from the level's player array, + // not just the entity storage + void skyColorChanged(); + void clear(); + void levelEvent(std::shared_ptr source, int type, int x, int y, + int z, int data); + void destroyTileProgress(int id, int x, int y, int z, int progress); + void registerTextures(IconRegister* iconRegister); + + typedef std::unordered_map >, + IntKeyHash, IntKeyEq> + rteMap; - typedef std::unordered_map >, IntKeyHash, IntKeyEq> rteMap; private: + // debug + int m_freezeticks; // used to freeze the clouds - // debug - int m_freezeticks; // used to freeze the clouds + // 4J - this block of declarations was scattered round the code but have + // gathered everything into one place + rteMap renderableTileEntities; // 4J - changed - was + // std::vector, + // now hashed by chunk so we can find them + CRITICAL_SECTION m_csRenderableTileEntities; + MultiPlayerLevel* level[4]; // 4J - now one per player + Textures* textures; + // std::vector *sortedChunks[4]; // 4J - removed - not + // sorting our chunks anymore + ClipChunkArray chunks[4]; // 4J - now one per player + int lastPlayerCount[4]; // 4J - added + int xChunks, yChunks, zChunks; + int chunkLists; + Minecraft* mc; + TileRenderer* tileRenderer[4]; // 4J - now one per player + int ticks; + int starList, skyList, darkList, haloRingList; + int cloudList; // 4J added + int xMinChunk, yMinChunk, zMinChunk; + int xMaxChunk, yMaxChunk, zMaxChunk; + int lastViewDistance; + int noEntityRenderFrames; + int totalEntities; + int renderedEntities; + int culledEntities; + int chunkFixOffs; + std::vector _renderChunks; + int frame; + int repeatList; + double xOld[4]; // 4J - now one per player + double yOld[4]; // 4J - now one per player + double zOld[4]; // 4J - now one per player - // 4J - this block of declarations was scattered round the code but have gathered everything into one place - rteMap renderableTileEntities; // 4J - changed - was std::vector, now hashed by chunk so we can find them - CRITICAL_SECTION m_csRenderableTileEntities; - MultiPlayerLevel *level[4]; // 4J - now one per player - Textures *textures; - // std::vector *sortedChunks[4]; // 4J - removed - not sorting our chunks anymore - ClipChunkArray chunks[4]; // 4J - now one per player - int lastPlayerCount[4]; // 4J - added - int xChunks, yChunks, zChunks; - int chunkLists; - Minecraft *mc; - TileRenderer *tileRenderer[4]; // 4J - now one per player - int ticks; - int starList, skyList, darkList, haloRingList; - int cloudList; // 4J added - int xMinChunk, yMinChunk, zMinChunk; - int xMaxChunk, yMaxChunk, zMaxChunk; - int lastViewDistance; - int noEntityRenderFrames; - int totalEntities; - int renderedEntities; - int culledEntities; - int chunkFixOffs; - std::vector _renderChunks; - int frame; - int repeatList; - double xOld[4]; // 4J - now one per player - double yOld[4]; // 4J - now one per player - double zOld[4]; // 4J - now one per player + int totalChunks, offscreenChunks, occludedChunks, renderedChunks, + emptyChunks; + static const int RENDERLISTS_LENGTH = 4; // 4J - added + OffsettedRenderList renderLists[RENDERLISTS_LENGTH]; - int totalChunks, offscreenChunks, occludedChunks, renderedChunks, emptyChunks; - static const int RENDERLISTS_LENGTH = 4; // 4J - added - OffsettedRenderList renderLists[RENDERLISTS_LENGTH]; - - std::unordered_map destroyingBlocks; - Icon **breakingTextures; + std::unordered_map destroyingBlocks; + Icon** breakingTextures; public: - void fullyFlagRenderableTileEntitiesToBeRemoved(); // 4J added + void fullyFlagRenderableTileEntitiesToBeRemoved(); // 4J added - CRITICAL_SECTION m_csDirtyChunks; - bool m_nearDirtyChunk; + CRITICAL_SECTION m_csDirtyChunks; + bool m_nearDirtyChunk; + // 4J - Destroyed Tile Management - these things added so we can track tiles + // which have been recently destroyed, and provide temporary collision for + // them until the render data has been updated to reflect this change + class DestroyedTileManager { + private: + class RecentTile { + public: + int x; + int y; + int z; + Level* level; + AABBList boxes; + int timeout_ticks; + bool rebuilt; + RecentTile(int x, int y, int z, Level* level); + ~RecentTile(); + }; + CRITICAL_SECTION m_csDestroyedTiles; + std::vector m_destroyedTiles; - // 4J - Destroyed Tile Management - these things added so we can track tiles which have been recently destroyed, and - // provide temporary collision for them until the render data has been updated to reflect this change - class DestroyedTileManager - { - private: - class RecentTile - { - public: - int x; - int y; - int z; - Level *level; - AABBList boxes; - int timeout_ticks; - bool rebuilt; - RecentTile(int x, int y, int z, Level *level); - ~RecentTile(); - }; - CRITICAL_SECTION m_csDestroyedTiles; - std::vector m_destroyedTiles; - public: - void destroyingTileAt( Level *level, int x, int y, int z ); // For game to let this manager know that a tile is about to be destroyed (must be called before it actually is) - void updatedChunkAt( Level * level, int x, int y, int z, int veryNearCount ); // For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile render chunk) has been updated - void addAABBs( Level *level, AABB *box, AABBList *boxes ); // For game to get any AABBs that the user should be colliding with as render data has not yet been updated - void tick(); - DestroyedTileManager(); - ~DestroyedTileManager(); - }; - DestroyedTileManager *destroyedTileManager; + public: + void destroyingTileAt( + Level* level, int x, int y, + int z); // For game to let this manager know that a tile is about + // to be destroyed (must be called before it actually is) + void updatedChunkAt( + Level* level, int x, int y, int z, + int veryNearCount); // For chunk rebuilding to inform the manager + // that a chunk (a 16x16x16 tile render chunk) + // has been updated + void addAABBs(Level* level, AABB* box, + AABBList* boxes); // For game to get any AABBs that the + // user should be colliding with as + // render data has not yet been updated + void tick(); + DestroyedTileManager(); + ~DestroyedTileManager(); + }; + DestroyedTileManager* destroyedTileManager; - float destroyProgress; + float destroyProgress; - // 4J - added for new render list handling - // This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side - // so that we can render the "infinite" sea at the edges - static const int MAX_LEVEL_RENDER_SIZE[3]; - static const int DIMENSION_OFFSETS[3]; - // This is the TOTAL area of columns of chunks to be allocated for render round the players. So for one player, it would be a region of - // sqrt(PLAYER_RENDER_AREA) x sqrt(PLAYER_RENDER_AREA) + // 4J - added for new render list handling + // This defines the maximum size of renderable level, must be big enough to + // cope with actual size of level + view distance at each side so that we + // can render the "infinite" sea at the edges + static const int MAX_LEVEL_RENDER_SIZE[3]; + static const int DIMENSION_OFFSETS[3]; + // This is the TOTAL area of columns of chunks to be allocated for render + // round the players. So for one player, it would be a region of + // sqrt(PLAYER_RENDER_AREA) x sqrt(PLAYER_RENDER_AREA) #ifdef _LARGE_WORLDS - static const int PLAYER_VIEW_DISTANCE = 18; // Straight line distance from centre to extent of visible world - static const int PLAYER_RENDER_AREA = (PLAYER_VIEW_DISTANCE * PLAYER_VIEW_DISTANCE * 4); + static const int PLAYER_VIEW_DISTANCE = + 18; // Straight line distance from centre to extent of visible world + static const int PLAYER_RENDER_AREA = + (PLAYER_VIEW_DISTANCE * PLAYER_VIEW_DISTANCE * 4); #else - static const int PLAYER_RENDER_AREA = 400; + static const int PLAYER_RENDER_AREA = 400; #endif - static int getDimensionIndexFromId(int id); - static int getGlobalIndexForChunk(int x, int y, int z, Level *level); - static int getGlobalIndexForChunk(int x, int y, int z, int dimensionId); - static bool isGlobalIndexInSameDimension( int idx, Level *level); - static int getGlobalChunkCount(); - static int getGlobalChunkCountForOverworld(); + static int getDimensionIndexFromId(int id); + static int getGlobalIndexForChunk(int x, int y, int z, Level* level); + static int getGlobalIndexForChunk(int x, int y, int z, int dimensionId); + static bool isGlobalIndexInSameDimension(int idx, Level* level); + static int getGlobalChunkCount(); + static int getGlobalChunkCountForOverworld(); - // Get/set/clear individual flags - bool getGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); - void setGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); - void setGlobalChunkFlag(int index, unsigned char flag, unsigned char shift = 0); - void clearGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); + // Get/set/clear individual flags + bool getGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); + void setGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); + void setGlobalChunkFlag(int index, unsigned char flag, + unsigned char shift = 0); + void clearGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); - // Get/set whole byte of flags - unsigned char getGlobalChunkFlags(int x, int y, int z, Level *level); - void setGlobalChunkFlags(int x, int y, int z, Level *level, unsigned char flags); + // Get/set whole byte of flags + unsigned char getGlobalChunkFlags(int x, int y, int z, Level* level); + void setGlobalChunkFlags(int x, int y, int z, Level* level, + unsigned char flags); - // Reference counting - unsigned char incGlobalChunkRefCount(int x, int y, int z, Level *level); - unsigned char decGlobalChunkRefCount(int x, int y, int z, Level *level); + // Reference counting + unsigned char incGlobalChunkRefCount(int x, int y, int z, Level* level); + unsigned char decGlobalChunkRefCount(int x, int y, int z, Level* level); - // Actual storage for flags - unsigned char *globalChunkFlags; + // Actual storage for flags + unsigned char* globalChunkFlags; - // The flag definitions - static const int CHUNK_FLAG_COMPILED = 0x01; - static const int CHUNK_FLAG_DIRTY = 0x02; - static const int CHUNK_FLAG_EMPTY0 = 0x04; - static const int CHUNK_FLAG_EMPTY1 = 0x08; - static const int CHUNK_FLAG_EMPTYBOTH = 0x0c; - static const int CHUNK_FLAG_NOTSKYLIT = 0x10; + // The flag definitions + static const int CHUNK_FLAG_COMPILED = 0x01; + static const int CHUNK_FLAG_DIRTY = 0x02; + static const int CHUNK_FLAG_EMPTY0 = 0x04; + static const int CHUNK_FLAG_EMPTY1 = 0x08; + static const int CHUNK_FLAG_EMPTYBOTH = 0x0c; + static const int CHUNK_FLAG_NOTSKYLIT = 0x10; #ifdef _CRITICAL_CHUNKS - static const int CHUNK_FLAG_CRITICAL = 0x20; - static const int CHUNK_FLAG_CUT_OUT = 0x40; - static const int CHUNK_FLAG_REF_MASK = 0x01; - static const int CHUNK_FLAG_REF_SHIFT = 7; + static const int CHUNK_FLAG_CRITICAL = 0x20; + static const int CHUNK_FLAG_CUT_OUT = 0x40; + static const int CHUNK_FLAG_REF_MASK = 0x01; + static const int CHUNK_FLAG_REF_SHIFT = 7; #else - static const int CHUNK_FLAG_REF_MASK = 0x07; - static const int CHUNK_FLAG_REF_SHIFT = 5; + static const int CHUNK_FLAG_REF_MASK = 0x07; + static const int CHUNK_FLAG_REF_SHIFT = 5; #endif - XLockFreeStack dirtyChunksLockFreeStack; + XLockFreeStack dirtyChunksLockFreeStack; - bool dirtyChunkPresent; - __int64 lastDirtyChunkFound; - static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 250; + bool dirtyChunkPresent; + __int64 lastDirtyChunkFound; + static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 250; #ifdef _LARGE_WORLDS - static const int MAX_CONCURRENT_CHUNK_REBUILDS = 4; - static const int MAX_CHUNK_REBUILD_THREADS = MAX_CONCURRENT_CHUNK_REBUILDS - 1; - static Chunk permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; - static C4JThread *rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; - static C4JThread::EventArray *s_rebuildCompleteEvents; - static C4JThread::Event *s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; - static void staticCtor(); - static int rebuildChunkThreadProc(void *lpParam); + static const int MAX_CONCURRENT_CHUNK_REBUILDS = 4; + static const int MAX_CHUNK_REBUILD_THREADS = + MAX_CONCURRENT_CHUNK_REBUILDS - 1; + static Chunk permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; + static C4JThread* rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; + static C4JThread::EventArray* s_rebuildCompleteEvents; + static C4JThread::Event* s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; + static void staticCtor(); + static int rebuildChunkThreadProc(void* lpParam); - CRITICAL_SECTION m_csChunkFlags; + CRITICAL_SECTION m_csChunkFlags; #endif - void nonStackDirtyChunksAdded(); + void nonStackDirtyChunksAdded(); }; diff --git a/Minecraft.Client/Rendering/Lighting.cpp b/Minecraft.Client/Rendering/Lighting.cpp index eafba1dfd..c0eb8e562 100644 --- a/Minecraft.Client/Rendering/Lighting.cpp +++ b/Minecraft.Client/Rendering/Lighting.cpp @@ -3,19 +3,16 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/Util/Vec3.h" -FloatBuffer *Lighting::lb = new FloatBuffer(16); +FloatBuffer* Lighting::lb = new FloatBuffer(16); - -void Lighting::turnOff() -{ +void Lighting::turnOff() { glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_LIGHT1); glDisable(GL_COLOR_MATERIAL); } -void Lighting::turnOn() -{ +void Lighting::turnOn() { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); @@ -25,7 +22,7 @@ void Lighting::turnOn() float d = 0.6f; float s = 0.0f; - Vec3 *l = Vec3::newTemp(0.2f, 1.0f, -0.7f)->normalize(); + Vec3* l = Vec3::newTemp(0.2f, 1.0f, -0.7f)->normalize(); glLight(GL_LIGHT0, GL_POSITION, getBuffer(l->x, l->y, l->z, 0)); glLight(GL_LIGHT0, GL_DIFFUSE, getBuffer(d, d, d, 1)); glLight(GL_LIGHT0, GL_AMBIENT, getBuffer(0.0f, 0.0f, 0.0f, 1.0f)); @@ -39,27 +36,23 @@ void Lighting::turnOn() glShadeModel(GL_FLAT); glLightModel(GL_LIGHT_MODEL_AMBIENT, getBuffer(a, a, a, 1)); - } -FloatBuffer *Lighting::getBuffer(double a, double b, double c, double d) -{ - return getBuffer((float) a, (float) b, (float) c, (float) d); +FloatBuffer* Lighting::getBuffer(double a, double b, double c, double d) { + return getBuffer((float)a, (float)b, (float)c, (float)d); } -FloatBuffer *Lighting::getBuffer(float a, float b, float c, float d) -{ +FloatBuffer* Lighting::getBuffer(float a, float b, float c, float d) { lb->clear(); lb->put(a)->put(b)->put(c)->put(d); lb->flip(); return lb; } -void Lighting::turnOnGui() -{ - glPushMatrix(); - glRotatef(-30, 0, 1, 0); - glRotatef(165, 1, 0, 0); - turnOn(); - glPopMatrix(); +void Lighting::turnOnGui() { + glPushMatrix(); + glRotatef(-30, 0, 1, 0); + glRotatef(165, 1, 0, 0); + turnOn(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Lighting.h b/Minecraft.Client/Rendering/Lighting.h index c06fd5399..561406c79 100644 --- a/Minecraft.Client/Rendering/Lighting.h +++ b/Minecraft.Client/Rendering/Lighting.h @@ -1,16 +1,16 @@ #pragma once class FloatBuffer; -class Lighting -{ +class Lighting { private: - static FloatBuffer *lb; + static FloatBuffer* lb; public: - static void turnOff(); + static void turnOff(); static void turnOn(); - static void turnOnGui(); + static void turnOnGui(); + private: - static FloatBuffer *getBuffer(double a, double b, double c, double d); - static FloatBuffer *getBuffer(float a, float b, float c, float d); + static FloatBuffer* getBuffer(double a, double b, double c, double d); + static FloatBuffer* getBuffer(float a, float b, float c, float d); }; diff --git a/Minecraft.Client/Rendering/Minimap.cpp b/Minecraft.Client/Rendering/Minimap.cpp index 51126a522..bf8c61b2a 100644 --- a/Minecraft.Client/Rendering/Minimap.cpp +++ b/Minecraft.Client/Rendering/Minimap.cpp @@ -9,173 +9,192 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.material.h" #ifdef __ORBIS__ -short Minimap::LUT[256]; // 4J added +short Minimap::LUT[256]; // 4J added #else -int Minimap::LUT[256]; // 4J added +int Minimap::LUT[256]; // 4J added #endif -bool Minimap::genLUT = true; // 4J added +bool Minimap::genLUT = true; // 4J added -Minimap::Minimap(Font *font, Options *options, Textures *textures, bool optimised) -{ +Minimap::Minimap(Font* font, Options* options, Textures* textures, + bool optimised) { #ifdef __PS3__ - // we're using the RSX now to upload textures to vram, so we need the main ram textures allocated from io space - this->pixels = intArray((int*)RenderManager.allocIOMem(w*h*sizeof(int)), 16*16); + // we're using the RSX now to upload textures to vram, so we need the main + // ram textures allocated from io space + this->pixels = + intArray((int*)RenderManager.allocIOMem(w * h * sizeof(int)), 16 * 16); #elif defined __ORBIS__ - this->pixels = shortArray(w*h); + this->pixels = shortArray(w * h); #else - this->pixels = intArray(w*h); + this->pixels = intArray(w * h); #endif this->options = options; this->font = font; - BufferedImage *img = new BufferedImage(w, h, BufferedImage::TYPE_INT_ARGB); + BufferedImage* img = new BufferedImage(w, h, BufferedImage::TYPE_INT_ARGB); #ifdef __ORBIS__ - mapTexture = textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw5551, false ); // 4J - make sure we aren't mipmapping as we never set the data for mipmaps + mapTexture = + textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw5551, + false); // 4J - make sure we aren't mipmapping as + // we never set the data for mipmaps #else - mapTexture = textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw, false ); // 4J - make sure we aren't mipmapping as we never set the data for mipmaps + mapTexture = + textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw, + false); // 4J - make sure we aren't mipmapping as + // we never set the data for mipmaps #endif - delete img; - for (int i = 0; i < w * h; i++) - { + delete img; + for (int i = 0; i < w * h; i++) { pixels[i] = 0x00000000; - } + } - // 4J added - generate the colour mapping that we'll be needing as a LUT to minimise processing we actually need to do during normal rendering - if( genLUT ) - { - reloadColours(); - } - renderCount = 0; // 4J added - m_optimised = optimised; + // 4J added - generate the colour mapping that we'll be needing as a LUT to + // minimise processing we actually need to do during normal rendering + if (genLUT) { + reloadColours(); + } + renderCount = 0; // 4J added + m_optimised = optimised; } -void Minimap::reloadColours() -{ - ColourTable *colourTable = Minecraft::GetInstance()->getColourTable(); - // 4J note that this code has been extracted pretty much as it was in Minimap::render, although with some byte order changes - for( int i = 0; i < (14 * 4); i++ ) // 14 material colours currently, 4 brightnesses of each - { - if (i / 4 == 0) - { - // 4J - changed byte order to save having to reorder later +void Minimap::reloadColours() { + ColourTable* colourTable = Minecraft::GetInstance()->getColourTable(); + // 4J note that this code has been extracted pretty much as it was in + // Minimap::render, although with some byte order changes + for (int i = 0; i < (14 * 4); + i++) // 14 material colours currently, 4 brightnesses of each + { + if (i / 4 == 0) { + // 4J - changed byte order to save having to reorder later #ifdef __ORBIS__ - LUT[i] = 0; + LUT[i] = 0; #else - LUT[i] = (((i + i / w) & 1) * 8 + 16); + LUT[i] = (((i + i / w) & 1) * 8 + 16); #endif - //pixels[i] = (((i + i / w) & 1) * 8 + 16) << 24; - } - else - { - int color = colourTable->getColor( MaterialColor::colors[i / 4]->col ); - int brightness = i & 3; + // pixels[i] = (((i + i / w) & 1) * 8 + 16) << 24; + } else { + int color = + colourTable->getColor(MaterialColor::colors[i / 4]->col); + int brightness = i & 3; - int br = 220; - if (brightness == 2) br = 255; - if (brightness == 0) br = 180; + int br = 220; + if (brightness == 2) br = 255; + if (brightness == 0) br = 180; - int r = ((color >> 16) & 0xff) * br / 255; - int g = ((color >> 8) & 0xff) * br / 255; - int b = ((color) & 0xff) * br / 255; + int r = ((color >> 16) & 0xff) * br / 255; + int g = ((color >> 8) & 0xff) * br / 255; + int b = ((color) & 0xff) * br / 255; - // 4J - changed byte order to save having to reorder later -#if ( defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__ ) - LUT[i] = 255 << 24 | b << 16 | g << 8 | r; + // 4J - changed byte order to save having to reorder later +#if (defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__) + LUT[i] = 255 << 24 | b << 16 | g << 8 | r; #elif defined _XBOX - LUT[i] = 255 << 24 | r << 16 | g << 8 | b; + LUT[i] = 255 << 24 | r << 16 | g << 8 | b; #elif defined __ORBIS__ - r >>= 3; g >>= 3; b >>= 3; - LUT[i] = 1 << 15 | ( r << 10 ) | ( g << 5 ) | b; + r >>= 3; + g >>= 3; + b >>= 3; + LUT[i] = 1 << 15 | (r << 10) | (g << 5) | b; #else - LUT[i] = r << 24 | g << 16 | b << 8 | 255; + LUT[i] = r << 24 | g << 16 | b << 8 | 255; #endif - //pixels[i] = (255) << 24 | r << 16 | g << 8 | b; - } - - } - genLUT = false; + // pixels[i] = (255) << 24 | r << 16 | g << 8 | b; + } + } + genLUT = false; } // 4J added entityId -void Minimap::render(std::shared_ptr player, Textures *textures, std::shared_ptr data, int entityId) -{ - // 4J - only update every 8 renders, as an optimisation - // We don't want to use this for ItemFrame renders of maps, as then we can't have different maps together - if( !m_optimised || ( renderCount & 7 ) == 0 ) - { - for (int i = 0; i < w * h; i++) - { - int val = data->colors[i]; - // 4J - moved the code that used to run here into a LUT that is generated once in the ctor above - pixels[i] = LUT[val]; - } - } - renderCount++; +void Minimap::render(std::shared_ptr player, Textures* textures, + std::shared_ptr data, int entityId) { + // 4J - only update every 8 renders, as an optimisation + // We don't want to use this for ItemFrame renders of maps, as then we can't + // have different maps together + if (!m_optimised || (renderCount & 7) == 0) { + for (int i = 0; i < w * h; i++) { + int val = data->colors[i]; + // 4J - moved the code that used to run here into a LUT that is + // generated once in the ctor above + pixels[i] = LUT[val]; + } + } + renderCount++; - // 4J - changed - have changed texture generation here to put the bytes in the right order already, so we don't have to do any copying round etc. in the texture replacement itself + // 4J - changed - have changed texture generation here to put the bytes in + // the right order already, so we don't have to do any copying round etc. in + // the texture replacement itself textures->replaceTextureDirect(pixels, w, h, mapTexture); int x = 0; int y = 0; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float vo = 0; glBindTexture(GL_TEXTURE_2D, mapTexture); glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_ALPHA_TEST); t->begin(); - // 4J - moved to -0.02 to stop z fighting ( was -0.01) - // AP - Vita still has issues so push it a bit more - float Offset = -0.02f; + // 4J - moved to -0.02 to stop z fighting ( was -0.01) + // AP - Vita still has issues so push it a bit more + float Offset = -0.02f; #ifdef __PSVITA__ - Offset = -0.03f; + Offset = -0.03f; #endif - t->vertexUV((float)(x + 0 + vo), (float)( y + h - vo), (float)( Offset), (float)( 0), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + h - vo), (float)( Offset), (float)( 1), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + 0 + vo), (float)( Offset), (float)( 1), (float)( 0)); - t->vertexUV((float)(x + 0 + vo), (float)( y + 0 + vo), (float)( Offset), (float)( 0), (float)( 0)); + t->vertexUV((float)(x + 0 + vo), (float)(y + h - vo), (float)(Offset), + (float)(0), (float)(1)); + t->vertexUV((float)(x + w - vo), (float)(y + h - vo), (float)(Offset), + (float)(1), (float)(1)); + t->vertexUV((float)(x + w - vo), (float)(y + 0 + vo), (float)(Offset), + (float)(1), (float)(0)); + t->vertexUV((float)(x + 0 + vo), (float)(y + 0 + vo), (float)(Offset), + (float)(0), (float)(0)); t->end(); glEnable(GL_ALPHA_TEST); glDisable(GL_BLEND); + textures->bind( + textures->loadTexture(TN_MISC_MAPICONS)); // L"/misc/mapicons.png")); - textures->bind(textures->loadTexture(TN_MISC_MAPICONS));//L"/misc/mapicons.png")); - - AUTO_VAR(itEnd, data->decorations.end()); + AUTO_VAR(itEnd, data->decorations.end()); #ifdef _LARGE_WORLDS - std::vector m_edgeIcons; + std::vector m_edgeIcons; #endif - // 4J-PB - stack the map icons - float fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( std::vector::iterator it = data->decorations.begin(); it != itEnd; it++ ) - { - MapItemSavedData::MapDecoration *dec = *it; + // 4J-PB - stack the map icons + float fIconZ = + -0.04f; // 4J - moved to -0.04 (was -0.02) to stop z fighting + for (std::vector::iterator it = + data->decorations.begin(); + it != itEnd; it++) { + MapItemSavedData::MapDecoration* dec = *it; - if(!dec->visible) continue; + if (!dec->visible) continue; - char imgIndex = dec->img; + char imgIndex = dec->img; #ifdef _LARGE_WORLDS - // For edge icons, use a different texture - if(imgIndex >= 16) - { - m_edgeIcons.push_back(dec); - continue; - } + // For edge icons, use a different texture + if (imgIndex >= 16) { + m_edgeIcons.push_back(dec); + continue; + } #endif - // 4J Stu - For item frame renders, the player is NULL. We do not want to show player icons on the frames. - if(player == NULL && (imgIndex != 12)) continue; - else if (player != NULL && imgIndex == 12) continue; - else if( imgIndex == 12 && dec->entityId != entityId) continue; + // 4J Stu - For item frame renders, the player is NULL. We do not want + // to show player icons on the frames. + if (player == NULL && (imgIndex != 12)) + continue; + else if (player != NULL && imgIndex == 12) + continue; + else if (imgIndex == 12 && dec->entityId != entityId) + continue; glPushMatrix(); - glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, fIconZ); + glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, + fIconZ); glRotatef(dec->rot * 360 / 16.0f, 0, 0, 1); glScalef(4, 4, 3); glTranslatef(-1.0f / 8.0f, +1.0f / 8.0f, 0); @@ -186,34 +205,42 @@ void Minimap::render(std::shared_ptr player, Textures *textures, std::sh float v1 = (imgIndex / 4 + 1) / 4.0f; t->begin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV((float)(-1), (float)(+1), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+1), (float)(+1), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+1), (float)(-1), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-1), (float)(-1), (float)(0), (float)(u0), + (float)(v1)); t->end(); glPopMatrix(); - fIconZ-=0.01f; + fIconZ -= 0.01f; } #ifdef _LARGE_WORLDS - // For players on the edge of the world - textures->bind(textures->loadTexture(TN_MISC_ADDITIONALMAPICONS)); + // For players on the edge of the world + textures->bind(textures->loadTexture(TN_MISC_ADDITIONALMAPICONS)); - fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( AUTO_VAR(it,m_edgeIcons.begin()); it != m_edgeIcons.end(); it++ ) - { - MapItemSavedData::MapDecoration *dec = *it; - - char imgIndex = dec->img; - imgIndex -= 16; + fIconZ = -0.04f; // 4J - moved to -0.04 (was -0.02) to stop z fighting + for (AUTO_VAR(it, m_edgeIcons.begin()); it != m_edgeIcons.end(); it++) { + MapItemSavedData::MapDecoration* dec = *it; - // 4J Stu - For item frame renders, the player is NULL. We do not want to show player icons on the frames. - if(player == NULL && (imgIndex != 12)) continue; - else if (player != NULL && imgIndex == 12) continue; - else if( imgIndex == 12 && dec->entityId != entityId) continue; + char imgIndex = dec->img; + imgIndex -= 16; + + // 4J Stu - For item frame renders, the player is NULL. We do not want + // to show player icons on the frames. + if (player == NULL && (imgIndex != 12)) + continue; + else if (player != NULL && imgIndex == 12) + continue; + else if (imgIndex == 12 && dec->entityId != entityId) + continue; glPushMatrix(); - glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, fIconZ); + glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, + fIconZ); glRotatef(dec->rot * 360 / 16.0f, 0, 0, 1); glScalef(4, 4, 3); glTranslatef(-1.0f / 8.0f, +1.0f / 8.0f, 0); @@ -224,39 +251,43 @@ void Minimap::render(std::shared_ptr player, Textures *textures, std::sh float v1 = (imgIndex / 4 + 1) / 4.0f; t->begin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV((float)(-1), (float)(+1), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+1), (float)(+1), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+1), (float)(-1), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-1), (float)(-1), (float)(0), (float)(u0), + (float)(v1)); t->end(); glPopMatrix(); - fIconZ-=0.01f; + fIconZ -= 0.01f; } #endif glPushMatrix(); -// glRotatef(0, 1, 0, 0); + // glRotatef(0, 1, 0, 0); glTranslatef(0, 0, -0.06f); glScalef(1, 1, 1); -// 4J Stu - Don't render the text name, except in debug -//#if 1 -//#ifdef _DEBUG -// font->draw(data->id, x, y, 0xff000000); -//#else - // 4J Stu - TU-1 hotfix - // DCR: Render the players current position here instead - if(player != NULL) - { - wchar_t playerPosText[32]; - ZeroMemory(&playerPosText, sizeof(wchar_t) * 32); - int posx = floor(player->x); - int posy = floor(player->y); - int posz = floor(player->z); - swprintf(playerPosText, 32, L"X: %d, Y: %d, Z: %d", posx, posy, posz); - - font->draw(playerPosText, x, y, Minecraft::GetInstance()->getColourTable()->getColour(eMinecraftColour_Map_Text)); - } -//#endif - glPopMatrix(); + // 4J Stu - Don't render the text name, except in debug + // #if 1 + // #ifdef _DEBUG + // font->draw(data->id, x, y, 0xff000000); + // #else + // 4J Stu - TU-1 hotfix + // DCR: Render the players current position here instead + if (player != NULL) { + wchar_t playerPosText[32]; + ZeroMemory(&playerPosText, sizeof(wchar_t) * 32); + int posx = floor(player->x); + int posy = floor(player->y); + int posz = floor(player->z); + swprintf(playerPosText, 32, L"X: %d, Y: %d, Z: %d", posx, posy, posz); + font->draw(playerPosText, x, y, + Minecraft::GetInstance()->getColourTable()->getColour( + eMinecraftColour_Map_Text)); + } + // #endif + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/Minimap.h b/Minecraft.Client/Rendering/Minimap.h index 2743f03d5..5ff83c5aa 100644 --- a/Minecraft.Client/Rendering/Minimap.h +++ b/Minecraft.Client/Rendering/Minimap.h @@ -6,30 +6,32 @@ class Textures; class Player; class MapItemSavedData; -class Minimap -{ +class Minimap { private: - static const int w = MapItem::IMAGE_WIDTH; + static const int w = MapItem::IMAGE_WIDTH; static const int h = MapItem::IMAGE_HEIGHT; #ifdef __ORBIS__ - static short LUT[256]; // 4J added + static short LUT[256]; // 4J added #else - static int LUT[256]; // 4J added + static int LUT[256]; // 4J added #endif - static bool genLUT; // 4J added - int renderCount; // 4J added - bool m_optimised; // 4J Added + static bool genLUT; // 4J added + int renderCount; // 4J added + bool m_optimised; // 4J Added #ifdef __ORBIS__ - shortArray pixels; + shortArray pixels; #else intArray pixels; #endif int mapTexture; - Options *options; - Font *font; + Options* options; + Font* font; public: - Minimap(Font *font, Options *options, Textures *textures, bool optimised = true); // 4J Added optimised param - static void reloadColours(); - void render(std::shared_ptr player, Textures *textures, std::shared_ptr data, int entityId); // 4J added entityId param + Minimap(Font* font, Options* options, Textures* textures, + bool optimised = true); // 4J Added optimised param + static void reloadColours(); + void render(std::shared_ptr player, Textures* textures, + std::shared_ptr data, + int entityId); // 4J added entityId param }; diff --git a/Minecraft.Client/Rendering/Models/BlazeModel.cpp b/Minecraft.Client/Rendering/Models/BlazeModel.cpp index f1a805957..8fbb67e04 100644 --- a/Minecraft.Client/Rendering/Models/BlazeModel.cpp +++ b/Minecraft.Client/Rendering/Models/BlazeModel.cpp @@ -3,12 +3,10 @@ #include "BlazeModel.h" #include "ModelPart.h" -BlazeModel::BlazeModel() : Model() -{ +BlazeModel::BlazeModel() : Model() { upperBodyParts = ModelPartArray(12); - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { + for (unsigned int i = 0; i < upperBodyParts.length; i++) { upperBodyParts[i] = new ModelPart(this, 0, 16); upperBodyParts[i]->addBox(0, 0, 0, 2, 8, 2); } @@ -16,61 +14,54 @@ BlazeModel::BlazeModel() : Model() head = new ModelPart(this, 0, 0); head->addBox(-4, -4, -4, 8, 8, 8); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { - upperBodyParts[i]->compile(1.0f/16.0f); - } - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + for (unsigned int i = 0; i < upperBodyParts.length; i++) { + upperBodyParts[i]->compile(1.0f / 16.0f); + } + head->compile(1.0f / 16.0f); } -int BlazeModel::modelVersion() -{ - return 8; -} +int BlazeModel::modelVersion() { return 8; } -void BlazeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void BlazeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { + head->render(scale, usecompiled); + for (unsigned int i = 0; i < upperBodyParts.length; i++) { upperBodyParts[i]->render(scale, usecompiled); } } -void BlazeModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - +void BlazeModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { float angle = bob * PI * -.1f; - for (int i = 0; i < 4; i++) - { - upperBodyParts[i]->y = -2 + Mth::cos((i * 2 + bob) * .25f); - upperBodyParts[i]->x = Mth::cos(angle) * 9.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 9.0f; + for (int i = 0; i < 4; i++) { + upperBodyParts[i]->y = -2 + Mth::cos((i * 2 + bob) * .25f); + upperBodyParts[i]->x = Mth::cos(angle) * 9.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 9.0f; angle += PI * 0.5f; } angle = .25f * PI + bob * PI * .03f; - for (int i = 4; i < 8; i++) - { - upperBodyParts[i]->y = 2 + Mth::cos((i * 2 + bob) * .25f); - upperBodyParts[i]->x = Mth::cos(angle) * 7.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 7.0f; + for (int i = 4; i < 8; i++) { + upperBodyParts[i]->y = 2 + Mth::cos((i * 2 + bob) * .25f); + upperBodyParts[i]->x = Mth::cos(angle) * 7.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 7.0f; angle += PI * 0.5f; } angle = .15f * PI + bob * PI * -.05f; - for (int i = 8; i < 12; i++) - { - upperBodyParts[i]->y = 11 + Mth::cos((i * 1.5f + bob) * .5f); - upperBodyParts[i]->x = Mth::cos(angle) * 5.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 5.0f; + for (int i = 8; i < 12; i++) { + upperBodyParts[i]->y = 11 + Mth::cos((i * 1.5f + bob) * .5f); + upperBodyParts[i]->x = Mth::cos(angle) * 5.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 5.0f; angle += PI * 0.5f; } - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); } - diff --git a/Minecraft.Client/Rendering/Models/BlazeModel.h b/Minecraft.Client/Rendering/Models/BlazeModel.h index 9e702ecb4..3abf74199 100644 --- a/Minecraft.Client/Rendering/Models/BlazeModel.h +++ b/Minecraft.Client/Rendering/Models/BlazeModel.h @@ -1,16 +1,18 @@ #pragma once #include "Model.h" -class BlazeModel : public Model -{ - +class BlazeModel : public Model { private: - ModelPartArray upperBodyParts; - ModelPart *head; + ModelPartArray upperBodyParts; + ModelPart* head; public: - BlazeModel(); - int modelVersion(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + BlazeModel(); + int modelVersion(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/BoatModel.cpp b/Minecraft.Client/Rendering/Models/BoatModel.cpp index 90a9752d5..e0b5da365 100644 --- a/Minecraft.Client/Rendering/Models/BoatModel.cpp +++ b/Minecraft.Client/Rendering/Models/BoatModel.cpp @@ -1,51 +1,51 @@ #include "../../Platform/stdafx.h" #include "BoatModel.h" -BoatModel::BoatModel() : Model() -{ - cubes[0] = new ModelPart(this, 0, 8); - cubes[1] = new ModelPart(this, 0, 0); - cubes[2] = new ModelPart(this, 0, 0); - cubes[3] = new ModelPart(this, 0, 0); - cubes[4] = new ModelPart(this, 0, 0); +BoatModel::BoatModel() : Model() { + cubes[0] = new ModelPart(this, 0, 8); + cubes[1] = new ModelPart(this, 0, 0); + cubes[2] = new ModelPart(this, 0, 0); + cubes[3] = new ModelPart(this, 0, 0); + cubes[4] = new ModelPart(this, 0, 0); - int w = 24; - int d = 6; - int h = 20; - int yOff = 4; + int w = 24; + int d = 6; + int h = 20; + int yOff = 4; - cubes[0]->addBox((float)(-w / 2), (float)(-h / 2 + 2), -3, w, h - 4, 4, 0); - cubes[0]->setPos(0, (float)(0 + yOff), 0); - - cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); - - cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); - - cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); - - cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); - - cubes[0]->xRot = PI / 2; - cubes[1]->yRot = PI / 2 * 3; - cubes[2]->yRot = PI / 2 * 1; - cubes[3]->yRot = PI / 2 * 2; + cubes[0]->addBox((float)(-w / 2), (float)(-h / 2 + 2), -3, w, h - 4, 4, 0); + cubes[0]->setPos(0, (float)(0 + yOff), 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - cubes[0]->compile(1.0f/16.0f); - cubes[1]->compile(1.0f/16.0f); - cubes[2]->compile(1.0f/16.0f); - cubes[3]->compile(1.0f/16.0f); - cubes[4]->compile(1.0f/16.0f); + cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); + + cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); + + cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); + + cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); + + cubes[0]->xRot = PI / 2; + cubes[1]->yRot = PI / 2 * 3; + cubes[2]->yRot = PI / 2 * 1; + cubes[3]->yRot = PI / 2 * 2; + + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + cubes[0]->compile(1.0f / 16.0f); + cubes[1]->compile(1.0f / 16.0f); + cubes[2]->compile(1.0f / 16.0f); + cubes[3]->compile(1.0f / 16.0f); + cubes[4]->compile(1.0f / 16.0f); } -void BoatModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - for (int i = 0; i < 5; i++) - { - cubes[i]->render(scale, usecompiled); - } +void BoatModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + for (int i = 0; i < 5; i++) { + cubes[i]->render(scale, usecompiled); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/BoatModel.h b/Minecraft.Client/Rendering/Models/BoatModel.h index 192e140f3..d96fdef06 100644 --- a/Minecraft.Client/Rendering/Models/BoatModel.h +++ b/Minecraft.Client/Rendering/Models/BoatModel.h @@ -2,10 +2,11 @@ #include "Model.h" #include "ModelPart.h" -class BoatModel : public Model -{ +class BoatModel : public Model { public: - ModelPart *cubes[5]; + ModelPart* cubes[5]; BoatModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/BookModel.cpp b/Minecraft.Client/Rendering/Models/BookModel.cpp index 04237d2be..b5b522eef 100644 --- a/Minecraft.Client/Rendering/Models/BookModel.cpp +++ b/Minecraft.Client/Rendering/Models/BookModel.cpp @@ -3,66 +3,77 @@ #include "BookModel.h" #include "ModelPart.h" -BookModel::BookModel() -{ - leftLid = (new ModelPart(this))->texOffs(0, 0)->addBox(-6, -5, 0, 6, 10, 0); - rightLid = (new ModelPart(this))->texOffs(16, 0)->addBox(0, -5, 0, 6, 10, 0); +BookModel::BookModel() { + leftLid = (new ModelPart(this))->texOffs(0, 0)->addBox(-6, -5, 0, 6, 10, 0); + rightLid = + (new ModelPart(this))->texOffs(16, 0)->addBox(0, -5, 0, 6, 10, 0); - seam = (new ModelPart(this))->texOffs(12, 0)->addBox(-1, -5, 0, 2, 10, 0); + seam = (new ModelPart(this))->texOffs(12, 0)->addBox(-1, -5, 0, 2, 10, 0); - // 4J - added faceMasks here to remove sides of these page boxes which end up being nearly coplanar to the cover of the book and flickering when rendering at a distance - leftPages = (new ModelPart(this))->texOffs(0, 10)->addBoxWithMask(0, -4, -1 + 0.01f, 5, 8, 1, 47); // 4J - faceMask is binary 101111 - rightPages = (new ModelPart(this))->texOffs(12, 10)->addBoxWithMask(0, -4, -0.01f, 5, 8, 1, 31); // 4J - faceMask is binary 011111 + // 4J - added faceMasks here to remove sides of these page boxes which end + // up being nearly coplanar to the cover of the book and flickering when + // rendering at a distance + leftPages = (new ModelPart(this)) + ->texOffs(0, 10) + ->addBoxWithMask(0, -4, -1 + 0.01f, 5, 8, 1, + 47); // 4J - faceMask is binary 101111 + rightPages = (new ModelPart(this)) + ->texOffs(12, 10) + ->addBoxWithMask(0, -4, -0.01f, 5, 8, 1, + 31); // 4J - faceMask is binary 011111 - flipPage1 = (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); - flipPage2 = (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); + flipPage1 = + (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); + flipPage2 = + (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); - leftLid->setPos(0, 0, -1); - rightLid->setPos(0, 0, 1); + leftLid->setPos(0, 0, -1); + rightLid->setPos(0, 0, 1); - seam->yRot = PI / 2; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - leftLid->compile(1.0f/16.0f); - rightLid->compile(1.0f/16.0f); - seam->compile(1.0f/16.0f); - leftPages->compile(1.0f/16.0f); - rightPages->compile(1.0f/16.0f); - flipPage1->compile(1.0f/16.0f); - flipPage2->compile(1.0f/16.0f); + seam->yRot = PI / 2; + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + leftLid->compile(1.0f / 16.0f); + rightLid->compile(1.0f / 16.0f); + seam->compile(1.0f / 16.0f); + leftPages->compile(1.0f / 16.0f); + rightPages->compile(1.0f / 16.0f); + flipPage1->compile(1.0f / 16.0f); + flipPage2->compile(1.0f / 16.0f); } -void BookModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void BookModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - leftLid->render(scale,usecompiled); - rightLid->render(scale,usecompiled); - seam->render(scale,usecompiled); + leftLid->render(scale, usecompiled); + rightLid->render(scale, usecompiled); + seam->render(scale, usecompiled); - leftPages->render(scale,usecompiled); - rightPages->render(scale,usecompiled); + leftPages->render(scale, usecompiled); + rightPages->render(scale, usecompiled); - flipPage1->render(scale,usecompiled); - flipPage2->render(scale,usecompiled); + flipPage1->render(scale, usecompiled); + flipPage2->render(scale, usecompiled); } -void BookModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - float openness = (Mth::sin(time * 0.02f) * 0.10f + 1.25f) * yRot; +void BookModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + float openness = (Mth::sin(time * 0.02f) * 0.10f + 1.25f) * yRot; - leftLid->yRot = PI + openness; - rightLid->yRot = -openness; - leftPages->yRot = +openness; - rightPages->yRot = -openness; + leftLid->yRot = PI + openness; + rightLid->yRot = -openness; + leftPages->yRot = +openness; + rightPages->yRot = -openness; - flipPage1->yRot = +openness - openness * 2 * r; - flipPage2->yRot = +openness - openness * 2 * bob; + flipPage1->yRot = +openness - openness * 2 * r; + flipPage2->yRot = +openness - openness * 2 * bob; - leftPages->x = Mth::sin(openness); - rightPages->x = Mth::sin(openness); - flipPage1->x = Mth::sin(openness); - flipPage2->x = Mth::sin(openness); + leftPages->x = Mth::sin(openness); + rightPages->x = Mth::sin(openness); + flipPage1->x = Mth::sin(openness); + flipPage2->x = Mth::sin(openness); } - diff --git a/Minecraft.Client/Rendering/Models/BookModel.h b/Minecraft.Client/Rendering/Models/BookModel.h index 411d2df55..152c9fec8 100644 --- a/Minecraft.Client/Rendering/Models/BookModel.h +++ b/Minecraft.Client/Rendering/Models/BookModel.h @@ -2,15 +2,18 @@ #pragma once #include "Model.h" -class BookModel : public Model -{ +class BookModel : public Model { public: - ModelPart *leftLid, *rightLid; - ModelPart *leftPages, *rightPages; - ModelPart *flipPage1, *flipPage2; - ModelPart *seam; + ModelPart *leftLid, *rightLid; + ModelPart *leftPages, *rightPages; + ModelPart *flipPage1, *flipPage2; + ModelPart* seam; - BookModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + BookModel(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/ChestModel.cpp b/Minecraft.Client/Rendering/Models/ChestModel.cpp index 51e5cf0bc..918c44620 100644 --- a/Minecraft.Client/Rendering/Models/ChestModel.cpp +++ b/Minecraft.Client/Rendering/Models/ChestModel.cpp @@ -2,42 +2,42 @@ #include "ChestModel.h" #include "ModelPart.h" -ChestModel::ChestModel() -{ - lid = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); - lid->addBox(0.0f, -5.0f, -14.0f, 14, 5, 14, 0.0f); - lid->x = 1; - lid->y = 7; - lid->z = 15; +ChestModel::ChestModel() { + lid = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); + lid->addBox(0.0f, -5.0f, -14.0f, 14, 5, 14, 0.0f); + lid->x = 1; + lid->y = 7; + lid->z = 15; - lock = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); - lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); - lock->x = 8; - lock->y = 7; - lock->z = 15; + lock = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); + lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); + lock->x = 8; + lock->y = 7; + lock->z = 15; - bottom = ((new ModelPart(this, 0, 19)))->setTexSize(64, 64); - bottom->addBox(0.0f, 0.0f, 0.0f, 14, 10, 14, 0.0f); - bottom->x = 1; - bottom->y = 6; - bottom->z = 1; + bottom = ((new ModelPart(this, 0, 19)))->setTexSize(64, 64); + bottom->addBox(0.0f, 0.0f, 0.0f, 14, 10, 14, 0.0f); + bottom->x = 1; + bottom->y = 6; + bottom->z = 1; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - lid->compile(1.0f/16.0f); - lock->compile(1.0f/16.0f); - bottom->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + lid->compile(1.0f / 16.0f); + lock->compile(1.0f / 16.0f); + bottom->compile(1.0f / 16.0f); } -void ChestModel::render(bool usecompiled) -{ - lock->xRot = lid->xRot; +void ChestModel::render(bool usecompiled) { + lock->xRot = lid->xRot; - lock->render(1 / 16.0f, usecompiled); - bottom->render(1 / 16.0f, usecompiled); + lock->render(1 / 16.0f, usecompiled); + bottom->render(1 / 16.0f, usecompiled); - // 4J - moved lid to last and added z-bias to avoid glitching caused by z-fighting between the area of overlap between the lid & bottom of the chest - glPolygonOffset(-0.3f, -0.3f); - lid->render(1 / 16.0f, usecompiled); - glPolygonOffset(0.0f, 0.0f); + // 4J - moved lid to last and added z-bias to avoid glitching caused by + // z-fighting between the area of overlap between the lid & bottom of the + // chest + glPolygonOffset(-0.3f, -0.3f); + lid->render(1 / 16.0f, usecompiled); + glPolygonOffset(0.0f, 0.0f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ChestModel.h b/Minecraft.Client/Rendering/Models/ChestModel.h index 416ccf753..3b3cfd8b2 100644 --- a/Minecraft.Client/Rendering/Models/ChestModel.h +++ b/Minecraft.Client/Rendering/Models/ChestModel.h @@ -4,15 +4,14 @@ class Cube; -class ChestModel : public Model -{ +class ChestModel : public Model { public: - using Model::render; + using Model::render; - ModelPart *lid; - ModelPart *bottom; - ModelPart *lock; + ModelPart* lid; + ModelPart* bottom; + ModelPart* lock; - ChestModel(); - void render(bool usecompiled); + ChestModel(); + void render(bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/ChickenModel.cpp b/Minecraft.Client/Rendering/Models/ChickenModel.cpp index 642954c9f..b75d80319 100644 --- a/Minecraft.Client/Rendering/Models/ChickenModel.cpp +++ b/Minecraft.Client/Rendering/Models/ChickenModel.cpp @@ -3,102 +3,101 @@ #include "ChickenModel.h" #include "ModelPart.h" -ChickenModel::ChickenModel() : Model() -{ +ChickenModel::ChickenModel() : Model() { int yo = 16; head = new ModelPart(this, 0, 0); - head->addBox(-2.0f, -6.0f, -2.0f, 4, 6, 3, 0.0f); // Head + head->addBox(-2.0f, -6.0f, -2.0f, 4, 6, 3, 0.0f); // Head head->setPos(0, (float)(-1 + yo), -4); beak = new ModelPart(this, 14, 0); - beak->addBox(-2.0f, -4.0f, -4.0f, 4, 2, 2, 0.0f); // Beak + beak->addBox(-2.0f, -4.0f, -4.0f, 4, 2, 2, 0.0f); // Beak beak->setPos(0, (float)(-1 + yo), -4); redThing = new ModelPart(this, 14, 4); - redThing->addBox(-1.0f, -2.0f, -3.0f, 2, 2, 2, 0.0f); // Beak + redThing->addBox(-1.0f, -2.0f, -3.0f, 2, 2, 2, 0.0f); // Beak redThing->setPos(0, (float)(-1 + yo), -4); body = new ModelPart(this, 0, 9); - body->addBox(-3.0f, -4.0f, -3.0f, 6, 8, 6, 0.0f); // Body + body->addBox(-3.0f, -4.0f, -3.0f, 6, 8, 6, 0.0f); // Body body->setPos(0, (float)(0 + yo), 0); leg0 = new ModelPart(this, 26, 0); - leg0->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg0 + leg0->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg0 leg0->setPos(-2, (float)(3 + yo), 1); leg1 = new ModelPart(this, 26, 0); - leg1->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg1 + leg1->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg1 leg1->setPos(1, (float)(3 + yo), 1); wing0 = new ModelPart(this, 24, 13); - wing0->addBox(0.0f, 0.0f, -3.0f, 1, 4, 6); // Wing0 + wing0->addBox(0.0f, 0.0f, -3.0f, 1, 4, 6); // Wing0 wing0->setPos(-4, (float)(-3 + yo), 0); wing1 = new ModelPart(this, 24, 13); - wing1->addBox(-1.0f, 0.0f, -3.0f, 1, 4, 6); // Wing1 + wing1->addBox(-1.0f, 0.0f, -3.0f, 1, 4, 6); // Wing1 wing1->setPos(4, (float)(-3 + yo), 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - beak->compile(1.0f/16.0f); - redThing->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - wing0->compile(1.0f/16.0f); - wing1->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + beak->compile(1.0f / 16.0f); + redThing->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + wing0->compile(1.0f / 16.0f); + wing1->compile(1.0f / 16.0f); } -void ChickenModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void ChickenModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2; - glPushMatrix(); - glTranslatef(0, 5 * scale, 2 * scale); - head->render(scale,usecompiled); - beak->render(scale,usecompiled); - redThing->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - wing0->render(scale,usecompiled); - wing1->render(scale,usecompiled); - glPopMatrix(); - } - else - { - head->render(scale,usecompiled); - beak->render(scale,usecompiled); - redThing->render(scale,usecompiled); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - wing0->render(scale,usecompiled); - wing1->render(scale,usecompiled); - } + if (young) { + float ss = 2; + glPushMatrix(); + glTranslatef(0, 5 * scale, 2 * scale); + head->render(scale, usecompiled); + beak->render(scale, usecompiled); + redThing->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + wing0->render(scale, usecompiled); + wing1->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + beak->render(scale, usecompiled); + redThing->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + wing0->render(scale, usecompiled); + wing1->render(scale, usecompiled); + } } -void ChickenModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); - - beak->xRot = head->xRot; - beak->yRot = head->yRot; - - redThing->xRot = head->xRot; - redThing->yRot = head->yRot; - - body->xRot = 90 / (float) (180 / PI); +void ChickenModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); - leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f + PI) * 1.4f) * r; - wing0->zRot = bob; - wing1->zRot = -bob; + beak->xRot = head->xRot; + beak->yRot = head->yRot; + + redThing->xRot = head->xRot; + redThing->yRot = head->yRot; + + body->xRot = 90 / (float)(180 / PI); + + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; + wing0->zRot = bob; + wing1->zRot = -bob; } diff --git a/Minecraft.Client/Rendering/Models/ChickenModel.h b/Minecraft.Client/Rendering/Models/ChickenModel.h index 7ef7e99b4..5b21368e6 100644 --- a/Minecraft.Client/Rendering/Models/ChickenModel.h +++ b/Minecraft.Client/Rendering/Models/ChickenModel.h @@ -1,12 +1,16 @@ #pragma once #include "Model.h" -class ChickenModel : public Model -{ +class ChickenModel : public Model { public: - ModelPart *head, *hair, *body, *leg0, *leg1, *wing0,* wing1, *beak, *redThing; + ModelPart *head, *hair, *body, *leg0, *leg1, *wing0, *wing1, *beak, + *redThing; ChickenModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/CowModel.cpp b/Minecraft.Client/Rendering/Models/CowModel.cpp index 698cbfc6a..78efcd2a6 100644 --- a/Minecraft.Client/Rendering/Models/CowModel.cpp +++ b/Minecraft.Client/Rendering/Models/CowModel.cpp @@ -2,18 +2,17 @@ #include "CowModel.h" #include "ModelPart.h" -CowModel::CowModel() : QuadrupedModel(12,0) -{ +CowModel::CowModel() : QuadrupedModel(12, 0) { head = new ModelPart(this, 0, 0); - head->addBox(-4, -4, -6, 8, 8, 6, 0); // Head + head->addBox(-4, -4, -6, 8, 8, 6, 0); // Head head->setPos(0, 12 - 6 - 2, -8); - head->texOffs(22, 0)->addBox(-5, -5, -4, 1, 3, 1, 0); // Horn1 - head->texOffs(22, 0)->addBox(+4, -5, -4, 1, 3, 1, 0); // Horn1 + head->texOffs(22, 0)->addBox(-5, -5, -4, 1, 3, 1, 0); // Horn1 + head->texOffs(22, 0)->addBox(+4, -5, -4, 1, 3, 1, 0); // Horn1 body = new ModelPart(this, 18, 4); - body->addBox(-6, -10, -7, 12, 18, 10, 0); // Body + body->addBox(-6, -10, -7, 12, 18, 10, 0); // Body body->setPos(0, 11 + 6 - 12, 2); - body->texOffs(52, 0)->addBox(-2, 2, -8, 4, 6, 1); + body->texOffs(52, 0)->addBox(-2, 2, -8, 4, 6, 1); leg0->x -= 1; leg1->x += 1; @@ -24,9 +23,10 @@ CowModel::CowModel() : QuadrupedModel(12,0) leg2->z -= 1; leg3->z -= 1; - this->zHeadOffs += 2; + this->zHeadOffs += 2; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); } diff --git a/Minecraft.Client/Rendering/Models/CowModel.h b/Minecraft.Client/Rendering/Models/CowModel.h index dcd7671c6..125da558c 100644 --- a/Minecraft.Client/Rendering/Models/CowModel.h +++ b/Minecraft.Client/Rendering/Models/CowModel.h @@ -1,10 +1,11 @@ #pragma once #include "QuadrupedModel.h" -class CowModel : public QuadrupedModel -{ +class CowModel : public QuadrupedModel { public: CowModel(); -// virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); -// virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); + // virtual void render(std::shared_ptr entity, float time, float + // r, float bob, float yRot, float xRot, float scale, bool usecompiled); + // virtual void setupAnim(float time, float r, float bob, float yRot, + // float xRot, float scale); }; diff --git a/Minecraft.Client/Rendering/Models/CreeperModel.cpp b/Minecraft.Client/Rendering/Models/CreeperModel.cpp index 8a2d2e498..a92685595 100644 --- a/Minecraft.Client/Rendering/Models/CreeperModel.cpp +++ b/Minecraft.Client/Rendering/Models/CreeperModel.cpp @@ -4,60 +4,55 @@ #include "ModelPart.h" // 4J - added -void CreeperModel::_init(float g) -{ +void CreeperModel::_init(float g) { int yo = 4; head = new ModelPart(this, 0, 0); - head->addBox(-4, - 8, -4, 8, 8, 8, g); // Head + head->addBox(-4, -8, -4, 8, 8, 8, g); // Head head->setPos(0, (float)(yo), 0); hair = new ModelPart(this, 32, 0); - hair->addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head + hair->addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head hair->setPos(0, (float)(yo), 0); body = new ModelPart(this, 16, 16); - body->addBox(-4, 0, -2, 8, 12, 4, g); // Body + body->addBox(-4, 0, -2, 8, 12, 4, g); // Body body->setPos(0, (float)(yo), 0); leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 + leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 leg0->setPos(-2, (float)(12 + yo), 4); leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 + leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 leg1->setPos(2, (float)(12 + yo), 4); leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 + leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 leg2->setPos(-2, (float)(12 + yo), -4); leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 + leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 leg3->setPos(2, (float)(12 + yo), -4); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -CreeperModel::CreeperModel() : Model() -{ - _init(0); -} +CreeperModel::CreeperModel() : Model() { _init(0); } -CreeperModel::CreeperModel(float g) : Model() -{ - _init(g); -} +CreeperModel::CreeperModel(float g) : Model() { _init(g); } -void CreeperModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void CreeperModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); head->render(scale, usecompiled); @@ -68,10 +63,11 @@ void CreeperModel::render(std::shared_ptr entity, float time, float r, f leg3->render(scale, usecompiled); } -void CreeperModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void CreeperModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; diff --git a/Minecraft.Client/Rendering/Models/CreeperModel.h b/Minecraft.Client/Rendering/Models/CreeperModel.h index 0c4e9448e..cb5843522 100644 --- a/Minecraft.Client/Rendering/Models/CreeperModel.h +++ b/Minecraft.Client/Rendering/Models/CreeperModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class CreeperModel : public Model -{ +class CreeperModel : public Model { public: - ModelPart *head, *hair, *body, *leg0, *leg1, *leg2, *leg3; + ModelPart *head, *hair, *body, *leg0, *leg1, *leg2, *leg3; - void _init(float g); // 4J added + void _init(float g); // 4J added CreeperModel(); CreeperModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/DragonModel.cpp b/Minecraft.Client/Rendering/Models/DragonModel.cpp index 9f85bed2e..59ec47a5d 100644 --- a/Minecraft.Client/Rendering/Models/DragonModel.cpp +++ b/Minecraft.Client/Rendering/Models/DragonModel.cpp @@ -3,246 +3,248 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Entities/Mobs/EnderDragon.h" -DragonModel::DragonModel(float g) : Model() -{ - // 4J-PB - texWidth = 256; - texHeight = 256; +DragonModel::DragonModel(float g) : Model() { + // 4J-PB + texWidth = 256; + texHeight = 256; - setMapTex(L"body.body", 0, 0); - setMapTex(L"wing.skin", -56, 88); - setMapTex(L"wingtip.skin", -56, 144); - setMapTex(L"rearleg.main", 0, 0); - setMapTex(L"rearfoot.main", 112, 0); - setMapTex(L"rearlegtip.main", 196, 0); - setMapTex(L"head.upperhead", 112, 30); - setMapTex(L"wing.bone", 112, 88); - setMapTex(L"head.upperlip", 176, 44); - setMapTex(L"jaw.jaw", 176, 65); - setMapTex(L"frontleg.main", 112, 104); - setMapTex(L"wingtip.bone", 112, 136); - setMapTex(L"frontfoot.main", 144, 104); - setMapTex(L"neck.box", 192, 104); - setMapTex(L"frontlegtip.main", 226, 138); - setMapTex(L"body.scale", 220, 53); - setMapTex(L"head.scale", 0, 0); - setMapTex(L"neck.scale", 48, 0); - setMapTex(L"head.nostril", 112, 0); + setMapTex(L"body.body", 0, 0); + setMapTex(L"wing.skin", -56, 88); + setMapTex(L"wingtip.skin", -56, 144); + setMapTex(L"rearleg.main", 0, 0); + setMapTex(L"rearfoot.main", 112, 0); + setMapTex(L"rearlegtip.main", 196, 0); + setMapTex(L"head.upperhead", 112, 30); + setMapTex(L"wing.bone", 112, 88); + setMapTex(L"head.upperlip", 176, 44); + setMapTex(L"jaw.jaw", 176, 65); + setMapTex(L"frontleg.main", 112, 104); + setMapTex(L"wingtip.bone", 112, 136); + setMapTex(L"frontfoot.main", 144, 104); + setMapTex(L"neck.box", 192, 104); + setMapTex(L"frontlegtip.main", 226, 138); + setMapTex(L"body.scale", 220, 53); + setMapTex(L"head.scale", 0, 0); + setMapTex(L"neck.scale", 48, 0); + setMapTex(L"head.nostril", 112, 0); - float zo = -16; - head = new ModelPart(this, L"head"); - head->addBox(L"upperlip", -6, -1, -8 + zo, 12, 5, 16); - head->addBox(L"upperhead", -8, -8, 6 + zo, 16, 16, 16); - head->bMirror = true; - head->addBox(L"scale", -1 - 4, -12, 12 + zo, 2, 4, 6); - head->addBox(L"nostril", -1 - 4, -3, -6 + zo, 2, 2, 4); - head->bMirror = false; - head->addBox(L"scale", -1 + 4, -12, 12 + zo, 2, 4, 6); - head->addBox(L"nostril", -1 + 4, -3, -6 + zo, 2, 2, 4); + float zo = -16; + head = new ModelPart(this, L"head"); + head->addBox(L"upperlip", -6, -1, -8 + zo, 12, 5, 16); + head->addBox(L"upperhead", -8, -8, 6 + zo, 16, 16, 16); + head->bMirror = true; + head->addBox(L"scale", -1 - 4, -12, 12 + zo, 2, 4, 6); + head->addBox(L"nostril", -1 - 4, -3, -6 + zo, 2, 2, 4); + head->bMirror = false; + head->addBox(L"scale", -1 + 4, -12, 12 + zo, 2, 4, 6); + head->addBox(L"nostril", -1 + 4, -3, -6 + zo, 2, 2, 4); - jaw = new ModelPart(this, L"jaw"); - jaw->setPos(0, 4, 8 + zo); - jaw->addBox(L"jaw", -6, 0, -16, 12, 4, 16); - head->addChild(jaw); + jaw = new ModelPart(this, L"jaw"); + jaw->setPos(0, 4, 8 + zo); + jaw->addBox(L"jaw", -6, 0, -16, 12, 4, 16); + head->addChild(jaw); - neck = new ModelPart(this, L"neck"); - neck->addBox(L"box", -5, -5, -5, 10, 10, 10); - neck->addBox(L"scale", -1, -9, -5 + 2, 2, 4, 6); + neck = new ModelPart(this, L"neck"); + neck->addBox(L"box", -5, -5, -5, 10, 10, 10); + neck->addBox(L"scale", -1, -9, -5 + 2, 2, 4, 6); - body = new ModelPart(this, L"body"); - body->setPos(0, 4, 8); - body->addBox(L"body", -12, 0, -16, 24, 24, 64); - body->addBox(L"scale", -1, -6, -10 + 20 * 0, 2, 6, 12); - body->addBox(L"scale", -1, -6, -10 + 20 * 1, 2, 6, 12); - body->addBox(L"scale", -1, -6, -10 + 20 * 2, 2, 6, 12); + body = new ModelPart(this, L"body"); + body->setPos(0, 4, 8); + body->addBox(L"body", -12, 0, -16, 24, 24, 64); + body->addBox(L"scale", -1, -6, -10 + 20 * 0, 2, 6, 12); + body->addBox(L"scale", -1, -6, -10 + 20 * 1, 2, 6, 12); + body->addBox(L"scale", -1, -6, -10 + 20 * 2, 2, 6, 12); - wing = new ModelPart(this, L"wing"); - wing->setPos(-12, 5, 2); - wing->addBox(L"bone", -56, -4, -4, 56, 8, 8); - wing->addBox(L"skin", -56, 0, +2, 56, 0, 56); - wingTip = new ModelPart(this, L"wingtip"); - wingTip->setPos(-56, 0, 0); - wingTip->addBox(L"bone", -56, -2, -2, 56, 4, 4); - wingTip->addBox(L"skin", -56, 0, +2, 56, 0, 56); - wing->addChild(wingTip); + wing = new ModelPart(this, L"wing"); + wing->setPos(-12, 5, 2); + wing->addBox(L"bone", -56, -4, -4, 56, 8, 8); + wing->addBox(L"skin", -56, 0, +2, 56, 0, 56); + wingTip = new ModelPart(this, L"wingtip"); + wingTip->setPos(-56, 0, 0); + wingTip->addBox(L"bone", -56, -2, -2, 56, 4, 4); + wingTip->addBox(L"skin", -56, 0, +2, 56, 0, 56); + wing->addChild(wingTip); - frontLeg = new ModelPart(this, L"frontleg"); - frontLeg->setPos(-12, 20, 2); - frontLeg->addBox(L"main", -4, -4, -4, 8, 24, 8); - frontLegTip = new ModelPart(this, L"frontlegtip"); - frontLegTip->setPos(0, 20, -1); - frontLegTip->addBox(L"main", -3, -1, -3, 6, 24, 6); - frontLeg->addChild(frontLegTip); - frontFoot = new ModelPart(this, L"frontfoot"); - frontFoot->setPos(0, 23, 0); - frontFoot->addBox(L"main", -4, 0, -12, 8, 4, 16); - frontLegTip->addChild(frontFoot); + frontLeg = new ModelPart(this, L"frontleg"); + frontLeg->setPos(-12, 20, 2); + frontLeg->addBox(L"main", -4, -4, -4, 8, 24, 8); + frontLegTip = new ModelPart(this, L"frontlegtip"); + frontLegTip->setPos(0, 20, -1); + frontLegTip->addBox(L"main", -3, -1, -3, 6, 24, 6); + frontLeg->addChild(frontLegTip); + frontFoot = new ModelPart(this, L"frontfoot"); + frontFoot->setPos(0, 23, 0); + frontFoot->addBox(L"main", -4, 0, -12, 8, 4, 16); + frontLegTip->addChild(frontFoot); - rearLeg = new ModelPart(this, L"rearleg"); - rearLeg->setPos(-12 - 4, 16, 2 + 40); - rearLeg->addBox(L"main", -8, -4, -8, 16, 32, 16); - rearLegTip = new ModelPart(this, L"rearlegtip"); - rearLegTip->setPos(0, 32, -4); - rearLegTip->addBox(L"main", -6, -2, 0, 12, 32, 12); - rearLeg->addChild(rearLegTip); - rearFoot = new ModelPart(this, L"rearfoot"); - rearFoot->setPos(0, 31, 4); - rearFoot->addBox(L"main", -9, 0, -20, 18, 6, 24); - rearLegTip->addChild(rearFoot); + rearLeg = new ModelPart(this, L"rearleg"); + rearLeg->setPos(-12 - 4, 16, 2 + 40); + rearLeg->addBox(L"main", -8, -4, -8, 16, 32, 16); + rearLegTip = new ModelPart(this, L"rearlegtip"); + rearLegTip->setPos(0, 32, -4); + rearLegTip->addBox(L"main", -6, -2, 0, 12, 32, 12); + rearLeg->addChild(rearLegTip); + rearFoot = new ModelPart(this, L"rearfoot"); + rearFoot->setPos(0, 31, 4); + rearFoot->addBox(L"main", -9, 0, -20, 18, 6, 24); + rearLegTip->addChild(rearFoot); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - head->compile(1.0f/16.0f); - jaw->compile(1.0f/16.0f); - neck->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - wing->compile(1.0f/16.0f); - wingTip->compile(1.0f/16.0f); - frontLeg->compile(1.0f/16.0f); - frontLegTip->compile(1.0f/16.0f); - frontFoot->compile(1.0f/16.0f); - rearLeg->compile(1.0f/16.0f); - rearLegTip->compile(1.0f/16.0f); - rearFoot->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + head->compile(1.0f / 16.0f); + jaw->compile(1.0f / 16.0f); + neck->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + wing->compile(1.0f / 16.0f); + wingTip->compile(1.0f / 16.0f); + frontLeg->compile(1.0f / 16.0f); + frontLegTip->compile(1.0f / 16.0f); + frontFoot->compile(1.0f / 16.0f); + rearLeg->compile(1.0f / 16.0f); + rearLegTip->compile(1.0f / 16.0f); + rearFoot->compile(1.0f / 16.0f); } -void DragonModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - this->a = a; +void DragonModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + this->a = a; } -void DragonModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - glPushMatrix(); - std::shared_ptr dragon = std::dynamic_pointer_cast(entity); +void DragonModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + glPushMatrix(); + std::shared_ptr dragon = + std::dynamic_pointer_cast(entity); - float ttt = dragon->oFlapTime + (dragon->flapTime - dragon->oFlapTime) * a; - jaw->xRot = (float) (Mth::sin(ttt * PI * 2) + 1) * 0.2f; + float ttt = dragon->oFlapTime + (dragon->flapTime - dragon->oFlapTime) * a; + jaw->xRot = (float)(Mth::sin(ttt * PI * 2) + 1) * 0.2f; - float yo = (float) (Mth::sin(ttt * PI * 2 - 1) + 1); - yo = (yo * yo * 1 + yo * 2) * 0.05f; + float yo = (float)(Mth::sin(ttt * PI * 2 - 1) + 1); + yo = (yo * yo * 1 + yo * 2) * 0.05f; - glTranslatef(0, yo - 2.0f, -3); - glRotatef(yo * 2, 1, 0, 0); + glTranslatef(0, yo - 2.0f, -3); + glRotatef(yo * 2, 1, 0, 0); - float yy = -30.0f; - float zz = 22.0f; - float xx = 0.0f; + float yy = -30.0f; + float zz = 22.0f; + float xx = 0.0f; - float rotScale = 1.5f; + float rotScale = 1.5f; + double startComponents[3]; + doubleArray start = doubleArray(startComponents, 3); + dragon->getLatencyPos(start, 6, a); - double startComponents[3]; - doubleArray start = doubleArray(startComponents,3); - dragon->getLatencyPos(start, 6, a); + double latencyPosAComponents[3], latencyPosBComponents[3]; + doubleArray latencyPosA = doubleArray(latencyPosAComponents, 3); + doubleArray latencyPosB = doubleArray(latencyPosBComponents, 3); + dragon->getLatencyPos(latencyPosA, 5, a); + dragon->getLatencyPos(latencyPosB, 10, a); + float rot2 = rotWrap(latencyPosA[0] - latencyPosB[0]); + float rot = rotWrap(latencyPosA[0] + rot2 / 2); - double latencyPosAComponents[3], latencyPosBComponents[3]; - doubleArray latencyPosA = doubleArray( latencyPosAComponents, 3 ); - doubleArray latencyPosB = doubleArray( latencyPosBComponents, 3 ); - dragon->getLatencyPos(latencyPosA, 5, a); - dragon->getLatencyPos(latencyPosB, 10, a); - float rot2 = rotWrap(latencyPosA[0] - latencyPosB[0]); - float rot = rotWrap(latencyPosA[0] + rot2 / 2); + yy += 2.0f; - yy += 2.0f; + float rr = 0; + float roff = ttt * PI * 2.0f; + yy = 20.0f; + zz = -12.0f; + double pComponents[3]; + doubleArray p = doubleArray(pComponents, 3); - float rr = 0; - float roff = ttt * PI * 2.0f; - yy = 20.0f; - zz = -12.0f; - double pComponents[3]; - doubleArray p = doubleArray(pComponents,3); + for (int i = 0; i < 5; i++) { + dragon->getLatencyPos(p, 5 - i, a); - for (int i = 0; i < 5; i++) - { - dragon->getLatencyPos(p, 5 - i, a); + rr = (float)Mth::cos(i * 0.45f + roff) * 0.15f; + neck->yRot = rotWrap(dragon->getHeadPartYRotDiff(i, start, p)) * PI / + 180.0f * rotScale; // 4J replaced "p[0] - start[0] with + // call to getHeadPartYRotDiff + neck->xRot = rr + (float)(dragon->getHeadPartYOffset(i, start, p)) * + PI / 180.0f * rotScale * + 5.0f; // 4J replaced "p[1] - start[1]" with call + // to getHeadPartYOffset + neck->zRot = -rotWrap(p[0] - rot) * PI / 180.0f * rotScale; - rr = (float) Mth::cos(i * 0.45f + roff) * 0.15f; - neck->yRot = rotWrap(dragon->getHeadPartYRotDiff(i, start, p)) * PI / 180.0f * rotScale; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - neck->xRot = rr + (float) (dragon->getHeadPartYOffset(i, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J replaced "p[1] - start[1]" with call to getHeadPartYOffset - neck->zRot = -rotWrap(p[0] - rot) * PI / 180.0f * rotScale; + neck->y = yy; + neck->z = zz; + neck->x = xx; + yy += Mth::sin(neck->xRot) * 10.0f; + zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; + xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; + neck->render(scale, usecompiled); + } - neck->y = yy; - neck->z = zz; - neck->x = xx; - yy += Mth::sin(neck->xRot) * 10.0f; - zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; - xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; - neck->render(scale,usecompiled); - } + head->y = yy; + head->z = zz; + head->x = xx; + dragon->getLatencyPos(p, 0, a); + head->yRot = + rotWrap(dragon->getHeadPartYRotDiff(6, start, p)) * PI / 180.0f * + 1; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff + head->xRot = (float)(dragon->getHeadPartYOffset(6, start, p)) * PI / + 180.0f * rotScale * 5.0f; // 4J Added + head->zRot = -rotWrap(p[0] - rot) * PI / 180 * 1; + head->render(scale, usecompiled); + glPushMatrix(); + glTranslatef(0, 1, 0); + glRotatef(-(float)(rot2)*rotScale * 1, 0, 0, 1); + glTranslatef(0, -1, 0); + body->zRot = 0; + body->render(scale, usecompiled); - head->y = yy; - head->z = zz; - head->x = xx; - dragon->getLatencyPos(p, 0, a); - head->yRot = rotWrap(dragon->getHeadPartYRotDiff(6, start, p)) * PI / 180.0f * 1; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - head->xRot = (float) (dragon->getHeadPartYOffset(6, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J Added - head->zRot = -rotWrap(p[0] - rot) * PI / 180 * 1; - head->render(scale,usecompiled); - glPushMatrix(); - glTranslatef(0, 1, 0); - glRotatef(-(float) (rot2) * rotScale * 1, 0, 0, 1); - glTranslatef(0, -1, 0); - body->zRot = 0; - body->render(scale,usecompiled); - - glEnable(GL_CULL_FACE); - for (int i = 0; i < 2; i++) - { - float flapTime = ttt * PI * 2; - wing->xRot = 0.125f - (float) (Mth::cos(flapTime)) * 0.2f; - wing->yRot = 0.25f; - wing->zRot = (float) (Mth::sin(flapTime) + 0.125f) * 0.8f; - wingTip->zRot = -(float) (Mth::sin(flapTime + 2.0f) + 0.5f) * 0.75f; + glEnable(GL_CULL_FACE); + for (int i = 0; i < 2; i++) { + float flapTime = ttt * PI * 2; + wing->xRot = 0.125f - (float)(Mth::cos(flapTime)) * 0.2f; + wing->yRot = 0.25f; + wing->zRot = (float)(Mth::sin(flapTime) + 0.125f) * 0.8f; + wingTip->zRot = -(float)(Mth::sin(flapTime + 2.0f) + 0.5f) * 0.75f; - rearLeg->xRot = 1.0f + yo * 0.1f; - rearLegTip->xRot = 0.5f + yo * 0.1f; - rearFoot->xRot = 0.75f + yo * 0.1f; + rearLeg->xRot = 1.0f + yo * 0.1f; + rearLegTip->xRot = 0.5f + yo * 0.1f; + rearFoot->xRot = 0.75f + yo * 0.1f; - frontLeg->xRot = 1.3f + yo * 0.1f; - frontLegTip->xRot = -0.5f - yo * 0.1f; - frontFoot->xRot = 0.75f + yo * 0.1f; - wing->render(scale,usecompiled); - frontLeg->render(scale,usecompiled); - rearLeg->render(scale,usecompiled); - glScalef(-1, 1, 1); - if (i == 0) - { - glCullFace(GL_FRONT); - } - } - glPopMatrix(); - glCullFace(GL_BACK); - glDisable(GL_CULL_FACE); + frontLeg->xRot = 1.3f + yo * 0.1f; + frontLegTip->xRot = -0.5f - yo * 0.1f; + frontFoot->xRot = 0.75f + yo * 0.1f; + wing->render(scale, usecompiled); + frontLeg->render(scale, usecompiled); + rearLeg->render(scale, usecompiled); + glScalef(-1, 1, 1); + if (i == 0) { + glCullFace(GL_FRONT); + } + } + glPopMatrix(); + glCullFace(GL_BACK); + glDisable(GL_CULL_FACE); - rr = -(float) Mth::sin(ttt * PI * 2) * 0.0f; - roff = ttt * PI * 2; - yy = 10; - zz = 60; - xx = 0; - dragon->getLatencyPos(start, 11, a); - for (int i = 0; i < 12; i++) - { - dragon->getLatencyPos(p, 12 + i, a); - rr += Mth::sin(i * 0.45f + roff) * 0.05f; - neck->yRot = (rotWrap(p[0] - start[0]) * rotScale + 180) * PI / 180; - neck->xRot = rr + (float) (p[1] - start[1]) * PI / 180 * rotScale * 5; - neck->zRot = rotWrap(p[0] - rot) * PI / 180 * rotScale; - neck->y = yy; - neck->z = zz; - neck->x = xx; - yy += Mth::sin(neck->xRot) * 10; - zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10; - xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10; - neck->render(scale,usecompiled); - } - glPopMatrix(); + rr = -(float)Mth::sin(ttt * PI * 2) * 0.0f; + roff = ttt * PI * 2; + yy = 10; + zz = 60; + xx = 0; + dragon->getLatencyPos(start, 11, a); + for (int i = 0; i < 12; i++) { + dragon->getLatencyPos(p, 12 + i, a); + rr += Mth::sin(i * 0.45f + roff) * 0.05f; + neck->yRot = (rotWrap(p[0] - start[0]) * rotScale + 180) * PI / 180; + neck->xRot = rr + (float)(p[1] - start[1]) * PI / 180 * rotScale * 5; + neck->zRot = rotWrap(p[0] - rot) * PI / 180 * rotScale; + neck->y = yy; + neck->z = zz; + neck->x = xx; + yy += Mth::sin(neck->xRot) * 10; + zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10; + xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10; + neck->render(scale, usecompiled); + } + glPopMatrix(); } -float DragonModel::rotWrap(double d) -{ - while (d >= 180) - d -= 360; - while (d < -180) - d += 360; - return (float) d; +float DragonModel::rotWrap(double d) { + while (d >= 180) d -= 360; + while (d < -180) d += 360; + return (float)d; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/DragonModel.h b/Minecraft.Client/Rendering/Models/DragonModel.h index baee83dec..e52112e80 100644 --- a/Minecraft.Client/Rendering/Models/DragonModel.h +++ b/Minecraft.Client/Rendering/Models/DragonModel.h @@ -2,34 +2,34 @@ #include "Model.h" #include "ModelPart.h" -class DragonModel : public Model -{ +class DragonModel : public Model { public: - static const int MODEL_ID = 4; + static const int MODEL_ID = 4; private: - ModelPart *head; - ModelPart *neck; - ModelPart *jaw; - ModelPart *body; - ModelPart *rearLeg; - ModelPart *frontLeg; - ModelPart *rearLegTip; - ModelPart *frontLegTip; - ModelPart *rearFoot; - ModelPart *frontFoot; - ModelPart *wing; - ModelPart *wingTip; - float a; + ModelPart* head; + ModelPart* neck; + ModelPart* jaw; + ModelPart* body; + ModelPart* rearLeg; + ModelPart* frontLeg; + ModelPart* rearLegTip; + ModelPart* frontLegTip; + ModelPart* rearFoot; + ModelPart* frontFoot; + ModelPart* wing; + ModelPart* wingTip; + float a; public: - - ModelPart *cubes[5]; + ModelPart* cubes[5]; DragonModel(float g); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); private: - float rotWrap(double d); - + float rotWrap(double d); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp b/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp index 05cb52e2c..3d6cf075b 100644 --- a/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp +++ b/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp @@ -1,44 +1,42 @@ #include "../../Platform/stdafx.h" #include "EnderCrystalModel.h" +EnderCrystalModel::EnderCrystalModel(float g) { + glass = new ModelPart(this, L"glass"); + glass->texOffs(0, 0)->addBox(-4, -4, -4, 8, 8, 8); + cube = new ModelPart(this, L"cube"); + cube->texOffs(32, 0)->addBox(-4, -4, -4, 8, 8, 8); -EnderCrystalModel::EnderCrystalModel(float g) -{ - glass = new ModelPart(this, L"glass"); - glass->texOffs(0, 0)->addBox(-4, -4, -4, 8, 8, 8); + base = new ModelPart(this, L"base"); + base->texOffs(0, 16)->addBox(-6, 0, -6, 12, 4, 12); - cube = new ModelPart(this, L"cube"); - cube->texOffs(32, 0)->addBox(-4, -4, -4, 8, 8, 8); - - base = new ModelPart(this, L"base"); - base->texOffs(0, 16)->addBox(-6, 0, -6, 12, 4, 12); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - glass->compile(1.0f/16.0f); - cube->compile(1.0f/16.0f); - base->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + glass->compile(1.0f / 16.0f); + cube->compile(1.0f / 16.0f); + base->compile(1.0f / 16.0f); } - -void EnderCrystalModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - glPushMatrix(); - glScalef(2, 2, 2); - glTranslatef(0, -0.5f, 0); - base->render(scale,usecompiled); - glRotatef(r, 0, 1, 0); - glTranslatef(0, 0.8f + bob, 0); - glRotatef(60, 0.7071f, 0, 0.7071f); - glass->render(scale,usecompiled); - float ss = 14 / 16.0f; - glScalef(ss, ss, ss); - glRotatef(60, 0.7071f, 0, 0.7071f); - glRotatef(r, 0, 1, 0); - glass->render(scale,usecompiled); - glScalef(ss, ss, ss); - glRotatef(60, 0.7071f, 0, 0.7071f); - glRotatef(r, 0, 1, 0); - cube->render(scale,usecompiled); - glPopMatrix(); +void EnderCrystalModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + glPushMatrix(); + glScalef(2, 2, 2); + glTranslatef(0, -0.5f, 0); + base->render(scale, usecompiled); + glRotatef(r, 0, 1, 0); + glTranslatef(0, 0.8f + bob, 0); + glRotatef(60, 0.7071f, 0, 0.7071f); + glass->render(scale, usecompiled); + float ss = 14 / 16.0f; + glScalef(ss, ss, ss); + glRotatef(60, 0.7071f, 0, 0.7071f); + glRotatef(r, 0, 1, 0); + glass->render(scale, usecompiled); + glScalef(ss, ss, ss); + glRotatef(60, 0.7071f, 0, 0.7071f); + glRotatef(r, 0, 1, 0); + cube->render(scale, usecompiled); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderCrystalModel.h b/Minecraft.Client/Rendering/Models/EnderCrystalModel.h index 42ae1b3d1..ead865977 100644 --- a/Minecraft.Client/Rendering/Models/EnderCrystalModel.h +++ b/Minecraft.Client/Rendering/Models/EnderCrystalModel.h @@ -2,17 +2,18 @@ #include "Model.h" #include "ModelPart.h" -class EnderCrystalModel : public Model -{ +class EnderCrystalModel : public Model { public: - static const int MODEL_ID = 1; + static const int MODEL_ID = 1; private: - ModelPart *cube; - ModelPart *glass; - ModelPart *base; + ModelPart* cube; + ModelPart* glass; + ModelPart* base; public: - EnderCrystalModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + EnderCrystalModel(float g); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderManModel.cpp b/Minecraft.Client/Rendering/Models/EnderManModel.cpp index 81816d05b..377f0a874 100644 --- a/Minecraft.Client/Rendering/Models/EnderManModel.cpp +++ b/Minecraft.Client/Rendering/Models/EnderManModel.cpp @@ -2,120 +2,116 @@ #include "EnderManModel.h" #include "ModelPart.h" -EndermanModel::EndermanModel() : HumanoidModel(0, -14, 64, 32) -{ - carrying = false; - creepy = false; +EndermanModel::EndermanModel() : HumanoidModel(0, -14, 64, 32) { + carrying = false; + creepy = false; - float yOffset = -14.0f; - float g = 0; + float yOffset = -14.0f; + float g = 0; - delete hair; - hair = new ModelPart(this, 0, 16); - hair->addBox(-4.0f, -8.0f, -4.0f, 8, 8, 8, g - 0.5f); // Head - hair->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete hair; + hair = new ModelPart(this, 0, 16); + hair->addBox(-4.0f, -8.0f, -4.0f, 8, 8, 8, g - 0.5f); // Head + hair->setPos(0.0f, 0.0f + yOffset, 0.0f); - delete body; - body = new ModelPart(this, 32, 16); - body->addBox(-4.0f, 0.0f, -2.0f, 8, 12, 4, g); // Body - body->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete body; + body = new ModelPart(this, 32, 16); + body->addBox(-4.0f, 0.0f, -2.0f, 8, 12, 4, g); // Body + body->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete arm0; + arm0 = new ModelPart(this, 56, 0); + arm0->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm0 + arm0->setPos(-3.0f, 2.0f + yOffset, 0.0f); - delete arm0; - arm0 = new ModelPart(this, 56, 0); - arm0->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm0 - arm0->setPos(-3.0f, 2.0f + yOffset, 0.0f); + delete arm1; + arm1 = new ModelPart(this, 56, 0); + arm1->bMirror = true; + arm1->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm1 + arm1->setPos(5.0f, 2.0f + yOffset, 0.0f); + delete leg0; + leg0 = new ModelPart(this, 56, 0); + leg0->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg0 + leg0->setPos(-2.0f, 12.0f + yOffset, 0.0f); - delete arm1; - arm1 = new ModelPart(this, 56, 0); - arm1->bMirror = true; - arm1->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm1 - arm1->setPos(5.0f, 2.0f + yOffset, 0.0f); - - delete leg0; - leg0 = new ModelPart(this, 56, 0); - leg0->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg0 - leg0->setPos(-2.0f, 12.0f + yOffset, 0.0f); - - delete leg1; - leg1 = new ModelPart(this, 56, 0); - leg1->bMirror = true; - leg1->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg1 - leg1->setPos(2.0f, 12.0f + yOffset, 0.0f); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - body->compile(1.0f/16.0f); - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); + delete leg1; + leg1 = new ModelPart(this, 56, 0); + leg1->bMirror = true; + leg1->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg1 + leg1->setPos(2.0f, 12.0f + yOffset, 0.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + body->compile(1.0f / 16.0f); + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); } -void EndermanModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void EndermanModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); - head->visible = true; + head->visible = true; - float yOffs = -14.0f; - body->xRot = 0.0f; - body->y = yOffs; - body->z = -0.0f; + float yOffs = -14.0f; + body->xRot = 0.0f; + body->y = yOffs; + body->z = -0.0f; - leg0->xRot -= 0.0f; - leg1->xRot -= 0.0f; + leg0->xRot -= 0.0f; + leg1->xRot -= 0.0f; - arm0->xRot *= 0.5f; - arm1->xRot *= 0.5f; - leg0->xRot *= 0.5f; - leg1->xRot *= 0.5f; + arm0->xRot *= 0.5f; + arm1->xRot *= 0.5f; + leg0->xRot *= 0.5f; + leg1->xRot *= 0.5f; - float max = 0.4f; - if (arm0->xRot > +max) arm0->xRot = +max; - if (arm1->xRot > +max) arm1->xRot = +max; - if (arm0->xRot < -max) arm0->xRot = -max; - if (arm1->xRot < -max) arm1->xRot = -max; - if (leg0->xRot > +max) leg0->xRot = +max; - if (leg1->xRot > +max) leg1->xRot = +max; - if (leg0->xRot < -max) leg0->xRot = -max; - if (leg1->xRot < -max) leg1->xRot = -max; + float max = 0.4f; + if (arm0->xRot > +max) arm0->xRot = +max; + if (arm1->xRot > +max) arm1->xRot = +max; + if (arm0->xRot < -max) arm0->xRot = -max; + if (arm1->xRot < -max) arm1->xRot = -max; + if (leg0->xRot > +max) leg0->xRot = +max; + if (leg1->xRot > +max) leg1->xRot = +max; + if (leg0->xRot < -max) leg0->xRot = -max; + if (leg1->xRot < -max) leg1->xRot = -max; + if (carrying) { + arm0->xRot = -0.5f; + arm1->xRot = -0.5f; + arm0->zRot = 0.05f; + arm1->zRot = -0.05f; + } - if (carrying) - { - arm0->xRot = -0.5f; - arm1->xRot = -0.5f; - arm0->zRot = 0.05f; - arm1->zRot = -0.05f; - } + arm0->z = -0.0f; + arm1->z = -0.0f; + leg0->z = -0.0f; + leg1->z = -0.0f; - arm0->z = -0.0f; - arm1->z = -0.0f; - leg0->z = -0.0f; - leg1->z = -0.0f; + arm0->y = 2.0f + yOffs; + arm1->y = 2.0f + yOffs; - arm0->y = 2.0f + yOffs; - arm1->y = 2.0f + yOffs; + leg0->y = +9.0f + yOffs; + leg1->y = +9.0f + yOffs; - leg0->y = +9.0f + yOffs; - leg1->y = +9.0f + yOffs; + head->z = -0.0f; + head->y = +yOffs + 1; - head->z = -0.0f; - head->y = +yOffs + 1; + hair->x = head->x; + hair->y = head->y; + hair->z = head->z; + hair->xRot = head->xRot; + hair->yRot = head->yRot; + hair->zRot = head->zRot; - hair->x = head->x; - hair->y = head->y; - hair->z = head->z; - hair->xRot = head->xRot; - hair->yRot = head->yRot; - hair->zRot = head->zRot; - - if (creepy) - { - float amt = 1; - head->y -= (float) (amt * 5); - } + if (creepy) { + float amt = 1; + head->y -= (float)(amt * 5); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderManModel.h b/Minecraft.Client/Rendering/Models/EnderManModel.h index 3760e7968..a1a8ebce6 100644 --- a/Minecraft.Client/Rendering/Models/EnderManModel.h +++ b/Minecraft.Client/Rendering/Models/EnderManModel.h @@ -2,12 +2,13 @@ #include "HumanoidModel.h" -class EndermanModel : public HumanoidModel -{ +class EndermanModel : public HumanoidModel { public: - bool carrying; - bool creepy; + bool carrying; + bool creepy; - EndermanModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + EndermanModel(); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/GhastModel.cpp b/Minecraft.Client/Rendering/Models/GhastModel.cpp index b5f64fd21..5f8f70153 100644 --- a/Minecraft.Client/Rendering/Models/GhastModel.cpp +++ b/Minecraft.Client/Rendering/Models/GhastModel.cpp @@ -4,16 +4,15 @@ #include "GhastModel.h" #include "ModelPart.h" -GhastModel::GhastModel() : Model() -{ +GhastModel::GhastModel() : Model() { int yoffs = -16; body = new ModelPart(this, 0, 0); body->addBox(-8, -8, -8, 16, 16, 16); body->y += (8 + 16) + yoffs; - Random *random = new Random(1660); - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { + Random* random = new Random(1660); + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i] = new ModelPart(this, 0, 0); float xo = (((i % 3 - (i / 3 % 2) * 0.5f + 0.25f) / 2.0f * 2 - 1) * 5); @@ -26,34 +25,36 @@ GhastModel::GhastModel() : Model() tentacles[i]->y = (float)(31 + yoffs); } - // 4J added - compile now to avoid random performance hit first time cubes are rendered - body->compile(1.0f/16.0f); - for( int i = 0; i < TENTACLESLENGTH; i++ ) - { - tentacles[i]->compile(1.0f/16.0f); - } + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + body->compile(1.0f / 16.0f); + for (int i = 0; i < TENTACLESLENGTH; i++) { + tentacles[i]->compile(1.0f / 16.0f); + } } -void GhastModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { +void GhastModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i]->xRot = 0.2f * Mth::sin(bob * 0.3f + i) + 0.4f; } } -void GhastModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void GhastModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - glPushMatrix(); - glTranslatef(0, .6f, 0); + glPushMatrix(); + glTranslatef(0, .6f, 0); body->render(scale, usecompiled); - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i]->render(scale, usecompiled); } - glPopMatrix(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/GhastModel.h b/Minecraft.Client/Rendering/Models/GhastModel.h index 59ce7b7df..610152766 100644 --- a/Minecraft.Client/Rendering/Models/GhastModel.h +++ b/Minecraft.Client/Rendering/Models/GhastModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class GhastModel : public Model -{ +class GhastModel : public Model { public: - static const int TENTACLESLENGTH=9; - ModelPart *body; - ModelPart *tentacles[TENTACLESLENGTH]; + static const int TENTACLESLENGTH = 9; + ModelPart* body; + ModelPart* tentacles[TENTACLESLENGTH]; GhastModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/HumanoidModel.cpp b/Minecraft.Client/Rendering/Models/HumanoidModel.cpp index a548edf8c..ef4d78f95 100644 --- a/Minecraft.Client/Rendering/Models/HumanoidModel.cpp +++ b/Minecraft.Client/Rendering/Models/HumanoidModel.cpp @@ -4,438 +4,419 @@ #include "../../../Minecraft.World/Entities/Entity.h" #include "ModelPart.h" -// 4J added +// 4J added -ModelPart * HumanoidModel::AddOrRetrievePart(SKIN_BOX *pBox) -{ - ModelPart *pAttachTo=NULL; +ModelPart* HumanoidModel::AddOrRetrievePart(SKIN_BOX* pBox) { + ModelPart* pAttachTo = NULL; - switch(pBox->ePart) - { - case eBodyPart_Head: - pAttachTo=head; - break; - case eBodyPart_Body: - pAttachTo=body; - break; - case eBodyPart_Arm0: - pAttachTo=arm0; - break; - case eBodyPart_Arm1: - pAttachTo=arm1; - break; - case eBodyPart_Leg0: - pAttachTo=leg0; - break; - case eBodyPart_Leg1: - pAttachTo=leg1; - break; - case eBodyPart_Unknown: - default: - return NULL; - } + switch (pBox->ePart) { + case eBodyPart_Head: + pAttachTo = head; + break; + case eBodyPart_Body: + pAttachTo = body; + break; + case eBodyPart_Arm0: + pAttachTo = arm0; + break; + case eBodyPart_Arm1: + pAttachTo = arm1; + break; + case eBodyPart_Leg0: + pAttachTo = leg0; + break; + case eBodyPart_Leg1: + pAttachTo = leg1; + break; + case eBodyPart_Unknown: + default: + return NULL; + } - // first check this box doesn't already exist - ModelPart *pNewBox = pAttachTo->retrieveChild(pBox); + // first check this box doesn't already exist + ModelPart* pNewBox = pAttachTo->retrieveChild(pBox); - if(pNewBox) - { - if((pNewBox->getfU()!=(int)pBox->fU) || (pNewBox->getfV()!=(int)pBox->fV)) - { - app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Box geometry was found, but with different uvs\n"); - pNewBox=NULL; - } - } - if(pNewBox==NULL) - { - //app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Adding box to model part\n"); + if (pNewBox) { + if ((pNewBox->getfU() != (int)pBox->fU) || + (pNewBox->getfV() != (int)pBox->fV)) { + app.DebugPrintf( + "HumanoidModel::AddOrRetrievePart - Box geometry was found, " + "but with different uvs\n"); + pNewBox = NULL; + } + } + if (pNewBox == NULL) { + // app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Adding box to + // model part\n"); - pNewBox = new ModelPart(this, (int)pBox->fU, (int)pBox->fV); - pNewBox->visible=false; - pNewBox->addHumanoidBox(pBox->fX, pBox->fY, pBox->fZ, pBox->fW, pBox->fH, pBox->fD, 0); - // 4J-PB - don't compile here, since the lighting isn't set up. It'll be compiled on first use. - //pNewBox->compile(1.0f/16.0f); - pAttachTo->addChild(pNewBox); - } + pNewBox = new ModelPart(this, (int)pBox->fU, (int)pBox->fV); + pNewBox->visible = false; + pNewBox->addHumanoidBox(pBox->fX, pBox->fY, pBox->fZ, pBox->fW, + pBox->fH, pBox->fD, 0); + // 4J-PB - don't compile here, since the lighting isn't set up. It'll be + // compiled on first use. + // pNewBox->compile(1.0f/16.0f); + pAttachTo->addChild(pNewBox); + } - return pNewBox; + return pNewBox; } -void HumanoidModel::_init(float g, float yOffset, int texWidth, int texHeight) -{ - this->texWidth = texWidth; - this->texHeight = texHeight; +void HumanoidModel::_init(float g, float yOffset, int texWidth, int texHeight) { + this->texWidth = texWidth; + this->texHeight = texHeight; - m_fYOffset=yOffset; + m_fYOffset = yOffset; cloak = new ModelPart(this, 0, 0); - cloak->addHumanoidBox(-5, -0, -1, 10, 16, 1, g); // Cloak + cloak->addHumanoidBox(-5, -0, -1, 10, 16, 1, g); // Cloak ear = new ModelPart(this, 24, 0); - ear->addHumanoidBox(-3, -6, -1, 6, 6, 1, g); // Ear - + ear->addHumanoidBox(-3, -6, -1, 6, 6, 1, g); // Ear + head = new ModelPart(this, 0, 0); - head->addHumanoidBox(-4, -8, -4, 8, 8, 8, g); // Head + head->addHumanoidBox(-4, -8, -4, 8, 8, 8, g); // Head head->setPos(0, 0 + yOffset, 0); hair = new ModelPart(this, 32, 0); - hair->addHumanoidBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head + hair->addHumanoidBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head hair->setPos(0, 0 + yOffset, 0); body = new ModelPart(this, 16, 16); - body->addHumanoidBox(-4, 0, -2, 8, 12, 4, g); // Body + body->addHumanoidBox(-4, 0, -2, 8, 12, 4, g); // Body body->setPos(0, 0 + yOffset, 0); arm0 = new ModelPart(this, 24 + 16, 16); - arm0->addHumanoidBox(-3, -2, -2, 4, 12, 4, g); // Arm0 + arm0->addHumanoidBox(-3, -2, -2, 4, 12, 4, g); // Arm0 arm0->setPos(-5, 2 + yOffset, 0); arm1 = new ModelPart(this, 24 + 16, 16); arm1->bMirror = true; - arm1->addHumanoidBox(-1, -2, -2, 4, 12, 4, g); // Arm1 + arm1->addHumanoidBox(-1, -2, -2, 4, 12, 4, g); // Arm1 arm1->setPos(5, 2 + yOffset, 0); leg0 = new ModelPart(this, 0, 16); - leg0->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg0 + leg0->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg0 leg0->setPos(-1.9, 12 + yOffset, 0); leg1 = new ModelPart(this, 0, 16); leg1->bMirror = true; - leg1->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg1 + leg1->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg1 leg1->setPos(1.9, 12 + yOffset, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - cloak->compile(1.0f/16.0f); - ear->compile(1.0f/16.0f); - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + cloak->compile(1.0f / 16.0f); + ear->compile(1.0f / 16.0f); + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); - holdingLeftHand=0; - holdingRightHand=0; - sneaking=false; - idle=false; - bowAndArrow=false; + holdingLeftHand = 0; + holdingRightHand = 0; + sneaking = false; + idle = false; + bowAndArrow = false; - // 4J added - eating = false; - eating_t = 0.0f; - eating_swing = 0.0f; - m_uiAnimOverrideBitmask = 0L; + // 4J added + eating = false; + eating_t = 0.0f; + eating_swing = 0.0f; + m_uiAnimOverrideBitmask = 0L; } -HumanoidModel::HumanoidModel() : Model() -{ - _init(0, 0, 64, 32); +HumanoidModel::HumanoidModel() : Model() { _init(0, 0, 64, 32); } + +HumanoidModel::HumanoidModel(float g) : Model() { _init(g, 0, 64, 32); } + +HumanoidModel::HumanoidModel(float g, float yOffset, int texWidth, + int texHeight) + : Model() { + _init(g, yOffset, texWidth, texHeight); } -HumanoidModel::HumanoidModel(float g) : Model() -{ - _init(g, 0, 64, 32); +void HumanoidModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + if (entity != NULL) { + m_uiAnimOverrideBitmask = entity->getAnimOverrideBitmask(); + } + + setupAnim(time, r, bob, yRot, xRot, scale, m_uiAnimOverrideBitmask); + + if (young) { + float ss = 2.0f; + glPushMatrix(); + glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); + glTranslatef(0, 16 * scale, 0); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + arm0->render(scale, usecompiled); + arm1->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + hair->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHead)) > 0); + body->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderTorso)) > 0); + arm0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm0)) > 0); + arm1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm1)) > 0); + leg0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg0)) > 0); + leg1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg1)) > 0); + hair->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHair)) > 0); + } } -HumanoidModel::HumanoidModel(float g, float yOffset, int texWidth, int texHeight) : Model() -{ - _init(g,yOffset,texWidth,texHeight); +void HumanoidModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + // bool bIsAttacking = (attackTime > -9990.0f); + + { + head->yRot = yRot / (float)(180.0f / PI); + head->xRot = xRot / (float)(180.0f / PI); + hair->yRot = head->yRot; + hair->xRot = head->xRot; + + // Does the skin have an override for anim? + + if (uiBitmaskOverrideAnim & (1 << eAnim_ArmsDown)) { + arm0->xRot = 0.0f; + arm1->xRot = 0.0f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + + } else if (uiBitmaskOverrideAnim & (1 << eAnim_ArmsOutFront)) { + arm0->xRot = -HALF_PI; + arm1->xRot = -HALF_PI; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_SingleArms)) { + arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm1->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } + // 4J-PB - Weeping Angel - does't look good holding something in the arm + // that's up + else if ((uiBitmaskOverrideAnim & (1 << eAnim_StatueOfLiberty)) && + (holdingRightHand == 0) && (attackTime == 0.0f)) { + arm0->xRot = -PI; + arm0->zRot = -0.3f; + arm1->xRot = (Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; + arm1->zRot = 0.0f; + } else { + arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm1->xRot = (Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } + // arm0.zRot = ((float) (util.Mth.cos(time * 0.2312f) + 1) * 1) * + // r; + + // arm1.zRot = ((float) (util.Mth.cos(time * 0.2812f) - 1) * 1) * + // r; + + leg0->yRot = 0.0f; + leg1->yRot = 0.0f; + + if (riding) { + arm0->xRot += -HALF_PI * 0.4f; + arm1->xRot += -HALF_PI * 0.4f; + leg0->xRot = -HALF_PI * 0.8f; + leg1->xRot = -HALF_PI * 0.8f; + leg0->yRot = HALF_PI * 0.2f; + leg1->yRot = -HALF_PI * 0.2f; + } else if (idle && !sneaking) { + leg0->xRot = -HALF_PI; + leg1->xRot = -HALF_PI; + leg0->yRot = HALF_PI * 0.2f; + leg1->yRot = -HALF_PI * 0.2f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_NoLegAnim)) { + leg0->xRot = 0.0f; + leg0->zRot = 0.0f; + leg1->xRot = 0.0f; + leg1->zRot = 0.0f; + leg0->yRot = 0.0f; + leg1->yRot = 0.0f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_SingleLegs)) { + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + } else { + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; + } + + if (holdingLeftHand != 0) { + arm1->xRot = arm1->xRot * 0.5f - HALF_PI * 0.2f * holdingLeftHand; + } + if (holdingRightHand != 0) { + arm0->xRot = arm0->xRot * 0.5f - HALF_PI * 0.2f * holdingRightHand; + } + + arm0->yRot = 0.0f; + arm1->yRot = 0.0f; + if (attackTime > -9990.0f) { + float swing = attackTime; + body->yRot = Mth::sin(sqrt(swing) * PI * 2.0f) * 0.2f; + arm0->z = Mth::sin(body->yRot) * 5.0f; + arm0->x = -Mth::cos(body->yRot) * 5.0f; + arm1->z = -Mth::sin(body->yRot) * 5.0f; + arm1->x = Mth::cos(body->yRot) * 5.0f; + arm0->yRot += body->yRot; + arm1->yRot += body->yRot; + arm1->xRot += body->yRot; + + swing = 1.0f - attackTime; + swing *= swing; + swing *= swing; + swing = 1.0f - swing; + float aa = Mth::sin(swing * PI); + float bb = Mth::sin(attackTime * PI) * -(head->xRot - 0.7f) * 0.75f; + arm0->xRot -= aa * 1.2f + bb; // 4J - changed 1.2 -> 1.2f + arm0->yRot += body->yRot * 2.0f; + + if ((uiBitmaskOverrideAnim & (1 << eAnim_StatueOfLiberty)) && + (holdingRightHand == 0) && (attackTime == 0.0f)) { + arm0->zRot -= Mth::sin(attackTime * PI) * -0.4f; + } else { + arm0->zRot = Mth::sin(attackTime * PI) * -0.4f; + } + } + + // 4J added + if (eating) { + // These factors are largely lifted from ItemInHandRenderer to try + // and keep the 3rd person eating animation as similar as possible + float is = 1 - eating_swing; + is = is * is * is; + is = is * is * is; + is = is * is * is; + float iss = 1 - is; + arm0->xRot = -Mth::abs(Mth::cos(eating_t / 4.0f * PI) * 0.1f) * + (eating_swing > 0.2 ? 1.0f : 0.0f) * + 2.0f; // This factor is the chomping bit (conditional + // factor is so that he doesn't eat whilst the + // food is being pulled away at the end) + arm0->yRot -= + iss * 0.5f; // This factor and the following to the general arm + // movement through the life of the swing + arm0->xRot -= iss * 1.2f; + } + + if (sneaking) { + body->xRot = 0.5f; + leg0->xRot -= 0.0f; + leg1->xRot -= 0.0f; + arm0->xRot += 0.4f; + arm1->xRot += 0.4f; + leg0->z = +4.0f; + leg1->z = +4.0f; + body->y = 0.0f; + arm0->y = 2.0f; + arm1->y = 2.0f; + leg0->y = +9.0f; + leg1->y = +9.0f; + head->y = +1.0f; + hair->y = +1.0f; + ear->y = +1.0f; + cloak->y = 0.0f; + } else { + body->xRot = 0.0f; + leg0->z = 0.1f; + leg1->z = 0.1f; + + if (!riding && idle) { + leg0->y = 22.0f; + leg1->y = 22.0f; + body->y = 10.0f; + arm0->y = 12.0f; + arm1->y = 12.0f; + head->y = 10.0f; + hair->y = 10.0f; + ear->y = 11.0f; + cloak->y = 10.0f; + } else { + leg0->y = 12.0f; + leg1->y = 12.0f; + body->y = 0.0f; + arm0->y = 2.0f; + arm1->y = 2.0f; + head->y = 0.0f; + hair->y = 0.0f; + ear->y = 1.0f; + cloak->y = 0.0f; + } + } + + arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); + arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); + + if (bowAndArrow) { + float attack2 = 0.0f; + float attack = 0.0f; + + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + arm0->yRot = -(0.1f - attack2 * 0.6f) + head->yRot; + arm1->yRot = +(0.1f - attack2 * 0.6f) + head->yRot + 0.4f; + arm0->xRot = -HALF_PI + head->xRot; + arm1->xRot = -HALF_PI + head->xRot; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + arm0->zRot += ((float)(Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((float)(Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm0->xRot += ((float)(Mth::sin(bob * 0.067f)) * 0.05f); + arm1->xRot -= ((float)(Mth::sin(bob * 0.067f)) * 0.05f); + } + } } -void HumanoidModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - if(entity!=NULL) - { - m_uiAnimOverrideBitmask=entity->getAnimOverrideBitmask(); - } - - setupAnim(time, r, bob, yRot, xRot, scale, m_uiAnimOverrideBitmask); - - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); - glTranslatef(0, 16 * scale, 0); - head->render(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - arm0->render(scale, usecompiled); - arm1->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - hair->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - body->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - hair->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - } -} - -void HumanoidModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - //bool bIsAttacking = (attackTime > -9990.0f); - - { - head->yRot = yRot / (float) (180.0f / PI); - head->xRot = xRot / (float) (180.0f / PI); - hair->yRot = head->yRot; - hair->xRot = head->xRot; - - // Does the skin have an override for anim? - - if(uiBitmaskOverrideAnim&(1<xRot=0.0f; - arm1->xRot=0.0f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - - } - else if(uiBitmaskOverrideAnim&(1<xRot=-HALF_PI; - arm1->xRot=-HALF_PI; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - else if(uiBitmaskOverrideAnim&(1<xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm1->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - // 4J-PB - Weeping Angel - does't look good holding something in the arm that's up - else if((uiBitmaskOverrideAnim&(1<xRot = -PI; - arm0->zRot = -0.3f; - arm1->xRot = ( Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; - arm1->zRot = 0.0f; - } - else - { - arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm1->xRot = ( Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - // arm0.zRot = ((float) (util.Mth.cos(time * 0.2312f) + 1) * 1) * r; - - - // arm1.zRot = ((float) (util.Mth.cos(time * 0.2812f) - 1) * 1) * r; - - - leg0->yRot = 0.0f; - leg1->yRot = 0.0f; - - if (riding) - { - arm0->xRot += -HALF_PI * 0.4f; - arm1->xRot += -HALF_PI * 0.4f; - leg0->xRot = -HALF_PI * 0.8f; - leg1->xRot = -HALF_PI * 0.8f; - leg0->yRot = HALF_PI * 0.2f; - leg1->yRot = -HALF_PI * 0.2f; - } - else if(idle && !sneaking ) - { - leg0->xRot = -HALF_PI; - leg1->xRot = -HALF_PI; - leg0->yRot = HALF_PI * 0.2f; - leg1->yRot = -HALF_PI * 0.2f; - } - else if(uiBitmaskOverrideAnim&(1<xRot=0.0f; - leg0->zRot=0.0f; - leg1->xRot=0.0f; - leg1->zRot=0.0f; - leg0->yRot = 0.0f; - leg1->yRot = 0.0f; - } - else if(uiBitmaskOverrideAnim&(1<xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - } - else - { - leg0->xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f + PI) * 1.4f) * r; - } - - - if (holdingLeftHand != 0) - { - arm1->xRot = arm1->xRot * 0.5f - HALF_PI * 0.2f * holdingLeftHand; - } - if (holdingRightHand != 0) - { - arm0->xRot = arm0->xRot * 0.5f - HALF_PI * 0.2f * holdingRightHand; - } - - arm0->yRot = 0.0f; - arm1->yRot = 0.0f; - if (attackTime > -9990.0f) - { - float swing = attackTime; - body->yRot = Mth::sin(sqrt(swing) * PI * 2.0f) * 0.2f; - arm0->z = Mth::sin(body->yRot) * 5.0f; - arm0->x = -Mth::cos(body->yRot) * 5.0f; - arm1->z = -Mth::sin(body->yRot) * 5.0f; - arm1->x = Mth::cos(body->yRot) * 5.0f; - arm0->yRot += body->yRot; - arm1->yRot += body->yRot; - arm1->xRot += body->yRot; - - swing = 1.0f - attackTime; - swing *= swing; - swing *= swing; - swing = 1.0f - swing; - float aa = Mth::sin(swing * PI); - float bb = Mth::sin(attackTime * PI) * -(head->xRot - 0.7f) * 0.75f; - arm0->xRot -= aa * 1.2f + bb; // 4J - changed 1.2 -> 1.2f - arm0->yRot += body->yRot * 2.0f; - - if((uiBitmaskOverrideAnim&(1<zRot -= Mth::sin(attackTime * PI) * -0.4f; - } - else - { - arm0->zRot = Mth::sin(attackTime * PI) * -0.4f; - } - } - - // 4J added - if( eating ) - { - // These factors are largely lifted from ItemInHandRenderer to try and keep the 3rd person eating animation as similar as possible - float is = 1 - eating_swing; - is = is * is * is; - is = is * is * is; - is = is * is * is; - float iss = 1 - is; - arm0->xRot = - Mth::abs(Mth::cos(eating_t / 4.0f * PI) * 0.1f) * (eating_swing > 0.2 ? 1.0f : 0.0f) * 2.0f; // This factor is the chomping bit (conditional factor is so that he doesn't eat whilst the food is being pulled away at the end) - arm0->yRot -= iss * 0.5f; // This factor and the following to the general arm movement through the life of the swing - arm0->xRot -= iss * 1.2f; - - } - - if (sneaking) - { - body->xRot = 0.5f; - leg0->xRot -= 0.0f; - leg1->xRot -= 0.0f; - arm0->xRot += 0.4f; - arm1->xRot += 0.4f; - leg0->z = +4.0f; - leg1->z = +4.0f; - body->y = 0.0f; - arm0->y = 2.0f; - arm1->y = 2.0f; - leg0->y = +9.0f; - leg1->y = +9.0f; - head->y = +1.0f; - hair->y = +1.0f; - ear->y = +1.0f; - cloak->y = 0.0f; - } - else - { - body->xRot = 0.0f; - leg0->z = 0.1f; - leg1->z = 0.1f; - - if(!riding && idle) - { - leg0->y = 22.0f; - leg1->y = 22.0f; - body->y = 10.0f; - arm0->y = 12.0f; - arm1->y = 12.0f; - head->y = 10.0f; - hair->y = 10.0f; - ear->y = 11.0f; - cloak->y = 10.0f; - } - else - { - leg0->y = 12.0f; - leg1->y = 12.0f; - body->y = 0.0f; - arm0->y = 2.0f; - arm1->y = 2.0f; - head->y = 0.0f; - hair->y = 0.0f; - ear->y = 1.0f; - cloak->y = 0.0f; - } - } - - - arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); - arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); - - if (bowAndArrow) - { - float attack2 = 0.0f; - float attack = 0.0f; - - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - arm0->yRot = -(0.1f - attack2 * 0.6f) + head->yRot; - arm1->yRot = +(0.1f - attack2 * 0.6f) + head->yRot + 0.4f; - arm0->xRot = -HALF_PI + head->xRot; - arm1->xRot = -HALF_PI + head->xRot; - arm0->xRot -= attack2 * 1.2f - attack * 0.4f; - arm1->xRot -= attack2 * 1.2f - attack * 0.4f; - arm0->zRot += ((float) (Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm1->zRot -= ((float) (Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm0->xRot += ((float) (Mth::sin(bob * 0.067f)) * 0.05f); - arm1->xRot -= ((float) (Mth::sin(bob * 0.067f)) * 0.05f); - } - } -} - -void HumanoidModel::renderHair(float scale,bool usecompiled) -{ +void HumanoidModel::renderHair(float scale, bool usecompiled) { hair->yRot = head->yRot; hair->xRot = head->xRot; - hair->render(scale,usecompiled); + hair->render(scale, usecompiled); } -void HumanoidModel::renderEars(float scale,bool usecompiled) -{ +void HumanoidModel::renderEars(float scale, bool usecompiled) { ear->yRot = head->yRot; ear->xRot = head->xRot; - ear->x=0; - ear->y=0; - ear->render(scale,usecompiled); + ear->x = 0; + ear->y = 0; + ear->render(scale, usecompiled); } -void HumanoidModel::renderCloak(float scale,bool usecompiled) -{ - cloak->render(scale,usecompiled); +void HumanoidModel::renderCloak(float scale, bool usecompiled) { + cloak->render(scale, usecompiled); } -void HumanoidModel::render(HumanoidModel *model, float scale, bool usecompiled) -{ +void HumanoidModel::render(HumanoidModel* model, float scale, + bool usecompiled) { head->yRot = model->head->yRot; head->y = model->head->y; head->xRot = model->head->xRot; @@ -444,23 +425,37 @@ void HumanoidModel::render(HumanoidModel *model, float scale, bool usecompiled) hair->xRot = head->xRot; body->yRot = model->body->yRot; - + arm0->xRot = model->arm0->xRot; arm0->yRot = model->arm0->yRot; arm0->zRot = model->arm0->zRot; - + arm1->xRot = model->arm1->xRot; arm1->yRot = model->arm1->yRot; arm1->zRot = model->arm1->zRot; - + leg0->xRot = model->leg0->xRot; leg1->xRot = model->leg1->xRot; - head->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - body->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - hair->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); + head->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHead)) > 0); + body->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderTorso)) > 0); + arm0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm0)) > 0); + arm1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm1)) > 0); + leg0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg0)) > 0); + leg1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg1)) > 0); + hair->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHair)) > 0); } diff --git a/Minecraft.Client/Rendering/Models/HumanoidModel.h b/Minecraft.Client/Rendering/Models/HumanoidModel.h index 2f9fcff57..3eb256b77 100644 --- a/Minecraft.Client/Rendering/Models/HumanoidModel.h +++ b/Minecraft.Client/Rendering/Models/HumanoidModel.h @@ -1,65 +1,69 @@ #pragma once #include "Model.h" -class HumanoidModel : public Model -{ +class HumanoidModel : public Model { public: - ModelPart *head, *hair, *body, *arm0, *arm1, *leg0, *leg1, *ear, *cloak; - //ModelPart *hat; + ModelPart *head, *hair, *body, *arm0, *arm1, *leg0, *leg1, *ear, *cloak; + // ModelPart *hat; - int holdingLeftHand; + int holdingLeftHand; int holdingRightHand; - bool idle; - bool sneaking; - bool bowAndArrow; - bool eating; // 4J added - float eating_t; // 4J added - float eating_swing; // 4J added - unsigned int m_uiAnimOverrideBitmask; // 4J added - float m_fYOffset; // 4J added - enum animbits - { - eAnim_ArmsDown =0, - eAnim_ArmsOutFront, - eAnim_NoLegAnim, - eAnim_HasIdle, - eAnim_ForceAnim, // Claptrap looks bad if the user turns off custom skin anim - // 4J-PB - DaveK wants Fish characters to move both legs in the same way - eAnim_SingleLegs, - eAnim_SingleArms, - eAnim_StatueOfLiberty, // Dr Who Weeping Angel - eAnim_DontRenderArmour, // Dr Who Daleks - eAnim_NoBobbing, // Dr Who Daleks - eAnim_DisableRenderHead, - eAnim_DisableRenderArm0, - eAnim_DisableRenderArm1, - eAnim_DisableRenderTorso, - eAnim_DisableRenderLeg0, - eAnim_DisableRenderLeg1, - eAnim_DisableRenderHair + bool idle; + bool sneaking; + bool bowAndArrow; + bool eating; // 4J added + float eating_t; // 4J added + float eating_swing; // 4J added + unsigned int m_uiAnimOverrideBitmask; // 4J added + float m_fYOffset; // 4J added + enum animbits { + eAnim_ArmsDown = 0, + eAnim_ArmsOutFront, + eAnim_NoLegAnim, + eAnim_HasIdle, + eAnim_ForceAnim, // Claptrap looks bad if the user turns off custom + // skin anim + // 4J-PB - DaveK wants Fish characters to move both legs in the same way + eAnim_SingleLegs, + eAnim_SingleArms, + eAnim_StatueOfLiberty, // Dr Who Weeping Angel + eAnim_DontRenderArmour, // Dr Who Daleks + eAnim_NoBobbing, // Dr Who Daleks + eAnim_DisableRenderHead, + eAnim_DisableRenderArm0, + eAnim_DisableRenderArm1, + eAnim_DisableRenderTorso, + eAnim_DisableRenderLeg0, + eAnim_DisableRenderLeg1, + eAnim_DisableRenderHair - }; + }; - static const unsigned int m_staticBitmaskIgnorePlayerCustomAnimSetting= (1< entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); void renderHair(float scale, bool usecompiled); void renderEars(float scale, bool usecompiled); - void renderCloak(float scale, bool usecompiled); - void render(HumanoidModel *model, float scale, bool usecompiled); + void renderCloak(float scale, bool usecompiled); + void render(HumanoidModel* model, float scale, bool usecompiled); -// Add new bits to models - ModelPart * AddOrRetrievePart(SKIN_BOX *pBox); + // Add new bits to models + ModelPart* AddOrRetrievePart(SKIN_BOX* pBox); }; diff --git a/Minecraft.Client/Rendering/Models/LargeChestModel.cpp b/Minecraft.Client/Rendering/Models/LargeChestModel.cpp index 65a708509..f9a11082a 100644 --- a/Minecraft.Client/Rendering/Models/LargeChestModel.cpp +++ b/Minecraft.Client/Rendering/Models/LargeChestModel.cpp @@ -2,28 +2,28 @@ #include "LargeChestModel.h" #include "ModelPart.h" -LargeChestModel::LargeChestModel() -{ - lid = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); - lid->addBox(0.0f, -5.0f, -14.0f, 14+16, 5, 14, 0.0f); - lid->x = 1; - lid->y = 7; - lid->z = 15; +LargeChestModel::LargeChestModel() { + lid = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); + lid->addBox(0.0f, -5.0f, -14.0f, 14 + 16, 5, 14, 0.0f); + lid->x = 1; + lid->y = 7; + lid->z = 15; - lock = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); - lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); - lock->x = 8+8; - lock->y = 7; - lock->z = 15; + lock = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); + lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); + lock->x = 8 + 8; + lock->y = 7; + lock->z = 15; - bottom = ((new ModelPart(this, 0, 19)))->setTexSize(128, 64); - bottom->addBox(0.0f, 0.0f, 0.0f, 14+16, 10, 14, 0.0f); - bottom->x = 1; - bottom->y = 6; - bottom->z = 1; + bottom = ((new ModelPart(this, 0, 19)))->setTexSize(128, 64); + bottom->addBox(0.0f, 0.0f, 0.0f, 14 + 16, 10, 14, 0.0f); + bottom->x = 1; + bottom->y = 6; + bottom->z = 1; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - lid->compile(1.0f/16.0f); - lock->compile(1.0f/16.0f); - bottom->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + lid->compile(1.0f / 16.0f); + lock->compile(1.0f / 16.0f); + bottom->compile(1.0f / 16.0f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/LargeChestModel.h b/Minecraft.Client/Rendering/Models/LargeChestModel.h index a2dcb991c..ebe4724c8 100644 --- a/Minecraft.Client/Rendering/Models/LargeChestModel.h +++ b/Minecraft.Client/Rendering/Models/LargeChestModel.h @@ -2,8 +2,7 @@ #include "ChestModel.h" -class LargeChestModel : public ChestModel -{ +class LargeChestModel : public ChestModel { public: - LargeChestModel(); + LargeChestModel(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp b/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp index 3bb1e9d35..67d423b62 100644 --- a/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp +++ b/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp @@ -4,20 +4,14 @@ #include "ModelPart.h" #include "../../../Minecraft.World/Entities/Mobs/LavaSlime.h" - -LavaSlimeModel::LavaSlimeModel() -{ - for (int i = 0; i < BODYCUBESLENGTH; i++) - { +LavaSlimeModel::LavaSlimeModel() { + for (int i = 0; i < BODYCUBESLENGTH; i++) { int u = 0; int v = i; - if (i == 2) - { + if (i == 2) { u = 24; v = 10; - } - else if (i == 3) - { + } else if (i == 3) { u = 24; v = 19; } @@ -28,44 +22,39 @@ LavaSlimeModel::LavaSlimeModel() insideCube = new ModelPart(this, 0, 16); insideCube->addBox(-2, 16 + 2, -2, 4, 4, 4); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - insideCube->compile(1.0f/16.0f); - for( int i = 0; i < BODYCUBESLENGTH; i++ ) - { - bodyCubes[i]->compile(1.0f/16.0f); - } + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + insideCube->compile(1.0f / 16.0f); + for (int i = 0; i < BODYCUBESLENGTH; i++) { + bodyCubes[i]->compile(1.0f / 16.0f); + } } -int LavaSlimeModel::getModelVersion() -{ - return 5; -} +int LavaSlimeModel::getModelVersion() { return 5; } -void LavaSlimeModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr lavaSlime = std::dynamic_pointer_cast(mob); +void LavaSlimeModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + std::shared_ptr lavaSlime = + std::dynamic_pointer_cast(mob); - float slimeSquish = (lavaSlime->oSquish + (lavaSlime->squish - lavaSlime->oSquish) * a); - if (slimeSquish < 0) - { + float slimeSquish = + (lavaSlime->oSquish + (lavaSlime->squish - lavaSlime->oSquish) * a); + if (slimeSquish < 0) { slimeSquish = 0.0f; } - for (int i = 0; i < BODYCUBESLENGTH; i++) - { + for (int i = 0; i < BODYCUBESLENGTH; i++) { bodyCubes[i]->y = -(4 - i) * slimeSquish * 1.7f; } } -void LavaSlimeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - - insideCube->render(scale, usecompiled); - for (int i = 0; i < BODYCUBESLENGTH; i++) - { - bodyCubes[i]->render(scale, usecompiled); - } +void LavaSlimeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + insideCube->render(scale, usecompiled); + for (int i = 0; i < BODYCUBESLENGTH; i++) { + bodyCubes[i]->render(scale, usecompiled); + } } - diff --git a/Minecraft.Client/Rendering/Models/LavaSlimeModel.h b/Minecraft.Client/Rendering/Models/LavaSlimeModel.h index 4fcce75de..4f9f8ef07 100644 --- a/Minecraft.Client/Rendering/Models/LavaSlimeModel.h +++ b/Minecraft.Client/Rendering/Models/LavaSlimeModel.h @@ -1,15 +1,17 @@ #pragma once #include "Model.h" -class LavaSlimeModel : public Model -{ - static const int BODYCUBESLENGTH=8; - ModelPart *bodyCubes[BODYCUBESLENGTH]; - ModelPart *insideCube; +class LavaSlimeModel : public Model { + static const int BODYCUBESLENGTH = 8; + ModelPart* bodyCubes[BODYCUBESLENGTH]; + ModelPart* insideCube; public: - LavaSlimeModel(); - int getModelVersion(); - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + LavaSlimeModel(); + int getModelVersion(); + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/MinecartModel.cpp b/Minecraft.Client/Rendering/Models/MinecartModel.cpp index e7e659362..1feb9ab3b 100644 --- a/Minecraft.Client/Rendering/Models/MinecartModel.cpp +++ b/Minecraft.Client/Rendering/Models/MinecartModel.cpp @@ -2,8 +2,7 @@ #include "MinecartModel.h" #include "ModelPart.h" -MinecartModel::MinecartModel() : Model() -{ +MinecartModel::MinecartModel() : Model() { cubes[0] = new ModelPart(this, 0, 10); cubes[1] = new ModelPart(this, 0, 0); cubes[2] = new ModelPart(this, 0, 0); @@ -18,40 +17,41 @@ MinecartModel::MinecartModel() : Model() cubes[0]->addBox((float)(-w / 2), (float)(-h / 2), -1, w, h, 2, 0); cubes[0]->setPos(0, (float)(0 + yOff), 0); - - cubes[5]->addBox((float)(-w / 2 + 1), (float)(-h / 2 + 1), -1, w - 2, h - 2, 1, 0); + + cubes[5]->addBox((float)(-w / 2 + 1), (float)(-h / 2 + 1), -1, w - 2, h - 2, + 1, 0); cubes[5]->setPos(0, (float)(0 + yOff), 0); - + cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); - + cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); - + cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); - + cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); - + cubes[0]->xRot = PI / 2; cubes[1]->yRot = PI / 2 * 3; cubes[2]->yRot = PI / 2 * 1; cubes[3]->yRot = PI / 2 * 2; cubes[5]->xRot = -PI / 2; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - for (int i = 0; i < MINECART_LENGTH; i++) - { - cubes[i]->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + for (int i = 0; i < MINECART_LENGTH; i++) { + cubes[i]->compile(1.0f / 16.0f); } } -void MinecartModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void MinecartModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { cubes[5]->y = 4 - bob; - for (int i = 0; i < MINECART_LENGTH; i++) - { + for (int i = 0; i < MINECART_LENGTH; i++) { cubes[i]->render(scale, usecompiled); } } diff --git a/Minecraft.Client/Rendering/Models/MinecartModel.h b/Minecraft.Client/Rendering/Models/MinecartModel.h index 2cf6d0efb..13b7cf69e 100644 --- a/Minecraft.Client/Rendering/Models/MinecartModel.h +++ b/Minecraft.Client/Rendering/Models/MinecartModel.h @@ -1,13 +1,14 @@ #pragma once #include "Model.h" -class MinecartModel : public Model -{ +class MinecartModel : public Model { public: - static const int MINECART_LENGTH=6; + static const int MINECART_LENGTH = 6; - ModelPart *cubes[MINECART_LENGTH]; + ModelPart* cubes[MINECART_LENGTH]; MinecartModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/Model.cpp b/Minecraft.Client/Rendering/Models/Model.cpp index e4f278cbc..788738bd5 100644 --- a/Minecraft.Client/Rendering/Models/Model.cpp +++ b/Minecraft.Client/Rendering/Models/Model.cpp @@ -2,22 +2,18 @@ #include "../TexOffs.h" #include "Model.h" - -Model::Model() -{ - riding = false; - young=true; - texWidth=64; - texHeight=32; -} - -void Model::setMapTex(std::wstring id, int x, int y) -{ - mappedTexOffs[id]=new TexOffs(x, y); +Model::Model() { + riding = false; + young = true; + texWidth = 64; + texHeight = 32; } -TexOffs *Model::getMapTex(std::wstring id) -{ - // 4J-PB - assuming there will always be this one - return mappedTexOffs[id]; +void Model::setMapTex(std::wstring id, int x, int y) { + mappedTexOffs[id] = new TexOffs(x, y); +} + +TexOffs* Model::getMapTex(std::wstring id) { + // 4J-PB - assuming there will always be this one + return mappedTexOffs[id]; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/Model.h b/Minecraft.Client/Rendering/Models/Model.h index c80f9e8f6..f1cfc5f74 100644 --- a/Minecraft.Client/Rendering/Models/Model.h +++ b/Minecraft.Client/Rendering/Models/Model.h @@ -6,30 +6,35 @@ class Mob; class ModelPart; class TexOffs; - -class Model -{ +class Model { public: - float attackTime; + float attackTime; bool riding; - std::vector cubes; - bool young; - std::unordered_map mappedTexOffs; - int texWidth; - int texHeight; + std::vector cubes; + bool young; + std::unordered_map mappedTexOffs; + int texWidth; + int texHeight; - Model(); // 4J added - virtual ~Model(){} - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) {} - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0) {} - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a) {} - virtual ModelPart *getRandomCube(Random random) {return cubes.at(random.nextInt((int)cubes.size()));} - virtual ModelPart * AddOrRetrievePart(SKIN_BOX *pBox) { return NULL;} + Model(); // 4J added + virtual ~Model() {} + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) {} + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0) {} + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a) {} + virtual ModelPart* getRandomCube(Random random) { + return cubes.at(random.nextInt((int)cubes.size())); + } + virtual ModelPart* AddOrRetrievePart(SKIN_BOX* pBox) { return NULL; } - void setMapTex(std::wstring id, int x, int y); - TexOffs *getMapTex(std::wstring id); + void setMapTex(std::wstring id, int x, int y); + TexOffs* getMapTex(std::wstring id); protected: - float yHeadOffs; - float zHeadOffs; + float yHeadOffs; + float zHeadOffs; }; diff --git a/Minecraft.Client/Rendering/Models/ModelPart.cpp b/Minecraft.Client/Rendering/Models/ModelPart.cpp index 341a0cb57..833746e3b 100644 --- a/Minecraft.Client/Rendering/Models/ModelPart.cpp +++ b/Minecraft.Client/Rendering/Models/ModelPart.cpp @@ -5,318 +5,263 @@ const float ModelPart::RAD = (180.0f / PI); -void ModelPart::_init() -{ - xTexSize = 64.0f; - yTexSize = 32.0f; - list = 0; - compiled=false; - bMirror = false; - visible = true; - neverRender = false; - x=y=z = 0.0f; - xRot=yRot=zRot = 0.0f; +void ModelPart::_init() { + xTexSize = 64.0f; + yTexSize = 32.0f; + list = 0; + compiled = false; + bMirror = false; + visible = true; + neverRender = false; + x = y = z = 0.0f; + xRot = yRot = zRot = 0.0f; } -ModelPart::ModelPart() -{ - _init(); +ModelPart::ModelPart() { _init(); } + +ModelPart::ModelPart(Model* model, const std::wstring& id) { + construct(model, id); } -ModelPart::ModelPart(Model *model, const std::wstring& id) -{ - construct(model, id); +ModelPart::ModelPart(Model* model) { construct(model); } + +ModelPart::ModelPart(Model* model, int xTexOffs, int yTexOffs) { + construct(model, xTexOffs, yTexOffs); } -ModelPart::ModelPart(Model *model) -{ - construct(model); +void ModelPart::construct(Model* model, const std::wstring& id) { + _init(); + this->model = model; + model->cubes.push_back(this); + this->id = id; + setTexSize(model->texWidth, model->texHeight); } -ModelPart::ModelPart(Model *model, int xTexOffs, int yTexOffs) -{ - construct(model, xTexOffs, yTexOffs); +void ModelPart::construct(Model* model) { + _init(); + construct(model, L""); } - -void ModelPart::construct(Model *model, const std::wstring& id) -{ - _init(); - this->model = model; - model->cubes.push_back(this); - this->id = id; - setTexSize(model->texWidth, model->texHeight); +void ModelPart::construct(Model* model, int xTexOffs, int yTexOffs) { + _init(); + construct(model); + texOffs(xTexOffs, yTexOffs); } -void ModelPart::construct(Model *model) -{ - _init(); - construct(model, L""); +void ModelPart::addChild(ModelPart* child) { + // if (children == NULL) children = new ModelPartArray; + children.push_back(child); } -void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) -{ - _init(); - construct(model); - texOffs(xTexOffs, yTexOffs); +ModelPart* ModelPart::retrieveChild(SKIN_BOX* pBox) { + for (AUTO_VAR(it, children.begin()); it != children.end(); ++it) { + ModelPart* child = *it; + + for (AUTO_VAR(itcube, child->cubes.begin()); + itcube != child->cubes.end(); ++itcube) { + Cube* pCube = *itcube; + + if ((pCube->x0 == pBox->fX) && (pCube->y0 == pBox->fY) && + (pCube->z0 == pBox->fZ) && + (pCube->x1 == (pBox->fX + pBox->fW)) && + (pCube->y1 == (pBox->fY + pBox->fH)) && + (pCube->z1 == (pBox->fZ + pBox->fD))) { + return child; + break; + } + } + } + + return NULL; } - -void ModelPart::addChild(ModelPart *child) -{ - //if (children == NULL) children = new ModelPartArray; - children.push_back(child); +ModelPart* ModelPart::mirror() { + bMirror = !bMirror; + return this; } -ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) -{ - for(AUTO_VAR(it, children.begin()); it != children.end(); ++it) - { - ModelPart *child=*it; - - for(AUTO_VAR(itcube, child->cubes.begin()); itcube != child->cubes.end(); ++itcube) - { - Cube *pCube=*itcube; - - if((pCube->x0==pBox->fX) && - (pCube->y0==pBox->fY) && - (pCube->z0==pBox->fZ) && - (pCube->x1==(pBox->fX + pBox->fW)) && - (pCube->y1==(pBox->fY + pBox->fH)) && - (pCube->z1==(pBox->fZ + pBox->fD)) - ) - { - return child; - break; - } - } - } - - return NULL; +ModelPart* ModelPart::texOffs(int xTexOffs, int yTexOffs) { + this->xTexOffs = xTexOffs; + this->yTexOffs = yTexOffs; + return this; } -ModelPart *ModelPart::mirror() -{ - bMirror = !bMirror; - return this; +ModelPart* ModelPart::addBox(std::wstring id, float x0, float y0, float z0, + int w, int h, int d) { + id = this->id + L"." + id; + TexOffs* offs = model->getMapTex(id); + texOffs(offs->x, offs->y); + cubes.push_back((new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)) + ->setId(id)); + return this; } -ModelPart *ModelPart::texOffs(int xTexOffs, int yTexOffs) -{ - this->xTexOffs = xTexOffs; - this->yTexOffs = yTexOffs; - return this; +ModelPart* ModelPart::addBox(float x0, float y0, float z0, int w, int h, + int d) { + cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)); + return this; } -ModelPart *ModelPart::addBox(std::wstring id, float x0, float y0, float z0, int w, int h, int d) -{ - id = this->id + L"." + id; - TexOffs *offs = model->getMapTex(id); - texOffs(offs->x, offs->y); - cubes.push_back((new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0))->setId(id)); - return this; +void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, + int d, float g) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g, 63, true)); } -ModelPart *ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)); - return this; +ModelPart* ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, + int d, int faceMask) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0, faceMask)); + return this; } -void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g, 63, true)); +void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, + float g) { + cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g)); } -ModelPart *ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0, faceMask)); - return this; +void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, + int tex) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, (float)tex)); } -void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, float g) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g)); +void ModelPart::setPos(float x, float y, float z) { + this->x = x; + this->y = y; + this->z = z; } +void ModelPart::render(float scale, bool usecompiled, + bool bHideParentBodyPart) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); -void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, (float)tex)); + if (xRot != 0 || yRot != 0 || zRot != 0) { + glPushMatrix(); + glTranslatef(x * scale, y * scale, z * scale); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + + glPopMatrix(); + } else if (x != 0 || y != 0 || z != 0) { + glTranslatef(x * scale, y * scale, z * scale); + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + glTranslatef(-x * scale, -y * scale, -z * scale); + } else { + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + } } -void ModelPart::setPos(float x, float y, float z) -{ - this->x = x; - this->y = y; - this->z = z; +void ModelPart::renderRollable(float scale, bool usecompiled) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); + + glPushMatrix(); + glTranslatef(x * scale, y * scale, z * scale); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + glCallList(list); + glPopMatrix(); } -void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); +void ModelPart::translateTo(float scale) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); - if (xRot != 0 || yRot != 0 || zRot != 0) - { - glPushMatrix(); - glTranslatef(x * scale, y * scale, z * scale); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - - glPopMatrix(); - } - else if (x != 0 || y != 0 || z != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - glTranslatef(-x * scale, -y * scale, -z * scale); - } - else - { - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - } + if (xRot != 0 || yRot != 0 || zRot != 0) { + glTranslatef(x * scale, y * scale, z * scale); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + } else if (x != 0 || y != 0 || z != 0) { + glTranslatef(x * scale, y * scale, z * scale); + } else { + } } -void ModelPart::renderRollable(float scale, bool usecompiled) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); +void ModelPart::compile(float scale) { + list = MemoryTracker::genLists(1); - glPushMatrix(); - glTranslatef(x * scale, y * scale, z * scale); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - glCallList(list); - glPopMatrix(); + glNewList(list, GL_COMPILE); + // Set a few render states that aren't configured by default + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glDepthMask(true); + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes.at(i)->render(t, scale); + } + + glEndList(); + + compiled = true; } -void ModelPart::translateTo(float scale) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); - - if (xRot != 0 || yRot != 0 || zRot != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - } - else if (x != 0 || y != 0 || z != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - } - else - { - } +ModelPart* ModelPart::setTexSize(int xs, int ys) { + this->xTexSize = (float)xs; + this->yTexSize = (float)ys; + return this; } -void ModelPart::compile(float scale) -{ - list = MemoryTracker::genLists(1); - - glNewList(list, GL_COMPILE); - // Set a few render states that aren't configured by default - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - glDepthMask(true); - Tesselator *t = Tesselator::getInstance(); - - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes.at(i)->render(t, scale); - } - - glEndList(); - - compiled = true; -} - -ModelPart *ModelPart::setTexSize(int xs, int ys) -{ - this->xTexSize = (float)xs; - this->yTexSize = (float)ys; - return this; -} - -void ModelPart::mimic(ModelPart *o) -{ - x = o->x; - y = o->y; - z = o->z; - xRot = o->xRot; - yRot = o->yRot; - zRot = o->zRot; +void ModelPart::mimic(ModelPart* o) { + x = o->x; + y = o->y; + z = o->z; + xRot = o->xRot; + yRot = o->yRot; + zRot = o->zRot; } diff --git a/Minecraft.Client/Rendering/Models/ModelPart.h b/Minecraft.Client/Rendering/Models/ModelPart.h index 822ed1025..f412fc244 100644 --- a/Minecraft.Client/Rendering/Models/ModelPart.h +++ b/Minecraft.Client/Rendering/Models/ModelPart.h @@ -7,56 +7,62 @@ class Cube; -class ModelPart -{ +class ModelPart { public: float xTexSize; float yTexSize; - float x, y, z; - float xRot, yRot, zRot; - bool bMirror; - bool visible; - bool neverRender; - std::vector cubes; - std::vector children; + float x, y, z; + float xRot, yRot, zRot; + bool bMirror; + bool visible; + bool neverRender; + std::vector cubes; + std::vector children; static const float RAD; private: std::wstring id; - int xTexOffs, yTexOffs; + int xTexOffs, yTexOffs; boolean compiled; int list; - Model *model; - + Model* model; + public: - void _init(); // 4J added - ModelPart(); - ModelPart(Model *model, const std::wstring &id); - ModelPart(Model *model); - ModelPart(Model *model, int xTexOffs, int yTexOffs); + void _init(); // 4J added + ModelPart(); + ModelPart(Model* model, const std::wstring& id); + ModelPart(Model* model); + ModelPart(Model* model, int xTexOffs, int yTexOffs); - // MGH - had to add these for PS3, as calling constructors from others was only introduced in c++11 - https://en.wikipedia.org/wiki/C++11#Object_construction_improvement - void construct(Model *model, const std::wstring &id); - void construct(Model *model); - void construct(Model *model, int xTexOffs, int yTexOffs); + // MGH - had to add these for PS3, as calling constructors from others was + // only introduced in c++11 - + // https://en.wikipedia.org/wiki/C++11#Object_construction_improvement + void construct(Model* model, const std::wstring& id); + void construct(Model* model); + void construct(Model* model, int xTexOffs, int yTexOffs); - void addChild(ModelPart *child); - ModelPart * retrieveChild(SKIN_BOX *pBox); - ModelPart *mirror(); - ModelPart *texOffs(int xTexOffs, int yTexOffs); - ModelPart *addBox(std::wstring id, float x0, float y0, float z0, int w, int h, int d); - ModelPart *addBox(float x0, float y0, float z0, int w, int h, int d); - ModelPart *addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask); // 4J added + void addChild(ModelPart* child); + ModelPart* retrieveChild(SKIN_BOX* pBox); + ModelPart* mirror(); + ModelPart* texOffs(int xTexOffs, int yTexOffs); + ModelPart* addBox(std::wstring id, float x0, float y0, float z0, int w, + int h, int d); + ModelPart* addBox(float x0, float y0, float z0, int w, int h, int d); + ModelPart* addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, + int faceMask); // 4J added void addBox(float x0, float y0, float z0, int w, int h, int d, float g); - void addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g); // 4J - to flip the poly 3 uvs so the skin maps correctly + void addHumanoidBox( + float x0, float y0, float z0, int w, int h, int d, + float g); // 4J - to flip the poly 3 uvs so the skin maps correctly void addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex); void setPos(float x, float y, float z); - void render(float scale, bool usecompiled,bool bHideParentBodyPart=false); + void render(float scale, bool usecompiled, + bool bHideParentBodyPart = false); void renderRollable(float scale, bool usecompiled); void translateTo(float scale); - ModelPart *setTexSize(int xs, int ys); - void mimic(ModelPart *o); - void compile(float scale); - int getfU() {return xTexOffs;} - int getfV() {return yTexOffs;} - }; + ModelPart* setTexSize(int xs, int ys); + void mimic(ModelPart* o); + void compile(float scale); + int getfU() { return xTexOffs; } + int getfV() { return yTexOffs; } +}; diff --git a/Minecraft.Client/Rendering/Models/OcelotModel.cpp b/Minecraft.Client/Rendering/Models/OcelotModel.cpp index 03e0e5dac..ba239b4cc 100644 --- a/Minecraft.Client/Rendering/Models/OcelotModel.cpp +++ b/Minecraft.Client/Rendering/Models/OcelotModel.cpp @@ -21,228 +21,214 @@ const float OzelotModel::backLegZ = 14 + zo; const float OzelotModel::frontLegY = -2.2f + yo; const float OzelotModel::frontLegZ = 4.f + zo; -OzelotModel::OzelotModel() -{ - state = WALK_STATE; +OzelotModel::OzelotModel() { + state = WALK_STATE; - setMapTex(L"head.main", 0, 0); - setMapTex(L"head.nose", 0, 24); - setMapTex(L"head.ear1", 0, 10); - setMapTex(L"head.ear2", 6, 10); + setMapTex(L"head.main", 0, 0); + setMapTex(L"head.nose", 0, 24); + setMapTex(L"head.ear1", 0, 10); + setMapTex(L"head.ear2", 6, 10); - head = new ModelPart(this, L"head"); - head->addBox(L"main", -2.5f, -2, -3, 5, 4, 5); - head->addBox(L"nose", -1.5f, 0, -4, 3, 2, 2); - head->addBox(L"ear1", -2, -3, 0, 1, 1, 2); - head->addBox(L"ear2", 1, -3, 0, 1, 1, 2); - head->setPos(0 + xo, headWalkY, headWalkZ); + head = new ModelPart(this, L"head"); + head->addBox(L"main", -2.5f, -2, -3, 5, 4, 5); + head->addBox(L"nose", -1.5f, 0, -4, 3, 2, 2); + head->addBox(L"ear1", -2, -3, 0, 1, 1, 2); + head->addBox(L"ear2", 1, -3, 0, 1, 1, 2); + head->setPos(0 + xo, headWalkY, headWalkZ); - body = new ModelPart(this, 20, 0); - body->addBox(-2, 3, -8, 4, 16, 6, 0); - body->setPos(0 + xo, bodyWalkY, bodyWalkZ); + body = new ModelPart(this, 20, 0); + body->addBox(-2, 3, -8, 4, 16, 6, 0); + body->setPos(0 + xo, bodyWalkY, bodyWalkZ); - tail1 = new ModelPart(this, 0, 15); - tail1->addBox(-0.5f, 0, 0, 1, 8, 1); - tail1->xRot = 0.9f; - tail1->setPos(0 + xo, tail1WalkY, tail1WalkZ); + tail1 = new ModelPart(this, 0, 15); + tail1->addBox(-0.5f, 0, 0, 1, 8, 1); + tail1->xRot = 0.9f; + tail1->setPos(0 + xo, tail1WalkY, tail1WalkZ); - tail2 = new ModelPart(this, 4, 15); - tail2->addBox(-0.5f, 0, 0, 1, 8, 1); - tail2->setPos(0 + xo, tail2WalkY, tail2WalkZ); + tail2 = new ModelPart(this, 4, 15); + tail2->addBox(-0.5f, 0, 0, 1, 8, 1); + tail2->setPos(0 + xo, tail2WalkY, tail2WalkZ); - backLegL = new ModelPart(this, 8, 13); - backLegL->addBox(-1, 0, 1, 2, 6, 2); - backLegL->setPos(1.1f + xo, backLegY, backLegZ); + backLegL = new ModelPart(this, 8, 13); + backLegL->addBox(-1, 0, 1, 2, 6, 2); + backLegL->setPos(1.1f + xo, backLegY, backLegZ); - backLegR = new ModelPart(this, 8, 13); - backLegR->addBox(-1, 0, 1, 2, 6, 2); - backLegR->setPos(-1.1f + xo, backLegY, backLegZ); + backLegR = new ModelPart(this, 8, 13); + backLegR->addBox(-1, 0, 1, 2, 6, 2); + backLegR->setPos(-1.1f + xo, backLegY, backLegZ); - frontLegL = new ModelPart(this, 40, 0); - frontLegL->addBox(-1, 0, 0, 2, 10, 2); - frontLegL->setPos(1.2f + xo, frontLegY, frontLegZ); + frontLegL = new ModelPart(this, 40, 0); + frontLegL->addBox(-1, 0, 0, 2, 10, 2); + frontLegL->setPos(1.2f + xo, frontLegY, frontLegZ); - frontLegR = new ModelPart(this, 40, 0); - frontLegR->addBox(-1, 0, 0, 2, 10, 2); - frontLegR->setPos(-1.2f + xo, frontLegY, frontLegZ); + frontLegR = new ModelPart(this, 40, 0); + frontLegR->addBox(-1, 0, 0, 2, 10, 2); + frontLegR->setPos(-1.2f + xo, frontLegY, frontLegZ); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - tail1->compile(1.0f/16.0f); - tail2->compile(1.0f/16.0f); - backLegL->compile(1.0f/16.0f); - backLegR->compile(1.0f/16.0f); - backLegL->compile(1.0f/16.0f); - backLegR->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + tail1->compile(1.0f / 16.0f); + tail2->compile(1.0f / 16.0f); + backLegL->compile(1.0f / 16.0f); + backLegR->compile(1.0f / 16.0f); + backLegL->compile(1.0f / 16.0f); + backLegR->compile(1.0f / 16.0f); } -void OzelotModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); - glTranslatef(0, 10 * scale, 4 * scale); - head->render(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); - tail1->render(scale, usecompiled); - tail2->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - tail1->render(scale, usecompiled); - tail2->render(scale, usecompiled); - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); - } +void OzelotModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + if (young) { + float ss = 2.0f; + glPushMatrix(); + glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); + glTranslatef(0, 10 * scale, 4 * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); + tail1->render(scale, usecompiled); + tail2->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + tail1->render(scale, usecompiled); + tail2->render(scale, usecompiled); + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); + } } -void OzelotModel::render(OzelotModel *model, float scale, bool usecompiled) -{ - head->yRot = model->head->yRot; - head->xRot = model->head->xRot; - head->y = model->head->y; - head->x = model->head->x; - body->yRot = model->body->yRot; - body->xRot = model->body->xRot; +void OzelotModel::render(OzelotModel* model, float scale, bool usecompiled) { + head->yRot = model->head->yRot; + head->xRot = model->head->xRot; + head->y = model->head->y; + head->x = model->head->x; + body->yRot = model->body->yRot; + body->xRot = model->body->xRot; - tail1->yRot = model->body->yRot; - tail1->y = model->body->y; - tail1->x = model->body->x; - tail1->render(scale, usecompiled); + tail1->yRot = model->body->yRot; + tail1->y = model->body->y; + tail1->x = model->body->x; + tail1->render(scale, usecompiled); - tail2->yRot = model->body->yRot; - tail2->y = model->body->y; - tail2->x = model->body->x; - tail2->render(scale, usecompiled); + tail2->yRot = model->body->yRot; + tail2->y = model->body->y; + tail2->x = model->body->x; + tail2->render(scale, usecompiled); - backLegL->xRot = model->backLegL->xRot; - backLegR->xRot = model->backLegR->xRot; - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); + backLegL->xRot = model->backLegL->xRot; + backLegR->xRot = model->backLegR->xRot; + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); - frontLegL->xRot = model->frontLegL->xRot; - frontLegR->xRot = model->frontLegR->xRot; - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); + frontLegL->xRot = model->frontLegL->xRot; + frontLegR->xRot = model->frontLegR->xRot; + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); - head->render(scale, usecompiled); - body->render(scale, usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); } -void OzelotModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); +void OzelotModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); - if (state == SITTING_STATE) - { + if (state == SITTING_STATE) { + } else { + body->xRot = 90 / (float)(180 / PI); + if (state == SPRINT_STATE) { + backLegL->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; + backLegR->xRot = ((float)Mth::cos(time * 0.6662f + 0.3f) * 1.f) * r; + frontLegL->xRot = + ((float)Mth::cos(time * 0.6662f + PI + 0.3f) * 1.f) * r; + frontLegR->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + tail2->xRot = 0.55f * PI + 0.1f * PI * Mth::cos(time) * r; + } else { + backLegL->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; + backLegR->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + frontLegL->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + frontLegR->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; - } - else - { - body->xRot = 90 / (float) (180 / PI); - if (state == SPRINT_STATE) - { - backLegL->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - backLegR->xRot = ((float) Mth::cos(time * 0.6662f + 0.3f) * 1.f) * r; - frontLegL->xRot = ((float) Mth::cos(time * 0.6662f + PI + 0.3f) * 1.f) * r; - frontLegR->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - tail2->xRot = 0.55f * PI + 0.1f * PI * Mth::cos(time) * r; - } - else - { - backLegL->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - backLegR->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - frontLegL->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - frontLegR->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - - if (state == WALK_STATE) tail2->xRot = 0.55f * PI + 0.25f * PI * Mth::cos(time) * r; - else tail2->xRot = 0.55f * PI + 0.15f * PI * Mth::cos(time) * r; - } - } + if (state == WALK_STATE) + tail2->xRot = 0.55f * PI + 0.25f * PI * Mth::cos(time) * r; + else + tail2->xRot = 0.55f * PI + 0.15f * PI * Mth::cos(time) * r; + } + } } -void OzelotModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr ozelot = std::dynamic_pointer_cast(mob); +void OzelotModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + std::shared_ptr ozelot = std::dynamic_pointer_cast(mob); - body->y = bodyWalkY; - body->z = bodyWalkZ; - head->y = headWalkY; - head->z = headWalkZ; - tail1->y = tail1WalkY; - tail1->z = tail1WalkZ; - tail2->y = tail2WalkY; - tail2->z = tail2WalkZ; - frontLegL->y = frontLegR->y = frontLegY; - frontLegL->z = frontLegR->z = frontLegZ; - backLegL->y = backLegR->y = backLegY; - backLegL->z = backLegR->z = backLegZ; - tail1->xRot = 0.9f; + body->y = bodyWalkY; + body->z = bodyWalkZ; + head->y = headWalkY; + head->z = headWalkZ; + tail1->y = tail1WalkY; + tail1->z = tail1WalkZ; + tail2->y = tail2WalkY; + tail2->z = tail2WalkZ; + frontLegL->y = frontLegR->y = frontLegY; + frontLegL->z = frontLegR->z = frontLegZ; + backLegL->y = backLegR->y = backLegY; + backLegL->z = backLegR->z = backLegZ; + tail1->xRot = 0.9f; - if (ozelot->isSneaking()) - { - body->y += 1; - head->y += 2; - tail1->y += 1; - tail2->y += -4; - tail2->z += 2; - tail1->xRot = 0.5f * PI; - tail2->xRot = 0.5f * PI; - state = SNEAK_STATE; - } - else if (ozelot->isSprinting()) - { - tail2->y = tail1->y; - tail2->z += 2; - tail1->xRot = 0.5f * PI; - tail2->xRot = 0.5f * PI; - state = SPRINT_STATE; - } - else if (ozelot->isSitting()) - { - body->xRot = 45 / (float) (180 / PI); - body->y += -4; - body->z += 5; - head->y += -3.3f; - head->z += 1; + if (ozelot->isSneaking()) { + body->y += 1; + head->y += 2; + tail1->y += 1; + tail2->y += -4; + tail2->z += 2; + tail1->xRot = 0.5f * PI; + tail2->xRot = 0.5f * PI; + state = SNEAK_STATE; + } else if (ozelot->isSprinting()) { + tail2->y = tail1->y; + tail2->z += 2; + tail1->xRot = 0.5f * PI; + tail2->xRot = 0.5f * PI; + state = SPRINT_STATE; + } else if (ozelot->isSitting()) { + body->xRot = 45 / (float)(180 / PI); + body->y += -4; + body->z += 5; + head->y += -3.3f; + head->z += 1; - tail1->y += 8; - tail1->z += -2; - tail2->y += 2; - tail2->z += -0.8f; - tail1->xRot = PI * 0.55f; - tail2->xRot = PI * 0.85f; + tail1->y += 8; + tail1->z += -2; + tail2->y += 2; + tail2->z += -0.8f; + tail1->xRot = PI * 0.55f; + tail2->xRot = PI * 0.85f; - frontLegL->xRot = frontLegR->xRot = -PI * 0.05f; - frontLegL->y = frontLegR->y = frontLegY + 2; - frontLegL->z = frontLegR->z = -7; + frontLegL->xRot = frontLegR->xRot = -PI * 0.05f; + frontLegL->y = frontLegR->y = frontLegY + 2; + frontLegL->z = frontLegR->z = -7; - backLegL->xRot = backLegR->xRot = -PI * 0.5f; - backLegL->y = backLegR->y = backLegY + 3; - backLegL->z = backLegR->z = backLegZ - 4; - state = SITTING_STATE; - } - else - { - state = WALK_STATE; - } + backLegL->xRot = backLegR->xRot = -PI * 0.5f; + backLegL->y = backLegR->y = backLegY + 3; + backLegL->z = backLegR->z = backLegZ - 4; + state = SITTING_STATE; + } else { + state = WALK_STATE; + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/OcelotModel.h b/Minecraft.Client/Rendering/Models/OcelotModel.h index cdccc8fe8..c34b8e0d6 100644 --- a/Minecraft.Client/Rendering/Models/OcelotModel.h +++ b/Minecraft.Client/Rendering/Models/OcelotModel.h @@ -2,42 +2,44 @@ #include "Model.h" -class OzelotModel : public Model -{ +class OzelotModel : public Model { private: - ModelPart *backLegL, *backLegR; - ModelPart *frontLegL, *frontLegR; - ModelPart *tail1, *tail2, *head, *body; + ModelPart *backLegL, *backLegR; + ModelPart *frontLegL, *frontLegR; + ModelPart *tail1, *tail2, *head, *body; - static const int SNEAK_STATE = 0; - static const int WALK_STATE = 1; - static const int SPRINT_STATE = 2; - static const int SITTING_STATE = 3; + static const int SNEAK_STATE = 0; + static const int WALK_STATE = 1; + static const int SPRINT_STATE = 2; + static const int SITTING_STATE = 3; - int state; + int state; - static const float xo; - static const float yo; - static const float zo; + static const float xo; + static const float yo; + static const float zo; - static const float headWalkY; - static const float headWalkZ; - static const float bodyWalkY; - static const float bodyWalkZ; - static const float tail1WalkY; - static const float tail1WalkZ; - static const float tail2WalkY; - static const float tail2WalkZ; - static const float backLegY; - static const float backLegZ; - static const float frontLegY; - static const float frontLegZ ; + static const float headWalkY; + static const float headWalkZ; + static const float bodyWalkY; + static const float bodyWalkZ; + static const float tail1WalkY; + static const float tail1WalkZ; + static const float tail2WalkY; + static const float tail2WalkZ; + static const float backLegY; + static const float backLegZ; + static const float frontLegY; + static const float frontLegZ; public: - OzelotModel(); + OzelotModel(); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void render(OzelotModel *model, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void render(OzelotModel* model, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/PigModel.cpp b/Minecraft.Client/Rendering/Models/PigModel.cpp index f5facc2f6..eb5308133 100644 --- a/Minecraft.Client/Rendering/Models/PigModel.cpp +++ b/Minecraft.Client/Rendering/Models/PigModel.cpp @@ -2,19 +2,16 @@ #include "PigModel.h" #include "ModelPart.h" -PigModel::PigModel() : QuadrupedModel(6, 0) -{ - head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, 0.0f); - yHeadOffs = 4; +PigModel::PigModel() : QuadrupedModel(6, 0) { + head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, 0.0f); + yHeadOffs = 4; - head->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); } -PigModel::PigModel(float grow) : QuadrupedModel(6, grow) -{ - head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, grow); - yHeadOffs = 4; +PigModel::PigModel(float grow) : QuadrupedModel(6, grow) { + head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, grow); + yHeadOffs = 4; - head->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); } - diff --git a/Minecraft.Client/Rendering/Models/PigModel.h b/Minecraft.Client/Rendering/Models/PigModel.h index c443115d9..1f5998a52 100644 --- a/Minecraft.Client/Rendering/Models/PigModel.h +++ b/Minecraft.Client/Rendering/Models/PigModel.h @@ -1,10 +1,8 @@ #pragma once #include "QuadrupedModel.h" -class PigModel : public QuadrupedModel -{ +class PigModel : public QuadrupedModel { public: - - PigModel(); - PigModel(float grow); + PigModel(); + PigModel(float grow); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp b/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp index ff9354681..f5685c209 100644 --- a/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp +++ b/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp @@ -3,79 +3,78 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -QuadrupedModel::QuadrupedModel(int legSize, float g) : Model() -{ - yHeadOffs = 8; - zHeadOffs = 4; +QuadrupedModel::QuadrupedModel(int legSize, float g) : Model() { + yHeadOffs = 8; + zHeadOffs = 4; - head = new ModelPart(this, 0, 0); - head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(12 + 6 - legSize), -6); + head = new ModelPart(this, 0, 0); + head->addBox(-4, -4, -8, 8, 8, 8, g); // Head + head->setPos(0, (float)(12 + 6 - legSize), -6); - body = new ModelPart(this, 28, 8); - body->addBox(-5, -10, -7, 10, 16, 8, g); // Body - body->setPos(0, (float)(11 + 6 - legSize), 2); + body = new ModelPart(this, 28, 8); + body->addBox(-5, -10, -7, 10, 16, 8, g); // Body + body->setPos(0, (float)(11 + 6 - legSize), 2); - leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg0 - leg0->setPos(-3, (float)(18 + 6 - legSize), 7); + leg0 = new ModelPart(this, 0, 16); + leg0->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg0 + leg0->setPos(-3, (float)(18 + 6 - legSize), 7); - leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg1 - leg1->setPos(3, (float)(18 + 6 - legSize), 7); + leg1 = new ModelPart(this, 0, 16); + leg1->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg1 + leg1->setPos(3, (float)(18 + 6 - legSize), 7); - leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg2 - leg2->setPos(-3, (float)(18 + 6 - legSize), -5); + leg2 = new ModelPart(this, 0, 16); + leg2->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg2 + leg2->setPos(-3, (float)(18 + 6 - legSize), -5); - leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg3 - leg3->setPos(3, (float)(18 + 6 - legSize), -5); + leg3 = new ModelPart(this, 0, 16); + leg3->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg3 + leg3->setPos(3, (float)(18 + 6 - legSize), -5); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -void QuadrupedModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void QuadrupedModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glTranslatef(0, yHeadOffs * scale, zHeadOffs * scale); - head->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - } + if (young) { + float ss = 2.0f; + glPushMatrix(); + glTranslatef(0, yHeadOffs * scale, zHeadOffs * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + } } -void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - float rad = (float) (180 / PI); +void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + float rad = (float)(180 / PI); head->xRot = xRot / rad; head->yRot = yRot / rad; body->xRot = 90 / rad; @@ -86,8 +85,8 @@ void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, float leg3->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; } -void QuadrupedModel::render(QuadrupedModel *model, float scale, bool usecompiled) -{ +void QuadrupedModel::render(QuadrupedModel* model, float scale, + bool usecompiled) { head->yRot = model->head->yRot; head->xRot = model->head->xRot; @@ -102,30 +101,27 @@ void QuadrupedModel::render(QuadrupedModel *model, float scale, bool usecompiled leg2->xRot = model->leg2->xRot; leg3->xRot = model->leg3->xRot; - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glTranslatef(0, 8 * scale, 4 * scale); - head->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - } + if (young) { + float ss = 2.0f; + glPushMatrix(); + glTranslatef(0, 8 * scale, 4 * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + } } diff --git a/Minecraft.Client/Rendering/Models/QuadrupedModel.h b/Minecraft.Client/Rendering/Models/QuadrupedModel.h index d1c24de78..f7dcdc0d9 100644 --- a/Minecraft.Client/Rendering/Models/QuadrupedModel.h +++ b/Minecraft.Client/Rendering/Models/QuadrupedModel.h @@ -1,13 +1,16 @@ #pragma once #include "Model.h" -class QuadrupedModel : public Model -{ +class QuadrupedModel : public Model { public: - ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; + ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; - QuadrupedModel(int legSize, float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void render(QuadrupedModel *model, float scale, bool usecompiled); + QuadrupedModel(int legSize, float g); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + void render(QuadrupedModel* model, float scale, bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepFurModel.cpp b/Minecraft.Client/Rendering/Models/SheepFurModel.cpp index c12ad5fdc..de078c74e 100644 --- a/Minecraft.Client/Rendering/Models/SheepFurModel.cpp +++ b/Minecraft.Client/Rendering/Models/SheepFurModel.cpp @@ -3,55 +3,56 @@ #include "SheepFurModel.h" #include "ModelPart.h" -SheepFurModel::SheepFurModel() : QuadrupedModel(12, 0) -{ - headXRot = 0.0f; +SheepFurModel::SheepFurModel() : QuadrupedModel(12, 0) { + headXRot = 0.0f; head = new ModelPart(this, 0, 0); - head->addBox(-3, -4, -4, 6, 6, 6, 0.6f); // Head + head->addBox(-3, -4, -4, 6, 6, 6, 0.6f); // Head head->setPos(0, 12 - 6, -8); body = new ModelPart(this, 28, 8); - body->addBox(-4, -10, -7, 8, 16, 6, 1.75f); // Body + body->addBox(-4, -10, -7, 8, 16, 6, 1.75f); // Body body->setPos(0, 11 + 6 - 12, 2); float g = 0.5f; leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 + leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 leg0->setPos(-3, 18 + 6 - 12, 7); leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 + leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 leg1->setPos(3, 18 + 6 - 12, 7); leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 + leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 leg2->setPos(-3, 18 + 6 - 12, -5); leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 + leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 leg3->setPos(3, 18 + 6 - 12, -5); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -void SheepFurModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - QuadrupedModel::prepareMobModel(mob, time, r, a); +void SheepFurModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + QuadrupedModel::prepareMobModel(mob, time, r, a); - std::shared_ptr sheep = std::dynamic_pointer_cast(mob); - head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; - headXRot = sheep->getHeadEatAngleScale(a); + std::shared_ptr sheep = std::dynamic_pointer_cast(mob); + head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; + headXRot = sheep->getHeadEatAngleScale(a); } -void SheepFurModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = headXRot; +void SheepFurModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); + head->xRot = headXRot; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepFurModel.h b/Minecraft.Client/Rendering/Models/SheepFurModel.h index 65bb913ed..3b43feafb 100644 --- a/Minecraft.Client/Rendering/Models/SheepFurModel.h +++ b/Minecraft.Client/Rendering/Models/SheepFurModel.h @@ -1,13 +1,16 @@ #pragma once #include "QuadrupedModel.h" -class SheepFurModel : public QuadrupedModel -{ +class SheepFurModel : public QuadrupedModel { private: - float headXRot; -public: - SheepFurModel(); + float headXRot; - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); +public: + SheepFurModel(); + + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepModel.cpp b/Minecraft.Client/Rendering/Models/SheepModel.cpp index 40ded26ff..8599efe9c 100644 --- a/Minecraft.Client/Rendering/Models/SheepModel.cpp +++ b/Minecraft.Client/Rendering/Models/SheepModel.cpp @@ -3,35 +3,36 @@ #include "SheepModel.h" #include "ModelPart.h" -SheepModel::SheepModel() : QuadrupedModel(12, 0) -{ - headXRot = 0.0f; +SheepModel::SheepModel() : QuadrupedModel(12, 0) { + headXRot = 0.0f; head = new ModelPart(this, 0, 0); - head->addBox(-3, -4, -6, 6, 6, 8, 0); // Head - head->setPos(0, 12-6, -8); - + head->addBox(-3, -4, -6, 6, 6, 8, 0); // Head + head->setPos(0, 12 - 6, -8); + body = new ModelPart(this, 28, 8); - body->addBox(-4, -10, -7, 8, 16, 6, 0); // Body - body->setPos(0, 11+6-12, 2); + body->addBox(-4, -10, -7, 8, 16, 6, 0); // Body + body->setPos(0, 11 + 6 - 12, 2); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); } -void SheepModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - QuadrupedModel::prepareMobModel(mob, time, r, a); +void SheepModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + QuadrupedModel::prepareMobModel(mob, time, r, a); - std::shared_ptr sheep = std::dynamic_pointer_cast(mob); - head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; - headXRot = sheep->getHeadEatAngleScale(a); + std::shared_ptr sheep = std::dynamic_pointer_cast(mob); + head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; + headXRot = sheep->getHeadEatAngleScale(a); } -void SheepModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); +void SheepModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = headXRot; + head->xRot = headXRot; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepModel.h b/Minecraft.Client/Rendering/Models/SheepModel.h index 78c3b7c8b..6fbfcebc2 100644 --- a/Minecraft.Client/Rendering/Models/SheepModel.h +++ b/Minecraft.Client/Rendering/Models/SheepModel.h @@ -1,13 +1,16 @@ #pragma once #include "QuadrupedModel.h" -class SheepModel : public QuadrupedModel -{ +class SheepModel : public QuadrupedModel { private: - float headXRot; -public: - SheepModel(); + float headXRot; - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); +public: + SheepModel(); + + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SignModel.cpp b/Minecraft.Client/Rendering/Models/SignModel.cpp index 1035d32fd..4b72bbbd0 100644 --- a/Minecraft.Client/Rendering/Models/SignModel.cpp +++ b/Minecraft.Client/Rendering/Models/SignModel.cpp @@ -2,21 +2,20 @@ #include "SignModel.h" #include "ModelPart.h" -SignModel::SignModel() -{ +SignModel::SignModel() { cube = new ModelPart(this, 0, 0); cube->addBox(-12, -14, -1, 24, 12, 2, 0); - + cube2 = new ModelPart(this, 0, 14); cube2->addBox(-1, -2, -1, 2, 14, 2, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - cube->compile(1.0f/16.0f); - cube2->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + cube->compile(1.0f / 16.0f); + cube2->compile(1.0f / 16.0f); } -void SignModel::render(bool usecompiled) -{ - cube->render(1/16.0f,usecompiled); - cube2->render(1/16.0f,usecompiled); +void SignModel::render(bool usecompiled) { + cube->render(1 / 16.0f, usecompiled); + cube2->render(1 / 16.0f, usecompiled); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SignModel.h b/Minecraft.Client/Rendering/Models/SignModel.h index 6de4ce131..3c2d26d22 100644 --- a/Minecraft.Client/Rendering/Models/SignModel.h +++ b/Minecraft.Client/Rendering/Models/SignModel.h @@ -4,13 +4,12 @@ class Cube; -class SignModel : public Model -{ +class SignModel : public Model { public: - using Model::render; - ModelPart *cube; - ModelPart *cube2; - + using Model::render; + ModelPart* cube; + ModelPart* cube2; + SignModel(); void render(bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/SilverfishModel.cpp b/Minecraft.Client/Rendering/Models/SilverfishModel.cpp index 6e03ee6dd..6ddc1187d 100644 --- a/Minecraft.Client/Rendering/Models/SilverfishModel.cpp +++ b/Minecraft.Client/Rendering/Models/SilverfishModel.cpp @@ -5,108 +5,79 @@ #include "ModelPart.h" const int SilverfishModel::BODY_SIZES[BODY_COUNT][3] = { - { - 3, 2, 2 - }, { - 4, 3, 2 - }, { - 6, 4, 3 - }, { - 3, 3, 3 - }, { - 2, 2, 3 - }, { - 2, 1, 2 - }, { - 1, 1, 2 - }, + {3, 2, 2}, {4, 3, 2}, {6, 4, 3}, {3, 3, 3}, {2, 2, 3}, {2, 1, 2}, {1, 1, 2}, }; const int SilverfishModel::BODY_TEXS[BODY_COUNT][2] = { - { - 0, 0 - }, { - 0, 4 - }, { - 0, 9 - }, { - 0, 16 - }, { - 0, 22 - }, { - 11, 0 - }, { - 13, 4 - }, + {0, 0}, {0, 4}, {0, 9}, {0, 16}, {0, 22}, {11, 0}, {13, 4}, }; -SilverfishModel::SilverfishModel() -{ - bodyParts = ModelPartArray(BODY_COUNT); - float placement = -3.5f; - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i] = new ModelPart(this, BODY_TEXS[i][0], BODY_TEXS[i][1]); - bodyParts[i]->addBox(BODY_SIZES[i][0] * -0.5f, 0, BODY_SIZES[i][2] * -0.5f, BODY_SIZES[i][0], BODY_SIZES[i][1], BODY_SIZES[i][2]); - bodyParts[i]->setPos(0.0f, 24.0f - (float)BODY_SIZES[i][1], placement); - zPlacement[i] = placement; - if (i < bodyParts.length - 1) - { - placement += (BODY_SIZES[i][2] + BODY_SIZES[i + 1][2]) * .5f; - } - } +SilverfishModel::SilverfishModel() { + bodyParts = ModelPartArray(BODY_COUNT); + float placement = -3.5f; + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i] = new ModelPart(this, BODY_TEXS[i][0], BODY_TEXS[i][1]); + bodyParts[i]->addBox(BODY_SIZES[i][0] * -0.5f, 0, + BODY_SIZES[i][2] * -0.5f, BODY_SIZES[i][0], + BODY_SIZES[i][1], BODY_SIZES[i][2]); + bodyParts[i]->setPos(0.0f, 24.0f - (float)BODY_SIZES[i][1], placement); + zPlacement[i] = placement; + if (i < bodyParts.length - 1) { + placement += (BODY_SIZES[i][2] + BODY_SIZES[i + 1][2]) * .5f; + } + } - bodyLayers = ModelPartArray(3); - bodyLayers[0] = new ModelPart(this, 20, 0); - bodyLayers[0]->addBox(-5, 0, BODY_SIZES[2][2] * -0.5f, 10, 8, BODY_SIZES[2][2]); - bodyLayers[0]->setPos(0, 24 - 8, zPlacement[2]); - bodyLayers[1] = new ModelPart(this, 20, 11); - bodyLayers[1]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 4, BODY_SIZES[4][2]); - bodyLayers[1]->setPos(0, 24 - 4, zPlacement[4]); - bodyLayers[2] = new ModelPart(this, 20, 18); - bodyLayers[2]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 5, BODY_SIZES[1][2]); - bodyLayers[2]->setPos(0, 24 - 5, zPlacement[1]); + bodyLayers = ModelPartArray(3); + bodyLayers[0] = new ModelPart(this, 20, 0); + bodyLayers[0]->addBox(-5, 0, BODY_SIZES[2][2] * -0.5f, 10, 8, + BODY_SIZES[2][2]); + bodyLayers[0]->setPos(0, 24 - 8, zPlacement[2]); + bodyLayers[1] = new ModelPart(this, 20, 11); + bodyLayers[1]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 4, + BODY_SIZES[4][2]); + bodyLayers[1]->setPos(0, 24 - 4, zPlacement[4]); + bodyLayers[2] = new ModelPart(this, 20, 18); + bodyLayers[2]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 5, + BODY_SIZES[1][2]); + bodyLayers[2]->setPos(0, 24 - 5, zPlacement[1]); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->compile(1.0f/16.0f); - } - bodyLayers[0]->compile(1.0f/16.0f); - bodyLayers[1]->compile(1.0f/16.0f); - bodyLayers[2]->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->compile(1.0f / 16.0f); + } + bodyLayers[0]->compile(1.0f / 16.0f); + bodyLayers[1]->compile(1.0f / 16.0f); + bodyLayers[2]->compile(1.0f / 16.0f); } -int SilverfishModel::modelVersion() -{ - return 38; +int SilverfishModel::modelVersion() { return 38; } + +void SilverfishModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->render(scale, usecompiled); + } + for (unsigned int i = 0; i < bodyLayers.length; i++) { + bodyLayers[i]->render(scale, usecompiled); + } } -void SilverfishModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->render(scale, usecompiled); - } - for (unsigned int i = 0; i < bodyLayers.length; i++) - { - bodyLayers[i]->render(scale, usecompiled); - } -} - -void SilverfishModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * (1 + abs((int)i - 2)); - bodyParts[i]->x = Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs((int)i - 2); - } - bodyLayers[0]->yRot = bodyParts[2]->yRot; - bodyLayers[1]->yRot = bodyParts[4]->yRot; - bodyLayers[1]->x = bodyParts[4]->x; - bodyLayers[2]->yRot = bodyParts[1]->yRot; - bodyLayers[2]->x = bodyParts[1]->x; +void SilverfishModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * + (1 + abs((int)i - 2)); + bodyParts[i]->x = + Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs((int)i - 2); + } + bodyLayers[0]->yRot = bodyParts[2]->yRot; + bodyLayers[1]->yRot = bodyParts[4]->yRot; + bodyLayers[1]->x = bodyParts[4]->x; + bodyLayers[2]->yRot = bodyParts[1]->yRot; + bodyLayers[2]->x = bodyParts[1]->x; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SilverfishModel.h b/Minecraft.Client/Rendering/Models/SilverfishModel.h index 4ce0e16ee..9db32edd5 100644 --- a/Minecraft.Client/Rendering/Models/SilverfishModel.h +++ b/Minecraft.Client/Rendering/Models/SilverfishModel.h @@ -2,25 +2,26 @@ #include "Model.h" -class SilverfishModel : public Model -{ +class SilverfishModel : public Model { +private: + static const int BODY_COUNT = 7; private: - static const int BODY_COUNT = 7; + ModelPartArray bodyParts; + ModelPartArray bodyLayers; + float zPlacement[BODY_COUNT]; -private: - ModelPartArray bodyParts; - ModelPartArray bodyLayers; - float zPlacement[BODY_COUNT]; + static const int BODY_SIZES[BODY_COUNT][3]; - static const int BODY_SIZES[BODY_COUNT][3]; - - static const int BODY_TEXS[BODY_COUNT][2]; + static const int BODY_TEXS[BODY_COUNT][2]; public: - SilverfishModel(); + SilverfishModel(); - int modelVersion(); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + int modelVersion(); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp index 6f472a0c2..4b84b1e88 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp +++ b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp @@ -2,42 +2,42 @@ #include "ModelPart.h" #include "SkeletonHeadModel.h" -void SkeletonHeadModel::_init(int u, int v, int tw, int th) -{ - texWidth = tw; - texHeight = th; - head = new ModelPart(this, u, v); +void SkeletonHeadModel::_init(int u, int v, int tw, int th) { + texWidth = tw; + texHeight = th; + head = new ModelPart(this, u, v); - // 4J Stu - Set "g" param to 0.1 to fix z-fighting issues (hair has this set to 0.5, so need to be less that that) - // Fix for #101501 - TU12: Content: Art: Z-Fighting occurs on the bottom side of a character's head when a Mob Head is equipped. - head->addBox(-4, -8, -4, 8, 8, 8, 0.1); // Head - head->setPos(0, 0, 0); + // 4J Stu - Set "g" param to 0.1 to fix z-fighting issues (hair has this set + // to 0.5, so need to be less that that) Fix for #101501 - TU12: Content: + // Art: Z-Fighting occurs on the bottom side of a character's head when a + // Mob Head is equipped. + head->addBox(-4, -8, -4, 8, 8, 8, 0.1); // Head + head->setPos(0, 0, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); } -SkeletonHeadModel::SkeletonHeadModel() -{ - _init(0, 35, 64, 64); +SkeletonHeadModel::SkeletonHeadModel() { _init(0, 35, 64, 64); } + +SkeletonHeadModel::SkeletonHeadModel(int u, int v, int tw, int th) { + _init(u, v, tw, th); } -SkeletonHeadModel::SkeletonHeadModel(int u, int v, int tw, int th) -{ - _init(u,v,tw,th); +void SkeletonHeadModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + + head->render(scale, usecompiled); } -void SkeletonHeadModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void SkeletonHeadModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + Model::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - head->render(scale,usecompiled); -} - -void SkeletonHeadModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - Model::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - - head->yRot = yRot / (180 / PI); - head->xRot = xRot / (180 / PI); + head->yRot = yRot / (180 / PI); + head->xRot = xRot / (180 / PI); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h index aa045571e..b276c0ce5 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h +++ b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h @@ -2,18 +2,19 @@ #include "Model.h" -class SkeletonHeadModel : public Model -{ +class SkeletonHeadModel : public Model { public: - ModelPart *head; + ModelPart* head; private: - void _init(int u, int v, int tw, int th); + void _init(int u, int v, int tw, int th); public: - SkeletonHeadModel(); - SkeletonHeadModel(int u, int v, int tw, int th); + SkeletonHeadModel(); + SkeletonHeadModel(int u, int v, int tw, int th); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonModel.cpp b/Minecraft.Client/Rendering/Models/SkeletonModel.cpp index 0239e4c44..d6d363257 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonModel.cpp +++ b/Minecraft.Client/Rendering/Models/SkeletonModel.cpp @@ -3,45 +3,41 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -void SkeletonModel::_init(float g) -{ +void SkeletonModel::_init(float g) { arm0 = new ModelPart(this, 24 + 16, 16); - arm0->addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 + arm0->addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 arm0->setPos(-5, 2, 0); arm1 = new ModelPart(this, 24 + 16, 16); arm1->bMirror = true; - arm1->addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 + arm1->addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 arm1->setPos(5, 2, 0); leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 + leg0->addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 leg0->setPos(-2, 12, 0); leg1 = new ModelPart(this, 0, 16); leg1->bMirror = true; - leg1->addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 + leg1->addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 leg1->setPos(2, 12, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); } -SkeletonModel::SkeletonModel() : ZombieModel(0, 0, 64, 32) -{ - _init(0); -} +SkeletonModel::SkeletonModel() : ZombieModel(0, 0, 64, 32) { _init(0); } -SkeletonModel::SkeletonModel(float g) : ZombieModel(g, 0, 64, 32) -{ - _init(g); -} +SkeletonModel::SkeletonModel(float g) : ZombieModel(g, 0, 64, 32) { _init(g); } -void SkeletonModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - bowAndArrow=true; - ZombieModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void SkeletonModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + bowAndArrow = true; + ZombieModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonModel.h b/Minecraft.Client/Rendering/Models/SkeletonModel.h index ba5f9449d..db0d093ac 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonModel.h +++ b/Minecraft.Client/Rendering/Models/SkeletonModel.h @@ -1,13 +1,14 @@ #pragma once #include "ZombieModel.h" -class SkeletonModel : public ZombieModel -{ +class SkeletonModel : public ZombieModel { private: - void _init(float g); + void _init(float g); public: - SkeletonModel(); - SkeletonModel(float g); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + SkeletonModel(); + SkeletonModel(float g); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkinBox.h b/Minecraft.Client/Rendering/Models/SkinBox.h index 827e4447c..eaa39143c 100644 --- a/Minecraft.Client/Rendering/Models/SkinBox.h +++ b/Minecraft.Client/Rendering/Models/SkinBox.h @@ -1,19 +1,16 @@ #pragma once -enum eBodyPart -{ - eBodyPart_Unknown=0, - eBodyPart_Head, - eBodyPart_Body, - eBodyPart_Arm0, - eBodyPart_Arm1, - eBodyPart_Leg0, - eBodyPart_Leg1, +enum eBodyPart { + eBodyPart_Unknown = 0, + eBodyPart_Head, + eBodyPart_Body, + eBodyPart_Arm0, + eBodyPart_Arm1, + eBodyPart_Leg0, + eBodyPart_Leg1, }; -typedef struct -{ - eBodyPart ePart; - float fX,fY,fZ,fW,fH,fD,fU,fV; -} -SKIN_BOX; +typedef struct { + eBodyPart ePart; + float fX, fY, fZ, fW, fH, fD, fU, fV; +} SKIN_BOX; diff --git a/Minecraft.Client/Rendering/Models/SlimeModel.cpp b/Minecraft.Client/Rendering/Models/SlimeModel.cpp index b8244ebbd..029d7a1c4 100644 --- a/Minecraft.Client/Rendering/Models/SlimeModel.cpp +++ b/Minecraft.Client/Rendering/Models/SlimeModel.cpp @@ -2,47 +2,44 @@ #include "SlimeModel.h" #include "ModelPart.h" -SlimeModel::SlimeModel(int vOffs) -{ +SlimeModel::SlimeModel(int vOffs) { cube = new ModelPart(this, 0, vOffs); cube->addBox(-4, 16, -4, 8, 8, 8); - if (vOffs > 0) - { + if (vOffs > 0) { cube = new ModelPart(this, 0, vOffs); - cube->addBox(-3, 16+1, -3, 6, 6, 6); + cube->addBox(-3, 16 + 1, -3, 6, 6, 6); eye0 = new ModelPart(this, 32, 0); - eye0->addBox(-3-0.25f, 16+2, -3.5f, 2, 2, 2); + eye0->addBox(-3 - 0.25f, 16 + 2, -3.5f, 2, 2, 2); eye1 = new ModelPart(this, 32, 4); - eye1->addBox(+1+0.25f, 16+2, -3.5f, 2, 2, 2); + eye1->addBox(+1 + 0.25f, 16 + 2, -3.5f, 2, 2, 2); mouth = new ModelPart(this, 32, 8); - mouth->addBox(0, 16+5, -3.5f, 1, 1, 1); + mouth->addBox(0, 16 + 5, -3.5f, 1, 1, 1); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - eye0->compile(1.0f/16.0f); - eye1->compile(1.0f/16.0f); - mouth->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time + // cubes are rendered + eye0->compile(1.0f / 16.0f); + eye1->compile(1.0f / 16.0f); + mouth->compile(1.0f / 16.0f); + } else { + eye0 = NULL; + eye1 = NULL; + mouth = NULL; } - else - { - eye0 = NULL; - eye1 = NULL; - mouth = NULL; - } - cube->compile(1.0f/16.0f); + cube->compile(1.0f / 16.0f); } -void SlimeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SlimeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - cube->render(scale,usecompiled); - if (eye0!=NULL) - { - eye0->render(scale,usecompiled); - eye1->render(scale,usecompiled); - mouth->render(scale,usecompiled); + cube->render(scale, usecompiled); + if (eye0 != NULL) { + eye0->render(scale, usecompiled); + eye1->render(scale, usecompiled); + mouth->render(scale, usecompiled); } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SlimeModel.h b/Minecraft.Client/Rendering/Models/SlimeModel.h index fe2a4fc2b..c9c8cadcb 100644 --- a/Minecraft.Client/Rendering/Models/SlimeModel.h +++ b/Minecraft.Client/Rendering/Models/SlimeModel.h @@ -1,13 +1,14 @@ #pragma once #include "Model.h" -class SlimeModel : public Model -{ +class SlimeModel : public Model { public: - ModelPart *cube; - ModelPart *eye0, *eye1,* mouth; + ModelPart* cube; + ModelPart *eye0, *eye1, *mouth; SlimeModel(int vOffs); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SnowManModel.cpp b/Minecraft.Client/Rendering/Models/SnowManModel.cpp index ba1053e1b..5d9daa888 100644 --- a/Minecraft.Client/Rendering/Models/SnowManModel.cpp +++ b/Minecraft.Client/Rendering/Models/SnowManModel.cpp @@ -3,70 +3,70 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SnowManModel::SnowManModel() : Model() -{ +SnowManModel::SnowManModel() : Model() { float yOffset = 4; float g = 0; head = (new ModelPart(this, 0, 0))->setTexSize(64, 64); - head->addBox(-4, -8, -4, 8, 8, 8, g - 0.5f); // head + head->addBox(-4, -8, -4, 8, 8, 8, g - 0.5f); // head head->setPos(0, 0 + yOffset, 0); arm1 = (new ModelPart(this, 32, 0))->setTexSize(64, 64); - arm1->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm + arm1->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm arm1->setPos(0, 0 + yOffset + 9 - 7, 0); arm2 = (new ModelPart(this, 32, 0))->setTexSize(64, 64); - arm2->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm + arm2->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm arm2->setPos(0, 0 + yOffset + 9 - 7, 0); piece1 = (new ModelPart(this, 0, 16))->setTexSize(64, 64); - piece1->addBox(-5, -10, -5, 10, 10, 10, g - 0.5f); // upper body + piece1->addBox(-5, -10, -5, 10, 10, 10, g - 0.5f); // upper body piece1->setPos(0, 0 + yOffset + 9, 0); piece2 = (new ModelPart(this, 0, 36))->setTexSize(64, 64); - piece2->addBox(-6, -12, -6, 12, 12, 12, g - 0.5f); // lower body - piece2->setPos(0, 0 + yOffset + 20, 0); + piece2->addBox(-6, -12, -6, 12, 12, 12, g - 0.5f); // lower body + piece2->setPos(0, 0 + yOffset + 20, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - arm2->compile(1.0f/16.0f); - piece1->compile(1.0f/16.0f); - piece2->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + arm2->compile(1.0f / 16.0f); + piece1->compile(1.0f / 16.0f); + piece2->compile(1.0f / 16.0f); } -void SnowManModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ +void SnowManModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { Model::setupAnim(time, r, bob, yRot, xRot, scale); - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); - piece1->yRot = (yRot / (float) (180 / PI)) * 0.25f; + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); + piece1->yRot = (yRot / (float)(180 / PI)) * 0.25f; - float s = Mth::sin(piece1->yRot); - float c = Mth::cos(piece1->yRot); + float s = Mth::sin(piece1->yRot); + float c = Mth::cos(piece1->yRot); - arm1->zRot = 1; - arm2->zRot = -1; - arm1->yRot = 0 + piece1->yRot; - arm2->yRot = PI + piece1->yRot; + arm1->zRot = 1; + arm2->zRot = -1; + arm1->yRot = 0 + piece1->yRot; + arm2->yRot = PI + piece1->yRot; - arm1->x = (c) * 5; - arm1->z = (-s) * 5; - - arm2->x = (-c) * 5; - arm2->z = (s) * 5; + arm1->x = (c) * 5; + arm1->z = (-s) * 5; + + arm2->x = (-c) * 5; + arm2->z = (s) * 5; } -void SnowManModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void SnowManModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - piece1->render(scale,usecompiled); - piece2->render(scale,usecompiled); - head->render(scale,usecompiled); - arm1->render(scale,usecompiled); - arm2->render(scale,usecompiled); + piece1->render(scale, usecompiled); + piece2->render(scale, usecompiled); + head->render(scale, usecompiled); + arm1->render(scale, usecompiled); + arm2->render(scale, usecompiled); } - - diff --git a/Minecraft.Client/Rendering/Models/SnowManModel.h b/Minecraft.Client/Rendering/Models/SnowManModel.h index b2d8229ac..971172a22 100644 --- a/Minecraft.Client/Rendering/Models/SnowManModel.h +++ b/Minecraft.Client/Rendering/Models/SnowManModel.h @@ -1,13 +1,15 @@ #pragma once #include "Model.h" -class SnowManModel : public Model -{ +class SnowManModel : public Model { public: - ModelPart *piece1, *piece2, *head; - ModelPart *arm1, *arm2; + ModelPart *piece1, *piece2, *head; + ModelPart *arm1, *arm2; - SnowManModel() ; - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + SnowManModel(); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/SpiderModel.cpp b/Minecraft.Client/Rendering/Models/SpiderModel.cpp index ff1a79b1d..da0dff534 100644 --- a/Minecraft.Client/Rendering/Models/SpiderModel.cpp +++ b/Minecraft.Client/Rendering/Models/SpiderModel.cpp @@ -3,108 +3,109 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SpiderModel::SpiderModel() : Model() -{ +SpiderModel::SpiderModel() : Model() { float g = 0; - - int yo = 18+6-9; + + int yo = 18 + 6 - 9; head = new ModelPart(this, 32, 4); - head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(0+yo), -3); + head->addBox(-4, -4, -8, 8, 8, 8, g); // Head + head->setPos(0, (float)(0 + yo), -3); body0 = new ModelPart(this, 0, 0); - body0->addBox(-3, -3, -3, 6, 6, 6, g); // Body - body0->setPos(0,(float)(yo), 0); + body0->addBox(-3, -3, -3, 6, 6, 6, g); // Body + body0->setPos(0, (float)(yo), 0); body1 = new ModelPart(this, 0, 12); - body1->addBox(-5, -4, -6, 10, 8, 12, g); // Body - body1->setPos(0, (float)(0+yo), 3 + 6); - + body1->addBox(-5, -4, -6, 10, 8, 12, g); // Body + body1->setPos(0, (float)(0 + yo), 3 + 6); leg0 = new ModelPart(this, 18, 0); - leg0->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg0->setPos(-4, (float)(0+yo), 2); + leg0->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg0->setPos(-4, (float)(0 + yo), 2); leg1 = new ModelPart(this, 18, 0); - leg1->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg1->setPos(4, (float)(0+yo), 2); + leg1->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg1->setPos(4, (float)(0 + yo), 2); leg2 = new ModelPart(this, 18, 0); - leg2->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg2->setPos(-4, (float)(0+yo), 1); + leg2->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg2->setPos(-4, (float)(0 + yo), 1); leg3 = new ModelPart(this, 18, 0); - leg3->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg3->setPos(4, (float)(0+yo), 1); + leg3->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg3->setPos(4, (float)(0 + yo), 1); leg4 = new ModelPart(this, 18, 0); - leg4->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg4->setPos(-4, (float)(0+yo), 0); + leg4->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg4->setPos(-4, (float)(0 + yo), 0); leg5 = new ModelPart(this, 18, 0); - leg5->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg5->setPos(4, (float)(0+yo), 0); + leg5->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg5->setPos(4, (float)(0 + yo), 0); leg6 = new ModelPart(this, 18, 0); - leg6->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg6->setPos(-4, (float)(0+yo), -1); + leg6->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg6->setPos(-4, (float)(0 + yo), -1); leg7 = new ModelPart(this, 18, 0); - leg7->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg7->setPos(4, (float)(0+yo), -1); + leg7->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg7->setPos(4, (float)(0 + yo), -1); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body0->compile(1.0f/16.0f); - body1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); - leg4->compile(1.0f/16.0f); - leg5->compile(1.0f/16.0f); - leg6->compile(1.0f/16.0f); - leg7->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body0->compile(1.0f / 16.0f); + body1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); + leg4->compile(1.0f / 16.0f); + leg5->compile(1.0f / 16.0f); + leg6->compile(1.0f / 16.0f); + leg7->compile(1.0f / 16.0f); } -void SpiderModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SpiderModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - body0->render(scale,usecompiled); - body1->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - leg2->render(scale,usecompiled); - leg3->render(scale,usecompiled); - leg4->render(scale,usecompiled); - leg5->render(scale,usecompiled); - leg6->render(scale,usecompiled); - leg7->render(scale,usecompiled); + head->render(scale, usecompiled); + body0->render(scale, usecompiled); + body1->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + leg4->render(scale, usecompiled); + leg5->render(scale, usecompiled); + leg6->render(scale, usecompiled); + leg7->render(scale, usecompiled); } -void SpiderModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void SpiderModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); - float sr = (float) PI / 4.0f; + float sr = (float)PI / 4.0f; leg0->zRot = -sr; leg1->zRot = sr; - + leg2->zRot = -sr * 0.74f; leg3->zRot = sr * 0.74f; - + leg4->zRot = -sr * 0.74f; leg5->zRot = sr * 0.74f; - + leg6->zRot = -sr; leg7->zRot = sr; - float ro = -(float) PI / 2.0f * 0; - float ur = (float) PI / 8.0f; + float ro = -(float)PI / 2.0f * 0; + float ur = (float)PI / 8.0f; leg0->yRot = +ur * 2.0f + ro; leg1->yRot = -ur * 2.0f - ro; leg2->yRot = +ur * 1.0f + ro; @@ -114,16 +115,23 @@ void SpiderModel::setupAnim(float time, float r, float bob, float yRot, float xR leg6->yRot = -ur * 2.0f + ro; leg7->yRot = +ur * 2.0f - ro; + float c0 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 0 / 4.0f) * 0.4f) * r; + float c1 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 2 / 4.0f) * 0.4f) * r; + float c2 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 1 / 4.0f) * 0.4f) * r; + float c3 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 3 / 4.0f) * 0.4f) * r; - float c0 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 0 / 4.0f) * 0.4f) * r; - float c1 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 2 / 4.0f) * 0.4f) * r; - float c2 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 1 / 4.0f) * 0.4f) * r; - float c3 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 3 / 4.0f) * 0.4f) * r; - - float s0 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 0 / 4.0f) * 0.4f) * r; - float s1 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 2 / 4.0f) * 0.4f) * r; - float s2 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 1 / 4.0f) * 0.4f) * r; - float s3 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 3 / 4.0f) * 0.4f) * r; + float s0 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 0 / 4.0f) * 0.4f) * r; + float s1 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 2 / 4.0f) * 0.4f) * r; + float s2 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 1 / 4.0f) * 0.4f) * r; + float s3 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 3 / 4.0f) * 0.4f) * r; leg0->yRot += +c0; leg1->yRot += -c0; diff --git a/Minecraft.Client/Rendering/Models/SpiderModel.h b/Minecraft.Client/Rendering/Models/SpiderModel.h index 2d9d15273..ea2624647 100644 --- a/Minecraft.Client/Rendering/Models/SpiderModel.h +++ b/Minecraft.Client/Rendering/Models/SpiderModel.h @@ -1,12 +1,16 @@ #pragma once #include "Model.h" - class SpiderModel : public Model -{ +class SpiderModel : public Model { public: - ModelPart *head, *body0, *body1, *leg0, *leg1, *leg2, *leg3, *leg4, *leg5, *leg6, *leg7; + ModelPart *head, *body0, *body1, *leg0, *leg1, *leg2, *leg3, *leg4, *leg5, + *leg6, *leg7; SpiderModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SquidModel.cpp b/Minecraft.Client/Rendering/Models/SquidModel.cpp index baeb6ea19..bf0541d19 100644 --- a/Minecraft.Client/Rendering/Models/SquidModel.cpp +++ b/Minecraft.Client/Rendering/Models/SquidModel.cpp @@ -3,18 +3,18 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SquidModel::SquidModel() : Model() -{ +SquidModel::SquidModel() : Model() { int yoffs = -16; body = new ModelPart(this, 0, 0); body->addBox(-6, -8, -6, 12, 16, 12); body->y += (8 + 16) + yoffs; - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length - { + for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length + { tentacles[i] = new ModelPart(this, 48, 0); - double angle = i * PI * 2.0 / (double) TENTACLES_LENGTH; // 4J - 8 was tentacles.length + double angle = i * PI * 2.0 / + (double)TENTACLES_LENGTH; // 4J - 8 was tentacles.length float xo = Mth::cos((float)angle) * 5; float yo = Mth::sin((float)angle) * 5; tentacles[i]->addBox(-1, 0, -1, 2, 18, 2); @@ -23,33 +23,37 @@ SquidModel::SquidModel() : Model() tentacles[i]->z = yo; tentacles[i]->y = (float)(31 + yoffs); - angle = i * PI * -2.0 / (double) TENTACLES_LENGTH + PI * .5; // 4J - 8 was tentacles.length - tentacles[i]->yRot = (float) angle; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - tentacles[i]->compile(1.0f/16.0f); - } - body->compile(1.0f/16.0f); + angle = i * PI * -2.0 / (double)TENTACLES_LENGTH + + PI * .5; // 4J - 8 was tentacles.length + tentacles[i]->yRot = (float)angle; + // 4J added - compile now to avoid random performance hit first time + // cubes are rendered + tentacles[i]->compile(1.0f / 16.0f); + } + body->compile(1.0f / 16.0f); } -void SquidModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length - { - +void SquidModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length + { // tentacle angle is calculated in SquidRenderer tentacles[i]->xRot = bob; } } -void SquidModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SquidModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); body->render(scale, usecompiled); - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length // 4J Stu - Was 9 but I made it 8 as the array is [0,8) - { + for (int i = 0; i < TENTACLES_LENGTH; + i++) // 4J - 8 was tentacles.length // 4J Stu - Was 9 but I made it 8 + // as the array is [0,8) + { tentacles[i]->render(scale, usecompiled); } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SquidModel.h b/Minecraft.Client/Rendering/Models/SquidModel.h index 0b7948a80..28bc025a7 100644 --- a/Minecraft.Client/Rendering/Models/SquidModel.h +++ b/Minecraft.Client/Rendering/Models/SquidModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class SquidModel : public Model -{ +class SquidModel : public Model { public: - static const int TENTACLES_LENGTH=8; - ModelPart *body; - ModelPart *tentacles[TENTACLES_LENGTH]; + static const int TENTACLES_LENGTH = 8; + ModelPart* body; + ModelPart* tentacles[TENTACLES_LENGTH]; SquidModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp b/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp index ec83b39c8..4e55acee3 100644 --- a/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp @@ -3,88 +3,84 @@ #include "ModelPart.h" #include "VillagerGolemModel.h" -VillagerGolemModel::VillagerGolemModel(float g, float yOffset) -{ - int xTexSize = 128; - int yTexSize = 128; +VillagerGolemModel::VillagerGolemModel(float g, float yOffset) { + int xTexSize = 128; + int yTexSize = 128; - head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - head->setPos(0, 0 + yOffset, -2); - head->texOffs(0, 0)->addBox(-4, -12, -5.5f, 8, 10, 8, g); - head->texOffs(24, 0)->addBox(-1, -5.0f, -7.5f, 2, 4, 2, g); + head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + head->setPos(0, 0 + yOffset, -2); + head->texOffs(0, 0)->addBox(-4, -12, -5.5f, 8, 10, 8, g); + head->texOffs(24, 0)->addBox(-1, -5.0f, -7.5f, 2, 4, 2, g); - body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - body->setPos(0, 0 + yOffset, 0); - body->texOffs(0, 40)->addBox(-9, -2, -6, 18, 12, 11, g); - body->texOffs(0, 70)->addBox(-4.5f, 10, -3, 9, 5, 6, g + 0.5f); + body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + body->setPos(0, 0 + yOffset, 0); + body->texOffs(0, 40)->addBox(-9, -2, -6, 18, 12, 11, g); + body->texOffs(0, 70)->addBox(-4.5f, 10, -3, 9, 5, 6, g + 0.5f); - arm0 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arm0->setPos(0, -7, 0); - arm0->texOffs(60, 21)->addBox(-13, -2.5f, -3, 4, 30, 6, g); + arm0 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arm0->setPos(0, -7, 0); + arm0->texOffs(60, 21)->addBox(-13, -2.5f, -3, 4, 30, 6, g); - arm1 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arm1->setPos(0, -7, 0); - arm1->texOffs(60, 58)->addBox(9, -2.5f, -3, 4, 30, 6, g); + arm1 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arm1->setPos(0, -7, 0); + arm1->texOffs(60, 58)->addBox(9, -2.5f, -3, 4, 30, 6, g); - leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg0->setPos(-4.0f, 18 + yOffset, 0); - leg0->texOffs(37, 0)->addBox(-3.5f, -3, -3, 6, 16, 5, g); + leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg0->setPos(-4.0f, 18 + yOffset, 0); + leg0->texOffs(37, 0)->addBox(-3.5f, -3, -3, 6, 16, 5, g); - leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg1->bMirror = true; - leg1->texOffs(60, 0)->setPos(5.0f, 18 + yOffset, 0); - leg1->addBox(-3.5f, -3, -3, 6, 16, 5, g); + leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg1->bMirror = true; + leg1->texOffs(60, 0)->setPos(5.0f, 18 + yOffset, 0); + leg1->addBox(-3.5f, -3, -3, 6, 16, 5, g); } -void VillagerGolemModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void VillagerGolemModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - arm0->render(scale, usecompiled); - arm1->render(scale, usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + arm0->render(scale, usecompiled); + arm1->render(scale, usecompiled); } -void VillagerGolemModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void VillagerGolemModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); - leg0->xRot = (-1.5f * triangleWave(time, 13)) * r; - leg1->xRot = (1.5f * triangleWave(time, 13)) * r; - leg0->yRot = 0; - leg1->yRot = 0; + leg0->xRot = (-1.5f * triangleWave(time, 13)) * r; + leg1->xRot = (1.5f * triangleWave(time, 13)) * r; + leg0->yRot = 0; + leg1->yRot = 0; } -void VillagerGolemModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr vg = std::dynamic_pointer_cast(mob); - int attackTick = vg->getAttackAnimationTick(); - if (attackTick > 0) - { - arm0->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); - arm1->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); - } - else - { - int offerFlowerTick = vg->getOfferFlowerTick(); - if (offerFlowerTick > 0) - { - arm0->xRot = -0.8f + 0.025f * triangleWave(offerFlowerTick, 70); - arm1->xRot = 0; - } - else - { - arm0->xRot = (-0.2f + 1.5f * triangleWave(time, 13)) * r; - arm1->xRot = (-0.2f - 1.5f * triangleWave(time, 13)) * r; - } - } +void VillagerGolemModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + std::shared_ptr vg = + std::dynamic_pointer_cast(mob); + int attackTick = vg->getAttackAnimationTick(); + if (attackTick > 0) { + arm0->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); + arm1->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); + } else { + int offerFlowerTick = vg->getOfferFlowerTick(); + if (offerFlowerTick > 0) { + arm0->xRot = -0.8f + 0.025f * triangleWave(offerFlowerTick, 70); + arm1->xRot = 0; + } else { + arm0->xRot = (-0.2f + 1.5f * triangleWave(time, 13)) * r; + arm1->xRot = (-0.2f - 1.5f * triangleWave(time, 13)) * r; + } + } } -float VillagerGolemModel::triangleWave(float bob, float period) -{ - return (abs(fmod(bob, period) - period * 0.5f) - period * 0.25f) / (period * 0.25f); +float VillagerGolemModel::triangleWave(float bob, float period) { + return (abs(fmod(bob, period) - period * 0.5f) - period * 0.25f) / + (period * 0.25f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerGolemModel.h b/Minecraft.Client/Rendering/Models/VillagerGolemModel.h index 80c822d5c..9dba11416 100644 --- a/Minecraft.Client/Rendering/Models/VillagerGolemModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerGolemModel.h @@ -4,27 +4,29 @@ class ModelPart; -class VillagerGolemModel : public Model -{ +class VillagerGolemModel : public Model { public: - ModelPart *head, *body, *arm0, *arm1, *leg0, *leg1; + ModelPart *head, *body, *arm0, *arm1, *leg0, *leg1; - //VillagerGolemModel() - //{ - // this(0); - //} + // VillagerGolemModel() + //{ + // this(0); + // } - //VillagerGolemModel(float g) - //{ - // this(g, -7); - //} + // VillagerGolemModel(float g) + //{ + // this(g, -7); + // } - VillagerGolemModel(float g = 0.0f, float yOffset = -7.0f); + VillagerGolemModel(float g = 0.0f, float yOffset = -7.0f); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); private: - float triangleWave(float bob, float period); + float triangleWave(float bob, float period); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerModel.cpp b/Minecraft.Client/Rendering/Models/VillagerModel.cpp index 3f7242175..42990ef1e 100644 --- a/Minecraft.Client/Rendering/Models/VillagerModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerModel.cpp @@ -3,81 +3,77 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" +void VillagerModel::_init(float g, float yOffset) { + int xTexSize = 64; + int yTexSize = 64; -void VillagerModel::_init(float g, float yOffset) -{ - int xTexSize = 64; - int yTexSize = 64; + head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + head->setPos(0, 0 + yOffset, 0); + head->texOffs(0, 0)->addBox(-4, -10, -4, 8, 10, 8, g); + // head.texOffs(32, 0).addBox(-4, -10, -4, 8, 12, 8, g + 0.5f); + head->texOffs(24, 0)->addBox(-1, -3, -6, 2, 4, 2, g); - head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - head->setPos(0, 0 + yOffset, 0); - head->texOffs(0, 0)->addBox(-4, -10, -4, 8, 10, 8, g); - // head.texOffs(32, 0).addBox(-4, -10, -4, 8, 12, 8, g + 0.5f); - head->texOffs(24, 0)->addBox(-1, -3, -6, 2, 4, 2, g); + body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + body->setPos(0, 0 + yOffset, 0); + body->texOffs(16, 20)->addBox(-4, 0, -3, 8, 12, 6, g); + body->texOffs(0, 38)->addBox(-4, 0, -3, 8, 18, 6, g + 0.5f); - body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - body->setPos(0, 0 + yOffset, 0); - body->texOffs(16, 20)->addBox(-4, 0, -3, 8, 12, 6, g); - body->texOffs(0, 38)->addBox(-4, 0, -3, 8, 18, 6, g + 0.5f); + arms = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arms->setPos(0, 0 + yOffset + 2, 0); + arms->texOffs(44, 22)->addBox(-6 - 2, -2, -2, 4, 8, 4, g); + arms->texOffs(44, 22)->addBox(6 - 2, -2, -2, 4, 8, 4, g); + arms->texOffs(40, 38)->addBox(-4, 2, -2, 8, 4, 4, g); - arms = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arms->setPos(0, 0 + yOffset + 2, 0); - arms->texOffs(44, 22)->addBox(-6 - 2, -2, -2, 4, 8, 4, g); - arms->texOffs(44, 22)->addBox(6 - 2, -2, -2, 4, 8, 4, g); - arms->texOffs(40, 38)->addBox(-4, 2, -2, 8, 4, 4, g); + leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg0->setPos(-2, 12 + yOffset, 0); + leg0->addBox(-2, 0, -2, 4, 12, 4, g); // Leg0 - leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg0->setPos(-2, 12 + yOffset, 0); - leg0->addBox(-2, 0, -2, 4, 12, 4, g); // Leg0 + leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg1->bMirror = true; + leg1->setPos(2, 12 + yOffset, 0); + leg1->addBox(-2, 0, -2, 4, 12, 4, g); // Leg1 - leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg1->bMirror = true; - leg1->setPos(2, 12 + yOffset, 0); - leg1->addBox(-2, 0, -2, 4, 12, 4, g); // Leg1 + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - arms->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + arms->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); } -VillagerModel::VillagerModel(float g) : Model() -{ - _init(g, 0); +VillagerModel::VillagerModel(float g) : Model() { _init(g, 0); } + +VillagerModel::VillagerModel(float g, float yOffset) : Model() { + _init(g, yOffset); } -VillagerModel::VillagerModel(float g, float yOffset) : Model() -{ - _init(g,yOffset); -} - -void VillagerModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void VillagerModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - arms->render(scale,usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + arms->render(scale, usecompiled); } -void VillagerModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); - +void VillagerModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); + arms->y = 3; arms->z = -1; arms->xRot = -0.75f; - - leg0->xRot = ((float) Mth::cos(time * 0.6662f) * 1.4f) * r * 0.5f; - leg1->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.4f) * r * 0.5f; + + leg0->xRot = ((float)Mth::cos(time * 0.6662f) * 1.4f) * r * 0.5f; + leg1->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.4f) * r * 0.5f; leg0->yRot = 0; leg1->yRot = 0; } - diff --git a/Minecraft.Client/Rendering/Models/VillagerModel.h b/Minecraft.Client/Rendering/Models/VillagerModel.h index cfb4b1d9f..59f3b18de 100644 --- a/Minecraft.Client/Rendering/Models/VillagerModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerModel.h @@ -2,14 +2,17 @@ #pragma once #include "Model.h" -class VillagerModel : public Model -{ +class VillagerModel : public Model { public: - ModelPart *head, *body, *arms, *leg0, *leg1; + ModelPart *head, *body, *arms, *leg0, *leg1; - void _init(float g, float yOffset); // 4J added + void _init(float g, float yOffset); // 4J added VillagerModel(float g, float yOffset); VillagerModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) ; - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp b/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp index 891f98faf..152e991cc 100644 --- a/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp @@ -3,60 +3,54 @@ #include "VillagerZombieModel.h" #include "../../../Minecraft.World/Util/Mth.h" -void VillagerZombieModel::_init(float g, float yOffset, bool isArmor) -{ - delete head; - if (isArmor) - { - head = new ModelPart(this, 0, 0); - head->addBox(-4, -10, -4, 8, 6, 8, g); // Head - head->setPos(0, 0 + yOffset, 0); - } - else - { - head = new ModelPart(this); - head->setPos(0, 0 + yOffset, 0); - head->texOffs(0, 32)->addBox(-4, -10, -4, 8, 10, 8, g); - head->texOffs(24, 32)->addBox(-1, -3, -6, 2, 4, 2, g); - } +void VillagerZombieModel::_init(float g, float yOffset, bool isArmor) { + delete head; + if (isArmor) { + head = new ModelPart(this, 0, 0); + head->addBox(-4, -10, -4, 8, 6, 8, g); // Head + head->setPos(0, 0 + yOffset, 0); + } else { + head = new ModelPart(this); + head->setPos(0, 0 + yOffset, 0); + head->texOffs(0, 32)->addBox(-4, -10, -4, 8, 10, 8, g); + head->texOffs(24, 32)->addBox(-1, -3, -6, 2, 4, 2, g); + } - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); } -VillagerZombieModel::VillagerZombieModel() : HumanoidModel(0, 0, 64, 64) -{ - _init(0, 0, false); +VillagerZombieModel::VillagerZombieModel() : HumanoidModel(0, 0, 64, 64) { + _init(0, 0, false); } -VillagerZombieModel::VillagerZombieModel(float g, float yOffset, bool isArmor) : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) -{ - _init(g, yOffset, isArmor); +VillagerZombieModel::VillagerZombieModel(float g, float yOffset, bool isArmor) + : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) { + _init(g, yOffset, isArmor); } -int VillagerZombieModel::version() -{ - return 10; -} +int VillagerZombieModel::version() { return 10; } -void VillagerZombieModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void VillagerZombieModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); - float attack2 = Mth::sin(attackTime * PI); - float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); - arm0->zRot = 0; - arm1->zRot = 0; - arm0->yRot = -(0.1f - attack2 * 0.6f); - arm1->yRot = +(0.1f - attack2 * 0.6f); - arm0->xRot = -PI / 2.0f; - arm1->xRot = -PI / 2.0f; - arm0->xRot -= attack2 * 1.2f - attack * 0.4f; - arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + float attack2 = Mth::sin(attackTime * PI); + float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); + arm0->zRot = 0; + arm1->zRot = 0; + arm0->yRot = -(0.1f - attack2 * 0.6f); + arm1->yRot = +(0.1f - attack2 * 0.6f); + arm0->xRot = -PI / 2.0f; + arm1->xRot = -PI / 2.0f; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; - arm0->zRot += (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); - arm1->zRot -= (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); - arm0->xRot += (Mth::sin(bob * 0.067f) * 0.05f); - arm1->xRot -= (Mth::sin(bob * 0.067f) * 0.05f); + arm0->zRot += (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); + arm1->zRot -= (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); + arm0->xRot += (Mth::sin(bob * 0.067f) * 0.05f); + arm1->xRot -= (Mth::sin(bob * 0.067f) * 0.05f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerZombieModel.h b/Minecraft.Client/Rendering/Models/VillagerZombieModel.h index b4400b354..201664a68 100644 --- a/Minecraft.Client/Rendering/Models/VillagerZombieModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerZombieModel.h @@ -2,15 +2,15 @@ #include "HumanoidModel.h" -class VillagerZombieModel : public HumanoidModel -{ +class VillagerZombieModel : public HumanoidModel { private: - void _init(float g, float yOffset, bool isArmor); + void _init(float g, float yOffset, bool isArmor); public: - VillagerZombieModel(); - VillagerZombieModel(float g, float yOffset, bool isArmor); + VillagerZombieModel(); + VillagerZombieModel(float g, float yOffset, bool isArmor); - int version(); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + int version(); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/WolfModel.cpp b/Minecraft.Client/Rendering/Models/WolfModel.cpp index 101f3a58e..ebacdb74f 100644 --- a/Minecraft.Client/Rendering/Models/WolfModel.cpp +++ b/Minecraft.Client/Rendering/Models/WolfModel.cpp @@ -4,111 +4,105 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -WolfModel::WolfModel() -{ +WolfModel::WolfModel() { float g = 0; float headHeight = 12 + 9.5f - legSize; head = new ModelPart(this, 0, 0); - head->addBox(-3, -3, -2, 6, 6, 4, g); // Head + head->addBox(-3, -3, -2, 6, 6, 4, g); // Head head->setPos(-1, headHeight, -7); body = new ModelPart(this, 18, 14); - body->addBox(-4, -2, -3, 6, 9, 6, g); // Body + body->addBox(-4, -2, -3, 6, 9, 6, g); // Body body->setPos(0, 11 + 11 - legSize, 2); upperBody = new ModelPart(this, 21, 0); - upperBody->addBox(-4, -3, -3, 8, 6, 7, g); // Body + upperBody->addBox(-4, -3, -3, 8, 6, 7, g); // Body upperBody->setPos(-1.0f, 11 + 11.0f - legSize, 2); leg0 = new ModelPart(this, 0, 18); - leg0->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg0 + leg0->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg0 leg0->setPos(-2.5f, 18 + 6 - legSize, 7); leg1 = new ModelPart(this, 0, 18); - leg1->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg1 + leg1->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg1 leg1->setPos(.5f, 18 + 6 - legSize, 7); leg2 = new ModelPart(this, 0, 18); - leg2->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg2 + leg2->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg2 leg2->setPos(-2.5f, 18 + 6 - legSize, -4); leg3 = new ModelPart(this, 0, 18); - leg3->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg3 + leg3->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg3 leg3->setPos(.5f, 18 + 6 - legSize, -4); tail = new ModelPart(this, 9, 18); tail->addBox(-1, 0, -1, 2, 8, 2, g); tail->setPos(-1, 2 + 18 - legSize, 8); - head->texOffs(16, 14)->addBox(-3, -5, 0, 2, 2, 1, g); - head->texOffs(16, 14)->addBox(1, -5, 0, 2, 2, 1, g); - head->texOffs(0, 10)->addBox(-1.5f, 0, -5, 3, 3, 4, g); + head->texOffs(16, 14)->addBox(-3, -5, 0, 2, 2, 1, g); + head->texOffs(16, 14)->addBox(1, -5, 0, 2, 2, 1, g); + head->texOffs(0, 10)->addBox(-1.5f, 0, -5, 3, 3, 4, g); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - upperBody->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); - tail->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + upperBody->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); + tail->compile(1.0f / 16.0f); } -void WolfModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void WolfModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { Model::render(entity, time, r, bob, yRot, xRot, scale, usecompiled); setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2; - glPushMatrix(); - glTranslatef(0, 5 * scale, 2 * scale); - head->renderRollable(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - tail->renderRollable(scale, usecompiled); - upperBody->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->renderRollable(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - tail->renderRollable(scale, usecompiled); - upperBody->render(scale, usecompiled); - } + if (young) { + float ss = 2; + glPushMatrix(); + glTranslatef(0, 5 * scale, 2 * scale); + head->renderRollable(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + tail->renderRollable(scale, usecompiled); + upperBody->render(scale, usecompiled); + glPopMatrix(); + } else { + head->renderRollable(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + tail->renderRollable(scale, usecompiled); + upperBody->render(scale, usecompiled); + } } -void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ +void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { std::shared_ptr wolf = std::dynamic_pointer_cast(mob); - if (wolf->isAngry()) - { + if (wolf->isAngry()) { tail->yRot = 0; - } - else - { + } else { tail->yRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; } - if (wolf->isSitting()) - { + if (wolf->isSitting()) { upperBody->setPos(-1.0f, 11 + 13.0f - 8, -3); upperBody->xRot = .40f * PI; upperBody->yRot = .0f * PI; @@ -127,11 +121,9 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f leg2->setPos(-2.49f, 18 + 7.0f - legSize, -4); leg3->xRot = 1.85f * PI; leg3->setPos(.51f, 18 + 7.0f - legSize, -4); - } - else - { + } else { body->setPos(0, 11 + 11 - legSize, 2); - body->xRot = 90 / (float) (180 / PI); + body->xRot = 90 / (float)(180 / PI); upperBody->setPos(-1.0f, 11 + 11.0f - legSize, -3); upperBody->xRot = body->xRot; @@ -143,7 +135,6 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f leg2->setPos(-2.5f, 18 + 6 - legSize, -4); leg3->setPos(.5f, 18 + 6 - legSize, -4); - leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; leg2->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; @@ -158,10 +149,11 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f tail->zRot = wolf->getBodyRollAngle(a, -.2f); } -void WolfModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ +void WolfModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { Model::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); tail->xRot = bob; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/WolfModel.h b/Minecraft.Client/Rendering/Models/WolfModel.h index 809259906..efdddbc58 100644 --- a/Minecraft.Client/Rendering/Models/WolfModel.h +++ b/Minecraft.Client/Rendering/Models/WolfModel.h @@ -2,20 +2,26 @@ #include "Model.h" #include "../../../Minecraft.World/Entities/Mob.h" -class WolfModel : public Model -{ +class WolfModel : public Model { public: - ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; -// Cube *ear1; -// Cube *ear2; -// Cube *mouth; - ModelPart *tail; - ModelPart *upperBody; + ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; + // Cube *ear1; + // Cube *ear2; + // Cube *mouth; + ModelPart* tail; + ModelPart* upperBody; + private: - static const int legSize = 8; + static const int legSize = 8; + public: - WolfModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + WolfModel(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ZombieModel.cpp b/Minecraft.Client/Rendering/Models/ZombieModel.cpp index 918f751fc..b159f6019 100644 --- a/Minecraft.Client/Rendering/Models/ZombieModel.cpp +++ b/Minecraft.Client/Rendering/Models/ZombieModel.cpp @@ -3,34 +3,32 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -ZombieModel::ZombieModel() : HumanoidModel(0, 0, 64, 32) -{ -} +ZombieModel::ZombieModel() : HumanoidModel(0, 0, 64, 32) {} -ZombieModel::ZombieModel(float g, float yOffset, int texWidth, int texHeight) : HumanoidModel(g, yOffset, texWidth, texHeight) -{ -} +ZombieModel::ZombieModel(float g, float yOffset, int texWidth, int texHeight) + : HumanoidModel(g, yOffset, texWidth, texHeight) {} -ZombieModel::ZombieModel(float g, bool isArmor) : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) -{ -} +ZombieModel::ZombieModel(float g, bool isArmor) + : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) {} -void ZombieModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - - float attack2 = Mth::sin(attackTime*PI); - float attack = Mth::sin((1-(1-attackTime)*(1-attackTime))*PI); +void ZombieModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); + + float attack2 = Mth::sin(attackTime * PI); + float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); arm0->zRot = 0; arm1->zRot = 0; - arm0->yRot = -(0.1f-attack2*0.6f); - arm1->yRot = +(0.1f-attack2*0.6f); - arm0->xRot = -(float)PI/2.0f; - arm1->xRot = -(float)PI/2.0f; - arm0->xRot -= attack2*1.2f-attack*0.4f; - arm1->xRot -= attack2*1.2f-attack*0.4f; - arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f+0.05f); - arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f+0.05f); + arm0->yRot = -(0.1f - attack2 * 0.6f); + arm1->yRot = +(0.1f - attack2 * 0.6f); + arm0->xRot = -(float)PI / 2.0f; + arm1->xRot = -(float)PI / 2.0f; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ZombieModel.h b/Minecraft.Client/Rendering/Models/ZombieModel.h index 1971db097..90351967b 100644 --- a/Minecraft.Client/Rendering/Models/ZombieModel.h +++ b/Minecraft.Client/Rendering/Models/ZombieModel.h @@ -1,16 +1,17 @@ #pragma once #include "HumanoidModel.h" -class ZombieModel : public HumanoidModel -{ +class ZombieModel : public HumanoidModel { public: - ZombieModel(); + ZombieModel(); protected: - ZombieModel(float g, float yOffset, int texWidth, int texHeight); + ZombieModel(float g, float yOffset, int texWidth, int texHeight); public: - ZombieModel(float g, bool isArmor); + ZombieModel(float g, bool isArmor); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/OffsettedRenderList.cpp b/Minecraft.Client/Rendering/OffsettedRenderList.cpp index 2c2dfd92d..685da0524 100644 --- a/Minecraft.Client/Rendering/OffsettedRenderList.cpp +++ b/Minecraft.Client/Rendering/OffsettedRenderList.cpp @@ -3,54 +3,48 @@ #include "OffsettedRenderList.h" // 4J added -OffsettedRenderList::OffsettedRenderList() -{ - x = y = z = 0; - xOff = yOff = zOff = 0; - lists = MemoryTracker::createIntBuffer(1024 * 64); - inited = false; - rendered = false; +OffsettedRenderList::OffsettedRenderList() { + x = y = z = 0; + xOff = yOff = zOff = 0; + lists = MemoryTracker::createIntBuffer(1024 * 64); + inited = false; + rendered = false; } -void OffsettedRenderList::init(int x, int y, int z, double xOff, double yOff, double zOff) -{ +void OffsettedRenderList::init(int x, int y, int z, double xOff, double yOff, + double zOff) { inited = true; lists->clear(); this->x = x; this->y = y; this->z = z; - this->xOff = (float) xOff; - this->yOff = (float) yOff; - this->zOff = (float) zOff; + this->xOff = (float)xOff; + this->yOff = (float)yOff; + this->zOff = (float)zOff; } -bool OffsettedRenderList::isAt(int x, int y, int z) -{ +bool OffsettedRenderList::isAt(int x, int y, int z) { if (!inited) return false; return x == this->x && y == this->y && z == this->z; } -void OffsettedRenderList::add(int list) -{ - // 4J - added - chunkList::getList returns -1 when chunks aren't visible, we really don't want to end up sending that to glCallLists - if( list >= 0 ) - { - lists->put(list); - } +void OffsettedRenderList::add(int list) { + // 4J - added - chunkList::getList returns -1 when chunks aren't visible, we + // really don't want to end up sending that to glCallLists + if (list >= 0) { + lists->put(list); + } if (lists->remaining() == 0) render(); } -void OffsettedRenderList::render() -{ +void OffsettedRenderList::render() { if (!inited) return; - if (!rendered) - { + if (!rendered) { lists->flip(); rendered = true; } - if (lists->remaining() > 0) - { + if (lists->remaining() > 0) { glPushMatrix(); glTranslatef(x - xOff, y - yOff, z - zOff); glCallLists(lists); @@ -58,8 +52,7 @@ void OffsettedRenderList::render() } } -void OffsettedRenderList::clear() -{ +void OffsettedRenderList::clear() { inited = false; rendered = false; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/OffsettedRenderList.h b/Minecraft.Client/Rendering/OffsettedRenderList.h index c989da31b..cc529edee 100644 --- a/Minecraft.Client/Rendering/OffsettedRenderList.h +++ b/Minecraft.Client/Rendering/OffsettedRenderList.h @@ -2,17 +2,16 @@ class IntBuffer; -class OffsettedRenderList -{ +class OffsettedRenderList { private: - int x, y, z; + int x, y, z; float xOff, yOff, zOff; - IntBuffer *lists; + IntBuffer* lists; bool inited; - bool rendered ; + bool rendered; public: - OffsettedRenderList(); // 4J added + OffsettedRenderList(); // 4J added void init(int x, int y, int z, double xOff, double yOff, double zOff); bool isAt(int x, int y, int z); void add(int list); diff --git a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp index b20aaa6e5..c7655ec0c 100644 --- a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp @@ -5,60 +5,68 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -void BreakingItemParticle::_init(Item *item, Textures *textures, int data) -{ +void BreakingItemParticle::_init(Item* item, Textures* textures, int data) { this->setTex(textures, item->getIcon(data)); rCol = gCol = bCol = 1.0f; gravity = Tile::snow->gravity; size /= 2; } -BreakingItemParticle::BreakingItemParticle(Level *level, double x, double y, double z, Item *item, Textures *textures, int data) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(item, textures, data); +BreakingItemParticle::BreakingItemParticle(Level* level, double x, double y, + double z, Item* item, + Textures* textures, int data) + : Particle(level, x, y, z, 0, 0, 0) { + _init(item, textures, data); } -BreakingItemParticle::BreakingItemParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Item *item, Textures *textures, int data) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(item, textures, data); - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; +BreakingItemParticle::BreakingItemParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, Item* item, + Textures* textures, int data) + : Particle(level, x, y, z, 0, 0, 0) { + _init(item, textures, data); + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; } -int BreakingItemParticle::getParticleTexture() -{ - return ParticleEngine::ITEM_TEXTURE; +int BreakingItemParticle::getParticleTexture() { + return ParticleEngine::ITEM_TEXTURE; } -void BreakingItemParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void BreakingItemParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float u0 = (texX + uo / 4.0f) / 16.0f; float u1 = u0 + 0.999f / 16.0f / 4; float v0 = (texY + vo / 4.0f) / 16.0f; float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - } + if (tex != NULL) { + u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); - float br = SharedConstants::TEXTURE_LIGHTING ? 1 : getBrightness(a); // 4J - change brought forward from 1.8.2 + float x = (float)(xo + (this->x - xo) * a - xOff); + float y = (float)(yo + (this->y - yo) * a - yOff); + float z = (float)(zo + (this->z - zo) * a - zOff); + float br = + SharedConstants::TEXTURE_LIGHTING + ? 1 + : getBrightness(a); // 4J - change brought forward from 1.8.2 t->color(br * rCol, br * gCol, br * bCol); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u0), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u1), (float)( v1)); - + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u0), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u1), (float)(v1)); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h index 390426d41..7fd7e5aab 100644 --- a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h +++ b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h @@ -1,15 +1,18 @@ #pragma once #include "Particle.h" -class BreakingItemParticle : public Particle -{ - // virtual eINSTANCEOF GetType(); // 4J-IB/JEV TODO needs implementation +class BreakingItemParticle : public Particle { + // virtual eINSTANCEOF GetType(); // 4J-IB/JEV TODO needs implementation public: - virtual eINSTANCEOF GetType() { return eType_BREAKINGITEMPARTICLE; } - void _init(Item *item, Textures *textures, int data); - BreakingItemParticle(Level *level, double x, double y, double z, Item *item, Textures *textures, int data = 0); - BreakingItemParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Item *item, Textures *textures, int data = 0); + virtual eINSTANCEOF GetType() { return eType_BREAKINGITEMPARTICLE; } + void _init(Item* item, Textures* textures, int data); + BreakingItemParticle(Level* level, double x, double y, double z, Item* item, + Textures* textures, int data = 0); + BreakingItemParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, Item* item, Textures* textures, + int data = 0); virtual int getParticleTexture(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); }; diff --git a/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp b/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp index 54011b215..79008ef54 100644 --- a/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp @@ -6,25 +6,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" -BubbleParticle::BubbleParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) - { - rCol = 1.0f; - gCol = 1.0f; - bCol = 1.0f; - setMiscTex(32); - this->setSize(0.02f, 0.02f); - - size = size*(random->nextFloat()*0.6f+0.2f); - - xd = xa*0.2f+(float)(Math::random()*2-1)*0.02f; - yd = ya*0.2f+(float)(Math::random()*2-1)*0.02f; - zd = za*0.2f+(float)(Math::random()*2-1)*0.02f; +BubbleParticle::BubbleParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + rCol = 1.0f; + gCol = 1.0f; + bCol = 1.0f; + setMiscTex(32); + this->setSize(0.02f, 0.02f); - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + size = size * (random->nextFloat() * 0.6f + 0.2f); + + xd = xa * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + yd = ya * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + zd = za * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); } -void BubbleParticle::tick() -{ +void BubbleParticle::tick() { xo = x; yo = y; zo = z; @@ -35,7 +35,9 @@ void BubbleParticle::tick() yd *= 0.85f; zd *= 0.85f; - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != + Material::water) + remove(); if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/BubbleParticle.h b/Minecraft.Client/Rendering/Particles/BubbleParticle.h index 0e786d9de..18ad2f785 100644 --- a/Minecraft.Client/Rendering/Particles/BubbleParticle.h +++ b/Minecraft.Client/Rendering/Particles/BubbleParticle.h @@ -1,10 +1,10 @@ #pragma once #include "Particle.h" -class BubbleParticle : public Particle -{ +class BubbleParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_BUBBLEPARTICLE; } - BubbleParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - virtual void tick(); + virtual eINSTANCEOF GetType() { return eType_BUBBLEPARTICLE; } + BubbleParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle.cpp b/Minecraft.Client/Rendering/Particles/CritParticle.cpp index 8f142f2e6..11457da37 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/CritParticle.cpp @@ -5,57 +5,54 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -void CritParticle::_init(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type) -{ - life = 0; - this->entity = entity; - lifeTime = 3; - particleName = type; - // 4J-PB - can't use a shared_from_this in the constructor - //tick(); +void CritParticle::_init(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type) { + life = 0; + this->entity = entity; + lifeTime = 3; + particleName = type; + // 4J-PB - can't use a shared_from_this in the constructor + // tick(); } -CritParticle::CritParticle(Level *level, std::shared_ptr entity) : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, entity->z, entity->xd, entity->yd, entity->zd) -{ - _init(level,entity,eParticleType_crit); +CritParticle::CritParticle(Level* level, std::shared_ptr entity) + : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, + entity->z, entity->xd, entity->yd, entity->zd) { + _init(level, entity, eParticleType_crit); } -CritParticle::CritParticle(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type) : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, entity->z, entity->xd, entity->yd, entity->zd) -{ - _init(level, entity, type); +CritParticle::CritParticle(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type) + : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, + entity->z, entity->xd, entity->yd, entity->zd) { + _init(level, entity, type); } -// 4J - Added this so that we can use some std::shared_ptr functions that were needed in the ctor -void CritParticle::CritParticlePostConstructor(void) -{ - tick(); +// 4J - Added this so that we can use some std::shared_ptr functions that were +// needed in the ctor +void CritParticle::CritParticlePostConstructor(void) { tick(); } + +void CritParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) {} + +void CritParticle::tick() { + for (int i = 0; i < 16; i++) { + double xa = random->nextFloat() * 2 - 1; + double ya = random->nextFloat() * 2 - 1; + double za = random->nextFloat() * 2 - 1; + if (xa * xa + ya * ya + za * za > 1) continue; + double x = entity->x + xa * entity->bbWidth / 4; + double y = + entity->bb->y0 + entity->bbHeight / 2 + ya * entity->bbHeight / 4; + double z = entity->z + za * entity->bbWidth / 4; + level->addParticle(particleName, x, y, z, xa, ya + 0.2, za); + } + life++; + if (life >= lifeTime) { + remove(); + } } -void CritParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ -} - -void CritParticle::tick() -{ - for (int i=0; i<16; i++) - { - double xa = random->nextFloat()*2-1; - double ya = random->nextFloat()*2-1; - double za = random->nextFloat()*2-1; - if (xa*xa+ya*ya+za*za>1) continue; - double x = entity->x+xa*entity->bbWidth/4; - double y = entity->bb->y0+entity->bbHeight/2+ya*entity->bbHeight/4; - double z = entity->z+za*entity->bbWidth/4; - level->addParticle(particleName, x, y, z, xa, ya+0.2, za); - } - life++; - if (life >= lifeTime) - { - remove(); - } -} - -int CritParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int CritParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle.h b/Minecraft.Client/Rendering/Particles/CritParticle.h index 5bad1c251..22ae938dd 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle.h +++ b/Minecraft.Client/Rendering/Particles/CritParticle.h @@ -4,22 +4,24 @@ class Entity; -class CritParticle : public Particle -{ +class CritParticle : public Particle { private: - std::shared_ptr entity; - int life; - int lifeTime; - ePARTICLE_TYPE particleName; + std::shared_ptr entity; + int life; + int lifeTime; + ePARTICLE_TYPE particleName; - void _init(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type); + void _init(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type); public: - virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE; } - CritParticle(Level *level, std::shared_ptr entity); - CritParticle(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type); - void CritParticlePostConstructor(void); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE; } + CritParticle(Level* level, std::shared_ptr entity); + CritParticle(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type); + void CritParticlePostConstructor(void); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle2.cpp b/Minecraft.Client/Rendering/Particles/CritParticle2.cpp index 2c01bd48f..cd9f40d32 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle2.cpp +++ b/Minecraft.Client/Rendering/Particles/CritParticle2.cpp @@ -2,92 +2,82 @@ #include "CritParticle2.h" #include "../../../Minecraft.World/Util/JavaMath.h" -void CritParticle2::_init(double xa, double ya, double za, float scale) -{ - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa * 0.4; - yd += ya * 0.4; - zd += za * 0.4; +void CritParticle2::_init(double xa, double ya, double za, float scale) { + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa * 0.4; + yd += ya * 0.4; + zd += za * 0.4; - rCol = gCol = bCol = (float) (Math::random() * 0.3f + 0.6f); - size *= 0.75f; - size *= scale; - oSize = size; + rCol = gCol = bCol = (float)(Math::random() * 0.3f + 0.6f); + size *= 0.75f; + size *= scale; + oSize = size; - lifetime = (int) (6 / (Math::random() * 0.8 + 0.6)); - lifetime *= scale; - noPhysics = false; + lifetime = (int)(6 / (Math::random() * 0.8 + 0.6)); + lifetime *= scale; + noPhysics = false; - setMiscTex(16 * 4 + 1); - // 4J-PB - can't use a shared_from_this in the constructor - //tick(); - m_bAgeUniformly=false; // 4J added + setMiscTex(16 * 4 + 1); + // 4J-PB - can't use a shared_from_this in the constructor + // tick(); + m_bAgeUniformly = false; // 4J added } -CritParticle2::CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(xa,ya,za,1); +CritParticle2::CritParticle2(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + _init(xa, ya, za, 1); } -CritParticle2::CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(xa,ya,za,scale); +CritParticle2::CritParticle2(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + _init(xa, ya, za, scale); } -void CritParticle2::CritParticle2PostConstructor(void) -{ - tick(); +void CritParticle2::CritParticle2PostConstructor(void) { tick(); } + +void CritParticle2::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; + + size = oSize * l; + Particle::render(t, a, xa, ya, za, xa2, za2); } -void CritParticle2::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; +void CritParticle2::SetAgeUniformly() { m_bAgeUniformly = true; } - size = oSize * l; - Particle::render(t, a, xa, ya, za, xa2, za2); -} - -void CritParticle2::SetAgeUniformly() -{ - m_bAgeUniformly=true; -} - -void CritParticle2::tick() -{ - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - move(xd, yd, zd); - gCol *= 0.96; - bCol *= 0.9; - - if(m_bAgeUniformly) - { - rCol *= 0.99; - gCol *= 0.99; - bCol *= 0.99; - } - else - { - gCol *= 0.96; - bCol *= 0.9; - } - - xd *= 0.70f; - yd *= 0.70f; - zd *= 0.70f; - yd-=0.02f; - - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } +void CritParticle2::tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + move(xd, yd, zd); + gCol *= 0.96; + bCol *= 0.9; + + if (m_bAgeUniformly) { + rCol *= 0.99; + gCol *= 0.99; + bCol *= 0.99; + } else { + gCol *= 0.96; + bCol *= 0.9; + } + + xd *= 0.70f; + yd *= 0.70f; + zd *= 0.70f; + yd -= 0.02f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } diff --git a/Minecraft.Client/Rendering/Particles/CritParticle2.h b/Minecraft.Client/Rendering/Particles/CritParticle2.h index 3febb0ffe..10fdffcb1 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle2.h +++ b/Minecraft.Client/Rendering/Particles/CritParticle2.h @@ -2,18 +2,20 @@ #include "Particle.h" -class CritParticle2 : public Particle -{ -public: - float oSize; - bool m_bAgeUniformly; // 4J added for Halo texture pack +class CritParticle2 : public Particle { +public: + float oSize; + bool m_bAgeUniformly; // 4J added for Halo texture pack - virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE2; } - void _init(double xa, double ya, double za, float scale); - CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za); - CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - void CritParticle2PostConstructor(void); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - void SetAgeUniformly(); + virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE2; } + void _init(double xa, double ya, double za, float scale); + CritParticle2(Level* level, double x, double y, double z, double xa, + double ya, double za); + CritParticle2(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + void CritParticle2PostConstructor(void); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + void SetAgeUniformly(); }; diff --git a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp index 53f9bd3e2..ca58a3250 100644 --- a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp @@ -2,47 +2,55 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "DragonBreathParticle.h" -void DragonBreathParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void DragonBreathParticle::init(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; - xd = xa; //+= xa; - yd = ya; //+= ya; - zd = za; //+= za; + xd = xa; //+= xa; + yd = ya; //+= ya; + zd = za; //+= za; - unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DragonBreathMin ); //0xb700d2 - unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DragonBreathMax ); //0xdf00f9 - double rMin = ( (cMin>>16)&0xFF )/255.0f, gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; - double rMax = ( (cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF )/255.0; + unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DragonBreathMin); // 0xb700d2 + unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DragonBreathMax); // 0xdf00f9 + double rMin = ((cMin >> 16) & 0xFF) / 255.0f, + gMin = ((cMin >> 8) & 0xFF) / 255.0, bMin = (cMin & 0xFF) / 255.0; + double rMax = ((cMax >> 16) & 0xFF) / 255.0f, + gMax = ((cMax >> 8) & 0xFF) / 255.0, bMax = (cMax & 0xFF) / 255.0; - rCol = (rMax - rMin) * Math::random() + rMin; // 184/255 -- 224/255 - gCol = (gMax - gMin) * Math::random() + gMin; // 0,0 - bCol = (bMax - bMin) * Math::random() + bMin; // 210/255 -- 250/255 + rCol = (rMax - rMin) * Math::random() + rMin; // 184/255 -- 224/255 + gCol = (gMax - gMin) * Math::random() + gMin; // 0,0 + bCol = (bMax - bMin) * Math::random() + bMin; // 210/255 -- 250/255 size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = (int)(20 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; - m_bHasHitGround = false; + m_bHasHitGround = false; } -DragonBreathParticle::DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 1); +DragonBreathParticle::DragonBreathParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 1); } -DragonBreathParticle::DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +DragonBreathParticle::DragonBreathParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void DragonBreathParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void DragonBreathParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; @@ -51,54 +59,49 @@ void DragonBreathParticle::render(Tesselator *t, float a, float xa, float ya, fl Particle::render(t, a, xa, ya, za, xa2, za2); } -void DragonBreathParticle::tick() -{ +void DragonBreathParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - setMiscTex( ( 3 * age / lifetime) + 5 ); + setMiscTex((3 * age / lifetime) + 5); - if(onGround) - { - yd = 0; - m_bHasHitGround = true; - } + if (onGround) { + yd = 0; + m_bHasHitGround = true; + } - if(m_bHasHitGround) yd += 0.002; //0.004; + if (m_bHasHitGround) yd += 0.002; // 0.004; move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } xd *= 0.96f; zd *= 0.96f; - if(m_bHasHitGround) yd *= 0.96f; + if (m_bHasHitGround) yd *= 0.96f; - // if (onGround) - //{ - // xd *= 0.7f; - // zd *= 0.7f; - // } + // if (onGround) + //{ + // xd *= 0.7f; + // zd *= 0.7f; + // } } -int DragonBreathParticle::getParticleTexture() -{ - return ParticleEngine::DRAGON_BREATH_TEXTURE; +int DragonBreathParticle::getParticleTexture() { + return ParticleEngine::DRAGON_BREATH_TEXTURE; } -float DragonBreathParticle::getBrightness(float a) -{ - float l = ((age + a) / lifetime) * 32; +float DragonBreathParticle::getBrightness(float a) { + float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; - float brightness = (0.5f / l) + 0.5f; + float brightness = (0.5f / l) + 0.5f; - return brightness; + return brightness; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h index e9199d7c1..dfb9cf2f2 100644 --- a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h +++ b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h @@ -1,20 +1,24 @@ #pragma once #include "Particle.h" -class DragonBreathParticle : public Particle -{ +class DragonBreathParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eTYPE_DRAGONBREATHPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_DRAGONBREATHPARTICLE; } + private: - bool m_bHasHitGround; - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + bool m_bHasHitGround; + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + DragonBreathParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + DragonBreathParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); - virtual int getParticleTexture(); - virtual float getBrightness(float a); + virtual int getParticleTexture(); + virtual float getBrightness(float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/DripParticle.cpp b/Minecraft.Client/Rendering/Particles/DripParticle.cpp index a66e38fdd..be5e8f889 100644 --- a/Minecraft.Client/Rendering/Particles/DripParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/DripParticle.cpp @@ -6,127 +6,126 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "DripParticle.h" -DripParticle::DripParticle(Level *level, double x, double y, double z, Material *material) : Particle(level, x, y, z, 0, 0, 0) -{ - xd = yd = zd = 0; +DripParticle::DripParticle(Level* level, double x, double y, double z, + Material* material) + : Particle(level, x, y, z, 0, 0, 0) { + xd = yd = zd = 0; - unsigned int clr; - if (material == Material::water) - { - clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripWater); - } - else - { - clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaStart ); - } + unsigned int clr; + if (material == Material::water) { + clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripWater); + } else { + clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaStart); + } - rCol = ( (clr>>16)&0xFF )/255.0f; - gCol = ( (clr>>8)&0xFF )/255.0; - bCol = ( clr&0xFF )/255.0; + rCol = ((clr >> 16) & 0xFF) / 255.0f; + gCol = ((clr >> 8) & 0xFF) / 255.0; + bCol = (clr & 0xFF) / 255.0; - setMiscTex(16 * 7 + 1); - this->setSize(0.01f, 0.01f); - gravity = 0.06f; - this->material = material; - stuckTime = 40; + setMiscTex(16 * 7 + 1); + this->setSize(0.01f, 0.01f); + gravity = 0.06f; + this->material = material; + stuckTime = 40; - lifetime = (int) (64 / (Math::random() * 0.8 + 0.2)); - xd = yd = zd = 0; + lifetime = (int)(64 / (Math::random() * 0.8 + 0.2)); + xd = yd = zd = 0; } -int DripParticle::getLightColor(float a) -{ - if (material == Material::water) return Particle::getLightColor(a); - - // 4J-JEV: Looks like this value was never used on the java version, - // but it is on ours, so I've changed this to be bright manualy. - int s = 0x0f; - int b = 0x0f; - return s << 20 | b << 4; // MGH changed this to a proper value as PS3 wasn't clamping the values. +int DripParticle::getLightColor(float a) { + if (material == Material::water) return Particle::getLightColor(a); + + // 4J-JEV: Looks like this value was never used on the java version, + // but it is on ours, so I've changed this to be bright manualy. + int s = 0x0f; + int b = 0x0f; + return s << 20 | b << 4; // MGH changed this to a proper value as PS3 + // wasn't clamping the values. } -float DripParticle::getBrightness(float a) -{ - if (material == Material::water) return Particle::getBrightness(a); - else return 1.0f; +float DripParticle::getBrightness(float a) { + if (material == Material::water) + return Particle::getBrightness(a); + else + return 1.0f; } -void DripParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void DripParticle::tick() { + xo = x; + yo = y; + zo = z; - if (material == Material::water) - { - //rCol = 0.2f; - //gCol = 0.3f; - //bCol = 1.0f; + if (material == Material::water) { + // rCol = 0.2f; + // gCol = 0.3f; + // bCol = 1.0f; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripWater); - rCol = ( (clr>>16)&0xFF )/255.0f; - gCol = ( (clr>>8)&0xFF )/255.0; - bCol = ( clr&0xFF )/255.0; - } - else - { - //rCol = 1.0f; - //gCol = 16.0f / (40 - stuckTime + 16); - //bCol = 4.0f / (40 - stuckTime + 8); + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripWater); + rCol = ((clr >> 16) & 0xFF) / 255.0f; + gCol = ((clr >> 8) & 0xFF) / 255.0; + bCol = (clr & 0xFF) / 255.0; + } else { + // rCol = 1.0f; + // gCol = 16.0f / (40 - stuckTime + 16); + // bCol = 4.0f / (40 - stuckTime + 8); - unsigned int cStart = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaStart ); - unsigned int cEnd = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaEnd ); - double rStart = ( (cStart>>16)&0xFF )/255.0f, gStart = ( (cStart>>8)&0xFF )/255.0, bStart = ( cStart&0xFF )/255.0; - double rEnd = ( (cEnd>>16)&0xFF )/255.0f, gEnd = ( (cEnd>>8)&0xFF )/255.0, bEnd = ( cEnd&0xFF )/255.0; + unsigned int cStart = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaStart); + unsigned int cEnd = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaEnd); + double rStart = ((cStart >> 16) & 0xFF) / 255.0f, + gStart = ((cStart >> 8) & 0xFF) / 255.0, + bStart = (cStart & 0xFF) / 255.0; + double rEnd = ((cEnd >> 16) & 0xFF) / 255.0f, + gEnd = ((cEnd >> 8) & 0xFF) / 255.0, + bEnd = (cEnd & 0xFF) / 255.0; - float variance = (40 - stuckTime); - rCol = rStart - ((rStart - rEnd)/40) * variance; - gCol = gStart - ((gStart - gEnd)/40) * variance; - bCol = bStart - ((bStart - bEnd)/40) * variance; - } + float variance = (40 - stuckTime); + rCol = rStart - ((rStart - rEnd) / 40) * variance; + gCol = gStart - ((gStart - gEnd) / 40) * variance; + bCol = bStart - ((bStart - bEnd) / 40) * variance; + } - yd -= gravity; - if (stuckTime-- > 0) - { - xd *= 0.02; - yd *= 0.02; - zd *= 0.02; - setMiscTex(16 * 7 + 1); - } - else - { - setMiscTex(16 * 7 + 0); - } - move(xd, yd, zd); - xd *= 0.98f; - yd *= 0.98f; - zd *= 0.98f; + yd -= gravity; + if (stuckTime-- > 0) { + xd *= 0.02; + yd *= 0.02; + zd *= 0.02; + setMiscTex(16 * 7 + 1); + } else { + setMiscTex(16 * 7 + 0); + } + move(xd, yd, zd); + xd *= 0.98f; + yd *= 0.98f; + zd *= 0.98f; - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); - if (onGround) - { - if (material == Material::water) - { - remove(); - level->addParticle(eParticleType_splash, x, y, z, 0, 0, 0); - } - else - { - setMiscTex(16 * 7 + 2); + if (onGround) { + if (material == Material::water) { + remove(); + level->addParticle(eParticleType_splash, x, y, z, 0, 0, 0); + } else { + setMiscTex(16 * 7 + 2); + } + xd *= 0.7f; + zd *= 0.7f; + } - } - xd *= 0.7f; - zd *= 0.7f; - } - - Material *m = level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - if (m->isLiquid() || m->isSolid()) - { - double y0 = Mth::floor(y) + 1 - LiquidTile::getHeight(level->getData(Mth::floor(x), Mth::floor(y), Mth::floor(z))); - if (y < y0) - { - remove(); - } - } + Material* m = + level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + if (m->isLiquid() || m->isSolid()) { + double y0 = Mth::floor(y) + 1 - + LiquidTile::getHeight(level->getData( + Mth::floor(x), Mth::floor(y), Mth::floor(z))); + if (y < y0) { + remove(); + } + } } diff --git a/Minecraft.Client/Rendering/Particles/DripParticle.h b/Minecraft.Client/Rendering/Particles/DripParticle.h index 1549c3384..7c0b62364 100644 --- a/Minecraft.Client/Rendering/Particles/DripParticle.h +++ b/Minecraft.Client/Rendering/Particles/DripParticle.h @@ -5,18 +5,18 @@ class Level; class Material; -class DripParticle : public Particle -{ +class DripParticle : public Particle { private: - Material *material; - int stuckTime; + Material* material; + int stuckTime; -public: - virtual eINSTANCEOF GetType() { return eTYPE_DRIPPARTICLE; } +public: + virtual eINSTANCEOF GetType() { return eTYPE_DRIPPARTICLE; } - DripParticle(Level *level, double x, double y, double z, Material *material); + DripParticle(Level* level, double x, double y, double z, + Material* material); - virtual int getLightColor(float a); - virtual float getBrightness(float a); - virtual void tick(); + virtual int getLightColor(float a); + virtual float getBrightness(float a); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp index 113edbff2..ff20c175f 100644 --- a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp @@ -2,70 +2,71 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "EnchantmentTableParticle.h" -EchantmentTableParticle::EchantmentTableParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; - this->xStart = this->x = x; - this->yStart = this->y = y; - this->zStart = this->z = z; +EchantmentTableParticle::EchantmentTableParticle(Level* level, double x, + double y, double z, double xd, + double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; + this->xStart = this->x = x; + this->yStart = this->y = y; + this->zStart = this->z = z; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_EnchantmentTable ); //0xE5E5FF - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_EnchantmentTable); // 0xE5E5FF + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; - float br = random->nextFloat() * 0.6f + 0.4f; - rCol = r * br; - gCol = g * br; - bCol = b * br; + float br = random->nextFloat() * 0.6f + 0.4f; + rCol = r * br; + gCol = g * br; + bCol = b * br; - oSize = size = random->nextFloat() * 0.5f + 0.2f; + oSize = size = random->nextFloat() * 0.5f + 0.2f; - lifetime = (int) (Math::random() * 10) + 30; - noPhysics = true; - setMiscTex( (int) (Math::random() * 26 + 1 + 14 * 16) ); + lifetime = (int)(Math::random() * 10) + 30; + noPhysics = true; + setMiscTex((int)(Math::random() * 26 + 1 + 14 * 16)); } -int EchantmentTableParticle::getLightColor(float a) -{ - int br = Particle::getLightColor(a); +int EchantmentTableParticle::getLightColor(float a) { + int br = Particle::getLightColor(a); - float pos = age / (float) lifetime; - pos = pos * pos; - pos = pos * pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; - int br1 = (br) & 0xff; - int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); - if (br2 > 15 * 16) br2 = 15 * 16; - return br1 | br2 << 16; + int br1 = (br) & 0xff; + int br2 = (br >> 16) & 0xff; + br2 += (int)(pos * 15 * 16); + if (br2 > 15 * 16) br2 = 15 * 16; + return br1 | br2 << 16; } -float EchantmentTableParticle::getBrightness(float a) -{ - float br = Particle::getBrightness(a); - float pos = age / (float) lifetime; - pos = pos * pos; - pos = pos * pos; - return br * (1 - pos) + pos; +float EchantmentTableParticle::getBrightness(float a) { + float br = Particle::getBrightness(a); + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void EchantmentTableParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void EchantmentTableParticle::tick() { + xo = x; + yo = y; + zo = z; - float pos = age / (float) lifetime; + float pos = age / (float)lifetime; - pos = 1 - pos; + pos = 1 - pos; - float pp = 1 - pos; - pp = pp * pp; - pp = pp * pp; - x = xStart + xd * pos; - y = yStart + yd * pos - pp * 1.2f; - z = zStart + zd * pos; + float pp = 1 - pos; + pp = pp * pp; + pp = pp * pp; + x = xStart + xd * pos; + y = yStart + yd * pos - pp * 1.2f; + z = zStart + zd * pos; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h index 98b027c60..334655d5f 100644 --- a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h +++ b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h @@ -4,18 +4,18 @@ class Level; -class EchantmentTableParticle : public Particle -{ +class EchantmentTableParticle : public Particle { private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - virtual eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEPARTICLE; } - EchantmentTableParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); + EchantmentTableParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd); - virtual int getLightColor(float a); - virtual float getBrightness(float a); - virtual void tick(); + virtual int getLightColor(float a); + virtual float getBrightness(float a); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnderParticle.cpp b/Minecraft.Client/Rendering/Particles/EnderParticle.cpp index 9b786d009..5e9458e32 100644 --- a/Minecraft.Client/Rendering/Particles/EnderParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/EnderParticle.cpp @@ -3,11 +3,13 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "../../../Minecraft.World/Util/Random.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use +// this particle -EnderParticle::EnderParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ +EnderParticle::EnderParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { this->xd = xd; this->yd = yd; this->zd = zd; @@ -15,80 +17,80 @@ EnderParticle::EnderParticle(Level *level, double x, double y, double z, double this->yStart = this->y = y; this->zStart = this->z = z; - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Ender ); //0xE54CFF - rCol = ( (col>>16)&0xFF )/255.0f, gCol = ( (col>>8)&0xFF )/255.0, bCol = ( col&0xFF )/255.0; + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Ender); // 0xE54CFF + rCol = ((col >> 16) & 0xFF) / 255.0f, gCol = ((col >> 8) & 0xFF) / 255.0, + bCol = (col & 0xFF) / 255.0; float br = random->nextFloat() * 0.6f + 0.4f; - rCol *= br; gCol *= br; bCol *= br; + rCol *= br; + gCol *= br; + bCol *= br; - //rCol = gCol = bCol = 1.0f*br; - //gCol *= 0.3f; - //rCol *= 0.9f; + // rCol = gCol = bCol = 1.0f*br; + // gCol *= 0.3f; + // rCol *= 0.9f; - oSize = size = random->nextFloat()*0.2f+0.5f; + oSize = size = random->nextFloat() * 0.2f + 0.5f; - lifetime = (int) (Math::random()*10) + 40; + lifetime = (int)(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex((int)(Math::random() * 8)); } -void EnderParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - s = 1-s; - s = s*s; - s = 1-s; +void EnderParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float s = (age + a) / (float)lifetime; + s = 1 - s; + s = s * s; + s = 1 - s; size = oSize * (s); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int EnderParticle::getLightColor(float a) -{ +int EnderParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += (int)(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } -float EnderParticle::getBrightness(float a) -{ +float EnderParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - return br*(1-pos)+pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void EnderParticle::tick() -{ +void EnderParticle::tick() { xo = x; yo = y; zo = z; - - float pos = age/(float)lifetime; + + float pos = age / (float)lifetime; float a = pos; - pos = -pos+pos*pos*2; -// pos = pos*pos; -// pos = pos*pos; - pos = 1-pos; - - x = xStart+xd*pos; - y = yStart+yd*pos+(1-a); - z = zStart+zd*pos; - - -// spd+=0.002/lifetime*age; + pos = -pos + pos * pos * 2; + // pos = pos*pos; + // pos = pos*pos; + pos = 1 - pos; + + x = xStart + xd * pos; + y = yStart + yd * pos + (1 - a); + z = zStart + zd * pos; + + // spd+=0.002/lifetime*age; if (age++ >= lifetime) remove(); -// move(xd*spd, yd*spd, zd*spd); + // move(xd*spd, yd*spd, zd*spd); } diff --git a/Minecraft.Client/Rendering/Particles/EnderParticle.h b/Minecraft.Client/Rendering/Particles/EnderParticle.h index 56b75b61e..5da1cf44d 100644 --- a/Minecraft.Client/Rendering/Particles/EnderParticle.h +++ b/Minecraft.Client/Rendering/Particles/EnderParticle.h @@ -1,21 +1,24 @@ #pragma once #include "Particle.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use +// this particle -class EnderParticle : public Particle -{ +class EnderParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_ENDERPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_ENDERPARTICLE; } + private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - EnderParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + EnderParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp b/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp index 11d9e257e..586428892 100644 --- a/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp @@ -3,50 +3,54 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "../../../Minecraft.World/Util/Random.h" -ExplodeParticle::ExplodeParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - xd = xa+(float)(Math::random()*2-1)*0.05f; - yd = ya+(float)(Math::random()*2-1)*0.05f; - zd = za+(float)(Math::random()*2-1)*0.05f; - - //rCol = gCol = bCol = random->nextFloat()*.3f+.7; - - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Explode ); //0xFFFFFF - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; +ExplodeParticle::ExplodeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + xd = xa + (float)(Math::random() * 2 - 1) * 0.05f; + yd = ya + (float)(Math::random() * 2 - 1) * 0.05f; + zd = za + (float)(Math::random() * 2 - 1) * 0.05f; - float br = random->nextFloat() * 0.3f + 0.7f; - rCol = r * br; - gCol = g * br; - bCol = b * br; + // rCol = gCol = bCol = random->nextFloat()*.3f+.7; - size = random->nextFloat()*random->nextFloat()*6+1; - - lifetime = (int)(16/(random->nextFloat()*0.8+0.2))+2; -// noPhysics = true; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Explode); // 0xFFFFFF + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; + + float br = random->nextFloat() * 0.3f + 0.7f; + rCol = r * br; + gCol = g * br; + bCol = b * br; + + size = random->nextFloat() * random->nextFloat() * 6 + 1; + + lifetime = (int)(16 / (random->nextFloat() * 0.8 + 0.2)) + 2; + // noPhysics = true; } -void ExplodeParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); +void ExplodeParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + // 4J - don't render explosion particles that are less than 3 metres away, + // to try and avoid large particles that are causing us problems with + // photosensitivity testing + float x = (float)(xo + (this->x - xo) * a - xOff); + float y = (float)(yo + (this->y - yo) * a - yOff); + float z = (float)(zo + (this->z - zo) * a - zOff); - float distSq = (x*x + y*y + z*z); - if( distSq < (3.0f * 3.0f) ) return; + float distSq = (x * x + y * y + z * z); + if (distSq < (3.0f * 3.0f)) return; - Particle::render(t, a, xa, ya, za, xa2, za2); + Particle::render(t, a, xa, ya, za, xa2, za2); } -void ExplodeParticle::tick() -{ +void ExplodeParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - - setMiscTex(7-age*8/lifetime); + + setMiscTex(7 - age * 8 / lifetime); yd += 0.004; move(xd, yd, zd); @@ -54,8 +58,7 @@ void ExplodeParticle::tick() yd *= 0.90f; zd *= 0.90f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/ExplodeParticle.h b/Minecraft.Client/Rendering/Particles/ExplodeParticle.h index e25243d60..6bace3ea0 100644 --- a/Minecraft.Client/Rendering/Particles/ExplodeParticle.h +++ b/Minecraft.Client/Rendering/Particles/ExplodeParticle.h @@ -1,11 +1,12 @@ #pragma once #include "Particle.h" -class ExplodeParticle : public Particle -{ +class ExplodeParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_EXPLODEPARTICLE; } - ExplodeParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual void tick(); + virtual eINSTANCEOF GetType() { return eType_EXPLODEPARTICLE; } + ExplodeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FlameParticle.cpp b/Minecraft.Client/Rendering/Particles/FlameParticle.cpp index 4ef80a2e1..89106e8e4 100644 --- a/Minecraft.Client/Rendering/Particles/FlameParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/FlameParticle.cpp @@ -3,33 +3,33 @@ #include "../../../Minecraft.World/Util/Random.h" #include "FlameParticle.h" -FlameParticle::FlameParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ - this->xd=this->xd*0.01f+xd; - this->yd=this->yd*0.01f+yd; - this->zd=this->zd*0.01f+zd; - x+=(random->nextFloat()-random->nextFloat())*0.05f; - y+=(random->nextFloat()-random->nextFloat())*0.05f; - z+=(random->nextFloat()-random->nextFloat())*0.05f; - +FlameParticle::FlameParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { + this->xd = this->xd * 0.01f + xd; + this->yd = this->yd * 0.01f + yd; + this->zd = this->zd * 0.01f + zd; + x += (random->nextFloat() - random->nextFloat()) * 0.05f; + y += (random->nextFloat() - random->nextFloat()) * 0.05f; + z += (random->nextFloat() - random->nextFloat()) * 0.05f; + oSize = size; rCol = gCol = bCol = 1.0f; - - lifetime = (int)(8/(Math::random()*0.8+0.2))+4; + + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)) + 4; noPhysics = true; setMiscTex(48); } -void FlameParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - size = oSize * (1 - s*s*0.5f); +void FlameParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float s = (age + a) / (float)lifetime; + size = oSize * (1 - s * s * 0.5f); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int FlameParticle::getLightColor(float a) -{ +int FlameParticle::getLightColor(float a) { float l = (age + a) / lifetime; if (l < 0) l = 0; if (l > 1) l = 1; @@ -37,23 +37,21 @@ int FlameParticle::getLightColor(float a) int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br1 += (int) (l * 15 * 16); + br1 += (int)(l * 15 * 16); if (br1 > 15 * 16) br1 = 15 * 16; return br1 | br2 << 16; } -float FlameParticle::getBrightness(float a) -{ - float l = (age+a)/lifetime; - if (l<0) l = 0; - if (l>1) l = 1; - float br = Particle::getBrightness(a); - - return br*l+(1-l); +float FlameParticle::getBrightness(float a) { + float l = (age + a) / lifetime; + if (l < 0) l = 0; + if (l > 1) l = 1; + float br = Particle::getBrightness(a); + + return br * l + (1 - l); } -void FlameParticle::tick() -{ +void FlameParticle::tick() { xo = x; yo = y; zo = z; @@ -65,8 +63,7 @@ void FlameParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/FlameParticle.h b/Minecraft.Client/Rendering/Particles/FlameParticle.h index 7097d9dc4..a0fb9f691 100644 --- a/Minecraft.Client/Rendering/Particles/FlameParticle.h +++ b/Minecraft.Client/Rendering/Particles/FlameParticle.h @@ -1,17 +1,19 @@ #pragma once #include "Particle.h" -class FlameParticle : public Particle -{ +class FlameParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_FLAMEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_FLAMEPARTICLE; } + private: - float oSize; - + float oSize; + public: - FlameParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + FlameParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp b/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp index 8d4e9d86c..40961989c 100644 --- a/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp @@ -5,19 +5,20 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -FootstepParticle::FootstepParticle(Textures *textures, Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ - // 4J added initialisers - life = 0; - lifeTime = 0; +FootstepParticle::FootstepParticle(Textures* textures, Level* level, double x, + double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { + // 4J added initialisers + life = 0; + lifeTime = 0; - this->textures = textures; - xd = yd = zd = 0; - lifeTime = 200; + this->textures = textures; + xd = yd = zd = 0; + lifeTime = 200; } -void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void FootstepParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float time = (life + a) / lifeTime; time = time * time; @@ -28,36 +29,38 @@ void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float glDisable(GL_LIGHTING); float r = 2 / 16.0f; - float xx = (float) (x - xOff); - float yy = (float) (y - yOff); - float zz = (float) (z - zOff); + float xx = (float)(x - xOff); + float yy = (float)(y - yOff); + float zz = (float)(z - zOff); - float br = level->getBrightness(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + float br = + level->getBrightness(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - textures->bindTexture(TN_MISC_FOOTSTEP);//L"/misc/footprint.png")); + textures->bindTexture(TN_MISC_FOOTSTEP); // L"/misc/footprint.png")); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); t->begin(); t->color(br, br, br, alpha); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz + r), (float)( 0), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz + r), (float)( 1), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz - r), (float)( 1), (float)( 0)); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz - r), (float)( 0), (float)( 0)); + t->vertexUV((float)(xx - r), (float)(yy), (float)(zz + r), (float)(0), + (float)(1)); + t->vertexUV((float)(xx + r), (float)(yy), (float)(zz + r), (float)(1), + (float)(1)); + t->vertexUV((float)(xx + r), (float)(yy), (float)(zz - r), (float)(1), + (float)(0)); + t->vertexUV((float)(xx - r), (float)(yy), (float)(zz - r), (float)(0), + (float)(0)); t->end(); glDisable(GL_BLEND); glEnable(GL_LIGHTING); - } -void FootstepParticle::tick() -{ +void FootstepParticle::tick() { life++; if (life == lifeTime) remove(); } -int FootstepParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int FootstepParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FootstepParticle.h b/Minecraft.Client/Rendering/Particles/FootstepParticle.h index 50e5e36d1..398b6addd 100644 --- a/Minecraft.Client/Rendering/Particles/FootstepParticle.h +++ b/Minecraft.Client/Rendering/Particles/FootstepParticle.h @@ -2,18 +2,20 @@ #include "Particle.h" class Textures; -class FootstepParticle : public Particle -{ +class FootstepParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_FOOTSTEPPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_FOOTSTEPPARTICLE; } + private: - int life; + int life; int lifeTime; - Textures *textures; + Textures* textures; public: - FootstepParticle(Textures *textures, Level *level, double x, double y, double z); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + FootstepParticle(Textures* textures, Level* level, double x, double y, + double z); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); virtual int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticle.cpp b/Minecraft.Client/Rendering/Particles/GuiParticle.cpp index 27c828da9..85497e989 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/GuiParticle.cpp @@ -2,17 +2,16 @@ #include "GuiParticle.h" #include "../../../Minecraft.World/Util/Random.h" -Random *GuiParticle::random = new Random(); +Random* GuiParticle::random = new Random(); -GuiParticle::GuiParticle(double x, double y, double xa, double ya) -{ - // 4J - added initialisation block +GuiParticle::GuiParticle(double x, double y, double xa, double ya) { + // 4J - added initialisation block removed = false; life = 0; a = 1; oR = oG = oB = oA = 0; - - this->xo = this->x = x; + + this->xo = this->x = x; this->yo = this->y = y; this->xa = xa; this->ya = ya; @@ -24,11 +23,10 @@ GuiParticle::GuiParticle(double x, double y, double xa, double ya) friction = 1.0 / (random->nextDouble() * 0.05 + 1.01); - lifeTime = (int) (10.0 / (random->nextDouble() * 2 + 0.1)); + lifeTime = (int)(10.0 / (random->nextDouble() * 2 + 0.1)); } -void GuiParticle::tick(GuiParticles *guiParticles) -{ +void GuiParticle::tick(GuiParticles* guiParticles) { x += xa; y += ya; @@ -37,14 +35,13 @@ void GuiParticle::tick(GuiParticles *guiParticles) ya += 0.1; if (++life > lifeTime) remove(); - a = 2 - (life / (double) lifeTime) * 2; + a = 2 - (life / (double)lifeTime) * 2; if (a > 1) a = 1; a = a * a; a *= 0.5; } -void GuiParticle::preTick() -{ +void GuiParticle::preTick() { oR = r; oG = g; oB = b; @@ -54,7 +51,4 @@ void GuiParticle::preTick() yo = y; } -void GuiParticle::remove() -{ - removed = true; -} \ No newline at end of file +void GuiParticle::remove() { removed = true; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticle.h b/Minecraft.Client/Rendering/Particles/GuiParticle.h index 27b14a69e..60434a1e3 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticle.h +++ b/Minecraft.Client/Rendering/Particles/GuiParticle.h @@ -2,13 +2,12 @@ class GuiParticles; class Random; -class GuiParticle -{ +class GuiParticle { private: - static Random *random; + static Random* random; public: - double x, y; + double x, y; double xo, yo; double xa, ya; double friction; @@ -16,10 +15,11 @@ public: int life, lifeTime; double r, g, b, a; - double oR, oG, oB, oA; // MGH - remaned these, as PS3 complained about "or" var name + double oR, oG, oB, + oA; // MGH - remaned these, as PS3 complained about "or" var name GuiParticle(double x, double y, double xa, double ya); - void tick(GuiParticles *guiParticles); + void tick(GuiParticles* guiParticles); void preTick(); void remove(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticles.cpp b/Minecraft.Client/Rendering/Particles/GuiParticles.cpp index 3311854f5..c60ffcd81 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticles.cpp +++ b/Minecraft.Client/Rendering/Particles/GuiParticles.cpp @@ -3,37 +3,29 @@ #include "GuiParticle.h" #include "../../Textures/Textures.h" -GuiParticles::GuiParticles(Minecraft *mc) -{ - this->mc = mc; -} +GuiParticles::GuiParticles(Minecraft* mc) { this->mc = mc; } -void GuiParticles::tick() -{ - for (unsigned int i = 0; i < particles.size(); i++) - { - GuiParticle *gp = particles[i]; +void GuiParticles::tick() { + for (unsigned int i = 0; i < particles.size(); i++) { + GuiParticle* gp = particles[i]; gp->preTick(); gp->tick(this); - if (gp->removed) - { - particles.erase(particles.begin()+i); - i--; + if (gp->removed) { + particles.erase(particles.begin() + i); + i--; } } } -void GuiParticles::add(GuiParticle *guiParticle) -{ +void GuiParticles::add(GuiParticle* guiParticle) { particles.push_back(guiParticle); guiParticle->preTick(); } -void GuiParticles::render(float a) -{ - // 4J Stu - Never used +void GuiParticles::render(float a) { + // 4J Stu - Never used #if 0 mc->textures->bindTexture(L"/gui/particles.png"); diff --git a/Minecraft.Client/Rendering/Particles/GuiParticles.h b/Minecraft.Client/Rendering/Particles/GuiParticles.h index 82be7ec60..4c277f4f7 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticles.h +++ b/Minecraft.Client/Rendering/Particles/GuiParticles.h @@ -4,16 +4,14 @@ class GuiParticle; class Minecraft; - -class GuiParticles : public GuiComponent -{ +class GuiParticles : public GuiComponent { private: - std::vector particles; - Minecraft *mc; + std::vector particles; + Minecraft* mc; public: - GuiParticles(Minecraft *mc); + GuiParticles(Minecraft* mc); void tick(); - void add(GuiParticle *guiParticle); + void add(GuiParticle* guiParticle); void render(float a); }; diff --git a/Minecraft.Client/Rendering/Particles/HeartParticle.cpp b/Minecraft.Client/Rendering/Particles/HeartParticle.cpp index 7109c688a..cb77054ce 100644 --- a/Minecraft.Client/Rendering/Particles/HeartParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HeartParticle.cpp @@ -2,8 +2,8 @@ #include "HeartParticle.h" // 4J - added -void HeartParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void HeartParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.01f; yd *= 0.01f; zd *= 0.01f; @@ -16,22 +16,23 @@ void HeartParticle::init(Level *level, double x, double y, double z, double xa, lifetime = 16; noPhysics = false; - setMiscTex(16 * 5); } -HeartParticle::HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 2); +HeartParticle::HeartParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 2); } -HeartParticle::HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level,x,y,z,xa,ya,za,scale); +HeartParticle::HeartParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void HeartParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void HeartParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; @@ -40,8 +41,7 @@ void HeartParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void HeartParticle::tick() -{ +void HeartParticle::tick() { xo = x; yo = y; zo = z; @@ -49,8 +49,7 @@ void HeartParticle::tick() if (age++ >= lifetime) remove(); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -58,8 +57,7 @@ void HeartParticle::tick() yd *= 0.86f; zd *= 0.86f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/HeartParticle.h b/Minecraft.Client/Rendering/Particles/HeartParticle.h index f249325ef..9c9ef358f 100644 --- a/Minecraft.Client/Rendering/Particles/HeartParticle.h +++ b/Minecraft.Client/Rendering/Particles/HeartParticle.h @@ -1,19 +1,23 @@ #pragma once #include "Particle.h" -class HeartParticle : public Particle -{ +class HeartParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_HEARTPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_HEARTPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J added public: - HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + HeartParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); + HeartParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp index e57961054..eefda7f41 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp @@ -5,78 +5,79 @@ #include "../Tesselator.h" #include "../Lighting.h" -HugeExplosionParticle::HugeExplosionParticle(Textures *textures, Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - life = 0; +HugeExplosionParticle::HugeExplosionParticle(Textures* textures, Level* level, + double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + life = 0; - this->textures = textures; - lifeTime = 6 + random->nextInt(4); + this->textures = textures; + lifeTime = 6 + random->nextInt(4); - // rCol = gCol = bCol = random->nextFloat() * 0.6f + 0.4f; + // rCol = gCol = bCol = random->nextFloat() * 0.6f + 0.4f; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_HugeExplosion ); //0x999999 - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_HugeExplosion); // 0x999999 + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; - double br = random->nextFloat() * 0.6 + 0.4; - rCol = r * br; - gCol = g * br; - bCol = b * br; - - size = 1 - (float) xa * 0.5f; + double br = random->nextFloat() * 0.6 + 0.4; + rCol = r * br; + gCol = g * br; + bCol = b * br; + + size = 1 - (float)xa * 0.5f; } -void HugeExplosionParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - int tex = (int) ((life + a) * 15 / lifeTime); - if (tex > 15) return; - textures->bindTexture(TN_MISC_EXPLOSION); // 4J was "/misc/explosion.png" +void HugeExplosionParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + int tex = (int)((life + a) * 15 / lifeTime); + if (tex > 15) return; + textures->bindTexture(TN_MISC_EXPLOSION); // 4J was "/misc/explosion.png" - float u0 = (tex % 4) / 4.0f; - float u1 = u0 + 0.999f / 4.0f; - float v0 = (tex / 4) / 4.0f; - float v1 = v0 + 0.999f / 4.0f; + float u0 = (tex % 4) / 4.0f; + float u1 = u0 + 0.999f / 4.0f; + float v0 = (tex / 4) / 4.0f; + float v1 = v0 + 0.999f / 4.0f; - float r = 2.0f * size; + float r = 2.0f * size; - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = (float)(xo + (this->x - xo) * a - xOff); + float y = (float)(yo + (this->y - yo) * a - yOff); + float z = (float)(zo + (this->z - zo) * a - zOff); - // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - float distSq = (x*x + y*y + z*z); - if( distSq < ( 3.0f * 3.0f )) return; + // 4J - don't render explosion particles that are less than 3 metres away, + // to try and avoid large particles that are causing us problems with + // photosensitivity testing + float distSq = (x * x + y * y + z * z); + if (distSq < (3.0f * 3.0f)) return; - glColor4f(1, 1, 1, 1); - glDisable(GL_LIGHTING); - Lighting::turnOff(); - t->begin(); - t->color(rCol, gCol, bCol, 1.0f); - t->normal(0, 1, 0); - t->tex2(0x00f0); - t->vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u1, v1); - t->vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u1, v0); - t->vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u0, v0); - t->vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u0, v1); - t->end(); - glPolygonOffset(0, 0.0f); - glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, 1); + glDisable(GL_LIGHTING); + Lighting::turnOff(); + t->begin(); + t->color(rCol, gCol, bCol, 1.0f); + t->normal(0, 1, 0); + t->tex2(0x00f0); + t->vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u1, v1); + t->vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u1, v0); + t->vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u0, v0); + t->vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u0, v1); + t->end(); + glPolygonOffset(0, 0.0f); + glEnable(GL_LIGHTING); } -int HugeExplosionParticle::getLightColor(float a) -{ - return 0xf0f0; +int HugeExplosionParticle::getLightColor(float a) { return 0xf0f0; } + +void HugeExplosionParticle::tick() { + xo = x; + yo = y; + zo = z; + life++; + if (life == lifeTime) remove(); } -void HugeExplosionParticle::tick() -{ - xo = x; - yo = y; - zo = z; - life++; - if (life == lifeTime) remove(); -} - -int HugeExplosionParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int HugeExplosionParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h index 0f02d1227..2c44d2148 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h @@ -2,19 +2,20 @@ #include "Particle.h" -class HugeExplosionParticle : public Particle -{ +class HugeExplosionParticle : public Particle { private: - int life; - int lifeTime; - Textures *textures; - float size; + int life; + int lifeTime; + Textures* textures; + float size; public: - virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONPARTICLE; } - HugeExplosionParticle(Textures *textures, Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - int getLightColor(float a); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONPARTICLE; } + HugeExplosionParticle(Textures* textures, Level* level, double x, double y, + double z, double xa, double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + int getLightColor(float a); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp index cdbc6e157..2bfc541be 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp @@ -3,35 +3,39 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -HugeExplosionSeedParticle::HugeExplosionSeedParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - life = 0; +HugeExplosionSeedParticle::HugeExplosionSeedParticle(Level* level, double x, + double y, double z, + double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + life = 0; - lifeTime = 8; + lifeTime = 8; } -void HugeExplosionSeedParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void HugeExplosionSeedParticle::render(Tesselator* t, float a, float xa, + float ya, float za, float xa2, + float za2) {} + +void HugeExplosionSeedParticle::tick() { + // Horrible hack to communicate with the level renderer, which is just + // attached as a listener to this level. This let's the particle rendering + // know to use this level (rather than try to work it out from the current + // player), and to not bother distance clipping particles which would again + // be based on the current player. + Minecraft::GetInstance()->animateTickLevel = level; + for (int i = 0; i < 6; i++) { + double xx = x + (random->nextDouble() - random->nextDouble()) * 4; + double yy = y + (random->nextDouble() - random->nextDouble()) * 4; + double zz = z + (random->nextDouble() - random->nextDouble()) * 4; + level->addParticle(eParticleType_largeexplode, xx, yy, zz, + life / (float)lifeTime, 0, 0); + } + Minecraft::GetInstance()->animateTickLevel = NULL; + life++; + if (life == lifeTime) remove(); } -void HugeExplosionSeedParticle::tick() -{ - // Horrible hack to communicate with the level renderer, which is just attached as a listener to this level. This let's the particle - // rendering know to use this level (rather than try to work it out from the current player), and to not bother distance clipping particles - // which would again be based on the current player. - Minecraft::GetInstance()->animateTickLevel = level; - for (int i = 0; i < 6; i++) { - double xx = x + (random->nextDouble() - random->nextDouble()) * 4; - double yy = y + (random->nextDouble() - random->nextDouble()) * 4; - double zz = z + (random->nextDouble() - random->nextDouble()) * 4; - level->addParticle(eParticleType_largeexplode, xx, yy, zz, life / (float) lifeTime, 0, 0); - } - Minecraft::GetInstance()->animateTickLevel = NULL; - life++; - if (life == lifeTime) remove(); -} - -int HugeExplosionSeedParticle::getParticleTexture() -{ - return ParticleEngine::TERRAIN_TEXTURE; +int HugeExplosionSeedParticle::getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h index 445c8a347..0ed0b9e33 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h @@ -2,16 +2,17 @@ #include "Particle.h" -class HugeExplosionSeedParticle : public Particle -{ +class HugeExplosionSeedParticle : public Particle { private: - int life; - int lifeTime; + int life; + int lifeTime; public: - virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONSEEDPARTICLE; } - HugeExplosionSeedParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONSEEDPARTICLE; } + HugeExplosionSeedParticle(Level* level, double x, double y, double z, + double xa, double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/LavaParticle.cpp b/Minecraft.Client/Rendering/Particles/LavaParticle.cpp index 9eb825357..b3cb03c18 100644 --- a/Minecraft.Client/Rendering/Particles/LavaParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/LavaParticle.cpp @@ -4,8 +4,8 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -LavaParticle::LavaParticle(Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ +LavaParticle::LavaParticle(Level* level, double x, double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { xd *= 0.8f; yd *= 0.8f; zd *= 0.8f; @@ -15,14 +15,13 @@ LavaParticle::LavaParticle(Level *level, double x, double y, double z) : Particl size *= (random->nextFloat() * 2 + 0.2f); oSize = size; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(16 / (Math::random() * 0.8 + 0.2)); noPhysics = false; setMiscTex(49); } // 4J - brought forward from 1.8.2 -int LavaParticle::getLightColor(float a) -{ +int LavaParticle::getLightColor(float a) { float l = (age + a) / lifetime; if (l < 0) l = 0; if (l > 1) l = 1; @@ -33,27 +32,24 @@ int LavaParticle::getLightColor(float a) return br1 | br2 << 16; } -float LavaParticle::getBrightness(float a) -{ - return 1; -} +float LavaParticle::getBrightness(float a) { return 1; } -void LavaParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - size = oSize * (1 - s*s); +void LavaParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float s = (age + a) / (float)lifetime; + size = oSize * (1 - s * s); Particle::render(t, a, xa, ya, za, xa2, za2); } -void LavaParticle::tick() -{ +void LavaParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - float odds = age / (float) lifetime; - if (random->nextFloat() > odds) level->addParticle(eParticleType_smoke, x, y, z, xd, yd, zd); + float odds = age / (float)lifetime; + if (random->nextFloat() > odds) + level->addParticle(eParticleType_smoke, x, y, z, xd, yd, zd); yd -= 0.03; move(xd, yd, zd); @@ -61,8 +57,7 @@ void LavaParticle::tick() yd *= 0.999f; zd *= 0.999f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/LavaParticle.h b/Minecraft.Client/Rendering/Particles/LavaParticle.h index 235edcf41..de5f4f4b5 100644 --- a/Minecraft.Client/Rendering/Particles/LavaParticle.h +++ b/Minecraft.Client/Rendering/Particles/LavaParticle.h @@ -1,16 +1,18 @@ #pragma once #include "Particle.h" -class LavaParticle : public Particle -{ +class LavaParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_LAVAPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_LAVAPARTICLE; } + private: - float oSize; + float oSize; + public: - LavaParticle(Level *level, double x, double y, double z); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + LavaParticle(Level* level, double x, double y, double z); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp index 5667515eb..315adc071 100644 --- a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp @@ -4,11 +4,13 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../Minecraft.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// Only the nether portal uses this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle Only the nether portal uses this particle -NetherPortalParticle::NetherPortalParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ +NetherPortalParticle::NetherPortalParticle(Level* level, double x, double y, + double z, double xd, double yd, + double zd) + : Particle(level, x, y, z, xd, yd, zd) { this->xd = xd; this->yd = yd; this->zd = zd; @@ -16,84 +18,81 @@ NetherPortalParticle::NetherPortalParticle(Level *level, double x, double y, dou this->yStart = this->y = y; this->zStart = this->z = z; - float br = random->nextFloat()*0.6f+0.4f; - oSize = size = random->nextFloat()*0.2f+0.5f; - //rCol = gCol = bCol = 1.0f*br; - //gCol *= 0.3f; - //rCol *= 0.9f; + float br = random->nextFloat() * 0.6f + 0.4f; + oSize = size = random->nextFloat() * 0.2f + 0.5f; + // rCol = gCol = bCol = 1.0f*br; + // gCol *= 0.3f; + // rCol *= 0.9f; - // Default colour (0.9f, 0.3f, 1.0f) - // 0xE64DFF + // Default colour (0.9f, 0.3f, 1.0f) + // 0xE64DFF - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NetherPortal ); - int r = (colour>>16)&0xFF; - int g = (colour>>8)&0xFF; - int b = colour&0xFF; - rCol = (r/255.0f)*br; - gCol = (g/255.0f)*br; - bCol = (b/255.0f)*br; + unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_NetherPortal); + int r = (colour >> 16) & 0xFF; + int g = (colour >> 8) & 0xFF; + int b = colour & 0xFF; + rCol = (r / 255.0f) * br; + gCol = (g / 255.0f) * br; + bCol = (b / 255.0f) * br; - lifetime = (int) (Math::random()*10) + 40; + lifetime = (int)(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex((int)(Math::random() * 8)); } -void NetherPortalParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - s = 1-s; - s = s*s; - s = 1-s; +void NetherPortalParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + float s = (age + a) / (float)lifetime; + s = 1 - s; + s = s * s; + s = 1 - s; size = oSize * (s); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int NetherPortalParticle::getLightColor(float a) -{ +int NetherPortalParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += (int)(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } -float NetherPortalParticle::getBrightness(float a) -{ +float NetherPortalParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - return br*(1-pos)+pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void NetherPortalParticle::tick() -{ +void NetherPortalParticle::tick() { xo = x; yo = y; zo = z; - - float pos = age/(float)lifetime; + + float pos = age / (float)lifetime; float a = pos; - pos = -pos+pos*pos*2; -// pos = pos*pos; -// pos = pos*pos; - pos = 1-pos; - - x = xStart+xd*pos; - y = yStart+yd*pos+(1-a); - z = zStart+zd*pos; - - -// spd+=0.002/lifetime*age; + pos = -pos + pos * pos * 2; + // pos = pos*pos; + // pos = pos*pos; + pos = 1 - pos; + + x = xStart + xd * pos; + y = yStart + yd * pos + (1 - a); + z = zStart + zd * pos; + + // spd+=0.002/lifetime*age; if (age++ >= lifetime) remove(); -// move(xd*spd, yd*spd, zd*spd); + // move(xd*spd, yd*spd, zd*spd); } diff --git a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h index 85aa8c669..a053d356e 100644 --- a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h +++ b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h @@ -1,21 +1,23 @@ #pragma once #include "Particle.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// Only the nether portal uses this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle Only the nether portal uses this particle -class NetherPortalParticle : public Particle -{ +class NetherPortalParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_NETHERPORTALPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_NETHERPORTALPARTICLE; } + private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - NetherPortalParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + NetherPortalParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/NoteParticle.cpp b/Minecraft.Client/Rendering/Particles/NoteParticle.cpp index d4f50d182..db6bb47b5 100644 --- a/Minecraft.Client/Rendering/Particles/NoteParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/NoteParticle.cpp @@ -2,32 +2,38 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "NoteParticle.h" -void NoteParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void NoteParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.01f; yd *= 0.01f; zd *= 0.01f; yd += 0.2; - /* - unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NoteMin ); - unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NoteMax ); - double rMin = ( (cMin>>16)&0xFF )/255.0f, gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; - double rMax = ( (cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF )/255.0; + /* + unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( +eMinecraftColour_Particle_NoteMin ); unsigned int cMax = +Minecraft::GetInstance()->getColourTable()->getColor( +eMinecraftColour_Particle_NoteMax ); double rMin = ( (cMin>>16)&0xFF )/255.0f, +gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; double rMax = ( +(cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF +)/255.0; - rCol = Mth::sin(((float) xa + 0.0f / 3) * PI * 2) * (rMax - rMin) + rMin; - gCol = Mth::sin(((float) xa + 1.0f / 3) * PI * 2) * (gMax - gMin) + gMin; - bCol = Mth::sin(((float) xa + 2.0f / 3) * PI * 2) * (bMax - bMin) + bMin; - */ +rCol = Mth::sin(((float) xa + 0.0f / 3) * PI * 2) * (rMax - rMin) + rMin; +gCol = Mth::sin(((float) xa + 1.0f / 3) * PI * 2) * (gMax - gMin) + gMin; +bCol = Mth::sin(((float) xa + 2.0f / 3) * PI * 2) * (bMax - bMin) + bMin; + */ - // 4J-JEV: Added, - // There are 24 valid colours for this particle input through the 'xa' field (0.0-1.0). - int note = (int) floor(0.5 + (xa*24.0)) + (int) eMinecraftColour_Particle_Note_00; - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( (eMinecraftColour) note ); - - rCol = ( (col>>16)&0xFF )/255.0; - gCol = ( (col>>8)&0xFF )/255.0; - bCol = ( col&0xFF )/255.0; + // 4J-JEV: Added, + // There are 24 valid colours for this particle input through the 'xa' field + // (0.0-1.0). + int note = + (int)floor(0.5 + (xa * 24.0)) + (int)eMinecraftColour_Particle_Note_00; + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + (eMinecraftColour)note); + + rCol = ((col >> 16) & 0xFF) / 255.0; + gCol = ((col >> 8) & 0xFF) / 255.0; + bCol = (col & 0xFF) / 255.0; size *= 0.75f; size *= scale; @@ -36,22 +42,23 @@ void NoteParticle::init(Level *level, double x, double y, double z, double xa, d lifetime = 6; noPhysics = false; - setMiscTex(16 * 4); } -NoteParticle::NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 2); +NoteParticle::NoteParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 2); } -NoteParticle::NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +NoteParticle::NoteParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void NoteParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void NoteParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; @@ -60,8 +67,7 @@ void NoteParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void NoteParticle::tick() -{ +void NoteParticle::tick() { xo = x; yo = y; zo = z; @@ -69,8 +75,7 @@ void NoteParticle::tick() if (age++ >= lifetime) remove(); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -78,10 +83,8 @@ void NoteParticle::tick() yd *= 0.66f; zd *= 0.66f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } - } diff --git a/Minecraft.Client/Rendering/Particles/NoteParticle.h b/Minecraft.Client/Rendering/Particles/NoteParticle.h index b53910b8d..75af522d5 100644 --- a/Minecraft.Client/Rendering/Particles/NoteParticle.h +++ b/Minecraft.Client/Rendering/Particles/NoteParticle.h @@ -1,16 +1,20 @@ #pragma once #include "Particle.h" -class NoteParticle : public Particle -{ +class NoteParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_NOTEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_NOTEPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + NoteParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + NoteParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/Particle.cpp b/Minecraft.Client/Rendering/Particles/Particle.cpp index 422f9ca6d..8fea088a5 100644 --- a/Minecraft.Client/Rendering/Particles/Particle.cpp +++ b/Minecraft.Client/Rendering/Particles/Particle.cpp @@ -9,116 +9,93 @@ /* protected int tex; protected float gravity; - */ + */ double Particle::xOff = 0; double Particle::yOff = 0; double Particle::zOff = 0; -void Particle::_init(Level *level, double x, double y, double z) -{ - // 4J - added these initialisers - alpha = 1.0f; +void Particle::_init(Level* level, double x, double y, double z) { + // 4J - added these initialisers + alpha = 1.0f; tex = NULL; - gravity = 0.0f; + gravity = 0.0f; - setSize(0.2f, 0.2f); - heightOffset = bbHeight / 2.0f; - setPos(x, y, z); - xo = xOld = x; - yo = yOld = y; - zo = zOld = z; - rCol = gCol = bCol = 1.0f; + setSize(0.2f, 0.2f); + heightOffset = bbHeight / 2.0f; + setPos(x, y, z); + xo = xOld = x; + yo = yOld = y; + zo = zOld = z; + rCol = gCol = bCol = 1.0f; - uo = random->nextFloat() * 3; - vo = random->nextFloat() * 3; + uo = random->nextFloat() * 3; + vo = random->nextFloat() * 3; - size = (random->nextFloat() * 0.5f + 0.5f) * 2; + size = (random->nextFloat() * 0.5f + 0.5f) * 2; - lifetime = (int) (4 / (random->nextFloat() * 0.9f + 0.1f)); - age = 0; + lifetime = (int)(4 / (random->nextFloat() * 0.9f + 0.1f)); + age = 0; - texX = 0; - texY = 0; + texX = 0; + texY = 0; } -Particle::Particle(Level *level, double x, double y, double z) : Entity(level, false) -{ - _init(level,x,y,z); +Particle::Particle(Level* level, double x, double y, double z) + : Entity(level, false) { + _init(level, x, y, z); } -Particle::Particle(Level *level, double x, double y, double z, double xa, double ya, double za) : Entity(level, false) -{ - _init(level,x,y,z); +Particle::Particle(Level* level, double x, double y, double z, double xa, + double ya, double za) + : Entity(level, false) { + _init(level, x, y, z); - xd = xa + (float) (Math::random() * 2 - 1) * 0.4f; - yd = ya + (float) (Math::random() * 2 - 1) * 0.4f; - zd = za + (float) (Math::random() * 2 - 1) * 0.4f; - float speed = (float) (Math::random() + Math::random() + 1) * 0.15f; + xd = xa + (float)(Math::random() * 2 - 1) * 0.4f; + yd = ya + (float)(Math::random() * 2 - 1) * 0.4f; + zd = za + (float)(Math::random() * 2 - 1) * 0.4f; + float speed = (float)(Math::random() + Math::random() + 1) * 0.15f; - float dd = (float) (Mth::sqrt(xd * xd + yd * yd + zd * zd)); + float dd = (float)(Mth::sqrt(xd * xd + yd * yd + zd * zd)); xd = xd / dd * speed * 0.4f; yd = yd / dd * speed * 0.4f + 0.1f; - zd = zd / dd * speed * 0.4f;} + zd = zd / dd * speed * 0.4f; +} -std::shared_ptr Particle::setPower(float power) -{ +std::shared_ptr Particle::setPower(float power) { xd *= power; yd = (yd - 0.1f) * power + 0.1f; zd *= power; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -std::shared_ptr Particle::scale(float scale) -{ +std::shared_ptr Particle::scale(float scale) { setSize(0.2f * scale, 0.2f * scale); size *= scale; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -void Particle::setColor(float r, float g, float b) -{ - this->rCol = r; - this->gCol = g; - this->bCol = b; +void Particle::setColor(float r, float g, float b) { + this->rCol = r; + this->gCol = g; + this->bCol = b; } -void Particle::setAlpha(float alpha) -{ - this->alpha = alpha; -} +void Particle::setAlpha(float alpha) { this->alpha = alpha; } -float Particle::getRedCol() -{ - return rCol; -} +float Particle::getRedCol() { return rCol; } -float Particle::getGreenCol() -{ - return gCol; -} +float Particle::getGreenCol() { return gCol; } -float Particle::getBlueCol() -{ - return bCol; -} +float Particle::getBlueCol() { return bCol; } -float Particle::getAlpha() -{ - return alpha; -} +float Particle::getAlpha() { return alpha; } -bool Particle::makeStepSound() -{ - return false; -} +bool Particle::makeStepSound() { return false; } -void Particle::defineSynchedData() -{ -} +void Particle::defineSynchedData() {} -void Particle::tick() -{ +void Particle::tick() { xo = x; yo = y; zo = z; @@ -131,116 +108,102 @@ void Particle::tick() yd *= 0.98f; zd *= 0.98f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } - } -void Particle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void Particle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { float u0 = texX / 16.0f; float u1 = u0 + 0.999f / 16.0f; float v0 = texY / 16.0f; float v1 = v0 + 0.999f / 16.0f; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU0(); - u1 = tex->getU1(); - v0 = tex->getV0(); - v1 = tex->getV1(); - } + if (tex != NULL) { + u0 = tex->getU0(); + u1 = tex->getU1(); + v0 = tex->getV0(); + v1 = tex->getV1(); + } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = (float)(xo + (this->x - xo) * a - xOff); + float y = (float)(yo + (this->y - yo) * a - yOff); + float z = (float)(zo + (this->z - zo) * a - zOff); - float br = 1.0f; // 4J - change brought forward from 1.8.2 - if( !SharedConstants::TEXTURE_LIGHTING ) - { - br = getBrightness(a); - } + float br = 1.0f; // 4J - change brought forward from 1.8.2 + if (!SharedConstants::TEXTURE_LIGHTING) { + br = getBrightness(a); + } #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time. - t->tileParticleQuad((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u1), (float)( v1), - (float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u1), (float)( v0), - (float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u0), (float)( v0), - (float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u0), (float)( v1), - rCol * br, gCol * br, bCol * br, alpha); + // AP - this will set up the 4 vertices in half the time. + t->tileParticleQuad((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u1), (float)(v1), + (float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u1), (float)(v0), + (float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u0), (float)(v0), + (float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u0), (float)(v1), + rCol * br, gCol * br, bCol * br, alpha); #else t->color(rCol * br, gCol * br, bCol * br, alpha); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u1), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u0), (float)( v1)); + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u1), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u0), (float)(v1)); #endif } -int Particle::getParticleTexture() -{ - return ParticleEngine::MISC_TEXTURE; -} +int Particle::getParticleTexture() { return ParticleEngine::MISC_TEXTURE; } -void Particle::addAdditonalSaveData(CompoundTag *entityTag) -{ -} +void Particle::addAdditonalSaveData(CompoundTag* entityTag) {} -void Particle::readAdditionalSaveData(CompoundTag *tag) -{ -} +void Particle::readAdditionalSaveData(CompoundTag* tag) {} -void Particle::setTex(Textures *textures, Icon *icon) -{ - if (getParticleTexture() == ParticleEngine::TERRAIN_TEXTURE) - { - tex = icon; - } - else if (getParticleTexture() == ParticleEngine::ITEM_TEXTURE) - { - tex = icon; - } - else - { +void Particle::setTex(Textures* textures, Icon* icon) { + if (getParticleTexture() == ParticleEngine::TERRAIN_TEXTURE) { + tex = icon; + } else if (getParticleTexture() == ParticleEngine::ITEM_TEXTURE) { + tex = icon; + } else { #ifndef _CONTENT_PACKAGE - printf("Invalid call to Particle.setTex, use coordinate methods\n"); - __debugbreak(); + printf("Invalid call to Particle.setTex, use coordinate methods\n"); + __debugbreak(); #endif - //throw new RuntimeException("Invalid call to Particle.setTex, use coordinate methods"); - } + // throw new RuntimeException("Invalid call to Particle.setTex, use + // coordinate methods"); + } } -void Particle::setMiscTex(int slotIndex) -{ - if (getParticleTexture() != ParticleEngine::MISC_TEXTURE && getParticleTexture() != ParticleEngine::DRAGON_BREATH_TEXTURE) - { +void Particle::setMiscTex(int slotIndex) { + if (getParticleTexture() != ParticleEngine::MISC_TEXTURE && + getParticleTexture() != ParticleEngine::DRAGON_BREATH_TEXTURE) { #ifndef _CONTENT_PACKAGE - printf("Invalid call to Particle.setMixTex\n"); - __debugbreak(); - //throw new RuntimeException("Invalid call to Particle.setMiscTex"); + printf("Invalid call to Particle.setMixTex\n"); + __debugbreak(); + // throw new RuntimeException("Invalid call to Particle.setMiscTex"); #endif - } - texX = slotIndex % 16; - texY = slotIndex / 16; + } + texX = slotIndex % 16; + texY = slotIndex / 16; } -void Particle::setNextMiscAnimTex() -{ - texX++; -} +void Particle::setNextMiscAnimTex() { texX++; } -bool Particle::isAttackable() -{ - return false; -} +bool Particle::isAttackable() { return false; } //@Override -std::wstring Particle::toString() -{ - return L"A particle"; //getClass()->getSimpleName() + ", Pos (" + x + "," + y + "," + z + "), RGBA (" + rCol + "," + gCol + "," + bCol + "," + alpha + "), Age " + age; +std::wstring Particle::toString() { + return L"A particle"; // getClass()->getSimpleName() + ", Pos (" + x + "," + // + y + "," + z + "), RGBA (" + rCol + "," + gCol + + // "," + bCol + "," + alpha + "), Age " + age; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/Particle.h b/Minecraft.Client/Rendering/Particles/Particle.h index e2202c14c..f8b99761f 100644 --- a/Minecraft.Client/Rendering/Particles/Particle.h +++ b/Minecraft.Client/Rendering/Particles/Particle.h @@ -1,6 +1,5 @@ #pragma once - #include "../../../Minecraft.World/Entities/Entity.h" #include "../../../Minecraft.World/Util/ParticleTypes.h" #include "ParticleEngine.h" @@ -8,46 +7,53 @@ class Tesselator; class CompoundTag; class Icon; -class Particle : public Entity -{ +class Particle : public Entity { protected: - int texX, texY; + int texX, texY; float uo, vo; int age; int lifetime; float size; float gravity; float rCol, gCol, bCol; - float alpha; - Icon *tex; + float alpha; + Icon* tex; + public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; + private: - void _init(Level *level, double x, double y, double z); + void _init(Level* level, double x, double y, double z); + protected: - Particle(Level *level, double x, double y, double z); + Particle(Level* level, double x, double y, double z); + public: - Particle(Level *level, double x, double y, double z, double xa, double ya, double za); + Particle(Level* level, double x, double y, double z, double xa, double ya, + double za); virtual std::shared_ptr setPower(float power); virtual std::shared_ptr scale(float scale); - void setColor(float r, float g, float b); - void setAlpha(float alpha); - float getRedCol(); - float getGreenCol(); - float getBlueCol(); - float getAlpha(); + void setColor(float r, float g, float b); + void setAlpha(float alpha); + float getRedCol(); + float getGreenCol(); + float getBlueCol(); + float getAlpha(); + protected: - virtual bool makeStepSound(); + virtual bool makeStepSound(); virtual void defineSynchedData(); + public: - virtual void tick(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getParticleTexture(); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *tag); - virtual void setTex(Textures *textures, Icon *icon); - virtual void setMiscTex(int slotIndex); - virtual void setNextMiscAnimTex(); - virtual bool isAttackable(); - virtual std::wstring toString(); + virtual void tick(); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getParticleTexture(); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* tag); + virtual void setTex(Textures* textures, Icon* icon); + virtual void setMiscTex(int slotIndex); + virtual void setNextMiscAnimTex(); + virtual bool isAttackable(); + virtual std::wstring toString(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp b/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp index 978ac1ea0..2eb3e59cb 100644 --- a/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp +++ b/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp @@ -11,54 +11,50 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h" -ParticleEngine::ParticleEngine(Level *level, Textures *textures) -{ -// if (level != NULL) // 4J - removed - we want level to be initialised to *something* - { +ParticleEngine::ParticleEngine(Level* level, Textures* textures) { + // if (level != NULL) // 4J - removed - we want level to be + // initialised to *something* + { this->level = level; } this->textures = textures; - - this->random = new Random(); + + this->random = new Random(); } -ParticleEngine::~ParticleEngine() -{ - delete random; -} +ParticleEngine::~ParticleEngine() { delete random; } -void ParticleEngine::add(std::shared_ptr p) -{ +void ParticleEngine::add(std::shared_ptr p) { int t = p->getParticleTexture(); - int l = p->level->dimension->id == 0 ? 0 : ( p->level->dimension->id == -1 ? 1 : 2); - if ( (t != DRAGON_BREATH_TEXTURE && particles[l][t].size() >= MAX_PARTICLES_PER_LAYER) || particles[l][t].size() >= MAX_DRAGON_BREATH_PARTICLES) particles[l][t].pop_front();//particles[l][t].erase(particles[l][t].begin()); + int l = p->level->dimension->id == 0 + ? 0 + : (p->level->dimension->id == -1 ? 1 : 2); + if ((t != DRAGON_BREATH_TEXTURE && + particles[l][t].size() >= MAX_PARTICLES_PER_LAYER) || + particles[l][t].size() >= MAX_DRAGON_BREATH_PARTICLES) + particles[l][t] + .pop_front(); // particles[l][t].erase(particles[l][t].begin()); particles[l][t].push_back(p); } -void ParticleEngine::tick() -{ - for( int l = 0; l < 3; l++ ) - { - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { - std::shared_ptr p = particles[l][tt][i]; - p->tick(); - if (p->removed) - { - particles[l][tt][i] = particles[l][tt].back(); - particles[l][tt].pop_back(); - i--; - } - } - } - } +void ParticleEngine::tick() { + for (int l = 0; l < 3; l++) { + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { + std::shared_ptr p = particles[l][tt][i]; + p->tick(); + if (p->removed) { + particles[l][tt][i] = particles[l][tt].back(); + particles[l][tt].pop_back(); + i--; + } + } + } + } } -void ParticleEngine::render(std::shared_ptr player, float a) -{ - // 4J - change brought forward from 1.2.3 +void ParticleEngine::render(std::shared_ptr player, float a) { + // 4J - change brought forward from 1.2.3 float xa = Camera::xa; float za = Camera::za; @@ -69,19 +65,22 @@ void ParticleEngine::render(std::shared_ptr player, float a) Particle::xOff = (player->xOld + (player->x - player->xOld) * a); Particle::yOff = (player->yOld + (player->y - player->yOld) * a); Particle::zOff = (player->zOld + (player->z - player->zOld) * a); - int l = level->dimension->id == 0 ? 0 : ( level->dimension->id == -1 ? 1 : 2 ); - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - if(tt == ENTITY_PARTICLE_TEXTURE) continue; + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + if (tt == ENTITY_PARTICLE_TEXTURE) continue; if (particles[l][tt].empty()) continue; - MemSect(31); - if (tt == MISC_TEXTURE || tt == DRAGON_BREATH_TEXTURE) textures->bindTexture(TN_PARTICLES); // 4J was L"/particles.png" - if (tt == TERRAIN_TEXTURE) textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - if (tt == ITEM_TEXTURE) textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + if (tt == MISC_TEXTURE || tt == DRAGON_BREATH_TEXTURE) + textures->bindTexture(TN_PARTICLES); // 4J was L"/particles.png" + if (tt == TERRAIN_TEXTURE) + textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + if (tt == ITEM_TEXTURE) + textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); glColor4f(1.0f, 1.0f, 1.0f, 1); #if 0 // Note that these changes were brought in from java (1.5ish), but as with the java version, break rendering of the particles @@ -92,17 +91,16 @@ void ParticleEngine::render(std::shared_ptr player, float a) glAlphaFunc(GL_GREATER, 1.0f / 255.0f); #endif t->begin(); - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { - if(t->hasMaxVertices()) - { - t->end(); - t->begin(); - } + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { + if (t->hasMaxVertices()) { + t->end(); + t->begin(); + } std::shared_ptr p = particles[l][tt][i]; - if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { + if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought + // forward from 1.8.2 + { t->tex2(p->getLightColor(a)); } p->render(t, a, xa, ya, za, xa2, za2); @@ -115,98 +113,110 @@ void ParticleEngine::render(std::shared_ptr player, float a) glAlphaFunc(GL_GREATER, .1f); #endif } - } -void ParticleEngine::renderLit(std::shared_ptr player, float a) -{ - // 4J - added. We call this before ParticleEngine::render in the general render per player, so if we - // don't set this here then the offsets will be from the previous player - a single frame lag for the - // java game, or totally incorrect placement of things for split screen. +void ParticleEngine::renderLit(std::shared_ptr player, float a) { + // 4J - added. We call this before ParticleEngine::render in the general + // render per player, so if we don't set this here then the offsets will be + // from the previous player - a single frame lag for the java game, or + // totally incorrect placement of things for split screen. Particle::xOff = (player->xOld + (player->x - player->xOld) * a); Particle::yOff = (player->yOld + (player->y - player->yOld) * a); Particle::zOff = (player->zOld + (player->z - player->zOld) * a); - float RAD = PI / 180; - float xa = (float) Mth::cos(player->yRot * RAD); - float za = (float) Mth::sin(player->yRot * RAD); + float RAD = PI / 180; + float xa = (float)Mth::cos(player->yRot * RAD); + float za = (float)Mth::sin(player->yRot * RAD); - float xa2 = -za * (float) Mth::sin(player->xRot * RAD); - float za2 = xa * (float) Mth::sin(player->xRot * RAD); - float ya = (float) Mth::cos(player->xRot * RAD); + float xa2 = -za * (float)Mth::sin(player->xRot * RAD); + float za2 = xa * (float)Mth::sin(player->xRot * RAD); + float ya = (float)Mth::cos(player->xRot * RAD); - int l = level->dimension->id == 0 ? 0 : ( level->dimension->id == -1 ? 1 : 2 ); + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); int tt = ENTITY_PARTICLE_TEXTURE; if (particles[l][tt].empty()) return; - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { std::shared_ptr p = particles[l][tt][i]; - if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { + if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward + // from 1.8.2 + { t->tex2(p->getLightColor(a)); } p->render(t, a, xa, ya, za, xa2, za2); } } -void ParticleEngine::setLevel(Level *level) -{ +void ParticleEngine::setLevel(Level* level) { this->level = level; - // 4J - we've now got a set of particle vectors for each dimension, and only clearing them when its game over & the level is set to NULL - if( level == NULL ) - { - for( int l = 0; l < 3; l++ ) - { - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - particles[l][tt].clear(); - } - } - } + // 4J - we've now got a set of particle vectors for each dimension, and only + // clearing them when its game over & the level is set to NULL + if (level == NULL) { + for (int l = 0; l < 3; l++) { + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + particles[l][tt].clear(); + } + } + } } -void ParticleEngine::destroy(int x, int y, int z, int tid, int data) -{ +void ParticleEngine::destroy(int x, int y, int z, int tid, int data) { if (tid == 0) return; - Tile *tile = Tile::tiles[tid]; + Tile* tile = Tile::tiles[tid]; int SD = 4; for (int xx = 0; xx < SD; xx++) for (int yy = 0; yy < SD; yy++) - for (int zz = 0; zz < SD; zz++) - { + for (int zz = 0; zz < SD; zz++) { double xp = x + (xx + 0.5) / SD; double yp = y + (yy + 0.5) / SD; double zp = z + (zz + 0.5) / SD; - int face = random->nextInt(6); - add(( std::shared_ptr(new TerrainParticle(level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, zp - z - 0.5f, tile, face, data, textures) ) )->init(x, y, z, data)); + int face = random->nextInt(6); + add((std::shared_ptr(new TerrainParticle( + level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, + zp - z - 0.5f, tile, face, data, textures))) + ->init(x, y, z, data)); } } -void ParticleEngine::crack(int x, int y, int z, int face) -{ +void ParticleEngine::crack(int x, int y, int z, int face) { int tid = level->getTile(x, y, z); if (tid == 0) return; - Tile *tile = Tile::tiles[tid]; + Tile* tile = Tile::tiles[tid]; float r = 0.10f; - double xp = x + random->nextDouble() * ((tile->getShapeX1() - tile->getShapeX0()) - r * 2) + r + tile->getShapeX0(); - double yp = y + random->nextDouble() * ((tile->getShapeY1() - tile->getShapeY0()) - r * 2) + r + tile->getShapeY0(); - double zp = z + random->nextDouble() * ((tile->getShapeZ1() - tile->getShapeZ0()) - r * 2) + r + tile->getShapeZ0(); + double xp = x + + random->nextDouble() * + ((tile->getShapeX1() - tile->getShapeX0()) - r * 2) + + r + tile->getShapeX0(); + double yp = y + + random->nextDouble() * + ((tile->getShapeY1() - tile->getShapeY0()) - r * 2) + + r + tile->getShapeY0(); + double zp = z + + random->nextDouble() * + ((tile->getShapeZ1() - tile->getShapeZ0()) - r * 2) + + r + tile->getShapeZ0(); if (face == 0) yp = y + tile->getShapeY0() - r; if (face == 1) yp = y + tile->getShapeY1() + r; if (face == 2) zp = z + tile->getShapeZ0() - r; if (face == 3) zp = z + tile->getShapeZ1() + r; if (face == 4) xp = x + tile->getShapeX0() - r; if (face == 5) xp = x + tile->getShapeX1() + r; - add(( std::shared_ptr(new TerrainParticle(level, xp, yp, zp, 0, 0, 0, tile, face, level->getData(x, y, z), textures) ) )->init(x, y, z, level->getData(x, y, z))->setPower(0.2f)->scale(0.6f)); - + add((std::shared_ptr( + new TerrainParticle(level, xp, yp, zp, 0, 0, 0, tile, face, + level->getData(x, y, z), textures))) + ->init(x, y, z, level->getData(x, y, z)) + ->setPower(0.2f) + ->scale(0.6f)); } -std::wstring ParticleEngine::countParticles() -{ - int l = level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2 ); - return _toString((int)(particles[l][0].size() + particles[l][1].size() + particles[l][2].size())); +std::wstring ParticleEngine::countParticles() { + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); + return _toString((int)(particles[l][0].size() + + particles[l][1].size() + + particles[l][2].size())); } diff --git a/Minecraft.Client/Rendering/Particles/ParticleEngine.h b/Minecraft.Client/Rendering/Particles/ParticleEngine.h index 0d06d6590..271bd90ca 100644 --- a/Minecraft.Client/Rendering/Particles/ParticleEngine.h +++ b/Minecraft.Client/Rendering/Particles/ParticleEngine.h @@ -1,43 +1,43 @@ #pragma once - class Particle; class Level; class Textures; class Entity; class Random; - -class ParticleEngine -{ +class ParticleEngine { private: - static const int MAX_PARTICLES_PER_LAYER = 200; // 4J - reduced from 4000 - static const int MAX_DRAGON_BREATH_PARTICLES = 1000; + static const int MAX_PARTICLES_PER_LAYER = 200; // 4J - reduced from 4000 + static const int MAX_DRAGON_BREATH_PARTICLES = 1000; public: - static const int MISC_TEXTURE = 0; + static const int MISC_TEXTURE = 0; static const int TERRAIN_TEXTURE = 1; static const int ITEM_TEXTURE = 2; static const int ENTITY_PARTICLE_TEXTURE = 3; - static const int DRAGON_BREATH_TEXTURE = 4; // 4J Added + static const int DRAGON_BREATH_TEXTURE = 4; // 4J Added static const int TEXTURE_COUNT = 5; protected: - Level *level; + Level* level; + private: - std::deque > particles[3][TEXTURE_COUNT]; // 4J made two arrays to cope with simultaneous two dimensions - Textures *textures; - Random *random; + std::deque > + particles[3][TEXTURE_COUNT]; // 4J made two arrays to cope with + // simultaneous two dimensions + Textures* textures; + Random* random; public: - ParticleEngine(Level *level, Textures *textures); - ~ParticleEngine(); + ParticleEngine(Level* level, Textures* textures); + ~ParticleEngine(); void add(std::shared_ptr p); void tick(); void render(std::shared_ptr player, float a); void renderLit(std::shared_ptr player, float a); - void setLevel(Level *level); + void setLevel(Level* level); void destroy(int x, int y, int z, int tid, int data); void crack(int x, int y, int z, int face); std::wstring countParticles(); diff --git a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp index f11b6f961..145630db1 100644 --- a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp @@ -5,64 +5,62 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" -PlayerCloudParticle::PlayerCloudParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - float scale = 2.5f; - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; +PlayerCloudParticle::PlayerCloudParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + float scale = 2.5f; + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); - size *= 0.75f; - size *= scale; - oSize = size; + rCol = gCol = bCol = 1 - (float)(Math::random() * 0.3f); + size *= 0.75f; + size *= scale; + oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.3)); - lifetime *= scale; - noPhysics = false; + lifetime = (int)(8 / (Math::random() * 0.8 + 0.3)); + lifetime *= scale; + noPhysics = false; } -void PlayerCloudParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; +void PlayerCloudParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; - size = oSize * l; - Particle::render(t, a, xa, ya, za, xa2, za2); + size = oSize * l; + Particle::render(t, a, xa, ya, za, xa2, za2); } -void PlayerCloudParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void PlayerCloudParticle::tick() { + xo = x; + yo = y; + zo = z; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); - setMiscTex(7 - age * 8 / lifetime); + setMiscTex(7 - age * 8 / lifetime); - move(xd, yd, zd); - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; - std::shared_ptr p = level->getNearestPlayer(shared_from_this(), 2); - if (p != NULL) - { - if (y > p->bb->y0) - { - y+=(p->bb->y0-y)*0.2; - yd += (p->yd-yd)*0.2; - setPos(x, y, z); - } - } + move(xd, yd, zd); + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; + std::shared_ptr p = level->getNearestPlayer(shared_from_this(), 2); + if (p != NULL) { + if (y > p->bb->y0) { + y += (p->bb->y0 - y) * 0.2; + yd += (p->yd - yd) * 0.2; + setPos(x, y, z); + } + } - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h index 410020176..7004eca2f 100644 --- a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h +++ b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h @@ -2,14 +2,15 @@ #include "Particle.h" -class PlayerCloudParticle : public Particle -{ +class PlayerCloudParticle : public Particle { private: - float oSize; + float oSize; public: - virtual eINSTANCEOF GetType() { return eType_PLAYERCLOUDPARTICLEPARTICLE; } - PlayerCloudParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); + virtual eINSTANCEOF GetType() { return eType_PLAYERCLOUDPARTICLEPARTICLE; } + PlayerCloudParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp b/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp index e10544ddb..aac218649 100644 --- a/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp @@ -2,43 +2,46 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "RedDustParticle.h" -void RedDustParticle::init(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol) -{ +void RedDustParticle::init(Level* level, double x, double y, double z, + float scale, float rCol, float gCol, float bCol) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; - // 4J Stu - If they are all 0 then this particle has been created differently - // If just red is 0 it could be because we have made redstone a completely different colour (eg blue) - if (rCol == 0 && gCol == 0 && bCol == 0) - { + // 4J Stu - If they are all 0 then this particle has been created + // differently If just red is 0 it could be because we have made redstone a + // completely different colour (eg blue) + if (rCol == 0 && gCol == 0 && bCol == 0) { rCol = 1; } - float brr = (float) Math::random() * 0.4f + 0.6f; - this->rCol = ((float) (Math::random() * 0.2f) + 0.8f) * rCol * brr; - this->gCol = ((float) (Math::random() * 0.2f) + 0.8f) * gCol * brr; - this->bCol = ((float) (Math::random() * 0.2f) + 0.8f) * bCol * brr; + float brr = (float)Math::random() * 0.4f + 0.6f; + this->rCol = ((float)(Math::random() * 0.2f) + 0.8f) * rCol * brr; + this->gCol = ((float)(Math::random() * 0.2f) + 0.8f) * gCol * brr; + this->bCol = ((float)(Math::random() * 0.2f) + 0.8f) * bCol * brr; size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); lifetime = (int)(lifetime * scale); noPhysics = false; } -RedDustParticle::RedDustParticle(Level *level, double x, double y, double z, float rCol, float gCol, float bCol) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, 1, rCol, gCol, bCol); +RedDustParticle::RedDustParticle(Level* level, double x, double y, double z, + float rCol, float gCol, float bCol) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, 1, rCol, gCol, bCol); } -RedDustParticle::RedDustParticle(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, scale, rCol, gCol, bCol); +RedDustParticle::RedDustParticle(Level* level, double x, double y, double z, + float scale, float rCol, float gCol, + float bCol) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, scale, rCol, gCol, bCol); } -void RedDustParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void RedDustParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; @@ -47,8 +50,7 @@ void RedDustParticle::render(Tesselator *t, float a, float xa, float ya, float z Particle::render(t, a, xa, ya, za, xa2, za2); } -void RedDustParticle::tick() -{ +void RedDustParticle::tick() { xo = x; yo = y; zo = z; @@ -58,8 +60,7 @@ void RedDustParticle::tick() setMiscTex(7 - age * 8 / lifetime); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -67,8 +68,7 @@ void RedDustParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/RedDustParticle.h b/Minecraft.Client/Rendering/Particles/RedDustParticle.h index b1903b6ef..f5a5cc63c 100644 --- a/Minecraft.Client/Rendering/Particles/RedDustParticle.h +++ b/Minecraft.Client/Rendering/Particles/RedDustParticle.h @@ -1,17 +1,21 @@ #pragma once #include "Particle.h" -class RedDustParticle : public Particle -{ +class RedDustParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_REDDUSTPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_REDDUSTPARTICLE; } + private: - void init(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol); // 4J - added + void init(Level* level, double x, double y, double z, float scale, + float rCol, float gCol, float bCol); // 4J - added public: - RedDustParticle(Level *level, double x, double y, double z, float rCol, float gCol, float bCol); + RedDustParticle(Level* level, double x, double y, double z, float rCol, + float gCol, float bCol); float oSize; - RedDustParticle(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + RedDustParticle(Level* level, double x, double y, double z, float scale, + float rCol, float gCol, float bCol); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp b/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp index 15cf3b5d7..58794dbc7 100644 --- a/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp @@ -2,8 +2,8 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SmokeParticle.h" -void SmokeParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void SmokeParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; @@ -11,38 +11,41 @@ void SmokeParticle::init(Level *level, double x, double y, double z, double xa, yd += ya; zd += za; - //rCol = gCol = bCol = (float) (Math::random() * 0.3f); + // rCol = gCol = bCol = (float) (Math::random() * 0.3f); - float br = Math::random(); - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Smoke ); - int r = (colour>>16)&0xFF; - int g = (colour>>8)&0xFF; - int b = colour&0xFF; - rCol = (r/255.0f)*br; - gCol = (g/255.0f)*br; - bCol = (b/255.0f)*br; + float br = Math::random(); + unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Smoke); + int r = (colour >> 16) & 0xFF; + int g = (colour >> 8) & 0xFF; + int b = colour & 0xFF; + rCol = (r / 255.0f) * br; + gCol = (g / 255.0f) * br; + bCol = (b / 255.0f) * br; size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; } -SmokeParticle::SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 1); +SmokeParticle::SmokeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 1); } -SmokeParticle::SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +SmokeParticle::SmokeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void SmokeParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void SmokeParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; @@ -51,8 +54,7 @@ void SmokeParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void SmokeParticle::tick() -{ +void SmokeParticle::tick() { xo = x; yo = y; zo = z; @@ -63,8 +65,7 @@ void SmokeParticle::tick() yd += 0.004; move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -72,8 +73,7 @@ void SmokeParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/SmokeParticle.h b/Minecraft.Client/Rendering/Particles/SmokeParticle.h index 51ee5e17a..f1cf05da5 100644 --- a/Minecraft.Client/Rendering/Particles/SmokeParticle.h +++ b/Minecraft.Client/Rendering/Particles/SmokeParticle.h @@ -1,18 +1,21 @@ #pragma once #include "Particle.h" -class SmokeParticle : public Particle -{ +class SmokeParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SMOKEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_SMOKEPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SmokeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + SmokeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); - }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp index 6e57fc8b5..4dd53aaa3 100644 --- a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp @@ -2,8 +2,8 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SnowShovelParticle.h" -void SnowShovelParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void SnowShovelParticle::init(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; @@ -11,39 +11,41 @@ void SnowShovelParticle::init(Level *level, double x, double y, double z, double yd += ya; zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); + rCol = gCol = bCol = 1 - (float)(Math::random() * 0.3f); size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) ( lifetime * scale ); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; } -SnowShovelParticle::SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - init(level, x, y, z, xa, ya, za, 1); +SnowShovelParticle::SnowShovelParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, xa, ya, za) { + init(level, x, y, z, xa, ya, za, 1); } -SnowShovelParticle::SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, xa, ya, za) -{ - init(level, x, y, z, xa, ya, za, scale); +SnowShovelParticle::SnowShovelParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, float scale) + : Particle(level, x, y, z, xa, ya, za) { + init(level, x, y, z, xa, ya, za, scale); } -void SnowShovelParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void SnowShovelParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; size = oSize * l; Particle::render(t, a, xa, ya, za, xa2, za2); - } -void SnowShovelParticle::tick() -{ +void SnowShovelParticle::tick() { xo = x; yo = y; zo = z; @@ -58,8 +60,7 @@ void SnowShovelParticle::tick() yd *= 0.99f; zd *= 0.99f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h index 3570e2467..065d45941 100644 --- a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h +++ b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h @@ -1,17 +1,21 @@ #pragma once #include "Particle.h" -class SnowShovelParticle : public Particle -{ +class SnowShovelParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SNOWSHOVELPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_SNOWSHOVELPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SnowShovelParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + SnowShovelParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SpellParticle.cpp b/Minecraft.Client/Rendering/Particles/SpellParticle.cpp index f53228112..661f24d2d 100644 --- a/Minecraft.Client/Rendering/Particles/SpellParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SpellParticle.cpp @@ -2,61 +2,55 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SpellParticle.h" -SpellParticle::SpellParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - yd *= 0.2f; - if (xa == 0 && za == 0) - { - xd *= 0.1f; - zd *= 0.1f; - } +SpellParticle::SpellParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + yd *= 0.2f; + if (xa == 0 && za == 0) { + xd *= 0.1f; + zd *= 0.1f; + } - size *= 0.75f; + size *= 0.75f; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - noPhysics = false; + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + noPhysics = false; - baseTex = 8 * 16; + baseTex = 8 * 16; } -void SpellParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; +void SpellParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; - Particle::render(t, a, xa, ya, za, xa2, za2); + Particle::render(t, a, xa, ya, za, xa2, za2); } -void SpellParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SpellParticle::tick() { + xo = x; + yo = y; + zo = z; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); - setMiscTex(baseTex + (7 - age * 8 / lifetime)); + setMiscTex(baseTex + (7 - age * 8 / lifetime)); - yd += 0.004; - move(xd, yd, zd); - if (y == yo) - { - xd *= 1.1; - zd *= 1.1; - } - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; + yd += 0.004; + move(xd, yd, zd); + if (y == yo) { + xd *= 1.1; + zd *= 1.1; + } + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } -void SpellParticle::setBaseTex(int baseTex) -{ - this->baseTex = baseTex; -} \ No newline at end of file +void SpellParticle::setBaseTex(int baseTex) { this->baseTex = baseTex; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SpellParticle.h b/Minecraft.Client/Rendering/Particles/SpellParticle.h index 212fab0bd..29e6d9721 100644 --- a/Minecraft.Client/Rendering/Particles/SpellParticle.h +++ b/Minecraft.Client/Rendering/Particles/SpellParticle.h @@ -2,17 +2,18 @@ #include "Particle.h" -class SpellParticle : public Particle -{ +class SpellParticle : public Particle { private: - int baseTex; + int baseTex; public: - virtual eINSTANCEOF GetType() { return eTYPE_SPELLPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_SPELLPARTICLE; } - SpellParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SpellParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual void tick(); - virtual void setBaseTex(int baseTex); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual void tick(); + virtual void setBaseTex(int baseTex); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SplashParticle.cpp b/Minecraft.Client/Rendering/Particles/SplashParticle.cpp index b71fa6b72..5704aff6d 100644 --- a/Minecraft.Client/Rendering/Particles/SplashParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SplashParticle.cpp @@ -1,12 +1,12 @@ #include "../../Platform/stdafx.h" #include "SplashParticle.h" -SplashParticle::SplashParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : WaterDropParticle(level, x, y, z) -{ +SplashParticle::SplashParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : WaterDropParticle(level, x, y, z) { gravity = 0.04f; setNextMiscAnimTex(); - if (ya == 0 && (xa != 0 || za != 0)) - { + if (ya == 0 && (xa != 0 || za != 0)) { this->xd = xa; this->yd = ya + 0.1; this->zd = za; diff --git a/Minecraft.Client/Rendering/Particles/SplashParticle.h b/Minecraft.Client/Rendering/Particles/SplashParticle.h index 176b2c872..3bcbccab0 100644 --- a/Minecraft.Client/Rendering/Particles/SplashParticle.h +++ b/Minecraft.Client/Rendering/Particles/SplashParticle.h @@ -1,9 +1,9 @@ #pragma once #include "WaterDropParticle.h" -class SplashParticle : public WaterDropParticle -{ +class SplashParticle : public WaterDropParticle { public: - virtual eINSTANCEOF GetType() { return eType_SPLASHPARTICLE; } - SplashParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + virtual eINSTANCEOF GetType() { return eType_SPLASHPARTICLE; } + SplashParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp b/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp index 81d62e265..924611472 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp @@ -6,37 +6,41 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" -SuspendedParticle::SuspendedParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x, y - 2 / 16.0f, z, xa, ya, za) -{ - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Suspend ); - rCol = ( (col>>16)&0xFF )/255.0f, gCol = ( (col>>8)&0xFF )/255.0, bCol = ( col&0xFF )/255.0; +SuspendedParticle::SuspendedParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y - 2 / 16.0f, z, xa, ya, za) { + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Suspend); + rCol = ((col >> 16) & 0xFF) / 255.0f, gCol = ((col >> 8) & 0xFF) / 255.0, + bCol = (col & 0xFF) / 255.0; - //rCol = 0.4f; - //gCol = 0.4f; - //bCol = 0.7f; + // rCol = 0.4f; + // gCol = 0.4f; + // bCol = 0.7f; - setMiscTex(0); - this->setSize(0.01f, 0.01f); + setMiscTex(0); + this->setSize(0.01f, 0.01f); - size = size * (random->nextFloat() * 0.6f + 0.2f); + size = size * (random->nextFloat() * 0.6f + 0.2f); - xd = xa * 0.0f; - yd = ya * 0.0f; - zd = za * 0.0f; + xd = xa * 0.0f; + yd = ya * 0.0f; + zd = za * 0.0f; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(16 / (Math::random() * 0.8 + 0.2)); } -void SuspendedParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SuspendedParticle::tick() { + xo = x; + yo = y; + zo = z; - move(xd, yd, zd); + move(xd, yd, zd); - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != + Material::water) + remove(); - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedParticle.h b/Minecraft.Client/Rendering/Particles/SuspendedParticle.h index 8273b423e..d3843cc1c 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedParticle.h +++ b/Minecraft.Client/Rendering/Particles/SuspendedParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" -class SuspendedParticle : public Particle -{ +class SuspendedParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SUSPENDEDPARTICLE; } - SuspendedParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void tick(); + virtual eINSTANCEOF GetType() { return eType_SUSPENDEDPARTICLE; } + SuspendedParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp index 7d719ec32..c25074575 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp @@ -3,35 +3,36 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Util/JavaMath.h" -SuspendedTownParticle::SuspendedTownParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - float br = random->nextFloat() * 0.1f + 0.2f; - rCol = br; - gCol = br; - bCol = br; - setMiscTex(0); - this->setSize(0.02f, 0.02f); +SuspendedTownParticle::SuspendedTownParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, xa, ya, za) { + float br = random->nextFloat() * 0.1f + 0.2f; + rCol = br; + gCol = br; + bCol = br; + setMiscTex(0); + this->setSize(0.02f, 0.02f); - size = size * (random->nextFloat() * 0.6f + 0.5f); + size = size * (random->nextFloat() * 0.6f + 0.5f); - xd *= 0.02f; - yd *= 0.02f; - zd *= 0.02f; + xd *= 0.02f; + yd *= 0.02f; + zd *= 0.02f; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); - this->noPhysics = true; + lifetime = (int)(20 / (Math::random() * 0.8 + 0.2)); + this->noPhysics = true; } -void SuspendedTownParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SuspendedTownParticle::tick() { + xo = x; + yo = y; + zo = z; - move(xd, yd, zd); - xd *= 0.99; - yd *= 0.99; - zd *= 0.99; + move(xd, yd, zd); + xd *= 0.99; + yd *= 0.99; + zd *= 0.99; - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h index 1d5318413..d443456ec 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h +++ b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" -class SuspendedTownParticle : public Particle -{ +class SuspendedTownParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SUSPENDEDTOWNPARTICLE; } - SuspendedTownParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void tick(); + virtual eINSTANCEOF GetType() { return eType_SUSPENDEDTOWNPARTICLE; } + SuspendedTownParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp index 7f6318fe9..0272da4b9 100644 --- a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp @@ -5,76 +5,70 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Util/Mth.h" -TakeAnimationParticle::TakeAnimationParticle(Level *level, std::shared_ptr item, std::shared_ptr target, float yOffs) : Particle(level, item->x, item->y, item->z, item->xd, item->yd, item->zd) -{ - // 4J - added initialisers - life = 0; - lifeTime = 0; +TakeAnimationParticle::TakeAnimationParticle(Level* level, + std::shared_ptr item, + std::shared_ptr target, + float yOffs) + : Particle(level, item->x, item->y, item->z, item->xd, item->yd, item->zd) { + // 4J - added initialisers + life = 0; + lifeTime = 0; this->item = item; this->target = target; lifeTime = 3; this->yOffs = yOffs; - } -TakeAnimationParticle::~TakeAnimationParticle() -{ -} +TakeAnimationParticle::~TakeAnimationParticle() {} -void TakeAnimationParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void TakeAnimationParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float time = (life + a) / lifeTime; - time = time*time; + time = time * time; double xo = item->x; double yo = item->y; double zo = item->z; double xt = target->xOld + (target->x - target->xOld) * a; - double yt = target->yOld + (target->y - target->yOld) * a+yOffs; + double yt = target->yOld + (target->y - target->yOld) * a + yOffs; double zt = target->zOld + (target->z - target->zOld) * a; double xx = xo + (xt - xo) * time; double yy = yo + (yt - yo) * time; double zz = zo + (zt - zo) * time; - + int xTile = Mth::floor(xx); int yTile = Mth::floor(yy + heightOffset / 2.0f); int zTile = Mth::floor(zz); - // 4J - change brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { int col = getLightColor(a); - int u = col%65536; - int v = col/65536; - glMultiTexCoord2f(GL_TEXTURE1, u/1.0f, v/1.0f); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); + } else { + float br = level->getBrightness(xTile, yTile, zTile); + glColor4f(br, br, br, 1); } - else - { - float br = level->getBrightness(xTile, yTile, zTile); - glColor4f(br, br, br, 1); - } - - xx-=xOff; - yy-=yOff; - zz-=zOff; - - - EntityRenderDispatcher::instance->render(item, (float)xx, (float)yy, (float)zz, item->yRot, a); + xx -= xOff; + yy -= yOff; + zz -= zOff; + + EntityRenderDispatcher::instance->render(item, (float)xx, (float)yy, + (float)zz, item->yRot, a); } -void TakeAnimationParticle::tick() -{ +void TakeAnimationParticle::tick() { life++; if (life == lifeTime) remove(); } -int TakeAnimationParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int TakeAnimationParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } diff --git a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h index 33c4535f3..d1943b536 100644 --- a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h +++ b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" class Entity; -class TakeAnimationParticle : public Particle -{ +class TakeAnimationParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_TAKEANIMATIONPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_TAKEANIMATIONPARTICLE; } + private: std::shared_ptr item; std::shared_ptr target; @@ -14,9 +14,11 @@ private: float yOffs; public: - TakeAnimationParticle(Level *level, std::shared_ptr item, std::shared_ptr target, float yOffs); - ~TakeAnimationParticle(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + TakeAnimationParticle(Level* level, std::shared_ptr item, + std::shared_ptr target, float yOffs); + ~TakeAnimationParticle(); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); virtual int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp b/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp index 8cac8d642..3dcff7e57 100644 --- a/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp @@ -5,71 +5,84 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -TerrainParticle::TerrainParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Tile *tile, int face, int data, Textures *textures) : Particle(level, x, y, z, xa, ya, za) -{ +TerrainParticle::TerrainParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, Tile* tile, + int face, int data, Textures* textures) + : Particle(level, x, y, z, xa, ya, za) { this->tile = tile; - this->setTex(textures, tile->getTexture(0, data)); // 4J - change brought forward from 1.8.2 to fix purple particles on door damage + this->setTex( + textures, + tile->getTexture(0, data)); // 4J - change brought forward from 1.8.2 + // to fix purple particles on door damage this->gravity = tile->gravity; rCol = gCol = bCol = 0.6f; size /= 2; } -std::shared_ptr TerrainParticle::init(int x, int y, int z, int data) // 4J - added data parameter +std::shared_ptr TerrainParticle::init( + int x, int y, int z, int data) // 4J - added data parameter { - if (tile == Tile::grass) return std::dynamic_pointer_cast( shared_from_this() ); - int col = tile->getColor(level, x, y, z, data); // 4J - added data parameter + if (tile == Tile::grass) + return std::dynamic_pointer_cast(shared_from_this()); + int col = + tile->getColor(level, x, y, z, data); // 4J - added data parameter rCol *= ((col >> 16) & 0xff) / 255.0f; gCol *= ((col >> 8) & 0xff) / 255.0f; bCol *= ((col) & 0xff) / 255.0f; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -std::shared_ptr TerrainParticle::init(int data) -{ - if (tile == Tile::grass) return std::dynamic_pointer_cast( shared_from_this() ); - int col = tile->getColor(data); - rCol *= ((col >> 16) & 0xff) / 255.0f; - gCol *= ((col >> 8) & 0xff) / 255.0f; - bCol *= ((col) & 0xff) / 255.0f; - return std::dynamic_pointer_cast( shared_from_this() ); +std::shared_ptr TerrainParticle::init(int data) { + if (tile == Tile::grass) + return std::dynamic_pointer_cast(shared_from_this()); + int col = tile->getColor(data); + rCol *= ((col >> 16) & 0xff) / 255.0f; + gCol *= ((col >> 8) & 0xff) / 255.0f; + bCol *= ((col) & 0xff) / 255.0f; + return std::dynamic_pointer_cast(shared_from_this()); } -int TerrainParticle::getParticleTexture() -{ - return ParticleEngine::TERRAIN_TEXTURE; +int TerrainParticle::getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; } -void TerrainParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void TerrainParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float u0 = (texX + uo / 4.0f) / 16.0f; float u1 = u0 + 0.999f / 16.0f / 4; float v0 = (texY + vo / 4.0f) / 16.0f; float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - } + if (tex != NULL) { + u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + } - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); + float x = (float)(xo + (this->x - xo) * a - xOff); + float y = (float)(yo + (this->y - yo) * a - yOff); + float z = (float)(zo + (this->z - zo) * a - zOff); - // 4J - don't render terrain particles that are less than a metre away, to try and avoid large particles that are causing us problems with - // photosensitivity testing - float distSq = (x*x + y*y + z*z); - if( distSq < 1.0f ) return; + // 4J - don't render terrain particles that are less than a metre away, to + // try and avoid large particles that are causing us problems with + // photosensitivity testing + float distSq = (x * x + y * y + z * z); + if (distSq < 1.0f) return; - float br = SharedConstants::TEXTURE_LIGHTING ? 1.0f : getBrightness(a); // 4J - change brought forward from 1.8.2 + float br = + SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : getBrightness(a); // 4J - change brought forward from 1.8.2 t->color(br * rCol, br * gCol, br * bCol); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u0), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u1), (float)( v1)); - + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u0), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u1), (float)(v1)); } diff --git a/Minecraft.Client/Rendering/Particles/TerrainParticle.h b/Minecraft.Client/Rendering/Particles/TerrainParticle.h index df9ca42fe..28db9b2d8 100644 --- a/Minecraft.Client/Rendering/Particles/TerrainParticle.h +++ b/Minecraft.Client/Rendering/Particles/TerrainParticle.h @@ -2,17 +2,21 @@ #include "Particle.h" class Tile; -class TerrainParticle : public Particle -{ +class TerrainParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_TERRAINPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_TERRAINPARTICLE; } + private: - Tile *tile; + Tile* tile; public: - TerrainParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Tile *tile, int face, int data, Textures *textures); - std::shared_ptr init(int x, int y, int z, int data); // 4J - added data parameter - std::shared_ptr init(int data); + TerrainParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, Tile* tile, int face, int data, + Textures* textures); + std::shared_ptr init( + int x, int y, int z, int data); // 4J - added data parameter + std::shared_ptr init(int data); virtual int getParticleTexture(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp b/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp index 36c14c98c..150dca852 100644 --- a/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp @@ -5,25 +5,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -WaterDropParticle::WaterDropParticle(Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ +WaterDropParticle::WaterDropParticle(Level* level, double x, double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { xd *= 0.3f; - yd = (float) Math::random() * 0.2f + 0.1f; + yd = (float)Math::random() * 0.2f + 0.1f; zd *= 0.3f; rCol = 1.0f; gCol = 1.0f; bCol = 1.0f; - setMiscTex(16+3+random->nextInt(4)); + setMiscTex(16 + 3 + random->nextInt(4)); this->setSize(0.01f, 0.01f); gravity = 0.06f; - noPhysics = true; // 4J - optimisation - do we really need collision on these? its really slow... - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + noPhysics = true; // 4J - optimisation - do we really need collision on + // these? its really slow... + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); } -void WaterDropParticle::tick() -{ +void WaterDropParticle::tick() { xo = x; yo = y; zo = z; @@ -36,19 +36,19 @@ void WaterDropParticle::tick() if (lifetime-- <= 0) remove(); - if (onGround) - { + if (onGround) { if (Math::random() < 0.5) remove(); xd *= 0.7f; zd *= 0.7f; } - Material *m = level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - if (m->isLiquid() || m->isSolid()) - { - double y0 = Mth::floor(y) + 1 - LiquidTile::getHeight(level->getData(Mth::floor(x), Mth::floor(y), Mth::floor(z))); - if (y < y0) - { + Material* m = + level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + if (m->isLiquid() || m->isSolid()) { + double y0 = Mth::floor(y) + 1 - + LiquidTile::getHeight(level->getData( + Mth::floor(x), Mth::floor(y), Mth::floor(z))); + if (y < y0) { remove(); } } diff --git a/Minecraft.Client/Rendering/Particles/WaterDropParticle.h b/Minecraft.Client/Rendering/Particles/WaterDropParticle.h index 0822cef8a..a1e501a5c 100644 --- a/Minecraft.Client/Rendering/Particles/WaterDropParticle.h +++ b/Minecraft.Client/Rendering/Particles/WaterDropParticle.h @@ -1,10 +1,9 @@ #pragma once #include "Particle.h" -class WaterDropParticle : public Particle -{ +class WaterDropParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_WATERDROPPARTICLE; } - WaterDropParticle(Level *level, double x, double y, double z) ; + virtual eINSTANCEOF GetType() { return eType_WATERDROPPARTICLE; } + WaterDropParticle(Level* level, double x, double y, double z); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Polygon.cpp b/Minecraft.Client/Rendering/Polygon.cpp index 73c7cca83..28c37260e 100644 --- a/Minecraft.Client/Rendering/Polygon.cpp +++ b/Minecraft.Client/Rendering/Polygon.cpp @@ -2,8 +2,7 @@ #include "Polygon.h" // 4J added for common init code -void _Polygon::_init(VertexArray vertices) -{ +void _Polygon::_init(VertexArray vertices) { vertexCount = 0; _flipNormal = false; @@ -11,18 +10,15 @@ void _Polygon::_init(VertexArray vertices) vertexCount = vertices.length; } -_Polygon::_Polygon(VertexArray vertices) -{ - _init(vertices); -} +_Polygon::_Polygon(VertexArray vertices) { _init(vertices); } -_Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float xTexSize, float yTexSize) -{ - _init(vertices); +_Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, + float xTexSize, float yTexSize) { + _init(vertices); - // 4J - added - don't assume that u1 > u0, v1 > v0 - float us = ( u1 > u0 ) ? ( 0.1f / xTexSize ) : ( -0.1f / xTexSize ); - float vs = ( v1 > v0 ) ? ( 0.1f / yTexSize ) : ( -0.1f / yTexSize ); + // 4J - added - don't assume that u1 > u0, v1 > v0 + float us = (u1 > u0) ? (0.1f / xTexSize) : (-0.1f / xTexSize); + float vs = (v1 > v0) ? (0.1f / yTexSize) : (-0.1f / yTexSize); vertices[0] = vertices[0]->remap(u1 / xTexSize - us, v0 / yTexSize + vs); vertices[1] = vertices[1]->remap(u0 / xTexSize + us, v0 / yTexSize + vs); @@ -30,8 +26,8 @@ _Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float x vertices[3] = vertices[3]->remap(u1 / xTexSize - us, v1 / yTexSize - vs); } -_Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, float v1) -{ +_Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, + float v1) { _init(vertices); vertices[0] = vertices[0]->remap(u1, v0); @@ -40,41 +36,35 @@ _Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, float v1) vertices[3] = vertices[3]->remap(u1, v1); } -void _Polygon::mirror() -{ +void _Polygon::mirror() { VertexArray newVertices = VertexArray(vertices.length); for (unsigned int i = 0; i < vertices.length; i++) newVertices[i] = vertices[vertices.length - i - 1]; - delete [] vertices.data; + delete[] vertices.data; vertices = newVertices; } -void _Polygon::render(Tesselator *t, float scale) -{ - Vec3 *v0 = vertices[1]->pos->vectorTo(vertices[0]->pos); - Vec3 *v1 = vertices[1]->pos->vectorTo(vertices[2]->pos); - Vec3 *n = v1->cross(v0)->normalize(); - +void _Polygon::render(Tesselator* t, float scale) { + Vec3* v0 = vertices[1]->pos->vectorTo(vertices[0]->pos); + Vec3* v1 = vertices[1]->pos->vectorTo(vertices[2]->pos); + Vec3* n = v1->cross(v0)->normalize(); + t->begin(); - if (_flipNormal) - { + if (_flipNormal) { t->normal(-(float)n->x, -(float)n->y, -(float)n->z); - } - else - { + } else { t->normal((float)n->x, (float)n->y, (float)n->z); } - for (int i = 0; i < 4; i++) - { - Vertex *v = vertices[i]; - t->vertexUV((float)(v->pos->x * scale), (float)( v->pos->y * scale), (float)( v->pos->z * scale), (float)( v->u), (float)( v->v)); + for (int i = 0; i < 4; i++) { + Vertex* v = vertices[i]; + t->vertexUV((float)(v->pos->x * scale), (float)(v->pos->y * scale), + (float)(v->pos->z * scale), (float)(v->u), (float)(v->v)); } t->end(); } -_Polygon *_Polygon::flipNormal() -{ +_Polygon* _Polygon::flipNormal() { _flipNormal = true; return this; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Polygon.h b/Minecraft.Client/Rendering/Polygon.h index e8c71f8b0..38c6e9094 100644 --- a/Minecraft.Client/Rendering/Polygon.h +++ b/Minecraft.Client/Rendering/Polygon.h @@ -3,20 +3,21 @@ #include "Tesselator.h" #include "../../Minecraft.World/Util/ArrayWithLength.h" -class _Polygon -{ +class _Polygon { public: - VertexArray vertices; + VertexArray vertices; int vertexCount; + private: - bool _flipNormal; + bool _flipNormal; public: - void _init(VertexArray vertices); // 4J added for common init code - _Polygon(VertexArray vertices); - _Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float xTexSize, float yTexSize); + void _init(VertexArray vertices); // 4J added for common init code + _Polygon(VertexArray vertices); + _Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, + float xTexSize, float yTexSize); _Polygon(VertexArray vertices, float u0, float v0, float u1, float v1); void mirror(); - void render(Tesselator *t, float scale); - _Polygon *flipNormal(); + void render(Tesselator* t, float scale); + _Polygon* flipNormal(); }; diff --git a/Minecraft.Client/Rendering/Tesselator.cpp b/Minecraft.Client/Rendering/Tesselator.cpp index 517c8a61d..acc2ce854 100644 --- a/Minecraft.Client/Rendering/Tesselator.cpp +++ b/Minecraft.Client/Rendering/Tesselator.cpp @@ -26,176 +26,197 @@ int normal; */ unsigned int Tesselator::tlsIdx = TlsAlloc(); -Tesselator *Tesselator::getInstance() -{ - return (Tesselator *)TlsGetValue(tlsIdx); +Tesselator* Tesselator::getInstance() { + return (Tesselator*)TlsGetValue(tlsIdx); } -void Tesselator::CreateNewThreadStorage(int bytes) -{ - Tesselator *instance = new Tesselator(bytes/4); - TlsSetValue(tlsIdx, instance); +void Tesselator::CreateNewThreadStorage(int bytes) { + Tesselator* instance = new Tesselator(bytes / 4); + TlsSetValue(tlsIdx, instance); } // she tessalate my vertices till i render -Tesselator::Tesselator(int size) -{ - // 4J - this block of things moved to constructor from general initialisations round Java class - vertices = 0; - hasColor = false; - hasTexture = false; - hasTexture2 = false; - hasNormal = false; - p = 0; - count = 0; - _noColor = false; - tesselating = false; - vboMode = false; - vboId = 0; - vboCounts = 10; +Tesselator::Tesselator(int size) { + // 4J - this block of things moved to constructor from general + // initialisations round Java class + vertices = 0; + hasColor = false; + hasTexture = false; + hasTexture2 = false; + hasNormal = false; + p = 0; + count = 0; + _noColor = false; + tesselating = false; + vboMode = false; + vboId = 0; + vboCounts = 10; - // 4J - adding these things to constructor just to be sure that they are initialised with something - u = v = 0; - col = 0; - mode = 0; - xo = yo = zo = 0; - xoo = yoo = zoo = 0; // 4J added - _normal = 0; + // 4J - adding these things to constructor just to be sure that they are + // initialised with something + u = v = 0; + col = 0; + mode = 0; + xo = yo = zo = 0; + xoo = yoo = zoo = 0; // 4J added + _normal = 0; - useCompactFormat360 = false; // 4J added - mipmapEnable = true; // 4J added - useProjectedTexturePixelShader = false; // 4J added + useCompactFormat360 = false; // 4J added + mipmapEnable = true; // 4J added + useProjectedTexturePixelShader = false; // 4J added - this->size = size; + this->size = size; - _array = new intArray(size); + _array = new intArray(size); - vboMode = USE_VBO; // 4J removed - && GLContext.getCapabilities().GL_ARB_vertex_buffer_object; - if (vboMode) - { - vboIds = MemoryTracker::createIntBuffer(vboCounts); - ARBVertexBufferObject::glGenBuffersARB(vboIds); - } + vboMode = + USE_VBO; // 4J removed - && + // GLContext.getCapabilities().GL_ARB_vertex_buffer_object; + if (vboMode) { + vboIds = MemoryTracker::createIntBuffer(vboCounts); + ARBVertexBufferObject::glGenBuffersARB(vboIds); + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - alphaCutOutEnabled = false; + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + alphaCutOutEnabled = false; - // this is the cut out enabled vertex array - _array2 = new intArray(size); + // this is the cut out enabled vertex array + _array2 = new intArray(size); vertices2 = 0; p2 = 0; #endif } -Tesselator *Tesselator::getUniqueInstance(int size) -{ +Tesselator* Tesselator::getUniqueInstance(int size) { return new Tesselator(size); } -void Tesselator::end() -{ -// if (!tesselating) throw new IllegalStateException("Not tesselating!"); // 4J - removed +void Tesselator::end() { + // if (!tesselating) throw new IllegalStateException("Not tesselating!"); + // // 4J - removed tesselating = false; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Check both counts for valid vertices - if( vertices > 0 || vertices2 > 0 ) + // AP - alpha cut out is expensive on vita. Check both counts for valid + // vertices + if (vertices > 0 || vertices2 > 0) #else if (vertices > 0) #endif - { - // 4J - a lot of stuff taken out here for fiddling round with enable client states etc. - // that don't matter for our renderer - if (!hasColor) - { - // 4J - TEMP put in fixed vertex colors if we don't have any, until we have a shader that can cope without them - // Use 0x00000000 (not 0xffffffff) so DrawVertices skips glColor for these vertices, - // letting any caller-set GL colour (e.g. sky colour) pass through unmodified. - unsigned int *pColData = (unsigned int *)_array->data; - pColData += 5; - for( int i = 0; i < vertices; i++ ) - { - *pColData = 0x00000000; - pColData += 8; - } + { + // 4J - a lot of stuff taken out here for fiddling round with enable + // client states etc. that don't matter for our renderer + if (!hasColor) { + // 4J - TEMP put in fixed vertex colors if we don't have any, until + // we have a shader that can cope without them Use 0x00000000 (not + // 0xffffffff) so DrawVertices skips glColor for these vertices, + // letting any caller-set GL colour (e.g. sky colour) pass through + // unmodified. + unsigned int* pColData = (unsigned int*)_array->data; + pColData += 5; + for (int i = 0; i < vertices; i++) { + *pColData = 0x00000000; + pColData += 8; + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Check both counts for valid vertices - pColData = (unsigned int *)_array2->data; - pColData += 5; - for( int i = 0; i < vertices2; i++ ) - { - *pColData = 0xffffffff; - pColData += 8; - } -#endif - } - if (mode == GL_QUADS && TRIANGLE_MODE) - { - // glDrawArrays(GL_TRIANGLES, 0, vertices); // 4J - changed for xbox -#ifdef _XBOX - RenderManager.DrawVertices(D3DPT_TRIANGLELIST,vertices,_array->data, - useCompactFormat360?C4JRender::VERTEX_TYPE_PS3_TS2_CS1:C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, - useProjectedTexturePixelShader?C4JRender::PIXEL_SHADER_TYPE_PROJECTION:C4JRender::PIXEL_SHADER_TYPE_STANDARD); -#else - RenderManager.DrawVertices(C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST,vertices,_array->data, - useCompactFormat360?C4JRender::VERTEX_TYPE_COMPRESSED:C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, - useProjectedTexturePixelShader?C4JRender::PIXEL_SHADER_TYPE_PROJECTION:C4JRender::PIXEL_SHADER_TYPE_STANDARD); + // AP - alpha cut out is expensive on vita. Check both counts for + // valid vertices + pColData = (unsigned int*)_array2->data; + pColData += 5; + for (int i = 0; i < vertices2; i++) { + *pColData = 0xffffffff; + pColData += 8; + } #endif } - else - { -// glDrawArrays(mode, 0, vertices); // 4J - changed for xbox - // For compact vertices, the vertexCount has to be calculated from the amount of data written, as - // we insert extra fake vertices to encode supplementary data for more awkward quads that have non - // axis aligned UVs (eg flowing lava/water) + if (mode == GL_QUADS && TRIANGLE_MODE) { + // glDrawArrays(GL_TRIANGLES, 0, vertices); // 4J - changed for xbox #ifdef _XBOX - int vertexCount = vertices; - if( useCompactFormat360 ) - { - vertexCount = p / 2; - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PS3_TS2_CS1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - else - { - if( useProjectedTexturePixelShader ) - { - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); - } - else - { - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - } + RenderManager.DrawVertices( + D3DPT_TRIANGLELIST, vertices, _array->data, + useCompactFormat360 + ? C4JRender::VERTEX_TYPE_PS3_TS2_CS1 + : C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + useProjectedTexturePixelShader + ? C4JRender::PIXEL_SHADER_TYPE_PROJECTION + : C4JRender::PIXEL_SHADER_TYPE_STANDARD); #else - int vertexCount = vertices; - if( useCompactFormat360 ) - { + RenderManager.DrawVertices( + C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST, vertices, _array->data, + useCompactFormat360 + ? C4JRender::VERTEX_TYPE_COMPRESSED + : C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + useProjectedTexturePixelShader + ? C4JRender::PIXEL_SHADER_TYPE_PROJECTION + : C4JRender::PIXEL_SHADER_TYPE_STANDARD); +#endif + } else { +// glDrawArrays(mode, 0, vertices); // 4J - changed for xbox +// For compact vertices, the vertexCount has to be calculated from the amount of +// data written, as we insert extra fake vertices to encode supplementary data +// for more awkward quads that have non axis aligned UVs (eg flowing lava/water) +#ifdef _XBOX + int vertexCount = vertices; + if (useCompactFormat360) { + vertexCount = p / 2; + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PS3_TS2_CS1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } else { + if (useProjectedTexturePixelShader) { + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, + C4JRender::PIXEL_SHADER_TYPE_PROJECTION); + } else { + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + } +#else + int vertexCount = vertices; + if (useCompactFormat360) { #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Render non-cut out stuff first then send the cut out stuff - if( vertexCount ) - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - if( vertices2 ) - { - RenderManager.DrawVerticesCutOut((C4JRender::ePrimitiveType)mode,vertices2,_array2->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } + // AP - alpha cut out is expensive on vita. Render non-cut out + // stuff first then send the cut out stuff + if (vertexCount) { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + if (vertices2) { + RenderManager.DrawVerticesCutOut( + (C4JRender::ePrimitiveType)mode, vertices2, + _array2->data, C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } #else - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); #endif - } - else - { - if( useProjectedTexturePixelShader ) - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); - } - else - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - } + } else { + if (useProjectedTexturePixelShader) { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, + C4JRender::PIXEL_SHADER_TYPE_PROJECTION); + } else { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + } #endif } glDisableClientState(GL_VERTEX_ARRAY); @@ -207,71 +228,58 @@ void Tesselator::end() clear(); } -void Tesselator::clear() -{ +void Tesselator::clear() { vertices = 0; p = 0; count = 0; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Clear the cut out variables + // AP - alpha cut out is expensive on vita. Clear the cut out variables vertices2 = 0; p2 = 0; #endif } -void Tesselator::begin() -{ +void Tesselator::begin() { begin(GL_QUADS); - bounds.reset(); // 4J MGH - added -} - -void Tesselator::useProjectedTexture(bool enable) -{ - useProjectedTexturePixelShader = enable; + bounds.reset(); // 4J MGH - added } -void Tesselator::useCompactVertices(bool enable) -{ - useCompactFormat360 = enable; +void Tesselator::useProjectedTexture(bool enable) { + useProjectedTexturePixelShader = enable; } -bool Tesselator::getCompactVertices() -{ - return useCompactFormat360; +void Tesselator::useCompactVertices(bool enable) { + useCompactFormat360 = enable; } -bool Tesselator::setMipmapEnable(bool enable) -{ - bool prev = mipmapEnable; - mipmapEnable = enable; - return prev; +bool Tesselator::getCompactVertices() { return useCompactFormat360; } + +bool Tesselator::setMipmapEnable(bool enable) { + bool prev = mipmapEnable; + mipmapEnable = enable; + return prev; } #ifdef __PSVITA__ -// AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha -void Tesselator::setAlphaCutOut(bool enable) -{ - alphaCutOutEnabled = enable; -} +// AP - alpha cut out is expensive on vita. Use this to defer primitives that +// use icons with alpha +void Tesselator::setAlphaCutOut(bool enable) { alphaCutOutEnabled = enable; } // AP - was any cut out geometry added since the last call to Clear -bool Tesselator::getCutOutFound() -{ - if( vertices2 ) - return true; +bool Tesselator::getCutOutFound() { + if (vertices2) return true; - return false; + return false; } #endif -void Tesselator::begin(int mode) -{ - /* // 4J - removed - if (tesselating) { - throw new IllegalStateException("Already tesselating!"); - } */ +void Tesselator::begin(int mode) { + /* // 4J - removed +if (tesselating) { + throw new IllegalStateException("Already tesselating!"); +} */ tesselating = true; clear(); @@ -279,40 +287,32 @@ void Tesselator::begin(int mode) hasNormal = false; hasColor = false; hasTexture = false; - hasTexture2 = false; + hasTexture2 = false; _noColor = false; } -void Tesselator::tex(float u, float v) -{ +void Tesselator::tex(float u, float v) { hasTexture = true; this->u = u; this->v = v; } -void Tesselator::tex2(int tex2) -{ +void Tesselator::tex2(int tex2) { hasTexture2 = true; - this->_tex2 = tex2; + this->_tex2 = tex2; } -void Tesselator::color(float r, float g, float b) -{ - color((int) (r * 255), (int) (g * 255), (int) (b * 255)); +void Tesselator::color(float r, float g, float b) { + color((int)(r * 255), (int)(g * 255), (int)(b * 255)); } -void Tesselator::color(float r, float g, float b, float a) -{ - color((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); +void Tesselator::color(float r, float g, float b, float a) { + color((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255)); } -void Tesselator::color(int r, int g, int b) -{ - color(r, g, b, 255); -} +void Tesselator::color(int r, int g, int b) { color(r, g, b, 255); } -void Tesselator::color(int r, int g, int b, int a) -{ +void Tesselator::color(int r, int g, int b, int a) { if (_noColor) return; if (r > 255) r = 255; @@ -325,48 +325,52 @@ void Tesselator::color(int r, int g, int b, int a) if (a < 0) a = 0; hasColor = true; - // 4J - removed little-endian option + // 4J - removed little-endian option col = (r << 24) | (g << 16) | (b << 8) | (a); } -void Tesselator::color(std::uint8_t r, std::uint8_t g, std::uint8_t b) -{ - color(r & 0xff, g & 0xff, b & 0xff); +void Tesselator::color(std::uint8_t r, std::uint8_t g, std::uint8_t b) { + color(r & 0xff, g & 0xff, b & 0xff); } -void Tesselator::vertexUV(float x, float y, float z, float u, float v) -{ +void Tesselator::vertexUV(float x, float y, float z, float u, float v) { tex(u, v); vertex(x, y, z); } -// Pack the 4 vertices of a quad up into a compact format. This is structured as 8 bytes per vertex, -// arranged in blocks of 4 vertices per quad. Currently this is (one letter per nyblle): +// Pack the 4 vertices of a quad up into a compact format. This is structured as +// 8 bytes per vertex, arranged in blocks of 4 vertices per quad. Currently this +// is (one letter per nyblle): // // cccc xxyy zzll rgbi (vertex 0) // umin xxyy zzll rgbi (vertex 1) // vmin xxyy zzll rgbi (vertex 2) // udvd xxyy zzll rgbi (vertex 3) // -// where: cccc is a 15-bit (5 bits per x/y/z) origin position / offset for the whole quad. Each -// component is unsigned, and offset by 16 so has a range 0 to 31 actually representing -16 to 15 -// xx,yy,zz are 8-bit deltas from this origin to each vertex. These are unsigned 1.7 fixed point, ie +// where: cccc is a 15-bit (5 bits per x/y/z) origin position / offset +// for the whole quad. Each +// component is unsigned, and offset by 16 +//so has a range 0 to 31 actually representing -16 to 15 +// xx,yy,zz are 8-bit deltas from this origin to each vertex. These are +// unsigned 1.7 fixed point, ie // representing a range of 0 to 1.9921875 // rgb is 4:4:4 RGB -// umin, vmin are 3:13 unsigned fixed point UVs reprenting the min u and v required by the quad -// ud,vd are 8-bit unsigned fixed pont UV deltas, which can be added to umin/vmin to get umax, vmax -// and therefore define the 4 corners of an axis aligned UV mapping -// i is a code per vertex that indicates which of umin/umax should be used for u, and which -// of vmin/vmax should be used for v for this vertex. The coding is: -// 0 - u = umin, v = vmin -// 1 - u = umin, v = vmax -// 2 - u = umax, v = vmin -// 3 - u = umax, v = vmax -// 4 - not axis aligned, use uv stored in the vertex data 4 on from this one -// ll is an 8-bit (4 bit per u/v) index into the current lighting texture +// umin, vmin are 3:13 unsigned fixed point UVs reprenting the min u and +// v required by the quad ud,vd are 8-bit unsigned fixed pont +// UV deltas, which can be added to umin/vmin to get umax, vmax +// and therefore define the 4 corners of +//an axis aligned UV mapping +// i is a code per vertex that indicates which of umin/umax +// should be used for u, and which +// of vmin/vmax should be used for v for +//this vertex. The coding is: 0 - u = umin, v = vmin 1 - u = umin, v = vmax 2 - +//u = umax, v = vmin 3 - u = umax, v = vmax 4 - not axis aligned, use uv stored +//in the vertex data 4 on from this one ll is an 8-bit (4 bit per +//u/v) index into the current lighting texture // -// For quads that don't have axis aligned UVs (ie have a code for 4 in i as described above) the 8 byte vertex -// is followed by a further 8 bytes which have explicit UVs defined for each vertex: +// For quads that don't have axis aligned UVs (ie have a code for 4 in i as +// described above) the 8 byte vertex is followed by a further 8 bytes which +// have explicit UVs defined for each vertex: // // 0000 0000 uuuu vvvv (vertex 0) // 0000 0000 uuuu vvvv (vertex 1) @@ -374,489 +378,481 @@ void Tesselator::vertexUV(float x, float y, float z, float u, float v) // 0000 0000 uuuu vvvv (vertex 3) // -void Tesselator::packCompactQuad() -{ - // Offset x/y/z by 16 so that we can deal with a -16 -> 16 range - for( int i = 0; i < 4; i++ ) - { - m_ix[i] += 16 * 128; - m_iy[i] += 16 * 128; - m_iz[i] += 16 * 128; - } - // Find min x/y/z - unsigned int minx = m_ix[0]; - unsigned int miny = m_iy[0]; - unsigned int minz = m_iz[0]; - for( int i = 1; i < 4; i++ ) - { - if( m_ix[i] < minx ) minx = m_ix[i]; - if( m_iy[i] < miny ) miny = m_iy[i]; - if( m_iz[i] < minz ) minz = m_iz[i]; - } - // Everything has been scaled by a factor of 128 to get it into an int, and so - // the minimum now should be in the range of (0->32) * 128. Get the base x/y/z - // that our quad will be referenced from now, which can be stored in 5 bits - unsigned int basex = ( minx >> 7 ); - unsigned int basey = ( miny >> 7 ); - unsigned int basez = ( minz >> 7 ); - // If the min is 32, then this whole quad must be in that plane - make the min 15 instead so - // we can still offset from that with our delta to get to the exact edge - if( basex == 32 ) basex = 31; - if( basey == 32 ) basey = 31; - if( basez == 32 ) basez = 31; - // Now get deltas to each vertex - these have an 8-bit range so they can span a - // full unit range from the base position - for( int i = 0; i < 4; i++ ) - { - m_ix[i] -= basex << 7; - m_iy[i] -= basey << 7; - m_iz[i] -= basez << 7; - } - // Now write the data out - unsigned int *data = (unsigned int *)&_array->data[p]; - - for( int i = 0; i < 4; i++ ) - { - data[i * 2 + 0] = ( m_ix[i] << 8 ) | ( m_iy[i] ); - data[i * 2 + 1] = ( m_iz[i] << 24 ) | ( m_clr[i] ); - } - data[0] |= ( basex << 26 ) | ( basey << 21 )| ( basez << 16 ); +void Tesselator::packCompactQuad() { + // Offset x/y/z by 16 so that we can deal with a -16 -> 16 range + for (int i = 0; i < 4; i++) { + m_ix[i] += 16 * 128; + m_iy[i] += 16 * 128; + m_iz[i] += 16 * 128; + } + // Find min x/y/z + unsigned int minx = m_ix[0]; + unsigned int miny = m_iy[0]; + unsigned int minz = m_iz[0]; + for (int i = 1; i < 4; i++) { + if (m_ix[i] < minx) minx = m_ix[i]; + if (m_iy[i] < miny) miny = m_iy[i]; + if (m_iz[i] < minz) minz = m_iz[i]; + } + // Everything has been scaled by a factor of 128 to get it into an int, and + // so the minimum now should be in the range of (0->32) * 128. Get the base + // x/y/z that our quad will be referenced from now, which can be stored in 5 + // bits + unsigned int basex = (minx >> 7); + unsigned int basey = (miny >> 7); + unsigned int basez = (minz >> 7); + // If the min is 32, then this whole quad must be in that plane - make the + // min 15 instead so we can still offset from that with our delta to get to + // the exact edge + if (basex == 32) basex = 31; + if (basey == 32) basey = 31; + if (basez == 32) basez = 31; + // Now get deltas to each vertex - these have an 8-bit range so they can + // span a full unit range from the base position + for (int i = 0; i < 4; i++) { + m_ix[i] -= basex << 7; + m_iy[i] -= basey << 7; + m_iz[i] -= basez << 7; + } + // Now write the data out + unsigned int* data = (unsigned int*)&_array->data[p]; - // Now process UVs. First find min & max U & V - unsigned int minu = m_u[0]; - unsigned int minv = m_v[0]; - unsigned int maxu = m_u[0]; - unsigned int maxv = m_v[0]; + for (int i = 0; i < 4; i++) { + data[i * 2 + 0] = (m_ix[i] << 8) | (m_iy[i]); + data[i * 2 + 1] = (m_iz[i] << 24) | (m_clr[i]); + } + data[0] |= (basex << 26) | (basey << 21) | (basez << 16); - for( int i = 1; i < 4; i++ ) - { - if( m_u[i] < minu ) minu = m_u[i]; - if( m_v[i] < minv ) minv = m_v[i]; - if( m_u[i] > maxu ) maxu = m_u[i]; - if( m_v[i] > maxv ) maxv = m_v[i]; - } - // In nearly all cases, all our UVs should be axis aligned for this quad. So the only values they should - // have in each dimension should be the min/max. We're going to store: - // (1) minu/maxu (16 bits each, only actuall needs to store 14 bits to get a 0 to 2 range for each - // (2) du/dv ( ie maxu-minu, maxv-minv) - 8 bits each, to store a range of 0 to 15.9375 texels. This - // should be enough to map the full UV range of a single 16x16 region of the terrain texture, since - // we always pull UVs in by 1/16th of their range at the sides - unsigned int du = maxu - minu; - unsigned int dv = maxv - minv; - if( du > 255 ) du = 255; - if( dv > 255 ) dv = 255; - // Check if this quad has UVs that can be referenced this way. This should only happen for flowing water - // and lava, where the texture coordinates are rotated for the top surface of the tile. - bool axisAligned = true; - for( int i = 0; i < 4; i++ ) - { - if(! ( ( ( m_u[i] == minu ) || ( m_u[i] == maxu ) ) && - ( ( m_v[i] == minv ) || ( m_v[i] == maxv ) ) ) ) - { - axisAligned = false; - } - } + // Now process UVs. First find min & max U & V + unsigned int minu = m_u[0]; + unsigned int minv = m_v[0]; + unsigned int maxu = m_u[0]; + unsigned int maxv = m_v[0]; - if( axisAligned ) - { - // Now go through each vertex, and work out which of the min/max should be used for each dimension, - // and store - for( int i = 0; i < 4; i++ ) - { - unsigned int code = 0; - if( m_u[i] == maxu ) code |= 2; - if( m_v[i] == maxv ) code |= 1; - data[i * 2 + 1] |= code; - data[i * 2 + 1] |= m_t2[i] << 16; - } - // Finally, store the minu/minv/du/dv - data[1 * 2 + 0] |= minu << 16; - data[2 * 2 + 0] |= minv << 16; - data[3 * 2 + 0] |= ( du << 24 | dv << 16 ); + for (int i = 1; i < 4; i++) { + if (m_u[i] < minu) minu = m_u[i]; + if (m_v[i] < minv) minv = m_v[i]; + if (m_u[i] > maxu) maxu = m_u[i]; + if (m_v[i] > maxv) maxv = m_v[i]; + } + // In nearly all cases, all our UVs should be axis aligned for this quad. So + // the only values they should have in each dimension should be the min/max. + // We're going to store: (1) minu/maxu (16 bits each, only actuall needs to + // store 14 bits to get a 0 to 2 range for each (2) du/dv ( ie maxu-minu, + // maxv-minv) - 8 bits each, to store a range of 0 to 15.9375 texels. This + // should be enough to map the full UV range of a single 16x16 region of the + // terrain texture, since we always pull UVs in by 1/16th of their range at + // the sides + unsigned int du = maxu - minu; + unsigned int dv = maxv - minv; + if (du > 255) du = 255; + if (dv > 255) dv = 255; + // Check if this quad has UVs that can be referenced this way. This should + // only happen for flowing water and lava, where the texture coordinates are + // rotated for the top surface of the tile. + bool axisAligned = true; + for (int i = 0; i < 4; i++) { + if (!(((m_u[i] == minu) || (m_u[i] == maxu)) && + ((m_v[i] == minv) || (m_v[i] == maxv)))) { + axisAligned = false; + } + } - p += 4 * 2; - } - else - { - // The UVs aren't axis aligned - store them in the next 4 vertices. These will be indexed from - // our base vertices because we'll set a special code (4) for the UVs. They won't be drawn as actual - // verts when these extra vertices go through the vertex shader, because we'll make sure that - // they get interpreted as a zero area quad and so they'll be quickly eliminated from rendering post-tranform + if (axisAligned) { + // Now go through each vertex, and work out which of the min/max should + // be used for each dimension, and store + for (int i = 0; i < 4; i++) { + unsigned int code = 0; + if (m_u[i] == maxu) code |= 2; + if (m_v[i] == maxv) code |= 1; + data[i * 2 + 1] |= code; + data[i * 2 + 1] |= m_t2[i] << 16; + } + // Finally, store the minu/minv/du/dv + data[1 * 2 + 0] |= minu << 16; + data[2 * 2 + 0] |= minv << 16; + data[3 * 2 + 0] |= (du << 24 | dv << 16); - for( int i = 0; i < 4; i++ ) - { - data[i * 2 + 1] |= ( 4 ); // The special code to indicate they need further data to be fetched - data[i * 2 + 1] |= m_t2[i] << 16; - data[8 + i * 2] = 0; // This includes x/y coordinate of each vert as (0,0) so they will be interpreted as a zero area quad - data[9 + i * 2] = m_u[i] << 16 | m_v[i]; - } + p += 4 * 2; + } else { + // The UVs aren't axis aligned - store them in the next 4 vertices. + // These will be indexed from our base vertices because we'll set a + // special code (4) for the UVs. They won't be drawn as actual verts + // when these extra vertices go through the vertex shader, because we'll + // make sure that they get interpreted as a zero area quad and so + // they'll be quickly eliminated from rendering post-tranform - // Extra 8 bytes required - p += 8 * 2; - } + for (int i = 0; i < 4; i++) { + data[i * 2 + 1] |= (4); // The special code to indicate they need + // further data to be fetched + data[i * 2 + 1] |= m_t2[i] << 16; + data[8 + i * 2] = + 0; // This includes x/y coordinate of each vert as (0,0) so + // they will be interpreted as a zero area quad + data[9 + i * 2] = m_u[i] << 16 | m_v[i]; + } + + // Extra 8 bytes required + p += 8 * 2; + } } #ifdef __PSVITA__ -void Tesselator::tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, float g1, float b1, int tex1, - float x2, float y2, float z2, float u2, float v2, float r2, float g2, float b2, int tex2, - float x3, float y3, float z3, float u3, float v3, float r3, float g3, float b3, int tex3, - float x4, float y4, float z4, float u4, float v4, float r4, float g4, float b4, int tex4 - ) -{ +void Tesselator::tileQuad(float x1, float y1, float z1, float u1, float v1, + float r1, float g1, float b1, int tex1, float x2, + float y2, float z2, float u2, float v2, float r2, + float g2, float b2, int tex2, float x3, float y3, + float z3, float u3, float v3, float r3, float g3, + float b3, int tex3, float x4, float y4, float z4, + float u4, float v4, float r4, float g4, float b4, + int tex4) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - count+=4; + count += 4; - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - std::int16_t* pShortData; - if( !alphaCutOutEnabled ) - { - pShortData = (std::int16_t*)&_array->data[p]; - p += 16; - vertices+=4; - } - else - { - pShortData = (std::int16_t*)&_array2->data[p2]; - p2 += 16; - vertices2+=4; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + std::int16_t* pShortData; + if (!alphaCutOutEnabled) { + pShortData = (std::int16_t*)&_array->data[p]; + p += 16; + vertices += 4; + } else { + pShortData = (std::int16_t*)&_array2->data[p2]; + p2 += 16; + vertices2 += 4; + } - int r = ((int) (r1 * 31)) << 11; - int g = ((int) (g1 * 63)) << 5; - int b = ((int) (b1 * 31)); - int ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + int r = ((int)(r1 * 31)) << 11; + int g = ((int)(g1 * 63)) << 5; + int b = ((int)(b1 * 31)); + int ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x1+xo, y1+yo, z1+zo); // 4J MGH - added - pShortData[0] = (((int)((x1 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y1 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z1 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u1 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v1 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex1; - pShortData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); // 4J MGH - added + pShortData[0] = (((int)((x1 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y1 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z1 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u1 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v1 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex1; + pShortData += 8; - r = ((int) (r2 * 31)) << 11; - g = ((int) (g2 * 63)) << 5; - b = ((int) (b2 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r2 * 31)) << 11; + g = ((int)(g2 * 63)) << 5; + b = ((int)(b2 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x2+xo, y2+yo, z2+zo); // 4J MGH - added - pShortData[0] = (((int)((x2 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y2 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z2 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u2 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v2 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex2; - pShortData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); // 4J MGH - added + pShortData[0] = (((int)((x2 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y2 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z2 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u2 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v2 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex2; + pShortData += 8; - r = ((int) (r3 * 31)) << 11; - g = ((int) (g3 * 63)) << 5; - b = ((int) (b3 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r3 * 31)) << 11; + g = ((int)(g3 * 63)) << 5; + b = ((int)(b3 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x3+xo, y3+yo, z3+zo); // 4J MGH - added - pShortData[0] = (((int)((x3 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y3 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z3 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u3 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v3 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex3; - pShortData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); // 4J MGH - added + pShortData[0] = (((int)((x3 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y3 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z3 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u3 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v3 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex3; + pShortData += 8; - r = ((int) (r4 * 31)) << 11; - g = ((int) (g4 * 63)) << 5; - b = ((int) (b4 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r4 * 31)) << 11; + g = ((int)(g4 * 63)) << 5; + b = ((int)(b4 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x4+xo, y4+yo, z4+zo); // 4J MGH - added - pShortData[0] = (((int)((x4 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y4 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z4 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u4 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v4 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex4; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); // 4J MGH - added + pShortData[0] = (((int)((x4 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y4 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z4 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u4 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v4 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex4; - // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it - if ( (!alphaCutOutEnabled && vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) )) || - (alphaCutOutEnabled && vertices2 % 4 == 0 && ( ( p2 >= size - 4 * 4 ) || ( ( p2 / 4 ) >= 65532 ) )) ) - { - end(); - tesselating = true; - } + // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad + // to catch it + if ((!alphaCutOutEnabled && vertices % 4 == 0 && + ((p >= size - 4 * 4) || ((p / 4) >= 65532))) || + (alphaCutOutEnabled && vertices2 % 4 == 0 && + ((p2 >= size - 4 * 4) || ((p2 / 4) >= 65532)))) { + end(); + tesselating = true; + } } -void Tesselator::tileRainQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1, - float r2, float g2, float b2, float a2, - int tex1 - ) -{ +void Tesselator::tileRainQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1, float r2, + float g2, float b2, float a2, int tex1) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - float* pfData = (float*)&_array->data[p]; + float* pfData = (float*)&_array->data[p]; - count+=4; - p += 4 * 8; - vertices+=4; + count += 4; + p += 4 * 8; + vertices += 4; - unsigned int col1 = ((int)(r1*255) << 24) | ((int)(g1*255) << 16) | ((int)(b1*255) << 8) | (int)(a1*255); + unsigned int col1 = ((int)(r1 * 255) << 24) | ((int)(g1 * 255) << 16) | + ((int)(b1 * 255) << 8) | (int)(a1 * 255); - bounds.addVert(x1+xo, y1+yo, z1+zo); - pfData[0] = (x1 + xo); - pfData[1] = (y1 + yo); - pfData[2] = (z1 + zo); - pfData[3] = u1; - pfData[4] = v1; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); + pfData[0] = (x1 + xo); + pfData[1] = (y1 + yo); + pfData[2] = (z1 + zo); + pfData[3] = u1; + pfData[4] = v1; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - bounds.addVert(x2+xo, y2+yo, z2+zo); - pfData[0] = (x2 + xo); - pfData[1] = (y2 + yo); - pfData[2] = (z2 + zo); - pfData[3] = u2; - pfData[4] = v2; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); + pfData[0] = (x2 + xo); + pfData[1] = (y2 + yo); + pfData[2] = (z2 + zo); + pfData[3] = u2; + pfData[4] = v2; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - col1 = ((int)(r2*255) << 24) | ((int)(g2*255) << 16) | ((int)(b2*255) << 8) | (int)(a2*255); + col1 = ((int)(r2 * 255) << 24) | ((int)(g2 * 255) << 16) | + ((int)(b2 * 255) << 8) | (int)(a2 * 255); - bounds.addVert(x3+xo, y3+yo, z3+zo); - pfData[0] = (x3 + xo); - pfData[1] = (y3 + yo); - pfData[2] = (z3 + zo); - pfData[3] = u3; - pfData[4] = v3; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); + pfData[0] = (x3 + xo); + pfData[1] = (y3 + yo); + pfData[2] = (z3 + zo); + pfData[3] = u3; + pfData[4] = v3; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - bounds.addVert(x4+xo, y4+yo, z4+zo); - pfData[0] = (x4 + xo); - pfData[1] = (y4 + yo); - pfData[2] = (z4 + zo); - pfData[3] = u4; - pfData[4] = v4; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); + pfData[0] = (x4 + xo); + pfData[1] = (y4 + yo); + pfData[2] = (z4 + zo); + pfData[3] = u4; + pfData[4] = v4; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } } -void Tesselator::tileParticleQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1) -{ +void Tesselator::tileParticleQuad(float x1, float y1, float z1, float u1, + float v1, float x2, float y2, float z2, + float u2, float v2, float x3, float y3, + float z3, float u3, float v3, float x4, + float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - float* pfData = (float*)&_array->data[p]; + float* pfData = (float*)&_array->data[p]; - count+=4; - p += 4 * 8; - vertices+=4; + count += 4; + p += 4 * 8; + vertices += 4; - unsigned int col1 = ((int)(r1*255) << 24) | ((int)(g1*255) << 16) | ((int)(b1*255) << 8) | (int)(a1*255); + unsigned int col1 = ((int)(r1 * 255) << 24) | ((int)(g1 * 255) << 16) | + ((int)(b1 * 255) << 8) | (int)(a1 * 255); - bounds.addVert(x1+xo, y1+yo, z1+zo); - pfData[0] = (x1 + xo); - pfData[1] = (y1 + yo); - pfData[2] = (z1 + zo); - pfData[3] = u1; - pfData[4] = v1; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); + pfData[0] = (x1 + xo); + pfData[1] = (y1 + yo); + pfData[2] = (z1 + zo); + pfData[3] = u1; + pfData[4] = v1; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x2+xo, y2+yo, z2+zo); - pfData[0] = (x2 + xo); - pfData[1] = (y2 + yo); - pfData[2] = (z2 + zo); - pfData[3] = u2; - pfData[4] = v2; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); + pfData[0] = (x2 + xo); + pfData[1] = (y2 + yo); + pfData[2] = (z2 + zo); + pfData[3] = u2; + pfData[4] = v2; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x3+xo, y3+yo, z3+zo); - pfData[0] = (x3 + xo); - pfData[1] = (y3 + yo); - pfData[2] = (z3 + zo); - pfData[3] = u3; - pfData[4] = v3; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); + pfData[0] = (x3 + xo); + pfData[1] = (y3 + yo); + pfData[2] = (z3 + zo); + pfData[3] = u3; + pfData[4] = v3; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x4+xo, y4+yo, z4+zo); - pfData[0] = (x4 + xo); - pfData[1] = (y4 + yo); - pfData[2] = (z4 + zo); - pfData[3] = u4; - pfData[4] = v4; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); + pfData[0] = (x4 + xo); + pfData[1] = (y4 + yo); + pfData[2] = (z4 + zo); + pfData[3] = u4; + pfData[4] = v4; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } } #endif -typedef unsigned short hfloat; +typedef unsigned short hfloat; extern hfloat convertFloatToHFloat(float f); extern float convertHFloatToFloat(hfloat hf); -void Tesselator::vertex(float x, float y, float z) -{ - bounds.addVert(x+xo, y+yo, z+zo); // 4J MGH - added +void Tesselator::vertex(float x, float y, float z) { + bounds.addVert(x + xo, y + yo, z + zo); // 4J MGH - added count++; - // Signal to pixel shader whether to use mipmapping or not, by putting u into > 1 range if it is to be disabled - float uu = mipmapEnable ? u : (u + 1.0f); + // Signal to pixel shader whether to use mipmapping or not, by putting u + // into > 1 range if it is to be disabled + float uu = mipmapEnable ? u : (u + 1.0f); - // 4J - this format added for 360 to keep memory size of tesselated tiles down - - // see comments in packCompactQuad() for exact format - if( useCompactFormat360 ) - { - unsigned int ucol = (unsigned int)col; + // 4J - this format added for 360 to keep memory size of tesselated tiles + // down - see comments in packCompactQuad() for exact format + if (useCompactFormat360) { + unsigned int ucol = (unsigned int)col; #ifdef _XBOX - // Pack as 4:4:4 RGB_ - unsigned short packedcol = (((col & 0xf0000000 ) >> 16 ) | - ((col & 0x00f00000 ) >> 12 ) | - ((col & 0x0000f000 ) >> 8 )); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + // Pack as 4:4:4 RGB_ + unsigned short packedcol = + (((col & 0xf0000000) >> 16) | ((col & 0x00f00000) >> 12) | + ((col & 0x0000f000) >> 8)); + int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range - int quadIdx = vertices % 4; - m_ix[ quadIdx ] = (unsigned int)((x + xo) * 128.0f); - m_iy[ quadIdx ] = (unsigned int)((y + yo) * 128.0f); - m_iz[ quadIdx ] = (unsigned int)((z + zo) * 128.0f); - m_clr[ quadIdx ] = (unsigned int)ipackedcol; - m_u[ quadIdx ] = (int)(uu * 4096.0f); - m_v[ quadIdx ] = (int)(v * 4096.0f); - m_t2[ quadIdx ] = ( ( _tex2 & 0x00f00000 ) >> 20 ) | ( _tex2 & 0x000000f0 ); - if( quadIdx == 3 ) - { - packCompactQuad(); - } + int quadIdx = vertices % 4; + m_ix[quadIdx] = (unsigned int)((x + xo) * 128.0f); + m_iy[quadIdx] = (unsigned int)((y + yo) * 128.0f); + m_iz[quadIdx] = (unsigned int)((z + zo) * 128.0f); + m_clr[quadIdx] = (unsigned int)ipackedcol; + m_u[quadIdx] = (int)(uu * 4096.0f); + m_v[quadIdx] = (int)(v * 4096.0f); + m_t2[quadIdx] = ((_tex2 & 0x00f00000) >> 20) | (_tex2 & 0x000000f0); + if (quadIdx == 3) { + packCompactQuad(); + } #else - unsigned short packedcol = ((col & 0xf8000000 ) >> 16 ) | - ((col & 0x00fc0000 ) >> 13 ) | - ((col & 0x0000f800 ) >> 11 ); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + unsigned short packedcol = ((col & 0xf8000000) >> 16) | + ((col & 0x00fc0000) >> 13) | + ((col & 0x0000f800) >> 11); + int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - std::int16_t* pShortData; - if( !alphaCutOutEnabled ) - { - pShortData = (std::int16_t*)&_array->data[p]; - } - else - { - pShortData = (std::int16_t*)&_array2->data[p2]; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + std::int16_t* pShortData; + if (!alphaCutOutEnabled) { + pShortData = (std::int16_t*)&_array->data[p]; + } else { + pShortData = (std::int16_t*)&_array2->data[p2]; + } #else - std::int16_t* pShortData = (std::int16_t*)&_array->data[p]; + std::int16_t* pShortData = (std::int16_t*)&_array->data[p]; #endif - - #ifdef __PS3__ - float tex2U = ((std::int16_t*)&_tex2)[1] + 8; - float tex2V = ((std::int16_t*)&_tex2)[0] + 8; - float colVal1 = ((col&0xff000000)>>24)/256.0f; - float colVal2 = ((col&0x00ff0000)>>16)/256.0f; - float colVal3 = ((col&0x0000ff00)>>8)/256.0f; + float tex2U = ((std::int16_t*)&_tex2)[1] + 8; + float tex2V = ((std::int16_t*)&_tex2)[0] + 8; + float colVal1 = ((col & 0xff000000) >> 24) / 256.0f; + float colVal2 = ((col & 0x00ff0000) >> 16) / 256.0f; + float colVal3 = ((col & 0x0000ff00) >> 8) / 256.0f; -// pShortData[0] = convertFloatToHFloat(x + xo); -// pShortData[1] = convertFloatToHFloat(y + yo); -// pShortData[2] = convertFloatToHFloat(z + zo); -// pShortData[3] = convertFloatToHFloat(uu); -// pShortData[4] = convertFloatToHFloat(tex2U + colVal1); -// pShortData[5] = convertFloatToHFloat(tex2V + colVal2); -// pShortData[6] = convertFloatToHFloat(colVal3); -// pShortData[7] = convertFloatToHFloat(v); + // pShortData[0] = convertFloatToHFloat(x + xo); + // pShortData[1] = convertFloatToHFloat(y + yo); + // pShortData[2] = convertFloatToHFloat(z + zo); + // pShortData[3] = convertFloatToHFloat(uu); + // pShortData[4] = convertFloatToHFloat(tex2U + colVal1); + // pShortData[5] = convertFloatToHFloat(tex2V + colVal2); + // pShortData[6] = convertFloatToHFloat(colVal3); + // pShortData[7] = convertFloatToHFloat(v); - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); - pShortData[6] = (((int)(tex2U * (8192.0f/256.0f)))&0xffff); - pShortData[7] = (((int)(tex2V * (8192.0f/256.0f)))&0xffff); + pShortData[0] = (((int)((x + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(uu * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v * 8192.0f)) & 0xffff); + pShortData[6] = (((int)(tex2U * (8192.0f / 256.0f))) & 0xffff); + pShortData[7] = (((int)(tex2V * (8192.0f / 256.0f))) & 0xffff); - p += 4; + p += 4; #else - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); - std::int16_t u2 = ((std::int16_t*)&_tex2)[0]; - std::int16_t v2 = ((std::int16_t*)&_tex2)[1]; + pShortData[0] = (((int)((x + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(uu * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v * 8192.0f)) & 0xffff); + std::int16_t u2 = ((std::int16_t*)&_tex2)[0]; + std::int16_t v2 = ((std::int16_t*)&_tex2)[1]; #if defined _XBOX_ONE || defined __ORBIS__ - // Optimisation - pack the second UVs into a single short (they could actually go in a byte), which frees up a short to store the x offset for this chunk in the vertex itself. - // This means that when rendering chunks, we don't need to update the vertex constants that specify the location for a chunk, when only the x offset has changed. - pShortData[6] = ( u2 << 8 ) | v2; - pShortData[7] = -xoo; + // Optimisation - pack the second UVs into a single short (they could + // actually go in a byte), which frees up a short to store the x offset + // for this chunk in the vertex itself. This means that when rendering + // chunks, we don't need to update the vertex constants that specify the + // location for a chunk, when only the x offset has changed. + pShortData[6] = (u2 << 8) | v2; + pShortData[7] = -xoo; #else - pShortData[6] = u2; - pShortData[7] = v2; + pShortData[6] = u2; + pShortData[7] = v2; #endif #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - if( !alphaCutOutEnabled ) - { - p += 4; - } - else - { - p2 += 4; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + if (!alphaCutOutEnabled) { + p += 4; + } else { + p2 += 4; + } #else - p += 4; + p += 4; #endif #endif @@ -864,152 +860,143 @@ void Tesselator::vertex(float x, float y, float z) #endif #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Increase the correct vertices depending on cut out enabled - if( !alphaCutOutEnabled ) - { - vertices++; - } - else - { - vertices2++; - } + // AP - alpha cut out is expensive on vita. Increase the correct + // vertices depending on cut out enabled + if (!alphaCutOutEnabled) { + vertices++; + } else { + vertices2++; + } #else - vertices++; + vertices++; #endif #ifdef _XBOX - if (vertices % 4 == 0 && ( ( p >= size - 8 * 2 ) || ( ( p / 2 ) >= 65532 ) ) ) // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it + if (vertices % 4 == 0 && + ((p >= size - 8 * 2) || + ((p / 2) >= + 65532))) // Max 65535 verts in D3D, so 65532 is the last point at + // the end of a quad to catch it #else #ifdef __PSVITA__ - // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it - if ( (!alphaCutOutEnabled && vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) )) || - (alphaCutOutEnabled && vertices2 % 4 == 0 && ( ( p2 >= size - 4 * 4 ) || ( ( p2 / 4 ) >= 65532 ) )) ) + // Max 65535 verts in D3D, so 65532 is the last point at the end of a + // quad to catch it + if ((!alphaCutOutEnabled && vertices % 4 == 0 && + ((p >= size - 4 * 4) || ((p / 4) >= 65532))) || + (alphaCutOutEnabled && vertices2 % 4 == 0 && + ((p2 >= size - 4 * 4) || ((p2 / 4) >= 65532)))) #else - if (vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) ) ) // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it + if (vertices % 4 == 0 && + ((p >= size - 4 * 4) || + ((p / 4) >= + 65532))) // Max 65535 verts in D3D, so 65532 is the last point at + // the end of a quad to catch it #endif #endif - { - end(); - tesselating = true; - } - } - else - { - if (mode == GL_QUADS && TRIANGLE_MODE && count % 4 == 0) - { - for (int i = 0; i < 2; i++) - { - int offs = 8 * (3 - i); - if (hasTexture) - { - _array->data[p + 3] = _array->data[p - offs + 3]; - _array->data[p + 4] = _array->data[p - offs + 4]; - } - if (hasColor) - { - _array->data[p + 5] = _array->data[p - offs + 5]; - } + { + end(); + tesselating = true; + } + } else { + if (mode == GL_QUADS && TRIANGLE_MODE && count % 4 == 0) { + for (int i = 0; i < 2; i++) { + int offs = 8 * (3 - i); + if (hasTexture) { + _array->data[p + 3] = _array->data[p - offs + 3]; + _array->data[p + 4] = _array->data[p - offs + 4]; + } + if (hasColor) { + _array->data[p + 5] = _array->data[p - offs + 5]; + } - _array->data[p + 0] = _array->data[p - offs + 0]; - _array->data[p + 1] = _array->data[p - offs + 1]; - _array->data[p + 2] = _array->data[p - offs + 2]; + _array->data[p + 0] = _array->data[p - offs + 0]; + _array->data[p + 1] = _array->data[p - offs + 1]; + _array->data[p + 2] = _array->data[p - offs + 2]; - vertices++; - p += 8; - } - } + vertices++; + p += 8; + } + } - if (hasTexture) - { - float *fdata = (float *)(_array->data + p + 3); - *fdata++ = uu; - *fdata++ = v; - } - if (hasColor) - { - _array->data[p + 5] = col; - } - if (hasNormal) - { - _array->data[p + 6] = _normal; - } - if (hasTexture2) - { + if (hasTexture) { + float* fdata = (float*)(_array->data + p + 3); + *fdata++ = uu; + *fdata++ = v; + } + if (hasColor) { + _array->data[p + 5] = col; + } + if (hasNormal) { + _array->data[p + 6] = _normal; + } + if (hasTexture2) { #ifdef _XBOX - _array->data[p + 7] = ( ( _tex2 >> 16 ) & 0xffff ) | ( _tex2 << 16 ); + _array->data[p + 7] = ((_tex2 >> 16) & 0xffff) | (_tex2 << 16); #else - // 4jcraft: we will be lighting the blocks right in here - #if defined(__PS3__) || defined (__linux__) - #ifdef __PS3__ - std::int16_t tex2U = ((std::int16_t*)&_tex2)[1] + 8; - std::int16_t tex2V = ((std::int16_t*)&_tex2)[0] + 8; - #else - std::int16_t tex2U = ((std::int16_t*)&_tex2)[0] + 8; - std::int16_t tex2V = ((std::int16_t*)&_tex2)[1] + 8; - #endif - std::int16_t* pShortArray = (std::int16_t*)&_array->data[p + 7]; - pShortArray[0] = tex2U; - pShortArray[1] = tex2V; - #else - _array->data[p + 7] = _tex2; - #endif +// 4jcraft: we will be lighting the blocks right in here +#if defined(__PS3__) || defined(__linux__) +#ifdef __PS3__ + std::int16_t tex2U = ((std::int16_t*)&_tex2)[1] + 8; + std::int16_t tex2V = ((std::int16_t*)&_tex2)[0] + 8; +#else + std::int16_t tex2U = ((std::int16_t*)&_tex2)[0] + 8; + std::int16_t tex2V = ((std::int16_t*)&_tex2)[1] + 8; #endif - } - else - { - // -512 each for u/v will mean that the renderer will use global settings (set via - // RenderManager.StateSetVertexTextureUV) rather than these local ones - *(unsigned int *)(&_array->data[p + 7]) = 0xfe00fe00; - } + std::int16_t* pShortArray = (std::int16_t*)&_array->data[p + 7]; + pShortArray[0] = tex2U; + pShortArray[1] = tex2V; +#else + _array->data[p + 7] = _tex2; +#endif +#endif + } else { + // -512 each for u/v will mean that the renderer will use global + // settings (set via RenderManager.StateSetVertexTextureUV) rather + // than these local ones + *(unsigned int*)(&_array->data[p + 7]) = 0xfe00fe00; + } - float *fdata = (float *)(_array->data + p); - *fdata++ = (x + xo); - *fdata++ = (y + yo); - *fdata++ = (z + zo); - p += 8; + float* fdata = (float*)(_array->data + p); + *fdata++ = (x + xo); + *fdata++ = (y + yo); + *fdata++ = (z + zo); + p += 8; - vertices++; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } - } + vertices++; + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } + } } -void Tesselator::color(int c) -{ +void Tesselator::color(int c) { int r = ((c >> 16) & 255); int g = ((c >> 8) & 255); int b = ((c) & 255); color(r, g, b); } -void Tesselator::color(int c, int alpha) -{ +void Tesselator::color(int c, int alpha) { int r = ((c >> 16) & 255); int g = ((c >> 8) & 255); int b = ((c) & 255); color(r, g, b, alpha); } -void Tesselator::noColor() -{ - _noColor = true; -} +void Tesselator::noColor() { _noColor = true; } #ifdef __PS3__ -std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) -{ - // 11111111111 X 0x000007FF - // 1111111111100000000000 Y 0x003FF800 - // 11111111110000000000000000000000 Z 0xFFC00000 - // ZZZZZZZZZZYYYYYYYYYYYXXXXXXXXXXX - // #defines for X11Y11Z10N format +std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) { + // 11111111111 X 0x000007FF + // 1111111111100000000000 Y 0x003FF800 + // 11111111110000000000000000000000 Z 0xFFC00000 + // ZZZZZZZZZZYYYYYYYYYYYXXXXXXXXXXX + // #defines for X11Y11Z10N format #define X11Y11Z10N_X_MASK 0x000007FF #define X11Y11Z10N_X_BITS 11 #define X11Y11Z10N_X_SHIFT 0 @@ -1023,68 +1010,93 @@ std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) #define X11Y11Z10N_Z_SHIFT 22 #ifndef _CONTENT_PACKAGE - if (x<-1.0f || x>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", x); } - if (y<-1.0f || y>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", y); } - if (z<-1.0f || z>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", z); } + if (x < -1.0f || x > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + x); + } + if (y < -1.0f || y > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + y); + } + if (z < -1.0f || z > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + z); + } #endif - const std::uint32_t uX = ((std::int32_t(std::max(std::min(((x)*2047.f - 1.f)*0.5f, 1023.f), -1024.f)) & (X11Y11Z10N_X_MASK >> X11Y11Z10N_X_SHIFT)) << X11Y11Z10N_X_SHIFT); - const std::uint32_t uY = ((std::int32_t(std::max(std::min(((y)*2047.f - 1.f)*0.5f, 1023.f), -1024.f)) & (X11Y11Z10N_Y_MASK >> X11Y11Z10N_Y_SHIFT)) << X11Y11Z10N_Y_SHIFT); - const std::uint32_t uZ = ((std::int32_t(std::max(std::min(((z)*1023.f - 1.f)*0.5f, 511.f), -512.f )) & (X11Y11Z10N_Z_MASK >> X11Y11Z10N_Z_SHIFT)) << X11Y11Z10N_Z_SHIFT); - const std::uint32_t xyz = uX | uY | uZ; - return xyz; + const std::uint32_t uX = + ((std::int32_t(std::max(std::min(((x) * 2047.f - 1.f) * 0.5f, 1023.f), + -1024.f)) & + (X11Y11Z10N_X_MASK >> X11Y11Z10N_X_SHIFT)) + << X11Y11Z10N_X_SHIFT); + const std::uint32_t uY = + ((std::int32_t(std::max(std::min(((y) * 2047.f - 1.f) * 0.5f, 1023.f), + -1024.f)) & + (X11Y11Z10N_Y_MASK >> X11Y11Z10N_Y_SHIFT)) + << X11Y11Z10N_Y_SHIFT); + const std::uint32_t uZ = + ((std::int32_t( + std::max(std::min(((z) * 1023.f - 1.f) * 0.5f, 511.f), -512.f)) & + (X11Y11Z10N_Z_MASK >> X11Y11Z10N_Z_SHIFT)) + << X11Y11Z10N_Z_SHIFT); + const std::uint32_t xyz = uX | uY | uZ; + return xyz; } -#endif // __PS3__ +#endif // __PS3__ -void Tesselator::normal(float x, float y, float z) -{ +void Tesselator::normal(float x, float y, float z) { hasNormal = true; #ifdef __PS3__ - _normal = _ConvertF32toX11Y11Z10N(x,y,z); + _normal = _ConvertF32toX11Y11Z10N(x, y, z); #elif __PSVITA__ - // AP - casting a negative value to 'byte' on Vita results in zero. changed to a signed 8 value - std::int8_t xx = (std::int8_t) (x * 127); - std::int8_t yy = (std::int8_t) (y * 127); - std::int8_t zz = (std::int8_t) (z * 127); - _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); + // AP - casting a negative value to 'byte' on Vita results in zero. changed + // to a signed 8 value + std::int8_t xx = (std::int8_t)(x * 127); + std::int8_t yy = (std::int8_t)(y * 127); + std::int8_t zz = (std::int8_t)(z * 127); + _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #else - // 4jcraft copied the PSVITA branch, read comment above - std::int8_t xx = (std::int8_t) (x * 127); - std::int8_t yy = (std::int8_t) (y * 127); - std::int8_t zz = (std::int8_t) (z * 127); - _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); + // 4jcraft copied the PSVITA branch, read comment above + std::int8_t xx = (std::int8_t)(x * 127); + std::int8_t yy = (std::int8_t)(y * 127); + std::int8_t zz = (std::int8_t)(z * 127); + _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #endif } -void Tesselator::offset(float xo, float yo, float zo) -{ +void Tesselator::offset(float xo, float yo, float zo) { this->xo = xo; this->yo = yo; this->zo = zo; - // 4J added + // 4J added this->xoo = xo; this->yoo = yo; this->zoo = zo; } -void Tesselator::addOffset(float x, float y, float z) -{ +void Tesselator::addOffset(float x, float y, float z) { xo += x; yo += y; zo += z; } -bool Tesselator::hasMaxVertices() -{ +bool Tesselator::hasMaxVertices() { #ifdef __ORBIS__ - // On PS4, the way we push data to the command buffer has a maximum size of a single command packet of 2^16 bytes, - // and the effective maximum size will be slightly less than that due to packet headers and padding. - int bytes = vertices * (useCompactFormat360?16:32); + // On PS4, the way we push data to the command buffer has a maximum size of + // a single command packet of 2^16 bytes, and the effective maximum size + // will be slightly less than that due to packet headers and padding. + int bytes = vertices * (useCompactFormat360 ? 16 : 32); - return bytes > 60 * 1024; + return bytes > 60 * 1024; #else - return false; + return false; #endif } diff --git a/Minecraft.Client/Rendering/Tesselator.h b/Minecraft.Client/Rendering/Tesselator.h index eefeaa73a..02d43a12c 100644 --- a/Minecraft.Client/Rendering/Tesselator.h +++ b/Minecraft.Client/Rendering/Tesselator.h @@ -4,136 +4,133 @@ class ChunkRebuildData; class Tesselator { // private static boolean TRIANGLE_MODE = false; - friend ChunkRebuildData; + friend ChunkRebuildData; + private: - static bool TRIANGLE_MODE; + static bool TRIANGLE_MODE; static bool USE_VBO; static const int MAX_MEMORY_USE = 16 * 1024 * 1024; static const int MAX_FLOATS = MAX_MEMORY_USE / 4 / 2; - intArray *_array; + intArray* _array; int vertices; float u, v; - int _tex2; + int _tex2; int col; bool hasColor; bool hasTexture; - bool hasTexture2; + bool hasTexture2; bool hasNormal; - int p ; - bool useCompactFormat360; // 4J - added - bool useProjectedTexturePixelShader; // 4J - added + int p; + bool useCompactFormat360; // 4J - added + bool useProjectedTexturePixelShader; // 4J - added public: int count; + private: bool _noColor; int mode; float xo, yo, zo; - float xoo, yoo, zoo; + float xoo, yoo, zoo; int _normal; - // 4J - added for thread local storage + // 4J - added for thread local storage public: - static void CreateNewThreadStorage(int bytes); -private: - static unsigned int tlsIdx; -public: - static Tesselator *getInstance(); + static void CreateNewThreadStorage(int bytes); private: - bool tesselating; - bool mipmapEnable; // 4J added + static unsigned int tlsIdx; + +public: + static Tesselator* getInstance(); + +private: + bool tesselating; + bool mipmapEnable; // 4J added bool vboMode; - IntBuffer *vboIds; + IntBuffer* vboIds; int vboId; int vboCounts; int size; Tesselator(int size); -public: - Tesselator *getUniqueInstance(int size); - void end(); -private: - void clear(); - // 4J - added to handle compact quad vertex format, which need packaged up as quads - unsigned int m_ix[4],m_iy[4],m_iz[4]; - unsigned int m_clr[4]; - unsigned int m_u[4], m_v[4]; - unsigned int m_t2[4]; - void packCompactQuad(); +public: + Tesselator* getUniqueInstance(int size); + void end(); + +private: + void clear(); + + // 4J - added to handle compact quad vertex format, which need packaged up + // as quads + unsigned int m_ix[4], m_iy[4], m_iz[4]; + unsigned int m_clr[4]; + unsigned int m_u[4], m_v[4]; + unsigned int m_t2[4]; + void packCompactQuad(); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - bool alphaCutOutEnabled; + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + bool alphaCutOutEnabled; - // this is the cut out enabled vertex array - intArray *_array2; + // this is the cut out enabled vertex array + intArray* _array2; int vertices2; int p2; #endif public: + // 4J MGH - added, to calculate tight bounds + class Bounds { + public: + void reset() { + boundingBox[0] = FLT_MAX; + boundingBox[1] = FLT_MAX; + boundingBox[2] = FLT_MAX; + boundingBox[3] = -FLT_MAX; + boundingBox[4] = -FLT_MAX; + boundingBox[5] = -FLT_MAX; + } + void addVert(float x, float y, float z) { + if (x < boundingBox[0]) boundingBox[0] = x; + if (y < boundingBox[1]) boundingBox[1] = y; + if (z < boundingBox[2]) boundingBox[2] = z; - // 4J MGH - added, to calculate tight bounds - class Bounds - { - public: - void reset() - { - boundingBox[0] = FLT_MAX; - boundingBox[1] = FLT_MAX; - boundingBox[2] = FLT_MAX; - boundingBox[3] = -FLT_MAX; - boundingBox[4] = -FLT_MAX; - boundingBox[5] = -FLT_MAX; - } - void addVert(float x, float y, float z) - { - if(x < boundingBox[0]) - boundingBox[0] = x; - if(y < boundingBox[1]) - boundingBox[1] = y; - if(z < boundingBox[2]) - boundingBox[2] = z; + if (x > boundingBox[3]) boundingBox[3] = x; + if (y > boundingBox[4]) boundingBox[4] = y; + if (z > boundingBox[5]) boundingBox[5] = z; + } + void addBounds(Bounds& ob) { + if (ob.boundingBox[0] < boundingBox[0]) + boundingBox[0] = ob.boundingBox[0]; + if (ob.boundingBox[1] < boundingBox[1]) + boundingBox[1] = ob.boundingBox[1]; + if (ob.boundingBox[2] < boundingBox[2]) + boundingBox[2] = ob.boundingBox[2]; - if(x > boundingBox[3]) - boundingBox[3] = x; - if(y > boundingBox[4]) - boundingBox[4] = y; - if(z > boundingBox[5]) - boundingBox[5] = z; - } - void addBounds(Bounds& ob) - { - if(ob.boundingBox[0] < boundingBox[0]) - boundingBox[0] = ob.boundingBox[0]; - if(ob.boundingBox[1] < boundingBox[1]) - boundingBox[1] = ob.boundingBox[1]; - if(ob.boundingBox[2] < boundingBox[2]) - boundingBox[2] = ob.boundingBox[2]; + if (ob.boundingBox[3] > boundingBox[3]) + boundingBox[3] = ob.boundingBox[3]; + if (ob.boundingBox[4] > boundingBox[4]) + boundingBox[4] = ob.boundingBox[4]; + if (ob.boundingBox[5] > boundingBox[5]) + boundingBox[5] = ob.boundingBox[5]; + } + float boundingBox[6]; // 4J MGH added - if(ob.boundingBox[3] > boundingBox[3]) - boundingBox[3] = ob.boundingBox[3]; - if(ob.boundingBox[4] > boundingBox[4]) - boundingBox[4] = ob.boundingBox[4]; - if(ob.boundingBox[5] > boundingBox[5]) - boundingBox[5] = ob.boundingBox[5]; - } - float boundingBox[6]; // 4J MGH added + } bounds; - } bounds; - - void begin(); + void begin(); void begin(int mode); - void useCompactVertices(bool enable); // 4J added - bool getCompactVertices(); // AP added - void useProjectedTexture(bool enable); // 4J added + void useCompactVertices(bool enable); // 4J added + bool getCompactVertices(); // AP added + void useProjectedTexture(bool enable); // 4J added void tex(float u, float v); - void tex2(int tex2); // 4J - change brought forward from 1.8.2 + void tex2(int tex2); // 4J - change brought forward from 1.8.2 void color(float r, float g, float b); void color(float r, float g, float b, float a); void color(int r, int g, int b); @@ -147,32 +144,34 @@ public: void normal(float x, float y, float z); void offset(float xo, float yo, float zo); void addOffset(float x, float y, float z); - bool setMipmapEnable(bool enable); // 4J added + bool setMipmapEnable(bool enable); // 4J added - bool hasMaxVertices(); // 4J Added + bool hasMaxVertices(); // 4J Added #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - void setAlphaCutOut(bool enable); - bool getCutOutFound(); + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + void setAlphaCutOut(bool enable); + bool getCutOutFound(); - // AP - a faster way of creating a compressed tile quad - void tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, float g1, float b1, int tex1, - float x2, float y2, float z2, float u2, float v2, float r2, float g2, float b2, int tex2, - float x3, float y3, float z3, float u3, float v3, float r3, float g3, float b3, int tex3, - float x4, float y4, float z4, float u4, float v4, float r4, float g4, float b4, int tex4); - // AP - a faster way of creating rain quads - void tileRainQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1, - float r2, float g2, float b2, float a2, int tex1); - // AP - a faster way of creating particles - void tileParticleQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1); + // AP - a faster way of creating a compressed tile quad + void tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, + float g1, float b1, int tex1, float x2, float y2, float z2, + float u2, float v2, float r2, float g2, float b2, int tex2, + float x3, float y3, float z3, float u3, float v3, float r3, + float g3, float b3, int tex3, float x4, float y4, float z4, + float u4, float v4, float r4, float g4, float b4, int tex4); + // AP - a faster way of creating rain quads + void tileRainQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1, float r2, + float g2, float b2, float a2, int tex1); + // AP - a faster way of creating particles + void tileParticleQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1); #endif - }; diff --git a/Minecraft.Client/Rendering/TexOffs.cpp b/Minecraft.Client/Rendering/TexOffs.cpp index 372023966..4cb40a021 100644 --- a/Minecraft.Client/Rendering/TexOffs.cpp +++ b/Minecraft.Client/Rendering/TexOffs.cpp @@ -1,9 +1,4 @@ #include "../Platform/stdafx.h" #include "TexOffs.h" -TexOffs::TexOffs(int x, int y) : -x(x), -y(y) -{ - -} \ No newline at end of file +TexOffs::TexOffs(int x, int y) : x(x), y(y) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/TexOffs.h b/Minecraft.Client/Rendering/TexOffs.h index df3c22b71..367add126 100644 --- a/Minecraft.Client/Rendering/TexOffs.h +++ b/Minecraft.Client/Rendering/TexOffs.h @@ -1,9 +1,8 @@ #pragma once -class TexOffs -{ +class TexOffs { public: - const int x, y; + const int x, y; - TexOffs(int x, int y); + TexOffs(int x, int y); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Vertex.cpp b/Minecraft.Client/Rendering/Vertex.cpp index 42c79ac3e..b4c70ae19 100644 --- a/Minecraft.Client/Rendering/Vertex.cpp +++ b/Minecraft.Client/Rendering/Vertex.cpp @@ -1,27 +1,21 @@ #include "../Platform/stdafx.h" #include "Vertex.h" -Vertex::Vertex(float x, float y, float z, float u, float v) -{ - this->pos = Vec3::newPermanent(x,y,z); +Vertex::Vertex(float x, float y, float z, float u, float v) { + this->pos = Vec3::newPermanent(x, y, z); this->u = u; this->v = v; } -Vertex *Vertex::remap(float u, float v) -{ - return new Vertex(this, u, v); -} +Vertex* Vertex::remap(float u, float v) { return new Vertex(this, u, v); } -Vertex::Vertex(Vertex *vertex, float u, float v) -{ +Vertex::Vertex(Vertex* vertex, float u, float v) { this->pos = vertex->pos; this->u = u; this->v = v; } -Vertex::Vertex(Vec3 *pos, float u, float v) -{ +Vertex::Vertex(Vec3* pos, float u, float v) { this->pos = pos; this->u = u; this->v = v; diff --git a/Minecraft.Client/Rendering/Vertex.h b/Minecraft.Client/Rendering/Vertex.h index 0c446ddea..99166d1ee 100644 --- a/Minecraft.Client/Rendering/Vertex.h +++ b/Minecraft.Client/Rendering/Vertex.h @@ -1,14 +1,14 @@ #pragma once #include "../../Minecraft.World/Util/Vec3.h" -class Vertex -{ +class Vertex { public: - Vec3 *pos; - float u,v; + Vec3* pos; + float u, v; + public: - Vertex(float x, float y, float z, float u, float v); - Vertex *remap(float u, float v); - Vertex(Vertex *vertex, float u, float v); - Vertex(Vec3 *pos, float u, float v); + Vertex(float x, float y, float z, float u, float v); + Vertex* remap(float u, float v); + Vertex(Vertex* vertex, float u, float v); + Vertex(Vec3* pos, float u, float v); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/glWrapper.cpp b/Minecraft.Client/Rendering/glWrapper.cpp index 7b13fc285..c1a3628ef 100644 --- a/Minecraft.Client/Rendering/glWrapper.cpp +++ b/Minecraft.Client/Rendering/glWrapper.cpp @@ -6,389 +6,312 @@ #include "../../Minecraft.World/IO/Streams/IntBuffer.h" #include "../../Minecraft.World/IO/Streams/ByteBuffer.h" -void glViewport(int x, int y, int w, int h) -{ - // We don't really need anything here because minecraft doesn't current do anything other than the default viewport +void glViewport(int x, int y, int w, int h) { + // We don't really need anything here because minecraft doesn't current do + // anything other than the default viewport } -void glTranslatef(float x,float y,float z) -{ - RenderManager.MatrixTranslate(x,y,z); +void glTranslatef(float x, float y, float z) { + RenderManager.MatrixTranslate(x, y, z); } -void glRotatef(float angle, float x, float y, float z) -{ - RenderManager.MatrixRotate(angle*(PI/180.0f),x,y,z); +void glRotatef(float angle, float x, float y, float z) { + RenderManager.MatrixRotate(angle * (PI / 180.0f), x, y, z); } -void glPopMatrix() -{ - RenderManager.MatrixPop(); +void glPopMatrix() { RenderManager.MatrixPop(); } + +void glPushMatrix() { RenderManager.MatrixPush(); } + +void glScalef(float x, float y, float z) { RenderManager.MatrixScale(x, y, z); } + +void glMultMatrixf(float* m) { RenderManager.MatrixMult(m); } + +void glMatrixMode(int type) { RenderManager.MatrixMode(type); } + +void glLoadIdentity() { RenderManager.MatrixSetIdentity(); } + +void gluPerspective(float fovy, float aspect, float zNear, float zFar) { + RenderManager.MatrixPerspective(fovy, aspect, zNear, zFar); } -void glPushMatrix() -{ - RenderManager.MatrixPush(); +void glOrtho(float left, float right, float bottom, float top, float zNear, + float zFar) { + RenderManager.MatrixOrthogonal(left, right, bottom, top, zNear, zFar); } -void glScalef(float x, float y, float z) -{ - RenderManager.MatrixScale(x,y,z); +void glScaled(double x, double y, double z) { + RenderManager.MatrixScale((float)x, (float)y, (float)z); } -void glMultMatrixf(float *m) -{ - RenderManager.MatrixMult(m); +void glGetFloat(int type, FloatBuffer* buff) { + memcpy(buff->_getDataPointer(), RenderManager.MatrixGet(type), 64); } -void glMatrixMode(int type) -{ - RenderManager.MatrixMode(type); +void glDeleteLists(int first, int count) { + RenderManager.CBuffDelete(first, count); } -void glLoadIdentity() -{ - RenderManager.MatrixSetIdentity(); -} +int glGenLists(int count) { return RenderManager.CBuffCreate(count); } -void gluPerspective(float fovy, float aspect, float zNear, float zFar) -{ - RenderManager.MatrixPerspective(fovy,aspect,zNear,zFar); -} +void glNewList(int index, int mode) { RenderManager.CBuffStart(index); } -void glOrtho(float left,float right,float bottom,float top,float zNear,float zFar) -{ - RenderManager.MatrixOrthogonal(left,right,bottom,top,zNear,zFar); -} - -void glScaled(double x,double y,double z) -{ - RenderManager.MatrixScale((float)x,(float)y,(float)z); -} - -void glGetFloat(int type, FloatBuffer *buff) -{ - memcpy(buff->_getDataPointer(),RenderManager.MatrixGet(type),64); -} - -void glDeleteLists(int first,int count) -{ - RenderManager.CBuffDelete(first,count); -} - -int glGenLists(int count) -{ - return RenderManager.CBuffCreate(count); -} - -void glNewList(int index, int mode) -{ - RenderManager.CBuffStart(index); -} - -void glEndList(int vertexCount) -{ +void glEndList(int vertexCount) { #ifdef _XBOX - RenderManager.CBuffEnd(vertexCount); + RenderManager.CBuffEnd(vertexCount); #else - RenderManager.CBuffEnd(); + RenderManager.CBuffEnd(); #endif } -void glCallList(int index) -{ - RenderManager.CBuffCall(index); +void glCallList(int index) { RenderManager.CBuffCall(index); } + +void glCallLists(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + RenderManager.CBuffCall(ib->get(i)); + } } -void glCallLists(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - RenderManager.CBuffCall(ib->get(i)); - } -} +void glClear(int flags) { RenderManager.Clear(flags); } -void glClear(int flags) -{ - RenderManager.Clear(flags); -} - -void glClearColor(float r, float g, float b, float a) -{ +void glClearColor(float r, float g, float b, float a) { #ifdef _XBOX - int ir = (int)(r * 255.0f); if( ir < 0 ) ir = 0; if( ir > 255 ) ir = 255; - int ig = (int)(g * 255.0f); if( ig < 0 ) ig = 0; if( ig > 255 ) ig = 255; - int ib = (int)(b * 255.0f); if( ib < 0 ) ib = 0; if( ib > 255 ) ib = 255; - int ia = (int)(a * 255.0f); if( ia < 0 ) ia = 0; if( ia > 255 ) ia = 255; + int ir = (int)(r * 255.0f); + if (ir < 0) ir = 0; + if (ir > 255) ir = 255; + int ig = (int)(g * 255.0f); + if (ig < 0) ig = 0; + if (ig > 255) ig = 255; + int ib = (int)(b * 255.0f); + if (ib < 0) ib = 0; + if (ib > 255) ib = 255; + int ia = (int)(a * 255.0f); + if (ia < 0) ia = 0; + if (ia > 255) ia = 255; - RenderManager.SetClearColour(D3DCOLOR_RGBA(ir,ig,ib,ia)); + RenderManager.SetClearColour(D3DCOLOR_RGBA(ir, ig, ib, ia)); #else - float rgba[4] = {r,g,b,a}; - RenderManager.SetClearColour(rgba); + float rgba[4] = {r, g, b, a}; + RenderManager.SetClearColour(rgba); #endif } -void Display::update() -{ +void Display::update() {} + +void Display::swapBuffers() {} + +void glBindTexture(int target, int texture) { + RenderManager.TextureBind(texture); } -void Display::swapBuffers() -{ +void glTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int format, int type, + ByteBuffer* data) { + RenderManager.TextureData(width, height, data->getBuffer(), level); } -void glBindTexture(int target,int texture) -{ - RenderManager.TextureBind(texture); -} - -void glTexImage2D(int target,int level,int internalformat,int width,int height,int border,int format,int type, ByteBuffer *data) -{ - RenderManager.TextureData(width,height,data->getBuffer(),level); -} - -void glDeleteTextures(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - RenderManager.TextureFree(ib->get(i)); - } +void glDeleteTextures(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + RenderManager.TextureFree(ib->get(i)); + } } // 4J Stu - I'm pretty sure this is what it should do -void glDeleteTextures(int id) -{ - RenderManager.TextureFree(id); -} +void glDeleteTextures(int id) { RenderManager.TextureFree(id); } -void glGenTextures(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - ib->put(RenderManager.TextureCreate()); - } +void glGenTextures(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + ib->put(RenderManager.TextureCreate()); + } } // 4J Stu - I'm pretty sure this is what it should do -int glGenTextures() -{ - return RenderManager.TextureCreate(); +int glGenTextures() { return RenderManager.TextureCreate(); } + +void glColor3f(float r, float g, float b) { + RenderManager.StateSetColour(r, g, b, 1.0f); } -void glColor3f(float r, float g, float b) -{ - RenderManager.StateSetColour(r,g,b,1.0f); +void glColor4f(float r, float g, float b, float a) { + RenderManager.StateSetColour(r, g, b, a); } -void glColor4f(float r, float g, float b, float a) -{ - RenderManager.StateSetColour(r,g,b,a); +void glDisable(int state) { + switch (state) { + case GL_TEXTURE_2D: + RenderManager.TextureBind(-1); + break; + case GL_BLEND: + RenderManager.StateSetBlendEnable(false); + break; + case GL_CULL_FACE: + RenderManager.StateSetFaceCull(false); + break; + case GL_DEPTH_TEST: + RenderManager.StateSetDepthTestEnable(false); + break; + case GL_ALPHA_TEST: + RenderManager.StateSetAlphaTestEnable(false); + break; + case GL_FOG: + RenderManager.StateSetFogEnable(false); + break; + case GL_LIGHTING: + RenderManager.StateSetLightingEnable(false); + break; + case GL_LIGHT0: + RenderManager.StateSetLightEnable(0, false); + break; + case GL_LIGHT1: + RenderManager.StateSetLightEnable(1, false); + break; + } } -void glDisable(int state) -{ - switch(state) - { - case GL_TEXTURE_2D: - RenderManager.TextureBind(-1); - break; - case GL_BLEND: - RenderManager.StateSetBlendEnable(false); - break; - case GL_CULL_FACE: - RenderManager.StateSetFaceCull(false); - break; - case GL_DEPTH_TEST: - RenderManager.StateSetDepthTestEnable(false); - break; - case GL_ALPHA_TEST: - RenderManager.StateSetAlphaTestEnable(false); - break; - case GL_FOG: - RenderManager.StateSetFogEnable(false); - break; - case GL_LIGHTING: - RenderManager.StateSetLightingEnable(false); - break; - case GL_LIGHT0: - RenderManager.StateSetLightEnable(0,false); - break; - case GL_LIGHT1: - RenderManager.StateSetLightEnable(1,false); - break; - } +void glEnable(int state) { + switch (state) { + case GL_BLEND: + RenderManager.StateSetBlendEnable(true); + break; + case GL_CULL_FACE: + RenderManager.StateSetFaceCull(true); + break; + case GL_DEPTH_TEST: + RenderManager.StateSetDepthTestEnable(true); + break; + case GL_ALPHA_TEST: + RenderManager.StateSetAlphaTestEnable(true); + break; + case GL_FOG: + RenderManager.StateSetFogEnable(true); + break; + case GL_LIGHTING: + RenderManager.StateSetLightingEnable(true); + break; + case GL_LIGHT0: + RenderManager.StateSetLightEnable(0, true); + break; + case GL_LIGHT1: + RenderManager.StateSetLightEnable(1, true); + break; + } } -void glEnable(int state) -{ - switch(state) - { - case GL_BLEND: - RenderManager.StateSetBlendEnable(true); - break; - case GL_CULL_FACE: - RenderManager.StateSetFaceCull(true); - break; - case GL_DEPTH_TEST: - RenderManager.StateSetDepthTestEnable(true); - break; - case GL_ALPHA_TEST: - RenderManager.StateSetAlphaTestEnable(true); - break; - case GL_FOG: - RenderManager.StateSetFogEnable(true); - break; - case GL_LIGHTING: - RenderManager.StateSetLightingEnable(true); - break; - case GL_LIGHT0: - RenderManager.StateSetLightEnable(0,true); - break; - case GL_LIGHT1: - RenderManager.StateSetLightEnable(1,true); - break; - } +void glDepthMask(bool enable) { RenderManager.StateSetDepthMask(enable); } + +void glBlendFunc(int src, int dst) { + RenderManager.StateSetBlendFunc(src, dst); } -void glDepthMask(bool enable) -{ - RenderManager.StateSetDepthMask(enable); +void glAlphaFunc(int func, float param) { + RenderManager.StateSetAlphaFunc(func, param); } -void glBlendFunc(int src, int dst) -{ - RenderManager.StateSetBlendFunc(src,dst); -} - -void glAlphaFunc(int func,float param) -{ - RenderManager.StateSetAlphaFunc(func, param); -} - -void glDepthFunc(int func) -{ +void glDepthFunc(int func) { #ifdef _XBOX - RenderManager.StateSetDepthFunc(func); + RenderManager.StateSetDepthFunc(func); #else - RenderManager.StateSetDepthFunc(func); + RenderManager.StateSetDepthFunc(func); #endif } -void glTexParameteri(int target, int param, int value) -{ - RenderManager.TextureSetParam(param,value); +void glTexParameteri(int target, int param, int value) { + RenderManager.TextureSetParam(param, value); } -void glPolygonOffset(float factor, float units) -{ +void glPolygonOffset(float factor, float units) { #ifdef __PS3__ - RenderManager.StateSetDepthSlopeAndBias(factor, units); + RenderManager.StateSetDepthSlopeAndBias(factor, units); #else - // DirectX specifies these offsets in z buffer 0 to 1 sort of range, whereas opengl seems to be in a 0 -> depth buffer size sort of range. - // The slope factor is quite possibly different too. Magic factor for now anyway. - const float magicFactor = 65536.0f; - RenderManager.StateSetDepthSlopeAndBias(factor / magicFactor, units / magicFactor); + // DirectX specifies these offsets in z buffer 0 to 1 sort of range, whereas + // opengl seems to be in a 0 -> depth buffer size sort of range. The slope + // factor is quite possibly different too. Magic factor for now anyway. + const float magicFactor = 65536.0f; + RenderManager.StateSetDepthSlopeAndBias(factor / magicFactor, + units / magicFactor); #endif } -void glFogi(int param, int value) -{ - if( param == GL_FOG_MODE ) - { - RenderManager.StateSetFogMode(value); - } +void glFogi(int param, int value) { + if (param == GL_FOG_MODE) { + RenderManager.StateSetFogMode(value); + } } -void glFogf(int param, float value) -{ - switch(param) - { - case GL_FOG_START: - RenderManager.StateSetFogNearDistance(value); - break; - case GL_FOG_END: - RenderManager.StateSetFogFarDistance(value); - break; - case GL_FOG_DENSITY: - RenderManager.StateSetFogDensity(value); - break; - } +void glFogf(int param, float value) { + switch (param) { + case GL_FOG_START: + RenderManager.StateSetFogNearDistance(value); + break; + case GL_FOG_END: + RenderManager.StateSetFogFarDistance(value); + break; + case GL_FOG_DENSITY: + RenderManager.StateSetFogDensity(value); + break; + } } -void glFog(int param,FloatBuffer *values) -{ - if( param == GL_FOG_COLOR ) - { - float *data = values->_getDataPointer(); - RenderManager.StateSetFogColour(data[0],data[1],data[2]); - } +void glFog(int param, FloatBuffer* values) { + if (param == GL_FOG_COLOR) { + float* data = values->_getDataPointer(); + RenderManager.StateSetFogColour(data[0], data[1], data[2]); + } } -void glLight(int light, int mode,FloatBuffer *values) -{ - int idx; - if( light == GL_LIGHT0 ) - { - idx = 0; - } - else if( light == GL_LIGHT1 ) - { - idx = 1; - } - else return; - float *data =values->_getDataPointer(); - switch( mode ) - { - case GL_POSITION: - RenderManager.StateSetLightDirection(idx, data[0], data[1], data[2]); - break; - case GL_DIFFUSE: - RenderManager.StateSetLightColour(idx, data[0], data[1], data[2]); - break; - case GL_AMBIENT: - break; - case GL_SPECULAR: - break; - } +void glLight(int light, int mode, FloatBuffer* values) { + int idx; + if (light == GL_LIGHT0) { + idx = 0; + } else if (light == GL_LIGHT1) { + idx = 1; + } else + return; + float* data = values->_getDataPointer(); + switch (mode) { + case GL_POSITION: + RenderManager.StateSetLightDirection(idx, data[0], data[1], + data[2]); + break; + case GL_DIFFUSE: + RenderManager.StateSetLightColour(idx, data[0], data[1], data[2]); + break; + case GL_AMBIENT: + break; + case GL_SPECULAR: + break; + } } -void glLightModel(int mode, FloatBuffer *values) -{ - float *data =values->_getDataPointer(); - if( mode == GL_LIGHT_MODEL_AMBIENT ) - { - RenderManager.StateSetLightAmbientColour(data[0],data[1],data[2]); - } +void glLightModel(int mode, FloatBuffer* values) { + float* data = values->_getDataPointer(); + if (mode == GL_LIGHT_MODEL_AMBIENT) { + RenderManager.StateSetLightAmbientColour(data[0], data[1], data[2]); + } } -void glLineWidth(float width) -{ - RenderManager.StateSetLineWidth(width); +void glLineWidth(float width) { RenderManager.StateSetLineWidth(width); } + +void glColorMask(bool red, bool green, bool blue, bool alpha) { + RenderManager.StateSetWriteEnable(red, green, blue, alpha); } -void glColorMask(bool red, bool green, bool blue, bool alpha) -{ - RenderManager.StateSetWriteEnable(red, green, blue, alpha); +void glMultiTexCoord2f(int, float u, float v) { + // Clamp these values just to be safe - the lighting code can get broken if + // we pass things to StateSetVertexTextureUV that are >= 1 + if (u > 255.0f) u = 255.0f; + if (v > 255.0f) v = 255.0f; + + RenderManager.StateSetVertexTextureUV(u / 256.0f, v / 256.0f); } -void glMultiTexCoord2f(int, float u , float v) -{ - // Clamp these values just to be safe - the lighting code can get broken if we pass things to StateSetVertexTextureUV that are >= 1 - if( u > 255.0f ) u = 255.0f; - if( v > 255.0f ) v = 255.0f; +void glTexGen(int coord, int mode, FloatBuffer* vec) { + float* data = vec->_getDataPointer(); - RenderManager.StateSetVertexTextureUV( u / 256.0f, v / 256.0f); + RenderManager.StateSetTexGenCol(coord, data[0], data[1], data[2], data[3], + mode == GL_EYE_PLANE); } -void glTexGen(int coord, int mode, FloatBuffer *vec) -{ - float *data = vec->_getDataPointer(); - - RenderManager.StateSetTexGenCol( coord, data[0], data[1], data[2], data[3], mode == GL_EYE_PLANE ); -} - -void glCullFace(int dir) -{ - RenderManager.StateSetFaceCullCW( dir == GL_BACK); -} +void glCullFace(int dir) { RenderManager.StateSetFaceCullCW(dir == GL_BACK); } #endif diff --git a/Minecraft.Client/Textures/BufferedImage.cpp b/Minecraft.Client/Textures/BufferedImage.cpp index d8065851f..0c505003d 100644 --- a/Minecraft.Client/Textures/BufferedImage.cpp +++ b/Minecraft.Client/Textures/BufferedImage.cpp @@ -1,400 +1,336 @@ -#include "../Platform/stdafx.h" +#include "../Platform/stdafx.h" #include "../../Minecraft.World/Util/StringHelpers.h" #include "Textures.h" #include "../../Minecraft.World/Util/ArrayWithLength.h" #include "BufferedImage.h" #ifdef _XBOX -typedef struct -{ - unsigned int filesz; - unsigned short creator1; - unsigned short creator2; - unsigned int bmp_offset; - unsigned int header_sz; - unsigned int width; - unsigned int height; - unsigned short nplanes; - unsigned short bitspp; - unsigned int compress_type; - unsigned int bmp_bytesz; - int hres; - int vres; - unsigned int ncolors; - unsigned int nimpcolors; +typedef struct { + unsigned int filesz; + unsigned short creator1; + unsigned short creator2; + unsigned int bmp_offset; + unsigned int header_sz; + unsigned int width; + unsigned int height; + unsigned short nplanes; + unsigned short bitspp; + unsigned int compress_type; + unsigned int bmp_bytesz; + int hres; + int vres; + unsigned int ncolors; + unsigned int nimpcolors; } BITMAPINFOHEADER; #endif -BufferedImage::BufferedImage(int width,int height,int type) -{ - data[0] = new int[width*height]; +BufferedImage::BufferedImage(int width, int height, int type) { + data[0] = new int[width * height]; - for( int i = 1 ; i < 10; i++ ) - { - data[i] = NULL; - } - this->width = width; - this->height = height; + for (int i = 1; i < 10; i++) { + data[i] = NULL; + } + this->width = width; + this->height = height; } -void BufferedImage::ByteFlip4(unsigned int &data) -{ - data = ( data >> 24 ) | - ( ( data >> 8 ) & 0x0000ff00 ) | - ( ( data << 8 ) & 0x00ff0000 ) | - ( data << 24 ); +void BufferedImage::ByteFlip4(unsigned int& data) { + data = (data >> 24) | ((data >> 8) & 0x0000ff00) | + ((data << 8) & 0x00ff0000) | (data << 24); } -// Loads a bitmap into a buffered image - only currently supports the 2 types of 32-bit image that we've made so far -// and determines which of these is which by the compression method. Compression method 3 is a 32-bit image with only -// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image with a valid alpha channel. -BufferedImage::BufferedImage(const std::wstring& File, bool filenameHasExtension /*=false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - HRESULT hr; - std::wstring wDrive; - std::wstring filePath; - filePath = File; +// Loads a bitmap into a buffered image - only currently supports the 2 types of +// 32-bit image that we've made so far and determines which of these is which by +// the compression method. Compression method 3 is a 32-bit image with only +// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image +// with a valid alpha channel. +BufferedImage::BufferedImage(const std::wstring& File, + bool filenameHasExtension /*=false*/, + bool bTitleUpdateTexture /*=false*/, + const std::wstring& drive /*=L""*/) { + HRESULT hr; + std::wstring wDrive; + std::wstring filePath; + filePath = File; - wDrive = drive; - if(wDrive.empty()) - { + wDrive = drive; + if (wDrive.empty()) { #ifdef _XBOX - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed #ifdef _TU_BUILD - wDrive=L"UPDATE:\\"; + wDrive = L"UPDATE:\\"; #else - wDrive=L"GAME:\\res\\TitleUpdate\\"; + wDrive = L"GAME:\\res\\TitleUpdate\\"; #endif - } - else - { - wDrive=L"GAME:\\"; - } + } else { + wDrive = L"GAME:\\"; + } #else #ifdef __PS3__ - char *pchUsrDir; - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(File); - pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - } - else - { - pchUsrDir=getUsrDirPath(); - } + char* pchUsrDir; + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(File); + pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + } else { + pchUsrDir = getUsrDirPath(); + } - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"/Common/"; + } #elif __PSVITA__ - /*char *pchUsrDir=getUsrDirPath(); + /*char *pchUsrDir=getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - }*/ + if(bTitleUpdateTexture) + { + // Make the content package point to to the UPDATE: drive is + needed wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; + } + else + { + wDrive= wstr + L"/Common/"; + }*/ - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #else - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #endif #endif - } + } - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } - for( int l = 0; l < 10; l++ ) - { - std::wstring name; - std::wstring mipMapPath = L""; - if( l != 0 ) - { - mipMapPath = L"MipMapLevel" + _toString(l+1); - } - if( filenameHasExtension ) - { - name = wDrive + L"res" + filePath.substr(0,filePath.length()); - } - else - { - name = wDrive + L"res" + filePath.substr(0,filePath.length()-4) + mipMapPath + L".png"; - } + for (int l = 0; l < 10; l++) { + std::wstring name; + std::wstring mipMapPath = L""; + if (l != 0) { + mipMapPath = L"MipMapLevel" + _toString(l + 1); + } + if (filenameHasExtension) { + name = wDrive + L"res" + filePath.substr(0, filePath.length()); + } else { + name = wDrive + L"res" + filePath.substr(0, filePath.length() - 4) + + mipMapPath + L".png"; + } - const char *pchTextureName=wstringtofilename(name); + const char* pchTextureName = wstringtofilename(name); #ifdef _DEBUG - app.DebugPrintf("\n--- Loading TEXTURE - %s\n\n",pchTextureName); + app.DebugPrintf("\n--- Loading TEXTURE - %s\n\n", pchTextureName); #endif - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - hr=RenderManager.LoadTextureData(pchTextureName,&ImageInfo,&data[l]); + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + hr = + RenderManager.LoadTextureData(pchTextureName, &ImageInfo, &data[l]); + if (hr != ERROR_SUCCESS) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - if(hr!=ERROR_SUCCESS) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } - - if( l == 0 ) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - } + if (l == 0) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } + } } -BufferedImage::BufferedImage(DLCPack *dlcPack, const std::wstring& File, bool filenameHasExtension /*= false*/ ) -{ - HRESULT hr; - std::wstring filePath = File; - std::uint8_t *pbData = NULL; - std::uint32_t dataBytes = 0; +BufferedImage::BufferedImage(DLCPack* dlcPack, const std::wstring& File, + bool filenameHasExtension /*= false*/) { + HRESULT hr; + std::wstring filePath = File; + std::uint8_t* pbData = NULL; + std::uint32_t dataBytes = 0; - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } - for( int l = 0; l < 10; l++ ) - { - std::wstring name; - std::wstring mipMapPath = L""; - if( l != 0 ) - { - mipMapPath = L"MipMapLevel" + _toString(l+1); - } - if( filenameHasExtension ) - { - name = L"res" + filePath.substr(0,filePath.length()); - } - else - { - name = L"res" + filePath.substr(0,filePath.length()-4) + mipMapPath + L".png"; - } + for (int l = 0; l < 10; l++) { + std::wstring name; + std::wstring mipMapPath = L""; + if (l != 0) { + mipMapPath = L"MipMapLevel" + _toString(l + 1); + } + if (filenameHasExtension) { + name = L"res" + filePath.substr(0, filePath.length()); + } else { + name = L"res" + filePath.substr(0, filePath.length() - 4) + + mipMapPath + L".png"; + } - if(!dlcPack->doesPackContainFile(DLCManager::e_DLCType_All, name)) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } + if (!dlcPack->doesPackContainFile(DLCManager::e_DLCType_All, name)) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - DLCFile *dlcFile = dlcPack->getFile(DLCManager::e_DLCType_All, name); - pbData = dlcFile->getData(dataBytes); - if(pbData == NULL || dataBytes == 0) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } + DLCFile* dlcFile = dlcPack->getFile(DLCManager::e_DLCType_All, name); + pbData = dlcFile->getData(dataBytes); + if (pbData == NULL || dataBytes == 0) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - hr=RenderManager.LoadTextureData(pbData,dataBytes,&ImageInfo,&data[l]); + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + hr = RenderManager.LoadTextureData(pbData, dataBytes, &ImageInfo, + &data[l]); + if (hr != ERROR_SUCCESS) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - if(hr!=ERROR_SUCCESS) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } - - if( l == 0 ) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - } + if (l == 0) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } + } } +BufferedImage::BufferedImage(std::uint8_t* pbData, std::uint32_t dataBytes) { + int iCurrentByte = 0; + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } -BufferedImage::BufferedImage(std::uint8_t *pbData, std::uint32_t dataBytes) -{ - int iCurrentByte=0; - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + HRESULT hr = + RenderManager.LoadTextureData(pbData, dataBytes, &ImageInfo, &data[0]); - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - HRESULT hr=RenderManager.LoadTextureData(pbData,dataBytes,&ImageInfo,&data[0]); - - if(hr==ERROR_SUCCESS) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - else - { - app.FatalLoadError(); - } + if (hr == ERROR_SUCCESS) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } else { + app.FatalLoadError(); + } } -BufferedImage::~BufferedImage() -{ - for(int i = 0; i < 10; i++ ) - { - delete[] data[i]; - } +BufferedImage::~BufferedImage() { + for (int i = 0; i < 10; i++) { + delete[] data[i]; + } } -int BufferedImage::getWidth() -{ - return width; +int BufferedImage::getWidth() { return width; } + +int BufferedImage::getHeight() { return height; } + +void BufferedImage::getRGB(int startX, int startY, int w, int h, intArray out, + int offset, int scansize, int level) { + int ww = width >> level; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + out[y * scansize + offset + x] = + data[level][startX + x + ww * (startY + y)]; + } + } } -int BufferedImage::getHeight() -{ - return height; +int* BufferedImage::getData() { return data[0]; } + +int* BufferedImage::getData(int level) { return data[level]; } + +Graphics* BufferedImage::getGraphics() { return NULL; } + +// Returns the transparency. Returns either OPAQUE, BITMASK, or TRANSLUCENT. +// Specified by: +// getTransparency in interface Transparency +// Returns: +// the transparency of this BufferedImage. +int BufferedImage::getTransparency() { + // TODO - 4J Implement? + return 0; } -void BufferedImage::getRGB(int startX, int startY, int w, int h, intArray out,int offset,int scansize, int level) -{ - int ww = width >> level; - for( int y = 0; y < h; y++ ) - { - for( int x = 0; x < w; x++ ) - { - out[ y * scansize + offset + x] = data[level][ startX + x + ww * ( startY + y ) ]; - } - } +// Returns a subimage defined by a specified rectangular region. The returned +// BufferedImage shares the same data array as the original image. Parameters: +// x, y - the coordinates of the upper-left corner of the specified rectangular +// region w - the width of the specified rectangular region h - the height of +// the specified rectangular region Returns: a BufferedImage that is the +// subimage of this BufferedImage. +BufferedImage* BufferedImage::getSubimage(int x, int y, int w, int h) { + // TODO - 4J Implement + + BufferedImage* img = new BufferedImage(w, h, 0); + intArray arrayWrapper(img->data[0], w * h); + this->getRGB(x, y, w, h, arrayWrapper, 0, w); + + int level = 1; + while (getData(level) != NULL) { + int ww = w >> level; + int hh = h >> level; + int xx = x >> level; + int yy = y >> level; + img->data[level] = new int[ww * hh]; + intArray arrayWrapper(img->data[level], ww * hh); + this->getRGB(xx, yy, ww, hh, arrayWrapper, 0, ww, level); + + ++level; + } + + return img; } -int *BufferedImage::getData() -{ - return data[0]; -} - -int *BufferedImage::getData(int level) -{ - return data[level]; -} - -Graphics *BufferedImage::getGraphics() -{ - return NULL; -} - -//Returns the transparency. Returns either OPAQUE, BITMASK, or TRANSLUCENT. -//Specified by: -//getTransparency in interface Transparency -//Returns: -//the transparency of this BufferedImage. -int BufferedImage::getTransparency() -{ - // TODO - 4J Implement? - return 0; -} - -//Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image. -//Parameters: -//x, y - the coordinates of the upper-left corner of the specified rectangular region -//w - the width of the specified rectangular region -//h - the height of the specified rectangular region -//Returns: -//a BufferedImage that is the subimage of this BufferedImage. -BufferedImage *BufferedImage::getSubimage(int x ,int y, int w, int h) -{ - // TODO - 4J Implement - - BufferedImage *img = new BufferedImage(w,h,0); - intArray arrayWrapper(img->data[0], w*h); - this->getRGB(x, y, w, h, arrayWrapper,0,w); - - int level = 1; - while(getData(level) != NULL) - { - int ww = w >> level; - int hh = h >> level; - int xx = x >> level; - int yy = y >> level; - img->data[level] = new int[ww*hh]; - intArray arrayWrapper(img->data[level], ww*hh); - this->getRGB(xx, yy, ww, hh, arrayWrapper,0,ww,level); - - ++level; - } - - return img; -} - - -void BufferedImage::preMultiplyAlpha() -{ - int *curData = data[0]; - - int cur = 0; - int alpha = 0; - int r = 0; - int g = 0; - int b = 0; - - int total = width * height; - for(unsigned int i = 0; i < total; ++i) - { - cur = curData[i]; - alpha = (cur >> 24) & 0xff; - r = ((cur >> 16) & 0xff) * (float)alpha/255; - g = ((cur >> 8) & 0xff) * (float)alpha/255; - b = (cur & 0xff) * (float)alpha/255; - - curData[i] = (r << 16) | (g << 8) | (b ) | (alpha << 24); - } +void BufferedImage::preMultiplyAlpha() { + int* curData = data[0]; + + int cur = 0; + int alpha = 0; + int r = 0; + int g = 0; + int b = 0; + + int total = width * height; + for (unsigned int i = 0; i < total; ++i) { + cur = curData[i]; + alpha = (cur >> 24) & 0xff; + r = ((cur >> 16) & 0xff) * (float)alpha / 255; + g = ((cur >> 8) & 0xff) * (float)alpha / 255; + b = (cur & 0xff) * (float)alpha / 255; + + curData[i] = (r << 16) | (g << 8) | (b) | (alpha << 24); + } } diff --git a/Minecraft.Client/Textures/BufferedImage.h b/Minecraft.Client/Textures/BufferedImage.h index 94ffe0576..fbbf39283 100644 --- a/Minecraft.Client/Textures/BufferedImage.h +++ b/Minecraft.Client/Textures/BufferedImage.h @@ -1,34 +1,36 @@ #pragma once #include - class Graphics; class DLCPack; -class BufferedImage -{ +class BufferedImage { private: - int *data[10]; // Arrays for mipmaps - NULL if not used - int width; - int height; - void ByteFlip4(unsigned int &data); // 4J added + int* data[10]; // Arrays for mipmaps - NULL if not used + int width; + int height; + void ByteFlip4(unsigned int& data); // 4J added public: - static const int TYPE_INT_ARGB = 0; - static const int TYPE_INT_RGB = 1; - BufferedImage(int width,int height,int type); - BufferedImage(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); // 4J added - BufferedImage(DLCPack *dlcPack, const std::wstring& File, bool filenameHasExtension = false ); // 4J Added - BufferedImage(std::uint8_t *pbData, std::uint32_t dataBytes); // 4J added - ~BufferedImage(); + static const int TYPE_INT_ARGB = 0; + static const int TYPE_INT_RGB = 1; + BufferedImage(int width, int height, int type); + BufferedImage(const std::wstring& File, bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); // 4J added + BufferedImage(DLCPack* dlcPack, const std::wstring& File, + bool filenameHasExtension = false); // 4J Added + BufferedImage(std::uint8_t* pbData, std::uint32_t dataBytes); // 4J added + ~BufferedImage(); - int getWidth(); - int getHeight(); - void getRGB(int startX, int startY, int w, int h, intArray out,int offset,int scansize, int level = 0); // 4J Added level param - int *getData(); // 4J added - int *getData(int level); // 4J added - Graphics *getGraphics(); - int getTransparency(); - BufferedImage *getSubimage(int x, int y, int w, int h); + int getWidth(); + int getHeight(); + void getRGB(int startX, int startY, int w, int h, intArray out, int offset, + int scansize, int level = 0); // 4J Added level param + int* getData(); // 4J added + int* getData(int level); // 4J added + Graphics* getGraphics(); + int getTransparency(); + BufferedImage* getSubimage(int x, int y, int w, int h); - void preMultiplyAlpha(); + void preMultiplyAlpha(); }; diff --git a/Minecraft.Client/Textures/ClockTexture.cpp b/Minecraft.Client/Textures/ClockTexture.cpp index 592b1260d..65420510e 100644 --- a/Minecraft.Client/Textures/ClockTexture.cpp +++ b/Minecraft.Client/Textures/ClockTexture.cpp @@ -7,113 +7,87 @@ #include "Texture.h" #include "ClockTexture.h" -ClockTexture::ClockTexture() : StitchedTexture(L"compass") -{ - rot = rota = 0.0; - m_dataTexture = NULL; - m_iPad = XUSER_INDEX_ANY; +ClockTexture::ClockTexture() : StitchedTexture(L"compass") { + rot = rota = 0.0; + m_dataTexture = NULL; + m_iPad = XUSER_INDEX_ANY; } -ClockTexture::ClockTexture(int iPad, ClockTexture *dataTexture) : StitchedTexture(L"compass") -{ - rot = rota = 0.0; - m_dataTexture = dataTexture; - m_iPad = iPad; +ClockTexture::ClockTexture(int iPad, ClockTexture* dataTexture) + : StitchedTexture(L"compass") { + rot = rota = 0.0; + m_dataTexture = dataTexture; + m_iPad = iPad; } -void ClockTexture::cycleFrames() -{ +void ClockTexture::cycleFrames() { + Minecraft* mc = Minecraft::GetInstance(); - Minecraft *mc = Minecraft::GetInstance(); + double rott = 0; + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && + mc->localplayers[m_iPad] != NULL) { + float time = mc->localplayers[m_iPad]->level->getTimeOfDay(1); + rott = time; + if (!mc->localplayers[m_iPad]->level->dimension->isNaturalDimension()) { + rott = Math::random(); + } + } else { + // 4J Stu - For the static version, pretend we are already on a frame + // other than 0 + frame = 1; + } - double rott = 0; - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) - { - float time = mc->localplayers[m_iPad]->level->getTimeOfDay(1); - rott = time; - if (!mc->localplayers[m_iPad]->level->dimension->isNaturalDimension()) - { - rott = Math::random(); - } - } - else - { - // 4J Stu - For the static version, pretend we are already on a frame other than 0 - frame = 1; - } + double rotd = rott - rot; + while (rotd < -.5) rotd += 1.0; + while (rotd >= .5) rotd -= 1.0; + if (rotd < -1) rotd = -1; + if (rotd > 1) rotd = 1; + rota += rotd * 0.1; + rota *= 0.8; - double rotd = rott - rot; - while (rotd < -.5) - rotd += 1.0; - while (rotd >= .5) - rotd -= 1.0; - if (rotd < -1) rotd = -1; - if (rotd > 1) rotd = 1; - rota += rotd * 0.1; - rota *= 0.8; + rot += rota; - rot += rota; - - // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) - { - int newFrame = (int) ((rot + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - m_dataTexture->source->blit(x, y, m_dataTexture->frames->at(this->frame), rotated); - } - } - else - { - int newFrame = (int) ((rot + 1.0) * frames->size()) % frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + frames->size()) % frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - source->blit(x, y, frames->at(this->frame), rotated); - } - } + // 4J Stu - We share data with another texture + if (m_dataTexture != NULL) { + int newFrame = (int)((rot + 1.0) * m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + m_dataTexture->source->blit( + x, y, m_dataTexture->frames->at(this->frame), rotated); + } + } else { + int newFrame = (int)((rot + 1.0) * frames->size()) % frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + frames->size()) % frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + source->blit(x, y, frames->at(this->frame), rotated); + } + } } -int ClockTexture::getSourceWidth() const -{ - return source->getWidth(); +int ClockTexture::getSourceWidth() const { return source->getWidth(); } + +int ClockTexture::getSourceHeight() const { return source->getHeight(); } + +int ClockTexture::getFrames() { + if (m_dataTexture == NULL) { + return StitchedTexture::getFrames(); + } else { + return m_dataTexture->getFrames(); + } } -int ClockTexture::getSourceHeight() const -{ - return source->getHeight(); +void ClockTexture::freeFrameTextures() { + if (m_dataTexture == NULL) { + StitchedTexture::freeFrameTextures(); + } } -int ClockTexture::getFrames() -{ - if(m_dataTexture == NULL) - { - return StitchedTexture::getFrames(); - } - else - { - return m_dataTexture->getFrames(); - } -} - -void ClockTexture::freeFrameTextures() -{ - if(m_dataTexture == NULL) - { - StitchedTexture::freeFrameTextures(); - } -} - -bool ClockTexture::hasOwnData() -{ - return m_dataTexture == NULL; -} \ No newline at end of file +bool ClockTexture::hasOwnData() { return m_dataTexture == NULL; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/ClockTexture.h b/Minecraft.Client/Textures/ClockTexture.h index ea9011c3e..fc745bed7 100644 --- a/Minecraft.Client/Textures/ClockTexture.h +++ b/Minecraft.Client/Textures/ClockTexture.h @@ -1,21 +1,20 @@ #pragma once #include "Stitching/StitchedTexture.h" -class ClockTexture : public StitchedTexture -{ +class ClockTexture : public StitchedTexture { private: - double rot, rota; - int m_iPad; - ClockTexture* m_dataTexture; + double rot, rota; + int m_iPad; + ClockTexture* m_dataTexture; public: - ClockTexture(); - ClockTexture(int iPad, ClockTexture *dataTexture); - void cycleFrames(); - - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual int getFrames(); - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + ClockTexture(); + ClockTexture(int iPad, ClockTexture* dataTexture); + void cycleFrames(); + + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual int getFrames(); + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/CompassTexture.cpp b/Minecraft.Client/Textures/CompassTexture.cpp index fe26b4222..e09cfcadc 100644 --- a/Minecraft.Client/Textures/CompassTexture.cpp +++ b/Minecraft.Client/Textures/CompassTexture.cpp @@ -7,136 +7,113 @@ #include "Texture.h" #include "CompassTexture.h" -CompassTexture *CompassTexture::instance = NULL; +CompassTexture* CompassTexture::instance = NULL; -CompassTexture::CompassTexture() : StitchedTexture(L"compass") -{ - instance = this; +CompassTexture::CompassTexture() : StitchedTexture(L"compass") { + instance = this; - m_dataTexture = NULL; - m_iPad = XUSER_INDEX_ANY; + m_dataTexture = NULL; + m_iPad = XUSER_INDEX_ANY; - rot = rota = 0.0; + rot = rota = 0.0; } -CompassTexture::CompassTexture(int iPad, CompassTexture *dataTexture) : StitchedTexture(L"compass") -{ - m_dataTexture = dataTexture; - m_iPad = iPad; +CompassTexture::CompassTexture(int iPad, CompassTexture* dataTexture) + : StitchedTexture(L"compass") { + m_dataTexture = dataTexture; + m_iPad = iPad; - rot = rota = 0.0; + rot = rota = 0.0; } -void CompassTexture::cycleFrames() -{ - Minecraft *mc = Minecraft::GetInstance(); +void CompassTexture::cycleFrames() { + Minecraft* mc = Minecraft::GetInstance(); - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) - { - updateFromPosition(mc->localplayers[m_iPad]->level, mc->localplayers[m_iPad]->x, mc->localplayers[m_iPad]->z, mc->localplayers[m_iPad]->yRot, false, false); - } - else - { - frame = 1; - updateFromPosition(NULL, 0, 0, 0, false, true); - } + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && + mc->localplayers[m_iPad] != NULL) { + updateFromPosition(mc->localplayers[m_iPad]->level, + mc->localplayers[m_iPad]->x, + mc->localplayers[m_iPad]->z, + mc->localplayers[m_iPad]->yRot, false, false); + } else { + frame = 1; + updateFromPosition(NULL, 0, 0, 0, false, true); + } } -void CompassTexture::updateFromPosition(Level *level, double x, double z, double yRot, bool noNeedle, bool instant) -{ - double rott = 0; - if (level != NULL && !noNeedle) - { - Pos *spawnPos = level->getSharedSpawnPos(); - double xa = spawnPos->x - x; - double za = spawnPos->z - z; - delete spawnPos; - yRot = (int)yRot % 360; - rott = -((yRot - 90) * PI / 180 - atan2(za, xa)); - if (!level->dimension->isNaturalDimension()) - { - rott = Math::random() * PI * 2; - } - } +void CompassTexture::updateFromPosition(Level* level, double x, double z, + double yRot, bool noNeedle, + bool instant) { + double rott = 0; + if (level != NULL && !noNeedle) { + Pos* spawnPos = level->getSharedSpawnPos(); + double xa = spawnPos->x - x; + double za = spawnPos->z - z; + delete spawnPos; + yRot = (int)yRot % 360; + rott = -((yRot - 90) * PI / 180 - atan2(za, xa)); + if (!level->dimension->isNaturalDimension()) { + rott = Math::random() * PI * 2; + } + } - if (instant) - { - rot = rott; - } - else - { - double rotd = rott - rot; - while (rotd < -PI) - rotd += PI * 2; - while (rotd >= PI) - rotd -= PI * 2; - if (rotd < -1) rotd = -1; - if (rotd > 1) rotd = 1; - rota += rotd * 0.1; - rota *= 0.8; - rot += rota; - } + if (instant) { + rot = rott; + } else { + double rotd = rott - rot; + while (rotd < -PI) rotd += PI * 2; + while (rotd >= PI) rotd -= PI * 2; + if (rotd < -1) rotd = -1; + if (rotd > 1) rotd = 1; + rota += rotd * 0.1; + rota *= 0.8; + rot += rota; + } - // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) - { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - m_dataTexture->source->blit(this->x, this->y, m_dataTexture->frames->at(this->frame), rotated); - } - } - else - { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + frames->size()) % frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - source->blit(this->x, this->y, frames->at(this->frame), rotated); - } - } + // 4J Stu - We share data with another texture + if (m_dataTexture != NULL) { + int newFrame = + (int)(((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + m_dataTexture->source->blit(this->x, this->y, + m_dataTexture->frames->at(this->frame), + rotated); + } + } else { + int newFrame = + (int)(((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + frames->size()) % frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + source->blit(this->x, this->y, frames->at(this->frame), rotated); + } + } } -int CompassTexture::getSourceWidth() const -{ - return source->getWidth(); +int CompassTexture::getSourceWidth() const { return source->getWidth(); } + +int CompassTexture::getSourceHeight() const { return source->getHeight(); } + +int CompassTexture::getFrames() { + if (m_dataTexture == NULL) { + return StitchedTexture::getFrames(); + } else { + return m_dataTexture->getFrames(); + } } -int CompassTexture::getSourceHeight() const -{ - return source->getHeight(); +void CompassTexture::freeFrameTextures() { + if (m_dataTexture == NULL) { + StitchedTexture::freeFrameTextures(); + } } -int CompassTexture::getFrames() -{ - if(m_dataTexture == NULL) - { - return StitchedTexture::getFrames(); - } - else - { - return m_dataTexture->getFrames(); - } -} - -void CompassTexture::freeFrameTextures() -{ - if(m_dataTexture == NULL) - { - StitchedTexture::freeFrameTextures(); - } -} - -bool CompassTexture::hasOwnData() -{ - return m_dataTexture == NULL; -} \ No newline at end of file +bool CompassTexture::hasOwnData() { return m_dataTexture == NULL; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/CompassTexture.h b/Minecraft.Client/Textures/CompassTexture.h index fc7897095..50121d7db 100644 --- a/Minecraft.Client/Textures/CompassTexture.h +++ b/Minecraft.Client/Textures/CompassTexture.h @@ -1,25 +1,25 @@ #pragma once #include "Stitching/StitchedTexture.h" -class CompassTexture : public StitchedTexture -{ +class CompassTexture : public StitchedTexture { private: - int m_iPad; - CompassTexture* m_dataTexture; + int m_iPad; + CompassTexture* m_dataTexture; public: - static CompassTexture *instance; - double rot, rota; + static CompassTexture* instance; + double rot, rota; - CompassTexture(); - CompassTexture(int iPad, CompassTexture *dataTexture); + CompassTexture(); + CompassTexture(int iPad, CompassTexture* dataTexture); - void cycleFrames(); - void updateFromPosition(Level *level, double x, double z, double yRot, bool noNeedle, bool instant); - - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual int getFrames(); - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + void cycleFrames(); + void updateFromPosition(Level* level, double x, double z, double yRot, + bool noNeedle, bool instant); + + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual int getFrames(); + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTexture.cpp b/Minecraft.Client/Textures/HttpTexture.cpp index 05ea7e8fb..f7a658f42 100644 --- a/Minecraft.Client/Textures/HttpTexture.cpp +++ b/Minecraft.Client/Textures/HttpTexture.cpp @@ -1,12 +1,12 @@ #include "../Platform/stdafx.h" #include "HttpTexture.h" -HttpTexture::HttpTexture(const std::wstring& _url, HttpTextureProcessor *processor) -{ - // 4J - added +HttpTexture::HttpTexture(const std::wstring& _url, + HttpTextureProcessor* processor) { + // 4J - added count = 1; id = -1; isLoaded = false; - // 4J - TODO - actually implement + // 4J - TODO - actually implement } \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTexture.h b/Minecraft.Client/Textures/HttpTexture.h index 3c87cd8f0..4737b13f0 100644 --- a/Minecraft.Client/Textures/HttpTexture.h +++ b/Minecraft.Client/Textures/HttpTexture.h @@ -2,13 +2,12 @@ class BufferedImage; class HttpTextureProcessor; - class HttpTexture { public: - BufferedImage *loadedImage; + BufferedImage* loadedImage; int count; int id; bool isLoaded; - HttpTexture(const std::wstring& _url, HttpTextureProcessor *processor); + HttpTexture(const std::wstring& _url, HttpTextureProcessor* processor); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTextureProcessor.h b/Minecraft.Client/Textures/HttpTextureProcessor.h index a585a0345..351c9f124 100644 --- a/Minecraft.Client/Textures/HttpTextureProcessor.h +++ b/Minecraft.Client/Textures/HttpTextureProcessor.h @@ -1,8 +1,7 @@ #pragma once class BufferedImage; -class HttpTextureProcessor -{ +class HttpTextureProcessor { public: - virtual BufferedImage *process(BufferedImage *read) = 0; + virtual BufferedImage* process(BufferedImage* read) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/MemTexture.cpp b/Minecraft.Client/Textures/MemTexture.cpp index e243a94ce..c6e337639 100644 --- a/Minecraft.Client/Textures/MemTexture.cpp +++ b/Minecraft.Client/Textures/MemTexture.cpp @@ -1,33 +1,26 @@ #include "../Platform/stdafx.h" #include "MemTexture.h" -MemTexture::MemTexture(const std::wstring& _url, std::uint8_t *pbData, std::uint32_t dataBytes, MemTextureProcessor *processor) -{ - // 4J - added +MemTexture::MemTexture(const std::wstring& _url, std::uint8_t* pbData, + std::uint32_t dataBytes, + MemTextureProcessor* processor) { + // 4J - added count = 1; id = -1; isLoaded = false; - ticksSinceLastUse = 0; + ticksSinceLastUse = 0; - // 4J - TODO - actually implement - - // load the texture, and process it - //loadedImage=Textures::getTexture() - // 4J - remember to add deletes in here for any created BufferedImages when implemented - loadedImage = new BufferedImage(pbData,dataBytes); - if(processor==NULL) - { - - } - else - { - //loadedImage=processor.process(ImageIO.read(huc.getInputStream())); - } - + // 4J - TODO - actually implement + // load the texture, and process it + // loadedImage=Textures::getTexture() + // 4J - remember to add deletes in here for any created BufferedImages when + // implemented + loadedImage = new BufferedImage(pbData, dataBytes); + if (processor == NULL) { + } else { + // loadedImage=processor.process(ImageIO.read(huc.getInputStream())); + } } -MemTexture::~MemTexture() -{ - delete loadedImage; -} +MemTexture::~MemTexture() { delete loadedImage; } diff --git a/Minecraft.Client/Textures/MemTexture.h b/Minecraft.Client/Textures/MemTexture.h index d8c9c4d1a..0cbbce319 100644 --- a/Minecraft.Client/Textures/MemTexture.h +++ b/Minecraft.Client/Textures/MemTexture.h @@ -3,16 +3,16 @@ class BufferedImage; class MemTextureProcessor; - class MemTexture { public: - BufferedImage *loadedImage; + BufferedImage* loadedImage; int count; int id; bool isLoaded; - int ticksSinceLastUse; - static const int UNUSED_TICKS_TO_FREE = 20; + int ticksSinceLastUse; + static const int UNUSED_TICKS_TO_FREE = 20; - MemTexture(const std::wstring& _name, std::uint8_t *pbData, std::uint32_t dataBytes, MemTextureProcessor *processor); - ~MemTexture(); + MemTexture(const std::wstring& _name, std::uint8_t* pbData, + std::uint32_t dataBytes, MemTextureProcessor* processor); + ~MemTexture(); }; diff --git a/Minecraft.Client/Textures/MemTextureProcessor.h b/Minecraft.Client/Textures/MemTextureProcessor.h index 56590d428..3d48cb8aa 100644 --- a/Minecraft.Client/Textures/MemTextureProcessor.h +++ b/Minecraft.Client/Textures/MemTextureProcessor.h @@ -1,9 +1,8 @@ #pragma once class BufferedImage; -class MemTextureProcessor -{ +class MemTextureProcessor { public: - virtual ~MemTextureProcessor(){} - virtual BufferedImage *process(BufferedImage *read) = 0; + virtual ~MemTextureProcessor() {} + virtual BufferedImage* process(BufferedImage* read) = 0; }; diff --git a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp index 73122d7ef..81e0d69d0 100644 --- a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp +++ b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp @@ -1,15 +1,15 @@ #include "../Platform/stdafx.h" #include "MobSkinMemTextureProcessor.h" -BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) -{ +BufferedImage* MobSkinMemTextureProcessor::process(BufferedImage* in) { if (in == NULL) return NULL; width = 64; height = 32; - BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); - Graphics *g = out->getGraphics(); + BufferedImage* out = + new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); + Graphics* g = out->getGraphics(); g->drawImage(in, 0, 0, NULL); g->dispose(); @@ -20,18 +20,16 @@ BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) setNoAlpha(0, 16, 64, 32); bool hasAlpha = false; for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } - // 4J-PB - looks like the code below is wrong, and really should be looping from 0 to <32 - if (!hasAlpha) - { + // 4J-PB - looks like the code below is wrong, and really should be looping + // from 0 to <32 + if (!hasAlpha) { for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } @@ -40,31 +38,25 @@ BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) return out; } -void MobSkinMemTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinMemTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) { if (hasAlpha(x0, y0, x1, y1)) return; for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] &= 0x00ffffff; } } -void MobSkinMemTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinMemTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] |= 0xff000000; } } -bool MobSkinMemTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) -{ +bool MobSkinMemTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { int pix = pixels[x + y * width]; if (((pix >> 24) & 0xff) < 128) return true; } diff --git a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h index a28f80a3d..6a06aaaad 100644 --- a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h +++ b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h @@ -1,16 +1,16 @@ #pragma once #include "MemTextureProcessor.h" -class MobSkinMemTextureProcessor : public MemTextureProcessor -{ +class MobSkinMemTextureProcessor : public MemTextureProcessor { private: - int *pixels; - int width, height; + int* pixels; + int width, height; + public: - virtual BufferedImage *process(BufferedImage *in); + virtual BufferedImage* process(BufferedImage* in); private: - void setForceAlpha(int x0, int y0, int x1, int y1); + void setForceAlpha(int x0, int y0, int x1, int y1); void setNoAlpha(int x0, int y0, int x1, int y1); bool hasAlpha(int x0, int y0, int x1, int y1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp b/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp index aea0f4b17..ee2962f70 100644 --- a/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp +++ b/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp @@ -1,15 +1,15 @@ #include "../Platform/stdafx.h" #include "MobSkinTextureProcessor.h" -BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) -{ +BufferedImage* MobSkinTextureProcessor::process(BufferedImage* in) { if (in == NULL) return NULL; width = 64; height = 32; - BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); - Graphics *g = out->getGraphics(); + BufferedImage* out = + new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); + Graphics* g = out->getGraphics(); g->drawImage(in, 0, 0, NULL); g->dispose(); @@ -20,17 +20,14 @@ BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) setNoAlpha(0, 16, 64, 32); bool hasAlpha = false; for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } - if (!hasAlpha) - { + if (!hasAlpha) { for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } @@ -39,31 +36,25 @@ BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) return out; } -void MobSkinTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) { if (hasAlpha(x0, y0, x1, y1)) return; for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] &= 0x00ffffff; } } -void MobSkinTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] |= 0xff000000; } } -bool MobSkinTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) -{ +bool MobSkinTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { int pix = pixels[x + y * width]; if (((pix >> 24) & 0xff) < 128) return true; } diff --git a/Minecraft.Client/Textures/MobSkinTextureProcessor.h b/Minecraft.Client/Textures/MobSkinTextureProcessor.h index ee51a8a3d..a4aba77f6 100644 --- a/Minecraft.Client/Textures/MobSkinTextureProcessor.h +++ b/Minecraft.Client/Textures/MobSkinTextureProcessor.h @@ -1,16 +1,16 @@ #pragma once #include "HttpTextureProcessor.h" -class MobSkinTextureProcessor : public HttpTextureProcessor -{ +class MobSkinTextureProcessor : public HttpTextureProcessor { private: - int *pixels; - int width, height; + int* pixels; + int width, height; + public: - virtual BufferedImage *process(BufferedImage *in); + virtual BufferedImage* process(BufferedImage* in); private: - void setForceAlpha(int x0, int y0, int x1, int y1); + void setForceAlpha(int x0, int y0, int x1, int y1); void setNoAlpha(int x0, int y0, int x1, int y1); bool hasAlpha(int x0, int y0, int x1, int y1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp b/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp index 8821e6068..c65a973cb 100644 --- a/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp @@ -6,71 +6,73 @@ #include -AbstractTexturePack::AbstractTexturePack(std::uint32_t id, File *file, const std::wstring &name, TexturePack *fallback) : id(id), name(name) -{ - // 4J init - textureId = -1; - m_colourTable = NULL; +AbstractTexturePack::AbstractTexturePack(std::uint32_t id, File* file, + const std::wstring& name, + TexturePack* fallback) + : id(id), name(name) { + // 4J init + textureId = -1; + m_colourTable = NULL; + this->file = file; + this->fallback = fallback; - this->file = file; - this->fallback = fallback; + m_iconData = NULL; + m_iconSize = 0; - m_iconData = NULL; - m_iconSize = 0; + m_comparisonData = NULL; + m_comparisonSize = 0; - m_comparisonData = NULL; - m_comparisonSize = 0; - - // 4J Stu - These calls need to be in the most derived version of the class - //loadIcon(); - //loadDescription(); + // 4J Stu - These calls need to be in the most derived version of the class + // loadIcon(); + // loadDescription(); } -std::wstring AbstractTexturePack::trim(std::wstring line) -{ - if (!line.empty() && line.length() > 34) - { - line = line.substr(0, 34); - } - return line; +std::wstring AbstractTexturePack::trim(std::wstring line) { + if (!line.empty() && line.length() > 34) { + line = line.substr(0, 34); + } + return line; } -void AbstractTexturePack::loadIcon() -{ +void AbstractTexturePack::loadIcon() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/Graphics/TexturePackIcon.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); - m_iconSize = static_cast(size); + unsigned int size = 0; + HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); + m_iconSize = static_cast(size); #endif } -void AbstractTexturePack::loadComparison() -{ +void AbstractTexturePack::loadComparison() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/DefaultPack_Comparison.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", + L"media/Graphics/DefaultPack_Comparison.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_comparisonData, &size); - m_comparisonSize = static_cast(size); + unsigned int size = 0; + HRESULT hr = + XuiResourceLoadAllNoLoc(szResourceLocator, &m_comparisonData, &size); + m_comparisonSize = static_cast(size); #endif } -void AbstractTexturePack::loadDescription() -{ - // 4J Unused currently +void AbstractTexturePack::loadDescription() { + // 4J Unused currently #if 0 InputStream *inputStream = NULL; BufferedReader *br = NULL; @@ -99,311 +101,286 @@ void AbstractTexturePack::loadDescription() #endif } -void AbstractTexturePack::loadName() -{ -} +void AbstractTexturePack::loadName() {} -InputStream *AbstractTexturePack::getResource(const std::wstring &name, bool allowFallback) //throws IOException +InputStream* AbstractTexturePack::getResource( + const std::wstring& name, bool allowFallback) // throws IOException { - app.DebugPrintf("texture - %ls\n",name.c_str()); - InputStream *is = getResourceImplementation(name); - if (is == NULL && fallback != NULL && allowFallback) - { - is = fallback->getResource(name, true); - } + app.DebugPrintf("texture - %ls\n", name.c_str()); + InputStream* is = getResourceImplementation(name); + if (is == NULL && fallback != NULL && allowFallback) { + is = fallback->getResource(name, true); + } - return is; + return is; } // 4J Currently removed due to override in TexturePack class -//InputStream *AbstractTexturePack::getResource(const std::wstring &name) //throws IOException +// InputStream *AbstractTexturePack::getResource(const std::wstring &name) +// //throws IOException //{ // return getResource(name, true); //} -void AbstractTexturePack::unload(Textures *textures) -{ - if (iconImage != NULL && textureId != -1) - { - textures->releaseTexture(textureId); - } +void AbstractTexturePack::unload(Textures* textures) { + if (iconImage != NULL && textureId != -1) { + textures->releaseTexture(textureId); + } } -void AbstractTexturePack::load(Textures *textures) -{ - if (iconImage != NULL) - { - if (textureId == -1) - { - textureId = textures->getTexture(iconImage); - } - glBindTexture(GL_TEXTURE_2D, textureId); - textures->clearLastBoundId(); - } - else - { - // 4J Stu - Don't do this - //textures->bindTexture(L"/gui/unknown_pack.png"); - } +void AbstractTexturePack::load(Textures* textures) { + if (iconImage != NULL) { + if (textureId == -1) { + textureId = textures->getTexture(iconImage); + } + glBindTexture(GL_TEXTURE_2D, textureId); + textures->clearLastBoundId(); + } else { + // 4J Stu - Don't do this + // textures->bindTexture(L"/gui/unknown_pack.png"); + } } -bool AbstractTexturePack::hasFile(const std::wstring &name, bool allowFallback) -{ - bool hasFile = this->hasFile(name); +bool AbstractTexturePack::hasFile(const std::wstring& name, + bool allowFallback) { + bool hasFile = this->hasFile(name); - return !hasFile && (allowFallback && fallback != NULL) ? fallback->hasFile(name, allowFallback) : hasFile; + return !hasFile && (allowFallback && fallback != NULL) + ? fallback->hasFile(name, allowFallback) + : hasFile; } -std::uint32_t AbstractTexturePack::getId() -{ - return id; +std::uint32_t AbstractTexturePack::getId() { return id; } + +std::wstring AbstractTexturePack::getName() { return texname; } + +std::wstring AbstractTexturePack::getWorldName() { return m_wsWorldName; } + +std::wstring AbstractTexturePack::getDesc1() { return desc1; } + +std::wstring AbstractTexturePack::getDesc2() { return desc2; } + +std::wstring AbstractTexturePack::getAnimationString( + const std::wstring& textureName, const std::wstring& path, + bool allowFallback) { + return getAnimationString(textureName, path); } -std::wstring AbstractTexturePack::getName() -{ - return texname; -} +std::wstring AbstractTexturePack::getAnimationString( + const std::wstring& textureName, const std::wstring& path) { + std::wstring animationDefinitionFile = textureName + L".txt"; -std::wstring AbstractTexturePack::getWorldName() -{ - return m_wsWorldName; -} + bool requiresFallback = !hasFile(L"\\" + textureName + L".png", false); -std::wstring AbstractTexturePack::getDesc1() -{ - return desc1; -} + InputStream* fileStream = + getResource(L"\\" + path + animationDefinitionFile, requiresFallback); -std::wstring AbstractTexturePack::getDesc2() -{ - return desc2; -} - -std::wstring AbstractTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback) -{ - return getAnimationString(textureName, path); -} - -std::wstring AbstractTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path) -{ - std::wstring animationDefinitionFile = textureName + L".txt"; - - bool requiresFallback = !hasFile(L"\\" + textureName + L".png", false); - - InputStream *fileStream = getResource(L"\\" + path + animationDefinitionFile, requiresFallback); - - //Minecraft::getInstance()->getLogger().info("Found animation info for: " + animationDefinitionFile); + // Minecraft::getInstance()->getLogger().info("Found animation info for: " + + // animationDefinitionFile); #ifndef _CONTENT_PACKAGE - wprintf(L"Found animation info for: %ls\n", animationDefinitionFile.c_str() ); + wprintf(L"Found animation info for: %ls\n", + animationDefinitionFile.c_str()); #endif - InputStreamReader isr(fileStream); - BufferedReader br(&isr); - - std::wstring result = L""; + InputStreamReader isr(fileStream); + BufferedReader br(&isr); - std::wstring line = br.readLine(); - while (!line.empty()) - { - line = trimString(line); - if (line.length() > 0) - { - result.append(L","); - result.append(line); - } - line = br.readLine(); - } - delete fileStream; + std::wstring result = L""; - return result; + std::wstring line = br.readLine(); + while (!line.empty()) { + line = trimString(line); + if (line.length() > 0) { + result.append(L","); + result.append(line); + } + line = br.readLine(); + } + delete fileStream; + + return result; } -BufferedImage *AbstractTexturePack::getImageResource(const std::wstring& File, bool filenameHasExtension /*= false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - const char *pchTexture=wstringtofilename(File); - app.DebugPrintf("AbstractTexturePack::getImageResource - %s, drive is %s\n",pchTexture, wstringtofilename(drive)); +BufferedImage* AbstractTexturePack::getImageResource( + const std::wstring& File, bool filenameHasExtension /*= false*/, + bool bTitleUpdateTexture /*=false*/, const std::wstring& drive /*=L""*/) { + const char* pchTexture = wstringtofilename(File); + app.DebugPrintf("AbstractTexturePack::getImageResource - %s, drive is %s\n", + pchTexture, wstringtofilename(drive)); - return new BufferedImage(TexturePack::getResource(L"/" + File),filenameHasExtension,bTitleUpdateTexture,drive); + return new BufferedImage(TexturePack::getResource(L"/" + File), + filenameHasExtension, bTitleUpdateTexture, drive); } -void AbstractTexturePack::loadDefaultUI() -{ +void AbstractTexturePack::loadDefaultUI() { #ifdef _XBOX - // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + // load from the .xzp file + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - // Load new skin - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/skin_Minecraft.xur"); - - XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/skin_Minecraft.xur"); + + XuiFreeVisuals(L""); + app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #else - ui.ReloadSkin(); + ui.ReloadSkin(); #endif } -void AbstractTexturePack::loadColourTable() -{ - loadDefaultColourTable(); - loadDefaultHTMLColourTable(); +void AbstractTexturePack::loadColourTable() { + loadDefaultColourTable(); + loadDefaultHTMLColourTable(); } -void AbstractTexturePack::loadDefaultColourTable() -{ - // Load the file - File coloursFile(AbstractTexturePack::getPath(true).append(L"res/colours.col")); +void AbstractTexturePack::loadDefaultColourTable() { + // Load the file + File coloursFile( + AbstractTexturePack::getPath(true).append(L"res/colours.col")); - if(coloursFile.exists()) - { - const __int64 colourTableLength = coloursFile.length(); - if(colourTableLength < 0 || colourTableLength > static_cast<__int64>(std::numeric_limits::max())) - { - app.DebugPrintf("Failed to load the default colours table\n"); - app.FatalLoadError(); - return; - } + if (coloursFile.exists()) { + const __int64 colourTableLength = coloursFile.length(); + if (colourTableLength < 0 || + colourTableLength > static_cast<__int64>( + std::numeric_limits::max())) { + app.DebugPrintf("Failed to load the default colours table\n"); + app.FatalLoadError(); + return; + } - const unsigned int dataLength = static_cast(colourTableLength); - byteArray data(dataLength); + const unsigned int dataLength = + static_cast(colourTableLength); + byteArray data(dataLength); - FileInputStream fis(coloursFile); - fis.read(data,0,dataLength); - fis.close(); - if(m_colourTable != NULL) delete m_colourTable; - m_colourTable = new ColourTable(data.data, dataLength); + FileInputStream fis(coloursFile); + fis.read(data, 0, dataLength); + fis.close(); + if (m_colourTable != NULL) delete m_colourTable; + m_colourTable = new ColourTable(data.data, dataLength); - delete [] data.data; - } - else - { - app.DebugPrintf("Failed to load the default colours table\n"); - app.FatalLoadError(); - } + delete[] data.data; + } else { + app.DebugPrintf("Failed to load the default colours table\n"); + app.FatalLoadError(); + } } -void AbstractTexturePack::loadDefaultHTMLColourTable() -{ +void AbstractTexturePack::loadDefaultHTMLColourTable() { #ifdef _XBOX - // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + // load from the .xzp file + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - // Try and load the HTMLColours.col based off the common XML first, before the deprecated xuiscene_colourtable - wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/HTMLColours.col"); - std::uint8_t *data; - unsigned int dataLength; - if(XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) - { - m_colourTable->loadColoursFromData(data,dataLength); + // Try and load the HTMLColours.col based off the common XML first, before + // the deprecated xuiscene_colourtable + wsprintfW(szResourceLocator, L"section://%X,%s#%s", c_ModuleHandle, + L"media", L"media/HTMLColours.col"); + std::uint8_t* data; + unsigned int dataLength; + if (XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) { + m_colourTable->loadColoursFromData(data, dataLength); - XuiFree(data); - } - else - { - wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); - HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,L"xuiscene_colourtable.xur", NULL, &hScene); + XuiFree(data); + } else { + wsprintfW(szResourceLocator, L"section://%X,%s#%s", c_ModuleHandle, + L"media", L"media/"); + HXUIOBJ hScene; + HRESULT hr = XuiSceneCreate(szResourceLocator, + L"xuiscene_colourtable.xur", NULL, &hScene); - if(HRESULT_SUCCEEDED(hr)) - { - loadHTMLColourTableFromXuiScene(hScene); - } - } + if (HRESULT_SUCCEEDED(hr)) { + loadHTMLColourTableFromXuiScene(hScene); + } + } #else - if(app.hasArchiveFile(L"HTMLColours.col")) - { - byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); - m_colourTable->loadColoursFromData(textColours.data,textColours.length); + if (app.hasArchiveFile(L"HTMLColours.col")) { + byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); + m_colourTable->loadColoursFromData(textColours.data, + textColours.length); - delete [] textColours.data; - } + delete[] textColours.data; + } #endif } #ifdef _XBOX -void AbstractTexturePack::loadHTMLColourTableFromXuiScene(HXUIOBJ hObj) -{ - HXUIOBJ child; - HRESULT hr = XuiElementGetFirstChild(hObj, &child); +void AbstractTexturePack::loadHTMLColourTableFromXuiScene(HXUIOBJ hObj) { + HXUIOBJ child; + HRESULT hr = XuiElementGetFirstChild(hObj, &child); - while(HRESULT_SUCCEEDED(hr) && child != NULL) - { - LPCWSTR childName; - XuiElementGetId(child,&childName); - m_colourTable->setColour(childName,XuiTextElementGetText(child)); + while (HRESULT_SUCCEEDED(hr) && child != NULL) { + LPCWSTR childName; + XuiElementGetId(child, &childName); + m_colourTable->setColour(childName, XuiTextElementGetText(child)); - //eMinecraftTextColours colourIndex = eTextColor_NONE; - //for(int i = 0; i < (int)eTextColor_MAX; i++) - //{ - // if(wcscmp(HTMLColourTableElements[i],childName)==0) - // { - // colourIndex = (eMinecraftTextColours)i; - // break; - // } - //} + // eMinecraftTextColours colourIndex = eTextColor_NONE; + // for(int i = 0; i < (int)eTextColor_MAX; i++) + //{ + // if(wcscmp(HTMLColourTableElements[i],childName)==0) + // { + // colourIndex = (eMinecraftTextColours)i; + // break; + // } + // } - //LPCWSTR stringValue = XuiTextElementGetText(child); + // LPCWSTR stringValue = XuiTextElementGetText(child); - //m_htmlColourTable[colourIndex] = XuiTextElementGetText(child); + // m_htmlColourTable[colourIndex] = XuiTextElementGetText(child); - hr = XuiElementGetNext(child, &child); - } + hr = XuiElementGetNext(child, &child); + } } #endif -void AbstractTexturePack::loadUI() -{ - loadColourTable(); - +void AbstractTexturePack::loadUI() { + loadColourTable(); + #ifdef _XBOX - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif } -void AbstractTexturePack::unloadUI() -{ - // Do nothing +void AbstractTexturePack::unloadUI() { + // Do nothing } -std::wstring AbstractTexturePack::getXuiRootPath() -{ - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); +std::wstring AbstractTexturePack::getXuiRootPath() { + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - // Load new skin - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); - return szResourceLocator; + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/"); + return szResourceLocator; } -std::uint8_t *AbstractTexturePack::getPackIcon(std::uint32_t &imageBytes) -{ - if(m_iconSize == 0 || m_iconData == NULL) loadIcon(); - imageBytes = m_iconSize; - return m_iconData; +std::uint8_t* AbstractTexturePack::getPackIcon(std::uint32_t& imageBytes) { + if (m_iconSize == 0 || m_iconData == NULL) loadIcon(); + imageBytes = m_iconSize; + return m_iconData; } -std::uint8_t *AbstractTexturePack::getPackComparison(std::uint32_t &imageBytes) -{ - if(m_comparisonSize == 0 || m_comparisonData == NULL) loadComparison(); +std::uint8_t* AbstractTexturePack::getPackComparison( + std::uint32_t& imageBytes) { + if (m_comparisonSize == 0 || m_comparisonData == NULL) loadComparison(); - imageBytes = m_comparisonSize; - return m_comparisonData; + imageBytes = m_comparisonSize; + return m_comparisonData; } -unsigned int AbstractTexturePack::getDLCParentPackId() -{ - return 0; -} +unsigned int AbstractTexturePack::getDLCParentPackId() { return 0; } -unsigned char AbstractTexturePack::getDLCSubPackId() -{ - return 0; -} +unsigned char AbstractTexturePack::getDLCSubPackId() { return 0; } diff --git a/Minecraft.Client/Textures/Packs/AbstractTexturePack.h b/Minecraft.Client/Textures/Packs/AbstractTexturePack.h index d9cbd8222..b633ff31b 100644 --- a/Minecraft.Client/Textures/Packs/AbstractTexturePack.h +++ b/Minecraft.Client/Textures/Packs/AbstractTexturePack.h @@ -1,93 +1,100 @@ #pragma once - #include "TexturePack.h" class BufferedImage; -class AbstractTexturePack : public TexturePack -{ +class AbstractTexturePack : public TexturePack { private: - const std::uint32_t id; - const std::wstring name; + const std::uint32_t id; + const std::wstring name; protected: - File *file; - std::wstring texname; - std::wstring m_wsWorldName; + File* file; + std::wstring texname; + std::wstring m_wsWorldName; - std::wstring desc1; - std::wstring desc2; + std::wstring desc1; + std::wstring desc2; - std::uint8_t *m_iconData; - std::uint32_t m_iconSize; + std::uint8_t* m_iconData; + std::uint32_t m_iconSize; - std::uint8_t *m_comparisonData; - std::uint32_t m_comparisonSize; + std::uint8_t* m_comparisonData; + std::uint32_t m_comparisonSize; - TexturePack *fallback; + TexturePack* fallback; - ColourTable *m_colourTable; + ColourTable* m_colourTable; protected: - BufferedImage *iconImage; + BufferedImage* iconImage; private: - int textureId; + int textureId; protected: - AbstractTexturePack(std::uint32_t id, File *file, const std::wstring &name, TexturePack *fallback); + AbstractTexturePack(std::uint32_t id, File* file, const std::wstring& name, + TexturePack* fallback); private: - static std::wstring trim(std::wstring line); - + static std::wstring trim(std::wstring line); + protected: - virtual void loadIcon(); - virtual void loadComparison(); - virtual void loadDescription(); - virtual void loadName(); + virtual void loadIcon(); + virtual void loadComparison(); + virtual void loadDescription(); + virtual void loadName(); public: - virtual InputStream *getResource(const std::wstring &name, bool allowFallback); //throws IOException - // 4J Removed do to current override in TexturePack class - //virtual InputStream *getResource(const std::wstring &name); //throws IOException - virtual DLCPack * getDLCPack() =0; - + virtual InputStream* getResource(const std::wstring& name, + bool allowFallback); // throws IOException + // 4J Removed do to current override in TexturePack class + // virtual InputStream *getResource(const std::wstring &name); //throws + // IOException + virtual DLCPack* getDLCPack() = 0; protected: - virtual InputStream *getResourceImplementation(const std::wstring &name) = 0; // throws IOException; + virtual InputStream* getResourceImplementation( + const std::wstring& name) = 0; // throws IOException; public: - virtual void unload(Textures *textures); - virtual void load(Textures *textures); - virtual bool hasFile(const std::wstring &name, bool allowFallback); - virtual bool hasFile(const std::wstring &name) = 0; - virtual std::uint32_t getId(); - virtual std::wstring getName(); - virtual std::wstring getDesc1(); - virtual std::wstring getDesc2(); - virtual std::wstring getWorldName(); - - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback); + virtual void unload(Textures* textures); + virtual void load(Textures* textures); + virtual bool hasFile(const std::wstring& name, bool allowFallback); + virtual bool hasFile(const std::wstring& name) = 0; + virtual std::uint32_t getId(); + virtual std::wstring getName(); + virtual std::wstring getDesc1(); + virtual std::wstring getDesc2(); + virtual std::wstring getWorldName(); + + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path, + bool allowFallback); protected: - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path); - void loadDefaultUI(); - void loadDefaultColourTable(); - void loadDefaultHTMLColourTable(); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path); + void loadDefaultUI(); + void loadDefaultColourTable(); + void loadDefaultHTMLColourTable(); #ifdef _XBOX - void loadHTMLColourTableFromXuiScene(HXUIOBJ hObj); + void loadHTMLColourTableFromXuiScene(HXUIOBJ hObj); #endif public: - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); - virtual void loadColourTable(); - virtual void loadUI(); - virtual void unloadUI(); - virtual std::wstring getXuiRootPath(); - virtual std::uint8_t *getPackIcon(std::uint32_t &imageBytes); - virtual std::uint8_t *getPackComparison(std::uint32_t &imageBytes); - virtual unsigned int getDLCParentPackId(); - virtual unsigned char getDLCSubPackId(); - virtual ColourTable *getColourTable() { return m_colourTable; } - virtual ArchiveFile *getArchiveFile() { return NULL; } + virtual BufferedImage* getImageResource(const std::wstring& File, + bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); + virtual void loadColourTable(); + virtual void loadUI(); + virtual void unloadUI(); + virtual std::wstring getXuiRootPath(); + virtual std::uint8_t* getPackIcon(std::uint32_t& imageBytes); + virtual std::uint8_t* getPackComparison(std::uint32_t& imageBytes); + virtual unsigned int getDLCParentPackId(); + virtual unsigned char getDLCSubPackId(); + virtual ColourTable* getColourTable() { return m_colourTable; } + virtual ArchiveFile* getArchiveFile() { return NULL; } }; diff --git a/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp b/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp index 4d56cf46e..4c58b82a0 100644 --- a/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp @@ -20,567 +20,580 @@ #include "../../Platform/Xbox/XML/xmlFilesCallback.h" #endif -namespace -{ - bool ReadPortableBinaryFile(File &file, std::uint8_t *&data, unsigned int &size) - { - const __int64 fileLength = file.length(); - if (fileLength < 0 || fileLength > static_cast<__int64>(std::numeric_limits::max())) - { - data = NULL; - size = 0; - return false; - } +namespace { +bool ReadPortableBinaryFile(File& file, std::uint8_t*& data, + unsigned int& size) { + const __int64 fileLength = file.length(); + if (fileLength < 0 || + fileLength > + static_cast<__int64>(std::numeric_limits::max())) { + data = NULL; + size = 0; + return false; + } - const std::size_t capacity = static_cast(fileLength); - std::uint8_t *buffer = new std::uint8_t[capacity == 0 ? 1 : capacity]; - const PortableFileIO::BinaryReadResult readResult = PortableFileIO::ReadBinaryFile(file.getPath(), buffer, capacity); - if (readResult.status != PortableFileIO::BinaryReadStatus::ok - || readResult.fileSize > std::numeric_limits::max()) - { - delete [] buffer; - data = NULL; - size = 0; - return false; - } + const std::size_t capacity = static_cast(fileLength); + std::uint8_t* buffer = new std::uint8_t[capacity == 0 ? 1 : capacity]; + const PortableFileIO::BinaryReadResult readResult = + PortableFileIO::ReadBinaryFile(file.getPath(), buffer, capacity); + if (readResult.status != PortableFileIO::BinaryReadStatus::ok || + readResult.fileSize > std::numeric_limits::max()) { + delete[] buffer; + data = NULL; + size = 0; + return false; + } - data = buffer; - size = static_cast(readResult.fileSize); - return true; - } + data = buffer; + size = static_cast(readResult.fileSize); + return true; } +} // namespace -DLCTexturePack::DLCTexturePack(std::uint32_t id, DLCPack *pack, TexturePack *fallback) : AbstractTexturePack(id, NULL, pack->getName(), fallback) -{ - m_dlcInfoPack = pack; - m_dlcDataPack = NULL; - bUILoaded = false; - m_bLoadingData = false; - m_bHasLoadedData = false; - m_archiveFile = NULL; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - m_bUsingDefaultColourTable = true; +DLCTexturePack::DLCTexturePack(std::uint32_t id, DLCPack* pack, + TexturePack* fallback) + : AbstractTexturePack(id, NULL, pack->getName(), fallback) { + m_dlcInfoPack = pack; + m_dlcDataPack = NULL; + bUILoaded = false; + m_bLoadingData = false; + m_bHasLoadedData = false; + m_archiveFile = NULL; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + m_bUsingDefaultColourTable = true; - m_stringTable = NULL; + m_stringTable = NULL; #ifdef _XBOX - m_pStreamedWaveBank=NULL; - m_pSoundBank=NULL; + m_pStreamedWaveBank = NULL; + m_pSoundBank = NULL; #endif - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")) - { - DLCLocalisationFile *localisationFile = (DLCLocalisationFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc"); - m_stringTable = localisationFile->getStringTable(); - } + if (m_dlcInfoPack->doesPackContainFile( + DLCManager::e_DLCType_LocalisationData, L"languages.loc")) { + DLCLocalisationFile* localisationFile = + (DLCLocalisationFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_LocalisationData, L"languages.loc"); + m_stringTable = localisationFile->getStringTable(); + } - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); - //loadDefaultHTMLColourTable(); + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); + // loadDefaultHTMLColourTable(); } -void DLCTexturePack::loadIcon() -{ - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"icon.png")) - { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"icon.png"); - std::uint32_t iconSize = 0; - m_iconData = textureFile->getData(iconSize); - m_iconSize = iconSize; - } - else - { - AbstractTexturePack::loadIcon(); - } +void DLCTexturePack::loadIcon() { + if (m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, + L"icon.png")) { + DLCTextureFile* textureFile = (DLCTextureFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_Texture, L"icon.png"); + std::uint32_t iconSize = 0; + m_iconData = textureFile->getData(iconSize); + m_iconSize = iconSize; + } else { + AbstractTexturePack::loadIcon(); + } } -void DLCTexturePack::loadComparison() -{ - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"comparison.png")) - { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"comparison.png"); - std::uint32_t comparisonSize = 0; - m_comparisonData = textureFile->getData(comparisonSize); - m_comparisonSize = comparisonSize; - } +void DLCTexturePack::loadComparison() { + if (m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, + L"comparison.png")) { + DLCTextureFile* textureFile = (DLCTextureFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_Texture, L"comparison.png"); + std::uint32_t comparisonSize = 0; + m_comparisonData = textureFile->getData(comparisonSize); + m_comparisonSize = comparisonSize; + } } -void DLCTexturePack::loadName() -{ - texname = L""; - - if(m_dlcInfoPack->GetPackID()&1024) - { - if(m_stringTable != NULL) - { - texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); - m_wsWorldName=m_stringTable->getString(L"IDS_WORLD_NAME"); - } - } - else - { - if(m_stringTable != NULL) - { - texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); - } - } +void DLCTexturePack::loadName() { + texname = L""; + if (m_dlcInfoPack->GetPackID() & 1024) { + if (m_stringTable != NULL) { + texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); + m_wsWorldName = m_stringTable->getString(L"IDS_WORLD_NAME"); + } + } else { + if (m_stringTable != NULL) { + texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); + } + } } -void DLCTexturePack::loadDescription() -{ - desc1 = L""; +void DLCTexturePack::loadDescription() { + desc1 = L""; - if(m_stringTable != NULL) - { - desc1 = m_stringTable->getString(L"IDS_TP_DESCRIPTION"); - } + if (m_stringTable != NULL) { + desc1 = m_stringTable->getString(L"IDS_TP_DESCRIPTION"); + } } -std::wstring DLCTexturePack::getResource(const std::wstring& name) -{ - // 4J Stu - We should never call this function +std::wstring DLCTexturePack::getResource(const std::wstring& name) { + // 4J Stu - We should never call this function #ifndef __CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - return L""; + return L""; } -InputStream *DLCTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* DLCTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { - // 4J Stu - We should never call this function + // 4J Stu - We should never call this function #ifndef _CONTENT_PACKAGE - __debugbreak(); - if(hasFile(name)) return NULL; + __debugbreak(); + if (hasFile(name)) return NULL; #endif - return NULL; //resource; + return NULL; // resource; } -bool DLCTexturePack::hasFile(const std::wstring &name) -{ - bool hasFile = false; - if(m_dlcDataPack != NULL) hasFile = m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_Texture, name); - return hasFile; +bool DLCTexturePack::hasFile(const std::wstring& name) { + bool hasFile = false; + if (m_dlcDataPack != NULL) + hasFile = m_dlcDataPack->doesPackContainFile( + DLCManager::e_DLCType_Texture, name); + return hasFile; } -bool DLCTexturePack::isTerrainUpdateCompatible() -{ - return true; +bool DLCTexturePack::isTerrainUpdateCompatible() { return true; } + +std::wstring DLCTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + return L""; } -std::wstring DLCTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - return L""; +std::wstring DLCTexturePack::getAnimationString(const std::wstring& textureName, + const std::wstring& path) { + std::wstring result = L""; + + std::wstring fullpath = L"res/" + path + textureName + L".png"; + if (hasFile(fullpath)) { + result = m_dlcDataPack->getFile(DLCManager::e_DLCType_Texture, fullpath) + ->getParameterAsString(DLCManager::e_DLCParamType_Anim); + } + + return result; } -std::wstring DLCTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path) -{ - std::wstring result = L""; - - std::wstring fullpath = L"res/" + path + textureName + L".png"; - if(hasFile(fullpath)) - { - result = m_dlcDataPack->getFile(DLCManager::e_DLCType_Texture, fullpath)->getParameterAsString(DLCManager::e_DLCParamType_Anim); - } - - return result; +BufferedImage* DLCTexturePack::getImageResource( + const std::wstring& File, bool filenameHasExtension /*= false*/, + bool bTitleUpdateTexture /*=false*/, const std::wstring& drive /*=L""*/) { + if (m_dlcDataPack) + return new BufferedImage(m_dlcDataPack, L"/" + File, + filenameHasExtension); + else + return fallback->getImageResource(File, filenameHasExtension, + bTitleUpdateTexture, drive); } -BufferedImage *DLCTexturePack::getImageResource(const std::wstring& File, bool filenameHasExtension /*= false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - if(m_dlcDataPack) return new BufferedImage(m_dlcDataPack, L"/" + File, filenameHasExtension); - else return fallback->getImageResource(File, filenameHasExtension, bTitleUpdateTexture, drive); -} +DLCPack* DLCTexturePack::getDLCPack() { return m_dlcDataPack; } -DLCPack * DLCTexturePack::getDLCPack() -{ - return m_dlcDataPack; -} +void DLCTexturePack::loadColourTable() { + // Load the game colours + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, + L"colours.col")) { + DLCColourTableFile* colourFile = + (DLCColourTableFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_ColourTable, L"colours.col"); + m_colourTable = colourFile->getColourTable(); + m_bUsingDefaultColourTable = false; + } else { + // 4J Stu - We can delete the default colour table, but not the one from + // the DLCColourTableFile + if (!m_bUsingDefaultColourTable) m_colourTable = NULL; + loadDefaultColourTable(); + m_bUsingDefaultColourTable = true; + } -void DLCTexturePack::loadColourTable() -{ - // Load the game colours - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, L"colours.col")) - { - DLCColourTableFile *colourFile = (DLCColourTableFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_ColourTable, L"colours.col"); - m_colourTable = colourFile->getColourTable(); - m_bUsingDefaultColourTable = false; - } - else - { - // 4J Stu - We can delete the default colour table, but not the one from the DLCColourTableFile - if(!m_bUsingDefaultColourTable) m_colourTable = NULL; - loadDefaultColourTable(); - m_bUsingDefaultColourTable = true; - } - - // Load the text colours + // Load the text colours #ifdef _XBOX - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - - // Try and load the HTMLColours.col based off the common XML first, before the deprecated xuiscene_colourtable - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#HTMLColours.col",pbData, dwSize); - std::uint8_t *data; - unsigned int dataLength; - if(XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) - { - m_colourTable->loadColoursFromData(data,dataLength); + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - XuiFree(data); - } - else - { + // Try and load the HTMLColours.col based off the common XML first, + // before the deprecated xuiscene_colourtable + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#HTMLColours.col", pbData, dwSize); + std::uint8_t* data; + unsigned int dataLength; + if (XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) { + m_colourTable->loadColoursFromData(data, dataLength); - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#xuiscene_colourtable.xur",pbData, dwSize); - HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,szResourceLocator, NULL, &hScene); + XuiFree(data); + } else { + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#xuiscene_colourtable.xur", pbData, + dwSize); + HXUIOBJ hScene; + HRESULT hr = XuiSceneCreate(szResourceLocator, szResourceLocator, + NULL, &hScene); - if(HRESULT_SUCCEEDED(hr)) - { - loadHTMLColourTableFromXuiScene(hScene); - } - else - { - loadDefaultHTMLColourTable(); - } - } - } - else - { - loadDefaultHTMLColourTable(); - } + if (HRESULT_SUCCEEDED(hr)) { + loadHTMLColourTableFromXuiScene(hScene); + } else { + loadDefaultHTMLColourTable(); + } + } + } else { + loadDefaultHTMLColourTable(); + } #else - if(app.hasArchiveFile(L"HTMLColours.col")) - { - byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); - m_colourTable->loadColoursFromData(textColours.data,textColours.length); + if (app.hasArchiveFile(L"HTMLColours.col")) { + byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); + m_colourTable->loadColoursFromData(textColours.data, + textColours.length); - delete [] textColours.data; - } + delete[] textColours.data; + } #endif } -void DLCTexturePack::loadData() -{ - int mountIndex = m_dlcInfoPack->GetDLCMountIndex(); +void DLCTexturePack::loadData() { + int mountIndex = m_dlcInfoPack->GetDLCMountIndex(); - if(mountIndex > -1) - { + if (mountIndex > -1) { #ifdef _DURANGO - if(StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(),mountIndex,&DLCTexturePack::packMounted,this,L"TPACK")!=ERROR_IO_PENDING) + if (StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(), + mountIndex, + &DLCTexturePack::packMounted, this, + L"TPACK") != ERROR_IO_PENDING) #else - if(StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(),mountIndex,&DLCTexturePack::packMounted,this,"TPACK")!=ERROR_IO_PENDING) + if (StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(), + mountIndex, + &DLCTexturePack::packMounted, this, + "TPACK") != ERROR_IO_PENDING) #endif - { - // corrupt DLC - m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.DebugPrintf("Failed to mount texture pack DLC %d for pad %d\n",mountIndex,ProfileManager.GetPrimaryPad()); - } - else - { - m_bLoadingData = true; - app.DebugPrintf("Attempted to mount DLC data for texture pack %d\n", mountIndex); - } - } - else - { - m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } + { + // corrupt DLC + m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.DebugPrintf("Failed to mount texture pack DLC %d for pad %d\n", + mountIndex, ProfileManager.GetPrimaryPad()); + } else { + m_bLoadingData = true; + app.DebugPrintf("Attempted to mount DLC data for texture pack %d\n", + mountIndex); + } + } else { + m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } } - - - - -std::wstring DLCTexturePack::getFilePath(std::uint32_t packId, std::wstring filename, bool bAddDataFolder) -{ - return app.getFilePath(packId,filename,bAddDataFolder); +std::wstring DLCTexturePack::getFilePath(std::uint32_t packId, + std::wstring filename, + bool bAddDataFolder) { + return app.getFilePath(packId, filename, bAddDataFolder); } -int DLCTexturePack::packMounted(void *pParam,int iPad,std::uint32_t dwErr,std::uint32_t dwLicenceMask) -{ - DLCTexturePack *texturePack = static_cast(pParam); - texturePack->m_bLoadingData = false; - if(dwErr!=ERROR_SUCCESS) - { - // corrupt DLC - app.DebugPrintf("Failed to mount DLC for pad %d: %u\n",iPad,dwErr); - } - else - { - app.DebugPrintf("Mounted DLC for texture pack, attempting to load data\n"); - texturePack->m_dlcDataPack = new DLCPack(texturePack->m_dlcInfoPack->getName(), dwLicenceMask); - texturePack->setHasAudio(false); - unsigned int dwFilesProcessed = 0; - // Load the DLC textures - std::wstring dataFilePath = texturePack->m_dlcInfoPack->getFullDataPath(); - if(!dataFilePath.empty()) - { - if(!app.m_dlcManager.readDLCDataFile(dwFilesProcessed, getFilePath(texturePack->m_dlcInfoPack->GetPackID(), dataFilePath),texturePack->m_dlcDataPack)) - { - delete texturePack->m_dlcDataPack; - texturePack->m_dlcDataPack = NULL; - } +int DLCTexturePack::packMounted(void* pParam, int iPad, std::uint32_t dwErr, + std::uint32_t dwLicenceMask) { + DLCTexturePack* texturePack = static_cast(pParam); + texturePack->m_bLoadingData = false; + if (dwErr != ERROR_SUCCESS) { + // corrupt DLC + app.DebugPrintf("Failed to mount DLC for pad %d: %u\n", iPad, dwErr); + } else { + app.DebugPrintf( + "Mounted DLC for texture pack, attempting to load data\n"); + texturePack->m_dlcDataPack = + new DLCPack(texturePack->m_dlcInfoPack->getName(), dwLicenceMask); + texturePack->setHasAudio(false); + unsigned int dwFilesProcessed = 0; + // Load the DLC textures + std::wstring dataFilePath = + texturePack->m_dlcInfoPack->getFullDataPath(); + if (!dataFilePath.empty()) { + if (!app.m_dlcManager.readDLCDataFile( + dwFilesProcessed, + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + dataFilePath), + texturePack->m_dlcDataPack)) { + delete texturePack->m_dlcDataPack; + texturePack->m_dlcDataPack = NULL; + } - // Load the UI data - if(texturePack->m_dlcDataPack != NULL) - { + // Load the UI data + if (texturePack->m_dlcDataPack != NULL) { #ifdef _XBOX - File xzpPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"TexturePack.xzp") ) ); + File xzpPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"TexturePack.xzp"))); - if(xzpPath.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int bytesRead = 0; - if( ReadPortableBinaryFile(xzpPath, pbData, bytesRead) ) - { - DLCUIDataFile *uiDLCFile = (DLCUIDataFile *)texturePack->m_dlcDataPack->addFile(DLCManager::e_DLCType_UIData,L"TexturePack.xzp"); - uiDLCFile->addData(pbData,bytesRead,true); - } - } + if (xzpPath.exists()) { + std::uint8_t* pbData = NULL; + unsigned int bytesRead = 0; + if (ReadPortableBinaryFile(xzpPath, pbData, bytesRead)) { + DLCUIDataFile* uiDLCFile = + (DLCUIDataFile*)texturePack->m_dlcDataPack->addFile( + DLCManager::e_DLCType_UIData, + L"TexturePack.xzp"); + uiDLCFile->addData(pbData, bytesRead, true); + } + } #else - File archivePath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"media.arc") ) ); - if(archivePath.exists()) texturePack->m_archiveFile = new ArchiveFile(archivePath); + File archivePath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"media.arc"))); + if (archivePath.exists()) + texturePack->m_archiveFile = new ArchiveFile(archivePath); #endif - /** - 4J-JEV: - For all the GameRuleHeader files we find - */ - DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if (levelGen != NULL && !levelGen->hasLoadedData()) - { - int gameRulesCount = pack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader); - for(int i = 0; i < gameRulesCount; ++i) - { - DLCGameRulesHeader *dlcFile = (DLCGameRulesHeader *) pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i); - - if (!dlcFile->getGrfPath().empty()) - { - File grf( getFilePath(texturePack->m_dlcInfoPack->GetPackID(), dlcFile->getGrfPath() ) ); - if (grf.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int fileSize = 0; - if( ReadPortableBinaryFile(grf, pbData, fileSize) ) - { - // 4J-PB - is it possible that we can get here after a read fail and it's not an error? - dlcFile->setGrfData(pbData, fileSize, texturePack->m_stringTable); + /** + 4J-JEV: + For all the GameRuleHeader files we find + */ + DLCPack* pack = texturePack->m_dlcInfoPack->GetParentPack(); + LevelGenerationOptions* levelGen = + app.getLevelGenerationOptions(); + if (levelGen != NULL && !levelGen->hasLoadedData()) { + int gameRulesCount = pack->getDLCItemsCount( + DLCManager::e_DLCType_GameRulesHeader); + for (int i = 0; i < gameRulesCount; ++i) { + DLCGameRulesHeader* dlcFile = + (DLCGameRulesHeader*)pack->getFile( + DLCManager::e_DLCType_GameRulesHeader, i); - delete [] pbData; + if (!dlcFile->getGrfPath().empty()) { + File grf(getFilePath( + texturePack->m_dlcInfoPack->GetPackID(), + dlcFile->getGrfPath())); + if (grf.exists()) { + std::uint8_t* pbData = NULL; + unsigned int fileSize = 0; + if (ReadPortableBinaryFile(grf, pbData, + fileSize)) { + // 4J-PB - is it possible that we can get + // here after a read fail and it's not an + // error? + dlcFile->setGrfData( + pbData, fileSize, + texturePack->m_stringTable); - app.m_gameRules.setLevelGenerationOptions( dlcFile->lgo ); - } - else - { - app.FatalLoadError(); - } - } - } - } - if(levelGen->requiresBaseSave() && !levelGen->getBaseSavePath().empty() ) - { - File grf(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), levelGen->getBaseSavePath() )); - if (grf.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int fileSize = 0; - if( ReadPortableBinaryFile(grf, pbData, fileSize) ) - { - // 4J-PB - is it possible that we can get here after a read fail and it's not an error? - levelGen->setBaseSaveData(pbData, fileSize); - } - else - { - app.FatalLoadError(); - } - } - } - } - + delete[] pbData; - // any audio data? -#ifdef _XBOX - File audioXSBPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"MashUp.xsb") ) ); - File audioXWBPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"MashUp.xwb") ) ); - - if(audioXSBPath.exists() && audioXWBPath.exists()) - { + app.m_gameRules.setLevelGenerationOptions( + dlcFile->lgo); + } else { + app.FatalLoadError(); + } + } + } + } + if (levelGen->requiresBaseSave() && + !levelGen->getBaseSavePath().empty()) { + File grf( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + levelGen->getBaseSavePath())); + if (grf.exists()) { + std::uint8_t* pbData = NULL; + unsigned int fileSize = 0; + if (ReadPortableBinaryFile(grf, pbData, fileSize)) { + // 4J-PB - is it possible that we can get here + // after a read fail and it's not an error? + levelGen->setBaseSaveData(pbData, fileSize); + } else { + app.FatalLoadError(); + } + } + } + } - texturePack->setHasAudio(true); - const char *pchXWBFilename=wstringtofilename(audioXWBPath.getPath()); - Minecraft::GetInstance()->soundEngine->CreateStreamingWavebank(pchXWBFilename,&texturePack->m_pStreamedWaveBank); - const char *pchXSBFilename=wstringtofilename(audioXSBPath.getPath()); - Minecraft::GetInstance()->soundEngine->CreateSoundbank(pchXSBFilename,&texturePack->m_pSoundBank); - - } -#else - //DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); - if(pack->getDLCItemsCount(DLCManager::e_DLCType_Audio)>0) - { - DLCAudioFile *dlcFile = (DLCAudioFile *) pack->getFile(DLCManager::e_DLCType_Audio, 0); - texturePack->setHasAudio(true); - // init the streaming sound ids for this texture pack - int iOverworldStart, iNetherStart, iEndStart; - int iOverworldC, iNetherC, iEndC; - - iOverworldStart=0; - iOverworldC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_Overworld); - iNetherStart=iOverworldC; - iNetherC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_Nether); - iEndStart=iOverworldC+iNetherC; - iEndC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_End); - - Minecraft::GetInstance()->soundEngine->SetStreamingSounds(iOverworldStart,iOverworldStart+iOverworldC, - iNetherStart,iNetherStart+iNetherC,iEndStart,iEndStart+iEndC,iEndStart+iEndC); // push the CD start to after - } -#endif -} - texturePack->loadColourTable(); - } - - // 4J-PB - we need to leave the texture pack mounted if it contained streaming audio - if(texturePack->hasAudio()==false) - { + // any audio data? #ifdef _XBOX - StorageManager.UnmountInstalledDLC("TPACK"); -#endif - } - } - - texturePack->m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); + File audioXSBPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"MashUp.xsb"))); + File audioXWBPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"MashUp.xwb"))); - return 0; -} - -void DLCTexturePack::loadUI() -{ -#ifdef _XBOX -//Syntax: "memory://" + Address + "," + Size + "#" + File -//L"memory://0123ABCD,21A3#skin_default.xur" - - // Load new skin - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); - - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#skin_Minecraft.xur",pbData, dwSize); - - XuiFreeVisuals(L""); - - - HRESULT hr = app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - if(HRESULT_SUCCEEDED(hr)) - { - bUILoaded = true; - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - //CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); - } - } + if (audioXSBPath.exists() && audioXWBPath.exists()) { + texturePack->setHasAudio(true); + const char* pchXWBFilename = + wstringtofilename(audioXWBPath.getPath()); + Minecraft::GetInstance() + ->soundEngine->CreateStreamingWavebank( + pchXWBFilename, &texturePack->m_pStreamedWaveBank); + const char* pchXSBFilename = + wstringtofilename(audioXSBPath.getPath()); + Minecraft::GetInstance()->soundEngine->CreateSoundbank( + pchXSBFilename, &texturePack->m_pSoundBank); + } #else - if(m_archiveFile && m_archiveFile->hasFile(L"skin.swf")) - { - ui.ReloadSkin(); - bUILoaded = true; - } -#endif - else - { - loadDefaultUI(); - bUILoaded = true; - } + // DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); + if (pack->getDLCItemsCount(DLCManager::e_DLCType_Audio) > 0) { + DLCAudioFile* dlcFile = (DLCAudioFile*)pack->getFile( + DLCManager::e_DLCType_Audio, 0); + texturePack->setHasAudio(true); + // init the streaming sound ids for this texture pack + int iOverworldStart, iNetherStart, iEndStart; + int iOverworldC, iNetherC, iEndC; - AbstractTexturePack::loadUI(); + iOverworldStart = 0; + iOverworldC = dlcFile->GetCountofType( + DLCAudioFile::e_AudioType_Overworld); + iNetherStart = iOverworldC; + iNetherC = dlcFile->GetCountofType( + DLCAudioFile::e_AudioType_Nether); + iEndStart = iOverworldC + iNetherC; + iEndC = + dlcFile->GetCountofType(DLCAudioFile::e_AudioType_End); + + Minecraft::GetInstance()->soundEngine->SetStreamingSounds( + iOverworldStart, iOverworldStart + iOverworldC, + iNetherStart, iNetherStart + iNetherC, iEndStart, + iEndStart + iEndC, + iEndStart + iEndC); // push the CD start to after + } +#endif + } + texturePack->loadColourTable(); + } + + // 4J-PB - we need to leave the texture pack mounted if it contained + // streaming audio + if (texturePack->hasAudio() == false) { +#ifdef _XBOX + StorageManager.UnmountInstalledDLC("TPACK"); +#endif + } + } + + texturePack->m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); + + return 0; +} + +void DLCTexturePack::loadUI() { +#ifdef _XBOX + // Syntax: "memory://" + Address + "," + Size + "#" + File + // L"memory://0123ABCD,21A3#skin_default.xur" + + // Load new skin + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); + + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); + + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#skin_Minecraft.xur", pbData, dwSize); + + XuiFreeVisuals(L""); + + HRESULT hr = app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + if (HRESULT_SUCCEEDED(hr)) { + bUILoaded = true; + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + // CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + } + } +#else + if (m_archiveFile && m_archiveFile->hasFile(L"skin.swf")) { + ui.ReloadSkin(); + bUILoaded = true; + } +#endif + else { + loadDefaultUI(); + bUILoaded = true; + } + + AbstractTexturePack::loadUI(); #ifndef _XBOX - if(hasAudio()==false && !ui.IsReloadingSkin()) - { + if (hasAudio() == false && !ui.IsReloadingSkin()) { #ifdef _DURANGO - StorageManager.UnmountInstalledDLC(L"TPACK"); + StorageManager.UnmountInstalledDLC(L"TPACK"); #else - StorageManager.UnmountInstalledDLC("TPACK"); + StorageManager.UnmountInstalledDLC("TPACK"); #endif - } + } #endif } -void DLCTexturePack::unloadUI() -{ - // Unload skin - if(bUILoaded) - { +void DLCTexturePack::unloadUI() { + // Unload skin + if (bUILoaded) { #ifdef _XBOX - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif - setHasAudio(false); - } - AbstractTexturePack::unloadUI(); + setHasAudio(false); + } + AbstractTexturePack::unloadUI(); - app.m_dlcManager.removePack(m_dlcDataPack); - m_dlcDataPack = NULL; - delete m_archiveFile; - m_bHasLoadedData = false; + app.m_dlcManager.removePack(m_dlcDataPack); + m_dlcDataPack = NULL; + delete m_archiveFile; + m_bHasLoadedData = false; - bUILoaded = false; + bUILoaded = false; } -std::wstring DLCTexturePack::getXuiRootPath() -{ - std::wstring path = L""; - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); +std::wstring DLCTexturePack::getXuiRootPath() { + std::wstring path = L""; + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#",pbData, dwSize); - path = szResourceLocator; - } - return path; + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; + swprintf(szResourceLocator, LOCATOR_SIZE, L"memory://%08X,%04X#", + pbData, dwSize); + path = szResourceLocator; + } + return path; } -unsigned int DLCTexturePack::getDLCParentPackId() -{ - return m_dlcInfoPack->GetParentPackId(); +unsigned int DLCTexturePack::getDLCParentPackId() { + return m_dlcInfoPack->GetParentPackId(); } -unsigned char DLCTexturePack::getDLCSubPackId() -{ - return (m_dlcInfoPack->GetPackId()>>24)&0xFF; +unsigned char DLCTexturePack::getDLCSubPackId() { + return (m_dlcInfoPack->GetPackId() >> 24) & 0xFF; } -DLCPack * DLCTexturePack::getDLCInfoParentPack() -{ - return m_dlcInfoPack->GetParentPack(); +DLCPack* DLCTexturePack::getDLCInfoParentPack() { + return m_dlcInfoPack->GetParentPack(); } -XCONTENTDEVICEID DLCTexturePack::GetDLCDeviceID() -{ - return m_dlcInfoPack->GetDLCDeviceID(); +XCONTENTDEVICEID DLCTexturePack::GetDLCDeviceID() { + return m_dlcInfoPack->GetDLCDeviceID(); } diff --git a/Minecraft.Client/Textures/Packs/DLCTexturePack.h b/Minecraft.Client/Textures/Packs/DLCTexturePack.h index 39ca39e27..1d2c7acde 100644 --- a/Minecraft.Client/Textures/Packs/DLCTexturePack.h +++ b/Minecraft.Client/Textures/Packs/DLCTexturePack.h @@ -5,68 +5,73 @@ class DLCPack; class StringTable; -class DLCTexturePack : public AbstractTexturePack -{ +class DLCTexturePack : public AbstractTexturePack { private: - DLCPack *m_dlcInfoPack; // Description, icon etc - DLCPack *m_dlcDataPack; // Actual textures - StringTable *m_stringTable; - bool bUILoaded; - bool m_bLoadingData, m_bHasLoadedData; - bool m_bUsingDefaultColourTable; - //bool m_bHasAudio; - ArchiveFile *m_archiveFile; - - + DLCPack* m_dlcInfoPack; // Description, icon etc + DLCPack* m_dlcDataPack; // Actual textures + StringTable* m_stringTable; + bool bUILoaded; + bool m_bLoadingData, m_bHasLoadedData; + bool m_bUsingDefaultColourTable; + // bool m_bHasAudio; + ArchiveFile* m_archiveFile; public: - using AbstractTexturePack::getResource; + using AbstractTexturePack::getResource; - DLCTexturePack(std::uint32_t id, DLCPack *pack, TexturePack *fallback); - ~DLCTexturePack(){}; + DLCTexturePack(std::uint32_t id, DLCPack* pack, TexturePack* fallback); + ~DLCTexturePack() {}; - virtual std::wstring getResource(const std::wstring& name); - virtual DLCPack * getDLCPack(); - // Added for sound banks with MashUp packs + virtual std::wstring getResource(const std::wstring& name); + virtual DLCPack* getDLCPack(); + // Added for sound banks with MashUp packs #ifdef _XBOX - IXACT3WaveBank *m_pStreamedWaveBank; - IXACT3SoundBank *m_pSoundBank; + IXACT3WaveBank* m_pStreamedWaveBank; + IXACT3SoundBank* m_pSoundBank; #endif protected: - //@Override - void loadIcon(); - void loadComparison(); - void loadName(); - void loadDescription(); - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + //@Override + void loadIcon(); + void loadComparison(); + void loadName(); + void loadDescription(); + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path); - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); - virtual void loadColourTable(); - virtual bool hasData() { return m_bHasLoadedData; } - virtual bool isLoadingData() { return m_bLoadingData; } + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path); + virtual BufferedImage* getImageResource(const std::wstring& File, + bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); + virtual void loadColourTable(); + virtual bool hasData() { return m_bHasLoadedData; } + virtual bool isLoadingData() { return m_bLoadingData; } private: - static std::wstring getRootPath(std::uint32_t packId, bool allowOverride, bool bAddDataFolder); - static std::wstring getFilePath(std::uint32_t packId, std::wstring filename, bool bAddDataFolder=true); + static std::wstring getRootPath(std::uint32_t packId, bool allowOverride, + bool bAddDataFolder); + static std::wstring getFilePath(std::uint32_t packId, std::wstring filename, + bool bAddDataFolder = true); public: - static int packMounted(void *pParam,int iPad,std::uint32_t dwErr,std::uint32_t dwLicenceMask); - virtual void loadData(); - virtual void loadUI(); - virtual void unloadUI(); - virtual std::wstring getXuiRootPath(); - virtual ArchiveFile *getArchiveFile() { return m_archiveFile; } + static int packMounted(void* pParam, int iPad, std::uint32_t dwErr, + std::uint32_t dwLicenceMask); + virtual void loadData(); + virtual void loadUI(); + virtual void unloadUI(); + virtual std::wstring getXuiRootPath(); + virtual ArchiveFile* getArchiveFile() { return m_archiveFile; } - virtual unsigned int getDLCParentPackId(); - virtual DLCPack *getDLCInfoParentPack(); - virtual unsigned char getDLCSubPackId(); - XCONTENTDEVICEID GetDLCDeviceID(); + virtual unsigned int getDLCParentPackId(); + virtual DLCPack* getDLCInfoParentPack(); + virtual unsigned char getDLCSubPackId(); + XCONTENTDEVICEID GetDLCDeviceID(); }; diff --git a/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp b/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp index a6e59d471..e1a92faef 100644 --- a/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp @@ -3,129 +3,122 @@ #include "../Textures.h" #include "../../../Minecraft.World/Util/StringHelpers.h" - -DefaultTexturePack::DefaultTexturePack() : AbstractTexturePack(0, NULL, L"Minecraft", NULL) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); // 4J-PB - added so the PS3 can have localised texture names' - loadDescription(); - loadColourTable(); +DefaultTexturePack::DefaultTexturePack() + : AbstractTexturePack(0, NULL, L"Minecraft", NULL) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); // 4J-PB - added so the PS3 can have localised texture names' + loadDescription(); + loadColourTable(); } -void DefaultTexturePack::loadIcon() -{ +void DefaultTexturePack::loadIcon() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/Graphics/TexturePackIcon.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); - m_iconSize = size; + unsigned int size = 0; + HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); + m_iconSize = size; #else - if(app.hasArchiveFile(L"Graphics\\TexturePackIcon.png")) - { - byteArray ba = app.getArchiveFile(L"Graphics\\TexturePackIcon.png"); - m_iconData = ba.data; - m_iconSize = static_cast(ba.length); - } + if (app.hasArchiveFile(L"Graphics\\TexturePackIcon.png")) { + byteArray ba = app.getArchiveFile(L"Graphics\\TexturePackIcon.png"); + m_iconData = ba.data; + m_iconSize = static_cast(ba.length); + } #endif } -void DefaultTexturePack::loadDescription() -{ - desc1 = L"LOCALISE ME: The default look of Minecraft"; +void DefaultTexturePack::loadDescription() { + desc1 = L"LOCALISE ME: The default look of Minecraft"; } -void DefaultTexturePack::loadName() -{ - texname = L"Minecraft"; +void DefaultTexturePack::loadName() { texname = L"Minecraft"; } + +bool DefaultTexturePack::hasFile(const std::wstring& name) { + // return DefaultTexturePack::class->getResourceAsStream(name) != null; + return true; } -bool DefaultTexturePack::hasFile(const std::wstring &name) -{ -// return DefaultTexturePack::class->getResourceAsStream(name) != null; - return true; -} +bool DefaultTexturePack::isTerrainUpdateCompatible() { return true; } -bool DefaultTexturePack::isTerrainUpdateCompatible() +InputStream* DefaultTexturePack::getResourceImplementation( + const std::wstring& name) // throws FileNotFoundException { - return true; -} - -InputStream *DefaultTexturePack::getResourceImplementation(const std::wstring &name)// throws FileNotFoundException -{ - std::wstring wDrive = L""; - // Make the content package point to to the UPDATE: drive is needed + std::wstring wDrive = L""; + // Make the content package point to to the UPDATE: drive is needed #ifdef _XBOX - #ifdef _TU_BUILD - wDrive=L"UPDATE:\\res"; - #else - - wDrive=L"GAME:\\res\\TitleUpdate\\res"; - #endif +#ifdef _TU_BUILD + wDrive = L"UPDATE:\\res"; +#else + + wDrive = L"GAME:\\res\\TitleUpdate\\res"; +#endif #elif __PS3__ - char *pchUsrDir; - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(name); - pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - app.DebugPrintf("DefaultTexturePack::getResourceImplementation - texture %s - Drive - %s\n",pchTextureName,pchUsrDir); - } - else - { - const char *pchTextureName=wstringtofilename(name); - pchUsrDir=getUsrDirPath(); - app.DebugPrintf("DefaultTexturePack::getResourceImplementation - texture %s - Drive - %s\n",pchTextureName,pchUsrDir); - } + char* pchUsrDir; + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(name); + pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + app.DebugPrintf( + "DefaultTexturePack::getResourceImplementation - texture %s - " + "Drive - %s\n", + pchTextureName, pchUsrDir); + } else { + const char* pchTextureName = wstringtofilename(name); + pchUsrDir = getUsrDirPath(); + app.DebugPrintf( + "DefaultTexturePack::getResourceImplementation - texture %s - " + "Drive - %s\n", + pchTextureName, pchUsrDir); + } + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - - wDrive = wstr + L"\\Common\\res\\TitleUpdate\\res"; + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\res"; #elif __PSVITA__ - /* - char *pchUsrDir=getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - - wDrive = wstr + L"Common\\res\\TitleUpdate\\res"; - */ - wDrive = L"Common\\res\\TitleUpdate\\res"; + /* + char *pchUsrDir=getUsrDirPath(); + std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + + wDrive = wstr + L"Common\\res\\TitleUpdate\\res"; + */ + wDrive = L"Common\\res\\TitleUpdate\\res"; #else - wDrive = L"Common\\res\\TitleUpdate\\res"; + wDrive = L"Common\\res\\TitleUpdate\\res"; #endif - InputStream *resource = InputStream::getResourceAsStream(wDrive + name); - //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) - //{ - // throw new FileNotFoundException(name); - //} + InputStream* resource = InputStream::getResourceAsStream(wDrive + name); + // InputStream *stream = + // DefaultTexturePack::class->getResourceAsStream(name); if (stream == NULL) + //{ + // throw new FileNotFoundException(name); + // } - //return stream; - return resource; + // return stream; + return resource; } -void DefaultTexturePack::loadUI() -{ - loadDefaultUI(); +void DefaultTexturePack::loadUI() { + loadDefaultUI(); - AbstractTexturePack::loadUI(); + AbstractTexturePack::loadUI(); } -void DefaultTexturePack::unloadUI() -{ +void DefaultTexturePack::unloadUI() { #ifdef _XBOX - // Unload skin - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + // Unload skin + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif - AbstractTexturePack::unloadUI(); + AbstractTexturePack::unloadUI(); } diff --git a/Minecraft.Client/Textures/Packs/DefaultTexturePack.h b/Minecraft.Client/Textures/Packs/DefaultTexturePack.h index 1b46f22f3..a3f5f9efb 100644 --- a/Minecraft.Client/Textures/Packs/DefaultTexturePack.h +++ b/Minecraft.Client/Textures/Packs/DefaultTexturePack.h @@ -1,33 +1,33 @@ #pragma once #include "AbstractTexturePack.h" -class DefaultTexturePack : public AbstractTexturePack -{ +class DefaultTexturePack : public AbstractTexturePack { public: - DefaultTexturePack(); - DLCPack * getDLCPack() {return NULL;} + DefaultTexturePack(); + DLCPack* getDLCPack() { return NULL; } protected: - //@Override - void loadIcon(); - void loadName(); - void loadDescription(); + //@Override + void loadIcon(); + void loadName(); + void loadDescription(); public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - std::wstring getDesc1() {return app.GetString(IDS_DEFAULT_TEXTUREPACK);} + std::wstring getDesc1() { return app.GetString(IDS_DEFAULT_TEXTUREPACK); } protected: - //@Override - InputStream *getResourceImplementation(const std::wstring &name); // throws FileNotFoundException + //@Override + InputStream* getResourceImplementation( + const std::wstring& name); // throws FileNotFoundException public: - virtual bool hasData() { return true; } - virtual bool hasAudio() { return false; } - virtual bool isLoadingData() { return false; } - virtual void loadUI(); - virtual void unloadUI(); + virtual bool hasData() { return true; } + virtual bool hasAudio() { return false; } + virtual bool isLoadingData() { return false; } + virtual void loadUI(); + virtual void unloadUI(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Packs/FileTexturePack.cpp b/Minecraft.Client/Textures/Packs/FileTexturePack.cpp index c70b462d6..5d0dee1b8 100644 --- a/Minecraft.Client/Textures/Packs/FileTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/FileTexturePack.cpp @@ -1,16 +1,16 @@ #include "../../Platform/stdafx.h" #include "FileTexturePack.h" -FileTexturePack::FileTexturePack(std::uint32_t id, File *file, TexturePack *fallback) : AbstractTexturePack(id, file, file->getName(), fallback) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); +FileTexturePack::FileTexturePack(std::uint32_t id, File* file, + TexturePack* fallback) + : AbstractTexturePack(id, file, file->getName(), fallback) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); } -void FileTexturePack::unload(Textures *textures) -{ +void FileTexturePack::unload(Textures* textures) { #if 0 super.unload(textures); @@ -24,7 +24,8 @@ void FileTexturePack::unload(Textures *textures) #endif } -InputStream *FileTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* FileTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { #if 0 loadZipFile(); @@ -36,11 +37,10 @@ InputStream *FileTexturePack::getResourceImplementation(const std::wstring &name return zipFile.getInputStream(entry); #endif - return NULL; + return NULL; } -bool FileTexturePack::hasFile(const std::wstring &name) -{ +bool FileTexturePack::hasFile(const std::wstring& name) { #if 0 try { loadZipFile(); @@ -50,10 +50,10 @@ bool FileTexturePack::hasFile(const std::wstring &name) return false; } #endif - return false; + return false; } -void FileTexturePack::loadZipFile() //throws IOException +void FileTexturePack::loadZipFile() // throws IOException { #if 0 if (zipFile != null) { @@ -64,8 +64,7 @@ void FileTexturePack::loadZipFile() //throws IOException #endif } -bool FileTexturePack::isTerrainUpdateCompatible() -{ +bool FileTexturePack::isTerrainUpdateCompatible() { #if 0 try { loadZipFile(); @@ -82,5 +81,5 @@ bool FileTexturePack::isTerrainUpdateCompatible() boolean hasOldFiles = hasFile("terrain.png") || hasFile("gui/items.png"); return !hasOldFiles; #endif - return false; + return false; } diff --git a/Minecraft.Client/Textures/Packs/FileTexturePack.h b/Minecraft.Client/Textures/Packs/FileTexturePack.h index 3643d6f74..6db1ca759 100644 --- a/Minecraft.Client/Textures/Packs/FileTexturePack.h +++ b/Minecraft.Client/Textures/Packs/FileTexturePack.h @@ -1,32 +1,31 @@ #pragma once #include "AbstractTexturePack.h" -//class ZipFile; +// class ZipFile; class BufferedImage; class File; class Textures; - -class FileTexturePack : public AbstractTexturePack -{ +class FileTexturePack : public AbstractTexturePack { private: - //ZipFile *zipFile; + // ZipFile *zipFile; public: - FileTexturePack(std::uint32_t id, File *file, TexturePack *fallback); + FileTexturePack(std::uint32_t id, File* file, TexturePack* fallback); - //@Override - void unload(Textures *textures); + //@Override + void unload(Textures* textures); protected: - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); + //@Override + bool hasFile(const std::wstring& name); private: - void loadZipFile(); //throws IOException + void loadZipFile(); // throws IOException public: - bool isTerrainUpdateCompatible(); + bool isTerrainUpdateCompatible(); }; diff --git a/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp b/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp index 2365d08cb..8ca9267d9 100644 --- a/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp @@ -1,17 +1,19 @@ #include "../../Platform/stdafx.h" #include "FolderTexturePack.h" -FolderTexturePack::FolderTexturePack(std::uint32_t id, const std::wstring &name, File *folder, TexturePack *fallback) : AbstractTexturePack(id, folder, name, fallback) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); +FolderTexturePack::FolderTexturePack(std::uint32_t id, const std::wstring& name, + File* folder, TexturePack* fallback) + : AbstractTexturePack(id, folder, name, fallback) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); - bUILoaded = false; + bUILoaded = false; } -InputStream *FolderTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* FolderTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { #if 0 final File file = new File(this.file, name.substring(1)); @@ -22,89 +24,86 @@ InputStream *FolderTexturePack::getResourceImplementation(const std::wstring &na return new BufferedInputStream(new FileInputStream(file)); #endif - std::wstring wDrive = L""; - // Make the content package point to to the UPDATE: drive is needed + std::wstring wDrive = L""; + // Make the content package point to to the UPDATE: drive is needed #ifdef _XBOX - wDrive=L"GAME:\\DummyTexturePack\\res"; + wDrive = L"GAME:\\DummyTexturePack\\res"; #else - wDrive = L"Common\\DummyTexturePack\\res"; + wDrive = L"Common\\DummyTexturePack\\res"; #endif - InputStream *resource = InputStream::getResourceAsStream(wDrive + name); - //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) - //{ - // throw new FileNotFoundException(name); - //} + InputStream* resource = InputStream::getResourceAsStream(wDrive + name); + // InputStream *stream = + // DefaultTexturePack::class->getResourceAsStream(name); if (stream == NULL) + //{ + // throw new FileNotFoundException(name); + // } - //return stream; - return resource; + // return stream; + return resource; } -bool FolderTexturePack::hasFile(const std::wstring &name) -{ - File file = File( getPath() + name); - return file.exists() && file.isFile(); - //return true; +bool FolderTexturePack::hasFile(const std::wstring& name) { + File file = File(getPath() + name); + return file.exists() && file.isFile(); + // return true; } -bool FolderTexturePack::isTerrainUpdateCompatible() -{ +bool FolderTexturePack::isTerrainUpdateCompatible() { #if 0 final File dir = new File(this.file, "textures/"); final boolean hasTexturesFolder = dir.exists() && dir.isDirectory(); final boolean hasOldFiles = hasFile("terrain.png") || hasFile("gui/items.png"); return hasTexturesFolder || !hasOldFiles; #endif - return true; + return true; } -std::wstring FolderTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - std::wstring wDrive; +std::wstring FolderTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + std::wstring wDrive; #ifdef _XBOX - wDrive=L"GAME:\\" + file->getPath() + L"\\"; + wDrive = L"GAME:\\" + file->getPath() + L"\\"; #else - wDrive=L"Common\\" + file->getPath() + L"\\"; + wDrive = L"Common\\" + file->getPath() + L"\\"; #endif - return wDrive; + return wDrive; } -void FolderTexturePack::loadUI() -{ +void FolderTexturePack::loadUI() { #ifdef _XBOX - //"file://" + Drive + PathToXZP + "#" + PathInsideXZP + //"file://" + Drive + PathToXZP + "#" + PathInsideXZP - //L"file://game:/ui.xzp#skin_default.xur" + // L"file://game:/ui.xzp#skin_default.xur" - // Load new skin - if(hasFile(L"TexturePack.xzp")) - { - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + if (hasFile(L"TexturePack.xzp")) { + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"file://%lsTexturePack.xzp#skin_Minecraft.xur",getPath().c_str()); + swprintf(szResourceLocator, LOCATOR_SIZE, + L"file://%lsTexturePack.xzp#skin_Minecraft.xur", + getPath().c_str()); - XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - bUILoaded = true; - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - } + XuiFreeVisuals(L""); + app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + bUILoaded = true; + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + } - AbstractTexturePack::loadUI(); + AbstractTexturePack::loadUI(); #endif } -void FolderTexturePack::unloadUI() -{ +void FolderTexturePack::unloadUI() { #ifdef _XBOX - // Unload skin - if(bUILoaded) - { - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); - } - AbstractTexturePack::unloadUI(); + // Unload skin + if (bUILoaded) { + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); + } + AbstractTexturePack::unloadUI(); #endif } diff --git a/Minecraft.Client/Textures/Packs/FolderTexturePack.h b/Minecraft.Client/Textures/Packs/FolderTexturePack.h index 3cd30859e..24105b1a1 100644 --- a/Minecraft.Client/Textures/Packs/FolderTexturePack.h +++ b/Minecraft.Client/Textures/Packs/FolderTexturePack.h @@ -2,25 +2,26 @@ #include "AbstractTexturePack.h" -class FolderTexturePack : public AbstractTexturePack -{ +class FolderTexturePack : public AbstractTexturePack { private: - bool bUILoaded; + bool bUILoaded; public: - FolderTexturePack(std::uint32_t id, const std::wstring &name, File *folder, TexturePack *fallback); + FolderTexturePack(std::uint32_t id, const std::wstring& name, File* folder, + TexturePack* fallback); protected: - //@Override - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + //@Override + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual void loadUI(); - virtual void unloadUI(); + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual void loadUI(); + virtual void unloadUI(); }; diff --git a/Minecraft.Client/Textures/Packs/TexturePack.cpp b/Minecraft.Client/Textures/Packs/TexturePack.cpp index cd9a0adf8..eeccc03f3 100644 --- a/Minecraft.Client/Textures/Packs/TexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/TexturePack.cpp @@ -1,70 +1,57 @@ #include "../../Platform/stdafx.h" #include "TexturePack.h" -std::wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - std::wstring wDrive; +std::wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + std::wstring wDrive; #ifdef _XBOX - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed #ifdef _TU_BUILD - wDrive=L"UPDATE:\\"; + wDrive = L"UPDATE:\\"; #else - wDrive=L"GAME:\\res\\TitleUpdate\\"; + wDrive = L"GAME:\\res\\TitleUpdate\\"; #endif - } - else - { - wDrive=L"GAME:\\"; - } + } else { + wDrive = L"GAME:\\"; + } #else #ifdef __PS3__ - // 4J-PB - we need to check for a BD patch - this is going to be an issue for full DLC texture packs (Halloween) + // 4J-PB - we need to check for a BD patch - this is going to be an issue + // for full DLC texture packs (Halloween) - char *pchUsrDir=getUsrDirPath(); - - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + char* pchUsrDir = getUsrDirPath(); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - } + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"/Common/"; + } #elif __PSVITA__ - char *pchUsrDir="";//getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + char* pchUsrDir = ""; // getUsrDirPath(); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"Common\\"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"Common\\"; + } #else - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive=L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive=L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #endif #endif - return wDrive; + return wDrive; } diff --git a/Minecraft.Client/Textures/Packs/TexturePack.h b/Minecraft.Client/Textures/Packs/TexturePack.h index 621c3d458..cbd7f649b 100644 --- a/Minecraft.Client/Textures/Packs/TexturePack.h +++ b/Minecraft.Client/Textures/Packs/TexturePack.h @@ -8,54 +8,59 @@ class InputStream; class Minecraft; class ArchiveFile; -class TexturePack -{ +class TexturePack { public: - - TexturePack() { m_bHasAudio=false;} - virtual ~TexturePack(){} - virtual bool hasData() = 0; - virtual bool hasAudio() { return m_bHasAudio;} - virtual void setHasAudio(bool bVal) {m_bHasAudio=bVal;} - virtual bool isLoadingData() = 0; - virtual void loadData() {} - virtual void unload(Textures *textures) = 0; - virtual void load(Textures *textures) = 0; - virtual InputStream *getResource(const std::wstring &name, bool allowFallback) = 0;// throws IOException; - //virtual InputStream *getResource(const std::wstring &name) = 0;// throws IOException; + TexturePack() { m_bHasAudio = false; } + virtual ~TexturePack() {} + virtual bool hasData() = 0; + virtual bool hasAudio() { return m_bHasAudio; } + virtual void setHasAudio(bool bVal) { m_bHasAudio = bVal; } + virtual bool isLoadingData() = 0; + virtual void loadData() {} + virtual void unload(Textures* textures) = 0; + virtual void load(Textures* textures) = 0; + virtual InputStream* getResource( + const std::wstring& name, + bool allowFallback) = 0; // throws IOException; + // virtual InputStream *getResource(const std::wstring &name) = 0;// throws + // IOException; virtual std::uint32_t getId() = 0; virtual std::wstring getName() = 0; virtual std::wstring getDesc1() = 0; virtual std::wstring getDesc2() = 0; - virtual bool hasFile(const std::wstring &name, bool allowFallback) = 0; + virtual bool hasFile(const std::wstring& name, bool allowFallback) = 0; virtual bool isTerrainUpdateCompatible() = 0; - virtual std::wstring getResource(const std::wstring& name) // 4J - changed to just return a name rather than an input stream - { - /* 4J - TODO - return TexturePack.class.getResourceAsStream(name); - */ - return name; + virtual std::wstring getResource( + const std::wstring& name) // 4J - changed to just return a name rather + // than an input stream + { + /* 4J - TODO +return TexturePack.class.getResourceAsStream(name); + */ + return name; } - virtual DLCPack * getDLCPack() { return NULL;} + virtual DLCPack* getDLCPack() { return NULL; } - - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback) = 0; - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L"") = 0; - virtual void loadColourTable() = 0; - virtual void loadUI() = 0; - virtual void unloadUI() = 0; - virtual std::wstring getXuiRootPath() = 0; - virtual std::uint8_t *getPackIcon(std::uint32_t &imageBytes) = 0; - virtual std::uint8_t *getPackComparison(std::uint32_t &imageBytes) = 0; - virtual unsigned int getDLCParentPackId() = 0; - virtual unsigned char getDLCSubPackId() = 0; - virtual ColourTable *getColourTable() = 0; - virtual ArchiveFile *getArchiveFile() = 0; + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path, + bool allowFallback) = 0; + virtual BufferedImage* getImageResource( + const std::wstring& File, bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, const std::wstring& drive = L"") = 0; + virtual void loadColourTable() = 0; + virtual void loadUI() = 0; + virtual void unloadUI() = 0; + virtual std::wstring getXuiRootPath() = 0; + virtual std::uint8_t* getPackIcon(std::uint32_t& imageBytes) = 0; + virtual std::uint8_t* getPackComparison(std::uint32_t& imageBytes) = 0; + virtual unsigned int getDLCParentPackId() = 0; + virtual unsigned char getDLCSubPackId() = 0; + virtual ColourTable* getColourTable() = 0; + virtual ArchiveFile* getArchiveFile() = 0; private: - bool m_bHasAudio; - + bool m_bHasAudio; }; diff --git a/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp b/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp index 9eccc3ff6..892e025d2 100644 --- a/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp +++ b/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp @@ -9,77 +9,76 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "../../Rendering/Minimap.h" -TexturePack *TexturePackRepository::DEFAULT_TEXTURE_PACK = NULL; +TexturePack* TexturePackRepository::DEFAULT_TEXTURE_PACK = NULL; -TexturePackRepository::TexturePackRepository(File workingDirectory, Minecraft *minecraft) -{ - if(!DEFAULT_TEXTURE_PACK) DEFAULT_TEXTURE_PACK = new DefaultTexturePack(); +TexturePackRepository::TexturePackRepository(File workingDirectory, + Minecraft* minecraft) { + if (!DEFAULT_TEXTURE_PACK) DEFAULT_TEXTURE_PACK = new DefaultTexturePack(); - // 4J - added - usingWeb = false; - selected = NULL; - texturePacks = new std::vector; + // 4J - added + usingWeb = false; + selected = NULL; + texturePacks = new std::vector; this->minecraft = minecraft; - texturePacks->push_back(DEFAULT_TEXTURE_PACK); - cacheById[DEFAULT_TEXTURE_PACK->getId()] = DEFAULT_TEXTURE_PACK; + texturePacks->push_back(DEFAULT_TEXTURE_PACK); + cacheById[DEFAULT_TEXTURE_PACK->getId()] = DEFAULT_TEXTURE_PACK; selected = DEFAULT_TEXTURE_PACK; - DEFAULT_TEXTURE_PACK->loadColourTable(); + DEFAULT_TEXTURE_PACK->loadColourTable(); - m_dummyTexturePack = NULL; - m_dummyDLCTexturePack = NULL; - lastSelected = NULL; + m_dummyTexturePack = NULL; + m_dummyDLCTexturePack = NULL; + lastSelected = NULL; updateList(); } -void TexturePackRepository::addDebugPacks() -{ +void TexturePackRepository::addDebugPacks() { #ifndef _CONTENT_PACKAGE - //File *file = new File(L"DummyTexturePack"); // Path to the test texture pack - //m_dummyTexturePack = new FolderTexturePack(FOLDER_TEST_TEXTURE_PACK_ID, L"FolderTestPack", file, DEFAULT_TEXTURE_PACK); - //texturePacks->push_back(m_dummyTexturePack); - //cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; + // File *file = new File(L"DummyTexturePack"); // Path to the test texture + // pack m_dummyTexturePack = new + // FolderTexturePack(FOLDER_TEST_TEXTURE_PACK_ID, L"FolderTestPack", file, + // DEFAULT_TEXTURE_PACK); texturePacks->push_back(m_dummyTexturePack); + // cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; #ifdef _XBOX - File packedTestFile(L"GAME:\\DummyTexturePack\\TexturePack.pck"); - if(packedTestFile.exists()) - { - DLCPack *pack = app.m_dlcManager.getPack(L"DLCTestPack"); + File packedTestFile(L"GAME:\\DummyTexturePack\\TexturePack.pck"); + if (packedTestFile.exists()) { + DLCPack* pack = app.m_dlcManager.getPack(L"DLCTestPack"); - if( pack != NULL && pack->IsCorrupt() ) - { - app.m_dlcManager.removePack(pack); - pack = NULL; - } + if (pack != NULL && pack->IsCorrupt()) { + app.m_dlcManager.removePack(pack); + pack = NULL; + } - if(pack == NULL) - { - wprintf(L"Pack \"%ls\" is not installed, so adding it\n", L"DLCTestPack"); - pack = new DLCPack(L"DLCTestPack",0xffffffff); - unsigned int dwFilesProcessed = 0; - if( app.m_dlcManager.readDLCDataFile(dwFilesProcessed, "GAME:\\DummyTexturePack\\TexturePack.pck",pack)) - { - // 4J Stu - Don't need to do this, as the readDLCDataFile now adds texture packs - //m_dummyDLCTexturePack = addTexturePackFromDLC(pack, DLC_TEST_TEXTURE_PACK_ID); //new DLCTexturePack(0xFFFFFFFE, L"DLCTestPack", pack, DEFAULT_TEXTURE_PACK); - app.m_dlcManager.addPack(pack); - } - else - { - delete pack; - } - } - } + if (pack == NULL) { + wprintf(L"Pack \"%ls\" is not installed, so adding it\n", + L"DLCTestPack"); + pack = new DLCPack(L"DLCTestPack", 0xffffffff); + unsigned int dwFilesProcessed = 0; + if (app.m_dlcManager.readDLCDataFile( + dwFilesProcessed, + "GAME:\\DummyTexturePack\\TexturePack.pck", pack)) { + // 4J Stu - Don't need to do this, as the readDLCDataFile now + // adds texture packs + // m_dummyDLCTexturePack = addTexturePackFromDLC(pack, + // DLC_TEST_TEXTURE_PACK_ID); //new DLCTexturePack(0xFFFFFFFE, + // L"DLCTestPack", pack, DEFAULT_TEXTURE_PACK); + app.m_dlcManager.addPack(pack); + } else { + delete pack; + } + } + } -#endif // _XBOX -#endif // _CONTENT_PACKAGE +#endif // _XBOX +#endif // _CONTENT_PACKAGE } -void TexturePackRepository::createWorkingDirecoryUnlessExists() -{ - // 4J Unused +void TexturePackRepository::createWorkingDirecoryUnlessExists() { + // 4J Unused #if 0 if (!workDir.isDirectory()) { workDir.delete(); @@ -93,21 +92,20 @@ void TexturePackRepository::createWorkingDirecoryUnlessExists() #endif } -bool TexturePackRepository::selectSkin(TexturePack *skin) -{ - if (skin==selected) return false; - - lastSelected = selected; +bool TexturePackRepository::selectSkin(TexturePack* skin) { + if (skin == selected) return false; + + lastSelected = selected; usingWeb = false; selected = skin; - //minecraft->options->skin = skin->getName(); - //minecraft->options->save(); + // minecraft->options->skin = skin->getName(); + // minecraft->options->save(); return true; } -void TexturePackRepository::selectWebSkin(const std::wstring &url) -{ - app.DebugPrintf("TexturePackRepository::selectWebSkin is not implemented\n"); +void TexturePackRepository::selectWebSkin(const std::wstring& url) { + app.DebugPrintf( + "TexturePackRepository::selectWebSkin is not implemented\n"); #if 0 String filename = url.substring(url.lastIndexOf("/") + 1); if (filename.contains("?")) filename = filename.substring(0, filename.indexOf("?")); @@ -117,9 +115,10 @@ void TexturePackRepository::selectWebSkin(const std::wstring &url) #endif } -void TexturePackRepository::downloadWebSkin(const std::wstring &url, File file) -{ - app.DebugPrintf("TexturePackRepository::selectWebSkin is not implemented\n"); +void TexturePackRepository::downloadWebSkin(const std::wstring& url, + File file) { + app.DebugPrintf( + "TexturePackRepository::selectWebSkin is not implemented\n"); #if 0 Map headers = new HashMap(); final ProgressScreen listener = new ProgressScreen(); @@ -141,21 +140,17 @@ void TexturePackRepository::downloadWebSkin(const std::wstring &url, File file) #endif } -bool TexturePackRepository::isUsingWebSkin() -{ - return usingWeb; +bool TexturePackRepository::isUsingWebSkin() { return usingWeb; } + +void TexturePackRepository::resetWebSkin() { + usingWeb = false; + updateList(); + minecraft->delayTextureReload(); } -void TexturePackRepository::resetWebSkin() -{ - usingWeb = false; - updateList(); - minecraft->delayTextureReload(); -} - -void TexturePackRepository::updateList() -{ - // 4J Stu - We don't ever want to completely refresh the lists, we keep them up-to-date as we go +void TexturePackRepository::updateList() { + // 4J Stu - We don't ever want to completely refresh the lists, we keep them + // up-to-date as we go #if 0 std::vector *currentPacks = new std::vector; currentPacks->push_back(DEFAULT_TEXTURE_PACK); @@ -219,9 +214,8 @@ void TexturePackRepository::updateList() #endif } -std::wstring TexturePackRepository::getIdOrNull(File file) -{ - app.DebugPrintf("TexturePackRepository::getIdOrNull is not implemented\n"); +std::wstring TexturePackRepository::getIdOrNull(File file) { + app.DebugPrintf("TexturePackRepository::getIdOrNull is not implemented\n"); #if 0 if (file.isFile() && file.getName().toLowerCase().endsWith(".zip")) { return file.getName() + ":" + file.length() + ":" + file.lastModified(); @@ -231,12 +225,12 @@ std::wstring TexturePackRepository::getIdOrNull(File file) return NULL; #endif - return L""; + return L""; } -std::vector TexturePackRepository::getWorkDirContents() -{ - app.DebugPrintf("TexturePackRepository::getWorkDirContents is not implemented\n"); +std::vector TexturePackRepository::getWorkDirContents() { + app.DebugPrintf( + "TexturePackRepository::getWorkDirContents is not implemented\n"); #if 0 if (workDir.exists() && workDir.isDirectory()) { return Arrays.asList(workDir.listFiles()); @@ -244,24 +238,24 @@ std::vector TexturePackRepository::getWorkDirContents() return Collections.emptyList(); #endif - return std::vector(); + return std::vector(); } -std::vector *TexturePackRepository::getAll() -{ - // 4J - note that original constucted a copy of texturePacks here - return texturePacks; +std::vector* TexturePackRepository::getAll() { + // 4J - note that original constucted a copy of texturePacks here + return texturePacks; } -TexturePack *TexturePackRepository::getSelected() -{ - if(selected->hasData()) return selected; - else return DEFAULT_TEXTURE_PACK; +TexturePack* TexturePackRepository::getSelected() { + if (selected->hasData()) + return selected; + else + return DEFAULT_TEXTURE_PACK; } -bool TexturePackRepository::shouldPromptForWebSkin() -{ - app.DebugPrintf("TexturePackRepository::shouldPromptForWebSkin is not implemented\n"); +bool TexturePackRepository::shouldPromptForWebSkin() { + app.DebugPrintf( + "TexturePackRepository::shouldPromptForWebSkin is not implemented\n"); #if 0 if (!minecraft.options.serverTextures) return false; ServerData data = minecraft.getCurrentServer(); @@ -272,12 +266,12 @@ bool TexturePackRepository::shouldPromptForWebSkin() return data.promptOnTextures(); } #endif - return false; + return false; } -bool TexturePackRepository::canUseWebSkin() -{ - app.DebugPrintf("TexturePackRepository::canUseWebSkin is not implemented\n"); +bool TexturePackRepository::canUseWebSkin() { + app.DebugPrintf( + "TexturePackRepository::canUseWebSkin is not implemented\n"); #if 0 if (!minecraft.options.serverTextures) return false; ServerData data = minecraft.getCurrentServer(); @@ -288,177 +282,158 @@ bool TexturePackRepository::canUseWebSkin() return data.allowTextures(); } #endif - return false; + return false; } -std::vector< std::pair > *TexturePackRepository::getTexturePackIdNames() -{ - std::vector< std::pair > *packList = new std::vector< std::pair >(); +std::vector >* +TexturePackRepository::getTexturePackIdNames() { + std::vector >* packList = + new std::vector >(); - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) - { - TexturePack *pack = *it; - packList->push_back( std::pair(pack->getId(),pack->getName()) ); - } - return packList; + for (AUTO_VAR(it, texturePacks->begin()); it != texturePacks->end(); ++it) { + TexturePack* pack = *it; + packList->push_back(std::pair( + pack->getId(), pack->getName())); + } + return packList; } -bool TexturePackRepository::selectTexturePackById(std::uint32_t id) -{ - bool bDidSelect = false; +bool TexturePackRepository::selectTexturePackById(std::uint32_t id) { + bool bDidSelect = false; - //4J-PB - add in a store of the texture pack required, so that join from invite games - // (where they don't have the texture pack) can check this when the texture pack is installed - app.SetRequiredTexturePackID(id); + // 4J-PB - add in a store of the texture pack required, so that join from + // invite games + // (where they don't have the texture pack) can check this when the texture + // pack is installed + app.SetRequiredTexturePackID(id); - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - TexturePack *newPack = it->second; - if(newPack != selected) - { - selectSkin(newPack); + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + TexturePack* newPack = it->second; + if (newPack != selected) { + selectSkin(newPack); - if(newPack->hasData()) - { - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } - else - { - newPack->loadData(); - } - //Minecraft *pMinecraft = Minecraft::GetInstance(); - //pMinecraft->textures->reloadAll(); - } - else - { - app.DebugPrintf("TexturePack with id %d is already selected\n",id); - } - bDidSelect = true; - } - else - { - app.DebugPrintf("Failed to select texture pack %d as it is not in the list\n", id); + if (newPack->hasData()) { + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } else { + newPack->loadData(); + } + // Minecraft *pMinecraft = Minecraft::GetInstance(); + // pMinecraft->textures->reloadAll(); + } else { + app.DebugPrintf("TexturePack with id %d is already selected\n", id); + } + bDidSelect = true; + } else { + app.DebugPrintf( + "Failed to select texture pack %d as it is not in the list\n", id); #ifndef _CONTENT_PACKAGE - // TODO - 4J Stu: We should report this to the player in some way - //__debugbreak(); + // TODO - 4J Stu: We should report this to the player in some way + //__debugbreak(); #endif - // Fail safely - if( selectSkin( DEFAULT_TEXTURE_PACK ) ) - { - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } - } - return bDidSelect; + // Fail safely + if (selectSkin(DEFAULT_TEXTURE_PACK)) { + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } + } + return bDidSelect; } -TexturePack *TexturePackRepository::getTexturePackById(std::uint32_t id) -{ - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - return it->second; - } +TexturePack* TexturePackRepository::getTexturePackById(std::uint32_t id) { + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + return it->second; + } - return NULL; + return NULL; } -TexturePack *TexturePackRepository::addTexturePackFromDLC(DLCPack *dlcPack, std::uint32_t id) -{ - TexturePack *newPack = NULL; - // 4J-PB - The City texture pack went out with a child id for the texture pack of 1 instead of zero - // we need to mask off the child id here to deal with this - const std::uint32_t parentId = id & 0xFFFFFFu; // child id is <<24 and Or'd with parent +TexturePack* TexturePackRepository::addTexturePackFromDLC(DLCPack* dlcPack, + std::uint32_t id) { + TexturePack* newPack = NULL; + // 4J-PB - The City texture pack went out with a child id for the texture + // pack of 1 instead of zero we need to mask off the child id here to deal + // with this + const std::uint32_t parentId = + id & 0xFFFFFFu; // child id is <<24 and Or'd with parent - if(dlcPack != NULL) - { - newPack = new DLCTexturePack(parentId, dlcPack, DEFAULT_TEXTURE_PACK); - texturePacks->push_back(newPack); - cacheById[parentId] = newPack; + if (dlcPack != NULL) { + newPack = new DLCTexturePack(parentId, dlcPack, DEFAULT_TEXTURE_PACK); + texturePacks->push_back(newPack); + cacheById[parentId] = newPack; #ifndef _CONTENT_PACKAGE - if(dlcPack->hasPurchasedFile(DLCManager::e_DLCType_TexturePack,L"")) - { - wprintf(L"Added new FULL DLCTexturePack: %ls - id=%u\n", dlcPack->getName().c_str(), parentId ); - } - else - { - wprintf(L"Added new TRIAL DLCTexturePack: %ls - id=%u\n", dlcPack->getName().c_str(), parentId ); - } + if (dlcPack->hasPurchasedFile(DLCManager::e_DLCType_TexturePack, L"")) { + wprintf(L"Added new FULL DLCTexturePack: %ls - id=%u\n", + dlcPack->getName().c_str(), parentId); + } else { + wprintf(L"Added new TRIAL DLCTexturePack: %ls - id=%u\n", + dlcPack->getName().c_str(), parentId); + } #endif - } - return newPack; + } + return newPack; } -void TexturePackRepository::clearInvalidTexturePacks() -{ - for(AUTO_VAR(it, m_texturePacksToDelete.begin()); it != m_texturePacksToDelete.end(); ++it) - { - delete *it; - } +void TexturePackRepository::clearInvalidTexturePacks() { + for (AUTO_VAR(it, m_texturePacksToDelete.begin()); + it != m_texturePacksToDelete.end(); ++it) { + delete *it; + } } -void TexturePackRepository::removeTexturePackById(std::uint32_t id) -{ - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - TexturePack *oldPack = it->second; +void TexturePackRepository::removeTexturePackById(std::uint32_t id) { + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + TexturePack* oldPack = it->second; - AUTO_VAR(it2, find(texturePacks->begin(), texturePacks->end(),oldPack) ); - if(it2 != texturePacks->end()) - { - texturePacks->erase(it2); - if(lastSelected == oldPack) - { - lastSelected = NULL; - } - } - m_texturePacksToDelete.push_back(oldPack); - } + AUTO_VAR(it2, + find(texturePacks->begin(), texturePacks->end(), oldPack)); + if (it2 != texturePacks->end()) { + texturePacks->erase(it2); + if (lastSelected == oldPack) { + lastSelected = NULL; + } + } + m_texturePacksToDelete.push_back(oldPack); + } } -void TexturePackRepository::updateUI() -{ - if(lastSelected != NULL && lastSelected != selected) - { - lastSelected->unloadUI(); - selected->loadUI(); - Minimap::reloadColours(); - ui.StartReloadSkinThread(); - lastSelected = NULL; - } +void TexturePackRepository::updateUI() { + if (lastSelected != NULL && lastSelected != selected) { + lastSelected->unloadUI(); + selected->loadUI(); + Minimap::reloadColours(); + ui.StartReloadSkinThread(); + lastSelected = NULL; + } } -bool TexturePackRepository::needsUIUpdate() -{ - return lastSelected != NULL && lastSelected != selected; +bool TexturePackRepository::needsUIUpdate() { + return lastSelected != NULL && lastSelected != selected; } -unsigned int TexturePackRepository::getTexturePackCount() -{ - return texturePacks->size(); +unsigned int TexturePackRepository::getTexturePackCount() { + return texturePacks->size(); } -TexturePack *TexturePackRepository::getTexturePackByIndex(unsigned int index) -{ - TexturePack *pack = NULL; - if(index < texturePacks->size()) - { - pack = texturePacks->at(index); - } - return pack; +TexturePack* TexturePackRepository::getTexturePackByIndex(unsigned int index) { + TexturePack* pack = NULL; + if (index < texturePacks->size()) { + pack = texturePacks->at(index); + } + return pack; } -unsigned int TexturePackRepository::getTexturePackIndex(std::uint32_t id) -{ - int currentIndex = 0; - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) - { - TexturePack *pack = *it; - if(pack->getId() == id) break; - ++currentIndex; - } - if(currentIndex >= texturePacks->size()) currentIndex = 0; - return currentIndex; +unsigned int TexturePackRepository::getTexturePackIndex(std::uint32_t id) { + int currentIndex = 0; + for (AUTO_VAR(it, texturePacks->begin()); it != texturePacks->end(); ++it) { + TexturePack* pack = *it; + if (pack->getId() == id) break; + ++currentIndex; + } + if (currentIndex >= texturePacks->size()) currentIndex = 0; + return currentIndex; } diff --git a/Minecraft.Client/Textures/Packs/TexturePackRepository.h b/Minecraft.Client/Textures/Packs/TexturePackRepository.h index a93e1f7c6..105c634e0 100644 --- a/Minecraft.Client/Textures/Packs/TexturePackRepository.h +++ b/Minecraft.Client/Textures/Packs/TexturePackRepository.h @@ -1,77 +1,82 @@ #pragma once #include "TexturePack.h" - class Minecraft; -class TexturePackRepository -{ +class TexturePackRepository { public: - static constexpr std::uint32_t DEFAULT_TEXTURE_PACK_ID = 0; - static constexpr std::uint32_t FOLDER_TEST_TEXTURE_PACK_ID = 1; - static constexpr std::uint32_t DLC_TEST_TEXTURE_PACK_ID = 2; + static constexpr std::uint32_t DEFAULT_TEXTURE_PACK_ID = 0; + static constexpr std::uint32_t FOLDER_TEST_TEXTURE_PACK_ID = 1; + static constexpr std::uint32_t DLC_TEST_TEXTURE_PACK_ID = 2; + private: - static TexturePack *DEFAULT_TEXTURE_PACK; - TexturePack *m_dummyTexturePack; - TexturePack *m_dummyDLCTexturePack; + static TexturePack* DEFAULT_TEXTURE_PACK; + TexturePack* m_dummyTexturePack; + TexturePack* m_dummyDLCTexturePack; - Minecraft *minecraft; - File workDir; - File multiplayerDir; - std::vector *texturePacks; - std::vector m_texturePacksToDelete; + Minecraft* minecraft; + File workDir; + File multiplayerDir; + std::vector* texturePacks; + std::vector m_texturePacksToDelete; - std::unordered_map cacheById; + std::unordered_map cacheById; - TexturePack *selected; - TexturePack *lastSelected; + TexturePack* selected; + TexturePack* lastSelected; bool usingWeb; - static const int MAX_WEB_FILESIZE = 10 * 1000 * 1000; // 10 Megabytes + static const int MAX_WEB_FILESIZE = 10 * 1000 * 1000; // 10 Megabytes public: - TexturePackRepository(File workingDirectory, Minecraft *minecraft); - void addDebugPacks(); -private: - void createWorkingDirecoryUnlessExists(); - -public: - bool selectSkin(TexturePack *skin); - - void selectWebSkin(const std::wstring &url); + TexturePackRepository(File workingDirectory, Minecraft* minecraft); + void addDebugPacks(); private: - void downloadWebSkin(const std::wstring &url, File file); + void createWorkingDirecoryUnlessExists(); public: - bool isUsingWebSkin(); - void resetWebSkin(); + bool selectSkin(TexturePack* skin); + + void selectWebSkin(const std::wstring& url); + +private: + void downloadWebSkin(const std::wstring& url, File file); + +public: + bool isUsingWebSkin(); + void resetWebSkin(); void updateList(); private: - std::wstring getIdOrNull(File file); + std::wstring getIdOrNull(File file); std::vector getWorkDirContents(); public: - std::vector *getAll(); + std::vector* getAll(); - TexturePack *getSelected(); - bool shouldPromptForWebSkin(); - bool canUseWebSkin(); - bool isUsingDefaultSkin() { return selected == DEFAULT_TEXTURE_PACK; } // 4J Added - TexturePack *getDefault() { return DEFAULT_TEXTURE_PACK; } // 4J Added + TexturePack* getSelected(); + bool shouldPromptForWebSkin(); + bool canUseWebSkin(); + bool isUsingDefaultSkin() { + return selected == DEFAULT_TEXTURE_PACK; + } // 4J Added + TexturePack* getDefault() { return DEFAULT_TEXTURE_PACK; } // 4J Added - std::vector< std::pair > *getTexturePackIdNames(); - bool selectTexturePackById(std::uint32_t id); // 4J Added - TexturePack *getTexturePackById(std::uint32_t id); // 4J Added + std::vector >* + getTexturePackIdNames(); + bool selectTexturePackById(std::uint32_t id); // 4J Added + TexturePack* getTexturePackById(std::uint32_t id); // 4J Added + + TexturePack* addTexturePackFromDLC(DLCPack* dlcPack, std::uint32_t id); + void clearInvalidTexturePacks(); + void updateUI(); + bool needsUIUpdate(); - TexturePack *addTexturePackFromDLC(DLCPack *dlcPack, std::uint32_t id); - void clearInvalidTexturePacks(); - void updateUI(); - bool needsUIUpdate(); private: - void removeTexturePackById(std::uint32_t id); + void removeTexturePackById(std::uint32_t id); + public: - unsigned int getTexturePackCount(); - TexturePack *getTexturePackByIndex(unsigned int index); - unsigned int getTexturePackIndex(std::uint32_t id); + unsigned int getTexturePackCount(); + TexturePack* getTexturePackByIndex(unsigned int index); + unsigned int getTexturePackIndex(std::uint32_t id); }; diff --git a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp index 99066524e..431037140 100644 --- a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp +++ b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp @@ -22,210 +22,216 @@ const std::wstring PreStitchedTextureMap::NAME_MISSING_TEXTURE = L"missingno"; -PreStitchedTextureMap::PreStitchedTextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipmap) : iconType(type), name(name), path(path), extension(L".png") -{ - this->missingTexture = missingTexture; +PreStitchedTextureMap::PreStitchedTextureMap(int type, const std::wstring& name, + const std::wstring& path, + BufferedImage* missingTexture, + bool mipmap) + : iconType(type), name(name), path(path), extension(L".png") { + this->missingTexture = missingTexture; - // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + // 4J Initialisers + missingPosition = NULL; + stitchResult = NULL; - m_mipMap = mipmap; - missingPosition = (StitchedTexture *)(new SimpleIcon(NAME_MISSING_TEXTURE,0,0,1,1)); + m_mipMap = mipmap; + missingPosition = + (StitchedTexture*)(new SimpleIcon(NAME_MISSING_TEXTURE, 0, 0, 1, 1)); } -void PreStitchedTextureMap::stitch() -{ - // Animated StitchedTextures store a vector of textures for each frame of the animation. Free any pre-existing ones here. - for(AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); ++it) - { - StitchedTexture *animatedStitchedTexture = (StitchedTexture *)texturesByName[it->first]; - animatedStitchedTexture->freeFrameTextures(); - } +void PreStitchedTextureMap::stitch() { + // Animated StitchedTextures store a vector of textures for each frame of + // the animation. Free any pre-existing ones here. + for (AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); + ++it) { + StitchedTexture* animatedStitchedTexture = + (StitchedTexture*)texturesByName[it->first]; + animatedStitchedTexture->freeFrameTextures(); + } - loadUVs(); + loadUVs(); - if (iconType == Icon::TYPE_TERRAIN) - { - //for (Tile tile : Tile.tiles) - for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) - { - if (Tile::tiles[i] != NULL) - { - Tile::tiles[i]->registerIcons(this); - } - } + if (iconType == Icon::TYPE_TERRAIN) { + // for (Tile tile : Tile.tiles) + for (unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { + if (Tile::tiles[i] != NULL) { + Tile::tiles[i]->registerIcons(this); + } + } - Minecraft::GetInstance()->levelRenderer->registerTextures(this); - EntityRenderDispatcher::instance->registerTerrainTextures(this); - } + Minecraft::GetInstance()->levelRenderer->registerTextures(this); + EntityRenderDispatcher::instance->registerTerrainTextures(this); + } - //for (Item item : Item.items) - for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) - { - Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) - { - item->registerIcons(this); - } - } + // for (Item item : Item.items) + for (unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { + Item* item = Item::items[i]; + if (item != NULL && item->getIconType() == iconType) { + item->registerIcons(this); + } + } - // Collection bucket for multiple frames per texture - std::unordered_map * > textures; // = new HashMap>(); + // Collection bucket for multiple frames per texture + std::unordered_map*> + textures; // = new HashMap>(); - Stitcher *stitcher = TextureManager::getInstance()->createStitcher(name); + Stitcher* stitcher = TextureManager::getInstance()->createStitcher(name); - animatedTextures.clear(); + animatedTextures.clear(); - // Create the final image - std::wstring filename = name + extension; + // Create the final image + std::wstring filename = name + extension; - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - //try { - int mode = Texture::TM_DYNAMIC; - int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader //Texture::WM_CLAMP; - int minFilter = Texture::TFLT_NEAREST; - int magFilter = Texture::TFLT_NEAREST; + TexturePack* texturePack = Minecraft::GetInstance()->skins->getSelected(); + // try { + int mode = Texture::TM_DYNAMIC; + int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues + // with how we signal non-mipmmapped textures + // to the pixel shader //Texture::WM_CLAMP; + int minFilter = Texture::TFLT_NEAREST; + int magFilter = Texture::TFLT_NEAREST; - MemSect(32); - std::wstring drive = L""; - if(texturePack->hasFile(L"res/" + filename,false)) - { - drive = texturePack->getPath(true); - } - else - { - drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); - texturePack = Minecraft::GetInstance()->skins->getDefault(); - } - //BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + filename),false,true,drive); //ImageIO::read(texturePack->getResource(L"/" + filename)); - BufferedImage *image = texturePack->getImageResource(filename, false, true, drive); - MemSect(0); - int height = image->getHeight(); - int width = image->getWidth(); + MemSect(32); + std::wstring drive = L""; + if (texturePack->hasFile(L"res/" + filename, false)) { + drive = texturePack->getPath(true); + } else { + drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); + texturePack = Minecraft::GetInstance()->skins->getDefault(); + } + // BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + + // filename),false,true,drive); + // //ImageIO::read(texturePack->getResource(L"/" + filename)); + BufferedImage* image = + texturePack->getImageResource(filename, false, true, drive); + MemSect(0); + int height = image->getHeight(); + int width = image->getWidth(); - if(stitchResult != NULL) - { - TextureManager::getInstance()->unregisterTexture(name, stitchResult); - delete stitchResult; - } - stitchResult = TextureManager::getInstance()->createTexture(name, Texture::TM_DYNAMIC, width, height, Texture::TFMT_RGBA, m_mipMap); - stitchResult->transferFromImage(image); - delete image; - TextureManager::getInstance()->registerName(name, stitchResult); - //stitchResult = stitcher->constructTexture(m_mipMap); + if (stitchResult != NULL) { + TextureManager::getInstance()->unregisterTexture(name, stitchResult); + delete stitchResult; + } + stitchResult = TextureManager::getInstance()->createTexture( + name, Texture::TM_DYNAMIC, width, height, Texture::TFMT_RGBA, m_mipMap); + stitchResult->transferFromImage(image); + delete image; + TextureManager::getInstance()->registerName(name, stitchResult); + // stitchResult = stitcher->constructTexture(m_mipMap); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - StitchedTexture *preStitched = (StitchedTexture *)it->second; + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + StitchedTexture* preStitched = (StitchedTexture*)it->second; - int x = preStitched->getU0() * stitchResult->getWidth(); - int y = preStitched->getV0() * stitchResult->getHeight(); - int width = (preStitched->getU1() * stitchResult->getWidth()) - x; - int height = (preStitched->getV1() * stitchResult->getHeight()) - y; + int x = preStitched->getU0() * stitchResult->getWidth(); + int y = preStitched->getV0() * stitchResult->getHeight(); + int width = (preStitched->getU1() * stitchResult->getWidth()) - x; + int height = (preStitched->getV1() * stitchResult->getHeight()) - y; - preStitched->init(stitchResult, NULL, x, y, width, height, false); - } + preStitched->init(stitchResult, NULL, x, y, width, height, false); + } - MemSect(52); - for(AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); ++it) - { - std::wstring textureName = it->first; - std::wstring textureFileName = it->second; + MemSect(52); + for (AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); + ++it) { + std::wstring textureName = it->first; + std::wstring textureFileName = it->second; - StitchedTexture *preStitched = (StitchedTexture *)texturesByName[textureName]; + StitchedTexture* preStitched = + (StitchedTexture*)texturesByName[textureName]; - if(!preStitched->hasOwnData()) - { - if(preStitched->getFrames() > 1) animatedTextures.push_back(preStitched); - continue; - } + if (!preStitched->hasOwnData()) { + if (preStitched->getFrames() > 1) + animatedTextures.push_back(preStitched); + continue; + } - std::wstring filename = path + textureFileName + extension; + std::wstring filename = path + textureFileName + extension; - // TODO: [EB] Put the frames into a proper object, not this inside out hack - std::vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); - if (frames == NULL || frames->empty()) - { - continue; // Couldn't load a texture, skip it - } + // TODO: [EB] Put the frames into a proper object, not this inside out + // hack + std::vector* frames = + TextureManager::getInstance()->createTextures(filename, m_mipMap); + if (frames == NULL || frames->empty()) { + continue; // Couldn't load a texture, skip it + } - Texture *first = frames->at(0); + Texture* first = frames->at(0); #ifndef _CONTENT_PACKAGE - if(first->getWidth() != preStitched->getWidth() || first->getHeight() != preStitched->getHeight()) - { - __debugbreak(); - } + if (first->getWidth() != preStitched->getWidth() || + first->getHeight() != preStitched->getHeight()) { + __debugbreak(); + } #endif - preStitched->init(stitchResult, frames, preStitched->getX(), preStitched->getY(), first->getWidth(), first->getHeight(), false); + preStitched->init(stitchResult, frames, preStitched->getX(), + preStitched->getY(), first->getWidth(), + first->getHeight(), false); - if (frames->size() > 1) - { - animatedTextures.push_back(preStitched); + if (frames->size() > 1) { + animatedTextures.push_back(preStitched); - std::wstring animString = texturePack->getAnimationString(textureFileName, path, true); + std::wstring animString = + texturePack->getAnimationString(textureFileName, path, true); - preStitched->loadAnimationFrames(animString); - } - } - MemSect(0); - //missingPosition = (StitchedTexture *)texturesByName.find(NAME_MISSING_TEXTURE)->second; - - stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); - stitchResult->updateOnGPU(); + preStitched->loadAnimationFrames(animString); + } + } + MemSect(0); + // missingPosition = (StitchedTexture + // *)texturesByName.find(NAME_MISSING_TEXTURE)->second; + stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); + stitchResult->updateOnGPU(); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita so we mark which icons actually require it - const std::uint8_t *data = this->getStitchedTexture()->getData()->getBuffer(); - int Width = this->getStitchedTexture()->getWidth(); - int Height = this->getStitchedTexture()->getHeight(); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - StitchedTexture *preStitched = (StitchedTexture *)it->second; + // AP - alpha cut out is expensive on vita so we mark which icons actually + // require it + const std::uint8_t* data = + this->getStitchedTexture()->getData()->getBuffer(); + int Width = this->getStitchedTexture()->getWidth(); + int Height = this->getStitchedTexture()->getHeight(); + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + StitchedTexture* preStitched = (StitchedTexture*)it->second; - bool Found = false; - int u0 = preStitched->getU0() * Width; - int u1 = preStitched->getU1() * Width; - int v0 = preStitched->getV0() * Height; - int v1 = preStitched->getV1() * Height; + bool Found = false; + int u0 = preStitched->getU0() * Width; + int u1 = preStitched->getU1() * Width; + int v0 = preStitched->getV0() * Height; + int v1 = preStitched->getV1() * Height; - // check all the texels for this icon. If ANY are transparent we mark it as 'cut out' - for( int v = v0;v < v1; v+= 1 ) - { - for( int u = u0;u < u1; u+= 1 ) - { - std::uint32_t pixel = 0; - std::memcpy(&pixel, data + ((v * Width + u) * sizeof(pixel)), sizeof(pixel)); - // is this texel alpha value < 0.1 - if( (pixel & 0xff000000) < 0x20000000 ) - { - // this texel is transparent. Mark the icon as such and bail - preStitched->setFlags(Icon::IS_ALPHA_CUT_OUT); - Found = true; - break; - } - } + // check all the texels for this icon. If ANY are transparent we mark it + // as 'cut out' + for (int v = v0; v < v1; v += 1) { + for (int u = u0; u < u1; u += 1) { + std::uint32_t pixel = 0; + std::memcpy(&pixel, data + ((v * Width + u) * sizeof(pixel)), + sizeof(pixel)); + // is this texel alpha value < 0.1 + if ((pixel & 0xff000000) < 0x20000000) { + // this texel is transparent. Mark the icon as such and bail + preStitched->setFlags(Icon::IS_ALPHA_CUT_OUT); + Found = true; + break; + } + } - if( Found ) - { - // move onto the next icon - break; - } - } - } + if (Found) { + // move onto the next icon + break; + } + } + } #endif } -StitchedTexture *PreStitchedTextureMap::getTexture(const std::wstring &name) -{ +StitchedTexture* PreStitchedTextureMap::getTexture(const std::wstring& name) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Not implemented!\n"); - __debugbreak(); + app.DebugPrintf("Not implemented!\n"); + __debugbreak(); #endif - return NULL; + return NULL; #if 0 StitchedTexture *result = texturesByName.find(name)->second; if (result == NULL) result = missingPosition; @@ -233,624 +239,1986 @@ StitchedTexture *PreStitchedTextureMap::getTexture(const std::wstring &name) #endif } -void PreStitchedTextureMap::cycleAnimationFrames() -{ - //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) - { - StitchedTexture *texture = *it; - texture->cycleFrames(); - } +void PreStitchedTextureMap::cycleAnimationFrames() { + // for (StitchedTexture texture : animatedTextures) + for (AUTO_VAR(it, animatedTextures.begin()); it != animatedTextures.end(); + ++it) { + StitchedTexture* texture = *it; + texture->cycleFrames(); + } } -Texture *PreStitchedTextureMap::getStitchedTexture() -{ - return stitchResult; -} +Texture* PreStitchedTextureMap::getStitchedTexture() { return stitchResult; } // 4J Stu - register is a reserved keyword in C++ -Icon *PreStitchedTextureMap::registerIcon(const std::wstring &name) -{ - Icon *result = NULL; - if (name.empty()) - { - app.DebugPrintf("Don't register NULL\n"); +Icon* PreStitchedTextureMap::registerIcon(const std::wstring& name) { + Icon* result = NULL; + if (name.empty()) { + app.DebugPrintf("Don't register NULL\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - result = missingPosition; - //new RuntimeException("Don't register null!").printStackTrace(); - } + result = missingPosition; + // new RuntimeException("Don't register null!").printStackTrace(); + } - AUTO_VAR(it, texturesByName.find(name)); - if(it != texturesByName.end()) result = it->second; + AUTO_VAR(it, texturesByName.find(name)); + if (it != texturesByName.end()) result = it->second; - if (result == NULL) - { + if (result == NULL) { #ifndef _CONTENT_PACKAGE - wprintf(L"Could not find uv data for icon %ls\n", name.c_str() ); - __debugbreak(); + wprintf(L"Could not find uv data for icon %ls\n", name.c_str()); + __debugbreak(); #endif - result = missingPosition; - } + result = missingPosition; + } - return result; + return result; } -int PreStitchedTextureMap::getIconType() -{ - return iconType; -} - -Icon *PreStitchedTextureMap::getMissingIcon() -{ - return missingPosition; -} - -void PreStitchedTextureMap::loadUVs() -{ - if(!texturesByName.empty()) - { - // 4J Stu - We only need to populate this once at the moment as we have hardcoded positions for each texture - // If we ever load that dynamically, be aware that the Icon objects could currently be being used by the - // GameRenderer::runUpdate thread - return; - } - - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - delete it->second; - } - texturesByName.clear(); - texturesToAnimate.clear(); - - float slotSize = 1.0f/16.0f; - if(iconType != Icon::TYPE_TERRAIN) - { - texturesByName.insert(stringIconMap::value_type(L"helmetCloth",new SimpleIcon(L"helmetCloth",slotSize*0,slotSize*0,slotSize*(0+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetChain",new SimpleIcon(L"helmetChain",slotSize*1,slotSize*0,slotSize*(1+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetIron",new SimpleIcon(L"helmetIron",slotSize*2,slotSize*0,slotSize*(2+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetDiamond",new SimpleIcon(L"helmetDiamond",slotSize*3,slotSize*0,slotSize*(3+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetGold",new SimpleIcon(L"helmetGold",slotSize*4,slotSize*0,slotSize*(4+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flintAndSteel",new SimpleIcon(L"flintAndSteel",slotSize*5,slotSize*0,slotSize*(5+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flint",new SimpleIcon(L"flint",slotSize*6,slotSize*0,slotSize*(6+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"coal",new SimpleIcon(L"coal",slotSize*7,slotSize*0,slotSize*(7+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"string",new SimpleIcon(L"string",slotSize*8,slotSize*0,slotSize*(8+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds",new SimpleIcon(L"seeds",slotSize*9,slotSize*0,slotSize*(9+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"apple",new SimpleIcon(L"apple",slotSize*10,slotSize*0,slotSize*(10+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"appleGold",new SimpleIcon(L"appleGold",slotSize*11,slotSize*0,slotSize*(11+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"egg",new SimpleIcon(L"egg",slotSize*12,slotSize*0,slotSize*(12+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"sugar",new SimpleIcon(L"sugar",slotSize*13,slotSize*0,slotSize*(13+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"snowball",new SimpleIcon(L"snowball",slotSize*14,slotSize*0,slotSize*(14+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_helmet",new SimpleIcon(L"slot_empty_helmet",slotSize*15,slotSize*0,slotSize*(15+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateCloth",new SimpleIcon(L"chestplateCloth",slotSize*0,slotSize*1,slotSize*(0+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateChain",new SimpleIcon(L"chestplateChain",slotSize*1,slotSize*1,slotSize*(1+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateIron",new SimpleIcon(L"chestplateIron",slotSize*2,slotSize*1,slotSize*(2+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateDiamond",new SimpleIcon(L"chestplateDiamond",slotSize*3,slotSize*1,slotSize*(3+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateGold",new SimpleIcon(L"chestplateGold",slotSize*4,slotSize*1,slotSize*(4+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow",new SimpleIcon(L"bow",slotSize*5,slotSize*1,slotSize*(5+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"brick",new SimpleIcon(L"brick",slotSize*6,slotSize*1,slotSize*(6+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"ingotIron",new SimpleIcon(L"ingotIron",slotSize*7,slotSize*1,slotSize*(7+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"feather",new SimpleIcon(L"feather",slotSize*8,slotSize*1,slotSize*(8+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"wheat",new SimpleIcon(L"wheat",slotSize*9,slotSize*1,slotSize*(9+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"painting",new SimpleIcon(L"painting",slotSize*10,slotSize*1,slotSize*(10+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"reeds",new SimpleIcon(L"reeds",slotSize*11,slotSize*1,slotSize*(11+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bone",new SimpleIcon(L"bone",slotSize*12,slotSize*1,slotSize*(12+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake",new SimpleIcon(L"cake",slotSize*13,slotSize*1,slotSize*(13+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"slimeball",new SimpleIcon(L"slimeball",slotSize*14,slotSize*1,slotSize*(14+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_chestplate",new SimpleIcon(L"slot_empty_chestplate",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsCloth",new SimpleIcon(L"leggingsCloth",slotSize*0,slotSize*2,slotSize*(0+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsChain",new SimpleIcon(L"leggingsChain",slotSize*1,slotSize*2,slotSize*(1+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsIron",new SimpleIcon(L"leggingsIron",slotSize*2,slotSize*2,slotSize*(2+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsDiamond",new SimpleIcon(L"leggingsDiamond",slotSize*3,slotSize*2,slotSize*(3+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsGold",new SimpleIcon(L"leggingsGold",slotSize*4,slotSize*2,slotSize*(4+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"arrow",new SimpleIcon(L"arrow",slotSize*5,slotSize*2,slotSize*(5+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"quiver",new SimpleIcon(L"quiver",slotSize*6,slotSize*2,slotSize*(6+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"ingotGold",new SimpleIcon(L"ingotGold",slotSize*7,slotSize*2,slotSize*(7+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"sulphur",new SimpleIcon(L"sulphur",slotSize*8,slotSize*2,slotSize*(8+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bread",new SimpleIcon(L"bread",slotSize*9,slotSize*2,slotSize*(9+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"sign",new SimpleIcon(L"sign",slotSize*10,slotSize*2,slotSize*(10+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood",new SimpleIcon(L"doorWood",slotSize*11,slotSize*2,slotSize*(11+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron",new SimpleIcon(L"doorIron",slotSize*12,slotSize*2,slotSize*(12+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed",new SimpleIcon(L"bed",slotSize*13,slotSize*2,slotSize*(13+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireball",new SimpleIcon(L"fireball",slotSize*14,slotSize*2,slotSize*(14+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_leggings",new SimpleIcon(L"slot_empty_leggings",slotSize*15,slotSize*2,slotSize*(15+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsCloth",new SimpleIcon(L"bootsCloth",slotSize*0,slotSize*3,slotSize*(0+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsChain",new SimpleIcon(L"bootsChain",slotSize*1,slotSize*3,slotSize*(1+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsIron",new SimpleIcon(L"bootsIron",slotSize*2,slotSize*3,slotSize*(2+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsDiamond",new SimpleIcon(L"bootsDiamond",slotSize*3,slotSize*3,slotSize*(3+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsGold",new SimpleIcon(L"bootsGold",slotSize*4,slotSize*3,slotSize*(4+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"stick",new SimpleIcon(L"stick",slotSize*5,slotSize*3,slotSize*(5+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"compass",new SimpleIcon(L"compass",slotSize*6,slotSize*3,slotSize*(6+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP0",new SimpleIcon(L"compassP0",slotSize*7,slotSize*14,slotSize*(7+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP1",new SimpleIcon(L"compassP1",slotSize*8,slotSize*14,slotSize*(8+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP2",new SimpleIcon(L"compassP2",slotSize*9,slotSize*14,slotSize*(9+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP3",new SimpleIcon(L"compassP3",slotSize*10,slotSize*14,slotSize*(10+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"compass",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP0",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP1",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP2",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP3",L"compass")); - texturesByName.insert(stringIconMap::value_type(L"diamond",new SimpleIcon(L"diamond",slotSize*7,slotSize*3,slotSize*(7+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstone",new SimpleIcon(L"redstone",slotSize*8,slotSize*3,slotSize*(8+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"clay",new SimpleIcon(L"clay",slotSize*9,slotSize*3,slotSize*(9+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"paper",new SimpleIcon(L"paper",slotSize*10,slotSize*3,slotSize*(10+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"book",new SimpleIcon(L"book",slotSize*11,slotSize*3,slotSize*(11+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"map",new SimpleIcon(L"map",slotSize*12,slotSize*3,slotSize*(12+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds_pumpkin",new SimpleIcon(L"seeds_pumpkin",slotSize*13,slotSize*3,slotSize*(13+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds_melon",new SimpleIcon(L"seeds_melon",slotSize*14,slotSize*3,slotSize*(14+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_boots",new SimpleIcon(L"slot_empty_boots",slotSize*15,slotSize*3,slotSize*(15+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordWood",new SimpleIcon(L"swordWood",slotSize*0,slotSize*4,slotSize*(0+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordStone",new SimpleIcon(L"swordStone",slotSize*1,slotSize*4,slotSize*(1+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordIron",new SimpleIcon(L"swordIron",slotSize*2,slotSize*4,slotSize*(2+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordDiamond",new SimpleIcon(L"swordDiamond",slotSize*3,slotSize*4,slotSize*(3+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordGold",new SimpleIcon(L"swordGold",slotSize*4,slotSize*4,slotSize*(4+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishingRod",new SimpleIcon(L"fishingRod",slotSize*5,slotSize*4,slotSize*(5+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clock",new SimpleIcon(L"clock",slotSize*6,slotSize*4,slotSize*(6+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP0",new SimpleIcon(L"clockP0",slotSize*11,slotSize*14,slotSize*(11+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP1",new SimpleIcon(L"clockP1",slotSize*12,slotSize*14,slotSize*(12+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP2",new SimpleIcon(L"clockP2",slotSize*13,slotSize*14,slotSize*(13+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP3",new SimpleIcon(L"clockP3",slotSize*14,slotSize*14,slotSize*(14+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"clock",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP0",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP1",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP2",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP3",L"clock")); - texturesByName.insert(stringIconMap::value_type(L"bowl",new SimpleIcon(L"bowl",slotSize*7,slotSize*4,slotSize*(7+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroomStew",new SimpleIcon(L"mushroomStew",slotSize*8,slotSize*4,slotSize*(8+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"yellowDust",new SimpleIcon(L"yellowDust",slotSize*9,slotSize*4,slotSize*(9+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucket",new SimpleIcon(L"bucket",slotSize*10,slotSize*4,slotSize*(10+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucketWater",new SimpleIcon(L"bucketWater",slotSize*11,slotSize*4,slotSize*(11+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucketLava",new SimpleIcon(L"bucketLava",slotSize*12,slotSize*4,slotSize*(12+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"milk",new SimpleIcon(L"milk",slotSize*13,slotSize*4,slotSize*(13+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_black",new SimpleIcon(L"dyePowder_black",slotSize*14,slotSize*4,slotSize*(14+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_gray",new SimpleIcon(L"dyePowder_gray",slotSize*15,slotSize*4,slotSize*(15+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelWood",new SimpleIcon(L"shovelWood",slotSize*0,slotSize*5,slotSize*(0+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelStone",new SimpleIcon(L"shovelStone",slotSize*1,slotSize*5,slotSize*(1+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelIron",new SimpleIcon(L"shovelIron",slotSize*2,slotSize*5,slotSize*(2+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelDiamond",new SimpleIcon(L"shovelDiamond",slotSize*3,slotSize*5,slotSize*(3+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelGold",new SimpleIcon(L"shovelGold",slotSize*4,slotSize*5,slotSize*(4+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishingRod_empty",new SimpleIcon(L"fishingRod_empty",slotSize*5,slotSize*5,slotSize*(5+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"diode",new SimpleIcon(L"diode",slotSize*6,slotSize*5,slotSize*(6+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"porkchopRaw",new SimpleIcon(L"porkchopRaw",slotSize*7,slotSize*5,slotSize*(7+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"porkchopCooked",new SimpleIcon(L"porkchopCooked",slotSize*8,slotSize*5,slotSize*(8+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishRaw",new SimpleIcon(L"fishRaw",slotSize*9,slotSize*5,slotSize*(9+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishCooked",new SimpleIcon(L"fishCooked",slotSize*10,slotSize*5,slotSize*(10+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"rottenFlesh",new SimpleIcon(L"rottenFlesh",slotSize*11,slotSize*5,slotSize*(11+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"cookie",new SimpleIcon(L"cookie",slotSize*12,slotSize*5,slotSize*(12+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shears",new SimpleIcon(L"shears",slotSize*13,slotSize*5,slotSize*(13+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_red",new SimpleIcon(L"dyePowder_red",slotSize*14,slotSize*5,slotSize*(14+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_pink",new SimpleIcon(L"dyePowder_pink",slotSize*15,slotSize*5,slotSize*(15+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeWood",new SimpleIcon(L"pickaxeWood",slotSize*0,slotSize*6,slotSize*(0+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeStone",new SimpleIcon(L"pickaxeStone",slotSize*1,slotSize*6,slotSize*(1+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeIron",new SimpleIcon(L"pickaxeIron",slotSize*2,slotSize*6,slotSize*(2+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeDiamond",new SimpleIcon(L"pickaxeDiamond",slotSize*3,slotSize*6,slotSize*(3+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeGold",new SimpleIcon(L"pickaxeGold",slotSize*4,slotSize*6,slotSize*(4+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_0",new SimpleIcon(L"bow_pull_0",slotSize*5,slotSize*6,slotSize*(5+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrotOnAStick",new SimpleIcon(L"carrotOnAStick",slotSize*6,slotSize*6,slotSize*(6+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"leather",new SimpleIcon(L"leather",slotSize*7,slotSize*6,slotSize*(7+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"saddle",new SimpleIcon(L"saddle",slotSize*8,slotSize*6,slotSize*(8+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"beefRaw",new SimpleIcon(L"beefRaw",slotSize*9,slotSize*6,slotSize*(9+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"beefCooked",new SimpleIcon(L"beefCooked",slotSize*10,slotSize*6,slotSize*(10+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"enderPearl",new SimpleIcon(L"enderPearl",slotSize*11,slotSize*6,slotSize*(11+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"blazeRod",new SimpleIcon(L"blazeRod",slotSize*12,slotSize*6,slotSize*(12+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon",new SimpleIcon(L"melon",slotSize*13,slotSize*6,slotSize*(13+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_green",new SimpleIcon(L"dyePowder_green",slotSize*14,slotSize*6,slotSize*(14+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_lime",new SimpleIcon(L"dyePowder_lime",slotSize*15,slotSize*6,slotSize*(15+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetWood",new SimpleIcon(L"hatchetWood",slotSize*0,slotSize*7,slotSize*(0+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetStone",new SimpleIcon(L"hatchetStone",slotSize*1,slotSize*7,slotSize*(1+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetIron",new SimpleIcon(L"hatchetIron",slotSize*2,slotSize*7,slotSize*(2+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetDiamond",new SimpleIcon(L"hatchetDiamond",slotSize*3,slotSize*7,slotSize*(3+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetGold",new SimpleIcon(L"hatchetGold",slotSize*4,slotSize*7,slotSize*(4+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_1",new SimpleIcon(L"bow_pull_1",slotSize*5,slotSize*7,slotSize*(5+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoBaked",new SimpleIcon(L"potatoBaked",slotSize*6,slotSize*7,slotSize*(6+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"potato",new SimpleIcon(L"potato",slotSize*7,slotSize*7,slotSize*(7+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots",new SimpleIcon(L"carrots",slotSize*8,slotSize*7,slotSize*(8+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"chickenRaw",new SimpleIcon(L"chickenRaw",slotSize*9,slotSize*7,slotSize*(9+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"chickenCooked",new SimpleIcon(L"chickenCooked",slotSize*10,slotSize*7,slotSize*(10+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"ghastTear",new SimpleIcon(L"ghastTear",slotSize*11,slotSize*7,slotSize*(11+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldNugget",new SimpleIcon(L"goldNugget",slotSize*12,slotSize*7,slotSize*(12+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalkSeeds",new SimpleIcon(L"netherStalkSeeds",slotSize*13,slotSize*7,slotSize*(13+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_brown",new SimpleIcon(L"dyePowder_brown",slotSize*14,slotSize*7,slotSize*(14+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_yellow",new SimpleIcon(L"dyePowder_yellow",slotSize*15,slotSize*7,slotSize*(15+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeWood",new SimpleIcon(L"hoeWood",slotSize*0,slotSize*8,slotSize*(0+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeStone",new SimpleIcon(L"hoeStone",slotSize*1,slotSize*8,slotSize*(1+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeIron",new SimpleIcon(L"hoeIron",slotSize*2,slotSize*8,slotSize*(2+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeDiamond",new SimpleIcon(L"hoeDiamond",slotSize*3,slotSize*8,slotSize*(3+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeGold",new SimpleIcon(L"hoeGold",slotSize*4,slotSize*8,slotSize*(4+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_2",new SimpleIcon(L"bow_pull_2",slotSize*5,slotSize*8,slotSize*(5+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoPoisonous",new SimpleIcon(L"potatoPoisonous",slotSize*6,slotSize*8,slotSize*(6+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecart",new SimpleIcon(L"minecart",slotSize*7,slotSize*8,slotSize*(7+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"boat",new SimpleIcon(L"boat",slotSize*8,slotSize*8,slotSize*(8+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"speckledMelon",new SimpleIcon(L"speckledMelon",slotSize*9,slotSize*8,slotSize*(9+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"fermentedSpiderEye",new SimpleIcon(L"fermentedSpiderEye",slotSize*10,slotSize*8,slotSize*(10+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"spiderEye",new SimpleIcon(L"spiderEye",slotSize*11,slotSize*8,slotSize*(11+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion",new SimpleIcon(L"potion",slotSize*12,slotSize*8,slotSize*(12+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"glassBottle",new SimpleIcon(L"glassBottle",slotSize*12,slotSize*8,slotSize*(12+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion_contents",new SimpleIcon(L"potion_contents",slotSize*13,slotSize*8,slotSize*(13+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_blue",new SimpleIcon(L"dyePowder_blue",slotSize*14,slotSize*8,slotSize*(14+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_lightBlue",new SimpleIcon(L"dyePowder_lightBlue",slotSize*15,slotSize*8,slotSize*(15+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetCloth_overlay",new SimpleIcon(L"helmetCloth_overlay",slotSize*0,slotSize*9,slotSize*(0+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator",new SimpleIcon(L"comparator",slotSize*5,slotSize*9,slotSize*(5+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrotGolden",new SimpleIcon(L"carrotGolden",slotSize*6,slotSize*9,slotSize*(6+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartChest",new SimpleIcon(L"minecartChest",slotSize*7,slotSize*9,slotSize*(7+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkinPie",new SimpleIcon(L"pumpkinPie",slotSize*8,slotSize*9,slotSize*(8+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"monsterPlacer",new SimpleIcon(L"monsterPlacer",slotSize*9,slotSize*9,slotSize*(9+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion_splash",new SimpleIcon(L"potion_splash",slotSize*10,slotSize*9,slotSize*(10+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"eyeOfEnder",new SimpleIcon(L"eyeOfEnder",slotSize*11,slotSize*9,slotSize*(11+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron",new SimpleIcon(L"cauldron",slotSize*12,slotSize*9,slotSize*(12+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"blazePowder",new SimpleIcon(L"blazePowder",slotSize*13,slotSize*9,slotSize*(13+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_purple",new SimpleIcon(L"dyePowder_purple",slotSize*14,slotSize*9,slotSize*(14+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_magenta",new SimpleIcon(L"dyePowder_magenta",slotSize*15,slotSize*9,slotSize*(15+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateCloth_overlay",new SimpleIcon(L"chestplateCloth_overlay",slotSize*0,slotSize*10,slotSize*(0+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherbrick",new SimpleIcon(L"netherbrick",slotSize*5,slotSize*10,slotSize*(5+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartFurnace",new SimpleIcon(L"minecartFurnace",slotSize*7,slotSize*10,slotSize*(7+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"monsterPlacer_overlay",new SimpleIcon(L"monsterPlacer_overlay",slotSize*9,slotSize*10,slotSize*(9+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"ruby",new SimpleIcon(L"ruby",slotSize*10,slotSize*10,slotSize*(10+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"expBottle",new SimpleIcon(L"expBottle",slotSize*11,slotSize*10,slotSize*(11+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand",new SimpleIcon(L"brewingStand",slotSize*12,slotSize*10,slotSize*(12+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"magmaCream",new SimpleIcon(L"magmaCream",slotSize*13,slotSize*10,slotSize*(13+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_cyan",new SimpleIcon(L"dyePowder_cyan",slotSize*14,slotSize*10,slotSize*(14+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_orange",new SimpleIcon(L"dyePowder_orange",slotSize*15,slotSize*10,slotSize*(15+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsCloth_overlay",new SimpleIcon(L"leggingsCloth_overlay",slotSize*0,slotSize*11,slotSize*(0+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartHopper",new SimpleIcon(L"minecartHopper",slotSize*7,slotSize*11,slotSize*(7+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper",new SimpleIcon(L"hopper",slotSize*8,slotSize*11,slotSize*(8+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStar",new SimpleIcon(L"netherStar",slotSize*9,slotSize*11,slotSize*(9+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"emerald",new SimpleIcon(L"emerald",slotSize*10,slotSize*11,slotSize*(10+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"writingBook",new SimpleIcon(L"writingBook",slotSize*11,slotSize*11,slotSize*(11+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"writtenBook",new SimpleIcon(L"writtenBook",slotSize*12,slotSize*11,slotSize*(12+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"flowerPot",new SimpleIcon(L"flowerPot",slotSize*13,slotSize*11,slotSize*(13+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_silver",new SimpleIcon(L"dyePowder_silver",slotSize*14,slotSize*11,slotSize*(14+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_white",new SimpleIcon(L"dyePowder_white",slotSize*15,slotSize*11,slotSize*(15+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsCloth_overlay",new SimpleIcon(L"bootsCloth_overlay",slotSize*0,slotSize*12,slotSize*(0+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartTnt",new SimpleIcon(L"minecartTnt",slotSize*7,slotSize*12,slotSize*(7+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworks",new SimpleIcon(L"fireworks",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworksCharge",new SimpleIcon(L"fireworksCharge",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworksCharge_overlay",new SimpleIcon(L"fireworksCharge_overlay",slotSize*11,slotSize*12,slotSize*(11+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherquartz",new SimpleIcon(L"netherquartz",slotSize*12,slotSize*12,slotSize*(12+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"emptyMap",new SimpleIcon(L"emptyMap",slotSize*13,slotSize*12,slotSize*(13+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"frame",new SimpleIcon(L"frame",slotSize*14,slotSize*12,slotSize*(14+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantedBook",new SimpleIcon(L"enchantedBook",slotSize*15,slotSize*12,slotSize*(15+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_skeleton",new SimpleIcon(L"skull_skeleton",slotSize*0,slotSize*14,slotSize*(0+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_wither",new SimpleIcon(L"skull_wither",slotSize*1,slotSize*14,slotSize*(1+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_zombie",new SimpleIcon(L"skull_zombie",slotSize*2,slotSize*14,slotSize*(2+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_char",new SimpleIcon(L"skull_char",slotSize*3,slotSize*14,slotSize*(3+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_creeper",new SimpleIcon(L"skull_creeper",slotSize*4,slotSize*14,slotSize*(4+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"dragonFireball",new SimpleIcon(L"dragonFireball",slotSize*15,slotSize*14,slotSize*(15+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_13",new SimpleIcon(L"record_13",slotSize*0,slotSize*15,slotSize*(0+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_cat",new SimpleIcon(L"record_cat",slotSize*1,slotSize*15,slotSize*(1+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_blocks",new SimpleIcon(L"record_blocks",slotSize*2,slotSize*15,slotSize*(2+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_chirp",new SimpleIcon(L"record_chirp",slotSize*3,slotSize*15,slotSize*(3+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_far",new SimpleIcon(L"record_far",slotSize*4,slotSize*15,slotSize*(4+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_mall",new SimpleIcon(L"record_mall",slotSize*5,slotSize*15,slotSize*(5+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_mellohi",new SimpleIcon(L"record_mellohi",slotSize*6,slotSize*15,slotSize*(6+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_stal",new SimpleIcon(L"record_stal",slotSize*7,slotSize*15,slotSize*(7+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_strad",new SimpleIcon(L"record_strad",slotSize*8,slotSize*15,slotSize*(8+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_ward",new SimpleIcon(L"record_ward",slotSize*9,slotSize*15,slotSize*(9+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_11",new SimpleIcon(L"record_11",slotSize*10,slotSize*15,slotSize*(10+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_where are we now",new SimpleIcon(L"record_where are we now",slotSize*11,slotSize*15,slotSize*(11+1),slotSize*(15+1)))); - - // Special cases - ClockTexture *dataClock = new ClockTexture(); - Icon *oldClock = texturesByName[L"clock"]; - dataClock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clock"] = dataClock; - - ClockTexture *clock = new ClockTexture(0, dataClock); - oldClock = texturesByName[L"clockP0"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP0"] = clock; - - clock = new ClockTexture(1, dataClock); - oldClock = texturesByName[L"clockP1"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP1"] = clock; - - clock = new ClockTexture(2, dataClock); - oldClock = texturesByName[L"clockP2"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP2"] = clock; - - clock = new ClockTexture(3, dataClock); - oldClock = texturesByName[L"clockP3"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP3"] = clock; - - CompassTexture *dataCompass = new CompassTexture(); - Icon *oldCompass = texturesByName[L"compass"]; - dataCompass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compass"] = dataCompass; - - CompassTexture *compass = new CompassTexture(0, dataCompass); - oldCompass = texturesByName[L"compassP0"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP0"] = compass; - - compass = new CompassTexture(1, dataCompass); - oldCompass = texturesByName[L"compassP1"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP1"] = compass; - - compass = new CompassTexture(2, dataCompass); - oldCompass = texturesByName[L"compassP2"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP2"] = compass; - - compass = new CompassTexture(3, dataCompass); - oldCompass = texturesByName[L"compassP3"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP3"] = compass; - } - else - { - texturesByName.insert(stringIconMap::value_type(L"grass_top",new SimpleIcon(L"grass_top",slotSize*0,slotSize*0,slotSize*(0+1),slotSize*(0+1)))); - texturesByName[L"grass_top"]->setFlags(Icon::IS_GRASS_TOP); // 4J added for faster determination of texture type in tesselation - texturesByName.insert(stringIconMap::value_type(L"stone",new SimpleIcon(L"stone",slotSize*1,slotSize*0,slotSize*(1+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"dirt",new SimpleIcon(L"dirt",slotSize*2,slotSize*0,slotSize*(2+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"grass_side",new SimpleIcon(L"grass_side",slotSize*3,slotSize*0,slotSize*(3+1),slotSize*(0+1)))); - texturesByName[L"grass_side"]->setFlags(Icon::IS_GRASS_SIDE); // 4J added for faster determination of texture type in tesselation - texturesByName.insert(stringIconMap::value_type(L"wood",new SimpleIcon(L"wood",slotSize*4,slotSize*0,slotSize*(4+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneslab_side",new SimpleIcon(L"stoneslab_side",slotSize*5,slotSize*0,slotSize*(5+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneslab_top",new SimpleIcon(L"stoneslab_top",slotSize*6,slotSize*0,slotSize*(6+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"brick",new SimpleIcon(L"brick",slotSize*7,slotSize*0,slotSize*(7+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_side",new SimpleIcon(L"tnt_side",slotSize*8,slotSize*0,slotSize*(8+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_top",new SimpleIcon(L"tnt_top",slotSize*9,slotSize*0,slotSize*(9+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_bottom",new SimpleIcon(L"tnt_bottom",slotSize*10,slotSize*0,slotSize*(10+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"web",new SimpleIcon(L"web",slotSize*11,slotSize*0,slotSize*(11+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"rose",new SimpleIcon(L"rose",slotSize*12,slotSize*0,slotSize*(12+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flower",new SimpleIcon(L"flower",slotSize*13,slotSize*0,slotSize*(13+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"portal",new SimpleIcon(L"portal",slotSize*14,slotSize*0,slotSize*(14+1),slotSize*(0+1)))); - texturesToAnimate.push_back(std::pair(L"portal",L"portal")); - texturesByName.insert(stringIconMap::value_type(L"sapling",new SimpleIcon(L"sapling",slotSize*15,slotSize*0,slotSize*(15+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebrick",new SimpleIcon(L"stonebrick",slotSize*0,slotSize*1,slotSize*(0+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bedrock",new SimpleIcon(L"bedrock",slotSize*1,slotSize*1,slotSize*(1+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"sand",new SimpleIcon(L"sand",slotSize*2,slotSize*1,slotSize*(2+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"gravel",new SimpleIcon(L"gravel",slotSize*3,slotSize*1,slotSize*(3+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_side",new SimpleIcon(L"tree_side",slotSize*4,slotSize*1,slotSize*(4+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_top",new SimpleIcon(L"tree_top",slotSize*5,slotSize*1,slotSize*(5+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockIron",new SimpleIcon(L"blockIron",slotSize*6,slotSize*1,slotSize*(6+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockGold",new SimpleIcon(L"blockGold",slotSize*7,slotSize*1,slotSize*(7+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockDiamond",new SimpleIcon(L"blockDiamond",slotSize*8,slotSize*1,slotSize*(8+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockEmerald",new SimpleIcon(L"blockEmerald",slotSize*9,slotSize*1,slotSize*(9+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockRedstone",new SimpleIcon(L"blockRedstone",slotSize*10,slotSize*1,slotSize*(10+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"dropper_front",new SimpleIcon(L"dropper_front",slotSize*11,slotSize*1,slotSize*(11+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_red",new SimpleIcon(L"mushroom_red",slotSize*12,slotSize*1,slotSize*(12+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_brown",new SimpleIcon(L"mushroom_brown",slotSize*13,slotSize*1,slotSize*(13+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_jungle",new SimpleIcon(L"sapling_jungle",slotSize*14,slotSize*1,slotSize*(14+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"fire_0",new SimpleIcon(L"fire_0",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesToAnimate.push_back(std::pair(L"fire_0",L"fire_0")); - texturesByName.insert(stringIconMap::value_type(L"oreGold",new SimpleIcon(L"oreGold",slotSize*0,slotSize*2,slotSize*(0+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreIron",new SimpleIcon(L"oreIron",slotSize*1,slotSize*2,slotSize*(1+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreCoal",new SimpleIcon(L"oreCoal",slotSize*2,slotSize*2,slotSize*(2+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bookshelf",new SimpleIcon(L"bookshelf",slotSize*3,slotSize*2,slotSize*(3+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneMoss",new SimpleIcon(L"stoneMoss",slotSize*4,slotSize*2,slotSize*(4+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"obsidian",new SimpleIcon(L"obsidian",slotSize*5,slotSize*2,slotSize*(5+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"grass_side_overlay",new SimpleIcon(L"grass_side_overlay",slotSize*6,slotSize*2,slotSize*(6+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"tallgrass",new SimpleIcon(L"tallgrass",slotSize*7,slotSize*2,slotSize*(7+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dispenser_front_vertical",new SimpleIcon(L"dispenser_front_vertical",slotSize*8,slotSize*2,slotSize*(8+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"beacon",new SimpleIcon(L"beacon",slotSize*9,slotSize*2,slotSize*(9+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dropper_front_vertical",new SimpleIcon(L"dropper_front_vertical",slotSize*10,slotSize*2,slotSize*(10+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_top",new SimpleIcon(L"workbench_top",slotSize*11,slotSize*2,slotSize*(11+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_front",new SimpleIcon(L"furnace_front",slotSize*12,slotSize*2,slotSize*(12+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_side",new SimpleIcon(L"furnace_side",slotSize*13,slotSize*2,slotSize*(13+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dispenser_front",new SimpleIcon(L"dispenser_front",slotSize*14,slotSize*2,slotSize*(14+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"fire_1",new SimpleIcon(L"fire_1",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesToAnimate.push_back(std::pair(L"fire_1",L"fire_1")); - texturesByName.insert(stringIconMap::value_type(L"sponge",new SimpleIcon(L"sponge",slotSize*0,slotSize*3,slotSize*(0+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"glass",new SimpleIcon(L"glass",slotSize*1,slotSize*3,slotSize*(1+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreDiamond",new SimpleIcon(L"oreDiamond",slotSize*2,slotSize*3,slotSize*(2+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreRedstone",new SimpleIcon(L"oreRedstone",slotSize*3,slotSize*3,slotSize*(3+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves",new SimpleIcon(L"leaves",slotSize*4,slotSize*3,slotSize*(4+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_opaque",new SimpleIcon(L"leaves_opaque",slotSize*5,slotSize*3,slotSize*(5+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth",new SimpleIcon(L"stonebricksmooth",slotSize*6,slotSize*3,slotSize*(6+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"deadbush",new SimpleIcon(L"deadbush",slotSize*7,slotSize*3,slotSize*(7+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"fern",new SimpleIcon(L"fern",slotSize*8,slotSize*3,slotSize*(8+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"daylightDetector_top",new SimpleIcon(L"daylightDetector_top",slotSize*9,slotSize*3,slotSize*(9+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"daylightDetector_side",new SimpleIcon(L"daylightDetector_side",slotSize*10,slotSize*3,slotSize*(10+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_side",new SimpleIcon(L"workbench_side",slotSize*11,slotSize*3,slotSize*(11+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_front",new SimpleIcon(L"workbench_front",slotSize*12,slotSize*3,slotSize*(12+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_front_lit",new SimpleIcon(L"furnace_front_lit",slotSize*13,slotSize*3,slotSize*(13+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_top",new SimpleIcon(L"furnace_top",slotSize*14,slotSize*3,slotSize*(14+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_spruce",new SimpleIcon(L"sapling_spruce",slotSize*15,slotSize*3,slotSize*(15+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_0",new SimpleIcon(L"cloth_0",slotSize*0,slotSize*4,slotSize*(0+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mobSpawner",new SimpleIcon(L"mobSpawner",slotSize*1,slotSize*4,slotSize*(1+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"snow",new SimpleIcon(L"snow",slotSize*2,slotSize*4,slotSize*(2+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"ice",new SimpleIcon(L"ice",slotSize*3,slotSize*4,slotSize*(3+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"snow_side",new SimpleIcon(L"snow_side",slotSize*4,slotSize*4,slotSize*(4+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_top",new SimpleIcon(L"cactus_top",slotSize*5,slotSize*4,slotSize*(5+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_side",new SimpleIcon(L"cactus_side",slotSize*6,slotSize*4,slotSize*(6+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_bottom",new SimpleIcon(L"cactus_bottom",slotSize*7,slotSize*4,slotSize*(7+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clay",new SimpleIcon(L"clay",slotSize*8,slotSize*4,slotSize*(8+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"reeds",new SimpleIcon(L"reeds",slotSize*9,slotSize*4,slotSize*(9+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"musicBlock",new SimpleIcon(L"musicBlock",slotSize*10,slotSize*4,slotSize*(10+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"jukebox_top",new SimpleIcon(L"jukebox_top",slotSize*11,slotSize*4,slotSize*(11+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"waterlily",new SimpleIcon(L"waterlily",slotSize*12,slotSize*4,slotSize*(12+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mycel_side",new SimpleIcon(L"mycel_side",slotSize*13,slotSize*4,slotSize*(13+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mycel_top",new SimpleIcon(L"mycel_top",slotSize*14,slotSize*4,slotSize*(14+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_birch",new SimpleIcon(L"sapling_birch",slotSize*15,slotSize*4,slotSize*(15+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"torch",new SimpleIcon(L"torch",slotSize*0,slotSize*5,slotSize*(0+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood_upper",new SimpleIcon(L"doorWood_upper",slotSize*1,slotSize*5,slotSize*(1+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron_upper",new SimpleIcon(L"doorIron_upper",slotSize*2,slotSize*5,slotSize*(2+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"ladder",new SimpleIcon(L"ladder",slotSize*3,slotSize*5,slotSize*(3+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"trapdoor",new SimpleIcon(L"trapdoor",slotSize*4,slotSize*5,slotSize*(4+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fenceIron",new SimpleIcon(L"fenceIron",slotSize*5,slotSize*5,slotSize*(5+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"farmland_wet",new SimpleIcon(L"farmland_wet",slotSize*6,slotSize*5,slotSize*(6+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"farmland_dry",new SimpleIcon(L"farmland_dry",slotSize*7,slotSize*5,slotSize*(7+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_0",new SimpleIcon(L"crops_0",slotSize*8,slotSize*5,slotSize*(8+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_1",new SimpleIcon(L"crops_1",slotSize*9,slotSize*5,slotSize*(9+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_2",new SimpleIcon(L"crops_2",slotSize*10,slotSize*5,slotSize*(10+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_3",new SimpleIcon(L"crops_3",slotSize*11,slotSize*5,slotSize*(11+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_4",new SimpleIcon(L"crops_4",slotSize*12,slotSize*5,slotSize*(12+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_5",new SimpleIcon(L"crops_5",slotSize*13,slotSize*5,slotSize*(13+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_6",new SimpleIcon(L"crops_6",slotSize*14,slotSize*5,slotSize*(14+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_7",new SimpleIcon(L"crops_7",slotSize*15,slotSize*5,slotSize*(15+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"lever",new SimpleIcon(L"lever",slotSize*0,slotSize*6,slotSize*(0+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood_lower",new SimpleIcon(L"doorWood_lower",slotSize*1,slotSize*6,slotSize*(1+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron_lower",new SimpleIcon(L"doorIron_lower",slotSize*2,slotSize*6,slotSize*(2+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"redtorch_lit",new SimpleIcon(L"redtorch_lit",slotSize*3,slotSize*6,slotSize*(3+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_mossy",new SimpleIcon(L"stonebricksmooth_mossy",slotSize*4,slotSize*6,slotSize*(4+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_cracked",new SimpleIcon(L"stonebricksmooth_cracked",slotSize*5,slotSize*6,slotSize*(5+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_top",new SimpleIcon(L"pumpkin_top",slotSize*6,slotSize*6,slotSize*(6+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hellrock",new SimpleIcon(L"hellrock",slotSize*7,slotSize*6,slotSize*(7+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hellsand",new SimpleIcon(L"hellsand",slotSize*8,slotSize*6,slotSize*(8+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"lightgem",new SimpleIcon(L"lightgem",slotSize*9,slotSize*6,slotSize*(9+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_top_sticky",new SimpleIcon(L"piston_top_sticky",slotSize*10,slotSize*6,slotSize*(10+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_top",new SimpleIcon(L"piston_top",slotSize*11,slotSize*6,slotSize*(11+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_side",new SimpleIcon(L"piston_side",slotSize*12,slotSize*6,slotSize*(12+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_bottom",new SimpleIcon(L"piston_bottom",slotSize*13,slotSize*6,slotSize*(13+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_inner_top",new SimpleIcon(L"piston_inner_top",slotSize*14,slotSize*6,slotSize*(14+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stem_straight",new SimpleIcon(L"stem_straight",slotSize*15,slotSize*6,slotSize*(15+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"rail_turn",new SimpleIcon(L"rail_turn",slotSize*0,slotSize*7,slotSize*(0+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_15",new SimpleIcon(L"cloth_15",slotSize*1,slotSize*7,slotSize*(1+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_7",new SimpleIcon(L"cloth_7",slotSize*2,slotSize*7,slotSize*(2+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"redtorch",new SimpleIcon(L"redtorch",slotSize*3,slotSize*7,slotSize*(3+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_spruce",new SimpleIcon(L"tree_spruce",slotSize*4,slotSize*7,slotSize*(4+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_birch",new SimpleIcon(L"tree_birch",slotSize*5,slotSize*7,slotSize*(5+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_side",new SimpleIcon(L"pumpkin_side",slotSize*6,slotSize*7,slotSize*(6+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_face",new SimpleIcon(L"pumpkin_face",slotSize*7,slotSize*7,slotSize*(7+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_jack",new SimpleIcon(L"pumpkin_jack",slotSize*8,slotSize*7,slotSize*(8+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_top",new SimpleIcon(L"cake_top",slotSize*9,slotSize*7,slotSize*(9+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_side",new SimpleIcon(L"cake_side",slotSize*10,slotSize*7,slotSize*(10+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_inner",new SimpleIcon(L"cake_inner",slotSize*11,slotSize*7,slotSize*(11+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_bottom",new SimpleIcon(L"cake_bottom",slotSize*12,slotSize*7,slotSize*(12+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_red",new SimpleIcon(L"mushroom_skin_red",slotSize*13,slotSize*7,slotSize*(13+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_brown",new SimpleIcon(L"mushroom_skin_brown",slotSize*14,slotSize*7,slotSize*(14+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"stem_bent",new SimpleIcon(L"stem_bent",slotSize*15,slotSize*7,slotSize*(15+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"rail",new SimpleIcon(L"rail",slotSize*0,slotSize*8,slotSize*(0+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_14",new SimpleIcon(L"cloth_14",slotSize*1,slotSize*8,slotSize*(1+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_6",new SimpleIcon(L"cloth_6",slotSize*2,slotSize*8,slotSize*(2+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"repeater",new SimpleIcon(L"repeater",slotSize*3,slotSize*8,slotSize*(3+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_spruce",new SimpleIcon(L"leaves_spruce",slotSize*4,slotSize*8,slotSize*(4+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_spruce_opaque",new SimpleIcon(L"leaves_spruce_opaque",slotSize*5,slotSize*8,slotSize*(5+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_top",new SimpleIcon(L"bed_feet_top",slotSize*6,slotSize*8,slotSize*(6+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_top",new SimpleIcon(L"bed_head_top",slotSize*7,slotSize*8,slotSize*(7+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon_side",new SimpleIcon(L"melon_side",slotSize*8,slotSize*8,slotSize*(8+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon_top",new SimpleIcon(L"melon_top",slotSize*9,slotSize*8,slotSize*(9+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_top",new SimpleIcon(L"cauldron_top",slotSize*10,slotSize*8,slotSize*(10+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_inner",new SimpleIcon(L"cauldron_inner",slotSize*11,slotSize*8,slotSize*(11+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_stem",new SimpleIcon(L"mushroom_skin_stem",slotSize*13,slotSize*8,slotSize*(13+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_inside",new SimpleIcon(L"mushroom_inside",slotSize*14,slotSize*8,slotSize*(14+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"vine",new SimpleIcon(L"vine",slotSize*15,slotSize*8,slotSize*(15+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockLapis",new SimpleIcon(L"blockLapis",slotSize*0,slotSize*9,slotSize*(0+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_13",new SimpleIcon(L"cloth_13",slotSize*1,slotSize*9,slotSize*(1+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_5",new SimpleIcon(L"cloth_5",slotSize*2,slotSize*9,slotSize*(2+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"repeater_lit",new SimpleIcon(L"repeater_lit",slotSize*3,slotSize*9,slotSize*(3+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"thinglass_top",new SimpleIcon(L"thinglass_top",slotSize*4,slotSize*9,slotSize*(4+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_end",new SimpleIcon(L"bed_feet_end",slotSize*5,slotSize*9,slotSize*(5+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_side",new SimpleIcon(L"bed_feet_side",slotSize*6,slotSize*9,slotSize*(6+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_side",new SimpleIcon(L"bed_head_side",slotSize*7,slotSize*9,slotSize*(7+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_end",new SimpleIcon(L"bed_head_end",slotSize*8,slotSize*9,slotSize*(8+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_jungle",new SimpleIcon(L"tree_jungle",slotSize*9,slotSize*9,slotSize*(9+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_side",new SimpleIcon(L"cauldron_side",slotSize*10,slotSize*9,slotSize*(10+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_bottom",new SimpleIcon(L"cauldron_bottom",slotSize*11,slotSize*9,slotSize*(11+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand_base",new SimpleIcon(L"brewingStand_base",slotSize*12,slotSize*9,slotSize*(12+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand",new SimpleIcon(L"brewingStand",slotSize*13,slotSize*9,slotSize*(13+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_top",new SimpleIcon(L"endframe_top",slotSize*14,slotSize*9,slotSize*(14+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_side",new SimpleIcon(L"endframe_side",slotSize*15,slotSize*9,slotSize*(15+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreLapis",new SimpleIcon(L"oreLapis",slotSize*0,slotSize*10,slotSize*(0+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_12",new SimpleIcon(L"cloth_12",slotSize*1,slotSize*10,slotSize*(1+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_4",new SimpleIcon(L"cloth_4",slotSize*2,slotSize*10,slotSize*(2+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldenRail",new SimpleIcon(L"goldenRail",slotSize*3,slotSize*10,slotSize*(3+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_cross",new SimpleIcon(L"redstoneDust_cross",slotSize*4,slotSize*10,slotSize*(4+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_line",new SimpleIcon(L"redstoneDust_line",slotSize*5,slotSize*10,slotSize*(5+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_top",new SimpleIcon(L"enchantment_top",slotSize*6,slotSize*10,slotSize*(6+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dragonEgg",new SimpleIcon(L"dragonEgg",slotSize*7,slotSize*10,slotSize*(7+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_2",new SimpleIcon(L"cocoa_2",slotSize*8,slotSize*10,slotSize*(8+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_1",new SimpleIcon(L"cocoa_1",slotSize*9,slotSize*10,slotSize*(9+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_0",new SimpleIcon(L"cocoa_0",slotSize*10,slotSize*10,slotSize*(10+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreEmerald",new SimpleIcon(L"oreEmerald",slotSize*11,slotSize*10,slotSize*(11+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"tripWireSource",new SimpleIcon(L"tripWireSource",slotSize*12,slotSize*10,slotSize*(12+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"tripWire",new SimpleIcon(L"tripWire",slotSize*13,slotSize*10,slotSize*(13+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_eye",new SimpleIcon(L"endframe_eye",slotSize*14,slotSize*10,slotSize*(14+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"whiteStone",new SimpleIcon(L"whiteStone",slotSize*15,slotSize*10,slotSize*(15+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_top",new SimpleIcon(L"sandstone_top",slotSize*0,slotSize*11,slotSize*(0+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_11",new SimpleIcon(L"cloth_11",slotSize*1,slotSize*11,slotSize*(1+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_3",new SimpleIcon(L"cloth_3",slotSize*2,slotSize*11,slotSize*(2+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldenRail_powered",new SimpleIcon(L"goldenRail_powered",slotSize*3,slotSize*11,slotSize*(3+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_cross_overlay",new SimpleIcon(L"redstoneDust_cross_overlay",slotSize*4,slotSize*11,slotSize*(4+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_line_overlay",new SimpleIcon(L"redstoneDust_line_overlay",slotSize*5,slotSize*11,slotSize*(5+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_side",new SimpleIcon(L"enchantment_side",slotSize*6,slotSize*11,slotSize*(6+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_bottom",new SimpleIcon(L"enchantment_bottom",slotSize*7,slotSize*11,slotSize*(7+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"commandBlock",new SimpleIcon(L"commandBlock",slotSize*8,slotSize*11,slotSize*(8+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"itemframe_back",new SimpleIcon(L"itemframe_back",slotSize*9,slotSize*11,slotSize*(9+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"flowerPot",new SimpleIcon(L"flowerPot",slotSize*10,slotSize*11,slotSize*(10+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator",new SimpleIcon(L"comparator",slotSize*11,slotSize*11,slotSize*(11+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator_lit",new SimpleIcon(L"comparator_lit",slotSize*12,slotSize*11,slotSize*(12+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"activatorRail",new SimpleIcon(L"activatorRail",slotSize*13,slotSize*11,slotSize*(13+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"activatorRail_powered",new SimpleIcon(L"activatorRail_powered",slotSize*14,slotSize*11,slotSize*(14+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherquartz",new SimpleIcon(L"netherquartz",slotSize*15,slotSize*11,slotSize*(15+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_side",new SimpleIcon(L"sandstone_side",slotSize*0,slotSize*12,slotSize*(0+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_10",new SimpleIcon(L"cloth_10",slotSize*1,slotSize*12,slotSize*(1+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_2",new SimpleIcon(L"cloth_2",slotSize*2,slotSize*12,slotSize*(2+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"detectorRail",new SimpleIcon(L"detectorRail",slotSize*3,slotSize*12,slotSize*(3+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_jungle",new SimpleIcon(L"leaves_jungle",slotSize*4,slotSize*12,slotSize*(4+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_jungle_opaque",new SimpleIcon(L"leaves_jungle_opaque",slotSize*5,slotSize*12,slotSize*(5+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_spruce",new SimpleIcon(L"wood_spruce",slotSize*6,slotSize*12,slotSize*(6+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_jungle",new SimpleIcon(L"wood_jungle",slotSize*7,slotSize*12,slotSize*(7+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_0",new SimpleIcon(L"carrots_0",slotSize*8,slotSize*12,slotSize*(8+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_1",new SimpleIcon(L"carrots_1",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_2",new SimpleIcon(L"carrots_2",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_3",new SimpleIcon(L"carrots_3",slotSize*11,slotSize*12,slotSize*(11+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_0",new SimpleIcon(L"potatoes_0",slotSize*8,slotSize*12,slotSize*(8+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_1",new SimpleIcon(L"potatoes_1",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_2",new SimpleIcon(L"potatoes_2",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_3",new SimpleIcon(L"potatoes_3",slotSize*12,slotSize*12,slotSize*(12+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"water",new SimpleIcon(L"water",slotSize*13,slotSize*12,slotSize*(13+1),slotSize*(12+1)))); - texturesToAnimate.push_back(std::pair(L"water",L"water")); - texturesByName.insert(stringIconMap::value_type(L"water_flow",new SimpleIcon(L"water_flow",slotSize*14,slotSize*12,slotSize*(14+2),slotSize*(12+2)))); - texturesToAnimate.push_back(std::pair(L"water_flow",L"water_flow")); - texturesByName.insert(stringIconMap::value_type(L"sandstone_bottom",new SimpleIcon(L"sandstone_bottom",slotSize*0,slotSize*13,slotSize*(0+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_9",new SimpleIcon(L"cloth_9",slotSize*1,slotSize*13,slotSize*(1+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_1",new SimpleIcon(L"cloth_1",slotSize*2,slotSize*13,slotSize*(2+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneLight",new SimpleIcon(L"redstoneLight",slotSize*3,slotSize*13,slotSize*(3+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneLight_lit",new SimpleIcon(L"redstoneLight_lit",slotSize*4,slotSize*13,slotSize*(4+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_carved",new SimpleIcon(L"stonebricksmooth_carved",slotSize*5,slotSize*13,slotSize*(5+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_birch",new SimpleIcon(L"wood_birch",slotSize*6,slotSize*13,slotSize*(6+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_base",new SimpleIcon(L"anvil_base",slotSize*7,slotSize*13,slotSize*(7+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top_damaged_1",new SimpleIcon(L"anvil_top_damaged_1",slotSize*8,slotSize*13,slotSize*(8+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_chiseled_top",new SimpleIcon(L"quartzblock_chiseled_top",slotSize*9,slotSize*13,slotSize*(9+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_lines_top",new SimpleIcon(L"quartzblock_lines_top",slotSize*10,slotSize*13,slotSize*(10+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_top",new SimpleIcon(L"quartzblock_top",slotSize*11,slotSize*13,slotSize*(11+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper",new SimpleIcon(L"hopper",slotSize*12,slotSize*13,slotSize*(12+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"detectorRail_on",new SimpleIcon(L"detectorRail_on",slotSize*13,slotSize*13,slotSize*(13+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherBrick",new SimpleIcon(L"netherBrick",slotSize*0,slotSize*14,slotSize*(0+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_8",new SimpleIcon(L"cloth_8",slotSize*1,slotSize*14,slotSize*(1+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_0",new SimpleIcon(L"netherStalk_0",slotSize*2,slotSize*14,slotSize*(2+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_1",new SimpleIcon(L"netherStalk_1",slotSize*3,slotSize*14,slotSize*(3+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_2",new SimpleIcon(L"netherStalk_2",slotSize*4,slotSize*14,slotSize*(4+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_carved",new SimpleIcon(L"sandstone_carved",slotSize*5,slotSize*14,slotSize*(5+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_smooth",new SimpleIcon(L"sandstone_smooth",slotSize*6,slotSize*14,slotSize*(6+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top",new SimpleIcon(L"anvil_top",slotSize*7,slotSize*14,slotSize*(7+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top_damaged_2",new SimpleIcon(L"anvil_top_damaged_2",slotSize*8,slotSize*14,slotSize*(8+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_chiseled",new SimpleIcon(L"quartzblock_chiseled",slotSize*9,slotSize*14,slotSize*(9+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_lines",new SimpleIcon(L"quartzblock_lines",slotSize*10,slotSize*14,slotSize*(10+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_side",new SimpleIcon(L"quartzblock_side",slotSize*11,slotSize*14,slotSize*(11+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper_inside",new SimpleIcon(L"hopper_inside",slotSize*12,slotSize*14,slotSize*(12+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"lava",new SimpleIcon(L"lava",slotSize*13,slotSize*14,slotSize*(13+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"lava",L"lava")); - texturesByName.insert(stringIconMap::value_type(L"lava_flow",new SimpleIcon(L"lava_flow",slotSize*14,slotSize*14,slotSize*(14+2),slotSize*(14+2)))); - texturesToAnimate.push_back(std::pair(L"lava_flow",L"lava_flow")); - texturesByName.insert(stringIconMap::value_type(L"destroy_0",new SimpleIcon(L"destroy_0",slotSize*0,slotSize*15,slotSize*(0+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_1",new SimpleIcon(L"destroy_1",slotSize*1,slotSize*15,slotSize*(1+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_2",new SimpleIcon(L"destroy_2",slotSize*2,slotSize*15,slotSize*(2+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_3",new SimpleIcon(L"destroy_3",slotSize*3,slotSize*15,slotSize*(3+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_4",new SimpleIcon(L"destroy_4",slotSize*4,slotSize*15,slotSize*(4+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_5",new SimpleIcon(L"destroy_5",slotSize*5,slotSize*15,slotSize*(5+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_6",new SimpleIcon(L"destroy_6",slotSize*6,slotSize*15,slotSize*(6+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_7",new SimpleIcon(L"destroy_7",slotSize*7,slotSize*15,slotSize*(7+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_8",new SimpleIcon(L"destroy_8",slotSize*8,slotSize*15,slotSize*(8+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_9",new SimpleIcon(L"destroy_9",slotSize*9,slotSize*15,slotSize*(9+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_bottom",new SimpleIcon(L"quartzblock_bottom",slotSize*11,slotSize*15,slotSize*(11+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper_top",new SimpleIcon(L"hopper_top",slotSize*12,slotSize*15,slotSize*(12+1),slotSize*(15+1)))); - } +int PreStitchedTextureMap::getIconType() { return iconType; } + +Icon* PreStitchedTextureMap::getMissingIcon() { return missingPosition; } + +void PreStitchedTextureMap::loadUVs() { + if (!texturesByName.empty()) { + // 4J Stu - We only need to populate this once at the moment as we have + // hardcoded positions for each texture If we ever load that + // dynamically, be aware that the Icon objects could currently be being + // used by the GameRenderer::runUpdate thread + return; + } + + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + delete it->second; + } + texturesByName.clear(); + texturesToAnimate.clear(); + + float slotSize = 1.0f / 16.0f; + if (iconType != Icon::TYPE_TERRAIN) { + texturesByName.insert(stringIconMap::value_type( + L"helmetCloth", + new SimpleIcon(L"helmetCloth", slotSize * 0, slotSize * 0, + slotSize * (0 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetChain", + new SimpleIcon(L"helmetChain", slotSize * 1, slotSize * 0, + slotSize * (1 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetIron", + new SimpleIcon(L"helmetIron", slotSize * 2, slotSize * 0, + slotSize * (2 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetDiamond", + new SimpleIcon(L"helmetDiamond", slotSize * 3, slotSize * 0, + slotSize * (3 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetGold", + new SimpleIcon(L"helmetGold", slotSize * 4, slotSize * 0, + slotSize * (4 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flintAndSteel", + new SimpleIcon(L"flintAndSteel", slotSize * 5, slotSize * 0, + slotSize * (5 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flint", new SimpleIcon(L"flint", slotSize * 6, slotSize * 0, + slotSize * (6 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"coal", new SimpleIcon(L"coal", slotSize * 7, slotSize * 0, + slotSize * (7 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"string", new SimpleIcon(L"string", slotSize * 8, slotSize * 0, + slotSize * (8 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds", new SimpleIcon(L"seeds", slotSize * 9, slotSize * 0, + slotSize * (9 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"apple", new SimpleIcon(L"apple", slotSize * 10, slotSize * 0, + slotSize * (10 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"appleGold", + new SimpleIcon(L"appleGold", slotSize * 11, slotSize * 0, + slotSize * (11 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"egg", new SimpleIcon(L"egg", slotSize * 12, slotSize * 0, + slotSize * (12 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sugar", new SimpleIcon(L"sugar", slotSize * 13, slotSize * 0, + slotSize * (13 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snowball", + new SimpleIcon(L"snowball", slotSize * 14, slotSize * 0, + slotSize * (14 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_helmet", + new SimpleIcon(L"slot_empty_helmet", slotSize * 15, slotSize * 0, + slotSize * (15 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateCloth", + new SimpleIcon(L"chestplateCloth", slotSize * 0, slotSize * 1, + slotSize * (0 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateChain", + new SimpleIcon(L"chestplateChain", slotSize * 1, slotSize * 1, + slotSize * (1 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateIron", + new SimpleIcon(L"chestplateIron", slotSize * 2, slotSize * 1, + slotSize * (2 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateDiamond", + new SimpleIcon(L"chestplateDiamond", slotSize * 3, slotSize * 1, + slotSize * (3 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateGold", + new SimpleIcon(L"chestplateGold", slotSize * 4, slotSize * 1, + slotSize * (4 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow", new SimpleIcon(L"bow", slotSize * 5, slotSize * 1, + slotSize * (5 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brick", new SimpleIcon(L"brick", slotSize * 6, slotSize * 1, + slotSize * (6 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ingotIron", + new SimpleIcon(L"ingotIron", slotSize * 7, slotSize * 1, + slotSize * (7 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"feather", + new SimpleIcon(L"feather", slotSize * 8, slotSize * 1, + slotSize * (8 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wheat", new SimpleIcon(L"wheat", slotSize * 9, slotSize * 1, + slotSize * (9 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"painting", + new SimpleIcon(L"painting", slotSize * 10, slotSize * 1, + slotSize * (10 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"reeds", new SimpleIcon(L"reeds", slotSize * 11, slotSize * 1, + slotSize * (11 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bone", new SimpleIcon(L"bone", slotSize * 12, slotSize * 1, + slotSize * (12 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake", new SimpleIcon(L"cake", slotSize * 13, slotSize * 1, + slotSize * (13 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slimeball", + new SimpleIcon(L"slimeball", slotSize * 14, slotSize * 1, + slotSize * (14 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_chestplate", + new SimpleIcon(L"slot_empty_chestplate", slotSize * 15, + slotSize * 1, slotSize * (15 + 1), + slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsCloth", + new SimpleIcon(L"leggingsCloth", slotSize * 0, slotSize * 2, + slotSize * (0 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsChain", + new SimpleIcon(L"leggingsChain", slotSize * 1, slotSize * 2, + slotSize * (1 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsIron", + new SimpleIcon(L"leggingsIron", slotSize * 2, slotSize * 2, + slotSize * (2 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsDiamond", + new SimpleIcon(L"leggingsDiamond", slotSize * 3, slotSize * 2, + slotSize * (3 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsGold", + new SimpleIcon(L"leggingsGold", slotSize * 4, slotSize * 2, + slotSize * (4 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"arrow", new SimpleIcon(L"arrow", slotSize * 5, slotSize * 2, + slotSize * (5 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quiver", new SimpleIcon(L"quiver", slotSize * 6, slotSize * 2, + slotSize * (6 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ingotGold", + new SimpleIcon(L"ingotGold", slotSize * 7, slotSize * 2, + slotSize * (7 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sulphur", + new SimpleIcon(L"sulphur", slotSize * 8, slotSize * 2, + slotSize * (8 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bread", new SimpleIcon(L"bread", slotSize * 9, slotSize * 2, + slotSize * (9 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sign", new SimpleIcon(L"sign", slotSize * 10, slotSize * 2, + slotSize * (10 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood", + new SimpleIcon(L"doorWood", slotSize * 11, slotSize * 2, + slotSize * (11 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron", + new SimpleIcon(L"doorIron", slotSize * 12, slotSize * 2, + slotSize * (12 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed", new SimpleIcon(L"bed", slotSize * 13, slotSize * 2, + slotSize * (13 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireball", + new SimpleIcon(L"fireball", slotSize * 14, slotSize * 2, + slotSize * (14 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_leggings", + new SimpleIcon(L"slot_empty_leggings", slotSize * 15, slotSize * 2, + slotSize * (15 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsCloth", + new SimpleIcon(L"bootsCloth", slotSize * 0, slotSize * 3, + slotSize * (0 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsChain", + new SimpleIcon(L"bootsChain", slotSize * 1, slotSize * 3, + slotSize * (1 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsIron", + new SimpleIcon(L"bootsIron", slotSize * 2, slotSize * 3, + slotSize * (2 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsDiamond", + new SimpleIcon(L"bootsDiamond", slotSize * 3, slotSize * 3, + slotSize * (3 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsGold", + new SimpleIcon(L"bootsGold", slotSize * 4, slotSize * 3, + slotSize * (4 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stick", new SimpleIcon(L"stick", slotSize * 5, slotSize * 3, + slotSize * (5 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compass", + new SimpleIcon(L"compass", slotSize * 6, slotSize * 3, + slotSize * (6 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP0", + new SimpleIcon(L"compassP0", slotSize * 7, slotSize * 14, + slotSize * (7 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP1", + new SimpleIcon(L"compassP1", slotSize * 8, slotSize * 14, + slotSize * (8 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP2", + new SimpleIcon(L"compassP2", slotSize * 9, slotSize * 14, + slotSize * (9 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP3", + new SimpleIcon(L"compassP3", slotSize * 10, slotSize * 14, + slotSize * (10 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"compass", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP0", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP1", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP2", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP3", L"compass")); + texturesByName.insert(stringIconMap::value_type( + L"diamond", + new SimpleIcon(L"diamond", slotSize * 7, slotSize * 3, + slotSize * (7 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstone", + new SimpleIcon(L"redstone", slotSize * 8, slotSize * 3, + slotSize * (8 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clay", new SimpleIcon(L"clay", slotSize * 9, slotSize * 3, + slotSize * (9 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"paper", new SimpleIcon(L"paper", slotSize * 10, slotSize * 3, + slotSize * (10 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"book", new SimpleIcon(L"book", slotSize * 11, slotSize * 3, + slotSize * (11 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"map", new SimpleIcon(L"map", slotSize * 12, slotSize * 3, + slotSize * (12 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds_pumpkin", + new SimpleIcon(L"seeds_pumpkin", slotSize * 13, slotSize * 3, + slotSize * (13 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds_melon", + new SimpleIcon(L"seeds_melon", slotSize * 14, slotSize * 3, + slotSize * (14 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_boots", + new SimpleIcon(L"slot_empty_boots", slotSize * 15, slotSize * 3, + slotSize * (15 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordWood", + new SimpleIcon(L"swordWood", slotSize * 0, slotSize * 4, + slotSize * (0 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordStone", + new SimpleIcon(L"swordStone", slotSize * 1, slotSize * 4, + slotSize * (1 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordIron", + new SimpleIcon(L"swordIron", slotSize * 2, slotSize * 4, + slotSize * (2 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordDiamond", + new SimpleIcon(L"swordDiamond", slotSize * 3, slotSize * 4, + slotSize * (3 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordGold", + new SimpleIcon(L"swordGold", slotSize * 4, slotSize * 4, + slotSize * (4 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishingRod", + new SimpleIcon(L"fishingRod", slotSize * 5, slotSize * 4, + slotSize * (5 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clock", new SimpleIcon(L"clock", slotSize * 6, slotSize * 4, + slotSize * (6 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP0", + new SimpleIcon(L"clockP0", slotSize * 11, slotSize * 14, + slotSize * (11 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP1", + new SimpleIcon(L"clockP1", slotSize * 12, slotSize * 14, + slotSize * (12 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP2", + new SimpleIcon(L"clockP2", slotSize * 13, slotSize * 14, + slotSize * (13 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP3", + new SimpleIcon(L"clockP3", slotSize * 14, slotSize * 14, + slotSize * (14 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"clock", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP0", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP1", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP2", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP3", L"clock")); + texturesByName.insert(stringIconMap::value_type( + L"bowl", new SimpleIcon(L"bowl", slotSize * 7, slotSize * 4, + slotSize * (7 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroomStew", + new SimpleIcon(L"mushroomStew", slotSize * 8, slotSize * 4, + slotSize * (8 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"yellowDust", + new SimpleIcon(L"yellowDust", slotSize * 9, slotSize * 4, + slotSize * (9 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucket", + new SimpleIcon(L"bucket", slotSize * 10, slotSize * 4, + slotSize * (10 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucketWater", + new SimpleIcon(L"bucketWater", slotSize * 11, slotSize * 4, + slotSize * (11 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucketLava", + new SimpleIcon(L"bucketLava", slotSize * 12, slotSize * 4, + slotSize * (12 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"milk", new SimpleIcon(L"milk", slotSize * 13, slotSize * 4, + slotSize * (13 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_black", + new SimpleIcon(L"dyePowder_black", slotSize * 14, slotSize * 4, + slotSize * (14 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_gray", + new SimpleIcon(L"dyePowder_gray", slotSize * 15, slotSize * 4, + slotSize * (15 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelWood", + new SimpleIcon(L"shovelWood", slotSize * 0, slotSize * 5, + slotSize * (0 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelStone", + new SimpleIcon(L"shovelStone", slotSize * 1, slotSize * 5, + slotSize * (1 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelIron", + new SimpleIcon(L"shovelIron", slotSize * 2, slotSize * 5, + slotSize * (2 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelDiamond", + new SimpleIcon(L"shovelDiamond", slotSize * 3, slotSize * 5, + slotSize * (3 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelGold", + new SimpleIcon(L"shovelGold", slotSize * 4, slotSize * 5, + slotSize * (4 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishingRod_empty", + new SimpleIcon(L"fishingRod_empty", slotSize * 5, slotSize * 5, + slotSize * (5 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"diode", new SimpleIcon(L"diode", slotSize * 6, slotSize * 5, + slotSize * (6 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"porkchopRaw", + new SimpleIcon(L"porkchopRaw", slotSize * 7, slotSize * 5, + slotSize * (7 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"porkchopCooked", + new SimpleIcon(L"porkchopCooked", slotSize * 8, slotSize * 5, + slotSize * (8 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishRaw", + new SimpleIcon(L"fishRaw", slotSize * 9, slotSize * 5, + slotSize * (9 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishCooked", + new SimpleIcon(L"fishCooked", slotSize * 10, slotSize * 5, + slotSize * (10 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rottenFlesh", + new SimpleIcon(L"rottenFlesh", slotSize * 11, slotSize * 5, + slotSize * (11 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cookie", + new SimpleIcon(L"cookie", slotSize * 12, slotSize * 5, + slotSize * (12 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shears", + new SimpleIcon(L"shears", slotSize * 13, slotSize * 5, + slotSize * (13 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_red", + new SimpleIcon(L"dyePowder_red", slotSize * 14, slotSize * 5, + slotSize * (14 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_pink", + new SimpleIcon(L"dyePowder_pink", slotSize * 15, slotSize * 5, + slotSize * (15 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeWood", + new SimpleIcon(L"pickaxeWood", slotSize * 0, slotSize * 6, + slotSize * (0 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeStone", + new SimpleIcon(L"pickaxeStone", slotSize * 1, slotSize * 6, + slotSize * (1 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeIron", + new SimpleIcon(L"pickaxeIron", slotSize * 2, slotSize * 6, + slotSize * (2 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeDiamond", + new SimpleIcon(L"pickaxeDiamond", slotSize * 3, slotSize * 6, + slotSize * (3 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeGold", + new SimpleIcon(L"pickaxeGold", slotSize * 4, slotSize * 6, + slotSize * (4 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_0", + new SimpleIcon(L"bow_pull_0", slotSize * 5, slotSize * 6, + slotSize * (5 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrotOnAStick", + new SimpleIcon(L"carrotOnAStick", slotSize * 6, slotSize * 6, + slotSize * (6 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leather", + new SimpleIcon(L"leather", slotSize * 7, slotSize * 6, + slotSize * (7 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"saddle", new SimpleIcon(L"saddle", slotSize * 8, slotSize * 6, + slotSize * (8 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beefRaw", + new SimpleIcon(L"beefRaw", slotSize * 9, slotSize * 6, + slotSize * (9 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beefCooked", + new SimpleIcon(L"beefCooked", slotSize * 10, slotSize * 6, + slotSize * (10 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enderPearl", + new SimpleIcon(L"enderPearl", slotSize * 11, slotSize * 6, + slotSize * (11 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blazeRod", + new SimpleIcon(L"blazeRod", slotSize * 12, slotSize * 6, + slotSize * (12 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon", new SimpleIcon(L"melon", slotSize * 13, slotSize * 6, + slotSize * (13 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_green", + new SimpleIcon(L"dyePowder_green", slotSize * 14, slotSize * 6, + slotSize * (14 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_lime", + new SimpleIcon(L"dyePowder_lime", slotSize * 15, slotSize * 6, + slotSize * (15 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetWood", + new SimpleIcon(L"hatchetWood", slotSize * 0, slotSize * 7, + slotSize * (0 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetStone", + new SimpleIcon(L"hatchetStone", slotSize * 1, slotSize * 7, + slotSize * (1 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetIron", + new SimpleIcon(L"hatchetIron", slotSize * 2, slotSize * 7, + slotSize * (2 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetDiamond", + new SimpleIcon(L"hatchetDiamond", slotSize * 3, slotSize * 7, + slotSize * (3 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetGold", + new SimpleIcon(L"hatchetGold", slotSize * 4, slotSize * 7, + slotSize * (4 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_1", + new SimpleIcon(L"bow_pull_1", slotSize * 5, slotSize * 7, + slotSize * (5 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoBaked", + new SimpleIcon(L"potatoBaked", slotSize * 6, slotSize * 7, + slotSize * (6 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potato", new SimpleIcon(L"potato", slotSize * 7, slotSize * 7, + slotSize * (7 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots", + new SimpleIcon(L"carrots", slotSize * 8, slotSize * 7, + slotSize * (8 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chickenRaw", + new SimpleIcon(L"chickenRaw", slotSize * 9, slotSize * 7, + slotSize * (9 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chickenCooked", + new SimpleIcon(L"chickenCooked", slotSize * 10, slotSize * 7, + slotSize * (10 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ghastTear", + new SimpleIcon(L"ghastTear", slotSize * 11, slotSize * 7, + slotSize * (11 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldNugget", + new SimpleIcon(L"goldNugget", slotSize * 12, slotSize * 7, + slotSize * (12 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalkSeeds", + new SimpleIcon(L"netherStalkSeeds", slotSize * 13, slotSize * 7, + slotSize * (13 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_brown", + new SimpleIcon(L"dyePowder_brown", slotSize * 14, slotSize * 7, + slotSize * (14 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_yellow", + new SimpleIcon(L"dyePowder_yellow", slotSize * 15, slotSize * 7, + slotSize * (15 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeWood", + new SimpleIcon(L"hoeWood", slotSize * 0, slotSize * 8, + slotSize * (0 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeStone", + new SimpleIcon(L"hoeStone", slotSize * 1, slotSize * 8, + slotSize * (1 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeIron", + new SimpleIcon(L"hoeIron", slotSize * 2, slotSize * 8, + slotSize * (2 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeDiamond", + new SimpleIcon(L"hoeDiamond", slotSize * 3, slotSize * 8, + slotSize * (3 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeGold", + new SimpleIcon(L"hoeGold", slotSize * 4, slotSize * 8, + slotSize * (4 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_2", + new SimpleIcon(L"bow_pull_2", slotSize * 5, slotSize * 8, + slotSize * (5 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoPoisonous", + new SimpleIcon(L"potatoPoisonous", slotSize * 6, slotSize * 8, + slotSize * (6 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecart", + new SimpleIcon(L"minecart", slotSize * 7, slotSize * 8, + slotSize * (7 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"boat", new SimpleIcon(L"boat", slotSize * 8, slotSize * 8, + slotSize * (8 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"speckledMelon", + new SimpleIcon(L"speckledMelon", slotSize * 9, slotSize * 8, + slotSize * (9 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fermentedSpiderEye", + new SimpleIcon(L"fermentedSpiderEye", slotSize * 10, slotSize * 8, + slotSize * (10 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"spiderEye", + new SimpleIcon(L"spiderEye", slotSize * 11, slotSize * 8, + slotSize * (11 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion", + new SimpleIcon(L"potion", slotSize * 12, slotSize * 8, + slotSize * (12 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"glassBottle", + new SimpleIcon(L"glassBottle", slotSize * 12, slotSize * 8, + slotSize * (12 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion_contents", + new SimpleIcon(L"potion_contents", slotSize * 13, slotSize * 8, + slotSize * (13 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_blue", + new SimpleIcon(L"dyePowder_blue", slotSize * 14, slotSize * 8, + slotSize * (14 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_lightBlue", + new SimpleIcon(L"dyePowder_lightBlue", slotSize * 15, slotSize * 8, + slotSize * (15 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetCloth_overlay", + new SimpleIcon(L"helmetCloth_overlay", slotSize * 0, slotSize * 9, + slotSize * (0 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator", + new SimpleIcon(L"comparator", slotSize * 5, slotSize * 9, + slotSize * (5 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrotGolden", + new SimpleIcon(L"carrotGolden", slotSize * 6, slotSize * 9, + slotSize * (6 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartChest", + new SimpleIcon(L"minecartChest", slotSize * 7, slotSize * 9, + slotSize * (7 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkinPie", + new SimpleIcon(L"pumpkinPie", slotSize * 8, slotSize * 9, + slotSize * (8 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"monsterPlacer", + new SimpleIcon(L"monsterPlacer", slotSize * 9, slotSize * 9, + slotSize * (9 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion_splash", + new SimpleIcon(L"potion_splash", slotSize * 10, slotSize * 9, + slotSize * (10 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"eyeOfEnder", + new SimpleIcon(L"eyeOfEnder", slotSize * 11, slotSize * 9, + slotSize * (11 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron", + new SimpleIcon(L"cauldron", slotSize * 12, slotSize * 9, + slotSize * (12 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blazePowder", + new SimpleIcon(L"blazePowder", slotSize * 13, slotSize * 9, + slotSize * (13 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_purple", + new SimpleIcon(L"dyePowder_purple", slotSize * 14, slotSize * 9, + slotSize * (14 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_magenta", + new SimpleIcon(L"dyePowder_magenta", slotSize * 15, slotSize * 9, + slotSize * (15 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateCloth_overlay", + new SimpleIcon(L"chestplateCloth_overlay", slotSize * 0, + slotSize * 10, slotSize * (0 + 1), + slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherbrick", + new SimpleIcon(L"netherbrick", slotSize * 5, slotSize * 10, + slotSize * (5 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartFurnace", + new SimpleIcon(L"minecartFurnace", slotSize * 7, slotSize * 10, + slotSize * (7 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"monsterPlacer_overlay", + new SimpleIcon(L"monsterPlacer_overlay", slotSize * 9, + slotSize * 10, slotSize * (9 + 1), + slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ruby", new SimpleIcon(L"ruby", slotSize * 10, slotSize * 10, + slotSize * (10 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"expBottle", + new SimpleIcon(L"expBottle", slotSize * 11, slotSize * 10, + slotSize * (11 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand", + new SimpleIcon(L"brewingStand", slotSize * 12, slotSize * 10, + slotSize * (12 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"magmaCream", + new SimpleIcon(L"magmaCream", slotSize * 13, slotSize * 10, + slotSize * (13 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_cyan", + new SimpleIcon(L"dyePowder_cyan", slotSize * 14, slotSize * 10, + slotSize * (14 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_orange", + new SimpleIcon(L"dyePowder_orange", slotSize * 15, slotSize * 10, + slotSize * (15 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsCloth_overlay", + new SimpleIcon(L"leggingsCloth_overlay", slotSize * 0, + slotSize * 11, slotSize * (0 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartHopper", + new SimpleIcon(L"minecartHopper", slotSize * 7, slotSize * 11, + slotSize * (7 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper", + new SimpleIcon(L"hopper", slotSize * 8, slotSize * 11, + slotSize * (8 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStar", + new SimpleIcon(L"netherStar", slotSize * 9, slotSize * 11, + slotSize * (9 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"emerald", + new SimpleIcon(L"emerald", slotSize * 10, slotSize * 11, + slotSize * (10 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"writingBook", + new SimpleIcon(L"writingBook", slotSize * 11, slotSize * 11, + slotSize * (11 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"writtenBook", + new SimpleIcon(L"writtenBook", slotSize * 12, slotSize * 11, + slotSize * (12 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flowerPot", + new SimpleIcon(L"flowerPot", slotSize * 13, slotSize * 11, + slotSize * (13 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_silver", + new SimpleIcon(L"dyePowder_silver", slotSize * 14, slotSize * 11, + slotSize * (14 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_white", + new SimpleIcon(L"dyePowder_white", slotSize * 15, slotSize * 11, + slotSize * (15 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsCloth_overlay", + new SimpleIcon(L"bootsCloth_overlay", slotSize * 0, slotSize * 12, + slotSize * (0 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartTnt", + new SimpleIcon(L"minecartTnt", slotSize * 7, slotSize * 12, + slotSize * (7 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworks", + new SimpleIcon(L"fireworks", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworksCharge", + new SimpleIcon(L"fireworksCharge", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworksCharge_overlay", + new SimpleIcon(L"fireworksCharge_overlay", slotSize * 11, + slotSize * 12, slotSize * (11 + 1), + slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherquartz", + new SimpleIcon(L"netherquartz", slotSize * 12, slotSize * 12, + slotSize * (12 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"emptyMap", + new SimpleIcon(L"emptyMap", slotSize * 13, slotSize * 12, + slotSize * (13 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"frame", + new SimpleIcon(L"frame", slotSize * 14, slotSize * 12, + slotSize * (14 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantedBook", + new SimpleIcon(L"enchantedBook", slotSize * 15, slotSize * 12, + slotSize * (15 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_skeleton", + new SimpleIcon(L"skull_skeleton", slotSize * 0, slotSize * 14, + slotSize * (0 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_wither", + new SimpleIcon(L"skull_wither", slotSize * 1, slotSize * 14, + slotSize * (1 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_zombie", + new SimpleIcon(L"skull_zombie", slotSize * 2, slotSize * 14, + slotSize * (2 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_char", + new SimpleIcon(L"skull_char", slotSize * 3, slotSize * 14, + slotSize * (3 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_creeper", + new SimpleIcon(L"skull_creeper", slotSize * 4, slotSize * 14, + slotSize * (4 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dragonFireball", + new SimpleIcon(L"dragonFireball", slotSize * 15, slotSize * 14, + slotSize * (15 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_13", + new SimpleIcon(L"record_13", slotSize * 0, slotSize * 15, + slotSize * (0 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_cat", + new SimpleIcon(L"record_cat", slotSize * 1, slotSize * 15, + slotSize * (1 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_blocks", + new SimpleIcon(L"record_blocks", slotSize * 2, slotSize * 15, + slotSize * (2 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_chirp", + new SimpleIcon(L"record_chirp", slotSize * 3, slotSize * 15, + slotSize * (3 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_far", + new SimpleIcon(L"record_far", slotSize * 4, slotSize * 15, + slotSize * (4 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_mall", + new SimpleIcon(L"record_mall", slotSize * 5, slotSize * 15, + slotSize * (5 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_mellohi", + new SimpleIcon(L"record_mellohi", slotSize * 6, slotSize * 15, + slotSize * (6 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_stal", + new SimpleIcon(L"record_stal", slotSize * 7, slotSize * 15, + slotSize * (7 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_strad", + new SimpleIcon(L"record_strad", slotSize * 8, slotSize * 15, + slotSize * (8 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_ward", + new SimpleIcon(L"record_ward", slotSize * 9, slotSize * 15, + slotSize * (9 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_11", + new SimpleIcon(L"record_11", slotSize * 10, slotSize * 15, + slotSize * (10 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_where are we now", + new SimpleIcon(L"record_where are we now", slotSize * 11, + slotSize * 15, slotSize * (11 + 1), + slotSize * (15 + 1)))); + + // Special cases + ClockTexture* dataClock = new ClockTexture(); + Icon* oldClock = texturesByName[L"clock"]; + dataClock->initUVs(oldClock->getU0(), oldClock->getV0(), + oldClock->getU1(), oldClock->getV1()); + delete oldClock; + texturesByName[L"clock"] = dataClock; + + ClockTexture* clock = new ClockTexture(0, dataClock); + oldClock = texturesByName[L"clockP0"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP0"] = clock; + + clock = new ClockTexture(1, dataClock); + oldClock = texturesByName[L"clockP1"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP1"] = clock; + + clock = new ClockTexture(2, dataClock); + oldClock = texturesByName[L"clockP2"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP2"] = clock; + + clock = new ClockTexture(3, dataClock); + oldClock = texturesByName[L"clockP3"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP3"] = clock; + + CompassTexture* dataCompass = new CompassTexture(); + Icon* oldCompass = texturesByName[L"compass"]; + dataCompass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compass"] = dataCompass; + + CompassTexture* compass = new CompassTexture(0, dataCompass); + oldCompass = texturesByName[L"compassP0"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP0"] = compass; + + compass = new CompassTexture(1, dataCompass); + oldCompass = texturesByName[L"compassP1"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP1"] = compass; + + compass = new CompassTexture(2, dataCompass); + oldCompass = texturesByName[L"compassP2"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP2"] = compass; + + compass = new CompassTexture(3, dataCompass); + oldCompass = texturesByName[L"compassP3"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP3"] = compass; + } else { + texturesByName.insert(stringIconMap::value_type( + L"grass_top", + new SimpleIcon(L"grass_top", slotSize * 0, slotSize * 0, + slotSize * (0 + 1), slotSize * (0 + 1)))); + texturesByName[L"grass_top"]->setFlags( + Icon::IS_GRASS_TOP); // 4J added for faster determination of + // texture type in tesselation + texturesByName.insert(stringIconMap::value_type( + L"stone", new SimpleIcon(L"stone", slotSize * 1, slotSize * 0, + slotSize * (1 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dirt", new SimpleIcon(L"dirt", slotSize * 2, slotSize * 0, + slotSize * (2 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"grass_side", + new SimpleIcon(L"grass_side", slotSize * 3, slotSize * 0, + slotSize * (3 + 1), slotSize * (0 + 1)))); + texturesByName[L"grass_side"]->setFlags( + Icon::IS_GRASS_SIDE); // 4J added for faster determination of + // texture type in tesselation + texturesByName.insert(stringIconMap::value_type( + L"wood", new SimpleIcon(L"wood", slotSize * 4, slotSize * 0, + slotSize * (4 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneslab_side", + new SimpleIcon(L"stoneslab_side", slotSize * 5, slotSize * 0, + slotSize * (5 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneslab_top", + new SimpleIcon(L"stoneslab_top", slotSize * 6, slotSize * 0, + slotSize * (6 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brick", new SimpleIcon(L"brick", slotSize * 7, slotSize * 0, + slotSize * (7 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_side", + new SimpleIcon(L"tnt_side", slotSize * 8, slotSize * 0, + slotSize * (8 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_top", + new SimpleIcon(L"tnt_top", slotSize * 9, slotSize * 0, + slotSize * (9 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_bottom", + new SimpleIcon(L"tnt_bottom", slotSize * 10, slotSize * 0, + slotSize * (10 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"web", new SimpleIcon(L"web", slotSize * 11, slotSize * 0, + slotSize * (11 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rose", new SimpleIcon(L"rose", slotSize * 12, slotSize * 0, + slotSize * (12 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flower", + new SimpleIcon(L"flower", slotSize * 13, slotSize * 0, + slotSize * (13 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"portal", + new SimpleIcon(L"portal", slotSize * 14, slotSize * 0, + slotSize * (14 + 1), slotSize * (0 + 1)))); + texturesToAnimate.push_back( + std::pair(L"portal", L"portal")); + texturesByName.insert(stringIconMap::value_type( + L"sapling", + new SimpleIcon(L"sapling", slotSize * 15, slotSize * 0, + slotSize * (15 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebrick", + new SimpleIcon(L"stonebrick", slotSize * 0, slotSize * 1, + slotSize * (0 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bedrock", + new SimpleIcon(L"bedrock", slotSize * 1, slotSize * 1, + slotSize * (1 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sand", new SimpleIcon(L"sand", slotSize * 2, slotSize * 1, + slotSize * (2 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"gravel", new SimpleIcon(L"gravel", slotSize * 3, slotSize * 1, + slotSize * (3 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_side", + new SimpleIcon(L"tree_side", slotSize * 4, slotSize * 1, + slotSize * (4 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_top", + new SimpleIcon(L"tree_top", slotSize * 5, slotSize * 1, + slotSize * (5 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockIron", + new SimpleIcon(L"blockIron", slotSize * 6, slotSize * 1, + slotSize * (6 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockGold", + new SimpleIcon(L"blockGold", slotSize * 7, slotSize * 1, + slotSize * (7 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockDiamond", + new SimpleIcon(L"blockDiamond", slotSize * 8, slotSize * 1, + slotSize * (8 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockEmerald", + new SimpleIcon(L"blockEmerald", slotSize * 9, slotSize * 1, + slotSize * (9 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockRedstone", + new SimpleIcon(L"blockRedstone", slotSize * 10, slotSize * 1, + slotSize * (10 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dropper_front", + new SimpleIcon(L"dropper_front", slotSize * 11, slotSize * 1, + slotSize * (11 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_red", + new SimpleIcon(L"mushroom_red", slotSize * 12, slotSize * 1, + slotSize * (12 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_brown", + new SimpleIcon(L"mushroom_brown", slotSize * 13, slotSize * 1, + slotSize * (13 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_jungle", + new SimpleIcon(L"sapling_jungle", slotSize * 14, slotSize * 1, + slotSize * (14 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fire_0", + new SimpleIcon(L"fire_0", slotSize * 15, slotSize * 1, + slotSize * (15 + 1), slotSize * (1 + 1)))); + texturesToAnimate.push_back( + std::pair(L"fire_0", L"fire_0")); + texturesByName.insert(stringIconMap::value_type( + L"oreGold", + new SimpleIcon(L"oreGold", slotSize * 0, slotSize * 2, + slotSize * (0 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreIron", + new SimpleIcon(L"oreIron", slotSize * 1, slotSize * 2, + slotSize * (1 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreCoal", + new SimpleIcon(L"oreCoal", slotSize * 2, slotSize * 2, + slotSize * (2 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bookshelf", + new SimpleIcon(L"bookshelf", slotSize * 3, slotSize * 2, + slotSize * (3 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneMoss", + new SimpleIcon(L"stoneMoss", slotSize * 4, slotSize * 2, + slotSize * (4 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"obsidian", + new SimpleIcon(L"obsidian", slotSize * 5, slotSize * 2, + slotSize * (5 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"grass_side_overlay", + new SimpleIcon(L"grass_side_overlay", slotSize * 6, slotSize * 2, + slotSize * (6 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tallgrass", + new SimpleIcon(L"tallgrass", slotSize * 7, slotSize * 2, + slotSize * (7 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dispenser_front_vertical", + new SimpleIcon(L"dispenser_front_vertical", slotSize * 8, + slotSize * 2, slotSize * (8 + 1), + slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beacon", new SimpleIcon(L"beacon", slotSize * 9, slotSize * 2, + slotSize * (9 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dropper_front_vertical", + new SimpleIcon(L"dropper_front_vertical", slotSize * 10, + slotSize * 2, slotSize * (10 + 1), + slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_top", + new SimpleIcon(L"workbench_top", slotSize * 11, slotSize * 2, + slotSize * (11 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_front", + new SimpleIcon(L"furnace_front", slotSize * 12, slotSize * 2, + slotSize * (12 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_side", + new SimpleIcon(L"furnace_side", slotSize * 13, slotSize * 2, + slotSize * (13 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dispenser_front", + new SimpleIcon(L"dispenser_front", slotSize * 14, slotSize * 2, + slotSize * (14 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fire_1", + new SimpleIcon(L"fire_1", slotSize * 15, slotSize * 1, + slotSize * (15 + 1), slotSize * (1 + 1)))); + texturesToAnimate.push_back( + std::pair(L"fire_1", L"fire_1")); + texturesByName.insert(stringIconMap::value_type( + L"sponge", new SimpleIcon(L"sponge", slotSize * 0, slotSize * 3, + slotSize * (0 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"glass", new SimpleIcon(L"glass", slotSize * 1, slotSize * 3, + slotSize * (1 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreDiamond", + new SimpleIcon(L"oreDiamond", slotSize * 2, slotSize * 3, + slotSize * (2 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreRedstone", + new SimpleIcon(L"oreRedstone", slotSize * 3, slotSize * 3, + slotSize * (3 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves", new SimpleIcon(L"leaves", slotSize * 4, slotSize * 3, + slotSize * (4 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_opaque", + new SimpleIcon(L"leaves_opaque", slotSize * 5, slotSize * 3, + slotSize * (5 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth", + new SimpleIcon(L"stonebricksmooth", slotSize * 6, slotSize * 3, + slotSize * (6 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"deadbush", + new SimpleIcon(L"deadbush", slotSize * 7, slotSize * 3, + slotSize * (7 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fern", new SimpleIcon(L"fern", slotSize * 8, slotSize * 3, + slotSize * (8 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"daylightDetector_top", + new SimpleIcon(L"daylightDetector_top", slotSize * 9, slotSize * 3, + slotSize * (9 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"daylightDetector_side", + new SimpleIcon(L"daylightDetector_side", slotSize * 10, + slotSize * 3, slotSize * (10 + 1), + slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_side", + new SimpleIcon(L"workbench_side", slotSize * 11, slotSize * 3, + slotSize * (11 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_front", + new SimpleIcon(L"workbench_front", slotSize * 12, slotSize * 3, + slotSize * (12 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_front_lit", + new SimpleIcon(L"furnace_front_lit", slotSize * 13, slotSize * 3, + slotSize * (13 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_top", + new SimpleIcon(L"furnace_top", slotSize * 14, slotSize * 3, + slotSize * (14 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_spruce", + new SimpleIcon(L"sapling_spruce", slotSize * 15, slotSize * 3, + slotSize * (15 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_0", + new SimpleIcon(L"cloth_0", slotSize * 0, slotSize * 4, + slotSize * (0 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mobSpawner", + new SimpleIcon(L"mobSpawner", slotSize * 1, slotSize * 4, + slotSize * (1 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snow", new SimpleIcon(L"snow", slotSize * 2, slotSize * 4, + slotSize * (2 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ice", new SimpleIcon(L"ice", slotSize * 3, slotSize * 4, + slotSize * (3 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snow_side", + new SimpleIcon(L"snow_side", slotSize * 4, slotSize * 4, + slotSize * (4 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_top", + new SimpleIcon(L"cactus_top", slotSize * 5, slotSize * 4, + slotSize * (5 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_side", + new SimpleIcon(L"cactus_side", slotSize * 6, slotSize * 4, + slotSize * (6 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_bottom", + new SimpleIcon(L"cactus_bottom", slotSize * 7, slotSize * 4, + slotSize * (7 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clay", new SimpleIcon(L"clay", slotSize * 8, slotSize * 4, + slotSize * (8 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"reeds", new SimpleIcon(L"reeds", slotSize * 9, slotSize * 4, + slotSize * (9 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"musicBlock", + new SimpleIcon(L"musicBlock", slotSize * 10, slotSize * 4, + slotSize * (10 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"jukebox_top", + new SimpleIcon(L"jukebox_top", slotSize * 11, slotSize * 4, + slotSize * (11 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"waterlily", + new SimpleIcon(L"waterlily", slotSize * 12, slotSize * 4, + slotSize * (12 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mycel_side", + new SimpleIcon(L"mycel_side", slotSize * 13, slotSize * 4, + slotSize * (13 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mycel_top", + new SimpleIcon(L"mycel_top", slotSize * 14, slotSize * 4, + slotSize * (14 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_birch", + new SimpleIcon(L"sapling_birch", slotSize * 15, slotSize * 4, + slotSize * (15 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"torch", new SimpleIcon(L"torch", slotSize * 0, slotSize * 5, + slotSize * (0 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood_upper", + new SimpleIcon(L"doorWood_upper", slotSize * 1, slotSize * 5, + slotSize * (1 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron_upper", + new SimpleIcon(L"doorIron_upper", slotSize * 2, slotSize * 5, + slotSize * (2 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ladder", new SimpleIcon(L"ladder", slotSize * 3, slotSize * 5, + slotSize * (3 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"trapdoor", + new SimpleIcon(L"trapdoor", slotSize * 4, slotSize * 5, + slotSize * (4 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fenceIron", + new SimpleIcon(L"fenceIron", slotSize * 5, slotSize * 5, + slotSize * (5 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"farmland_wet", + new SimpleIcon(L"farmland_wet", slotSize * 6, slotSize * 5, + slotSize * (6 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"farmland_dry", + new SimpleIcon(L"farmland_dry", slotSize * 7, slotSize * 5, + slotSize * (7 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_0", + new SimpleIcon(L"crops_0", slotSize * 8, slotSize * 5, + slotSize * (8 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_1", + new SimpleIcon(L"crops_1", slotSize * 9, slotSize * 5, + slotSize * (9 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_2", + new SimpleIcon(L"crops_2", slotSize * 10, slotSize * 5, + slotSize * (10 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_3", + new SimpleIcon(L"crops_3", slotSize * 11, slotSize * 5, + slotSize * (11 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_4", + new SimpleIcon(L"crops_4", slotSize * 12, slotSize * 5, + slotSize * (12 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_5", + new SimpleIcon(L"crops_5", slotSize * 13, slotSize * 5, + slotSize * (13 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_6", + new SimpleIcon(L"crops_6", slotSize * 14, slotSize * 5, + slotSize * (14 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_7", + new SimpleIcon(L"crops_7", slotSize * 15, slotSize * 5, + slotSize * (15 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lever", new SimpleIcon(L"lever", slotSize * 0, slotSize * 6, + slotSize * (0 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood_lower", + new SimpleIcon(L"doorWood_lower", slotSize * 1, slotSize * 6, + slotSize * (1 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron_lower", + new SimpleIcon(L"doorIron_lower", slotSize * 2, slotSize * 6, + slotSize * (2 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redtorch_lit", + new SimpleIcon(L"redtorch_lit", slotSize * 3, slotSize * 6, + slotSize * (3 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_mossy", + new SimpleIcon(L"stonebricksmooth_mossy", slotSize * 4, + slotSize * 6, slotSize * (4 + 1), + slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_cracked", + new SimpleIcon(L"stonebricksmooth_cracked", slotSize * 5, + slotSize * 6, slotSize * (5 + 1), + slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_top", + new SimpleIcon(L"pumpkin_top", slotSize * 6, slotSize * 6, + slotSize * (6 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hellrock", + new SimpleIcon(L"hellrock", slotSize * 7, slotSize * 6, + slotSize * (7 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hellsand", + new SimpleIcon(L"hellsand", slotSize * 8, slotSize * 6, + slotSize * (8 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lightgem", + new SimpleIcon(L"lightgem", slotSize * 9, slotSize * 6, + slotSize * (9 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_top_sticky", + new SimpleIcon(L"piston_top_sticky", slotSize * 10, slotSize * 6, + slotSize * (10 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_top", + new SimpleIcon(L"piston_top", slotSize * 11, slotSize * 6, + slotSize * (11 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_side", + new SimpleIcon(L"piston_side", slotSize * 12, slotSize * 6, + slotSize * (12 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_bottom", + new SimpleIcon(L"piston_bottom", slotSize * 13, slotSize * 6, + slotSize * (13 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_inner_top", + new SimpleIcon(L"piston_inner_top", slotSize * 14, slotSize * 6, + slotSize * (14 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stem_straight", + new SimpleIcon(L"stem_straight", slotSize * 15, slotSize * 6, + slotSize * (15 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rail_turn", + new SimpleIcon(L"rail_turn", slotSize * 0, slotSize * 7, + slotSize * (0 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_15", + new SimpleIcon(L"cloth_15", slotSize * 1, slotSize * 7, + slotSize * (1 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_7", + new SimpleIcon(L"cloth_7", slotSize * 2, slotSize * 7, + slotSize * (2 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redtorch", + new SimpleIcon(L"redtorch", slotSize * 3, slotSize * 7, + slotSize * (3 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_spruce", + new SimpleIcon(L"tree_spruce", slotSize * 4, slotSize * 7, + slotSize * (4 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_birch", + new SimpleIcon(L"tree_birch", slotSize * 5, slotSize * 7, + slotSize * (5 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_side", + new SimpleIcon(L"pumpkin_side", slotSize * 6, slotSize * 7, + slotSize * (6 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_face", + new SimpleIcon(L"pumpkin_face", slotSize * 7, slotSize * 7, + slotSize * (7 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_jack", + new SimpleIcon(L"pumpkin_jack", slotSize * 8, slotSize * 7, + slotSize * (8 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_top", + new SimpleIcon(L"cake_top", slotSize * 9, slotSize * 7, + slotSize * (9 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_side", + new SimpleIcon(L"cake_side", slotSize * 10, slotSize * 7, + slotSize * (10 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_inner", + new SimpleIcon(L"cake_inner", slotSize * 11, slotSize * 7, + slotSize * (11 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_bottom", + new SimpleIcon(L"cake_bottom", slotSize * 12, slotSize * 7, + slotSize * (12 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_red", + new SimpleIcon(L"mushroom_skin_red", slotSize * 13, slotSize * 7, + slotSize * (13 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_brown", + new SimpleIcon(L"mushroom_skin_brown", slotSize * 14, slotSize * 7, + slotSize * (14 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stem_bent", + new SimpleIcon(L"stem_bent", slotSize * 15, slotSize * 7, + slotSize * (15 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rail", new SimpleIcon(L"rail", slotSize * 0, slotSize * 8, + slotSize * (0 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_14", + new SimpleIcon(L"cloth_14", slotSize * 1, slotSize * 8, + slotSize * (1 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_6", + new SimpleIcon(L"cloth_6", slotSize * 2, slotSize * 8, + slotSize * (2 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"repeater", + new SimpleIcon(L"repeater", slotSize * 3, slotSize * 8, + slotSize * (3 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_spruce", + new SimpleIcon(L"leaves_spruce", slotSize * 4, slotSize * 8, + slotSize * (4 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_spruce_opaque", + new SimpleIcon(L"leaves_spruce_opaque", slotSize * 5, slotSize * 8, + slotSize * (5 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_top", + new SimpleIcon(L"bed_feet_top", slotSize * 6, slotSize * 8, + slotSize * (6 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_top", + new SimpleIcon(L"bed_head_top", slotSize * 7, slotSize * 8, + slotSize * (7 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon_side", + new SimpleIcon(L"melon_side", slotSize * 8, slotSize * 8, + slotSize * (8 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon_top", + new SimpleIcon(L"melon_top", slotSize * 9, slotSize * 8, + slotSize * (9 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_top", + new SimpleIcon(L"cauldron_top", slotSize * 10, slotSize * 8, + slotSize * (10 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_inner", + new SimpleIcon(L"cauldron_inner", slotSize * 11, slotSize * 8, + slotSize * (11 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_stem", + new SimpleIcon(L"mushroom_skin_stem", slotSize * 13, slotSize * 8, + slotSize * (13 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_inside", + new SimpleIcon(L"mushroom_inside", slotSize * 14, slotSize * 8, + slotSize * (14 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"vine", new SimpleIcon(L"vine", slotSize * 15, slotSize * 8, + slotSize * (15 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockLapis", + new SimpleIcon(L"blockLapis", slotSize * 0, slotSize * 9, + slotSize * (0 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_13", + new SimpleIcon(L"cloth_13", slotSize * 1, slotSize * 9, + slotSize * (1 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_5", + new SimpleIcon(L"cloth_5", slotSize * 2, slotSize * 9, + slotSize * (2 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"repeater_lit", + new SimpleIcon(L"repeater_lit", slotSize * 3, slotSize * 9, + slotSize * (3 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"thinglass_top", + new SimpleIcon(L"thinglass_top", slotSize * 4, slotSize * 9, + slotSize * (4 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_end", + new SimpleIcon(L"bed_feet_end", slotSize * 5, slotSize * 9, + slotSize * (5 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_side", + new SimpleIcon(L"bed_feet_side", slotSize * 6, slotSize * 9, + slotSize * (6 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_side", + new SimpleIcon(L"bed_head_side", slotSize * 7, slotSize * 9, + slotSize * (7 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_end", + new SimpleIcon(L"bed_head_end", slotSize * 8, slotSize * 9, + slotSize * (8 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_jungle", + new SimpleIcon(L"tree_jungle", slotSize * 9, slotSize * 9, + slotSize * (9 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_side", + new SimpleIcon(L"cauldron_side", slotSize * 10, slotSize * 9, + slotSize * (10 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_bottom", + new SimpleIcon(L"cauldron_bottom", slotSize * 11, slotSize * 9, + slotSize * (11 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand_base", + new SimpleIcon(L"brewingStand_base", slotSize * 12, slotSize * 9, + slotSize * (12 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand", + new SimpleIcon(L"brewingStand", slotSize * 13, slotSize * 9, + slotSize * (13 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_top", + new SimpleIcon(L"endframe_top", slotSize * 14, slotSize * 9, + slotSize * (14 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_side", + new SimpleIcon(L"endframe_side", slotSize * 15, slotSize * 9, + slotSize * (15 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreLapis", + new SimpleIcon(L"oreLapis", slotSize * 0, slotSize * 10, + slotSize * (0 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_12", + new SimpleIcon(L"cloth_12", slotSize * 1, slotSize * 10, + slotSize * (1 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_4", + new SimpleIcon(L"cloth_4", slotSize * 2, slotSize * 10, + slotSize * (2 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldenRail", + new SimpleIcon(L"goldenRail", slotSize * 3, slotSize * 10, + slotSize * (3 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_cross", + new SimpleIcon(L"redstoneDust_cross", slotSize * 4, slotSize * 10, + slotSize * (4 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_line", + new SimpleIcon(L"redstoneDust_line", slotSize * 5, slotSize * 10, + slotSize * (5 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_top", + new SimpleIcon(L"enchantment_top", slotSize * 6, slotSize * 10, + slotSize * (6 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dragonEgg", + new SimpleIcon(L"dragonEgg", slotSize * 7, slotSize * 10, + slotSize * (7 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_2", + new SimpleIcon(L"cocoa_2", slotSize * 8, slotSize * 10, + slotSize * (8 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_1", + new SimpleIcon(L"cocoa_1", slotSize * 9, slotSize * 10, + slotSize * (9 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_0", + new SimpleIcon(L"cocoa_0", slotSize * 10, slotSize * 10, + slotSize * (10 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreEmerald", + new SimpleIcon(L"oreEmerald", slotSize * 11, slotSize * 10, + slotSize * (11 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tripWireSource", + new SimpleIcon(L"tripWireSource", slotSize * 12, slotSize * 10, + slotSize * (12 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tripWire", + new SimpleIcon(L"tripWire", slotSize * 13, slotSize * 10, + slotSize * (13 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_eye", + new SimpleIcon(L"endframe_eye", slotSize * 14, slotSize * 10, + slotSize * (14 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"whiteStone", + new SimpleIcon(L"whiteStone", slotSize * 15, slotSize * 10, + slotSize * (15 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_top", + new SimpleIcon(L"sandstone_top", slotSize * 0, slotSize * 11, + slotSize * (0 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_11", + new SimpleIcon(L"cloth_11", slotSize * 1, slotSize * 11, + slotSize * (1 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_3", + new SimpleIcon(L"cloth_3", slotSize * 2, slotSize * 11, + slotSize * (2 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldenRail_powered", + new SimpleIcon(L"goldenRail_powered", slotSize * 3, slotSize * 11, + slotSize * (3 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_cross_overlay", + new SimpleIcon(L"redstoneDust_cross_overlay", slotSize * 4, + slotSize * 11, slotSize * (4 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_line_overlay", + new SimpleIcon(L"redstoneDust_line_overlay", slotSize * 5, + slotSize * 11, slotSize * (5 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_side", + new SimpleIcon(L"enchantment_side", slotSize * 6, slotSize * 11, + slotSize * (6 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_bottom", + new SimpleIcon(L"enchantment_bottom", slotSize * 7, slotSize * 11, + slotSize * (7 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"commandBlock", + new SimpleIcon(L"commandBlock", slotSize * 8, slotSize * 11, + slotSize * (8 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"itemframe_back", + new SimpleIcon(L"itemframe_back", slotSize * 9, slotSize * 11, + slotSize * (9 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flowerPot", + new SimpleIcon(L"flowerPot", slotSize * 10, slotSize * 11, + slotSize * (10 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator", + new SimpleIcon(L"comparator", slotSize * 11, slotSize * 11, + slotSize * (11 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator_lit", + new SimpleIcon(L"comparator_lit", slotSize * 12, slotSize * 11, + slotSize * (12 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"activatorRail", + new SimpleIcon(L"activatorRail", slotSize * 13, slotSize * 11, + slotSize * (13 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"activatorRail_powered", + new SimpleIcon(L"activatorRail_powered", slotSize * 14, + slotSize * 11, slotSize * (14 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherquartz", + new SimpleIcon(L"netherquartz", slotSize * 15, slotSize * 11, + slotSize * (15 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_side", + new SimpleIcon(L"sandstone_side", slotSize * 0, slotSize * 12, + slotSize * (0 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_10", + new SimpleIcon(L"cloth_10", slotSize * 1, slotSize * 12, + slotSize * (1 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_2", + new SimpleIcon(L"cloth_2", slotSize * 2, slotSize * 12, + slotSize * (2 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"detectorRail", + new SimpleIcon(L"detectorRail", slotSize * 3, slotSize * 12, + slotSize * (3 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_jungle", + new SimpleIcon(L"leaves_jungle", slotSize * 4, slotSize * 12, + slotSize * (4 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_jungle_opaque", + new SimpleIcon(L"leaves_jungle_opaque", slotSize * 5, slotSize * 12, + slotSize * (5 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_spruce", + new SimpleIcon(L"wood_spruce", slotSize * 6, slotSize * 12, + slotSize * (6 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_jungle", + new SimpleIcon(L"wood_jungle", slotSize * 7, slotSize * 12, + slotSize * (7 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_0", + new SimpleIcon(L"carrots_0", slotSize * 8, slotSize * 12, + slotSize * (8 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_1", + new SimpleIcon(L"carrots_1", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_2", + new SimpleIcon(L"carrots_2", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_3", + new SimpleIcon(L"carrots_3", slotSize * 11, slotSize * 12, + slotSize * (11 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_0", + new SimpleIcon(L"potatoes_0", slotSize * 8, slotSize * 12, + slotSize * (8 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_1", + new SimpleIcon(L"potatoes_1", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_2", + new SimpleIcon(L"potatoes_2", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_3", + new SimpleIcon(L"potatoes_3", slotSize * 12, slotSize * 12, + slotSize * (12 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"water", + new SimpleIcon(L"water", slotSize * 13, slotSize * 12, + slotSize * (13 + 1), slotSize * (12 + 1)))); + texturesToAnimate.push_back( + std::pair(L"water", L"water")); + texturesByName.insert(stringIconMap::value_type( + L"water_flow", + new SimpleIcon(L"water_flow", slotSize * 14, slotSize * 12, + slotSize * (14 + 2), slotSize * (12 + 2)))); + texturesToAnimate.push_back(std::pair( + L"water_flow", L"water_flow")); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_bottom", + new SimpleIcon(L"sandstone_bottom", slotSize * 0, slotSize * 13, + slotSize * (0 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_9", + new SimpleIcon(L"cloth_9", slotSize * 1, slotSize * 13, + slotSize * (1 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_1", + new SimpleIcon(L"cloth_1", slotSize * 2, slotSize * 13, + slotSize * (2 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneLight", + new SimpleIcon(L"redstoneLight", slotSize * 3, slotSize * 13, + slotSize * (3 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneLight_lit", + new SimpleIcon(L"redstoneLight_lit", slotSize * 4, slotSize * 13, + slotSize * (4 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_carved", + new SimpleIcon(L"stonebricksmooth_carved", slotSize * 5, + slotSize * 13, slotSize * (5 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_birch", + new SimpleIcon(L"wood_birch", slotSize * 6, slotSize * 13, + slotSize * (6 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_base", + new SimpleIcon(L"anvil_base", slotSize * 7, slotSize * 13, + slotSize * (7 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top_damaged_1", + new SimpleIcon(L"anvil_top_damaged_1", slotSize * 8, slotSize * 13, + slotSize * (8 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_chiseled_top", + new SimpleIcon(L"quartzblock_chiseled_top", slotSize * 9, + slotSize * 13, slotSize * (9 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_lines_top", + new SimpleIcon(L"quartzblock_lines_top", slotSize * 10, + slotSize * 13, slotSize * (10 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_top", + new SimpleIcon(L"quartzblock_top", slotSize * 11, slotSize * 13, + slotSize * (11 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper", + new SimpleIcon(L"hopper", slotSize * 12, slotSize * 13, + slotSize * (12 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"detectorRail_on", + new SimpleIcon(L"detectorRail_on", slotSize * 13, slotSize * 13, + slotSize * (13 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherBrick", + new SimpleIcon(L"netherBrick", slotSize * 0, slotSize * 14, + slotSize * (0 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_8", + new SimpleIcon(L"cloth_8", slotSize * 1, slotSize * 14, + slotSize * (1 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_0", + new SimpleIcon(L"netherStalk_0", slotSize * 2, slotSize * 14, + slotSize * (2 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_1", + new SimpleIcon(L"netherStalk_1", slotSize * 3, slotSize * 14, + slotSize * (3 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_2", + new SimpleIcon(L"netherStalk_2", slotSize * 4, slotSize * 14, + slotSize * (4 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_carved", + new SimpleIcon(L"sandstone_carved", slotSize * 5, slotSize * 14, + slotSize * (5 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_smooth", + new SimpleIcon(L"sandstone_smooth", slotSize * 6, slotSize * 14, + slotSize * (6 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top", + new SimpleIcon(L"anvil_top", slotSize * 7, slotSize * 14, + slotSize * (7 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top_damaged_2", + new SimpleIcon(L"anvil_top_damaged_2", slotSize * 8, slotSize * 14, + slotSize * (8 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_chiseled", + new SimpleIcon(L"quartzblock_chiseled", slotSize * 9, slotSize * 14, + slotSize * (9 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_lines", + new SimpleIcon(L"quartzblock_lines", slotSize * 10, slotSize * 14, + slotSize * (10 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_side", + new SimpleIcon(L"quartzblock_side", slotSize * 11, slotSize * 14, + slotSize * (11 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper_inside", + new SimpleIcon(L"hopper_inside", slotSize * 12, slotSize * 14, + slotSize * (12 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lava", new SimpleIcon(L"lava", slotSize * 13, slotSize * 14, + slotSize * (13 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"lava", L"lava")); + texturesByName.insert(stringIconMap::value_type( + L"lava_flow", + new SimpleIcon(L"lava_flow", slotSize * 14, slotSize * 14, + slotSize * (14 + 2), slotSize * (14 + 2)))); + texturesToAnimate.push_back( + std::pair(L"lava_flow", L"lava_flow")); + texturesByName.insert(stringIconMap::value_type( + L"destroy_0", + new SimpleIcon(L"destroy_0", slotSize * 0, slotSize * 15, + slotSize * (0 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_1", + new SimpleIcon(L"destroy_1", slotSize * 1, slotSize * 15, + slotSize * (1 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_2", + new SimpleIcon(L"destroy_2", slotSize * 2, slotSize * 15, + slotSize * (2 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_3", + new SimpleIcon(L"destroy_3", slotSize * 3, slotSize * 15, + slotSize * (3 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_4", + new SimpleIcon(L"destroy_4", slotSize * 4, slotSize * 15, + slotSize * (4 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_5", + new SimpleIcon(L"destroy_5", slotSize * 5, slotSize * 15, + slotSize * (5 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_6", + new SimpleIcon(L"destroy_6", slotSize * 6, slotSize * 15, + slotSize * (6 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_7", + new SimpleIcon(L"destroy_7", slotSize * 7, slotSize * 15, + slotSize * (7 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_8", + new SimpleIcon(L"destroy_8", slotSize * 8, slotSize * 15, + slotSize * (8 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_9", + new SimpleIcon(L"destroy_9", slotSize * 9, slotSize * 15, + slotSize * (9 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_bottom", + new SimpleIcon(L"quartzblock_bottom", slotSize * 11, slotSize * 15, + slotSize * (11 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper_top", + new SimpleIcon(L"hopper_top", slotSize * 12, slotSize * 15, + slotSize * (12 + 1), slotSize * (15 + 1)))); + } } diff --git a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h index 3d6cac29e..76798e707 100644 --- a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h +++ b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h @@ -1,6 +1,5 @@ #pragma once - #include "../../../Minecraft.World/Util/IconRegister.h" class Icon; @@ -9,43 +8,47 @@ class Texture; class BufferedImage; // 4J Added this class to stop having to do texture stitching at runtime -class PreStitchedTextureMap : public IconRegister -{ +class PreStitchedTextureMap : public IconRegister { public: - static const std::wstring NAME_MISSING_TEXTURE; + static const std::wstring NAME_MISSING_TEXTURE; private: - const int iconType; + const int iconType; - const std::wstring name; - const std::wstring path; - const std::wstring extension; + const std::wstring name; + const std::wstring path; + const std::wstring extension; - bool m_mipMap; + bool m_mipMap; - typedef std::unordered_map stringIconMap; - stringIconMap texturesByName; // = new HashMap(); - BufferedImage *missingTexture; // = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); - StitchedTexture *missingPosition; - Texture *stitchResult; - std::vector animatedTextures; // = new ArrayList(); + typedef std::unordered_map stringIconMap; + stringIconMap texturesByName; // = new HashMap(); + BufferedImage* missingTexture; // = new BufferedImage(64, 64, + // BufferedImage.TYPE_INT_ARGB); + StitchedTexture* missingPosition; + Texture* stitchResult; + std::vector + animatedTextures; // = new ArrayList(); - std::vector > texturesToAnimate; + std::vector > texturesToAnimate; + + void loadUVs(); - void loadUVs(); public: - PreStitchedTextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipMap = false); + PreStitchedTextureMap(int type, const std::wstring& name, + const std::wstring& path, + BufferedImage* missingTexture, bool mipMap = false); - void stitch(); - StitchedTexture *getTexture(const std::wstring &name); - void cycleAnimationFrames(); - Texture *getStitchedTexture(); + void stitch(); + StitchedTexture* getTexture(const std::wstring& name); + void cycleAnimationFrames(); + Texture* getStitchedTexture(); - // 4J Stu - register is a reserved keyword in C++ - Icon *registerIcon(const std::wstring &name); + // 4J Stu - register is a reserved keyword in C++ + Icon* registerIcon(const std::wstring& name); - int getIconType(); - Icon *getMissingIcon(); + int getIconType(); + Icon* getMissingIcon(); - int getFlags() const; + int getFlags() const; }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchSlot.cpp b/Minecraft.Client/Textures/Stitching/StitchSlot.cpp index c79b57bb9..4186ddde9 100644 --- a/Minecraft.Client/Textures/Stitching/StitchSlot.cpp +++ b/Minecraft.Client/Textures/Stitching/StitchSlot.cpp @@ -3,154 +3,138 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "StitchSlot.h" -StitchSlot::StitchSlot(int originX, int originY, int width, int height) : originX(originX), originY(originY), width(width), height(height) -{ - subSlots = NULL; - textureHolder = NULL; +StitchSlot::StitchSlot(int originX, int originY, int width, int height) + : originX(originX), originY(originY), width(width), height(height) { + subSlots = NULL; + textureHolder = NULL; } -TextureHolder *StitchSlot::getHolder() -{ - return textureHolder; +TextureHolder* StitchSlot::getHolder() { return textureHolder; } + +int StitchSlot::getX() { return originX; } + +int StitchSlot::getY() { return originY; } + +bool StitchSlot::add(TextureHolder* textureHolder) { + // Already holding a texture -- doesn't account for subslots. + if (this->textureHolder != NULL) { + return false; + } + + int textureWidth = textureHolder->getWidth(); + int textureHeight = textureHolder->getHeight(); + + // We're too small to fit the texture + if (textureWidth > width || textureHeight > height) { + return false; + } + + // Exact fit! best-case-solution + if (textureWidth == width && textureHeight == height && subSlots == NULL) { + // Store somehow + this->textureHolder = textureHolder; + return true; + } + + // See if we're already divided before, if not, setup subSlots + if (subSlots == NULL) { + subSlots = new std::vector(); + + // First slot is for the new texture + subSlots->push_back( + new StitchSlot(originX, originY, textureWidth, textureHeight)); + + int spareWidth = width - textureWidth; + int spareHeight = height - textureHeight; + + if (spareHeight > 0 && spareWidth > 0) { + // Space below AND right + // + // <-right-> + // +-----+-------+ + // | | | + // | Tex | | + // | | | + // |-----+ | ^ + // | | |- bottom + // +-------------+ v + // We need to add two more areas, the one with the 'biggest' + // dimensions should be used (In the case of this ASCII drawing, + // it's the 'right hand side' that should win) + + // The 'fattest' area should be used (or when tied, the right hand + // one) + int right = std::max(height, spareWidth); + int bottom = std::max(width, spareHeight); + if (right >= bottom) { + subSlots->push_back(new StitchSlot(originX, + originY + textureHeight, + textureWidth, spareHeight)); + subSlots->push_back(new StitchSlot( + originX + textureWidth, originY, spareWidth, height)); + } else { + subSlots->push_back(new StitchSlot(originX + textureWidth, + originY, spareWidth, + textureHeight)); + subSlots->push_back(new StitchSlot( + originX, originY + textureHeight, width, spareHeight)); + } + + } else if (spareWidth == 0) { + // We just have space left below + // + // +-------------+ + // | | + // | Tex | + // | | + // |-------------+ ^ + // | | |- bottom + // +-------------+ v + subSlots->push_back(new StitchSlot(originX, originY + textureHeight, + textureWidth, spareHeight)); + } else if (spareHeight == 0) { + // Only space to the right + // + // <-right-> + // +-----+-------+ + // | | | + // | Tex | | + // | | | + // | | | + // | | | + // +-----+-------+ + subSlots->push_back(new StitchSlot(originX + textureWidth, originY, + spareWidth, textureHeight)); + } + } + + // for (final StitchSlot subSlot : subSlots) + for (AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) { + StitchSlot* subSlot = *it; + if (subSlot->add(textureHolder)) { + return true; + } + } + + return false; } -int StitchSlot::getX() -{ - return originX; -} - -int StitchSlot::getY() -{ - return originY; -} - -bool StitchSlot::add(TextureHolder *textureHolder) -{ - // Already holding a texture -- doesn't account for subslots. - if (this->textureHolder != NULL) - { - return false; - } - - int textureWidth = textureHolder->getWidth(); - int textureHeight = textureHolder->getHeight(); - - // We're too small to fit the texture - if (textureWidth > width || textureHeight > height) - { - return false; - } - - // Exact fit! best-case-solution - if (textureWidth == width && textureHeight == height && subSlots == NULL) - { - // Store somehow - this->textureHolder = textureHolder; - return true; - } - - // See if we're already divided before, if not, setup subSlots - if (subSlots == NULL) - { - subSlots = new std::vector(); - - // First slot is for the new texture - subSlots->push_back(new StitchSlot(originX, originY, textureWidth, textureHeight)); - - int spareWidth = width - textureWidth; - int spareHeight = height - textureHeight; - - if (spareHeight > 0 && spareWidth > 0) - { - // Space below AND right - // - // <-right-> - // +-----+-------+ - // | | | - // | Tex | | - // | | | - // |-----+ | ^ - // | | |- bottom - // +-------------+ v - // We need to add two more areas, the one with the 'biggest' dimensions should be used - // (In the case of this ASCII drawing, it's the 'right hand side' that should win) - - // The 'fattest' area should be used (or when tied, the right hand one) - int right = std::max(height, spareWidth); - int bottom = std::max(width, spareHeight); - if (right >= bottom) - { - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, textureWidth, spareHeight)); - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, height)); - } - else - { - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, textureHeight)); - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, width, spareHeight)); - } - - } - else if (spareWidth == 0) - { - // We just have space left below - // - // +-------------+ - // | | - // | Tex | - // | | - // |-------------+ ^ - // | | |- bottom - // +-------------+ v - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, textureWidth, spareHeight)); - } - else if (spareHeight == 0) - { - // Only space to the right - // - // <-right-> - // +-----+-------+ - // | | | - // | Tex | | - // | | | - // | | | - // | | | - // +-----+-------+ - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, textureHeight)); - } - } - - //for (final StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) - { - StitchSlot *subSlot = *it; - if (subSlot->add(textureHolder)) - { - return true; - } - } - - return false; -} - -void StitchSlot::collectAssignments(std::vector *result) -{ - if (textureHolder != NULL) - { - result->push_back(this); - } - else if (subSlots != NULL) - { - //for (StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) - { - StitchSlot *subSlot = *it; - subSlot->collectAssignments(result); - } - } +void StitchSlot::collectAssignments(std::vector* result) { + if (textureHolder != NULL) { + result->push_back(this); + } else if (subSlots != NULL) { + // for (StitchSlot subSlot : subSlots) + for (AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) { + StitchSlot* subSlot = *it; + subSlot->collectAssignments(result); + } + } } //@Override -std::wstring StitchSlot::toString() -{ - return L"Slot{originX=" + _toString(originX) + L", originY=" + _toString(originY) + L", width=" + _toString(width) + L", height=" + _toString(height) + L", texture=" + _toString(textureHolder) + L", subSlots=" + _toString(subSlots) + L'}'; +std::wstring StitchSlot::toString() { + return L"Slot{originX=" + _toString(originX) + L", originY=" + + _toString(originY) + L", width=" + _toString(width) + L", height=" + + _toString(height) + L", texture=" + _toString(textureHolder) + + L", subSlots=" + _toString(subSlots) + L'}'; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchSlot.h b/Minecraft.Client/Textures/Stitching/StitchSlot.h index a1a7dc832..b9725d674 100644 --- a/Minecraft.Client/Textures/Stitching/StitchSlot.h +++ b/Minecraft.Client/Textures/Stitching/StitchSlot.h @@ -1,28 +1,26 @@ #pragma once - class TextureHolder; -class StitchSlot -{ +class StitchSlot { private: - const int originX; - const int originY; + const int originX; + const int originY; - const int width; - const int height; - std::vector *subSlots; - TextureHolder *textureHolder; + const int width; + const int height; + std::vector* subSlots; + TextureHolder* textureHolder; public: - StitchSlot(int originX, int originY, int width, int height); + StitchSlot(int originX, int originY, int width, int height); - TextureHolder *getHolder(); - int getX(); - int getY(); - bool add(TextureHolder *textureHolder); - void collectAssignments(std::vector *result); + TextureHolder* getHolder(); + int getX(); + int getY(); + bool add(TextureHolder* textureHolder); + void collectAssignments(std::vector* result); - //@Override - std::wstring toString(); + //@Override + std::wstring toString(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp b/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp index 124c7207f..48baaf6ad 100644 --- a/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp +++ b/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp @@ -6,355 +6,275 @@ #include "StitchedTexture.h" #include "../TextureManager.h" -StitchedTexture *StitchedTexture::create(const std::wstring &name) -{ - // TODO: Generalize? - if (name.compare(L"clock") == 0) - { - return new ClockTexture(); - } - else if (name.compare(L"compass") == 0) - { - return new CompassTexture(); - } - else - { - return new StitchedTexture(name); - } +StitchedTexture* StitchedTexture::create(const std::wstring& name) { + // TODO: Generalize? + if (name.compare(L"clock") == 0) { + return new ClockTexture(); + } else if (name.compare(L"compass") == 0) { + return new CompassTexture(); + } else { + return new StitchedTexture(name); + } } -StitchedTexture::StitchedTexture(const std::wstring &name) : name(name) -{ - // 4J Initialisers - source = NULL; - rotated = false; - x = 0; - y = 0; - width = 0; - height = 0; - u0 = 0.0f; - u1 = 0.0f; - v0 = 0.0f; - v1 = 0.0f; - widthTranslation = 0.0f; - heightTranslation = 0.0f; - frame = 0; - subFrame = 0; - frameOverride = NULL; - flags = 0; - frames = NULL; +StitchedTexture::StitchedTexture(const std::wstring& name) : name(name) { + // 4J Initialisers + source = NULL; + rotated = false; + x = 0; + y = 0; + width = 0; + height = 0; + u0 = 0.0f; + u1 = 0.0f; + v0 = 0.0f; + v1 = 0.0f; + widthTranslation = 0.0f; + heightTranslation = 0.0f; + frame = 0; + subFrame = 0; + frameOverride = NULL; + flags = 0; + frames = NULL; } -void StitchedTexture::freeFrameTextures() -{ - if( frames ) - { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) - { - TextureManager::getInstance()->unregisterTexture(L"", *it); - delete *it; - } - delete frames; - } +void StitchedTexture::freeFrameTextures() { + if (frames) { + for (AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) { + TextureManager::getInstance()->unregisterTexture(L"", *it); + delete *it; + } + delete frames; + } } -StitchedTexture::~StitchedTexture() -{ - // 4jcraft, added null check - // the constructor does not allocate the frames vector. - // in some scenarios the destructor/delete is called - // without ever calling ::init() - if(frames) { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) - { - delete *it; - } - delete frames; - } +StitchedTexture::~StitchedTexture() { + // 4jcraft, added null check + // the constructor does not allocate the frames vector. + // in some scenarios the destructor/delete is called + // without ever calling ::init() + if (frames) { + for (AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) { + delete *it; + } + delete frames; + } } -void StitchedTexture::initUVs(float U0, float V0, float U1, float V1) -{ - u0 = U0; - u1 = U1; - v0 = V0; - v1 = V1; +void StitchedTexture::initUVs(float U0, float V0, float U1, float V1) { + u0 = U0; + u1 = U1; + v0 = V0; + v1 = V1; } -void StitchedTexture::init(Texture *source, std::vector *frames, int x, int y, int width, int height, bool rotated) -{ - this->source = source; - this->frames = frames; - frame = -1; // Force an update of animated textures - this->x = x; - this->y = y; - this->width = width; - this->height = height; - this->rotated = rotated; +void StitchedTexture::init(Texture* source, std::vector* frames, + int x, int y, int width, int height, bool rotated) { + this->source = source; + this->frames = frames; + frame = -1; // Force an update of animated textures + this->x = x; + this->y = y; + this->width = width; + this->height = height; + this->rotated = rotated; - float marginX = 0.0f; //0.01f / source->getWidth(); - float marginY = 0.0f; //0.01f / source->getHeight(); + float marginX = 0.0f; // 0.01f / source->getWidth(); + float marginY = 0.0f; // 0.01f / source->getHeight(); - this->u0 = x / (float) source->getWidth() + marginX; - this->u1 = (x + width) / (float) source->getWidth() - marginX; - this->v0 = y / (float) source->getHeight() + marginY; - this->v1 = (y + height) / (float) source->getHeight() - marginY; + this->u0 = x / (float)source->getWidth() + marginX; + this->u1 = (x + width) / (float)source->getWidth() - marginX; + this->v0 = y / (float)source->getHeight() + marginY; + this->v1 = (y + height) / (float)source->getHeight() - marginY; #ifndef _CONTENT_PACKAGE - bool addBreakpoint = false; - if(addBreakpoint) - { - printf("\nTreeTop\n"); - printf("u0 = %f\n", u0); - printf("u1 = %f\n", u1); - printf("v0 = %f\n", v0); - printf("v1 = %f\n", v1); - printf("\n\n"); - } + bool addBreakpoint = false; + if (addBreakpoint) { + printf("\nTreeTop\n"); + printf("u0 = %f\n", u0); + printf("u1 = %f\n", u1); + printf("v0 = %f\n", v0); + printf("v1 = %f\n", v1); + printf("\n\n"); + } #endif - this->widthTranslation = width / (float) SharedConstants::WORLD_RESOLUTION; - this->heightTranslation = height / (float) SharedConstants::WORLD_RESOLUTION; + this->widthTranslation = width / (float)SharedConstants::WORLD_RESOLUTION; + this->heightTranslation = height / (float)SharedConstants::WORLD_RESOLUTION; } -void StitchedTexture::replaceWith(StitchedTexture *texture) -{ - init(texture->source, texture->frames, texture->x, texture->y, texture->width, texture->height, texture->rotated); +void StitchedTexture::replaceWith(StitchedTexture* texture) { + init(texture->source, texture->frames, texture->x, texture->y, + texture->width, texture->height, texture->rotated); } -int StitchedTexture::getX() const -{ - return x; +int StitchedTexture::getX() const { return x; } + +int StitchedTexture::getY() const { return y; } + +int StitchedTexture::getWidth() const { return width; } + +int StitchedTexture::getHeight() const { return height; } + +static const float UVAdjust = (1.0f / 16.0f) / 256.0f; + +float StitchedTexture::getU0(bool adjust /*=false*/) const { + return adjust ? (u0 + UVAdjust) : u0; } -int StitchedTexture::getY() const -{ - return y; +float StitchedTexture::getU1(bool adjust /*=false*/) const { + return adjust ? (u1 - UVAdjust) : u1; } -int StitchedTexture::getWidth() const -{ - return width; +float StitchedTexture::getU(double offset, bool adjust /*=false*/) const { + float diff = getU1(adjust) - getU0(adjust); + return getU0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -int StitchedTexture::getHeight() const -{ - return height; +float StitchedTexture::getV0(bool adjust /*=false*/) const { + return adjust ? (v0 + UVAdjust) : v0; } -static const float UVAdjust = (1.0f/16.0f)/256.0f; - -float StitchedTexture::getU0(bool adjust/*=false*/) const -{ - return adjust ? ( u0 + UVAdjust ) : u0; +float StitchedTexture::getV1(bool adjust /*=false*/) const { + return adjust ? (v1 - UVAdjust) : v1; } -float StitchedTexture::getU1(bool adjust/*=false*/) const -{ - return adjust ? ( u1 - UVAdjust ) : u1; +float StitchedTexture::getV(double offset, bool adjust /*=false*/) const { + float diff = getV1(adjust) - getV0(adjust); + return getV0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -float StitchedTexture::getU(double offset, bool adjust/*=false*/) const -{ - float diff = getU1(adjust) - getU0(adjust); - return getU0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); +std::wstring StitchedTexture::getName() const { return name; } + +int StitchedTexture::getSourceWidth() const { return source->getWidth(); } + +int StitchedTexture::getSourceHeight() const { return source->getHeight(); } + +void StitchedTexture::cycleFrames() { + if (frameOverride != NULL) { + std::pair current = frameOverride->at(frame); + subFrame++; + if (subFrame >= current.second) { + int oldFrame = current.first; + frame = (frame + 1) % frameOverride->size(); + subFrame = 0; + + current = frameOverride->at(frame); + int newFrame = current.first; + if (oldFrame != newFrame && newFrame >= 0 && + newFrame < frames->size()) { + source->blit(x, y, frames->at(newFrame), rotated); + } + } + + } else { + int oldFrame = frame; + frame = (frame + 1) % frames->size(); + + if (oldFrame != frame) { + source->blit(x, y, frames->at(this->frame), rotated); + } + } } -float StitchedTexture::getV0(bool adjust/*=false*/) const -{ - return adjust ? ( v0 + UVAdjust ) : v0; -} +Texture* StitchedTexture::getSource() { return source; } -float StitchedTexture::getV1(bool adjust/*=false*/) const -{ - return adjust ? ( v1 - UVAdjust ) : v1; -} +Texture* StitchedTexture::getFrame(int i) { return frames->at(i); } -float StitchedTexture::getV(double offset, bool adjust/*=false*/) const -{ - float diff = getV1(adjust) - getV0(adjust); - return getV0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); -} - -std::wstring StitchedTexture::getName() const -{ - return name; -} - -int StitchedTexture::getSourceWidth() const -{ - return source->getWidth(); -} - -int StitchedTexture::getSourceHeight() const -{ - return source->getHeight(); -} - -void StitchedTexture::cycleFrames() -{ - if (frameOverride != NULL) - { - std::pair current = frameOverride->at(frame); - subFrame++; - if (subFrame >= current.second) - { - int oldFrame = current.first; - frame = (frame + 1) % frameOverride->size(); - subFrame = 0; - - current = frameOverride->at(frame); - int newFrame = current.first; - if (oldFrame != newFrame && newFrame >= 0 && newFrame < frames->size()) - { - source->blit(x, y, frames->at(newFrame), rotated); - } - } - - } - else - { - int oldFrame = frame; - frame = (frame + 1) % frames->size(); - - if (oldFrame != frame) - { - source->blit(x, y, frames->at(this->frame), rotated); - } - } -} - -Texture *StitchedTexture::getSource() -{ - return source; -} - -Texture *StitchedTexture::getFrame(int i) -{ - return frames->at(i); -} - -int StitchedTexture::getFrames() -{ - return frames?frames->size():0; -} +int StitchedTexture::getFrames() { return frames ? frames->size() : 0; } /** -* Loads animation frames from a file with the syntax, -* 0,1,2,3, -* 4*10,5*10, -* 4*10,3,2,1, -* 0 -* or similar -* -* @param bufferedReader -*/ -void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) -{ - if(frameOverride != NULL) - { - delete frameOverride; - frameOverride = NULL; - } - frame = 0; - subFrame = 0; + * Loads animation frames from a file with the syntax, + * 0,1,2,3, + * 4*10,5*10, + * 4*10,3,2,1, + * 0 + * or similar + * + * @param bufferedReader + */ +void StitchedTexture::loadAnimationFrames(BufferedReader* bufferedReader) { + if (frameOverride != NULL) { + delete frameOverride; + frameOverride = NULL; + } + frame = 0; + subFrame = 0; - intPairVector *results = new intPairVector(); + intPairVector* results = new intPairVector(); - //try { - std::wstring line = bufferedReader->readLine(); - while (!line.empty()) - { - line = trimString(line); - if (line.length() > 0) - { - std::vector tokens = stringSplit(line, L','); - //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) - { - std::wstring token = *it; - int multiPos = token.find_first_of('*'); - if (multiPos > 0) - { - int frame = _fromString(token.substr(0, multiPos)); - int count = _fromString(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); - } - else - { - int tokenVal = _fromString(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); - } - } - } - line = bufferedReader->readLine(); - } - //} catch (Exception e) { - // System.err.println("Failed to read animation info for " + name + ": " + e.getMessage()); - //} + // try { + std::wstring line = bufferedReader->readLine(); + while (!line.empty()) { + line = trimString(line); + if (line.length() > 0) { + std::vector tokens = stringSplit(line, L','); + // for (String token : tokens) + for (AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) { + std::wstring token = *it; + int multiPos = token.find_first_of('*'); + if (multiPos > 0) { + int frame = _fromString(token.substr(0, multiPos)); + int count = _fromString(token.substr(multiPos + 1)); + results->push_back(intPairVector::value_type(frame, count)); + } else { + int tokenVal = _fromString(token); + results->push_back(intPairVector::value_type(tokenVal, 1)); + } + } + } + line = bufferedReader->readLine(); + } + //} catch (Exception e) { + // System.err.println("Failed to read animation info for " + name + ": " + + //e.getMessage()); + //} - if (!results->empty() && results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) - { - frameOverride = results; - } - else - { - delete results; - } + if (!results->empty() && + results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) { + frameOverride = results; + } else { + delete results; + } } -void StitchedTexture::loadAnimationFrames(const std::wstring &string) -{ - if(frameOverride != NULL) - { - delete frameOverride; - frameOverride = NULL; - } - frame = 0; - subFrame = 0; +void StitchedTexture::loadAnimationFrames(const std::wstring& string) { + if (frameOverride != NULL) { + delete frameOverride; + frameOverride = NULL; + } + frame = 0; + subFrame = 0; - intPairVector *results = new intPairVector(); + intPairVector* results = new intPairVector(); - std::vector tokens = stringSplit(trimString(string), L','); - //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) - { - std::wstring token = trimString(*it); - int multiPos = token.find_first_of('*'); - if (multiPos > 0) - { - int frame = _fromString(token.substr(0, multiPos)); - int count = _fromString(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); - } - else if(!token.empty()) - { - int tokenVal = _fromString(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); - } - } + std::vector tokens = stringSplit(trimString(string), L','); + // for (String token : tokens) + for (AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) { + std::wstring token = trimString(*it); + int multiPos = token.find_first_of('*'); + if (multiPos > 0) { + int frame = _fromString(token.substr(0, multiPos)); + int count = _fromString(token.substr(multiPos + 1)); + results->push_back(intPairVector::value_type(frame, count)); + } else if (!token.empty()) { + int tokenVal = _fromString(token); + results->push_back(intPairVector::value_type(tokenVal, 1)); + } + } - if (!results->empty() && results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) - { - frameOverride = results; - } - else - { - delete results; - } + if (!results->empty() && + results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) { + frameOverride = results; + } else { + delete results; + } } -void StitchedTexture::setFlags(int flags) -{ - this->flags = flags; -} +void StitchedTexture::setFlags(int flags) { this->flags = flags; } -int StitchedTexture::getFlags() const -{ - return this->flags; -} +int StitchedTexture::getFlags() const { return this->flags; } -bool StitchedTexture::hasOwnData() -{ - return true; -} +bool StitchedTexture::hasOwnData() { return true; } diff --git a/Minecraft.Client/Textures/Stitching/StitchedTexture.h b/Minecraft.Client/Textures/Stitching/StitchedTexture.h index 306ffd1b7..e1059ed5e 100644 --- a/Minecraft.Client/Textures/Stitching/StitchedTexture.h +++ b/Minecraft.Client/Textures/Stitching/StitchedTexture.h @@ -1,89 +1,89 @@ #pragma once - #include "../../../Minecraft.World/Util/Icon.h" class Texture; -class StitchedTexture : public Icon -{ +class StitchedTexture : public Icon { private: - const std::wstring name; + const std::wstring name; protected: - Texture *source; - std::vector *frames; + Texture* source; + std::vector* frames; private: - typedef std::vector > intPairVector; - intPairVector *frameOverride; - int flags; + typedef std::vector > intPairVector; + intPairVector* frameOverride; + int flags; protected: - bool rotated; + bool rotated; - int x; - int y; + int x; + int y; protected: - int width; - int height; + int width; + int height; - float u0; - float u1; - float v0; - float v1; + float u0; + float u1; + float v0; + float v1; - float widthTranslation; - float heightTranslation; + float widthTranslation; + float heightTranslation; protected: - int frame; - int subFrame; + int frame; + int subFrame; public: - static StitchedTexture *create(const std::wstring &name); - - ~StitchedTexture(); + static StitchedTexture* create(const std::wstring& name); + + ~StitchedTexture(); + protected: - StitchedTexture(const std::wstring &name); + StitchedTexture(const std::wstring& name); public: - void initUVs(float U0, float V0, float U1, float V1); - void init(Texture *source, std::vector *frames, int x, int y, int width, int height, bool rotated); - void replaceWith(StitchedTexture *texture); - int getX() const; - int getY() const; - int getWidth() const; - int getHeight() const; - float getU0(bool adjust = false) const; - float getU1(bool adjust = false) const; - float getU(double offset, bool adjust = false) const; - float getV0(bool adjust = false) const; - float getV1(bool adjust = false) const; - float getV(double offset, bool adjust = false) const; - std::wstring getName() const; - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual void cycleFrames(); - Texture *getSource(); - Texture *getFrame(int i); - virtual int getFrames(); + void initUVs(float U0, float V0, float U1, float V1); + void init(Texture* source, std::vector* frames, int x, int y, + int width, int height, bool rotated); + void replaceWith(StitchedTexture* texture); + int getX() const; + int getY() const; + int getWidth() const; + int getHeight() const; + float getU0(bool adjust = false) const; + float getU1(bool adjust = false) const; + float getU(double offset, bool adjust = false) const; + float getV0(bool adjust = false) const; + float getV1(bool adjust = false) const; + float getV(double offset, bool adjust = false) const; + std::wstring getName() const; + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual void cycleFrames(); + Texture* getSource(); + Texture* getFrame(int i); + virtual int getFrames(); - /** - * Loads animation frames from a file with the syntax, - * 0,1,2,3, - * 4*10,5*10, - * 4*10,3,2,1, - * 0 - * or similar - * - * @param bufferedReader - */ - void loadAnimationFrames(BufferedReader *bufferedReader); - void loadAnimationFrames(const std::wstring &string); // 4J Added + /** + * Loads animation frames from a file with the syntax, + * 0,1,2,3, + * 4*10,5*10, + * 4*10,3,2,1, + * 0 + * or similar + * + * @param bufferedReader + */ + void loadAnimationFrames(BufferedReader* bufferedReader); + void loadAnimationFrames(const std::wstring& string); // 4J Added - int getFlags() const ; // 4J added - void setFlags(int flags); // 4J added - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + int getFlags() const; // 4J added + void setFlags(int flags); // 4J added + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; diff --git a/Minecraft.Client/Textures/Stitching/Stitcher.cpp b/Minecraft.Client/Textures/Stitching/Stitcher.cpp index b70751dde..24f3332d1 100644 --- a/Minecraft.Client/Textures/Stitching/Stitcher.cpp +++ b/Minecraft.Client/Textures/Stitching/Stitcher.cpp @@ -6,256 +6,233 @@ #include "StitchedTexture.h" #include "Stitcher.h" -void Stitcher::_init(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale) -{ - this->name = name; - this->maxWidth = maxWidth; - this->maxHeight = maxHeight; - this->forcePowerOfTwo = forcePowerOfTwo; - this->forcedScale = forcedScale; +void Stitcher::_init(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale) { + this->name = name; + this->maxWidth = maxWidth; + this->maxHeight = maxHeight; + this->forcePowerOfTwo = forcePowerOfTwo; + this->forcedScale = forcedScale; - // 4J init - storageX = 0; - storageY = 0; - stitchedTexture = NULL; + // 4J init + storageX = 0; + storageY = 0; + stitchedTexture = NULL; } -Stitcher::Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo) -{ - _init(name, maxWidth, maxHeight, forcePowerOfTwo, 0); +Stitcher::Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo) { + _init(name, maxWidth, maxHeight, forcePowerOfTwo, 0); } -Stitcher::Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale) -{ - _init(name, maxWidth, maxHeight, forcePowerOfTwo, forcedScale); +Stitcher::Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale) { + _init(name, maxWidth, maxHeight, forcePowerOfTwo, forcedScale); } -int Stitcher::getWidth() -{ - return storageX; +int Stitcher::getWidth() { return storageX; } + +int Stitcher::getHeight() { return storageY; } + +void Stitcher::addTexture(TextureHolder* textureHolder) { + if (forcedScale > 0) { + textureHolder->setForcedScale(forcedScale); + } + texturesToBeStitched.insert(textureHolder); } -int Stitcher::getHeight() -{ - return storageY; +Texture* Stitcher::constructTexture(bool mipmap) { + if (forcePowerOfTwo) { + storageX = smallestEncompassingPowerOfTwo(storageX); + storageY = smallestEncompassingPowerOfTwo(storageY); + } + + stitchedTexture = TextureManager::getInstance()->createTexture( + name, Texture::TM_DYNAMIC, storageX, storageY, Texture::TFMT_RGBA, + mipmap); + stitchedTexture->fill(stitchedTexture->getRect(), 0xffff0000); + + std::vector* slots = gatherAreas(); + for (int index = 0; index < slots->size(); index++) { + StitchSlot* slot = slots->at(index); + TextureHolder* textureHolder = slot->getHolder(); + stitchedTexture->blit(slot->getX(), slot->getY(), + textureHolder->getTexture(), + textureHolder->isRotated()); + } + delete slots; + TextureManager::getInstance()->registerName(name, stitchedTexture); + + return stitchedTexture; } -void Stitcher::addTexture(TextureHolder *textureHolder) -{ - if (forcedScale > 0) - { - textureHolder->setForcedScale(forcedScale); - } - texturesToBeStitched.insert(textureHolder); -} +void Stitcher::stitch() { + // TextureHolder[] textureHolders = texturesToBeStitched.toArray(new + // TextureHolder[texturesToBeStitched.size()]); Arrays.sort(textureHolders); -Texture *Stitcher::constructTexture(bool mipmap) -{ - if (forcePowerOfTwo) - { - storageX = smallestEncompassingPowerOfTwo(storageX); - storageY = smallestEncompassingPowerOfTwo(storageY); - } + stitchedTexture = NULL; - stitchedTexture = TextureManager::getInstance()->createTexture(name, Texture::TM_DYNAMIC, storageX, storageY, Texture::TFMT_RGBA, mipmap); - stitchedTexture->fill(stitchedTexture->getRect(), 0xffff0000); + // for (int i = 0; i < textureHolders.length; i++) + for (AUTO_VAR(it, texturesToBeStitched.begin()); + it != texturesToBeStitched.end(); ++it) { + TextureHolder* textureHolder = *it; // textureHolders[i]; - std::vector *slots = gatherAreas(); - for (int index = 0; index < slots->size(); index++) - { - StitchSlot *slot = slots->at(index); - TextureHolder *textureHolder = slot->getHolder(); - stitchedTexture->blit(slot->getX(), slot->getY(), textureHolder->getTexture(), textureHolder->isRotated()); - } - delete slots; - TextureManager::getInstance()->registerName(name, stitchedTexture); - - return stitchedTexture; -} - -void Stitcher::stitch() -{ - //TextureHolder[] textureHolders = texturesToBeStitched.toArray(new TextureHolder[texturesToBeStitched.size()]); - //Arrays.sort(textureHolders); - - stitchedTexture = NULL; - - //for (int i = 0; i < textureHolders.length; i++) - for(AUTO_VAR(it, texturesToBeStitched.begin()); it != texturesToBeStitched.end(); ++it) - { - TextureHolder *textureHolder = *it; //textureHolders[i]; - - if (!addToStorage(textureHolder)) - { - app.DebugPrintf("Stitcher exception!\n"); + if (!addToStorage(textureHolder)) { + app.DebugPrintf("Stitcher exception!\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //throw new StitcherException(textureHolder); - } - } + // throw new StitcherException(textureHolder); + } + } } -std::vector *Stitcher::gatherAreas() -{ - std::vector *result = new std::vector(); +std::vector* Stitcher::gatherAreas() { + std::vector* result = new std::vector(); - //for (StitchSlot slot : storage) - for(AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) - { - StitchSlot *slot = *it; - slot->collectAssignments(result); - } + // for (StitchSlot slot : storage) + for (AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) { + StitchSlot* slot = *it; + slot->collectAssignments(result); + } - return result; + return result; } // Based on: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -int Stitcher::smallestEncompassingPowerOfTwo(int input) -{ - int result = input - 1; - result |= result >> 1; - result |= result >> 2; - result |= result >> 4; - result |= result >> 8; - result |= result >> 16; - return result + 1; +int Stitcher::smallestEncompassingPowerOfTwo(int input) { + int result = input - 1; + result |= result >> 1; + result |= result >> 2; + result |= result >> 4; + result |= result >> 8; + result |= result >> 16; + return result + 1; } -bool Stitcher::addToStorage(TextureHolder *textureHolder) -{ - for (int i = 0; i < storage.size(); i++) - { - if (storage.at(i)->add(textureHolder)) - { - return true; - } +bool Stitcher::addToStorage(TextureHolder* textureHolder) { + for (int i = 0; i < storage.size(); i++) { + if (storage.at(i)->add(textureHolder)) { + return true; + } - // Try rotated - textureHolder->rotate(); - if (storage.at(i)->add(textureHolder)) - { - return true; - } + // Try rotated + textureHolder->rotate(); + if (storage.at(i)->add(textureHolder)) { + return true; + } - // Undo rotation - textureHolder->rotate(); - } + // Undo rotation + textureHolder->rotate(); + } - return expand(textureHolder); + return expand(textureHolder); } /** -* Expand the current storage to take in account the new texture. -* This should only be called if it didn't fit anywhere. -* -* @param textureHolder -* @return Boolean indicating if it could accommodate for the growth -*/ -bool Stitcher::expand(TextureHolder *textureHolder) -{ - int minDistance = std::min(textureHolder->getHeight(), textureHolder->getWidth()); - bool firstAddition = storageX == 0 && storageY == 0; + * Expand the current storage to take in account the new texture. + * This should only be called if it didn't fit anywhere. + * + * @param textureHolder + * @return Boolean indicating if it could accommodate for the growth + */ +bool Stitcher::expand(TextureHolder* textureHolder) { + int minDistance = + std::min(textureHolder->getHeight(), textureHolder->getWidth()); + bool firstAddition = storageX == 0 && storageY == 0; - // It couldn't fit, decide which direction to grow to - bool growOnX; - if (forcePowerOfTwo) - { - int xCurrentSize = smallestEncompassingPowerOfTwo(storageX); - int yCurrentSize = smallestEncompassingPowerOfTwo(storageY); - int xNewSize = smallestEncompassingPowerOfTwo(storageX + minDistance); - int yNewSize = smallestEncompassingPowerOfTwo(storageY + minDistance); + // It couldn't fit, decide which direction to grow to + bool growOnX; + if (forcePowerOfTwo) { + int xCurrentSize = smallestEncompassingPowerOfTwo(storageX); + int yCurrentSize = smallestEncompassingPowerOfTwo(storageY); + int xNewSize = smallestEncompassingPowerOfTwo(storageX + minDistance); + int yNewSize = smallestEncompassingPowerOfTwo(storageY + minDistance); - bool xCanGrow = xNewSize <= maxWidth; - bool yCanGrow = yNewSize <= maxHeight; + bool xCanGrow = xNewSize <= maxWidth; + bool yCanGrow = yNewSize <= maxHeight; - if (!xCanGrow && !yCanGrow) - { - return false; - } + if (!xCanGrow && !yCanGrow) { + return false; + } - // Even if the smallest side fits the larger might not >.> - int maxDistance = std::max(textureHolder->getHeight(), textureHolder->getWidth()); - // TODO: This seems wrong ... - if (firstAddition && !xCanGrow && !(smallestEncompassingPowerOfTwo(storageY + maxDistance) <= maxHeight)) - { - return false; - } + // Even if the smallest side fits the larger might not >.> + int maxDistance = + std::max(textureHolder->getHeight(), textureHolder->getWidth()); + // TODO: This seems wrong ... + if (firstAddition && !xCanGrow && + !(smallestEncompassingPowerOfTwo(storageY + maxDistance) <= + maxHeight)) { + return false; + } - bool xWillGrow = xCurrentSize != xNewSize; - bool yWillGrow = yCurrentSize != yNewSize; + bool xWillGrow = xCurrentSize != xNewSize; + bool yWillGrow = yCurrentSize != yNewSize; - if (xWillGrow ^ yWillGrow) - { - // Either grows - //only pick X if it can grow AND it wanted to grow - // if !xCanGrow then yCanGrow + if (xWillGrow ^ yWillGrow) { + // Either grows + // only pick X if it can grow AND it wanted to grow + // if !xCanGrow then yCanGrow + growOnX = xWillGrow && xCanGrow; + } else { + // Both or Neither grow -- smallest side wins + growOnX = xCanGrow && xCurrentSize <= yCurrentSize; + } + } else { + // We need to figure out to either expand + bool xCanGrow = (storageX + minDistance) <= maxWidth; + bool yCanGrow = (storageY + minDistance) <= maxHeight; - growOnX = xWillGrow && xCanGrow; - } - else - { - // Both or Neither grow -- smallest side wins - growOnX = xCanGrow && xCurrentSize <= yCurrentSize; - } - } - else - { - // We need to figure out to either expand - bool xCanGrow = (storageX + minDistance) <= maxWidth; - bool yCanGrow = (storageY + minDistance) <= maxHeight; + if (!xCanGrow && !yCanGrow) { + return false; + } - if (!xCanGrow && !yCanGrow) - { - return false; - } + // Prefer growing on X when its: first addition *or* its the smaller of + // the two sides + growOnX = (firstAddition || storageX <= storageY) && xCanGrow; + } - // Prefer growing on X when its: first addition *or* its the smaller of the two sides - growOnX = (firstAddition || storageX <= storageY) && xCanGrow; - } + StitchSlot* slot; + if (growOnX) { + if (textureHolder->getWidth() > textureHolder->getHeight()) { + textureHolder->rotate(); + } - StitchSlot *slot; - if (growOnX) - { - if (textureHolder->getWidth() > textureHolder->getHeight()) - { - textureHolder->rotate(); - } + // Grow the 'Y' when it has no size yet + if (storageY == 0) { + storageY = textureHolder->getHeight(); + } - // Grow the 'Y' when it has no size yet - if (storageY == 0) - { - storageY = textureHolder->getHeight(); - } + int newSlotWidth = textureHolder->getWidth(); + // 4J Stu - If we are expanding the texture, then allocate the full + // powerOfTwo size that we are going to eventually create + if (forcePowerOfTwo) { + newSlotWidth = + smallestEncompassingPowerOfTwo(storageX + newSlotWidth) - + storageX; + } + slot = new StitchSlot(storageX, 0, newSlotWidth, storageY); + // storageX += textureHolder->getWidth(); + storageX += newSlotWidth; + } else { + int newSlotHeight = textureHolder->getHeight(); + // 4J Stu - If we are expanding the texture, then allocate the full + // powerOfTwo size that we are going to eventually create + if (forcePowerOfTwo) { + newSlotHeight = + smallestEncompassingPowerOfTwo(storageY + newSlotHeight) - + storageY; + } - int newSlotWidth = textureHolder->getWidth(); - // 4J Stu - If we are expanding the texture, then allocate the full powerOfTwo size that we are going to eventually create - if (forcePowerOfTwo) - { - newSlotWidth = smallestEncompassingPowerOfTwo(storageX + newSlotWidth) - storageX; - } - slot = new StitchSlot(storageX, 0, newSlotWidth, storageY); - //storageX += textureHolder->getWidth(); - storageX += newSlotWidth; - } - else - { - int newSlotHeight = textureHolder->getHeight(); - // 4J Stu - If we are expanding the texture, then allocate the full powerOfTwo size that we are going to eventually create - if (forcePowerOfTwo) - { - newSlotHeight = smallestEncompassingPowerOfTwo(storageY + newSlotHeight) - storageY; - } + // grow on Y + slot = new StitchSlot(0, storageY, storageX, newSlotHeight); + // storageY += textureHolder->getHeight(); + storageY += newSlotHeight; + } - // grow on Y - slot = new StitchSlot(0, storageY, storageX, newSlotHeight); - //storageY += textureHolder->getHeight(); - storageY += newSlotHeight; - } + slot->add(textureHolder); + storage.push_back(slot); - slot->add(textureHolder); - storage.push_back(slot); - - return true; + return true; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/Stitcher.h b/Minecraft.Client/Textures/Stitching/Stitcher.h index 7ade956a8..ca5c7846a 100644 --- a/Minecraft.Client/Textures/Stitching/Stitcher.h +++ b/Minecraft.Client/Textures/Stitching/Stitcher.h @@ -1,60 +1,64 @@ #pragma once - class StitchSlot; class Texture; #include "../TextureHolder.h" -class Stitcher -{ +class Stitcher { public: - static const int STITCH_SUCCESS = 0; - static const int STITCH_RETRY = 1; - static const int STITCH_ABORT = 2; + static const int STITCH_SUCCESS = 0; + static const int STITCH_RETRY = 1; + static const int STITCH_ABORT = 2; - static const int MAX_MIPLEVEL = 0; // This should be 4 again later when we *ACTUALLY* mipmap - static const int MIN_TEXEL = 1 << MAX_MIPLEVEL; + static const int MAX_MIPLEVEL = + 0; // This should be 4 again later when we *ACTUALLY* mipmap + static const int MIN_TEXEL = 1 << MAX_MIPLEVEL; private: - std::set texturesToBeStitched; // = new HashSet(256); - std::vector storage; // = new ArrayList(256); - int storageX; - int storageY; + std::set + texturesToBeStitched; // = new HashSet(256); + std::vector storage; // = new ArrayList(256); + int storageX; + int storageY; - int maxWidth; - int maxHeight; - bool forcePowerOfTwo; - int forcedScale; + int maxWidth; + int maxHeight; + bool forcePowerOfTwo; + int forcedScale; - Texture *stitchedTexture; + Texture* stitchedTexture; - std::wstring name; + std::wstring name; - void _init(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale); + void _init(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale); public: - Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo); - Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale); + Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo); + Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale); - int getWidth(); - int getHeight(); - void addTexture(TextureHolder *textureHolder); - Texture *constructTexture(bool mipmap = true); // 4J Added mipmap param - void stitch(); - std::vector *gatherAreas(); + int getWidth(); + int getHeight(); + void addTexture(TextureHolder* textureHolder); + Texture* constructTexture(bool mipmap = true); // 4J Added mipmap param + void stitch(); + std::vector* gatherAreas(); -private: - // Based on: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 - int smallestEncompassingPowerOfTwo(int input); +private: + // Based on: + // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + int smallestEncompassingPowerOfTwo(int input); - bool addToStorage(TextureHolder *textureHolder); + bool addToStorage(TextureHolder* textureHolder); - /** - * Expand the current storage to take in account the new texture. - * This should only be called if it didn't fit anywhere. - * - * @param textureHolder - * @return Boolean indicating if it could accommodate for the growth - */ - bool expand(TextureHolder *textureHolder); + /** + * Expand the current storage to take in account the new texture. + * This should only be called if it didn't fit anywhere. + * + * @param textureHolder + * @return Boolean indicating if it could accommodate for the growth + */ + bool expand(TextureHolder* textureHolder); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/TextureMap.cpp b/Minecraft.Client/Textures/Stitching/TextureMap.cpp index dc8efa546..a0af280bb 100644 --- a/Minecraft.Client/Textures/Stitching/TextureMap.cpp +++ b/Minecraft.Client/Textures/Stitching/TextureMap.cpp @@ -17,232 +17,234 @@ const std::wstring TextureMap::NAME_MISSING_TEXTURE = L"missingno"; -TextureMap::TextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipmap) : iconType(type), name(name), path(path), extension(L".png") -{ - this->missingTexture = missingTexture; +TextureMap::TextureMap(int type, const std::wstring& name, + const std::wstring& path, BufferedImage* missingTexture, + bool mipmap) + : iconType(type), name(name), path(path), extension(L".png") { + this->missingTexture = missingTexture; - // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + // 4J Initialisers + missingPosition = NULL; + stitchResult = NULL; - m_mipMap = mipmap; + m_mipMap = mipmap; } -void TextureMap::stitch() -{ - texturesToRegister.clear(); +void TextureMap::stitch() { + texturesToRegister.clear(); - if (iconType == Icon::TYPE_TERRAIN) - { - //for (Tile tile : Tile.tiles) - for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) - { - if (Tile::tiles[i] != NULL) - { - Tile::tiles[i]->registerIcons(this); - } - } + if (iconType == Icon::TYPE_TERRAIN) { + // for (Tile tile : Tile.tiles) + for (unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { + if (Tile::tiles[i] != NULL) { + Tile::tiles[i]->registerIcons(this); + } + } - Minecraft::GetInstance()->levelRenderer->registerTextures(this); - EntityRenderDispatcher::instance->registerTerrainTextures(this); - } + Minecraft::GetInstance()->levelRenderer->registerTextures(this); + EntityRenderDispatcher::instance->registerTerrainTextures(this); + } - //for (Item item : Item.items) - for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) - { - Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) - { - item->registerIcons(this); - } - } + // for (Item item : Item.items) + for (unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { + Item* item = Item::items[i]; + if (item != NULL && item->getIconType() == iconType) { + item->registerIcons(this); + } + } - // Collection bucket for multiple frames per texture - std::unordered_map * > textures; // = new HashMap>(); + // Collection bucket for multiple frames per texture + std::unordered_map*> + textures; // = new HashMap>(); - Stitcher *stitcher = TextureManager::getInstance()->createStitcher(name); - - for(AUTO_VAR(it,texturesByName.begin()); it != texturesByName.end(); ++it) - { - delete it->second; - } - texturesByName.clear(); - animatedTextures.clear(); + Stitcher* stitcher = TextureManager::getInstance()->createStitcher(name); - // Prep missing texture -- anything that has no resources will get pointed at this one - Texture *missingTex = TextureManager::getInstance()->createTexture(NAME_MISSING_TEXTURE, Texture::TM_CONTAINER, missingTexture->getWidth(), missingTexture->getHeight(), Texture::WM_CLAMP, Texture::TFMT_RGBA, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, m_mipMap, missingTexture); - TextureHolder *missingHolder = new TextureHolder(missingTex); + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + delete it->second; + } + texturesByName.clear(); + animatedTextures.clear(); - stitcher->addTexture(missingHolder); - std::vector *missingVec = new std::vector(); - missingVec->push_back(missingTex); - textures.insert( std::unordered_map * >::value_type( missingHolder, missingVec )); + // Prep missing texture -- anything that has no resources will get pointed + // at this one + Texture* missingTex = TextureManager::getInstance()->createTexture( + NAME_MISSING_TEXTURE, Texture::TM_CONTAINER, missingTexture->getWidth(), + missingTexture->getHeight(), Texture::WM_CLAMP, Texture::TFMT_RGBA, + Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, m_mipMap, missingTexture); + TextureHolder* missingHolder = new TextureHolder(missingTex); - // Extract frames from textures and add them to the stitchers - //for (final String name : texturesToRegister.keySet()) - for(AUTO_VAR(it, texturesToRegister.begin()); it != texturesToRegister.end(); ++it) - { - std::wstring name = it->first; + stitcher->addTexture(missingHolder); + std::vector* missingVec = new std::vector(); + missingVec->push_back(missingTex); + textures.insert( + std::unordered_map*>::value_type( + missingHolder, missingVec)); - std::wstring filename = path + name + extension; + // Extract frames from textures and add them to the stitchers + // for (final String name : texturesToRegister.keySet()) + for (AUTO_VAR(it, texturesToRegister.begin()); + it != texturesToRegister.end(); ++it) { + std::wstring name = it->first; - // TODO: [EB] Put the frames into a proper object, not this inside out hack - std::vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); + std::wstring filename = path + name + extension; - if (frames == NULL || frames->empty()) - { - continue; // Couldn't load a texture, skip it - } + // TODO: [EB] Put the frames into a proper object, not this inside out + // hack + std::vector* frames = + TextureManager::getInstance()->createTextures(filename, m_mipMap); - TextureHolder *holder = new TextureHolder(frames->at(0)); - stitcher->addTexture(holder); + if (frames == NULL || frames->empty()) { + continue; // Couldn't load a texture, skip it + } - // Store frames - textures.insert( std::unordered_map * >::value_type( holder, frames ) ); - } + TextureHolder* holder = new TextureHolder(frames->at(0)); + stitcher->addTexture(holder); - // Stitch! - //try { - stitcher->stitch(); - //} catch (StitcherException e) { - // throw e; - // TODO: [EB] Retry mechanism - //} + // Store frames + textures.insert( + std::unordered_map*>::value_type(holder, + frames)); + } - // Create the final image - stitchResult = stitcher->constructTexture(m_mipMap); + // Stitch! + // try { + stitcher->stitch(); + //} catch (StitcherException e) { + // throw e; + // TODO: [EB] Retry mechanism + //} - // Extract all the final positions and store them - AUTO_VAR(areas, stitcher->gatherAreas()); - //for (StitchSlot slot : stitcher.gatherAreas()) - for(AUTO_VAR(it, areas->begin()); it != areas->end(); ++it) - { - StitchSlot *slot = *it; - TextureHolder *textureHolder = slot->getHolder(); + // Create the final image + stitchResult = stitcher->constructTexture(m_mipMap); - Texture *texture = textureHolder->getTexture(); - std::wstring textureName = texture->getName(); + // Extract all the final positions and store them + AUTO_VAR(areas, stitcher->gatherAreas()); + // for (StitchSlot slot : stitcher.gatherAreas()) + for (AUTO_VAR(it, areas->begin()); it != areas->end(); ++it) { + StitchSlot* slot = *it; + TextureHolder* textureHolder = slot->getHolder(); - std::vector *frames = textures.find(textureHolder)->second; + Texture* texture = textureHolder->getTexture(); + std::wstring textureName = texture->getName(); - StitchedTexture *stored = NULL; - - AUTO_VAR(itTex, texturesToRegister.find(textureName) ); - if(itTex != texturesToRegister.end() ) stored = itTex->second; + std::vector* frames = textures.find(textureHolder)->second; - // [EB]: What is this code for? debug warnings for when during transition? - bool missing = false; - if (stored == NULL) - { - missing = true; - stored = StitchedTexture::create(textureName); + StitchedTexture* stored = NULL; - if (textureName.compare(NAME_MISSING_TEXTURE)!=0) - { - //Minecraft::getInstance()->getLogger().warning("Couldn't find premade icon for " + textureName + " doing " + name); + AUTO_VAR(itTex, texturesToRegister.find(textureName)); + if (itTex != texturesToRegister.end()) stored = itTex->second; + + // [EB]: What is this code for? debug warnings for when during + // transition? + bool missing = false; + if (stored == NULL) { + missing = true; + stored = StitchedTexture::create(textureName); + + if (textureName.compare(NAME_MISSING_TEXTURE) != 0) { + // Minecraft::getInstance()->getLogger().warning("Couldn't find + // premade icon for " + textureName + " doing " + name); #ifndef _CONTENT_PACKAGE - wprintf(L"Couldn't find premade icon for %ls doing %ls\n", textureName.c_str(), name.c_str() ); + wprintf(L"Couldn't find premade icon for %ls doing %ls\n", + textureName.c_str(), name.c_str()); #endif - } - } + } + } - stored->init(stitchResult, frames, slot->getX(), slot->getY(), textureHolder->getTexture()->getWidth(), textureHolder->getTexture()->getHeight(), textureHolder->isRotated()); + stored->init(stitchResult, frames, slot->getX(), slot->getY(), + textureHolder->getTexture()->getWidth(), + textureHolder->getTexture()->getHeight(), + textureHolder->isRotated()); - texturesByName.insert( stringStitchedTextureMap::value_type(textureName, stored) ); - if (!missing) texturesToRegister.erase(textureName); + texturesByName.insert( + stringStitchedTextureMap::value_type(textureName, stored)); + if (!missing) texturesToRegister.erase(textureName); - if (frames->size() > 1) - { - animatedTextures.push_back(stored); + if (frames->size() > 1) { + animatedTextures.push_back(stored); - std::wstring animationDefinitionFile = textureName + L".txt"; + std::wstring animationDefinitionFile = textureName + L".txt"; - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - bool requiresFallback = !texturePack->hasFile(L"\\" + textureName + L".png", false); - //try { - InputStream *fileStream = texturePack->getResource(L"\\" + path + animationDefinitionFile, requiresFallback); + TexturePack* texturePack = + Minecraft::GetInstance()->skins->getSelected(); + bool requiresFallback = + !texturePack->hasFile(L"\\" + textureName + L".png", false); + // try { + InputStream* fileStream = texturePack->getResource( + L"\\" + path + animationDefinitionFile, requiresFallback); - //Minecraft::getInstance()->getLogger().info("Found animation info for: " + animationDefinitionFile); + // Minecraft::getInstance()->getLogger().info("Found animation info + // for: " + animationDefinitionFile); #ifndef _CONTENT_PACKAGE - wprintf(L"Found animation info for: %ls\n", animationDefinitionFile.c_str() ); + wprintf(L"Found animation info for: %ls\n", + animationDefinitionFile.c_str()); #endif - InputStreamReader isr(fileStream); - BufferedReader br(&isr); - stored->loadAnimationFrames(&br); - delete fileStream; - //} catch (IOException ignored) { - //} - } - } - delete areas; + InputStreamReader isr(fileStream); + BufferedReader br(&isr); + stored->loadAnimationFrames(&br); + delete fileStream; + //} catch (IOException ignored) { + //} + } + } + delete areas; - missingPosition = texturesByName.find(NAME_MISSING_TEXTURE)->second; + missingPosition = texturesByName.find(NAME_MISSING_TEXTURE)->second; - //for (StitchedTexture texture : texturesToRegister.values()) - for(AUTO_VAR(it, texturesToRegister.begin() ); it != texturesToRegister.end(); ++it) - { - StitchedTexture *texture = it->second; - texture->replaceWith(missingPosition); - } + // for (StitchedTexture texture : texturesToRegister.values()) + for (AUTO_VAR(it, texturesToRegister.begin()); + it != texturesToRegister.end(); ++it) { + StitchedTexture* texture = it->second; + texture->replaceWith(missingPosition); + } - stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); - stitchResult->updateOnGPU(); + stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); + stitchResult->updateOnGPU(); } -StitchedTexture *TextureMap::getTexture(const std::wstring &name) -{ - StitchedTexture *result = texturesByName.find(name)->second; - if (result == NULL) result = missingPosition; - return result; +StitchedTexture* TextureMap::getTexture(const std::wstring& name) { + StitchedTexture* result = texturesByName.find(name)->second; + if (result == NULL) result = missingPosition; + return result; } -void TextureMap::cycleAnimationFrames() -{ - //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) - { - StitchedTexture *texture = *it; - texture->cycleFrames(); - } +void TextureMap::cycleAnimationFrames() { + // for (StitchedTexture texture : animatedTextures) + for (AUTO_VAR(it, animatedTextures.begin()); it != animatedTextures.end(); + ++it) { + StitchedTexture* texture = *it; + texture->cycleFrames(); + } } -Texture *TextureMap::getStitchedTexture() -{ - return stitchResult; -} +Texture* TextureMap::getStitchedTexture() { return stitchResult; } // 4J Stu - register is a reserved keyword in C++ -Icon *TextureMap::registerIcon(const std::wstring &name) -{ - if (name.empty()) - { - app.DebugPrintf("Don't register NULL\n"); +Icon* TextureMap::registerIcon(const std::wstring& name) { + if (name.empty()) { + app.DebugPrintf("Don't register NULL\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //new RuntimeException("Don't register null!").printStackTrace(); - } + // new RuntimeException("Don't register null!").printStackTrace(); + } - // TODO: [EB]: Why do we allow multiple registrations? - StitchedTexture *result = NULL; - AUTO_VAR(it, texturesToRegister.find(name)); - if(it != texturesToRegister.end()) result = it->second; + // TODO: [EB]: Why do we allow multiple registrations? + StitchedTexture* result = NULL; + AUTO_VAR(it, texturesToRegister.find(name)); + if (it != texturesToRegister.end()) result = it->second; - if (result == NULL) - { - result = StitchedTexture::create(name); - texturesToRegister.insert( stringStitchedTextureMap::value_type(name, result) ); - } + if (result == NULL) { + result = StitchedTexture::create(name); + texturesToRegister.insert( + stringStitchedTextureMap::value_type(name, result)); + } - return result; + return result; } -int TextureMap::getIconType() -{ - return iconType; -} +int TextureMap::getIconType() { return iconType; } -Icon *TextureMap::getMissingIcon() -{ - return missingPosition; -} \ No newline at end of file +Icon* TextureMap::getMissingIcon() { return missingPosition; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/TextureMap.h b/Minecraft.Client/Textures/Stitching/TextureMap.h index af13345ef..d139b1e4e 100644 --- a/Minecraft.Client/Textures/Stitching/TextureMap.h +++ b/Minecraft.Client/Textures/Stitching/TextureMap.h @@ -1,46 +1,50 @@ #pragma once - #include "../../../Minecraft.World/Util/IconRegister.h" class StitchedTexture; class Texture; class BufferedImage; -class TextureMap : public IconRegister -{ +class TextureMap : public IconRegister { public: - static const std::wstring NAME_MISSING_TEXTURE; + static const std::wstring NAME_MISSING_TEXTURE; private: - const int iconType; + const int iconType; - const std::wstring name; - const std::wstring path; - const std::wstring extension; + const std::wstring name; + const std::wstring path; + const std::wstring extension; - bool m_mipMap; + bool m_mipMap; - typedef std::unordered_map stringStitchedTextureMap; - stringStitchedTextureMap texturesByName; // = new HashMap(); - BufferedImage *missingTexture; // = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); - StitchedTexture *missingPosition; - Texture *stitchResult; - std::vector animatedTextures; // = new ArrayList(); + typedef std::unordered_map + stringStitchedTextureMap; + stringStitchedTextureMap + texturesByName; // = new HashMap(); + BufferedImage* missingTexture; // = new BufferedImage(64, 64, + // BufferedImage.TYPE_INT_ARGB); + StitchedTexture* missingPosition; + Texture* stitchResult; + std::vector + animatedTextures; // = new ArrayList(); - stringStitchedTextureMap texturesToRegister; // = new HashMap(); + stringStitchedTextureMap + texturesToRegister; // = new HashMap(); public: - TextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipMap = false); + TextureMap(int type, const std::wstring& name, const std::wstring& path, + BufferedImage* missingTexture, bool mipMap = false); - void stitch(); - StitchedTexture *getTexture(const std::wstring &name); - void cycleAnimationFrames(); - Texture *getStitchedTexture(); + void stitch(); + StitchedTexture* getTexture(const std::wstring& name); + void cycleAnimationFrames(); + Texture* getStitchedTexture(); - // 4J Stu - register is a reserved keyword in C++ - Icon *registerIcon(const std::wstring &name); + // 4J Stu - register is a reserved keyword in C++ + Icon* registerIcon(const std::wstring& name); - int getIconType(); - Icon *getMissingIcon(); + int getIconType(); + Icon* getMissingIcon(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Texture.cpp b/Minecraft.Client/Textures/Texture.cpp index f01691229..efed2bb17 100644 --- a/Minecraft.Client/Textures/Texture.cpp +++ b/Minecraft.Client/Textures/Texture.cpp @@ -8,243 +8,229 @@ #include "../Platform/PS3/SPU_Tasks/Texture_blit/Texture_blit.h" #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" static const int sc_maxTextureBlits = 256; -static Texture_blit_DataIn g_textureBlitDataIn[sc_maxTextureBlits] __attribute__((__aligned__(16))); +static Texture_blit_DataIn g_textureBlitDataIn[sc_maxTextureBlits] + __attribute__((__aligned__(16))); static int g_currentTexBlit = 0; C4JSpursJobQueue::Port* g_texBlitJobQueuePort; -#endif //__PS3__ +#endif //__PS3__ #define MAX_MIP_LEVELS 5 -Texture::Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, mipMap); } -void Texture::_init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap) -{ +void Texture::_init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap) { #ifdef __PS3__ - if(g_texBlitJobQueuePort == NULL) - g_texBlitJobQueuePort = new C4JSpursJobQueue::Port("C4JSpursJob_Texture_blit"); + if (g_texBlitJobQueuePort == NULL) + g_texBlitJobQueuePort = + new C4JSpursJobQueue::Port("C4JSpursJob_Texture_blit"); #endif - this->name = name; - this->mode = mode; - this->width = width; - this->height = height; - this->depth = depth; - this->format = format; - this->minFilter = minFilter; - this->magFilter = magFilter; - this->wrapMode = wrapMode; - immediateUpdate = false; - m_bInitialised = false; - for( int i = 0 ; i < 10; i++ ) - { - data[i] = NULL; - } + this->name = name; + this->mode = mode; + this->width = width; + this->height = height; + this->depth = depth; + this->format = format; + this->minFilter = minFilter; + this->magFilter = magFilter; + this->wrapMode = wrapMode; + immediateUpdate = false; + m_bInitialised = false; + for (int i = 0; i < 10; i++) { + data[i] = NULL; + } - rect = new Rect2i(0, 0, width, height); - // 4J Removed 1D and 3D - //if (height == 1 && depth == 1) - //{ - // type = GL_TEXTURE_1D; - //} - //else if(depth == 1) - //{ - type = GL_TEXTURE_2D; - //} - //else - //{ - // type = GL_TEXTURE_3D; - //} + rect = new Rect2i(0, 0, width, height); + // 4J Removed 1D and 3D + // if (height == 1 && depth == 1) + //{ + // type = GL_TEXTURE_1D; + //} + // else if(depth == 1) + //{ + type = GL_TEXTURE_2D; + //} + // else + //{ + // type = GL_TEXTURE_3D; + //} - mipmapped = mipMap || (minFilter != GL_NEAREST && minFilter != GL_LINEAR) || - (magFilter != GL_NEAREST && magFilter != GL_LINEAR); - m_iMipLevels=1; - - if(mipmapped) - { - // 4J-PB - In the new XDK, the CreateTexture will fail if the number of mipmaps is higher than the width & height passed in will allow! - int iWidthMips=1; - int iHeightMips=1; - while((8< MAX_MIP_LEVELS) m_iMipLevels = MAX_MIP_LEVELS; - } + if (mipmapped) { + // 4J-PB - In the new XDK, the CreateTexture will fail if the number of + // mipmaps is higher than the width & height passed in will allow! + int iWidthMips = 1; + int iHeightMips = 1; + while ((8 << iWidthMips) < width) iWidthMips++; + while ((8 << iHeightMips) < height) iHeightMips++; + + m_iMipLevels = (iWidthMips < iHeightMips) ? iWidthMips : iHeightMips; + + // TODO - The render libs currently limit max mip map levels to 5 + if (m_iMipLevels > MAX_MIP_LEVELS) m_iMipLevels = MAX_MIP_LEVELS; + } #ifdef __PSVITA__ - // vita doesn't have a mipmap conditional shader because it's too slow so make sure this texture don't look awful at the lower mips - if( name == L"terrain" ) - { - m_iMipLevels = 3; - } + // vita doesn't have a mipmap conditional shader because it's too slow so + // make sure this texture don't look awful at the lower mips + if (name == L"terrain") { + m_iMipLevels = 3; + } #endif - if (mode != TM_CONTAINER) - { - glId = glGenTextures(); + if (mode != TM_CONTAINER) { + glId = glGenTextures(); - glBindTexture(type, glId); - glTexParameteri(type, GL_TEXTURE_MIN_FILTER, minFilter); - glTexParameteri(type, GL_TEXTURE_MAG_FILTER, magFilter); - glTexParameteri(type, GL_TEXTURE_WRAP_S, wrapMode); - glTexParameteri(type, GL_TEXTURE_WRAP_T, wrapMode); - } - else - { - glId = -1; - } + glBindTexture(type, glId); + glTexParameteri(type, GL_TEXTURE_MIN_FILTER, minFilter); + glTexParameteri(type, GL_TEXTURE_MAG_FILTER, magFilter); + glTexParameteri(type, GL_TEXTURE_WRAP_S, wrapMode); + glTexParameteri(type, GL_TEXTURE_WRAP_T, wrapMode); + } else { + glId = -1; + } - managerId = TextureManager::getInstance()->createTextureID(); + managerId = TextureManager::getInstance()->createTextureID(); } -void Texture::_init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, mipMap); - if (image == NULL) - { - if (width == -1 || height == -1) - { - valid = false; - } - else - { - byteArray tempBytes = byteArray(width * height * depth * 4); - for (int index = 0; index < tempBytes.length; index++) - { - tempBytes[index] = 0; - } +void Texture::_init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, mipMap); + if (image == NULL) { + if (width == -1 || height == -1) { + valid = false; + } else { + byteArray tempBytes = byteArray(width * height * depth * 4); + for (int index = 0; index < tempBytes.length; index++) { + tempBytes[index] = 0; + } #ifdef __PS3__ - data[0] = new ByteBuffer_IO(tempBytes.length); + data[0] = new ByteBuffer_IO(tempBytes.length); #else - data[0] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - data[0]->clear(); - data[0]->put(tempBytes); - data[0]->position(0)->limit(tempBytes.length); + data[0] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + data[0]->clear(); + data[0]->put(tempBytes); + data[0]->position(0)->limit(tempBytes.length); - delete [] tempBytes.data; + delete[] tempBytes.data; - if(mipmapped) - { - for(unsigned int level = 1; level < m_iMipLevels; ++level) - { - int ww = width >> level; - int hh = height >> level; + if (mipmapped) { + for (unsigned int level = 1; level < m_iMipLevels; ++level) { + int ww = width >> level; + int hh = height >> level; - byteArray tempBytes = byteArray(ww * hh * depth * 4); - for (int index = 0; index < tempBytes.length; index++) - { - tempBytes[index] = 0; - } + byteArray tempBytes = byteArray(ww * hh * depth * 4); + for (int index = 0; index < tempBytes.length; index++) { + tempBytes[index] = 0; + } #ifdef __PS3__ - data[level] = new ByteBuffer_IO(tempBytes.length); + data[level] = new ByteBuffer_IO(tempBytes.length); #else - data[level] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __PS3__ - data[level]->clear(); - data[level]->put(tempBytes); - data[level]->position(0)->limit(tempBytes.length); + data[level] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __PS3__ + data[level]->clear(); + data[level]->put(tempBytes); + data[level]->position(0)->limit(tempBytes.length); - delete [] tempBytes.data; - } - } + delete[] tempBytes.data; + } + } - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } - } - } - else - { - valid = true; + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } + } + } else { + valid = true; - transferFromImage(image); + transferFromImage(image); - if (mode != TM_CONTAINER) - { - updateOnGPU(); - immediateUpdate = false; - } - } + if (mode != TM_CONTAINER) { + updateOnGPU(); + immediateUpdate = false; + } + } } -Texture::Texture(const std::wstring &name, int mode, int width, int height, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, 1, wrapMode, format, minFilter, magFilter, image, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, 1, wrapMode, format, minFilter, magFilter, + image, mipMap); } -Texture::Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, image, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, image, mipMap); } -Texture::~Texture() -{ - delete rect; - - for(int i = 0; i < 10; i++ ) - { - if(data[i] != NULL) delete data[i]; - } +Texture::~Texture() { + delete rect; - if(glId >= 0) - { - glDeleteTextures(glId); - } + for (int i = 0; i < 10; i++) { + if (data[i] != NULL) delete data[i]; + } + + if (glId >= 0) { + glDeleteTextures(glId); + } } -const Rect2i *Texture::getRect() -{ - return rect; +const Rect2i* Texture::getRect() { return rect; } + +void Texture::fill(const Rect2i* rect, int color) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} + + Rect2i* myRect = new Rect2i(0, 0, width, height); + myRect->intersect(rect); + data[0]->position(0); + for (int y = myRect->getY(); y < (myRect->getY() + myRect->getHeight()); + y++) { + int line = y * width * 4; + for (int x = myRect->getX(); x < (myRect->getX() + myRect->getWidth()); + x++) { + data[0]->put(line + x * 4 + 0, + static_cast((color >> 24) & 0x000000ff)); + data[0]->put(line + x * 4 + 1, + static_cast((color >> 16) & 0x000000ff)); + data[0]->put(line + x * 4 + 2, + static_cast((color >> 8) & 0x000000ff)); + data[0]->put(line + x * 4 + 3, + static_cast((color >> 0) & 0x000000ff)); + } + } + delete myRect; + + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -void Texture::fill(const Rect2i *rect, int color) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} - - Rect2i *myRect = new Rect2i(0, 0, width, height); - myRect->intersect(rect); - data[0]->position(0); - for (int y = myRect->getY(); y < (myRect->getY() + myRect->getHeight()); y++) - { - int line = y * width * 4; - for (int x = myRect->getX(); x < (myRect->getX() + myRect->getWidth()); x++) - { - data[0]->put(line + x * 4 + 0, static_cast((color >> 24) & 0x000000ff)); - data[0]->put(line + x * 4 + 1, static_cast((color >> 16) & 0x000000ff)); - data[0]->put(line + x * 4 + 2, static_cast((color >> 8) & 0x000000ff)); - data[0]->put(line + x * 4 + 3, static_cast((color >> 0) & 0x000000ff)); - } - } - delete myRect; - - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } -} - -void Texture::writeAsBMP(const std::wstring &name) -{ - // 4J Don't need +void Texture::writeAsBMP(const std::wstring& name) { + // 4J Don't need #if 0 if (type == GL_TEXTURE_3D) { @@ -329,9 +315,8 @@ void Texture::writeAsBMP(const std::wstring &name) #endif } -void Texture::writeAsPNG(const std::wstring &filename) -{ - // 4J Don't need +void Texture::writeAsPNG(const std::wstring& filename) { + // 4J Don't need #if 0 BufferedImage *image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); ByteBuffer *buffer = this->getData(); @@ -366,535 +351,507 @@ void Texture::writeAsPNG(const std::wstring &filename) #endif } -void Texture::blit(int x, int y, Texture *source) -{ - blit(x, y, source, false); -} +void Texture::blit(int x, int y, Texture* source) { blit(x, y, source, false); } -void Texture::blit(int x, int y, Texture *source, bool rotated) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} +void Texture::blit(int x, int y, Texture* source, bool rotated) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} - for(unsigned int level = 0; level < m_iMipLevels; ++level) - { - ByteBuffer *srcBuffer = source->getData(level); + for (unsigned int level = 0; level < m_iMipLevels; ++level) { + ByteBuffer* srcBuffer = source->getData(level); - if(srcBuffer == NULL) break; + if (srcBuffer == NULL) break; - int yy = y >> level; - int xx = x >> level; - int hh = height >> level; - int ww = width >> level; - int shh = source->getHeight() >> level; - int sww = source->getWidth() >> level; + int yy = y >> level; + int xx = x >> level; + int hh = height >> level; + int ww = width >> level; + int shh = source->getHeight() >> level; + int sww = source->getWidth() >> level; - data[level]->position(0); - srcBuffer->position(0); + data[level]->position(0); + srcBuffer->position(0); #if defined __PS3__ && !defined DISABLE_SPU_CODE - if(g_texBlitJobQueuePort->hasCompleted()) - { - // all outstanding blits have completed, so reset to the start of the blit list - g_currentTexBlit = 0; - } - Texture_blit_DataIn& dataIn = g_textureBlitDataIn[g_currentTexBlit]; - g_currentTexBlit++; - if(g_currentTexBlit >= sc_maxTextureBlits) - { - app.DebugPrintf("ran out of tex blit slots, stalling for completion\n"); - g_texBlitJobQueuePort->waitForCompletion(); - g_currentTexBlit = 0; - } - dataIn.pSrcData = srcBuffer->getBuffer(); - dataIn.pDstData = data[level]->getBuffer(); - dataIn.yy = yy; - dataIn.xx = xx; - dataIn.hh = hh; - dataIn.ww = ww; - dataIn.shh = shh; - dataIn.sww = sww; - dataIn.rotated = rotated; + if (g_texBlitJobQueuePort->hasCompleted()) { + // all outstanding blits have completed, so reset to the start of + // the blit list + g_currentTexBlit = 0; + } + Texture_blit_DataIn& dataIn = g_textureBlitDataIn[g_currentTexBlit]; + g_currentTexBlit++; + if (g_currentTexBlit >= sc_maxTextureBlits) { + app.DebugPrintf( + "ran out of tex blit slots, stalling for completion\n"); + g_texBlitJobQueuePort->waitForCompletion(); + g_currentTexBlit = 0; + } + dataIn.pSrcData = srcBuffer->getBuffer(); + dataIn.pDstData = data[level]->getBuffer(); + dataIn.yy = yy; + dataIn.xx = xx; + dataIn.hh = hh; + dataIn.ww = ww; + dataIn.shh = shh; + dataIn.sww = sww; + dataIn.rotated = rotated; - C4JSpursJob_Texture_blit blitJob(&dataIn); - g_texBlitJobQueuePort->submitJob(&blitJob); -// p.waitForCompletion(); + C4JSpursJob_Texture_blit blitJob(&dataIn); + g_texBlitJobQueuePort->submitJob(&blitJob); + // p.waitForCompletion(); #elif __PSVITA__ - unsigned int *src = (unsigned int *) srcBuffer->getBuffer(); - unsigned int *dst = (unsigned int *) data[level]->getBuffer(); + unsigned int* src = (unsigned int*)srcBuffer->getBuffer(); + unsigned int* dst = (unsigned int*)data[level]->getBuffer(); - for (int srcY = 0; srcY < shh; srcY++) - { - int dstY = yy + srcY; - int srcLine = srcY * sww; - int dstLine = dstY * ww; + for (int srcY = 0; srcY < shh; srcY++) { + int dstY = yy + srcY; + int srcLine = srcY * sww; + int dstLine = dstY * ww; - if (rotated) - { - dstY = yy + (shh - srcY); - } + if (rotated) { + dstY = yy + (shh - srcY); + } - if (!rotated) - { - memcpy(dst + dstLine + xx, src + srcLine, sww * 4); - } - else - { - for (int srcX = 0; srcX < sww; srcX++) - { - int dstPos = dstLine + (srcX + xx); - int srcPos = srcLine + srcX; + if (!rotated) { + memcpy(dst + dstLine + xx, src + srcLine, sww * 4); + } else { + for (int srcX = 0; srcX < sww; srcX++) { + int dstPos = dstLine + (srcX + xx); + int srcPos = srcLine + srcX; - if (rotated) - { - dstPos = (xx + srcX * ww) + dstY; - } + if (rotated) { + dstPos = (xx + srcX * ww) + dstY; + } - dst[dstPos] = src[srcPos]; - } - } - } + dst[dstPos] = src[srcPos]; + } + } + } #else - for (int srcY = 0; srcY < shh; srcY++) - { - int dstY = yy + srcY; - int srcLine = srcY * sww * 4; - int dstLine = dstY * ww * 4; + for (int srcY = 0; srcY < shh; srcY++) { + int dstY = yy + srcY; + int srcLine = srcY * sww * 4; + int dstLine = dstY * ww * 4; - if (rotated) - { - dstY = yy + (shh - srcY); - } + if (rotated) { + dstY = yy + (shh - srcY); + } - for (int srcX = 0; srcX < sww; srcX++) - { - int dstPos = dstLine + (srcX + xx) * 4; - int srcPos = srcLine + srcX * 4; + for (int srcX = 0; srcX < sww; srcX++) { + int dstPos = dstLine + (srcX + xx) * 4; + int srcPos = srcLine + srcX * 4; - if (rotated) - { - dstPos = (xx + srcX * ww * 4) + dstY * 4; - } + if (rotated) { + dstPos = (xx + srcX * ww * 4) + dstY * 4; + } - data[level]->put(dstPos + 0, srcBuffer->get(srcPos + 0)); - data[level]->put(dstPos + 1, srcBuffer->get(srcPos + 1)); - data[level]->put(dstPos + 2, srcBuffer->get(srcPos + 2)); - data[level]->put(dstPos + 3, srcBuffer->get(srcPos + 3)); - } - } - // Don't delete this, as it belongs to the source texture - //delete srcBuffer; + data[level]->put(dstPos + 0, srcBuffer->get(srcPos + 0)); + data[level]->put(dstPos + 1, srcBuffer->get(srcPos + 1)); + data[level]->put(dstPos + 2, srcBuffer->get(srcPos + 2)); + data[level]->put(dstPos + 3, srcBuffer->get(srcPos + 3)); + } + } + // Don't delete this, as it belongs to the source texture + // delete srcBuffer; #endif - data[level]->position(ww * hh * 4); - } + data[level]->position(ww * hh * 4); + } - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -void Texture::transferFromBuffer(intArray buffer) -{ - if (depth == 1) - { - return; - } +void Texture::transferFromBuffer(intArray buffer) { + if (depth == 1) { + return; + } -// #ifdef __PS3__ -// int byteRemapRGBA[] = { 3, 0, 1, 2 }; -// int byteRemapBGRA[] = { 3, 2, 1, 0 }; -// #else - int byteRemapRGBA[] = { 0, 1, 2, 3 }; - int byteRemapBGRA[] = { 2, 1, 0, 3 }; -// #endif - int *byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); + // #ifdef __PS3__ + // int byteRemapRGBA[] = { 3, 0, 1, 2 }; + // int byteRemapBGRA[] = { 3, 2, 1, 0 }; + // #else + int byteRemapRGBA[] = {0, 1, 2, 3}; + int byteRemapBGRA[] = {2, 1, 0, 3}; + // #endif + int* byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); - for (int z = 0; z < depth; z++) - { - int plane = z * height * width * 4; - for (int y = 0; y < height; y++) - { - int column = plane + y * width * 4; - for (int x = 0; x < width; x++) - { - int texel = column + x * 4; - data[0]->position(0); - data[0]->put(texel + byteRemap[0], (uint8_t)((buffer[texel >> 2] >> 24) & 0xff)); - data[0]->put(texel + byteRemap[1], (uint8_t)((buffer[texel >> 2] >> 16) & 0xff)); - data[0]->put(texel + byteRemap[2], (uint8_t)((buffer[texel >> 2] >> 8) & 0xff)); - data[0]->put(texel + byteRemap[3], (uint8_t)((buffer[texel >> 2] >> 0) & 0xff)); - } - } - } + for (int z = 0; z < depth; z++) { + int plane = z * height * width * 4; + for (int y = 0; y < height; y++) { + int column = plane + y * width * 4; + for (int x = 0; x < width; x++) { + int texel = column + x * 4; + data[0]->position(0); + data[0]->put(texel + byteRemap[0], + (uint8_t)((buffer[texel >> 2] >> 24) & 0xff)); + data[0]->put(texel + byteRemap[1], + (uint8_t)((buffer[texel >> 2] >> 16) & 0xff)); + data[0]->put(texel + byteRemap[2], + (uint8_t)((buffer[texel >> 2] >> 8) & 0xff)); + data[0]->put(texel + byteRemap[3], + (uint8_t)((buffer[texel >> 2] >> 0) & 0xff)); + } + } + } - data[0]->position(width * height * depth * 4); + data[0]->position(width * height * depth * 4); - updateOnGPU(); + updateOnGPU(); } -void Texture::transferFromImage(BufferedImage *image) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} +void Texture::transferFromImage(BufferedImage* image) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} - int imgWidth = image->getWidth(); - int imgHeight = image->getHeight(); - if (imgWidth > width || imgHeight > height) - { - //Minecraft::GetInstance().getLogger().warning("transferFromImage called with a BufferedImage with dimensions (" + - // imgWidth + ", " + imgHeight + ") larger than the Texture dimensions (" + width + - // ", " + height + "). Ignoring."); - app.DebugPrintf("transferFromImage called with a BufferedImage with dimensions (%d, %d) larger than the Texture dimensions (%d, %d). Ignoring.\n", imgWidth, imgHeight, width, height); - return; - } + int imgWidth = image->getWidth(); + int imgHeight = image->getHeight(); + if (imgWidth > width || imgHeight > height) { + // Minecraft::GetInstance().getLogger().warning("transferFromImage + // called with a BufferedImage with dimensions (" + imgWidth + ", " + + //imgHeight + ") larger than the Texture dimensions (" + width + + // ", " + height + "). Ignoring."); + app.DebugPrintf( + "transferFromImage called with a BufferedImage with dimensions " + "(%d, %d) larger than the Texture dimensions (%d, %d). Ignoring.\n", + imgWidth, imgHeight, width, height); + return; + } // #ifdef __PS3__ // int byteRemapRGBA[] = { 0, 1, 2, 3 }; // int byteRemapBGRA[] = { 2, 1, 0, 3 }; // #else #ifdef _XBOX - int byteRemapRGBA[] = { 0, 1, 2, 3 }; + int byteRemapRGBA[] = {0, 1, 2, 3}; #else - int byteRemapRGBA[] = { 3, 0, 1, 2 }; + int byteRemapRGBA[] = {3, 0, 1, 2}; #endif - int byteRemapBGRA[] = { 3, 2, 1, 0 }; -// #endif - int *byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); + int byteRemapBGRA[] = {3, 2, 1, 0}; + // #endif + int* byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); - intArray tempPixels = intArray(width * height); - int transparency = image->getTransparency(); - image->getRGB(0, 0, width, height, tempPixels, 0, imgWidth); + intArray tempPixels = intArray(width * height); + int transparency = image->getTransparency(); + image->getRGB(0, 0, width, height, tempPixels, 0, imgWidth); - byteArray tempBytes = byteArray(width * height * 4); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int intIndex = y * width + x; - int byteIndex = intIndex * 4; + byteArray tempBytes = byteArray(width * height * 4); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int intIndex = y * width + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((tempPixels[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((tempPixels[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((tempPixels[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((tempPixels[intIndex] >> 0) & 0xff); - } - } + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((tempPixels[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((tempPixels[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((tempPixels[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((tempPixels[intIndex] >> 0) & 0xff); + } + } - for(int i = 0; i < 10; i++ ) - { - if(data[i] != NULL) - { - delete data[i]; - data[i] = NULL; - } - } + for (int i = 0; i < 10; i++) { + if (data[i] != NULL) { + delete data[i]; + data[i] = NULL; + } + } - MemSect(51); + MemSect(51); #ifdef __PS3__ - data[0] = new ByteBuffer_IO(tempBytes.length); + data[0] = new ByteBuffer_IO(tempBytes.length); #else - data[0] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - MemSect(0); - data[0]->clear(); - data[0]->put(tempBytes); - data[0]->limit(tempBytes.length); + data[0] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + MemSect(0); + data[0]->clear(); + data[0]->put(tempBytes); + data[0]->limit(tempBytes.length); - delete [] tempBytes.data; + delete[] tempBytes.data; - if(mipmapped || image->getData(1) != NULL) - { - mipmapped = true; - for(unsigned int level = 1; level < MAX_MIP_LEVELS; ++level) - { - int ww = width >> level; - int hh = height >> level; + if (mipmapped || image->getData(1) != NULL) { + mipmapped = true; + for (unsigned int level = 1; level < MAX_MIP_LEVELS; ++level) { + int ww = width >> level; + int hh = height >> level; - byteArray tempBytes = byteArray(ww * hh * 4); - unsigned int *tempData = new unsigned int[ww * hh]; + byteArray tempBytes = byteArray(ww * hh * 4); + unsigned int* tempData = new unsigned int[ww * hh]; - if( image->getData( level ) ) - { - memcpy( tempData, image->getData( level ), ww * hh * 4); - for (int y = 0; y < hh; y++) - { - for (int x = 0; x < ww; x++) - { - int intIndex = y * ww + x; - int byteIndex = intIndex * 4; + if (image->getData(level)) { + memcpy(tempData, image->getData(level), ww * hh * 4); + for (int y = 0; y < hh; y++) { + for (int x = 0; x < ww; x++) { + int intIndex = y * ww + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on + // format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((tempData[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((tempData[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((tempData[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((tempData[intIndex] >> 0) & 0xff); - } - } - } - else - { - int ow = width >> (level - 1); - - for (int x = 0; x < ww; x++) - for (int y = 0; y < hh; y++) - { - int c0 = data[level - 1]->getInt(((x * 2 + 0) + (y * 2 + 0) * ow) * 4); - int c1 = data[level - 1]->getInt(((x * 2 + 1) + (y * 2 + 0) * ow) * 4); - int c2 = data[level - 1]->getInt(((x * 2 + 1) + (y * 2 + 1) * ow) * 4); - int c3 = data[level - 1]->getInt(((x * 2 + 0) + (y * 2 + 1) * ow) * 4); + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((tempData[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((tempData[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((tempData[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((tempData[intIndex] >> 0) & 0xff); + } + } + } else { + int ow = width >> (level - 1); + + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + int c0 = data[level - 1]->getInt( + ((x * 2 + 0) + (y * 2 + 0) * ow) * 4); + int c1 = data[level - 1]->getInt( + ((x * 2 + 1) + (y * 2 + 0) * ow) * 4); + int c2 = data[level - 1]->getInt( + ((x * 2 + 1) + (y * 2 + 1) * ow) * 4); + int c3 = data[level - 1]->getInt( + ((x * 2 + 0) + (y * 2 + 1) * ow) * 4); #ifndef _XBOX - // 4J - convert our RGBA texels to ARGB that crispBlend is expecting - // 4jcraft, added uint cast to pervent shift of neg int - c0 = ( ( c0 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c0 << 24 ); - c1 = ( ( c1 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c1 << 24 ); - c2 = ( ( c2 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c2 << 24 ); - c3 = ( ( c3 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c3 << 24 ); + // 4J - convert our RGBA texels to ARGB that crispBlend + // is expecting 4jcraft, added uint cast to pervent + // shift of neg int + c0 = + ((c0 >> 8) & 0x00ffffff) | ((unsigned int)c0 << 24); + c1 = + ((c1 >> 8) & 0x00ffffff) | ((unsigned int)c1 << 24); + c2 = + ((c2 >> 8) & 0x00ffffff) | ((unsigned int)c2 << 24); + c3 = + ((c3 >> 8) & 0x00ffffff) | ((unsigned int)c3 << 24); #endif - int col = crispBlend(crispBlend(c0, c1), crispBlend(c2, c3)); - // 4J - and back from ARGB -> RGBA - //col = ( col << 8 ) | (( col >> 24 ) & 0xff); - //tempData[x + y * ww] = col; + int col = + crispBlend(crispBlend(c0, c1), crispBlend(c2, c3)); + // 4J - and back from ARGB -> RGBA + // col = ( col << 8 ) | (( col >> 24 ) & 0xff); + // tempData[x + y * ww] = col; - int intIndex = y * ww + x; - int byteIndex = intIndex * 4; + int intIndex = y * ww + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on + // format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((col >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((col >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((col >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((col >> 0) & 0xff); - } - } + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((col >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((col >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((col >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((col >> 0) & 0xff); + } + } - MemSect(51); + MemSect(51); #ifdef __PS3__ - data[level] = new ByteBuffer_IO(tempBytes.length); + data[level] = new ByteBuffer_IO(tempBytes.length); #else - data[level] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - MemSect(0); - data[level]->clear(); - data[level]->put(tempBytes); - data[level]->limit(tempBytes.length); - delete [] tempBytes.data; - delete [] tempData; - } - } + data[level] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + MemSect(0); + data[level]->clear(); + data[level]->put(tempBytes); + data[level]->limit(tempBytes.length); + delete[] tempBytes.data; + delete[] tempData; + } + } - delete [] tempPixels.data; + delete[] tempPixels.data; - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -// 4J Kept from older versions for where we create mip-maps for levels that do not have pre-made graphics -int Texture::crispBlend(int c0, int c1) -{ - int a0 = (int) (((c0 & 0xff000000) >> 24)) & 0xff; - int a1 = (int) (((c1 & 0xff000000) >> 24)) & 0xff; +// 4J Kept from older versions for where we create mip-maps for levels that do +// not have pre-made graphics +int Texture::crispBlend(int c0, int c1) { + int a0 = (int)(((c0 & 0xff000000) >> 24)) & 0xff; + int a1 = (int)(((c1 & 0xff000000) >> 24)) & 0xff; - int a = 255; - if (a0 + a1 < 255) - { - a = 0; - a0 = 1; - a1 = 1; - } - else if (a0 > a1) - { - a0 = 255; - a1 = 1; - } - else - { - a0 = 1; - a1 = 255; + int a = 255; + if (a0 + a1 < 255) { + a = 0; + a0 = 1; + a1 = 1; + } else if (a0 > a1) { + a0 = 255; + a1 = 1; + } else { + a0 = 1; + a1 = 255; + } - } + int r0 = ((c0 >> 16) & 0xff) * a0; + int g0 = ((c0 >> 8) & 0xff) * a0; + int b0 = ((c0) & 0xff) * a0; - int r0 = ((c0 >> 16) & 0xff) * a0; - int g0 = ((c0 >> 8) & 0xff) * a0; - int b0 = ((c0) & 0xff) * a0; + int r1 = ((c1 >> 16) & 0xff) * a1; + int g1 = ((c1 >> 8) & 0xff) * a1; + int b1 = ((c1) & 0xff) * a1; - int r1 = ((c1 >> 16) & 0xff) * a1; - int g1 = ((c1 >> 8) & 0xff) * a1; - int b1 = ((c1) & 0xff) * a1; + int r = (r0 + r1) / (a0 + a1); + int g = (g0 + g1) / (a0 + a1); + int b = (b0 + b1) / (a0 + a1); - int r = (r0 + r1) / (a0 + a1); - int g = (g0 + g1) / (a0 + a1); - int b = (b0 + b1) / (a0 + a1); - - return (a << 24) | (r << 16) | (g << 8) | b; + return (a << 24) | (r << 16) | (g << 8) | b; } -int Texture::getManagerId() -{ - return managerId; +int Texture::getManagerId() { return managerId; } + +int Texture::getGlId() { return glId; } + +int Texture::getWidth() { return width; } + +int Texture::getHeight() { return height; } + +std::wstring Texture::getName() { return name; } + +void Texture::setImmediateUpdate(bool immediateUpdate) { + this->immediateUpdate = immediateUpdate; } -int Texture::getGlId() -{ - return glId; +void Texture::bind(int mipMapIndex) { + // 4J Removed 3D + // if (depth == 1) + //{ + glEnable(GL_TEXTURE_2D); + //} + // else + //{ + // glEnable(GL_TEXTURE_3D); + //} + + glActiveTexture(GL_TEXTURE0 + mipMapIndex); + glBindTexture(type, glId); + if (!updated) { + updateOnGPU(); + } } -int Texture::getWidth() -{ - return width; -} +void Texture::updateOnGPU() { + data[0]->flip(); + if (mipmapped) { + for (int level = 1; level < m_iMipLevels; level++) { + if (data[level] == NULL) break; -int Texture::getHeight() -{ - return height; -} - -std::wstring Texture::getName() -{ - return name; -} - -void Texture::setImmediateUpdate(bool immediateUpdate) -{ - this->immediateUpdate = immediateUpdate; -} - -void Texture::bind(int mipMapIndex) -{ - // 4J Removed 3D - //if (depth == 1) - //{ - glEnable(GL_TEXTURE_2D); - //} - //else - //{ - // glEnable(GL_TEXTURE_3D); - //} - - glActiveTexture(GL_TEXTURE0 + mipMapIndex); - glBindTexture(type, glId); - if (!updated) - { - updateOnGPU(); - } -} - -void Texture::updateOnGPU() -{ - data[0]->flip(); - if(mipmapped) - { - for (int level = 1; level < m_iMipLevels; level++) - { - if(data[level] == NULL) break; - - data[level]->flip(); - } - } - // 4J remove 3D and 1D - //if (height != 1 && depth != 1) - //{ - // glTexImage3D(type, 0, format, width, height, depth, 0, format, GL_UNSIGNED_BYTE, data); - //} - //else if(height != 1) - //{ - // 4J Added check so we can differentiate between which RenderManager function to call - if(!m_bInitialised) - { - RenderManager.TextureSetTextureLevels(m_iMipLevels); // 4J added + data[level]->flip(); + } + } + // 4J remove 3D and 1D + // if (height != 1 && depth != 1) + //{ + // glTexImage3D(type, 0, format, width, height, depth, 0, format, + //GL_UNSIGNED_BYTE, data); + //} + // else if(height != 1) + //{ + // 4J Added check so we can differentiate between which RenderManager + // function to call + if (!m_bInitialised) { + RenderManager.TextureSetTextureLevels(m_iMipLevels); // 4J added #ifdef __PSVITA__ - // AP - replace the dynamic ram buffer to one that points to a newly allocated video ram texture buffer. This means we don't have to memcpy - // the ram based buffer to it any more inside RenderManager.TextureDataUpdate - unsigned char *newData = RenderManager.TextureData(width,height,data[0]->getBuffer(),0,C4JRender::TEXTURE_FORMAT_RxGyBzAw); - ByteBuffer *oldBuffer = data[0]; - data[0] = new ByteBuffer(data[0]->getSize(), (uint8_t*) newData); - delete oldBuffer; - newData += width * height * 4; + // AP - replace the dynamic ram buffer to one that points to a newly + // allocated video ram texture buffer. This means we don't have to + // memcpy the ram based buffer to it any more inside + // RenderManager.TextureDataUpdate + unsigned char* newData = + RenderManager.TextureData(width, height, data[0]->getBuffer(), 0, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); + ByteBuffer* oldBuffer = data[0]; + data[0] = new ByteBuffer(data[0]->getSize(), (uint8_t*)newData); + delete oldBuffer; + newData += width * height * 4; #else - RenderManager.TextureData(width,height,data[0]->getBuffer(),0,C4JRender::TEXTURE_FORMAT_RxGyBzAw); + RenderManager.TextureData(width, height, data[0]->getBuffer(), 0, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); #endif - if(mipmapped) - { - for (int level = 1; level < m_iMipLevels; level++) - { - int levelWidth = width >> level; - int levelHeight = height >> level; + if (mipmapped) { + for (int level = 1; level < m_iMipLevels; level++) { + int levelWidth = width >> level; + int levelHeight = height >> level; #ifdef __PSVITA__ - // AP - replace the dynamic ram buffer to one that points to a newly allocated video ram texture buffer. This means we don't have to memcpy - // the ram based buffer to it any more inside RenderManager.TextureDataUpdate - RenderManager.TextureDataUpdate(0, 0,levelWidth,levelHeight,data[level]->getBuffer(),level); - ByteBuffer *oldBuffer = data[level]; - data[level] = new ByteBuffer(data[level]->getSize(), (uint8_t*) newData); - delete oldBuffer; - newData += levelWidth * levelHeight * 4; + // AP - replace the dynamic ram buffer to one that points to a + // newly allocated video ram texture buffer. This means we don't + // have to memcpy the ram based buffer to it any more inside + // RenderManager.TextureDataUpdate + RenderManager.TextureDataUpdate(0, 0, levelWidth, levelHeight, + data[level]->getBuffer(), + level); + ByteBuffer* oldBuffer = data[level]; + data[level] = + new ByteBuffer(data[level]->getSize(), (uint8_t*)newData); + delete oldBuffer; + newData += levelWidth * levelHeight * 4; #else - RenderManager.TextureData(levelWidth,levelHeight,data[level]->getBuffer(),level,C4JRender::TEXTURE_FORMAT_RxGyBzAw); + RenderManager.TextureData(levelWidth, levelHeight, + data[level]->getBuffer(), level, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); #endif - } - } + } + } - m_bInitialised = true; - } - else - { + m_bInitialised = true; + } else { #ifdef _XBOX - RenderManager.TextureDataUpdate(data[0]->getBuffer(),0); + RenderManager.TextureDataUpdate(data[0]->getBuffer(), 0); #else - RenderManager.TextureDataUpdate(0, 0,width,height,data[0]->getBuffer(),0); + RenderManager.TextureDataUpdate(0, 0, width, height, + data[0]->getBuffer(), 0); #endif - if(mipmapped) - { - if (RenderManager.TextureGetTextureLevels() > 1) - { - for (int level = 1; level < m_iMipLevels; level++) - { - int levelWidth = width >> level; - int levelHeight = height >> level; - + if (mipmapped) { + if (RenderManager.TextureGetTextureLevels() > 1) { + for (int level = 1; level < m_iMipLevels; level++) { + int levelWidth = width >> level; + int levelHeight = height >> level; + #ifdef _XBOX - RenderManager.TextureDataUpdate(data[level]->getBuffer(),level); + RenderManager.TextureDataUpdate(data[level]->getBuffer(), + level); #else - RenderManager.TextureDataUpdate(0, 0,levelWidth,levelHeight,data[level]->getBuffer(),level); + RenderManager.TextureDataUpdate( + 0, 0, levelWidth, levelHeight, data[level]->getBuffer(), + level); #endif - } - } - } - } - //glTexImage2D(type, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); - //} - //else - //{ - // glTexImage1D(type, 0, format, width, 0, format, GL_UNSIGNED_BYTE, data); - //} - updated = true; + } + } + } + } + // glTexImage2D(type, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, + // data); + //} + // else + //{ + // glTexImage1D(type, 0, format, width, 0, format, GL_UNSIGNED_BYTE, data); + //} + updated = true; } -ByteBuffer *Texture::getData(unsigned int level) -{ - return data[level]; -} +ByteBuffer* Texture::getData(unsigned int level) { return data[level]; } diff --git a/Minecraft.Client/Textures/Texture.h b/Minecraft.Client/Textures/Texture.h index 74afaea66..732c1960c 100644 --- a/Minecraft.Client/Textures/Texture.h +++ b/Minecraft.Client/Textures/Texture.h @@ -8,91 +8,103 @@ class BufferedImage; class ByteBuffer_IO; #endif -class Texture -{ +class Texture { public: - static const int WM_WRAP = GL_REPEAT; - static const int WM_CLAMP = GL_CLAMP; - static const int WM_MIRROR = 0; //GL_MIRRORED_REPEAT; + static const int WM_WRAP = GL_REPEAT; + static const int WM_CLAMP = GL_CLAMP; + static const int WM_MIRROR = 0; // GL_MIRRORED_REPEAT; - static const int TFMT_RGBA = GL_RGBA; - static const int TFMT_BGRA = GL_BGRA; + static const int TFMT_RGBA = GL_RGBA; + static const int TFMT_BGRA = GL_BGRA; - static const int TFLT_NEAREST = GL_NEAREST; - static const int TFLT_LINEAR = GL_LINEAR; - static const int TFLT_LINEAR_MIP_NEAREST = 0; //GL_LINEAR_MIPMAP_NEAREST; - static const int TFLT_LINEAR_MIP_LINEAR = 0; //GL_LINEAR_MIPMAP_LINEAR; - static const int TFLT_NEAREST_MIP_NEAREST = 0; //GL_NEAREST_MIPMAP_NEAREST; - static const int TFLT_NEAREST_MIP_LINEAR = GL_NEAREST_MIPMAP_LINEAR; + static const int TFLT_NEAREST = GL_NEAREST; + static const int TFLT_LINEAR = GL_LINEAR; + static const int TFLT_LINEAR_MIP_NEAREST = 0; // GL_LINEAR_MIPMAP_NEAREST; + static const int TFLT_LINEAR_MIP_LINEAR = 0; // GL_LINEAR_MIPMAP_LINEAR; + static const int TFLT_NEAREST_MIP_NEAREST = 0; // GL_NEAREST_MIPMAP_NEAREST; + static const int TFLT_NEAREST_MIP_LINEAR = GL_NEAREST_MIPMAP_LINEAR; - static const int TM_STATIC = 0; - static const int TM_DYNAMIC = 1; - static const int TM_CONTAINER = 2; + static const int TM_STATIC = 0; + static const int TM_DYNAMIC = 1; + static const int TM_CONTAINER = 2; private: - int glId; - int managerId; + int glId; + int managerId; - // Indicates certain aspects of this texture's behavior in terms of how tightly it is bound, conceptually. A static - // texture is loaded once, uploaded to the GPU, and discarded CPU-side. A dynamic texture is kept on both the CPU - // and GPU, as it will likely be dynamically updated on the CPU. A container texture exists only to keep the data - // on the CPU, usually for later combination into a larger texture via the Stitcher class. - int mode; + // Indicates certain aspects of this texture's behavior in terms of how + // tightly it is bound, conceptually. A static texture is loaded once, + // uploaded to the GPU, and discarded CPU-side. A dynamic texture is kept on + // both the CPU and GPU, as it will likely be dynamically updated on the + // CPU. A container texture exists only to keep the data on the CPU, usually + // for later combination into a larger texture via the Stitcher class. + int mode; - int width; - int height; - int depth; - int format; - int type; - int minFilter; - int magFilter; - int wrapMode; - bool mipmapped; - std::wstring name; + int width; + int height; + int depth; + int format; + int type; + int minFilter; + int magFilter; + int wrapMode; + bool mipmapped; + std::wstring name; - Rect2i *rect; + Rect2i* rect; - bool valid; - bool immediateUpdate; - bool updated; - int m_iMipLevels; + bool valid; + bool immediateUpdate; + bool updated; + int m_iMipLevels; #ifdef __PS3__ - ByteBuffer_IO *data[10]; + ByteBuffer_IO* data[10]; #else - ByteBuffer *data[10]; // Arrays for mipmaps - NULL if not used + ByteBuffer* data[10]; // Arrays for mipmaps - NULL if not used #endif public: - bool m_bInitialised; // 4J Added + bool m_bInitialised; // 4J Added + + ~Texture(); - ~Texture(); private: - Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, int magFilter, + bool mipMap = true); - void _init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap); - void _init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap); + void _init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap); + void _init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap); public: - Texture(const std::wstring &name, int mode, int width, int height, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap = true); - Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap = true); - const Rect2i *getRect(); - void fill(const Rect2i *rect, int color); - void writeAsBMP(const std::wstring &name); - void writeAsPNG(const std::wstring &filename); - void blit(int x, int y, Texture *source); - void blit(int x, int y, Texture *source, bool rotated); - void transferFromBuffer(intArray buffer); - void transferFromImage(BufferedImage *image); - int getManagerId(); - int getGlId(); - int getWidth(); - int getHeight(); - std::wstring getName(); - void setImmediateUpdate(bool immediateUpdate); - void bind(int mipMapIndex); - void updateOnGPU(); - ByteBuffer *getData(unsigned int level = 0); + const Rect2i* getRect(); + void fill(const Rect2i* rect, int color); + void writeAsBMP(const std::wstring& name); + void writeAsPNG(const std::wstring& filename); + void blit(int x, int y, Texture* source); + void blit(int x, int y, Texture* source, bool rotated); + void transferFromBuffer(intArray buffer); + void transferFromImage(BufferedImage* image); + int getManagerId(); + int getGlId(); + int getWidth(); + int getHeight(); + std::wstring getName(); + void setImmediateUpdate(bool immediateUpdate); + void bind(int mipMapIndex); + void updateOnGPU(); + ByteBuffer* getData(unsigned int level = 0); - static int crispBlend(int c0, int c1); + static int crispBlend(int c0, int c1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureHolder.cpp b/Minecraft.Client/Textures/TextureHolder.cpp index 9723e420e..3c29330c6 100644 --- a/Minecraft.Client/Textures/TextureHolder.cpp +++ b/Minecraft.Client/Textures/TextureHolder.cpp @@ -4,81 +4,65 @@ #include "../../Minecraft.World/Util/StringHelpers.h" #include "TextureHolder.h" -TextureHolder::TextureHolder(Texture *texture) -{ - scale = 1.0f; +TextureHolder::TextureHolder(Texture* texture) { + scale = 1.0f; - this->texture = texture; - this->width = texture->getWidth(); - this->height = texture->getHeight(); + this->texture = texture; + this->width = texture->getWidth(); + this->height = texture->getHeight(); - this->rotated = smallestFittingMinTexel(height) > smallestFittingMinTexel(width); + this->rotated = + smallestFittingMinTexel(height) > smallestFittingMinTexel(width); } -Texture *TextureHolder::getTexture() -{ - return texture; +Texture* TextureHolder::getTexture() { return texture; } + +int TextureHolder::getWidth() const { + return rotated ? smallestFittingMinTexel((int)(height * scale)) + : smallestFittingMinTexel((int)(width * scale)); } -int TextureHolder::getWidth() const -{ - return rotated ? smallestFittingMinTexel((int) (height * scale)) : smallestFittingMinTexel((int) (width * scale)); +int TextureHolder::getHeight() const { + return rotated ? smallestFittingMinTexel((int)(width * scale)) + : smallestFittingMinTexel((int)(height * scale)); } -int TextureHolder::getHeight() const -{ - return rotated ? smallestFittingMinTexel((int) (width * scale)) : smallestFittingMinTexel((int) (height * scale)); +void TextureHolder::rotate() { rotated = !rotated; } + +bool TextureHolder::isRotated() { return rotated; } + +int TextureHolder::smallestFittingMinTexel(int input) const { + return ((input >> Stitcher::MAX_MIPLEVEL) + + ((input & (Stitcher::MIN_TEXEL - 1)) == 0 ? 0 : 1)) + << Stitcher::MAX_MIPLEVEL; } -void TextureHolder::rotate() -{ - rotated = !rotated; -} +void TextureHolder::setForcedScale(int targetSize) { + if (width <= targetSize || height <= targetSize) { + return; + } -bool TextureHolder::isRotated() -{ - return rotated; -} - -int TextureHolder::smallestFittingMinTexel(int input) const -{ - return ((input >> Stitcher::MAX_MIPLEVEL) + ((input & (Stitcher::MIN_TEXEL - 1)) == 0 ? 0 : 1)) << Stitcher::MAX_MIPLEVEL; -} - -void TextureHolder::setForcedScale(int targetSize) -{ - if (width <= targetSize || height <= targetSize) - { - return; - } - - scale = (float) targetSize / std::min(width, height); + scale = (float)targetSize / std::min(width, height); } //@Override -std::wstring TextureHolder::toString() -{ - return L"TextureHolder{width=" + _toString(width) + L", height=" + _toString(height) + L'}'; +std::wstring TextureHolder::toString() { + return L"TextureHolder{width=" + _toString(width) + L", height=" + + _toString(height) + L'}'; } -int TextureHolder::compareTo(const TextureHolder *other) const -{ - int result = 0; - if (this->getHeight() == other->getHeight()) - { - if (this->getWidth() == other->getWidth()) - { - if (texture->getName().empty()) - { - return other->texture->getName().empty() ? 0 : -1; - } - return texture->getName().compare(other->texture->getName()); - } - result = this->getWidth() < other->getWidth() ? 1 : -1; - } - else - { - result = this->getHeight() < other->getHeight() ? 1 : -1; - } - return result; +int TextureHolder::compareTo(const TextureHolder* other) const { + int result = 0; + if (this->getHeight() == other->getHeight()) { + if (this->getWidth() == other->getWidth()) { + if (texture->getName().empty()) { + return other->texture->getName().empty() ? 0 : -1; + } + return texture->getName().compare(other->texture->getName()); + } + result = this->getWidth() < other->getWidth() ? 1 : -1; + } else { + result = this->getHeight() < other->getHeight() ? 1 : -1; + } + return result; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureHolder.h b/Minecraft.Client/Textures/TextureHolder.h index cab827dd1..5215b7ffd 100644 --- a/Minecraft.Client/Textures/TextureHolder.h +++ b/Minecraft.Client/Textures/TextureHolder.h @@ -2,35 +2,37 @@ class Texture; -class TextureHolder //implements Comparable { +class TextureHolder // implements Comparable { { private: - Texture *texture; - int width; - int height; - bool rotated; - float scale; + Texture* texture; + int width; + int height; + bool rotated; + float scale; public: - TextureHolder(Texture *texture); + TextureHolder(Texture* texture); - Texture *getTexture(); - int getWidth() const; - int getHeight() const; - void rotate(); - bool isRotated(); + Texture* getTexture(); + int getWidth() const; + int getHeight() const; + void rotate(); + bool isRotated(); private: - int smallestFittingMinTexel(int input) const; + int smallestFittingMinTexel(int input) const; public: - void setForcedScale(int targetSize); - //@Override - std::wstring toString(); - int compareTo(const TextureHolder *other) const; + void setForcedScale(int targetSize); + //@Override + std::wstring toString(); + int compareTo(const TextureHolder* other) const; }; -struct TextureHolderLessThan -{ - bool operator() (const TextureHolder *first, const TextureHolder *second) const { return first->compareTo(second) >= 0; } +struct TextureHolderLessThan { + bool operator()(const TextureHolder* first, + const TextureHolder* second) const { + return first->compareTo(second) >= 0; + } }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureManager.cpp b/Minecraft.Client/Textures/TextureManager.cpp index 546bdc17f..a618be6d1 100644 --- a/Minecraft.Client/Textures/TextureManager.cpp +++ b/Minecraft.Client/Textures/TextureManager.cpp @@ -7,190 +7,196 @@ #include "TextureManager.h" #include "../../Minecraft.World/Util/StringHelpers.h" -TextureManager *TextureManager::instance = NULL; +TextureManager* TextureManager::instance = NULL; -void TextureManager::createInstance() -{ - instance = new TextureManager(); +void TextureManager::createInstance() { instance = new TextureManager(); } + +TextureManager* TextureManager::getInstance() { return instance; } + +TextureManager::TextureManager() { nextID = 0; } + +int TextureManager::createTextureID() { return nextID++; } + +Texture* TextureManager::getTexture(const std::wstring& name) { + if (stringToIDMap.find(name) != stringToIDMap.end()) { + return idToTextureMap.find(stringToIDMap.find(name)->second)->second; + } + + return NULL; } -TextureManager *TextureManager::getInstance() -{ - return instance; +void TextureManager::registerName(const std::wstring& name, Texture* texture) { + stringToIDMap.insert( + stringIntMap::value_type(name, texture->getManagerId())); + + if (idToTextureMap.find(texture->getManagerId()) == idToTextureMap.end()) { + idToTextureMap.insert( + intTextureMap::value_type(texture->getManagerId(), texture)); + } } -TextureManager::TextureManager() -{ - nextID = 0; +void TextureManager::registerTexture(Texture* texture) { + for (AUTO_VAR(it, idToTextureMap.begin()); it != idToTextureMap.end(); + ++it) { + if (it->second == texture) { + // Minecraft.getInstance().getLogger().warning("TextureManager.registerTexture + // called, but this texture has " + "already been registered. + // ignoring."); + app.DebugPrintf( + "TextureManager.registerTexture called, but this texture has " + "already been registered. ignoring."); + return; + } + } + + idToTextureMap.insert( + intTextureMap::value_type(texture->getManagerId(), texture)); } -int TextureManager::createTextureID() -{ - return nextID++; +void TextureManager::unregisterTexture(const std::wstring& name, + Texture* texture) { + AUTO_VAR(it, idToTextureMap.find(texture->getManagerId())); + if (it != idToTextureMap.end()) idToTextureMap.erase(it); + + AUTO_VAR(it2, stringToIDMap.find(name)); + if (it2 != stringToIDMap.end()) stringToIDMap.erase(it2); } -Texture *TextureManager::getTexture(const std::wstring &name) -{ - if (stringToIDMap.find(name) != stringToIDMap.end()) - { - return idToTextureMap.find(stringToIDMap.find(name)->second)->second; - } +Stitcher* TextureManager::createStitcher(const std::wstring& name) { + int maxTextureSize = Minecraft::maxSupportedTextureSize(); - return NULL; + return new Stitcher(name, maxTextureSize, maxTextureSize, true); } -void TextureManager::registerName(const std::wstring &name, Texture *texture) -{ - stringToIDMap.insert( stringIntMap::value_type( name, texture->getManagerId() ) ); +std::vector* TextureManager::createTextures( + const std::wstring& filename, bool mipmap) { + std::vector* result = new std::vector(); + TexturePack* texturePack = Minecraft::GetInstance()->skins->getSelected(); + // try { + int mode = Texture::TM_CONTAINER; // Most important -- so it doesn't get + // uploaded to videoram + int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues + // with how we signal non-mipmmapped textures + // to the pixel shader //Texture::WM_CLAMP; + int format = Texture::TFMT_RGBA; + int minFilter = Texture::TFLT_NEAREST; + int magFilter = Texture::TFLT_NEAREST; - if (idToTextureMap.find(texture->getManagerId()) == idToTextureMap.end()) - { - idToTextureMap.insert( intTextureMap::value_type( texture->getManagerId(), texture) ); - } -} + MemSect(32); + std::wstring drive = L""; -void TextureManager::registerTexture(Texture *texture) -{ - for(AUTO_VAR(it, idToTextureMap.begin()); it != idToTextureMap.end(); ++it) - { - if(it->second == texture) - { - //Minecraft.getInstance().getLogger().warning("TextureManager.registerTexture called, but this texture has " + "already been registered. ignoring."); - app.DebugPrintf("TextureManager.registerTexture called, but this texture has already been registered. ignoring."); - return; - } - } - - idToTextureMap.insert( intTextureMap::value_type( texture->getManagerId(), texture ) ); -} - -void TextureManager::unregisterTexture(const std::wstring &name, Texture *texture) -{ - AUTO_VAR(it, idToTextureMap.find(texture->getManagerId())); - if(it != idToTextureMap.end()) idToTextureMap.erase(it); - - AUTO_VAR(it2, stringToIDMap.find(name)); - if(it2 != stringToIDMap.end()) stringToIDMap.erase(it2); -} - -Stitcher *TextureManager::createStitcher(const std::wstring &name) -{ - int maxTextureSize = Minecraft::maxSupportedTextureSize(); - - return new Stitcher(name, maxTextureSize, maxTextureSize, true); -} - -std::vector *TextureManager::createTextures(const std::wstring &filename, bool mipmap) -{ - std::vector *result = new std::vector(); - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - //try { - int mode = Texture::TM_CONTAINER; // Most important -- so it doesn't get uploaded to videoram - int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader //Texture::WM_CLAMP; - int format = Texture::TFMT_RGBA; - int minFilter = Texture::TFLT_NEAREST; - int magFilter = Texture::TFLT_NEAREST; - - MemSect(32); - std::wstring drive = L""; - - - if(texturePack->hasFile(L"res/" + filename,false)) - { - drive = texturePack->getPath(true); - } - else - { + if (texturePack->hasFile(L"res/" + filename, false)) { + drive = texturePack->getPath(true); + } else { #ifdef __PS3__ - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(filename); - char *pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - drive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else -#endif - { - drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); - } - } - - //BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + filename),false,true,drive); //ImageIO::read(texturePack->getResource(L"/" + filename)); - - BufferedImage *image = texturePack->getImageResource(filename, false, true, drive); - MemSect(0); - int height = image->getHeight(); - int width = image->getWidth(); - - std::wstring texName = getTextureNameFromPath(filename); - - if (isAnimation(filename, texturePack)) - { - // TODO: Read this information from the animation file later - int frameWidth = width; - int frameHeight = width; - - // This could end as 0 frames - int frameCount = height / frameWidth; - for (int i = 0; i < frameCount; i++) - { - BufferedImage *subImage = image->getSubimage(0, frameHeight * i, frameWidth, frameHeight); - Texture *texture = createTexture(texName, mode, frameWidth, frameHeight, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, subImage); - delete subImage; - result->push_back(texture); - } - } - else - { - // TODO: Remove this hack -- fix proper rotation support (needed for 'off-aspect textures') - if (width == height) - { - result->push_back(createTexture(texName, mode, width, height, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, image)); - } - else - { - //Minecraft.getInstance().getLogger().warning("TextureManager.createTexture: Skipping " + filename + " because of broken aspect ratio and not animation"); -#ifndef _CONTENT_PACKAGE - wprintf(L"TextureManager.createTexture: Skipping %ls because of broken aspect ratio and not animation\n", filename.c_str()); + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(filename); + char* pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); + drive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else #endif - } - } - delete image; + { + drive = + Minecraft::GetInstance()->skins->getDefault()->getPath(true); + } + } + // BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + + // filename),false,true,drive); + // //ImageIO::read(texturePack->getResource(L"/" + filename)); - //return result; - //} catch (FileNotFoundException e) { - // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture called for file " + filename + ", but that file does not exist. Ignoring."); - //} catch (IOException e) { - // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture encountered an IOException when " + "trying to read file " + filename + ". Ignoring."); - //} - return result; + BufferedImage* image = + texturePack->getImageResource(filename, false, true, drive); + MemSect(0); + int height = image->getHeight(); + int width = image->getWidth(); + + std::wstring texName = getTextureNameFromPath(filename); + + if (isAnimation(filename, texturePack)) { + // TODO: Read this information from the animation file later + int frameWidth = width; + int frameHeight = width; + + // This could end as 0 frames + int frameCount = height / frameWidth; + for (int i = 0; i < frameCount; i++) { + BufferedImage* subImage = + image->getSubimage(0, frameHeight * i, frameWidth, frameHeight); + Texture* texture = + createTexture(texName, mode, frameWidth, frameHeight, clamp, + format, minFilter, magFilter, + mipmap || image->getData(1) != NULL, subImage); + delete subImage; + result->push_back(texture); + } + } else { + // TODO: Remove this hack -- fix proper rotation support (needed for + // 'off-aspect textures') + if (width == height) { + result->push_back(createTexture( + texName, mode, width, height, clamp, format, minFilter, + magFilter, mipmap || image->getData(1) != NULL, image)); + } else { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture: + // Skipping " + filename + " because of broken aspect ratio and not + // animation"); +#ifndef _CONTENT_PACKAGE + wprintf( + L"TextureManager.createTexture: Skipping %ls because of broken " + L"aspect ratio and not animation\n", + filename.c_str()); +#endif + } + } + delete image; + + // return result; + // } catch (FileNotFoundException e) { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture + //called for file " + filename + ", but that file does not exist. + //Ignoring."); } catch (IOException e) { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture + //encountered an IOException when " + "trying to read file " + filename + ". + //Ignoring."); + // } + return result; } -std::wstring TextureManager::getTextureNameFromPath(const std::wstring &filename) -{ - File file(filename); - return file.getName().substr(0, file.getName().find_last_of(L'.')); +std::wstring TextureManager::getTextureNameFromPath( + const std::wstring& filename) { + File file(filename); + return file.getName().substr(0, file.getName().find_last_of(L'.')); } -bool TextureManager::isAnimation(const std::wstring &filename, TexturePack *texturePack) -{ - std::wstring dataFileName = L"/" + filename.substr(0, filename.find_last_of(L'.')) + L".txt"; - bool hasOriginalImage = texturePack->hasFile(L"/" + filename, false); - return Minecraft::GetInstance()->skins->getSelected()->hasFile(dataFileName, !hasOriginalImage); +bool TextureManager::isAnimation(const std::wstring& filename, + TexturePack* texturePack) { + std::wstring dataFileName = + L"/" + filename.substr(0, filename.find_last_of(L'.')) + L".txt"; + bool hasOriginalImage = texturePack->hasFile(L"/" + filename, false); + return Minecraft::GetInstance()->skins->getSelected()->hasFile( + dataFileName, !hasOriginalImage); } -Texture *TextureManager::createTexture(const std::wstring &name, int mode, int width, int height, int wrap, int format, int minFilter, int magFilter, bool mipmap, BufferedImage *image) -{ - Texture *newTex = new Texture(name, mode, width, height, wrap, format, minFilter, magFilter, image, mipmap); - registerTexture(newTex); - return newTex; +Texture* TextureManager::createTexture(const std::wstring& name, int mode, + int width, int height, int wrap, + int format, int minFilter, int magFilter, + bool mipmap, BufferedImage* image) { + Texture* newTex = new Texture(name, mode, width, height, wrap, format, + minFilter, magFilter, image, mipmap); + registerTexture(newTex); + return newTex; } -Texture *TextureManager::createTexture(const std::wstring &name, int mode, int width, int height, int format, bool mipmap) -{ - // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader - //return createTexture(name, mode, width, height, Texture::WM_CLAMP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); - return createTexture(name, mode, width, height, Texture::WM_WRAP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); +Texture* TextureManager::createTexture(const std::wstring& name, int mode, + int width, int height, int format, + bool mipmap) { + // 4J Stu - Don't clamp as it causes issues with how we signal + // non-mipmmapped textures to the pixel shader + // return createTexture(name, mode, width, height, Texture::WM_CLAMP, + // format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); + return createTexture(name, mode, width, height, Texture::WM_WRAP, format, + Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, + NULL); } diff --git a/Minecraft.Client/Textures/TextureManager.h b/Minecraft.Client/Textures/TextureManager.h index 4fb859546..cf1f96b12 100644 --- a/Minecraft.Client/Textures/TextureManager.h +++ b/Minecraft.Client/Textures/TextureManager.h @@ -4,38 +4,42 @@ class Texture; class Stitcher; class TexturePack; -class TextureManager -{ +class TextureManager { private: - static TextureManager *instance; + static TextureManager* instance; - int nextID; - typedef std::unordered_map stringIntMap; - typedef std::unordered_map intTextureMap; - intTextureMap idToTextureMap; - stringIntMap stringToIDMap; + int nextID; + typedef std::unordered_map stringIntMap; + typedef std::unordered_map intTextureMap; + intTextureMap idToTextureMap; + stringIntMap stringToIDMap; public: - static void createInstance(); - static TextureManager *getInstance(); + static void createInstance(); + static TextureManager* getInstance(); private: - TextureManager(); + TextureManager(); public: - int createTextureID(); - Texture *getTexture(const std::wstring &name); - void registerName(const std::wstring &name, Texture *texture); - void registerTexture(Texture *texture); - void unregisterTexture(const std::wstring &name, Texture *texture); - Stitcher *createStitcher(const std::wstring &name); - std::vector *createTextures(const std::wstring &filename, bool mipmap); // 4J added mipmap param + int createTextureID(); + Texture* getTexture(const std::wstring& name); + void registerName(const std::wstring& name, Texture* texture); + void registerTexture(Texture* texture); + void unregisterTexture(const std::wstring& name, Texture* texture); + Stitcher* createStitcher(const std::wstring& name); + std::vector* createTextures( + const std::wstring& filename, bool mipmap); // 4J added mipmap param private: - std::wstring getTextureNameFromPath(const std::wstring &filename); - bool isAnimation(const std::wstring &filename, TexturePack *texturePack); + std::wstring getTextureNameFromPath(const std::wstring& filename); + bool isAnimation(const std::wstring& filename, TexturePack* texturePack); public: - Texture *createTexture(const std::wstring &name, int mode, int width, int height, int wrap, int format, int minFilter, int magFilter, bool mipmap, BufferedImage *image); - Texture *createTexture(const std::wstring &name, int mode, int width, int height, int format, bool mipmap); // 4J Added mipmap param + Texture* createTexture(const std::wstring& name, int mode, int width, + int height, int wrap, int format, int minFilter, + int magFilter, bool mipmap, BufferedImage* image); + Texture* createTexture(const std::wstring& name, int mode, int width, + int height, int format, + bool mipmap); // 4J Added mipmap param }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Textures.cpp b/Minecraft.Client/Textures/Textures.cpp index eecc06df1..98d7d1211 100644 --- a/Minecraft.Client/Textures/Textures.cpp +++ b/Minecraft.Client/Textures/Textures.cpp @@ -17,520 +17,488 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Util/StringHelpers.h" -// Linux/PC port: disable mipmapping globally so textures are always sampled from -// the full-resolution level 0 with GL_NEAREST, giving pixel-crisp Minecraft blocks -// at all distances. Mipmapping causes glGenerateMipmap() to fire (which resets the -// min-filter to GL_NEAREST_MIPMAP_LINEAR on many Mesa/Nvidia drivers) and the -// per-level crispBlend loop is both wasteful and still causes visible blurring. +// Linux/PC port: disable mipmapping globally so textures are always sampled +// from the full-resolution level 0 with GL_NEAREST, giving pixel-crisp +// Minecraft blocks at all distances. Mipmapping causes glGenerateMipmap() to +// fire (which resets the min-filter to GL_NEAREST_MIPMAP_LINEAR on many +// Mesa/Nvidia drivers) and the per-level crispBlend loop is both wasteful and +// still causes visible blurring. bool Textures::MIPMAP = false; -C4JRender::eTextureFormat Textures::TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; +C4JRender::eTextureFormat Textures::TEXTURE_FORMAT = + C4JRender::TEXTURE_FORMAT_RxGyBzAw; int Textures::preLoadedIdx[TN_COUNT]; -const wchar_t *Textures::preLoaded[TN_COUNT] = -{ - L"%blur%misc/pumpkinblur", -// L"%blur%/misc/vignette", // Not currently used - L"%clamp%misc/shadow", -// L"/achievement/bg", // Not currently used - L"art/kz", - L"environment/clouds", - L"environment/rain", - L"environment/snow", - L"gui/gui", - L"gui/icons", - L"item/arrows", - L"item/boat", - L"item/cart", - L"item/sign", - L"misc/mapbg", - L"misc/mapicons", - L"misc/water", - L"misc/footprint", - L"mob/saddle", - L"mob/sheep_fur", - L"mob/spider_eyes", - L"particles", - L"mob/chicken", - L"mob/cow", - L"mob/pig", - L"mob/sheep", - L"mob/squid", - L"mob/wolf", - L"mob/wolf_tame", - L"mob/wolf_angry", - L"mob/creeper", - L"mob/ghast", - L"mob/ghast_fire", - L"mob/zombie", - L"mob/pigzombie", - L"mob/skeleton", - L"mob/slime", - L"mob/spider", - L"mob/char", - L"mob/char1", - L"mob/char2", - L"mob/char3", - L"mob/char4", - L"mob/char5", - L"mob/char6", - L"mob/char7", - L"terrain/moon", - L"terrain/sun", - L"armor/power", +const wchar_t* Textures::preLoaded[TN_COUNT] = { + L"%blur%misc/pumpkinblur", + // L"%blur%/misc/vignette", // Not currently used + L"%clamp%misc/shadow", + // L"/achievement/bg", // Not currently used + L"art/kz", + L"environment/clouds", + L"environment/rain", + L"environment/snow", + L"gui/gui", + L"gui/icons", + L"item/arrows", + L"item/boat", + L"item/cart", + L"item/sign", + L"misc/mapbg", + L"misc/mapicons", + L"misc/water", + L"misc/footprint", + L"mob/saddle", + L"mob/sheep_fur", + L"mob/spider_eyes", + L"particles", + L"mob/chicken", + L"mob/cow", + L"mob/pig", + L"mob/sheep", + L"mob/squid", + L"mob/wolf", + L"mob/wolf_tame", + L"mob/wolf_angry", + L"mob/creeper", + L"mob/ghast", + L"mob/ghast_fire", + L"mob/zombie", + L"mob/pigzombie", + L"mob/skeleton", + L"mob/slime", + L"mob/spider", + L"mob/char", + L"mob/char1", + L"mob/char2", + L"mob/char3", + L"mob/char4", + L"mob/char5", + L"mob/char6", + L"mob/char7", + L"terrain/moon", + L"terrain/sun", + L"armor/power", - // 1.8.2 - L"mob/cavespider", - L"mob/enderman", - L"mob/silverfish", - L"mob/enderman_eyes", - L"misc/explosion", - L"item/xporb", - L"item/chest", - L"item/largechest", + // 1.8.2 + L"mob/cavespider", + L"mob/enderman", + L"mob/silverfish", + L"mob/enderman_eyes", + L"misc/explosion", + L"item/xporb", + L"item/chest", + L"item/largechest", - // 1.3.2 - L"item/enderchest", + // 1.3.2 + L"item/enderchest", - // 1.0.1 - L"mob/redcow", - L"mob/snowman", - L"mob/enderdragon/ender", - L"mob/fire", - L"mob/lava", - L"mob/villager/villager", - L"mob/villager/farmer", - L"mob/villager/librarian", - L"mob/villager/priest", - L"mob/villager/smith", - L"mob/villager/butcher", - L"mob/enderdragon/crystal", - L"mob/enderdragon/shuffle", - L"mob/enderdragon/beam", - L"mob/enderdragon/ender_eyes", - L"%blur%misc/glint", - L"item/book", - L"misc/tunnel", - L"misc/particlefield", - L"terrain/moon_phases", + // 1.0.1 + L"mob/redcow", + L"mob/snowman", + L"mob/enderdragon/ender", + L"mob/fire", + L"mob/lava", + L"mob/villager/villager", + L"mob/villager/farmer", + L"mob/villager/librarian", + L"mob/villager/priest", + L"mob/villager/smith", + L"mob/villager/butcher", + L"mob/enderdragon/crystal", + L"mob/enderdragon/shuffle", + L"mob/enderdragon/beam", + L"mob/enderdragon/ender_eyes", + L"%blur%misc/glint", + L"item/book", + L"misc/tunnel", + L"misc/particlefield", + L"terrain/moon_phases", - // 1.2.3 - L"mob/ozelot", - L"mob/cat_black", - L"mob/cat_red", - L"mob/cat_siamese", - L"mob/villager_golem", - L"mob/skeleton_wither", + // 1.2.3 + L"mob/ozelot", + L"mob/cat_black", + L"mob/cat_red", + L"mob/cat_siamese", + L"mob/villager_golem", + L"mob/skeleton_wither", - // TU 14 - L"mob/wolf_collar", - L"mob/zombie_villager", + // TU 14 + L"mob/wolf_collar", + L"mob/zombie_villager", #ifdef _LARGE_WORLDS - L"misc/additionalmapicons", + L"misc/additionalmapicons", #endif - L"font/Default", - L"font/alternate", + L"font/Default", + L"font/alternate", - // skin packs -/* L"/SP1", - L"/SP2", - L"/SP3", - L"/SPF", + // skin packs + /* L"/SP1", + L"/SP2", + L"/SP3", + L"/SPF", - // themes - L"/ThSt", - L"/ThIr", - L"/ThGo", - L"/ThDi", + // themes + L"/ThSt", + L"/ThIr", + L"/ThGo", + L"/ThDi", - // gamerpics - L"/GPAn", - L"/GPCo", - L"/GPEn", - L"/GPFo", - L"/GPTo", - L"/GPBA", - L"/GPFa", - L"/GPME", - L"/GPMF", - L"/GPMM", - L"/GPSE", + // gamerpics + L"/GPAn", + L"/GPCo", + L"/GPEn", + L"/GPFo", + L"/GPTo", + L"/GPBA", + L"/GPFa", + L"/GPME", + L"/GPMF", + L"/GPMM", + L"/GPSE", - // avatar items - - L"/AH_0006", - L"/AH_0003", - L"/AH_0007", - L"/AH_0005", - L"/AH_0004", - L"/AH_0001", - L"/AH_0002", - L"/AT_0001", - L"/AT_0002", - L"/AT_0003", - L"/AT_0004", - L"/AT_0005", - L"/AT_0006", - L"/AT_0007", - L"/AT_0008", - L"/AT_0009", - L"/AT_0010", - L"/AT_0011", - L"/AT_0012", - L"/AP_0001", - L"/AP_0002", - L"/AP_0003", - L"/AP_0004", - L"/AP_0005", - L"/AP_0006", - L"/AP_0007", - L"/AP_0009", - L"/AP_0010", - L"/AP_0011", - L"/AP_0012", - L"/AP_0013", - L"/AP_0014", - L"/AP_0015", - L"/AP_0016", - L"/AP_0017", - L"/AP_0018", - L"/AA_0001", - L"/AT_0013", - L"/AT_0014", - L"/AT_0015", - L"/AT_0016", - L"/AT_0017", - L"/AT_0018", - L"/AP_0019", - L"/AP_0020", - L"/AP_0021", - L"/AP_0022", - L"/AP_0023", - L"/AH_0008", - L"/AH_0009",*/ + // avatar items - L"gui/items", - L"terrain", + L"/AH_0006", + L"/AH_0003", + L"/AH_0007", + L"/AH_0005", + L"/AH_0004", + L"/AH_0001", + L"/AH_0002", + L"/AT_0001", + L"/AT_0002", + L"/AT_0003", + L"/AT_0004", + L"/AT_0005", + L"/AT_0006", + L"/AT_0007", + L"/AT_0008", + L"/AT_0009", + L"/AT_0010", + L"/AT_0011", + L"/AT_0012", + L"/AP_0001", + L"/AP_0002", + L"/AP_0003", + L"/AP_0004", + L"/AP_0005", + L"/AP_0006", + L"/AP_0007", + L"/AP_0009", + L"/AP_0010", + L"/AP_0011", + L"/AP_0012", + L"/AP_0013", + L"/AP_0014", + L"/AP_0015", + L"/AP_0016", + L"/AP_0017", + L"/AP_0018", + L"/AA_0001", + L"/AT_0013", + L"/AT_0014", + L"/AT_0015", + L"/AT_0016", + L"/AT_0017", + L"/AT_0018", + L"/AP_0019", + L"/AP_0020", + L"/AP_0021", + L"/AP_0022", + L"/AP_0023", + L"/AH_0008", + L"/AH_0009",*/ + + L"gui/items", + L"terrain", }; -Textures::Textures(TexturePackRepository *skins, Options *options) -{ -// pixels = MemoryTracker::createIntBuffer(2048 * 2048); // 4J removed - now just creating this buffer when we need it - missingNo = new BufferedImage(16, 16, BufferedImage::TYPE_INT_ARGB); +Textures::Textures(TexturePackRepository* skins, Options* options) { + // pixels = MemoryTracker::createIntBuffer(2048 * 2048); // 4J removed - + // now just creating this buffer when we need it + missingNo = new BufferedImage(16, 16, BufferedImage::TYPE_INT_ARGB); this->skins = skins; this->options = options; - /* 4J - TODO, maybe... - Graphics g = missingNo.getGraphics(); - g.setColor(Color.WHITE); - g.fillRect(0, 0, 64, 64); - g.setColor(Color.BLACK); - int y = 10; - int i = 0; - while (y < 64) { - String text = (i++ % 2 == 0) ? "missing" : "texture"; - g.drawString(text, 1, y); - y += g.getFont().getSize(); - if (i % 2 == 0) y += 5; - } + /* 4J - TODO, maybe... + Graphics g = missingNo.getGraphics(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, 64, 64); + g.setColor(Color.BLACK); + int y = 10; + int i = 0; + while (y < 64) { + String text = (i++ % 2 == 0) ? "missing" : "texture"; + g.drawString(text, 1, y); + y += g.getFont().getSize(); + if (i % 2 == 0) y += 5; + } - g.dispose(); - */ +g.dispose(); + */ - // 4J Stu - Changed these to our PreStitchedTextureMap from TextureMap - terrain = new PreStitchedTextureMap(Icon::TYPE_TERRAIN, L"terrain", L"textures/blocks/", missingNo, true); - items = new PreStitchedTextureMap(Icon::TYPE_ITEM, L"items", L"textures/items/", missingNo, true); + // 4J Stu - Changed these to our PreStitchedTextureMap from TextureMap + terrain = new PreStitchedTextureMap(Icon::TYPE_TERRAIN, L"terrain", + L"textures/blocks/", missingNo, true); + items = new PreStitchedTextureMap(Icon::TYPE_ITEM, L"items", + L"textures/items/", missingNo, true); - // 4J - added - preload a set of commonly used textures that can then be referenced directly be an enumerated type rather by string - loadIndexedTextures(); + // 4J - added - preload a set of commonly used textures that can then be + // referenced directly be an enumerated type rather by string + loadIndexedTextures(); } -void Textures::loadIndexedTextures() -{ - // 4J - added - preload a set of commonly used textures that can then be referenced directly be an enumerated type rather by string - for( int i = 0; i < TN_COUNT - 2; i++ ) - { - preLoadedIdx[i] = loadTexture((TEXTURE_NAME)i, std::wstring(preLoaded[i]) + L".png"); - } +void Textures::loadIndexedTextures() { + // 4J - added - preload a set of commonly used textures that can then be + // referenced directly be an enumerated type rather by string + for (int i = 0; i < TN_COUNT - 2; i++) { + preLoadedIdx[i] = + loadTexture((TEXTURE_NAME)i, std::wstring(preLoaded[i]) + L".png"); + } } -intArray Textures::loadTexturePixels(TEXTURE_NAME texId, const std::wstring& resourceName) -{ - TexturePack *skin = skins->getSelected(); +intArray Textures::loadTexturePixels(TEXTURE_NAME texId, + const std::wstring& resourceName) { + TexturePack* skin = skins->getSelected(); { intArray id = pixelsMap[resourceName]; - // 4J - if resourceName isn't in the map, it should add an element and as that will use the default constructor, its - // internal data pointer will be NULL + // 4J - if resourceName isn't in the map, it should add an element and + // as that will use the default constructor, its internal data pointer + // will be NULL if (id.data != NULL) return id; } - // 4J - removed try/catch -// try { - intArray res; - //std::wstring in = skin->getResource(resourceName); - if (false)// 4J - removed - was ( in == NULL) - { - res = loadTexturePixels(missingNo); - } - else - { - BufferedImage *bufImage = readImage(texId, resourceName); //in); - res = loadTexturePixels(bufImage); - delete bufImage; - } - - pixelsMap[resourceName] = res; - return res; -/* -} - catch (IOException e) { - e.printStackTrace(); - int[] res = loadTexturePixels(missingNo); - pixelsMap.put(resourceName, res); - return res; + // 4J - removed try/catch + // try { + intArray res; + // std::wstring in = skin->getResource(resourceName); + if (false) // 4J - removed - was ( in == NULL) + { + res = loadTexturePixels(missingNo); + } else { + BufferedImage* bufImage = readImage(texId, resourceName); // in); + res = loadTexturePixels(bufImage); + delete bufImage; } - */ + + pixelsMap[resourceName] = res; + return res; + /* + } + catch (IOException e) { + e.printStackTrace(); + int[] res = loadTexturePixels(missingNo); + pixelsMap.put(resourceName, res); + return res; + } + */ } -intArray Textures::loadTexturePixels(BufferedImage *img) -{ +intArray Textures::loadTexturePixels(BufferedImage* img) { int w = img->getWidth(); int h = img->getHeight(); - intArray pixels(w*h); + intArray pixels(w * h); return loadTexturePixels(img, pixels); } -intArray Textures::loadTexturePixels(BufferedImage *img, intArray pixels) -{ +intArray Textures::loadTexturePixels(BufferedImage* img, intArray pixels) { int w = img->getWidth(); int h = img->getHeight(); img->getRGB(0, 0, w, h, pixels, 0, w); return pixels; } -int Textures::loadTexture(int idx) -{ - if( idx == -1 ) - { - return 0; - } - else - { - if ( idx == TN_TERRAIN ) - { - terrain->getStitchedTexture()->bind(0); - return terrain->getStitchedTexture()->getGlId(); - } - if ( idx == TN_GUI_ITEMS) - { - items->getStitchedTexture()->bind(0); - return items->getStitchedTexture()->getGlId(); - } - return preLoadedIdx[idx]; - } +int Textures::loadTexture(int idx) { + if (idx == -1) { + return 0; + } else { + if (idx == TN_TERRAIN) { + terrain->getStitchedTexture()->bind(0); + return terrain->getStitchedTexture()->getGlId(); + } + if (idx == TN_GUI_ITEMS) { + items->getStitchedTexture()->bind(0); + return items->getStitchedTexture()->getGlId(); + } + return preLoadedIdx[idx]; + } } -// 4J added - textures default to standard 32-bit RGBA format, but where we can, use an 8-bit format. There's 3 different varieties of these currently -// in the renderer that map the single 8-bit channel to RGBA differently. -void Textures::setTextureFormat(const std::wstring& resourceName) -{ - // 4J Stu - These texture formats are not currently in the render header +// 4J added - textures default to standard 32-bit RGBA format, but where we can, +// use an 8-bit format. There's 3 different varieties of these currently in the +// renderer that map the single 8-bit channel to RGBA differently. +void Textures::setTextureFormat(const std::wstring& resourceName) { + // 4J Stu - These texture formats are not currently in the render header #ifdef _XBOX - if(resourceName == L"/environment/clouds.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R1G1B1Ax; - } - else if(resourceName == L"%blur%/misc/pumpkinblur.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; - } - else if(resourceName == L"%clamp%/misc/shadow.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; - } - else if(resourceName == L"/environment/snow.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; - } - else if(resourceName == L"/1_2_2/misc/explosion.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; - } - else + if (resourceName == L"/environment/clouds.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R1G1B1Ax; + } else if (resourceName == L"%blur%/misc/pumpkinblur.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; + } else if (resourceName == L"%clamp%/misc/shadow.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; + } else if (resourceName == L"/environment/snow.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; + } else if (resourceName == L"/1_2_2/misc/explosion.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; + } else #endif - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - } + { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + } } -void Textures::bindTexture(const std::wstring &resourceName) -{ - bind(loadTexture(TN_COUNT,resourceName)); +void Textures::bindTexture(const std::wstring& resourceName) { + bind(loadTexture(TN_COUNT, resourceName)); } // 4J Added -void Textures::bindTexture(int resourceId) -{ - bind(loadTexture(resourceId)); +void Textures::bindTexture(int resourceId) { bind(loadTexture(resourceId)); } + +void Textures::bind(int id) { + // if (id != lastBoundId) + { + if (id < 0) return; + glBindTexture(GL_TEXTURE_2D, id); + // lastBoundId = id; + } } -void Textures::bind(int id) -{ - //if (id != lastBoundId) - { - if(id < 0) return; - glBindTexture(GL_TEXTURE_2D, id); - // lastBoundId = id; - } -} +void Textures::clearLastBoundId() { lastBoundId = -1; } -void Textures::clearLastBoundId() -{ - lastBoundId = -1; -} +int Textures::loadTexture(TEXTURE_NAME texId, + const std::wstring& resourceName) { + // char buf[256]; + // wcstombs(buf, resourceName.c_str(), 256); + // printf("Textures::loadTexture name - %s\n",buf); -int Textures::loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName) -{ -// char buf[256]; -// wcstombs(buf, resourceName.c_str(), 256); -// printf("Textures::loadTexture name - %s\n",buf); + // if (resourceName.compare(L"/terrain.png") == 0) + //{ + // terrain->getStitchedTexture()->bind(0); + // return terrain->getStitchedTexture()->getGlId(); + // } + // if (resourceName.compare(L"/gui/items.png") == 0) + //{ + // items->getStitchedTexture()->bind(0); + // return items->getStitchedTexture()->getGlId(); + // } - //if (resourceName.compare(L"/terrain.png") == 0) - //{ - // terrain->getStitchedTexture()->bind(0); - // return terrain->getStitchedTexture()->getGlId(); - //} - //if (resourceName.compare(L"/gui/items.png") == 0) - //{ - // items->getStitchedTexture()->bind(0); - // return items->getStitchedTexture()->getGlId(); - //} - - // If the texture is not present in the idMap, load it, otherwise return its id + // If the texture is not present in the idMap, load it, otherwise return its + // id { - bool inMap = ( idMap.find(resourceName) != idMap.end() ); + bool inMap = (idMap.find(resourceName) != idMap.end()); int id = idMap[resourceName]; if (inMap) return id; } - std::wstring pathName = resourceName; + std::wstring pathName = resourceName; - // 4J - added special cases to avoid mipmapping on clouds & shadows - if( (resourceName == L"environment/clouds.png") || - (resourceName == L"%clamp%misc/shadow.png") || - (resourceName == L"%blur%misc/pumpkinblur.png") || - (resourceName == L"%clamp%misc/shadow.png") || - (resourceName == L"gui/icons.png" ) || - (resourceName == L"gui/gui.png" ) || - (resourceName == L"misc/footprint.png") ) - { - MIPMAP = false; - } - setTextureFormat(resourceName); - - // 4J - removed try/catch -// try { - int id = MemoryTracker::genTextures(); - - - std::wstring prefix = L"%blur%"; - bool blur = resourceName.substr(0, prefix.size()).compare(prefix) == 0; //resourceName.startsWith("%blur%"); - if (blur) pathName = resourceName.substr(6); - - prefix = L"%clamp%"; - bool clamp = resourceName.substr(0, prefix.size()).compare(prefix) == 0; //resourceName.startsWith("%clamp%"); - if (clamp) pathName = resourceName.substr(7); - - //std::wstring in = skins->getSelected()->getResource(pathName); - if (false ) // 4J - removed was ( in == NULL) - { - loadTexture(missingNo, id, blur, clamp); - } - else - { - // 4J Stu - Get resource above just returns the name for texture packs - BufferedImage *bufImage = readImage(texId, pathName); //in); - loadTexture(bufImage, id, blur, clamp); - delete bufImage; - } - - idMap[resourceName] = id; - MIPMAP = true; // 4J added - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - return id; - /* - } catch (IOException e) { - e.printStackTrace(); - MemoryTracker.genTextures(ib); - int id = ib.get(0); - loadTexture(missingNo, id); - idMap.put(resourceName, id); - return id; + // 4J - added special cases to avoid mipmapping on clouds & shadows + if ((resourceName == L"environment/clouds.png") || + (resourceName == L"%clamp%misc/shadow.png") || + (resourceName == L"%blur%misc/pumpkinblur.png") || + (resourceName == L"%clamp%misc/shadow.png") || + (resourceName == L"gui/icons.png") || + (resourceName == L"gui/gui.png") || + (resourceName == L"misc/footprint.png")) { + MIPMAP = false; } - */ + setTextureFormat(resourceName); + + // 4J - removed try/catch + // try { + int id = MemoryTracker::genTextures(); + + std::wstring prefix = L"%blur%"; + bool blur = resourceName.substr(0, prefix.size()).compare(prefix) == + 0; // resourceName.startsWith("%blur%"); + if (blur) pathName = resourceName.substr(6); + + prefix = L"%clamp%"; + bool clamp = resourceName.substr(0, prefix.size()).compare(prefix) == + 0; // resourceName.startsWith("%clamp%"); + if (clamp) pathName = resourceName.substr(7); + + // std::wstring in = skins->getSelected()->getResource(pathName); + if (false) // 4J - removed was ( in == NULL) + { + loadTexture(missingNo, id, blur, clamp); + } else { + // 4J Stu - Get resource above just returns the name for texture packs + BufferedImage* bufImage = readImage(texId, pathName); // in); + loadTexture(bufImage, id, blur, clamp); + delete bufImage; + } + + idMap[resourceName] = id; + MIPMAP = true; // 4J added + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + return id; + /* +} catch (IOException e) { +e.printStackTrace(); +MemoryTracker.genTextures(ib); +int id = ib.get(0); +loadTexture(missingNo, id); +idMap.put(resourceName, id); +return id; +} +*/ } -int Textures::getTexture(BufferedImage *img, C4JRender::eTextureFormat format, bool mipmap) -{ +int Textures::getTexture(BufferedImage* img, C4JRender::eTextureFormat format, + bool mipmap) { int id = MemoryTracker::genTextures(); - TEXTURE_FORMAT = format; - MIPMAP = mipmap; + TEXTURE_FORMAT = format; + MIPMAP = mipmap; loadTexture(img, id); - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - MIPMAP = true; + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + MIPMAP = true; loadedImages[id] = img; return id; } -void Textures::loadTexture(BufferedImage *img, int id) -{ -// printf("Textures::loadTexture BufferedImage %d\n",id); +void Textures::loadTexture(BufferedImage* img, int id) { + // printf("Textures::loadTexture BufferedImage %d\n",id); - loadTexture(img, id, false, false); + loadTexture(img, id, false, false); } -void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) -{ -// printf("Textures::loadTexture BufferedImage with blur and clamp %d\n",id); - int iMipLevels=1; - MemSect(33); +void Textures::loadTexture(BufferedImage* img, int id, bool blur, bool clamp) { + // printf("Textures::loadTexture BufferedImage with blur and clamp + //%d\n",id); + int iMipLevels = 1; + MemSect(33); glBindTexture(GL_TEXTURE_2D, id); - if (MIPMAP) - { - // Linux/PC port: force GL_NEAREST to avoid mip-level distance blurring and keep - // Minecraft textures pixel-crisp at all distances. + if (MIPMAP) { + // Linux/PC port: force GL_NEAREST to avoid mip-level distance blurring + // and keep Minecraft textures pixel-crisp at all distances. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4); - */ - } - else - { + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4); + */ + } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } - if (blur) - { + if (blur) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } - if (clamp) - { + if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - } - else - { + } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } @@ -538,154 +506,154 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) int w = img->getWidth(); int h = img->getHeight(); - intArray rawPixels(w*h); + intArray rawPixels(w * h); img->getRGB(0, 0, w, h, rawPixels, 0, w); - if (options != NULL && options->anaglyph3d) - { - rawPixels = anaglyph(rawPixels); - } + if (options != NULL && options->anaglyph3d) { + rawPixels = anaglyph(rawPixels); + } - byteArray newPixels(w * h * 4); - for (unsigned int i = 0; i < rawPixels.length; i++) - { + byteArray newPixels(w * h * 4); + for (unsigned int i = 0; i < rawPixels.length; i++) { int a = (rawPixels[i] >> 24) & 0xff; int r = (rawPixels[i] >> 16) & 0xff; int g = (rawPixels[i] >> 8) & 0xff; int b = (rawPixels[i]) & 0xff; #ifdef _XBOX - newPixels[i * 4 + 0] = (uint8_t) a; - newPixels[i * 4 + 1] = (uint8_t) r; - newPixels[i * 4 + 2] = (uint8_t) g; - newPixels[i * 4 + 3] = (uint8_t) b; + newPixels[i * 4 + 0] = (uint8_t)a; + newPixels[i * 4 + 1] = (uint8_t)r; + newPixels[i * 4 + 2] = (uint8_t)g; + newPixels[i * 4 + 3] = (uint8_t)b; #else - newPixels[i * 4 + 0] = (uint8_t) r; - newPixels[i * 4 + 1] = (uint8_t) g; - newPixels[i * 4 + 2] = (uint8_t) b; - newPixels[i * 4 + 3] = (uint8_t) a; + newPixels[i * 4 + 0] = (uint8_t)r; + newPixels[i * 4 + 1] = (uint8_t)g; + newPixels[i * 4 + 2] = (uint8_t)b; + newPixels[i * 4 + 3] = (uint8_t)a; #endif } - // 4J - now creating a buffer of the size we require dynamically - ByteBuffer *pixels = MemoryTracker::createByteBuffer(w * h * 4); + // 4J - now creating a buffer of the size we require dynamically + ByteBuffer* pixels = MemoryTracker::createByteBuffer(w * h * 4); pixels->clear(); pixels->put(newPixels); pixels->position(0)->limit(newPixels.length); - delete[] rawPixels.data; - delete[] newPixels.data; - - if (MIPMAP) - { - // 4J-PB - In the new XDK, the CreateTexture will fail if the number of mipmaps is higher than the width & height passed in will allow! - int iWidthMips=1; - int iHeightMips=1; - while((8<5)iMipLevels = 5; - RenderManager.TextureSetTextureLevels(iMipLevels); // 4J added - } - RenderManager.TextureData(w,h,pixels->getBuffer(),0,TEXTURE_FORMAT); - //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + delete[] rawPixels.data; + delete[] newPixels.data; - if (MIPMAP) - { - for (int level = 1; level < iMipLevels; level++) - { + if (MIPMAP) { + // 4J-PB - In the new XDK, the CreateTexture will fail if the number of + // mipmaps is higher than the width & height passed in will allow! + int iWidthMips = 1; + int iHeightMips = 1; + while ((8 << iWidthMips) < w) iWidthMips++; + while ((8 << iHeightMips) < h) iHeightMips++; + + iMipLevels = (iWidthMips < iHeightMips) ? iWidthMips : iHeightMips; + // RenderManager.TextureSetTextureLevels(5); // 4J added + if (iMipLevels > 5) iMipLevels = 5; + RenderManager.TextureSetTextureLevels(iMipLevels); // 4J added + } + RenderManager.TextureData(w, h, pixels->getBuffer(), 0, TEXTURE_FORMAT); + // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL12.GL_BGRA, + // GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + + if (MIPMAP) { + for (int level = 1; level < iMipLevels; level++) { int ow = w >> (level - 1); // int oh = h >> (level - 1); int ww = w >> level; int hh = h >> level; - // 4J - added tempData so we aren't overwriting source data - unsigned int *tempData = new unsigned int[ww * hh]; - // 4J - added - have we loaded mipmap data for this level? Use that rather than generating if possible - if( img->getData( level ) ) - { - memcpy( tempData, img->getData( level ), ww * hh * 4); + // 4J - added tempData so we aren't overwriting source data + unsigned int* tempData = new unsigned int[ww * hh]; + // 4J - added - have we loaded mipmap data for this level? Use that + // rather than generating if possible + if (img->getData(level)) { + memcpy(tempData, img->getData(level), ww * hh * 4); #ifndef _XBOX - // Swap ARGB to RGBA - for( int i = 0; i < ww * hh ; i++ ) - { - tempData[i] = ( tempData[i] >> 24 ) | (tempData[i] << 8 ); - } + // Swap ARGB to RGBA + for (int i = 0; i < ww * hh; i++) { + tempData[i] = (tempData[i] >> 24) | (tempData[i] << 8); + } #endif - } - else - { - for (int x = 0; x < ww; x++) - for (int y = 0; y < hh; y++) - { - int c0 = pixels->getInt(((x * 2 + 0) + (y * 2 + 0) * ow) * 4); - int c1 = pixels->getInt(((x * 2 + 1) + (y * 2 + 0) * ow) * 4); - int c2 = pixels->getInt(((x * 2 + 1) + (y * 2 + 1) * ow) * 4); - int c3 = pixels->getInt(((x * 2 + 0) + (y * 2 + 1) * ow) * 4); + } else { + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + int c0 = pixels->getInt( + ((x * 2 + 0) + (y * 2 + 0) * ow) * 4); + int c1 = pixels->getInt( + ((x * 2 + 1) + (y * 2 + 0) * ow) * 4); + int c2 = pixels->getInt( + ((x * 2 + 1) + (y * 2 + 1) * ow) * 4); + int c3 = pixels->getInt( + ((x * 2 + 0) + (y * 2 + 1) * ow) * 4); #ifndef _XBOX - // 4J - convert our RGBA texels to ARGB that crispBlend is expecting - // 4jcraft, added uint cast to pervent shift of neg int - c0 = ( ( c0 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c0 << 24 ); - c1 = ( ( c1 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c1 << 24 ); - c2 = ( ( c2 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c2 << 24 ); - c3 = ( ( c3 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c3 << 24 ); + // 4J - convert our RGBA texels to ARGB that crispBlend + // is expecting 4jcraft, added uint cast to pervent + // shift of neg int + c0 = + ((c0 >> 8) & 0x00ffffff) | ((unsigned int)c0 << 24); + c1 = + ((c1 >> 8) & 0x00ffffff) | ((unsigned int)c1 << 24); + c2 = + ((c2 >> 8) & 0x00ffffff) | ((unsigned int)c2 << 24); + c3 = + ((c3 >> 8) & 0x00ffffff) | ((unsigned int)c3 << 24); #endif - int col = Texture::crispBlend(Texture::crispBlend(c0, c1), Texture::crispBlend(c2, c3)); + int col = + Texture::crispBlend(Texture::crispBlend(c0, c1), + Texture::crispBlend(c2, c3)); #ifndef _XBOX - // 4J - and back from ARGB -> RGBA - col = ( (unsigned int) col << 8 ) | (( col >> 24 ) & 0xff); + // 4J - and back from ARGB -> RGBA + col = ((unsigned int)col << 8) | ((col >> 24) & 0xff); #endif - tempData[x + y * ww] = col; - } - } - for (int x = 0; x < ww; x++ ) - for (int y = 0; y < hh; y++) - { - pixels->putInt((x + y * ww) * 4, tempData[x + y * ww]); - } - delete [] tempData; - RenderManager.TextureData(ww,hh,pixels->getBuffer(),level,TEXTURE_FORMAT); + tempData[x + y * ww] = col; + } + } + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + pixels->putInt((x + y * ww) * 4, tempData[x + y * ww]); + } + delete[] tempData; + RenderManager.TextureData(ww, hh, pixels->getBuffer(), level, + TEXTURE_FORMAT); } } /* - * if (MIPMAP) { GLU.gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, w, h, - * GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { } - */ - delete pixels; // 4J - now creating this dynamically - MemSect(0); + * if (MIPMAP) { GLU.gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, w, h, + * GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { } + */ + delete pixels; // 4J - now creating this dynamically + MemSect(0); } -intArray Textures::anaglyph(intArray rawPixels) -{ - intArray result(rawPixels.length); - for (unsigned int i = 0; i < rawPixels.length; i++) - { - int a = (rawPixels[i] >> 24) & 0xff; - int r = (rawPixels[i] >> 16) & 0xff; - int g = (rawPixels[i] >> 8) & 0xff; - int b = (rawPixels[i]) & 0xff; +intArray Textures::anaglyph(intArray rawPixels) { + intArray result(rawPixels.length); + for (unsigned int i = 0; i < rawPixels.length; i++) { + int a = (rawPixels[i] >> 24) & 0xff; + int r = (rawPixels[i] >> 16) & 0xff; + int g = (rawPixels[i] >> 8) & 0xff; + int b = (rawPixels[i]) & 0xff; - int rr = (r * 30 + g * 59 + b * 11) / 100; - int gg = (r * 30 + g * 70) / (100); - int bb = (r * 30 + b * 70) / (100); + int rr = (r * 30 + g * 59 + b * 11) / 100; + int gg = (r * 30 + g * 70) / (100); + int bb = (r * 30 + b * 70) / (100); + result[i] = a << 24 | rr << 16 | gg << 8 | bb; + } - result[i] = a << 24 | rr << 16 | gg << 8 | bb; - } + delete[] rawPixels.data; - delete[] rawPixels.data; - - return result; + return result; } -void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) -{ +void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) { bind(id); - // Removed in Java + // Removed in Java #if 0 if (MIPMAP) { @@ -700,29 +668,26 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - if (options != NULL && options->anaglyph3d) - { - rawPixels = anaglyph(rawPixels); - } + if (options != NULL && options->anaglyph3d) { + rawPixels = anaglyph(rawPixels); + } - byteArray newPixels(w * h * 4); - for (unsigned int i = 0; i < rawPixels.length; i++) - { + byteArray newPixels(w * h * 4); + for (unsigned int i = 0; i < rawPixels.length; i++) { int a = (rawPixels[i] >> 24) & 0xff; int r = (rawPixels[i] >> 16) & 0xff; int g = (rawPixels[i] >> 8) & 0xff; int b = (rawPixels[i]) & 0xff; - if (options != NULL && options->anaglyph3d) - { + if (options != NULL && options->anaglyph3d) { int rr = (r * 30 + g * 59 + b * 11) / 100; int gg = (r * 30 + g * 70) / (100); int bb = (r * 30 + b * 70) / (100); @@ -732,35 +697,38 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) b = bb; } - newPixels[i * 4 + 0] = (uint8_t) r; - newPixels[i * 4 + 1] = (uint8_t) g; - newPixels[i * 4 + 2] = (uint8_t) b; - newPixels[i * 4 + 3] = (uint8_t) a; + newPixels[i * 4 + 0] = (uint8_t)r; + newPixels[i * 4 + 1] = (uint8_t)g; + newPixels[i * 4 + 2] = (uint8_t)b; + newPixels[i * 4 + 3] = (uint8_t)a; } - ByteBuffer *pixels = MemoryTracker::createByteBuffer(w * h * 4); // 4J - now creating dynamically + ByteBuffer* pixels = MemoryTracker::createByteBuffer( + w * h * 4); // 4J - now creating dynamically pixels->put(newPixels); pixels->position(0)->limit(newPixels.length); - delete [] newPixels.data; + delete[] newPixels.data; - // New - // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + // New + // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, + // GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); #ifdef _XBOX - RenderManager.TextureDataUpdate(pixels->getBuffer(),0); + RenderManager.TextureDataUpdate(pixels->getBuffer(), 0); #else - RenderManager.TextureDataUpdate(0, 0,w,h,pixels->getBuffer(),0); + RenderManager.TextureDataUpdate(0, 0, w, h, pixels->getBuffer(), 0); #endif - // Old - //glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - delete pixels; + // Old + // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, + // pixels); + delete pixels; } -// 4J - added. This is a more minimal version of replaceTexture that assumes the texture bytes are already in order, and so doesn't do any of the extra copying round -// that the original java version does -void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) -{ +// 4J - added. This is a more minimal version of replaceTexture that assumes the +// texture bytes are already in order, and so doesn't do any of the extra +// copying round that the original java version does +void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) { glBindTexture(GL_TEXTURE_2D, id); - // Remove in Java + // Remove in Java #if 0 if (MIPMAP) { @@ -775,28 +743,29 @@ void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #ifdef _XBOX - RenderManager.TextureDataUpdate(rawPixels.data, 0); + RenderManager.TextureDataUpdate(rawPixels.data, 0); #else - RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); + RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); #endif } -// 4J - added. This is a more minimal version of replaceTexture that assumes the texture bytes are already in order, and so doesn't do any of the extra copying round -// that the original java version does -void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, int id) -{ +// 4J - added. This is a more minimal version of replaceTexture that assumes the +// texture bytes are already in order, and so doesn't do any of the extra +// copying round that the original java version does +void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, + int id) { glBindTexture(GL_TEXTURE_2D, id); - // Remove in Java + // Remove in Java #if 0 if (MIPMAP) { @@ -811,105 +780,84 @@ void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #ifdef _XBOX - RenderManager.TextureDataUpdate(rawPixels.data, 0); + RenderManager.TextureDataUpdate(rawPixels.data, 0); #else - RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); + RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); #endif } -void Textures::releaseTexture(int id) -{ +void Textures::releaseTexture(int id) { loadedImages.erase(id); glDeleteTextures(id); } -int Textures::loadHttpTexture(const std::wstring& url, const std::wstring& backup) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - if (texture->id < 0) - { +int Textures::loadHttpTexture(const std::wstring& url, + const std::wstring& backup) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + if (texture->id < 0) { texture->id = getTexture(texture->loadedImage); - } - else - { + } else { loadTexture(texture->loadedImage, texture->id); } texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) - { - if (backup.empty() ) return -1; + if (texture == NULL || texture->id < 0) { + if (backup.empty()) return -1; return loadTexture(TN_COUNT, backup); } return texture->id; } -int Textures::loadHttpTexture(const std::wstring& url, int backup) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - if (texture->id < 0) - { +int Textures::loadHttpTexture(const std::wstring& url, int backup) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + if (texture->id < 0) { texture->id = getTexture(texture->loadedImage); - } - else - { + } else { loadTexture(texture->loadedImage, texture->id); } texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) - { + if (texture == NULL || texture->id < 0) { return loadTexture(backup); } return texture->id; } -bool Textures::hasHttpTexture(const std::wstring &url) -{ - return httpTextures.find(url) != httpTextures.end(); +bool Textures::hasHttpTexture(const std::wstring& url) { + return httpTextures.find(url) != httpTextures.end(); } -HttpTexture *Textures::addHttpTexture(const std::wstring& url, HttpTextureProcessor *processor) -{ - HttpTexture *texture = httpTextures[url]; - if (texture == NULL) - { +HttpTexture* Textures::addHttpTexture(const std::wstring& url, + HttpTextureProcessor* processor) { + HttpTexture* texture = httpTextures[url]; + if (texture == NULL) { httpTextures[url] = new HttpTexture(url, processor); - } - else - { + } else { texture->count++; } return texture; } -void Textures::removeHttpTexture(const std::wstring& url) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { +void Textures::removeHttpTexture(const std::wstring& url) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { texture->count--; - if (texture->count == 0) - { + if (texture->count == 0) { if (texture->id >= 0) releaseTexture(texture->id); httpTextures.erase(url); } @@ -917,130 +865,112 @@ void Textures::removeHttpTexture(const std::wstring& url) } // 4J-PB - adding for texture in memory (from global title storage) -int Textures::loadMemTexture(const std::wstring& url, const std::wstring& backup) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL && app.IsFileInMemoryTextures(url)) - { - // If we haven't loaded it yet, but we have the data for it then add it - texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); - } - if(texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo - if( ( url.substr(0,7) == L"dlcskin" ) || - ( url.substr(0,7) == L"dlccape" ) ) - { - MIPMAP = false; - } +int Textures::loadMemTexture(const std::wstring& url, + const std::wstring& backup) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL && app.IsFileInMemoryTextures(url)) { + // If we haven't loaded it yet, but we have the data for it then add it + texture = addMemTexture(url, new MobSkinMemTextureProcessor()); + } + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + // 4J - Disable mipmapping in general for skins & capes. Have seen + // problems with edge-on polys for some eg mumbo jumbo + if ((url.substr(0, 7) == L"dlcskin") || + (url.substr(0, 7) == L"dlccape")) { + MIPMAP = false; + } - if (texture->id < 0) - { - texture->id = getTexture(texture->loadedImage, C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); - } - else - { - loadTexture(texture->loadedImage, texture->id); - } - texture->isLoaded = true; - MIPMAP = true; - } - } - if (texture == NULL || texture->id < 0) - { - if (backup.empty() ) return -1; - return loadTexture(TN_COUNT,backup); - } - return texture->id; + if (texture->id < 0) { + texture->id = + getTexture(texture->loadedImage, + C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); + } else { + loadTexture(texture->loadedImage, texture->id); + } + texture->isLoaded = true; + MIPMAP = true; + } + } + if (texture == NULL || texture->id < 0) { + if (backup.empty()) return -1; + return loadTexture(TN_COUNT, backup); + } + return texture->id; } -int Textures::loadMemTexture(const std::wstring& url, int backup) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL && app.IsFileInMemoryTextures(url)) - { - // If we haven't loaded it yet, but we have the data for it then add it - texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); - } - if(texture != NULL) - { - texture->ticksSinceLastUse = 0; - if (texture->loadedImage != NULL && !texture->isLoaded) - { - // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo - if( ( url.substr(0,7) == L"dlcskin" ) || - ( url.substr(0,7) == L"dlccape" ) ) - { - MIPMAP = false; - } - if (texture->id < 0) - { - texture->id = getTexture(texture->loadedImage, C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); - } - else - { - loadTexture(texture->loadedImage, texture->id); - } - texture->isLoaded = true; - MIPMAP = true; - } - } - if (texture == NULL || texture->id < 0) - { - return loadTexture(backup); - } - return texture->id; +int Textures::loadMemTexture(const std::wstring& url, int backup) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL && app.IsFileInMemoryTextures(url)) { + // If we haven't loaded it yet, but we have the data for it then add it + texture = addMemTexture(url, new MobSkinMemTextureProcessor()); + } + if (texture != NULL) { + texture->ticksSinceLastUse = 0; + if (texture->loadedImage != NULL && !texture->isLoaded) { + // 4J - Disable mipmapping in general for skins & capes. Have seen + // problems with edge-on polys for some eg mumbo jumbo + if ((url.substr(0, 7) == L"dlcskin") || + (url.substr(0, 7) == L"dlccape")) { + MIPMAP = false; + } + if (texture->id < 0) { + texture->id = + getTexture(texture->loadedImage, + C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); + } else { + loadTexture(texture->loadedImage, texture->id); + } + texture->isLoaded = true; + MIPMAP = true; + } + } + if (texture == NULL || texture->id < 0) { + return loadTexture(backup); + } + return texture->id; } -MemTexture *Textures::addMemTexture(const std::wstring& name,MemTextureProcessor *processor) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(name) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL) - { - // can we find it in the app mem files? - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(name,&pbData,&dwBytes); +MemTexture* Textures::addMemTexture(const std::wstring& name, + MemTextureProcessor* processor) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(name)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL) { + // can we find it in the app mem files? + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(name, &pbData, &dwBytes); - if(dwBytes!=0) - { - texture = new MemTexture(name, pbData, dwBytes, processor); - memTextures[name] = texture; - } - else - { - // 4J Stu - Make an entry for this anyway and we can populate it later - memTextures[name] = NULL; - } - } - else - { - texture->count++; - } + if (dwBytes != 0) { + texture = new MemTexture(name, pbData, dwBytes, processor); + memTextures[name] = texture; + } else { + // 4J Stu - Make an entry for this anyway and we can populate it + // later + memTextures[name] = NULL; + } + } else { + texture->count++; + } - delete processor; + delete processor; - return texture; + return texture; } -// MemTexture *Textures::getMemTexture(const std::wstring& url, MemTextureProcessor *processor) +// MemTexture *Textures::getMemTexture(const std::wstring& url, +// MemTextureProcessor *processor) // { // MemTexture *texture = memTextures[url]; // if (texture != NULL) @@ -1050,93 +980,90 @@ MemTexture *Textures::addMemTexture(const std::wstring& name,MemTextureProcessor // return texture; // } -void Textures::removeMemTexture(const std::wstring& url) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; +void Textures::removeMemTexture(const std::wstring& url) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; - // If it's NULL then we should just remove the entry - if( texture == NULL ) memTextures.erase(url); - } - if(texture != NULL) - { - texture->count--; - if (texture->count == 0) - { - if (texture->id >= 0) releaseTexture(texture->id); - memTextures.erase(url); - delete texture; - } - } + // If it's NULL then we should just remove the entry + if (texture == NULL) memTextures.erase(url); + } + if (texture != NULL) { + texture->count--; + if (texture->count == 0) { + if (texture->id >= 0) releaseTexture(texture->id); + memTextures.erase(url); + delete texture; + } + } } -void Textures::tick(bool updateTextures, bool tickDynamics) // 4J added updateTextures parameter & tickDynamics +void Textures::tick( + bool updateTextures, + bool tickDynamics) // 4J added updateTextures parameter & tickDynamics { - MemSect(22); - if(tickDynamics) - { - // 4J - added - if we aren't updating the final renderer textures, just tick each of the dynamic textures instead. This is used so that in frames were we have multiple - // ticks due to framerate compensation, that we don't lock the renderer textures twice needlessly and force the CPU to sync with the GPU. - if( !updateTextures ) - { - MemSect(0); - return; - } + MemSect(22); + if (tickDynamics) { + // 4J - added - if we aren't updating the final renderer textures, just + // tick each of the dynamic textures instead. This is used so that in + // frames were we have multiple ticks due to framerate compensation, + // that we don't lock the renderer textures twice needlessly and force + // the CPU to sync with the GPU. + if (!updateTextures) { + MemSect(0); + return; + } - // 4J - added - tell renderer that we're about to do a block of dynamic texture updates, so we can unlock the resources after they are done rather than a series of locks/unlocks - //RenderManager.TextureDynamicUpdateStart(); - terrain->cycleAnimationFrames(); + // 4J - added - tell renderer that we're about to do a block of dynamic + // texture updates, so we can unlock the resources after they are done + // rather than a series of locks/unlocks + // RenderManager.TextureDynamicUpdateStart(); + terrain->cycleAnimationFrames(); items->cycleAnimationFrames(); - //RenderManager.TextureDynamicUpdateEnd(); // 4J added - see comment above - } + // RenderManager.TextureDynamicUpdateEnd(); // 4J added - see + // comment above + } - // 4J - go over all the memory textures once per frame, and free any that haven't been used for a while. Ones that are being used will - // have their ticksSinceLastUse reset in Textures::loadMemTexture. - for( AUTO_VAR(it, memTextures.begin() ); it != memTextures.end(); ) - { - MemTexture *tex = it->second; + // 4J - go over all the memory textures once per frame, and free any that + // haven't been used for a while. Ones that are being used will have their + // ticksSinceLastUse reset in Textures::loadMemTexture. + for (AUTO_VAR(it, memTextures.begin()); it != memTextures.end();) { + MemTexture* tex = it->second; - if( tex && ( ++tex->ticksSinceLastUse > MemTexture::UNUSED_TICKS_TO_FREE ) ) - { - if (tex->id >= 0) releaseTexture(tex->id); - delete tex; - it = memTextures.erase(it); - } - else - { - it++; - } - - } - MemSect(0); + if (tex && + (++tex->ticksSinceLastUse > MemTexture::UNUSED_TICKS_TO_FREE)) { + if (tex->id >= 0) releaseTexture(tex->id); + delete tex; + it = memTextures.erase(it); + } else { + it++; + } + } + MemSect(0); } -void Textures::reloadAll() -{ - TexturePack *skin = skins->getSelected(); +void Textures::reloadAll() { + TexturePack* skin = skins->getSelected(); - for( int i = 0; i < TN_COUNT - 2; i++ ) - { - releaseTexture(preLoadedIdx[i]); - } + for (int i = 0; i < TN_COUNT - 2; i++) { + releaseTexture(preLoadedIdx[i]); + } - idMap.clear(); - loadedImages.clear(); + idMap.clear(); + loadedImages.clear(); - loadIndexedTextures(); + loadIndexedTextures(); - pixelsMap.clear(); - // 4J Stu - These are not used any more - //WaterColor::init(loadTexturePixels(L"misc/watercolor.png")); - //GrassColor::init(loadTexturePixels(L"misc/grasscolor.png")); - //FoliageColor::init(loadTexturePixels(L"misc/foliagecolor.png")); + pixelsMap.clear(); + // 4J Stu - These are not used any more + // WaterColor::init(loadTexturePixels(L"misc/watercolor.png")); + // GrassColor::init(loadTexturePixels(L"misc/grasscolor.png")); + // FoliageColor::init(loadTexturePixels(L"misc/foliagecolor.png")); - stitch(); + stitch(); - skins->clearInvalidTexturePacks(); + skins->clearInvalidTexturePacks(); #if 0 AUTO_VAR(itEndLI, loadedImages.end() ); @@ -1191,222 +1118,167 @@ void Textures::reloadAll() } #endif - // Recalculate fonts - //Minecraft::GetInstance()->font->loadCharacterWidths(); - //Minecraft::GetInstance()->altFont->loadCharacterWidths(); + // Recalculate fonts + // Minecraft::GetInstance()->font->loadCharacterWidths(); + // Minecraft::GetInstance()->altFont->loadCharacterWidths(); } -void Textures::stitch() -{ - terrain->stitch(); - items->stitch(); +void Textures::stitch() { + terrain->stitch(); + items->stitch(); } -Icon *Textures::getMissingIcon(int type) -{ - switch (type) - { - case Icon::TYPE_ITEM: - default: - return items->getMissingIcon(); - case Icon::TYPE_TERRAIN: - return terrain->getMissingIcon(); - } +Icon* Textures::getMissingIcon(int type) { + switch (type) { + case Icon::TYPE_ITEM: + default: + return items->getMissingIcon(); + case Icon::TYPE_TERRAIN: + return terrain->getMissingIcon(); + } } -BufferedImage *Textures::readImage(TEXTURE_NAME texId, const std::wstring& name) // 4J was InputStream *in +BufferedImage* Textures::readImage( + TEXTURE_NAME texId, const std::wstring& name) // 4J was InputStream *in { - BufferedImage *img=NULL; - MemSect(32); - // is this image one of the Title Update ones? - bool isTu = IsTUImage(texId, name); - std::wstring drive = L""; + BufferedImage* img = NULL; + MemSect(32); + // is this image one of the Title Update ones? + bool isTu = IsTUImage(texId, name); + std::wstring drive = L""; - if(!skins->isUsingDefaultSkin() && skins->getSelected()->hasFile(L"res/" + name,false)) - { - drive = skins->getSelected()->getPath(isTu); - img = skins->getSelected()->getImageResource(name, false, isTu, drive); //new BufferedImage(name,false,isTu,drive); - } - else - { - const char *pchName=wstringtofilename(name); + if (!skins->isUsingDefaultSkin() && + skins->getSelected()->hasFile(L"res/" + name, false)) { + drive = skins->getSelected()->getPath(isTu); + img = skins->getSelected()->getImageResource( + name, false, isTu, + drive); // new BufferedImage(name,false,isTu,drive); + } else { + const char* pchName = wstringtofilename(name); #ifdef __PS3__ - if(app.GetBootedFromDiscPatch() && app.IsFileInPatchList(pchName)) - { - char *pchUsrDir = app.GetBDUsrDirPath(pchName); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + if (app.GetBootedFromDiscPatch() && app.IsFileInPatchList(pchName)) { + char* pchUsrDir = app.GetBDUsrDirPath(pchName); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(isTu) - { - drive= wstr + L"\\Common\\res\\TitleUpdate\\"; + if (isTu) { + drive = wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - drive= wstr + L"\\Common\\"; - } - } - else + } else { + drive = wstr + L"\\Common\\"; + } + } else #endif - { - drive = skins->getDefault()->getPath(isTu); - } + { + drive = skins->getDefault()->getPath(isTu); + } - const char *pchDrive=wstringtofilename(drive); + const char* pchDrive = wstringtofilename(drive); - if(IsOriginalImage(texId, name) || isTu) - { - img = skins->getDefault()->getImageResource(name,false,isTu,drive); //new BufferedImage(name,false,isTu,drive); - } - else - { - img = skins->getDefault()->getImageResource(L"1_2_2/" + name, false, isTu, drive); //new BufferedImage(L"/1_2_2" + name,false,isTu,drive); - } - } + if (IsOriginalImage(texId, name) || isTu) { + img = skins->getDefault()->getImageResource( + name, false, isTu, + drive); // new BufferedImage(name,false,isTu,drive); + } else { + img = skins->getDefault()->getImageResource( + L"1_2_2/" + name, false, isTu, + drive); // new BufferedImage(L"/1_2_2" + + // name,false,isTu,drive); + } + } - MemSect(0); + MemSect(0); return img; } // Match the preload images from their enum to avoid a ton of string comparisons -TEXTURE_NAME TUImages[] = -{ - TN_POWERED_CREEPER, - TN_MOB_ENDERMAN_EYES, - TN_MISC_EXPLOSION, - TN_MOB_ZOMBIE, - TN_MISC_FOOTSTEP, - TN_MOB_RED_COW, - TN_MOB_SNOWMAN, - TN_MOB_ENDERDRAGON, - TN_MOB_VILLAGER_VILLAGER, - TN_MOB_VILLAGER_FARMER, - TN_MOB_VILLAGER_LIBRARIAN, - TN_MOB_VILLAGER_PRIEST, - TN_MOB_VILLAGER_SMITH, - TN_MOB_VILLAGER_BUTCHER, - TN_MOB_ENDERDRAGON_ENDEREYES, - TN__BLUR__MISC_GLINT, - TN_ITEM_BOOK, - TN_MISC_PARTICLEFIELD, +TEXTURE_NAME TUImages[] = { + TN_POWERED_CREEPER, TN_MOB_ENDERMAN_EYES, TN_MISC_EXPLOSION, TN_MOB_ZOMBIE, + TN_MISC_FOOTSTEP, TN_MOB_RED_COW, TN_MOB_SNOWMAN, TN_MOB_ENDERDRAGON, + TN_MOB_VILLAGER_VILLAGER, TN_MOB_VILLAGER_FARMER, TN_MOB_VILLAGER_LIBRARIAN, + TN_MOB_VILLAGER_PRIEST, TN_MOB_VILLAGER_SMITH, TN_MOB_VILLAGER_BUTCHER, + TN_MOB_ENDERDRAGON_ENDEREYES, TN__BLUR__MISC_GLINT, TN_ITEM_BOOK, + TN_MISC_PARTICLEFIELD, - // TU9 - TN_MISC_TUNNEL, - TN_MOB_ENDERDRAGON_BEAM, - TN_GUI_ITEMS, - TN_TERRAIN, - TN_MISC_MAPICONS, + // TU9 + TN_MISC_TUNNEL, TN_MOB_ENDERDRAGON_BEAM, TN_GUI_ITEMS, TN_TERRAIN, + TN_MISC_MAPICONS, - // TU12 - TN_MOB_WITHER_SKELETON, + // TU12 + TN_MOB_WITHER_SKELETON, - // TU14 - TN_TILE_ENDER_CHEST, - TN_ART_KZ, - TN_MOB_WOLF_TAME, - TN_MOB_WOLF_COLLAR, - TN_PARTICLES, - TN_MOB_ZOMBIE_VILLAGER, + // TU14 + TN_TILE_ENDER_CHEST, TN_ART_KZ, TN_MOB_WOLF_TAME, TN_MOB_WOLF_COLLAR, + TN_PARTICLES, TN_MOB_ZOMBIE_VILLAGER, #ifdef _LARGE_WORLDS - TN_MISC_ADDITIONALMAPICONS, + TN_MISC_ADDITIONALMAPICONS, #endif - // TU17 - TN_DEFAULT_FONT, - // TN_ALT_FONT, // Not in TU yet + // TU17 + TN_DEFAULT_FONT, + // TN_ALT_FONT, // Not in TU yet - TN_COUNT // Why is this here? + TN_COUNT // Why is this here? }; // This is for any TU textures that aren't part of our enum indexed preload set -const wchar_t *TUImagePaths[] = -{ - L"font/Default", - L"font/Mojangles_7", - L"font/Mojangles_11", +const wchar_t* TUImagePaths[] = {L"font/Default", L"font/Mojangles_7", + L"font/Mojangles_11", - // TU12 - L"armor/cloth_1.png", - L"armor/cloth_1_b.png", - L"armor/cloth_2.png", - L"armor/cloth_2_b.png", + // TU12 + L"armor/cloth_1.png", L"armor/cloth_1_b.png", + L"armor/cloth_2.png", L"armor/cloth_2_b.png", - NULL -}; + NULL}; -bool Textures::IsTUImage(TEXTURE_NAME texId, const std::wstring& name) -{ - int i = 0; - if(texId < TN_COUNT) - { - while(TUImages[i] < TN_COUNT) - { - if(texId == TUImages[i]) - { - return true; - } - i++; - } - } - i = 0; - while(TUImagePaths[i]) - { - if(name.compare(TUImagePaths[i])==0) - { - return true; - } - i++; - } - return false; +bool Textures::IsTUImage(TEXTURE_NAME texId, const std::wstring& name) { + int i = 0; + if (texId < TN_COUNT) { + while (TUImages[i] < TN_COUNT) { + if (texId == TUImages[i]) { + return true; + } + i++; + } + } + i = 0; + while (TUImagePaths[i]) { + if (name.compare(TUImagePaths[i]) == 0) { + return true; + } + i++; + } + return false; } -TEXTURE_NAME OriginalImages[] = -{ - TN_MOB_CHAR, - TN_MOB_CHAR1, - TN_MOB_CHAR2, - TN_MOB_CHAR3, - TN_MOB_CHAR4, - TN_MOB_CHAR5, - TN_MOB_CHAR6, - TN_MOB_CHAR7, +TEXTURE_NAME OriginalImages[] = {TN_MOB_CHAR, TN_MOB_CHAR1, TN_MOB_CHAR2, + TN_MOB_CHAR3, TN_MOB_CHAR4, TN_MOB_CHAR5, + TN_MOB_CHAR6, TN_MOB_CHAR7, - TN_MISC_MAPBG, + TN_MISC_MAPBG, - TN_COUNT -}; - -const wchar_t *OriginalImagesPaths[] = -{ - L"misc/watercolor.png", + TN_COUNT}; - NULL -}; +const wchar_t* OriginalImagesPaths[] = {L"misc/watercolor.png", -bool Textures::IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name) -{ - int i = 0; - if(texId < TN_COUNT) - { - while(OriginalImages[i] < TN_COUNT) - { - if(texId == OriginalImages[i]) - { - return true; - } - i++; - } - } - i = 0; - while(OriginalImagesPaths[i]) - { - if(name.compare(OriginalImagesPaths[i])==0) - { - return true; - } - i++; - } - return false; + NULL}; + +bool Textures::IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name) { + int i = 0; + if (texId < TN_COUNT) { + while (OriginalImages[i] < TN_COUNT) { + if (texId == OriginalImages[i]) { + return true; + } + i++; + } + } + i = 0; + while (OriginalImagesPaths[i]) { + if (name.compare(OriginalImagesPaths[i]) == 0) { + return true; + } + i++; + } + return false; } - diff --git a/Minecraft.Client/Textures/Textures.h b/Minecraft.Client/Textures/Textures.h index a96947384..f44075c58 100644 --- a/Minecraft.Client/Textures/Textures.h +++ b/Minecraft.Client/Textures/Textures.h @@ -13,275 +13,291 @@ class Options; class IntBuffer; class PreStitchedTextureMap; +typedef enum _TEXTURE_NAME { + TN__BLUR__MISC_PUMPKINBLUR, + // TN__BLUR__MISC_VIGNETTE, // Not currently used + TN__CLAMP__MISC_SHADOW, + // TN_ACHIEVEMENT_BG, // Not currently used + TN_ART_KZ, + TN_ENVIRONMENT_CLOUDS, + TN_ENVIRONMENT_RAIN, + TN_ENVIRONMENT_SNOW, + TN_GUI_GUI, + TN_GUI_ICONS, + TN_ITEM_ARROWS, + TN_ITEM_BOAT, + TN_ITEM_CART, + TN_ITEM_SIGN, + TN_MISC_MAPBG, + TN_MISC_MAPICONS, + TN_MISC_WATER, + TN_MISC_FOOTSTEP, + TN_MOB_SADDLE, + TN_MOB_SHEEP_FUR, + TN_MOB_SPIDER_EYES, + TN_PARTICLES, + TN_MOB_CHICKEN, + TN_MOB_COW, + TN_MOB_PIG, + TN_MOB_SHEEP, + TN_MOB_SQUID, + TN_MOB_WOLF, + TN_MOB_WOLF_TAME, + TN_MOB_WOLF_ANGRY, + TN_MOB_CREEPER, + TN_MOB_GHAST, + TN_MOB_GHAST_FIRE, + TN_MOB_ZOMBIE, + TN_MOB_PIGZOMBIE, + TN_MOB_SKELETON, + TN_MOB_SLIME, + TN_MOB_SPIDER, + TN_MOB_CHAR, + TN_MOB_CHAR1, + TN_MOB_CHAR2, + TN_MOB_CHAR3, + TN_MOB_CHAR4, + TN_MOB_CHAR5, + TN_MOB_CHAR6, + TN_MOB_CHAR7, + TN_TERRAIN_MOON, + TN_TERRAIN_SUN, + TN_POWERED_CREEPER, -typedef enum _TEXTURE_NAME -{ - TN__BLUR__MISC_PUMPKINBLUR, -// TN__BLUR__MISC_VIGNETTE, // Not currently used - TN__CLAMP__MISC_SHADOW, -// TN_ACHIEVEMENT_BG, // Not currently used - TN_ART_KZ, - TN_ENVIRONMENT_CLOUDS, - TN_ENVIRONMENT_RAIN, - TN_ENVIRONMENT_SNOW, - TN_GUI_GUI, - TN_GUI_ICONS, - TN_ITEM_ARROWS, - TN_ITEM_BOAT, - TN_ITEM_CART, - TN_ITEM_SIGN, - TN_MISC_MAPBG, - TN_MISC_MAPICONS, - TN_MISC_WATER, - TN_MISC_FOOTSTEP, - TN_MOB_SADDLE, - TN_MOB_SHEEP_FUR, - TN_MOB_SPIDER_EYES, - TN_PARTICLES, - TN_MOB_CHICKEN, - TN_MOB_COW, - TN_MOB_PIG, - TN_MOB_SHEEP, - TN_MOB_SQUID, - TN_MOB_WOLF, - TN_MOB_WOLF_TAME, - TN_MOB_WOLF_ANGRY, - TN_MOB_CREEPER, - TN_MOB_GHAST, - TN_MOB_GHAST_FIRE, - TN_MOB_ZOMBIE, - TN_MOB_PIGZOMBIE, - TN_MOB_SKELETON, - TN_MOB_SLIME, - TN_MOB_SPIDER, - TN_MOB_CHAR, - TN_MOB_CHAR1, - TN_MOB_CHAR2, - TN_MOB_CHAR3, - TN_MOB_CHAR4, - TN_MOB_CHAR5, - TN_MOB_CHAR6, - TN_MOB_CHAR7, - TN_TERRAIN_MOON, - TN_TERRAIN_SUN, - TN_POWERED_CREEPER, + // 1.8.2 + TN_MOB_CAVE_SPIDER, + TN_MOB_ENDERMAN, + TN_MOB_SILVERFISH, + TN_MOB_ENDERMAN_EYES, + TN_MISC_EXPLOSION, + TN_ITEM_EXPERIENCE_ORB, + TN_TILE_CHEST, + TN_TILE_LARGE_CHEST, - // 1.8.2 - TN_MOB_CAVE_SPIDER, - TN_MOB_ENDERMAN, - TN_MOB_SILVERFISH, - TN_MOB_ENDERMAN_EYES, - TN_MISC_EXPLOSION, - TN_ITEM_EXPERIENCE_ORB, - TN_TILE_CHEST, - TN_TILE_LARGE_CHEST, + // 1.3.2 + TN_TILE_ENDER_CHEST, - // 1.3.2 - TN_TILE_ENDER_CHEST, + // 1.0.1 + TN_MOB_RED_COW, + TN_MOB_SNOWMAN, + TN_MOB_ENDERDRAGON, + TN_MOB_BLAZE, + TN_MOB_LAVA, + TN_MOB_VILLAGER_VILLAGER, + TN_MOB_VILLAGER_FARMER, + TN_MOB_VILLAGER_LIBRARIAN, + TN_MOB_VILLAGER_PRIEST, + TN_MOB_VILLAGER_SMITH, + TN_MOB_VILLAGER_BUTCHER, + TN_MOB_ENDERDRAGON_ENDERCRYSTAL, + TN_MOB_ENDERDRAGON_SHUFFLE, + TN_MOB_ENDERDRAGON_BEAM, + TN_MOB_ENDERDRAGON_ENDEREYES, + TN__BLUR__MISC_GLINT, + TN_ITEM_BOOK, + TN_MISC_TUNNEL, + TN_MISC_PARTICLEFIELD, + TN_TERRAIN_MOON_PHASES, - // 1.0.1 - TN_MOB_RED_COW, - TN_MOB_SNOWMAN, - TN_MOB_ENDERDRAGON, - TN_MOB_BLAZE, - TN_MOB_LAVA, - TN_MOB_VILLAGER_VILLAGER, - TN_MOB_VILLAGER_FARMER, - TN_MOB_VILLAGER_LIBRARIAN, - TN_MOB_VILLAGER_PRIEST, - TN_MOB_VILLAGER_SMITH, - TN_MOB_VILLAGER_BUTCHER, - TN_MOB_ENDERDRAGON_ENDERCRYSTAL, - TN_MOB_ENDERDRAGON_SHUFFLE, - TN_MOB_ENDERDRAGON_BEAM, - TN_MOB_ENDERDRAGON_ENDEREYES, - TN__BLUR__MISC_GLINT, - TN_ITEM_BOOK, - TN_MISC_TUNNEL, - TN_MISC_PARTICLEFIELD, - TN_TERRAIN_MOON_PHASES, + // 1.2.3 + TN_MOB_OZELOT, + TN_MOB_CAT_BLACK, + TN_MOB_CAT_RED, + TN_MOB_CAT_SIAMESE, + TN_MOB_VILLAGER_GOLEM, + TN_MOB_WITHER_SKELETON, - // 1.2.3 - TN_MOB_OZELOT, - TN_MOB_CAT_BLACK, - TN_MOB_CAT_RED, - TN_MOB_CAT_SIAMESE, - TN_MOB_VILLAGER_GOLEM, - TN_MOB_WITHER_SKELETON, - - // TU14 - TN_MOB_WOLF_COLLAR, - TN_MOB_ZOMBIE_VILLAGER, + // TU14 + TN_MOB_WOLF_COLLAR, + TN_MOB_ZOMBIE_VILLAGER, #ifdef _LARGE_WORLDS - TN_MISC_ADDITIONALMAPICONS, + TN_MISC_ADDITIONALMAPICONS, #endif - TN_DEFAULT_FONT, - TN_ALT_FONT, + TN_DEFAULT_FONT, + TN_ALT_FONT, -/* TN_SP1, - TN_SP2, - TN_SP3, - TN_SPF, - TN_THST, - TN_THIR, - TN_THGO, - TN_THDI, - TN_GPAN, - TN_GPCO, - TN_GPEN, - TN_GPFO, - TN_GPTO, - TN_GPBA, - TN_GPFA, - TN_GPME, - TN_GPMF, - TN_GPMM, - TN_GPSE, - TN_AH_0006, - TN_AH_0003, - TN_AH_0007, - TN_AH_0005, - TN_AH_0004, - TN_AH_0001, - TN_AH_0002, - TN_AT_0001, - TN_AT_0002, - TN_AT_0003, - TN_AT_0004, - TN_AT_0005, - TN_AT_0006, - TN_AT_0007, - TN_AT_0008, - TN_AT_0009, - TN_AT_0010, - TN_AT_0011, - TN_AT_0012, - TN_AP_0001, - TN_AP_0002, - TN_AP_0003, - TN_AP_0004, - TN_AP_0005, - TN_AP_0006, - TN_AP_0007, - TN_AP_0009, - TN_AP_0010, - TN_AP_0011, - TN_AP_0012, - TN_AP_0013, - TN_AP_0014, - TN_AP_0015, - TN_AP_0016, - TN_AP_0017, - TN_AP_0018, - TN_AA_0001, - TN_AT_0013, - TN_AT_0014, - TN_AT_0015, - TN_AT_0016, - TN_AT_0017, - TN_AT_0018, - TN_AP_0019, - TN_AP_0020, - TN_AP_0021, - TN_AP_0022, - TN_AP_0023, - TN_AH_0008, - TN_AH_0009,*/ + /* TN_SP1, + TN_SP2, + TN_SP3, + TN_SPF, + TN_THST, + TN_THIR, + TN_THGO, + TN_THDI, + TN_GPAN, + TN_GPCO, + TN_GPEN, + TN_GPFO, + TN_GPTO, + TN_GPBA, + TN_GPFA, + TN_GPME, + TN_GPMF, + TN_GPMM, + TN_GPSE, + TN_AH_0006, + TN_AH_0003, + TN_AH_0007, + TN_AH_0005, + TN_AH_0004, + TN_AH_0001, + TN_AH_0002, + TN_AT_0001, + TN_AT_0002, + TN_AT_0003, + TN_AT_0004, + TN_AT_0005, + TN_AT_0006, + TN_AT_0007, + TN_AT_0008, + TN_AT_0009, + TN_AT_0010, + TN_AT_0011, + TN_AT_0012, + TN_AP_0001, + TN_AP_0002, + TN_AP_0003, + TN_AP_0004, + TN_AP_0005, + TN_AP_0006, + TN_AP_0007, + TN_AP_0009, + TN_AP_0010, + TN_AP_0011, + TN_AP_0012, + TN_AP_0013, + TN_AP_0014, + TN_AP_0015, + TN_AP_0016, + TN_AP_0017, + TN_AP_0018, + TN_AA_0001, + TN_AT_0013, + TN_AT_0014, + TN_AT_0015, + TN_AT_0016, + TN_AT_0017, + TN_AT_0018, + TN_AP_0019, + TN_AP_0020, + TN_AP_0021, + TN_AP_0022, + TN_AP_0023, + TN_AH_0008, + TN_AH_0009,*/ - TN_GUI_ITEMS, - TN_TERRAIN, + TN_GUI_ITEMS, + TN_TERRAIN, - TN_COUNT, - -} -TEXTURE_NAME; + TN_COUNT, -class Textures -{ +} TEXTURE_NAME; + +class Textures { public: - static bool MIPMAP; - static C4JRender::eTextureFormat TEXTURE_FORMAT; + static bool MIPMAP; + static C4JRender::eTextureFormat TEXTURE_FORMAT; private: - static const wchar_t *preLoaded[TN_COUNT]; - static int preLoadedIdx[TN_COUNT]; + static const wchar_t* preLoaded[TN_COUNT]; + static int preLoadedIdx[TN_COUNT]; - std::unordered_map idMap; + std::unordered_map idMap; std::unordered_map pixelsMap; - std::unordered_map loadedImages; - //IntBuffer *pixels; // 4J - removed so we don't have a permanent buffer kicking round using up 1MB + std::unordered_map loadedImages; + // IntBuffer *pixels; // 4J - removed so we don't have a permanent + // buffer kicking round using up 1MB - std::unordered_map httpTextures; - // 4J-PB - Added for GTS textures - std::unordered_map memTextures; - Options *options; + std::unordered_map httpTextures; + // 4J-PB - Added for GTS textures + std::unordered_map memTextures; + Options* options; private: - TexturePackRepository *skins; - BufferedImage *missingNo; - PreStitchedTextureMap *terrain; - PreStitchedTextureMap *items; + TexturePackRepository* skins; + BufferedImage* missingNo; + PreStitchedTextureMap* terrain; + PreStitchedTextureMap* items; + + int lastBoundId; - int lastBoundId; public: - Textures(TexturePackRepository *skins, Options *options); + Textures(TexturePackRepository* skins, Options* options); private: - void loadIndexedTextures(); // 4J Added + void loadIndexedTextures(); // 4J Added public: - intArray loadTexturePixels(TEXTURE_NAME texId, const std::wstring& resourceName); -private: - intArray loadTexturePixels(BufferedImage *img); - intArray loadTexturePixels(BufferedImage *img, intArray pixels); - void setTextureFormat(const std::wstring& resourceName); // 4J added - -public: - void bindTexture(const std::wstring &resourceName); - void bindTexture(int resourceId); // 4J Added - - // 4J Made public for use in XUI controls - void bind(int id); - -public: - void clearLastBoundId(); + intArray loadTexturePixels(TEXTURE_NAME texId, + const std::wstring& resourceName); private: - int loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName); + intArray loadTexturePixels(BufferedImage* img); + intArray loadTexturePixels(BufferedImage* img, intArray pixels); + void setTextureFormat(const std::wstring& resourceName); // 4J added + public: - int loadTexture(int idx); // 4J added - int getTexture(BufferedImage *img, C4JRender::eTextureFormat format = C4JRender::TEXTURE_FORMAT_RxGyBzAw, bool mipmap = true); - void loadTexture(BufferedImage *img, int id); - void loadTexture(BufferedImage *img, int id, bool blur, bool clamp); + void bindTexture(const std::wstring& resourceName); + void bindTexture(int resourceId); // 4J Added + + // 4J Made public for use in XUI controls + void bind(int id); + +public: + void clearLastBoundId(); + private: - intArray anaglyph(intArray rawPixels); + int loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName); + +public: + int loadTexture(int idx); // 4J added + int getTexture( + BufferedImage* img, + C4JRender::eTextureFormat format = C4JRender::TEXTURE_FORMAT_RxGyBzAw, + bool mipmap = true); + void loadTexture(BufferedImage* img, int id); + void loadTexture(BufferedImage* img, int id, bool blur, bool clamp); + +private: + intArray anaglyph(intArray rawPixels); + public: void replaceTexture(intArray rawPixels, int w, int h, int id); - void replaceTextureDirect(intArray rawPixels, int w, int h, int id); // 4J added as optimisation - void replaceTextureDirect(shortArray rawPixels, int w, int h, int id); // 4J added as optimisation - void releaseTexture(int id); + void replaceTextureDirect(intArray rawPixels, int w, int h, + int id); // 4J added as optimisation + void replaceTextureDirect(shortArray rawPixels, int w, int h, + int id); // 4J added as optimisation + void releaseTexture(int id); int loadHttpTexture(const std::wstring& url, const std::wstring& backup); - int loadHttpTexture(const std::wstring& url, int backup); // 4J added - bool hasHttpTexture(const std::wstring &url); - HttpTexture *addHttpTexture(const std::wstring& url, HttpTextureProcessor *processor); + int loadHttpTexture(const std::wstring& url, int backup); // 4J added + bool hasHttpTexture(const std::wstring& url); + HttpTexture* addHttpTexture(const std::wstring& url, + HttpTextureProcessor* processor); void removeHttpTexture(const std::wstring& url); - // 4J-PB - for the GTS textures - int loadMemTexture(const std::wstring& url, const std::wstring& backup); - int loadMemTexture(const std::wstring& url, int backup); - MemTexture * addMemTexture(const std::wstring& url, MemTextureProcessor *processor); - //MemTexture * getMemTexture(const std::wstring& url, MemTextureProcessor *processor); - void removeMemTexture(const std::wstring& url); + // 4J-PB - for the GTS textures + int loadMemTexture(const std::wstring& url, const std::wstring& backup); + int loadMemTexture(const std::wstring& url, int backup); + MemTexture* addMemTexture(const std::wstring& url, + MemTextureProcessor* processor); + // MemTexture * getMemTexture(const std::wstring& url, + // MemTextureProcessor *processor); + void removeMemTexture(const std::wstring& url); - void tick(bool updateTextures, bool tickDynamics = true); // 4J added updateTextures parameter & tickDynamics + void tick(bool updateTextures, + bool tickDynamics = + true); // 4J added updateTextures parameter & tickDynamics public: - void reloadAll(); - void stitch(); - Icon *getMissingIcon(int type); - BufferedImage *readImage(TEXTURE_NAME texId, const std::wstring& name); // Moved this to public for Font.cpp access - // check list of title update textures to see if we need to use the UPDATE: drive - static bool IsTUImage(TEXTURE_NAME texId, const std::wstring& name); - static bool IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name); + void reloadAll(); + void stitch(); + Icon* getMissingIcon(int type); + BufferedImage* readImage( + TEXTURE_NAME texId, + const std::wstring& name); // Moved this to public for Font.cpp access + // check list of title update textures to see if we need to use the UPDATE: + // drive + static bool IsTUImage(TEXTURE_NAME texId, const std::wstring& name); + static bool IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name); }; diff --git a/Minecraft.Client/UI/Button.cpp b/Minecraft.Client/UI/Button.cpp index d3cfe3e3b..09630ed6b 100644 --- a/Minecraft.Client/UI/Button.cpp +++ b/Minecraft.Client/UI/Button.cpp @@ -2,23 +2,20 @@ #include "Button.h" #include "../Textures/Textures.h" -Button::Button(int id, int x, int y, const std::wstring& msg) -{ - init(id, x, y, 200, 20, msg); +Button::Button(int id, int x, int y, const std::wstring& msg) { + init(id, x, y, 200, 20, msg); } -Button::Button(int id, int x, int y, int w, int h, const std::wstring& msg) -{ - init(id, x, y, w, h, msg); +Button::Button(int id, int x, int y, int w, int h, const std::wstring& msg) { + init(id, x, y, w, h, msg); } // 4J - added -void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) -{ - active = true; - visible = true; +void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) { + active = true; + visible = true; - // this bit of code from original ctor + // this bit of code from original ctor this->id = id; this->x = x; this->y = y; @@ -27,24 +24,24 @@ void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) this->msg = msg; } -int Button::getYImage(bool hovered) -{ +int Button::getYImage(bool hovered) { int res = 1; - if (!active) res = 0; - else if (hovered) res = 2; + if (!active) + res = 0; + else if (hovered) + res = 2; return res; } -void Button::render(Minecraft *minecraft, int xm, int ym) -{ +void Button::render(Minecraft* minecraft, int xm, int ym) { if (!visible) return; - Font *font = minecraft->font; + Font* font = minecraft->font; - glBindTexture(GL_TEXTURE_2D, minecraft->textures->loadTexture(TN_GUI_GUI)); // 4J was L"/gui/gui.png" + glBindTexture(GL_TEXTURE_2D, minecraft->textures->loadTexture( + TN_GUI_GUI)); // 4J was L"/gui/gui.png" glColor4f(1, 1, 1, 1); - bool hovered = xm >= x && ym >= y && xm < x + w && ym < y + h; int yImage = getYImage(hovered); @@ -53,33 +50,21 @@ void Button::render(Minecraft *minecraft, int xm, int ym) renderBg(minecraft, xm, ym); - if (!active) - { + if (!active) { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xffa0a0a0); - } - else - { - if (hovered) - { + } else { + if (hovered) { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xffffa0); - } - else - { + } else { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xe0e0e0); } } - } -void Button::renderBg(Minecraft *minecraft, int xm, int ym) -{ -} +void Button::renderBg(Minecraft* minecraft, int xm, int ym) {} -void Button::released(int mx, int my) -{ -} +void Button::released(int mx, int my) {} -bool Button::clicked(Minecraft *minecraft, int mx, int my) -{ - return active && mx >= x && my >= y && mx < x + w && my < y + h; +bool Button::clicked(Minecraft* minecraft, int mx, int my) { + return active && mx >= x && my >= y && mx < x + w && my < y + h; } \ No newline at end of file diff --git a/Minecraft.Client/UI/Button.h b/Minecraft.Client/UI/Button.h index aac43cda4..529ab0902 100644 --- a/Minecraft.Client/UI/Button.h +++ b/Minecraft.Client/UI/Button.h @@ -1,14 +1,13 @@ #pragma once #include "GuiComponent.h" - -class Button : public GuiComponent -{ +class Button : public GuiComponent { protected: - int w; + int w; int h; + public: - int x, y; + int x, y; std::wstring msg; int id; bool active; @@ -16,15 +15,18 @@ public: Button(int id, int x, int y, const std::wstring& msg); Button(int id, int x, int y, int w, int h, const std::wstring& msg); - void init(int id, int x, int y, int w, int h, const std::wstring& msg); // 4J - added + void init(int id, int x, int y, int w, int h, + const std::wstring& msg); // 4J - added protected: - virtual int getYImage(bool hovered); + virtual int getYImage(bool hovered); + public: - virtual void render(Minecraft *minecraft, int xm, int ym); + virtual void render(Minecraft* minecraft, int xm, int ym); protected: - virtual void renderBg(Minecraft *minecraft, int xm, int ym); + virtual void renderBg(Minecraft* minecraft, int xm, int ym); + public: - virtual void released(int mx, int my); - virtual bool clicked(Minecraft *minecraft, int mx, int my); + virtual void released(int mx, int my); + virtual bool clicked(Minecraft* minecraft, int mx, int my); }; diff --git a/Minecraft.Client/UI/EditBox.cpp b/Minecraft.Client/UI/EditBox.cpp index 0a0e9550e..2ce3d3224 100644 --- a/Minecraft.Client/UI/EditBox.cpp +++ b/Minecraft.Client/UI/EditBox.cpp @@ -2,109 +2,84 @@ #include "EditBox.h" #include "../../Minecraft.World/Util/SharedConstants.h" -EditBox::EditBox(Screen *screen, Font *font, int x, int y, int width, int height, const std::wstring& value) -{ - // 4J - added initialisers - maxLength = 0; - frame = 0; +EditBox::EditBox(Screen* screen, Font* font, int x, int y, int width, + int height, const std::wstring& value) { + // 4J - added initialisers + maxLength = 0; + frame = 0; - this->screen = screen; - this->font = font; - this->x = x; - this->y = y; - this->width = width; - this->height = height; - this->setValue(value); + this->screen = screen; + this->font = font; + this->x = x; + this->y = y; + this->width = width; + this->height = height; + this->setValue(value); } -void EditBox::setValue(const std::wstring& value) -{ - this->value = value; -} +void EditBox::setValue(const std::wstring& value) { this->value = value; } -std::wstring EditBox::getValue() -{ - return value; -} +std::wstring EditBox::getValue() { return value; } -void EditBox::tick() -{ - frame++; -} +void EditBox::tick() { frame++; } -void EditBox::keyPressed(wchar_t ch, int eventKey) -{ +void EditBox::keyPressed(wchar_t ch, int eventKey) { if (!active || !inFocus) { return; } - - if (ch == 9) - { + if (ch == 9) { screen->tabPressed(); } -/* 4J removed - if (ch == 22) - { - String msg = Screen.getClipboard(); - if (msg == null) msg = ""; - int toAdd = 32 - value.length(); - if (toAdd > msg.length()) toAdd = msg.length(); - if (toAdd > 0) { - value += msg.substring(0, toAdd); + /* 4J removed + if (ch == 22) + { + String msg = Screen.getClipboard(); + if (msg == null) msg = ""; + int toAdd = 32 - value.length(); + if (toAdd > msg.length()) toAdd = msg.length(); + if (toAdd > 0) { + value += msg.substring(0, toAdd); + } } - } - */ + */ - if (eventKey == Keyboard::KEY_BACK && value.length() > 0) - { + if (eventKey == Keyboard::KEY_BACK && value.length() > 0) { value = value.substr(0, value.length() - 1); } - if (SharedConstants::acceptableLetters.find(ch) != std::wstring::npos && (value.length() < maxLength || maxLength == 0)) - { + if (SharedConstants::acceptableLetters.find(ch) != std::wstring::npos && + (value.length() < maxLength || maxLength == 0)) { value += ch; } - } -void EditBox::mouseClicked(int mouseX, int mouseY, int buttonNum) -{ - bool newFocus = active && (mouseX >= x && mouseX < (x + width) && mouseY >= y && mouseY < (y + height)); +void EditBox::mouseClicked(int mouseX, int mouseY, int buttonNum) { + bool newFocus = active && (mouseX >= x && mouseX < (x + width) && + mouseY >= y && mouseY < (y + height)); focus(newFocus); } -void EditBox::focus(bool newFocus) -{ - if (newFocus && !inFocus) - { +void EditBox::focus(bool newFocus) { + if (newFocus && !inFocus) { // reset the underscore counter to give quicker selection feedback frame = 0; } inFocus = newFocus; } -void EditBox::render() -{ +void EditBox::render() { fill(x - 1, y - 1, x + width + 1, y + height + 1, 0xffa0a0a0); fill(x, y, x + width, y + height, 0xff000000); - if (active) - { + if (active) { bool renderUnderscore = inFocus && (frame / 6 % 2 == 0); - drawString(font, value + (renderUnderscore ? L"_" : L""), x + 4, y + (height - 8) / 2, 0xe0e0e0); - } - else - { + drawString(font, value + (renderUnderscore ? L"_" : L""), x + 4, + y + (height - 8) / 2, 0xe0e0e0); + } else { drawString(font, value, x + 4, y + (height - 8) / 2, 0x707070); } } -void EditBox::setMaxLength(int maxLength) -{ - this->maxLength = maxLength; -} +void EditBox::setMaxLength(int maxLength) { this->maxLength = maxLength; } -int EditBox::getMaxLength() -{ - return maxLength; -} \ No newline at end of file +int EditBox::getMaxLength() { return maxLength; } \ No newline at end of file diff --git a/Minecraft.Client/UI/EditBox.h b/Minecraft.Client/UI/EditBox.h index d0f2e8614..1b78d424f 100644 --- a/Minecraft.Client/UI/EditBox.h +++ b/Minecraft.Client/UI/EditBox.h @@ -4,10 +4,9 @@ class Font; class Screen; -class EditBox : public GuiComponent -{ +class EditBox : public GuiComponent { private: - Font *font; + Font* font; int x; int y; int width; @@ -17,13 +16,15 @@ private: int frame; public: - bool inFocus; + bool inFocus; bool active; + private: - Screen *screen; + Screen* screen; public: - EditBox(Screen *screen, Font *font, int x, int y, int width, int height, const std::wstring& value); + EditBox(Screen* screen, Font* font, int x, int y, int width, int height, + const std::wstring& value); void setValue(const std::wstring& value); std::wstring getValue(); void tick(); diff --git a/Minecraft.Client/UI/Font.cpp b/Minecraft.Client/UI/Font.cpp index 096e548a3..4ea8f151b 100644 --- a/Minecraft.Client/UI/Font.cpp +++ b/Minecraft.Client/UI/Font.cpp @@ -8,71 +8,69 @@ #include "../../Minecraft.World/Util/StringHelpers.h" #include "../../Minecraft.World/Util/Random.h" -Font::Font(Options *options, const std::wstring& name, Textures* textures, bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[]/* = nullptr */) : textures(textures) -{ - int charC = cols * rows; // Number of characters in the font +Font::Font(Options* options, const std::wstring& name, Textures* textures, + bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, + int charWidth, int charHeight, + unsigned short charMap[] /* = nullptr */) + : textures(textures) { + int charC = cols * rows; // Number of characters in the font - charWidths = new int[charC]; + charWidths = new int[charC]; - // 4J - added initialisers - memset(charWidths, 0, charC); + // 4J - added initialisers + memset(charWidths, 0, charC); - enforceUnicodeSheet = false; - bidirectional = false; - xPos = yPos = 0.0f; + enforceUnicodeSheet = false; + bidirectional = false; + xPos = yPos = 0.0f; - // Set up member variables - m_cols = cols; - m_rows = rows; - m_charWidth = charWidth; - m_charHeight = charHeight; - m_textureName = textureName; + // Set up member variables + m_cols = cols; + m_rows = rows; + m_charWidth = charWidth; + m_charHeight = charHeight; + m_textureName = textureName; - // Build character map - if (charMap != NULL) - { - for(int i = 0; i < charC; i++) - { - m_charMap.insert(std::make_pair(charMap[i], i)); - } - } - - random = new Random(); - - // Load the image - BufferedImage *img = textures->readImage(m_textureName, name); - - /* - 4J - TODO - try { - img = ImageIO.read(Textures.class.getResourceAsStream(name)); - } catch (IOException e) { - throw new RuntimeException(e); + // Build character map + if (charMap != NULL) { + for (int i = 0; i < charC; i++) { + m_charMap.insert(std::make_pair(charMap[i], i)); + } } - */ + + random = new Random(); + + // Load the image + BufferedImage* img = textures->readImage(m_textureName, name); + + /* - 4J - TODO + try { + img = ImageIO.read(Textures.class.getResourceAsStream(name)); +} catch (IOException e) { + throw new RuntimeException(e); +} + */ int w = img->getWidth(); int h = img->getHeight(); intArray rawPixels(w * h); img->getRGB(0, 0, w, h, rawPixels, 0, w); - for (int i = 0; i < charC; i++) - { + for (int i = 0; i < charC; i++) { int xt = i % m_cols; int yt = i / m_cols; - + int x = 7; - for (; x >= 0; x--) - { + for (; x >= 0; x--) { int xPixel = xt * 8 + x; bool emptyColumn = true; - for (int y = 0; y < 8 && emptyColumn; y++) - { + for (int y = 0; y < 8 && emptyColumn; y++) { int yPixel = (yt * 8 + y) * w; - bool emptyPixel = (rawPixels[xPixel + yPixel] >> 24) == 0; // Check the alpha value - if (!emptyPixel) emptyColumn = false; + bool emptyPixel = (rawPixels[xPixel + yPixel] >> 24) == + 0; // Check the alpha value + if (!emptyPixel) emptyColumn = false; } - if (!emptyColumn) - { + if (!emptyColumn) { break; } } @@ -81,369 +79,326 @@ Font::Font(Options *options, const std::wstring& name, Textures* textures, bool charWidths[i] = x + 2; } - delete img; + delete img; - // calculate colors - for (int colorN = 0; colorN < 32; ++colorN) - { - int var10 = (colorN >> 3 & 1) * 85; - int red = (colorN >> 2 & 1) * 170 + var10; - int green = (colorN >> 1 & 1) * 170 + var10; - int blue = (colorN >> 0 & 1) * 170 + var10; + // calculate colors + for (int colorN = 0; colorN < 32; ++colorN) { + int var10 = (colorN >> 3 & 1) * 85; + int red = (colorN >> 2 & 1) * 170 + var10; + int green = (colorN >> 1 & 1) * 170 + var10; + int blue = (colorN >> 0 & 1) * 170 + var10; - if (colorN == 6) - { - red += 85; - } + if (colorN == 6) { + red += 85; + } - if (options->anaglyph3d) - { - int tmpRed = (red * 30 + green * 59 + blue * 11) / 100; - int tmpGreen = (red * 30 + green * 70) / 100; - int tmpBlue = (red * 30 + blue * 70) / 100; - red = tmpRed; - green = tmpGreen; - blue = tmpBlue; - } + if (options->anaglyph3d) { + int tmpRed = (red * 30 + green * 59 + blue * 11) / 100; + int tmpGreen = (red * 30 + green * 70) / 100; + int tmpBlue = (red * 30 + blue * 70) / 100; + red = tmpRed; + green = tmpGreen; + blue = tmpBlue; + } - if (colorN >= 16) - { - red /= 4; - green /= 4; - blue /= 4; - } + if (colorN >= 16) { + red /= 4; + green /= 4; + blue /= 4; + } - colors[colorN] = (red & 255) << 16 | (green & 255) << 8 | (blue & 255); - } + colors[colorN] = (red & 255) << 16 | (green & 255) << 8 | (blue & 255); + } } #ifndef _XBOX -// 4J Stu - This dtor clashes with one in xui! We never delete these anyway so take it out for now. Can go back when we have got rid of XUI -Font::~Font() -{ - delete[] charWidths; -} +// 4J Stu - This dtor clashes with one in xui! We never delete these anyway so +// take it out for now. Can go back when we have got rid of XUI +Font::~Font() { delete[] charWidths; } #endif -void Font::renderCharacter(wchar_t c) -{ - float xOff = c % m_cols * m_charWidth; - float yOff = c / m_cols * m_charWidth; +void Font::renderCharacter(wchar_t c) { + float xOff = c % m_cols * m_charWidth; + float yOff = c / m_cols * m_charWidth; - float width = charWidths[c] - .01f; - float height = m_charHeight - .01f; - - float fontWidth = m_cols * m_charWidth; - float fontHeight = m_rows * m_charHeight; + float width = charWidths[c] - .01f; + float height = m_charHeight - .01f; - Tesselator *t = Tesselator::getInstance(); - // 4J Stu - Changed to a quad so that we can use within a command buffer + float fontWidth = m_cols * m_charWidth; + float fontHeight = m_rows * m_charHeight; + + Tesselator* t = Tesselator::getInstance(); + // 4J Stu - Changed to a quad so that we can use within a command buffer #if 1 - t->begin(); - t->tex(xOff / fontWidth, (yOff + 7.99f) / fontHeight); - t->vertex(xPos, yPos + height, 0.0f); + t->begin(); + t->tex(xOff / fontWidth, (yOff + 7.99f) / fontHeight); + t->vertex(xPos, yPos + height, 0.0f); - t->tex((xOff + width) / fontWidth, (yOff + 7.99f) / fontHeight); - t->vertex(xPos + width, yPos + height, 0.0f); + t->tex((xOff + width) / fontWidth, (yOff + 7.99f) / fontHeight); + t->vertex(xPos + width, yPos + height, 0.0f); - t->tex((xOff + width) / fontWidth, yOff / fontHeight); - t->vertex(xPos + width, yPos, 0.0f); + t->tex((xOff + width) / fontWidth, yOff / fontHeight); + t->vertex(xPos + width, yPos, 0.0f); - t->tex(xOff / fontWidth, yOff / fontHeight); - t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / fontWidth, yOff / fontHeight); + t->vertex(xPos, yPos, 0.0f); - t->end(); + t->end(); #else - t->begin(GL_TRIANGLE_STRIP); - t->tex(xOff / 128.0F, yOff / 128.0F); - t->vertex(xPos, yPos, 0.0f); - t->tex(xOff / 128.0F, (yOff + 7.99f) / 128.0F); - t->vertex(xPos, yPos + 7.99f, 0.0f); - t->tex((xOff + width) / 128.0F, yOff / 128.0F); - t->vertex(xPos + width, yPos, 0.0f); - t->tex((xOff + width) / 128.0F, (yOff + 7.99f) / 128.0F); - t->vertex(xPos + width, yPos + 7.99f, 0.0f); - t->end(); + t->begin(GL_TRIANGLE_STRIP); + t->tex(xOff / 128.0F, yOff / 128.0F); + t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / 128.0F, (yOff + 7.99f) / 128.0F); + t->vertex(xPos, yPos + 7.99f, 0.0f); + t->tex((xOff + width) / 128.0F, yOff / 128.0F); + t->vertex(xPos + width, yPos, 0.0f); + t->tex((xOff + width) / 128.0F, (yOff + 7.99f) / 128.0F); + t->vertex(xPos + width, yPos + 7.99f, 0.0f); + t->end(); #endif - xPos += (float) charWidths[c]; + xPos += (float)charWidths[c]; } -void Font::drawShadow(const std::wstring& str, int x, int y, int color) -{ +void Font::drawShadow(const std::wstring& str, int x, int y, int color) { draw(str, x + 1, y + 1, color, true); draw(str, x, y, color, false); } -void Font::drawShadowWordWrap(const std::wstring &str, int x, int y, int w, int color, int h) -{ - drawWordWrapInternal(str, x + 1, y + 1, w, color, true, h); - drawWordWrapInternal(str, x, y, w, color, h); +void Font::drawShadowWordWrap(const std::wstring& str, int x, int y, int w, + int color, int h) { + drawWordWrapInternal(str, x + 1, y + 1, w, color, true, h); + drawWordWrapInternal(str, x, y, w, color, h); } -void Font::draw(const std::wstring& str, int x, int y, int color) -{ - draw(str, x, y, color, false); +void Font::draw(const std::wstring& str, int x, int y, int color) { + draw(str, x, y, color, false); } -std::wstring Font::reorderBidi(const std::wstring &str) -{ - // 4J Not implemented - return str; +std::wstring Font::reorderBidi(const std::wstring& str) { + // 4J Not implemented + return str; } -void Font::draw(const std::wstring &str, bool dropShadow) -{ - // Bind the texture - textures->bindTexture(m_textureName); +void Font::draw(const std::wstring& str, bool dropShadow) { + // Bind the texture + textures->bindTexture(m_textureName); - bool noise = false; - std::wstring cleanStr = sanitize(str); + bool noise = false; + std::wstring cleanStr = sanitize(str); - for (int i = 0; i < (int)cleanStr.length(); ++i) - { - // Map character - wchar_t c = cleanStr.at(i); + for (int i = 0; i < (int)cleanStr.length(); ++i) { + // Map character + wchar_t c = cleanStr.at(i); - if (c == 167 && i + 1 < cleanStr.length()) - { - // 4J - following block was: - // int colorN = L"0123456789abcdefk".indexOf(str.toLowerCase().charAt(i + 1)); - wchar_t ca = cleanStr[i+1]; - int colorN = 16; - if(( ca >= L'0' ) && (ca <= L'9')) colorN = ca - L'0'; - else if(( ca >= L'a' ) && (ca <= L'f')) colorN = (ca - L'a') + 10; - else if(( ca >= L'A' ) && (ca <= L'F')) colorN = (ca - L'A') + 10; + if (c == 167 && i + 1 < cleanStr.length()) { + // 4J - following block was: + // int colorN = + // L"0123456789abcdefk".indexOf(str.toLowerCase().charAt(i + 1)); + wchar_t ca = cleanStr[i + 1]; + int colorN = 16; + if ((ca >= L'0') && (ca <= L'9')) + colorN = ca - L'0'; + else if ((ca >= L'a') && (ca <= L'f')) + colorN = (ca - L'a') + 10; + else if ((ca >= L'A') && (ca <= L'F')) + colorN = (ca - L'A') + 10; - if (colorN == 16) - { - noise = true; - } - else - { - noise = false; - if (colorN < 0 || colorN > 15) colorN = 15; + if (colorN == 16) { + noise = true; + } else { + noise = false; + if (colorN < 0 || colorN > 15) colorN = 15; - if (dropShadow) colorN += 16; + if (dropShadow) colorN += 16; - int color = colors[colorN]; - glColor3f((color >> 16) / 255.0F, ((color >> 8) & 255) / 255.0F, (color & 255) / 255.0F); - } + int color = colors[colorN]; + glColor3f((color >> 16) / 255.0F, ((color >> 8) & 255) / 255.0F, + (color & 255) / 255.0F); + } + i += 1; + continue; + } - i += 1; - continue; - } - - // "noise" for crazy splash screen message - if (noise) - { - int newc; - do - { - newc = random->nextInt(SharedConstants::acceptableLetters.length()); - } while (charWidths[c + 32] != charWidths[newc + 32]); - c = newc; - } + // "noise" for crazy splash screen message + if (noise) { + int newc; + do { + newc = random->nextInt( + SharedConstants::acceptableLetters.length()); + } while (charWidths[c + 32] != charWidths[newc + 32]); + c = newc; + } - renderCharacter(c); - } + renderCharacter(c); + } } -void Font::draw(const std::wstring& str, int x, int y, int color, bool dropShadow) -{ - if (!str.empty()) - { - if ((color & 0xFC000000) == 0) color |= 0xFF000000; // force alpha - // if not set +void Font::draw(const std::wstring& str, int x, int y, int color, + bool dropShadow) { + if (!str.empty()) { + if ((color & 0xFC000000) == 0) color |= 0xFF000000; // force alpha + // if not set - if (dropShadow) // divide RGB by 4, preserve alpha - // 4jcraft changed -1 << 24 to the value of 1 (0xFF FF FF FF) - color = (color & 0xfcfcfc) >> 2 | (color & (0xFFFFFFFF << 24)); + if (dropShadow) // divide RGB by 4, preserve alpha + // 4jcraft changed -1 << 24 to the value of 1 (0xFF FF + // FF FF) + color = (color & 0xfcfcfc) >> 2 | (color & (0xFFFFFFFF << 24)); - glColor4f((color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, (color & 255) / 255.0F, (color >> 24 & 255) / 255.0F); + glColor4f((color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, + (color & 255) / 255.0F, (color >> 24 & 255) / 255.0F); - xPos = x; - yPos = y; - draw(str, dropShadow); - } + xPos = x; + yPos = y; + draw(str, dropShadow); + } } -int Font::width(const std::wstring& str) -{ - std::wstring cleanStr = sanitize(str); +int Font::width(const std::wstring& str) { + std::wstring cleanStr = sanitize(str); - if (cleanStr == L"") return 0; // 4J - was NULL comparison - int len = 0; + if (cleanStr == L"") return 0; // 4J - was NULL comparison + int len = 0; - for (int i = 0; i < cleanStr.length(); ++i) - { - wchar_t c = cleanStr.at(i); + for (int i = 0; i < cleanStr.length(); ++i) { + wchar_t c = cleanStr.at(i); - if(c == 167) - { - // Ignore the character used to define coloured text - ++i; - } - else - { - len += charWidths[c]; - } - } + if (c == 167) { + // Ignore the character used to define coloured text + ++i; + } else { + len += charWidths[c]; + } + } - return len; + return len; } -std::wstring Font::sanitize(const std::wstring& str) -{ - std::wstring sb = str; +std::wstring Font::sanitize(const std::wstring& str) { + std::wstring sb = str; - for (unsigned int i = 0; i < sb.length(); i++) - { - if (CharacterExists(sb[i])) - { - sb[i] = MapCharacter(sb[i]); - } - else - { - // If this character isn't supported, just show the first character (empty square box character) - sb[i] = 0; - } + for (unsigned int i = 0; i < sb.length(); i++) { + if (CharacterExists(sb[i])) { + sb[i] = MapCharacter(sb[i]); + } else { + // If this character isn't supported, just show the first character + // (empty square box character) + sb[i] = 0; + } } return sb; } -int Font::MapCharacter(wchar_t c) -{ - if (!m_charMap.empty()) - { - // Don't map space character - return c == ' ' ? c : m_charMap[c]; - } - else - { - return c; - } +int Font::MapCharacter(wchar_t c) { + if (!m_charMap.empty()) { + // Don't map space character + return c == ' ' ? c : m_charMap[c]; + } else { + return c; + } } -bool Font::CharacterExists(wchar_t c) -{ - if (!m_charMap.empty()) - { - return m_charMap.find(c) != m_charMap.end(); - } - else - { - return c >= 0 && c <= m_rows*m_cols; - } +bool Font::CharacterExists(wchar_t c) { + if (!m_charMap.empty()) { + return m_charMap.find(c) != m_charMap.end(); + } else { + return c >= 0 && c <= m_rows * m_cols; + } } -void Font::drawWordWrap(const std::wstring &string, int x, int y, int w, int col, int h) -{ - //if (bidirectional) - //{ - // string = reorderBidi(string); - //} - drawWordWrapInternal(string, x, y, w, col, h); +void Font::drawWordWrap(const std::wstring& string, int x, int y, int w, + int col, int h) { + // if (bidirectional) + //{ + // string = reorderBidi(string); + // } + drawWordWrapInternal(string, x, y, w, col, h); } -void Font::drawWordWrapInternal(const std::wstring &string, int x, int y, int w, int col, int h) -{ - drawWordWrapInternal(string, x, y, w, col, false, h); +void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, int h) { + drawWordWrapInternal(string, x, y, w, col, false, h); } -void Font::drawWordWrap(const std::wstring &string, int x, int y, int w, int col, bool darken, int h) -{ - //if (bidirectional) - //{ - // string = reorderBidi(string); - //} - drawWordWrapInternal(string, x, y, w, col, darken, h); +void Font::drawWordWrap(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h) { + // if (bidirectional) + //{ + // string = reorderBidi(string); + // } + drawWordWrapInternal(string, x, y, w, col, darken, h); } -void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, int col, bool darken, int h) -{ - std::vectorlines = stringSplit(string,L'\n'); - if (lines.size() > 1) - { - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if( (y + this->wordWrapHeight(*it, w)) > h) break; +void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h) { + std::vector lines = stringSplit(string, L'\n'); + if (lines.size() > 1) { + AUTO_VAR(itEnd, lines.end()); + for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) { + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if ((y + this->wordWrapHeight(*it, w)) > h) break; drawWordWrapInternal(*it, x, y, w, col, h); y += this->wordWrapHeight(*it, w); } return; } - std::vector words = stringSplit(string,L' '); + std::vector words = stringSplit(string, L' '); unsigned int pos = 0; - while (pos < words.size()) - { + while (pos < words.size()) { std::wstring line = words[pos++] + L" "; - while (pos < words.size() && width(line + words[pos]) < w) - { + while (pos < words.size() && width(line + words[pos]) < w) { line += words[pos++] + L" "; } - while (width(line) > w) - { + while (width(line) > w) { int l = 0; - while (width(line.substr(0, l + 1)) <= w) - { + while (width(line.substr(0, l + 1)) <= w) { l++; } - if (trimString(line.substr(0, l)).length() > 0) - { + if (trimString(line.substr(0, l)).length() > 0) { draw(line.substr(0, l), x, y, col); y += 8; } line = line.substr(l); - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if( (y + 8) > h) break; + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if ((y + 8) > h) break; } - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if (trimString(line).length() > 0 && !( (y + 8) > h) ) - { + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if (trimString(line).length() > 0 && !((y + 8) > h)) { draw(line, x, y, col); y += 8; } } - } -int Font::wordWrapHeight(const std::wstring& string, int w) -{ - std::vector lines = stringSplit(string,L'\n'); - if (lines.size() > 1) - { +int Font::wordWrapHeight(const std::wstring& string, int w) { + std::vector lines = stringSplit(string, L'\n'); + if (lines.size() > 1) { int h = 0; - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { + AUTO_VAR(itEnd, lines.end()); + for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) { h += this->wordWrapHeight(*it, w); } return h; } - std::vector words = stringSplit(string,L' '); + std::vector words = stringSplit(string, L' '); unsigned int pos = 0; int y = 0; - while (pos < words.size()) - { + while (pos < words.size()) { std::wstring line = words[pos++] + L" "; - while (pos < words.size() && width(line + words[pos]) < w) - { + while (pos < words.size() && width(line + words[pos]) < w) { line += words[pos++] + L" "; } - while (width(line) > w) - { + while (width(line) > w) { int l = 0; - while (width(line.substr(0, l + 1)) <= w) - { + while (width(line.substr(0, l + 1)) <= w) { l++; } - if (trimString(line.substr(0, l)).length() > 0) - { + if (trimString(line.substr(0, l)).length() > 0) { y += 8; } line = line.substr(l); @@ -454,164 +409,162 @@ int Font::wordWrapHeight(const std::wstring& string, int w) } if (y < 8) y += 8; return y; - } -void Font::setEnforceUnicodeSheet(bool enforceUnicodeSheet) -{ - this->enforceUnicodeSheet = enforceUnicodeSheet; +void Font::setEnforceUnicodeSheet(bool enforceUnicodeSheet) { + this->enforceUnicodeSheet = enforceUnicodeSheet; } -void Font::setBidirectional(bool bidirectional) -{ - this->bidirectional = bidirectional; +void Font::setBidirectional(bool bidirectional) { + this->bidirectional = bidirectional; } -bool Font::AllCharactersValid(const std::wstring &str) -{ - for (int i = 0; i < (int)str.length(); ++i) - { - wchar_t c = str.at(i); +bool Font::AllCharactersValid(const std::wstring& str) { + for (int i = 0; i < (int)str.length(); ++i) { + wchar_t c = str.at(i); - if (c == 167 && i + 1 < str.length()) - { - // skip special color setting - i += 1; - continue; - } + if (c == 167 && i + 1 < str.length()) { + // skip special color setting + i += 1; + continue; + } - int index = SharedConstants::acceptableLetters.find(c); + int index = SharedConstants::acceptableLetters.find(c); - if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) - { - return false; - } - } - return true; + if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) { + return false; + } + } + return true; } // Not in use -/*// 4J - this code is lifted from #if 0 section above, so that we can directly create what would have gone in each of our 256 + 32 command buffers -void Font::renderFakeCB(IntBuffer *ib) +/*// 4J - this code is lifted from #if 0 section above, so that we can directly +create what would have gone in each of our 256 + 32 command buffers void +Font::renderFakeCB(IntBuffer *ib) { Tesselator *t = Tesselator::getInstance(); - int i; + int i; - for(unsigned int j = 0; j < ib->limit(); j++) - { - int cb = ib->get(j); + for(unsigned int j = 0; j < ib->limit(); j++) + { + int cb = ib->get(j); - if( cb < 256 ) - { - i = cb; - t->begin(); - int ix = i % 16 * 8; - int iy = i / 16 * 8; - // float s = 7.99f; - float s = 7.99f; + if( cb < 256 ) + { + i = cb; + t->begin(); + int ix = i % 16 * 8; + int iy = i / 16 * 8; + // float s = 7.99f; + float s = 7.99f; - float uo = (0.0f) / 128.0f; - float vo = (0.0f) / 128.0f; + float uo = (0.0f) / 128.0f; + float vo = (0.0f) / 128.0f; - t->vertexUV((float)(0), (float)( 0 + s), (float)( 0), (float)( ix / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); - t->vertexUV((float)(0 + s), (float)( 0 + s), (float)( 0), (float)( (ix + s) / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); - t->vertexUV((float)(0 + s), (float)( 0), (float)( 0), (float)( (ix + s) / 128.0f + uo), (float)( iy / 128.0f + vo)); - t->vertexUV((float)(0), (float)( 0), (float)( 0), (float)( ix / 128.0f + uo), (float)( iy / 128.0f + vo)); - // target.colorBlit(texture, x + xo, y, color, ix, iy, - // charWidths[chars[i]], 8); - t->end(); + t->vertexUV((float)(0), (float)( 0 + s), (float)( 0), +(float)( ix / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); + t->vertexUV((float)(0 + s), (float)( 0 + s), (float)( +0), (float)( (ix + s) / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); + t->vertexUV((float)(0 + s), (float)( 0), (float)( 0), +(float)( (ix + s) / 128.0f + uo), (float)( iy / 128.0f + vo)); + t->vertexUV((float)(0), (float)( 0), (float)( 0), +(float)( ix / 128.0f + uo), (float)( iy / 128.0f + vo)); + // target.colorBlit(texture, x + xo, y, color, ix, iy, + // charWidths[chars[i]], 8); + t->end(); - glTranslatef((float)charWidths[i], 0, 0); - } - else - { - i = cb - 256; + glTranslatef((float)charWidths[i], 0, 0); + } + else + { + i = cb - 256; - int br = ((i >> 3) & 1) * 0x55; - int r = ((i >> 2) & 1) * 0xaa + br; - int g = ((i >> 1) & 1) * 0xaa + br; - int b = ((i >> 0) & 1) * 0xaa + br; - if (i == 6) - { - r += 0x55; - } - bool darken = i >= 16; + int br = ((i >> 3) & 1) * 0x55; + int r = ((i >> 2) & 1) * 0xaa + br; + int g = ((i >> 1) & 1) * 0xaa + br; + int b = ((i >> 0) & 1) * 0xaa + br; + if (i == 6) + { + r += 0x55; + } + bool darken = i >= 16; - // color = r << 16 | g << 8 | b; - if (darken) - { - r /= 4; - g /= 4; - b /= 4; - } - glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); - } - } + // color = r << 16 | g << 8 | b; + if (darken) + { + r /= 4; + g /= 4; + b /= 4; + } + glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); + } + } } void Font::loadUnicodePage(int page) { - wchar_t fileName[25]; - //String fileName = String.format("/1_2_2/font/glyph_%02X.png", page); - swprintf(fileName,25,L"/1_2_2/font/glyph_%02X.png",page); - BufferedImage *image = new BufferedImage(fileName); - //try - //{ - // image = ImageIO.read(Textures.class.getResourceAsStream(fileName.toString())); - //} - //catch (IOException e) - //{ - // throw new RuntimeException(e); - //} + wchar_t fileName[25]; + //String fileName = String.format("/1_2_2/font/glyph_%02X.png", page); + swprintf(fileName,25,L"/1_2_2/font/glyph_%02X.png",page); + BufferedImage *image = new BufferedImage(fileName); + //try + //{ + // image = +ImageIO.read(Textures.class.getResourceAsStream(fileName.toString())); + //} + //catch (IOException e) + //{ + // throw new RuntimeException(e); + //} - unicodeTexID[page] = textures->getTexture(image); - lastBoundTexture = unicodeTexID[page]; + unicodeTexID[page] = textures->getTexture(image); + lastBoundTexture = unicodeTexID[page]; } void Font::renderUnicodeCharacter(wchar_t c) { - if (unicodeWidth[c] == 0) - { - // System.out.println("no-width char " + c); - return; - } + if (unicodeWidth[c] == 0) + { + // System.out.println("no-width char " + c); + return; + } - int page = c / 256; + int page = c / 256; - if (unicodeTexID[page] == 0) loadUnicodePage(page); + if (unicodeTexID[page] == 0) loadUnicodePage(page); - if (lastBoundTexture != unicodeTexID[page]) - { - glBindTexture(GL_TEXTURE_2D, unicodeTexID[page]); - lastBoundTexture = unicodeTexID[page]; - } + if (lastBoundTexture != unicodeTexID[page]) + { + glBindTexture(GL_TEXTURE_2D, unicodeTexID[page]); + lastBoundTexture = unicodeTexID[page]; + } - // first column with non-trans pixels - int firstLeft = unicodeWidth[c] >> 4; - // last column with non-trans pixels - int firstRight = unicodeWidth[c] & 0xF; + // first column with non-trans pixels + int firstLeft = unicodeWidth[c] >> 4; + // last column with non-trans pixels + int firstRight = unicodeWidth[c] & 0xF; - float left = firstLeft; - float right = firstRight + 1; + float left = firstLeft; + float right = firstRight + 1; + + float xOff = c % 16 * 16 + left; + float yOff = (c & 0xFF) / 16 * 16; + float width = right - left - .02f; - float xOff = c % 16 * 16 + left; - float yOff = (c & 0xFF) / 16 * 16; - float width = right - left - .02f; - Tesselator *t = Tesselator::getInstance(); - t->begin(GL_TRIANGLE_STRIP); - t->tex(xOff / 256.0F, yOff / 256.0F); - t->vertex(xPos, yPos, 0.0f); - t->tex(xOff / 256.0F, (yOff + 15.98f) / 256.0F); - t->vertex(xPos, yPos + 7.99f, 0.0f); - t->tex((xOff + width) / 256.0F, yOff / 256.0F); - t->vertex(xPos + width / 2, yPos, 0.0f); - t->tex((xOff + width) / 256.0F, (yOff + 15.98f) / 256.0F); - t->vertex(xPos + width / 2, yPos + 7.99f, 0.0f); - t->end(); + t->begin(GL_TRIANGLE_STRIP); + t->tex(xOff / 256.0F, yOff / 256.0F); + t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / 256.0F, (yOff + 15.98f) / 256.0F); + t->vertex(xPos, yPos + 7.99f, 0.0f); + t->tex((xOff + width) / 256.0F, yOff / 256.0F); + t->vertex(xPos + width / 2, yPos, 0.0f); + t->tex((xOff + width) / 256.0F, (yOff + 15.98f) / 256.0F); + t->vertex(xPos + width / 2, yPos + 7.99f, 0.0f); + t->end(); - xPos += (right - left) / 2 + 1; + xPos += (right - left) / 2 + 1; } */ - diff --git a/Minecraft.Client/UI/Font.h b/Minecraft.Client/UI/Font.h index e7769698c..fcfe83359 100644 --- a/Minecraft.Client/UI/Font.h +++ b/Minecraft.Client/UI/Font.h @@ -3,81 +3,90 @@ class IntBuffer; class Options; class Textures; -class Font -{ +class Font { private: - int *charWidths; -public: - int fontTexture; - Random *random; - -private: - int colors[32]; // RGB colors for formatting - - Textures *textures; - - float xPos; - float yPos; - - bool enforceUnicodeSheet; // use unicode sheet for ascii - bool bidirectional; // use bidi to flip strings - - int m_cols; // Number of columns in font sheet - int m_rows; // Number of rows in font sheet - int m_charWidth; // Maximum character width - int m_charHeight; // Maximum character height - TEXTURE_NAME m_textureName; // Texture - std::map m_charMap; + int* charWidths; public: - Font(Options *options, const std::wstring& name, Textures* textures, bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[] = NULL); + int fontTexture; + Random* random; + +private: + int colors[32]; // RGB colors for formatting + + Textures* textures; + + float xPos; + float yPos; + + bool enforceUnicodeSheet; // use unicode sheet for ascii + bool bidirectional; // use bidi to flip strings + + int m_cols; // Number of columns in font sheet + int m_rows; // Number of rows in font sheet + int m_charWidth; // Maximum character width + int m_charHeight; // Maximum character height + TEXTURE_NAME m_textureName; // Texture + std::map m_charMap; + +public: + Font(Options* options, const std::wstring& name, Textures* textures, + bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, + int charWidth, int charHeight, unsigned short charMap[] = NULL); #ifndef _XBOX - // 4J Stu - This dtor clashes with one in xui! We never delete these anyway so take it out for now. Can go back when we have got rid of XUI - ~Font(); + // 4J Stu - This dtor clashes with one in xui! We never delete these anyway + // so take it out for now. Can go back when we have got rid of XUI + ~Font(); #endif - void renderFakeCB(IntBuffer *cb); // 4J added + void renderFakeCB(IntBuffer* cb); // 4J added private: - void renderCharacter(wchar_t c); // 4J added + void renderCharacter(wchar_t c); // 4J added public: void drawShadow(const std::wstring& str, int x, int y, int color); - void drawShadowWordWrap(const std::wstring &str, int x, int y, int w, int color, int h); // 4J Added h param - void draw(const std::wstring &str, int x, int y, int color); - /** - * Reorders the string according to bidirectional levels. A bit expensive at - * the moment. - * - * @param str - * @return - */ + void drawShadowWordWrap(const std::wstring& str, int x, int y, int w, + int color, int h); // 4J Added h param + void draw(const std::wstring& str, int x, int y, int color); + /** + * Reorders the string according to bidirectional levels. A bit expensive at + * the moment. + * + * @param str + * @return + */ private: - std::wstring reorderBidi(const std::wstring &str); + std::wstring reorderBidi(const std::wstring& str); - void draw(const std::wstring &str, bool dropShadow); - void draw(const std::wstring& str, int x, int y, int color, bool dropShadow); - int MapCharacter(wchar_t c); // 4J added - bool CharacterExists(wchar_t c); // 4J added + void draw(const std::wstring& str, bool dropShadow); + void draw(const std::wstring& str, int x, int y, int color, + bool dropShadow); + int MapCharacter(wchar_t c); // 4J added + bool CharacterExists(wchar_t c); // 4J added public: int width(const std::wstring& str); std::wstring sanitize(const std::wstring& str); - void drawWordWrap(const std::wstring &string, int x, int y, int w, int col, int h); // 4J Added h param + void drawWordWrap(const std::wstring& string, int x, int y, int w, int col, + int h); // 4J Added h param private: - void drawWordWrapInternal(const std::wstring &string, int x, int y, int w, int col, int h); // 4J Added h param + void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, int h); // 4J Added h param public: - void drawWordWrap(const std::wstring &string, int x, int y, int w, int col, bool darken, int h); // 4J Added h param + void drawWordWrap(const std::wstring& string, int x, int y, int w, int col, + bool darken, int h); // 4J Added h param private: - void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, int col, bool darken, int h); // 4J Added h param + void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h); // 4J Added h param public: int wordWrapHeight(const std::wstring& string, int w); - void setEnforceUnicodeSheet(bool enforceUnicodeSheet); - void setBidirectional(bool bidirectional); + void setEnforceUnicodeSheet(bool enforceUnicodeSheet); + void setBidirectional(bool bidirectional); - // 4J-PB - check for invalid player name - Japanese local name - bool AllCharactersValid(const std::wstring &str); + // 4J-PB - check for invalid player name - Japanese local name + bool AllCharactersValid(const std::wstring& str); }; diff --git a/Minecraft.Client/UI/Gui.cpp b/Minecraft.Client/UI/Gui.cpp index fc1f8ea47..04b8170f0 100644 --- a/Minecraft.Client/UI/Gui.cpp +++ b/Minecraft.Client/UI/Gui.cpp @@ -35,831 +35,911 @@ // #define RENDER_HUD 1 // #endif -float Gui::currentGuiBlendFactor = 1.0f; // 4J added -float Gui::currentGuiScaleFactor = 1.0f; // 4J added -ItemRenderer *Gui::itemRenderer = new ItemRenderer(); +float Gui::currentGuiBlendFactor = 1.0f; // 4J added +float Gui::currentGuiScaleFactor = 1.0f; // 4J added +ItemRenderer* Gui::itemRenderer = new ItemRenderer(); -Gui::Gui(Minecraft *minecraft) -{ - // 4J - initialisers added +Gui::Gui(Minecraft* minecraft) { + // 4J - initialisers added random = new Random(); - tickCount = 0; + tickCount = 0; overlayMessageTime = 0; animateOverlayMessageColor = false; - progress = 0.0f; - tbr = 1.0f; - fAlphaIncrementPerCent=255.0f/100.0f; + progress = 0.0f; + tbr = 1.0f; + fAlphaIncrementPerCent = 255.0f / 100.0f; - this->minecraft = minecraft; + this->minecraft = minecraft; - lastTickA = 0.0f; + lastTickA = 0.0f; } -void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) -{ - // 4J Stu - I have copied this code for XUI_BaseScene. If/when it gets changed it should be broken out - // 4J - altered to force full screen mode to 3X scaling, and any split screen modes to 2X scaling. This is so that the further scaling by 0.5 that - // happens in split screen modes results in a final scaling of 1 rather than 1.5. - int splitYOffset;// = 20; // This offset is applied when doing the 2X scaling above to move the gui out of the way of the tool tips - int guiScale;// = ( minecraft->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN ? 3 : 2 ); - int iPad=minecraft->player->GetXboxPad(); - int iWidthOffset=0,iHeightOffset=0; // used to get the interface looking right on a 2 player split screen game +void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) { + // 4J Stu - I have copied this code for XUI_BaseScene. If/when it gets + // changed it should be broken out 4J - altered to force full screen mode to + // 3X scaling, and any split screen modes to 2X scaling. This is so that the + // further scaling by 0.5 that happens in split screen modes results in a + // final scaling of 1 rather than 1.5. + int splitYOffset; // = 20; // This offset is applied when doing the 2X + // scaling above to move the gui out of the way of the + // tool tips + int guiScale; // = ( minecraft->player->m_iScreenSection == + // C4JRender::VIEWPORT_TYPE_FULLSCREEN ? 3 : 2 ); + int iPad = minecraft->player->GetXboxPad(); + int iWidthOffset = 0, + iHeightOffset = 0; // used to get the interface looking right on a 2 + // player split screen game - // 4J-PB - selected the gui scale based on the slider settings - if(minecraft->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN) - { - guiScale=app.GetGameSettings(iPad,eGameSetting_UISize) + 2; - } - else - { - guiScale=app.GetGameSettings(iPad,eGameSetting_UISizeSplitscreen) + 2; - } + // 4J-PB - selected the gui scale based on the slider settings + if (minecraft->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_FULLSCREEN) { + guiScale = app.GetGameSettings(iPad, eGameSetting_UISize) + 2; + } else { + guiScale = + app.GetGameSettings(iPad, eGameSetting_UISizeSplitscreen) + 2; + } + ScreenSizeCalculator ssc(minecraft->options, minecraft->width, + minecraft->height, guiScale); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + int iSafezoneXHalf = 0, iSafezoneYHalf = 0; + int iTooltipsYOffset = 0; + int quickSelectWidth = 182; + int quickSelectHeight = 22; + float fScaleFactorWidth = 1.0f, fScaleFactorHeight = 1.0f; + bool bTwoPlayerSplitscreen = false; + currentGuiScaleFactor = + (float)guiScale; // Keep static copy of scale so we know how gui + // coordinates map to physical pixels - this is also + // affected by the viewport - ScreenSizeCalculator ssc(minecraft->options, minecraft->width, minecraft->height, guiScale ); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - int iSafezoneXHalf=0,iSafezoneYHalf=0; - int iTooltipsYOffset=0; - int quickSelectWidth=182; - int quickSelectHeight=22; - float fScaleFactorWidth=1.0f,fScaleFactorHeight=1.0f; - bool bTwoPlayerSplitscreen=false; - currentGuiScaleFactor = (float) guiScale; // Keep static copy of scale so we know how gui coordinates map to physical pixels - this is also affected by the viewport + switch (guiScale) { + case 3: + splitYOffset = 0; + break; + case 4: + splitYOffset = -5; + break; + default: // 2 + splitYOffset = 10; + break; + } - switch(guiScale) - { - case 3: - splitYOffset = 0; - break; - case 4: - splitYOffset = -5; - break; - default: // 2 - splitYOffset = 10; - break; - } + // Check which screen section this player is in + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + // single player + iSafezoneXHalf = screenWidth / 20; // 5% + iSafezoneYHalf = screenHeight / 20; // 5% + iTooltipsYOffset = 40 + splitYOffset; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + iSafezoneXHalf = + screenWidth / + 10; // 5% (need to treat the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset; + fScaleFactorWidth = 0.5f; + iWidthOffset = + (int)((float)screenWidth * (1.0f - fScaleFactorWidth)); + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + iSafezoneXHalf = + screenWidth / + 10; // 5% (need to treat the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorWidth = 0.5f; + iWidthOffset = + (int)((float)screenWidth * (1.0f - fScaleFactorWidth)); + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorHeight = 0.5f; + iHeightOffset = screenHeight; + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorHeight = 0.5f; + iHeightOffset = screenHeight; + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset; + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = splitYOffset; // 5% + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = + splitYOffset + + screenHeight / 10; // 5% (the whole screen is 2x this screen) + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = + splitYOffset + + screenHeight / 10; // 5% (the whole screen is 2x this screen) + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + } - // Check which screen section this player is in - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - // single player - iSafezoneXHalf = screenWidth/20; // 5% - iSafezoneYHalf = screenHeight/20; // 5% - iTooltipsYOffset=40+splitYOffset; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - iSafezoneXHalf = screenWidth/10; // 5% (need to treat the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset; - fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - iSafezoneXHalf = screenWidth/10; // 5% (need to treat the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorHeight=0.5f; - iHeightOffset=screenHeight; - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorHeight=0.5f; - iHeightOffset=screenHeight; - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset; - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset; // 5% - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10; // 5% (the whole screen is 2x this screen) - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset + screenHeight/10; // 5% (the whole screen is 2x this screen) - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - - } + // 4J-PB - turn off the slot display if a xui menu is up, or if we're + // autosaving + bool bDisplayGui = !ui.GetMenuDisplayed(iPad) && + !(app.GetXuiAction(iPad) == + eAppAction_AutosaveSaveGameCapturedThumbnail); - // 4J-PB - turn off the slot display if a xui menu is up, or if we're autosaving - bool bDisplayGui=!ui.GetMenuDisplayed(iPad) && !(app.GetXuiAction(iPad)==eAppAction_AutosaveSaveGameCapturedThumbnail); + // if tooltips are off, set the y offset to zero + if (app.GetGameSettings(iPad, eGameSetting_Tooltips) == 0 && bDisplayGui) { + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + iTooltipsYOffset = screenHeight / 10; + break; + default: + // iTooltipsYOffset=screenHeight/10; + switch (guiScale) { + case 3: + iTooltipsYOffset = 28; // screenHeight/10; + break; + case 4: + iTooltipsYOffset = 28; // screenHeight/10; + break; + default: // 2 + iTooltipsYOffset = 14; // screenHeight/10; + break; + } + break; + } + } - // if tooltips are off, set the y offset to zero - if(app.GetGameSettings(iPad,eGameSetting_Tooltips)==0 && bDisplayGui) - { - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - iTooltipsYOffset=screenHeight/10; - break; - default: - //iTooltipsYOffset=screenHeight/10; - switch(guiScale) - { - case 3: - iTooltipsYOffset=28;//screenHeight/10; - break; - case 4: - iTooltipsYOffset=28;//screenHeight/10; - break; - default: // 2 - iTooltipsYOffset=14;//screenHeight/10; - break; - } - break; - } - } - - // 4J-PB - Turn off interface if eGameSetting_DisplayHUD is off - for screen shots/videos. - if ( app.GetGameSettings(iPad,eGameSetting_DisplayHUD)==0 ) - { - bDisplayGui = false; - } - - Font *font = minecraft->font; + // 4J-PB - Turn off interface if eGameSetting_DisplayHUD is off - for screen + // shots/videos. + if (app.GetGameSettings(iPad, eGameSetting_DisplayHUD) == 0) { + bDisplayGui = false; + } + Font* font = minecraft->font; minecraft->gameRenderer->setupGuiScreen(guiScale); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // 4J - added - this did actually get set in renderVignette but that code is currently commented out + glBlendFunc(GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA); // 4J - added - this did actually get + // set in renderVignette but that code + // is currently commented out - if (Minecraft::useFancyGraphics()) - { - renderVignette(minecraft->player->getBrightness(a), screenWidth, screenHeight); - } + if (Minecraft::useFancyGraphics()) { + renderVignette(minecraft->player->getBrightness(a), screenWidth, + screenHeight); + } - ///////////////////////////////////////////////////////////////////////////////////// - // Display the pumpkin screen effect - ///////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////// + // Display the pumpkin screen effect + ///////////////////////////////////////////////////////////////////////////////////// - std::shared_ptr headGear = minecraft->player->inventory->getArmor(3); + std::shared_ptr headGear = + minecraft->player->inventory->getArmor(3); - // 4J-PB - changing this to be per player - //if (!minecraft->options->thirdPersonView && headGear != NULL && headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, screenHeight); - if ((minecraft->player->ThirdPersonView()==0) && headGear != NULL && headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, screenHeight); - if (!minecraft->player->hasEffect(MobEffect::confusion)) - { - float pt = minecraft->player->oPortalTime + (minecraft->player->portalTime - minecraft->player->oPortalTime) * a; - if (pt > 0) - { - renderTp(pt, screenWidth, screenHeight); - } - } + // 4J-PB - changing this to be per player + // if (!minecraft->options->thirdPersonView && headGear != NULL && + // headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, + // screenHeight); + if ((minecraft->player->ThirdPersonView() == 0) && headGear != NULL && + headGear->id == Tile::pumpkin_Id) + renderPumpkin(screenWidth, screenHeight); + if (!minecraft->player->hasEffect(MobEffect::confusion)) { + float pt = + minecraft->player->oPortalTime + + (minecraft->player->portalTime - minecraft->player->oPortalTime) * + a; + if (pt > 0) { + renderTp(pt, screenWidth, screenHeight); + } + } - if (!minecraft->gameMode->isCutScene()) - { - if(bDisplayGui && bTwoPlayerSplitscreen) - { - // need to apply scale factors depending on the mode - glPushMatrix(); - glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); - } + if (!minecraft->gameMode->isCutScene()) { + if (bDisplayGui && bTwoPlayerSplitscreen) { + // need to apply scale factors depending on the mode + glPushMatrix(); + glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); + } #if RENDER_HUD - ///////////////////////////////////////////////////////////////////////////////////// - // Display the quick select background, the quick select selection, and the crosshair - ///////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////// + // Display the quick select background, the quick select selection, and + // the crosshair + ///////////////////////////////////////////////////////////////////////////////////// - glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); - // 4J - this is where to set the blend factor for gui things - // use the primary player's settings - unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); + // 4J - this is where to set the blend factor for gui things + // use the primary player's settings + unsigned char ucAlpha = app.GetGameSettings( + ProfileManager.GetPrimaryPad(), eGameSetting_InterfaceOpacity); - // If the user has started to navigate their quickselect bar, ignore the alpha setting, and display at default value - float fVal=fAlphaIncrementPerCent*(float)ucAlpha; - if(ucAlpha<80) - { - // check if we have the timer running for the opacity - unsigned int uiOpacityTimer=app.GetOpacityTimer(iPad); - if(uiOpacityTimer!=0) - { - if(uiOpacityTimer<10) - { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=fAlphaIncrementPerCent*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); - } - else - { - fVal=fAlphaIncrementPerCent*80.0f; - } - } - else - { - fVal=fAlphaIncrementPerCent*(float)ucAlpha; - } - } - else - { - fVal=fAlphaIncrementPerCent*(float)ucAlpha; - } + // If the user has started to navigate their quickselect bar, ignore the + // alpha setting, and display at default value + float fVal = fAlphaIncrementPerCent * (float)ucAlpha; + if (ucAlpha < 80) { + // check if we have the timer running for the opacity + unsigned int uiOpacityTimer = app.GetOpacityTimer(iPad); + if (uiOpacityTimer != 0) { + if (uiOpacityTimer < 10) { + float fStep = (80.0f - (float)ucAlpha) / 10.0f; + fVal = fAlphaIncrementPerCent * + (80.0f - ((10.0f - (float)uiOpacityTimer) * fStep)); + } else { + fVal = fAlphaIncrementPerCent * 80.0f; + } + } else { + fVal = fAlphaIncrementPerCent * (float)ucAlpha; + } + } else { + fVal = fAlphaIncrementPerCent * (float)ucAlpha; + } - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)fVal)<<24)); - currentGuiBlendFactor = fVal / 255.0f; - // RenderManager.StateSetBlendFactor(0x40ffffff); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)fVal) << 24)); + currentGuiBlendFactor = fVal / 255.0f; + // RenderManager.StateSetBlendFactor(0x40ffffff); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - blitOffset = -90; + blitOffset = -90; - ///////////////////////////////////////////////////////////////////////////////////// - // Display the quick select background, the quick select selection, and the crosshair - ///////////////////////////////////////////////////////////////////////////////////// - if(bDisplayGui) - { - MemSect(31); - minecraft->textures->bindTexture(TN_GUI_GUI); // 4J was L"/gui/gui.png" - MemSect(0); + ///////////////////////////////////////////////////////////////////////////////////// + // Display the quick select background, the quick select selection, and + // the crosshair + ///////////////////////////////////////////////////////////////////////////////////// + if (bDisplayGui) { + MemSect(31); + minecraft->textures->bindTexture( + TN_GUI_GUI); // 4J was L"/gui/gui.png" + MemSect(0); - std::shared_ptr inventory = minecraft->player->inventory; - if(bTwoPlayerSplitscreen) - { - // need to apply scale factors depending on the mode + std::shared_ptr inventory = minecraft->player->inventory; + if (bTwoPlayerSplitscreen) { + // need to apply scale factors depending on the mode - // 4J Stu - Moved this push and scale further up as we still need to do it for the few HUD components not replaced by xui - //glPushMatrix(); - //glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); - - // 4J-PB - move into the safe zone, and account for 2 player splitscreen - blit(iWidthOffset + (screenWidth - quickSelectWidth)/2, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset , 0, 0, 182, 22); - blit(iWidthOffset + (screenWidth - quickSelectWidth)/2 - 1 + inventory->selected * 20, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 1, 0, 22, 24, 22); - } - else - { - blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset , 0, 0, 182, 22); - blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2 - 1 + inventory->selected * 20, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 1, 0, 22, 24, 22); - } + // 4J Stu - Moved this push and scale further up as we still + // need to do it for the few HUD components not replaced by xui + // glPushMatrix(); + // glScalef(fScaleFactorWidth, fScaleFactorHeight, + // fScaleFactorWidth); + // 4J-PB - move into the safe zone, and account for 2 player + // splitscreen + blit(iWidthOffset + (screenWidth - quickSelectWidth) / 2, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset, + 0, 0, 182, 22); + blit(iWidthOffset + (screenWidth - quickSelectWidth) / 2 - 1 + + inventory->selected * 20, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 1, + 0, 22, 24, 22); + } else { + blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset, + 0, 0, 182, 22); + blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2 - 1 + + inventory->selected * 20, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 1, + 0, 22, 24, 22); + } - MemSect(31); - minecraft->textures->bindTexture(TN_GUI_ICONS);//L"/gui/icons.png")); - MemSect(0); - glEnable(GL_BLEND); - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)fVal)<<24)); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - //glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); - // 4J Stu - We don't want to adjust the cursor by the safezone, we want it centred - if(bTwoPlayerSplitscreen) - { - blit(iWidthOffset + screenWidth / 2 - 7, (iHeightOffset + screenHeight) / 2 - 7, 0, 0, 16, 16); - } - else - { - blit(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); - } - glDisable(GL_BLEND); + MemSect(31); + minecraft->textures->bindTexture( + TN_GUI_ICONS); // L"/gui/icons.png")); + MemSect(0); + glEnable(GL_BLEND); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)fVal) << 24)); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + // glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); + // 4J Stu - We don't want to adjust the cursor by the safezone, we + // want it centred + if (bTwoPlayerSplitscreen) { + blit(iWidthOffset + screenWidth / 2 - 7, + (iHeightOffset + screenHeight) / 2 - 7, 0, 0, 16, 16); + } else { + blit(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); + } + glDisable(GL_BLEND); - // if(bTwoPlayerSplitscreen) - // { - // glPopMatrix(); - // } + // if(bTwoPlayerSplitscreen) + // { + // glPopMatrix(); + // } + } - } + bool blink = minecraft->player->invulnerableTime / 3 % 2 == 1; + if (minecraft->player->invulnerableTime < 10) blink = false; + int iHealth = minecraft->player->getHealth(); + int iLastHealth = minecraft->player->lastHealth; + random->setSeed(tickCount * 312871); - bool blink = minecraft->player->invulnerableTime / 3 % 2 == 1; - if (minecraft->player->invulnerableTime < 10) blink = false; - int iHealth = minecraft->player->getHealth(); - int iLastHealth = minecraft->player->lastHealth; - random->setSeed(tickCount * 312871); + bool foodBlink = false; + FoodData* foodData = minecraft->player->getFoodData(); + int food = foodData->getFoodLevel(); + int oldFood = foodData->getLastFoodLevel(); - bool foodBlink = false; - FoodData *foodData = minecraft->player->getFoodData(); - int food = foodData->getFoodLevel(); - int oldFood = foodData->getLastFoodLevel(); + // if (false) //(true) + // { + // renderBossHealth(); + // } -// if (false) //(true) -// { -// renderBossHealth(); -// } + ///////////////////////////////////////////////////////////////////////////////////// + // Display the experience, food, armour, health and the air bubbles + ///////////////////////////////////////////////////////////////////////////////////// + if (bDisplayGui) { + // 4J - added blend for fading gui + glEnable(GL_BLEND); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - ///////////////////////////////////////////////////////////////////////////////////// - // Display the experience, food, armour, health and the air bubbles - ///////////////////////////////////////////////////////////////////////////////////// - if(bDisplayGui) - { - // 4J - added blend for fading gui - glEnable(GL_BLEND); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + if (minecraft->gameMode->canHurtPlayer()) { + int xLeft, xRight; + // 4J Stu - TODO Work out proper positioning for splitscreen + if (bTwoPlayerSplitscreen) { + xLeft = iWidthOffset + (screenWidth - quickSelectWidth) / 2; + xRight = + iWidthOffset + (screenWidth + quickSelectWidth) / 2; + } else { + xLeft = (screenWidth - quickSelectWidth) / 2; + xRight = (screenWidth + quickSelectWidth) / 2; + } - if (minecraft->gameMode->canHurtPlayer()) - { - int xLeft, xRight; - // 4J Stu - TODO Work out proper positioning for splitscreen - if(bTwoPlayerSplitscreen) - { - xLeft = iWidthOffset + (screenWidth - quickSelectWidth)/2; - xRight = iWidthOffset + (screenWidth + quickSelectWidth)/2; - } - else - { - xLeft = (screenWidth - quickSelectWidth)/2; - xRight = (screenWidth + quickSelectWidth) / 2; - } + // render experience bar + int xpNeededForNextLevel = + minecraft->player->getXpNeededForNextLevel(); + if (xpNeededForNextLevel > 0) { + int w = 182; - // render experience bar - int xpNeededForNextLevel = minecraft->player->getXpNeededForNextLevel(); - if (xpNeededForNextLevel > 0) - { - int w = 182; + int progress = (int)(minecraft->player->experienceProgress * + (float)(w + 1)); - int progress = (int) (minecraft->player->experienceProgress * (float) (w + 1)); + int yo = + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 8; + if (bTwoPlayerSplitscreen) { + yo += iHeightOffset; + } + blit(xLeft, yo, 0, 64, w, 5); + if (progress > 0) { + blit(xLeft, yo, 0, 69, progress, 5); + } + } - int yo = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 8; - if(bTwoPlayerSplitscreen) - { - yo+=iHeightOffset; - } - blit(xLeft, yo, 0, 64, w, 5); - if (progress > 0) - { - blit(xLeft, yo, 0, 69, progress, 5); - } - } + int yLine1, yLine2; + if (bTwoPlayerSplitscreen) { + // yo = iHeightOffset + screenHeight - 10 - iSafezoneYHalf - + // iTooltipsYOffset; + yLine1 = iHeightOffset + screenHeight - 18 - + iSafezoneYHalf - iTooltipsYOffset; + yLine2 = yLine1 - 10; + } else { + // yo = screenHeight - 10 - iSafezoneYHalf - + // iTooltipsYOffset; + yLine1 = + screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; + yLine2 = yLine1 - 10; + } - int yLine1, yLine2; - if(bTwoPlayerSplitscreen) - { - //yo = iHeightOffset + screenHeight - 10 - iSafezoneYHalf - iTooltipsYOffset; - yLine1 = iHeightOffset + screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; - yLine2 = yLine1 - 10; - } - else - { - //yo = screenHeight - 10 - iSafezoneYHalf - iTooltipsYOffset; - yLine1 = screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; - yLine2 = yLine1 - 10; - } + int armor = minecraft->player->getArmorValue(); + int heartOffsetIndex = -1; + if (minecraft->player->hasEffect(MobEffect::regeneration)) { + heartOffsetIndex = tickCount % 25; + } - int armor = minecraft->player->getArmorValue(); - int heartOffsetIndex = -1; - if (minecraft->player->hasEffect(MobEffect::regeneration)) - { - heartOffsetIndex = tickCount % 25; - } + // render health and armor + for (int i = 0; i < Player::MAX_HEALTH / 2; i++) { + if (armor > 0) { + int xo = xLeft + i * 8; - // render health and armor - for (int i = 0; i < Player::MAX_HEALTH / 2; i++) - { - if (armor > 0) - { - int xo = xLeft + i * 8; + // HEALTH + if (i * 2 + 1 < armor) + blit(xo, yLine2, 16 + 2 * 9, 9 * 1, 9, 9); + if (i * 2 + 1 == armor) + blit(xo, yLine2, 16 + 1 * 9, 9 * 1, 9, 9); + if (i * 2 + 1 > armor) + blit(xo, yLine2, 16 + 0 * 9, 9 * 1, 9, 9); + } - // HEALTH - if (i * 2 + 1 < armor) blit(xo, yLine2, 16 + 2 * 9, 9 * 1, 9, 9); - if (i * 2 + 1 == armor) blit(xo, yLine2, 16 + 1 * 9, 9 * 1, 9, 9); - if (i * 2 + 1 > armor) blit(xo, yLine2, 16 + 0 * 9, 9 * 1, 9, 9); - } + int healthTexBaseX = 16; + if (minecraft->player->hasEffect(MobEffect::poison)) { + healthTexBaseX += 4 * 9; + } - int healthTexBaseX = 16; - if (minecraft->player->hasEffect(MobEffect::poison)) - { - healthTexBaseX += 4 * 9; - } + int bg = 0; + if (blink) bg = 1; + int xo = xLeft + i * 8; + int yo = yLine1; - int bg = 0; - if (blink) bg = 1; - int xo = xLeft + i * 8; - int yo = yLine1; - - if (iHealth <= 4) - { - yo += random->nextInt(2); - } - if (i == heartOffsetIndex) - { - yo -= 2; - } + if (iHealth <= 4) { + yo += random->nextInt(2); + } + if (i == heartOffsetIndex) { + yo -= 2; + } - int y0 = 0; - // 4J-PB - no hardcore in xbox -// if (minecraft.level.getLevelData().isHardcore()) { -// y0 = 5; -// } - blit(xo, yo, 16 + bg * 9, 9 * 0, 9, 9); - if (blink) - { - if (i * 2 + 1 < iLastHealth) blit(xo, yo, healthTexBaseX + 6 * 9, 9 * y0, 9, 9); - if (i * 2 + 1 == iLastHealth) blit(xo, yo, healthTexBaseX + 7 * 9, 9 * y0, 9, 9); - } - if (i * 2 + 1 < iHealth) blit(xo, yo, healthTexBaseX + 4 * 9, 9 * y0, 9, 9); - if (i * 2 + 1 == iHealth) blit(xo, yo, healthTexBaseX + 5 * 9, 9 * y0, 9, 9); - } + int y0 = 0; + // 4J-PB - no hardcore in xbox + // if + // (minecraft.level.getLevelData().isHardcore()) { y0 = 5; + // } + blit(xo, yo, 16 + bg * 9, 9 * 0, 9, 9); + if (blink) { + if (i * 2 + 1 < iLastHealth) + blit(xo, yo, healthTexBaseX + 6 * 9, 9 * y0, 9, 9); + if (i * 2 + 1 == iLastHealth) + blit(xo, yo, healthTexBaseX + 7 * 9, 9 * y0, 9, 9); + } + if (i * 2 + 1 < iHealth) + blit(xo, yo, healthTexBaseX + 4 * 9, 9 * y0, 9, 9); + if (i * 2 + 1 == iHealth) + blit(xo, yo, healthTexBaseX + 5 * 9, 9 * y0, 9, 9); + } - // render food - for (int i = 0; i < FoodConstants::MAX_FOOD / 2; i++) - { - int yo = yLine1; + // render food + for (int i = 0; i < FoodConstants::MAX_FOOD / 2; i++) { + int yo = yLine1; + int texBaseX = 16; + int bg = 0; + if (minecraft->player->hasEffect(MobEffect::hunger)) { + texBaseX += 4 * 9; + bg = 13; + } - int texBaseX = 16; - int bg = 0; - if (minecraft->player->hasEffect(MobEffect::hunger)) - { - texBaseX += 4 * 9; - bg = 13; - } + if (minecraft->player->getFoodData() + ->getSaturationLevel() <= 0) { + if ((tickCount % (food * 3 + 1)) == 0) { + yo += random->nextInt(3) - 1; + } + } - if (minecraft->player->getFoodData()->getSaturationLevel() <= 0) - { - if ((tickCount % (food * 3 + 1)) == 0) - { - yo += random->nextInt(3) - 1; - } - } + if (foodBlink) bg = 1; + int xo = xRight - i * 8 - 9; + blit(xo, yo, 16 + bg * 9, 9 * 3, 9, 9); + if (foodBlink) { + if (i * 2 + 1 < oldFood) + blit(xo, yo, texBaseX + 6 * 9, 9 * 3, 9, 9); + if (i * 2 + 1 == oldFood) + blit(xo, yo, texBaseX + 7 * 9, 9 * 3, 9, 9); + } + if (i * 2 + 1 < food) + blit(xo, yo, texBaseX + 4 * 9, 9 * 3, 9, 9); + if (i * 2 + 1 == food) + blit(xo, yo, texBaseX + 5 * 9, 9 * 3, 9, 9); + } - if (foodBlink) bg = 1; - int xo = xRight - i * 8 - 9; - blit(xo, yo, 16 + bg * 9, 9 * 3, 9, 9); - if (foodBlink) - { - if (i * 2 + 1 < oldFood) blit(xo, yo, texBaseX + 6 * 9, 9 * 3, 9, 9); - if (i * 2 + 1 == oldFood) blit(xo, yo, texBaseX + 7 * 9, 9 * 3, 9, 9); - } - if (i * 2 + 1 < food) blit(xo, yo, texBaseX + 4 * 9, 9 * 3, 9, 9); - if (i * 2 + 1 == food) blit(xo, yo, texBaseX + 5 * 9, 9 * 3, 9, 9); - } + // render air bubbles + if (minecraft->player->isUnderLiquid(Material::water)) { + int count = + (int)ceil((minecraft->player->getAirSupply() - 2) * + 10.0f / Player::TOTAL_AIR_SUPPLY); + int extra = (int)ceil((minecraft->player->getAirSupply()) * + 10.0f / Player::TOTAL_AIR_SUPPLY) - + count; + for (int i = 0; i < count + extra; i++) { + // Air bubbles + if (i < count) + blit(xRight - i * 8 - 9, yLine2, 16, 9 * 2, 9, 9); + else + blit(xRight - i * 8 - 9, yLine2, 16 + 9, 9 * 2, 9, + 9); + } + } + } + } - // render air bubbles - if (minecraft->player->isUnderLiquid(Material::water)) - { - int count = (int) ceil((minecraft->player->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY); - int extra = (int) ceil((minecraft->player->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY) - count; - for (int i = 0; i < count + extra; i++) - { - // Air bubbles - if (i < count) blit(xRight - i * 8 - 9, yLine2, 16, 9 * 2, 9, 9); - else blit(xRight - i * 8 - 9, yLine2, 16 + 9, 9 * 2, 9, 9); - } - } - } + // 4J-PB - turn off the slot display if a xui menu is up - } + //////////////////////////// + // render the slot contents + //////////////////////////// + if (bDisplayGui) { + // glDisable(GL_BLEND); 4J - removed - we want + //to be able to fade our gui - // 4J-PB - turn off the slot display if a xui menu is up + glEnable(GL_RESCALE_NORMAL); - //////////////////////////// - // render the slot contents - //////////////////////////// - if(bDisplayGui) - { - // glDisable(GL_BLEND); 4J - removed - we want to be able to fade our gui + Lighting::turnOnGui(); - glEnable(GL_RESCALE_NORMAL); + int x, y; - Lighting::turnOnGui(); - + for (int i = 0; i < 9; i++) { + if (bTwoPlayerSplitscreen) { + x = iWidthOffset + screenWidth / 2 - 9 * 10 + i * 20 + 2; + y = iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 16 - 3 + 22; + } else { + x = screenWidth / 2 - 9 * 10 + i * 20 + 2; + y = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - + 3 + 22; + } + this->renderSlot(i, x, y, a); + } + Lighting::turnOff(); + glDisable(GL_RESCALE_NORMAL); + } +#endif // RENDER_HUD - int x,y; + // 4J - do render of crouched player. This code is largely taken from + // the inventory render of the player, with some special hard-coded + // positions worked out by hand from the xui implementation of the + // crouch icon - for (int i = 0; i < 9; i++) - { - if(bTwoPlayerSplitscreen) - { - x = iWidthOffset + screenWidth / 2 - 9 * 10 + i * 20 + 2; - y = iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - 3 + 22; - } - else - { - x = screenWidth / 2 - 9 * 10 + i * 20 + 2; - y = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - 3 + 22; - } - this->renderSlot(i, x, y, a); - } - Lighting::turnOff(); - glDisable(GL_RESCALE_NORMAL); - } -#endif // RENDER_HUD + if (app.GetGameSettings(iPad, eGameSetting_AnimatedCharacter)) { + // int playerIdx = minecraft->player->GetXboxPad(); - // 4J - do render of crouched player. This code is largely taken from the inventory render of the player, with some special hard-coded positions - // worked out by hand from the xui implementation of the crouch icon + static int characterDisplayTimer[4] = {0}; + if (!bDisplayGui) { + characterDisplayTimer[iPad] = 0; + } else if (minecraft->player->isSneaking()) { + characterDisplayTimer[iPad] = 30; + } else if (minecraft->player->isSprinting()) { + characterDisplayTimer[iPad] = 30; + } else if (minecraft->player->abilities.flying) { + characterDisplayTimer[iPad] = + 5; // quickly get rid of the player display if they stop + // flying + } else if (characterDisplayTimer[iPad] > 0) { + --characterDisplayTimer[iPad]; + } + bool displayCrouch = minecraft->player->isSneaking() || + (characterDisplayTimer[iPad] > 0); + bool displaySprint = minecraft->player->isSprinting() || + (characterDisplayTimer[iPad] > 0); + bool displayFlying = minecraft->player->abilities.flying || + (characterDisplayTimer[iPad] > 0); - if(app.GetGameSettings(iPad,eGameSetting_AnimatedCharacter)) - { - //int playerIdx = minecraft->player->GetXboxPad(); + if (bDisplayGui && + (displayCrouch || displaySprint || displayFlying)) { + EntityRenderDispatcher::instance->prepare( + minecraft->level, minecraft->textures, minecraft->font, + minecraft->cameraTargetPlayer, minecraft->options, a); + glEnable(GL_RESCALE_NORMAL); + glEnable(GL_COLOR_MATERIAL); - static int characterDisplayTimer[4] = {0}; - if( !bDisplayGui ) - { - characterDisplayTimer[iPad] = 0; - } - else if( minecraft->player->isSneaking() ) - { - characterDisplayTimer[iPad] = 30; - } - else if( minecraft->player->isSprinting() ) - { - characterDisplayTimer[iPad] = 30; - } - else if( minecraft->player->abilities.flying) - { - characterDisplayTimer[iPad] = 5; // quickly get rid of the player display if they stop flying - } - else if( characterDisplayTimer[iPad] > 0 ) - { - --characterDisplayTimer[iPad]; - } - bool displayCrouch = minecraft->player->isSneaking() || ( characterDisplayTimer[iPad] > 0 ); - bool displaySprint = minecraft->player->isSprinting() || ( characterDisplayTimer[iPad] > 0 ); - bool displayFlying = minecraft->player->abilities.flying || ( characterDisplayTimer[iPad] > 0 ); + int xo = 0; + int yo = 0; + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + default: + if (RenderManager.IsHiDef()) xo = -22; + yo = -36; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + xo = 0; + yo = -48; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + xo = -43; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + xo = -43; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + xo = 0; + yo = -48; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + xo = -43; + yo = -48; + break; + } + glPushMatrix(); + glTranslatef((float)xo + 51, (float)yo + 75, 50); + float ss = 12; + glScalef(-ss, ss, ss); + glRotatef(180, 0, 0, 1); - if( bDisplayGui && (displayCrouch || displaySprint || displayFlying) ) - { - EntityRenderDispatcher::instance->prepare(minecraft->level, minecraft->textures, minecraft->font, minecraft->cameraTargetPlayer, minecraft->options, a); - glEnable(GL_RESCALE_NORMAL); - glEnable(GL_COLOR_MATERIAL); + float oyr = minecraft->player->yRot; + float oyrO = minecraft->player->yRotO; + float oxr = minecraft->player->xRot; + int ofire = minecraft->player->onFire; + bool ofireflag = + minecraft->player->getSharedFlag(Entity::FLAG_ONFIRE); - int xo = 0; - int yo = 0; - switch( minecraft->player->m_iScreenSection ) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - default: - if(RenderManager.IsHiDef()) xo = -22; - yo = -36; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - xo = 0; yo = -48; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - xo = -43; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xo = -43; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - xo = 0; yo = -48; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xo = -43; yo = -48; - break; - } - glPushMatrix(); - glTranslatef((float)xo + 51, (float)yo + 75, 50); - float ss = 12; - glScalef(-ss, ss, ss); - glRotatef(180, 0, 0, 1); + float xd = -40; + float yd = 10; - float oyr = minecraft->player->yRot; - float oyrO = minecraft->player->yRotO; - float oxr = minecraft->player->xRot; - int ofire = minecraft->player->onFire; - bool ofireflag = minecraft->player->getSharedFlag(Entity::FLAG_ONFIRE); + // 4J Stu - This is all based on the inventory player renderer, + // with changes to ensure that capes render correctly by + // minimising the changes to member variables of the player + // which are all related - float xd = -40; - float yd = 10; + glRotatef(45 + 90, 0, 1, 0); + Lighting::turnOn(); + glRotatef(-45 - 90, 0, 1, 0); - // 4J Stu - This is all based on the inventory player renderer, with changes to ensure that capes render correctly - // by minimising the changes to member variables of the player which are all related + glRotatef(-(float)atan(yd / 40.0f) * 20, 1, 0, 0); + float bodyRot = (minecraft->player->yBodyRotO + + (minecraft->player->yBodyRot - + minecraft->player->yBodyRotO)); + // Fixed rotation angle of degrees, adjusted by bodyRot to + // negate the rotation that occurs in the renderer bodyRot in + // the rotation below is a simplification of "180 - (180 - + // bodyRot)" where the first 180 is + // EntityRenderDispatcher::instance->playerRotY that we set + // below and (180 - bodyRot) is the angle of rotation that is + // performed within the mob renderer + glRotatef(bodyRot - ((float)atan(xd / 40.0f) * 20), 0, 1, 0); + glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glRotatef(45 + 90, 0, 1, 0); - Lighting::turnOn(); - glRotatef(-45 - 90, 0, 1, 0); + // Set head rotation to body rotation to make head static + minecraft->player->yRot = bodyRot; + minecraft->player->yRotO = minecraft->player->yRot; + minecraft->player->xRot = -(float)atan(yd / 40.0f) * 20; - glRotatef(-(float) atan(yd / 40.0f ) * 20, 1, 0, 0); - float bodyRot = (minecraft->player->yBodyRotO + (minecraft->player->yBodyRot - minecraft->player->yBodyRotO)); - // Fixed rotation angle of degrees, adjusted by bodyRot to negate the rotation that occurs in the renderer - // bodyRot in the rotation below is a simplification of "180 - (180 - bodyRot)" where the first 180 is EntityRenderDispatcher::instance->playerRotY that we set below - // and (180 - bodyRot) is the angle of rotation that is performed within the mob renderer - glRotatef( bodyRot - ( (float) atan(xd / 40.0f) * 20), 0, 1, 0); - glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + minecraft->player->onFire = 0; + minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); - // Set head rotation to body rotation to make head static - minecraft->player->yRot = bodyRot; - minecraft->player->yRotO = minecraft->player->yRot; - minecraft->player->xRot = -(float) atan(yd / 40.0f) * 20; + glTranslatef(0, minecraft->player->heightOffset, 0); + EntityRenderDispatcher::instance->playerRotY = 180; + EntityRenderDispatcher::instance->isGuiRender = true; + EntityRenderDispatcher::instance->render(minecraft->player, 0, + 0, 0, 0, 1); + EntityRenderDispatcher::instance->isGuiRender = false; - minecraft->player->onFire = 0; - minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); - - glTranslatef(0, minecraft->player->heightOffset, 0); - EntityRenderDispatcher::instance->playerRotY = 180; - EntityRenderDispatcher::instance->isGuiRender = true; - EntityRenderDispatcher::instance->render(minecraft->player, 0, 0, 0, 0, 1); - EntityRenderDispatcher::instance->isGuiRender = false; - - minecraft->player->yRot = oyr; - minecraft->player->yRotO = oyrO; - minecraft->player->xRot = oxr; - minecraft->player->onFire = ofire; - minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE,ofireflag); - glPopMatrix(); - Lighting::turnOff(); - glDisable(GL_RESCALE_NORMAL); - } - } - } + minecraft->player->yRot = oyr; + minecraft->player->yRotO = oyrO; + minecraft->player->xRot = oxr; + minecraft->player->onFire = ofire; + minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, + ofireflag); + glPopMatrix(); + Lighting::turnOff(); + glDisable(GL_RESCALE_NORMAL); + } + } + } #if RENDER_HUD - // Moved so the opacity blend is applied to it - if (bDisplayGui && minecraft->gameMode->hasExperience() && minecraft->player->experienceLevel > 0) - { - if (true) - { - bool blink = false; - int col = blink ? 0xffffff : 0x80ff20; - wchar_t formatted[10]; - swprintf(formatted, 10, L"%d",minecraft->player->experienceLevel); + // Moved so the opacity blend is applied to it + if (bDisplayGui && minecraft->gameMode->hasExperience() && + minecraft->player->experienceLevel > 0) { + if (true) { + bool blink = false; + int col = blink ? 0xffffff : 0x80ff20; + wchar_t formatted[10]; + swprintf(formatted, 10, L"%d", minecraft->player->experienceLevel); - std::wstring str = formatted; - int x = iWidthOffset + (screenWidth - font->width(str)) / 2; - int y = screenHeight - iSafezoneYHalf - iTooltipsYOffset; - // If we're in creative mode, we don't need to offset the XP display so much - if (minecraft->gameMode->canHurtPlayer()) - { - y-=18; - } - else - { - y-=13; - } - - if(bTwoPlayerSplitscreen) - { - y+=iHeightOffset; - } - //int y = screenHeight - 31 - 4; - font->draw(str, x + 1, y, 0x000000); - font->draw(str, x - 1, y, 0x000000); - font->draw(str, x, y + 1, 0x000000); - font->draw(str, x, y - 1, 0x000000); - // font->draw(str, x + 1, y + 1, 0x000000); - // font->draw(str, x - 1, y + 1, 0x000000); - // font->draw(str, x + 1, y - 1, 0x000000); - // font->draw(str, x - 1, y - 1, 0x000000); - font->draw(str, x, y, col); - } - } -#endif // RENDER_HUD + std::wstring str = formatted; + int x = iWidthOffset + (screenWidth - font->width(str)) / 2; + int y = screenHeight - iSafezoneYHalf - iTooltipsYOffset; + // If we're in creative mode, we don't need to offset the XP display + // so much + if (minecraft->gameMode->canHurtPlayer()) { + y -= 18; + } else { + y -= 13; + } - // 4J - added to disable blends, which we have enabled previously to allow gui fading - glDisable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (bTwoPlayerSplitscreen) { + y += iHeightOffset; + } + // int y = screenHeight - 31 - 4; + font->draw(str, x + 1, y, 0x000000); + font->draw(str, x - 1, y, 0x000000); + font->draw(str, x, y + 1, 0x000000); + font->draw(str, x, y - 1, 0x000000); + // font->draw(str, x + 1, y + 1, 0x000000); + // font->draw(str, x - 1, y + 1, 0x000000); + // font->draw(str, x + 1, y - 1, 0x000000); + // font->draw(str, x - 1, y - 1, 0x000000); + font->draw(str, x, y, col); + } + } +#endif // RENDER_HUD + + // 4J - added to disable blends, which we have enabled previously to allow + // gui fading + glDisable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // if the player is falling asleep we render a dark overlay - if (minecraft->player->getSleepTimer() > 0) - { + if (minecraft->player->getSleepTimer() > 0) { glDisable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); int timer = minecraft->player->getSleepTimer(); - float amount = (float) timer / (float) Player::SLEEP_DURATION; - if (amount > 1) - { + float amount = (float)timer / (float)Player::SLEEP_DURATION; + if (amount > 1) { // waking up - amount = 1.0f - ((float) (timer - Player::SLEEP_DURATION) / (float) Player::WAKE_UP_DURATION); + amount = 1.0f - ((float)(timer - Player::SLEEP_DURATION) / + (float)Player::WAKE_UP_DURATION); } - int color = (int) (220.0f * amount) << 24 | (0x101020); - fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); + int color = (int)(220.0f * amount) << 24 | (0x101020); + fill(0, 0, screenWidth / fScaleFactorWidth, + screenHeight / fScaleFactorHeight, color); glEnable(GL_ALPHA_TEST); glEnable(GL_DEPTH_TEST); } - // 4J-PB - Request from Mojang to have a red death screen - if (!minecraft->player->isAlive()) - { - glDisable(GL_DEPTH_TEST); - glDisable(GL_ALPHA_TEST); - int timer = minecraft->player->getDeathFadeTimer(); - float amount = (float) timer / (float) Player::DEATHFADE_DURATION; + // 4J-PB - Request from Mojang to have a red death screen + if (!minecraft->player->isAlive()) { + glDisable(GL_DEPTH_TEST); + glDisable(GL_ALPHA_TEST); + int timer = minecraft->player->getDeathFadeTimer(); + float amount = (float)timer / (float)Player::DEATHFADE_DURATION; - int color = (int) (220.0f * amount) << 24 | (0x200000); - fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); - glEnable(GL_ALPHA_TEST); - glEnable(GL_DEPTH_TEST); + int color = (int)(220.0f * amount) << 24 | (0x200000); + fill(0, 0, screenWidth / fScaleFactorWidth, + screenHeight / fScaleFactorHeight, color); + glEnable(GL_ALPHA_TEST); + glEnable(GL_DEPTH_TEST); + } - } - - - // { - // String str = "" + minecraft.player.getFoodData().getExhaustionLevel() + ", " + minecraft.player.getFoodData().getSaturationLevel(); - // int x = (screenWidth - font.width(str)) / 2; - // int y = screenHeight - 64; - // font.draw(str, x + 1, y, 0xffffff); - // } + // { + // String str = "" + + // minecraft.player.getFoodData().getExhaustionLevel() + ", " + + // minecraft.player.getFoodData().getSaturationLevel(); int x = + // (screenWidth - font.width(str)) / 2; int y = screenHeight - + // 64; font.draw(str, x + 1, y, 0xffffff); + // } #ifndef _FINAL_BUILD - MemSect(31); - if (minecraft->options->renderDebug) - { + MemSect(31); + if (minecraft->options->renderDebug) { glPushMatrix(); if (Minecraft::warezTime > 0) glTranslatef(0, 32, 0); - font->drawShadow(ClientConstants::VERSION_STRING + L" (" + minecraft->fpsString + L")", iSafezoneXHalf+2, 20, 0xffffff); - font->drawShadow(L"Seed: " + _toString<__int64>(minecraft->level->getLevelData()->getSeed() ), iSafezoneXHalf+2, 32 + 00, 0xffffff); - font->drawShadow(minecraft->gatherStats1(), iSafezoneXHalf+2, 32 + 10, 0xffffff); - font->drawShadow(minecraft->gatherStats2(), iSafezoneXHalf+2, 32 + 20, 0xffffff); - font->drawShadow(minecraft->gatherStats3(), iSafezoneXHalf+2, 32 + 30, 0xffffff); - font->drawShadow(minecraft->gatherStats4(), iSafezoneXHalf+2, 32 + 40, 0xffffff); + font->drawShadow(ClientConstants::VERSION_STRING + L" (" + + minecraft->fpsString + L")", + iSafezoneXHalf + 2, 20, 0xffffff); + font->drawShadow( + L"Seed: " + + _toString<__int64>(minecraft->level->getLevelData()->getSeed()), + iSafezoneXHalf + 2, 32 + 00, 0xffffff); + font->drawShadow(minecraft->gatherStats1(), iSafezoneXHalf + 2, 32 + 10, + 0xffffff); + font->drawShadow(minecraft->gatherStats2(), iSafezoneXHalf + 2, 32 + 20, + 0xffffff); + font->drawShadow(minecraft->gatherStats3(), iSafezoneXHalf + 2, 32 + 30, + 0xffffff); + font->drawShadow(minecraft->gatherStats4(), iSafezoneXHalf + 2, 32 + 40, + 0xffffff); - // TERRAIN FEATURES - int iYPos=82; + // TERRAIN FEATURES + int iYPos = 82; - if(minecraft->level->dimension->id==0) - { - std::wstring wfeature[eTerrainFeature_Count]; + if (minecraft->level->dimension->id == 0) { + std::wstring wfeature[eTerrainFeature_Count]; - wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; - wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; - wfeature[eTerrainFeature_Village] = L"Village: "; - wfeature[eTerrainFeature_Ravine] = L"Ravine: "; + wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; + wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; + wfeature[eTerrainFeature_Village] = L"Village: "; + wfeature[eTerrainFeature_Ravine] = L"Ravine: "; - for(int i=0;i( pFeatureData->x*16 ) + L", " + _toString( pFeatureData->z*16 ) + L"] "; - wfeature[pFeatureData->eTerrainFeature] += itemInfo; - } + std::wstring itemInfo = + L"[" + _toString(pFeatureData->x * 16) + L", " + + _toString(pFeatureData->z * 16) + L"] "; + wfeature[pFeatureData->eTerrainFeature] += itemInfo; + } - for( int i = eTerrainFeature_Stronghold; i < (int) eTerrainFeature_Count; i++ ) - { - font->drawShadow(wfeature[i], iSafezoneXHalf + 2, iYPos, 0xffffff); - iYPos+=10; - } - } - - //font->drawShadow(minecraft->gatherStats5(), iSafezoneXHalf+2, 32 + 10, 0xffffff); - { - /* 4J - removed - long max = Runtime.getRuntime().maxMemory(); - long total = Runtime.getRuntime().totalMemory(); - long free = Runtime.getRuntime().freeMemory(); - long used = total - free; - String msg = "Used memory: " + (used * 100 / max) + "% (" + (used / 1024 / 1024) + "MB) of " + (max / 1024 / 1024) + "MB"; - drawString(font, msg, screenWidth - font.width(msg) - 2, 2, 0xe0e0e0); - msg = "Allocated memory: " + (total * 100 / max) + "% (" + (total / 1024 / 1024) + "MB)"; - drawString(font, msg, screenWidth - font.width(msg) - 2, 12, 0xe0e0e0); - */ + for (int i = eTerrainFeature_Stronghold; + i < (int)eTerrainFeature_Count; i++) { + font->drawShadow(wfeature[i], iSafezoneXHalf + 2, iYPos, + 0xffffff); + iYPos += 10; + } } - // 4J Stu - Moved these so that they don't overlap - double xBlockPos = floor(minecraft->player->x); - double yBlockPos = floor(minecraft->player->y); - double zBlockPos = floor(minecraft->player->z); - drawString(font, L"x: " + _toString(minecraft->player->x) + L"/ Head: " + _toString(xBlockPos) + L"/ Chunk: " + _toString(minecraft->player->xChunk), iSafezoneXHalf+2, iYPos + 8 * 0, 0xe0e0e0); - drawString(font, L"y: " + _toString(minecraft->player->y) + L"/ Head: " + _toString(yBlockPos), iSafezoneXHalf+2, iYPos + 8 * 1, 0xe0e0e0); - drawString(font, L"z: " + _toString(minecraft->player->z) + L"/ Head: " + _toString(zBlockPos) + L"/ Chunk: " + _toString(minecraft->player->zChunk), iSafezoneXHalf+2, iYPos + 8 * 2, 0xe0e0e0); - drawString(font, L"f: " + _toString(Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3) + L"/ yRot: " + _toString(minecraft->player->yRot), iSafezoneXHalf+2, iYPos + 8 * 3, 0xe0e0e0); - iYPos += 8*4; - int px = Mth::floor(minecraft->player->x); - int py = Mth::floor(minecraft->player->y); - int pz = Mth::floor(minecraft->player->z); - if (minecraft->level != NULL && minecraft->level->hasChunkAt(px, py, pz)) - { - LevelChunk *chunkAt = minecraft->level->getChunkAt(px, pz); - Biome *biome = chunkAt->getBiome(px & 15, pz & 15, minecraft->level->getBiomeSource()); - drawString( - font, - L"b: " + biome->m_name + L" (" + _toString(biome->id) + L")", iSafezoneXHalf+2, iYPos, 0xe0e0e0); - } + // font->drawShadow(minecraft->gatherStats5(), iSafezoneXHalf+2, 32 + + // 10, 0xffffff); + { + /* 4J - removed +long max = Runtime.getRuntime().maxMemory(); +long total = Runtime.getRuntime().totalMemory(); +long free = Runtime.getRuntime().freeMemory(); +long used = total - free; +String msg = "Used memory: " + (used * 100 / max) + "% (" + (used / 1024 / 1024) ++ "MB) of " + (max / 1024 / 1024) + "MB"; drawString(font, msg, screenWidth - +font.width(msg) - 2, 2, 0xe0e0e0); msg = "Allocated memory: " + (total * 100 / +max) + "% (" + (total / 1024 / 1024) + "MB)"; drawString(font, msg, screenWidth +- font.width(msg) - 2, 12, 0xe0e0e0); + */ + } + // 4J Stu - Moved these so that they don't overlap + double xBlockPos = floor(minecraft->player->x); + double yBlockPos = floor(minecraft->player->y); + double zBlockPos = floor(minecraft->player->z); + drawString(font, + L"x: " + _toString(minecraft->player->x) + + L"/ Head: " + _toString(xBlockPos) + + L"/ Chunk: " + + _toString(minecraft->player->xChunk), + iSafezoneXHalf + 2, iYPos + 8 * 0, 0xe0e0e0); + drawString(font, + L"y: " + _toString(minecraft->player->y) + + L"/ Head: " + _toString(yBlockPos), + iSafezoneXHalf + 2, iYPos + 8 * 1, 0xe0e0e0); + drawString(font, + L"z: " + _toString(minecraft->player->z) + + L"/ Head: " + _toString(zBlockPos) + + L"/ Chunk: " + + _toString(minecraft->player->zChunk), + iSafezoneXHalf + 2, iYPos + 8 * 2, 0xe0e0e0); + drawString( + font, + L"f: " + + _toString( + Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & + 0x3) + + L"/ yRot: " + _toString(minecraft->player->yRot), + iSafezoneXHalf + 2, iYPos + 8 * 3, 0xe0e0e0); + iYPos += 8 * 4; + + int px = Mth::floor(minecraft->player->x); + int py = Mth::floor(minecraft->player->y); + int pz = Mth::floor(minecraft->player->z); + if (minecraft->level != NULL && + minecraft->level->hasChunkAt(px, py, pz)) { + LevelChunk* chunkAt = minecraft->level->getChunkAt(px, pz); + Biome* biome = chunkAt->getBiome( + px & 15, pz & 15, minecraft->level->getBiomeSource()); + drawString(font, + L"b: " + biome->m_name + L" (" + + _toString(biome->id) + L")", + iSafezoneXHalf + 2, iYPos, 0xe0e0e0); + } glPopMatrix(); } - MemSect(0); + MemSect(0); #endif - lastTickA = a; - // 4J Stu - This is now displayed in a xui scene + lastTickA = a; + // 4J Stu - This is now displayed in a xui scene #if 0 // Jukebox CD message if (overlayMessageTime > 0) @@ -894,11 +974,10 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } } #endif - + unsigned int max = 10; bool isChatting = false; - if (dynamic_cast(minecraft->screen) != NULL) - { + if (dynamic_cast(minecraft->screen) != NULL) { max = 20; isChatting = true; } @@ -954,7 +1033,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glPopMatrix(); #endif - // 4J Stu - Copied over but not used + // 4J Stu - Copied over but not used #if 0 if (minecraft.player instanceof MultiplayerLocalPlayer && minecraft.options.keyPlayerList.isDown) { @@ -1012,79 +1091,77 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } #endif - if(bDisplayGui && bTwoPlayerSplitscreen) - { - // pop the scaled matrix - glPopMatrix(); - } + if (bDisplayGui && bTwoPlayerSplitscreen) { + // pop the scaled matrix + glPopMatrix(); + } - glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - glEnable(GL_ALPHA_TEST); + glEnable(GL_ALPHA_TEST); } // Moved to the xui base scene // void Gui::renderBossHealth(void) // { // if (EnderDragonRenderer::bossInstance == NULL) return; -// +// // std::shared_ptr boss = EnderDragonRenderer::bossInstance; // EnderDragonRenderer::bossInstance = NULL; -// +// // Minecraft *pMinecraft=Minecraft::GetInstance(); -// +// // Font *font = pMinecraft->font; -// -// ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); -// int screenWidth = ssc.getWidth(); -// +// +// ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, +// pMinecraft->height_phys); int screenWidth = ssc.getWidth(); +// // int w = 182; // int xLeft = screenWidth / 2 - w / 2; -// -// int progress = (int) (boss->getSynchedHealth() / (float) boss->getMaxHealth() * (float) (w + 1)); -// +// +// int progress = (int) (boss->getSynchedHealth() / (float) +// boss->getMaxHealth() * (float) (w + 1)); +// // int yo = 12; // blit(xLeft, yo, 0, 74, w, 5); // blit(xLeft, yo, 0, 74, w, 5); -// if (progress > 0) +// if (progress > 0) // { // blit(xLeft, yo, 0, 79, progress, 5); // } -// +// // std::wstring msg = L"Boss health - NON LOCALISED"; -// font->drawShadow(msg, screenWidth / 2 - font->width(msg) / 2, yo - 10, 0xff00ff); -// glColor4f(1, 1, 1, 1); -// glBindTexture(GL_TEXTURE_2D, pMinecraft->textures->loadTexture(TN_GUI_ICONS) );//"/gui/icons.png")); -// +// font->drawShadow(msg, screenWidth / 2 - font->width(msg) / 2, yo - 10, +// 0xff00ff); glColor4f(1, 1, 1, 1); glBindTexture(GL_TEXTURE_2D, +// pMinecraft->textures->loadTexture(TN_GUI_ICONS) );//"/gui/icons.png")); +// // } -void Gui::renderPumpkin(int w, int h) -{ +void Gui::renderPumpkin(int w, int h) { glDisable(GL_DEPTH_TEST); glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, 1); glDisable(GL_ALPHA_TEST); - MemSect(31); - minecraft->textures->bindTexture(TN__BLUR__MISC_PUMPKINBLUR);//L"%blur%/misc/pumpkinblur.png")); - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + minecraft->textures->bindTexture( + TN__BLUR__MISC_PUMPKINBLUR); // L"%blur%/misc/pumpkinblur.png")); + MemSect(0); + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( 0), (float)( 1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( 1), (float)( 1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( 1), (float)( 0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( 0), (float)( 0)); + t->vertexUV((float)(0), (float)(h), (float)(-90), (float)(0), (float)(1)); + t->vertexUV((float)(w), (float)(h), (float)(-90), (float)(1), (float)(1)); + t->vertexUV((float)(w), (float)(0), (float)(-90), (float)(1), (float)(0)); + t->vertexUV((float)(0), (float)(0), (float)(-90), (float)(0), (float)(0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); glEnable(GL_ALPHA_TEST); glColor4f(1, 1, 1, 1); - } - -void Gui::renderVignette(float br, int w, int h) -{ + +void Gui::renderVignette(float br, int w, int h) { br = 1 - br; if (br < 0) br = 0; if (br > 1) br = 1; @@ -1110,10 +1187,8 @@ void Gui::renderVignette(float br, int w, int h) #endif } -void Gui::renderTp(float br, int w, int h) -{ - if (br < 1) - { +void Gui::renderTp(float br, int w, int h) { + if (br < 1) { br = br * br; br = br * br; br = br * 0.8f + 0.2f; @@ -1124,401 +1199,368 @@ void Gui::renderTp(float br, int w, int h) glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, br); - MemSect(31); - minecraft->textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); - MemSect(0); - - Icon *slot = Tile::portalTile->getTexture(Facing::UP); + MemSect(31); + minecraft->textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + MemSect(0); + + Icon* slot = Tile::portalTile->getTexture(Facing::UP); float u0 = slot->getU0(); float v0 = slot->getV0(); float u1 = slot->getU1(); float v1 = slot->getV1(); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( u0), (float)( v1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( u1), (float)( v1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( u1), (float)( v0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( u0), (float)( v0)); + t->vertexUV((float)(0), (float)(h), (float)(-90), (float)(u0), (float)(v1)); + t->vertexUV((float)(w), (float)(h), (float)(-90), (float)(u1), (float)(v1)); + t->vertexUV((float)(w), (float)(0), (float)(-90), (float)(u1), (float)(v0)); + t->vertexUV((float)(0), (float)(0), (float)(-90), (float)(u0), (float)(v0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); glEnable(GL_ALPHA_TEST); glColor4f(1, 1, 1, 1); - } -void Gui::renderSlot(int slot, int x, int y, float a) -{ - std::shared_ptr item = minecraft->player->inventory->items[slot]; +void Gui::renderSlot(int slot, int x, int y, float a) { + std::shared_ptr item = + minecraft->player->inventory->items[slot]; if (item == NULL) return; float pop = item->popTime - a; - if (pop > 0) - { + if (pop > 0) { glPushMatrix(); - float squeeze = 1 + pop / (float) Inventory::POP_TIME_DURATION; + float squeeze = 1 + pop / (float)Inventory::POP_TIME_DURATION; glTranslatef((float)(x + 8), (float)(y + 12), 0); glScalef(1 / squeeze, (squeeze + 1) / 2, 1); glTranslatef((float)-(x + 8), (float)-(y + 12), 0); } - itemRenderer->renderAndDecorateItem(minecraft->font, minecraft->textures, item, x, y); + itemRenderer->renderAndDecorateItem(minecraft->font, minecraft->textures, + item, x, y); - if (pop > 0) - { + if (pop > 0) { glPopMatrix(); } - itemRenderer->renderGuiItemDecorations(minecraft->font, minecraft->textures, item, x, y); - + itemRenderer->renderGuiItemDecorations(minecraft->font, minecraft->textures, + item, x, y); } -void Gui::tick() -{ +void Gui::tick() { if (overlayMessageTime > 0) overlayMessageTime--; tickCount++; - for(int iPad=0;iPadlocalplayers[i]) - { - guiMessages[i].clear(); - } - } - } - else - { - guiMessages[iPad].clear(); - } -} - - -void Gui::addMessage(const std::wstring& _string,int iPad,bool bIsDeathMessage) -{ - std::wstring string = _string; // 4J - Take copy of input as it is const - //int iScale=1; - - //if((minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_TOP) || - // (minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) - //{ - // iScale=2; - //} - - // while (minecraft->font->width(string) > (m_iMaxMessageWidth*iScale)) - //{ - // unsigned int i = 1; - // while (i < string.length() && minecraft->font->width(string.substr(0, i + 1)) <= (m_iMaxMessageWidth*iScale)) - // { - // i++; - // } - // int iLast=string.find_last_of(L" ",i); - - // // if a space was found, include the space on this line - // if(iLast!=i) - // { - // iLast++; - // } - // addMessage(string.substr(0, iLast), iPad); - // string = string.substr(iLast); - // } - - int maximumChars; - - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - if(RenderManager.IsHiDef()) - { - maximumChars = 105; - } - else - { - maximumChars = 55; - } -#ifdef __PSVITA__ - maximumChars = 90; -#endif - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - if(RenderManager.IsHiDef()) - { - maximumChars = 70; - } - else - { - maximumChars = 35; - } -#ifdef __PSVITA__ - maximumChars = 55; -#endif - break; - } - break; - default: - maximumChars = 55; - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - maximumChars = 35; - break; - } - break; - } - - - while (string.length() > maximumChars) - { - unsigned int i = 1; - while (i < string.length() && (i + 1) <= maximumChars) - { - i++; + for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) { + // 4J Stu - Fix for #10929 - MP LAB: Network Disconnects: Host does not + // receive an error message stating the client left the game when + // viewing the Pause Menu. We don't show the guiMessages when a menu is + // up, so don't fade them out + if (!ui.GetMenuDisplayed(iPad)) { + AUTO_VAR(itEnd, guiMessages[iPad].end()); + for (AUTO_VAR(it, guiMessages[iPad].begin()); it != itEnd; it++) { + (*it).ticks++; + } } - int iLast=(int)string.find_last_of(L" ",i); - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - iLast = maximumChars; - break; - default: - iLast=(int)string.find_last_of(L" ",i); - break; - } + } +} - // if a space was found, include the space on this line - if(iLast!=i) - { - iLast++; - } - addMessage(string.substr(0, iLast), iPad, bIsDeathMessage); - string = string.substr(iLast); +void Gui::clearMessages(int iPad) { + if (iPad == -1) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + guiMessages[i].clear(); + } + } + } else { + guiMessages[iPad].clear(); + } +} + +void Gui::addMessage(const std::wstring& _string, int iPad, + bool bIsDeathMessage) { + std::wstring string = _string; // 4J - Take copy of input as it is const + // int iScale=1; + + // if((minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_TOP) + // || + // (minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) + //{ + // iScale=2; + // } + + // while (minecraft->font->width(string) > (m_iMaxMessageWidth*iScale)) + //{ + // unsigned int i = 1; + // while (i < string.length() && + // minecraft->font->width(string.substr(0, i + 1)) <= + // (m_iMaxMessageWidth*iScale)) + // { + // i++; + // } + // int iLast=string.find_last_of(L" ",i); + + // // if a space was found, include the space on this line + // if(iLast!=i) + // { + // iLast++; + // } + // addMessage(string.substr(0, iLast), iPad); + // string = string.substr(iLast); + // } + + int maximumChars; + + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + if (RenderManager.IsHiDef()) { + maximumChars = 105; + } else { + maximumChars = 55; + } +#ifdef __PSVITA__ + maximumChars = 90; +#endif + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + if (RenderManager.IsHiDef()) { + maximumChars = 70; + } else { + maximumChars = 35; + } +#ifdef __PSVITA__ + maximumChars = 55; +#endif + break; + } + break; + default: + maximumChars = 55; + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + maximumChars = 35; + break; + } + break; } - if(iPad==-1) - { - // add to all - for(int i=0;ilocalplayers[i] && !(bIsDeathMessage && app.GetGameSettings(i,eGameSetting_DeathMessages)==0)) - { - guiMessages[i].insert(guiMessages[i].begin(), GuiMessage(string)); - while (guiMessages[i].size() > 50) - { - guiMessages[i].pop_back(); - } - } - } - } - else if(!(bIsDeathMessage && app.GetGameSettings(iPad,eGameSetting_DeathMessages)==0)) - { - guiMessages[iPad].insert(guiMessages[iPad].begin(), GuiMessage(string)); - while (guiMessages[iPad].size() > 50) - { - guiMessages[iPad].pop_back(); - } - } + while (string.length() > maximumChars) { + unsigned int i = 1; + while (i < string.length() && (i + 1) <= maximumChars) { + i++; + } + int iLast = (int)string.find_last_of(L" ", i); + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + iLast = maximumChars; + break; + default: + iLast = (int)string.find_last_of(L" ", i); + break; + } + // if a space was found, include the space on this line + if (iLast != i) { + iLast++; + } + addMessage(string.substr(0, iLast), iPad, bIsDeathMessage); + string = string.substr(iLast); + } + if (iPad == -1) { + // add to all + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i] && + !(bIsDeathMessage && + app.GetGameSettings(i, eGameSetting_DeathMessages) == 0)) { + guiMessages[i].insert(guiMessages[i].begin(), + GuiMessage(string)); + while (guiMessages[i].size() > 50) { + guiMessages[i].pop_back(); + } + } + } + } else if (!(bIsDeathMessage && + app.GetGameSettings(iPad, eGameSetting_DeathMessages) == 0)) { + guiMessages[iPad].insert(guiMessages[iPad].begin(), GuiMessage(string)); + while (guiMessages[iPad].size() > 50) { + guiMessages[iPad].pop_back(); + } + } } // 4J Added -float Gui::getOpacity(int iPad, std::size_t index) -{ - float opacityPercentage = 0; - if (guiMessages[iPad].size() > index && guiMessages[iPad][index].ticks < 20 * 10) - { - double t = guiMessages[iPad][index].ticks / (20 * 10.0); - t = 1 - t; - t = t * 10; - if (t < 0) t = 0; - if (t > 1) t = 1; - t = t * t; - opacityPercentage = t; - } - return opacityPercentage; +float Gui::getOpacity(int iPad, std::size_t index) { + float opacityPercentage = 0; + if (guiMessages[iPad].size() > index && + guiMessages[iPad][index].ticks < 20 * 10) { + double t = guiMessages[iPad][index].ticks / (20 * 10.0); + t = 1 - t; + t = t * 10; + if (t < 0) t = 0; + if (t > 1) t = 1; + t = t * t; + opacityPercentage = t; + } + return opacityPercentage; } -float Gui::getJukeboxOpacity(int iPad) -{ - float t = overlayMessageTime - lastTickA; - int alpha = (int) (t * 256 / 20); +float Gui::getJukeboxOpacity(int iPad) { + float t = overlayMessageTime - lastTickA; + int alpha = (int)(t * 256 / 20); if (alpha > 255) alpha = 255; - alpha /= 255; + alpha /= 255; - return alpha; + return alpha; } -void Gui::setNowPlaying(const std::wstring& string) -{ -// overlayMessageString = L"Now playing: " + string; - overlayMessageString = app.GetString(IDS_NOWPLAYING) + string; +void Gui::setNowPlaying(const std::wstring& string) { + // overlayMessageString = L"Now playing: " + string; + overlayMessageString = app.GetString(IDS_NOWPLAYING) + string; overlayMessageTime = 20 * 3; animateOverlayMessageColor = true; } -void Gui::displayClientMessage(int messageId, int iPad) -{ - //Language *language = Language::getInstance(); - std::wstring languageString = app.GetString(messageId);//language->getElement(messageId); +void Gui::displayClientMessage(int messageId, int iPad) { + // Language *language = Language::getInstance(); + std::wstring languageString = + app.GetString(messageId); // language->getElement(messageId); addMessage(languageString, iPad); } // 4J Added -void Gui::renderGraph(int dataLength, int dataPos, __int64 *dataA, float dataAScale, int dataAWarning, __int64 *dataB, float dataBScale, int dataBWarning) -{ - int height = minecraft->height; - // This causes us to cover xScale*dataLength pixels in the horizontal - int xScale = 1; - if(dataA != NULL && dataB != NULL) xScale = 2; +void Gui::renderGraph(int dataLength, int dataPos, __int64* dataA, + float dataAScale, int dataAWarning, __int64* dataB, + float dataBScale, int dataBWarning) { + int height = minecraft->height; + // This causes us to cover xScale*dataLength pixels in the horizontal + int xScale = 1; + if (dataA != NULL && dataB != NULL) xScale = 2; - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINES); - for (int i = 0; i < dataLength; i++) - { - int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; + t->begin(GL_LINES); + for (int i = 0; i < dataLength; i++) { + int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; - if( dataA != NULL ) - { - if (dataA[i] > dataAWarning) - { - t->color(0xff000000 + cc * 65536); - } - else - { - t->color(0xff000000 + cc * 256); - } + if (dataA != NULL) { + if (dataA[i] > dataAWarning) { + t->color(0xff000000 + cc * 65536); + } else { + t->color(0xff000000 + cc * 256); + } - __int64 aVal = dataA[i] / dataAScale; + __int64 aVal = dataA[i] / dataAScale; - t->vertex((float)(xScale*i + 0.5f), (float)( height - aVal + 0.5f), (float)( 0)); - t->vertex((float)(xScale*i + 0.5f), (float)( height + 0.5f), (float)( 0)); - } - - if( dataB != NULL ) - { - if (dataB[i]>dataBWarning) - { - t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); - } - else - { - t->color(0xff808080 + cc/2 * 256); - } + t->vertex((float)(xScale * i + 0.5f), (float)(height - aVal + 0.5f), + (float)(0)); + t->vertex((float)(xScale * i + 0.5f), (float)(height + 0.5f), + (float)(0)); + } - __int64 bVal = dataB[i] / dataBScale; + if (dataB != NULL) { + if (dataB[i] > dataBWarning) { + t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); + } else { + t->color(0xff808080 + cc / 2 * 256); + } - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height - bVal + 0.5f), (float)( 0)); - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height + 0.5f), (float)( 0)); - } - } - t->end(); + __int64 bVal = dataB[i] / dataBScale; - glEnable(GL_TEXTURE_2D); + t->vertex((float)(xScale * i + (xScale - 1) + 0.5f), + (float)(height - bVal + 0.5f), (float)(0)); + t->vertex((float)(xScale * i + (xScale - 1) + 0.5f), + (float)(height + 0.5f), (float)(0)); + } + } + t->end(); + + glEnable(GL_TEXTURE_2D); } -void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, __int64 (*func)(unsigned int dataPos, unsigned int dataSource) ) -{ - int height = minecraft->height; +void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, + __int64 (*func)(unsigned int dataPos, + unsigned int dataSource)) { + int height = minecraft->height; - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINES); - __int64 thisVal = 0; - __int64 topVal = 0; - for (int i = 0; i < dataLength; i++) - { - thisVal = 0; - topVal = 0; - int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; + t->begin(GL_LINES); + __int64 thisVal = 0; + __int64 topVal = 0; + for (int i = 0; i < dataLength; i++) { + thisVal = 0; + topVal = 0; + int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; + for (unsigned int source = 0; source < dataSources; ++source) { + thisVal = func(i, source); - for(unsigned int source = 0; source < dataSources; ++source ) - { - thisVal = func( i, source ); + if (thisVal > 0) { + float vary = (float)source / dataSources; + int fColour = floor(vary * 0xffffff); - if( thisVal > 0 ) - { - float vary = (float)source/dataSources; - int fColour = floor(vary * 0xffffff); + int colour = 0xff000000 + fColour; + // printf("Colour is %x\n", colour); + t->color(colour); - int colour = 0xff000000 + fColour; - //printf("Colour is %x\n", colour); - t->color(colour); + t->vertex((float)(i + 0.5f), + (float)(height - topVal - thisVal + 0.5f), + (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height - topVal + 0.5f), + (float)(0)); - t->vertex((float)(i + 0.5f), (float)( height - topVal - thisVal + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - topVal + 0.5f), (float)( 0)); + topVal += thisVal; + } + } - topVal += thisVal; - } - } + // Draw some horizontals + for (unsigned int horiz = 1; horiz < 7; ++horiz) { + t->color(0xff000000); - // Draw some horizontals - for(unsigned int horiz = 1; horiz < 7; ++horiz ) - { - t->color(0xff000000); + t->vertex((float)(0 + 0.5f), (float)(height - (horiz * 100) + 0.5f), + (float)(0)); + t->vertex((float)(dataLength + 0.5f), + (float)(height - (horiz * 100) + 0.5f), (float)(0)); + } + } + t->end(); - t->vertex((float)(0 + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); - t->vertex((float)(dataLength + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); - } - } - t->end(); - - glEnable(GL_TEXTURE_2D); + glEnable(GL_TEXTURE_2D); } diff --git a/Minecraft.Client/UI/Gui.h b/Minecraft.Client/UI/Gui.h index 725a3b4c6..fc5767e1f 100644 --- a/Minecraft.Client/UI/Gui.h +++ b/Minecraft.Client/UI/Gui.h @@ -6,64 +6,75 @@ class Random; class Minecraft; class ItemRenderer; -class Gui : public GuiComponent -{ +class Gui : public GuiComponent { private: - // 4J-PB - this doesn't account for the safe zone, and the indent applied to messages - //static const int MAX_MESSAGE_WIDTH = 320; - static const int m_iMaxMessageWidth = 280; - static ItemRenderer *itemRenderer; + // 4J-PB - this doesn't account for the safe zone, and the indent applied to + // messages + // static const int MAX_MESSAGE_WIDTH = 320; + static const int m_iMaxMessageWidth = 280; + static ItemRenderer* itemRenderer; std::vector guiMessages[XUSER_MAX_COUNT]; - Random *random; + Random* random; + + Minecraft* minecraft; - Minecraft *minecraft; public: - std::wstring selectedName; + std::wstring selectedName; + private: - int tickCount; + int tickCount; std::wstring overlayMessageString; int overlayMessageTime; bool animateOverlayMessageColor; - // 4J Added - float lastTickA; - float fAlphaIncrementPerCent; -public: - static float currentGuiBlendFactor; // 4J added - static float currentGuiScaleFactor; // 4J added - - float progress; - -// private DecimalFormat df = new DecimalFormat("##.00"); + // 4J Added + float lastTickA; + float fAlphaIncrementPerCent; public: - Gui(Minecraft *minecraft); + static float currentGuiBlendFactor; // 4J added + static float currentGuiScaleFactor; // 4J added - void render(float a, bool mouseFree, int xMouse, int yMouse); + float progress; + + // private DecimalFormat df = new DecimalFormat("##.00"); + +public: + Gui(Minecraft* minecraft); + + void render(float a, bool mouseFree, int xMouse, int yMouse); float tbr; private: - //void renderBossHealth(void); - void renderPumpkin(int w, int h); + // void renderBossHealth(void); + void renderPumpkin(int w, int h); void renderVignette(float br, int w, int h); void renderTp(float br, int w, int h); void renderSlot(int slot, int x, int y, float a); + public: - void tick(); - void clearMessages(int iPad=-1); - void addMessage(const std::wstring& string, int iPad,bool bIsDeathMessage=false); + void tick(); + void clearMessages(int iPad = -1); + void addMessage(const std::wstring& string, int iPad, + bool bIsDeathMessage = false); void setNowPlaying(const std::wstring& string); void displayClientMessage(int messageId, int iPad); - // 4J Added - std::size_t getMessagesCount(int iPad) { return guiMessages[iPad].size(); } - std::wstring getMessage(int iPad, std::size_t index) { return guiMessages[iPad].at(index).string; } - float getOpacity(int iPad, std::size_t index); + // 4J Added + std::size_t getMessagesCount(int iPad) { return guiMessages[iPad].size(); } + std::wstring getMessage(int iPad, std::size_t index) { + return guiMessages[iPad].at(index).string; + } + float getOpacity(int iPad, std::size_t index); - std::wstring getJukeboxMessage(int iPad) { return overlayMessageString; } - float getJukeboxOpacity(int iPad); + std::wstring getJukeboxMessage(int iPad) { return overlayMessageString; } + float getJukeboxOpacity(int iPad); - // 4J Added - void renderGraph(int dataLength, int dataPos, __int64 *dataA, float dataAScale, int dataAWarning, __int64 *dataB, float dataBScale, int dataBWarning); - void renderStackedGraph(int dataPos, int dataLength, int dataSources, __int64 (*func)(unsigned int dataPos, unsigned int dataSource) ); + // 4J Added + void renderGraph(int dataLength, int dataPos, __int64* dataA, + float dataAScale, int dataAWarning, __int64* dataB, + float dataBScale, int dataBWarning); + void renderStackedGraph(int dataPos, int dataLength, int dataSources, + __int64 (*func)(unsigned int dataPos, + unsigned int dataSource)); }; diff --git a/Minecraft.Client/UI/GuiComponent.cpp b/Minecraft.Client/UI/GuiComponent.cpp index 460cf6fa1..d9149f2c8 100644 --- a/Minecraft.Client/UI/GuiComponent.cpp +++ b/Minecraft.Client/UI/GuiComponent.cpp @@ -2,10 +2,8 @@ #include "GuiComponent.h" #include "../Rendering/Tesselator.h" -void GuiComponent::hLine(int x0, int x1, int y, int col) -{ - if (x1 < x0) - { +void GuiComponent::hLine(int x0, int x1, int y, int col) { + if (x1 < x0) { int tmp = x0; x0 = x1; x1 = tmp; @@ -13,10 +11,8 @@ void GuiComponent::hLine(int x0, int x1, int y, int col) fill(x0, y, x1 + 1, y + 1, col); } -void GuiComponent::vLine(int x, int y0, int y1, int col) -{ - if (y1 < y0) - { +void GuiComponent::vLine(int x, int y0, int y1, int col) { + if (y1 < y0) { int tmp = y0; y0 = y1; y1 = tmp; @@ -24,16 +20,13 @@ void GuiComponent::vLine(int x, int y0, int y1, int col) fill(x, y0 + 1, x + 1, y1, col); } -void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) -{ - if (x0 < x1) - { +void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) { + if (x0 < x1) { int tmp = x0; x0 = x1; x1 = tmp; } - if (y0 < y1) - { + if (y0 < y1) { int tmp = y0; y0 = y1; y1 = tmp; @@ -42,23 +35,23 @@ void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) float r = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glEnable(GL_BLEND); glDisable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(r, g, b, a); t->begin(); - t->vertex((float)(x0), (float)( y1), (float)( 0)); - t->vertex((float)(x1), (float)( y1), (float)( 0)); - t->vertex((float)(x1), (float)( y0), (float)( 0)); - t->vertex((float)(x0), (float)( y0), (float)( 0)); + t->vertex((float)(x0), (float)(y1), (float)(0)); + t->vertex((float)(x1), (float)(y1), (float)(0)); + t->vertex((float)(x1), (float)(y0), (float)(0)); + t->vertex((float)(x0), (float)(y0), (float)(0)); t->end(); glEnable(GL_TEXTURE_2D); glDisable(GL_BLEND); } -void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int col2) -{ +void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, + int col2) { float a1 = ((col1 >> 24) & 0xff) / 255.0f; float r1 = ((col1 >> 16) & 0xff) / 255.0f; float g1 = ((col1 >> 8) & 0xff) / 255.0f; @@ -74,14 +67,14 @@ void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int co glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_SMOOTH); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); t->color(r1, g1, b1, a1); - t->vertex((float)(x1), (float)( y0), blitOffset); - t->vertex((float)(x0), (float)( y0), blitOffset); + t->vertex((float)(x1), (float)(y0), blitOffset); + t->vertex((float)(x0), (float)(y0), blitOffset); t->color(r2, g2, b2, a2); - t->vertex((float)(x0), (float)( y1), blitOffset); - t->vertex((float)(x1), (float)( y1), blitOffset); + t->vertex((float)(x0), (float)(y1), blitOffset); + t->vertex((float)(x1), (float)(y1), blitOffset); t->end(); glShadeModel(GL_FLAT); @@ -90,47 +83,62 @@ void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int co glEnable(GL_TEXTURE_2D); } -GuiComponent::GuiComponent() -{ - blitOffset = 0; +GuiComponent::GuiComponent() { blitOffset = 0; } + +void GuiComponent::drawCenteredString(Font* font, const std::wstring& str, + int x, int y, int color) { + font->drawShadow(str, x - (font->width(str)) / 2, y, color); } -void GuiComponent::drawCenteredString(Font *font, const std::wstring& str, int x, int y, int color) -{ - font->drawShadow(str, x - (font->width(str)) / 2, y, color); +void GuiComponent::drawString(Font* font, const std::wstring& str, int x, int y, + int color) { + font->drawShadow(str, x, y, color); } -void GuiComponent::drawString(Font *font, const std::wstring& str, int x, int y, int color) -{ - font->drawShadow(str, x, y, color); -} - -void GuiComponent::blit(int x, int y, int sx, int sy, int w, int h) -{ +void GuiComponent::blit(int x, int y, int sx, int sy, int w, int h) { float us = 1 / 256.0f; float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); - // This is a bit of a mystery. In general this ought to be 0.5 to match the centre of texels & pixels in the DX9 version of things. However, when scaling the GUI by a factor of 1.5, I'm - // really not sure how exactly point sampled rasterisation works, but when shifting by 0.5 we get a discontinuity down the diagonal of quads. Setting this shift to 0.75 in all cases seems to work fine. - const float extraShift = 0.75f; + // This is a bit of a mystery. In general this ought to be 0.5 to match the + // centre of texels & pixels in the DX9 version of things. However, when + // scaling the GUI by a factor of 1.5, I'm really not sure how exactly point + // sampled rasterisation works, but when shifting by 0.5 we get a + // discontinuity down the diagonal of quads. Setting this shift to 0.75 in + // all cases seems to work fine. + const float extraShift = 0.75f; - // 4J - subtracting extraShift (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float dx = ( extraShift * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; - // 4J - Also factor in the scaling from gui coordinate space to the screen. This varies based on user-selected gui scale, and whether we are in a viewport mode or not - dx /= Gui::currentGuiScaleFactor; - float dy = extraShift / Gui::currentGuiScaleFactor; - // Ensure that the x/y, width and height are actually pixel aligned at our current scale factor - in particular, for split screen mode with the default (3X) - // scale, we have an overall scale factor of 3 * 0.5 = 1.5, and so any odd pixels won't align - float fx = (floorf((float)x * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fy = (floorf((float)y * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fw = (floorf((float)w * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fh = (floorf((float)h * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; + // 4J - subtracting extraShift (actual screen pixels, so need to compensate + // for physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float dx = (extraShift * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; + // 4J - Also factor in the scaling from gui coordinate space to the screen. + // This varies based on user-selected gui scale, and whether we are in a + // viewport mode or not + dx /= Gui::currentGuiScaleFactor; + float dy = extraShift / Gui::currentGuiScaleFactor; + // Ensure that the x/y, width and height are actually pixel aligned at our + // current scale factor - in particular, for split screen mode with the + // default (3X) scale, we have an overall scale factor of 3 * 0.5 = 1.5, and + // so any odd pixels won't align + float fx = (floorf((float)x * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fy = (floorf((float)y * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fw = (floorf((float)w * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fh = (floorf((float)h * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; - t->vertexUV(fx + 0 - dx, fy + fh - dy, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); - t->vertexUV(fx + fw - dx, fy + fh - dy, (float)( blitOffset), (float)( (sx + w) * us), (float)( (sy + h) * vs)); - t->vertexUV(fx + fw - dx, fy + 0 - dy, (float)( blitOffset), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); - t->vertexUV(fx + 0 - dx, fy + 0 - dy, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); + t->vertexUV(fx + 0 - dx, fy + fh - dy, (float)(blitOffset), + (float)((sx + 0) * us), (float)((sy + h) * vs)); + t->vertexUV(fx + fw - dx, fy + fh - dy, (float)(blitOffset), + (float)((sx + w) * us), (float)((sy + h) * vs)); + t->vertexUV(fx + fw - dx, fy + 0 - dy, (float)(blitOffset), + (float)((sx + w) * us), (float)((sy + 0) * vs)); + t->vertexUV(fx + 0 - dx, fy + 0 - dy, (float)(blitOffset), + (float)((sx + 0) * us), (float)((sy + 0) * vs)); t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/UI/GuiComponent.h b/Minecraft.Client/UI/GuiComponent.h index 71324d0e3..fe7ece730 100644 --- a/Minecraft.Client/UI/GuiComponent.h +++ b/Minecraft.Client/UI/GuiComponent.h @@ -1,19 +1,21 @@ #pragma once class Font; +class GuiComponent { +protected: + float blitOffset; -class GuiComponent -{ protected: - float blitOffset; -protected: - void hLine(int x0, int x1, int y, int col); + void hLine(int x0, int x1, int y, int col); void vLine(int x, int y0, int y1, int col); void fill(int x0, int y0, int x1, int y1, int col); void fillGradient(int x0, int y0, int x1, int y1, int col1, int col2); + public: - GuiComponent(); // 4J added - void drawCenteredString(Font *font, const std::wstring& str, int x, int y, int color); - void drawString(Font *font, const std::wstring& str, int x, int y, int color); + GuiComponent(); // 4J added + void drawCenteredString(Font* font, const std::wstring& str, int x, int y, + int color); + void drawString(Font* font, const std::wstring& str, int x, int y, + int color); void blit(int x, int y, int sx, int sy, int w, int h); }; diff --git a/Minecraft.Client/UI/GuiMessage.cpp b/Minecraft.Client/UI/GuiMessage.cpp index 6f62556a5..961c9e04b 100644 --- a/Minecraft.Client/UI/GuiMessage.cpp +++ b/Minecraft.Client/UI/GuiMessage.cpp @@ -1,8 +1,7 @@ #include "../Platform/stdafx.h" #include "GuiMessage.h" -GuiMessage::GuiMessage(const std::wstring& string) -{ - this->string = string; - ticks = 0; +GuiMessage::GuiMessage(const std::wstring& string) { + this->string = string; + ticks = 0; } \ No newline at end of file diff --git a/Minecraft.Client/UI/GuiMessage.h b/Minecraft.Client/UI/GuiMessage.h index ad1403084..84596a860 100644 --- a/Minecraft.Client/UI/GuiMessage.h +++ b/Minecraft.Client/UI/GuiMessage.h @@ -1,10 +1,8 @@ #pragma once - -class GuiMessage -{ +class GuiMessage { public: - std::wstring string; - int ticks; - GuiMessage(const std::wstring& string); + std::wstring string; + int ticks; + GuiMessage(const std::wstring& string); }; \ No newline at end of file diff --git a/Minecraft.Client/UI/Rect2i.cpp b/Minecraft.Client/UI/Rect2i.cpp index 6681adf15..e7d8e0f52 100644 --- a/Minecraft.Client/UI/Rect2i.cpp +++ b/Minecraft.Client/UI/Rect2i.cpp @@ -1,76 +1,49 @@ #include "../Platform/stdafx.h" #include "Rect2i.h" -Rect2i::Rect2i(int x, int y, int width, int height) -{ - xPos = x; - yPos = y; - this->width = width; - this->height = height; +Rect2i::Rect2i(int x, int y, int width, int height) { + xPos = x; + yPos = y; + this->width = width; + this->height = height; } -Rect2i *Rect2i::intersect(const Rect2i *other) -{ - int x0 = xPos; - int y0 = yPos; - int x1 = xPos + width; - int y1 = yPos + height; +Rect2i* Rect2i::intersect(const Rect2i* other) { + int x0 = xPos; + int y0 = yPos; + int x1 = xPos + width; + int y1 = yPos + height; - int x2 = other->getX(); - int y2 = other->getY(); - int x3 = x2 + other->getWidth(); - int y3 = y2 + other->getHeight(); + int x2 = other->getX(); + int y2 = other->getY(); + int x3 = x2 + other->getWidth(); + int y3 = y2 + other->getHeight(); - xPos = std::max(x0, x2); - yPos = std::max(y0, y2); - width = std::max(0, std::min(x1, x3) - xPos); - height = std::max(0, std::min(y1, y3) - yPos); + xPos = std::max(x0, x2); + yPos = std::max(y0, y2); + width = std::max(0, std::min(x1, x3) - xPos); + height = std::max(0, std::min(y1, y3) - yPos); - return this; + return this; } -int Rect2i::getX() const -{ - return xPos; -} +int Rect2i::getX() const { return xPos; } -int Rect2i::getY() const -{ - return yPos; -} +int Rect2i::getY() const { return yPos; } -void Rect2i::setX(int x) -{ - xPos = x; -} +void Rect2i::setX(int x) { xPos = x; } -void Rect2i::setY(int y) -{ - yPos = y; -} +void Rect2i::setY(int y) { yPos = y; } -int Rect2i::getWidth() const -{ - return width; -} +int Rect2i::getWidth() const { return width; } -int Rect2i::getHeight() const -{ - return height; -} +int Rect2i::getHeight() const { return height; } -void Rect2i::setWidth(int width) -{ - this->width = width; -} +void Rect2i::setWidth(int width) { this->width = width; } -void Rect2i::setHeight(int height) -{ - this->height = height; -} +void Rect2i::setHeight(int height) { this->height = height; } -void Rect2i::setPosition(int x, int y) -{ - xPos = x; - yPos = y; +void Rect2i::setPosition(int x, int y) { + xPos = x; + yPos = y; } \ No newline at end of file diff --git a/Minecraft.Client/UI/Rect2i.h b/Minecraft.Client/UI/Rect2i.h index cb9471a02..9f52a726f 100644 --- a/Minecraft.Client/UI/Rect2i.h +++ b/Minecraft.Client/UI/Rect2i.h @@ -1,24 +1,23 @@ #pragma once -class Rect2i -{ +class Rect2i { private: - int xPos; - int yPos; - int width; - int height; + int xPos; + int yPos; + int width; + int height; public: - Rect2i(int x, int y, int width, int height); + Rect2i(int x, int y, int width, int height); - Rect2i *intersect(const Rect2i *other); - int getX() const; - int getY() const; - void setX(int x); - void setY(int y); - int getWidth() const; - int getHeight() const; - void setWidth(int width); - void setHeight(int height); - void setPosition(int x, int y); + Rect2i* intersect(const Rect2i* other); + int getX() const; + int getY() const; + void setX(int x); + void setY(int y); + int getWidth() const; + int getHeight() const; + void setWidth(int width); + void setHeight(int height); + void setPosition(int x, int y); }; \ No newline at end of file diff --git a/Minecraft.Client/UI/Screen.cpp b/Minecraft.Client/UI/Screen.cpp index 3fe91d598..719e6c24c 100644 --- a/Minecraft.Client/UI/Screen.cpp +++ b/Minecraft.Client/UI/Screen.cpp @@ -6,59 +6,47 @@ #include "../Textures/Textures.h" #include "../../Minecraft.World/Util/SoundTypes.h" - - -Screen::Screen() // 4J added +Screen::Screen() // 4J added { - minecraft = NULL; - width = 0; + minecraft = NULL; + width = 0; height = 0; - passEvents = false; - font = NULL; - particles = NULL; - clickedButton = NULL; + passEvents = false; + font = NULL; + particles = NULL; + clickedButton = NULL; } -void Screen::render(int xm, int ym, float a) -{ - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) - { - Button *button = *it; //buttons[i]; +void Screen::render(int xm, int ym, float a) { + AUTO_VAR(itEnd, buttons.end()); + for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) { + Button* button = *it; // buttons[i]; button->render(minecraft, xm, ym); } } -void Screen::keyPressed(wchar_t eventCharacter, int eventKey) -{ - if (eventKey == Keyboard::KEY_ESCAPE) - { - minecraft->setScreen(NULL); -// minecraft->grabMouse(); // 4J - removed - } +void Screen::keyPressed(wchar_t eventCharacter, int eventKey) { + if (eventKey == Keyboard::KEY_ESCAPE) { + minecraft->setScreen(NULL); + // minecraft->grabMouse(); // 4J - removed + } } -std::wstring Screen::getClipboard() -{ - // 4J - removed - return NULL; +std::wstring Screen::getClipboard() { + // 4J - removed + return NULL; } -void Screen::setClipboard(const std::wstring& str) -{ - // 4J - removed +void Screen::setClipboard(const std::wstring& str) { + // 4J - removed } -void Screen::mouseClicked(int x, int y, int buttonNum) -{ - if (buttonNum == 0) - { - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) - { - Button *button = *it; //buttons[i]; - if (button->clicked(minecraft, x, y)) - { +void Screen::mouseClicked(int x, int y, int buttonNum) { + if (buttonNum == 0) { + AUTO_VAR(itEnd, buttons.end()); + for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) { + Button* button = *it; // buttons[i]; + if (button->clicked(minecraft, x, y)) { clickedButton = button; minecraft->soundEngine->playUI(eSoundType_RANDOM_CLICK, 1, 1); buttonClicked(button); @@ -67,21 +55,16 @@ void Screen::mouseClicked(int x, int y, int buttonNum) } } -void Screen::mouseReleased(int x, int y, int buttonNum) -{ - if (clickedButton!=NULL && buttonNum==0) - { +void Screen::mouseReleased(int x, int y, int buttonNum) { + if (clickedButton != NULL && buttonNum == 0) { clickedButton->released(x, y); clickedButton = NULL; } } -void Screen::buttonClicked(Button *button) -{ -} +void Screen::buttonClicked(Button* button) {} -void Screen::init(Minecraft *minecraft, int width, int height) -{ +void Screen::init(Minecraft* minecraft, int width, int height) { particles = new GuiParticles(minecraft); this->minecraft = minecraft; this->font = minecraft->font; @@ -91,97 +74,71 @@ void Screen::init(Minecraft *minecraft, int width, int height) init(); } -void Screen::setSize(int width, int height) -{ +void Screen::setSize(int width, int height) { this->width = width; this->height = height; } -void Screen::init() -{ +void Screen::init() {} + +void Screen::updateEvents() { + /* 4J - TODO +while (Mouse.next()) { + mouseEvent(); } -void Screen::updateEvents() -{ - /* 4J - TODO - while (Mouse.next()) { - mouseEvent(); - } - - while (Keyboard.next()) { - keyboardEvent(); - } - */ - +while (Keyboard.next()) { + keyboardEvent(); +} + */ } -void Screen::mouseEvent() -{ - /* 4J - TODO - if (Mouse.getEventButtonState()) { - int xm = Mouse.getEventX() * width / minecraft.width; - int ym = height - Mouse.getEventY() * height / minecraft.height - 1; - mouseClicked(xm, ym, Mouse.getEventButton()); +void Screen::mouseEvent() { + /* 4J - TODO +if (Mouse.getEventButtonState()) { + int xm = Mouse.getEventX() * width / minecraft.width; + int ym = height - Mouse.getEventY() * height / minecraft.height - 1; + mouseClicked(xm, ym, Mouse.getEventButton()); +} else { + int xm = Mouse.getEventX() * width / minecraft.width; + int ym = height - Mouse.getEventY() * height / minecraft.height - 1; + mouseReleased(xm, ym, Mouse.getEventButton()); +} + */ +} + +void Screen::keyboardEvent() { + /* 4J - TODO +if (Keyboard.getEventKeyState()) { + if (Keyboard.getEventKey() == Keyboard.KEY_F11) { + minecraft.toggleFullScreen(); + return; + } + keyPressed(Keyboard.getEventCharacter(), Keyboard.getEventKey()); +} + */ +} + +void Screen::tick() {} + +void Screen::removed() {} + +void Screen::renderBackground() { renderBackground(0); } + +void Screen::renderBackground(int vo) { + if (minecraft->level != NULL) { + fillGradient(0, 0, width, height, 0xc0101010, 0xd0101010); } else { - int xm = Mouse.getEventX() * width / minecraft.width; - int ym = height - Mouse.getEventY() * height / minecraft.height - 1; - mouseReleased(xm, ym, Mouse.getEventButton()); + renderDirtBackground(vo); } - */ } -void Screen::keyboardEvent() -{ - /* 4J - TODO - if (Keyboard.getEventKeyState()) { - if (Keyboard.getEventKey() == Keyboard.KEY_F11) { - minecraft.toggleFullScreen(); - return; - } - keyPressed(Keyboard.getEventCharacter(), Keyboard.getEventKey()); - } - */ -} - -void Screen::tick() -{ -} - -void Screen::removed() -{ -} - -void Screen::renderBackground() -{ - renderBackground(0); -} - -void Screen::renderBackground(int vo) -{ - if (minecraft->level != NULL) - { - fillGradient(0, 0, width, height, 0xc0101010, 0xd0101010); - } - else - { - renderDirtBackground(vo); - } -} - -void Screen::renderDirtBackground(int vo) -{ +void Screen::renderDirtBackground(int vo) { // 4J Unused - Iggy Flash UI renders the background on consoles } -bool Screen::isPauseScreen() -{ - return true; -} +bool Screen::isPauseScreen() { return true; } -void Screen::confirmResult(bool result, int id) -{ -} +void Screen::confirmResult(bool result, int id) {} -void Screen::tabPressed() -{ -} +void Screen::tabPressed() {} diff --git a/Minecraft.Client/UI/Screen.h b/Minecraft.Client/UI/Screen.h index 169b49f33..9395e9de9 100644 --- a/Minecraft.Client/UI/Screen.h +++ b/Minecraft.Client/UI/Screen.h @@ -4,39 +4,46 @@ class Button; class GuiParticles; class Minecraft; - -class Screen : public GuiComponent -{ +class Screen : public GuiComponent { protected: - Minecraft *minecraft; + Minecraft* minecraft; + public: - int width; + int width; int height; -protected: - std::vector